babylon.csg.js 23 KB

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