babylon.csg.js 23 KB

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