Spaces:
Running

File size: 8,648 Bytes
5e1643b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
import * as THREE from 'three';

// Movement uses the camera's full orientation, including pitch: forward while
// looking down descends, and backward retraces that direction. No fixed world-plane projection.
export class PilotFlight {
  constructor(viewer, ui) {
    this.viewer=viewer;this.canvas=viewer.canvas;this.ui=ui;this.mode='fly';this.keys=new Set();
    this.drag=null;this.touches=new Map();this.pinch=null;this.handlers=[];
    this.lookSpeed=.65;this.stickMoveMultiplier=3;
    this.analog={move:{x:0,y:0},look:{x:0,y:0}};this.inputResetListeners=new Set();
    this.origin={position:viewer.camera.position.clone(),quaternion:viewer.camera.quaternion.clone(),refCam:structuredClone(viewer.refCam)};
    this.euler=new THREE.Euler().setFromQuaternion(viewer.camera.quaternion,'YXZ');
    this.speed=THREE.MathUtils.clamp(viewer.asset.radius*.18,8,35);
    this.originalAim=viewer.aim.bind(viewer);this.originalDraw=viewer.draw.bind(viewer);
    viewer.aim=()=>this.aim();
    viewer.draw=dt=>{this.update(dt);this.originalDraw(dt);};
    viewer.paused=true;
    this.bind();this.setMode('fly');this.canvas.focus({preventScroll:true});
  }
  listen(target,name,fn,options){target.addEventListener(name,fn,options);this.handlers.push(()=>target.removeEventListener(name,fn,options));}
  forward(){return this.viewer.camera.getWorldDirection(new THREE.Vector3());}
  right(){return new THREE.Vector3(1,0,0).applyQuaternion(this.viewer.camera.quaternion).normalize();}
  aim(){
    if(this.mode==='orbit'){this.originalAim();this.euler.setFromQuaternion(this.viewer.camera.quaternion,'YXZ');return;}
    const v=this.viewer,c=v.camera;c.aspect=v.w/v.h;
    c.fov=2*Math.atan(Math.tan(this.origin.refCam.hfov*Math.PI/360)/c.aspect)*180/Math.PI;
    c.near=.04;c.far=Math.max(3000,v.asset.radius*30);
    c.quaternion.setFromEuler(this.euler);c.updateProjectionMatrix();
  }
  update(dt){
    if(this.mode!=='fly'||!this.viewer.visible||document.hidden)return;
    const step=Math.max(0,Math.min(dt,.1)),look=this.analog.look;
    if(look.x||look.y){
      this.euler.y-=look.x*this.lookSpeed*step;
      this.euler.x=THREE.MathUtils.clamp(this.euler.x-look.y*this.lookSpeed*step,-Math.PI/2+.01,Math.PI/2-.01);
      this.viewer.camera.quaternion.setFromEuler(this.euler);this.viewer.dirty=true;
    }
    const direction=new THREE.Vector3();
    const f=(this.keys.has('ArrowUp')||this.keys.has('KeyW')?1:0)-(this.keys.has('ArrowDown')||this.keys.has('KeyS')?1:0)-this.analog.move.y;
    const r=(this.keys.has('ArrowRight')||this.keys.has('KeyD')?1:0)-(this.keys.has('ArrowLeft')||this.keys.has('KeyA')?1:0)+this.analog.move.x;
    direction.addScaledVector(this.forward(),f).addScaledVector(this.right(),r);
    direction.y+=(this.keys.has('KeyE')?1:0)-(this.keys.has('KeyQ')?1:0);
    if(direction.lengthSq()){
      const boost=this.keys.has('ShiftLeft')||this.keys.has('ShiftRight')?3:1;
      // Keep a light stick deflection slow; clamp diagonals to the same top speed.
      if(this.keys.size||direction.lengthSq()>1)direction.normalize();
      // Boost only stick movement; desktop keys and wheel retain their speed.
      const stickBoost=this.analog.move.x||this.analog.move.y?this.stickMoveMultiplier:1;
      this.viewer.camera.position.addScaledVector(direction,this.speed*step*boost*stickBoost);
      this.viewer.dirty=true;
    }
  }
  dolly(distance){this.viewer.camera.position.addScaledVector(this.forward(),distance);this.viewer.dirty=true;}
  resetInputs(){
    this.keys.clear();this.drag=null;this.touches.clear();this.pinch=null;
    for(const axis of Object.values(this.analog)){axis.x=0;axis.y=0;}
    for(const reset of this.inputResetListeners)reset();
  }
  setMode(mode){
    this.resetInputs();
    const v=this.viewer;
    if(mode==='orbit'&&this.mode==='fly'){
      const pos=v.camera.position.clone(),distance=THREE.MathUtils.clamp(pos.distanceTo(v.asset.centre),4,v.asset.radius*4);
      v.refCam={pos:pos.toArray(),target:pos.clone().addScaledVector(this.forward(),distance).toArray(),hfov:this.origin.refCam.hfov};
      [v.rotationX,v.rotationY]=v.initialRotation;v.zoom=1;
    }else if(mode==='fly')this.euler.setFromQuaternion(v.camera.quaternion,'YXZ');
    this.mode=mode;v.paused=true;v.dragging=false;v.dirty=true;
    for(const b of this.ui.modes)b.setAttribute('aria-pressed',String(b.dataset.mode===mode));
    this.ui.help.textContent=mode==='fly'?(document.body.dataset.touch==='true'?'Left stick: look · Right stick: move · Pinch to zoom':'Drag to look · ↑/↓ forward/back · ←/→ strafe · Scroll to zoom · Shift faster · Q/E down/up'):(document.body.dataset.touch==='true'?'Drag to orbit · Pinch to zoom':'Drag to orbit · Scroll to zoom');
    this.ui.speed.disabled=mode!=='fly';
    this.canvas.setAttribute('aria-label',mode==='fly'?'3D scene. Drag to look. Arrow keys move relative to your view. Q and E descend and ascend.':'3D scene. Drag to orbit and scroll to zoom.');
    document.body.dataset.cameraMode=mode;
  }
  reset(){
    const v=this.viewer;this.resetInputs();
    v.camera.position.copy(this.origin.position);v.camera.quaternion.copy(this.origin.quaternion);
    this.euler.setFromQuaternion(this.origin.quaternion,'YXZ');v.refCam=structuredClone(this.origin.refCam);
    [v.rotationX,v.rotationY]=v.initialRotation;v.zoom=1;v.paused=true;v.dirty=true;
    this.canvas.focus({preventScroll:true});
  }
  bind(){
    const c=this.canvas,handled=new Set(['ArrowUp','ArrowDown','ArrowLeft','ArrowRight','KeyW','KeyA','KeyS','KeyD','KeyQ','KeyE','ShiftLeft','ShiftRight','Equal','Minus','NumpadAdd','NumpadSubtract','KeyR']);
    this.ui.speed.value=String(Math.round(this.speed));
    this.listen(this.ui.speed,'input',()=>{this.speed=Number(this.ui.speed.value);});
    for(const b of this.ui.modes)this.listen(b,'click',()=>{this.setMode(b.dataset.mode);c.focus({preventScroll:true});});
    this.listen(this.ui.reset,'click',()=>this.reset());
    this.listen(c,'keydown',e=>{
      if(this.mode!=='fly'||!handled.has(e.code))return;
      if(e.ctrlKey||e.metaKey||e.altKey){e.stopImmediatePropagation();return;}
      e.preventDefault();e.stopImmediatePropagation();
      if(e.code==='KeyR'){this.reset();return;}
      if(['Equal','NumpadAdd','Minus','NumpadSubtract'].includes(e.code)){this.dolly(this.speed*.15*(e.code==='Minus'||e.code==='NumpadSubtract'?-1:1));return;}
      this.keys.add(e.code);
    },true);
    this.listen(window,'keyup',e=>this.keys.delete(e.code));
    this.listen(window,'blur',()=>this.resetInputs());
    this.listen(c,'blur',()=>this.keys.clear());
    this.listen(document,'visibilitychange',()=>{if(document.hidden)this.resetInputs();});
    this.listen(c,'pointerdown',e=>{
      if(this.mode!=='fly')return;if(e.button!==0&&e.pointerType!=='touch')return;
      e.preventDefault();e.stopImmediatePropagation();c.focus({preventScroll:true});c.setPointerCapture(e.pointerId);
      this.touches.set(e.pointerId,[e.clientX,e.clientY]);
      this.drag={id:e.pointerId,x:e.clientX,y:e.clientY};
      if(this.touches.size===2){const [a,b]=[...this.touches.values()];this.pinch=Math.hypot(a[0]-b[0],a[1]-b[1]);this.drag=null;}
    },true);
    this.listen(c,'pointermove',e=>{
      if(this.mode!=='fly'||!this.touches.has(e.pointerId))return;e.preventDefault();e.stopImmediatePropagation();
      this.touches.set(e.pointerId,[e.clientX,e.clientY]);
      if(this.touches.size===2){const [a,b]=[...this.touches.values()],distance=Math.hypot(a[0]-b[0],a[1]-b[1]);if(this.pinch)this.dolly(Math.log(distance/this.pinch)*this.speed*1.5);this.pinch=distance;return;}
      if(this.drag?.id!==e.pointerId)return;
      this.euler.y-=(e.clientX-this.drag.x)*.004;
      this.euler.x=THREE.MathUtils.clamp(this.euler.x-(e.clientY-this.drag.y)*.004,-Math.PI/2+.01,Math.PI/2-.01);
      this.drag.x=e.clientX;this.drag.y=e.clientY;this.viewer.camera.quaternion.setFromEuler(this.euler);this.viewer.dirty=true;
    },{capture:true,passive:false});
    for(const name of ['pointerup','pointercancel','lostpointercapture'])this.listen(c,name,e=>{this.touches.delete(e.pointerId);this.pinch=null;if(this.drag?.id===e.pointerId)this.drag=null;},true);
    this.listen(c,'wheel',e=>{
      if(this.mode!=='fly')return;e.preventDefault();e.stopImmediatePropagation();
      const pixels=e.deltaY*(e.deltaMode===1?16:e.deltaMode===2?this.viewer.h:1);
      this.dolly(-THREE.MathUtils.clamp(pixels,-300,300)*this.speed*.006);
    },{capture:true,passive:false});
  }
  destroy(){this.resetInputs();this.inputResetListeners.clear();this.handlers.forEach(fn=>fn());this.viewer.aim=this.originalAim;this.viewer.draw=this.originalDraw;}
}