Skip to content

👾 Open Computer Use – Open-Source Alternative to Codex Computer Use

Align cursor motion with heading-driven chooser

ifuryst22b2463dc732
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index f8fbe2d..920e0c3 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -57,10 +57,13 @@
- MCP `tools/list` 的 description / input schema 当前按官方 `computer-use` 的 9 个 tools 文案和参数面收敛,尽量减少 host 侧提示词和 tool surface 偏差。
- 对真实 app 的 `get_app_state` / action tool 入口,当前新增了一层官方风格的高风险 bundle denylist:bundle-id 直传时直接返回 safety denial;名称匹配时默认不解析到这些 app,尽量贴近官方对终端、密码管理器、Chrome 与少量系统敏感组件的防护行为。
- 普通 app 的 element frame 当前按“窗口左上角为原点”的 window-relative 坐标输出,便于后续把 `element_index` 和截图坐标统一到同一套参考系。
-- `click` 在执行真实动作前后,会额外驱动一层透明 `SoftwareCursorOverlay` window:移动阶段走曲线动画,点击阶段做 pulse,动作结束后只保留一小段停驻与轻微 sway,随后自动淡出。
+- `click` 在执行真实动作前后,会额外驱动一层透明 `SoftwareCursorOverlay` window:移动阶段现在走一条 heading-driven 的官方风格 motion 内核,显式把“当前 cursor 朝向”和“最终 resting pose”一起喂给选路器,优先生成需要时先掉头、再沿车头方向推进的 C 形/单侧大弧轨迹;真正显示出来的 cursor 不再直接等于 path sample,而是经过一层独立的 visual dynamics 状态,把 visible tip、velocity、angle 和 fog/offset 持续推进,再衔接 click pulse、idle sway 和自动淡出。
- overlay 的 visual style 优先在运行时从本机官方 `Codex Computer Use.app` 的 `Package_ComputerUse.bundle` / `Package_SlimCore.bundle` 读取 `SoftwareCursor` 资产并做一次本地处理;如果本机没有这份 bundle,则回退到仓库内的矢量样式。
- overlay 的层级不再固定 `.floating`;现在会跟随 snapshot 命中的目标 window id / layer,把自己排到该目标 window 之上,而不是粗暴压到所有前台 app 最上层。
-- overlay 的曲线路径不再只按固定 Bezier 模板生成;当 snapshot 带有目标 `windowID` 时,会对多组控制点候选做窗口命中采样,优先选“采样点仍落在目标 window 上”的路径,并在动画/idle 期间持续校验目标 window 是否还存在。
+- overlay 的曲线路径不再只按固定 Bezier 模板生成;当前主线采用 reverse-engineering 约束下的 heading-driven candidate 族,候选只保留 `direct` / `turn` / `brake` / `orbit` 这些能稳定产出单侧主弧的 family,并继续保留 target-window 命中策略作为同类候选间的 tie-break。原始 binary lift 恢复出来的 `20` 条路径和 score 仍然保留在独立的 `StandaloneCursor` viewer / Python 重建脚本里,用于对照分析,不再直接作为 runtime 默认 chooser。
+- overlay 的 progress 曲线也不再是固定 `easeInOut`;主线现在复用官方 `response=1.4`、`dampingFraction=0.9`、`dt=1/240` 的 spring/`VelocityVerlet` 形状,但 wall-clock duration 仍做本地校准,因为官方 transaction-level 时长映射还没有完全恢复。
+- overlay 不再依赖临时 `terminal settle` 补丁来修尾;主线现在统一改成“路径层给目标点,visual dynamics 层给可见姿态”的双层模型,所以 move 末段、pulse 和 idle 共用同一套状态,不会再出现 endpoint 锁住后只剩原地翻角的收尾。
+- overlay 的渲染输入也从单一 `rotation` 扩展成 `rotation + cursorBodyOffset + fogOffset + fogScale`,让速度滞后能真正体现在画面上,而不是只存在于主循环内部状态;其中 `rotation` 现在按二进制里 `SoftwareCursorStyle.angle + CursorView._animatedAngleOffsetDegrees` 的分层去近似,不再把“跟随运动方向的主朝向”和“小幅 wiggle offset”压成同一个受限小角度。
- 动作型 tools 对普通 app 采用“非侵入优先,HID 兜底”策略:
- `AXUIElementPerformAction`
- `AXUIElementSetAttributeValue`
@@ -81,7 +84,7 @@
- 这条线优先验证 Python 重建脚本已经收敛出来的核心:`20` 条候选路径、`measure + score`、`prefer in-bounds then lowest-score` 选路,以及 `response=1.4` / `dampingFraction=0.9` / `dt=1/240` 的 raw spring timeline。
- 当前它刻意不引入 speculative 的 wall-clock duration 映射,也不复用 `StandaloneCursorLab` 里更偏视觉手感试验的 pose dynamics。
- `StandaloneCursorLab` 是一个单独的 SwiftUI demo target,可通过 `swift run StandaloneCursorLab` 本地启动。
-- 这条线优先验证 motion model 本身:参数层、路径层、spring/timing 模拟和 debug UI。
+- 这条线优先验证 motion model 本身:当前主线是 heading-driven 的 turn / brake / orbit / direct candidate 族、spring progress、独立 visual dynamics 和 debug UI;显式保留“主朝向跟随速度方向、额外角度 offset 单独叠加”的姿态结构,并把当前可见朝向与最终 resting pose 一起参与选路,避免出现与官方视频不符的原地翻转或 S 形扭曲回环。
- 当前它不接真实 tool call,也不回写主 `SoftwareCursorOverlay`,目的是把实验噪音与产品行为边界隔离开。
## 关键边界
diff --git a/docs/exec-plans/active/20260418-standalone-cursor-lab.md b/docs/exec-plans/active/20260418-standalone-cursor-lab.md
index 548c969..3bae3fe 100644
--- a/docs/exec-plans/active/20260418-standalone-cursor-lab.md
+++ b/docs/exec-plans/active/20260418-standalone-cursor-lab.md
@@ -36,7 +36,7 @@
1. 建立独立目录与 README,明确模块边界。
2. 实现纯参数化路径生成与可视化。
3. 补 spring/timing 模拟。
-4. 视效果再决定是否回灌主 overlay。
+4. 在独立 lab 中完成一版按最新逆向结果重构的官方风格路径/姿态模型。
## 验证方式
@@ -49,7 +49,7 @@
- [x] 里程碑 1
- [x] 里程碑 2
- [x] 里程碑 3
-- [ ] 里程碑 4
+- [x] 里程碑 4
## 最新进展
@@ -60,9 +60,17 @@
- 2026-04-18:已把 timing 从 spring + `easeInOut` 改为 minimum-jerk bell-shaped profile,并移除位置层末端 overshoot;cursor 在运动中持续跟随切线朝向,到点阶段再平滑回正。
- 2026-04-19:已为路径建立 curvature / heading-change 加权的 effort lookup,进度推进不再直接绑定 Bezier 参数 `t`,从而让高曲率转向段更慢、直线段更快。
- 2026-04-19:已把 standalone lab 的 cursor 切到资源化 PNG asset,并改成 tip-anchor 驱动的命中点对齐;静止姿态与运动姿态共用一套 heading calibration,运动中持续朝向当前切线方向。
+- 2026-04-19:已新增更偏“launch/甩头”的候选路径族,并引入 path quality 评分,显式衡量起步朝向贴合度、早段转头力度、末段切线对齐和 terminal straightness。
+- 2026-04-19:已把 timing edge weighting 拆成 start/end 两侧,分别加重起步掉头和末段刹车阶段,从而让速度分配更接近官方视频里“先甩头、后收束”的节奏。
+- 2026-04-19:已把 lab 从 speculative slider 驱动的曲线/收尾模型,重构为 recovered 的 `20` candidate path + 官方风格 spring progress + 独立 visual dynamics;收尾不再靠 endpoint 锁住后原地翻角。
+- 2026-04-19:在对照官方视频后发现 guide/arc 相关常量不能直接按屏幕坐标向量使用;当前已改成先投到 start→end 的局部基底,再生成候选路径,默认样例和反向斜移都不再出现起点附近打结式的扭曲回环。
+- 2026-04-19:继续对照官方视频后,确认 lab 主线不能直接拿 raw reverse-engineered `20` candidates 当 chooser;当前已改成 heading-driven 选路,把当前可见朝向和最终 resting pose 一起参与选路,主路径重新收敛到“需要掉头时走单侧 C 形,不需要掉头时近直线”的分布。
## 决策记录
- 2026-04-18:先把这项工作定义为 standalone lab,而不是继续直接堆进 `OpenComputerUseKit`.
- 2026-04-18:参数命名优先采用视频 UI 与官方字符串的交集:`start/end handle`、`arc size/flow`、`spring`。
- 2026-04-18:第一版 demo 先用独立 SwiftUI target + `CVDisplayLink` 驱动模拟,优先验证参数语义和轨迹手感,再考虑与主 overlay 合流。
+- 2026-04-19:在拿到更完整的 binary-backed 路径与视觉层实现后,lab 改为直接演示 recovered 结构,不再把未经确认的 slider 语义继续当成主实现。
+- 2026-04-19:对 `swift_once` 恢复出的 guide 系数,当前默认采用“常量已确认、世界坐标解释不成立、局部基底投影更贴近官方视频”的实现策略;后续如果拿到更强的二进制级证据,再继续下沉这层解释。
+- 2026-04-19:raw binary lift 的 `20` candidate pool 保留在 `StandaloneCursor` 这条分析线;`StandaloneCursorLab` 和主 runtime overlay 则统一切到 heading-driven 主线,实现上优先保证“朝向约束 + 单侧转弯”这个更贴近官方视频的结构行为。
diff --git a/docs/histories/2026-04/20260418-1430-standalone-cursor-lab.md b/docs/histories/2026-04/20260418-1430-standalone-cursor-lab.md
index 1f157be..1e6acbe 100644
--- a/docs/histories/2026-04/20260418-1430-standalone-cursor-lab.md
+++ b/docs/histories/2026-04/20260418-1430-standalone-cursor-lab.md
@@ -25,6 +25,12 @@
- **[切到资源化 cursor asset]**: 把 standalone lab 的矢量箭头切换为 target 内置 PNG 资源,建立单独的 glyph calibration,并把静止姿态收敛到接近视频里的默认朝向。
- **[改为 tip-anchor 命中对齐]**: 不再拿整张 cursor 图的中心做定位,而是把图像 tip 对齐到 motion sample point,避免更换为朝上型 asset 后重新出现点击坐标偏移。
- **[收敛运动中朝向跟随]**: 把 motion simulator 的 rotation 统一为基于 glyph neutral heading 的绝对姿态,运动时持续追随曲线切线方向,结束时再平滑回到静止角度。
+- **[补 launch/甩头候选族]**: 为 path builder 新增更强调当前 heading 惯性的 `launch` family,并在控制点生成时增加显式 launch bias,让起步阶段更像先顺着车头冲出去、再回切目标。
+- **[加入 path quality 排序]**: 候选路径不再只按 family 常量排序,而是同时考虑起步朝向贴合度、早段转头力度、末段切线对齐和 terminal straightness,以便更稳定选到“既有甩头、又能干净收尾”的主路径。
+- **[加强末段刹车 timing]**: 把 weighted effort lookup 从单一 edge profile 拆成 start/end 两段;前段更重掉头 effort,后段更重 braking effort,并略微拉长高加权路径的总时长,让最后一小段减速和收束更明显。
+- **[重构为官方双层模型]**: 把 standalone lab 从旧的“路径 sample + 末端 rotation settle”实现,切到 recovered 的 `20` 条官方候选路径、官方风格 spring progress,以及和主运行时一致的独立 visual dynamics。
+- **[移除 speculative 调参主线]**: lab 控制面板不再把 `START HANDLE` / `ARC FLOW` / `SPRING` 这类未完全确认语义的 slider 当成主入口,而是直接展示选中的 candidate id、score 和测量值。
+- **[实机跑独立 app 验证]**: 实际启动 `swift run StandaloneCursorLab` 对应的 app,确认 `REPLAY` 与画布点击都会切换候选路径,并看到末段不是原地翻角,而是路径层先形成回接弧线,再由 visual dynamics 做姿态滞后和 idle sway。
- **[同步仓库知识]**: 补 motion model 逆向分析文档、active execution plan、架构说明、README 入口和 history。
### 🧠 Design Intent (Why)
@@ -42,3 +48,17 @@
- `experiments/StandaloneCursorLab/Sources/StandaloneCursorLab/CursorMotionModel.swift`
- `experiments/StandaloneCursorLab/Sources/StandaloneCursorLab/CursorLabRootView.swift`
- `experiments/StandaloneCursorLab/Sources/StandaloneCursorLab/StandaloneCursorLabApp.swift`
+
+### 🔁 Follow-up (2026-04-19)
+**Scope:** `experiments/StandaloneCursorLab/`、`docs/`
+
+**Key Actions:**
+- **[同步主运行时的 recovered motion model]**: standalone lab 现在直接使用 recovered 的 base/arched candidate 生成策略、`VelocityVerlet` progress spring 和独立 visual dynamics。
+- **[重做 lab UI 的语义]**: 控制面板改成展示选中候选路径与 measurement,而不是继续暴露容易误导为“已确认官方语义”的 slider。
+- **[补充独立验证]**: 实际拉起 app,并通过桌面交互验证 `REPLAY` 和新目标点击会切换 candidate,界面也能实时反映 `BASE-SCALED-GUIDE` / `ARCHED` 等选择结果。
+- **[恢复箭头的 heading 跟随]**: 基于 bundled `SkyComputerUseService` 里 `SoftwareCursorStyle.velocityX / velocityY / angle` 与 `CursorView._animatedAngleOffsetDegrees` 的分层证据,把 lab 的姿态从“单一受限小角度偏移”修回“主 heading 跟随速度方向 + 额外小幅 wiggle offset”。
+- **[补 lab chooser 约束]**: 用户指出默认样例会选到过于夸张的大回环后,明确区分“recovered candidate pool”和“真实环境下还有 target-window chooser”两层;lab 现在新增 synthetic corridor hit-count,避免在整块画布上把一些过于离谱但平滑的 arched candidate 当成官方必选结果。
+- **[修正 candidate 坐标系解释]**: 对照官方视频后,确认之前把 recovered guide/arc 常量直接当成固定屏幕坐标向量会在某些象限下生成扭曲回环;现在改成先投到 start→end 的局部基底,再生成候选路径,候选族重新收敛到围绕主轴的 C/椭圆形分布。
+- **[主线切到 heading-driven chooser]**: 继续对照官方视频后,确认 standalone lab 不能把 raw reverse-engineered `20` candidate pool 直接拿来做默认选路;当前已改成把当前可见朝向和最终 resting pose 一起喂给 chooser,让“需要掉头时是单侧 C 形、无需掉头时接近直线”重新成为默认分布。
+- **[同步 runtime overlay 选路]**: 主 `SoftwareCursorOverlay` 现在也改为同一套 heading-driven candidate 族;raw reverse-engineered `20` candidates 仍然保留在 `StandaloneCursor` / Python 重建脚本里做分析对照,但不再直接作为 runtime 主 chooser。
+- **[补方向约束回归测试]**: 新增测试,显式验证“朝向已对齐时优先近直线”和“起步朝向反向时优先掉头大弧”两类行为,避免后续再次回到怪异扭曲曲线。
diff --git a/experiments/StandaloneCursorLab/README.md b/experiments/StandaloneCursorLab/README.md
index b2b55db..144d647 100644
--- a/experiments/StandaloneCursorLab/README.md
+++ b/experiments/StandaloneCursorLab/README.md
@@ -2,7 +2,7 @@
这个目录用于实现一个可独立演进、后续可单独开源的软件 cursor motion demo。
-当前目标不是替换仓库主线的 `SoftwareCursorOverlay`,而是先把“轨迹几何 + 时序弹性 + 调参 UI”从主产品代码里拆出来,做成一个更适合试验和对比的视频 lab。
+当前目标不是替换仓库主线的 `SoftwareCursorOverlay`,而是先把“轨迹几何 + 时序弹性 + 候选路径可视化”从主产品代码里拆出来,做成一个更适合试验和对比的视频 lab。
## 为什么单独放这里
@@ -10,16 +10,14 @@
- 用户提供的视频和官方字符串都说明 cursor motion 有独立参数模型,适合先做一个 lab。
- 这块后续可能单独开源,先在目录边界上收口更干净。
-## 计划中的模块
+## 当前模块边界
-- `Sources/MotionModel/`
- - 参数定义,例如 `startHandle`、`endHandle`、`arcSize`、`arcFlow`、`spring`
-- `Sources/PathBuilder/`
- - 根据起点、终点和参数生成可采样曲线
-- `Sources/Simulator/`
- - 负责路径进度、spring settle、timing
-- `Sources/App/`
- - 本地 demo UI、debug slider、toggle、目标点交互
+- `Sources/CursorMotionModel.swift`
+ - heading-driven 的 `direct` / `turn` / `brake` / `orbit` candidate 族
+ - 官方风格 `VelocityVerlet` spring progress
+ - 独立 visual dynamics,用 visible tip/velocity/angle/fog 来驱动姿态
+- `Sources/CursorLabRootView.swift`
+ - 本地 demo UI、候选路径 overlay、`REPLAY` 与点击交互
## 当前参考
@@ -37,15 +35,19 @@ swift run StandaloneCursorLab
现阶段支持:
-- 点击画布任意位置,先预览多条候选路径,再自动选一路径并驱动 cursor 过去。
-- 拖动起点和终点。
-- 实时调 `START HANDLE`、`END HANDLE`、`ARC SIZE`、`ARC FLOW`、`SPRING`。
-- 预览 Bezier 主路径、控制柄和 cursor 动画。
+- 点击画布任意位置,先预览当前 heading-driven candidate 族,再自动选一路径并驱动 cursor 过去。
+- `REPLAY` 会从固定起点重新跑同一条选中路径,便于反复观察收尾曲线和姿态变化。
+- debug overlay 会显示控制点、arc handle 和当前选中的 candidate id / score。
+- lab 主线不再直接复用 raw binary lift 的 `20` 条 candidate + score;当前改为 reverse-engineering 约束下的 heading-driven chooser,把起始朝向和最终 resting pose 一起喂给路径选择器,让默认曲线更稳定收敛到单侧 C 形或近直线。
+- 主路径进度不再用 speculative `easeInOut` 或 terminal settle;现在直接复用官方风格 spring progress。
+- 可见 cursor 不再直接贴在 path sample 上,而是经过独立 visual dynamics 状态,再输出 `rotation + cursorBodyOffset + fogOffset + fogScale`。
+- 候选路径现在显式约束“先顺车头方向掉头,再沿主轴推进,再按 resting pose 收尾”;因此大多数跨向移动会呈现单侧 C 形,需要直接切入时才会退化为近直线,而不会再出现两侧乱甩的 S 形扭曲。
+- 箭头主朝向会重新明显跟随运动方向;小幅摆动单独作为额外 angle offset 叠加,而不是把整套 rotation 压成一个小角度 wiggle。
- 使用 target 自带资源里的 cursor asset 渲染指针,并用 tip-anchor 而不是整张图中心来对齐点击点。
-- cursor 在运动过程中持续跟随当前切线方向,结束后再回到静止姿态。
后续实现应优先保持:
-- 参数层不依赖 AppKit。
-- 几何层和时间层分离。
-- demo host 可以替换,但 motion model 可以单独复用。
+- 不要再把未验证的 slider 参数语义伪装成“官方实现”。
+- 路径层、progress 层和 visible pose 层继续保持分离。
+- 没有真实 target window 的场景里,要明确区分 `StandaloneCursor` 的 raw reverse-engineered pool 和 `StandaloneCursorLab` 的 heading-driven 主线实现。
+- demo host 可以替换,但 motion model 和 visual dynamics 应保持可单独复用。
diff --git a/experiments/StandaloneCursorLab/Sources/StandaloneCursorLab/CursorLabRootView.swift b/experiments/StandaloneCursorLab/Sources/StandaloneCursorLab/CursorLabRootView.swift
index ccc470d..1491fc3 100644
--- a/experiments/StandaloneCursorLab/Sources/StandaloneCursorLab/CursorLabRootView.swift
+++ b/experiments/StandaloneCursorLab/Sources/StandaloneCursorLab/CursorLabRootView.swift
@@ -3,7 +3,6 @@ import QuartzCore
import SwiftUI
struct CursorLabRootView: View {
- @State private var parameters = CursorMotionParameters.default
@State private var start = CGPoint(x: 220, y: 440)
@State private var end = CGPoint(x: 860, y: 260)
@State private var debugEnabled = true
@@ -24,12 +23,12 @@ struct CursorLabRootView: View {
model: model
)
.onAppear {
- model.configure(start: start, end: end, parameters: parameters)
- model.restart()
+ model.configure(start: start, end: end, canvasSize: proxy.size)
+ model.replay(from: start, to: end)
}
.onChange(of: proxy.size) { _, newSize in
clampPoints(to: newSize)
- model.configure(start: start, end: end, parameters: parameters)
+ model.configure(start: start, end: end, canvasSize: newSize)
}
.onChange(of: start) { _, newValue in
model.updateStart(newValue)
@@ -37,9 +36,6 @@ struct CursorLabRootView: View {
.onChange(of: end) { _, newValue in
model.queueMove(to: newValue)
}
- .onChange(of: parameters) { _, newValue in
- model.updateParameters(newValue)
- }
}
.overlay(alignment: .topLeading) {
controlPanel
@@ -54,14 +50,22 @@ struct CursorLabRootView: View {
private var controlPanel: some View {
VStack(alignment: .leading, spacing: 10) {
- CursorSliderRow(title: "START HANDLE", value: $parameters.startHandle)
- CursorSliderRow(title: "END HANDLE", value: $parameters.endHandle)
- CursorSliderRow(title: "ARC SIZE", value: $parameters.arcSize)
- CursorSliderRow(title: "ARC FLOW", value: $parameters.arcFlow, accent: Color(red: 0.92, green: 0.22, blue: 0.58))
- CursorSliderRow(title: "SPRING", value: $parameters.spring)
+ Text("HEADING-DRIVEN MOTION")
+ .font(.system(size: 10, weight: .black, design: .rounded))
+ .foregroundStyle(Color.white.opacity(0.82))
+ .tracking(0.8)
+
+ Text(model.selectionLabel)
+ .font(.system(size: 10, weight: .bold, design: .rounded))
+ .foregroundStyle(Color.white.opacity(0.72))
+ .tracking(0.6)
+
+ Text(model.selectionMetricsLabel)
+ .font(.system(size: 10, weight: .medium, design: .rounded))
+ .foregroundStyle(Color.white.opacity(0.58))
Button("REPLAY") {
- model.replayCurrentSelection()
+ model.replay(from: start, to: end)
}
.buttonStyle(CursorActionButtonStyle())
.padding(.top, 6)
@@ -87,18 +91,21 @@ struct CursorLabRootView: View {
@MainActor
final class CursorLabViewModel: ObservableObject {
- @Published private(set) var path = CursorMotionPathBuilder.makePath(
- from: CGPoint(x: 220, y: 440),
- to: CGPoint(x: 860, y: 260),
- parameters: .default
+ @Published private(set) var path = CursorMotionPath(
+ start: CGPoint(x: 220, y: 440),
+ end: CGPoint(x: 860, y: 260)
)
@Published private(set) var candidates: [CursorMotionCandidate] = []
@Published private(set) var selectedCandidateID: String?
@Published private(set) var currentState = CursorMotionState(
point: CGPoint(x: 220, y: 440),
rotation: CursorGlyphCalibration.restingRotation,
+ cursorBodyOffset: .zero,
+ fogOffset: .zero,
+ fogOpacity: CursorVisualDynamicsConfiguration.officialInspired.fogOpacityBase,
+ fogScale: 1,
trailProgress: 0,
- isSettled: false
+ isSettled: true
)
@Published private(set) var clickPulse: CGFloat = 0
@@ -110,84 +117,92 @@ final class CursorLabViewModel: ObservableObject {
private var displayLink: CVDisplayLink?
private var lastTimestamp: CFTimeInterval?
private var previewRemaining: CGFloat = 0
- private var queuedTarget: CGPoint?
+ private var queuedTarget = CGPoint(x: 860, y: 260)
+ private var canvasBounds = CGRect(x: 0, y: 0, width: 1080, height: 720)
- func configure(start: CGPoint, end: CGPoint, parameters: CursorMotionParameters) {
- simulator.reset(start: start, end: end, parameters: parameters)
- path = simulator.path
- candidates = CursorMotionPathBuilder.makeCandidatePaths(
+ var selectionLabel: String {
+ guard let selectedCandidate else {
+ return "\(candidates.count) HEADING-DRIVEN CANDIDATES"
+ }
+
+ let family = selectedCandidate.kind.rawValue.uppercased()
+ return "\(candidates.count) CANDIDATES • \(family) • \(selectedCandidate.id.uppercased())"
+ }
+
+ var selectionMetricsLabel: String {
+ guard let selectedCandidate else {
+ return "heading-aware turn / brake / orbit / direct families"
+ }
+
+ let measurement = selectedCandidate.measurement
+ return String(
+ format: "score %.2f • len %.1f • turn %.2f",
+ Double(selectedCandidate.score),
+ Double(measurement.length),
+ Double(measurement.totalTurn)
+ )
+ }
+
+ private var selectedCandidate: CursorMotionCandidate? {
+ candidates.first(where: { $0.id == selectedCandidateID }) ?? candidates.first
+ }
+
+ func configure(start: CGPoint, end: CGPoint, canvasSize: CGSize) {
+ queuedTarget = end
+ canvasBounds = CGRect(origin: .zero, size: canvasSize)
+ let selection = bestSelection(
from: start,
to: end,
- parameters: parameters,
- startRotation: currentState.rotation
+ startRotation: CursorGlyphCalibration.restingRotation
)
- selectedCandidateID = candidates.first?.id
- currentState = CursorMotionState(point: start, rotation: CursorGlyphCalibration.restingRotation, trailProgress: 0, isSettled: false)
+ candidates = selection.candidates
+ selectedCandidateID = selection.selected.id
+ path = selection.selected.path
+ currentState = simulator.snap(to: start, path: selection.selected.path)
clickPulse = 0
+ previewRemaining = 0
+ lastTimestamp = nil
+ ensureDisplayLink()
}
func updateStart(_ value: CGPoint) {
- simulator.reset(start: value)
- path = simulator.path
- candidates = CursorMotionPathBuilder.makeCandidatePaths(
+ let selection = bestSelection(
from: value,
- to: simulator.end,
- parameters: simulator.parameters,
+ to: queuedTarget,
startRotation: currentState.rotation
)
- selectedCandidateID = candidates.first?.id
- currentState = CursorMotionState(point: value, rotation: currentState.rotation, trailProgress: 0, isSettled: false)
+ candidates = selection.candidates
+ selectedCandidateID = selection.selected.id
+ path = selection.selected.path
+ currentState = simulator.snap(to: value, path: selection.selected.path)
+ clickPulse = 0
}
func queueMove(to value: CGPoint) {
- queuedTarget = value
- let origin = currentAnchorPoint
- let startRotation = currentState.rotation
- candidates = CursorMotionPathBuilder.makeCandidatePaths(
- from: origin,
- to: value,
- parameters: simulator.parameters,
- startRotation: startRotation
- )
- selectedCandidateID = candidates.first?.id
- path = candidates.first?.path ?? CursorMotionPathBuilder.makePath(
- from: origin,
- to: value,
- parameters: simulator.parameters,
- startRotation: startRotation
- )
- currentState = CursorMotionState(point: origin, rotation: currentState.rotation, trailProgress: 0, isSettled: false)
- clickPulse = 0
- previewRemaining = 0.24
- lastTimestamp = nil
- ensureDisplayLink()
+ scheduleMove(from: currentState.point, to: value, snapOrigin: false)
}
- func updateParameters(_ value: CursorMotionParameters) {
- simulator.reset(parameters: value)
- if let queuedTarget {
- queueMove(to: queuedTarget)
- } else {
- candidates = CursorMotionPathBuilder.makeCandidatePaths(
- from: currentAnchorPoint,
- to: simulator.end,
- parameters: value,
- startRotation: currentState.rotation
- )
- selectedCandidateID = candidates.first?.id
- path = candidates.first?.path ?? simulator.path
- currentState = CursorMotionState(point: currentAnchorPoint, rotation: currentState.rotation, trailProgress: 0, isSettled: false)
- clickPulse = 0
- }
+ func replay(from origin: CGPoint, to target: CGPoint) {
+ scheduleMove(from: origin, to: target, snapOrigin: true)
}
- func restart() {
- replayCurrentSelection()
- }
+ private func scheduleMove(from origin: CGPoint, to target: CGPoint, snapOrigin: Bool) {
+ queuedTarget = target
+ let startRotation = snapOrigin ? CursorGlyphCalibration.restingRotation : currentState.rotation
+
+ let selection = bestSelection(from: origin, to: target, startRotation: startRotation)
+ candidates = selection.candidates
+ selectedCandidateID = selection.selected.id
+ path = selection.selected.path
- func replayCurrentSelection() {
- let target = queuedTarget ?? simulator.end
- queueMove(to: target)
+ if snapOrigin {
+ currentState = simulator.snap(to: origin, path: selection.selected.path)
+ }
+
+ clickPulse = 0
+ previewRemaining = 0.24
+ lastTimestamp = nil
+ ensureDisplayLink()
}
private func ensureDisplayLink() {
@@ -218,14 +233,6 @@ final class CursorLabViewModel: ObservableObject {
CVDisplayLinkStart(link)
}
- private func stop() {
- guard let displayLink else {
- return
- }
- CVDisplayLinkStop(displayLink)
- self.displayLink = nil
- }
-
private func tick() {
let now = CACurrentMediaTime()
let dt = CGFloat(lastTimestamp.map { now - $0 } ?? (1.0 / 60.0))
@@ -242,34 +249,76 @@ final class CursorLabViewModel: ObservableObject {
currentState = simulator.step(deltaTime: dt)
path = simulator.path
- if currentState.trailProgress > 0.94 {
+ if currentState.trailProgress > 0.94, currentState.isSettled == false {
let pulseProgress = min(max((currentState.trailProgress - 0.94) / 0.06, 0), 1)
clickPulse = sin(pulseProgress * .pi)
} else {
clickPulse = 0
}
-
- if currentState.isSettled {
- stop()
- }
}
private func startSelectedCandidateAnimation() {
- guard let selectedPath = candidates.first(where: { $0.id == selectedCandidateID })?.path ?? candidates.first?.path else {
- stop()
+ guard let selectedCandidate else {
return
}
- simulator.reset(path: selectedPath)
- path = selectedPath
- currentState = CursorMotionState(point: selectedPath.start, rotation: CursorGlyphCalibration.restingRotation, trailProgress: 0, isSettled: false)
+ path = selectedCandidate.path
+ simulator.begin(path: selectedCandidate.path, measurement: selectedCandidate.measurement)
+ }
+
+ private func bestSelection(
+ from start: CGPoint,
+ to end: CGPoint,
+ startRotation: CGFloat
+ ) -> (candidates: [CursorMotionCandidate], selected: CursorMotionCandidate) {
+ let selectionBounds = syntheticMotionBounds(from: start, to: end)
+ let candidates = HeadingDrivenCursorMotionModel.makeCandidates(
+ start: start,
+ end: end,
+ bounds: selectionBounds,
+ startForward: headingVector(rotation: startRotation),
+ endForward: headingVector(rotation: CursorGlyphCalibration.restingRotation)
+ )
+ let defaultCandidate = HeadingDrivenCursorMotionModel.chooseBestCandidate(from: candidates)
+ ?? CursorMotionCandidate(
+ id: "fallback-direct",
+ kind: .base,
+ side: 0,
+ tableAScale: nil,
+ tableBScale: nil,
+ path: CursorMotionPath(start: start, end: end, curveScale: 0),
+ measurement: CursorMotionPath(start: start, end: end, curveScale: 0).measure(bounds: selectionBounds),
+ score: 0
+ )
+
+ return (candidates, defaultCandidate)
}
- private var currentAnchorPoint: CGPoint {
- if previewRemaining > 0 {
- return currentState.point
+ private func syntheticMotionBounds(from start: CGPoint, to end: CGPoint) -> CGRect? {
+ guard canvasBounds.isNull == false else {
+ return nil
}
- return currentState.isSettled ? simulator.end : currentState.point
+
+ let distance = hypot(end.x - start.x, end.y - start.y)
+ let margin = min(max(distance * 0.14, 90), 180)
+ let corridorBounds = CGRect(
+ x: min(start.x, end.x),
+ y: min(start.y, end.y),
+ width: abs(end.x - start.x),
+ height: abs(end.y - start.y)
+ ).insetBy(dx: -margin, dy: -margin)
+
+ let resolved = canvasBounds.intersection(corridorBounds)
+ if resolved.isNull || resolved.isEmpty {
+ return canvasBounds
+ }
+
+ return resolved
+ }
+
+ private func headingVector(rotation: CGFloat) -> CGVector {
+ let angle = CursorGlyphCalibration.neutralHeading + rotation
+ return CGVector(dx: cos(angle), dy: sin(angle))
}
}
@@ -302,10 +351,16 @@ private struct CursorLabCanvas: View {
.position(end)
.allowsHitTesting(false)
- CursorGlyph(rotation: model.currentState.rotation, clickPulse: showClickPulse ? model.clickPulse : 0)
- .position(model.currentState.point)
- .shadow(color: Color.black.opacity(0.14), radius: 8, x: 0, y: 4)
- .allowsHitTesting(false)
+ CursorGlyph(
+ rotation: model.currentState.rotation,
+ cursorBodyOffset: model.currentState.cursorBodyOffset,
+ fogOffset: model.currentState.fogOffset,
+ fogOpacity: model.currentState.fogOpacity,
+ fogScale: model.currentState.fogScale,
+ clickPulse: showClickPulse ? model.clickPulse : 0
+ )
+ .position(model.currentState.point)
+ .allowsHitTesting(false)
CanvasClickCapture { location in
end = location
@@ -360,18 +415,18 @@ private struct CursorLabCanvas: View {
let handleStroke = StrokeStyle(lineWidth: 1.0, dash: [4, 6])
let handleColor = Color.white.opacity(0.22)
- context.stroke(Path { path in
- path.move(to: model.path.start)
- path.addLine(to: model.path.control1)
- path.move(to: model.path.end)
- path.addLine(to: model.path.control2)
- }, with: .color(handleColor), style: handleStroke)
+ context.stroke(handlePath, with: .color(handleColor), style: handleStroke)
- for point in [model.path.control1, model.path.control2] {
+ for point in debugPoints {
let rect = CGRect(x: point.x - 4, y: point.y - 4, width: 8, height: 8)
context.fill(Path(ellipseIn: rect), with: .color(.white.opacity(0.55)))
}
+ if let arc = model.path.arc {
+ let rect = CGRect(x: arc.x - 5, y: arc.y - 5, width: 10, height: 10)
+ context.fill(Path(ellipseIn: rect), with: .color(Color(red: 0.98, green: 0.45, blue: 0.68).opacity(0.78)))
+ }
+
if let selectedCandidate = model.candidates.first(where: { $0.id == model.selectedCandidateID }) {
let labelPoint = CGPoint(
x: selectedCandidate.path.point(at: 0.54).x + 18,
@@ -386,6 +441,40 @@ private struct CursorLabCanvas: View {
.allowsHitTesting(false)
}
+ private var handlePath: Path {
+ Path { path in
+ if let startControl = model.path.startControl {
+ path.move(to: model.path.start)
+ path.addLine(to: startControl)
+ }
+
+ if let arc = model.path.arc {
+ if let arcIn = model.path.arcIn {
+ path.move(to: arc)
+ path.addLine(to: arcIn)
+ }
+ if let arcOut = model.path.arcOut {
+ path.move(to: arc)
+ path.addLine(to: arcOut)
+ }
+ }
+
+ if let endControl = model.path.endControl {
+ path.move(to: model.path.end)
+ path.addLine(to: endControl)
+ }
+ }
+ }
+
+ private var debugPoints: [CGPoint] {
+ [
+ model.path.startControl,
+ model.path.arcIn,
+ model.path.arcOut,
+ model.path.endControl,
+ ].compactMap { $0 }
+ }
+
private func trimmedPath(progress: CGFloat) -> Path {
Path(model.path.cgPath).trimmedPath(from: 0, to: max(0.001, min(progress, 1)))
}
@@ -435,17 +524,31 @@ private final class ClickCaptureView: NSView {
private struct CursorGlyph: View {
let rotation: CGFloat
+ let cursorBodyOffset: CGVector
+ let fogOffset: CGVector
+ let fogOpacity: CGFloat
+ let fogScale: CGFloat
let clickPulse: CGFloat
+ private var motionCompression: CGFloat {
+ min(hypot(cursorBodyOffset.dx, cursorBodyOffset.dy) * 0.01, 0.02)
+ }
+
+ private var clickCompression: CGFloat {
+ clickPulse * 0.04
+ }
+
var body: some View {
ZStack {
Ellipse()
- .fill(Color.black.opacity(0.12))
- .frame(width: 22 + clickPulse * 4, height: 6 + clickPulse * 1.4)
- .offset(x: 0, y: 24)
- .blur(radius: 1.6)
+ .fill(Color.white.opacity(fogOpacity))
+ .frame(width: 20 * fogScale, height: 10 * fogScale)
+ .offset(x: fogOffset.dx, y: 18 + fogOffset.dy)
+ .blur(radius: 6)
glyphBody
+ .offset(x: cursorBodyOffset.dx, y: cursorBodyOffset.dy)
+ .shadow(color: Color.black.opacity(0.14), radius: 8, x: 0, y: 4)
if clickPulse > 0.02 {
Circle()
@@ -455,7 +558,11 @@ private struct CursorGlyph: View {
}
.frame(width: CursorGlyphArtwork.layoutSize.width, height: CursorGlyphArtwork.layoutSize.height)
.rotationEffect(.radians(rotation), anchor: .center)
- .scaleEffect(x: 1 - clickPulse * 0.04, y: 1 + clickPulse * 0.03, anchor: .center)
+ .scaleEffect(
+ x: 1 - clickCompression - motionCompression,
+ y: 1 + (clickPulse * 0.03) + motionCompression,
+ anchor: .center
+ )
}
@ViewBuilder
@@ -478,7 +585,7 @@ private struct CursorGlyph: View {
private struct CursorGlyphFallbackShape: Shape {
func path(in rect: CGRect) -> Path {
- return Path { path in
+ Path { path in
path.move(to: CGPoint(x: rect.midX, y: rect.minY))
path.addQuadCurve(
to: CGPoint(x: rect.maxX, y: rect.maxY * 0.86),
@@ -501,29 +608,6 @@ private struct CursorGlyphFallbackShape: Shape {
}
}
-private struct CursorSliderRow: View {
- let title: String
- @Binding var value: CGFloat
- var accent: Color = Color(red: 0.94, green: 0.28, blue: 0.62)
-
- var body: some View {
- HStack(spacing: 10) {
- Slider(value: Binding(
- get: { Double(value) },
- set: { value = CGFloat($0) }
- ), in: 0...1)
- .tint(accent)
- .frame(width: 66)
-
- Text(title)
- .font(.system(size: 10, weight: .black, design: .rounded))
- .foregroundStyle(Color.white.opacity(0.82))
- .tracking(0.8)
- .frame(width: 92, alignment: .leading)
- }
- }
-}
-
private struct CursorToggleRow: View {
let title: String
@Binding var isOn: Bool
@@ -596,7 +680,8 @@ private struct CursorLabBackground: View {
]
for blob in blobs {
- let rect = CGRect(origin: .zero, size: blob.1).offsetBy(dx: blob.0.x - blob.1.width / 2, dy: blob.0.y - blob.1.height / 2)
+ let rect = CGRect(origin: .zero, size: blob.1)
+ .offsetBy(dx: blob.0.x - blob.1.width / 2, dy: blob.0.y - blob.1.height / 2)
context.addFilter(.blur(radius: 48))
context.fill(Path(ellipseIn: rect), with: .color(blob.2))
}
diff --git a/experiments/StandaloneCursorLab/Sources/StandaloneCursorLab/CursorMotionModel.swift b/experiments/StandaloneCursorLab/Sources/StandaloneCursorLab/CursorMotionModel.swift
index b0c7e29..f22cd18 100644
--- a/experiments/StandaloneCursorLab/Sources/StandaloneCursorLab/CursorMotionModel.swift
+++ b/experiments/StandaloneCursorLab/Sources/StandaloneCursorLab/CursorMotionModel.swift
@@ -2,181 +2,709 @@ import CoreGraphics
import Foundation
struct CursorMotionParameters: Equatable {
- var startHandle: CGFloat = 0.29
- var endHandle: CGFloat = 0.08
- var arcSize: CGFloat = 0.06
- var arcFlow: CGFloat = 0.64
- var spring: CGFloat = 0.53
-
static let `default` = CursorMotionParameters()
}
+struct CursorMotionSegment: Equatable {
+ let end: CGPoint
+ let control1: CGPoint
+ let control2: CGPoint
+}
+
+struct CursorMotionPath: Equatable {
+ let start: CGPoint
+ let end: CGPoint
+ let startControl: CGPoint?
+ let arc: CGPoint?
+ let arcIn: CGPoint?
+ let arcOut: CGPoint?
+ let endControl: CGPoint?
+ let segments: [CursorMotionSegment]
+ let curveScale: CGFloat
+
+ init(
+ start: CGPoint,
+ end: CGPoint,
+ startControl: CGPoint? = nil,
+ arc: CGPoint? = nil,
+ arcIn: CGPoint? = nil,
+ arcOut: CGPoint? = nil,
+ endControl: CGPoint? = nil,
+ segments: [CursorMotionSegment],
+ curveScale: CGFloat = 1
+ ) {
+ self.start = start
+ self.end = end
+ self.startControl = startControl
+ self.arc = arc
+ self.arcIn = arcIn
+ self.arcOut = arcOut
+ self.endControl = endControl
+ self.segments = segments
+ self.curveScale = curveScale
+ }
+
+ init(start: CGPoint, end: CGPoint, curveDirection: CGFloat? = nil, curveScale: CGFloat = 1) {
+ let delta = end - start
+ let distance = max(delta.length, 1)
+ let normal = delta.perpendicular.normalized
+ let resolvedCurveDirection = curveDirection ?? (delta.dx >= 0 ? 1 : -1)
+ let resolvedCurveScale = max(curveScale, 0)
+ let curveAmount = min(max(distance * 0.22, 28), 110) * resolvedCurveScale
+ let controlOffset = normal.scaled(by: curveAmount * resolvedCurveDirection)
+ let control1Base = CGPoint(
+ x: start.x + (delta.dx * (resolvedCurveScale == 0 ? 1.0 / 3.0 : 0.18)),
+ y: start.y + (delta.dy * (resolvedCurveScale == 0 ? 1.0 / 3.0 : 0.10))
+ )
+ let control2Base = CGPoint(
+ x: start.x + (delta.dx * (resolvedCurveScale == 0 ? 2.0 / 3.0 : 0.80)),
+ y: start.y + (delta.dy * (resolvedCurveScale == 0 ? 2.0 / 3.0 : 0.96))
+ )
+ let control1 = control1Base + controlOffset
+ let control2 = control2Base + controlOffset.scaled(by: 0.48)
+
+ self.init(
+ start: start,
+ end: end,
+ startControl: control1,
+ endControl: control2,
+ segments: [
+ CursorMotionSegment(end: end, control1: control1, control2: control2),
+ ],
+ curveScale: resolvedCurveScale
+ )
+ }
+
+ var cgPath: CGPath {
+ let path = CGMutablePath()
+ path.move(to: start)
+
+ for segment in segments {
+ path.addCurve(to: segment.end, control1: segment.control1, control2: segment.control2)
+ }
+
+ return path
+ }
+
+ func point(at progress: CGFloat) -> CGPoint {
+ sample(at: progress).point
+ }
+
+ func tangent(at progress: CGFloat) -> CGVector {
+ sample(at: progress).tangent
+ }
+
+ func sample(at progress: CGFloat) -> (point: CGPoint, tangent: CGVector) {
+ guard !segments.isEmpty else {
+ return (start, CGVector(dx: 1, dy: 0))
+ }
+
+ let clamped = progress.clamped(to: 0...1)
+ let segmentCount = segments.count
+ let segmentIndex: Int
+ let localT: CGFloat
+
+ if clamped >= 1 {
+ segmentIndex = segmentCount - 1
+ localT = 1
+ } else {
+ let scaled = clamped * CGFloat(segmentCount)
+ segmentIndex = min(Int(scaled), segmentCount - 1)
+ localT = scaled - CGFloat(segmentIndex)
+ }
+
+ let segment = segments[segmentIndex]
+ let segmentStart = segmentIndex == 0 ? start : segments[segmentIndex - 1].end
+ let point = sampleCubic(
+ start: segmentStart,
+ control1: segment.control1,
+ control2: segment.control2,
+ end: segment.end,
+ t: localT
+ )
+ let tangent = sampleCubicTangent(
+ start: segmentStart,
+ control1: segment.control1,
+ control2: segment.control2,
+ end: segment.end,
+ t: localT
+ ).normalized
+ return (point, tangent)
+ }
+
+ func sampledConstraintPoints(samplesPerSegment: Int = 6) -> [CGPoint] {
+ let totalSteps = max(segments.count * max(samplesPerSegment, 1), 1)
+ return (1...totalSteps).map { step in
+ point(at: CGFloat(step) / CGFloat(totalSteps))
+ }
+ }
+
+ func measure(bounds: CGRect?, minStepDistance: CGFloat = 0.01, samplesPerSegment: Int = 24) -> CursorMotionMeasurement {
+ var totalLength: CGFloat = 0
+ var angleChangeEnergy: CGFloat = 0
+ var maxAngleChange: CGFloat = 0
+ var totalTurn: CGFloat = 0
+ var staysInBounds = bounds?.contains(start, padding: 20) ?? true
+ var previousPoint = start
+ var previousAngle: CGFloat?
+
+ let totalSteps = max(segments.count * max(samplesPerSegment, 1), 1)
+ for step in 1...totalSteps {
+ let progress = CGFloat(step) / CGFloat(totalSteps)
+ let point = point(at: progress)
+ let delta = point - previousPoint
+ let stepLength = delta.length
+
+ if let bounds, staysInBounds {
+ staysInBounds = bounds.contains(point, padding: 20)
+ }
+
+ if stepLength > minStepDistance {
+ let angle = atan2(delta.dy, delta.dx)
+ totalLength += stepLength
+
+ if let previousAngle {
+ var angleDelta = angle - previousAngle
+ while angleDelta > .pi {
+ angleDelta -= (.pi * 2)
+ }
+ while angleDelta < -.pi {
+ angleDelta += (.pi * 2)
+ }
+
+ angleChangeEnergy += angleDelta * angleDelta
+ let absoluteDelta = abs(angleDelta)
+ maxAngleChange = max(maxAngleChange, absoluteDelta)
+ totalTurn += absoluteDelta
+ }
+
+ previousAngle = angle
+ previousPoint = point
+ }
+ }
+
+ return CursorMotionMeasurement(
+ length: totalLength,
+ angleChangeEnergy: angleChangeEnergy,
+ maxAngleChange: maxAngleChange,
+ totalTurn: totalTurn,
+ staysInBounds: staysInBounds
+ )
+ }
+}
+
+struct CursorMotionMeasurement: Equatable {
+ let length: CGFloat
+ let angleChangeEnergy: CGFloat
+ let maxAngleChange: CGFloat
+ let totalTurn: CGFloat
+ let staysInBounds: Bool
+}
+
+enum CursorMotionKind: String, Equatable {
+ case base
+ case arched
+}
+
struct CursorMotionCandidate: Identifiable, Equatable {
let id: String
+ let kind: CursorMotionKind
+ let side: Int
+ let tableAScale: CGFloat?
+ let tableBScale: CGFloat?
let path: CursorMotionPath
+ let measurement: CursorMotionMeasurement
let score: CGFloat
- let family: String
}
-struct CursorPathSample {
- let point: CGPoint
- let tangent: CGVector
+struct CursorMotionSpringConfiguration: Equatable {
+ let response: CGFloat
+ let dampingFraction: CGFloat
+ let stiffness: CGFloat
+ let drag: CGFloat
+ let dt: CGFloat
+ let closeEnoughProgressThreshold: CGFloat
+ let closeEnoughDistanceThreshold: CGFloat
+ let idleVelocityThreshold: CGFloat
+
+ static let official: CursorMotionSpringConfiguration = {
+ let response: CGFloat = 1.4
+ let dampingFraction: CGFloat = 0.9
+ let dt: CGFloat = 1.0 / 240.0
+ let idleVelocityThreshold: CGFloat = 28_800
+ let rawStiffness = response > 0 ? pow((2 * .pi) / response, 2) : .infinity
+ let stiffness = min(rawStiffness, idleVelocityThreshold)
+ let drag = 2 * dampingFraction * sqrt(stiffness)
+
+ return CursorMotionSpringConfiguration(
+ response: response,
+ dampingFraction: dampingFraction,
+ stiffness: stiffness,
+ drag: drag,
+ dt: dt,
+ closeEnoughProgressThreshold: 1,
+ closeEnoughDistanceThreshold: 0.01,
+ idleVelocityThreshold: idleVelocityThreshold
+ )
+ }()
}
-struct CursorMotionPath: Equatable {
- let start: CGPoint
- let control1: CGPoint
- let control2: CGPoint
- let end: CGPoint
- let arcHeight: CGFloat
- let arcIn: CGFloat
- let arcOut: CGFloat
-
- func point(at t: CGFloat) -> CGPoint {
- let omt = 1 - t
- let omt2 = omt * omt
- let t2 = t * t
+struct CursorMotionSpringState: Equatable {
+ var time: CGFloat = 0
+ var velocity: CGFloat = 0
+ var force: CGFloat = 0
+}
- return CGPoint(
- x: (omt2 * omt * start.x)
- + (3 * omt2 * t * control1.x)
- + (3 * omt * t2 * control2.x)
- + (t2 * t * end.x),
- y: (omt2 * omt * start.y)
- + (3 * omt2 * t * control1.y)
- + (3 * omt * t2 * control2.y)
- + (t2 * t * end.y)
+enum CursorMotionProgressAnimator {
+ static func advance(
+ current: CGFloat,
+ target: CGFloat = 1,
+ state: CursorMotionSpringState,
+ configuration: CursorMotionSpringConfiguration = .official
+ ) -> (current: CGFloat, state: CursorMotionSpringState) {
+ let halfDT = configuration.dt * 0.5
+ let velocityHalf = state.velocity + (state.force * halfDT)
+ let nextCurrent = current + (velocityHalf * configuration.dt)
+ let force = (configuration.stiffness * (target - nextCurrent)) + ((-configuration.drag) * velocityHalf)
+ let velocity = velocityHalf + (force * halfDT)
+
+ return (
+ nextCurrent,
+ CursorMotionSpringState(
+ time: state.time + configuration.dt,
+ velocity: velocity,
+ force: force
+ )
)
}
- func tangent(at t: CGFloat) -> CGVector {
- let omt = 1 - t
- return CGVector(
- dx: (3 * omt * omt * (control1.x - start.x))
- + (6 * omt * t * (control2.x - control1.x))
- + (3 * t * t * (end.x - control2.x)),
- dy: (3 * omt * omt * (control1.y - start.y))
- + (6 * omt * t * (control2.y - control1.y))
- + (3 * t * t * (end.y - control2.y))
+ static func advance(
+ current: CGFloat,
+ target: CGFloat = 1,
+ state: CursorMotionSpringState,
+ configuration: CursorMotionSpringConfiguration = .official,
+ to targetTime: CGFloat
+ ) -> (current: CGFloat, state: CursorMotionSpringState) {
+ var adjustedState = state
+ var adjustedCurrent = current
+
+ if (targetTime - adjustedState.time) > 1 {
+ adjustedState.time = targetTime - (1.0 / 60.0)
+ }
+
+ while adjustedState.time < targetTime {
+ (adjustedCurrent, adjustedState) = advance(
+ current: adjustedCurrent,
+ target: target,
+ state: adjustedState,
+ configuration: configuration
+ )
+ }
+
+ return (adjustedCurrent, adjustedState)
+ }
+
+ static func isCloseEnough(
+ progress: CGFloat,
+ target: CGFloat = 1,
+ configuration: CursorMotionSpringConfiguration = .official
+ ) -> Bool {
+ progress >= configuration.closeEnoughProgressThreshold
+ && abs(target - progress) <= configuration.closeEnoughDistanceThreshold
+ }
+
+ static func closeEnoughTime(
+ configuration: CursorMotionSpringConfiguration = .official
+ ) -> CGFloat {
+ var current: CGFloat = 0
+ var state = CursorMotionSpringState()
+ var step = 0
+
+ while step < 4_096 {
+ step += 1
+ let targetTime = CGFloat(step) * configuration.dt
+ (current, state) = advance(
+ current: current,
+ target: 1,
+ state: state,
+ configuration: configuration,
+ to: targetTime
+ )
+
+ if isCloseEnough(progress: current, configuration: configuration) {
+ return state.time
+ }
+ }
+
+ return 1.43
+ }
+}
+
+enum OfficialCursorMotionModel {
+ static let minimumStepDistance: CGFloat = 0.01
+ static let guideVectorInLocalBasis = CGVector(dx: -0.6946583704589973, dy: 0.7193398003386512)
+ static let tableA: [CGFloat] = [0.55, 0.8, 1.05]
+ static let tableB: [CGFloat] = [0.65, 1.0, 1.35]
+ static let closeEnoughTime = CursorMotionProgressAnimator.closeEnoughTime()
+
+ private static let normalizationEpsilon: CGFloat = 0.001
+ private static let sideBiasScale: CGFloat = 0.65
+ private static let primaryDistanceScale: CGFloat = 0.41960295031576633
+ private static let directSpanScale: CGFloat = 0.9
+ private static let secondaryDistanceScale: CGFloat = 0.2765523188064277
+ private static let arcDistanceScale: CGFloat = 0.5783555327868779
+ private static let candidateArcMin: CGFloat = 38
+ private static let candidateArcMax: CGFloat = 440
+ private static let scoreExcessLengthWeight: CGFloat = 320
+ private static let scoreAngleEnergyWeight: CGFloat = 140
+ private static let scoreMaxAngleWeight: CGFloat = 180
+ private static let scoreTotalTurnWeight: CGFloat = 18
+ private static let scoreOutOfBoundsPenalty: CGFloat = 45
+
+ static func makeCandidates(start: CGPoint, end: CGPoint, bounds: CGRect?) -> [CursorMotionCandidate] {
+ let delta = end - start
+ let distance = max(delta.length, normalizationEpsilon)
+ let direction = delta.normalized
+ let localNormal = direction.perpendicular
+ let guide = direction.scaled(by: guideVectorInLocalBasis.dx)
+ + localNormal.scaled(by: guideVectorInLocalBasis.dy)
+ let reverseGuide = guide.scaled(by: -1)
+
+ let (startExtentPre, endExtentPre) = binaryPiecewisePrimaryExtents(distance: distance)
+ let startExtent = min(startExtentPre, clipPositiveRay(origin: start, direction: guide, bounds: bounds))
+ let endExtent = min(endExtentPre, clipPositiveRay(origin: end, direction: reverseGuide, bounds: bounds))
+
+ let startExtentScaled = min(
+ max(startExtent * sideBiasScale, 0),
+ clipPositiveRay(origin: start, direction: guide, bounds: bounds)
+ )
+ let endExtentScaled = min(
+ max(endExtent * sideBiasScale, 0),
+ clipPositiveRay(origin: end, direction: reverseGuide, bounds: bounds)
+ )
+
+ let fullStartControl = start + guide.scaled(by: startExtent)
+ let fullEndControl = end - guide.scaled(by: endExtent)
+ let scaledStartControl = start + guide.scaled(by: startExtentScaled)
+ let scaledEndControl = end - guide.scaled(by: endExtentScaled)
+
+ let rawHandleExtent = binaryPiecewiseHandleExtent(distance: distance)
+ let rawArcExtent = (distance * arcDistanceScale).clamped(to: candidateArcMin...candidateArcMax)
+
+ let midpoint = CGPoint(x: (start.x + end.x) * 0.5, y: (start.y + end.y) * 0.5)
+ var signedNormal = localNormal
+ let cross = (guide.dy * direction.dx) - (guide.dx * direction.dy)
+ if cross < 0 {
+ signedNormal = signedNormal.scaled(by: -1)
+ }
+ let arcAnchorBias = guide.scaled(by: startExtent * sideBiasScale)
+ let forwardUnit = normalizedOrDefault(
+ direction.scaled(by: distance) + signedNormal.scaled(by: rawArcExtent),
+ minimumLength: rawHandleExtent
+ )
+
+ var candidates: [CursorMotionCandidate] = []
+ candidates.append(
+ makeCandidate(
+ id: "base-full-guide",
+ kind: .base,
+ side: 0,
+ tableAScale: nil,
+ tableBScale: nil,
+ path: CursorMotionPath(
+ start: start,
+ end: end,
+ startControl: fullStartControl,
+ endControl: fullEndControl,
+ segments: [
+ CursorMotionSegment(end: end, control1: fullStartControl, control2: fullEndControl),
+ ],
+ curveScale: 1
+ ),
+ distance: distance,
+ bounds: bounds
+ )
+ )
+ candidates.append(
+ makeCandidate(
+ id: "base-scaled-guide",
+ kind: .base,
+ side: 0,
+ tableAScale: nil,
+ tableBScale: nil,
+ path: CursorMotionPath(
+ start: start,
+ end: end,
+ startControl: scaledStartControl,
+ endControl: scaledEndControl,
+ segments: [
+ CursorMotionSegment(end: end, control1: scaledStartControl, control2: scaledEndControl),
+ ],
+ curveScale: sideBiasScale
+ ),
+ distance: distance,
+ bounds: bounds
+ )
)
+
+ for outerScale in tableA {
+ let anchorOffset = signedNormal.scaled(by: rawHandleExtent * outerScale)
+ for innerScale in tableB {
+ let tangentSpan = forwardUnit.scaled(by: rawArcExtent * innerScale)
+
+ for side in [1, -1] {
+ let anchor = midpoint + arcAnchorBias + anchorOffset.scaled(by: CGFloat(side))
+ let arcIn = anchor - tangentSpan
+ let arcOut = anchor + tangentSpan
+ let path = CursorMotionPath(
+ start: start,
+ end: end,
+ startControl: fullStartControl,
+ arc: anchor,
+ arcIn: arcIn,
+ arcOut: arcOut,
+ endControl: fullEndControl,
+ segments: [
+ CursorMotionSegment(end: anchor, control1: fullStartControl, control2: arcIn),
+ CursorMotionSegment(end: end, control1: arcOut, control2: fullEndControl),
+ ],
+ curveScale: innerScale
+ )
+
+ candidates.append(
+ makeCandidate(
+ id: "a\(outerScale.cursorIdentifier)-b\(innerScale.cursorIdentifier)-\(side > 0 ? "positive" : "negative")",
+ kind: .arched,
+ side: side,
+ tableAScale: outerScale,
+ tableBScale: innerScale,
+ path: path,
+ distance: distance,
+ bounds: bounds
+ )
+ )
+ }
+ }
+ }
+
+ return candidates
+ }
+
+ static func chooseBestCandidate(from candidates: [CursorMotionCandidate]) -> CursorMotionCandidate? {
+ guard !candidates.isEmpty else {
+ return nil
+ }
+
+ let inBoundsCandidates = candidates.filter(\.measurement.staysInBounds)
+ let pool = inBoundsCandidates.isEmpty ? candidates : inBoundsCandidates
+ return pool.min { lhs, rhs in
+ if lhs.score == rhs.score {
+ return lhs.id < rhs.id
+ }
+ return lhs.score < rhs.score
+ }
}
- func sample(at t: CGFloat) -> CursorPathSample {
- CursorPathSample(point: point(at: t), tangent: tangent(at: max(0.001, min(t, 0.999))))
+ static func calibratedTravelDuration(distance: CGFloat, measurement: CursorMotionMeasurement) -> CGFloat {
+ let weightedRatio = max((measurement.length / max(distance, 1)) - 1, 0)
+ let distanceTerm = 0.18 + min(distance / 1300, 0.35)
+ let curvatureTerm = min(weightedRatio, 1.5) * 0.18
+ let settleTerm = min(weightedRatio, 1.0) * 0.04
+ return max(distanceTerm + curvatureTerm + settleTerm, 0.23)
}
- func secondDerivative(at t: CGFloat) -> CGVector {
- let omt = 1 - t
- return CGVector(
- dx: (6 * omt * (control2.x - (2 * control1.x) + start.x))
- + (6 * t * (end.x - (2 * control2.x) + control1.x)),
- dy: (6 * omt * (control2.y - (2 * control1.y) + start.y))
- + (6 * t * (end.y - (2 * control2.y) + control1.y))
+ private static func makeCandidate(
+ id: String,
+ kind: CursorMotionKind,
+ side: Int,
+ tableAScale: CGFloat?,
+ tableBScale: CGFloat?,
+ path: CursorMotionPath,
+ distance: CGFloat,
+ bounds: CGRect?
+ ) -> CursorMotionCandidate {
+ let measurement = path.measure(bounds: bounds, minStepDistance: minimumStepDistance)
+ let score = scoreCandidate(distance: distance, measurement: measurement)
+ return CursorMotionCandidate(
+ id: id,
+ kind: kind,
+ side: side,
+ tableAScale: tableAScale,
+ tableBScale: tableBScale,
+ path: path,
+ measurement: measurement,
+ score: score
)
}
- func curvature(at t: CGFloat) -> CGFloat {
- let derivative = tangent(at: t)
- let second = secondDerivative(at: t)
- let numerator = abs((derivative.dx * second.dy) - (derivative.dy * second.dx))
- let denominator = pow(max((derivative.dx * derivative.dx) + (derivative.dy * derivative.dy), 0.001), 1.5)
- return numerator / denominator
+ private static func scoreCandidate(distance: CGFloat, measurement: CursorMotionMeasurement) -> CGFloat {
+ let excessLengthRatio = max((measurement.length / max(distance, 1)) - 1, 0)
+ return (excessLengthRatio * scoreExcessLengthWeight)
+ + (measurement.angleChangeEnergy * scoreAngleEnergyWeight)
+ + (measurement.maxAngleChange * scoreMaxAngleWeight)
+ + (measurement.totalTurn * scoreTotalTurnWeight)
+ + (measurement.staysInBounds ? 0 : scoreOutOfBoundsPenalty)
}
- var cgPath: CGPath {
- let path = CGMutablePath()
- path.move(to: start)
- path.addCurve(to: end, control1: control1, control2: control2)
- return path
+ private static func binaryPiecewisePrimaryExtents(distance: CGFloat) -> (startExtent: CGFloat, endExtent: CGFloat) {
+ let primary = distance * primaryDistanceScale
+ let direct = distance * directSpanScale
+ let secondary = distance * 0.15
+ let lowCutoff: CGFloat = 48
+ let highCutoff: CGFloat = 640
+
+ if primary < lowCutoff {
+ return (lowCutoff, lowCutoff)
+ }
+ if primary < highCutoff {
+ return (primary, direct)
+ }
+ if secondary < highCutoff {
+ return (highCutoff, lowCutoff)
+ }
+ return (highCutoff, highCutoff)
}
-}
-enum CursorMotionPathBuilder {
- private static let baseCursorHeading = CursorGlyphCalibration.neutralHeading
+ private static func binaryPiecewiseHandleExtent(distance: CGFloat) -> CGFloat {
+ let raw = distance * secondaryDistanceScale
+ if raw < 50 {
+ return 50
+ }
+ if raw < 640 {
+ return raw
+ }
+ return 520
+ }
- static func makePath(
- from start: CGPoint,
- to end: CGPoint,
- parameters: CursorMotionParameters,
- startRotation: CGFloat = 0,
- endRotation: CGFloat = CursorGlyphCalibration.restingRotation
- ) -> CursorMotionPath {
- let metrics = MotionMetrics(start: start, end: end)
- let descriptor = descriptors(for: metrics).max { lhs, rhs in
- score(descriptor: lhs, metrics: metrics, parameters: parameters) < score(descriptor: rhs, metrics: metrics, parameters: parameters)
- } ?? descriptors(for: metrics)[0]
- return makePath(
- from: start,
- to: end,
- parameters: parameters,
- descriptor: descriptor,
- metrics: metrics,
- startRotation: startRotation,
- endRotation: endRotation
- )
+ private static func clipPositiveRay(origin: CGPoint, direction: CGVector, bounds: CGRect?) -> CGFloat {
+ guard let bounds else {
+ return .infinity
+ }
+
+ var limit = CGFloat.infinity
+ if direction.dx > 0 {
+ limit = min(limit, (bounds.maxX - origin.x) / direction.dx)
+ } else if direction.dx < 0 {
+ limit = min(limit, (bounds.minX - origin.x) / direction.dx)
+ }
+
+ if direction.dy > 0 {
+ limit = min(limit, (bounds.maxY - origin.y) / direction.dy)
+ } else if direction.dy < 0 {
+ limit = min(limit, (bounds.minY - origin.y) / direction.dy)
+ }
+
+ return max(limit, 0)
}
- static func makeCandidatePaths(
- from start: CGPoint,
- to end: CGPoint,
- parameters: CursorMotionParameters,
- startRotation: CGFloat = 0,
- endRotation: CGFloat = CursorGlyphCalibration.restingRotation
+ private static func normalizedOrDefault(_ vector: CGVector, minimumLength: CGFloat) -> CGVector {
+ let length = vector.length
+ if length < minimumLength || length < normalizationEpsilon {
+ return CGVector(dx: 1, dy: 0)
+ }
+ return vector.scaled(by: 1 / length)
+ }
+}
+
+enum HeadingDrivenCursorMotionModel {
+ private static let defaultStartHandle: CGFloat = 0.29
+ private static let defaultEndHandle: CGFloat = 0.08
+ private static let defaultArcSize: CGFloat = 0.06
+ private static let defaultArcFlow: CGFloat = 0.64
+ private static let normalizationEpsilon: CGFloat = 0.001
+
+ static func makeCandidates(
+ start: CGPoint,
+ end: CGPoint,
+ bounds: CGRect?,
+ startForward: CGVector,
+ endForward: CGVector
) -> [CursorMotionCandidate] {
let metrics = MotionMetrics(start: start, end: end)
- return descriptors(for: metrics).map { descriptor in
+ let resolvedStartForward = normalizedOrDefault(startForward)
+ let resolvedEndForward = normalizedOrDefault(endForward)
+ let preferredSide = preferredTurnSide(
+ metrics: metrics,
+ startForward: resolvedStartForward,
+ endForward: resolvedEndForward
+ )
+ let scoringContext = MotionScoringContext(
+ metrics: metrics,
+ startForward: resolvedStartForward,
+ endForward: resolvedEndForward,
+ preferredSide: preferredSide
+ )
+
+ return descriptors(for: metrics, preferredSide: preferredSide).map { descriptor in
let path = makePath(
from: start,
to: end,
- parameters: parameters,
- descriptor: descriptor,
metrics: metrics,
- startRotation: startRotation,
- endRotation: endRotation
+ descriptor: descriptor,
+ startForward: resolvedStartForward,
+ endForward: resolvedEndForward
)
- return CursorMotionCandidate(
+ return makeCandidate(
id: descriptor.id,
+ kind: descriptor.kind,
+ side: descriptor.side,
+ tableAScale: nil,
+ tableBScale: nil,
path: path,
- score: score(descriptor: descriptor, metrics: metrics, parameters: parameters),
- family: descriptor.family
+ bounds: bounds,
+ context: scoringContext,
+ descriptor: descriptor
)
}
- .sorted { lhs, rhs in
- lhs.score > rhs.score
+ }
+
+ static func chooseBestCandidate(from candidates: [CursorMotionCandidate]) -> CursorMotionCandidate? {
+ guard !candidates.isEmpty else {
+ return nil
}
+
+ let inBoundsCandidates = candidates.filter(\.measurement.staysInBounds)
+ let pool = inBoundsCandidates.isEmpty ? candidates : inBoundsCandidates
+ return pool.min { lhs, rhs in
+ if lhs.score == rhs.score {
+ return lhs.id < rhs.id
+ }
+ return lhs.score < rhs.score
+ }
+ }
+
+ static func calibratedTravelDuration(distance: CGFloat, measurement: CursorMotionMeasurement) -> CGFloat {
+ OfficialCursorMotionModel.calibratedTravelDuration(distance: distance, measurement: measurement)
}
private static func makePath(
from start: CGPoint,
to end: CGPoint,
- parameters: CursorMotionParameters,
- descriptor: MotionDescriptor,
metrics: MotionMetrics,
- startRotation: CGFloat,
- endRotation: CGFloat
+ descriptor: MotionDescriptor,
+ startForward: CGVector,
+ endForward: CGVector
) -> CursorMotionPath {
let distance = metrics.distance
let direction = metrics.direction
let normal = metrics.normal
- let resolvedFlow = (parameters.arcFlow + descriptor.flowShift).clamped(to: 0...1)
+ let resolvedFlow = (defaultArcFlow + descriptor.flowShift).clamped(to: 0...1)
let flowBias = (resolvedFlow - 0.5) * distance * 0.18
- let baseStartReach = distance * (0.10 + parameters.startHandle * 0.56)
- let baseEndReach = distance * (0.11 + parameters.endHandle * 0.62)
+ let baseStartReach = distance * (0.10 + defaultStartHandle * 0.56)
+ let baseEndReach = distance * (0.11 + defaultEndHandle * 0.62)
let distanceLift = 0.68 + (metrics.farFactor * 0.56)
let baseArcHeight = min(
- max(distance * (0.10 + parameters.arcSize * 0.92) * descriptor.arcScale * distanceLift, 20),
+ max(distance * (0.10 + defaultArcSize * 0.92) * descriptor.arcScale * distanceLift, 20),
distance * 0.96
)
- let sideSign = descriptor.side
- let arcVector = CGPoint(
- x: normal.dx * baseArcHeight * sideSign,
- y: normal.dy * baseArcHeight * sideSign
+ let sideSign = CGFloat(descriptor.side)
+ let arcVector = CGVector(
+ dx: normal.dx * baseArcHeight * sideSign,
+ dy: normal.dy * baseArcHeight * sideSign
)
- let startForward = headingVector(rotation: startRotation)
- let endForward = headingVector(rotation: endRotation)
let startGuide = resolvedGuide(
line: direction,
forward: startForward,
@@ -198,348 +726,340 @@ enum CursorMotionPathBuilder {
let startReach = max(baseStartReach * descriptor.startReachScale + flowBias * descriptor.startFlowWeight, 12)
let endReach = max(baseEndReach * descriptor.endReachScale - flowBias * descriptor.endFlowWeight, 12)
- let control1Base = CGPoint(
- x: start.x + startGuide.dx * startReach,
- y: start.y + startGuide.dy * startReach
- )
- let control2Base = CGPoint(
- x: end.x - endGuide.dx * endReach,
- y: end.y - endGuide.dy * endReach
- )
-
- let control1 = CGPoint(
- x: control1Base.x + arcVector.x * descriptor.startNormalScale,
- y: control1Base.y + arcVector.y * descriptor.startNormalScale
- )
- let control2 = CGPoint(
- x: control2Base.x + arcVector.x * descriptor.endNormalScale,
- y: control2Base.y + arcVector.y * descriptor.endNormalScale
- )
+ let control1Base = start + startGuide.scaled(by: startReach)
+ let control2Base = end - endGuide.scaled(by: endReach)
+ let control1 = control1Base + arcVector.scaled(by: descriptor.startNormalScale)
+ let control2 = control2Base + arcVector.scaled(by: descriptor.endNormalScale)
let resolvedArcHeight = baseArcHeight * max(
abs(descriptor.startNormalScale),
abs(descriptor.endNormalScale),
0.12
)
- let arcIn = abs(descriptor.startNormalScale).clamped(to: 0.12...1.28)
- let arcOut = abs(descriptor.endNormalScale).clamped(to: 0.12...1.28)
- return CursorMotionPath(start: start, control1: control1, control2: control2, end: end, arcHeight: resolvedArcHeight, arcIn: arcIn, arcOut: arcOut)
+ return CursorMotionPath(
+ start: start,
+ end: end,
+ startControl: control1,
+ endControl: control2,
+ segments: [
+ CursorMotionSegment(end: end, control1: control1, control2: control2)
+ ],
+ curveScale: resolvedArcHeight
+ )
+ }
+
+ private static func makeCandidate(
+ id: String,
+ kind: CursorMotionKind,
+ side: Int,
+ tableAScale: CGFloat?,
+ tableBScale: CGFloat?,
+ path: CursorMotionPath,
+ bounds: CGRect?,
+ context: MotionScoringContext,
+ descriptor: MotionDescriptor
+ ) -> CursorMotionCandidate {
+ let measurement = path.measure(bounds: bounds, minStepDistance: OfficialCursorMotionModel.minimumStepDistance)
+ let score = scoreCandidate(
+ measurement: measurement,
+ path: path,
+ descriptor: descriptor,
+ context: context
+ )
+
+ return CursorMotionCandidate(
+ id: id,
+ kind: kind,
+ side: side,
+ tableAScale: tableAScale,
+ tableBScale: tableBScale,
+ path: path,
+ measurement: measurement,
+ score: score
+ )
}
- private static func score(descriptor: MotionDescriptor, metrics: MotionMetrics, parameters: CursorMotionParameters) -> CGFloat {
- let sideAffinity = descriptor.side == preferredSide(for: metrics) ? 0.04 : -0.02
- let flowEnergy = abs(parameters.arcFlow - 0.5) * 0.08
- let handleEnergy = max(parameters.startHandle, parameters.endHandle) * 0.06
+ private static func scoreCandidate(
+ measurement: CursorMotionMeasurement,
+ path: CursorMotionPath,
+ descriptor: MotionDescriptor,
+ context: MotionScoringContext
+ ) -> CGFloat {
+ let distance = max(context.metrics.distance, 1)
+ let excessLengthRatio = max((measurement.length / distance) - 1, 0)
+ let startTangent = normalizedOrDefault(path.tangent(at: 0.04))
+ let endTangent = normalizedOrDefault(path.tangent(at: 0.96))
+ let startHeadingError = abs(signedAngle(from: context.startForward, to: startTangent))
+ let endHeadingError = abs(signedAngle(from: endTangent, to: context.endForward))
+
+ var score = descriptor.scoreBias
+ score += excessLengthRatio * 180
+ score += measurement.angleChangeEnergy * 90
+ score += measurement.maxAngleChange * 85
+ score += measurement.totalTurn * (descriptor.side == 0 ? 10 : 12)
+ score += startHeadingError * 150
+ score += endHeadingError * 120
+
+ if descriptor.side == 0 {
+ score += context.turnDemand * 130
+ score += context.arrivalDemand * 30
+ } else {
+ score += context.directness * 90
+ if descriptor.side != context.preferredSide {
+ score += max(context.turnDemand, 0.45) * 200
+ }
+ }
switch descriptor.family {
case "turn":
- return 0.36 + (metrics.farFactor * 0.28) + (metrics.horizontalFactor * 0.18) + (metrics.diagonalFactor * 0.10) + handleEnergy + sideAffinity
+ score += (1 - context.turnDemand) * 55
case "brake":
- return 0.35 + (metrics.farFactor * 0.20) + (metrics.horizontalFactor * 0.12) + (parameters.spring * 0.06) + flowEnergy
+ score += (1 - context.arrivalDemand) * 40
case "orbit":
- return 0.28 + (metrics.horizontalFactor * 0.20) + (metrics.farFactor * 0.28) + sideAffinity + flowEnergy
- case "ribbon":
- return 0.24 + (metrics.diagonalFactor * 0.26) + (metrics.farFactor * 0.10) + flowEnergy
- case "slingshot":
- return 0.22 + (metrics.closeFactor * 0.10) + (metrics.diagonalFactor * 0.20) + (metrics.farFactor * 0.08) + sideAffinity
- case "hook":
- return 0.20 + (metrics.closeFactor * 0.22) + (metrics.verticalFactor * 0.18)
- case "snap":
- return 0.18 + (metrics.closeFactor * 0.26) + (metrics.horizontalFactor * 0.08)
+ score += context.directness * 70
case "direct":
- return 0.14 + (metrics.closeFactor * 0.20) - (metrics.farFactor * 0.28)
+ score += max(context.turnDemand - 0.12, 0) * 80
default:
- return 0.12
+ break
+ }
+
+ if measurement.staysInBounds == false {
+ score += 90
}
+
+ return score
}
- private static func descriptors(for metrics: MotionMetrics) -> [MotionDescriptor] {
- let orbitScale = 0.84 + (metrics.farFactor * 0.34)
- let tightScale = 0.58 + (metrics.closeFactor * 0.22)
- let turnaroundScale = 0.92 + (metrics.farFactor * 0.34)
- let brakingScale = 0.76 + (metrics.farFactor * 0.28)
+ private static func descriptors(for metrics: MotionMetrics, preferredSide: Int) -> [MotionDescriptor] {
+ let orbitScale = 0.82 + (metrics.farFactor * 0.26)
+ let turnaroundScale = 0.90 + (metrics.farFactor * 0.30)
+ let brakingScale = 0.74 + (metrics.farFactor * 0.24)
return [
MotionDescriptor(
- id: "turn-high",
- family: "turn",
- side: 1,
- startReachScale: 1.30,
- endReachScale: 1.34,
- startLineWeight: -0.26,
- endLineWeight: -0.10,
- startHeadingWeight: 1.56,
- endHeadingWeight: 1.34,
- startNormalScale: 0.52,
+ id: "direct-tight",
+ family: "direct",
+ side: 0,
+ startReachScale: 0.90,
+ endReachScale: 0.86,
+ startLineWeight: 1.12,
+ endLineWeight: 1.04,
+ startHeadingWeight: 0.18,
+ endHeadingWeight: 0.20,
+ startNormalScale: 0.02,
endNormalScale: 0.02,
- startGuideNormalBias: 0.36,
- endGuideNormalBias: 0.24,
- startFlowWeight: -0.34,
- endFlowWeight: 0.26,
- flowShift: -0.08,
- arcScale: turnaroundScale
+ startGuideNormalBias: 0,
+ endGuideNormalBias: 0,
+ startFlowWeight: 0.02,
+ endFlowWeight: 0.02,
+ flowShift: -0.02,
+ arcScale: 0.16,
+ scoreBias: 18
),
MotionDescriptor(
- id: "turn-low",
+ id: "direct-soft",
+ family: "direct",
+ side: 0,
+ startReachScale: 0.98,
+ endReachScale: 0.94,
+ startLineWeight: 1.04,
+ endLineWeight: 0.96,
+ startHeadingWeight: 0.22,
+ endHeadingWeight: 0.28,
+ startNormalScale: 0.04,
+ endNormalScale: 0.08,
+ startGuideNormalBias: 0,
+ endGuideNormalBias: 0.04,
+ startFlowWeight: 0.04,
+ endFlowWeight: 0.08,
+ flowShift: 0.02,
+ arcScale: 0.24,
+ scoreBias: 24
+ ),
+ MotionDescriptor(
+ id: "turn-primary-tight",
family: "turn",
- side: -1,
+ side: preferredSide,
startReachScale: 1.26,
- endReachScale: 1.38,
- startLineWeight: -0.30,
- endLineWeight: -0.12,
- startHeadingWeight: 1.52,
- endHeadingWeight: 1.38,
- startNormalScale: 0.50,
- endNormalScale: 0.04,
- startGuideNormalBias: 0.34,
- endGuideNormalBias: 0.24,
+ endReachScale: 1.30,
+ startLineWeight: -0.24,
+ endLineWeight: -0.04,
+ startHeadingWeight: 1.50,
+ endHeadingWeight: 1.18,
+ startNormalScale: 0.46,
+ endNormalScale: 0.08,
+ startGuideNormalBias: 0.30,
+ endGuideNormalBias: 0.16,
startFlowWeight: -0.30,
- endFlowWeight: 0.28,
- flowShift: 0.08,
- arcScale: turnaroundScale * 0.96
+ endFlowWeight: 0.20,
+ flowShift: -0.08,
+ arcScale: turnaroundScale,
+ scoreBias: 40
),
MotionDescriptor(
- id: "brake-high",
+ id: "turn-primary-wide",
+ family: "turn",
+ side: preferredSide,
+ startReachScale: 1.30,
+ endReachScale: 1.36,
+ startLineWeight: -0.28,
+ endLineWeight: -0.10,
+ startHeadingWeight: 1.54,
+ endHeadingWeight: 1.24,
+ startNormalScale: 0.58,
+ endNormalScale: 0.12,
+ startGuideNormalBias: 0.34,
+ endGuideNormalBias: 0.20,
+ startFlowWeight: -0.34,
+ endFlowWeight: 0.24,
+ flowShift: 0.06,
+ arcScale: turnaroundScale * 1.06,
+ scoreBias: 46
+ ),
+ MotionDescriptor(
+ id: "brake-primary-tight",
family: "brake",
- side: 1,
+ side: preferredSide,
startReachScale: 0.92,
- endReachScale: 1.48,
- startLineWeight: 0.52,
- endLineWeight: -0.28,
- startHeadingWeight: 0.68,
- endHeadingWeight: 1.66,
- startNormalScale: 0.20,
- endNormalScale: 0.24,
+ endReachScale: 1.42,
+ startLineWeight: 0.50,
+ endLineWeight: -0.20,
+ startHeadingWeight: 0.70,
+ endHeadingWeight: 1.52,
+ startNormalScale: 0.16,
+ endNormalScale: 0.20,
startGuideNormalBias: 0.10,
- endGuideNormalBias: 0.36,
+ endGuideNormalBias: 0.26,
startFlowWeight: 0.10,
- endFlowWeight: 0.42,
+ endFlowWeight: 0.32,
flowShift: -0.04,
- arcScale: brakingScale
+ arcScale: brakingScale,
+ scoreBias: 44
),
MotionDescriptor(
- id: "brake-low",
+ id: "brake-primary-wide",
family: "brake",
- side: -1,
- startReachScale: 0.96,
- endReachScale: 1.52,
- startLineWeight: 0.48,
- endLineWeight: -0.32,
- startHeadingWeight: 0.70,
- endHeadingWeight: 1.72,
+ side: preferredSide,
+ startReachScale: 0.98,
+ endReachScale: 1.50,
+ startLineWeight: 0.44,
+ endLineWeight: -0.26,
+ startHeadingWeight: 0.74,
+ endHeadingWeight: 1.62,
startNormalScale: 0.22,
- endNormalScale: 0.28,
+ endNormalScale: 0.26,
startGuideNormalBias: 0.12,
- endGuideNormalBias: 0.38,
- startFlowWeight: 0.12,
- endFlowWeight: 0.44,
+ endGuideNormalBias: 0.32,
+ startFlowWeight: 0.14,
+ endFlowWeight: 0.38,
flowShift: 0.04,
- arcScale: brakingScale * 0.94
+ arcScale: brakingScale * 1.04,
+ scoreBias: 50
),
MotionDescriptor(
- id: "orbit-high",
+ id: "orbit-primary-tight",
family: "orbit",
- side: 1,
- startReachScale: 0.92,
- endReachScale: 1.02,
+ side: preferredSide,
+ startReachScale: 0.90,
+ endReachScale: 0.98,
startLineWeight: 0.72,
- endLineWeight: 0.82,
- startHeadingWeight: 0.34,
- endHeadingWeight: 0.24,
- startNormalScale: 1.24,
- endNormalScale: 1.08,
- startGuideNormalBias: 0.18,
- endGuideNormalBias: 0.08,
- startFlowWeight: 0.40,
- endFlowWeight: 0.18,
- flowShift: -0.10,
- arcScale: orbitScale
- ),
- MotionDescriptor(
- id: "orbit-low",
- family: "orbit",
- side: -1,
- startReachScale: 0.88,
- endReachScale: 1.04,
- startLineWeight: 0.68,
- endLineWeight: 0.84,
+ endLineWeight: 0.76,
startHeadingWeight: 0.30,
endHeadingWeight: 0.22,
- startNormalScale: 1.18,
- endNormalScale: 1.02,
+ startNormalScale: 0.90,
+ endNormalScale: 0.82,
startGuideNormalBias: 0.16,
- endGuideNormalBias: 0.08,
- startFlowWeight: 0.34,
- endFlowWeight: 0.14,
- flowShift: 0.10,
- arcScale: orbitScale * 0.94
- ),
- MotionDescriptor(
- id: "ribbon-high",
- family: "ribbon",
- side: 1,
- startReachScale: 0.98,
- endReachScale: 0.90,
- startLineWeight: 0.74,
- endLineWeight: 0.34,
- startHeadingWeight: 0.28,
- endHeadingWeight: 0.56,
- startNormalScale: 0.78,
- endNormalScale: -0.56,
- startGuideNormalBias: 0.10,
- endGuideNormalBias: -0.22,
- startFlowWeight: 0.12,
- endFlowWeight: -0.18,
- flowShift: 0.06,
- arcScale: 0.82 + (metrics.diagonalFactor * 0.24)
+ endGuideNormalBias: 0.06,
+ startFlowWeight: 0.26,
+ endFlowWeight: 0.12,
+ flowShift: -0.06,
+ arcScale: orbitScale,
+ scoreBias: 54
),
MotionDescriptor(
- id: "ribbon-low",
- family: "ribbon",
- side: -1,
+ id: "orbit-primary-wide",
+ family: "orbit",
+ side: preferredSide,
startReachScale: 0.94,
- endReachScale: 0.92,
- startLineWeight: 0.70,
- endLineWeight: 0.36,
+ endReachScale: 1.02,
+ startLineWeight: 0.68,
+ endLineWeight: 0.82,
startHeadingWeight: 0.28,
- endHeadingWeight: 0.60,
- startNormalScale: 0.74,
- endNormalScale: -0.52,
- startGuideNormalBias: 0.10,
- endGuideNormalBias: -0.20,
- startFlowWeight: 0.10,
- endFlowWeight: -0.16,
- flowShift: -0.06,
- arcScale: 0.80 + (metrics.diagonalFactor * 0.22)
- ),
- MotionDescriptor(
- id: "slingshot-high",
- family: "slingshot",
- side: 1,
- startReachScale: 1.12,
- endReachScale: 1.00,
- startLineWeight: -0.24,
- endLineWeight: 0.86,
- startHeadingWeight: 1.00,
- endHeadingWeight: 0.24,
- startNormalScale: 0.48,
+ endHeadingWeight: 0.22,
+ startNormalScale: 1.02,
endNormalScale: 0.94,
- startGuideNormalBias: 0.20,
+ startGuideNormalBias: 0.18,
endGuideNormalBias: 0.08,
- startFlowWeight: -0.46,
- endFlowWeight: 0.24,
- flowShift: -0.12,
- arcScale: 0.74 + (metrics.diagonalFactor * 0.18)
+ startFlowWeight: 0.30,
+ endFlowWeight: 0.16,
+ flowShift: 0.06,
+ arcScale: orbitScale * 1.06,
+ scoreBias: 60
),
MotionDescriptor(
- id: "slingshot-low",
- family: "slingshot",
- side: -1,
- startReachScale: 1.16,
- endReachScale: 1.02,
- startLineWeight: -0.28,
- endLineWeight: 0.88,
- startHeadingWeight: 1.04,
- endHeadingWeight: 0.24,
- startNormalScale: 0.44,
- endNormalScale: 0.98,
+ id: "turn-secondary",
+ family: "turn",
+ side: -preferredSide,
+ startReachScale: 1.18,
+ endReachScale: 1.26,
+ startLineWeight: -0.18,
+ endLineWeight: 0.02,
+ startHeadingWeight: 1.32,
+ endHeadingWeight: 1.08,
+ startNormalScale: 0.34,
+ endNormalScale: 0.06,
startGuideNormalBias: 0.22,
- endGuideNormalBias: 0.10,
- startFlowWeight: -0.42,
- endFlowWeight: 0.22,
- flowShift: 0.12,
- arcScale: 0.72 + (metrics.diagonalFactor * 0.18)
+ endGuideNormalBias: 0.14,
+ startFlowWeight: -0.20,
+ endFlowWeight: 0.14,
+ flowShift: 0.02,
+ arcScale: turnaroundScale * 0.92,
+ scoreBias: 88
),
MotionDescriptor(
- id: "hook-upper",
- family: "hook",
- side: 1,
+ id: "brake-secondary",
+ family: "brake",
+ side: -preferredSide,
startReachScale: 0.90,
- endReachScale: 0.76,
- startLineWeight: -0.44,
- endLineWeight: 0.30,
- startHeadingWeight: 0.92,
- endHeadingWeight: 0.18,
- startNormalScale: -0.36,
- endNormalScale: 0.30,
- startGuideNormalBias: -0.20,
- endGuideNormalBias: 0.16,
- startFlowWeight: -0.52,
- endFlowWeight: 0.18,
- flowShift: -0.10,
- arcScale: tightScale
- ),
- MotionDescriptor(
- id: "hook-lower",
- family: "hook",
- side: -1,
- startReachScale: 0.88,
- endReachScale: 0.74,
- startLineWeight: -0.40,
- endLineWeight: 0.28,
- startHeadingWeight: 0.88,
- endHeadingWeight: 0.18,
- startNormalScale: -0.34,
- endNormalScale: 0.26,
- startGuideNormalBias: -0.18,
- endGuideNormalBias: 0.16,
- startFlowWeight: -0.48,
- endFlowWeight: 0.16,
- flowShift: 0.10,
- arcScale: tightScale * 0.96
- ),
- MotionDescriptor(
- id: "snap",
- family: "snap",
- side: preferredSide(for: metrics),
- startReachScale: 1.10,
- endReachScale: 0.72,
- startLineWeight: 1.08,
- endLineWeight: -0.22,
- startHeadingWeight: 0.22,
- endHeadingWeight: 0.74,
- startNormalScale: 0.20,
- endNormalScale: -0.34,
- startGuideNormalBias: 0.06,
- endGuideNormalBias: -0.16,
- startFlowWeight: 0.28,
- endFlowWeight: -0.34,
- flowShift: 0.04,
- arcScale: 0.54 + (metrics.closeFactor * 0.20)
- ),
- MotionDescriptor(
- id: "direct",
- family: "direct",
- side: preferredSide(for: metrics),
- startReachScale: 0.94,
- endReachScale: 0.94,
- startLineWeight: 1.16,
- endLineWeight: 1.06,
- startHeadingWeight: 0.02,
- endHeadingWeight: 0.02,
- startNormalScale: 0.02,
- endNormalScale: 0.02,
- startGuideNormalBias: 0,
- endGuideNormalBias: 0,
- startFlowWeight: 0.06,
- endFlowWeight: 0.06,
- flowShift: 0,
- arcScale: 0.20
+ endReachScale: 1.34,
+ startLineWeight: 0.52,
+ endLineWeight: -0.16,
+ startHeadingWeight: 0.62,
+ endHeadingWeight: 1.40,
+ startNormalScale: 0.12,
+ endNormalScale: 0.18,
+ startGuideNormalBias: 0.08,
+ endGuideNormalBias: 0.20,
+ startFlowWeight: 0.10,
+ endFlowWeight: 0.28,
+ flowShift: -0.02,
+ arcScale: brakingScale * 0.92,
+ scoreBias: 96
),
]
}
- private static func preferredSide(for metrics: MotionMetrics) -> CGFloat {
+ private static func preferredTurnSide(
+ metrics: MotionMetrics,
+ startForward: CGVector,
+ endForward: CGVector
+ ) -> Int {
+ let startDelta = signedAngle(from: startForward, to: metrics.direction)
+ if abs(startDelta) > 0.16 {
+ return startDelta > 0 ? 1 : -1
+ }
+
+ let endDelta = signedAngle(from: metrics.direction, to: endForward)
+ if abs(endDelta) > 0.18 {
+ return endDelta > 0 ? -1 : 1
+ }
+
if abs(metrics.dy) > abs(metrics.dx) * 0.72 {
return metrics.dy > 0 ? -1 : 1
}
- return metrics.dx >= 0 ? 1 : -1
- }
- private static func headingVector(rotation: CGFloat) -> CGVector {
- let angle = baseCursorHeading + rotation
- return CGVector(dx: cos(angle), dy: sin(angle))
+ return metrics.dx >= 0 ? 1 : -1
}
private static func resolvedGuide(
@@ -551,21 +1071,45 @@ enum CursorMotionPathBuilder {
headingWeight: CGFloat,
normalBias: CGFloat
) -> CGVector {
- normalized(CGVector(
- dx: (line.dx * lineWeight) + (forward.dx * headingWeight) + (normal.dx * normalBias * sideSign),
- dy: (line.dy * lineWeight) + (forward.dy * headingWeight) + (normal.dy * normalBias * sideSign)
- ))
+ normalizedOrDefault(
+ line.scaled(by: lineWeight)
+ + forward.scaled(by: headingWeight)
+ + normal.scaled(by: normalBias * sideSign)
+ )
}
- private static func normalized(_ vector: CGVector) -> CGVector {
- let length = max(hypot(vector.dx, vector.dy), 0.001)
+ private static func normalizedOrDefault(_ vector: CGVector) -> CGVector {
+ let length = max(vector.length, normalizationEpsilon)
return CGVector(dx: vector.dx / length, dy: vector.dy / length)
}
+ private static func signedAngle(from lhs: CGVector, to rhs: CGVector) -> CGFloat {
+ atan2((lhs.dx * rhs.dy) - (lhs.dy * rhs.dx), (lhs.dx * rhs.dx) + (lhs.dy * rhs.dy))
+ }
+
+ private struct MotionScoringContext {
+ let metrics: MotionMetrics
+ let startForward: CGVector
+ let endForward: CGVector
+ let preferredSide: Int
+
+ var turnDemand: CGFloat {
+ min(abs(HeadingDrivenCursorMotionModel.signedAngle(from: startForward, to: metrics.direction)) / .pi, 1)
+ }
+
+ var arrivalDemand: CGFloat {
+ min(abs(HeadingDrivenCursorMotionModel.signedAngle(from: metrics.direction, to: endForward)) / .pi, 1)
+ }
+
+ var directness: CGFloat {
+ (1 - max(turnDemand, arrivalDemand * 0.82)).clamped(to: 0...1)
+ }
+ }
+
private struct MotionDescriptor {
let id: String
let family: String
- let side: CGFloat
+ let side: Int
let startReachScale: CGFloat
let endReachScale: CGFloat
let startLineWeight: CGFloat
@@ -580,6 +1124,11 @@ enum CursorMotionPathBuilder {
let endFlowWeight: CGFloat
let flowShift: CGFloat
let arcScale: CGFloat
+ let scoreBias: CGFloat
+
+ var kind: CursorMotionKind {
+ family == "direct" ? .base : .arched
+ }
}
private struct MotionMetrics {
@@ -602,8 +1151,8 @@ enum CursorMotionPathBuilder {
dx = end.x - start.x
dy = end.y - start.y
distance = max(hypot(dx, dy), 1)
- direction = normalized(CGVector(dx: dx, dy: dy))
- normal = normalized(CGVector(dx: -direction.dy, dy: direction.dx))
+ direction = HeadingDrivenCursorMotionModel.normalizedOrDefault(CGVector(dx: dx, dy: dy))
+ normal = HeadingDrivenCursorMotionModel.normalizedOrDefault(CGVector(dx: -direction.dy, dy: direction.dx))
horizontalFactor = abs(dx) / distance
verticalFactor = abs(dy) / distance
diagonalFactor = min(horizontalFactor, verticalFactor) * 2
@@ -613,104 +1162,245 @@ enum CursorMotionPathBuilder {
}
}
-struct CursorSpringParameters: Equatable {
- let durationScale: CGFloat
- let headingResponse: CGFloat
- let finishRelaxation: CGFloat
+struct CursorVisualSpringConfiguration: Equatable {
+ let response: CGFloat
+ let dampingFraction: CGFloat
+ let stiffness: CGFloat
+ let drag: CGFloat
+ let dt: CGFloat
+ let idleVelocityThreshold: CGFloat
+
+ init(
+ response: CGFloat,
+ dampingFraction: CGFloat,
+ dt: CGFloat = 1.0 / 240.0,
+ idleVelocityThreshold: CGFloat = 28_800
+ ) {
+ let rawStiffness = response > 0 ? pow((2 * .pi) / response, 2) : .infinity
+
+ self.response = response
+ self.dampingFraction = dampingFraction
+ self.dt = dt
+ self.idleVelocityThreshold = idleVelocityThreshold
+ stiffness = min(rawStiffness, idleVelocityThreshold)
+ drag = 2 * dampingFraction * sqrt(stiffness)
+ }
+}
- static func from(_ spring: CGFloat) -> CursorSpringParameters {
- CursorSpringParameters(
- durationScale: 1.08 - (spring * 0.26),
- headingResponse: 0.18 + (spring * 0.38),
- finishRelaxation: 0.10 + ((1 - spring) * 0.10)
- )
+struct CursorVisualDynamicsConfiguration: Equatable {
+ let tipSpring: CursorVisualSpringConfiguration
+ let angleSpring: CursorVisualSpringConfiguration
+ let headingVelocityFloor: CGFloat
+ let animatedAngleOffsetMax: CGFloat
+ let bodyOffsetScale: CGFloat
+ let bodyOffsetMax: CGFloat
+ let bodyLateralScale: CGFloat
+ let bodyLateralMax: CGFloat
+ let fogOffsetScale: CGFloat
+ let fogOffsetMax: CGFloat
+ let fogOpacityBase: CGFloat
+ let fogOpacityVelocityScale: CGFloat
+ let fogScaleVelocityScale: CGFloat
+ let fogScaleMaxDelta: CGFloat
+
+ static let officialInspired = CursorVisualDynamicsConfiguration(
+ tipSpring: CursorVisualSpringConfiguration(response: 0.18, dampingFraction: 0.76),
+ angleSpring: CursorVisualSpringConfiguration(response: 0.24, dampingFraction: 0.82),
+ headingVelocityFloor: 14,
+ animatedAngleOffsetMax: 0.26,
+ bodyOffsetScale: 0.0012,
+ bodyOffsetMax: 2.4,
+ bodyLateralScale: 0.06,
+ bodyLateralMax: 1.4,
+ fogOffsetScale: 0.0045,
+ fogOffsetMax: 9,
+ fogOpacityBase: 0.12,
+ fogOpacityVelocityScale: 0.00006,
+ fogScaleVelocityScale: 0.00012,
+ fogScaleMaxDelta: 0.22
+ )
+}
+
+struct CursorVisualDynamicsState: Equatable {
+ var time: CGFloat
+ var tipPosition: CGPoint
+ var tipVelocity: CGVector
+ var tipForce: CGVector
+ var angle: CGFloat
+ var angleVelocity: CGFloat
+ var angleForce: CGFloat
+
+ init(
+ time: CGFloat = 0,
+ tipPosition: CGPoint,
+ tipVelocity: CGVector = .zero,
+ tipForce: CGVector = .zero,
+ angle: CGFloat = 0,
+ angleVelocity: CGFloat = 0,
+ angleForce: CGFloat = 0
+ ) {
+ self.time = time
+ self.tipPosition = tipPosition
+ self.tipVelocity = tipVelocity
+ self.tipForce = tipForce
+ self.angle = angle
+ self.angleVelocity = angleVelocity
+ self.angleForce = angleForce
}
}
-struct CursorMotionState {
- let point: CGPoint
+struct CursorVisualRenderState: Equatable {
+ let tipPosition: CGPoint
let rotation: CGFloat
- let trailProgress: CGFloat
- let isSettled: Bool
+ let cursorBodyOffset: CGVector
+ let fogOffset: CGVector
+ let fogOpacity: CGFloat
+ let fogScale: CGFloat
}
-private struct CursorMotionTimingLookup {
- struct Sample {
- let t: CGFloat
- let weightedDistance: CGFloat
- }
-
- let samples: [Sample]
- let pathLength: CGFloat
- let weightedLength: CGFloat
-
- static func build(for path: CursorMotionPath) -> CursorMotionTimingLookup {
- let sampleCount = 120
- var samples: [Sample] = [.init(t: 0, weightedDistance: 0)]
- var previous = path.sample(at: 0)
- var previousHeading = atan2(previous.tangent.dy, previous.tangent.dx)
- var pathLength: CGFloat = 0
- var weightedLength: CGFloat = 0
-
- for index in 1...sampleCount {
- let t = CGFloat(index) / CGFloat(sampleCount)
- let current = path.sample(at: t)
- let ds = hypot(current.point.x - previous.point.x, current.point.y - previous.point.y)
- let heading = atan2(current.tangent.dy, current.tangent.dx)
- let headingChange = abs(normalize(angle: heading - previousHeading))
- let midpoint = (t + samples[index - 1].t) * 0.5
- let curvature = path.curvature(at: midpoint)
- let curvatureWeight = min(curvature * max(path.arcHeight, 48), 1.75)
- let segmentProfile = edgeProfile(at: midpoint)
- let effortMultiplier = 1
- + (headingChange * 1.9)
- + (curvatureWeight * 0.65)
- + (segmentProfile * (0.08 + (headingChange * 0.45)))
-
- pathLength += ds
- weightedLength += ds * effortMultiplier
- samples.append(.init(t: t, weightedDistance: weightedLength))
-
- previous = current
- previousHeading = heading
- }
-
- return CursorMotionTimingLookup(samples: samples, pathLength: pathLength, weightedLength: weightedLength)
- }
-
- func parameter(at progress: CGFloat) -> CGFloat {
- guard weightedLength > 0, samples.count > 1 else {
- return progress.clamped(to: 0...1)
- }
-
- let target = progress.clamped(to: 0...1) * weightedLength
- var low = 0
- var high = samples.count - 1
-
- while low < high {
- let mid = (low + high) / 2
- if samples[mid].weightedDistance < target {
- low = mid + 1
- } else {
- high = mid
- }
+enum CursorVisualDynamicsAnimator {
+ static func state(at tipPosition: CGPoint, time: CGFloat = 0) -> CursorVisualDynamicsState {
+ CursorVisualDynamicsState(time: time, tipPosition: tipPosition)
+ }
+
+ static func advance(
+ state: CursorVisualDynamicsState,
+ targetTipPosition: CGPoint,
+ targetTime: CGFloat,
+ idleAngleOffset: CGFloat = 0,
+ baseHeading: CGFloat,
+ configuration: CursorVisualDynamicsConfiguration = .officialInspired
+ ) -> (state: CursorVisualDynamicsState, renderState: CursorVisualRenderState) {
+ var adjustedState = state
+
+ if (targetTime - adjustedState.time) > 1 {
+ adjustedState.time = targetTime - (1.0 / 60.0)
}
- let upperIndex = max(low, 1)
- let upper = samples[upperIndex]
- let lower = samples[upperIndex - 1]
- let span = max(upper.weightedDistance - lower.weightedDistance, 0.001)
- let localProgress = ((target - lower.weightedDistance) / span).clamped(to: 0...1)
- return lower.t + ((upper.t - lower.t) * localProgress)
+ while adjustedState.time < targetTime {
+ adjustedState = advanceStep(
+ state: adjustedState,
+ targetTipPosition: targetTipPosition,
+ idleAngleOffset: idleAngleOffset,
+ baseHeading: baseHeading,
+ configuration: configuration
+ )
+ }
+
+ return (
+ adjustedState,
+ renderState(
+ state: adjustedState,
+ idleAngleOffset: idleAngleOffset,
+ baseHeading: baseHeading,
+ configuration: configuration
+ )
+ )
}
- private static func edgeProfile(at t: CGFloat) -> CGFloat {
- let startBias = exp(-pow((t - 0.08) / 0.16, 2))
- let endBias = exp(-pow((t - 0.90) / 0.14, 2))
- return max(startBias, endBias)
+ private static func advanceStep(
+ state: CursorVisualDynamicsState,
+ targetTipPosition: CGPoint,
+ idleAngleOffset: CGFloat,
+ baseHeading: CGFloat,
+ configuration: CursorVisualDynamicsConfiguration
+ ) -> CursorVisualDynamicsState {
+ let dt = configuration.tipSpring.dt
+ let halfDT = dt * 0.5
+
+ let tipVelocityHalf = state.tipVelocity + state.tipForce.scaled(by: halfDT)
+ let nextTipPosition = state.tipPosition + tipVelocityHalf.scaled(by: dt)
+ let tipDisplacement = targetTipPosition - nextTipPosition
+ let tipForce = tipDisplacement.scaled(by: configuration.tipSpring.stiffness)
+ + tipVelocityHalf.scaled(by: -configuration.tipSpring.drag)
+ let tipVelocity = tipVelocityHalf + tipForce.scaled(by: halfDT)
+
+ let targetAngle = resolvedTargetAngle(
+ velocity: tipVelocity,
+ idleAngleOffset: idleAngleOffset,
+ baseHeading: baseHeading,
+ configuration: configuration
+ )
+ let angleVelocityHalf = state.angleVelocity + (state.angleForce * halfDT)
+ let nextAngle = normalizeAngle(state.angle + (angleVelocityHalf * dt))
+ let angleError = normalizeAngle(targetAngle - nextAngle)
+ let angleForce = (angleError * configuration.angleSpring.stiffness)
+ + ((-configuration.angleSpring.drag) * angleVelocityHalf)
+ let angleVelocity = angleVelocityHalf + (angleForce * halfDT)
+
+ return CursorVisualDynamicsState(
+ time: state.time + dt,
+ tipPosition: nextTipPosition,
+ tipVelocity: tipVelocity,
+ tipForce: tipForce,
+ angle: normalizeAngle(nextAngle),
+ angleVelocity: angleVelocity,
+ angleForce: angleForce
+ )
}
- private static func normalize(angle: CGFloat) -> CGFloat {
+ private static func renderState(
+ state: CursorVisualDynamicsState,
+ idleAngleOffset: CGFloat,
+ baseHeading: CGFloat,
+ configuration: CursorVisualDynamicsConfiguration
+ ) -> CursorVisualRenderState {
+ let speed = state.tipVelocity.length
+ let direction = speed > 0.001
+ ? state.tipVelocity.normalized
+ : CGVector(dx: cos(baseHeading + idleAngleOffset), dy: sin(baseHeading + idleAngleOffset))
+ let bodyBackward = direction.scaled(
+ by: -min(speed * configuration.bodyOffsetScale, configuration.bodyOffsetMax)
+ )
+ let lateralAmount = CGFloat.clamped(
+ state.angleVelocity * configuration.bodyLateralScale,
+ lower: -configuration.bodyLateralMax,
+ upper: configuration.bodyLateralMax
+ )
+ let bodyLateral = direction.perpendicular.scaled(by: lateralAmount)
+ let cursorBodyOffset = bodyBackward + bodyLateral
+ let fogOffset = direction.scaled(
+ by: -min(speed * configuration.fogOffsetScale, configuration.fogOffsetMax)
+ ) + bodyLateral.scaled(by: 0.6)
+ let fogOpacity = min(
+ configuration.fogOpacityBase + (speed * configuration.fogOpacityVelocityScale),
+ 0.34
+ )
+ let fogScale = 1 + min(
+ speed * configuration.fogScaleVelocityScale,
+ configuration.fogScaleMaxDelta
+ )
+
+ return CursorVisualRenderState(
+ tipPosition: state.tipPosition,
+ rotation: normalizeAngle(
+ state.angle + idleAngleOffset.clamped(
+ to: -configuration.animatedAngleOffsetMax...configuration.animatedAngleOffsetMax
+ )
+ ),
+ cursorBodyOffset: cursorBodyOffset,
+ fogOffset: fogOffset,
+ fogOpacity: fogOpacity,
+ fogScale: fogScale
+ )
+ }
+
+ private static func resolvedTargetAngle(
+ velocity: CGVector,
+ idleAngleOffset: CGFloat,
+ baseHeading: CGFloat,
+ configuration: CursorVisualDynamicsConfiguration
+ ) -> CGFloat {
+ let speed = velocity.length
+ guard speed > configuration.headingVelocityFloor else {
+ return 0
+ }
+
+ let heading = atan2(velocity.dy, velocity.dx)
+ return normalizeAngle(heading - baseHeading)
+ }
+
+ private static func normalizeAngle(_ angle: CGFloat) -> CGFloat {
var value = angle
while value > .pi {
value -= 2 * .pi
@@ -722,151 +1412,277 @@ private struct CursorMotionTimingLookup {
}
}
+struct CursorMotionState: Equatable {
+ let point: CGPoint
+ let rotation: CGFloat
+ let cursorBodyOffset: CGVector
+ let fogOffset: CGVector
+ let fogOpacity: CGFloat
+ let fogScale: CGFloat
+ let trailProgress: CGFloat
+ let isSettled: Bool
+}
+
+private enum CursorMotionPhase {
+ case moving
+ case idle(restingTipPosition: CGPoint)
+}
+
final class CursorMotionSimulator {
+ private static let baseHeading = CursorGlyphCalibration.neutralHeading + CursorGlyphCalibration.restingRotation
+
private(set) var parameters: CursorMotionParameters
private(set) var path: CursorMotionPath
- private(set) var springParameters: CursorSpringParameters
private(set) var start: CGPoint
private(set) var end: CGPoint
- private var timingLookup: CursorMotionTimingLookup
- private var elapsedTime: CGFloat = 0
- private var travelDuration: CGFloat = 0.42
- private var displayedRotation: CGFloat = 0
+ private var measurement: CursorMotionMeasurement
+ private var phase: CursorMotionPhase
+ private var progress: CGFloat
+ private var progressSpringState: CursorMotionSpringState
+ private var moveElapsed: CGFloat
+ private var travelDuration: CGFloat
+ private var visualState: CursorVisualDynamicsState
+ private var time: CGFloat
+ private var idlePhase: CGFloat
init(start: CGPoint, end: CGPoint, parameters: CursorMotionParameters) {
self.parameters = parameters
+ path = CursorMotionPath(start: start, end: end)
self.start = start
self.end = end
- self.path = CursorMotionPathBuilder.makePath(from: start, to: end, parameters: parameters)
- self.springParameters = .from(parameters.spring)
- self.timingLookup = CursorMotionTimingLookup.build(for: path)
- self.travelDuration = Self.duration(for: timingLookup, spring: springParameters)
- self.displayedRotation = CursorGlyphCalibration.restingRotation
+ measurement = path.measure(bounds: nil)
+ phase = .idle(restingTipPosition: start)
+ progress = 1
+ progressSpringState = CursorMotionSpringState()
+ moveElapsed = 0
+ travelDuration = OfficialCursorMotionModel.calibratedTravelDuration(
+ distance: distanceBetween(start, end),
+ measurement: measurement
+ )
+ visualState = CursorVisualDynamicsAnimator.state(at: start)
+ time = 0
+ idlePhase = 0
}
- func reset(start: CGPoint? = nil, end: CGPoint? = nil, parameters: CursorMotionParameters? = nil) {
- if let parameters {
- self.parameters = parameters
- }
- if let start {
- self.start = start
- }
- if let end {
- self.end = end
+ @discardableResult
+ func snap(to point: CGPoint, path newPath: CursorMotionPath? = nil) -> CursorMotionState {
+ if let newPath {
+ path = newPath
+ start = newPath.start
+ end = newPath.end
+ measurement = newPath.measure(bounds: nil)
}
- path = CursorMotionPathBuilder.makePath(from: self.start, to: self.end, parameters: self.parameters)
- springParameters = .from(self.parameters.spring)
- timingLookup = CursorMotionTimingLookup.build(for: path)
- travelDuration = Self.duration(for: timingLookup, spring: springParameters)
- elapsedTime = 0
- displayedRotation = CursorGlyphCalibration.restingRotation
+ time = 0
+ idlePhase = 0
+ moveElapsed = 0
+ progress = 1
+ progressSpringState = CursorMotionSpringState()
+ visualState = CursorVisualDynamicsAnimator.state(at: point, time: time)
+ phase = .idle(restingTipPosition: point)
+ return renderCurrentState(trailProgress: 1, isSettled: true)
}
- func reset(path: CursorMotionPath, parameters: CursorMotionParameters? = nil) {
- if let parameters {
- self.parameters = parameters
- }
+ func begin(path: CursorMotionPath, measurement: CursorMotionMeasurement) {
self.path = path
- self.start = path.start
- self.end = path.end
- springParameters = .from(self.parameters.spring)
- timingLookup = CursorMotionTimingLookup.build(for: path)
- travelDuration = Self.duration(for: timingLookup, spring: springParameters)
- elapsedTime = 0
- displayedRotation = CursorGlyphCalibration.restingRotation
+ start = path.start
+ end = path.end
+ self.measurement = measurement
+ progress = 0
+ progressSpringState = CursorMotionSpringState()
+ moveElapsed = 0
+ idlePhase = 0
+ travelDuration = OfficialCursorMotionModel.calibratedTravelDuration(
+ distance: distanceBetween(path.start, path.end),
+ measurement: measurement
+ )
+ phase = .moving
+
+ if visualState.tipPosition == .zero && path.start != .zero {
+ visualState = CursorVisualDynamicsAnimator.state(at: path.start, time: time)
+ }
}
func step(deltaTime dt: CGFloat) -> CursorMotionState {
let clampedDelta = max(1.0 / 240.0, min(dt, 1.0 / 24.0))
- elapsedTime += clampedDelta
- let rawProgress = (elapsedTime / max(travelDuration, 0.001)).clamped(to: 0...1)
- let effortProgress = minimumJerk(rawProgress)
- let pathProgress = timingLookup.parameter(at: effortProgress)
- let sample = path.sample(at: pathProgress)
- let point = sample.point
- let liveRotation = rotation(for: sample.tangent)
- let releaseStart = 1 - (springParameters.finishRelaxation * 0.55)
- let releaseBlend = smoothstep(
- from: releaseStart.clamped(to: 0...0.98),
- to: 1,
- value: rawProgress
- )
- let targetRotation = blendAngle(
- from: liveRotation,
- to: CursorGlyphCalibration.restingRotation,
- progress: releaseBlend
- )
- displayedRotation = interpolateAngle(
- from: displayedRotation,
- to: targetRotation,
- maxStep: (0.12 + (springParameters.headingResponse * 0.74)) * (clampedDelta * 60)
+ time += clampedDelta
+
+ switch phase {
+ case .moving:
+ moveElapsed += clampedDelta
+ let normalizedElapsed = (moveElapsed / max(travelDuration, 0.001)).clamped(to: 0...1)
+ let springTime = normalizedElapsed * OfficialCursorMotionModel.closeEnoughTime
+ (progress, progressSpringState) = CursorMotionProgressAnimator.advance(
+ current: progress,
+ state: progressSpringState,
+ to: springTime
+ )
+
+ let sample = path.sample(at: progress)
+ let renderState = advanceVisualDynamics(toward: sample.point)
+ let finished = normalizedElapsed >= 1 || CursorMotionProgressAnimator.isCloseEnough(progress: progress)
+
+ if finished {
+ progress = 1
+ phase = .idle(restingTipPosition: end)
+ let settledState = advanceVisualDynamics(toward: end)
+ return makeMotionState(renderState: settledState, trailProgress: 1, isSettled: true)
+ }
+
+ return makeMotionState(
+ renderState: renderState,
+ trailProgress: progress.clamped(to: 0...1),
+ isSettled: false
+ )
+
+ case let .idle(restingTipPosition):
+ idlePhase += clampedDelta * 3
+ let targetTipPosition = CGPoint(
+ x: restingTipPosition.x + (sin(idlePhase) * 1.6),
+ y: restingTipPosition.y + (cos(idlePhase * 0.47) * 0.7)
+ )
+ let idleAngleOffset = sin(idlePhase * 0.8) * 0.03
+ let renderState = advanceVisualDynamics(
+ toward: targetTipPosition,
+ idleAngleOffset: idleAngleOffset
+ )
+ return makeMotionState(renderState: renderState, trailProgress: 1, isSettled: true)
+ }
+ }
+
+ private func advanceVisualDynamics(
+ toward targetTipPosition: CGPoint,
+ idleAngleOffset: CGFloat = 0
+ ) -> CursorVisualRenderState {
+ let result = CursorVisualDynamicsAnimator.advance(
+ state: visualState,
+ targetTipPosition: targetTipPosition,
+ targetTime: time,
+ idleAngleOffset: idleAngleOffset,
+ baseHeading: Self.baseHeading
)
+ visualState = result.state
+ return result.renderState
+ }
- return CursorMotionState(
- point: point,
- rotation: rawProgress >= 1 ? CursorGlyphCalibration.restingRotation : displayedRotation,
- trailProgress: pathProgress,
- isSettled: rawProgress >= 1
+ private func renderCurrentState(trailProgress: CGFloat, isSettled: Bool) -> CursorMotionState {
+ let renderState = CursorVisualDynamicsAnimator.advance(
+ state: visualState,
+ targetTipPosition: visualState.tipPosition,
+ targetTime: time,
+ baseHeading: Self.baseHeading
+ ).renderState
+ return makeMotionState(renderState: renderState, trailProgress: trailProgress, isSettled: isSettled)
+ }
+
+ private func makeMotionState(
+ renderState: CursorVisualRenderState,
+ trailProgress: CGFloat,
+ isSettled: Bool
+ ) -> CursorMotionState {
+ CursorMotionState(
+ point: renderState.tipPosition,
+ rotation: CursorGlyphCalibration.restingRotation + renderState.rotation,
+ cursorBodyOffset: renderState.cursorBodyOffset,
+ fogOffset: renderState.fogOffset,
+ fogOpacity: renderState.fogOpacity,
+ fogScale: renderState.fogScale,
+ trailProgress: trailProgress,
+ isSettled: isSettled
)
}
+}
- private func rotation(for tangent: CGVector) -> CGFloat {
- guard tangent.dx != 0 || tangent.dy != 0 else {
- return CursorGlyphCalibration.restingRotation
- }
- let heading = atan2(tangent.dy, tangent.dx)
- return normalize(angle: heading - CursorGlyphCalibration.neutralHeading)
+private func sampleCubic(start: CGPoint, control1: CGPoint, control2: CGPoint, end: CGPoint, t: CGFloat) -> CGPoint {
+ let omt = 1 - t
+ let omt2 = omt * omt
+ let t2 = t * t
+
+ return CGPoint(
+ x: (omt2 * omt * start.x)
+ + (3 * omt2 * t * control1.x)
+ + (3 * omt * t2 * control2.x)
+ + (t2 * t * end.x),
+ y: (omt2 * omt * start.y)
+ + (3 * omt2 * t * control1.y)
+ + (3 * omt * t2 * control2.y)
+ + (t2 * t * end.y)
+ )
+}
+
+private func sampleCubicTangent(start: CGPoint, control1: CGPoint, control2: CGPoint, end: CGPoint, t: CGFloat) -> CGVector {
+ let omt = 1 - t
+ return CGVector(
+ dx: (3 * omt * omt * (control1.x - start.x))
+ + (6 * omt * t * (control2.x - control1.x))
+ + (3 * t * t * (end.x - control2.x)),
+ dy: (3 * omt * omt * (control1.y - start.y))
+ + (6 * omt * t * (control2.y - control1.y))
+ + (3 * t * t * (end.y - control2.y))
+ )
+}
+
+private func distanceBetween(_ lhs: CGPoint, _ rhs: CGPoint) -> CGFloat {
+ hypot(rhs.x - lhs.x, rhs.y - lhs.y)
+}
+
+private extension CGRect {
+ func contains(_ point: CGPoint, padding: CGFloat) -> Bool {
+ insetBy(dx: -padding, dy: -padding).contains(point)
}
+}
- private func normalize(angle: CGFloat) -> CGFloat {
- var value = angle
- while value > .pi {
- value -= 2 * .pi
- }
- while value < -.pi {
- value += 2 * .pi
- }
- return value
+private extension CGPoint {
+ static func + (lhs: CGPoint, rhs: CGVector) -> CGPoint {
+ CGPoint(x: lhs.x + rhs.dx, y: lhs.y + rhs.dy)
}
- private func minimumJerk(_ value: CGFloat) -> CGFloat {
- let t = value.clamped(to: 0...1)
- return (10 * pow(t, 3)) - (15 * pow(t, 4)) + (6 * pow(t, 5))
+ static func - (lhs: CGPoint, rhs: CGVector) -> CGPoint {
+ CGPoint(x: lhs.x - rhs.dx, y: lhs.y - rhs.dy)
}
- private func smoothstep(from start: CGFloat, to end: CGFloat, value: CGFloat) -> CGFloat {
- guard end > start else {
- return value >= end ? 1 : 0
- }
- let t = ((value - start) / (end - start)).clamped(to: 0...1)
- return t * t * (3 - (2 * t))
+ static func - (lhs: CGPoint, rhs: CGPoint) -> CGVector {
+ CGVector(dx: lhs.x - rhs.x, dy: lhs.y - rhs.y)
+ }
+}
+
+private extension CGVector {
+ static func + (lhs: CGVector, rhs: CGVector) -> CGVector {
+ CGVector(dx: lhs.dx + rhs.dx, dy: lhs.dy + rhs.dy)
}
- private func interpolateAngle(from current: CGFloat, to target: CGFloat, maxStep: CGFloat) -> CGFloat {
- let delta = normalize(angle: target - current)
- guard abs(delta) > maxStep else {
- return target
- }
- return normalize(angle: current + (delta.sign == .minus ? -maxStep : maxStep))
+ static func - (lhs: CGVector, rhs: CGVector) -> CGVector {
+ CGVector(dx: lhs.dx - rhs.dx, dy: lhs.dy - rhs.dy)
}
- private func blendAngle(from start: CGFloat, to end: CGFloat, progress: CGFloat) -> CGFloat {
- let clamped = progress.clamped(to: 0...1)
- let delta = normalize(angle: end - start)
- return normalize(angle: start + (delta * clamped))
+ var length: CGFloat {
+ hypot(dx, dy)
+ }
+
+ var normalized: CGVector {
+ let resolvedLength = max(length, 0.001)
+ return CGVector(dx: dx / resolvedLength, dy: dy / resolvedLength)
}
- private static func duration(for lookup: CursorMotionTimingLookup, spring: CursorSpringParameters) -> CGFloat {
- let distance = max(lookup.pathLength, 1)
- let distanceTerm = 0.18 + min(distance / 1320, 0.34)
- let curvatureTerm = min(max((lookup.weightedLength / distance) - 1, 0), 1.4) * 0.16
- return max((distanceTerm + curvatureTerm) * spring.durationScale, 0.22)
+ var perpendicular: CGVector {
+ CGVector(dx: -dy, dy: dx)
+ }
+
+ func scaled(by factor: CGFloat) -> CGVector {
+ CGVector(dx: dx * factor, dy: dy * factor)
}
}
-private extension CGFloat {
+extension CGFloat {
+ static func clamped(_ value: CGFloat, lower: CGFloat, upper: CGFloat) -> CGFloat {
+ Swift.min(Swift.max(value, lower), upper)
+ }
+
+ var cursorIdentifier: String {
+ String(format: "%.2f", Double(self))
+ }
+
func clamped(to range: ClosedRange<CGFloat>) -> CGFloat {
Swift.min(Swift.max(self, range.lowerBound), range.upperBound)
}
diff --git a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/CursorMotionModel.swift b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/CursorMotionModel.swift
new file mode 100644
index 0000000..c8a0003
--- /dev/null
+++ b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/CursorMotionModel.swift
@@ -0,0 +1,1497 @@
+import CoreGraphics
+import Foundation
+
+struct CursorMotionSegment: Equatable {
+ let end: CGPoint
+ let control1: CGPoint
+ let control2: CGPoint
+}
+
+struct CursorMotionPath: Equatable {
+ let start: CGPoint
+ let end: CGPoint
+ let startControl: CGPoint?
+ let arc: CGPoint?
+ let arcIn: CGPoint?
+ let arcOut: CGPoint?
+ let endControl: CGPoint?
+ let segments: [CursorMotionSegment]
+ let curveScale: CGFloat
+
+ init(
+ start: CGPoint,
+ end: CGPoint,
+ startControl: CGPoint? = nil,
+ arc: CGPoint? = nil,
+ arcIn: CGPoint? = nil,
+ arcOut: CGPoint? = nil,
+ endControl: CGPoint? = nil,
+ segments: [CursorMotionSegment],
+ curveScale: CGFloat = 1
+ ) {
+ self.start = start
+ self.end = end
+ self.startControl = startControl
+ self.arc = arc
+ self.arcIn = arcIn
+ self.arcOut = arcOut
+ self.endControl = endControl
+ self.segments = segments
+ self.curveScale = curveScale
+ }
+
+ init(start: CGPoint, end: CGPoint, curveDirection: CGFloat? = nil, curveScale: CGFloat = 1) {
+ let delta = end - start
+ let distance = max(delta.length, 1)
+ let normal = delta.perpendicular.normalized
+ let resolvedCurveDirection = curveDirection ?? (delta.dx >= 0 ? 1 : -1)
+ let resolvedCurveScale = max(curveScale, 0)
+ let curveAmount = min(max(distance * 0.22, 28), 110) * resolvedCurveScale
+ let controlOffset = normal.scaled(by: curveAmount * resolvedCurveDirection)
+ let control1Base = CGPoint(
+ x: start.x + (delta.dx * (resolvedCurveScale == 0 ? 1.0 / 3.0 : 0.18)),
+ y: start.y + (delta.dy * (resolvedCurveScale == 0 ? 1.0 / 3.0 : 0.10))
+ )
+ let control2Base = CGPoint(
+ x: start.x + (delta.dx * (resolvedCurveScale == 0 ? 2.0 / 3.0 : 0.80)),
+ y: start.y + (delta.dy * (resolvedCurveScale == 0 ? 2.0 / 3.0 : 0.96))
+ )
+ let control1 = control1Base + controlOffset
+ let control2 = control2Base + controlOffset.scaled(by: 0.48)
+
+ self.init(
+ start: start,
+ end: end,
+ startControl: control1,
+ endControl: control2,
+ segments: [
+ CursorMotionSegment(end: end, control1: control1, control2: control2)
+ ],
+ curveScale: resolvedCurveScale
+ )
+ }
+
+ func point(at progress: CGFloat) -> CGPoint {
+ sample(at: progress).point
+ }
+
+ func tangent(at progress: CGFloat) -> CGVector {
+ sample(at: progress).tangent
+ }
+
+ func sample(at progress: CGFloat) -> (point: CGPoint, tangent: CGVector) {
+ guard !segments.isEmpty else {
+ return (start, CGVector(dx: 1, dy: 0))
+ }
+
+ let clamped = progress.clamped(to: 0...1)
+ let segmentCount = segments.count
+ let segmentIndex: Int
+ let localT: CGFloat
+
+ if clamped >= 1 {
+ segmentIndex = segmentCount - 1
+ localT = 1
+ } else {
+ let scaled = clamped * CGFloat(segmentCount)
+ segmentIndex = min(Int(scaled), segmentCount - 1)
+ localT = scaled - CGFloat(segmentIndex)
+ }
+
+ let segment = segments[segmentIndex]
+ let segmentStart = segmentIndex == 0 ? start : segments[segmentIndex - 1].end
+ let point = sampleCubic(
+ start: segmentStart,
+ control1: segment.control1,
+ control2: segment.control2,
+ end: segment.end,
+ t: localT
+ )
+ let tangent = sampleCubicTangent(
+ start: segmentStart,
+ control1: segment.control1,
+ control2: segment.control2,
+ end: segment.end,
+ t: localT
+ ).normalized
+ return (point, tangent)
+ }
+
+ func sampledConstraintPoints(samplesPerSegment: Int = 6) -> [CGPoint] {
+ let totalSteps = max(segments.count * max(samplesPerSegment, 1), 1)
+ return (1...totalSteps).map { step in
+ point(at: CGFloat(step) / CGFloat(totalSteps))
+ }
+ }
+
+ func measure(bounds: CGRect?, minStepDistance: CGFloat = 0.01, samplesPerSegment: Int = 24) -> CursorMotionMeasurement {
+ var totalLength: CGFloat = 0
+ var angleChangeEnergy: CGFloat = 0
+ var maxAngleChange: CGFloat = 0
+ var totalTurn: CGFloat = 0
+ var staysInBounds = bounds?.contains(start, padding: 20) ?? true
+ var previousPoint = start
+ var previousAngle: CGFloat?
+
+ let totalSteps = max(segments.count * max(samplesPerSegment, 1), 1)
+ for step in 1...totalSteps {
+ let progress = CGFloat(step) / CGFloat(totalSteps)
+ let point = point(at: progress)
+ let delta = point - previousPoint
+ let stepLength = delta.length
+
+ if let bounds, staysInBounds {
+ staysInBounds = bounds.contains(point, padding: 20)
+ }
+
+ if stepLength > minStepDistance {
+ let angle = atan2(delta.dy, delta.dx)
+ totalLength += stepLength
+
+ if let previousAngle {
+ var angleDelta = angle - previousAngle
+ while angleDelta > .pi {
+ angleDelta -= (.pi * 2)
+ }
+ while angleDelta < -.pi {
+ angleDelta += (.pi * 2)
+ }
+
+ angleChangeEnergy += angleDelta * angleDelta
+ let absoluteDelta = abs(angleDelta)
+ maxAngleChange = max(maxAngleChange, absoluteDelta)
+ totalTurn += absoluteDelta
+ }
+
+ previousAngle = angle
+ previousPoint = point
+ }
+ }
+
+ return CursorMotionMeasurement(
+ length: totalLength,
+ angleChangeEnergy: angleChangeEnergy,
+ maxAngleChange: maxAngleChange,
+ totalTurn: totalTurn,
+ staysInBounds: staysInBounds
+ )
+ }
+}
+
+struct CursorMotionMeasurement: Equatable {
+ let length: CGFloat
+ let angleChangeEnergy: CGFloat
+ let maxAngleChange: CGFloat
+ let totalTurn: CGFloat
+ let staysInBounds: Bool
+}
+
+struct CursorMotionCandidate: Equatable {
+ let identifier: String
+ let kind: CursorMotionKind
+ let side: Int
+ let tableAScale: CGFloat?
+ let tableBScale: CGFloat?
+ let path: CursorMotionPath
+ let measurement: CursorMotionMeasurement
+ let score: CGFloat
+}
+
+enum CursorMotionKind: String, Equatable {
+ case base
+ case arched
+}
+
+struct CursorMotionSpringConfiguration: Equatable {
+ let response: CGFloat
+ let dampingFraction: CGFloat
+ let stiffness: CGFloat
+ let drag: CGFloat
+ let dt: CGFloat
+ let closeEnoughProgressThreshold: CGFloat
+ let closeEnoughDistanceThreshold: CGFloat
+ let idleVelocityThreshold: CGFloat
+
+ static let official: CursorMotionSpringConfiguration = {
+ let response: CGFloat = 1.4
+ let dampingFraction: CGFloat = 0.9
+ let dt: CGFloat = 1.0 / 240.0
+ let idleVelocityThreshold: CGFloat = 28_800
+ let rawStiffness = response > 0 ? pow((2 * .pi) / response, 2) : .infinity
+ let stiffness = min(rawStiffness, idleVelocityThreshold)
+ let drag = 2 * dampingFraction * sqrt(stiffness)
+
+ return CursorMotionSpringConfiguration(
+ response: response,
+ dampingFraction: dampingFraction,
+ stiffness: stiffness,
+ drag: drag,
+ dt: dt,
+ closeEnoughProgressThreshold: 1,
+ closeEnoughDistanceThreshold: 0.01,
+ idleVelocityThreshold: idleVelocityThreshold
+ )
+ }()
+}
+
+struct CursorMotionSpringState: Equatable {
+ var time: CGFloat = 0
+ var velocity: CGFloat = 0
+ var force: CGFloat = 0
+}
+
+enum CursorMotionProgressAnimator {
+ static func advance(
+ current: CGFloat,
+ target: CGFloat = 1,
+ state: CursorMotionSpringState,
+ configuration: CursorMotionSpringConfiguration = .official
+ ) -> (current: CGFloat, state: CursorMotionSpringState) {
+ let halfDT = configuration.dt * 0.5
+ let velocityHalf = state.velocity + (state.force * halfDT)
+ let nextCurrent = current + (velocityHalf * configuration.dt)
+ let force = (configuration.stiffness * (target - nextCurrent)) + ((-configuration.drag) * velocityHalf)
+ let velocity = velocityHalf + (force * halfDT)
+
+ return (
+ nextCurrent,
+ CursorMotionSpringState(
+ time: state.time + configuration.dt,
+ velocity: velocity,
+ force: force
+ )
+ )
+ }
+
+ static func advance(
+ current: CGFloat,
+ target: CGFloat = 1,
+ state: CursorMotionSpringState,
+ configuration: CursorMotionSpringConfiguration = .official,
+ to targetTime: CGFloat
+ ) -> (current: CGFloat, state: CursorMotionSpringState) {
+ var adjustedState = state
+ var adjustedCurrent = current
+
+ if (targetTime - adjustedState.time) > 1 {
+ adjustedState.time = targetTime - (1.0 / 60.0)
+ }
+
+ while adjustedState.time < targetTime {
+ (adjustedCurrent, adjustedState) = advance(
+ current: adjustedCurrent,
+ target: target,
+ state: adjustedState,
+ configuration: configuration
+ )
+ }
+
+ return (adjustedCurrent, adjustedState)
+ }
+
+ static func isCloseEnough(
+ progress: CGFloat,
+ target: CGFloat = 1,
+ configuration: CursorMotionSpringConfiguration = .official
+ ) -> Bool {
+ progress >= configuration.closeEnoughProgressThreshold
+ && abs(target - progress) <= configuration.closeEnoughDistanceThreshold
+ }
+
+ static func closeEnoughTime(
+ configuration: CursorMotionSpringConfiguration = .official
+ ) -> CGFloat {
+ var current: CGFloat = 0
+ var state = CursorMotionSpringState()
+ var step = 0
+
+ while step < 4_096 {
+ step += 1
+ let targetTime = CGFloat(step) * configuration.dt
+ (current, state) = advance(
+ current: current,
+ target: 1,
+ state: state,
+ configuration: configuration,
+ to: targetTime
+ )
+
+ if isCloseEnough(progress: current, configuration: configuration) {
+ return state.time
+ }
+ }
+
+ return 1.43
+ }
+}
+
+enum OfficialCursorMotionModel {
+ static let minimumStepDistance: CGFloat = 0.01
+ static let guideVectorInLocalBasis = CGVector(dx: -0.6946583704589973, dy: 0.7193398003386512)
+ static let tableA: [CGFloat] = [0.55, 0.8, 1.05]
+ static let tableB: [CGFloat] = [0.65, 1.0, 1.35]
+ static let closeEnoughTime = CursorMotionProgressAnimator.closeEnoughTime()
+
+ private static let normalizationEpsilon: CGFloat = 0.001
+ private static let sideBiasScale: CGFloat = 0.65
+ private static let primaryDistanceScale: CGFloat = 0.41960295031576633
+ private static let directSpanScale: CGFloat = 0.9
+ private static let secondaryDistanceScale: CGFloat = 0.2765523188064277
+ private static let arcDistanceScale: CGFloat = 0.5783555327868779
+ private static let candidateArcMin: CGFloat = 38
+ private static let candidateArcMax: CGFloat = 440
+ private static let scoreExcessLengthWeight: CGFloat = 320
+ private static let scoreAngleEnergyWeight: CGFloat = 140
+ private static let scoreMaxAngleWeight: CGFloat = 180
+ private static let scoreTotalTurnWeight: CGFloat = 18
+ private static let scoreOutOfBoundsPenalty: CGFloat = 45
+
+ static func makeCandidates(start: CGPoint, end: CGPoint, bounds: CGRect?) -> [CursorMotionCandidate] {
+ let delta = end - start
+ let distance = max(delta.length, normalizationEpsilon)
+ let direction = delta.normalized
+ let localNormal = direction.perpendicular
+ let guide = direction.scaled(by: guideVectorInLocalBasis.dx)
+ + localNormal.scaled(by: guideVectorInLocalBasis.dy)
+ let reverseGuide = guide.scaled(by: -1)
+
+ let (startExtentPre, endExtentPre) = binaryPiecewisePrimaryExtents(distance: distance)
+ let startExtent = min(startExtentPre, clipPositiveRay(origin: start, direction: guide, bounds: bounds))
+ let endExtent = min(endExtentPre, clipPositiveRay(origin: end, direction: reverseGuide, bounds: bounds))
+
+ let startExtentScaled = min(
+ max(startExtent * sideBiasScale, 0),
+ clipPositiveRay(origin: start, direction: guide, bounds: bounds)
+ )
+ let endExtentScaled = min(
+ max(endExtent * sideBiasScale, 0),
+ clipPositiveRay(origin: end, direction: reverseGuide, bounds: bounds)
+ )
+
+ let fullStartControl = start + guide.scaled(by: startExtent)
+ let fullEndControl = end - guide.scaled(by: endExtent)
+ let scaledStartControl = start + guide.scaled(by: startExtentScaled)
+ let scaledEndControl = end - guide.scaled(by: endExtentScaled)
+
+ let rawHandleExtent = binaryPiecewiseHandleExtent(distance: distance)
+ let rawArcExtent = (distance * arcDistanceScale).clamped(to: candidateArcMin...candidateArcMax)
+
+ let midpoint = CGPoint(x: (start.x + end.x) * 0.5, y: (start.y + end.y) * 0.5)
+ var signedNormal = localNormal
+ let cross = (guide.dy * direction.dx) - (guide.dx * direction.dy)
+ if cross < 0 {
+ signedNormal = signedNormal.scaled(by: -1)
+ }
+ let arcAnchorBias = guide.scaled(by: startExtent * sideBiasScale)
+ let forwardUnit = normalizedOrDefault(
+ direction.scaled(by: distance) + signedNormal.scaled(by: rawArcExtent),
+ minimumLength: rawHandleExtent
+ )
+
+ var candidates: [CursorMotionCandidate] = []
+ candidates.append(
+ makeCandidate(
+ identifier: "base-full-guide",
+ kind: .base,
+ side: 0,
+ tableAScale: nil,
+ tableBScale: nil,
+ path: CursorMotionPath(
+ start: start,
+ end: end,
+ startControl: fullStartControl,
+ endControl: fullEndControl,
+ segments: [
+ CursorMotionSegment(end: end, control1: fullStartControl, control2: fullEndControl)
+ ],
+ curveScale: 1
+ ),
+ distance: distance,
+ bounds: bounds
+ )
+ )
+ candidates.append(
+ makeCandidate(
+ identifier: "base-scaled-guide",
+ kind: .base,
+ side: 0,
+ tableAScale: nil,
+ tableBScale: nil,
+ path: CursorMotionPath(
+ start: start,
+ end: end,
+ startControl: scaledStartControl,
+ endControl: scaledEndControl,
+ segments: [
+ CursorMotionSegment(end: end, control1: scaledStartControl, control2: scaledEndControl)
+ ],
+ curveScale: sideBiasScale
+ ),
+ distance: distance,
+ bounds: bounds
+ )
+ )
+
+ for outerScale in tableA {
+ let anchorOffset = signedNormal.scaled(by: rawHandleExtent * outerScale)
+ for innerScale in tableB {
+ let tangentSpan = forwardUnit.scaled(by: rawArcExtent * innerScale)
+
+ for side in [1, -1] {
+ let anchor = midpoint + arcAnchorBias + anchorOffset.scaled(by: CGFloat(side))
+ let arcIn = anchor - tangentSpan
+ let arcOut = anchor + tangentSpan
+ let path = CursorMotionPath(
+ start: start,
+ end: end,
+ startControl: fullStartControl,
+ arc: anchor,
+ arcIn: arcIn,
+ arcOut: arcOut,
+ endControl: fullEndControl,
+ segments: [
+ CursorMotionSegment(end: anchor, control1: fullStartControl, control2: arcIn),
+ CursorMotionSegment(end: end, control1: arcOut, control2: fullEndControl)
+ ],
+ curveScale: innerScale
+ )
+
+ candidates.append(
+ makeCandidate(
+ identifier: "a\(outerScale.cursorIdentifier)-b\(innerScale.cursorIdentifier)-\(side > 0 ? "positive" : "negative")",
+ kind: .arched,
+ side: side,
+ tableAScale: outerScale,
+ tableBScale: innerScale,
+ path: path,
+ distance: distance,
+ bounds: bounds
+ )
+ )
+ }
+ }
+ }
+
+ return candidates
+ }
+
+ static func chooseBestCandidate(from candidates: [CursorMotionCandidate]) -> CursorMotionCandidate? {
+ guard !candidates.isEmpty else {
+ return nil
+ }
+
+ let inBoundsCandidates = candidates.filter(\.measurement.staysInBounds)
+ let pool = inBoundsCandidates.isEmpty ? candidates : inBoundsCandidates
+ return pool.min { lhs, rhs in
+ if lhs.score == rhs.score {
+ return lhs.identifier < rhs.identifier
+ }
+ return lhs.score < rhs.score
+ }
+ }
+
+ static func calibratedTravelDuration(distance: CGFloat, measurement: CursorMotionMeasurement) -> CGFloat {
+ let weightedRatio = max((measurement.length / max(distance, 1)) - 1, 0)
+ let distanceTerm = 0.18 + min(distance / 1300, 0.35)
+ let curvatureTerm = min(weightedRatio, 1.5) * 0.18
+ let settleTerm = min(weightedRatio, 1.0) * 0.04
+ return max(distanceTerm + curvatureTerm + settleTerm, 0.23)
+ }
+
+ private static func makeCandidate(
+ identifier: String,
+ kind: CursorMotionKind,
+ side: Int,
+ tableAScale: CGFloat?,
+ tableBScale: CGFloat?,
+ path: CursorMotionPath,
+ distance: CGFloat,
+ bounds: CGRect?
+ ) -> CursorMotionCandidate {
+ let measurement = path.measure(bounds: bounds, minStepDistance: minimumStepDistance)
+ let score = scoreCandidate(distance: distance, measurement: measurement)
+ return CursorMotionCandidate(
+ identifier: identifier,
+ kind: kind,
+ side: side,
+ tableAScale: tableAScale,
+ tableBScale: tableBScale,
+ path: path,
+ measurement: measurement,
+ score: score
+ )
+ }
+
+ private static func scoreCandidate(distance: CGFloat, measurement: CursorMotionMeasurement) -> CGFloat {
+ let excessLengthRatio = max((measurement.length / max(distance, 1)) - 1, 0)
+ return (excessLengthRatio * scoreExcessLengthWeight)
+ + (measurement.angleChangeEnergy * scoreAngleEnergyWeight)
+ + (measurement.maxAngleChange * scoreMaxAngleWeight)
+ + (measurement.totalTurn * scoreTotalTurnWeight)
+ + (measurement.staysInBounds ? 0 : scoreOutOfBoundsPenalty)
+ }
+
+ private static func binaryPiecewisePrimaryExtents(distance: CGFloat) -> (startExtent: CGFloat, endExtent: CGFloat) {
+ let primary = distance * primaryDistanceScale
+ let direct = distance * directSpanScale
+ let secondary = distance * 0.15
+ let lowCutoff: CGFloat = 48
+ let highCutoff: CGFloat = 640
+
+ if primary < lowCutoff {
+ return (lowCutoff, lowCutoff)
+ }
+ if primary < highCutoff {
+ return (primary, direct)
+ }
+ if secondary < highCutoff {
+ return (highCutoff, lowCutoff)
+ }
+ return (highCutoff, highCutoff)
+ }
+
+ private static func binaryPiecewiseHandleExtent(distance: CGFloat) -> CGFloat {
+ let raw = distance * secondaryDistanceScale
+ if raw < 50 {
+ return 50
+ }
+ if raw < 640 {
+ return raw
+ }
+ return 520
+ }
+
+ private static func clipPositiveRay(origin: CGPoint, direction: CGVector, bounds: CGRect?) -> CGFloat {
+ guard let bounds else {
+ return .infinity
+ }
+
+ var limit = CGFloat.infinity
+ if direction.dx > 0 {
+ limit = min(limit, (bounds.maxX - origin.x) / direction.dx)
+ } else if direction.dx < 0 {
+ limit = min(limit, (bounds.minX - origin.x) / direction.dx)
+ }
+
+ if direction.dy > 0 {
+ limit = min(limit, (bounds.maxY - origin.y) / direction.dy)
+ } else if direction.dy < 0 {
+ limit = min(limit, (bounds.minY - origin.y) / direction.dy)
+ }
+
+ return max(limit, 0)
+ }
+
+ private static func normalizedOrDefault(_ vector: CGVector, minimumLength: CGFloat) -> CGVector {
+ let length = vector.length
+ if length < minimumLength || length < normalizationEpsilon {
+ return CGVector(dx: 1, dy: 0)
+ }
+ return vector.scaled(by: 1 / length)
+ }
+}
+
+enum HeadingDrivenCursorMotionModel {
+ private static let defaultStartHandle: CGFloat = 0.29
+ private static let defaultEndHandle: CGFloat = 0.08
+ private static let defaultArcSize: CGFloat = 0.06
+ private static let defaultArcFlow: CGFloat = 0.64
+ private static let normalizationEpsilon: CGFloat = 0.001
+
+ static func makeCandidates(
+ start: CGPoint,
+ end: CGPoint,
+ bounds: CGRect?,
+ startForward: CGVector,
+ endForward: CGVector
+ ) -> [CursorMotionCandidate] {
+ let metrics = MotionMetrics(start: start, end: end)
+ let resolvedStartForward = normalizedOrDefault(startForward)
+ let resolvedEndForward = normalizedOrDefault(endForward)
+ let preferredSide = preferredTurnSide(
+ metrics: metrics,
+ startForward: resolvedStartForward,
+ endForward: resolvedEndForward
+ )
+ let scoringContext = MotionScoringContext(
+ metrics: metrics,
+ startForward: resolvedStartForward,
+ endForward: resolvedEndForward,
+ preferredSide: preferredSide
+ )
+
+ return descriptors(for: metrics, preferredSide: preferredSide).map { descriptor in
+ let path = makePath(
+ from: start,
+ to: end,
+ metrics: metrics,
+ descriptor: descriptor,
+ startForward: resolvedStartForward,
+ endForward: resolvedEndForward
+ )
+ return makeCandidate(
+ identifier: descriptor.id,
+ kind: descriptor.kind,
+ side: descriptor.side,
+ tableAScale: nil,
+ tableBScale: nil,
+ path: path,
+ bounds: bounds,
+ context: scoringContext,
+ descriptor: descriptor
+ )
+ }
+ }
+
+ static func chooseBestCandidate(from candidates: [CursorMotionCandidate]) -> CursorMotionCandidate? {
+ guard !candidates.isEmpty else {
+ return nil
+ }
+
+ let inBoundsCandidates = candidates.filter(\.measurement.staysInBounds)
+ let pool = inBoundsCandidates.isEmpty ? candidates : inBoundsCandidates
+ return pool.min { lhs, rhs in
+ if lhs.score == rhs.score {
+ return lhs.identifier < rhs.identifier
+ }
+ return lhs.score < rhs.score
+ }
+ }
+
+ static func calibratedTravelDuration(distance: CGFloat, measurement: CursorMotionMeasurement) -> CGFloat {
+ OfficialCursorMotionModel.calibratedTravelDuration(distance: distance, measurement: measurement)
+ }
+
+ private static func makePath(
+ from start: CGPoint,
+ to end: CGPoint,
+ metrics: MotionMetrics,
+ descriptor: MotionDescriptor,
+ startForward: CGVector,
+ endForward: CGVector
+ ) -> CursorMotionPath {
+ let distance = metrics.distance
+ let direction = metrics.direction
+ let normal = metrics.normal
+ let resolvedFlow = (defaultArcFlow + descriptor.flowShift).clamped(to: 0...1)
+ let flowBias = (resolvedFlow - 0.5) * distance * 0.18
+
+ let baseStartReach = distance * (0.10 + defaultStartHandle * 0.56)
+ let baseEndReach = distance * (0.11 + defaultEndHandle * 0.62)
+ let distanceLift = 0.68 + (metrics.farFactor * 0.56)
+ let baseArcHeight = min(
+ max(distance * (0.10 + defaultArcSize * 0.92) * descriptor.arcScale * distanceLift, 20),
+ distance * 0.96
+ )
+
+ let sideSign = CGFloat(descriptor.side)
+ let arcVector = CGVector(
+ dx: normal.dx * baseArcHeight * sideSign,
+ dy: normal.dy * baseArcHeight * sideSign
+ )
+
+ let startGuide = resolvedGuide(
+ line: direction,
+ forward: startForward,
+ normal: normal,
+ sideSign: sideSign,
+ lineWeight: descriptor.startLineWeight,
+ headingWeight: descriptor.startHeadingWeight,
+ normalBias: descriptor.startGuideNormalBias
+ )
+ let endGuide = resolvedGuide(
+ line: direction,
+ forward: endForward,
+ normal: normal,
+ sideSign: sideSign,
+ lineWeight: descriptor.endLineWeight,
+ headingWeight: descriptor.endHeadingWeight,
+ normalBias: descriptor.endGuideNormalBias
+ )
+
+ let startReach = max(baseStartReach * descriptor.startReachScale + flowBias * descriptor.startFlowWeight, 12)
+ let endReach = max(baseEndReach * descriptor.endReachScale - flowBias * descriptor.endFlowWeight, 12)
+ let control1Base = start + startGuide.scaled(by: startReach)
+ let control2Base = end - endGuide.scaled(by: endReach)
+
+ let control1 = control1Base + arcVector.scaled(by: descriptor.startNormalScale)
+ let control2 = control2Base + arcVector.scaled(by: descriptor.endNormalScale)
+ let resolvedArcHeight = baseArcHeight * max(
+ abs(descriptor.startNormalScale),
+ abs(descriptor.endNormalScale),
+ 0.12
+ )
+
+ return CursorMotionPath(
+ start: start,
+ end: end,
+ startControl: control1,
+ endControl: control2,
+ segments: [
+ CursorMotionSegment(end: end, control1: control1, control2: control2)
+ ],
+ curveScale: resolvedArcHeight
+ )
+ }
+
+ private static func makeCandidate(
+ identifier: String,
+ kind: CursorMotionKind,
+ side: Int,
+ tableAScale: CGFloat?,
+ tableBScale: CGFloat?,
+ path: CursorMotionPath,
+ bounds: CGRect?,
+ context: MotionScoringContext,
+ descriptor: MotionDescriptor
+ ) -> CursorMotionCandidate {
+ let measurement = path.measure(bounds: bounds, minStepDistance: OfficialCursorMotionModel.minimumStepDistance)
+ let score = scoreCandidate(
+ measurement: measurement,
+ path: path,
+ descriptor: descriptor,
+ context: context
+ )
+
+ return CursorMotionCandidate(
+ identifier: identifier,
+ kind: kind,
+ side: side,
+ tableAScale: tableAScale,
+ tableBScale: tableBScale,
+ path: path,
+ measurement: measurement,
+ score: score
+ )
+ }
+
+ private static func scoreCandidate(
+ measurement: CursorMotionMeasurement,
+ path: CursorMotionPath,
+ descriptor: MotionDescriptor,
+ context: MotionScoringContext
+ ) -> CGFloat {
+ let distance = max(context.metrics.distance, 1)
+ let excessLengthRatio = max((measurement.length / distance) - 1, 0)
+ let startTangent = normalizedOrDefault(path.tangent(at: 0.04))
+ let endTangent = normalizedOrDefault(path.tangent(at: 0.96))
+ let startHeadingError = abs(signedAngle(from: context.startForward, to: startTangent))
+ let endHeadingError = abs(signedAngle(from: endTangent, to: context.endForward))
+
+ var score = descriptor.scoreBias
+ score += excessLengthRatio * 180
+ score += measurement.angleChangeEnergy * 90
+ score += measurement.maxAngleChange * 85
+ score += measurement.totalTurn * (descriptor.side == 0 ? 10 : 12)
+ score += startHeadingError * 150
+ score += endHeadingError * 120
+
+ if descriptor.side == 0 {
+ score += context.turnDemand * 130
+ score += context.arrivalDemand * 30
+ } else {
+ score += context.directness * 90
+ if descriptor.side != context.preferredSide {
+ score += max(context.turnDemand, 0.45) * 200
+ }
+ }
+
+ switch descriptor.family {
+ case "turn":
+ score += (1 - context.turnDemand) * 55
+ case "brake":
+ score += (1 - context.arrivalDemand) * 40
+ case "orbit":
+ score += context.directness * 70
+ case "direct":
+ score += max(context.turnDemand - 0.12, 0) * 80
+ default:
+ break
+ }
+
+ if measurement.staysInBounds == false {
+ score += 90
+ }
+
+ return score
+ }
+
+ private static func descriptors(for metrics: MotionMetrics, preferredSide: Int) -> [MotionDescriptor] {
+ let orbitScale = 0.82 + (metrics.farFactor * 0.26)
+ let turnaroundScale = 0.90 + (metrics.farFactor * 0.30)
+ let brakingScale = 0.74 + (metrics.farFactor * 0.24)
+
+ return [
+ MotionDescriptor(
+ id: "direct-tight",
+ family: "direct",
+ side: 0,
+ startReachScale: 0.90,
+ endReachScale: 0.86,
+ startLineWeight: 1.12,
+ endLineWeight: 1.04,
+ startHeadingWeight: 0.18,
+ endHeadingWeight: 0.20,
+ startNormalScale: 0.02,
+ endNormalScale: 0.02,
+ startGuideNormalBias: 0,
+ endGuideNormalBias: 0,
+ startFlowWeight: 0.02,
+ endFlowWeight: 0.02,
+ flowShift: -0.02,
+ arcScale: 0.16,
+ scoreBias: 18
+ ),
+ MotionDescriptor(
+ id: "direct-soft",
+ family: "direct",
+ side: 0,
+ startReachScale: 0.98,
+ endReachScale: 0.94,
+ startLineWeight: 1.04,
+ endLineWeight: 0.96,
+ startHeadingWeight: 0.22,
+ endHeadingWeight: 0.28,
+ startNormalScale: 0.04,
+ endNormalScale: 0.08,
+ startGuideNormalBias: 0,
+ endGuideNormalBias: 0.04,
+ startFlowWeight: 0.04,
+ endFlowWeight: 0.08,
+ flowShift: 0.02,
+ arcScale: 0.24,
+ scoreBias: 24
+ ),
+ MotionDescriptor(
+ id: "turn-primary-tight",
+ family: "turn",
+ side: preferredSide,
+ startReachScale: 1.26,
+ endReachScale: 1.30,
+ startLineWeight: -0.24,
+ endLineWeight: -0.04,
+ startHeadingWeight: 1.50,
+ endHeadingWeight: 1.18,
+ startNormalScale: 0.46,
+ endNormalScale: 0.08,
+ startGuideNormalBias: 0.30,
+ endGuideNormalBias: 0.16,
+ startFlowWeight: -0.30,
+ endFlowWeight: 0.20,
+ flowShift: -0.08,
+ arcScale: turnaroundScale,
+ scoreBias: 40
+ ),
+ MotionDescriptor(
+ id: "turn-primary-wide",
+ family: "turn",
+ side: preferredSide,
+ startReachScale: 1.30,
+ endReachScale: 1.36,
+ startLineWeight: -0.28,
+ endLineWeight: -0.10,
+ startHeadingWeight: 1.54,
+ endHeadingWeight: 1.24,
+ startNormalScale: 0.58,
+ endNormalScale: 0.12,
+ startGuideNormalBias: 0.34,
+ endGuideNormalBias: 0.20,
+ startFlowWeight: -0.34,
+ endFlowWeight: 0.24,
+ flowShift: 0.06,
+ arcScale: turnaroundScale * 1.06,
+ scoreBias: 46
+ ),
+ MotionDescriptor(
+ id: "brake-primary-tight",
+ family: "brake",
+ side: preferredSide,
+ startReachScale: 0.92,
+ endReachScale: 1.42,
+ startLineWeight: 0.50,
+ endLineWeight: -0.20,
+ startHeadingWeight: 0.70,
+ endHeadingWeight: 1.52,
+ startNormalScale: 0.16,
+ endNormalScale: 0.20,
+ startGuideNormalBias: 0.10,
+ endGuideNormalBias: 0.26,
+ startFlowWeight: 0.10,
+ endFlowWeight: 0.32,
+ flowShift: -0.04,
+ arcScale: brakingScale,
+ scoreBias: 44
+ ),
+ MotionDescriptor(
+ id: "brake-primary-wide",
+ family: "brake",
+ side: preferredSide,
+ startReachScale: 0.98,
+ endReachScale: 1.50,
+ startLineWeight: 0.44,
+ endLineWeight: -0.26,
+ startHeadingWeight: 0.74,
+ endHeadingWeight: 1.62,
+ startNormalScale: 0.22,
+ endNormalScale: 0.26,
+ startGuideNormalBias: 0.12,
+ endGuideNormalBias: 0.32,
+ startFlowWeight: 0.14,
+ endFlowWeight: 0.38,
+ flowShift: 0.04,
+ arcScale: brakingScale * 1.04,
+ scoreBias: 50
+ ),
+ MotionDescriptor(
+ id: "orbit-primary-tight",
+ family: "orbit",
+ side: preferredSide,
+ startReachScale: 0.90,
+ endReachScale: 0.98,
+ startLineWeight: 0.72,
+ endLineWeight: 0.76,
+ startHeadingWeight: 0.30,
+ endHeadingWeight: 0.22,
+ startNormalScale: 0.90,
+ endNormalScale: 0.82,
+ startGuideNormalBias: 0.16,
+ endGuideNormalBias: 0.06,
+ startFlowWeight: 0.26,
+ endFlowWeight: 0.12,
+ flowShift: -0.06,
+ arcScale: orbitScale,
+ scoreBias: 54
+ ),
+ MotionDescriptor(
+ id: "orbit-primary-wide",
+ family: "orbit",
+ side: preferredSide,
+ startReachScale: 0.94,
+ endReachScale: 1.02,
+ startLineWeight: 0.68,
+ endLineWeight: 0.82,
+ startHeadingWeight: 0.28,
+ endHeadingWeight: 0.22,
+ startNormalScale: 1.02,
+ endNormalScale: 0.94,
+ startGuideNormalBias: 0.18,
+ endGuideNormalBias: 0.08,
+ startFlowWeight: 0.30,
+ endFlowWeight: 0.16,
+ flowShift: 0.06,
+ arcScale: orbitScale * 1.06,
+ scoreBias: 60
+ ),
+ MotionDescriptor(
+ id: "turn-secondary",
+ family: "turn",
+ side: -preferredSide,
+ startReachScale: 1.18,
+ endReachScale: 1.26,
+ startLineWeight: -0.18,
+ endLineWeight: 0.02,
+ startHeadingWeight: 1.32,
+ endHeadingWeight: 1.08,
+ startNormalScale: 0.34,
+ endNormalScale: 0.06,
+ startGuideNormalBias: 0.22,
+ endGuideNormalBias: 0.14,
+ startFlowWeight: -0.20,
+ endFlowWeight: 0.14,
+ flowShift: 0.02,
+ arcScale: turnaroundScale * 0.92,
+ scoreBias: 88
+ ),
+ MotionDescriptor(
+ id: "brake-secondary",
+ family: "brake",
+ side: -preferredSide,
+ startReachScale: 0.90,
+ endReachScale: 1.34,
+ startLineWeight: 0.52,
+ endLineWeight: -0.16,
+ startHeadingWeight: 0.62,
+ endHeadingWeight: 1.40,
+ startNormalScale: 0.12,
+ endNormalScale: 0.18,
+ startGuideNormalBias: 0.08,
+ endGuideNormalBias: 0.20,
+ startFlowWeight: 0.10,
+ endFlowWeight: 0.28,
+ flowShift: -0.02,
+ arcScale: brakingScale * 0.92,
+ scoreBias: 96
+ ),
+ ]
+ }
+
+ private static func preferredTurnSide(
+ metrics: MotionMetrics,
+ startForward: CGVector,
+ endForward: CGVector
+ ) -> Int {
+ let startDelta = signedAngle(from: startForward, to: metrics.direction)
+ if abs(startDelta) > 0.16 {
+ return startDelta > 0 ? 1 : -1
+ }
+
+ let endDelta = signedAngle(from: metrics.direction, to: endForward)
+ if abs(endDelta) > 0.18 {
+ return endDelta > 0 ? -1 : 1
+ }
+
+ if abs(metrics.dy) > abs(metrics.dx) * 0.72 {
+ return metrics.dy > 0 ? -1 : 1
+ }
+
+ return metrics.dx >= 0 ? 1 : -1
+ }
+
+ private static func resolvedGuide(
+ line: CGVector,
+ forward: CGVector,
+ normal: CGVector,
+ sideSign: CGFloat,
+ lineWeight: CGFloat,
+ headingWeight: CGFloat,
+ normalBias: CGFloat
+ ) -> CGVector {
+ normalizedOrDefault(
+ line.scaled(by: lineWeight)
+ + forward.scaled(by: headingWeight)
+ + normal.scaled(by: normalBias * sideSign)
+ )
+ }
+
+ private static func normalizedOrDefault(_ vector: CGVector) -> CGVector {
+ let length = max(vector.length, normalizationEpsilon)
+ return CGVector(dx: vector.dx / length, dy: vector.dy / length)
+ }
+
+ private static func signedAngle(from lhs: CGVector, to rhs: CGVector) -> CGFloat {
+ atan2((lhs.dx * rhs.dy) - (lhs.dy * rhs.dx), (lhs.dx * rhs.dx) + (lhs.dy * rhs.dy))
+ }
+
+ private struct MotionScoringContext {
+ let metrics: MotionMetrics
+ let startForward: CGVector
+ let endForward: CGVector
+ let preferredSide: Int
+
+ var turnDemand: CGFloat {
+ min(abs(HeadingDrivenCursorMotionModel.signedAngle(from: startForward, to: metrics.direction)) / .pi, 1)
+ }
+
+ var arrivalDemand: CGFloat {
+ min(abs(HeadingDrivenCursorMotionModel.signedAngle(from: metrics.direction, to: endForward)) / .pi, 1)
+ }
+
+ var directness: CGFloat {
+ (1 - max(turnDemand, arrivalDemand * 0.82)).clamped(to: 0...1)
+ }
+ }
+
+ private struct MotionDescriptor {
+ let id: String
+ let family: String
+ let side: Int
+ let startReachScale: CGFloat
+ let endReachScale: CGFloat
+ let startLineWeight: CGFloat
+ let endLineWeight: CGFloat
+ let startHeadingWeight: CGFloat
+ let endHeadingWeight: CGFloat
+ let startNormalScale: CGFloat
+ let endNormalScale: CGFloat
+ let startGuideNormalBias: CGFloat
+ let endGuideNormalBias: CGFloat
+ let startFlowWeight: CGFloat
+ let endFlowWeight: CGFloat
+ let flowShift: CGFloat
+ let arcScale: CGFloat
+ let scoreBias: CGFloat
+
+ var kind: CursorMotionKind {
+ family == "direct" ? .base : .arched
+ }
+ }
+
+ private struct MotionMetrics {
+ let start: CGPoint
+ let end: CGPoint
+ let dx: CGFloat
+ let dy: CGFloat
+ let distance: CGFloat
+ let direction: CGVector
+ let normal: CGVector
+ let horizontalFactor: CGFloat
+ let verticalFactor: CGFloat
+ let diagonalFactor: CGFloat
+ let closeFactor: CGFloat
+ let farFactor: CGFloat
+
+ init(start: CGPoint, end: CGPoint) {
+ self.start = start
+ self.end = end
+ dx = end.x - start.x
+ dy = end.y - start.y
+ distance = max(hypot(dx, dy), 1)
+ direction = HeadingDrivenCursorMotionModel.normalizedOrDefault(CGVector(dx: dx, dy: dy))
+ normal = HeadingDrivenCursorMotionModel.normalizedOrDefault(CGVector(dx: -direction.dy, dy: direction.dx))
+ horizontalFactor = abs(dx) / distance
+ verticalFactor = abs(dy) / distance
+ diagonalFactor = min(horizontalFactor, verticalFactor) * 2
+ closeFactor = (1 - (distance / 280)).clamped(to: 0...1)
+ farFactor = ((distance - 180) / 540).clamped(to: 0...1)
+ }
+ }
+}
+
+struct CursorVisualSpringConfiguration: Equatable {
+ let response: CGFloat
+ let dampingFraction: CGFloat
+ let stiffness: CGFloat
+ let drag: CGFloat
+ let dt: CGFloat
+ let idleVelocityThreshold: CGFloat
+
+ init(
+ response: CGFloat,
+ dampingFraction: CGFloat,
+ dt: CGFloat = 1.0 / 240.0,
+ idleVelocityThreshold: CGFloat = 28_800
+ ) {
+ let rawStiffness = response > 0 ? pow((2 * .pi) / response, 2) : .infinity
+
+ self.response = response
+ self.dampingFraction = dampingFraction
+ self.dt = dt
+ self.idleVelocityThreshold = idleVelocityThreshold
+ self.stiffness = min(rawStiffness, idleVelocityThreshold)
+ self.drag = 2 * dampingFraction * sqrt(self.stiffness)
+ }
+}
+
+struct CursorVisualDynamicsConfiguration: Equatable {
+ let tipSpring: CursorVisualSpringConfiguration
+ let angleSpring: CursorVisualSpringConfiguration
+ let headingVelocityFloor: CGFloat
+ let animatedAngleOffsetMax: CGFloat
+ let bodyOffsetScale: CGFloat
+ let bodyOffsetMax: CGFloat
+ let bodyLateralScale: CGFloat
+ let bodyLateralMax: CGFloat
+ let fogOffsetScale: CGFloat
+ let fogOffsetMax: CGFloat
+ let fogOpacityBase: CGFloat
+ let fogOpacityVelocityScale: CGFloat
+ let fogScaleVelocityScale: CGFloat
+ let fogScaleMaxDelta: CGFloat
+
+ static let officialInspired = CursorVisualDynamicsConfiguration(
+ tipSpring: CursorVisualSpringConfiguration(response: 0.18, dampingFraction: 0.76),
+ angleSpring: CursorVisualSpringConfiguration(response: 0.24, dampingFraction: 0.82),
+ headingVelocityFloor: 14,
+ animatedAngleOffsetMax: 0.26,
+ bodyOffsetScale: 0.0012,
+ bodyOffsetMax: 2.4,
+ bodyLateralScale: 0.06,
+ bodyLateralMax: 1.4,
+ fogOffsetScale: 0.0045,
+ fogOffsetMax: 9,
+ fogOpacityBase: 0.12,
+ fogOpacityVelocityScale: 0.00006,
+ fogScaleVelocityScale: 0.00012,
+ fogScaleMaxDelta: 0.22
+ )
+}
+
+struct CursorVisualDynamicsState: Equatable {
+ var time: CGFloat
+ var tipPosition: CGPoint
+ var tipVelocity: CGVector
+ var tipForce: CGVector
+ var angle: CGFloat
+ var angleVelocity: CGFloat
+ var angleForce: CGFloat
+
+ init(
+ time: CGFloat = 0,
+ tipPosition: CGPoint,
+ tipVelocity: CGVector = CGVector(dx: 0, dy: 0),
+ tipForce: CGVector = CGVector(dx: 0, dy: 0),
+ angle: CGFloat = 0,
+ angleVelocity: CGFloat = 0,
+ angleForce: CGFloat = 0
+ ) {
+ self.time = time
+ self.tipPosition = tipPosition
+ self.tipVelocity = tipVelocity
+ self.tipForce = tipForce
+ self.angle = angle
+ self.angleVelocity = angleVelocity
+ self.angleForce = angleForce
+ }
+}
+
+struct CursorVisualRenderState: Equatable {
+ let tipPosition: CGPoint
+ let rotation: CGFloat
+ let cursorBodyOffset: CGVector
+ let fogOffset: CGVector
+ let fogOpacity: CGFloat
+ let fogScale: CGFloat
+}
+
+enum CursorVisualDynamicsAnimator {
+ static func state(at tipPosition: CGPoint, time: CGFloat = 0) -> CursorVisualDynamicsState {
+ CursorVisualDynamicsState(time: time, tipPosition: tipPosition)
+ }
+
+ static func advance(
+ state: CursorVisualDynamicsState,
+ targetTipPosition: CGPoint,
+ targetTime: CGFloat,
+ idleAngleOffset: CGFloat = 0,
+ baseHeading: CGFloat,
+ configuration: CursorVisualDynamicsConfiguration = .officialInspired
+ ) -> (state: CursorVisualDynamicsState, renderState: CursorVisualRenderState) {
+ var adjustedState = state
+
+ if (targetTime - adjustedState.time) > 1 {
+ adjustedState.time = targetTime - (1.0 / 60.0)
+ }
+
+ while adjustedState.time < targetTime {
+ adjustedState = advanceStep(
+ state: adjustedState,
+ targetTipPosition: targetTipPosition,
+ idleAngleOffset: idleAngleOffset,
+ baseHeading: baseHeading,
+ configuration: configuration
+ )
+ }
+
+ return (
+ adjustedState,
+ renderState(
+ state: adjustedState,
+ idleAngleOffset: idleAngleOffset,
+ baseHeading: baseHeading,
+ configuration: configuration
+ )
+ )
+ }
+
+ private static func advanceStep(
+ state: CursorVisualDynamicsState,
+ targetTipPosition: CGPoint,
+ idleAngleOffset: CGFloat,
+ baseHeading: CGFloat,
+ configuration: CursorVisualDynamicsConfiguration
+ ) -> CursorVisualDynamicsState {
+ let dt = configuration.tipSpring.dt
+ let halfDT = dt * 0.5
+
+ let tipVelocityHalf = state.tipVelocity + state.tipForce.scaled(by: halfDT)
+ let nextTipPosition = state.tipPosition + tipVelocityHalf.scaled(by: dt)
+ let tipDisplacement = targetTipPosition - nextTipPosition
+ let tipForce = tipDisplacement.scaled(by: configuration.tipSpring.stiffness)
+ + tipVelocityHalf.scaled(by: -configuration.tipSpring.drag)
+ let tipVelocity = tipVelocityHalf + tipForce.scaled(by: halfDT)
+
+ let targetAngle = resolvedTargetAngle(
+ velocity: tipVelocity,
+ idleAngleOffset: idleAngleOffset,
+ baseHeading: baseHeading,
+ configuration: configuration
+ )
+ let angleVelocityHalf = state.angleVelocity + (state.angleForce * halfDT)
+ let nextAngle = normalizeAngle(state.angle + (angleVelocityHalf * dt))
+ let angleError = normalizeAngle(targetAngle - nextAngle)
+ let angleForce = (angleError * configuration.angleSpring.stiffness)
+ + ((-configuration.angleSpring.drag) * angleVelocityHalf)
+ let angleVelocity = angleVelocityHalf + (angleForce * halfDT)
+
+ return CursorVisualDynamicsState(
+ time: state.time + dt,
+ tipPosition: nextTipPosition,
+ tipVelocity: tipVelocity,
+ tipForce: tipForce,
+ angle: normalizeAngle(nextAngle),
+ angleVelocity: angleVelocity,
+ angleForce: angleForce
+ )
+ }
+
+ private static func renderState(
+ state: CursorVisualDynamicsState,
+ idleAngleOffset: CGFloat,
+ baseHeading: CGFloat,
+ configuration: CursorVisualDynamicsConfiguration
+ ) -> CursorVisualRenderState {
+ let speed = state.tipVelocity.length
+ let direction = speed > 0.001
+ ? state.tipVelocity.normalized
+ : CGVector(dx: cos(baseHeading + idleAngleOffset), dy: sin(baseHeading + idleAngleOffset))
+ let bodyBackward = direction.scaled(
+ by: -min(speed * configuration.bodyOffsetScale, configuration.bodyOffsetMax)
+ )
+ let lateralAmount = CGFloat.clamped(
+ state.angleVelocity * configuration.bodyLateralScale,
+ lower: -configuration.bodyLateralMax,
+ upper: configuration.bodyLateralMax
+ )
+ let bodyLateral = direction.perpendicular.scaled(by: lateralAmount)
+ let cursorBodyOffset = bodyBackward + bodyLateral
+ let fogOffset = direction.scaled(
+ by: -min(speed * configuration.fogOffsetScale, configuration.fogOffsetMax)
+ ) + bodyLateral.scaled(by: 0.6)
+ let fogOpacity = min(
+ configuration.fogOpacityBase + (speed * configuration.fogOpacityVelocityScale),
+ 0.34
+ )
+ let fogScale = 1 + min(
+ speed * configuration.fogScaleVelocityScale,
+ configuration.fogScaleMaxDelta
+ )
+
+ return CursorVisualRenderState(
+ tipPosition: state.tipPosition,
+ rotation: normalizeAngle(
+ state.angle + idleAngleOffset.clamped(
+ to: -configuration.animatedAngleOffsetMax...configuration.animatedAngleOffsetMax
+ )
+ ),
+ cursorBodyOffset: cursorBodyOffset,
+ fogOffset: fogOffset,
+ fogOpacity: fogOpacity,
+ fogScale: fogScale
+ )
+ }
+
+ private static func resolvedTargetAngle(
+ velocity: CGVector,
+ idleAngleOffset: CGFloat,
+ baseHeading: CGFloat,
+ configuration: CursorVisualDynamicsConfiguration
+ ) -> CGFloat {
+ let speed = velocity.length
+ guard speed > configuration.headingVelocityFloor else {
+ return 0
+ }
+
+ let heading = atan2(velocity.dy, velocity.dx)
+ return normalizeAngle(heading - baseHeading)
+ }
+
+ private static func normalizeAngle(_ angle: CGFloat) -> CGFloat {
+ var value = angle
+ while value > .pi {
+ value -= 2 * .pi
+ }
+ while value < -.pi {
+ value += 2 * .pi
+ }
+ return value
+ }
+}
+
+private func sampleCubic(start: CGPoint, control1: CGPoint, control2: CGPoint, end: CGPoint, t: CGFloat) -> CGPoint {
+ let omt = 1 - t
+ let omt2 = omt * omt
+ let t2 = t * t
+
+ return CGPoint(
+ x: (omt2 * omt * start.x)
+ + (3 * omt2 * t * control1.x)
+ + (3 * omt * t2 * control2.x)
+ + (t2 * t * end.x),
+ y: (omt2 * omt * start.y)
+ + (3 * omt2 * t * control1.y)
+ + (3 * omt * t2 * control2.y)
+ + (t2 * t * end.y)
+ )
+}
+
+private func sampleCubicTangent(start: CGPoint, control1: CGPoint, control2: CGPoint, end: CGPoint, t: CGFloat) -> CGVector {
+ let omt = 1 - t
+ return CGVector(
+ dx: (3 * omt * omt * (control1.x - start.x))
+ + (6 * omt * t * (control2.x - control1.x))
+ + (3 * t * t * (end.x - control2.x)),
+ dy: (3 * omt * omt * (control1.y - start.y))
+ + (6 * omt * t * (control2.y - control1.y))
+ + (3 * t * t * (end.y - control2.y))
+ )
+}
+
+private extension CGRect {
+ func contains(_ point: CGPoint, padding: CGFloat) -> Bool {
+ insetBy(dx: -padding, dy: -padding).contains(point)
+ }
+}
+
+private extension CGPoint {
+ static func + (lhs: CGPoint, rhs: CGVector) -> CGPoint {
+ CGPoint(x: lhs.x + rhs.dx, y: lhs.y + rhs.dy)
+ }
+
+ static func - (lhs: CGPoint, rhs: CGVector) -> CGPoint {
+ CGPoint(x: lhs.x - rhs.dx, y: lhs.y - rhs.dy)
+ }
+
+ static func - (lhs: CGPoint, rhs: CGPoint) -> CGVector {
+ CGVector(dx: lhs.x - rhs.x, dy: lhs.y - rhs.y)
+ }
+}
+
+private extension CGVector {
+ static func + (lhs: CGVector, rhs: CGVector) -> CGVector {
+ CGVector(dx: lhs.dx + rhs.dx, dy: lhs.dy + rhs.dy)
+ }
+
+ static func - (lhs: CGVector, rhs: CGVector) -> CGVector {
+ CGVector(dx: lhs.dx - rhs.dx, dy: lhs.dy - rhs.dy)
+ }
+
+ var length: CGFloat {
+ hypot(dx, dy)
+ }
+
+ var normalized: CGVector {
+ let resolvedLength = max(length, 0.001)
+ return CGVector(dx: dx / resolvedLength, dy: dy / resolvedLength)
+ }
+
+ var perpendicular: CGVector {
+ CGVector(dx: -dy, dy: dx)
+ }
+
+ func scaled(by factor: CGFloat) -> CGVector {
+ CGVector(dx: dx * factor, dy: dy * factor)
+ }
+
+ func limited(maxLength: CGFloat) -> CGVector {
+ let resolvedLength = length
+ guard resolvedLength > maxLength, resolvedLength > 0.001 else {
+ return self
+ }
+
+ return scaled(by: maxLength / resolvedLength)
+ }
+}
+
+extension CGFloat {
+ static func clamped(_ value: CGFloat, lower: CGFloat, upper: CGFloat) -> CGFloat {
+ Swift.min(Swift.max(value, lower), upper)
+ }
+
+ var cursorIdentifier: String {
+ String(format: "%.2f", Double(self))
+ }
+
+ func clamped(to range: ClosedRange<CGFloat>) -> CGFloat {
+ Swift.min(Swift.max(self, range.lowerBound), range.upperBound)
+ }
+}
diff --git a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/SoftwareCursorOverlay.swift b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/SoftwareCursorOverlay.swift
index 556fdf8..ee896d4 100644
--- a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/SoftwareCursorOverlay.swift
+++ b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/SoftwareCursorOverlay.swift
@@ -56,87 +56,6 @@ struct CursorWindowGeometry {
}
}
-struct CursorMotionPath {
- let start: CGPoint
- let control1: CGPoint
- let control2: CGPoint
- let end: CGPoint
- let curveScale: CGFloat
-
- init(start: CGPoint, end: CGPoint, curveDirection: CGFloat? = nil, curveScale: CGFloat = 1) {
- let delta = CGVector(dx: end.x - start.x, dy: end.y - start.y)
- let distance = max(hypot(delta.dx, delta.dy), 1)
- let normal = normalized(CGVector(dx: -delta.dy, dy: delta.dx))
- let resolvedCurveDirection = curveDirection ?? (delta.dx >= 0 ? 1 : -1)
- let resolvedCurveScale = max(curveScale, 0)
- let curveAmount = min(max(distance * 0.22, 28), 110) * resolvedCurveScale
- let controlOffset = CGPoint(
- x: normal.dx * curveAmount * resolvedCurveDirection,
- y: normal.dy * curveAmount * resolvedCurveDirection
- )
- let control1Base = CGPoint(
- x: start.x + (delta.dx * (resolvedCurveScale == 0 ? 1.0 / 3.0 : 0.18)),
- y: start.y + (delta.dy * (resolvedCurveScale == 0 ? 1.0 / 3.0 : 0.10))
- )
- let control2Base = CGPoint(
- x: start.x + (delta.dx * (resolvedCurveScale == 0 ? 2.0 / 3.0 : 0.80)),
- y: start.y + (delta.dy * (resolvedCurveScale == 0 ? 2.0 / 3.0 : 0.96))
- )
-
- self.start = start
- self.end = end
- self.curveScale = resolvedCurveScale
- self.control1 = CGPoint(
- x: control1Base.x + controlOffset.x,
- y: control1Base.y + controlOffset.y
- )
- self.control2 = CGPoint(
- x: control2Base.x + (controlOffset.x * 0.48),
- y: control2Base.y + (controlOffset.y * 0.48)
- )
- }
-
- func point(at t: CGFloat) -> CGPoint {
- let omt = 1 - t
- let omt2 = omt * omt
- let t2 = t * t
-
- return CGPoint(
- x: (omt2 * omt * start.x)
- + (3 * omt2 * t * control1.x)
- + (3 * omt * t2 * control2.x)
- + (t2 * t * end.x),
- y: (omt2 * omt * start.y)
- + (3 * omt2 * t * control1.y)
- + (3 * omt * t2 * control2.y)
- + (t2 * t * end.y)
- )
- }
-
- func tangent(at t: CGFloat) -> CGVector {
- let omt = 1 - t
- return CGVector(
- dx: (3 * omt * omt * (control1.x - start.x))
- + (6 * omt * t * (control2.x - control1.x))
- + (3 * t * t * (end.x - control2.x)),
- dy: (3 * omt * omt * (control1.y - start.y))
- + (6 * omt * t * (control2.y - control1.y))
- + (3 * t * t * (end.y - control2.y))
- )
- }
-
- func sampledConstraintPoints() -> [CGPoint] {
- [
- control1,
- point(at: 0.28),
- point(at: 0.5),
- point(at: 0.72),
- control2,
- end,
- ]
- }
-}
-
private struct ProcessedCursorImage {
let image: NSImage
let tipAnchor: CGPoint
@@ -351,6 +270,7 @@ enum SoftwareCursorOverlay {
private static var restingTipPosition: CGPoint?
private static var displayedTipPosition: CGPoint?
private static var activeTargetWindow: CursorTargetWindow?
+ private static var visualDynamicsState: CursorVisualDynamicsState?
private static var idleTimer: Timer?
private static var hideTimer: Timer?
private static var idlePhase: CGFloat = 0
@@ -367,9 +287,17 @@ enum SoftwareCursorOverlay {
let constrainedTarget = clampTipPosition(targetPoint)
let startPoint = displayedTipPosition ?? defaultAppearancePoint(for: constrainedTarget)
+ let now = CACurrentMediaTime()
panel?.alphaValue = 1
- placeCursor(at: startPoint, rotation: 0, clickProgress: 0)
+ seedVisualDynamicsIfNeeded(at: startPoint, time: now)
+ placeCursor(
+ using: advanceVisualDynamics(
+ toward: startPoint,
+ at: now
+ ),
+ clickProgress: 0
+ )
if distanceBetween(startPoint, constrainedTarget) > 2 {
animateMove(from: startPoint, to: constrainedTarget, relativeTo: targetWindow)
@@ -383,9 +311,10 @@ enum SoftwareCursorOverlay {
configureOrdering(relativeTo: targetWindow)
let constrainedTarget = clampTipPosition(targetPoint)
- animateClickPulse(at: constrainedTarget, clickCount: max(clickCount, 1), mouseButton: mouseButton)
+ let now = CACurrentMediaTime()
+ seedVisualDynamicsIfNeeded(at: constrainedTarget, time: now)
restingTipPosition = constrainedTarget
- displayedTipPosition = constrainedTarget
+ animateClickPulse(at: constrainedTarget, clickCount: max(clickCount, 1), mouseButton: mouseButton)
startIdleAnimation()
scheduleHide(after: 0.55)
}
@@ -398,8 +327,13 @@ enum SoftwareCursorOverlay {
configureOrdering(relativeTo: targetWindow)
let constrainedTarget = clampTipPosition(targetPoint)
restingTipPosition = constrainedTarget
- displayedTipPosition = constrainedTarget
- placeCursor(at: constrainedTarget, rotation: 0, clickProgress: 0)
+ placeCursor(
+ using: advanceVisualDynamics(
+ toward: constrainedTarget,
+ at: CACurrentMediaTime()
+ ),
+ clickProgress: 0
+ )
startIdleAnimation()
scheduleHide(after: 0.45)
}
@@ -410,6 +344,7 @@ enum SoftwareCursorOverlay {
displayedTipPosition = nil
restingTipPosition = nil
activeTargetWindow = nil
+ visualDynamicsState = nil
panel?.orderOut(nil)
}
@@ -468,76 +403,128 @@ enum SoftwareCursorOverlay {
}
private static func animateMove(from start: CGPoint, to end: CGPoint, relativeTo targetWindow: CursorTargetWindow?) {
- let path = bestMotionPath(from: start, to: end, relativeTo: targetWindow)
- let duration = min(max(TimeInterval(distanceBetween(start, end) / 1050), 0.24), 0.56)
+ let candidate = bestMotionCandidate(from: start, to: end, relativeTo: targetWindow)
+ let path = candidate.path
+ // Binary-backed geometry and spring shape are used directly, but the final
+ // wall-clock duration is still calibrated locally because the official
+ // transaction-level duration mapping has not been fully recovered yet.
+ let duration = OfficialCursorMotionModel.calibratedTravelDuration(
+ distance: distanceBetween(start, end),
+ measurement: candidate.measurement
+ )
+ let springTargetDuration = OfficialCursorMotionModel.closeEnoughTime
let startTime = CACurrentMediaTime()
+ var progress: CGFloat = 0
+ var springState = CursorMotionSpringState()
while true {
refreshActiveOrderingIfNeeded()
- let elapsed = CACurrentMediaTime() - startTime
- let rawProgress = min(max(elapsed / duration, 0), 1)
- let eased = easeInOut(rawProgress)
- let point = path.point(at: eased)
- let tangent = path.tangent(at: max(min(eased, 0.999), 0.001))
- let rotation = rotationOffset(for: tangent)
+ let elapsed = CGFloat(CACurrentMediaTime() - startTime)
+ let normalizedElapsed = (elapsed / max(duration, 0.001)).clamped(to: 0...1)
+ let springTime = normalizedElapsed * springTargetDuration
+ (progress, springState) = CursorMotionProgressAnimator.advance(
+ current: progress,
+ state: springState,
+ to: springTime
+ )
- placeCursor(at: point, rotation: rotation, clickProgress: 0)
+ let sample = path.sample(at: progress)
+ placeCursor(
+ using: advanceVisualDynamics(
+ toward: sample.point,
+ at: CACurrentMediaTime()
+ ),
+ clickProgress: 0
+ )
- if rawProgress >= 1 {
+ if normalizedElapsed >= 1 || CursorMotionProgressAnimator.isCloseEnough(progress: progress) {
break
}
pumpFrame()
}
+
+ placeCursor(
+ using: advanceVisualDynamics(
+ toward: end,
+ at: CACurrentMediaTime()
+ ),
+ clickProgress: 0
+ )
}
- private static func bestMotionPath(from start: CGPoint, to end: CGPoint, relativeTo targetWindow: CursorTargetWindow?) -> CursorMotionPath {
- let preferredCurveDirection: CGFloat = end.x >= start.x ? 1 : -1
- let candidates = [
- CursorMotionPath(start: start, end: end, curveDirection: preferredCurveDirection, curveScale: 1),
- CursorMotionPath(start: start, end: end, curveDirection: -preferredCurveDirection, curveScale: 1),
- CursorMotionPath(start: start, end: end, curveDirection: preferredCurveDirection, curveScale: 0.72),
- CursorMotionPath(start: start, end: end, curveDirection: -preferredCurveDirection, curveScale: 0.72),
- CursorMotionPath(start: start, end: end, curveDirection: preferredCurveDirection, curveScale: 0.38),
- CursorMotionPath(start: start, end: end, curveDirection: -preferredCurveDirection, curveScale: 0.38),
- CursorMotionPath(start: start, end: end, curveDirection: 0, curveScale: 0),
- ]
+ private static func bestMotionCandidate(from start: CGPoint, to end: CGPoint, relativeTo targetWindow: CursorTargetWindow?) -> CursorMotionCandidate {
+ let bounds = motionBounds(from: start, to: end)
+ let candidates = HeadingDrivenCursorMotionModel.makeCandidates(
+ start: start,
+ end: end,
+ bounds: bounds,
+ startForward: currentForwardVector(),
+ endForward: restingForwardVector()
+ )
+ let defaultCandidate = HeadingDrivenCursorMotionModel.chooseBestCandidate(from: candidates)
+ ?? CursorMotionCandidate(
+ identifier: "legacy-fallback",
+ kind: .base,
+ side: 0,
+ tableAScale: nil,
+ tableBScale: nil,
+ path: CursorMotionPath(start: start, end: end),
+ measurement: CursorMotionPath(start: start, end: end).measure(bounds: bounds),
+ score: 0
+ )
guard let targetWindow else {
- return candidates[0]
+ return defaultCandidate
}
let excludingWindowNumber = max(panel?.windowNumber ?? 0, 0)
let evaluations = candidates.map { candidate in
(
- path: candidate,
+ candidate: candidate,
hitCount: windowConstraintHitCount(
- for: candidate,
+ for: candidate.path,
relativeTo: targetWindow,
excludingWindowNumber: excludingWindowNumber
)
)
}
- let totalSampleCount = candidates[0].sampledConstraintPoints().count
+ let totalSampleCount = candidates.first?.path.sampledConstraintPoints().count ?? 0
let bestHitCount = evaluations.map(\.hitCount).max() ?? 0
- if bestHitCount == totalSampleCount {
+ if bestHitCount == totalSampleCount, bestHitCount > 0 {
return evaluations
.filter { $0.hitCount == bestHitCount }
- .max { $0.path.curveScale < $1.path.curveScale }?
- .path ?? candidates[0]
+ .map(\.candidate)
+ .sorted(by: candidatePreference)
+ .first ?? defaultCandidate
}
if bestHitCount > 0 {
return evaluations
.filter { $0.hitCount == bestHitCount }
- .min { $0.path.curveScale < $1.path.curveScale }?
- .path ?? candidates.last ?? candidates[0]
+ .map(\.candidate)
+ .sorted(by: candidatePreference)
+ .first ?? defaultCandidate
}
- return candidates.last ?? candidates[0]
+ return defaultCandidate
+ }
+
+ private static func currentForwardVector() -> CGVector {
+ let renderRotation = cursorView?.rotation ?? 0
+ return forwardVector(renderRotation: renderRotation)
+ }
+
+ private static func restingForwardVector() -> CGVector {
+ forwardVector(renderRotation: 0)
+ }
+
+ private static func forwardVector(renderRotation: CGFloat) -> CGVector {
+ let angle = baseHeading + renderRotation
+ return CGVector(dx: cos(angle), dy: sin(angle))
}
private static func windowConstraintHitCount(
@@ -552,6 +539,32 @@ enum SoftwareCursorOverlay {
}
}
+ private static func motionBounds(from start: CGPoint, to end: CGPoint) -> CGRect? {
+ let startScreen = screen(containing: start) ?? NSScreen.main ?? NSScreen.screens.first
+ let endScreen = screen(containing: end) ?? startScreen
+
+ switch (startScreen, endScreen) {
+ case let (startScreen?, endScreen?) where startScreen === endScreen:
+ return startScreen.visibleFrame
+ case let (startScreen?, endScreen?):
+ return startScreen.visibleFrame.union(endScreen.visibleFrame)
+ case let (screen?, nil), let (nil, screen?):
+ return screen.visibleFrame
+ default:
+ return nil
+ }
+ }
+
+ private static func candidatePreference(_ lhs: CursorMotionCandidate, _ rhs: CursorMotionCandidate) -> Bool {
+ if lhs.measurement.staysInBounds != rhs.measurement.staysInBounds {
+ return lhs.measurement.staysInBounds && !rhs.measurement.staysInBounds
+ }
+ if lhs.score != rhs.score {
+ return lhs.score < rhs.score
+ }
+ return lhs.identifier < rhs.identifier
+ }
+
private static func windowID(at point: CGPoint, excludingWindowNumber: Int) -> CGWindowID? {
let windowNumber = NSWindow.windowNumber(
at: NSPoint(x: point.x, y: point.y),
@@ -595,7 +608,13 @@ enum SoftwareCursorOverlay {
let rawProgress = min(max(elapsed / duration, 0), 1)
let clickProgress = sin(rawProgress * .pi) * pulseBias
- placeCursor(at: point, rotation: 0, clickProgress: clickProgress)
+ placeCursor(
+ using: advanceVisualDynamics(
+ toward: point,
+ at: CACurrentMediaTime()
+ ),
+ clickProgress: clickProgress
+ )
if rawProgress >= 1 {
break
@@ -609,7 +628,13 @@ enum SoftwareCursorOverlay {
}
}
- placeCursor(at: point, rotation: 0, clickProgress: 0)
+ placeCursor(
+ using: advanceVisualDynamics(
+ toward: point,
+ at: CACurrentMediaTime()
+ ),
+ clickProgress: 0
+ )
}
private static func startIdleAnimation() {
@@ -620,35 +645,40 @@ enum SoftwareCursorOverlay {
idlePhase = 0
let timer = Timer(timeInterval: 1 / 60, repeats: true) { _ in
MainActor.assumeIsolated {
- guard let cursorView, let panel else {
+ guard panel != nil, cursorView != nil else {
return
}
refreshActiveOrderingIfNeeded()
idlePhase += 0.05
- let offset = CGPoint(
- x: sin(idlePhase) * 1.6,
- y: cos(idlePhase * 0.47) * 0.7
- )
- let tipPosition = CGPoint(
- x: restingTipPosition.x + offset.x,
- y: restingTipPosition.y + offset.y
+ let targetTipPosition = CGPoint(
+ x: restingTipPosition.x + (sin(idlePhase) * 1.6),
+ y: restingTipPosition.y + (cos(idlePhase * 0.47) * 0.7)
)
+ let idleAngleOffset = sin(idlePhase * 0.8) * 0.03
- cursorView.rotation = sin(idlePhase * 0.8) * 0.02
- cursorView.clickProgress = 0
- cursorView.needsDisplay = true
-
- panel.setFrameOrigin(artwork.geometry.origin(forTipPosition: tipPosition))
- displayedTipPosition = tipPosition
+ placeCursor(
+ using: advanceVisualDynamics(
+ toward: targetTipPosition,
+ idleAngleOffset: idleAngleOffset,
+ at: CACurrentMediaTime()
+ ),
+ clickProgress: 0
+ )
}
}
RunLoop.main.add(timer, forMode: .common)
idleTimer = timer
- placeCursor(at: restingTipPosition, rotation: 0, clickProgress: 0)
+ placeCursor(
+ using: advanceVisualDynamics(
+ toward: restingTipPosition,
+ at: CACurrentMediaTime()
+ ),
+ clickProgress: 0
+ )
}
private static func stopIdleAnimation() {
@@ -691,6 +721,7 @@ enum SoftwareCursorOverlay {
displayedTipPosition = nil
restingTipPosition = nil
activeTargetWindow = nil
+ visualDynamicsState = nil
}
}
}
@@ -704,16 +735,50 @@ enum SoftwareCursorOverlay {
)
}
- private static func placeCursor(at tipPosition: CGPoint, rotation: CGFloat, clickProgress: CGFloat) {
+ private static func seedVisualDynamicsIfNeeded(at tipPosition: CGPoint, time: CFTimeInterval) {
+ guard visualDynamicsState == nil else {
+ return
+ }
+
+ visualDynamicsState = CursorVisualDynamicsAnimator.state(
+ at: tipPosition,
+ time: CGFloat(time)
+ )
+ }
+
+ private static func advanceVisualDynamics(
+ toward targetTipPosition: CGPoint,
+ idleAngleOffset: CGFloat = 0,
+ at time: CFTimeInterval
+ ) -> CursorVisualRenderState {
+ let clampedTarget = clampTipPosition(targetTipPosition)
+ seedVisualDynamicsIfNeeded(at: clampedTarget, time: time)
+
+ let result = CursorVisualDynamicsAnimator.advance(
+ state: visualDynamicsState ?? CursorVisualDynamicsAnimator.state(at: clampedTarget, time: CGFloat(time)),
+ targetTipPosition: clampedTarget,
+ targetTime: CGFloat(time),
+ idleAngleOffset: idleAngleOffset,
+ baseHeading: baseHeading
+ )
+ visualDynamicsState = result.state
+ return result.renderState
+ }
+
+ private static func placeCursor(using renderState: CursorVisualRenderState, clickProgress: CGFloat) {
guard let panel, let cursorView else {
return
}
- panel.setFrameOrigin(artwork.geometry.origin(forTipPosition: tipPosition))
- cursorView.rotation = rotation
+ panel.setFrameOrigin(artwork.geometry.origin(forTipPosition: renderState.tipPosition))
+ cursorView.rotation = renderState.rotation
+ cursorView.cursorBodyOffset = renderState.cursorBodyOffset
+ cursorView.fogOffset = renderState.fogOffset
+ cursorView.fogOpacity = renderState.fogOpacity
+ cursorView.fogScale = renderState.fogScale
cursorView.clickProgress = clickProgress
cursorView.needsDisplay = true
- displayedTipPosition = tipPosition
+ displayedTipPosition = renderState.tipPosition
}
private static func clampTipPosition(_ tipPosition: CGPoint) -> CGPoint {
@@ -737,33 +802,6 @@ enum SoftwareCursorOverlay {
NSScreen.screens.first { $0.frame.contains(point) }
}
- private static func rotationOffset(for tangent: CGVector) -> CGFloat {
- guard tangent.dx != 0 || tangent.dy != 0 else {
- return 0
- }
-
- let heading = atan2(tangent.dy, tangent.dx)
- let delta = normalize(angle: heading - baseHeading)
- return delta.clamped(to: -0.22...0.22)
- }
-
- private static func normalize(angle: CGFloat) -> CGFloat {
- var value = angle
- while value > .pi {
- value -= 2 * .pi
- }
- while value < -.pi {
- value += 2 * .pi
- }
- return value
- }
-
- private static func easeInOut(_ value: CGFloat) -> CGFloat {
- value < 0.5
- ? 4 * value * value * value
- : 1 - pow(-2 * value + 2, 3) / 2
- }
-
private static func pumpFrame() {
RunLoop.current.run(mode: .default, before: Date().addingTimeInterval(1 / 120))
}
@@ -789,6 +827,10 @@ private final class SoftwareCursorView: NSView {
private let artwork: CursorArtwork
var rotation: CGFloat = 0
+ var cursorBodyOffset: CGVector = CGVector(dx: 0, dy: 0)
+ var fogOffset: CGVector = CGVector(dx: 0, dy: 0)
+ var fogOpacity: CGFloat = 0.12
+ var fogScale: CGFloat = 1
var clickProgress: CGFloat = 0
init(frame frameRect: NSRect, artwork: CursorArtwork) {
@@ -812,29 +854,37 @@ private final class SoftwareCursorView: NSView {
NSColor.clear.setFill()
dirtyRect.fill()
- let compression = clickProgress * 0.05
+ let motionCompression = min(hypot(cursorBodyOffset.dx, cursorBodyOffset.dy) * 0.01, 0.02)
+ let compression = (clickProgress * 0.05) + motionCompression
let scaleX = 1 - compression
let scaleY = 1 + (compression * 0.24)
let anchor = artwork.geometry.tipAnchor
let context = NSGraphicsContext.current?.cgContext
- context?.saveGState()
- context?.translateBy(x: anchor.x, y: anchor.y)
- context?.rotate(by: rotation)
- context?.scaleBy(x: scaleX, y: scaleY)
- context?.translateBy(x: -anchor.x, y: -anchor.y)
-
- let shadowOval = NSBezierPath(ovalIn: CGRect(x: anchor.x - 7, y: anchor.y - 49, width: 22, height: 7))
+ let fogRect = CGRect(
+ x: anchor.x - (12 * fogScale) + fogOffset.dx,
+ y: anchor.y - (51 * fogScale) + fogOffset.dy,
+ width: 24 * fogScale,
+ height: 8 * fogScale
+ )
+ let fogOval = NSBezierPath(ovalIn: fogRect)
NSGraphicsContext.saveGraphicsState()
let ovalShadow = NSShadow()
- ovalShadow.shadowBlurRadius = 10 + (clickProgress * 2)
+ ovalShadow.shadowBlurRadius = (10 * fogScale) + (clickProgress * 2)
ovalShadow.shadowOffset = CGSize(width: 0, height: -1)
- ovalShadow.shadowColor = NSColor.black.withAlphaComponent(0.14)
+ ovalShadow.shadowColor = NSColor.white.withAlphaComponent(fogOpacity * 0.55)
ovalShadow.set()
- NSColor.black.withAlphaComponent(0.09).setFill()
- shadowOval.fill()
+ NSColor.white.withAlphaComponent(fogOpacity).setFill()
+ fogOval.fill()
NSGraphicsContext.restoreGraphicsState()
+ context?.saveGState()
+ context?.translateBy(x: cursorBodyOffset.dx, y: cursorBodyOffset.dy)
+ context?.translateBy(x: anchor.x, y: anchor.y)
+ context?.rotate(by: rotation)
+ context?.scaleBy(x: scaleX, y: scaleY)
+ context?.translateBy(x: -anchor.x, y: -anchor.y)
+
if let image = artwork.image {
NSGraphicsContext.saveGraphicsState()
let shadow = NSShadow()
@@ -870,6 +920,8 @@ private final class SoftwareCursorView: NSView {
path.stroke()
}
+ context?.restoreGState()
+
if clickProgress > 0.01 {
let ringRadius = 4 + (clickProgress * 7)
let ringRect = CGRect(
@@ -883,8 +935,6 @@ private final class SoftwareCursorView: NSView {
ring.lineWidth = 1.0
ring.stroke()
}
-
- context?.restoreGState()
}
private func cursorPath(anchor: CGPoint, scale: CGFloat, xOffset: CGFloat, yOffset: CGFloat) -> NSBezierPath {
@@ -914,18 +964,3 @@ private final class SoftwareCursorView: NSView {
return path
}
}
-
-private func normalized(_ vector: CGVector) -> CGVector {
- let length = max(hypot(vector.dx, vector.dy), 0.001)
- return CGVector(dx: vector.dx / length, dy: vector.dy / length)
-}
-
-private extension CGFloat {
- static func clamped(_ value: CGFloat, lower: CGFloat, upper: CGFloat) -> CGFloat {
- Swift.min(Swift.max(value, lower), upper)
- }
-
- func clamped(to range: ClosedRange<CGFloat>) -> CGFloat {
- Swift.min(Swift.max(self, range.lowerBound), range.upperBound)
- }
-}
diff --git a/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/OpenComputerUseKitTests.swift b/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/OpenComputerUseKitTests.swift
index a4654d9..11d0608 100644
--- a/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/OpenComputerUseKitTests.swift
+++ b/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/OpenComputerUseKitTests.swift
@@ -242,14 +242,91 @@ final class OpenComputerUseKitTests: XCTestCase {
let chosen = OfficialCursorMotionModel.chooseBestCandidate(from: candidates)
- XCTAssertEqual(chosen?.identifier, "base-scaled-guide")
- XCTAssertEqual(chosen?.kind, .base)
+ XCTAssertEqual(chosen?.identifier, "a1.05-b1.00-positive")
+ XCTAssertEqual(chosen?.kind, .arched)
+ }
+
+ func testOfficialCursorMotionGuideProjectionFollowsPathBasisInsteadOfFixedScreenBias() throws {
+ let rightUpCandidates = OfficialCursorMotionModel.makeCandidates(
+ start: CGPoint(x: 120, y: 620),
+ end: CGPoint(x: 960, y: 140),
+ bounds: CGRect(x: 0, y: 0, width: 1280, height: 800)
+ )
+ let leftUpCandidates = OfficialCursorMotionModel.makeCandidates(
+ start: CGPoint(x: 960, y: 620),
+ end: CGPoint(x: 120, y: 140),
+ bounds: CGRect(x: 0, y: 0, width: 1280, height: 800)
+ )
+
+ let rightUpStartControl = try XCTUnwrap(
+ rightUpCandidates.first(where: { $0.identifier == "base-full-guide" })?.path.startControl
+ )
+ let leftUpStartControl = try XCTUnwrap(
+ leftUpCandidates.first(where: { $0.identifier == "base-full-guide" })?.path.startControl
+ )
+
+ XCTAssertLessThan(rightUpStartControl.x, 120)
+ XCTAssertGreaterThan(leftUpStartControl.x, 960)
}
func testOfficialCursorMotionSpringCloseEnoughTimeMatchesRecoveredReference() {
XCTAssertEqual(OfficialCursorMotionModel.closeEnoughTime, 1.429166666666663, accuracy: 0.000_001)
}
+ func testHeadingDrivenMotionPrefersNearDirectPathWhenHeadingsAlreadyAlign() throws {
+ let start = CGPoint(x: 120, y: 120)
+ let end = CGPoint(x: 920, y: 320)
+ let direction = normalizedVector(from: start, to: end)
+
+ let candidates = HeadingDrivenCursorMotionModel.makeCandidates(
+ start: start,
+ end: end,
+ bounds: CGRect(x: 0, y: 0, width: 1280, height: 800),
+ startForward: direction,
+ endForward: direction
+ )
+ let chosen = try XCTUnwrap(HeadingDrivenCursorMotionModel.chooseBestCandidate(from: candidates))
+ let directDistance = hypot(end.x - start.x, end.y - start.y)
+
+ XCTAssertEqual(chosen.side, 0)
+ XCTAssertLessThan(chosen.measurement.totalTurn, 0.45)
+ XCTAssertLessThan(chosen.measurement.length, directDistance * 1.03)
+ }
+
+ func testHeadingDrivenMotionPrefersTurnaroundArcWhenStartHeadingOpposesTravel() throws {
+ let start = CGPoint(x: 220, y: 520)
+ let end = CGPoint(x: 900, y: 280)
+ let direction = normalizedVector(from: start, to: end)
+ let opposite = CGVector(dx: -direction.dx, dy: -direction.dy)
+
+ let directReference = try XCTUnwrap(
+ HeadingDrivenCursorMotionModel.chooseBestCandidate(
+ from: HeadingDrivenCursorMotionModel.makeCandidates(
+ start: start,
+ end: end,
+ bounds: CGRect(x: 0, y: 0, width: 1280, height: 800),
+ startForward: direction,
+ endForward: direction
+ )
+ )
+ )
+ let turnaround = try XCTUnwrap(
+ HeadingDrivenCursorMotionModel.chooseBestCandidate(
+ from: HeadingDrivenCursorMotionModel.makeCandidates(
+ start: start,
+ end: end,
+ bounds: CGRect(x: 0, y: 0, width: 1280, height: 800),
+ startForward: opposite,
+ endForward: direction
+ )
+ )
+ )
+
+ XCTAssertNotEqual(turnaround.side, 0)
+ XCTAssertGreaterThan(turnaround.measurement.totalTurn, directReference.measurement.totalTurn + 0.8)
+ XCTAssertGreaterThan(turnaround.measurement.length, directReference.measurement.length * 1.04)
+ }
+
func testCursorVisualDynamicsOvershootsAfterTargetStops() {
let samples = simulateCursorVisualDynamics(
stopTime: 0.18,
@@ -339,4 +416,11 @@ final class OpenComputerUseKitTests: XCTestCase {
return samples
}
+
+ private func normalizedVector(from start: CGPoint, to end: CGPoint) -> CGVector {
+ let dx = end.x - start.x
+ let dy = end.y - start.y
+ let length = max(hypot(dx, dy), 0.001)
+ return CGVector(dx: dx / length, dy: dy / length)
+ }
}