08_Decals.as 12 KB

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