sandbox.cpp 25 KB

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