2
0

level_editor.cpp 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501
  1. /*
  2. * Copyright (c) 2012-2018 Daniele Bartolini and individual contributors.
  3. * License: https://github.com/dbartolini/crown/blob/master/LICENSE
  4. */
  5. #if CROWN_TOOLS
  6. #include "core/containers/vector.h"
  7. #include "core/filesystem/file.h"
  8. #include "core/filesystem/filesystem_disk.h"
  9. #include "core/filesystem/path.h"
  10. #include "core/json/json.h"
  11. #include "core/json/json_object.h"
  12. #include "core/json/sjson.h"
  13. #include "core/math/vector2.h"
  14. #include "core/network/socket.h"
  15. #include "core/strings/dynamic_string.h"
  16. #include "device/device.h"
  17. #include "device/device_event_queue.h"
  18. #include "device/device_options.h"
  19. #include "device/input_device.h"
  20. #include "device/input_manager.h"
  21. #include "device/input_types.h"
  22. #include "device/log.h"
  23. #include "device/pipeline.h"
  24. #include "imgui_context.h"
  25. #include "resource/resource_manager.h"
  26. #include "resource/texture_resource.h"
  27. #include "tool_api.h"
  28. #include <iconfontheaders/icons_material_design.h>
  29. #include <imgui.h>
  30. #include <nfd.h>
  31. #include <time.h>
  32. #if CROWN_PLATFORM_POSIX
  33. #include <sys/time.h>
  34. #endif
  35. namespace { const crown::log_internal::System LEVEL_EDITOR = { "LevelEditor" }; }
  36. namespace crown
  37. {
  38. static u16 _width = 1280;
  39. static u16 _height = 720;
  40. struct Pivot
  41. {
  42. enum Enum
  43. {
  44. TOP_LEFT,
  45. TOP_CENTER,
  46. TOP_RIGHT,
  47. LEFT,
  48. CENTER,
  49. RIGHT,
  50. BOTTOM_LEFT,
  51. BOTTOM_CENTER,
  52. BOTTOM_RIGHT,
  53. COUNT
  54. };
  55. };
  56. static const char* pivot_names[] =
  57. {
  58. "Top Left", // Pivot::TOP_LEFT
  59. "Top Right", // Pivot::TOP_CENTER
  60. "Top Center", // Pivot::TOP_RIGHT
  61. "Left", // Pivot::LEFT
  62. "Center", // Pivot::CENTER
  63. "Right", // Pivot::RIGHT
  64. "Bottom Left", // Pivot::BOTTOM_LEFT
  65. "Bottom Center", // Pivot::BOTTOM_CENTER
  66. "Bottom Right" // Pivot::BOTTOM_RIGHT
  67. };
  68. CE_STATIC_ASSERT(countof(pivot_names) == Pivot::COUNT);
  69. Vector2 sprite_cell_xy(int r, int c, int offset_x, int offset_y, int cell_w, int cell_h, int spacing_x, int spacing_y)
  70. {
  71. int x0 = offset_x + c*cell_w + c*spacing_x;
  72. int y0 = offset_y + r*cell_h + r*spacing_y;
  73. return vector2((f32)x0, (f32)y0);
  74. }
  75. Vector2 sprite_cell_pivot_xy(int cell_w, int cell_h, int pivot)
  76. {
  77. int pivot_x = 0;
  78. int pivot_y = 0;
  79. switch (pivot)
  80. {
  81. case Pivot::TOP_LEFT:
  82. pivot_x = 0;
  83. pivot_y = 0;
  84. break;
  85. case Pivot::TOP_CENTER:
  86. pivot_x = cell_w / 2;
  87. pivot_y = 0;
  88. break;
  89. case Pivot::TOP_RIGHT:
  90. pivot_x = cell_w;
  91. pivot_y = 0;
  92. break;
  93. case Pivot::BOTTOM_LEFT:
  94. pivot_x = 0;
  95. pivot_y = cell_h;
  96. break;
  97. case Pivot::BOTTOM_CENTER:
  98. pivot_x = cell_w / 2;
  99. pivot_y = cell_h;
  100. break;
  101. case Pivot::BOTTOM_RIGHT:
  102. pivot_x = cell_w;
  103. pivot_y = cell_h;
  104. break;
  105. case Pivot::LEFT:
  106. pivot_x = 0;
  107. pivot_y = cell_h / 2;
  108. break;
  109. case Pivot::CENTER:
  110. pivot_x = cell_w / 2;
  111. pivot_y = cell_h / 2;
  112. break;
  113. case Pivot::RIGHT:
  114. pivot_x = cell_w;
  115. pivot_y = cell_h / 2;
  116. break;
  117. default:
  118. CE_FATAL("Unknown pivot");
  119. break;
  120. }
  121. return vector2((f32)pivot_x, (f32)pivot_y);
  122. }
  123. struct SpriteImporter
  124. {
  125. int width;
  126. int height;
  127. int cells_h;
  128. int cells_v;
  129. bool cell_wh_auto;
  130. int cell_w;
  131. int cell_h;
  132. int offset_x;
  133. int offset_y;
  134. int spacing_x;
  135. int spacing_y;
  136. int pivot;
  137. int layer;
  138. int depth;
  139. SpriteImporter()
  140. : width(128)
  141. , height(128)
  142. , cells_h(4)
  143. , cells_v(4)
  144. , cell_wh_auto(false)
  145. , cell_w(16)
  146. , cell_h(16)
  147. , offset_x(0)
  148. , offset_y(0)
  149. , spacing_x(0)
  150. , spacing_y(0)
  151. , pivot(Pivot::CENTER)
  152. , layer(0)
  153. , depth(0)
  154. {
  155. }
  156. void draw()
  157. {
  158. ImGui::Columns(2);
  159. #if 1
  160. ImDrawList* draw_list = ImGui::GetWindowDrawList();
  161. {
  162. // Here we are using InvisibleButton() as a convenience to 1) advance the cursor and 2) allows us to use IsItemHovered()
  163. // However you can draw directly and poll mouse/keyboard by yourself. You can manipulate the cursor using GetCursorPos() and SetCursorPos().
  164. // If you only use the ImDrawList API, you can notify the owner window of its extends by using SetCursorPos(max).
  165. ImVec2 canvas_pos = ImGui::GetCursorScreenPos(); // ImDrawList API uses screen coordinates!
  166. ImVec2 canvas_size = ImGui::GetContentRegionAvail(); // Resize canvas to what's available
  167. if (canvas_size.x < 50.0f) canvas_size.x = 10.0f;
  168. if (canvas_size.y < 50.0f) canvas_size.y = 50.0f;
  169. draw_list->AddRectFilledMultiColor(canvas_pos, ImVec2(canvas_pos.x + canvas_size.x, canvas_pos.y + canvas_size.y), ImColor(50,50,50), ImColor(50,50,60), ImColor(60,60,70), ImColor(50,50,60));
  170. // Pivot is relative to the top-left corner of the cell
  171. Vector2 pivot_xy = sprite_cell_pivot_xy(cell_w
  172. , cell_h
  173. , pivot
  174. );
  175. int num_v = cells_v;
  176. int num_h = cells_h;
  177. for (int h = 0; h < num_v; ++h)
  178. {
  179. for (int w = 0; w < num_h; ++w)
  180. {
  181. Vector2 cell = sprite_cell_xy(h
  182. , w
  183. , offset_x
  184. , offset_y
  185. , cell_w
  186. , cell_h
  187. , spacing_x
  188. , spacing_y
  189. );
  190. const int x0 = (int)cell.x;
  191. const int y0 = (int)cell.y;
  192. const int x1 = x0+(int)cell_w;
  193. const int y1 = y0+(int)cell_h;
  194. draw_list->AddRect(ImVec2(canvas_pos.x + x0, canvas_pos.y + y0)
  195. , ImVec2(canvas_pos.x + x1, canvas_pos.y + y1)
  196. , ImColor(230, 26, 26, 153)
  197. );
  198. draw_list->AddCircleFilled(ImVec2(x0 + canvas_pos.x + pivot_xy.x, y0 + canvas_pos.y + pivot_xy.y)
  199. , 5.0f
  200. , ImColor(26, 26, 230, 153)
  201. );
  202. }
  203. }
  204. ImGui::InvisibleButton("canvas", canvas_size);
  205. draw_list->PushClipRect(canvas_pos, ImVec2(canvas_pos.x+canvas_size.x, canvas_pos.y+canvas_size.y)); // clip lines within the canvas (if we resize it, etc.)
  206. }
  207. #endif
  208. ImGui::NextColumn();
  209. ImGui::BeginGroup();
  210. ImGui::LabelText("Resolution", "%d x %d", width, height);
  211. // FIXME: replace fclamp
  212. ImGui::InputInt("Cells H", &cells_h);
  213. cells_h = (int)fclamp((f32)cells_h, 1.0f, 256.0f);
  214. ImGui::InputInt("Cells V", &cells_v);
  215. cells_v = (int)fclamp((f32)cells_v, 1.0f, 256.0f);
  216. ImGui::Checkbox("Cell WH auto", &cell_wh_auto);
  217. ImGui::InputInt("Cell W", &cell_w);
  218. cell_w = (int)fclamp((f32)cell_w, 1.0f, 4096.0f);
  219. ImGui::InputInt("Cell H", &cell_h);
  220. cell_h = (int)fclamp((f32)cell_h, 1.0f, 4096.0f);
  221. ImGui::InputInt("Offset X", &offset_x);
  222. offset_x = (int)fclamp((f32)offset_x, 0.0f, 128.0f);
  223. ImGui::InputInt("Offset Y", &offset_y);
  224. offset_y = (int)fclamp((f32)offset_y, 0.0f, 128.0f);
  225. ImGui::InputInt("Spacing X", &spacing_x);
  226. spacing_x = (int)fclamp((f32)spacing_x, 0.0f, 128.0f);
  227. ImGui::InputInt("Spacing Y", &spacing_y);
  228. spacing_y = (int)fclamp((f32)spacing_y, 0.0f, 128.0f);
  229. ImGui::Combo("Pivot", &pivot, pivot_names, Pivot::COUNT);
  230. ImGui::InputInt("Layer", &layer);
  231. layer = (int)fclamp((f32)layer, 0.0f, 7.0f);
  232. ImGui::InputInt("Depth", &depth);
  233. depth = (int)fclamp((f32)depth, 0.0f, 9999.0f);
  234. ImGui::EndGroup();
  235. }
  236. };
  237. //-----------------------------------------------------------------------------
  238. struct Inspector
  239. {
  240. // Inspector
  241. char _name[1024];
  242. f32 _position[3];
  243. f32 _rotation[3];
  244. f32 _scale[3];
  245. char _sprite[1024];
  246. char _material[1024];
  247. bool _visible;
  248. char _state_machine[1024];
  249. bool _open;
  250. Inspector()
  251. : _visible(true)
  252. , _open(true)
  253. {
  254. memset(_name, 0, sizeof(_name));
  255. memset(_sprite, 0, sizeof(_sprite));
  256. memset(_material, 0, sizeof(_material));
  257. memset(_position, 0, sizeof(_position));
  258. memset(_rotation, 0, sizeof(_rotation));
  259. memset(_scale, 0, sizeof(_scale));
  260. memset(_state_machine, 0, sizeof(_state_machine));
  261. }
  262. void draw()
  263. {
  264. if (!_open)
  265. return;
  266. if (ImGui::TreeNodeEx("Unit", ImGuiTreeNodeFlags_DefaultOpen))
  267. {
  268. ImGui::InputText("Name", _name, sizeof(_name));
  269. ImGui::TreePop();
  270. }
  271. if (ImGui::TreeNodeEx("Transform", ImGuiTreeNodeFlags_DefaultOpen))
  272. {
  273. ImGui::InputFloat3("Position", _position);
  274. ImGui::InputFloat3("Rotation", _rotation);
  275. ImGui::InputFloat3("Scale", _scale);
  276. ImGui::TreePop();
  277. }
  278. if (ImGui::TreeNodeEx("Renderer", ImGuiTreeNodeFlags_DefaultOpen))
  279. {
  280. ImGui::InputText("Sprite", _sprite, sizeof(_sprite));
  281. ImGui::InputText("Material", _material, sizeof(_material));
  282. ImGui::Checkbox("Visible", &_visible);
  283. ImGui::TreePop();
  284. }
  285. if (ImGui::TreeNodeEx("Animation", ImGuiTreeNodeFlags_DefaultOpen))
  286. {
  287. ImGui::InputText("State Machine", _state_machine, sizeof(_state_machine));
  288. ImGui::TreePop();
  289. }
  290. }
  291. };
  292. //-----------------------------------------------------------------------------
  293. struct SceneView
  294. {
  295. ImVec2 _origin;
  296. ImVec2 _size;
  297. ImVec2 _cursor;
  298. bool _open;
  299. SceneView()
  300. : _open(true)
  301. {
  302. }
  303. void draw()
  304. {
  305. if (!_open)
  306. return;
  307. _origin = ImGui::GetCursorScreenPos();
  308. uint16_t w, h;
  309. device()->resolution(w, h);
  310. bgfx::TextureHandle txh = device()->_pipeline->_buffers[0];
  311. CE_ENSURE(bgfx::isValid(txh));
  312. ImGui::Image((void*)(uintptr_t)txh.idx
  313. , ImVec2(w, h)
  314. #if CROWN_PLATFORM_WINDOWS
  315. , ImVec2(0, 0)
  316. , ImVec2(1, 1)
  317. #else
  318. , ImVec2(0, 1)
  319. , ImVec2(1, 0)
  320. #endif // CROWN_PLATFORM_WINDOWS
  321. );
  322. ImVec2 mouse_pos_in_view = ImVec2(ImGui::GetIO().MousePos.x - _origin.x
  323. , ImGui::GetIO().MousePos.y - _origin.y
  324. );
  325. if (ImGui::IsWindowHovered()
  326. && mouse_pos_in_view.x > 0
  327. && mouse_pos_in_view.x < w
  328. && mouse_pos_in_view.y > 0
  329. && mouse_pos_in_view.y < h
  330. )
  331. {
  332. // Send all input to engine
  333. ImGui::CaptureMouseFromApp(false);
  334. ImGui::CaptureKeyboardFromApp(false);
  335. }
  336. else
  337. {
  338. // Send all input to imgui
  339. ImGui::CaptureMouseFromApp(true);
  340. ImGui::CaptureKeyboardFromApp(true);
  341. }
  342. _size = ImGui::GetWindowSize();
  343. _size.x -= _origin.x;
  344. }
  345. };
  346. //-----------------------------------------------------------------------------
  347. struct SceneTree
  348. {
  349. bool _open;
  350. SceneTree()
  351. : _open(true)
  352. {
  353. }
  354. void draw()
  355. {
  356. if (!_open)
  357. return;
  358. if (ImGui::TreeNodeEx("Units", ImGuiTreeNodeFlags_DefaultOpen))
  359. {
  360. if (ImGui::TreeNodeEx("Objects", ImGuiTreeNodeFlags_DefaultOpen))
  361. {
  362. for (int i = 0; i < 5; i++)
  363. if (ImGui::TreeNode((void*)(intptr_t)i, "Child %d", i))
  364. {
  365. ImGui::Text("blah blah");
  366. ImGui::SameLine();
  367. if (ImGui::SmallButton("print")) printf("Child %d pressed", i);
  368. ImGui::TreePop();
  369. }
  370. ImGui::TreePop();
  371. }
  372. if (ImGui::TreeNodeEx("Lights", ImGuiTreeNodeFlags_DefaultOpen))
  373. {
  374. // ShowHelpMarker("This is a more standard looking tree with selectable nodes.\nClick to select, Ctrl+Click to toggle, click on arrows or double-click to open.");
  375. static bool align_label_with_current_x_position = false;
  376. ImGui::Checkbox("Align label with current X position)", &align_label_with_current_x_position);
  377. ImGui::Text("Hello!");
  378. if (align_label_with_current_x_position)
  379. ImGui::Unindent(ImGui::GetTreeNodeToLabelSpacing());
  380. static int selection_mask = (1 << 2); // Dumb representation of what may be user-side selection state. You may carry selection state inside or outside your objects in whatever format you see fit.
  381. int node_clicked = -1; // Temporary storage of what node we have clicked to process selection at the end of the loop. May be a pointer to your own node type, etc.
  382. ImGui::PushStyleVar(ImGuiStyleVar_IndentSpacing, ImGui::GetFontSize()*3); // Increase spacing to differentiate leaves from expanded contents.
  383. for (int i = 0; i < 6; i++)
  384. {
  385. // Disable the default open on single-click behavior and pass in Selected flag according to our selection state.
  386. ImGuiTreeNodeFlags node_flags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick | ((selection_mask & (1 << i)) ? ImGuiTreeNodeFlags_Selected : 0);
  387. if (i < 3)
  388. {
  389. // Node
  390. bool node_open = ImGui::TreeNodeEx((void*)(intptr_t)i, node_flags, "Selectable Node %d", i);
  391. if (ImGui::IsItemClicked())
  392. node_clicked = i;
  393. if (node_open)
  394. {
  395. ImGui::Text("Blah blah\nBlah Blah");
  396. ImGui::TreePop();
  397. }
  398. }
  399. else
  400. {
  401. // Leaf: The only reason we have a TreeNode at all is to allow selection of the leaf. Otherwise we can use BulletText() or TreeAdvanceToLabelPos()+Text().
  402. ImGui::TreeNodeEx((void*)(intptr_t)i, node_flags | ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen, "Selectable Leaf %d", i);
  403. if (ImGui::IsItemClicked())
  404. node_clicked = i;
  405. }
  406. }
  407. if (node_clicked != -1)
  408. {
  409. // Update selection state. Process outside of tree loop to avoid visual inconsistencies during the clicking-frame.
  410. if (ImGui::GetIO().KeyCtrl)
  411. selection_mask ^= (1 << node_clicked); // Ctrl+click to toggle
  412. else //if (!(selection_mask & (1 << node_clicked))) // Depending on selection behavior you want, this commented bit preserve selection when clicking on item that is part of the selection
  413. selection_mask = (1 << node_clicked); // Click to single-select
  414. }
  415. ImGui::PopStyleVar();
  416. if (align_label_with_current_x_position)
  417. ImGui::Indent(ImGui::GetTreeNodeToLabelSpacing());
  418. ImGui::TreePop();
  419. }
  420. ImGui::TreePop();
  421. }
  422. }
  423. };
  424. //-----------------------------------------------------------------------------
  425. struct SpriteAnimator
  426. {
  427. bool _open;
  428. bool _add_animation_popup_open;
  429. Array<const char*> _entities;
  430. s32 _cur_entity;
  431. TextureResource* _texture;
  432. u32 _texture_width;
  433. u32 _texture_height;
  434. struct Frame
  435. {
  436. char name[512];
  437. ImVec2 pivot;
  438. ImVec4 region;
  439. };
  440. Array<Frame> _frames;
  441. char _anim_name[512];
  442. f32 _anim_time;
  443. Array<const char*> _listbox_items;
  444. s32 _listbox_item_current;
  445. Array<Frame> _anim_preview_frames;
  446. f32 _delta;
  447. u32 current;
  448. Vector<DynamicString> file_list_sprites;
  449. FilesystemDisk* _fs;
  450. SpriteAnimator(const DynamicString& src_dir)
  451. : _open(false)
  452. , _add_animation_popup_open(false)
  453. , _entities(default_allocator())
  454. , _cur_entity(0)
  455. , _texture(nullptr)
  456. , _texture_width(0)
  457. , _texture_height(0)
  458. , _frames(default_allocator())
  459. , _anim_time(0.1f)
  460. , _listbox_items(default_allocator())
  461. , _listbox_item_current(0)
  462. , _anim_preview_frames(default_allocator())
  463. , _delta(0.0f)
  464. , current(0)
  465. , file_list_sprites(default_allocator())
  466. {
  467. memset(_anim_name, 0, sizeof(_anim_name));
  468. _fs = CE_NEW(default_allocator(), FilesystemDisk)(default_allocator());
  469. _fs->set_prefix(src_dir.c_str());
  470. get_sprites_list();
  471. }
  472. ~SpriteAnimator()
  473. {
  474. CE_DELETE(default_allocator(), _fs);
  475. }
  476. ImVec2 pixel_to_uv(u32 tex_w, u32 tex_h, f32 x, f32 y)
  477. {
  478. ImVec2 uv;
  479. uv.x = (f32)x / (f32)tex_w;
  480. uv.y = (f32)y / (f32)tex_h;
  481. return uv;
  482. }
  483. void get_directory(DynamicString& dir, const char* path)
  484. {
  485. CE_ENSURE(NULL != path);
  486. const char* ls = strrchr(path, '/');
  487. u32 file_len = strlen32(ls+1);
  488. u32 dir_len = strlen32(path) - file_len;
  489. char buff[1024];
  490. memcpy(buff, path, dir_len);
  491. buff[dir_len] = '\0';
  492. path::reduce(dir, buff);
  493. }
  494. void save_sprite_animation()
  495. {
  496. TempAllocator4096 ta;
  497. StringStream ss(ta);
  498. ss << "frames = [ ";
  499. for (u32 i = 0; i < array::size(_listbox_items); i++)
  500. {
  501. ss << _listbox_items[i] + 7 << " ";
  502. }
  503. ss << "]\n";
  504. ss << "total_time = ";
  505. ss << _anim_time;
  506. DynamicString dir(ta);
  507. get_directory(dir, _entities[_cur_entity]);
  508. DynamicString file_name(ta);
  509. path::join(file_name, dir.c_str(), _anim_name);
  510. file_name += ".sprite_animation";
  511. File* f = _fs->open(file_name.c_str(), FileOpenMode::WRITE);
  512. f->write(string_stream::c_str(ss), strlen32(string_stream::c_str(ss)));
  513. f->close();
  514. }
  515. void get_files_list(Vector<DynamicString>& out, const char* path="")
  516. {
  517. TempAllocator4096 ta;
  518. Vector<DynamicString> files(ta);
  519. _fs->list_files(path, files);
  520. for (u32 i = 0; i < vector::size(files); i++)
  521. {
  522. DynamicString join(ta);
  523. path::join(join, path, files[i].c_str());
  524. join = join.c_str()[0] == '/' ? join.c_str()+1 : join.c_str();
  525. if (_fs->is_directory(join.c_str()))
  526. {
  527. get_files_list(out, join.c_str());
  528. }
  529. else
  530. {
  531. vector::push_back(out, join);
  532. }
  533. }
  534. }
  535. void get_sprites_list()
  536. {
  537. TempAllocator4096 ta;
  538. Vector<DynamicString> files(ta);
  539. get_files_list(files);
  540. for (DynamicString* f = vector::begin(files); f != vector::end(files); f++)
  541. if (f->has_suffix(".sprite"))
  542. array::push_back(_entities, (const char*) strdup(f->c_str()));
  543. }
  544. void draw()
  545. {
  546. if (!_open)
  547. return;
  548. if (_texture)
  549. {
  550. Frame f = _frames[0];
  551. ImVec2 start = pixel_to_uv(_texture_width, _texture_height, f.region.x, f.region.y);
  552. ImVec2 end = pixel_to_uv(_texture_width, _texture_height, f.region.x+f.region.z, f.region.y+f.region.w);
  553. ImGui::Image((void*)(uintptr_t)_texture->handle.idx
  554. , ImVec2(f.region.z, f.region.w)
  555. , start
  556. , end
  557. , ImColor(255, 255, 255, 55)
  558. );
  559. }
  560. if (ImGui::Combo("Entities", &_cur_entity, (const char* const*) array::begin(_entities), array::size(_entities)))
  561. {
  562. array::clear(_frames);
  563. const char* sprite = _entities[_cur_entity];
  564. u32 sprite_len = strlen32(sprite);
  565. char entity[1024];
  566. strncpy(entity, sprite, sizeof(entity)-1);
  567. entity[sprite_len-7] = '\0'; // remove ".sprite"
  568. ResourceManager* resman = device()->_resource_manager;
  569. _texture = (TextureResource*)resman->get(RESOURCE_TYPE_TEXTURE, StringId64(entity));
  570. File* file = _fs->open(sprite, FileOpenMode::READ);
  571. const u32 size = file->size();
  572. Buffer buf(default_allocator());
  573. array::resize(buf, size);
  574. file->read(array::begin(buf), size);
  575. _fs->close(*file);
  576. JsonObject obj(default_allocator());
  577. JsonArray list(default_allocator());
  578. sjson::parse(buf, obj);
  579. sjson::parse_array(obj["frames"], list);
  580. _texture_width = sjson::parse_int(obj["width"]);
  581. _texture_height = sjson::parse_int(obj["height"]);
  582. for (u32 i = 0; i < array::size(list); i++)
  583. {
  584. JsonObject frame(default_allocator());
  585. DynamicString name(default_allocator());
  586. JsonArray pivot(default_allocator());
  587. JsonArray region(default_allocator());
  588. sjson::parse_object(list[i], frame);
  589. sjson::parse_array(frame["pivot"], pivot);
  590. sjson::parse_array(frame["region"], region);
  591. Frame f;
  592. sjson::parse_string(frame["name"], name);
  593. strncpy(f.name, name.c_str(), name.length());
  594. f.name[name.length()] = '\0';
  595. f.pivot.x = sjson::parse_float(pivot[0]);
  596. f.pivot.y = sjson::parse_float(pivot[1]);
  597. f.region.x = sjson::parse_float(region[0]);
  598. f.region.y = sjson::parse_float(region[1]);
  599. f.region.z = sjson::parse_float(region[2]);
  600. f.region.w = sjson::parse_float(region[3]);
  601. array::push_back(_frames, f);
  602. }
  603. }
  604. if (ImGui::Button("Add animation", ImVec2(100, 25)))
  605. {
  606. _add_animation_popup_open = true;
  607. }
  608. if (_add_animation_popup_open)
  609. {
  610. ImGui::OpenPopup("Add animation");
  611. }
  612. if (ImGui::BeginPopup("Add animation"))
  613. {
  614. ImGui::InputText("Name", _anim_name, sizeof(_anim_name));
  615. ImGui::InputFloat("Time", &_anim_time, 0.1f, 0.1f);
  616. ImGui::ListBox("Animation Frames", &_listbox_item_current, (const char* const*)array::begin(_listbox_items), array::size(_listbox_items));
  617. if (ImGui::Button("Clear Frames", ImVec2(100.0f, 25.0f)))
  618. {
  619. array::clear(_listbox_items);
  620. array::clear(_anim_preview_frames);
  621. _delta = 0.0f;
  622. current = 0;
  623. }
  624. if (array::size(_anim_preview_frames) > 0)
  625. {
  626. _delta += 1.0f/60.0f;
  627. if (_delta >= _anim_time/array::size(_anim_preview_frames))
  628. {
  629. _delta = 0;
  630. current++;
  631. if (current >= array::size(_anim_preview_frames))
  632. current = 0;
  633. }
  634. Frame f = _anim_preview_frames[current];
  635. ImVec2 start = pixel_to_uv(_texture_width, _texture_height, f.region.x, f.region.y);
  636. ImVec2 end = pixel_to_uv(_texture_width, _texture_height, f.region.x+f.region.z, f.region.y+f.region.w);
  637. ImGui::Image(
  638. (void*)(uintptr_t)_texture->handle.idx
  639. , ImVec2(f.region.z, f.region.w)
  640. , start
  641. , end
  642. , ImColor(255, 255, 255, 55)
  643. );
  644. }
  645. ImGui::Separator();
  646. for (u32 i = 0; i < array::size(_frames); i++)
  647. {
  648. Frame f = _frames[i];
  649. ImVec2 start = pixel_to_uv(_texture_width, _texture_height, f.region.x, f.region.y);
  650. ImVec2 end = pixel_to_uv(_texture_width, _texture_height, f.region.x+f.region.z, f.region.y+f.region.w);
  651. ImGui::SameLine();
  652. if (i % 9 == 0) ImGui::NewLine();
  653. ImGui::BeginGroup();
  654. ImGui::Image(
  655. (void*)(uintptr_t)_texture->handle.idx
  656. , ImVec2(f.region.z, f.region.w)
  657. , start
  658. , end
  659. , ImColor(255, 255, 255, 55)
  660. );
  661. ImGui::NewLine();
  662. if (ImGui::Button(_frames[i].name, ImVec2(100.0f, 25.0f)))
  663. {
  664. array::push_back(_listbox_items, (const char*) strdup(_frames[i].name));
  665. array::push_back(_anim_preview_frames, _frames[i]);
  666. }
  667. ImGui::EndGroup();
  668. }
  669. if (ImGui::Button("Save", ImVec2(100, 25)))
  670. {
  671. save_sprite_animation();
  672. ImGui::CloseCurrentPopup();
  673. _add_animation_popup_open = false;
  674. }
  675. ImGui::SameLine();
  676. if (ImGui::Button("Cancel", ImVec2(100, 25)))
  677. {
  678. ImGui::CloseCurrentPopup();
  679. _add_animation_popup_open = false;
  680. }
  681. ImGui::EndPopup();
  682. }
  683. }
  684. };
  685. //-----------------------------------------------------------------------------
  686. struct LevelEditor
  687. {
  688. DynamicString _source_dir;
  689. // FX
  690. TextureResource* tool_move_texture;
  691. TextureResource* tool_place_texture;
  692. TextureResource* tool_rotate_texture;
  693. TextureResource* tool_scale_texture;
  694. TextureResource* reference_world_texture;
  695. TextureResource* reference_local_texture;
  696. TextureResource* axis_local_texture;
  697. TextureResource* axis_world_texture;
  698. TextureResource* snap_to_grid_texture;
  699. // State
  700. f32 _grid_size;
  701. f32 _rotation_snap;
  702. bool _show_grid;
  703. bool _snap_to_grid;
  704. bool _debug_render_world;
  705. bool _debug_physics_world;
  706. tool::ToolType::Enum _tool_type;
  707. tool::SnapMode::Enum _snap_mode;
  708. tool::ReferenceSystem::Enum _reference_system;
  709. ImVec2 _main_menu_pos;
  710. ImVec2 _main_menu_size;
  711. Console _console;
  712. Inspector _inspector;
  713. SceneView _scene_view;
  714. SceneTree _scene_tree;
  715. SpriteAnimator _animator;
  716. SpriteImporter _sprite_importer;
  717. LevelEditor(const DynamicString& source_dir)
  718. : _source_dir(default_allocator())
  719. , _grid_size(1.0f)
  720. , _rotation_snap(15)
  721. , _show_grid(true)
  722. , _snap_to_grid(true)
  723. , _debug_render_world(false)
  724. , _debug_physics_world(false)
  725. , _tool_type(tool::ToolType::MOVE)
  726. , _snap_mode(tool::SnapMode::RELATIVE)
  727. , _reference_system(tool::ReferenceSystem::LOCAL)
  728. , _main_menu_pos(0, 0)
  729. , _main_menu_size(0, 0)
  730. , _animator(source_dir)
  731. {
  732. ResourceManager* resman = device()->_resource_manager;
  733. tool_move_texture = (TextureResource*)resman->get(RESOURCE_TYPE_TEXTURE, StringId64("core/editors/gui/tool-move"));
  734. tool_place_texture = (TextureResource*)resman->get(RESOURCE_TYPE_TEXTURE, StringId64("core/editors/gui/tool-place"));
  735. tool_rotate_texture = (TextureResource*)resman->get(RESOURCE_TYPE_TEXTURE, StringId64("core/editors/gui/tool-rotate"));
  736. tool_scale_texture = (TextureResource*)resman->get(RESOURCE_TYPE_TEXTURE, StringId64("core/editors/gui/tool-scale"));
  737. reference_world_texture = (TextureResource*)resman->get(RESOURCE_TYPE_TEXTURE, StringId64("core/editors/gui/reference-world"));
  738. reference_local_texture = (TextureResource*)resman->get(RESOURCE_TYPE_TEXTURE, StringId64("core/editors/gui/reference-local"));
  739. axis_local_texture = (TextureResource*)resman->get(RESOURCE_TYPE_TEXTURE, StringId64("core/editors/gui/axis-local"));
  740. axis_world_texture = (TextureResource*)resman->get(RESOURCE_TYPE_TEXTURE, StringId64("core/editors/gui/axis-world"));
  741. snap_to_grid_texture = (TextureResource*)resman->get(RESOURCE_TYPE_TEXTURE, StringId64("core/editors/gui/snap-to-grid"));
  742. imgui_create();
  743. ImGui::LoadDock();
  744. }
  745. ~LevelEditor()
  746. {
  747. ImGui::SaveDock();
  748. imgui_destroy();
  749. }
  750. void update(f32 dt)
  751. {
  752. CE_UNUSED(dt);
  753. static f32 last_w = 0.0f;
  754. static f32 last_h = 0.0f;
  755. if (last_w != _scene_view._size.x || last_h != _scene_view._size.y)
  756. {
  757. last_w = _scene_view._size.x;
  758. last_h = _scene_view._size.y;
  759. device()->_width = u16(_scene_view._size.x != 0.0f ? _scene_view._size.x : 128.0f);
  760. device()->_height = u16(_scene_view._size.y != 0.0f ? _scene_view._size.y : 128.0f);
  761. }
  762. u32 message_count = 0;
  763. // Receive response from engine
  764. for (;;)
  765. {
  766. u32 msg_len = 0;
  767. ReadResult rr = _console._client.read_nonblock(&msg_len, sizeof(msg_len));
  768. if (rr.error == ReadResult::WOULDBLOCK)
  769. break;
  770. if (ReadResult::SUCCESS == rr.error)
  771. {
  772. char msg[8192];
  773. rr = _console._client.read(msg, msg_len);
  774. msg[msg_len] = '\0';
  775. message_count++;
  776. // logi(LEVEL_EDITOR, "count: %d", message_count);
  777. if (ReadResult::SUCCESS == rr.error)
  778. {
  779. TempAllocator4096 ta;
  780. JsonObject obj(ta);
  781. DynamicString type(ta);
  782. json::parse(msg, obj);
  783. json::parse_string(obj["type"], type);
  784. if (type == "message")
  785. {
  786. DynamicString severity(ta);
  787. DynamicString message(ta);
  788. json::parse_string(obj["severity"], severity);
  789. json::parse_string(obj["message"], message);
  790. LogSeverity::Enum ls = LogSeverity::COUNT;
  791. if (strcmp("info", severity.c_str()) == 0)
  792. ls = LogSeverity::LOG_INFO;
  793. else if (strcmp("warning", severity.c_str()) == 0)
  794. ls = LogSeverity::LOG_WARN;
  795. else if (strcmp("error", severity.c_str()) == 0)
  796. ls = LogSeverity::LOG_ERROR;
  797. else
  798. CE_FATAL("Unknown severity");
  799. _console.add_log(ls, message.c_str());
  800. }
  801. else
  802. {
  803. _console.add_log(LogSeverity::LOG_ERROR, "Unknown message type");
  804. }
  805. console_scroll_to_bottom(_console);
  806. }
  807. }
  808. }
  809. imgui_begin_frame(VIEW_IMGUI, _width, _height);
  810. f32 offset_y = _main_menu_size.y;
  811. ImGui::RootDock(ImVec2(0, offset_y), ImVec2(_width, _height-offset_y));
  812. main_menu_bar();
  813. if (ImGui::BeginDock("Scene View"
  814. , &_scene_view._open
  815. , ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse)
  816. )
  817. {
  818. // Draw toolbar
  819. ImGui::BeginGroup();
  820. if (ImGui::ImageButton((void*)(uintptr_t)tool_place_texture->handle.idx, ImVec2(16, 16)))
  821. {
  822. _tool_type = tool::ToolType::PLACE;
  823. tool_send_state();
  824. }
  825. if (ImGui::ImageButton((void*)(uintptr_t)tool_move_texture->handle.idx, ImVec2(16, 16)))
  826. {
  827. _tool_type = tool::ToolType::MOVE;
  828. tool_send_state();
  829. }
  830. if (ImGui::ImageButton((void*)(uintptr_t)tool_rotate_texture->handle.idx, ImVec2(16, 16)))
  831. {
  832. _tool_type = tool::ToolType::ROTATE;
  833. tool_send_state();
  834. }
  835. if (ImGui::ImageButton((void*)(uintptr_t)tool_scale_texture->handle.idx, ImVec2(16, 16)))
  836. {
  837. _tool_type = tool::ToolType::SCALE;
  838. tool_send_state();
  839. }
  840. ImGui::Separator();
  841. if (ImGui::ImageButton((void*)(uintptr_t)axis_local_texture->handle.idx, ImVec2(16, 16)))
  842. {
  843. _reference_system = tool::ReferenceSystem::LOCAL;
  844. tool_send_state();
  845. }
  846. if (ImGui::ImageButton((void*)(uintptr_t)axis_world_texture->handle.idx, ImVec2(16, 16)))
  847. {
  848. _reference_system = tool::ReferenceSystem::WORLD;
  849. tool_send_state();
  850. }
  851. ImGui::Separator();
  852. if (ImGui::ImageButton((void*)(uintptr_t)reference_world_texture->handle.idx, ImVec2(16, 16)))
  853. {
  854. _snap_mode = tool::SnapMode::RELATIVE;
  855. tool_send_state();
  856. }
  857. if (ImGui::ImageButton((void*)(uintptr_t)reference_local_texture->handle.idx, ImVec2(16, 16)))
  858. {
  859. _snap_mode = tool::SnapMode::ABSOLUTE;
  860. tool_send_state();
  861. }
  862. ImGui::Separator();
  863. if (ImGui::ImageButton((void*)(uintptr_t)snap_to_grid_texture->handle.idx, ImVec2(16, 16)))
  864. {
  865. _snap_to_grid = !_snap_to_grid;
  866. tool_send_state();
  867. }
  868. ImGui::EndGroup();
  869. // Draw scene view
  870. ImGui::SameLine();
  871. _scene_view.draw();
  872. }
  873. ImGui::EndDock();
  874. if (ImGui::BeginDock("Scene Tree", &_scene_tree._open))
  875. {
  876. _scene_tree.draw();
  877. }
  878. ImGui::EndDock();
  879. if (ImGui::BeginDock("Inspector", &_inspector._open))
  880. {
  881. _inspector.draw();
  882. }
  883. ImGui::EndDock();
  884. if (ImGui::BeginDock("Console", &_console._open, ImGuiWindowFlags_NoScrollbar))
  885. {
  886. console_draw(_console);
  887. }
  888. ImGui::EndDock();
  889. if (ImGui::BeginDock("Animator", &_animator._open))
  890. {
  891. _animator.draw();
  892. }
  893. ImGui::EndDock();
  894. // _sprite_importer.draw();
  895. imgui_end_frame();
  896. }
  897. void send_command(StringStream& ss)
  898. {
  899. TempAllocator4096 ta;
  900. StringStream out(ta);
  901. out << "{\"type\":\"script\",\"script\":\"";
  902. out << string_stream::c_str(ss);
  903. out << "\"}";
  904. const char* cmd = string_stream::c_str(out);
  905. const u32 size = strlen32(cmd);
  906. _console._client.write(&size, sizeof(u32));
  907. _console._client.write(cmd, size);
  908. }
  909. void tool_send_state()
  910. {
  911. TempAllocator256 ta;
  912. StringStream ss(ta);
  913. tool::set_grid_size(ss, _grid_size);
  914. tool::set_rotation_snap(ss, _rotation_snap);
  915. tool::enable_show_grid(ss, _show_grid);
  916. tool::enable_snap_to_grid(ss, _snap_to_grid);
  917. tool::enable_debug_render_world(ss, _debug_render_world);
  918. tool::enable_debug_physics_world(ss, _debug_physics_world);
  919. tool::set_tool_type(ss, _tool_type);
  920. tool::set_snap_mode(ss, _snap_mode);
  921. tool::set_reference_system(ss, _reference_system);
  922. send_command(ss);
  923. }
  924. void format_time(uint64_t time, char* str, size_t size)
  925. {
  926. #if CROWN_PLATFORM_WINDOWS
  927. // SYSTEMTIME st;
  928. // FileTimeToSystemTime(&time, &st);
  929. // sprintf(str, "%d/%d/%d %d:%d"
  930. // , st.wDay
  931. // , st.wMonth
  932. // , st.wYear
  933. // , st.wHour
  934. // , st.wMinute);
  935. #else
  936. struct tm lt;
  937. localtime_r((time_t*)&time, &lt);
  938. strftime(str, size, "%d/%m/%Y %H:%M", &lt);
  939. #endif
  940. }
  941. void main_menu_bar()
  942. {
  943. // Main Menu
  944. if (ImGui::BeginMainMenuBar())
  945. {
  946. if (ImGui::BeginMenu("File"))
  947. {
  948. if (ImGui::MenuItem("New"))
  949. {
  950. }
  951. if (ImGui::MenuItem("Open", "Ctrl+O"))
  952. {
  953. nfdchar_t *out_path = NULL;
  954. nfdresult_t result = NFD_OpenDialog(NULL, NULL, &out_path);
  955. if ( result == NFD_OKAY )
  956. {
  957. logi(LEVEL_EDITOR, "Success!");
  958. logi(LEVEL_EDITOR, out_path);
  959. free(out_path);
  960. }
  961. else if ( result == NFD_CANCEL )
  962. {
  963. logi(LEVEL_EDITOR, "User pressed cancel.");
  964. }
  965. else
  966. {
  967. loge(LEVEL_EDITOR, "Error: %s\n", NFD_GetError());
  968. }
  969. }
  970. if (ImGui::MenuItem("Save", "Ctrl+S"))
  971. {
  972. }
  973. if (ImGui::MenuItem("Save As..."))
  974. {
  975. }
  976. ImGui::Separator();
  977. if (ImGui::MenuItem("Quit", "Ctrl+Q", false, true))
  978. {
  979. TempAllocator64 ta;
  980. StringStream ss(ta);
  981. tool::device_quit(ss);
  982. send_command(ss);
  983. }
  984. ImGui::EndMenu();
  985. }
  986. if (ImGui::BeginMenu("Edit"))
  987. {
  988. if (ImGui::MenuItem("Undo", "Ctrl+Z")) {}
  989. if (ImGui::MenuItem("Redo", "Ctrl+Y")) {}
  990. ImGui::EndMenu();
  991. }
  992. if (ImGui::BeginMenu("Create"))
  993. {
  994. TempAllocator256 ta;
  995. StringStream ss(ta);
  996. if (ImGui::BeginMenu("Primitives"))
  997. {
  998. if (ImGui::MenuItem("Cube", NULL, false, true))
  999. {
  1000. _tool_type = tool::ToolType::PLACE;
  1001. tool_send_state();
  1002. tool::set_placeable(ss, "unit", "core/units/primitives/cube");
  1003. send_command(ss);
  1004. }
  1005. if (ImGui::MenuItem("Sphere"))
  1006. {
  1007. _tool_type = tool::ToolType::PLACE;
  1008. tool_send_state();
  1009. tool::set_placeable(ss, "unit", "core/units/primitives/sphere");
  1010. send_command(ss);
  1011. }
  1012. if (ImGui::MenuItem("Cone"))
  1013. {
  1014. _tool_type = tool::ToolType::PLACE;
  1015. tool_send_state();
  1016. tool::set_placeable(ss, "unit", "core/units/primitives/cone");
  1017. send_command(ss);
  1018. }
  1019. if (ImGui::MenuItem("Cylinder"))
  1020. {
  1021. _tool_type = tool::ToolType::PLACE;
  1022. tool_send_state();
  1023. tool::set_placeable(ss, "unit", "core/units/primitives/cylinder");
  1024. send_command(ss);
  1025. }
  1026. if (ImGui::MenuItem("Plane"))
  1027. {
  1028. _tool_type = tool::ToolType::PLACE;
  1029. tool_send_state();
  1030. tool::set_placeable(ss, "unit", "core/units/primitives/plane");
  1031. send_command(ss);
  1032. }
  1033. ImGui::EndMenu();
  1034. }
  1035. if (ImGui::MenuItem("Camera"))
  1036. {
  1037. _tool_type = tool::ToolType::PLACE;
  1038. tool_send_state();
  1039. tool::set_placeable(ss, "unit", "core/units/camera");
  1040. send_command(ss);
  1041. }
  1042. if (ImGui::MenuItem("Light"))
  1043. {
  1044. _tool_type = tool::ToolType::PLACE;
  1045. tool_send_state();
  1046. tool::set_placeable(ss, "unit", "core/units/light");
  1047. send_command(ss);
  1048. }
  1049. if (ImGui::MenuItem("Sound"))
  1050. {
  1051. _tool_type = tool::ToolType::PLACE;
  1052. tool_send_state();
  1053. tool::set_placeable(ss, "sound", "core/units/camera");
  1054. send_command(ss);
  1055. }
  1056. ImGui::EndMenu();
  1057. }
  1058. if (ImGui::BeginMenu("Scene View"))
  1059. {
  1060. TempAllocator256 ta;
  1061. StringStream ss(ta);
  1062. if (ImGui::BeginMenu("Camera View"))
  1063. {
  1064. if (ImGui::MenuItem("Perspective"))
  1065. {
  1066. tool::camera_view_perspective(ss);
  1067. send_command(ss);
  1068. }
  1069. if (ImGui::MenuItem("Front"))
  1070. {
  1071. tool::camera_view_front(ss);
  1072. send_command(ss);
  1073. }
  1074. if (ImGui::MenuItem("Back"))
  1075. {
  1076. tool::camera_view_back(ss);
  1077. send_command(ss);
  1078. }
  1079. if (ImGui::MenuItem("Right"))
  1080. {
  1081. tool::camera_view_right(ss);
  1082. send_command(ss);
  1083. }
  1084. if (ImGui::MenuItem("Left"))
  1085. {
  1086. tool::camera_view_left(ss);
  1087. send_command(ss);
  1088. }
  1089. if (ImGui::MenuItem("Top"))
  1090. {
  1091. tool::camera_view_top(ss);
  1092. send_command(ss);
  1093. }
  1094. if (ImGui::MenuItem("Bottom"))
  1095. {
  1096. tool::camera_view_bottom(ss);
  1097. send_command(ss);
  1098. }
  1099. ImGui::EndMenu();
  1100. }
  1101. ImGui::Separator();
  1102. if (ImGui::MenuItem("Show Grid", NULL, _show_grid))
  1103. {
  1104. _show_grid = !_show_grid;
  1105. tool_send_state();
  1106. }
  1107. if (ImGui::SliderFloat("Grid Size", &_grid_size, 0.1f, 5.0f))
  1108. {
  1109. tool_send_state();
  1110. }
  1111. if (ImGui::SliderFloat("Snap Rot", &_rotation_snap, 1, 180))
  1112. {
  1113. tool_send_state();
  1114. }
  1115. ImGui::EndMenu();
  1116. }
  1117. if (ImGui::BeginMenu("Windows"))
  1118. {
  1119. if (ImGui::MenuItem("Scene"))
  1120. {
  1121. _scene_view._open = true;
  1122. }
  1123. if (ImGui::MenuItem("Scene Tree"))
  1124. {
  1125. _scene_tree._open = true;
  1126. }
  1127. if (ImGui::MenuItem("Inspector"))
  1128. {
  1129. _inspector._open = true;
  1130. }
  1131. if (ImGui::MenuItem("Console"))
  1132. {
  1133. _console._open = true;
  1134. }
  1135. if (ImGui::MenuItem("Animator"))
  1136. {
  1137. _animator._open = true;
  1138. }
  1139. ImGui::EndMenu();
  1140. }
  1141. if (ImGui::BeginMenu("Help"))
  1142. {
  1143. ImGui::MenuItem("About", "");
  1144. ImGui::EndMenu();
  1145. }
  1146. _main_menu_pos = ImGui::GetWindowPos();
  1147. _main_menu_size = ImGui::GetWindowSize();
  1148. ImGui::EndMainMenuBar();
  1149. }
  1150. }
  1151. };
  1152. LevelEditor* s_editor;
  1153. void tool_init()
  1154. {
  1155. const DeviceOptions& opt = device()->_device_options;
  1156. s_editor = CE_NEW(default_allocator(), LevelEditor)(opt._source_dir);
  1157. }
  1158. void tool_update(f32 dt)
  1159. {
  1160. s_editor->update(dt);
  1161. }
  1162. void tool_shutdown()
  1163. {
  1164. CE_DELETE(default_allocator(), s_editor);
  1165. }
  1166. extern bool next_event(OsEvent& ev);
  1167. bool tool_process_events()
  1168. {
  1169. ImGuiIO& io = ImGui::GetIO();
  1170. bool exit = false;
  1171. bool reset = false;
  1172. TempAllocator4096 ta;
  1173. StringStream ss(ta);
  1174. OsEvent event;
  1175. while (next_event(event))
  1176. {
  1177. if (event.type == OsEventType::NONE)
  1178. continue;
  1179. switch (event.type)
  1180. {
  1181. case OsEventType::BUTTON:
  1182. switch (event.button.device_id)
  1183. {
  1184. case crown::InputDeviceType::KEYBOARD:
  1185. io.KeyCtrl = ((event.button.button_num == crown::KeyboardButton::CTRL_LEFT)
  1186. || (event.button.button_num == crown::KeyboardButton::CTRL_RIGHT)) && event.button.pressed;
  1187. io.KeyShift = ((event.button.button_num == crown::KeyboardButton::SHIFT_LEFT)
  1188. || (event.button.button_num == crown::KeyboardButton::SHIFT_RIGHT)) && event.button.pressed;
  1189. io.KeyAlt = ((event.button.button_num == crown::KeyboardButton::ALT_LEFT)
  1190. || (event.button.button_num == crown::KeyboardButton::ALT_RIGHT)) && event.button.pressed;
  1191. io.KeySuper = ((event.button.button_num == crown::KeyboardButton::SUPER_LEFT)
  1192. || (event.button.button_num == crown::KeyboardButton::SUPER_RIGHT)) && event.button.pressed;
  1193. io.KeysDown[event.button.button_num] = event.button.pressed;
  1194. if (!io.WantCaptureKeyboard)
  1195. {
  1196. if (event.button.pressed)
  1197. {
  1198. if (event.button.button_num == crown::KeyboardButton::W)
  1199. tool::key_down(ss, "w");
  1200. if (event.button.button_num == crown::KeyboardButton::A)
  1201. tool::key_down(ss, "a");
  1202. if (event.button.button_num == crown::KeyboardButton::S)
  1203. tool::key_down(ss, "s");
  1204. if (event.button.button_num == crown::KeyboardButton::D)
  1205. tool::key_down(ss, "d");
  1206. if (event.button.button_num == crown::KeyboardButton::CTRL_LEFT)
  1207. tool::key_down(ss, "ctrl_left");
  1208. if (event.button.button_num == crown::KeyboardButton::SHIFT_LEFT)
  1209. tool::key_down(ss, "shift_left");
  1210. if (event.button.button_num == crown::KeyboardButton::ALT_LEFT)
  1211. tool::key_down(ss, "alt_left");
  1212. }
  1213. else
  1214. {
  1215. if (event.button.button_num == crown::KeyboardButton::W)
  1216. tool::key_up(ss, "w");
  1217. if (event.button.button_num == crown::KeyboardButton::A)
  1218. tool::key_up(ss, "a");
  1219. if (event.button.button_num == crown::KeyboardButton::S)
  1220. tool::key_up(ss, "s");
  1221. if (event.button.button_num == crown::KeyboardButton::D)
  1222. tool::key_up(ss, "d");
  1223. if (event.button.button_num == crown::KeyboardButton::CTRL_LEFT)
  1224. tool::key_up(ss, "ctrl_left");
  1225. if (event.button.button_num == crown::KeyboardButton::SHIFT_LEFT)
  1226. tool::key_up(ss, "shift_left");
  1227. if (event.button.button_num == crown::KeyboardButton::ALT_LEFT)
  1228. tool::key_up(ss, "alt_left");
  1229. }
  1230. }
  1231. break;
  1232. case crown::InputDeviceType::MOUSE:
  1233. io.MouseDown[0] = (event.button.button_num == crown::MouseButton::LEFT) && event.button.pressed;
  1234. io.MouseDown[1] = (event.button.button_num == crown::MouseButton::RIGHT) && event.button.pressed;
  1235. io.MouseDown[2] = (event.button.button_num == crown::MouseButton::MIDDLE) && event.button.pressed;
  1236. if (!io.WantCaptureMouse)
  1237. {
  1238. ImVec2& cursor = s_editor->_scene_view._cursor;
  1239. cursor.x = io.MousePos.x - s_editor->_scene_view._origin.x;
  1240. cursor.y = io.MousePos.y - s_editor->_scene_view._origin.y;
  1241. tool::set_mouse_state(ss
  1242. , cursor.x
  1243. , cursor.y
  1244. , io.MouseDown[0]
  1245. , io.MouseDown[2]
  1246. , io.MouseDown[1]
  1247. );
  1248. if (event.button.button_num == crown::MouseButton::LEFT)
  1249. {
  1250. if (event.button.pressed)
  1251. tool::mouse_down(ss, cursor.x, cursor.y);
  1252. else
  1253. tool::mouse_up(ss, cursor.x, cursor.y);
  1254. }
  1255. }
  1256. break;
  1257. }
  1258. break;
  1259. case OsEventType::AXIS:
  1260. switch(event.axis.device_id)
  1261. {
  1262. case InputDeviceType::MOUSE:
  1263. switch(event.axis.axis_num)
  1264. {
  1265. case crown::MouseAxis::CURSOR:
  1266. io.MousePos = ImVec2(event.axis.axis_x, event.axis.axis_y);
  1267. if (!io.WantCaptureMouse)
  1268. {
  1269. ImVec2& cursor = s_editor->_scene_view._cursor;
  1270. cursor.x = io.MousePos.x - s_editor->_scene_view._origin.x;
  1271. cursor.y = io.MousePos.y - s_editor->_scene_view._origin.y;
  1272. tool::mouse_move(ss, cursor.x, cursor.y);
  1273. }
  1274. break;
  1275. case crown::MouseAxis::WHEEL:
  1276. io.MouseWheel += event.axis.axis_y;
  1277. if (!io.WantCaptureMouse)
  1278. tool::mouse_wheel(ss, io.MouseWheel);
  1279. break;
  1280. }
  1281. }
  1282. break;
  1283. case OsEventType::TEXT:
  1284. io.AddInputCharactersUTF8((const char*) event.text.utf8);
  1285. break;
  1286. case OsEventType::RESOLUTION:
  1287. _width = event.resolution.width;
  1288. _height = event.resolution.height;
  1289. reset = true;
  1290. break;
  1291. case OsEventType::EXIT:
  1292. exit = true;
  1293. break;
  1294. default:
  1295. break;
  1296. }
  1297. }
  1298. s_editor->send_command(ss);
  1299. bool vsync = true;
  1300. if (reset)
  1301. bgfx::reset(_width, _height, (vsync ? BGFX_RESET_VSYNC : BGFX_RESET_NONE));
  1302. return exit;
  1303. }
  1304. } // namespace crown
  1305. #endif // CROWN_TOOLS