babylon.meshBuilder.ts 95 KB

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