geometry.ts 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481
  1. import { Nullable, FloatArray, DataArray, IndicesArray } from "../types";
  2. import { Scene } from "../scene";
  3. import { Vector3, Vector2, Color4 } from "../Maths/math";
  4. import { Engine } from "../Engines/engine";
  5. import { IGetSetVerticesData, VertexData } from "../Meshes/mesh.vertexData";
  6. import { VertexBuffer } from "../Meshes/buffer";
  7. import { SubMesh } from "../Meshes/subMesh";
  8. import { AbstractMesh } from "../Meshes/abstractMesh";
  9. import { Effect } from "../Materials/effect";
  10. import { SceneLoaderFlags } from "../Loading/sceneLoaderFlags";
  11. import { BoundingInfo } from "../Culling/boundingInfo";
  12. import { Constants } from "../Engines/constants";
  13. import { Tools } from "../Misc/tools";
  14. import { Tags } from "../Misc/tags";
  15. import { DataBuffer } from './dataBuffer';
  16. declare type Mesh = import("../Meshes/mesh").Mesh;
  17. /**
  18. * Class used to store geometry data (vertex buffers + index buffer)
  19. */
  20. export class Geometry implements IGetSetVerticesData {
  21. // Members
  22. /**
  23. * Gets or sets the ID of the geometry
  24. */
  25. public id: string;
  26. /**
  27. * Gets or sets the unique ID of the geometry
  28. */
  29. public uniqueId: number;
  30. /**
  31. * Gets the delay loading state of the geometry (none by default which means not delayed)
  32. */
  33. public delayLoadState = Constants.DELAYLOADSTATE_NONE;
  34. /**
  35. * Gets the file containing the data to load when running in delay load state
  36. */
  37. public delayLoadingFile: Nullable<string>;
  38. /**
  39. * Callback called when the geometry is updated
  40. */
  41. public onGeometryUpdated: (geometry: Geometry, kind?: string) => void;
  42. // Private
  43. private _scene: Scene;
  44. private _engine: Engine;
  45. private _meshes: Mesh[];
  46. private _totalVertices = 0;
  47. /** @hidden */
  48. public _indices: IndicesArray;
  49. /** @hidden */
  50. public _vertexBuffers: { [key: string]: VertexBuffer; };
  51. private _isDisposed = false;
  52. private _extend: { minimum: Vector3, maximum: Vector3 };
  53. private _boundingBias: Vector2;
  54. /** @hidden */
  55. public _delayInfo: Array<string>;
  56. private _indexBuffer: Nullable<DataBuffer>;
  57. private _indexBufferIsUpdatable = false;
  58. /** @hidden */
  59. public _boundingInfo: Nullable<BoundingInfo>;
  60. /** @hidden */
  61. public _delayLoadingFunction: Nullable<(any: any, geometry: Geometry) => void>;
  62. /** @hidden */
  63. public _softwareSkinningFrameId: number;
  64. private _vertexArrayObjects: { [key: string]: WebGLVertexArrayObject; };
  65. private _updatable: boolean;
  66. // Cache
  67. /** @hidden */
  68. public _positions: Nullable<Vector3[]>;
  69. /**
  70. * Gets or sets the Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y
  71. */
  72. public get boundingBias(): Vector2 {
  73. return this._boundingBias;
  74. }
  75. /**
  76. * Gets or sets the Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y
  77. */
  78. public set boundingBias(value: Vector2) {
  79. if (this._boundingBias) {
  80. this._boundingBias.copyFrom(value);
  81. }
  82. else {
  83. this._boundingBias = value.clone();
  84. }
  85. this._updateBoundingInfo(true, null);
  86. }
  87. /**
  88. * Static function used to attach a new empty geometry to a mesh
  89. * @param mesh defines the mesh to attach the geometry to
  90. * @returns the new Geometry
  91. */
  92. public static CreateGeometryForMesh(mesh: Mesh): Geometry {
  93. let geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  94. geometry.applyToMesh(mesh);
  95. return geometry;
  96. }
  97. /**
  98. * Creates a new geometry
  99. * @param id defines the unique ID
  100. * @param scene defines the hosting scene
  101. * @param vertexData defines the VertexData used to get geometry data
  102. * @param updatable defines if geometry must be updatable (false by default)
  103. * @param mesh defines the mesh that will be associated with the geometry
  104. */
  105. constructor(id: string, scene: Scene, vertexData?: VertexData, updatable: boolean = false, mesh: Nullable<Mesh> = null) {
  106. this.id = id;
  107. this.uniqueId = scene.getUniqueId();
  108. this._engine = scene.getEngine();
  109. this._meshes = [];
  110. this._scene = scene;
  111. //Init vertex buffer cache
  112. this._vertexBuffers = {};
  113. this._indices = [];
  114. this._updatable = updatable;
  115. // vertexData
  116. if (vertexData) {
  117. this.setAllVerticesData(vertexData, updatable);
  118. }
  119. else {
  120. this._totalVertices = 0;
  121. this._indices = [];
  122. }
  123. if (this._engine.getCaps().vertexArrayObject) {
  124. this._vertexArrayObjects = {};
  125. }
  126. // applyToMesh
  127. if (mesh) {
  128. this.applyToMesh(mesh);
  129. mesh.computeWorldMatrix(true);
  130. }
  131. }
  132. /**
  133. * Gets the current extend of the geometry
  134. */
  135. public get extend(): { minimum: Vector3, maximum: Vector3 } {
  136. return this._extend;
  137. }
  138. /**
  139. * Gets the hosting scene
  140. * @returns the hosting Scene
  141. */
  142. public getScene(): Scene {
  143. return this._scene;
  144. }
  145. /**
  146. * Gets the hosting engine
  147. * @returns the hosting Engine
  148. */
  149. public getEngine(): Engine {
  150. return this._engine;
  151. }
  152. /**
  153. * Defines if the geometry is ready to use
  154. * @returns true if the geometry is ready to be used
  155. */
  156. public isReady(): boolean {
  157. return this.delayLoadState === Constants.DELAYLOADSTATE_LOADED || this.delayLoadState === Constants.DELAYLOADSTATE_NONE;
  158. }
  159. /**
  160. * Gets a value indicating that the geometry should not be serialized
  161. */
  162. public get doNotSerialize(): boolean {
  163. for (var index = 0; index < this._meshes.length; index++) {
  164. if (!this._meshes[index].doNotSerialize) {
  165. return false;
  166. }
  167. }
  168. return true;
  169. }
  170. /** @hidden */
  171. public _rebuild(): void {
  172. if (this._vertexArrayObjects) {
  173. this._vertexArrayObjects = {};
  174. }
  175. // Index buffer
  176. if (this._meshes.length !== 0 && this._indices) {
  177. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  178. }
  179. // Vertex buffers
  180. for (var key in this._vertexBuffers) {
  181. let vertexBuffer = <VertexBuffer>this._vertexBuffers[key];
  182. vertexBuffer._rebuild();
  183. }
  184. }
  185. /**
  186. * Affects all geometry data in one call
  187. * @param vertexData defines the geometry data
  188. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  189. */
  190. public setAllVerticesData(vertexData: VertexData, updatable?: boolean): void {
  191. vertexData.applyToGeometry(this, updatable);
  192. this.notifyUpdate();
  193. }
  194. /**
  195. * Set specific vertex data
  196. * @param kind defines the data kind (Position, normal, etc...)
  197. * @param data defines the vertex data to use
  198. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  199. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  200. */
  201. public setVerticesData(kind: string, data: FloatArray, updatable: boolean = false, stride?: number): void {
  202. var buffer = new VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  203. this.setVerticesBuffer(buffer);
  204. }
  205. /**
  206. * Removes a specific vertex data
  207. * @param kind defines the data kind (Position, normal, etc...)
  208. */
  209. public removeVerticesData(kind: string) {
  210. if (this._vertexBuffers[kind]) {
  211. this._vertexBuffers[kind].dispose();
  212. delete this._vertexBuffers[kind];
  213. }
  214. }
  215. /**
  216. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  217. * @param buffer defines the vertex buffer to use
  218. * @param totalVertices defines the total number of vertices for position kind (could be null)
  219. */
  220. public setVerticesBuffer(buffer: VertexBuffer, totalVertices: Nullable<number> = null): void {
  221. var kind = buffer.getKind();
  222. if (this._vertexBuffers[kind]) {
  223. this._vertexBuffers[kind].dispose();
  224. }
  225. this._vertexBuffers[kind] = buffer;
  226. if (kind === VertexBuffer.PositionKind) {
  227. var data = <FloatArray>buffer.getData();
  228. if (totalVertices != null) {
  229. this._totalVertices = totalVertices;
  230. } else {
  231. if (data != null) {
  232. this._totalVertices = data.length / (buffer.byteStride / 4);
  233. }
  234. }
  235. this._updateExtend(data);
  236. this._resetPointsArrayCache();
  237. var meshes = this._meshes;
  238. var numOfMeshes = meshes.length;
  239. for (var index = 0; index < numOfMeshes; index++) {
  240. var mesh = meshes[index];
  241. mesh._boundingInfo = new BoundingInfo(this._extend.minimum, this._extend.maximum);
  242. mesh._createGlobalSubMesh(false);
  243. mesh.computeWorldMatrix(true);
  244. }
  245. }
  246. this.notifyUpdate(kind);
  247. if (this._vertexArrayObjects) {
  248. this._disposeVertexArrayObjects();
  249. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  250. }
  251. }
  252. /**
  253. * Update a specific vertex buffer
  254. * This function will directly update the underlying DataBuffer according to the passed numeric array or Float32Array
  255. * It will do nothing if the buffer is not updatable
  256. * @param kind defines the data kind (Position, normal, etc...)
  257. * @param data defines the data to use
  258. * @param offset defines the offset in the target buffer where to store the data
  259. * @param useBytes set to true if the offset is in bytes
  260. */
  261. public updateVerticesDataDirectly(kind: string, data: DataArray, offset: number, useBytes: boolean = false): void {
  262. var vertexBuffer = this.getVertexBuffer(kind);
  263. if (!vertexBuffer) {
  264. return;
  265. }
  266. vertexBuffer.updateDirectly(data, offset, useBytes);
  267. this.notifyUpdate(kind);
  268. }
  269. /**
  270. * Update a specific vertex buffer
  271. * This function will create a new buffer if the current one is not updatable
  272. * @param kind defines the data kind (Position, normal, etc...)
  273. * @param data defines the data to use
  274. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  275. */
  276. public updateVerticesData(kind: string, data: FloatArray, updateExtends: boolean = false): void {
  277. var vertexBuffer = this.getVertexBuffer(kind);
  278. if (!vertexBuffer) {
  279. return;
  280. }
  281. vertexBuffer.update(data);
  282. if (kind === VertexBuffer.PositionKind) {
  283. this._updateBoundingInfo(updateExtends, data);
  284. }
  285. this.notifyUpdate(kind);
  286. }
  287. private _updateBoundingInfo(updateExtends: boolean, data: Nullable<FloatArray>) {
  288. if (updateExtends) {
  289. this._updateExtend(data);
  290. }
  291. this._resetPointsArrayCache();
  292. if (updateExtends) {
  293. var meshes = this._meshes;
  294. for (const mesh of meshes) {
  295. if (mesh._boundingInfo) {
  296. mesh._boundingInfo.reConstruct(this._extend.minimum, this._extend.maximum);
  297. }
  298. else {
  299. mesh._boundingInfo = new BoundingInfo(this._extend.minimum, this._extend.maximum);
  300. }
  301. const subMeshes = mesh.subMeshes;
  302. for (const subMesh of subMeshes) {
  303. subMesh.refreshBoundingInfo();
  304. }
  305. }
  306. }
  307. }
  308. /** @hidden */
  309. public _bind(effect: Nullable<Effect>, indexToBind?: Nullable<DataBuffer>): void {
  310. if (!effect) {
  311. return;
  312. }
  313. if (indexToBind === undefined) {
  314. indexToBind = this._indexBuffer;
  315. }
  316. let vbs = this.getVertexBuffers();
  317. if (!vbs) {
  318. return;
  319. }
  320. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  321. this._engine.bindBuffers(vbs, indexToBind, effect);
  322. return;
  323. }
  324. // Using VAO
  325. if (!this._vertexArrayObjects[effect.key]) {
  326. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  327. }
  328. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  329. }
  330. /**
  331. * Gets total number of vertices
  332. * @returns the total number of vertices
  333. */
  334. public getTotalVertices(): number {
  335. if (!this.isReady()) {
  336. return 0;
  337. }
  338. return this._totalVertices;
  339. }
  340. /**
  341. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  342. * @param kind defines the data kind (Position, normal, etc...)
  343. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  344. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  345. * @returns a float array containing vertex data
  346. */
  347. public getVerticesData(kind: string, copyWhenShared?: boolean, forceCopy?: boolean): Nullable<FloatArray> {
  348. const vertexBuffer = this.getVertexBuffer(kind);
  349. if (!vertexBuffer) {
  350. return null;
  351. }
  352. let data = vertexBuffer.getData();
  353. if (!data) {
  354. return null;
  355. }
  356. const tightlyPackedByteStride = vertexBuffer.getSize() * VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  357. const count = this._totalVertices * vertexBuffer.getSize();
  358. if (vertexBuffer.type !== VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  359. const copy: number[] = [];
  360. vertexBuffer.forEach(count, (value) => copy.push(value));
  361. return copy;
  362. }
  363. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  364. if (data instanceof Array) {
  365. const offset = vertexBuffer.byteOffset / 4;
  366. return Tools.Slice(data, offset, offset + count);
  367. }
  368. else if (data instanceof ArrayBuffer) {
  369. return new Float32Array(data, vertexBuffer.byteOffset, count);
  370. }
  371. else {
  372. const offset = data.byteOffset + vertexBuffer.byteOffset;
  373. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  374. let result = new Float32Array(count);
  375. let source = new Float32Array(data.buffer, offset, count);
  376. result.set(source);
  377. return result;
  378. }
  379. return new Float32Array(data.buffer, offset, count);
  380. }
  381. }
  382. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  383. return Tools.Slice(data);
  384. }
  385. return data;
  386. }
  387. /**
  388. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  389. * @param kind defines the data kind (Position, normal, etc...)
  390. * @returns true if the vertex buffer with the specified kind is updatable
  391. */
  392. public isVertexBufferUpdatable(kind: string): boolean {
  393. let vb = this._vertexBuffers[kind];
  394. if (!vb) {
  395. return false;
  396. }
  397. return vb.isUpdatable();
  398. }
  399. /**
  400. * Gets a specific vertex buffer
  401. * @param kind defines the data kind (Position, normal, etc...)
  402. * @returns a VertexBuffer
  403. */
  404. public getVertexBuffer(kind: string): Nullable<VertexBuffer> {
  405. if (!this.isReady()) {
  406. return null;
  407. }
  408. return this._vertexBuffers[kind];
  409. }
  410. /**
  411. * Returns all vertex buffers
  412. * @return an object holding all vertex buffers indexed by kind
  413. */
  414. public getVertexBuffers(): Nullable<{ [key: string]: VertexBuffer; }> {
  415. if (!this.isReady()) {
  416. return null;
  417. }
  418. return this._vertexBuffers;
  419. }
  420. /**
  421. * Gets a boolean indicating if specific vertex buffer is present
  422. * @param kind defines the data kind (Position, normal, etc...)
  423. * @returns true if data is present
  424. */
  425. public isVerticesDataPresent(kind: string): boolean {
  426. if (!this._vertexBuffers) {
  427. if (this._delayInfo) {
  428. return this._delayInfo.indexOf(kind) !== -1;
  429. }
  430. return false;
  431. }
  432. return this._vertexBuffers[kind] !== undefined;
  433. }
  434. /**
  435. * Gets a list of all attached data kinds (Position, normal, etc...)
  436. * @returns a list of string containing all kinds
  437. */
  438. public getVerticesDataKinds(): string[] {
  439. var result = [];
  440. var kind;
  441. if (!this._vertexBuffers && this._delayInfo) {
  442. for (kind in this._delayInfo) {
  443. result.push(kind);
  444. }
  445. } else {
  446. for (kind in this._vertexBuffers) {
  447. result.push(kind);
  448. }
  449. }
  450. return result;
  451. }
  452. /**
  453. * Update index buffer
  454. * @param indices defines the indices to store in the index buffer
  455. * @param offset defines the offset in the target buffer where to store the data
  456. * @param gpuMemoryOnly defines a boolean indicating that only the GPU memory must be updated leaving the CPU version of the indices unchanged (false by default)
  457. */
  458. public updateIndices(indices: IndicesArray, offset?: number, gpuMemoryOnly = false): void {
  459. if (!this._indexBuffer) {
  460. return;
  461. }
  462. if (!this._indexBufferIsUpdatable) {
  463. this.setIndices(indices, null, true);
  464. } else {
  465. const needToUpdateSubMeshes = indices.length !== this._indices.length;
  466. if (!gpuMemoryOnly) {
  467. this._indices = indices.slice();
  468. }
  469. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  470. if (needToUpdateSubMeshes) {
  471. for (const mesh of this._meshes) {
  472. mesh._createGlobalSubMesh(true);
  473. }
  474. }
  475. }
  476. }
  477. /**
  478. * Creates a new index buffer
  479. * @param indices defines the indices to store in the index buffer
  480. * @param totalVertices defines the total number of vertices (could be null)
  481. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  482. */
  483. public setIndices(indices: IndicesArray, totalVertices: Nullable<number> = null, updatable: boolean = false): void {
  484. if (this._indexBuffer) {
  485. this._engine._releaseBuffer(this._indexBuffer);
  486. }
  487. this._disposeVertexArrayObjects();
  488. this._indices = indices;
  489. this._indexBufferIsUpdatable = updatable;
  490. if (this._meshes.length !== 0 && this._indices) {
  491. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  492. }
  493. if (totalVertices != undefined) { // including null and undefined
  494. this._totalVertices = totalVertices;
  495. }
  496. for (const mesh of this._meshes) {
  497. mesh._createGlobalSubMesh(true);
  498. }
  499. this.notifyUpdate();
  500. }
  501. /**
  502. * Return the total number of indices
  503. * @returns the total number of indices
  504. */
  505. public getTotalIndices(): number {
  506. if (!this.isReady()) {
  507. return 0;
  508. }
  509. return this._indices.length;
  510. }
  511. /**
  512. * Gets the index buffer array
  513. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  514. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  515. * @returns the index buffer array
  516. */
  517. public getIndices(copyWhenShared?: boolean, forceCopy?: boolean): Nullable<IndicesArray> {
  518. if (!this.isReady()) {
  519. return null;
  520. }
  521. var orig = this._indices;
  522. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  523. return orig;
  524. } else {
  525. var len = orig.length;
  526. var copy = [];
  527. for (var i = 0; i < len; i++) {
  528. copy.push(orig[i]);
  529. }
  530. return copy;
  531. }
  532. }
  533. /**
  534. * Gets the index buffer
  535. * @return the index buffer
  536. */
  537. public getIndexBuffer(): Nullable<DataBuffer> {
  538. if (!this.isReady()) {
  539. return null;
  540. }
  541. return this._indexBuffer;
  542. }
  543. /** @hidden */
  544. public _releaseVertexArrayObject(effect: Nullable<Effect> = null) {
  545. if (!effect || !this._vertexArrayObjects) {
  546. return;
  547. }
  548. if (this._vertexArrayObjects[effect.key]) {
  549. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  550. delete this._vertexArrayObjects[effect.key];
  551. }
  552. }
  553. /**
  554. * Release the associated resources for a specific mesh
  555. * @param mesh defines the source mesh
  556. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  557. */
  558. public releaseForMesh(mesh: Mesh, shouldDispose?: boolean): void {
  559. var meshes = this._meshes;
  560. var index = meshes.indexOf(mesh);
  561. if (index === -1) {
  562. return;
  563. }
  564. meshes.splice(index, 1);
  565. mesh._geometry = null;
  566. if (meshes.length === 0 && shouldDispose) {
  567. this.dispose();
  568. }
  569. }
  570. /**
  571. * Apply current geometry to a given mesh
  572. * @param mesh defines the mesh to apply geometry to
  573. */
  574. public applyToMesh(mesh: Mesh): void {
  575. if (mesh._geometry === this) {
  576. return;
  577. }
  578. var previousGeometry = mesh._geometry;
  579. if (previousGeometry) {
  580. previousGeometry.releaseForMesh(mesh);
  581. }
  582. var meshes = this._meshes;
  583. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  584. mesh._geometry = this;
  585. this._scene.pushGeometry(this);
  586. meshes.push(mesh);
  587. if (this.isReady()) {
  588. this._applyToMesh(mesh);
  589. }
  590. else {
  591. mesh._boundingInfo = this._boundingInfo;
  592. }
  593. }
  594. private _updateExtend(data: Nullable<FloatArray> = null) {
  595. if (!data) {
  596. data = this.getVerticesData(VertexBuffer.PositionKind)!;
  597. }
  598. this._extend = Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  599. }
  600. private _applyToMesh(mesh: Mesh): void {
  601. var numOfMeshes = this._meshes.length;
  602. // vertexBuffers
  603. for (var kind in this._vertexBuffers) {
  604. if (numOfMeshes === 1) {
  605. this._vertexBuffers[kind].create();
  606. }
  607. var buffer = this._vertexBuffers[kind].getBuffer();
  608. if (buffer) {
  609. buffer.references = numOfMeshes;
  610. }
  611. if (kind === VertexBuffer.PositionKind) {
  612. if (!this._extend) {
  613. this._updateExtend();
  614. }
  615. mesh._boundingInfo = new BoundingInfo(this._extend.minimum, this._extend.maximum);
  616. mesh._createGlobalSubMesh(false);
  617. //bounding info was just created again, world matrix should be applied again.
  618. mesh._updateBoundingInfo();
  619. }
  620. }
  621. // indexBuffer
  622. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  623. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  624. }
  625. if (this._indexBuffer) {
  626. this._indexBuffer.references = numOfMeshes;
  627. }
  628. // morphTargets
  629. mesh._syncGeometryWithMorphTargetManager();
  630. // instances
  631. mesh.synchronizeInstances();
  632. }
  633. private notifyUpdate(kind?: string) {
  634. if (this.onGeometryUpdated) {
  635. this.onGeometryUpdated(this, kind);
  636. }
  637. for (var mesh of this._meshes) {
  638. mesh._markSubMeshesAsAttributesDirty();
  639. }
  640. }
  641. /**
  642. * Load the geometry if it was flagged as delay loaded
  643. * @param scene defines the hosting scene
  644. * @param onLoaded defines a callback called when the geometry is loaded
  645. */
  646. public load(scene: Scene, onLoaded?: () => void): void {
  647. if (this.delayLoadState === Constants.DELAYLOADSTATE_LOADING) {
  648. return;
  649. }
  650. if (this.isReady()) {
  651. if (onLoaded) {
  652. onLoaded();
  653. }
  654. return;
  655. }
  656. this.delayLoadState = Constants.DELAYLOADSTATE_LOADING;
  657. this._queueLoad(scene, onLoaded);
  658. }
  659. private _queueLoad(scene: Scene, onLoaded?: () => void): void {
  660. if (!this.delayLoadingFile) {
  661. return;
  662. }
  663. scene._addPendingData(this);
  664. scene._loadFile(this.delayLoadingFile, (data) => {
  665. if (!this._delayLoadingFunction) {
  666. return;
  667. }
  668. this._delayLoadingFunction(JSON.parse(data as string), this);
  669. this.delayLoadState = Constants.DELAYLOADSTATE_LOADED;
  670. this._delayInfo = [];
  671. scene._removePendingData(this);
  672. var meshes = this._meshes;
  673. var numOfMeshes = meshes.length;
  674. for (var index = 0; index < numOfMeshes; index++) {
  675. this._applyToMesh(meshes[index]);
  676. }
  677. if (onLoaded) {
  678. onLoaded();
  679. }
  680. }, undefined, true);
  681. }
  682. /**
  683. * Invert the geometry to move from a right handed system to a left handed one.
  684. */
  685. public toLeftHanded(): void {
  686. // Flip faces
  687. let tIndices = this.getIndices(false);
  688. if (tIndices != null && tIndices.length > 0) {
  689. for (let i = 0; i < tIndices.length; i += 3) {
  690. let tTemp = tIndices[i + 0];
  691. tIndices[i + 0] = tIndices[i + 2];
  692. tIndices[i + 2] = tTemp;
  693. }
  694. this.setIndices(tIndices);
  695. }
  696. // Negate position.z
  697. let tPositions = this.getVerticesData(VertexBuffer.PositionKind, false);
  698. if (tPositions != null && tPositions.length > 0) {
  699. for (let i = 0; i < tPositions.length; i += 3) {
  700. tPositions[i + 2] = -tPositions[i + 2];
  701. }
  702. this.setVerticesData(VertexBuffer.PositionKind, tPositions, false);
  703. }
  704. // Negate normal.z
  705. let tNormals = this.getVerticesData(VertexBuffer.NormalKind, false);
  706. if (tNormals != null && tNormals.length > 0) {
  707. for (let i = 0; i < tNormals.length; i += 3) {
  708. tNormals[i + 2] = -tNormals[i + 2];
  709. }
  710. this.setVerticesData(VertexBuffer.NormalKind, tNormals, false);
  711. }
  712. }
  713. // Cache
  714. /** @hidden */
  715. public _resetPointsArrayCache(): void {
  716. this._positions = null;
  717. }
  718. /** @hidden */
  719. public _generatePointsArray(): boolean {
  720. if (this._positions) {
  721. return true;
  722. }
  723. var data = this.getVerticesData(VertexBuffer.PositionKind);
  724. if (!data || data.length === 0) {
  725. return false;
  726. }
  727. this._positions = [];
  728. for (var index = 0; index < data.length; index += 3) {
  729. this._positions.push(Vector3.FromArray(data, index));
  730. }
  731. return true;
  732. }
  733. /**
  734. * Gets a value indicating if the geometry is disposed
  735. * @returns true if the geometry was disposed
  736. */
  737. public isDisposed(): boolean {
  738. return this._isDisposed;
  739. }
  740. private _disposeVertexArrayObjects(): void {
  741. if (this._vertexArrayObjects) {
  742. for (var kind in this._vertexArrayObjects) {
  743. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  744. }
  745. this._vertexArrayObjects = {};
  746. }
  747. }
  748. /**
  749. * Free all associated resources
  750. */
  751. public dispose(): void {
  752. var meshes = this._meshes;
  753. var numOfMeshes = meshes.length;
  754. var index: number;
  755. for (index = 0; index < numOfMeshes; index++) {
  756. this.releaseForMesh(meshes[index]);
  757. }
  758. this._meshes = [];
  759. this._disposeVertexArrayObjects();
  760. for (var kind in this._vertexBuffers) {
  761. this._vertexBuffers[kind].dispose();
  762. }
  763. this._vertexBuffers = {};
  764. this._totalVertices = 0;
  765. if (this._indexBuffer) {
  766. this._engine._releaseBuffer(this._indexBuffer);
  767. }
  768. this._indexBuffer = null;
  769. this._indices = [];
  770. this.delayLoadState = Constants.DELAYLOADSTATE_NONE;
  771. this.delayLoadingFile = null;
  772. this._delayLoadingFunction = null;
  773. this._delayInfo = [];
  774. this._boundingInfo = null;
  775. this._scene.removeGeometry(this);
  776. this._isDisposed = true;
  777. }
  778. /**
  779. * Clone the current geometry into a new geometry
  780. * @param id defines the unique ID of the new geometry
  781. * @returns a new geometry object
  782. */
  783. public copy(id: string): Geometry {
  784. var vertexData = new VertexData();
  785. vertexData.indices = [];
  786. var indices = this.getIndices();
  787. if (indices) {
  788. for (var index = 0; index < indices.length; index++) {
  789. (<number[]>vertexData.indices).push(indices[index]);
  790. }
  791. }
  792. var updatable = false;
  793. var stopChecking = false;
  794. var kind;
  795. for (kind in this._vertexBuffers) {
  796. // using slice() to make a copy of the array and not just reference it
  797. var data = this.getVerticesData(kind);
  798. if (data) {
  799. if (data instanceof Float32Array) {
  800. vertexData.set(new Float32Array(<Float32Array>data), kind);
  801. } else {
  802. vertexData.set((<number[]>data).slice(0), kind);
  803. }
  804. if (!stopChecking) {
  805. let vb = this.getVertexBuffer(kind);
  806. if (vb) {
  807. updatable = vb.isUpdatable();
  808. stopChecking = !updatable;
  809. }
  810. }
  811. }
  812. }
  813. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  814. geometry.delayLoadState = this.delayLoadState;
  815. geometry.delayLoadingFile = this.delayLoadingFile;
  816. geometry._delayLoadingFunction = this._delayLoadingFunction;
  817. for (kind in this._delayInfo) {
  818. geometry._delayInfo = geometry._delayInfo || [];
  819. geometry._delayInfo.push(kind);
  820. }
  821. // Bounding info
  822. geometry._boundingInfo = new BoundingInfo(this._extend.minimum, this._extend.maximum);
  823. return geometry;
  824. }
  825. /**
  826. * Serialize the current geometry info (and not the vertices data) into a JSON object
  827. * @return a JSON representation of the current geometry data (without the vertices data)
  828. */
  829. public serialize(): any {
  830. var serializationObject: any = {};
  831. serializationObject.id = this.id;
  832. serializationObject.updatable = this._updatable;
  833. if (Tags && Tags.HasTags(this)) {
  834. serializationObject.tags = Tags.GetTags(this);
  835. }
  836. return serializationObject;
  837. }
  838. private toNumberArray(origin: Nullable<Float32Array | IndicesArray>): number[] {
  839. if (Array.isArray(origin)) {
  840. return origin;
  841. } else {
  842. return Array.prototype.slice.call(origin);
  843. }
  844. }
  845. /**
  846. * Serialize all vertices data into a JSON oject
  847. * @returns a JSON representation of the current geometry data
  848. */
  849. public serializeVerticeData(): any {
  850. var serializationObject = this.serialize();
  851. if (this.isVerticesDataPresent(VertexBuffer.PositionKind)) {
  852. serializationObject.positions = this.toNumberArray(this.getVerticesData(VertexBuffer.PositionKind));
  853. if (this.isVertexBufferUpdatable(VertexBuffer.PositionKind)) {
  854. serializationObject.positions._updatable = true;
  855. }
  856. }
  857. if (this.isVerticesDataPresent(VertexBuffer.NormalKind)) {
  858. serializationObject.normals = this.toNumberArray(this.getVerticesData(VertexBuffer.NormalKind));
  859. if (this.isVertexBufferUpdatable(VertexBuffer.NormalKind)) {
  860. serializationObject.normals._updatable = true;
  861. }
  862. }
  863. if (this.isVerticesDataPresent(VertexBuffer.TangentKind)) {
  864. serializationObject.tangets = this.toNumberArray(this.getVerticesData(VertexBuffer.TangentKind));
  865. if (this.isVertexBufferUpdatable(VertexBuffer.TangentKind)) {
  866. serializationObject.tangets._updatable = true;
  867. }
  868. }
  869. if (this.isVerticesDataPresent(VertexBuffer.UVKind)) {
  870. serializationObject.uvs = this.toNumberArray(this.getVerticesData(VertexBuffer.UVKind));
  871. if (this.isVertexBufferUpdatable(VertexBuffer.UVKind)) {
  872. serializationObject.uvs._updatable = true;
  873. }
  874. }
  875. if (this.isVerticesDataPresent(VertexBuffer.UV2Kind)) {
  876. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(VertexBuffer.UV2Kind));
  877. if (this.isVertexBufferUpdatable(VertexBuffer.UV2Kind)) {
  878. serializationObject.uv2s._updatable = true;
  879. }
  880. }
  881. if (this.isVerticesDataPresent(VertexBuffer.UV3Kind)) {
  882. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(VertexBuffer.UV3Kind));
  883. if (this.isVertexBufferUpdatable(VertexBuffer.UV3Kind)) {
  884. serializationObject.uv3s._updatable = true;
  885. }
  886. }
  887. if (this.isVerticesDataPresent(VertexBuffer.UV4Kind)) {
  888. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(VertexBuffer.UV4Kind));
  889. if (this.isVertexBufferUpdatable(VertexBuffer.UV4Kind)) {
  890. serializationObject.uv4s._updatable = true;
  891. }
  892. }
  893. if (this.isVerticesDataPresent(VertexBuffer.UV5Kind)) {
  894. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(VertexBuffer.UV5Kind));
  895. if (this.isVertexBufferUpdatable(VertexBuffer.UV5Kind)) {
  896. serializationObject.uv5s._updatable = true;
  897. }
  898. }
  899. if (this.isVerticesDataPresent(VertexBuffer.UV6Kind)) {
  900. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(VertexBuffer.UV6Kind));
  901. if (this.isVertexBufferUpdatable(VertexBuffer.UV6Kind)) {
  902. serializationObject.uv6s._updatable = true;
  903. }
  904. }
  905. if (this.isVerticesDataPresent(VertexBuffer.ColorKind)) {
  906. serializationObject.colors = this.toNumberArray(this.getVerticesData(VertexBuffer.ColorKind));
  907. if (this.isVertexBufferUpdatable(VertexBuffer.ColorKind)) {
  908. serializationObject.colors._updatable = true;
  909. }
  910. }
  911. if (this.isVerticesDataPresent(VertexBuffer.MatricesIndicesKind)) {
  912. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(VertexBuffer.MatricesIndicesKind));
  913. serializationObject.matricesIndices._isExpanded = true;
  914. if (this.isVertexBufferUpdatable(VertexBuffer.MatricesIndicesKind)) {
  915. serializationObject.matricesIndices._updatable = true;
  916. }
  917. }
  918. if (this.isVerticesDataPresent(VertexBuffer.MatricesWeightsKind)) {
  919. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(VertexBuffer.MatricesWeightsKind));
  920. if (this.isVertexBufferUpdatable(VertexBuffer.MatricesWeightsKind)) {
  921. serializationObject.matricesWeights._updatable = true;
  922. }
  923. }
  924. serializationObject.indices = this.toNumberArray(this.getIndices());
  925. return serializationObject;
  926. }
  927. // Statics
  928. /**
  929. * Extracts a clone of a mesh geometry
  930. * @param mesh defines the source mesh
  931. * @param id defines the unique ID of the new geometry object
  932. * @returns the new geometry object
  933. */
  934. public static ExtractFromMesh(mesh: Mesh, id: string): Nullable<Geometry> {
  935. var geometry = mesh._geometry;
  936. if (!geometry) {
  937. return null;
  938. }
  939. return geometry.copy(id);
  940. }
  941. /**
  942. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  943. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  944. * Be aware Math.random() could cause collisions, but:
  945. * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide"
  946. * @returns a string containing a new GUID
  947. */
  948. public static RandomId(): string {
  949. return Tools.RandomId();
  950. }
  951. /** @hidden */
  952. public static _ImportGeometry(parsedGeometry: any, mesh: Mesh): void {
  953. var scene = mesh.getScene();
  954. // Geometry
  955. var geometryId = parsedGeometry.geometryId;
  956. if (geometryId) {
  957. var geometry = scene.getGeometryByID(geometryId);
  958. if (geometry) {
  959. geometry.applyToMesh(mesh);
  960. }
  961. } else if (parsedGeometry instanceof ArrayBuffer) {
  962. var binaryInfo = mesh._binaryInfo;
  963. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  964. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  965. mesh.setVerticesData(VertexBuffer.PositionKind, positionsData, false);
  966. }
  967. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  968. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  969. mesh.setVerticesData(VertexBuffer.NormalKind, normalsData, false);
  970. }
  971. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  972. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  973. mesh.setVerticesData(VertexBuffer.TangentKind, tangentsData, false);
  974. }
  975. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  976. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  977. mesh.setVerticesData(VertexBuffer.UVKind, uvsData, false);
  978. }
  979. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  980. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  981. mesh.setVerticesData(VertexBuffer.UV2Kind, uvs2Data, false);
  982. }
  983. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  984. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  985. mesh.setVerticesData(VertexBuffer.UV3Kind, uvs3Data, false);
  986. }
  987. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  988. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  989. mesh.setVerticesData(VertexBuffer.UV4Kind, uvs4Data, false);
  990. }
  991. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  992. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  993. mesh.setVerticesData(VertexBuffer.UV5Kind, uvs5Data, false);
  994. }
  995. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  996. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  997. mesh.setVerticesData(VertexBuffer.UV6Kind, uvs6Data, false);
  998. }
  999. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  1000. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  1001. mesh.setVerticesData(VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  1002. }
  1003. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  1004. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  1005. var floatIndices = [];
  1006. for (var i = 0; i < matricesIndicesData.length; i++) {
  1007. var index = matricesIndicesData[i];
  1008. floatIndices.push(index & 0x000000FF);
  1009. floatIndices.push((index & 0x0000FF00) >> 8);
  1010. floatIndices.push((index & 0x00FF0000) >> 16);
  1011. floatIndices.push(index >> 24);
  1012. }
  1013. mesh.setVerticesData(VertexBuffer.MatricesIndicesKind, floatIndices, false);
  1014. }
  1015. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  1016. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  1017. mesh.setVerticesData(VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  1018. }
  1019. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  1020. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  1021. mesh.setIndices(indicesData, null);
  1022. }
  1023. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  1024. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  1025. mesh.subMeshes = [];
  1026. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  1027. var materialIndex = subMeshesData[(i * 5) + 0];
  1028. var verticesStart = subMeshesData[(i * 5) + 1];
  1029. var verticesCount = subMeshesData[(i * 5) + 2];
  1030. var indexStart = subMeshesData[(i * 5) + 3];
  1031. var indexCount = subMeshesData[(i * 5) + 4];
  1032. SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, <AbstractMesh>mesh);
  1033. }
  1034. }
  1035. } else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  1036. mesh.setVerticesData(VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  1037. mesh.setVerticesData(VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  1038. if (parsedGeometry.tangents) {
  1039. mesh.setVerticesData(VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  1040. }
  1041. if (parsedGeometry.uvs) {
  1042. mesh.setVerticesData(VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  1043. }
  1044. if (parsedGeometry.uvs2) {
  1045. mesh.setVerticesData(VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  1046. }
  1047. if (parsedGeometry.uvs3) {
  1048. mesh.setVerticesData(VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  1049. }
  1050. if (parsedGeometry.uvs4) {
  1051. mesh.setVerticesData(VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  1052. }
  1053. if (parsedGeometry.uvs5) {
  1054. mesh.setVerticesData(VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  1055. }
  1056. if (parsedGeometry.uvs6) {
  1057. mesh.setVerticesData(VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  1058. }
  1059. if (parsedGeometry.colors) {
  1060. mesh.setVerticesData(VertexBuffer.ColorKind, Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  1061. }
  1062. if (parsedGeometry.matricesIndices) {
  1063. if (!parsedGeometry.matricesIndices._isExpanded) {
  1064. var floatIndices = [];
  1065. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  1066. var matricesIndex = parsedGeometry.matricesIndices[i];
  1067. floatIndices.push(matricesIndex & 0x000000FF);
  1068. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  1069. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  1070. floatIndices.push(matricesIndex >> 24);
  1071. }
  1072. mesh.setVerticesData(VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  1073. } else {
  1074. delete parsedGeometry.matricesIndices._isExpanded;
  1075. mesh.setVerticesData(VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  1076. }
  1077. }
  1078. if (parsedGeometry.matricesIndicesExtra) {
  1079. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  1080. var floatIndices = [];
  1081. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  1082. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  1083. floatIndices.push(matricesIndex & 0x000000FF);
  1084. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  1085. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  1086. floatIndices.push(matricesIndex >> 24);
  1087. }
  1088. mesh.setVerticesData(VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  1089. } else {
  1090. delete parsedGeometry.matricesIndices._isExpanded;
  1091. mesh.setVerticesData(VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  1092. }
  1093. }
  1094. if (parsedGeometry.matricesWeights) {
  1095. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  1096. mesh.setVerticesData(VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  1097. }
  1098. if (parsedGeometry.matricesWeightsExtra) {
  1099. mesh.setVerticesData(VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  1100. }
  1101. mesh.setIndices(parsedGeometry.indices, null);
  1102. }
  1103. // SubMeshes
  1104. if (parsedGeometry.subMeshes) {
  1105. mesh.subMeshes = [];
  1106. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  1107. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  1108. SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, <AbstractMesh>mesh);
  1109. }
  1110. }
  1111. // Flat shading
  1112. if (mesh._shouldGenerateFlatShading) {
  1113. mesh.convertToFlatShadedMesh();
  1114. delete mesh._shouldGenerateFlatShading;
  1115. }
  1116. // Update
  1117. mesh.computeWorldMatrix(true);
  1118. scene.onMeshImportedObservable.notifyObservers(<AbstractMesh>mesh);
  1119. }
  1120. private static _CleanMatricesWeights(parsedGeometry: any, mesh: Mesh): void {
  1121. const epsilon: number = 1e-3;
  1122. if (!SceneLoaderFlags.CleanBoneMatrixWeights) {
  1123. return;
  1124. }
  1125. let noInfluenceBoneIndex = 0.0;
  1126. if (parsedGeometry.skeletonId > -1) {
  1127. let skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  1128. if (!skeleton) {
  1129. return;
  1130. }
  1131. noInfluenceBoneIndex = skeleton.bones.length;
  1132. } else {
  1133. return;
  1134. }
  1135. let matricesIndices = (<FloatArray>mesh.getVerticesData(VertexBuffer.MatricesIndicesKind));
  1136. let matricesIndicesExtra = (<FloatArray>mesh.getVerticesData(VertexBuffer.MatricesIndicesExtraKind));
  1137. let matricesWeights = parsedGeometry.matricesWeights;
  1138. let matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  1139. let influencers = parsedGeometry.numBoneInfluencer;
  1140. let size = matricesWeights.length;
  1141. for (var i = 0; i < size; i += 4) {
  1142. let weight = 0.0;
  1143. let firstZeroWeight = -1;
  1144. for (var j = 0; j < 4; j++) {
  1145. let w = matricesWeights[i + j];
  1146. weight += w;
  1147. if (w < epsilon && firstZeroWeight < 0) {
  1148. firstZeroWeight = j;
  1149. }
  1150. }
  1151. if (matricesWeightsExtra) {
  1152. for (var j = 0; j < 4; j++) {
  1153. let w = matricesWeightsExtra[i + j];
  1154. weight += w;
  1155. if (w < epsilon && firstZeroWeight < 0) {
  1156. firstZeroWeight = j + 4;
  1157. }
  1158. }
  1159. }
  1160. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  1161. firstZeroWeight = influencers - 1;
  1162. }
  1163. if (weight > epsilon) {
  1164. let mweight = 1.0 / weight;
  1165. for (var j = 0; j < 4; j++) {
  1166. matricesWeights[i + j] *= mweight;
  1167. }
  1168. if (matricesWeightsExtra) {
  1169. for (var j = 0; j < 4; j++) {
  1170. matricesWeightsExtra[i + j] *= mweight;
  1171. }
  1172. }
  1173. } else {
  1174. if (firstZeroWeight >= 4) {
  1175. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  1176. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  1177. } else {
  1178. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  1179. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  1180. }
  1181. }
  1182. }
  1183. mesh.setVerticesData(VertexBuffer.MatricesIndicesKind, matricesIndices);
  1184. if (parsedGeometry.matricesWeightsExtra) {
  1185. mesh.setVerticesData(VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  1186. }
  1187. }
  1188. /**
  1189. * Create a new geometry from persisted data (Using .babylon file format)
  1190. * @param parsedVertexData defines the persisted data
  1191. * @param scene defines the hosting scene
  1192. * @param rootUrl defines the root url to use to load assets (like delayed data)
  1193. * @returns the new geometry object
  1194. */
  1195. public static Parse(parsedVertexData: any, scene: Scene, rootUrl: string): Nullable<Geometry> {
  1196. if (scene.getGeometryByID(parsedVertexData.id)) {
  1197. return null; // null since geometry could be something else than a box...
  1198. }
  1199. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  1200. if (Tags) {
  1201. Tags.AddTagsTo(geometry, parsedVertexData.tags);
  1202. }
  1203. if (parsedVertexData.delayLoadingFile) {
  1204. geometry.delayLoadState = Constants.DELAYLOADSTATE_NOTLOADED;
  1205. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  1206. geometry._boundingInfo = new BoundingInfo(Vector3.FromArray(parsedVertexData.boundingBoxMinimum), Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  1207. geometry._delayInfo = [];
  1208. if (parsedVertexData.hasUVs) {
  1209. geometry._delayInfo.push(VertexBuffer.UVKind);
  1210. }
  1211. if (parsedVertexData.hasUVs2) {
  1212. geometry._delayInfo.push(VertexBuffer.UV2Kind);
  1213. }
  1214. if (parsedVertexData.hasUVs3) {
  1215. geometry._delayInfo.push(VertexBuffer.UV3Kind);
  1216. }
  1217. if (parsedVertexData.hasUVs4) {
  1218. geometry._delayInfo.push(VertexBuffer.UV4Kind);
  1219. }
  1220. if (parsedVertexData.hasUVs5) {
  1221. geometry._delayInfo.push(VertexBuffer.UV5Kind);
  1222. }
  1223. if (parsedVertexData.hasUVs6) {
  1224. geometry._delayInfo.push(VertexBuffer.UV6Kind);
  1225. }
  1226. if (parsedVertexData.hasColors) {
  1227. geometry._delayInfo.push(VertexBuffer.ColorKind);
  1228. }
  1229. if (parsedVertexData.hasMatricesIndices) {
  1230. geometry._delayInfo.push(VertexBuffer.MatricesIndicesKind);
  1231. }
  1232. if (parsedVertexData.hasMatricesWeights) {
  1233. geometry._delayInfo.push(VertexBuffer.MatricesWeightsKind);
  1234. }
  1235. geometry._delayLoadingFunction = VertexData.ImportVertexData;
  1236. } else {
  1237. VertexData.ImportVertexData(parsedVertexData, geometry);
  1238. }
  1239. scene.pushGeometry(geometry, true);
  1240. return geometry;
  1241. }
  1242. }