sandbox.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  1. 
  2. /*
  3. An application for previewing tiles and sprites together for potential games.
  4. If you design game assets separatelly, they will often look much worse when you put them together.
  5. Unmatching scale, shadows, colors, themes, et cetera...
  6. That's why it's important to preview your assets together as early as possible while still designing them.
  7. */
  8. /*
  9. BUGS:
  10. * The mouse move is repeated automatically when changing pixel scale, but the same doesn't work for when the window itself moved.
  11. How can a new mouse-move event be triggered from the current location when toggling full-screen so that the window itself moves?
  12. * Tiles placed at different heights do not have synchronized rounding between each other.
  13. Try to round the Y offset separatelly from the XZ location's screen coordinate.
  14. 3D BUGS:
  15. DRAWN:
  16. * There's an ugly seam from not connecting the other side of cylinder fields.
  17. Probably haven't created any extra triangle strip on that region.
  18. SHADOWS:
  19. * The bounding box of shadows differs from the visible pixel's bound in the config file.
  20. Expand the bound using the shadow model's points to include everything safely.
  21. * When eroding the dimensions of shadow shapes, there's gaps when placing tiles next to each other
  22. Can erosion and bias be applied in each shadow map while sampling or as a separate pass?
  23. Is this much bias even needed when using bilinear interpolation in depth divided space directly from the texture?
  24. * There's no way to close the gaps on height fields without using black pixels to create zero offset at the ends.
  25. This creates open holes when not using zero clipping.
  26. An optional triangle patch can be added along the open sides. (all for planes and excluding sides for cylinders)
  27. VISUALS:
  28. * Make a directed light source that casts light and shadows from a fixed direction but can fade like a point light.
  29. Useful for street-lights and sky-lights that want to avoid normalizing and projecting light directions per pixel.
  30. Can be used both with and without casting shadows.
  31. Can use intensity maps to project patterns within the square.
  32. A rough 2D convex hull from the image can be generated for a tighter light frustum.
  33. Otherwise, one can just apply a round mask and use a cone.
  34. * Projective background decals.
  35. Used like passive lights but drawing to the diffuse layer and ignoring dynamic sprites.
  36. Will only be drawn when updating passive blocks or adding to existing background blocks.
  37. A 3D transform defines where the decal is placed like a cube in world space.
  38. The near and far clipping can use a fading threshold to allow placing explosion decals without creating hard seams.
  39. New sprites added after a decal should not be affected by an old sprite.
  40. How can this be solved without resorting to dangerous polymorphism.
  41. Allow defining decals locally for each level by loading their images from a temporary image pool of level specific content.
  42. This can be used to write instructions specific to a certain mission and give a unique look to an otherwise generic level.
  43. Billboards and signs can also be possible to reuse with custom images and text.
  44. * Allow having many high-quality light sources by introducing fully passive lights.
  45. Useful for indirect light from the sky and general ambient light.
  46. The background stores RGBA light buffers to make passive lights super cheap.
  47. This light will mostly store soft light, so shadows from dynamic sprites will
  48. draw blob shadows as decals on the background before drawing themselves.
  49. This will give an illusion of dynamic ambient occlusion,
  50. especially if surface normals affect the intensity using custom shadow decals.
  51. Dynamic sprites overwrites with their own interpretation of the passive light.
  52. Dynamic lights add to the light buffer without caring about what's background and what's dynamic.
  53. A quad-tree stencil will remember which areas have foreground drawn on top of the background.
  54. This stencil is later used for a pass of dynamic light from passive light sources using stored primary cubemaps.
  55. The background will divide the light using multiple cube-maps for the same illumination by adding offset varitations in the light sampling function.
  56. * Make a reusable system for distance adaptive light sources.
  57. The same illumination filter should take multiple cubemaps rendered from slightly different locations.
  58. These can be interleaved into a unified packed look-up if the distortion
  59. of looking it up from the same offset is compensated for somehow.
  60. The first cubemap will be persistent and used later for dynamic light.
  61. The later cubemaps will be temporary when generating the background's softer light.
  62. OPTIMIZE:
  63. * Make a tile based light culling.
  64. The background has pre-stored minimum and maximum depth for tiles of 32² pixel blocks.
  65. The screen has 64² pixel min-max blocks reading from 4-9 background blocks.
  66. Drawing active sprites will write using its own 32² max blocks to the screens depth bound.
  67. Minimum is kept because drawing can only increase and rarely covers whole areas.
  68. Each 64² block on the screen then generates a tilted cube hull of the region's visible pixels.
  69. This tells which light frustums are seen and which parts of their cube maps have to be rendered.
  70. After rendering the seen shadow-map viewports, blocks including the same set of light sources are merged horizontally.
  71. A vertical split of blocks is used for multi-threading.
  72. Example light count for square light regions (real regions will be shaped by 3D light frustums intersecting visible pixel bounds)
  73. 0--01----10-0
  74. 1--12-21-10-0
  75. 1--12-21-10-0
  76. 1-----10----0
  77. * Create a debug feature in spriteAPI for displaying the octree using lines.
  78. One color for the owned space and another for the sprite bounding boxes.
  79. Pressing a certain button in Sandbox should toggle the debug drawing to allow asserting that the tree is well balanced for the level's size.
  80. LATER:
  81. * Make a ground layer using height and blend maps for outdoor scenes.
  82. Each tile region will decide if ground should be drawn there.
  83. Disabling the ground on a tile will look at the main tile replacing the ground for walking heights.
  84. Grass and small stones will use a separate system, because background sprites do not adapt to the ground height.
  85. These can be generated from deterministic random values compared against blend maps to save space.
  86. Additional natural sprites can be added one by one at specific locations.
  87. * When loading the frames from an atlas, crop the images further and apply separate offsets per frame.
  88. This will significantly improve rendering speed for 8 direction sprites.
  89. */
  90. #include "../../DFPSR/includeFramework.h"
  91. #include "../SpriteEngine/spriteAPI.h"
  92. #include "../SpriteEngine/importer.h"
  93. #include <cassert>
  94. #include <limits>
  95. using namespace dsr;
  96. static const String mediaPath = file_combinePaths(file_getApplicationFolder(), U"media");
  97. static const String imagePath = file_combinePaths(mediaPath, U"images");
  98. static const String modelPath = file_combinePaths(mediaPath, U"models");
  99. // Variables
  100. static bool running = true;
  101. static bool updateImage = true;
  102. static IVector2D mousePos;
  103. static bool panorate = false;
  104. static bool tileAlign = false;
  105. static int debugView = 0;
  106. static int mouseLights = 1;
  107. static int random(const int minimum, const int maximum) {
  108. if (maximum > minimum) {
  109. return (std::rand() % (maximum + 1 - minimum)) + minimum;
  110. } else {
  111. return minimum;
  112. }
  113. }
  114. // Variables
  115. static int brushHeight = 0; // In mini-tile units
  116. static SpriteInstance spriteBrush(0, ortho_dir0, IVector3D(), true);
  117. static bool placingModel = false; // True when left mouse button is pressed and the direction is being assigned
  118. static ModelInstance modelBrush(0, Transform3D());
  119. static const int brushStep = ortho_miniUnitsPerTile / 32;
  120. static int pressing_left = 0, pressing_right = 0, pressing_up = 0, pressing_down = 0, pressing_delete = 0;
  121. static IVector2D cameraMovement;
  122. static const int cameraSpeed = 1;
  123. // World
  124. static SpriteWorld world;
  125. bool ambientLight = true;
  126. bool castShadows = true;
  127. // GUI
  128. static Window window;
  129. Component mainPanel, toolPanel, spritePanel, spriteList, modelPanel, modelList;
  130. static int overlayMode = 2;
  131. static const int OverlayMode_None = 0;
  132. static const int OverlayMode_Profiling = 1;
  133. static const int OverlayMode_Tools = 2;
  134. static const int OverlayModeCount = 3;
  135. static int tool = 0;
  136. static const int Tool_PlaceSprite = 0;
  137. static const int Tool_PlaceModel = 1;
  138. static const int ToolCount = 2;
  139. void updateOverlay() {
  140. component_setProperty_integer(toolPanel, U"Visible", overlayMode == OverlayMode_Tools);
  141. component_setProperty_integer(spritePanel, U"Visible", tool == Tool_PlaceSprite);
  142. component_setProperty_integer(modelPanel, U"Visible", tool == Tool_PlaceModel);
  143. }
  144. void loadSprite(const ReadableString& name) {
  145. spriteWorld_loadSpriteTypeFromFile(imagePath, name);
  146. component_call(spriteList, U"PushElement", name);
  147. component_setProperty_integer(spriteList, U"SelectedIndex", 0);
  148. }
  149. void loadModel(const ReadableString& name, const ReadableString& visibleName, const ReadableString& shadowName) {
  150. spriteWorld_loadModelTypeFromFile(modelPath, visibleName, shadowName);
  151. component_call(modelList, U"PushElement", name);
  152. component_setProperty_integer(modelList, U"SelectedIndex", 0);
  153. }
  154. void sandbox_main() {
  155. // Create the world
  156. world = spriteWorld_create(OrthoSystem(string_load(file_combinePaths(mediaPath, U"Ortho.ini"))), 256);
  157. // Create a window
  158. String title = U"David Piuva's Software Renderer - Graphics sandbox";
  159. window = window_create(title, 1600, 900);
  160. //window = window_create_fullscreen(title);
  161. // Load an interface to the window
  162. window_loadInterfaceFromFile(window, file_combinePaths(mediaPath, U"interface.lof"));
  163. // Tell the application to terminate when the window is closed
  164. window_setCloseEvent(window, []() {
  165. running = false;
  166. });
  167. // Get direct window events
  168. window_setMouseEvent(window, [](const MouseEvent& event) {
  169. if (event.mouseEventType == MouseEventType::MouseMove) {
  170. if (panorate) {
  171. // Move the camera in exact pixels
  172. spriteWorld_moveCameraInPixels(world, mousePos - event.position);
  173. }
  174. mousePos = event.position;
  175. }
  176. });
  177. window_setKeyboardEvent(window, [](const KeyboardEvent& event) {
  178. DsrKey key = event.dsrKey;
  179. if (event.keyboardEventType == KeyboardEventType::KeyDown) {
  180. if (key == DsrKey_V) {
  181. debugView = 0;
  182. } else if (key == DsrKey_B) {
  183. debugView = 1;
  184. } else if (key == DsrKey_N) {
  185. debugView = 2;
  186. } else if (key == DsrKey_M) {
  187. debugView = 3;
  188. } else if (key == DsrKey_L) {
  189. debugView = 4;
  190. } else if (key >= DsrKey_1 && key <= DsrKey_9) {
  191. window_setPixelScale(window, key - DsrKey_0);
  192. } else if (key == DsrKey_R) {
  193. ambientLight = !ambientLight;
  194. } else if (key == DsrKey_T) {
  195. tileAlign = !tileAlign;
  196. } else if (key == DsrKey_Y) {
  197. castShadows = !castShadows;
  198. } else if (key == DsrKey_F) {
  199. overlayMode = (overlayMode + 1) % OverlayModeCount;
  200. updateOverlay();
  201. } else if (key == DsrKey_K) {
  202. mouseLights = (mouseLights + 1) % 5;
  203. } else if (key == DsrKey_C) {
  204. // Rotate the world clockwise using four camera angles
  205. spriteWorld_setCameraDirectionIndex(world, (spriteWorld_getCameraDirectionIndex(world) + 1) % 4);
  206. } else if (key == DsrKey_Z) {
  207. // Rotate the world counter-clockwise using four camera angles
  208. spriteWorld_setCameraDirectionIndex(world, (spriteWorld_getCameraDirectionIndex(world) + 3) % 4);
  209. } else if (key == DsrKey_F11) {
  210. // Toggle full-screen
  211. window_setFullScreen(window, !window_isFullScreen(window));
  212. } else if (key == DsrKey_Escape) {
  213. // Terminate safely after the next frame
  214. running = false;
  215. } else if (key == DsrKey_A) {
  216. pressing_left = 1;
  217. } else if (key == DsrKey_D) {
  218. pressing_right = 1;
  219. } else if (key == DsrKey_W) {
  220. pressing_up = 1;
  221. } else if (key == DsrKey_S) {
  222. pressing_down = 1;
  223. } else if (key == DsrKey_Delete) {
  224. pressing_delete = 1;
  225. } else if (key == DsrKey_LeftArrow) {
  226. spriteBrush.direction = correctDirection(spriteBrush.direction + ortho_dir270);
  227. } else if (key == DsrKey_RightArrow) {
  228. spriteBrush.direction = correctDirection(spriteBrush.direction + ortho_dir90);
  229. }
  230. } else if (event.keyboardEventType == KeyboardEventType::KeyUp) {
  231. if (key == DsrKey_A) {
  232. pressing_left = 0;
  233. } else if (key == DsrKey_D) {
  234. pressing_right = 0;
  235. } else if (key == DsrKey_W) {
  236. pressing_up = 0;
  237. } else if (key == DsrKey_S) {
  238. pressing_down = 0;
  239. } else if (key == DsrKey_Delete) {
  240. pressing_delete = 0;
  241. }
  242. }
  243. cameraMovement.x = pressing_right - pressing_left;
  244. cameraMovement.y = pressing_down - pressing_up;
  245. });
  246. // Get component handles and assign actions
  247. mainPanel = window_getRoot(window);
  248. component_setMouseDownEvent(mainPanel, [](const MouseEvent& event) {
  249. if (event.key == MouseKeyEnum::Left) {
  250. if (overlayMode == OverlayMode_Tools) {
  251. // Place a passive visual instance using the brush
  252. if (tool == Tool_PlaceSprite) {
  253. spriteWorld_addBackgroundSprite(world, spriteBrush);
  254. } else if (tool == Tool_PlaceModel) {
  255. placingModel = true;
  256. }
  257. }
  258. } else if (event.key == MouseKeyEnum::Right) {
  259. panorate = true;
  260. }
  261. });
  262. component_setMouseUpEvent(mainPanel, [](const MouseEvent& event) {
  263. if (event.key == MouseKeyEnum::Left) {
  264. if (overlayMode == OverlayMode_Tools) {
  265. // Place a passive visual instance using the brush
  266. if (tool == Tool_PlaceModel && placingModel) {
  267. spriteWorld_addBackgroundModel(world, modelBrush);
  268. placingModel = false;
  269. }
  270. }
  271. } else if (event.key == MouseKeyEnum::Right) {
  272. panorate = false;
  273. }
  274. });
  275. component_setMouseScrollEvent(mainPanel, [](const MouseEvent& event) {
  276. if (event.key == MouseKeyEnum::ScrollUp) {
  277. brushHeight += brushStep;
  278. } else if (event.key == MouseKeyEnum::ScrollDown) {
  279. brushHeight -= brushStep;
  280. }
  281. });
  282. toolPanel = window_findComponentByName(window, U"toolPanel");
  283. spritePanel = window_findComponentByName(window, U"spritePanel");
  284. modelPanel = window_findComponentByName(window, U"modelPanel");
  285. component_setPressedEvent(window_findComponentByName(window, U"spriteButton"), []() {
  286. tool = Tool_PlaceSprite;
  287. placingModel = false;
  288. updateOverlay();
  289. });
  290. component_setPressedEvent(window_findComponentByName(window, U"modelButton"), []() {
  291. tool = Tool_PlaceModel;
  292. placingModel = false;
  293. updateOverlay();
  294. });
  295. spriteList = window_findComponentByName(window, U"spriteList");
  296. component_setSelectEvent(spriteList, [](int64_t index) {
  297. spriteBrush.typeIndex = index;
  298. });
  299. modelList = window_findComponentByName(window, U"modelList");
  300. component_setSelectEvent(modelList, [](int64_t index) {
  301. modelBrush.typeIndex = index;
  302. });
  303. component_setPressedEvent(window_findComponentByName(window, U"leftButton"), []() {
  304. spriteBrush.direction = correctDirection(spriteBrush.direction + ortho_dir270);
  305. });
  306. component_setPressedEvent(window_findComponentByName(window, U"rightButton"), []() {
  307. spriteBrush.direction = correctDirection(spriteBrush.direction + ortho_dir90);
  308. });
  309. updateOverlay();
  310. // Create sprite types while listing their presence in the tool menu
  311. loadSprite(U"Floor");
  312. loadSprite(U"WoodenFloor");
  313. loadSprite(U"WoodenFence");
  314. loadSprite(U"WoodenBarrel");
  315. loadSprite(U"Pillar");
  316. loadSprite(U"Character_Mage");
  317. // Load models
  318. loadModel(U"Barrel", U"Barrel_LowDetail.ply", U"Barrel_Shadow.ply");
  319. loadModel(U"Mage", U"Character_Mage.ply", U"Character_Mage_Shadow.ply");
  320. // Create passive sprites
  321. for (int z = -300; z < 300; z++) {
  322. for (int x = -300; x < 300; x++) {
  323. // The bottom floor does not have to throw shadows
  324. spriteWorld_addBackgroundSprite(world, SpriteInstance(random(0, 1), random(0, 3) * ortho_dir90, IVector3D(x * ortho_miniUnitsPerTile, 0, z * ortho_miniUnitsPerTile), false));
  325. }
  326. }
  327. for (int z = -300; z < 300; z++) {
  328. for (int x = -300; x < 300; x++) {
  329. if (random(1, 4) == 1) {
  330. // Obstacles should cast shadows when possible
  331. spriteWorld_addBackgroundSprite(world, SpriteInstance(random(2, 4), random(0, 3) * ortho_dir90, IVector3D(x * ortho_miniUnitsPerTile, 0, z * ortho_miniUnitsPerTile), true));
  332. } else if (random(1, 20) == 1) {
  333. // Characters are just static geometry for testing
  334. spriteWorld_addBackgroundSprite(world, SpriteInstance(5, random(0, 7) * ortho_dir45, IVector3D(x * ortho_miniUnitsPerTile, 0, z * ortho_miniUnitsPerTile), true));
  335. }
  336. }
  337. }
  338. // Animation timing
  339. double frameStartTime = time_getSeconds();
  340. double secondsPerFrame = 0.0;
  341. double stepRemainder = 0.0;
  342. // Profiling
  343. double profileStartTime = time_getSeconds();
  344. int64_t profileFrameCount = 0; // Frames per second
  345. float profileFrameRate = 0.0f;
  346. double maxFrameTime = 0.0, lastMaxFrameTime = 0.0; // Peak per second
  347. while(running) {
  348. // Always render the image when profiling or moving the camera
  349. updateImage = overlayMode != OverlayMode_Tools || cameraMovement.x != 0 || cameraMovement.y != 0;
  350. // Execute actions
  351. if (window_executeEvents(window)) {
  352. // If editing, only update the image when the user did something
  353. updateImage = true;
  354. }
  355. if (updateImage) {
  356. // Request buffers after executing the events, to get newly allocated buffers after resize events
  357. AlignedImageRgbaU8 colorBuffer = window_getCanvas(window);
  358. // Calculate a number of whole millisecond ticks per frame
  359. // By performing game logic in multiples of msTicks, integer operations
  360. // can be scaled without comming to a full stop in high frame rates
  361. stepRemainder += secondsPerFrame * 1000.0;
  362. int msTicks = (int)stepRemainder;
  363. stepRemainder -= (double)msTicks;
  364. // Move the camera
  365. int cameraSteps = cameraSpeed * msTicks;
  366. // TODO: Find a way to move the camera using exact pixel offsets so that the camera's 3D location is only generating the 2D offset when rotating.
  367. // Can the sprite brush be guaranteed to come back to the mouse location after adding and subtracting the same 2D camera offset?
  368. // A new integer coordinate system along the ground might move half a pixel vertically and a full pixel sideways in the diagonal view.
  369. // Otherwise the approximation defeats the whole purpose of using whole integers in msTicks.
  370. spriteWorld_moveCameraInPixels(world, cameraMovement * cameraSteps);
  371. // Remove temporary visuals
  372. spriteWorld_clearTemporary(world);
  373. // Place the brush
  374. IVector3D mouseMiniPos = spriteWorld_findGroundAtPixel(world, colorBuffer, mousePos);
  375. FVector3D worldBrushPos = FVector3D(
  376. mouseMiniPos.x * ortho_tilesPerMiniUnit,
  377. brushHeight * ortho_tilesPerMiniUnit,
  378. mouseMiniPos.z * ortho_tilesPerMiniUnit
  379. );
  380. if (placingModel) {
  381. // Drag with the left mouse button around the selected location to select the angle
  382. // Scroll to another height to direct it towards another height
  383. modelBrush.location.transform = FMatrix3x3::makeAxisSystem(modelBrush.location.position - worldBrushPos, FVector3D(0.0f, 1.0f, 0.0f)); // TODO: An integer based rotation system for the brush
  384. } else {
  385. modelBrush.location = Transform3D(
  386. worldBrushPos,
  387. FMatrix3x3::makeAxisSystem(FVector3D(1.0f, 0.0f, 0.0f), FVector3D(0.0f, 1.0f, 0.0f)) // TODO: An integer based rotation system for the brush
  388. );
  389. }
  390. spriteBrush.location = IVector3D(mouseMiniPos.x, brushHeight, mouseMiniPos.z);
  391. if (tileAlign) {
  392. spriteBrush.location = ortho_roundToTile(spriteBrush.location);
  393. }
  394. // Repeated tools
  395. if (pressing_delete) {
  396. IVector3D searchMinBound = IVector3D(mouseMiniPos.x - ortho_miniUnitsPerTile / 2,-1000000, mouseMiniPos.z - ortho_miniUnitsPerTile / 2);
  397. IVector3D searchMaxBound = IVector3D(mouseMiniPos.x + ortho_miniUnitsPerTile / 2, 1000000, mouseMiniPos.z + ortho_miniUnitsPerTile / 2);
  398. spriteWorld_removeBackgroundSprites(world, searchMinBound, searchMaxBound);
  399. spriteWorld_removeBackgroundModels(world, searchMinBound, searchMaxBound);
  400. }
  401. // Illuminate the world using soft light from the sky
  402. if (ambientLight) {
  403. spriteWorld_createTemporary_directedLight(world, FVector3D(1.0f, -1.0f, 0.0f), 0.1f, ColorRgbI32(255, 255, 255));
  404. }
  405. // Create a temporary point light over the brush
  406. // Temporary light sources are easier to use for dynamic light because they don't need any handle
  407. if (mouseLights == 1) {
  408. spriteWorld_createTemporary_pointLight(world, ortho_miniToFloatingTile(spriteBrush.location) + FVector3D(0.0f, 0.5f, 0.0f), 4.0f, 4.0f, ColorRgbI32(128, 255, 128), castShadows);
  409. } else if (mouseLights == 2) {
  410. spriteWorld_createTemporary_pointLight(world, ortho_miniToFloatingTile(spriteBrush.location) + FVector3D(-2.0f, 0.5f, 1.0f), 4.0f, 2.0f, ColorRgbI32(255, 128, 128), castShadows);
  411. spriteWorld_createTemporary_pointLight(world, ortho_miniToFloatingTile(spriteBrush.location) + FVector3D(2.0f, 0.52f, -1.0f), 4.0f, 2.0f, ColorRgbI32(128, 255, 128), castShadows);
  412. } else if (mouseLights == 3) {
  413. spriteWorld_createTemporary_pointLight(world, ortho_miniToFloatingTile(spriteBrush.location) + FVector3D(-2.0f, 0.5f, 1.0f), 4.0f, 1.333f, ColorRgbI32(255, 128, 128), castShadows);
  414. spriteWorld_createTemporary_pointLight(world, ortho_miniToFloatingTile(spriteBrush.location) + FVector3D(1.0f, 0.51f, 2.0f), 4.0f, 1.333f, ColorRgbI32(128, 255, 128), castShadows);
  415. spriteWorld_createTemporary_pointLight(world, ortho_miniToFloatingTile(spriteBrush.location) + FVector3D(2.0f, 0.52f, -1.0f), 4.0f, 1.333f, ColorRgbI32(128, 128, 255), castShadows);
  416. } else if (mouseLights == 4) {
  417. spriteWorld_createTemporary_pointLight(world, ortho_miniToFloatingTile(spriteBrush.location) + FVector3D(-2.0f, 0.5f, 1.0f), 4.0f, 1.0f, ColorRgbI32(255, 128, 128), castShadows);
  418. spriteWorld_createTemporary_pointLight(world, ortho_miniToFloatingTile(spriteBrush.location) + FVector3D(1.0f, 0.51f, 2.0f), 4.0f, 1.0f, ColorRgbI32(128, 255, 128), castShadows);
  419. spriteWorld_createTemporary_pointLight(world, ortho_miniToFloatingTile(spriteBrush.location) + FVector3D(2.0f, 0.52f, -1.0f), 4.0f, 1.0f, ColorRgbI32(128, 128, 255), castShadows);
  420. spriteWorld_createTemporary_pointLight(world, ortho_miniToFloatingTile(spriteBrush.location) + FVector3D(-1.0f, 0.53f, -2.0f), 4.0f, 1.0f, ColorRgbI32(255, 255, 128), castShadows);
  421. }
  422. // Show the sprite brush
  423. if (overlayMode == OverlayMode_Tools) {
  424. if (tool == Tool_PlaceSprite && spriteWorld_getSpriteTypeCount() > 0) {
  425. spriteWorld_addTemporarySprite(world, spriteBrush);
  426. } else if (tool == Tool_PlaceModel && spriteWorld_getModelTypeCount() > 0) {
  427. spriteWorld_addTemporaryModel(world, modelBrush);
  428. }
  429. }
  430. // Draw the world
  431. spriteWorld_draw(world, colorBuffer);
  432. // Debug views (Slow but failsafe)
  433. if (debugView == 1) {
  434. draw_copy(colorBuffer, spriteWorld_getDiffuseBuffer(world));
  435. } else if (debugView == 2) {
  436. draw_copy(colorBuffer, spriteWorld_getNormalBuffer(world));
  437. } else if (debugView == 3) {
  438. AlignedImageF32 heightBuffer = spriteWorld_getHeightBuffer(world);
  439. for (int y = 0; y < image_getHeight(colorBuffer); y++) {
  440. for (int x = 0; x < image_getWidth(colorBuffer); x++) {
  441. float height = image_readPixel_clamp(heightBuffer, x, y) * 255.0f;
  442. if (height < 0.0f) { height = 0.0f; }
  443. if (height > 255.0f) { height = 255.0f; }
  444. image_writePixel(colorBuffer, x, y, ColorRgbaI32(height, 0, 0, 255));
  445. }
  446. }
  447. } else if (debugView == 4) {
  448. draw_copy(colorBuffer, spriteWorld_getLightBuffer(world));
  449. }
  450. // Overlays
  451. window_drawComponents(window);
  452. // Profiling mode
  453. if (overlayMode == OverlayMode_Profiling) {
  454. IVector2D writer = IVector2D(10, 10);
  455. font_printLine(colorBuffer, font_getDefault(), string_combine(U"FPS: ", profileFrameRate), writer, ColorRgbaI32(255, 255, 255, 255)); writer.y += 20;
  456. font_printLine(colorBuffer, font_getDefault(), string_combine(U"avg ms: ", 1000.0f / profileFrameRate), writer, ColorRgbaI32(255, 255, 255, 255)); writer.y += 20;
  457. font_printLine(colorBuffer, font_getDefault(), string_combine(U"max ms: ", 1000.0f * lastMaxFrameTime), writer, ColorRgbaI32(255, 255, 255, 255)); writer.y += 20;
  458. }
  459. window_showCanvas(window);
  460. } else {
  461. // If updateImage is false then just delay a bit while waiting for input
  462. time_sleepSeconds(0.01);
  463. }
  464. double newTime = time_getSeconds();
  465. secondsPerFrame = newTime - frameStartTime;
  466. frameStartTime = newTime;
  467. // Profiling
  468. if (secondsPerFrame > maxFrameTime) { maxFrameTime = secondsPerFrame; }
  469. profileFrameCount++;
  470. if (newTime > profileStartTime + 1.0) {
  471. double duration = newTime - profileStartTime;
  472. profileFrameRate = (double)profileFrameCount / duration;
  473. profileStartTime = newTime;
  474. profileFrameCount = 0;
  475. lastMaxFrameTime = maxFrameTime;
  476. maxFrameTime = 0.0;
  477. }
  478. }
  479. }