geometry.ts 90 KB

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