babylon.mesh.vertexData.ts 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131
  1. module BABYLON {
  2. export interface IGetSetVerticesData {
  3. isVerticesDataPresent(kind: string): boolean;
  4. getVerticesData(kind: string): number[];
  5. getIndices(): number[];
  6. setVerticesData(kind: string, data: number[], updatable?: boolean): void;
  7. updateVerticesData(kind: string, data: number[], updateExtends?: boolean, makeItUnique?: boolean): void;
  8. setIndices(indices: number[]): void;
  9. }
  10. export class VertexData {
  11. public positions: number[];
  12. public normals: number[];
  13. public uvs: number[];
  14. public uv2s: number[];
  15. public colors: number[];
  16. public matricesIndices: number[];
  17. public matricesWeights: number[];
  18. public indices: number[];
  19. public set(data: number[], kind: string) {
  20. switch (kind) {
  21. case BABYLON.VertexBuffer.PositionKind:
  22. this.positions = data;
  23. break;
  24. case BABYLON.VertexBuffer.NormalKind:
  25. this.normals = data;
  26. break;
  27. case BABYLON.VertexBuffer.UVKind:
  28. this.uvs = data;
  29. break;
  30. case BABYLON.VertexBuffer.UV2Kind:
  31. this.uv2s = data;
  32. break;
  33. case BABYLON.VertexBuffer.ColorKind:
  34. this.colors = data;
  35. break;
  36. case BABYLON.VertexBuffer.MatricesIndicesKind:
  37. this.matricesIndices = data;
  38. break;
  39. case BABYLON.VertexBuffer.MatricesWeightsKind:
  40. this.matricesWeights = data;
  41. break;
  42. }
  43. }
  44. public applyToMesh(mesh: Mesh, updatable?: boolean): void {
  45. this._applyTo(mesh, updatable);
  46. }
  47. public applyToGeometry(geometry: Geometry, updatable?: boolean): void {
  48. this._applyTo(geometry, updatable);
  49. }
  50. public updateMesh(mesh: Mesh, updateExtends?: boolean, makeItUnique?: boolean): void {
  51. this._update(mesh);
  52. }
  53. public updateGeometry(geometry: Geometry, updateExtends?: boolean, makeItUnique?: boolean): void {
  54. this._update(geometry);
  55. }
  56. private _applyTo(meshOrGeometry: IGetSetVerticesData, updatable?: boolean) {
  57. if (this.positions) {
  58. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  59. }
  60. if (this.normals) {
  61. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  62. }
  63. if (this.uvs) {
  64. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  65. }
  66. if (this.uv2s) {
  67. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  68. }
  69. if (this.colors) {
  70. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  71. }
  72. if (this.matricesIndices) {
  73. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  74. }
  75. if (this.matricesWeights) {
  76. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  77. }
  78. if (this.indices) {
  79. meshOrGeometry.setIndices(this.indices);
  80. }
  81. }
  82. private _update(meshOrGeometry: IGetSetVerticesData, updateExtends?: boolean, makeItUnique?: boolean) {
  83. if (this.positions) {
  84. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  85. }
  86. if (this.normals) {
  87. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  88. }
  89. if (this.uvs) {
  90. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  91. }
  92. if (this.uv2s) {
  93. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  94. }
  95. if (this.colors) {
  96. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  97. }
  98. if (this.matricesIndices) {
  99. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  100. }
  101. if (this.matricesWeights) {
  102. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  103. }
  104. if (this.indices) {
  105. meshOrGeometry.setIndices(this.indices);
  106. }
  107. }
  108. public transform(matrix: Matrix): void {
  109. var transformed = BABYLON.Vector3.Zero();
  110. if (this.positions) {
  111. var position = BABYLON.Vector3.Zero();
  112. for (var index = 0; index < this.positions.length; index += 3) {
  113. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  114. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  115. this.positions[index] = transformed.x;
  116. this.positions[index + 1] = transformed.y;
  117. this.positions[index + 2] = transformed.z;
  118. }
  119. }
  120. if (this.normals) {
  121. var normal = BABYLON.Vector3.Zero();
  122. for (index = 0; index < this.normals.length; index += 3) {
  123. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  124. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  125. this.normals[index] = transformed.x;
  126. this.normals[index + 1] = transformed.y;
  127. this.normals[index + 2] = transformed.z;
  128. }
  129. }
  130. }
  131. public merge(other: VertexData): void {
  132. if (other.indices) {
  133. if (!this.indices) {
  134. this.indices = [];
  135. }
  136. var offset = this.positions ? this.positions.length / 3 : 0;
  137. for (var index = 0; index < other.indices.length; index++) {
  138. this.indices.push(other.indices[index] + offset);
  139. }
  140. }
  141. if (other.positions) {
  142. if (!this.positions) {
  143. this.positions = [];
  144. }
  145. for (index = 0; index < other.positions.length; index++) {
  146. this.positions.push(other.positions[index]);
  147. }
  148. }
  149. if (other.normals) {
  150. if (!this.normals) {
  151. this.normals = [];
  152. }
  153. for (index = 0; index < other.normals.length; index++) {
  154. this.normals.push(other.normals[index]);
  155. }
  156. }
  157. if (other.uvs) {
  158. if (!this.uvs) {
  159. this.uvs = [];
  160. }
  161. for (index = 0; index < other.uvs.length; index++) {
  162. this.uvs.push(other.uvs[index]);
  163. }
  164. }
  165. if (other.uv2s) {
  166. if (!this.uv2s) {
  167. this.uv2s = [];
  168. }
  169. for (index = 0; index < other.uv2s.length; index++) {
  170. this.uv2s.push(other.uv2s[index]);
  171. }
  172. }
  173. if (other.matricesIndices) {
  174. if (!this.matricesIndices) {
  175. this.matricesIndices = [];
  176. }
  177. for (index = 0; index < other.matricesIndices.length; index++) {
  178. this.matricesIndices.push(other.matricesIndices[index]);
  179. }
  180. }
  181. if (other.matricesWeights) {
  182. if (!this.matricesWeights) {
  183. this.matricesWeights = [];
  184. }
  185. for (index = 0; index < other.matricesWeights.length; index++) {
  186. this.matricesWeights.push(other.matricesWeights[index]);
  187. }
  188. }
  189. if (other.colors) {
  190. if (!this.colors) {
  191. this.colors = [];
  192. }
  193. for (index = 0; index < other.colors.length; index++) {
  194. this.colors.push(other.colors[index]);
  195. }
  196. }
  197. }
  198. // Statics
  199. public static ExtractFromMesh(mesh: Mesh): VertexData {
  200. return VertexData._ExtractFrom(mesh);
  201. }
  202. public static ExtractFromGeometry(geometry: Geometry): VertexData {
  203. return VertexData._ExtractFrom(geometry);
  204. }
  205. private static _ExtractFrom(meshOrGeometry: IGetSetVerticesData): VertexData {
  206. var result = new BABYLON.VertexData();
  207. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  208. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  209. }
  210. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  211. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  212. }
  213. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  214. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  215. }
  216. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  217. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  218. }
  219. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  220. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  221. }
  222. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  223. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  224. }
  225. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  226. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  227. }
  228. result.indices = meshOrGeometry.getIndices();
  229. return result;
  230. }
  231. public static CreateRibbon(pathArray: Vector3[][], closeArray: boolean, closePath: boolean, offset: number): VertexData {
  232. closeArray = closeArray || false;
  233. closePath = closePath || false;
  234. var defaultOffset = Math.floor(pathArray[0].length / 2);
  235. offset = offset || defaultOffset;
  236. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  237. var positions = [];
  238. var indices = [];
  239. var normals = [];
  240. var uvs = [];
  241. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  242. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  243. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  244. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  245. var minlg; // minimal length among all paths from pathArray
  246. var lg = []; // array of path lengths : nb of vertex per path
  247. var idx = []; // array of path indexes : index of each path (first vertex) in positions array
  248. // if single path in pathArray
  249. if ( pathArray.length < 2) {
  250. var ar1 = [];
  251. var ar2 = [];
  252. for (var i = 0; i < pathArray[0].length - offset; i++) {
  253. ar1.push(pathArray[0][i]);
  254. ar2.push(pathArray[0][i+offset]);
  255. }
  256. pathArray = [ar1, ar2];
  257. }
  258. // positions and horizontal distances (u)
  259. var idc = 0;
  260. minlg = pathArray[0].length;
  261. for(var p = 0; p < pathArray.length; p++) {
  262. uTotalDistance[p] = 0;
  263. us[p] = [0];
  264. var path = pathArray[p];
  265. var l = path.length;
  266. minlg = (minlg < l) ? minlg : l;
  267. lg[p] = l;
  268. idx[p] = idc;
  269. var j = 0;
  270. while (j < l) {
  271. positions.push(path[j].x, path[j].y, path[j].z);
  272. if (j > 0) {
  273. var vectlg = path[j].subtract(path[j-1]).length();
  274. var dist = vectlg + uTotalDistance[p];
  275. us[p].push(dist);
  276. uTotalDistance[p] = dist;
  277. }
  278. j++;
  279. }
  280. if ( closePath ) {
  281. var vectlg = path[0].subtract(path[j-1]).length();
  282. var dist = vectlg + uTotalDistance[p];
  283. uTotalDistance[p] = dist;
  284. }
  285. idc += l;
  286. }
  287. // vertical distances (v)
  288. for(var i = 0; i < minlg; i++) {
  289. vTotalDistance[i] = 0;
  290. vs[i] =[0];
  291. for (var p = 0; p < pathArray.length-1; p++) {
  292. var path1 = pathArray[p];
  293. var path2 = pathArray[p+1];
  294. var vectlg = path2[i].subtract(path1[i]).length();
  295. var dist = vectlg + vTotalDistance[i];
  296. vs[i].push(dist);
  297. vTotalDistance[i] = dist;
  298. }
  299. if (closeArray) {
  300. var path1 = pathArray[p];
  301. var path2 = pathArray[0];
  302. var vectlg = path2[i].subtract(path1[i]).length();
  303. var dist = vectlg + vTotalDistance[i];
  304. vTotalDistance[i] = dist;
  305. }
  306. }
  307. // uvs
  308. for(var p = 0; p < pathArray.length; p++) {
  309. for(var i = 0; i < minlg; i++) {
  310. var u = us[p][i] / uTotalDistance[p];
  311. var v = vs[i][p] / vTotalDistance[i];
  312. uvs.push(u, v);
  313. }
  314. }
  315. // indices
  316. var p = 0; // path index
  317. var i = 0; // positions array index
  318. var l1 = lg[p] - 1; // path1 length
  319. var l2 = lg[p+1] - 1; // path2 length
  320. var min = ( l1 < l2 ) ? l1 : l2 ; // current path stop index
  321. var shft = idx[1] - idx[0]; // shift
  322. var path1nb = closeArray ? lg.length : lg.length -1; // number of path1 to iterate
  323. while ( i <= min && p < path1nb ) { // stay under min and don't go over next to last path
  324. // draw two triangles between path1 (p1) and path2 (p2) : (p1.i, p2.i, p1.i+1) and (p2.i+1, p1.i+1, p2.i) clockwise
  325. var t1 = i;
  326. var t2 = i + shft;
  327. var t3 = i +1;
  328. var t4 = i + shft + 1;
  329. indices.push(i, i+shft, i+1);
  330. indices.push(i+shft+1, i+1, i+shft);
  331. i += 1;
  332. if ( i == min ) { // if end of one of two consecutive paths reached, go next existing path
  333. if (closePath) { // if closePath, add last triangles between start and end of the paths
  334. indices.push(i, i+shft, idx[p]);
  335. indices.push(idx[p]+shft, idx[p], i+shft);
  336. t3 = idx[p];
  337. t4 = idx[p] + shft;
  338. }
  339. p++;
  340. if ( p == lg.length - 1 ) { // last path of pathArray reached <=> closeArray == true
  341. shft = idx[0] - idx[p];
  342. l1 = lg[p] - 1;
  343. l2 = lg[0] - 1;
  344. }
  345. else {
  346. shft = idx[p+1] - idx[p];
  347. l1 = lg[p] - 1;
  348. l2 = lg[p+1] - 1;
  349. }
  350. i = idx[p];
  351. min = ( l1 < l2 ) ? l1 + i : l2 + i;
  352. }
  353. }
  354. // normals
  355. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  356. // Result
  357. var vertexData = new BABYLON.VertexData();
  358. vertexData.indices = indices;
  359. vertexData.positions = positions;
  360. vertexData.normals = normals;
  361. vertexData.uvs = uvs;
  362. return vertexData;
  363. }
  364. public static CreateBox(size: number): VertexData {
  365. var normalsSource = [
  366. new BABYLON.Vector3(0, 0, 1),
  367. new BABYLON.Vector3(0, 0, -1),
  368. new BABYLON.Vector3(1, 0, 0),
  369. new BABYLON.Vector3(-1, 0, 0),
  370. new BABYLON.Vector3(0, 1, 0),
  371. new BABYLON.Vector3(0, -1, 0)
  372. ];
  373. var indices = [];
  374. var positions = [];
  375. var normals = [];
  376. var uvs = [];
  377. size = size || 1;
  378. // Create each face in turn.
  379. for (var index = 0; index < normalsSource.length; index++) {
  380. var normal = normalsSource[index];
  381. // Get two vectors perpendicular to the face normal and to each other.
  382. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  383. var side2 = BABYLON.Vector3.Cross(normal, side1);
  384. // Six indices (two triangles) per face.
  385. var verticesLength = positions.length / 3;
  386. indices.push(verticesLength);
  387. indices.push(verticesLength + 1);
  388. indices.push(verticesLength + 2);
  389. indices.push(verticesLength);
  390. indices.push(verticesLength + 2);
  391. indices.push(verticesLength + 3);
  392. // Four vertices per face.
  393. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  394. positions.push(vertex.x, vertex.y, vertex.z);
  395. normals.push(normal.x, normal.y, normal.z);
  396. uvs.push(1.0, 1.0);
  397. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  398. positions.push(vertex.x, vertex.y, vertex.z);
  399. normals.push(normal.x, normal.y, normal.z);
  400. uvs.push(0.0, 1.0);
  401. vertex = normal.add(side1).add(side2).scale(size / 2);
  402. positions.push(vertex.x, vertex.y, vertex.z);
  403. normals.push(normal.x, normal.y, normal.z);
  404. uvs.push(0.0, 0.0);
  405. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  406. positions.push(vertex.x, vertex.y, vertex.z);
  407. normals.push(normal.x, normal.y, normal.z);
  408. uvs.push(1.0, 0.0);
  409. }
  410. // Result
  411. var vertexData = new BABYLON.VertexData();
  412. vertexData.indices = indices;
  413. vertexData.positions = positions;
  414. vertexData.normals = normals;
  415. vertexData.uvs = uvs;
  416. return vertexData;
  417. }
  418. public static CreateSphere(segments: number, diameter: number): VertexData {
  419. segments = segments || 32;
  420. diameter = diameter || 1;
  421. var radius = diameter / 2;
  422. var totalZRotationSteps = 2 + segments;
  423. var totalYRotationSteps = 2 * totalZRotationSteps;
  424. var indices = [];
  425. var positions = [];
  426. var normals = [];
  427. var uvs = [];
  428. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  429. var normalizedZ = zRotationStep / totalZRotationSteps;
  430. var angleZ = (normalizedZ * Math.PI);
  431. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  432. var normalizedY = yRotationStep / totalYRotationSteps;
  433. var angleY = normalizedY * Math.PI * 2;
  434. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  435. var rotationY = BABYLON.Matrix.RotationY(angleY);
  436. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  437. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  438. var vertex = complete.scale(radius);
  439. var normal = BABYLON.Vector3.Normalize(vertex);
  440. positions.push(vertex.x, vertex.y, vertex.z);
  441. normals.push(normal.x, normal.y, normal.z);
  442. uvs.push(normalizedZ, normalizedY);
  443. }
  444. if (zRotationStep > 0) {
  445. var verticesCount = positions.length / 3;
  446. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  447. indices.push((firstIndex));
  448. indices.push((firstIndex + 1));
  449. indices.push(firstIndex + totalYRotationSteps + 1);
  450. indices.push((firstIndex + totalYRotationSteps + 1));
  451. indices.push((firstIndex + 1));
  452. indices.push((firstIndex + totalYRotationSteps + 2));
  453. }
  454. }
  455. }
  456. // Result
  457. var vertexData = new BABYLON.VertexData();
  458. vertexData.indices = indices;
  459. vertexData.positions = positions;
  460. vertexData.normals = normals;
  461. vertexData.uvs = uvs;
  462. return vertexData;
  463. }
  464. public static CreateCylinder(height: number, diameterTop: number, diameterBottom: number, tessellation: number, subdivisions: number = 1): VertexData {
  465. var radiusTop = diameterTop / 2;
  466. var radiusBottom = diameterBottom / 2;
  467. var indices = [];
  468. var positions = [];
  469. var normals = [];
  470. var uvs = [];
  471. height = height || 1;
  472. diameterTop = diameterTop || 0.5;
  473. diameterBottom = diameterBottom || 1;
  474. tessellation = tessellation || 16;
  475. subdivisions = subdivisions || 1;
  476. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  477. var getCircleVector = i => {
  478. var angle = (i * 2.0 * Math.PI / tessellation);
  479. var dx = Math.cos(angle);
  480. var dz = Math.sin(angle);
  481. return new BABYLON.Vector3(dx, 0, dz);
  482. };
  483. var createCylinderCap = isTop => {
  484. var radius = isTop ? radiusTop : radiusBottom;
  485. if (radius == 0) {
  486. return;
  487. }
  488. var vbase = positions.length / 3;
  489. var offset = new BABYLON.Vector3(0, height / 2, 0);
  490. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  491. if (!isTop) {
  492. offset.scaleInPlace(-1);
  493. textureScale.x = -textureScale.x;
  494. }
  495. // Positions, normals & uvs
  496. for (i = 0; i < tessellation; i++) {
  497. var circleVector = getCircleVector(i);
  498. var position = circleVector.scale(radius).add(offset);
  499. var textureCoordinate = new BABYLON.Vector2(
  500. circleVector.x * textureScale.x + 0.5,
  501. circleVector.z * textureScale.y + 0.5
  502. );
  503. positions.push(position.x, position.y, position.z);
  504. uvs.push(textureCoordinate.x, textureCoordinate.y);
  505. }
  506. // Indices
  507. for (var i = 0; i < tessellation - 2; i++) {
  508. if (!isTop) {
  509. indices.push(vbase);
  510. indices.push(vbase + (i + 2) % tessellation);
  511. indices.push(vbase + (i + 1) % tessellation);
  512. } else {
  513. indices.push(vbase);
  514. indices.push(vbase + (i + 1) % tessellation);
  515. indices.push(vbase + (i + 2) % tessellation);
  516. }
  517. }
  518. };
  519. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  520. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  521. var stride = tessellation + 1;
  522. // Positions, normals & uvs
  523. for (var i = 0; i <= tessellation; i++) {
  524. var circleVector = getCircleVector(i);
  525. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  526. var position, radius = radiusBottom;
  527. for (var s = 0; s <= subdivisions; s++) {
  528. // Update variables
  529. position = circleVector.scale(radius);
  530. position.addInPlace(base.add(offset.scale(s)));
  531. textureCoordinate.y += 1 / subdivisions;
  532. radius += (radiusTop - radiusBottom) / subdivisions;
  533. // Push in arrays
  534. positions.push(position.x, position.y, position.z);
  535. uvs.push(textureCoordinate.x, textureCoordinate.y);
  536. }
  537. }
  538. subdivisions += 1;
  539. // Indices
  540. for (var s = 0; s < subdivisions - 1; s++) {
  541. for (var i = 0; i <= tessellation; i++) {
  542. indices.push(i * subdivisions + s);
  543. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  544. indices.push(i * subdivisions + (s + 1));
  545. indices.push(i * subdivisions + (s + 1));
  546. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  547. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  548. }
  549. }
  550. // Create flat triangle fan caps to seal the top and bottom.
  551. createCylinderCap(true);
  552. createCylinderCap(false);
  553. // Normals
  554. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  555. // Result
  556. var vertexData = new BABYLON.VertexData();
  557. vertexData.indices = indices;
  558. vertexData.positions = positions;
  559. vertexData.normals = normals;
  560. vertexData.uvs = uvs;
  561. return vertexData;
  562. }
  563. public static CreateTorus(diameter, thickness, tessellation) {
  564. var indices = [];
  565. var positions = [];
  566. var normals = [];
  567. var uvs = [];
  568. diameter = diameter || 1;
  569. thickness = thickness || 0.5;
  570. tessellation = tessellation || 16;
  571. var stride = tessellation + 1;
  572. for (var i = 0; i <= tessellation; i++) {
  573. var u = i / tessellation;
  574. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  575. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  576. for (var j = 0; j <= tessellation; j++) {
  577. var v = 1 - j / tessellation;
  578. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  579. var dx = Math.cos(innerAngle);
  580. var dy = Math.sin(innerAngle);
  581. // Create a vertex.
  582. var normal = new BABYLON.Vector3(dx, dy, 0);
  583. var position = normal.scale(thickness / 2);
  584. var textureCoordinate = new BABYLON.Vector2(u, v);
  585. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  586. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  587. positions.push(position.x, position.y, position.z);
  588. normals.push(normal.x, normal.y, normal.z);
  589. uvs.push(textureCoordinate.x, textureCoordinate.y);
  590. // And create indices for two triangles.
  591. var nextI = (i + 1) % stride;
  592. var nextJ = (j + 1) % stride;
  593. indices.push(i * stride + j);
  594. indices.push(i * stride + nextJ);
  595. indices.push(nextI * stride + j);
  596. indices.push(i * stride + nextJ);
  597. indices.push(nextI * stride + nextJ);
  598. indices.push(nextI * stride + j);
  599. }
  600. }
  601. // Result
  602. var vertexData = new BABYLON.VertexData();
  603. vertexData.indices = indices;
  604. vertexData.positions = positions;
  605. vertexData.normals = normals;
  606. vertexData.uvs = uvs;
  607. return vertexData;
  608. }
  609. public static CreateLines(points: Vector3[]): VertexData {
  610. var indices = [];
  611. var positions = [];
  612. for (var index = 0; index < points.length; index++) {
  613. positions.push(points[index].x, points[index].y, points[index].z);
  614. if (index > 0) {
  615. indices.push(index - 1);
  616. indices.push(index);
  617. }
  618. }
  619. // Result
  620. var vertexData = new BABYLON.VertexData();
  621. vertexData.indices = indices;
  622. vertexData.positions = positions;
  623. return vertexData;
  624. }
  625. public static CreateGround(width: number, height: number, subdivisions: number): VertexData {
  626. var indices = [];
  627. var positions = [];
  628. var normals = [];
  629. var uvs = [];
  630. var row, col;
  631. width = width || 1;
  632. height = height || 1;
  633. subdivisions = subdivisions || 1;
  634. for (row = 0; row <= subdivisions; row++) {
  635. for (col = 0; col <= subdivisions; col++) {
  636. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  637. var normal = new BABYLON.Vector3(0, 1.0, 0);
  638. positions.push(position.x, position.y, position.z);
  639. normals.push(normal.x, normal.y, normal.z);
  640. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  641. }
  642. }
  643. for (row = 0; row < subdivisions; row++) {
  644. for (col = 0; col < subdivisions; col++) {
  645. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  646. indices.push(col + 1 + row * (subdivisions + 1));
  647. indices.push(col + row * (subdivisions + 1));
  648. indices.push(col + (row + 1) * (subdivisions + 1));
  649. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  650. indices.push(col + row * (subdivisions + 1));
  651. }
  652. }
  653. // Result
  654. var vertexData = new BABYLON.VertexData();
  655. vertexData.indices = indices;
  656. vertexData.positions = positions;
  657. vertexData.normals = normals;
  658. vertexData.uvs = uvs;
  659. return vertexData;
  660. }
  661. public static CreateTiledGround(xmin: number, zmin: number, xmax: number, zmax: number, subdivisions = { w: 1, h: 1 }, precision = { w: 1, h: 1 }): VertexData {
  662. var indices = [];
  663. var positions = [];
  664. var normals = [];
  665. var uvs = [];
  666. var row, col, tileRow, tileCol;
  667. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  668. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  669. precision.w = (precision.w < 1) ? 1 : precision.w;
  670. precision.h = (precision.h < 1) ? 1 : precision.h;
  671. var tileSize = {
  672. 'w': (xmax - xmin) / subdivisions.w,
  673. 'h': (zmax - zmin) / subdivisions.h
  674. };
  675. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  676. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  677. applyTile(
  678. xmin + tileCol * tileSize.w,
  679. zmin + tileRow * tileSize.h,
  680. xmin + (tileCol + 1) * tileSize.w,
  681. zmin + (tileRow + 1) * tileSize.h
  682. );
  683. }
  684. }
  685. function applyTile(xTileMin: number, zTileMin: number, xTileMax: number, zTileMax: number) {
  686. // Indices
  687. var base = positions.length / 3;
  688. var rowLength = precision.w + 1;
  689. for (row = 0; row < precision.h; row++) {
  690. for (col = 0; col < precision.w; col++) {
  691. var square = [
  692. base + col + row * rowLength,
  693. base + (col + 1) + row * rowLength,
  694. base + (col + 1) + (row + 1) * rowLength,
  695. base + col + (row + 1) * rowLength
  696. ];
  697. indices.push(square[1]);
  698. indices.push(square[2]);
  699. indices.push(square[3]);
  700. indices.push(square[0]);
  701. indices.push(square[1]);
  702. indices.push(square[3]);
  703. }
  704. }
  705. // Position, normals and uvs
  706. var position = BABYLON.Vector3.Zero();
  707. var normal = new BABYLON.Vector3(0, 1.0, 0);
  708. for (row = 0; row <= precision.h; row++) {
  709. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  710. for (col = 0; col <= precision.w; col++) {
  711. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  712. position.y = 0;
  713. positions.push(position.x, position.y, position.z);
  714. normals.push(normal.x, normal.y, normal.z);
  715. uvs.push(col / precision.w, row / precision.h);
  716. }
  717. }
  718. }
  719. // Result
  720. var vertexData = new BABYLON.VertexData();
  721. vertexData.indices = indices;
  722. vertexData.positions = positions;
  723. vertexData.normals = normals;
  724. vertexData.uvs = uvs;
  725. return vertexData;
  726. }
  727. public static CreateGroundFromHeightMap(width: number, height: number, subdivisions: number, minHeight: number, maxHeight: number, buffer: Uint8Array, bufferWidth: number, bufferHeight: number): VertexData {
  728. var indices = [];
  729. var positions = [];
  730. var normals = [];
  731. var uvs = [];
  732. var row, col;
  733. // Vertices
  734. for (row = 0; row <= subdivisions; row++) {
  735. for (col = 0; col <= subdivisions; col++) {
  736. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  737. // Compute height
  738. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  739. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  740. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  741. var r = buffer[pos] / 255.0;
  742. var g = buffer[pos + 1] / 255.0;
  743. var b = buffer[pos + 2] / 255.0;
  744. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  745. position.y = minHeight + (maxHeight - minHeight) * gradient;
  746. // Add vertex
  747. positions.push(position.x, position.y, position.z);
  748. normals.push(0, 0, 0);
  749. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  750. }
  751. }
  752. // Indices
  753. for (row = 0; row < subdivisions; row++) {
  754. for (col = 0; col < subdivisions; col++) {
  755. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  756. indices.push(col + 1 + row * (subdivisions + 1));
  757. indices.push(col + row * (subdivisions + 1));
  758. indices.push(col + (row + 1) * (subdivisions + 1));
  759. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  760. indices.push(col + row * (subdivisions + 1));
  761. }
  762. }
  763. // Normals
  764. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  765. // Result
  766. var vertexData = new BABYLON.VertexData();
  767. vertexData.indices = indices;
  768. vertexData.positions = positions;
  769. vertexData.normals = normals;
  770. vertexData.uvs = uvs;
  771. return vertexData;
  772. }
  773. public static CreatePlane(size: number): VertexData {
  774. var indices = [];
  775. var positions = [];
  776. var normals = [];
  777. var uvs = [];
  778. size = size || 1;
  779. // Vertices
  780. var halfSize = size / 2.0;
  781. positions.push(-halfSize, -halfSize, 0);
  782. normals.push(0, 0, -1.0);
  783. uvs.push(0.0, 0.0);
  784. positions.push(halfSize, -halfSize, 0);
  785. normals.push(0, 0, -1.0);
  786. uvs.push(1.0, 0.0);
  787. positions.push(halfSize, halfSize, 0);
  788. normals.push(0, 0, -1.0);
  789. uvs.push(1.0, 1.0);
  790. positions.push(-halfSize, halfSize, 0);
  791. normals.push(0, 0, -1.0);
  792. uvs.push(0.0, 1.0);
  793. // Indices
  794. indices.push(0);
  795. indices.push(1);
  796. indices.push(2);
  797. indices.push(0);
  798. indices.push(2);
  799. indices.push(3);
  800. // Result
  801. var vertexData = new BABYLON.VertexData();
  802. vertexData.indices = indices;
  803. vertexData.positions = positions;
  804. vertexData.normals = normals;
  805. vertexData.uvs = uvs;
  806. return vertexData;
  807. }
  808. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  809. public static CreateTorusKnot(radius: number, tube: number, radialSegments: number, tubularSegments: number, p: number, q: number): VertexData {
  810. var indices = [];
  811. var positions = [];
  812. var normals = [];
  813. var uvs = [];
  814. radius = radius || 2;
  815. tube = tube || 0.5;
  816. radialSegments = radialSegments || 32;
  817. tubularSegments = tubularSegments || 32;
  818. p = p || 2;
  819. q = q || 3;
  820. // Helper
  821. var getPos = (angle) => {
  822. var cu = Math.cos(angle);
  823. var su = Math.sin(angle);
  824. var quOverP = q / p * angle;
  825. var cs = Math.cos(quOverP);
  826. var tx = radius * (2 + cs) * 0.5 * cu;
  827. var ty = radius * (2 + cs) * su * 0.5;
  828. var tz = radius * Math.sin(quOverP) * 0.5;
  829. return new BABYLON.Vector3(tx, ty, tz);
  830. };
  831. // Vertices
  832. for (var i = 0; i <= radialSegments; i++) {
  833. var modI = i % radialSegments;
  834. var u = modI / radialSegments * 2 * p * Math.PI;
  835. var p1 = getPos(u);
  836. var p2 = getPos(u + 0.01);
  837. var tang = p2.subtract(p1);
  838. var n = p2.add(p1);
  839. var bitan = BABYLON.Vector3.Cross(tang, n);
  840. n = BABYLON.Vector3.Cross(bitan, tang);
  841. bitan.normalize();
  842. n.normalize();
  843. for (var j = 0; j < tubularSegments; j++) {
  844. var modJ = j % tubularSegments;
  845. var v = modJ / tubularSegments * 2 * Math.PI;
  846. var cx = -tube * Math.cos(v);
  847. var cy = tube * Math.sin(v);
  848. positions.push(p1.x + cx * n.x + cy * bitan.x);
  849. positions.push(p1.y + cx * n.y + cy * bitan.y);
  850. positions.push(p1.z + cx * n.z + cy * bitan.z);
  851. uvs.push(i / radialSegments);
  852. uvs.push(j / tubularSegments);
  853. }
  854. }
  855. for (i = 0; i < radialSegments; i++) {
  856. for (j = 0; j < tubularSegments; j++) {
  857. var jNext = (j + 1) % tubularSegments;
  858. var a = i * tubularSegments + j;
  859. var b = (i + 1) * tubularSegments + j;
  860. var c = (i + 1) * tubularSegments + jNext;
  861. var d = i * tubularSegments + jNext;
  862. indices.push(d); indices.push(b); indices.push(a);
  863. indices.push(d); indices.push(c); indices.push(b);
  864. }
  865. }
  866. // Normals
  867. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  868. // Result
  869. var vertexData = new BABYLON.VertexData();
  870. vertexData.indices = indices;
  871. vertexData.positions = positions;
  872. vertexData.normals = normals;
  873. vertexData.uvs = uvs;
  874. return vertexData;
  875. }
  876. // Tools
  877. public static ComputeNormals(positions: number[], indices: number[], normals: number[]) {
  878. var positionVectors = [];
  879. var facesOfVertices = [];
  880. var index;
  881. for (index = 0; index < positions.length; index += 3) {
  882. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  883. positionVectors.push(vector3);
  884. facesOfVertices.push([]);
  885. }
  886. // Compute normals
  887. var facesNormals = [];
  888. for (index = 0; index < indices.length / 3; index++) {
  889. var i1 = indices[index * 3];
  890. var i2 = indices[index * 3 + 1];
  891. var i3 = indices[index * 3 + 2];
  892. var p1 = positionVectors[i1];
  893. var p2 = positionVectors[i2];
  894. var p3 = positionVectors[i3];
  895. var p1p2 = p1.subtract(p2);
  896. var p3p2 = p3.subtract(p2);
  897. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  898. facesOfVertices[i1].push(index);
  899. facesOfVertices[i2].push(index);
  900. facesOfVertices[i3].push(index);
  901. }
  902. for (index = 0; index < positionVectors.length; index++) {
  903. var faces = facesOfVertices[index];
  904. var normal = BABYLON.Vector3.Zero();
  905. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  906. normal.addInPlace(facesNormals[faces[faceIndex]]);
  907. }
  908. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  909. normals[index * 3] = normal.x;
  910. normals[index * 3 + 1] = normal.y;
  911. normals[index * 3 + 2] = normal.z;
  912. }
  913. }
  914. }
  915. }