08_Decals.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. //
  2. // Copyright (c) 2008-2015 the Urho3D project.
  3. // Copyright (c) 2015 Xamarin Inc
  4. // Copyright (c) 2016 THUNDERBEAST GAMES LLC
  5. //
  6. // Permission is hereby granted, free of charge, to any person obtaining a copy
  7. // of this software and associated documentation files (the "Software"), to deal
  8. // in the Software without restriction, including without limitation the rights
  9. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. // copies of the Software, and to permit persons to whom the Software is
  11. // furnished to do so, subject to the following conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be included in
  14. // all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. // THE SOFTWARE.
  23. //
  24. using System;
  25. using System.Linq;
  26. using AtomicEngine;
  27. namespace FeatureExamples
  28. {
  29. public class DecalSample : Sample
  30. {
  31. bool drawDebug;
  32. Camera camera;
  33. public DecalSample() : base() { }
  34. public override void Start()
  35. {
  36. base.Start();
  37. CreateScene();
  38. CreateUI();
  39. SetupViewport();
  40. SubscribeToEvents();
  41. }
  42. void CreateUI()
  43. {
  44. SimpleCreateInstructionsWithWasd(
  45. "\nLMB to paint decals, RMB to rotate view\n" +
  46. "Space to toggle debug geometry\n" +
  47. "7 to toggle occlusion culling");
  48. }
  49. void SubscribeToEvents()
  50. {
  51. // Subscribe HandlePostRenderUpdate() function for
  52. // processing the post-render update event, sent after
  53. // Renderer subsystem is done with defining the draw
  54. // calls for the viewports (but before actually
  55. // executing them.) We will request debug geometry
  56. // rendering during that event
  57. SubscribeToEvent<PostRenderUpdateEvent>(e =>
  58. {
  59. // If draw debug mode is enabled, draw viewport debug geometry, which will show eg. drawable bounding boxes and skeleton
  60. // bones. Note that debug geometry has to be separately requested each frame. Disable depth test so that we can see the
  61. // bones properly
  62. if (drawDebug)
  63. {
  64. GetSubsystem<Renderer>().DrawDebugGeometry(false);
  65. }
  66. });
  67. }
  68. protected override void Update(float timeStep)
  69. {
  70. UI ui = GetSubsystem<UI>();
  71. var input = GetSubsystem<Input>();
  72. const float mouseSensitivity = .1f;
  73. const float moveSpeed = 40f;
  74. if (input.GetMouseButtonDown(Constants.MOUSEB_RIGHT))
  75. {
  76. var mouseMove = input.MouseMove;
  77. Yaw += mouseSensitivity * mouseMove.X;
  78. Pitch += mouseSensitivity * mouseMove.Y;
  79. Pitch = MathHelper.Clamp(Pitch, -90, 90);
  80. }
  81. CameraNode.Rotation = new Quaternion(Pitch, Yaw, 0);
  82. if (input.GetKeyDown(Constants.KEY_W))
  83. CameraNode.Translate(Vector3.UnitZ * moveSpeed * timeStep);
  84. if (input.GetKeyDown(Constants.KEY_S))
  85. CameraNode.Translate(-Vector3.UnitZ * moveSpeed * timeStep);
  86. if (input.GetKeyDown(Constants.KEY_A))
  87. CameraNode.Translate(-Vector3.UnitX * moveSpeed * timeStep);
  88. if (input.GetKeyDown(Constants.KEY_D))
  89. CameraNode.Translate(Vector3.UnitX * moveSpeed * timeStep);
  90. if (input.GetKeyPress(Constants.KEY_SPACE))
  91. drawDebug = !drawDebug;
  92. if (input.GetMouseButtonPress(Constants.MOUSEB_LEFT))
  93. PaintDecal();
  94. base.Update(timeStep);
  95. }
  96. void SetupViewport()
  97. {
  98. var renderer = GetSubsystem<Renderer>();
  99. renderer.SetViewport(0, new Viewport(scene, CameraNode.GetComponent<Camera>()));
  100. }
  101. void CreateScene()
  102. {
  103. var cache = GetSubsystem<ResourceCache>();
  104. scene = new Scene();
  105. // Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
  106. // Also create a DebugRenderer component so that we can draw debug geometry
  107. scene.CreateComponent<Octree>();
  108. scene.CreateComponent<DebugRenderer>();
  109. // Create scene node & StaticModel component for showing a static plane
  110. var planeNode = scene.CreateChild("Plane");
  111. planeNode.Scale = new Vector3(100.0f, 1.0f, 100.0f);
  112. var planeObject = planeNode.CreateComponent<StaticModel>();
  113. planeObject.Model = cache.Get<Model>("Models/Plane.mdl");
  114. planeObject.SetMaterial(cache.Get<Material>("Materials/StoneTiled.xml"));
  115. // Create a Zone component for ambient lighting & fog control
  116. var zoneNode = scene.CreateChild("Zone");
  117. var zone = zoneNode.CreateComponent<Zone>();
  118. zone.SetBoundingBox(new BoundingBox(-1000.0f, 1000.0f));
  119. zone.AmbientColor = new Color(0.15f, 0.15f, 0.15f);
  120. zone.FogColor = new Color(0.5f, 0.5f, 0.7f);
  121. zone.FogStart = 100.0f;
  122. zone.FogEnd = 300.0f;
  123. // Create a directional light to the world. Enable cascaded shadows on it
  124. var lightNode = scene.CreateChild("DirectionalLight");
  125. lightNode.SetDirection(new Vector3(0.6f, -1.0f, 0.8f));
  126. var light = lightNode.CreateComponent<Light>();
  127. light.LightType = LightType.LIGHT_DIRECTIONAL;
  128. light.CastShadows = true;
  129. light.ShadowBias = new BiasParameters(0.00025f, 0.5f);
  130. // Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
  131. light.ShadowCascade = new CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f);
  132. // Create some mushrooms
  133. const uint numMushrooms = 240;
  134. for (uint i = 0; i < numMushrooms; ++i)
  135. {
  136. var mushroomNode = scene.CreateChild("Mushroom");
  137. mushroomNode.Position = new Vector3(NextRandom(90.0f) - 45.0f, 0.0f, NextRandom(90.0f) - 45.0f);
  138. mushroomNode.Rotation = new Quaternion(0.0f, NextRandom(360.0f), 0.0f);
  139. mushroomNode.SetScale(0.5f + NextRandom(2.0f));
  140. var mushroomObject = mushroomNode.CreateComponent<StaticModel>();
  141. mushroomObject.Model = cache.Get<Model>("Models/Mushroom.mdl");
  142. mushroomObject.SetMaterial(cache.Get<Material>("Materials/Mushroom.xml"));
  143. mushroomObject.CastShadows = true;
  144. }
  145. // Create randomly sized boxes. If boxes are big enough, make them occluders. Occluders will be software rasterized before
  146. // rendering to a low-resolution depth-only buffer to test the objects in the view frustum for visibility
  147. const uint numBoxes = 20;
  148. for (uint i = 0; i < numBoxes; ++i)
  149. {
  150. var boxNode = scene.CreateChild("Box");
  151. float size = 1.0f + NextRandom(10.0f);
  152. boxNode.Position = new Vector3(NextRandom(80.0f) - 40.0f, size * 0.5f, NextRandom(80.0f) - 40.0f);
  153. boxNode.SetScale(size);
  154. var boxObject = boxNode.CreateComponent<StaticModel>();
  155. boxObject.Model = cache.Get<Model>("Models/Box.mdl");
  156. boxObject.SetMaterial(cache.Get<Material>("Materials/Stone.xml"));
  157. boxObject.CastShadows = true;
  158. if (size >= 3.0f)
  159. boxObject.Occluder = true;
  160. }
  161. // Create the camera. Limit far clip distance to match the fog
  162. CameraNode = scene.CreateChild("Camera");
  163. camera = CameraNode.CreateComponent<Camera>();
  164. camera.FarClip = 300.0f;
  165. // Set an initial position for the camera scene node above the plane
  166. CameraNode.Position = new Vector3(0.0f, 5.0f, 0.0f);
  167. }
  168. bool Raycast(float maxDistance, out Vector3 hitPos, out Drawable hitDrawable)
  169. {
  170. hitDrawable = null;
  171. hitPos = Vector3.Zero;
  172. var graphics = GetSubsystem<Graphics>();
  173. var input = GetSubsystem<Input>();
  174. IntVector2 pos = input.MousePosition;
  175. Ray cameraRay = camera.GetScreenRay((float)pos.X / graphics.Width, (float)pos.Y / graphics.Height);
  176. RayOctreeQuery query = new RayOctreeQuery(cameraRay, RayQueryLevel.RAY_TRIANGLE, maxDistance, Constants.DRAWABLE_GEOMETRY);
  177. scene.GetComponent<Octree>().RaycastSingle(query);
  178. if (query.Results.Count > 0)
  179. {
  180. var first = query.Results.First();
  181. hitPos = first.Position;
  182. hitDrawable = first.Drawable;
  183. return true;
  184. }
  185. return false;
  186. }
  187. void PaintDecal()
  188. {
  189. Vector3 hitPos;
  190. Drawable hitDrawable;
  191. if (Raycast(250.0f, out hitPos, out hitDrawable))
  192. {
  193. var targetNode = hitDrawable.Node;
  194. var decal = targetNode.GetComponent<DecalSet>();
  195. if (decal == null)
  196. {
  197. var cache = GetSubsystem<ResourceCache>();
  198. decal = targetNode.CreateComponent<DecalSet>();
  199. decal.Material = cache.Get<Material>("Materials/UrhoDecal.xml");
  200. }
  201. // Add a square decal to the decal set using the geometry of the drawable that was hit, orient it to face the camera,
  202. // 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
  203. // plane) over a large area using just one DecalSet component, the decals will all be culled as one unit. If that is
  204. // undesirable, it may be necessary to create more than one DecalSet based on the distance
  205. decal.AddDecal(hitDrawable, hitPos, CameraNode.Rotation, 0.5f, 1.0f, 1.0f, Vector2.Zero,
  206. Vector2.One, 0.0f, 0.1f, uint.MaxValue);
  207. }
  208. }
  209. }
  210. }