@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/edit/EditController.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{formatAngle as t,formatArea as e,formatLength as s}from"../engine/Labels.js";import{closestOnSegment as i,selfIntersections as n}from"../math/Lines.js";import{area as r,distance as o,pathLength as h,pointOnSurface as a}from"../math/Measure.js";import{pointInPolygon as d}from"../math/Polygons.js";import{snapRole as l}from"./CreateController.js";import{EditHistory as p}from"./EditHistory.js";import{cloneEditShape as c,fillsOf as u,fromEditShape as f,midpoints as m,orientRings as g,outlines as y,removeVertex as x,toEditShape as k,vertices as v}from"./EditShape.js";import{GeometryController as b}from"./GeometryController.js";import{Sketch as M,SKETCH_THEME as P}from"./Sketch.js";import{Snapper as A}from"./Snapper.js";export class EditController extends b{constructor(t){super(),this.options=t,this.snapper=null,this.target=null,this.mode="vertices",this.hovered=null,this.overBody=!1,this.selectedVertex=null,this.drag=null,this.problem=null,this.offHistory=null,this.history=t.history??new p,this.sketch=new M({...P,...t.theme})}setOptions(t){this.options={...this.options,...t},this.snapper&&void 0!==t.snapping&&(this.snapper.options=!1===t.snapping?{vertices:!1,edges:!1}:t.snapping),this.render()}getTarget(){const t=this.target;return t?{layer:t.layer,feature:t.feature,geometry:f(t.shape)}:null}getMode(){return this.mode}setMode(t){t!==this.mode&&(this.mode=t,this.selectedVertex=null,this.render(),this.emit("mode",t))}edit(t,e){const s=t.getFeature(e);return!!s?.geometry&&(this.target?.layer===t&&this.target.feature.id===e||(this.stop(),this.target={layer:t,feature:s,shape:k(s.geometry)},this.render(),this.emit("select",this.getTarget())),!0)}stop(){const t=this.target;t&&(t.layer.setOverride([t.feature.id],null),this.target=null,this.drag=null,this.selectedVertex=null,this.hovered=null,this.problem=null,this.render(),this.emit("select",null))}deleteFeature(){const t=this.target;return!!t&&(this.stop(),t.layer.removeFeatures([t.feature.id]),this.history.push("Delete feature",[{layer:t.layer,before:t.feature,after:null}]),this.emit("delete",{layer:t.layer,feature:t.feature}),!0)}undo(){return null!==this.history.undo()}redo(){return null!==this.history.redo()}onAttach(t){this.sketch.attach(t),!1!==this.options.snapping&&(this.snapper=new A(t,this.options.snapping??{}),this.snapper.warm()),this.offHistory=this.history.on("apply",({step:t})=>{const e=this.target;if(!e)return;if(!t.records.find(t=>t.layer===e.layer&&(t.before?.id??t.after?.id)===e.feature.id))return;const s=e.layer.getFeature(e.feature.id);s?.geometry?(e.feature=s,e.shape=k(s.geometry),this.selectedVertex=null,this.render()):this.stop()}),this.render()}onDetach(t){this.stop(),this.offHistory?.(),this.offHistory=null,this.sketch.detach(),this.snapper?.dispose(),this.snapper=null,t.labels?.clear("edit")}onPointerMove(t){if(!this.target)return this.cursor=null,!1;const e=this.handleAt(t.x,t.y),s=!e&&this.bodyAt(t.x,t.y);return e?.kind===this.hovered?.kind&&e?.path===this.hovered?.path&&e?.index===this.hovered?.index&&s===this.overBody||(this.hovered=e,this.overBody=s,this.render()),this.cursor=e?"rotate"===e.kind?"grab":"pointer":s?"move":null,!!e||s}onPointerDown(t){const e=this.target,s=this.host;if(!e||!s||0!==t.button)return!1;const i=this.handleAt(t.x,t.y),n=c(e.shape),r=this.centerOf(e.shape);if(i){let{path:o,index:h}=i,a="vertex",d="Move vertex";return"mid"===i.kind?(e.shape.paths[o].points.splice(h,0,[...i.point]),d="Add vertex"):"vertex"===i.kind&&t.alt&&!1!==this.options.heights&&"3d"===s.mode?(a="height",d="Change height"):"scale"===i.kind?(a="scale",d="Scale"):"rotate"===i.kind&&(a="rotate",d="Rotate"),"scale"!==i.kind&&"rotate"!==i.kind||(o=-1,h=-1),this.drag={kind:a,path:o,index:h,start:"mid"===i.kind?c(e.shape):n,before:n,startPoint:[...i.point],center:r,moved:"mid"===i.kind,snap:null,label:d},"vertex"!==i.kind&&"mid"!==i.kind||(this.selectedVertex={path:o,index:h}),this.cursor="rotate"===a?"grabbing":"move",this.render(),!0}if(this.bodyAt(t.x,t.y)){const e=s.toGround(t.x,t.y,r[2]);return!!e&&(this.drag={kind:"move",path:-1,index:-1,start:n,before:n,startPoint:e,center:r,moved:!1,snap:null,label:"Move"},this.cursor="move",!0)}return!1}onPointerDrag(e){const s=this.drag,i=this.target,n=this.host;if(!s||!i||!n)return;s.moved&&"vertex"!==s.kind&&"height"!==s.kind||i.layer.setOverride([i.feature.id],"faded"),s.moved=!0;const r=c(s.start);if("vertex"===s.kind){const t=r.paths[s.path],o=t.points[s.index],h=t.points.length>1?[t.points[(s.index+t.points.length-1)%t.points.length]]:[],a=this.snapper?.snap(e.x,e.y,e.shift,{z:o[2],from:h[0]??null,exclude:{layer:i.layer,id:i.feature.id}})??(()=>{const t=n.toGround(e.x,e.y,o[2]);return t?{point:t,kind:"none"}:null})();a&&(t.points[s.index]=[a.point[0],a.point[1],"vertex"===a.kind||"edge"===a.kind?a.point[2]:o[2]],"vertex"!==a.kind&&"edge"!==a.kind||(r.has3D=r.has3D||0!==a.point[2])),s.snap=a}else if("height"===s.kind){const t=r.paths[s.path].points[s.index],i=this.heightAt(e.x,e.y,t);null!==i&&(t[2]=i,r.has3D=!0)}else{const i=n.toGround(e.x,e.y,s.center[2]);if(!i)return;const o=s.center;let h;if("move"===s.kind){const t=i[0]-s.startPoint[0],e=i[1]-s.startPoint[1];h=s=>[s[0]+t,s[1]+e,s[2]]}else if("rotate"===s.kind){let n=Math.atan2(i[1]-o[1],i[0]-o[0])-Math.atan2(s.startPoint[1]-o[1],s.startPoint[0]-o[0]);e.shift&&(n=Math.round(n/(Math.PI/12))*(Math.PI/12));const r=Math.cos(n),a=Math.sin(n);h=t=>[o[0]+(t[0]-o[0])*r-(t[1]-o[1])*a,o[1]+(t[0]-o[0])*a+(t[1]-o[1])*r,t[2]],s.label=`Rotate ${t(180*n/Math.PI)}`}else{const t=Math.hypot(s.startPoint[0]-o[0],s.startPoint[1]-o[1]),e=t>0?Math.hypot(i[0]-o[0],i[1]-o[1])/t:1;h=t=>[o[0]+(t[0]-o[0])*e,o[1]+(t[1]-o[1])*e,t[2]],s.label=`Scale × ${e.toFixed(2)}`}r.paths.forEach(t=>{t.points=t.points.map(h)})}i.shape=r,this.problem=null,this.render(),this.emit("change",this.getTarget())}onPointerUp(){const t=this.drag;this.drag=null,t&&this.target&&(this.target.layer.setOverride([this.target.feature.id],null),t.moved?this.commit("move"===t.kind?"Move":"rotate"===t.kind?"Rotate":"scale"===t.kind?"Scale":t.label,t.before):this.render())}onClick(t){const e=this.host;return e&&0===t.button&&!1!==this.options.clickToEdit?(e.pickAt(t.x,t.y).then(t=>{t&&this.options.layers.includes(t.layer)?this.edit(t.layer,t.id):this.target&&this.stop()}),!0):!!this.target}onDoubleClick(t){const e=this.target;if(!e||"vertices"!==this.mode)return!1;const s=this.handleAt(t.x,t.y),i=c(e.shape);if("vertex"===s?.kind)return x(e.shape,s.path,s.index)&&(this.selectedVertex=null,this.commit("Delete vertex",i)),!0;const n=this.edgeAt(t.x,t.y);return!!n&&(e.shape.paths[n.path].points.splice(n.index,0,n.point),this.selectedVertex={path:n.path,index:n.index},this.commit("Add vertex",i),!0)}onKeyDown(t){const e=t.ctrlKey||t.metaKey,s=t.key.toLowerCase();if(e&&"z"===s)return t.shiftKey?this.redo():this.undo();if(e&&"y"===s)return this.redo();const i=this.target;if(!i)return!1;if("Escape"===t.key)return this.drag?(i.shape=this.drag.before,this.drag=null,i.layer.setOverride([i.feature.id],null),this.render()):this.stop(),!0;if("Delete"===t.key||"Backspace"===t.key){if(this.selectedVertex&&"vertices"===this.mode){const t=c(i.shape);return x(i.shape,this.selectedVertex.path,this.selectedVertex.index)?(this.selectedVertex=null,this.commit("Delete vertex",t)):this.refuse("A shape needs more vertices than that",i.shape.paths[this.selectedVertex.path].points[0]),!0}return this.deleteFeature()}return"t"===s&&!e&&(this.setMode("vertices"===this.mode?"transform":"vertices"),!0)}onPointerLeave(){(this.hovered||this.overBody)&&(this.hovered=null,this.overBody=!1,this.render())}commit(t,e){const s=this.target;if(!s)return;g(s.shape);const i=f(s.shape),n=this.check(i,s.feature);if(n)return s.shape=e,void this.refuse(n.message,n.at);const r=s.feature,o={...r,geometry:i};s.layer.updateFeatures([o]),s.feature=o,s.shape=k(i),this.history.push(t,[{layer:s.layer,before:r,after:o}]),this.render(),this.emit("commit",{layer:s.layer,before:r,after:o,label:t})}refuse(t,e){this.problem={message:t,at:e},this.render(),this.emit("problem",{message:t}),window.setTimeout(()=>{this.problem?.message===t&&(this.problem=null,this.render())},2200)}check(t,e){const s=function(t){let e=[0,0];switch(t.type){case"Point":e=t.coordinates;break;case"MultiPoint":case"LineString":e=t.coordinates[0];break;case"MultiLineString":case"Polygon":e=t.coordinates[0][0];break;case"MultiPolygon":e=t.coordinates[0][0][0]}return[e[0],e[1],e[2]??0]}(t);if(this.options.validate){const i=this.options.validate(t,e);return i?{message:i,at:s}:null}if("Polygon"===t.type||"MultiPolygon"===t.type){const e="Polygon"===t.type?[t.coordinates]:t.coordinates;for(const t of e)for(const e of t){const t=n(e,!0)[0];if(t)return{message:"Edges cross",at:t.point}}}return null}handles(){const t=this.target,e=this.host;if(!t||!e)return[];if("transform"===this.mode){const e=this.boxOf(t.shape),s=e.corners.map((t,e)=>({kind:"scale",path:-1,index:e,point:t}));return s.push({kind:"rotate",path:-1,index:0,point:e.rotate}),s}const s=v(t.shape).map(t=>({kind:"vertex",...t}));for(const i of m(t.shape)){const n=t.shape.paths[i.path],r=e.toScreen(n.points[i.index-1]),o=e.toScreen(n.points[i.index%n.points.length]);r&&o&&Math.hypot(r[0]-o[0],r[1]-o[1])>36&&s.push({kind:"mid",...i})}return s}handleAt(t,e){const s=this.host;if(!s)return null;let i=null,n=1/0;for(const r of this.handles()){const o=s.toScreen(r.point);if(!o)continue;const h=Math.hypot(o[0]-t,o[1]-e),a="mid"===r.kind?7:9,d=h+("mid"===r.kind?4:0);h<=a&&d<n&&(n=d,i=r)}return i}bodyAt(t,e){const s=this.target,i=this.host;if(!s||!i)return!1;if(this.edgeAt(t,e,7))return!0;const n=this.centerOf(s.shape),r=i.toGround(t,e,n[2]);if(r&&u(s.shape).some(t=>d(r,t)))return!0;for(const n of s.shape.paths){if("point"!==n.kind)continue;const s=i.toScreen(n.points[0]);if(s&&Math.hypot(s[0]-t,s[1]-e)<=11)return!0}return!1}edgeAt(t,e,s=7){const n=this.target,r=this.host;if(!n||!r)return null;let o=null,h=s;return n.shape.paths.forEach((s,n)=>{if("point"===s.kind)return;const a=s.points.length,d="ring"===s.kind?a:a-1;for(let l=0;l<d;l++){const d=s.points[l],p=s.points[(l+1)%a],c=r.toScreen(d),u=r.toScreen(p);if(!c||!u)continue;const f=i([t,e],c,u,2);if(f.distance<h){h=f.distance;const t=f.t;o={path:n,index:l+1,point:[d[0]+(p[0]-d[0])*t,d[1]+(p[1]-d[1])*t,d[2]+(p[2]-d[2])*t]}}}}),o}heightAt(t,e,s){const i=this.host;if(!i)return null;const{origin:n,direction:r}=i.rayAt(t,e),{f:o}=i.camera.basis();let h=o[0],a=o[1];const d=Math.hypot(h,a);if(d<1e-6)return null;h/=d,a/=d;const l=h*r[0]+a*r[1];if(Math.abs(l)<1e-6)return null;const p=(h*(s[0]-n[0])+a*(s[1]-n[1]))/l;return p>0?n[2]+r[2]*p:null}centerOf(t){return this.boxOf(t).center}boxOf(t){let e=1/0,s=1/0,i=-1/0,n=-1/0,r=0,o=0;t.paths.forEach(t=>t.points.forEach(t=>{e=Math.min(e,t[0]),s=Math.min(s,t[1]),i=Math.max(i,t[0]),n=Math.max(n,t[1]),r+=t[2],o++})),r=o>0?r/o:0;const h=[(e+i)/2,(s+n)/2,r],a=[[e,s,r],[i,s,r],[i,n,r],[e,n,r]],d=this.host?.pixelSizeAt(h)??1;return{center:h,corners:a,rotate:[h[0],n+32*d,r],top:[h[0],n,r]}}render(){const t=this.host;if(!t)return;const i=this.target,n=[];if(!i)return this.sketch.clear(),t.labels?.set("edit",n),void t.requestRepaint();const d=i.shape,p=this.drag,c=!!this.problem,m={fills:[],lines:[],points:[]};if(u(d).forEach(t=>m.fills.push({rings:t,role:c?"invalid":"fill"})),y(d).forEach(t=>m.lines.push({coordinates:t,role:c?"invalid":"edge"})),"transform"===this.mode){const t=this.boxOf(d);m.lines.push({coordinates:[...t.corners,t.corners[0]],role:"guide"}),m.lines.push({coordinates:[t.top,t.rotate],role:"guide"}),m.points.push({position:t.center,role:"center"})}const g=t=>this.selectedVertex&&"vertex"===t.kind&&t.path===this.selectedVertex.path&&t.index===this.selectedVertex.index||this.hovered&&t.kind===this.hovered.kind&&t.path===this.hovered.path&&t.index===this.hovered.index;for(const t of this.handles()){const e=g(t)?"active":"mid"===t.kind?"mid":"scale"===t.kind?"scale":"rotate"===t.kind?"rotate":d.type.includes("Point")?"point":"vertex";m.points.push({position:t.point,role:e})}if(p?.snap&&"none"!==p.snap.kind&&m.points.push({position:p.snap.point,role:l(p.snap)}),!1!==this.options.measure){const t=f(d),i=p&&p.path>=0?{path:p.path,index:p.index}:this.selectedVertex;if(i){const t=d.paths[i.path],e=t?.points.length??0;if(t&&"point"!==t.kind)for(const r of[i.index-1,i.index]){if(!("ring"===t.kind)&&(r<0||r+1>=e))continue;const i=t.points[(r+e)%e],h=t.points[(r+1)%e];n.push({id:`e${r}`,position:S(i,h),text:s(o(i,h)),kind:"segment"})}if("height"===p?.kind&&t){const e=t.points[i.index],s=p.start.paths[i.path].points[i.index][2],r=e[2]-s;n.push({id:"z",position:e,text:`z ${e[2].toFixed(2)} m (${r>=0?"+":""}${r.toFixed(2)})`,kind:"measure",offset:[0,-24]})}}if("Polygon"===t.type||"MultiPolygon"===t.type){const s=a(t);s&&n.push({id:"area",position:s,text:e(r(t)),kind:"measure"})}else if("LineString"===t.type||"MultiLineString"===t.type){const e="LineString"===t.type?[t.coordinates]:t.coordinates,i=e.reduce((t,e)=>t+h(e),0),r=e.reduce((t,e)=>h(e)>h(t)?e:t,e[0]);n.push({id:"length",position:V(r),text:s(i),kind:"measure",offset:[0,-18]})}if(p&&p.moved&&("move"===p.kind||"rotate"===p.kind||"scale"===p.kind)){const t=this.centerOf(d),e="move"===p.kind?`Δ ${s(Math.hypot(t[0]-p.center[0],t[1]-p.center[1]))}`:p.label.replace(/^(Rotate|Scale) /,"");n.push({id:"transform",position:t,text:e,kind:"info",offset:[0,24]})}}this.problem&&n.push({id:"problem",position:this.problem.at,text:this.problem.message,kind:"warning",offset:[0,22]}),this.sketch.set(m),t.labels?.set("edit",n),t.requestRepaint()}}function S(t,e){return[(t[0]+e[0])/2,(t[1]+e[1])/2,((t[2]??0)+(e[2]??0))/2]}function V(t){const e=h(t)/2;let s=0;for(let i=1;i<t.length;i++){const n=o(t[i-1],t[i]);if(s+n>=e&&n>0){const r=(e-s)/n,o=t[i-1],h=t[i];return[o[0]+(h[0]-o[0])*r,o[1]+(h[1]-o[1])*r,(o[2]??0)+((h[2]??0)-(o[2]??0))*r]}s+=n}const i=t[0];return[i[0],i[1],i[2]??0]}
|
|
1
|
+
import{formatAngle as t,formatArea as e,formatLength as s}from"../engine/Labels.js";import{closestOnSegment as i,selfIntersections as n}from"../math/Lines.js";import{area as r,distance as o,pathLength as h,pointOnSurface as a}from"../math/Measure.js";import{pointInPolygon as d}from"../math/Polygons.js";import{snapRole as l}from"./CreateController.js";import{EditHistory as p}from"./EditHistory.js";import{cloneEditShape as c,fillsOf as u,fromEditShape as f,midpoints as m,orientRings as g,outlines as y,removeVertex as x,toEditShape as k,vertices as v}from"./EditShape.js";import{GeometryController as b}from"./GeometryController.js";import{Sketch as M,SKETCH_THEME as P}from"./Sketch.js";import{Snapper as A}from"./Snapper.js";export class EditController extends b{constructor(t){super(),this.options=t,this.snapper=null,this.target=null,this.mode="vertices",this.hovered=null,this.overBody=!1,this.selectedVertex=null,this.drag=null,this.problem=null,this.offHistory=null,this.history=t.history??new p,this.sketch=new M({...P,...t.theme},t.theme??{})}setOptions(t){this.options={...this.options,...t},this.snapper&&void 0!==t.snapping&&(this.snapper.options=!1===t.snapping?{vertices:!1,edges:!1}:t.snapping),this.render()}getTarget(){const t=this.target;return t?{layer:t.layer,feature:t.feature,geometry:f(t.shape)}:null}getMode(){return this.mode}setMode(t){t!==this.mode&&(this.mode=t,this.selectedVertex=null,this.render(),this.emit("mode",t))}edit(t,e){const s=t.getFeature(e);return!!s?.geometry&&(this.target?.layer===t&&this.target.feature.id===e||(this.stop(),this.target={layer:t,feature:s,shape:k(s.geometry)},this.render(),this.emit("select",this.getTarget())),!0)}stop(){const t=this.target;t&&(t.layer.setOverride([t.feature.id],null),this.target=null,this.drag=null,this.selectedVertex=null,this.hovered=null,this.problem=null,this.render(),this.emit("select",null))}deleteFeature(){const t=this.target;return!!t&&(this.stop(),t.layer.removeFeatures([t.feature.id]),this.history.push("Delete feature",[{layer:t.layer,before:t.feature,after:null}]),this.emit("delete",{layer:t.layer,feature:t.feature}),!0)}undo(){return null!==this.history.undo()}redo(){return null!==this.history.redo()}onAttach(t){this.sketch.attach(t),!1!==this.options.snapping&&(this.snapper=new A(t,this.options.snapping??{}),this.snapper.warm()),this.offHistory=this.history.on("apply",({step:t})=>{const e=this.target;if(!e)return;if(!t.records.find(t=>t.layer===e.layer&&(t.before?.id??t.after?.id)===e.feature.id))return;const s=e.layer.getFeature(e.feature.id);s?.geometry?(e.feature=s,e.shape=k(s.geometry),this.selectedVertex=null,this.render()):this.stop()}),this.render()}onDetach(t){this.stop(),this.offHistory?.(),this.offHistory=null,this.sketch.detach(),this.snapper?.dispose(),this.snapper=null,t.labels?.clear("edit")}onPointerMove(t){if(!this.target)return this.cursor=null,!1;const e=this.handleAt(t.x,t.y),s=!e&&this.bodyAt(t.x,t.y);return e?.kind===this.hovered?.kind&&e?.path===this.hovered?.path&&e?.index===this.hovered?.index&&s===this.overBody||(this.hovered=e,this.overBody=s,this.render()),this.cursor=e?"rotate"===e.kind?"grab":"pointer":s?"move":null,!!e||s}onPointerDown(t){const e=this.target,s=this.host;if(!e||!s||0!==t.button)return!1;const i=this.handleAt(t.x,t.y),n=c(e.shape),r=this.centerOf(e.shape);if(i){let{path:o,index:h}=i,a="vertex",d="Move vertex";return"mid"===i.kind?(e.shape.paths[o].points.splice(h,0,[...i.point]),d="Add vertex"):"vertex"===i.kind&&t.alt&&!1!==this.options.heights&&"3d"===s.mode?(a="height",d="Change height"):"scale"===i.kind?(a="scale",d="Scale"):"rotate"===i.kind&&(a="rotate",d="Rotate"),"scale"!==i.kind&&"rotate"!==i.kind||(o=-1,h=-1),this.drag={kind:a,path:o,index:h,start:"mid"===i.kind?c(e.shape):n,before:n,startPoint:[...i.point],center:r,moved:"mid"===i.kind,snap:null,label:d},"vertex"!==i.kind&&"mid"!==i.kind||(this.selectedVertex={path:o,index:h}),this.cursor="rotate"===a?"grabbing":"move",this.render(),!0}if(this.bodyAt(t.x,t.y)){const e=s.toGround(t.x,t.y,r[2]);return!!e&&(this.drag={kind:"move",path:-1,index:-1,start:n,before:n,startPoint:e,center:r,moved:!1,snap:null,label:"Move"},this.cursor="move",!0)}return!1}onPointerDrag(e){const s=this.drag,i=this.target,n=this.host;if(!s||!i||!n)return;s.moved&&"vertex"!==s.kind&&"height"!==s.kind||i.layer.setOverride([i.feature.id],"faded"),s.moved=!0;const r=c(s.start);if("vertex"===s.kind){const t=r.paths[s.path],o=t.points[s.index],h=t.points.length>1?[t.points[(s.index+t.points.length-1)%t.points.length]]:[],a=this.snapper?.snap(e.x,e.y,e.shift,{z:o[2],from:h[0]??null,exclude:{layer:i.layer,id:i.feature.id}})??(()=>{const t=n.toGround(e.x,e.y,o[2]);return t?{point:t,kind:"none"}:null})();a&&(t.points[s.index]=[a.point[0],a.point[1],"vertex"===a.kind||"edge"===a.kind?a.point[2]:o[2]],"vertex"!==a.kind&&"edge"!==a.kind||(r.has3D=r.has3D||0!==a.point[2])),s.snap=a}else if("height"===s.kind){const t=r.paths[s.path].points[s.index],i=this.heightAt(e.x,e.y,t);null!==i&&(t[2]=i,r.has3D=!0)}else{const i=n.toGround(e.x,e.y,s.center[2]);if(!i)return;const o=s.center;let h;if("move"===s.kind){const t=i[0]-s.startPoint[0],e=i[1]-s.startPoint[1];h=s=>[s[0]+t,s[1]+e,s[2]]}else if("rotate"===s.kind){let n=Math.atan2(i[1]-o[1],i[0]-o[0])-Math.atan2(s.startPoint[1]-o[1],s.startPoint[0]-o[0]);e.shift&&(n=Math.round(n/(Math.PI/12))*(Math.PI/12));const r=Math.cos(n),a=Math.sin(n);h=t=>[o[0]+(t[0]-o[0])*r-(t[1]-o[1])*a,o[1]+(t[0]-o[0])*a+(t[1]-o[1])*r,t[2]],s.label=`Rotate ${t(180*n/Math.PI)}`}else{const t=Math.hypot(s.startPoint[0]-o[0],s.startPoint[1]-o[1]),e=t>0?Math.hypot(i[0]-o[0],i[1]-o[1])/t:1;h=t=>[o[0]+(t[0]-o[0])*e,o[1]+(t[1]-o[1])*e,t[2]],s.label=`Scale × ${e.toFixed(2)}`}r.paths.forEach(t=>{t.points=t.points.map(h)})}i.shape=r,this.problem=null,this.render(),this.emit("change",this.getTarget())}onPointerUp(){const t=this.drag;this.drag=null,t&&this.target&&(this.target.layer.setOverride([this.target.feature.id],null),t.moved?this.commit("move"===t.kind?"Move":"rotate"===t.kind?"Rotate":"scale"===t.kind?"Scale":t.label,t.before):this.render())}onClick(t){const e=this.host;return e&&0===t.button&&!1!==this.options.clickToEdit?(e.pickAt(t.x,t.y).then(t=>{t&&this.options.layers.includes(t.layer)?this.edit(t.layer,t.id):this.target&&this.stop()}),!0):!!this.target}onDoubleClick(t){const e=this.target;if(!e||"vertices"!==this.mode)return!1;const s=this.handleAt(t.x,t.y),i=c(e.shape);if("vertex"===s?.kind)return x(e.shape,s.path,s.index)&&(this.selectedVertex=null,this.commit("Delete vertex",i)),!0;const n=this.edgeAt(t.x,t.y);return!!n&&(e.shape.paths[n.path].points.splice(n.index,0,n.point),this.selectedVertex={path:n.path,index:n.index},this.commit("Add vertex",i),!0)}onKeyDown(t){const e=t.ctrlKey||t.metaKey,s=t.key.toLowerCase();if(e&&"z"===s)return t.shiftKey?this.redo():this.undo();if(e&&"y"===s)return this.redo();const i=this.target;if(!i)return!1;if("Escape"===t.key)return this.drag?(i.shape=this.drag.before,this.drag=null,i.layer.setOverride([i.feature.id],null),this.render()):this.stop(),!0;if("Delete"===t.key||"Backspace"===t.key){if(this.selectedVertex&&"vertices"===this.mode){const t=c(i.shape);return x(i.shape,this.selectedVertex.path,this.selectedVertex.index)?(this.selectedVertex=null,this.commit("Delete vertex",t)):this.refuse("A shape needs more vertices than that",i.shape.paths[this.selectedVertex.path].points[0]),!0}return this.deleteFeature()}return"t"===s&&!e&&(this.setMode("vertices"===this.mode?"transform":"vertices"),!0)}onPointerLeave(){(this.hovered||this.overBody)&&(this.hovered=null,this.overBody=!1,this.render())}commit(t,e){const s=this.target;if(!s)return;g(s.shape);const i=f(s.shape),n=this.check(i,s.feature);if(n)return s.shape=e,void this.refuse(n.message,n.at);const r=s.feature,o={...r,geometry:i};s.layer.updateFeatures([o]),s.feature=o,s.shape=k(i),this.history.push(t,[{layer:s.layer,before:r,after:o}]),this.render(),this.emit("commit",{layer:s.layer,before:r,after:o,label:t})}refuse(t,e){this.problem={message:t,at:e},this.render(),this.emit("problem",{message:t}),window.setTimeout(()=>{this.problem?.message===t&&(this.problem=null,this.render())},2200)}check(t,e){const s=function(t){let e=[0,0];switch(t.type){case"Point":e=t.coordinates;break;case"MultiPoint":case"LineString":e=t.coordinates[0];break;case"MultiLineString":case"Polygon":e=t.coordinates[0][0];break;case"MultiPolygon":e=t.coordinates[0][0][0]}return[e[0],e[1],e[2]??0]}(t);if(this.options.validate){const i=this.options.validate(t,e);return i?{message:i,at:s}:null}if("Polygon"===t.type||"MultiPolygon"===t.type){const e="Polygon"===t.type?[t.coordinates]:t.coordinates;for(const t of e)for(const e of t){const t=n(e,!0)[0];if(t)return{message:"Edges cross",at:t.point}}}return null}handles(){const t=this.target,e=this.host;if(!t||!e)return[];if("transform"===this.mode){const e=this.boxOf(t.shape),s=e.corners.map((t,e)=>({kind:"scale",path:-1,index:e,point:t}));return s.push({kind:"rotate",path:-1,index:0,point:e.rotate}),s}const s=v(t.shape).map(t=>({kind:"vertex",...t}));for(const i of m(t.shape)){const n=t.shape.paths[i.path],r=e.toScreen(n.points[i.index-1]),o=e.toScreen(n.points[i.index%n.points.length]);r&&o&&Math.hypot(r[0]-o[0],r[1]-o[1])>36&&s.push({kind:"mid",...i})}return s}handleAt(t,e){const s=this.host;if(!s)return null;let i=null,n=1/0;for(const r of this.handles()){const o=s.toScreen(r.point);if(!o)continue;const h=Math.hypot(o[0]-t,o[1]-e),a="mid"===r.kind?7:9,d=h+("mid"===r.kind?4:0);h<=a&&d<n&&(n=d,i=r)}return i}bodyAt(t,e){const s=this.target,i=this.host;if(!s||!i)return!1;if(this.edgeAt(t,e,7))return!0;const n=this.centerOf(s.shape),r=i.toGround(t,e,n[2]);if(r&&u(s.shape).some(t=>d(r,t)))return!0;for(const n of s.shape.paths){if("point"!==n.kind)continue;const s=i.toScreen(n.points[0]);if(s&&Math.hypot(s[0]-t,s[1]-e)<=11)return!0}return!1}edgeAt(t,e,s=7){const n=this.target,r=this.host;if(!n||!r)return null;let o=null,h=s;return n.shape.paths.forEach((s,n)=>{if("point"===s.kind)return;const a=s.points.length,d="ring"===s.kind?a:a-1;for(let l=0;l<d;l++){const d=s.points[l],p=s.points[(l+1)%a],c=r.toScreen(d),u=r.toScreen(p);if(!c||!u)continue;const f=i([t,e],c,u,2);if(f.distance<h){h=f.distance;const t=f.t;o={path:n,index:l+1,point:[d[0]+(p[0]-d[0])*t,d[1]+(p[1]-d[1])*t,d[2]+(p[2]-d[2])*t]}}}}),o}heightAt(t,e,s){const i=this.host;if(!i)return null;const{origin:n,direction:r}=i.rayAt(t,e),{f:o}=i.camera.basis();let h=o[0],a=o[1];const d=Math.hypot(h,a);if(d<1e-6)return null;h/=d,a/=d;const l=h*r[0]+a*r[1];if(Math.abs(l)<1e-6)return null;const p=(h*(s[0]-n[0])+a*(s[1]-n[1]))/l;return p>0?n[2]+r[2]*p:null}centerOf(t){return this.boxOf(t).center}boxOf(t){let e=1/0,s=1/0,i=-1/0,n=-1/0,r=0,o=0;t.paths.forEach(t=>t.points.forEach(t=>{e=Math.min(e,t[0]),s=Math.min(s,t[1]),i=Math.max(i,t[0]),n=Math.max(n,t[1]),r+=t[2],o++})),r=o>0?r/o:0;const h=[(e+i)/2,(s+n)/2,r],a=[[e,s,r],[i,s,r],[i,n,r],[e,n,r]],d=this.host?.pixelSizeAt(h)??1;return{center:h,corners:a,rotate:[h[0],n+32*d,r],top:[h[0],n,r]}}render(){const t=this.host;if(!t)return;const i=this.target,n=[];if(!i)return this.sketch.clear(),t.labels?.set("edit",n),void t.requestRepaint();const d=i.shape,p=this.drag,c=!!this.problem,m={fills:[],lines:[],points:[]};if(u(d).forEach(t=>m.fills.push({rings:t,role:c?"invalid":"fill"})),y(d).forEach(t=>m.lines.push({coordinates:t,role:c?"invalid":"edge"})),"transform"===this.mode){const t=this.boxOf(d);m.lines.push({coordinates:[...t.corners,t.corners[0]],role:"guide"}),m.lines.push({coordinates:[t.top,t.rotate],role:"guide"}),m.points.push({position:t.center,role:"center"})}const g=t=>this.selectedVertex&&"vertex"===t.kind&&t.path===this.selectedVertex.path&&t.index===this.selectedVertex.index||this.hovered&&t.kind===this.hovered.kind&&t.path===this.hovered.path&&t.index===this.hovered.index;for(const t of this.handles()){const e=g(t)?"active":"mid"===t.kind?"mid":"scale"===t.kind?"scale":"rotate"===t.kind?"rotate":d.type.includes("Point")?"point":"vertex";m.points.push({position:t.point,role:e})}if(p?.snap&&"none"!==p.snap.kind&&m.points.push({position:p.snap.point,role:l(p.snap)}),!1!==this.options.measure){const t=f(d),i=p&&p.path>=0?{path:p.path,index:p.index}:this.selectedVertex;if(i){const t=d.paths[i.path],e=t?.points.length??0;if(t&&"point"!==t.kind)for(const r of[i.index-1,i.index]){if(!("ring"===t.kind)&&(r<0||r+1>=e))continue;const i=t.points[(r+e)%e],h=t.points[(r+1)%e];n.push({id:`e${r}`,position:S(i,h),text:s(o(i,h)),kind:"segment"})}if("height"===p?.kind&&t){const e=t.points[i.index],s=p.start.paths[i.path].points[i.index][2],r=e[2]-s;n.push({id:"z",position:e,text:`z ${e[2].toFixed(2)} m (${r>=0?"+":""}${r.toFixed(2)})`,kind:"measure",offset:[0,-24]})}}if("Polygon"===t.type||"MultiPolygon"===t.type){const s=a(t);s&&n.push({id:"area",position:s,text:e(r(t)),kind:"measure"})}else if("LineString"===t.type||"MultiLineString"===t.type){const e="LineString"===t.type?[t.coordinates]:t.coordinates,i=e.reduce((t,e)=>t+h(e),0),r=e.reduce((t,e)=>h(e)>h(t)?e:t,e[0]);n.push({id:"length",position:V(r),text:s(i),kind:"measure",offset:[0,-18]})}if(p&&p.moved&&("move"===p.kind||"rotate"===p.kind||"scale"===p.kind)){const t=this.centerOf(d),e="move"===p.kind?`Δ ${s(Math.hypot(t[0]-p.center[0],t[1]-p.center[1]))}`:p.label.replace(/^(Rotate|Scale) /,"");n.push({id:"transform",position:t,text:e,kind:"info",offset:[0,24]})}}this.problem&&n.push({id:"problem",position:this.problem.at,text:this.problem.message,kind:"warning",offset:[0,22]}),this.sketch.set(m),t.labels?.set("edit",n),t.requestRepaint()}}function S(t,e){return[(t[0]+e[0])/2,(t[1]+e[1])/2,((t[2]??0)+(e[2]??0))/2]}function V(t){const e=h(t)/2;let s=0;for(let i=1;i<t.length;i++){const n=o(t[i-1],t[i]);if(s+n>=e&&n>0){const r=(e-s)/n,o=t[i-1],h=t[i];return[o[0]+(h[0]-o[0])*r,o[1]+(h[1]-o[1])*r,(o[2]??0)+((h[2]??0)-(o[2]??0))*r]}s+=n}const i=t[0];return[i[0],i[1],i[2]??0]}
|
|
@@ -5,6 +5,7 @@ import type { MapCamera } from '../engine/MapCamera';
|
|
|
5
5
|
import { TypedEventEmitter } from '../event/TypedEventEmitter';
|
|
6
6
|
import type { GeometryLayer } from '../layers/GeometryLayer';
|
|
7
7
|
import type { Vec3 } from '../math/Vector';
|
|
8
|
+
import type { ThemeTokens } from '../theme/Theme';
|
|
8
9
|
/** A pointer event as a controller gets it: where in the view, which button, which keys held. */
|
|
9
10
|
export interface ControllerPointer {
|
|
10
11
|
/** View pixels from the view's top-left. */
|
|
@@ -47,10 +48,15 @@ export interface ControllerHost {
|
|
|
47
48
|
pixelSizeAt(p: Position): number;
|
|
48
49
|
pickAt(x: number, y: number): Promise<GeometryHit | null>;
|
|
49
50
|
requestRepaint(): void;
|
|
51
|
+
/**
|
|
52
|
+
* The theme's tokens in force at the view, what a sketch is drawn in; a new object when they
|
|
53
|
+
* change, with the overlays restyled. A host without them leaves the sketch's own colours.
|
|
54
|
+
*/
|
|
55
|
+
readonly tokens?: ThemeTokens;
|
|
50
56
|
}
|
|
51
57
|
/**
|
|
52
58
|
* Something that takes over the pointer and keys of a view for a while - drawing new geometry,
|
|
53
|
-
* editing it, measuring - as
|
|
59
|
+
* editing it, measuring - as a map toolkit's controllers do on its map. The view offers it every
|
|
54
60
|
* event first; what it handles (returns true for) the view leaves alone, the rest - panning,
|
|
55
61
|
* zooming, hovering, selecting - goes on as usual.
|
|
56
62
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{formatArea as
|
|
1
|
+
import{formatArea as e,formatLength as t,formatSlope as i}from"../engine/Labels.js";import{area as s,distance as n,distance2D as o,pathLength as h,perimeter as r,pointOnSurface as a,slope as p}from"../math/Measure.js";import{geometryDistance as c}from"../math/Relations.js";import{snapRole as l}from"./CreateController.js";import{GeometryController as d}from"./GeometryController.js";import{Sketch as u,SKETCH_THEME as f}from"./Sketch.js";import{Snapper as m}from"./Snapper.js";export class MeasureController extends d{constructor(e){super(),this.options=e,this.snapper=null,this.points=[],this.hover=null,this.done=!1,this.picked=[],this.clearance=null,this.queue=Promise.resolve(),this.pointer=null,this.hoverPicking=!1,this.sketch=new u({...f,...e.theme},e.theme??{}),this.cursor="crosshair"}get mode(){return this.options.mode}setMode(e){this.options={...this.options,mode:e},this.clear()}clear(){this.points=[],this.picked=[],this.clearance=null,this.done=!1,this.render()}onAttach(e){this.sketch.attach(e),!1!==this.options.snapping&&(this.snapper=new m(e,this.options.snapping??{}),this.snapper.warm()),this.render()}onDetach(e){this.sketch.detach(),this.snapper?.dispose(),this.snapper=null,e.labels?.clear("measure"),this.points=[],this.picked=[],this.clearance=null}onPointerMove(e){return"clearance"!==this.options.mode&&(this.hover=this.done?null:this.locate(e),this.render(),this.pickHover(e),!0)}pickHover(e){this.pointer={x:e.x,y:e.y};const t=this.host;if(!t||this.done||!1===this.options.surface||this.hoverPicking)return;this.hoverPicking=!0;const{x:i,y:s}=this.pointer;t.pickAt(i,s).then(t=>{this.hoverPicking=!1;const n=this.pointer;if(!n||this.done||!this.host)return;if(n.x!==i||n.y!==s)return void this.pickHover({...e,x:n.x,y:n.y});const o=this.hover,h=o&&("vertex"===o.kind||"edge"===o.kind||"self"===o.kind);!t||h&&!this.behind(o.point,t.point)||(this.hover={point:t.point,kind:"none"},this.render())},()=>{this.hoverPicking=!1})}onPointerLeave(){this.hover=null,this.render()}onClick(e){if(0!==e.button)return!1;const t=this.host;if(!t)return!0;this.done&&(this.points=[],this.picked=[],this.clearance=null,this.done=!1);const i=this.locate(e),s="clearance"===this.options.mode||!1!==this.options.surface;return this.queue=this.queue.then(async()=>{const n=s?await t.pickAt(e.x,e.y):null;this.place(i,n)}),!0}onDoubleClick(){return"clearance"===this.options.mode||(this.queue=this.queue.then(()=>{const e=this.points.length;e>=2&&n(this.points[e-1],this.points[e-2])<1e-6&&this.points.pop(),this.finish()})),!0}onKeyDown(e){return"Escape"===e.key?(0!==this.points.length||0!==this.picked.length)&&(this.clear(),!0):"Enter"===e.key?(this.finish(),!0):("Backspace"===e.key||"Delete"===e.key)&&(0!==this.points.length&&!this.done&&(this.points.pop(),this.render(),!0))}place(e,t){const i=this.options.mode;if("clearance"===i){if(!t)return;if(this.picked.length>=2&&(this.picked=[],this.clearance=null,this.done=!1),1===this.picked.length&&this.picked[0].layer===t.layer&&this.picked[0].feature.id===t.id)return;return this.picked.push({layer:t.layer,feature:t.feature,point:t.point}),2===this.picked.length&&this.measureClearance(),void this.render()}let s=e?.point??null;const n=e&&("vertex"===e.kind||"edge"===e.kind||"self"===e.kind);!t||n&&!this.behind(e.point,t.point)||(s=t.point),s&&(this.points.push([...s]),"height"===i&&this.points.length>=2&&(this.done=!0),this.render())}behind(e,t){const i=this.host;if(!i||i.camera.orthographic)return!1;const{f:s,eye:n}=i.camera.basis(),o=e=>(e[0]-n[0])*s[0]+(e[1]-n[1])*s[1]+(e[2]-n[2])*s[2],h=o(t);return o(e)>h+Math.max(.3,.01*h)}finish(){const e="area"===this.options.mode?3:2;this.points.length>=e&&(this.done=!0),this.hover=null,this.render()}measureClearance(){const[e,t]=this.picked;if(!e.feature.geometry||!t.feature.geometry)return;const i=c(e.feature.geometry,t.feature.geometry,3);if(!Number.isFinite(i.distance))return;const s=this.options.radius?.(e.layer,e.feature)??0,n=this.options.radius?.(t.layer,t.feature)??0;this.clearance={a:i.pointA,b:i.pointB,gap:Math.max(0,i.distance-s-n)},this.done=!0}locate(e){const t=this.host;if(!t)return null;const i=this.options.z??t.camera.state.target[2],s=this.points[this.points.length-1]??null;if(this.snapper)return this.snapper.snap(e.x,e.y,e.shift,{z:i,from:s});const n=t.toGround(e.x,e.y,i);return n?{point:n,kind:"none"}:null}measurement(){const e=this.options.mode;if("clearance"===e){if(0===this.picked.length)return null;const[t,i]=this.picked;return{mode:e,points:this.clearance?[this.clearance.a,this.clearance.b]:[],clearance:this.clearance?.gap,a:t,b:i,done:this.done}}const t=!this.done&&this.hover?[...this.points,this.hover.point]:[...this.points];if(0===t.length)return null;const i=t[0],n=t[t.length-1],o={mode:e,points:t,done:this.done};if(o.length=h(t),o.horizontal=h(t,2),o.rise=n[2]-i[2],o.slope=p(i,n),"area"===e&&t.length>=3){const e={type:"Polygon",coordinates:[[...t,t[0]]]};o.area=s(e),o.perimeter=r(e)}return o}render(){const s=this.host;if(!s)return;const h=this.options.mode,r=this.measurement(),c={fills:[],lines:[],points:[]},d=[];if("clearance"===h)if(this.picked.forEach(e=>c.points.push({position:e.point,role:"vertex"})),this.clearance){const{a:e,b:i,gap:s}=this.clearance;c.lines.push({coordinates:[e,i],role:"measure"}),c.points.push({position:e,role:"active"},{position:i,role:"active"}),d.push({id:"gap",position:g(e,i),text:`${t(s)} clear`,kind:"measure",anchor:"left",offset:[14,-10]});const n=Math.abs(e[2]-i[2]);n>.005&&d.push({id:"dz",position:g(e,i),text:`${t(n)} apart in height`,kind:"info",anchor:"left",offset:[14,12]})}else 1===this.picked.length&&d.push({id:"hint",position:this.picked[0].point,text:"Now click the second",kind:"info",offset:[0,-22]});else if(r){const s=r.points;"area"===h&&s.length>=3&&c.fills.push({rings:[[...s,s[0]]],role:"fill"});const u=this.points;if(u.length>=2&&c.lines.push({coordinates:"area"===h&&this.done?[...u,u[0]]:u,role:"measure"}),!this.done&&this.hover&&u.length>=1&&(c.lines.push({coordinates:[u[u.length-1],this.hover.point],role:"rubber"}),"area"===h&&u.length>=2&&c.lines.push({coordinates:[this.hover.point,u[0]],role:"guide"})),u.forEach(e=>c.points.push({position:e,role:"vertex"})),!this.done&&this.hover&&c.points.push({position:this.hover.point,role:l(this.hover)}),"height"===h&&s.length>=2){const[e,h]=[s[0],s[1]],[r,a]=e[2]<=h[2]?[e,h]:[h,e],l=[r[0],r[1],a[2]];c.lines.push({coordinates:[r,l],role:"guide"},{coordinates:[l,a],role:"guide"}),d.push({id:"rise",position:g(r,l),text:`↕ ${t(Math.abs(h[2]-e[2]))}`,kind:"measure",offset:[34,0]}),d.push({id:"across",position:g(l,a),text:`↔ ${t(o(e,h))}`,kind:"segment"}),d.push({id:"slope",position:g(e,h),text:`${t(n(e,h))} · ${i(p(e,h))}`,kind:"info",offset:[0,20]})}else if("distance"===h||"area"===h){const i="area"===h&&s.length>=3?[[s[s.length-1],s[0]]]:[];if([...s.slice(1).map((e,t)=>[s[t],e]),...i].forEach(([e,i],s)=>{const o=n(e,i);o>0&&d.push({id:`s${s}`,position:g(e,i),text:t(o),kind:"segment"})}),"area"===h&&void 0!==r.area&&s.length>=3){const i=a({type:"Polygon",coordinates:[[...s,s[0]]]});i&&d.push({id:"area",position:i,text:`${e(r.area)} · ${t(r.perimeter??0)} round`,kind:"measure"})}else if("distance"===h&&s.length>=2){const e=r.rise??0,i=Math.abs(e)>.005?`${t(r.length??0)} · ${t(r.horizontal??0)} across · ${e>=0?"+":""}${t(e)}`:t(r.length??0);d.push({id:"total",position:s[s.length-1],text:i,kind:"measure",offset:[0,-24]})}}}this.sketch.set(c),s.labels?.set("measure",d),s.requestRepaint(),this.emit("change",r)}}function g(e,t){return[(e[0]+t[0])/2,(e[1]+t[1])/2,((e[2]??0)+(t[2]??0))/2]}
|
package/edit/Sketch.d.ts
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
import
|
|
1
|
+
import { ColorLike } from '../common/Colors';
|
|
2
2
|
import type { Position } from '../data/Geometry';
|
|
3
3
|
import { AreaLayer } from '../layers/AreaLayer';
|
|
4
4
|
import { LineLayer } from '../layers/LineLayer';
|
|
5
5
|
import { PointLayer } from '../layers/PointLayer';
|
|
6
|
+
import { ThemeTokens } from '../theme/Theme';
|
|
6
7
|
import type { ControllerHost } from './GeometryController';
|
|
7
8
|
/** The colours a sketch is drawn in. */
|
|
8
9
|
export interface SketchTheme {
|
|
@@ -22,6 +23,12 @@ export interface SketchTheme {
|
|
|
22
23
|
/** Construction lines: the rubber band's guides, a transform's box. */
|
|
23
24
|
guide: ColorLike;
|
|
24
25
|
}
|
|
26
|
+
/**
|
|
27
|
+
* A sketch's colours from the theme's tokens: what is drawn in the accent, handles in the text's
|
|
28
|
+
* colour, what was snapped to in the highlight's, a shape that cannot be in danger's.
|
|
29
|
+
*/
|
|
30
|
+
export declare function sketchTheme(tokens: ThemeTokens): SketchTheme;
|
|
31
|
+
/** A sketch's colours where its view has no theme: Protomaze's, dark. */
|
|
25
32
|
export declare const SKETCH_THEME: SketchTheme;
|
|
26
33
|
export type SketchLineRole = 'edge' | 'rubber' | 'guide' | 'invalid' | 'measure';
|
|
27
34
|
export type SketchPointRole = 'vertex' | 'mid' | 'active' | 'snap-vertex' | 'snap-edge' | 'snap-other' | 'center' | 'rotate' | 'scale' | 'point';
|
|
@@ -57,7 +64,17 @@ export declare class Sketch {
|
|
|
57
64
|
readonly points: PointLayer;
|
|
58
65
|
private host;
|
|
59
66
|
private last;
|
|
60
|
-
|
|
67
|
+
/** The colours the application chose: over the view's theme, which gives the rest. */
|
|
68
|
+
private readonly own;
|
|
69
|
+
private themed;
|
|
70
|
+
/**
|
|
71
|
+
* `theme` is what the sketch is drawn in where its host has no theme tokens; in a view that
|
|
72
|
+
* has them, the tokens' colours (`sketchTheme`) with `own` over them - by default whatever of
|
|
73
|
+
* `theme` is not `SKETCH_THEME` itself.
|
|
74
|
+
*/
|
|
75
|
+
constructor(theme?: SketchTheme, own?: Partial<SketchTheme>);
|
|
76
|
+
/** The colours drawn in now: the host's theme, the application's own over it; `theme` without one. */
|
|
77
|
+
private colors;
|
|
61
78
|
attach(host: ControllerHost): void;
|
|
62
79
|
private warming;
|
|
63
80
|
/**
|
package/edit/Sketch.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{parseColor as e}from"../common/Colors.js";import{AreaLayer as t}from"../layers/AreaLayer.js";import{LineLayer as s}from"../layers/LineLayer.js";import{PointLayer as i}from"../layers/PointLayer.js";import{PROTOMAZE_DARK as r}from"../theme/Theme.js";export function sketchTheme(t){const s=(t,s)=>{const[i,r,o]=e(t);return[i,r,o,s]};return{stroke:t.accent,fill:s(t.accent,.18),vertex:t.text,border:t.background,active:t.accent,snap:t.highlight,invalid:t.danger,guide:s(t.text,.67)}}export const SKETCH_THEME=sketchTheme(r);const o={vertex:{shape:"circle",size:11,color:"vertex"},point:{shape:"circle",size:13,color:"stroke"},mid:{shape:"circle",size:8,color:"vertex",opacity:.55},active:{shape:"circle",size:15,color:"active"},"snap-vertex":{shape:"ring",size:22,color:"snap"},"snap-edge":{shape:"diamond",size:15,color:"snap"},"snap-other":{shape:"cross",size:14,color:"snap"},center:{shape:"cross",size:14,color:"guide"},rotate:{shape:"circle",size:13,color:"active"},scale:{shape:"square",size:11,color:"vertex"}};export class Sketch{constructor(e=SKETCH_THEME,r){this.theme=e,this.host=null,this.last={fills:"",lines:"",points:""},this.themed=null,this.warming=!1,this.own=r??(e===SKETCH_THEME?{}:e),this.fills=new t({id:"sketch-fills",outlines:!1,pickable:!1,style:e=>{const t=this.colors();return{color:"invalid"===e.properties.role?l(t.invalid,.2):t.fill}}}),this.lines=new s({id:"sketch-lines",mode:"space",pickable:!1,style:e=>{const t=this.colors();switch(e.properties.role){case"rubber":return{color:t.stroke,width:2,dashed:!0,arrow:!1};case"guide":return{color:t.guide,width:1.25,dashed:!0,arrow:!1};case"invalid":return{color:t.invalid,width:2.5,arrow:!1};case"measure":return{color:t.stroke,width:2.25,arrow:!1};default:return{color:t.stroke,width:2.5,arrow:!1}}}}),this.points=new i({id:"sketch-points",pickable:!1,depthTest:!1,border:1.5,style:e=>{const t=o[e.properties.role]??o.vertex;return{shape:t.shape,size:t.size,color:this.colors()[t.color],opacity:t.opacity}}})}colors(){const e=this.host?.tokens;return e?(this.themed?.tokens!==e&&(this.themed={tokens:e,theme:{...sketchTheme(e),...this.own}}),this.themed.theme):this.theme}attach(e){this.host!==e&&(this.detach(),this.host=e,e.addOverlay(this.fills),e.addOverlay(this.lines),e.addOverlay(this.points),this.warm(e))}warm(e){if(this.points.primitive)return;const t=e.camera.state.target,s=[t[0],t[1],t[2]],i=[t[0]+.01,t[1],t[2]],r=[t[0],t[1]+.01,t[2]];this.set({fills:[{rings:[[s,i,r,s]],role:"fill"}],lines:[{coordinates:[s,i],role:"edge"}],points:[{position:s,role:"vertex"}]}),this.warming=!0,[this.fills,this.lines,this.points].forEach(e=>e.setOpacity(0));const o=this.points.on("build",()=>{o(),[this.fills,this.lines,this.points].forEach(e=>e.setOpacity(1)),this.warming&&this.clear(),this.warming=!1})}detach(){const e=this.host;e&&(e.removeOverlay(this.fills),e.removeOverlay(this.lines),e.removeOverlay(this.points),this.host=null)}set(e){this.warming=!1,[this.fills,this.lines,this.points].forEach(e=>e.setOpacity(1));const t=(e.fills??[]).filter(e=>e.rings.length>0&&e.rings[0].length>=3).map((e,t)=>({id:`fill-${t}`,geometry:{type:"Polygon",coordinates:e.rings},properties:{role:e.role}})),s=(e.lines??[]).filter(e=>e.coordinates.length>=2).map((e,t)=>({id:`line-${t}`,geometry:{type:"LineString",coordinates:e.coordinates},properties:{role:e.role}})),i=(e.points??[]).map((e,t)=>({id:`point-${t}`,geometry:{type:"Point",coordinates:e.position},properties:{role:e.role}}));this.update(this.fills,t,"fills"),this.update(this.lines,s,"lines"),this.update(this.points,i,"points")}clear(){this.set({})}update(e,t,s){const i=JSON.stringify(t.map(e=>[e.geometry,e.properties.role]));i!==this.last[s]&&(this.last[s]=i,e.setFeatures(t))}}function l(t,s){const[i,r,o,l]=e(t);return[i,r,o,l*s]}
|
|
@@ -39,7 +39,7 @@ export interface FrameInput {
|
|
|
39
39
|
* in, in doubles, so float32 vertices relative to it keep millimetres.
|
|
40
40
|
*/
|
|
41
41
|
viewProjection: ArrayLike<number>;
|
|
42
|
-
/** Whether clip z runs -1..1 (OpenGL's,
|
|
42
|
+
/** Whether clip z runs -1..1 (OpenGL's, as many hosts' cameras have it) rather than the backend's own. */
|
|
43
43
|
glDepth: boolean;
|
|
44
44
|
near: number;
|
|
45
45
|
pixelRatio: number;
|
|
@@ -59,8 +59,8 @@ export interface FrameInput {
|
|
|
59
59
|
* the heatmap and the GPU pick.
|
|
60
60
|
*
|
|
61
61
|
* Two kinds of engine extend it: `CanvasGeometryEngine` draws on a canvas of its own, under a
|
|
62
|
-
* camera of its own; `HostedGeometryEngine` draws into a frame someone else draws -
|
|
63
|
-
* on its WebGPU device - under that one's camera. The primitives cannot tell the two apart.
|
|
62
|
+
* camera of its own; `HostedGeometryEngine` draws into a frame someone else draws - a map's, a
|
|
63
|
+
* globe's, on its WebGPU device - under that one's camera. The primitives cannot tell the two apart.
|
|
64
64
|
*/
|
|
65
65
|
export declare abstract class GeometryEngine extends TypedEventEmitter<GeometryEngineEvents> {
|
|
66
66
|
readonly scene: Scene;
|
|
@@ -166,6 +166,25 @@ export declare abstract class GeometryEngine extends TypedEventEmitter<GeometryE
|
|
|
166
166
|
onBeforeDraw(callback: (width: number, height: number) => void): () => void;
|
|
167
167
|
/** Asks for a new frame, for a change only this engine's content knows about. */
|
|
168
168
|
abstract requestRepaint(): void;
|
|
169
|
+
/** What animates now - a camera flight, flow along the lines - and keeps frames coming. */
|
|
170
|
+
protected readonly animators: Set<string>;
|
|
171
|
+
/** Keeps frames coming while `key` animates something. */
|
|
172
|
+
setAnimating(key: string, animating: boolean): void;
|
|
173
|
+
/**
|
|
174
|
+
* The view's size in view (CSS) pixels, and frame pixels per view pixel: the last frame's,
|
|
175
|
+
* for an engine that draws into someone else's frame.
|
|
176
|
+
*/
|
|
177
|
+
get viewSize(): {
|
|
178
|
+
width: number;
|
|
179
|
+
height: number;
|
|
180
|
+
pixelRatio: number;
|
|
181
|
+
};
|
|
182
|
+
/**
|
|
183
|
+
* Where a world position was on the last frame drawn, in view pixels from its top-left; null
|
|
184
|
+
* behind the camera, or before the first frame. The frame's own camera, whoever made it: what
|
|
185
|
+
* a view puts its labels by when the host moves the camera.
|
|
186
|
+
*/
|
|
187
|
+
toView(p: readonly number[]): [number, number] | null;
|
|
169
188
|
/** Puts a primitive's meshes into the scenes of their passes; it is handed every frame. */
|
|
170
189
|
attach(primitive: GeometryPrimitive): void;
|
|
171
190
|
/** Takes a primitive's meshes out of the scenes; it is not disposed. */
|
package/engine/GeometryEngine.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{AddEquation as e,Camera as t,Color as r,CustomBlending as s,DepthTexture as i,FloatType as n,LinearSRGBColorSpace as a,Matrix4 as o,NearestFilter as h,NoToneMapping as c,OneFactor as d,PostProcessing as l,RenderTarget as p,Scene as u,Vector2 as m,Vector3 as f,WebGPUCoordinateSystem as g,ZeroFactor as y}from"three/webgpu";import{pass as w,uniform as b}from"three/tsl";import{bloom as T}from"three/examples/jsm/tsl/display/BloomNode.js";import{TypedEventEmitter as x}from"../event/TypedEventEmitter.js";import{DensityMap as P}from"../three/DensityMap.js";import{Halo as k}from"../three/Halo.js";import{pickPassUniforms as R}from"./GeometryFrame.js";export class HostCamera extends t{updateProjectionMatrix(){}}export class GeometryEngine extends x{constructor(){super(),this.scene=new u,this.underlayScene=new u,this.bloomScene=new u,this.pickScene=new u,this.pickPass=R(),this.density=new P,this.halo=new k,this.camera=new HostCamera,this.lastRenderMs=0,this.frame={pxPerWorld:1,pixelRatio:1,near:.3,geocentric:!1,depth:!1,focal:1e3,orthographic:!0,width:1,height:1,eye:new f,time:0},this.bloom=null,this.renderer=null,this.ready=!1,this.disposed=!1,this.depthWanted=!1,this.bloomPost=null,this.bloomTarget=null,this.origins=new Map,this.drawn=new m,this.beforeRender=new Set,this.beforeDraw=new Set,this.pickSources=new Map,this.nextPickSource=1,this.pending=[],this.attached=new Map,this.unready=new Map,this.compiled=new WeakSet,this.compiling=new Set,this.startTime=performance.now(),this.drawnCamera=new o,this.pickTarget=new p(7,7,{type:n,depthBuffer:!0,generateMipmaps:!1,minFilter:h,magFilter:h}),this.depthUniforms={enabled:b(0),near:b(.3)},this.clearColor=new r,this.camera.matrixAutoUpdate=!1,this.camera.matrixWorldAutoUpdate=!1,this.scene.add(this.density.quad),this.underlayScene.add(this.halo.quad),this.depth=this.createDepthTexture(),this.sceneDepth={texture:this.depth,enabled:this.depthUniforms.enabled,near:this.depthUniforms.near}}createDepthTexture(){const e=new i(1,1,n);return e.minFilter=h,e.magFilter=h,e}getRenderer(){return this.renderer}get webgpu(){return this.renderer?.coordinateSystem===g}originKey(){return"world"}setOrigin(e,t,r=0){this.origins.set(this.originKey(),[e,t,r])}getOrigin(){return this.origins.get(this.originKey())??null}originFor(e){let t=this.getOrigin();return t||(this.setOrigin(e[0],e[1],e[2]??0),t=this.getOrigin()),t}depthTexture(){return this.depthWanted=!0,this.depth}onBeforeRender(e){return this.beforeRender.add(e),()=>{this.beforeRender.delete(e)}}onBeforeDraw(e){return this.beforeDraw.add(e),()=>{this.beforeDraw.delete(e)}}attach(e){if(this.attached.has(e))return;const t=[],r=e.passes();Object.keys(r).forEach(e=>{for(const s of r[e]??[])s&&(this.sceneOf(e).add(s),t.push({mesh:s,pass:e}),this.compiled.has(s)||this.unready.set(s,e))}),this.attached.set(e,{primitive:e,meshes:t}),e.setFrame(this.frame),this.requestRepaint()}detach(e){const t=this.attached.get(e);t&&(t.meshes.forEach(({mesh:e,pass:t})=>{this.sceneOf(t).remove(e),this.unready.delete(e)}),this.attached.delete(e),this.requestRepaint())}sceneOf(e){switch(e){case"scene":return this.scene;case"underlay":return this.underlayScene;case"bloom":return this.bloomScene;case"pick":return this.pickScene;case"density":return this.density.scene;case"halo":return this.halo.scene}}renderToTarget(e,t){const r=this.renderer;if(!r||!this.ready)return!1;const s=r.getRenderTarget();return r.setRenderTarget(t),this.clearToZero(r),r.render(e,this.camera),r.setRenderTarget(s),!0}clearToZero(e){e.getClearColor(this.clearColor);const t=e.getClearAlpha();e.setClearColor(0,0),e.clear(!0,!0,!0),e.setClearColor(this.clearColor,t)}addPickSource(e){const t=this.nextPickSource++;return this.pickSources.set(t,e),{id:t,remove:()=>{this.pickSources.delete(t)}}}pick(e,t){return new Promise(r=>{const s={x:e,y:t,resolve:r},i=setTimeout(()=>{this.pending=this.pending.filter(e=>e!==s),r(null)},1e3);s.resolve=e=>{clearTimeout(i),r(e)},this.ready&&this.renderer&&this.drawn.x>0?this.runPick(s,this.drawn.x,this.drawn.y):(this.pending.push(s),this.requestRepaint())})}dispose(){this.disposed=!0,this.missPicks(),[...this.attached.keys()].forEach(e=>this.detach(e)),this.pickTarget.dispose(),this.density.dispose(),this.halo.dispose(),this.depth.dispose();try{this.bloomPost?.dispose()}catch{}this.bloomPost=null;try{this.renderer?.dispose()}catch{}this.renderer=null,this.ready=!1}adoptRenderer(e){try{this.bloomPost?.dispose()}catch{}this.bloomPost=null,this.renderer=e,this.ready=!1,e.outputColorSpace=a,e.toneMapping=c,e.autoClear=!0,e.autoClearColor=!1,e.autoClearStencil=!1,this.createBloom(e)}createBloom(t){const r=w(this.bloomScene,this.camera);this.bloomTarget=r;const i=T(r,1.2,.5,0);this.bloom=i;const n=new(function(){const e=Object.getPrototypeOf(l);return"function"==typeof e&&e!==Function.prototype&&"function"==typeof e.prototype?.render?e:l}())(t,i);n.outputColorTransform=!1;const a=n._quadMesh.material;a.transparent=!0,a.blending=s,a.blendSrc=d,a.blendDst=d,a.blendEquation=e,a.blendSrcAlpha=y,a.blendDstAlpha=d,a.depthTest=!1,a.depthWrite=!1,this.bloomPost=n}updateCamera(e){const t=e.viewProjection,r=this.frame,{width:s,height:i}=e;r.width=s,r.height=i,r.pixelRatio=e.pixelRatio,r.near=e.near,r.geocentric=!!e.geocentric,r.pxPerWorld=e.pxPerWorld??Math.hypot(t[0]*s/2,t[4]*i/2);const n=e.orthographic??Math.abs(t[12])+Math.abs(t[13])+Math.abs(t[14])<1e-12;r.orthographic=n,r.focal=e.focal??(n?r.pxPerWorld:Math.hypot(t[0],t[1],t[2])*s/2),r.depth=this.depthWanted&&this.depthReady(),r.time=(performance.now()-this.startTime)/1e3,this.depthUniforms.near.value=e.near,this.depthUniforms.enabled.value=r.depth?1:0;const[a,o,h]=this.getOrigin()??[0,0,0];e.eye&&r.eye.set(e.eye[0]-a,e.eye[1]-o,(e.eye[2]??0)-h);const c=this.camera.projectionMatrix.elements;for(let e=0;e<4;e++)c[e]=t[4*e],c[4+e]=t[4*e+1],c[8+e]=t[4*e+2],c[12+e]=t[4*e]*a+t[4*e+1]*o+t[4*e+2]*h+t[4*e+3];if(e.glDepth&&this.webgpu)for(let e=0;e<4;e++)c[4*e+2]=.5*c[4*e+2]+.5*c[4*e+3];this.camera.projectionMatrixInverse.copy(this.camera.projectionMatrix).invert()}depthReady(){return!0}renderFrame(e,t){const r=this.renderer;if(this.lastRenderMs=0,!this.ready||!r)return!1;const s=performance.now();r._nodes?.nodeFrame?.update?.(),this.updateCamera(e),this.attached.forEach(({primitive:e})=>e.setFrame(this.frame)),this.beforeRender.forEach(e=>e(this.frame)),this.warmUp(r);const i=this.holdBack();try{return this.drawFrame(r,e,s,t)}finally{i.forEach(e=>{e.visible=!0})}}drawFrame(e,t,r,s){this.density.update();const i=e=>e.children.some(e=>e.visible);if(!i(this.scene)&&!i(this.underlayScene))return this.missPicks(),this.lastRenderMs=performance.now()-r,!1;if(s&&!s())return!1;this.beforeDraw.forEach(e=>e(t.width,t.height));const n=(e,t)=>{this.renderToTarget(e,t)};if(this.halo.draw(t.width,t.height,n),this.density.draw(t.width,t.height,n),this.drawn.set(t.width,t.height),this.drawnCamera.copy(this.camera.projectionMatrix),this.pending.length>0&&this.runPick(this.pending.shift(),t.width,t.height),i(this.underlayScene)&&e.render(this.underlayScene,this.camera),e.render(this.scene,this.camera),this.bloomPost&&i(this.bloomScene)){const t=this.bloomTarget?.renderTarget;if(t){const r=e.getRenderTarget();e.setRenderTarget(t),this.clearToZero(e),e.setRenderTarget(r)}this.bloomPost.render()}return this.lastRenderMs=performance.now()-r,this.emit("frame",{ms:this.lastRenderMs,width:t.width,height:t.height}),!0}warmUp(e){if(0===this.unready.size)return;if("function"!=typeof e.compileAsync)return void this.unready.clear();const t=[...this.unready].filter(([e])=>e.visible&&!this.compiling.has(e));0!==t.length&&(t.forEach(([e])=>this.compiling.add(e)),this.compile(e,t).catch(e=>console.warn("[geometry] Compiling in the background failed; drawn as it comes",e)).finally(()=>{t.forEach(([e])=>{this.compiling.delete(e),this.unready.delete(e),this.compiled.add(e)}),this.requestRepaint()}))}get compilingShaders(){return this.compiling.size>0}async compile(e,t){const r=[];for(const[s,i]of t){await M();const t=this.sceneOf(i);if(!this.renderer||!this.unready.has(s)||s.parent!==t)continue;const n=e.getRenderTarget();try{e.setRenderTarget(this.targetOf(i)),r.push(e.compileAsync(s,this.camera,t))}finally{e.setRenderTarget(n)}}await Promise.all(r)}targetOf(e){switch(e){case"scene":case"underlay":return null;case"bloom":return this.bloomTarget?.renderTarget??null;case"pick":return this.pickTarget;case"density":return this.density.target;case"halo":return this.halo.target}}holdBack(){const e=[];return this.unready.forEach((t,r)=>{r.visible&&(r.visible=!1,e.push(r))}),e}missPicks(){this.drawn.set(0,0);const e=this.pending;this.pending=[],e.forEach(e=>e.resolve(null))}runPick(e,t,r){this.pending.length>0&&this.requestRepaint();const s=Math.floor(e.x*this.frame.pixelRatio),i=Math.floor(e.y*this.frame.pixelRatio),n=(s+.5)/t*2-1,a=1-(i+.5)/r*2,o=t/7,h=r/7;this.pickPass.window.value.set(o,0,0,-n*o,0,h,0,-a*h,0,0,1,0,0,0,0,1),this.pickPass.origin.value.set(s-3,i-3),this.pickPass.frameSize.value.set(t,r);const c=this.drawnCamera.clone(),d=this.getOrigin()??[0,0,0];this.renderToTarget(this.pickScene,this.pickTarget)?this.readPick(s,i,t,r,c,d).then(e.resolve,t=>{console.warn("[geometry] Pick failed",t),e.resolve(null)}):e.resolve(null)}async readTexels(){const e=this.renderer;if(!e)return null;const t=e.backend,r=t?.device,s=t?.get?.(this.pickTarget.texture)?.texture;if(this.webgpu&&r&&s){const{GPUBufferUsage:e,GPUMapMode:t}=globalThis,i=256,n=r.createBuffer({size:7*i,usage:e.COPY_DST|e.MAP_READ}),a=r.createCommandEncoder();a.copyTextureToBuffer({texture:s},{buffer:n,bytesPerRow:i},[7,7]),r.queue.submit([a.finish()]);try{return await n.mapAsync(t.READ),{data:new Float32Array(n.getMappedRange().slice(0)),stride:i/4,bottomUp:!1}}finally{n.destroy()}}const i=await e.readRenderTargetPixelsAsync(this.pickTarget,0,0,7,7);return{data:new Float32Array(i.buffer,i.byteOffset,i.byteLength/4),stride:28,bottomUp:!0}}async readPick(e,t,r,s,i,n){const a=await this.readTexels();if(!a)return null;const{data:o,stride:h,bottomUp:c}=a,d=[];for(let r=0;r<7;r++)for(let s=0;s<7;s++){const i=r*h+4*s,n=Math.round(o[i]);if(n<=0)continue;const a=s-3,l=c?3-r:r-3;d.push({source:n,index:Math.round(o[i+1]),w:o[i+2],x:e+a,y:t+l,d:a*a+l*l})}d.sort((e,t)=>e.d-t.d||e.w-t.w);for(const e of d){const t=this.pickSources.get(e.source)?.(e.index);if(null==t)continue;const a=unproject(i,(e.x+.5)/r*2-1,1-(e.y+.5)/s*2,e.w,-n[2]);return{hit:t,point:[a[0]+n[0],a[1]+n[1],a[2]+n[2]],source:e.source,index:e.index,distance:e.w}}return null}}export function unproject(e,t,r,s,i=0){const n=e.elements,a=e=>[n[e],n[4+e],n[8+e],n[12+e]],[o,h,c]=[a(0),a(1),a(3)];if(Math.abs(c[0])+Math.abs(c[1])+Math.abs(c[2])<1e-12){const[e,s,n,a]=[o[0],o[1],h[0],h[1]],[d,l]=[t*c[3]-o[3]-o[2]*i,r*c[3]-h[3]-h[2]*i],p=e*a-s*n;return[(d*a-s*l)/p,(e*l-d*n)/p,i]}const d=[[0,1,2].map(e=>o[e]-t*c[e]),[0,1,2].map(e=>h[e]-r*c[e]),[c[0],c[1],c[2]]],l=[t*c[3]-o[3],r*c[3]-h[3],s-c[3]],p=e=>e[0][0]*(e[1][1]*e[2][2]-e[1][2]*e[2][1])-e[0][1]*(e[1][0]*e[2][2]-e[1][2]*e[2][0])+e[0][2]*(e[1][0]*e[2][1]-e[1][1]*e[2][0]),u=p(d),m=[0,1,2].map(e=>p(d.map((t,r)=>t.map((t,s)=>s===e?l[r]:t)))/u);return[m[0],m[1],m[2]]}function M(){const e=globalThis.scheduler;return"function"==typeof e?.yield?e.yield():new Promise(e=>setTimeout(e,0))}
|
|
1
|
+
import{AddEquation as e,Camera as t,Color as r,CustomBlending as i,DepthTexture as s,FloatType as n,LinearSRGBColorSpace as a,Matrix4 as o,NearestFilter as h,NoToneMapping as c,OneFactor as d,PostProcessing as l,RenderTarget as p,Scene as u,Vector2 as m,Vector3 as f,WebGPUCoordinateSystem as g,ZeroFactor as y}from"three/webgpu";import{pass as w,uniform as b}from"three/tsl";import{bloom as x}from"three/examples/jsm/tsl/display/BloomNode.js";import{TypedEventEmitter as T}from"../event/TypedEventEmitter.js";import{DensityMap as R}from"../three/DensityMap.js";import{Halo as P}from"../three/Halo.js";import{pickPassUniforms as k}from"./GeometryFrame.js";export class HostCamera extends t{updateProjectionMatrix(){}}export class GeometryEngine extends T{constructor(){super(),this.scene=new u,this.underlayScene=new u,this.bloomScene=new u,this.pickScene=new u,this.pickPass=k(),this.density=new R,this.halo=new P,this.camera=new HostCamera,this.lastRenderMs=0,this.frame={pxPerWorld:1,pixelRatio:1,near:.3,geocentric:!1,depth:!1,focal:1e3,orthographic:!0,width:1,height:1,eye:new f,time:0},this.bloom=null,this.renderer=null,this.ready=!1,this.disposed=!1,this.depthWanted=!1,this.bloomPost=null,this.bloomTarget=null,this.origins=new Map,this.drawn=new m,this.beforeRender=new Set,this.beforeDraw=new Set,this.pickSources=new Map,this.nextPickSource=1,this.pending=[],this.attached=new Map,this.unready=new Map,this.compiled=new WeakSet,this.compiling=new Set,this.startTime=performance.now(),this.drawnCamera=new o,this.pickTarget=new p(7,7,{type:n,depthBuffer:!0,generateMipmaps:!1,minFilter:h,magFilter:h}),this.depthUniforms={enabled:b(0),near:b(.3)},this.animators=new Set,this.clearColor=new r,this.camera.matrixAutoUpdate=!1,this.camera.matrixWorldAutoUpdate=!1,this.scene.add(this.density.quad),this.underlayScene.add(this.halo.quad),this.depth=this.createDepthTexture(),this.sceneDepth={texture:this.depth,enabled:this.depthUniforms.enabled,near:this.depthUniforms.near}}createDepthTexture(){const e=new s(1,1,n);return e.minFilter=h,e.magFilter=h,e}getRenderer(){return this.renderer}get webgpu(){return this.renderer?.coordinateSystem===g}originKey(){return"world"}setOrigin(e,t,r=0){this.origins.set(this.originKey(),[e,t,r])}getOrigin(){return this.origins.get(this.originKey())??null}originFor(e){let t=this.getOrigin();return t||(this.setOrigin(e[0],e[1],e[2]??0),t=this.getOrigin()),t}depthTexture(){return this.depthWanted=!0,this.depth}onBeforeRender(e){return this.beforeRender.add(e),()=>{this.beforeRender.delete(e)}}onBeforeDraw(e){return this.beforeDraw.add(e),()=>{this.beforeDraw.delete(e)}}setAnimating(e,t){t?this.animators.add(e):this.animators.delete(e),t&&this.requestRepaint()}get viewSize(){const e=this.frame.pixelRatio||1;return{width:this.drawn.x/e,height:this.drawn.y/e,pixelRatio:e}}toView(e){const t=this.drawn.x,r=this.drawn.y;if(t<=0||r<=0)return null;const[i,s,n]=this.getOrigin()??[0,0,0],a=e[0]-i,o=e[1]-s,h=(e[2]??0)-n,c=this.drawnCamera.elements,d=c[0]*a+c[4]*o+c[8]*h+c[12],l=c[1]*a+c[5]*o+c[9]*h+c[13],p=c[3]*a+c[7]*o+c[11]*h+c[15];if(p<=1e-9)return null;const u=this.frame.pixelRatio||1;return[(d/p+1)/2*t/u,(1-l/p)/2*r/u]}attach(e){if(this.attached.has(e))return;const t=[],r=e.passes();Object.keys(r).forEach(e=>{for(const i of r[e]??[])i&&(this.sceneOf(e).add(i),t.push({mesh:i,pass:e}),this.compiled.has(i)||this.unready.set(i,e))}),this.attached.set(e,{primitive:e,meshes:t}),e.setFrame(this.frame),this.requestRepaint()}detach(e){const t=this.attached.get(e);t&&(t.meshes.forEach(({mesh:e,pass:t})=>{this.sceneOf(t).remove(e),this.unready.delete(e)}),this.attached.delete(e),this.requestRepaint())}sceneOf(e){switch(e){case"scene":return this.scene;case"underlay":return this.underlayScene;case"bloom":return this.bloomScene;case"pick":return this.pickScene;case"density":return this.density.scene;case"halo":return this.halo.scene}}renderToTarget(e,t){const r=this.renderer;if(!r||!this.ready)return!1;const i=r.getRenderTarget();return r.setRenderTarget(t),this.clearToZero(r),r.render(e,this.camera),r.setRenderTarget(i),!0}clearToZero(e){e.getClearColor(this.clearColor);const t=e.getClearAlpha();e.setClearColor(0,0),e.clear(!0,!0,!0),e.setClearColor(this.clearColor,t)}addPickSource(e){const t=this.nextPickSource++;return this.pickSources.set(t,e),{id:t,remove:()=>{this.pickSources.delete(t)}}}pick(e,t){return new Promise(r=>{const i={x:e,y:t,resolve:r},s=setTimeout(()=>{this.pending=this.pending.filter(e=>e!==i),r(null)},1e3);i.resolve=e=>{clearTimeout(s),r(e)},this.ready&&this.renderer&&this.drawn.x>0?this.runPick(i,this.drawn.x,this.drawn.y):(this.pending.push(i),this.requestRepaint())})}dispose(){this.disposed=!0,this.missPicks(),[...this.attached.keys()].forEach(e=>this.detach(e)),this.pickTarget.dispose(),this.density.dispose(),this.halo.dispose(),this.depth.dispose();try{this.bloomPost?.dispose()}catch{}this.bloomPost=null;try{this.renderer?.dispose()}catch{}this.renderer=null,this.ready=!1}adoptRenderer(e){try{this.bloomPost?.dispose()}catch{}this.bloomPost=null,this.renderer=e,this.ready=!1,e.outputColorSpace=a,e.toneMapping=c,e.autoClear=!0,e.autoClearColor=!1,e.autoClearStencil=!1,this.createBloom(e)}createBloom(t){const r=w(this.bloomScene,this.camera);this.bloomTarget=r;const s=x(r,1.2,.5,0);this.bloom=s;const n=new(function(){const e=Object.getPrototypeOf(l);return"function"==typeof e&&e!==Function.prototype&&"function"==typeof e.prototype?.render?e:l}())(t,s);n.outputColorTransform=!1;const a=n._quadMesh.material;a.transparent=!0,a.blending=i,a.blendSrc=d,a.blendDst=d,a.blendEquation=e,a.blendSrcAlpha=y,a.blendDstAlpha=d,a.depthTest=!1,a.depthWrite=!1,this.bloomPost=n}updateCamera(e){const t=e.viewProjection,r=this.frame,{width:i,height:s}=e;r.width=i,r.height=s,r.pixelRatio=e.pixelRatio,r.near=e.near,r.geocentric=!!e.geocentric,r.pxPerWorld=e.pxPerWorld??Math.hypot(t[0]*i/2,t[4]*s/2);const n=e.orthographic??Math.abs(t[12])+Math.abs(t[13])+Math.abs(t[14])<1e-12;r.orthographic=n,r.focal=e.focal??(n?r.pxPerWorld:Math.hypot(t[0],t[1],t[2])*i/2),r.depth=this.depthWanted&&this.depthReady(),r.time=(performance.now()-this.startTime)/1e3,this.depthUniforms.near.value=e.near,this.depthUniforms.enabled.value=r.depth?1:0;const[a,o,h]=this.getOrigin()??[0,0,0];e.eye&&r.eye.set(e.eye[0]-a,e.eye[1]-o,(e.eye[2]??0)-h);const c=this.camera.projectionMatrix.elements;for(let e=0;e<4;e++)c[e]=t[4*e],c[4+e]=t[4*e+1],c[8+e]=t[4*e+2],c[12+e]=t[4*e]*a+t[4*e+1]*o+t[4*e+2]*h+t[4*e+3];if(e.glDepth&&this.webgpu)for(let e=0;e<4;e++)c[4*e+2]=.5*c[4*e+2]+.5*c[4*e+3];this.camera.projectionMatrixInverse.copy(this.camera.projectionMatrix).invert()}depthReady(){return!0}renderFrame(e,t){const r=this.renderer;if(this.lastRenderMs=0,!this.ready||!r)return!1;const i=performance.now();r._nodes?.nodeFrame?.update?.(),this.updateCamera(e),this.attached.forEach(({primitive:e})=>e.setFrame(this.frame)),this.beforeRender.forEach(e=>e(this.frame)),this.warmUp(r);const s=this.holdBack();try{return this.drawFrame(r,e,i,t)}finally{s.forEach(e=>{e.visible=!0})}}drawFrame(e,t,r,i){this.density.update();const s=e=>e.children.some(e=>e.visible);if(!s(this.scene)&&!s(this.underlayScene))return this.missPicks(),this.lastRenderMs=performance.now()-r,!1;if(i&&!i())return!1;this.beforeDraw.forEach(e=>e(t.width,t.height));const n=(e,t)=>{this.renderToTarget(e,t)};if(this.halo.draw(t.width,t.height,n),this.density.draw(t.width,t.height,n),this.drawn.set(t.width,t.height),this.drawnCamera.copy(this.camera.projectionMatrix),this.pending.length>0&&this.runPick(this.pending.shift(),t.width,t.height),s(this.underlayScene)&&e.render(this.underlayScene,this.camera),e.render(this.scene,this.camera),this.bloomPost&&s(this.bloomScene)){const t=this.bloomTarget?.renderTarget;if(t){const r=e.getRenderTarget();e.setRenderTarget(t),this.clearToZero(e),e.setRenderTarget(r)}this.bloomPost.render()}return this.lastRenderMs=performance.now()-r,this.emit("frame",{ms:this.lastRenderMs,width:t.width,height:t.height}),!0}warmUp(e){if(0===this.unready.size)return;if("function"!=typeof e.compileAsync)return void this.unready.clear();const t=[...this.unready].filter(([e])=>e.visible&&!this.compiling.has(e));0!==t.length&&(t.forEach(([e])=>this.compiling.add(e)),this.compile(e,t).catch(e=>console.warn("[geometry] Compiling in the background failed; drawn as it comes",e)).finally(()=>{t.forEach(([e])=>{this.compiling.delete(e),this.unready.delete(e),this.compiled.add(e)}),this.requestRepaint()}))}get compilingShaders(){return this.compiling.size>0}async compile(e,t){const r=[];for(const[i,s]of t){await M();const t=this.sceneOf(s);if(!this.renderer||!this.unready.has(i)||i.parent!==t)continue;const n=e.getRenderTarget();try{e.setRenderTarget(this.targetOf(s)),r.push(e.compileAsync(i,this.camera,t))}finally{e.setRenderTarget(n)}}await Promise.all(r)}targetOf(e){switch(e){case"scene":case"underlay":return null;case"bloom":return this.bloomTarget?.renderTarget??null;case"pick":return this.pickTarget;case"density":return this.density.target;case"halo":return this.halo.target}}holdBack(){const e=[];return this.unready.forEach((t,r)=>{r.visible&&(r.visible=!1,e.push(r))}),e}missPicks(){this.drawn.set(0,0);const e=this.pending;this.pending=[],e.forEach(e=>e.resolve(null))}runPick(e,t,r){this.pending.length>0&&this.requestRepaint();const i=Math.floor(e.x*this.frame.pixelRatio),s=Math.floor(e.y*this.frame.pixelRatio),n=(i+.5)/t*2-1,a=1-(s+.5)/r*2,o=t/7,h=r/7;this.pickPass.window.value.set(o,0,0,-n*o,0,h,0,-a*h,0,0,1,0,0,0,0,1),this.pickPass.origin.value.set(i-3,s-3),this.pickPass.frameSize.value.set(t,r);const c=this.drawnCamera.clone(),d=this.getOrigin()??[0,0,0];this.renderToTarget(this.pickScene,this.pickTarget)?this.readPick(i,s,t,r,c,d).then(e.resolve,t=>{console.warn("[geometry] Pick failed",t),e.resolve(null)}):e.resolve(null)}async readTexels(){const e=this.renderer;if(!e)return null;const t=e.backend,r=t?.device,i=t?.get?.(this.pickTarget.texture)?.texture;if(this.webgpu&&r&&i){const{GPUBufferUsage:e,GPUMapMode:t}=globalThis,s=256,n=r.createBuffer({size:7*s,usage:e.COPY_DST|e.MAP_READ}),a=r.createCommandEncoder();a.copyTextureToBuffer({texture:i},{buffer:n,bytesPerRow:s},[7,7]),r.queue.submit([a.finish()]);try{return await n.mapAsync(t.READ),{data:new Float32Array(n.getMappedRange().slice(0)),stride:s/4,bottomUp:!1}}finally{n.destroy()}}const s=await e.readRenderTargetPixelsAsync(this.pickTarget,0,0,7,7);return{data:new Float32Array(s.buffer,s.byteOffset,s.byteLength/4),stride:28,bottomUp:!0}}async readPick(e,t,r,i,s,n){const a=await this.readTexels();if(!a)return null;const{data:o,stride:h,bottomUp:c}=a,d=[];for(let r=0;r<7;r++)for(let i=0;i<7;i++){const s=r*h+4*i,n=Math.round(o[s]);if(n<=0)continue;const a=i-3,l=c?3-r:r-3;d.push({source:n,index:Math.round(o[s+1]),w:o[s+2],x:e+a,y:t+l,d:a*a+l*l})}d.sort((e,t)=>e.d-t.d||e.w-t.w);for(const e of d){const t=this.pickSources.get(e.source)?.(e.index);if(null==t)continue;const a=unproject(s,(e.x+.5)/r*2-1,1-(e.y+.5)/i*2,e.w,-n[2]);return{hit:t,point:[a[0]+n[0],a[1]+n[1],a[2]+n[2]],source:e.source,index:e.index,distance:e.w}}return null}}export function unproject(e,t,r,i,s=0){const n=e.elements,a=e=>[n[e],n[4+e],n[8+e],n[12+e]],[o,h,c]=[a(0),a(1),a(3)];if(Math.abs(c[0])+Math.abs(c[1])+Math.abs(c[2])<1e-12){const[e,i,n,a]=[o[0],o[1],h[0],h[1]],[d,l]=[t*c[3]-o[3]-o[2]*s,r*c[3]-h[3]-h[2]*s],p=e*a-i*n;return[(d*a-i*l)/p,(e*l-d*n)/p,s]}const d=[[0,1,2].map(e=>o[e]-t*c[e]),[0,1,2].map(e=>h[e]-r*c[e]),[c[0],c[1],c[2]]],l=[t*c[3]-o[3],r*c[3]-h[3],i-c[3]],p=e=>e[0][0]*(e[1][1]*e[2][2]-e[1][2]*e[2][1])-e[0][1]*(e[1][0]*e[2][2]-e[1][2]*e[2][0])+e[0][2]*(e[1][0]*e[2][1]-e[1][1]*e[2][0]),u=p(d),m=[0,1,2].map(e=>p(d.map((t,r)=>t.map((t,i)=>i===e?l[r]:t)))/u);return[m[0],m[1],m[2]]}function M(){const e=globalThis.scheduler;return"function"==typeof e?.yield?e.yield():new Promise(e=>setTimeout(e,0))}
|
|
@@ -3,9 +3,6 @@ import { Matrix4, Vector2, Vector3 } from 'three/webgpu';
|
|
|
3
3
|
/**
|
|
4
4
|
* What drawing in pixels or metres needs to know about the frame being drawn. An engine fills it
|
|
5
5
|
* in before every frame and hands it to each primitive's `setFrame`.
|
|
6
|
-
*
|
|
7
|
-
* The first five are the ones the Ing+ map's `ThreeFrame` has, with the same meaning, so that a
|
|
8
|
-
* frame from either is good for both.
|
|
9
6
|
*/
|
|
10
7
|
export interface GeometryFrame {
|
|
11
8
|
/** Frame pixels per world unit, at the view's centre: exact on a flat (orthographic) map. */
|
|
@@ -50,15 +47,15 @@ export interface PickOptions {
|
|
|
50
47
|
/**
|
|
51
48
|
* What may stand in front of geometry drawn on or under the ground: a node for the fragment
|
|
52
49
|
* shader saying whether something hides a fragment `distance` (clip w) from the camera. `pixel`,
|
|
53
|
-
* the frame pixel, when not the fragment's own (the pick pass).
|
|
54
|
-
* one; the package's own scene depth does without.
|
|
50
|
+
* the frame pixel, when not the fragment's own (the pick pass). A host's mask of what stands -
|
|
51
|
+
* buildings, trees - is one; the package's own scene depth does without.
|
|
55
52
|
*/
|
|
56
53
|
export interface GeometryOccluder {
|
|
57
54
|
/** Another for each new occluder: geometry made with an old one is made again. */
|
|
58
55
|
readonly id: number;
|
|
59
56
|
hides(distance: any, pixel?: any): any;
|
|
60
57
|
}
|
|
61
|
-
/** The
|
|
58
|
+
/** The same, by the name the lines take it under. */
|
|
62
59
|
export type LineOccluder = GeometryOccluder;
|
|
63
60
|
/**
|
|
64
61
|
* The passes an engine draws, each a scene:
|
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
import type { ColorRamp } from '../common/Colors';
|
|
2
|
+
import type { GeometryEngine } from './GeometryEngine';
|
|
2
3
|
import type { CameraLimits, CameraState } from './MapCamera';
|
|
4
|
+
import { ThemeScheme } from '../theme/Theme';
|
|
3
5
|
/** How what is lit - selected, pointed at, emphasized - is set off. */
|
|
4
6
|
export interface GeometryHighlightOptions {
|
|
5
7
|
/** A glow round it, or an outline. A glow by default. */
|
|
6
8
|
look?: 'glow' | 'outline';
|
|
7
|
-
/** The glow from the bloom pass - soft, over everything - or drawn in the line shader, cheaper. */
|
|
8
|
-
glow?: 'bloom' | 'shader';
|
|
9
|
+
/** The glow from the bloom pass - soft, over everything - or drawn in the line shader, cheaper; or none. */
|
|
10
|
+
glow?: 'bloom' | 'shader' | 'none';
|
|
9
11
|
/** The outline's colour, and width in view pixels. */
|
|
10
12
|
outlineColor?: string;
|
|
11
13
|
outlineWidth?: number;
|
|
@@ -13,15 +15,31 @@ export interface GeometryHighlightOptions {
|
|
|
13
15
|
hoverFades?: boolean;
|
|
14
16
|
/** How bright the rest is then, 0 to 1. */
|
|
15
17
|
othersShade?: number;
|
|
18
|
+
/** What the rest is shaded towards then: 0 black, 1 white. The theme's by default (dark 0, light 1). */
|
|
19
|
+
othersToward?: number;
|
|
20
|
+
/**
|
|
21
|
+
* How opaque a selected or emphasised feature is whose own style - or a filter - fades or hides
|
|
22
|
+
* it: drawn lit all the same, its glow or outline behind it, only this faint, to show it is not
|
|
23
|
+
* in view now. Never picked where its style hides it. 0.6 by default.
|
|
24
|
+
*/
|
|
25
|
+
outsideOpacity?: number;
|
|
16
26
|
/** Whether pointing at a feature lights it as the selection is. On by default. */
|
|
17
27
|
hoverLights?: boolean;
|
|
18
28
|
}
|
|
29
|
+
/**
|
|
30
|
+
* What a view draws its scene in. `background`, `outline`, `grid` and `othersToward` come from the
|
|
31
|
+
* Protomaze theme's tokens (`--pm-*`, see `Theme.ts`); `ground`, `sky` and `windowsLit` are the
|
|
32
|
+
* scene's own, one set per look. Any of them given in the `theme` option wins over both.
|
|
33
|
+
*/
|
|
19
34
|
export interface GeometryTheme {
|
|
35
|
+
/** Under everything: what a 2D map shows past its ground. The `background` token. */
|
|
20
36
|
background: string;
|
|
21
37
|
ground: string;
|
|
38
|
+
/** The ground grid's lines, drawn faint. The `text` token. */
|
|
22
39
|
grid: string;
|
|
40
|
+
/** The outline round what is lit, `highlight.look` 'outline'. The `highlight` token. */
|
|
23
41
|
outline: string;
|
|
24
|
-
/** What the rest is shaded towards while something is lit: 0 black, 1 white. */
|
|
42
|
+
/** What the rest is shaded towards while something is lit: 0 black, 1 white. The look's. */
|
|
25
43
|
othersToward: number;
|
|
26
44
|
/** The sky in perspective: overhead, at the horizon, and the glow just above it. */
|
|
27
45
|
sky: {
|
|
@@ -32,12 +50,38 @@ export interface GeometryTheme {
|
|
|
32
50
|
/** Windows on volumes lit at night (dark), or dark glass (light). */
|
|
33
51
|
windowsLit: number;
|
|
34
52
|
}
|
|
53
|
+
/** The `theme` option as an object: scene colours of the application's own, over the look `scheme` names (dark by default). */
|
|
54
|
+
export type GeometryThemeOptions = Partial<GeometryTheme> & {
|
|
55
|
+
scheme?: ThemeScheme;
|
|
56
|
+
};
|
|
57
|
+
/** The dark look: Protomaze's dark tokens, a night sky. */
|
|
35
58
|
export declare const DARK_THEME: GeometryTheme;
|
|
59
|
+
/** The light look: Protomaze's light tokens, a day sky. */
|
|
36
60
|
export declare const LIGHT_THEME: GeometryTheme;
|
|
61
|
+
/** What a view inside a host's frame is given, besides its options. */
|
|
62
|
+
export interface GeometryViewHostOptions<E extends GeometryEngine = GeometryEngine> {
|
|
63
|
+
/**
|
|
64
|
+
* An engine that draws in someone else's frame (`HostedGeometryEngine`), for a view inside a
|
|
65
|
+
* host - a map, a globe - rather than on a canvas of its own. The host has the camera, the
|
|
66
|
+
* ground and the input: such a view has layers, their looks, the highlight, selection and
|
|
67
|
+
* picking (`pickAt`), and is never `init`ed. Left out, the view makes its own canvas engine.
|
|
68
|
+
*/
|
|
69
|
+
engine?: E;
|
|
70
|
+
/**
|
|
71
|
+
* With `engine`: the host's element, round which the `--pm-*` tokens are read. The page's
|
|
72
|
+
* root by default.
|
|
73
|
+
*/
|
|
74
|
+
element?: HTMLElement | null;
|
|
75
|
+
}
|
|
37
76
|
export interface GeometryViewOptions {
|
|
38
77
|
/** A 2D map (orthographic, straight down) or 3D (perspective, tilting). 3D by default. */
|
|
39
78
|
mode?: '2d' | '3d';
|
|
40
|
-
|
|
79
|
+
/**
|
|
80
|
+
* The look: 'dark' (the default), 'light', or 'auto' - the page's `color-scheme`, else the
|
|
81
|
+
* system's. Colours follow the `--pm-*` tokens set round the view; an object sets scene
|
|
82
|
+
* colours of its own over them.
|
|
83
|
+
*/
|
|
84
|
+
theme?: ThemeScheme | GeometryThemeOptions;
|
|
41
85
|
/** Where the camera starts. */
|
|
42
86
|
camera?: Partial<CameraState>;
|
|
43
87
|
limits?: Partial<CameraLimits>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export const DARK_THEME={background:
|
|
1
|
+
import{PROTOMAZE_DARK as o,PROTOMAZE_LIGHT as t}from"../theme/Theme.js";export const DARK_THEME={background:o.background,ground:"#14181d",grid:o.text,outline:o.highlight,othersToward:0,sky:{zenith:"#05080d",horizon:"#1d2938",glow:"#2e4d6c"},windowsLit:.35};export const LIGHT_THEME={background:t.background,ground:"#f8f9fa",grid:t.text,outline:t.highlight,othersToward:1,sky:{zenith:"#9fb7cf",horizon:"#e8eef3",glow:"#ffffff"},windowsLit:0};
|
package/engine/GeometryView.d.ts
CHANGED
|
@@ -7,9 +7,10 @@ import { GeometryLayer, LayerHit, LayerHost, ResolvedHighlight, SelectMode } fro
|
|
|
7
7
|
import { CanvasGeometryEngine } from '../three/CanvasGeometryEngine';
|
|
8
8
|
import { Ground, GroundOptions } from '../three/Ground';
|
|
9
9
|
import { Lighting } from '../three/Shading';
|
|
10
|
-
import { GeometryFrameStats } from './GeometryEngine';
|
|
11
|
-
import { GeometryViewOptions } from './GeometryOptions';
|
|
10
|
+
import { GeometryEngine, GeometryFrameStats } from './GeometryEngine';
|
|
11
|
+
import { GeometryViewHostOptions, GeometryViewOptions } from './GeometryOptions';
|
|
12
12
|
import { CameraState, MapCamera } from './MapCamera';
|
|
13
|
+
import { ResolvedTheme } from '../theme/Theme';
|
|
13
14
|
/** What the pointer is on, or a click hit: a layer's feature, and the point on it. */
|
|
14
15
|
export interface GeometryHit<F = GeometryFeature> extends LayerHit<F> {
|
|
15
16
|
point: [number, number, number];
|
|
@@ -59,18 +60,32 @@ export interface GeometryViewEvents {
|
|
|
59
60
|
* view.addLayer(new TubeLayer({ features: pipes, style: f => ({ color: colorOf(f) }) }));
|
|
60
61
|
* view.on('select', selection => ...);
|
|
61
62
|
* ```
|
|
63
|
+
*
|
|
64
|
+
* Or inside a host's own frame - a map's, a globe's - on an engine that draws there: the host keeps
|
|
65
|
+
* its camera, ground and input, the view its layers, their looks, the highlight and the picking.
|
|
66
|
+
*
|
|
67
|
+
* ```ts
|
|
68
|
+
* const view = new GeometryView({ engine: hostedEngine, mode: '3d' });
|
|
69
|
+
* view.addLayer(lines);
|
|
70
|
+
* const hit = await view.pickAt(x, y);
|
|
71
|
+
* ```
|
|
62
72
|
*/
|
|
63
|
-
export declare class GeometryView extends TypedEventEmitter<GeometryViewEvents> implements LayerHost, ControllerHost {
|
|
64
|
-
readonly engine:
|
|
73
|
+
export declare class GeometryView<E extends GeometryEngine = CanvasGeometryEngine> extends TypedEventEmitter<GeometryViewEvents> implements LayerHost, ControllerHost {
|
|
74
|
+
readonly engine: E;
|
|
65
75
|
readonly camera: MapCamera;
|
|
66
76
|
readonly lighting: Lighting;
|
|
67
|
-
|
|
77
|
+
/** Whether the view draws in a host's frame, on an engine it was given, rather than on its own canvas. */
|
|
78
|
+
readonly hosted: boolean;
|
|
79
|
+
/** In a host's frame: the host's element, round which the theme's tokens are read. */
|
|
80
|
+
private readonly hostElement;
|
|
68
81
|
mode: '2d' | '3d';
|
|
69
82
|
highlight: ResolvedHighlight;
|
|
70
83
|
/** Labels on world positions over the view: what controllers measure, or the application's own. */
|
|
71
84
|
labels: LabelOverlay | null;
|
|
72
85
|
private options;
|
|
73
86
|
private theme;
|
|
87
|
+
private resolved;
|
|
88
|
+
private resolvedKey;
|
|
74
89
|
private layers;
|
|
75
90
|
private overlays;
|
|
76
91
|
private controller;
|
|
@@ -89,7 +104,19 @@ export declare class GeometryView extends TypedEventEmitter<GeometryViewEvents>
|
|
|
89
104
|
private drag;
|
|
90
105
|
private touches;
|
|
91
106
|
private pinch;
|
|
92
|
-
constructor(options?: GeometryViewOptions);
|
|
107
|
+
constructor(options?: GeometryViewOptions & GeometryViewHostOptions<E>);
|
|
108
|
+
/**
|
|
109
|
+
* The ground's up at the origin: a level world's z, or on a globe (geocentric) the ellipsoid's
|
|
110
|
+
* normal at the engine's origin - what shafts stand along and volumes rise along.
|
|
111
|
+
*/
|
|
112
|
+
get up(): [number, number, number];
|
|
113
|
+
/** The view's own canvas engine; a view in a host's frame has none. */
|
|
114
|
+
private get own();
|
|
115
|
+
/**
|
|
116
|
+
* What every view does once it draws: its layers built on the frames, the frames' figures
|
|
117
|
+
* reported, the theme's tokens followed round `themeRoot` (the page's root when null).
|
|
118
|
+
*/
|
|
119
|
+
private start;
|
|
93
120
|
/** Puts the view into `container`, which it fills, and starts drawing. */
|
|
94
121
|
init(container: HTMLElement): Promise<void>;
|
|
95
122
|
dispose(): void;
|
|
@@ -97,7 +124,19 @@ export declare class GeometryView extends TypedEventEmitter<GeometryViewEvents>
|
|
|
97
124
|
get element(): HTMLDivElement | null;
|
|
98
125
|
setOptions(options: Partial<GeometryViewOptions>): void;
|
|
99
126
|
getOptions(): Readonly<GeometryViewOptions>;
|
|
127
|
+
/**
|
|
128
|
+
* The theme's tokens in force at the view: Protomaze's for its look, then the `--pm-*`
|
|
129
|
+
* properties the page sets round it. What its chrome - outline, labels, sketches - is drawn in.
|
|
130
|
+
*/
|
|
131
|
+
get tokens(): ResolvedTheme;
|
|
132
|
+
/** The options, and the theme as it stands, onto the engine, the ground, the labels and the sketches. */
|
|
100
133
|
private applyOptions;
|
|
134
|
+
/**
|
|
135
|
+
* The scene's colours: the look's own, then the tokens at the view's element (none before
|
|
136
|
+
* `init`), then what the application's `theme` object sets. New tokens restyle the labels
|
|
137
|
+
* and the sketches.
|
|
138
|
+
*/
|
|
139
|
+
private resolveColors;
|
|
101
140
|
/** What needs the engine started: the bloom's settings, the halo's, the heatmap's. */
|
|
102
141
|
private applyRuntimeOptions;
|
|
103
142
|
/** Adds a layer on top, or under `below`. */
|
|
@@ -138,6 +177,8 @@ export declare class GeometryView extends TypedEventEmitter<GeometryViewEvents>
|
|
|
138
177
|
bounds(): Bounds3 | null;
|
|
139
178
|
/** A ground under everything: its depth is the scene's, what lies under it ghosted. Null for none. */
|
|
140
179
|
setGround(options: GroundOptions | null): void;
|
|
180
|
+
/** The ground's colour and its grid's: the application's, else the theme's. */
|
|
181
|
+
private applyGroundColors;
|
|
141
182
|
getGround(): Ground | null;
|
|
142
183
|
/** The heatmap of these layers - all, by default - instead of them; null to draw them again. */
|
|
143
184
|
setDensity(spec: {
|
|
@@ -166,6 +207,7 @@ export declare class GeometryView extends TypedEventEmitter<GeometryViewEvents>
|
|
|
166
207
|
getSelection(): GeometrySelection;
|
|
167
208
|
/** A layer's place among the view's, overlays above them all. */
|
|
168
209
|
rankOf(layer: GeometryLayer<any, any>): number;
|
|
210
|
+
/** Whether anything is pointed at or emphasised, in any layer: the rest is shaded then (`highlight.hoverFades`). */
|
|
169
211
|
get anyHovered(): boolean;
|
|
170
212
|
get windowsLit(): number;
|
|
171
213
|
requestRepaint(): void;
|