From 2198c1fe79b4a6ffad39ad11ba3cf02d4104c4ba Mon Sep 17 00:00:00 2001 From: Formsmith746 <214276465+Formsmith746@users.noreply.github.com> Date: Sun, 30 Aug 2026 15:54:43 +0300 Subject: [PATCH] release: SketchForge 1.0.8 --- README.md | 2 +- apps/web/src/components/SketchForgeEditor.tsx | 46 ++-- apps/web/src/components/WorkplaneViewport.tsx | 236 ++++++++++++------ .../components/workplane/TransformOverlay.tsx | 5 +- .../workplane/transformOverlayTypes.ts | 71 +++++- apps/web/src/lib/geometryRotation.ts | 76 ++++++ apps/web/src/lib/skfProject.ts | 2 +- docs/CHANGELOG.md | 8 + package-lock.json | 4 +- package.json | 2 +- tests/unit/geometryRotation.test.ts | 121 +++++++++ tests/unit/transformOverlayTypes.test.ts | 168 ++++++++++++- 12 files changed, 621 insertions(+), 120 deletions(-) create mode 100644 apps/web/src/lib/geometryRotation.ts create mode 100644 tests/unit/geometryRotation.test.ts diff --git a/README.md b/README.md index 3c7efbd..1224462 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,7 @@ Star SketchForge on GitHub Sponsor SketchForge on GitHub Local first - Version v1.0.7 + Version v1.0.8

diff --git a/apps/web/src/components/SketchForgeEditor.tsx b/apps/web/src/components/SketchForgeEditor.tsx index 5363442..c8b5c9c 100644 --- a/apps/web/src/components/SketchForgeEditor.tsx +++ b/apps/web/src/components/SketchForgeEditor.tsx @@ -86,6 +86,7 @@ import { import { cloneWorkplaneShapeSnapshot, compactEdgeTreatmentHistory, edgeTreatmentAppliedFrame, restoreShapeBeforeEdgeTreatment } from "@/lib/edgeTreatmentHistory"; import { appendEditorHistorySnapshot, boundedEditorHistoryState, editorHistoryEntry, editorHistoryForExport, hydrateEditorHistoryState, projectShapesFingerprint, type EditorHistoryEntry, type EditorHistoryExportLimit, type EditorHistoryState } from "@/lib/editorHistory"; import { snapShapeFootprintToVisibleGrid, visibleGridStep } from "@/lib/gridSnap"; +import { geometryRotationDegreesForShortcut, geometryRotationDelta, rotatedGeometryShapePatch } from "@/lib/geometryRotation"; import { createLocalId } from "@/lib/localIds"; import { projectExportFileName } from "@/lib/exportNames"; import { exportMeshesToObj } from "@/lib/objExport"; @@ -8868,10 +8869,14 @@ export function SketchForgeEditor({ [commitShapes, hasSelection, placementWorkplane, selectedIds, selectedShapes.length, shapes], ); - const rotateSelected45 = useCallback(() => { + const rotateSelectedBy = useCallback((angleDegrees: number) => { if (!hasSelection) { return; } + if (projectInteractionActiveRef.current) { + setNotice("Finish the current drag or transform before rotating"); + return; + } const selected = new Set(selectedIds); const rotatableShapes = selectedShapes.filter((shape) => !shape.locked); @@ -8880,17 +8885,7 @@ export function SketchForgeEditor({ return; } - const axis = new THREE.Vector3( - placementWorkplane.normal.x, - placementWorkplane.normal.y, - placementWorkplane.normal.z, - ); - if (axis.lengthSq() < 0.000001) { - axis.set(0, 1, 0); - } else { - axis.normalize(); - } - const rotationDelta = new THREE.Quaternion().setFromAxisAngle(axis, THREE.MathUtils.degToRad(45)); + const rotationDelta = geometryRotationDelta(placementWorkplane, angleDegrees); const pivot = rotatableShapes.length > 1 ? selectionCenterOnWorkplane(rotatableShapes, placementWorkplane) : null; const nextShapes = shapes.map((shape) => { @@ -8898,28 +8893,15 @@ export function SketchForgeEditor({ return shape; } - const nextQuaternion = rotationDelta.clone().multiply(quaternionForShape(shape)); - const rotationPatch = rotationFromQuaternion(nextQuaternion); - let rotated = canonicalizeShape({ ...shape, ...rotationPatch }); - - if (pivot) { - const startCenter = new THREE.Vector3(shape.x, (shape.elevation ?? 0) + shape.height / 2, shape.z); - const nextCenter = pivot.clone().add(startCenter.sub(pivot).applyQuaternion(rotationDelta)); - rotated = canonicalizeShape({ - ...rotated, - x: cleanNearZero(nextCenter.x, 0.0005), - z: cleanNearZero(nextCenter.z, 0.0005), - elevation: cleanNearZero(nextCenter.y - shape.height / 2, 0.0005), - }); - } - + const rotated = canonicalizeShape({ ...shape, ...rotatedGeometryShapePatch(shape, rotationDelta, pivot) }); return canonicalizeShape(bakeShapeTransformIntoMesh(rotated)); }); + const angleLabel = Number(angleDegrees.toFixed(1)); commitShapes( nextShapes, selectedIds, - `Rotated ${rotatableShapes.length} shape${rotatableShapes.length === 1 ? "" : "s"} by 45°`, + `Rotated ${rotatableShapes.length} shape${rotatableShapes.length === 1 ? "" : "s"} by ${angleLabel}°`, ); }, [commitShapes, hasSelection, placementWorkplane, selectedIds, selectedShapes, shapes]); @@ -9052,6 +9034,13 @@ export function SketchForgeEditor({ return; } + const geometryRotationDegrees = geometryRotationDegreesForShortcut(event); + if (geometryRotationDegrees !== null && hasSelection) { + event.preventDefault(); + rotateSelectedBy(geometryRotationDegrees); + return; + } + const step = event.shiftKey ? 5 : 1; if (shortcut && event.key === "ArrowUp") { event.preventDefault(); @@ -9103,6 +9092,7 @@ export function SketchForgeEditor({ pasteShape, raiseSelected, redo, + rotateSelectedBy, rotateSelectedClosedSketch45, sketchActive, sketchRedo, diff --git a/apps/web/src/components/WorkplaneViewport.tsx b/apps/web/src/components/WorkplaneViewport.tsx index d0bbe07..ddf92fd 100644 --- a/apps/web/src/components/WorkplaneViewport.tsx +++ b/apps/web/src/components/WorkplaneViewport.tsx @@ -52,9 +52,12 @@ import { TransformOverlay, continuousSnappedWheelRotation, getElevationMeasureKey, + isPointInsideTransformBounds, measureKeyForHandle, normalizedRotationPlaneBasis, - rotationWheelDirectionSign, + rotationPlaneDirectionSign, + transformBoundsIntersectClipVolume, + transformOverlayScreenPoint, ROTATION_WHEEL_SHIFT_SNAP_DEGREES, ROTATION_WHEEL_SNAP_DEGREES, snappedRotationDelta, @@ -279,6 +282,7 @@ type ThreeState = { workplanePreviewLayer: THREE.Group; shapeLayer: THREE.Group; helperLayer: THREE.Group; + transformGuideLayer: THREE.Group; moveDimensionLayer: THREE.Group; modifierLayer: THREE.Group; shapeRecords: Map; @@ -825,6 +829,58 @@ function syncMoveDimensionWorldLines( state.needsRender = true; } +function syncTransformGuideWorldLines( + state: ThreeState, + segments: Array | null, + theme: ResolvedAppTheme, +) { + const layer = state.transformGuideLayer; + const signature = segments + ? [ + theme, + ...segments.flatMap(([start, end]) => [start.x, start.y, start.z, end.x, end.y, end.z]), + ].join(":") + : ""; + if (layer.userData.transformGuideSignature === signature) { + return; + } + + layer.userData.transformGuideSignature = signature; + disposeChildren(layer); + if (!segments || segments.length === 0) { + state.needsRender = true; + return; + } + + const positions = segments.flatMap(([start, end]) => [start.x, start.y, start.z, end.x, end.y, end.z]); + const geometry = new LineSegmentsGeometry(); + geometry.setPositions(positions); + const material = new LineMaterial({ + color: theme === "dark" ? "#cfe1ea" : "#1f272e", + linewidth: 1.15, + worldUnits: false, + dashed: true, + dashSize: 0.625, + gapSize: 0.625, + transparent: true, + opacity: theme === "dark" ? 0.86 : 0.72, + depthTest: false, + depthWrite: false, + alphaToCoverage: false, + }); + material.toneMapped = false; + const rect = state.renderer.domElement.getBoundingClientRect(); + material.resolution.set(Math.max(1, rect.width), Math.max(1, rect.height)); + const lines = new LineSegments2(geometry, material); + lines.computeLineDistances(); + lines.renderOrder = 999; + lines.frustumCulled = false; + setObjectRenderLayer(lines, RENDER_LAYER_HELPERS); + freezeStaticObjectMatrices(lines); + layer.add(lines); + state.needsRender = true; +} + function rulerShapeDimensions(object: THREE.Object3D) { const dimensions = object.userData.rulerDimensions as [number, number, number] | undefined; return dimensions ?? [1, 1, 1]; @@ -2628,6 +2684,7 @@ export function WorkplaneViewport({ Boolean(transformRef.current || dragRef.current), false, placementWorkplaneRef.current, + resolvedThemeRef.current, ); syncAlignOverlay(threeRef.current, alignReferenceShapesRef.current, selectedIdsRef.current, alignModeRef.current, alignAnchorIdRef.current, alignHandlesRef.current, alignOverlayRef, setAlignOverlay); syncMirrorOverlay(threeRef.current, mirrorReferenceShapesRef.current, selectedIdsRef.current, mirrorModeRef.current, mirrorOverlayRef, setMirrorOverlay); @@ -2688,6 +2745,7 @@ export function WorkplaneViewport({ Boolean(transformRef.current || dragRef.current), false, placementWorkplaneRef.current, + resolvedThemeRef.current, ); syncAlignOverlay(threeRef.current, alignReferenceShapesRef.current, selectedIds, alignModeRef.current, alignAnchorIdRef.current, alignHandlesRef.current, alignOverlayRef, setAlignOverlay); syncMirrorOverlay(threeRef.current, mirrorReferenceShapesRef.current, selectedIds, mirrorModeRef.current, mirrorOverlayRef, setMirrorOverlay); @@ -2791,6 +2849,7 @@ export function WorkplaneViewport({ Boolean(transformRef.current || dragRef.current), false, placementWorkplaneRef.current, + resolvedThemeRef.current, ); } setSelectionHelpersVisible(state, !workplaneMode && transformRef.current?.kind !== "rotate"); @@ -2831,6 +2890,7 @@ export function WorkplaneViewport({ Boolean(transformRef.current || dragRef.current), false, placementWorkplaneRef.current, + resolvedThemeRef.current, ); syncRulerOverlay(threeRef.current, rulerModelRef.current, rulerOverlayRef, setRulerOverlay, workspace.accuracy); syncMoveDimensionWorldLines(threeRef.current, moveDimensionSessionRef.current, resolvedTheme); @@ -2906,6 +2966,7 @@ export function WorkplaneViewport({ Boolean(transformRef.current || dragRef.current), false, placementWorkplaneRef.current, + resolvedThemeRef.current, ); syncAlignOverlay(state, alignReferenceShapesRef.current, selectedIdsRef.current, alignModeRef.current, alignAnchorIdRef.current, alignHandlesRef.current, alignOverlayRef, setAlignOverlay); syncMirrorOverlay(state, mirrorReferenceShapesRef.current, selectedIdsRef.current, mirrorModeRef.current, mirrorOverlayRef, setMirrorOverlay); @@ -2952,6 +3013,7 @@ export function WorkplaneViewport({ disposeChildren(state.shapeLayer); state.shapeRecords.clear(); disposeChildren(state.helperLayer); + disposeChildren(state.transformGuideLayer); disposeChildren(state.moveDimensionLayer); disposeChildren(state.modifierLayer); state.renderer.dispose(); @@ -2969,6 +3031,25 @@ export function WorkplaneViewport({ }; }, []); + useEffect(() => { + const state = threeRef.current; + if (!state) { + return; + } + const visible = !workplaneMode + && !alignMode + && !mirrorMode + && !rulerMode + && !rulerDeleteMode + && !rulerMoveMode + && !modifierActive + && activeTransformKind !== "rotate"; + if (state.transformGuideLayer.visible !== visible) { + state.transformGuideLayer.visible = visible; + state.needsRender = true; + } + }, [activeTransformKind, alignMode, mirrorMode, modifierActive, rulerDeleteMode, rulerMode, rulerMoveMode, workplaneMode]); + useEffect(() => { window.sketchforgePerf = { get: () => { @@ -3680,13 +3761,13 @@ export function WorkplaneViewport({ ); const rawPointerAngle = rotationPlanePointerAngle(transform.rotationPlaneView, localClientX, localClientY, rotationCenter); const wheelSnapDegrees = shiftKey ? ROTATION_WHEEL_SHIFT_SNAP_DEGREES : ROTATION_WHEEL_SNAP_DEGREES; - const wheelScreenSign = rotationWheelDirectionSign(transform.rotationScreenSign ?? 1); + const wheelDirectionSign = transform.rotationPlaneView?.directionSign ?? (transform.rotationAxis === "z" ? 1 : -1); const snappedWheel = insideSnapWheel ? snappedWheelRotation( rawPointerAngle, transform.rotationStartPointerAngle - ?? rawPointerAngle - rawDelta * (transform.rotationScreenSign ?? 1), - wheelScreenSign, + ?? rawPointerAngle - rawDelta * wheelDirectionSign, + wheelDirectionSign, wheelSnapDegrees, ) : null; @@ -4520,6 +4601,7 @@ export function WorkplaneViewport({ true, true, placementWorkplaneRef.current, + resolvedThemeRef.current, ); syncCutPreviewOverlays(threeRef.current, previewShapes); syncMoveDimensionOverlay( @@ -5232,13 +5314,16 @@ function createThreeScene(host: HTMLDivElement): ThreeState { const helperLayer = new THREE.Group(); helperLayer.name = "SelectionHelpers"; helperLayer.layers.set(RENDER_LAYER_HELPERS); + const transformGuideLayer = new THREE.Group(); + transformGuideLayer.name = "TransformGuides"; + transformGuideLayer.layers.set(RENDER_LAYER_HELPERS); const moveDimensionLayer = new THREE.Group(); moveDimensionLayer.name = "MoveDimensions"; moveDimensionLayer.layers.set(RENDER_LAYER_HELPERS); const modifierLayer = new THREE.Group(); modifierLayer.name = "EdgeModifier"; modifierLayer.layers.set(RENDER_LAYER_MODIFIERS); - scene.add(workplaneLayer, workplanePreviewLayer, shapeLayer, helperLayer, moveDimensionLayer, modifierLayer); + scene.add(workplaneLayer, workplanePreviewLayer, shapeLayer, helperLayer, transformGuideLayer, moveDimensionLayer, modifierLayer); const raycaster = new THREE.Raycaster(); raycaster.params.Line = { threshold: 1.15 }; @@ -5251,13 +5336,15 @@ function createThreeScene(host: HTMLDivElement): ThreeState { const height = Math.max(1, host.clientHeight); renderer.setSize(width, height); updateCameraViewport(state.camera, width, height); - state.moveDimensionLayer.traverse((child) => { - const material = (child as THREE.Mesh).material; - const materials = Array.isArray(material) ? material : material ? [material] : []; - materials.forEach((candidate) => { - if (candidate instanceof LineMaterial) { - candidate.resolution.set(width, height); - } + [state.transformGuideLayer, state.moveDimensionLayer].forEach((layer) => { + layer.traverse((child) => { + const material = (child as THREE.Mesh).material; + const materials = Array.isArray(material) ? material : material ? [material] : []; + materials.forEach((candidate) => { + if (candidate instanceof LineMaterial) { + candidate.resolution.set(width, height); + } + }); }); }); state.needsRender = true; @@ -5272,6 +5359,7 @@ function createThreeScene(host: HTMLDivElement): ThreeState { workplanePreviewLayer, shapeLayer, helperLayer, + transformGuideLayer, moveDimensionLayer, modifierLayer, shapeRecords: new Map(), @@ -6317,8 +6405,10 @@ function syncTransformOverlay( keepVisibleDuringInteraction = false, updateDomImmediately = false, workplane: PlacementWorkplane = horizontalPlacementWorkplane(), + theme: ResolvedAppTheme = "light", ) { if (selectedIds.length < 1) { + syncTransformGuideWorldLines(state, null, theme); if (overlayRef.current) { overlayRef.current = null; setOverlay(null); @@ -6329,6 +6419,7 @@ function syncTransformOverlay( const activeWorkplane = workplane; const frame = selectionFrameForShapes(shapes, selectedIds, activeWorkplane); if (!frame) { + syncTransformGuideWorldLines(state, null, theme); if (overlayRef.current) { overlayRef.current = null; setOverlay(null); @@ -6342,38 +6433,26 @@ function syncTransformOverlay( // camera matrix can otherwise be one frame stale, making handles/lines trail. state.camera.updateMatrixWorld(); const corners = selectionFrameCorners(frame); - const projectedCorners = corners.map((corner) => { - const cameraSpace = corner.clone().applyMatrix4(state.camera.matrixWorldInverse); - const projected = corner.clone().project(state.camera); - return { cameraSpace, projected }; - }); - const nearPlane = state.camera instanceof THREE.PerspectiveCamera ? state.camera.near : 0.1; - const selectionRadius = Math.max(MIN_SHAPE_SIZE, Math.sqrt(frame.width ** 2 + frame.height ** 2 + frame.depth ** 2) / 2); - const cameraDistance = state.camera.position.distanceTo(frame.center); - // When zoomed into/through a selected object, the projected overlay can span - // thousands of pixels even before any corner crosses the near plane. Hide it - // at that depth instead of drawing misleading dashed lines across the scene. - const cameraInsideSelection = cameraDistance < selectionRadius * 1.12; - const projectionInvalid = projectedCorners.some(({ cameraSpace, projected }) => cameraSpace.z > -nearPlane * 1.5 || !Number.isFinite(projected.x) || !Number.isFinite(projected.y)); - const projectedSpanTooLarge = (() => { - const xs = projectedCorners.map(({ projected }) => ((projected.x + 1) / 2) * rect.width); - const ys = projectedCorners.map(({ projected }) => ((1 - projected.y) / 2) * rect.height); - return Math.max(...xs) - Math.min(...xs) > rect.width * 4 || Math.max(...ys) - Math.min(...ys) > rect.height * 4; - })(); - const overlayTooClose = projectionInvalid || (!keepVisibleDuringInteraction && (cameraInsideSelection || projectedSpanTooLarge)); - if (overlayTooClose) { + const viewProjection = new THREE.Matrix4().multiplyMatrices(state.camera.projectionMatrix, state.camera.matrixWorldInverse); + const selectionIntersectsView = transformBoundsIntersectClipVolume(corners.map((corner) => { + const clip = new THREE.Vector4(corner.x, corner.y, corner.z, 1).applyMatrix4(viewProjection); + return { x: clip.x, y: clip.y, z: clip.z, w: clip.w }; + })); + if (!selectionIntersectsView && !keepVisibleDuringInteraction) { + syncTransformGuideWorldLines(state, null, theme); if (overlayRef.current) { overlayRef.current = null; setOverlay(null); } return; } + const cameraDistance = state.camera.position.distanceTo(frame.center); + const cameraInSelectionFrame = frameLocalPoint(frame, state.camera.position); + const cameraInsideSelection = isPointInsideTransformBounds(cameraInSelectionFrame, frame.min, frame.max); const project = (point: THREE.Vector3) => { - const projected = point.clone().project(state.camera); - return { - x: ((projected.x + 1) / 2) * rect.width, - y: ((1 - projected.y) / 2) * rect.height, - }; + const cameraSpace = point.clone().applyMatrix4(state.camera.matrixWorldInverse); + const projected = cameraSpace.clone().applyMatrix4(state.camera.projectionMatrix); + return transformOverlayScreenPoint(projected, cameraSpace.z, rect.width, rect.height); }; const xFootAxis = frame.xAxis.clone().normalize(); @@ -6397,6 +6476,13 @@ function syncTransformOverlay( }; const bottomCenterWorld = framePoint(frame, 0, footprintY, 0); const topCenterWorld = framePoint(frame, 0, oppositeY, 0); + syncTransformGuideWorldLines(state, [ + [topCenterWorld, bottomCenterWorld], + [footprintWorld.nearLeft, footprintWorld.nearRight], + [footprintWorld.nearRight, footprintWorld.farRight], + [footprintWorld.farRight, footprintWorld.farLeft], + [footprintWorld.farLeft, footprintWorld.nearLeft], + ], theme); const lowerCenterWorld = framePoint(frame, 0, frame.min.y, 0); const upperCenterWorld = framePoint(frame, 0, frame.max.y, 0); const liftOffset = Math.max(2, frame.height * 0.08); @@ -6415,8 +6501,6 @@ function syncTransformOverlay( far: project(footprintWorld.far), left: project(footprintWorld.left), }; - const bottomCenterPoint = project(bottomCenterWorld); - const topPoint = project(topCenterWorld); const heightPoint = project(showLowerHandles ? lowerCenterWorld : upperCenterWorld); const liftPoint = project(liftHandle); const liftBasePoint = project(showLowerHandles ? lowerCenterWorld : upperCenterWorld); @@ -6425,12 +6509,6 @@ function syncTransformOverlay( ); const liftHandleAngle = liftTargetAngle - (showLowerHandles ? 90 : -90); const centerPoint = project(frame.center); - const footprintGuides = [ - { x1: bottom.nearLeft.x, y1: bottom.nearLeft.y, x2: bottom.nearRight.x, y2: bottom.nearRight.y }, - { x1: bottom.nearRight.x, y1: bottom.nearRight.y, x2: bottom.farRight.x, y2: bottom.farRight.y }, - { x1: bottom.farRight.x, y1: bottom.farRight.y, x2: bottom.farLeft.x, y2: bottom.farLeft.y }, - { x1: bottom.farLeft.x, y1: bottom.farLeft.y, x2: bottom.nearLeft.x, y2: bottom.nearLeft.y }, - ]; const widthLabel = formatMeasure(frame.width, accuracy); const depthLabel = formatMeasure(frame.depth, accuracy); const heightLabel = formatMeasure(frame.height, accuracy); @@ -6508,9 +6586,12 @@ function syncTransformOverlay( } return framePoint(frame, 0, y, frame.min.z); }; - const rotateLeft = screenOffsetFromCenter(project(sidePoint(rotationSides.x, frame.max.y)), 24); - const rotateRight = screenOffsetFromCenter(project(sidePoint(rotationSides.z, frame.max.y)), 28); - const rotateBottomAnchor = screenOffsetFromCenter(project(sidePoint(rotationSides.y, footprintY)), 26); + const rotateLeftSource = project(sidePoint(rotationSides.x, frame.max.y)); + const rotateRightSource = project(sidePoint(rotationSides.z, frame.max.y)); + const rotateBottomSource = project(sidePoint(rotationSides.y, footprintY)); + const rotateLeft = screenOffsetFromCenter(rotateLeftSource, 24); + const rotateRight = screenOffsetFromCenter(rotateRightSource, 28); + const rotateBottomAnchor = screenOffsetFromCenter(rotateBottomSource, 26); const rotateBottom = { ...rotateBottomAnchor, y: rotateBottomAnchor.y - 5 }; const xFaceCenter = sidePoint(rotationSides.x, 0); const zFaceCenter = sidePoint(rotationSides.z, 0); @@ -6524,7 +6605,8 @@ function syncTransformOverlay( : { u: zFootAxis, v: xFootAxis.clone().multiplyScalar(-1) }; const planeRadius = 154; const planeWorldStep = Math.max(0.1, cameraDistance * 0.01); - const makePlaneView = (centerWorld: THREE.Vector3, uAxis: THREE.Vector3, vAxis: THREE.Vector3): RotationPlaneView => { + const makePlaneView = (centerWorld: THREE.Vector3, uAxis: THREE.Vector3, vAxis: THREE.Vector3, axisVector: THREE.Vector3): RotationPlaneView => { + const directionSign = rotationPlaneDirectionSign(axisVector, uAxis, vAxis); const screenCenter = project(centerWorld); const uOffset = uAxis.clone().multiplyScalar(planeWorldStep); const vOffset = vAxis.clone().multiplyScalar(planeWorldStep); @@ -6536,7 +6618,7 @@ function syncTransformOverlay( const dv = { x: (vEnd.x - vStart.x) / 2, y: (vEnd.y - vStart.y) / 2 }; const longest = Math.max(Math.hypot(du.x, du.y), Math.hypot(dv.x, dv.y)); if (!Number.isFinite(longest) || longest < 0.000001) { - return { x: screenCenter.x, y: screenCenter.y, a: 1, b: 0, c: 0, d: 1 }; + return { x: screenCenter.x, y: screenCenter.y, a: 1, b: 0, c: 0, d: 1, directionSign }; } const scale = planeRadius / longest / 100; return { @@ -6546,6 +6628,7 @@ function syncTransformOverlay( b: du.y * scale, c: dv.x * scale, d: dv.y * scale, + directionSign, }; }; const makeWheel = (centerWorld: THREE.Vector3) => { @@ -6564,9 +6647,9 @@ function syncTransformOverlay( z: makeWorldPoint(zFaceCenter), }; const rotationPlanes: Record = { - x: makePlaneView(xFaceCenter, zFootAxis, yFootAxis), - y: makePlaneView(yFaceCenter, xFootAxis, zFootAxis), - z: makePlaneView(zFaceCenter, xFootAxis, yFootAxis), + x: makePlaneView(xFaceCenter, zFootAxis, yFootAxis, xFootAxis), + y: makePlaneView(yFaceCenter, xFootAxis, zFootAxis, yFootAxis), + z: makePlaneView(zFaceCenter, xFootAxis, yFootAxis, zFootAxis), }; const makeCameraPlaneView = (uAxis: THREE.Vector3, vAxis: THREE.Vector3): RotationPlaneView => { const u = uAxis.clone().transformDirection(state.camera.matrixWorldInverse); @@ -6582,31 +6665,32 @@ function syncTransformOverlay( z: makeCameraPlaneView(xFootAxis, yFootAxis), }; + const handles = [ + { point: bottom.nearLeft, handle: { key: "near-left", className: "corner", kind: "scale" as const, x: bottom.nearLeft.x, y: bottom.nearLeft.y, title: "Resize" } }, + { point: bottom.nearRight, handle: { key: "near-right", className: "corner", kind: "scale" as const, x: bottom.nearRight.x, y: bottom.nearRight.y, title: "Resize" } }, + { point: bottom.farRight, handle: { key: "far-right", className: "corner", kind: "scale" as const, x: bottom.farRight.x, y: bottom.farRight.y, title: "Resize" } }, + { point: bottom.farLeft, handle: { key: "far-left", className: "corner", kind: "scale" as const, x: bottom.farLeft.x, y: bottom.farLeft.y, title: "Resize" } }, + { point: mid.near, handle: { key: "near-mid", className: "edge dark", kind: "scale" as const, x: mid.near.x, y: mid.near.y, title: "Resize" } }, + { point: mid.right, handle: { key: "right-mid", className: "edge dark", kind: "scale" as const, x: mid.right.x, y: mid.right.y, title: "Resize" } }, + { point: mid.far, handle: { key: "far-mid", className: "edge dark", kind: "scale" as const, x: mid.far.x, y: mid.far.y, title: "Resize" } }, + { point: mid.left, handle: { key: "left-mid", className: "edge dark", kind: "scale" as const, x: mid.left.x, y: mid.left.y, title: "Resize" } }, + { point: heightPoint, handle: { key: heightHandleKey, className: "height-top", kind: "height" as const, x: heightPoint.x, y: heightPoint.y, title: "Height" } }, + { point: liftPoint, handle: { key: liftHandleKey, className: showLowerHandles ? "height-lift lower" : "height-lift", kind: "lift" as const, x: liftPoint.x, y: liftPoint.y, title: "Lift", angle: liftHandleAngle } }, + ].filter(({ point }) => point.visible).map(({ handle }) => handle); + const rotationChromeVisible = !cameraInsideSelection && centerPoint.visible; + const rotateHandles = rotationChromeVisible ? [ + rotateLeftSource.visible ? { key: "rotate-left", className: "screen-left", x: rotateLeft.x, y: rotateLeft.y, plane: normalizedRotationPlaneBasis(rotationHandlePlanes.x, true) } : null, + rotateRightSource.visible ? { key: "rotate-right", className: "screen-right", x: rotateRight.x, y: rotateRight.y, plane: normalizedRotationPlaneBasis(rotationHandlePlanes.z, true) } : null, + rotateBottomSource.visible ? { key: "rotate-bottom", className: "screen-bottom", x: rotateBottom.x, y: rotateBottom.y, plane: normalizedRotationPlaneBasis(rotationHandlePlanes.y, true) } : null, + ].filter((handle): handle is NonNullable => Boolean(handle)) : []; + const next = { id: frame.ids.join("|"), width: rect.width, height: rect.height, - guides: [ - { x1: topPoint.x, y1: topPoint.y, x2: bottomCenterPoint.x, y2: bottomCenterPoint.y }, - ...footprintGuides, - ], - handles: [ - { key: "near-left", className: "corner", kind: "scale" as const, x: bottom.nearLeft.x, y: bottom.nearLeft.y, title: "Resize" }, - { key: "near-right", className: "corner", kind: "scale" as const, x: bottom.nearRight.x, y: bottom.nearRight.y, title: "Resize" }, - { key: "far-right", className: "corner", kind: "scale" as const, x: bottom.farRight.x, y: bottom.farRight.y, title: "Resize" }, - { key: "far-left", className: "corner", kind: "scale" as const, x: bottom.farLeft.x, y: bottom.farLeft.y, title: "Resize" }, - { key: "near-mid", className: "edge dark", kind: "scale" as const, x: mid.near.x, y: mid.near.y, title: "Resize" }, - { key: "right-mid", className: "edge dark", kind: "scale" as const, x: mid.right.x, y: mid.right.y, title: "Resize" }, - { key: "far-mid", className: "edge dark", kind: "scale" as const, x: mid.far.x, y: mid.far.y, title: "Resize" }, - { key: "left-mid", className: "edge dark", kind: "scale" as const, x: mid.left.x, y: mid.left.y, title: "Resize" }, - { key: heightHandleKey, className: "height-top", kind: "height" as const, x: heightPoint.x, y: heightPoint.y, title: "Height" }, - { key: liftHandleKey, className: showLowerHandles ? "height-lift lower" : "height-lift", kind: "lift" as const, x: liftPoint.x, y: liftPoint.y, title: "Lift", angle: liftHandleAngle }, - ], - rotateHandles: [ - { key: "rotate-left", className: "screen-left", x: rotateLeft.x, y: rotateLeft.y, plane: normalizedRotationPlaneBasis(rotationHandlePlanes.x, true) }, - { key: "rotate-right", className: "screen-right", x: rotateRight.x, y: rotateRight.y, plane: normalizedRotationPlaneBasis(rotationHandlePlanes.z, true) }, - { key: "rotate-bottom", className: "screen-bottom", x: rotateBottom.x, y: rotateBottom.y, plane: normalizedRotationPlaneBasis(rotationHandlePlanes.y, true) }, - ], + guides: [], + handles, + rotateHandles, dimensions: dimensionMarks, rotationWheel: rotationWheels.y, rotationWheels, @@ -7151,7 +7235,7 @@ function sharedShapeMaterial(shape: WorkplaneShape) { transparent: Boolean(shape.hole), opacity: shape.hole ? (shape.importedMesh ? 0.34 : 0.52) : 1, roughness: shape.hole ? 0.88 : 0.57, - side: shape.importedMesh?.sourceFormat === "json" || mirroredAxisCount(shape) % 2 === 1 ? "double" : "front", + side: "double", }); const cached = sharedShapeMaterialCache.get(key); if (cached) { @@ -7165,7 +7249,7 @@ function sharedShapeMaterial(shape: WorkplaneShape) { opacity: shape.hole ? (shape.importedMesh ? 0.34 : 0.52) : 1, roughness: shape.hole ? 0.88 : 0.57, metalness: 0.02, - side: shape.importedMesh?.sourceFormat === "json" || mirroredAxisCount(shape) % 2 === 1 ? THREE.DoubleSide : THREE.FrontSide, + side: THREE.DoubleSide, }); material.userData.cached = true; material.userData.sharedShapeMaterialKey = key; diff --git a/apps/web/src/components/workplane/TransformOverlay.tsx b/apps/web/src/components/workplane/TransformOverlay.tsx index 66287f5..bb3d894 100644 --- a/apps/web/src/components/workplane/TransformOverlay.tsx +++ b/apps/web/src/components/workplane/TransformOverlay.tsx @@ -9,9 +9,12 @@ import { export { continuousSnappedWheelRotation, getElevationMeasureKey, + isPointInsideTransformBounds, measureKeyForHandle, normalizedRotationPlaneBasis, - rotationWheelDirectionSign, + rotationPlaneDirectionSign, + transformBoundsIntersectClipVolume, + transformOverlayScreenPoint, snappedRotationDelta, snappedWheelRotation, ROTATION_WHEEL_SHIFT_SNAP_DEGREES, diff --git a/apps/web/src/components/workplane/transformOverlayTypes.ts b/apps/web/src/components/workplane/transformOverlayTypes.ts index 0ba8021..ba4fc6f 100644 --- a/apps/web/src/components/workplane/transformOverlayTypes.ts +++ b/apps/web/src/components/workplane/transformOverlayTypes.ts @@ -11,15 +11,78 @@ export type RotationPlaneView = { b: number; c: number; d: number; + directionSign?: number; }; export type RotationPlaneBasis = Pick; +export type TransformOverlayPoint = { x: number; y: number }; +export type TransformOverlayPoint3D = TransformOverlayPoint & { z: number }; +export type TransformOverlayClipPoint = TransformOverlayPoint3D & { w: number }; + +export function isPointInsideTransformBounds( + point: TransformOverlayPoint3D, + min: TransformOverlayPoint3D, + max: TransformOverlayPoint3D, +) { + return point.x >= min.x + && point.x <= max.x + && point.y >= min.y + && point.y <= max.y + && point.z >= min.z + && point.z <= max.z; +} + +export function transformBoundsIntersectClipVolume(points: TransformOverlayClipPoint[]) { + if (points.length === 0 || points.some((point) => ![point.x, point.y, point.z, point.w].every(Number.isFinite))) { + return false; + } + + // A convex selection box is outside the camera frustum only when every one + // of its corners is beyond the same homogeneous clip plane. Checking the + // planes before dividing by w also handles boxes behind the camera and boxes + // that surround the camera during close zoom. + const outsidePlanes = [ + (point: TransformOverlayClipPoint) => point.x < -point.w, + (point: TransformOverlayClipPoint) => point.x > point.w, + (point: TransformOverlayClipPoint) => point.y < -point.w, + (point: TransformOverlayClipPoint) => point.y > point.w, + (point: TransformOverlayClipPoint) => point.z < -point.w, + (point: TransformOverlayClipPoint) => point.z > point.w, + ]; + return !outsidePlanes.some((isOutside) => points.every(isOutside)); +} + +export function transformOverlayScreenPoint( + projectedNdc: TransformOverlayPoint, + cameraSpaceZ: number, + width: number, + height: number, +) { + const x = ((projectedNdc.x + 1) / 2) * width; + const y = ((1 - projectedNdc.y) / 2) * height; + return { + x, + y, + visible: cameraSpaceZ < -0.0001 && Number.isFinite(x) && Number.isFinite(y), + }; +} + export const ROTATION_WHEEL_SNAP_DEGREES = 45; export const ROTATION_WHEEL_SHIFT_SNAP_DEGREES = 22.5; -export function rotationWheelDirectionSign(screenSign: number) { - return screenSign < 0 ? 1 : -1; +type RotationDirectionVector = { x: number; y: number; z: number }; + +export function rotationPlaneDirectionSign( + axis: RotationDirectionVector, + uAxis: RotationDirectionVector, + vAxis: RotationDirectionVector, +) { + const crossX = uAxis.y * vAxis.z - uAxis.z * vAxis.y; + const crossY = uAxis.z * vAxis.x - uAxis.x * vAxis.z; + const crossZ = uAxis.x * vAxis.y - uAxis.y * vAxis.x; + const alignment = axis.x * crossX + axis.y * crossY + axis.z * crossZ; + return alignment < 0 ? -1 : 1; } export function snappedRotationDelta(rawDelta: number, insideSnapWheel: boolean, shiftKey: boolean) { @@ -30,7 +93,7 @@ export function snappedRotationDelta(rawDelta: number, insideSnapWheel: boolean, export function snappedWheelRotation( pointerAngle: number, startPointerAngle: number, - screenSign = 1, + directionSign = 1, snapDegrees = ROTATION_WHEEL_SNAP_DEGREES, ) { const snappedPointerAngle = Math.round(pointerAngle / snapDegrees) * snapDegrees; @@ -38,7 +101,7 @@ export function snappedWheelRotation( let pointerDelta = snappedPointerAngle - snappedStartPointerAngle; while (pointerDelta > 180) pointerDelta -= 360; while (pointerDelta <= -180) pointerDelta += 360; - const direction = screenSign < 0 ? -1 : 1; + const direction = directionSign < 0 ? -1 : 1; const delta = pointerDelta * direction; return { delta: delta === 0 ? 0 : delta, diff --git a/apps/web/src/lib/geometryRotation.ts b/apps/web/src/lib/geometryRotation.ts new file mode 100644 index 0000000..41a7fb8 --- /dev/null +++ b/apps/web/src/lib/geometryRotation.ts @@ -0,0 +1,76 @@ +import * as THREE from "three"; +import type { PlacementWorkplane } from "@/lib/placementWorkplane"; +import { cleanNearZero, cleanRotationDegrees } from "@/lib/workplaneShapes"; +import type { WorkplaneShape } from "@/types/sketchforge"; + +export const GEOMETRY_ROTATION_STEP_DEGREES = 45; +export const GEOMETRY_FINE_ROTATION_STEP_DEGREES = 22.5; + +type GeometryRotationShortcutEvent = { + altKey: boolean; + code: string; + ctrlKey: boolean; + key: string; + metaKey: boolean; + shiftKey: boolean; +}; + +export function geometryRotationDegreesForShortcut(event: GeometryRotationShortcutEvent) { + if (event.ctrlKey || event.metaKey || event.altKey) { + return null; + } + if (event.code !== "KeyR" && event.key.toLowerCase() !== "r") { + return null; + } + return event.shiftKey ? GEOMETRY_FINE_ROTATION_STEP_DEGREES : GEOMETRY_ROTATION_STEP_DEGREES; +} + +export function geometryRotationDelta(workplane: PlacementWorkplane, degrees: number) { + const axis = new THREE.Vector3(workplane.normal.x, workplane.normal.y, workplane.normal.z); + if (axis.lengthSq() < 0.000001) { + axis.set(0, 1, 0); + } else { + axis.normalize(); + } + return new THREE.Quaternion().setFromAxisAngle(axis, THREE.MathUtils.degToRad(Number.isFinite(degrees) ? degrees : 0)); +} + +function quaternionForShape(shape: WorkplaneShape) { + return new THREE.Quaternion().setFromEuler( + new THREE.Euler( + THREE.MathUtils.degToRad(shape.rotationX ?? 0), + THREE.MathUtils.degToRad(shape.rotation), + THREE.MathUtils.degToRad(shape.rotationZ ?? 0), + "XYZ", + ), + ); +} + +function rotationPatchFromQuaternion(quaternion: THREE.Quaternion) { + const euler = new THREE.Euler().setFromQuaternion(quaternion, "XYZ"); + return { + rotationX: cleanRotationDegrees(THREE.MathUtils.radToDeg(euler.x)), + rotation: cleanRotationDegrees(THREE.MathUtils.radToDeg(euler.y)), + rotationZ: cleanRotationDegrees(THREE.MathUtils.radToDeg(euler.z)), + }; +} + +export function rotatedGeometryShapePatch( + shape: WorkplaneShape, + rotationDelta: THREE.Quaternion, + pivot: THREE.Vector3 | null, +): Partial { + const patch: Partial = rotationPatchFromQuaternion( + rotationDelta.clone().multiply(quaternionForShape(shape)), + ); + + if (pivot) { + const startCenter = new THREE.Vector3(shape.x, (shape.elevation ?? 0) + shape.height / 2, shape.z); + const nextCenter = pivot.clone().add(startCenter.sub(pivot).applyQuaternion(rotationDelta)); + patch.x = cleanNearZero(nextCenter.x, 0.0005); + patch.z = cleanNearZero(nextCenter.z, 0.0005); + patch.elevation = cleanNearZero(nextCenter.y - shape.height / 2, 0.0005); + } + + return patch; +} diff --git a/apps/web/src/lib/skfProject.ts b/apps/web/src/lib/skfProject.ts index 4e03557..02db9ce 100644 --- a/apps/web/src/lib/skfProject.ts +++ b/apps/web/src/lib/skfProject.ts @@ -12,7 +12,7 @@ import type { GridSize, ProjectAsset, ProjectAssetSourceFormat, SketchOperation, export const SKF_SCHEMA_ID = "com.sketchforge.project"; export const SKF_FORMAT_VERSION = 1; export const SKF_MINIMUM_READER_VERSION = 1; -export const SKF_CREATED_WITH_VERSION = "1.0.7"; +export const SKF_CREATED_WITH_VERSION = "1.0.8"; export const SKF_MEDIA_TYPE = "application/vnd.sketchforge.project+zip"; export const SKF_LIMITS = { diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 63898f0..ccbf5da 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.0.8 + +- Duplicated objects now stay in the exact position of their source instead of receiving an automatic offset. +- Added geometry shortcuts: `R` rotates selected objects by 45 degrees and `Shift+R` rotates them by 22.5 degrees around the active workplane normal. +- Corrected rotation controls so objects turn in the direction indicated by the pointer on every rotation plane. +- Kept selection outlines, resize anchors, and height controls stable during close zoom while naturally hiding controls that leave the viewport. +- Kept object faces visible from inside the object and hid rotation controls while the camera is inside the selection. + ## 1.0.7 - Raised the supported `project.json` size in `.skf` packages from 32 MiB to 64 MiB and compacted new project exports without removing editable data. diff --git a/package-lock.json b/package-lock.json index 9ff40c7..6aa5238 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "sketchforge", - "version": "1.0.7", + "version": "1.0.8", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "sketchforge", - "version": "1.0.7", + "version": "1.0.8", "license": "AGPL-3.0-only", "dependencies": { "@tailwindcss/postcss": "^4.1.8", diff --git a/package.json b/package.json index dc3e4df..5e7009b 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "sketchforge", - "version": "1.0.7", + "version": "1.0.8", "private": true, "description": "A local-first 3D design editor.", "author": { diff --git a/tests/unit/geometryRotation.test.ts b/tests/unit/geometryRotation.test.ts new file mode 100644 index 0000000..c5898d6 --- /dev/null +++ b/tests/unit/geometryRotation.test.ts @@ -0,0 +1,121 @@ +import { describe, expect, it } from "vitest"; +import * as THREE from "three"; +import { + GEOMETRY_FINE_ROTATION_STEP_DEGREES, + GEOMETRY_ROTATION_STEP_DEGREES, + geometryRotationDegreesForShortcut, + geometryRotationDelta, + rotatedGeometryShapePatch, +} from "@/lib/geometryRotation"; +import { horizontalPlacementWorkplane, placementWorkplaneFromSurface } from "@/lib/placementWorkplane"; +import type { WorkplaneShape } from "@/types/sketchforge"; + +function shape(overrides: Partial = {}): WorkplaneShape { + return { + id: "box-1", + name: "Box", + kind: "box", + color: "#d41721", + x: 0, + z: 0, + elevation: 0, + size: 20, + width: 20, + depth: 20, + height: 20, + rotation: 0, + locked: false, + hidden: false, + ...overrides, + }; +} + +function shortcut(overrides: Partial[0]> = {}) { + return geometryRotationDegreesForShortcut({ + altKey: false, + code: "KeyR", + ctrlKey: false, + key: "r", + metaKey: false, + shiftKey: false, + ...overrides, + }); +} + +describe("geometry rotation shortcut", () => { + it("maps R to 45 degrees and Shift+R to 22.5 degrees", () => { + expect(shortcut()).toBe(GEOMETRY_ROTATION_STEP_DEGREES); + expect(shortcut({ key: "R", shiftKey: true })).toBe(GEOMETRY_FINE_ROTATION_STEP_DEGREES); + }); + + it("does not intercept browser, command, Alt, or unrelated shortcuts", () => { + expect(shortcut({ ctrlKey: true })).toBeNull(); + expect(shortcut({ metaKey: true })).toBeNull(); + expect(shortcut({ altKey: true })).toBeNull(); + expect(shortcut({ code: "KeyT", key: "t" })).toBeNull(); + }); + + it("uses the physical R key even when the keyboard layout reports another character", () => { + expect(shortcut({ key: "ρ" })).toBe(GEOMETRY_ROTATION_STEP_DEGREES); + }); +}); + +describe("geometry rotation transform", () => { + it("rotates an object 45 degrees around the base workplane normal", () => { + const delta = geometryRotationDelta(horizontalPlacementWorkplane(), 45); + const patch = rotatedGeometryShapePatch(shape(), delta, null); + + expect(patch).toMatchObject({ rotationX: 0, rotation: 45, rotationZ: 0 }); + expect(patch).not.toHaveProperty("x"); + expect(patch).not.toHaveProperty("elevation"); + }); + + it("preserves the fine 22.5-degree step on an oriented workplane", () => { + const vertical = placementWorkplaneFromSurface( + { x: 0, y: 0, z: 0 }, + { x: 1, y: 0, z: 0 }, + { x: 0, y: 1, z: 0 }, + ); + const delta = geometryRotationDelta(vertical, 22.5); + const patch = rotatedGeometryShapePatch(shape(), delta, null); + + expect(patch).toMatchObject({ rotationX: 22.5, rotation: 0, rotationZ: 0 }); + }); + + it("rotates multi-object centers around the shared selection pivot", () => { + const delta = geometryRotationDelta(horizontalPlacementWorkplane(), 90); + const patch = rotatedGeometryShapePatch(shape({ x: 10, elevation: 4 }), delta, new THREE.Vector3(0, 14, 0)); + + expect(patch.x).toBeCloseTo(0, 8); + expect(patch.z).toBeCloseTo(-10, 8); + expect(patch.elevation).toBeCloseTo(4, 8); + }); + + it("pre-multiplies the shortcut around the world workplane axis for compound rotations", () => { + const source = shape({ rotationX: 18, rotation: 31, rotationZ: 12 }); + const delta = geometryRotationDelta(horizontalPlacementWorkplane(), 22.5); + const patch = rotatedGeometryShapePatch(source, delta, null); + const actual = new THREE.Quaternion().setFromEuler(new THREE.Euler( + THREE.MathUtils.degToRad(patch.rotationX ?? 0), + THREE.MathUtils.degToRad(patch.rotation ?? 0), + THREE.MathUtils.degToRad(patch.rotationZ ?? 0), + "XYZ", + )); + const sourceQuaternion = new THREE.Quaternion().setFromEuler(new THREE.Euler( + THREE.MathUtils.degToRad(source.rotationX ?? 0), + THREE.MathUtils.degToRad(source.rotation), + THREE.MathUtils.degToRad(source.rotationZ ?? 0), + "XYZ", + )); + const expected = delta.clone().multiply(sourceQuaternion); + + expect(actual.angleTo(expected)).toBeLessThan(0.002); + }); + + it("falls back to the world-up axis for a malformed workplane normal", () => { + const malformed = { ...horizontalPlacementWorkplane(), normal: { x: 0, y: 0, z: 0 } }; + const patch = rotatedGeometryShapePatch(shape(), geometryRotationDelta(malformed, 45), null); + + expect(patch).toMatchObject({ rotationX: 0, rotation: 45, rotationZ: 0 }); + }); +}); diff --git a/tests/unit/transformOverlayTypes.test.ts b/tests/unit/transformOverlayTypes.test.ts index 5e7a89b..ff527c8 100644 --- a/tests/unit/transformOverlayTypes.test.ts +++ b/tests/unit/transformOverlayTypes.test.ts @@ -1,13 +1,74 @@ import { describe, expect, it } from "vitest"; +import * as THREE from "three"; import { continuousSnappedWheelRotation, + isPointInsideTransformBounds, normalizedRotationPlaneBasis, - rotationWheelDirectionSign, + rotationPlaneDirectionSign, + transformBoundsIntersectClipVolume, + transformOverlayScreenPoint, snappedRotationDelta, snappedWheelRotation, } from "@/components/workplane/transformOverlayTypes"; describe("rotation handle projection", () => { + it("hides transform chrome when the whole selection is outside one camera plane", () => { + const offscreenRight = Array.from({ length: 8 }, (_, index) => ({ + x: index % 2 === 0 ? 2 : 3, + y: index % 4 < 2 ? -0.5 : 0.5, + z: index < 4 ? -0.5 : 0.5, + w: 1, + })); + expect(transformBoundsIntersectClipVolume(offscreenRight)).toBe(false); + }); + + it("hides transform chrome when the selection is wholly behind the camera", () => { + const behindCamera = Array.from({ length: 8 }, (_, index) => ({ + x: index % 2 === 0 ? -0.25 : 0.25, + y: index % 4 < 2 ? -0.25 : 0.25, + z: index < 4 ? -1.5 : -1.25, + w: -1, + })); + expect(transformBoundsIntersectClipVolume(behindCamera)).toBe(false); + }); + + it("keeps transform chrome when close zoom puts the viewport inside the selection projection", () => { + const surroundingSelection = Array.from({ length: 8 }, (_, index) => ({ + x: index % 2 === 0 ? -2 : 2, + y: index % 4 < 2 ? -2 : 2, + z: index < 4 ? -0.5 : 0.5, + w: 1, + })); + expect(transformBoundsIntersectClipVolume(surroundingSelection)).toBe(true); + }); + + it("rejects invalid projected selection bounds", () => { + expect(transformBoundsIntersectClipVolume([{ x: 0, y: 0, z: 0, w: Number.NaN }])).toBe(false); + }); + + it("keeps anchors at their projected world position instead of clamping them to the viewport", () => { + expect(transformOverlayScreenPoint({ x: -3, y: 2 }, -10, 900, 600)).toEqual({ + x: -900, + y: -300, + visible: true, + }); + }); + + it("marks anchors behind the camera as hidden without relocating them", () => { + expect(transformOverlayScreenPoint({ x: 0.25, y: -0.5 }, 2, 800, 500)).toEqual({ + x: 500, + y: 375, + visible: false, + }); + }); + + it("detects when the camera is inside the selected oriented frame", () => { + const min = { x: -10, y: -5, z: -8 }; + const max = { x: 10, y: 5, z: 8 }; + expect(isPointInsideTransformBounds({ x: 0, y: 0, z: 0 }, min, max)).toBe(true); + expect(isPointInsideTransformBounds({ x: 10.01, y: 0, z: 0 }, min, max)).toBe(false); + }); + it("preserves face-plane foreshortening while normalizing icon size", () => { expect(normalizedRotationPlaneBasis({ x: 10, y: 20, a: 2, b: 0, c: 0.5, d: 1 })).toEqual({ a: 1, @@ -35,21 +96,41 @@ describe("rotation handle projection", () => { }); }); - it("moves 45-degree rotation in the same screen direction as 22.5-degree rotation", () => { - const direction = rotationWheelDirectionSign(1); + it("moves 45-degree rotation in the same pointer direction as 22.5-degree rotation", () => { + const direction = -1; expect(snappedWheelRotation(-52, -80, direction)).toEqual({ delta: -45, pointerAngle: -45 }); expect(snappedWheelRotation(-58, -80, direction)).toEqual({ delta: -45, pointerAngle: -45 }); expect(snappedWheelRotation(-69, -80, direction)).toEqual({ delta: 0, pointerAngle: -90 }); }); + it.each([ + { direction: -1, coarseClockwise: -45, fineClockwise: -22.5, coarseCounterClockwise: 45, fineCounterClockwise: 22.5 }, + { direction: 1, coarseClockwise: 45, fineClockwise: 22.5, coarseCounterClockwise: -45, fineCounterClockwise: -22.5 }, + ])("keeps both snap modes aligned for plane direction $direction", ({ direction, coarseClockwise, fineClockwise, coarseCounterClockwise, fineCounterClockwise }) => { + expect(snappedWheelRotation(-58, -80, direction).delta).toBe(coarseClockwise); + expect(snappedWheelRotation(-58, -80, direction, 22.5).delta).toBe(fineClockwise); + expect(snappedWheelRotation(-120, -80, direction).delta).toBe(coarseCounterClockwise); + expect(snappedWheelRotation(-120, -80, direction, 22.5).delta).toBe(fineCounterClockwise); + expect(Math.sign(coarseClockwise)).toBe(Math.sign(fineClockwise)); + expect(Math.sign(coarseCounterClockwise)).toBe(Math.sign(fineCounterClockwise)); + }); + + it.each([ + { direction: -1, coarse: [0, -45, -90], fine: [0, -22.5, -45, -67.5] }, + { direction: 1, coarse: [0, 45, 90], fine: [0, 22.5, 45, 67.5] }, + ])("advances monotonically through 45 and 22.5 degree marks for plane direction $direction", ({ direction, coarse, fine }) => { + expect([-90, -45, 0].map((pointer) => snappedWheelRotation(pointer, -90, direction).delta)).toEqual(coarse); + expect([-90, -67.5, -45, -22.5].map((pointer) => snappedWheelRotation(pointer, -90, direction, 22.5).delta)).toEqual(fine); + }); + it("switches the wheel rotation and orange indicator to 22.5-degree marks with Shift", () => { - const direction = rotationWheelDirectionSign(1); + const direction = -1; expect(snappedWheelRotation(-58, -80, direction, 22.5)).toEqual({ delta: -22.5, pointerAngle: -67.5 }); expect(snappedWheelRotation(-52, -80, direction, 22.5)).toEqual({ delta: -45, pointerAngle: -45 }); }); it("keeps the current result continuous when switching to 22.5-degree snapping", () => { - const direction = rotationWheelDirectionSign(1); + const direction = -1; const coarse = snappedWheelRotation(-58, -80, direction); const fineAtShift = continuousSnappedWheelRotation( snappedWheelRotation(-58, -80, direction, 22.5), @@ -82,6 +163,74 @@ describe("rotation handle projection", () => { }); }); + it.each([ + { direction: -1, coarseDelta: -45, fineDelta: -67.5 }, + { direction: 1, coarseDelta: 45, fineDelta: 67.5 }, + ])("does not reverse or jump when Shift is pressed and released for plane direction $direction", ({ direction, coarseDelta, fineDelta }) => { + const coarse = snappedWheelRotation(-58, -80, direction); + const fineAtShift = continuousSnappedWheelRotation( + snappedWheelRotation(-58, -80, direction, 22.5), + 22.5, + 45, + coarse.delta, + coarse.pointerAngle, + ); + const fineAfterMove = continuousSnappedWheelRotation( + snappedWheelRotation(-52, -80, direction, 22.5), + 22.5, + 22.5, + fineAtShift.delta, + fineAtShift.pointerAngle, + fineAtShift.deltaOffset, + fineAtShift.pointerOffset, + ); + const coarseAtRelease = continuousSnappedWheelRotation( + snappedWheelRotation(-52, -80, direction), + 45, + 22.5, + fineAfterMove.delta, + fineAfterMove.pointerAngle, + fineAfterMove.deltaOffset, + fineAfterMove.pointerOffset, + ); + + expect(coarse.delta).toBe(coarseDelta); + expect(fineAtShift.delta).toBe(coarseDelta); + expect(fineAfterMove.delta).toBe(fineDelta); + expect(coarseAtRelease.delta).toBe(fineDelta); + expect(Math.sign(fineAfterMove.delta)).toBe(Math.sign(coarse.delta)); + }); + + it("derives rotation direction from each protractor plane's handedness", () => { + const x = new THREE.Vector3(1, 0, 0); + const y = new THREE.Vector3(0, 1, 0); + const z = new THREE.Vector3(0, 0, 1); + expect(rotationPlaneDirectionSign(x, z, y)).toBe(-1); + expect(rotationPlaneDirectionSign(y, x, z)).toBe(-1); + expect(rotationPlaneDirectionSign(y, x.clone().negate(), z.clone().negate())).toBe(-1); + expect(rotationPlaneDirectionSign(y, z.clone().negate(), x)).toBe(-1); + expect(rotationPlaneDirectionSign(y, z, x.clone().negate())).toBe(-1); + expect(rotationPlaneDirectionSign(z, x, y)).toBe(1); + }); + + it.each([ + { name: "X", axis: new THREE.Vector3(1, 0, 0), u: new THREE.Vector3(0, 0, 1), v: new THREE.Vector3(0, 1, 0) }, + { name: "Y", axis: new THREE.Vector3(0, 1, 0), u: new THREE.Vector3(1, 0, 0), v: new THREE.Vector3(0, 0, 1) }, + { name: "Z", axis: new THREE.Vector3(0, 0, 1), u: new THREE.Vector3(1, 0, 0), v: new THREE.Vector3(0, 1, 0) }, + ])("makes the object follow both 45 and Shift+22.5 pointer marks around $name", ({ axis, u, v }) => { + const direction = rotationPlaneDirectionSign(axis, u, v); + [45, 22.5, -45, -22.5].forEach((pointerDelta) => { + const snapDegrees = Math.abs(pointerDelta) === 22.5 ? 22.5 : 45; + const objectDelta = snappedWheelRotation(pointerDelta, 0, direction, snapDegrees).delta; + const actual = u.clone().applyQuaternion( + new THREE.Quaternion().setFromAxisAngle(axis, THREE.MathUtils.degToRad(objectDelta)), + ); + const pointerRadians = THREE.MathUtils.degToRad(pointerDelta); + const intended = u.clone().multiplyScalar(Math.cos(pointerRadians)).add(v.clone().multiplyScalar(Math.sin(pointerRadians))).normalize(); + expect(actual.angleTo(intended)).toBeLessThan(1e-8); + }); + }); + it("keeps one-degree rotation outside the wheel", () => { expect(snappedRotationDelta(28.4, false, false)).toBe(28); }); @@ -90,7 +239,7 @@ describe("rotation handle projection", () => { expect(snappedRotationDelta(28, false, true)).toBe(45); }); - it("keeps absolute wheel snapping synchronized when screen rotation is inverted", () => { + it("keeps absolute wheel snapping synchronized for a negative plane direction", () => { expect(snappedWheelRotation(-134, -80, -1)).toEqual({ delta: 45, pointerAngle: -135 }); }); @@ -98,4 +247,11 @@ describe("rotation handle projection", () => { expect(snappedWheelRotation(-179, 179)).toEqual({ delta: 0, pointerAngle: -180 }); expect(snappedWheelRotation(-134, 179)).toEqual({ delta: 45, pointerAngle: -135 }); }); + + it.each([ + { direction: 1, expected: 22.5 }, + { direction: -1, expected: -22.5 }, + ])("wraps 22.5-degree Shift snapping without reversing for plane direction $direction", ({ direction, expected }) => { + expect(snappedWheelRotation(-157, 179, direction, 22.5)).toEqual({ delta: expected, pointerAngle: -157.5 }); + }); });