babylon.csg.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  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(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;
  131. public plane: Plane;
  132. constructor(vertices: Vertex[], shared) {
  133. this.vertices = vertices;
  134. this.shared = shared;
  135. this.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()).filter(v => v.plane);
  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 = null;
  154. private front = null;
  155. private back = null;
  156. private polygons = [];
  157. constructor(polygons?) {
  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[]) {
  191. if (!this.plane) return polygons.slice();
  192. var front = [], back = [];
  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[]) {
  225. if (!polygons.length) return;
  226. if (!this.plane) this.plane = polygons[0].plane.clone();
  227. var front = [], back = [];
  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: 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: Quaternion,
  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 = mesh.getIndices(),
  272. positions = mesh.getVerticesData(VertexBuffer.PositionKind),
  273. normals = mesh.getVerticesData(VertexBuffer.NormalKind),
  274. uvs = 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. private toPolygons(): Polygon[] {
  317. return this.polygons;
  318. }
  319. public union(csg: CSG): CSG {
  320. var a = new Node(this.clone().polygons);
  321. var b = new Node(csg.clone().polygons);
  322. a.clipTo(b);
  323. b.clipTo(a);
  324. b.invert();
  325. b.clipTo(a);
  326. b.invert();
  327. a.build(b.allPolygons());
  328. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  329. }
  330. public unionInPlace(csg: CSG): void {
  331. var a = new Node(this.polygons);
  332. var b = new Node(csg.polygons);
  333. a.clipTo(b);
  334. b.clipTo(a);
  335. b.invert();
  336. b.clipTo(a);
  337. b.invert();
  338. a.build(b.allPolygons());
  339. this.polygons = a.allPolygons();
  340. }
  341. public subtract(csg: CSG): CSG {
  342. var a = new Node(this.clone().polygons);
  343. var b = new Node(csg.clone().polygons);
  344. a.invert();
  345. a.clipTo(b);
  346. b.clipTo(a);
  347. b.invert();
  348. b.clipTo(a);
  349. b.invert();
  350. a.build(b.allPolygons());
  351. a.invert();
  352. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  353. }
  354. public subtractInPlace(csg: CSG): void {
  355. var a = new Node(this.polygons);
  356. var b = new Node(csg.polygons);
  357. a.invert();
  358. a.clipTo(b);
  359. b.clipTo(a);
  360. b.invert();
  361. b.clipTo(a);
  362. b.invert();
  363. a.build(b.allPolygons());
  364. a.invert();
  365. this.polygons = a.allPolygons();
  366. }
  367. public intersect(csg: CSG): CSG {
  368. var a = new Node(this.clone().polygons);
  369. var b = new Node(csg.clone().polygons);
  370. a.invert();
  371. b.clipTo(a);
  372. b.invert();
  373. a.clipTo(b);
  374. b.clipTo(a);
  375. a.build(b.allPolygons());
  376. a.invert();
  377. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  378. }
  379. public intersectInPlace(csg: CSG): void {
  380. var a = new Node(this.polygons);
  381. var b = new Node(csg.polygons);
  382. a.invert();
  383. b.clipTo(a);
  384. b.invert();
  385. a.clipTo(b);
  386. b.clipTo(a);
  387. a.build(b.allPolygons());
  388. a.invert();
  389. this.polygons = a.allPolygons();
  390. }
  391. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  392. // not modified.
  393. public inverse(): CSG {
  394. var csg = this.clone();
  395. csg.inverseInPlace();
  396. return csg;
  397. }
  398. public inverseInPlace(): void {
  399. this.polygons.map(p => { p.flip(); });
  400. }
  401. // This is used to keep meshes transformations so they can be restored
  402. // when we build back a Babylon Mesh
  403. // NB : All CSG operations are performed in world coordinates
  404. public copyTransformAttributes(csg: CSG): CSG {
  405. this.matrix = csg.matrix;
  406. this.position = csg.position;
  407. this.rotation = csg.rotation;
  408. this.scaling = csg.scaling;
  409. this.rotationQuaternion = csg.rotationQuaternion;
  410. return this;
  411. }
  412. // Build Raw mesh from CSG
  413. // Coordinates here are in world space
  414. public buildMeshGeometry(name: string, scene: Scene, keepSubMeshes: boolean): Mesh {
  415. var matrix = this.matrix.clone();
  416. matrix.invert();
  417. var mesh = new Mesh(name, scene),
  418. vertices = [],
  419. indices = [],
  420. normals = [],
  421. uvs = [],
  422. vertex = Vector3.Zero(),
  423. normal = Vector3.Zero(),
  424. uv = Vector2.Zero(),
  425. polygons = this.polygons,
  426. polygonIndices = [0, 0, 0], polygon,
  427. vertice_dict = {},
  428. vertex_idx,
  429. currentIndex = 0,
  430. subMesh_dict = {},
  431. subMesh_obj;
  432. if (keepSubMeshes) {
  433. // Sort Polygons, since subMeshes are indices range
  434. polygons.sort((a, b) => {
  435. if (a.shared.meshId === b.shared.meshId) {
  436. return a.shared.subMeshId - b.shared.subMeshId;
  437. } else {
  438. return a.shared.meshId - b.shared.meshId;
  439. }
  440. });
  441. }
  442. for (var i = 0, il = polygons.length; i < il; i++) {
  443. polygon = polygons[i];
  444. // Building SubMeshes
  445. if (!subMesh_dict[polygon.shared.meshId]) {
  446. subMesh_dict[polygon.shared.meshId] = {};
  447. }
  448. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  449. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  450. indexStart: +Infinity,
  451. indexEnd: -Infinity,
  452. materialIndex: polygon.shared.materialIndex
  453. };
  454. }
  455. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  456. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  457. polygonIndices[0] = 0;
  458. polygonIndices[1] = j - 1;
  459. polygonIndices[2] = j;
  460. for (var k = 0; k < 3; k++) {
  461. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  462. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  463. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  464. var localVertex = Vector3.TransformCoordinates(vertex, matrix);
  465. var localNormal = Vector3.TransformNormal(normal, matrix);
  466. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  467. // Check if 2 points can be merged
  468. if (!(typeof vertex_idx !== 'undefined' &&
  469. normals[vertex_idx * 3] === localNormal.x &&
  470. normals[vertex_idx * 3 + 1] === localNormal.y &&
  471. normals[vertex_idx * 3 + 2] === localNormal.z &&
  472. uvs[vertex_idx * 2] === uv.x &&
  473. uvs[vertex_idx * 2 + 1] === uv.y)) {
  474. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  475. uvs.push(uv.x, uv.y);
  476. normals.push(normal.x, normal.y, normal.z);
  477. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  478. }
  479. indices.push(vertex_idx);
  480. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  481. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  482. currentIndex++;
  483. }
  484. }
  485. }
  486. mesh.setVerticesData(VertexBuffer.PositionKind, vertices);
  487. mesh.setVerticesData(VertexBuffer.NormalKind, normals);
  488. mesh.setVerticesData(VertexBuffer.UVKind, uvs);
  489. mesh.setIndices(indices);
  490. if (keepSubMeshes) {
  491. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  492. var materialIndexOffset = 0,
  493. materialMaxIndex;
  494. mesh.subMeshes = new Array<SubMesh>();
  495. for (var m in subMesh_dict) {
  496. materialMaxIndex = -1;
  497. for (var sm in subMesh_dict[m]) {
  498. subMesh_obj = subMesh_dict[m][sm];
  499. SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  500. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  501. }
  502. materialIndexOffset += ++materialMaxIndex;
  503. }
  504. }
  505. return mesh;
  506. }
  507. // Build Mesh from CSG taking material and transforms into account
  508. public toMesh(name: string, material: Material, scene: Scene, keepSubMeshes: boolean): Mesh {
  509. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  510. mesh.material = material;
  511. mesh.position.copyFrom(this.position);
  512. mesh.rotation.copyFrom(this.rotation);
  513. if(this.rotationQuaternion) {
  514. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  515. }
  516. mesh.scaling.copyFrom(this.scaling);
  517. mesh.computeWorldMatrix(true);
  518. return mesh;
  519. }
  520. }
  521. }