08_Decals.as 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. // Decals example.
  2. // This sample demonstrates:
  3. // - Performing a raycast to the octree and adding a decal to the hit location
  4. // - Defining a Cursor UI element which stays inside the window and can be shown/hidden
  5. // - Marking suitable (large) objects as occluders for occlusion culling
  6. // - Displaying renderer debug geometry to see the effect of occlusion
  7. #include "Scripts/Utilities/Sample.as"
  8. Scene@ scene_;
  9. Node@ cameraNode;
  10. float yaw = 0.0f;
  11. float pitch = 0.0f;
  12. bool drawDebug = false;
  13. void Start()
  14. {
  15. // Execute the common startup for samples
  16. SampleStart();
  17. // Create the scene content
  18. CreateScene();
  19. // Create the UI content
  20. CreateUI();
  21. // Setup the viewport for displaying the scene
  22. SetupViewport();
  23. // Hook up to the frame update and render post-update events
  24. SubscribeToEvents();
  25. }
  26. void CreateScene()
  27. {
  28. scene_ = Scene();
  29. // Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
  30. // Also create a DebugRenderer component so that we can draw debug geometry
  31. scene_.CreateComponent("Octree");
  32. scene_.CreateComponent("DebugRenderer");
  33. // Create scene node & StaticModel component for showing a static plane
  34. Node@ planeNode = scene_.CreateChild("Plane");
  35. planeNode.scale = Vector3(100.0f, 1.0f, 100.0f);
  36. StaticModel@ planeObject = planeNode.CreateComponent("StaticModel");
  37. planeObject.model = cache.GetResource("Model", "Models/Plane.mdl");
  38. planeObject.material = cache.GetResource("Material", "Materials/StoneTiled.xml");
  39. // Create a Zone component for ambient lighting & fog control
  40. Node@ zoneNode = scene_.CreateChild("Zone");
  41. Zone@ zone = zoneNode.CreateComponent("Zone");
  42. zone.boundingBox = BoundingBox(-1000.0f, 1000.0f);
  43. zone.ambientColor = Color(0.15f, 0.15f, 0.15f);
  44. zone.fogColor = Color(0.5f, 0.5f, 0.7f);
  45. zone.fogStart = 100.0f;
  46. zone.fogEnd = 300.0f;
  47. // Create a directional light to the world. Enable cascaded shadows on it
  48. Node@ lightNode = scene_.CreateChild("DirectionalLight");
  49. lightNode.direction = Vector3(0.6f, -1.0f, 0.8f);
  50. Light@ light = lightNode.CreateComponent("Light");
  51. light.lightType = LIGHT_DIRECTIONAL;
  52. light.castShadows = true;
  53. light.shadowBias = BiasParameters(0.00025f, 0.5f);
  54. // Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
  55. light.shadowCascade = CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f);
  56. // Create some mushrooms
  57. const uint NUM_MUSHROOMS = 240;
  58. for (uint i = 0; i < NUM_MUSHROOMS; ++i)
  59. {
  60. Node@ mushroomNode = scene_.CreateChild("Mushroom");
  61. mushroomNode.position = Vector3(Random(90.0f) - 45.0f, 0.0f, Random(90.0f) - 45.0f);
  62. mushroomNode.rotation = Quaternion(0.0f, Random(360.0f), 0.0f);
  63. mushroomNode.SetScale(0.5f + Random(2.0f));
  64. StaticModel@ mushroomObject = mushroomNode.CreateComponent("StaticModel");
  65. mushroomObject.model = cache.GetResource("Model", "Models/Mushroom.mdl");
  66. mushroomObject.material = cache.GetResource("Material", "Materials/Mushroom.xml");
  67. mushroomObject.castShadows = true;
  68. }
  69. // Create randomly sized boxes. If boxes are big enough, make them occluders. Occluders will be software rasterized before
  70. // rendering to a low-resolution depth-only buffer to test the objects in the view frustum for visibility
  71. const uint NUM_BOXES = 20;
  72. for (uint i = 0; i < NUM_BOXES; ++i)
  73. {
  74. Node@ boxNode = scene_.CreateChild("Box");
  75. float size = 1.0f + Random(10.0f);
  76. boxNode.position = Vector3(Random(80.0f) - 40.0f, size * 0.5f, Random(80.0f) - 40.0f);
  77. boxNode.SetScale(size);
  78. StaticModel@ boxObject = boxNode.CreateComponent("StaticModel");
  79. boxObject.model = cache.GetResource("Model", "Models/Box.mdl");
  80. boxObject.material = cache.GetResource("Material", "Materials/Stone.xml");
  81. boxObject.castShadows = true;
  82. if (size >= 3.0f)
  83. boxObject.occluder = true;
  84. }
  85. // Create the camera. Limit far clip distance to match the fog
  86. cameraNode = scene_.CreateChild("Camera");
  87. Camera@ camera = cameraNode.CreateComponent("Camera");
  88. camera.farClip = 300.0f;
  89. // Set an initial position for the camera scene node above the plane
  90. cameraNode.position = Vector3(0.0f, 5.0f, 0.0f);
  91. }
  92. void CreateUI()
  93. {
  94. // Create a Cursor UI element because we want to be able to hide and show it at will. When hidden, the mouse cursor will
  95. // control the camera, and when visible, it will point the raycast target
  96. XMLFile@ style = cache.GetResource("XMLFile", "UI/DefaultStyle.xml");
  97. Cursor@ cursor = Cursor();
  98. cursor.SetStyleAuto(style);
  99. ui.cursor = cursor;
  100. // Set starting position of the cursor at the rendering window center
  101. cursor.SetPosition(graphics.width / 2, graphics.height / 2);
  102. // Construct new Text object, set string to display and font to use
  103. Text@ instructionText = ui.root.CreateChild("Text");
  104. instructionText.text =
  105. "Use WASD keys to move\n"
  106. "LMB to paint decals, RMB to rotate view\n"
  107. "Space to toggle debug geometry\n"
  108. "7 to toggle occlusion culling";
  109. instructionText.SetFont(cache.GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15);
  110. // The text has multiple rows. Center them in relation to each other
  111. instructionText.textAlignment = HA_CENTER;
  112. // Position the text relative to the screen center
  113. instructionText.horizontalAlignment = HA_CENTER;
  114. instructionText.verticalAlignment = VA_CENTER;
  115. instructionText.SetPosition(0, ui.root.height / 4);
  116. }
  117. void SetupViewport()
  118. {
  119. // Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
  120. Viewport@ viewport = Viewport(scene_, cameraNode.GetComponent("Camera"));
  121. renderer.viewports[0] = viewport;
  122. }
  123. void SubscribeToEvents()
  124. {
  125. // Subscribe HandleUpdate() function for processing update events
  126. SubscribeToEvent("Update", "HandleUpdate");
  127. // Subscribe HandlePostRenderUpdate() function for processing the post-render update event, during which we request
  128. // debug geometry
  129. SubscribeToEvent("PostRenderUpdate", "HandlePostRenderUpdate");
  130. }
  131. void MoveCamera(float timeStep)
  132. {
  133. // Right mouse button controls mouse cursor visibility: hide when pressed
  134. ui.cursor.visible = !input.mouseButtonDown[MOUSEB_RIGHT];
  135. // Do not move if the UI has a focused element (the console)
  136. if (ui.focusElement !is null)
  137. return;
  138. // Movement speed as world units per second
  139. const float MOVE_SPEED = 20.0f;
  140. // Mouse sensitivity as degrees per pixel
  141. const float MOUSE_SENSITIVITY = 0.1f;
  142. // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  143. // Only move the camera when the cursor is hidden
  144. if (!ui.cursor.visible)
  145. {
  146. IntVector2 mouseMove = input.mouseMove;
  147. yaw += MOUSE_SENSITIVITY * mouseMove.x;
  148. pitch += MOUSE_SENSITIVITY * mouseMove.y;
  149. pitch = Clamp(pitch, -90.0f, 90.0f);
  150. // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  151. cameraNode.rotation = Quaternion(pitch, yaw, 0.0f);
  152. }
  153. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  154. if (input.keyDown['W'])
  155. cameraNode.TranslateRelative(Vector3(0.0f, 0.0f, 1.0f) * MOVE_SPEED * timeStep);
  156. if (input.keyDown['S'])
  157. cameraNode.TranslateRelative(Vector3(0.0f, 0.0f, -1.0f) * MOVE_SPEED * timeStep);
  158. if (input.keyDown['A'])
  159. cameraNode.TranslateRelative(Vector3(-1.0f, 0.0f, 0.0f) * MOVE_SPEED * timeStep);
  160. if (input.keyDown['D'])
  161. cameraNode.TranslateRelative(Vector3(1.0f, 0.0f, 0.0f) * MOVE_SPEED * timeStep);
  162. // Toggle debug geometry with space
  163. if (input.keyPress[KEY_SPACE])
  164. drawDebug = !drawDebug;
  165. // Paint decal with the left mousebutton; cursor must be visible
  166. if (ui.cursor.visible && input.mouseButtonPress[MOUSEB_LEFT])
  167. PaintDecal();
  168. }
  169. void PaintDecal()
  170. {
  171. Vector3 hitPos;
  172. Drawable@ hitDrawable;
  173. if (Raycast(250.0f, hitPos, hitDrawable))
  174. {
  175. // Check if target scene node already has a DecalSet component. If not, create now
  176. Node@ targetNode = hitDrawable.node;
  177. DecalSet@ decal = targetNode.GetComponent("DecalSet");
  178. if (decal is null)
  179. {
  180. decal = targetNode.CreateComponent("DecalSet");
  181. decal.material = cache.GetResource("Material", "Materials/UrhoDecal.xml");
  182. }
  183. // Add a square decal to the decal set using the geometry of the drawable that was hit, orient it to face the camera,
  184. // use full texture UV's (0,0) to (1,1). Note that if we create several decals to a large object (such as the ground
  185. // plane) over a large area using just one DecalSet component, the decals will all be culled as one unit. If that is
  186. // undesirable, it may be necessary to create more than one DecalSet based on the distance
  187. decal.AddDecal(hitDrawable, hitPos, cameraNode.rotation, 0.5f, 1.0f, 1.0f, Vector2(0.0f, 0.0f), Vector2(1.0f, 1.0f));
  188. }
  189. }
  190. bool Raycast(float maxDistance, Vector3& hitPos, Drawable@& hitDrawable)
  191. {
  192. hitDrawable = null;
  193. IntVector2 pos = ui.cursorPosition;
  194. // Check the cursor is visible and there is no UI element in front of the cursor
  195. if (!ui.cursor.visible || ui.GetElementAt(pos, true) !is null)
  196. return false;
  197. Camera@ camera = cameraNode.GetComponent("Camera");
  198. Ray cameraRay = camera.GetScreenRay(float(pos.x) / graphics.width, float(pos.y) / graphics.height);
  199. // Pick only geometry objects, not eg. zones or lights, only get the first (closest) hit
  200. // Note the convenience accessor to scene's Octree component
  201. RayQueryResult result = scene_.octree.RaycastSingle(cameraRay, RAY_TRIANGLE, maxDistance, DRAWABLE_GEOMETRY);
  202. if (result.drawable !is null)
  203. {
  204. hitPos = result.position;
  205. hitDrawable = result.drawable;
  206. return true;
  207. }
  208. return false;
  209. }
  210. void HandleUpdate(StringHash eventType, VariantMap& eventData)
  211. {
  212. // Take the frame time step, which is stored as a float
  213. float timeStep = eventData["TimeStep"].GetFloat();
  214. // Move the camera, scale movement with time step
  215. MoveCamera(timeStep);
  216. }
  217. void HandlePostRenderUpdate(StringHash eventType, VariantMap& eventData)
  218. {
  219. // If draw debug mode is enabled, draw viewport debug geometry. Disable depth test so that we can see the effect of occlusion
  220. if (drawDebug)
  221. renderer.DrawDebugGeometry(false);
  222. }