csg.ts 29 KB

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