@pirireis/webglobeplugins 1.0.2 → 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 (259) hide show
  1. package/Math/{angle-calculation.ts → angle-calculation.js} +14 -18
  2. package/Math/{arc-cdf-points.ts → arc-cdf-points.js} +272 -329
  3. package/Math/{arc-generate-points-exponantial.ts → arc-generate-points-exponantial.js} +254 -299
  4. package/Math/{arc.ts → arc.js} +292 -421
  5. package/Math/bounds/line-bbox.js +186 -225
  6. package/Math/{circle-cdf-points.ts → circle-cdf-points.js} +78 -143
  7. package/Math/{circle.ts → circle.js} +33 -49
  8. package/Math/{constants.ts → constants.js} +4 -12
  9. package/Math/contour/{quadtreecontours.ts → quadtreecontours.js} +300 -371
  10. package/Math/contour/quadtreecontours1.js +298 -336
  11. package/Math/{finite-line-2d.ts → finite-line-2d.js} +58 -68
  12. package/Math/{haversine.ts → haversine.js} +22 -33
  13. package/Math/index.js +1 -0
  14. package/Math/juction/{arc-plane.ts → arc-plane.js} +143 -203
  15. package/Math/juction/{line-sphere.ts → line-sphere.js} +22 -32
  16. package/Math/juction/{plane-plane.ts → plane-plane.js} +53 -62
  17. package/Math/{line.ts → line.js} +52 -84
  18. package/Math/matrix4.js +1 -0
  19. package/Math/{methods.ts → methods.js} +126 -182
  20. package/Math/{plane.ts → plane.js} +56 -92
  21. package/Math/{quaternion.ts → quaternion.js} +106 -128
  22. package/Math/templete-shapes/{grid-visually-equal.ts → grid-visually-equal.js} +65 -118
  23. package/Math/tessellation/constants.js +1 -0
  24. package/Math/tessellation/{methods.ts → methods.js} +49 -79
  25. package/Math/tessellation/{nearest-value-padding.ts → nearest-value-padding.js} +112 -147
  26. package/Math/tessellation/{spherical-triangle-area.ts → spherical-triangle-area.js} +99 -127
  27. package/Math/tessellation/{tile-merger.ts → tile-merger.js} +429 -578
  28. package/Math/tessellation/{triangle-tessellation.ts → triangle-tessellation.js} +386 -533
  29. package/Math/tessellation/types.js +1 -0
  30. package/Math/types.js +1 -0
  31. package/Math/utils.js +2 -3
  32. package/Math/{vec3.ts → vec3.js} +155 -227
  33. package/Math/{xyz-tile.ts → xyz-tile.js} +18 -26
  34. package/algorithms/search-binary.js +16 -14
  35. package/altitude-locator/adaptors.js +1 -0
  36. package/altitude-locator/keymethod.js +1 -0
  37. package/altitude-locator/plugin.js +344 -445
  38. package/altitude-locator/types.js +21 -26
  39. package/compass-rose/compass-rose-padding-flat.js +230 -274
  40. package/compass-rose/{compass-text-writer.ts → compass-text-writer.js} +155 -210
  41. package/compass-rose/index.js +3 -3
  42. package/{constants.ts → constants.js} +6 -8
  43. package/heatwave/datamanager.js +149 -168
  44. package/heatwave/heatwave.js +206 -261
  45. package/heatwave/index.js +5 -5
  46. package/heatwave/isobar.js +303 -340
  47. package/heatwave/{texture-point-sampler.ts → texture-point-sampler.js} +187 -220
  48. package/investigation-tools/draw/tiles/adapters.js +67 -0
  49. package/investigation-tools/draw/tiles/{tiles.ts → tiles.js} +128 -162
  50. package/jest.config.js +7 -6
  51. package/package.json +1 -1
  52. package/pin/pin-object-array1.js +300 -381
  53. package/pin/pin-point-totem1.js +60 -77
  54. package/programs/arrowfield/arrow-field.js +60 -89
  55. package/programs/arrowfield/logic.js +141 -173
  56. package/programs/data2legend/density-to-legend.js +68 -86
  57. package/programs/data2legend/point-to-density-texture.js +67 -84
  58. package/programs/float2legendwithratio/index.js +2 -3
  59. package/programs/float2legendwithratio/logic.js +118 -144
  60. package/programs/float2legendwithratio/object.js +104 -141
  61. package/programs/helpers/blender.js +58 -73
  62. package/programs/helpers/{fadeaway.ts → fadeaway.js} +60 -73
  63. package/programs/index.js +20 -19
  64. package/programs/line-on-globe/circle-accurate-3d.js +85 -112
  65. package/programs/line-on-globe/circle-accurate-flat.js +148 -200
  66. package/programs/line-on-globe/degree-padding-around-circle-3d.js +102 -134
  67. package/programs/line-on-globe/index.js +1 -0
  68. package/programs/line-on-globe/lines-color-instanced-flat.js +80 -99
  69. package/programs/line-on-globe/linestrip/data.js +4 -0
  70. package/programs/line-on-globe/linestrip/{linestrip.ts → linestrip.js} +93 -152
  71. package/programs/line-on-globe/{naive-accurate-flexible.ts → naive-accurate-flexible.js} +126 -175
  72. package/programs/line-on-globe/util.js +5 -8
  73. package/programs/picking/pickable-polygon-renderer.js +98 -129
  74. package/programs/picking/pickable-renderer.js +98 -130
  75. package/programs/point-on-globe/element-globe-surface-glow.js +93 -122
  76. package/programs/point-on-globe/element-point-glow.js +80 -114
  77. package/programs/point-on-globe/square-pixel-point.js +121 -139
  78. package/programs/polygon-on-globe/{texture-dem-triangles.ts → texture-dem-triangles.js} +163 -207
  79. package/programs/{programcache.ts → programcache.js} +126 -134
  80. package/programs/rings/index.js +1 -1
  81. package/programs/rings/partial-ring/{piece-of-pie.ts → piece-of-pie.js} +152 -222
  82. package/programs/totems/camera-totem-attactment-interface.js +1 -0
  83. package/programs/totems/{camerauniformblock.ts → camerauniformblock.js} +225 -310
  84. package/programs/totems/{canvas-webglobe-info.ts → canvas-webglobe-info.js} +132 -147
  85. package/programs/totems/{dem-textures-manager.ts → dem-textures-manager.js} +257 -360
  86. package/programs/totems/{globe-changes.ts → globe-changes.js} +59 -79
  87. package/programs/totems/gpu-selection-uniform-block.js +99 -127
  88. package/programs/totems/{index.ts → index.js} +2 -2
  89. package/programs/two-d/pixel-padding-for-compass.js +87 -101
  90. package/programs/util.js +14 -19
  91. package/programs/vectorfields/logics/{constants.ts → constants.js} +4 -5
  92. package/programs/vectorfields/logics/{drawrectangleparticles.ts → drawrectangleparticles.js} +80 -115
  93. package/programs/vectorfields/logics/index.js +2 -4
  94. package/programs/vectorfields/logics/particle-ubo.js +16 -0
  95. package/programs/vectorfields/logics/{pixelbased.ts → pixelbased.js} +86 -115
  96. package/programs/vectorfields/logics/ubo.js +51 -57
  97. package/programs/vectorfields/{pingpongbuffermanager.ts → pingpongbuffermanager.js} +99 -113
  98. package/range-tools-on-terrain/bearing-line/{adapters.ts → adapters.js} +114 -154
  99. package/range-tools-on-terrain/bearing-line/{plugin.ts → plugin.js} +457 -569
  100. package/range-tools-on-terrain/bearing-line/types.js +1 -0
  101. package/range-tools-on-terrain/circle-line-chain/{adapters.ts → adapters.js} +85 -104
  102. package/range-tools-on-terrain/circle-line-chain/{chain-list-map.ts → chain-list-map.js} +382 -446
  103. package/range-tools-on-terrain/circle-line-chain/{plugin.ts → plugin.js} +464 -607
  104. package/range-tools-on-terrain/circle-line-chain/types.js +1 -0
  105. package/range-tools-on-terrain/range-ring/{adapters.ts → adapters.js} +93 -114
  106. package/range-tools-on-terrain/range-ring/{enum.ts → enum.js} +2 -2
  107. package/range-tools-on-terrain/range-ring/{plugin.ts → plugin.js} +377 -444
  108. package/range-tools-on-terrain/range-ring/rangeringangletext.js +331 -0
  109. package/range-tools-on-terrain/range-ring/types.js +9 -0
  110. package/semiplugins/interface.js +1 -0
  111. package/semiplugins/lightweight/{line-plugin.ts → line-plugin.js} +221 -342
  112. package/semiplugins/lightweight/{piece-of-pie-plugin.ts → piece-of-pie-plugin.js} +200 -275
  113. package/semiplugins/shape-on-terrain/{arc-plugin.ts → arc-plugin.js} +481 -616
  114. package/semiplugins/shape-on-terrain/{circle-plugin.ts → circle-plugin.js} +444 -588
  115. package/semiplugins/shape-on-terrain/{padding-1-degree.ts → padding-1-degree.js} +539 -713
  116. package/semiplugins/shape-on-terrain/terrain-polygon/{adapters.ts → adapters.js} +55 -69
  117. package/semiplugins/shape-on-terrain/terrain-polygon/data/{cache.ts → cache.js} +102 -149
  118. package/semiplugins/shape-on-terrain/terrain-polygon/data/{index-polygon-map.ts → index-polygon-map.js} +45 -58
  119. package/semiplugins/shape-on-terrain/terrain-polygon/data/{manager.ts → manager.js} +4 -4
  120. package/semiplugins/shape-on-terrain/terrain-polygon/data/master-worker.js +177 -196
  121. package/semiplugins/shape-on-terrain/terrain-polygon/data/{polygon-to-triangles.ts → polygon-to-triangles.js} +100 -144
  122. package/semiplugins/shape-on-terrain/terrain-polygon/data/{random.ts → random.js} +121 -165
  123. package/semiplugins/shape-on-terrain/terrain-polygon/data/types.js +1 -0
  124. package/semiplugins/shape-on-terrain/terrain-polygon/data/{worker-contact.ts → worker-contact.js} +63 -81
  125. package/semiplugins/shape-on-terrain/terrain-polygon/data/worker.js +125 -146
  126. package/semiplugins/shape-on-terrain/terrain-polygon/{terrain-polygon.ts → terrain-polygon.js} +219 -265
  127. package/semiplugins/shape-on-terrain/terrain-polygon/types.js +8 -0
  128. package/semiplugins/shell/bbox-renderer/index.js +2 -0
  129. package/semiplugins/shell/bbox-renderer/{logic.ts → logic.js} +209 -273
  130. package/semiplugins/shell/bbox-renderer/object.js +75 -0
  131. package/semiplugins/type.js +1 -0
  132. package/semiplugins/utility/{container-plugin.ts → container-plugin.js} +94 -126
  133. package/semiplugins/utility/{object-pass-container-plugin.ts → object-pass-container-plugin.js} +80 -101
  134. package/shaders/fragment-toy/firework.js +1 -1
  135. package/shaders/fragment-toy/singularity.js +2 -5
  136. package/tracks/point-heat-map/adaptors/timetracksplugin-format-to-this.js +63 -78
  137. package/tracks/point-heat-map/index.js +1 -0
  138. package/tracks/point-heat-map/plugin-webworker.js +121 -148
  139. package/tracks/point-heat-map/point-to-heat-map-flow.js +121 -150
  140. package/tracks/point-tracks/key-methods.js +2 -3
  141. package/tracks/point-tracks/plugin.js +401 -487
  142. package/tracks/timetracks/adaptors-line-strip.js +65 -79
  143. package/tracks/timetracks/plugin-line-strip.js +240 -295
  144. package/tracks/timetracks/program-line-strip.js +411 -495
  145. package/tracks/timetracks/programpoint-line-strip.js +109 -137
  146. package/types.js +19 -0
  147. package/util/account/bufferoffsetmanager.js +176 -209
  148. package/util/account/create-buffermap-orchastration.js +39 -0
  149. package/util/account/index.js +3 -6
  150. package/util/account/single-attribute-buffer-management/{buffer-manager.ts → buffer-manager.js} +119 -151
  151. package/util/account/single-attribute-buffer-management/{buffer-orchestrator.ts → buffer-orchestrator.js} +212 -238
  152. package/util/account/single-attribute-buffer-management/{buffer-orchestrator1.ts → buffer-orchestrator1.js} +159 -184
  153. package/util/account/single-attribute-buffer-management/{index.ts → index.js} +4 -11
  154. package/util/account/single-attribute-buffer-management/{object-store.ts → object-store.js} +55 -76
  155. package/util/account/single-attribute-buffer-management/types.js +1 -0
  156. package/util/account/util.js +18 -22
  157. package/util/algorithms/index.js +1 -0
  158. package/util/algorithms/search-binary.js +25 -26
  159. package/util/build-strategy/{static-dynamic.ts → static-dynamic.js} +41 -50
  160. package/util/check/index.js +1 -0
  161. package/util/check/typecheck.js +66 -0
  162. package/util/{frame-counter-trigger.ts → frame-counter-trigger.js} +84 -99
  163. package/util/geometry/{index.ts → index.js} +121 -155
  164. package/util/gl-util/buffer/{attribute-loader.ts → attribute-loader.js} +62 -84
  165. package/util/gl-util/buffer/{index.ts → index.js} +3 -6
  166. package/util/gl-util/draw-options/{methods.ts → methods.js} +32 -47
  167. package/util/gl-util/uniform-block/{manager.ts → manager.js} +200 -232
  168. package/util/{globe-default-gl-states.ts → globe-default-gl-states.js} +4 -5
  169. package/util/{helper-methods.ts → helper-methods.js} +8 -9
  170. package/util/index.js +10 -9
  171. package/util/interpolation/index.js +1 -0
  172. package/util/interpolation/timetrack/index.js +2 -9
  173. package/util/interpolation/timetrack/timetrack-interpolator.js +79 -94
  174. package/util/interpolation/timetrack/web-worker.js +46 -51
  175. package/util/picking/{fence.ts → fence.js} +43 -47
  176. package/util/picking/{picker-displayer.ts → picker-displayer.js} +176 -226
  177. package/util/programs/draw-from-pixel-coords.js +164 -201
  178. package/util/programs/{draw-texture-on-canvas.ts → draw-texture-on-canvas.js} +69 -91
  179. package/util/programs/supersampletotextures.js +97 -130
  180. package/util/programs/texturetoglobe.js +128 -153
  181. package/util/shaderfunctions/{geometrytransformations.ts → geometrytransformations.js} +44 -106
  182. package/util/shaderfunctions/index.js +2 -2
  183. package/util/shaderfunctions/nodata.js +2 -4
  184. package/util/shaderfunctions/noisefunctions.js +7 -10
  185. package/util/{webglobjectbuilders.ts → webglobjectbuilders.js} +358 -446
  186. package/vectorfield/arrowfield/adaptor.js +11 -11
  187. package/vectorfield/arrowfield/index.js +3 -3
  188. package/vectorfield/arrowfield/plugin.js +83 -128
  189. package/vectorfield/waveparticles/adaptor.js +15 -16
  190. package/vectorfield/waveparticles/index.js +3 -3
  191. package/vectorfield/waveparticles/{plugin.ts → plugin.js} +415 -506
  192. package/vectorfield/wind/adapters/{image-to-fields.ts → image-to-fields.js} +61 -74
  193. package/vectorfield/wind/adapters/types.js +1 -0
  194. package/vectorfield/wind/{imagetovectorfieldandmagnitude.ts → imagetovectorfieldandmagnitude.js} +53 -78
  195. package/vectorfield/wind/index.js +5 -5
  196. package/vectorfield/wind/{plugin-persistant copy.ts → plugin-persistant copy.js } +364 -461
  197. package/vectorfield/wind/{plugin-persistant.ts → plugin-persistant.js} +375 -483
  198. package/vectorfield/wind/plugin.js +685 -883
  199. package/vectorfield/wind/vectorfieldimage.js +23 -27
  200. package/write-text/{context-text-bulk.ts → context-text-bulk.js} +200 -285
  201. package/write-text/context-text3.js +167 -0
  202. package/write-text/{context-text4.ts → context-text4.js} +146 -231
  203. package/write-text/context-textDELETE.js +94 -125
  204. package/write-text/objectarraylabels/{index.ts → index.js} +2 -2
  205. package/write-text/objectarraylabels/objectarraylabels.js +200 -247
  206. package/Math/matrix4.ts +0 -0
  207. package/Math/mesh/mapbox-delaunay.d.ts +0 -74
  208. package/Math/roadmap.md +0 -10
  209. package/Math/tessellation/constants.ts +0 -1
  210. package/Math/tessellation/roadmap.md +0 -48
  211. package/Math/tessellation/types.ts +0 -1
  212. package/Math/types.ts +0 -68
  213. package/investigation-tools/draw/tiles/adapters.ts +0 -133
  214. package/programs/line-on-globe/linestrip/data.ts +0 -29
  215. package/programs/polygon-on-globe/roadmap.md +0 -8
  216. package/programs/totems/camera-totem-attactment-interface.ts +0 -4
  217. package/programs/vectorfields/logics/particle-ubo.ts +0 -23
  218. package/publish.bat +0 -62
  219. package/range-tools-on-terrain/bearing-line/types.ts +0 -65
  220. package/range-tools-on-terrain/circle-line-chain/types.ts +0 -43
  221. package/range-tools-on-terrain/range-ring/rangeringangletext.ts +0 -396
  222. package/range-tools-on-terrain/range-ring/types.ts +0 -30
  223. package/semiplugins/interface.ts +0 -14
  224. package/semiplugins/shape-on-terrain/goal.md +0 -12
  225. package/semiplugins/shape-on-terrain/terrain-polygon/data/cache-shortcuts.md +0 -20
  226. package/semiplugins/shape-on-terrain/terrain-polygon/data/master-worker.ts +0 -209
  227. package/semiplugins/shape-on-terrain/terrain-polygon/data/readme.md +0 -5
  228. package/semiplugins/shape-on-terrain/terrain-polygon/data/types.ts +0 -37
  229. package/semiplugins/shape-on-terrain/terrain-polygon/notes.md +0 -90
  230. package/semiplugins/shape-on-terrain/terrain-polygon/types.ts +0 -69
  231. package/semiplugins/shell/bbox-renderer/index.ts +0 -2
  232. package/semiplugins/shell/bbox-renderer/object.ts +0 -129
  233. package/semiplugins/type.ts +0 -8
  234. package/terrain-plugin.mmd +0 -83
  235. package/tests/Math/arc-sampling-test.js +0 -367
  236. package/tests/Math/arc-sampling-test.ts +0 -429
  237. package/tests/Math/arc.test.ts +0 -77
  238. package/tests/Math/junction/arc-limit.test.ts +0 -7
  239. package/tests/Math/junction/arc-plane-points.test.ts +0 -196
  240. package/tests/Math/junction/arc-plane.test.ts +0 -172
  241. package/tests/Math/junction/line-sphere.test.ts +0 -127
  242. package/tests/Math/junction/plane-plane.test.ts +0 -91
  243. package/tests/Math/plane-test.ts +0 -17
  244. package/tests/Math/plane.test.ts +0 -43
  245. package/tests/Math/vec3.test.ts +0 -33
  246. package/tracks/point-heat-map/readme.md +0 -15
  247. package/tracks/timetracks/readme.md +0 -1
  248. package/tsconfig.json +0 -22
  249. package/types/@pirireis/webglobe.d.ts +0 -102
  250. package/types/delaunator.d.ts +0 -40
  251. package/types/earcut.d.ts +0 -11
  252. package/types/rbush.d.ts +0 -57
  253. package/types.ts +0 -319
  254. package/util/account/create-buffermap-orchastration.ts +0 -85
  255. package/util/account/single-attribute-buffer-management/types.ts +0 -43
  256. package/util/check/typecheck.ts +0 -74
  257. package/vectorfield/wind/adapters/types.ts +0 -12
  258. package/write-text/context-text3.ts +0 -252
  259. package/write-text/objectarraylabels/objectarraylabels.d.ts +0 -72
@@ -1,578 +1,429 @@
1
- import { DrawnTileInfo, GlobeBBox, Globe } from "../../types";
2
- import { xyzToBBOX } from "../xyz-tile";
3
- import { calculateMergedMeshDimLength } from "./methods";
4
- import { NearestValuePadding } from "./nearest-value-padding";
5
- // Channel of float32array mesh is 1;
6
-
7
-
8
- type TileLimit = {
9
- minX: number;
10
- maxX: number;
11
- minY: number;
12
- maxY: number;
13
- antimeridian?: boolean;
14
- centerX?: number;
15
- centerY?: number;
16
- }
17
-
18
- type TileMetaData = {
19
- tileMap: Map<string, DrawnTileInfo>;
20
- maxLevel: number;
21
- minLevel: number;
22
- tileLimitsByZoom: Map<number, TileLimit>;
23
-
24
-
25
- }
26
-
27
-
28
-
29
-
30
-
31
- export type MergedTilesInfo = {
32
- mesh: Float32Array, bbox: GlobeBBox, zoom: number, coverRatio: { x: number, y: number }
33
- };
34
-
35
-
36
-
37
-
38
- function keyMethod(x: number, y: number, level: number): string {
39
- return `${level}_${x}_${y}`;
40
- }
41
-
42
- function calculateParentTile(x: number, y: number, level: number): { x: number, y: number, level: number } {
43
- return {
44
- x: Math.floor(x / 2),
45
- y: Math.floor(y / 2),
46
- level: level - 1
47
- };
48
- }
49
-
50
- // helper for analyses
51
- type ZoomLevelData = {
52
- xValues: number[]; // All X coordinates at this level
53
- yValues: number[]; // All Y Coordinates at this level
54
- }
55
-
56
- function createMapAndMetaData(tiles: DrawnTileInfo[], globe: Globe): TileMetaData {
57
- const tileMap = new Map<string, DrawnTileInfo>();
58
- let maxLevel = -Infinity;
59
- let minLevel = Infinity;
60
-
61
- // Intermediate storage to analyze distributions per zoom level
62
- const zoomData = new Map<number, ZoomLevelData>();
63
-
64
- // 1. First Pass: Populate Map and Collect Coordinates
65
- for (const tile of tiles) {
66
- const key = keyMethod(tile.x, tile.y, tile.level);
67
- tileMap.set(key, tile);
68
-
69
- // Update Level Range
70
- if (tile.level > maxLevel) maxLevel = tile.level;
71
- if (tile.level < minLevel) minLevel = tile.level;
72
-
73
- // Collect Data
74
- if (!zoomData.has(tile.level)) {
75
- zoomData.set(tile.level, { xValues: [], yValues: [] });
76
- }
77
- const data = zoomData.get(tile.level)!;
78
- data.xValues.push(tile.x);
79
- data.yValues.push(tile.y);
80
- }
81
-
82
- const tileLimitsByZoom = new Map<number, TileLimit>();
83
-
84
- // 2. Second Pass: Analyze Data per Zoom Level
85
- zoomData.forEach((data, level) => {
86
- // --- Calculate Gravity Centers (Mode) ---
87
-
88
-
89
- // --- Calculate Min/Max and Antimeridian ---
90
- // Sort X values to detect gaps
91
- const sortedX = [...new Set(data.xValues)].sort((a, b) => a - b);
92
- const minY = Math.min(...data.yValues);
93
- const maxY = Math.max(...data.yValues);
94
-
95
- let minX = sortedX[0];
96
- let maxX = sortedX[sortedX.length - 1];
97
- let isAntimeridian = false;
98
-
99
-
100
- // We only check for wrapping if we have tiles near both edges (0 and Max)
101
- // A simple heuristic: find the largest gap between sorted indices.
102
- let maxGap = 0;
103
- let gapIndex = -1;
104
-
105
- for (let i = 0; i < sortedX.length - 1; i++) {
106
- const gap = sortedX[i + 1] - sortedX[i];
107
- if (gap > maxGap) {
108
- maxGap = gap;
109
- gapIndex = i;
110
- }
111
- }
112
-
113
- // Also check the wrap-around gap (distance from last tile to world end + first tile)
114
- // Though strictly for clustering split, we usually look for the internal gap.
115
-
116
- // If the largest internal gap is significantly large (e.g., > worldWidth / 2),
117
- // we treat the smaller numbers as the "East of view" (Right side)
118
- // and large numbers as "West of view" (Left side) relative to the dateline.
119
- // let centerX = getGravityCenter(data.xValues);
120
- // const centerY = getGravityCenter(data.yValues);
121
- const { x: centerX, y: centerY } = getCenterFromCamera(globe, level);
122
- if (maxGap > 5 && maxX === Math.pow(2, level) - 1 && minX === 0) {
123
- isAntimeridian = true;
124
-
125
- // Cluster 1 (Low X): sortedX[0] ... sortedX[gapIndex] -> "West Cluster" (The Americas/Left side of map 0..x)
126
- // Cluster 2 (High X): sortedX[gapIndex+1] ... end -> "East Cluster" (Asia/Right side of map x..max)
127
-
128
- // Per requirements:
129
- // "max value now represents max of west cluster" -> Max of the Low X numbers
130
- maxX = sortedX[gapIndex];
131
-
132
- // "min values represents min of east cluster" -> Min of the High X numbers
133
- minX = sortedX[gapIndex + 1];
134
-
135
- }
136
-
137
- tileLimitsByZoom.set(level, {
138
- minX,
139
- maxX,
140
- minY,
141
- maxY,
142
- antimeridian: isAntimeridian,
143
- centerX,
144
- centerY
145
- });
146
- });
147
-
148
- return {
149
- tileMap,
150
- maxLevel,
151
- minLevel,
152
- tileLimitsByZoom
153
- };
154
- }
155
-
156
- // Helper to find the most frequent value (Gravity Center)
157
- function getMode(arr: number[]): number {
158
- if (arr.length === 0) return 0;
159
- const map = new Map<number, number>();
160
- let maxCount = 0;
161
- let mode = arr[0];
162
-
163
- for (const num of arr) {
164
- const count = (map.get(num) || 0) + 1;
165
- map.set(num, count);
166
- if (count > maxCount) {
167
- maxCount = count;
168
- mode = num;
169
- }
170
- }
171
- return mode;
172
- }
173
-
174
-
175
- function getGravityCenter(arr: number[]): number {
176
- if (arr.length === 0) return 0;
177
- const sum = arr.reduce((acc, val) => acc + val, 0);
178
- return Math.round(sum / arr.length);
179
- }
180
-
181
- function getCenterFromCamera(globe: any, zoom: number): { x: number, y: number } {
182
- const camLongLat = globe.FCamera.FCamLongLat;
183
- const n = Math.pow(2, zoom);
184
- const x = Math.floor((camLongLat.x / (2 * Math.PI) + 0.5) * n);
185
- const y = Math.floor((camLongLat.y / Math.PI + 0.5) * n);
186
- return { x, y };
187
-
188
- }
189
-
190
-
191
- function populateTileIntoHigherZoomLevel(
192
- tileMesh: Float32Array[], tileDimensionLength: number,
193
- targetDimensionLength: number,
194
- ): Float32Array[] {
195
- const newMesh = Array.from({ length: targetDimensionLength }, () => new Float32Array(targetDimensionLength));
196
- // use linear interpolation to populate
197
- for (let row = 0; row < targetDimensionLength; row++) {
198
- for (let col = 0; col < targetDimensionLength; col++) {
199
- const sourceRow = row / (targetDimensionLength - 1) * (tileDimensionLength - 1);
200
- const sourceCol = col / (targetDimensionLength - 1) * (tileDimensionLength - 1);
201
- const rowLow = Math.floor(sourceRow);
202
- const rowHigh = Math.min(Math.ceil(sourceRow), tileDimensionLength - 1);
203
- const colLow = Math.floor(sourceCol);
204
- const colHigh = Math.min(Math.ceil(sourceCol), tileDimensionLength - 1);
205
- const topLeft = tileMesh[rowLow][colLow];
206
- const topRight = tileMesh[rowLow][colHigh];
207
- const bottomLeft = tileMesh[rowHigh][colLow];
208
- const bottomRight = tileMesh[rowHigh][colHigh];
209
- const top = topLeft + (topRight - topLeft) * (sourceCol - colLow);
210
- const bottom = bottomLeft + (bottomRight - bottomLeft) * (sourceCol - colLow);
211
- newMesh[row][col] = top + (bottom - top) * (sourceRow - rowLow);
212
- }
213
- }
214
- return newMesh;
215
- }
216
-
217
-
218
-
219
-
220
- function fillFromChildren(
221
- targetMesh: Float32Array, targetDimensionLength: number,
222
- childrenMeshes: (Float32Array[] | undefined)[], sourceDimensionLength: number,
223
- startX: number, startY: number): void {
224
-
225
- const halfDim = (sourceDimensionLength - 1) / 2;
226
-
227
- // Child 0: Top Left
228
- if (childrenMeshes[0]) {
229
- const child = childrenMeshes[0];
230
- for (let r = 0; r <= halfDim; r++) {
231
- // Read from top of child (source convention is bottom-up, so top is index Length-1)
232
- // We skip every second row: (L-1), (L-3), ...
233
- const childRowIndex = (sourceDimensionLength - 1) - (r * 2);
234
- const rowData = child[childRowIndex];
235
- for (let c = 0; c <= halfDim; c++) {
236
- // Skip every second column
237
- const val = rowData[c * 2];
238
- const targetIdx = (startY + r) * targetDimensionLength + (startX + c);
239
- targetMesh[targetIdx] = val;
240
- }
241
- }
242
- }
243
-
244
- // Child 1: Top Right
245
- // In mergeTiles loop (dx outer, dy inner), index 2 corresponds to dx=1, dy=0 (Top Right)
246
- if (childrenMeshes[2]) {
247
- const child = childrenMeshes[2];
248
- for (let r = 0; r <= halfDim; r++) {
249
- const childRowIndex = (sourceDimensionLength - 1) - (r * 2);
250
- const rowData = child[childRowIndex];
251
- for (let c = 0; c <= halfDim; c++) {
252
- const val = rowData[c * 2];
253
- const targetIdx = (startY + r) * targetDimensionLength + (startX + halfDim + c);
254
- if (isNaN(targetMesh[targetIdx])) {
255
- targetMesh[targetIdx] = val;
256
- }
257
- }
258
- }
259
- }
260
-
261
- // Child 2: Bottom Left
262
- // In mergeTiles loop, index 1 corresponds to dx=0, dy=1 (Bottom Left)
263
- if (childrenMeshes[1]) {
264
- const child = childrenMeshes[1];
265
- for (let r = 0; r <= halfDim; r++) {
266
- const childRowIndex = (sourceDimensionLength - 1) - (r * 2);
267
- const rowData = child[childRowIndex];
268
- for (let c = 0; c <= halfDim; c++) {
269
- const val = rowData[c * 2];
270
- const targetIdx = (startY + halfDim + r) * targetDimensionLength + (startX + c);
271
- if (isNaN(targetMesh[targetIdx])) {
272
- targetMesh[targetIdx] = val;
273
- }
274
- }
275
- }
276
- }
277
-
278
- // Child 3: Bottom Right
279
- if (childrenMeshes[3]) {
280
- const child = childrenMeshes[3];
281
- for (let r = 0; r <= halfDim; r++) {
282
- const childRowIndex = (sourceDimensionLength - 1) - (r * 2);
283
- const rowData = child[childRowIndex];
284
- for (let c = 0; c <= halfDim; c++) {
285
- const val = rowData[c * 2];
286
- const targetIdx = (startY + halfDim + r) * targetDimensionLength + (startX + halfDim + c);
287
- if (isNaN(targetMesh[targetIdx])) {
288
- targetMesh[targetIdx] = val;
289
- }
290
- }
291
- }
292
- }
293
- }
294
-
295
-
296
-
297
- // This function is correct, assuming its inputs are prepared properly.
298
- // This function is correct, assuming its inputs are prepared properly.
299
- function moveMeshToMergedMesh(
300
- targetMesh: Float32Array, targetDimensionLength: number,
301
- sourceMesh: Float32Array[], sourceDimensionLength: number,
302
- startX: number, startY: number): void {
303
- // sourceMesh[0][0] is south west corner
304
- // targetMesh[0][0] is top left corner
305
- let targetIndex: number = startY * targetDimensionLength + startX;
306
- for (let y = 0; y < sourceDimensionLength; y++) {
307
- // Read from bottom to top (source mesh convention)
308
- const vertical = sourceMesh[sourceDimensionLength - y - 1];
309
- for (let x = 0; x < sourceDimensionLength; x++) {
310
- const value = vertical[x];
311
- // const currentValue = targetMesh[targetIndex];
312
- // TODO: investigate why overlapping values are not the same. cancel parent filling
313
- // if (!isNaN(value) && value !== 0 && currentValue !== 0) {
314
- // if (currentValue !== value) {
315
- // console.warn(`Overlapping values are not the same: currentValue=${currentValue}, newValue=${value}`);
316
- // }
317
- // }
318
- if (isNaN(targetMesh[targetIndex])) {
319
- targetMesh[targetIndex] = value;
320
- }
321
- targetIndex++;
322
- }
323
- targetIndex += targetDimensionLength - sourceDimensionLength;
324
- }
325
- }
326
-
327
-
328
-
329
-
330
-
331
- function limitCheck(limit: TileLimit, limitRange = 12): void {
332
- // TODO: far tiles from camera should be pruned to fit in the limit range
333
- const rowRange = limit.maxX - limit.minX + 1;
334
- const colRange = limit.maxY - limit.minY + 1;
335
-
336
- if (rowRange > limitRange || colRange > limitRange) {
337
- console.warn(`Tile limit range exceeded: Row Range = ${rowRange}, Col Range = ${colRange}, Limit Range = ${limitRange}`);
338
- throw new Error("Tile limit range exceeded");
339
- }
340
- }
341
-
342
- function mergeTiles(tilesMetaData: TileMetaData, mergeCount = 8, tileDimensionLength = 5, processLimit = 6): MergedTilesInfo[] {
343
- const mergedMeshDimLength = calculateMergedMeshDimLength(mergeCount, tileDimensionLength);
344
- const nearestValuePadding = new NearestValuePadding(tileDimensionLength, mergeCount);
345
-
346
- // Helper to check if a number is between range (inclusive)
347
-
348
- const result: MergedTilesInfo[] = [];
349
-
350
- for (let zoom = tilesMetaData.maxLevel; zoom >= tilesMetaData.minLevel; zoom--) {
351
-
352
- if (tilesMetaData.maxLevel - zoom >= processLimit) {
353
- break;
354
- }
355
-
356
- const limits = tilesMetaData.tileLimitsByZoom.get(zoom);
357
- if (!limits) continue;
358
-
359
- const mergedMesh = new Float32Array(mergedMeshDimLength * mergedMeshDimLength).fill(NaN);
360
-
361
- // Initialize BBox.
362
- // We track East (high X) and West (low X) clusters separately for Antimeridian cases.
363
- const bboxLimit: GlobeBBox = {
364
- ur: { x: -Infinity, y: -Infinity },
365
- ll: { x: Infinity, y: Infinity }
366
- };
367
-
368
- // Specific BBox trackers for antimeridian split
369
- let eastClusterMinX = Infinity; // For the left side of the view (e.g. 170)
370
- let westClusterMaxX = -Infinity; // For the right side of the view (e.g. -170)
371
-
372
- // limitCheck(limits, 20); // Assumed helper<
373
-
374
- const worldWidth = Math.pow(2, zoom);
375
-
376
- // --- Task 1: Calculate Grid Origin (Centering) ---
377
- // We determine where the top-left of our mergeCount x mergeCount grid starts in tile coordinates.
378
-
379
- let originX = limits.minX;
380
- let originY = limits.minY;
381
-
382
- const rangeX = limits.antimeridian
383
- ? (worldWidth - limits.minX) + limits.maxX + 1
384
- : limits.maxX - limits.minX + 1;
385
- const rangeY = limits.maxY - limits.minY + 1;
386
-
387
- // If the data is wider than the mesh, center it using centerX
388
- if (rangeX > mergeCount && limits.centerX !== undefined) {
389
- originX = Math.floor(limits.centerX - (mergeCount / 2));
390
- }
391
-
392
- // If the data is taller than the mesh, center it using centerY
393
- if (rangeY > mergeCount && limits.centerY !== undefined) {
394
- originY = Math.floor(limits.centerY - (mergeCount / 2));
395
- }
396
-
397
- // --- Task 2: Iterate Grid Slots ---
398
- // Instead of iterating tile coordinates, we iterate the target grid slots (0..mergeCount)
399
- // and calculate which tile belongs there.
400
-
401
- for (let i = 0; i < mergeCount; i++) {
402
- for (let j = 0; j < mergeCount; j++) {
403
-
404
- // Calculate actual Tile Coordinates
405
- // Handle X Wrapping for Antimeridian
406
- let tileX = (originX + i);
407
- // JS modulo of negative numbers behaves oddly, ensure positive wrap
408
- tileX = ((tileX % worldWidth) + worldWidth) % worldWidth;
409
-
410
- const tileY = originY + j;
411
-
412
- // --- Validity Check ---
413
- // Check if this specific tileX/tileY is actually part of the visible map data
414
- let isValidX = false;
415
- if (limits.antimeridian) {
416
- isValidX = tileX >= limits.minX || tileX <= limits.maxX;
417
- } else {
418
- isValidX = tileX >= limits.minX && tileX <= limits.maxX;
419
- }
420
-
421
- const isValidY = tileY >= limits.minY && tileY <= limits.maxY;
422
-
423
- if (!isValidX || !isValidY) continue;
424
-
425
- const key = keyMethod(tileX, tileY, zoom);
426
- const tile = tilesMetaData.tileMap.get(key);
427
-
428
- // Calculate mesh offset (target position in pixels/floats)
429
- const meshOffsetX = i * (tileDimensionLength - 1);
430
- const meshOffsetY = j * (tileDimensionLength - 1);
431
-
432
- if (tile) {
433
- // 1. Direct Tile Found
434
- nearestValuePadding.insert(tile.x, tile.y); // Using original coordinates for padding logic
435
- moveMeshToMergedMesh(
436
- mergedMesh, mergedMeshDimLength,
437
- tile.mesh, tileDimensionLength,
438
- meshOffsetX, meshOffsetY
439
- );
440
-
441
- // Update BBox Limits
442
- // We simply expand the LL/UR.
443
- // Post-processing will fix the inverted X for antimeridian.
444
- if (tile.bbox.ll.x < bboxLimit.ll.x) bboxLimit.ll.x = tile.bbox.ll.x;
445
- if (tile.bbox.ll.y < bboxLimit.ll.y) bboxLimit.ll.y = tile.bbox.ll.y;
446
- if (tile.bbox.ur.x > bboxLimit.ur.x) bboxLimit.ur.x = tile.bbox.ur.x;
447
- if (tile.bbox.ur.y > bboxLimit.ur.y) bboxLimit.ur.y = tile.bbox.ur.y;
448
-
449
- // Track clusters for antimeridian split
450
- // High X values (East Cluster) -> Left side of visual boundary
451
- // Low X values (West Cluster) -> Right side of visual boundary
452
- if (limits.antimeridian) {
453
- if (tileX >= limits.minX) {
454
- if (tile.bbox.ll.x < eastClusterMinX) eastClusterMinX = tile.bbox.ll.x;
455
- } else {
456
- if (tile.bbox.ur.x > westClusterMaxX) westClusterMaxX = tile.bbox.ur.x;
457
- }
458
- }
459
-
460
- } else {
461
- // 2. Parent Tile Fallback
462
- const parentTileCoord = calculateParentTile(tileX, tileY, zoom);
463
- const parentKey = keyMethod(parentTileCoord.x, parentTileCoord.y, parentTileCoord.level);
464
- const parentTile = tilesMetaData.tileMap.get(parentKey);
465
-
466
- if (parentTile) {
467
- const populatedMesh = populateTileIntoHigherZoomLevel(
468
- parentTile.mesh, tileDimensionLength,
469
- tileDimensionLength * 2 - 1
470
- );
471
-
472
- // Adjust offset for parent logic
473
- // If current tile is odd (right/bottom), the parent mesh drawing needs to shift back
474
- // because 'populatedMesh' covers 2x2.
475
- const parentDrawOffsetX = meshOffsetX - (tileX % 2) * (tileDimensionLength - 1);
476
- const parentDrawOffsetY = meshOffsetY - (tileY % 2) * (tileDimensionLength - 1);
477
-
478
- moveMeshToMergedMesh(
479
- mergedMesh, mergedMeshDimLength,
480
- populatedMesh, tileDimensionLength * 2 - 1,
481
- parentDrawOffsetX,
482
- parentDrawOffsetY
483
- );
484
-
485
- // Padding logic for parents
486
- const xP = parentTile.x * 2;
487
- const yP = parentTile.y * 2;
488
- for (let dx = 0; dx < 2; dx++) {
489
- for (let dy = 0; dy < 2; dy++) {
490
- nearestValuePadding.insert(xP + dx, yP + dy);
491
- }
492
- }
493
- } else {
494
- // 3. Children Tile Fallback
495
- const childrenTiles: (Float32Array[] | undefined)[] = [];
496
- let anyChildren = 0;
497
- for (let dx = 0; dx < 2; dx++) {
498
- for (let dy = 0; dy < 2; dy++) {
499
- const childX = tileX * 2 + dx;
500
- const childY = tileY * 2 + dy;
501
- const childKey = keyMethod(childX, childY, zoom + 1);
502
- const childTile = tilesMetaData.tileMap.get(childKey);
503
- if (childTile) {
504
- anyChildren++;
505
- childrenTiles.push(childTile.mesh);
506
- } else {
507
- childrenTiles.push(undefined);
508
- }
509
- }
510
- }
511
-
512
- if (anyChildren > 0) {
513
- nearestValuePadding.insert(tileX, tileY);
514
- fillFromChildren(
515
- mergedMesh, mergedMeshDimLength,
516
- childrenTiles, tileDimensionLength,
517
- meshOffsetX, meshOffsetY
518
- );
519
- }
520
- }
521
- }
522
- }
523
- }
524
-
525
- // Post-Processing BBox for Antimeridian
526
- if (limits.antimeridian) {
527
- // Task: bbox.ll should contain lower-left of East Cluster, bbox.ur should contain upper-right of West Cluster
528
- // This creates the condition ur.x < ll.x (e.g. 170 to -170)
529
-
530
- // Only update if we actually found tiles in those clusters
531
- if (eastClusterMinX !== Infinity) bboxLimit.ll.x = eastClusterMinX;
532
- if (westClusterMaxX !== -Infinity) bboxLimit.ur.x = westClusterMaxX;
533
- // console.log("Antimeridian BBox adjusted:", bboxLimit);
534
- }
535
-
536
- // We pad the merged mesh based on the VALID range we iterated.
537
- // Since we iterate 0..mergeCount, the indices are implicitly 0..mergeCount
538
- // However, the clamp function usually expects absolute coordinates.
539
- // Given the new "Grid" approach, the mesh is always locally 0 to mergeCount in valid data.
540
- // We pass the grid-relative limits to clamp.
541
- nearestValuePadding.clamp(mergedMesh, 0, 0, mergeCount, mergeCount);
542
- nearestValuePadding.clear();
543
-
544
- // Calculate Cover Ratio
545
- // How much of the mesh grid (mergeCount) is covered by actual data range?
546
- const currentWidth = limits.antimeridian ? rangeX : (limits.maxX - limits.minX + 1);
547
- const currentHeight = limits.maxY - limits.minY + 1;
548
-
549
- const usedWidth = Math.min(mergeCount, currentWidth);
550
- const usedHeight = Math.min(mergeCount, currentHeight);
551
-
552
- const xRatio = calculateMergedMeshDimLength(usedWidth, tileDimensionLength) / mergedMeshDimLength;
553
- const yRatio = calculateMergedMeshDimLength(usedHeight, tileDimensionLength) / mergedMeshDimLength;
554
-
555
- result.push({ mesh: mergedMesh, bbox: bboxLimit, zoom: zoom, coverRatio: { x: xRatio, y: yRatio } });
556
- }
557
-
558
- return result;
559
- }
560
-
561
-
562
- export function mergeMeshes(
563
-
564
- tiles: DrawnTileInfo[],
565
- mergeCount = 12,
566
- tileDimensionLength = 5,
567
- processLimit = 6,
568
- globe: Globe
569
- ): MergedTilesInfo[] {
570
- // filter out tiles with NaN values
571
- // return returnTop6tiles(tiles);
572
-
573
- const tilesMetaData = createMapAndMetaData(tiles, globe);
574
- const mergedTiles = mergeTiles(tilesMetaData, mergeCount, tileDimensionLength, processLimit);
575
- return mergedTiles;
576
- }
577
-
578
-
1
+ import { calculateMergedMeshDimLength } from "./methods";
2
+ import { NearestValuePadding } from "./nearest-value-padding";
3
+ function keyMethod(x, y, level) {
4
+ return `${level}_${x}_${y}`;
5
+ }
6
+ function calculateParentTile(x, y, level) {
7
+ return {
8
+ x: Math.floor(x / 2),
9
+ y: Math.floor(y / 2),
10
+ level: level - 1
11
+ };
12
+ }
13
+ function createMapAndMetaData(tiles, globe) {
14
+ const tileMap = new Map();
15
+ let maxLevel = -Infinity;
16
+ let minLevel = Infinity;
17
+ // Intermediate storage to analyze distributions per zoom level
18
+ const zoomData = new Map();
19
+ // 1. First Pass: Populate Map and Collect Coordinates
20
+ for (const tile of tiles) {
21
+ const key = keyMethod(tile.x, tile.y, tile.level);
22
+ tileMap.set(key, tile);
23
+ // Update Level Range
24
+ if (tile.level > maxLevel)
25
+ maxLevel = tile.level;
26
+ if (tile.level < minLevel)
27
+ minLevel = tile.level;
28
+ // Collect Data
29
+ if (!zoomData.has(tile.level)) {
30
+ zoomData.set(tile.level, { xValues: [], yValues: [] });
31
+ }
32
+ const data = zoomData.get(tile.level);
33
+ data.xValues.push(tile.x);
34
+ data.yValues.push(tile.y);
35
+ }
36
+ const tileLimitsByZoom = new Map();
37
+ // 2. Second Pass: Analyze Data per Zoom Level
38
+ zoomData.forEach((data, level) => {
39
+ // --- Calculate Gravity Centers (Mode) ---
40
+ // --- Calculate Min/Max and Antimeridian ---
41
+ // Sort X values to detect gaps
42
+ const sortedX = [...new Set(data.xValues)].sort((a, b) => a - b);
43
+ const minY = Math.min(...data.yValues);
44
+ const maxY = Math.max(...data.yValues);
45
+ let minX = sortedX[0];
46
+ let maxX = sortedX[sortedX.length - 1];
47
+ let isAntimeridian = false;
48
+ // We only check for wrapping if we have tiles near both edges (0 and Max)
49
+ // A simple heuristic: find the largest gap between sorted indices.
50
+ let maxGap = 0;
51
+ let gapIndex = -1;
52
+ for (let i = 0; i < sortedX.length - 1; i++) {
53
+ const gap = sortedX[i + 1] - sortedX[i];
54
+ if (gap > maxGap) {
55
+ maxGap = gap;
56
+ gapIndex = i;
57
+ }
58
+ }
59
+ // Also check the wrap-around gap (distance from last tile to world end + first tile)
60
+ // Though strictly for clustering split, we usually look for the internal gap.
61
+ // If the largest internal gap is significantly large (e.g., > worldWidth / 2),
62
+ // we treat the smaller numbers as the "East of view" (Right side)
63
+ // and large numbers as "West of view" (Left side) relative to the dateline.
64
+ // let centerX = getGravityCenter(data.xValues);
65
+ // const centerY = getGravityCenter(data.yValues);
66
+ const { x: centerX, y: centerY } = getCenterFromCamera(globe, level);
67
+ if (maxGap > 5 && maxX === Math.pow(2, level) - 1 && minX === 0) {
68
+ isAntimeridian = true;
69
+ // Cluster 1 (Low X): sortedX[0] ... sortedX[gapIndex] -> "West Cluster" (The Americas/Left side of map 0..x)
70
+ // Cluster 2 (High X): sortedX[gapIndex+1] ... end -> "East Cluster" (Asia/Right side of map x..max)
71
+ // Per requirements:
72
+ // "max value now represents max of west cluster" -> Max of the Low X numbers
73
+ maxX = sortedX[gapIndex];
74
+ // "min values represents min of east cluster" -> Min of the High X numbers
75
+ minX = sortedX[gapIndex + 1];
76
+ }
77
+ tileLimitsByZoom.set(level, {
78
+ minX,
79
+ maxX,
80
+ minY,
81
+ maxY,
82
+ antimeridian: isAntimeridian,
83
+ centerX,
84
+ centerY
85
+ });
86
+ });
87
+ return {
88
+ tileMap,
89
+ maxLevel,
90
+ minLevel,
91
+ tileLimitsByZoom
92
+ };
93
+ }
94
+ // Helper to find the most frequent value (Gravity Center)
95
+ function getMode(arr) {
96
+ if (arr.length === 0)
97
+ return 0;
98
+ const map = new Map();
99
+ let maxCount = 0;
100
+ let mode = arr[0];
101
+ for (const num of arr) {
102
+ const count = (map.get(num) || 0) + 1;
103
+ map.set(num, count);
104
+ if (count > maxCount) {
105
+ maxCount = count;
106
+ mode = num;
107
+ }
108
+ }
109
+ return mode;
110
+ }
111
+ function getGravityCenter(arr) {
112
+ if (arr.length === 0)
113
+ return 0;
114
+ const sum = arr.reduce((acc, val) => acc + val, 0);
115
+ return Math.round(sum / arr.length);
116
+ }
117
+ function getCenterFromCamera(globe, zoom) {
118
+ const camLongLat = globe.FCamera.FCamLongLat;
119
+ const n = Math.pow(2, zoom);
120
+ const x = Math.floor((camLongLat.x / (2 * Math.PI) + 0.5) * n);
121
+ const y = Math.floor((camLongLat.y / Math.PI + 0.5) * n);
122
+ return { x, y };
123
+ }
124
+ function populateTileIntoHigherZoomLevel(tileMesh, tileDimensionLength, targetDimensionLength) {
125
+ const newMesh = Array.from({ length: targetDimensionLength }, () => new Float32Array(targetDimensionLength));
126
+ // use linear interpolation to populate
127
+ for (let row = 0; row < targetDimensionLength; row++) {
128
+ for (let col = 0; col < targetDimensionLength; col++) {
129
+ const sourceRow = row / (targetDimensionLength - 1) * (tileDimensionLength - 1);
130
+ const sourceCol = col / (targetDimensionLength - 1) * (tileDimensionLength - 1);
131
+ const rowLow = Math.floor(sourceRow);
132
+ const rowHigh = Math.min(Math.ceil(sourceRow), tileDimensionLength - 1);
133
+ const colLow = Math.floor(sourceCol);
134
+ const colHigh = Math.min(Math.ceil(sourceCol), tileDimensionLength - 1);
135
+ const topLeft = tileMesh[rowLow][colLow];
136
+ const topRight = tileMesh[rowLow][colHigh];
137
+ const bottomLeft = tileMesh[rowHigh][colLow];
138
+ const bottomRight = tileMesh[rowHigh][colHigh];
139
+ const top = topLeft + (topRight - topLeft) * (sourceCol - colLow);
140
+ const bottom = bottomLeft + (bottomRight - bottomLeft) * (sourceCol - colLow);
141
+ newMesh[row][col] = top + (bottom - top) * (sourceRow - rowLow);
142
+ }
143
+ }
144
+ return newMesh;
145
+ }
146
+ function fillFromChildren(targetMesh, targetDimensionLength, childrenMeshes, sourceDimensionLength, startX, startY) {
147
+ const halfDim = (sourceDimensionLength - 1) / 2;
148
+ // Child 0: Top Left
149
+ if (childrenMeshes[0]) {
150
+ const child = childrenMeshes[0];
151
+ for (let r = 0; r <= halfDim; r++) {
152
+ // Read from top of child (source convention is bottom-up, so top is index Length-1)
153
+ // We skip every second row: (L-1), (L-3), ...
154
+ const childRowIndex = (sourceDimensionLength - 1) - (r * 2);
155
+ const rowData = child[childRowIndex];
156
+ for (let c = 0; c <= halfDim; c++) {
157
+ // Skip every second column
158
+ const val = rowData[c * 2];
159
+ const targetIdx = (startY + r) * targetDimensionLength + (startX + c);
160
+ targetMesh[targetIdx] = val;
161
+ }
162
+ }
163
+ }
164
+ // Child 1: Top Right
165
+ // In mergeTiles loop (dx outer, dy inner), index 2 corresponds to dx=1, dy=0 (Top Right)
166
+ if (childrenMeshes[2]) {
167
+ const child = childrenMeshes[2];
168
+ for (let r = 0; r <= halfDim; r++) {
169
+ const childRowIndex = (sourceDimensionLength - 1) - (r * 2);
170
+ const rowData = child[childRowIndex];
171
+ for (let c = 0; c <= halfDim; c++) {
172
+ const val = rowData[c * 2];
173
+ const targetIdx = (startY + r) * targetDimensionLength + (startX + halfDim + c);
174
+ if (isNaN(targetMesh[targetIdx])) {
175
+ targetMesh[targetIdx] = val;
176
+ }
177
+ }
178
+ }
179
+ }
180
+ // Child 2: Bottom Left
181
+ // In mergeTiles loop, index 1 corresponds to dx=0, dy=1 (Bottom Left)
182
+ if (childrenMeshes[1]) {
183
+ const child = childrenMeshes[1];
184
+ for (let r = 0; r <= halfDim; r++) {
185
+ const childRowIndex = (sourceDimensionLength - 1) - (r * 2);
186
+ const rowData = child[childRowIndex];
187
+ for (let c = 0; c <= halfDim; c++) {
188
+ const val = rowData[c * 2];
189
+ const targetIdx = (startY + halfDim + r) * targetDimensionLength + (startX + c);
190
+ if (isNaN(targetMesh[targetIdx])) {
191
+ targetMesh[targetIdx] = val;
192
+ }
193
+ }
194
+ }
195
+ }
196
+ // Child 3: Bottom Right
197
+ if (childrenMeshes[3]) {
198
+ const child = childrenMeshes[3];
199
+ for (let r = 0; r <= halfDim; r++) {
200
+ const childRowIndex = (sourceDimensionLength - 1) - (r * 2);
201
+ const rowData = child[childRowIndex];
202
+ for (let c = 0; c <= halfDim; c++) {
203
+ const val = rowData[c * 2];
204
+ const targetIdx = (startY + halfDim + r) * targetDimensionLength + (startX + halfDim + c);
205
+ if (isNaN(targetMesh[targetIdx])) {
206
+ targetMesh[targetIdx] = val;
207
+ }
208
+ }
209
+ }
210
+ }
211
+ }
212
+ // This function is correct, assuming its inputs are prepared properly.
213
+ // This function is correct, assuming its inputs are prepared properly.
214
+ function moveMeshToMergedMesh(targetMesh, targetDimensionLength, sourceMesh, sourceDimensionLength, startX, startY) {
215
+ // sourceMesh[0][0] is south west corner
216
+ // targetMesh[0][0] is top left corner
217
+ let targetIndex = startY * targetDimensionLength + startX;
218
+ for (let y = 0; y < sourceDimensionLength; y++) {
219
+ // Read from bottom to top (source mesh convention)
220
+ const vertical = sourceMesh[sourceDimensionLength - y - 1];
221
+ for (let x = 0; x < sourceDimensionLength; x++) {
222
+ const value = vertical[x];
223
+ // const currentValue = targetMesh[targetIndex];
224
+ // TODO: investigate why overlapping values are not the same. cancel parent filling
225
+ // if (!isNaN(value) && value !== 0 && currentValue !== 0) {
226
+ // if (currentValue !== value) {
227
+ // console.warn(`Overlapping values are not the same: currentValue=${currentValue}, newValue=${value}`);
228
+ // }
229
+ // }
230
+ if (isNaN(targetMesh[targetIndex])) {
231
+ targetMesh[targetIndex] = value;
232
+ }
233
+ targetIndex++;
234
+ }
235
+ targetIndex += targetDimensionLength - sourceDimensionLength;
236
+ }
237
+ }
238
+ function limitCheck(limit, limitRange = 12) {
239
+ // TODO: far tiles from camera should be pruned to fit in the limit range
240
+ const rowRange = limit.maxX - limit.minX + 1;
241
+ const colRange = limit.maxY - limit.minY + 1;
242
+ if (rowRange > limitRange || colRange > limitRange) {
243
+ console.warn(`Tile limit range exceeded: Row Range = ${rowRange}, Col Range = ${colRange}, Limit Range = ${limitRange}`);
244
+ throw new Error("Tile limit range exceeded");
245
+ }
246
+ }
247
+ function mergeTiles(tilesMetaData, mergeCount = 8, tileDimensionLength = 5, processLimit = 6) {
248
+ const mergedMeshDimLength = calculateMergedMeshDimLength(mergeCount, tileDimensionLength);
249
+ const nearestValuePadding = new NearestValuePadding(tileDimensionLength, mergeCount);
250
+ // Helper to check if a number is between range (inclusive)
251
+ const result = [];
252
+ for (let zoom = tilesMetaData.maxLevel; zoom >= tilesMetaData.minLevel; zoom--) {
253
+ if (tilesMetaData.maxLevel - zoom >= processLimit) {
254
+ break;
255
+ }
256
+ const limits = tilesMetaData.tileLimitsByZoom.get(zoom);
257
+ if (!limits)
258
+ continue;
259
+ const mergedMesh = new Float32Array(mergedMeshDimLength * mergedMeshDimLength).fill(NaN);
260
+ // Initialize BBox.
261
+ // We track East (high X) and West (low X) clusters separately for Antimeridian cases.
262
+ const bboxLimit = {
263
+ ur: { x: -Infinity, y: -Infinity },
264
+ ll: { x: Infinity, y: Infinity }
265
+ };
266
+ // Specific BBox trackers for antimeridian split
267
+ let eastClusterMinX = Infinity; // For the left side of the view (e.g. 170)
268
+ let westClusterMaxX = -Infinity; // For the right side of the view (e.g. -170)
269
+ // limitCheck(limits, 20); // Assumed helper<
270
+ const worldWidth = Math.pow(2, zoom);
271
+ // --- Task 1: Calculate Grid Origin (Centering) ---
272
+ // We determine where the top-left of our mergeCount x mergeCount grid starts in tile coordinates.
273
+ let originX = limits.minX;
274
+ let originY = limits.minY;
275
+ const rangeX = limits.antimeridian
276
+ ? (worldWidth - limits.minX) + limits.maxX + 1
277
+ : limits.maxX - limits.minX + 1;
278
+ const rangeY = limits.maxY - limits.minY + 1;
279
+ // If the data is wider than the mesh, center it using centerX
280
+ if (rangeX > mergeCount && limits.centerX !== undefined) {
281
+ originX = Math.floor(limits.centerX - (mergeCount / 2));
282
+ }
283
+ // If the data is taller than the mesh, center it using centerY
284
+ if (rangeY > mergeCount && limits.centerY !== undefined) {
285
+ originY = Math.floor(limits.centerY - (mergeCount / 2));
286
+ }
287
+ // --- Task 2: Iterate Grid Slots ---
288
+ // Instead of iterating tile coordinates, we iterate the target grid slots (0..mergeCount)
289
+ // and calculate which tile belongs there.
290
+ for (let i = 0; i < mergeCount; i++) {
291
+ for (let j = 0; j < mergeCount; j++) {
292
+ // Calculate actual Tile Coordinates
293
+ // Handle X Wrapping for Antimeridian
294
+ let tileX = (originX + i);
295
+ // JS modulo of negative numbers behaves oddly, ensure positive wrap
296
+ tileX = ((tileX % worldWidth) + worldWidth) % worldWidth;
297
+ const tileY = originY + j;
298
+ // --- Validity Check ---
299
+ // Check if this specific tileX/tileY is actually part of the visible map data
300
+ let isValidX = false;
301
+ if (limits.antimeridian) {
302
+ isValidX = tileX >= limits.minX || tileX <= limits.maxX;
303
+ }
304
+ else {
305
+ isValidX = tileX >= limits.minX && tileX <= limits.maxX;
306
+ }
307
+ const isValidY = tileY >= limits.minY && tileY <= limits.maxY;
308
+ if (!isValidX || !isValidY)
309
+ continue;
310
+ const key = keyMethod(tileX, tileY, zoom);
311
+ const tile = tilesMetaData.tileMap.get(key);
312
+ // Calculate mesh offset (target position in pixels/floats)
313
+ const meshOffsetX = i * (tileDimensionLength - 1);
314
+ const meshOffsetY = j * (tileDimensionLength - 1);
315
+ if (tile) {
316
+ // 1. Direct Tile Found
317
+ nearestValuePadding.insert(tile.x, tile.y); // Using original coordinates for padding logic
318
+ moveMeshToMergedMesh(mergedMesh, mergedMeshDimLength, tile.mesh, tileDimensionLength, meshOffsetX, meshOffsetY);
319
+ // Update BBox Limits
320
+ // We simply expand the LL/UR.
321
+ // Post-processing will fix the inverted X for antimeridian.
322
+ if (tile.bbox.ll.x < bboxLimit.ll.x)
323
+ bboxLimit.ll.x = tile.bbox.ll.x;
324
+ if (tile.bbox.ll.y < bboxLimit.ll.y)
325
+ bboxLimit.ll.y = tile.bbox.ll.y;
326
+ if (tile.bbox.ur.x > bboxLimit.ur.x)
327
+ bboxLimit.ur.x = tile.bbox.ur.x;
328
+ if (tile.bbox.ur.y > bboxLimit.ur.y)
329
+ bboxLimit.ur.y = tile.bbox.ur.y;
330
+ // Track clusters for antimeridian split
331
+ // High X values (East Cluster) -> Left side of visual boundary
332
+ // Low X values (West Cluster) -> Right side of visual boundary
333
+ if (limits.antimeridian) {
334
+ if (tileX >= limits.minX) {
335
+ if (tile.bbox.ll.x < eastClusterMinX)
336
+ eastClusterMinX = tile.bbox.ll.x;
337
+ }
338
+ else {
339
+ if (tile.bbox.ur.x > westClusterMaxX)
340
+ westClusterMaxX = tile.bbox.ur.x;
341
+ }
342
+ }
343
+ }
344
+ else {
345
+ // 2. Parent Tile Fallback
346
+ const parentTileCoord = calculateParentTile(tileX, tileY, zoom);
347
+ const parentKey = keyMethod(parentTileCoord.x, parentTileCoord.y, parentTileCoord.level);
348
+ const parentTile = tilesMetaData.tileMap.get(parentKey);
349
+ if (parentTile) {
350
+ const populatedMesh = populateTileIntoHigherZoomLevel(parentTile.mesh, tileDimensionLength, tileDimensionLength * 2 - 1);
351
+ // Adjust offset for parent logic
352
+ // If current tile is odd (right/bottom), the parent mesh drawing needs to shift back
353
+ // because 'populatedMesh' covers 2x2.
354
+ const parentDrawOffsetX = meshOffsetX - (tileX % 2) * (tileDimensionLength - 1);
355
+ const parentDrawOffsetY = meshOffsetY - (tileY % 2) * (tileDimensionLength - 1);
356
+ moveMeshToMergedMesh(mergedMesh, mergedMeshDimLength, populatedMesh, tileDimensionLength * 2 - 1, parentDrawOffsetX, parentDrawOffsetY);
357
+ // Padding logic for parents
358
+ const xP = parentTile.x * 2;
359
+ const yP = parentTile.y * 2;
360
+ for (let dx = 0; dx < 2; dx++) {
361
+ for (let dy = 0; dy < 2; dy++) {
362
+ nearestValuePadding.insert(xP + dx, yP + dy);
363
+ }
364
+ }
365
+ }
366
+ else {
367
+ // 3. Children Tile Fallback
368
+ const childrenTiles = [];
369
+ let anyChildren = 0;
370
+ for (let dx = 0; dx < 2; dx++) {
371
+ for (let dy = 0; dy < 2; dy++) {
372
+ const childX = tileX * 2 + dx;
373
+ const childY = tileY * 2 + dy;
374
+ const childKey = keyMethod(childX, childY, zoom + 1);
375
+ const childTile = tilesMetaData.tileMap.get(childKey);
376
+ if (childTile) {
377
+ anyChildren++;
378
+ childrenTiles.push(childTile.mesh);
379
+ }
380
+ else {
381
+ childrenTiles.push(undefined);
382
+ }
383
+ }
384
+ }
385
+ if (anyChildren > 0) {
386
+ nearestValuePadding.insert(tileX, tileY);
387
+ fillFromChildren(mergedMesh, mergedMeshDimLength, childrenTiles, tileDimensionLength, meshOffsetX, meshOffsetY);
388
+ }
389
+ }
390
+ }
391
+ }
392
+ }
393
+ // Post-Processing BBox for Antimeridian
394
+ if (limits.antimeridian) {
395
+ // Task: bbox.ll should contain lower-left of East Cluster, bbox.ur should contain upper-right of West Cluster
396
+ // This creates the condition ur.x < ll.x (e.g. 170 to -170)
397
+ // Only update if we actually found tiles in those clusters
398
+ if (eastClusterMinX !== Infinity)
399
+ bboxLimit.ll.x = eastClusterMinX;
400
+ if (westClusterMaxX !== -Infinity)
401
+ bboxLimit.ur.x = westClusterMaxX;
402
+ // console.log("Antimeridian BBox adjusted:", bboxLimit);
403
+ }
404
+ // We pad the merged mesh based on the VALID range we iterated.
405
+ // Since we iterate 0..mergeCount, the indices are implicitly 0..mergeCount
406
+ // However, the clamp function usually expects absolute coordinates.
407
+ // Given the new "Grid" approach, the mesh is always locally 0 to mergeCount in valid data.
408
+ // We pass the grid-relative limits to clamp.
409
+ nearestValuePadding.clamp(mergedMesh, 0, 0, mergeCount, mergeCount);
410
+ nearestValuePadding.clear();
411
+ // Calculate Cover Ratio
412
+ // How much of the mesh grid (mergeCount) is covered by actual data range?
413
+ const currentWidth = limits.antimeridian ? rangeX : (limits.maxX - limits.minX + 1);
414
+ const currentHeight = limits.maxY - limits.minY + 1;
415
+ const usedWidth = Math.min(mergeCount, currentWidth);
416
+ const usedHeight = Math.min(mergeCount, currentHeight);
417
+ const xRatio = calculateMergedMeshDimLength(usedWidth, tileDimensionLength) / mergedMeshDimLength;
418
+ const yRatio = calculateMergedMeshDimLength(usedHeight, tileDimensionLength) / mergedMeshDimLength;
419
+ result.push({ mesh: mergedMesh, bbox: bboxLimit, zoom: zoom, coverRatio: { x: xRatio, y: yRatio } });
420
+ }
421
+ return result;
422
+ }
423
+ export function mergeMeshes(tiles, mergeCount = 12, tileDimensionLength = 5, processLimit = 6, globe) {
424
+ // filter out tiles with NaN values
425
+ // return returnTop6tiles(tiles);
426
+ const tilesMetaData = createMapAndMetaData(tiles, globe);
427
+ const mergedTiles = mergeTiles(tilesMetaData, mergeCount, tileDimensionLength, processLimit);
428
+ return mergedTiles;
429
+ }