babylon.geometry.ts 89 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222
  1. module BABYLON {
  2. /**
  3. * Class used to store geometry data (vertex buffers + index buffer)
  4. */
  5. export class Geometry implements IGetSetVerticesData {
  6. // Members
  7. /**
  8. * Gets or sets the ID of the geometry
  9. */
  10. public id: string;
  11. /**
  12. * Gets or sets the unique ID of the geometry
  13. */
  14. public uniqueId: number;
  15. /**
  16. * Gets the delay loading state of the geometry (none by default which means not delayed)
  17. */
  18. public delayLoadState = Engine.DELAYLOADSTATE_NONE;
  19. /**
  20. * Gets the file containing the data to load when running in delay load state
  21. */
  22. public delayLoadingFile: Nullable<string>;
  23. /**
  24. * Callback called when the geometry is updated
  25. */
  26. public onGeometryUpdated: (geometry: Geometry, kind?: string) => void;
  27. // Private
  28. private _scene: Scene;
  29. private _engine: Engine;
  30. private _meshes: Mesh[];
  31. private _totalVertices = 0;
  32. /** @hidden */
  33. public _indices: IndicesArray;
  34. /** @hidden */
  35. public _vertexBuffers: { [key: string]: VertexBuffer; };
  36. private _isDisposed = false;
  37. private _extend: { minimum: Vector3, maximum: Vector3 };
  38. private _boundingBias: Vector2;
  39. /** @hidden */
  40. public _delayInfo: Array<string>;
  41. private _indexBuffer: Nullable<WebGLBuffer>;
  42. private _indexBufferIsUpdatable = false;
  43. /** @hidden */
  44. public _boundingInfo: Nullable<BoundingInfo>;
  45. /** @hidden */
  46. public _delayLoadingFunction: Nullable<(any: any, geometry: Geometry) => void>;
  47. /** @hidden */
  48. public _softwareSkinningFrameId: number;
  49. private _vertexArrayObjects: { [key: string]: WebGLVertexArrayObject; };
  50. private _updatable: boolean;
  51. // Cache
  52. /** @hidden */
  53. public _positions: Nullable<Vector3[]>;
  54. /**
  55. * 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
  56. */
  57. public get boundingBias(): Vector2 {
  58. return this._boundingBias;
  59. }
  60. /**
  61. * 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
  62. */
  63. public set boundingBias(value: Vector2) {
  64. if (this._boundingBias) {
  65. this._boundingBias.copyFrom(value);
  66. }
  67. else {
  68. this._boundingBias = value.clone();
  69. }
  70. this._updateBoundingInfo(true, null);
  71. }
  72. /**
  73. * Static function used to attach a new empty geometry to a mesh
  74. * @param mesh defines the mesh to attach the geometry to
  75. * @returns the new Geometry
  76. */
  77. public static CreateGeometryForMesh(mesh: Mesh): Geometry {
  78. let geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  79. geometry.applyToMesh(mesh);
  80. return geometry;
  81. }
  82. /**
  83. * Creates a new geometry
  84. * @param id defines the unique ID
  85. * @param scene defines the hosting scene
  86. * @param vertexData defines the VertexData used to get geometry data
  87. * @param updatable defines if geometry must be updatable (false by default)
  88. * @param mesh defines the mesh that will be associated with the geometry
  89. */
  90. constructor(id: string, scene: Scene, vertexData?: VertexData, updatable: boolean = false, mesh: Nullable<Mesh> = null) {
  91. this.id = id;
  92. this.uniqueId = scene.getUniqueId();
  93. this._engine = scene.getEngine();
  94. this._meshes = [];
  95. this._scene = scene;
  96. //Init vertex buffer cache
  97. this._vertexBuffers = {};
  98. this._indices = [];
  99. this._updatable = updatable;
  100. // vertexData
  101. if (vertexData) {
  102. this.setAllVerticesData(vertexData, updatable);
  103. }
  104. else {
  105. this._totalVertices = 0;
  106. this._indices = [];
  107. }
  108. if (this._engine.getCaps().vertexArrayObject) {
  109. this._vertexArrayObjects = {};
  110. }
  111. // applyToMesh
  112. if (mesh) {
  113. this.applyToMesh(mesh);
  114. mesh.computeWorldMatrix(true);
  115. }
  116. }
  117. /**
  118. * Gets the current extend of the geometry
  119. */
  120. public get extend(): { minimum: Vector3, maximum: Vector3 } {
  121. return this._extend;
  122. }
  123. /**
  124. * Gets the hosting scene
  125. * @returns the hosting Scene
  126. */
  127. public getScene(): Scene {
  128. return this._scene;
  129. }
  130. /**
  131. * Gets the hosting engine
  132. * @returns the hosting Engine
  133. */
  134. public getEngine(): Engine {
  135. return this._engine;
  136. }
  137. /**
  138. * Defines if the geometry is ready to use
  139. * @returns true if the geometry is ready to be used
  140. */
  141. public isReady(): boolean {
  142. return this.delayLoadState === Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === Engine.DELAYLOADSTATE_NONE;
  143. }
  144. /**
  145. * Gets a value indicating that the geometry should not be serialized
  146. */
  147. public get doNotSerialize(): boolean {
  148. for (var index = 0; index < this._meshes.length; index++) {
  149. if (!this._meshes[index].doNotSerialize) {
  150. return false;
  151. }
  152. }
  153. return true;
  154. }
  155. /** @hidden */
  156. public _rebuild(): void {
  157. if (this._vertexArrayObjects) {
  158. this._vertexArrayObjects = {};
  159. }
  160. // Index buffer
  161. if (this._meshes.length !== 0 && this._indices) {
  162. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  163. }
  164. // Vertex buffers
  165. for (var key in this._vertexBuffers) {
  166. let vertexBuffer = <VertexBuffer>this._vertexBuffers[key];
  167. vertexBuffer._rebuild();
  168. }
  169. }
  170. /**
  171. * Affects all geometry data in one call
  172. * @param vertexData defines the geometry data
  173. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  174. */
  175. public setAllVerticesData(vertexData: VertexData, updatable?: boolean): void {
  176. vertexData.applyToGeometry(this, updatable);
  177. this.notifyUpdate();
  178. }
  179. /**
  180. * Set specific vertex data
  181. * @param kind defines the data kind (Position, normal, etc...)
  182. * @param data defines the vertex data to use
  183. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  184. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  185. */
  186. public setVerticesData(kind: string, data: FloatArray, updatable: boolean = false, stride?: number): void {
  187. var buffer = new VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  188. this.setVerticesBuffer(buffer);
  189. }
  190. /**
  191. * Removes a specific vertex data
  192. * @param kind defines the data kind (Position, normal, etc...)
  193. */
  194. public removeVerticesData(kind: string) {
  195. if (this._vertexBuffers[kind]) {
  196. this._vertexBuffers[kind].dispose();
  197. delete this._vertexBuffers[kind];
  198. }
  199. }
  200. /**
  201. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  202. * @param buffer defines the vertex buffer to use
  203. * @param totalVertices defines the total number of vertices for position kind (could be null)
  204. */
  205. public setVerticesBuffer(buffer: VertexBuffer, totalVertices: Nullable<number> = null): void {
  206. var kind = buffer.getKind();
  207. if (this._vertexBuffers[kind]) {
  208. this._vertexBuffers[kind].dispose();
  209. }
  210. this._vertexBuffers[kind] = buffer;
  211. if (kind === VertexBuffer.PositionKind) {
  212. var data = <FloatArray>buffer.getData();
  213. if (totalVertices != null) {
  214. this._totalVertices = totalVertices;
  215. } else {
  216. if (data != null) {
  217. this._totalVertices = data.length / (buffer.byteStride / 4);
  218. }
  219. }
  220. this._updateExtend(data);
  221. this._resetPointsArrayCache();
  222. var meshes = this._meshes;
  223. var numOfMeshes = meshes.length;
  224. for (var index = 0; index < numOfMeshes; index++) {
  225. var mesh = meshes[index];
  226. mesh._boundingInfo = new BoundingInfo(this._extend.minimum, this._extend.maximum);
  227. mesh._createGlobalSubMesh(false);
  228. mesh.computeWorldMatrix(true);
  229. }
  230. }
  231. this.notifyUpdate(kind);
  232. if (this._vertexArrayObjects) {
  233. this._disposeVertexArrayObjects();
  234. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  235. }
  236. }
  237. /**
  238. * Update a specific vertex buffer
  239. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  240. * It will do nothing if the buffer is not updatable
  241. * @param kind defines the data kind (Position, normal, etc...)
  242. * @param data defines the data to use
  243. * @param offset defines the offset in the target buffer where to store the data
  244. * @param useBytes set to true if the offset is in bytes
  245. */
  246. public updateVerticesDataDirectly(kind: string, data: DataArray, offset: number, useBytes: boolean = false): void {
  247. var vertexBuffer = this.getVertexBuffer(kind);
  248. if (!vertexBuffer) {
  249. return;
  250. }
  251. vertexBuffer.updateDirectly(data, offset, useBytes);
  252. this.notifyUpdate(kind);
  253. }
  254. /**
  255. * Update a specific vertex buffer
  256. * This function will create a new buffer if the current one is not updatable
  257. * @param kind defines the data kind (Position, normal, etc...)
  258. * @param data defines the data to use
  259. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  260. */
  261. public updateVerticesData(kind: string, data: FloatArray, updateExtends: boolean = false): void {
  262. var vertexBuffer = this.getVertexBuffer(kind);
  263. if (!vertexBuffer) {
  264. return;
  265. }
  266. vertexBuffer.update(data);
  267. if (kind === VertexBuffer.PositionKind) {
  268. this._updateBoundingInfo(updateExtends, data);
  269. }
  270. this.notifyUpdate(kind);
  271. }
  272. private _updateBoundingInfo(updateExtends: boolean, data: Nullable<FloatArray>) {
  273. if (updateExtends) {
  274. this._updateExtend(data);
  275. }
  276. this._resetPointsArrayCache();
  277. if (updateExtends) {
  278. var meshes = this._meshes;
  279. for (const mesh of meshes) {
  280. if (mesh._boundingInfo) {
  281. mesh._boundingInfo.reConstruct(this._extend.minimum, this._extend.maximum);
  282. }
  283. else {
  284. mesh._boundingInfo = new BoundingInfo(this._extend.minimum, this._extend.maximum);
  285. }
  286. const subMeshes = mesh.subMeshes;
  287. for (const subMesh of subMeshes) {
  288. subMesh.refreshBoundingInfo();
  289. }
  290. }
  291. }
  292. }
  293. /** @hidden */
  294. public _bind(effect: Nullable<Effect>, indexToBind?: Nullable<WebGLBuffer>): void {
  295. if (!effect) {
  296. return;
  297. }
  298. if (indexToBind === undefined) {
  299. indexToBind = this._indexBuffer;
  300. }
  301. let vbs = this.getVertexBuffers();
  302. if (!vbs) {
  303. return;
  304. }
  305. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  306. this._engine.bindBuffers(vbs, indexToBind, effect);
  307. return;
  308. }
  309. // Using VAO
  310. if (!this._vertexArrayObjects[effect.key]) {
  311. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  312. }
  313. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  314. }
  315. /**
  316. * Gets total number of vertices
  317. * @returns the total number of vertices
  318. */
  319. public getTotalVertices(): number {
  320. if (!this.isReady()) {
  321. return 0;
  322. }
  323. return this._totalVertices;
  324. }
  325. /**
  326. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  327. * @param kind defines the data kind (Position, normal, etc...)
  328. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  329. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  330. * @returns a float array containing vertex data
  331. */
  332. public getVerticesData(kind: string, copyWhenShared?: boolean, forceCopy?: boolean): Nullable<FloatArray> {
  333. const vertexBuffer = this.getVertexBuffer(kind);
  334. if (!vertexBuffer) {
  335. return null;
  336. }
  337. let data = vertexBuffer.getData();
  338. if (!data) {
  339. return null;
  340. }
  341. const tightlyPackedByteStride = vertexBuffer.getSize() * VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  342. const count = this._totalVertices * vertexBuffer.getSize();
  343. if (vertexBuffer.type !== VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  344. const copy : number[] = [];
  345. vertexBuffer.forEach(count, (value) => copy.push(value));
  346. return copy;
  347. }
  348. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  349. if (data instanceof Array) {
  350. const offset = vertexBuffer.byteOffset / 4;
  351. return Tools.Slice(data, offset, offset + count);
  352. }
  353. else if (data instanceof ArrayBuffer) {
  354. return new Float32Array(data, vertexBuffer.byteOffset, count);
  355. }
  356. else {
  357. const offset = data.byteOffset + vertexBuffer.byteOffset;
  358. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  359. let result = new Float32Array(count);
  360. let source = new Float32Array(data.buffer, offset, count);
  361. result.set(source);
  362. return result;
  363. }
  364. return new Float32Array(data.buffer, offset, count);
  365. }
  366. }
  367. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  368. return Tools.Slice(data);
  369. }
  370. return data;
  371. }
  372. /**
  373. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  374. * @param kind defines the data kind (Position, normal, etc...)
  375. * @returns true if the vertex buffer with the specified kind is updatable
  376. */
  377. public isVertexBufferUpdatable(kind: string): boolean {
  378. let vb = this._vertexBuffers[kind];
  379. if (!vb) {
  380. return false;
  381. }
  382. return vb.isUpdatable();
  383. }
  384. /**
  385. * Gets a specific vertex buffer
  386. * @param kind defines the data kind (Position, normal, etc...)
  387. * @returns a VertexBuffer
  388. */
  389. public getVertexBuffer(kind: string): Nullable<VertexBuffer> {
  390. if (!this.isReady()) {
  391. return null;
  392. }
  393. return this._vertexBuffers[kind];
  394. }
  395. /**
  396. * Returns all vertex buffers
  397. * @return an object holding all vertex buffers indexed by kind
  398. */
  399. public getVertexBuffers(): Nullable<{ [key: string]: VertexBuffer; }> {
  400. if (!this.isReady()) {
  401. return null;
  402. }
  403. return this._vertexBuffers;
  404. }
  405. /**
  406. * Gets a boolean indicating if specific vertex buffer is present
  407. * @param kind defines the data kind (Position, normal, etc...)
  408. * @returns true if data is present
  409. */
  410. public isVerticesDataPresent(kind: string): boolean {
  411. if (!this._vertexBuffers) {
  412. if (this._delayInfo) {
  413. return this._delayInfo.indexOf(kind) !== -1;
  414. }
  415. return false;
  416. }
  417. return this._vertexBuffers[kind] !== undefined;
  418. }
  419. /**
  420. * Gets a list of all attached data kinds (Position, normal, etc...)
  421. * @returns a list of string containing all kinds
  422. */
  423. public getVerticesDataKinds(): string[] {
  424. var result = [];
  425. var kind;
  426. if (!this._vertexBuffers && this._delayInfo) {
  427. for (kind in this._delayInfo) {
  428. result.push(kind);
  429. }
  430. } else {
  431. for (kind in this._vertexBuffers) {
  432. result.push(kind);
  433. }
  434. }
  435. return result;
  436. }
  437. /**
  438. * Update index buffer
  439. * @param indices defines the indices to store in the index buffer
  440. * @param offset defines the offset in the target buffer where to store the data
  441. */
  442. public updateIndices(indices: IndicesArray, offset?: number): void {
  443. if (!this._indexBuffer) {
  444. return;
  445. }
  446. if (!this._indexBufferIsUpdatable) {
  447. this.setIndices(indices, null, true);
  448. } else {
  449. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  450. }
  451. }
  452. /**
  453. * Creates a new index buffer
  454. * @param indices defines the indices to store in the index buffer
  455. * @param totalVertices defines the total number of vertices (could be null)
  456. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  457. */
  458. public setIndices(indices: IndicesArray, totalVertices: Nullable<number> = null, updatable: boolean = false): void {
  459. if (this._indexBuffer) {
  460. this._engine._releaseBuffer(this._indexBuffer);
  461. }
  462. this._disposeVertexArrayObjects();
  463. this._indices = indices;
  464. this._indexBufferIsUpdatable = updatable;
  465. if (this._meshes.length !== 0 && this._indices) {
  466. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  467. }
  468. if (totalVertices != undefined) { // including null and undefined
  469. this._totalVertices = totalVertices;
  470. }
  471. var meshes = this._meshes;
  472. var numOfMeshes = meshes.length;
  473. for (var index = 0; index < numOfMeshes; index++) {
  474. meshes[index]._createGlobalSubMesh(true);
  475. }
  476. this.notifyUpdate();
  477. }
  478. /**
  479. * Return the total number of indices
  480. * @returns the total number of indices
  481. */
  482. public getTotalIndices(): number {
  483. if (!this.isReady()) {
  484. return 0;
  485. }
  486. return this._indices.length;
  487. }
  488. /**
  489. * Gets the index buffer array
  490. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  491. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  492. * @returns the index buffer array
  493. */
  494. public getIndices(copyWhenShared?: boolean, forceCopy?: boolean): Nullable<IndicesArray> {
  495. if (!this.isReady()) {
  496. return null;
  497. }
  498. var orig = this._indices;
  499. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  500. return orig;
  501. } else {
  502. var len = orig.length;
  503. var copy = [];
  504. for (var i = 0; i < len; i++) {
  505. copy.push(orig[i]);
  506. }
  507. return copy;
  508. }
  509. }
  510. /**
  511. * Gets the index buffer
  512. * @return the index buffer
  513. */
  514. public getIndexBuffer(): Nullable<WebGLBuffer> {
  515. if (!this.isReady()) {
  516. return null;
  517. }
  518. return this._indexBuffer;
  519. }
  520. /** @hidden */
  521. public _releaseVertexArrayObject(effect: Nullable<Effect> = null) {
  522. if (!effect || !this._vertexArrayObjects) {
  523. return;
  524. }
  525. if (this._vertexArrayObjects[effect.key]) {
  526. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  527. delete this._vertexArrayObjects[effect.key];
  528. }
  529. }
  530. /**
  531. * Release the associated resources for a specific mesh
  532. * @param mesh defines the source mesh
  533. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  534. */
  535. public releaseForMesh(mesh: Mesh, shouldDispose?: boolean): void {
  536. var meshes = this._meshes;
  537. var index = meshes.indexOf(mesh);
  538. if (index === -1) {
  539. return;
  540. }
  541. meshes.splice(index, 1);
  542. mesh._geometry = null;
  543. if (meshes.length === 0 && shouldDispose) {
  544. this.dispose();
  545. }
  546. }
  547. /**
  548. * Apply current geometry to a given mesh
  549. * @param mesh defines the mesh to apply geometry to
  550. */
  551. public applyToMesh(mesh: Mesh): void {
  552. if (mesh._geometry === this) {
  553. return;
  554. }
  555. var previousGeometry = mesh._geometry;
  556. if (previousGeometry) {
  557. previousGeometry.releaseForMesh(mesh);
  558. }
  559. var meshes = this._meshes;
  560. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  561. mesh._geometry = this;
  562. this._scene.pushGeometry(this);
  563. meshes.push(mesh);
  564. if (this.isReady()) {
  565. this._applyToMesh(mesh);
  566. }
  567. else {
  568. mesh._boundingInfo = this._boundingInfo;
  569. }
  570. }
  571. private _updateExtend(data: Nullable<FloatArray> = null) {
  572. if (!data) {
  573. data = this.getVerticesData(VertexBuffer.PositionKind)!;
  574. }
  575. this._extend = Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  576. }
  577. private _applyToMesh(mesh: Mesh): void {
  578. var numOfMeshes = this._meshes.length;
  579. // vertexBuffers
  580. for (var kind in this._vertexBuffers) {
  581. if (numOfMeshes === 1) {
  582. this._vertexBuffers[kind].create();
  583. }
  584. var buffer = this._vertexBuffers[kind].getBuffer();
  585. if (buffer) {
  586. buffer.references = numOfMeshes;
  587. }
  588. if (kind === VertexBuffer.PositionKind) {
  589. if (!this._extend) {
  590. this._updateExtend();
  591. }
  592. mesh._boundingInfo = new BoundingInfo(this._extend.minimum, this._extend.maximum);
  593. mesh._createGlobalSubMesh(false);
  594. //bounding info was just created again, world matrix should be applied again.
  595. mesh._updateBoundingInfo();
  596. }
  597. }
  598. // indexBuffer
  599. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  600. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  601. }
  602. if (this._indexBuffer) {
  603. this._indexBuffer.references = numOfMeshes;
  604. }
  605. // morphTargets
  606. mesh._syncGeometryWithMorphTargetManager();
  607. // instances
  608. mesh.synchronizeInstances();
  609. }
  610. private notifyUpdate(kind?: string) {
  611. if (this.onGeometryUpdated) {
  612. this.onGeometryUpdated(this, kind);
  613. }
  614. for (var mesh of this._meshes) {
  615. mesh._markSubMeshesAsAttributesDirty();
  616. }
  617. }
  618. /**
  619. * Load the geometry if it was flagged as delay loaded
  620. * @param scene defines the hosting scene
  621. * @param onLoaded defines a callback called when the geometry is loaded
  622. */
  623. public load(scene: Scene, onLoaded?: () => void): void {
  624. if (this.delayLoadState === Engine.DELAYLOADSTATE_LOADING) {
  625. return;
  626. }
  627. if (this.isReady()) {
  628. if (onLoaded) {
  629. onLoaded();
  630. }
  631. return;
  632. }
  633. this.delayLoadState = Engine.DELAYLOADSTATE_LOADING;
  634. this._queueLoad(scene, onLoaded);
  635. }
  636. private _queueLoad(scene: Scene, onLoaded?: () => void): void {
  637. if (!this.delayLoadingFile) {
  638. return;
  639. }
  640. scene._addPendingData(this);
  641. scene._loadFile(this.delayLoadingFile, (data) => {
  642. if (!this._delayLoadingFunction) {
  643. return;
  644. }
  645. this._delayLoadingFunction(JSON.parse(data as string), this);
  646. this.delayLoadState = Engine.DELAYLOADSTATE_LOADED;
  647. this._delayInfo = [];
  648. scene._removePendingData(this);
  649. var meshes = this._meshes;
  650. var numOfMeshes = meshes.length;
  651. for (var index = 0; index < numOfMeshes; index++) {
  652. this._applyToMesh(meshes[index]);
  653. }
  654. if (onLoaded) {
  655. onLoaded();
  656. }
  657. }, undefined, true);
  658. }
  659. /**
  660. * Invert the geometry to move from a right handed system to a left handed one.
  661. */
  662. public toLeftHanded(): void {
  663. // Flip faces
  664. let tIndices = this.getIndices(false);
  665. if (tIndices != null && tIndices.length > 0) {
  666. for (let i = 0; i < tIndices.length; i += 3) {
  667. let tTemp = tIndices[i + 0];
  668. tIndices[i + 0] = tIndices[i + 2];
  669. tIndices[i + 2] = tTemp;
  670. }
  671. this.setIndices(tIndices);
  672. }
  673. // Negate position.z
  674. let tPositions = this.getVerticesData(VertexBuffer.PositionKind, false);
  675. if (tPositions != null && tPositions.length > 0) {
  676. for (let i = 0; i < tPositions.length; i += 3) {
  677. tPositions[i + 2] = -tPositions[i + 2];
  678. }
  679. this.setVerticesData(VertexBuffer.PositionKind, tPositions, false);
  680. }
  681. // Negate normal.z
  682. let tNormals = this.getVerticesData(VertexBuffer.NormalKind, false);
  683. if (tNormals != null && tNormals.length > 0) {
  684. for (let i = 0; i < tNormals.length; i += 3) {
  685. tNormals[i + 2] = -tNormals[i + 2];
  686. }
  687. this.setVerticesData(VertexBuffer.NormalKind, tNormals, false);
  688. }
  689. }
  690. // Cache
  691. /** @hidden */
  692. public _resetPointsArrayCache(): void {
  693. this._positions = null;
  694. }
  695. /** @hidden */
  696. public _generatePointsArray(): boolean {
  697. if (this._positions) {
  698. return true;
  699. }
  700. var data = this.getVerticesData(VertexBuffer.PositionKind);
  701. if (!data || data.length === 0) {
  702. return false;
  703. }
  704. this._positions = [];
  705. for (var index = 0; index < data.length; index += 3) {
  706. this._positions.push(Vector3.FromArray(data, index));
  707. }
  708. return true;
  709. }
  710. /**
  711. * Gets a value indicating if the geometry is disposed
  712. * @returns true if the geometry was disposed
  713. */
  714. public isDisposed(): boolean {
  715. return this._isDisposed;
  716. }
  717. private _disposeVertexArrayObjects(): void {
  718. if (this._vertexArrayObjects) {
  719. for (var kind in this._vertexArrayObjects) {
  720. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  721. }
  722. this._vertexArrayObjects = {};
  723. }
  724. }
  725. /**
  726. * Free all associated resources
  727. */
  728. public dispose(): void {
  729. var meshes = this._meshes;
  730. var numOfMeshes = meshes.length;
  731. var index: number;
  732. for (index = 0; index < numOfMeshes; index++) {
  733. this.releaseForMesh(meshes[index]);
  734. }
  735. this._meshes = [];
  736. this._disposeVertexArrayObjects();
  737. for (var kind in this._vertexBuffers) {
  738. this._vertexBuffers[kind].dispose();
  739. }
  740. this._vertexBuffers = {};
  741. this._totalVertices = 0;
  742. if (this._indexBuffer) {
  743. this._engine._releaseBuffer(this._indexBuffer);
  744. }
  745. this._indexBuffer = null;
  746. this._indices = [];
  747. this.delayLoadState = Engine.DELAYLOADSTATE_NONE;
  748. this.delayLoadingFile = null;
  749. this._delayLoadingFunction = null;
  750. this._delayInfo = [];
  751. this._boundingInfo = null;
  752. this._scene.removeGeometry(this);
  753. this._isDisposed = true;
  754. }
  755. /**
  756. * Clone the current geometry into a new geometry
  757. * @param id defines the unique ID of the new geometry
  758. * @returns a new geometry object
  759. */
  760. public copy(id: string): Geometry {
  761. var vertexData = new VertexData();
  762. vertexData.indices = [];
  763. var indices = this.getIndices();
  764. if (indices) {
  765. for (var index = 0; index < indices.length; index++) {
  766. (<number[]>vertexData.indices).push(indices[index]);
  767. }
  768. }
  769. var updatable = false;
  770. var stopChecking = false;
  771. var kind;
  772. for (kind in this._vertexBuffers) {
  773. // using slice() to make a copy of the array and not just reference it
  774. var data = this.getVerticesData(kind);
  775. if (data instanceof Float32Array) {
  776. vertexData.set(new Float32Array(<Float32Array>data), kind);
  777. } else {
  778. vertexData.set((<number[]>data).slice(0), kind);
  779. }
  780. if (!stopChecking) {
  781. let vb = this.getVertexBuffer(kind);
  782. if (vb) {
  783. updatable = vb.isUpdatable();
  784. stopChecking = !updatable;
  785. }
  786. }
  787. }
  788. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  789. geometry.delayLoadState = this.delayLoadState;
  790. geometry.delayLoadingFile = this.delayLoadingFile;
  791. geometry._delayLoadingFunction = this._delayLoadingFunction;
  792. for (kind in this._delayInfo) {
  793. geometry._delayInfo = geometry._delayInfo || [];
  794. geometry._delayInfo.push(kind);
  795. }
  796. // Bounding info
  797. geometry._boundingInfo = new BoundingInfo(this._extend.minimum, this._extend.maximum);
  798. return geometry;
  799. }
  800. /**
  801. * Serialize the current geometry info (and not the vertices data) into a JSON object
  802. * @return a JSON representation of the current geometry data (without the vertices data)
  803. */
  804. public serialize(): any {
  805. var serializationObject: any = {};
  806. serializationObject.id = this.id;
  807. serializationObject.updatable = this._updatable;
  808. if (Tags && Tags.HasTags(this)) {
  809. serializationObject.tags = Tags.GetTags(this);
  810. }
  811. return serializationObject;
  812. }
  813. private toNumberArray(origin: Nullable<Float32Array | IndicesArray>): number[] {
  814. if (Array.isArray(origin)) {
  815. return origin;
  816. } else {
  817. return Array.prototype.slice.call(origin);
  818. }
  819. }
  820. /**
  821. * Serialize all vertices data into a JSON oject
  822. * @returns a JSON representation of the current geometry data
  823. */
  824. public serializeVerticeData(): any {
  825. var serializationObject = this.serialize();
  826. if (this.isVerticesDataPresent(VertexBuffer.PositionKind)) {
  827. serializationObject.positions = this.toNumberArray(this.getVerticesData(VertexBuffer.PositionKind));
  828. if (this.isVertexBufferUpdatable(VertexBuffer.PositionKind)) {
  829. serializationObject.positions._updatable = true;
  830. }
  831. }
  832. if (this.isVerticesDataPresent(VertexBuffer.NormalKind)) {
  833. serializationObject.normals = this.toNumberArray(this.getVerticesData(VertexBuffer.NormalKind));
  834. if (this.isVertexBufferUpdatable(VertexBuffer.NormalKind)) {
  835. serializationObject.normals._updatable = true;
  836. }
  837. }
  838. if (this.isVerticesDataPresent(VertexBuffer.TangentKind)) {
  839. serializationObject.tangets = this.toNumberArray(this.getVerticesData(VertexBuffer.TangentKind));
  840. if (this.isVertexBufferUpdatable(VertexBuffer.TangentKind)) {
  841. serializationObject.tangets._updatable = true;
  842. }
  843. }
  844. if (this.isVerticesDataPresent(VertexBuffer.UVKind)) {
  845. serializationObject.uvs = this.toNumberArray(this.getVerticesData(VertexBuffer.UVKind));
  846. if (this.isVertexBufferUpdatable(VertexBuffer.UVKind)) {
  847. serializationObject.uvs._updatable = true;
  848. }
  849. }
  850. if (this.isVerticesDataPresent(VertexBuffer.UV2Kind)) {
  851. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(VertexBuffer.UV2Kind));
  852. if (this.isVertexBufferUpdatable(VertexBuffer.UV2Kind)) {
  853. serializationObject.uv2s._updatable = true;
  854. }
  855. }
  856. if (this.isVerticesDataPresent(VertexBuffer.UV3Kind)) {
  857. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(VertexBuffer.UV3Kind));
  858. if (this.isVertexBufferUpdatable(VertexBuffer.UV3Kind)) {
  859. serializationObject.uv3s._updatable = true;
  860. }
  861. }
  862. if (this.isVerticesDataPresent(VertexBuffer.UV4Kind)) {
  863. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(VertexBuffer.UV4Kind));
  864. if (this.isVertexBufferUpdatable(VertexBuffer.UV4Kind)) {
  865. serializationObject.uv4s._updatable = true;
  866. }
  867. }
  868. if (this.isVerticesDataPresent(VertexBuffer.UV5Kind)) {
  869. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(VertexBuffer.UV5Kind));
  870. if (this.isVertexBufferUpdatable(VertexBuffer.UV5Kind)) {
  871. serializationObject.uv5s._updatable = true;
  872. }
  873. }
  874. if (this.isVerticesDataPresent(VertexBuffer.UV6Kind)) {
  875. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(VertexBuffer.UV6Kind));
  876. if (this.isVertexBufferUpdatable(VertexBuffer.UV6Kind)) {
  877. serializationObject.uv6s._updatable = true;
  878. }
  879. }
  880. if (this.isVerticesDataPresent(VertexBuffer.ColorKind)) {
  881. serializationObject.colors = this.toNumberArray(this.getVerticesData(VertexBuffer.ColorKind));
  882. if (this.isVertexBufferUpdatable(VertexBuffer.ColorKind)) {
  883. serializationObject.colors._updatable = true;
  884. }
  885. }
  886. if (this.isVerticesDataPresent(VertexBuffer.MatricesIndicesKind)) {
  887. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(VertexBuffer.MatricesIndicesKind));
  888. serializationObject.matricesIndices._isExpanded = true;
  889. if (this.isVertexBufferUpdatable(VertexBuffer.MatricesIndicesKind)) {
  890. serializationObject.matricesIndices._updatable = true;
  891. }
  892. }
  893. if (this.isVerticesDataPresent(VertexBuffer.MatricesWeightsKind)) {
  894. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(VertexBuffer.MatricesWeightsKind));
  895. if (this.isVertexBufferUpdatable(VertexBuffer.MatricesWeightsKind)) {
  896. serializationObject.matricesWeights._updatable = true;
  897. }
  898. }
  899. serializationObject.indices = this.toNumberArray(this.getIndices());
  900. return serializationObject;
  901. }
  902. // Statics
  903. /**
  904. * Extracts a clone of a mesh geometry
  905. * @param mesh defines the source mesh
  906. * @param id defines the unique ID of the new geometry object
  907. * @returns the new geometry object
  908. */
  909. public static ExtractFromMesh(mesh: Mesh, id: string): Nullable<Geometry> {
  910. var geometry = mesh._geometry;
  911. if (!geometry) {
  912. return null;
  913. }
  914. return geometry.copy(id);
  915. }
  916. /**
  917. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  918. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  919. * Be aware Math.random() could cause collisions, but:
  920. * "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"
  921. * @returns a string containing a new GUID
  922. */
  923. public static RandomId(): string {
  924. return Tools.RandomId();
  925. }
  926. /** @hidden */
  927. public static _ImportGeometry(parsedGeometry: any, mesh: Mesh): void {
  928. var scene = mesh.getScene();
  929. // Geometry
  930. var geometryId = parsedGeometry.geometryId;
  931. if (geometryId) {
  932. var geometry = scene.getGeometryByID(geometryId);
  933. if (geometry) {
  934. geometry.applyToMesh(mesh);
  935. }
  936. } else if (parsedGeometry instanceof ArrayBuffer) {
  937. var binaryInfo = mesh._binaryInfo;
  938. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  939. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  940. mesh.setVerticesData(VertexBuffer.PositionKind, positionsData, false);
  941. }
  942. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  943. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  944. mesh.setVerticesData(VertexBuffer.NormalKind, normalsData, false);
  945. }
  946. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  947. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  948. mesh.setVerticesData(VertexBuffer.TangentKind, tangentsData, false);
  949. }
  950. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  951. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  952. mesh.setVerticesData(VertexBuffer.UVKind, uvsData, false);
  953. }
  954. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  955. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  956. mesh.setVerticesData(VertexBuffer.UV2Kind, uvs2Data, false);
  957. }
  958. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  959. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  960. mesh.setVerticesData(VertexBuffer.UV3Kind, uvs3Data, false);
  961. }
  962. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  963. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  964. mesh.setVerticesData(VertexBuffer.UV4Kind, uvs4Data, false);
  965. }
  966. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  967. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  968. mesh.setVerticesData(VertexBuffer.UV5Kind, uvs5Data, false);
  969. }
  970. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  971. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  972. mesh.setVerticesData(VertexBuffer.UV6Kind, uvs6Data, false);
  973. }
  974. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  975. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  976. mesh.setVerticesData(VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  977. }
  978. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  979. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  980. var floatIndices = [];
  981. for (var i = 0; i < matricesIndicesData.length; i++) {
  982. var index = matricesIndicesData[i];
  983. floatIndices.push(index & 0x000000FF);
  984. floatIndices.push((index & 0x0000FF00) >> 8);
  985. floatIndices.push((index & 0x00FF0000) >> 16);
  986. floatIndices.push(index >> 24);
  987. }
  988. mesh.setVerticesData(VertexBuffer.MatricesIndicesKind, floatIndices, false);
  989. }
  990. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  991. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  992. mesh.setVerticesData(VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  993. }
  994. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  995. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  996. mesh.setIndices(indicesData, null);
  997. }
  998. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  999. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  1000. mesh.subMeshes = [];
  1001. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  1002. var materialIndex = subMeshesData[(i * 5) + 0];
  1003. var verticesStart = subMeshesData[(i * 5) + 1];
  1004. var verticesCount = subMeshesData[(i * 5) + 2];
  1005. var indexStart = subMeshesData[(i * 5) + 3];
  1006. var indexCount = subMeshesData[(i * 5) + 4];
  1007. SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, <AbstractMesh>mesh);
  1008. }
  1009. }
  1010. } else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  1011. mesh.setVerticesData(VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  1012. mesh.setVerticesData(VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  1013. if (parsedGeometry.tangents) {
  1014. mesh.setVerticesData(VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  1015. }
  1016. if (parsedGeometry.uvs) {
  1017. mesh.setVerticesData(VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  1018. }
  1019. if (parsedGeometry.uvs2) {
  1020. mesh.setVerticesData(VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  1021. }
  1022. if (parsedGeometry.uvs3) {
  1023. mesh.setVerticesData(VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  1024. }
  1025. if (parsedGeometry.uvs4) {
  1026. mesh.setVerticesData(VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  1027. }
  1028. if (parsedGeometry.uvs5) {
  1029. mesh.setVerticesData(VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  1030. }
  1031. if (parsedGeometry.uvs6) {
  1032. mesh.setVerticesData(VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  1033. }
  1034. if (parsedGeometry.colors) {
  1035. mesh.setVerticesData(VertexBuffer.ColorKind, Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  1036. }
  1037. if (parsedGeometry.matricesIndices) {
  1038. if (!parsedGeometry.matricesIndices._isExpanded) {
  1039. var floatIndices = [];
  1040. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  1041. var matricesIndex = parsedGeometry.matricesIndices[i];
  1042. floatIndices.push(matricesIndex & 0x000000FF);
  1043. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  1044. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  1045. floatIndices.push(matricesIndex >> 24);
  1046. }
  1047. mesh.setVerticesData(VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  1048. } else {
  1049. delete parsedGeometry.matricesIndices._isExpanded;
  1050. mesh.setVerticesData(VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  1051. }
  1052. }
  1053. if (parsedGeometry.matricesIndicesExtra) {
  1054. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  1055. var floatIndices = [];
  1056. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  1057. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  1058. floatIndices.push(matricesIndex & 0x000000FF);
  1059. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  1060. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  1061. floatIndices.push(matricesIndex >> 24);
  1062. }
  1063. mesh.setVerticesData(VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  1064. } else {
  1065. delete parsedGeometry.matricesIndices._isExpanded;
  1066. mesh.setVerticesData(VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  1067. }
  1068. }
  1069. if (parsedGeometry.matricesWeights) {
  1070. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  1071. mesh.setVerticesData(VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  1072. }
  1073. if (parsedGeometry.matricesWeightsExtra) {
  1074. mesh.setVerticesData(VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  1075. }
  1076. mesh.setIndices(parsedGeometry.indices, null);
  1077. }
  1078. // SubMeshes
  1079. if (parsedGeometry.subMeshes) {
  1080. mesh.subMeshes = [];
  1081. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  1082. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  1083. SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, <AbstractMesh>mesh);
  1084. }
  1085. }
  1086. // Flat shading
  1087. if (mesh._shouldGenerateFlatShading) {
  1088. mesh.convertToFlatShadedMesh();
  1089. delete mesh._shouldGenerateFlatShading;
  1090. }
  1091. // Update
  1092. mesh.computeWorldMatrix(true);
  1093. scene.onMeshImportedObservable.notifyObservers(<AbstractMesh>mesh);
  1094. }
  1095. private static _CleanMatricesWeights(parsedGeometry: any, mesh: Mesh): void {
  1096. const epsilon: number = 1e-3;
  1097. if (!SceneLoader.CleanBoneMatrixWeights) {
  1098. return;
  1099. }
  1100. let noInfluenceBoneIndex = 0.0;
  1101. if (parsedGeometry.skeletonId > -1) {
  1102. let skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  1103. if (!skeleton) {
  1104. return;
  1105. }
  1106. noInfluenceBoneIndex = skeleton.bones.length;
  1107. } else {
  1108. return;
  1109. }
  1110. let matricesIndices = (<FloatArray>mesh.getVerticesData(VertexBuffer.MatricesIndicesKind));
  1111. let matricesIndicesExtra = (<FloatArray>mesh.getVerticesData(VertexBuffer.MatricesIndicesExtraKind));
  1112. let matricesWeights = parsedGeometry.matricesWeights;
  1113. let matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  1114. let influencers = parsedGeometry.numBoneInfluencer;
  1115. let size = matricesWeights.length;
  1116. for (var i = 0; i < size; i += 4) {
  1117. let weight = 0.0;
  1118. let firstZeroWeight = -1;
  1119. for (var j = 0; j < 4; j++) {
  1120. let w = matricesWeights[i + j];
  1121. weight += w;
  1122. if (w < epsilon && firstZeroWeight < 0) {
  1123. firstZeroWeight = j;
  1124. }
  1125. }
  1126. if (matricesWeightsExtra) {
  1127. for (var j = 0; j < 4; j++) {
  1128. let w = matricesWeightsExtra[i + j];
  1129. weight += w;
  1130. if (w < epsilon && firstZeroWeight < 0) {
  1131. firstZeroWeight = j + 4;
  1132. }
  1133. }
  1134. }
  1135. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  1136. firstZeroWeight = influencers - 1;
  1137. }
  1138. if (weight > epsilon) {
  1139. let mweight = 1.0 / weight;
  1140. for (var j = 0; j < 4; j++) {
  1141. matricesWeights[i + j] *= mweight;
  1142. }
  1143. if (matricesWeightsExtra) {
  1144. for (var j = 0; j < 4; j++) {
  1145. matricesWeightsExtra[i + j] *= mweight;
  1146. }
  1147. }
  1148. } else {
  1149. if (firstZeroWeight >= 4) {
  1150. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  1151. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  1152. } else {
  1153. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  1154. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  1155. }
  1156. }
  1157. }
  1158. mesh.setVerticesData(VertexBuffer.MatricesIndicesKind, matricesIndices);
  1159. if (parsedGeometry.matricesWeightsExtra) {
  1160. mesh.setVerticesData(VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  1161. }
  1162. }
  1163. /**
  1164. * Create a new geometry from persisted data (Using .babylon file format)
  1165. * @param parsedVertexData defines the persisted data
  1166. * @param scene defines the hosting scene
  1167. * @param rootUrl defines the root url to use to load assets (like delayed data)
  1168. * @returns the new geometry object
  1169. */
  1170. public static Parse(parsedVertexData: any, scene: Scene, rootUrl: string): Nullable<Geometry> {
  1171. if (scene.getGeometryByID(parsedVertexData.id)) {
  1172. return null; // null since geometry could be something else than a box...
  1173. }
  1174. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  1175. if (Tags) {
  1176. Tags.AddTagsTo(geometry, parsedVertexData.tags);
  1177. }
  1178. if (parsedVertexData.delayLoadingFile) {
  1179. geometry.delayLoadState = Engine.DELAYLOADSTATE_NOTLOADED;
  1180. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  1181. geometry._boundingInfo = new BoundingInfo(Vector3.FromArray(parsedVertexData.boundingBoxMinimum), Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  1182. geometry._delayInfo = [];
  1183. if (parsedVertexData.hasUVs) {
  1184. geometry._delayInfo.push(VertexBuffer.UVKind);
  1185. }
  1186. if (parsedVertexData.hasUVs2) {
  1187. geometry._delayInfo.push(VertexBuffer.UV2Kind);
  1188. }
  1189. if (parsedVertexData.hasUVs3) {
  1190. geometry._delayInfo.push(VertexBuffer.UV3Kind);
  1191. }
  1192. if (parsedVertexData.hasUVs4) {
  1193. geometry._delayInfo.push(VertexBuffer.UV4Kind);
  1194. }
  1195. if (parsedVertexData.hasUVs5) {
  1196. geometry._delayInfo.push(VertexBuffer.UV5Kind);
  1197. }
  1198. if (parsedVertexData.hasUVs6) {
  1199. geometry._delayInfo.push(VertexBuffer.UV6Kind);
  1200. }
  1201. if (parsedVertexData.hasColors) {
  1202. geometry._delayInfo.push(VertexBuffer.ColorKind);
  1203. }
  1204. if (parsedVertexData.hasMatricesIndices) {
  1205. geometry._delayInfo.push(VertexBuffer.MatricesIndicesKind);
  1206. }
  1207. if (parsedVertexData.hasMatricesWeights) {
  1208. geometry._delayInfo.push(VertexBuffer.MatricesWeightsKind);
  1209. }
  1210. geometry._delayLoadingFunction = VertexData.ImportVertexData;
  1211. } else {
  1212. VertexData.ImportVertexData(parsedVertexData, geometry);
  1213. }
  1214. scene.pushGeometry(geometry, true);
  1215. return geometry;
  1216. }
  1217. }
  1218. // Primitives
  1219. /// Abstract class
  1220. /**
  1221. * Abstract class used to provide common services for all typed geometries
  1222. * @hidden
  1223. */
  1224. export class _PrimitiveGeometry extends Geometry {
  1225. private _beingRegenerated: boolean;
  1226. /**
  1227. * Creates a new typed geometry
  1228. * @param id defines the unique ID of the geometry
  1229. * @param scene defines the hosting scene
  1230. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  1231. * @param mesh defines the hosting mesh (can be null)
  1232. */
  1233. constructor(id: string, scene: Scene, private _canBeRegenerated: boolean = false, mesh: Nullable<Mesh> = null) {
  1234. super(id, scene, undefined, false, mesh); // updatable = false to be sure not to update vertices
  1235. this._beingRegenerated = true;
  1236. this.regenerate();
  1237. this._beingRegenerated = false;
  1238. }
  1239. /**
  1240. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  1241. * @returns true if the geometry can be regenerated
  1242. */
  1243. public canBeRegenerated(): boolean {
  1244. return this._canBeRegenerated;
  1245. }
  1246. /**
  1247. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  1248. */
  1249. public regenerate(): void {
  1250. if (!this._canBeRegenerated) {
  1251. return;
  1252. }
  1253. this._beingRegenerated = true;
  1254. this.setAllVerticesData(this._regenerateVertexData(), false);
  1255. this._beingRegenerated = false;
  1256. }
  1257. /**
  1258. * Clone the geometry
  1259. * @param id defines the unique ID of the new geometry
  1260. * @returns the new geometry
  1261. */
  1262. public asNewGeometry(id: string): Geometry {
  1263. return super.copy(id);
  1264. }
  1265. // overrides
  1266. public setAllVerticesData(vertexData: VertexData, updatable?: boolean): void {
  1267. if (!this._beingRegenerated) {
  1268. return;
  1269. }
  1270. super.setAllVerticesData(vertexData, false);
  1271. }
  1272. public setVerticesData(kind: string, data: FloatArray, updatable?: boolean): void {
  1273. if (!this._beingRegenerated) {
  1274. return;
  1275. }
  1276. super.setVerticesData(kind, data, false);
  1277. }
  1278. // to override
  1279. /** @hidden */
  1280. public _regenerateVertexData(): VertexData {
  1281. throw new Error("Abstract method");
  1282. }
  1283. public copy(id: string): Geometry {
  1284. throw new Error("Must be overriden in sub-classes.");
  1285. }
  1286. public serialize(): any {
  1287. var serializationObject = super.serialize();
  1288. serializationObject.canBeRegenerated = this.canBeRegenerated();
  1289. return serializationObject;
  1290. }
  1291. }
  1292. /**
  1293. * Creates a ribbon geometry
  1294. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  1295. */
  1296. export class RibbonGeometry extends _PrimitiveGeometry {
  1297. /**
  1298. * Creates a ribbon geometry
  1299. * @param id defines the unique ID of the geometry
  1300. * @param scene defines the hosting scene
  1301. * @param pathArray defines the array of paths to use
  1302. * @param closeArray defines if the last path and the first path must be joined
  1303. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  1304. * @param offset defines the offset between points
  1305. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  1306. * @param mesh defines the hosting mesh (can be null)
  1307. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  1308. */
  1309. constructor(
  1310. id: string, scene: Scene,
  1311. /**
  1312. * Defines the array of paths to use
  1313. */
  1314. public pathArray: Vector3[][],
  1315. /**
  1316. * Defines if the last and first points of each path in your pathArray must be joined
  1317. */
  1318. public closeArray: boolean,
  1319. /**
  1320. * Defines if the last and first points of each path in your pathArray must be joined
  1321. */
  1322. public closePath: boolean,
  1323. /**
  1324. * Defines the offset between points
  1325. */
  1326. public offset: number,
  1327. canBeRegenerated?: boolean,
  1328. mesh?: Mesh,
  1329. /**
  1330. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  1331. */
  1332. public side: number = Mesh.DEFAULTSIDE) {
  1333. super(id, scene, canBeRegenerated, mesh);
  1334. }
  1335. /** @hidden */
  1336. public _regenerateVertexData(): VertexData {
  1337. return VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  1338. }
  1339. public copy(id: string): Geometry {
  1340. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  1341. }
  1342. }
  1343. /**
  1344. * Creates a box geometry
  1345. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  1346. */
  1347. export class BoxGeometry extends _PrimitiveGeometry {
  1348. /**
  1349. * Creates a box geometry
  1350. * @param id defines the unique ID of the geometry
  1351. * @param scene defines the hosting scene
  1352. * @param size defines the zise of the box (width, height and depth are the same)
  1353. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  1354. * @param mesh defines the hosting mesh (can be null)
  1355. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  1356. */
  1357. constructor(
  1358. id: string, scene: Scene,
  1359. /**
  1360. * Defines the zise of the box (width, height and depth are the same)
  1361. */
  1362. public size: number,
  1363. canBeRegenerated?: boolean,
  1364. mesh: Nullable<Mesh> = null,
  1365. /**
  1366. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  1367. */
  1368. public side: number = Mesh.DEFAULTSIDE) {
  1369. super(id, scene, canBeRegenerated, mesh);
  1370. }
  1371. /** @hidden */
  1372. public _regenerateVertexData(): VertexData {
  1373. return VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  1374. }
  1375. public copy(id: string): Geometry {
  1376. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  1377. }
  1378. public serialize(): any {
  1379. var serializationObject = super.serialize();
  1380. serializationObject.size = this.size;
  1381. return serializationObject;
  1382. }
  1383. public static Parse(parsedBox: any, scene: Scene): Nullable<BoxGeometry> {
  1384. if (scene.getGeometryByID(parsedBox.id)) {
  1385. return null; // null since geometry could be something else than a box...
  1386. }
  1387. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  1388. if (Tags) {
  1389. Tags.AddTagsTo(box, parsedBox.tags);
  1390. }
  1391. scene.pushGeometry(box, true);
  1392. return box;
  1393. }
  1394. }
  1395. /**
  1396. * Creates a sphere geometry
  1397. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  1398. */
  1399. export class SphereGeometry extends _PrimitiveGeometry {
  1400. /**
  1401. * Create a new sphere geometry
  1402. * @param id defines the unique ID of the geometry
  1403. * @param scene defines the hosting scene
  1404. * @param segments defines the number of segments to use to create the sphere
  1405. * @param diameter defines the diameter of the sphere
  1406. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  1407. * @param mesh defines the hosting mesh (can be null)
  1408. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  1409. */
  1410. constructor(
  1411. id: string, scene: Scene,
  1412. /**
  1413. * Defines the number of segments to use to create the sphere
  1414. */
  1415. public segments: number,
  1416. /**
  1417. * Defines the diameter of the sphere
  1418. */
  1419. public diameter: number,
  1420. canBeRegenerated?: boolean,
  1421. mesh: Nullable<Mesh> = null,
  1422. /**
  1423. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  1424. */
  1425. public side: number = Mesh.DEFAULTSIDE) {
  1426. super(id, scene, canBeRegenerated, mesh);
  1427. }
  1428. /** @hidden */
  1429. public _regenerateVertexData(): VertexData {
  1430. return VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  1431. }
  1432. public copy(id: string): Geometry {
  1433. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  1434. }
  1435. public serialize(): any {
  1436. var serializationObject = super.serialize();
  1437. serializationObject.segments = this.segments;
  1438. serializationObject.diameter = this.diameter;
  1439. return serializationObject;
  1440. }
  1441. public static Parse(parsedSphere: any, scene: Scene): Nullable<SphereGeometry> {
  1442. if (scene.getGeometryByID(parsedSphere.id)) {
  1443. return null; // null since geometry could be something else than a sphere...
  1444. }
  1445. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  1446. if (Tags) {
  1447. Tags.AddTagsTo(sphere, parsedSphere.tags);
  1448. }
  1449. scene.pushGeometry(sphere, true);
  1450. return sphere;
  1451. }
  1452. }
  1453. /**
  1454. * Creates a disc geometry
  1455. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  1456. */
  1457. export class DiscGeometry extends _PrimitiveGeometry {
  1458. /**
  1459. * Creates a new disc geometry
  1460. * @param id defines the unique ID of the geometry
  1461. * @param scene defines the hosting scene
  1462. * @param radius defines the radius of the disc
  1463. * @param tessellation defines the tesselation factor to apply to the disc
  1464. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  1465. * @param mesh defines the hosting mesh (can be null)
  1466. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  1467. */
  1468. constructor(
  1469. id: string, scene: Scene,
  1470. /**
  1471. * Defines the radius of the disc
  1472. */
  1473. public radius: number,
  1474. /**
  1475. * Defines the tesselation factor to apply to the disc
  1476. */
  1477. public tessellation: number,
  1478. canBeRegenerated?: boolean,
  1479. mesh: Nullable<Mesh> = null,
  1480. /**
  1481. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  1482. */
  1483. public side: number = Mesh.DEFAULTSIDE) {
  1484. super(id, scene, canBeRegenerated, mesh);
  1485. }
  1486. /** @hidden */
  1487. public _regenerateVertexData(): VertexData {
  1488. return VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  1489. }
  1490. public copy(id: string): Geometry {
  1491. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  1492. }
  1493. }
  1494. /**
  1495. * Creates a new cylinder geometry
  1496. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  1497. */
  1498. export class CylinderGeometry extends _PrimitiveGeometry {
  1499. /**
  1500. * Creates a new cylinder geometry
  1501. * @param id defines the unique ID of the geometry
  1502. * @param scene defines the hosting scene
  1503. * @param height defines the height of the cylinder
  1504. * @param diameterTop defines the diameter of the cylinder's top cap
  1505. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  1506. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  1507. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  1508. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  1509. * @param mesh defines the hosting mesh (can be null)
  1510. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  1511. */
  1512. constructor(
  1513. id: string, scene: Scene,
  1514. /**
  1515. * Defines the height of the cylinder
  1516. */
  1517. public height: number,
  1518. /**
  1519. * Defines the diameter of the cylinder's top cap
  1520. */
  1521. public diameterTop: number,
  1522. /**
  1523. * Defines the diameter of the cylinder's bottom cap
  1524. */
  1525. public diameterBottom: number,
  1526. /**
  1527. * Defines the tessellation factor to apply to the cylinder
  1528. */
  1529. public tessellation: number,
  1530. /**
  1531. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  1532. */
  1533. public subdivisions: number = 1,
  1534. canBeRegenerated?: boolean, mesh:
  1535. Nullable<Mesh> = null,
  1536. /**
  1537. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  1538. */
  1539. public side: number = Mesh.DEFAULTSIDE) {
  1540. super(id, scene, canBeRegenerated, mesh);
  1541. }
  1542. /** @hidden */
  1543. public _regenerateVertexData(): VertexData {
  1544. return VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  1545. }
  1546. public copy(id: string): Geometry {
  1547. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  1548. }
  1549. public serialize(): any {
  1550. var serializationObject = super.serialize();
  1551. serializationObject.height = this.height;
  1552. serializationObject.diameterTop = this.diameterTop;
  1553. serializationObject.diameterBottom = this.diameterBottom;
  1554. serializationObject.tessellation = this.tessellation;
  1555. return serializationObject;
  1556. }
  1557. public static Parse(parsedCylinder: any, scene: Scene): Nullable<CylinderGeometry> {
  1558. if (scene.getGeometryByID(parsedCylinder.id)) {
  1559. return null; // null since geometry could be something else than a cylinder...
  1560. }
  1561. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  1562. if (Tags) {
  1563. Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  1564. }
  1565. scene.pushGeometry(cylinder, true);
  1566. return cylinder;
  1567. }
  1568. }
  1569. /**
  1570. * Creates a new torus geometry
  1571. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  1572. */
  1573. export class TorusGeometry extends _PrimitiveGeometry {
  1574. /**
  1575. * Creates a new torus geometry
  1576. * @param id defines the unique ID of the geometry
  1577. * @param scene defines the hosting scene
  1578. * @param diameter defines the diameter of the torus
  1579. * @param thickness defines the thickness of the torus (ie. internal diameter)
  1580. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  1581. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  1582. * @param mesh defines the hosting mesh (can be null)
  1583. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  1584. */
  1585. constructor(
  1586. id: string, scene: Scene,
  1587. /**
  1588. * Defines the diameter of the torus
  1589. */
  1590. public diameter: number,
  1591. /**
  1592. * Defines the thickness of the torus (ie. internal diameter)
  1593. */
  1594. public thickness: number,
  1595. /**
  1596. * Defines the tesselation factor to apply to the torus
  1597. */
  1598. public tessellation: number,
  1599. canBeRegenerated?: boolean,
  1600. mesh: Nullable<Mesh> = null,
  1601. /**
  1602. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  1603. */
  1604. public side: number = Mesh.DEFAULTSIDE) {
  1605. super(id, scene, canBeRegenerated, mesh);
  1606. }
  1607. /** @hidden */
  1608. public _regenerateVertexData(): VertexData {
  1609. return VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  1610. }
  1611. public copy(id: string): Geometry {
  1612. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  1613. }
  1614. public serialize(): any {
  1615. var serializationObject = super.serialize();
  1616. serializationObject.diameter = this.diameter;
  1617. serializationObject.thickness = this.thickness;
  1618. serializationObject.tessellation = this.tessellation;
  1619. return serializationObject;
  1620. }
  1621. public static Parse(parsedTorus: any, scene: Scene): Nullable<TorusGeometry> {
  1622. if (scene.getGeometryByID(parsedTorus.id)) {
  1623. return null; // null since geometry could be something else than a torus...
  1624. }
  1625. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  1626. if (Tags) {
  1627. Tags.AddTagsTo(torus, parsedTorus.tags);
  1628. }
  1629. scene.pushGeometry(torus, true);
  1630. return torus;
  1631. }
  1632. }
  1633. /**
  1634. * Creates a new ground geometry
  1635. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  1636. */
  1637. export class GroundGeometry extends _PrimitiveGeometry {
  1638. /**
  1639. * Creates a new ground geometry
  1640. * @param id defines the unique ID of the geometry
  1641. * @param scene defines the hosting scene
  1642. * @param width defines the width of the ground
  1643. * @param height defines the height of the ground
  1644. * @param subdivisions defines the subdivisions to apply to the ground
  1645. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  1646. * @param mesh defines the hosting mesh (can be null)
  1647. */
  1648. constructor(
  1649. id: string, scene: Scene,
  1650. /**
  1651. * Defines the width of the ground
  1652. */
  1653. public width: number,
  1654. /**
  1655. * Defines the height of the ground
  1656. */
  1657. public height: number,
  1658. /**
  1659. * Defines the subdivisions to apply to the ground
  1660. */
  1661. public subdivisions: number,
  1662. canBeRegenerated?: boolean,
  1663. mesh: Nullable<Mesh> = null) {
  1664. super(id, scene, canBeRegenerated, mesh);
  1665. }
  1666. /** @hidden */
  1667. public _regenerateVertexData(): VertexData {
  1668. return VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  1669. }
  1670. public copy(id: string): Geometry {
  1671. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  1672. }
  1673. public serialize(): any {
  1674. var serializationObject = super.serialize();
  1675. serializationObject.width = this.width;
  1676. serializationObject.height = this.height;
  1677. serializationObject.subdivisions = this.subdivisions;
  1678. return serializationObject;
  1679. }
  1680. public static Parse(parsedGround: any, scene: Scene): Nullable<GroundGeometry> {
  1681. if (scene.getGeometryByID(parsedGround.id)) {
  1682. return null; // null since geometry could be something else than a ground...
  1683. }
  1684. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  1685. if (Tags) {
  1686. Tags.AddTagsTo(ground, parsedGround.tags);
  1687. }
  1688. scene.pushGeometry(ground, true);
  1689. return ground;
  1690. }
  1691. }
  1692. /**
  1693. * Creates a tiled ground geometry
  1694. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  1695. */
  1696. export class TiledGroundGeometry extends _PrimitiveGeometry {
  1697. /**
  1698. * Creates a tiled ground geometry
  1699. * @param id defines the unique ID of the geometry
  1700. * @param scene defines the hosting scene
  1701. * @param xmin defines the minimum value on X axis
  1702. * @param zmin defines the minimum value on Z axis
  1703. * @param xmax defines the maximum value on X axis
  1704. * @param zmax defines the maximum value on Z axis
  1705. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  1706. * @param precision defines the precision to use when computing the tiles
  1707. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  1708. * @param mesh defines the hosting mesh (can be null)
  1709. */
  1710. constructor(
  1711. id: string, scene: Scene,
  1712. /**
  1713. * Defines the minimum value on X axis
  1714. */
  1715. public xmin: number,
  1716. /**
  1717. * Defines the minimum value on Z axis
  1718. */
  1719. public zmin: number,
  1720. /**
  1721. * Defines the maximum value on X axis
  1722. */
  1723. public xmax: number,
  1724. /**
  1725. * Defines the maximum value on Z axis
  1726. */
  1727. public zmax: number,
  1728. /**
  1729. * Defines the subdivisions to apply to the ground
  1730. */
  1731. public subdivisions: { w: number; h: number; },
  1732. /**
  1733. * Defines the precision to use when computing the tiles
  1734. */
  1735. public precision: { w: number; h: number; },
  1736. canBeRegenerated?: boolean,
  1737. mesh: Nullable<Mesh> = null) {
  1738. super(id, scene, canBeRegenerated, mesh);
  1739. }
  1740. /** @hidden */
  1741. public _regenerateVertexData(): VertexData {
  1742. return VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  1743. }
  1744. public copy(id: string): Geometry {
  1745. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  1746. }
  1747. }
  1748. /**
  1749. * Creates a plane geometry
  1750. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  1751. */
  1752. export class PlaneGeometry extends _PrimitiveGeometry {
  1753. /**
  1754. * Creates a plane geometry
  1755. * @param id defines the unique ID of the geometry
  1756. * @param scene defines the hosting scene
  1757. * @param size defines the size of the plane (width === height)
  1758. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  1759. * @param mesh defines the hosting mesh (can be null)
  1760. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  1761. */
  1762. constructor(
  1763. id: string, scene: Scene,
  1764. /**
  1765. * Defines the size of the plane (width === height)
  1766. */
  1767. public size: number,
  1768. canBeRegenerated?: boolean,
  1769. mesh: Nullable<Mesh> = null,
  1770. /**
  1771. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  1772. */
  1773. public side: number = Mesh.DEFAULTSIDE) {
  1774. super(id, scene, canBeRegenerated, mesh);
  1775. }
  1776. /** @hidden */
  1777. public _regenerateVertexData(): VertexData {
  1778. return VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  1779. }
  1780. public copy(id: string): Geometry {
  1781. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  1782. }
  1783. public serialize(): any {
  1784. var serializationObject = super.serialize();
  1785. serializationObject.size = this.size;
  1786. return serializationObject;
  1787. }
  1788. public static Parse(parsedPlane: any, scene: Scene): Nullable<PlaneGeometry> {
  1789. if (scene.getGeometryByID(parsedPlane.id)) {
  1790. return null; // null since geometry could be something else than a ground...
  1791. }
  1792. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  1793. if (Tags) {
  1794. Tags.AddTagsTo(plane, parsedPlane.tags);
  1795. }
  1796. scene.pushGeometry(plane, true);
  1797. return plane;
  1798. }
  1799. }
  1800. /**
  1801. * Creates a torus knot geometry
  1802. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  1803. */
  1804. export class TorusKnotGeometry extends _PrimitiveGeometry {
  1805. /**
  1806. * Creates a torus knot geometry
  1807. * @param id defines the unique ID of the geometry
  1808. * @param scene defines the hosting scene
  1809. * @param radius defines the radius of the torus knot
  1810. * @param tube defines the thickness of the torus knot tube
  1811. * @param radialSegments defines the number of radial segments
  1812. * @param tubularSegments defines the number of tubular segments
  1813. * @param p defines the first number of windings
  1814. * @param q defines the second number of windings
  1815. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  1816. * @param mesh defines the hosting mesh (can be null)
  1817. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  1818. */
  1819. constructor(
  1820. id: string, scene: Scene,
  1821. /**
  1822. * Defines the radius of the torus knot
  1823. */
  1824. public radius: number,
  1825. /**
  1826. * Defines the thickness of the torus knot tube
  1827. */
  1828. public tube: number,
  1829. /**
  1830. * Defines the number of radial segments
  1831. */
  1832. public radialSegments: number,
  1833. /**
  1834. * Defines the number of tubular segments
  1835. */
  1836. public tubularSegments: number,
  1837. /**
  1838. * Defines the first number of windings
  1839. */
  1840. public p: number,
  1841. /**
  1842. * Defines the second number of windings
  1843. */
  1844. public q: number,
  1845. canBeRegenerated?: boolean,
  1846. mesh: Nullable<Mesh> = null,
  1847. /**
  1848. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  1849. */
  1850. public side: number = Mesh.DEFAULTSIDE) {
  1851. super(id, scene, canBeRegenerated, mesh);
  1852. }
  1853. /** @hidden */
  1854. public _regenerateVertexData(): VertexData {
  1855. return VertexData.CreateTorusKnot({ radius: this.radius, tube: this.tube, radialSegments: this.radialSegments, tubularSegments: this.tubularSegments, p: this.p, q: this.q, sideOrientation: this.side });
  1856. }
  1857. public copy(id: string): Geometry {
  1858. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  1859. }
  1860. public serialize(): any {
  1861. var serializationObject = super.serialize();
  1862. serializationObject.radius = this.radius;
  1863. serializationObject.tube = this.tube;
  1864. serializationObject.radialSegments = this.radialSegments;
  1865. serializationObject.tubularSegments = this.tubularSegments;
  1866. serializationObject.p = this.p;
  1867. serializationObject.q = this.q;
  1868. return serializationObject;
  1869. }
  1870. public static Parse(parsedTorusKnot: any, scene: Scene): Nullable<TorusKnotGeometry> {
  1871. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  1872. return null; // null since geometry could be something else than a ground...
  1873. }
  1874. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  1875. if (Tags) {
  1876. Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  1877. }
  1878. scene.pushGeometry(torusKnot, true);
  1879. return torusKnot;
  1880. }
  1881. }
  1882. //}
  1883. }