hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
sequencelengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
sequencelengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
sequencelengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
fb0c822bd4723386ad46a1d03f4d974cacbae84b
10,884
cpp
C++
export/windows/obj/src/openfl/display/GraphicsStroke.cpp
seanbashaw/frozenlight
47c540d30d63e946ea2dc787b4bb602cc9347d21
[ "MIT" ]
null
null
null
export/windows/obj/src/openfl/display/GraphicsStroke.cpp
seanbashaw/frozenlight
47c540d30d63e946ea2dc787b4bb602cc9347d21
[ "MIT" ]
null
null
null
export/windows/obj/src/openfl/display/GraphicsStroke.cpp
seanbashaw/frozenlight
47c540d30d63e946ea2dc787b4bb602cc9347d21
[ "MIT" ]
null
null
null
// Generated by Haxe 3.4.7 #include <hxcpp.h> #ifndef INCLUDED_95f339a1d026d52c #define INCLUDED_95f339a1d026d52c #include "hxMath.h" #endif #ifndef INCLUDED_openfl_display_GraphicsDataType #include <openfl/display/GraphicsDataType.h> #endif #ifndef INCLUDED_openfl_display_GraphicsStroke #include <openfl/display/GraphicsStroke.h> #endif #ifndef INCLUDED_openfl_display_IGraphicsData #include <openfl/display/IGraphicsData.h> #endif #ifndef INCLUDED_openfl_display_IGraphicsFill #include <openfl/display/IGraphicsFill.h> #endif #ifndef INCLUDED_openfl_display_IGraphicsStroke #include <openfl/display/IGraphicsStroke.h> #endif HX_DEFINE_STACK_FRAME(_hx_pos_55614d7317440053_221_new,"openfl.display.GraphicsStroke","new",0x5684f03f,"openfl.display.GraphicsStroke.new","openfl/display/GraphicsStroke.hx",221,0x5e4870cf) namespace openfl{ namespace display{ void GraphicsStroke_obj::__construct( ::Dynamic thickness,hx::Null< bool > __o_pixelHinting, ::Dynamic __o_scaleMode, ::Dynamic __o_caps, ::Dynamic __o_joints,hx::Null< Float > __o_miterLimit,::Dynamic fill){ bool pixelHinting = __o_pixelHinting.Default(false); ::Dynamic scaleMode = __o_scaleMode.Default(2); ::Dynamic caps = __o_caps.Default(0); ::Dynamic joints = __o_joints.Default(2); Float miterLimit = __o_miterLimit.Default(3); HX_STACKFRAME(&_hx_pos_55614d7317440053_221_new) HXLINE( 223) if (hx::IsNull( thickness )) { HXLINE( 223) thickness = ::Math_obj::NaN; } HXLINE( 225) this->caps = caps; HXLINE( 226) this->fill = fill; HXLINE( 227) this->joints = joints; HXLINE( 228) this->miterLimit = miterLimit; HXLINE( 229) this->pixelHinting = pixelHinting; HXLINE( 230) this->scaleMode = scaleMode; HXLINE( 231) this->thickness = thickness; HXLINE( 232) this->_hx___graphicsDataType = ::openfl::display::GraphicsDataType_obj::STROKE_dyn(); } Dynamic GraphicsStroke_obj::__CreateEmpty() { return new GraphicsStroke_obj; } void *GraphicsStroke_obj::_hx_vtable = 0; Dynamic GraphicsStroke_obj::__Create(hx::DynamicArray inArgs) { hx::ObjectPtr< GraphicsStroke_obj > _hx_result = new GraphicsStroke_obj(); _hx_result->__construct(inArgs[0],inArgs[1],inArgs[2],inArgs[3],inArgs[4],inArgs[5],inArgs[6]); return _hx_result; } bool GraphicsStroke_obj::_hx_isInstanceOf(int inClassId) { return inClassId==(int)0x00000001 || inClassId==(int)0x7fc28725; } static ::openfl::display::IGraphicsStroke_obj _hx_openfl_display_GraphicsStroke__hx_openfl_display_IGraphicsStroke= { }; static ::openfl::display::IGraphicsData_obj _hx_openfl_display_GraphicsStroke__hx_openfl_display_IGraphicsData= { }; void *GraphicsStroke_obj::_hx_getInterface(int inHash) { switch(inHash) { case (int)0xf088881a: return &_hx_openfl_display_GraphicsStroke__hx_openfl_display_IGraphicsStroke; case (int)0xc177ee0c: return &_hx_openfl_display_GraphicsStroke__hx_openfl_display_IGraphicsData; } #ifdef HXCPP_SCRIPTABLE return super::_hx_getInterface(inHash); #else return 0; #endif } hx::ObjectPtr< GraphicsStroke_obj > GraphicsStroke_obj::__new( ::Dynamic thickness,hx::Null< bool > __o_pixelHinting, ::Dynamic __o_scaleMode, ::Dynamic __o_caps, ::Dynamic __o_joints,hx::Null< Float > __o_miterLimit,::Dynamic fill) { hx::ObjectPtr< GraphicsStroke_obj > __this = new GraphicsStroke_obj(); __this->__construct(thickness,__o_pixelHinting,__o_scaleMode,__o_caps,__o_joints,__o_miterLimit,fill); return __this; } hx::ObjectPtr< GraphicsStroke_obj > GraphicsStroke_obj::__alloc(hx::Ctx *_hx_ctx, ::Dynamic thickness,hx::Null< bool > __o_pixelHinting, ::Dynamic __o_scaleMode, ::Dynamic __o_caps, ::Dynamic __o_joints,hx::Null< Float > __o_miterLimit,::Dynamic fill) { GraphicsStroke_obj *__this = (GraphicsStroke_obj*)(hx::Ctx::alloc(_hx_ctx, sizeof(GraphicsStroke_obj), true, "openfl.display.GraphicsStroke")); *(void **)__this = GraphicsStroke_obj::_hx_vtable; __this->__construct(thickness,__o_pixelHinting,__o_scaleMode,__o_caps,__o_joints,__o_miterLimit,fill); return __this; } GraphicsStroke_obj::GraphicsStroke_obj() { } void GraphicsStroke_obj::__Mark(HX_MARK_PARAMS) { HX_MARK_BEGIN_CLASS(GraphicsStroke); HX_MARK_MEMBER_NAME(caps,"caps"); HX_MARK_MEMBER_NAME(fill,"fill"); HX_MARK_MEMBER_NAME(joints,"joints"); HX_MARK_MEMBER_NAME(miterLimit,"miterLimit"); HX_MARK_MEMBER_NAME(pixelHinting,"pixelHinting"); HX_MARK_MEMBER_NAME(scaleMode,"scaleMode"); HX_MARK_MEMBER_NAME(thickness,"thickness"); HX_MARK_MEMBER_NAME(_hx___graphicsDataType,"__graphicsDataType"); HX_MARK_END_CLASS(); } void GraphicsStroke_obj::__Visit(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(caps,"caps"); HX_VISIT_MEMBER_NAME(fill,"fill"); HX_VISIT_MEMBER_NAME(joints,"joints"); HX_VISIT_MEMBER_NAME(miterLimit,"miterLimit"); HX_VISIT_MEMBER_NAME(pixelHinting,"pixelHinting"); HX_VISIT_MEMBER_NAME(scaleMode,"scaleMode"); HX_VISIT_MEMBER_NAME(thickness,"thickness"); HX_VISIT_MEMBER_NAME(_hx___graphicsDataType,"__graphicsDataType"); } hx::Val GraphicsStroke_obj::__Field(const ::String &inName,hx::PropertyAccess inCallProp) { switch(inName.length) { case 4: if (HX_FIELD_EQ(inName,"caps") ) { return hx::Val( caps ); } if (HX_FIELD_EQ(inName,"fill") ) { return hx::Val( fill ); } break; case 6: if (HX_FIELD_EQ(inName,"joints") ) { return hx::Val( joints ); } break; case 9: if (HX_FIELD_EQ(inName,"scaleMode") ) { return hx::Val( scaleMode ); } if (HX_FIELD_EQ(inName,"thickness") ) { return hx::Val( thickness ); } break; case 10: if (HX_FIELD_EQ(inName,"miterLimit") ) { return hx::Val( miterLimit ); } break; case 12: if (HX_FIELD_EQ(inName,"pixelHinting") ) { return hx::Val( pixelHinting ); } break; case 18: if (HX_FIELD_EQ(inName,"__graphicsDataType") ) { return hx::Val( _hx___graphicsDataType ); } } return super::__Field(inName,inCallProp); } hx::Val GraphicsStroke_obj::__SetField(const ::String &inName,const hx::Val &inValue,hx::PropertyAccess inCallProp) { switch(inName.length) { case 4: if (HX_FIELD_EQ(inName,"caps") ) { caps=inValue.Cast< ::Dynamic >(); return inValue; } if (HX_FIELD_EQ(inName,"fill") ) { fill=inValue.Cast< ::Dynamic >(); return inValue; } break; case 6: if (HX_FIELD_EQ(inName,"joints") ) { joints=inValue.Cast< ::Dynamic >(); return inValue; } break; case 9: if (HX_FIELD_EQ(inName,"scaleMode") ) { scaleMode=inValue.Cast< ::Dynamic >(); return inValue; } if (HX_FIELD_EQ(inName,"thickness") ) { thickness=inValue.Cast< Float >(); return inValue; } break; case 10: if (HX_FIELD_EQ(inName,"miterLimit") ) { miterLimit=inValue.Cast< Float >(); return inValue; } break; case 12: if (HX_FIELD_EQ(inName,"pixelHinting") ) { pixelHinting=inValue.Cast< bool >(); return inValue; } break; case 18: if (HX_FIELD_EQ(inName,"__graphicsDataType") ) { _hx___graphicsDataType=inValue.Cast< ::openfl::display::GraphicsDataType >(); return inValue; } } return super::__SetField(inName,inValue,inCallProp); } void GraphicsStroke_obj::__GetFields(Array< ::String> &outFields) { outFields->push(HX_HCSTRING("caps","\x21","\x1c","\xba","\x41")); outFields->push(HX_HCSTRING("fill","\x83","\xce","\xbb","\x43")); outFields->push(HX_HCSTRING("joints","\xe9","\xe7","\x09","\x91")); outFields->push(HX_HCSTRING("miterLimit","\xf6","\x5c","\x6a","\x54")); outFields->push(HX_HCSTRING("pixelHinting","\xd5","\x9b","\xfb","\x6c")); outFields->push(HX_HCSTRING("scaleMode","\x0d","\xdb","\xd3","\x2b")); outFields->push(HX_HCSTRING("thickness","\x74","\xf1","\x66","\x5a")); outFields->push(HX_HCSTRING("__graphicsDataType","\x0f","\x5d","\x4d","\x46")); super::__GetFields(outFields); }; #if HXCPP_SCRIPTABLE static hx::StorageInfo GraphicsStroke_obj_sMemberStorageInfo[] = { {hx::fsObject /*Dynamic*/ ,(int)offsetof(GraphicsStroke_obj,caps),HX_HCSTRING("caps","\x21","\x1c","\xba","\x41")}, {hx::fsObject /*::openfl::display::IGraphicsFill*/ ,(int)offsetof(GraphicsStroke_obj,fill),HX_HCSTRING("fill","\x83","\xce","\xbb","\x43")}, {hx::fsObject /*Dynamic*/ ,(int)offsetof(GraphicsStroke_obj,joints),HX_HCSTRING("joints","\xe9","\xe7","\x09","\x91")}, {hx::fsFloat,(int)offsetof(GraphicsStroke_obj,miterLimit),HX_HCSTRING("miterLimit","\xf6","\x5c","\x6a","\x54")}, {hx::fsBool,(int)offsetof(GraphicsStroke_obj,pixelHinting),HX_HCSTRING("pixelHinting","\xd5","\x9b","\xfb","\x6c")}, {hx::fsObject /*Dynamic*/ ,(int)offsetof(GraphicsStroke_obj,scaleMode),HX_HCSTRING("scaleMode","\x0d","\xdb","\xd3","\x2b")}, {hx::fsFloat,(int)offsetof(GraphicsStroke_obj,thickness),HX_HCSTRING("thickness","\x74","\xf1","\x66","\x5a")}, {hx::fsObject /*::openfl::display::GraphicsDataType*/ ,(int)offsetof(GraphicsStroke_obj,_hx___graphicsDataType),HX_HCSTRING("__graphicsDataType","\x0f","\x5d","\x4d","\x46")}, { hx::fsUnknown, 0, null()} }; static hx::StaticInfo *GraphicsStroke_obj_sStaticStorageInfo = 0; #endif static ::String GraphicsStroke_obj_sMemberFields[] = { HX_HCSTRING("caps","\x21","\x1c","\xba","\x41"), HX_HCSTRING("fill","\x83","\xce","\xbb","\x43"), HX_HCSTRING("joints","\xe9","\xe7","\x09","\x91"), HX_HCSTRING("miterLimit","\xf6","\x5c","\x6a","\x54"), HX_HCSTRING("pixelHinting","\xd5","\x9b","\xfb","\x6c"), HX_HCSTRING("scaleMode","\x0d","\xdb","\xd3","\x2b"), HX_HCSTRING("thickness","\x74","\xf1","\x66","\x5a"), HX_HCSTRING("__graphicsDataType","\x0f","\x5d","\x4d","\x46"), ::String(null()) }; static void GraphicsStroke_obj_sMarkStatics(HX_MARK_PARAMS) { HX_MARK_MEMBER_NAME(GraphicsStroke_obj::__mClass,"__mClass"); }; #ifdef HXCPP_VISIT_ALLOCS static void GraphicsStroke_obj_sVisitStatics(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(GraphicsStroke_obj::__mClass,"__mClass"); }; #endif hx::Class GraphicsStroke_obj::__mClass; void GraphicsStroke_obj::__register() { hx::Object *dummy = new GraphicsStroke_obj; GraphicsStroke_obj::_hx_vtable = *(void **)dummy; hx::Static(__mClass) = new hx::Class_obj(); __mClass->mName = HX_HCSTRING("openfl.display.GraphicsStroke","\xcd","\x64","\xa2","\xa3"); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &hx::Class_obj::GetNoStaticField; __mClass->mSetStaticField = &hx::Class_obj::SetNoStaticField; __mClass->mMarkFunc = GraphicsStroke_obj_sMarkStatics; __mClass->mStatics = hx::Class_obj::dupFunctions(0 /* sStaticFields */); __mClass->mMembers = hx::Class_obj::dupFunctions(GraphicsStroke_obj_sMemberFields); __mClass->mCanCast = hx::TCanCast< GraphicsStroke_obj >; #ifdef HXCPP_VISIT_ALLOCS __mClass->mVisitFunc = GraphicsStroke_obj_sVisitStatics; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = GraphicsStroke_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = GraphicsStroke_obj_sStaticStorageInfo; #endif hx::_hx_RegisterClass(__mClass->mName, __mClass); } } // end namespace openfl } // end namespace display
42.186047
255
0.745774
seanbashaw
fb1232dae595059d8531347e9f6289b8481a1010
4,166
cpp
C++
src/mxml/parsing/AppearanceHandler.cpp
dkun7944/mxml
6450e7cab88eb6ee0ac469f437047072e1868ea4
[ "MIT" ]
18
2016-05-22T00:55:28.000Z
2021-03-29T08:44:23.000Z
src/mxml/parsing/AppearanceHandler.cpp
dkun7944/mxml
6450e7cab88eb6ee0ac469f437047072e1868ea4
[ "MIT" ]
6
2017-05-17T13:20:09.000Z
2018-10-22T20:00:57.000Z
src/mxml/parsing/AppearanceHandler.cpp
dkun7944/mxml
6450e7cab88eb6ee0ac469f437047072e1868ea4
[ "MIT" ]
14
2016-05-12T22:54:34.000Z
2021-10-19T12:43:16.000Z
// Copyright © 2016 Venture Media Labs. // // This file is part of mxml. The full mxml copyright notice, including // terms governing use, modification, and redistribution, is contained in the // file LICENSE at the root of the source code distribution tree. #include "AppearanceHandler.h" #include <lxml/DoubleHandler.h> #include <mxml/dom/InvalidDataError.h> #include <cstring> namespace mxml { static const char* kLineWidthTag = "line-width"; static const char* kNoteSizeTag = "note-size"; static const char* kDistanceTag = "distance"; void AppearanceHandler::startElement(const lxml::QName& qname, const AttributeMap& attributes) { _result = dom::Appearance{}; } lxml::RecursiveHandler* AppearanceHandler::startSubElement(const lxml::QName& qname) { if (strcmp(qname.localName(), kLineWidthTag) == 0) return &_handler; else if (strcmp(qname.localName(), kNoteSizeTag) == 0) return &_handler; else if (strcmp(qname.localName(), kDistanceTag) == 0) return &_handler; return 0; } void AppearanceHandler::endSubElement(const lxml::QName& qname, RecursiveHandler* parser) { if (strcmp(qname.localName(), kLineWidthTag) == 0) { auto lineWidthNode = _handler.result(); auto type = lineTypeFromString(lineWidthNode->attribute("type")); auto value = lxml::DoubleHandler::parseDouble(lineWidthNode->text()); _result.lineWidths[type] = static_cast<dom::tenths_t>(value); } else if (strcmp(qname.localName(), kNoteSizeTag) == 0) { auto sizeNode = _handler.result(); auto type = noteTypeFromString(sizeNode->attribute("type")); auto value = lxml::DoubleHandler::parseDouble(sizeNode->text()); _result.noteSizes[type] = static_cast<dom::tenths_t>(value); } else if (strcmp(qname.localName(), kDistanceTag) == 0) { auto distanceNode = _handler.result(); auto type = distanceTypeFromString(distanceNode->attribute("type")); auto value = lxml::DoubleHandler::parseDouble(distanceNode->text()); _result.distances[type] = static_cast<dom::tenths_t>(value); } } dom::LineType AppearanceHandler::lineTypeFromString(const std::string& string) { if (string == "beam") return dom::LineType::Beam; if (string == "bracket") return dom::LineType::Bracket; if (string == "dashes") return dom::LineType::Dashes; if (string == "enclosure") return dom::LineType::Enclosure; if (string == "ending") return dom::LineType::Ending; if (string == "extend") return dom::LineType::Extend; if (string == "heavy barline") return dom::LineType::HeavyBarline; if (string == "leger") return dom::LineType::Leger; if (string == "light barline") return dom::LineType::LightBarline; if (string == "octave shift") return dom::LineType::OctaveShift; if (string == "pedal") return dom::LineType::Pedal; if (string == "slur middle") return dom::LineType::SlurMiddle; if (string == "slur tip") return dom::LineType::SlurTip; if (string == "staff") return dom::LineType::Staff; if (string == "stem") return dom::LineType::Stem; if (string == "tie middle") return dom::LineType::TieMiddle; if (string == "tie tip") return dom::LineType::TieTip; if (string == "tuplet bracket") return dom::LineType::TupletBracket; if (string == "wedge") return dom::LineType::Wedge; throw dom::InvalidDataError("Invalid halign type " + string); } dom::NoteType AppearanceHandler::noteTypeFromString(const std::string& string) { if (string == "cue") return dom::NoteType::Cue; if (string == "grace") return dom::NoteType::Grace; if (string == "large") return dom::NoteType::Large; throw dom::InvalidDataError("Invalid halign type " + string); } dom::DistanceType AppearanceHandler::distanceTypeFromString(const std::string& string) { if (string == "beam") return dom::DistanceType::Beam; if (string == "hyphen") return dom::DistanceType::Hyphen; throw dom::InvalidDataError("Invalid halign type " + string); } } // namespace mxml
44.795699
96
0.665146
dkun7944
fb166ed48090ebcf1b71d7b9cc98bb6a4615758e
1,765
cpp
C++
VNTextProxy/AlternateProxies/xinput1_3/Proxy.cpp
xenei/VNTranslationTools
7d197b3d0b73fd279b1fb5680404ea03975c31af
[ "MIT" ]
41
2021-10-01T13:53:01.000Z
2022-03-22T22:30:58.000Z
VNTextProxy/AlternateProxies/xinput1_3/Proxy.cpp
xenei/VNTranslationTools
7d197b3d0b73fd279b1fb5680404ea03975c31af
[ "MIT" ]
28
2021-10-15T03:56:27.000Z
2022-03-28T08:04:35.000Z
VNTextProxy/AlternateProxies/xinput1_3/Proxy.cpp
xenei/VNTranslationTools
7d197b3d0b73fd279b1fb5680404ea03975c31af
[ "MIT" ]
9
2021-12-04T17:35:16.000Z
2022-03-19T17:14:42.000Z
#include "pch.h" void Proxy::Init() { wchar_t realDllPath[MAX_PATH]; GetSystemDirectory(realDllPath, MAX_PATH); wcscat_s(realDllPath, L"\\xinput1_3.dll"); HMODULE hDll = LoadLibrary(realDllPath); if (hDll == nullptr) { MessageBox(nullptr, L"Cannot load original xinput1_3.dll library", L"Proxy", MB_ICONERROR); ExitProcess(0); } #define RESOLVE(fn) Original##fn = GetProcAddress(hDll, #fn) RESOLVE(DllMain); RESOLVE(XInputEnable); RESOLVE(XInputGetBatteryInformation); RESOLVE(XInputGetCapabilities); RESOLVE(XInputGetDSoundAudioDeviceGuids); RESOLVE(XInputGetKeystroke); RESOLVE(XInputGetState); RESOLVE(XInputSetState); #undef RESOLVE } __declspec(naked) void FakeDllMain() { __asm { jmp [Proxy::OriginalDllMain] } } __declspec(naked) void FakeXInputEnable() { __asm { jmp [Proxy::OriginalXInputEnable] } } __declspec(naked) void FakeXInputGetBatteryInformation() { __asm { jmp [Proxy::OriginalXInputGetBatteryInformation] } } __declspec(naked) void FakeXInputGetCapabilities() { __asm { jmp [Proxy::OriginalXInputGetCapabilities] } } __declspec(naked) void FakeXInputGetDSoundAudioDeviceGuids() { __asm { jmp [Proxy::OriginalXInputGetDSoundAudioDeviceGuids] } } __declspec(naked) void FakeXInputGetKeystroke() { __asm { jmp [Proxy::OriginalXInputGetKeystroke] } } __declspec(naked) void FakeXInputGetState() { __asm { jmp [Proxy::OriginalXInputGetState] } } __declspec(naked) void FakeXInputSetState() { __asm { jmp [Proxy::OriginalXInputSetState] } }
51.911765
143
0.649858
xenei
fb16a001dc9906e5e013f5bca2efd32df7f3ba3d
9,245
cpp
C++
3dc/avp/bh_dummy.cpp
Melanikus/AvP
9d61eb974a23538e32bf2ef1b738643a018935a0
[ "BSD-3-Clause" ]
null
null
null
3dc/avp/bh_dummy.cpp
Melanikus/AvP
9d61eb974a23538e32bf2ef1b738643a018935a0
[ "BSD-3-Clause" ]
null
null
null
3dc/avp/bh_dummy.cpp
Melanikus/AvP
9d61eb974a23538e32bf2ef1b738643a018935a0
[ "BSD-3-Clause" ]
null
null
null
/* CDF 9/10/98 A bold new initiaitive! */ #include "3dc.h" #include "inline.h" #include "module.h" #include "io.h" #include "strategy_def.h" #include "gamedef.h" #include "bh_types.h" #include "dynblock.h" #include "dynamics.h" #include "weapons.h" #include "compiled_shapes.h" #include "inventory.h" #include "triggers.h" #include "mslhand.h" #define UseLocalAssert TRUE #include "ourasert.h" #include "pmove.h" #include "pvisible.h" #include "bh_switch_door.h" #include "bh_platform_lift.h" #include "load_shape.h" #include "bh_weapon.h" #include "bh_debris.h" #include "lighting.h" #include "bh_link_switch.h" #include "bh_binary_switch.h" #include "pheromone.h" #include "bh_predator.h" #include "bh_agun.h" #include "plat_shp.h" #include "psnd.h" #include "ai_sight.h" #include "sequences.h" #include "huddefs.h" #include "showcmds.h" #include "sfx.h" #include "bh_marine.h" #include "bh_dummy.h" #include "bh_far.h" #include "targeting.h" #include "dxlog.h" #include "los.h" #include "psndplat.h" #include "extents.h" #include "pldghost.h" #include "pldnet.h" extern unsigned char Null_Name[8]; extern ACTIVESOUNDSAMPLE ActiveSounds[]; extern SECTION * GetNamedHierarchyFromLibrary(const char * rif_name, const char * hier_name); void CreateDummy(VECTORCH *Position); /* Begin code! */ void CastDummy(void) { #define BOTRANGE 2000 VECTORCH position; if (AvP.Network!=I_No_Network) { NewOnScreenMessage("NO DUMMYS IN MULTIPLAYER MODE"); return; } position=Player->ObStrategyBlock->DynPtr->Position; position.vx+=MUL_FIXED(Player->ObStrategyBlock->DynPtr->OrientMat.mat31,BOTRANGE); position.vy+=MUL_FIXED(Player->ObStrategyBlock->DynPtr->OrientMat.mat32,BOTRANGE); position.vz+=MUL_FIXED(Player->ObStrategyBlock->DynPtr->OrientMat.mat33,BOTRANGE); CreateDummy(&position); } void CreateDummy(VECTORCH *Position) { STRATEGYBLOCK* sbPtr; /* create and initialise a strategy block */ sbPtr = CreateActiveStrategyBlock(); if(!sbPtr) { NewOnScreenMessage("FAILED TO CREATE DUMMY: SB CREATION FAILURE"); return; /* failure */ } InitialiseSBValues(sbPtr); sbPtr->I_SBtype = I_BehaviourDummy; AssignNewSBName(sbPtr); /* create, initialise and attach a dynamics block */ sbPtr->DynPtr = AllocateDynamicsBlock(DYNAMICS_TEMPLATE_MARINE_PLAYER); if(sbPtr->DynPtr) { EULER zeroEuler = {0,0,0}; DYNAMICSBLOCK *dynPtr = sbPtr->DynPtr; GLOBALASSERT(dynPtr); dynPtr->PrevPosition = dynPtr->Position = *Position; dynPtr->OrientEuler = zeroEuler; CreateEulerMatrix(&dynPtr->OrientEuler, &dynPtr->OrientMat); TransposeMatrixCH(&dynPtr->OrientMat); } else { /* dynamics block allocation failed... */ RemoveBehaviourStrategy(sbPtr); NewOnScreenMessage("FAILED TO CREATE DUMMY: DYNBLOCK CREATION FAILURE"); return; } sbPtr->shapeIndex = 0; sbPtr->maintainVisibility = 1; sbPtr->containingModule = ModuleFromPosition(&(sbPtr->DynPtr->Position), (MODULE*)0); /* Initialise dummy's stats */ { sbPtr->SBDamageBlock.Health=30000<<ONE_FIXED_SHIFT; sbPtr->SBDamageBlock.Armour=30000<<ONE_FIXED_SHIFT; sbPtr->SBDamageBlock.SB_H_flags.AcidResistant=1; sbPtr->SBDamageBlock.SB_H_flags.FireResistant=1; sbPtr->SBDamageBlock.SB_H_flags.ElectricResistant=1; sbPtr->SBDamageBlock.SB_H_flags.PerfectArmour=1; sbPtr->SBDamageBlock.SB_H_flags.ElectricSensitive=0; sbPtr->SBDamageBlock.SB_H_flags.Combustability=0; sbPtr->SBDamageBlock.SB_H_flags.Indestructable=1; } /* create, initialise and attach a dummy data block */ sbPtr->SBdataptr = (void *)AllocateMem(sizeof(DUMMY_STATUS_BLOCK)); if(sbPtr->SBdataptr) { SECTION *root_section; DUMMY_STATUS_BLOCK *dummyStatus = (DUMMY_STATUS_BLOCK *)sbPtr->SBdataptr; GLOBALASSERT(dummyStatus); dummyStatus->incidentFlag=0; dummyStatus->incidentTimer=0; dummyStatus->HModelController.section_data=NULL; dummyStatus->HModelController.Deltas=NULL; switch (AvP.PlayerType) { case I_Marine: dummyStatus->PlayerType=I_Marine; root_section=GetNamedHierarchyFromLibrary("hnpcmarine","marine with pulse rifle"); if (!root_section) { RemoveBehaviourStrategy(sbPtr); NewOnScreenMessage("FAILED TO CREATE DUMMY: NO HMODEL"); return; } Create_HModel(&dummyStatus->HModelController,root_section); InitHModelSequence(&dummyStatus->HModelController,(int)HMSQT_MarineStand,(int)MSSS_Fidget_A,-1); break; case I_Alien: dummyStatus->PlayerType=I_Alien; root_section=GetNamedHierarchyFromLibrary("hnpcalien","alien"); if (!root_section) { RemoveBehaviourStrategy(sbPtr); NewOnScreenMessage("FAILED TO CREATE DUMMY: NO HMODEL"); return; } Create_HModel(&dummyStatus->HModelController,root_section); InitHModelSequence(&dummyStatus->HModelController,(int)HMSQT_AlienStand,(int)ASSS_Standard,-1); break; case I_Predator: dummyStatus->PlayerType=I_Predator; root_section=GetNamedHierarchyFromLibrary("hnpcpredator","pred with wristblade"); if (!root_section) { RemoveBehaviourStrategy(sbPtr); NewOnScreenMessage("FAILED TO CREATE DUMMY: NO HMODEL"); return; } Create_HModel(&dummyStatus->HModelController,root_section); InitHModelSequence(&dummyStatus->HModelController,(int)HMSQT_PredatorStand,(int)PSSS_Standard,-1); break; } ProveHModel_Far(&dummyStatus->HModelController,sbPtr); if(!(sbPtr->containingModule)) { /* no containing module can be found... abort*/ RemoveBehaviourStrategy(sbPtr); NewOnScreenMessage("FAILED TO CREATE DUMMY: MODULE CONTAINMENT FAILURE"); return; } LOCALASSERT(sbPtr->containingModule); MakeDummyNear(sbPtr); NewOnScreenMessage("DUMMY CREATED"); } else { /* no data block can be allocated */ RemoveBehaviourStrategy(sbPtr); NewOnScreenMessage("FAILED TO CREATE DUMMY: MALLOC FAILURE"); return; } } void MakeDummyNear(STRATEGYBLOCK *sbPtr) { extern MODULEMAPBLOCK AlienDefaultMap; MODULE tempModule; DISPLAYBLOCK *dPtr; DYNAMICSBLOCK *dynPtr; DUMMY_STATUS_BLOCK *dummyStatusPointer; LOCALASSERT(sbPtr); LOCALASSERT(sbPtr->SBdptr == NULL); dynPtr = sbPtr->DynPtr; dummyStatusPointer = (DUMMY_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(dummyStatusPointer); LOCALASSERT(dynPtr); AlienDefaultMap.MapShape = sbPtr->shapeIndex; tempModule.m_mapptr = &AlienDefaultMap; tempModule.m_sbptr = (STRATEGYBLOCK*)NULL; tempModule.m_numlights = 0; tempModule.m_lightarray = (struct lightblock *)0; tempModule.m_extraitemdata = (struct extraitemdata *)0; tempModule.m_dptr = NULL; AllocateModuleObject(&tempModule); dPtr = tempModule.m_dptr; if(dPtr==NULL) return; /* cannot allocate displayblock, so leave far */ sbPtr->SBdptr = dPtr; dPtr->ObStrategyBlock = sbPtr; dPtr->ObMyModule = NULL; /* need to initialise positional information in the new display block */ dPtr->ObWorld = dynPtr->Position; dPtr->ObEuler = dynPtr->OrientEuler; dPtr->ObMat = dynPtr->OrientMat; /* zero linear velocity in dynamics block */ sbPtr->DynPtr->LinVelocity.vx = 0; sbPtr->DynPtr->LinVelocity.vy = 0; sbPtr->DynPtr->LinVelocity.vz = 0; /* state and sequence initialisation */ dPtr->HModelControlBlock=&dummyStatusPointer->HModelController; ProveHModel(dPtr->HModelControlBlock,dPtr); /*Copy extents from the collision extents in extents.c*/ dPtr->ObMinX=-CollisionExtents[CE_MARINE].CollisionRadius; dPtr->ObMaxX=CollisionExtents[CE_MARINE].CollisionRadius; dPtr->ObMinZ=-CollisionExtents[CE_MARINE].CollisionRadius; dPtr->ObMaxZ=CollisionExtents[CE_MARINE].CollisionRadius; dPtr->ObMinY=CollisionExtents[CE_MARINE].CrouchingTop; dPtr->ObMaxY=CollisionExtents[CE_MARINE].Bottom; dPtr->ObRadius = 1000; } void MakeDummyFar(STRATEGYBLOCK *sbPtr) { DUMMY_STATUS_BLOCK *dummyStatusPointer; int i; LOCALASSERT(sbPtr); LOCALASSERT(sbPtr->SBdptr != NULL); dummyStatusPointer = (DUMMY_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(dummyStatusPointer); /* get rid of the displayblock */ i = DestroyActiveObject(sbPtr->SBdptr); LOCALASSERT(i==0); sbPtr->SBdptr = NULL; /* zero linear velocity in dynamics block */ sbPtr->DynPtr->LinVelocity.vx = 0; sbPtr->DynPtr->LinVelocity.vy = 0; sbPtr->DynPtr->LinVelocity.vz = 0; } void DummyBehaviour(STRATEGYBLOCK *sbPtr) { DUMMY_STATUS_BLOCK *dummyStatusPointer; LOCALASSERT(sbPtr); LOCALASSERT(sbPtr->containingModule); dummyStatusPointer = (DUMMY_STATUS_BLOCK *)(sbPtr->SBdataptr); LOCALASSERT(dummyStatusPointer); /* Should be the same near as far. */ /* test if we've got a containing module: if we haven't, do nothing. This is important as the object could have been marked for deletion by the visibility management system...*/ if(!sbPtr->containingModule) { DestroyAnyStrategyBlock(sbPtr); /* just to make sure */ return; } else if (dummyStatusPointer->PlayerType!=I_Alien) { AddMarinePheromones(sbPtr->containingModule->m_aimodule); } /* Incident handling. */ dummyStatusPointer->incidentFlag=0; dummyStatusPointer->incidentTimer-=NormalFrameTime; if (dummyStatusPointer->incidentTimer<0) { dummyStatusPointer->incidentFlag=1; dummyStatusPointer->incidentTimer=32767+(FastRandom()&65535); } }
29.349206
102
0.743429
Melanikus
fb17e58356bb333e7cedf7bbe6d02f3b46ff139b
2,517
cpp
C++
Algorithms/graphs/TwoColor/TwoColor/main.cpp
mingyuefly/geekTimeCode
d97c5f29a429ac9cc7289ac34e049ea43fa58822
[ "MIT" ]
1
2019-05-01T04:51:14.000Z
2019-05-01T04:51:14.000Z
Algorithms/graphs/TwoColor/TwoColor/main.cpp
mingyuefly/geekTimeCode
d97c5f29a429ac9cc7289ac34e049ea43fa58822
[ "MIT" ]
null
null
null
Algorithms/graphs/TwoColor/TwoColor/main.cpp
mingyuefly/geekTimeCode
d97c5f29a429ac9cc7289ac34e049ea43fa58822
[ "MIT" ]
null
null
null
// // main.cpp // TwoColor // // Created by mingyue on 2022/3/6. // Copyright © 2022 Gmingyue. All rights reserved. // #include <iostream> #include <vector> using namespace std; class Graph { public: vector<vector<int> *> * adj; Graph() { } Graph(int V) { this->V = V; this->E = 0; adj = new vector<vector<int> *>(this->V); for (int i = 0; i < V; i++) { adj->at(i) = new vector<int>(); } } ~Graph() { cout << "~Graph()" << endl; for (int i = 0; i < V; i++) { delete adj->at(i); } delete adj; } int getV() { return V; } int getE() { return E; } void addEdge(int v, int w) { adj->at(v)->push_back(w); adj->at(w)->push_back(v); E++; } void show() { for (int i = 0; i < adj->size(); i++) { cout << i << ":"; for (int j = 0; j < adj->at(i)->size(); j++) { cout << adj->at(i)->at(j) << " "; } cout << endl; } } private: int V; int E; }; class TwoColor { public: TwoColor() { } TwoColor(Graph * g) { marked = new vector<bool>(g->getV(), false); color = new vector<bool>(g->getV(), false); for (int s = 0; s < g->getV(); s++) { if (marked->at(s) == false) { dfs(g, s); } } } ~TwoColor() { cout << "~TwoColor()" << endl; delete marked; delete color; } bool getIsTwoColorable() { return isTwoColorable; } private: vector<bool> * marked; vector<bool> * color; bool isTwoColorable = true; void dfs(Graph * g, int v) { marked->at(v) = true; for (int w = 0; w < g->adj->at(v)->size(); w++) { if (marked->at(g->adj->at(v)->at(w)) == false) { color->at(g->adj->at(v)->at(w)) = !color->at(v); dfs(g, g->adj->at(v)->at(w)); } else if (color->at(g->adj->at(v)->at(w)) == color->at(v)) { isTwoColorable = false; } } } }; int main(int argc, const char * argv[]) { Graph * g = new Graph(4); g->addEdge(0, 1); g->addEdge(1, 2); g->addEdge(2, 3); g->addEdge(3, 0); // g->addEdge(1, 3); g->show(); TwoColor twoColor = TwoColor(g); cout << twoColor.getIsTwoColorable() << endl; delete g; return 0; }
21.512821
73
0.424712
mingyuefly
fb183a4b905d4aae0fb85a0f3a6d0268f39b6326
597
cpp
C++
src/platforms/android/androidadjusthelper.cpp
swatson555/mozilla-vpn-client
feb23f893968bd032686fc16bbab71e02b006289
[ "MIT" ]
null
null
null
src/platforms/android/androidadjusthelper.cpp
swatson555/mozilla-vpn-client
feb23f893968bd032686fc16bbab71e02b006289
[ "MIT" ]
null
null
null
src/platforms/android/androidadjusthelper.cpp
swatson555/mozilla-vpn-client
feb23f893968bd032686fc16bbab71e02b006289
[ "MIT" ]
null
null
null
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "androidadjusthelper.h" #include <QAndroidJniObject> #include <QString> void AndroidAdjustHelper::trackEvent(const QString& event) { QAndroidJniObject javaMessage = QAndroidJniObject::fromString(event); QAndroidJniObject::callStaticMethod<void>( "org/mozilla/firefox/vpn/qt/VPNAdjustHelper", "trackEvent", "(Ljava/lang/String;)V", javaMessage.object<jstring>()); }
39.8
71
0.743719
swatson555
fb1a14fc904379b1fedd08288d1128d830a1dc14
2,469
cpp
C++
Engine/BuildSystem/Configuration/BuildConfiguration.cpp
GabyForceQ/PolluxEngine
2dbc84ed1d434f1b6d794f775f315758f0e8cc49
[ "BSD-3-Clause" ]
3
2020-05-19T20:24:28.000Z
2020-09-27T11:28:42.000Z
Engine/BuildSystem/Configuration/BuildConfiguration.cpp
GabyForceQ/PolluxEngine
2dbc84ed1d434f1b6d794f775f315758f0e8cc49
[ "BSD-3-Clause" ]
31
2020-05-27T11:01:27.000Z
2020-08-08T15:53:23.000Z
Engine/BuildSystem/Configuration/BuildConfiguration.cpp
GabyForceQ/PolluxEngine
2dbc84ed1d434f1b6d794f775f315758f0e8cc49
[ "BSD-3-Clause" ]
null
null
null
/***************************************************************************************************************************** * Copyright 2020 Gabriel Gheorghe. All rights reserved. * This code is licensed under the BSD 3-Clause "New" or "Revised" License * License url: https://github.com/GabyForceQ/PolluxEngine/blob/master/LICENSE *****************************************************************************************************************************/ #include "Engine/enginepch.hpp" #include "BuildConfiguration.hpp" namespace Pollux::BuildSystem { BuildConfiguration::BuildConfiguration(BuildOptimization optimization) noexcept : optimization{ optimization } { } BuildConfiguration& BuildConfiguration::operator=(const BuildConfiguration& rhs) { projectName = rhs.projectName; projectPath = rhs.projectPath; buildOutputType = rhs.buildOutputType; preprocessorDefinitions = rhs.preprocessorDefinitions; includeDirectories = rhs.includeDirectories; bUsePrecompiledHeaders = rhs.bUsePrecompiledHeaders; precompiledHeaderName = rhs.precompiledHeaderName; bUseDebugLibraries = rhs.bUseDebugLibraries; wholeProgramOptimization = rhs.wholeProgramOptimization; bLinkIncremental = rhs.bLinkIncremental; functionLevelLinking = rhs.functionLevelLinking; bIntrinsicFunctions = rhs.bIntrinsicFunctions; bBufferSecurityCheck = rhs.bBufferSecurityCheck; bStringPooling = rhs.bStringPooling; bGenerateDebugInformation = rhs.bGenerateDebugInformation; bOptimizeReferences = rhs.bOptimizeReferences; bEnableCOMDATFolding = rhs.bEnableCOMDATFolding; return *this; } void BuildConfiguration::Reset() { projectName = ""; projectPath = ""; buildOutputType = BuildOutputType::None; preprocessorDefinitions.clear(); includeDirectories.clear(); bUsePrecompiledHeaders = false; precompiledHeaderName = ""; bUseDebugLibraries = false; wholeProgramOptimization = BuildBooleanType::None; bLinkIncremental = false; functionLevelLinking = BuildBooleanType::None; bIntrinsicFunctions = false; bBufferSecurityCheck = false; bStringPooling = false; bGenerateDebugInformation = false; bOptimizeReferences = false; bEnableCOMDATFolding = false; } }
37.984615
127
0.63143
GabyForceQ
fb296164604e03b8de299a508c7ae07883a02eb2
5,743
cpp
C++
ros/src/convert.cpp
norlab-ulaval/navtechradar
4d3ccd2558e79142d656a6c12cd826d9397b0f2d
[ "MIT" ]
2
2020-11-18T17:48:40.000Z
2021-01-12T14:15:17.000Z
ros/src/convert.cpp
norlab-ulaval/navtechradar
4d3ccd2558e79142d656a6c12cd826d9397b0f2d
[ "MIT" ]
null
null
null
ros/src/convert.cpp
norlab-ulaval/navtechradar
4d3ccd2558e79142d656a6c12cd826d9397b0f2d
[ "MIT" ]
1
2022-03-22T16:09:51.000Z
2022-03-22T16:09:51.000Z
#include <ros/ros.h> #include <omp.h> #include <cv_bridge/cv_bridge.h> #include <sensor_msgs/Image.h> #include <opencv2/core.hpp> #include <opencv2/highgui/highgui.hpp> ros::Publisher pub; ros::Subscriber sub; double radar_upgrade_time = 1632182400; void load_radar(cv::Mat raw_data, std::vector<int64_t> &timestamps, std::vector<float> &azimuths, std::vector<bool> &valid, cv::Mat &fft_data) { int encoder_size = 5600; int N = raw_data.rows; timestamps = std::vector<int64_t>(N, 0); azimuths = std::vector<float>(N, 0); valid = std::vector<bool>(N, true); int range_bins = raw_data.cols - 11; fft_data = cv::Mat::zeros(N, range_bins, CV_32F); #pragma omp parallel for (int i = 0; i < N; ++i) { uchar* byteArray = raw_data.ptr<uchar>(i); timestamps[i] = *((int64_t *)(byteArray)); azimuths[i] = *((uint16_t *)(byteArray + 8)) * 2 * M_PI / float(encoder_size); // std::cout << azimuths[i] << std::endl; valid[i] = byteArray[10] == 255; for (int j = 0; j < range_bins; j++) { fft_data.at<float>(i, j) = (float)*(byteArray + 11 + j) / 255.0; } } // std::cout << timestamps[0] << " " << timestamps[1] << std::endl; } float get_azimuth_index(std::vector<float> &azimuths, float azimuth) { float mind = 1000; float closest = 0; for (uint i = 0; i < azimuths.size(); ++i) { float d = fabs(azimuths[i] - azimuth); if (d < mind) { mind = d; closest = i; } } if (azimuths[closest] < azimuth) { float delta = (azimuth - azimuths[closest]) / (azimuths[closest + 1] - azimuths[closest]); closest += delta; } else if (azimuths[closest] > azimuth){ float delta = (azimuths[closest] - azimuth) / (azimuths[closest] - azimuths[closest - 1]); closest -= delta; } return closest; } void radar_polar_to_cartesian(std::vector<float> &azimuths, cv::Mat &fft_data, float radar_resolution, float cart_resolution, int cart_pixel_width, bool interpolate_crossover, cv::Mat &cart_img) { float cart_min_range = (cart_pixel_width / 2) * cart_resolution; if (cart_pixel_width % 2 == 0) cart_min_range = (cart_pixel_width / 2 - 0.5) * cart_resolution; cv::Mat map_x = cv::Mat::zeros(cart_pixel_width, cart_pixel_width, CV_32F); cv::Mat map_y = cv::Mat::zeros(cart_pixel_width, cart_pixel_width, CV_32F); #pragma omp parallel for collapse(2) for (int j = 0; j < map_y.cols; ++j) { for (int i = 0; i < map_y.rows; ++i) { map_y.at<float>(i, j) = -1 * cart_min_range + j * cart_resolution; } } #pragma omp parallel for collapse(2) for (int i = 0; i < map_x.rows; ++i) { for (int j = 0; j < map_x.cols; ++j) { map_x.at<float>(i, j) = cart_min_range - i * cart_resolution; } } cv::Mat range = cv::Mat::zeros(cart_pixel_width, cart_pixel_width, CV_32F); cv::Mat angle = cv::Mat::zeros(cart_pixel_width, cart_pixel_width, CV_32F); float azimuth_step = azimuths[1] - azimuths[0]; // float azimuth_step = (M_PI / 200); // azimuths[0] = 0; #pragma omp parallel for collapse(2) for (int i = 0; i < range.rows; ++i) { for (int j = 0; j < range.cols; ++j) { float x = map_x.at<float>(i, j); float y = map_y.at<float>(i, j); float r = (sqrt(pow(x, 2) + pow(y, 2)) - radar_resolution / 2) / radar_resolution; if (r < 0) r = 0; range.at<float>(i, j) = r; float theta = atan2f(y, x); if (theta < 0) theta += 2 * M_PI; // angle.at<float>(i, j) = get_azimuth_index(azimuths, theta); angle.at<float>(i, j) = (theta - azimuths[0]) / azimuth_step; } } if (interpolate_crossover) { cv::Mat a0 = cv::Mat::zeros(1, fft_data.cols, CV_32F); cv::Mat aN_1 = cv::Mat::zeros(1, fft_data.cols, CV_32F); for (int j = 0; j < fft_data.cols; ++j) { a0.at<float>(0, j) = fft_data.at<float>(0, j); aN_1.at<float>(0, j) = fft_data.at<float>(fft_data.rows-1, j); } cv::vconcat(aN_1, fft_data, fft_data); cv::vconcat(fft_data, a0, fft_data); angle = angle + 1; } cv::remap(fft_data, cart_img, range, angle, cv::INTER_LINEAR, cv::BORDER_CONSTANT, cv::Scalar(0, 0, 0)); } void callback(const sensor_msgs::ImageConstPtr & msg) { cv_bridge::CvImagePtr cv_ptr = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::MONO8); cv::Mat raw_data = cv_ptr->image; // Extract fft_data and relevant meta data std::vector<int64_t> timestamps; std::vector<float> azimuths; std::vector<bool> valid; cv::Mat polar_img; load_radar(raw_data, timestamps, azimuths, valid, polar_img); cv::Mat cart_img; float cart_resolution = 0.25; int cart_pixel_width = 1000; bool interpolate_crossover = true; float radar_resolution = 0.0596; double t = msg->header.stamp.toSec();; if (t > radar_upgrade_time) { radar_resolution = 0.04381; } radar_polar_to_cartesian(azimuths, polar_img, radar_resolution, cart_resolution, cart_pixel_width, interpolate_crossover, cart_img); // Convert to cartesian cv::Mat vis; cart_img.convertTo(vis, CV_8U, 255.0); cv_bridge::CvImage out_msg; out_msg.encoding = "mono8"; out_msg.image = vis; pub.publish(out_msg.toImageMsg()); } int main(int32_t argc, char** argv) { ros::init(argc, argv, "convert"); ros::NodeHandle nh; std::cout << omp_get_num_threads() << std::endl; pub = nh.advertise<sensor_msgs::Image>("/Navtech/Cartesian", 4); sub = nh.subscribe("/talker1/Navtech/Polar", 10, &callback); ros::spin(); return 0; }
37.535948
108
0.608045
norlab-ulaval
fb2f7b6e5e5b37fa23bdc5935bd721bfb325d3e9
239
hpp
C++
include/Pomdog/Graphics/Shader.hpp
ValtoForks/pomdog
73798ae5f4a4c3b9b1e1e96239187c4b842c93b2
[ "MIT" ]
null
null
null
include/Pomdog/Graphics/Shader.hpp
ValtoForks/pomdog
73798ae5f4a4c3b9b1e1e96239187c4b842c93b2
[ "MIT" ]
null
null
null
include/Pomdog/Graphics/Shader.hpp
ValtoForks/pomdog
73798ae5f4a4c3b9b1e1e96239187c4b842c93b2
[ "MIT" ]
null
null
null
// Copyright (c) 2013-2018 mogemimi. Distributed under the MIT license. #pragma once #include "Pomdog/Basic/Export.hpp" namespace Pomdog { class POMDOG_EXPORT Shader { public: virtual ~Shader() = default; }; } // namespace Pomdog
15.933333
71
0.719665
ValtoForks
fb2fe2d8dc1a20e134b62b4b28f2096cef0e7054
2,212
cpp
C++
examples/tcp_server/client.cpp
jharmer95/rpc.hpp
8cba8ff7b63b28546d58bcf828ab93a9df03744e
[ "BSD-3-Clause" ]
1
2019-11-15T21:05:18.000Z
2019-11-15T21:05:18.000Z
examples/tcp_server/client.cpp
jharmer95/rpc.hpp
8cba8ff7b63b28546d58bcf828ab93a9df03744e
[ "BSD-3-Clause" ]
47
2019-11-15T20:58:44.000Z
2022-03-30T13:19:24.000Z
examples/tcp_server/client.cpp
jharmer95/rpc.hpp
8cba8ff7b63b28546d58bcf828ab93a9df03744e
[ "BSD-3-Clause" ]
null
null
null
#define RPC_HPP_CLIENT_IMPL #include "client.hpp" #include <iostream> #include <stdexcept> #include <string> int main(int argc, char* argv[]) { if (argc < 3) { std::cerr << "USAGE: rpc_client <server_ipv4> <port_num>\n"; return EXIT_FAILURE; } RpcClient client{ argv[1], argv[2] }; std::string currentFuncName; try { // Trivial function example { currentFuncName = "Sum"; const auto result = client.template call_func<int>("Sum", 1, 2); std::cout << "Sum(1, 2) == " << result << '\n'; } // Example of calling w/ references { currentFuncName = "AddOneToEach"; std::vector<int> vec{ 1, 2, 3, 4, 5 }; client.template call_func<void>("AddOneToEach", vec); std::cout << "AddOneToEach({ 1, 2, 3, 4, 5 }) == {"; for (size_t i = 0; i < vec.size() - 1; ++i) { std::cout << ' ' << vec[i] << ", "; } std::cout << ' ' << vec.back() << " }\n"; } // Template function example { currentFuncName = "GetTypeName<int>"; auto result = client.template call_func<std::string>("GetTypeName<int>"); std::cout << "GetTypeName<int>() == \"" << result << "\"\n"; currentFuncName = "GetTypeName<double>"; result = client.template call_func<std::string>("GetTypeName<double>"); std::cout << "GetTypeName<double>() == \"" << result << "\"\n"; currentFuncName = "GetTypeName<std::string>"; result = client.template call_func<std::string>("GetTypeName<std::string>"); std::cout << "GetTypeName<std::string>() == \"" << result << "\"\n"; } // Now shutdown the server { currentFuncName = "KillServer"; client.call_func("KillServer"); std::cout << "Server shutdown remotely...\n"; } return EXIT_SUCCESS; } catch (const std::exception& ex) { std::cerr << "Call to '" << currentFuncName << "' failed, reason: " << ex.what() << '\n'; return EXIT_FAILURE; } }
28
97
0.5
jharmer95
fb364774eda945e18763b58742a6b965aa847895
1,196
cpp
C++
stl/pqueue_fns.cpp
Praneeth-rdy/cp-practice
26ef8beae3708a0867ed332d308743b990f0a68c
[ "MIT" ]
null
null
null
stl/pqueue_fns.cpp
Praneeth-rdy/cp-practice
26ef8beae3708a0867ed332d308743b990f0a68c
[ "MIT" ]
null
null
null
stl/pqueue_fns.cpp
Praneeth-rdy/cp-practice
26ef8beae3708a0867ed332d308743b990f0a68c
[ "MIT" ]
null
null
null
#include <iostream> #include <queue> using namespace std; int main(){ // declaring max pqueue priority_queue<int> maxpq; // declaring min pqueue // any container which supports the following opreations can be used to implement priority_queue // empty(), push_back(), size(), pop_back(), front() // replace the container you want in place of vector priority_queue<int, vector<int>, greater<int>> minpq; // operations on max pq // inserting a new element into priority queue maxpq.push(10); maxpq.push(20); maxpq.push(30); // getting top element cout << "maxpq top element: " << maxpq.top() << "\n"; // removing top element which is the highest value element maxpq.pop(); // operations on minpq minpq.push(30); minpq.push(100); minpq.push(25); minpq.push(40); // getting the top element cout << "minpq top element: " << minpq.top() << "\n"; return 0; } /* maxpqueue is a container adaptor heap property is always maintained first element is always the greatest element (max maxpqueue) internally uses functions of heap like make_heap, push_heap and pop_heap to maintain heap structure */ /* */
26
100
0.668896
Praneeth-rdy
fb3a6a685fb315858b43119fbf797eac5c326813
2,575
cpp
C++
Vishv_GE/Framework/AI/Src/WorldIO.cpp
InFaNsO/Vishv_GameEngine
e721afa899fb8715e52cdd67c2656ba6cce7ffed
[ "MIT" ]
1
2021-12-19T02:06:12.000Z
2021-12-19T02:06:12.000Z
Vishv_GE/Framework/AI/Src/WorldIO.cpp
InFaNsO/Vishv_GameEngine
e721afa899fb8715e52cdd67c2656ba6cce7ffed
[ "MIT" ]
null
null
null
Vishv_GE/Framework/AI/Src/WorldIO.cpp
InFaNsO/Vishv_GameEngine
e721afa899fb8715e52cdd67c2656ba6cce7ffed
[ "MIT" ]
null
null
null
#include "Precompiled.h" #include "WorldIO.h" #include "World.h" namespace { std::string ToString(const Vishv::Math::Shapes::Capsule& cap) { std::string txt; txt += "Position: " + cap.mTransform.Position().ToString() + "\n"; txt += "Rotation: " + cap.mTransform.Rotation().ToString() + "\n"; txt += "Radius: " + std::to_string(cap.mRadius) + "\n"; txt += "Height: " + std::to_string(cap.GetHeight()) + "\n"; return std::move(txt); } std::string ToString(const Vishv::Math::Shapes::Cuboid& c) { std::string txt; txt += "Position: " + c.mTransform.Position().ToString() + "\n"; txt += "Rotation: " + c.mTransform.Rotation().ToString() + "\n"; txt += "LengthX: " + std::to_string(c.GetLengthX()) + "\n"; txt += "LengthY: " + std::to_string(c.GetLengthY()) + "\n"; txt += "LengthZ: " + std::to_string(c.GetLengthZ()) + "\n"; return std::move(txt); } } void Vishv::AI::WorldIO::Save(std::filesystem::path path, const World & world) { std::fstream file; file.open(path, std::ios::out); file.close(); file.open(path); if (!file.is_open()) return; file << "NumberObstacles: " << world.GetObstacles().size() << std::endl; file << "NumberWalls: " << world.GetWalls().size() << std::endl; for (size_t i = 0; i < world.GetObstacles().size(); ++i) file << ToString(world.GetObstacles()[i]); for (size_t i = 0; i < world.GetWalls().size(); ++i) file << ToString(world.GetWalls()[i]); } void Vishv::AI::WorldIO::Load(std::filesystem::path path, World & world) { std::fstream file; file.close(); file.open(path); if (!file.is_open()) return; size_t maxObs, maxWall; std::string holder; file >> holder >> maxObs >> holder >> maxWall; world.GetObstacles().reserve(maxObs); world.GetWalls().reserve(maxWall); for (size_t i = 0; i < maxObs; ++i) { World::Obstacle obs; Math::Vector3 pr; Math::Quaternion q; file >> holder >> pr.x >> pr.y >> pr.z; obs.mTransform.mPosition = pr; file >> holder >> q.w >> q.x >> q.y >> q.z; obs.mTransform.SetRotation(std::move(q)); float h; file >> holder >> obs.mRadius >> holder >> h; obs.SetHeight(h); world.Register(obs); } for (size_t i = 0; i < maxWall; ++i) { World::Wall wall; Math::Vector3 pr; Math::Quaternion q; file >> holder >> pr.x >> pr.y >> pr.z; wall.mTransform.mPosition = pr; file >> holder >> q.w >> q.x >> q.y >> q.z; wall.mTransform.SetRotation(std::move(q)); file >> holder >> pr.x >> holder >> pr.y >> holder >> pr.z; wall.SetLengthX(pr.x); wall.SetLengthY(pr.y); wall.SetLengthZ(pr.z); world.Register(wall); } }
26.010101
78
0.609709
InFaNsO
fb3dea7527198b4818d176f7146d3dc90932d1be
3,279
cpp
C++
src/base/muduo/base/common/logfile.cpp
sbfhy/server1
b9597a3783a0f7bb929b4b9fa7f621c81740b056
[ "BSD-3-Clause" ]
null
null
null
src/base/muduo/base/common/logfile.cpp
sbfhy/server1
b9597a3783a0f7bb929b4b9fa7f621c81740b056
[ "BSD-3-Clause" ]
null
null
null
src/base/muduo/base/common/logfile.cpp
sbfhy/server1
b9597a3783a0f7bb929b4b9fa7f621c81740b056
[ "BSD-3-Clause" ]
null
null
null
#include "muduo/base/common/logfile.h" #include "muduo/base/common/logging.h" #include "muduo/base/common/file_util.h" #include "muduo/base/common/process_info.h" #include "define/define_new.h" #include <assert.h> #include <cstdio> #include <cstring> #include <ctime> #include <libgen.h> using namespace muduo; std::string LogFile::s_fileDir = "log/"; std::unique_ptr<muduo::LogFile> g_logFile; void outputFunc(const CHAR* msg, SDWORD len) { g_logFile->append(msg, len); } void flushFunc() { g_logFile->flush(); } LogFile::LogFile(const std::string& basename, off_t rollSize, bool threadSafe, SDWORD flushInterval, SDWORD checkEveryN) : m_basename(basename) , m_rollSize(rollSize) , m_flushInterval(flushInterval) , m_checkEveryN(checkEveryN) , m_count(0) , m_mutex(threadSafe ? NEW MutexLock : nullptr) , m_startOfPeriod(0) , m_lastRoll(0) , m_lastFlush(0) { assert(basename.find('/') == std::string::npos); RollFile(); } LogFile::~LogFile() = default; void LogFile::append(const CHAR* logline, SDWORD len) { if (m_mutex) { MutexLockGuard lock(*m_mutex); append_unlocked(logline, len); } else { append_unlocked(logline, len); } } void LogFile::flush() { if (m_mutex) { MutexLockGuard lock(*m_mutex); m_file->flush(); } else { m_file->flush(); } } void LogFile::append_unlocked(const CHAR* logline, SDWORD len) { m_file->append(logline, len); if (m_file->getWrittenBytes() > m_rollSize) { RollFile(); } else { ++ m_count; if (m_count >= m_checkEveryN) { m_count = 0; time_t now = ::time(nullptr); time_t thisPeriod = now / kRollPerSeconds * kRollPerSeconds; if (thisPeriod != m_startOfPeriod) { RollFile(); } else if (now - m_lastFlush > m_flushInterval) { m_lastFlush = now; m_file->flush(); } } } } bool LogFile::RollFile() { time_t now = 0; std::string filename = getLogFileName(m_basename, &now); time_t start = now / kRollPerSeconds * kRollPerSeconds; if (now > m_lastRoll) { m_lastRoll = now; m_lastFlush = now; m_startOfPeriod = start; m_file.reset(NEW FileUtil::AppendFile(LogFile::s_fileDir + filename)); return true; } return false; } void LogFile::SetLogFile(const char* exePath, const char* baseName, off_t rollSize) { g_logFile.reset(NEW muduo::LogFile(baseName, rollSize)); muduo::Logger::setOutputFunc(outputFunc); muduo::Logger::setFlushFunc(flushFunc); } void LogFile::setLogFileDir(const char* fileDir) { s_fileDir = ::dirname(const_cast<char*>(fileDir)); s_fileDir += "/log/"; } std::string LogFile::getLogFileName(const std::string& basename, time_t* now) { std::string filename; filename.reserve(basename.size() + 64); filename = basename; CHAR timebuf[32]; struct tm tm; *now = time(nullptr); //gmtime_r(now, &tm); // FIXME: localtime_r ? localtime_r(now, &tm); strftime(timebuf, sizeof timebuf, "_%Y%m%d_%H%M%S_", &tm); filename += timebuf; // filename += ProcessInfo::hostname(); CHAR pidbuf[32]; snprintf(pidbuf, sizeof pidbuf, "%d", ProcessInfo::pid()); filename += pidbuf; filename += ".log"; return filename; }
21.715232
83
0.652028
sbfhy
fb41daf612b10ada62a4d52accc687895a383c62
8,237
cpp
C++
anet/test/sockettf.cpp
imyouxia/Source
624df9ffeb73d9ce918d5f7ef77bae6b9919e30a
[ "MIT" ]
115
2016-08-02T02:07:12.000Z
2022-03-04T01:44:13.000Z
anet/test/sockettf.cpp
EmpTan/Source
624df9ffeb73d9ce918d5f7ef77bae6b9919e30a
[ "MIT" ]
null
null
null
anet/test/sockettf.cpp
EmpTan/Source
624df9ffeb73d9ce918d5f7ef77bae6b9919e30a
[ "MIT" ]
46
2016-08-09T09:54:27.000Z
2021-03-05T10:47:55.000Z
#include <iostream> #include <string> #include "sockettf.h" #include <anet/anet.h> #include <unistd.h> #include <anet/serversocket.h> #include <anet/log.h> #include <signal.h> using namespace std; namespace anet { CPPUNIT_TEST_SUITE_REGISTRATION(SocketTF); class PlainConnectRunnable : public Runnable { public: void run(Thread* thread, void *args) { Socket *socket = (Socket *) args; CPPUNIT_ASSERT(socket); CPPUNIT_ASSERT(socket->connect()); } }; struct SocketPair { ServerSocket * serverSocket; Socket *acceptedSocket; }; class PlainServerRunnable : public Runnable { public: void run(Thread* thread, void *args) { SocketPair *sockpair = (SocketPair*)args; CPPUNIT_ASSERT(sockpair->serverSocket); sockpair->acceptedSocket = sockpair->serverSocket->accept(); CPPUNIT_ASSERT(sockpair->acceptedSocket); } }; struct PlainReadArgs { Socket *socket; char * buffer; int bytes; int bytesRead; }; class PlainReadRunnable : public Runnable { public: void run(Thread* thread, void *args) { PlainReadArgs *myArgs = static_cast<PlainReadArgs*> (args); myArgs->bytesRead = myArgs->socket->read(myArgs->buffer, myArgs->bytes); } }; void SocketTF::setUp() { } void SocketTF::tearDown() { } void SocketTF::testSetGetAddress() { Socket socket; char result[32]; string expect; //testing invalid address CPPUNIT_ASSERT(!socket.setAddress("NoSushAddress.james.zhang",12345)); CPPUNIT_ASSERT(socket.setAddress(NULL, 12345)); CPPUNIT_ASSERT(socket.getAddr(result, 10)); CPPUNIT_ASSERT_EQUAL(string("0.0.0.0:1"), string(result)); CPPUNIT_ASSERT(socket.setAddress("", 0)); CPPUNIT_ASSERT(socket.setAddress("localhost", 12345)); CPPUNIT_ASSERT(socket.getAddr(result, 32)); CPPUNIT_ASSERT_EQUAL(string("127.0.0.1:12345"), string(result)); CPPUNIT_ASSERT(socket.setAddress("127.0.0.1", -1)); CPPUNIT_ASSERT(socket.getAddr(result, 32)); CPPUNIT_ASSERT_EQUAL(string("127.0.0.1:65535"), string(result)); CPPUNIT_ASSERT(socket.setAddress("202.165.102.205", 12345)); CPPUNIT_ASSERT(socket.setAddress("www.yahoo.com", 12345)); CPPUNIT_ASSERT(socket.setAddress("g.cn", 12345)); } void SocketTF::testReadWrite() { Socket socket; ServerSocket serverSocket; char data[]="Some Data"; char output[1024]; CPPUNIT_ASSERT_EQUAL(-1,socket.write(data, strlen(data))); CPPUNIT_ASSERT(socket.setAddress("localhost", 11234)); CPPUNIT_ASSERT(serverSocket.setAddress("localhost", 11234)); CPPUNIT_ASSERT(serverSocket.listen()); SocketPair socketPair; socketPair.serverSocket=&serverSocket; Thread tc, ts; PlainConnectRunnable pcr; PlainServerRunnable psr; tc.start(&pcr,&socket);//connect ts.start(&psr,&socketPair);//accept ts.join(); tc.join(); Socket *acceptedSocket = socketPair.acceptedSocket; acceptedSocket->setSoBlocking(false); socket.setSoBlocking(false); CPPUNIT_ASSERT(acceptedSocket); CPPUNIT_ASSERT_EQUAL(9, socket.write(data, strlen(data))); CPPUNIT_ASSERT_EQUAL(9, acceptedSocket->read(output, 10)); CPPUNIT_ASSERT_EQUAL(-1, acceptedSocket->read(NULL, 3)); CPPUNIT_ASSERT_EQUAL(string(data, 9), string(output, 9)); CPPUNIT_ASSERT_EQUAL(-1, acceptedSocket->read(output,10)); CPPUNIT_ASSERT_EQUAL(EAGAIN, Socket::getLastError()); CPPUNIT_ASSERT_EQUAL(3, socket.write(data, 3)); CPPUNIT_ASSERT_EQUAL(3, acceptedSocket->read(output, 10)); CPPUNIT_ASSERT_EQUAL(4, acceptedSocket->write(data, 4)); CPPUNIT_ASSERT_EQUAL(4, socket.read(output, 10)); CPPUNIT_ASSERT_EQUAL(string(data, 4), string(output, 4)); CPPUNIT_ASSERT_EQUAL(-1, socket.write(NULL, 3)); CPPUNIT_ASSERT_EQUAL(-1, acceptedSocket->read(NULL, 3)); acceptedSocket->close(); CPPUNIT_ASSERT_EQUAL(-1, acceptedSocket->read(output, 10)); CPPUNIT_ASSERT_EQUAL(0, socket.read(output,3)); /**@note: we can write to socket whose peer was closed*/ CPPUNIT_ASSERT_EQUAL(3, socket.write(data,3)); delete acceptedSocket; socket.close(); CPPUNIT_ASSERT_EQUAL(-1, socket.write(data, 3)); tc.start(&pcr,&socket);//connect ts.start(&psr,&socketPair);//accept ts.join(); tc.join(); acceptedSocket = socketPair.acceptedSocket; acceptedSocket->setSoBlocking(false); CPPUNIT_ASSERT(acceptedSocket); acceptedSocket->shutdown(); CPPUNIT_ASSERT_EQUAL(-1, acceptedSocket->read(output, 10)); signal(SIGPIPE, SIG_IGN); CPPUNIT_ASSERT_EQUAL(-1, acceptedSocket->write(data, 10)); /** * @todo need to handle socket shutdown? * CPPUNIT_ASSERT_EQUAL(-1, acceptedSocket->read(output, 10)); * CPPUNIT_ASSERT_EQUAL(-1, acceptedSocket->write(data, 10)); */ socket.close(); delete acceptedSocket; CPPUNIT_ASSERT(socket.createUDP()); CPPUNIT_ASSERT_EQUAL(-1, socket.write(data, 3)); CPPUNIT_ASSERT(socket.setAddress("localhost",22)); CPPUNIT_ASSERT(socket.connect()); CPPUNIT_ASSERT_EQUAL(5, socket.write(data, 5)); /** * @todo need more UDP interface * CPPUNIT_ASSERT_EQUAL(string("Need More"), string("UDP Interface")); */ socket.close(); serverSocket.close(); acceptedSocket->close(); } void SocketTF::testConnect() { char data[] = "Short Data"; char output[256]; Socket socket; CPPUNIT_ASSERT(!socket.connect()); CPPUNIT_ASSERT(socket.setAddress("localhost",12346)); CPPUNIT_ASSERT(!socket.connect()); ServerSocket serverSocket; ServerSocket serverSocket2; CPPUNIT_ASSERT(!serverSocket.listen()); CPPUNIT_ASSERT(serverSocket.setAddress("localhost",12346)); CPPUNIT_ASSERT(serverSocket2.setAddress("localhost",12346)); CPPUNIT_ASSERT(serverSocket.listen()); CPPUNIT_ASSERT(serverSocket.setSoBlocking(false)); CPPUNIT_ASSERT(!serverSocket2.listen()); CPPUNIT_ASSERT(socket.connect()); CPPUNIT_ASSERT(socket.setSoBlocking(false)); /** * @todo should we detect if no body accept()? * CPPUNIT_ASSERT_EQUAL(-1, socket.write(data,3)); */ CPPUNIT_ASSERT_EQUAL(3, socket.write(data,3)); Socket *acceptedSocket = serverSocket.accept(); CPPUNIT_ASSERT(acceptedSocket); CPPUNIT_ASSERT(acceptedSocket->setSoBlocking(false)); ANET_LOG(DEBUG,"Before acceptedSocket->read(output,256)"); CPPUNIT_ASSERT_EQUAL(3, acceptedSocket->read(output,256)); ANET_LOG(DEBUG,"After acceptedSocket->read(output,256)"); CPPUNIT_ASSERT_EQUAL(string(data,3), string(output,3)); ANET_LOG(DEBUG,"Before serverSocket.accept()"); Socket *acceptedSocket2 = serverSocket.accept(); ANET_LOG(DEBUG,"After serverSocket.accept()"); CPPUNIT_ASSERT(!acceptedSocket2); delete acceptedSocket; acceptedSocket = NULL; CPPUNIT_ASSERT(socket.reconnect()); acceptedSocket2 = serverSocket.accept(); CPPUNIT_ASSERT(acceptedSocket2); CPPUNIT_ASSERT(acceptedSocket2->setSoBlocking(true)); Thread thread; PlainReadRunnable readRunnable; PlainReadArgs args; args.socket = acceptedSocket2; args.buffer = output; args.bytes = 8; thread.start(&readRunnable, &args); socket.setTcpNoDelay(true); sleep(1); CPPUNIT_ASSERT_EQUAL(3, socket.write(data,3)); CPPUNIT_ASSERT_EQUAL(5, socket.write(data+3, 5)); thread.join(); /**Blocking read will be blocked when there is no data to read! * So we should expect args.bytes > 0*/ CPPUNIT_ASSERT(args.bytesRead > 0); CPPUNIT_ASSERT_EQUAL(string(data,args.bytesRead), string(output,args.bytesRead)); delete acceptedSocket2; } void SocketTF::testListenZeroIPZeroPort() { ANET_LOG(DEBUG, "testListenZeroIPZeroPort"); ServerSocket server; CPPUNIT_ASSERT(server.setAddress("0.0.0.0", 0)); char result[32]; CPPUNIT_ASSERT(server.getAddr(result, 32)); CPPUNIT_ASSERT_EQUAL(string("0.0.0.0:0"), string(result)); CPPUNIT_ASSERT(!server.getAddr(result, 32, true)); CPPUNIT_ASSERT(server.listen()); CPPUNIT_ASSERT(server.getAddr(result, 32, true)); ANET_LOG(DEBUG, "active address: %s", result); CPPUNIT_ASSERT(string("0.0.0.0:0") != string(result)); } }
34.902542
74
0.697098
imyouxia
fb440012eb7e1eb2fac399bc134e1987affba322
2,670
cpp
C++
tests/test.cpp
summersoul17/Lab-12-refactoring-summersoul
9d516191808f33ba41ce6ba7ecb2f4fea389f879
[ "MIT" ]
null
null
null
tests/test.cpp
summersoul17/Lab-12-refactoring-summersoul
9d516191808f33ba41ce6ba7ecb2f4fea389f879
[ "MIT" ]
null
null
null
tests/test.cpp
summersoul17/Lab-12-refactoring-summersoul
9d516191808f33ba41ce6ba7ecb2f4fea389f879
[ "MIT" ]
null
null
null
// Copyright 2020 Your Name <your_email> #include <gmock/gmock.h> #include <page_container.hpp> #include "stat_sender_test.hpp" #include <used_memory.hpp> TEST(MemoryUsage, MemUsingTest) { std::vector<std::string> old_raw_data{ "first" }, new_raw_data { "first", "second", "third", "fourth" }; used_memory memory; memory.on_raw_data_load(old_raw_data, new_raw_data); EXPECT_EQ(memory.used(), 45); memory.clear(); std::vector<item> old_data{}, new_data{ {1, "rand", 10}, {2, "rand", 20}, {3, "rand", 30} }; memory.on_data_load(old_data, new_data); EXPECT_EQ(memory.used(), 69); } void prepare_stringstream(std::stringstream& ss, size_t lines = 20){ for (size_t i = 0; i < lines; ++i) { ss << (i + 1) << " cor " << (i < 6 ? 25 : 50) << '\n'; } ss << 21 << " inc " << "ls" << '\n'; ss << 22 << " inc " << "la" << '\n'; } TEST(PageContainer_Test, Data_Test) { srand(time(nullptr)); std::stringstream ss{}; prepare_stringstream(ss); page_container page; page.load_raw_data(ss); page.load_data(0); EXPECT_EQ(page.data_size(), 20); } TEST(PageContainer_Test, AsyncSend_Test) { using ::testing::_; using ::testing::AtLeast; srand(time(nullptr)); std::stringstream ss{}; prepare_stringstream(ss); used_memory* used = new used_memory(); mock_stat_sender* sender = new mock_stat_sender(); page_container<mock_stat_sender> page(used, sender); page.load_raw_data(ss); EXPECT_CALL(*sender, async_send(_, std::string_view{"/items/loaded"})) .Times(2); EXPECT_CALL(*sender, async_send(_, std::string_view{"/items/skipped"})) .Times(12); page.load_data(0); page.load_data(30); } TEST(PageContainer_Test, AlreadySeen){ std::stringstream ss{}; prepare_stringstream(ss); ss << 20 << " cop " << 20 << '\n'; page_container page{}; page.load_raw_data(ss); EXPECT_THROW(page.load_data(0), std::runtime_error); } TEST(PageContainer_Test, EmptyFile){ std::ifstream file_{"empty.txt"}; std::ofstream empty{"empty.txt"}; page_container page{}; EXPECT_THROW(page.load_raw_data(file_), std::runtime_error); empty.close(); } TEST(PageContainer_Test, CorruptedFile){ std::ifstream file_; file_.close(); page_container page{}; EXPECT_THROW(page.load_raw_data(file_), std::runtime_error); } TEST(PageContainer_Test, TooSmallInputStream){ std::stringstream ss{}; prepare_stringstream(ss, 5); page_container page{}; EXPECT_THROW(page.load_raw_data(ss), std::runtime_error); } TEST(PageContainer_Test, TooSmallInputStream_LoadData){ std::stringstream ss{}; prepare_stringstream(ss); page_container page{}; page.load_raw_data(ss); EXPECT_THROW(page.load_data(1000),std::runtime_error); }
23.628319
68
0.693633
summersoul17
fb494cbd3333c238418b7175dbef8c17b8d67c33
179
cpp
C++
oj-noi-level1/1003.cpp
xiaji/noip-csp
7551478e848f3c3d2a4cc2d780d0efeedab67e6e
[ "MIT" ]
1
2021-02-22T03:40:59.000Z
2021-02-22T03:40:59.000Z
oj-noi-level1/1003.cpp
xiaji/noip-csp
7551478e848f3c3d2a4cc2d780d0efeedab67e6e
[ "MIT" ]
null
null
null
oj-noi-level1/1003.cpp
xiaji/noip-csp
7551478e848f3c3d2a4cc2d780d0efeedab67e6e
[ "MIT" ]
null
null
null
/* * guess number */ #include <iostream> using namespace std; int main() { int input; cin >> input; input *= 1001; input /= 7 * 11 * 13; cout << input; return 0; }
11.933333
23
0.564246
xiaji
fb4a7a7be35a7eabb6eea80cd086885cc11ea557
2,633
hpp
C++
soccer/planning/primitives/PathSmoothing.hpp
kasohrab/robocup-software
73c92878baf960844b5a4b34c72804093f1ea459
[ "Apache-2.0" ]
null
null
null
soccer/planning/primitives/PathSmoothing.hpp
kasohrab/robocup-software
73c92878baf960844b5a4b34c72804093f1ea459
[ "Apache-2.0" ]
null
null
null
soccer/planning/primitives/PathSmoothing.hpp
kasohrab/robocup-software
73c92878baf960844b5a4b34c72804093f1ea459
[ "Apache-2.0" ]
null
null
null
#pragma once #include <Geometry2d/Point.hpp> #include "planning/MotionConstraints.hpp" namespace Planning { /** * @brief A spatial path with no time or angle information. */ class BezierPath { public: /** * @brief Construct a bezier path for a curve with a given velocity, going * through the specified points and with specified velocity at endpoints. * * @param points The points through which the final curve must pass. These * will be used as the endpoints for consecutive Bezier segments. In * total there will be points.size() - 1 curves. This must not be * empty. * @param vi The initial velocity, used as a tangent for the first curve. * @param vf The final velocity, used as a tangent for the last curve. * @param motion_constraints Linear constraints for motion. These are used * to approximate the time between control points, which is later used * to match up tangent vectors (approximately) with velocities. */ BezierPath(const std::vector<Geometry2d::Point>& points, Geometry2d::Point vi, Geometry2d::Point vf, MotionConstraints motion_constraints); /** * @brief Evaluate the path at a particular instant drawn from [0, 1]. * Calculates only those values requested (by passing in a non-null * pointer). * * @param s The index to sample along, in the range of [0, 1]. * @param position Output parameter for the position at s, if non-null. * @param tangent Output parameter for the tangent vector at s, if non-null. * @param curvature Output parameter for the curvature at s, if non-null. */ void Evaluate(double s, Geometry2d::Point* position = nullptr, Geometry2d::Point* tangent = nullptr, double* curvature = nullptr) const; /** * @brief Whether or not this curve is empty. */ [[nodiscard]] bool empty() const { return control.empty(); } /** * @brief The number of cubic segments in this Bezier curve. */ [[nodiscard]] int size() const { return control.size(); } /** * @brief Control points for a Bezier curve. */ struct CubicBezierControlPoints { Geometry2d::Point p0, p1, p2, p3; CubicBezierControlPoints() = default; CubicBezierControlPoints(Geometry2d::Point p0, Geometry2d::Point p1, Geometry2d::Point p2, Geometry2d::Point p3) : p0(p0), p1(p1), p2(p2), p3(p3) {} }; private: std::vector<CubicBezierControlPoints> control; }; } // namespace Planning
35.581081
80
0.642993
kasohrab
fb4dcc170a16c5da307f59ff76b5678ecc8f51b6
5,209
cpp
C++
src/node_id.cpp
syoummer/boost.actor
58f35499bac8871b8f5b0b024246a467b63c6fb0
[ "BSL-1.0" ]
2
2015-03-20T21:11:16.000Z
2020-01-20T08:05:41.000Z
src/node_id.cpp
syoummer/boost.actor
58f35499bac8871b8f5b0b024246a467b63c6fb0
[ "BSL-1.0" ]
null
null
null
src/node_id.cpp
syoummer/boost.actor
58f35499bac8871b8f5b0b024246a467b63c6fb0
[ "BSL-1.0" ]
null
null
null
/******************************************************************************\ * * * ____ _ _ _ * * | __ ) ___ ___ ___| |_ / \ ___| |_ ___ _ __ * * | _ \ / _ \ / _ \/ __| __| / _ \ / __| __/ _ \| '__| * * | |_) | (_) | (_) \__ \ |_ _ / ___ \ (__| || (_) | | * * |____/ \___/ \___/|___/\__(_)_/ \_\___|\__\___/|_| * * * * * * * * Copyright (C) 2011 - 2014 * * Dominik Charousset <dominik.charousset@haw-hamburg.de> * * * * Distributed under the Boost Software License, Version 1.0. See * * accompanying file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt * \******************************************************************************/ #include <cstdio> #include <cstring> #include <sstream> #include <unistd.h> #include <sys/types.h> #include "boost/actor/config.hpp" #include "boost/actor/node_id.hpp" #include "boost/actor/serializer.hpp" #include "boost/actor/singletons.hpp" #include "boost/actor/primitive_variant.hpp" #include "boost/actor/io/middleman.hpp" #include "boost/actor/detail/ripemd_160.hpp" #include "boost/actor/detail/get_root_uuid.hpp" #include "boost/actor/detail/get_mac_addresses.hpp" #include "boost/actor/detail/safe_equal.hpp" namespace { std::uint8_t hex_char_value(char c) { if (isdigit(c)) { return static_cast<std::uint8_t>(c - '0'); } else if (isalpha(c)) { if (c >= 'a' && c <= 'f') { return static_cast<std::uint8_t>((c - 'a') + 10); } else if (c >= 'A' && c <= 'F') { return static_cast<std::uint8_t>((c - 'A') + 10); } } throw std::invalid_argument(std::string("illegal character: ") + c); } } // namespace <anonymous> namespace boost { namespace actor { void host_id_from_string(const std::string& hash, node_id::host_id_type& node_id) { if (hash.size() != (node_id.size() * 2)) { throw std::invalid_argument("string argument is not a node id hash"); } auto j = hash.c_str(); for (size_t i = 0; i < node_id.size(); ++i) { // read two characters, each representing 4 bytes auto& val = node_id[i]; val = static_cast<uint8_t>(hex_char_value(*j++) << 4); val |= hex_char_value(*j++); } } bool equal(const std::string& hash, const node_id::host_id_type& node_id) { if (hash.size() != (node_id.size() * 2)) { return false; } auto j = hash.c_str(); try { for (size_t i = 0; i < node_id.size(); ++i) { // read two characters, each representing 4 bytes std::uint8_t val; val = static_cast<uint8_t>(hex_char_value(*j++) << 4); val |= hex_char_value(*j++); if (val != node_id[i]) { return false; } } } catch (std::invalid_argument&) { return false; } return true; } node_id::~node_id() { } node_id::node_id(const node_id& other) : super(), m_process_id(other.process_id()), m_host_id(other.host_id()) { } node_id::node_id(std::uint32_t a, const std::string& b) : m_process_id(a) { host_id_from_string(b, m_host_id); } node_id::node_id(std::uint32_t a, const host_id_type& b) : m_process_id(a), m_host_id(b) { } std::string to_string(const node_id::host_id_type& node_id) { std::ostringstream oss; oss << std::hex; oss.fill('0'); for (size_t i = 0; i < node_id::host_id_size; ++i) { oss.width(2); oss << static_cast<std::uint32_t>(node_id[i]); } return oss.str(); } int node_id::compare(const node_id& other) const { int tmp = strncmp(reinterpret_cast<const char*>(host_id().data()), reinterpret_cast<const char*>(other.host_id().data()), host_id_size); if (tmp == 0) { if (m_process_id < other.process_id()) return -1; else if (m_process_id == other.process_id()) return 0; return 1; } return tmp; } void node_id::serialize_invalid(serializer* sink) { sink->write_value(static_cast<uint32_t>(0)); node_id::host_id_type zero; std::fill(zero.begin(), zero.end(), 0); sink->write_raw(node_id::host_id_size, zero.data()); } std::string to_string(const node_id& what) { std::ostringstream oss; oss << what.process_id() << "@" << to_string(what.host_id()); return oss.str(); } std::string to_string(const node_id_ptr& what) { std::ostringstream oss; oss << "@process_info("; if (!what) oss << "null"; else oss << to_string(*what); oss << ")"; return oss.str(); } } // namespace actor } // namespace boost
32.761006
80
0.499136
syoummer
fb523d08972668a1932853bee5cc8631a527f9ae
3,905
cpp
C++
tests/src/helpers/cyclicbuffertestcase.cpp
MacroGu/log4cxx_gcc_4_8
c6c82ee6dca2808c42cfa567d32f640a8bd9ac3e
[ "Apache-2.0" ]
1
2016-10-06T20:09:32.000Z
2016-10-06T20:09:32.000Z
tests/src/helpers/cyclicbuffertestcase.cpp
MacroGu/log4cxx_gcc_4_8
c6c82ee6dca2808c42cfa567d32f640a8bd9ac3e
[ "Apache-2.0" ]
null
null
null
tests/src/helpers/cyclicbuffertestcase.cpp
MacroGu/log4cxx_gcc_4_8
c6c82ee6dca2808c42cfa567d32f640a8bd9ac3e
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2003,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <cppunit/TestFixture.h> #include <cppunit/extensions/HelperMacros.h> #include <log4cxx/logmanager.h> #include <log4cxx/logger.h> #include <log4cxx/helpers/cyclicbuffer.h> #include <log4cxx/spi/loggingevent.h> using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::spi; #define MAX 1000 class CyclicBufferTestCase : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(CyclicBufferTestCase); CPPUNIT_TEST(test0); CPPUNIT_TEST(test1); CPPUNIT_TEST(testResize); CPPUNIT_TEST_SUITE_END(); LoggerPtr logger; std::vector<LoggingEventPtr> e; public: void setUp() { logger = Logger::getLogger(_T("x")); e.reserve(1000); for (int i = 0; i < MAX; i++) { e.push_back( new LoggingEvent(_T(""), logger, Level::DEBUG, _T("e"))); } } void tearDown() { LogManager::shutdown(); } void test0() { int size = 2; CyclicBuffer cb(size); CPPUNIT_ASSERT_EQUAL(size, cb.getMaxSize()); cb.add(e[0]); CPPUNIT_ASSERT_EQUAL(1, cb.length()); CPPUNIT_ASSERT_EQUAL(e[0], cb.get()); CPPUNIT_ASSERT_EQUAL(0, cb.length()); CPPUNIT_ASSERT(cb.get() == 0); CPPUNIT_ASSERT_EQUAL(0, cb.length()); CyclicBuffer cb2(size); cb2.add(e[0]); cb2.add(e[1]); CPPUNIT_ASSERT_EQUAL(2, cb2.length()); CPPUNIT_ASSERT_EQUAL(e[0], cb2.get()); CPPUNIT_ASSERT_EQUAL(1, cb2.length()); CPPUNIT_ASSERT_EQUAL(e[1], cb2.get()); CPPUNIT_ASSERT_EQUAL(0, cb2.length()); CPPUNIT_ASSERT(cb2.get() == 0); CPPUNIT_ASSERT_EQUAL(0, cb2.length()); } void test1() { for (int bufSize = 1; bufSize <= 128; bufSize *= 2) doTest1(bufSize); } void doTest1(int size) { //System.out.println("Doing test with size = "+size); CyclicBuffer cb(size); CPPUNIT_ASSERT_EQUAL(size, cb.getMaxSize()); int i; for (i = -(size + 10); i < (size + 10); i++) { CPPUNIT_ASSERT(cb.get(i) == 0); } for (i = 0; i < MAX; i++) { cb.add(e[i]); int limit = (i < (size - 1)) ? i : (size - 1); //System.out.println("\nLimit is " + limit + ", i="+i); for (int j = limit; j >= 0; j--) { //System.out.println("i= "+i+", j="+j); CPPUNIT_ASSERT_EQUAL(e[i - (limit - j)], cb.get(j)); } CPPUNIT_ASSERT(cb.get(-1) == 0); CPPUNIT_ASSERT(cb.get(limit + 1) == 0); } } void testResize() { for (int isize = 1; isize <= 128; isize *= 2) { doTestResize(isize, (isize / 2) + 1, (isize / 2) + 1); doTestResize(isize, (isize / 2) + 1, isize + 10); doTestResize(isize, isize + 10, (isize / 2) + 1); doTestResize(isize, isize + 10, isize + 10); } } void doTestResize(int initialSize, int numberOfAdds, int newSize) { //System.out.println("initialSize = "+initialSize+", numberOfAdds=" // +numberOfAdds+", newSize="+newSize); CyclicBuffer cb(initialSize); for (int i = 0; i < numberOfAdds; i++) { cb.add(e[i]); } cb.resize(newSize); int offset = numberOfAdds - initialSize; if (offset < 0) { offset = 0; } int len = (newSize < numberOfAdds) ? newSize : numberOfAdds; len = (len < initialSize) ? len : initialSize; //System.out.println("Len = "+len+", offset="+offset); for (int j = 0; j < len; j++) { CPPUNIT_ASSERT_EQUAL(e[offset + j], cb.get(j)); } } }; CPPUNIT_TEST_SUITE_REGISTRATION(CyclicBufferTestCase);
23.383234
75
0.644814
MacroGu
fb5636875fada244e2d08b484c0ab9880a342d4f
516
cpp
C++
Advanced_programmation2/bart-dx-engine-a17/D3DEngine/Camera.cpp
Bigbell01/Portfolio
ec094a7f96239904ddec9d090bcba2c044eb6119
[ "MIT" ]
null
null
null
Advanced_programmation2/bart-dx-engine-a17/D3DEngine/Camera.cpp
Bigbell01/Portfolio
ec094a7f96239904ddec9d090bcba2c044eb6119
[ "MIT" ]
null
null
null
Advanced_programmation2/bart-dx-engine-a17/D3DEngine/Camera.cpp
Bigbell01/Portfolio
ec094a7f96239904ddec9d090bcba2c044eb6119
[ "MIT" ]
null
null
null
#include "Camera.h" Camera::Camera(float width, float height) : up(0.f, -1.f, 0.f) , target(0.f, 0.f, 0.f) , width(width) , height(height) { } void Camera::Update() { D3DXMatrixLookAtLH(&view, &GetTransform()->GetPosition(), &target, &up); D3DXMatrixOrthoLH(&proj, width, height, 0.01f, 1000.0f); //D3DXMatrixPerspectiveFovLH(&proj, D3DX_PI/4, width/height, 0.01f, 1000.0f); HR(gD3DDevice->SetTransform(D3DTS_VIEW, &view)); HR(gD3DDevice->SetTransform(D3DTS_PROJECTION, &proj)); } Camera::~Camera() { }
21.5
78
0.684109
Bigbell01
fb5fe129bec2cb3a0dae0336ca0f4cebcca7a46b
136
cpp
C++
bin/maxPlugin/renElemPch.cpp
HonzaMD/Krkal2
e53e9b096d89d1441ec472deb6d695c45bcae41f
[ "OLDAP-2.5" ]
1
2018-04-01T16:47:52.000Z
2018-04-01T16:47:52.000Z
bin/maxPlugin/renElemPch.cpp
HonzaMD/Krkal2
e53e9b096d89d1441ec472deb6d695c45bcae41f
[ "OLDAP-2.5" ]
null
null
null
bin/maxPlugin/renElemPch.cpp
HonzaMD/Krkal2
e53e9b096d89d1441ec472deb6d695c45bcae41f
[ "OLDAP-2.5" ]
null
null
null
//////////////////////////////////////////////////////////////// // precompiled header for render elements // #include "renElemPch.h"
34
65
0.382353
HonzaMD
fb60cb73416b98fa31239668e0c09f2b4179a8fb
1,453
cpp
C++
Blik2D/element/blik_vector.cpp
BonexGu/Blik2D
8e0592787e5c8e8a28682d0e1826b8223eae5983
[ "MIT" ]
13
2017-02-22T02:20:06.000Z
2018-06-06T04:18:03.000Z
Blik2D/element/blik_vector.cpp
BonexGu/Blik2D
8e0592787e5c8e8a28682d0e1826b8223eae5983
[ "MIT" ]
null
null
null
Blik2D/element/blik_vector.cpp
BonexGu/Blik2D
8e0592787e5c8e8a28682d0e1826b8223eae5983
[ "MIT" ]
null
null
null
#include <blik.hpp> #include "blik_vector.hpp" namespace BLIK { Vector::Vector() { x = 0; y = 0; vx = 0; vy = 0; } Vector::Vector(const Vector& rhs) { operator=(rhs); } Vector::Vector(float x, float y, float vx, float vy) { this->x = x; this->y = y; this->vx = vx; this->vy = vy; } Vector::Vector(const Point& pos, const Point& vec) { x = pos.x; y = pos.y; vx = vec.x; vy = vec.y; } Vector::~Vector() { } Vector& Vector::operator=(const Vector& rhs) { x = rhs.x; y = rhs.y; vx = rhs.vx; vy = rhs.vy; return *this; } Vector& Vector::operator+=(const Point& rhs) { x += rhs.x; y += rhs.y; return *this; } Vector Vector::operator+(const Point& rhs) const { return Vector(*this).operator+=(rhs); } Vector& Vector::operator-=(const Point& rhs) { x -= rhs.x; y -= rhs.y; return *this; } Vector Vector::operator-(const Point& rhs) const { return Vector(*this).operator-=(rhs); } bool Vector::operator==(const Vector& rhs) const { return (x == rhs.x && y == rhs.y && vx == rhs.vx && vy == rhs.vy); } bool Vector::operator!=(const Vector& rhs) const { return !operator==(rhs); } }
17.719512
74
0.461115
BonexGu
fb6a9103018e519ff465f69fa6024c10161bce5e
4,099
cpp
C++
src/slider.cpp
bebuch/BitmapViewer
51259974e74859767982a363f419965e2396c513
[ "BSL-1.0" ]
null
null
null
src/slider.cpp
bebuch/BitmapViewer
51259974e74859767982a363f419965e2396c513
[ "BSL-1.0" ]
null
null
null
src/slider.cpp
bebuch/BitmapViewer
51259974e74859767982a363f419965e2396c513
[ "BSL-1.0" ]
null
null
null
//----------------------------------------------------------------------------- // Copyright (c) 2013-2018 Benjamin Buch // // https://github.com/bebuch/BitmapViewer // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt) //----------------------------------------------------------------------------- #include <BitmapViewer/slider.hpp> #include <QMouseEvent> #include <QPaintEvent> #include <QWheelEvent> #include <QPainter> #include <cmath> namespace bitmap_viewer{ constexpr double shift_range = std::numeric_limits< unsigned >::max() + 1.; slider::slider(QWidget* parent): QWidget(parent), active_(false), shift_(0), startpos_(0), startshift_(0) { setCursor(Qt::OpenHandCursor); colors_.update.connect([this]{repaint();change();}); } void slider::set_shift(unsigned s){ shift_ = colors_.pass_pos(s); repaint(); shift_changed(s); change(); } void slider::set_strips(unsigned count){ colors_.set_strips(count); set_shift(shift()); } void slider::contrast_line(bool enable){ colors_.contrast_line(enable); } void slider::next_palette(){ colors_.next_palette(); } unsigned slider::inc_step(unsigned step, int inc)const{ if(inc < 0){ inc = -inc % colors_.strips(); step += colors_.strips() - inc; }else{ step += inc; step %= colors_.strips(); } return step; } void slider::right_shift(){ auto step_pos = colors_.step_pos(shift_); step_pos = inc_step(step_pos, -1); set_shift(colors_.pass_step_pos(step_pos)); } void slider::left_shift(){ auto step_pos = colors_.step_pos(shift_); step_pos = inc_step(step_pos, 1); set_shift(colors_.pass_step_pos(step_pos)); } void slider::fold_linear(){ colors_.set_fold(colors_.fold() + 1); } void slider::unfold_linear(){ colors_.set_fold(colors_.fold() - 1); } void slider::fold_exponential(){ colors_.set_fold(colors_.fold() << 1); } void slider::unfold_exponential(){ colors_.set_fold(colors_.fold() >> 1); } void slider::mouseMoveEvent(QMouseEvent* event){ if(!active_) return; unsigned w = width(); set_shift(startshift_ + startpos_ - event->x() * (shift_range / w)); } void slider::mousePressEvent(QMouseEvent* event){ if(event->button() != Qt::LeftButton) return; active_ = true; setCursor(Qt::ClosedHandCursor); unsigned w = width(); startpos_ = event->x() * (shift_range / w); startshift_ = shift_; } void slider::mouseReleaseEvent(QMouseEvent* event){ if(event->button() != Qt::LeftButton) return; setCursor(Qt::OpenHandCursor); active_ = false; } void slider::paintEvent(QPaintEvent*){ QPainter painter(this); unsigned w = width(); for(unsigned i = 0; i < w; ++i){ painter.setPen(colors_(shift_ + i * (shift_range / w))); painter.drawLine(i, 0, i, height()); } auto text = QString("Pos: %1").arg(colors_.step_pos(shift_)); auto flags = Qt::AlignLeft | Qt::AlignVCenter; auto fontfactor = 0.7; auto fontsize = height() * fontfactor; auto x_offset = height() * (1 - fontfactor) / 2; auto p1 = QPointF(x_offset, 0); auto p2 = QPointF(w - 2*x_offset, height()); QFont font; font.setPixelSize(fontsize); font.setStyleStrategy(QFont::PreferAntialias); font.setStyleStrategy(QFont::PreferQuality); painter.setRenderHint(QPainter::TextAntialiasing); painter.setFont(font); painter.setPen(Qt::white); int range = 2; for(int y = -range; y <= range; ++y){ for(int x = -range; x <= range; ++x){ painter.drawText(QRectF(p1 + QPointF(x, y), p2), text, flags); } } painter.setPen(Qt::black); painter.drawText(QRectF(p1, p2), text, flags); } void slider::wheelEvent(QWheelEvent* event){ auto step_pos = colors_.step_pos(shift_); double factor = 1; if(event->buttons() & Qt::LeftButton) factor = 0.25; if(event->buttons() & Qt::RightButton) factor = 4; step_pos = inc_step( step_pos, std::max(factor * colors_.strips() / 32, 1.) * (event->angleDelta().y() > 0 ? 1 : -1) ); set_shift(colors_.pass_step_pos(step_pos)); } }
24.254438
79
0.647719
bebuch
fb6ce7d99eb2d5d25919416dbe37b55aa1bdef92
431
hpp
C++
src/Client/Input/Window.hpp
fqhd/BuildBattle
f85ec857aa232313f4678514aa317af73c37de10
[ "MIT" ]
10
2021-08-17T20:55:52.000Z
2022-03-28T00:45:14.000Z
src/Client/Input/Window.hpp
fqhd/BuildBattle
f85ec857aa232313f4678514aa317af73c37de10
[ "MIT" ]
null
null
null
src/Client/Input/Window.hpp
fqhd/BuildBattle
f85ec857aa232313f4678514aa317af73c37de10
[ "MIT" ]
2
2021-07-05T18:49:56.000Z
2021-07-10T22:03:17.000Z
#pragma once #define GLFW_INCLUDE_NONE #include <GLFW/glfw3.h> #include <GL/glew.h> #include "Math.hpp" #include <iostream> class Window { public: static void create(unsigned int _width, unsigned int _height, const char* _title, bool _resizable = false, bool _decorated = true); static void clear(); static void update(); static void close(); static GLFWwindow* getWindowPtr(); private: static GLFWwindow* m_window; };
18.73913
132
0.737819
fqhd
fb81584a0290e80a06d56da0f6fd5d9c007ca880
1,980
cpp
C++
src/core/sample.cpp
BiRDLab-UMinho/trignoclient
507351e818b37199aa00aefedb124885dda1ea98
[ "MIT" ]
null
null
null
src/core/sample.cpp
BiRDLab-UMinho/trignoclient
507351e818b37199aa00aefedb124885dda1ea98
[ "MIT" ]
null
null
null
src/core/sample.cpp
BiRDLab-UMinho/trignoclient
507351e818b37199aa00aefedb124885dda1ea98
[ "MIT" ]
null
null
null
#include <string> #include <vector> #include <iostream> #include <cstring> // std::memcpy #include "core/sample.hpp" // trigno::sample::ID namespace trigno { Sample::Sample(sensor::ID id, size_t n_channels, const char* raw_data) : _id(id), _data(n_channels) { /* ... */ if (raw_data != nullptr) { for (int ch = 0; ch < n_channels; ch++) { std::memcpy(&_data[ch], raw_data, sizeof(_data[ch])); } } } Sample::Sample(sensor::ID id, const std::vector< float >& values) : _id(id), _data(values) { /* ... */ } sensor::ID Sample::id() const noexcept { return _id; } size_t Sample::size() const noexcept { return _data.size(); } bool Sample::empty() const noexcept { return _data.empty(); } float& Sample::operator[](size_t channel) { if (channel >= _data.size()) { throw std::out_of_range("[" + std::string(__func__) + "] Invalid channel index!!"); } return _data[channel]; } const float& Sample::operator[](size_t channel) const { if (channel >= _data.size()) { throw std::out_of_range("[" + std::string(__func__) + "] Invalid channel index!!"); } return _data[channel]; } const Sample::Container& Sample::data() const { return _data; } Sample::operator const Container&() const { return _data; } Sample::operator const Sample::Value&() const noexcept { return _data.front(); } Sample::Value Sample::average() const { auto avg = 0.0; for (const auto& value : _data) { avg += value; } return (avg/=size()); } std::vector< float >::iterator Sample::begin() { return _data.begin(); } std::vector< float >::const_iterator Sample::begin() const { return _data.begin(); } std::vector< float >::iterator Sample::end() { return _data.end(); } std::vector< float >::const_iterator Sample::end() const { return _data.end(); } } // namespace trigno
16.923077
91
0.589394
BiRDLab-UMinho
fb81d82969cfe6877be8c84fb2a33d590bef3de3
4,050
cpp
C++
src/HoursMinutes.cpp
hartogjr/timecal
2c4607947b03a6fa8ee82fd3eeb6e2dc36cdd93b
[ "BSD-3-Clause" ]
null
null
null
src/HoursMinutes.cpp
hartogjr/timecal
2c4607947b03a6fa8ee82fd3eeb6e2dc36cdd93b
[ "BSD-3-Clause" ]
null
null
null
src/HoursMinutes.cpp
hartogjr/timecal
2c4607947b03a6fa8ee82fd3eeb6e2dc36cdd93b
[ "BSD-3-Clause" ]
null
null
null
/* BSD 3-Clause License * * Copyright (c) 2020, Simon de Hartog <simon@dehartog.name> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * vim:set ts=4 sw=4 noexpandtab: */ #include <cerrno> #include <ctime> #include <iomanip> #include <iostream> #include <sstream> #include <stdexcept> #include "HoursMinutes.h" namespace SdH { uint8_t HoursMinutes::parseChar(const char char_i) { if (char_i < '0' || char_i > '9') { throw std::invalid_argument( std::string("Invalid character '") + char_i + "' in time string" ); } return char_i - '0'; } uint8_t HoursMinutes::parse(const std::string & str_i, const uint8_t max_i) { if (str_i.empty() || str_i == "0" || str_i == "00") return 0; uint8_t rv = 0; // Return Value switch (str_i.size()) { case 2: rv = parseChar(str_i[0]) * 10 + parseChar(str_i[1]); break; case 1: rv = parseChar(str_i[0]); break; default: throw std::invalid_argument("Integer string longer than two characters"); } if (rv > max_i) { std::ostringstream oss; oss << "String value \"" << str_i << "\" is a valid integer but is larger than "; oss << static_cast<uint16_t>(max_i); throw std::overflow_error(oss.str()); } return rv; } void HoursMinutes::set(const std::string & hm_i) { size_t pos = 0; uint8_t tmphrs = 0; uint8_t tmpmin = 0; if (hm_i.empty() || hm_i == ":") { reset(); return; } pos = hm_i.find(':'); if (pos == std::string::npos) { // No hours specified, just minutes tmpmin = parse(hm_i, 59); hours_a = 0; minutes_a = tmpmin; return; } tmphrs = parse(hm_i.substr(0, pos), 23); tmpmin = parse(hm_i.substr(pos+1), 59); hours_a = tmphrs; minutes_a = tmpmin; } void HoursMinutes::set(const time_t & time_i) { struct tm *tmptr = nullptr; tmptr = localtime(&time_i); if (tmptr == nullptr) { throw std::runtime_error("Unable to break down time to parts"); } hours_a = tmptr->tm_hour; minutes_a = tmptr->tm_min; } HoursMinutes & HoursMinutes::operator+=(const HoursMinutes & rhs_i) { hours_a += rhs_i.hours_a; minutes_a += rhs_i.minutes_a; if (minutes_a > 59) { hours_a++; minutes_a %= 60; } if (hours_a > 23) hours_a %= 24; return (*this); } } // SdH namespace std::ostream & operator<<(std::ostream & os, const SdH::HoursMinutes & hm) { os << std::dec << std::setw(2) << std::setfill('0') << static_cast<uint16_t>(hm.hours()); os << ':'; os << std::dec << std::setw(2) << std::setfill('0') << static_cast<uint16_t>(hm.minutes()); return os; }
27.739726
92
0.675062
hartogjr
fb8329526b43d2615bd1cedcaf9f5ab374b45723
3,592
hpp
C++
src/verbatim_vertex_buffer.hpp
trilkk/faemiyah-demoscene_2015-04_64k-intro_junamatkailuintro
fdd055871a95f99c9162bced542e6d08be47f7e8
[ "BSD-3-Clause" ]
2
2015-05-25T02:22:41.000Z
2015-10-06T17:39:55.000Z
src/verbatim_vertex_buffer.hpp
faemiyah/faemiyah-demoscene_2015-04_64k-intro_junamatkailuintro
fdd055871a95f99c9162bced542e6d08be47f7e8
[ "BSD-3-Clause" ]
null
null
null
src/verbatim_vertex_buffer.hpp
faemiyah/faemiyah-demoscene_2015-04_64k-intro_junamatkailuintro
fdd055871a95f99c9162bced542e6d08be47f7e8
[ "BSD-3-Clause" ]
null
null
null
#ifndef VERBATIM_VERTEX_BUFFER #define VERBATIM_VERTEX_BUFFER #include "verbatim_array.hpp" #include "verbatim_vertex.hpp" // Forward declaration. class Program; /** Vertex buffer. */ class VertexBuffer { private: /** Current vertex buffer. */ static const VertexBuffer* g_bound_vertex_buffer; /** Currently programmed vertex buffer. */ static const VertexBuffer* g_programmed_vertex_buffer; private: /** OpenGL id. */ GLuint m_id_data[2]; /** Vertex array. */ Array<Vertex> m_vertices; /** Index array. */ Array<uint16_t> m_indices; private: /** \brief Accessor. * * \return Vertex buffer OpenGL id. */ GLuint getVertexId() const { return m_id_data[0]; } /** \brief Accessor. * * \return Index buffer OpenGL id. */ GLuint getIndexId() const { return m_id_data[1]; } public: /** \brief Accessor. * * \param idx Index of vertex to access. * \return Vertex at given index. */ const Vertex& getVertex(size_t idx) const { return m_vertices[idx]; } public: /** \brief Constructor. */ VertexBuffer(); public: /** \brief Add face to this vertex buffer. * * \param op Index to add. */ void addIndex(uint16_t op) { #if defined(USE_LD) if(g_debug) { std::cout << op << std::endl; } #endif m_indices.add(op); } /** \brief Add vertex to this vertex buffer. * * \param op Vertex to add. */ void addVertex(const Vertex &op) { #if defined(USE_LD) if(g_debug) { std::cout << op << std::endl; } #endif m_vertices.add(op); } /** \brief Tell if amount of vertices fits in this vertex buffer. * * \param op Number of offered vertices. * \return True if fits, false if not. */ bool fitsVertices(size_t op) { return (65536 >= (m_vertices.getSize() + op)); } /** \brief Accessor. * * \return Index count. */ size_t getIndexCount() const { return m_indices.getSize(); } /** \brief Accessor. * * \return Vertex count. */ size_t getVertexCount() const { return m_vertices.getSize(); } private: /** \brief Bind this vertex buffer for rendering and/or modification. */ void bind() const; public: /** \brief Update this vertex buffer into the GPU. * * \param indicesEnabled Set to true (default) if index buffer is relevant and should be uploaded. */ void update(bool indicesEnabled = true); /** \brief Use this vertex buffer for rendering. * * \param op Program to use. */ void use(const Program *op) const; public: /** \brief Reset programmed vertex buffer. * * Must be done when changing a program. */ static void reset_programmed_vertex_buffer() { g_programmed_vertex_buffer = NULL; } /** \brief Unbind vertex buffer. */ static void unbind() { dnload_glBindBuffer(GL_ARRAY_BUFFER, 0); dnload_glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); g_bound_vertex_buffer = NULL; reset_programmed_vertex_buffer(); } #if defined(USE_LD) public: /** \brief Print operator. * * \param lhs Left-hand-side operand. * \param rhs Right-hand-side operand. */ friend std::ostream& operator<<(std::ostream &lhs, const VertexBuffer &rhs) { return lhs << "VertexBuffer(" << &rhs << ')'; } #endif }; #endif
20.067039
102
0.587695
trilkk
fb86376e6ae741650d8de5fa5d2b561ba273006b
821
cpp
C++
src/homework/01_variables/main.cpp
acc-cosc-1337-spring-2021/acc-cosc-1337-spring-2021-derekoko
437f55150491c2b89eb4ef730ac73d55a6ed07a2
[ "MIT" ]
null
null
null
src/homework/01_variables/main.cpp
acc-cosc-1337-spring-2021/acc-cosc-1337-spring-2021-derekoko
437f55150491c2b89eb4ef730ac73d55a6ed07a2
[ "MIT" ]
null
null
null
src/homework/01_variables/main.cpp
acc-cosc-1337-spring-2021/acc-cosc-1337-spring-2021-derekoko
437f55150491c2b89eb4ef730ac73d55a6ed07a2
[ "MIT" ]
null
null
null
//write include statements #include"variables.h" //write namespace using statement for cout using std::cin; using std::cout; /* Call multiply_numbers with 10 and 10 parameter values and display function result */ int main() { double meal_amount; double tip_rate; double tip_amount; double tax_amount; double total; cout<<"Enter your meal amount here: "; cin>>meal_amount; tax_amount = get_sales_tax(meal_amount); cout<<"Enter the percent tip here without the percent sign decimals: "; cin>>tip_rate; tip_amount = get_tip_amount(meal_amount, tip_rate); total = tax_amount + meal_amount + tip_amount; cout<<"\n"<<"Your meal amount is: "<<meal_amount<<"\n"; cout<<"The sales tax is: "<<tax_amount<<"\n"; cout<<"Your tip amount is: "<<tip_amount<<"\n"; cout<<"Your total is: "<<total; return 0; }
22.189189
81
0.713764
acc-cosc-1337-spring-2021
fb8dfdff0a5ce1a0d6951b35bf37fef581793740
3,865
cpp
C++
src/graphics/graphicstool.cpp
quizzmaster/chemkit
803e4688b514008c605cb5c7790f7b36e67b68fc
[ "BSD-3-Clause" ]
34
2015-01-24T23:59:41.000Z
2020-11-12T13:48:01.000Z
src/graphics/graphicstool.cpp
soplwang/chemkit
d62b7912f2d724a05fa8be757f383776fdd5bbcb
[ "BSD-3-Clause" ]
4
2015-12-28T20:29:16.000Z
2016-01-26T06:48:19.000Z
src/graphics/graphicstool.cpp
soplwang/chemkit
d62b7912f2d724a05fa8be757f383776fdd5bbcb
[ "BSD-3-Clause" ]
17
2015-01-23T14:50:24.000Z
2021-06-10T15:43:50.000Z
/****************************************************************************** ** ** Copyright (C) 2009-2011 Kyle Lutz <kyle.r.lutz@gmail.com> ** All rights reserved. ** ** This file is a part of the chemkit project. For more information ** see <http://www.chemkit.org>. ** ** Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions ** are met: ** ** * Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** * Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in the ** documentation and/or other materials provided with the distribution. ** * Neither the name of the chemkit project nor the names of its ** contributors may be used to endorse or promote products derived ** from this software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** ******************************************************************************/ #include "graphicstool.h" #include "graphicsview.h" namespace chemkit { // === GraphicsToolPrivate ================================================= // class GraphicsToolPrivate { public: GraphicsView *view; }; // === GraphicsTool ======================================================== // /// \class GraphicsTool graphicstool.h chemkit/graphicstool.h /// \ingroup chemkit-graphics /// \brief The GraphicsTool class handles graphics events for a /// GraphicsView. // --- Construction and Destruction ---------------------------------------- // /// Creates a new graphics tool. GraphicsTool::GraphicsTool() : d(new GraphicsToolPrivate) { d->view = 0; } /// Destroys the graphics tool. GraphicsTool::~GraphicsTool() { delete d; } // --- Properties ---------------------------------------------------------- // /// Sets the view to \p view. void GraphicsTool::setView(GraphicsView *view) { d->view = view; } /// Returns the view the tool is a part of. Returns \c 0 if the tool /// is not in any view. GraphicsView* GraphicsTool::view() const { return d->view; } // --- Event Handling------------------------------------------------------- // /// Handle a mouse press event. void GraphicsTool::mousePressEvent(QMouseEvent *event) { Q_UNUSED(event); } /// Handle a mouse release event. void GraphicsTool::mouseReleaseEvent(QMouseEvent *event) { Q_UNUSED(event); } /// Handle a mouse double click event. void GraphicsTool::mouseDoubleClickEvent(QMouseEvent *event) { Q_UNUSED(event); } /// Handle a mouse move event. void GraphicsTool::mouseMoveEvent(QMouseEvent *event) { Q_UNUSED(event); } /// Handle a mouse wheel event. void GraphicsTool::wheelEvent(QWheelEvent *event) { Q_UNUSED(event); } /// This method is called when the current tool in the view changes. /// /// \see GraphicsView::setTool() void GraphicsTool::toolChanged(const boost::shared_ptr<GraphicsTool> &tool) { Q_UNUSED(tool); } } // end chemkit namespace
31.422764
79
0.647348
quizzmaster
65201e989d10d77f9dfcfecc527d957232c2fa49
25,386
cpp
C++
ODFAEG/src/odfaeg/Graphics/GUI/filedialog.cpp
Mechap/ODFAEG
ad4bf026ee7055aaf168c5a8e3dc57baaaf42e40
[ "Zlib" ]
null
null
null
ODFAEG/src/odfaeg/Graphics/GUI/filedialog.cpp
Mechap/ODFAEG
ad4bf026ee7055aaf168c5a8e3dc57baaaf42e40
[ "Zlib" ]
1
2020-02-14T14:19:44.000Z
2020-12-04T17:39:17.000Z
ODFAEG/src/odfaeg/Graphics/GUI/filedialog.cpp
Mechap/ODFAEG
ad4bf026ee7055aaf168c5a8e3dc57baaaf42e40
[ "Zlib" ]
2
2021-05-23T13:45:28.000Z
2021-07-24T13:36:13.000Z
#include "../../../../include/odfaeg/Graphics/GUI/filedialog.hpp" #include "../../../../include/odfaeg/Math/maths.h" #include <filesystem> namespace odfaeg { namespace graphic { namespace gui { FileDialog::FileDialog(math::Vec3f position, math::Vec3f size, const Font* font) : rw(sf::VideoMode(size.x, size.y), "File Dialog", sf::Style::Default, window::ContextSettings(0, 0, 0, 3, 0)), LightComponent (rw, position, size, size * 0.5), font(font) { std::cout<<"position : "<<getPosition()<<std::endl; rw.setPosition(sf::Vector2i(position.x, position.y)); pTop = new Panel (rw, position, size); pBottom = new Panel (rw, position, size); pDirectories = new Panel (rw, position, size); pFiles = new Panel (rw, position, size); lTop = new Label (rw, position, size, font, "", 15); bChoose = new Button (position, size, font, "Choose", 15, rw); bCancel = new Button (position, size, font, "Cancel", 15, rw); pTop->setRelPosition(0.f, 0.f); pTop->setRelSize(1.f, 0.1f); pDirectories->setRelPosition(0.f, 0.1f); pDirectories->setRelSize(0.5f, 0.8f); pFiles->setRelPosition(0.5f, 0.1f); pFiles->setRelSize(0.5f, 0.8f); pBottom->setRelPosition(0.f, 0.9f); pBottom->setRelSize(1.f, 0.1f); pTop->setParent(this); pBottom->setParent(this); pDirectories->setParent(this); pFiles->setParent(this); addChild(pTop); addChild(pBottom); addChild(pDirectories); addChild(pFiles); lTop->setParent(pTop); bChoose->setParent(pBottom); bCancel->setParent(pBottom); bChoose->addActionListener(this); bCancel->addActionListener(this); std::string currentPath = std::filesystem::current_path(); lTop->setRelPosition(0.f, 0.f); lTop->setRelSize(1.f, 1.f); lTop->setForegroundColor(sf::Color::Black); pTop->addChild(lTop); lTop->setText(currentPath); lTop->setBackgroundColor(sf::Color::Red); appliDir = lTop->getText(); std::string textDir; #if defined (ODFAEG_SYSTEM_LINUX) if (DIR* root = opendir("/")) { dirent* ent; unsigned int i = 0; while((ent = readdir(root)) != NULL) { if (strcmp(ent->d_name, ".") && strcmp(ent->d_name, "..")) { textDir = std::string(ent->d_name); Label* lDirectory = new Label(rw, position, size, font, "",15); //lDirectory->setBackgroundColor(sf::Color(math::Math::random(0, 255),math::Math::random(0, 255), math::Math::random(0, 255), 255)); lDirectory->setParent(pDirectories); lDirectory->setRelPosition(0.f, 0.04f * i); lDirectory->setRelSize(1, 0.04f); pDirectories->addChild(lDirectory); lDirectory->setText(sf::String(textDir)); core::Action a (core::Action::EVENT_TYPE::MOUSE_BUTTON_PRESSED_ONCE, window::IMouse::Left); core::Command cmd (a, core::FastDelegate<bool>(&Label::isMouseInside, lDirectory), core::FastDelegate<void>(&FileDialog::onDirSelected, this, lDirectory)); if(ent->d_type == DT_DIR) { lDirectory->setForegroundColor(sf::Color::Red); getListener().connect("1d"+textDir, cmd); } else { getListener().connect("1f"+textDir, cmd); } i++; } } } currentPath = lTop->getText(); if (DIR* current = opendir(currentPath.c_str())) { dirent *ent; std::string fileNames; unsigned int i = 0; while ((ent = readdir(current)) != NULL) { if (strcmp(ent->d_name, ".") && strcmp(ent->d_name, "..")) { fileNames = std::string(ent->d_name); Label* lFile = new Label(rw, position, size, font, "",15); //lFile->setBackgroundColor(sf::Color(math::Math::random(0, 255),math::Math::random(0, 255), math::Math::random(0, 255), 255)); lFile->setParent(pFiles); lFile->setRelPosition(0.f, 0.04f * i); lFile->setRelSize(1.f, 0.04f); pFiles->addChild(lFile); lFile->setText(sf::String(fileNames)); core::Action a (core::Action::EVENT_TYPE::MOUSE_BUTTON_PRESSED_ONCE, window::IMouse::Left); core::Command cmd (a, core::FastDelegate<bool>(&Label::isMouseInside, lFile), core::FastDelegate<void>(&FileDialog::onFileSelected, this, lFile)); if(ent->d_type == DT_DIR) { lFile->setForegroundColor(sf::Color::Red); getListener().connect("2d"+fileNames, cmd); } else { getListener().connect("2f"+fileNames, cmd); } i++; } } } #else if defined(ODFAEG_SYSTEM_WINDOWS) if (DIR* root = opendir("C:\\")) { dirent* ent; struct stat st; unsigned int i = 0; while((ent = readdir(root)) != NULL) { if (strcmp(ent->d_name, ".") && strcmp(ent->d_name, "..")) { textDir = std::string(ent->d_name); std::string fullPath = "C:\\" + textDir; stat(fullPath.c_str(), &st); Label* lDirectory = new Label(rw, position, size, font, "",15); //lDirectory->setBackgroundColor(sf::Color(math::Math::random(0, 255),math::Math::random(0, 255), math::Math::random(0, 255), 255)); lDirectory->setParent(pDirectories); lDirectory->setRelPosition(0.f, 0.04f * i); lDirectory->setRelSize(1, 0.04f); pDirectories->addChild(lDirectory); lDirectory->setText(textDir); core::Action a (core::Action::EVENT_TYPE::MOUSE_BUTTON_PRESSED_ONCE, window::IMouse::Left); core::Command cmd (a, core::FastDelegate<bool>(&Label::isMouseInside, lDirectory), core::FastDelegate<void>(&FileDialog::onDirSelected, this, lDirectory)); if(S_ISDIR(st.st_mode)) { lDirectory->setForegroundColor(sf::Color::Red); getListener().connect("1d"+textDir, cmd); } else { lDirectory->setForegroundColor(sf::Color::Black); getListener().connect("1f"+textDir, cmd); } i++; } } } currentPath = lTop->getText(); if (DIR* current = opendir(currentPath.c_str())) { dirent *ent; struct stat st; std::string fileNames; unsigned int i = 0; while ((ent = readdir(current)) != NULL) { if (strcmp(ent->d_name, ".") && strcmp(ent->d_name, "..")) { fileNames = std::string(ent->d_name); stat(fileNames.c_str(), &st); Label* lFile = new Label(rw, position, size, font, "",15); //lFile->setBackgroundColor(sf::Color(math::Math::random(0, 255),math::Math::random(0, 255), math::Math::random(0, 255), 255)); lFile->setParent(pFiles); lFile->setRelPosition(0.f, 0.04f * i); lFile->setRelSize(1.f, 0.04f); pFiles->addChild(lFile); lFile->setText(fileNames); core::Action a (core::Action::EVENT_TYPE::MOUSE_BUTTON_PRESSED_ONCE, window::IMouse::Left); core::Command cmd (a, core::FastDelegate<bool>(&Label::isMouseInside, lFile), core::FastDelegate<void>(&FileDialog::onFileSelected, this, lFile)); if(S_ISDIR(st.st_mode)) { lFile->setForegroundColor(sf::Color::Red); getListener().connect("2d"+fileNames, cmd); } else { lFile->setForegroundColor(sf::Color::Black); getListener().connect("2f"+fileNames, cmd); } i++; } } } #endif bChoose->setRelPosition(0.7f, 0.1f); bChoose->setRelSize(0.1f, 0.8f); bChoose->setParent(pBottom); pBottom->addChild(bChoose); bCancel->setRelPosition(0.85f, 0.1f); bCancel->setRelSize(0.1f, 0.8f); bCancel->setParent(pBottom); pBottom->addChild(bCancel); setRelPosition(0, 0); setRelSize(1, 1); setAutoResized(true); } void FileDialog::clear() { rw.clear(); pTop->clear(); pBottom->clear(); pDirectories->clear(); pFiles->clear(); } void FileDialog::onDraw(RenderTarget& target, RenderStates states) { //if (rw.isOpen()) { target.draw(*pTop, states); target.draw(*pDirectories, states); target.draw(*pFiles, states); target.draw(*pBottom, states); //} } void FileDialog::onDirSelected(Label* label) { for (unsigned int i = 0; i < pFiles->getChildren().size(); i++) { if (static_cast<Label*>(pFiles->getChildren()[i])->getForegroundColor() == sf::Color::Red) { getListener().removeCommand("2d"+static_cast<Label*>(pFiles->getChildren()[i])->getText()); } else { getListener().removeCommand("2f"+static_cast<Label*>(pFiles->getChildren()[i])->getText()); } } pFiles->removeAll(); for (unsigned int i = 0; i < pDirectories->getChildren().size(); i++) { static_cast<Label*>(pDirectories->getChildren()[i])->setBackgroundColor(sf::Color::Black); } std::string dirName; #if defined (ODFAEG_SYSTEM_LINUX) dirName = "/" + label->getText(); #else if defined (ODFAEG_SYSTEM_WINDOWS) dirName = "C:\\" + label->getText(); #endif // if std::string currentDir = dirName; lTop->setText(currentDir); label->setBackgroundColor(sf::Color::Blue); if (label->getForegroundColor() == sf::Color::Red) { #if defined (ODFAEG_SYSTEM_LINUX) if (DIR* current = opendir(dirName.c_str())) { dirent *ent; std::string fileNames; unsigned int i = 0; while ((ent = readdir(current)) != NULL) { if (strcmp(ent->d_name, ".") && strcmp(ent->d_name, "..")) { fileNames = std::string(ent->d_name); Label* lFile = new Label(rw, getPosition(), getSize(), font, "",15); //lFile->setBackgroundColor(sf::Color(math::Math::random(0, 255),math::Math::random(0, 255), math::Math::random(0, 255), 255)); lFile->setParent(pFiles); lFile->setRelPosition(0.f, 0.04f * i); lFile->setRelSize(1.f, 0.04f); pFiles->addChild(lFile); lFile->setText(fileNames); core::Action a (core::Action::EVENT_TYPE::MOUSE_BUTTON_PRESSED_ONCE, window::IMouse::Left); core::Command cmd (a, core::FastDelegate<bool>(&Label::isMouseInside, lFile), core::FastDelegate<void>(&FileDialog::onFileSelected, this, lFile)); if(ent->d_type == DT_DIR) { lFile->setForegroundColor(sf::Color::Red); getListener().connect("2d"+fileNames, cmd); } else { getListener().connect("2f"+fileNames, cmd); } i++; } } closedir(current); } #else if defined (ODFAEG_SYSTEM_WINDOWS) if (DIR* current = opendir(dirName.c_str())) { dirent *ent; struct stat st; std::string fileNames; unsigned int i = 0; while ((ent = readdir(current)) != NULL) { if (strcmp(ent->d_name, ".") && strcmp(ent->d_name, "..")) { fileNames = std::string(ent->d_name); std::string fullPath = currentDir + "\\" + fileNames; stat(fullPath.c_str(), &st); Label* lFile = new Label(rw, getPosition(), getSize(), font, "",15); //lFile->setBackgroundColor(sf::Color(math::Math::random(0, 255),math::Math::random(0, 255), math::Math::random(0, 255), 255)); lFile->setParent(pFiles); lFile->setRelPosition(0.f, 0.04f * i); lFile->setRelSize(1.f, 0.04f); lFile->setName("LFILE"); pFiles->addChild(lFile); lFile->setText(fileNames); core::Action a (core::Action::EVENT_TYPE::MOUSE_BUTTON_PRESSED_ONCE, window::IMouse::Left); core::Command cmd (a, core::FastDelegate<bool>(&Label::isMouseInside, lFile), core::FastDelegate<void>(&FileDialog::onFileSelected, this, lFile)); if(S_ISDIR(st.st_mode)) { lFile->setForegroundColor(sf::Color::Red); getListener().connect("2d"+fileNames, cmd); } else { lFile->setForegroundColor(sf::Color::Black); getListener().connect("2f"+fileNames, cmd); } i++; } } closedir(current); } #endif } setAutoResized(true); } void FileDialog::onFileSelected(Label* label) { std::string fileName = label->getText(); sf::Color color = label->getForegroundColor(); if (color == sf::Color::Red) { for (unsigned int i = 0; i < pFiles->getChildren().size(); i++) { if (static_cast<Label*>(pFiles->getChildren()[i])->getForegroundColor() == sf::Color::Red) { if (static_cast<Label*>(pFiles->getChildren()[i])->getText() == label->getText()) getListener().removeLater("2d"+static_cast<Label*>(pFiles->getChildren()[i])->getText()); else getListener().removeCommand("2d"+static_cast<Label*>(pFiles->getChildren()[i])->getText()); } else { if (static_cast<Label*>(pFiles->getChildren()[i])->getText() == label->getText()) getListener().removeLater("2f"+static_cast<Label*>(pFiles->getChildren()[i])->getText()); else getListener().removeCommand("2f"+static_cast<Label*>(pFiles->getChildren()[i])->getText()); } } pFiles->removeAll(); std::string currentDir = lTop->getText(); #if defined (ODFAEG_SYSTEM_LINUX) currentDir += "/"+fileName; #else if defined (ODFAEG_SYSTEM_WINDOWS) currentDir += "\\"+fileName; #endif // if lTop->setText(currentDir); #if defined (ODFAEG_SYSTEM_LINUX) if (DIR* current = opendir(currentDir.c_str())) { dirent *ent; std::string fileNames; unsigned int i = 0; while ((ent = readdir(current)) != NULL) { if (strcmp(ent->d_name, ".") && strcmp(ent->d_name, "..")) { fileNames = std::string(ent->d_name); Label* lFile = new Label(rw, getPosition(), getSize(), font, "",15); //lFile->setBackgroundColor(sf::Color(math::Math::random(0, 255),math::Math::random(0, 255), math::Math::random(0, 255), 255)); lFile->setParent(pFiles); lFile->setRelPosition(0.f, 0.04f * i); lFile->setRelSize(1.f, 0.04f); pFiles->addChild(lFile); lFile->setText(fileNames); core::Action a (core::Action::EVENT_TYPE::MOUSE_BUTTON_PRESSED_ONCE, window::IMouse::Left); core::Command cmd (a, core::FastDelegate<bool>(&Label::isMouseInside, lFile), core::FastDelegate<void>(&FileDialog::onFileSelected, this, lFile)); if(ent->d_type == DT_DIR) { lFile->setForegroundColor(sf::Color::Red); getListener().connect("2d"+fileNames, cmd); } else { getListener().connect("2f"+fileNames, cmd); } i++; } } closedir(current); } #else if defined (ODFAEG_SYSTEM_WINDOWS) if (DIR* current = opendir(currentDir.c_str())) { dirent *ent; struct stat st; std::string fileNames; unsigned int i = 0; while ((ent = readdir(current)) != NULL) { if (strcmp(ent->d_name, ".") && strcmp(ent->d_name, "..")) { fileNames = std::string(ent->d_name); std::string fullPath = currentDir + "\\" + fileNames; stat(fullPath.c_str(), &st); Label* lFile = new Label(rw, getPosition(), getSize(), font, "",15); //lFile->setBackgroundColor(sf::Color(math::Math::random(0, 255),math::Math::random(0, 255), math::Math::random(0, 255), 255)); lFile->setParent(pFiles); lFile->setRelPosition(0.f, 0.04f * i); lFile->setRelSize(1.f, 0.04f); pFiles->addChild(lFile); lFile->setText(fileNames); lFile->setName("LFILE"); core::Action a (core::Action::EVENT_TYPE::MOUSE_BUTTON_PRESSED_ONCE, window::IMouse::Left); core::Command cmd (a, core::FastDelegate<bool>(&Label::isMouseInside, lFile), core::FastDelegate<void>(&FileDialog::onFileSelected, this, lFile)); if(S_ISDIR(st.st_mode)) { lFile->setForegroundColor(sf::Color::Red); getListener().connect("2d"+fileNames, cmd); } else { lFile->setForegroundColor(sf::Color::Black); getListener().connect("2f"+fileNames, cmd); } i++; } } closedir(current); } #endif } else { for (unsigned int i = 0; i < pFiles->getChildren().size(); i++) { static_cast<Label*>(pFiles->getChildren()[i])->setBackgroundColor(sf::Color::Black); } label->setBackgroundColor(sf::Color::Blue); } setAutoResized(true); } std::string FileDialog::getPathChosen() { std::string path = pathChosen; pathChosen = ""; return path; } std::string FileDialog::getAppiDir() { return appliDir; } void FileDialog::onEventPushed(window::IEvent event, RenderWindow& window) { if (event.type == window::IEvent::WINDOW_EVENT && event.mouseButton.type == window::IEvent::WINDOW_EVENT_CLOSED) { rw.setVisible(false); } /*for (unsigned int i = 0; i < pDirectories.getChildren().size(); i++) { pDirectories.getChildren()[i]->onUpdate(&getWindow(), event); } for (unsigned int i = 0; i < pFiles.getChildren().size(); i++) { pFiles.getChildren()[i]->onUpdate(&getWindow(), event); } bChoose.onUpdate(&getWindow(), event); bCancel.onUpdate(&getWindow(), event); getListener().pushEvent(event); bChoose.getListener().pushEvent(event); bCancel.getListener().pushEvent(event);*/ } void FileDialog::onVisibilityChanged(bool visible) { rw.setVisible(visible); } void FileDialog::actionPerformed(Button* button) { if (button->getText() == "Choose") { for (unsigned int i = 0; i < pDirectories->getChildren().size(); i++) { Label* label = static_cast<Label*>(pDirectories->getChildren()[i]); if (label->getForegroundColor() == sf::Color::Black && label->getBackgroundColor() == sf::Color::Blue) { pathChosen = lTop->getText(); return; } } for (unsigned int i = 0; i < pFiles->getChildren().size(); i++) { Label* label = static_cast<Label*>(pFiles->getChildren()[i]); if (label->getForegroundColor() == sf::Color::Black && label->getBackgroundColor() == sf::Color::Blue) { #if defined (ODFAEG_SYSTEM_LINUX) pathChosen = lTop->getText()+"/"+label->getText(); #else if defined (ODFAEG_SYSTEM_WINDOWS) pathChosen = lTop->getText()+"\\"+label->getText(); #endif // if } } } else if (button->getText() == "Cancel") { rw.setVisible(false); } } } } }
59.174825
183
0.430986
Mechap
65268449db5d310967a2853f69e9940460ebe922
1,271
cpp
C++
Mragpp/Paths.cpp
codecat/MragPP
96c1c5474ea552f364e6c04da7cc72923fdade0a
[ "MIT" ]
1
2017-06-26T20:44:44.000Z
2017-06-26T20:44:44.000Z
Mragpp/Paths.cpp
codecat/MragPP
96c1c5474ea552f364e6c04da7cc72923fdade0a
[ "MIT" ]
null
null
null
Mragpp/Paths.cpp
codecat/MragPP
96c1c5474ea552f364e6c04da7cc72923fdade0a
[ "MIT" ]
null
null
null
#include "StdH.h" #include "Paths.h" MRAGPP_NAMESPACE_BEGIN; CPaths::CPaths() { ps_iIterator = 0; } CPaths::~CPaths() { ps_aPaths.Clear(); } CPath& CPaths::Create(const Vector2f &vPos1, const Vector2f &vPos2, int iTotalFrameCount, mragPathsOnUpdateFunction onUpdate, mragPathsOnFinishFunction onFinish) { CPath &newPath = ps_aPaths.Push(); newPath.p_pPaths = this; newPath.p_vPos1 = vPos1; newPath.p_vPos2 = vPos2; newPath.p_iTotalFrameCount = iTotalFrameCount; newPath.p_pOnUpdate = onUpdate; newPath.p_pOnFinish = onFinish; return newPath; } CPath& CPaths::Create(const Vector2f &vPos1, const Vector2f &vPos2, float fSeconds, mragPathsOnUpdateFunction onUpdate, mragPathsOnFinishFunction onFinish) { return Create(vPos1, vPos2, (int)ceil(fSeconds / 0.0166667f), onUpdate, onFinish); } void CPaths::Update() { for(int i=0; i<ps_aPaths.Count(); i++) { ps_aPaths[i].p_bReady = true; } for(ps_iIterator=0; ps_iIterator<ps_aPaths.Count(); ps_iIterator++) { if(!ps_aPaths[ps_iIterator].p_bReady) { continue; } ps_aPaths[ps_iIterator].Update(); } } void CPaths::Render() { for(ps_iIterator=0; ps_iIterator<ps_aPaths.Count(); ps_iIterator++) { ps_aPaths[ps_iIterator].Render(); } } MRAGPP_NAMESPACE_END;
22.298246
89
0.721479
codecat
65292232ffd58a136fbded3f7dca65106452dc4d
5,051
cpp
C++
src/nao_speech.cpp
sheosi/nao_auto_bridge
d5593219abacc56684c537f042d24ef89fcc94d3
[ "BSD-3-Clause" ]
null
null
null
src/nao_speech.cpp
sheosi/nao_auto_bridge
d5593219abacc56684c537f042d24ef89fcc94d3
[ "BSD-3-Clause" ]
null
null
null
src/nao_speech.cpp
sheosi/nao_auto_bridge
d5593219abacc56684c537f042d24ef89fcc94d3
[ "BSD-3-Clause" ]
null
null
null
#include "nao_auto_bridge.h" #include <boost/algorithm/string/join.hpp> #include <iostream> #include <vector> #include <ros/ros.h> #include <actionlib/server/simple_action_server.h> #include <naoqi_bridge_msgs/SpeechWithFeedbackAction.h> #include <naoqi_bridge_msgs/SetSpeechVocabularyAction.h> #include <naoqi_bridge_msgs/WordRecognized.h> #include <std_msgs/String.h> #include <std_srvs/Empty.h> using std::string; void SimulatedNao::OnSpeechActionGoal(const string& text) { //Note: We could replicate behaviour ROS_INFO("Nao said: %s", text.c_str()); } void SimulatedNao::OnSpeechVocabularyAction(const std::vector<string>& words) { //Note: We could replicate behaviour const string joined = boost::algorithm::join(words, ","); ROS_INFO("Words recognized set: %s", joined.c_str()); } void SimulatedNao::OnSpeech(const string& text) { //Note: We could replicate behaviour ROS_INFO("Nao said: %s", text.c_str()); } void SimulatedNao::OnReconfigure() { //Note: We could replicate behaviour ROS_INFO("Speech reconfigured"); } void SimulatedNao::OnStartRecognition() { //Note: We could replicate behaviour if (!this->speech_data.recognition_started) { ROS_INFO("Recognition started"); this->speech_data.recognition_started = true; } else { ROS_INFO("Tried to start recognition, but it was already started by another node"); } } void SimulatedNao::OnStopRecognition() { //Note: We could replicate behaviour if (this->speech_data.recognition_started) { ROS_INFO("Recognition stopped"); this->speech_data.recognition_started = false; } else { ROS_INFO("Tried top stop recognition, but it is already stopped"); } } namespace BridgeNaoSpeech { std::unique_ptr<actionlib::SimpleActionServer<naoqi_bridge_msgs::SpeechWithFeedbackAction>> act_srv_speech_action_goal; std::unique_ptr<actionlib::SimpleActionServer<naoqi_bridge_msgs::SetSpeechVocabularyAction>> act_srv_speech_vocabulary_action; ros::Subscriber sub_speech; ros::ServiceServer srv_reconfigure, srv_start_recognition, srv_stop_recognition; void on_speech_action_goal( const naoqi_bridge_msgs::SpeechWithFeedbackGoalConstPtr &goal ) { nao_connection.OnSpeechActionGoal(goal->say); naoqi_bridge_msgs::SpeechWithFeedbackResult result; act_srv_speech_action_goal->setSucceeded(result); } void on_speech_vocabulary_action( const naoqi_bridge_msgs::SetSpeechVocabularyGoalConstPtr &goal ) { nao_connection.OnSpeechVocabularyAction(goal->words); naoqi_bridge_msgs::SetSpeechVocabularyResult result; act_srv_speech_vocabulary_action->setSucceeded(result); } void on_speech( const std_msgs::StringConstPtr &msg ) { nao_connection.OnSpeech(msg->data); } bool on_reconfigure( std_srvs::Empty::Request &req, std_srvs::Empty::Response &resp ){ nao_connection.OnReconfigure(); return true; } bool on_start_recognition( std_srvs::Empty::Request &req, std_srvs::Empty::Response &resp ){ nao_connection.OnStartRecognition(); return true; } bool on_stop_recognition( std_srvs::Empty::Request &req, std_srvs::Empty::Response &resp ){ nao_connection.OnStopRecognition(); return true; } void init(ros::NodeHandle &n) { std::string voice, language; float volume; std::vector<std::string> vocabulary; bool enable_audio_expression, enable_visual_expression, word_spoting; n.param("voice", voice, std::string("")); n.param("language", language, std::string("")); n.param("volume", volume, 0.0f); n.param("vocabulary", vocabulary, std::vector<std::string>()); n.param("enable_audio_expression", enable_audio_expression, false); n.param("enable_visual_expression", enable_visual_expression, false); n.param("word_spoting", word_spoting, false); act_srv_speech_action_goal = std::unique_ptr<actionlib::SimpleActionServer<naoqi_bridge_msgs::SpeechWithFeedbackAction>>( new actionlib::SimpleActionServer<naoqi_bridge_msgs::SpeechWithFeedbackAction>(n, "speech_action/goal", on_speech_action_goal, true)); act_srv_speech_vocabulary_action = std::unique_ptr<actionlib::SimpleActionServer<naoqi_bridge_msgs::SetSpeechVocabularyAction>>( new actionlib::SimpleActionServer<naoqi_bridge_msgs::SetSpeechVocabularyAction>(n, "/speech_vocabulary_action/goal", on_speech_vocabulary_action, true)); sub_speech = n.subscribe("speech", 1000, on_speech); srv_reconfigure = n.advertiseService("reconfigure", on_reconfigure); srv_start_recognition = n.advertiseService("start_recognition", on_start_recognition); srv_stop_recognition = n.advertiseService("stop_recognition", on_stop_recognition); } }
35.076389
165
0.703623
sheosi
652d3e39002c919df906a77e8bbecd68705eaaa1
141,050
cpp
C++
src/editor.cpp
TijmenUU/VVVVVV
ce6c07c800f3dce98e0bd40f32311b98a01a4cd6
[ "RSA-MD" ]
null
null
null
src/editor.cpp
TijmenUU/VVVVVV
ce6c07c800f3dce98e0bd40f32311b98a01a4cd6
[ "RSA-MD" ]
null
null
null
src/editor.cpp
TijmenUU/VVVVVV
ce6c07c800f3dce98e0bd40f32311b98a01a4cd6
[ "RSA-MD" ]
null
null
null
#include <Entity.hpp> #include <Graphics.hpp> #include <KeyPoll.hpp> #include <Map.hpp> #include <Music.hpp> #include <Script.hpp> #include <editor.hpp> //#include "UtilityClass.h" #include <Enums.hpp> #include <FileSystemUtils.hpp> #include <ctime> #include <string> #include <tinyxml/tinyxml.hpp> edlevelclass::edlevelclass() { tileset = 0; tilecol = 0; roomname = ""; warpdir = 0; platx1 = 0; platy1 = 0; platx2 = 320; platy2 = 240; platv = 4; enemyx1 = 0; enemyy1 = 0; enemyx2 = 320; enemyy2 = 240; enemytype = 0; directmode = 0; } editorclass::editorclass() { maxwidth = 20; maxheight = 20; //We create a blank map for(int j = 0; j < 30 * maxwidth; j++) { for(int i = 0; i < 40 * maxheight; i++) { contents.push_back(0); } } for(int j = 0; j < 30; j++) { for(int i = 0; i < 40; i++) { swapmap.push_back(0); } } for(int i = 0; i < 30 * maxheight; i++) { vmult.push_back(int(i * 40 * maxwidth)); } reset(); } // comparison, not case sensitive. bool compare_nocase(std::string first, std::string second) { unsigned int i = 0; while((i < first.length()) && (i < second.length())) { if(tolower(first[i]) < tolower(second[i])) return true; else if(tolower(first[i]) > tolower(second[i])) return false; ++i; } if(first.length() < second.length()) return true; else return false; } void editorclass::getDirectoryData() { ListOfMetaData.clear(); directoryList.clear(); directoryList = FILESYSTEM_getLevelDirFileNames(); for(size_t i = 0; i < directoryList.size(); i++) { LevelMetaData temp; if(getLevelMetaData(directoryList[i], temp)) { ListOfMetaData.push_back(temp); } } for(size_t i = 0; i < ListOfMetaData.size(); i++) { for(size_t k = 0; k < ListOfMetaData.size(); k++) { if(compare_nocase(ListOfMetaData[i].title, ListOfMetaData[k].title)) { std::swap(ListOfMetaData[i], ListOfMetaData[k]); std::swap(directoryList[i], directoryList[k]); } } } } bool editorclass::getLevelMetaData(std::string & _path, LevelMetaData & _data) { unsigned char * mem = NULL; FILESYSTEM_loadFileToMemory(_path.c_str(), &mem, NULL); if(mem == NULL) { printf("Level %s not found :(\n", _path.c_str()); return false; } TiXmlDocument doc; doc.Parse((const char *)mem); FILESYSTEM_freeMemory(&mem); TiXmlHandle hDoc(&doc); TiXmlElement * pElem; TiXmlHandle hRoot(0); { pElem = hDoc.FirstChildElement().Element(); // should always have a valid root but handle gracefully if it does if(!pElem) { printf("No valid root! Corrupt level file?\n"); } // save this for later hRoot = TiXmlHandle(pElem); } for(pElem = hRoot.FirstChild("Data").FirstChild().Element(); pElem; pElem = pElem->NextSiblingElement()) { std::string pKey(pElem->Value()); const char * pText = pElem->GetText(); if(pText == NULL) { pText = ""; } if(pKey == "MetaData") { for(TiXmlElement * subElem = pElem->FirstChildElement(); subElem; subElem = subElem->NextSiblingElement()) { std::string pKey(subElem->Value()); const char * pText = subElem->GetText(); if(pText == NULL) { pText = ""; } _data.filename = _path; if(pKey == "Created") { _data.timeCreated = pText; } if(pKey == "Creator") { _data.creator = pText; } if(pKey == "Title") { _data.title = pText; } if(pKey == "Modified") { _data.timeModified = pText; } if(pKey == "Modifiers") { _data.modifier = pText; } if(pKey == "Desc1") { _data.Desc1 = pText; } if(pKey == "Desc2") { _data.Desc2 = pText; } if(pKey == "Desc3") { _data.Desc3 = pText; } if(pKey == "website") { _data.website = pText; } } } } return (_data.filename != ""); } void editorclass::reset() { version = 2; //New smaller format change is 2 mapwidth = 5; mapheight = 5; EditorData::GetInstance().title = "Untitled Level"; EditorData::GetInstance().creator = "Unknown"; Desc1 = ""; Desc2 = ""; Desc3 = ""; website = ""; roomnamehide = 0; zmod = false; xmod = false; spacemod = false; spacemenu = 0; shiftmenu = false; shiftkey = false; saveandquit = false; note = ""; notedelay = 0; roomnamemod = false; textentry = false; savemod = false; loadmod = false; deletekeyheld = false; titlemod = false; creatormod = false; desc1mod = false; desc2mod = false; desc3mod = false; websitemod = false; settingsmod = false; warpmod = false; //Two step process warpent = -1; boundarymod = 0; boundarytype = 0; boundx1 = 0; boundx2 = 0; boundy1 = 0; boundy2 = 0; scripttextmod = false; scripttextent = 0; scripttexttype = 0; drawmode = 0; dmtile = 0; dmtileeditor = 0; entcol = 0; tilex = 0; tiley = 0; levx = 0; levy = 0; keydelay = 0; lclickdelay = 0; savekey = false; loadkey = false; updatetiles = true; changeroom = true; levmusic = 0; entframe = 0; entframedelay = 0; numtrinkets = 0; numcrewmates = 0; EditorData::GetInstance().numedentities = 0; levmusic = 0; roomtextmod = false; roomtextent = 0; for(int j = 0; j < maxheight; j++) { for(int i = 0; i < maxwidth; i++) { level[i + (j * maxwidth)].tileset = 0; level[i + (j * maxwidth)].tilecol = (i + j) % 32; level[i + (j * maxwidth)].roomname = ""; level[i + (j * maxwidth)].warpdir = 0; level[i + (j * maxwidth)].platx1 = 0; level[i + (j * maxwidth)].platy1 = 0; level[i + (j * maxwidth)].platx2 = 320; level[i + (j * maxwidth)].platy2 = 240; level[i + (j * maxwidth)].platv = 4; level[i + (j * maxwidth)].enemyx1 = 0; level[i + (j * maxwidth)].enemyy1 = 0; level[i + (j * maxwidth)].enemyx2 = 320; level[i + (j * maxwidth)].enemyy2 = 240; } } for(int j = 0; j < 30 * maxwidth; j++) { for(int i = 0; i < 40 * maxheight; i++) { contents[i + (j * 30 * maxwidth)] = 0; } } if(numhooks > 0) { for(int i = 0; i < numhooks; i++) { removehook(hooklist[i]); } } for(int i = 0; i < 500; i++) { sb[i] = ""; } for(int i = 0; i < 500; i++) { hooklist[i] = ""; } clearscriptbuffer(); sblength = 1; sbx = 0; sby = 0; pagey = 0; scripteditmod = false; sbscript = "null"; scripthelppage = 0; scripthelppagedelay = 0; hookmenupage = 0; hookmenu = 0; numhooks = 0; script.customscript.clear(); } void editorclass::weirdloadthing(std::string t) { //Stupid pointless function because I hate C++ and everything to do with it //It's even stupider now that I don't need to append .vvvvvv anymore! bah, whatever //t=t+".vvvvvv"; load(t); } void editorclass::gethooks() { //Scan through the script and create a hooks list based on it numhooks = 0; std::string tstring; std::string tstring2; for(size_t i = 0; i < script.customscript.size(); i++) { tstring = script.customscript[i]; if((int)tstring.length() - 1 >= 0) // FIXME: This is sketchy. -flibit { tstring = tstring[tstring.length() - 1]; } else { tstring = ""; } if(tstring == ":") { tstring2 = ""; tstring = script.customscript[i]; for(size_t j = 0; j < tstring.length() - 1; j++) { tstring2 += tstring[j]; } hooklist[numhooks] = tstring2; numhooks++; } } } void editorclass::loadhookineditor(std::string t) { //Find hook t in the scriptclass, then load it into the editor clearscriptbuffer(); std::string tstring; bool removemode = false; for(size_t i = 0; i < script.customscript.size(); i++) { if(script.customscript[i] == t + ":") { removemode = true; } else if(removemode) { tstring = script.customscript[i]; if(tstring != "") { tstring = tstring[tstring.length() - 1]; } if(tstring == ":") { //this is a hook removemode = false; } else { //load in this line sb[sblength - 1] = script.customscript[i]; sblength++; } } } if(sblength > 1) sblength--; } void editorclass::addhooktoscript(std::string t) { //Adds hook+the scriptbuffer to the end of the scriptclass removehookfromscript(t); script.customscript.push_back(t + ":"); if(sblength >= 1) { for(int i = 0; i < sblength; i++) { script.customscript.push_back(sb[i]); } } } void editorclass::removehookfromscript(std::string t) { //Find hook t in the scriptclass, then removes it (and any other code with it) std::string tstring; bool removemode = false; for(size_t i = 0; i < script.customscript.size(); i++) { if(script.customscript[i] == t + ":") { removemode = true; //Remove this line for(size_t j = i; j < script.customscript.size() - 1; j++) { script.customscript[j] = script.customscript[j + 1]; } script.customscript.pop_back(); i--; } else if(removemode) { //If this line is not the start of a new hook, remove it! tstring = script.customscript[i]; tstring = tstring[tstring.length() - 1]; if(tstring == ":") { //this is a hook removemode = false; } else { //Remove this line for(size_t j = i; j < script.customscript.size() - 1; j++) { script.customscript[j] = script.customscript[j + 1]; } script.customscript.pop_back(); i--; } } } } void editorclass::removehook(std::string t) { //Check the hooklist for the hook t. If it's there, remove it from here and the script for(int i = 0; i < numhooks; i++) { if(hooklist[i] == t) { removehookfromscript(t); for(int j = i; j < numhooks; j++) { hooklist[j] = hooklist[j + 1]; } hooklist[numhooks] = ""; numhooks--; i--; } } } void editorclass::addhook(std::string t) { //Add an empty function to the list in both editor and script removehook(t); hooklist[numhooks] = t; numhooks++; addhooktoscript(t); } bool editorclass::checkhook(std::string t) { //returns true if hook t already is in the list for(int i = 0; i < numhooks; i++) { if(hooklist[i] == t) return true; } return false; } void editorclass::clearscriptbuffer() { for(int i = 0; i < sblength + 1; i++) { sb[i] = ""; } sblength = 1; } void editorclass::removeline(int t) { //Remove line t from the script if(sblength > 0) { if(sblength == t) { sblength--; } else { for(int i = t; i < sblength; i++) { sb[i] = sb[i + 1]; } sb[sblength] = ""; sblength--; } } } void editorclass::insertline(int t) { //insert a blank line into script at line t for(int i = sblength; i >= t; i--) { sb[i + 1] = sb[i]; } sb[t] = ""; sblength++; } void editorclass::loadlevel(int rxi, int ryi) { //Set up our buffer array to be picked up by mapclass rxi -= 100; ryi -= 100; if(rxi < 0) rxi += mapwidth; if(ryi < 0) ryi += mapheight; if(rxi >= mapwidth) rxi -= mapwidth; if(ryi >= mapheight) ryi -= mapheight; for(int j = 0; j < 30; j++) { for(int i = 0; i < 40; i++) { swapmap[i + (j * 40)] = contents[i + (rxi * 40) + vmult[j + (ryi * 30)]]; } } } int editorclass::getlevelcol(int t) { if(level[t].tileset == 0) //Space Station { return level[t].tilecol; } else if(level[t].tileset == 1) //Outside { return 32 + level[t].tilecol; } else if(level[t].tileset == 2) //Lab { return 40 + level[t].tilecol; } else if(level[t].tileset == 3) //Warp Zone { return 46 + level[t].tilecol; } else if(level[t].tileset == 4) //Ship { return 52 + level[t].tilecol; } return 0; } int editorclass::getenemycol(int t) { switch(t) { //RED case 3: case 7: case 12: case 23: case 28: case 34: case 42: case 48: case 58: return 6; break; //GREEN case 5: case 9: case 22: case 25: case 29: case 31: case 38: case 46: case 52: case 53: return 7; break; //BLUE case 1: case 6: case 14: case 27: case 33: case 44: case 50: case 57: return 12; break; //YELLOW case 4: case 17: case 24: case 30: case 37: case 45: case 51: case 55: return 9; break; //PURPLE case 2: case 11: case 15: case 19: case 32: case 36: case 49: return 20; break; //CYAN case 8: case 10: case 13: case 18: case 26: case 35: case 41: case 47: case 54: return 11; break; //PINK case 16: case 20: case 39: case 43: case 56: return 8; break; //ORANGE case 21: case 40: return 17; break; default: return 6; break; } return 0; } int editorclass::getwarpbackground(int rx, int ry) { int tmp = rx + (maxwidth * ry); switch(level[tmp].tileset) { case 0: //Space Station switch(level[tmp].tilecol) { case 0: return 3; break; case 1: return 2; break; case 2: return 1; break; case 3: return 4; break; case 4: return 5; break; case 5: return 3; break; case 6: return 1; break; case 7: return 0; break; case 8: return 5; break; case 9: return 0; break; case 10: return 2; break; case 11: return 1; break; case 12: return 5; break; case 13: return 0; break; case 14: return 3; break; case 15: return 2; break; case 16: return 4; break; case 17: return 0; break; case 18: return 3; break; case 19: return 1; break; case 20: return 4; break; case 21: return 5; break; case 22: return 1; break; case 23: return 4; break; case 24: return 5; break; case 25: return 0; break; case 26: return 3; break; case 27: return 1; break; case 28: return 5; break; case 29: return 4; break; case 30: return 5; break; case 31: return 2; break; default: return 6; break; } break; case 1: //Outside switch(level[tmp].tilecol) { case 0: return 3; break; case 1: return 1; break; case 2: return 0; break; case 3: return 2; break; case 4: return 4; break; case 5: return 5; break; case 6: return 2; break; case 7: return 4; break; default: return 6; break; } break; case 2: //Lab switch(level[tmp].tilecol) { case 0: return 0; break; case 1: return 1; break; case 2: return 2; break; case 3: return 3; break; case 4: return 4; break; case 5: return 5; break; case 6: return 6; break; default: return 6; break; } break; case 3: //Warp Zone switch(level[tmp].tilecol) { case 0: return 0; break; case 1: return 1; break; case 2: return 2; break; case 3: return 3; break; case 4: return 4; break; case 5: return 5; break; case 6: return 6; break; default: return 6; break; } break; case 4: //Ship switch(level[tmp].tilecol) { case 0: return 5; break; case 1: return 0; break; case 2: return 4; break; case 3: return 2; break; case 4: return 3; break; case 5: return 1; break; case 6: return 6; break; default: return 6; break; } break; case 5: //Tower return 6; break; default: return 6; break; } } int editorclass::getenemyframe(int t) { switch(t) { case 0: return 78; break; case 1: return 88; break; case 2: return 36; break; case 3: return 164; break; case 4: return 68; break; case 5: return 48; break; case 6: return 176; break; case 7: return 168; break; case 8: return 112; break; case 9: return 114; break; default: return 78; break; } return 78; } void editorclass::placetile(int x, int y, int t) { if(x >= 0 && y >= 0 && x < mapwidth * 40 && y < mapheight * 30) { contents[x + (levx * 40) + vmult[y + (levy * 30)]] = t; } } void editorclass::placetilelocal(int x, int y, int t) { if(x >= 0 && y >= 0 && x < 40 && y < 30) { contents[x + (levx * 40) + vmult[y + (levy * 30)]] = t; } updatetiles = true; } int editorclass::base(int x, int y) { //Return the base tile for the given tileset and colour temp = x + (y * maxwidth); if(level[temp].tileset == 0) //Space Station { if(level[temp].tilecol >= 22) { return 483 + ((level[temp].tilecol - 22) * 3); } else if(level[temp].tilecol >= 11) { return 283 + ((level[temp].tilecol - 11) * 3); } else { return 83 + (level[temp].tilecol * 3); } } else if(level[temp].tileset == 1) //Outside { return 480 + (level[temp].tilecol * 3); } else if(level[temp].tileset == 2) //Lab { return 280 + (level[temp].tilecol * 3); } else if(level[temp].tileset == 3) //Warp Zone/Intermission { return 80 + (level[temp].tilecol * 3); } else if(level[temp].tileset == 4) //SHIP { return 101 + (level[temp].tilecol * 3); } return 0; } int editorclass::backbase(int x, int y) { //Return the base tile for the background of the given tileset and colour temp = x + (y * maxwidth); if(level[temp].tileset == 0) //Space Station { //Pick depending on tilecol switch(level[temp].tilecol) { case 0: case 5: case 26: return 680; //Blue break; case 3: case 16: case 23: return 683; //Yellow break; case 9: case 12: case 21: return 686; //Greeny Cyan break; case 4: case 8: case 24: case 28: case 30: return 689; //Green break; case 20: case 29: return 692; //Orange break; case 2: case 6: case 11: case 22: case 27: return 695; //Red break; case 1: case 10: case 15: case 19: case 31: return 698; //Pink break; case 14: case 18: return 701; //Dark Blue break; case 7: case 13: case 17: case 25: return 704; //Cyan break; default: return 680; break; } } else if(level[temp].tileset == 1) //outside { return 680 + (level[temp].tilecol * 3); } else if(level[temp].tileset == 2) //Lab { return 0; } else if(level[temp].tileset == 3) //Warp Zone/Intermission { return 120 + (level[temp].tilecol * 3); } else if(level[temp].tileset == 4) //SHIP { return 741 + (level[temp].tilecol * 3); } return 0; } int editorclass::at(int x, int y) { if(x < 0) return at(0, y); if(y < 0) return at(x, 0); if(x >= 40) return at(39, y); if(y >= 30) return at(x, 29); if(x >= 0 && y >= 0 && x < 40 && y < 30) { return contents[x + (levx * 40) + vmult[y + (levy * 30)]]; } return 0; } int editorclass::freewrap(int x, int y) { if(x < 0) return freewrap(x + (mapwidth * 40), y); if(y < 0) return freewrap(x, y + (mapheight * 30)); if(x >= (mapwidth * 40)) return freewrap(x - (mapwidth * 40), y); if(y >= (mapheight * 30)) return freewrap(x, y - (mapheight * 30)); if(x >= 0 && y >= 0 && x < (mapwidth * 40) && y < (mapheight * 30)) { if(contents[x + vmult[y]] == 0) { return 0; } else { if(contents[x + vmult[y]] >= 2 && contents[x + vmult[y]] < 80) { return 0; } if(contents[x + vmult[y]] >= 680) { return 0; } } } return 1; } int editorclass::backonlyfree(int x, int y) { //Returns 1 if tile is a background tile, 0 otherwise if(x < 0) return backonlyfree(0, y); if(y < 0) return backonlyfree(x, 0); if(x >= 40) return backonlyfree(39, y); if(y >= 30) return backonlyfree(x, 29); if(x >= 0 && y >= 0 && x < 40 && y < 30) { if(contents[x + (levx * 40) + vmult[y + (levy * 30)]] >= 680) { return 1; } } return 0; } int editorclass::backfree(int x, int y) { //Returns 0 if tile is not a block or background tile, 1 otherwise if(x < 0) return backfree(0, y); if(y < 0) return backfree(x, 0); if(x >= 40) return backfree(39, y); if(y >= 30) return backfree(x, 29); if(x >= 0 && y >= 0 && x < 40 && y < 30) { if(contents[x + (levx * 40) + vmult[y + (levy * 30)]] == 0) { return 0; } else { //if(contents[x+(levx*40)+vmult[y+(levy*30)]]>=2 && contents[x+(levx*40)+vmult[y+(levy*30)]]<80){ // return 0; //} } } return 1; } int editorclass::spikefree(int x, int y) { //Returns 0 if tile is not a block or spike, 1 otherwise if(x == -1) return free(0, y); if(y == -1) return free(x, 0); if(x == 40) return free(39, y); if(y == 30) return free(x, 29); if(x >= 0 && y >= 0 && x < 40 && y < 30) { if(contents[x + (levx * 40) + vmult[y + (levy * 30)]] == 0) { return 0; } else { if(contents[x + (levx * 40) + vmult[y + (levy * 30)]] >= 680) { return 0; } } } return 1; } int editorclass::free(int x, int y) { //Returns 0 if tile is not a block, 1 otherwise if(x == -1) return free(0, y); if(y == -1) return free(x, 0); if(x == 40) return free(39, y); if(y == 30) return free(x, 29); if(x >= 0 && y >= 0 && x < 40 && y < 30) { if(contents[x + (levx * 40) + vmult[y + (levy * 30)]] == 0) { return 0; } else { if(contents[x + (levx * 40) + vmult[y + (levy * 30)]] >= 2 && contents[x + (levx * 40) + vmult[y + (levy * 30)]] < 80) { return 0; } if(contents[x + (levx * 40) + vmult[y + (levy * 30)]] >= 680) { return 0; } } } return 1; } int editorclass::absfree(int x, int y) { //Returns 0 if tile is not a block, 1 otherwise, abs on grid if(x >= 0 && y >= 0 && x < mapwidth * 40 && y < mapheight * 30) { if(contents[x + vmult[y]] == 0) { return 0; } else { if(contents[x + vmult[y]] >= 2 && contents[x + vmult[y]] < 80) { return 0; } if(contents[x + vmult[y]] >= 680) { return 0; } } } return 1; } int editorclass::match(int x, int y) { if(free(x - 1, y) == 0 && free(x, y - 1) == 0 && free(x + 1, y) == 0 && free(x, y + 1) == 0) return 0; if(free(x - 1, y) == 0 && free(x, y - 1) == 0) return 10; if(free(x + 1, y) == 0 && free(x, y - 1) == 0) return 11; if(free(x - 1, y) == 0 && free(x, y + 1) == 0) return 12; if(free(x + 1, y) == 0 && free(x, y + 1) == 0) return 13; if(free(x, y - 1) == 0) return 1; if(free(x - 1, y) == 0) return 2; if(free(x, y + 1) == 0) return 3; if(free(x + 1, y) == 0) return 4; if(free(x - 1, y - 1) == 0) return 5; if(free(x + 1, y - 1) == 0) return 6; if(free(x - 1, y + 1) == 0) return 7; if(free(x + 1, y + 1) == 0) return 8; return 0; } int editorclass::warpzonematch(int x, int y) { if(free(x - 1, y) == 0 && free(x, y - 1) == 0 && free(x + 1, y) == 0 && free(x, y + 1) == 0) return 0; if(free(x - 1, y) == 0 && free(x, y - 1) == 0) return 10; if(free(x + 1, y) == 0 && free(x, y - 1) == 0) return 11; if(free(x - 1, y) == 0 && free(x, y + 1) == 0) return 12; if(free(x + 1, y) == 0 && free(x, y + 1) == 0) return 13; if(free(x, y - 1) == 0) return 1; if(free(x - 1, y) == 0) return 2; if(free(x, y + 1) == 0) return 3; if(free(x + 1, y) == 0) return 4; if(free(x - 1, y - 1) == 0) return 5; if(free(x + 1, y - 1) == 0) return 6; if(free(x - 1, y + 1) == 0) return 7; if(free(x + 1, y + 1) == 0) return 8; return 0; } int editorclass::outsidematch(int x, int y) { if(backonlyfree(x - 1, y) == 0 && backonlyfree(x + 1, y) == 0) return 2; if(backonlyfree(x, y - 1) == 0 && backonlyfree(x, y + 1) == 0) return 1; return 0; } int editorclass::backmatch(int x, int y) { //Returns the first position match for a border // 5 1 6 // 2 X 4 // 7 3 8 /* if(at(x-1,y)>=80 && at(x,y-1)>=80) return 10; if(at(x+1,y)>=80 && at(x,y-1)>=80) return 11; if(at(x-1,y)>=80 && at(x,y+1)>=80) return 12; if(at(x+1,y)>=80 && at(x,y+1)>=80) return 13; if(at(x,y-1)>=80) return 1; if(at(x-1,y)>=80) return 2; if(at(x,y+1)>=80) return 3; if(at(x+1,y)>=80) return 4; if(at(x-1,y-1)>=80) return 5; if(at(x+1,y-1)>=80) return 6; if(at(x-1,y+1)>=80) return 7; if(at(x+1,y+1)>=80) return 8; */ if(backfree(x - 1, y) == 0 && backfree(x, y - 1) == 0 && backfree(x + 1, y) == 0 && backfree(x, y + 1) == 0) return 0; if(backfree(x - 1, y) == 0 && backfree(x, y - 1) == 0) return 10; if(backfree(x + 1, y) == 0 && backfree(x, y - 1) == 0) return 11; if(backfree(x - 1, y) == 0 && backfree(x, y + 1) == 0) return 12; if(backfree(x + 1, y) == 0 && backfree(x, y + 1) == 0) return 13; if(backfree(x, y - 1) == 0) return 1; if(backfree(x - 1, y) == 0) return 2; if(backfree(x, y + 1) == 0) return 3; if(backfree(x + 1, y) == 0) return 4; if(backfree(x - 1, y - 1) == 0) return 5; if(backfree(x + 1, y - 1) == 0) return 6; if(backfree(x - 1, y + 1) == 0) return 7; if(backfree(x + 1, y + 1) == 0) return 8; return 0; } int editorclass::edgetile(int x, int y) { switch(match(x, y)) { case 14: return 0; break; case 10: return 80; break; case 11: return 82; break; case 12: return 160; break; case 13: return 162; break; case 1: return 81; break; case 2: return 120; break; case 3: return 161; break; case 4: return 122; break; case 5: return 42; break; case 6: return 41; break; case 7: return 2; break; case 8: return 1; break; case 0: default: return 0; break; } return 0; } int editorclass::warpzoneedgetile(int x, int y) { switch(backmatch(x, y)) { case 14: return 0; break; case 10: return 80; break; case 11: return 82; break; case 12: return 160; break; case 13: return 162; break; case 1: return 81; break; case 2: return 120; break; case 3: return 161; break; case 4: return 122; break; case 5: return 42; break; case 6: return 41; break; case 7: return 2; break; case 8: return 1; break; case 0: default: return 0; break; } return 0; } int editorclass::outsideedgetile(int x, int y) { switch(outsidematch(x, y)) { case 2: return 0; break; case 1: return 1; break; case 0: default: return 2; break; } return 2; } int editorclass::backedgetile(int x, int y) { switch(backmatch(x, y)) { case 14: return 0; break; case 10: return 80; break; case 11: return 82; break; case 12: return 160; break; case 13: return 162; break; case 1: return 81; break; case 2: return 120; break; case 3: return 161; break; case 4: return 122; break; case 5: return 42; break; case 6: return 41; break; case 7: return 2; break; case 8: return 1; break; case 0: default: return 0; break; } return 0; } int editorclass::labspikedir(int x, int y, int t) { // a slightly more tricky case if(free(x, y + 1) == 1) return 63 + (t * 2); if(free(x, y - 1) == 1) return 64 + (t * 2); if(free(x - 1, y) == 1) return 51 + (t * 2); if(free(x + 1, y) == 1) return 52 + (t * 2); return 63 + (t * 2); } int editorclass::spikedir(int x, int y) { if(free(x, y + 1) == 1) return 8; if(free(x, y - 1) == 1) return 9; if(free(x - 1, y) == 1) return 49; if(free(x + 1, y) == 1) return 50; return 8; } void editorclass::findstartpoint(Game & game) { //Ok! Scan the room for the closest checkpoint int testeditor = -1; //First up; is there a start point on this screen? for(int i = 0; i < EditorData::GetInstance().numedentities; i++) { //if() on screen if(edentity[i].t == 16 && testeditor == -1) { testeditor = i; } } if(testeditor == -1) { game.edsavex = 160; game.edsavey = 120; game.edsaverx = 100; game.edsavery = 100; game.edsavegc = 0; game.edsavey--; game.edsavedir = 1 - edentity[testeditor].p1; } else { //Start point spawn int tx = (edentity[testeditor].x - (edentity[testeditor].x % 40)) / 40; int ty = (edentity[testeditor].y - (edentity[testeditor].y % 30)) / 30; game.edsavex = ((edentity[testeditor].x % 40) * 8) - 4; game.edsavey = (edentity[testeditor].y % 30) * 8; game.edsaverx = 100 + tx; game.edsavery = 100 + ty; game.edsavegc = 0; game.edsavey--; game.edsavedir = 1 - edentity[testeditor].p1; } } void editorclass::saveconvertor() { //In the case of resizing breaking a level, this function can fix it maxwidth = 20; maxheight = 20; int oldwidth = 10, oldheight = 10; std::vector<int> tempcontents; for(int j = 0; j < 30 * oldwidth; j++) { for(int i = 0; i < 40 * oldheight; i++) { tempcontents.push_back(contents[i + (j * 40 * oldwidth)]); } } contents.clear(); for(int j = 0; j < 30 * maxheight; j++) { for(int i = 0; i < 40 * maxwidth; i++) { contents.push_back(0); } } for(int j = 0; j < 30 * oldheight; j++) { for(int i = 0; i < 40 * oldwidth; i++) { contents[i + (j * 40 * oldwidth)] = tempcontents[i + (j * 40 * oldwidth)]; } } tempcontents.clear(); for(int i = 0; i < 30 * maxheight; i++) { vmult.push_back(int(i * 40 * maxwidth)); } for(int j = 0; j < maxheight; j++) { for(int i = 0; i < maxwidth; i++) { level[i + (j * maxwidth)].tilecol = (i + j) % 6; } } contents.clear(); } int editorclass::findtrinket(int t) { int ttrinket = 0; for(int i = 0; i < EditorData::GetInstance().numedentities; i++) { if(i == t) return ttrinket; if(edentity[i].t == 9) ttrinket++; } return 0; } int editorclass::findcrewmate(int t) { int ttrinket = 0; for(int i = 0; i < EditorData::GetInstance().numedentities; i++) { if(i == t) return ttrinket; if(edentity[i].t == 15) ttrinket++; } return 0; } int editorclass::findwarptoken(int t) { int ttrinket = 0; for(int i = 0; i < EditorData::GetInstance().numedentities; i++) { if(i == t) return ttrinket; if(edentity[i].t == 13) ttrinket++; } return 0; } void editorclass::countstuff() { numtrinkets = 0; numcrewmates = 0; for(int i = 0; i < EditorData::GetInstance().numedentities; i++) { if(edentity[i].t == 9) numtrinkets++; if(edentity[i].t == 15) numcrewmates++; } } void editorclass::load(std::string & _path) { reset(); unsigned char * mem = NULL; static const char * levelDir = "levels/"; if(_path.compare(0, strlen(levelDir), levelDir) != 0) { _path = levelDir + _path; } FILESYSTEM_loadFileToMemory(_path.c_str(), &mem, NULL); if(mem == NULL) { printf("No level %s to load :(\n", _path.c_str()); return; } TiXmlDocument doc; doc.Parse((const char *)mem); FILESYSTEM_freeMemory(&mem); TiXmlHandle hDoc(&doc); TiXmlElement * pElem; TiXmlHandle hRoot(0); version = 0; { pElem = hDoc.FirstChildElement().Element(); // should always have a valid root but handle gracefully if it does if(!pElem) { printf("No valid root! Corrupt level file?\n"); } pElem->QueryIntAttribute("version", &version); // save this for later hRoot = TiXmlHandle(pElem); } for(pElem = hRoot.FirstChild("Data").FirstChild().Element(); pElem; pElem = pElem->NextSiblingElement()) { std::string pKey(pElem->Value()); const char * pText = pElem->GetText(); if(pText == NULL) { pText = ""; } if(pKey == "MetaData") { for(TiXmlElement * subElem = pElem->FirstChildElement(); subElem; subElem = subElem->NextSiblingElement()) { std::string pKey(subElem->Value()); const char * pText = subElem->GetText(); if(pText == NULL) { pText = ""; } if(pKey == "Creator") { EditorData::GetInstance().creator = pText; } if(pKey == "Title") { EditorData::GetInstance().title = pText; } if(pKey == "Desc1") { Desc1 = pText; } if(pKey == "Desc2") { Desc2 = pText; } if(pKey == "Desc3") { Desc3 = pText; } if(pKey == "website") { website = pText; } } } if(pKey == "mapwidth") { mapwidth = atoi(pText); } if(pKey == "mapheight") { mapheight = atoi(pText); } if(pKey == "levmusic") { levmusic = atoi(pText); } if(pKey == "contents") { std::string TextString = (pText); if(TextString.length()) { std::vector<std::string> values = split(TextString, ','); //contents.clear(); for(size_t i = 0; i < contents.size(); i++) { contents[i] = 0; } int x = 0; int y = 0; for(size_t i = 0; i < values.size(); i++) { contents[x + (maxwidth * 40 * y)] = atoi(values[i].c_str()); x++; if(x == mapwidth * 40) { x = 0; y++; } } } } /*else if(version==1){ if (pKey == "contents") { std::string TextString = (pText); if(TextString.length()) { std::vector<std::string> values = split(TextString,','); contents.clear(); for(int i = 0; i < values.size(); i++) { contents.push_back(atoi(values[i].c_str())); } } } //} */ if(pKey == "edEntities") { int i = 0; for(TiXmlElement * edEntityEl = pElem->FirstChildElement(); edEntityEl; edEntityEl = edEntityEl->NextSiblingElement()) { std::string pKey(edEntityEl->Value()); //const char* pText = edEntityEl->GetText() ; if(edEntityEl->GetText() != NULL) { edentity[i].scriptname = std::string(edEntityEl->GetText()); } edEntityEl->QueryIntAttribute("x", &edentity[i].x); edEntityEl->QueryIntAttribute("y", &edentity[i].y); edEntityEl->QueryIntAttribute("t", &edentity[i].t); edEntityEl->QueryIntAttribute("p1", &edentity[i].p1); edEntityEl->QueryIntAttribute("p2", &edentity[i].p2); edEntityEl->QueryIntAttribute("p3", &edentity[i].p3); edEntityEl->QueryIntAttribute("p4", &edentity[i].p4); edEntityEl->QueryIntAttribute("p5", &edentity[i].p5); edEntityEl->QueryIntAttribute("p6", &edentity[i].p6); i++; } EditorData::GetInstance().numedentities = i; } if(pKey == "levelMetaData") { int i = 0; for(TiXmlElement * edLevelClassElement = pElem->FirstChildElement(); edLevelClassElement; edLevelClassElement = edLevelClassElement->NextSiblingElement()) { std::string pKey(edLevelClassElement->Value()); if(edLevelClassElement->GetText() != NULL) { level[i].roomname = std::string(edLevelClassElement->GetText()); } edLevelClassElement->QueryIntAttribute("tileset", &level[i].tileset); edLevelClassElement->QueryIntAttribute("tilecol", &level[i].tilecol); edLevelClassElement->QueryIntAttribute("platx1", &level[i].platx1); edLevelClassElement->QueryIntAttribute("platy1", &level[i].platy1); edLevelClassElement->QueryIntAttribute("platx2", &level[i].platx2); edLevelClassElement->QueryIntAttribute("platy2", &level[i].platy2); edLevelClassElement->QueryIntAttribute("platv", &level[i].platv); edLevelClassElement->QueryIntAttribute("enemyx1", &level[i].enemyx1); edLevelClassElement->QueryIntAttribute("enemyy1", &level[i].enemyy1); edLevelClassElement->QueryIntAttribute("enemyx2", &level[i].enemyx2); edLevelClassElement->QueryIntAttribute("enemyy2", &level[i].enemyy2); edLevelClassElement->QueryIntAttribute("enemytype", &level[i].enemytype); edLevelClassElement->QueryIntAttribute("directmode", &level[i].directmode); edLevelClassElement->QueryIntAttribute("warpdir", &level[i].warpdir); i++; } } if(pKey == "script") { std::string TextString = (pText); if(TextString.length()) { std::vector<std::string> values = split(TextString, '|'); script.clearcustom(); for(size_t i = 0; i < values.size(); i++) { script.customscript.push_back(values[i]); } } } } gethooks(); countstuff(); version = 2; //saveconvertor(); } void editorclass::save(std::string & _path) { TiXmlDocument doc; TiXmlElement * msg; TiXmlDeclaration * decl = new TiXmlDeclaration("1.0", "", ""); doc.LinkEndChild(decl); TiXmlElement * root = new TiXmlElement("MapData"); root->SetAttribute("version", version); doc.LinkEndChild(root); TiXmlComment * comment = new TiXmlComment(); comment->SetValue(" Save file "); root->LinkEndChild(comment); TiXmlElement * data = new TiXmlElement("Data"); root->LinkEndChild(data); msg = new TiXmlElement("MetaData"); time_t rawtime; struct tm * timeinfo; time(&rawtime); timeinfo = localtime(&rawtime); std::string timeAndDate = asctime(timeinfo); //timeAndDate += dateStr; EditorData::GetInstance().timeModified = timeAndDate; if(EditorData::GetInstance().timeModified == "") { EditorData::GetInstance().timeCreated = timeAndDate; } //getUser TiXmlElement * meta = new TiXmlElement("Creator"); meta->LinkEndChild(new TiXmlText(EditorData::GetInstance().creator.c_str())); msg->LinkEndChild(meta); meta = new TiXmlElement("Title"); meta->LinkEndChild(new TiXmlText(EditorData::GetInstance().title.c_str())); msg->LinkEndChild(meta); meta = new TiXmlElement("Created"); meta->LinkEndChild(new TiXmlText(UtilityClass::String(version).c_str())); msg->LinkEndChild(meta); meta = new TiXmlElement("Modified"); meta->LinkEndChild(new TiXmlText(EditorData::GetInstance().modifier.c_str())); msg->LinkEndChild(meta); meta = new TiXmlElement("Modifiers"); meta->LinkEndChild(new TiXmlText(UtilityClass::String(version).c_str())); msg->LinkEndChild(meta); meta = new TiXmlElement("Desc1"); meta->LinkEndChild(new TiXmlText(Desc1.c_str())); msg->LinkEndChild(meta); meta = new TiXmlElement("Desc2"); meta->LinkEndChild(new TiXmlText(Desc2.c_str())); msg->LinkEndChild(meta); meta = new TiXmlElement("Desc3"); meta->LinkEndChild(new TiXmlText(Desc3.c_str())); msg->LinkEndChild(meta); meta = new TiXmlElement("website"); meta->LinkEndChild(new TiXmlText(website.c_str())); msg->LinkEndChild(meta); data->LinkEndChild(msg); msg = new TiXmlElement("mapwidth"); msg->LinkEndChild(new TiXmlText(UtilityClass::String(mapwidth).c_str())); data->LinkEndChild(msg); msg = new TiXmlElement("mapheight"); msg->LinkEndChild(new TiXmlText(UtilityClass::String(mapheight).c_str())); data->LinkEndChild(msg); msg = new TiXmlElement("levmusic"); msg->LinkEndChild(new TiXmlText(UtilityClass::String(levmusic).c_str())); data->LinkEndChild(msg); //New save format std::string contentsString = ""; for(int y = 0; y < mapheight * 30; y++) { for(int x = 0; x < mapwidth * 40; x++) { contentsString += UtilityClass::String(contents[x + (maxwidth * 40 * y)]) + ","; } } msg = new TiXmlElement("contents"); msg->LinkEndChild(new TiXmlText(contentsString.c_str())); data->LinkEndChild(msg); //Old save format /* std::string contentsString; for(int i = 0; i < contents.size(); i++ ) { contentsString += UtilityClass::String(contents[i]) + ","; } msg = new TiXmlElement( "contents" ); msg->LinkEndChild( new TiXmlText( contentsString.c_str() )); data->LinkEndChild( msg ); */ msg = new TiXmlElement("edEntities"); for(int i = 0; i < EditorData::GetInstance().numedentities; i++) { TiXmlElement * edentityElement = new TiXmlElement("edentity"); edentityElement->SetAttribute("x", edentity[i].x); edentityElement->SetAttribute("y", edentity[i].y); edentityElement->SetAttribute("t", edentity[i].t); edentityElement->SetAttribute("p1", edentity[i].p1); edentityElement->SetAttribute("p2", edentity[i].p2); edentityElement->SetAttribute("p3", edentity[i].p3); edentityElement->SetAttribute("p4", edentity[i].p4); edentityElement->SetAttribute("p5", edentity[i].p5); edentityElement->SetAttribute("p6", edentity[i].p6); edentityElement->LinkEndChild(new TiXmlText(edentity[i].scriptname.c_str())); edentityElement->LinkEndChild(new TiXmlText("")); msg->LinkEndChild(edentityElement); } data->LinkEndChild(msg); msg = new TiXmlElement("levelMetaData"); for(int i = 0; i < 400; i++) { TiXmlElement * edlevelclassElement = new TiXmlElement("edLevelClass"); edlevelclassElement->SetAttribute("tileset", level[i].tileset); edlevelclassElement->SetAttribute("tilecol", level[i].tilecol); edlevelclassElement->SetAttribute("platx1", level[i].platx1); edlevelclassElement->SetAttribute("platy1", level[i].platy1); edlevelclassElement->SetAttribute("platx2", level[i].platx2); edlevelclassElement->SetAttribute("platy2", level[i].platy2); edlevelclassElement->SetAttribute("platv", level[i].platv); edlevelclassElement->SetAttribute("enemyx1", level[i].enemyx1); edlevelclassElement->SetAttribute("enemyy1", level[i].enemyy1); edlevelclassElement->SetAttribute("enemyx2", level[i].enemyx2); edlevelclassElement->SetAttribute("enemyy2", level[i].enemyy2); edlevelclassElement->SetAttribute("enemytype", level[i].enemytype); edlevelclassElement->SetAttribute("directmode", level[i].directmode); edlevelclassElement->SetAttribute("warpdir", level[i].warpdir); edlevelclassElement->LinkEndChild(new TiXmlText(level[i].roomname.c_str())); msg->LinkEndChild(edlevelclassElement); } data->LinkEndChild(msg); std::string scriptString; for(size_t i = 0; i < script.customscript.size(); i++) { scriptString += script.customscript[i] + "|"; } msg = new TiXmlElement("script"); msg->LinkEndChild(new TiXmlText(scriptString.c_str())); data->LinkEndChild(msg); doc.SaveFile((std::string(FILESYSTEM_getUserLevelDirectory()) + _path).c_str()); } void addedentity(int xp, int yp, int tp, int p1 /*=0*/, int p2 /*=0*/, int p3 /*=0*/, int p4 /*=0*/, int p5 /*=320*/, int p6 /*=240*/) { edentity[EditorData::GetInstance().numedentities].x = xp; edentity[EditorData::GetInstance().numedentities].y = yp; edentity[EditorData::GetInstance().numedentities].t = tp; edentity[EditorData::GetInstance().numedentities].p1 = p1; edentity[EditorData::GetInstance().numedentities].p2 = p2; edentity[EditorData::GetInstance().numedentities].p3 = p3; edentity[EditorData::GetInstance().numedentities].p4 = p4; edentity[EditorData::GetInstance().numedentities].p5 = p5; edentity[EditorData::GetInstance().numedentities].p6 = p6; edentity[EditorData::GetInstance().numedentities].scriptname = ""; EditorData::GetInstance().numedentities++; } void naddedentity(int xp, int yp, int tp, int p1 /*=0*/, int p2 /*=0*/, int p3 /*=0*/, int p4 /*=0*/, int p5 /*=320*/, int p6 /*=240*/) { edentity[EditorData::GetInstance().numedentities].x = xp; edentity[EditorData::GetInstance().numedentities].y = yp; edentity[EditorData::GetInstance().numedentities].t = tp; edentity[EditorData::GetInstance().numedentities].p1 = p1; edentity[EditorData::GetInstance().numedentities].p2 = p2; edentity[EditorData::GetInstance().numedentities].p3 = p3; edentity[EditorData::GetInstance().numedentities].p4 = p4; edentity[EditorData::GetInstance().numedentities].p5 = p5; edentity[EditorData::GetInstance().numedentities].p6 = p6; edentity[EditorData::GetInstance().numedentities].scriptname = ""; } void copyedentity(int a, int b) { edentity[a].x = edentity[b].x; edentity[a].y = edentity[b].y; edentity[a].t = edentity[b].t; edentity[a].p1 = edentity[b].p1; edentity[a].p2 = edentity[b].p2; edentity[a].p3 = edentity[b].p3; edentity[a].p4 = edentity[b].p4; edentity[a].p5 = edentity[b].p5; edentity[a].p6 = edentity[b].p6; edentity[a].scriptname = edentity[b].scriptname; } void removeedentity(int t) { if(t == EditorData::GetInstance().numedentities - 1) { EditorData::GetInstance().numedentities--; } else { for(int m = t; m < EditorData::GetInstance().numedentities; m++) copyedentity(m, m + 1); EditorData::GetInstance().numedentities--; } } int edentat(int xp, int yp) { for(int i = 0; i < EditorData::GetInstance().numedentities; i++) { if(edentity[i].x == xp && edentity[i].y == yp) return i; } return -1; } bool edentclear(int xp, int yp) { for(int i = 0; i < EditorData::GetInstance().numedentities; i++) { if(edentity[i].x == xp && edentity[i].y == yp) return false; } return true; } void fillbox(Graphics & dwgfx, int x, int y, int x2, int y2, int c) { FillRect(dwgfx.backBuffer, x, y, x2 - x, 1, c); FillRect(dwgfx.backBuffer, x, y2 - 1, x2 - x, 1, c); FillRect(dwgfx.backBuffer, x, y, 1, y2 - y, c); FillRect(dwgfx.backBuffer, x2 - 1, y, 1, y2 - y, c); } void fillboxabs(Graphics & dwgfx, int x, int y, int x2, int y2, int c) { FillRect(dwgfx.backBuffer, x, y, x2, 1, c); FillRect(dwgfx.backBuffer, x, y + y2 - 1, x2, 1, c); FillRect(dwgfx.backBuffer, x, y, 1, y2, c); FillRect(dwgfx.backBuffer, x + x2 - 1, y, 1, y2, c); } extern editorclass ed; extern edentities edentity[3000]; extern int temp; extern scriptclass script; void editorclass::generatecustomminimap(Graphics & dwgfx, mapclass & map) { map.customwidth = mapwidth; map.customheight = mapheight; map.customzoom = 1; if(map.customwidth <= 10 && map.customheight <= 10) map.customzoom = 2; if(map.customwidth <= 5 && map.customheight <= 5) map.customzoom = 4; //Set minimap offsets if(map.customzoom == 4) { map.custommmxoff = 24 * (5 - map.customwidth); map.custommmxsize = 240 - (map.custommmxoff * 2); map.custommmyoff = 18 * (5 - map.customheight); map.custommmysize = 180 - (map.custommmyoff * 2); } else if(map.customzoom == 2) { map.custommmxoff = 12 * (10 - map.customwidth); map.custommmxsize = 240 - (map.custommmxoff * 2); map.custommmyoff = 9 * (10 - map.customheight); map.custommmysize = 180 - (map.custommmyoff * 2); } else { map.custommmxoff = 6 * (20 - map.customwidth); map.custommmxsize = 240 - (map.custommmxoff * 2); map.custommmyoff = int(4.5 * (20 - map.customheight)); map.custommmysize = 180 - (map.custommmyoff * 2); } FillRect(dwgfx.images[12], dwgfx.getRGB(0, 0, 0)); int tm = 0; int temp = 0; //Scan over the map size if(ed.mapheight <= 5 && ed.mapwidth <= 5) { //4x map for(int j2 = 0; j2 < ed.mapheight; j2++) { for(int i2 = 0; i2 < ed.mapwidth; i2++) { //Ok, now scan over each square tm = 196; if(ed.level[i2 + (j2 * ed.maxwidth)].tileset == 1) tm = 96; for(int j = 0; j < 36; j++) { for(int i = 0; i < 48; i++) { temp = ed.absfree(int(i * 0.83) + (i2 * 40), int(j * 0.83) + (j2 * 30)); if(temp >= 1) { //Fill in this pixel FillRect(dwgfx.images[12], (i2 * 48) + i, (j2 * 36) + j, 1, 1, dwgfx.getRGB(tm, tm, tm)); } } } } } } else if(ed.mapheight <= 10 && ed.mapwidth <= 10) { //2x map for(int j2 = 0; j2 < ed.mapheight; j2++) { for(int i2 = 0; i2 < ed.mapwidth; i2++) { //Ok, now scan over each square tm = 196; if(ed.level[i2 + (j2 * ed.maxwidth)].tileset == 1) tm = 96; for(int j = 0; j < 18; j++) { for(int i = 0; i < 24; i++) { temp = ed.absfree(int(i * 1.6) + (i2 * 40), int(j * 1.6) + (j2 * 30)); if(temp >= 1) { //Fill in this pixel FillRect(dwgfx.images[12], (i2 * 24) + i, (j2 * 18) + j, 1, 1, dwgfx.getRGB(tm, tm, tm)); } } } } } } else { for(int j2 = 0; j2 < ed.mapheight; j2++) { for(int i2 = 0; i2 < ed.mapwidth; i2++) { //Ok, now scan over each square tm = 196; if(ed.level[i2 + (j2 * ed.maxwidth)].tileset == 1) tm = 96; for(int j = 0; j < 9; j++) { for(int i = 0; i < 12; i++) { temp = ed.absfree(3 + (i * 3) + (i2 * 40), (j * 3) + (j2 * 30)); if(temp >= 1) { //Fill in this pixel FillRect(dwgfx.images[12], (i2 * 12) + i, (j2 * 9) + j, 1, 1, dwgfx.getRGB(tm, tm, tm)); } } } } } } } void editorrender(KeyPoll & key, Graphics & dwgfx, Game & game, mapclass & map, entityclass & obj, UtilityClass & help) { //TODO //dwgfx.backbuffer.lock(); //Draw grid FillRect(dwgfx.backBuffer, 0, 0, 320, 240, dwgfx.getRGB(0, 0, 0)); for(int j = 0; j < 30; j++) { for(int i = 0; i < 40; i++) { fillbox(dwgfx, i * 8, j * 8, (i * 8) + 7, (j * 8) + 7, dwgfx.getRGB(8, 8, 8)); //a simple grid if(i % 4 == 0) fillbox(dwgfx, i * 8, j * 8, (i * 8) + 7, (j * 8) + 7, dwgfx.getRGB(16, 16, 16)); if(j % 4 == 0) fillbox(dwgfx, i * 8, j * 8, (i * 8) + 7, (j * 8) + 7, dwgfx.getRGB(16, 16, 16)); //Minor guides if(i == 9) fillbox(dwgfx, i * 8, j * 8, (i * 8) + 7, (j * 8) + 7, dwgfx.getRGB(24, 24, 24)); if(i == 30) fillbox(dwgfx, i * 8, j * 8, (i * 8) + 7, (j * 8) + 7, dwgfx.getRGB(24, 24, 24)); if(j == 6 || j == 7) fillbox(dwgfx, i * 8, j * 8, (i * 8) + 7, (j * 8) + 7, dwgfx.getRGB(24, 24, 24)); if(j == 21 || j == 22) fillbox(dwgfx, i * 8, j * 8, (i * 8) + 7, (j * 8) + 7, dwgfx.getRGB(24, 24, 24)); //Major guides if(i == 20 || i == 19) fillbox(dwgfx, i * 8, j * 8, (i * 8) + 7, (j * 8) + 7, dwgfx.getRGB(32, 32, 32)); if(j == 14) fillbox(dwgfx, i * 8, j * 8, (i * 8) + 7, (j * 8) + 7, dwgfx.getRGB(32, 32, 32)); } } //Or draw background //dwgfx.drawbackground(1, map); if(!ed.settingsmod) { switch(ed.level[ed.levx + (ed.levy * ed.maxwidth)].warpdir) { case 1: dwgfx.rcol = ed.getwarpbackground(ed.levx, ed.levy); dwgfx.drawbackground(3, map); break; case 2: dwgfx.rcol = ed.getwarpbackground(ed.levx, ed.levy); dwgfx.drawbackground(4, map); break; case 3: dwgfx.rcol = ed.getwarpbackground(ed.levx, ed.levy); dwgfx.drawbackground(5, map); break; default: break; } } //Draw map, in function int temp; if(ed.level[ed.levx + (ed.maxwidth * ed.levy)].tileset == 0 || ed.level[ed.levx + (ed.maxwidth * ed.levy)].tileset == 10) { for(int j = 0; j < 30; j++) { for(int i = 0; i < 40; i++) { temp = ed.contents[i + (ed.levx * 40) + ed.vmult[j + (ed.levy * 30)]]; if(temp > 0) dwgfx.drawtile(i * 8, j * 8, temp); } } } else { for(int j = 0; j < 30; j++) { for(int i = 0; i < 40; i++) { temp = ed.contents[i + (ed.levx * 40) + ed.vmult[j + (ed.levy * 30)]]; if(temp > 0) dwgfx.drawtile2(i * 8, j * 8, temp); } } } //Edge tile fix //Buffer the sides of the new room with tiles from other rooms, to ensure no gap problems. for(int j = 0; j < 30; j++) { //left edge if(ed.freewrap((ed.levx * 40) - 1, j + (ed.levy * 30)) == 1) { FillRect(dwgfx.backBuffer, 0, j * 8, 2, 8, dwgfx.getRGB(255, 255, 255 - help.glow)); } //right edge if(ed.freewrap((ed.levx * 40) + 40, j + (ed.levy * 30)) == 1) { FillRect(dwgfx.backBuffer, 318, j * 8, 2, 8, dwgfx.getRGB(255, 255, 255 - help.glow)); } } for(int i = 0; i < 40; i++) { if(ed.freewrap((ed.levx * 40) + i, (ed.levy * 30) - 1) == 1) { FillRect(dwgfx.backBuffer, i * 8, 0, 8, 2, dwgfx.getRGB(255, 255, 255 - help.glow)); } if(ed.freewrap((ed.levx * 40) + i, 30 + (ed.levy * 30)) == 1) { FillRect(dwgfx.backBuffer, i * 8, 238, 8, 2, dwgfx.getRGB(255, 255, 255 - help.glow)); } } //Draw entities game.customcol = ed.getlevelcol(ed.levx + (ed.levy * ed.maxwidth)) + 1; ed.entcol = ed.getenemycol(game.customcol); obj.customplatformtile = game.customcol * 12; ed.temp = edentat(ed.tilex + (ed.levx * 40), ed.tiley + (ed.levy * 30)); for(int i = 0; i < EditorData::GetInstance().numedentities; i++) { //if() on screen int tx = (edentity[i].x - (edentity[i].x % 40)) / 40; int ty = (edentity[i].y - (edentity[i].y % 30)) / 30; point tpoint; SDL_Rect drawRect; if(tx == ed.levx && ty == ed.levy) { switch(edentity[i].t) { case 1: //Entities //FillRect(dwgfx.backBuffer, (edentity[i].x*8)- (ed.levx*40*8),(edentity[i].y*8)- (ed.levy*30*8), 16,16, dwgfx.getRGB(64,32,64)); //dwgfx.drawsprite((edentity[i].x*8)- (ed.levx*40*8),(edentity[i].y*8)- (ed.levy*30*8),ed.getenemyframe(ed.level[ed.levx+(ed.levy*ed.maxwidth)].enemytype),164,48,48); dwgfx.drawspritesetcol((edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8), ed.getenemyframe(ed.level[ed.levx + (ed.levy * ed.maxwidth)].enemytype), ed.entcol, help); if(edentity[i].p1 == 0) dwgfx.Print((edentity[i].x * 8) - (ed.levx * 40 * 8) + 4, (edentity[i].y * 8) - (ed.levy * 30 * 8) + 4, "V", 255, 255, 255 - help.glow, false); if(edentity[i].p1 == 1) dwgfx.Print((edentity[i].x * 8) - (ed.levx * 40 * 8) + 4, (edentity[i].y * 8) - (ed.levy * 30 * 8) + 4, "^", 255, 255, 255 - help.glow, false); if(edentity[i].p1 == 2) dwgfx.Print((edentity[i].x * 8) - (ed.levx * 40 * 8) + 4, (edentity[i].y * 8) - (ed.levy * 30 * 8) + 4, "<", 255, 255, 255 - help.glow, false); if(edentity[i].p1 == 3) dwgfx.Print((edentity[i].x * 8) - (ed.levx * 40 * 8) + 4, (edentity[i].y * 8) - (ed.levy * 30 * 8) + 4, ">", 255, 255, 255 - help.glow, false); fillboxabs(dwgfx, (edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8), 16, 16, dwgfx.getBGR(255, 164, 255)); break; case 2: //Threadmills & platforms tpoint.x = (edentity[i].x * 8) - (ed.levx * 40 * 8); tpoint.y = (edentity[i].y * 8) - (ed.levy * 30 * 8); drawRect = dwgfx.tiles_rect; drawRect.x += tpoint.x; drawRect.y += tpoint.y; BlitSurfaceStandard(dwgfx.entcolours[obj.customplatformtile], NULL, dwgfx.backBuffer, &drawRect); drawRect.x += 8; BlitSurfaceStandard(dwgfx.entcolours[obj.customplatformtile], NULL, dwgfx.backBuffer, &drawRect); drawRect.x += 8; BlitSurfaceStandard(dwgfx.entcolours[obj.customplatformtile], NULL, dwgfx.backBuffer, &drawRect); drawRect.x += 8; BlitSurfaceStandard(dwgfx.entcolours[obj.customplatformtile], NULL, dwgfx.backBuffer, &drawRect); if(edentity[i].p1 <= 4) { if(edentity[i].p1 == 0) dwgfx.Print((edentity[i].x * 8) - (ed.levx * 40 * 8) + 12, (edentity[i].y * 8) - (ed.levy * 30 * 8), "V", 255 - help.glow, 255 - help.glow, 255 - help.glow, false); if(edentity[i].p1 == 1) dwgfx.Print((edentity[i].x * 8) - (ed.levx * 40 * 8) + 12, (edentity[i].y * 8) - (ed.levy * 30 * 8), "^", 255 - help.glow, 255 - help.glow, 255 - help.glow, false); if(edentity[i].p1 == 2) dwgfx.Print((edentity[i].x * 8) - (ed.levx * 40 * 8) + 12, (edentity[i].y * 8) - (ed.levy * 30 * 8), "<", 255 - help.glow, 255 - help.glow, 255 - help.glow, false); if(edentity[i].p1 == 3) dwgfx.Print((edentity[i].x * 8) - (ed.levx * 40 * 8) + 12, (edentity[i].y * 8) - (ed.levy * 30 * 8), ">", 255 - help.glow, 255 - help.glow, 255 - help.glow, false); fillboxabs(dwgfx, (edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8), 32, 8, dwgfx.getBGR(255, 255, 255)); } if(edentity[i].p1 == 5) { dwgfx.Print((edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8), ">>>>", 255 - help.glow, 255 - help.glow, 255 - help.glow, false); fillboxabs(dwgfx, (edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8), 32, 8, dwgfx.getBGR(255, 255, 255)); } else if(edentity[i].p1 == 6) { dwgfx.Print((edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8), "<<<<", 255 - help.glow, 255 - help.glow, 255 - help.glow, false); fillboxabs(dwgfx, (edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8), 32, 8, dwgfx.getBGR(255, 255, 255)); } if(edentity[i].p1 >= 7) { //FillRect(dwgfx.backBuffer, (edentity[i].x*8)- (ed.levx*40*8),(edentity[i].y*8)- (ed.levy*30*8), 32,8, dwgfx.getBGR(64,128,64)); tpoint.x = (edentity[i].x * 8) - (ed.levx * 40 * 8) + 32; tpoint.y = (edentity[i].y * 8) - (ed.levy * 30 * 8); drawRect = dwgfx.tiles_rect; drawRect.x += tpoint.x; drawRect.y += tpoint.y; BlitSurfaceStandard(dwgfx.entcolours[obj.customplatformtile], NULL, dwgfx.backBuffer, &drawRect); drawRect.x += 8; BlitSurfaceStandard(dwgfx.entcolours[obj.customplatformtile], NULL, dwgfx.backBuffer, &drawRect); drawRect.x += 8; BlitSurfaceStandard(dwgfx.entcolours[obj.customplatformtile], NULL, dwgfx.backBuffer, &drawRect); drawRect.x += 8; BlitSurfaceStandard(dwgfx.entcolours[obj.customplatformtile], NULL, dwgfx.backBuffer, &drawRect); } if(edentity[i].p1 == 7) { dwgfx.Print((edentity[i].x * 8) - (ed.levx * 40 * 8) + 4, (edentity[i].y * 8) - (ed.levy * 30 * 8), "> > > > ", 255 - help.glow, 255 - help.glow, 255 - help.glow, false); fillboxabs(dwgfx, (edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8), 64, 8, dwgfx.getBGR(255, 255, 255)); } else if(edentity[i].p1 == 8) { dwgfx.Print((edentity[i].x * 8) - (ed.levx * 40 * 8) + 4, (edentity[i].y * 8) - (ed.levy * 30 * 8), "< < < < ", 255 - help.glow, 255 - help.glow, 255 - help.glow, false); fillboxabs(dwgfx, (edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8), 64, 8, dwgfx.getBGR(255, 255, 255)); } break; case 3: //Disappearing Platform //FillRect(dwgfx.backBuffer, (edentity[i].x*8)- (ed.levx*40*8),(edentity[i].y*8)- (ed.levy*30*8), 32,8, dwgfx.getBGR(64,64,128)); tpoint.x = (edentity[i].x * 8) - (ed.levx * 40 * 8); tpoint.y = (edentity[i].y * 8) - (ed.levy * 30 * 8); drawRect = dwgfx.tiles_rect; drawRect.x += tpoint.x; drawRect.y += tpoint.y; BlitSurfaceStandard(dwgfx.entcolours[obj.customplatformtile], NULL, dwgfx.backBuffer, &drawRect); drawRect.x += 8; BlitSurfaceStandard(dwgfx.entcolours[obj.customplatformtile], NULL, dwgfx.backBuffer, &drawRect); drawRect.x += 8; BlitSurfaceStandard(dwgfx.entcolours[obj.customplatformtile], NULL, dwgfx.backBuffer, &drawRect); drawRect.x += 8; BlitSurfaceStandard(dwgfx.entcolours[obj.customplatformtile], NULL, dwgfx.backBuffer, &drawRect); dwgfx.Print((edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8), "////", 255 - help.glow, 255 - help.glow, 255 - help.glow, false); fillboxabs(dwgfx, (edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8), 32, 8, dwgfx.getBGR(255, 255, 255)); break; case 9: //Shiny Trinket dwgfx.drawsprite((edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8), 22, 196, 196, 196); fillboxabs(dwgfx, (edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8), 16, 16, dwgfx.getRGB(164, 164, 255)); break; case 10: //Checkpoints if(edentity[i].p1 == 0) //From roof { dwgfx.drawsprite((edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8), 20, 196, 196, 196); } else if(edentity[i].p1 == 1) //From floor { dwgfx.drawsprite((edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8), 21, 196, 196, 196); } fillboxabs(dwgfx, (edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8), 16, 16, dwgfx.getRGB(164, 164, 255)); break; case 11: //Gravity lines if(edentity[i].p1 == 0) //Horizontal { int tx = edentity[i].x - (ed.levx * 40); int tx2 = edentity[i].x - (ed.levx * 40); int ty = edentity[i].y - (ed.levy * 30); while(ed.spikefree(tx, ty) == 0) tx--; while(ed.spikefree(tx2, ty) == 0) tx2++; tx++; FillRect(dwgfx.backBuffer, (tx * 8), (ty * 8) + 4, (tx2 - tx) * 8, 1, dwgfx.getRGB(194, 194, 194)); fillboxabs(dwgfx, (edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8), 8, 8, dwgfx.getRGB(164, 255, 164)); edentity[i].p2 = tx; edentity[i].p3 = (tx2 - tx) * 8; } else //Vertical { int tx = edentity[i].x - (ed.levx * 40); int ty = edentity[i].y - (ed.levy * 30); int ty2 = edentity[i].y - (ed.levy * 30); while(ed.spikefree(tx, ty) == 0) ty--; while(ed.spikefree(tx, ty2) == 0) ty2++; ty++; FillRect(dwgfx.backBuffer, (tx * 8) + 3, (ty * 8), 1, (ty2 - ty) * 8, dwgfx.getRGB(194, 194, 194)); fillboxabs(dwgfx, (edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8), 8, 8, dwgfx.getRGB(164, 255, 164)); edentity[i].p2 = ty; edentity[i].p3 = (ty2 - ty) * 8; } break; case 13: //Warp tokens dwgfx.drawsprite((edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8), 18 + (ed.entframe % 2), 196, 196, 196); fillboxabs(dwgfx, (edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8), 16, 16, dwgfx.getRGB(164, 164, 255)); if(ed.temp == i) { dwgfx.Print((edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8) - 8, "(" + help.String(((edentity[i].p1 - int(edentity[i].p1 % 40)) / 40) + 1) + "," + help.String(((edentity[i].p2 - int(edentity[i].p2 % 30)) / 30) + 1) + ")", 210, 210, 255); } else { dwgfx.Print((edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8) - 8, help.String(ed.findwarptoken(i)), 210, 210, 255); } break; case 15: //Crewmates dwgfx.drawspritesetcol((edentity[i].x * 8) - (ed.levx * 40 * 8) - 4, (edentity[i].y * 8) - (ed.levy * 30 * 8), 144, obj.crewcolour(edentity[i].p1), help); fillboxabs(dwgfx, (edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8), 16, 24, dwgfx.getRGB(164, 164, 164)); break; case 16: //Start if(edentity[i].p1 == 0) //Left { dwgfx.drawspritesetcol((edentity[i].x * 8) - (ed.levx * 40 * 8) - 4, (edentity[i].y * 8) - (ed.levy * 30 * 8), 0, obj.crewcolour(0), help); } else if(edentity[i].p1 == 1) { dwgfx.drawspritesetcol((edentity[i].x * 8) - (ed.levx * 40 * 8) - 4, (edentity[i].y * 8) - (ed.levy * 30 * 8), 3, obj.crewcolour(0), help); } fillboxabs(dwgfx, (edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8), 16, 24, dwgfx.getRGB(164, 255, 255)); if(ed.entframe < 2) { dwgfx.Print((edentity[i].x * 8) - (ed.levx * 40 * 8) - 12, (edentity[i].y * 8) - (ed.levy * 30 * 8) - 8, "START", 255, 255, 255); } else { dwgfx.Print((edentity[i].x * 8) - (ed.levx * 40 * 8) - 12, (edentity[i].y * 8) - (ed.levy * 30 * 8) - 8, "START", 196, 196, 196); } break; case 17: //Roomtext if(edentity[i].scriptname.length() < 1) { fillboxabs(dwgfx, (edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8), 8, 8, dwgfx.getRGB(96, 96, 96)); } else { fillboxabs(dwgfx, (edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8), edentity[i].scriptname.length() * 8, 8, dwgfx.getRGB(96, 96, 96)); } dwgfx.Print((edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8), edentity[i].scriptname, 196, 196, 255 - help.glow); break; case 18: //Terminals dwgfx.drawsprite((edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8) + 8, 17, 96, 96, 96); fillboxabs(dwgfx, (edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8), 16, 24, dwgfx.getRGB(164, 164, 164)); if(ed.temp == i) { dwgfx.Print((edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8) - 8, edentity[i].scriptname, 210, 210, 255); } break; case 19: //Script Triggers fillboxabs(dwgfx, (edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8), edentity[i].p1 * 8, edentity[i].p2 * 8, dwgfx.getRGB(255, 164, 255)); fillboxabs(dwgfx, (edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8), 8, 8, dwgfx.getRGB(255, 255, 255)); if(ed.temp == i) { dwgfx.Print((edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8) - 8, edentity[i].scriptname, 210, 210, 255); } break; case 50: //Warp lines if(edentity[i].p1 >= 2) //Horizontal { int tx = edentity[i].x - (ed.levx * 40); int tx2 = edentity[i].x - (ed.levx * 40); int ty = edentity[i].y - (ed.levy * 30); while(ed.free(tx, ty) == 0) tx--; while(ed.free(tx2, ty) == 0) tx2++; tx++; fillboxabs(dwgfx, (tx * 8), (ty * 8) + 1, (tx2 - tx) * 8, 6, dwgfx.getRGB(255, 255, 194)); fillboxabs(dwgfx, (edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8), 8, 8, dwgfx.getRGB(255, 255, 164)); edentity[i].p2 = tx; edentity[i].p3 = (tx2 - tx) * 8; } else //Vertical { int tx = edentity[i].x - (ed.levx * 40); int ty = edentity[i].y - (ed.levy * 30); int ty2 = edentity[i].y - (ed.levy * 30); while(ed.free(tx, ty) == 0) ty--; while(ed.free(tx, ty2) == 0) ty2++; ty++; fillboxabs(dwgfx, (tx * 8) + 1, (ty * 8), 6, (ty2 - ty) * 8, dwgfx.getRGB(255, 255, 194)); fillboxabs(dwgfx, (edentity[i].x * 8) - (ed.levx * 40 * 8), (edentity[i].y * 8) - (ed.levy * 30 * 8), 8, 8, dwgfx.getRGB(255, 255, 164)); edentity[i].p2 = ty; edentity[i].p3 = (ty2 - ty) * 8; } break; } } //Need to also check warp point destinations if(edentity[i].t == 13 && ed.warpent != i) { tx = (edentity[i].p1 - (edentity[i].p1 % 40)) / 40; ty = (edentity[i].p2 - (edentity[i].p2 % 30)) / 30; if(tx == ed.levx && ty == ed.levy) { dwgfx.drawsprite((edentity[i].p1 * 8) - (ed.levx * 40 * 8), (edentity[i].p2 * 8) - (ed.levy * 30 * 8), 18 + (ed.entframe % 2), 64, 64, 64); fillboxabs(dwgfx, (edentity[i].p1 * 8) - (ed.levx * 40 * 8), (edentity[i].p2 * 8) - (ed.levy * 30 * 8), 16, 16, dwgfx.getRGB(64, 64, 96)); if(ed.tilex + (ed.levx * 40) == edentity[i].p1 && ed.tiley + (ed.levy * 30) == edentity[i].p2) { dwgfx.Print((edentity[i].p1 * 8) - (ed.levx * 40 * 8), (edentity[i].p2 * 8) - (ed.levy * 30 * 8) - 8, "(" + help.String(((edentity[i].x - int(edentity[i].x % 40)) / 40) + 1) + "," + help.String(((edentity[i].y - int(edentity[i].y % 30)) / 30) + 1) + ")", 190, 190, 225); } else { dwgfx.Print((edentity[i].p1 * 8) - (ed.levx * 40 * 8), (edentity[i].p2 * 8) - (ed.levy * 30 * 8) - 8, help.String(ed.findwarptoken(i)), 190, 190, 225); } } } } if(ed.boundarymod > 0) { if(ed.boundarymod == 1) { fillboxabs(dwgfx, ed.tilex * 8, ed.tiley * 8, 8, 8, dwgfx.getRGB(255 - (help.glow / 2), 191 + (help.glow), 210 + (help.glow / 2))); fillboxabs(dwgfx, (ed.tilex * 8) + 2, (ed.tiley * 8) + 2, 4, 4, dwgfx.getRGB(128 - (help.glow / 4), 100 + (help.glow / 2), 105 + (help.glow / 4))); } else if(ed.boundarymod == 2) { if((ed.tilex * 8) + 8 <= ed.boundx1 || (ed.tiley * 8) + 8 <= ed.boundy1) { fillboxabs(dwgfx, ed.boundx1, ed.boundy1, 8, 8, dwgfx.getRGB(255 - (help.glow / 2), 191 + (help.glow), 210 + (help.glow / 2))); fillboxabs(dwgfx, ed.boundx1 + 2, ed.boundy1 + 2, 4, 4, dwgfx.getRGB(128 - (help.glow / 4), 100 + (help.glow / 2), 105 + (help.glow / 4))); } else { fillboxabs(dwgfx, ed.boundx1, ed.boundy1, (ed.tilex * 8) + 8 - ed.boundx1, (ed.tiley * 8) + 8 - ed.boundy1, dwgfx.getRGB(255 - (help.glow / 2), 191 + (help.glow), 210 + (help.glow / 2))); fillboxabs(dwgfx, ed.boundx1 + 2, ed.boundy1 + 2, (ed.tilex * 8) + 8 - ed.boundx1 - 4, (ed.tiley * 8) + 8 - ed.boundy1 - 4, dwgfx.getRGB(128 - (help.glow / 4), 100 + (help.glow / 2), 105 + (help.glow / 4))); } } } else { //Draw boundaries int tmp = ed.levx + (ed.levy * ed.maxwidth); if(ed.level[tmp].enemyx1 != 0 && ed.level[tmp].enemyy1 != 0 && ed.level[tmp].enemyx2 != 320 && ed.level[tmp].enemyy2 != 240) { fillboxabs(dwgfx, ed.level[tmp].enemyx1, ed.level[tmp].enemyy1, ed.level[tmp].enemyx2 - ed.level[tmp].enemyx1, ed.level[tmp].enemyy2 - ed.level[tmp].enemyy1, dwgfx.getBGR(255 - (help.glow / 2), 64, 64)); } if(ed.level[tmp].platx1 != 0 && ed.level[tmp].platy1 != 0 && ed.level[tmp].platx2 != 320 && ed.level[tmp].platy2 != 240) { fillboxabs(dwgfx, ed.level[tmp].platx1, ed.level[tmp].platy1, ed.level[tmp].platx2 - ed.level[tmp].platx1, ed.level[tmp].platy2 - ed.level[tmp].platy1, dwgfx.getBGR(64, 64, 255 - (help.glow / 2))); } } //Draw connecting map guidelines //TODO //Draw Cursor switch(ed.drawmode) { case 0: case 1: case 2: case 9: case 10: case 12: //Single point fillboxabs(dwgfx, (ed.tilex * 8), (ed.tiley * 8), 8, 8, dwgfx.getRGB(200, 32, 32)); break; case 3: case 4: case 8: case 13: //2x2 fillboxabs(dwgfx, (ed.tilex * 8), (ed.tiley * 8), 16, 16, dwgfx.getRGB(200, 32, 32)); break; case 5: case 6: case 7: //Platform fillboxabs(dwgfx, (ed.tilex * 8), (ed.tiley * 8), 32, 8, dwgfx.getRGB(200, 32, 32)); break; case 14: //X if not on edge if(ed.tilex == 0 || ed.tilex == 39 || ed.tiley == 0 || ed.tiley == 29) { fillboxabs(dwgfx, (ed.tilex * 8), (ed.tiley * 8), 8, 8, dwgfx.getRGB(200, 32, 32)); } else { dwgfx.Print((ed.tilex * 8), (ed.tiley * 8), "X", 255, 0, 0); } break; case 11: case 15: case 16: //2x3 fillboxabs(dwgfx, (ed.tilex * 8), (ed.tiley * 8), 16, 24, dwgfx.getRGB(200, 32, 32)); break; } if(ed.drawmode < 3) { if(ed.zmod && ed.drawmode < 2) { fillboxabs(dwgfx, (ed.tilex * 8) - 8, (ed.tiley * 8) - 8, 24, 24, dwgfx.getRGB(200, 32, 32)); } else if(ed.xmod && ed.drawmode < 2) { fillboxabs(dwgfx, (ed.tilex * 8) - 16, (ed.tiley * 8) - 16, 24 + 16, 24 + 16, dwgfx.getRGB(200, 32, 32)); } } //If in directmode, show current directmode tile if(ed.level[ed.levx + (ed.levy * ed.maxwidth)].directmode == 1) { //Tile box for direct mode int t2 = 0; if(ed.dmtileeditor > 0) { ed.dmtileeditor--; if(ed.dmtileeditor <= 4) { t2 = (4 - ed.dmtileeditor) * 12; } //Draw five lines of the editor temp = ed.dmtile - (ed.dmtile % 40); temp -= 80; FillRect(dwgfx.backBuffer, 0, -t2, 320, 40, dwgfx.getRGB(0, 0, 0)); FillRect(dwgfx.backBuffer, 0, -t2 + 40, 320, 2, dwgfx.getRGB(255, 255, 255)); if(ed.level[ed.levx + (ed.levy * ed.maxwidth)].tileset == 0) { for(int i = 0; i < 40; i++) { dwgfx.drawtile(i * 8, 0 - t2, (temp + 1200 + i) % 1200); dwgfx.drawtile(i * 8, 8 - t2, (temp + 1200 + 40 + i) % 1200); dwgfx.drawtile(i * 8, 16 - t2, (temp + 1200 + 80 + i) % 1200); dwgfx.drawtile(i * 8, 24 - t2, (temp + 1200 + 120 + i) % 1200); dwgfx.drawtile(i * 8, 32 - t2, (temp + 1200 + 160 + i) % 1200); } } else { for(int i = 0; i < 40; i++) { dwgfx.drawtile2(i * 8, 0 - t2, (temp + 1200 + i) % 1200); dwgfx.drawtile2(i * 8, 8 - t2, (temp + 1200 + 40 + i) % 1200); dwgfx.drawtile2(i * 8, 16 - t2, (temp + 1200 + 80 + i) % 1200); dwgfx.drawtile2(i * 8, 24 - t2, (temp + 1200 + 120 + i) % 1200); dwgfx.drawtile2(i * 8, 32 - t2, (temp + 1200 + 160 + i) % 1200); } } //Highlight our little block fillboxabs(dwgfx, ((ed.dmtile % 40) * 8) - 2, 16 - 2, 12, 12, dwgfx.getRGB(196, 196, 255 - help.glow)); fillboxabs(dwgfx, ((ed.dmtile % 40) * 8) - 1, 16 - 1, 10, 10, dwgfx.getRGB(0, 0, 0)); } if(ed.dmtileeditor > 0 && t2 <= 30) { dwgfx.Print(2, 45 - t2, "Tile:", 196, 196, 255 - help.glow, false); dwgfx.Print(58, 45 - t2, help.String(ed.dmtile), 196, 196, 255 - help.glow, false); FillRect(dwgfx.backBuffer, 44, 44 - t2, 10, 10, dwgfx.getRGB(196, 196, 255 - help.glow)); FillRect(dwgfx.backBuffer, 45, 45 - t2, 8, 8, dwgfx.getRGB(0, 0, 0)); if(ed.level[ed.levx + (ed.levy * ed.maxwidth)].tileset == 0) { dwgfx.drawtile(45, 45 - t2, ed.dmtile); } else { dwgfx.drawtile2(45, 45 - t2, ed.dmtile); } } else { dwgfx.Print(2, 12, "Tile:", 196, 196, 255 - help.glow, false); dwgfx.Print(58, 12, help.String(ed.dmtile), 196, 196, 255 - help.glow, false); FillRect(dwgfx.backBuffer, 44, 11, 10, 10, dwgfx.getRGB(196, 196, 255 - help.glow)); FillRect(dwgfx.backBuffer, 45, 12, 8, 8, dwgfx.getRGB(0, 0, 0)); if(ed.level[ed.levx + (ed.levy * ed.maxwidth)].tileset == 0) { dwgfx.drawtile(45, 12, ed.dmtile); } else { dwgfx.drawtile2(45, 12, ed.dmtile); } } } //Draw GUI if(ed.boundarymod > 0) { if(ed.boundarymod == 1) { FillRect(dwgfx.backBuffer, 0, 230, 320, 240, dwgfx.getRGB(32, 32, 32)); FillRect(dwgfx.backBuffer, 0, 231, 320, 240, dwgfx.getRGB(0, 0, 0)); switch(ed.boundarytype) { case 0: dwgfx.Print(4, 232, "SCRIPT BOX: Click on top left", 255, 255, 255, false); break; case 1: dwgfx.Print(4, 232, "ENEMY BOUNDS: Click on top left", 255, 255, 255, false); break; case 2: dwgfx.Print(4, 232, "PLATFORM BOUNDS: Click on top left", 255, 255, 255, false); break; case 3: dwgfx.Print(4, 232, "COPY TILES: Click on top left", 255, 255, 255, false); break; default: dwgfx.Print(4, 232, "Click on top left", 255, 255, 255, false); break; } } else if(ed.boundarymod == 2) { FillRect(dwgfx.backBuffer, 0, 230, 320, 240, dwgfx.getRGB(32, 32, 32)); FillRect(dwgfx.backBuffer, 0, 231, 320, 240, dwgfx.getRGB(0, 0, 0)); switch(ed.boundarytype) { case 0: dwgfx.Print(4, 232, "SCRIPT BOX: Click on bottom right", 255, 255, 255, false); break; case 1: dwgfx.Print(4, 232, "ENEMY BOUNDS: Click on bottom right", 255, 255, 255, false); break; case 2: dwgfx.Print(4, 232, "PLATFORM BOUNDS: Click on bottom right", 255, 255, 255, false); break; case 3: dwgfx.Print(4, 232, "COPY TILES: Click on bottom right", 255, 255, 255, false); break; default: dwgfx.Print(4, 232, "Click on bottom right", 255, 255, 255, false); break; } } } else if(ed.scripteditmod) { //Elaborate C64 BASIC menu goes here! FillRect(dwgfx.backBuffer, 0, 0, 320, 240, dwgfx.getBGR(123, 111, 218)); FillRect(dwgfx.backBuffer, 14, 16, 292, 208, dwgfx.getRGB(162, 48, 61)); switch(ed.scripthelppage) { case 0: dwgfx.Print(16, 28, "**** VVVVVV SCRIPT EDITOR ****", 123, 111, 218, true); dwgfx.Print(16, 44, "PRESS ESC TO RETURN TO MENU", 123, 111, 218, true); //dwgfx.Print(16,60,"READY.", 123, 111, 218, false); if(ed.numhooks > 0) { for(int i = 0; i < 9; i++) { if(ed.hookmenupage + i < ed.numhooks) { if(ed.hookmenupage + i == ed.hookmenu) { std::string tstring = "> " + ed.hooklist[(ed.numhooks - 1) - (ed.hookmenupage + i)] + " <"; std::transform(tstring.begin(), tstring.end(), tstring.begin(), ::toupper); dwgfx.Print(16, 68 + (i * 16), tstring, 123, 111, 218, true); } else { dwgfx.Print(16, 68 + (i * 16), ed.hooklist[(ed.numhooks - 1) - (ed.hookmenupage + i)], 123, 111, 218, true); } } } } else { dwgfx.Print(16, 110, "NO SCRIPT IDS FOUND", 123, 111, 218, true); dwgfx.Print(16, 130, "CREATE A SCRIPT WITH EITHER", 123, 111, 218, true); dwgfx.Print(16, 140, "THE TERMINAL OR SCRIPT BOX TOOLS", 123, 111, 218, true); } break; case 1: //Current scriptname FillRect(dwgfx.backBuffer, 14, 226, 292, 12, dwgfx.getRGB(162, 48, 61)); dwgfx.Print(16, 228, "CURRENT SCRIPT: " + ed.sbscript, 123, 111, 218, true); //Draw text for(int i = 0; i < 25; i++) { if(i + ed.pagey < 500) { dwgfx.Print(16, 20 + (i * 8), ed.sb[i + ed.pagey], 123, 111, 218, false); } } //Draw cursor if(ed.entframe < 2) { dwgfx.Print(16 + (ed.sbx * 8), 20 + (ed.sby * 8), "_", 123, 111, 218, false); } break; } } else if(ed.settingsmod) { if(!game.colourblindmode) dwgfx.drawtowerbackgroundsolo(map); int tr = map.r - (help.glow / 4) - int(fRandom() * 4); int tg = map.g - (help.glow / 4) - int(fRandom() * 4); int tb = map.b - (help.glow / 4) - int(fRandom() * 4); if(tr < 0) tr = 0; if(tr > 255) tr = 255; if(tg < 0) tg = 0; if(tg > 255) tg = 255; if(tb < 0) tb = 0; if(tb > 255) tb = 255; if(game.currentmenuname == "ed_settings") { dwgfx.bigprint(-1, 75, "Map Settings", tr, tg, tb, true); } else if(game.currentmenuname == "ed_desc") { if(ed.titlemod) { if(ed.entframe < 2) { dwgfx.bigprint(-1, 35, key.keybuffer + "_", tr, tg, tb, true); } else { dwgfx.bigprint(-1, 35, key.keybuffer + " ", tr, tg, tb, true); } } else { dwgfx.bigprint(-1, 35, EditorData::GetInstance().title, tr, tg, tb, true); } if(ed.creatormod) { if(ed.entframe < 2) { dwgfx.Print(-1, 60, "by " + key.keybuffer + "_", tr, tg, tb, true); } else { dwgfx.Print(-1, 60, "by " + key.keybuffer + " ", tr, tg, tb, true); } } else { dwgfx.Print(-1, 60, "by " + EditorData::GetInstance().creator, tr, tg, tb, true); } if(ed.websitemod) { if(ed.entframe < 2) { dwgfx.Print(-1, 70, key.keybuffer + "_", tr, tg, tb, true); } else { dwgfx.Print(-1, 70, key.keybuffer + " ", tr, tg, tb, true); } } else { dwgfx.Print(-1, 70, ed.website, tr, tg, tb, true); } if(ed.desc1mod) { if(ed.entframe < 2) { dwgfx.Print(-1, 90, key.keybuffer + "_", tr, tg, tb, true); } else { dwgfx.Print(-1, 90, key.keybuffer + " ", tr, tg, tb, true); } } else { dwgfx.Print(-1, 90, ed.Desc1, tr, tg, tb, true); } if(ed.desc2mod) { if(ed.entframe < 2) { dwgfx.Print(-1, 100, key.keybuffer + "_", tr, tg, tb, true); } else { dwgfx.Print(-1, 100, key.keybuffer + " ", tr, tg, tb, true); } } else { dwgfx.Print(-1, 100, ed.Desc2, tr, tg, tb, true); } if(ed.desc3mod) { if(ed.entframe < 2) { dwgfx.Print(-1, 110, key.keybuffer + "_", tr, tg, tb, true); } else { dwgfx.Print(-1, 110, key.keybuffer + " ", tr, tg, tb, true); } } else { dwgfx.Print(-1, 110, ed.Desc3, tr, tg, tb, true); } } else if(game.currentmenuname == "ed_music") { dwgfx.bigprint(-1, 65, "Map Music", tr, tg, tb, true); dwgfx.Print(-1, 85, "Current map music:", tr, tg, tb, true); switch(ed.levmusic) { case 0: dwgfx.Print(-1, 120, "No background music", tr, tg, tb, true); break; case 1: dwgfx.Print(-1, 120, "1: Pushing Onwards", tr, tg, tb, true); break; case 2: dwgfx.Print(-1, 120, "2: Positive Force", tr, tg, tb, true); break; case 3: dwgfx.Print(-1, 120, "3: Potential For Anything", tr, tg, tb, true); break; case 4: dwgfx.Print(-1, 120, "4: Passion For Exploring", tr, tg, tb, true); break; case 6: dwgfx.Print(-1, 120, "5: Presenting VVVVVV", tr, tg, tb, true); break; case 8: dwgfx.Print(-1, 120, "6: Predestined Fate", tr, tg, tb, true); break; case 10: dwgfx.Print(-1, 120, "7: Popular Potpourri", tr, tg, tb, true); break; case 11: dwgfx.Print(-1, 120, "8: Pipe Dream", tr, tg, tb, true); break; case 12: dwgfx.Print(-1, 120, "9: Pressure Cooker", tr, tg, tb, true); break; case 13: dwgfx.Print(-1, 120, "10: Paced Energy", tr, tg, tb, true); break; case 14: dwgfx.Print(-1, 120, "11: Piercing The Sky", tr, tg, tb, true); break; default: dwgfx.Print(-1, 120, "?: something else", tr, tg, tb, true); break; } } else if(game.currentmenuname == "ed_quit") { dwgfx.bigprint(-1, 90, "Save before", tr, tg, tb, true); dwgfx.bigprint(-1, 110, "quiting?", tr, tg, tb, true); } dwgfx.drawmenu(game, tr, tg, tb, 15); /* dwgfx.Print(4, 224, "Enter name to save map as:", 255,255,255, false); if(ed.entframe<2){ dwgfx.Print(4, 232, ed.filename+"_", 196, 196, 255 - help.glow, true); }else{ dwgfx.Print(4, 232, ed.filename+" ", 196, 196, 255 - help.glow, true); } */ } else if(ed.scripttextmod) { FillRect(dwgfx.backBuffer, 0, 221, 320, 240, dwgfx.getRGB(32, 32, 32)); FillRect(dwgfx.backBuffer, 0, 222, 320, 240, dwgfx.getRGB(0, 0, 0)); dwgfx.Print(4, 224, "Enter script id name:", 255, 255, 255, false); if(ed.entframe < 2) { dwgfx.Print(4, 232, edentity[ed.scripttextent].scriptname + "_", 196, 196, 255 - help.glow, true); } else { dwgfx.Print(4, 232, edentity[ed.scripttextent].scriptname + " ", 196, 196, 255 - help.glow, true); } } else if(ed.savemod) { FillRect(dwgfx.backBuffer, 0, 221, 320, 240, dwgfx.getRGB(32, 32, 32)); FillRect(dwgfx.backBuffer, 0, 222, 320, 240, dwgfx.getRGB(0, 0, 0)); dwgfx.Print(4, 224, "Enter filename to save map as:", 255, 255, 255, false); if(ed.entframe < 2) { dwgfx.Print(4, 232, ed.filename + "_", 196, 196, 255 - help.glow, true); } else { dwgfx.Print(4, 232, ed.filename + " ", 196, 196, 255 - help.glow, true); } } else if(ed.loadmod) { FillRect(dwgfx.backBuffer, 0, 221, 320, 240, dwgfx.getRGB(32, 32, 32)); FillRect(dwgfx.backBuffer, 0, 222, 320, 240, dwgfx.getRGB(0, 0, 0)); dwgfx.Print(4, 224, "Enter map filename to load:", 255, 255, 255, false); if(ed.entframe < 2) { dwgfx.Print(4, 232, ed.filename + "_", 196, 196, 255 - help.glow, true); } else { dwgfx.Print(4, 232, ed.filename + " ", 196, 196, 255 - help.glow, true); } } else if(ed.roomnamemod) { FillRect(dwgfx.backBuffer, 0, 221, 320, 240, dwgfx.getRGB(32, 32, 32)); FillRect(dwgfx.backBuffer, 0, 222, 320, 240, dwgfx.getRGB(0, 0, 0)); dwgfx.Print(4, 224, "Enter new room name:", 255, 255, 255, false); if(ed.entframe < 2) { dwgfx.Print(4, 232, ed.level[ed.levx + (ed.levy * ed.maxwidth)].roomname + "_", 196, 196, 255 - help.glow, true); } else { dwgfx.Print(4, 232, ed.level[ed.levx + (ed.levy * ed.maxwidth)].roomname + " ", 196, 196, 255 - help.glow, true); } } else if(ed.roomtextmod) { FillRect(dwgfx.backBuffer, 0, 221, 320, 240, dwgfx.getRGB(32, 32, 32)); FillRect(dwgfx.backBuffer, 0, 222, 320, 240, dwgfx.getRGB(0, 0, 0)); dwgfx.Print(4, 224, "Enter text string:", 255, 255, 255, false); if(ed.entframe < 2) { dwgfx.Print(4, 232, edentity[ed.roomtextent].scriptname + "_", 196, 196, 255 - help.glow, true); } else { dwgfx.Print(4, 232, edentity[ed.roomtextent].scriptname + " ", 196, 196, 255 - help.glow, true); } } else if(ed.warpmod) { //placing warp token FillRect(dwgfx.backBuffer, 0, 221, 320, 240, dwgfx.getRGB(32, 32, 32)); FillRect(dwgfx.backBuffer, 0, 222, 320, 240, dwgfx.getRGB(0, 0, 0)); dwgfx.Print(4, 224, "Left click to place warp destination", 196, 196, 255 - help.glow, false); dwgfx.Print(4, 232, "Right click to cancel", 196, 196, 255 - help.glow, false); } else { if(ed.spacemod) { FillRect(dwgfx.backBuffer, 0, 208, 320, 240, dwgfx.getRGB(32, 32, 32)); FillRect(dwgfx.backBuffer, 0, 209, 320, 240, dwgfx.getRGB(0, 0, 0)); //Draw little icons for each thingy int tx = 6, ty = 211, tg = 32; if(ed.spacemenu == 0) { for(int i = 0; i < 10; i++) { FillRect(dwgfx.backBuffer, 4 + (i * tg), 209, 20, 20, dwgfx.getRGB(32, 32, 32)); } FillRect(dwgfx.backBuffer, 4 + (ed.drawmode * tg), 209, 20, 20, dwgfx.getRGB(64, 64, 64)); //0: dwgfx.drawtile(tx, ty, 83); dwgfx.drawtile(tx + 8, ty, 83); dwgfx.drawtile(tx, ty + 8, 83); dwgfx.drawtile(tx + 8, ty + 8, 83); //1: tx += tg; dwgfx.drawtile(tx, ty, 680); dwgfx.drawtile(tx + 8, ty, 680); dwgfx.drawtile(tx, ty + 8, 680); dwgfx.drawtile(tx + 8, ty + 8, 680); //2: tx += tg; dwgfx.drawtile(tx + 4, ty + 4, 8); //3: tx += tg; dwgfx.drawsprite(tx, ty, 22, 196, 196, 196); //4: tx += tg; dwgfx.drawsprite(tx, ty, 21, 196, 196, 196); //5: tx += tg; dwgfx.drawtile(tx, ty + 4, 3); dwgfx.drawtile(tx + 8, ty + 4, 4); //6: tx += tg; dwgfx.drawtile(tx, ty + 4, 24); dwgfx.drawtile(tx + 8, ty + 4, 24); //7: tx += tg; dwgfx.drawtile(tx, ty + 4, 1); dwgfx.drawtile(tx + 8, ty + 4, 1); //8: tx += tg; dwgfx.drawsprite(tx, ty, 78 + ed.entframe, 196, 196, 196); //9: tx += tg; FillRect(dwgfx.backBuffer, tx + 2, ty + 8, 12, 1, dwgfx.getRGB(255, 255, 255)); for(int i = 0; i < 9; i++) { fillboxabs(dwgfx, 4 + (i * tg), 209, 20, 20, dwgfx.getRGB(96, 96, 96)); dwgfx.Print(22 + (i * tg) - 4, 225 - 4, help.String(i + 1), 164, 164, 164, false); } if(ed.drawmode == 9) dwgfx.Print(22 + (ed.drawmode * tg) - 4, 225 - 4, "0", 255, 255, 255, false); fillboxabs(dwgfx, 4 + (9 * tg), 209, 20, 20, dwgfx.getRGB(96, 96, 96)); dwgfx.Print(22 + (9 * tg) - 4, 225 - 4, "0", 164, 164, 164, false); fillboxabs(dwgfx, 4 + (ed.drawmode * tg), 209, 20, 20, dwgfx.getRGB(200, 200, 200)); if(ed.drawmode < 9) { dwgfx .Print(22 + (ed.drawmode * tg) - 4, 225 - 4, help.String(ed.drawmode + 1), 255, 255, 255, false); } dwgfx.Print(4, 232, "1/2", 196, 196, 255 - help.glow, false); } else { for(int i = 0; i < 7; i++) { FillRect(dwgfx.backBuffer, 4 + (i * tg), 209, 20, 20, dwgfx.getRGB(32, 32, 32)); } FillRect(dwgfx.backBuffer, 4 + ((ed.drawmode - 10) * tg), 209, 20, 20, dwgfx.getRGB(64, 64, 64)); //10: dwgfx.Print(tx, ty, "A", 196, 196, 255 - help.glow, false); dwgfx.Print(tx + 8, ty, "B", 196, 196, 255 - help.glow, false); dwgfx.Print(tx, ty + 8, "C", 196, 196, 255 - help.glow, false); dwgfx.Print(tx + 8, ty + 8, "D", 196, 196, 255 - help.glow, false); //11: tx += tg; dwgfx.drawsprite(tx, ty, 17, 196, 196, 196); //12: tx += tg; fillboxabs(dwgfx, tx + 4, ty + 4, 8, 8, dwgfx.getRGB(96, 96, 96)); //13: tx += tg; dwgfx.drawsprite(tx, ty, 18 + (ed.entframe % 2), 196, 196, 196); //14: tx += tg; FillRect(dwgfx.backBuffer, tx + 6, ty + 2, 4, 12, dwgfx.getRGB(255, 255, 255)); //15: tx += tg; dwgfx.drawsprite(tx, ty, 186, 75, 75, 255 - help.glow / 4 - (fRandom() * 20)); //16: tx += tg; dwgfx .drawsprite(tx, ty, 184, 160 - help.glow / 2 - (fRandom() * 20), 200 - help.glow / 2, 220 - help.glow); if(ed.drawmode == 10) dwgfx.Print(22 + ((ed.drawmode - 10) * tg) - 4, 225 - 4, "R", 255, 255, 255, false); if(ed.drawmode == 11) dwgfx.Print(22 + ((ed.drawmode - 10) * tg) - 4, 225 - 4, "T", 255, 255, 255, false); if(ed.drawmode == 12) dwgfx.Print(22 + ((ed.drawmode - 10) * tg) - 4, 225 - 4, "Y", 255, 255, 255, false); if(ed.drawmode == 13) dwgfx.Print(22 + ((ed.drawmode - 10) * tg) - 4, 225 - 4, "U", 255, 255, 255, false); if(ed.drawmode == 14) dwgfx.Print(22 + ((ed.drawmode - 10) * tg) - 4, 225 - 4, "I", 255, 255, 255, false); if(ed.drawmode == 15) dwgfx.Print(22 + ((ed.drawmode - 10) * tg) - 4, 225 - 4, "O", 255, 255, 255, false); if(ed.drawmode == 16) dwgfx.Print(22 + ((ed.drawmode - 10) * tg) - 4, 225 - 4, "P", 255, 255, 255, false); fillboxabs(dwgfx, 4 + (0 * tg), 209, 20, 20, dwgfx.getRGB(96, 96, 96)); dwgfx.Print(22 + (0 * tg) - 4, 225 - 4, "R", 164, 164, 164, false); fillboxabs(dwgfx, 4 + (1 * tg), 209, 20, 20, dwgfx.getRGB(96, 96, 96)); dwgfx.Print(22 + (1 * tg) - 4, 225 - 4, "T", 164, 164, 164, false); fillboxabs(dwgfx, 4 + (2 * tg), 209, 20, 20, dwgfx.getRGB(96, 96, 96)); dwgfx.Print(22 + (2 * tg) - 4, 225 - 4, "Y", 164, 164, 164, false); fillboxabs(dwgfx, 4 + (3 * tg), 209, 20, 20, dwgfx.getRGB(96, 96, 96)); dwgfx.Print(22 + (3 * tg) - 4, 225 - 4, "U", 164, 164, 164, false); fillboxabs(dwgfx, 4 + (4 * tg), 209, 20, 20, dwgfx.getRGB(96, 96, 96)); dwgfx.Print(22 + (4 * tg) - 4, 225 - 4, "I", 164, 164, 164, false); fillboxabs(dwgfx, 4 + (5 * tg), 209, 20, 20, dwgfx.getRGB(96, 96, 96)); dwgfx.Print(22 + (5 * tg) - 4, 225 - 4, "O", 164, 164, 164, false); fillboxabs(dwgfx, 4 + (6 * tg), 209, 20, 20, dwgfx.getRGB(96, 96, 96)); dwgfx.Print(22 + (6 * tg) - 4, 225 - 4, "P", 164, 164, 164, false); dwgfx.Print(4, 232, "2/2", 196, 196, 255 - help.glow, false); } dwgfx.Print(128, 232, "< and > keys change tool", 196, 196, 255 - help.glow, false); FillRect(dwgfx.backBuffer, 0, 198, 120, 10, dwgfx.getRGB(32, 32, 32)); FillRect(dwgfx.backBuffer, 0, 199, 119, 9, dwgfx.getRGB(0, 0, 0)); switch(ed.drawmode) { case 0: dwgfx.Print(2, 199, "1: Walls", 196, 196, 255 - help.glow); break; case 1: dwgfx.Print(2, 199, "2: Backing", 196, 196, 255 - help.glow); break; case 2: dwgfx.Print(2, 199, "3: Spikes", 196, 196, 255 - help.glow); break; case 3: dwgfx.Print(2, 199, "4: Trinkets", 196, 196, 255 - help.glow); break; case 4: dwgfx.Print(2, 199, "5: Checkpoint", 196, 196, 255 - help.glow); break; case 5: dwgfx.Print(2, 199, "6: Disappear", 196, 196, 255 - help.glow); break; case 6: dwgfx.Print(2, 199, "7: Conveyors", 196, 196, 255 - help.glow); break; case 7: dwgfx.Print(2, 199, "8: Moving", 196, 196, 255 - help.glow); break; case 8: dwgfx.Print(2, 199, "9: Enemies", 196, 196, 255 - help.glow); break; case 9: dwgfx.Print(2, 199, "0: Grav Line", 196, 196, 255 - help.glow); break; case 10: dwgfx.Print(2, 199, "R: Roomtext", 196, 196, 255 - help.glow); break; case 11: dwgfx.Print(2, 199, "T: Terminal", 196, 196, 255 - help.glow); break; case 12: dwgfx.Print(2, 199, "Y: Script Box", 196, 196, 255 - help.glow); break; case 13: dwgfx.Print(2, 199, "U: Warp Token", 196, 196, 255 - help.glow); break; case 14: dwgfx.Print(2, 199, "I: Warp Lines", 196, 196, 255 - help.glow); break; case 15: dwgfx.Print(2, 199, "O: Crewmate", 196, 196, 255 - help.glow); break; case 16: dwgfx.Print(2, 199, "P: Start Point", 196, 196, 255 - help.glow); break; } FillRect(dwgfx.backBuffer, 260, 198, 80, 10, dwgfx.getRGB(32, 32, 32)); FillRect(dwgfx.backBuffer, 261, 199, 80, 9, dwgfx.getRGB(0, 0, 0)); dwgfx.Print(268, 199, "(" + help.String(ed.levx + 1) + "," + help.String(ed.levy + 1) + ")", 196, 196, 255 - help.glow, false); } else { //FillRect(dwgfx.backBuffer, 0,230,72,240, dwgfx.RGB(32,32,32)); //FillRect(dwgfx.backBuffer, 0,231,71,240, dwgfx.RGB(0,0,0)); if(ed.level[ed.levx + (ed.maxwidth * ed.levy)].roomname != "") { if(ed.tiley < 28) { if(ed.roomnamehide > 0) ed.roomnamehide--; FillRect(dwgfx.backBuffer, 0, 230 + ed.roomnamehide, 320, 10, dwgfx.getRGB(0, 0, 0)); dwgfx.Print(5, 231 + ed.roomnamehide, ed.level[ed.levx + (ed.maxwidth * ed.levy)].roomname, 196, 196, 255 - help.glow, true); } else { if(ed.roomnamehide < 12) ed.roomnamehide++; FillRect(dwgfx.backBuffer, 0, 230 + ed.roomnamehide, 320, 10, dwgfx.getRGB(0, 0, 0)); dwgfx.Print(5, 231 + ed.roomnamehide, ed.level[ed.levx + (ed.maxwidth * ed.levy)].roomname, 196, 196, 255 - help.glow, true); } dwgfx.Print(4, 222, "SPACE ^ SHIFT ^", 196, 196, 255 - help.glow, false); dwgfx.Print(268, 222, "(" + help.String(ed.levx + 1) + "," + help.String(ed.levy + 1) + ")", 196, 196, 255 - help.glow, false); } else { dwgfx.Print(4, 232, "SPACE ^ SHIFT ^", 196, 196, 255 - help.glow, false); dwgfx.Print(268, 232, "(" + help.String(ed.levx + 1) + "," + help.String(ed.levy + 1) + ")", 196, 196, 255 - help.glow, false); } } if(ed.shiftmenu) { fillboxabs(dwgfx, 0, 127, 161 + 8, 140, dwgfx.getRGB(64, 64, 64)); FillRect(dwgfx.backBuffer, 0, 128, 160 + 8, 140, dwgfx.getRGB(0, 0, 0)); dwgfx.Print(4, 130, "F1: Change Tileset", 164, 164, 164, false); dwgfx.Print(4, 140, "F2: Change Colour", 164, 164, 164, false); dwgfx.Print(4, 150, "F3: Change Enemies", 164, 164, 164, false); dwgfx.Print(4, 160, "F4: Enemy Bounds", 164, 164, 164, false); dwgfx.Print(4, 170, "F5: Platform Bounds", 164, 164, 164, false); dwgfx.Print(4, 190, "F10: Direct Mode", 164, 164, 164, false); dwgfx.Print(4, 210, "W: Change Warp Dir", 164, 164, 164, false); dwgfx.Print(4, 220, "E: Change Roomname", 164, 164, 164, false); fillboxabs(dwgfx, 220, 207, 100, 60, dwgfx.getRGB(64, 64, 64)); FillRect(dwgfx.backBuffer, 221, 208, 160, 60, dwgfx.getRGB(0, 0, 0)); dwgfx.Print(224, 210, "S: Save Map", 164, 164, 164, false); dwgfx.Print(224, 220, "L: Load Map", 164, 164, 164, false); } } if(!ed.settingsmod && !ed.scripteditmod) { //Same as above, without borders switch(ed.drawmode) { case 0: dwgfx.Print(2, 2, "1: Walls", 196, 196, 255 - help.glow); break; case 1: dwgfx.Print(2, 2, "2: Backing", 196, 196, 255 - help.glow); break; case 2: dwgfx.Print(2, 2, "3: Spikes", 196, 196, 255 - help.glow); break; case 3: dwgfx.Print(2, 2, "4: Trinkets", 196, 196, 255 - help.glow); break; case 4: dwgfx.Print(2, 2, "5: Checkpoint", 196, 196, 255 - help.glow); break; case 5: dwgfx.Print(2, 2, "6: Disappear", 196, 196, 255 - help.glow); break; case 6: dwgfx.Print(2, 2, "7: Conveyors", 196, 196, 255 - help.glow); break; case 7: dwgfx.Print(2, 2, "8: Moving", 196, 196, 255 - help.glow); break; case 8: dwgfx.Print(2, 2, "9: Enemies", 196, 196, 255 - help.glow); break; case 9: dwgfx.Print(2, 2, "0: Grav Line", 196, 196, 255 - help.glow); break; case 10: dwgfx.Print(2, 2, "R: Roomtext", 196, 196, 255 - help.glow); break; case 11: dwgfx.Print(2, 2, "T: Terminal", 196, 196, 255 - help.glow); break; case 12: dwgfx.Print(2, 2, "Y: Script Box", 196, 196, 255 - help.glow); break; case 13: dwgfx.Print(2, 2, "U: Warp Token", 196, 196, 255 - help.glow); break; case 14: dwgfx.Print(2, 2, "I: Warp Lines", 196, 196, 255 - help.glow); break; case 15: dwgfx.Print(2, 2, "O: Crewmate", 196, 196, 255 - help.glow); break; case 16: dwgfx.Print(2, 2, "P: Start Point", 196, 196, 255 - help.glow); break; } //dwgfx.Print(254, 2, "F1: HELP", 196, 196, 255 - help.glow, false); } /* for(int i=0; i<script.customscript.size(); i++){ dwgfx.Print(0,i*8,script.customscript[i],255,255,255); } dwgfx.Print(0,8*script.customscript.size(),help.String(script.customscript.size()),255,255,255); for(int i=0; i<ed.numhooks; i++){ dwgfx.Print(260,i*8,ed.hooklist[i],255,255,255); } dwgfx.Print(260,8*ed.numhooks,help.String(ed.numhooks),255,255,255); */ if(ed.notedelay > 0) { FillRect(dwgfx.backBuffer, 0, 115, 320, 18, dwgfx.getRGB(92, 92, 92)); FillRect(dwgfx.backBuffer, 0, 116, 320, 16, dwgfx.getRGB(0, 0, 0)); dwgfx.Print(0, 121, ed.note, 196 - ((45 - ed.notedelay) * 4), 196 - ((45 - ed.notedelay) * 4), 196 - ((45 - ed.notedelay) * 4), true); } if(game.test) { dwgfx.Print(5, 5, game.teststring, 196, 196, 255 - help.glow, false); } dwgfx.drawfade(); if(game.flashlight > 0 && !game.noflashingmode) { game.flashlight--; dwgfx.flashlight(); } if(game.screenshake > 0 && !game.noflashingmode) { game.screenshake--; dwgfx.screenshake(); } else { dwgfx.render(); } //dwgfx.backbuffer.unlock(); } void editorlogic(Graphics & dwgfx, Game & game, musicclass & music, mapclass & map, UtilityClass & help) { //Misc help.updateglow(); map.bypos -= 2; map.bscroll = -2; ed.entframedelay--; if(ed.entframedelay <= 0) { ed.entframe = (ed.entframe + 1) % 4; ed.entframedelay = 8; } if(ed.notedelay > 0) { ed.notedelay--; } if(dwgfx.fademode == 1) { //Return to game map.nexttowercolour(); map.colstate = 10; game.gamestate = 1; dwgfx.fademode = 4; music.stopmusic(); music.play(6); map.nexttowercolour(); ed.settingsmod = false; dwgfx.backgrounddrawn = false; game.createmenu("mainmenu"); } } void editorinput(KeyPoll & key, Graphics & dwgfx, Game & game, mapclass & map, entityclass & obj, UtilityClass & help, musicclass & music) { //TODO Mouse Input! game.mx = (float)key.mx; game.my = (float)key.my; ed.tilex = (game.mx - (game.mx % 8)) / 8; ed.tiley = (game.my - (game.my % 8)) / 8; game.press_left = false; game.press_right = false; game.press_action = false; game.press_map = false; if(key.isDown(KEYBOARD_LEFT) || key.isDown(KEYBOARD_a)) { game.press_left = true; } if(key.isDown(KEYBOARD_RIGHT) || key.isDown(KEYBOARD_d)) { game.press_right = true; } if(key.isDown(KEYBOARD_z) || key.isDown(KEYBOARD_SPACE) || key.isDown(KEYBOARD_v)) { // || key.isDown(KEYBOARD_UP) || key.isDown(KEYBOARD_DOWN) game.press_action = true; }; if(key.isDown(KEYBOARD_ENTER)) game.press_map = true; if(key.isDown(27) && !ed.settingskey) { ed.settingskey = true; if(ed.textentry) { key.disabletextentry(); ed.roomnamemod = false; ed.loadmod = false; ed.savemod = false; ed.textentry = false; ed.titlemod = false; ed.desc1mod = false; ed.desc2mod = false; ed.desc3mod = false; ed.websitemod = false; ed.creatormod = false; if(ed.scripttextmod) { ed.scripttextmod = false; removeedentity(ed.scripttextmod); } ed.shiftmenu = false; ed.shiftkey = false; } else if(ed.boundarymod > 0) { ed.boundarymod = 0; } else { ed.settingsmod = !ed.settingsmod; dwgfx.backgrounddrawn = false; game.createmenu("ed_settings"); map.nexttowercolour(); } } if(!key.isDown(27)) { ed.settingskey = false; } if(key.keymap[SDLK_LCTRL] || key.keymap[SDLK_RCTRL]) { if(key.leftbutton) key.rightbutton = true; } if(ed.scripteditmod) { if(ed.scripthelppage == 0) { //hook select menu if(ed.keydelay > 0) ed.keydelay--; if(key.keymap[SDLK_UP] && ed.keydelay <= 0) { ed.keydelay = 6; ed.hookmenu--; } if(key.keymap[SDLK_DOWN] && ed.keydelay <= 0) { ed.keydelay = 6; ed.hookmenu++; } if(ed.hookmenu >= ed.numhooks) { ed.hookmenu = ed.numhooks - 1; } if(ed.hookmenu < 0) ed.hookmenu = 0; if(ed.hookmenu < ed.hookmenupage) { ed.hookmenupage = ed.hookmenu; } if(ed.hookmenu >= ed.hookmenupage + 9) { ed.hookmenupage = ed.hookmenu + 8; } if(!key.keymap[SDLK_BACKSPACE]) ed.deletekeyheld = 0; if(key.keymap[SDLK_BACKSPACE] && ed.deletekeyheld == 0) { ed.deletekeyheld = 1; music.playef(2); ed.removehook(ed.hooklist[(ed.numhooks - 1) - ed.hookmenu]); } if(!game.press_action && !game.press_left && !game.press_right && !key.keymap[SDLK_UP] && !key.keymap[SDLK_DOWN] && !key.isDown(27)) game.jumpheld = false; if(!game.jumpheld) { if(game.press_action || game.press_left || game.press_right || game.press_map || key.keymap[SDLK_UP] || key.keymap[SDLK_DOWN] || key.isDown(27)) { game.jumpheld = true; } if((game.press_action || game.press_map) && ed.numhooks > 0) { game.mapheld = true; ed.scripthelppage = 1; key.keybuffer = ""; ed.sbscript = ed.hooklist[(ed.numhooks - 1) - ed.hookmenu]; ed.loadhookineditor(ed.sbscript); ed.sby = ed.sblength - 1; ed.pagey = 0; while(ed.sby >= 20) { ed.pagey++; ed.sby--; } key.keybuffer = ed.sb[ed.pagey + ed.sby]; ed.sbx = ed.sb[ed.pagey + ed.sby].length(); } if(key.isDown(27)) { ed.scripteditmod = false; ed.settingsmod = false; } } } else if(ed.scripthelppage == 1) { //Script editor! if(key.isDown(27)) { ed.scripthelppage = 0; game.jumpheld = true; //save the script for use again! ed.addhook(ed.sbscript); } if(ed.keydelay > 0) ed.keydelay--; if(key.keymap[SDLK_UP] && ed.keydelay <= 0) { ed.keydelay = 6; ed.sby--; if(ed.sby <= 5) { if(ed.pagey > 0) { ed.pagey--; ed.sby++; } else { if(ed.sby < 0) ed.sby = 0; } } key.keybuffer = ed.sb[ed.pagey + ed.sby]; } if(key.keymap[SDLK_DOWN] && ed.keydelay <= 0) { ed.keydelay = 6; if(ed.sby + ed.pagey < ed.sblength) { ed.sby++; if(ed.sby >= 20) { ed.pagey++; ed.sby--; } } key.keybuffer = ed.sb[ed.pagey + ed.sby]; } if(key.pressedbackspace && ed.sb[ed.pagey + ed.sby] == "") { //Remove this line completely ed.removeline(ed.pagey + ed.sby); ed.sby--; if(ed.sby <= 5) { if(ed.pagey > 0) { ed.pagey--; ed.sby++; } else { if(ed.sby < 0) ed.sby = 0; } } key.keybuffer = ed.sb[ed.pagey + ed.sby]; } ed.sb[ed.pagey + ed.sby] = key.keybuffer; ed.sbx = ed.sb[ed.pagey + ed.sby].length(); if(!game.press_map && !key.isDown(27)) game.mapheld = false; if(!game.mapheld) { if(game.press_map) { game.mapheld = true; //Continue to next line if(ed.sby + ed.pagey >= ed.sblength) //we're on the last line { ed.sby++; if(ed.sby >= 20) { ed.pagey++; ed.sby--; } if(ed.sby + ed.pagey >= ed.sblength) ed.sblength = ed.sby + ed.pagey; key.keybuffer = ed.sb[ed.pagey + ed.sby]; ed.sbx = ed.sb[ed.pagey + ed.sby].length(); } else { //We're not, insert a line instead ed.sby++; if(ed.sby >= 20) { ed.pagey++; ed.sby--; } ed.insertline(ed.sby + ed.pagey); key.keybuffer = ""; ed.sbx = 0; } } } } } else if(ed.textentry) { if(ed.roomnamemod) { ed.level[ed.levx + (ed.levy * ed.maxwidth)].roomname = key.keybuffer; } else if(ed.savemod) { ed.filename = key.keybuffer; } else if(ed.loadmod) { ed.filename = key.keybuffer; } else if(ed.roomtextmod) { edentity[ed.roomtextent].scriptname = key.keybuffer; } else if(ed.scripttextmod) { edentity[ed.scripttextent].scriptname = key.keybuffer; } else if(ed.titlemod) { EditorData::GetInstance().title = key.keybuffer; } else if(ed.creatormod) { EditorData::GetInstance().creator = key.keybuffer; } else if(ed.websitemod) { ed.website = key.keybuffer; } else if(ed.desc1mod) { ed.Desc1 = key.keybuffer; } else if(ed.desc2mod) { ed.Desc2 = key.keybuffer; } else if(ed.desc3mod) { ed.Desc3 = key.keybuffer; } if(!game.press_map && !key.isDown(27)) game.mapheld = false; if(!game.mapheld) { if(game.press_map) { game.mapheld = true; if(ed.roomnamemod) { ed.level[ed.levx + (ed.levy * ed.maxwidth)].roomname = key.keybuffer; ed.roomnamemod = false; } else if(ed.savemod) { std::string savestring = ed.filename + ".vvvvvv"; ed.save(savestring); ed.note = "[ Saved map: " + ed.filename + ".vvvvvv]"; ed.notedelay = 45; ed.savemod = false; ed.shiftmenu = false; ed.shiftkey = false; if(ed.saveandquit) { //quit editor dwgfx.fademode = 2; } } else if(ed.loadmod) { std::string loadstring = ed.filename + ".vvvvvv"; ed.load(loadstring); ed.note = "[ Loaded map: " + ed.filename + ".vvvvvv]"; ed.notedelay = 45; ed.loadmod = false; ed.shiftmenu = false; ed.shiftkey = false; } else if(ed.roomtextmod) { edentity[ed.roomtextent].scriptname = key.keybuffer; ed.roomtextmod = false; ed.shiftmenu = false; ed.shiftkey = false; } else if(ed.scripttextmod) { edentity[ed.scripttextent].scriptname = key.keybuffer; ed.scripttextmod = false; ed.clearscriptbuffer(); if(!ed.checkhook(edentity[ed.scripttextent].scriptname)) { ed.addhook(edentity[ed.scripttextent].scriptname); } } else if(ed.titlemod) { EditorData::GetInstance().title = key.keybuffer; ed.titlemod = false; } else if(ed.creatormod) { EditorData::GetInstance().creator = key.keybuffer; ed.creatormod = false; } else if(ed.websitemod) { ed.website = key.keybuffer; ed.websitemod = false; } else if(ed.desc1mod) { ed.Desc1 = key.keybuffer; } else if(ed.desc2mod) { ed.Desc2 = key.keybuffer; } else if(ed.desc3mod) { ed.Desc3 = key.keybuffer; ed.desc3mod = false; } key.disabletextentry(); ed.textentry = false; if(ed.desc1mod) { ed.desc1mod = false; ed.textentry = true; ed.desc2mod = true; key.enabletextentry(); key.keybuffer = ed.Desc2; } else if(ed.desc2mod) { ed.desc2mod = false; ed.textentry = true; ed.desc3mod = true; key.enabletextentry(); key.keybuffer = ed.Desc3; } } } } else { if(ed.settingsmod) { if(!game.press_action && !game.press_left && !game.press_right && !key.keymap[SDLK_UP] && !key.keymap[SDLK_DOWN]) game.jumpheld = false; if(!game.jumpheld) { if(game.press_action || game.press_left || game.press_right || game.press_map || key.keymap[SDLK_UP] || key.keymap[SDLK_DOWN]) { game.jumpheld = true; } if(game.menustart) { if(game.press_left || key.keymap[SDLK_UP]) { game.currentmenuoption--; } else if(game.press_right || key.keymap[SDLK_DOWN]) { game.currentmenuoption++; } } if(game.currentmenuoption < 0) game.currentmenuoption = game.nummenuoptions - 1; if(game.currentmenuoption >= game.nummenuoptions) game.currentmenuoption = 0; if(game.press_action) { if(game.currentmenuname == "ed_desc") { if(game.currentmenuoption == 0) { ed.textentry = true; ed.titlemod = true; key.enabletextentry(); key.keybuffer = EditorData::GetInstance().title; } else if(game.currentmenuoption == 1) { ed.textentry = true; ed.creatormod = true; key.enabletextentry(); key.keybuffer = EditorData::GetInstance().creator; } else if(game.currentmenuoption == 2) { ed.textentry = true; ed.desc1mod = true; key.enabletextentry(); key.keybuffer = ed.Desc1; } else if(game.currentmenuoption == 3) { ed.textentry = true; ed.websitemod = true; key.enabletextentry(); key.keybuffer = ed.website; } else if(game.currentmenuoption == 4) { music.playef(11); game.createmenu("ed_settings"); map.nexttowercolour(); } } else if(game.currentmenuname == "ed_settings") { if(game.currentmenuoption == 0) { //Change level description stuff music.playef(11); game.createmenu("ed_desc"); map.nexttowercolour(); } else if(game.currentmenuoption == 1) { //Enter script editormode music.playef(11); ed.scripteditmod = true; ed.clearscriptbuffer(); key.enabletextentry(); key.keybuffer = ""; ed.hookmenupage = 0; ed.hookmenu = 0; ed.scripthelppage = 0; ed.scripthelppagedelay = 0; ed.sby = 0; ed.sbx = 0, ed.pagey = 0; } else if(game.currentmenuoption == 2) { music.playef(11); game.createmenu("ed_music"); map.nexttowercolour(); if(ed.levmusic > 0) music.play(ed.levmusic); } else if(game.currentmenuoption == 3) { //Load level ed.settingsmod = false; dwgfx.backgrounddrawn = false; map.nexttowercolour(); ed.loadmod = true; ed.textentry = true; key.enabletextentry(); key.keybuffer = ed.filename; ed.keydelay = 6; game.mapheld = true; dwgfx.backgrounddrawn = false; } else if(game.currentmenuoption == 4) { //Save level ed.settingsmod = false; dwgfx.backgrounddrawn = false; map.nexttowercolour(); ed.savemod = true; ed.textentry = true; key.enabletextentry(); key.keybuffer = ed.filename; ed.keydelay = 6; game.mapheld = true; dwgfx.backgrounddrawn = false; } else if(game.currentmenuoption == 5) { music.playef(11); game.createmenu("ed_quit"); map.nexttowercolour(); } } else if(game.currentmenuname == "ed_music") { if(game.currentmenuoption == 0) { ed.levmusic++; if(ed.levmusic == 5) ed.levmusic = 6; if(ed.levmusic == 7) ed.levmusic = 8; if(ed.levmusic == 9) ed.levmusic = 10; if(ed.levmusic == 15) ed.levmusic = 0; if(ed.levmusic > 0) { music.play(ed.levmusic); } else { music.haltdasmusik(); } music.playef(11); } else if(game.currentmenuoption == 1) { music.playef(11); music.fadeout(); game.createmenu("ed_settings"); map.nexttowercolour(); } } else if(game.currentmenuname == "ed_quit") { if(game.currentmenuoption == 0) { //Saving and quit ed.saveandquit = true; ed.settingsmod = false; dwgfx.backgrounddrawn = false; map.nexttowercolour(); ed.savemod = true; ed.textentry = true; key.enabletextentry(); key.keybuffer = ed.filename; ed.keydelay = 6; game.mapheld = true; dwgfx.backgrounddrawn = false; } else if(game.currentmenuoption == 1) { //Quit without saving music.playef(11); music.fadeout(); dwgfx.fademode = 2; } else if(game.currentmenuoption == 2) { //Go back to editor music.playef(11); game.createmenu("ed_settings"); map.nexttowercolour(); } } } } } else { //Shortcut keys //TO DO: make more user friendly if(key.keymap[SDLK_F1] && ed.keydelay == 0) { ed.level[ed.levx + (ed.levy * ed.maxwidth)].tileset++; dwgfx.backgrounddrawn = false; if(ed.level[ed.levx + (ed.levy * ed.maxwidth)].tileset >= 5) ed.level[ed.levx + (ed.levy * ed.maxwidth)].tileset = 0; if(ed.level[ed.levx + (ed.levy * ed.maxwidth)].tileset == 0) { if(ed.level[ed.levx + (ed.levy * ed.maxwidth)].tilecol >= 32) ed.level[ed.levx + (ed.levy * ed.maxwidth)].tilecol = 0; } else if(ed.level[ed.levx + (ed.levy * ed.maxwidth)].tileset == 1) { if(ed.level[ed.levx + (ed.levy * ed.maxwidth)].tilecol >= 8) ed.level[ed.levx + (ed.levy * ed.maxwidth)].tilecol = 0; } else { if(ed.level[ed.levx + (ed.levy * ed.maxwidth)].tilecol >= 6) ed.level[ed.levx + (ed.levy * ed.maxwidth)].tilecol = 0; } ed.notedelay = 45; switch(ed.level[ed.levx + (ed.levy * ed.maxwidth)].tileset) { case 0: ed.note = "Now using Space Station Tileset"; break; case 1: ed.note = "Now using Outside Tileset"; break; case 2: ed.note = "Now using Lab Tileset"; break; case 3: ed.note = "Now using Warp Zone Tileset"; break; case 4: ed.note = "Now using Ship Tileset"; break; case 5: ed.note = "Now using Tower Tileset"; break; default: ed.note = "Tileset Changed"; break; } ed.updatetiles = true; ed.keydelay = 6; } if(key.keymap[SDLK_F2] && ed.keydelay == 0) { ed.level[ed.levx + (ed.levy * ed.maxwidth)].tilecol++; dwgfx.backgrounddrawn = false; if(ed.level[ed.levx + (ed.levy * ed.maxwidth)].tileset == 0) { if(ed.level[ed.levx + (ed.levy * ed.maxwidth)].tilecol >= 32) ed.level[ed.levx + (ed.levy * ed.maxwidth)].tilecol = 0; } else if(ed.level[ed.levx + (ed.levy * ed.maxwidth)].tileset == 1) { if(ed.level[ed.levx + (ed.levy * ed.maxwidth)].tilecol >= 8) ed.level[ed.levx + (ed.levy * ed.maxwidth)].tilecol = 0; } else { if(ed.level[ed.levx + (ed.levy * ed.maxwidth)].tilecol >= 6) ed.level[ed.levx + (ed.levy * ed.maxwidth)].tilecol = 0; } ed.updatetiles = true; ed.keydelay = 6; ed.notedelay = 45; ed.note = "Tileset Colour Changed"; } if(key.keymap[SDLK_F3] && ed.keydelay == 0) { ed.level[ed.levx + (ed.levy * ed.maxwidth)].enemytype = (ed.level[ed.levx + (ed.levy * ed.maxwidth)].enemytype + 1) % 10; ed.keydelay = 6; ed.notedelay = 45; ed.note = "Enemy Type Changed"; } if(key.keymap[SDLK_F4] && ed.keydelay == 0) { ed.keydelay = 6; ed.boundarytype = 1; ed.boundarymod = 1; } if(key.keymap[SDLK_F5] && ed.keydelay == 0) { ed.keydelay = 6; ed.boundarytype = 2; ed.boundarymod = 1; } if(key.keymap[SDLK_F10] && ed.keydelay == 0) { if(ed.level[ed.levx + (ed.levy * ed.maxwidth)].directmode == 1) { ed.level[ed.levx + (ed.levy * ed.maxwidth)].directmode = 0; ed.note = "Direct Mode Disabled"; } else { ed.level[ed.levx + (ed.levy * ed.maxwidth)].directmode = 1; ed.note = "Direct Mode Enabled"; } dwgfx.backgrounddrawn = false; ed.notedelay = 45; ed.updatetiles = true; ed.keydelay = 6; } if(key.keymap[SDLK_1]) ed.drawmode = 0; if(key.keymap[SDLK_2]) ed.drawmode = 1; if(key.keymap[SDLK_3]) ed.drawmode = 2; if(key.keymap[SDLK_4]) ed.drawmode = 3; if(key.keymap[SDLK_5]) ed.drawmode = 4; if(key.keymap[SDLK_6]) ed.drawmode = 5; if(key.keymap[SDLK_7]) ed.drawmode = 6; if(key.keymap[SDLK_8]) ed.drawmode = 7; if(key.keymap[SDLK_9]) ed.drawmode = 8; if(key.keymap[SDLK_0]) ed.drawmode = 9; if(key.keymap[SDLK_r]) ed.drawmode = 10; if(key.keymap[SDLK_t]) ed.drawmode = 11; if(key.keymap[SDLK_y]) ed.drawmode = 12; if(key.keymap[SDLK_u]) ed.drawmode = 13; if(key.keymap[SDLK_i]) ed.drawmode = 14; if(key.keymap[SDLK_o]) ed.drawmode = 15; if(key.keymap[SDLK_p]) ed.drawmode = 16; if(key.keymap[SDLK_w] && ed.keydelay == 0) { int j = 0, tx = 0, ty = 0; for(int i = 0; i < EditorData::GetInstance().numedentities; i++) { if(edentity[i].t == 50) { tx = (edentity[i].p1 - (edentity[i].p1 % 40)) / 40; ty = (edentity[i].p2 - (edentity[i].p2 % 30)) / 30; if(tx == ed.levx && ty == ed.levy) { j++; } } } if(j > 0) { ed.note = "ERROR: Cannot have both warp types"; ed.notedelay = 45; } else { ed.level[ed.levx + (ed.levy * ed.maxwidth)].warpdir = (ed.level[ed.levx + (ed.levy * ed.maxwidth)].warpdir + 1) % 4; if(ed.level[ed.levx + (ed.levy * ed.maxwidth)].warpdir == 0) { ed.note = "Room warping disabled"; ed.notedelay = 45; dwgfx.backgrounddrawn = false; } else if(ed.level[ed.levx + (ed.levy * ed.maxwidth)].warpdir == 1) { ed.note = "Room warps horizontally"; ed.notedelay = 45; dwgfx.backgrounddrawn = false; } else if(ed.level[ed.levx + (ed.levy * ed.maxwidth)].warpdir == 2) { ed.note = "Room warps vertically"; ed.notedelay = 45; dwgfx.backgrounddrawn = false; } else if(ed.level[ed.levx + (ed.levy * ed.maxwidth)].warpdir == 3) { ed.note = "Room warps in all directions"; ed.notedelay = 45; dwgfx.backgrounddrawn = false; } } ed.keydelay = 6; } if(key.keymap[SDLK_e] && ed.keydelay == 0) { ed.roomnamemod = true; ed.textentry = true; key.enabletextentry(); key.keybuffer = ed.level[ed.levx + (ed.levy * ed.maxwidth)].roomname; ed.keydelay = 6; game.mapheld = true; } //Save and load if(key.keymap[SDLK_s] && ed.keydelay == 0) { ed.savemod = true; ed.textentry = true; key.enabletextentry(); key.keybuffer = ed.filename; ed.keydelay = 6; game.mapheld = true; dwgfx.backgrounddrawn = false; } if(key.keymap[SDLK_l] && ed.keydelay == 0) { ed.loadmod = true; ed.textentry = true; key.enabletextentry(); key.keybuffer = ed.filename; ed.keydelay = 6; game.mapheld = true; dwgfx.backgrounddrawn = false; } if(!game.press_map) game.mapheld = false; if(!game.mapheld) { if(game.press_map) { game.mapheld = true; //Ok! Scan the room for the closest checkpoint int testeditor = -1; int startpoint = 0; //First up; is there a start point on this screen? for(int i = 0; i < EditorData::GetInstance().numedentities; i++) { //if() on screen if(edentity[i].t == 16 && testeditor == -1) { int tx = (edentity[i].x - (edentity[i].x % 40)) / 40; int ty = (edentity[i].y - (edentity[i].y % 30)) / 30; if(tx == ed.levx && ty == ed.levy) { testeditor = i; startpoint = 1; } } } if(testeditor == -1) { //Ok, settle for a check point for(int i = 0; i < EditorData::GetInstance().numedentities; i++) { //if() on screen if(edentity[i].t == 10 && testeditor == -1) { int tx = (edentity[i].x - (edentity[i].x % 40)) / 40; int ty = (edentity[i].y - (edentity[i].y % 30)) / 30; if(tx == ed.levx && ty == ed.levy) { testeditor = i; } } } } if(testeditor == -1) { ed.note = "ERROR: No checkpoint to spawn at"; ed.notedelay = 45; } else { if(startpoint == 0) { //Checkpoint spawn int tx = (edentity[testeditor].x - (edentity[testeditor].x % 40)) / 40; int ty = (edentity[testeditor].y - (edentity[testeditor].y % 30)) / 30; game.edsavex = (edentity[testeditor].x % 40) * 8; game.edsavey = (edentity[testeditor].y % 30) * 8; game.edsaverx = 100 + tx; game.edsavery = 100 + ty; game.edsavegc = edentity[testeditor].p1; if(game.edsavegc == 0) { game.edsavey--; } else { game.edsavey -= 8; } game.edsavedir = 0; } else { //Start point spawn int tx = (edentity[testeditor].x - (edentity[testeditor].x % 40)) / 40; int ty = (edentity[testeditor].y - (edentity[testeditor].y % 30)) / 30; game.edsavex = ((edentity[testeditor].x % 40) * 8) - 4; game.edsavey = (edentity[testeditor].y % 30) * 8; game.edsaverx = 100 + tx; game.edsavery = 100 + ty; game.edsavegc = 0; game.edsavey--; game.edsavedir = 1 - edentity[testeditor].p1; } music.stopmusic(); dwgfx.backgrounddrawn = false; script.startgamemode(21, dwgfx, game, map, obj, music); } //Return to game //game.gamestate=GAMEMODE; /*if(dwgfx.fademode==0) { dwgfx.fademode = 2; music.fadeout(); }*/ } } if(key.keymap[SDLK_x]) { ed.xmod = true; } else { ed.xmod = false; } if(key.keymap[SDLK_z]) { ed.zmod = true; } else { ed.zmod = false; } //Keyboard shortcuts if(ed.keydelay > 0) { ed.keydelay--; } else { if(key.keymap[SDLK_LSHIFT] || key.keymap[SDLK_RSHIFT]) { if(key.keymap[SDLK_UP]) { ed.keydelay = 6; ed.mapheight--; } else if(key.keymap[SDLK_DOWN]) { ed.keydelay = 6; ed.mapheight++; } if(key.keymap[SDLK_LEFT]) { ed.keydelay = 6; ed.mapwidth--; } else if(key.keymap[SDLK_RIGHT]) { ed.keydelay = 6; ed.mapwidth++; } if(ed.keydelay == 6) { if(ed.mapwidth < 1) ed.mapwidth = 1; if(ed.mapheight < 1) ed.mapheight = 1; if(ed.mapwidth >= ed.maxwidth) ed.mapwidth = ed.maxwidth; if(ed.mapheight >= ed.maxheight) ed.mapheight = ed.maxheight; ed.note = "Mapsize is now [" + help.String(ed.mapwidth) + "," + help.String(ed.mapheight) + "]"; ed.notedelay = 45; } } else { if(key.keymap[SDLK_COMMA]) { ed.drawmode--; ed.keydelay = 6; } else if(key.keymap[SDLK_PERIOD]) { ed.drawmode++; ed.keydelay = 6; } if(ed.drawmode < 0) { ed.drawmode = 16; if(ed.spacemod) ed.spacemenu = 0; } if(ed.drawmode > 16) ed.drawmode = 0; if(ed.drawmode > 9) { if(ed.spacemod) ed.spacemenu = 1; } else { if(ed.spacemod) ed.spacemenu = 0; } if(key.keymap[SDLK_LCTRL] || key.keymap[SDLK_RCTRL]) { ed.dmtileeditor = 10; if(key.keymap[SDLK_LEFT]) { ed.dmtile--; ed.keydelay = 3; if(ed.dmtile < 0) ed.dmtile += 1200; } else if(key.keymap[SDLK_RIGHT]) { ed.dmtile++; ed.keydelay = 3; if(ed.dmtile >= 1200) ed.dmtile -= 1200; } if(key.keymap[SDLK_UP]) { ed.dmtile -= 40; ed.keydelay = 3; if(ed.dmtile < 0) ed.dmtile += 1200; } else if(key.keymap[SDLK_DOWN]) { ed.dmtile += 40; ed.keydelay = 3; if(ed.dmtile >= 1200) ed.dmtile -= 1200; } } else { if(key.keymap[SDLK_UP]) { ed.keydelay = 6; dwgfx.backgrounddrawn = false; ed.levy--; ed.updatetiles = true; ed.changeroom = true; } else if(key.keymap[SDLK_DOWN]) { ed.keydelay = 6; dwgfx.backgrounddrawn = false; ed.levy++; ed.updatetiles = true; ed.changeroom = true; } else if(key.keymap[SDLK_LEFT]) { ed.keydelay = 6; dwgfx.backgrounddrawn = false; ed.levx--; ed.updatetiles = true; ed.changeroom = true; } else if(key.keymap[SDLK_RIGHT]) { ed.keydelay = 6; dwgfx.backgrounddrawn = false; ed.levx++; ed.updatetiles = true; ed.changeroom = true; } } if(ed.levx < 0) ed.levx += ed.mapwidth; if(ed.levx >= ed.mapwidth) ed.levx -= ed.mapwidth; if(ed.levy < 0) ed.levy += ed.mapheight; if(ed.levy >= ed.mapheight) ed.levy -= ed.mapheight; } if(key.keymap[SDLK_SPACE]) { ed.spacemod = !ed.spacemod; ed.keydelay = 6; } if(key.keymap[SDLK_LSHIFT] || key.keymap[SDLK_RSHIFT]) { if(!ed.shiftkey) { if(ed.shiftmenu) { ed.shiftmenu = false; } else { ed.shiftmenu = true; } } ed.shiftkey = true; } else { ed.shiftkey = false; } } } if(!ed.settingsmod) { if(ed.boundarymod > 0) { if(key.leftbutton) { if(ed.lclickdelay == 0) { if(ed.boundarymod == 1) { ed.lclickdelay = 1; ed.boundx1 = (ed.tilex * 8); ed.boundy1 = (ed.tiley * 8); ed.boundarymod = 2; } else if(ed.boundarymod == 2) { if((ed.tilex * 8) + 8 >= ed.boundx1 || (ed.tiley * 8) + 8 >= ed.boundy1) { ed.boundx2 = (ed.tilex * 8) + 8; ed.boundy2 = (ed.tiley * 8) + 8; } else { ed.boundx2 = ed.boundx1 + 8; ed.boundy2 = ed.boundy1 + 8; } if(ed.boundarytype == 0) { //Script trigger ed.scripttextmod = true; ed.scripttextent = EditorData::GetInstance().numedentities; addedentity((ed.boundx1 / 8) + (ed.levx * 40), (ed.boundy1 / 8) + (ed.levy * 30), 19, (ed.boundx2 - ed.boundx1) / 8, (ed.boundy2 - ed.boundy1) / 8); ed.lclickdelay = 1; ed.textentry = true; key.enabletextentry(); key.keybuffer = ""; ed.lclickdelay = 1; } else if(ed.boundarytype == 1) { //Enemy bounds int tmp = ed.levx + (ed.levy * ed.maxwidth); ed.level[tmp].enemyx1 = ed.boundx1; ed.level[tmp].enemyy1 = ed.boundy1; ed.level[tmp].enemyx2 = ed.boundx2; ed.level[tmp].enemyy2 = ed.boundy2; } else if(ed.boundarytype == 2) { //Platform bounds int tmp = ed.levx + (ed.levy * ed.maxwidth); ed.level[tmp].platx1 = ed.boundx1; ed.level[tmp].platy1 = ed.boundy1; ed.level[tmp].platx2 = ed.boundx2; ed.level[tmp].platy2 = ed.boundy2; } else if(ed.boundarytype == 3) { //Copy } ed.boundarymod = 0; ed.lclickdelay = 1; } } } else { ed.lclickdelay = 0; } if(key.rightbutton) { ed.boundarymod = 0; } } else if(ed.warpmod) { //Placing warp token if(key.leftbutton) { if(ed.lclickdelay == 0) { if(ed.free(ed.tilex, ed.tiley) == 0) { edentity[ed.warpent].p1 = ed.tilex + (ed.levx * 40); edentity[ed.warpent].p2 = ed.tiley + (ed.levy * 30); ed.warpmod = false; ed.warpent = -1; ed.lclickdelay = 1; } } } else { ed.lclickdelay = 0; } if(key.rightbutton) { removeedentity(ed.warpent); ed.warpmod = false; ed.warpent = -1; } } else { //Mouse input if(key.leftbutton) { if(ed.lclickdelay == 0) { //Depending on current mode, place something if(ed.drawmode == 0) { //place tiles //Are we in direct mode? if(ed.level[ed.levx + (ed.levy * ed.maxwidth)].directmode >= 1) { if(ed.xmod) { for(int j = -2; j < 3; j++) { for(int i = -2; i < 3; i++) { ed.placetilelocal(ed.tilex + i, ed.tiley + j, ed.dmtile); } } } else if(ed.zmod) { for(int j = -1; j < 2; j++) { for(int i = -1; i < 2; i++) { ed.placetilelocal(ed.tilex + i, ed.tiley + j, ed.dmtile); } } } else { ed.placetilelocal(ed.tilex, ed.tiley, ed.dmtile); } } else { if(ed.xmod) { for(int j = -2; j < 3; j++) { for(int i = -2; i < 3; i++) { ed.placetilelocal(ed.tilex + i, ed.tiley + j, 80); } } } else if(ed.zmod) { for(int j = -1; j < 2; j++) { for(int i = -1; i < 2; i++) { ed.placetilelocal(ed.tilex + i, ed.tiley + j, 80); } } } else { ed.placetilelocal(ed.tilex, ed.tiley, 80); } } } else if(ed.drawmode == 1) { //place background tiles if(ed.xmod) { for(int j = -2; j < 3; j++) { for(int i = -2; i < 3; i++) { ed.placetilelocal(ed.tilex + i, ed.tiley + j, 2); } } } else if(ed.zmod) { for(int j = -1; j < 2; j++) { for(int i = -1; i < 2; i++) { ed.placetilelocal(ed.tilex + i, ed.tiley + j, 2); } } } else { ed.placetilelocal(ed.tilex, ed.tiley, 2); } } else if(ed.drawmode == 2) { //place spikes ed.placetilelocal(ed.tilex, ed.tiley, 8); } int tmp = edentat(ed.tilex + (ed.levx * 40), ed.tiley + (ed.levy * 30)); if(tmp == -1) { //Room text and script triggers can be placed in walls if(ed.drawmode == 10) { ed.roomtextmod = true; ed.roomtextent = EditorData::GetInstance().numedentities; ed.textentry = true; key.enabletextentry(); key.keybuffer = ""; dwgfx.backgrounddrawn = false; addedentity(ed.tilex + (ed.levx * 40), ed.tiley + (ed.levy * 30), 17); ed.lclickdelay = 1; } else if(ed.drawmode == 12) //Script Trigger { ed.boundarytype = 0; ed.boundx1 = ed.tilex * 8; ed.boundy1 = ed.tiley * 8; ed.boundarymod = 2; ed.lclickdelay = 1; } } if(tmp == -1 && ed.free(ed.tilex, ed.tiley) == 0) { if(ed.drawmode == 3) { if(ed.numtrinkets < 20) { addedentity(ed.tilex + (ed.levx * 40), ed.tiley + (ed.levy * 30), 9); ed.lclickdelay = 1; ed.numtrinkets++; } else { ed.note = "ERROR: Max number of trinkets is 20"; ed.notedelay = 45; } } else if(ed.drawmode == 4) { addedentity(ed.tilex + (ed.levx * 40), ed.tiley + (ed.levy * 30), 10, 1); ed.lclickdelay = 1; } else if(ed.drawmode == 5) { addedentity(ed.tilex + (ed.levx * 40), ed.tiley + (ed.levy * 30), 3); ed.lclickdelay = 1; } else if(ed.drawmode == 6) { addedentity(ed.tilex + (ed.levx * 40), ed.tiley + (ed.levy * 30), 2, 5); ed.lclickdelay = 1; } else if(ed.drawmode == 7) { addedentity(ed.tilex + (ed.levx * 40), ed.tiley + (ed.levy * 30), 2, 0); ed.lclickdelay = 1; } else if(ed.drawmode == 8) { addedentity(ed.tilex + (ed.levx * 40), ed.tiley + (ed.levy * 30), 1, 0); ed.lclickdelay = 1; } else if(ed.drawmode == 9) { addedentity(ed.tilex + (ed.levx * 40), ed.tiley + (ed.levy * 30), 11, 0); ed.lclickdelay = 1; } else if(ed.drawmode == 11) { ed.scripttextmod = true; ed.scripttextent = EditorData::GetInstance().numedentities; ed.textentry = true; key.enabletextentry(); addedentity(ed.tilex + (ed.levx * 40), ed.tiley + (ed.levy * 30), 18, 0); ed.lclickdelay = 1; } else if(ed.drawmode == 13) { ed.warpmod = true; ed.warpent = EditorData::GetInstance().numedentities; addedentity(ed.tilex + (ed.levx * 40), ed.tiley + (ed.levy * 30), 13); ed.lclickdelay = 1; } else if(ed.drawmode == 14) { //Warp lines if(ed.level[ed.levx + (ed.maxwidth * ed.levy)].warpdir == 0) { if(ed.tilex == 0) { addedentity(ed.tilex + (ed.levx * 40), ed.tiley + (ed.levy * 30), 50, 0); } else if(ed.tilex == 39) { addedentity(ed.tilex + (ed.levx * 40), ed.tiley + (ed.levy * 30), 50, 1); } else if(ed.tiley == 0) { addedentity(ed.tilex + (ed.levx * 40), ed.tiley + (ed.levy * 30), 50, 2); } else if(ed.tiley == 29) { addedentity(ed.tilex + (ed.levx * 40), ed.tiley + (ed.levy * 30), 50, 3); } else { ed.note = "ERROR: Warp lines must be on edges"; ed.notedelay = 45; } } else { ed.note = "ERROR: Cannot have both warp types"; ed.notedelay = 45; } ed.lclickdelay = 1; } else if(ed.drawmode == 15) //Crewmate { if(ed.numcrewmates < 20) { addedentity(ed.tilex + (ed.levx * 40), ed.tiley + (ed.levy * 30), 15, 1 + int(fRandom() * 5)); ed.lclickdelay = 1; ed.numcrewmates++; } else { ed.note = "ERROR: Max number of crewmates is 20"; ed.notedelay = 45; } } else if(ed.drawmode == 16) //Start Point { //If there is another start point, destroy it for(int i = 0; i < EditorData::GetInstance().numedentities; i++) { if(edentity[i].t == 16) { removeedentity(i); i--; } } addedentity(ed.tilex + (ed.levx * 40), ed.tiley + (ed.levy * 30), 16, 0); ed.lclickdelay = 1; } } else if(edentity[tmp].t == 1) { edentity[tmp].p1 = (edentity[tmp].p1 + 1) % 4; ed.lclickdelay = 1; } else if(edentity[tmp].t == 2) { if(edentity[tmp].p1 >= 5) { edentity[tmp].p1 = (edentity[tmp].p1 + 1) % 9; if(edentity[tmp].p1 < 5) edentity[tmp].p1 = 5; } else { edentity[tmp].p1 = (edentity[tmp].p1 + 1) % 4; } ed.lclickdelay = 1; } else if(edentity[tmp].t == 10) { edentity[tmp].p1 = (edentity[tmp].p1 + 1) % 2; ed.lclickdelay = 1; } else if(edentity[tmp].t == 11) { edentity[tmp].p1 = (edentity[tmp].p1 + 1) % 2; ed.lclickdelay = 1; } else if(edentity[tmp].t == 15) { edentity[tmp].p1 = (edentity[tmp].p1 + 1) % 6; ed.lclickdelay = 1; } else if(edentity[tmp].t == 16) { edentity[tmp].p1 = (edentity[tmp].p1 + 1) % 2; ed.lclickdelay = 1; } else if(edentity[tmp].t == 17) { ed.roomtextmod = true; ed.roomtextent = tmp; ed.textentry = true; key.enabletextentry(); key.keybuffer = edentity[tmp].scriptname; ed.lclickdelay = 1; } else if(edentity[tmp].t == 18) { ed.scripttextmod = true; ed.scripttextent = tmp; ed.textentry = true; key.enabletextentry(); key.keybuffer = edentity[tmp].scriptname; ed.lclickdelay = 1; } } } else { ed.lclickdelay = 0; } if(key.rightbutton) { //place tiles if(ed.xmod) { for(int j = -2; j < 3; j++) { for(int i = -2; i < 3; i++) { ed.placetilelocal(ed.tilex + i, ed.tiley + j, 0); } } } else if(ed.zmod) { for(int j = -1; j < 2; j++) { for(int i = -1; i < 2; i++) { ed.placetilelocal(ed.tilex + i, ed.tiley + j, 0); } } } else { ed.placetilelocal(ed.tilex, ed.tiley, 0); } for(int i = 0; i < EditorData::GetInstance().numedentities; i++) { if(edentity[i].x == ed.tilex + (ed.levx * 40) && edentity[i].y == ed.tiley + (ed.levy * 30)) { if(edentity[i].t == 9) ed.numtrinkets--; if(edentity[i].t == 15) ed.numcrewmates--; removeedentity(i); } } } if(key.middlebutton) { ed.dmtile = ed.contents[ed.tilex + (ed.levx * 40) + ed.vmult[ed.tiley + (ed.levy * 30)]]; } } } } if(ed.updatetiles && ed.level[ed.levx + (ed.levy * ed.maxwidth)].directmode == 0) { ed.updatetiles = false; //Correctly set the tiles in the current room switch(ed.level[ed.levx + (ed.levy * ed.maxwidth)].tileset) { case 0: //The Space Station for(int j = 0; j < 30; j++) { for(int i = 0; i < 40; i++) { temp = i + (ed.levx * 40) + ed.vmult[j + (ed.levy * 30)]; if(ed.contents[temp] >= 3 && ed.contents[temp] < 80) { //Fix spikes ed.contents[temp] = ed.spikedir(i, j); } else if(ed.contents[temp] == 2 || ed.contents[temp] >= 680) { //Fix background ed.contents[temp] = ed.backedgetile(i, j) + ed.backbase(ed.levx, ed.levy); } else if(ed.contents[temp] > 0) { //Fix tiles ed.contents[temp] = ed.edgetile(i, j) + ed.base(ed.levx, ed.levy); } } } break; case 1: //Outside for(int j = 0; j < 30; j++) { for(int i = 0; i < 40; i++) { temp = i + (ed.levx * 40) + ed.vmult[j + (ed.levy * 30)]; if(ed.contents[temp] >= 3 && ed.contents[temp] < 80) { //Fix spikes ed.contents[temp] = ed.spikedir(i, j); } else if(ed.contents[temp] == 2 || ed.contents[temp] >= 680) { //Fix background ed.contents[temp] = ed.outsideedgetile(i, j) + ed.backbase(ed.levx, ed.levy); } else if(ed.contents[temp] > 0) { //Fix tiles ed.contents[temp] = ed.edgetile(i, j) + ed.base(ed.levx, ed.levy); } } } break; case 2: //Lab for(int j = 0; j < 30; j++) { for(int i = 0; i < 40; i++) { temp = i + (ed.levx * 40) + ed.vmult[j + (ed.levy * 30)]; if(ed.contents[temp] >= 3 && ed.contents[temp] < 80) { //Fix spikes ed.contents[temp] = ed.labspikedir(i, j, ed.level[ed.levx + (ed.maxwidth * ed.levy)].tilecol); } else if(ed.contents[temp] == 2 || ed.contents[temp] >= 680) { //Fix background ed.contents[temp] = 713; } else if(ed.contents[temp] > 0) { //Fix tiles ed.contents[temp] = ed.edgetile(i, j) + ed.base(ed.levx, ed.levy); } } } break; case 3: //Warp Zone/Intermission for(int j = 0; j < 30; j++) { for(int i = 0; i < 40; i++) { temp = i + (ed.levx * 40) + ed.vmult[j + (ed.levy * 30)]; if(ed.contents[temp] >= 3 && ed.contents[temp] < 80) { //Fix spikes ed.contents[temp] = ed.spikedir(i, j); } else if(ed.contents[temp] == 2 || ed.contents[temp] >= 680) { //Fix background ed.contents[temp] = 713; //ed.backbase(ed.levx,ed.levy); } else if(ed.contents[temp] > 0) { //Fix tiles //ed.contents[temp]=ed.warpzoneedgetile(i,j)+ed.base(ed.levx,ed.levy); ed.contents[temp] = ed.edgetile(i, j) + ed.base(ed.levx, ed.levy); } } } break; case 4: //The ship for(int j = 0; j < 30; j++) { for(int i = 0; i < 40; i++) { temp = i + (ed.levx * 40) + ed.vmult[j + (ed.levy * 30)]; if(ed.contents[temp] >= 3 && ed.contents[temp] < 80) { //Fix spikes ed.contents[temp] = ed.spikedir(i, j); } else if(ed.contents[temp] == 2 || ed.contents[temp] >= 680) { //Fix background ed.contents[temp] = ed.backedgetile(i, j) + ed.backbase(ed.levx, ed.levy); } else if(ed.contents[temp] > 0) { //Fix tiles ed.contents[temp] = ed.edgetile(i, j) + ed.base(ed.levx, ed.levy); } } } break; case 5: //The Tower break; case 6: //Custom Set 1 break; case 7: //Custom Set 2 break; case 8: //Custom Set 3 break; case 9: //Custom Set 4 break; } } }
23.717841
171
0.540716
TijmenUU
652ea7d3b537e73f69adb502881ab69f22a61727
490
cpp
C++
EU4toV2/Source/Mappers/FactoryTypes/FactoryTypeInputs.cpp
GregB76/EU4toVic2
0a8822101a36a16036fdc315e706d113d9231101
[ "MIT" ]
1
2020-10-03T16:01:28.000Z
2020-10-03T16:01:28.000Z
EU4toV2/Source/Mappers/FactoryTypes/FactoryTypeInputs.cpp
P4blo7/EU4toVic2
3f6d354a1f5e529f3d96b3616fe5109bc23f2972
[ "MIT" ]
null
null
null
EU4toV2/Source/Mappers/FactoryTypes/FactoryTypeInputs.cpp
P4blo7/EU4toVic2
3f6d354a1f5e529f3d96b3616fe5109bc23f2972
[ "MIT" ]
null
null
null
#include "FactoryTypeInputs.h" #include "ParserHelpers.h" mappers::FactoryTypeInputs::FactoryTypeInputs(std::istream& theStream) { registerRegex("[a-z_]+", [this](const std::string& inputGood, std::istream& theStream) { const commonItems::singleDouble inputValue(theStream); productionInputValues.insert(std::make_pair(inputGood, inputValue.getDouble())); }); registerRegex("[a-zA-Z0-9\\_.:]+", commonItems::ignoreItem); parseStream(theStream); clearRegisteredKeywords(); }
30.625
87
0.746939
GregB76
6531c48161494a299204e96901484ac2c847b15e
192
cpp
C++
Statistics.cpp
1-gcc/Loup
ff0d54b4b068e68d39dcd9a4d92ed9fcdb9c6f09
[ "MIT" ]
null
null
null
Statistics.cpp
1-gcc/Loup
ff0d54b4b068e68d39dcd9a4d92ed9fcdb9c6f09
[ "MIT" ]
null
null
null
Statistics.cpp
1-gcc/Loup
ff0d54b4b068e68d39dcd9a4d92ed9fcdb9c6f09
[ "MIT" ]
null
null
null
// Statistics.cpp // (C) Copyright 2017 by Martin Brunn see License.txt for details // #include "Statistics.h" Statistics::Statistics() { } Statistics::~Statistics() { }
12
67
0.630208
1-gcc
6531eff7da7e2206e904fd0577e38bbb47b142e1
836
hpp
C++
include/architect/clang.hpp
KoltesDigital/architect.cpp
97d1225a89887624ad467f602d6f6468410c49ab
[ "MIT" ]
2
2018-07-02T01:47:31.000Z
2019-12-14T23:53:02.000Z
include/architect/clang.hpp
Bloutiouf/architect.cpp
97d1225a89887624ad467f602d6f6468410c49ab
[ "MIT" ]
null
null
null
include/architect/clang.hpp
Bloutiouf/architect.cpp
97d1225a89887624ad467f602d6f6468410c49ab
[ "MIT" ]
null
null
null
#pragma once #ifdef ARCHITECT_CLANG_SUPPORT #include <functional> #include <string> typedef struct CXTranslationUnitImpl *CXTranslationUnit; namespace architect { class Registry; namespace clang { typedef std::function<bool(const std::string &)> Filter; struct Parameters { Filter filter; // returns whether to visit symbols in the file Parameters(); }; class DirectoryFilter { public: DirectoryFilter(); // working directory DirectoryFilter(const std::string &path); bool operator()(const std::string &filename) const; private: std::string _path; }; void parse(Registry &registry, const CXTranslationUnit translationUnit, Parameters &parameters = Parameters()); bool parse(Registry &registry, int argc, const char *const *argv, Parameters &parameters = Parameters()); } } #endif
19.44186
113
0.727273
KoltesDigital
6532f9844d9f1887eeda5e8bdb0ee88a38a732fb
2,609
cpp
C++
src/Popup.cpp
LeandreBl/sfml-scene
3fb0d1167f1585c0c82775a23b44df46ec7378d5
[ "Apache-2.0" ]
2
2020-12-10T20:22:17.000Z
2020-12-10T20:23:35.000Z
src/Popup.cpp
LeandreBl/sfml-scene
3fb0d1167f1585c0c82775a23b44df46ec7378d5
[ "Apache-2.0" ]
null
null
null
src/Popup.cpp
LeandreBl/sfml-scene
3fb0d1167f1585c0c82775a23b44df46ec7378d5
[ "Apache-2.0" ]
null
null
null
#include "Popup.hpp" #include "Colors.hpp" namespace sfs { Popup::Popup(Scene &scene, const sf::Font &font, const sf::Vector2f &position) noexcept : UI(scene, "Popup", position) , _box(addComponent<Rectangle>()) , _text(addComponent<Text>(font, "", sf::Color::Black)) , _queue() , _elapsed(0.f) { } void Popup::updateString() noexcept { _text.setString(_queue.front().first); auto rect = _text.getLocalBounds(); float gapx = rect.width * 1.5; float gapy = rect.height * 2; _box.setSize(sf::Vector2f(gapx, gapy)); _box.setOffset(sf::Vector2f(-rect.width, 0)); auto boxrect = _box.getLocalBounds(); _text.setOffset(sf::Vector2f((boxrect.width - rect.width) / 2 - rect.left, (boxrect.height - rect.height) / 2 - rect.top) + _box.getOffset()); } sf::Uint8 Popup::getAlpha() const noexcept { if (_elapsed <= _queue.front().second / 3) { return _elapsed * 255 / (_queue.front().second / 3); } else if (_elapsed <= _queue.front().second * 2 / 3) { return 255; } return 255 - (_elapsed * 255 / (_queue.front().second / 3)); } sf::FloatRect Popup::getGlobalBounds() noexcept { return _text.getGlobalBounds(); } void Popup::clean() noexcept { auto color = _box.getFillColor(); color.a = 0; _box.setFillColor(color); _text.setString(""); _elapsed = 0; } void Popup::start() noexcept { } void Popup::update() noexcept { if (_queue.size() > 0) { _elapsed += scene().deltaTime(); if (_elapsed >= _queue.front().second) { _queue.pop(); _elapsed = 0.f; if (_queue.size() > 0) { updateString(); } else { Popup::clean(); return; } } auto color = _box.getFillColor(); auto alpha = getAlpha(); color.a = alpha; _box.setFillColor(color); color = _text.getFillColor(); color.a = alpha; _text.setFillColor(color); } } void Popup::onEvent(const sf::Event &) noexcept { } void Popup::onDestroy() noexcept { } void Popup::setTexture(const sf::Texture &texture) noexcept { _box.setTexture(&texture); } void Popup::setCharacterSize(uint32_t size) noexcept { _text.setCharacterSize(size); } void Popup::setBoxColor(const sf::Color &color) noexcept { _box.setFillColor(color); } void Popup::setTextColor(const sf::Color &color) noexcept { _text.setFillColor(color); } void Popup::push(const sf::String &string, float duration) noexcept { _queue.emplace(string, duration); if (_queue.size() == 1) updateString(); } void Popup::clear() noexcept { pop(_queue.size()); } void Popup::pop(size_t n) noexcept { while (_queue.size() > 0 && n > 0) _queue.pop(); if (_queue.size() == 0) Popup::clean(); } } // namespace sfs
19.765152
87
0.661173
LeandreBl
6539554ea836c0fd3caecb6811692e2324946b42
10,355
cpp
C++
src/MinConsoleNative/CellRenderer.cpp
OpenGreatDream/Console
205a6802c6d12d322fa66c91fa7baa3e38e8d6c1
[ "MIT" ]
5
2021-04-11T17:32:45.000Z
2021-09-16T18:27:58.000Z
src/MinConsoleNative/CellRenderer.cpp
OpenGreatDream/MinConsole
4adc9e5574c77985488d22528ee318a1f62649b0
[ "MIT" ]
4
2021-05-01T10:22:14.000Z
2021-05-05T11:20:34.000Z
src/MinConsoleNative/CellRenderer.cpp
OpenGreatDream/Console
205a6802c6d12d322fa66c91fa7baa3e38e8d6c1
[ "MIT" ]
null
null
null
#include "CellRenderer.hpp" #include "String.hpp" #include "TextLayout.hpp" #include "VTConverter.hpp" #include <string> using namespace std; namespace MinConsoleNative { CellRenderer::CellRenderer(int consoleWidth, int consoleHeight, CellRendererMode mode) { this->consoleWidth = consoleWidth; this->consoleHeight = consoleHeight; this->mode = mode; this->cellArray = new Cell[consoleWidth * consoleHeight]; this->cellArrayBuffer = new Cell[consoleWidth * consoleHeight]; if (mode == CellRendererMode::Fast) { this->charInfos = new CHAR_INFO[consoleWidth * consoleHeight]; } else { this->charInfos = nullptr; } } CellRenderer::~CellRenderer() { delete[] this->cellArray; delete[] this->cellArrayBuffer; if (mode == CellRendererMode::Fast) { delete[] this->charInfos; } } void CellRenderer::Clear(const Cell& cell) { for (int i = 0; i < consoleWidth * consoleHeight; i++) { this->cellArrayBuffer[i] = this->cellArray[i]; //copy this->cellArray[i] = cell; //set default } } void CellRenderer::Render() { if (mode == CellRendererMode::Fast) RenderFast(); else if (mode == CellRendererMode::TrueColor) RenderTrueColor(); else if (mode == CellRendererMode::Mixed) RenderMixed(); else if (mode == CellRendererMode::FastTrueColor) RenderFastTrueColor(); } void CellRenderer::Draw(const Vector2& pos, const Cell& cell) { if (pos.x < 0 || pos.x > consoleWidth - 1 || pos.y < 0 || pos.y > consoleHeight - 1) return; int index = consoleWidth * pos.y + pos.x; this->cellArray[index] = cell; } void CellRenderer::DrawString(const Vector2& pos, const std::wstring& wstr, Color24 foreColor, Color24 backColor, bool underScore) { for (int i = 0; i < wstr.size(); i++) { CellRenderer::Draw(Vector2(pos.x + i, pos.y), Cell(wstr[i], foreColor, backColor, underScore)); } } int CellRenderer::DrawString2(const Vector2& pos, const std::wstring& wstr, Color24 foreColor, Color24 backColor, bool underScore) { vector<wstring> grids = textLayout.WstringToGrids(wstr); for (int i = 0; i < grids.size(); i++) { const wstring& gridStr = grids[i]; if (gridStr.size() == 1) { CellRenderer::Draw(Vector2(pos.x + i * 2, pos.y), Cell(gridStr[0], foreColor, backColor, underScore, true)); CellRenderer::Draw(Vector2(pos.x + i * 2 + 1, pos.y), Cell(L' ', foreColor, backColor, underScore, false)); } else if (gridStr.size() == 2) { CellRenderer::Draw(Vector2(pos.x + i * 2, pos.y), Cell(gridStr[0], foreColor, backColor, underScore)); CellRenderer::Draw(Vector2(pos.x + i * 2 + 1, pos.y), Cell(gridStr[1], foreColor, backColor, underScore)); } } return grids.size(); } void CellRenderer::DrawStringWrap(const Vector2& pos, const std::wstring& wstr, Color24 foreColor, Color24 backColor, bool underScore) { for (int i = 0; i < wstr.size(); i++) { int positionX = pos.x + i; int positionY = pos.y; while (positionX > consoleWidth - 1) { positionX -= consoleWidth; positionY++; } CellRenderer::Draw(Vector2(positionX, positionY), Cell(wstr[i], foreColor, backColor, underScore)); } } int CellRenderer::DrawString2Wrap(const Vector2& pos, const std::wstring& wstr, Color24 foreColor, Color24 backColor, bool underScore) { vector<wstring> grids = textLayout.WstringToGrids(wstr); for (int i = 0; i < grids.size(); i++) { int positionX = pos.x + i * 2; int positionY = pos.y; while (positionX > consoleWidth - 1) { positionX -= consoleWidth; positionY++; } const wstring& gridStr = grids[i]; if (gridStr.size() == 1) { CellRenderer::Draw(Vector2(positionX, positionY), Cell(gridStr[0], foreColor, backColor, underScore, true)); CellRenderer::Draw(Vector2(positionX + 1, positionY), Cell(L' ', foreColor, backColor, underScore, false)); } else if (gridStr.size() == 2) { CellRenderer::Draw(Vector2(positionX, positionY), Cell(gridStr[0], foreColor, backColor, underScore)); CellRenderer::Draw(Vector2(positionX + 1, positionY), Cell(gridStr[1], foreColor, backColor, underScore)); } } return grids.size(); } void CellRenderer::DrawBorderBox(const Vector2& pos, const Vector2& size, const Vector2& borderSize, const Cell& cell, const Cell& borderCell) { for (int i = 0; i < size.y; i++) { for (int j = 0; j < size.x; j++) { if (i >= 0 && i < borderSize.y || j >= 0 && j < borderSize.x || i <= size.y - 1 && i > size.y - 1 - borderSize.y || j <= size.x - 1 && j > size.x - 1 - borderSize.x) { CellRenderer::Draw(Vector2(pos.x + j, pos.y + i), borderCell); } else { CellRenderer::Draw(Vector2(pos.x + j, pos.y + i), cell); } } } } void CellRenderer::DrawBorderBox2(const Vector2& pos, const Vector2& size, const Vector2& borderSize, const std::wstring& cellWstr, Color24 cellForeColor, Color24 cellBackColor, bool cellUnderScore, const std::wstring& borderWstr, Color24 borderForeColor, Color24 borderBackColor, bool borderUnderScore) { for (int i = 0; i < size.y; i++) { for (int j = 0; j < size.x; j++) { if (i >= 0 && i < borderSize.y || j >= 0 && j < borderSize.x || i <= size.y - 1 && i > size.y - 1 - borderSize.y || j <= size.x - 1 && j > size.x - 1 - borderSize.x) { CellRenderer::DrawString2(Vector2(pos.x + j * 2, pos.y + i), borderWstr, borderForeColor, borderBackColor, borderUnderScore); } else { CellRenderer::DrawString2(Vector2(pos.x + j * 2, pos.y + i), cellWstr, cellForeColor, cellBackColor, cellUnderScore); } } } } void CellRenderer::RenderFast() { bool findLeadingByte = false; for (int i = 0; i < consoleWidth * consoleHeight; i++) { const Cell& cell = this->cellArray[i]; ushort att = 0; att |= MinConsoleColorToUshort(cell.foreColor.ToConsoleColor(), cell.backColor.ToConsoleColor()); if (cell.underScore) att |= COMMON_LVB_UNDERSCORE; if (cell.isLeadingByte) { att |= COMMON_LVB_LEADING_BYTE; findLeadingByte = true; } else if (findLeadingByte) { att |= COMMON_LVB_TRAILING_BYTE; findLeadingByte = false; } charInfos[i].Attributes = att; charInfos[i].Char.UnicodeChar = cell.c; } console.WriteConsoleOutputW(charInfos, 0, 0, consoleWidth, consoleHeight); } void CellRenderer::RenderMixed() { //draw true color: for (int i = 0; i < consoleWidth * consoleHeight; i++) { const Cell& cell = this->cellArray[i]; const Cell& cellBuffer = this->cellArrayBuffer[i]; if (cell != cellBuffer) { COORD position = { i % consoleWidth, i / consoleWidth }; COORD beforePosition = console.GetConsoleCursorPos(); console.SetConsoleCursorPos(position); console.Write(String::WcharToWstring(L' '), cell.foreColor, cell.backColor, cell.underScore); console.SetConsoleCursorPos(beforePosition); } } //draw string: wstring* lines = new wstring[consoleHeight]; for (int i = 0; i < consoleWidth * consoleHeight; i++) { lines[i / consoleWidth] += this->cellArray[i].c; const Cell& cell = this->cellArray[i]; if (cell.isLeadingByte) { i++; } } for (int i = 0; i < consoleHeight; i++) { console.WriteConsoleOutputCharacterW(lines[i], { 0, (short)i }); } delete[] lines; } void CellRenderer::RenderTrueColor() { for (int i = 0; i < consoleWidth * consoleHeight; i++) { const Cell& cell = this->cellArray[i]; const Cell& cellBuffer = this->cellArrayBuffer[i]; if (cell != cellBuffer) { COORD position = { i % consoleWidth, i / consoleWidth }; COORD beforePosition = console.GetConsoleCursorPos(); console.SetConsoleCursorPos(position); console.Write(String::WcharToWstring(cell.c), cell.foreColor, cell.backColor, cell.underScore); console.SetConsoleCursorPos(beforePosition); } } } void CellRenderer::RenderFastTrueColor() { wstring wstr; for (int i = 0; i < consoleWidth * consoleHeight; i++) { const Cell& cell = this->cellArray[i]; wstr += cell.c; //wstring foreColor = L"\033[38;2;255;0;255m"; //wstr += foreColor + cell.c; //wstring fore_str = VTConverter::VTForeColor(cell.foreColor); //wstring back_str = VTConverter::VTBackColor(cell.backColor); //wstring us_str = VTConverter::VTUnderline(cell.underScore); //wstring reset_str = VTConverter::VTResetStyle(); //wstr += (fore_str + back_str + us_str + cell.c + reset_str); } //console.Write(wstr, { 233,21,22 }); console.Write(wstr); } }
38.210332
307
0.538098
OpenGreatDream
653b53055a56822d2126e130ad93f87441fe3d70
817
cpp
C++
I8086CL/I8086CL.cpp
koutheir/i8086sim
c47fe1ad1cfe8121a7cd6c66f673097c283d2af6
[ "BSD-3-Clause" ]
3
2018-08-25T00:03:42.000Z
2020-01-06T12:37:04.000Z
I8086CL/I8086CL.cpp
koutheir/i8086sim
c47fe1ad1cfe8121a7cd6c66f673097c283d2af6
[ "BSD-3-Clause" ]
null
null
null
I8086CL/I8086CL.cpp
koutheir/i8086sim
c47fe1ad1cfe8121a7cd6c66f673097c283d2af6
[ "BSD-3-Clause" ]
null
null
null
#include <windows.h> BOOL APIENTRY wWinMain(HINSTANCE, HINSTANCE, LPTSTR, int) { int argc; wchar_t **argv = CommandLineToArgvW(GetCommandLineW(), &argc); if (argc < 4) return ERROR_INVALID_PARAMETER; DWORD nErr=ERROR_SUCCESS, nParentID = (DWORD)_wtol(argv[1]); HANDLE hList[2] = { OpenProcess(SYNCHRONIZE, FALSE, nParentID), (HANDLE)_wtol(argv[3]) }; if (!hList[0]) return GetLastError(); if (!AttachConsole(nParentID)) { //Attach to the parent console nErr = GetLastError(); goto Done; } if (!SetEvent((HANDLE)_wtol(argv[2]))) { //Allow the parent to continue execution nErr = GetLastError(); goto Done; } if (WaitForMultipleObjects(2, hList, FALSE, INFINITE) == WAIT_FAILED) nErr = GetLastError(); Done: CloseHandle(hList[0]); return nErr; }
22.694444
84
0.667075
koutheir
653ba5cc16c9453cb55af179bff0c153d989a2c8
24,644
cxx
C++
src/runtime_src/tools/xclbinutil/SectionAIEPartition.cxx
bryanloz-xilinx/XRT
8de6bc04f7060c8272cbb7857531335f1aa31099
[ "Apache-2.0" ]
null
null
null
src/runtime_src/tools/xclbinutil/SectionAIEPartition.cxx
bryanloz-xilinx/XRT
8de6bc04f7060c8272cbb7857531335f1aa31099
[ "Apache-2.0" ]
null
null
null
src/runtime_src/tools/xclbinutil/SectionAIEPartition.cxx
bryanloz-xilinx/XRT
8de6bc04f7060c8272cbb7857531335f1aa31099
[ "Apache-2.0" ]
null
null
null
/** * Copyright (C) 2022 Advanced Micro Devices, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"). You may * not use this file except in compliance with the License. A copy of the * License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ #include "SectionAIEPartition.h" #include "XclBinUtilities.h" #include <boost/algorithm/string/predicate.hpp> #include <boost/algorithm/string/replace.hpp> #include <boost/functional/factory.hpp> #include <boost/property_tree/json_parser.hpp> #include <iostream> namespace XUtil = XclBinUtilities; // ------------------------------------------------------------------------- // Static Variables / Classes SectionAIEPartition::init SectionAIEPartition::initializer; SectionAIEPartition::init::init() { auto sectionInfo = std::make_unique<SectionInfo>(AIE_PARTITION, "AIE_PARTITION", boost::factory<SectionAIEPartition*>()); sectionInfo->nodeName = "aie_partition"; sectionInfo->supportsSubSections = true; sectionInfo->supportsIndexing = true; // There is only one-subsection that is supported. By default it is not named. sectionInfo->subSections.push_back(""); sectionInfo->supportedAddFormats.push_back(FormatType::json); sectionInfo->supportedDumpFormats.push_back(FormatType::json); addSectionType(std::move(sectionInfo)); } // ------------------------------------------------------------------------- class SectionHeap { public: SectionHeap() = delete; SectionHeap(uint64_t heapSectionOffset) { if (XUtil::bytesToAlign(heapSectionOffset) != 0) throw std::runtime_error("Error: HeapSectionOffset is not aligned to 8 bytes"); m_heapSectionOffset = heapSectionOffset; } void write(const char* pBuffer, size_t size, bool align = true) { if ((pBuffer != nullptr) && size) m_heapBuffer.write(pBuffer, size); if (align) XUtil::alignBytes(m_heapBuffer, 8); } uint64_t getNextBufferOffset() { // Get the current size m_heapBuffer.seekp(0, std::ios_base::end); uint64_t bufSize = (uint64_t)m_heapBuffer.tellp(); // And add it to the buffer offset. return bufSize + m_heapSectionOffset; } void writeHeapToStream(std::ostringstream& osStream) { const auto& sHeap = m_heapBuffer.str(); osStream.write(sHeap.c_str(), sHeap.size()); } protected: uint64_t m_heapSectionOffset; std::ostringstream m_heapBuffer; }; // ---------------------------------------------------------------------------- bool SectionAIEPartition::subSectionExists(const std::string& /*sSubSectionName*/) const { // No buffer no subsections return (m_pBuffer != nullptr); } // ------------------------------------------------------------------------- static const std::vector<std::pair<std::string, CDO_Type>> CTTypes = { { "UNKNOWN", CT_UNKNOWN }, { "PRIMARY", CT_PRIMARY }, { "LITE", CT_LITE } }; static const std::string& getCDOTypeStr(CDO_Type eCDOType) { auto iter = std::find_if(CTTypes.begin(), CTTypes.end(), [&](const auto& entry) {return entry.second == eCDOType;}); if (iter == CTTypes.end()) return getCDOTypeStr(CT_UNKNOWN); return iter->first; } static CDO_Type getCDOTypesEnum(const std::string& sTypeName) { auto iter = std::find_if(CTTypes.begin(), CTTypes.end(), [&](const auto& entry) {return boost::iequals(entry.first, sTypeName);}); if (iter == CTTypes.end()) return CT_UNKNOWN; return iter->second; } // ------------------------------------------------------------------------- static void process_PDI_uuid(const boost::property_tree::ptree& ptPDI, aie_pdi& aieParitionPDI) { XUtil::TRACE("Processing PDI UUID"); auto uuid = ptPDI.get<std::string>("uuid", ""); if (uuid.empty()) throw std::runtime_error("Error: The PDI element is missing the 'uuid' node."); // Clean up the UUID boost::replace_all(uuid, "0x", ""); // Remove all "0x" boost::replace_all(uuid, "-", ""); // Remove all minus signs if (uuid.size() < (2 * sizeof(aie_pdi::uuid))) // Add leading zeros uuid.insert(0, (2 * sizeof(aie_pdi::uuid) - uuid.size()), '0'); if (uuid.size() > (2 * sizeof(aie_pdi::uuid))) throw std::runtime_error("Error: The UUID node value is larger then the storage size for this value."); // Write out the value XUtil::hexStringToBinaryBuffer(uuid, reinterpret_cast<unsigned char*>(aieParitionPDI.uuid), sizeof(aie_pdi::uuid)); } // ------------------------------------------------------------------------- static void read_file_into_buffer(const std::string& fileName, const boost::filesystem::path& fromRelativeDir, std::vector<char>& buffer) { // Build the path to our file of interest boost::filesystem::path filePath = fileName; if (filePath.is_relative()) { filePath = fromRelativeDir; filePath /= fileName; } XUtil::TRACE(boost::format("Reading in the file: '%s'") % filePath.string()); // Open the file std::ifstream file(filePath.string(), std::ifstream::in | std::ifstream::binary); if (!file.is_open()) throw std::runtime_error("ERROR: Unable to open the file for reading: " + fileName); // Get the file size file.seekg(0, file.end); std::streamsize fileSize = file.tellg(); file.seekg(0, file.beg); // Resize the buffer and read in the array buffer.resize(fileSize); file.read(buffer.data(), fileSize); // Make sure that the entire buffer was read if (file.gcount() != fileSize) throw std::runtime_error("ERROR: Input stream for the binary buffer is smaller then the expected size."); } // ------------------------------------------------------------------------- static void process_PDI_file(const boost::property_tree::ptree& ptAIEPartitionPDI, const boost::filesystem::path& relativeFromDir, aie_pdi& aiePartitionPDI, SectionHeap& heap) { XUtil::TRACE("Processing PDI Files"); const auto& fileName = ptAIEPartitionPDI.get<std::string>("file_name", ""); if (fileName.empty()) throw std::runtime_error("Error: Missing PDI file name node."); // Read file image from disk std::vector<char> buffer; read_file_into_buffer(fileName, relativeFromDir, buffer); // Store file image in the heap aiePartitionPDI.pdi_image.size = static_cast<decltype(aiePartitionPDI.pdi_image.size)>(buffer.size()); aiePartitionPDI.pdi_image.offset = static_cast<decltype(aiePartitionPDI.pdi_image.offset)>(heap.getNextBufferOffset()); heap.write(reinterpret_cast<const char*>(buffer.data()), buffer.size()); } // ------------------------------------------------------------------------- static void process_pre_cdo_groups(const boost::property_tree::ptree& ptAIECDOGroup, cdo_group& aieCDOGroup, SectionHeap& heap) { XUtil::TRACE("Processing Pre CDO Groups"); std::vector<std::string> preCDOGroups = XUtil::as_vector_simple<std::string>(ptAIECDOGroup, "pre_cdo_groups"); aieCDOGroup.pre_cdo_groups.size = static_cast<decltype(aieCDOGroup.pre_cdo_groups.size)>(preCDOGroups.size()); // It is O.K. not to have any CDO groups if (aieCDOGroup.pre_cdo_groups.size == 0) return; // Record where the CDO group array starts. aieCDOGroup.pre_cdo_groups.offset = static_cast<decltype(aieCDOGroup.pre_cdo_groups.offset)>(heap.getNextBufferOffset()); // Write out the CDO value to the heap. for (const auto& element : preCDOGroups) { uint64_t preGroupID = std::strtoul(element.c_str(), NULL, 0); heap.write(reinterpret_cast<const char*>(&preGroupID), sizeof(decltype(preGroupID)), false /*align*/); } // Align the heap to the next 64-bit word. heap.write(nullptr, 0); } // ------------------------------------------------------------------------- static void process_PDI_cdo_groups(const boost::property_tree::ptree& ptAIEPartitionPDI, aie_pdi& aiePDI, SectionHeap& heap) { XUtil::TRACE("Processing CDO Groups"); std::vector<boost::property_tree::ptree> ptCDOs = XUtil::as_vector<boost::property_tree::ptree>(ptAIEPartitionPDI, "cdo_groups"); aiePDI.cdo_groups.size = static_cast<decltype(aiePDI.cdo_groups.size)>(ptCDOs.size()); if (aiePDI.cdo_groups.size == 0) throw std::runtime_error("Error: There are no cdo groups in the PDI node AIE Partition section."); // Examine each of the CDO groups std::vector<cdo_group> vCDOs; for (const auto& element : ptCDOs) { cdo_group aieCDOGroup = { }; // Name auto name = element.get<std::string>("name", ""); aieCDOGroup.mpo_name = static_cast<decltype(aieCDOGroup.mpo_name)>(heap.getNextBufferOffset()); heap.write(reinterpret_cast<const char*>(name.c_str()), name.size() + 1 /*Null CharL*/); // Type aieCDOGroup.cdo_type = static_cast<decltype(aieCDOGroup.cdo_type)>(getCDOTypesEnum(element.get<std::string>("type", ""))); // PDI ID auto sPDIValue = element.get<std::string>("pdi_id", ""); if (sPDIValue.empty()) throw std::runtime_error("Error: PDI ID node value not found"); aieCDOGroup.pdi_id = std::strtoul(sPDIValue.c_str(), NULL, 0); // DPU Function ID (optional) auto sDPUValue = element.get<std::string>("dpu_kernel_id", ""); if (!sDPUValue.empty()) aieCDOGroup.dpu_kernel_id = std::strtoul(sDPUValue.c_str(), NULL, 0); // PRE CDO Groups (optional) process_pre_cdo_groups(element, aieCDOGroup, heap); // Finished processing the element. Save it away. vCDOs.push_back(aieCDOGroup); } // Write out the CDO group array. Note: The CDO group element is 64-bit aligned. aiePDI.cdo_groups.offset = static_cast<decltype(aiePDI.cdo_groups.offset)>(heap.getNextBufferOffset()); for (const auto& element : vCDOs) heap.write(reinterpret_cast<const char*>(&element), sizeof(cdo_group)); } // ------------------------------------------------------------------------- static void process_PDIs(const boost::property_tree::ptree& ptAIEPartition, const boost::filesystem::path& relativeFromDir, aie_partition& aiePartitionHdr, SectionHeap& heap) { XUtil::TRACE("Processing PDIs"); std::vector<boost::property_tree::ptree> ptPDIs = XUtil::as_vector<boost::property_tree::ptree>(ptAIEPartition, "PDIs"); aiePartitionHdr.aie_pdi.size = static_cast<decltype(aiePartitionHdr.aie_pdi.size)>(ptPDIs.size()); if (aiePartitionHdr.aie_pdi.size == 0) throw std::runtime_error("Error: There are no PDI nodes in the AIE Partition section."); // Examine each of the PDI entries std::vector<aie_pdi> vPDIs; for (const auto& element : ptPDIs) { aie_pdi aiePartitionPDI = { }; process_PDI_uuid(element, aiePartitionPDI); process_PDI_file(element, relativeFromDir, aiePartitionPDI, heap); process_PDI_cdo_groups(element, aiePartitionPDI, heap); // Finished processing the element. Save it away. vPDIs.push_back(aiePartitionPDI); } // Write out the PDI array. Note: The PDI elements are 64-bit aligned. aiePartitionHdr.aie_pdi.offset = static_cast<decltype(aiePartitionHdr.aie_pdi.offset)>(heap.getNextBufferOffset()); for (const auto& element : vPDIs) heap.write(reinterpret_cast<const char*>(&element), sizeof(aie_pdi)); } // ------------------------------------------------------------------------- static void process_partition_info(const boost::property_tree::ptree& ptAIEPartition, aie_partition_info& partitionInfo, SectionHeap& heap) { XUtil::TRACE("Processing partition info"); static const boost::property_tree::ptree ptEmpty; // Get the information regarding the relocatable partitions const auto& ptPartition = ptAIEPartition.get_child("partition", ptEmpty); if (ptPartition.empty()) throw std::runtime_error("Error: The AIE partition is missing the 'partition' node."); partitionInfo = { }; // Parse the column's width partitionInfo.column_width = ptPartition.get<uint16_t>("column_width", 0); if (partitionInfo.column_width == 0) throw std::runtime_error("Error: Missing AIE partition column width"); // Parse the start columns std::vector<uint16_t> startColumns = XUtil::as_vector_simple<uint16_t>(ptPartition, "start_columns"); partitionInfo.start_columns.size = static_cast<decltype(partitionInfo.start_columns.size)>(startColumns.size()); if (partitionInfo.start_columns.size == 0) throw std::runtime_error("Error: Missing start columns for the AIE partition."); // Write out the 16-bit array. partitionInfo.start_columns.offset = static_cast<decltype(partitionInfo.start_columns.offset)>(heap.getNextBufferOffset()); for (const auto element : startColumns) heap.write(reinterpret_cast<const char*>(&element), sizeof(uint16_t), false /*align*/); // Align the heap to the next 64 bit word heap.write(nullptr, 0, true /*align*/); } // ------------------------------------------------------------------------- static void createAIEPartitionImage(const std::string& sectionIndexName, const boost::filesystem::path& relativeFromDir, std::istream& iStream, std::ostringstream& osBuffer) { errno = 0; // Reset any strtoul errors that might have occurred elsewhere // Get the boost property tree iStream.clear(); iStream.seekg(0); boost::property_tree::ptree pt; boost::property_tree::read_json(iStream, pt); XUtil::TRACE_PrintTree("AIE_PARTITION", pt); const boost::property_tree::ptree& ptAIEPartition = pt.get_child("aie_partition"); aie_partition aie_partitionHdr = { }; // Initialized the start of the section heap SectionHeap heap(sizeof(aie_partition)); aie_partitionHdr.mpo_name = static_cast<decltype(aie_partitionHdr.mpo_name)>(heap.getNextBufferOffset()); heap.write(sectionIndexName.c_str(), sectionIndexName.size() + 1 /*Null char*/); // Process the nodes process_partition_info(ptAIEPartition, aie_partitionHdr.info, heap); process_PDIs(ptAIEPartition, relativeFromDir, aie_partitionHdr, heap); // Write out the contents of the section osBuffer.write(reinterpret_cast<const char*>(&aie_partitionHdr), sizeof(aie_partitionHdr)); heap.writeHeapToStream(osBuffer); } // ------------------------------------------------------------------------- void SectionAIEPartition::readSubPayload(const char* pOrigDataSection, unsigned int /*origSectionSize*/, std::istream& iStream, const std::string& sSubSectionName, Section::FormatType eFormatType, std::ostringstream& buffer) const { // Only default (e.g. empty) sub sections are supported if (!sSubSectionName.empty()) { auto errMsg = boost::format("ERROR: Subsection '%s' not support by section '%s") % sSubSectionName % getSectionKindAsString(); throw std::runtime_error(boost::str(errMsg)); } // Some basic DRC checks if (pOrigDataSection != nullptr) { std::string errMsg = "ERROR: AIE Partition section already exists."; throw std::runtime_error(errMsg); } if (eFormatType != Section::FormatType::json) { std::string errMsg = "ERROR: AIE Parition only supports the JSON format."; throw std::runtime_error(errMsg); } // Get the JSON's file parent directory. This is used later to any // relative PDI images that might need need to be read in. boost::filesystem::path p(getPathAndName()); const auto relativeFromDir = p.parent_path(); createAIEPartitionImage(getSectionIndexName(), relativeFromDir, iStream, buffer); } // ------------------------------------------------------------------------- static void populate_partition_info(const char* pBase, const aie_partition_info& aiePartitionInfo, boost::property_tree::ptree& ptAiePartition) { XUtil::TRACE("Populating Partition Info"); boost::property_tree::ptree ptPartitionInfo; // Column Width ptPartitionInfo.put("column_width", (boost::format("%d") % aiePartitionInfo.column_width).str()); // Start Columns boost::property_tree::ptree ptStartColumnArray; const uint16_t* columnArray = reinterpret_cast<const uint16_t*>(pBase + aiePartitionInfo.start_columns.offset); for (uint32_t index = 0; index < aiePartitionInfo.start_columns.size; index++) { boost::property_tree::ptree ptElement; ptElement.put("", (boost::format("%d") % columnArray[index]).str()); ptStartColumnArray.push_back({ "", ptElement }); } ptPartitionInfo.add_child("start_columns", ptStartColumnArray); ptAiePartition.add_child("partition", ptPartitionInfo); } // ------------------------------------------------------------------------- static void populate_pre_cdo_groups(const char* pBase, const cdo_group& aieCDOGroup, boost::property_tree::ptree& ptCDOGroup) { XUtil::TRACE("Populating PRE CDO groups"); // If there is nothing to process, don't create the entry if (aieCDOGroup.pre_cdo_groups.size == 0) return; boost::property_tree::ptree ptPreCDOGroupArray; const uint64_t* aiePreCDOGroupArray = reinterpret_cast<const uint64_t*>(pBase + aieCDOGroup.pre_cdo_groups.offset); for (uint32_t index = 0; index < aieCDOGroup.pre_cdo_groups.size; index++) { const uint64_t& element = aiePreCDOGroupArray[index]; boost::property_tree::ptree ptElement; ptElement.put("", (boost::format("0x%x") % element)); ptPreCDOGroupArray.push_back({ "", ptElement }); } ptCDOGroup.add_child("pre_cdo_groups", ptPreCDOGroupArray); } // ------------------------------------------------------------------------- static void populate_cdo_groups(const char* pBase, const aie_pdi& aiePDI, boost::property_tree::ptree& ptAiePDI) { XUtil::TRACE("Populating CDO groups"); boost::property_tree::ptree ptCDOGroupArray; const cdo_group* aieCDOGroupArray = reinterpret_cast<const cdo_group*>(pBase + aiePDI.cdo_groups.offset); for (uint32_t index = 0; index < aiePDI.cdo_groups.size; index++) { const cdo_group& element = aieCDOGroupArray[index]; boost::property_tree::ptree ptElement; // Name ptElement.put("name", reinterpret_cast<const char*>(pBase + element.mpo_name)); // Type if ((CDO_Type)element.cdo_type != CT_UNKNOWN) ptElement.put("type", getCDOTypeStr((CDO_Type)element.cdo_type)); // PDI ID ptElement.put("pdi_id", (boost::format("0x%x") % element.pdi_id).str()); // Function ID if (element.dpu_kernel_id) ptElement.put("dpu_kernel_id", (boost::format("0x%x") % element.dpu_kernel_id).str()); // Pre cdo groups populate_pre_cdo_groups(pBase, element, ptElement); // Add the cdo group element to the array ptCDOGroupArray.push_back({ "", ptElement }); } ptAiePDI.add_child("cdo_groups", ptCDOGroupArray); } // ------------------------------------------------------------------------- static void write_pdi_image(const char* pBase, const aie_pdi& aiePDI, const std::string& fileName, const boost::filesystem::path& relativeToDir) { boost::filesystem::path filePath = relativeToDir; filePath /= fileName; XUtil::TRACE(boost::format("Creating PDI Image: %s") % filePath.string()); std::fstream oPDIFile; oPDIFile.open(filePath.string(), std::ifstream::out | std::ifstream::binary); if (!oPDIFile.is_open()) { const auto errMsg = boost::format("ERROR: Unable to open the file for writing: %s") % filePath.string(); throw std::runtime_error(errMsg.str()); } oPDIFile.write(reinterpret_cast<const char*>(pBase + aiePDI.pdi_image.offset), aiePDI.pdi_image.size); } // ------------------------------------------------------------------------- static void populate_PDIs(const char* pBase, const boost::filesystem::path& relativeToDir, const aie_partition& aiePartition, boost::property_tree::ptree& ptAiePartition) { XUtil::TRACE("Populating DPI Array"); boost::property_tree::ptree ptPDIArray; const aie_pdi* aiePdiArray = reinterpret_cast<const aie_pdi*>(pBase + aiePartition.aie_pdi.offset); for (uint32_t index = 0; index < aiePartition.aie_pdi.size; index++) { const aie_pdi& element = aiePdiArray[index]; boost::property_tree::ptree ptElement; // UUID ptElement.put("uuid", XUtil::getUUIDAsString(element.uuid)); // Partition Image std::string fileName = XUtil::getUUIDAsString(element.uuid) + ".pdi"; write_pdi_image(pBase, element, fileName, relativeToDir); ptElement.put("file_name", fileName); // CDO Groups populate_cdo_groups(pBase, element, ptElement); // Add the PDI element to the array ptPDIArray.push_back({ "", ptElement }); } ptAiePartition.add_child("PDIs", ptPDIArray); } // ------------------------------------------------------------------------- static void writeAIEPartitionImage(const char* pBuffer, unsigned int bufferSize, const boost::filesystem::path& relativeToDir, std::ostream& oStream) { XUtil::TRACE("AIE_PARTITION : Creating JSON IMAGE"); // Do we have enough room to overlay the header structure if (bufferSize < sizeof(aie_partition)) { auto errMsg = boost::format("ERROR: Segment size (%d) is smaller than the size of the aie_partition structure (%d)") % bufferSize % sizeof(aie_partition); throw std::runtime_error(boost::str(errMsg)); } auto pHdr = reinterpret_cast<const aie_partition*>(pBuffer); // Name boost::property_tree::ptree ptAiePartition; ptAiePartition.put("name", pBuffer + pHdr->mpo_name); // Partition info populate_partition_info(pBuffer, pHdr->info, ptAiePartition); // PDIs populate_PDIs(pBuffer, relativeToDir, *pHdr, ptAiePartition); // Write out the built property tree boost::property_tree::ptree ptRoot; ptRoot.put_child("aie_partition", ptAiePartition); XUtil::TRACE_PrintTree("root", ptRoot); boost::property_tree::write_json(oStream, ptRoot); } // ------------------------------------------------------------------------- void SectionAIEPartition::writeSubPayload(const std::string& sSubSectionName, FormatType eFormatType, std::fstream& oStream) const { // Some basic DRC checks if (m_pBuffer == nullptr) { std::string errMsg = "ERROR: Vendor Metadata section does not exist."; throw std::runtime_error(errMsg); } if (!sSubSectionName.empty()) { auto errMsg = boost::format("ERROR: Subsection '%s' not support by section '%s") % sSubSectionName % getSectionKindAsString(); throw std::runtime_error(boost::str(errMsg)); } // Some basic DRC checks if (eFormatType != Section::FormatType::json) { std::string errMsg = "ERROR: AIE Partition section only supports the JSON format."; throw std::runtime_error(errMsg); } boost::filesystem::path p(getPathAndName()); const auto relativeToDir = p.parent_path(); writeAIEPartitionImage(m_pBuffer, m_bufferSize, relativeToDir, oStream); } // ------------------------------------------------------------------------- void SectionAIEPartition::readXclBinBinary(std::istream& iStream, const axlf_section_header& sectionHeader) { Section::readXclBinBinary(iStream, sectionHeader); XUtil::TRACE("Determining AIE_PARTITION Section Name"); // Do we have enough room to overlay the header structure if (m_bufferSize < sizeof(aie_partition)) { auto errMsg = boost::format("ERROR: Segment size (%d) is smaller than the size of the aie_partition structure (%d)") % m_bufferSize % sizeof(aie_partition); throw std::runtime_error(boost::str(errMsg)); } auto pHdr = reinterpret_cast<const aie_partition*>(m_pBuffer); // Name std::string name = m_pBuffer + pHdr->mpo_name; XUtil::TRACE(std::string("Successfully read in the AIE_PARTITION section: '") + name + "' "); Section::m_sIndexName = name; } // -------------------------------------------------------------------------
36.02924
158
0.646689
bryanloz-xilinx
653fa5e0e418f3ee481bfbcf8b1ccdb258d914ec
2,144
cpp
C++
tests/cthread/test_reset_noninit_read.cpp
hachetman/systemc-compiler
0cc81ace03336d752c0146340ff5763a20e3cefd
[ "Apache-2.0" ]
86
2020-10-23T15:59:47.000Z
2022-03-28T18:51:19.000Z
tests/cthread/test_reset_noninit_read.cpp
hachetman/systemc-compiler
0cc81ace03336d752c0146340ff5763a20e3cefd
[ "Apache-2.0" ]
18
2020-12-14T13:11:26.000Z
2022-03-14T05:34:20.000Z
tests/cthread/test_reset_noninit_read.cpp
hachetman/systemc-compiler
0cc81ace03336d752c0146340ff5763a20e3cefd
[ "Apache-2.0" ]
17
2020-10-29T16:19:43.000Z
2022-03-11T09:51:05.000Z
/****************************************************************************** * Copyright (c) 2020, Intel Corporation. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception. * *****************************************************************************/ #include "systemc.h" #include <sct_assert.h> using namespace sc_core; // Read not initialized variables/arrays in reset -- error/warning reported class A : public sc_module { public: sc_in<bool> clk{"clk"}; sc_signal<bool> nrst{"nrst"}; int* p; int m; int* q = &m; int n; int& r = n; int mm; SC_CTOR(A) { p = sc_new<int>(); SC_CTHREAD(readProc1, clk.pos()); async_reset_signal_is(nrst, false); SC_CTHREAD(readProc2, clk.pos()); async_reset_signal_is(nrst, false); } sc_signal<int> s{"s"}; void f1(int par_a[3]) { auto ii = par_a[1]; } void f2(int (&par_a)[3], int i) { auto ii = par_a[i]; } void f3(int par_a[3][3], int i) { auto ii = par_a[i+1][i+2]; } sc_signal<int> s0; void readProc1() { int aa[3]; int bb[3] = {0,1,2}; int cc[3][3]; int dd[3]; f1(aa); // Warning f2(bb, 1); f3(cc, 0); // Warning int i = dd[1]; // Warning int j; int& r = j; i = r; // Warning int l; i = l + 1; // Warning s0 = i; wait(); while(1) { wait(); } } sc_signal<int> s1; void readProc2() { int i; i = *p; // Error i = mm; // Error int j = *q; // Error j = r; // Error s1 = i + j; wait(); while(1) { wait(); } } }; int sc_main(int argc, char* argv[]) { sc_clock clk("clk", 1, SC_NS); A a_mod{"a_mod"}; a_mod.clk(clk); sc_start(); return 0; }
20.815534
79
0.392257
hachetman
6548f6c55271d48e71e07382db71dd153efca912
559
cc
C++
src/auth.cc
watersalesman/BeastQuest
7622ce59a87c79cabbc7efee77d17866ab626b40
[ "MIT" ]
1
2019-10-31T12:41:42.000Z
2019-10-31T12:41:42.000Z
src/auth.cc
watersalesman/BeastQuest
7622ce59a87c79cabbc7efee77d17866ab626b40
[ "MIT" ]
null
null
null
src/auth.cc
watersalesman/BeastQuest
7622ce59a87c79cabbc7efee77d17866ab626b40
[ "MIT" ]
null
null
null
#include "beastquest/auth.hh" #include <boost/beast.hpp> #include <string> namespace detail = boost::beast::detail; namespace quest { BasicAuth::BasicAuth(std::string username, std::string password) : username_{std::move(username)}, password_{std::move(password)}, auth_string_("Basic " + detail::base64_encode(username_ + ":" + password_)) {} std::string BasicAuth::GetAuthString() const noexcept { return auth_string_; } bool BasicAuth::IsEmpty() const noexcept { return auth_string_.empty(); } } // namespace quest
29.421053
78
0.692308
watersalesman
65490c281c0ad50b3926840de0dd526a144466c3
27,492
hpp
C++
dmp/openCV_dmp.hpp
klaricmn/snippets
a1ae04c13a2209dee013284358d2d987bb0fb4fc
[ "MIT" ]
null
null
null
dmp/openCV_dmp.hpp
klaricmn/snippets
a1ae04c13a2209dee013284358d2d987bb0fb4fc
[ "MIT" ]
null
null
null
dmp/openCV_dmp.hpp
klaricmn/snippets
a1ae04c13a2209dee013284358d2d987bb0fb4fc
[ "MIT" ]
null
null
null
#ifndef _OPENCV_DMP_HPP_ #define _OPENCV_DMP_HPP_ #include <vector> #include <opencv2/core/core.hpp> #include <boost/filesystem.hpp> #include <limits> #include <map> #include <set> #include <list> #include <vector> #include <stdexcept> #include <opencv2/imgproc/imgproc.hpp> //for DEBUG //#include <opencv2/highgui/highgui.hpp> /// /// Generate a opening DMP profile /// \param inputImage The image that will be filtered for light objects /// \param ses The set of strictly increasing geodesic structuring elements /// template <typename OperatingPixelType> std::vector<cv::Mat> opencvOpenDmp(const cv::Mat& inputImage, const std::vector<int>& ses); /// /// Dilation by Reconstruction using the Downhill Filter algorithm (Robinson,Whelan) /// /// \param mask The image/surface that bounds the reconstruction of the marker /// \param mark The image/surface that initializes the reconstruction /// \returns The dilation reconstruction template <typename OperatingPixelType> cv::Mat dilationByReconstructionDownhill(const cv::Mat& mask, const cv::Mat& mark); /// /// Generate a closing DMP profile /// \param inputImage The image that will be filtered for dark objects /// \param ses The set of strictly increasing geodesic structuring elements /// template <typename OperatingPixelType> std::vector<cv::Mat> opencvCloseDmp(const cv::Mat& inputImage, const std::vector<int>& ses); /// /// Erosion by Reconstruction using an Uphill Filter algorithm (insp. by Robinson,Whelan) /// /// \param mask The image/surface that bounds the reconstruction of the marker /// \param mark The image/surface that initializes the reconstruction /// \returns The erosion reconstruction template <typename OperatingPixelType> cv::Mat erosionByReconstructionUphill(const cv::Mat& mask, const cv::Mat& mark); /// Dump the pyramid levels /// \param dmp the pyramid cells to dump /// \param sideTag the Open or Close identifier for the levels /// \param outputPath the output directory /// \param filePath the filename being processed void dumpDmpLevels(const std::vector<cv::Mat>& dmp, const std::vector<int>& ses, const std::string& sideTag, const boost::filesystem::path& outputPath, const boost::filesystem::path& filePath); // ============================ // ============================ // == BEGIN Template Functions // ============================ // ============================ template <typename OperatingPixelType> std::vector<cv::Mat> opencvOpenDmp(const cv::Mat& inputImage, const std::vector<int>& ses) { //cgi::log::MetaLogStream& log(cgi::log::MetaLogStream::instance()); // ++ Open, then dilate by reconstruction //if (false == std::numeric_limits<T>::is_integer) // CGI_THROW(std::logic_error,"Invalid template type"); // Build Structuring Elements std::vector<cv::Mat> structuringElements; for (std::vector<int>::const_iterator level = ses.begin();level!=ses.end();++level) { const int lev = *level; // Circular structuring element const int edgeSize = lev+1+lev; // turn radius into edge size structuringElements.push_back( cv::getStructuringElement(cv::MORPH_ELLIPSE,cv::Size(edgeSize,edgeSize)) ); } // Build Morphological Operation Stack (open) std::vector<cv::Mat> mos; for (unsigned int level = 0;level<structuringElements.size();++level) { cv::Mat filteredImage(inputImage.size().height, inputImage.size().width, cv::DataType<OperatingPixelType>::type); cv::morphologyEx(inputImage, filteredImage, cv::MORPH_OPEN, structuringElements.at(level)); mos.push_back(filteredImage); } const int n_lvls = mos.size(); // log << cgi::log::Priority::INFO << "opencvOpenDmp" << "MOS Produced, size:" << n_lvls << cgi::log::flush; // Set the Tile band count to the SEs array size std::vector<cv::Mat> profile; profile.reserve(n_lvls); // //////////////////////////////////////////////////////////////////////// // USE: dilationByReconstructionDownhill(const cv::Mat& mask,const cv::Mat& mark) cv::Mat tempRec; // Temporary Open Record cv::Mat lastRec; // previous level Open Record // Open = (erode,dilate) //typename MorphologyOperator<DataType>::type morphology(_ses[0]); //typename ReconstructionOperator<DataType>::type reconstructor; //dilationByReconstructionDownhill( inputImage, mos.at(0) ).copyTo(tempRec); tempRec = dilationByReconstructionDownhill<OperatingPixelType>( inputImage, mos.at(0) ).clone(); // get the absolute difference of the two images cv::Mat diffImage(inputImage.size().height, inputImage.size().width, cv::DataType<OperatingPixelType>::type); absdiff(inputImage, tempRec, diffImage); profile.push_back(diffImage.clone()); tempRec.copyTo(lastRec); // Subsequent Levels for (int i = 1;i < n_lvls;++i) { // reconstruction(mask , mark) //dilationByReconstructionDownhill( inputImage, mos.at(i) ).copyTo(tempRec); tempRec = dilationByReconstructionDownhill<OperatingPixelType>( inputImage, mos.at(i) ).clone(); // BEGIN DEBUG /* std::stringstream ss; ss << "reconstruction_from_opening_" << i << ".png"; if(!cv::imwrite(ss.str(), tempRec)) { throw std::runtime_error("Failed to write"); } */ // END DEBUG // get the absolute difference of the two images absdiff(lastRec, tempRec, diffImage); profile.push_back(diffImage.clone()); tempRec.copyTo(lastRec); } return profile; } template <typename OperatingPixelType> cv::Mat dilationByReconstructionDownhill(const cv::Mat& mask, const cv::Mat& mark) { //typedef unsigned short OperatingPixelType; //cgi::log::MetaLogStream& log(cgi::log::MetaLogStream::instance()); if (false == std::numeric_limits<OperatingPixelType>::is_integer) //CGI_THROW(std::logic_error,"Invalid template / operating-pixel type"); throw new std::logic_error("Invalid template / operating-pixel type"); const cv::Size size = mask.size(); //if (size.width != mark.size().width || size.height != mark.size().height) if (size != mark.size()) { //log << cgi::log::Priority::ERROR << "dilationByReconstructionUphill" //<< "Size mismatch: (" //<< size.width << "," << size.height << ") != (" //<< mark.size().width << "," << mark.size().height << ")" << cgi::log::flush; } // -------------------------------- // Place each p : I(p) > 0 into List[I(p)] // -------------------------------- // Copy the marker into the reconstruction // we can then grow it in place // value i has a list of pixels at position (y,x) cv::Mat reconstruction(mark.size().height, mark.size().width, cv::DataType<OperatingPixelType>::type); mark.copyTo(reconstruction); // for template, use typename // typedef typename std::list<std::pair<int,int> > LocationListType; // typedef typename std::map< OperatingPixelType, LocationListType > MapOfLocationListType; typedef typename std::list<std::pair<int,int> > LocationListType; typedef typename std::map< OperatingPixelType, LocationListType > MapOfLocationListType; // This is essentially an indexed image version of the input `mark' raster MapOfLocationListType valueLocationListMap; // Build an in-memory indexed image // but while we are at it, verify that it is properly bounded by `mask' raster for (int i = 0; i < size.height; ++i) for (int j = 0; j < size.width; ++j) { const OperatingPixelType pixelValue = reconstruction.at<OperatingPixelType>(i, j); if (pixelValue > mask.at<OperatingPixelType>(i, j)) { //std::cout << "Storing ("<< i << "," << j <<") into valueLocationListMap["<< static_cast<int>(pixelValue) << "]" << std::endl; std::stringstream msg; msg << "(pixelValue > mask[0](i, j)), for raster location = ("<<i<<","<<j<<")"; //CGI_THROW (std::logic_error, msg.str()); // the marker must always be LTE the mask, by definition throw new std::logic_error( msg.str()); } valueLocationListMap[pixelValue].push_back( std::make_pair<int,int>(i,j) ); } // No valid pixels or values above floor? Return the input as output if (valueLocationListMap.size() == 0) return reconstruction; // -------------------------------- // The farthest downhill we will go // is to the current min(mark[0]) // therefore, we do not need to // process the current min, we // already copied them to output const OperatingPixelType minValue = valueLocationListMap.begin()->first; valueLocationListMap[minValue].clear(); std::set<std::pair<int,int> > finalizedPixels; // -------------------------------- // Do a backward iteration (downhill) // through the // valueLocationListMap[values] // -------------------------------- // use typename for template version //for (typename MapOfLocationListType::reverse_iterator valueList = valueLocationListMap.rbegin(); // valueList != valueLocationListMap.rend(); ++valueList) for (typename MapOfLocationListType::reverse_iterator valueList = valueLocationListMap.rbegin(); valueList != valueLocationListMap.rend(); ++valueList) { // The gray value const OperatingPixelType currentValue = valueList->first; // The list of (y,x) tuples LocationListType locations = valueList->second; // for each location indexed in the value list while (!locations.empty()) { // Debug thing // if (locations.size() > (size.width * size.height)) // { // CGI_THROW(std::logic_error, "GrayscaleDilationByReconstructionDownhill has gone out of control, this should never happen!"); // } // pull/pop the first position from the list, mark it as finalized std::pair<int,int> frontPosition = locations.front(); finalizedPixels.insert(frontPosition); locations.pop_front(); const int y = frontPosition.first; const int x = frontPosition.second; const int pre_x = x - 1; const int post_x = x + 1; const int pre_y = y - 1; const int post_y = y + 1; // For each neighbor // - a - // b p d // - c - // a = (pre_y,x), b = (y,pre_x), c = (post_y,x), d = (y,post_x) // Neighbor Pixel 'a' const std::pair<int,int> a = std::make_pair<int,int>(pre_y,x); const OperatingPixelType mask_a = mask.at<OperatingPixelType>(pre_y,x); // if neighbor index is within bounds and not finalized if ((finalizedPixels.find(a) == finalizedPixels.end()) && (pre_y >= 0) && (mask_a > 0)) { OperatingPixelType neighborValue = reconstruction.at<OperatingPixelType>(pre_y,x); OperatingPixelType constraintValue = std::min<OperatingPixelType>(currentValue,mask_a); // std::cout << "Neighbor(a) = ("<< static_cast<int>(neighborValue) << "), constraint=(" << static_cast<int>(constraintValue) <<")" << std::endl; if (neighborValue < constraintValue) { reconstruction.at<OperatingPixelType>(pre_y,x) = constraintValue; if ( constraintValue == currentValue ) { // std::cout << "Adding ("<< pre_y << "," << x <<") to current list" << std::endl; locations.push_back( a ); } else { // std::cout << "Moving ("<< pre_y << "," << x <<") from " // << static_cast<int>(neighborValue) << " to " << static_cast<int>(constraintValue) << std::endl; valueLocationListMap[neighborValue].remove( a ); valueLocationListMap[constraintValue].push_back( a ); } } } // Neighbor Pixel 'b' const std::pair<int,int> b = std::make_pair<int,int>(y,pre_x); const OperatingPixelType mask_b = mask.at<OperatingPixelType>(y,pre_x); if ((finalizedPixels.find(b) == finalizedPixels.end()) && (pre_x >= 0) && (mask_b > 0)) { OperatingPixelType neighborValue = reconstruction.at<OperatingPixelType>(y,pre_x); OperatingPixelType constraintValue = std::min<OperatingPixelType>(currentValue,mask_b); // std::cout << "Neighbor(b) = ("<< static_cast<int>(neighborValue) << "), constraint=(" << static_cast<int>(constraintValue) <<")" << std::endl; if (neighborValue < constraintValue) { reconstruction.at<OperatingPixelType>(y,pre_x) = constraintValue; if ( constraintValue == currentValue ) { // std::cout << "Adding ("<< y << "," << pre_x <<") to current list" << std::endl; locations.push_back( b ); } else { // std::cout << "Moving ("<< y << "," << pre_x <<") from " // << static_cast<int>(neighborValue) << " to " << static_cast<int>(constraintValue) << std::endl; valueLocationListMap[neighborValue].remove( b ); valueLocationListMap[constraintValue].push_back( b ); } } } // Neighbor Pixel 'c' const std::pair<int,int> c = std::make_pair<int,int>(post_y,x); const OperatingPixelType mask_c = mask.at<OperatingPixelType>(post_y,x); if ((finalizedPixels.find(c) == finalizedPixels.end()) && (post_y < size.height) && (mask_c > 0)) { OperatingPixelType neighborValue = reconstruction.at<OperatingPixelType>(post_y,x); OperatingPixelType constraintValue = std::min<OperatingPixelType>(currentValue,mask_c); // std::cout << "Neighbor(c) = ("<< static_cast<int>(neighborValue) << "), constraint=(" << static_cast<int>(constraintValue) <<")" << std::endl; if (neighborValue < constraintValue) { reconstruction.at<OperatingPixelType>(post_y,x) = constraintValue; if ( constraintValue == currentValue ) { // std::cout << "Adding ("<< post_y << "," << x <<") to current list" << std::endl; locations.push_back( c ); } else { // std::cout << "Moving ("<< post_y << "," << x <<") from " // << static_cast<int>(neighborValue) << " to " << static_cast<int>(constraintValue) << std::endl; valueLocationListMap[neighborValue].remove( c ); valueLocationListMap[constraintValue].push_back( c ); } } } // Neighbor Pixel 'd' const std::pair<int,int> d = std::make_pair<int,int>(y,post_x); const OperatingPixelType mask_d = mask.at<OperatingPixelType>(y,post_x); if ((finalizedPixels.find(d) == finalizedPixels.end()) && (post_x < size.width) && (mask_d > 0)) { OperatingPixelType neighborValue = reconstruction.at<OperatingPixelType>(y,post_x); OperatingPixelType constraintValue = std::min<OperatingPixelType>(currentValue,mask_d); // std::cout << "Neighbor(d) = ("<< static_cast<int>(neighborValue) << "), constraint=(" << static_cast<int>(constraintValue) <<")" << std::endl; if (neighborValue < constraintValue) { reconstruction.at<OperatingPixelType>(y,post_x) = constraintValue; if ( constraintValue == currentValue ) { // std::cout << "Adding ("<< y << "," << post_x <<") to current list" << std::endl; locations.push_back( d ); } else { // std::cout << "Moving ("<< y << "," << post_x <<") from " // << static_cast<int>(neighborValue) << " to " << static_cast<int>(constraintValue) << std::endl; valueLocationListMap[neighborValue].remove( d ); valueLocationListMap[constraintValue].push_back( d ); } } } } // end, a value's position list is emptied. } // end for each value in the marker return reconstruction; }; template <typename OperatingPixelType> std::vector<cv::Mat> opencvCloseDmp(const cv::Mat& inputImage, const std::vector<int>& ses) { //cgi::log::MetaLogStream& log(cgi::log::MetaLogStream::instance()); // ++ Close, then erode by reconstruction //if (false == std::numeric_limits<T>::is_integer) // CGI_THROW(std::logic_error,"Invalid template type"); // Build Structuring Elements std::vector<cv::Mat> structuringElements; for (std::vector<int>::const_iterator level = ses.begin();level!=ses.end();++level) { const int lev = *level; // Circular structuring element const int edgeSize = lev+1+lev; // turn radius into edge size structuringElements.push_back( cv::getStructuringElement(cv::MORPH_ELLIPSE,cv::Size(edgeSize,edgeSize)) ); } // Build Morphological Operation Stack (close) std::vector<cv::Mat> mos; for (unsigned int level = 0;level<structuringElements.size();++level) { cv::Mat filteredImage(inputImage.size().height, inputImage.size().width, cv::DataType<OperatingPixelType>::type); cv::morphologyEx(inputImage, filteredImage, cv::MORPH_CLOSE, structuringElements.at(level)); mos.push_back(filteredImage); } const int n_lvls = mos.size(); // log << cgi::log::Priority::INFO << "opencvCloseDmp" << "MOS Produced, size:" << n_lvls << cgi::log::flush; // Set the Tile band count to the SEs array size std::vector<cv::Mat> profile; profile.reserve(n_lvls); // //////////////////////////////////////////////////////////////////////// // USE: erosionByReconstructionUphill(const cv::Mat& mask,const cv::Mat& mark) cv::Mat tempRec; // Temporary Close Record cv::Mat lastRec; // previous level Close Record // Close = (dilate,erode) //typename MorphologyOperator<DataType>::type morphology(_ses[0]); //typename ReconstructionOperator<DataType>::type reconstructor; //erosionByReconstructionUphill<OperatingPixelType>( inputImage, mos.at(0) ).copyTo(tempRec); tempRec = erosionByReconstructionUphill<OperatingPixelType>( inputImage, mos.at(0) ).clone(); // get the absolute difference of the two images cv::Mat diffImage(inputImage.size().height, inputImage.size().width, cv::DataType<OperatingPixelType>::type); absdiff(inputImage, tempRec, diffImage); profile.push_back(diffImage.clone()); tempRec.copyTo(lastRec); // Subsequent Levels for (int i = 1;i < n_lvls;++i) { // reconstruction(mask , mark) // NOTE: Potentially bad line //erosionByReconstructionUphill<OperatingPixelType>( inputImage, mos.at(i) ).copyTo(tempRec); tempRec = erosionByReconstructionUphill<OperatingPixelType>( inputImage, mos.at(i) ).clone(); // BEGIN DEBUG /* std::stringstream ss; ss << "reconstruction_from_closing_" << i << ".png"; if(!cv::imwrite(ss.str(), tempRec)) { throw std::runtime_error("Failed to write"); } */ // END DEBUG // get the absolute difference of the two images absdiff(lastRec, tempRec, diffImage); profile.push_back(diffImage.clone()); tempRec.copyTo(lastRec); } return profile; }; template <typename OperatingPixelType> cv::Mat erosionByReconstructionUphill(const cv::Mat& mask, const cv::Mat& mark) { // cgi::log::MetaLogStream& log(cgi::log::MetaLogStream::instance()); if (false == std::numeric_limits<OperatingPixelType>::is_integer) //CGI_THROW(std::logic_error,"Invalid template / operating-pixel type"); throw new std::logic_error("Invalid template / operating-pixel type"); const cv::Size size = mask.size(); //if (size.width != mark.size().width || size.height != mark.size().height) if (size != mark.size()) { //log << cgi::log::Priority::ERROR << "erosionByReconstructionDownhill" //<< "Size mismatch: (" //<< size.width << "," << size.height << ") != (" //<< mark.size().width << "," << mark.size().height << ")" << cgi::log::flush; } // -------------------------------- // Place each p : I(p) > 0 into List[I(p)] // -------------------------------- // Copy the marker into the reconstruction // we can then grow it in place // value i has a list of pixels at position (y,x) cv::Mat reconstruction(mark.size().height, mark.size().width, cv::DataType<OperatingPixelType>::type); mark.copyTo(reconstruction); // for template, use typename // typedef typename std::list<std::pair<int,int> > LocationListType; // typedef typename std::map< OperatingPixelType, LocationListType > MapOfLocationListType; typedef std::list<std::pair<int,int> > LocationListType; typedef std::map< OperatingPixelType, LocationListType > MapOfLocationListType; // This is essentially an indexed image version of the input `mark' raster MapOfLocationListType valueLocationListMap; // Build an in-memory indexed image // but while we are at it, verify that it is properly bounded by `mask' raster for (int i = 0; i < size.height; ++i) for (int j = 0; j < size.width; ++j) { const OperatingPixelType pixelValue = reconstruction.at<OperatingPixelType>(i, j); if (pixelValue < mask.at<OperatingPixelType>(i, j)) { //std::cout << "Storing ("<< i << "," << j <<") into valueLocationListMap["<< static_cast<int>(pixelValue) << "]" << std::endl; std::stringstream msg; msg << "(pixelValue < mask[0](i, j)), for raster location = ("<<i<<","<<j<<")"; //CGI_THROW (std::logic_error, msg.str()); // the marker must always be GTE the mask, by definition throw new std::logic_error(msg.str()); } valueLocationListMap[pixelValue].push_back( std::make_pair<int,int>(i,j) ); } // No valid pixels or values below floor? Return the input as output if (valueLocationListMap.size() == 0) return reconstruction; // -------------------------------- // The farthest uphill we will go // is to the current max(mark[0]) // therefore, we do not need to // process the current max, we // already copied them to output const OperatingPixelType maxValue = valueLocationListMap.rbegin()->first; valueLocationListMap[maxValue].clear(); std::set<std::pair<int,int> > finalizedPixels; // -------------------------------- // Do a forward iteration (uphill) // through the // valueLocationListMap[values] // -------------------------------- // use typename for template version //for (typename MapOfLocationListType::iterator valueList = valueLocationListMap.begin(); // valueList != valueLocationListMap.end(); ++valueList) for (typename MapOfLocationListType::iterator valueList = valueLocationListMap.begin(); valueList != valueLocationListMap.end(); ++valueList) { // The gray value const OperatingPixelType currentValue = valueList->first; // The list of (y,x) tuples LocationListType locations = valueList->second; // for each location indexed in the value list while (!locations.empty()) { // Debug thing // if (locations.size() > (size.width * size.height)) // { // CGI_THROW(std::logic_error, "GrayscaleDilationByReconstructionDownhill has gone out of control, this should never happen!"); // } // pull/pop the first position from the list, mark it as finalized std::pair<int,int> frontPosition = locations.front(); finalizedPixels.insert(frontPosition); locations.pop_front(); const int y = frontPosition.first; const int x = frontPosition.second; const int pre_x = x - 1; const int post_x = x + 1; const int pre_y = y - 1; const int post_y = y + 1; // For each neighbor // - a - // b p d // - c - // a = (pre_y,x), b = (y,pre_x), c = (post_y,x), d = (y,post_x) // Neighbor Pixel 'a' const std::pair<int,int> a = std::make_pair<int,int>(pre_y,x); const OperatingPixelType mask_a = mask.at<OperatingPixelType>(pre_y,x); // if neighbor index is within bounds and not finalized if ((finalizedPixels.find(a) == finalizedPixels.end()) && (pre_y >= 0) && (mask_a > 0)) { OperatingPixelType neighborValue = reconstruction.at<OperatingPixelType>(pre_y,x); OperatingPixelType constraintValue = std::max<OperatingPixelType>(currentValue,mask_a); // std::cout << "Neighbor(a) = ("<< static_cast<int>(neighborValue) << "), constraint=(" << static_cast<int>(constraintValue) <<")" << std::endl; if (neighborValue > constraintValue) { reconstruction.at<OperatingPixelType>(pre_y,x) = constraintValue; if ( constraintValue == currentValue ) { // std::cout << "Adding ("<< pre_y << "," << x <<") to current list" << std::endl; locations.push_back( a ); } else { // std::cout << "Moving ("<< pre_y << "," << x <<") from " // << static_cast<int>(neighborValue) << " to " << static_cast<int>(constraintValue) << std::endl; valueLocationListMap[neighborValue].remove( a ); valueLocationListMap[constraintValue].push_back( a ); } } } // Neighbor Pixel 'b' const std::pair<int,int> b = std::make_pair<int,int>(y,pre_x); const OperatingPixelType mask_b = mask.at<OperatingPixelType>(y,pre_x); if ((finalizedPixels.find(b) == finalizedPixels.end()) && (pre_x >= 0) && (mask_b > 0)) { OperatingPixelType neighborValue = reconstruction.at<OperatingPixelType>(y,pre_x); OperatingPixelType constraintValue = std::max<OperatingPixelType>(currentValue,mask_b); // std::cout << "Neighbor(b) = ("<< static_cast<int>(neighborValue) << "), constraint=(" << static_cast<int>(constraintValue) <<")" << std::endl; if (neighborValue > constraintValue) { reconstruction.at<OperatingPixelType>(y,pre_x) = constraintValue; if ( constraintValue == currentValue ) { // std::cout << "Adding ("<< y << "," << pre_x <<") to current list" << std::endl; locations.push_back( b ); } else { // std::cout << "Moving ("<< y << "," << pre_x <<") from " // << static_cast<int>(neighborValue) << " to " << static_cast<int>(constraintValue) << std::endl; valueLocationListMap[neighborValue].remove( b ); valueLocationListMap[constraintValue].push_back( b ); } } } // Neighbor Pixel 'c' const std::pair<int,int> c = std::make_pair<int,int>(post_y,x); const OperatingPixelType mask_c = mask.at<OperatingPixelType>(post_y,x); if ((finalizedPixels.find(c) == finalizedPixels.end()) && (post_y < size.height) && (mask_c > 0)) { OperatingPixelType neighborValue = reconstruction.at<OperatingPixelType>(post_y,x); OperatingPixelType constraintValue = std::max<OperatingPixelType>(currentValue,mask_c); // std::cout << "Neighbor(c) = ("<< static_cast<int>(neighborValue) << "), constraint=(" << static_cast<int>(constraintValue) <<")" << std::endl; if (neighborValue > constraintValue) { reconstruction.at<OperatingPixelType>(post_y,x) = constraintValue; if ( constraintValue == currentValue ) { // std::cout << "Adding ("<< post_y << "," << x <<") to current list" << std::endl; locations.push_back( c ); } else { // std::cout << "Moving ("<< post_y << "," << x <<") from " // << static_cast<int>(neighborValue) << " to " << static_cast<int>(constraintValue) << std::endl; valueLocationListMap[neighborValue].remove( c ); valueLocationListMap[constraintValue].push_back( c ); } } } // Neighbor Pixel 'd' const std::pair<int,int> d = std::make_pair<int,int>(y,post_x); const OperatingPixelType mask_d = mask.at<OperatingPixelType>(y,post_x); if ((finalizedPixels.find(d) == finalizedPixels.end()) && (post_x < size.width) && (mask_d > 0)) { OperatingPixelType neighborValue = reconstruction.at<OperatingPixelType>(y,post_x); OperatingPixelType constraintValue = std::max<OperatingPixelType>(currentValue,mask_d); // std::cout << "Neighbor(d) = ("<< static_cast<int>(neighborValue) << "), constraint=(" << static_cast<int>(constraintValue) <<")" << std::endl; if (neighborValue > constraintValue) { reconstruction.at<OperatingPixelType>(y,post_x) = constraintValue; if ( constraintValue == currentValue ) { // std::cout << "Adding ("<< y << "," << post_x <<") to current list" << std::endl; locations.push_back( d ); } else { // std::cout << "Moving ("<< y << "," << post_x <<") from " // << static_cast<int>(neighborValue) << " to " << static_cast<int>(constraintValue) << std::endl; valueLocationListMap[neighborValue].remove( d ); valueLocationListMap[constraintValue].push_back( d ); } } } } // end, a value's position list is emptied. } // end for each value in the marker return reconstruction; }; #endif //_OPENCV_DMP_HPP_
36.317041
148
0.658337
klaricmn
654bc48e35c6d43864f860a1bb44b802a040c7d1
2,291
cpp
C++
Pimple/CPointerToImplementation.cpp
infojg9/CDesignPatterns
8e9025c2ec93210d4c6e294a726302c9efc6b94d
[ "MIT" ]
null
null
null
Pimple/CPointerToImplementation.cpp
infojg9/CDesignPatterns
8e9025c2ec93210d4c6e294a726302c9efc6b94d
[ "MIT" ]
null
null
null
Pimple/CPointerToImplementation.cpp
infojg9/CDesignPatterns
8e9025c2ec93210d4c6e294a726302c9efc6b94d
[ "MIT" ]
null
null
null
/* * \file CPointerToImplementation.cpp * \author https://github.com/infojg9 * \brief An example of the PIMPL Design / Pointer to Implementation. * \copyright MIT/BSD Redistributable License */ #include "CPointerToImplementation.h" #include <iostream> #ifdef _WIN32 #include <windows.h> #else #include <sys/time.h> #endif namespace Pimple { namespace V1 { /// \class Private Impl class decoupled implementation, kind of Bridge pattern class CPointerToImplementation::Impl { public: Impl() = default; virtual ~Impl(); Impl(Impl const&) = default; Impl& operator=(Impl const&) = default; Impl(Impl&&) = default; Impl& operator=(Impl&&) = default; double GetElapsed() const; std::string mName; #ifdef _WIN32 DWORD mStartTime; #else struct timeval mStartTime; #endif }; CPointerToImplementation::CPointerToImplementation(std::string const& name) : m_pImpl(std::make_unique<CPointerToImplementation::Impl>()) { m_pImpl->mName = name; #ifdef _WIN32 m_pImpl->mStartTime = GetTickCount(); #else gettimeofday(&m_pImpl->mStartTime, nullptr); #endif } CPointerToImplementation::~CPointerToImplementation() { std::cout << m_pImpl->mName << ": consumed : " << m_pImpl->GetElapsed() << " secs" << std::endl; m_pImpl.reset(); m_pImpl = nullptr; } CPointerToImplementation::ImplPtr&& CPointerToImplementation::getImplPtr() { return std::move(m_pImpl); } /// Allow explicit deep copy in copy constructor from rImpl object reference CPointerToImplementation::CPointerToImplementation( CPointerToImplementation const& rImpl) : m_pImpl(std::make_unique<Impl>(*rImpl.m_pImpl)) {} /// Allow explicit deep copy in copy assignment operator from rImpl object reference CPointerToImplementation& CPointerToImplementation::operator=(CPointerToImplementation const& rImpl) { *m_pImpl = *rImpl.m_pImpl; return *this; } double CPointerToImplementation::Impl::GetElapsed() const { #ifdef _WIN32 return (GetTickCount() - mStartTime) / 1e3; #else struct timeval end_time; gettimeofday(&end_time, nullptr); double t1 = mStartTime.tv_usec / 1e6 + mStartTime.tv_sec; double t2 = end_time.tv_usec / 1e6 + end_time.tv_sec; return t2 - t1; #endif } CPointerToImplementation::Impl::~Impl() { } } /// namespace V1 } /// namespace Pimple
23.618557
84
0.730249
infojg9
654fcf199103e19bfe2d2396fd21c110466e72ce
3,694
hpp
C++
include/http_session.hpp
helderthh/imgwriter
60877cfa883faf3f0824c2328a75414c41b7110f
[ "Apache-2.0" ]
null
null
null
include/http_session.hpp
helderthh/imgwriter
60877cfa883faf3f0824c2328a75414c41b7110f
[ "Apache-2.0" ]
null
null
null
include/http_session.hpp
helderthh/imgwriter
60877cfa883faf3f0824c2328a75414c41b7110f
[ "Apache-2.0" ]
null
null
null
#ifndef __HTTP_SESSION_H__ #define __HTTP_SESSION_H__ #include <memory> #include <iostream> #include <boost/beast/core.hpp> #include <boost/beast/http.hpp> #include <boost/beast/version.hpp> #include <boost/asio/bind_executor.hpp> #include <boost/asio/ip/tcp.hpp> #include <boost/asio/strand.hpp> #include <boost/property_tree/json_parser.hpp> #include "utils.hpp" using tcp = boost::asio::ip::tcp; namespace http = boost::beast::http; namespace ptree = boost::property_tree; template<class Body, class Allocator, class Send> using RequestHandlerType = void (*) (http::request<Body, http::basic_fields<Allocator>>&& req, Send&& send); // Handles an HTTP server connection template <template<typename, typename> class RequestHandler> class Session : public std::enable_shared_from_this<Session<RequestHandler>> { struct SendLambda { Session& session_; explicit SendLambda(Session& self) : session_(self) { /* */ } template<bool isRequest, class MsgBody, class Fields> void operator()(http::message<isRequest, MsgBody, Fields>&& msg) const { // The lifetime of the message has to extend // for the duration of the async operation so // we use a shared_ptr to manage it. auto msgSp = std::make_shared<http::message<isRequest, MsgBody, Fields>>(std::move(msg)); // Store a type-erased version of the shared // pointer in the class to keep it alive. session_.res_ = msgSp; // Write the response http::async_write( session_.socket_, *msgSp, boost::asio::bind_executor( session_.strand_, std::bind( &Session::on_write, this->session_.shared_from_this(), std::placeholders::_1, std::placeholders::_2, msgSp->need_eof()))); } }; tcp::socket socket_; boost::asio::strand<boost::asio::io_context::executor_type> strand_; boost::beast::flat_buffer buffer_; http::request<http::string_body> req_; std::shared_ptr<void> res_; SendLambda sendLambda_; public: // Take ownership of the socket explicit Session(tcp::socket socket) : socket_(std::move(socket)), strand_(socket_.get_executor()), sendLambda_(*this) { } void run() { do_read(); } void do_read() { req_ = {}; // Clean the request // And then read it http::async_read(socket_, buffer_, req_, boost::asio::bind_executor( strand_, std::bind( &Session::on_read, this->shared_from_this(), std::placeholders::_1, std::placeholders::_2 ) ) ); } void do_close() { boost::system::error_code ec; socket_.shutdown(tcp::socket::shutdown_send, ec); } void on_read(boost::system::error_code ec, std::size_t bytes_transferred) { boost::ignore_unused(bytes_transferred); // This means they closed the connection if(ec == http::error::end_of_stream) return do_close(); if(ec) return fail(ec, "couldn't read"); // Send the response RequestHandler<http::string_body, SendLambda>()(std::move(req_), sendLambda_); } void on_write(boost::system::error_code ec, std::size_t bytes_transferred, bool close) { boost::ignore_unused(bytes_transferred); if(ec) return fail(ec, "write"); if(close) { // This means we should close the connection, usually because // the response indicated the "Connection: close" semantic. return do_close(); } // We're done with the response so delete it res_ = nullptr; // Read another request do_read(); } }; #endif
25.30137
84
0.641581
helderthh
65574902b30d43ae2e1fd8b7957f113e08eb03f7
1,512
cpp
C++
src/PihaDeviceProvider.cpp
jbitoniau/Piha
9f346066bf09a93abc5753b5dd996c7f598c9d38
[ "MIT" ]
null
null
null
src/PihaDeviceProvider.cpp
jbitoniau/Piha
9f346066bf09a93abc5753b5dd996c7f598c9d38
[ "MIT" ]
null
null
null
src/PihaDeviceProvider.cpp
jbitoniau/Piha
9f346066bf09a93abc5753b5dd996c7f598c9d38
[ "MIT" ]
null
null
null
#include "PihaDeviceProvider.h" #include <assert.h> #include <algorithm> #include "PihaDevice.h" namespace Piha { DeviceProvider::DeviceProvider() { } DeviceProvider::~DeviceProvider() { deleteDevices(); } void DeviceProvider::addDevice( Device* device ) { mDevices.push_back( device ); for ( Listeners::iterator itrListener=mListeners.begin(); itrListener!=mListeners.end(); ++itrListener ) (*itrListener)->onDeviceAdded( this, device ); } void DeviceProvider::deleteDevice( Device* device ) { Devices::iterator itr = std::find( mDevices.begin(), mDevices.end(), device ); if ( itr==mDevices.end() ) return; for ( Listeners::iterator itrListener=mListeners.begin(); itrListener!=mListeners.end(); ++itrListener ) (*itrListener)->onDeviceRemoving( this, device ); mDevices.erase( itr ); delete device; } void DeviceProvider::deleteDevices() { Devices devices = mDevices; // The copy is on purpose here for ( Devices::iterator itr=devices.begin(); itr!=devices.end(); itr++ ) { Device* device = *itr; deleteDevice( device ); } assert( mDevices.empty() ); } const Devices& DeviceProvider::getDevices() const { return mDevices; } void DeviceProvider::addListener( Listener* listener ) { assert(listener); mListeners.push_back(listener); } bool DeviceProvider::removeListener( Listener* listener ) { Listeners::iterator itr = std::find( mListeners.begin(), mListeners.end(), listener ); if ( itr==mListeners.end() ) return false; mListeners.erase( itr ); return true; } }
22.235294
105
0.71627
jbitoniau
6557c36df0718bdbe577a9f48111d44fc834df2c
914
cpp
C++
source/hougfx/src/hou/gfx/mesh_draw_mode.cpp
DavideCorradiDev/houzi-game-engine
d704aa9c5b024300578aafe410b7299c4af4fcec
[ "MIT" ]
2
2018-04-12T20:59:20.000Z
2018-07-26T16:04:07.000Z
source/hougfx/src/hou/gfx/mesh_draw_mode.cpp
DavideCorradiDev/houzi-game-engine
d704aa9c5b024300578aafe410b7299c4af4fcec
[ "MIT" ]
null
null
null
source/hougfx/src/hou/gfx/mesh_draw_mode.cpp
DavideCorradiDev/houzi-game-engine
d704aa9c5b024300578aafe410b7299c4af4fcec
[ "MIT" ]
null
null
null
// Houzi Game Engine // Copyright (c) 2018 Davide Corradi // Licensed under the MIT license. #include "hou/gfx/mesh_draw_mode.hpp" #include "hou/cor/core_functions.hpp" #define MESH_DRAW_MODE_CASE(mdm, os) \ case mesh_draw_mode::mdm: \ return (os) << #mdm namespace hou { std::ostream& operator<<(std::ostream& os, mesh_draw_mode mdm) { switch(mdm) { MESH_DRAW_MODE_CASE(points, os); MESH_DRAW_MODE_CASE(line_strip, os); MESH_DRAW_MODE_CASE(line_loop, os); MESH_DRAW_MODE_CASE(lines, os); MESH_DRAW_MODE_CASE(line_strip_adjacency, os); MESH_DRAW_MODE_CASE(line_adjacency, os); MESH_DRAW_MODE_CASE(triangle_strip, os); MESH_DRAW_MODE_CASE(triangle_fan, os); MESH_DRAW_MODE_CASE(triangles, os); MESH_DRAW_MODE_CASE(triangle_strip_adjacency, os); MESH_DRAW_MODE_CASE(patches, os); } return STREAM_VALUE(os, mesh_draw_mode, mdm); } } // namespace hou
24.052632
62
0.730853
DavideCorradiDev
6559fb3179769f5671f90cd3402cfd258384eda6
2,487
cpp
C++
test/test.cpp
smahajan07/advanced-lane-detection
56b116c27d16210be4679ac7e0f5a5db2e31d397
[ "MIT" ]
null
null
null
test/test.cpp
smahajan07/advanced-lane-detection
56b116c27d16210be4679ac7e0f5a5db2e31d397
[ "MIT" ]
1
2018-10-19T19:44:50.000Z
2018-11-26T04:46:17.000Z
test/test.cpp
smahajan07/advanced-lane-detection
56b116c27d16210be4679ac7e0f5a5db2e31d397
[ "MIT" ]
null
null
null
/** MIT License Copyright (c) 2018 Sarthak Mahajan Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** *@copyright Copyright (c) 2018 Sarthak Mahajan *@file test.cpp *@author Sarthak Mahajan *@brief All tests are defined here. * Primarily to check image channels and predicted turns. */ #include <gtest/gtest.h> #include <gmock/gmock.h> #include <iostream> #include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" #include "opencv2/opencv.hpp" #include "../include/lanedetector.hpp" #include "../include/preProcess.hpp" #include "include/mockpreProcess.hpp" TEST(channels, testNumOfChannelsReturned) { preProcess helperObj; cv::Mat testImg, retImg; std::string imgPath("test.png"); testImg = cv::imread(imgPath, cv::IMREAD_COLOR); retImg = helperObj.grayImage(testImg); EXPECT_EQ(1, retImg.channels()); } TEST(turns, checkTurnDirectionLeft) { lanedetector testObj(true, true, 1.5, -1.5, cv::Point(200, 0), cv::Point(800, 0), 640, 12); EXPECT_EQ("LEFT", testObj.predictTurn()); } TEST(turns, checkTurnDirectionRight) { lanedetector testObj(true, true, 1.5, 1.5, cv::Point(200, 0), cv::Point(400, 0), 640, 12); EXPECT_EQ("RIGHT", testObj.predictTurn()); } TEST(preProcess, testPreProcessFuncs) { std::string imgPath("test.png"); mockpreProcess mockObj; EXPECT_CALL(mockObj, performAllOps(imgPath)).Times(1).WillOnce( ::testing::Return(1)); mockObj.performAllOps(imgPath); }
36.043478
79
0.735022
smahajan07
655d1fdd8d3026f21c1059d361f944aa9d1b3a63
1,327
cpp
C++
Practice/2018/2018.8.8/BZOJ1046.cpp
SYCstudio/OI
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
[ "MIT" ]
4
2017-10-31T14:25:18.000Z
2018-06-10T16:10:17.000Z
Practice/2018/2018.8.8/BZOJ1046.cpp
SYCstudio/OI
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
[ "MIT" ]
null
null
null
Practice/2018/2018.8.8/BZOJ1046.cpp
SYCstudio/OI
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
[ "MIT" ]
null
null
null
#include<iostream> #include<cstdio> #include<cstdlib> #include<cstring> #include<algorithm> using namespace std; #define ll long long #define mem(Arr,x) memset(Arr,x,sizeof(Arr)) #define lowbit(x) ((x)&(-x)) const int maxN=101000; const int inf=2147483647; int n,Seq[maxN]; int numcnt,Num[maxN]; int BIT[maxN],F[maxN]; int GetMax(int pos); void Modify(int pos,int key); int main(){ scanf("%d",&n); for (int i=1;i<=n;i++) scanf("%d",&Seq[i]),Num[i]=Seq[i]=-Seq[i]; numcnt=n; sort(&Num[1],&Num[n+1]);numcnt=unique(&Num[1],&Num[n+1])-Num-1; int Mx=0; for (int i=n;i>=1;i--){ int p=lower_bound(&Num[1],&Num[numcnt+1],Seq[i])-Num;//cout<<"p:"<<p<<endl; F[i]=GetMax(p-1)+1; Modify(p,F[i]); Mx=max(Mx,F[i]); } //for (int i=1;i<=n;i++) cout<<F[i]<<" ";cout<<endl; for (int i=1;i<=n;i++) Seq[i]=-Seq[i]; int Q;scanf("%d",&Q); while (Q--){ int k;scanf("%d",&k); if (k>Mx) printf("Impossible\n"); else{ for (int i=1,j=1,mn=-inf;(j<=k)&&(i<=n);i++) if ((F[i]+j-1>=k)&&(Seq[i]>mn)){ printf("%d ",Seq[i]);mn=max(mn,Seq[i]);j++; } printf("\n"); } } return 0; } int GetMax(int pos){ int ret=0; while (pos){ ret=max(ret,BIT[pos]);pos-=lowbit(pos); } return ret; } void Modify(int pos,int key){ while (pos<=numcnt){ BIT[pos]=max(BIT[pos],key);pos+=lowbit(pos); } return; }
18.957143
77
0.57272
SYCstudio
655e6fa04c5577c4ff5ecec8e498b656508f6fb3
2,338
hpp
C++
model/CellVisitorConcepts.hpp
cuzdav/illum
b78b6477f8d3fbf31408e419f671dbfe421b4e9e
[ "MIT" ]
null
null
null
model/CellVisitorConcepts.hpp
cuzdav/illum
b78b6477f8d3fbf31408e419f671dbfe421b4e9e
[ "MIT" ]
null
null
null
model/CellVisitorConcepts.hpp
cuzdav/illum
b78b6477f8d3fbf31408e419f671dbfe421b4e9e
[ "MIT" ]
null
null
null
#pragma once #include "CellState.hpp" #include "Coord.hpp" #include "Direction.hpp" #include <concepts> #include <cstdint> namespace model { enum class VisitStatus : std::uint8_t { STOP_VISITING, KEEP_VISITING }; using enum VisitStatus; // Non-directional visitors don't have a direction. They are used with // visit-algorithms that are not "linear", but involve mult-direction scans, // such as the whole board, or "what's adjacent to this cell" // // returning void indicates there is no early-stop while visiting // If you don't care about short-circuiting the visit, don't return true. // template <typename T> concept CellVisitorAll = requires(T visitor, CellState cell) { { visitor(Coord{0, 0}, cell) } -> std::same_as<void>; }; // // returning a VisitStatus indicates the visit may be stopped prematurely // template <typename T> concept CellVisitorSome = requires(T visitor, CellState cell) { { visitor(Coord{0, 0}, cell) } -> std::same_as<VisitStatus>; }; // // Unify both Some/All cell visitors // Many visit algos can work with either - when undirected // template <typename T> concept CellVisitor = CellVisitorAll<T> || CellVisitorSome<T>; // ============== // Directed visitors are CellVisitors but are also notified of the direction // they are going. This is generally associated with the visitors that travel // along lines. template <typename T> concept DirectedCellVisitorAll = requires(T visitor, CellState cell) { { visitor(Direction{}, Coord{0, 0}, cell) } -> std::same_as<void>; }; template <typename T> concept DirectedCellVisitorSome = requires(T visitor, CellState cell) { { visitor(Direction{}, Coord{0, 0}, cell) } -> std::same_as<VisitStatus>; }; // // Short circuitable or not, up to the caller // template <typename T> concept DirectedCellVisitor = DirectedCellVisitorAll<T> || DirectedCellVisitorSome<T>; // The most flexible of all for the caller, short-circuitable or not, directed // or not. template <typename T> concept OptDirCellVisitor = DirectedCellVisitor<T> || CellVisitor<T>; // for determining if we should visit a cell or not, for when the visit function // queries a predicate before dispatching. template <typename T> concept CellVisitPredicate = requires(T visitor, CellState cell) { { visitor(Coord{0, 0}, cell) } -> std::same_as<bool>; }; } // namespace model
29.974359
80
0.729256
cuzdav
65692f61ce76acbf17fda313272d5a1f7d65a77b
19,279
cpp
C++
src/lug/Graphics/GltfLoader.cpp
Lugdunum3D/Lugdunum3D
b6d6907d034fdba1ffc278b96598eba1d860f0d4
[ "MIT" ]
275
2016-10-08T15:33:17.000Z
2022-03-30T06:11:56.000Z
src/lug/Graphics/GltfLoader.cpp
Lugdunum3D/Lugdunum3D
b6d6907d034fdba1ffc278b96598eba1d860f0d4
[ "MIT" ]
24
2016-09-29T20:51:20.000Z
2018-05-09T21:41:36.000Z
src/lug/Graphics/GltfLoader.cpp
Lugdunum3D/Lugdunum3D
b6d6907d034fdba1ffc278b96598eba1d860f0d4
[ "MIT" ]
37
2017-02-25T05:03:48.000Z
2021-05-10T19:06:29.000Z
#include <lug/Graphics/GltfLoader.hpp> #if defined(LUG_SYSTEM_ANDROID) #include <android/asset_manager.h> #include <lug/Window/Android/WindowImplAndroid.hpp> #include <lug/Window/Window.hpp> #endif #include <gltf2/Exceptions.hpp> #include <lug/System/Logger/Logger.hpp> #include <lug/Graphics/Builder/Scene.hpp> #include <lug/Graphics/Builder/Material.hpp> #include <lug/Graphics/Builder/Mesh.hpp> #include <lug/Graphics/Builder/Texture.hpp> #include <lug/Graphics/Scene/Scene.hpp> namespace lug { namespace Graphics { GltfLoader::GltfLoader(Renderer& renderer): Loader(renderer) {} static void* getBufferViewData(const gltf2::Asset& asset, const gltf2::Accessor& accessor) { const gltf2::BufferView& bufferView = asset.bufferViews[accessor.bufferView]; const gltf2::Buffer& buffer = asset.buffers[bufferView.buffer]; if (!buffer.data) { LUG_LOG.error("GltfLoader::createMesh Buffer data can't be null"); return nullptr; } // TODO(nokitoo): handle uri return buffer.data + bufferView.byteOffset + accessor.byteOffset; } static uint32_t getAttributeSize(const gltf2::Accessor& accessor) { uint32_t componentSize = 0; switch (accessor.componentType) { case gltf2::Accessor::ComponentType::Byte: componentSize = sizeof(char); break; case gltf2::Accessor::ComponentType::UnsignedByte: componentSize = sizeof(unsigned char); break; case gltf2::Accessor::ComponentType::Short: componentSize = sizeof(short); break; case gltf2::Accessor::ComponentType::UnsignedShort: componentSize = sizeof(unsigned short); break; case gltf2::Accessor::ComponentType::UnsignedInt: componentSize = sizeof(unsigned int); break; case gltf2::Accessor::ComponentType::Float: componentSize = sizeof(float); break; } // Mutliply the componentSize according to the type switch (accessor.type) { case gltf2::Accessor::Type::Scalar: return componentSize; case gltf2::Accessor::Type::Vec2: return componentSize * 2; case gltf2::Accessor::Type::Vec3: return componentSize * 3; case gltf2::Accessor::Type::Vec4: return componentSize * 4; case gltf2::Accessor::Type::Mat2: return componentSize * 4; case gltf2::Accessor::Type::Mat3: return componentSize * 9; case gltf2::Accessor::Type::Mat4: return componentSize * 16; } return componentSize; } Resource::SharedPtr<Render::Texture> GltfLoader::createTexture(Renderer& renderer, const gltf2::Asset& asset, GltfLoader::LoadedAssets& loadedAssets, int32_t index) { const gltf2::Texture& gltfTexture = asset.textures[index]; if (loadedAssets.textures[index]) { return loadedAssets.textures[index]; } Builder::Texture textureBuilder(renderer); if (gltfTexture.source != -1) { // TODO: Handle correctly the load with bufferView / uri data if (!textureBuilder.addLayer(asset.images[gltfTexture.source].uri)) { LUG_LOG.error("GltfLoader::createTexture: Can't load the texture \"{}\"", asset.images[gltfTexture.source].uri); return nullptr; } } if (gltfTexture.sampler != -1) { const gltf2::Sampler& sampler = asset.samplers[gltfTexture.sampler]; switch(sampler.magFilter) { case gltf2::Sampler::MagFilter::None: break; case gltf2::Sampler::MagFilter::Nearest: textureBuilder.setMagFilter(Render::Texture::Filter::Nearest); break; case gltf2::Sampler::MagFilter::Linear: textureBuilder.setMagFilter(Render::Texture::Filter::Linear); break; } switch(sampler.minFilter) { case gltf2::Sampler::MinFilter::None: break; case gltf2::Sampler::MinFilter::Nearest: textureBuilder.setMinFilter(Render::Texture::Filter::Nearest); break; case gltf2::Sampler::MinFilter::Linear: textureBuilder.setMinFilter(Render::Texture::Filter::Linear); break; case gltf2::Sampler::MinFilter::NearestMipMapNearest: textureBuilder.setMinFilter(Render::Texture::Filter::Nearest); textureBuilder.setMipMapFilter(Render::Texture::Filter::Nearest); break; case gltf2::Sampler::MinFilter::LinearMipMapNearest: textureBuilder.setMinFilter(Render::Texture::Filter::Linear); textureBuilder.setMipMapFilter(Render::Texture::Filter::Nearest); break; case gltf2::Sampler::MinFilter::NearestMipMapLinear: textureBuilder.setMinFilter(Render::Texture::Filter::Nearest); textureBuilder.setMipMapFilter(Render::Texture::Filter::Linear); break; case gltf2::Sampler::MinFilter::LinearMipMapLinear: textureBuilder.setMinFilter(Render::Texture::Filter::Linear); textureBuilder.setMipMapFilter(Render::Texture::Filter::Linear); break; } switch(sampler.wrapS) { case gltf2::Sampler::WrappingMode::ClampToEdge: textureBuilder.setWrapS(Render::Texture::WrappingMode::ClampToEdge); break; case gltf2::Sampler::WrappingMode::MirroredRepeat: textureBuilder.setWrapS(Render::Texture::WrappingMode::MirroredRepeat); break; case gltf2::Sampler::WrappingMode::Repeat: textureBuilder.setWrapS(Render::Texture::WrappingMode::Repeat); break; } switch(sampler.wrapT) { case gltf2::Sampler::WrappingMode::ClampToEdge: textureBuilder.setWrapT(Render::Texture::WrappingMode::ClampToEdge); break; case gltf2::Sampler::WrappingMode::MirroredRepeat: textureBuilder.setWrapT(Render::Texture::WrappingMode::MirroredRepeat); break; case gltf2::Sampler::WrappingMode::Repeat: textureBuilder.setWrapT(Render::Texture::WrappingMode::Repeat); break; } } loadedAssets.textures[index] = textureBuilder.build(); return loadedAssets.textures[index]; } Resource::SharedPtr<Render::Material> GltfLoader::createMaterial(Renderer& renderer, const gltf2::Asset& asset, GltfLoader::LoadedAssets& loadedAssets, int32_t index) { if (index == -1) { return createDefaultMaterial(renderer, loadedAssets); } if (loadedAssets.materials[index]) { return loadedAssets.materials[index]; } const gltf2::Material& gltfMaterial = asset.materials[index]; Builder::Material materialBuilder(renderer); materialBuilder.setName(gltfMaterial.name); materialBuilder.setBaseColorFactor({ gltfMaterial.pbr.baseColorFactor[0], gltfMaterial.pbr.baseColorFactor[1], gltfMaterial.pbr.baseColorFactor[2], gltfMaterial.pbr.baseColorFactor[3] }); if (gltfMaterial.pbr.baseColorTexture.index != -1) { Resource::SharedPtr<Render::Texture> texture = createTexture(renderer, asset, loadedAssets, gltfMaterial.pbr.baseColorTexture.index); if (!texture) { LUG_LOG.error("GltfLoader::createMaterial Can't create the texture resource"); return nullptr; } materialBuilder.setBaseColorTexture(texture, gltfMaterial.pbr.baseColorTexture.texCoord); } materialBuilder.setMetallicFactor(gltfMaterial.pbr.metallicFactor); materialBuilder.setRoughnessFactor(gltfMaterial.pbr.roughnessFactor); if (gltfMaterial.pbr.metallicRoughnessTexture.index != -1) { Resource::SharedPtr<Render::Texture> texture = createTexture(renderer, asset, loadedAssets, gltfMaterial.pbr.metallicRoughnessTexture.index); if (!texture) { LUG_LOG.error("GltfLoader::createMaterial Can't create the texture resource"); return nullptr; } materialBuilder.setMetallicRoughnessTexture(texture, gltfMaterial.pbr.metallicRoughnessTexture.texCoord); } if (gltfMaterial.normalTexture.index != -1) { Resource::SharedPtr<Render::Texture> texture = createTexture(renderer, asset, loadedAssets, gltfMaterial.normalTexture.index); if (!texture) { LUG_LOG.error("GltfLoader::createMaterial Can't create the texture resource"); return nullptr; } materialBuilder.setNormalTexture(texture, gltfMaterial.normalTexture.texCoord); } if (gltfMaterial.occlusionTexture.index != -1) { Resource::SharedPtr<Render::Texture> texture = createTexture(renderer, asset, loadedAssets, gltfMaterial.occlusionTexture.index); if (!texture) { LUG_LOG.error("GltfLoader::createMaterial Can't create the texture resource"); return nullptr; } materialBuilder.setOcclusionTexture(texture, gltfMaterial.occlusionTexture.texCoord); } if (gltfMaterial.emissiveTexture.index != -1) { Resource::SharedPtr<Render::Texture> texture = createTexture(renderer, asset, loadedAssets, gltfMaterial.emissiveTexture.index); if (!texture) { LUG_LOG.error("GltfLoader::createMaterial Can't create the texture resource"); return nullptr; } materialBuilder.setEmissiveTexture(texture, gltfMaterial.emissiveTexture.texCoord); } materialBuilder.setEmissiveFactor({ gltfMaterial.emissiveFactor[0], gltfMaterial.emissiveFactor[1], gltfMaterial.emissiveFactor[2] }); loadedAssets.materials[index] = materialBuilder.build(); return loadedAssets.materials[index]; } Resource::SharedPtr<Render::Material> GltfLoader::createDefaultMaterial(Renderer& renderer, GltfLoader::LoadedAssets& loadedAssets) { if (loadedAssets.defaultMaterial) { return loadedAssets.defaultMaterial; } Builder::Material materialBuilder(renderer); loadedAssets.defaultMaterial = materialBuilder.build(); return loadedAssets.defaultMaterial; } static void* generateNormals(float* positions, uint32_t accessorCount) { Math::Vec3f* data = new Math::Vec3f[accessorCount]; uint32_t trianglesCount = accessorCount / 3; uint32_t positionsIdx = 0; for (uint32_t i = 0; i < trianglesCount; ++i) { Math::Vec3f a{positions[positionsIdx], positions[positionsIdx + 1], positions[positionsIdx + 2]}; Math::Vec3f b{positions[positionsIdx + 3], positions[positionsIdx + 4], positions[positionsIdx + 5]}; Math::Vec3f c{positions[positionsIdx + 6], positions[positionsIdx + 7], positions[positionsIdx + 8]}; Math::Vec3f edge1 = b - a; Math::Vec3f edge2 = c - a; data[i++] = cross(edge1, edge2); } return data; } Resource::SharedPtr<Render::Mesh> GltfLoader::createMesh(Renderer& renderer, const gltf2::Asset& asset, GltfLoader::LoadedAssets& loadedAssets, int32_t index) { const gltf2::Mesh& gltfMesh = asset.meshes[index]; if (loadedAssets.meshes[index]) { return loadedAssets.meshes[index]; } Builder::Mesh meshBuilder(renderer); meshBuilder.setName(gltfMesh.name); for (const gltf2::Primitive& gltfPrimitive : gltfMesh.primitives) { Builder::Mesh::PrimitiveSet* primitiveSet = meshBuilder.addPrimitiveSet(); // Mode switch (gltfPrimitive.mode) { case gltf2::Primitive::Mode::Points: primitiveSet->setMode(Render::Mesh::PrimitiveSet::Mode::Points); break; case gltf2::Primitive::Mode::Lines: primitiveSet->setMode(Render::Mesh::PrimitiveSet::Mode::Lines); break; case gltf2::Primitive::Mode::LineLoop: LUG_LOG.error("GltfLoader::createMesh Unsupported mode LineLoop"); return nullptr; case gltf2::Primitive::Mode::LineStrip: primitiveSet->setMode(Render::Mesh::PrimitiveSet::Mode::LineStrip); break; case gltf2::Primitive::Mode::Triangles: primitiveSet->setMode(Render::Mesh::PrimitiveSet::Mode::Triangles); break; case gltf2::Primitive::Mode::TriangleStrip: primitiveSet->setMode(Render::Mesh::PrimitiveSet::Mode::TriangleStrip); break; case gltf2::Primitive::Mode::TriangleFan: primitiveSet->setMode(Render::Mesh::PrimitiveSet::Mode::TriangleFan); break; } // Indices if (gltfPrimitive.indices != -1) { const gltf2::Accessor& accessor = asset.accessors[gltfPrimitive.indices]; // Get the accessor from its index (directly from indices) uint32_t componentSize = getAttributeSize(accessor); void* data = getBufferViewData(asset, accessor); if (!data) { return nullptr; } primitiveSet->addAttributeBuffer( data, componentSize, accessor.count, Render::Mesh::PrimitiveSet::Attribute::Type::Indice ); } // Attributes struct { void* data{nullptr}; uint32_t accessorCount{0}; } positions; // Store positions for normals generation bool hasNormals = false; for (auto& attribute : gltfPrimitive.attributes) { Render::Mesh::PrimitiveSet::Attribute::Type type; if (attribute.first == "POSITION") { type = Render::Mesh::PrimitiveSet::Attribute::Type::Position; } else if (attribute.first == "NORMAL") { type = Render::Mesh::PrimitiveSet::Attribute::Type::Normal; hasNormals = true; } else if (attribute.first == "TANGENT") { type = Render::Mesh::PrimitiveSet::Attribute::Type::Tangent; } else if (attribute.first.find("TEXCOORD_") != std::string::npos) { type = Render::Mesh::PrimitiveSet::Attribute::Type::TexCoord; } else if (attribute.first.find("COLOR_") != std::string::npos) { type = Render::Mesh::PrimitiveSet::Attribute::Type::Color; } else { LUG_LOG.warn("GltfLoader::createMesh Unsupported attribute {}", attribute.first); continue; } // TODO(nokitoo): See if we can use COLOR_0 or if we just discard it const gltf2::Accessor& accessor = asset.accessors[attribute.second]; // Get the accessor from its index (second in the pair) uint32_t componentSize = getAttributeSize(accessor); void* data = getBufferViewData(asset, accessor); if (!data) { return nullptr; } if (type == Render::Mesh::PrimitiveSet::Attribute::Type::Position) { // Store positions in case we need to generate the normals later positions.data = data; positions.accessorCount = accessor.count; } primitiveSet->addAttributeBuffer(data, componentSize, accessor.count, type); } // Generate flat normals if there is not any if (!hasNormals) { void* data = generateNormals((float*)positions.data, positions.accessorCount); if (!data) { return nullptr; } primitiveSet->addAttributeBuffer( data, sizeof(Math::Vec3f), positions.accessorCount, Render::Mesh::PrimitiveSet::Attribute::Type::Normal ); } // Material Resource::SharedPtr<Render::Material> material = createMaterial(renderer, asset, loadedAssets, gltfPrimitive.material); if (!material) { LUG_LOG.error("GltfLoader::createMesh Can't create the material resource"); return nullptr; } primitiveSet->setMaterial(material); // TODO(nokitoo): set node transformations } loadedAssets.meshes[index] = meshBuilder.build(); return loadedAssets.meshes[index]; } bool GltfLoader::createNode(Renderer& renderer, const gltf2::Asset& asset, GltfLoader::LoadedAssets& loadedAssets, int32_t index, Scene::Node& parent) { const gltf2::Node& gltfNode = asset.nodes[index]; Scene::Node* node = parent.createSceneNode(gltfNode.name); parent.attachChild(*node); if (gltfNode.mesh != -1) { Resource::SharedPtr<Render::Mesh> mesh = createMesh(renderer, asset, loadedAssets, gltfNode.mesh); if (!mesh) { LUG_LOG.error("GltfLoader::createNode Can't create the mesh resource"); return false; } node->attachMeshInstance(mesh); } node->setPosition({ gltfNode.translation[0], gltfNode.translation[1], gltfNode.translation[2] }, Node::TransformSpace::Parent); node->setRotation(Math::Quatf{ gltfNode.rotation[3], gltfNode.rotation[0], gltfNode.rotation[1], gltfNode.rotation[2] }, Node::TransformSpace::Parent); node->scale({ gltfNode.scale[0], gltfNode.scale[1], gltfNode.scale[2] }); for (uint32_t nodeIdx : gltfNode.children) { if (!createNode(renderer, asset, loadedAssets, nodeIdx, *node)) { return false; } } return true; } Resource::SharedPtr<Resource> GltfLoader::loadFile(const std::string& filename) { gltf2::Asset asset; try { #if defined(LUG_SYSTEM_ANDROID) asset = gltf2::load(filename, (lug::Window::priv::WindowImpl::activity)->assetManager); #else asset = gltf2::load(filename); #endif // TODO(nokitoo): Format the asset if not already done // Should we store the version of format in asset.extensions or asset.copyright/asset.version ? } catch (gltf2::MisformattedException& e) { LUG_LOG.error("GltfLoader::loadFile Can't load the file \"{}\": {}", filename, e.what()); return nullptr; } // Create the container for the already loaded assets GltfLoader::LoadedAssets loadedAssets; loadedAssets.textures.resize(asset.textures.size()); loadedAssets.materials.resize(asset.materials.size()); loadedAssets.meshes.resize(asset.meshes.size()); // Load the scene if (asset.scene == -1) { // No scene to load return nullptr; } const gltf2::Scene& gltfScene = asset.scenes[asset.scene]; Builder::Scene sceneBuilder(_renderer); sceneBuilder.setName(gltfScene.name); Resource::SharedPtr<lug::Graphics::Scene::Scene> scene = sceneBuilder.build(); if (!scene) { LUG_LOG.error("GltfLoader::loadFile Can't create the scene resource"); return nullptr; } for (uint32_t nodeIdx : gltfScene.nodes) { if (!createNode(_renderer, asset, loadedAssets, nodeIdx, scene->getRoot())) { return nullptr; } } return Resource::SharedPtr<Resource>::cast(scene); } } // Graphics } // lug
38.868952
168
0.635147
Lugdunum3D
656e2da18bebbd4f035afda333be8b0dbf5ec7a9
550
cpp
C++
app/hibp_convert.cpp
oschonrock/hibp
690309ed4b13f89b4622155a15da1a344e2f63dd
[ "Apache-2.0" ]
null
null
null
app/hibp_convert.cpp
oschonrock/hibp
690309ed4b13f89b4622155a15da1a344e2f63dd
[ "Apache-2.0" ]
null
null
null
app/hibp_convert.cpp
oschonrock/hibp
690309ed4b13f89b4622155a15da1a344e2f63dd
[ "Apache-2.0" ]
null
null
null
#include "flat_file.hpp" #include "hibp.hpp" #include <cstdlib> int main(int /* argc */, char* argv[]) { std::ios_base::sync_with_stdio(false); std::cerr << argv[0] << ": reading `have i been pawned` text database from stdin,\n" "converting to binary format and writing to stdout." << std::endl; auto writer = flat_file::stream_writer<hibp::pawned_pw>(std::cout); for (std::string line; std::getline(std::cin, line);) writer.write(hibp::convert_to_binary(line)); return EXIT_SUCCESS; }
28.947368
88
0.630909
oschonrock
656f71c8f3474b223f685bbdb0ce01589dce8a63
4,126
cpp
C++
heap.cpp
MichaelRFairhurst/vaiven
47a0ae7fbfd10aee7bed1d6c25bdb566b1a10174
[ "Apache-2.0" ]
61
2017-03-22T11:25:15.000Z
2021-11-19T23:12:48.000Z
heap.cpp
MichaelRFairhurst/vaiven
47a0ae7fbfd10aee7bed1d6c25bdb566b1a10174
[ "Apache-2.0" ]
2
2019-07-05T23:41:36.000Z
2019-07-14T23:32:18.000Z
heap.cpp
MichaelRFairhurst/vaiven
47a0ae7fbfd10aee7bed1d6c25bdb566b1a10174
[ "Apache-2.0" ]
2
2018-06-27T16:11:24.000Z
2018-07-05T07:31:44.000Z
#include "heap.h" #include <algorithm> #include <cassert> #include "stack.h" using namespace vaiven; using std::min; using std::max; // set by interpreter Heap* vaiven::globalHeap = NULL; GcableType vaiven::Gcable::getType() { return (GcableType) (((GcableType) this->type) & ~GcableMarkBit); } bool vaiven::Gcable::isMarked() { return (this->type & GcableMarkBit) == GcableMarkBit; } bool vaiven::Gcable::mark() { if (isMarked()) { return false; } this->type = (GcableType) (((GcableType) this->type) | GcableMarkBit); return true; } void vaiven::Gcable::unmark() { this->type = (GcableType) (((GcableType) this->type) & ~GcableMarkBit); } GcableList* vaiven::Heap::newList() { if (isFull()) { gc(); } GcableList* ptr = new GcableList(); owned_ptrs.insert(ptr); heap_min = min(heap_min, (uint64_t) ptr); heap_max = max(heap_max, (uint64_t) ptr); return ptr; } GcableString* vaiven::Heap::newString() { if (isFull()) { gc(); } GcableString* ptr = new GcableString(); owned_ptrs.insert(ptr); heap_min = min(heap_min, (uint64_t) ptr); heap_max = max(heap_max, (uint64_t) ptr); return ptr; } GcableObject* vaiven::Heap::newObject() { if (isFull()) { gc(); } GcableObject* ptr = new GcableObject(); owned_ptrs.insert(ptr); heap_min = min(heap_min, (uint64_t) ptr); heap_max = max(heap_max, (uint64_t) ptr); return ptr; } bool vaiven::Heap::owns(void* ptr) { uint64_t addr = (uint64_t) ptr; // inside heap and is aligned to 64 bits if (addr < heap_min || addr > heap_max || addr & 7 != 1) { return false; } return owned_ptrs.find((Gcable*) ptr) != owned_ptrs.end(); } bool vaiven::Heap::isFull() { return owned_ptrs.size() >= size; } void vaiven::Heap::mark(Gcable* ptr) { if (!owns(ptr)) { return; } if (ptr->mark()) { return; } switch (ptr->getType()) { case GCABLE_TYPE_LIST: { GcableList* list = (GcableList*) ptr; for (vector<Value>::iterator it = list->list.begin(); it != list->list.end(); ++it) { mark(it->getPtr()); } break; } case GCABLE_TYPE_STRING: // already marked, nothing to do break; case GCABLE_TYPE_OBJECT: { GcableObject* object = (GcableObject*) ptr; for (unordered_map<string, Value>::iterator it = object->properties.begin(); it != object->properties.end(); ++it) { mark(it->second.getPtr()); } } } } void vaiven::Heap::sweep() { unordered_set<Gcable*>::iterator it = owned_ptrs.begin(); while (it != owned_ptrs.end()) { Gcable* gcable = (Gcable*) *it; if (!gcable->isMarked()) { switch (gcable->getType()) { case GCABLE_TYPE_LIST: delete static_cast<GcableList*>(gcable); break; case GCABLE_TYPE_STRING: delete static_cast<GcableString*>(gcable); break; case GCABLE_TYPE_OBJECT: delete static_cast<GcableObject*>(gcable); break; } it = owned_ptrs.erase(it); } else { gcable->unmark(); ++it; } } } void vaiven::Heap::free(Gcable* ptr) { if (ptr->getType() == GCABLE_TYPE_LIST) { delete (GcableList*) ptr; } else if (ptr->getType() == GCABLE_TYPE_STRING) { delete (GcableString*) ptr; } else if (ptr->getType() == GCABLE_TYPE_OBJECT) { delete (GcableObject*) ptr; } owned_ptrs.erase(ptr); } void vaiven::Heap::gc() { Stack callStack; StackFrame frame = callStack.top(); while (true) { for (int i = 0; i < frame.size; ++i) { mark((Gcable*) frame.locals[i]); } if (!frame.hasNext()) { break; } frame = frame.next(); } for (std::deque<Value>::iterator it = interpreterStack.c.begin(); it != interpreterStack.c.end(); ++it) { mark((Gcable*) it->getPtr()); } std::map<string, Value> scopeMap; globalScope.fill(scopeMap); for (std::map<string, Value>::iterator it = scopeMap.begin(); it != scopeMap.end(); ++it) { mark((Gcable*) it->second.getPtr()); } sweep(); size = max((int) owned_ptrs.size() * HEAP_FACTOR, MIN_HEAP_SIZE); }
22.302703
124
0.60349
MichaelRFairhurst
65721c4f649cc6e333e45345687d2f6f913f4849
590
cpp
C++
perception_oru-port-kinetic/graph_map/src/ndt_dl/ndtdl_map_param.cpp
lllray/ndt-loam
331867941e0764b40e1a980dd85d2174f861e9c8
[ "BSD-3-Clause" ]
1
2020-11-14T08:21:13.000Z
2020-11-14T08:21:13.000Z
perception_oru-port-kinetic/graph_map/src/ndt_dl/ndtdl_map_param.cpp
lllray/ndt-loam
331867941e0764b40e1a980dd85d2174f861e9c8
[ "BSD-3-Clause" ]
1
2021-07-28T04:47:56.000Z
2021-07-28T04:47:56.000Z
perception_oru-port-kinetic/graph_map/src/ndt_dl/ndtdl_map_param.cpp
lllray/ndt-loam
331867941e0764b40e1a980dd85d2174f861e9c8
[ "BSD-3-Clause" ]
2
2020-12-18T11:25:53.000Z
2022-02-19T12:59:59.000Z
#include "graph_map/ndt_dl/ndtdl_map_param.h" #include <boost/serialization/export.hpp> BOOST_CLASS_EXPORT(perception_oru::libgraphMap::NDTDLMapParam) using namespace std; namespace perception_oru{ namespace libgraphMap{ void NDTDLMapParam::GetParametersFromRos(){ MapParam::GetParametersFromRos(); ros::NodeHandle nh("~"); cout<<"reading parameters from ros inside NDTDLMapParam::GetRosParametersFromRos()"<<endl; nh.param<std::string>("Super_important_map_parameter",SuperImportantMapParameter,"parhaps not so important..."); nh.param("resolution",resolution_,1.0); } } }
26.818182
114
0.786441
lllray
6573ece9acf8698ec8d945159bec5a18d4713324
1,830
hpp
C++
include/owlcpp/detail/vector_set.hpp
GreyMerlin/owl_cpp
ccc6128dbd08dcf7fcbe6679ec6acd714732bbb6
[ "BSL-1.0" ]
10
2017-12-21T05:20:40.000Z
2021-09-18T05:14:01.000Z
include/owlcpp/detail/vector_set.hpp
GreyMerlin/owl_cpp
ccc6128dbd08dcf7fcbe6679ec6acd714732bbb6
[ "BSL-1.0" ]
2
2017-12-21T07:31:54.000Z
2021-06-23T08:52:35.000Z
include/owlcpp/detail/vector_set.hpp
GreyMerlin/owl_cpp
ccc6128dbd08dcf7fcbe6679ec6acd714732bbb6
[ "BSL-1.0" ]
7
2016-02-17T13:20:31.000Z
2021-11-08T09:30:43.000Z
/** @file "/owlcpp/include/owlcpp/detail/vector_set.hpp" part of owlcpp project. @n @n Distributed under the Boost Software License, Version 1.0; see doc/license.txt. @n Copyright Mikhail K Levin 2013 *******************************************************************************/ #ifndef VECTOR_SET_HPP_ #define VECTOR_SET_HPP_ #include <vector> namespace owlcpp{ /**@brief Collection of unique objects stored in a vector *******************************************************************************/ template<class T, class Comp = std::less<T>, class Alloc = std::allocator<T> > class Vector_set { typedef std::vector<T, Alloc> stor_t; public: typedef T value_type; typedef typename stor_t::iterator iterator; typedef typename stor_t::const_iterator const_iterator; Vector_set() : v_(), comp_() {} Vector_set(Comp const& comp) : v_(), comp_(comp) {} iterator begin() {return v_.begin();} iterator end() {return v_.end();} const_iterator begin() const {return v_.begin();} const_iterator end() const {return v_.end();} std::size_t size() const {return v_.size();} std::pair<iterator, bool> insert(value_type const& t) { iterator i = std::lower_bound(v_.begin(), v_.end(), t, comp_); if( i == v_.end() || comp_(t, *i) ) { return std::make_pair(v_.insert(i, t), true); } return std::make_pair(i, false); } const_iterator find(value_type const& t) const { const_iterator i = std::lower_bound(v_.begin(), v_.end(), t, comp_); if( i == v_.end() || comp_(t, *i) ) return v_.end(); return i; } value_type const& operator[](const std::size_t n) const {return v_[n];} value_type const& at(const std::size_t n) const {return v_.at(n);} private: stor_t v_; Comp comp_; }; }//namespace owlcpp #endif /* VECTOR_SET_HPP_ */
34.528302
85
0.604372
GreyMerlin
6576840e8ff3dd280cb0c3738aa2fc72123e5ae2
2,455
hpp
C++
falcon/functional/invoke_partial_recursive_param_loop.hpp
jonathanpoelen/falcon
5b60a39787eedf15b801d83384193a05efd41a89
[ "MIT" ]
2
2018-02-02T14:19:59.000Z
2018-05-13T02:48:24.000Z
falcon/functional/invoke_partial_recursive_param_loop.hpp
jonathanpoelen/falcon
5b60a39787eedf15b801d83384193a05efd41a89
[ "MIT" ]
null
null
null
falcon/functional/invoke_partial_recursive_param_loop.hpp
jonathanpoelen/falcon
5b60a39787eedf15b801d83384193a05efd41a89
[ "MIT" ]
null
null
null
#ifndef FALCON_FUNCTIONAL_INVOKE_PARTIAL_RECURSIVE_PARAM_HPP #define FALCON_FUNCTIONAL_INVOKE_PARTIAL_RECURSIVE_PARAM_HPP #include <falcon/math/min.hpp> #include <falcon/c++1x/syntax.hpp> #include <falcon/functional/invoke.hpp> #include <falcon/parameter/manip.hpp> #include <falcon/preprocessor/not_ide_parser.hpp> #include <utility> namespace falcon { template<std::size_t NumberArg> class invoke_partial_recursive_param_loop_fn { static_assert(NumberArg > 1, "NumberArg < 2"); template<std::size_t N, class = void> struct Impl { template< class F, class... Args , std::size_t Start = (N - 1) * (NumberArg - 1) + NumberArg + 1> static constexpr CPP1X_DELEGATE_FUNCTION( impl_(F && func, Args&&... args) , invoke( typename parameter_index_cat< parameter_index<0>, build_range_parameter_index_t< Start , min(Start + (NumberArg - 1), sizeof...(Args) + 1) > >::type() , std::forward<F>(func) , Impl<N-1>::impl_(std::forward<F>(func), std::forward<Args>(args)...) , std::forward<Args>(args)... ) ) }; template<class T> struct Impl<0, T> { template<class F, class... Args> static constexpr CPP1X_DELEGATE_FUNCTION( impl_(F && func, Args&&... args) , invoke( build_parameter_index_t<min(NumberArg, sizeof...(Args))>() , std::forward<F>(func) , std::forward<Args>(args)... ) ) }; public: constexpr invoke_partial_recursive_param_loop_fn() noexcept {} template< class F, class... Args , std::size_t N = (sizeof...(Args) - 2) / (NumberArg - 1)> constexpr CPP1X_DELEGATE_FUNCTION( operator()(F && func, Args&&... args) const , Impl<N>::impl_(std::forward<F>(func), std::forward<Args>(args)...) ) }; /** * \brief Call \c func with \c NumberArg arguments. The return of \c func is the first argument of next call. * \return Last operations. * * \code * int n = invoke_partial_param_loop<2>(accu_t(), 1,2,3,4,5,6); * \endcode * equivalent to * \code * accu_t accu; * int n = accu(accu(accu(accu(accu(1,2),3),4),5),6); * \endcode * * \ingroup call-arguments */ template<std::size_t NumberArg, class F, class... Args> constexpr CPP1X_DELEGATE_FUNCTION( invoke_partial_recursive_param_loop(F func, Args&&... args) , invoke_partial_recursive_param_loop_fn<NumberArg>()( std::forward<F>(func), std::forward<Args>(args)...) ) } #endif
26.684783
109
0.648473
jonathanpoelen
65773eb4d3d4009263fbd5df2240e268355ac09a
309
cpp
C++
Decorator Pattern/Decorator Pattern/HouseBlend.cpp
mrlegowatch/HeadFirstDesignPatternsCpp
436ee8f0344b6a2ccfef6dcfa216a16a6ca7b482
[ "MIT" ]
43
2018-07-17T21:53:21.000Z
2022-03-23T13:15:06.000Z
Decorator Pattern/Decorator Pattern/HouseBlend.cpp
mrlegowatch/HeadFirstDesignPatternsCpp
436ee8f0344b6a2ccfef6dcfa216a16a6ca7b482
[ "MIT" ]
null
null
null
Decorator Pattern/Decorator Pattern/HouseBlend.cpp
mrlegowatch/HeadFirstDesignPatternsCpp
436ee8f0344b6a2ccfef6dcfa216a16a6ca7b482
[ "MIT" ]
14
2019-04-10T13:01:07.000Z
2022-03-08T13:19:14.000Z
// // HouseBlend.cpp // Decorator Pattern // // Created by Kevin Lee on 2/13/18. // Copyright © 2018 Brian Arnold. All rights reserved. // #include "HouseBlend.hpp" std::string HouseBlend::getDescription() const { return "House Blend Coffee"; } double HouseBlend::cost() const { return 0.89; }
17.166667
55
0.673139
mrlegowatch
657b6e05c0b450096ec97900a9be50fd856371f9
10,078
cpp
C++
eX0/src/PolyBoolean/pbpolys.cpp
shurcooL/eX0
425cdd4bace184bef3b63efa0867add4e469e291
[ "MIT" ]
54
2015-03-09T08:38:12.000Z
2021-06-20T15:54:57.000Z
eX0/src/PolyBoolean/pbpolys.cpp
shurcooL/eX0
425cdd4bace184bef3b63efa0867add4e469e291
[ "MIT" ]
7
2015-03-02T21:03:54.000Z
2017-12-21T06:06:00.000Z
eX0/src/PolyBoolean/pbpolys.cpp
shurcooL/eX0
425cdd4bace184bef3b63efa0867add4e469e291
[ "MIT" ]
10
2015-03-11T06:38:38.000Z
2021-05-10T04:35:33.000Z
// pbpolys.cpp - basic operations with vertices and polygons // // This file is a part of PolyBoolean software library // (C) 1998-1999 Michael Leonov // Consult your license regarding permissions and restrictions // // fix: 2006 Oct 2 Alexey Nikitin // PLINE2::Prepare / left middle point from 3 points on the same line #include "polybool.h" #include "pbimpl.h" #define SETBITS(n,mask,s) (((n)->Flags & ~(mask)) | ((s) & mask)) namespace POLYBOOLEAN { ////////////////////// class VNODE2 ///////////////////////////// VNODE2 * VNODE2::New(const GRID2 & g) { VNODE2 * res = (VNODE2 *)calloc(1, sizeof(VNODE2)); if (res == NULL) error(err_no_memory); res->g = g; res->prev = res->next = res; return res; } // VNODE2::New //////////////////// class PLINE2 ///////////////////////// local void AdjustBox(PLINE2 * pline, const GRID2 & g) { if (pline->gMin.x > g.x) pline->gMin.x = g.x; if (pline->gMin.y > g.y) pline->gMin.y = g.y; if (pline->gMax.x < g.x) pline->gMax.x = g.x; if (pline->gMax.y < g.y) pline->gMax.y = g.y; } // AdjustBox local bool GridInBox(const GRID2 & g, const PLINE2 * pline) { return (g.x > pline->gMin.x and g.y > pline->gMin.y and g.x < pline->gMax.x and g.y < pline->gMax.y); } // GridInBox local bool BoxInBox(const PLINE2 * c1, const PLINE2 * c2) { return (c1->gMin.x >= c2->gMin.x and c1->gMin.y >= c2->gMin.y and c1->gMax.x <= c2->gMax.x and c1->gMax.y <= c2->gMax.y); } // BoxInBox void PLINE2::Del(PLINE2 ** pline) { if (*pline == NULL) return; VNODE2 *vn; while ((vn = (*pline)->head->next) != (*pline)->head) vn->Excl(), free(vn); free(vn); free(*pline), *pline = NULL; } // PLINE2::Del PLINE2 * PLINE2::New(const GRID2 &g) { PLINE2 *res = (PLINE2 *)calloc(1, sizeof(PLINE2)); if (res == NULL) error(err_no_memory); try { res->head = VNODE2::New(g); } catch (int) { free(res); throw; } res->gMax = res->gMin = g; res->Count = 1; return res; } // PLINE2::New local void InclPlineVnode(PLINE2 *c, VNODE2 *vn) { assert(vn != NULL and c != NULL); vn->Incl(c->head->prev); c->Count++; AdjustBox(c, vn->g); } // InclPlineVnode void PLINE2::Incl(PLINE2 ** pline, const GRID2 & g) { if (*pline == NULL) *pline = PLINE2::New(g); else InclPlineVnode(*pline, VNODE2::New(g)); } // PLINE2::Incl PLINE2 * PLINE2::Copy(bool bMakeLinks) const { PLINE2 * dst = NULL; VNODE2* vn = head; try { do { Incl(&dst, vn->g); if (bMakeLinks) (vn->vn = dst->head->prev)->vn = vn; } while ((vn = vn->next) != head); } catch (int) { Del(&dst); throw; } dst->Count = Count; dst->Flags = Flags; dst->gMin = gMin; dst->gMax = gMax; return dst; } // PLINE2::Copy // returns if b lies on (a,c) local bool PointOnLine(const GRID2 & a, const GRID2 & b, const GRID2 & c) { return (INT64)(b.x - a.x) * (c.y - b.y) == (INT64)(b.y - a.y) * (c.x - b.x); } // PointOnLine bool PLINE2::Prepare() { gMin.x = gMax.x = head->g.x; gMin.y = gMax.y = head->g.y; // remove coincident vertices and those lying on the same line VNODE2 * p = head; VNODE2 * c = p->next; for (int test = 0, tests = Count; test < tests; ++test) { VNODE2 * n = c->next; if (PointOnLine(p->g, c->g, n->g)) { ++tests; if (n == head) ++tests; --Count; if (Count < 3) return false; if (c == head) head = p; c->Excl(), free(c); p = (c = p)->prev; } else { p = c; c = n; } } c = head; p = c->prev; INT64 nArea = 0; do { nArea += (INT64)(p->g.x - c->g.x) * (p->g.y + c->g.y); AdjustBox(this, c->g); } while ((c = (p = c)->next) != head); if (nArea == 0) return false; Flags = SETBITS(this, ORIENT, (nArea < 0) ? INV : DIR); return true; } // PLINE2::Prepare void PLINE2::Invert() { VNODE2 *vn = head, *next; do { next = vn->next, vn->next = vn->prev, vn->prev = next; } while ((vn = next) != head); Flags ^= ORIENT; } // PLINE2::Invert /********************** PAREA stuff **********************************/ PAREA *PAREA::New() { PAREA *res = (PAREA *)calloc(1, sizeof(PAREA)); if (res == NULL) error(err_no_memory); return res->f = res->b = res; } // PAREA::New local void ClearArea(PAREA *P) { PLINE2 *p; assert(P != NULL); while ((p = P->cntr) != NULL) { P->cntr = p->next; PLINE2::Del(&p); } free(P->tria), P->tria = NULL; P->tnum = 0; } // ClearArea void PAREA::Del(PAREA ** p) { if (*p == NULL) return; PAREA *cur; while ((cur = (*p)->f) != *p) { (cur->b->f = cur->f)->b = cur->b; ClearArea(cur); free(cur); } ClearArea(cur); free(cur), *p = NULL; } // PAREA::Del local void InclPareaPline(PAREA * p, PLINE2 * c) { assert(c->next == NULL); if (c->IsOuter()) { assert(p->cntr == NULL); p->cntr = c; } else { assert(p->cntr != NULL); c->next = p->cntr->next, p->cntr->next = c; } } // InclPareaPline void PAREA::InclParea(PAREA **list, PAREA *a) { if (a != NULL) { if (*list == NULL) *list = a; else (((a->b = (*list)->b)->f = a)->f = *list)->b = a; } } // PAREA::InclParea void PAREA::InclPline(PAREA ** area, PLINE2 * pline) { assert(pline != NULL and pline->next == NULL); PAREA * t; if (pline->IsOuter()) { t = New(); InclParea(area, t); } else { assert(*area != NULL); // find the smallest container for the hole t = NULL; PAREA * pa = *area; do { if (PlineInPline(pline, pa->cntr) and (t == NULL or PlineInPline(pa->cntr, t->cntr))) t = pa; } while ((pa = pa->f) != *area); if (t == NULL) // couldn't find a container for the hole error(err_bad_parm); } InclPareaPline(t, pline); } // PAREA::InclPline void PLINE2::Put(PLINE2 * pline, PAREA ** area, PLINE2 ** holes) { assert(pline->next == NULL); if (pline->IsOuter()) PAREA::InclPline(area, pline); else pline->next = *holes, *holes = pline; } // PLINE2::Put void PAREA::InsertHoles(PAREA ** area, PLINE2 ** holes) { if (*holes == NULL) return; if (*area == NULL) error(err_bad_parm); while (*holes != NULL) { PLINE2 * next = (*holes)->next; (*holes)->next = NULL; InclPline(area, *holes); *holes = next; } } // PAREA::InsertHoles local PAREA * PareaCopy0(const PAREA * area) { PAREA * dst = NULL; try { for (const PLINE2 * pline = area->cntr; pline != NULL; pline = pline->next) PAREA::InclPline(&dst, pline->Copy(true)); if (area->tria == NULL) return dst; dst->tria = (PTRIA2 *)calloc(area->tnum, sizeof(PTRIA2)); if (dst->tria == NULL) error(err_no_memory); } catch (int) { PAREA::Del(&dst); throw; } dst->tnum = area->tnum; for (UINT32 i = 0; i < area->tnum; i++) { PTRIA2 * td = dst->tria + i; PTRIA2 * ts = area->tria + i; td->v0 = ts->v0->vn; td->v1 = ts->v1->vn; td->v2 = ts->v2->vn; } return dst; } // PareaCopy0 PAREA * PAREA::Copy() const { PAREA * dst = NULL; const PAREA *src = this; try { do { PAREA *di = PareaCopy0(src); InclParea(&dst, di); } while ((src = src->f) != this); } catch (int) { Del(&dst); throw; } return dst; } // PAREA::Copy bool GridInPline(const GRID2 * g, const PLINE2 * outer) { if (outer == NULL) return false; if (!GridInBox(*g, outer)) return false; const VNODE2 *vn = outer->head; bool bInside = false; do { const GRID2 & vc = vn->g; const GRID2 & vp = vn->prev->g; if (vc.y <= g->y and g->y < vp.y and (INT64)(vp.y - vc.y) * (g->x - vc.x) < (INT64)(g->y - vc.y) * (vp.x - vc.x)) { bInside = not bInside; } else if (vp.y <= g->y and g->y < vc.y and (INT64)(vp.y - vc.y) * (g->x - vc.x) > (INT64)(g->y - vc.y) * (vp.x - vc.x)) { bInside = not bInside; } } while ((vn = vn->next) != outer->head); return bInside; } // GridInPline bool PlineInPline(const PLINE2 * p, const PLINE2 * outer) { assert(p != NULL); return outer != NULL && BoxInBox(p, outer) and GridInPline(&p->head->g, outer); } // PlineInPline typedef bool (*INSIDE_PROC)(const void *p, const PLINE2 *outer); local bool PolyInside(const void *p, const PAREA * outfst, INSIDE_PROC ins_actor) { const PAREA * pa = outfst; if (pa == NULL) return false; assert(p != NULL && pa != NULL); do { const PLINE2 *curc = pa->cntr; if (ins_actor(p, curc)) { while ((curc = curc->next) != NULL) if (ins_actor(p, curc)) goto Proceed; return true; } Proceed: ; } while ((pa = pa->f) != outfst); return false; } // PolyInside bool GridInParea(const GRID2 * g, const PAREA * outer) { return PolyInside(g, outer, (INSIDE_PROC)GridInPline); } // GridInParea bool PlineInParea(const PLINE2* p, const PAREA * outer) { return PolyInside(p, outer, (INSIDE_PROC)PlineInPline); } // PlineInParea #ifndef NDEBUG local bool Chk(INT32 x) { return INT20_MIN > x or x > INT20_MAX; } bool PAREA::CheckDomain() { PAREA * pa = this; do { for (PLINE2 * pline = pa->cntr; pline != NULL; pline = pline->next) { if (Chk(pline->gMin.x) or Chk(pline->gMin.y) or Chk(pline->gMax.x) or Chk(pline->gMax.y)) return false; } } while ((pa = pa->f) != this); return true; } // PAREA::CheckDomain #endif // NDEBUG } // namespace POLYBOOLEAN
21.261603
78
0.513991
shurcooL
6583b3d93fb5f4885db405c9f64563c26ccf25f8
5,709
hpp
C++
sources/SceneGraph/Animation/spAnimationJoint.hpp
rontrek/softpixel
73a13a67e044c93f5c3da9066eedbaf3805d6807
[ "Zlib" ]
14
2015-08-16T21:05:20.000Z
2019-08-21T17:22:01.000Z
sources/SceneGraph/Animation/spAnimationJoint.hpp
rontrek/softpixel
73a13a67e044c93f5c3da9066eedbaf3805d6807
[ "Zlib" ]
null
null
null
sources/SceneGraph/Animation/spAnimationJoint.hpp
rontrek/softpixel
73a13a67e044c93f5c3da9066eedbaf3805d6807
[ "Zlib" ]
3
2020-02-15T09:17:41.000Z
2020-05-21T14:10:40.000Z
/* * Animation bone header * * This file is part of the "SoftPixel Engine" (Copyright (c) 2008 by Lukas Hermanns) * See "SoftPixelEngine.hpp" for license information. */ #ifndef __SP_ANIMATION_BONE_H__ #define __SP_ANIMATION_BONE_H__ #include "Base/spStandard.hpp" #include "Base/spInputOutputString.hpp" #include "Base/spDimension.hpp" #include "Base/spMemoryManagement.hpp" #include "SceneGraph/spSceneMesh.hpp" #include "Base/spTransformation3D.hpp" #include "SceneGraph/Animation/spAnimationBaseStructures.hpp" #include <vector> namespace sp { namespace scene { class AnimationSkeleton; /** Animation joints are the foundation of animation skeletons (used for skeletal animations). \see AnimationSkeleton. \ingroup group_animation */ class SP_EXPORT AnimationJoint : public BaseObject { public: AnimationJoint( const Transformation &OriginTransform, const io::stringc Name = "" ); virtual ~AnimationJoint(); /* === Functions === */ //! Returns the global joint transformation. virtual dim::matrix4f getGlobalTransformation() const; //! Returns the final vertex transformation. Use this to transform the vertices by yourself. virtual dim::matrix4f getVertexTransformation() const; /* === Inline functions === */ /** Enables or disables the bone. If disabled the bone won't be transformed automatically by the animation but you can still transform it manual. By default enabled. \todo RENAME this to "setAutoTransform" */ inline void setEnable(bool Enable) // !TODO! -> RENAME this to "setAutoTransform" { isEnable_ = Enable; } inline bool getEnable() const { return isEnable_; } //! Returns a pointer to the AnimationJoint parent object. inline AnimationJoint* getParent() const { return Parent_; } //! Sets the vertex groups list. inline void setVertexGroups(const std::vector<SVertexGroup> &VertexGroups) { VertexGroups_ = VertexGroups; } inline const std::vector<SVertexGroup>& getVertexGroups() const { return VertexGroups_; } inline std::vector<SVertexGroup>& getVertexGroups() { return VertexGroups_; } //! Sets the new (local) origin transformation. Internally the origin transformation is stored as inverse matrix. inline void setOriginTransformation(const Transformation &Transform) { OriginTransform_ = Transform; } inline Transformation getOriginTransformation() const { return OriginTransform_; } //! Sets the new (local) current transformation. inline void setTransformation(const Transformation &Transform) { Transform_ = Transform; } inline const Transformation& getTransformation() const { return Transform_; } inline Transformation& getTransformation() { return Transform_; } //! Returns the final origin matrix which will be computed when the "AnimationSkeleton::updateSkeleton" function is called. inline dim::matrix4f getOriginMatrix() const { return OriginMatrix_; } //! Returns the joint children list. inline const std::vector<AnimationJoint*>& getChildren() const { return Children_; } protected: friend class AnimationSkeleton; /* === Functions === */ /** Transforms the vertices of the specified Mesh object. Which vertices will be transformed depends on the bone's vertex groups. \param[in] MeshObj Specifies the mesh object which vertices are to be transformed. This pointer must never be null! \param[in] BaseMatrix: Specifies the base matrix transformation. If the bone has a parent this matrix should be its parent's matrix transformation. \param[in] useTangentSpace: Specifies whether tanget space is used or not. \note The pointer is not checked for validity! */ void transformVertices(scene::Mesh* MeshObj, dim::matrix4f BaseMatrix, bool useTangentSpace) const; bool checkParentIncest(AnimationJoint* Joint) const; /* === Inline functions === */ inline void setParent(AnimationJoint* Parent) { Parent_ = Parent; } inline void addChild(AnimationJoint* Child) { Children_.push_back(Child); } inline void removeChild(AnimationJoint* Child) { MemoryManager::removeElement(Children_, Child); } private: /* === Members === */ bool isEnable_; AnimationJoint* Parent_; std::vector<AnimationJoint*> Children_; Transformation OriginTransform_; //!< Origin transformation. Transformation Transform_; //!< Current transformation. dim::matrix4f OriginMatrix_; //!< Final origin transformation matrix. Stored as inverse matrix for combining with the current transformation. std::vector<SVertexGroup> VertexGroups_; }; } // /namespace scene } // /namespace sp #endif // ================================================================================
29.890052
156
0.602207
rontrek
658aabb1147a7a406e2f86a21215a02bc2ec3809
2,304
cpp
C++
ctable.cpp
Rescator7/Hearts
e72e46c5a1f90a0a553bf5527ee9a5aabf5154d7
[ "MIT" ]
13
2018-11-19T00:11:52.000Z
2022-03-31T20:01:49.000Z
ctable.cpp
Rescator7/Hearts
e72e46c5a1f90a0a553bf5527ee9a5aabf5154d7
[ "MIT" ]
3
2019-10-22T18:46:03.000Z
2022-03-31T18:16:48.000Z
ctable.cpp
Rescator7/Hearts
e72e46c5a1f90a0a553bf5527ee9a5aabf5154d7
[ "MIT" ]
2
2020-10-12T11:34:11.000Z
2021-01-21T07:12:56.000Z
#ifdef ONLINE_PLAY #include "ctable.h" #include "define.h" #include "ui_ctable.h" CTable::CTable(QWidget *parent) : QWidget(parent), ui(new Ui::CTable) { ui->setupUi(this); ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers); setWindowTitle(tr("Tables list")); setAttribute( Qt::WA_QuitOnClose, false ); } CTable::~CTable() { delete ui; } void CTable::AddRow(QString id, QString flags) { int rowc = ui->tableWidget->rowCount(); ui->tableWidget->insertRow(rowc); QTableWidgetItem *item_id = new QTableWidgetItem(id); ui->tableWidget->setItem(rowc, 0, item_id); QString s; int i = flags.toInt(); if (i & QUEEN_SPADE_f) s += "Q "; if (i & PERFECT_100_f) s += "P "; if (i & OMNIBUS_f) s += "O "; if (i & NO_TRICK_BONUS_f) s += "T "; if (i & NEW_MOON_f) s += "M "; if (!(i & NO_DRAW_f)) s += "D"; QTableWidgetItem *item_flags = new QTableWidgetItem(s); ui->tableWidget->setItem(rowc, 1, item_flags); for (int i=0; i<4; i++) { QTableWidgetItem *empty_item = new QTableWidgetItem(""); ui->tableWidget->setItem(rowc, i+2, empty_item); } } void CTable::Empty() { ui->tableWidget->setRowCount(0); } void CTable::RemoveRow(QString id) { int rowc = ui->tableWidget->rowCount(); for (int i=0; i<rowc; i++) { if (ui->tableWidget->item(i, 0)->text() == id) { ui->tableWidget->removeRow(i); // by removing a row, the index changes, don't forget to break. break; } } } void CTable::SetPlayer(QString id, QString name, QString chair) { int rowc = ui->tableWidget->rowCount(); int c = 0; if (chair == "n") c = 2; else if (chair == "s") c = 3; else if (chair == "w") c = 4; else if (chair == "e") c = 5; if (!c) return; for (int i=0; i<rowc; i++) { if (ui->tableWidget->item(i, 0)->text() == id) { ui->tableWidget->item(i, c)->setText(name); } } } void CTable::on_tableWidget_cellDoubleClicked(int row, int column) { int id = ui->tableWidget->item(row, 0)->text().toInt(); char chair = ' '; switch (column) { case 2: chair = 'n'; break; case 3: chair = 's'; break; case 4: chair = 'w'; break; case 5: chair = 'e'; break; } emit clicked(id, chair); } void CTable::Translate() { ui->retranslateUi(this); } #endif // ONLINE_PLAY
20.756757
100
0.608073
Rescator7
6590d71a0949a66233120069104b8f4dc05e9e49
991
cpp
C++
UVa/11241.cpp
tico88612/Solution-Note
31a9d220fd633c6920760707a07c9a153c2f76cc
[ "MIT" ]
1
2018-02-11T09:41:54.000Z
2018-02-11T09:41:54.000Z
UVa/11241.cpp
tico88612/Solution-Note
31a9d220fd633c6920760707a07c9a153c2f76cc
[ "MIT" ]
null
null
null
UVa/11241.cpp
tico88612/Solution-Note
31a9d220fd633c6920760707a07c9a153c2f76cc
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; double T=-999999,D=-999999,H=-999999; double dohum(double tt,double dd){ double ee=6.11*exp(5417.7530*((1/273.16)-(1/(dd+273.16)))); double hh=(0.5555)*(ee-10.0); return tt+hh; } double dotemp(){ double ee=6.11*exp(5417.7530*((1/273.16)-(1/(D+273.16)))); double hh=(0.5555)*(ee-10.0); return H-hh; } double dodew(){ double ans=0; double delta=100; for(delta=100;delta>0.00001;delta*=0.5){ if(dohum(T,ans)>H) ans-=delta; else ans+=delta; } return ans; } int main(){ char e1,e2; double t1,t2; while(scanf(" %c",&e1)&&e1!='E'){ scanf("%lf %c %lf",&t1,&e2,&t2); if(e1=='T') T=t1; else if(e1=='D') D=t1; else if(e1=='H') H=t1; if(e2=='T') T=t2; else if(e2=='D') D=t2; else if(e2=='H') H=t2; if(T==-999999) T=dotemp(); else if(D==-999999) D=dodew(); else if(H==-999999) H=dohum(T,D); printf("T %0.1lf D %0.1lf H %0.1lf\n",T,D,H); T=-999999; D=-999999; H=-999999; } return 0; }
19.057692
60
0.565086
tico88612
6594a2eb329a534b7fef1a53777d488e87f37a03
76,327
cpp
C++
source/ff.graphics/source/draw_device.cpp
spadapet/ff_game_library
f1bf00f90adde66c2c2aa35b109fe61b8d2c6352
[ "MIT" ]
null
null
null
source/ff.graphics/source/draw_device.cpp
spadapet/ff_game_library
f1bf00f90adde66c2c2aa35b109fe61b8d2c6352
[ "MIT" ]
null
null
null
source/ff.graphics/source/draw_device.cpp
spadapet/ff_game_library
f1bf00f90adde66c2c2aa35b109fe61b8d2c6352
[ "MIT" ]
null
null
null
#include "pch.h" #include "depth.h" #include "draw_device.h" #include "graphics.h" #include "matrix.h" #include "matrix_stack.h" #include "palette_data.h" #include "shader.h" #include "sprite_data.h" #include "sprite_type.h" #include "target_base.h" #include "texture.h" #include "texture_view_base.h" #include "transform.h" #include "vertex.h" #if DXVER == 11 static const size_t MAX_TEXTURES = 32; static const size_t MAX_TEXTURES_USING_PALETTE = 32; static const size_t MAX_PALETTES = 128; // 256 color palettes only static const size_t MAX_PALETTE_REMAPS = 128; // 256 entries only static const size_t MAX_TRANSFORM_MATRIXES = 1024; static const size_t MAX_RENDER_COUNT = 524288; // 0x00080000 static const float MAX_RENDER_DEPTH = 1.0f; static const float RENDER_DEPTH_DELTA = ::MAX_RENDER_DEPTH / ::MAX_RENDER_COUNT; static std::array<ID3D11ShaderResourceView*, ::MAX_TEXTURES + ::MAX_TEXTURES_USING_PALETTE + 2 /* palette + remap */> NULL_TEXTURES{}; static std::array<uint8_t, ff::constants::palette_size> DEFAULT_PALETTE_REMAP = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, }; static size_t DEFAULT_PALETTE_REMAP_HASH = ff::stable_hash_bytes(::DEFAULT_PALETTE_REMAP.data(), ff::array_byte_size(::DEFAULT_PALETTE_REMAP)); namespace { enum class alpha_type { opaque, transparent, invisible, }; enum class last_depth_type { none, nudged, line, circle, triangle, sprite, line_no_overlap, circle_no_overlap, triangle_no_overlap, sprite_no_overlap, start_no_overlap = line_no_overlap, }; enum class geometry_bucket_type { lines, circles, triangles, sprites, palette_sprites, lines_alpha, circles_alpha, triangles_alpha, sprites_alpha, count, first_alpha = lines_alpha, }; class geometry_bucket { private: geometry_bucket( ::geometry_bucket_type bucket_type, const std::type_info& item_type, size_t item_size, size_t item_align, const D3D11_INPUT_ELEMENT_DESC* element_desc, size_t element_count) : bucket_type_(bucket_type) , item_type_(&item_type) , item_size_(item_size) , item_align(item_align) , render_start_(0) , render_count_(0) , data_start(nullptr) , data_cur(nullptr) , data_end(nullptr) , element_desc(element_desc) , element_count(element_count) {} public: template<typename T, ::geometry_bucket_type BucketType> static ::geometry_bucket create() { return ::geometry_bucket(BucketType, typeid(T), sizeof(T), alignof(T), T::layout().data(), T::layout().size()); } geometry_bucket(::geometry_bucket&& rhs) noexcept : vs_res(std::move(rhs.vs_res)) , gs_res(std::move(rhs.gs_res)) , ps_res(std::move(rhs.ps_res)) , ps_palette_out_res(std::move(rhs.ps_palette_out_res)) , layout(std::move(rhs.layout)) , vs(std::move(rhs.vs)) , gs(std::move(rhs.gs)) , ps(std::move(rhs.ps)) , ps_palette_out(std::move(rhs.ps_palette_out)) , element_desc(rhs.element_desc) , element_count(rhs.element_count) , bucket_type_(rhs.bucket_type_) , item_type_(rhs.item_type_) , item_size_(rhs.item_size_) , item_align(rhs.item_align) , render_start_(0) , render_count_(0) , data_start(rhs.data_start) , data_cur(rhs.data_cur) , data_end(rhs.data_end) { rhs.data_start = nullptr; rhs.data_cur = nullptr; rhs.data_end = nullptr; } ~geometry_bucket() { ::_aligned_free(this->data_start); } void reset(std::string_view vs_res, std::string_view gs_res, std::string_view ps_res, std::string_view ps_palette_out_res) { this->reset(); this->vs_res = ff::global_resources::get(vs_res); this->gs_res = ff::global_resources::get(gs_res); this->ps_res = ff::global_resources::get(ps_res); this->ps_palette_out_res = ff::global_resources::get(ps_palette_out_res); } void reset() { this->layout.Reset(); this->vs.Reset(); this->gs.Reset(); this->ps.Reset(); this->ps_palette_out.Reset(); ::_aligned_free(this->data_start); this->data_start = nullptr; this->data_cur = nullptr; this->data_end = nullptr; } void apply(ID3D11Buffer* geometry_buffer, bool palette_out) const { const_cast<::geometry_bucket*>(this)->create_shaders(palette_out); ff_dx::device_state& state = ff_dx::get_device_state(); state.set_vertex_ia(geometry_buffer, item_size(), 0); state.set_layout_ia(this->layout.Get()); state.set_vs(this->vs.Get()); state.set_gs(this->gs.Get()); state.set_ps(palette_out ? this->ps_palette_out.Get() : this->ps.Get()); } void* add(const void* data = nullptr) { if (this->data_cur == this->data_end) { size_t cur_size = this->data_end - this->data_start; size_t new_size = std::max<size_t>(cur_size * 2, this->item_size_ * 64); this->data_start = reinterpret_cast<uint8_t*>(_aligned_realloc(this->data_start, new_size, this->item_align)); this->data_cur = this->data_start + cur_size; this->data_end = this->data_start + new_size; } if (this->data_cur && data) { std::memcpy(this->data_cur, data, this->item_size_); } void* result = this->data_cur; this->data_cur += this->item_size_; return result; } size_t item_size() const { return this->item_size_; } const std::type_info& item_type() const { return *this->item_type_; } ::geometry_bucket_type bucket_type() const { return this->bucket_type_; } size_t count() const { return (this->data_cur - this->data_start) / this->item_size_; } void clear_items() { this->data_cur = this->data_start; } size_t byte_size() const { return this->data_cur - this->data_start; } const uint8_t* data() const { return this->data_start; } void render_start(size_t start) { this->render_start_ = start; this->render_count_ = this->count(); } size_t render_start() const { return this->render_start_; } size_t render_count() const { return this->render_count_; } private: void create_shaders(bool palette_out) { if (!this->vs) { this->vs = ff_dx::get_object_cache().get_vertex_shader_and_input_layout(this->vs_res.resource()->name(), this->layout, this->element_desc, this->element_count); } if (!this->gs) { this->gs = ff_dx::get_object_cache().get_geometry_shader(this->gs_res.resource()->name()); } Microsoft::WRL::ComPtr<ID3D11PixelShader>& ps = palette_out ? this->ps_palette_out : this->ps; if (!ps) { ps = ff_dx::get_object_cache().get_pixel_shader(palette_out ? this->ps_palette_out_res.resource()->name() : this->ps_res.resource()->name()); } } ff::auto_resource<ff::shader> vs_res; ff::auto_resource<ff::shader> gs_res; ff::auto_resource<ff::shader> ps_res; ff::auto_resource<ff::shader> ps_palette_out_res; Microsoft::WRL::ComPtr<ID3D11InputLayout> layout; Microsoft::WRL::ComPtr<ID3D11VertexShader> vs; Microsoft::WRL::ComPtr<ID3D11GeometryShader> gs; Microsoft::WRL::ComPtr<ID3D11PixelShader> ps; Microsoft::WRL::ComPtr<ID3D11PixelShader> ps_palette_out; const D3D11_INPUT_ELEMENT_DESC* element_desc; size_t element_count; ::geometry_bucket_type bucket_type_; const std::type_info* item_type_; size_t item_size_; size_t item_align; size_t render_start_; size_t render_count_; uint8_t* data_start; uint8_t* data_cur; uint8_t* data_end; }; struct alpha_geometry_entry { const ::geometry_bucket* bucket; size_t index; float depth; }; struct geometry_shader_constants_0 { DirectX::XMFLOAT4X4 projection; ff::point_float view_size; ff::point_float view_scale; float z_offset; float padding[3]; }; struct geometry_shader_constants_1 { std::vector<DirectX::XMFLOAT4X4> model; }; struct pixel_shader_constants_0 { std::array<ff::rect_float, ::MAX_TEXTURES_USING_PALETTE> texture_palette_sizes; }; } namespace std { static bool operator==(const DirectX::XMFLOAT4X4& lhs, const DirectX::XMFLOAT4X4& rhs) { return ::operator==(lhs, rhs); } } static ::alpha_type get_alpha_type(const DirectX::XMFLOAT4& color, bool force_opaque) { if (color.w == 0) { return alpha_type::invisible; } if (color.w == 1 || force_opaque) { return alpha_type::opaque; } return alpha_type::transparent; } static alpha_type get_alpha_type(const DirectX::XMFLOAT4* colors, size_t count, bool force_opaque) { alpha_type type = alpha_type::invisible; for (size_t i = 0; i < count; i++) { switch (::get_alpha_type(colors[i], force_opaque)) { case alpha_type::opaque: type = alpha_type::opaque; break; case alpha_type::transparent: return alpha_type::transparent; } } return type; } static alpha_type get_alpha_type(const ff::sprite_data& data, const DirectX::XMFLOAT4& color, bool force_opaque) { switch (::get_alpha_type(color, force_opaque)) { case alpha_type::transparent: return ff::flags::has(data.type(), ff::sprite_type::palette) ? alpha_type::opaque : alpha_type::transparent; case alpha_type::opaque: return (ff::flags::has(data.type(), ff::sprite_type::transparent) && !force_opaque) ? alpha_type::transparent : alpha_type::opaque; default: return alpha_type::invisible; } } static alpha_type get_alpha_type(const ff::sprite_data** datas, const DirectX::XMFLOAT4* colors, size_t count, bool force_opaque) { alpha_type type = alpha_type::invisible; for (size_t i = 0; i < count; i++) { switch (::get_alpha_type(*datas[i], colors[i], force_opaque)) { case alpha_type::opaque: type = alpha_type::opaque; break; case alpha_type::transparent: return alpha_type::transparent; } } return type; } static void get_alpha_blend(D3D11_RENDER_TARGET_BLEND_DESC& desc) { // newColor = (srcColor * SrcBlend) BlendOp (destColor * DestBlend) // newAlpha = (srcAlpha * SrcBlendAlpha) BlendOpAlpha (destAlpha * DestBlendAlpha) desc.BlendEnable = TRUE; desc.SrcBlend = D3D11_BLEND_SRC_ALPHA; desc.DestBlend = D3D11_BLEND_INV_SRC_ALPHA; desc.BlendOp = D3D11_BLEND_OP_ADD; desc.SrcBlendAlpha = D3D11_BLEND_ONE; desc.DestBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA; desc.BlendOpAlpha = D3D11_BLEND_OP_ADD; } static void get_pre_multiplied_alpha_blend(D3D11_RENDER_TARGET_BLEND_DESC& desc) { // newColor = (srcColor * SrcBlend) BlendOp (destColor * DestBlend) // newAlpha = (srcAlpha * SrcBlendAlpha) BlendOpAlpha (destAlpha * DestBlendAlpha) desc.BlendEnable = TRUE; desc.SrcBlend = D3D11_BLEND_ONE; desc.DestBlend = D3D11_BLEND_INV_SRC_ALPHA; desc.BlendOp = D3D11_BLEND_OP_ADD; desc.SrcBlendAlpha = D3D11_BLEND_ONE; desc.DestBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA; desc.BlendOpAlpha = D3D11_BLEND_OP_ADD; } static ID3D11SamplerState* get_texture_sampler_state(D3D11_FILTER filter) { CD3D11_SAMPLER_DESC sampler(D3D11_DEFAULT); sampler.Filter = filter; return ff_dx::get_object_cache().get_sampler_state(sampler); } static ID3D11BlendState* get_opaque_blend_state() { CD3D11_BLEND_DESC blend(D3D11_DEFAULT); return ff_dx::get_object_cache().get_blend_state(blend); } static ID3D11BlendState* get_alpha_blend_state() { CD3D11_BLEND_DESC blend(D3D11_DEFAULT); ::get_alpha_blend(blend.RenderTarget[0]); return ff_dx::get_object_cache().get_blend_state(blend); } static ID3D11BlendState* get_pre_multiplied_alpha_blend_state() { CD3D11_BLEND_DESC blend(D3D11_DEFAULT); ::get_pre_multiplied_alpha_blend(blend.RenderTarget[0]); return ff_dx::get_object_cache().get_blend_state(blend); } static ID3D11DepthStencilState* get_enabled_depth_state() { CD3D11_DEPTH_STENCIL_DESC depth(D3D11_DEFAULT); depth.DepthFunc = D3D11_COMPARISON_GREATER; return ff_dx::get_object_cache().get_depth_stencil_state(depth); } static ID3D11DepthStencilState* get_disabled_depth_state() { CD3D11_DEPTH_STENCIL_DESC depth(D3D11_DEFAULT); depth.DepthEnable = FALSE; depth.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ZERO; return ff_dx::get_object_cache().get_depth_stencil_state(depth); } static ID3D11RasterizerState* get_no_cull_raster_state() { CD3D11_RASTERIZER_DESC raster(D3D11_DEFAULT); raster.CullMode = D3D11_CULL_NONE; return ff_dx::get_object_cache().get_rasterize_state(raster); } static ff_dx::fixed_state create_opaque_draw_state() { ff_dx::fixed_state state; state.blend = ::get_opaque_blend_state(); state.depth = ::get_enabled_depth_state(); state.disabled_depth = ::get_disabled_depth_state(); state.raster = ::get_no_cull_raster_state(); return state; } static ff_dx::fixed_state create_alpha_draw_state() { ff_dx::fixed_state state; state.blend = ::get_alpha_blend_state(); state.depth = ::get_enabled_depth_state(); state.disabled_depth = ::get_disabled_depth_state(); state.raster = ::get_no_cull_raster_state(); return state; } static ff_dx::fixed_state create_pre_multiplied_alpha_draw_state() { ff_dx::fixed_state state; state.blend = ::get_pre_multiplied_alpha_blend_state(); state.depth = ::get_enabled_depth_state(); state.disabled_depth = ::get_disabled_depth_state(); state.raster = ::get_no_cull_raster_state(); return state; } static ff::rect_float get_rotated_view_rect(ff::target_base& target, const ff::rect_float& view_rect) { ff::window_size size = target.size(); ff::rect_float rotated_view_rect; switch (size.current_rotation) { default: rotated_view_rect = view_rect; break; case DMDO_90: { float height = size.rotated_pixel_size().cast<float>().y; rotated_view_rect.left = height - view_rect.bottom; rotated_view_rect.top = view_rect.left; rotated_view_rect.right = height - view_rect.top; rotated_view_rect.bottom = view_rect.right; } break; case DMDO_180: { ff::point_float target_size = size.rotated_pixel_size().cast<float>(); rotated_view_rect.left = target_size.x - view_rect.right; rotated_view_rect.top = target_size.y - view_rect.bottom; rotated_view_rect.right = target_size.x - view_rect.left; rotated_view_rect.bottom = target_size.y - view_rect.top; } break; case DMDO_270: { float width = size.rotated_pixel_size().cast<float>().x; rotated_view_rect.left = view_rect.top; rotated_view_rect.top = width - view_rect.right; rotated_view_rect.right = view_rect.bottom; rotated_view_rect.bottom = width - view_rect.left; } break; } return rotated_view_rect; } static DirectX::XMMATRIX get_view_matrix(const ff::rect_float& world_rect) { return DirectX::XMMatrixOrthographicOffCenterLH( world_rect.left, world_rect.right, world_rect.bottom, world_rect.top, 0, ::MAX_RENDER_DEPTH); } static DirectX::XMMATRIX get_orientation_matrix(ff::target_base& target, const ff::rect_float& view_rect, ff::point_float world_center) { DirectX::XMMATRIX orientation_matrix; int degrees = target.size().current_rotation; switch (degrees) { default: orientation_matrix = DirectX::XMMatrixIdentity(); break; case DMDO_90: case DMDO_270: { float view_height_per_width = view_rect.height() / view_rect.width(); float view_width_per_height = view_rect.width() / view_rect.height(); orientation_matrix = DirectX::XMMatrixTransformation2D( DirectX::XMVectorSet(world_center.x, world_center.y, 0, 0), 0, // scale center DirectX::XMVectorSet(view_height_per_width, view_width_per_height, 1, 1), // scale DirectX::XMVectorSet(world_center.x, world_center.y, 0, 0), // rotation center ff::math::pi<float>() * degrees / 2.0f, // rotation DirectX::XMVectorZero()); // translation } break; case DMDO_180: orientation_matrix = DirectX::XMMatrixAffineTransformation2D( DirectX::XMVectorSet(1, 1, 1, 1), // scale DirectX::XMVectorSet(world_center.x, world_center.y, 0, 0), // rotation center ff::math::pi<float>(), // rotation DirectX::XMVectorZero()); // translation break; } return orientation_matrix; } static D3D11_VIEWPORT get_viewport(const ff::rect_float& view_rect) { D3D11_VIEWPORT viewport; viewport.TopLeftX = view_rect.left; viewport.TopLeftY = view_rect.top; viewport.Width = view_rect.width(); viewport.Height = view_rect.height(); viewport.MinDepth = 0; viewport.MaxDepth = 1; return viewport; } static bool setup_view_matrix(ff::target_base& target, const ff::rect_float& view_rect, const ff::rect_float& world_rect, DirectX::XMFLOAT4X4& view_matrix) { if (world_rect.width() != 0 && world_rect.height() != 0 && view_rect.width() > 0 && view_rect.height() > 0) { DirectX::XMMATRIX unoriented_view_matrix = ::get_view_matrix(world_rect); DirectX::XMMATRIX orientation_matrix = ::get_orientation_matrix(target, view_rect, world_rect.center()); DirectX::XMStoreFloat4x4(&view_matrix, DirectX::XMMatrixTranspose(orientation_matrix * unoriented_view_matrix)); return true; } return false; } static bool setup_render_target(ff::target_base& target, ff::depth* depth, const ff::rect_float& view_rect) { ID3D11RenderTargetView* target_view = target.view(); if (target_view) { ID3D11DepthStencilView* depth_view = nullptr; if (depth) { if (depth->size(target.size().pixel_size)) { depth->clear(0, 0); depth_view = depth->view(); } if (!depth_view) { assert(false); return false; } } ff::rect_float rotated_view_rect = ::get_rotated_view_rect(target, view_rect); D3D11_VIEWPORT viewport = ::get_viewport(rotated_view_rect); ff_dx::get_device_state().set_targets(&target_view, 1, depth_view); ff_dx::get_device_state().set_viewports(&viewport, 1); return true; } assert(false); return false; } namespace { class draw_device_internal : public ff::draw_device , public ff::draw_base , private ff::dxgi::device_child_base { public: draw_device_internal() : state(::draw_device_internal::state_t::invalid) , world_matrix_stack_changing_connection(this->world_matrix_stack_.matrix_changing().connect(std::bind(&draw_device_internal::matrix_changing, this, std::placeholders::_1))) , geometry_buffer(ff::dxgi::buffer_type::vertex) , geometry_constants_buffer_0(ff::dxgi::buffer_type::constant) , geometry_constants_buffer_1(ff::dxgi::buffer_type::constant) , pixel_constants_buffer_0(ff::dxgi::buffer_type::constant) , geometry_buckets { ::geometry_bucket::create<ff::vertex::line_geometry, ::geometry_bucket_type::lines>(), ::geometry_bucket::create<ff::vertex::circle_geometry, ::geometry_bucket_type::circles>(), ::geometry_bucket::create<ff::vertex::triangle_geometry, ::geometry_bucket_type::triangles>(), ::geometry_bucket::create<ff::vertex::sprite_geometry, ::geometry_bucket_type::sprites>(), ::geometry_bucket::create<ff::vertex::sprite_geometry, ::geometry_bucket_type::palette_sprites>(), ::geometry_bucket::create<ff::vertex::line_geometry, ::geometry_bucket_type::lines_alpha>(), ::geometry_bucket::create<ff::vertex::circle_geometry, ::geometry_bucket_type::circles_alpha>(), ::geometry_bucket::create<ff::vertex::triangle_geometry, ::geometry_bucket_type::triangles_alpha>(), ::geometry_bucket::create<ff::vertex::sprite_geometry, ::geometry_bucket_type::sprites_alpha>(), } { this->reset(); ff_dx::add_device_child(this, ff_dx::device_reset_priority::normal); } virtual ~draw_device_internal() override { assert(this->state != ::draw_device_internal::state_t::drawing); ff_dx::remove_device_child(this); } draw_device_internal(draw_device_internal&& other) noexcept = delete; draw_device_internal(const draw_device_internal& other) = delete; draw_device_internal& operator=(draw_device_internal&& other) noexcept = delete; draw_device_internal& operator=(const draw_device_internal& other) = delete; virtual bool valid() const override { return this->state != ::draw_device_internal::state_t::invalid; } virtual ff::draw_ptr begin_draw(ff::target_base& target, ff::depth* depth, const ff::rect_float& view_rect, const ff::rect_float& world_rect, ff::draw_options options) override { this->end_draw(); if (::setup_view_matrix(target, view_rect, world_rect, this->view_matrix) && ::setup_render_target(target, depth, view_rect)) { this->init_geometry_constant_buffers_0(target, view_rect, world_rect); this->target_requires_palette = ff::dxgi::palette_format(target.format()); this->force_pre_multiplied_alpha = ff::flags::has(options, ff::draw_options::pre_multiplied_alpha) && ff::dxgi::supports_pre_multiplied_alpha(target.format()) ? 1 : 0; this->state = ::draw_device_internal::state_t::drawing; return this; } return nullptr; } virtual void end_draw() override { if (this->state == state_t::drawing) { this->flush(); ff_dx::get_device_state().set_resources_ps(::NULL_TEXTURES.data(), 0, ::NULL_TEXTURES.size()); this->state = ::draw_device_internal::state_t::valid; this->palette_stack.resize(1); this->palette_remap_stack.resize(1); this->sampler_stack.resize(1); this->custom_context_stack.clear(); this->world_matrix_stack_.reset(); this->draw_depth = 0; this->force_no_overlap = 0; this->force_opaque = 0; this->force_pre_multiplied_alpha = 0; } } virtual void draw_sprite(const ff::sprite_data& sprite, const ff::transform& transform) override { ::alpha_type alpha_type = ::get_alpha_type(sprite, transform.color, this->force_opaque || this->target_requires_palette); if (alpha_type != ::alpha_type::invisible && sprite.view()) { bool use_palette = ff::flags::has(sprite.type(), ff::sprite_type::palette); ::geometry_bucket_type bucket_type = (alpha_type == ::alpha_type::transparent && !this->target_requires_palette) ? (use_palette ? ::geometry_bucket_type::palette_sprites : ::geometry_bucket_type::sprites_alpha) : (use_palette ? ::geometry_bucket_type::palette_sprites : ::geometry_bucket_type::sprites); float depth = this->nudge_depth(this->force_no_overlap ? ::last_depth_type::sprite_no_overlap : ::last_depth_type::sprite); ff::vertex::sprite_geometry& input = *reinterpret_cast<ff::vertex::sprite_geometry*>(this->add_geometry(nullptr, bucket_type, depth)); this->get_world_matrix_and_texture_index(*sprite.view(), use_palette, input.matrix_index, input.texture_index); input.position.x = transform.position.x; input.position.y = transform.position.y; input.position.z = depth; input.scale = *reinterpret_cast<const DirectX::XMFLOAT2*>(&transform.scale); input.rotate = transform.rotation_radians(); input.color = transform.color; input.uv_rect = *reinterpret_cast<const DirectX::XMFLOAT4*>(&sprite.texture_uv()); input.rect = *reinterpret_cast<const DirectX::XMFLOAT4*>(&sprite.world()); } } virtual void draw_line_strip(const ff::point_float* points, const DirectX::XMFLOAT4* colors, size_t count, float thickness, bool pixel_thickness) override { this->draw_line_strip(points, count, colors, count, thickness, pixel_thickness); } virtual void draw_line_strip(const ff::point_float* points, size_t count, const DirectX::XMFLOAT4& color, float thickness, bool pixel_thickness) override { this->draw_line_strip(points, count, &color, 1, thickness, pixel_thickness); } virtual void draw_line(const ff::point_float& start, const ff::point_float& end, const DirectX::XMFLOAT4& color, float thickness, bool pixel_thickness) override { const ff::point_float points[2] = { start, end }; this->draw_line_strip(points, 2, color, thickness, pixel_thickness); } virtual void draw_filled_rectangle(const ff::rect_float& rect, const DirectX::XMFLOAT4* colors) override { const float tri_points[12] = { rect.left, rect.top, rect.right, rect.top, rect.right, rect.bottom, rect.right, rect.bottom, rect.left, rect.bottom, rect.left, rect.top, }; const DirectX::XMFLOAT4 tri_colors[6] = { colors[0], colors[1], colors[2], colors[2], colors[3], colors[0], }; this->draw_filled_triangles(reinterpret_cast<const ff::point_float*>(tri_points), tri_colors, 2); } virtual void draw_filled_rectangle(const ff::rect_float& rect, const DirectX::XMFLOAT4& color) override { const float tri_points[12] = { rect.left, rect.top, rect.right, rect.top, rect.right, rect.bottom, rect.right, rect.bottom, rect.left, rect.bottom, rect.left, rect.top, }; const DirectX::XMFLOAT4 tri_colors[6] = { color, color, color, color, color, color, }; this->draw_filled_triangles(reinterpret_cast<const ff::point_float*>(tri_points), tri_colors, 2); } virtual void draw_filled_triangles(const ff::point_float* points, const DirectX::XMFLOAT4* colors, size_t count) override { ff::vertex::triangle_geometry input; input.matrix_index = (this->world_matrix_index == ff::constants::invalid_dword) ? this->get_world_matrix_index() : this->world_matrix_index; input.depth = this->nudge_depth(this->force_no_overlap ? ::last_depth_type::triangle_no_overlap : ::last_depth_type::triangle); for (size_t i = 0; i < count; i++, points += 3, colors += 3) { std::memcpy(input.position, points, sizeof(input.position)); std::memcpy(input.color, colors, sizeof(input.color)); ::alpha_type alpha_type = ::get_alpha_type(colors, 3, this->force_opaque || this->target_requires_palette); if (alpha_type != ::alpha_type::invisible) { ::geometry_bucket_type bucket_type = (alpha_type == ::alpha_type::transparent) ? ::geometry_bucket_type::triangles_alpha : ::geometry_bucket_type::triangles; this->add_geometry(&input, bucket_type, input.depth); } } } virtual void draw_filled_circle(const ff::point_float& center, float radius, const DirectX::XMFLOAT4& color) override { this->draw_outline_circle(center, radius, color, color, std::abs(radius), false); } virtual void draw_filled_circle(const ff::point_float& center, float radius, const DirectX::XMFLOAT4& inside_color, const DirectX::XMFLOAT4& outside_color) override { this->draw_outline_circle(center, radius, inside_color, outside_color, std::abs(radius), false); } virtual void draw_outline_rectangle(const ff::rect_float& rect, const DirectX::XMFLOAT4& color, float thickness, bool pixel_thickness) override { ff::rect_float rect2 = rect.normalize(); if (thickness < 0) { ff::point_float deflate = this->geometry_constants_0.view_scale * thickness; rect2 = rect2.deflate(deflate); this->draw_outline_rectangle(rect2, color, -thickness, pixel_thickness); } else if (!pixel_thickness && (thickness * 2 >= rect2.width() || thickness * 2 >= rect2.height())) { this->draw_filled_rectangle(rect2, color); } else { ff::point_float half_thickness(thickness / 2, thickness / 2); if (pixel_thickness) { half_thickness *= this->geometry_constants_0.view_scale; } rect2 = rect2.deflate(half_thickness); const ff::point_float points[5] = { rect2.top_left(), rect2.top_right(), rect2.bottom_right(), rect2.bottom_left(), rect2.top_left(), }; this->draw_line_strip(points, 5, color, thickness, pixel_thickness); } } virtual void draw_outline_circle(const ff::point_float& center, float radius, const DirectX::XMFLOAT4& color, float thickness, bool pixel_thickness) override { this->draw_outline_circle(center, radius, color, color, thickness, pixel_thickness); } virtual void draw_outline_circle(const ff::point_float& center, float radius, const DirectX::XMFLOAT4& inside_color, const DirectX::XMFLOAT4& outside_color, float thickness, bool pixel_thickness) override { ff::vertex::circle_geometry input; input.matrix_index = (this->world_matrix_index == ff::constants::invalid_dword) ? this->get_world_matrix_index() : this->world_matrix_index; input.position.x = center.x; input.position.y = center.y; input.position.z = this->nudge_depth(this->force_no_overlap ? ::last_depth_type::circle_no_overlap : ::last_depth_type::circle); input.radius = std::abs(radius); input.thickness = pixel_thickness ? -std::abs(thickness) : std::min(std::abs(thickness), input.radius); input.inside_color = inside_color; input.outside_color = outside_color; ::alpha_type alpha_type = ::get_alpha_type(&input.inside_color, 2, this->force_opaque || this->target_requires_palette); if (alpha_type != ::alpha_type::invisible) { ::geometry_bucket_type bucket_type = (alpha_type == ::alpha_type::transparent) ? ::geometry_bucket_type::circles_alpha : ::geometry_bucket_type::circles; this->add_geometry(&input, bucket_type, input.position.z); } } virtual void draw_palette_line_strip(const ff::point_float* points, const int* colors, size_t count, float thickness, bool pixel_thickness) override { ff::stack_vector<DirectX::XMFLOAT4, 64> colors2; colors2.resize(count); for (size_t i = 0; i != colors2.size(); i++) { ff::palette_index_to_color(this->remap_palette_index(colors[i]), colors2[i]); } this->draw_line_strip(points, count, colors2.data(), count, thickness, pixel_thickness); } virtual void draw_palette_line_strip(const ff::point_float* points, size_t count, int color, float thickness, bool pixel_thickness) override { DirectX::XMFLOAT4 color2; ff::palette_index_to_color(this->remap_palette_index(color), color2); this->draw_line_strip(points, count, &color2, 1, thickness, pixel_thickness); } virtual void draw_palette_line(const ff::point_float& start, const ff::point_float& end, int color, float thickness, bool pixel_thickness) override { DirectX::XMFLOAT4 color2; ff::palette_index_to_color(this->remap_palette_index(color), color2); this->draw_line(start, end, color2, thickness, pixel_thickness); } virtual void draw_palette_filled_rectangle(const ff::rect_float& rect, const int* colors) override { std::array<DirectX::XMFLOAT4, 4> colors2; for (size_t i = 0; i != colors2.size(); i++) { ff::palette_index_to_color(this->remap_palette_index(colors[i]), colors2[i]); } this->draw_filled_rectangle(rect, colors2.data()); } virtual void draw_palette_filled_rectangle(const ff::rect_float& rect, int color) override { DirectX::XMFLOAT4 color2; ff::palette_index_to_color(this->remap_palette_index(color), color2); this->draw_filled_rectangle(rect, color2); } virtual void draw_palette_filled_triangles(const ff::point_float* points, const int* colors, size_t count) override { ff::stack_vector<DirectX::XMFLOAT4, 64 * 3> colors2; colors2.resize(count * 3); for (size_t i = 0; i != colors2.size(); i++) { ff::palette_index_to_color(this->remap_palette_index(colors[i]), colors2[i]); } this->draw_filled_triangles(points, colors2.data(), count); } virtual void draw_palette_filled_circle(const ff::point_float& center, float radius, int color) override { DirectX::XMFLOAT4 color2; ff::palette_index_to_color(this->remap_palette_index(color), color2); this->draw_filled_circle(center, radius, color2); } virtual void draw_palette_filled_circle(const ff::point_float& center, float radius, int inside_color, int outside_color) override { DirectX::XMFLOAT4 inside_color2, outside_color2; ff::palette_index_to_color(this->remap_palette_index(inside_color), inside_color2); ff::palette_index_to_color(this->remap_palette_index(outside_color), outside_color2); this->draw_filled_circle(center, radius, inside_color2, outside_color2); } virtual void draw_palette_outline_rectangle(const ff::rect_float& rect, int color, float thickness, bool pixel_thickness) override { DirectX::XMFLOAT4 color2; ff::palette_index_to_color(this->remap_palette_index(color), color2); this->draw_outline_rectangle(rect, color2, thickness, pixel_thickness); } virtual void draw_palette_outline_circle(const ff::point_float& center, float radius, int color, float thickness, bool pixel_thickness) override { DirectX::XMFLOAT4 color2; ff::palette_index_to_color(this->remap_palette_index(color), color2); this->draw_outline_circle(center, radius, color2, thickness, pixel_thickness); } virtual void draw_palette_outline_circle(const ff::point_float& center, float radius, int inside_color, int outside_color, float thickness, bool pixel_thickness) override { DirectX::XMFLOAT4 inside_color2, outside_color2; ff::palette_index_to_color(this->remap_palette_index(inside_color), inside_color2); ff::palette_index_to_color(this->remap_palette_index(outside_color), outside_color2); this->draw_outline_circle(center, radius, inside_color2, outside_color2, thickness, pixel_thickness); } virtual ff::matrix_stack& world_matrix_stack() override { return this->world_matrix_stack_; } virtual void nudge_depth() override { this->last_depth_type = ::last_depth_type::nudged; } virtual void push_palette(ff::palette_base* palette) override { assert(!this->target_requires_palette && palette); this->palette_stack.push_back(palette); this->palette_index = ff::constants::invalid_dword; this->push_palette_remap(palette->index_remap(), palette->index_remap_hash()); } virtual void pop_palette() override { assert(this->palette_stack.size() > 1); this->palette_stack.pop_back(); this->palette_index = ff::constants::invalid_dword; this->pop_palette_remap(); } virtual void push_palette_remap(const uint8_t* remap, size_t hash) override { this->palette_remap_stack.push_back(std::make_pair( remap ? remap : ::DEFAULT_PALETTE_REMAP.data(), remap ? (hash ? hash : ff::stable_hash_bytes(remap, ff::constants::palette_size)) : ::DEFAULT_PALETTE_REMAP_HASH)); this->palette_remap_index = ff::constants::invalid_dword; } virtual void pop_palette_remap() override { assert(this->palette_remap_stack.size() > 1); this->palette_remap_stack.pop_back(); this->palette_remap_index = ff::constants::invalid_dword; } virtual void push_no_overlap() override { this->force_no_overlap++; } virtual void pop_no_overlap() override { assert(this->force_no_overlap > 0); if (!--this->force_no_overlap) { this->nudge_depth(); } } virtual void push_opaque() override { this->force_opaque++; } virtual void pop_opaque() override { assert(this->force_opaque > 0); this->force_opaque--; } virtual void push_pre_multiplied_alpha() override { if (!this->force_pre_multiplied_alpha) { this->flush(); } this->force_pre_multiplied_alpha++; } virtual void pop_pre_multiplied_alpha() override { assert(this->force_pre_multiplied_alpha > 0); if (this->force_pre_multiplied_alpha == 1) { this->flush(); } this->force_pre_multiplied_alpha--; } virtual void push_custom_context(ff::draw_base::custom_context_func&& func) override { this->flush(); this->custom_context_stack.push_back(std::move(func)); } virtual void pop_custom_context() override { assert(this->custom_context_stack.size()); this->flush(); this->custom_context_stack.pop_back(); } virtual void push_sampler_linear_filter(bool linear_filter) override { this->flush(); this->sampler_stack.push_back(::get_texture_sampler_state(linear_filter ? D3D11_FILTER_MIN_MAG_MIP_LINEAR : D3D11_FILTER_MIN_MAG_MIP_POINT)); } virtual void pop_sampler_linear_filter() override { assert(this->sampler_stack.size() > 1); this->flush(); this->sampler_stack.pop_back(); } private: // device_child_base virtual bool reset() { this->destroy(); // Geometry buckets this->get_geometry_bucket(::geometry_bucket_type::lines).reset("ff.shader.line_vs", "ff.shader.line_gs", "ff.shader.color_ps", "ff.shader.palette_out_color_ps"); this->get_geometry_bucket(::geometry_bucket_type::circles).reset("ff.shader.circle_vs", "ff.shader.circle_gs", "ff.shader.color_ps", "ff.shader.palette_out_color_ps"); this->get_geometry_bucket(::geometry_bucket_type::triangles).reset("ff.shader.triangle_vs", "ff.shader.triangle_gs", "ff.shader.color_ps", "ff.shader.palette_out_color_ps"); this->get_geometry_bucket(::geometry_bucket_type::sprites).reset("ff.shader.sprite_vs", "ff.shader.sprite_gs", "ff.shader.sprite_ps", "ff.shader.palette_out_sprite_ps"); this->get_geometry_bucket(::geometry_bucket_type::palette_sprites).reset("ff.shader.sprite_vs", "ff.shader.sprite_gs", "ff.shader.sprite_palette_ps", "ff.shader.palette_out_sprite_palette_ps"); this->get_geometry_bucket(::geometry_bucket_type::lines_alpha).reset("ff.shader.line_vs", "ff.shader.line_gs", "ff.shader.color_ps", "ff.shader.palette_out_color_ps"); this->get_geometry_bucket(::geometry_bucket_type::circles_alpha).reset("ff.shader.circle_vs", "ff.shader.circle_gs", "ff.shader.color_ps", "ff.shader.palette_out_color_ps"); this->get_geometry_bucket(::geometry_bucket_type::triangles_alpha).reset("ff.shader.triangle_vs", "ff.shader.triangle_gs", "ff.shader.color_ps", "ff.shader.palette_out_color_ps"); this->get_geometry_bucket(::geometry_bucket_type::sprites_alpha).reset("ff.shader.sprite_vs", "ff.shader.sprite_gs", "ff.shader.sprite_ps", "ff.shader.palette_out_sprite_ps"); // Palette this->palette_stack.push_back(nullptr); this->palette_texture = std::make_shared<ff::texture>( ff::point_size(ff::constants::palette_size, ::MAX_PALETTES).cast<int>(), ff::dxgi::PALETTE_FORMAT); this->palette_remap_stack.push_back(std::make_pair(::DEFAULT_PALETTE_REMAP.data(), ::DEFAULT_PALETTE_REMAP_HASH)); this->palette_remap_texture = std::make_shared<ff::texture>( ff::point_size(ff::constants::palette_size, ::MAX_PALETTE_REMAPS).cast<int>(), ff::dxgi::PALETTE_INDEX_FORMAT); // States this->sampler_stack.push_back(::get_texture_sampler_state(D3D11_FILTER_MIN_MAG_MIP_POINT)); this->opaque_state = ::create_opaque_draw_state(); this->alpha_state = ::create_alpha_draw_state(); this->pre_multiplied_alpha_state = ::create_pre_multiplied_alpha_draw_state(); this->state = ::draw_device_internal::state_t::valid; return true; } void destroy() { this->state = ::draw_device_internal::state_t::invalid; this->geometry_constants_0 = ::geometry_shader_constants_0{}; this->geometry_constants_1 = ::geometry_shader_constants_1{}; this->pixel_constants_0 = ::pixel_shader_constants_0{}; this->geometry_constants_hash_0 = 0; this->geometry_constants_hash_1 = 0; this->pixel_constants_hash_0 = 0; this->sampler_stack.clear(); this->opaque_state = ff_dx::fixed_state(); this->alpha_state = ff_dx::fixed_state(); this->pre_multiplied_alpha_state = ff_dx::fixed_state(); this->custom_context_stack.clear(); this->view_matrix = ff::matrix::identity_4x4(); this->world_matrix_stack_.reset(); this->world_matrix_to_index.clear(); this->world_matrix_index = ff::constants::invalid_dword; std::memset(this->textures.data(), 0, ff::array_byte_size(this->textures)); std::memset(this->textures_using_palette.data(), 0, ff::array_byte_size(this->textures_using_palette)); this->texture_count = 0; this->textures_using_palette_count = 0; std::memset(this->palette_texture_hashes.data(), 0, ff::array_byte_size(this->palette_texture_hashes)); this->palette_stack.clear(); this->palette_to_index.clear(); this->palette_texture = nullptr; this->palette_index = ff::constants::invalid_dword; std::memset(this->palette_remap_texture_hashes.data(), 0, ff::array_byte_size(this->palette_remap_texture_hashes)); this->palette_remap_stack.clear(); this->palette_remap_to_index.clear(); this->palette_remap_texture = nullptr; this->palette_remap_index = ff::constants::invalid_dword; this->alpha_geometry.clear(); this->last_depth_type = ::last_depth_type::none; this->draw_depth = 0; this->force_no_overlap = 0; this->force_opaque = 0; this->force_pre_multiplied_alpha = 0; for (auto& bucket : this->geometry_buckets) { bucket.reset(); } } void matrix_changing(const ff::matrix_stack& matrix_stack) { this->world_matrix_index = ff::constants::invalid_dword; } void draw_line_strip(const ff::point_float* points, size_t point_count, const DirectX::XMFLOAT4* colors, size_t color_count, float thickness, bool pixel_thickness) { assert(color_count == 1 || color_count == point_count); thickness = pixel_thickness ? -std::abs(thickness) : std::abs(thickness); ff::vertex::line_geometry input; input.matrix_index = (this->world_matrix_index == ff::constants::invalid_dword) ? this->get_world_matrix_index() : this->world_matrix_index; input.depth = this->nudge_depth(this->force_no_overlap ? ::last_depth_type::line_no_overlap : ::last_depth_type::line); input.color[0] = colors[0]; input.color[1] = colors[0]; input.thickness[0] = thickness; input.thickness[1] = thickness; const DirectX::XMFLOAT2* dxpoints = reinterpret_cast<const DirectX::XMFLOAT2*>(points); bool closed = point_count > 2 && points[0] == points[point_count - 1]; ::alpha_type alpha_type = ::get_alpha_type(colors[0], this->force_opaque || this->target_requires_palette); for (size_t i = 0; i < point_count - 1; i++) { input.position[1] = dxpoints[i]; input.position[2] = dxpoints[i + 1]; input.position[0] = (i == 0) ? (closed ? dxpoints[point_count - 2] : dxpoints[i]) : dxpoints[i - 1]; input.position[3] = (i == point_count - 2) ? (closed ? dxpoints[1] : dxpoints[i + 1]) : dxpoints[i + 2]; if (color_count != 1) { input.color[0] = colors[i]; input.color[1] = colors[i + 1]; alpha_type = ::get_alpha_type(colors + i, 2, this->force_opaque || this->target_requires_palette); } if (alpha_type != ::alpha_type::invisible) { ::geometry_bucket_type bucket_type = (alpha_type == ::alpha_type::transparent) ? ::geometry_bucket_type::lines_alpha : ::geometry_bucket_type::lines; this->add_geometry(&input, bucket_type, input.depth); } } } void init_geometry_constant_buffers_0(ff::target_base& target, const ff::rect_float& view_rect, const ff::rect_float& world_rect) { this->geometry_constants_0.view_size = view_rect.size() / static_cast<float>(target.size().dpi_scale); this->geometry_constants_0.view_scale = world_rect.size() / this->geometry_constants_0.view_size; } void update_geometry_constant_buffers_0() { this->geometry_constants_0.projection = this->view_matrix; size_t hash0 = ff::stable_hash_func(this->geometry_constants_0); if (!this->geometry_constants_hash_0 || this->geometry_constants_hash_0 != hash0) { this->geometry_constants_buffer_0.update(ff_dx::get_device_state(), &this->geometry_constants_0, sizeof(::geometry_shader_constants_0)); this->geometry_constants_hash_0 = hash0; } } void update_geometry_constant_buffers_1() { // Build up model matrix array size_t world_matrix_count = this->world_matrix_to_index.size(); this->geometry_constants_1.model.resize(world_matrix_count); for (const auto& iter : this->world_matrix_to_index) { this->geometry_constants_1.model[iter.second] = iter.first; } size_t hash1 = world_matrix_count ? ff::stable_hash_bytes(this->geometry_constants_1.model.data(), ff::vector_byte_size(this->geometry_constants_1.model)) : 0; if (!this->geometry_constants_hash_1 || this->geometry_constants_hash_1 != hash1) { this->geometry_constants_hash_1 = hash1; #if _DEBUG size_t buffer_size = sizeof(DirectX::XMFLOAT4X4) * ::MAX_TRANSFORM_MATRIXES; #else size_t buffer_size = sizeof(DirectX::XMFLOAT4X4) * world_matrix_count; #endif this->geometry_constants_buffer_1.update(ff_dx::get_device_state(), this->geometry_constants_1.model.data(), ff::vector_byte_size(this->geometry_constants_1.model), buffer_size); } } void update_pixel_constant_buffers_0() { if (this->textures_using_palette_count) { for (size_t i = 0; i < this->textures_using_palette_count; i++) { ff::rect_float& rect = this->pixel_constants_0.texture_palette_sizes[i]; ff::point_float size = this->textures_using_palette[i]->view_texture()->size().cast<float>(); rect.left = size.x; rect.top = size.y; } size_t hash0 = ff::stable_hash_func(this->pixel_constants_0); if (!this->pixel_constants_hash_0 || this->pixel_constants_hash_0 != hash0) { this->pixel_constants_buffer_0.update(ff_dx::get_device_state(), &this->pixel_constants_0, sizeof(::pixel_shader_constants_0)); this->pixel_constants_hash_0 = hash0; } } } void update_palette_texture() { if (this->textures_using_palette_count && !this->palette_to_index.empty()) { ID3D11Resource* dest_resource = this->palette_texture->dx_texture(); CD3D11_BOX box(0, 0, 0, static_cast<int>(ff::constants::palette_size), 1, 1); for (const auto& iter : this->palette_to_index) { ff::palette_base* palette = iter.second.first; if (palette) { unsigned int index = iter.second.second; size_t palette_row = palette->current_row(); const ff::palette_data* palette_data = palette->data(); size_t row_hash = palette_data->row_hash(palette_row); if (this->palette_texture_hashes[index] != row_hash) { this->palette_texture_hashes[index] = row_hash; ID3D11Resource* src_resource = palette_data->texture()->dx_texture(); box.top = static_cast<UINT>(palette_row); box.bottom = box.top + 1; ff_dx::get_device_state().copy_subresource_region(dest_resource, 0, 0, index, 0, src_resource, 0, &box); } } } } if ((this->textures_using_palette_count || this->target_requires_palette) && !this->palette_remap_to_index.empty()) { ID3D11Resource* dest_remap_resource = this->palette_remap_texture->dx_texture(); CD3D11_BOX box(0, 0, 0, static_cast<int>(ff::constants::palette_size), 1, 1); for (const auto& iter : this->palette_remap_to_index) { const uint8_t* remap = iter.second.first; unsigned int row = iter.second.second; size_t row_hash = iter.first; if (this->palette_remap_texture_hashes[row] != row_hash) { this->palette_remap_texture_hashes[row] = row_hash; box.top = row; box.bottom = row + 1; ff_dx::get_device_state().update_subresource(dest_remap_resource, 0, &box, remap, static_cast<UINT>(ff::constants::palette_size), 0); } } } } void set_shader_input() { std::array<ID3D11Buffer*, 2> buffers_gs = { this->geometry_constants_buffer_0.dx_buffer(), this->geometry_constants_buffer_1.dx_buffer() }; ff_dx::get_device_state().set_constants_gs(buffers_gs.data(), 0, buffers_gs.size()); std::array<ID3D11Buffer*, 1> buffers_ps = { this->pixel_constants_buffer_0.dx_buffer() }; ff_dx::get_device_state().set_constants_ps(buffers_ps.data(), 0, buffers_ps.size()); std::array<ID3D11SamplerState*, 1> sample_states = { this->sampler_stack.back().Get() }; ff_dx::get_device_state().set_samplers_ps(sample_states.data(), 0, sample_states.size()); if (this->texture_count) { std::array<ID3D11ShaderResourceView*, ::MAX_TEXTURES> textures; for (size_t i = 0; i < this->texture_count; i++) { textures[i] = this->textures[i]->view(); } ff_dx::get_device_state().set_resources_ps(textures.data(), 0, this->texture_count); } if (this->textures_using_palette_count) { std::array<ID3D11ShaderResourceView*, ::MAX_TEXTURES_USING_PALETTE> textures_using_palette; for (size_t i = 0; i < this->textures_using_palette_count; i++) { textures_using_palette[i] = this->textures_using_palette[i]->view(); } ff_dx::get_device_state().set_resources_ps(textures_using_palette.data(), ::MAX_TEXTURES, this->textures_using_palette_count); } if (this->textures_using_palette_count || this->target_requires_palette) { std::array<ID3D11ShaderResourceView*, 2> palettes = { (this->textures_using_palette_count ? this->palette_texture->view() : nullptr), this->palette_remap_texture->view(), }; ff_dx::get_device_state().set_resources_ps(palettes.data(), ::MAX_TEXTURES + ::MAX_TEXTURES_USING_PALETTE, palettes.size()); } } void flush() { if (this->last_depth_type != ::last_depth_type::none && this->create_geometry_buffer()) { this->update_geometry_constant_buffers_0(); this->update_geometry_constant_buffers_1(); this->update_pixel_constant_buffers_0(); this->update_palette_texture(); this->set_shader_input(); this->draw_opaque_geometry(); this->draw_alpha_geometry(); // Reset draw data this->world_matrix_to_index.clear(); this->world_matrix_index = ff::constants::invalid_dword; this->palette_to_index.clear(); this->palette_index = ff::constants::invalid_dword; this->palette_remap_to_index.clear(); this->palette_remap_index = ff::constants::invalid_dword; this->texture_count = 0; this->textures_using_palette_count = 0; this->alpha_geometry.clear(); this->last_depth_type = ::last_depth_type::none; } } bool create_geometry_buffer() { size_t byte_size = 0; for (::geometry_bucket& bucket : this->geometry_buckets) { byte_size = ff::math::round_up(byte_size, bucket.item_size()); bucket.render_start(byte_size / bucket.item_size()); byte_size += bucket.byte_size(); } void* buffer_data = this->geometry_buffer.map(ff_dx::get_device_state(), byte_size); if (buffer_data) { for (::geometry_bucket& bucket : this->geometry_buckets) { if (bucket.render_count()) { ::memcpy(reinterpret_cast<uint8_t*>(buffer_data) + bucket.render_start() * bucket.item_size(), bucket.data(), bucket.byte_size()); bucket.clear_items(); } } this->geometry_buffer.unmap(); return true; } assert(false); return false; } void draw_opaque_geometry() { const ff::draw_base::custom_context_func* custom_func = this->custom_context_stack.size() ? &this->custom_context_stack.back() : nullptr; ff_dx::get_device_state().set_topology_ia(D3D_PRIMITIVE_TOPOLOGY_POINTLIST); this->opaque_state.apply(); for (::geometry_bucket& bucket : this->geometry_buckets) { if (bucket.bucket_type() >= ::geometry_bucket_type::first_alpha) { break; } if (bucket.render_count()) { bucket.apply(this->geometry_buffer.dx_buffer(), this->target_requires_palette); if (!custom_func || (*custom_func)(bucket.item_type(), true)) { ff_dx::get_device_state().draw(bucket.render_count(), bucket.render_start()); } } } } void draw_alpha_geometry() { const size_t alpha_geometry_size = this->alpha_geometry.size(); if (alpha_geometry_size) { const ff::draw_base::custom_context_func* custom_func = this->custom_context_stack.size() ? &this->custom_context_stack.back() : nullptr; ff_dx::get_device_state().set_topology_ia(D3D_PRIMITIVE_TOPOLOGY_POINTLIST); ff_dx::fixed_state& alpha_state = this->force_pre_multiplied_alpha ? this->pre_multiplied_alpha_state : this->alpha_state; alpha_state.apply(); for (size_t i = 0; i < alpha_geometry_size; ) { const ::alpha_geometry_entry& entry = this->alpha_geometry[i]; size_t geometry_count = 1; for (i++; i < alpha_geometry_size; i++, geometry_count++) { const ::alpha_geometry_entry& entry2 = this->alpha_geometry[i]; if (entry2.bucket != entry.bucket || entry2.depth != entry.depth || entry2.index != entry.index + geometry_count) { break; } } entry.bucket->apply(this->geometry_buffer.dx_buffer(), this->target_requires_palette); if (!custom_func || (*custom_func)(entry.bucket->item_type(), false)) { ff_dx::get_device_state().draw(geometry_count, entry.bucket->render_start() + entry.index); } } } } float nudge_depth(::last_depth_type depth_type) { if (depth_type < ::last_depth_type::start_no_overlap || this->last_depth_type != depth_type) { this->draw_depth += ::RENDER_DEPTH_DELTA; } this->last_depth_type = depth_type; return this->draw_depth; } unsigned int get_world_matrix_index() { unsigned int index = this->get_world_matrix_index_no_flush(); if (index == ff::constants::invalid_dword) { this->flush(); index = this->get_world_matrix_index_no_flush(); } return index; } unsigned int get_world_matrix_index_no_flush() { if (this->world_matrix_index == ff::constants::invalid_dword) { DirectX::XMFLOAT4X4 wm; DirectX::XMStoreFloat4x4(&wm, DirectX::XMMatrixTranspose(DirectX::XMLoadFloat4x4(&this->world_matrix_stack_.matrix()))); auto iter = this->world_matrix_to_index.find(wm); if (iter == this->world_matrix_to_index.cend() && this->world_matrix_to_index.size() != ::MAX_TRANSFORM_MATRIXES) { iter = this->world_matrix_to_index.try_emplace(wm, static_cast<unsigned int>(this->world_matrix_to_index.size())).first; } if (iter != this->world_matrix_to_index.cend()) { this->world_matrix_index = iter->second; } } return this->world_matrix_index; } unsigned int get_texture_index_no_flush(const ff::texture_view_base& texture_view, bool use_palette) { if (use_palette) { unsigned int palette_index = (this->palette_index == ff::constants::invalid_dword) ? this->get_palette_index_no_flush() : this->palette_index; if (palette_index == ff::constants::invalid_dword) { return ff::constants::invalid_dword; } unsigned int palette_remap_index = (this->palette_remap_index == ff::constants::invalid_dword) ? this->get_palette_remap_index_no_flush() : this->palette_remap_index; if (palette_remap_index == ff::constants::invalid_dword) { return ff::constants::invalid_dword; } unsigned int texture_index = ff::constants::invalid_dword; for (size_t i = this->textures_using_palette_count; i != 0; i--) { if (this->textures_using_palette[i - 1] == &texture_view) { texture_index = static_cast<unsigned int>(i - 1); break; } } if (texture_index == ff::constants::invalid_dword) { if (this->textures_using_palette_count == ::MAX_TEXTURES_USING_PALETTE) { return ff::constants::invalid_dword; } this->textures_using_palette[this->textures_using_palette_count] = &texture_view; texture_index = static_cast<unsigned int>(this->textures_using_palette_count++); } return texture_index | (palette_index << 8) | (palette_remap_index << 16); } else { unsigned int palette_remap_index = 0; if (this->target_requires_palette) { palette_remap_index = (this->palette_remap_index == ff::constants::invalid_dword) ? this->get_palette_remap_index_no_flush() : this->palette_remap_index; if (palette_remap_index == ff::constants::invalid_dword) { return ff::constants::invalid_dword; } } unsigned int texture_index = ff::constants::invalid_dword; for (size_t i = this->texture_count; i != 0; i--) { if (this->textures[i - 1] == &texture_view) { texture_index = static_cast<unsigned int>(i - 1); break; } } if (texture_index == ff::constants::invalid_dword) { if (this->texture_count == ::MAX_TEXTURES) { return ff::constants::invalid_dword; } this->textures[this->texture_count] = &texture_view; texture_index = static_cast<unsigned int>(this->texture_count++); } return texture_index | (palette_remap_index << 16); } } unsigned int get_palette_index_no_flush() { if (this->palette_index == ff::constants::invalid_dword) { if (this->target_requires_palette) { // Not converting palette to RGBA, so don't use a palette this->palette_index = 0; } else { ff::palette_base* palette = this->palette_stack.back(); size_t palette_hash = palette ? palette->data()->row_hash(palette->current_row()) : 0; auto iter = this->palette_to_index.find(palette_hash); if (iter == this->palette_to_index.cend() && this->palette_to_index.size() != ::MAX_PALETTES) { iter = this->palette_to_index.try_emplace(palette_hash, std::make_pair(palette, static_cast<unsigned int>(this->palette_to_index.size()))).first; } if (iter != this->palette_to_index.cend()) { this->palette_index = iter->second.second; } } } return this->palette_index; } unsigned int get_palette_remap_index_no_flush() { if (this->palette_remap_index == ff::constants::invalid_dword) { auto& remap_pair = this->palette_remap_stack.back(); auto iter = this->palette_remap_to_index.find(remap_pair.second); if (iter == this->palette_remap_to_index.cend() && this->palette_remap_to_index.size() != ::MAX_PALETTE_REMAPS) { iter = this->palette_remap_to_index.try_emplace(remap_pair.second, std::make_pair(remap_pair.first, static_cast<unsigned int>(this->palette_remap_to_index.size()))).first; } if (iter != this->palette_remap_to_index.cend()) { this->palette_remap_index = iter->second.second; } } return this->palette_remap_index; } int remap_palette_index(int color) const { return this->palette_remap_stack.back().first[color]; } void get_world_matrix_and_texture_index(const ff::texture_view_base& texture_view, bool use_palette, unsigned int& model_index, unsigned int& texture_index) { model_index = (this->world_matrix_index == ff::constants::invalid_dword) ? this->get_world_matrix_index_no_flush() : this->world_matrix_index; texture_index = this->get_texture_index_no_flush(texture_view, use_palette); if (model_index == ff::constants::invalid_dword || texture_index == ff::constants::invalid_dword) { this->flush(); this->get_world_matrix_and_texture_index(texture_view, use_palette, model_index, texture_index); } } void get_world_matrix_and_texture_indexes(ff::texture_view_base* const* texture_views, bool use_palette, unsigned int* texture_indexes, size_t count, unsigned int& model_index) { model_index = (this->world_matrix_index == ff::constants::invalid_dword) ? this->get_world_matrix_index_no_flush() : this->world_matrix_index; bool flush = (model_index == ff::constants::invalid_dword); for (size_t i = 0; !flush && i < count; i++) { texture_indexes[i] = this->get_texture_index_no_flush(*texture_views[i], use_palette); flush |= (texture_indexes[i] == ff::constants::invalid_dword); } if (flush) { this->flush(); this->get_world_matrix_and_texture_indexes(texture_views, use_palette, texture_indexes, count, model_index); } } void* add_geometry(const void* data, ::geometry_bucket_type bucket_type, float depth) { ::geometry_bucket& bucket = this->get_geometry_bucket(bucket_type); if (bucket_type >= ::geometry_bucket_type::first_alpha) { assert(!this->force_opaque); this->alpha_geometry.push_back(::alpha_geometry_entry { &bucket, bucket.count(), depth }); } return bucket.add(data); } ::geometry_bucket& get_geometry_bucket(::geometry_bucket_type type) { return this->geometry_buckets[static_cast<size_t>(type)]; } enum class state_t { invalid, valid, drawing, } state; // Constant data for shaders ff_dx::buffer geometry_buffer; ff_dx::buffer geometry_constants_buffer_0; ff_dx::buffer geometry_constants_buffer_1; ff_dx::buffer pixel_constants_buffer_0; ::geometry_shader_constants_0 geometry_constants_0; ::geometry_shader_constants_1 geometry_constants_1; ::pixel_shader_constants_0 pixel_constants_0; size_t geometry_constants_hash_0; size_t geometry_constants_hash_1; size_t pixel_constants_hash_0; // Render state std::vector<Microsoft::WRL::ComPtr<ID3D11SamplerState>> sampler_stack; ff_dx::fixed_state opaque_state; ff_dx::fixed_state alpha_state; ff_dx::fixed_state pre_multiplied_alpha_state; std::vector<ff::draw_base::custom_context_func> custom_context_stack; // Matrixes DirectX::XMFLOAT4X4 view_matrix; ff::matrix_stack world_matrix_stack_; ff::signal_connection world_matrix_stack_changing_connection; std::unordered_map<DirectX::XMFLOAT4X4, unsigned int, ff::stable_hash<DirectX::XMFLOAT4X4>> world_matrix_to_index; unsigned int world_matrix_index; // Textures std::array<const ff::texture_view_base*, ::MAX_TEXTURES> textures; std::array<const ff::texture_view_base*, ::MAX_TEXTURES_USING_PALETTE> textures_using_palette; size_t texture_count; size_t textures_using_palette_count; // Palettes bool target_requires_palette; std::vector<ff::palette_base*> palette_stack; std::shared_ptr<ff::texture> palette_texture; std::array<size_t, ::MAX_PALETTES> palette_texture_hashes; std::unordered_map<size_t, std::pair<ff::palette_base*, unsigned int>, ff::no_hash<size_t>> palette_to_index; unsigned int palette_index; std::vector<std::pair<const uint8_t*, size_t>> palette_remap_stack; std::shared_ptr<ff::texture> palette_remap_texture; std::array<size_t, ::MAX_PALETTE_REMAPS> palette_remap_texture_hashes; std::unordered_map<size_t, std::pair<const uint8_t*, unsigned int>, ff::no_hash<size_t>> palette_remap_to_index; unsigned int palette_remap_index; // Render data std::vector<::alpha_geometry_entry> alpha_geometry; std::array<::geometry_bucket, static_cast<size_t>(::geometry_bucket_type::count)> geometry_buckets; ::last_depth_type last_depth_type; float draw_depth; int force_no_overlap; int force_opaque; int force_pre_multiplied_alpha; }; } std::unique_ptr<ff::draw_device> ff::draw_device::create() { return std::make_unique<::draw_device_internal>(); } ff::draw_ptr ff::draw_device::begin_draw(ff::target_base& target, ff::depth* depth, const ff::rect_fixed& view_rect, const ff::rect_fixed& world_rect, ff::draw_options options) { return this->begin_draw(target, depth, std::floor(view_rect).cast<float>(), std::floor(world_rect).cast<float>(), options); } #endif
40.024646
212
0.595844
spadapet