babylon.meshBuilder.ts 88 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308
  1. module BABYLON {
  2. export class MeshBuilder {
  3. private static updateSideOrientation(orientation: number, scene: Scene): number {
  4. if (orientation == Mesh.DOUBLESIDE) {
  5. return Mesh.DOUBLESIDE;
  6. }
  7. if (orientation === undefined || orientation === null) {
  8. return Mesh.FRONTSIDE;
  9. }
  10. return orientation;
  11. }
  12. /**
  13. * Creates a box mesh.
  14. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  15. * The parameter `size` sets the size (float) of each box side (default 1).
  16. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  17. * You can set different colors and different images to each box side by using the parameters `faceColors` (an array of 6 Color3 elements) and `faceUV` (an array of 6 Vector4 elements).
  18. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  19. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  21. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23. */
  24. public static CreateBox(name: string, options: { size?: number, width?: number, height?: number, depth?: number, faceUV?: Vector4[], faceColors?: Color4[], sideOrientation?: number, frontUVs?: Vector4, backUVs?: Vector4, updatable?: boolean }, scene: Scene): Mesh {
  25. var box = new Mesh(name, scene);
  26. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  27. box._originalBuilderSideOrientation = options.sideOrientation;
  28. var vertexData = VertexData.CreateBox(options);
  29. vertexData.applyToMesh(box, options.updatable);
  30. return box;
  31. }
  32. /**
  33. * Creates a sphere mesh.
  34. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  35. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  36. * You can set some different sphere dimensions, for instance to build an ellipsoid, by using the parameters `diameterX`, `diameterY` and `diameterZ` (all by default have the same value than `diameter`).
  37. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  38. * You can create an unclosed sphere with the parameter `arc` (positive float, default 1), valued between 0 and 1, what is the ratio of the circumference (latitude) : 2 x PI x ratio
  39. * You can create an unclosed sphere on its height with the parameter `slice` (positive float, default1), valued between 0 and 1, what is the height ratio (longitude).
  40. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  41. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  42. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44. */
  45. public static CreateSphere(name: string, options: { segments?: number, diameter?: number, diameterX?: number, diameterY?: number, diameterZ?: number, arc?: number, slice?: number, sideOrientation?: number, frontUVs?: Vector4, backUVs?: Vector4, updatable?: boolean }, scene: any): Mesh {
  46. var sphere = new Mesh(name, scene);
  47. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  48. sphere._originalBuilderSideOrientation = options.sideOrientation;
  49. var vertexData = VertexData.CreateSphere(options);
  50. vertexData.applyToMesh(sphere, options.updatable);
  51. return sphere;
  52. }
  53. /**
  54. * Creates a plane polygonal mesh. By default, this is a disc.
  55. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  56. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  57. * The parameter `tessellation` sets the number of polygon sides (positive integer, default 64). So a tessellation valued to 3 will build a triangle, to 4 a square, etc.
  58. * You can create an unclosed polygon with the parameter `arc` (positive float, default 1), valued between 0 and 1, what is the ratio of the circumference : 2 x PI x ratio
  59. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  61. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  62. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  63. */
  64. public static CreateDisc(name: string, options: { radius?: number, tessellation?: number, arc?: number, updatable?: boolean, sideOrientation?: number, frontUVs?: Vector4, backUVs?: Vector4 }, scene: Scene): Mesh {
  65. var disc = new Mesh(name, scene);
  66. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  67. disc._originalBuilderSideOrientation = options.sideOrientation;
  68. var vertexData = VertexData.CreateDisc(options);
  69. vertexData.applyToMesh(disc, options.updatable);
  70. return disc;
  71. }
  72. /**
  73. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  74. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  75. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  76. * You can set some different icosphere dimensions, for instance to build an ellipsoid, by using the parameters `radiusX`, `radiusY` and `radiusZ` (all by default have the same value than `radius`).
  77. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  78. * The parameter `flat` (boolean, default true) gives each side its own normals. Set it to false to get a smooth continuous light reflection on the surface.
  79. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  80. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  81. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  82. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  83. */
  84. public static CreateIcoSphere(name: string, options: { radius?: number, radiusX?: number, radiusY?: number, radiusZ?: number, flat?: boolean, subdivisions?: number, sideOrientation?: number, frontUVs?: Vector4, backUVs?: Vector4, updatable?: boolean }, scene: Scene): Mesh {
  85. var sphere = new Mesh(name, scene);
  86. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  87. sphere._originalBuilderSideOrientation = options.sideOrientation;
  88. var vertexData = VertexData.CreateIcoSphere(options);
  89. vertexData.applyToMesh(sphere, options.updatable);
  90. return sphere;
  91. };
  92. /**
  93. * Creates a ribbon mesh.
  94. * The ribbon is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  95. *
  96. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  97. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  98. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  99. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  100. * The parameter `offset` (positive integer, default : rounded half size of the pathArray length), is taken in account only if the `pathArray` is containing a single path.
  101. * It's the offset to join the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11.
  102. * The optional parameter `instance` is an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#ribbon
  103. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  104. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  105. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  106. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  107. * The parameter `uvs` is an optional flat array of `Vector2` to update/set each ribbon vertex with its own custom UV values instead of the computed ones.
  108. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  109. * Note that if you use the parameters `uvs` or `colors`, the passed arrays must be populated with the right number of elements, it is to say the number of ribbon vertices. Remember that
  110. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  111. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  112. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  113. */
  114. public static CreateRibbon(name: string, options: { pathArray: Vector3[][], closeArray?: boolean, closePath?: boolean, offset?: number, updatable?: boolean, sideOrientation?: number, frontUVs?: Vector4, backUVs?: Vector4, instance?: Mesh, invertUV?: boolean, uvs?: Vector2[], colors?: Color4[] }, scene?: Scene): Mesh {
  115. var pathArray = options.pathArray;
  116. var closeArray = options.closeArray;
  117. var closePath = options.closePath;
  118. var offset = options.offset;
  119. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  120. var instance = options.instance;
  121. var updatable = options.updatable;
  122. if (instance) { // existing ribbon instance update
  123. // positionFunction : ribbon case
  124. // only pathArray and sideOrientation parameters are taken into account for positions update
  125. Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Tmp.Vector3[0]); // minimum
  126. Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, Tmp.Vector3[1]);
  127. var positionFunction = positions => {
  128. var minlg = pathArray[0].length;
  129. var i = 0;
  130. var ns = (instance._originalBuilderSideOrientation === Mesh.DOUBLESIDE) ? 2 : 1;
  131. for (var si = 1; si <= ns; si++) {
  132. for (var p = 0; p < pathArray.length; p++) {
  133. var path = pathArray[p];
  134. var l = path.length;
  135. minlg = (minlg < l) ? minlg : l;
  136. var j = 0;
  137. while (j < minlg) {
  138. positions[i] = path[j].x;
  139. positions[i + 1] = path[j].y;
  140. positions[i + 2] = path[j].z;
  141. if (path[j].x < Tmp.Vector3[0].x) {
  142. Tmp.Vector3[0].x = path[j].x;
  143. }
  144. if (path[j].x > Tmp.Vector3[1].x) {
  145. Tmp.Vector3[1].x = path[j].x;
  146. }
  147. if (path[j].y < Tmp.Vector3[0].y) {
  148. Tmp.Vector3[0].y = path[j].y;
  149. }
  150. if (path[j].y > Tmp.Vector3[1].y) {
  151. Tmp.Vector3[1].y = path[j].y;
  152. }
  153. if (path[j].z < Tmp.Vector3[0].z) {
  154. Tmp.Vector3[0].z = path[j].z;
  155. }
  156. if (path[j].z > Tmp.Vector3[1].z) {
  157. Tmp.Vector3[1].z = path[j].z;
  158. }
  159. j++;
  160. i += 3;
  161. }
  162. if ((<any>instance)._closePath) {
  163. positions[i] = path[0].x;
  164. positions[i + 1] = path[0].y;
  165. positions[i + 2] = path[0].z;
  166. i += 3;
  167. }
  168. }
  169. }
  170. };
  171. var positions = instance.getVerticesData(VertexBuffer.PositionKind);
  172. positionFunction(positions);
  173. instance._boundingInfo = new BoundingInfo(Tmp.Vector3[0], Tmp.Vector3[1]);
  174. instance._boundingInfo.update(instance._worldMatrix);
  175. instance.updateVerticesData(VertexBuffer.PositionKind, positions, false, false);
  176. if (options.colors) {
  177. var colors = instance.getVerticesData(VertexBuffer.ColorKind);
  178. for (var c = 0; c < options.colors.length; c++) {
  179. colors[c * 4] = options.colors[c].r;
  180. colors[c * 4 + 1] = options.colors[c].g;
  181. colors[c * 4 + 2] = options.colors[c].b;
  182. colors[c * 4 + 3] = options.colors[c].a;
  183. }
  184. instance.updateVerticesData(VertexBuffer.ColorKind, colors, false, false);
  185. }
  186. if (options.uvs) {
  187. var uvs = instance.getVerticesData(VertexBuffer.UVKind);
  188. for (var i = 0; i < options.uvs.length; i++) {
  189. uvs[i * 2] = options.uvs[i].x;
  190. uvs[i * 2 + 1] = options.uvs[i].y;
  191. }
  192. instance.updateVerticesData(VertexBuffer.UVKind, uvs, false, false);
  193. }
  194. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  195. var indices = instance.getIndices();
  196. var normals = instance.getVerticesData(VertexBuffer.NormalKind);
  197. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  198. VertexData.ComputeNormals(positions, indices, normals, params);
  199. if ((<any>instance)._closePath) {
  200. var indexFirst: number = 0;
  201. var indexLast: number = 0;
  202. for (var p = 0; p < pathArray.length; p++) {
  203. indexFirst = (<any>instance)._idx[p] * 3;
  204. if (p + 1 < pathArray.length) {
  205. indexLast = ((<any>instance)._idx[p + 1] - 1) * 3;
  206. }
  207. else {
  208. indexLast = normals.length - 3;
  209. }
  210. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  211. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  212. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  213. normals[indexLast] = normals[indexFirst];
  214. normals[indexLast + 1] = normals[indexFirst + 1];
  215. normals[indexLast + 2] = normals[indexFirst + 2];
  216. }
  217. }
  218. if (!(instance.areNormalsFrozen)) {
  219. instance.updateVerticesData(VertexBuffer.NormalKind, normals, false, false);
  220. }
  221. }
  222. return instance;
  223. }
  224. else { // new ribbon creation
  225. var ribbon = new Mesh(name, scene);
  226. ribbon._originalBuilderSideOrientation = sideOrientation;
  227. var vertexData = VertexData.CreateRibbon(options);
  228. if (closePath) {
  229. (<any>ribbon)._idx = (<any>vertexData)._idx;
  230. }
  231. (<any>ribbon)._closePath = closePath;
  232. (<any>ribbon)._closeArray = closeArray;
  233. vertexData.applyToMesh(ribbon, updatable);
  234. return ribbon;
  235. }
  236. }
  237. /**
  238. * Creates a cylinder or a cone mesh.
  239. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  240. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  241. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  242. * The parameters `diameterTop` and `diameterBottom` overwrite the parameter `diameter` and set respectively the top cap and bottom cap diameter (floats, default 1). The parameter "diameterBottom" can't be zero.
  243. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  244. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  245. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  246. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  247. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  248. * You can set different colors and different images to each box side by using the parameters `faceColors` (an array of n Color3 elements) and `faceUV` (an array of n Vector4 elements).
  249. * The value of n is the number of cylinder faces. If the cylinder has only 1 subdivisions, n equals : top face + cylinder surface + bottom face = 3
  250. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  251. * Finally, if the cylinder has 5 independent subdivisions and is enclose, n equals : top face + 5 x (stripe surface + 2 closing faces) + bottom face = 2 + 5 * 3 = 17
  252. * Each array (color or UVs) is always ordered the same way : the first element is the bottom cap, the last element is the top cap. The other elements are each a ring surface.
  253. * If `enclose` is false, a ring surface is one element.
  254. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  255. * Example how to set colors and textures on a sliced cylinder : http://www.html5gamedevs.com/topic/17945-creating-a-closed-slice-of-a-cylinder/#comment-106379
  256. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  257. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  258. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  259. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  260. */
  261. public static CreateCylinder(name: string, options: { height?: number, diameterTop?: number, diameterBottom?: number, diameter?: number, tessellation?: number, subdivisions?: number, arc?: number, faceColors?: Color4[], faceUV?: Vector4[], updatable?: boolean, hasRings?: boolean, enclose?: boolean, sideOrientation?: number, frontUVs?: Vector4, backUVs?: Vector4 }, scene: any): Mesh {
  262. var cylinder = new Mesh(name, scene);
  263. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  264. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  265. var vertexData = VertexData.CreateCylinder(options);
  266. vertexData.applyToMesh(cylinder, options.updatable);
  267. return cylinder;
  268. }
  269. /**
  270. * Creates a torus mesh.
  271. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  272. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  273. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  274. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  275. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  276. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  277. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  278. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  279. */
  280. public static CreateTorus(name: string, options: { diameter?: number, thickness?: number, tessellation?: number, updatable?: boolean, sideOrientation?: number, frontUVs?: Vector4, backUVs?: Vector4 }, scene: any): Mesh {
  281. var torus = new Mesh(name, scene);
  282. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  283. torus._originalBuilderSideOrientation = options.sideOrientation;
  284. var vertexData = VertexData.CreateTorus(options);
  285. vertexData.applyToMesh(torus, options.updatable);
  286. return torus;
  287. }
  288. /**
  289. * Creates a torus knot mesh.
  290. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  291. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  292. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  293. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  294. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  295. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  296. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  297. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  298. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  299. */
  300. public static CreateTorusKnot(name: string, options: { radius?: number, tube?: number, radialSegments?: number, tubularSegments?: number, p?: number, q?: number, updatable?: boolean, sideOrientation?: number, frontUVs?: Vector4, backUVs?: Vector4 }, scene: any): Mesh {
  301. var torusKnot = new Mesh(name, scene);
  302. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  303. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  304. var vertexData = VertexData.CreateTorusKnot(options);
  305. vertexData.applyToMesh(torusKnot, options.updatable);
  306. return torusKnot;
  307. }
  308. /**
  309. * Creates a line system mesh.
  310. * A line system is a pool of many lines gathered in a single mesh.
  311. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  312. * A line system mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of lines as an input parameter.
  313. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  314. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  315. * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter. The way to update it is the same than for
  316. * updating a simple Line mesh, you just need to update every line in the `lines` array : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  317. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  318. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  319. */
  320. public static CreateLineSystem(name: string, options: { lines: Vector3[][], updatable: boolean, instance?: LinesMesh }, scene: Scene): LinesMesh {
  321. var instance = options.instance;
  322. var lines = options.lines;
  323. if (instance) { // lines update
  324. var positionFunction = positions => {
  325. var i = 0;
  326. for (var l = 0; l < lines.length; l++) {
  327. var points = lines[l];
  328. for (var p = 0; p < points.length; p++) {
  329. positions[i] = points[p].x;
  330. positions[i + 1] = points[p].y;
  331. positions[i + 2] = points[p].z;
  332. i += 3;
  333. }
  334. }
  335. };
  336. instance.updateMeshPositions(positionFunction, false);
  337. return instance;
  338. }
  339. // line system creation
  340. var lineSystem = new LinesMesh(name, scene);
  341. var vertexData = VertexData.CreateLineSystem(options);
  342. vertexData.applyToMesh(lineSystem, options.updatable);
  343. return lineSystem;
  344. }
  345. /**
  346. * Creates a line mesh.
  347. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  348. * A line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
  349. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  350. * The parameter `points` is an array successive Vector3.
  351. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  352. * When updating an instance, remember that only point positions can change, not the number of points.
  353. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  354. */
  355. public static CreateLines(name: string, options: { points: Vector3[], updatable?: boolean, instance?: LinesMesh }, scene: Scene): LinesMesh {
  356. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  357. return lines;
  358. }
  359. /**
  360. * Creates a dashed line mesh.
  361. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  362. * A dashed line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
  363. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  364. * The parameter `points` is an array successive Vector3.
  365. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  366. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  367. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  368. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  369. * When updating an instance, remember that only point positions can change, not the number of points.
  370. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  371. */
  372. public static CreateDashedLines(name: string, options: { points: Vector3[], dashSize?: number, gapSize?: number, dashNb?: number, updatable?: boolean, instance?: LinesMesh }, scene: Scene): LinesMesh {
  373. var points = options.points;
  374. var instance = options.instance;
  375. var gapSize = options.gapSize || 1;
  376. var dashSize = options.dashSize || 3;
  377. if (instance) { // dashed lines update
  378. var positionFunction = (positions: number[]): void => {
  379. var curvect = Vector3.Zero();
  380. var nbSeg = positions.length / 6;
  381. var lg = 0;
  382. var nb = 0;
  383. var shft = 0;
  384. var dashshft = 0;
  385. var curshft = 0;
  386. var p = 0;
  387. var i = 0;
  388. var j = 0;
  389. for (i = 0; i < points.length - 1; i++) {
  390. points[i + 1].subtractToRef(points[i], curvect);
  391. lg += curvect.length();
  392. }
  393. shft = lg / nbSeg;
  394. dashshft = (<any>instance).dashSize * shft / ((<any>instance).dashSize + (<any>instance).gapSize);
  395. for (i = 0; i < points.length - 1; i++) {
  396. points[i + 1].subtractToRef(points[i], curvect);
  397. nb = Math.floor(curvect.length() / shft);
  398. curvect.normalize();
  399. j = 0;
  400. while (j < nb && p < positions.length) {
  401. curshft = shft * j;
  402. positions[p] = points[i].x + curshft * curvect.x;
  403. positions[p + 1] = points[i].y + curshft * curvect.y;
  404. positions[p + 2] = points[i].z + curshft * curvect.z;
  405. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  406. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  407. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  408. p += 6;
  409. j++;
  410. }
  411. }
  412. while (p < positions.length) {
  413. positions[p] = points[i].x;
  414. positions[p + 1] = points[i].y;
  415. positions[p + 2] = points[i].z;
  416. p += 3;
  417. }
  418. };
  419. instance.updateMeshPositions(positionFunction, false);
  420. return instance;
  421. }
  422. // dashed lines creation
  423. var dashedLines = new LinesMesh(name, scene);
  424. var vertexData = VertexData.CreateDashedLines(options);
  425. vertexData.applyToMesh(dashedLines, options.updatable);
  426. (<any>dashedLines).dashSize = dashSize;
  427. (<any>dashedLines).gapSize = gapSize;
  428. return dashedLines;
  429. }
  430. /**
  431. * Creates an extruded shape mesh.
  432. * The extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  433. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  434. *
  435. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  436. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  437. * extruded along the Z axis.
  438. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  439. * The parameter `rotation` (float, default 0 radians) is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve.
  440. * The parameter `scale` (float, default 1) is the value to scale the shape.
  441. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  442. * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  443. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  444. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  445. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  446. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  447. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  448. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  449. */
  450. public static ExtrudeShape(name: string, options: { shape: Vector3[], path: Vector3[], scale?: number, rotation?: number, cap?: number, updatable?: boolean, sideOrientation?: number, frontUVs?: Vector4, backUVs?: Vector4, instance?: Mesh, invertUV?: boolean }, scene: Scene): Mesh {
  451. var path = options.path;
  452. var shape = options.shape;
  453. var scale = options.scale || 1;
  454. var rotation = options.rotation || 0;
  455. var cap = (options.cap === 0) ? 0 : options.cap || Mesh.NO_CAP;
  456. var updatable = options.updatable;
  457. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  458. var instance = options.instance;
  459. var invertUV = options.invertUV || false;
  460. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  461. }
  462. /**
  463. * Creates an custom extruded shape mesh.
  464. * The custom extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  465. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  466. *
  467. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  468. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  469. * extruded along the Z axis.
  470. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  471. * The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
  472. * and the distance of this point from the begining of the path :
  473. * ```javascript
  474. * var rotationFunction = function(i, distance) {
  475. * // do things
  476. * return rotationValue; }
  477. * ```
  478. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  479. * The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
  480. * and the distance of this point from the begining of the path :
  481. * ```javascript
  482. * var scaleFunction = function(i, distance) {
  483. * // do things
  484. * return scaleValue;}
  485. * ```
  486. * It must returns a float value that will be the scale value applied to the shape on each path point.
  487. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  488. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  489. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  490. * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  491. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  492. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  493. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  494. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  495. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  496. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  497. */
  498. public static ExtrudeShapeCustom(name: string, options: { shape: Vector3[], path: Vector3[], scaleFunction?: any, rotationFunction?: any, ribbonCloseArray?: boolean, ribbonClosePath?: boolean, cap?: number, updatable?: boolean, sideOrientation?: number, frontUVs?: Vector4, backUVs?: Vector4, instance?: Mesh, invertUV?: boolean }, scene: Scene): Mesh {
  499. var path = options.path;
  500. var shape = options.shape;
  501. var scaleFunction = options.scaleFunction || (() => { return 1; });
  502. var rotationFunction = options.rotationFunction || (() => { return 0; });
  503. var ribbonCloseArray = options.ribbonCloseArray || false;
  504. var ribbonClosePath = options.ribbonClosePath || false;
  505. var cap = (options.cap === 0) ? 0 : options.cap || Mesh.NO_CAP;
  506. var updatable = options.updatable;
  507. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  508. var instance = options.instance;
  509. var invertUV = options.invertUV || false;
  510. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  511. }
  512. /**
  513. * Creates lathe mesh.
  514. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  515. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  516. *
  517. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be
  518. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  519. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  520. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  521. * The parameter `arc` (positive float, default 1) is the ratio of the lathe. 0.5 builds for instance half a lathe, so an opened shape.
  522. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  523. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  524. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  525. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  526. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  527. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  528. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  529. */
  530. public static CreateLathe(name: string, options: { shape: Vector3[], radius?: number, tessellation?: number, arc?: number, closed?: boolean, updatable?: boolean, sideOrientation?: number, frontUVs?: Vector4, backUVs?: Vector4, cap?: number, invertUV?: boolean }, scene: Scene): Mesh {
  531. var arc: number = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  532. var closed: boolean = (options.closed === undefined) ? true : options.closed;
  533. var shape = options.shape;
  534. var radius = options.radius || 1;
  535. var tessellation = options.tessellation || 64;
  536. var updatable = options.updatable;
  537. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  538. var cap = options.cap || Mesh.NO_CAP;
  539. var pi2 = Math.PI * 2;
  540. var paths = new Array();
  541. var invertUV = options.invertUV || false;
  542. var i = 0;
  543. var p = 0;
  544. var step = pi2 / tessellation * arc;
  545. var rotated;
  546. var path = new Array<Vector3>();;
  547. for (i = 0; i <= tessellation; i++) {
  548. var path: Vector3[] = [];
  549. if (cap == Mesh.CAP_START || cap == Mesh.CAP_ALL) {
  550. path.push(new Vector3(0, shape[0].y, 0));
  551. path.push(new Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  552. }
  553. for (p = 0; p < shape.length; p++) {
  554. rotated = new Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  555. path.push(rotated);
  556. }
  557. if (cap == Mesh.CAP_END || cap == Mesh.CAP_ALL) {
  558. path.push(new Vector3(Math.cos(i * step) * shape[shape.length - 1].x * radius, shape[shape.length - 1].y, Math.sin(i * step) * shape[shape.length - 1].x * radius));
  559. path.push(new Vector3(0, shape[shape.length - 1].y, 0));
  560. }
  561. paths.push(path);
  562. }
  563. // lathe ribbon
  564. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  565. return lathe;
  566. }
  567. /**
  568. * Creates a plane mesh.
  569. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  570. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  571. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  572. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  573. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  574. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  575. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  576. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  577. */
  578. public static CreatePlane(name: string, options: { size?: number, width?: number, height?: number, sideOrientation?: number, frontUVs?: Vector4, backUVs?: Vector4, updatable?: boolean, sourcePlane?: Plane }, scene: Scene): Mesh {
  579. var plane = new Mesh(name, scene);
  580. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  581. plane._originalBuilderSideOrientation = options.sideOrientation;
  582. var vertexData = VertexData.CreatePlane(options);
  583. vertexData.applyToMesh(plane, options.updatable);
  584. if (options.sourcePlane) {
  585. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  586. var product = Math.acos(Vector3.Dot(options.sourcePlane.normal, Axis.Z));
  587. var vectorProduct = Vector3.Cross(Axis.Z, options.sourcePlane.normal);
  588. plane.rotate(vectorProduct, product);
  589. }
  590. return plane;
  591. }
  592. /**
  593. * Creates a ground mesh.
  594. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  595. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  596. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  597. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  598. */
  599. public static CreateGround(name: string, options: { width?: number, height?: number, subdivisions?: number, subdivisionsX?: number, subdivisionsY?: number, updatable?: boolean }, scene: any): Mesh {
  600. var ground = new GroundMesh(name, scene);
  601. ground._setReady(false);
  602. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  603. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  604. ground._width = options.width || 1;
  605. ground._height = options.height || 1;
  606. ground._maxX = ground._width / 2;
  607. ground._maxZ = ground._height / 2;
  608. ground._minX = -ground._maxX;
  609. ground._minZ = -ground._maxZ;
  610. var vertexData = VertexData.CreateGround(options);
  611. vertexData.applyToMesh(ground, options.updatable);
  612. ground._setReady(true);
  613. return ground;
  614. }
  615. /**
  616. * Creates a tiled ground mesh.
  617. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  618. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  619. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  620. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  621. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  622. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  623. * numbers of subdivisions on the ground width and height of each tile.
  624. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  625. */
  626. public static CreateTiledGround(name: string, options: { xmin: number, zmin: number, xmax: number, zmax: number, subdivisions?: { w: number; h: number; }, precision?: { w: number; h: number; }, updatable?: boolean }, scene: Scene): Mesh {
  627. var tiledGround = new Mesh(name, scene);
  628. var vertexData = VertexData.CreateTiledGround(options);
  629. vertexData.applyToMesh(tiledGround, options.updatable);
  630. return tiledGround;
  631. }
  632. /**
  633. * Creates a ground mesh from a height map.
  634. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  635. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  636. * The parameter `url` sets the URL of the height map image resource.
  637. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  638. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  639. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  640. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  641. * The parameter `colorFilter` (optional Color3, default (0.3, 0.59, 0.11) ) is the filter to apply to the image pixel colors to compute the height.
  642. * The parameter `onReady` is a javascript callback function that will be called once the mesh is just built (the height map download can last some time).
  643. * This function is passed the newly built mesh :
  644. * ```javascript
  645. * function(mesh) { // do things
  646. * return; }
  647. * ```
  648. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  649. */
  650. public static CreateGroundFromHeightMap(name: string, url: string, options: { width?: number, height?: number, subdivisions?: number, minHeight?: number, maxHeight?: number, colorFilter?: Color3, updatable?: boolean, onReady?: (mesh: GroundMesh) => void }, scene: Scene): GroundMesh {
  651. var width = options.width || 10.0;
  652. var height = options.height || 10.0;
  653. var subdivisions = options.subdivisions || 1|0;
  654. var minHeight = options.minHeight || 0.0;
  655. var maxHeight = options.maxHeight || 1.0;
  656. var filter = options.colorFilter || new Color3(0.3, 0.59, 0.11);
  657. var updatable = options.updatable;
  658. var onReady = options.onReady;
  659. var ground = new GroundMesh(name, scene);
  660. ground._subdivisionsX = subdivisions;
  661. ground._subdivisionsY = subdivisions;
  662. ground._width = width;
  663. ground._height = height;
  664. ground._maxX = ground._width / 2.0;
  665. ground._maxZ = ground._height / 2.0;
  666. ground._minX = -ground._maxX;
  667. ground._minZ = -ground._maxZ;
  668. ground._setReady(false);
  669. var onload = img => {
  670. // Getting height map data
  671. var canvas = document.createElement("canvas");
  672. var context = canvas.getContext("2d");
  673. var bufferWidth = img.width;
  674. var bufferHeight = img.height;
  675. canvas.width = bufferWidth;
  676. canvas.height = bufferHeight;
  677. context.drawImage(img, 0, 0);
  678. // Create VertexData from map data
  679. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  680. var buffer = <Uint8Array>(<any>context.getImageData(0, 0, bufferWidth, bufferHeight).data);
  681. var vertexData = VertexData.CreateGroundFromHeightMap({
  682. width: width, height: height,
  683. subdivisions: subdivisions,
  684. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  685. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  686. });
  687. vertexData.applyToMesh(ground, updatable);
  688. ground._setReady(true);
  689. //execute ready callback, if set
  690. if (onReady) {
  691. onReady(ground);
  692. }
  693. };
  694. Tools.LoadImage(url, onload, () => { }, scene.database);
  695. return ground;
  696. }
  697. /**
  698. * Creates a polygon mesh.
  699. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  700. * The parameter `shape` is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors.
  701. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  702. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  703. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  704. * Remember you can only change the shape positions, not their number when updating a polygon.
  705. */
  706. public static CreatePolygon(name: string, options: {shape: Vector3[], holes?: Vector3[][], depth?: number, faceUV?: Vector4[], faceColors?: Color4[], updatable?: boolean, sideOrientation?: number, frontUVs?: Vector4, backUVs?: Vector4}, scene: Scene): Mesh {
  707. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  708. var shape = options.shape;
  709. var holes = options.holes || [];
  710. var depth = options.depth || 0;
  711. var contours: Array<Vector2> = [];
  712. var hole: Array<Vector2> = [];
  713. for(var i=0; i < shape.length; i++) {
  714. contours[i] = new Vector2(shape[i].x, shape[i].z);
  715. }
  716. var epsilon = 0.00000001;
  717. if(contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  718. contours.pop();
  719. }
  720. var polygonTriangulation = new PolygonMeshBuilder(name, contours, scene);
  721. for(var hNb = 0; hNb < holes.length; hNb++) {
  722. hole = [];
  723. for(var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  724. hole.push(new Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  725. }
  726. polygonTriangulation.addHole(hole);
  727. }
  728. var polygon = polygonTriangulation.build(options.updatable, depth);
  729. polygon._originalBuilderSideOrientation = options.sideOrientation;
  730. var vertexData = VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  731. vertexData.applyToMesh(polygon, options.updatable);
  732. return polygon;
  733. };
  734. /**
  735. * Creates an extruded polygon mesh, with depth in the Y direction.
  736. * You can set different colors and different images to the top, bottom and extruded side by using the parameters `faceColors` (an array of 3 Color3 elements) and `faceUV` (an array of 3 Vector4 elements).
  737. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  738. */
  739. public static ExtrudePolygon(name: string, options: {shape: Vector3[], holes?: Vector3[][], depth?: number, faceUV?: Vector4[], faceColors?: Color4[], updatable?: boolean, sideOrientation?: number, frontUVs?: Vector4, backUVs?: Vector4}, scene: Scene): Mesh {
  740. return MeshBuilder.CreatePolygon(name, options, scene);
  741. };
  742. /**
  743. * Creates a tube mesh.
  744. * The tube is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  745. *
  746. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  747. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  748. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  749. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  750. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  751. * This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path.
  752. * It must return a radius value (positive float) :
  753. * ```javascript
  754. * var radiusFunction = function(i, distance) {
  755. * // do things
  756. * return radius; }
  757. * ```
  758. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  759. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  760. * The optional parameter `instance` is an instance of an existing Tube object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#tube
  761. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  762. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  763. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  764. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  765. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  766. */
  767. public static CreateTube(name: string, options: { path: Vector3[], radius?: number, tessellation?: number, radiusFunction?: { (i: number, distance: number): number; }, cap?: number, arc?: number, updatable?: boolean, sideOrientation?: number, frontUVs?: Vector4, backUVs?: Vector4, instance?: Mesh, invertUV?: boolean }, scene: Scene): Mesh {
  768. var path = options.path;
  769. var instance = options.instance;
  770. var radius = 1.0;
  771. if (instance) {
  772. radius = (<any>instance).radius;
  773. }
  774. if (options.radius !== undefined) {
  775. radius = options.radius;
  776. };
  777. var tessellation = options.tessellation || 64|0;
  778. var radiusFunction = options.radiusFunction;
  779. var cap = options.cap || Mesh.NO_CAP;
  780. var invertUV = options.invertUV || false;
  781. var updatable = options.updatable;
  782. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  783. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  784. // tube geometry
  785. var tubePathArray = (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) => {
  786. var tangents = path3D.getTangents();
  787. var normals = path3D.getNormals();
  788. var distances = path3D.getDistances();
  789. var pi2 = Math.PI * 2;
  790. var step = pi2 / tessellation * arc;
  791. var returnRadius: { (i: number, distance: number): number; } = () => radius;
  792. var radiusFunctionFinal: { (i: number, distance: number): number; } = radiusFunction || returnRadius;
  793. var circlePath: Vector3[];
  794. var rad: number;
  795. var normal: Vector3;
  796. var rotated: Vector3;
  797. var rotationMatrix: Matrix = Tmp.Matrix[0];
  798. var index = (cap === Mesh._NO_CAP || cap === Mesh.CAP_END) ? 0 : 2;
  799. for (var i = 0; i < path.length; i++) {
  800. rad = radiusFunctionFinal(i, distances[i]); // current radius
  801. circlePath = Array<Vector3>(); // current circle array
  802. normal = normals[i]; // current normal
  803. for (var t = 0; t < tessellation; t++) {
  804. Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  805. rotated = circlePath[t] ? circlePath[t] : Vector3.Zero();
  806. Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  807. rotated.scaleInPlace(rad).addInPlace(path[i]);
  808. circlePath[t] = rotated;
  809. }
  810. circlePaths[index] = circlePath;
  811. index++;
  812. }
  813. // cap
  814. var capPath = (nbPoints, pathIndex) => {
  815. var pointCap = Array<Vector3>();
  816. for (var i = 0; i < nbPoints; i++) {
  817. pointCap.push(path[pathIndex]);
  818. }
  819. return pointCap;
  820. };
  821. switch (cap) {
  822. case Mesh.NO_CAP:
  823. break;
  824. case Mesh.CAP_START:
  825. circlePaths[0] = capPath(tessellation, 0);
  826. circlePaths[1] = circlePaths[2].slice(0);
  827. break;
  828. case Mesh.CAP_END:
  829. circlePaths[index] = circlePaths[index - 1].slice(0);
  830. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  831. break;
  832. case Mesh.CAP_ALL:
  833. circlePaths[0] = capPath(tessellation, 0);
  834. circlePaths[1] = circlePaths[2].slice(0);
  835. circlePaths[index] = circlePaths[index - 1].slice(0);
  836. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  837. break;
  838. default:
  839. break;
  840. }
  841. return circlePaths;
  842. };
  843. var path3D;
  844. var pathArray;
  845. if (instance) { // tube update
  846. var arc = options.arc || (<any>instance).arc;
  847. path3D = ((<any>instance).path3D).update(path);
  848. pathArray = tubePathArray(path, path3D, (<any>instance).pathArray, radius, (<any>instance).tessellation, radiusFunction, (<any>instance).cap, arc);
  849. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  850. (<any>instance).path3D = path3D;
  851. (<any>instance).pathArray = pathArray;
  852. (<any>instance).arc = arc;
  853. (<any>instance).radius = radius;
  854. return instance;
  855. }
  856. // tube creation
  857. path3D = <any>new Path3D(path);
  858. var newPathArray = new Array<Array<Vector3>>();
  859. cap = (cap < 0 || cap > 3) ? 0 : cap;
  860. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  861. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  862. (<any>tube).pathArray = pathArray;
  863. (<any>tube).path3D = path3D;
  864. (<any>tube).tessellation = tessellation;
  865. (<any>tube).cap = cap;
  866. (<any>tube).arc = options.arc;
  867. (<any>tube).radius = radius;
  868. return tube;
  869. }
  870. /**
  871. * Creates a polyhedron mesh.
  872. *
  873. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  874. * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial
  875. * to choose the wanted type.
  876. * The parameter `size` (positive float, default 1) sets the polygon size.
  877. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  878. * You can build other polyhedron types than the 15 embbeded ones by setting the parameter `custom` (`polyhedronObject`, default null). If you set the parameter `custom`, this overwrittes the parameter `type`.
  879. * A `polyhedronObject` is a formatted javascript object. You'll find a full file with pre-set polyhedra here : https://github.com/BabylonJS/Extensions/tree/master/Polyhedron
  880. * You can set the color and the UV of each side of the polyhedron with the parameters `faceColors` (Color4, default `(1, 1, 1, 1)`) and faceUV (Vector4, default `(0, 0, 1, 1)`).
  881. * To understand how to set `faceUV` or `faceColors`, please read this by considering the right number of faces of your polyhedron, instead of only 6 for the box : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  882. * The parameter `flat` (boolean, default true). If set to false, it gives the polyhedron a single global face, so less vertices and shared normals. In this case, `faceColors` and `faceUV` are ignored.
  883. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  884. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  885. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  886. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  887. */
  888. public static CreatePolyhedron(name: string, options: { type?: number, size?: number, sizeX?: number, sizeY?: number, sizeZ?: number, custom?: any, faceUV?: Vector4[], faceColors?: Color4[], flat?: boolean, updatable?: boolean, sideOrientation?: number, frontUVs?: Vector4, backUVs?: Vector4 }, scene: Scene): Mesh {
  889. var polyhedron = new Mesh(name, scene);
  890. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  891. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  892. var vertexData = VertexData.CreatePolyhedron(options);
  893. vertexData.applyToMesh(polyhedron, options.updatable);
  894. return polyhedron;
  895. }
  896. /**
  897. * Creates a decal mesh.
  898. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  899. * A decal is a mesh usually applied as a model onto the surface of another mesh. So don't forget the parameter `sourceMesh` depicting the decal.
  900. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  901. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  902. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  903. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  904. */
  905. public static CreateDecal(name: string, sourceMesh: AbstractMesh, options: { position?: Vector3, normal?: Vector3, size?: Vector3, angle?: number }): Mesh {
  906. var indices = sourceMesh.getIndices();
  907. var positions = sourceMesh.getVerticesData(VertexBuffer.PositionKind);
  908. var normals = sourceMesh.getVerticesData(VertexBuffer.NormalKind);
  909. var position = options.position || Vector3.Zero();
  910. var normal = options.normal || Vector3.Up();
  911. var size = options.size || Vector3.One();
  912. var angle = options.angle || 0;
  913. // Getting correct rotation
  914. if (!normal) {
  915. var target = new Vector3(0, 0, 1);
  916. var camera = sourceMesh.getScene().activeCamera;
  917. var cameraWorldTarget = Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  918. normal = camera.globalPosition.subtract(cameraWorldTarget);
  919. }
  920. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  921. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  922. var pitch = Math.atan2(normal.y, len);
  923. // Matrix
  924. var decalWorldMatrix = Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(Matrix.Translation(position.x, position.y, position.z));
  925. var inverseDecalWorldMatrix = Matrix.Invert(decalWorldMatrix);
  926. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  927. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  928. var vertexData = new VertexData();
  929. vertexData.indices = [];
  930. vertexData.positions = [];
  931. vertexData.normals = [];
  932. vertexData.uvs = [];
  933. var currentVertexDataIndex = 0;
  934. var extractDecalVector3 = (indexId: number): PositionNormalVertex => {
  935. var vertexId = indices[indexId];
  936. var result = new PositionNormalVertex();
  937. result.position = new Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  938. // Send vector to decal local world
  939. result.position = Vector3.TransformCoordinates(result.position, transformMatrix);
  940. // Get normal
  941. result.normal = new Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  942. result.normal = Vector3.TransformNormal(result.normal, transformMatrix);
  943. return result;
  944. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  945. var clip = (vertices: PositionNormalVertex[], axis: Vector3): PositionNormalVertex[]=> {
  946. if (vertices.length === 0) {
  947. return vertices;
  948. }
  949. var clipSize = 0.5 * Math.abs(Vector3.Dot(size, axis));
  950. var clipVertices = (v0: PositionNormalVertex, v1: PositionNormalVertex): PositionNormalVertex => {
  951. var clipFactor = Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  952. return new PositionNormalVertex(
  953. Vector3.Lerp(v0.position, v1.position, clipFactor),
  954. Vector3.Lerp(v0.normal, v1.normal, clipFactor)
  955. );
  956. };
  957. var result = new Array<PositionNormalVertex>();
  958. for (var index = 0; index < vertices.length; index += 3) {
  959. var v1Out: boolean;
  960. var v2Out: boolean;
  961. var v3Out: boolean;
  962. var total = 0;
  963. var nV1: PositionNormalVertex, nV2: PositionNormalVertex, nV3: PositionNormalVertex, nV4: PositionNormalVertex;
  964. var d1 = Vector3.Dot(vertices[index].position, axis) - clipSize;
  965. var d2 = Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  966. var d3 = Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  967. v1Out = d1 > 0;
  968. v2Out = d2 > 0;
  969. v3Out = d3 > 0;
  970. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  971. switch (total) {
  972. case 0:
  973. result.push(vertices[index]);
  974. result.push(vertices[index + 1]);
  975. result.push(vertices[index + 2]);
  976. break;
  977. case 1:
  978. if (v1Out) {
  979. nV1 = vertices[index + 1];
  980. nV2 = vertices[index + 2];
  981. nV3 = clipVertices(vertices[index], nV1);
  982. nV4 = clipVertices(vertices[index], nV2);
  983. }
  984. if (v2Out) {
  985. nV1 = vertices[index];
  986. nV2 = vertices[index + 2];
  987. nV3 = clipVertices(vertices[index + 1], nV1);
  988. nV4 = clipVertices(vertices[index + 1], nV2);
  989. result.push(nV3);
  990. result.push(nV2.clone());
  991. result.push(nV1.clone());
  992. result.push(nV2.clone());
  993. result.push(nV3.clone());
  994. result.push(nV4);
  995. break;
  996. }
  997. if (v3Out) {
  998. nV1 = vertices[index];
  999. nV2 = vertices[index + 1];
  1000. nV3 = clipVertices(vertices[index + 2], nV1);
  1001. nV4 = clipVertices(vertices[index + 2], nV2);
  1002. }
  1003. result.push(nV1.clone());
  1004. result.push(nV2.clone());
  1005. result.push(nV3);
  1006. result.push(nV4);
  1007. result.push(nV3.clone());
  1008. result.push(nV2.clone());
  1009. break;
  1010. case 2:
  1011. if (!v1Out) {
  1012. nV1 = vertices[index].clone();
  1013. nV2 = clipVertices(nV1, vertices[index + 1]);
  1014. nV3 = clipVertices(nV1, vertices[index + 2]);
  1015. result.push(nV1);
  1016. result.push(nV2);
  1017. result.push(nV3);
  1018. }
  1019. if (!v2Out) {
  1020. nV1 = vertices[index + 1].clone();
  1021. nV2 = clipVertices(nV1, vertices[index + 2]);
  1022. nV3 = clipVertices(nV1, vertices[index]);
  1023. result.push(nV1);
  1024. result.push(nV2);
  1025. result.push(nV3);
  1026. }
  1027. if (!v3Out) {
  1028. nV1 = vertices[index + 2].clone();
  1029. nV2 = clipVertices(nV1, vertices[index]);
  1030. nV3 = clipVertices(nV1, vertices[index + 1]);
  1031. result.push(nV1);
  1032. result.push(nV2);
  1033. result.push(nV3);
  1034. }
  1035. break;
  1036. case 3:
  1037. break;
  1038. }
  1039. }
  1040. return result;
  1041. };
  1042. for (var index = 0; index < indices.length; index += 3) {
  1043. var faceVertices = new Array<PositionNormalVertex>();
  1044. faceVertices.push(extractDecalVector3(index));
  1045. faceVertices.push(extractDecalVector3(index + 1));
  1046. faceVertices.push(extractDecalVector3(index + 2));
  1047. // Clip
  1048. faceVertices = clip(faceVertices, new Vector3(1, 0, 0));
  1049. faceVertices = clip(faceVertices, new Vector3(-1, 0, 0));
  1050. faceVertices = clip(faceVertices, new Vector3(0, 1, 0));
  1051. faceVertices = clip(faceVertices, new Vector3(0, -1, 0));
  1052. faceVertices = clip(faceVertices, new Vector3(0, 0, 1));
  1053. faceVertices = clip(faceVertices, new Vector3(0, 0, -1));
  1054. if (faceVertices.length === 0) {
  1055. continue;
  1056. }
  1057. // Add UVs and get back to world
  1058. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  1059. var vertex = faceVertices[vIndex];
  1060. //TODO check for Int32Array | Uint32Array | Uint16Array
  1061. (<number[]>vertexData.indices).push(currentVertexDataIndex);
  1062. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  1063. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  1064. (<number[]>vertexData.uvs).push(0.5 + vertex.position.x / size.x);
  1065. (<number[]>vertexData.uvs).push(0.5 + vertex.position.y / size.y);
  1066. currentVertexDataIndex++;
  1067. }
  1068. }
  1069. // Return mesh
  1070. var decal = new Mesh(name, sourceMesh.getScene());
  1071. vertexData.applyToMesh(decal);
  1072. decal.position = position.clone();
  1073. decal.rotation = new Vector3(pitch, yaw, angle);
  1074. return decal;
  1075. }
  1076. // Privates
  1077. private static _ExtrudeShapeGeneric(name: string, shape: Vector3[], curve: Vector3[], scale: number, rotation: number, scaleFunction: { (i: number, distance: number): number; }, rotateFunction: { (i: number, distance: number): number; }, rbCA: boolean, rbCP: boolean, cap: number, custom: boolean, scene: Scene, updtbl: boolean, side: number, instance: Mesh, invertUV: boolean, frontUVs: Vector4, backUVs: Vector4): Mesh {
  1078. // extrusion geometry
  1079. var extrusionPathArray = (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) => {
  1080. var tangents = path3D.getTangents();
  1081. var normals = path3D.getNormals();
  1082. var binormals = path3D.getBinormals();
  1083. var distances = path3D.getDistances();
  1084. var angle = 0;
  1085. var returnScale: { (i: number, distance: number): number; } = () => { return scale; };
  1086. var returnRotation: { (i: number, distance: number): number; } = () => { return rotation; };
  1087. var rotate: { (i: number, distance: number): number; } = custom ? rotateFunction : returnRotation;
  1088. var scl: { (i: number, distance: number): number; } = custom ? scaleFunction : returnScale;
  1089. var index = (cap === Mesh.NO_CAP || cap === Mesh.CAP_END) ? 0 : 2;
  1090. var rotationMatrix: Matrix = Tmp.Matrix[0];
  1091. for (var i = 0; i < curve.length; i++) {
  1092. var shapePath = new Array<Vector3>();
  1093. var angleStep = rotate(i, distances[i]);
  1094. var scaleRatio = scl(i, distances[i]);
  1095. for (var p = 0; p < shape.length; p++) {
  1096. Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  1097. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  1098. var rotated = shapePath[p] ? shapePath[p] : Vector3.Zero();
  1099. Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  1100. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  1101. shapePath[p] = rotated;
  1102. }
  1103. shapePaths[index] = shapePath;
  1104. angle += angleStep;
  1105. index++;
  1106. }
  1107. // cap
  1108. var capPath = shapePath => {
  1109. var pointCap = Array<Vector3>();
  1110. var barycenter = Vector3.Zero();
  1111. var i: number;
  1112. for (i = 0; i < shapePath.length; i++) {
  1113. barycenter.addInPlace(shapePath[i]);
  1114. }
  1115. barycenter.scaleInPlace(1.0 / shapePath.length);
  1116. for (i = 0; i < shapePath.length; i++) {
  1117. pointCap.push(barycenter);
  1118. }
  1119. return pointCap;
  1120. };
  1121. switch (cap) {
  1122. case Mesh.NO_CAP:
  1123. break;
  1124. case Mesh.CAP_START:
  1125. shapePaths[0] = capPath(shapePaths[2]);
  1126. shapePaths[1] = shapePaths[2];
  1127. break;
  1128. case Mesh.CAP_END:
  1129. shapePaths[index] = shapePaths[index - 1];
  1130. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  1131. break;
  1132. case Mesh.CAP_ALL:
  1133. shapePaths[0] = capPath(shapePaths[2]);
  1134. shapePaths[1] = shapePaths[2];
  1135. shapePaths[index] = shapePaths[index - 1];
  1136. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  1137. break;
  1138. default:
  1139. break;
  1140. }
  1141. return shapePaths;
  1142. };
  1143. var path3D;
  1144. var pathArray;
  1145. if (instance) { // instance update
  1146. path3D = ((<any>instance).path3D).update(curve);
  1147. pathArray = extrusionPathArray(shape, curve, (<any>instance).path3D, (<any>instance).pathArray, scale, rotation, scaleFunction, rotateFunction, (<any>instance).cap, custom);
  1148. instance = Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  1149. return instance;
  1150. }
  1151. // extruded shape creation
  1152. path3D = <any>new Path3D(curve);
  1153. var newShapePaths = new Array<Array<Vector3>>();
  1154. cap = (cap < 0 || cap > 3) ? 0 : cap;
  1155. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  1156. var extrudedGeneric = MeshBuilder.CreateRibbon(name, {pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs, backUVs: backUVs}, scene);
  1157. (<any>extrudedGeneric).pathArray = pathArray;
  1158. (<any>extrudedGeneric).path3D = path3D;
  1159. (<any>extrudedGeneric).cap = cap;
  1160. return extrudedGeneric;
  1161. }
  1162. }
  1163. }