Commit b4137cf5

b4137cf595e8Mergedon cedricvidal-66f663

cedricvidal · 2 months ago · 2 files · +1 added · ~1 modified

Details

Commit
b4137cf595e8
Parent
688e1cbb0d4c

src/dragControls.tsaddedView file

1+import * as THREE from 'three';
2+import { RubiksCube, Axis } from './rubiks';
3+
4+const DRAG_THRESHOLD_PX = 10;
5+
6+interface DragState {
7+ pointerId: number;
8+ cubiePos: THREE.Vector3;
9+ faceNormal: THREE.Vector3;
10+ hitPoint: THREE.Vector3;
11+ startX: number;
12+ startY: number;
13+}
14+
15+/**
16+ * Drag a sticker to turn its layer. Runs in the capture phase so a drag that
17+ * starts on the cube never reaches OrbitControls; background drags fall
18+ * through and orbit the camera.
19+ */
20+export function attachDragControls(
21+ canvas: HTMLCanvasElement,
22+ camera: THREE.PerspectiveCamera,
23+ cube: RubiksCube,
24+): void {
25+ const raycaster = new THREE.Raycaster();
26+ const pointer = new THREE.Vector2();
27+ let drag: DragState | null = null;
28+
29+ const pick = (event: PointerEvent) => {
30+ const rect = canvas.getBoundingClientRect();
31+ pointer.set(
32+ ((event.clientX - rect.left) / rect.width) * 2 - 1,
33+ -((event.clientY - rect.top) / rect.height) * 2 + 1,
34+ );
35+ raycaster.setFromCamera(pointer, camera);
36+ return raycaster.intersectObjects(cube.cubies.map((c) => c.mesh))[0];
37+ };
38+
39+ /** Screen-space direction (pixels) of a world-space direction at a point. */
40+ const screenDirection = (origin: THREE.Vector3, dir: THREE.Vector3) => {
41+ const rect = canvas.getBoundingClientRect();
42+ const a = origin.clone().project(camera);
43+ const b = origin.clone().addScaledVector(dir, 0.5).project(camera);
44+ return new THREE.Vector2(
45+ ((b.x - a.x) * rect.width) / 2,
46+ (-(b.y - a.y) * rect.height) / 2,
47+ ).normalize();
48+ };
49+
50+ const onPointerDown = (event: PointerEvent) => {
51+ if (cube.isAnimating || event.button !== 0) return;
52+ const hit = pick(event);
53+ if (!hit || !hit.face) return;
54+
55+ // Claim the gesture before OrbitControls sees it.
56+ event.stopPropagation();
57+
58+ const mesh = hit.object as THREE.Mesh;
59+ drag = {
60+ pointerId: event.pointerId,
61+ cubiePos: mesh.position.clone().round(),
62+ faceNormal: hit.face.normal.clone().applyQuaternion(mesh.quaternion).round(),
63+ hitPoint: hit.point.clone(),
64+ startX: event.clientX,
65+ startY: event.clientY,
66+ };
67+ window.addEventListener('pointermove', onPointerMove);
68+ window.addEventListener('pointerup', onPointerUp);
69+ };
70+
71+ const onPointerMove = (event: PointerEvent) => {
72+ if (!drag || event.pointerId !== drag.pointerId) return;
73+ const dragVec = new THREE.Vector2(event.clientX - drag.startX, event.clientY - drag.startY);
74+ if (dragVec.length() < DRAG_THRESHOLD_PX) return;
75+ dragVec.normalize();
76+
77+ // Candidate world-space drag directions: the four axis-aligned unit
78+ // vectors tangent to the grabbed face.
79+ const n = drag.faceNormal;
80+ const candidates: THREE.Vector3[] = [];
81+ for (const base of [new THREE.Vector3(1, 0, 0), new THREE.Vector3(0, 1, 0), new THREE.Vector3(0, 0, 1)]) {
82+ if (Math.abs(base.dot(n)) > 0.5) continue;
83+ candidates.push(base.clone(), base.clone().negate());
84+ }
85+
86+ let best: THREE.Vector3 | null = null;
87+ let bestScore = -Infinity;
88+ for (const t of candidates) {
89+ const score = screenDirection(drag.hitPoint, t).dot(dragVec);
90+ if (score > bestScore) {
91+ bestScore = score;
92+ best = t;
93+ }
94+ }
95+
96+ const cubiePos = drag.cubiePos;
97+ endDrag();
98+ if (!best) return;
99+
100+ // Rotating about (n × t) moves the grabbed sticker along t.
101+ const axisVec = new THREE.Vector3().crossVectors(n, best);
102+ const axis: Axis = Math.abs(axisVec.x) > 0.5 ? 'x' : Math.abs(axisVec.y) > 0.5 ? 'y' : 'z';
103+ const sign = axisVec.x + axisVec.y + axisVec.z > 0 ? 1 : -1;
104+ const layer = Math.round(cubiePos[axis]) as 1 | -1 | 0;
105+ cube.enqueueLayerTurn(axis, layer, sign);
106+ };
107+
108+ const onPointerUp = (event: PointerEvent) => {
109+ if (drag && event.pointerId === drag.pointerId) endDrag();
110+ };
111+
112+ const endDrag = () => {
113+ drag = null;
114+ window.removeEventListener('pointermove', onPointerMove);
115+ window.removeEventListener('pointerup', onPointerUp);
116+ };
117+
118+ canvas.addEventListener('pointerdown', onPointerDown, { capture: true });
119+}