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
23 changes: 22 additions & 1 deletion Sources/Demos/InteractionGameplayDemo/GameScene.swift
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@
private var wasLeftMousePressed = false
private var isDraggingGizmo = false
private var wasSpacePressed = false
private var wasTabPressed = false
private var gizmoMode: GizmoMode = .translate

init() {
configureDemoEngine(assetBasePath: demoResourcesURL(), registerKeyboard: true, registerMouse: true)
Expand Down Expand Up @@ -111,6 +113,15 @@
if gameMode == false {
applyPendingGizmoDragUpdate()
handleGizmoInput()

// Tab cycles the gizmo tool (translate -> rotate -> scale) while an
// entity is selected, so rotate/scale are reachable from the keyboard.
if input.tabPressed, !wasTabPressed, activeEntity != .invalid {
gizmoMode = nextGizmoMode(after: gizmoMode)
createGizmo(mode: gizmoMode)
}
wasTabPressed = input.tabPressed

return
}

Expand Down Expand Up @@ -158,13 +169,23 @@

if let hit = pickEntity(rayOrigin: ray.origin, rayDirection: ray.direction, options: ScenePickOptions()) {
activeEntity = hit.entityId
createGizmo(mode: .translate)
gizmoMode = .translate
createGizmo(mode: gizmoMode)
} else {
activeEntity = .invalid
removeGizmo()
}
}

/// Translate -> rotate -> scale -> translate, for the Tab-key tool cycle.
private func nextGizmoMode(after mode: GizmoMode) -> GizmoMode {
switch mode {
case .translate: return .rotate
case .rotate: return .scale
case .scale: return .translate
}
}

/// Builds a world-space ray from the current mouse position using only
/// public engine API (no private renderer/camera internals).
private func currentMouseRay(cameraEntityId: EntityID) -> (origin: simd_float3, direction: simd_float3)? {
Expand Down
114 changes: 110 additions & 4 deletions Sources/UntoldEngine/Systems/GizmoSystem.swift
Original file line number Diff line number Diff line change
Expand Up @@ -75,10 +75,20 @@ private struct GizmoDragState {
/// the entity.
let usesHandleOverride: Bool
var appliedAxisAmount: Float = 0.0
/// For `.rotate`: where the ray met the rotation plane when the drag began,
/// as a direction from the gizmo's center. Angles are measured from this.
var rotationStartDirection: simd_float3?
/// For `.rotate`: the raw (unsnapped) turn applied so far, so each frame
/// only feeds its own increment into the snapping accumulator.
var appliedRotationDegrees: Float = 0.0

var isAxisDriven: Bool {
mode == .translate || mode == .scale
}

var isRotationDriven: Bool {
mode == .rotate
}
}

/// A rotation drag in progress: the whole turn so far, and the part of it
Expand Down Expand Up @@ -209,17 +219,40 @@ public func beginGizmoDrag(ray: GizmoDragRay) {
}

let axisDirection = gizmoAxisDirection(for: handleComponent.axis, entityId: activeEntity, space: gizmoTransformSpace)
let normalizedRayDirection = normalizeOrNil(ray.direction) ?? ray.direction

if handleComponent.mode == .rotate {
beginGizmoRotationDrag()
guard let referenceDirection = gizmoRotationPlaneDirection(
axis: axisDirection,
planePoint: gizmoRootWorldPosition(),
rayOrigin: ray.origin,
rayDirection: normalizedRayDirection
) else {
gizmoDragState = nil
return
}

gizmoDragState = GizmoDragState(
mode: .rotate,
axis: handleComponent.axis,
axisWorldDirection: axisDirection,
startAxisParameter: 0,
targets: gizmoTransformTargets().map(GizmoTargetStart.init(entityId:)),
startGizmoWorldPosition: gizmoRootWorldPosition(),
usesHandleOverride: false,
rotationStartDirection: referenceDirection
)
return
}

guard handleComponent.mode == .translate || handleComponent.mode == .scale,
simd_length_squared(axisDirection) > 0.0001
else {
gizmoDragState = nil
return
}

let normalizedRayDirection = normalizeOrNil(ray.direction) ?? ray.direction
guard let startParameter = closestParameterOnAxis(
axisPoint: gizmoRootWorldPosition(),
axisDirection: axisDirection,
Expand All @@ -242,13 +275,46 @@ public func beginGizmoDrag(ray: GizmoDragRay) {
}

func updateGizmoDrag(ray: GizmoDragRay) {
guard var state = gizmoDragState,
state.isAxisDriven
else {
guard var state = gizmoDragState else {
return
}

let normalizedRayDirection = normalizeOrNil(ray.direction) ?? ray.direction

if state.isRotationDriven {
guard let startDirection = state.rotationStartDirection,
let currentDirection = gizmoRotationPlaneDirection(
axis: state.axisWorldDirection,
planePoint: state.startGizmoWorldPosition,
rayOrigin: ray.origin,
rayDirection: normalizedRayDirection
)
else {
return
}

// The ray reports the total turn since the drag began; only this
// frame's slice of it feeds the snapping accumulator.
let totalDegrees = signedAngleDegrees(from: startDirection, to: currentDirection, axis: state.axisWorldDirection)
let incrementalDegrees = totalDegrees - state.appliedRotationDegrees
guard incrementalDegrees.isFinite else {
return
}

let snappedDelta = snappedGizmoRotationDelta(degrees: incrementalDegrees)
if snappedDelta != 0 {
applyGizmoRotation(axis: state.axisWorldDirection, degrees: snappedDelta)
}

state.appliedRotationDegrees = totalDegrees
gizmoDragState = state
return
}

guard state.isAxisDriven else {
return
}

guard let currentParameter = closestParameterOnAxis(
axisPoint: state.startGizmoWorldPosition,
axisDirection: state.axisWorldDirection,
Expand Down Expand Up @@ -537,6 +603,46 @@ private func closestParameterOnAxis(
return parameter.isFinite ? parameter : nil
}

/// Where a ray meets the plane through `planePoint` perpendicular to `axis`,
/// as a unit direction from `planePoint` — the point on a rotation ring a
/// drag ray is pointing at.
private func gizmoRotationPlaneDirection(
axis: simd_float3,
planePoint: simd_float3,
rayOrigin: simd_float3,
rayDirection: simd_float3
) -> simd_float3? {
guard let normal = normalizeOrNil(axis), let direction = normalizeOrNil(rayDirection) else {
return nil
}

let denominator = simd_dot(normal, direction)
guard abs(denominator) > 0.0001 else {
return nil
}

let distance = simd_dot(normal, planePoint - rayOrigin) / denominator
guard distance.isFinite else {
return nil
}

let intersection = rayOrigin + direction * distance
return normalizeOrNil(intersection - planePoint)
}

/// The signed turn in degrees from `from` to `to`, both already in the plane
/// perpendicular to `axis`: positive turns right-handed about `axis`.
private func signedAngleDegrees(from: simd_float3, to: simd_float3, axis: simd_float3) -> Float {
guard let normalizedAxis = normalizeOrNil(axis) else {
return 0
}

let dotValue = simd_dot(from, to)
let crossValue = simd_cross(from, to)
let angleRadians = atan2(simd_dot(crossValue, normalizedAxis), dotValue)
return angleRadians.isFinite ? radiansToDegrees(radians: angleRadians) : 0
}

private func applyGizmoHandleColor(entityId: EntityID, color: simd_float4) {
guard let renderComponent = scene.get(component: RenderComponent.self, for: entityId) else {
return
Expand Down
31 changes: 31 additions & 0 deletions Tests/UntoldEngineTests/GizmoSystemTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -555,6 +555,37 @@ final class GizmoSystemTests: XCTestCase {
XCTAssertEqual(getPosition(entityId: parentEntityIdGizmo), SIMD3<Float>(2, 0, 0))
}

/// Regression test: `beginGizmoDrag`/`updateGizmoDrag` used to discard `.rotate`
/// drags entirely (the ray→angle path was never wired in), so a rotate handle
/// never turned the entity even though the documented drag lifecycle implies it
/// works uniformly across translate/rotate/scale.
func test_axisGizmoDrag_rotatesFromCurrentRayConstraint() {
let active = makeEntity(name: "RotatedBox", pos: .zero)
activeEntity = active
createGizmo(mode: .rotate)

let yHandle = findGizmoHandle(mode: .rotate, axis: .y)
guard yHandle != .invalid else {
XCTFail("Expected y-axis rotate handle.")
return
}

activeHitGizmoEntity = yHandle
// A ray through (1, 0, 0) on the rotation plane...
beginGizmoDrag(
ray: GizmoDragRay(origin: SIMD3<Float>(1, 5, 0), direction: SIMD3<Float>(0, -1, 0))
)
// ...dragged to a ray through (0, 0, 1): a quarter turn about Y.
updateGizmoDrag(
ray: GizmoDragRay(origin: SIMD3<Float>(0, 5, 1), direction: SIMD3<Float>(0, -1, 0))
)

let expected = simd_quatf(angle: -Float.pi / 2, axis: SIMD3<Float>(0, 1, 0))
let actual = getRotationQuaternion(entityId: active)
XCTAssertEqual(actual.real, expected.real, accuracy: 0.001)
assertNearlyEqual(actual.imag, expected.imag, accuracy: 0.001)
}

func test_axisGizmoDrag_translationTracksAbsoluteAxisPositionForAllAxes() {
let axes: [TransformAxis] = [.x, .y, .z]

Expand Down
2 changes: 2 additions & 0 deletions docs/API/UsingGizmoSystem.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,8 @@ endGizmoDrag()

`queueGizmoDragUpdate`/`applyPendingGizmoDragUpdate` exist so a high-frequency input callback (mouse move, touch move) doesn't have to directly mutate transforms off the simulation's update cadence — queue the latest ray, and let the engine apply it once per frame.

This same ray-based lifecycle drives `.rotate` too: each ray is intersected with the rotation ring's plane, and the angle swept since `beginGizmoDrag` turns the entity about that handle's axis. You don't need a different calling convention for rotate handles — the same `beginGizmoDrag`/`queueGizmoDragUpdate`/`applyPendingGizmoDragUpdate`/`endGizmoDrag` sequence works for translate, rotate, and scale alike.

If more than one entity is selected, populate `gizmoTargets` with all of them before calling `beginGizmoDrag`; the gizmo then moves/rotates/scales every target together, anchored at their combined bounds. With a single selection, just set `activeEntity` as shown above.

**Call `applyPendingGizmoDragUpdate()` from your input-polling callback, not your gameplay-update callback.** If your app has a `setupCallbacks(gameUpdate:handleInput:)`-style split (as the demos do), be aware that the engine only invokes `gameUpdate` while `gameMode == true` — it is skipped entirely while paused/editing. `handleInput`, by contrast, runs every frame regardless of `gameMode`. Since a gizmo is typically only active while `gameMode == false` (see below), putting `applyPendingGizmoDragUpdate()` inside `gameUpdate` means it silently never runs during a drag. Call it from `handleInput` (or wherever your per-frame polling happens unconditionally) instead.
Expand Down
Loading