babylon.csg.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  1. module BABYLON {
  2. // Unique ID when we import meshes from Babylon to CSG
  3. var currentCSGMeshId = 0;
  4. // # class Vertex
  5. // Represents a vertex of a polygon. Use your own vertex class instead of this
  6. // one to provide additional features like texture coordinates and vertex
  7. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  8. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  9. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  10. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  11. // is not used anywhere else.
  12. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  13. class Vertex {
  14. constructor(public pos: Vector3, public normal: Vector3, public uv: Vector2) {
  15. }
  16. public clone(): Vertex {
  17. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  18. }
  19. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  20. // orientation of a polygon is flipped.
  21. public flip(): void {
  22. this.normal = this.normal.scale(-1);
  23. }
  24. // Create a new vertex between this vertex and `other` by linearly
  25. // interpolating all properties using a parameter of `t`. Subclasses should
  26. // override this to interpolate additional properties.
  27. public interpolate(other: Vertex, t: number): Vertex {
  28. return new Vertex(Vector3.Lerp(this.pos, other.pos, t),
  29. Vector3.Lerp(this.normal, other.normal, t),
  30. Vector2.Lerp(this.uv, other.uv, t)
  31. );
  32. }
  33. }
  34. // # class Plane
  35. // Represents a plane in 3D space.
  36. class Plane {
  37. constructor(public normal: Vector3, public w: number) {
  38. }
  39. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  40. // point is on the plane.
  41. static EPSILON = 1e-5;
  42. public static FromPoints(a: Vector3, b: Vector3, c: Vector3): Nullable<Plane> {
  43. var v0 = c.subtract(a);
  44. var v1 = b.subtract(a);
  45. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  46. return null;
  47. }
  48. var n = Vector3.Normalize(Vector3.Cross(v0, v1));
  49. return new Plane(n, Vector3.Dot(n, a));
  50. }
  51. public clone(): Plane {
  52. return new Plane(this.normal.clone(), this.w);
  53. }
  54. public flip() {
  55. this.normal.scaleInPlace(-1);
  56. this.w = -this.w;
  57. }
  58. // Split `polygon` by this plane if needed, then put the polygon or polygon
  59. // fragments in the appropriate lists. Coplanar polygons go into either
  60. // `coplanarFront` or `coplanarBack` depending on their orientation with
  61. // respect to this plane. Polygons in front or in back of this plane go into
  62. // either `front` or `back`.
  63. public splitPolygon(polygon: Polygon, coplanarFront: Polygon[], coplanarBack: Polygon[], front: Polygon[], back: Polygon[]): void {
  64. var COPLANAR = 0;
  65. var FRONT = 1;
  66. var BACK = 2;
  67. var SPANNING = 3;
  68. // Classify each point as well as the entire polygon into one of the above
  69. // four classes.
  70. var polygonType = 0;
  71. var types = [];
  72. var i: number;
  73. var t: number;
  74. for (i = 0; i < polygon.vertices.length; i++) {
  75. t = Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  76. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  77. polygonType |= type;
  78. types.push(type);
  79. }
  80. // Put the polygon in the correct list, splitting it when necessary.
  81. switch (polygonType) {
  82. case COPLANAR:
  83. (Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  84. break;
  85. case FRONT:
  86. front.push(polygon);
  87. break;
  88. case BACK:
  89. back.push(polygon);
  90. break;
  91. case SPANNING:
  92. var f = [], b = [];
  93. for (i = 0; i < polygon.vertices.length; i++) {
  94. var j = (i + 1) % polygon.vertices.length;
  95. var ti = types[i], tj = types[j];
  96. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  97. if (ti !== BACK) f.push(vi);
  98. if (ti !== FRONT) b.push(ti !== BACK ? vi.clone() : vi);
  99. if ((ti | tj) === SPANNING) {
  100. t = (this.w - Vector3.Dot(this.normal, vi.pos)) / Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  101. var v = vi.interpolate(vj, t);
  102. f.push(v);
  103. b.push(v.clone());
  104. }
  105. }
  106. var poly: Polygon;
  107. if (f.length >= 3) {
  108. poly = new Polygon(f, polygon.shared);
  109. if (poly.plane)
  110. front.push(poly);
  111. }
  112. if (b.length >= 3) {
  113. poly = new Polygon(b, polygon.shared);
  114. if (poly.plane)
  115. back.push(poly);
  116. }
  117. break;
  118. }
  119. }
  120. }
  121. // # class Polygon
  122. // Represents a convex polygon. The vertices used to initialize a polygon must
  123. // be coplanar and form a convex loop.
  124. //
  125. // Each convex polygon has a `shared` property, which is shared between all
  126. // polygons that are clones of each other or were split from the same polygon.
  127. // This can be used to define per-polygon properties (such as surface color).
  128. class Polygon {
  129. public vertices: Vertex[];
  130. public shared: any;
  131. public plane: Plane;
  132. constructor(vertices: Vertex[], shared: any) {
  133. this.vertices = vertices;
  134. this.shared = shared;
  135. this.plane = <Plane>Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  136. }
  137. public clone(): Polygon {
  138. var vertices = this.vertices.map(v => v.clone());
  139. return new Polygon(vertices, this.shared);
  140. }
  141. public flip() {
  142. this.vertices.reverse().map(v => { v.flip(); });
  143. this.plane.flip();
  144. }
  145. }
  146. // # class Node
  147. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  148. // by picking a polygon to split along. That polygon (and all other coplanar
  149. // polygons) are added directly to that node and the other polygons are added to
  150. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  151. // no distinction between internal and leaf nodes.
  152. class Node {
  153. private plane: Nullable<Plane> = null;
  154. private front: Nullable<Node> = null;
  155. private back: Nullable<Node> = null;
  156. private polygons = new Array<Polygon>();
  157. constructor(polygons?: Array<Polygon>) {
  158. if (polygons) {
  159. this.build(polygons);
  160. }
  161. }
  162. public clone(): Node {
  163. var node = new Node();
  164. node.plane = this.plane && this.plane.clone();
  165. node.front = this.front && this.front.clone();
  166. node.back = this.back && this.back.clone();
  167. node.polygons = this.polygons.map(p => p.clone());
  168. return node;
  169. }
  170. // Convert solid space to empty space and empty space to solid space.
  171. public invert(): void {
  172. for (var i = 0; i < this.polygons.length; i++) {
  173. this.polygons[i].flip();
  174. }
  175. if (this.plane) {
  176. this.plane.flip();
  177. }
  178. if (this.front) {
  179. this.front.invert();
  180. }
  181. if (this.back) {
  182. this.back.invert();
  183. }
  184. var temp = this.front;
  185. this.front = this.back;
  186. this.back = temp;
  187. }
  188. // Recursively remove all polygons in `polygons` that are inside this BSP
  189. // tree.
  190. clipPolygons(polygons: Polygon[]): Polygon[] {
  191. if (!this.plane) return polygons.slice();
  192. var front = new Array<Polygon>(), back = new Array<Polygon>();
  193. for (var i = 0; i < polygons.length; i++) {
  194. this.plane.splitPolygon(polygons[i], front, back, front, back);
  195. }
  196. if (this.front) {
  197. front = this.front.clipPolygons(front);
  198. }
  199. if (this.back) {
  200. back = this.back.clipPolygons(back);
  201. } else {
  202. back = [];
  203. }
  204. return front.concat(back);
  205. }
  206. // Remove all polygons in this BSP tree that are inside the other BSP tree
  207. // `bsp`.
  208. clipTo(bsp: Node): void {
  209. this.polygons = bsp.clipPolygons(this.polygons);
  210. if (this.front) this.front.clipTo(bsp);
  211. if (this.back) this.back.clipTo(bsp);
  212. }
  213. // Return a list of all polygons in this BSP tree.
  214. allPolygons(): Polygon[] {
  215. var polygons = this.polygons.slice();
  216. if (this.front) polygons = polygons.concat(this.front.allPolygons());
  217. if (this.back) polygons = polygons.concat(this.back.allPolygons());
  218. return polygons;
  219. }
  220. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  221. // new polygons are filtered down to the bottom of the tree and become new
  222. // nodes there. Each set of polygons is partitioned using the first polygon
  223. // (no heuristic is used to pick a good split).
  224. build(polygons: Polygon[]): void {
  225. if (!polygons.length) return;
  226. if (!this.plane) this.plane = polygons[0].plane.clone();
  227. var front = new Array<Polygon>(), back = new Array<Polygon>();
  228. for (var i = 0; i < polygons.length; i++) {
  229. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  230. }
  231. if (front.length) {
  232. if (!this.front) this.front = new Node();
  233. this.front.build(front);
  234. }
  235. if (back.length) {
  236. if (!this.back) this.back = new Node();
  237. this.back.build(back);
  238. }
  239. }
  240. }
  241. export class CSG {
  242. private polygons = new Array<Polygon>();
  243. public matrix: Matrix;
  244. public position: Vector3;
  245. public rotation: Vector3;
  246. public rotationQuaternion: Nullable<Quaternion>;
  247. public scaling: Vector3;
  248. // Convert BABYLON.Mesh to BABYLON.CSG
  249. public static FromMesh(mesh: Mesh): CSG {
  250. var vertex: Vertex, normal: Vector3, uv: Vector2, position: Vector3,
  251. polygon: Polygon,
  252. polygons = new Array<Polygon>(),
  253. vertices;
  254. var matrix: Matrix,
  255. meshPosition: Vector3,
  256. meshRotation: Vector3,
  257. meshRotationQuaternion: Nullable<Quaternion> = null,
  258. meshScaling: Vector3;
  259. if (mesh instanceof Mesh) {
  260. mesh.computeWorldMatrix(true);
  261. matrix = mesh.getWorldMatrix();
  262. meshPosition = mesh.position.clone();
  263. meshRotation = mesh.rotation.clone();
  264. if (mesh.rotationQuaternion) {
  265. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  266. }
  267. meshScaling = mesh.scaling.clone();
  268. } else {
  269. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  270. }
  271. var indices = <IndicesArray>mesh.getIndices(),
  272. positions = <FloatArray>mesh.getVerticesData(VertexBuffer.PositionKind),
  273. normals = <FloatArray>mesh.getVerticesData(VertexBuffer.NormalKind),
  274. uvs = <FloatArray>mesh.getVerticesData(VertexBuffer.UVKind);
  275. var subMeshes = mesh.subMeshes;
  276. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  277. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  278. vertices = [];
  279. for (var j = 0; j < 3; j++) {
  280. var sourceNormal = new Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  281. uv = new Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  282. var sourcePosition = new Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  283. position = Vector3.TransformCoordinates(sourcePosition, matrix);
  284. normal = Vector3.TransformNormal(sourceNormal, matrix);
  285. vertex = new Vertex(position, normal, uv);
  286. vertices.push(vertex);
  287. }
  288. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  289. // To handle the case of degenerated triangle
  290. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  291. if (polygon.plane)
  292. polygons.push(polygon);
  293. }
  294. }
  295. var csg = CSG.FromPolygons(polygons);
  296. csg.matrix = matrix;
  297. csg.position = meshPosition;
  298. csg.rotation = meshRotation;
  299. csg.scaling = meshScaling;
  300. csg.rotationQuaternion = meshRotationQuaternion;
  301. currentCSGMeshId++;
  302. return csg;
  303. }
  304. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  305. private static FromPolygons(polygons: Polygon[]): CSG {
  306. var csg = new CSG();
  307. csg.polygons = polygons;
  308. return csg;
  309. }
  310. public clone(): CSG {
  311. var csg = new CSG();
  312. csg.polygons = this.polygons.map(p => p.clone());
  313. csg.copyTransformAttributes(this);
  314. return csg;
  315. }
  316. public union(csg: CSG): CSG {
  317. var a = new Node(this.clone().polygons);
  318. var b = new Node(csg.clone().polygons);
  319. a.clipTo(b);
  320. b.clipTo(a);
  321. b.invert();
  322. b.clipTo(a);
  323. b.invert();
  324. a.build(b.allPolygons());
  325. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  326. }
  327. public unionInPlace(csg: CSG): void {
  328. var a = new Node(this.polygons);
  329. var b = new Node(csg.polygons);
  330. a.clipTo(b);
  331. b.clipTo(a);
  332. b.invert();
  333. b.clipTo(a);
  334. b.invert();
  335. a.build(b.allPolygons());
  336. this.polygons = a.allPolygons();
  337. }
  338. public subtract(csg: CSG): CSG {
  339. var a = new Node(this.clone().polygons);
  340. var b = new Node(csg.clone().polygons);
  341. a.invert();
  342. a.clipTo(b);
  343. b.clipTo(a);
  344. b.invert();
  345. b.clipTo(a);
  346. b.invert();
  347. a.build(b.allPolygons());
  348. a.invert();
  349. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  350. }
  351. public subtractInPlace(csg: CSG): void {
  352. var a = new Node(this.polygons);
  353. var b = new Node(csg.polygons);
  354. a.invert();
  355. a.clipTo(b);
  356. b.clipTo(a);
  357. b.invert();
  358. b.clipTo(a);
  359. b.invert();
  360. a.build(b.allPolygons());
  361. a.invert();
  362. this.polygons = a.allPolygons();
  363. }
  364. public intersect(csg: CSG): CSG {
  365. var a = new Node(this.clone().polygons);
  366. var b = new Node(csg.clone().polygons);
  367. a.invert();
  368. b.clipTo(a);
  369. b.invert();
  370. a.clipTo(b);
  371. b.clipTo(a);
  372. a.build(b.allPolygons());
  373. a.invert();
  374. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  375. }
  376. public intersectInPlace(csg: CSG): void {
  377. var a = new Node(this.polygons);
  378. var b = new Node(csg.polygons);
  379. a.invert();
  380. b.clipTo(a);
  381. b.invert();
  382. a.clipTo(b);
  383. b.clipTo(a);
  384. a.build(b.allPolygons());
  385. a.invert();
  386. this.polygons = a.allPolygons();
  387. }
  388. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  389. // not modified.
  390. public inverse(): CSG {
  391. var csg = this.clone();
  392. csg.inverseInPlace();
  393. return csg;
  394. }
  395. public inverseInPlace(): void {
  396. this.polygons.map(p => { p.flip(); });
  397. }
  398. // This is used to keep meshes transformations so they can be restored
  399. // when we build back a Babylon Mesh
  400. // NB : All CSG operations are performed in world coordinates
  401. public copyTransformAttributes(csg: CSG): CSG {
  402. this.matrix = csg.matrix;
  403. this.position = csg.position;
  404. this.rotation = csg.rotation;
  405. this.scaling = csg.scaling;
  406. this.rotationQuaternion = csg.rotationQuaternion;
  407. return this;
  408. }
  409. // Build Raw mesh from CSG
  410. // Coordinates here are in world space
  411. public buildMeshGeometry(name: string, scene: Scene, keepSubMeshes: boolean): Mesh {
  412. var matrix = this.matrix.clone();
  413. matrix.invert();
  414. var mesh = new Mesh(name, scene),
  415. vertices = [],
  416. indices = [],
  417. normals = [],
  418. uvs = [],
  419. vertex = Vector3.Zero(),
  420. normal = Vector3.Zero(),
  421. uv = Vector2.Zero(),
  422. polygons = this.polygons,
  423. polygonIndices = [0, 0, 0], polygon,
  424. vertice_dict = {},
  425. vertex_idx,
  426. currentIndex = 0,
  427. subMesh_dict = {},
  428. subMesh_obj;
  429. if (keepSubMeshes) {
  430. // Sort Polygons, since subMeshes are indices range
  431. polygons.sort((a, b) => {
  432. if (a.shared.meshId === b.shared.meshId) {
  433. return a.shared.subMeshId - b.shared.subMeshId;
  434. } else {
  435. return a.shared.meshId - b.shared.meshId;
  436. }
  437. });
  438. }
  439. for (var i = 0, il = polygons.length; i < il; i++) {
  440. polygon = polygons[i];
  441. // Building SubMeshes
  442. if (!(<any>subMesh_dict)[polygon.shared.meshId]) {
  443. (<any>subMesh_dict)[polygon.shared.meshId] = {};
  444. }
  445. if (!(<any>subMesh_dict)[polygon.shared.meshId][polygon.shared.subMeshId]) {
  446. (<any>subMesh_dict)[polygon.shared.meshId][polygon.shared.subMeshId] = {
  447. indexStart: +Infinity,
  448. indexEnd: -Infinity,
  449. materialIndex: polygon.shared.materialIndex
  450. };
  451. }
  452. subMesh_obj = (<any>subMesh_dict)[polygon.shared.meshId][polygon.shared.subMeshId];
  453. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  454. polygonIndices[0] = 0;
  455. polygonIndices[1] = j - 1;
  456. polygonIndices[2] = j;
  457. for (var k = 0; k < 3; k++) {
  458. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  459. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  460. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  461. var localVertex = Vector3.TransformCoordinates(vertex, matrix);
  462. var localNormal = Vector3.TransformNormal(normal, matrix);
  463. vertex_idx = (<any>vertice_dict)[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  464. // Check if 2 points can be merged
  465. if (!(typeof vertex_idx !== 'undefined' &&
  466. normals[vertex_idx * 3] === localNormal.x &&
  467. normals[vertex_idx * 3 + 1] === localNormal.y &&
  468. normals[vertex_idx * 3 + 2] === localNormal.z &&
  469. uvs[vertex_idx * 2] === uv.x &&
  470. uvs[vertex_idx * 2 + 1] === uv.y)) {
  471. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  472. uvs.push(uv.x, uv.y);
  473. normals.push(normal.x, normal.y, normal.z);
  474. vertex_idx = (<any>vertice_dict)[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  475. }
  476. indices.push(vertex_idx);
  477. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  478. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  479. currentIndex++;
  480. }
  481. }
  482. }
  483. mesh.setVerticesData(VertexBuffer.PositionKind, vertices);
  484. mesh.setVerticesData(VertexBuffer.NormalKind, normals);
  485. mesh.setVerticesData(VertexBuffer.UVKind, uvs);
  486. mesh.setIndices(indices, null);
  487. if (keepSubMeshes) {
  488. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  489. var materialIndexOffset = 0,
  490. materialMaxIndex;
  491. mesh.subMeshes = new Array<SubMesh>();
  492. for (var m in subMesh_dict) {
  493. materialMaxIndex = -1;
  494. for (var sm in (<any>subMesh_dict)[m]) {
  495. subMesh_obj = (<any>subMesh_dict)[m][sm];
  496. SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, <AbstractMesh>mesh);
  497. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  498. }
  499. materialIndexOffset += ++materialMaxIndex;
  500. }
  501. }
  502. return mesh;
  503. }
  504. // Build Mesh from CSG taking material and transforms into account
  505. public toMesh(name: string, material: Nullable<Material>, scene: Scene, keepSubMeshes: boolean): Mesh {
  506. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  507. mesh.material = material;
  508. mesh.position.copyFrom(this.position);
  509. mesh.rotation.copyFrom(this.rotation);
  510. if (this.rotationQuaternion) {
  511. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  512. }
  513. mesh.scaling.copyFrom(this.scaling);
  514. mesh.computeWorldMatrix(true);
  515. return mesh;
  516. }
  517. }
  518. }