34_DynamicGeometry.as 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. // Dynamic geometry example.
  2. // This sample demonstrates:
  3. // - Cloning a Model resource
  4. // - Modifying the vertex buffer data of the cloned models at runtime to efficiently animate them
  5. // - Creating a Model resource and its buffer data from scratch
  6. #include "Scripts/Utilities/Sample.as"
  7. bool animate = true;
  8. float animTime = 0.0;
  9. VectorBuffer originalVertexData;
  10. Array<VertexBuffer@> animatingBuffers;
  11. Array<Vector3> originalVertices;
  12. Array<uint> vertexDuplicates;
  13. void Start()
  14. {
  15. // Execute the common startup for samples
  16. SampleStart();
  17. // Create the scene content
  18. CreateScene();
  19. // Create the UI content
  20. CreateInstructions();
  21. // Setup the viewport for displaying the scene
  22. SetupViewport();
  23. // Hook up to the frame update events
  24. SubscribeToEvents();
  25. }
  26. void CreateScene()
  27. {
  28. scene_ = Scene();
  29. // Create the Octree component to the scene so that drawable objects can be rendered. Use default volume
  30. // (-1000, -1000, -1000) to (1000, 1000, 1000)
  31. scene_.CreateComponent("Octree");
  32. // Create a Zone for ambient light & fog control
  33. Node@ zoneNode = scene_.CreateChild("Zone");
  34. Zone@ zone = zoneNode.CreateComponent("Zone");
  35. zone.boundingBox = BoundingBox(-1000.0, 1000.0);
  36. zone.fogColor = Color(0.2, 0.2, 0.2);
  37. zone.fogStart = 200.0;
  38. zone.fogEnd = 300.0;
  39. // Create a directional light
  40. Node@ lightNode = scene_.CreateChild("DirectionalLight");
  41. lightNode.direction = Vector3(-0.6, -1.0, -0.8); // The direction vector does not need to be normalized
  42. Light@ light = lightNode.CreateComponent("Light");
  43. light.lightType = LIGHT_DIRECTIONAL;
  44. light.color = Color(0.4, 1.0, 0.4);
  45. light.specularIntensity = 1.5;
  46. // Get the original model and its unmodified vertices, which are used as source data for the animation
  47. Model@ originalModel = cache.GetResource("Model", "Models/Box.mdl");
  48. if (originalModel is null)
  49. {
  50. Print("Model not found, cannot initialize example scene");
  51. return;
  52. }
  53. // Get the vertex buffer from the first geometry's first LOD level
  54. VertexBuffer@ buffer = originalModel.GetGeometry(0, 0).vertexBuffers[0];
  55. originalVertexData = buffer.GetData();
  56. uint numVertices = buffer.vertexCount;
  57. uint vertexSize = buffer.vertexSize;
  58. // Copy the original vertex positions
  59. for (uint i = 0; i < numVertices; ++i)
  60. {
  61. originalVertexData.Seek(i * vertexSize);
  62. originalVertices.Push(originalVertexData.ReadVector3());
  63. }
  64. // Detect duplicate vertices to allow seamless animation
  65. vertexDuplicates.Resize(originalVertices.length);
  66. for (uint i = 0; i < originalVertices.length; ++i)
  67. {
  68. vertexDuplicates[i] = i; // Assume not a duplicate
  69. for (uint j = 0; j < i; ++j)
  70. {
  71. if (originalVertices[i].Equals(originalVertices[j]))
  72. {
  73. vertexDuplicates[i] = j;
  74. break;
  75. }
  76. }
  77. }
  78. // Create StaticModels in the scene. Clone the model for each so that we can modify the vertex data individually
  79. for (int y = -1; y <= 1; ++y)
  80. {
  81. for (int x = -1; x <= 1; ++x)
  82. {
  83. Node@ node = scene_.CreateChild("Object");
  84. node.position = Vector3(x * 2.0, 0.0, y * 2.0);
  85. StaticModel@ object = node.CreateComponent("StaticModel");
  86. Model@ cloneModel = originalModel.Clone();
  87. object.model = cloneModel;
  88. // Store the cloned vertex buffer that we will modify when animating
  89. animatingBuffers.Push(cloneModel.GetGeometry(0, 0).vertexBuffers[0]);
  90. }
  91. }
  92. // Finally create one model (pyramid shape) and a StaticModel to display it from scratch
  93. // Note: there are duplicated vertices to enable face normals. We will calculate normals programmatically
  94. {
  95. const uint numVertices = 18;
  96. float[] vertexData = {
  97. // Position Normal
  98. 0.0, 0.5, 0.0, 0.0, 0.0, 0.0,
  99. 0.5, -0.5, 0.5, 0.0, 0.0, 0.0,
  100. 0.5, -0.5, -0.5, 0.0, 0.0, 0.0,
  101. 0.0, 0.5, 0.0, 0.0, 0.0, 0.0,
  102. -0.5, -0.5, 0.5, 0.0, 0.0, 0.0,
  103. 0.5, -0.5, 0.5, 0.0, 0.0, 0.0,
  104. 0.0, 0.5, 0.0, 0.0, 0.0, 0.0,
  105. -0.5, -0.5, -0.5, 0.0, 0.0, 0.0,
  106. -0.5, -0.5, 0.5, 0.0, 0.0, 0.0,
  107. 0.0, 0.5, 0.0, 0.0, 0.0, 0.0,
  108. 0.5, -0.5, -0.5, 0.0, 0.0, 0.0,
  109. -0.5, -0.5, -0.5, 0.0, 0.0, 0.0,
  110. 0.5, -0.5, -0.5, 0.0, 0.0, 0.0,
  111. 0.5, -0.5, 0.5, 0.0, 0.0, 0.0,
  112. -0.5, -0.5, 0.5, 0.0, 0.0, 0.0,
  113. 0.5, -0.5, -0.5, 0.0, 0.0, 0.0,
  114. -0.5, -0.5, 0.5, 0.0, 0.0, 0.0,
  115. -0.5, -0.5, -0.5, 0.0, 0.0, 0.0
  116. };
  117. const uint16[] indexData = {
  118. 0, 1, 2,
  119. 3, 4, 5,
  120. 6, 7, 8,
  121. 9, 10, 11,
  122. 12, 13, 14,
  123. 15, 16, 17
  124. };
  125. // Calculate face normals now
  126. for (uint i = 0; i < numVertices; i += 3)
  127. {
  128. Vector3 v1(vertexData[6 * i], vertexData[6 * i + 1], vertexData[6 * i + 2]);
  129. Vector3 v2(vertexData[6 * i + 6], vertexData[6 * i + 7], vertexData[6 * i + 8]);
  130. Vector3 v3(vertexData[6 * i + 12], vertexData[6 * i + 13], vertexData[6 * i + 14]);
  131. Vector3 edge1 = v1 - v2;
  132. Vector3 edge2 = v1 - v3;
  133. Vector3 normal = edge1.CrossProduct(edge2).Normalized();
  134. vertexData[6 * i + 3] = vertexData[6 * i + 9] = vertexData[6 * i + 15] = normal.x;
  135. vertexData[6 * i + 4] = vertexData[6 * i + 10] = vertexData[6 * i + 16] = normal.y;
  136. vertexData[6 * i + 5] = vertexData[6 * i + 11] = vertexData[6 * i + 17] = normal.z;
  137. }
  138. Model@ fromScratchModel = Model();
  139. VertexBuffer@ vb = VertexBuffer();
  140. IndexBuffer@ ib = IndexBuffer();
  141. Geometry@ geom = Geometry();
  142. // Shadowed buffer needed for raycasts to work, and so that data can be automatically restored on device loss
  143. vb.shadowed = true;
  144. vb.SetSize(numVertices, MASK_POSITION|MASK_NORMAL);
  145. VectorBuffer temp;
  146. for (uint i = 0; i < numVertices * 6; ++i)
  147. temp.WriteFloat(vertexData[i]);
  148. vb.SetData(temp);
  149. ib.shadowed = true;
  150. ib.SetSize(numVertices, false);
  151. temp.Clear();
  152. for (uint i = 0; i < numVertices; ++i)
  153. temp.WriteUShort(indexData[i]);
  154. ib.SetData(temp);
  155. geom.SetVertexBuffer(0, vb);
  156. geom.SetIndexBuffer(ib);
  157. geom.SetDrawRange(TRIANGLE_LIST, 0, numVertices);
  158. fromScratchModel.numGeometries = 1;
  159. fromScratchModel.SetGeometry(0, 0, geom);
  160. fromScratchModel.boundingBox = BoundingBox(Vector3(-0.5, -0.5, -0.5), Vector3(0.5, 0.5, 0.5));
  161. Node@ node = scene_.CreateChild("FromScratchObject");
  162. node.position = Vector3(0.0, 3.0, 0.0);
  163. StaticModel@ object = node.CreateComponent("StaticModel");
  164. object.model = fromScratchModel;
  165. }
  166. // Create the camera
  167. cameraNode = Node("Camera");
  168. cameraNode.position = Vector3(0.0, 2.0, -20.0);
  169. Camera@ camera = cameraNode.CreateComponent("Camera");
  170. camera.farClip = 300.0f;
  171. }
  172. void CreateInstructions()
  173. {
  174. // Construct new Text object, set string to display and font to use
  175. Text@ instructionText = ui.root.CreateChild("Text");
  176. instructionText.text =
  177. "Use WASD keys and mouse/touch to move\n"
  178. "Space to toggle animation";
  179. instructionText.SetFont(cache.GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15);
  180. // The text has multiple rows. Center them in relation to each other
  181. instructionText.textAlignment = HA_CENTER;
  182. // Position the text relative to the screen center
  183. instructionText.horizontalAlignment = HA_CENTER;
  184. instructionText.verticalAlignment = VA_CENTER;
  185. instructionText.SetPosition(0, ui.root.height / 4);
  186. }
  187. void SetupViewport()
  188. {
  189. // Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
  190. Viewport@ viewport = Viewport(scene_, cameraNode.GetComponent("Camera"));
  191. renderer.viewports[0] = viewport;
  192. }
  193. void SubscribeToEvents()
  194. {
  195. // Subscribe HandleUpdate() function for processing update events
  196. SubscribeToEvent("Update", "HandleUpdate");
  197. }
  198. void MoveCamera(float timeStep)
  199. {
  200. // Do not move if the UI has a focused element (the console)
  201. if (ui.focusElement !is null)
  202. return;
  203. // Movement speed as world units per second
  204. const float MOVE_SPEED = 20.0f;
  205. // Mouse sensitivity as degrees per pixel
  206. const float MOUSE_SENSITIVITY = 0.1f;
  207. // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  208. IntVector2 mouseMove = input.mouseMove;
  209. yaw += MOUSE_SENSITIVITY * mouseMove.x;
  210. pitch += MOUSE_SENSITIVITY * mouseMove.y;
  211. pitch = Clamp(pitch, -90.0, 90.0f);
  212. // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  213. cameraNode.rotation = Quaternion(pitch, yaw, 0.0f);
  214. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  215. if (input.keyDown['W'])
  216. cameraNode.Translate(Vector3(0.0, 0.0, 1.0f) * MOVE_SPEED * timeStep);
  217. if (input.keyDown['S'])
  218. cameraNode.Translate(Vector3(0.0, 0.0, -1.0f) * MOVE_SPEED * timeStep);
  219. if (input.keyDown['A'])
  220. cameraNode.Translate(Vector3(-1.0, 0.0, 0.0f) * MOVE_SPEED * timeStep);
  221. if (input.keyDown['D'])
  222. cameraNode.Translate(Vector3(1.0, 0.0, 0.0f) * MOVE_SPEED * timeStep);
  223. }
  224. void AnimateObjects(float timeStep)
  225. {
  226. animTime += timeStep * 100.0;
  227. // Repeat for each of the cloned vertex buffers
  228. for (uint i = 0; i < animatingBuffers.length; ++i)
  229. {
  230. float startPhase = animTime + i * 30.0;
  231. VertexBuffer@ buffer = animatingBuffers[i];
  232. // Need to prepare a VectorBuffer with all data (positions, normals, uvs...)
  233. VectorBuffer newData;
  234. uint numVertices = buffer.vertexCount;
  235. uint vertexSize = buffer.vertexSize;
  236. for (uint j = 0; j < numVertices; ++j)
  237. {
  238. // If there are duplicate vertices, animate them in phase of the original
  239. float phase = startPhase + vertexDuplicates[j] * 10.0f;
  240. Vector3 src = originalVertices[j];
  241. Vector3 dest;
  242. dest.x = src.x * (1.0 + 0.1 * Sin(phase));
  243. dest.y = src.y * (1.0 + 0.1 * Sin(phase + 60.0));
  244. dest.z = src.z * (1.0 + 0.1 * Sin(phase + 120.0));
  245. // Write position
  246. newData.WriteVector3(dest);
  247. // Copy other vertex elements
  248. originalVertexData.Seek(j * vertexSize + 12); // Seek past the vertex position
  249. for (uint k = 12; k < vertexSize; k += 4)
  250. newData.WriteFloat(originalVertexData.ReadFloat());
  251. }
  252. buffer.SetData(newData);
  253. }
  254. }
  255. void HandleUpdate(StringHash eventType, VariantMap& eventData)
  256. {
  257. // Take the frame time step, which is stored as a float
  258. float timeStep = eventData["TimeStep"].GetFloat();
  259. // Toggle animation with space
  260. if (input.keyPress[KEY_SPACE])
  261. animate = !animate;
  262. // Move the camera, scale movement with time step
  263. MoveCamera(timeStep);
  264. // Animate objects' vertex data if enabled
  265. if (animate)
  266. AnimateObjects(timeStep);
  267. }
  268. // Create XML patch instructions for screen joystick layout specific to this sample app
  269. String patchInstructions =
  270. "<patch>"
  271. " <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/attribute[@name='Is Visible']\" />"
  272. " <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Animation</replace>"
  273. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]\">"
  274. " <element type=\"Text\">"
  275. " <attribute name=\"Name\" value=\"KeyBinding\" />"
  276. " <attribute name=\"Text\" value=\"SPACE\" />"
  277. " </element>"
  278. " </add>"
  279. "</patch>";