@pirireis/webglobeplugins 0.17.1 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/Math/haversine.js +22 -0
  2. package/Math/methods.js +15 -2
  3. package/Math/tessellation/methods.js +4 -1
  4. package/Math/tessellation/nearest-value-padding.js +112 -0
  5. package/Math/tessellation/spherical-triangle-area.js +99 -0
  6. package/Math/tessellation/tile-merger.js +346 -215
  7. package/Math/tessellation/triangle-tessellation.js +381 -9
  8. package/Math/vec3.js +4 -0
  9. package/Math/xyz-tile.js +18 -0
  10. package/altitude-locator/plugin.js +1 -2
  11. package/investigation-tools/draw/tiles/adapters.js +2 -2
  12. package/investigation-tools/draw/tiles/tiles.js +2 -2
  13. package/package.json +1 -1
  14. package/programs/helpers/fadeaway.js +6 -1
  15. package/programs/point-on-globe/square-pixel-point.js +1 -0
  16. package/programs/polygon-on-globe/texture-dem-triangles.js +94 -116
  17. package/programs/totems/camera-totem-attactment-interface.js +1 -0
  18. package/programs/totems/camerauniformblock.js +33 -22
  19. package/programs/totems/dem-textures-manager.js +265 -0
  20. package/programs/vectorfields/logics/drawrectangleparticles.js +51 -18
  21. package/programs/vectorfields/logics/{ubo-new.js → particle-ubo.js} +5 -14
  22. package/programs/vectorfields/logics/pixelbased.js +42 -36
  23. package/programs/vectorfields/pingpongbuffermanager.js +34 -8
  24. package/semiplugins/shape-on-terrain/terrain-polygon/adapters.js +55 -0
  25. package/semiplugins/shape-on-terrain/terrain-polygon/data/cache.js +102 -0
  26. package/semiplugins/shape-on-terrain/terrain-polygon/data/index-polygon-map.js +45 -0
  27. package/semiplugins/shape-on-terrain/terrain-polygon/data/manager.js +4 -0
  28. package/semiplugins/shape-on-terrain/terrain-polygon/data/master-worker.js +177 -0
  29. package/semiplugins/shape-on-terrain/terrain-polygon/data/polygon-to-triangles.js +100 -0
  30. package/semiplugins/shape-on-terrain/terrain-polygon/data/random.js +121 -0
  31. package/semiplugins/shape-on-terrain/terrain-polygon/data/types.js +1 -0
  32. package/semiplugins/shape-on-terrain/terrain-polygon/data/worker-contact.js +63 -0
  33. package/semiplugins/shape-on-terrain/terrain-polygon/data/worker.js +125 -0
  34. package/semiplugins/shape-on-terrain/terrain-polygon/terrain-polygon.js +219 -0
  35. package/semiplugins/shape-on-terrain/terrain-polygon/types.js +8 -0
  36. package/semiplugins/shell/bbox-renderer/logic.js +18 -58
  37. package/semiplugins/shell/bbox-renderer/object.js +19 -9
  38. package/tracks/point-heat-map/point-to-heat-map-flow.js +1 -1
  39. package/tracks/point-tracks/plugin.js +13 -6
  40. package/tracks/timetracks/program-line-strip.js +1 -1
  41. package/util/account/single-attribute-buffer-management/buffer-manager.js +5 -3
  42. package/util/account/single-attribute-buffer-management/buffer-orchestrator.js +2 -2
  43. package/util/gl-util/uniform-block/manager.js +20 -10
  44. package/util/helper-methods.js +8 -0
  45. package/util/picking/fence.js +4 -2
  46. package/util/picking/picker-displayer.js +51 -9
  47. package/util/programs/draw-texture-on-canvas.js +18 -15
  48. package/util/shaderfunctions/geometrytransformations.js +67 -1
  49. package/vectorfield/waveparticles/plugin.js +241 -116
  50. package/vectorfield/wind/adapters/image-to-fields.js +61 -0
  51. package/vectorfield/wind/adapters/types.js +1 -0
  52. package/vectorfield/wind/imagetovectorfieldandmagnitude.js +6 -9
  53. package/vectorfield/wind/plugin-persistant copy.js +364 -0
  54. package/vectorfield/wind/plugin-persistant.js +375 -0
  55. package/vectorfield/wind/plugin.js +1 -1
  56. package/Math/tessellation/earcut/adapters.js +0 -37
  57. package/Math/tessellation/hybrid-triangle-tessellation-meta.js +0 -123
  58. package/Math/tessellation/shred-input.js +0 -18
  59. package/Math/tessellation/tiler.js +0 -50
  60. package/Math/tessellation/triangle-tessellation-meta.js +0 -523
  61. package/programs/polygon-on-globe/texture-dem-triangle-test-plugin-triangle.js +0 -328
  62. package/programs/vectorfields/logics/drawrectangleparticles1.js +0 -112
  63. package/semiplugins/shape-on-terrain/terrain-cover/texture-dem-cover.js +0 -1
  64. package/util/gl-util/uniform-block/types.js +0 -1
  65. package/util/webglobe/index.js +0 -2
  66. /package/Math/tessellation/{zoom-catch.js → constants.js} +0 -0
  67. /package/util/{webglobe/gldefaultstates.js → globe-default-gl-states.js} +0 -0
@@ -1,523 +0,0 @@
1
- /**
2
- * @author Toprak Ozturk
3
- */
4
- import { create as createArc, calculateZLimitPoint } from "../arc";
5
- import { createUnitVectorFromLongLat, equals, length, vec3ToLongLatRadians } from "../vec3";
6
- import { TILE_COUNTS } from "./zoom-catch";
7
- import { pointsOnArc } from "../juction/arc-plane";
8
- import { latToTileY, tileYtoLat } from "./methods";
9
- import { isOnTileEdge } from "./methods";
10
- import Delaunator from "delaunator";
11
- import { radianToMercatorXY } from "../methods";
12
- // TODO:get rid of embedded lists. always flat list
13
- const TILE_DEM_VERTEX_COUNT = 5; // 5x5 grid for DEM
14
- const TILE_DEM_STEPCOUNT = TILE_DEM_VERTEX_COUNT - 1; // 4 inner divisions in each dimension
15
- const _plane = /*@__PURE__*/ { normal: [0, 0, 0], distance: 0 };
16
- const _resultPoints = /*@__PURE__*/ [[0, 0, 0], [0, 0, 0]];
17
- function createShellPoints(triangleMeta) {
18
- const arcs = triangleMeta.arcs;
19
- const points = [
20
- arcs[0].p0LongLat,
21
- arcs[1].p0LongLat,
22
- arcs[2].p0LongLat
23
- ];
24
- for (let i = 0; i < 3; i++) {
25
- if (arcs[i].exceededLimit) {
26
- if (arcs[i].exceededLimit !== undefined) {
27
- const longLat = vec3ToLongLatRadians(arcs[i].exceededLimit);
28
- points.push(longLat);
29
- }
30
- }
31
- }
32
- const center = [
33
- points.reduce((sum, p) => sum + p[0], 0) / points.length,
34
- points.reduce((sum, p) => sum + p[1], 0) / points.length
35
- ];
36
- const shellPoints = [];
37
- for (let i = 0; i < points.length; i++) {
38
- const p = points[i];
39
- const x = (p[0] - center[0]) / 10;
40
- const y = (p[1] - center[1]) / 10;
41
- shellPoints.push([p[0] + x, p[1] + y]);
42
- }
43
- return shellPoints;
44
- }
45
- function createBBox(p1, p2, limitVec) {
46
- if (limitVec) {
47
- const limitLongLat = vec3ToLongLatRadians(limitVec);
48
- console.log('Limit point found at:', limitLongLat, 'for p1:', p1, 'p2:', p2);
49
- return {
50
- min: [Math.min(p1[0], p2[0], limitLongLat[0]), Math.min(p1[1], p2[1], limitLongLat[1])],
51
- max: [Math.max(p1[0], p2[0], limitLongLat[0]), Math.max(p1[1], p2[1], limitLongLat[1])],
52
- };
53
- }
54
- return {
55
- min: [Math.min(p1[0], p2[0]), Math.min(p1[1], p2[1])],
56
- max: [Math.max(p1[0], p2[0]), Math.max(p1[1], p2[1])],
57
- };
58
- }
59
- export function createTriangleTessellationMeta(p1, p2, p3) {
60
- const p1v3 = createUnitVectorFromLongLat(p1);
61
- const p2v3 = createUnitVectorFromLongLat(p2);
62
- const p3v3 = createUnitVectorFromLongLat(p3);
63
- const arc1 = createArc(p1v3, p2v3);
64
- const arc2 = createArc(p2v3, p3v3);
65
- const arc3 = createArc(p3v3, p1v3);
66
- const limitVec = [0, 0, 0];
67
- if (calculateZLimitPoint(arc1, limitVec)) {
68
- arc1.exceededLimit = [limitVec[0], limitVec[1], limitVec[2]];
69
- const longlat_ = vec3ToLongLatRadians(arc1.exceededLimit);
70
- console.log('Arc 1 exceeded limit at:', longlat_.map(v => (v * 180 / Math.PI).toFixed(2)), 'rad:', arc1.exceededLimit);
71
- }
72
- arc1.bbox = createBBox(p1, p2, arc1.exceededLimit);
73
- arc1.p0LongLat = p1;
74
- arc1.p1LongLat = p2;
75
- if (calculateZLimitPoint(arc2, limitVec)) {
76
- arc2.exceededLimit = [limitVec[0], limitVec[1], limitVec[2]];
77
- }
78
- arc2.bbox = createBBox(p2, p3, arc2.exceededLimit);
79
- arc2.p0LongLat = p2;
80
- arc2.p1LongLat = p3;
81
- if (calculateZLimitPoint(arc3, limitVec)) {
82
- arc3.exceededLimit = [limitVec[0], limitVec[1], limitVec[2]];
83
- }
84
- arc3.bbox = createBBox(p3, p1, arc3.exceededLimit);
85
- arc3.p0LongLat = p3;
86
- arc3.p1LongLat = p1;
87
- const bbox = {
88
- min: [
89
- Math.min(arc1.bbox.min[0], arc2.bbox.min[0], arc3.bbox.min[0]),
90
- Math.min(arc1.bbox.min[1], arc2.bbox.min[1], arc3.bbox.min[1])
91
- ],
92
- max: [
93
- Math.max(arc1.bbox.max[0], arc2.bbox.max[0], arc3.bbox.max[0]),
94
- Math.max(arc1.bbox.max[1], arc2.bbox.max[1], arc3.bbox.max[1])
95
- ],
96
- };
97
- const meta = {
98
- arcs: [arc1, arc2, arc3],
99
- bbox
100
- };
101
- showMeta(meta);
102
- meta.shellPoints = createShellPoints(meta);
103
- return meta;
104
- }
105
- function showMeta(triangleMeta) {
106
- for (let i = 0; i < 3; i++) {
107
- const arc = triangleMeta.arcs[i];
108
- console.log(`Arc ${i} from ${showLongLatRadian(arc.p0LongLat)} to ${showLongLatRadian(arc.p1LongLat)}, bbox: min(${showLongLatRadian(arc.bbox.min)}) max(${showLongLatRadian(arc.bbox.max)})`);
109
- if (arc.exceededLimit) {
110
- console.log(`Exceeded limit at ${showLongLatRadian(vec3ToLongLatRadians(arc.exceededLimit))}`);
111
- }
112
- }
113
- console.log(`Triangle BBOX: min(${showLongLatRadian(triangleMeta.bbox.min)}) max(${showLongLatRadian(triangleMeta.bbox.max)})`);
114
- }
115
- /**
116
- *
117
- * @param triangleMeta
118
- * @param zoom
119
- * @param angle
120
- * @param dimension false for longitude (meridian) true for latitude (parallel)
121
- */
122
- export function getPoints(triangleMeta, angle, dimension) {
123
- // console.log("getPoints called with angle:", angle * 180 / Math.PI, "dimension:", dimension ? 'latitude' : 'longitude');
124
- // find which arcs are cut by plane
125
- const radians = angle;
126
- if (dimension) {
127
- _plane.normal[0] = 0;
128
- _plane.normal[1] = 0;
129
- _plane.normal[2] = 1;
130
- _plane.distance = Math.sin(radians);
131
- }
132
- else {
133
- _plane.normal[0] = Math.sin(radians);
134
- _plane.normal[1] = -Math.cos(radians);
135
- _plane.normal[2] = 0;
136
- _plane.distance = 0;
137
- }
138
- let result = [];
139
- // Add debugging
140
- let resultsFromDistinctArcs = 0;
141
- for (let i = 0; i < 3; i++) {
142
- const arc = triangleMeta.arcs[i];
143
- const coordIndex = dimension ? 1 : 0;
144
- const minCoord = arc.bbox.min[coordIndex];
145
- const maxCoord = arc.bbox.max[coordIndex];
146
- if (minCoord > angle || maxCoord < angle) {
147
- continue; // arc is out of range
148
- }
149
- const count = pointsOnArc(arc, _plane, _resultPoints);
150
- if (count === 1) {
151
- result.push([[..._resultPoints[0]], vec3ToLongLatRadians(_resultPoints[0])]);
152
- }
153
- else if (count === 2) {
154
- // throw new Error('Unexpected 2 cut points on arc, should be max 1'); // TODO DELETE this line later
155
- result.push([[..._resultPoints[0]], vec3ToLongLatRadians(_resultPoints[0])]);
156
- result.push([[..._resultPoints[1]], vec3ToLongLatRadians(_resultPoints[1])]); // TODO: this is a fix for a bug, need to investigate later
157
- }
158
- resultsFromDistinctArcs += 1;
159
- }
160
- if (resultsFromDistinctArcs === 3) {
161
- result = filterDuplicate(result);
162
- }
163
- if (result.length !== 2 && result.length !== 4) {
164
- // TODO: THERE is a case where 4 points are found.
165
- // this happens when two arcs has limit and share space in Z dimension
166
- console.log("ERROR");
167
- const text = 'Angle:' + angle + ' dimension:' + (dimension ? 'latitude' : 'longitude') + "\n" +
168
- 'Result points count:' + result.length + "\n" +
169
- "bbox:" + triangleMeta.bbox.min[0] * 180 / Math.PI + ", " + triangleMeta.bbox.min[1] * 180 / Math.PI + ", " + triangleMeta.bbox.max[0] * 180 / Math.PI + ", " + triangleMeta.bbox.max[1] * 180 / Math.PI + "\n";
170
- showMeta(triangleMeta);
171
- for (let res of result) {
172
- const ll = res[1];
173
- console.log("Point: " + ll[0] * 180 / Math.PI + ", " + ll[1] * 180 / Math.PI + "\n");
174
- }
175
- throw new Error(`Unexpected cut count for tile cut, got: ${result.length}, angle: ${angle * 180 / Math.PI}, dimension: ${dimension ? 'latitude' : 'longitude'} \n` + text);
176
- }
177
- // TODO: i want to see it delete later
178
- if (result.length === 4) {
179
- console.warn("Warning: 4 cut points found on triangle for angle:", angle * 180 / Math.PI, "dimension:", dimension ? 'latitude' : 'longitude', "points:", result);
180
- }
181
- result.sort((a, b) => {
182
- if (dimension) {
183
- return a[0][1] - b[0][1]; // sort by y for longitude cuts
184
- }
185
- else {
186
- return a[1][0] - b[1][0]; // sort by x for latitude cuts
187
- }
188
- });
189
- return result;
190
- }
191
- function getEdgePoints(triangleMeta) {
192
- const points = [
193
- triangleMeta.arcs[0].p0,
194
- triangleMeta.arcs[1].p0,
195
- triangleMeta.arcs[2].p0,
196
- ];
197
- for (let i = 0; i < 3; i++) {
198
- if (triangleMeta.arcs[i].exceededLimit) {
199
- points.push(triangleMeta.arcs[i].exceededLimit);
200
- }
201
- }
202
- return points;
203
- }
204
- // TODO: EDGES NEED ! LEVEL MORE ZOOM LEVEL OF RESOLUTION as THEY CAN BE NEIGHBOURS OF HIGHER ZOOM LEVEL TILES....
205
- // simple strategy: get max zoom level of neighbour, add edge cuts based on that zoom level, do not fill inner points.
206
- // partialTessellation cure this problem automatically
207
- export function getAllPoints(triangleMeta, zoom, innerCuts = TILE_DEM_STEPCOUNT) {
208
- // TODO: lonLengthRadian and latInnerStep might be change. Dynamic zoom level will show if needed
209
- const points = [];
210
- const longLatPoints = [];
211
- // CALCULATE INFORMATION NEEDED FOR CUTTING
212
- const tileCount = TILE_COUNTS[zoom];
213
- const lonLengthRadian = 2 * Math.PI / tileCount / innerCuts; // inner step
214
- const startMeridianRadian = triangleMeta.bbox.min[0];
215
- const endMeridianRadian = triangleMeta.bbox.max[0];
216
- const startParallelRadian = triangleMeta.bbox.min[1];
217
- const endParallelRadian = triangleMeta.bbox.max[1];
218
- // GET EDGE POINTS
219
- const edgePoints = getEdgePoints(triangleMeta);
220
- const shellPoints = triangleMeta.shellPoints;
221
- for (let i = 0; i < edgePoints.length; i++) {
222
- const longLat = vec3ToLongLatRadians(edgePoints[i]);
223
- longLatPoints.push(...shellPoints[i]);
224
- longLatPoints.push(...longLat);
225
- points.push(0, 0, 0);
226
- points.push(...edgePoints[i]);
227
- }
228
- // GET ALL PARRALLEL CUTS AND FILL MIDDLE POINTS
229
- // how to calculate parallel tiles in range of bbox
230
- const startTileY = latToTileY(startParallelRadian, zoom);
231
- const endTileY = latToTileY(endParallelRadian, zoom);
232
- const latInnerStep = 1 / innerCuts;
233
- let currentY = startTileY - Math.abs(startTileY % latInnerStep);
234
- if (currentY === startTileY)
235
- currentY -= latInnerStep; // since start point is already added
236
- let latCutCount = 0;
237
- while (currentY > endTileY) {
238
- const lat = tileYtoLat(currentY, zoom);
239
- const concurances = getPoints(triangleMeta, lat, true);
240
- for (let i = 0; i < concurances.length; i += 2) {
241
- const p0 = concurances[i];
242
- const p1 = concurances[i + 1];
243
- points.push(...p0[0]);
244
- longLatPoints.push(...p0[1]);
245
- fillBetweenInParallels(lat, p0[1], p1[1], lonLengthRadian, points, longLatPoints);
246
- points.push(...p1[0]);
247
- longLatPoints.push(...p1[1]);
248
- if (length(p0[0]) < 0.99 || length(p1[0]) < 0.99 || length(p0[0]) > 1.01 || length(p1[0]) > 1.01) {
249
- console.warn("Warning: Cut point is not on unit sphere!", length(p0[0]), length(p1[0]));
250
- }
251
- }
252
- currentY -= latInnerStep;
253
- latCutCount++;
254
- }
255
- let currentLong = startMeridianRadian - startMeridianRadian % lonLengthRadian;
256
- if (currentLong === startMeridianRadian)
257
- currentLong += lonLengthRadian; // since start point is already added
258
- while (currentLong < endMeridianRadian) {
259
- const [p0, p1] = getPoints(triangleMeta, currentLong, false);
260
- if (!isOnTileEdge(p0[1], zoom)) {
261
- points.push(...p0[0]);
262
- longLatPoints.push(...p0[1]);
263
- }
264
- if (!isOnTileEdge(p1[1], zoom)) {
265
- points.push(...p1[0]);
266
- longLatPoints.push(...p1[1]);
267
- }
268
- currentLong += lonLengthRadian;
269
- }
270
- const delaunator = new Delaunator(longLatPoints);
271
- let indices = delaunator.triangles;
272
- const edgeIndexes = shellPoints.map((e, index) => index * 2); // edge points are always first points in list
273
- indices = filteroutEdgeConnections(indices, edgeIndexes);
274
- // rotateIndices(indices);
275
- // for (let i = 0; i < longLatPoints.length / 2; i++) {
276
- // const xy = radianToMercatorXY([longLatPoints[i * 2], longLatPoints[i * 2 + 1]]);
277
- // longLatPoints[i * 2] = xy[0];
278
- // longLatPoints[i * 2 + 1] = xy[1];
279
- // }
280
- return { vec3s: new Float32Array(points), longLats: new Float32Array(longLatPoints), indices: indices };
281
- }
282
- function fillBetweenInParallels(lat, p1, p2, step, fillVec3Arr, longLatPoints) {
283
- // return;
284
- // const start = Math.min(p1[0], p2[0]);
285
- // const end = Math.max(p1[0], p2[0]);
286
- const start = p1[0];
287
- const end = p2[0];
288
- // console.log("start:", start * 180 / Math.PI, "end:", end * 180 / Math.PI, "lat:", lat * 180 / Math.PI);
289
- let current = start - (start % step);
290
- while (current < end) {
291
- const item = [current, lat];
292
- fillVec3Arr.push(...createUnitVectorFromLongLat(item));
293
- longLatPoints.push(...item);
294
- current += step;
295
- }
296
- }
297
- function filterDuplicate(points) {
298
- const result = [points[0]];
299
- let dublicate = false;
300
- for (let i = 1; i < points.length; i++) {
301
- for (let j = 0; j < result.length; j++) {
302
- if (equals(points[i][0], result[j][0])) {
303
- dublicate = true;
304
- break;
305
- }
306
- }
307
- if (!dublicate) {
308
- result.push(points[i]);
309
- }
310
- }
311
- return result;
312
- }
313
- function showLongLatRadian(longLat) {
314
- return `(${(longLat[0] * 180 / Math.PI).toFixed(2)}°, ${(longLat[1] * 180 / Math.PI).toFixed(2)}°)`;
315
- }
316
- // This method for removing external edge connections. The connections are unnecessary and cause a veil descending to the center of sphere from the edges
317
- function filteroutEdgeConnections(indexes, filterOutIndexes) {
318
- const length = indexes.length / 3;
319
- const result = [];
320
- for (let i = 0; i < length; i++) {
321
- let pass = false;
322
- for (let filterIndex of filterOutIndexes) {
323
- if (indexes[i * 3] === filterIndex || indexes[i * 3 + 1] === filterIndex || indexes[i * 3 + 2] === filterIndex) {
324
- pass = true;
325
- break;
326
- }
327
- }
328
- if (pass)
329
- continue;
330
- result.push(indexes[i * 3], indexes[i * 3 + 1], indexes[i * 3 + 2]);
331
- }
332
- return new Uint32Array(result);
333
- }
334
- /**
335
- * @unlockedPerk cache
336
- * final outpout can be saved on a hashmap since this triangles are static
337
- */
338
- function shredTriangleTessellationMeta(triangleMeta, zoomLevel) {
339
- /**
340
- * What if tile is covered by the curve of the limit of a single arc.
341
- */
342
- const result = [];
343
- // cut triangleMeta into smaller triangles based on zoom level...
344
- return result;
345
- }
346
- /**
347
- * @lockedPerk cache
348
- *
349
- * cache can be applied at tile triangle intersection level;
350
- *
351
- * @unlockedPerk smoothZoomTransition
352
- *
353
- * @puzzle triangle should be covered without duplicate points. A tile can be covered by a bigger one.
354
- * @solution bbox cuts:
355
- * Ax 1 x x is higher zoom level tile, A is a tile that covers it. 1 2 3 should be asked with A zoom level.
356
- * AA -> Problem1: 1 2 3 x will have edge points duplicated
357
- * 2 3 p1 sol1: edges can be taged, or added separately by and algorithm that only adds edge poitns.
358
- *
359
- * still all triangles should have some sort of cached tessellation to fast render on rapit earth rotation
360
- */
361
- /**
362
- * Creates a mesh for a spherical triangle, tessellated only within the
363
- * regions specified by the `limits` array.
364
- *
365
- * @param triangleMeta The metadata for the spherical triangle.
366
- * @param limits An array of bounding boxes and their associated zoom levels to tessellate.
367
- * @param innerCuts The number of subdivisions within each tile (e.g., TILE_DEM_STEPCOUNT).
368
- * @returns A set of arrays (vec3s, longLats, indices) representing the partial mesh.
369
- */
370
- export function partialTessellation(triangleMeta, limits, innerCuts) {
371
- // TODO: pointMap can be local variable and cleaned after function call to avoid reinitialization overhead
372
- const pointMap = new Map(); // Key: "lon|lat", Value: index
373
- const allVec3s = [];
374
- const allLongLats = [];
375
- let pointCounter = 0;
376
- const stepCount = innerCuts - 1; //
377
- /**
378
- * Precision for coordinate keys in the map. 1e-12 radians is
379
- * extremely small (sub-millimeter on Earth's surface) and avoids
380
- * floating point inaccuracies causing duplicate points.
381
- */
382
- const KEY_PRECISION = 10;
383
- /**
384
- * Adds a point to the vertex arrays if it doesn't already exist.
385
- * Returns the index of the point (new or existing).
386
- */
387
- const addPoint = (longLat, vec3) => {
388
- const key = `${longLat[0].toPrecision(KEY_PRECISION)}|${longLat[1].toPrecision(KEY_PRECISION)}`;
389
- let index = pointMap.get(key);
390
- if (index !== undefined) {
391
- return index; // Point already exists
392
- }
393
- // Point is new, add it
394
- const v3 = vec3 || createUnitVectorFromLongLat(longLat);
395
- allVec3s.push(...v3);
396
- allLongLats.push(...longLat);
397
- index = pointCounter++;
398
- pointMap.set(key, index);
399
- return index;
400
- };
401
- // 1. Add triangle's "shell" (for Delaunay) and "edge" (vertices/limits) points
402
- // These points constrain the triangulation.
403
- const shellPointIndices = [];
404
- const edgePoints = getEdgePoints(triangleMeta);
405
- // Assuming shellPoints and edgePoints have the same length and correspond
406
- const shellPointCount = Math.min(triangleMeta.shellPoints.length, edgePoints.length);
407
- for (let i = 0; i < shellPointCount; i++) {
408
- // Add the "shell" point (for Delaunay stability)
409
- shellPointIndices.push(addPoint(triangleMeta.shellPoints[i]));
410
- // Add the actual "edge" point (triangle vertex or limit point)
411
- addPoint(vec3ToLongLatRadians(edgePoints[i]), edgePoints[i]);
412
- }
413
- // 2. Iterate through each tile limit
414
- for (const { bbox: tileBBox, zoom } of limits) {
415
- // 2a. Calculate the intersection BBOX (the area we'll work on)
416
- const workBBox = {
417
- min: [
418
- Math.max(triangleMeta.bbox.min[0], tileBBox.min[0]),
419
- Math.max(triangleMeta.bbox.min[1], tileBBox.min[1])
420
- ],
421
- max: [
422
- Math.min(triangleMeta.bbox.max[0], tileBBox.max[0]),
423
- Math.min(triangleMeta.bbox.max[1], tileBBox.max[1])
424
- ],
425
- };
426
- // If the intersection is invalid (no overlap), skip this tile
427
- if (workBBox.min[0] >= workBBox.max[0] || workBBox.min[1] >= workBBox.max[1]) {
428
- continue;
429
- }
430
- // 2b. Calculate grid steps for this tile's zoom
431
- const tileCount = TILE_COUNTS[zoom];
432
- const lonStep = (2 * Math.PI) / tileCount / stepCount;
433
- const latStep = 1.0 / stepCount; // This is in tileY units
434
- // 2c. Generate Latitude (Parallel) Points
435
- const startTileY = latToTileY(workBBox.max[1], zoom); // max lat -> min tileY
436
- const endTileY = latToTileY(workBBox.min[1], zoom); // min lat -> max tileY
437
- // let currentY = Math.ceil(startTileY / latStep) * latStep;
438
- let currentY = startTileY - Math.abs(startTileY % latStep);
439
- // if (currentY < startTileY - 1e-9) currentY += latStep; // Ensure we start inside or on edge
440
- if (currentY === startTileY)
441
- currentY -= latStep; // since start point is already added
442
- while (currentY <= endTileY + 1e-9) {
443
- const lat = tileYtoLat(currentY, zoom);
444
- // Skip if rounding put us slightly outside the work box
445
- if (lat < workBBox.min[1] - 1e-9 || lat > workBBox.max[1] + 1e-9) {
446
- currentY += latStep;
447
- continue;
448
- }
449
- // Find where this latitude line intersects the triangle
450
- const intersections = getPoints(triangleMeta, lat, true);
451
- for (let i = 0; i < intersections.length; i += 2) {
452
- const p0 = intersections[i]; // [Vec3, LongLatRadian]
453
- const p1 = intersections[i + 1];
454
- // Find the segment of this latitude line that is *inside* both
455
- // the triangle (p0-p1) AND the tile BBOX (workBBox)
456
- const triMinLon = Math.min(p0[1][0], p1[1][0]);
457
- const triMaxLon = Math.max(p0[1][0], p1[1][0]);
458
- const segMinLon = Math.max(workBBox.min[0], triMinLon);
459
- const segMaxLon = Math.min(workBBox.max[0], triMaxLon);
460
- // If this clipped segment is valid, generate points
461
- if (segMinLon < segMaxLon - 1e-9) {
462
- // Add the exact start and end points of the clipped segment
463
- addPoint([segMinLon, lat]);
464
- addPoint([segMaxLon, lat]);
465
- // Add fill points *between* them
466
- let currentLon = Math.ceil(segMinLon / lonStep) * lonStep;
467
- if (currentLon < segMinLon - 1e-9)
468
- currentLon += lonStep;
469
- while (currentLon < segMaxLon - 1e-9) {
470
- addPoint([currentLon, lat]);
471
- currentLon += lonStep;
472
- }
473
- }
474
- }
475
- currentY += latStep;
476
- }
477
- // 2d. Generate Longitude (Meridian) Points
478
- const startLon = workBBox.min[0];
479
- const endLon = workBBox.max[0];
480
- let currentLon = Math.ceil(startLon / lonStep) * lonStep;
481
- if (currentLon < startLon - 1e-9)
482
- currentLon += lonStep;
483
- while (currentLon <= endLon + 1e-9) {
484
- // Find where this longitude line intersects the triangle
485
- const intersections = getPoints(triangleMeta, currentLon, false);
486
- for (const p of intersections) {
487
- const pLongLat = p[1];
488
- // Check if this point is inside the *workBBox*
489
- if (pLongLat[1] >= workBBox.min[1] - 1e-9 &&
490
- pLongLat[1] <= workBBox.max[1] + 1e-9) {
491
- addPoint(pLongLat, p[0]);
492
- }
493
- }
494
- currentLon += lonStep;
495
- }
496
- } // End loop over limits
497
- // 3. Triangulate
498
- // We must have at least 3 points to make a triangle
499
- if (pointCounter < 3) {
500
- return {
501
- vec3s: new Float32Array(),
502
- longLats: new Float32Array(),
503
- indices: new Uint32Array(),
504
- };
505
- }
506
- const delaunator = new Delaunator(allLongLats);
507
- let indices = delaunator.triangles;
508
- // 4. Filter out triangles connected to the "shell" points
509
- indices = filteroutEdgeConnections(indices, shellPointIndices);
510
- // console.log(...allLongLats.slice(0, 10));
511
- for (let i = 0; i < allLongLats.length / 2; i++) {
512
- const xy = radianToMercatorXY([allLongLats[i * 2], allLongLats[i * 2 + 1]]);
513
- allLongLats[i * 2] = xy[0];
514
- allLongLats[i * 2 + 1] = xy[1];
515
- }
516
- // show first 5
517
- // console.log(...allLongLats.slice(0, 10));
518
- return {
519
- vec3s: new Float32Array(allVec3s),
520
- longLats: new Float32Array(allLongLats),
521
- indices: indices,
522
- };
523
- }