skeletonViewer.ts 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873
  1. import { Vector3, Matrix, TmpVectors } from "../Maths/math.vector";
  2. import { Color3, Color4 } from '../Maths/math.color';
  3. import { Scene } from "../scene";
  4. import { Nullable } from "../types";
  5. import { Bone } from "../Bones/bone";
  6. import { Skeleton } from "../Bones/skeleton";
  7. import { AbstractMesh } from "../Meshes/abstractMesh";
  8. import { Mesh } from "../Meshes/mesh";
  9. import { LinesMesh } from "../Meshes/linesMesh";
  10. import { LinesBuilder } from "../Meshes/Builders/linesBuilder";
  11. import { UtilityLayerRenderer } from "../Rendering/utilityLayerRenderer";
  12. import { Material } from '../Materials/material';
  13. import { ShaderMaterial } from '../Materials/shaderMaterial';
  14. import { DynamicTexture } from '../Materials/Textures/dynamicTexture';
  15. import { VertexBuffer } from '../Meshes/buffer';
  16. import { Effect } from '../Materials/effect';
  17. import { ISkeletonViewerOptions, IBoneWeightShaderOptions, ISkeletonMapShaderOptions, ISkeletonMapShaderColorMapKnot } from './ISkeletonViewer';
  18. import { Observer } from '../Misc/observable';
  19. import { SphereBuilder } from '../Meshes/Builders/sphereBuilder';
  20. import { ShapeBuilder } from '../Meshes/Builders/shapeBuilder';
  21. import { MeshBuilder } from '../Meshes/meshBuilder';
  22. /**
  23. * Class used to render a debug view of a given skeleton
  24. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  25. */
  26. export class SkeletonViewer {
  27. /** public Display constants BABYLON.SkeletonViewer.DISPLAY_LINES */
  28. public static readonly DISPLAY_LINES = 0;
  29. /** public Display constants BABYLON.SkeletonViewer.DISPLAY_SPHERES */
  30. public static readonly DISPLAY_SPHERES = 1;
  31. /** public Display constants BABYLON.SkeletonViewer.DISPLAY_SPHERE_AND_SPURS */
  32. public static readonly DISPLAY_SPHERE_AND_SPURS = 2;
  33. /** public static method to create a BoneWeight Shader
  34. * @param options The constructor options
  35. * @param scene The scene that the shader is scoped to
  36. * @returns The created ShaderMaterial
  37. * @see http://www.babylonjs-playground.com/#1BZJVJ#395
  38. */
  39. static CreateBoneWeightShader(options: IBoneWeightShaderOptions, scene: Scene): ShaderMaterial {
  40. let skeleton: Skeleton = options.skeleton;
  41. let colorBase: Color3 = options.colorBase ?? Color3.Black();
  42. let colorZero: Color3 = options.colorZero ?? Color3.Blue();
  43. let colorQuarter: Color3 = options.colorQuarter ?? Color3.Green();
  44. let colorHalf: Color3 = options.colorHalf ?? Color3.Yellow();
  45. let colorFull: Color3 = options.colorFull ?? Color3.Red();
  46. let targetBoneIndex: number = options.targetBoneIndex ?? 0;
  47. Effect.ShadersStore['boneWeights:' + skeleton.name + "VertexShader"] =
  48. `precision highp float;
  49. attribute vec3 position;
  50. attribute vec2 uv;
  51. uniform mat4 view;
  52. uniform mat4 projection;
  53. uniform mat4 worldViewProjection;
  54. #include<bonesDeclaration>
  55. #include<instancesDeclaration>
  56. varying vec3 vColor;
  57. uniform vec3 colorBase;
  58. uniform vec3 colorZero;
  59. uniform vec3 colorQuarter;
  60. uniform vec3 colorHalf;
  61. uniform vec3 colorFull;
  62. uniform float targetBoneIndex;
  63. void main() {
  64. vec3 positionUpdated = position;
  65. #include<instancesVertex>
  66. #include<bonesVertex>
  67. vec4 worldPos = finalWorld * vec4(positionUpdated, 1.0);
  68. vec3 color = colorBase;
  69. float totalWeight = 0.;
  70. if(matricesIndices[0] == targetBoneIndex && matricesWeights[0] > 0.){
  71. totalWeight += matricesWeights[0];
  72. }
  73. if(matricesIndices[1] == targetBoneIndex && matricesWeights[1] > 0.){
  74. totalWeight += matricesWeights[1];
  75. }
  76. if(matricesIndices[2] == targetBoneIndex && matricesWeights[2] > 0.){
  77. totalWeight += matricesWeights[2];
  78. }
  79. if(matricesIndices[3] == targetBoneIndex && matricesWeights[3] > 0.){
  80. totalWeight += matricesWeights[3];
  81. }
  82. color = mix(color, colorZero, smoothstep(0., 0.25, totalWeight));
  83. color = mix(color, colorQuarter, smoothstep(0.25, 0.5, totalWeight));
  84. color = mix(color, colorHalf, smoothstep(0.5, 0.75, totalWeight));
  85. color = mix(color, colorFull, smoothstep(0.75, 1.0, totalWeight));
  86. vColor = color;
  87. gl_Position = projection * view * worldPos;
  88. }`;
  89. Effect.ShadersStore['boneWeights:' + skeleton.name + "FragmentShader"] =
  90. `
  91. precision highp float;
  92. varying vec3 vPosition;
  93. varying vec3 vColor;
  94. void main() {
  95. vec4 color = vec4(vColor, 1.0);
  96. gl_FragColor = color;
  97. }
  98. `;
  99. let shader: ShaderMaterial = new ShaderMaterial('boneWeight:' + skeleton.name, scene,
  100. {
  101. vertex: 'boneWeights:' + skeleton.name,
  102. fragment: 'boneWeights:' + skeleton.name
  103. },
  104. {
  105. attributes: ['position', 'normal'],
  106. uniforms: [
  107. 'world', 'worldView', 'worldViewProjection', 'view', 'projection', 'viewProjection',
  108. 'colorBase', 'colorZero', 'colorQuarter', 'colorHalf', 'colorFull', 'targetBoneIndex'
  109. ]
  110. });
  111. shader.setColor3('colorBase', colorBase);
  112. shader.setColor3('colorZero', colorZero);
  113. shader.setColor3('colorQuarter', colorQuarter);
  114. shader.setColor3('colorHalf', colorHalf);
  115. shader.setColor3('colorFull', colorFull);
  116. shader.setFloat('targetBoneIndex', targetBoneIndex);
  117. shader.getClassName = (): string => {
  118. return "BoneWeightShader";
  119. };
  120. shader.transparencyMode = Material.MATERIAL_OPAQUE;
  121. return shader;
  122. }
  123. /** public static method to create a BoneWeight Shader
  124. * @param options The constructor options
  125. * @param scene The scene that the shader is scoped to
  126. * @returns The created ShaderMaterial
  127. */
  128. static CreateSkeletonMapShader(options: ISkeletonMapShaderOptions, scene: Scene) {
  129. let skeleton: Skeleton = options.skeleton;
  130. let colorMap: ISkeletonMapShaderColorMapKnot[] = options.colorMap ?? [
  131. {
  132. color: new Color3(1, 0.38, 0.18),
  133. location : 0
  134. },
  135. {
  136. color: new Color3(.59, 0.18, 1.00),
  137. location : 0.2
  138. },
  139. {
  140. color: new Color3(0.59, 1, 0.18),
  141. location : 0.4
  142. },
  143. {
  144. color: new Color3(1, 0.87, 0.17),
  145. location : 0.6
  146. },
  147. {
  148. color: new Color3(1, 0.17, 0.42),
  149. location : 0.8
  150. },
  151. {
  152. color: new Color3(0.17, 0.68, 1.0),
  153. location : 1.0
  154. }
  155. ];
  156. let bufferWidth: number = skeleton.bones.length + 1;
  157. let colorMapBuffer: number[] = SkeletonViewer._CreateBoneMapColorBuffer(bufferWidth, colorMap, scene);
  158. let shader = new ShaderMaterial('boneWeights:' + skeleton.name, scene,
  159. {
  160. vertexSource:
  161. `precision highp float;
  162. attribute vec3 position;
  163. attribute vec2 uv;
  164. uniform mat4 view;
  165. uniform mat4 projection;
  166. uniform mat4 worldViewProjection;
  167. uniform float colorMap[` + ((skeleton.bones.length) * 4) + `];
  168. #include<bonesDeclaration>
  169. #include<instancesDeclaration>
  170. varying vec3 vColor;
  171. void main() {
  172. vec3 positionUpdated = position;
  173. #include<instancesVertex>
  174. #include<bonesVertex>
  175. vec3 color = vec3(0.);
  176. bool first = true;
  177. for (int i = 0; i < 4; i++) {
  178. int boneIdx = int(matricesIndices[i]);
  179. float boneWgt = matricesWeights[i];
  180. vec3 c = vec3(colorMap[boneIdx * 4 + 0], colorMap[boneIdx * 4 + 1], colorMap[boneIdx * 4 + 2]);
  181. if (boneWgt > 0.) {
  182. if (first) {
  183. first = false;
  184. color = c;
  185. } else {
  186. color = mix(color, c, boneWgt);
  187. }
  188. }
  189. }
  190. vColor = color;
  191. vec4 worldPos = finalWorld * vec4(positionUpdated, 1.0);
  192. gl_Position = projection * view * worldPos;
  193. }`,
  194. fragmentSource:
  195. `
  196. precision highp float;
  197. varying vec3 vColor;
  198. void main() {
  199. vec4 color = vec4( vColor, 1.0 );
  200. gl_FragColor = color;
  201. }
  202. `
  203. },
  204. {
  205. attributes: ['position', 'normal'],
  206. uniforms: [
  207. 'world', 'worldView', 'worldViewProjection', 'view', 'projection', 'viewProjection',
  208. 'colorMap'
  209. ]
  210. });
  211. shader.setFloats('colorMap', colorMapBuffer);
  212. shader.getClassName = (): string => {
  213. return "SkeletonMapShader";
  214. };
  215. shader.transparencyMode = Material.MATERIAL_OPAQUE;
  216. return shader;
  217. }
  218. /** private static method to create a BoneWeight Shader
  219. * @param size The size of the buffer to create (usually the bone count)
  220. * @param colorMap The gradient data to generate
  221. * @param scene The scene that the shader is scoped to
  222. * @returns an Array of floats from the color gradient values
  223. */
  224. private static _CreateBoneMapColorBuffer(size: number, colorMap: ISkeletonMapShaderColorMapKnot[], scene: Scene) {
  225. let tempGrad = new DynamicTexture('temp', {width: size, height: 1}, scene, false);
  226. let ctx = tempGrad.getContext();
  227. let grad = ctx.createLinearGradient(0, 0, size, 0);
  228. colorMap.forEach((stop) => {
  229. grad.addColorStop(stop.location, stop.color.toHexString());
  230. });
  231. ctx.fillStyle = grad;
  232. ctx.fillRect(0, 0, size, 1);
  233. tempGrad.update();
  234. let buffer: number[] = [];
  235. let data: Uint8ClampedArray = ctx.getImageData(0, 0, size, 1).data;
  236. let rUnit = 1 / 255;
  237. for (let i = 0; i < data.length; i++) {
  238. buffer.push(data[i] * rUnit);
  239. }
  240. tempGrad.dispose();
  241. return buffer;
  242. }
  243. /** If SkeletonViewer scene scope. */
  244. private _scene : Scene;
  245. /** Gets or sets the color used to render the skeleton */
  246. public color: Color3 = Color3.White();
  247. /** Array of the points of the skeleton fo the line view. */
  248. private _debugLines = new Array<Array<Vector3>>();
  249. /** The SkeletonViewers Mesh. */
  250. private _debugMesh: Nullable<LinesMesh>;
  251. /** The local axes Meshes. */
  252. private _localAxes: Nullable<LinesMesh> = null;
  253. /** If SkeletonViewer is enabled. */
  254. private _isEnabled = false;
  255. /** If SkeletonViewer is ready. */
  256. private _ready : boolean;
  257. /** SkeletonViewer render observable. */
  258. private _obs: Nullable<Observer<Scene>> = null;
  259. /** The Utility Layer to render the gizmos in. */
  260. private _utilityLayer: Nullable<UtilityLayerRenderer>;
  261. private _boneIndices: Set<number>;
  262. /** Gets the Scene. */
  263. get scene(): Scene {
  264. return this._scene;
  265. }
  266. /** Gets the utilityLayer. */
  267. get utilityLayer(): Nullable<UtilityLayerRenderer> {
  268. return this._utilityLayer;
  269. }
  270. /** Checks Ready Status. */
  271. get isReady(): Boolean {
  272. return this._ready;
  273. }
  274. /** Sets Ready Status. */
  275. set ready(value: boolean) {
  276. this._ready = value;
  277. }
  278. /** Gets the debugMesh */
  279. get debugMesh(): Nullable<AbstractMesh> | Nullable<LinesMesh> {
  280. return this._debugMesh;
  281. }
  282. /** Sets the debugMesh */
  283. set debugMesh(value: Nullable<AbstractMesh> | Nullable<LinesMesh>) {
  284. this._debugMesh = (value as any);
  285. }
  286. /** Gets the displayMode */
  287. get displayMode(): number {
  288. return this.options.displayMode || SkeletonViewer.DISPLAY_LINES;
  289. }
  290. /** Sets the displayMode */
  291. set displayMode(value: number) {
  292. if (value > SkeletonViewer.DISPLAY_SPHERE_AND_SPURS) {
  293. value = SkeletonViewer.DISPLAY_LINES;
  294. }
  295. this.options.displayMode = value;
  296. }
  297. /**
  298. * Creates a new SkeletonViewer
  299. * @param skeleton defines the skeleton to render
  300. * @param mesh defines the mesh attached to the skeleton
  301. * @param scene defines the hosting scene
  302. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  303. * @param renderingGroupId defines the rendering group id to use with the viewer
  304. * @param options All of the extra constructor options for the SkeletonViewer
  305. */
  306. constructor(
  307. /** defines the skeleton to render */
  308. public skeleton: Skeleton,
  309. /** defines the mesh attached to the skeleton */
  310. public mesh: AbstractMesh,
  311. /** The Scene scope*/
  312. scene: Scene,
  313. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  314. public autoUpdateBonesMatrices: boolean = true,
  315. /** defines the rendering group id to use with the viewer */
  316. public renderingGroupId: number = 3,
  317. /** is the options for the viewer */
  318. public options: Partial<ISkeletonViewerOptions> = {}
  319. ) {
  320. this._scene = scene;
  321. this._ready = false;
  322. //Defaults
  323. options.pauseAnimations = options.pauseAnimations ?? true;
  324. options.returnToRest = options.returnToRest ?? false;
  325. options.displayMode = options.displayMode ?? SkeletonViewer.DISPLAY_LINES;
  326. options.displayOptions = options.displayOptions ?? {};
  327. options.displayOptions.midStep = options.displayOptions.midStep ?? 0.235;
  328. options.displayOptions.midStepFactor = options.displayOptions.midStepFactor ?? 0.155;
  329. options.displayOptions.sphereBaseSize = options.displayOptions.sphereBaseSize ?? 0.15;
  330. options.displayOptions.sphereScaleUnit = options.displayOptions.sphereScaleUnit ?? 2;
  331. options.displayOptions.sphereFactor = options.displayOptions.sphereFactor ?? 0.865;
  332. options.displayOptions.showLocalAxes = options.displayOptions.showLocalAxes ?? false;
  333. options.displayOptions.localAxesSize = options.displayOptions.localAxesSize ?? 0.075;
  334. options.computeBonesUsingShaders = options.computeBonesUsingShaders ?? true;
  335. options.useAllBones = options.useAllBones ?? true;
  336. const initialMeshBoneIndices = mesh.getVerticesData(VertexBuffer.MatricesIndicesKind);
  337. const initialMeshBoneWeights = mesh.getVerticesData(VertexBuffer.MatricesWeightsKind);
  338. this._boneIndices = new Set();
  339. if (!options.useAllBones) {
  340. if (initialMeshBoneIndices && initialMeshBoneWeights) {
  341. for (let i = 0; i < initialMeshBoneIndices.length; ++i) {
  342. const index = initialMeshBoneIndices[i], weight = initialMeshBoneWeights[i];
  343. if (weight !== 0) {
  344. this._boneIndices.add(index);
  345. }
  346. }
  347. }
  348. }
  349. /* Create Utility Layer */
  350. this._utilityLayer = new UtilityLayerRenderer(this._scene, false);
  351. this._utilityLayer.pickUtilitySceneFirst = false;
  352. this._utilityLayer.utilityLayerScene.autoClearDepthAndStencil = true;
  353. let displayMode = this.options.displayMode || 0;
  354. if (displayMode > SkeletonViewer.DISPLAY_SPHERE_AND_SPURS) {
  355. displayMode = SkeletonViewer.DISPLAY_LINES;
  356. }
  357. this.displayMode = displayMode;
  358. //Prep the Systems
  359. this.update();
  360. this._bindObs();
  361. }
  362. /** The Dynamic bindings for the update functions */
  363. private _bindObs(): void {
  364. switch (this.displayMode){
  365. case SkeletonViewer.DISPLAY_LINES: {
  366. this._obs = this.scene.onBeforeRenderObservable.add(() => {
  367. this._displayLinesUpdate();
  368. });
  369. break;
  370. }
  371. }
  372. }
  373. /** Update the viewer to sync with current skeleton state, only used to manually update. */
  374. public update(): void {
  375. switch (this.displayMode){
  376. case SkeletonViewer.DISPLAY_LINES: {
  377. this._displayLinesUpdate();
  378. break;
  379. }
  380. case SkeletonViewer.DISPLAY_SPHERES: {
  381. this._buildSpheresAndSpurs(true);
  382. break;
  383. }
  384. case SkeletonViewer.DISPLAY_SPHERE_AND_SPURS: {
  385. this._buildSpheresAndSpurs(false);
  386. break;
  387. }
  388. }
  389. this._buildLocalAxes();
  390. }
  391. /** Gets or sets a boolean indicating if the viewer is enabled */
  392. public set isEnabled(value: boolean) {
  393. if (this.isEnabled === value) {
  394. return;
  395. }
  396. this._isEnabled = value;
  397. if (this.debugMesh) {
  398. this.debugMesh.setEnabled(value);
  399. }
  400. if (value && !this._obs) {
  401. this._bindObs();
  402. } else if (!value && this._obs) {
  403. this.scene.onBeforeRenderObservable.remove(this._obs);
  404. this._obs = null;
  405. }
  406. }
  407. public get isEnabled(): boolean {
  408. return this._isEnabled;
  409. }
  410. private _getBonePosition(position: Vector3, bone: Bone, meshMat: Matrix, x = 0, y = 0, z = 0): void {
  411. var tmat = TmpVectors.Matrix[0];
  412. var parentBone = bone.getParent();
  413. tmat.copyFrom(bone.getLocalMatrix());
  414. if (x !== 0 || y !== 0 || z !== 0) {
  415. var tmat2 = TmpVectors.Matrix[1];
  416. Matrix.IdentityToRef(tmat2);
  417. tmat2.setTranslationFromFloats(x, y, z);
  418. tmat2.multiplyToRef(tmat, tmat);
  419. }
  420. if (parentBone) {
  421. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  422. }
  423. tmat.multiplyToRef(meshMat, tmat);
  424. position.x = tmat.m[12];
  425. position.y = tmat.m[13];
  426. position.z = tmat.m[14];
  427. }
  428. private _getLinesForBonesWithLength(bones: Bone[], meshMat: Matrix): void {
  429. var len = bones.length;
  430. let mesh = this.mesh._effectiveMesh;
  431. var meshPos = mesh.position;
  432. let idx = 0;
  433. for (var i = 0; i < len; i++) {
  434. var bone = bones[i];
  435. var points = this._debugLines[idx];
  436. if (bone._index === -1 || (!this._boneIndices.has(bone.getIndex()) && !this.options.useAllBones)) {
  437. continue;
  438. }
  439. if (!points) {
  440. points = [Vector3.Zero(), Vector3.Zero()];
  441. this._debugLines[idx] = points;
  442. }
  443. this._getBonePosition(points[0], bone, meshMat);
  444. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  445. points[0].subtractInPlace(meshPos);
  446. points[1].subtractInPlace(meshPos);
  447. idx++;
  448. }
  449. }
  450. private _getLinesForBonesNoLength(bones: Bone[]): void {
  451. var len = bones.length;
  452. var boneNum = 0;
  453. let mesh = this.mesh._effectiveMesh;
  454. var meshPos = mesh.position;
  455. for (var i = len - 1; i >= 0; i--) {
  456. var childBone = bones[i];
  457. var parentBone = childBone.getParent();
  458. if (!parentBone || (!this._boneIndices.has(childBone.getIndex()) && !this.options.useAllBones)) {
  459. continue;
  460. }
  461. var points = this._debugLines[boneNum];
  462. if (!points) {
  463. points = [Vector3.Zero(), Vector3.Zero()];
  464. this._debugLines[boneNum] = points;
  465. }
  466. childBone.getAbsolutePositionToRef(mesh, points[0]);
  467. parentBone.getAbsolutePositionToRef(mesh, points[1]);
  468. points[0].subtractInPlace(meshPos);
  469. points[1].subtractInPlace(meshPos);
  470. boneNum++;
  471. }
  472. }
  473. /** function to revert the mesh and scene back to the initial state. */
  474. private _revert(animationState: boolean): void {
  475. if (this.options.pauseAnimations) {
  476. this.scene.animationsEnabled = animationState;
  477. }
  478. }
  479. /** function to build and bind sphere joint points and spur bone representations. */
  480. private _buildSpheresAndSpurs(spheresOnly = true): void {
  481. if (this._debugMesh) {
  482. this._debugMesh.dispose();
  483. this._debugMesh = null;
  484. this.ready = false;
  485. }
  486. this._ready = false;
  487. let scene = this.scene;
  488. let bones: Bone[] = this.skeleton.bones;
  489. let spheres: Array<[Mesh, Bone]> = [];
  490. let spurs: Mesh[] = [];
  491. const animationState = scene.animationsEnabled;
  492. try {
  493. if (this.options.pauseAnimations) {
  494. scene.animationsEnabled = false;
  495. }
  496. if (this.options.returnToRest) {
  497. this.skeleton.returnToRest();
  498. }
  499. if (this.autoUpdateBonesMatrices) {
  500. this.skeleton.computeAbsoluteTransforms();
  501. }
  502. let longestBoneLength = Number.NEGATIVE_INFINITY;
  503. let getAbsoluteRestPose = function(bone: Nullable<Bone>, matrix: Matrix) {
  504. if (bone === null || bone._index === -1) {
  505. matrix.copyFrom(Matrix.Identity());
  506. return;
  507. }
  508. getAbsoluteRestPose(bone.getParent(), matrix);
  509. bone.getBindPose().multiplyToRef(matrix, matrix);
  510. return;
  511. };
  512. let displayOptions = this.options.displayOptions || {};
  513. for (let i = 0; i < bones.length; i++) {
  514. let bone = bones[i];
  515. if (bone._index === -1 || (!this._boneIndices.has(bone.getIndex()) && !this.options.useAllBones)) {
  516. continue;
  517. }
  518. let boneAbsoluteRestTransform = new Matrix();
  519. getAbsoluteRestPose(bone, boneAbsoluteRestTransform);
  520. let anchorPoint = new Vector3();
  521. boneAbsoluteRestTransform.decompose(undefined, undefined, anchorPoint);
  522. bone.children.forEach((bc, i) => {
  523. let childAbsoluteRestTransform : Matrix = new Matrix();
  524. bc.getRestPose().multiplyToRef(boneAbsoluteRestTransform, childAbsoluteRestTransform);
  525. let childPoint = new Vector3();
  526. childAbsoluteRestTransform.decompose(undefined, undefined, childPoint);
  527. let distanceFromParent = Vector3.Distance(anchorPoint, childPoint);
  528. if (distanceFromParent > longestBoneLength) {
  529. longestBoneLength = distanceFromParent;
  530. }
  531. if (spheresOnly) {
  532. return;
  533. }
  534. let dir = childPoint.clone().subtract(anchorPoint.clone());
  535. let h = dir.length();
  536. let up = dir.normalize().scale(h);
  537. let midStep = displayOptions.midStep || 0.165;
  538. let midStepFactor = displayOptions.midStepFactor || 0.215;
  539. let up0 = up.scale(midStep);
  540. let spur = ShapeBuilder.ExtrudeShapeCustom('skeletonViewer',
  541. {
  542. shape: [
  543. new Vector3(1, -1, 0),
  544. new Vector3(1, 1, 0),
  545. new Vector3(-1, 1, 0),
  546. new Vector3(-1, -1, 0),
  547. new Vector3(1, -1, 0)
  548. ],
  549. path: [ Vector3.Zero(), up0, up ],
  550. scaleFunction:
  551. (i: number) => {
  552. switch (i){
  553. case 0:
  554. case 2:
  555. return 0;
  556. case 1:
  557. return h * midStepFactor;
  558. }
  559. return 0;
  560. },
  561. sideOrientation: Mesh.DEFAULTSIDE,
  562. updatable: false
  563. }, scene);
  564. spur.convertToFlatShadedMesh();
  565. let numVertices = spur.getTotalVertices();
  566. let mwk: number[] = [], mik: number[] = [];
  567. for (let i = 0; i < numVertices; i++) {
  568. mwk.push(1, 0, 0, 0);
  569. mik.push(bone.getIndex(), 0, 0, 0);
  570. }
  571. spur.position = anchorPoint.clone();
  572. spur.setVerticesData(VertexBuffer.MatricesWeightsKind, mwk, false);
  573. spur.setVerticesData(VertexBuffer.MatricesIndicesKind, mik, false);
  574. spurs.push(spur);
  575. });
  576. let sphereBaseSize = displayOptions.sphereBaseSize || 0.2;
  577. let sphere = SphereBuilder.CreateSphere('skeletonViewer', {
  578. segments: 6,
  579. diameter: sphereBaseSize,
  580. updatable: true
  581. }, scene);
  582. const numVertices = sphere.getTotalVertices();
  583. let mwk: number[] = [], mik: number[] = [];
  584. for (let i = 0; i < numVertices; i++) {
  585. mwk.push(1, 0, 0, 0);
  586. mik.push(bone.getIndex(), 0, 0, 0);
  587. }
  588. sphere.setVerticesData(VertexBuffer.MatricesWeightsKind, mwk, false);
  589. sphere.setVerticesData(VertexBuffer.MatricesIndicesKind, mik, false);
  590. sphere.position = anchorPoint.clone();
  591. spheres.push([sphere, bone]);
  592. }
  593. let sphereScaleUnit = displayOptions.sphereScaleUnit || 2;
  594. let sphereFactor = displayOptions.sphereFactor || 0.85;
  595. const meshes = [];
  596. for (let i = 0; i < spheres.length; i++) {
  597. let [sphere, bone] = spheres[i];
  598. let scale = 1 / (sphereScaleUnit / longestBoneLength);
  599. let _stepsOut = 0;
  600. let _b = bone;
  601. while ((_b.getParent()) && (_b.getParent() as Bone).getIndex() !== -1) {
  602. _stepsOut++;
  603. _b = (_b.getParent() as Bone);
  604. }
  605. sphere.scaling.scaleInPlace(scale * Math.pow(sphereFactor, _stepsOut));
  606. meshes.push(sphere);
  607. }
  608. this.debugMesh = Mesh.MergeMeshes(meshes.concat(spurs), true, true);
  609. if (this.debugMesh) {
  610. this.debugMesh.renderingGroupId = this.renderingGroupId;
  611. this.debugMesh.skeleton = this.skeleton;
  612. this.debugMesh.parent = this.mesh;
  613. this.debugMesh.computeBonesUsingShaders = this.options.computeBonesUsingShaders ?? true;
  614. this.debugMesh.alwaysSelectAsActiveMesh = true;
  615. }
  616. this._revert(animationState);
  617. this.ready = true;
  618. } catch (err) {
  619. console.error(err);
  620. this._revert(animationState);
  621. this.dispose();
  622. }
  623. }
  624. private _buildLocalAxes(): void {
  625. if (this._localAxes) {
  626. this._localAxes.dispose();
  627. }
  628. this._localAxes = null;
  629. let displayOptions = this.options.displayOptions || {};
  630. if (!displayOptions.showLocalAxes) {
  631. return;
  632. }
  633. const targetScene = this._utilityLayer!.utilityLayerScene;
  634. const size = displayOptions.localAxesSize || 0.075;
  635. for (let b of this.skeleton.bones) {
  636. if (b._index === -1 || (!this._boneIndices.has(b.getIndex()) && !this.options.useAllBones)) {
  637. continue;
  638. }
  639. let lines = [
  640. [Vector3.Zero(), new Vector3(size, 0, 0)],
  641. [Vector3.Zero(), new Vector3(0, size, 0)],
  642. [Vector3.Zero(), new Vector3(0, 0, size)]
  643. ];
  644. let red = new Color4(1, 0, 0, 1);
  645. let green = new Color4(0, 1, 0, 1);
  646. let blue = new Color4(0, 0, 1, 1);
  647. let colors = [[red, red], [green, green], [blue, blue]];
  648. this._localAxes = MeshBuilder.CreateLineSystem('localAxes', { lines: lines, colors: colors, updatable: true }, targetScene);
  649. if (this.displayMode === SkeletonViewer.DISPLAY_LINES && !this._localAxes.skeleton) {
  650. // The local axes needs a mesh. Since the world matrix of a bone is not recalculated unless its
  651. // skeleton is applied to at least one mesh. For the other display mode we don't have this issue.
  652. this._localAxes.skeleton = this.skeleton;
  653. }
  654. this._localAxes.parent = b;
  655. this._localAxes.renderingGroupId = this.renderingGroupId;
  656. }
  657. }
  658. /** Update the viewer to sync with current skeleton state, only used for the line display. */
  659. private _displayLinesUpdate(): void {
  660. if (!this._utilityLayer) {
  661. return;
  662. }
  663. if (this.autoUpdateBonesMatrices) {
  664. this.skeleton.computeAbsoluteTransforms();
  665. }
  666. let mesh = this.mesh._effectiveMesh;
  667. if (this.skeleton.bones[0].length === undefined) {
  668. this._getLinesForBonesNoLength(this.skeleton.bones);
  669. } else {
  670. this._getLinesForBonesWithLength(this.skeleton.bones, mesh.getWorldMatrix());
  671. }
  672. const targetScene = this._utilityLayer.utilityLayerScene;
  673. if (targetScene) {
  674. if (!this._debugMesh) {
  675. this._debugMesh = LinesBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, targetScene);
  676. this._debugMesh.renderingGroupId = this.renderingGroupId;
  677. } else {
  678. LinesBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, targetScene);
  679. }
  680. this._debugMesh.position.copyFrom(this.mesh.position);
  681. this._debugMesh.color = this.color;
  682. }
  683. }
  684. /** Changes the displayMode of the skeleton viewer
  685. * @param mode The displayMode numerical value
  686. */
  687. public changeDisplayMode(mode: number): void {
  688. let wasEnabled = (this.isEnabled) ? true : false;
  689. if (this.displayMode !== mode) {
  690. this.isEnabled = false;
  691. if (this._debugMesh) {
  692. this._debugMesh.dispose();
  693. this._debugMesh = null;
  694. this.ready = false;
  695. }
  696. this.displayMode = mode;
  697. this.update();
  698. this._bindObs();
  699. this.isEnabled = wasEnabled;
  700. }
  701. }
  702. /** Changes the displayMode of the skeleton viewer
  703. * @param option String of the option name
  704. * @param value The numerical option value
  705. */
  706. public changeDisplayOptions(option: string, value: number): void {
  707. let wasEnabled = (this.isEnabled) ? true : false;
  708. (this.options.displayOptions as any)[option] = value;
  709. this.isEnabled = false;
  710. if (this._debugMesh) {
  711. this._debugMesh.dispose();
  712. this._debugMesh = null;
  713. this.ready = false;
  714. }
  715. this.update();
  716. this._bindObs();
  717. this.isEnabled = wasEnabled;
  718. }
  719. /** Release associated resources */
  720. public dispose(): void {
  721. this.isEnabled = false;
  722. if (this._debugMesh) {
  723. this._debugMesh.dispose();
  724. this._debugMesh = null;
  725. }
  726. if (this._utilityLayer) {
  727. this._utilityLayer.dispose();
  728. this._utilityLayer = null;
  729. }
  730. this.ready = false;
  731. }
  732. }