babylon.csg.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  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. Plane.EPSILON = 1e-5;
  120. return Plane;
  121. })();
  122. // # class Polygon
  123. // Represents a convex polygon. The vertices used to initialize a polygon must
  124. // be coplanar and form a convex loop.
  125. //
  126. // Each convex polygon has a `shared` property, which is shared between all
  127. // polygons that are clones of each other or were split from the same polygon.
  128. // This can be used to define per-polygon properties (such as surface color).
  129. var Polygon = (function () {
  130. function Polygon(vertices, shared) {
  131. this.vertices = vertices;
  132. this.shared = shared;
  133. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  134. }
  135. Polygon.prototype.clone = function () {
  136. var vertices = this.vertices.map(function (v) {
  137. return v.clone();
  138. });
  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) {
  171. return p.clone();
  172. });
  173. return node;
  174. };
  175. // Convert solid space to empty space and empty space to solid space.
  176. Node.prototype.invert = function () {
  177. for (var i = 0; i < this.polygons.length; i++) {
  178. this.polygons[i].flip();
  179. }
  180. if (this.plane) {
  181. this.plane.flip();
  182. }
  183. if (this.front) {
  184. this.front.invert();
  185. }
  186. if (this.back) {
  187. this.back.invert();
  188. }
  189. var temp = this.front;
  190. this.front = this.back;
  191. this.back = temp;
  192. };
  193. // Recursively remove all polygons in `polygons` that are inside this BSP
  194. // tree.
  195. Node.prototype.clipPolygons = function (polygons) {
  196. if (!this.plane)
  197. return polygons.slice();
  198. var front = [], back = [];
  199. for (var i = 0; i < polygons.length; i++) {
  200. this.plane.splitPolygon(polygons[i], front, back, front, back);
  201. }
  202. if (this.front) {
  203. front = this.front.clipPolygons(front);
  204. }
  205. if (this.back) {
  206. back = this.back.clipPolygons(back);
  207. } else {
  208. back = [];
  209. }
  210. return front.concat(back);
  211. };
  212. // Remove all polygons in this BSP tree that are inside the other BSP tree
  213. // `bsp`.
  214. Node.prototype.clipTo = function (bsp) {
  215. this.polygons = bsp.clipPolygons(this.polygons);
  216. if (this.front)
  217. this.front.clipTo(bsp);
  218. if (this.back)
  219. this.back.clipTo(bsp);
  220. };
  221. // Return a list of all polygons in this BSP tree.
  222. Node.prototype.allPolygons = function () {
  223. var polygons = this.polygons.slice();
  224. if (this.front)
  225. polygons = polygons.concat(this.front.allPolygons());
  226. if (this.back)
  227. polygons = polygons.concat(this.back.allPolygons());
  228. return polygons;
  229. };
  230. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  231. // new polygons are filtered down to the bottom of the tree and become new
  232. // nodes there. Each set of polygons is partitioned using the first polygon
  233. // (no heuristic is used to pick a good split).
  234. Node.prototype.build = function (polygons) {
  235. if (!polygons.length)
  236. return;
  237. if (!this.plane)
  238. this.plane = polygons[0].plane.clone();
  239. var front = [], back = [];
  240. for (var i = 0; i < polygons.length; i++) {
  241. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  242. }
  243. if (front.length) {
  244. if (!this.front)
  245. this.front = new Node();
  246. this.front.build(front);
  247. }
  248. if (back.length) {
  249. if (!this.back)
  250. this.back = new Node();
  251. this.back.build(back);
  252. }
  253. };
  254. return Node;
  255. })();
  256. var CSG = (function () {
  257. function CSG() {
  258. this.polygons = new Array();
  259. }
  260. // Convert BABYLON.Mesh to BABYLON.CSG
  261. CSG.FromMesh = function (mesh) {
  262. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  263. if (mesh instanceof BABYLON.Mesh) {
  264. mesh.computeWorldMatrix(true);
  265. var matrix = mesh.getWorldMatrix();
  266. var meshPosition = mesh.position.clone();
  267. var meshRotation = mesh.rotation.clone();
  268. var meshScaling = mesh.scaling.clone();
  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. currentCSGMeshId++;
  299. return csg;
  300. };
  301. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  302. CSG.FromPolygons = function (polygons) {
  303. var csg = new BABYLON.CSG();
  304. csg.polygons = polygons;
  305. return csg;
  306. };
  307. CSG.prototype.clone = function () {
  308. var csg = new BABYLON.CSG();
  309. csg.polygons = this.polygons.map(function (p) {
  310. return p.clone();
  311. });
  312. csg.copyTransformAttributes(this);
  313. return csg;
  314. };
  315. CSG.prototype.toPolygons = function () {
  316. return this.polygons;
  317. };
  318. CSG.prototype.union = function (csg) {
  319. var a = new Node(this.clone().polygons);
  320. var b = new Node(csg.clone().polygons);
  321. a.clipTo(b);
  322. b.clipTo(a);
  323. b.invert();
  324. b.clipTo(a);
  325. b.invert();
  326. a.build(b.allPolygons());
  327. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  328. };
  329. CSG.prototype.unionInPlace = function (csg) {
  330. var a = new Node(this.polygons);
  331. var b = new Node(csg.polygons);
  332. a.clipTo(b);
  333. b.clipTo(a);
  334. b.invert();
  335. b.clipTo(a);
  336. b.invert();
  337. a.build(b.allPolygons());
  338. this.polygons = a.allPolygons();
  339. };
  340. CSG.prototype.subtract = function (csg) {
  341. var a = new Node(this.clone().polygons);
  342. var b = new Node(csg.clone().polygons);
  343. a.invert();
  344. a.clipTo(b);
  345. b.clipTo(a);
  346. b.invert();
  347. b.clipTo(a);
  348. b.invert();
  349. a.build(b.allPolygons());
  350. a.invert();
  351. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  352. };
  353. CSG.prototype.subtractInPlace = function (csg) {
  354. var a = new Node(this.polygons);
  355. var b = new Node(csg.polygons);
  356. a.invert();
  357. a.clipTo(b);
  358. b.clipTo(a);
  359. b.invert();
  360. b.clipTo(a);
  361. b.invert();
  362. a.build(b.allPolygons());
  363. a.invert();
  364. this.polygons = a.allPolygons();
  365. };
  366. CSG.prototype.intersect = function (csg) {
  367. var a = new Node(this.clone().polygons);
  368. var b = new Node(csg.clone().polygons);
  369. a.invert();
  370. b.clipTo(a);
  371. b.invert();
  372. a.clipTo(b);
  373. b.clipTo(a);
  374. a.build(b.allPolygons());
  375. a.invert();
  376. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  377. };
  378. CSG.prototype.intersectInPlace = function (csg) {
  379. var a = new Node(this.polygons);
  380. var b = new Node(csg.polygons);
  381. a.invert();
  382. b.clipTo(a);
  383. b.invert();
  384. a.clipTo(b);
  385. b.clipTo(a);
  386. a.build(b.allPolygons());
  387. a.invert();
  388. this.polygons = a.allPolygons();
  389. };
  390. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  391. // not modified.
  392. CSG.prototype.inverse = function () {
  393. var csg = this.clone();
  394. csg.inverseInPlace();
  395. return csg;
  396. };
  397. CSG.prototype.inverseInPlace = function () {
  398. this.polygons.map(function (p) {
  399. p.flip();
  400. });
  401. };
  402. // This is used to keep meshes transformations so they can be restored
  403. // when we build back a Babylon Mesh
  404. // NB : All CSG operations are performed in world coordinates
  405. CSG.prototype.copyTransformAttributes = function (csg) {
  406. this.matrix = csg.matrix;
  407. this.position = csg.position;
  408. this.rotation = csg.rotation;
  409. this.scaling = csg.scaling;
  410. return this;
  411. };
  412. // Build Raw mesh from CSG
  413. // Coordinates here are in world space
  414. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  415. var matrix = this.matrix.clone();
  416. matrix.invert();
  417. 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;
  418. if (keepSubMeshes) {
  419. // Sort Polygons, since subMeshes are indices range
  420. polygons.sort(function (a, b) {
  421. if (a.shared.meshId === b.shared.meshId) {
  422. return a.shared.subMeshId - b.shared.subMeshId;
  423. } else {
  424. return a.shared.meshId - b.shared.meshId;
  425. }
  426. });
  427. }
  428. for (var i = 0, il = polygons.length; i < il; i++) {
  429. polygon = polygons[i];
  430. // Building SubMeshes
  431. if (!subMesh_dict[polygon.shared.meshId]) {
  432. subMesh_dict[polygon.shared.meshId] = {};
  433. }
  434. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  435. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  436. indexStart: +Infinity,
  437. indexEnd: -Infinity,
  438. materialIndex: polygon.shared.materialIndex
  439. };
  440. }
  441. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  442. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  443. polygonIndices[0] = 0;
  444. polygonIndices[1] = j - 1;
  445. polygonIndices[2] = j;
  446. for (var k = 0; k < 3; k++) {
  447. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  448. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  449. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  450. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  451. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  452. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  453. // Check if 2 points can be merged
  454. 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)) {
  455. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  456. uvs.push(uv.x, uv.y);
  457. normals.push(normal.x, normal.y, normal.z);
  458. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  459. }
  460. indices.push(vertex_idx);
  461. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  462. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  463. currentIndex++;
  464. }
  465. }
  466. }
  467. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  468. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  469. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  470. mesh.setIndices(indices);
  471. if (keepSubMeshes) {
  472. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  473. var materialIndexOffset = 0, materialMaxIndex;
  474. mesh.subMeshes.length = 0;
  475. for (var m in subMesh_dict) {
  476. materialMaxIndex = -1;
  477. for (var sm in subMesh_dict[m]) {
  478. subMesh_obj = subMesh_dict[m][sm];
  479. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  480. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  481. }
  482. materialIndexOffset += ++materialMaxIndex;
  483. }
  484. }
  485. return mesh;
  486. };
  487. // Build Mesh from CSG taking material and transforms into account
  488. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  489. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  490. mesh.material = material;
  491. mesh.position.copyFrom(this.position);
  492. mesh.rotation.copyFrom(this.rotation);
  493. mesh.scaling.copyFrom(this.scaling);
  494. mesh.computeWorldMatrix(true);
  495. return mesh;
  496. };
  497. return CSG;
  498. })();
  499. BABYLON.CSG = CSG;
  500. })(BABYLON || (BABYLON = {}));
  501. //# sourceMappingURL=babylon.csg.js.map