physicsViewer.js 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824
  1. import { Mesh } from "../Meshes/mesh.js";
  2. import { CreateBox } from "../Meshes/Builders/boxBuilder.js";
  3. import { CreateSphere } from "../Meshes/Builders/sphereBuilder.js";
  4. import { Matrix, Quaternion, TmpVectors, Vector3 } from "../Maths/math.vector.js";
  5. import { Color3, Color4 } from "../Maths/math.color.js";
  6. import { EngineStore } from "../Engines/engineStore.js";
  7. import { StandardMaterial } from "../Materials/standardMaterial.js";
  8. import { PhysicsImpostor } from "../Physics/v1/physicsImpostor.js";
  9. import { UtilityLayerRenderer } from "../Rendering/utilityLayerRenderer.js";
  10. import { CreateCylinder } from "../Meshes/Builders/cylinderBuilder.js";
  11. import { CreateCapsule } from "../Meshes/Builders/capsuleBuilder.js";
  12. import { Logger } from "../Misc/logger.js";
  13. import { VertexData } from "../Meshes/mesh.vertexData.js";
  14. import { MeshBuilder } from "../Meshes/meshBuilder.js";
  15. import { AxesViewer } from "./axesViewer.js";
  16. import { TransformNode } from "../Meshes/transformNode.js";
  17. import { Epsilon } from "../Maths/math.constants.js";
  18. /**
  19. * Used to show the physics impostor around the specific mesh
  20. */
  21. export class PhysicsViewer {
  22. /**
  23. * Creates a new PhysicsViewer
  24. * @param scene defines the hosting scene
  25. */
  26. constructor(scene) {
  27. /** @internal */
  28. this._impostors = [];
  29. /** @internal */
  30. this._meshes = [];
  31. /** @internal */
  32. this._bodies = [];
  33. /** @internal */
  34. this._inertiaBodies = [];
  35. /** @internal */
  36. this._constraints = [];
  37. /** @internal */
  38. this._bodyMeshes = [];
  39. /** @internal */
  40. this._inertiaMeshes = [];
  41. /** @internal */
  42. this._constraintMeshes = [];
  43. /** @internal */
  44. this._numMeshes = 0;
  45. /** @internal */
  46. this._numBodies = 0;
  47. /** @internal */
  48. this._numInertiaBodies = 0;
  49. /** @internal */
  50. this._numConstraints = 0;
  51. this._debugMeshMeshes = new Array();
  52. this._constraintAxesSize = 0.4;
  53. this._scene = scene || EngineStore.LastCreatedScene;
  54. if (!this._scene) {
  55. return;
  56. }
  57. const physicEngine = this._scene.getPhysicsEngine();
  58. if (physicEngine) {
  59. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  60. }
  61. this._utilityLayer = new UtilityLayerRenderer(this._scene, false);
  62. this._utilityLayer.pickUtilitySceneFirst = false;
  63. this._utilityLayer.utilityLayerScene.autoClearDepthAndStencil = true;
  64. }
  65. /**
  66. * Updates the debug meshes of the physics engine.
  67. *
  68. * This code is useful for synchronizing the debug meshes of the physics engine with the physics impostor and mesh.
  69. * It checks if the impostor is disposed and if the plugin version is 1, then it syncs the mesh with the impostor.
  70. * This ensures that the debug meshes are up to date with the physics engine.
  71. */
  72. _updateDebugMeshes() {
  73. const plugin = this._physicsEnginePlugin;
  74. if (plugin?.getPluginVersion() === 1) {
  75. this._updateDebugMeshesV1();
  76. }
  77. else {
  78. this._updateDebugMeshesV2();
  79. }
  80. }
  81. /**
  82. * Updates the debug meshes of the physics engine.
  83. *
  84. * This method is useful for synchronizing the debug meshes with the physics impostors.
  85. * It iterates through the impostors and meshes, and if the plugin version is 1, it syncs the mesh with the impostor.
  86. * This ensures that the debug meshes accurately reflect the physics impostors, which is important for debugging the physics engine.
  87. */
  88. _updateDebugMeshesV1() {
  89. const plugin = this._physicsEnginePlugin;
  90. for (let i = 0; i < this._numMeshes; i++) {
  91. const impostor = this._impostors[i];
  92. if (!impostor) {
  93. continue;
  94. }
  95. if (impostor.isDisposed) {
  96. this.hideImpostor(this._impostors[i--]);
  97. }
  98. else {
  99. if (impostor.type === PhysicsImpostor.MeshImpostor) {
  100. continue;
  101. }
  102. const mesh = this._meshes[i];
  103. if (mesh && plugin) {
  104. plugin.syncMeshWithImpostor(mesh, impostor);
  105. }
  106. }
  107. }
  108. }
  109. /**
  110. * Updates the debug meshes of the physics engine for V2 plugin.
  111. *
  112. * This method is useful for synchronizing the debug meshes of the physics engine with the current state of the bodies.
  113. * It iterates through the bodies array and updates the debug meshes with the current transform of each body.
  114. * This ensures that the debug meshes accurately reflect the current state of the physics engine.
  115. */
  116. _updateDebugMeshesV2() {
  117. const plugin = this._physicsEnginePlugin;
  118. for (let i = 0; i < this._numBodies; i++) {
  119. const body = this._bodies[i];
  120. const transform = this._bodyMeshes[i];
  121. if (body && transform) {
  122. plugin.syncTransform(body, transform);
  123. }
  124. }
  125. }
  126. _updateInertiaMeshes() {
  127. for (let i = 0; i < this._numInertiaBodies; i++) {
  128. const body = this._inertiaBodies[i];
  129. const mesh = this._inertiaMeshes[i];
  130. if (body && mesh) {
  131. this._updateDebugInertia(body, mesh);
  132. }
  133. }
  134. }
  135. _updateDebugInertia(body, inertiaMesh) {
  136. const inertiaMatrixRef = Matrix.Identity();
  137. const transformMatrixRef = Matrix.Identity();
  138. const finalMatrixRef = Matrix.Identity();
  139. if (body._pluginDataInstances.length) {
  140. const inertiaAsMesh = inertiaMesh;
  141. const inertiaMeshMatrixData = inertiaAsMesh._thinInstanceDataStorage.matrixData;
  142. const bodyTransformMatrixData = body.transformNode._thinInstanceDataStorage.matrixData;
  143. for (let i = 0; i < body._pluginDataInstances.length; i++) {
  144. const props = body.getMassProperties(i);
  145. this._getMeshDebugInertiaMatrixToRef(props, inertiaMatrixRef);
  146. Matrix.FromArrayToRef(bodyTransformMatrixData, i * 16, transformMatrixRef);
  147. inertiaMatrixRef.multiplyToRef(transformMatrixRef, finalMatrixRef);
  148. finalMatrixRef.copyToArray(inertiaMeshMatrixData, i * 16);
  149. }
  150. inertiaAsMesh.thinInstanceBufferUpdated("matrix");
  151. }
  152. else {
  153. const props = body.getMassProperties();
  154. this._getMeshDebugInertiaMatrixToRef(props, inertiaMatrixRef);
  155. body.transformNode.rotationQuaternion?.toRotationMatrix(transformMatrixRef);
  156. transformMatrixRef.setTranslation(body.transformNode.position);
  157. if (body.transformNode.parent) {
  158. const parentTransform = body.transformNode.parent.computeWorldMatrix(true);
  159. transformMatrixRef.multiplyToRef(parentTransform, transformMatrixRef);
  160. }
  161. inertiaMatrixRef.multiplyToRef(transformMatrixRef, inertiaMatrixRef);
  162. inertiaMatrixRef.decomposeToTransformNode(inertiaMesh);
  163. }
  164. }
  165. _updateDebugConstraints() {
  166. for (let i = 0; i < this._numConstraints; i++) {
  167. const constraint = this._constraints[i];
  168. const mesh = this._constraintMeshes[i];
  169. if (constraint && mesh) {
  170. this._updateDebugConstraint(constraint, mesh);
  171. }
  172. }
  173. }
  174. /**
  175. * Given a scaling vector, make all of its components
  176. * 1, preserving the sign
  177. * @param scaling
  178. */
  179. _makeScalingUnitInPlace(scaling) {
  180. if (Math.abs(scaling.x - 1) > Epsilon) {
  181. scaling.x = 1 * Math.sign(scaling.x);
  182. }
  183. if (Math.abs(scaling.y - 1) > Epsilon) {
  184. scaling.y = 1 * Math.sign(scaling.y);
  185. }
  186. if (Math.abs(scaling.z - 1) > Epsilon) {
  187. scaling.z = 1 * Math.sign(scaling.z);
  188. }
  189. }
  190. _updateDebugConstraint(constraint, parentingMesh) {
  191. if (!constraint._initOptions) {
  192. return;
  193. }
  194. // Get constraint pivot and axes
  195. const { pivotA, pivotB, axisA, axisB, perpAxisA, perpAxisB } = constraint._initOptions;
  196. if (!pivotA || !pivotB || !axisA || !axisB || !perpAxisA || !perpAxisB) {
  197. return;
  198. }
  199. parentingMesh.getDescendants(true).forEach((parentConstraintMesh) => {
  200. // Get the parent transform
  201. const parentCoordSystemNode = parentConstraintMesh.getDescendants(true)[0];
  202. const childCoordSystemNode = parentConstraintMesh.getDescendants(true)[1];
  203. const { parentBody, parentBodyIndex } = parentCoordSystemNode.metadata;
  204. const { childBody, childBodyIndex } = childCoordSystemNode.metadata;
  205. const parentTransform = this._getTransformFromBodyToRef(parentBody, TmpVectors.Matrix[0], parentBodyIndex);
  206. const childTransform = this._getTransformFromBodyToRef(childBody, TmpVectors.Matrix[1], childBodyIndex);
  207. parentTransform.decomposeToTransformNode(parentCoordSystemNode);
  208. this._makeScalingUnitInPlace(parentCoordSystemNode.scaling);
  209. childTransform.decomposeToTransformNode(childCoordSystemNode);
  210. this._makeScalingUnitInPlace(childCoordSystemNode.scaling);
  211. // Create a transform node and set its matrix
  212. const parentTransformNode = parentCoordSystemNode.getDescendants(true)[0];
  213. parentTransformNode.position.copyFrom(pivotA);
  214. const childTransformNode = childCoordSystemNode.getDescendants(true)[0];
  215. childTransformNode.position.copyFrom(pivotB);
  216. // Get the transform to align the XYZ axes to the constraint axes
  217. Quaternion.FromRotationMatrixToRef(Matrix.FromXYZAxesToRef(axisA, perpAxisA, Vector3.CrossToRef(axisA, perpAxisA, TmpVectors.Vector3[0]), TmpVectors.Matrix[0]), parentTransformNode.rotationQuaternion);
  218. Quaternion.FromRotationMatrixToRef(Matrix.FromXYZAxesToRef(axisB, perpAxisB, Vector3.CrossToRef(axisB, perpAxisB, TmpVectors.Vector3[1]), TmpVectors.Matrix[1]), childTransformNode.rotationQuaternion);
  219. });
  220. }
  221. /**
  222. * Renders a specified physic impostor
  223. * @param impostor defines the impostor to render
  224. * @param targetMesh defines the mesh represented by the impostor
  225. * @returns the new debug mesh used to render the impostor
  226. */
  227. showImpostor(impostor, targetMesh) {
  228. if (!this._scene) {
  229. return null;
  230. }
  231. for (let i = 0; i < this._numMeshes; i++) {
  232. if (this._impostors[i] == impostor) {
  233. return null;
  234. }
  235. }
  236. const debugMesh = this._getDebugMesh(impostor, targetMesh);
  237. if (debugMesh) {
  238. this._impostors[this._numMeshes] = impostor;
  239. this._meshes[this._numMeshes] = debugMesh;
  240. if (this._numMeshes === 0) {
  241. this._renderFunction = () => this._updateDebugMeshes();
  242. this._scene.registerBeforeRender(this._renderFunction);
  243. }
  244. this._numMeshes++;
  245. }
  246. return debugMesh;
  247. }
  248. /**
  249. * Shows a debug mesh for a given physics body.
  250. * @param body The physics body to show.
  251. * @returns The debug mesh, or null if the body is already shown.
  252. *
  253. * This function is useful for visualizing the physics body in the scene.
  254. * It creates a debug mesh for the given body and adds it to the scene.
  255. * It also registers a before render function to update the debug mesh position and rotation.
  256. */
  257. showBody(body) {
  258. if (!this._scene) {
  259. return null;
  260. }
  261. for (let i = 0; i < this._numBodies; i++) {
  262. if (this._bodies[i] == body) {
  263. return null;
  264. }
  265. }
  266. const debugMesh = this._getDebugBodyMesh(body);
  267. if (debugMesh) {
  268. this._bodies[this._numBodies] = body;
  269. this._bodyMeshes[this._numBodies] = debugMesh;
  270. if (this._numBodies === 0) {
  271. this._renderFunction = () => this._updateDebugMeshes();
  272. this._scene.registerBeforeRender(this._renderFunction);
  273. }
  274. this._numBodies++;
  275. }
  276. return debugMesh;
  277. }
  278. /**
  279. * Shows a debug box corresponding to the inertia of a given body
  280. * @param body the physics body used to get the inertia
  281. * @returns the debug mesh used to show the inertia, or null if the body is already shown
  282. */
  283. showInertia(body) {
  284. if (!this._scene) {
  285. return null;
  286. }
  287. for (let i = 0; i < this._numInertiaBodies; i++) {
  288. if (this._inertiaBodies[i] == body) {
  289. return null;
  290. }
  291. }
  292. const debugMesh = this._getDebugInertiaMesh(body);
  293. if (debugMesh) {
  294. this._inertiaBodies[this._numInertiaBodies] = body;
  295. this._inertiaMeshes[this._numInertiaBodies] = debugMesh;
  296. if (this._numInertiaBodies === 0) {
  297. this._inertiaRenderFunction = () => this._updateInertiaMeshes();
  298. this._scene.registerBeforeRender(this._inertiaRenderFunction);
  299. }
  300. this._numInertiaBodies++;
  301. }
  302. return debugMesh;
  303. }
  304. /**
  305. * Shows a debug mesh for a given physics constraint.
  306. * @param constraint the physics constraint to show
  307. * @returns the debug mesh, or null if the constraint is already shown
  308. */
  309. showConstraint(constraint) {
  310. if (!this._scene) {
  311. return null;
  312. }
  313. for (let i = 0; i < this._numConstraints; i++) {
  314. if (this._constraints[i] == constraint) {
  315. return null;
  316. }
  317. }
  318. const debugMesh = this._getDebugConstraintMesh(constraint);
  319. if (debugMesh) {
  320. this._constraints[this._numConstraints] = constraint;
  321. this._constraintMeshes[this._numConstraints] = debugMesh;
  322. if (this._numConstraints === 0) {
  323. this._constraintRenderFunction = () => this._updateDebugConstraints();
  324. this._scene.registerBeforeRender(this._constraintRenderFunction);
  325. }
  326. this._numConstraints++;
  327. }
  328. return debugMesh;
  329. }
  330. /**
  331. * Hides an impostor from the scene.
  332. * @param impostor - The impostor to hide.
  333. *
  334. * This method is useful for hiding an impostor from the scene. It removes the
  335. * impostor from the utility layer scene, disposes the mesh, and removes the
  336. * impostor from the list of impostors. If the impostor is the last one in the
  337. * list, it also unregisters the render function.
  338. */
  339. hideImpostor(impostor) {
  340. if (!impostor || !this._scene || !this._utilityLayer) {
  341. return;
  342. }
  343. let removed = false;
  344. const utilityLayerScene = this._utilityLayer.utilityLayerScene;
  345. for (let i = 0; i < this._numMeshes; i++) {
  346. if (this._impostors[i] == impostor) {
  347. const mesh = this._meshes[i];
  348. if (!mesh) {
  349. continue;
  350. }
  351. utilityLayerScene.removeMesh(mesh);
  352. mesh.dispose();
  353. const index = this._debugMeshMeshes.indexOf(mesh);
  354. if (index > -1) {
  355. this._debugMeshMeshes.splice(index, 1);
  356. }
  357. this._numMeshes--;
  358. if (this._numMeshes > 0) {
  359. this._meshes[i] = this._meshes[this._numMeshes];
  360. this._impostors[i] = this._impostors[this._numMeshes];
  361. this._meshes[this._numMeshes] = null;
  362. this._impostors[this._numMeshes] = null;
  363. }
  364. else {
  365. this._meshes[0] = null;
  366. this._impostors[0] = null;
  367. }
  368. removed = true;
  369. break;
  370. }
  371. }
  372. if (removed && this._numMeshes === 0) {
  373. this._scene.unregisterBeforeRender(this._renderFunction);
  374. }
  375. }
  376. /**
  377. * Hides a body from the physics engine.
  378. * @param body - The body to hide.
  379. *
  380. * This function is useful for hiding a body from the physics engine.
  381. * It removes the body from the utility layer scene and disposes the mesh associated with it.
  382. * It also unregisters the render function if the number of bodies is 0.
  383. * This is useful for hiding a body from the physics engine without deleting it.
  384. */
  385. hideBody(body) {
  386. if (!body || !this._scene || !this._utilityLayer) {
  387. return;
  388. }
  389. let removed = false;
  390. const utilityLayerScene = this._utilityLayer.utilityLayerScene;
  391. for (let i = 0; i < this._numBodies; i++) {
  392. if (this._bodies[i] === body) {
  393. const mesh = this._bodyMeshes[i];
  394. if (!mesh) {
  395. continue;
  396. }
  397. utilityLayerScene.removeMesh(mesh);
  398. mesh.dispose();
  399. this._numBodies--;
  400. if (this._numBodies > 0) {
  401. this._bodyMeshes[i] = this._bodyMeshes[this._numBodies];
  402. this._bodies[i] = this._bodies[this._numBodies];
  403. this._bodyMeshes[this._numBodies] = null;
  404. this._bodies[this._numBodies] = null;
  405. }
  406. else {
  407. this._bodyMeshes[0] = null;
  408. this._bodies[0] = null;
  409. }
  410. removed = true;
  411. break;
  412. }
  413. }
  414. if (removed && this._numBodies === 0) {
  415. this._scene.unregisterBeforeRender(this._renderFunction);
  416. }
  417. }
  418. /**
  419. * Hides a body's inertia from the viewer utility layer
  420. * @param body the body to hide
  421. */
  422. hideInertia(body) {
  423. if (!body || !this._scene || !this._utilityLayer) {
  424. return;
  425. }
  426. let removed = false;
  427. const utilityLayerScene = this._utilityLayer.utilityLayerScene;
  428. for (let i = 0; i < this._numInertiaBodies; i++) {
  429. if (this._inertiaBodies[i] === body) {
  430. const mesh = this._inertiaMeshes[i];
  431. if (!mesh) {
  432. continue;
  433. }
  434. utilityLayerScene.removeMesh(mesh);
  435. mesh.dispose();
  436. this._inertiaBodies.splice(i, 1);
  437. this._inertiaMeshes.splice(i, 1);
  438. this._numInertiaBodies--;
  439. removed = true;
  440. break;
  441. }
  442. }
  443. if (removed && this._numInertiaBodies === 0) {
  444. this._scene.unregisterBeforeRender(this._inertiaRenderFunction);
  445. }
  446. }
  447. /**
  448. * Hide a physics constraint from the viewer utility layer
  449. * @param constraint the constraint to hide
  450. */
  451. hideConstraint(constraint) {
  452. if (!constraint || !this._scene || !this._utilityLayer) {
  453. return;
  454. }
  455. let removed = false;
  456. const utilityLayerScene = this._utilityLayer.utilityLayerScene;
  457. for (let i = 0; i < this._numConstraints; i++) {
  458. if (this._constraints[i] === constraint) {
  459. const mesh = this._constraintMeshes[i];
  460. if (!mesh) {
  461. continue;
  462. }
  463. utilityLayerScene.removeMesh(mesh);
  464. mesh.dispose();
  465. this._constraints.splice(i, 1);
  466. this._constraintMeshes.splice(i, 1);
  467. this._numConstraints--;
  468. if (this._numConstraints > 0) {
  469. this._constraints[i] = this._constraints[this._numConstraints];
  470. this._constraintMeshes[i] = this._constraintMeshes[this._numConstraints];
  471. this._constraints[this._numConstraints] = null;
  472. this._constraintMeshes[this._numConstraints] = null;
  473. }
  474. else {
  475. this._constraints[0] = null;
  476. this._constraintMeshes[0] = null;
  477. }
  478. removed = true;
  479. break;
  480. }
  481. }
  482. if (removed && this._numConstraints === 0) {
  483. this._scene.unregisterBeforeRender(this._constraintRenderFunction);
  484. }
  485. }
  486. _getDebugMaterial(scene) {
  487. if (!this._debugMaterial) {
  488. this._debugMaterial = new StandardMaterial("", scene);
  489. this._debugMaterial.wireframe = true;
  490. this._debugMaterial.emissiveColor = Color3.White();
  491. this._debugMaterial.disableLighting = true;
  492. }
  493. return this._debugMaterial;
  494. }
  495. _getDebugInertiaMaterial(scene) {
  496. if (!this._debugInertiaMaterial) {
  497. this._debugInertiaMaterial = new StandardMaterial("", scene);
  498. this._debugInertiaMaterial.disableLighting = true;
  499. this._debugInertiaMaterial.alpha = 0.0;
  500. }
  501. return this._debugInertiaMaterial;
  502. }
  503. _getDebugBoxMesh(scene) {
  504. if (!this._debugBoxMesh) {
  505. this._debugBoxMesh = CreateBox("physicsBodyBoxViewMesh", { size: 1 }, scene);
  506. this._debugBoxMesh.rotationQuaternion = Quaternion.Identity();
  507. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  508. this._debugBoxMesh.setEnabled(false);
  509. }
  510. return this._debugBoxMesh.createInstance("physicsBodyBoxViewInstance");
  511. }
  512. _getDebugSphereMesh(scene) {
  513. if (!this._debugSphereMesh) {
  514. this._debugSphereMesh = CreateSphere("physicsBodySphereViewMesh", { diameter: 1 }, scene);
  515. this._debugSphereMesh.rotationQuaternion = Quaternion.Identity();
  516. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  517. this._debugSphereMesh.setEnabled(false);
  518. }
  519. return this._debugSphereMesh.createInstance("physicsBodySphereViewInstance");
  520. }
  521. _getDebugCapsuleMesh(scene) {
  522. if (!this._debugCapsuleMesh) {
  523. this._debugCapsuleMesh = CreateCapsule("physicsBodyCapsuleViewMesh", { height: 1 }, scene);
  524. this._debugCapsuleMesh.rotationQuaternion = Quaternion.Identity();
  525. this._debugCapsuleMesh.material = this._getDebugMaterial(scene);
  526. this._debugCapsuleMesh.setEnabled(false);
  527. }
  528. return this._debugCapsuleMesh.createInstance("physicsBodyCapsuleViewInstance");
  529. }
  530. _getDebugCylinderMesh(scene) {
  531. if (!this._debugCylinderMesh) {
  532. this._debugCylinderMesh = CreateCylinder("physicsBodyCylinderViewMesh", { diameterTop: 1, diameterBottom: 1, height: 1 }, scene);
  533. this._debugCylinderMesh.rotationQuaternion = Quaternion.Identity();
  534. this._debugCylinderMesh.material = this._getDebugMaterial(scene);
  535. this._debugCylinderMesh.setEnabled(false);
  536. }
  537. return this._debugCylinderMesh.createInstance("physicsBodyCylinderViewInstance");
  538. }
  539. _getDebugMeshMesh(mesh, scene) {
  540. const wireframeOver = new Mesh(mesh.name, scene, null, mesh);
  541. wireframeOver.setParent(mesh);
  542. wireframeOver.position = Vector3.Zero();
  543. wireframeOver.material = this._getDebugMaterial(scene);
  544. this._debugMeshMeshes.push(wireframeOver);
  545. return wireframeOver;
  546. }
  547. _getDebugMesh(impostor, targetMesh) {
  548. if (!this._utilityLayer) {
  549. return null;
  550. }
  551. // Only create child impostor debug meshes when evaluating the parent
  552. if (targetMesh && targetMesh.parent && targetMesh.parent.physicsImpostor) {
  553. return null;
  554. }
  555. let mesh = null;
  556. const utilityLayerScene = this._utilityLayer.utilityLayerScene;
  557. if (!impostor.physicsBody) {
  558. Logger.Warn("Unable to get physicsBody of impostor. It might be initialized later by its parent's impostor.");
  559. return null;
  560. }
  561. switch (impostor.type) {
  562. case PhysicsImpostor.BoxImpostor:
  563. mesh = this._getDebugBoxMesh(utilityLayerScene);
  564. impostor.getBoxSizeToRef(mesh.scaling);
  565. break;
  566. case PhysicsImpostor.SphereImpostor: {
  567. mesh = this._getDebugSphereMesh(utilityLayerScene);
  568. const radius = impostor.getRadius();
  569. mesh.scaling.x = radius * 2;
  570. mesh.scaling.y = radius * 2;
  571. mesh.scaling.z = radius * 2;
  572. break;
  573. }
  574. case PhysicsImpostor.CapsuleImpostor: {
  575. mesh = this._getDebugCapsuleMesh(utilityLayerScene);
  576. const bi = impostor.object.getBoundingInfo();
  577. mesh.scaling.x = (bi.boundingBox.maximum.x - bi.boundingBox.minimum.x) * 2 * impostor.object.scaling.x;
  578. mesh.scaling.y = (bi.boundingBox.maximum.y - bi.boundingBox.minimum.y) * impostor.object.scaling.y;
  579. mesh.scaling.z = (bi.boundingBox.maximum.z - bi.boundingBox.minimum.z) * 2 * impostor.object.scaling.z;
  580. break;
  581. }
  582. case PhysicsImpostor.MeshImpostor:
  583. if (targetMesh) {
  584. mesh = this._getDebugMeshMesh(targetMesh, utilityLayerScene);
  585. }
  586. break;
  587. case PhysicsImpostor.NoImpostor:
  588. if (targetMesh) {
  589. // Handle compound impostors
  590. const childMeshes = targetMesh.getChildMeshes().filter((c) => {
  591. return c.physicsImpostor ? 1 : 0;
  592. });
  593. childMeshes.forEach((m) => {
  594. if (m.physicsImpostor && m.getClassName() === "Mesh") {
  595. const boundingInfo = m.getBoundingInfo();
  596. const min = boundingInfo.boundingBox.minimum;
  597. const max = boundingInfo.boundingBox.maximum;
  598. switch (m.physicsImpostor.type) {
  599. case PhysicsImpostor.BoxImpostor:
  600. mesh = this._getDebugBoxMesh(utilityLayerScene);
  601. mesh.position.copyFrom(min);
  602. mesh.position.addInPlace(max);
  603. mesh.position.scaleInPlace(0.5);
  604. break;
  605. case PhysicsImpostor.SphereImpostor:
  606. mesh = this._getDebugSphereMesh(utilityLayerScene);
  607. break;
  608. case PhysicsImpostor.CylinderImpostor:
  609. mesh = this._getDebugCylinderMesh(utilityLayerScene);
  610. break;
  611. default:
  612. mesh = null;
  613. break;
  614. }
  615. if (mesh) {
  616. mesh.scaling.x = max.x - min.x;
  617. mesh.scaling.y = max.y - min.y;
  618. mesh.scaling.z = max.z - min.z;
  619. mesh.parent = m;
  620. }
  621. }
  622. });
  623. }
  624. else {
  625. Logger.Warn("No target mesh parameter provided for NoImpostor. Skipping.");
  626. }
  627. mesh = null;
  628. break;
  629. case PhysicsImpostor.CylinderImpostor: {
  630. mesh = this._getDebugCylinderMesh(utilityLayerScene);
  631. const bi = impostor.object.getBoundingInfo();
  632. mesh.scaling.x = (bi.boundingBox.maximum.x - bi.boundingBox.minimum.x) * impostor.object.scaling.x;
  633. mesh.scaling.y = (bi.boundingBox.maximum.y - bi.boundingBox.minimum.y) * impostor.object.scaling.y;
  634. mesh.scaling.z = (bi.boundingBox.maximum.z - bi.boundingBox.minimum.z) * impostor.object.scaling.z;
  635. break;
  636. }
  637. }
  638. return mesh;
  639. }
  640. /**
  641. * Creates a debug mesh for a given physics body
  642. * @param body The physics body to create the debug mesh for
  643. * @returns The created debug mesh or null if the utility layer is not available
  644. *
  645. * This code is useful for creating a debug mesh for a given physics body.
  646. * It creates a Mesh object with a VertexData object containing the positions and indices
  647. * of the geometry of the body. The mesh is then assigned a debug material from the utility layer scene.
  648. * This allows for visualizing the physics body in the scene.
  649. */
  650. _getDebugBodyMesh(body) {
  651. if (!this._utilityLayer) {
  652. return null;
  653. }
  654. const utilityLayerScene = this._utilityLayer.utilityLayerScene;
  655. const mesh = new Mesh("custom", utilityLayerScene);
  656. const vertexData = new VertexData();
  657. const geometry = body.getGeometry();
  658. vertexData.positions = geometry.positions;
  659. vertexData.indices = geometry.indices;
  660. vertexData.applyToMesh(mesh);
  661. if (body._pluginDataInstances) {
  662. const instanceBuffer = new Float32Array(body._pluginDataInstances.length * 16);
  663. mesh.thinInstanceSetBuffer("matrix", instanceBuffer, 16, false);
  664. }
  665. mesh.material = this._getDebugMaterial(utilityLayerScene);
  666. return mesh;
  667. }
  668. _getMeshDebugInertiaMatrixToRef(massProps, matrix) {
  669. const orientation = massProps.inertiaOrientation ?? Quaternion.Identity();
  670. const inertiaLocal = massProps.inertia ?? Vector3.Zero();
  671. const center = massProps.centerOfMass ?? Vector3.Zero();
  672. const betaSqrd = (inertiaLocal.x - inertiaLocal.y + inertiaLocal.z) * 6;
  673. const beta = Math.sqrt(Math.max(betaSqrd, 0)); // Safety check for zeroed elements!
  674. const gammaSqrd = inertiaLocal.x * 12 - betaSqrd;
  675. const gamma = Math.sqrt(Math.max(gammaSqrd, 0)); // Safety check for zeroed elements!
  676. const alphaSqrd = inertiaLocal.z * 12 - betaSqrd;
  677. const alpha = Math.sqrt(Math.max(alphaSqrd, 0)); // Safety check for zeroed elements!
  678. const extents = TmpVectors.Vector3[0];
  679. extents.set(alpha, beta, gamma);
  680. const scaling = Matrix.ScalingToRef(extents.x, extents.y, extents.z, TmpVectors.Matrix[0]);
  681. const rotation = orientation.toRotationMatrix(TmpVectors.Matrix[1]);
  682. const translation = Matrix.TranslationToRef(center.x, center.y, center.z, TmpVectors.Matrix[2]);
  683. scaling.multiplyToRef(rotation, matrix);
  684. matrix.multiplyToRef(translation, matrix);
  685. return matrix;
  686. }
  687. _getDebugInertiaMesh(body) {
  688. if (!this._utilityLayer) {
  689. return null;
  690. }
  691. const utilityLayerScene = this._utilityLayer.utilityLayerScene;
  692. // The base inertia mesh is going to be a 1x1 cube that's scaled and rotated according to the inertia
  693. const inertiaBoxMesh = MeshBuilder.CreateBox("custom", { size: 1 }, utilityLayerScene);
  694. const matrixRef = Matrix.Identity();
  695. if (body._pluginDataInstances.length) {
  696. const instanceBuffer = new Float32Array(body._pluginDataInstances.length * 16);
  697. for (let i = 0; i < body._pluginDataInstances.length; ++i) {
  698. const props = body.getMassProperties(i);
  699. this._getMeshDebugInertiaMatrixToRef(props, matrixRef);
  700. matrixRef.copyToArray(instanceBuffer, i * 16);
  701. }
  702. inertiaBoxMesh.thinInstanceSetBuffer("matrix", instanceBuffer, 16, false);
  703. }
  704. else {
  705. const props = body.getMassProperties();
  706. this._getMeshDebugInertiaMatrixToRef(props, matrixRef);
  707. matrixRef.decomposeToTransformNode(inertiaBoxMesh);
  708. }
  709. inertiaBoxMesh.enableEdgesRendering();
  710. inertiaBoxMesh.edgesWidth = 2.0;
  711. inertiaBoxMesh.edgesColor = new Color4(1, 0, 1, 1);
  712. inertiaBoxMesh.material = this._getDebugInertiaMaterial(utilityLayerScene);
  713. return inertiaBoxMesh;
  714. }
  715. _getTransformFromBodyToRef(body, matrix, instanceIndex) {
  716. const tnode = body.transformNode;
  717. if (instanceIndex && instanceIndex >= 0) {
  718. return Matrix.FromArrayToRef(tnode._thinInstanceDataStorage.matrixData, instanceIndex, matrix);
  719. }
  720. else {
  721. return matrix.copyFrom(tnode.getWorldMatrix());
  722. }
  723. }
  724. _getDebugConstraintMesh(constraint) {
  725. if (!this._utilityLayer) {
  726. return null;
  727. }
  728. const utilityLayerScene = this._utilityLayer.utilityLayerScene;
  729. if (!constraint._initOptions) {
  730. return null;
  731. }
  732. // Get constraint pivot and axes
  733. const { pivotA, pivotB, axisA, axisB, perpAxisA, perpAxisB } = constraint._initOptions;
  734. if (!pivotA || !pivotB || !axisA || !axisB || !perpAxisA || !perpAxisB) {
  735. return null;
  736. }
  737. // Create a mesh to parent all the constraint debug meshes to
  738. const parentingMesh = new Mesh("parentingDebugConstraint", utilityLayerScene);
  739. // First, get a reference to all physic bodies that are using this constraint
  740. const bodiesUsingConstraint = constraint.getBodiesUsingConstraint();
  741. for (const bodyPairInfo of bodiesUsingConstraint) {
  742. // Create a mesh to keep the pair of constraint axes
  743. const parentOfPair = new TransformNode("parentOfPair", utilityLayerScene);
  744. parentOfPair.parent = parentingMesh;
  745. const { parentBody, parentBodyIndex, childBody, childBodyIndex } = bodyPairInfo;
  746. // Get the parent transform
  747. const parentTransform = this._getTransformFromBodyToRef(parentBody, TmpVectors.Matrix[0], parentBodyIndex);
  748. const childTransform = this._getTransformFromBodyToRef(childBody, TmpVectors.Matrix[1], childBodyIndex);
  749. const parentCoordSystemNode = new TransformNode("parentCoordSystem", utilityLayerScene);
  750. // parentCoordSystemNode.parent = parentingMesh;
  751. parentCoordSystemNode.parent = parentOfPair;
  752. // Save parent and index here to be able to get the transform on update
  753. parentCoordSystemNode.metadata = { parentBody, parentBodyIndex };
  754. parentTransform.decomposeToTransformNode(parentCoordSystemNode);
  755. const childCoordSystemNode = new TransformNode("childCoordSystem", utilityLayerScene);
  756. // childCoordSystemNode.parent = parentingMesh;
  757. childCoordSystemNode.parent = parentOfPair;
  758. // Save child and index here to be able to get the transform on update
  759. childCoordSystemNode.metadata = { childBody, childBodyIndex };
  760. childTransform.decomposeToTransformNode(childCoordSystemNode);
  761. // Get the transform to align the XYZ axes to the constraint axes
  762. const rotTransformParent = Quaternion.FromRotationMatrix(Matrix.FromXYZAxesToRef(axisA, perpAxisA, axisA.cross(perpAxisA), TmpVectors.Matrix[0]));
  763. const rotTransformChild = Quaternion.FromRotationMatrix(Matrix.FromXYZAxesToRef(axisB, perpAxisB, axisB.cross(perpAxisB), TmpVectors.Matrix[0]));
  764. const translateTransformParent = pivotA;
  765. const translateTransformChild = pivotB;
  766. // Create a transform node and set its matrix
  767. const parentTransformNode = new TransformNode("constraint_parent", utilityLayerScene);
  768. parentTransformNode.position.copyFrom(translateTransformParent);
  769. parentTransformNode.rotationQuaternion = rotTransformParent;
  770. parentTransformNode.parent = parentCoordSystemNode;
  771. const childTransformNode = new TransformNode("constraint_child", utilityLayerScene);
  772. childTransformNode.parent = childCoordSystemNode;
  773. childTransformNode.position.copyFrom(translateTransformChild);
  774. childTransformNode.rotationQuaternion = rotTransformChild;
  775. // Create axes for the constraint
  776. const parentAxes = new AxesViewer(utilityLayerScene, this._constraintAxesSize);
  777. parentAxes.xAxis.parent = parentTransformNode;
  778. parentAxes.yAxis.parent = parentTransformNode;
  779. parentAxes.zAxis.parent = parentTransformNode;
  780. const childAxes = new AxesViewer(utilityLayerScene, this._constraintAxesSize);
  781. childAxes.xAxis.parent = childTransformNode;
  782. childAxes.yAxis.parent = childTransformNode;
  783. childAxes.zAxis.parent = childTransformNode;
  784. }
  785. return parentingMesh;
  786. }
  787. /**
  788. * Clean up physics debug display
  789. */
  790. dispose() {
  791. // impostors
  792. for (let index = this._numMeshes - 1; index >= 0; index--) {
  793. this.hideImpostor(this._impostors[0]);
  794. }
  795. // bodies
  796. for (let index = this._numBodies - 1; index >= 0; index--) {
  797. this.hideBody(this._bodies[0]);
  798. }
  799. // inertia
  800. for (let index = this._numInertiaBodies - 1; index >= 0; index--) {
  801. this.hideInertia(this._inertiaBodies[0]);
  802. }
  803. if (this._debugBoxMesh) {
  804. this._debugBoxMesh.dispose();
  805. }
  806. if (this._debugSphereMesh) {
  807. this._debugSphereMesh.dispose();
  808. }
  809. if (this._debugCylinderMesh) {
  810. this._debugCylinderMesh.dispose();
  811. }
  812. if (this._debugMaterial) {
  813. this._debugMaterial.dispose();
  814. }
  815. this._impostors.length = 0;
  816. this._scene = null;
  817. this._physicsEnginePlugin = null;
  818. if (this._utilityLayer) {
  819. this._utilityLayer.dispose();
  820. this._utilityLayer = null;
  821. }
  822. }
  823. }
  824. //# sourceMappingURL=physicsViewer.js.map