skeletonViewer.ts 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906
  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.showLocalAxes = options.displayOptions.showLocalAxes ?? false;
  332. options.displayOptions.localAxesSize = options.displayOptions.localAxesSize ?? 0.075;
  333. options.computeBonesUsingShaders = options.computeBonesUsingShaders ?? true;
  334. options.useAllBones = options.useAllBones ?? true;
  335. const initialMeshBoneIndices = mesh.getVerticesData(VertexBuffer.MatricesIndicesKind);
  336. const initialMeshBoneWeights = mesh.getVerticesData(VertexBuffer.MatricesWeightsKind);
  337. this._boneIndices = new Set();
  338. if (!options.useAllBones) {
  339. if (initialMeshBoneIndices && initialMeshBoneWeights) {
  340. for (let i = 0; i < initialMeshBoneIndices.length; ++i) {
  341. const index = initialMeshBoneIndices[i], weight = initialMeshBoneWeights[i];
  342. if (weight !== 0) {
  343. this._boneIndices.add(index);
  344. }
  345. }
  346. }
  347. }
  348. /* Create Utility Layer */
  349. this._utilityLayer = new UtilityLayerRenderer(this._scene, false);
  350. this._utilityLayer.pickUtilitySceneFirst = false;
  351. this._utilityLayer.utilityLayerScene.autoClearDepthAndStencil = true;
  352. let displayMode = this.options.displayMode || 0;
  353. if (displayMode > SkeletonViewer.DISPLAY_SPHERE_AND_SPURS) {
  354. displayMode = SkeletonViewer.DISPLAY_LINES;
  355. }
  356. this.displayMode = displayMode;
  357. //Prep the Systems
  358. this.update();
  359. this._bindObs();
  360. }
  361. /** The Dynamic bindings for the update functions */
  362. private _bindObs(): void {
  363. switch (this.displayMode){
  364. case SkeletonViewer.DISPLAY_LINES: {
  365. this._obs = this.scene.onBeforeRenderObservable.add(() => {
  366. this._displayLinesUpdate();
  367. });
  368. break;
  369. }
  370. }
  371. }
  372. /** Update the viewer to sync with current skeleton state, only used to manually update. */
  373. public update(): void {
  374. switch (this.displayMode){
  375. case SkeletonViewer.DISPLAY_LINES: {
  376. this._displayLinesUpdate();
  377. break;
  378. }
  379. case SkeletonViewer.DISPLAY_SPHERES: {
  380. this._buildSpheresAndSpurs(true);
  381. break;
  382. }
  383. case SkeletonViewer.DISPLAY_SPHERE_AND_SPURS: {
  384. this._buildSpheresAndSpurs(false);
  385. break;
  386. }
  387. }
  388. this._buildLocalAxes();
  389. }
  390. /** Gets or sets a boolean indicating if the viewer is enabled */
  391. public set isEnabled(value: boolean) {
  392. if (this.isEnabled === value) {
  393. return;
  394. }
  395. this._isEnabled = value;
  396. if (this.debugMesh) {
  397. this.debugMesh.setEnabled(value);
  398. }
  399. if (value && !this._obs) {
  400. this._bindObs();
  401. } else if (!value && this._obs) {
  402. this.scene.onBeforeRenderObservable.remove(this._obs);
  403. this._obs = null;
  404. }
  405. }
  406. public get isEnabled(): boolean {
  407. return this._isEnabled;
  408. }
  409. private _getBonePosition(position: Vector3, bone: Bone, meshMat: Matrix, x = 0, y = 0, z = 0): void {
  410. var tmat = TmpVectors.Matrix[0];
  411. var parentBone = bone.getParent();
  412. tmat.copyFrom(bone.getLocalMatrix());
  413. if (x !== 0 || y !== 0 || z !== 0) {
  414. var tmat2 = TmpVectors.Matrix[1];
  415. Matrix.IdentityToRef(tmat2);
  416. tmat2.setTranslationFromFloats(x, y, z);
  417. tmat2.multiplyToRef(tmat, tmat);
  418. }
  419. if (parentBone) {
  420. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  421. }
  422. tmat.multiplyToRef(meshMat, tmat);
  423. position.x = tmat.m[12];
  424. position.y = tmat.m[13];
  425. position.z = tmat.m[14];
  426. }
  427. private _getLinesForBonesWithLength(bones: Bone[], meshMat: Matrix): void {
  428. var len = bones.length;
  429. let mesh = this.mesh._effectiveMesh;
  430. var meshPos = mesh.position;
  431. let idx = 0;
  432. for (var i = 0; i < len; i++) {
  433. var bone = bones[i];
  434. var points = this._debugLines[idx];
  435. if (bone._index === -1 || (!this._boneIndices.has(bone.getIndex()) && !this.options.useAllBones)) {
  436. continue;
  437. }
  438. if (!points) {
  439. points = [Vector3.Zero(), Vector3.Zero()];
  440. this._debugLines[idx] = points;
  441. }
  442. this._getBonePosition(points[0], bone, meshMat);
  443. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  444. points[0].subtractInPlace(meshPos);
  445. points[1].subtractInPlace(meshPos);
  446. idx++;
  447. }
  448. }
  449. private _getLinesForBonesNoLength(bones: Bone[]): void {
  450. var len = bones.length;
  451. var boneNum = 0;
  452. let mesh = this.mesh._effectiveMesh;
  453. var meshPos = mesh.position;
  454. for (var i = len - 1; i >= 0; i--) {
  455. var childBone = bones[i];
  456. var parentBone = childBone.getParent();
  457. if (!parentBone || (!this._boneIndices.has(childBone.getIndex()) && !this.options.useAllBones)) {
  458. continue;
  459. }
  460. var points = this._debugLines[boneNum];
  461. if (!points) {
  462. points = [Vector3.Zero(), Vector3.Zero()];
  463. this._debugLines[boneNum] = points;
  464. }
  465. childBone.getAbsolutePositionToRef(mesh, points[0]);
  466. parentBone.getAbsolutePositionToRef(mesh, points[1]);
  467. points[0].subtractInPlace(meshPos);
  468. points[1].subtractInPlace(meshPos);
  469. boneNum++;
  470. }
  471. }
  472. /** function to revert the mesh and scene back to the initial state. */
  473. private _revert(animationState: boolean): void {
  474. if (this.options.pauseAnimations) {
  475. this.scene.animationsEnabled = animationState;
  476. }
  477. }
  478. /** function to get the absolute bind pose of a bone by accumulating transformations up the bone hierarchy. */
  479. private getAbsoluteBindPoseToRef(bone: Nullable<Bone>, matrix: Matrix) {
  480. if (bone === null || bone._index === -1) {
  481. matrix.copyFrom(Matrix.Identity());
  482. return;
  483. }
  484. this.getAbsoluteBindPoseToRef(bone.getParent(), matrix);
  485. bone.getBindPose().multiplyToRef(matrix, matrix);
  486. return;
  487. }
  488. /** function to build and bind sphere joint points and spur bone representations. */
  489. private _buildSpheresAndSpurs(spheresOnly = true): void {
  490. if (this._debugMesh) {
  491. this._debugMesh.dispose();
  492. this._debugMesh = null;
  493. this.ready = false;
  494. }
  495. this._ready = false;
  496. let scene = this.scene;
  497. let bones: Bone[] = this.skeleton.bones;
  498. let spheres: Array<[Mesh, Bone]> = [];
  499. let spurs: Mesh[] = [];
  500. const animationState = scene.animationsEnabled;
  501. try {
  502. if (this.options.pauseAnimations) {
  503. scene.animationsEnabled = false;
  504. }
  505. if (this.options.returnToRest) {
  506. this.skeleton.returnToRest();
  507. }
  508. if (this.autoUpdateBonesMatrices) {
  509. this.skeleton.computeAbsoluteTransforms();
  510. }
  511. let longestBoneLength = Number.NEGATIVE_INFINITY;
  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 boneAbsoluteBindPoseTransform = new Matrix();
  519. this.getAbsoluteBindPoseToRef(bone, boneAbsoluteBindPoseTransform);
  520. let anchorPoint = new Vector3();
  521. boneAbsoluteBindPoseTransform.decompose(undefined, undefined, anchorPoint);
  522. bone.children.forEach((bc, i) => {
  523. let childAbsoluteRestPoseTransform : Matrix = new Matrix();
  524. bc.getRestPose().multiplyToRef(boneAbsoluteBindPoseTransform, childAbsoluteRestPoseTransform);
  525. let childPoint = new Vector3();
  526. childAbsoluteRestPoseTransform.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. let lines = [];
  636. let colors = [];
  637. let red = new Color4(1, 0, 0, 1);
  638. let green = new Color4(0, 1, 0, 1);
  639. let blue = new Color4(0, 0, 1, 1);
  640. let mwk: number[] = [];
  641. let mik: number[] = [];
  642. const vertsPerBone = 6;
  643. for (let i in this.skeleton.bones) {
  644. let bone = this.skeleton.bones[i];
  645. if (bone._index === -1 || (!this._boneIndices.has(bone.getIndex()) && !this.options.useAllBones)) {
  646. continue;
  647. }
  648. let boneAbsoluteBindPoseTransform = new Matrix();
  649. let boneOrigin = new Vector3();
  650. this.getAbsoluteBindPoseToRef(bone, boneAbsoluteBindPoseTransform);
  651. boneAbsoluteBindPoseTransform.decompose(undefined, undefined, boneOrigin);
  652. let m = bone.getBindPose().getRotationMatrix();
  653. let boneAxisX = Vector3.TransformCoordinates(new Vector3(0 + size, 0, 0), m);
  654. let boneAxisY = Vector3.TransformCoordinates(new Vector3(0, 0 + size, 0), m);
  655. let boneAxisZ = Vector3.TransformCoordinates(new Vector3(0, 0, 0 + size), m);
  656. let axisX = [boneOrigin, boneOrigin.add(boneAxisX)];
  657. let axisY = [boneOrigin, boneOrigin.add(boneAxisY)];
  658. let axisZ = [boneOrigin, boneOrigin.add(boneAxisZ)];
  659. let linePoints = [axisX, axisY, axisZ];
  660. let lineColors = [[red, red], [green, green], [blue, blue]];
  661. lines.push(...linePoints);
  662. colors.push(...lineColors);
  663. for (let j = 0; j < vertsPerBone; j++) {
  664. mwk.push(1, 0, 0, 0);
  665. mik.push(bone.getIndex(), 0, 0, 0);
  666. }
  667. }
  668. this._localAxes = LinesBuilder.CreateLineSystem('localAxes', { lines: lines, colors: colors, updatable: true }, targetScene);
  669. this._localAxes.setVerticesData(VertexBuffer.MatricesWeightsKind, mwk, false);
  670. this._localAxes.setVerticesData(VertexBuffer.MatricesIndicesKind, mik, false);
  671. this._localAxes.skeleton = this.skeleton;
  672. this._localAxes.renderingGroupId = this.renderingGroupId;
  673. this._localAxes.parent = this.mesh;
  674. this._localAxes.computeBonesUsingShaders = this.options.computeBonesUsingShaders ?? true;
  675. }
  676. /** Update the viewer to sync with current skeleton state, only used for the line display. */
  677. private _displayLinesUpdate(): void {
  678. if (!this._utilityLayer) {
  679. return;
  680. }
  681. if (this.autoUpdateBonesMatrices) {
  682. this.skeleton.computeAbsoluteTransforms();
  683. }
  684. let mesh = this.mesh._effectiveMesh;
  685. if (this.skeleton.bones[0].length === undefined) {
  686. this._getLinesForBonesNoLength(this.skeleton.bones);
  687. } else {
  688. this._getLinesForBonesWithLength(this.skeleton.bones, mesh.getWorldMatrix());
  689. }
  690. const targetScene = this._utilityLayer.utilityLayerScene;
  691. if (targetScene) {
  692. if (!this._debugMesh) {
  693. this._debugMesh = LinesBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, targetScene);
  694. this._debugMesh.renderingGroupId = this.renderingGroupId;
  695. } else {
  696. LinesBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, targetScene);
  697. }
  698. this._debugMesh.position.copyFrom(this.mesh.position);
  699. this._debugMesh.color = this.color;
  700. }
  701. }
  702. /** Changes the displayMode of the skeleton viewer
  703. * @param mode The displayMode numerical value
  704. */
  705. public changeDisplayMode(mode: number): void {
  706. let wasEnabled = (this.isEnabled) ? true : false;
  707. if (this.displayMode !== mode) {
  708. this.isEnabled = false;
  709. if (this._debugMesh) {
  710. this._debugMesh.dispose();
  711. this._debugMesh = null;
  712. this.ready = false;
  713. }
  714. this.displayMode = mode;
  715. this.update();
  716. this._bindObs();
  717. this.isEnabled = wasEnabled;
  718. }
  719. }
  720. /** Sets a display option of the skeleton viewer
  721. *
  722. * | Option | Type | Default | Description |
  723. * | --------------- | ------- | ------- | ----------- |
  724. * | showLocalAxes | boolean | false | Displays local axes on all bones. |
  725. * | localAxesSize | float | 0.075 | Determines the length of each local axis. |
  726. *
  727. * @param option String of the option name
  728. * @param value The numerical option value
  729. */
  730. public changeDisplayOptions(option: string, value: number): void {
  731. let wasEnabled = (this.isEnabled) ? true : false;
  732. (this.options.displayOptions as any)[option] = value;
  733. this.isEnabled = false;
  734. if (this._debugMesh) {
  735. this._debugMesh.dispose();
  736. this._debugMesh = null;
  737. this.ready = false;
  738. }
  739. this.update();
  740. this._bindObs();
  741. this.isEnabled = wasEnabled;
  742. }
  743. /** Release associated resources */
  744. public dispose(): void {
  745. this.isEnabled = false;
  746. if (this._debugMesh) {
  747. this._debugMesh.dispose();
  748. this._debugMesh = null;
  749. }
  750. if (this._utilityLayer) {
  751. this._utilityLayer.dispose();
  752. this._utilityLayer = null;
  753. }
  754. this.ready = false;
  755. }
  756. }