babylon.csg.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  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, t): 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): 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(c.subtract(a), b.subtract(a)));
  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 = this.normal.scale(-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. for (var i = 0; i < polygon.vertices.length; i++) {
  73. var t = Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  74. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  75. polygonType |= type;
  76. types.push(type);
  77. }
  78. // Put the polygon in the correct list, splitting it when necessary.
  79. switch (polygonType) {
  80. case COPLANAR:
  81. (Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  82. break;
  83. case FRONT:
  84. front.push(polygon);
  85. break;
  86. case BACK:
  87. back.push(polygon);
  88. break;
  89. case SPANNING:
  90. var f = [], b = [];
  91. for (i = 0; i < polygon.vertices.length; i++) {
  92. var j = (i + 1) % polygon.vertices.length;
  93. var ti = types[i], tj = types[j];
  94. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  95. if (ti != BACK) f.push(vi);
  96. if (ti != FRONT) b.push(ti != BACK ? vi.clone() : vi);
  97. if ((ti | tj) == SPANNING) {
  98. t = (this.w - Vector3.Dot(this.normal, vi.pos)) / Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  99. var v = vi.interpolate(vj, t);
  100. f.push(v);
  101. b.push(v.clone());
  102. }
  103. }
  104. if (f.length >= 3) front.push(new Polygon(f, polygon.shared));
  105. if (b.length >= 3) back.push(new Polygon(b, polygon.shared));
  106. break;
  107. }
  108. }
  109. }
  110. // # class Polygon
  111. // Represents a convex polygon. The vertices used to initialize a polygon must
  112. // be coplanar and form a convex loop.
  113. //
  114. // Each convex polygon has a `shared` property, which is shared between all
  115. // polygons that are clones of each other or were split from the same polygon.
  116. // This can be used to define per-polygon properties (such as surface color).
  117. class Polygon {
  118. public vertices: Vertex[];
  119. public shared;
  120. public plane: Plane;
  121. constructor(vertices: Vertex[], shared) {
  122. this.vertices = vertices;
  123. this.shared = shared;
  124. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  125. }
  126. public clone(): Polygon {
  127. var vertices = this.vertices.map(v => v.clone());
  128. return new Polygon(vertices, this.shared);
  129. }
  130. public flip() {
  131. this.vertices.reverse().map(v => { v.flip(); });
  132. this.plane.flip();
  133. }
  134. }
  135. // # class Node
  136. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  137. // by picking a polygon to split along. That polygon (and all other coplanar
  138. // polygons) are added directly to that node and the other polygons are added to
  139. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  140. // no distinction between internal and leaf nodes.
  141. class Node {
  142. private plane = null;
  143. private front = null;
  144. private back = null;
  145. private polygons = [];
  146. constructor(polygons?) {
  147. if (polygons) {
  148. this.build(polygons);
  149. }
  150. }
  151. public clone(): Node {
  152. var node = new Node();
  153. node.plane = this.plane && this.plane.clone();
  154. node.front = this.front && this.front.clone();
  155. node.back = this.back && this.back.clone();
  156. node.polygons = this.polygons.map(p => p.clone());
  157. return node;
  158. }
  159. // Convert solid space to empty space and empty space to solid space.
  160. public invert(): void {
  161. for (var i = 0; i < this.polygons.length; i++) {
  162. this.polygons[i].flip();
  163. }
  164. this.plane.flip();
  165. if (this.front) {
  166. this.front.invert();
  167. }
  168. if (this.back) {
  169. this.back.invert();
  170. }
  171. var temp = this.front;
  172. this.front = this.back;
  173. this.back = temp;
  174. }
  175. // Recursively remove all polygons in `polygons` that are inside this BSP
  176. // tree.
  177. clipPolygons(polygons: Polygon[]) {
  178. if (!this.plane) return polygons.slice();
  179. var front = [], back = [];
  180. for (var i = 0; i < polygons.length; i++) {
  181. this.plane.splitPolygon(polygons[i], front, back, front, back);
  182. }
  183. if (this.front) {
  184. front = this.front.clipPolygons(front);
  185. }
  186. if (this.back) {
  187. back = this.back.clipPolygons(back);
  188. } else {
  189. back = [];
  190. }
  191. return front.concat(back);
  192. }
  193. // Remove all polygons in this BSP tree that are inside the other BSP tree
  194. // `bsp`.
  195. clipTo(bsp: Node): void {
  196. this.polygons = bsp.clipPolygons(this.polygons);
  197. if (this.front) this.front.clipTo(bsp);
  198. if (this.back) this.back.clipTo(bsp);
  199. }
  200. // Return a list of all polygons in this BSP tree.
  201. allPolygons(): Polygon[] {
  202. var polygons = this.polygons.slice();
  203. if (this.front) polygons = polygons.concat(this.front.allPolygons());
  204. if (this.back) polygons = polygons.concat(this.back.allPolygons());
  205. return polygons;
  206. }
  207. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  208. // new polygons are filtered down to the bottom of the tree and become new
  209. // nodes there. Each set of polygons is partitioned using the first polygon
  210. // (no heuristic is used to pick a good split).
  211. build(polygons: Polygon[]) {
  212. if (!polygons.length) return;
  213. if (!this.plane) this.plane = polygons[0].plane.clone();
  214. var front = [], back = [];
  215. for (var i = 0; i < polygons.length; i++) {
  216. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  217. }
  218. if (front.length) {
  219. if (!this.front) this.front = new Node();
  220. this.front.build(front);
  221. }
  222. if (back.length) {
  223. if (!this.back) this.back = new Node();
  224. this.back.build(back);
  225. }
  226. }
  227. }
  228. export class CSG {
  229. private polygons = new Array<Polygon>();
  230. public matrix: Matrix;
  231. public position: Vector3;
  232. public rotation: Vector3;
  233. public scaling: Vector3;
  234. // Convert BABYLON.Mesh to BABYLON.CSG
  235. public static FromMesh(mesh: Mesh) {
  236. var vertex, normal, uv, position,
  237. polygon,
  238. polygons = [],
  239. vertices;
  240. if (mesh instanceof BABYLON.Mesh) {
  241. mesh.computeWorldMatrix(true);
  242. var matrix = mesh.getWorldMatrix();
  243. var meshPosition = mesh.position.clone();
  244. var meshRotation = mesh.rotation.clone();
  245. var meshScaling = mesh.scaling.clone();
  246. } else {
  247. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  248. }
  249. var indices = mesh.getIndices(),
  250. positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind),
  251. normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind),
  252. uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  253. var subMeshes = mesh.subMeshes;
  254. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  255. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  256. vertices = [];
  257. for (var j = 0; j < 3; j++) {
  258. normal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  259. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  260. position = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  261. position = BABYLON.Vector3.TransformCoordinates(position, matrix);
  262. normal = BABYLON.Vector3.TransformNormal(normal, matrix);
  263. vertex = new Vertex(position, normal, uv);
  264. vertices.push(vertex);
  265. }
  266. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  267. // To handle the case of degenerated triangle
  268. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  269. if (polygon.plane)
  270. polygons.push(polygon);
  271. }
  272. }
  273. var csg = CSG.FromPolygons(polygons);
  274. csg.matrix = matrix;
  275. csg.position = meshPosition;
  276. csg.rotation = meshRotation;
  277. csg.scaling = meshScaling;
  278. currentCSGMeshId++;
  279. return csg;
  280. }
  281. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  282. private static FromPolygons(polygons: Polygon[]): CSG {
  283. var csg = new BABYLON.CSG();
  284. csg.polygons = polygons;
  285. return csg;
  286. }
  287. public clone(): CSG {
  288. var csg = new BABYLON.CSG();
  289. csg.polygons = this.polygons.map(p => p.clone());
  290. csg.copyTransformAttributes(this);
  291. return csg;
  292. }
  293. private toPolygons(): Polygon[] {
  294. return this.polygons;
  295. }
  296. public union(csg: CSG): CSG {
  297. var a = new Node(this.clone().polygons);
  298. var b = new Node(csg.clone().polygons);
  299. a.clipTo(b);
  300. b.clipTo(a);
  301. b.invert();
  302. b.clipTo(a);
  303. b.invert();
  304. a.build(b.allPolygons());
  305. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  306. }
  307. public subtract(csg: CSG): CSG {
  308. var a = new Node(this.clone().polygons);
  309. var b = new Node(csg.clone().polygons);
  310. a.invert();
  311. a.clipTo(b);
  312. b.clipTo(a);
  313. b.invert();
  314. b.clipTo(a);
  315. b.invert();
  316. a.build(b.allPolygons());
  317. a.invert();
  318. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  319. }
  320. public intersect(csg: CSG): CSG {
  321. var a = new Node(this.clone().polygons);
  322. var b = new Node(csg.clone().polygons);
  323. a.invert();
  324. b.clipTo(a);
  325. b.invert();
  326. a.clipTo(b);
  327. b.clipTo(a);
  328. a.build(b.allPolygons());
  329. a.invert();
  330. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  331. }
  332. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  333. // not modified.
  334. public inverse(): CSG {
  335. var csg = this.clone();
  336. csg.polygons.map(p => { p.flip(); });
  337. return csg;
  338. }
  339. // This is used to keep meshes transformations so they can be restored
  340. // when we build back a Babylon Mesh
  341. // NB : All CSG operations are performed in world coordinates
  342. public copyTransformAttributes(csg: CSG): CSG {
  343. this.matrix = csg.matrix;
  344. this.position = csg.position;
  345. this.rotation = csg.rotation;
  346. this.scaling = csg.scaling;
  347. return this;
  348. }
  349. // Build Raw mesh from CSG
  350. // Coordinates here are in world space
  351. public buildMeshGeometry(name: string, scene: Scene, keepSubMeshes: boolean): Mesh {
  352. var matrix = this.matrix.clone();
  353. matrix.invert();
  354. var mesh = new BABYLON.Mesh(name, scene),
  355. vertices = [],
  356. indices = [],
  357. normals = [],
  358. uvs = [],
  359. vertex, normal, uv,
  360. polygons = this.polygons,
  361. polygonIndices = [0, 0, 0],
  362. polygon,
  363. vertice_dict = {},
  364. vertex_idx,
  365. currentIndex = 0,
  366. subMesh_dict = {},
  367. subMesh_obj;
  368. if (keepSubMeshes) {
  369. // Sort Polygons, since subMeshes are indices range
  370. polygons.sort((a, b) => {
  371. if (a.shared.meshId === b.shared.meshId) {
  372. return a.shared.subMeshId - b.shared.subMeshId;
  373. } else {
  374. return a.shared.meshId - b.shared.meshId;
  375. }
  376. });
  377. }
  378. for (var i = 0, il = polygons.length; i < il; i++) {
  379. polygon = polygons[i];
  380. // Building SubMeshes
  381. if (!subMesh_dict[polygon.shared.meshId]) {
  382. subMesh_dict[polygon.shared.meshId] = {};
  383. }
  384. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  385. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  386. indexStart: +Infinity,
  387. indexEnd: -Infinity,
  388. materialIndex: polygon.shared.materialIndex
  389. };
  390. }
  391. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  392. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  393. polygonIndices[0] = 0;
  394. polygonIndices[1] = j - 1;
  395. polygonIndices[2] = j;
  396. for (var k = 0; k < 3; k++) {
  397. vertex = polygon.vertices[polygonIndices[k]].pos;
  398. normal = polygon.vertices[polygonIndices[k]].normal;
  399. uv = polygon.vertices[polygonIndices[k]].uv;
  400. vertex = new BABYLON.Vector3(vertex.x, vertex.y, vertex.z);
  401. normal = new BABYLON.Vector3(normal.x, normal.y, normal.z);
  402. vertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  403. normal = BABYLON.Vector3.TransformNormal(normal, matrix);
  404. vertex_idx = vertice_dict[vertex.x + ',' + vertex.y + ',' + vertex.z];
  405. // Check if 2 points can be merged
  406. if (!(typeof vertex_idx !== 'undefined' &&
  407. normals[vertex_idx * 3] === normal.x &&
  408. normals[vertex_idx * 3 + 1] === normal.y &&
  409. normals[vertex_idx * 3 + 2] === normal.z &&
  410. uvs[vertex_idx * 2] === uv.x &&
  411. uvs[vertex_idx * 2 + 1] === uv.y)) {
  412. vertices.push(vertex.x, vertex.y, vertex.z);
  413. uvs.push(uv.x, uv.y);
  414. normals.push(normal.x, normal.y, normal.z);
  415. vertex_idx = vertice_dict[vertex.x + ',' + vertex.y + ',' + vertex.z] = (vertices.length / 3) - 1;
  416. }
  417. indices.push(vertex_idx);
  418. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  419. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  420. currentIndex++;
  421. }
  422. }
  423. }
  424. mesh.setVerticesData(vertices, BABYLON.VertexBuffer.PositionKind);
  425. mesh.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind);
  426. mesh.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind);
  427. mesh.setIndices(indices);
  428. if (keepSubMeshes) {
  429. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  430. var materialIndexOffset = 0,
  431. materialMaxIndex;
  432. mesh.subMeshes.length = 0;
  433. for (var m in subMesh_dict) {
  434. materialMaxIndex = -1;
  435. for (var sm in subMesh_dict[m]) {
  436. subMesh_obj = subMesh_dict[m][sm];
  437. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  438. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  439. }
  440. materialIndexOffset += ++materialMaxIndex;
  441. }
  442. }
  443. return mesh;
  444. }
  445. // Build Mesh from CSG taking material and transforms into account
  446. public toMesh(name: string, material: Material, scene: Scene, keepSubMeshes: boolean): Mesh {
  447. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  448. mesh.material = material;
  449. mesh.position.copyFrom(this.position);
  450. mesh.rotation.copyFrom(this.rotation);
  451. mesh.scaling.copyFrom(this.scaling);
  452. mesh.computeWorldMatrix(true);
  453. return mesh;
  454. }
  455. }
  456. }