08_Decals.lua 11 KB

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