@protomaze/geometry 0.0.0-stage → 0.1.0

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 (118) hide show
  1. package/GeometryDemo.d.ts +1 -0
  2. package/GeometryDemo.js +1 -0
  3. package/README.md +294 -2
  4. package/common/Colors.d.ts +47 -0
  5. package/common/Colors.js +1 -0
  6. package/common/Disposables.d.ts +7 -0
  7. package/common/Disposables.js +1 -0
  8. package/data/Geometry.d.ts +62 -0
  9. package/data/Geometry.js +1 -0
  10. package/demo/DemoControls.d.ts +68 -0
  11. package/demo/DemoControls.js +1 -0
  12. package/demo/Town.d.ts +115 -0
  13. package/demo/Town.js +1 -0
  14. package/edit/CreateController.d.ts +101 -0
  15. package/edit/CreateController.js +1 -0
  16. package/edit/EditController.d.ts +121 -0
  17. package/edit/EditController.js +1 -0
  18. package/edit/EditHistory.d.ts +46 -0
  19. package/edit/EditHistory.js +1 -0
  20. package/edit/EditShape.d.ts +45 -0
  21. package/edit/EditShape.js +1 -0
  22. package/edit/GeometryController.d.ts +83 -0
  23. package/edit/GeometryController.js +1 -0
  24. package/edit/MeasureController.d.ts +102 -0
  25. package/edit/MeasureController.js +1 -0
  26. package/edit/Sketch.d.ts +73 -0
  27. package/edit/Sketch.js +1 -0
  28. package/edit/Snapper.d.ts +67 -0
  29. package/edit/Snapper.js +1 -0
  30. package/engine/GeometryEngine.d.ts +257 -0
  31. package/engine/GeometryEngine.js +1 -0
  32. package/engine/GeometryFrame.d.ts +91 -0
  33. package/engine/GeometryFrame.js +1 -0
  34. package/engine/GeometryOptions.d.ts +79 -0
  35. package/engine/GeometryOptions.js +1 -0
  36. package/engine/GeometryView.d.ts +192 -0
  37. package/engine/GeometryView.js +1 -0
  38. package/engine/Labels.d.ts +42 -0
  39. package/engine/Labels.js +1 -0
  40. package/engine/MapCamera.d.ts +78 -0
  41. package/engine/MapCamera.js +1 -0
  42. package/event/TypedEventEmitter.d.ts +13 -0
  43. package/event/TypedEventEmitter.js +1 -0
  44. package/index.d.ts +53 -0
  45. package/index.js +1 -0
  46. package/layers/AreaLayer.d.ts +36 -0
  47. package/layers/AreaLayer.js +1 -0
  48. package/layers/GeometryLayer.d.ts +312 -0
  49. package/layers/GeometryLayer.js +1 -0
  50. package/layers/LineLayer.d.ts +48 -0
  51. package/layers/LineLayer.js +1 -0
  52. package/layers/PointLayer.d.ts +42 -0
  53. package/layers/PointLayer.js +1 -0
  54. package/layers/SphereLayer.d.ts +25 -0
  55. package/layers/SphereLayer.js +1 -0
  56. package/layers/TubeLayer.d.ts +52 -0
  57. package/layers/TubeLayer.js +1 -0
  58. package/math/Boolean.d.ts +21 -0
  59. package/math/Boolean.js +1 -0
  60. package/math/FeatureIndex.d.ts +70 -0
  61. package/math/FeatureIndex.js +1 -0
  62. package/math/Geodesy.d.ts +29 -0
  63. package/math/Geodesy.js +1 -0
  64. package/math/Lines.d.ts +115 -0
  65. package/math/Lines.js +1 -0
  66. package/math/Measure.d.ts +71 -0
  67. package/math/Measure.js +1 -0
  68. package/math/Polygons.d.ts +59 -0
  69. package/math/Polygons.js +1 -0
  70. package/math/Projection.d.ts +25 -0
  71. package/math/Projection.js +1 -0
  72. package/math/Relations.d.ts +27 -0
  73. package/math/Relations.js +1 -0
  74. package/math/SpatialIndex.d.ts +36 -0
  75. package/math/SpatialIndex.js +1 -0
  76. package/math/Transform.d.ts +36 -0
  77. package/math/Transform.js +1 -0
  78. package/math/Triangulate.d.ts +19 -0
  79. package/math/Triangulate.js +1 -0
  80. package/math/Vector.d.ts +24 -0
  81. package/math/Vector.js +1 -0
  82. package/package.json +76 -4
  83. package/react/ReactGeometry.d.ts +35 -0
  84. package/react/ReactGeometry.js +1 -0
  85. package/three/CanvasGeometryEngine.d.ts +79 -0
  86. package/three/CanvasGeometryEngine.js +1 -0
  87. package/three/DensityMap.d.ts +31 -0
  88. package/three/DensityMap.js +1 -0
  89. package/three/FeatureLook.d.ts +191 -0
  90. package/three/FeatureLook.js +1 -0
  91. package/three/Ground.d.ts +54 -0
  92. package/three/Ground.js +1 -0
  93. package/three/Halo.d.ts +26 -0
  94. package/three/Halo.js +1 -0
  95. package/three/HostedGeometryEngine.d.ts +57 -0
  96. package/three/HostedGeometryEngine.js +1 -0
  97. package/three/RiaGeometryEngine.d.ts +48 -0
  98. package/three/RiaGeometryEngine.js +1 -0
  99. package/three/Shading.d.ts +42 -0
  100. package/three/Shading.js +1 -0
  101. package/three/Sky.d.ts +27 -0
  102. package/three/Sky.js +1 -0
  103. package/three/Tsl.d.ts +47 -0
  104. package/three/Tsl.js +1 -0
  105. package/three/primitives/Body.d.ts +82 -0
  106. package/three/primitives/Body.js +1 -0
  107. package/three/primitives/GpuAreas.d.ts +72 -0
  108. package/three/primitives/GpuAreas.js +1 -0
  109. package/three/primitives/GpuIcons.d.ts +112 -0
  110. package/three/primitives/GpuIcons.js +1 -0
  111. package/three/primitives/GpuLines.d.ts +198 -0
  112. package/three/primitives/GpuLines.js +1 -0
  113. package/three/primitives/GpuSpheres.d.ts +55 -0
  114. package/three/primitives/GpuSpheres.js +1 -0
  115. package/three/primitives/GpuTubes.d.ts +125 -0
  116. package/three/primitives/GpuTubes.js +1 -0
  117. package/three/primitives/IconAtlas.d.ts +12 -0
  118. package/three/primitives/IconAtlas.js +1 -0
@@ -0,0 +1,102 @@
1
+ import type { GeometryFeature } from '../data/Geometry';
2
+ import type { GeometryLayer } from '../layers/GeometryLayer';
3
+ import type { Vec3 } from '../math/Vector';
4
+ import { ControllerHost, ControllerPointer, GeometryController } from './GeometryController';
5
+ import { SketchTheme } from './Sketch';
6
+ import { SnapOptions } from './Snapper';
7
+ /**
8
+ * What is measured: a distance along points, an area inside them, the height between two, or
9
+ * the clearance between two features - the nearest their geometries come in 3D.
10
+ */
11
+ export type MeasureMode = 'distance' | 'area' | 'height' | 'clearance';
12
+ export interface MeasureControllerOptions {
13
+ mode: MeasureMode;
14
+ /** Snapping to features' vertices and edges; false for none. */
15
+ snapping?: SnapOptions | false;
16
+ /** Points placed on what is drawn under the pointer - a pipe, a roof - where nothing is snapped to. On by default. */
17
+ surface?: boolean;
18
+ /** The height measured on where nothing is under the pointer: the camera target's by default. */
19
+ z?: number;
20
+ /**
21
+ * For clearances: how far a feature reaches out from its geometry - a pipe's radius - so the
22
+ * clearance is between their surfaces. 0 by default: between their axes.
23
+ */
24
+ radius?: (layer: GeometryLayer<any, any>, feature: GeometryFeature) => number;
25
+ theme?: Partial<SketchTheme>;
26
+ }
27
+ /** A measurement as it stands. */
28
+ export interface Measurement {
29
+ mode: MeasureMode;
30
+ points: Vec3[];
31
+ /** Along the points, in 3D; and across the map; and from the first height to the last. */
32
+ length?: number;
33
+ horizontal?: number;
34
+ rise?: number;
35
+ slope?: number;
36
+ area?: number;
37
+ perimeter?: number;
38
+ /** For clearances: the two features, the nearest points, and the gap between them. */
39
+ clearance?: number;
40
+ a?: {
41
+ layer: GeometryLayer<any, any>;
42
+ feature: GeometryFeature;
43
+ point: Vec3;
44
+ };
45
+ b?: {
46
+ layer: GeometryLayer<any, any>;
47
+ feature: GeometryFeature;
48
+ point: Vec3;
49
+ };
50
+ /** Whether it is finished: the next click starts another. */
51
+ done: boolean;
52
+ }
53
+ export interface MeasureControllerEvents {
54
+ change: Measurement | null;
55
+ }
56
+ /**
57
+ * Measures on the view: click points - on the ground, snapped to a vertex or an edge, or on
58
+ * whatever surface is drawn there, picked on the GPU - and read lengths, heights, slopes and
59
+ * areas beside them; or click two features for the clearance between them in 3D, the nearest
60
+ * points joined. Double-click or Enter finishes a measurement, Backspace takes a point back,
61
+ * Escape clears.
62
+ */
63
+ export declare class MeasureController extends GeometryController<MeasureControllerEvents> {
64
+ private options;
65
+ private readonly sketch;
66
+ private snapper;
67
+ private points;
68
+ private hover;
69
+ private done;
70
+ private picked;
71
+ private clearance;
72
+ /** Clicks are placed in order, each waiting for its pick. */
73
+ private queue;
74
+ constructor(options: MeasureControllerOptions);
75
+ get mode(): MeasureMode;
76
+ setMode(mode: MeasureMode): void;
77
+ /** Clears the measurement. */
78
+ clear(): void;
79
+ protected onAttach(host: ControllerHost): void;
80
+ protected onDetach(host: ControllerHost): void;
81
+ onPointerMove(event: ControllerPointer): boolean;
82
+ private pointer;
83
+ private hoverPicking;
84
+ /**
85
+ * The pointer's point on what is drawn under it - one pick at a time, the latest position
86
+ * picked next - so the line to the pointer runs to the roof or the pipe a click would land on.
87
+ */
88
+ private pickHover;
89
+ onPointerLeave(): void;
90
+ onClick(event: ControllerPointer): boolean;
91
+ onDoubleClick(): boolean;
92
+ onKeyDown(event: KeyboardEvent): boolean;
93
+ private place;
94
+ /** Whether `p` lies further from the camera than `surface`, by more than a little. */
95
+ private behind;
96
+ private finish;
97
+ private measureClearance;
98
+ private locate;
99
+ /** The measurement as it stands, the pointer's point included until it is done. */
100
+ measurement(): Measurement | null;
101
+ private render;
102
+ }
@@ -0,0 +1 @@
1
+ import{formatArea as t,formatLength as e,formatSlope as i}from"../engine/Labels.js";import{area as s,distance as n,distance2D as o,pathLength as h,perimeter as r,pointOnSurface as a,slope as p}from"../math/Measure.js";import{geometryDistance as c}from"../math/Relations.js";import{snapRole as l}from"./CreateController.js";import{GeometryController as d}from"./GeometryController.js";import{Sketch as u,SKETCH_THEME as f}from"./Sketch.js";import{Snapper as m}from"./Snapper.js";export class MeasureController extends d{constructor(t){super(),this.options=t,this.snapper=null,this.points=[],this.hover=null,this.done=!1,this.picked=[],this.clearance=null,this.queue=Promise.resolve(),this.pointer=null,this.hoverPicking=!1,this.sketch=new u({...f,...t.theme}),this.cursor="crosshair"}get mode(){return this.options.mode}setMode(t){this.options={...this.options,mode:t},this.clear()}clear(){this.points=[],this.picked=[],this.clearance=null,this.done=!1,this.render()}onAttach(t){this.sketch.attach(t),!1!==this.options.snapping&&(this.snapper=new m(t,this.options.snapping??{}),this.snapper.warm()),this.render()}onDetach(t){this.sketch.detach(),this.snapper?.dispose(),this.snapper=null,t.labels?.clear("measure"),this.points=[],this.picked=[],this.clearance=null}onPointerMove(t){return"clearance"!==this.options.mode&&(this.hover=this.done?null:this.locate(t),this.render(),this.pickHover(t),!0)}pickHover(t){this.pointer={x:t.x,y:t.y};const e=this.host;if(!e||this.done||!1===this.options.surface||this.hoverPicking)return;this.hoverPicking=!0;const{x:i,y:s}=this.pointer;e.pickAt(i,s).then(e=>{this.hoverPicking=!1;const n=this.pointer;if(!n||this.done||!this.host)return;if(n.x!==i||n.y!==s)return void this.pickHover({...t,x:n.x,y:n.y});const o=this.hover,h=o&&("vertex"===o.kind||"edge"===o.kind||"self"===o.kind);!e||h&&!this.behind(o.point,e.point)||(this.hover={point:e.point,kind:"none"},this.render())},()=>{this.hoverPicking=!1})}onPointerLeave(){this.hover=null,this.render()}onClick(t){if(0!==t.button)return!1;const e=this.host;if(!e)return!0;this.done&&(this.points=[],this.picked=[],this.clearance=null,this.done=!1);const i=this.locate(t),s="clearance"===this.options.mode||!1!==this.options.surface;return this.queue=this.queue.then(async()=>{const n=s?await e.pickAt(t.x,t.y):null;this.place(i,n)}),!0}onDoubleClick(){return"clearance"===this.options.mode||(this.queue=this.queue.then(()=>{const t=this.points.length;t>=2&&n(this.points[t-1],this.points[t-2])<1e-6&&this.points.pop(),this.finish()})),!0}onKeyDown(t){return"Escape"===t.key?(0!==this.points.length||0!==this.picked.length)&&(this.clear(),!0):"Enter"===t.key?(this.finish(),!0):("Backspace"===t.key||"Delete"===t.key)&&(0!==this.points.length&&!this.done&&(this.points.pop(),this.render(),!0))}place(t,e){const i=this.options.mode;if("clearance"===i){if(!e)return;if(this.picked.length>=2&&(this.picked=[],this.clearance=null,this.done=!1),1===this.picked.length&&this.picked[0].layer===e.layer&&this.picked[0].feature.id===e.id)return;return this.picked.push({layer:e.layer,feature:e.feature,point:e.point}),2===this.picked.length&&this.measureClearance(),void this.render()}let s=t?.point??null;const n=t&&("vertex"===t.kind||"edge"===t.kind||"self"===t.kind);!e||n&&!this.behind(t.point,e.point)||(s=e.point),s&&(this.points.push([...s]),"height"===i&&this.points.length>=2&&(this.done=!0),this.render())}behind(t,e){const i=this.host;if(!i||i.camera.orthographic)return!1;const{f:s,eye:n}=i.camera.basis(),o=t=>(t[0]-n[0])*s[0]+(t[1]-n[1])*s[1]+(t[2]-n[2])*s[2],h=o(e);return o(t)>h+Math.max(.3,.01*h)}finish(){const t="area"===this.options.mode?3:2;this.points.length>=t&&(this.done=!0),this.hover=null,this.render()}measureClearance(){const[t,e]=this.picked;if(!t.feature.geometry||!e.feature.geometry)return;const i=c(t.feature.geometry,e.feature.geometry,3);if(!Number.isFinite(i.distance))return;const s=this.options.radius?.(t.layer,t.feature)??0,n=this.options.radius?.(e.layer,e.feature)??0;this.clearance={a:i.pointA,b:i.pointB,gap:Math.max(0,i.distance-s-n)},this.done=!0}locate(t){const e=this.host;if(!e)return null;const i=this.options.z??e.camera.state.target[2],s=this.points[this.points.length-1]??null;if(this.snapper)return this.snapper.snap(t.x,t.y,t.shift,{z:i,from:s});const n=e.toGround(t.x,t.y,i);return n?{point:n,kind:"none"}:null}measurement(){const t=this.options.mode;if("clearance"===t){if(0===this.picked.length)return null;const[e,i]=this.picked;return{mode:t,points:this.clearance?[this.clearance.a,this.clearance.b]:[],clearance:this.clearance?.gap,a:e,b:i,done:this.done}}const e=!this.done&&this.hover?[...this.points,this.hover.point]:[...this.points];if(0===e.length)return null;const i=e[0],n=e[e.length-1],o={mode:t,points:e,done:this.done};if(o.length=h(e),o.horizontal=h(e,2),o.rise=n[2]-i[2],o.slope=p(i,n),"area"===t&&e.length>=3){const t={type:"Polygon",coordinates:[[...e,e[0]]]};o.area=s(t),o.perimeter=r(t)}return o}render(){const s=this.host;if(!s)return;const h=this.options.mode,r=this.measurement(),c={fills:[],lines:[],points:[]},d=[];if("clearance"===h)if(this.picked.forEach(t=>c.points.push({position:t.point,role:"vertex"})),this.clearance){const{a:t,b:i,gap:s}=this.clearance;c.lines.push({coordinates:[t,i],role:"measure"}),c.points.push({position:t,role:"active"},{position:i,role:"active"}),d.push({id:"gap",position:g(t,i),text:`${e(s)} clear`,kind:"measure",anchor:"left",offset:[14,-10]});const n=Math.abs(t[2]-i[2]);n>.005&&d.push({id:"dz",position:g(t,i),text:`${e(n)} apart in height`,kind:"info",anchor:"left",offset:[14,12]})}else 1===this.picked.length&&d.push({id:"hint",position:this.picked[0].point,text:"Now click the second",kind:"info",offset:[0,-22]});else if(r){const s=r.points;"area"===h&&s.length>=3&&c.fills.push({rings:[[...s,s[0]]],role:"fill"});const u=this.points;if(u.length>=2&&c.lines.push({coordinates:"area"===h&&this.done?[...u,u[0]]:u,role:"measure"}),!this.done&&this.hover&&u.length>=1&&(c.lines.push({coordinates:[u[u.length-1],this.hover.point],role:"rubber"}),"area"===h&&u.length>=2&&c.lines.push({coordinates:[this.hover.point,u[0]],role:"guide"})),u.forEach(t=>c.points.push({position:t,role:"vertex"})),!this.done&&this.hover&&c.points.push({position:this.hover.point,role:l(this.hover)}),"height"===h&&s.length>=2){const[t,h]=[s[0],s[1]],[r,a]=t[2]<=h[2]?[t,h]:[h,t],l=[r[0],r[1],a[2]];c.lines.push({coordinates:[r,l],role:"guide"},{coordinates:[l,a],role:"guide"}),d.push({id:"rise",position:g(r,l),text:`↕ ${e(Math.abs(h[2]-t[2]))}`,kind:"measure",offset:[34,0]}),d.push({id:"across",position:g(l,a),text:`↔ ${e(o(t,h))}`,kind:"segment"}),d.push({id:"slope",position:g(t,h),text:`${e(n(t,h))} · ${i(p(t,h))}`,kind:"info",offset:[0,20]})}else if("distance"===h||"area"===h){const i="area"===h&&s.length>=3?[[s[s.length-1],s[0]]]:[];if([...s.slice(1).map((t,e)=>[s[e],t]),...i].forEach(([t,i],s)=>{const o=n(t,i);o>0&&d.push({id:`s${s}`,position:g(t,i),text:e(o),kind:"segment"})}),"area"===h&&void 0!==r.area&&s.length>=3){const i=a({type:"Polygon",coordinates:[[...s,s[0]]]});i&&d.push({id:"area",position:i,text:`${t(r.area)} · ${e(r.perimeter??0)} round`,kind:"measure"})}else if("distance"===h&&s.length>=2){const t=r.rise??0,i=Math.abs(t)>.005?`${e(r.length??0)} · ${e(r.horizontal??0)} across · ${t>=0?"+":""}${e(t)}`:e(r.length??0);d.push({id:"total",position:s[s.length-1],text:i,kind:"measure",offset:[0,-24]})}}}this.sketch.set(c),s.labels?.set("measure",d),s.requestRepaint(),this.emit("change",r)}}function g(t,e){return[(t[0]+e[0])/2,(t[1]+e[1])/2,((t[2]??0)+(e[2]??0))/2]}
@@ -0,0 +1,73 @@
1
+ import type { ColorLike } from '../common/Colors';
2
+ import type { Position } from '../data/Geometry';
3
+ import { AreaLayer } from '../layers/AreaLayer';
4
+ import { LineLayer } from '../layers/LineLayer';
5
+ import { PointLayer } from '../layers/PointLayer';
6
+ import type { ControllerHost } from './GeometryController';
7
+ /** The colours a sketch is drawn in. */
8
+ export interface SketchTheme {
9
+ /** The shape's edges and the line being drawn. */
10
+ stroke: ColorLike;
11
+ /** The inside of an area being drawn. */
12
+ fill: ColorLike;
13
+ /** Vertex handles, and the border round them. */
14
+ vertex: ColorLike;
15
+ border: ColorLike;
16
+ /** The vertex pointed at or dragged; the rotate handle. */
17
+ active: ColorLike;
18
+ /** What the pointer snapped to. */
19
+ snap: ColorLike;
20
+ /** A shape that cannot be: crossing edges. */
21
+ invalid: ColorLike;
22
+ /** Construction lines: the rubber band's guides, a transform's box. */
23
+ guide: ColorLike;
24
+ }
25
+ export declare const SKETCH_THEME: SketchTheme;
26
+ export type SketchLineRole = 'edge' | 'rubber' | 'guide' | 'invalid' | 'measure';
27
+ export type SketchPointRole = 'vertex' | 'mid' | 'active' | 'snap-vertex' | 'snap-edge' | 'snap-other' | 'center' | 'rotate' | 'scale' | 'point';
28
+ export type SketchFillRole = 'fill' | 'invalid';
29
+ export interface SketchLine {
30
+ coordinates: readonly Position[];
31
+ role: SketchLineRole;
32
+ }
33
+ export interface SketchPoint {
34
+ position: Position;
35
+ role: SketchPointRole;
36
+ }
37
+ export interface SketchFill {
38
+ rings: readonly (readonly Position[])[];
39
+ role: SketchFillRole;
40
+ }
41
+ /** What a sketch shows: fills under lines under points. */
42
+ export interface SketchContent {
43
+ fills?: readonly SketchFill[];
44
+ lines?: readonly SketchLine[];
45
+ points?: readonly SketchPoint[];
46
+ }
47
+ /**
48
+ * What a controller draws while it works - the shape so far, the rubber band to the pointer,
49
+ * vertex handles, what the pointer snapped to - in three overlay layers over the view: fills,
50
+ * lines, points. Setting new content changes their features in place, keeping their shaders:
51
+ * a drag redraws a few buffers a frame.
52
+ */
53
+ export declare class Sketch {
54
+ readonly theme: SketchTheme;
55
+ readonly fills: AreaLayer;
56
+ readonly lines: LineLayer;
57
+ readonly points: PointLayer;
58
+ private host;
59
+ private last;
60
+ constructor(theme?: SketchTheme);
61
+ attach(host: ControllerHost): void;
62
+ private warming;
63
+ /**
64
+ * Something drawn - unseen - as soon as the sketch is in a view, then taken away: its shaders
65
+ * compile now, not at the first click. Emptied, the layers keep them.
66
+ */
67
+ private warm;
68
+ detach(): void;
69
+ /** Shows this, and nothing of what was shown before. Layers whose content is unchanged are left alone. */
70
+ set(content: SketchContent): void;
71
+ clear(): void;
72
+ private update;
73
+ }
package/edit/Sketch.js ADDED
@@ -0,0 +1 @@
1
+ import{AreaLayer as e}from"../layers/AreaLayer.js";import{LineLayer as s}from"../layers/LineLayer.js";import{PointLayer as i}from"../layers/PointLayer.js";export const SKETCH_THEME={stroke:"#22d3ee",fill:"#22d3ee2e",vertex:"#ffffff",border:"#0b1220",active:"#22d3ee",snap:"#ff3df0",invalid:"#ff4d6d",guide:"#ffffffaa"};const t={vertex:{shape:"circle",size:11,color:"vertex"},point:{shape:"circle",size:13,color:"stroke"},mid:{shape:"circle",size:8,color:"vertex",opacity:.55},active:{shape:"circle",size:15,color:"active"},"snap-vertex":{shape:"ring",size:22,color:"snap"},"snap-edge":{shape:"diamond",size:15,color:"snap"},"snap-other":{shape:"cross",size:14,color:"snap"},center:{shape:"cross",size:14,color:"guide"},rotate:{shape:"circle",size:13,color:"active"},scale:{shape:"square",size:11,color:"vertex"}};export class Sketch{constructor(r=SKETCH_THEME){this.theme=r,this.host=null,this.last={fills:"",lines:"",points:""},this.warming=!1;const o=r;this.fills=new e({id:"sketch-fills",outlines:!1,pickable:!1,style:e=>{return{color:"invalid"===e.properties.role?(s=o.invalid,i="33","string"==typeof s&&/^#[0-9a-f]{6}$/i.test(s)?s+i:s):o.fill};var s,i}}),this.lines=new s({id:"sketch-lines",mode:"space",pickable:!1,style:e=>{switch(e.properties.role){case"rubber":return{color:o.stroke,width:2,dashed:!0,arrow:!1};case"guide":return{color:o.guide,width:1.25,dashed:!0,arrow:!1};case"invalid":return{color:o.invalid,width:2.5,arrow:!1};case"measure":return{color:o.stroke,width:2.25,arrow:!1};default:return{color:o.stroke,width:2.5,arrow:!1}}}}),this.points=new i({id:"sketch-points",pickable:!1,depthTest:!1,border:1.5,style:e=>{const s=t[e.properties.role]??t.vertex;return{shape:s.shape,size:s.size,color:o[s.color],opacity:s.opacity}}})}attach(e){this.host!==e&&(this.detach(),this.host=e,e.addOverlay(this.fills),e.addOverlay(this.lines),e.addOverlay(this.points),this.warm(e))}warm(e){if(this.points.primitive)return;const s=e.camera.state.target,i=[s[0],s[1],s[2]],t=[s[0]+.01,s[1],s[2]],r=[s[0],s[1]+.01,s[2]];this.set({fills:[{rings:[[i,t,r,i]],role:"fill"}],lines:[{coordinates:[i,t],role:"edge"}],points:[{position:i,role:"vertex"}]}),this.warming=!0,[this.fills,this.lines,this.points].forEach(e=>e.setOpacity(0));const o=this.points.on("build",()=>{o(),[this.fills,this.lines,this.points].forEach(e=>e.setOpacity(1)),this.warming&&this.clear(),this.warming=!1})}detach(){const e=this.host;e&&(e.removeOverlay(this.fills),e.removeOverlay(this.lines),e.removeOverlay(this.points),this.host=null)}set(e){this.warming=!1,[this.fills,this.lines,this.points].forEach(e=>e.setOpacity(1));const s=(e.fills??[]).filter(e=>e.rings.length>0&&e.rings[0].length>=3).map((e,s)=>({id:`fill-${s}`,geometry:{type:"Polygon",coordinates:e.rings},properties:{role:e.role}})),i=(e.lines??[]).filter(e=>e.coordinates.length>=2).map((e,s)=>({id:`line-${s}`,geometry:{type:"LineString",coordinates:e.coordinates},properties:{role:e.role}})),t=(e.points??[]).map((e,s)=>({id:`point-${s}`,geometry:{type:"Point",coordinates:e.position},properties:{role:e.role}}));this.update(this.fills,s,"fills"),this.update(this.lines,i,"lines"),this.update(this.points,t,"points")}clear(){this.set({})}update(e,s,i){const t=JSON.stringify(s.map(e=>[e.geometry,e.properties.role]));t!==this.last[i]&&(this.last[i]=t,e.setFeatures(s))}}
@@ -0,0 +1,67 @@
1
+ import type { GeometryFeature, GeometryId, Position } from '../data/Geometry';
2
+ import type { GeometryLayer } from '../layers/GeometryLayer';
3
+ import type { Vec3 } from '../math/Vector';
4
+ import type { ControllerHost } from './GeometryController';
5
+ /** What a drawn or moved point snaps to. */
6
+ export interface SnapOptions {
7
+ /** The layers snapped to: these, or every visible one (`'visible'`, the default). */
8
+ layers?: readonly GeometryLayer<any, any>[] | 'visible';
9
+ /** To other features' vertices; on by default. */
10
+ vertices?: boolean;
11
+ /** To other features' edges and lines; on by default. */
12
+ edges?: boolean;
13
+ /** How near, in view pixels; 12 by default. */
14
+ tolerance?: number;
15
+ /** A grid of this spacing in world units, where nothing else is near; none by default. */
16
+ grid?: number | null;
17
+ /** With Shift held, the way from the last point turned to a multiple of this many degrees; 15 by default, null for never. */
18
+ angle?: number | null;
19
+ }
20
+ /** How a point was snapped: to a vertex, an edge, one of the shape's own vertices, the grid, an angle, or not at all. */
21
+ export type SnapKind = 'vertex' | 'edge' | 'self' | 'grid' | 'angle' | 'none';
22
+ export interface SnapResult {
23
+ point: Vec3;
24
+ kind: SnapKind;
25
+ /** The layer and feature snapped to. */
26
+ layer?: GeometryLayer<any, any>;
27
+ feature?: GeometryFeature;
28
+ /** The shape's own vertex snapped to (`self`): its index in `own`. */
29
+ own?: number;
30
+ }
31
+ /** What a snap is for: the level drawn on, the shape's own vertices, the point before, what to leave out. */
32
+ export interface SnapContext {
33
+ /** The height of the level drawn on, where nothing is snapped to. */
34
+ z: number;
35
+ /** The shape's own vertices: the first of a ring to close it, the last of a line to end it. */
36
+ own?: readonly Position[];
37
+ /** The point before, for Shift's angles. */
38
+ from?: Position | null;
39
+ /** A feature not to snap to: the one being edited. */
40
+ exclude?: {
41
+ layer: GeometryLayer<any, any>;
42
+ id: GeometryId;
43
+ } | null;
44
+ }
45
+ /**
46
+ * Snapping in the view's own terms: what is within so many pixels of the pointer on screen,
47
+ * however deep it lies - a vertex before an edge, the shape's own vertices before both. Each
48
+ * layer's features are indexed once (`FeatureIndex`), again when they change; the candidates
49
+ * near the pointer's ray are weighed by where they show on screen, so a pipe 3 m down snaps
50
+ * where it is seen, not where the ground under the pointer is.
51
+ */
52
+ export declare class Snapper {
53
+ private readonly host;
54
+ options: SnapOptions;
55
+ private readonly indices;
56
+ private prebuild;
57
+ constructor(host: ControllerHost, options?: SnapOptions);
58
+ /** Indexes the layers snapped to while nothing else is going on, so the first snap does not wait. */
59
+ warm(): void;
60
+ /** The point for a view position: snapped, or on the level `context.z`. Null where the pointer is above the horizon. */
61
+ snap(x: number, y: number, shift: boolean, context: SnapContext): SnapResult | null;
62
+ /** Forgets a layer's index - or every one - to index again at the next snap. */
63
+ invalidate(layer?: GeometryLayer<any, any>): void;
64
+ dispose(): void;
65
+ private layers;
66
+ private indexOf;
67
+ }
@@ -0,0 +1 @@
1
+ import{FeatureIndex as t}from"../math/FeatureIndex.js";import{segmentApproach as i}from"../math/Lines.js";export class Snapper{constructor(t,i={}){this.host=t,this.options=i,this.indices=new Map,this.prebuild=null}warm(){const t=this.layers().filter(t=>!this.indices.has(t)),i=()=>{const n=t.shift();n?(this.indexOf(n),this.prebuild=window.setTimeout(i,0)):this.prebuild=null};null===this.prebuild&&t.length>0&&(this.prebuild=window.setTimeout(i,30))}snap(t,n,e,o){const s=this.host,r=s.toGround(t,n,o.z),a=this.options.tolerance??12,h=void 0===this.options.angle?15:this.options.angle;let d=null,l=a;if(o.own?.forEach((i,e)=>{const r=s.toScreen(i);if(!r)return;const a=Math.hypot(r[0]-t,r[1]-n);a<l&&(l=a,d={point:[i[0],i[1],i[2]??o.z],kind:"self",own:e})}),d)return d;if(e&&h&&o.from&&r){const t=o.from,i=r[0]-t[0],n=r[1]-t[1];if(Math.hypot(i,n)>0){const e=h*Math.PI/180,s=Math.round(Math.atan2(n,i)/e)*e,r=i*Math.cos(s)+n*Math.sin(s);return{point:[t[0]+Math.cos(s)*r,t[1]+Math.sin(s)*r,t[2]??o.z],kind:"angle"}}}const c=!1!==this.options.vertices,u=!1!==this.options.edges;if(c||u){const e=s.rayAt(t,n);let h=null,d=a,l=null,f=a;for(const p of this.layers()){const m=this.indexOf(p);if(!m)continue;const M=[s.toGround(t,n,m.zMin),s.toGround(t,n,m.zMax),r].filter(t=>!!t);if(0===M.length)continue;let x=0;M.forEach(t=>{x=Math.max(x,s.pixelSizeAt(t)*a)});const g=Math.min(...M.map(t=>t[0]))-x,y=Math.min(...M.map(t=>t[1]))-x,b=Math.max(...M.map(t=>t[0]))+x,w=Math.max(...M.map(t=>t[1]))+x,k=m.index.itemsIn(g,y,b,w),z=Math.max(50*this.host.camera.state.distance,1e4),v=[e.origin[0]+e.direction[0]*z,e.origin[1]+e.direction[1]*z,e.origin[2]+e.direction[2]*z];for(const r of k){const a=m.index.item(r);if(!o.exclude||o.exclude.layer!==p||a.feature.id!==o.exclude.id){if(c)for(const i of"point"===a.kind?[a.a]:[a.a,a.b]){const e=s.toScreen(i);if(!e)continue;const o=Math.hypot(e[0]-t,e[1]-n);o<d&&(d=o,h={point:[...i],kind:"vertex",layer:p,feature:a.feature})}if(u&&"point"!==a.kind){const o=i(e.origin,v,a.a,a.b),r=s.toScreen(o.pointB);if(!r)continue;const h=Math.hypot(r[0]-t,r[1]-n);h<f&&(f=h,l={point:o.pointB,kind:"edge",layer:p,feature:a.feature})}}}}if(h)return h;if(l)return l}if(!r)return null;const f=this.options.grid;return f&&f>0?{point:[Math.round(r[0]/f)*f,Math.round(r[1]/f)*f,r[2]],kind:"grid"}:{point:r,kind:"none"}}invalidate(t){(t?[t]:[...this.indices.keys()]).forEach(t=>{this.indices.get(t)?.off(),this.indices.delete(t)})}dispose(){null!==this.prebuild&&window.clearTimeout(this.prebuild),this.prebuild=null,this.invalidate()}layers(){const t=this.options.layers;return(t&&"visible"!==t?[...t]:[...this.host.getLayers()]).filter(t=>t.isVisible()&&t.size>0)}indexOf(i){let n=this.indices.get(i);if(!n){const e=i.bounds(),o=i.on("change",({what:t})=>{"features"===t&&this.invalidate(i)});n={index:new t(i.getFeatures()),zMin:e.min[2],zMax:e.max[2],off:o},this.indices.set(i,n)}return n}}
@@ -0,0 +1,257 @@
1
+ import { Camera, DepthTexture, Matrix4, RenderTarget, Scene, Vector3, WebGPURenderer } from 'three/webgpu';
2
+ import { TypedEventEmitter } from '../event/TypedEventEmitter';
3
+ import { DensityMap } from '../three/DensityMap';
4
+ import { Halo } from '../three/Halo';
5
+ import { SceneDepth } from '../three/primitives/Body';
6
+ import { GeometryFrame, GeometryPassName, GeometryPrimitive, PickPass } from './GeometryFrame';
7
+ /** A camera whose matrix is set from outside; three asks it to recompute when it adopts it. */
8
+ export declare class HostCamera extends Camera {
9
+ updateProjectionMatrix(): void;
10
+ }
11
+ /** What a pick found: whatever its source made of the hit, where, and how far from the camera. */
12
+ export interface GeometryPick<T = unknown> {
13
+ hit: T;
14
+ /** The point hit, in world units (the origin added back). */
15
+ point: [number, number, number];
16
+ source: number;
17
+ index: number;
18
+ /** Clip w of the hit: its distance from the camera in 3D. */
19
+ distance: number;
20
+ }
21
+ /** What one frame cost and drew. */
22
+ export interface GeometryFrameStats {
23
+ /** CPU time of the frame's drawing: the before-render hooks and the draw submits, ms. */
24
+ ms: number;
25
+ width: number;
26
+ height: number;
27
+ }
28
+ export interface GeometryEngineEvents {
29
+ frame: GeometryFrameStats;
30
+ ready: void;
31
+ }
32
+ /** What a renderer's frame is drawn from: the camera and the frame's size. */
33
+ export interface FrameInput {
34
+ /** Frame pixels. */
35
+ width: number;
36
+ height: number;
37
+ /**
38
+ * World to clip, row-major, in world units (no origin taken off): the engine folds the origin
39
+ * in, in doubles, so float32 vertices relative to it keep millimetres.
40
+ */
41
+ viewProjection: ArrayLike<number>;
42
+ /** Whether clip z runs -1..1 (OpenGL's, LuciadRIA's) rather than the backend's own. */
43
+ glDepth: boolean;
44
+ near: number;
45
+ pixelRatio: number;
46
+ geocentric?: boolean;
47
+ orthographic?: boolean;
48
+ /** Frame pixels per world unit at one unit from the camera; worked out from the matrix if not given. */
49
+ focal?: number;
50
+ /** Frame pixels per world unit at the view's centre; worked out from the matrix if not given. */
51
+ pxPerWorld?: number;
52
+ /** The camera's position, in world units. */
53
+ eye?: readonly number[];
54
+ }
55
+ /**
56
+ * Draws three.js geometry over a frame: the package's engine, which every primitive and layer
57
+ * draws through. It owns the scenes each pass draws (`GeometryPassName`), the camera - the
58
+ * frame's whole view-projection, relative to `origin` - the scene's depth, the bloom, the halo,
59
+ * the heatmap and the GPU pick.
60
+ *
61
+ * Two kinds of engine extend it: `CanvasGeometryEngine` draws on a canvas of its own, under a
62
+ * camera of its own; `HostedGeometryEngine` draws into a frame someone else draws - LuciadRIA's,
63
+ * on its WebGPU device - under that one's camera. The primitives cannot tell the two apart.
64
+ */
65
+ export declare abstract class GeometryEngine extends TypedEventEmitter<GeometryEngineEvents> {
66
+ readonly scene: Scene;
67
+ /**
68
+ * Drawn before `scene`, which then starts on a cleared depth buffer: for what must darken the
69
+ * frame without hiding what comes after it - the halo under buried pipes.
70
+ */
71
+ readonly underlayScene: Scene;
72
+ /** What is drawn a second time, alone, to be blurred and added over the frame: the selection. */
73
+ readonly bloomScene: Scene;
74
+ /**
75
+ * What a pick can hit (`pick`): meshes that write, instead of a colour, their pick source's id,
76
+ * the feature's index and the fragment's clip w - `vec4(source, index, w, 1)`.
77
+ */
78
+ readonly pickScene: Scene;
79
+ readonly pickPass: PickPass;
80
+ /** The heatmap: what the primitives add up while drawing density, coloured over the frame. */
81
+ readonly density: DensityMap;
82
+ /** The halo round what is seen through the scene's surface. */
83
+ readonly halo: Halo;
84
+ readonly camera: HostCamera;
85
+ /** CPU time of the last frame's drawing. */
86
+ lastRenderMs: number;
87
+ readonly frame: Required<Omit<GeometryFrame, 'eye'>> & {
88
+ eye: Vector3;
89
+ };
90
+ /** The bloom's strength and radius, live. */
91
+ bloom: {
92
+ strength: {
93
+ value: number;
94
+ };
95
+ radius: {
96
+ value: number;
97
+ };
98
+ threshold: {
99
+ value: number;
100
+ };
101
+ } | null;
102
+ /** The scene's depth, as the primitives read it: what lies behind it is ghosted. */
103
+ readonly sceneDepth: SceneDepth;
104
+ protected renderer: WebGPURenderer | null;
105
+ protected ready: boolean;
106
+ protected disposed: boolean;
107
+ protected depth: DepthTexture;
108
+ /** Whether anything asked for the scene's depth; it is not kept until then. */
109
+ protected depthWanted: boolean;
110
+ private bloomPost;
111
+ private bloomTarget;
112
+ private origins;
113
+ private readonly drawn;
114
+ private readonly beforeRender;
115
+ private readonly beforeDraw;
116
+ private readonly pickSources;
117
+ private nextPickSource;
118
+ private pending;
119
+ private attached;
120
+ /**
121
+ * Meshes attached and not yet compiled, by pass: three compiles them in the background
122
+ * (`compileAsync`) while frames go on without them, a batch at a time - a page that answers
123
+ * while its shaders are made, rather than one frozen for a second or more at the first frame
124
+ * (WebGL 2's linking, three's node building, all at once). Each batch shows when it is done.
125
+ */
126
+ private readonly unready;
127
+ /** Meshes compiled once: attached again - a 2D map toggled back - they draw at once. */
128
+ private readonly compiled;
129
+ private warming;
130
+ private readonly startTime;
131
+ /** The view-projection the last frame was drawn with, relative to the origin, column-major. */
132
+ private readonly drawnCamera;
133
+ private readonly pickTarget;
134
+ private readonly depthUniforms;
135
+ constructor();
136
+ /** The texture the scene's depth is kept in; an engine that draws the scene itself gives its own. */
137
+ protected createDepthTexture(): DepthTexture;
138
+ /** The renderer, once there is one. */
139
+ getRenderer(): WebGPURenderer | null;
140
+ /** Whether the renderer runs on WebGPU (true) or on its WebGL 2 fallback. */
141
+ get webgpu(): boolean;
142
+ /** Which origin goes with the frame now: an engine whose world changes reference keeps one per reference. */
143
+ protected originKey(): string;
144
+ /**
145
+ * Where vertex coordinates are measured from, in world units. Set once, by the first content,
146
+ * before any geometry is made relative to it.
147
+ */
148
+ setOrigin(x: number, y: number, z?: number): void;
149
+ getOrigin(): [number, number, number] | null;
150
+ /** The origin, made from `at` if there is none yet. */
151
+ originFor(at: readonly number[]): [number, number, number];
152
+ /**
153
+ * The scene's depth for this frame, as a texture the primitives can sample (`1 - near / w`),
154
+ * kept from the first ask on. When it cannot be had, `frame.depth` is false and the primitives
155
+ * draw without it.
156
+ */
157
+ depthTexture(): DepthTexture;
158
+ /** Called at the start of every frame this engine draws; returns a remover. */
159
+ onBeforeRender(callback: (frame: GeometryEngine['frame']) => void): () => void;
160
+ /**
161
+ * Called each frame once the scene's depth is in, just before the scenes are drawn, with the
162
+ * frame's size in pixels: for what must read this frame's depth first. Returns a remover.
163
+ */
164
+ onBeforeDraw(callback: (width: number, height: number) => void): () => void;
165
+ /** Asks for a new frame, for a change only this engine's content knows about. */
166
+ abstract requestRepaint(): void;
167
+ /** Puts a primitive's meshes into the scenes of their passes; it is handed every frame. */
168
+ attach(primitive: GeometryPrimitive): void;
169
+ /** Takes a primitive's meshes out of the scenes; it is not disposed. */
170
+ detach(primitive: GeometryPrimitive): void;
171
+ sceneOf(pass: GeometryPassName): Scene;
172
+ /**
173
+ * Draws `scene` into `target`, cleared first: a mask that this frame's drawing reads. For a
174
+ * before-draw hook; false when there is no renderer yet.
175
+ */
176
+ renderToTarget(scene: Scene, target: RenderTarget): boolean;
177
+ /**
178
+ * Clears the current target to transparent black: a mask, a sum, ids. The frame's own clear
179
+ * colour - a view's background - would read as a mask everywhere, a weight everywhere, a hit
180
+ * on source 1.
181
+ */
182
+ private clearToZero;
183
+ private readonly clearColor;
184
+ /**
185
+ * A new id for meshes in `pickScene` to write, and what a hit on it means: whatever `resolve`
186
+ * makes of the index, or null for what cannot be picked now. Returns the id and a remover.
187
+ */
188
+ addPickSource<T>(resolve: (index: number) => T | null): {
189
+ id: number;
190
+ remove: () => void;
191
+ };
192
+ /**
193
+ * What is drawn under a view point (view pixels from the frame's top-left), or null.
194
+ * `pickScene` is drawn into a few pixels round the point and read back; of what they hold, the
195
+ * hit nearest the point wins, then the one nearest the camera.
196
+ *
197
+ * It is drawn at once, against the last frame - its camera, its depth, its masks: a pick does
198
+ * not move the view. Only before the first frame does it wait for one.
199
+ */
200
+ pick<T = unknown>(x: number, y: number): Promise<GeometryPick<T> | null>;
201
+ dispose(): void;
202
+ /**
203
+ * Adopts a renderer: linear output and no tone mapping, so colours go in as the sRGB values
204
+ * they are and three draws straight into the target; colour never cleared by itself.
205
+ */
206
+ protected adoptRenderer(renderer: WebGPURenderer): void;
207
+ /**
208
+ * The selection bloomed: the selected geometry rendered alone, blurred at five scales, and the
209
+ * blur added onto the finished frame. The quad that adds it blends one-plus-one, so the frame
210
+ * under it stays and only the glow comes on top.
211
+ */
212
+ private createBloom;
213
+ /** Sets the camera for a frame and works out what the primitives need to know of it. */
214
+ protected updateCamera(input: FrameInput): void;
215
+ /** Whether the depth texture holds this frame's depth: an engine that cannot get it says no. */
216
+ protected depthReady(): boolean;
217
+ /**
218
+ * Draws the frame: the hooks, the masks, the underlay, the scene and the bloom over what is in
219
+ * the target already. `prepareDepth` gets the scene's depth in (a copy, or a draw of its own)
220
+ * and says whether to go on.
221
+ */
222
+ protected renderFrame(input: FrameInput, prepareDepth?: () => boolean): boolean;
223
+ private drawFrame;
224
+ /**
225
+ * Starts compiling what was attached and is shown, unless a batch is under way: each mesh into
226
+ * the target its pass draws to, so that the frame finds its pipelines made. What is hidden
227
+ * waits until it is shown. A renderer without `compileAsync` draws everything at once.
228
+ */
229
+ private warmUp;
230
+ private compile;
231
+ /** The target a pass draws into: the frame's own (null) for the scene and the underlay. */
232
+ private targetOf;
233
+ /** Hides, for this frame's drawing, what is not compiled yet; returns what to show again after. */
234
+ private holdBack;
235
+ /** A frame with nothing in it: nothing to hit, then or until something draws again. */
236
+ protected missPicks(): void;
237
+ /**
238
+ * Draws `pickScene` for one pick, into the target the few pixels round it fill - this frame's
239
+ * clip space scaled up round the point (`pickPass.window`) - and reads the target back.
240
+ */
241
+ private runPick;
242
+ /**
243
+ * The pick target's texels. On WebGPU by a copy into a buffer of its own: three's
244
+ * `readRenderTargetPixelsAsync` (0.178) sizes its buffer without the 256-byte row padding
245
+ * WebGPU copies with, so for a target this small the copy fails validation. On WebGL through
246
+ * three, whose rows then run bottom-up.
247
+ */
248
+ private readTexels;
249
+ private readPick;
250
+ }
251
+ /**
252
+ * The point (relative to the origin) that a frame pixel at `ndcX`, `ndcY` shows at clip w `w`:
253
+ * the view-projection solved for it in doubles - x = ndcX w and y = ndcY w on the clip side, w
254
+ * itself the third equation. An orthographic camera has w 1 everywhere, which says nothing of
255
+ * where the pixel is: its points are taken on the level `planeZ`.
256
+ */
257
+ export declare function unproject(matrix: Matrix4, ndcX: number, ndcY: number, w: number, planeZ?: number): [number, number, number];
@@ -0,0 +1 @@
1
+ import{AddEquation as e,Camera as t,Color as r,CustomBlending as s,DepthTexture as i,FloatType as n,LinearSRGBColorSpace as a,Matrix4 as o,NearestFilter as h,NoToneMapping as c,OneFactor as d,PostProcessing as l,RenderTarget as p,Scene as u,Vector2 as m,Vector3 as f,WebGPUCoordinateSystem as g,ZeroFactor as y}from"three/webgpu";import{pass as w,uniform as b}from"three/tsl";import{bloom as T}from"three/examples/jsm/tsl/display/BloomNode.js";import{TypedEventEmitter as x}from"../event/TypedEventEmitter.js";import{DensityMap as k}from"../three/DensityMap.js";import{Halo as P}from"../three/Halo.js";import{pickPassUniforms as R}from"./GeometryFrame.js";export class HostCamera extends t{updateProjectionMatrix(){}}export class GeometryEngine extends x{constructor(){super(),this.scene=new u,this.underlayScene=new u,this.bloomScene=new u,this.pickScene=new u,this.pickPass=R(),this.density=new k,this.halo=new P,this.camera=new HostCamera,this.lastRenderMs=0,this.frame={pxPerWorld:1,pixelRatio:1,near:.3,geocentric:!1,depth:!1,focal:1e3,orthographic:!0,width:1,height:1,eye:new f,time:0},this.bloom=null,this.renderer=null,this.ready=!1,this.disposed=!1,this.depthWanted=!1,this.bloomPost=null,this.bloomTarget=null,this.origins=new Map,this.drawn=new m,this.beforeRender=new Set,this.beforeDraw=new Set,this.pickSources=new Map,this.nextPickSource=1,this.pending=[],this.attached=new Map,this.unready=new Map,this.compiled=new WeakSet,this.warming=null,this.startTime=performance.now(),this.drawnCamera=new o,this.pickTarget=new p(7,7,{type:n,depthBuffer:!0,generateMipmaps:!1,minFilter:h,magFilter:h}),this.depthUniforms={enabled:b(0),near:b(.3)},this.clearColor=new r,this.camera.matrixAutoUpdate=!1,this.camera.matrixWorldAutoUpdate=!1,this.scene.add(this.density.quad),this.underlayScene.add(this.halo.quad),this.depth=this.createDepthTexture(),this.sceneDepth={texture:this.depth,enabled:this.depthUniforms.enabled,near:this.depthUniforms.near}}createDepthTexture(){const e=new i(1,1,n);return e.minFilter=h,e.magFilter=h,e}getRenderer(){return this.renderer}get webgpu(){return this.renderer?.coordinateSystem===g}originKey(){return"world"}setOrigin(e,t,r=0){this.origins.set(this.originKey(),[e,t,r])}getOrigin(){return this.origins.get(this.originKey())??null}originFor(e){let t=this.getOrigin();return t||(this.setOrigin(e[0],e[1],e[2]??0),t=this.getOrigin()),t}depthTexture(){return this.depthWanted=!0,this.depth}onBeforeRender(e){return this.beforeRender.add(e),()=>{this.beforeRender.delete(e)}}onBeforeDraw(e){return this.beforeDraw.add(e),()=>{this.beforeDraw.delete(e)}}attach(e){if(this.attached.has(e))return;const t=[],r=e.passes();Object.keys(r).forEach(e=>{for(const s of r[e]??[])s&&(this.sceneOf(e).add(s),t.push({mesh:s,pass:e}),this.compiled.has(s)||this.unready.set(s,e))}),this.attached.set(e,{primitive:e,meshes:t}),e.setFrame(this.frame),this.requestRepaint()}detach(e){const t=this.attached.get(e);t&&(t.meshes.forEach(({mesh:e,pass:t})=>{this.sceneOf(t).remove(e),this.unready.delete(e)}),this.attached.delete(e),this.requestRepaint())}sceneOf(e){switch(e){case"scene":return this.scene;case"underlay":return this.underlayScene;case"bloom":return this.bloomScene;case"pick":return this.pickScene;case"density":return this.density.scene;case"halo":return this.halo.scene}}renderToTarget(e,t){const r=this.renderer;if(!r||!this.ready)return!1;const s=r.getRenderTarget();return r.setRenderTarget(t),this.clearToZero(r),r.render(e,this.camera),r.setRenderTarget(s),!0}clearToZero(e){e.getClearColor(this.clearColor);const t=e.getClearAlpha();e.setClearColor(0,0),e.clear(!0,!0,!0),e.setClearColor(this.clearColor,t)}addPickSource(e){const t=this.nextPickSource++;return this.pickSources.set(t,e),{id:t,remove:()=>{this.pickSources.delete(t)}}}pick(e,t){return new Promise(r=>{const s={x:e,y:t,resolve:r},i=setTimeout(()=>{this.pending=this.pending.filter(e=>e!==s),r(null)},1e3);s.resolve=e=>{clearTimeout(i),r(e)},this.ready&&this.renderer&&this.drawn.x>0?this.runPick(s,this.drawn.x,this.drawn.y):(this.pending.push(s),this.requestRepaint())})}dispose(){this.disposed=!0,this.missPicks(),[...this.attached.keys()].forEach(e=>this.detach(e)),this.pickTarget.dispose(),this.density.dispose(),this.halo.dispose(),this.depth.dispose();try{this.bloomPost?.dispose()}catch{}this.bloomPost=null;try{this.renderer?.dispose()}catch{}this.renderer=null,this.ready=!1}adoptRenderer(e){try{this.bloomPost?.dispose()}catch{}this.bloomPost=null,this.renderer=e,this.ready=!1,e.outputColorSpace=a,e.toneMapping=c,e.autoClear=!0,e.autoClearColor=!1,e.autoClearStencil=!1,this.createBloom(e)}createBloom(t){const r=w(this.bloomScene,this.camera);this.bloomTarget=r;const i=T(r,1.2,.5,0);this.bloom=i;const n=new(function(){const e=Object.getPrototypeOf(l);return"function"==typeof e&&e!==Function.prototype&&"function"==typeof e.prototype?.render?e:l}())(t,i);n.outputColorTransform=!1;const a=n._quadMesh.material;a.transparent=!0,a.blending=s,a.blendSrc=d,a.blendDst=d,a.blendEquation=e,a.blendSrcAlpha=y,a.blendDstAlpha=d,a.depthTest=!1,a.depthWrite=!1,this.bloomPost=n}updateCamera(e){const t=e.viewProjection,r=this.frame,{width:s,height:i}=e;r.width=s,r.height=i,r.pixelRatio=e.pixelRatio,r.near=e.near,r.geocentric=!!e.geocentric,r.pxPerWorld=e.pxPerWorld??Math.hypot(t[0]*s/2,t[4]*i/2);const n=e.orthographic??Math.abs(t[12])+Math.abs(t[13])+Math.abs(t[14])<1e-12;r.orthographic=n,r.focal=e.focal??(n?r.pxPerWorld:Math.hypot(t[0],t[1],t[2])*s/2),r.depth=this.depthWanted&&this.depthReady(),r.time=(performance.now()-this.startTime)/1e3,this.depthUniforms.near.value=e.near,this.depthUniforms.enabled.value=r.depth?1:0;const[a,o,h]=this.getOrigin()??[0,0,0];e.eye&&r.eye.set(e.eye[0]-a,e.eye[1]-o,(e.eye[2]??0)-h);const c=this.camera.projectionMatrix.elements;for(let e=0;e<4;e++)c[e]=t[4*e],c[4+e]=t[4*e+1],c[8+e]=t[4*e+2],c[12+e]=t[4*e]*a+t[4*e+1]*o+t[4*e+2]*h+t[4*e+3];if(e.glDepth&&this.webgpu)for(let e=0;e<4;e++)c[4*e+2]=.5*c[4*e+2]+.5*c[4*e+3];this.camera.projectionMatrixInverse.copy(this.camera.projectionMatrix).invert()}depthReady(){return!0}renderFrame(e,t){const r=this.renderer;if(this.lastRenderMs=0,!this.ready||!r)return!1;const s=performance.now();r._nodes?.nodeFrame?.update?.(),this.updateCamera(e),this.attached.forEach(({primitive:e})=>e.setFrame(this.frame)),this.beforeRender.forEach(e=>e(this.frame)),this.warmUp(r);const i=this.holdBack();try{return this.drawFrame(r,e,s,t)}finally{i.forEach(e=>{e.visible=!0})}}drawFrame(e,t,r,s){this.density.update();const i=e=>e.children.some(e=>e.visible);if(!i(this.scene)&&!i(this.underlayScene))return this.missPicks(),this.lastRenderMs=performance.now()-r,!1;if(s&&!s())return!1;this.beforeDraw.forEach(e=>e(t.width,t.height));const n=(e,t)=>{this.renderToTarget(e,t)};if(this.halo.draw(t.width,t.height,n),this.density.draw(t.width,t.height,n),this.drawn.set(t.width,t.height),this.drawnCamera.copy(this.camera.projectionMatrix),this.pending.length>0&&this.runPick(this.pending.shift(),t.width,t.height),i(this.underlayScene)&&e.render(this.underlayScene,this.camera),e.render(this.scene,this.camera),this.bloomPost&&i(this.bloomScene)){const t=this.bloomTarget?.renderTarget;if(t){const r=e.getRenderTarget();e.setRenderTarget(t),this.clearToZero(e),e.setRenderTarget(r)}this.bloomPost.render()}return this.lastRenderMs=performance.now()-r,this.emit("frame",{ms:this.lastRenderMs,width:t.width,height:t.height}),!0}warmUp(e){if(this.warming||0===this.unready.size)return;if("function"!=typeof e.compileAsync)return void this.unready.clear();const t=[...this.unready].filter(([e])=>e.visible);0!==t.length&&(this.warming=this.compile(e,t).catch(e=>console.warn("[geometry] Compiling in the background failed; drawn as it comes",e)).finally(()=>{t.forEach(([e])=>{this.unready.delete(e),this.compiled.add(e)}),this.warming=null,this.requestRepaint()}))}async compile(e,t){for(const[r,s]of t){const t=this.sceneOf(s);if(!this.unready.has(r)||r.parent!==t||!this.renderer)continue;const i=e.getRenderTarget();let n;try{e.setRenderTarget(this.targetOf(s)),n=e.compileAsync(r,this.camera,t)}finally{e.setRenderTarget(i)}await n}}targetOf(e){switch(e){case"scene":case"underlay":return null;case"bloom":return this.bloomTarget?.renderTarget??null;case"pick":return this.pickTarget;case"density":return this.density.target;case"halo":return this.halo.target}}holdBack(){const e=[];return this.unready.forEach((t,r)=>{r.visible&&(r.visible=!1,e.push(r))}),e}missPicks(){this.drawn.set(0,0);const e=this.pending;this.pending=[],e.forEach(e=>e.resolve(null))}runPick(e,t,r){this.pending.length>0&&this.requestRepaint();const s=Math.floor(e.x*this.frame.pixelRatio),i=Math.floor(e.y*this.frame.pixelRatio),n=(s+.5)/t*2-1,a=1-(i+.5)/r*2,o=t/7,h=r/7;this.pickPass.window.value.set(o,0,0,-n*o,0,h,0,-a*h,0,0,1,0,0,0,0,1),this.pickPass.origin.value.set(s-3,i-3),this.pickPass.frameSize.value.set(t,r);const c=this.drawnCamera.clone(),d=this.getOrigin()??[0,0,0];this.renderToTarget(this.pickScene,this.pickTarget)?this.readPick(s,i,t,r,c,d).then(e.resolve,t=>{console.warn("[geometry] Pick failed",t),e.resolve(null)}):e.resolve(null)}async readTexels(){const e=this.renderer;if(!e)return null;const t=e.backend,r=t?.device,s=t?.get?.(this.pickTarget.texture)?.texture;if(this.webgpu&&r&&s){const{GPUBufferUsage:e,GPUMapMode:t}=globalThis,i=256,n=r.createBuffer({size:7*i,usage:e.COPY_DST|e.MAP_READ}),a=r.createCommandEncoder();a.copyTextureToBuffer({texture:s},{buffer:n,bytesPerRow:i},[7,7]),r.queue.submit([a.finish()]);try{return await n.mapAsync(t.READ),{data:new Float32Array(n.getMappedRange().slice(0)),stride:i/4,bottomUp:!1}}finally{n.destroy()}}const i=await e.readRenderTargetPixelsAsync(this.pickTarget,0,0,7,7);return{data:new Float32Array(i.buffer,i.byteOffset,i.byteLength/4),stride:28,bottomUp:!0}}async readPick(e,t,r,s,i,n){const a=await this.readTexels();if(!a)return null;const{data:o,stride:h,bottomUp:c}=a,d=[];for(let r=0;r<7;r++)for(let s=0;s<7;s++){const i=r*h+4*s,n=Math.round(o[i]);if(n<=0)continue;const a=s-3,l=c?3-r:r-3;d.push({source:n,index:Math.round(o[i+1]),w:o[i+2],x:e+a,y:t+l,d:a*a+l*l})}d.sort((e,t)=>e.d-t.d||e.w-t.w);for(const e of d){const t=this.pickSources.get(e.source)?.(e.index);if(null==t)continue;const a=unproject(i,(e.x+.5)/r*2-1,1-(e.y+.5)/s*2,e.w,-n[2]);return{hit:t,point:[a[0]+n[0],a[1]+n[1],a[2]+n[2]],source:e.source,index:e.index,distance:e.w}}return null}}export function unproject(e,t,r,s,i=0){const n=e.elements,a=e=>[n[e],n[4+e],n[8+e],n[12+e]],[o,h,c]=[a(0),a(1),a(3)];if(Math.abs(c[0])+Math.abs(c[1])+Math.abs(c[2])<1e-12){const[e,s,n,a]=[o[0],o[1],h[0],h[1]],[d,l]=[t*c[3]-o[3]-o[2]*i,r*c[3]-h[3]-h[2]*i],p=e*a-s*n;return[(d*a-s*l)/p,(e*l-d*n)/p,i]}const d=[[0,1,2].map(e=>o[e]-t*c[e]),[0,1,2].map(e=>h[e]-r*c[e]),[c[0],c[1],c[2]]],l=[t*c[3]-o[3],r*c[3]-h[3],s-c[3]],p=e=>e[0][0]*(e[1][1]*e[2][2]-e[1][2]*e[2][1])-e[0][1]*(e[1][0]*e[2][2]-e[1][2]*e[2][0])+e[0][2]*(e[1][0]*e[2][1]-e[1][1]*e[2][0]),u=p(d),m=[0,1,2].map(e=>p(d.map((t,r)=>t.map((t,s)=>s===e?l[r]:t)))/u);return[m[0],m[1],m[2]]}
@@ -0,0 +1,91 @@
1
+ import type { Mesh } from 'three/webgpu';
2
+ import { Matrix4, Vector2, Vector3 } from 'three/webgpu';
3
+ /**
4
+ * What drawing in pixels or metres needs to know about the frame being drawn. An engine fills it
5
+ * in before every frame and hands it to each primitive's `setFrame`.
6
+ *
7
+ * The first five are the ones the Ing+ map's `ThreeFrame` has, with the same meaning, so that a
8
+ * frame from either is good for both.
9
+ */
10
+ export interface GeometryFrame {
11
+ /** Frame pixels per world unit, at the view's centre: exact on a flat (orthographic) map. */
12
+ pxPerWorld: number;
13
+ /** Frame pixels per view (CSS) pixel: the unit pixel style sizes are in. */
14
+ pixelRatio: number;
15
+ /** The camera's near plane this frame, in world units: the scene depth is `1 - near / w`. */
16
+ near: number;
17
+ /** Whether the world is geocentric (EPSG:4978) this frame. */
18
+ geocentric: boolean;
19
+ /** Whether `depthTexture()` holds the scene's depth this frame. */
20
+ depth: boolean;
21
+ /** Frame pixels per world unit at one world unit from the camera: what a size is on screen. */
22
+ focal?: number;
23
+ /** Whether the camera is orthographic: a 2D map, where a pixel is the same everywhere. */
24
+ orthographic?: boolean;
25
+ /** The frame's size, in frame pixels. */
26
+ width?: number;
27
+ height?: number;
28
+ /** The camera's position relative to the origin. */
29
+ eye?: Vector3;
30
+ /** Seconds since the engine started: for what moves by itself (flow, pulses). */
31
+ time?: number;
32
+ }
33
+ /**
34
+ * What the pick materials read: `window` takes this frame's clip space to the pick target's -
35
+ * the few pixels round the point filling it - and `origin` is the frame pixel of the target's
36
+ * top-left, for whatever looks things up by frame pixel (`screenCoordinate` there is the
37
+ * target's). Pixel sizes come from `frameSize`, never from `viewport`, which is the target's.
38
+ */
39
+ export declare function pickPassUniforms(): {
40
+ window: import("three/tsl").ShaderNodeObject<import("three/webgpu").UniformNode<Matrix4>>;
41
+ origin: import("three/tsl").ShaderNodeObject<import("three/webgpu").UniformNode<Vector2>>;
42
+ frameSize: import("three/tsl").ShaderNodeObject<import("three/webgpu").UniformNode<Vector2>>;
43
+ };
44
+ export type PickPass = ReturnType<typeof pickPassUniforms>;
45
+ /** What a primitive needs to be drawn into a pick pass: the pass, and the id it writes. */
46
+ export interface PickOptions {
47
+ pass: PickPass;
48
+ source: number;
49
+ }
50
+ /**
51
+ * What may stand in front of geometry drawn on or under the ground: a node for the fragment
52
+ * shader saying whether something hides a fragment `distance` (clip w) from the camera. `pixel`,
53
+ * the frame pixel, when not the fragment's own (the pick pass). The Ing+ map's buildings mask is
54
+ * one; the package's own scene depth does without.
55
+ */
56
+ export interface GeometryOccluder {
57
+ /** Another for each new occluder: geometry made with an old one is made again. */
58
+ readonly id: number;
59
+ hides(distance: any, pixel?: any): any;
60
+ }
61
+ /** The Ing+ map's name for it. */
62
+ export type LineOccluder = GeometryOccluder;
63
+ /**
64
+ * The passes an engine draws, each a scene:
65
+ * - `scene`: the geometry itself, over the frame.
66
+ * - `underlay`: before `scene`, which then starts on a cleared depth buffer - for what darkens the
67
+ * frame without hiding what comes after it (the halo under buried pipes).
68
+ * - `bloom`: drawn a second time, alone, blurred and added over the frame - the selection's glow.
69
+ * - `pick`: what a click can hit, each fragment writing `vec4(source, index, distance, 1)`.
70
+ * - `density`: weights added into the heatmap, coloured over the frame in one pass.
71
+ * - `halo`: silhouettes of what lies behind the scene's surface, blurred into the halo.
72
+ */
73
+ export type GeometryPassName = 'scene' | 'underlay' | 'bloom' | 'pick' | 'density' | 'halo';
74
+ export type GeometryPasses = Partial<Record<GeometryPassName, (Mesh | null | undefined)[]>>;
75
+ /**
76
+ * A primitive the engine can draw: a set of meshes, one or more per pass, sharing one geometry
77
+ * and one per-feature look. Every mesh is placed relative to the engine's origin, its vertex
78
+ * shader taking `cameraProjectionMatrix` as the whole view-projection.
79
+ */
80
+ export interface GeometryPrimitive {
81
+ passes(): GeometryPasses;
82
+ setFrame(frame: GeometryFrame): void;
83
+ dispose(): void;
84
+ /**
85
+ * Takes on the geometry of `other` - the same kind, built with the same options from new
86
+ * data - keeping its own materials, compiled already: features added, changed or removed
87
+ * without a recompile. False when it cannot (another kind, a mesh more or less), the caller
88
+ * then builds afresh. `other` is left without geometry, to be disposed.
89
+ */
90
+ adopt?(other: GeometryPrimitive): boolean;
91
+ }