23_Water.lua 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. -- Water example.
  2. -- This sample demonstrates:
  3. -- - Creating a large plane to represent a water body for rendering
  4. -- - Setting up a second camera to render reflections on the water surface
  5. require "LuaScripts/Utilities/Sample"
  6. local scene_ = nil
  7. local cameraNode = nil
  8. local reflectionCameraNode = nil
  9. local waterNode = nil
  10. local waterPlane = Plane()
  11. local waterClipPlane = Plane()
  12. local yaw = 0.0
  13. local pitch = 0.0
  14. local cache = GetCache()
  15. local fileSystem = GetFileSystem()
  16. local graphics = GetGraphics()
  17. local input = GetInput()
  18. local renderer = GetRenderer()
  19. local ui = GetUI()
  20. function Start()
  21. -- Execute the common startup for samples
  22. SampleStart()
  23. -- Create the scene content
  24. CreateScene()
  25. -- Create the UI content
  26. CreateInstructions()
  27. -- Setup the viewport for displaying the scene
  28. SetupViewport()
  29. -- Hook up to the frame update event
  30. SubscribeToEvents()
  31. end
  32. function CreateScene()
  33. scene_ = Scene()
  34. -- Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
  35. scene_:CreateComponent("Octree")
  36. -- Create a Zone component for ambient lighting & fog control
  37. local zoneNode = scene_:CreateChild("Zone")
  38. local zone = zoneNode:CreateComponent("Zone")
  39. zone.boundingBox = BoundingBox(-1000.0, 1000.0)
  40. zone.ambientColor = Color(0.15, 0.15, 0.15)
  41. zone.fogColor = Color(1.0, 1.0, 1.0)
  42. zone.fogStart = 500.0
  43. zone.fogEnd = 750.0
  44. -- Create a directional light to the world. Enable cascaded shadows on it
  45. local lightNode = scene_:CreateChild("DirectionalLight")
  46. lightNode.direction = Vector3(0.6, -1.0, 0.8)
  47. local light = lightNode:CreateComponent("Light")
  48. light.lightType = LIGHT_DIRECTIONAL
  49. light.castShadows = true
  50. light.shadowBias = BiasParameters(0.00025, 0.5)
  51. light.shadowCascade = CascadeParameters(10.0, 50.0, 200.0, 0.0, 0.8)
  52. light.specularIntensity = 0.5;
  53. -- Apply slightly overbright lighting to match the skybox
  54. light.color = Color(1.2, 1.2, 1.2);
  55. -- Create skybox. The Skybox component is used like StaticModel, but it will be always located at the camera, giving the
  56. -- illusion of the box planes being far away. Use just the ordinary Box model and a suitable material, whose shader will
  57. -- generate the necessary 3D texture coordinates for cube mapping
  58. local skyNode = scene_:CreateChild("Sky")
  59. skyNode:SetScale(500.0) -- The scale actually does not matter
  60. local skybox = skyNode:CreateComponent("Skybox")
  61. skybox.model = cache:GetResource("Model", "Models/Box.mdl")
  62. skybox.material = cache:GetResource("Material", "Materials/Skybox.xml")
  63. -- Create heightmap terrain
  64. local terrainNode = scene_:CreateChild("Terrain")
  65. terrainNode.position = Vector3(0.0, 0.0, 0.0)
  66. local terrain = terrainNode:CreateComponent("Terrain")
  67. terrain.patchSize = 64
  68. terrain.spacing = Vector3(2.0, 0.5, 2.0) -- Spacing between vertices and vertical resolution of the height map
  69. terrain.smoothing = true
  70. terrain.heightMap = cache:GetResource("Image", "Textures/HeightMap.png")
  71. terrain.material = cache:GetResource("Material", "Materials/Terrain.xml")
  72. -- The terrain consists of large triangles, which fits well for occlusion rendering, as a hill can occlude all
  73. -- terrain patches and other objects behind it
  74. terrain.occluder = true
  75. -- Create 1000 boxes in the terrain. Always face outward along the terrain normal
  76. local NUM_OBJECTS = 1000
  77. for i = 1, NUM_OBJECTS do
  78. local objectNode = scene_:CreateChild("Box")
  79. local position = Vector3(Random(2000.0) - 1000.0, 0.0, Random(2000.0) - 1000.0)
  80. position.y = terrain:GetHeight(position) + 2.25
  81. objectNode.position = position
  82. -- Create a rotation quaternion from up vector to terrain normal
  83. objectNode.rotation = Quaternion(Vector3(0.0, 1.0, 0.0), terrain:GetNormal(position))
  84. objectNode:SetScale(5.0)
  85. local object = objectNode:CreateComponent("StaticModel")
  86. object.model = cache:GetResource("Model", "Models/Box.mdl")
  87. object.material = cache:GetResource("Material", "Materials/Stone.xml")
  88. object.castShadows = true
  89. end
  90. -- Create a water plane object that is as large as the terrain
  91. waterNode = scene_:CreateChild("Water")
  92. waterNode.scale = Vector3(2048.0, 1.0, 2048.0)
  93. waterNode.position = Vector3(0.0, 5.0, 0.0)
  94. local water = waterNode:CreateComponent("StaticModel")
  95. water.model = cache:GetResource("Model", "Models/Plane.mdl")
  96. water.material = cache:GetResource("Material", "Materials/Water.xml")
  97. -- Set a different viewmask on the water plane to be able to hide it from the reflection camera
  98. water.viewMask = 0x80000000
  99. -- Create the camera. Set far clip to match the fog. Note: now we actually create the camera node outside
  100. -- the scene, because we want it to be unaffected by scene load / save
  101. cameraNode = Node()
  102. local camera = cameraNode:CreateComponent("Camera")
  103. camera.farClip = 750.0
  104. -- Set an initial position for the camera scene node above the floor
  105. cameraNode.position = Vector3(0.0, 7.0, -20.0)
  106. end
  107. function CreateInstructions()
  108. -- Construct new Text object, set string to display and font to use
  109. local instructionText = ui.root:CreateChild("Text")
  110. instructionText:SetText("Use WASD keys and mouse to move")
  111. instructionText:SetFont(cache:GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15)
  112. instructionText.textAlignment = HA_CENTER
  113. -- Position the text relative to the screen center
  114. instructionText.horizontalAlignment = HA_CENTER
  115. instructionText.verticalAlignment = VA_CENTER
  116. instructionText:SetPosition(0, ui.root.height / 4)
  117. end
  118. function SetupViewport()
  119. -- Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
  120. local viewport = Viewport:new(scene_, cameraNode:GetComponent("Camera"))
  121. renderer:SetViewport(0, viewport)
  122. -- Create a mathematical plane to represent the water in calculations
  123. waterPlane = Plane(waterNode.worldRotation * Vector3(0.0, 1.0, 0.0), waterNode.worldPosition)
  124. -- Create a downward biased plane for reflection view clipping. Biasing is necessary to avoid too aggressive clipping
  125. waterClipPlane = Plane(waterNode.worldRotation * Vector3(0.0, 1.0, 0.0), waterNode.worldPosition -
  126. Vector3(0.0, 0.1, 0.0))
  127. -- Create camera for water reflection
  128. -- It will have the same farclip and position as the main viewport camera, but uses a reflection plane to modify
  129. -- its position when rendering
  130. reflectionCameraNode = cameraNode:CreateChild()
  131. local reflectionCamera = reflectionCameraNode:CreateComponent("Camera")
  132. reflectionCamera.farClip = 750.0
  133. reflectionCamera.viewMask = 0x7fffffff -- Hide objects with only bit 31 in the viewmask (the water plane)
  134. reflectionCamera.autoAspectRatio = false
  135. reflectionCamera.useReflection = true
  136. reflectionCamera.reflectionPlane = waterPlane
  137. reflectionCamera.useClipping = true -- Enable clipping of geometry behind water plane
  138. reflectionCamera.clipPlane = waterClipPlane
  139. -- The water reflection texture is rectangular. Set reflection camera aspect ratio to match
  140. reflectionCamera.aspectRatio = graphics.width / graphics.height
  141. -- View override flags could be used to optimize reflection rendering. For example disable shadows
  142. --reflectionCamera.viewOverrideFlags = VO_DISABLE_SHADOWS
  143. -- Create a texture and setup viewport for water reflection. Assign the reflection texture to the diffuse
  144. -- texture unit of the water material
  145. local texSize = 1024
  146. local renderTexture = Texture2D:new()
  147. renderTexture:SetSize(texSize, texSize, Graphics:GetRGBFormat(), TEXTURE_RENDERTARGET)
  148. renderTexture.filterMode = FILTER_BILINEAR
  149. local surface = renderTexture.renderSurface
  150. local rttViewport = Viewport:new(scene_, reflectionCamera)
  151. surface:SetViewport(0, rttViewport)
  152. local waterMat = cache:GetResource("Material", "Materials/Water.xml")
  153. waterMat:SetTexture(TU_DIFFUSE, renderTexture)
  154. end
  155. function SubscribeToEvents()
  156. -- Subscribe HandleUpdate() function for processing update events
  157. SubscribeToEvent("Update", "HandleUpdate")
  158. end
  159. function MoveCamera(timeStep)
  160. -- Do not move if the UI has a focused element (the console)
  161. if ui.focusElement ~= nil then
  162. return
  163. end
  164. -- Movement speed as world units per second
  165. local MOVE_SPEED = 20.0
  166. -- Mouse sensitivity as degrees per pixel
  167. local MOUSE_SENSITIVITY = 0.1
  168. -- Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  169. local mouseMove = input.mouseMove
  170. yaw = yaw + MOUSE_SENSITIVITY * mouseMove.x
  171. pitch = pitch + MOUSE_SENSITIVITY * mouseMove.y
  172. pitch = Clamp(pitch, -90.0, 90.0)
  173. -- Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  174. cameraNode.rotation = Quaternion(pitch, yaw, 0.0)
  175. -- Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  176. if input:GetKeyDown(KEY_W) then
  177. cameraNode:TranslateRelative(Vector3(0.0, 0.0, 1.0) * MOVE_SPEED * timeStep)
  178. end
  179. if input:GetKeyDown(KEY_S) then
  180. cameraNode:TranslateRelative(Vector3(0.0, 0.0, -1.0) * MOVE_SPEED * timeStep)
  181. end
  182. if input:GetKeyDown(KEY_A) then
  183. cameraNode:TranslateRelative(Vector3(-1.0, 0.0, 0.0) * MOVE_SPEED * timeStep)
  184. end
  185. if input:GetKeyDown(KEY_D) then
  186. cameraNode:TranslateRelative(Vector3(1.0, 0.0, 0.0) * MOVE_SPEED * timeStep)
  187. end
  188. -- In case resolution has changed, adjust the reflection camera aspect ratio
  189. local reflectionCamera = reflectionCameraNode:GetComponent("Camera")
  190. reflectionCamera.aspectRatio = graphics.width / graphics.height
  191. end
  192. function HandleUpdate(eventType, eventData)
  193. -- Take the frame time step, which is stored as a float
  194. local timeStep = eventData:GetFloat("TimeStep")
  195. -- Move the camera, scale movement with time step
  196. MoveCamera(timeStep)
  197. end