@pirireis/webglobeplugins 0.15.2-3.alpha → 0.15.3-alpha

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 (45) hide show
  1. package/Math/arc-generate-points copy.js +366 -0
  2. package/Math/arc.js +2 -1
  3. package/Math/circle-cdf-points.js +170 -1
  4. package/Math/circle.js +25 -0
  5. package/Math/globe-util/horizon-plane.js +112 -0
  6. package/Math/methods.js +2 -2
  7. package/Math/vec3.js +2 -6
  8. package/altitude-locator/draw-subset-obj.js +16 -0
  9. package/altitude-locator/plugin.js +1 -1
  10. package/bearing-line/plugin.js +2 -3
  11. package/package.json +1 -1
  12. package/point-tracks/plugin.js +22 -82
  13. package/programs/line-on-globe/lines-color-instanced-flat.js +1 -0
  14. package/programs/line-on-globe/linestrip/linestrip.js +28 -2
  15. package/programs/line-on-globe/paddings/paddings.js +1 -0
  16. package/programs/point-on-globe/element-globe-surface-glow.js +1 -0
  17. package/programs/rings/partial-ring/piece-of-pie copy.js +286 -0
  18. package/programs/totems/camerauniformblock.js +0 -7
  19. package/programs/totems/canvas-webglobe-info.js +9 -9
  20. package/range-tools-on-terrain/bearing-line/adapters.js +5 -8
  21. package/range-tools-on-terrain/bearing-line/plugin.js +20 -95
  22. package/range-tools-on-terrain/circle-line-chain/adapters.js +8 -15
  23. package/range-tools-on-terrain/circle-line-chain/chain-list-map.js +12 -16
  24. package/range-tools-on-terrain/circle-line-chain/plugin.js +11 -67
  25. package/range-tools-on-terrain/range-ring/adapters.js +6 -74
  26. package/range-tools-on-terrain/range-ring/plugin.js +7 -222
  27. package/range-tools-on-terrain/range-ring/types.js +1 -9
  28. package/semiplugins/lightweight/line-plugin.js +47 -65
  29. package/semiplugins/lightweight/piece-of-pie-plugin.js +18 -44
  30. package/semiplugins/shape-on-terrain/arc-plugin.js +100 -197
  31. package/semiplugins/shape-on-terrain/circle-plugin.js +90 -209
  32. package/semiplugins/shape-on-terrain/derived/padding-plugin.js +101 -0
  33. package/semiplugins/shape-on-terrain/one-degree-padding.js +85 -0
  34. package/util/account/single-attribute-buffer-management/buffer-manager.js +0 -10
  35. package/util/account/single-attribute-buffer-management/buffer-orchestrator.js +8 -145
  36. package/util/account/single-attribute-buffer-management/object-store.js +0 -7
  37. package/util/build-strategy/static-dynamic.js +1 -11
  38. package/util/check/typecheck.js +0 -12
  39. package/util/geometry/index.js +1 -2
  40. package/programs/totems/globe-changes.js +0 -59
  41. package/semiplugins/interface.js +0 -1
  42. package/semiplugins/shape-on-terrain/padding-1-degree.js +0 -538
  43. package/util/account/single-attribute-buffer-management/buffer-orchestrator1.js +0 -159
  44. package/util/frame-counter-trigger.js +0 -84
  45. package/write-text/context-text4.js +0 -140
@@ -0,0 +1,366 @@
1
+ // TODO: Delete this file if it is not needed anymore.
2
+ // import { normilze as vec3Normalize, dot as vec3Dot, cross as vec3Cross, scale as vec3Scale, add as vec3Add, sub as vec3Sub } from './vec3';
3
+ // --- Utility Functions for 3D Vector Operations ---
4
+ /**
5
+ * Normalizes a 3D vector to unit length.
6
+ * @param v The input vector.
7
+ * @returns The normalized vector. Returns [0,0,0] if the input vector is a zero vector.
8
+ */
9
+ function vec3Normalize(v) {
10
+ const len = Math.sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]);
11
+ if (len < 1e-9) { // Use a small epsilon to handle near-zero vectors
12
+ return [0, 0, 0];
13
+ }
14
+ return [v[0] / len, v[1] / len, v[2] / len];
15
+ }
16
+ /**
17
+ * Calculates the dot product of two 3D vectors.
18
+ * @param v1 The first vector.
19
+ * @param v2 The second vector.
20
+ * @returns The dot product.
21
+ */
22
+ function vec3Dot(v1, v2) {
23
+ return v1[0] * v2[0] + v1[1] * v2[1] + v1[2] * v2[2];
24
+ }
25
+ /**
26
+ * Calculates the cross product of two 3D vectors.
27
+ * @param v1 The first vector.
28
+ * @param v2 The second vector.
29
+ * @returns The cross product vector.
30
+ */
31
+ function vec3Cross(v1, v2) {
32
+ return [
33
+ v1[1] * v2[2] - v1[2] * v2[1],
34
+ v1[2] * v2[0] - v1[0] * v2[2],
35
+ v1[0] * v2[1] - v1[1] * v2[0]
36
+ ];
37
+ }
38
+ /**
39
+ * Scales a 3D vector by a scalar.
40
+ * @param v The input vector.
41
+ * @param s The scalar value.
42
+ * @returns The scaled vector.
43
+ */
44
+ function vec3Scale(v, s) {
45
+ return [v[0] * s, v[1] * s, v[2] * s];
46
+ }
47
+ /**
48
+ * Adds two 3D vectors.
49
+ * @param v1 The first vector.
50
+ * @param v2 The second vector.
51
+ * @returns The resulting vector.
52
+ */
53
+ function vec3Add(v1, v2) {
54
+ return [v1[0] + v2[0], v1[1] + v2[1], v1[2] + v2[2]];
55
+ }
56
+ /**
57
+ * Subtracts the second 3D vector from the first.
58
+ * @param v1 The first vector.
59
+ * @param v2 The second vector.
60
+ * @returns The resulting vector.
61
+ */
62
+ function vec3Sub(v1, v2) {
63
+ return [v1[0] - v2[0], v1[1] - v2[1], v1[2] - v2[2]];
64
+ }
65
+ /**
66
+ * Clamps a numerical value within a specified range.
67
+ * @param value The value to clamp.
68
+ * @param min The minimum allowed value.
69
+ * @param max The maximum allowed value.
70
+ * @returns The clamped value.
71
+ */
72
+ function clamp(value, min, max) {
73
+ return Math.max(min, Math.min(value, max));
74
+ }
75
+ function vec3Distance(v1, v2) {
76
+ const dx = v1[0] - v2[0];
77
+ const dy = v1[1] - v2[1];
78
+ const dz = v1[2] - v2[2];
79
+ return Math.sqrt(dx * dx + dy * dy + dz * dz);
80
+ }
81
+ /**
82
+ * Rotates a vector around a given axis by a specified angle using Rodrigues' rotation formula.
83
+ * The axis must be a unit vector for correct results.
84
+ * @param v The vector to rotate.
85
+ * @param axis The unit axis of rotation.
86
+ * @param angle The angle of rotation in radians.
87
+ * @returns The rotated vector.
88
+ */
89
+ function rotateVector(v, axis, angle) {
90
+ const cosAngle = Math.cos(angle);
91
+ const sinAngle = Math.sin(angle);
92
+ const oneMinusCos = 1.0 - cosAngle;
93
+ const dotAxisV = vec3Dot(axis, v);
94
+ const crossAxisV = vec3Cross(axis, v);
95
+ // Rodrigues' rotation formula:
96
+ // v' = v * cos(angle) + (axis x v) * sin(angle) + axis * (axis . v) * (1 - cos(angle))
97
+ const term1 = vec3Scale(v, cosAngle);
98
+ const term2 = vec3Scale(crossAxisV, sinAngle);
99
+ const term3 = vec3Scale(axis, dotAxisV * oneMinusCos);
100
+ return vec3Add(vec3Add(term1, term2), term3);
101
+ }
102
+ /**
103
+ * Solves a quadratic equation Ax^2 + Bx + C = 0 for x, returning a root within a specified range.
104
+ * Handles linear cases (A approx 0) and multiple roots, selecting the most appropriate one for CDF inversion.
105
+ * @param a Coefficient A.
106
+ * @param b Coefficient B.
107
+ * @param c Coefficient C.
108
+ * @param minVal The minimum expected value for the root.
109
+ * @param maxVal The maximum expected value for the root.
110
+ * @returns The selected root within the range, or null if no valid real root.
111
+ */
112
+ function solveQuadratic(a, b, c, minVal, maxVal) {
113
+ const epsilon = 1e-12; // Small value for floating point comparisons
114
+ // Case 1: Linear equation (A is close to zero)
115
+ if (Math.abs(a) < epsilon) {
116
+ if (Math.abs(b) < epsilon) {
117
+ // Both A and B are zero. If C is also zero, infinitely many solutions, pick minVal.
118
+ // Otherwise, no solutions.
119
+ return Math.abs(c) < epsilon ? minVal : null;
120
+ }
121
+ const x = -c / b;
122
+ // Check if the linear solution is within the expected range
123
+ return (x >= minVal - epsilon && x <= maxVal + epsilon) ? x : null;
124
+ }
125
+ // Case 2: Quadratic equation
126
+ const discriminant = b * b - 4 * a * c;
127
+ if (discriminant < -epsilon) { // No real roots (discriminant is significantly negative)
128
+ console.log("No real roots for the quadratic equation.");
129
+ return null;
130
+ }
131
+ if (discriminant < epsilon) { // One real root (discriminant is close to zero)
132
+ const x = -b / (2 * a);
133
+ return (x >= minVal - epsilon && x <= maxVal + epsilon) ? x : null;
134
+ }
135
+ // Case 3: Two distinct real roots
136
+ const sqrtDisc = Math.sqrt(discriminant);
137
+ const x1 = (-b + sqrtDisc) / (2 * a);
138
+ const x2 = (-b - sqrtDisc) / (2 * a);
139
+ const validX1 = (x1 >= minVal - epsilon && x1 <= maxVal + epsilon);
140
+ const validX2 = (x2 >= minVal - epsilon && x2 <= maxVal + epsilon);
141
+ if (validX1 && validX2) {
142
+ // If both roots are valid, pick the one that is logically correct for CDF inversion.
143
+ // For an increasing CDF, we generally want the smallest valid non-negative root.
144
+ return Math.min(x1, x2);
145
+ }
146
+ else if (validX1) {
147
+ return x1;
148
+ }
149
+ else if (validX2) {
150
+ return x2;
151
+ }
152
+ else {
153
+ return null; // No valid roots within the range
154
+ }
155
+ }
156
+ // --- Main Function for Arc Point Generation ---
157
+ /**
158
+ * Generates points on the shortest arc between p0 and p1 on a unit sphere.
159
+ * The arc is formed by rotating p0 around axisA. The density of points
160
+ * is higher closer to the attractionPoint.
161
+ *
162
+ * @param p0 The starting point of the arc (will be normalized).
163
+ * @param p1 The ending point of the arc (will be normalized).
164
+ * @param axisA The axis of rotation (will be normalized).
165
+ * @param attractionPoint The point on the unit sphere that attracts sampled points (will be normalized).
166
+ * @param pointCount The total number of points to generate on the arc, including p0 and p1.
167
+ * @param strength Controls the density bias. A value of 0 means uniform sampling.
168
+ * Higher positive values (e.g., 1 to 10) result in stronger attraction.
169
+ * @returns An array of `Vec3` representing the deterministically sampled points on the arc.
170
+ */
171
+ export function generateArcPoints(p0, p1, axisA, attractionPoint, pointCount, strength) {
172
+ const sampledPoints = [];
173
+ const epsilon = 1e-7; // General epsilon for vector comparisons
174
+ // 1. Normalize all input vectors
175
+ let nP0 = vec3Normalize(p0);
176
+ let nP1 = vec3Normalize(p1);
177
+ let nAxisA = vec3Normalize(axisA);
178
+ let nAttractionPoint = vec3Normalize(attractionPoint);
179
+ // Handle edge cases for pointCount
180
+ if (pointCount < 1) {
181
+ return sampledPoints;
182
+ }
183
+ if (pointCount === 1) {
184
+ sampledPoints.push(nP0);
185
+ return sampledPoints;
186
+ }
187
+ // 2. Determine the total rotation angle required to go from p0 to p1 around axisA
188
+ // Project p0 and p1 onto the plane perpendicular to axisA
189
+ const p0Projected = vec3Sub(nP0, vec3Scale(nAxisA, vec3Dot(nP0, nAxisA)));
190
+ const p1Projected = vec3Sub(nP1, vec3Scale(nAxisA, vec3Dot(nP1, nAxisA)));
191
+ const lenP0Proj = Math.sqrt(vec3Dot(p0Projected, p0Projected));
192
+ const lenP1Proj = Math.sqrt(vec3Dot(p1Projected, p1Projected));
193
+ // Handle cases where p0 or p1 are colinear with the rotation axis
194
+ if (lenP0Proj < epsilon || lenP1Proj < epsilon) {
195
+ // If start and end points are effectively the same (on or very near the axis)
196
+ if (Math.abs(vec3Dot(nP0, nP1) - 1.0) < epsilon) {
197
+ for (let i = 0; i < pointCount; i++) {
198
+ sampledPoints.push(nP0); // Return identical points as no meaningful arc exists
199
+ }
200
+ return sampledPoints;
201
+ }
202
+ else {
203
+ console.warn("generateArcPoints: p0 or p1 is colinear with axisA. Cannot form a valid arc by rotation around axisA to reach p1. Falling back to linear interpolation.");
204
+ // Fallback: simple linear interpolation and normalize
205
+ for (let i = 0; i < pointCount; i++) {
206
+ const t = i / (pointCount - 1);
207
+ const interpolated = vec3Add(vec3Scale(nP0, (1 - t)), vec3Scale(nP1, t));
208
+ sampledPoints.push(vec3Normalize(interpolated));
209
+ }
210
+ return sampledPoints;
211
+ }
212
+ }
213
+ const nP0Projected = vec3Normalize(p0Projected);
214
+ const nP1Projected = vec3Normalize(p1Projected);
215
+ // Calculate total rotation angle using atan2 for a signed angle
216
+ const crossProj = vec3Cross(nP0Projected, nP1Projected);
217
+ const totalRotationAngle = Math.atan2(vec3Dot(crossProj, nAxisA), vec3Dot(nP0Projected, nP1Projected));
218
+ // If total rotation angle is negligible, all points are essentially p0
219
+ if (Math.abs(totalRotationAngle) < epsilon) {
220
+ for (let i = 0; i < pointCount; i++) {
221
+ sampledPoints.push(nP0);
222
+ }
223
+ return sampledPoints;
224
+ }
225
+ // 3. Find alpha_A: the angle parameter (from p0) where the arc point is closest to attractionPoint
226
+ // We search over `t` from 0 to 1, and map to actual rotation angles.
227
+ let alpha_A = 0.0; // This will be the actual rotation angle
228
+ let minAngleToAttraction = Math.PI; // Initialize with max possible angle
229
+ // TODO: USE GEOMETRY INSTEAD OF MARKOV CHOICE
230
+ const testSteps = 1000; // Granularity for finding alpha_A
231
+ for (let i = 0; i <= testSteps; i++) {
232
+ const t_test = i / testSteps; // Normalized parameter [0, 1]
233
+ const currentAlpha = totalRotationAngle * t_test; // Actual rotation angle
234
+ const pArcTest = rotateVector(nP0, nAxisA, currentAlpha); // Point on arc
235
+ const dotProduct = clamp(vec3Dot(pArcTest, nAttractionPoint), -1.0, 1.0);
236
+ const currentAngle = Math.acos(dotProduct);
237
+ if (currentAngle < minAngleToAttraction) {
238
+ minAngleToAttraction = currentAngle;
239
+ alpha_A = currentAlpha;
240
+ }
241
+ }
242
+ // minAngleToAttraction = 0.0;
243
+ console.log("generated alpha_A:", alpha_A, "minAngleToAttraction:", minAngleToAttraction);
244
+ // 4. Define the PDF parameters (for normalized parameter t in [0,1])
245
+ // The density function for 't' (normalized angle from 0 to 1)
246
+ const minDensity = 1.0;
247
+ // Strength ensures positive density. Higher strength gives more pronounced peak.
248
+ const maxDensity = minDensity + Math.max(0, strength);
249
+ // Normalize alpha_A to the [0, 1] range for the PDF/CDF calculations
250
+ // This represents the peak position (t_peak) within the normalized parameter space.
251
+ const alpha_A_normalized = totalRotationAngle !== 0 ? clamp(alpha_A / totalRotationAngle, 0, 1) : 0;
252
+ // Normalization constant for the PDF (integral over [0,1] must be 1)
253
+ // Area of trapezoid = 0.5 * (base1 + base2) * height
254
+ // In our case, the "bases" are minDensity and maxDensity, "height" is 1 (the t-interval length)
255
+ const pdfArea = 0.5 * (minDensity + maxDensity);
256
+ const pdfNormalizationConstant = 1.0 / pdfArea;
257
+ // Calculate CDF value at the peak point (alpha_A_normalized)
258
+ // This splits the CDF into two regions for the quadratic solver
259
+ const cdfAtAlphaA_norm = pdfNormalizationConstant * (minDensity * alpha_A_normalized + 0.5 * (maxDensity - minDensity) * alpha_A_normalized);
260
+ // 5. Generate deterministic points using inverse transform sampling
261
+ for (let i = 0; i < pointCount; i++) {
262
+ // Generate uniformly spaced values `u` in [0, 1]
263
+ const u = i / (pointCount - 1);
264
+ let t_sampled; // This will be the sampled normalized parameter [0, 1]
265
+ if (u <= cdfAtAlphaA_norm) {
266
+ // Case 1: The sampled point falls in the first part of the PDF (0 to alpha_A_normalized)
267
+ // F(t) = normConst * (minDensity * t + 0.5 * (maxDensity - minDensity) / alpha_A_normalized * t^2)
268
+ // Rearrange to A*t^2 + B*t + C = 0 for solving:
269
+ const A = (alpha_A_normalized !== 0) ? pdfNormalizationConstant * 0.5 * (maxDensity - minDensity) / alpha_A_normalized : 0;
270
+ const B = pdfNormalizationConstant * minDensity;
271
+ const C = -u;
272
+ const result = solveQuadratic(A, B, C, 0, alpha_A_normalized);
273
+ // Fallback for unexpected null (e.g., numerical issues)
274
+ t_sampled = result !== null ? result : (u / (cdfAtAlphaA_norm || epsilon)) * alpha_A_normalized;
275
+ }
276
+ else {
277
+ // Case 2: The sampled point falls in the second part of the PDF (alpha_A_normalized to 1)
278
+ // F(t) - cdfAtAlphaA_norm = normConst * [ maxDensity * (t - alpha_A_normalized) - 0.5 * (maxDensity - minDensity) / (1 - alpha_A_normalized) * (t - alpha_A_normalized)^2 ]
279
+ // Let x = t - alpha_A_normalized. Solve for x: A'*x^2 + B'*x + C' = 0
280
+ const rangeAfterA = 1 - alpha_A_normalized;
281
+ const A_prime = (rangeAfterA !== 0) ? -pdfNormalizationConstant * 0.5 * (maxDensity - minDensity) / rangeAfterA : 0;
282
+ const B_prime = pdfNormalizationConstant * maxDensity;
283
+ const C_prime = -(u - cdfAtAlphaA_norm);
284
+ const result_x = solveQuadratic(A_prime, B_prime, C_prime, 0, rangeAfterA);
285
+ // Fallback for unexpected null
286
+ t_sampled = (result_x !== null ? alpha_A_normalized + result_x :
287
+ alpha_A_normalized + (u - cdfAtAlphaA_norm) / ((1 - cdfAtAlphaA_norm) || epsilon) * rangeAfterA);
288
+ }
289
+ // Ensure t_sampled is within [0, 1] due to potential float inaccuracies
290
+ t_sampled = clamp(t_sampled, 0, 1);
291
+ // Convert the normalized parameter 't_sampled' back to the actual rotation angle
292
+ const actualRotationAngle = totalRotationAngle * t_sampled;
293
+ // Rotate the starting point p0 by this angle around axisA to get the final point
294
+ const currentPoint = rotateVector(nP0, nAxisA, actualRotationAngle);
295
+ sampledPoints.push(currentPoint);
296
+ }
297
+ return sampledPoints;
298
+ }
299
+ // --- Example Usage (for demonstration and testing) ---
300
+ // Example 1: Basic arc, attraction point in the middle
301
+ const p0_ex1 = [1, 0, 0];
302
+ const p1_ex1 = [0, 1, 0]; // 90 deg rotation around Z-axis
303
+ const axisA_ex1 = [0, 0, 1];
304
+ const attractionPoint_ex1 = [Math.sqrt(0.5), Math.sqrt(0.5), 0]; // On the arc, middle of P0-P1
305
+ const numPoints_ex1 = 50;
306
+ const strength_ex1 = 100.0; // Strong attraction
307
+ console.log("--- Example 1: Attraction point in the middle of the arc ---");
308
+ const points1 = generateArcPoints(p0_ex1, p1_ex1, axisA_ex1, attractionPoint_ex1, numPoints_ex1, strength_ex1);
309
+ console.log(`Generated ${points1.length} points.`);
310
+ // To observe concentration, you might visualize these points or calculate their 't' parameter distribution.
311
+ // For console output, let's print a few:
312
+ console.log("First 5 points:", points1.slice(0, 5).map(p => p.map(coord => coord.toFixed(4))));
313
+ console.log("Last 5 points:", points1.slice(-5).map(p => p.map(coord => coord.toFixed(4))));
314
+ // Expected: Points should be denser around [0.707, 0.707, 0]
315
+ const sequentialDistances1 = points1.map((p, i) => {
316
+ if (i === 0)
317
+ return 0; // Skip the first point
318
+ return vec3Distance(points1[i - 1], p);
319
+ });
320
+ console.log("Sequential distances between points (should be roughly equal for uniform distribution):", sequentialDistances1.map(d => d.toFixed(4)));
321
+ // Example 2: Attraction point near p0
322
+ const p0_ex2 = [1, 0, 0];
323
+ const p1_ex2 = [0, 1, 0];
324
+ const axisA_ex2 = [0, 0, 1];
325
+ const attractionPoint_ex2 = [0.99, 0.01, 0]; // Very close to P0
326
+ const numPoints_ex2 = 50;
327
+ const strength_ex2 = 10.0; // Very strong attraction
328
+ console.log("\n--- Example 2: Attraction point near the start (p0) ---");
329
+ const points2 = generateArcPoints(p0_ex2, p1_ex2, axisA_ex2, attractionPoint_ex2, numPoints_ex2, strength_ex2);
330
+ console.log(`Generated ${points2.length} points.`);
331
+ console.log("First 5 points:", points2.slice(0, 5).map(p => p.map(coord => coord.toFixed(4))));
332
+ console.log("Last 5 points:", points2.slice(-5).map(p => p.map(coord => coord.toFixed(4))));
333
+ // Expected: Points should be denser near [1, 0, 0]
334
+ // Example 3: Attraction point away from the arc (expect less concentration)
335
+ const p0_ex3 = [1, 0, 0];
336
+ const p1_ex3 = [0, 1, 0];
337
+ const axisA_ex3 = [0, 0, 1];
338
+ const attractionPoint_ex3 = [0, 0, 1]; // North pole, away from the XY plane arc
339
+ const numPoints_ex3 = 50;
340
+ const strength_ex3 = 5.0;
341
+ console.log("\n--- Example 3: Attraction point away from the arc ---");
342
+ const points3 = generateArcPoints(p0_ex3, p1_ex3, axisA_ex3, attractionPoint_ex3, numPoints_ex3, strength_ex3);
343
+ console.log(`Generated ${points3.length} points.`);
344
+ console.log("First 5 points:", points3.slice(0, 5).map(p => p.map(coord => coord.toFixed(4))));
345
+ console.log("Last 5 points:", points3.slice(-5).map(p => p.map(coord => coord.toFixed(4))));
346
+ // Expected: Points should be relatively uniformly distributed, as no point on the arc is significantly closer.
347
+ // The "closest point" on the arc will likely be determined by its closest angular projection.
348
+ // Example 4: No attraction (uniform distribution)
349
+ const p0_ex4 = [1, 0, 0];
350
+ const p1_ex4 = [0, 1, 0];
351
+ const axisA_ex4 = [0, 0, 1];
352
+ const attractionPoint_ex4 = [Math.sqrt(1 / 2), Math.sqrt(1 / 2), 0]; // Irrelevant when strength is 0
353
+ const numPoints_ex4 = 50;
354
+ const strength_ex4 = 4.0; // No attraction (uniform)
355
+ console.log("\n--- Example 4: Uniform distribution (strength = 0) ---");
356
+ const points4 = generateArcPoints(p0_ex4, p1_ex4, axisA_ex4, attractionPoint_ex4, numPoints_ex4, strength_ex4);
357
+ console.log(`Generated ${points4.length} points.`);
358
+ console.log("First 5 points:", points4.slice(0, 5).map(p => p.map(coord => coord.toFixed(4))));
359
+ console.log("Last 5 points:", points4.slice(-5).map(p => p.map(coord => coord.toFixed(4))));
360
+ // Expected: Points should be uniformly spaced.
361
+ const sequentialDistances = points4.map((p, i) => {
362
+ if (i === 0)
363
+ return 0; // Skip the first point
364
+ return vec3Distance(points4[i - 1], p);
365
+ });
366
+ console.log("Sequential distances between points (should be roughly equal for uniform distribution):", sequentialDistances.map(d => d.toFixed(4)));
package/Math/arc.js CHANGED
@@ -143,7 +143,8 @@ function _populatePointsWithClosestPointInsideArc(out, arc, count, closestPoint)
143
143
  * @param {Vec3} cameraPosition - The position of the camera.
144
144
  * @param {number} quaternionReuseCount - The number of times to apply the same rotation before recalculating. Higher is faster but less accurate.
145
145
  */
146
- function _distanceSampling(out, count, inArc, cameraPosition = vec3create(0, 0, 0), quaternionReuseCount = 1) {
146
+ function _distanceSampling(out, count, inArc, cameraPosition = vec3create(0, 0, 0), // TODO
147
+ quaternionReuseCount = 1) {
147
148
  if (count === 0) {
148
149
  return;
149
150
  }
@@ -1,4 +1,168 @@
1
1
  import { RADIANS } from "./methods";
2
+ function createTemplate(intervalCount, strength = 1.0) {
3
+ const out = new Array(intervalCount);
4
+ const TOTAL = 1;
5
+ let cummulative = 0;
6
+ if (strength <= 0) {
7
+ // If strength is 0, distribute evenly.
8
+ const step = TOTAL / (intervalCount - 1);
9
+ for (let i = 0; i < intervalCount; i++) {
10
+ out[i] = cummulative;
11
+ cummulative += step;
12
+ }
13
+ out[intervalCount - 1] = TOTAL; // Ensure the last value is exactly TOTAL
14
+ return out;
15
+ }
16
+ // If strength is greater than 0, bias towards the start.
17
+ const weights = new Array(intervalCount);
18
+ let currentStep = 1;
19
+ let totalWeight = 0;
20
+ // Calculate weights for each interval, decreasing for later intervals.
21
+ for (let i = 0; i < intervalCount; i++) {
22
+ // Using (i + 1) in the denominator gives earlier intervals the highest weight.
23
+ totalWeight += currentStep;
24
+ weights[i] = totalWeight;
25
+ currentStep += strength;
26
+ }
27
+ // Distribute the total angle based on the weights.
28
+ for (let i = 0; i < intervalCount; i++) {
29
+ // Round to the nearest whole number for this interval.
30
+ out[i] = (weights[i] / totalWeight) * TOTAL;
31
+ }
32
+ if (out[intervalCount - 1] !== TOTAL) {
33
+ out[intervalCount - 1] = TOTAL;
34
+ }
35
+ // console.log("createTemplate", "strength", strength, "intervalCount", intervalCount, "out", out);
36
+ return out;
37
+ }
38
+ function interpolation(a, b, t) {
39
+ return a + (b - a) * t;
40
+ }
41
+ /**
42
+ * Populates the `out` array with values from the `template` array,
43
+ * distributing the surplus length as interpolated values between the template samples.
44
+ *
45
+ * @param out The destination array to be filled. Its length must be >= template.length.
46
+ * @param template An ordered array of numbers to be placed in the `out` array.
47
+ * @param strength A parameter controlling the distribution bias of surplus samples.
48
+ * - strength = 0: Surplus samples are distributed evenly.
49
+ * - strength > 0: Surplus samples are biased towards the start of the template.
50
+ * - Higher values create a stronger bias.
51
+ */
52
+ function increasePopulation(// TODO: THERE IS A BUG
53
+ out, template, strength = 1.0) {
54
+ const sourceLength = template.length;
55
+ const destinationLength = out.length;
56
+ const outLengthAtStart = out.length;
57
+ // --- Handle Edge Cases ---
58
+ // If the template is empty, there is nothing to interpolate from.
59
+ if (sourceLength === 0) {
60
+ return;
61
+ }
62
+ // If the template has only one value, fill the output array with that value.
63
+ if (sourceLength === 1) {
64
+ out.fill(template[0]);
65
+ return;
66
+ }
67
+ // If the destination is not larger than the source, just copy the template values.
68
+ if (destinationLength <= sourceLength) {
69
+ for (let i = 0; i < destinationLength; i++) {
70
+ out[i] = template[i];
71
+ }
72
+ return;
73
+ }
74
+ // --- Main Logic ---
75
+ const surplus = destinationLength - sourceLength;
76
+ const numGaps = sourceLength - 1;
77
+ // This array will hold the number of extra samples to add in each gap.
78
+ const surplusPerGap = new Array(numGaps).fill(0);
79
+ if (surplus > 0) {
80
+ // --- Step 1: Determine the distribution of surplus items ---
81
+ // If strength is 0, distribute surplus items as evenly as possible.
82
+ if (strength <= 0) {
83
+ const baseToAdd = Math.floor(surplus / numGaps);
84
+ const remainder = surplus % numGaps;
85
+ for (let i = 0; i < numGaps; i++) {
86
+ // Distribute the remainder one by one to the first gaps.
87
+ surplusPerGap[i] = baseToAdd + (i < remainder ? 1 : 0);
88
+ }
89
+ }
90
+ else {
91
+ // Biased Distribution: more items in earlier gaps.
92
+ const weights = new Array(numGaps);
93
+ let totalWeight = 0;
94
+ // A. Calculate a weight for each gap. The weight decreases for later gaps.
95
+ // The `strength` parameter makes this decay steeper.
96
+ for (let i = 0; i < numGaps; i++) {
97
+ // Using (i + 1) in the denominator gives earlier gaps (i=0) the highest weight.
98
+ const weight = Math.pow(1 / (i + 1), strength);
99
+ weights[i] = weight;
100
+ totalWeight += weight;
101
+ }
102
+ // B. Distribute the surplus based on the calculated weights.
103
+ // This method ensures the total distributed count equals the surplus.
104
+ let distributedCount = 0;
105
+ for (let i = 0; i < numGaps - 1; i++) {
106
+ const idealCount = (weights[i] / totalWeight) * surplus;
107
+ // Round to the nearest whole number for this gap.
108
+ const countForThisGap = Math.ceil(idealCount);
109
+ surplusPerGap[i] = countForThisGap;
110
+ distributedCount += countForThisGap;
111
+ }
112
+ // Assign the remainder to the last gap to guarantee the sum is correct.
113
+ //surplusPerGap[numGaps - 1] = surplus - distributedCount;
114
+ // add to first
115
+ const leftover = surplus - distributedCount;
116
+ if (leftover > 0) {
117
+ surplusPerGap[0] += leftover; // Add any leftover to the first gap.
118
+ }
119
+ console.log("leftover", leftover, "distributedCount", distributedCount, "surplus", surplus);
120
+ }
121
+ }
122
+ // --- Step 2: Populate the `out` array ---
123
+ let outIndex = 0;
124
+ for (let i = 0; i < surplusPerGap.length; i++) {
125
+ if (typeof surplusPerGap[i] !== "number" || isNaN(surplusPerGap[i]) || !isFinite(surplusPerGap[i])) {
126
+ console.warn("increasePopulation: Invalid surplusPerGap value at index", i, ":", surplusPerGap[i]);
127
+ }
128
+ }
129
+ for (let i = 0; i < sourceLength; i++) {
130
+ // A. Add the original template item.
131
+ out[outIndex++] = template[i];
132
+ // B. If this is not the last template item, fill the gap after it.
133
+ if (i < numGaps) {
134
+ const numToAdd = surplusPerGap[i];
135
+ if (numToAdd <= 0)
136
+ continue;
137
+ const startVal = template[i];
138
+ const endVal = template[i + 1];
139
+ // C. Add the interpolated ("surplus") items for this gap.
140
+ // The total number of intervals in this gap is numToAdd + 1.
141
+ const totalIntervals = numToAdd + 1;
142
+ for (let j = 1; j <= numToAdd; j++) {
143
+ const t = j / totalIntervals; // The interpolation factor (0 < t < 1)
144
+ // Linear interpolation: out = start * (1 - t) + end * t
145
+ const interpolatedValue = startVal * (1 - t) + endVal * t;
146
+ out[outIndex++] = interpolatedValue;
147
+ if (outIndex >= out.length) {
148
+ console.warn("increasePopulation: Output array overflow. Stopping early.");
149
+ console.warn("processeed item ratio:", i, "/", sourceLength);
150
+ let count = numToAdd - j;
151
+ console.log("count", count);
152
+ for (let _i = i; _i < sourceLength; _i++) {
153
+ count += surplusPerGap[_i];
154
+ }
155
+ console.warn("increasePopulation: Not enough space to add", count, "more items.");
156
+ return; // Prevent overflow if the output array is not large enough.
157
+ }
158
+ }
159
+ }
160
+ }
161
+ // --- Step 3: Ensure the output length is correct ---
162
+ if (outLengthAtStart !== out.length) {
163
+ console.warn("increasePopulation: Output length mismatch. Expected", outLengthAtStart, "but got", out.length);
164
+ }
165
+ }
2
166
  function createCummulativeTemplate(numberOfPoints, strength, denseRatio = 0.5 // Ratio of points to be densely packed at the start.
3
167
  ) {
4
168
  // Handle edge cases for the number of points.
@@ -75,4 +239,9 @@ function globeFindPointByPolarHalfCircle(out, globe, centerLong, centerLat, radi
75
239
  offset -= 2;
76
240
  }
77
241
  }
78
- export { createCummulativeTemplateStash, globeFindPointByPolar, globeFindPointByPolarHalfCircle };
242
+ export {
243
+ // createTemplate,
244
+ // increasePopulation,
245
+ // interpolation,
246
+ // createCummulativeTemplate,
247
+ createCummulativeTemplateStash, globeFindPointByPolar, globeFindPointByPolarHalfCircle };
package/Math/circle.js CHANGED
@@ -29,5 +29,30 @@ function createCircleClosestAzimuthAngleProperties(circle) {
29
29
  normal: normal,
30
30
  northPointProjectedToOriginPlaneNormalized: N,
31
31
  };
32
+ // const distance = normal[2]; //dot(normal, [0, 0, 1] as Vec3)
33
+ // const N: Vec3 = [0, 0, 0];
34
+ // if (Math.abs(distance) < 1e-6) {
35
+ // N[0] = -1;
36
+ // N[1] = 0;
37
+ // N[2] = 0;
38
+ // } else {
39
+ // // TODO: add cases for 8 parts of the sphere
40
+ // copy(N, normal);
41
+ // multiplyScalar(N, N, distance);
42
+ // if (N[2] >= 0) {
43
+ // N[0] = -N[0];
44
+ // N[1] = -N[1];
45
+ // N[2] = 1 - N[2];
46
+ // } else {
47
+ // N[2] = -N[2];
48
+ // N[0] = -N[0];
49
+ // N[1] = -N[1];
50
+ // }
51
+ // }
52
+ // normalize(N, N);
53
+ // return {
54
+ // normal: normal,
55
+ // northPointProjectedToOriginPlaneNormalized: N,
56
+ // }
32
57
  }
33
58
  export { closestAzimuthAngle, createCircleClosestAzimuthAngleProperties };