23_Water.as 10.0 KB

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