polygonMesh.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. import { Logger } from "../Misc/logger";
  2. import { Scene } from "../scene";
  3. import { Vector3, Vector2 } from "../Maths/math.vector";
  4. import { VertexBuffer } from "../Meshes/buffer";
  5. import { Mesh } from "../Meshes/mesh";
  6. import { VertexData } from "../Meshes/mesh.vertexData";
  7. import { Engine } from "../Engines/engine";
  8. import { Nullable } from "../types";
  9. import { Path2 } from '../Maths/math.path';
  10. import { Epsilon } from '../Maths/math.constants';
  11. declare var earcut: any;
  12. /**
  13. * Vector2 wth index property
  14. */
  15. class IndexedVector2 extends Vector2 {
  16. constructor(
  17. original: Vector2,
  18. /** Index of the vector2 */
  19. public index: number) {
  20. super(original.x, original.y);
  21. }
  22. }
  23. /**
  24. * Defines points to create a polygon
  25. */
  26. class PolygonPoints {
  27. elements = new Array<IndexedVector2>();
  28. add(originalPoints: Array<Vector2>): Array<IndexedVector2> {
  29. var result = new Array<IndexedVector2>();
  30. originalPoints.forEach((point) => {
  31. var newPoint = new IndexedVector2(point, this.elements.length);
  32. result.push(newPoint);
  33. this.elements.push(newPoint);
  34. });
  35. return result;
  36. }
  37. computeBounds(): { min: Vector2; max: Vector2; width: number; height: number } {
  38. var lmin = new Vector2(this.elements[0].x, this.elements[0].y);
  39. var lmax = new Vector2(this.elements[0].x, this.elements[0].y);
  40. this.elements.forEach((point) => {
  41. // x
  42. if (point.x < lmin.x) {
  43. lmin.x = point.x;
  44. }
  45. else if (point.x > lmax.x) {
  46. lmax.x = point.x;
  47. }
  48. // y
  49. if (point.y < lmin.y) {
  50. lmin.y = point.y;
  51. }
  52. else if (point.y > lmax.y) {
  53. lmax.y = point.y;
  54. }
  55. });
  56. return {
  57. min: lmin,
  58. max: lmax,
  59. width: lmax.x - lmin.x,
  60. height: lmax.y - lmin.y
  61. };
  62. }
  63. }
  64. /**
  65. * Polygon
  66. * @see https://doc.babylonjs.com/how_to/parametric_shapes#non-regular-polygon
  67. */
  68. export class Polygon {
  69. /**
  70. * Creates a rectangle
  71. * @param xmin bottom X coord
  72. * @param ymin bottom Y coord
  73. * @param xmax top X coord
  74. * @param ymax top Y coord
  75. * @returns points that make the resulting rectation
  76. */
  77. static Rectangle(xmin: number, ymin: number, xmax: number, ymax: number): Vector2[] {
  78. return [
  79. new Vector2(xmin, ymin),
  80. new Vector2(xmax, ymin),
  81. new Vector2(xmax, ymax),
  82. new Vector2(xmin, ymax)
  83. ];
  84. }
  85. /**
  86. * Creates a circle
  87. * @param radius radius of circle
  88. * @param cx scale in x
  89. * @param cy scale in y
  90. * @param numberOfSides number of sides that make up the circle
  91. * @returns points that make the resulting circle
  92. */
  93. static Circle(radius: number, cx: number = 0, cy: number = 0, numberOfSides: number = 32): Vector2[] {
  94. var result = new Array<Vector2>();
  95. var angle = 0;
  96. var increment = (Math.PI * 2) / numberOfSides;
  97. for (var i = 0; i < numberOfSides; i++) {
  98. result.push(new Vector2(
  99. cx + Math.cos(angle) * radius,
  100. cy + Math.sin(angle) * radius
  101. ));
  102. angle -= increment;
  103. }
  104. return result;
  105. }
  106. /**
  107. * Creates a polygon from input string
  108. * @param input Input polygon data
  109. * @returns the parsed points
  110. */
  111. static Parse(input: string): Vector2[] {
  112. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter((val) => (!isNaN(val)));
  113. var i: number, result = [];
  114. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  115. result.push(new Vector2(floats[i], floats[i + 1]));
  116. }
  117. return result;
  118. }
  119. /**
  120. * Starts building a polygon from x and y coordinates
  121. * @param x x coordinate
  122. * @param y y coordinate
  123. * @returns the started path2
  124. */
  125. static StartingAt(x: number, y: number): Path2 {
  126. return Path2.StartingAt(x, y);
  127. }
  128. }
  129. /**
  130. * Builds a polygon
  131. * @see https://doc.babylonjs.com/how_to/polygonmeshbuilder
  132. */
  133. export class PolygonMeshBuilder {
  134. private _points = new PolygonPoints();
  135. private _outlinepoints = new PolygonPoints();
  136. private _holes = new Array<PolygonPoints>();
  137. private _name: string;
  138. private _scene: Nullable<Scene>;
  139. private _epoints: number[] = new Array<number>();
  140. private _eholes: number[] = new Array<number>();
  141. private _addToepoint(points: Vector2[]) {
  142. for (let p of points) {
  143. this._epoints.push(p.x, p.y);
  144. }
  145. }
  146. /**
  147. * Babylon reference to the earcut plugin.
  148. */
  149. public bjsEarcut: any;
  150. /**
  151. * Creates a PolygonMeshBuilder
  152. * @param name name of the builder
  153. * @param contours Path of the polygon
  154. * @param scene scene to add to when creating the mesh
  155. * @param earcutInjection can be used to inject your own earcut reference
  156. */
  157. constructor(name: string, contours: Path2 | Vector2[] | any, scene?: Scene, earcutInjection = earcut) {
  158. this.bjsEarcut = earcutInjection;
  159. this._name = name;
  160. this._scene = scene || Engine.LastCreatedScene;
  161. var points: Vector2[];
  162. if (contours instanceof Path2) {
  163. points = (<Path2>contours).getPoints();
  164. } else {
  165. points = (<Vector2[]>contours);
  166. }
  167. this._addToepoint(points);
  168. this._points.add(points);
  169. this._outlinepoints.add(points);
  170. if (typeof this.bjsEarcut === 'undefined') {
  171. Logger.Warn("Earcut was not found, the polygon will not be built.");
  172. }
  173. }
  174. /**
  175. * Adds a hole within the polygon
  176. * @param hole Array of points defining the hole
  177. * @returns this
  178. */
  179. addHole(hole: Vector2[]): PolygonMeshBuilder {
  180. this._points.add(hole);
  181. var holepoints = new PolygonPoints();
  182. holepoints.add(hole);
  183. this._holes.push(holepoints);
  184. this._eholes.push(this._epoints.length / 2);
  185. this._addToepoint(hole);
  186. return this;
  187. }
  188. /**
  189. * Creates the polygon
  190. * @param updatable If the mesh should be updatable
  191. * @param depth The depth of the mesh created
  192. * @param smoothingThreshold Dot product threshold for smoothed normals
  193. * @returns the created mesh
  194. */
  195. build(updatable: boolean = false, depth: number = 0, smoothingThreshold: number = 2): Mesh {
  196. var result = new Mesh(this._name, this._scene);
  197. var vertexData = this.buildVertexData(depth, smoothingThreshold);
  198. result.setVerticesData(VertexBuffer.PositionKind, <number[]>vertexData.positions, updatable);
  199. result.setVerticesData(VertexBuffer.NormalKind, <number[]>vertexData.normals, updatable);
  200. result.setVerticesData(VertexBuffer.UVKind, <number[]>vertexData.uvs, updatable);
  201. result.setIndices(<number[]>vertexData.indices);
  202. return result;
  203. }
  204. /**
  205. * Creates the polygon
  206. * @param depth The depth of the mesh created
  207. * @param smoothingThreshold Dot product threshold for smoothed normals
  208. * @returns the created VertexData
  209. */
  210. buildVertexData(depth: number = 0, smoothingThreshold: number = 2): VertexData {
  211. var result = new VertexData();
  212. var normals = new Array<number>();
  213. var positions = new Array<number>();
  214. var uvs = new Array<number>();
  215. var bounds = this._points.computeBounds();
  216. this._points.elements.forEach((p) => {
  217. normals.push(0, 1.0, 0);
  218. positions.push(p.x, 0, p.y);
  219. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  220. });
  221. var indices = new Array<number>();
  222. let res = this.bjsEarcut(this._epoints, this._eholes, 2);
  223. for (let i = 0; i < res.length; i++) {
  224. indices.push(res[i]);
  225. }
  226. if (depth > 0) {
  227. var positionscount = (positions.length / 3); //get the current pointcount
  228. this._points.elements.forEach((p) => { //add the elements at the depth
  229. normals.push(0, -1.0, 0);
  230. positions.push(p.x, -depth, p.y);
  231. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  232. });
  233. let totalCount = indices.length;
  234. for (let i = 0; i < totalCount; i += 3) {
  235. let i0 = indices[i + 0];
  236. let i1 = indices[i + 1];
  237. let i2 = indices[i + 2];
  238. indices.push(i2 + positionscount);
  239. indices.push(i1 + positionscount);
  240. indices.push(i0 + positionscount);
  241. }
  242. //Add the sides
  243. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false, smoothingThreshold);
  244. this._holes.forEach((hole) => {
  245. this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true, smoothingThreshold);
  246. });
  247. }
  248. result.indices = indices;
  249. result.positions = positions;
  250. result.normals = normals;
  251. result.uvs = uvs;
  252. return result;
  253. }
  254. /**
  255. * Adds a side to the polygon
  256. * @param positions points that make the polygon
  257. * @param normals normals of the polygon
  258. * @param uvs uvs of the polygon
  259. * @param indices indices of the polygon
  260. * @param bounds bounds of the polygon
  261. * @param points points of the polygon
  262. * @param depth depth of the polygon
  263. * @param flip flip of the polygon
  264. */
  265. private addSide(positions: any[], normals: any[], uvs: any[], indices: any[], bounds: any, points: PolygonPoints, depth: number, flip: boolean, smoothingThreshold: number) {
  266. var StartIndex: number = positions.length / 3;
  267. var ulength: number = 0;
  268. for (var i: number = 0; i < points.elements.length; i++) {
  269. const p: IndexedVector2 = points.elements[i];
  270. const p1: IndexedVector2 = points.elements[(i + 1) % points.elements.length];
  271. positions.push(p.x, 0, p.y);
  272. positions.push(p.x, -depth, p.y);
  273. positions.push(p1.x, 0, p1.y);
  274. positions.push(p1.x, -depth, p1.y);
  275. const p0: IndexedVector2 = points.elements[(i + points.elements.length - 1) % points.elements.length];
  276. const p2: IndexedVector2 = points.elements[(i + 2) % points.elements.length];
  277. let vc = new Vector3(-(p1.y - p.y), 0, p1.x - p.x);
  278. let vp = new Vector3(-(p.y - p0.y), 0, p.x - p0.x);
  279. let vn = new Vector3(-(p2.y - p1.y), 0, p2.x - p1.x);
  280. if (!flip) {
  281. vc = vc.scale(-1);
  282. vp = vp.scale(-1);
  283. vn = vn.scale(-1);
  284. }
  285. let vc_norm = vc.normalizeToNew();
  286. let vp_norm = vp.normalizeToNew();
  287. let vn_norm = vn.normalizeToNew();
  288. const dotp = Vector3.Dot(vp_norm, vc_norm);
  289. if (dotp > smoothingThreshold) {
  290. if (dotp < Epsilon - 1) {
  291. vp_norm = (new Vector3(p.x, 0, p.y)).subtract(new Vector3(p1.x, 0, p1.y)).normalize();
  292. }
  293. else {
  294. // cheap average weighed by side length
  295. vp_norm = vp.add(vc).normalize();
  296. }
  297. }
  298. else {
  299. vp_norm = vc_norm;
  300. }
  301. const dotn = Vector3.Dot(vn, vc);
  302. if (dotn > smoothingThreshold) {
  303. if (dotn < Epsilon - 1) {
  304. // back to back
  305. vn_norm = (new Vector3(p1.x, 0, p1.y)).subtract(new Vector3(p.x, 0, p.y)).normalize();
  306. }
  307. else {
  308. // cheap average weighed by side length
  309. vn_norm = vn.add(vc).normalize();
  310. }
  311. }
  312. else {
  313. vn_norm = vc_norm;
  314. }
  315. uvs.push(ulength / bounds.width, 0);
  316. uvs.push(ulength / bounds.width, 1);
  317. ulength += vc.length();
  318. uvs.push((ulength / bounds.width), 0);
  319. uvs.push((ulength / bounds.width), 1);
  320. normals.push(vp_norm.x, vp_norm.y, vp_norm.z);
  321. normals.push(vp_norm.x, vp_norm.y, vp_norm.z);
  322. normals.push(vn_norm.x, vn_norm.y, vn_norm.z);
  323. normals.push(vn_norm.x, vn_norm.y, vn_norm.z);
  324. if (!flip) {
  325. indices.push(StartIndex);
  326. indices.push(StartIndex + 1);
  327. indices.push(StartIndex + 2);
  328. indices.push(StartIndex + 1);
  329. indices.push(StartIndex + 3);
  330. indices.push(StartIndex + 2);
  331. }
  332. else {
  333. indices.push(StartIndex);
  334. indices.push(StartIndex + 2);
  335. indices.push(StartIndex + 1);
  336. indices.push(StartIndex + 1);
  337. indices.push(StartIndex + 2);
  338. indices.push(StartIndex + 3);
  339. }
  340. StartIndex += 4;
  341. }
  342. }
  343. }