@protomaze/geometry 0.2.0 → 0.3.1
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.
- package/README.md +71 -48
- package/common/Colors.d.ts +1 -2
- package/edit/GeometryController.d.ts +1 -1
- package/engine/GeometryEngine.d.ts +22 -3
- package/engine/GeometryEngine.js +1 -1
- package/engine/GeometryFrame.d.ts +3 -6
- package/engine/GeometryOptions.d.ts +26 -2
- package/engine/GeometryView.d.ts +31 -6
- package/engine/GeometryView.js +1 -1
- package/index.d.ts +1 -1
- package/index.js +1 -1
- package/layers/AreaLayer.js +1 -1
- package/layers/GeometryLayer.d.ts +33 -7
- package/layers/GeometryLayer.js +1 -1
- package/layers/LineLayer.d.ts +14 -0
- package/layers/LineLayer.js +1 -1
- package/layers/SphereLayer.js +1 -1
- package/layers/TubeLayer.d.ts +20 -5
- package/layers/TubeLayer.js +1 -1
- package/math/AxisIndex.d.ts +22 -0
- package/math/AxisIndex.js +1 -0
- package/package.json +1 -1
- package/three/CanvasGeometryEngine.d.ts +0 -3
- package/three/CanvasGeometryEngine.js +1 -1
- package/three/DensityMap.d.ts +3 -3
- package/three/FeatureLook.d.ts +19 -2
- package/three/FeatureLook.js +1 -1
- package/three/HostedGeometryEngine.d.ts +6 -5
- package/three/HostedGeometryEngine.js +1 -1
- package/three/Shading.d.ts +1 -1
- package/three/primitives/Body.d.ts +1 -1
- package/three/primitives/Body.js +1 -1
- package/three/primitives/GpuAreas.js +1 -1
- package/three/primitives/GpuIcons.d.ts +3 -3
- package/three/primitives/GpuIcons.js +1 -1
- package/three/primitives/GpuLines.d.ts +2 -2
- package/three/primitives/GpuLines.js +1 -1
- package/three/primitives/GpuSpheres.js +1 -1
- package/three/primitives/GpuTubes.d.ts +0 -2
- package/three/primitives/GpuTubes.js +1 -1
- package/three/RiaGeometryEngine.d.ts +0 -48
- package/three/RiaGeometryEngine.js +0 -1
package/README.md
CHANGED
|
@@ -3,23 +3,25 @@
|
|
|
3
3
|
GPU geometry for maps and scenes: points, lines, tubes, spheres and areas, in 2D and 3D, each layer
|
|
4
4
|
one instanced draw. Every feature's look - colour, width, state, material, category, value - lives
|
|
5
5
|
in float textures the shaders read, so a restyle, a filter, a hover or a selection costs a texture
|
|
6
|
-
upload or a uniform, never a rebuild.
|
|
7
|
-
|
|
6
|
+
upload or a uniform, never a rebuild. Networks drawn as they are on a map - pipes, manholes,
|
|
7
|
+
laterals, flow arrows, a heatmap, picking on the GPU - with the geometry calculations, and the
|
|
8
8
|
controllers to draw, edit and measure, that go with it.
|
|
9
9
|
|
|
10
10
|
```bash
|
|
11
11
|
npm run dev # the demo, on http://localhost:8091
|
|
12
12
|
npm test # the DOM-free parts: calculations, editing's shapes and history, the camera
|
|
13
|
-
npm run check # type-check everything, demo
|
|
13
|
+
npm run check # type-check everything, demo included
|
|
14
14
|
```
|
|
15
15
|
|
|
16
|
-
Built on three.js's WebGPU renderer and TSL, so the same shaders run on WebGPU -
|
|
17
|
-
|
|
16
|
+
Built on three.js's WebGPU renderer and TSL, so the same shaders run on WebGPU - on a canvas of
|
|
17
|
+
their own, or inside a host's WebGPU frame (a map's, a globe's) - and on WebGL 2 where a browser
|
|
18
|
+
has no WebGPU.
|
|
18
19
|
|
|
19
20
|
## The model
|
|
20
21
|
|
|
21
22
|
```
|
|
22
|
-
GeometryView / <ReactGeometry> ──
|
|
23
|
+
GeometryView / <ReactGeometry> ── layers, highlight, hover, selection, picking; on a canvas with a
|
|
24
|
+
│ camera that pans, zooms and orbits - or in a host's frame, the host's camera and input
|
|
23
25
|
│
|
|
24
26
|
├─ layers: LineLayer, PointLayer, TubeLayer, SphereLayer, AreaLayer
|
|
25
27
|
│ features + style + filters + selection; each builds its primitives and owns their looks
|
|
@@ -28,7 +30,7 @@ GeometryView / <ReactGeometry> ── a canvas, a camera that pans, zooms and or
|
|
|
28
30
|
│ a Sketch of overlay layers over everything, a Snapper, labels, an EditHistory
|
|
29
31
|
│
|
|
30
32
|
└─ CanvasGeometryEngine ── the engine: scenes per pass, origin, scene depth, bloom, halo, heatmap, pick
|
|
31
|
-
HostedGeometryEngine
|
|
33
|
+
HostedGeometryEngine ── the same engine inside a host's WebGPU frame: a map's, a globe's
|
|
32
34
|
|
|
33
35
|
primitives: GpuLines, GpuIcons, GpuTubes, GpuSpheres, GpuAreas ── one instanced draw per pass,
|
|
34
36
|
reading a FeatureLook: the per-feature textures plus the uniforms that filter, light and colour
|
|
@@ -36,7 +38,7 @@ primitives: GpuLines, GpuIcons, GpuTubes, GpuSpheres, GpuAreas ── one instan
|
|
|
36
38
|
|
|
37
39
|
Three levels, each usable on its own: the **view** for an application that wants a map; the
|
|
38
40
|
**layers** for one that has features and styles; the **primitives and an engine** for a host that
|
|
39
|
-
draws its own frame
|
|
41
|
+
draws its own frame.
|
|
40
42
|
|
|
41
43
|
## A view
|
|
42
44
|
|
|
@@ -66,12 +68,12 @@ The view emits `hover`, `click`, `select`, `camera`, `mode` and `frame` (fps, dr
|
|
|
66
68
|
|---|---|---|
|
|
67
69
|
| `LineLayer` | lines | across the screen (2D), flat on the ground in perspective, or in space at their own depth (trajectories); round joints, flat ends, flow arrows, dashes, light flowing along them |
|
|
68
70
|
| `PointLayer` | points | icons from an atlas or shapes drawn in the shader - circle, ring, square, diamond, triangle, hexagon, pin, cross, star, the manhole cover - in pixels or metres, facing the screen or lying on the ground |
|
|
69
|
-
| `TubeLayer` | lines, points | pipes, cables and ducts at their real size and cross-section, mitred bends, joints cut to the shafts' walls, materials; points as shafts or columns with covers. A 2D map draws the same features as lines and covers |
|
|
71
|
+
| `TubeLayer` | lines, points | pipes, cables and ducts at their real size and cross-section, mitred bends, joints cut to the shafts' walls, materials; points as shafts or columns with covers - `stand` from heights where z is up, or from a `foot` and a `top` position anywhere, a globe's included, where a pipe's end is in the shaft whose axis it lies on (in 3D, `joinTolerance`). A 2D map draws the same features as lines and covers |
|
|
70
72
|
| `SphereLayer` | points | lit spheres - connections, sensors, nodes, tree crowns |
|
|
71
73
|
| `AreaLayer` | polygons | flat fills, solid or hatched, with outlines; or extruded volumes, heights on the GPU, lit windows at night |
|
|
72
74
|
|
|
73
75
|
Every 3D body is ghosted where the scene's surface (the ground) is in front of it and outlined by a
|
|
74
|
-
dark halo
|
|
76
|
+
dark halo; never thinner on screen than its look's width in
|
|
75
77
|
pixels, so far off a pipe is a line, still at its depth.
|
|
76
78
|
|
|
77
79
|
## Styling, filtering, lighting up
|
|
@@ -80,7 +82,7 @@ pixels, so far off a pipe is a line, still at its depth.
|
|
|
80
82
|
|---|---|---|
|
|
81
83
|
| A style | `layer.setStyle(f => ...)`, `layer.restyle(ids?)` | one write per feature into the look's textures, one upload at the next frame |
|
|
82
84
|
| A filter | `layer.setFilter(f => ..., 'hide' \| 'fade')` | as a style: decided on the CPU |
|
|
83
|
-
| A range | `layer.setRange({ value, low, high, outside })`, then `setRangeBounds(low, high)` | every value written once
|
|
85
|
+
| A range | `layer.setRange({ value, low, high, outside, fixed, fail })`, then `setRangeBounds(low, high)`; `setRange(null)` ends it | every value written once - `fixed` says where the other filters settle it whatever the range, `fail` gives a look out of it instead of hiding or fading - and a drag step is two uniforms |
|
|
84
86
|
| Categories | `layer.setCategories({ of, keys, colors })`, `setCategoryMode(key, 'hidden' \| 'faded' \| 'shown' \| 'lit')` | one texel per switch; 'lit' lights a whole category, a legend entry pointed at |
|
|
85
87
|
| Colour by | `layer.colorBy({ by: 'category' })`, `colorBy({ value, ramp, domain })` | a uniform and a 256-texel ramp |
|
|
86
88
|
| Hover | the view's pointer, or `layer.setHovered(id)` | one uniform |
|
|
@@ -88,9 +90,14 @@ pixels, so far off a pipe is a line, still at its depth.
|
|
|
88
90
|
| Emphasis | `layer.emphasize(ids)`: lit as the selection is, without selecting | a few texels |
|
|
89
91
|
| Density | `view.setDensity({ layers, ramp, top })` | the same geometry adding its weight into the heatmap instead |
|
|
90
92
|
|
|
91
|
-
What is lit glows - the bloom pass over the selected geometry alone
|
|
92
|
-
|
|
93
|
-
|
|
93
|
+
What is lit glows - the bloom pass over the selected geometry alone, the line shader's own glow, or
|
|
94
|
+
none (`highlight.glow`) - or is outlined (`highlight.look`), and while the pointer rests on something,
|
|
95
|
+
or something is emphasised, the rest is shaded (`hoverFades`, `othersShade`, `othersToward`). Faded
|
|
96
|
+
features go grey and see-through, the same whether the CPU's filter or the GPU's faded them.
|
|
97
|
+
|
|
98
|
+
What is lit stays lit where its own style - or a filter, a range - fades or hides it: drawn as lit,
|
|
99
|
+
its glow or its outline behind it, only faded (`highlight.outsideOpacity`, 0.6), to show it is
|
|
100
|
+
selected but not in view now. Where its style hides it, it is never picked.
|
|
94
101
|
|
|
95
102
|
Several primitives can share one look (`FeatureLook`): an area's fill and its outline, a pipe drawn as
|
|
96
103
|
a tube in 3D and as a line in 2D. They light, filter and colour as one, from one texture upload.
|
|
@@ -188,8 +195,8 @@ reference - DOM-free and tested (`npm test`). Lengths and distances count height
|
|
|
188
195
|
|
|
189
196
|
## Drawing, editing, measuring
|
|
190
197
|
|
|
191
|
-
A controller takes over the view's pointer and keys for a while, as
|
|
192
|
-
its map: `view.setController(controller)`, or `<ReactGeometry controller={controller}>`; null gives
|
|
198
|
+
A controller takes over the view's pointer and keys for a while, as a map toolkit's controllers do
|
|
199
|
+
on its map: `view.setController(controller)`, or `<ReactGeometry controller={controller}>`; null gives
|
|
193
200
|
the view its own ways back. It sees every event first and leaves what it does not handle - a drag
|
|
194
201
|
on empty ground still pans, the wheel still zooms.
|
|
195
202
|
|
|
@@ -248,42 +255,58 @@ bodies read to tell what lies behind the ground.
|
|
|
248
255
|
Frames on demand, continuously only while something moves (flow, a flight).
|
|
249
256
|
- **`HostedGeometryEngine`**: inside a frame someone else draws with WebGPU. The host gives a device,
|
|
250
257
|
and every frame its colour texture, its depth texture and its camera; three draws into that colour
|
|
251
|
-
texture with the host's device.
|
|
252
|
-
- **`RiaGeometryEngine`**: the hosted engine on a LuciadRIA map, typed by shape (no RIA import):
|
|
253
|
-
`RiaGeometryEngine.of(map)` hooks `PostRender` and `WebGPUDeviceChanged`.
|
|
258
|
+
texture with the host's device (see "In a host's frame").
|
|
254
259
|
|
|
255
|
-
A primitive is attached with `engine.attach(primitive)`, or its meshes put into the scenes by hand
|
|
256
|
-
|
|
260
|
+
A primitive is attached with `engine.attach(primitive)`, or its meshes put into the scenes by hand;
|
|
261
|
+
every frame it gets `setFrame(frame)`.
|
|
257
262
|
|
|
258
|
-
## In
|
|
263
|
+
## In a host's frame
|
|
259
264
|
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
on every `npm run check`).
|
|
265
|
+
A map toolkit or a globe that renders with WebGPU can have the layers drawn in its own frame, over
|
|
266
|
+
what it draws and against its depth, under its camera. The package knows no host by name: an
|
|
267
|
+
application wires its host up in a few lines of its own.
|
|
264
268
|
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
269
|
+
```ts
|
|
270
|
+
const engine = new HostedGeometryEngine({
|
|
271
|
+
device: host.device, // the host's WebGPU device (`setDevice` when it makes another)
|
|
272
|
+
requestFrame: () => host.repaint(), // a frame for a change only the geometry knows of
|
|
273
|
+
originKey: () => host.referenceName, // an origin per reference, for a host that switches
|
|
274
|
+
});
|
|
275
|
+
host.afterDrawing((color, depth) => engine.render(color, depth, {
|
|
276
|
+
viewProjection: host.camera.viewProjection, // world to clip, row-major, in the host's world units
|
|
277
|
+
glDepth: true, // clip z -1..1, as OpenGL's cameras have it
|
|
278
|
+
near: host.camera.near,
|
|
279
|
+
pixelRatio: color.width / host.width,
|
|
280
|
+
geocentric: host.isGlobe, // ECEF: up is the ellipsoid's
|
|
281
|
+
eye: host.camera.eye,
|
|
282
|
+
}));
|
|
283
|
+
|
|
284
|
+
const view = new GeometryView({ engine, mode: '3d', element: host.element });
|
|
285
|
+
view.addLayer(new LineLayer({ features, style }));
|
|
286
|
+
host.onClick(async (x, y) => select(await view.pickAt(x, y))); // { layer, id, feature, point }
|
|
287
|
+
```
|
|
288
|
+
|
|
289
|
+
The view on a host's engine has layers, their looks, the highlight, selection, emphasis, the heatmap
|
|
290
|
+
and picking; the host keeps the camera, the ground and the input, so there is no `init`, no
|
|
291
|
+
controllers and no camera calls. `view.toScreen(p)` is where the host's camera put a position on
|
|
292
|
+
the last frame. On a globe (`geocentric`) the ground's up is the ellipsoid's normal at the origin,
|
|
293
|
+
which volumes rise along and covers lie across; give a shaft its own `foot` and `top`
|
|
294
|
+
(`TubeLayer`'s `stand`), and it stands along whatever its axis is. `view.setMode('2d' | '3d')` when the host switches:
|
|
295
|
+
the layers draw the other way, the host turns its camera. The `--pm-*` tokens are read round
|
|
296
|
+
`element`.
|
|
297
|
+
|
|
298
|
+
- **Depth.** The host's depth texture is copied in every frame and the bodies are ghosted behind it.
|
|
299
|
+
The camera's clip depth may be OpenGL's (`glDepth: true`, -1..1) or the backend's own; the engine
|
|
300
|
+
folds it into the camera, so the primitives use clip space as it is.
|
|
301
|
+
- **What stands in front.** A host's mask of buildings and trees is a `GeometryOccluder` by shape:
|
|
302
|
+
`occluder` on `LineLayer`, `TubeLayer`, `SphereLayer` (`layer.setOccluder` to change it).
|
|
303
|
+
- **Worlds not in metres.** On Web Mercator, `worldPerMetre: mercatorWorldPerMetre(y)` keeps a line's
|
|
304
|
+
width in metres true.
|
|
305
|
+
- **A host's own colour map.** `view.setDensity({ ramp })` takes a list of colours or anything with
|
|
306
|
+
`retrieveColor(level)`, as it is.
|
|
307
|
+
|
|
308
|
+
`npm run dev`, then `?hosted`: a stand-in host - its own WebGPU device, canvas, camera, colour and
|
|
309
|
+
depth - with the engine and a view in its frame (`src/hosted.tsx`, never in the package).
|
|
287
310
|
|
|
288
311
|
## How it draws
|
|
289
312
|
|
package/common/Colors.d.ts
CHANGED
|
@@ -15,8 +15,7 @@ export declare function desaturate([r, g, b, a]: Rgba, amount: number): Rgba;
|
|
|
15
15
|
export declare function withAlpha(color: ColorLike, alpha: number): Rgba;
|
|
16
16
|
/**
|
|
17
17
|
* Something that gives a colour for a level: a list of colours spread evenly from 0 to 1, or an
|
|
18
|
-
* object with `retrieveColor
|
|
19
|
-
* can be handed over as it is.
|
|
18
|
+
* object with `retrieveColor`, so a host's own colour map can be handed over as it is.
|
|
20
19
|
*/
|
|
21
20
|
export type ColorRamp = readonly ColorLike[] | {
|
|
22
21
|
retrieveColor(level: number): string;
|
|
@@ -56,7 +56,7 @@ export interface ControllerHost {
|
|
|
56
56
|
}
|
|
57
57
|
/**
|
|
58
58
|
* Something that takes over the pointer and keys of a view for a while - drawing new geometry,
|
|
59
|
-
* editing it, measuring - as
|
|
59
|
+
* editing it, measuring - as a map toolkit's controllers do on its map. The view offers it every
|
|
60
60
|
* event first; what it handles (returns true for) the view leaves alone, the rest - panning,
|
|
61
61
|
* zooming, hovering, selecting - goes on as usual.
|
|
62
62
|
*
|
|
@@ -39,7 +39,7 @@ export interface FrameInput {
|
|
|
39
39
|
* in, in doubles, so float32 vertices relative to it keep millimetres.
|
|
40
40
|
*/
|
|
41
41
|
viewProjection: ArrayLike<number>;
|
|
42
|
-
/** Whether clip z runs -1..1 (OpenGL's,
|
|
42
|
+
/** Whether clip z runs -1..1 (OpenGL's, as many hosts' cameras have it) rather than the backend's own. */
|
|
43
43
|
glDepth: boolean;
|
|
44
44
|
near: number;
|
|
45
45
|
pixelRatio: number;
|
|
@@ -59,8 +59,8 @@ export interface FrameInput {
|
|
|
59
59
|
* the heatmap and the GPU pick.
|
|
60
60
|
*
|
|
61
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 -
|
|
63
|
-
* on its WebGPU device - under that one's camera. The primitives cannot tell the two apart.
|
|
62
|
+
* camera of its own; `HostedGeometryEngine` draws into a frame someone else draws - a map's, a
|
|
63
|
+
* globe's, on its WebGPU device - under that one's camera. The primitives cannot tell the two apart.
|
|
64
64
|
*/
|
|
65
65
|
export declare abstract class GeometryEngine extends TypedEventEmitter<GeometryEngineEvents> {
|
|
66
66
|
readonly scene: Scene;
|
|
@@ -166,6 +166,25 @@ export declare abstract class GeometryEngine extends TypedEventEmitter<GeometryE
|
|
|
166
166
|
onBeforeDraw(callback: (width: number, height: number) => void): () => void;
|
|
167
167
|
/** Asks for a new frame, for a change only this engine's content knows about. */
|
|
168
168
|
abstract requestRepaint(): void;
|
|
169
|
+
/** What animates now - a camera flight, flow along the lines - and keeps frames coming. */
|
|
170
|
+
protected readonly animators: Set<string>;
|
|
171
|
+
/** Keeps frames coming while `key` animates something. */
|
|
172
|
+
setAnimating(key: string, animating: boolean): void;
|
|
173
|
+
/**
|
|
174
|
+
* The view's size in view (CSS) pixels, and frame pixels per view pixel: the last frame's,
|
|
175
|
+
* for an engine that draws into someone else's frame.
|
|
176
|
+
*/
|
|
177
|
+
get viewSize(): {
|
|
178
|
+
width: number;
|
|
179
|
+
height: number;
|
|
180
|
+
pixelRatio: number;
|
|
181
|
+
};
|
|
182
|
+
/**
|
|
183
|
+
* Where a world position was on the last frame drawn, in view pixels from its top-left; null
|
|
184
|
+
* behind the camera, or before the first frame. The frame's own camera, whoever made it: what
|
|
185
|
+
* a view puts its labels by when the host moves the camera.
|
|
186
|
+
*/
|
|
187
|
+
toView(p: readonly number[]): [number, number] | null;
|
|
169
188
|
/** Puts a primitive's meshes into the scenes of their passes; it is handed every frame. */
|
|
170
189
|
attach(primitive: GeometryPrimitive): void;
|
|
171
190
|
/** Takes a primitive's meshes out of the scenes; it is not disposed. */
|
package/engine/GeometryEngine.js
CHANGED
|
@@ -1 +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 P}from"../three/DensityMap.js";import{Halo as k}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 P,this.halo=new k,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.compiling=new Set,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(0===this.unready.size)return;if("function"!=typeof e.compileAsync)return void this.unready.clear();const t=[...this.unready].filter(([e])=>e.visible&&!this.compiling.has(e));0!==t.length&&(t.forEach(([e])=>this.compiling.add(e)),this.compile(e,t).catch(e=>console.warn("[geometry] Compiling in the background failed; drawn as it comes",e)).finally(()=>{t.forEach(([e])=>{this.compiling.delete(e),this.unready.delete(e),this.compiled.add(e)}),this.requestRepaint()}))}get compilingShaders(){return this.compiling.size>0}async compile(e,t){const r=[];for(const[s,i]of t){await M();const t=this.sceneOf(i);if(!this.renderer||!this.unready.has(s)||s.parent!==t)continue;const n=e.getRenderTarget();try{e.setRenderTarget(this.targetOf(i)),r.push(e.compileAsync(s,this.camera,t))}finally{e.setRenderTarget(n)}}await Promise.all(r)}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]]}function M(){const e=globalThis.scheduler;return"function"==typeof e?.yield?e.yield():new Promise(e=>setTimeout(e,0))}
|
|
1
|
+
import{AddEquation as e,Camera as t,Color as r,CustomBlending as i,DepthTexture as s,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 x}from"three/examples/jsm/tsl/display/BloomNode.js";import{TypedEventEmitter as T}from"../event/TypedEventEmitter.js";import{DensityMap as R}from"../three/DensityMap.js";import{Halo as P}from"../three/Halo.js";import{pickPassUniforms as k}from"./GeometryFrame.js";export class HostCamera extends t{updateProjectionMatrix(){}}export class GeometryEngine extends T{constructor(){super(),this.scene=new u,this.underlayScene=new u,this.bloomScene=new u,this.pickScene=new u,this.pickPass=k(),this.density=new R,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.compiling=new Set,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.animators=new Set,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 s(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)}}setAnimating(e,t){t?this.animators.add(e):this.animators.delete(e),t&&this.requestRepaint()}get viewSize(){const e=this.frame.pixelRatio||1;return{width:this.drawn.x/e,height:this.drawn.y/e,pixelRatio:e}}toView(e){const t=this.drawn.x,r=this.drawn.y;if(t<=0||r<=0)return null;const[i,s,n]=this.getOrigin()??[0,0,0],a=e[0]-i,o=e[1]-s,h=(e[2]??0)-n,c=this.drawnCamera.elements,d=c[0]*a+c[4]*o+c[8]*h+c[12],l=c[1]*a+c[5]*o+c[9]*h+c[13],p=c[3]*a+c[7]*o+c[11]*h+c[15];if(p<=1e-9)return null;const u=this.frame.pixelRatio||1;return[(d/p+1)/2*t/u,(1-l/p)/2*r/u]}attach(e){if(this.attached.has(e))return;const t=[],r=e.passes();Object.keys(r).forEach(e=>{for(const i of r[e]??[])i&&(this.sceneOf(e).add(i),t.push({mesh:i,pass:e}),this.compiled.has(i)||this.unready.set(i,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 i=r.getRenderTarget();return r.setRenderTarget(t),this.clearToZero(r),r.render(e,this.camera),r.setRenderTarget(i),!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 i={x:e,y:t,resolve:r},s=setTimeout(()=>{this.pending=this.pending.filter(e=>e!==i),r(null)},1e3);i.resolve=e=>{clearTimeout(s),r(e)},this.ready&&this.renderer&&this.drawn.x>0?this.runPick(i,this.drawn.x,this.drawn.y):(this.pending.push(i),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 s=x(r,1.2,.5,0);this.bloom=s;const n=new(function(){const e=Object.getPrototypeOf(l);return"function"==typeof e&&e!==Function.prototype&&"function"==typeof e.prototype?.render?e:l}())(t,s);n.outputColorTransform=!1;const a=n._quadMesh.material;a.transparent=!0,a.blending=i,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:i,height:s}=e;r.width=i,r.height=s,r.pixelRatio=e.pixelRatio,r.near=e.near,r.geocentric=!!e.geocentric,r.pxPerWorld=e.pxPerWorld??Math.hypot(t[0]*i/2,t[4]*s/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])*i/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 i=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 s=this.holdBack();try{return this.drawFrame(r,e,i,t)}finally{s.forEach(e=>{e.visible=!0})}}drawFrame(e,t,r,i){this.density.update();const s=e=>e.children.some(e=>e.visible);if(!s(this.scene)&&!s(this.underlayScene))return this.missPicks(),this.lastRenderMs=performance.now()-r,!1;if(i&&!i())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),s(this.underlayScene)&&e.render(this.underlayScene,this.camera),e.render(this.scene,this.camera),this.bloomPost&&s(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(0===this.unready.size)return;if("function"!=typeof e.compileAsync)return void this.unready.clear();const t=[...this.unready].filter(([e])=>e.visible&&!this.compiling.has(e));0!==t.length&&(t.forEach(([e])=>this.compiling.add(e)),this.compile(e,t).catch(e=>console.warn("[geometry] Compiling in the background failed; drawn as it comes",e)).finally(()=>{t.forEach(([e])=>{this.compiling.delete(e),this.unready.delete(e),this.compiled.add(e)}),this.requestRepaint()}))}get compilingShaders(){return this.compiling.size>0}async compile(e,t){const r=[];for(const[i,s]of t){await M();const t=this.sceneOf(s);if(!this.renderer||!this.unready.has(i)||i.parent!==t)continue;const n=e.getRenderTarget();try{e.setRenderTarget(this.targetOf(s)),r.push(e.compileAsync(i,this.camera,t))}finally{e.setRenderTarget(n)}}await Promise.all(r)}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 i=Math.floor(e.x*this.frame.pixelRatio),s=Math.floor(e.y*this.frame.pixelRatio),n=(i+.5)/t*2-1,a=1-(s+.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(i-3,s-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(i,s,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,i=t?.get?.(this.pickTarget.texture)?.texture;if(this.webgpu&&r&&i){const{GPUBufferUsage:e,GPUMapMode:t}=globalThis,s=256,n=r.createBuffer({size:7*s,usage:e.COPY_DST|e.MAP_READ}),a=r.createCommandEncoder();a.copyTextureToBuffer({texture:i},{buffer:n,bytesPerRow:s},[7,7]),r.queue.submit([a.finish()]);try{return await n.mapAsync(t.READ),{data:new Float32Array(n.getMappedRange().slice(0)),stride:s/4,bottomUp:!1}}finally{n.destroy()}}const s=await e.readRenderTargetPixelsAsync(this.pickTarget,0,0,7,7);return{data:new Float32Array(s.buffer,s.byteOffset,s.byteLength/4),stride:28,bottomUp:!0}}async readPick(e,t,r,i,s,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 i=0;i<7;i++){const s=r*h+4*i,n=Math.round(o[s]);if(n<=0)continue;const a=i-3,l=c?3-r:r-3;d.push({source:n,index:Math.round(o[s+1]),w:o[s+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(s,(e.x+.5)/r*2-1,1-(e.y+.5)/i*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,i,s=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,i,n,a]=[o[0],o[1],h[0],h[1]],[d,l]=[t*c[3]-o[3]-o[2]*s,r*c[3]-h[3]-h[2]*s],p=e*a-i*n;return[(d*a-i*l)/p,(e*l-d*n)/p,s]}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],i-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,i)=>i===e?l[r]:t)))/u);return[m[0],m[1],m[2]]}function M(){const e=globalThis.scheduler;return"function"==typeof e?.yield?e.yield():new Promise(e=>setTimeout(e,0))}
|
|
@@ -3,9 +3,6 @@ import { Matrix4, Vector2, Vector3 } from 'three/webgpu';
|
|
|
3
3
|
/**
|
|
4
4
|
* What drawing in pixels or metres needs to know about the frame being drawn. An engine fills it
|
|
5
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
6
|
*/
|
|
10
7
|
export interface GeometryFrame {
|
|
11
8
|
/** Frame pixels per world unit, at the view's centre: exact on a flat (orthographic) map. */
|
|
@@ -50,15 +47,15 @@ export interface PickOptions {
|
|
|
50
47
|
/**
|
|
51
48
|
* What may stand in front of geometry drawn on or under the ground: a node for the fragment
|
|
52
49
|
* 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).
|
|
54
|
-
* one; the package's own scene depth does without.
|
|
50
|
+
* the frame pixel, when not the fragment's own (the pick pass). A host's mask of what stands -
|
|
51
|
+
* buildings, trees - is one; the package's own scene depth does without.
|
|
55
52
|
*/
|
|
56
53
|
export interface GeometryOccluder {
|
|
57
54
|
/** Another for each new occluder: geometry made with an old one is made again. */
|
|
58
55
|
readonly id: number;
|
|
59
56
|
hides(distance: any, pixel?: any): any;
|
|
60
57
|
}
|
|
61
|
-
/** The
|
|
58
|
+
/** The same, by the name the lines take it under. */
|
|
62
59
|
export type LineOccluder = GeometryOccluder;
|
|
63
60
|
/**
|
|
64
61
|
* The passes an engine draws, each a scene:
|
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
import type { ColorRamp } from '../common/Colors';
|
|
2
|
+
import type { GeometryEngine } from './GeometryEngine';
|
|
2
3
|
import type { CameraLimits, CameraState } from './MapCamera';
|
|
3
4
|
import { ThemeScheme } from '../theme/Theme';
|
|
4
5
|
/** How what is lit - selected, pointed at, emphasized - is set off. */
|
|
5
6
|
export interface GeometryHighlightOptions {
|
|
6
7
|
/** A glow round it, or an outline. A glow by default. */
|
|
7
8
|
look?: 'glow' | 'outline';
|
|
8
|
-
/** The glow from the bloom pass - soft, over everything - or drawn in the line shader, cheaper. */
|
|
9
|
-
glow?: 'bloom' | 'shader';
|
|
9
|
+
/** The glow from the bloom pass - soft, over everything - or drawn in the line shader, cheaper; or none. */
|
|
10
|
+
glow?: 'bloom' | 'shader' | 'none';
|
|
10
11
|
/** The outline's colour, and width in view pixels. */
|
|
11
12
|
outlineColor?: string;
|
|
12
13
|
outlineWidth?: number;
|
|
@@ -14,6 +15,14 @@ export interface GeometryHighlightOptions {
|
|
|
14
15
|
hoverFades?: boolean;
|
|
15
16
|
/** How bright the rest is then, 0 to 1. */
|
|
16
17
|
othersShade?: number;
|
|
18
|
+
/** What the rest is shaded towards then: 0 black, 1 white. The theme's by default (dark 0, light 1). */
|
|
19
|
+
othersToward?: number;
|
|
20
|
+
/**
|
|
21
|
+
* How opaque a selected or emphasised feature is whose own style - or a filter - fades or hides
|
|
22
|
+
* it: drawn lit all the same, its glow or outline behind it, only this faint, to show it is not
|
|
23
|
+
* in view now. Never picked where its style hides it. 0.6 by default.
|
|
24
|
+
*/
|
|
25
|
+
outsideOpacity?: number;
|
|
17
26
|
/** Whether pointing at a feature lights it as the selection is. On by default. */
|
|
18
27
|
hoverLights?: boolean;
|
|
19
28
|
}
|
|
@@ -49,6 +58,21 @@ export type GeometryThemeOptions = Partial<GeometryTheme> & {
|
|
|
49
58
|
export declare const DARK_THEME: GeometryTheme;
|
|
50
59
|
/** The light look: Protomaze's light tokens, a day sky. */
|
|
51
60
|
export declare const LIGHT_THEME: GeometryTheme;
|
|
61
|
+
/** What a view inside a host's frame is given, besides its options. */
|
|
62
|
+
export interface GeometryViewHostOptions<E extends GeometryEngine = GeometryEngine> {
|
|
63
|
+
/**
|
|
64
|
+
* An engine that draws in someone else's frame (`HostedGeometryEngine`), for a view inside a
|
|
65
|
+
* host - a map, a globe - rather than on a canvas of its own. The host has the camera, the
|
|
66
|
+
* ground and the input: such a view has layers, their looks, the highlight, selection and
|
|
67
|
+
* picking (`pickAt`), and is never `init`ed. Left out, the view makes its own canvas engine.
|
|
68
|
+
*/
|
|
69
|
+
engine?: E;
|
|
70
|
+
/**
|
|
71
|
+
* With `engine`: the host's element, round which the `--pm-*` tokens are read. The page's
|
|
72
|
+
* root by default.
|
|
73
|
+
*/
|
|
74
|
+
element?: HTMLElement | null;
|
|
75
|
+
}
|
|
52
76
|
export interface GeometryViewOptions {
|
|
53
77
|
/** A 2D map (orthographic, straight down) or 3D (perspective, tilting). 3D by default. */
|
|
54
78
|
mode?: '2d' | '3d';
|
package/engine/GeometryView.d.ts
CHANGED
|
@@ -7,8 +7,8 @@ import { GeometryLayer, LayerHit, LayerHost, ResolvedHighlight, SelectMode } fro
|
|
|
7
7
|
import { CanvasGeometryEngine } from '../three/CanvasGeometryEngine';
|
|
8
8
|
import { Ground, GroundOptions } from '../three/Ground';
|
|
9
9
|
import { Lighting } from '../three/Shading';
|
|
10
|
-
import { GeometryFrameStats } from './GeometryEngine';
|
|
11
|
-
import { GeometryViewOptions } from './GeometryOptions';
|
|
10
|
+
import { GeometryEngine, GeometryFrameStats } from './GeometryEngine';
|
|
11
|
+
import { GeometryViewHostOptions, GeometryViewOptions } from './GeometryOptions';
|
|
12
12
|
import { CameraState, MapCamera } from './MapCamera';
|
|
13
13
|
import { ResolvedTheme } from '../theme/Theme';
|
|
14
14
|
/** What the pointer is on, or a click hit: a layer's feature, and the point on it. */
|
|
@@ -60,12 +60,24 @@ export interface GeometryViewEvents {
|
|
|
60
60
|
* view.addLayer(new TubeLayer({ features: pipes, style: f => ({ color: colorOf(f) }) }));
|
|
61
61
|
* view.on('select', selection => ...);
|
|
62
62
|
* ```
|
|
63
|
+
*
|
|
64
|
+
* Or inside a host's own frame - a map's, a globe's - on an engine that draws there: the host keeps
|
|
65
|
+
* its camera, ground and input, the view its layers, their looks, the highlight and the picking.
|
|
66
|
+
*
|
|
67
|
+
* ```ts
|
|
68
|
+
* const view = new GeometryView({ engine: hostedEngine, mode: '3d' });
|
|
69
|
+
* view.addLayer(lines);
|
|
70
|
+
* const hit = await view.pickAt(x, y);
|
|
71
|
+
* ```
|
|
63
72
|
*/
|
|
64
|
-
export declare class GeometryView extends TypedEventEmitter<GeometryViewEvents> implements LayerHost, ControllerHost {
|
|
65
|
-
readonly engine:
|
|
73
|
+
export declare class GeometryView<E extends GeometryEngine = CanvasGeometryEngine> extends TypedEventEmitter<GeometryViewEvents> implements LayerHost, ControllerHost {
|
|
74
|
+
readonly engine: E;
|
|
66
75
|
readonly camera: MapCamera;
|
|
67
76
|
readonly lighting: Lighting;
|
|
68
|
-
|
|
77
|
+
/** Whether the view draws in a host's frame, on an engine it was given, rather than on its own canvas. */
|
|
78
|
+
readonly hosted: boolean;
|
|
79
|
+
/** In a host's frame: the host's element, round which the theme's tokens are read. */
|
|
80
|
+
private readonly hostElement;
|
|
69
81
|
mode: '2d' | '3d';
|
|
70
82
|
highlight: ResolvedHighlight;
|
|
71
83
|
/** Labels on world positions over the view: what controllers measure, or the application's own. */
|
|
@@ -92,7 +104,19 @@ export declare class GeometryView extends TypedEventEmitter<GeometryViewEvents>
|
|
|
92
104
|
private drag;
|
|
93
105
|
private touches;
|
|
94
106
|
private pinch;
|
|
95
|
-
constructor(options?: GeometryViewOptions);
|
|
107
|
+
constructor(options?: GeometryViewOptions & GeometryViewHostOptions<E>);
|
|
108
|
+
/**
|
|
109
|
+
* The ground's up at the origin: a level world's z, or on a globe (geocentric) the ellipsoid's
|
|
110
|
+
* normal at the engine's origin - what shafts stand along and volumes rise along.
|
|
111
|
+
*/
|
|
112
|
+
get up(): [number, number, number];
|
|
113
|
+
/** The view's own canvas engine; a view in a host's frame has none. */
|
|
114
|
+
private get own();
|
|
115
|
+
/**
|
|
116
|
+
* What every view does once it draws: its layers built on the frames, the frames' figures
|
|
117
|
+
* reported, the theme's tokens followed round `themeRoot` (the page's root when null).
|
|
118
|
+
*/
|
|
119
|
+
private start;
|
|
96
120
|
/** Puts the view into `container`, which it fills, and starts drawing. */
|
|
97
121
|
init(container: HTMLElement): Promise<void>;
|
|
98
122
|
dispose(): void;
|
|
@@ -183,6 +207,7 @@ export declare class GeometryView extends TypedEventEmitter<GeometryViewEvents>
|
|
|
183
207
|
getSelection(): GeometrySelection;
|
|
184
208
|
/** A layer's place among the view's, overlays above them all. */
|
|
185
209
|
rankOf(layer: GeometryLayer<any, any>): number;
|
|
210
|
+
/** Whether anything is pointed at or emphasised, in any layer: the rest is shaded then (`highlight.hoverFades`). */
|
|
186
211
|
get anyHovered(): boolean;
|
|
187
212
|
get windowsLit(): number;
|
|
188
213
|
requestRepaint(): void;
|
package/engine/GeometryView.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{parseColor as t,toCss as e}from"../common/Colors.js";import{Disposables as i}from"../common/Disposables.js";import{isEmptyBounds as s,unionBounds as o}from"../data/Geometry.js";import{TypedEventEmitter as r}from"../event/TypedEventEmitter.js";import{LabelOverlay as n}from"./Labels.js";import{CanvasGeometryEngine as h}from"../three/CanvasGeometryEngine.js";import{Ground as a}from"../three/Ground.js";import{Lighting as l}from"../three/Shading.js";import{DARK_THEME as c,LIGHT_THEME as d}from"./GeometryOptions.js";import{MapCamera as p}from"./MapCamera.js";import{resolveTheme as u,watchTheme as m}from"../theme/Theme.js";export class GeometryView extends r{constructor(t={}){super(),this.lighting=new l,this.up=[0,0,1],this.labels=null,this.resolvedKey="",this.layers=[],this.overlays=[],this.controller=null,this.controllerDrag=null,this.root=null,this.disposables=new i,this.hovered=null,this.ground=null,this.groundOptions=null,this.lastCamera="",this.frames=[],this.pendingMode=null,this.hoverQueued=!1,this.pointer=null,this.drag=null,this.touches=new Map,this.pinch=null,this.options=t,this.mode=t.mode??"3d",this.engine=new h({antialias:t.antialias,forceWebGL:t.forceWebGL,maxPixelRatio:t.maxPixelRatio}),this.camera=new p(t.camera),this.camera.orthographic="2d"===this.mode,t.fov&&(this.camera.fovY=t.fov),t.limits&&(this.camera.limits={...this.camera.limits,...t.limits}),this.applyOptions()}async init(t){this.disposables=new i;const e=document.createElement("div");e.style.position="relative",e.style.width="100%",e.style.height="100%",e.style.overflow="hidden",e.style.outline="none",e.tabIndex=0,t.appendChild(e),e.appendChild(this.engine.canvas),this.root=e,this.disposables.add(()=>e.remove());const s=new n(e,t=>this.toScreen(t));this.labels=s,this.disposables.add(()=>{s.dispose(),this.labels=null}),this.resolvedKey="",this.applyOptions(),this.disposables.add(m(e,()=>{this.applyOptions(),this.requestRepaint()}));const o=()=>{const t=e.getBoundingClientRect();this.engine.setSize(t.width,t.height,window.devicePixelRatio||1)};o();const r=new ResizeObserver(o);r.observe(e),this.disposables.add(()=>r.disconnect()),this.listen(),this.engine.setCamera((t,e)=>(this.camera.tick()?this.engine.setAnimating("camera",!0):(this.engine.setAnimating("camera",!1),this.finishModeSwitch()),this.emitCamera(),this.ground?.setViewDistance(this.camera.state.distance),this.camera.frame(t,e))),this.disposables.add(this.engine.onBeforeRender(()=>{let t=!1;for(const e of[...this.layers,...this.overlays]){const i=e.wantsBuild;e.beforeRender(!t),i&&(t&&this.requestRepaint(),t=!0)}})),this.disposables.add(this.engine.on("frame",t=>this.onFrame(t))),await this.engine.init(),this.applyRuntimeOptions(),this.emit("ready")}dispose(){this.setController(null),this.disposables.dispose(),this.layers.forEach(t=>t.detach()),this.overlays.forEach(t=>t.detach()),this.ground?.dispose(),this.ground=null,this.engine.dispose(),this.root=null}get element(){return this.root}setOptions(t){const e=void 0!==t.mode&&t.mode!==this.mode;this.options={...this.options,...t},t.limits&&(this.camera.limits={...this.camera.limits,...t.limits}),t.fov&&(this.camera.fovY=t.fov),this.applyOptions(),this.applyRuntimeOptions(),e&&this.setMode(t.mode),this.requestRepaint()}getOptions(){return this.options}get tokens(){return this.resolved}applyOptions(){this.resolveColors();const e=this.options.highlight??{};this.highlight={look:e.look??"glow",glow:e.glow??"bloom",outlineColor:t(e.outlineColor??this.theme.outline),outlineWidth:e.outlineWidth??2,hoverFades:e.hoverFades??!0,othersShade:e.othersShade??.55,othersToward:this.theme.othersToward,hoverLights:e.hoverLights??!0},this.engine.setBackground(g(this.theme.background));const i=this.theme.sky;this.engine.sky.setColors({zenith:g(i.zenith),horizon:g(i.horizon),glow:g(i.glow),below:g(i.horizon)}),this.applyGroundColors()}resolveColors(){const t=this.options.theme,e="object"==typeof t&&t?t:{},i=u(this.root,"string"==typeof t?t:e.scheme??"dark"),s="light"===i.scheme?d:c,o={...s,background:i.background,outline:i.highlight,grid:i.text,othersToward:"light"===i.scheme?1:0};for(const t of Object.keys(s))void 0!==e[t]&&(o[t]=e[t]);this.theme=o,this.resolved=i;const r=JSON.stringify(i);r!==this.resolvedKey&&(this.resolvedKey=r,this.labels?.setTheme(i),this.overlays.forEach(t=>t.restyle()))}applyRuntimeOptions(){const t=this.options.bloom;this.engine.bloom&&(this.engine.bloom.strength.value=t?.strength??1.2,this.engine.bloom.radius.value=t?.radius??.5,this.engine.bloom.threshold.value=t?.threshold??0);const e=this.options.halo;this.engine.halo.strength.value=!1===e?0:e?.strength??.55,this.engine.halo.blur.value=!1===e?0:e?.blur??12;const i=this.options.density;(i?.ramp||i?.top)&&this.engine.density.setColorMap(i.ramp??this.engine.density.colorMap,i.top),void 0!==i?.opacity&&(this.engine.density.opacity.value=i.opacity)}addLayer(t,e){if(this.layers.includes(t))return t;const i=e?this.layers.indexOf(e):-1;return i>=0?this.layers.splice(i,0,t):this.layers.push(t),t.attach(this),this.requestRepaint(),t}removeLayer(t){const e=this.layers.indexOf(t);e<0||(this.hovered?.layer===t&&this.setHover(null),this.layers.splice(e,1),t.detach(),this.requestRepaint())}getLayers(){return this.layers}getLayer(t){return this.layers.find(e=>e.id===t)}addOverlay(t){this.overlays.includes(t)||(this.overlays.push(t),t.setOverlay(!0,this.overlays.length),t.setPickable(!1),t.attach(this),this.requestRepaint())}removeOverlay(t){const e=this.overlays.indexOf(t);e<0||(this.overlays.splice(e,1),t.detach(),this.requestRepaint())}setController(t){t!==this.controller&&(this.controller?.detach(),this.controller=t,this.controllerDrag=null,t?.attach(this),this.applyCursor(),this.requestRepaint())}getController(){return this.controller}get viewSize(){return this.engine.viewSize}toScreen(t){const{width:e,height:i}=this.engine.viewSize;if(e<=0||i<=0)return null;const s=this.camera.frame(e,i).viewProjection,o=t[0],r=t[1],n=t[2]??0,h=s[0]*o+s[1]*r+s[2]*n+s[3],a=s[4]*o+s[5]*r+s[6]*n+s[7],l=s[12]*o+s[13]*r+s[14]*n+s[15];return l<=1e-9?null:[(h/l+1)/2*e,(1-a/l)/2*i]}rayAt(t,e){const{width:i,height:s}=this.engine.viewSize;return this.camera.ray(t,e,i,s)}toGround(t,e,i=this.camera.state.target[2]){const{width:s,height:o}=this.engine.viewSize;return this.camera.groundAt(t,e,s,o,i)}pixelSizeAt(t){const{height:e}=this.engine.viewSize,i=Math.tan(this.camera.fovY*Math.PI/360);if(this.camera.orthographic)return 2*this.camera.state.distance*i/Math.max(1,e);const{f:s,eye:o}=this.camera.basis(),r=(t[0]-o[0])*s[0]+(t[1]-o[1])*s[1]+((t[2]??0)-o[2])*s[2];return 2*Math.max(r,this.camera.near())*i/Math.max(1,e)}bounds(){let t=null;for(const e of this.layers){const i=e.bounds();s(i)||(t=t?o(t,i):i)}return t}setGround(t){if(this.ground&&(this.engine.baseScene.remove(this.ground.mesh),this.ground.dispose(),this.ground=null),this.groundOptions=t,!t)return void this.requestRepaint();const[e,i,s,o]=t.bounds,r=this.engine.originFor([(e+s)/2,(i+o)/2,t.z??0]),n={spacing:10,major:10,color:this.theme.grid};this.ground=new a({color:this.theme.ground,...t,grid:t.grid?{...n,...t.grid}:"grid"in t?t.grid:n},r,{eye:this.engine.sky.eye,fog:this.engine.sky.horizon}),this.applyGroundColors(),this.engine.baseScene.add(this.ground.mesh),this.requestRepaint()}applyGroundColors(){const t=this.ground,e=this.groundOptions;if(!t||!e)return;const i=e.grid?e.grid.color:void 0;t.setColors({color:g(e.color??this.theme.ground),grid:g(i??this.theme.grid)})}getGround(){return this.ground}setDensity(t){const e=t?.layers?.map(t=>"string"==typeof t?this.getLayer(t):t);this.layers.forEach(i=>i.setDensity(!!t&&(!e||e.includes(i)))),(t?.ramp||t?.top)&&this.engine.density.setColorMap(t.ramp??this.engine.density.colorMap,t.top),this.requestRepaint()}getCamera(){return{...this.camera.state,target:[...this.camera.state.target]}}setCamera(t){this.camera.set(t),this.requestRepaint()}flyTo(t,e=900){this.camera.flyTo(t,e),this.engine.setAnimating("camera",!0)}fit(t=this.bounds(),e=900,i=.1){if(!t||s(t))return;const{width:o,height:r}=this.engine.viewSize,n=this.camera.fit(t.min,t.max,o,r,i);e>0?this.flyTo(n,e):this.setCamera(n)}setMode(t,e=55){if(this.options.mode=t,"2d"===t){if("2d"===this.mode&&this.camera.orthographic)return;this.pendingMode="2d",this.flyTo({tilt:0},450)}else{this.pendingMode=null;const t="2d"===this.mode;this.mode="3d",this.camera.orthographic=!1,t&&this.flyTo({tilt:Math.max(this.camera.state.tilt,e)},800),this.emit("mode","3d"),this.requestRepaint()}}finishModeSwitch(){"2d"===this.pendingMode&&(this.pendingMode=null,this.mode="2d",this.camera.orthographic=!0,this.emit("mode","2d"),this.requestRepaint())}async pickAt(t,e){const i=await this.engine.pick(t,e);return i?{...i.hit,point:i.point}:null}setHover(t){const e=this.hovered;e?.layer===t?.layer&&e?.id===t?.id||(e?.layer.setHovered(null),t?.layer.setHovered(t.id),this.hovered=t?{...e??{},...t}:null,this.applyCursor(),this.requestRepaint())}select(t,e,i="replace"){t.select(e,i),this.emitSelection()}clearSelection(){this.layers.forEach(t=>t.clearSelection()),this.emitSelection()}getSelection(){const t=this.layers.map(t=>({layer:t,ids:t.selection()})).filter(t=>t.ids.length>0);return{layers:t,count:t.reduce((t,e)=>t+e.ids.length,0)}}rankOf(t){const e=this.layers.indexOf(t);if(e>=0)return e;const i=this.overlays.indexOf(t);return i>=0?this.layers.length+i:0}get anyHovered(){return null!==this.hovered}get windowsLit(){return this.theme.windowsLit}requestRepaint(){this.engine.requestRepaint()}setAnimating(t,e){this.engine.setAnimating(t,e)}emitSelection(){this.emit("select",this.getSelection())}emitCamera(){const t=this.camera.state,e=`${t.target.join(",")}|${t.distance}|${t.heading}|${t.tilt}`;e!==this.lastCamera&&(this.lastCamera=e,this.emit("camera",this.getCamera()))}onFrame(t){this.labels?.update();const e=performance.now();for(this.frames.push(e);this.frames.length>0&&e-this.frames[0]>1e3;)this.frames.shift();const i=this.engine.getRenderer()?.info?.render??{};this.emit("frame",{...t,fps:this.frames.length,drawCalls:i.drawCalls??i.calls??0,triangles:i.triangles??0,backend:this.engine.webgpu?"webgpu":"webgl"})}local(t){const e=this.root.getBoundingClientRect();return{x:t.clientX-e.left,y:t.clientY-e.top}}pointerOf(t){const{x:e,y:i}=this.local(t);return{x:e,y:i,button:t.button,shift:t.shiftKey,ctrl:t.ctrlKey||t.metaKey,alt:t.altKey,pointerType:t.pointerType??"mouse",native:t}}capture(t){try{this.engine.canvas.setPointerCapture(t)}catch{}}applyCursor(){if(!this.root)return;const t=this.hovered?"pointer":this.drag?.moved?"pan"===this.drag.kind?"grabbing":"move":"grab";this.engine.canvas.style.cursor=this.controller?.cursor??t}listen(){const t=this.engine.canvas;t.style.cursor="grab";const e=(t,e,i,s)=>{t.addEventListener(e,i,s),this.disposables.add(()=>t.removeEventListener(e,i,s))};e(t,"contextmenu",t=>t.preventDefault()),e(t,"pointerdown",t=>this.onDown(t)),e(t,"pointermove",t=>this.onMove(t)),e(t,"pointerup",t=>this.onUp(t)),e(t,"pointercancel",t=>this.onUp(t,!0)),e(t,"pointerleave",()=>{this.pointer=null,this.controller?.onPointerLeave(),this.drag||this.setHover(null),this.emit("hover",null)}),e(t,"wheel",t=>this.onWheel(t),{passive:!1}),e(t,"dblclick",t=>{if(this.controller?.onDoubleClick(this.pointerOf(t)))return void this.applyCursor();if(!1===this.options.interactive)return;const{x:e,y:i}=this.local(t),{width:s,height:o}=this.engine.viewSize,r=this.camera.groundAt(e,i,s,o);r&&this.flyTo({target:r,distance:this.camera.state.distance*(t.shiftKey?2:.45)},600)}),e(this.root,"keydown",t=>{if(this.controller?.onKeyDown(t))return t.preventDefault(),void this.applyCursor();"Escape"===t.key&&this.clearSelection()})}onDown(t){this.root?.focus({preventScroll:!0});const{x:e,y:i}=this.local(t);if("touch"===t.pointerType&&(this.touches.set(t.pointerId,{x:e,y:i}),2===this.touches.size))return this.drag=null,void(this.pinch=this.pinchOf());if(this.controller&&null===this.controllerDrag&&this.controller.onPointerDown(this.pointerOf(t)))return this.controllerDrag=t.pointerId,this.camera.stop(),this.capture(t.pointerId),void this.applyCursor();this.camera.stop();const s=2===t.button||1===t.button||t.ctrlKey&&0===t.button&&"none"===this.options.selection,{width:o,height:r}=this.engine.viewSize;this.drag={id:t.pointerId,kind:s?"rotate":"pan",x:e,y:i,startX:e,startY:i,time:performance.now(),anchor:s?null:this.camera.groundAt(e,i,o,r),moved:!1,history:[]},this.capture(t.pointerId)}onMove(t){const{x:e,y:i}=this.local(t);if(this.pointer={x:e,y:i},this.controllerDrag===t.pointerId)return this.controller?.onPointerDrag(this.pointerOf(t)),void this.applyCursor();if("touch"===t.pointerType&&this.touches.has(t.pointerId)&&(this.touches.set(t.pointerId,{x:e,y:i}),this.pinch&&2===this.touches.size))return void this.onPinch();const s=this.drag;if(!s||s.id!==t.pointerId){return(this.controller?.onPointerMove(this.pointerOf(t))??!1)||this.queueHover(),void this.applyCursor()}if(!s.moved&&Math.hypot(e-s.startX,i-s.startY)>5&&(s.moved=!0,this.applyCursor()),!s.moved||!1===this.options.interactive)return;const{width:o,height:r}=this.engine.viewSize;if("pan"===s.kind&&s.anchor){this.camera.panTo(s.anchor,e,i,o,r);const t=performance.now();for(s.history.push({t:t,target:[this.camera.state.target[0],this.camera.state.target[1]]});s.history.length>0&&t-s.history[0].t>100;)s.history.shift()}else"rotate"===s.kind&&this.camera.rotate(.3*(e-s.x),"3d"===this.mode?.25*(i-s.y):0);s.x=e,s.y=i,this.requestRepaint()}onUp(t,e=!1){if(this.touches.delete(t.pointerId),this.touches.size<2&&(this.pinch=null),this.controllerDrag===t.pointerId){this.controllerDrag=null;try{this.engine.canvas.releasePointerCapture(t.pointerId)}catch{}return this.controller?.onPointerUp(this.pointerOf(t)),void this.applyCursor()}const i=this.drag;if(i&&i.id===t.pointerId){this.drag=null;try{this.engine.canvas.releasePointerCapture(t.pointerId)}catch{}if(this.applyCursor(),!e){if(i.moved&&"pan"===i.kind&&i.history.length>1){const t=i.history[0],e=i.history[i.history.length-1],s=(e.t-t.t)/1e3;s>.01&&performance.now()-e.t<60&&(this.camera.glide([(e.target[0]-t.target[0])/s,(e.target[1]-t.target[1])/s]),this.engine.setAnimating("camera",!0))}!i.moved&&performance.now()-i.time<600&&0===t.button&&this.onClick(t)}}}async onClick(t){if(this.controller?.onClick(this.pointerOf(t)))return void this.applyCursor();const{x:e,y:i}=this.local(t),s=await this.pickAt(e,i),o={hit:s,shift:t.shiftKey,ctrl:t.ctrlKey||t.metaKey,alt:t.altKey,x:e,y:i,native:t};this.emit("click",o);const r=this.options.selection??"multi";if("none"===r)return;const n="multi"===r&&(o.ctrl||o.shift);if(s){if(n)s.layer.select([s.id],o.ctrl?"toggle":"add");else{this.layers.forEach(t=>{t!==s.layer&&t.clearSelection()});const t=s.layer.selection(),e=1===t.length&&t[0]===s.id;s.layer.select(e?[]:[s.id],"replace")}this.emitSelection()}else n||this.clearSelection()}onWheel(t){if(!1===this.options.interactive)return;t.preventDefault();const{x:e,y:i}=this.local(t),{width:s,height:o}=this.engine.viewSize,r=1===t.deltaMode?33:2===t.deltaMode?400:1,n=Math.exp(t.deltaY*r*.0016);this.camera.stop(),this.camera.zoomAt(n,e,i,s,o),this.requestRepaint(),this.queueHover()}pinchOf(){const[t,e]=[...this.touches.values()];return{distance:Math.hypot(e.x-t.x,e.y-t.y),angle:Math.atan2(e.y-t.y,e.x-t.x),midY:(t.y+e.y)/2}}onPinch(){const t=this.pinch,e=this.pinchOf(),[i,s]=[...this.touches.values()],{width:o,height:r}=this.engine.viewSize;this.camera.zoomAt(t.distance/Math.max(1,e.distance),(i.x+s.x)/2,(i.y+s.y)/2,o,r),this.camera.rotate(180*-(e.angle-t.angle)/Math.PI,"3d"===this.mode?.25*(e.midY-t.midY):0),this.pinch=e,this.requestRepaint()}queueHover(){!1===this.options.hover||this.hoverQueued||this.drag?.moved||(this.hoverQueued=!0,requestAnimationFrame(async()=>{this.hoverQueued=!1;const t=this.pointer;if(!t||this.drag?.moved)return;const e=await this.pickAt(t.x,t.y);if(!this.pointer)return;const i=e?.layer!==this.hovered?.layer||e?.id!==this.hovered?.id;this.setHover(e),e&&(this.hovered=e),i&&this.emit("hover",e)}))}}function g(i){const[s,o,r]=t(i);return e([s,o,r,1])}
|
|
1
|
+
import{parseColor as t,toCss as e}from"../common/Colors.js";import{Disposables as i}from"../common/Disposables.js";import{isEmptyBounds as s,unionBounds as o}from"../data/Geometry.js";import{TypedEventEmitter as r}from"../event/TypedEventEmitter.js";import{LabelOverlay as n}from"./Labels.js";import{CanvasGeometryEngine as h}from"../three/CanvasGeometryEngine.js";import{ellipsoidUp as a}from"../math/Projection.js";import{Ground as l}from"../three/Ground.js";import{Lighting as c}from"../three/Shading.js";import{DARK_THEME as d,LIGHT_THEME as p}from"./GeometryOptions.js";import{MapCamera as u}from"./MapCamera.js";import{resolveTheme as m,watchTheme as g}from"../theme/Theme.js";export class GeometryView extends r{constructor(t={}){super(),this.lighting=new c,this.labels=null,this.resolvedKey="",this.layers=[],this.overlays=[],this.controller=null,this.controllerDrag=null,this.root=null,this.disposables=new i,this.hovered=null,this.ground=null,this.groundOptions=null,this.lastCamera="",this.frames=[],this.pendingMode=null,this.hoverQueued=!1,this.pointer=null,this.drag=null,this.touches=new Map,this.pinch=null;const{engine:e,element:s,...o}=t;if(this.options=o,this.mode=t.mode??"3d",this.hosted=!!e,this.hostElement=s??null,this.engine=e??new h({antialias:t.antialias,forceWebGL:t.forceWebGL,maxPixelRatio:t.maxPixelRatio}),this.camera=new u(t.camera),this.camera.orthographic="2d"===this.mode,t.fov&&(this.camera.fovY=t.fov),t.limits&&(this.camera.limits={...this.camera.limits,...t.limits}),this.applyOptions(),this.hosted){this.start(this.hostElement);const t=()=>{this.applyRuntimeOptions(),this.emit("ready")};this.engine.getRenderer()&&t(),this.disposables.add(this.engine.on("ready",t))}}get up(){if(this.engine.frame.geocentric){const t=this.engine.getOrigin();if(t)return a(t)}return[0,0,1]}get own(){if(this.hosted||!(this.engine instanceof h))throw new Error("[geometry] A view in a host's frame has no canvas, camera or ground of its own: the host has them");return this.engine}start(t){this.resolvedKey="",this.applyOptions();const e=t??("undefined"!=typeof document?document.documentElement:null);e&&this.disposables.add(g(e,()=>{this.applyOptions(),this.requestRepaint()})),this.disposables.add(this.engine.onBeforeRender(()=>{let t=!1;for(const e of[...this.layers,...this.overlays]){const i=e.wantsBuild;e.beforeRender(!t),i&&(t&&this.requestRepaint(),t=!0)}})),this.disposables.add(this.engine.on("frame",t=>this.onFrame(t)))}async init(t){const e=this.own;this.disposables=new i;const s=document.createElement("div");s.style.position="relative",s.style.width="100%",s.style.height="100%",s.style.overflow="hidden",s.style.outline="none",s.tabIndex=0,t.appendChild(s),s.appendChild(e.canvas),this.root=s,this.disposables.add(()=>s.remove());const o=new n(s,t=>this.toScreen(t));this.labels=o,this.disposables.add(()=>{o.dispose(),this.labels=null});const r=()=>{const t=s.getBoundingClientRect();e.setSize(t.width,t.height,window.devicePixelRatio||1)};r();const h=new ResizeObserver(r);h.observe(s),this.disposables.add(()=>h.disconnect()),this.listen(),e.setCamera((t,i)=>(this.camera.tick()?e.setAnimating("camera",!0):(e.setAnimating("camera",!1),this.finishModeSwitch()),this.emitCamera(),this.ground?.setViewDistance(this.camera.state.distance),this.camera.frame(t,i))),this.start(s),await e.init(),this.applyRuntimeOptions(),this.emit("ready")}dispose(){this.setController(null),this.disposables.dispose(),this.layers.forEach(t=>t.detach()),this.overlays.forEach(t=>t.detach()),this.ground?.dispose(),this.ground=null,this.hosted||this.engine.dispose(),this.root=null}get element(){return this.root}setOptions(t){const e=void 0!==t.mode&&t.mode!==this.mode;this.options={...this.options,...t},t.limits&&(this.camera.limits={...this.camera.limits,...t.limits}),t.fov&&(this.camera.fovY=t.fov),this.applyOptions(),this.applyRuntimeOptions(),e&&this.setMode(t.mode),this.requestRepaint()}getOptions(){return this.options}get tokens(){return this.resolved}applyOptions(){this.resolveColors();const e=this.options.highlight??{};if(this.highlight={look:e.look??"glow",glow:e.glow??"bloom",outlineColor:t(e.outlineColor??this.theme.outline),outlineWidth:e.outlineWidth??2,hoverFades:e.hoverFades??!0,othersShade:e.othersShade??.55,othersToward:e.othersToward??this.theme.othersToward,hoverLights:e.hoverLights??!0,outsideOpacity:e.outsideOpacity??.6},!this.hosted){const t=this.own;t.setBackground(y(this.theme.background));const e=this.theme.sky;t.sky.setColors({zenith:y(e.zenith),horizon:y(e.horizon),glow:y(e.glow),below:y(e.horizon)})}this.applyGroundColors()}resolveColors(){const t=this.options.theme,e="object"==typeof t&&t?t:{},i=this.hosted?this.hostElement:this.root,s=m(i,"string"==typeof t?t:e.scheme??"dark"),o="light"===s.scheme?p:d,r={...o,background:s.background,outline:s.highlight,grid:s.text,othersToward:"light"===s.scheme?1:0};for(const t of Object.keys(o))void 0!==e[t]&&(r[t]=e[t]);this.theme=r,this.resolved=s;const n=JSON.stringify(s);n!==this.resolvedKey&&(this.resolvedKey=n,this.labels?.setTheme(s),this.overlays.forEach(t=>t.restyle()))}applyRuntimeOptions(){const t=this.options.bloom;this.engine.bloom&&(this.engine.bloom.strength.value=t?.strength??1.2,this.engine.bloom.radius.value=t?.radius??.5,this.engine.bloom.threshold.value=t?.threshold??0);const e=this.options.halo;this.engine.halo.strength.value=!1===e?0:e?.strength??.55,this.engine.halo.blur.value=!1===e?0:e?.blur??12;const i=this.options.density;(i?.ramp||i?.top)&&this.engine.density.setColorMap(i.ramp??this.engine.density.colorMap,i.top),void 0!==i?.opacity&&(this.engine.density.opacity.value=i.opacity)}addLayer(t,e){if(this.layers.includes(t))return t;const i=e?this.layers.indexOf(e):-1;return i>=0?this.layers.splice(i,0,t):this.layers.push(t),t.attach(this),this.requestRepaint(),t}removeLayer(t){const e=this.layers.indexOf(t);e<0||(this.hovered?.layer===t&&this.setHover(null),this.layers.splice(e,1),t.detach(),this.requestRepaint())}getLayers(){return this.layers}getLayer(t){return this.layers.find(e=>e.id===t)}addOverlay(t){this.overlays.includes(t)||(this.overlays.push(t),t.setOverlay(!0,this.overlays.length),t.setPickable(!1),t.attach(this),this.requestRepaint())}removeOverlay(t){const e=this.overlays.indexOf(t);e<0||(this.overlays.splice(e,1),t.detach(),this.requestRepaint())}setController(t){if(t!==this.controller){if(t&&this.hosted)throw new Error("[geometry] Controllers need the view's own pointer and camera: a view in a host's frame has neither");this.controller?.detach(),this.controller=t,this.controllerDrag=null,t?.attach(this),this.applyCursor(),this.requestRepaint()}}getController(){return this.controller}get viewSize(){return this.engine.viewSize}toScreen(t){if(this.hosted)return this.engine.toView(t);const{width:e,height:i}=this.engine.viewSize;if(e<=0||i<=0)return null;const s=this.camera.frame(e,i).viewProjection,o=t[0],r=t[1],n=t[2]??0,h=s[0]*o+s[1]*r+s[2]*n+s[3],a=s[4]*o+s[5]*r+s[6]*n+s[7],l=s[12]*o+s[13]*r+s[14]*n+s[15];return l<=1e-9?null:[(h/l+1)/2*e,(1-a/l)/2*i]}rayAt(t,e){this.own;const{width:i,height:s}=this.engine.viewSize;return this.camera.ray(t,e,i,s)}toGround(t,e,i=this.camera.state.target[2]){this.own;const{width:s,height:o}=this.engine.viewSize;return this.camera.groundAt(t,e,s,o,i)}pixelSizeAt(t){this.own;const{height:e}=this.engine.viewSize,i=Math.tan(this.camera.fovY*Math.PI/360);if(this.camera.orthographic)return 2*this.camera.state.distance*i/Math.max(1,e);const{f:s,eye:o}=this.camera.basis(),r=(t[0]-o[0])*s[0]+(t[1]-o[1])*s[1]+((t[2]??0)-o[2])*s[2];return 2*Math.max(r,this.camera.near())*i/Math.max(1,e)}bounds(){let t=null;for(const e of this.layers){const i=e.bounds();s(i)||(t=t?o(t,i):i)}return t}setGround(t){const e=this.own;if(this.ground&&(e.baseScene.remove(this.ground.mesh),this.ground.dispose(),this.ground=null),this.groundOptions=t,!t)return void this.requestRepaint();const[i,s,o,r]=t.bounds,n=e.originFor([(i+o)/2,(s+r)/2,t.z??0]),h={spacing:10,major:10,color:this.theme.grid};this.ground=new l({color:this.theme.ground,...t,grid:t.grid?{...h,...t.grid}:"grid"in t?t.grid:h},n,{eye:e.sky.eye,fog:e.sky.horizon}),this.applyGroundColors(),e.baseScene.add(this.ground.mesh),this.requestRepaint()}applyGroundColors(){const t=this.ground,e=this.groundOptions;if(!t||!e)return;const i=e.grid?e.grid.color:void 0;t.setColors({color:y(e.color??this.theme.ground),grid:y(i??this.theme.grid)})}getGround(){return this.ground}setDensity(t){const e=t?.layers?.map(t=>"string"==typeof t?this.getLayer(t):t);this.layers.forEach(i=>i.setDensity(!!t&&(!e||e.includes(i)))),(t?.ramp||t?.top)&&this.engine.density.setColorMap(t.ramp??this.engine.density.colorMap,t.top),this.requestRepaint()}getCamera(){return{...this.camera.state,target:[...this.camera.state.target]}}setCamera(t){this.own,this.camera.set(t),this.requestRepaint()}flyTo(t,e=900){this.own,this.camera.flyTo(t,e),this.engine.setAnimating("camera",!0)}fit(t=this.bounds(),e=900,i=.1){if(!t||s(t))return;const{width:o,height:r}=this.engine.viewSize,n=this.camera.fit(t.min,t.max,o,r,i);e>0?this.flyTo(n,e):this.setCamera(n)}setMode(t,e=55){if(this.options.mode=t,this.hosted){if(t===this.mode)return;return this.mode=t,this.emit("mode",t),void this.requestRepaint()}if("2d"===t){if("2d"===this.mode&&this.camera.orthographic)return;this.pendingMode="2d",this.flyTo({tilt:0},450)}else{this.pendingMode=null;const t="2d"===this.mode;this.mode="3d",this.camera.orthographic=!1,t&&this.flyTo({tilt:Math.max(this.camera.state.tilt,e)},800),this.emit("mode","3d"),this.requestRepaint()}}finishModeSwitch(){"2d"===this.pendingMode&&(this.pendingMode=null,this.mode="2d",this.camera.orthographic=!0,this.emit("mode","2d"),this.requestRepaint())}async pickAt(t,e){const i=await this.engine.pick(t,e);return i?{...i.hit,point:i.point}:null}setHover(t){const e=this.hovered;e?.layer===t?.layer&&e?.id===t?.id||(e?.layer.setHovered(null),t?.layer.setHovered(t.id),this.hovered=t?{...e??{},...t}:null,this.applyCursor(),this.requestRepaint())}select(t,e,i="replace"){t.select(e,i),this.emitSelection()}clearSelection(){this.layers.forEach(t=>t.clearSelection()),this.emitSelection()}getSelection(){const t=this.layers.map(t=>({layer:t,ids:t.selection()})).filter(t=>t.ids.length>0);return{layers:t,count:t.reduce((t,e)=>t+e.ids.length,0)}}rankOf(t){const e=this.layers.indexOf(t);if(e>=0)return e;const i=this.overlays.indexOf(t);return i>=0?this.layers.length+i:0}get anyHovered(){return null!==this.hovered||this.layers.some(t=>t.isEmphasizing())}get windowsLit(){return this.theme.windowsLit}requestRepaint(){this.engine.requestRepaint()}setAnimating(t,e){this.engine.setAnimating(t,e)}emitSelection(){this.emit("select",this.getSelection())}emitCamera(){const t=this.camera.state,e=`${t.target.join(",")}|${t.distance}|${t.heading}|${t.tilt}`;e!==this.lastCamera&&(this.lastCamera=e,this.emit("camera",this.getCamera()))}onFrame(t){this.labels?.update();const e=performance.now();for(this.frames.push(e);this.frames.length>0&&e-this.frames[0]>1e3;)this.frames.shift();const i=this.engine.getRenderer()?.info?.render??{};this.emit("frame",{...t,fps:this.frames.length,drawCalls:i.drawCalls??i.calls??0,triangles:i.triangles??0,backend:this.engine.webgpu?"webgpu":"webgl"})}local(t){const e=this.root.getBoundingClientRect();return{x:t.clientX-e.left,y:t.clientY-e.top}}pointerOf(t){const{x:e,y:i}=this.local(t);return{x:e,y:i,button:t.button,shift:t.shiftKey,ctrl:t.ctrlKey||t.metaKey,alt:t.altKey,pointerType:t.pointerType??"mouse",native:t}}capture(t){try{this.own.canvas.setPointerCapture(t)}catch{}}applyCursor(){if(!this.root)return;const t=this.hovered?"pointer":this.drag?.moved?"pan"===this.drag.kind?"grabbing":"move":"grab";this.own.canvas.style.cursor=this.controller?.cursor??t}listen(){const t=this.own.canvas;t.style.cursor="grab";const e=(t,e,i,s)=>{t.addEventListener(e,i,s),this.disposables.add(()=>t.removeEventListener(e,i,s))};e(t,"contextmenu",t=>t.preventDefault()),e(t,"pointerdown",t=>this.onDown(t)),e(t,"pointermove",t=>this.onMove(t)),e(t,"pointerup",t=>this.onUp(t)),e(t,"pointercancel",t=>this.onUp(t,!0)),e(t,"pointerleave",()=>{this.pointer=null,this.controller?.onPointerLeave(),this.drag||this.setHover(null),this.emit("hover",null)}),e(t,"wheel",t=>this.onWheel(t),{passive:!1}),e(t,"dblclick",t=>{if(this.controller?.onDoubleClick(this.pointerOf(t)))return void this.applyCursor();if(!1===this.options.interactive)return;const{x:e,y:i}=this.local(t),{width:s,height:o}=this.engine.viewSize,r=this.camera.groundAt(e,i,s,o);r&&this.flyTo({target:r,distance:this.camera.state.distance*(t.shiftKey?2:.45)},600)}),e(this.root,"keydown",t=>{if(this.controller?.onKeyDown(t))return t.preventDefault(),void this.applyCursor();"Escape"===t.key&&this.clearSelection()})}onDown(t){this.root?.focus({preventScroll:!0});const{x:e,y:i}=this.local(t);if("touch"===t.pointerType&&(this.touches.set(t.pointerId,{x:e,y:i}),2===this.touches.size))return this.drag=null,void(this.pinch=this.pinchOf());if(this.controller&&null===this.controllerDrag&&this.controller.onPointerDown(this.pointerOf(t)))return this.controllerDrag=t.pointerId,this.camera.stop(),this.capture(t.pointerId),void this.applyCursor();this.camera.stop();const s=2===t.button||1===t.button||t.ctrlKey&&0===t.button&&"none"===this.options.selection,{width:o,height:r}=this.engine.viewSize;this.drag={id:t.pointerId,kind:s?"rotate":"pan",x:e,y:i,startX:e,startY:i,time:performance.now(),anchor:s?null:this.camera.groundAt(e,i,o,r),moved:!1,history:[]},this.capture(t.pointerId)}onMove(t){const{x:e,y:i}=this.local(t);if(this.pointer={x:e,y:i},this.controllerDrag===t.pointerId)return this.controller?.onPointerDrag(this.pointerOf(t)),void this.applyCursor();if("touch"===t.pointerType&&this.touches.has(t.pointerId)&&(this.touches.set(t.pointerId,{x:e,y:i}),this.pinch&&2===this.touches.size))return void this.onPinch();const s=this.drag;if(!s||s.id!==t.pointerId){return(this.controller?.onPointerMove(this.pointerOf(t))??!1)||this.queueHover(),void this.applyCursor()}if(!s.moved&&Math.hypot(e-s.startX,i-s.startY)>5&&(s.moved=!0,this.applyCursor()),!s.moved||!1===this.options.interactive)return;const{width:o,height:r}=this.engine.viewSize;if("pan"===s.kind&&s.anchor){this.camera.panTo(s.anchor,e,i,o,r);const t=performance.now();for(s.history.push({t:t,target:[this.camera.state.target[0],this.camera.state.target[1]]});s.history.length>0&&t-s.history[0].t>100;)s.history.shift()}else"rotate"===s.kind&&this.camera.rotate(.3*(e-s.x),"3d"===this.mode?.25*(i-s.y):0);s.x=e,s.y=i,this.requestRepaint()}onUp(t,e=!1){if(this.touches.delete(t.pointerId),this.touches.size<2&&(this.pinch=null),this.controllerDrag===t.pointerId){this.controllerDrag=null;try{this.own.canvas.releasePointerCapture(t.pointerId)}catch{}return this.controller?.onPointerUp(this.pointerOf(t)),void this.applyCursor()}const i=this.drag;if(i&&i.id===t.pointerId){this.drag=null;try{this.own.canvas.releasePointerCapture(t.pointerId)}catch{}if(this.applyCursor(),!e){if(i.moved&&"pan"===i.kind&&i.history.length>1){const t=i.history[0],e=i.history[i.history.length-1],s=(e.t-t.t)/1e3;s>.01&&performance.now()-e.t<60&&(this.camera.glide([(e.target[0]-t.target[0])/s,(e.target[1]-t.target[1])/s]),this.engine.setAnimating("camera",!0))}!i.moved&&performance.now()-i.time<600&&0===t.button&&this.onClick(t)}}}async onClick(t){if(this.controller?.onClick(this.pointerOf(t)))return void this.applyCursor();const{x:e,y:i}=this.local(t),s=await this.pickAt(e,i),o={hit:s,shift:t.shiftKey,ctrl:t.ctrlKey||t.metaKey,alt:t.altKey,x:e,y:i,native:t};this.emit("click",o);const r=this.options.selection??"multi";if("none"===r)return;const n="multi"===r&&(o.ctrl||o.shift);if(s){if(n)s.layer.select([s.id],o.ctrl?"toggle":"add");else{this.layers.forEach(t=>{t!==s.layer&&t.clearSelection()});const t=s.layer.selection(),e=1===t.length&&t[0]===s.id;s.layer.select(e?[]:[s.id],"replace")}this.emitSelection()}else n||this.clearSelection()}onWheel(t){if(!1===this.options.interactive)return;t.preventDefault();const{x:e,y:i}=this.local(t),{width:s,height:o}=this.engine.viewSize,r=1===t.deltaMode?33:2===t.deltaMode?400:1,n=Math.exp(t.deltaY*r*.0016);this.camera.stop(),this.camera.zoomAt(n,e,i,s,o),this.requestRepaint(),this.queueHover()}pinchOf(){const[t,e]=[...this.touches.values()];return{distance:Math.hypot(e.x-t.x,e.y-t.y),angle:Math.atan2(e.y-t.y,e.x-t.x),midY:(t.y+e.y)/2}}onPinch(){const t=this.pinch,e=this.pinchOf(),[i,s]=[...this.touches.values()],{width:o,height:r}=this.engine.viewSize;this.camera.zoomAt(t.distance/Math.max(1,e.distance),(i.x+s.x)/2,(i.y+s.y)/2,o,r),this.camera.rotate(180*-(e.angle-t.angle)/Math.PI,"3d"===this.mode?.25*(e.midY-t.midY):0),this.pinch=e,this.requestRepaint()}queueHover(){!1===this.options.hover||this.hoverQueued||this.drag?.moved||(this.hoverQueued=!0,requestAnimationFrame(async()=>{this.hoverQueued=!1;const t=this.pointer;if(!t||this.drag?.moved)return;const e=await this.pickAt(t.x,t.y);if(!this.pointer)return;const i=e?.layer!==this.hovered?.layer||e?.id!==this.hovered?.id;this.setHover(e),e&&(this.hovered=e),i&&this.emit("hover",e)}))}}function y(i){const[s,o,r]=t(i);return e([s,o,r,1])}
|
package/index.d.ts
CHANGED
|
@@ -11,6 +11,7 @@ export * from './math/Relations';
|
|
|
11
11
|
export * from './math/Geodesy';
|
|
12
12
|
export * from './math/SpatialIndex';
|
|
13
13
|
export * from './math/FeatureIndex';
|
|
14
|
+
export * from './math/AxisIndex';
|
|
14
15
|
export * from './engine/GeometryFrame';
|
|
15
16
|
export * from './engine/GeometryEngine';
|
|
16
17
|
export * from './engine/GeometryOptions';
|
|
@@ -27,7 +28,6 @@ export * from './edit/EditController';
|
|
|
27
28
|
export * from './edit/MeasureController';
|
|
28
29
|
export * from './three/CanvasGeometryEngine';
|
|
29
30
|
export * from './three/HostedGeometryEngine';
|
|
30
|
-
export * from './three/RiaGeometryEngine';
|
|
31
31
|
export * from './three/FeatureLook';
|
|
32
32
|
export * from './three/Shading';
|
|
33
33
|
export * from './three/DensityMap';
|
package/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export*from"./data/Geometry.js";export*from"./math/Triangulate.js";export*from"./math/Projection.js";export*from"./math/Vector.js";export*from"./math/Measure.js";export*from"./math/Lines.js";export*from"./math/Polygons.js";export*from"./math/Boolean.js";export*from"./math/Transform.js";export*from"./math/Relations.js";export*from"./math/Geodesy.js";export*from"./math/SpatialIndex.js";export*from"./math/FeatureIndex.js";export*from"./engine/GeometryFrame.js";export*from"./engine/GeometryEngine.js";export*from"./engine/GeometryOptions.js";export*from"./engine/GeometryView.js";export*from"./engine/MapCamera.js";export*from"./engine/Labels.js";export*from"./edit/GeometryController.js";export*from"./edit/Snapper.js";export*from"./edit/Sketch.js";export*from"./edit/EditShape.js";export*from"./edit/EditHistory.js";export*from"./edit/CreateController.js";export*from"./edit/EditController.js";export*from"./edit/MeasureController.js";export*from"./three/CanvasGeometryEngine.js";export*from"./three/HostedGeometryEngine.js";export*from"./three/
|
|
1
|
+
export*from"./data/Geometry.js";export*from"./math/Triangulate.js";export*from"./math/Projection.js";export*from"./math/Vector.js";export*from"./math/Measure.js";export*from"./math/Lines.js";export*from"./math/Polygons.js";export*from"./math/Boolean.js";export*from"./math/Transform.js";export*from"./math/Relations.js";export*from"./math/Geodesy.js";export*from"./math/SpatialIndex.js";export*from"./math/FeatureIndex.js";export*from"./math/AxisIndex.js";export*from"./engine/GeometryFrame.js";export*from"./engine/GeometryEngine.js";export*from"./engine/GeometryOptions.js";export*from"./engine/GeometryView.js";export*from"./engine/MapCamera.js";export*from"./engine/Labels.js";export*from"./edit/GeometryController.js";export*from"./edit/Snapper.js";export*from"./edit/Sketch.js";export*from"./edit/EditShape.js";export*from"./edit/EditHistory.js";export*from"./edit/CreateController.js";export*from"./edit/EditController.js";export*from"./edit/MeasureController.js";export*from"./three/CanvasGeometryEngine.js";export*from"./three/HostedGeometryEngine.js";export*from"./three/FeatureLook.js";export*from"./three/Shading.js";export*from"./three/DensityMap.js";export*from"./three/Halo.js";export*from"./three/Ground.js";export*from"./three/Tsl.js";export*from"./three/primitives/GpuLines.js";export*from"./three/primitives/GpuIcons.js";export*from"./three/primitives/GpuTubes.js";export*from"./three/primitives/GpuSpheres.js";export*from"./three/primitives/GpuAreas.js";export*from"./three/primitives/IconAtlas.js";export*from"./three/primitives/Body.js";export*from"./layers/GeometryLayer.js";export*from"./layers/LineLayer.js";export*from"./layers/PointLayer.js";export*from"./layers/TubeLayer.js";export*from"./layers/SphereLayer.js";export*from"./layers/AreaLayer.js";export*from"./react/ReactGeometry.js";export*from"./theme/Theme.js";export*from"./common/Colors.js";export*from"./common/Disposables.js";export*from"./event/TypedEventEmitter.js";
|
package/layers/AreaLayer.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{parseColor as t}from"../common/Colors.js";import{polygonsOf as
|
|
1
|
+
import{parseColor as t}from"../common/Colors.js";import{polygonsOf as o}from"../data/Geometry.js";import{FeatureState as e,isLit as i,LookFlag as r}from"../three/FeatureLook.js";import{GpuAreas as s}from"../three/primitives/GpuAreas.js";import{GpuLines as a}from"../three/primitives/GpuLines.js";import{materialCode as n}from"../three/Shading.js";import{GeometryLayer as h}from"./GeometryLayer.js";export class AreaLayer extends h{constructor(t={}){super(t),this.options=t}createPrimitives(h,l){const m=!!this.options.extrude&&"3d"===h.mode,p=this.addRole((t,o,e,i,s)=>{s.color=this.colorOf(e.color,e.opacity,i,m?"#8d99ae":"#4cc9f033"),s.flags="hatch"===e.pattern?r.Hatch:0,s.width=e.height??0,s.realWidth=e.base??0,s.material=n(e.material)}),c=[];this.features.forEach((t,e)=>{for(const i of o(t.geometry))c.push({index:e,rings:i.map(t=>t.map(t=>[t[0]-l[0],t[1]-l[1],(t[2]??0)-l[2]]))})});const d=[new s(c,{look:p,lighting:h.lighting,extrude:m,up:h.up,pick:this.pick??void 0,rank:h.rankOf?.(this)??0})];if(this.options.outlines??!m){const s=this.addRole((o,s,a,n,h)=>{const l=null===a.outline?[0,0,0,0]:t(a.outline??a.color??"#4cc9f0");h.color=this.colorOf([l[0],l[1],l[2],void 0===a.outline?1:l[3]],a.opacity,n,"#4cc9f0"),h.width=a.outlineWidth??1.5,h.meters=!1,h.flags=(a.outlineDashed?r.Dashed:0)|r.NoArrow,null!==a.outline||i(n)||(h.state=e.Hidden)}),n=this.features.map(t=>o(t.geometry).flatMap(t=>t.filter(t=>t.length>2).map(t=>(t[0][0]===t[t.length-1][0]&&t[0][1]===t[t.length-1][1]?t:[...t,t[0]]).map(t=>({x:t[0]-l[0],y:t[1]-l[1],z:(t[2]??0)-l[2]}))))),m="2d"===h.mode?{}:this.flat()?{ground:{up:h.up}}:{space:!0};d.push(new a(n,{look:s,pick:this.pick??void 0,arrows:!1,...m}))}return d}flat(){const t=this.bounds();return Math.abs(t.max[2]-t.min[2])<1e-6&&Math.abs(t.max[2])<1e-6}}
|