08_Decals.lua 12 KB

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