@protomaze/geometry 0.1.2 → 0.3.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.
- package/GeometryDemo.js +1 -1
- package/README.md +129 -47
- package/common/Colors.d.ts +1 -2
- package/common/Colors.js +1 -1
- package/demo/DemoControls.d.ts +13 -3
- package/demo/DemoControls.js +1 -1
- package/edit/CreateController.js +1 -1
- package/edit/EditController.js +1 -1
- package/edit/GeometryController.d.ts +7 -1
- package/edit/MeasureController.js +1 -1
- package/edit/Sketch.d.ts +19 -2
- package/edit/Sketch.js +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 +48 -4
- package/engine/GeometryOptions.js +1 -1
- package/engine/GeometryView.d.ts +48 -6
- package/engine/GeometryView.js +1 -1
- package/engine/Labels.d.ts +9 -0
- package/engine/Labels.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.js +1 -1
- package/package.json +1 -1
- package/theme/Theme.d.ts +125 -0
- package/theme/Theme.js +1 -0
- package/three/CanvasGeometryEngine.d.ts +1 -4
- 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/Ground.d.ts +5 -0
- package/three/Ground.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/engine/GeometryView.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{parseColor as t}from"../common/Colors.js";import{Disposables as e}from"../common/Disposables.js";import{isEmptyBounds as i,unionBounds as s}from"../data/Geometry.js";import{TypedEventEmitter as n}from"../event/TypedEventEmitter.js";import{LabelOverlay as o}from"./Labels.js";import{CanvasGeometryEngine as r}from"../three/CanvasGeometryEngine.js";import{Ground as h}from"../three/Ground.js";import{Lighting as a}from"../three/Shading.js";import{DARK_THEME as l,LIGHT_THEME as c}from"./GeometryOptions.js";import{MapCamera as d}from"./MapCamera.js";export class GeometryView extends n{constructor(t={}){super(),this.lighting=new a,this.up=[0,0,1],this.labels=null,this.layers=[],this.overlays=[],this.controller=null,this.controllerDrag=null,this.root=null,this.disposables=new e,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 r({antialias:t.antialias,forceWebGL:t.forceWebGL,maxPixelRatio:t.maxPixelRatio}),this.camera=new d(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 e;const i=document.createElement("div");i.style.position="relative",i.style.width="100%",i.style.height="100%",i.style.overflow="hidden",i.style.outline="none",i.tabIndex=0,t.appendChild(i),i.appendChild(this.engine.canvas),this.root=i,this.disposables.add(()=>i.remove());const s=new o(i,t=>this.toScreen(t));this.labels=s,this.disposables.add(()=>{s.dispose(),this.labels=null});const n=()=>{const t=i.getBoundingClientRect();this.engine.setSize(t.width,t.height,window.devicePixelRatio||1)};n();const r=new ResizeObserver(n);r.observe(i),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}applyOptions(){const e=this.options.theme;this.theme="light"===e?c:"dark"!==e&&e?{...l,...e}:l;const i=this.options.highlight??{};this.highlight={look:i.look??"glow",glow:i.glow??"bloom",outlineColor:t(i.outlineColor??this.theme.outline),outlineWidth:i.outlineWidth??2,hoverFades:i.hoverFades??!0,othersShade:i.othersShade??.55,othersToward:this.theme.othersToward,hoverLights:i.hoverLights??!0},this.engine.setBackground(this.theme.background),this.engine.sky.setColors({...this.theme.sky,below:this.theme.sky.horizon})}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,n=t[0],o=t[1],r=t[2]??0,h=s[0]*n+s[1]*o+s[2]*r+s[3],a=s[4]*n+s[5]*o+s[6]*r+s[7],l=s[12]*n+s[13]*o+s[14]*r+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:n}=this.engine.viewSize;return this.camera.groundAt(t,e,s,n,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:n}=this.camera.basis(),o=(t[0]-n[0])*s[0]+(t[1]-n[1])*s[1]+((t[2]??0)-n[2])*s[2];return 2*Math.max(o,this.camera.near())*i/Math.max(1,e)}bounds(){let t=null;for(const e of this.layers){const n=e.bounds();i(n)||(t=t?s(t,n):n)}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,n]=t.bounds,o=this.engine.originFor([(e+s)/2,(i+n)/2,t.z??0]);this.ground=new h({color:this.theme.ground,grid:{spacing:10,major:10,color:this.theme.grid},...t},o,{eye:this.engine.sky.eye,fog:this.engine.sky.horizon}),this.engine.baseScene.add(this.ground.mesh),this.requestRepaint()}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,s=.1){if(!t||i(t))return;const{width:n,height:o}=this.engine.viewSize,r=this.camera.fit(t.min,t.max,n,o,s);e>0?this.flyTo(r,e):this.setCamera(r)}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:n}=this.engine.viewSize,o=this.camera.groundAt(e,i,s,n);o&&this.flyTo({target:o,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:n,height:o}=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,n,o),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:n,height:o}=this.engine.viewSize;if("pan"===s.kind&&s.anchor){this.camera.panTo(s.anchor,e,i,n,o);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),n={hit:s,shift:t.shiftKey,ctrl:t.ctrlKey||t.metaKey,alt:t.altKey,x:e,y:i,native:t};this.emit("click",n);const o=this.options.selection??"multi";if("none"===o)return;const r="multi"===o&&(n.ctrl||n.shift);if(s){if(r)s.layer.select([s.id],n.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 r||this.clearSelection()}onWheel(t){if(!1===this.options.interactive)return;t.preventDefault();const{x:e,y:i}=this.local(t),{width:s,height:n}=this.engine.viewSize,o=1===t.deltaMode?33:2===t.deltaMode?400:1,r=Math.exp(t.deltaY*o*.0016);this.camera.stop(),this.camera.zoomAt(r,e,i,s,n),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:n,height:o}=this.engine.viewSize;this.camera.zoomAt(t.distance/Math.max(1,e.distance),(i.x+s.x)/2,(i.y+s.y)/2,n,o),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)}))}}
|
|
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/engine/Labels.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { Position } from '../data/Geometry';
|
|
2
|
+
import { ThemeTokens } from '../theme/Theme';
|
|
2
3
|
/** How a label looks: a measurement, a figure along an edge, a note, a warning. */
|
|
3
4
|
export type LabelKind = 'measure' | 'segment' | 'info' | 'warning';
|
|
4
5
|
/** A label on a world position, kept there as the camera moves. */
|
|
@@ -23,7 +24,15 @@ export declare class LabelOverlay {
|
|
|
23
24
|
private readonly project;
|
|
24
25
|
readonly element: HTMLDivElement;
|
|
25
26
|
private readonly groups;
|
|
27
|
+
private theme;
|
|
26
28
|
constructor(parent: HTMLElement, project: (p: Position) => [number, number] | null);
|
|
29
|
+
/**
|
|
30
|
+
* The tokens labels are drawn in - surface, text, muted text, danger, font, radius, shadow -
|
|
31
|
+
* as `resolveTheme` gives them: a view sets its own, and again when they change.
|
|
32
|
+
*/
|
|
33
|
+
setTheme(theme: ThemeTokens): void;
|
|
34
|
+
/** A label's look, for its kind in the theme. */
|
|
35
|
+
private paint;
|
|
27
36
|
/** Sets a group's labels: new ones made, gone ones removed, the rest moved and re-texted. */
|
|
28
37
|
set(group: string, labels: readonly LabelSpec[]): void;
|
|
29
38
|
/** Removes a group's labels, or every label. */
|
package/engine/Labels.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
import{parseColor as t,toCss as e}from"../common/Colors.js";import{PROTOMAZE_DARK as o}from"../theme/Theme.js";function n(e,o){const n=e=>{const o=t(e).slice(0,3).map(t=>t<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4));return.2126*o[0]+.7152*o[1]+.0722*o[2]},s=(t,e)=>(Math.max(t,e)+.05)/(Math.min(t,e)+.05),i=n(e);return s(i,n(o))>=s(i,1)?o:"#FFFFFF"}export class LabelOverlay{constructor(t,e){this.project=e,this.groups=new Map,this.theme=o;const n=document.createElement("div");n.style.position="absolute",n.style.inset="0",n.style.pointerEvents="none",n.style.overflow="hidden",t.appendChild(n),this.element=n,this.setTheme(this.theme)}setTheme(t){this.theme=t,this.element.style.fontFamily=t.fontFamily,this.element.style.fontSize=`${t.fontSize}px`,this.groups.forEach(t=>t.forEach(({spec:t,node:e})=>this.paint(e,t.kind)))}paint(o,s="measure"){o.style.borderRadius=`${this.theme.radius}px`,o.style.boxShadow=this.theme.shadow,Object.assign(o.style,function(o,s){const i=`${Math.max(9,s.fontSize-1)}px`,r=o=>e(function([t,e,o,n],s){return[t,e,o,n*s]}(t(s.surface),o));switch(o){case"segment":return{background:r(.78),color:s.text,fontWeight:String(s.fontWeight),fontSize:i,padding:"2px 5px"};case"info":return{background:r(.78),color:s.textMuted,fontWeight:String(s.fontWeight),fontSize:i,padding:"2px 6px"};case"warning":return{background:s.danger,color:n(s.danger,s.onAccent),fontWeight:String(s.fontWeightStrong),fontSize:i,padding:"2px 6px"};default:return{background:r(.88),color:s.text,fontWeight:String(s.fontWeightStrong),fontSize:`${s.fontSize}px`,padding:"3px 7px"}}}(s,this.theme)),o.dataset.kind=s}set(t,e){let o=this.groups.get(t);o||(o=new Map,this.groups.set(t,o));const n=new Set(e.map(t=>t.id));o.forEach((t,e)=>{n.has(e)||(t.node.remove(),o.delete(e))});for(const t of e){let e=o.get(t.id);if(!e){const n=document.createElement("div");n.style.position="absolute",n.style.left="0",n.style.top="0",n.style.whiteSpace="nowrap",n.style.fontVariantNumeric="tabular-nums",n.style.letterSpacing="0.2px",n.style.willChange="transform",this.element.appendChild(n),e={spec:t,node:n},o.set(t.id,e)}e.node.textContent!==t.text&&(e.node.textContent=t.text),e.spec.kind===t.kind&&e.node.dataset.kind||this.paint(e.node,t.kind),e.spec=t}this.update()}clear(t){const e=t?[t]:[...this.groups.keys()];for(const t of e)this.groups.get(t)?.forEach(t=>t.node.remove()),this.groups.delete(t)}update(){this.groups.forEach(t=>t.forEach(({spec:t,node:e})=>{const o=this.project(t.position);if(!o)return void(e.style.display="none");e.style.display="";const[n,s]=t.offset??[0,0];e.style.transform=`translate(${Math.round(o[0]+n)}px, ${Math.round(o[1]+s)}px) translate(${"left"===t.anchor?"0":"-50%"}, -50%)`}))}dispose(){this.clear(),this.element.remove()}}export function formatLength(t){const e=Math.abs(t);return e<1?`${(100*t).toFixed(e<.1?1:0)} cm`:e<1e4?`${t.toFixed(e<100?2:1)} m`:`${(t/1e3).toFixed(2)} km`}export function formatArea(t){const e=Math.abs(t);return e<1e4?`${t.toFixed(e<100?2:1)} m²`:e<1e6?`${(t/1e4).toFixed(2)} ha`:`${(t/1e6).toFixed(3)} km²`}export function formatAngle(t){return`${t.toFixed(1)}°`}export function formatSlope(t){if(!Number.isFinite(t))return"vertical";return Math.abs(t)<.1?`${(1e3*t).toFixed(1)} ‰`:`${(100*t).toFixed(1)} %`}
|
package/index.d.ts
CHANGED
|
@@ -27,7 +27,6 @@ export * from './edit/EditController';
|
|
|
27
27
|
export * from './edit/MeasureController';
|
|
28
28
|
export * from './three/CanvasGeometryEngine';
|
|
29
29
|
export * from './three/HostedGeometryEngine';
|
|
30
|
-
export * from './three/RiaGeometryEngine';
|
|
31
30
|
export * from './three/FeatureLook';
|
|
32
31
|
export * from './three/Shading';
|
|
33
32
|
export * from './three/DensityMap';
|
|
@@ -48,6 +47,7 @@ export * from './layers/TubeLayer';
|
|
|
48
47
|
export * from './layers/SphereLayer';
|
|
49
48
|
export * from './layers/AreaLayer';
|
|
50
49
|
export * from './react/ReactGeometry';
|
|
50
|
+
export * from './theme/Theme';
|
|
51
51
|
export * from './common/Colors';
|
|
52
52
|
export * from './common/Disposables';
|
|
53
53
|
export * from './event/TypedEventEmitter';
|
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"./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}}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { ColorLike, ColorRamp, Rgba } from '../common/Colors';
|
|
2
2
|
import { GeometryFeature, GeometryId, Bounds3 } from '../data/Geometry';
|
|
3
3
|
import { GeometryEngine } from '../engine/GeometryEngine';
|
|
4
|
-
import { GeometryPrimitive, PickOptions } from '../engine/GeometryFrame';
|
|
4
|
+
import { GeometryOccluder, GeometryPrimitive, PickOptions } from '../engine/GeometryFrame';
|
|
5
5
|
import { TypedEventEmitter } from '../event/TypedEventEmitter';
|
|
6
6
|
import { FeatureLook, FeatureLookStyle, FeatureState } from '../three/FeatureLook';
|
|
7
7
|
import { Lighting } from '../three/Shading';
|
|
@@ -9,8 +9,8 @@ import { Lighting } from '../three/Shading';
|
|
|
9
9
|
export interface ResolvedHighlight {
|
|
10
10
|
/** A glow round it (bloomed, or drawn in the line shader), or an outline. */
|
|
11
11
|
look: 'glow' | 'outline';
|
|
12
|
-
/** Where the glow comes from: the bloom pass (soft, over everything)
|
|
13
|
-
glow: 'bloom' | 'shader';
|
|
12
|
+
/** Where the glow comes from: the bloom pass (soft, over everything), the line shader (cheap), or nowhere. */
|
|
13
|
+
glow: 'bloom' | 'shader' | 'none';
|
|
14
14
|
outlineColor: Rgba;
|
|
15
15
|
/** View pixels. */
|
|
16
16
|
outlineWidth: number;
|
|
@@ -21,6 +21,8 @@ export interface ResolvedHighlight {
|
|
|
21
21
|
othersToward: number;
|
|
22
22
|
/** Whether pointing at a feature lights it as the selection is. */
|
|
23
23
|
hoverLights: boolean;
|
|
24
|
+
/** How opaque a lit feature is whose own style or a filter fades or hides it: drawn lit, only fainter. */
|
|
25
|
+
outsideOpacity: number;
|
|
24
26
|
}
|
|
25
27
|
/** What a layer needs of the view it is in. */
|
|
26
28
|
export interface LayerHost {
|
|
@@ -54,12 +56,23 @@ export interface CategorySpec<F> {
|
|
|
54
56
|
colors?: Record<string, ColorLike> | readonly ColorLike[];
|
|
55
57
|
}
|
|
56
58
|
/** The GPU's range filter: every feature's value, and the range it is held against. */
|
|
57
|
-
export interface RangeSpec<F> {
|
|
59
|
+
export interface RangeSpec<F, S = any> {
|
|
58
60
|
value: (feature: F) => number;
|
|
59
61
|
low: number;
|
|
60
62
|
high: number;
|
|
61
|
-
/** What falls out of it: hidden, or faded. */
|
|
63
|
+
/** What falls out of it: hidden, or faded. Left for `fail` where it gives a look. */
|
|
62
64
|
outside?: 'hide' | 'fade';
|
|
65
|
+
/**
|
|
66
|
+
* Whether the range has a say on a feature at all: 0 it does, 1 it passes whatever the range
|
|
67
|
+
* (the other filters keep it), 2 it fails whatever the range (they leave it out). 0 for all
|
|
68
|
+
* by default.
|
|
69
|
+
*/
|
|
70
|
+
fixed?: (feature: F) => 0 | 1 | 2;
|
|
71
|
+
/**
|
|
72
|
+
* What a feature looks like out of the range, as a style of the layer's own - instead of
|
|
73
|
+
* hiding or fading it. Written once with the values; the drag then only moves the bounds.
|
|
74
|
+
*/
|
|
75
|
+
fail?: (feature: F) => S;
|
|
63
76
|
}
|
|
64
77
|
/** What the features are coloured by on the GPU: their style, their category, or a value on a ramp. */
|
|
65
78
|
export type ColorBySpec<F> = {
|
|
@@ -105,6 +118,12 @@ export interface GeometryLayerOptions<F, S> {
|
|
|
105
118
|
opacity?: number;
|
|
106
119
|
/** A name for a legend. */
|
|
107
120
|
title?: string;
|
|
121
|
+
/**
|
|
122
|
+
* What stands in front and hides the features outright where they lie on or under the ground
|
|
123
|
+
* - a host's mask of buildings and trees, by shape (`GeometryOccluder`). Lines on the ground or
|
|
124
|
+
* in space, tubes and spheres use it.
|
|
125
|
+
*/
|
|
126
|
+
occluder?: GeometryOccluder | null;
|
|
108
127
|
}
|
|
109
128
|
/** What every style has. */
|
|
110
129
|
export interface BaseStyle {
|
|
@@ -172,6 +191,10 @@ export declare abstract class GeometryLayer<F extends GeometryFeature = Geometry
|
|
|
172
191
|
private builds;
|
|
173
192
|
private boundsCache;
|
|
174
193
|
constructor(options?: GeometryLayerOptions<F, S>);
|
|
194
|
+
/** What hides the features outright where something stands in front; null for nothing. */
|
|
195
|
+
protected occluder: GeometryOccluder | null;
|
|
196
|
+
/** Another occluder: the layer's geometry is built again for it. */
|
|
197
|
+
setOccluder(occluder: GeometryOccluder | null): void;
|
|
175
198
|
/**
|
|
176
199
|
* All the features at once. Drawn already, the layer keeps its compiled shaders and builds
|
|
177
200
|
* only the new geometry - as for `addFeatures`, `updateFeatures` and `removeFeatures`.
|
|
@@ -207,10 +230,10 @@ export declare abstract class GeometryLayer<F extends GeometryFeature = Geometry
|
|
|
207
230
|
/** A predicate on the CPU: what fails it is hidden, or faded. Null shows all. */
|
|
208
231
|
setFilter(filter: ((feature: F) => boolean) | null, outside?: 'hide' | 'fade'): void;
|
|
209
232
|
/** A range on the GPU; null for none. Every feature's value is written once, at the next frame. */
|
|
210
|
-
setRange(range: RangeSpec<F> | null): void;
|
|
233
|
+
setRange(range: RangeSpec<F, S> | null): void;
|
|
211
234
|
/** Moves the range: two uniforms, nothing per feature. */
|
|
212
235
|
setRangeBounds(low: number, high: number): void;
|
|
213
|
-
getRange(): RangeSpec<F> | null;
|
|
236
|
+
getRange(): RangeSpec<F, S> | null;
|
|
214
237
|
/** Categories on the GPU; null for none. */
|
|
215
238
|
setCategories(categories: CategorySpec<F> | null): void;
|
|
216
239
|
/** One category's mode: one texel. */
|
|
@@ -228,6 +251,8 @@ export declare abstract class GeometryLayer<F extends GeometryFeature = Geometry
|
|
|
228
251
|
isSelected(id: GeometryId): boolean;
|
|
229
252
|
/** Lights these features as the selection is, without selecting them: what is pointed at elsewhere. */
|
|
230
253
|
emphasize(ids: Iterable<GeometryId> | null): void;
|
|
254
|
+
/** Whether any feature is emphasised: what shades the rest, as pointing at one does. */
|
|
255
|
+
isEmphasizing(): boolean;
|
|
231
256
|
/**
|
|
232
257
|
* Forces a state on features whatever their style and filters say - faded, hidden or lit as
|
|
233
258
|
* selected - or, with null, lets them be again. What an editor sets off while it works on them.
|
|
@@ -300,6 +325,7 @@ export declare abstract class GeometryLayer<F extends GeometryFeature = Geometry
|
|
|
300
325
|
private translucent;
|
|
301
326
|
private updateLooks;
|
|
302
327
|
private readonly scratch;
|
|
328
|
+
private readonly failScratch;
|
|
303
329
|
private writeFeature;
|
|
304
330
|
private categoryOf;
|
|
305
331
|
private paletteColor;
|
package/layers/GeometryLayer.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Mesh as e}from"three/webgpu";import{CATEGORY_COLORS as t,desaturate as i,parseColor as s}from"../common/Colors.js";import{boundsOf as r}from"../data/Geometry.js";import{TypedEventEmitter as h}from"../event/TypedEventEmitter.js";import{CategoryMode as o,FeatureLook as a,FeatureState as n,MAX_CATEGORIES as l,NO_VALUE as d}from"../three/FeatureLook.js";const c={hidden:o.Hidden,faded:o.Faded,shown:o.Shown,lit:o.Lit};let u=0;export class GeometryLayer extends h{constructor(e={}){super(),this.features=[],this.indexOf=new Map,this.host=null,this.primitives=[],this.roles=[],this.pick=null,this.density=!1,this.filter=null,this.filterOutside="hide",this.range=null,this.categories=null,this.categoryIndex=new Map,this.categoryModes=new Map,this.coloring={by:"style"},this.selected=new Set,this.emphasized=new Set,this.hovered=null,this.needsBuild=!0,this.needsRefresh=!1,this.builtOrigin=null,this.overrides=new Map,this.allDirty=!0,this.dirty=new Set,this.removePickSource=null,this.builtFor="",this.builds=new Map,this.boundsCache=null,this.overlay=!1,this.overlayOrder=0,this.translucent=!1,this.scratch={},this.id=e.id??"layer-"+ ++u,this.title=e.title,this.style=e.style,this.visible=e.visible??!0,this.pickable=e.pickable??!0,this.opacity=e.opacity??1,e.features&&this.setFeatures(e.features)}setFeatures(e){this.features=e,this.categoryIndex.clear(),this.featuresChanged()}addFeatures(e){0!==e.length&&(this.features=[...this.features,...e],this.featuresChanged())}updateFeatures(e){if(0===e.length)return;const t=[...this.features];for(const i of e){const e=this.indexOf.get(i.id);void 0===e?t.push(i):t[e]=i}this.features=t,this.featuresChanged()}removeFeatures(e){const t=new Set(e);0!==t.size&&(this.features=this.features.filter(e=>!t.has(e.id)),t.forEach(e=>{this.selected.delete(e),this.emphasized.delete(e),this.overrides.delete(e)}),null!==this.hovered&&t.has(this.hovered)&&this.setHovered(null),this.featuresChanged())}featuresChanged(){this.indexOf.clear(),this.features.forEach((e,t)=>this.indexOf.set(e.id,t)),this.boundsCache=null,this.invalidateGeometry(),this.allDirty=!0,this.emit("change",{what:"features"})}invalidateGeometry(){this.primitives.length>0&&!this.needsBuild?this.needsRefresh=!0:this.needsBuild=!0,this.repaint()}getFeatures(){return this.features}getFeature(e){const t=this.indexOf.get(e);return void 0===t?void 0:this.features[t]}featureAt(e){return this.features[e]}get size(){return this.features.length}bounds(){return this.boundsCache??(this.boundsCache=r(this.features)),this.boundsCache}setStyle(e){this.style=e,this.invalidateAll(),this.emit("change",{what:"style"})}restyle(e){if(e){for(const t of e){const e=this.indexOf.get(t);void 0!==e&&this.dirty.add(e)}this.repaint()}else this.invalidateAll()}styleOf(e,t){const i=this.style;return"function"==typeof i?i(e,t)??{}:i??{}}setVisible(e){e!==this.visible&&(this.visible=e,this.repaint(),this.emit("change",{what:"visibility"}))}isVisible(){return this.visible}setPickable(e){this.pickable=e,this.repaint()}isPickable(){return this.pickable&&this.visible}setOpacity(e){this.opacity=e,this.repaint()}setDensity(e){e!==this.density&&(this.density=e,this.repaint())}get drawsDensity(){return this.density}setFilter(e,t="hide"){this.filter=e,this.filterOutside=t,this.invalidateAll(),this.emit("change",{what:"filter"})}setRange(e){const t=!e||!this.range||e.value!==this.range.value;this.range=e,t&&this.invalidateAll(),this.applyGpuState(),this.emit("change",{what:"filter"})}setRangeBounds(e,t){this.range&&(this.range={...this.range,low:e,high:t},this.applyGpuState(),this.emit("change",{what:"filter"}))}getRange(){return this.range}setCategories(e){this.categories=e,this.categoryIndex.clear(),this.categoryModes.clear(),e?.keys?.forEach((e,t)=>this.categoryIndex.set(String(e),t)),e?.modes&&Object.entries(e.modes).forEach(([e,t])=>this.categoryModes.set(this.categoryOf(e),c[t])),this.invalidateAll(),this.applyGpuState(),this.emit("change",{what:"filter"})}setCategoryMode(e,t){const i=this.categoryOf(String(e));this.categoryModes.set(i,c[t]),this.roles.forEach(e=>e.look.setCategoryMode(i,c[t])),this.repaint(),this.emit("change",{what:"filter"})}getCategoryMode(e){const t=this.categoryIndex.get(String(e)),i=void 0===t?o.Shown:this.categoryModes.get(t)??o.Shown;return Object.keys(c).find(e=>c[e]===i)??"shown"}categoryKeys(){return[...this.categoryIndex.keys()]}categoryColor(e){const t=this.categoryOf(String(e));return s(this.paletteColor(String(e),t))}colorBy(e){const t=this.coloring;this.coloring=e??{by:"style"};"value"in this.coloring&&(!("value"in t)||t.value!==this.coloring.value)&&this.invalidateAll(),this.applyGpuState(),this.emit("change",{what:"style"})}select(e,t="replace"){const i=new Set,s=[...e];"replace"===t&&(this.selected.forEach(e=>i.add(e)),this.selected.clear()),s.forEach(e=>{if(!this.indexOf.has(e))return;const s=this.selected.has(e);"remove"!==t&&("toggle"!==t||!s)?this.selected.add(e):this.selected.delete(e),i.add(e)}),0!==i.size&&(this.restyle(i),this.emit("change",{what:"selection"}))}clearSelection(){0!==this.selected.size&&this.select([],"replace")}selection(){return[...this.selected]}isSelected(e){return this.selected.has(e)}emphasize(e){const t=new Set(e??[]),i=new Set;this.emphasized.forEach(e=>{t.has(e)||i.add(e)}),t.forEach(e=>{this.emphasized.has(e)||i.add(e)}),this.emphasized.clear(),t.forEach(e=>this.emphasized.add(e)),i.size>0&&this.restyle(i)}setOverride(e,t){const i=[],s="hidden"===t?n.Hidden:"faded"===t?n.Faded:n.Selected;for(const r of e)(null===t?this.overrides.delete(r):this.overrides.get(r)!==s)&&i.push(r),null!==t&&this.overrides.set(r,s);i.length>0&&this.restyle(i)}clearOverrides(){const e=[...this.overrides.keys()];this.overrides.clear(),e.length>0&&this.restyle(e)}setHovered(e){if(e===this.hovered)return;this.hovered=e;const t=null===e?-1:this.indexOf.get(e)??-1;this.roles.forEach(e=>{e.look.hoverIndex.value=t}),this.repaint()}getHovered(){return this.hovered}get lit(){return this.selected.size>0||this.emphasized.size>0||null!==this.hovered||[...this.categoryModes.values()].some(e=>e===o.Lit)}hitAt(e){const t=this.features[e];return t&&this.isPickable()?{layer:this,feature:t,id:t.id,index:e}:null}attach(e){this.host=e;const t=e.engine.addPickSource(e=>this.hitAt(e));this.pick={pass:e.engine.pickPass,source:t.id},this.removePickSource=t.remove,this.invalidateBuild()}detach(){this.dropPrimitives(),this.removePickSource?.(),this.removePickSource=null,this.pick=null,this.host=null}dispose(){this.detach()}get wantsBuild(){const e=this.host;if(!e)return!1;const t=this.buildKey(e);return(this.needsBuild||t!==this.builtFor)&&!(this.builds.has(t)&&!this.needsBuild)}beforeRender(e=!0){const t=this.host;if(!t)return;const i=this.buildKey(t);if(this.needsBuild||i!==this.builtFor){if(!e&&this.wantsBuild)return;this.build(t,i)}else this.needsRefresh&&this.refresh(t,i);this.updateLooks(),this.updateMeshes(t)}buildKey(e){return e.mode}addRole(e,t){const i=new a(Math.max(1,this.features.length),t);return this.roles.push({look:i,write:e}),i}invalidateBuild(){this.needsBuild=!0,this.needsRefresh=!1,this.repaint()}setOverlay(e,t=0){e===this.overlay&&t===this.overlayOrder||(this.overlay=e,this.overlayOrder=t,this.invalidateBuild())}canRefresh(){return!0}refresh(e,t){this.needsRefresh=!1,this.dropStashed();const i=this.builtOrigin,s=this.roles.every(e=>e.look.capacity>=Math.max(1,this.features.length));if(!i||0===this.primitives.length||!s||!this.canRefresh())return this.needsBuild=!0,void this.build(e,t);const r=performance.now(),h=this.roles;this.roles=[];let o=[],a=[];try{o=this.createPrimitives(e,i)}finally{a=this.roles,this.roles=h}let n=o.length===this.primitives.length;for(let e=0;n&&e<o.length;e++)n=this.primitives[e].adopt?.(o[e])??!1;if(o.forEach(e=>e.dispose()),a.forEach(e=>e.look.dispose()),!n)return this.needsBuild=!0,void this.build(e,t);this.allDirty=!0,this.applyGpuState();const l=null===this.hovered?-1:this.indexOf.get(this.hovered)??-1;this.roles.forEach(e=>{e.look.hoverIndex.value=l}),this.emit("build",{ms:performance.now()-r,features:this.features.length,instances:this.instanceCount(),refresh:!0})}invalidateAll(){this.allDirty=!0,this.repaint()}repaint(){this.host?.requestRepaint()}build(e,t){const i=performance.now();this.stash(),this.needsBuild&&this.dropPrimitives(),this.needsBuild=!1,this.needsRefresh=!1,this.builtFor=t;const s=this.builds.get(t);if(s){this.builds.delete(t),this.primitives=s.primitives,this.roles=s.roles,this.primitives.forEach(t=>e.engine.attach(t)),this.allDirty=!0,this.applyGpuState();const i=null===this.hovered?-1:this.indexOf.get(this.hovered)??-1;return void this.roles.forEach(e=>{e.look.hoverIndex.value=i})}if(0===this.features.length)return;const r=e.engine.originFor(function(e){for(const t of e){const e=t.geometry;if(e)switch(e.type){case"Point":return e.coordinates;case"MultiPoint":case"LineString":if(e.coordinates.length)return e.coordinates[0];break;case"MultiLineString":case"Polygon":if(e.coordinates[0]?.length)return e.coordinates[0][0];break;case"MultiPolygon":if(e.coordinates[0]?.[0]?.length)return e.coordinates[0][0][0]}}return null}(this.features)??[0,0,0]);this.builtOrigin=r,this.primitives=this.createPrimitives(e,r),this.overlay&&this.primitives.forEach(e=>function(e,t){const i=e.passes();for(const e of[...i.scene??[],...i.underlay??[]]){if(!e)continue;const i=e.material;i.depthTest=!1,i.depthWrite=!1,e.renderOrder=1e5+100*t+e.renderOrder}}(e,this.overlayOrder)),this.primitives.forEach(t=>e.engine.attach(t)),this.allDirty=!0,this.applyGpuState();const h=null===this.hovered?-1:this.indexOf.get(this.hovered)??-1;this.roles.forEach(e=>{e.look.hoverIndex.value=h}),this.emit("build",{ms:performance.now()-i,features:this.features.length,instances:this.instanceCount()})}instanceCount(){return this.primitives.reduce((e,t)=>e+(t.segments??t.count??t.triangles??0),0)}stash(){if(0===this.primitives.length)return;const e=this.host?.engine;this.primitives.forEach(t=>e?.detach(t)),this.builds.set(this.builtFor,{primitives:this.primitives,roles:this.roles}),this.primitives=[],this.roles=[]}dropStashed(){this.builds.forEach(({primitives:e,roles:t})=>{e.forEach(e=>e.dispose()),t.forEach(e=>e.look.dispose())}),this.builds.clear()}dropPrimitives(){const e=this.host?.engine;[{primitives:this.primitives,roles:this.roles},...this.builds.values()].forEach(({primitives:t,roles:i})=>{t.forEach(t=>{e?.detach(t),t.dispose()}),i.forEach(e=>e.look.dispose())}),this.builds.clear(),this.primitives=[],this.roles=[]}stateOf(e,t){if("hidden"===t.state)return n.Hidden;let i="faded"===t.state?n.Faded:n.Default;if(this.filter&&!this.filter(e)){if("hide"===this.filterOutside)return n.Hidden;i=n.Faded}const s=this.overrides.get(e.id);return void 0!==s?s:this.selected.has(e.id)||this.emphasized.has(e.id)?n.Selected:i}colorOf(e,t,r,h){const o=s(e??h),a=o[3]*(t??1);if(r===n.Faded){const e=i(o,.7);return[e[0],e[1],e[2],.25*a]}return[o[0],o[1],o[2],a]}updateLooks(){if(0!==this.roles.length){if(this.allDirty){this.translucent=!1;for(let e=0;e<this.features.length;e++)this.writeFeature(e)}else this.dirty.forEach(e=>this.writeFeature(e));this.allDirty=!1,this.dirty.clear(),this.roles.forEach(e=>e.look.commit())}}writeFeature(e){const t=this.features[e];if(!t)return;const i=this.styleOf(t,e),s=this.stateOf(t,i),r=this.categories?this.categoryOf(this.categories.of(t)):-1,h=this.range?this.range.value(t):d,o="value"in this.coloring?this.coloring.value(t):d;for(const a of this.roles){const n=this.scratch;for(const e in n)delete n[e];a.write(t,e,i,s,n),n.state=n.state??s,n.category=r,n.colorValue=o,a.look.set(e,n),a.look.setValue(e,h);const l=n.color;l&&l[3]>.004&&l[3]<.99&&(this.translucent=!0)}}categoryOf(e){if(null==e)return-1;const t=String(e);let i=this.categoryIndex.get(t);if(void 0===i){if(i=this.categoryIndex.size,i>=l)return-1;this.categoryIndex.set(t,i),this.roles.forEach(e=>{e.look.setCategoryColor(i,this.paletteColor(t,i)),e.look.setCategoryMode(i,this.categoryModes.get(i)??o.Shown)})}return i}paletteColor(e,i){const s=this.categories?.colors;return Array.isArray(s)?s[i%s.length]:s&&s[e]?s[e]:t[i%t.length]}applyGpuState(){for(const{look:e}of this.roles){const t=this.range;e.rangeActive.value=t?1:0,e.rangeLow.value=t?.low??0,e.rangeHigh.value=t?.high??0,e.rangeOutside.value="fade"===t?.outside?2:1,e.categoryActive.value=this.categories?1:0,this.categoryIndex.forEach((t,i)=>{e.setCategoryColor(t,this.paletteColor(i,t)),e.setCategoryMode(t,this.categoryModes.get(t)??o.Shown)});const i=this.coloring;e.colorMode.value="value"in i?2:"category"===i.by?1:0,"value"in i&&e.setRamp(i.ramp,i.domain[0],i.domain[1])}this.repaint()}updateMeshes(t){const i=t.highlight,s=this.visible,r=this.density,h=this.lit,o="outline"===i.look,a=!o&&"bloom"===i.glow,[n,l,d]=i.outlineColor;for(const{look:e}of this.roles)e.opacity.value=this.opacity,e.othersShade.value=i.hoverFades&&t.anyHovered?i.othersShade:1,e.othersToward.value=i.othersToward,e.hoverLights.value=i.hoverLights?1:0;for(const c of this.primitives){const u=c,f=c.passes(),g=(e,t)=>f[e]?.forEach(e=>{e&&(e.visible=t)});g("scene",s&&!r),g("halo",s&&!r),g("pick",s&&this.pickable),g("density",s&&r),g("bloom",s&&!r&&h&&a),u.casingMesh instanceof e&&(u.casingMesh.visible=s&&!r&&h&&o),u.ghostMesh instanceof e&&(u.ghostMesh.visible=s&&!r&&this.translucent),u.glowMode&&(u.glowMode.value=o?2:"shader"===i.glow?1:0),u.outlineRgb&&u.outlineRgb.value.set(n,l,d),u.outlineWidth&&(u.outlineWidth.value=i.outlineWidth),u.outlineMode&&(u.outlineMode.value=o?1:0),u.rimRgb&&u.rimRgb.value.set(n,l,d),u.windowsLit&&void 0!==t.windowsLit&&(u.windowsLit.value=t.windowsLit),u.uniforms?.outlineRgb&&(u.uniforms.outlineRgb.value.set(n,l,d),u.uniforms.outlineWidth.value=i.outlineWidth)}}}export function relative(e,t){return[e[0]-t[0],e[1]-t[1],(e[2]??0)-t[2]]}
|
|
1
|
+
import{Mesh as e}from"three/webgpu";import{CATEGORY_COLORS as t,desaturate as i,parseColor as s}from"../common/Colors.js";import{boundsOf as r}from"../data/Geometry.js";import{TypedEventEmitter as h}from"../event/TypedEventEmitter.js";import{CategoryMode as o,FeatureLook as a,FeatureState as l,MAX_CATEGORIES as n,NO_VALUE as d}from"../three/FeatureLook.js";const c={hidden:o.Hidden,faded:o.Faded,shown:o.Shown,lit:o.Lit};let u=0;export class GeometryLayer extends h{constructor(e={}){super(),this.features=[],this.indexOf=new Map,this.host=null,this.primitives=[],this.roles=[],this.pick=null,this.density=!1,this.filter=null,this.filterOutside="hide",this.range=null,this.categories=null,this.categoryIndex=new Map,this.categoryModes=new Map,this.coloring={by:"style"},this.selected=new Set,this.emphasized=new Set,this.hovered=null,this.needsBuild=!0,this.needsRefresh=!1,this.builtOrigin=null,this.overrides=new Map,this.allDirty=!0,this.dirty=new Set,this.removePickSource=null,this.builtFor="",this.builds=new Map,this.boundsCache=null,this.overlay=!1,this.overlayOrder=0,this.translucent=!1,this.scratch={},this.failScratch={},this.id=e.id??"layer-"+ ++u,this.title=e.title,this.style=e.style,this.visible=e.visible??!0,this.pickable=e.pickable??!0,this.opacity=e.opacity??1,this.occluder=e.occluder??null,e.features&&this.setFeatures(e.features)}setOccluder(e){e!==this.occluder&&(this.occluder=e,this.invalidateBuild())}setFeatures(e){this.features=e,this.categoryIndex.clear(),this.featuresChanged()}addFeatures(e){0!==e.length&&(this.features=[...this.features,...e],this.featuresChanged())}updateFeatures(e){if(0===e.length)return;const t=[...this.features];for(const i of e){const e=this.indexOf.get(i.id);void 0===e?t.push(i):t[e]=i}this.features=t,this.featuresChanged()}removeFeatures(e){const t=new Set(e);0!==t.size&&(this.features=this.features.filter(e=>!t.has(e.id)),t.forEach(e=>{this.selected.delete(e),this.emphasized.delete(e),this.overrides.delete(e)}),null!==this.hovered&&t.has(this.hovered)&&this.setHovered(null),this.featuresChanged())}featuresChanged(){this.indexOf.clear(),this.features.forEach((e,t)=>this.indexOf.set(e.id,t)),this.boundsCache=null,this.invalidateGeometry(),this.allDirty=!0,this.emit("change",{what:"features"})}invalidateGeometry(){this.primitives.length>0&&!this.needsBuild?this.needsRefresh=!0:this.needsBuild=!0,this.repaint()}getFeatures(){return this.features}getFeature(e){const t=this.indexOf.get(e);return void 0===t?void 0:this.features[t]}featureAt(e){return this.features[e]}get size(){return this.features.length}bounds(){return this.boundsCache??(this.boundsCache=r(this.features)),this.boundsCache}setStyle(e){this.style=e,this.invalidateAll(),this.emit("change",{what:"style"})}restyle(e){if(e){for(const t of e){const e=this.indexOf.get(t);void 0!==e&&this.dirty.add(e)}this.repaint()}else this.invalidateAll()}styleOf(e,t){const i=this.style;return"function"==typeof i?i(e,t)??{}:i??{}}setVisible(e){e!==this.visible&&(this.visible=e,this.repaint(),this.emit("change",{what:"visibility"}))}isVisible(){return this.visible}setPickable(e){this.pickable=e,this.repaint()}isPickable(){return this.pickable&&this.visible}setOpacity(e){this.opacity=e,this.repaint()}setDensity(e){e!==this.density&&(this.density=e,this.repaint())}get drawsDensity(){return this.density}setFilter(e,t="hide"){this.filter=e,this.filterOutside=t,this.invalidateAll(),this.emit("change",{what:"filter"})}setRange(e){const t=this.range,i=!e||!t||e.value!==t.value||e.fixed!==t.fixed||e.fail!==t.fail;this.range=e,e?.fail&&this.roles.some(e=>!e.look.failStyles)?this.invalidateBuild():i&&this.invalidateAll(),this.applyGpuState(),this.emit("change",{what:"filter"})}setRangeBounds(e,t){this.range&&(this.range={...this.range,low:e,high:t},this.applyGpuState(),this.emit("change",{what:"filter"}))}getRange(){return this.range}setCategories(e){this.categories=e,this.categoryIndex.clear(),this.categoryModes.clear(),e?.keys?.forEach((e,t)=>this.categoryIndex.set(String(e),t)),e?.modes&&Object.entries(e.modes).forEach(([e,t])=>this.categoryModes.set(this.categoryOf(e),c[t])),this.invalidateAll(),this.applyGpuState(),this.emit("change",{what:"filter"})}setCategoryMode(e,t){const i=this.categoryOf(String(e));this.categoryModes.set(i,c[t]),this.roles.forEach(e=>e.look.setCategoryMode(i,c[t])),this.repaint(),this.emit("change",{what:"filter"})}getCategoryMode(e){const t=this.categoryIndex.get(String(e)),i=void 0===t?o.Shown:this.categoryModes.get(t)??o.Shown;return Object.keys(c).find(e=>c[e]===i)??"shown"}categoryKeys(){return[...this.categoryIndex.keys()]}categoryColor(e){const t=this.categoryOf(String(e));return s(this.paletteColor(String(e),t))}colorBy(e){const t=this.coloring;this.coloring=e??{by:"style"};"value"in this.coloring&&(!("value"in t)||t.value!==this.coloring.value)&&this.invalidateAll(),this.applyGpuState(),this.emit("change",{what:"style"})}select(e,t="replace"){const i=new Set,s=[...e];"replace"===t&&(this.selected.forEach(e=>i.add(e)),this.selected.clear()),s.forEach(e=>{if(!this.indexOf.has(e))return;const s=this.selected.has(e);"remove"!==t&&("toggle"!==t||!s)?this.selected.add(e):this.selected.delete(e),i.add(e)}),0!==i.size&&(this.restyle(i),this.emit("change",{what:"selection"}))}clearSelection(){0!==this.selected.size&&this.select([],"replace")}selection(){return[...this.selected]}isSelected(e){return this.selected.has(e)}emphasize(e){const t=new Set(e??[]),i=new Set;this.emphasized.forEach(e=>{t.has(e)||i.add(e)}),t.forEach(e=>{this.emphasized.has(e)||i.add(e)}),this.emphasized.clear(),t.forEach(e=>this.emphasized.add(e)),i.size>0&&this.restyle(i)}isEmphasizing(){return this.emphasized.size>0}setOverride(e,t){const i=[],s="hidden"===t?l.Hidden:"faded"===t?l.Faded:l.Selected;for(const r of e)(null===t?this.overrides.delete(r):this.overrides.get(r)!==s)&&i.push(r),null!==t&&this.overrides.set(r,s);i.length>0&&this.restyle(i)}clearOverrides(){const e=[...this.overrides.keys()];this.overrides.clear(),e.length>0&&this.restyle(e)}setHovered(e){if(e===this.hovered)return;this.hovered=e;const t=null===e?-1:this.indexOf.get(e)??-1;this.roles.forEach(e=>{e.look.hoverIndex.value=t}),this.repaint()}getHovered(){return this.hovered}get lit(){return this.selected.size>0||this.emphasized.size>0||null!==this.hovered||[...this.categoryModes.values()].some(e=>e===o.Lit)}hitAt(e){const t=this.features[e];return t&&this.isPickable()?{layer:this,feature:t,id:t.id,index:e}:null}attach(e){this.host=e;const t=e.engine.addPickSource(e=>this.hitAt(e));this.pick={pass:e.engine.pickPass,source:t.id},this.removePickSource=t.remove,this.invalidateBuild()}detach(){this.dropPrimitives(),this.removePickSource?.(),this.removePickSource=null,this.pick=null,this.host=null}dispose(){this.detach()}get wantsBuild(){const e=this.host;if(!e)return!1;const t=this.buildKey(e);return(this.needsBuild||t!==this.builtFor)&&!(this.builds.has(t)&&!this.needsBuild)}beforeRender(e=!0){const t=this.host;if(!t)return;const i=this.buildKey(t);if(this.needsBuild||i!==this.builtFor){if(!e&&this.wantsBuild)return;this.build(t,i)}else this.needsRefresh&&this.refresh(t,i);this.updateLooks(),this.updateMeshes(t)}buildKey(e){return e.mode}addRole(e,t){const i=new a(Math.max(1,this.features.length),{...t,failLooks:t?.failLooks||!!this.range?.fail});return this.roles.push({look:i,write:e}),i}invalidateBuild(){this.needsBuild=!0,this.needsRefresh=!1,this.repaint()}setOverlay(e,t=0){e===this.overlay&&t===this.overlayOrder||(this.overlay=e,this.overlayOrder=t,this.invalidateBuild())}canRefresh(){return!0}refresh(e,t){this.needsRefresh=!1,this.dropStashed();const i=this.builtOrigin,s=this.roles.every(e=>e.look.capacity>=Math.max(1,this.features.length));if(!i||0===this.primitives.length||!s||!this.canRefresh())return this.needsBuild=!0,void this.build(e,t);const r=performance.now(),h=this.roles;this.roles=[];let o=[],a=[];try{o=this.createPrimitives(e,i)}finally{a=this.roles,this.roles=h}let l=o.length===this.primitives.length;for(let e=0;l&&e<o.length;e++)l=this.primitives[e].adopt?.(o[e])??!1;if(o.forEach(e=>e.dispose()),a.forEach(e=>e.look.dispose()),!l)return this.needsBuild=!0,void this.build(e,t);this.allDirty=!0,this.applyGpuState();const n=null===this.hovered?-1:this.indexOf.get(this.hovered)??-1;this.roles.forEach(e=>{e.look.hoverIndex.value=n}),this.emit("build",{ms:performance.now()-r,features:this.features.length,instances:this.instanceCount(),refresh:!0})}invalidateAll(){this.allDirty=!0,this.repaint()}repaint(){this.host?.requestRepaint()}build(e,t){const i=performance.now();this.stash(),this.needsBuild&&this.dropPrimitives(),this.needsBuild=!1,this.needsRefresh=!1,this.builtFor=t;const s=this.builds.get(t);if(s){this.builds.delete(t),this.primitives=s.primitives,this.roles=s.roles,this.primitives.forEach(t=>e.engine.attach(t)),this.allDirty=!0,this.applyGpuState();const i=null===this.hovered?-1:this.indexOf.get(this.hovered)??-1;return void this.roles.forEach(e=>{e.look.hoverIndex.value=i})}if(0===this.features.length)return;const r=e.engine.originFor(function(e){for(const t of e){const e=t.geometry;if(e)switch(e.type){case"Point":return e.coordinates;case"MultiPoint":case"LineString":if(e.coordinates.length)return e.coordinates[0];break;case"MultiLineString":case"Polygon":if(e.coordinates[0]?.length)return e.coordinates[0][0];break;case"MultiPolygon":if(e.coordinates[0]?.[0]?.length)return e.coordinates[0][0][0]}}return null}(this.features)??[0,0,0]);this.builtOrigin=r,this.primitives=this.createPrimitives(e,r),this.overlay&&this.primitives.forEach(e=>function(e,t){const i=e.passes();for(const e of[...i.scene??[],...i.underlay??[]]){if(!e)continue;const i=e.material;i.depthTest=!1,i.depthWrite=!1,e.renderOrder=1e5+100*t+e.renderOrder}}(e,this.overlayOrder)),this.primitives.forEach(t=>e.engine.attach(t)),this.allDirty=!0,this.applyGpuState();const h=null===this.hovered?-1:this.indexOf.get(this.hovered)??-1;this.roles.forEach(e=>{e.look.hoverIndex.value=h}),this.emit("build",{ms:performance.now()-i,features:this.features.length,instances:this.instanceCount()})}instanceCount(){return this.primitives.reduce((e,t)=>e+(t.segments??t.count??t.triangles??0),0)}stash(){if(0===this.primitives.length)return;const e=this.host?.engine;this.primitives.forEach(t=>e?.detach(t)),this.builds.set(this.builtFor,{primitives:this.primitives,roles:this.roles}),this.primitives=[],this.roles=[]}dropStashed(){this.builds.forEach(({primitives:e,roles:t})=>{e.forEach(e=>e.dispose()),t.forEach(e=>e.look.dispose())}),this.builds.clear()}dropPrimitives(){const e=this.host?.engine;[{primitives:this.primitives,roles:this.roles},...this.builds.values()].forEach(({primitives:t,roles:i})=>{t.forEach(t=>{e?.detach(t),t.dispose()}),i.forEach(e=>e.look.dispose())}),this.builds.clear(),this.primitives=[],this.roles=[]}stateOf(e,t){let i="hidden"===t.state?l.Hidden:"faded"===t.state?l.Faded:l.Default;if(i!==l.Hidden&&this.filter&&!this.filter(e)&&(i="hide"===this.filterOutside?l.Hidden:l.Faded),i!==l.Hidden){const t=this.overrides.get(e.id);if(void 0!==t)return t}return this.selected.has(e.id)||this.emphasized.has(e.id)?i===l.Hidden?l.SelectedHidden:i===l.Faded?l.SelectedFaded:l.Selected:i}colorOf(e,t,r,h){const o=s(e??h),a=o[3]*(t??1);if(r===l.Faded){const e=i(o,.7);return[e[0],e[1],e[2],.25*a]}return[o[0],o[1],o[2],a]}updateLooks(){if(0!==this.roles.length){if(this.allDirty){this.translucent=!1;for(let e=0;e<this.features.length;e++)this.writeFeature(e)}else this.dirty.forEach(e=>this.writeFeature(e));this.allDirty=!1,this.dirty.clear(),this.roles.forEach(e=>e.look.commit())}}writeFeature(e){const t=this.features[e];if(!t)return;const i=this.styleOf(t,e),s=this.stateOf(t,i),r=this.categories?this.categoryOf(this.categories.of(t)):-1,h=this.range,o=h?h.value(t):d,a=h?.fixed?h.fixed(t):0,n=h?.fail?h.fail(t):null,c=n?this.stateOf(t,n):null,u="value"in this.coloring?this.coloring.value(t):d;for(const h of this.roles){const d=this.scratch;for(const e in d)delete d[e];if(h.write(t,e,i,s,d),d.state=d.state??s,d.category=r,d.colorValue=u,h.look.set(e,d),h.look.setValue(e,o,a),n&&null!==c&&h.look.failStyles){const i=this.failScratch;for(const e in i)delete i[e];h.write(t,e,n,c,i),i.state=i.state??c,h.look.setFail(e,i)}const f=d.color;f&&f[3]>.004&&f[3]<.99&&(this.translucent=!0),s>=l.SelectedFaded&&(this.translucent=!0)}}categoryOf(e){if(null==e)return-1;const t=String(e);let i=this.categoryIndex.get(t);if(void 0===i){if(i=this.categoryIndex.size,i>=n)return-1;this.categoryIndex.set(t,i),this.roles.forEach(e=>{e.look.setCategoryColor(i,this.paletteColor(t,i)),e.look.setCategoryMode(i,this.categoryModes.get(i)??o.Shown)})}return i}paletteColor(e,i){const s=this.categories?.colors;return Array.isArray(s)?s[i%s.length]:s&&s[e]?s[e]:t[i%t.length]}applyGpuState(){for(const{look:e}of this.roles){const t=this.range;e.rangeActive.value=t?1:0,e.rangeLow.value=t?.low??0,e.rangeHigh.value=t?.high??0,e.rangeOutside.value=t?.fail?0:"fade"===t?.outside?2:1,e.categoryActive.value=this.categories?1:0,this.categoryIndex.forEach((t,i)=>{e.setCategoryColor(t,this.paletteColor(i,t)),e.setCategoryMode(t,this.categoryModes.get(t)??o.Shown)});const i=this.coloring;e.colorMode.value="value"in i?2:"category"===i.by?1:0,"value"in i&&e.setRamp(i.ramp,i.domain[0],i.domain[1])}this.repaint()}updateMeshes(t){const i=t.highlight,s=this.visible,r=this.density,h=this.lit,o="outline"===i.look,a=!o&&"bloom"===i.glow,[l,n,d]=i.outlineColor;for(const{look:e}of this.roles)e.opacity.value=this.opacity,e.othersShade.value=i.hoverFades&&t.anyHovered?i.othersShade:1,e.othersToward.value=i.othersToward,e.hoverLights.value=i.hoverLights?1:0,e.outsideOpacity.value=i.outsideOpacity;for(const c of this.primitives){const u=c,f=c.passes(),g=(e,t)=>f[e]?.forEach(e=>{e&&(e.visible=t)});g("scene",s&&!r),g("halo",s&&!r),g("pick",s&&this.pickable),g("density",s&&r),g("bloom",s&&!r&&h&&a),u.casingMesh instanceof e&&(u.casingMesh.visible=s&&!r&&h&&o),u.ghostMesh instanceof e&&(u.ghostMesh.visible=s&&!r&&this.translucent),u.glowMode&&(u.glowMode.value=o?2:"shader"===i.glow?1:0),u.outlineRgb&&u.outlineRgb.value.set(l,n,d),u.outlineWidth&&(u.outlineWidth.value=i.outlineWidth),u.outlineMode&&(u.outlineMode.value=o?1:0),u.rimRgb&&u.rimRgb.value.set(l,n,d),u.windowsLit&&void 0!==t.windowsLit&&(u.windowsLit.value=t.windowsLit),u.uniforms?.outlineRgb&&(u.uniforms.outlineRgb.value.set(l,n,d),u.uniforms.outlineWidth.value=i.outlineWidth)}}}export function relative(e,t){return[e[0]-t[0],e[1]-t[1],(e[2]??0)-t[2]]}
|
package/layers/LineLayer.d.ts
CHANGED
|
@@ -26,6 +26,13 @@ export interface LineLayerOptions<F> extends GeometryLayerOptions<F, LineStyle>
|
|
|
26
26
|
arrows?: boolean;
|
|
27
27
|
/** How far each line stops short of its start and end, in world units: what stands there. */
|
|
28
28
|
ends?: (feature: F) => [number, number] | null | undefined;
|
|
29
|
+
/** Whether the lines stop short of their ends (`ends`) now: off while what stands there is not drawn. On by default. */
|
|
30
|
+
endsShown?: boolean;
|
|
31
|
+
/**
|
|
32
|
+
* World units per metre, where the world is not in metres - `mercatorWorldPerMetre` on Web
|
|
33
|
+
* Mercator - for widths in metres. 1 by default.
|
|
34
|
+
*/
|
|
35
|
+
worldPerMetre?: number;
|
|
29
36
|
}
|
|
30
37
|
/**
|
|
31
38
|
* Lines - networks, routes, trajectories, outlines - as `GpuLines`: one instanced draw, every
|
|
@@ -39,6 +46,13 @@ export declare class LineLayer<F extends GeometryFeature = GeometryFeature> exte
|
|
|
39
46
|
resolvedMode(host: LayerHost): 'screen' | 'ground' | 'space';
|
|
40
47
|
protected buildKey(host: LayerHost): string;
|
|
41
48
|
protected createPrimitives(host: LayerHost, origin: [number, number, number]): GeometryPrimitive[];
|
|
49
|
+
private endsShown;
|
|
50
|
+
private worldPerMetre;
|
|
51
|
+
/** Whether the lines stop short of their ends: a uniform, nothing rebuilt. */
|
|
52
|
+
setEndsShown(shown: boolean): void;
|
|
53
|
+
/** World units per metre, for widths in metres: a uniform, nothing rebuilt. */
|
|
54
|
+
setWorldPerMetre(worldPerMetre: number): void;
|
|
55
|
+
private applyLineUniforms;
|
|
42
56
|
beforeRender(): void;
|
|
43
57
|
private flowing;
|
|
44
58
|
private flows;
|
package/layers/LineLayer.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{linesOf as e}from"../data/Geometry.js";import{FeatureState as t,LookFlag as
|
|
1
|
+
import{linesOf as e}from"../data/Geometry.js";import{FeatureState as t,isLit as i,LookFlag as s}from"../three/FeatureLook.js";import{GpuLines as o}from"../three/primitives/GpuLines.js";import{GeometryLayer as r}from"./GeometryLayer.js";export class LineLayer extends r{constructor(e={}){super(e),this.options=e,this.endsShown=this.options.endsShown??!0,this.worldPerMetre=this.options.worldPerMetre??1,this.flowing=null}resolvedMode(e){const t=this.options.mode??"auto";if("2d"===e.mode)return"screen";if("auto"!==t&&"screen"!==t)return t;if("screen"===t)return"space";const i=this.bounds();return Math.abs(i.max[2]-i.min[2])>1e-6||Math.abs(i.max[2])>1e-6?"space":"ground"}buildKey(e){return`${e.mode}|${this.resolvedMode(e)}`}createPrimitives(r,n){const h=this.resolvedMode(r),l=this.features.map(t=>e(t.geometry).filter(e=>e.length>1).map(e=>e.map(e=>({x:e[0]-n[0],y:e[1]-n[1],z:(e[2]??0)-n[2]}))));let a;this.options.ends&&(a=new Float32Array(2*this.features.length),this.features.forEach((e,t)=>{const i=this.options.ends(e);i&&a.set(i,2*t)}));const d=this.addRole((e,o,r,n,h)=>{const l=this.colorOf(r.color,r.opacity,n,"#4cc9f0");h.color=l,h.width=r.width??2,h.meters="m"===r.widthUnit,h.realWidth=r.realWidth??0,h.flags=(r.dashed?s.Dashed:0)|(r.flow?s.Flow:0)|(!1===r.arrow?s.NoArrow:0),h.weight=r.weight??1,h.fadedWeight=.3*(r.weight??1),h.state=n,i(n)&&"faded"===r.state&&(h.color=this.colorOf(r.color,r.opacity,t.Default,"#4cc9f0"))}),p=new o(l,{look:d,pick:this.pick??void 0,arrows:!!this.options.arrows,ground:"ground"===h?{up:r.up}:void 0,space:"space"===h,ends:a,occluder:this.occluder});return this.applyLineUniforms(p),[p]}setEndsShown(e){this.endsShown=e,this.primitive&&this.applyLineUniforms(this.primitive),this.repaint()}setWorldPerMetre(e){this.worldPerMetre=e,this.primitive&&this.applyLineUniforms(this.primitive),this.repaint()}applyLineUniforms(e){e.endsShown.value=this.endsShown?1:0,e.worldPerMetre.value=this.worldPerMetre}beforeRender(){super.beforeRender();const e=this.host;e&&this.primitive&&e.setAnimating(`flow:${this.id}`,this.isVisible()&&this.flows())}flows(){return null===this.flowing&&(this.flowing=this.features.some((e,t)=>this.styleOf(e,t).flow)),this.flowing}invalidateAll(){this.flowing=null,super.invalidateAll()}get primitive(){return this.primitives.find(e=>e instanceof o)??null}}
|
package/layers/SphereLayer.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{pointsOf as e}from"../data/Geometry.js";import{GpuIcons as t,IconShape as i}from"../three/primitives/GpuIcons.js";import{GpuSpheres as o}from"../three/primitives/GpuSpheres.js";import{materialCode as r}from"../three/Shading.js";import{GeometryLayer as s}from"./GeometryLayer.js";export class SphereLayer extends s{constructor(e={}){super(e),this.options=e}createPrimitives(s,h){const n="2d"===s.mode,
|
|
1
|
+
import{pointsOf as e}from"../data/Geometry.js";import{GpuIcons as t,IconShape as i}from"../three/primitives/GpuIcons.js";import{GpuSpheres as o}from"../three/primitives/GpuSpheres.js";import{materialCode as r}from"../three/Shading.js";import{GeometryLayer as s}from"./GeometryLayer.js";export class SphereLayer extends s{constructor(e={}){super(e),this.options=e}createPrimitives(s,h){const n="2d"===s.mode,c=this.addRole((e,t,i,o,s)=>{s.color=this.colorOf(i.color,i.opacity,o,"#f72585"),s.material=r(i.material),s.width=n?2*(this.options.radius?.(e)??.25):i.width??4,s.meters=n,s.weight=i.weight??1,s.fadedWeight=.3*(i.weight??1)});if(n){const o=this.features.flatMap((t,o)=>e(t.geometry).map(e=>({x:e[0]-h[0],y:e[1]-h[1],z:0,cell:i.Circle,index:o})));return[new t(o,null,1,{look:c,pick:this.pick??void 0,minPixels:4,border:.6})]}const p=[];this.features.forEach((t,i)=>{const o=this.options.radius?.(t)??.25,r=this.options.reach?.(t)??0;for(const s of e(t.geometry))p.push({x:s[0]-h[0],y:s[1]-h[1],z:(s[2]??0)-h[2],index:i,radius:o,reach:r})});const a=!1!==this.options.ghost;return a&&s.engine.depthTexture(),[new o(p,{look:c,lighting:s.lighting,pick:this.pick??void 0,sceneDepth:a?s.engine.sceneDepth:null,occluder:this.occluder})]}}
|
package/layers/TubeLayer.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{linesOf as t,pointsOf as e}from"../data/Geometry.js";import{LookFlag as o}from"../three/FeatureLook.js";import{GpuIcons as r,IconShape as i}from"../three/primitives/GpuIcons.js";import{GpuLines as n}from"../three/primitives/GpuLines.js";import{GpuTubes as s,joinTubeEnds as p,roundProfile as h}from"../three/primitives/GpuTubes.js";import{materialCode as a}from"../three/Shading.js";import{GeometryLayer as c}from"./GeometryLayer.js";export class TubeLayer extends c{constructor(t={}){super(t),this.options=t}createPrimitives(c,d){const m=this.options,f=new Map,g=(t,e)=>`${Math.round(100*t)},${Math.round(100*e)}`,w=this.features.map(t=>{const o=e(t.geometry)[0],r=o&&m.stand?.(t);return o&&r&&!1!==r.open&&f.set(g(o[0],o[1]),r.radius),o&&r?{point:o,stand:r}:null}),v=this.addRole((t,e,r,i,n)=>{const s=w[e];n.color=this.colorOf(r.color,r.opacity,i,"#4cc9f0"),n.material=a(r.material),n.weight=r.weight??1,n.fadedWeight=.3*(r.weight??1),n.flags=r.flow?o.Flow:0,s?(n.width=2*s.stand.radius,n.meters=!0):(n.width=r.width??2.5,n.meters=!1,n.realWidth=2*l(m.profile?.(t))[0])}),k=[],y=[];if(w.forEach((t,e)=>{t&&!1!==t.stand.open&&!1!==m.covers&&y.push({x:t.point[0]-d[0],y:t.point[1]-d[1],z:t.stand.top-d[2]+.01,cell:i.Cover,index:e})}),"2d"===c.mode){const e=[],o=new Float32Array(2*this.features.length);return this.features.forEach((r,i)=>{e.push(t(r.geometry).filter(t=>t.length>1).map(t=>{const e=t[0],r=t[t.length-1];return o[2*i]=f.get(g(e[0],e[1]))??0,o[2*i+1]=f.get(g(r[0],r[1]))??0,t.map(t=>({x:t[0]-d[0],y:t[1]-d[1],z:0}))}))}),k.push(new n(e,{look:v,pick:this.pick??void 0,arrows:!!m.arrows,ends:o})),y.length>0&&k.push(new r(y.map(t=>({...t,z:0})),null,1,{look:v,pick:this.pick??void 0,minPixels:7})),k}const x=[],j=!1!==m.join;this.features.forEach((e,o)=>{const r=m.reach?.(e)??0,i=w[o];if(i){const{point:t,stand:e}=i;return void x.push({points:[[t[0]-d[0],t[1]-d[1],e.bottom-d[2]],[t[0]-d[0],t[1]-d[1],e.top-d[2]]],index:o,profile:h(e.radius),reach:r,kind:!1===e.open?"column":"shaft"})}const n=l(m.profile?.(e));for(const i of t(e.geometry)){if(i.length<2)continue;let t=i.map(t=>[t[0]-d[0],t[1]-d[1],(t[2]??0)-d[2]]);const e=[0,0];if(j){const o=f.get(g(i[0][0],i[0][1])),r=f.get(g(i[i.length-1][0],i[i.length-1][1]));o&&o>n[0]&&(e[0]=Math.sqrt(o*o-n[0]*n[0]),t=u(t,e[0])),r&&r>n[0]&&(e[1]=Math.sqrt(r*r-n[0]*n[0]),t=u(t.reverse(),e[1]).reverse())}t.length<2||x.push({points:t,index:o,profile:n,reach:r,cuts:e})}}),j&&p(x,.01);const M=!1!==m.ghost;M&&c.engine.depthTexture();const G=new s(x,{look:v,lighting:c.lighting,up:c.up,pick:this.pick??void 0,arrows:!!m.arrows,sceneDepth:M?c.engine.sceneDepth:null});return k.push(G),y.length>0&&k.push(new r(y,null,1,{look:v,pick:this.pick??void 0,orientation:"ground",up:c.up,depth:!0})),k}get primitive(){return this.primitives.find(t=>t instanceof s)??null}}function l(t){return void 0===t?h(.15):"number"==typeof t?h(t):t}function u(t,e){let o=e;for(let e=0;e<t.length-1;e++){const[r,i]=[t[e],t[e+1]],n=Math.hypot(i[0]-r[0],i[1]-r[1],i[2]-r[2]);if(n>o+.001){const s=o/n;return[[r[0]+(i[0]-r[0])*s,r[1]+(i[1]-r[1])*s,r[2]+(i[2]-r[2])*s],...t.slice(e+1)]}o-=n}return t}
|
|
1
|
+
import{linesOf as t,pointsOf as e}from"../data/Geometry.js";import{LookFlag as o}from"../three/FeatureLook.js";import{GpuIcons as r,IconShape as i}from"../three/primitives/GpuIcons.js";import{GpuLines as n}from"../three/primitives/GpuLines.js";import{GpuTubes as s,joinTubeEnds as p,roundProfile as h}from"../three/primitives/GpuTubes.js";import{materialCode as a}from"../three/Shading.js";import{GeometryLayer as c}from"./GeometryLayer.js";export class TubeLayer extends c{constructor(t={}){super(t),this.options=t}createPrimitives(c,d){const m=this.options,f=new Map,g=(t,e)=>`${Math.round(100*t)},${Math.round(100*e)}`,w=this.features.map(t=>{const o=e(t.geometry)[0],r=o&&m.stand?.(t);return o&&r&&!1!==r.open&&f.set(g(o[0],o[1]),r.radius),o&&r?{point:o,stand:r}:null}),v=this.addRole((t,e,r,i,n)=>{const s=w[e];n.color=this.colorOf(r.color,r.opacity,i,"#4cc9f0"),n.material=a(r.material),n.weight=r.weight??1,n.fadedWeight=.3*(r.weight??1),n.flags=r.flow?o.Flow:0,s?(n.width=2*s.stand.radius,n.meters=!0):(n.width=r.width??2.5,n.meters=!1,n.realWidth=2*l(m.profile?.(t))[0])}),k=[],y=[];if(w.forEach((t,e)=>{t&&!1!==t.stand.open&&!1!==m.covers&&y.push({x:t.point[0]-d[0],y:t.point[1]-d[1],z:t.stand.top-d[2]+.01,cell:i.Cover,index:e})}),"2d"===c.mode){const e=[],o=new Float32Array(2*this.features.length);return this.features.forEach((r,i)=>{e.push(t(r.geometry).filter(t=>t.length>1).map(t=>{const e=t[0],r=t[t.length-1];return o[2*i]=f.get(g(e[0],e[1]))??0,o[2*i+1]=f.get(g(r[0],r[1]))??0,t.map(t=>({x:t[0]-d[0],y:t[1]-d[1],z:0}))}))}),k.push(new n(e,{look:v,pick:this.pick??void 0,arrows:!!m.arrows,ends:o})),y.length>0&&k.push(new r(y.map(t=>({...t,z:0})),null,1,{look:v,pick:this.pick??void 0,minPixels:7})),k}const x=[],j=!1!==m.join;this.features.forEach((e,o)=>{const r=m.reach?.(e)??0,i=w[o];if(i){const{point:t,stand:e}=i;return void x.push({points:[[t[0]-d[0],t[1]-d[1],e.bottom-d[2]],[t[0]-d[0],t[1]-d[1],e.top-d[2]]],index:o,profile:h(e.radius),reach:r,kind:!1===e.open?"column":"shaft"})}const n=l(m.profile?.(e));for(const i of t(e.geometry)){if(i.length<2)continue;let t=i.map(t=>[t[0]-d[0],t[1]-d[1],(t[2]??0)-d[2]]);const e=[0,0];if(j){const o=f.get(g(i[0][0],i[0][1])),r=f.get(g(i[i.length-1][0],i[i.length-1][1]));o&&o>n[0]&&(e[0]=Math.sqrt(o*o-n[0]*n[0]),t=u(t,e[0])),r&&r>n[0]&&(e[1]=Math.sqrt(r*r-n[0]*n[0]),t=u(t.reverse(),e[1]).reverse())}t.length<2||x.push({points:t,index:o,profile:n,reach:r,cuts:e})}}),j&&p(x,.01);const M=!1!==m.ghost;M&&c.engine.depthTexture();const G=new s(x,{look:v,lighting:c.lighting,up:c.up,pick:this.pick??void 0,arrows:!!m.arrows,sceneDepth:M?c.engine.sceneDepth:null,occluder:this.occluder});return k.push(G),y.length>0&&k.push(new r(y,null,1,{look:v,pick:this.pick??void 0,orientation:"ground",up:c.up,depth:!0})),k}get primitive(){return this.primitives.find(t=>t instanceof s)??null}}function l(t){return void 0===t?h(.15):"number"==typeof t?h(t):t}function u(t,e){let o=e;for(let e=0;e<t.length-1;e++){const[r,i]=[t[e],t[e+1]],n=Math.hypot(i[0]-r[0],i[1]-r[1],i[2]-r[2]);if(n>o+.001){const s=o/n;return[[r[0]+(i[0]-r[0])*s,r[1]+(i[1]-r[1])*s,r[2]+(i[2]-r[2])*s],...t.slice(e+1)]}o-=n}return t}
|
package/package.json
CHANGED
package/theme/Theme.d.ts
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Protomaze theme: how every @protomaze package - time, charts, geometry, demo-engine - is
|
|
3
|
+
* styled, and how an application gives them its own look.
|
|
4
|
+
*
|
|
5
|
+
* The contract is a set of CSS custom properties, `--pm-*` (THEME_PROPERTIES), read where a
|
|
6
|
+
* package's UI sits. Set them on `:root`, or on any element around a package's UI, and every
|
|
7
|
+
* package follows: its HTML through `var(--pm-…)`, its canvas and GPU drawing through
|
|
8
|
+
* `resolveTheme`, which reads them there, and `watchTheme`, which sees them change. Whatever is left
|
|
9
|
+
* unset keeps Protomaze's own look (PROTOMAZE_DARK, PROTOMAZE_LIGHT).
|
|
10
|
+
*
|
|
11
|
+
* ```css
|
|
12
|
+
* :root {
|
|
13
|
+
* --pm-color-accent: #9AC0A6;
|
|
14
|
+
* --pm-font-family: 'IP Klartext', sans-serif;
|
|
15
|
+
* --pm-radius: 0px;
|
|
16
|
+
* }
|
|
17
|
+
* ```
|
|
18
|
+
*
|
|
19
|
+
* or, from code, `applyTheme({ accent: '#9AC0A6', fontFamily: "'IP Klartext', sans-serif", radius: 0 })`.
|
|
20
|
+
*
|
|
21
|
+
* This file is the same in @protomaze/time, @protomaze/charts and @protomaze/geometry
|
|
22
|
+
* (src/theme/Theme.ts): change them together.
|
|
23
|
+
*/
|
|
24
|
+
/** The two looks every token has a Protomaze default for. */
|
|
25
|
+
export type ColorScheme = 'dark' | 'light';
|
|
26
|
+
/** A package's `theme` option: one of the looks, or 'auto' - the page's `color-scheme`, else the system's. */
|
|
27
|
+
export type ThemeScheme = ColorScheme | 'auto';
|
|
28
|
+
/**
|
|
29
|
+
* The design tokens every package is styled with. Colours are any CSS colour; what a GPU draws
|
|
30
|
+
* should be opaque (a colour with alpha is drawn as its colour, its alpha ignored, where a
|
|
31
|
+
* package says so).
|
|
32
|
+
*/
|
|
33
|
+
export interface ThemeTokens {
|
|
34
|
+
/** Behind what a package draws: a time slider's track, a map's clear colour, a page. */
|
|
35
|
+
background: string;
|
|
36
|
+
/** Panels, menus, dialogs, tooltips: what floats on the background. */
|
|
37
|
+
surface: string;
|
|
38
|
+
/** A step up from the surface: buttons, fields, chips, a hovered row. */
|
|
39
|
+
surfaceRaised: string;
|
|
40
|
+
/** Hairlines: dividers, the borders of fields and panels. */
|
|
41
|
+
border: string;
|
|
42
|
+
/** Text, icons, a chart's labels and lines. */
|
|
43
|
+
text: string;
|
|
44
|
+
/** Secondary text: captions, hints, a lane's name. */
|
|
45
|
+
textMuted: string;
|
|
46
|
+
/** Text that is off: disabled, or a category with nothing in it. */
|
|
47
|
+
textDisabled: string;
|
|
48
|
+
/** Grid lines and ticks behind data. */
|
|
49
|
+
grid: string;
|
|
50
|
+
/** The one active thing: a primary button, the current time, what is being drawn. */
|
|
51
|
+
accent: string;
|
|
52
|
+
/** Text and icons on the accent. */
|
|
53
|
+
onAccent: string;
|
|
54
|
+
/** The outline round hovered or selected data. */
|
|
55
|
+
highlight: string;
|
|
56
|
+
/** The keyboard focus ring. */
|
|
57
|
+
focus: string;
|
|
58
|
+
danger: string;
|
|
59
|
+
success: string;
|
|
60
|
+
warning: string;
|
|
61
|
+
/** The UI's font, as CSS font-family. */
|
|
62
|
+
fontFamily: string;
|
|
63
|
+
/** Times, numbers and code. */
|
|
64
|
+
fontFamilyMono: string;
|
|
65
|
+
/** The UI's text size, px. */
|
|
66
|
+
fontSize: number;
|
|
67
|
+
/** Body text's weight. */
|
|
68
|
+
fontWeight: number;
|
|
69
|
+
/** Headings', buttons' and emphasized text's weight. */
|
|
70
|
+
fontWeightStrong: number;
|
|
71
|
+
/** Corner radius of buttons, fields and panels, px: 0 for square corners. */
|
|
72
|
+
radius: number;
|
|
73
|
+
/** The shadow under what floats: menus, dialogs, bars. CSS box-shadow. */
|
|
74
|
+
shadow: string;
|
|
75
|
+
}
|
|
76
|
+
/** Tokens resolved for one place in the page, with the look they started from. */
|
|
77
|
+
export type ResolvedTheme = ThemeTokens & {
|
|
78
|
+
scheme: ColorScheme;
|
|
79
|
+
};
|
|
80
|
+
/** The CSS custom property of each token. */
|
|
81
|
+
export declare const THEME_PROPERTIES: {
|
|
82
|
+
readonly [K in keyof ThemeTokens]: string;
|
|
83
|
+
};
|
|
84
|
+
/** Protomaze, dark: near black, white text, lime for the one active thing. The default. */
|
|
85
|
+
export declare const PROTOMAZE_DARK: Readonly<ThemeTokens>;
|
|
86
|
+
/**
|
|
87
|
+
* Protomaze, light: near white, black text. Lime does not read on white, so the active thing is
|
|
88
|
+
* a dark lime that does (4.7:1), with white on it.
|
|
89
|
+
*/
|
|
90
|
+
export declare const PROTOMAZE_LIGHT: Readonly<ThemeTokens>;
|
|
91
|
+
/** Protomaze's own tokens for a look. */
|
|
92
|
+
export declare function protomazeTheme(scheme: ColorScheme): Readonly<ThemeTokens>;
|
|
93
|
+
/** Tokens as CSS custom properties: `{ '--pm-color-accent': '#9AC0A6', '--pm-radius': '0px' }`. A React `style` takes it as it is. */
|
|
94
|
+
export declare function themeProperties(tokens: Partial<ThemeTokens>): Record<string, string>;
|
|
95
|
+
/** Tokens as a stylesheet rule, to put in the application's CSS: `:root { --pm-color-accent: #9AC0A6; … }`. */
|
|
96
|
+
export declare function themeCss(tokens: Partial<ThemeTokens>, selector?: string): string;
|
|
97
|
+
/**
|
|
98
|
+
* Sets tokens on an element - the whole page by default - as inline custom properties, so every
|
|
99
|
+
* package inside it follows at once. Gives back an undo that puts the element's own values back.
|
|
100
|
+
*/
|
|
101
|
+
export declare function applyTheme(tokens: Partial<ThemeTokens>, element?: HTMLElement): () => void;
|
|
102
|
+
/**
|
|
103
|
+
* The look a `theme` option means at an element: 'dark' and 'light' as they are; 'auto' the
|
|
104
|
+
* element's `color-scheme` where it names one, else the system's preference; nothing, `fallback`.
|
|
105
|
+
*/
|
|
106
|
+
export declare function resolveScheme(scheme: ThemeScheme | undefined, element?: Element | null, fallback?: ColorScheme): ColorScheme;
|
|
107
|
+
/**
|
|
108
|
+
* The tokens in force at an element: Protomaze's for the look `scheme` means there, then the
|
|
109
|
+
* `--pm-*` properties the page sets around it, then `overrides`. Colours come back as `rgb(…)` or
|
|
110
|
+
* `rgba(…)`, in sRGB, whatever a token is written in - `light-dark()`, `color-mix()`, `oklch()`,
|
|
111
|
+
* `var()` - so a GPU's colour parser reads them all; sizes in px.
|
|
112
|
+
* Without a document, or with the element not in one, Protomaze's tokens with the overrides.
|
|
113
|
+
*/
|
|
114
|
+
export declare function resolveTheme(element: Element | null | undefined, scheme?: ThemeScheme, overrides?: Partial<ThemeTokens>): ResolvedTheme;
|
|
115
|
+
/**
|
|
116
|
+
* Calls `onChange` (once a frame at most) whenever the tokens in force at `element` change: a
|
|
117
|
+
* `--pm-*` property set or changed anywhere above it - a class or stylesheet that switches the
|
|
118
|
+
* application's theme, `applyTheme` - its `color-scheme`, or the system's dark mode. A package
|
|
119
|
+
* then resolves its theme again. Gives back a stop.
|
|
120
|
+
*
|
|
121
|
+
* It watches through a hidden element it puts inside `element`, whose colours and fonts are the
|
|
122
|
+
* tokens', with a one-millisecond transition: the browser starts one whenever a token changes, and
|
|
123
|
+
* says so. An element the package made itself is the one to give, not one React renders.
|
|
124
|
+
*/
|
|
125
|
+
export declare function watchTheme(element: HTMLElement, onChange: () => void): () => void;
|
package/theme/Theme.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const THEME_PROPERTIES={background:"--pm-color-background",surface:"--pm-color-surface",surfaceRaised:"--pm-color-surface-raised",border:"--pm-color-border",text:"--pm-color-text",textMuted:"--pm-color-text-muted",textDisabled:"--pm-color-text-disabled",grid:"--pm-color-grid",accent:"--pm-color-accent",onAccent:"--pm-color-on-accent",highlight:"--pm-color-highlight",focus:"--pm-color-focus",danger:"--pm-color-danger",success:"--pm-color-success",warning:"--pm-color-warning",fontFamily:"--pm-font-family",fontFamilyMono:"--pm-font-family-mono",fontSize:"--pm-font-size",fontWeight:"--pm-font-weight",fontWeightStrong:"--pm-font-weight-strong",radius:"--pm-radius",shadow:"--pm-shadow"};const e=Object.keys(THEME_PROPERTIES),t=e.filter(e=>"shadow"!==e&&!e.startsWith("font")&&"radius"!==e),o=["fontSize","radius"];export const PROTOMAZE_DARK=Object.freeze({background:"#121212",surface:"#1E1E1E",surfaceRaised:"#2A2A2A",border:"#333333",text:"#FFFFFF",textMuted:"#B8B8B8",textDisabled:"#6C6C6C",grid:"#474747",accent:"#D9FF00",onAccent:"#000000",highlight:"#FFFFFF",focus:"#D9FF00",danger:"#FF6B6B",success:"#3ECF8E",warning:"#FFB300",fontFamily:"Arial, Roboto, Helvetica, sans-serif",fontFamilyMono:'ui-monospace, Menlo, Consolas, "Cascadia Mono", monospace',fontSize:12,fontWeight:400,fontWeightStrong:600,radius:6,shadow:"0 10px 40px rgba(0, 0, 0, 0.45)"});export const PROTOMAZE_LIGHT=Object.freeze({background:"#F5F5F5",surface:"#FFFFFF",surfaceRaised:"#EBEBEB",border:"#D6D6D6",text:"#121212",textMuted:"#5C5C5C",textDisabled:"#9E9E9E",grid:"#C8C8C8",accent:"#5A7D00",onAccent:"#FFFFFF",highlight:"#121212",focus:"#5A7D00",danger:"#D32F2F",success:"#1E8E5A",warning:"#B26A00",fontFamily:"Arial, Roboto, Helvetica, sans-serif",fontFamilyMono:'ui-monospace, Menlo, Consolas, "Cascadia Mono", monospace',fontSize:12,fontWeight:400,fontWeightStrong:600,radius:6,shadow:"0 10px 40px rgba(0, 0, 0, 0.18)"});export function protomazeTheme(e){return"light"===e?PROTOMAZE_LIGHT:PROTOMAZE_DARK}export function themeProperties(t){const n={};for(const r of e){const e=t[r];null!=e&&""!==e&&(n[THEME_PROPERTIES[r]]="number"==typeof e&&o.includes(r)?`${e}px`:String(e))}return n}export function themeCss(e,t=":root"){return`${t} {\n${Object.entries(themeProperties(e)).map(([e,t])=>` ${e}: ${t};`).join("\n")}\n}`}export function applyTheme(e,t){const o=t??("undefined"!=typeof document?document.documentElement:void 0);if(!o)return()=>{};const n=new Map;for(const[t,r]of Object.entries(themeProperties(e)))n.set(t,o.style.getPropertyValue(t)),o.style.setProperty(t,r);return()=>n.forEach((e,t)=>e?o.style.setProperty(t,e):o.style.removeProperty(t))}function n(e){const t=e?.ownerDocument?.defaultView;return t||("undefined"!=typeof window?window:void 0)}export function resolveScheme(e,t,o="dark"){if("dark"===e||"light"===e)return e;if("auto"!==e)return o;const r=n(t);if(!r)return o;if(t?.isConnected){const e=(r.getComputedStyle(t).colorScheme||"").split(/\s+/),o=e.includes("dark");if(o!==e.includes("light"))return o?"dark":"light"}const i=r.matchMedia?.("(prefers-color-scheme: dark)");return i?i.matches?"dark":"light":o}export function resolveTheme(t,o="dark",r){const a=resolveScheme(o,t),c={...protomazeTheme(a),scheme:a},l=n(t);if(t?.isConnected&&l){const o=l.getComputedStyle(t);let n;for(const r of e){const e=o.getPropertyValue(THEME_PROPERTIES[r]).trim();if(!e)continue;n??(n=i(t));const a=s(r,e,n,l);void 0!==a&&(c[r]=a)}n?.remove()}if(r)for(const t of e){const e=r[t];null!=e&&""!==e&&(c[t]=e)}return c}const r="position:absolute;left:0;top:0;width:0;height:0;overflow:hidden;visibility:hidden;pointer-events:none;";function i(e){const t=e.ownerDocument.createElement("span");return t.setAttribute("aria-hidden","true"),t.style.cssText=r,e.appendChild(t),t}function s(e,o,n,r){if(t.includes(e)){if(n.style.color="",n.style.color=o,!n.style.color)return;const e=r.getComputedStyle(n).color;return e?function(e,t){if(/^rgba?\(/i.test(e))return e;if(a??(a=t.createElement("canvas").getContext("2d",{willReadFrequently:!0})),!a)return e;a.clearRect(0,0,1,1),a.fillStyle="#000",a.fillStyle=e,a.fillRect(0,0,1,1);const[o,n,r,i]=a.getImageData(0,0,1,1).data;return 255===i?`rgb(${o}, ${n}, ${r})`:`rgba(${o}, ${n}, ${r}, ${Math.round(i/255*1e3)/1e3})`}(e,n.ownerDocument):void 0}if("fontSize"===e){if(n.style.fontSize="",n.style.fontSize=o,!n.style.fontSize)return;const e=parseFloat(r.getComputedStyle(n).fontSize);return Number.isFinite(e)?e:void 0}if("radius"===e){if(n.style.borderTopLeftRadius="",n.style.borderTopLeftRadius=o,!n.style.borderTopLeftRadius)return;const e=parseFloat(r.getComputedStyle(n).borderTopLeftRadius);return Number.isFinite(e)?e:void 0}if("fontWeight"===e||"fontWeightStrong"===e){if(n.style.fontWeight="",n.style.fontWeight=o,!n.style.fontWeight)return;const e=parseFloat(r.getComputedStyle(n).fontWeight);return Number.isFinite(e)?e:void 0}return o}let a;function c(t,o){if(!t.isConnected)return"";const n=o.getComputedStyle(t),r=o.matchMedia?.("(prefers-color-scheme: dark)").matches;return e.map(e=>n.getPropertyValue(THEME_PROPERTIES[e]).trim()).join("|")+`|${n.colorScheme}|${r}`}export function watchTheme(e,o){const i=n(e);if(!i||"function"!=typeof i.requestAnimationFrame)return()=>{};let s=c(e,i),a=0;const l=()=>{if(a=0,!e.isConnected)return;const t=c(e,i);t!==s&&(s=t,o())},f=()=>{a||(a=i.requestAnimationFrame(l))},d=e.ownerDocument,u=d.createElement("span");u.setAttribute("aria-hidden","true"),u.dataset.pmThemeWatch="",u.style.cssText=r;const m=e=>{const t=d.createElement("span");t.style.cssText=e,u.appendChild(t)},p=(e,t)=>`var(${THEME_PROPERTIES[e]}, ${t})`;for(const e of t)m(`color:${p(e,"rgba(1, 2, 3, 0.004)")};transition:color 1ms;`);m(`font-family:${p("fontFamily","pm-unset")};font-size:${p("fontSize","1234px")};font-weight:${p("fontWeight","1")};border-top-left-radius:${p("radius","1234px")};box-shadow:${p("shadow","1px 2px 3px 4px rgb(1, 2, 3)")};transition:all 1ms;transition-behavior:allow-discrete;`),m(`font-family:${p("fontFamilyMono","pm-unset")};font-weight:${p("fontWeightStrong","1")};color-scheme:inherit;transition:all 1ms;transition-behavior:allow-discrete;`);const h=e=>e.stopPropagation(),g=["transitionrun","transitionstart","transitionend","transitioncancel"];g.forEach(e=>u.addEventListener(e,h)),u.addEventListener("transitionrun",f),e.appendChild(u);const F=i.matchMedia?.("(prefers-color-scheme: dark)");F?.addEventListener?.("change",f);const y="function"==typeof i.ResizeObserver?new i.ResizeObserver(f):void 0;return y?.observe(e),()=>{a&&i.cancelAnimationFrame(a),u.removeEventListener("transitionrun",f),g.forEach(e=>u.removeEventListener(e,h)),u.remove(),F?.removeEventListener?.("change",f),y?.disconnect()}}
|
|
@@ -8,7 +8,7 @@ export interface CanvasGeometryEngineOptions {
|
|
|
8
8
|
antialias?: boolean;
|
|
9
9
|
/** Draw with WebGL 2 even where WebGPU is there. */
|
|
10
10
|
forceWebGL?: boolean;
|
|
11
|
-
/** The colour under everything. */
|
|
11
|
+
/** The colour under everything: Protomaze's dark background by default. A view sets its theme's. */
|
|
12
12
|
background?: string;
|
|
13
13
|
/** The most frame pixels per view pixel drawn: 2 keeps a 4K screen cheap. */
|
|
14
14
|
maxPixelRatio?: number;
|
|
@@ -36,7 +36,6 @@ export declare class CanvasGeometryEngine extends GeometryEngine {
|
|
|
36
36
|
private blit;
|
|
37
37
|
private camera3d;
|
|
38
38
|
private scheduled;
|
|
39
|
-
private readonly animators;
|
|
40
39
|
private size;
|
|
41
40
|
private background;
|
|
42
41
|
private initialising;
|
|
@@ -60,8 +59,6 @@ export declare class CanvasGeometryEngine extends GeometryEngine {
|
|
|
60
59
|
height: number;
|
|
61
60
|
pixelRatio: number;
|
|
62
61
|
};
|
|
63
|
-
/** Keeps frames coming while `key` animates something. */
|
|
64
|
-
setAnimating(key: string, animating: boolean): void;
|
|
65
62
|
requestRepaint(): void;
|
|
66
63
|
/** Draws a frame now, rather than at the next animation frame. */
|
|
67
64
|
draw(): void;
|