Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# Pull requests

- Follow [CONTRIBUTING.md](CONTRIBUTING.md). Use `(<type>) <Sentence-case summary>` for PR titles, for example `(fix) Add viewport-aligned rotation to Transform`. Use the same format for commit subjects that will become PR titles.
- Set the PR title explicitly when publishing. Before opening or updating a PR, validate the exact title and description with `PR_TITLE='<title>' PR_BODY_FILE='<body-file>' node scripts/check-pull-request.mjs`.
46 changes: 32 additions & 14 deletions src/components/CombinedTransform.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ export function CombinedTransform({ onPress }: { onPress: () => void }) {
[selection, scene],
);
const root = useRef<Group>(null),
viewRing = useRef<Group>(null),
worldSize = useRef(1);
const { camera, size, invalidate, get, setEvents } = useThree();
const [hover, setHover] = useState('');
Expand Down Expand Up @@ -183,6 +184,8 @@ export function CombinedTransform({ onPress }: { onPress: () => void }) {
};
}, [finish]);
const unavailable = !!selection.blocked || free;
const canRotateInView =
!selection.locks?.some(Boolean) && (selection.kind !== 'warp' || selection.parts.length > 1);
useEffect(() => {
if (unavailable) finish();
}, [unavailable, finish]);
Expand Down Expand Up @@ -237,14 +240,13 @@ export function CombinedTransform({ onPress }: { onPress: () => void }) {
right.x += 2 / size.width;
worldSize.current = right.unproject(camera).distanceTo(root.current.position) * 96;
root.current.scale.setScalar(worldSize.current);
const cameraInGizmo = root.current.quaternion.clone().invert().multiply(camera.quaternion);
viewRing.current?.quaternion.copy(cameraInGizmo);
// Keep uniform scale clear of the free-move center in every camera orientation.
root.current
.getObjectByName('transform:scale:uniform')
?.position.copy(
new Vector3(-0.45, -0.45, 0)
.applyQuaternion(camera.quaternion)
.applyQuaternion(root.current.quaternion.clone().invert()),
);
?.position.set(-0.45, -0.45, 0)
.applyQuaternion(cameraInGizmo);
const eye = camera.getWorldDirection(new Vector3()).negate();
root.current.traverse((child) => {
const normal = child.userData.planeNormal as number | undefined;
Expand Down Expand Up @@ -275,7 +277,10 @@ export function CombinedTransform({ onPress }: { onPress: () => void }) {
const state = useEditor.getState();
if (handle.mode === 'scale' && !usePreferences.getState().transform.scaling) return;
if (handle.mode === 'translate' && pinned) return;
if (handle.mode === 'rotate' && handle.axis !== null && selection.locks?.[handle.axis])
if (
handle.mode === 'rotate' &&
(handle.axis === null ? !canRotateInView : selection.locks?.[handle.axis])
)
return;
const capture = event.target as unknown as Capture;
drag.current = {
Expand Down Expand Up @@ -340,6 +345,23 @@ export function CombinedTransform({ onPress }: { onPress: () => void }) {
side={DoubleSide}
/>
);
const rotationRing = (
id: string,
axis: TransformHandle['axis'],
radius: number,
color: string,
) => (
<>
<mesh {...handlers(id, { mode: 'rotate', axis })} renderOrder={1001}>
<torusGeometry args={[radius, 0.045, 8, 80]} />
<meshBasicMaterial transparent opacity={0} depthWrite={false} side={DoubleSide} />
</mesh>
<mesh raycast={noRaycast} renderOrder={1001}>
<torusGeometry args={[radius, hover === id ? 0.018 : 0.011, 8, 80]} />
{material(id, color)}
</mesh>
</>
);
if (unavailable) return null;
return (
<group ref={root} name="combined-transform">
Expand Down Expand Up @@ -380,14 +402,7 @@ export function CombinedTransform({ onPress }: { onPress: () => void }) {
userData={{ planeNormal: i }}
quaternion={new Quaternion().setFromUnitVectors(new Vector3(0, 0, 1), axis)}
>
<mesh {...handlers(ring, { mode: 'rotate', axis: index })} renderOrder={1001}>
<torusGeometry args={[0.78, 0.045, 8, 80]} />
<meshBasicMaterial transparent opacity={0} depthWrite={false} side={DoubleSide} />
</mesh>
<mesh raycast={noRaycast} renderOrder={1001}>
<torusGeometry args={[0.78, hover === ring ? 0.018 : 0.011, 8, 80]} />
{material(ring, colors[i])}
</mesh>
{rotationRing(ring, index, 0.78, colors[i])}
</group>
) : null}
{scaling ? (
Expand All @@ -404,6 +419,9 @@ export function CombinedTransform({ onPress }: { onPress: () => void }) {
</group>
);
})}
{canRotateInView ? (
<group ref={viewRing}>{rotationRing('rotate:view', null, 1.3, '#e2e4e8')}</group>
) : null}
{!pinned ? (
<>
<mesh {...handlers('move:free', { mode: 'translate', axis: null })} renderOrder={1005}>
Expand Down
4 changes: 3 additions & 1 deletion src/components/TransformAdjustments.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,9 @@ export function TransformAdjustments() {
</label>
<p className="transform-help">
Drag an arrow to move, a ring to rotate{scaling ? ', or a cube to scale' : ''}.{' '}
{scaling ? 'Turn off scaling to hide its handles.' : 'Scale handles are disabled.'}
{!single && !selection.locks?.some(Boolean)
? 'The outer ring rotates in the plane of the viewport.'
: null}
</p>
<p className="transform-help">
Shift: fine adjustment · Uses Snap and the selected pivot.
Expand Down
9 changes: 6 additions & 3 deletions src/core/combined-transform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import type { TransformTarget } from './transform-selection';

export interface TransformHandle {
mode: 'translate' | 'rotate' | 'scale';
/** A null rotation axis uses the viewport normal. */
axis: 0 | 1 | 2 | null;
/** The normal axis of a planar move handle. */
plane?: 0 | 1 | 2;
Expand Down Expand Up @@ -40,9 +41,11 @@ export class CombinedTransformDrag {
this.pointer = pointer.clone();
this.motion = new FreeTransformMotion(this.camera, pivot, width, height);
this.worldAxis =
handle.axis === null
? null
: new Vector3().setComponent(handle.axis, 1).applyQuaternion(orientation);
handle.axis !== null
? new Vector3().setComponent(handle.axis, 1).applyQuaternion(orientation)
: handle.mode === 'rotate'
? this.camera.getWorldDirection(new Vector3()).negate()
: null;
const normal =
handle.plane !== undefined
? new Vector3().setComponent(handle.plane, 1).applyQuaternion(orientation)
Expand Down
60 changes: 59 additions & 1 deletion tests/e2e/combined-transform.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { expect, test, type Page } from '@playwright/test';
import { BoxGeometry } from 'three';
import { BoxGeometry, Quaternion, Vector3 } from 'three';
import { serializeGeometry } from '../../src/core/geometry';

const cube = {
Expand Down Expand Up @@ -82,6 +82,7 @@ async function state(page: Page) {
})),
enabled: root.controls.enabled,
handles,
viewAxis: root.camera.getWorldDirection(root.camera.position.clone()).negate().toArray(),
jointErrors: s.scene.joints.map((j: any) => anchorError(s.scene.parts, j)),
};
});
Expand Down Expand Up @@ -197,6 +198,62 @@ test('removes scaling from display and picking, persists the choice, and keeps m
).toHaveAttribute('aria-checked', 'false');
});

test('rotates in the viewport plane in perspective and orthographic views', async ({ page }) => {
await open(page);
await page.getByRole('button', { name: 'Local', exact: true }).click();
const snap = page.getByRole('spinbutton', { name: 'Transform rotation snap', exact: true });
await snap.fill('15');
await snap.press('Enter');
await page.getByRole('button', { name: 'Snap', exact: true }).click();
await page.getByRole('button', { name: 'Perspective', exact: true }).click();
await page.getByRole('button', { name: 'Isometric', exact: true }).click();

for (const projection of ['Perspective', 'Orthographic']) {
await expect(page.getByRole('button', { name: projection, exact: true })).toBeVisible();
const before = await state(page);
expect(Math.abs(before.viewAxis[0])).toBeGreaterThan(0.3);
expect(Math.abs(before.viewAxis[1])).toBeGreaterThan(0.3);
const name = 'transform:rotate:view';
const center = await point(page, name);
const right = await point(page, name, [1.3, 0, 0]);
const top = await point(page, name, [0, 1.3, 0]);
expect(right.y).toBeCloseTo(center.y, 3);
expect(top.x).toBeCloseTo(center.x, 3);
expect(right.x - center.x).toBeCloseTo(center.y - top.y, 3);

const angle = (40 * Math.PI) / 180;
const end = await point(page, name, [1.3 * Math.cos(angle), 1.3 * Math.sin(angle), 0]);
await drag(page, right, end);
const after = await state(page);
const rotation = new Quaternion().setFromAxisAngle(
new Vector3().fromArray(before.viewAxis),
Math.PI / 4,
);
const expected = rotation.multiply(new Quaternion().fromArray(before.parts[0].quaternion));
expect(new Quaternion().fromArray(after.parts[0].quaternion).angleTo(expected)).toBeLessThan(
1e-6,
);
const pivot = (p: (typeof after.parts)[number]) =>
new Vector3()
.fromArray(cube.pivot)
.applyQuaternion(new Quaternion().fromArray(p.quaternion))
.add(new Vector3().fromArray(p.position));
expect(pivot(after.parts[0]).distanceTo(pivot(before.parts[0]))).toBeLessThan(1e-6);
expect(after.parts[0].scale).toEqual(before.parts[0].scale);
expect(after.past).toBe(before.past + 1);
expect(after.enabled).toBe(true);

if (projection === 'Perspective') {
await page.keyboard.press('5');
} else {
await page.keyboard.press('Control+z');
const restored = await state(page);
expect(restored.parts).toEqual(before.parts);
expect(restored.past).toBe(before.past);
}
}
});

test('preserves redo on a click without motion and restores camera input on interruption', async ({
page,
}) => {
Expand Down Expand Up @@ -235,6 +292,7 @@ test('shows only free joint rotation axes and keeps the anchor connected', async
expect(handles).not.toContain('transform:move:X');
expect(handles).not.toContain('transform:rotate:X');
expect(handles).not.toContain('transform:rotate:Z');
expect(handles).not.toContain('transform:rotate:view');
expect(handles).toContain('transform:rotate:Y');
const from = await point(page, 'transform:rotate:Y', [
0.78 * Math.cos(Math.PI / 4),
Expand Down
Loading