csg.ts 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786
  1. module BABYLON {
  2. /**
  3. * Unique ID when we import meshes from Babylon to CSG
  4. */
  5. var currentCSGMeshId = 0;
  6. /**
  7. * Represents a vertex of a polygon. Use your own vertex class instead of this
  8. * one to provide additional features like texture coordinates and vertex
  9. * colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  10. * `flip()`, and `interpolate()` methods that behave analogous to the ones
  11. * defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  12. * functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  13. * is not used anywhere else.
  14. * Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  15. */
  16. class Vertex {
  17. /**
  18. * Initializes the vertex
  19. * @param pos The position of the vertex
  20. * @param normal The normal of the vertex
  21. * @param uv The texture coordinate of the vertex
  22. */
  23. constructor(
  24. /**
  25. * The position of the vertex
  26. */
  27. public pos: Vector3,
  28. /**
  29. * The normal of the vertex
  30. */
  31. public normal: Vector3,
  32. /**
  33. * The texture coordinate of the vertex
  34. */
  35. public uv: Vector2) {
  36. }
  37. /**
  38. * Make a clone, or deep copy, of the vertex
  39. * @returns A new Vertex
  40. */
  41. public clone(): Vertex {
  42. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  43. }
  44. /**
  45. * Invert all orientation-specific data (e.g. vertex normal). Called when the
  46. * orientation of a polygon is flipped.
  47. */
  48. public flip(): void {
  49. this.normal = this.normal.scale(-1);
  50. }
  51. /**
  52. * Create a new vertex between this vertex and `other` by linearly
  53. * interpolating all properties using a parameter of `t`. Subclasses should
  54. * override this to interpolate additional properties.
  55. * @param other the vertex to interpolate against
  56. * @param t The factor used to linearly interpolate between the vertices
  57. */
  58. public interpolate(other: Vertex, t: number): Vertex {
  59. return new Vertex(Vector3.Lerp(this.pos, other.pos, t),
  60. Vector3.Lerp(this.normal, other.normal, t),
  61. Vector2.Lerp(this.uv, other.uv, t)
  62. );
  63. }
  64. }
  65. /**
  66. * Represents a plane in 3D space.
  67. */
  68. class Plane {
  69. /**
  70. * Initializes the plane
  71. * @param normal The normal for the plane
  72. * @param w
  73. */
  74. constructor(public normal: Vector3, public w: number) {
  75. }
  76. /**
  77. * `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  78. * point is on the plane
  79. */
  80. static EPSILON = 1e-5;
  81. /**
  82. * Construct a plane from three points
  83. * @param a Point a
  84. * @param b Point b
  85. * @param c Point c
  86. */
  87. public static FromPoints(a: Vector3, b: Vector3, c: Vector3): Nullable<Plane> {
  88. var v0 = c.subtract(a);
  89. var v1 = b.subtract(a);
  90. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  91. return null;
  92. }
  93. var n = Vector3.Normalize(Vector3.Cross(v0, v1));
  94. return new Plane(n, Vector3.Dot(n, a));
  95. }
  96. /**
  97. * Clone, or make a deep copy of the plane
  98. * @returns a new Plane
  99. */
  100. public clone(): Plane {
  101. return new Plane(this.normal.clone(), this.w);
  102. }
  103. /**
  104. * Flip the face of the plane
  105. */
  106. public flip() {
  107. this.normal.scaleInPlace(-1);
  108. this.w = -this.w;
  109. }
  110. /**
  111. * Split `polygon` by this plane if needed, then put the polygon or polygon
  112. * fragments in the appropriate lists. Coplanar polygons go into either
  113. `* coplanarFront` or `coplanarBack` depending on their orientation with
  114. * respect to this plane. Polygons in front or in back of this plane go into
  115. * either `front` or `back`
  116. * @param polygon The polygon to be split
  117. * @param coplanarFront Will contain polygons coplanar with the plane that are oriented to the front of the plane
  118. * @param coplanarBack Will contain polygons coplanar with the plane that are oriented to the back of the plane
  119. * @param front Will contain the polygons in front of the plane
  120. * @param back Will contain the polygons begind the plane
  121. */
  122. public splitPolygon(polygon: Polygon, coplanarFront: Polygon[], coplanarBack: Polygon[], front: Polygon[], back: Polygon[]): void {
  123. var COPLANAR = 0;
  124. var FRONT = 1;
  125. var BACK = 2;
  126. var SPANNING = 3;
  127. // Classify each point as well as the entire polygon into one of the above
  128. // four classes.
  129. var polygonType = 0;
  130. var types = [];
  131. var i: number;
  132. var t: number;
  133. for (i = 0; i < polygon.vertices.length; i++) {
  134. t = Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  135. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  136. polygonType |= type;
  137. types.push(type);
  138. }
  139. // Put the polygon in the correct list, splitting it when necessary
  140. switch (polygonType) {
  141. case COPLANAR:
  142. (Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  143. break;
  144. case FRONT:
  145. front.push(polygon);
  146. break;
  147. case BACK:
  148. back.push(polygon);
  149. break;
  150. case SPANNING:
  151. var f = [], b = [];
  152. for (i = 0; i < polygon.vertices.length; i++) {
  153. var j = (i + 1) % polygon.vertices.length;
  154. var ti = types[i], tj = types[j];
  155. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  156. if (ti !== BACK) { f.push(vi); }
  157. if (ti !== FRONT) { b.push(ti !== BACK ? vi.clone() : vi); }
  158. if ((ti | tj) === SPANNING) {
  159. t = (this.w - Vector3.Dot(this.normal, vi.pos)) / Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  160. var v = vi.interpolate(vj, t);
  161. f.push(v);
  162. b.push(v.clone());
  163. }
  164. }
  165. var poly: Polygon;
  166. if (f.length >= 3) {
  167. poly = new Polygon(f, polygon.shared);
  168. if (poly.plane) {
  169. front.push(poly);
  170. }
  171. }
  172. if (b.length >= 3) {
  173. poly = new Polygon(b, polygon.shared);
  174. if (poly.plane) {
  175. back.push(poly);
  176. }
  177. }
  178. break;
  179. }
  180. }
  181. }
  182. /**
  183. * Represents a convex polygon. The vertices used to initialize a polygon must
  184. * be coplanar and form a convex loop.
  185. *
  186. * Each convex polygon has a `shared` property, which is shared between all
  187. * polygons that are clones of each other or were split from the same polygon.
  188. * This can be used to define per-polygon properties (such as surface color)
  189. */
  190. class Polygon {
  191. /**
  192. * Vertices of the polygon
  193. */
  194. public vertices: Vertex[];
  195. /**
  196. * Properties that are shared across all polygons
  197. */
  198. public shared: any;
  199. /**
  200. * A plane formed from the vertices of the polygon
  201. */
  202. public plane: Plane;
  203. /**
  204. * Initializes the polygon
  205. * @param vertices The vertices of the polygon
  206. * @param shared The properties shared across all polygons
  207. */
  208. constructor(vertices: Vertex[], shared: any) {
  209. this.vertices = vertices;
  210. this.shared = shared;
  211. this.plane = <Plane>Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  212. }
  213. /**
  214. * Clones, or makes a deep copy, or the polygon
  215. */
  216. public clone(): Polygon {
  217. var vertices = this.vertices.map((v) => v.clone());
  218. return new Polygon(vertices, this.shared);
  219. }
  220. /**
  221. * Flips the faces of the polygon
  222. */
  223. public flip() {
  224. this.vertices.reverse().map((v) => { v.flip(); });
  225. this.plane.flip();
  226. }
  227. }
  228. /**
  229. * Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  230. * by picking a polygon to split along. That polygon (and all other coplanar
  231. * polygons) are added directly to that node and the other polygons are added to
  232. * the front and/or back subtrees. This is not a leafy BSP tree since there is
  233. * no distinction between internal and leaf nodes
  234. */
  235. class Node {
  236. private plane: Nullable<Plane> = null;
  237. private front: Nullable<Node> = null;
  238. private back: Nullable<Node> = null;
  239. private polygons = new Array<Polygon>();
  240. /**
  241. * Initializes the node
  242. * @param polygons A collection of polygons held in the node
  243. */
  244. constructor(polygons?: Array<Polygon>) {
  245. if (polygons) {
  246. this.build(polygons);
  247. }
  248. }
  249. /**
  250. * Clones, or makes a deep copy, of the node
  251. * @returns The cloned node
  252. */
  253. public clone(): Node {
  254. var node = new Node();
  255. node.plane = this.plane && this.plane.clone();
  256. node.front = this.front && this.front.clone();
  257. node.back = this.back && this.back.clone();
  258. node.polygons = this.polygons.map((p) => p.clone());
  259. return node;
  260. }
  261. /**
  262. * Convert solid space to empty space and empty space to solid space
  263. */
  264. public invert(): void {
  265. for (var i = 0; i < this.polygons.length; i++) {
  266. this.polygons[i].flip();
  267. }
  268. if (this.plane) {
  269. this.plane.flip();
  270. }
  271. if (this.front) {
  272. this.front.invert();
  273. }
  274. if (this.back) {
  275. this.back.invert();
  276. }
  277. var temp = this.front;
  278. this.front = this.back;
  279. this.back = temp;
  280. }
  281. /**
  282. * Recursively remove all polygons in `polygons` that are inside this BSP
  283. * tree.
  284. * @param polygons Polygons to remove from the BSP
  285. * @returns Polygons clipped from the BSP
  286. */
  287. clipPolygons(polygons: Polygon[]): Polygon[] {
  288. if (!this.plane) { return polygons.slice(); }
  289. var front = new Array<Polygon>(), back = new Array<Polygon>();
  290. for (var i = 0; i < polygons.length; i++) {
  291. this.plane.splitPolygon(polygons[i], front, back, front, back);
  292. }
  293. if (this.front) {
  294. front = this.front.clipPolygons(front);
  295. }
  296. if (this.back) {
  297. back = this.back.clipPolygons(back);
  298. } else {
  299. back = [];
  300. }
  301. return front.concat(back);
  302. }
  303. /**
  304. * Remove all polygons in this BSP tree that are inside the other BSP tree
  305. * `bsp`.
  306. * @param bsp BSP containing polygons to remove from this BSP
  307. */
  308. clipTo(bsp: Node): void {
  309. this.polygons = bsp.clipPolygons(this.polygons);
  310. if (this.front) { this.front.clipTo(bsp); }
  311. if (this.back) { this.back.clipTo(bsp); }
  312. }
  313. /**
  314. * Return a list of all polygons in this BSP tree
  315. * @returns List of all polygons in this BSP tree
  316. */
  317. allPolygons(): Polygon[] {
  318. var polygons = this.polygons.slice();
  319. if (this.front) { polygons = polygons.concat(this.front.allPolygons()); }
  320. if (this.back) { polygons = polygons.concat(this.back.allPolygons()); }
  321. return polygons;
  322. }
  323. /**
  324. * Build a BSP tree out of `polygons`. When called on an existing tree, the
  325. * new polygons are filtered down to the bottom of the tree and become new
  326. * nodes there. Each set of polygons is partitioned using the first polygon
  327. * (no heuristic is used to pick a good split)
  328. * @param polygons Polygons used to construct the BSP tree
  329. */
  330. build(polygons: Polygon[]): void {
  331. if (!polygons.length) { return; }
  332. if (!this.plane) { this.plane = polygons[0].plane.clone(); }
  333. var front = new Array<Polygon>(), back = new Array<Polygon>();
  334. for (var i = 0; i < polygons.length; i++) {
  335. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  336. }
  337. if (front.length) {
  338. if (!this.front) { this.front = new Node(); }
  339. this.front.build(front);
  340. }
  341. if (back.length) {
  342. if (!this.back) { this.back = new Node(); }
  343. this.back.build(back);
  344. }
  345. }
  346. }
  347. /**
  348. * Class for building Constructive Solid Geometry
  349. */
  350. export class CSG {
  351. private polygons = new Array<Polygon>();
  352. /**
  353. * The world matrix
  354. */
  355. public matrix: Matrix;
  356. /**
  357. * Stores the position
  358. */
  359. public position: Vector3;
  360. /**
  361. * Stores the rotation
  362. */
  363. public rotation: Vector3;
  364. /**
  365. * Stores the rotation quaternion
  366. */
  367. public rotationQuaternion: Nullable<Quaternion>;
  368. /**
  369. * Stores the scaling vector
  370. */
  371. public scaling: Vector3;
  372. /**
  373. * Convert the BABYLON.Mesh to BABYLON.CSG
  374. * @param mesh The BABYLON.Mesh to convert to BABYLON.CSG
  375. * @returns A new BABYLON.CSG from the BABYLON.Mesh
  376. */
  377. public static FromMesh(mesh: Mesh): CSG {
  378. var vertex: Vertex, normal: Vector3, uv: Vector2, position: Vector3,
  379. polygon: Polygon,
  380. polygons = new Array<Polygon>(),
  381. vertices;
  382. var matrix: Matrix,
  383. meshPosition: Vector3,
  384. meshRotation: Vector3,
  385. meshRotationQuaternion: Nullable<Quaternion> = null,
  386. meshScaling: Vector3;
  387. if (mesh instanceof Mesh) {
  388. mesh.computeWorldMatrix(true);
  389. matrix = mesh.getWorldMatrix();
  390. meshPosition = mesh.position.clone();
  391. meshRotation = mesh.rotation.clone();
  392. if (mesh.rotationQuaternion) {
  393. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  394. }
  395. meshScaling = mesh.scaling.clone();
  396. } else {
  397. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  398. }
  399. var indices = <IndicesArray>mesh.getIndices(),
  400. positions = <FloatArray>mesh.getVerticesData(VertexBuffer.PositionKind),
  401. normals = <FloatArray>mesh.getVerticesData(VertexBuffer.NormalKind),
  402. uvs = <FloatArray>mesh.getVerticesData(VertexBuffer.UVKind);
  403. var subMeshes = mesh.subMeshes;
  404. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  405. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  406. vertices = [];
  407. for (var j = 0; j < 3; j++) {
  408. var sourceNormal = new Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  409. uv = new Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  410. var sourcePosition = new Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  411. position = Vector3.TransformCoordinates(sourcePosition, matrix);
  412. normal = Vector3.TransformNormal(sourceNormal, matrix);
  413. vertex = new Vertex(position, normal, uv);
  414. vertices.push(vertex);
  415. }
  416. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  417. // To handle the case of degenerated triangle
  418. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  419. if (polygon.plane) {
  420. polygons.push(polygon);
  421. }
  422. }
  423. }
  424. var csg = CSG.FromPolygons(polygons);
  425. csg.matrix = matrix;
  426. csg.position = meshPosition;
  427. csg.rotation = meshRotation;
  428. csg.scaling = meshScaling;
  429. csg.rotationQuaternion = meshRotationQuaternion;
  430. currentCSGMeshId++;
  431. return csg;
  432. }
  433. /**
  434. * Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  435. * @param polygons Polygons used to construct a BABYLON.CSG solid
  436. */
  437. private static FromPolygons(polygons: Polygon[]): CSG {
  438. var csg = new CSG();
  439. csg.polygons = polygons;
  440. return csg;
  441. }
  442. /**
  443. * Clones, or makes a deep copy, of the BABYLON.CSG
  444. * @returns A new BABYLON.CSG
  445. */
  446. public clone(): CSG {
  447. var csg = new CSG();
  448. csg.polygons = this.polygons.map((p) => p.clone());
  449. csg.copyTransformAttributes(this);
  450. return csg;
  451. }
  452. /**
  453. * Unions this CSG with another CSG
  454. * @param csg The CSG to union against this CSG
  455. * @returns The unioned CSG
  456. */
  457. public union(csg: CSG): CSG {
  458. var a = new Node(this.clone().polygons);
  459. var b = new Node(csg.clone().polygons);
  460. a.clipTo(b);
  461. b.clipTo(a);
  462. b.invert();
  463. b.clipTo(a);
  464. b.invert();
  465. a.build(b.allPolygons());
  466. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  467. }
  468. /**
  469. * Unions this CSG with another CSG in place
  470. * @param csg The CSG to union against this CSG
  471. */
  472. public unionInPlace(csg: CSG): void {
  473. var a = new Node(this.polygons);
  474. var b = new Node(csg.polygons);
  475. a.clipTo(b);
  476. b.clipTo(a);
  477. b.invert();
  478. b.clipTo(a);
  479. b.invert();
  480. a.build(b.allPolygons());
  481. this.polygons = a.allPolygons();
  482. }
  483. /**
  484. * Subtracts this CSG with another CSG
  485. * @param csg The CSG to subtract against this CSG
  486. * @returns A new BABYLON.CSG
  487. */
  488. public subtract(csg: CSG): CSG {
  489. var a = new Node(this.clone().polygons);
  490. var b = new Node(csg.clone().polygons);
  491. a.invert();
  492. a.clipTo(b);
  493. b.clipTo(a);
  494. b.invert();
  495. b.clipTo(a);
  496. b.invert();
  497. a.build(b.allPolygons());
  498. a.invert();
  499. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  500. }
  501. /**
  502. * Subtracts this CSG with another CSG in place
  503. * @param csg The CSG to subtact against this CSG
  504. */
  505. public subtractInPlace(csg: CSG): void {
  506. var a = new Node(this.polygons);
  507. var b = new Node(csg.polygons);
  508. a.invert();
  509. a.clipTo(b);
  510. b.clipTo(a);
  511. b.invert();
  512. b.clipTo(a);
  513. b.invert();
  514. a.build(b.allPolygons());
  515. a.invert();
  516. this.polygons = a.allPolygons();
  517. }
  518. /**
  519. * Intersect this CSG with another CSG
  520. * @param csg The CSG to intersect against this CSG
  521. * @returns A new BABYLON.CSG
  522. */
  523. public intersect(csg: CSG): CSG {
  524. var a = new Node(this.clone().polygons);
  525. var b = new Node(csg.clone().polygons);
  526. a.invert();
  527. b.clipTo(a);
  528. b.invert();
  529. a.clipTo(b);
  530. b.clipTo(a);
  531. a.build(b.allPolygons());
  532. a.invert();
  533. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  534. }
  535. /**
  536. * Intersects this CSG with another CSG in place
  537. * @param csg The CSG to intersect against this CSG
  538. */
  539. public intersectInPlace(csg: CSG): void {
  540. var a = new Node(this.polygons);
  541. var b = new Node(csg.polygons);
  542. a.invert();
  543. b.clipTo(a);
  544. b.invert();
  545. a.clipTo(b);
  546. b.clipTo(a);
  547. a.build(b.allPolygons());
  548. a.invert();
  549. this.polygons = a.allPolygons();
  550. }
  551. /**
  552. * Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  553. * not modified.
  554. * @returns A new BABYLON.CSG solid with solid and empty space switched
  555. */
  556. public inverse(): CSG {
  557. var csg = this.clone();
  558. csg.inverseInPlace();
  559. return csg;
  560. }
  561. /**
  562. * Inverses the BABYLON.CSG in place
  563. */
  564. public inverseInPlace(): void {
  565. this.polygons.map((p) => { p.flip(); });
  566. }
  567. /**
  568. * This is used to keep meshes transformations so they can be restored
  569. * when we build back a Babylon Mesh
  570. * NB : All CSG operations are performed in world coordinates
  571. * @param csg The BABYLON.CSG to copy the transform attributes from
  572. * @returns This BABYLON.CSG
  573. */
  574. public copyTransformAttributes(csg: CSG): CSG {
  575. this.matrix = csg.matrix;
  576. this.position = csg.position;
  577. this.rotation = csg.rotation;
  578. this.scaling = csg.scaling;
  579. this.rotationQuaternion = csg.rotationQuaternion;
  580. return this;
  581. }
  582. /**
  583. * Build Raw mesh from CSG
  584. * Coordinates here are in world space
  585. * @param name The name of the mesh geometry
  586. * @param scene The BABYLON.Scene
  587. * @param keepSubMeshes Specifies if the submeshes should be kept
  588. * @returns A new BABYLON.Mesh
  589. */
  590. public buildMeshGeometry(name: string, scene: Scene, keepSubMeshes: boolean): Mesh {
  591. var matrix = this.matrix.clone();
  592. matrix.invert();
  593. var mesh = new Mesh(name, scene),
  594. vertices = [],
  595. indices = [],
  596. normals = [],
  597. uvs = [],
  598. vertex = Vector3.Zero(),
  599. normal = Vector3.Zero(),
  600. uv = Vector2.Zero(),
  601. polygons = this.polygons,
  602. polygonIndices = [0, 0, 0], polygon,
  603. vertice_dict = {},
  604. vertex_idx,
  605. currentIndex = 0,
  606. subMesh_dict = {},
  607. subMesh_obj;
  608. if (keepSubMeshes) {
  609. // Sort Polygons, since subMeshes are indices range
  610. polygons.sort((a, b) => {
  611. if (a.shared.meshId === b.shared.meshId) {
  612. return a.shared.subMeshId - b.shared.subMeshId;
  613. } else {
  614. return a.shared.meshId - b.shared.meshId;
  615. }
  616. });
  617. }
  618. for (var i = 0, il = polygons.length; i < il; i++) {
  619. polygon = polygons[i];
  620. // Building SubMeshes
  621. if (!(<any>subMesh_dict)[polygon.shared.meshId]) {
  622. (<any>subMesh_dict)[polygon.shared.meshId] = {};
  623. }
  624. if (!(<any>subMesh_dict)[polygon.shared.meshId][polygon.shared.subMeshId]) {
  625. (<any>subMesh_dict)[polygon.shared.meshId][polygon.shared.subMeshId] = {
  626. indexStart: +Infinity,
  627. indexEnd: -Infinity,
  628. materialIndex: polygon.shared.materialIndex
  629. };
  630. }
  631. subMesh_obj = (<any>subMesh_dict)[polygon.shared.meshId][polygon.shared.subMeshId];
  632. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  633. polygonIndices[0] = 0;
  634. polygonIndices[1] = j - 1;
  635. polygonIndices[2] = j;
  636. for (var k = 0; k < 3; k++) {
  637. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  638. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  639. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  640. var localVertex = Vector3.TransformCoordinates(vertex, matrix);
  641. var localNormal = Vector3.TransformNormal(normal, matrix);
  642. vertex_idx = (<any>vertice_dict)[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  643. // Check if 2 points can be merged
  644. if (!(typeof vertex_idx !== 'undefined' &&
  645. normals[vertex_idx * 3] === localNormal.x &&
  646. normals[vertex_idx * 3 + 1] === localNormal.y &&
  647. normals[vertex_idx * 3 + 2] === localNormal.z &&
  648. uvs[vertex_idx * 2] === uv.x &&
  649. uvs[vertex_idx * 2 + 1] === uv.y)) {
  650. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  651. uvs.push(uv.x, uv.y);
  652. normals.push(normal.x, normal.y, normal.z);
  653. vertex_idx = (<any>vertice_dict)[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  654. }
  655. indices.push(vertex_idx);
  656. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  657. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  658. currentIndex++;
  659. }
  660. }
  661. }
  662. mesh.setVerticesData(VertexBuffer.PositionKind, vertices);
  663. mesh.setVerticesData(VertexBuffer.NormalKind, normals);
  664. mesh.setVerticesData(VertexBuffer.UVKind, uvs);
  665. mesh.setIndices(indices, null);
  666. if (keepSubMeshes) {
  667. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  668. var materialIndexOffset = 0,
  669. materialMaxIndex;
  670. mesh.subMeshes = new Array<SubMesh>();
  671. for (var m in subMesh_dict) {
  672. materialMaxIndex = -1;
  673. for (var sm in (<any>subMesh_dict)[m]) {
  674. subMesh_obj = (<any>subMesh_dict)[m][sm];
  675. SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, <AbstractMesh>mesh);
  676. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  677. }
  678. materialIndexOffset += ++materialMaxIndex;
  679. }
  680. }
  681. return mesh;
  682. }
  683. /**
  684. * Build Mesh from CSG taking material and transforms into account
  685. * @param name The name of the BABYLON.Mesh
  686. * @param material The material of the BABYLON.Mesh
  687. * @param scene The BABYLON.Scene
  688. * @param keepSubMeshes Specifies if submeshes should be kept
  689. * @returns The new BABYLON.Mesh
  690. */
  691. public toMesh(name: string, material: Nullable<Material>, scene: Scene, keepSubMeshes: boolean): Mesh {
  692. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  693. mesh.material = material;
  694. mesh.position.copyFrom(this.position);
  695. mesh.rotation.copyFrom(this.rotation);
  696. if (this.rotationQuaternion) {
  697. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  698. }
  699. mesh.scaling.copyFrom(this.scaling);
  700. mesh.computeWorldMatrix(true);
  701. return mesh;
  702. }
  703. }
  704. }