skeletonViewer.ts 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918
  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. /**
  22. * Class used to render a debug view of a given skeleton
  23. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  24. */
  25. export class SkeletonViewer {
  26. /** public Display constants BABYLON.SkeletonViewer.DISPLAY_LINES */
  27. public static readonly DISPLAY_LINES = 0;
  28. /** public Display constants BABYLON.SkeletonViewer.DISPLAY_SPHERES */
  29. public static readonly DISPLAY_SPHERES = 1;
  30. /** public Display constants BABYLON.SkeletonViewer.DISPLAY_SPHERE_AND_SPURS */
  31. public static readonly DISPLAY_SPHERE_AND_SPURS = 2;
  32. /** public static method to create a BoneWeight Shader
  33. * @param options The constructor options
  34. * @param scene The scene that the shader is scoped to
  35. * @returns The created ShaderMaterial
  36. * @see http://www.babylonjs-playground.com/#1BZJVJ#395
  37. */
  38. static CreateBoneWeightShader(options: IBoneWeightShaderOptions, scene: Scene): ShaderMaterial {
  39. let skeleton: Skeleton = options.skeleton;
  40. let colorBase: Color3 = options.colorBase ?? Color3.Black();
  41. let colorZero: Color3 = options.colorZero ?? Color3.Blue();
  42. let colorQuarter: Color3 = options.colorQuarter ?? Color3.Green();
  43. let colorHalf: Color3 = options.colorHalf ?? Color3.Yellow();
  44. let colorFull: Color3 = options.colorFull ?? Color3.Red();
  45. let targetBoneIndex: number = options.targetBoneIndex ?? 0;
  46. Effect.ShadersStore['boneWeights:' + skeleton.name + "VertexShader"] =
  47. `precision highp float;
  48. attribute vec3 position;
  49. attribute vec2 uv;
  50. uniform mat4 view;
  51. uniform mat4 projection;
  52. uniform mat4 worldViewProjection;
  53. #include<bonesDeclaration>
  54. #include<instancesDeclaration>
  55. varying vec3 vColor;
  56. uniform vec3 colorBase;
  57. uniform vec3 colorZero;
  58. uniform vec3 colorQuarter;
  59. uniform vec3 colorHalf;
  60. uniform vec3 colorFull;
  61. uniform float targetBoneIndex;
  62. void main() {
  63. vec3 positionUpdated = position;
  64. #include<instancesVertex>
  65. #include<bonesVertex>
  66. vec4 worldPos = finalWorld * vec4(positionUpdated, 1.0);
  67. vec3 color = colorBase;
  68. float totalWeight = 0.;
  69. if(matricesIndices[0] == targetBoneIndex && matricesWeights[0] > 0.){
  70. totalWeight += matricesWeights[0];
  71. }
  72. if(matricesIndices[1] == targetBoneIndex && matricesWeights[1] > 0.){
  73. totalWeight += matricesWeights[1];
  74. }
  75. if(matricesIndices[2] == targetBoneIndex && matricesWeights[2] > 0.){
  76. totalWeight += matricesWeights[2];
  77. }
  78. if(matricesIndices[3] == targetBoneIndex && matricesWeights[3] > 0.){
  79. totalWeight += matricesWeights[3];
  80. }
  81. color = mix(color, colorZero, smoothstep(0., 0.25, totalWeight));
  82. color = mix(color, colorQuarter, smoothstep(0.25, 0.5, totalWeight));
  83. color = mix(color, colorHalf, smoothstep(0.5, 0.75, totalWeight));
  84. color = mix(color, colorFull, smoothstep(0.75, 1.0, totalWeight));
  85. vColor = color;
  86. gl_Position = projection * view * worldPos;
  87. }`;
  88. Effect.ShadersStore['boneWeights:' + skeleton.name + "FragmentShader"] =
  89. `
  90. precision highp float;
  91. varying vec3 vPosition;
  92. varying vec3 vColor;
  93. void main() {
  94. vec4 color = vec4(vColor, 1.0);
  95. gl_FragColor = color;
  96. }
  97. `;
  98. let shader: ShaderMaterial = new ShaderMaterial('boneWeight:' + skeleton.name, scene,
  99. {
  100. vertex: 'boneWeights:' + skeleton.name,
  101. fragment: 'boneWeights:' + skeleton.name
  102. },
  103. {
  104. attributes: ['position', 'normal'],
  105. uniforms: [
  106. 'world', 'worldView', 'worldViewProjection', 'view', 'projection', 'viewProjection',
  107. 'colorBase', 'colorZero', 'colorQuarter', 'colorHalf', 'colorFull', 'targetBoneIndex'
  108. ]
  109. });
  110. shader.setColor3('colorBase', colorBase);
  111. shader.setColor3('colorZero', colorZero);
  112. shader.setColor3('colorQuarter', colorQuarter);
  113. shader.setColor3('colorHalf', colorHalf);
  114. shader.setColor3('colorFull', colorFull);
  115. shader.setFloat('targetBoneIndex', targetBoneIndex);
  116. shader.getClassName = (): string => {
  117. return "BoneWeightShader";
  118. };
  119. shader.transparencyMode = Material.MATERIAL_OPAQUE;
  120. return shader;
  121. }
  122. /** public static method to create a BoneWeight Shader
  123. * @param options The constructor options
  124. * @param scene The scene that the shader is scoped to
  125. * @returns The created ShaderMaterial
  126. */
  127. static CreateSkeletonMapShader(options: ISkeletonMapShaderOptions, scene: Scene) {
  128. let skeleton: Skeleton = options.skeleton;
  129. let colorMap: ISkeletonMapShaderColorMapKnot[] = options.colorMap ?? [
  130. {
  131. color: new Color3(1, 0.38, 0.18),
  132. location : 0
  133. },
  134. {
  135. color: new Color3(.59, 0.18, 1.00),
  136. location : 0.2
  137. },
  138. {
  139. color: new Color3(0.59, 1, 0.18),
  140. location : 0.4
  141. },
  142. {
  143. color: new Color3(1, 0.87, 0.17),
  144. location : 0.6
  145. },
  146. {
  147. color: new Color3(1, 0.17, 0.42),
  148. location : 0.8
  149. },
  150. {
  151. color: new Color3(0.17, 0.68, 1.0),
  152. location : 1.0
  153. }
  154. ];
  155. let bufferWidth: number = skeleton.bones.length + 1;
  156. let colorMapBuffer: number[] = SkeletonViewer._CreateBoneMapColorBuffer(bufferWidth, colorMap, scene);
  157. let shader = new ShaderMaterial('boneWeights:' + skeleton.name, scene,
  158. {
  159. vertexSource:
  160. `precision highp float;
  161. attribute vec3 position;
  162. attribute vec2 uv;
  163. uniform mat4 view;
  164. uniform mat4 projection;
  165. uniform mat4 worldViewProjection;
  166. uniform float colorMap[` + ((skeleton.bones.length) * 4) + `];
  167. #include<bonesDeclaration>
  168. #include<instancesDeclaration>
  169. varying vec3 vColor;
  170. void main() {
  171. vec3 positionUpdated = position;
  172. #include<instancesVertex>
  173. #include<bonesVertex>
  174. vec3 color = vec3(0.);
  175. bool first = true;
  176. for (int i = 0; i < 4; i++) {
  177. int boneIdx = int(matricesIndices[i]);
  178. float boneWgt = matricesWeights[i];
  179. vec3 c = vec3(colorMap[boneIdx * 4 + 0], colorMap[boneIdx * 4 + 1], colorMap[boneIdx * 4 + 2]);
  180. if (boneWgt > 0.) {
  181. if (first) {
  182. first = false;
  183. color = c;
  184. } else {
  185. color = mix(color, c, boneWgt);
  186. }
  187. }
  188. }
  189. vColor = color;
  190. vec4 worldPos = finalWorld * vec4(positionUpdated, 1.0);
  191. gl_Position = projection * view * worldPos;
  192. }`,
  193. fragmentSource:
  194. `
  195. precision highp float;
  196. varying vec3 vColor;
  197. void main() {
  198. vec4 color = vec4( vColor, 1.0 );
  199. gl_FragColor = color;
  200. }
  201. `
  202. },
  203. {
  204. attributes: ['position', 'normal'],
  205. uniforms: [
  206. 'world', 'worldView', 'worldViewProjection', 'view', 'projection', 'viewProjection',
  207. 'colorMap'
  208. ]
  209. });
  210. shader.setFloats('colorMap', colorMapBuffer);
  211. shader.getClassName = (): string => {
  212. return "SkeletonMapShader";
  213. };
  214. shader.transparencyMode = Material.MATERIAL_OPAQUE;
  215. return shader;
  216. }
  217. /** private static method to create a BoneWeight Shader
  218. * @param size The size of the buffer to create (usually the bone count)
  219. * @param colorMap The gradient data to generate
  220. * @param scene The scene that the shader is scoped to
  221. * @returns an Array of floats from the color gradient values
  222. */
  223. private static _CreateBoneMapColorBuffer(size: number, colorMap: ISkeletonMapShaderColorMapKnot[], scene: Scene) {
  224. let tempGrad = new DynamicTexture('temp', {width: size, height: 1}, scene, false);
  225. let ctx = tempGrad.getContext();
  226. let grad = ctx.createLinearGradient(0, 0, size, 0);
  227. colorMap.forEach((stop) => {
  228. grad.addColorStop(stop.location, stop.color.toHexString());
  229. });
  230. ctx.fillStyle = grad;
  231. ctx.fillRect(0, 0, size, 1);
  232. tempGrad.update();
  233. let buffer: number[] = [];
  234. let data: Uint8ClampedArray = ctx.getImageData(0, 0, size, 1).data;
  235. let rUnit = 1 / 255;
  236. for (let i = 0; i < data.length; i++) {
  237. buffer.push(data[i] * rUnit);
  238. }
  239. tempGrad.dispose();
  240. return buffer;
  241. }
  242. /** If SkeletonViewer scene scope. */
  243. private _scene : Scene;
  244. /** Gets or sets the color used to render the skeleton */
  245. public color: Color3 = Color3.White();
  246. /** Array of the points of the skeleton fo the line view. */
  247. private _debugLines = new Array<Array<Vector3>>();
  248. /** The SkeletonViewers Mesh. */
  249. private _debugMesh: Nullable<LinesMesh>;
  250. /** The local axes Meshes. */
  251. private _localAxes: Nullable<LinesMesh> = null;
  252. /** If SkeletonViewer is enabled. */
  253. private _isEnabled = false;
  254. /** If SkeletonViewer is ready. */
  255. private _ready : boolean;
  256. /** SkeletonViewer render observable. */
  257. private _obs: Nullable<Observer<Scene>> = null;
  258. /** The Utility Layer to render the gizmos in. */
  259. private _utilityLayer: Nullable<UtilityLayerRenderer>;
  260. private _boneIndices: Set<number>;
  261. /** Gets the Scene. */
  262. get scene(): Scene {
  263. return this._scene;
  264. }
  265. /** Gets the utilityLayer. */
  266. get utilityLayer(): Nullable<UtilityLayerRenderer> {
  267. return this._utilityLayer;
  268. }
  269. /** Checks Ready Status. */
  270. get isReady(): Boolean {
  271. return this._ready;
  272. }
  273. /** Sets Ready Status. */
  274. set ready(value: boolean) {
  275. this._ready = value;
  276. }
  277. /** Gets the debugMesh */
  278. get debugMesh(): Nullable<AbstractMesh> | Nullable<LinesMesh> {
  279. return this._debugMesh;
  280. }
  281. /** Sets the debugMesh */
  282. set debugMesh(value: Nullable<AbstractMesh> | Nullable<LinesMesh>) {
  283. this._debugMesh = (value as any);
  284. }
  285. /** Gets the displayMode */
  286. get displayMode(): number {
  287. return this.options.displayMode || SkeletonViewer.DISPLAY_LINES;
  288. }
  289. /** Sets the displayMode */
  290. set displayMode(value: number) {
  291. if (value > SkeletonViewer.DISPLAY_SPHERE_AND_SPURS) {
  292. value = SkeletonViewer.DISPLAY_LINES;
  293. }
  294. this.options.displayMode = value;
  295. }
  296. /**
  297. * Creates a new SkeletonViewer
  298. * @param skeleton defines the skeleton to render
  299. * @param mesh defines the mesh attached to the skeleton
  300. * @param scene defines the hosting scene
  301. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  302. * @param renderingGroupId defines the rendering group id to use with the viewer
  303. * @param options All of the extra constructor options for the SkeletonViewer
  304. */
  305. constructor(
  306. /** defines the skeleton to render */
  307. public skeleton: Skeleton,
  308. /** defines the mesh attached to the skeleton */
  309. public mesh: AbstractMesh,
  310. /** The Scene scope*/
  311. scene: Scene,
  312. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  313. public autoUpdateBonesMatrices: boolean = true,
  314. /** defines the rendering group id to use with the viewer */
  315. public renderingGroupId: number = 3,
  316. /** is the options for the viewer */
  317. public options: Partial<ISkeletonViewerOptions> = {}
  318. ) {
  319. this._scene = scene;
  320. this._ready = false;
  321. //Defaults
  322. options.pauseAnimations = options.pauseAnimations ?? true;
  323. options.returnToRest = options.returnToRest ?? false;
  324. options.displayMode = options.displayMode ?? SkeletonViewer.DISPLAY_LINES;
  325. options.displayOptions = options.displayOptions ?? {};
  326. options.displayOptions.midStep = options.displayOptions.midStep ?? 0.235;
  327. options.displayOptions.midStepFactor = options.displayOptions.midStepFactor ?? 0.155;
  328. options.displayOptions.sphereBaseSize = options.displayOptions.sphereBaseSize ?? 0.15;
  329. options.displayOptions.sphereScaleUnit = options.displayOptions.sphereScaleUnit ?? 2;
  330. options.displayOptions.sphereFactor = options.displayOptions.sphereFactor ?? 0.865;
  331. options.displayOptions.spurFollowsChild = options.displayOptions.spurFollowsChild ?? false;
  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 get the absolute bind pose of a bone by accumulating transformations up the bone hierarchy. */
  480. private _getAbsoluteBindPoseToRef(bone: Nullable<Bone>, matrix: Matrix) {
  481. if (bone === null || bone._index === -1) {
  482. matrix.copyFrom(Matrix.Identity());
  483. return;
  484. }
  485. this._getAbsoluteBindPoseToRef(bone.getParent(), matrix);
  486. bone.getBindPose().multiplyToRef(matrix, matrix);
  487. return;
  488. }
  489. /** function to build and bind sphere joint points and spur bone representations. */
  490. private _buildSpheresAndSpurs(spheresOnly = true): void {
  491. if (this._debugMesh) {
  492. this._debugMesh.dispose();
  493. this._debugMesh = null;
  494. this.ready = false;
  495. }
  496. this._ready = false;
  497. let scene = this.scene;
  498. let bones: Bone[] = this.skeleton.bones;
  499. let spheres: Array<[Mesh, Bone]> = [];
  500. let spurs: Mesh[] = [];
  501. const animationState = scene.animationsEnabled;
  502. try {
  503. if (this.options.pauseAnimations) {
  504. scene.animationsEnabled = false;
  505. }
  506. if (this.options.returnToRest) {
  507. this.skeleton.returnToRest();
  508. }
  509. if (this.autoUpdateBonesMatrices) {
  510. this.skeleton.computeAbsoluteTransforms();
  511. }
  512. let longestBoneLength = Number.NEGATIVE_INFINITY;
  513. let displayOptions = this.options.displayOptions || {};
  514. for (let i = 0; i < bones.length; i++) {
  515. let bone = bones[i];
  516. if (bone._index === -1 || (!this._boneIndices.has(bone.getIndex()) && !this.options.useAllBones)) {
  517. continue;
  518. }
  519. let boneAbsoluteBindPoseTransform = new Matrix();
  520. this._getAbsoluteBindPoseToRef(bone, boneAbsoluteBindPoseTransform);
  521. let anchorPoint = new Vector3();
  522. boneAbsoluteBindPoseTransform.decompose(undefined, undefined, anchorPoint);
  523. bone.children.forEach((bc, i) => {
  524. let childAbsoluteBindPoseTransform : Matrix = new Matrix();
  525. bc.getBindPose().multiplyToRef(boneAbsoluteBindPoseTransform, childAbsoluteBindPoseTransform);
  526. let childPoint = new Vector3();
  527. childAbsoluteBindPoseTransform.decompose(undefined, undefined, childPoint);
  528. let distanceFromParent = Vector3.Distance(anchorPoint, childPoint);
  529. if (distanceFromParent > longestBoneLength) {
  530. longestBoneLength = distanceFromParent;
  531. }
  532. if (spheresOnly) {
  533. return;
  534. }
  535. let dir = childPoint.clone().subtract(anchorPoint.clone());
  536. let h = dir.length();
  537. let up = dir.normalize().scale(h);
  538. let midStep = displayOptions.midStep || 0.165;
  539. let midStepFactor = displayOptions.midStepFactor || 0.215;
  540. let up0 = up.scale(midStep);
  541. let spur = ShapeBuilder.ExtrudeShapeCustom('skeletonViewer',
  542. {
  543. shape: [
  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. new Vector3(1, -1, 0)
  549. ],
  550. path: [ Vector3.Zero(), up0, up ],
  551. scaleFunction:
  552. (i: number) => {
  553. switch (i){
  554. case 0:
  555. case 2:
  556. return 0;
  557. case 1:
  558. return h * midStepFactor;
  559. }
  560. return 0;
  561. },
  562. sideOrientation: Mesh.DEFAULTSIDE,
  563. updatable: false
  564. }, scene);
  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. if (displayOptions.spurFollowsChild && i > 9) {
  570. mik.push(bc.getIndex(), 0, 0, 0);
  571. }
  572. else {
  573. mik.push(bone.getIndex(), 0, 0, 0);
  574. }
  575. }
  576. spur.position = anchorPoint.clone();
  577. spur.setVerticesData(VertexBuffer.MatricesWeightsKind, mwk, false);
  578. spur.setVerticesData(VertexBuffer.MatricesIndicesKind, mik, false);
  579. spur.convertToFlatShadedMesh();
  580. spurs.push(spur);
  581. });
  582. let sphereBaseSize = displayOptions.sphereBaseSize || 0.2;
  583. let sphere = SphereBuilder.CreateSphere('skeletonViewer', {
  584. segments: 6,
  585. diameter: sphereBaseSize,
  586. updatable: true
  587. }, scene);
  588. const numVertices = sphere.getTotalVertices();
  589. let mwk: number[] = [], mik: number[] = [];
  590. for (let i = 0; i < numVertices; i++) {
  591. mwk.push(1, 0, 0, 0);
  592. mik.push(bone.getIndex(), 0, 0, 0);
  593. }
  594. sphere.setVerticesData(VertexBuffer.MatricesWeightsKind, mwk, false);
  595. sphere.setVerticesData(VertexBuffer.MatricesIndicesKind, mik, false);
  596. sphere.position = anchorPoint.clone();
  597. spheres.push([sphere, bone]);
  598. }
  599. let sphereScaleUnit = displayOptions.sphereScaleUnit || 2;
  600. let sphereFactor = displayOptions.sphereFactor || 0.85;
  601. const meshes = [];
  602. for (let i = 0; i < spheres.length; i++) {
  603. let [sphere, bone] = spheres[i];
  604. let scale = 1 / (sphereScaleUnit / longestBoneLength);
  605. let _stepsOut = 0;
  606. let _b = bone;
  607. while ((_b.getParent()) && (_b.getParent() as Bone).getIndex() !== -1) {
  608. _stepsOut++;
  609. _b = (_b.getParent() as Bone);
  610. }
  611. sphere.scaling.scaleInPlace(scale * Math.pow(sphereFactor, _stepsOut));
  612. meshes.push(sphere);
  613. }
  614. this.debugMesh = Mesh.MergeMeshes(meshes.concat(spurs), true, true);
  615. if (this.debugMesh) {
  616. this.debugMesh.renderingGroupId = this.renderingGroupId;
  617. this.debugMesh.skeleton = this.skeleton;
  618. this.debugMesh.parent = this.mesh;
  619. this.debugMesh.computeBonesUsingShaders = this.options.computeBonesUsingShaders ?? true;
  620. this.debugMesh.alwaysSelectAsActiveMesh = true;
  621. }
  622. this._revert(animationState);
  623. this.ready = true;
  624. } catch (err) {
  625. console.error(err);
  626. this._revert(animationState);
  627. this.dispose();
  628. }
  629. }
  630. private _buildLocalAxes(): void {
  631. if (this._localAxes) {
  632. this._localAxes.dispose();
  633. }
  634. this._localAxes = null;
  635. let displayOptions = this.options.displayOptions || {};
  636. if (!displayOptions.showLocalAxes) {
  637. return;
  638. }
  639. const targetScene = this._utilityLayer!.utilityLayerScene;
  640. const size = displayOptions.localAxesSize || 0.075;
  641. let lines = [];
  642. let colors = [];
  643. let red = new Color4(1, 0, 0, 1);
  644. let green = new Color4(0, 1, 0, 1);
  645. let blue = new Color4(0, 0, 1, 1);
  646. let mwk: number[] = [];
  647. let mik: number[] = [];
  648. const vertsPerBone = 6;
  649. for (let i in this.skeleton.bones) {
  650. let bone = this.skeleton.bones[i];
  651. if (bone._index === -1 || (!this._boneIndices.has(bone.getIndex()) && !this.options.useAllBones)) {
  652. continue;
  653. }
  654. let boneAbsoluteBindPoseTransform = new Matrix();
  655. let boneOrigin = new Vector3();
  656. this._getAbsoluteBindPoseToRef(bone, boneAbsoluteBindPoseTransform);
  657. boneAbsoluteBindPoseTransform.decompose(undefined, undefined, boneOrigin);
  658. let m = bone.getBindPose().getRotationMatrix();
  659. let boneAxisX = Vector3.TransformCoordinates(new Vector3(0 + size, 0, 0), m);
  660. let boneAxisY = Vector3.TransformCoordinates(new Vector3(0, 0 + size, 0), m);
  661. let boneAxisZ = Vector3.TransformCoordinates(new Vector3(0, 0, 0 + size), m);
  662. let axisX = [boneOrigin, boneOrigin.add(boneAxisX)];
  663. let axisY = [boneOrigin, boneOrigin.add(boneAxisY)];
  664. let axisZ = [boneOrigin, boneOrigin.add(boneAxisZ)];
  665. let linePoints = [axisX, axisY, axisZ];
  666. let lineColors = [[red, red], [green, green], [blue, blue]];
  667. lines.push(...linePoints);
  668. colors.push(...lineColors);
  669. for (let j = 0; j < vertsPerBone; j++) {
  670. mwk.push(1, 0, 0, 0);
  671. mik.push(bone.getIndex(), 0, 0, 0);
  672. }
  673. }
  674. this._localAxes = LinesBuilder.CreateLineSystem('localAxes', { lines: lines, colors: colors, updatable: true }, targetScene);
  675. this._localAxes.setVerticesData(VertexBuffer.MatricesWeightsKind, mwk, false);
  676. this._localAxes.setVerticesData(VertexBuffer.MatricesIndicesKind, mik, false);
  677. this._localAxes.skeleton = this.skeleton;
  678. this._localAxes.renderingGroupId = this.renderingGroupId;
  679. this._localAxes.parent = this.mesh;
  680. this._localAxes.computeBonesUsingShaders = this.options.computeBonesUsingShaders ?? true;
  681. }
  682. /** Update the viewer to sync with current skeleton state, only used for the line display. */
  683. private _displayLinesUpdate(): void {
  684. if (!this._utilityLayer) {
  685. return;
  686. }
  687. if (this.autoUpdateBonesMatrices) {
  688. this.skeleton.computeAbsoluteTransforms();
  689. }
  690. let mesh = this.mesh._effectiveMesh;
  691. if (this.skeleton.bones[0].length === undefined) {
  692. this._getLinesForBonesNoLength(this.skeleton.bones);
  693. } else {
  694. this._getLinesForBonesWithLength(this.skeleton.bones, mesh.getWorldMatrix());
  695. }
  696. const targetScene = this._utilityLayer.utilityLayerScene;
  697. if (targetScene) {
  698. if (!this._debugMesh) {
  699. this._debugMesh = LinesBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, targetScene);
  700. this._debugMesh.renderingGroupId = this.renderingGroupId;
  701. } else {
  702. LinesBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, targetScene);
  703. }
  704. this._debugMesh.position.copyFrom(this.mesh.position);
  705. this._debugMesh.color = this.color;
  706. }
  707. }
  708. /** Changes the displayMode of the skeleton viewer
  709. * @param mode The displayMode numerical value
  710. */
  711. public changeDisplayMode(mode: number): void {
  712. let wasEnabled = (this.isEnabled) ? true : false;
  713. if (this.displayMode !== mode) {
  714. this.isEnabled = false;
  715. if (this._debugMesh) {
  716. this._debugMesh.dispose();
  717. this._debugMesh = null;
  718. this.ready = false;
  719. }
  720. this.displayMode = mode;
  721. this.update();
  722. this._bindObs();
  723. this.isEnabled = wasEnabled;
  724. }
  725. }
  726. /** Sets a display option of the skeleton viewer
  727. *
  728. * | Option | Type | Default | Description |
  729. * | ---------------- | ------- | ------- | ----------- |
  730. * | midStep | float | 0.235 | A percentage between a bone and its child that determines the widest part of a spur. Only used when `displayMode` is set to `DISPLAY_SPHERE_AND_SPURS`. |
  731. * | midStepFactor | float | 0.15 | Mid step width expressed as a factor of the length. A value of 0.5 makes the spur width half of the spur length. Only used when `displayMode` is set to `DISPLAY_SPHERE_AND_SPURS`. |
  732. * | sphereBaseSize | float | 2 | Sphere base size. Only used when `displayMode` is set to `DISPLAY_SPHERE_AND_SPURS`. |
  733. * | sphereScaleUnit | float | 0.865 | Sphere scale factor used to scale spheres in relation to the longest bone. Only used when `displayMode` is set to `DISPLAY_SPHERE_AND_SPURS`. |
  734. * | spurFollowsChild | boolean | false | Whether a spur should attach its far end to the child bone. |
  735. * | showLocalAxes | boolean | false | Displays local axes on all bones. |
  736. * | localAxesSize | float | 0.075 | Determines the length of each local axis. |
  737. *
  738. * @param option String of the option name
  739. * @param value The numerical option value
  740. */
  741. public changeDisplayOptions(option: string, value: number): void {
  742. let wasEnabled = (this.isEnabled) ? true : false;
  743. (this.options.displayOptions as any)[option] = value;
  744. this.isEnabled = false;
  745. if (this._debugMesh) {
  746. this._debugMesh.dispose();
  747. this._debugMesh = null;
  748. this.ready = false;
  749. }
  750. this.update();
  751. this._bindObs();
  752. this.isEnabled = wasEnabled;
  753. }
  754. /** Release associated resources */
  755. public dispose(): void {
  756. this.isEnabled = false;
  757. if (this._debugMesh) {
  758. this._debugMesh.dispose();
  759. this._debugMesh = null;
  760. }
  761. if (this._utilityLayer) {
  762. this._utilityLayer.dispose();
  763. this._utilityLayer = null;
  764. }
  765. this.ready = false;
  766. }
  767. }