MotionLab 的物理层是一个与项目无关的通用核心 PhysicsEngine:只吃纯数据描述符,不依赖 DOM、渲染或任何文件格式。你可以把它单独下载到自己的项目里,用同一套 API 搭建物理模拟。核心文件:physics-engine.js(引擎本体与后端注册表,ES 模块)、native-engine.js(1.12.0 起的自研 Native 后端,physics-engine.js 会引用它)和 matter.min.js(Matter.js 0.20 本体,默认后端用)。
当前版本:MotionLab — · PhysicsEngine — · Matter.js —。引擎版本在代码里可读 PhysicsEngine.VERSION(模块同时导出 VERSION 常量);设置面板的「关于」一栏显示的也是同一组版本号。
一、如何下载
二、如何调用(最小示例)
Matter 必须先以普通 script 加载为全局变量;引擎是 ES 模块,用 type="module" 引入。也可以不挂全局,改用 PhysicsEngine.setMatter(Matter) 或构造参数 { matter } 注入。
<script src="matter.min.js"></script>
<script type="module">
import { PhysicsEngine } from './physics-engine.js';
const pe = new PhysicsEngine({ enableSleeping: true, substeps: 2 });
// 静态地面
pe.addBody({ kind: 'rect', x: 400, y: 560, width: 800, height: 40, isStatic: true });
// 一个会弹跳的球
pe.addBody({ kind: 'circle', x: 400, y: 120, radius: 18, restitution: 0.6 });
let last = performance.now();
function frame(now) {
pe.advance(now - last); // 固定时间步推进
last = now;
// 在这里读取 pe.allBodies() 里每个 body 的 position / angle 自行绘制
requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
</script>
三、常用 API 速览
- 构造:
new PhysicsEngine({ gravity: { x: 0, y: 1 }, enableSleeping, fixedDt, maxSteps, substeps, seed, maxSpeed, gravitation }),setGravity(x, y, enabled) 改重力
- 物体:
addBody(desc) / removeBody(id) / clear() / allBodies() / count。desc 字段:kind('circle' | 'rect' | 'polygon')、x, y、radius(圆与多边形)、width, height(矩形)、sides(多边形边数)、density, friction, frictionAir, restitution, isStatic, lockRotation, vx, vy, angle(弧度)、magnet(磁极强度)、userData(宿主自定义数据,原样透传)
- 约束(弹簧 / 连杆):
addConstraint({ bodyA, bodyB, pointA, pointB, stiffness, damping, length })。bodyA 传 null 表示固定在世界坐标 pointA;stiffness 接近 1 即为硬连杆;removeConstraint(id) 删除,删物体会自动清理它的约束
- 推进:
advance(elapsedMs, speed) 固定步长累加器(任意刷新率都稳定);stepOnce() 单步;setSubsteps(1–8) 子步防穿模(拖拽除外)
- 存取:
snapshot() 导出纯 JSON { bodies, constraints, hinges, fluids, winds, rng };load(data) 还原(含随机流位置)
- 后端注册表(1.11.0,Native 于 1.12.0 落地):
PhysicsEngine.BACKENDS 列出 API 背后的求解器后端(matter 使用中 / native 自研·实验性),PhysicsEngine.create({ backend }) 按注册表构造、实例带 backendId;宿主只对 API 编程,未就绪的后端会明确报错、不静默回退;设置里的「物理引擎后端」可直接切换(切换即重演当前场景)
- 查询与冲量(1.2.0):
queryRegion(x, y, w, h) 区域内物体;raycast(x1, y1, x2, y2) 射线命中(由近到远,含命中点);addVelocity(body, dvx, dvy) 叠加速度;applyRadialImpulse(cx, cy, { radius, base, power, filter }) 径向冲击波(大小 = base + power×(1 − 距离/半径),返回推开数量)
- 随机种子(1.3.0):构造传
{ seed } 后,random() / randomRange(min, max) / randomInt(min, max) / choice(arr) / shuffle(arr) 走引擎自己的可复现随机流:同 seed 同序列,适合程序化场景与出生抖动;不传 seed 时随机选一个,可从 pe.seed 读回以便复现;setSeed(n) 随时重置,并同步 Matter 的内部种子
- 命名物体(1.4.0):描述符可带
name(可重名),用 getBodyByName(name) / getBodiesByName(name) 按名查找、renameBody(bodyOrId, name) 改名、nameOf(body) 读名;名字随快照保存。MotionLab 里物体的标签(label)即其引擎名
- 万有引力(1.4.0):
setGravitation(G, { softening }) 打开全体两两引力(牛顿公式 + 软化防奇点,静态体以 面积×密度 计质量),适合行星/轨道模拟;setGravitation(0) 关闭
- 流体浮力(1.4.0):
addFluid({ x, y, width, height, density, drag }) 定义流体区域(中心坐标,上沿为液面),物体按 密度比×浸没比例 受到浮力与水中阻尼——轻者浮、重者沉;removeFluid(id) 移除,快照携带流体
- 磁力(1.5.0):描述符字段
magnet(−100..100,正为 N 极、负为 S 极)——同极相斥、异极相吸,磁铁还会吸引无磁性的铁质物体;作用范围 320,动量守恒。setMagnetism(K, { range, softening }) 全局调参/关闭,setMagnet(body, v) 改单个物体,公式版为 Formulas.magneticForce
- 风场(1.5.0):
addWind({ x, y, width, height, vx, vy, power }) 定义风场区域(中心坐标),区域内物体被吹向风速方向,越轻吹得越快、铁块几乎不动;removeWind(id) 移除,快照携带风场。1.5.0 同时优化了两两力通道(引力+磁力统一遍历,隔离基准约快 40%)
- 铰链与马达(1.7.0):
addHinge({ bodyA, bodyB, pointA, pointB, motorSpeed, motorPower }) 把两个物体(或物体与固定铰座,bodyA: null)钉在同一点上,只能绕点转动;motorSpeed 是马达目标相对角速度(弧度/步,±0.3),加速有上限、反作用按转动惯量反比分配给另一端。同一台机器的零件互不碰撞(铰链簇共享负碰撞组),折叠旋转不卡角;被马达驱动的物体不会休眠。setHingeMotor(id, v) 改转速,hingeAnchors() 给渲染/拾取用的铰点坐标,快照携带铰链
- 在实验室里直接用(1.23 起,1.25/1.26 扩充):点画布空白处,右侧「场景属性」面板的「世界效应」一节可调万有引力 G、添加并编辑流体与风场区域;流体/风场区域在画布上可以直接拖动改位置。左侧工具栏的「磁铁」工具(或世界效应一节的按钮)能直接放固定磁铁,点选任意物体后还可改名、在「材质」一节设磁性,或一键套用泡沫/木头/橡胶/冰/铁材质预设;顶部「分享」按钮把整个场景压进一条链接,对方打开即进入该场景;「我的项目」主页工具栏有「导入场景」入口;另有「万有引力轨道」「浮力池」「磁铁阵列」「风洞实验」「材质实验室」「磁铁秋千」「马达风车」「摩天轮」等预设可直接载入体验
- 机械与录制(1.28):左侧工具栏新增「铰链」工具——先在第一个物体上点铰接点,再点第二个物体即可铰接(点空白 = 固定铰座);点选画布上的铰链圆点可设马达转速或删除。顶部「录制」按钮把画布动画录成循环 GIF 导出(最长 20 秒),发帖、做演示素材不用再录屏
- 失去支撑会醒来(1.44):睡着的物体每 15 步自动检查支撑——删掉睡塔的底层、拖走支撑物,上面睡着的物体会被唤醒并掉落,不再悬空(Matter 与 Native 双引擎);被弹簧/铰链挂住、浸在流体里都算有支撑,零重力时不检查
- 挑战与确定性回放(1.50):主界面侧栏新增「挑战模式」——6 个关卡、限定搭建预算、目标区连续停稳判定与三星评级(
js/challenges.js,无 DOM)。原 GIF 录制被确定性回放取代:录制 = 起始引擎快照 + 按模拟步编号的全部操作事件,导出 .replay.json 后可变速/拖动重播,结尾自动校验状态哈希(js/replay.js);同一脚本在 Matter 与 Native 双后端的实况与重演哈希逐位一致,已由 Node 测试证明。注意引擎快照不含重力,回放文件单独携带场景设置
- 性能优化与界面整理(1.51 / 引擎 1.12.5):性能剖析发现每 15 步的孤儿唤醒探测(1.44)在约 800 物体时占 Matter 后端步进总时间约 31%——其候选对查找是 O(睡眠体×全体)。现双后端均改走均匀网格(触碰判定与支撑语义不变):777 物体压测单步平均 4.9→3.5 ms、95 分位尖峰 25→10 ms。Native 另去掉接触排序/热启动键的模板字符串(改数字键)、求解器临时向量复用、支撑标记改步内戳记、解算后形状同步跳过睡眠体。回放检查点经实测仅约 0.4 ms,不是瓶颈,未动。界面:实验室场景属性面板移除挑战入口与实验室内挑战列表,挑战模式只从主界面侧栏进入,挑战卡「全部挑战」直达主界面挑战视图
- 回放拖动修复与视频录制(1.52):回放进度条拖动改为异步追赶——
scrubPlayback 只记目标步,主循环每帧以约 16 ms 预算步进追赶并逐帧渲染(回退时先恢复最近检查点);检查点间隔 300→120 步(3 分钟回放上限下最多 90 个,约 780 物体时实测单个快照约 323 KB JSON 等价)。新增 js/video.js:canvas.captureStream + MediaRecorder 实时录制,MIME 按 mp4 → webm 顺序探测(pickVideoMime 纯函数可测),最长 60 秒;视频为实时录制(帧率随现场),确定性回放仍是无损格式。能力缺失时按钮如实 toast 不支持(冒烟在 jsdom 无 MediaRecorder 环境下覆盖此路径)
- 代码清理(1.53):全仓审计后删除确认无引用的残留——
i18n.js 的 hasStoredLang、icons.js 的 TOOL_LABELS(工具名已由 i18n 提供)、lab3d.js 的 lab3DIsRunning、pf-stage.js 的 WORLD_SIZE(及其连带的 WORLD 导入)、storage.js 的 clearAutosave/clearVisited(职能已被 resetAllData 覆盖);CSS 删除旧场景选择弹窗(.scene-item 等)与 1.51 移除的实验室挑战列表(.chal-row 等)共 11 条失效规则。内部使用但仅误标导出的格式常量(SCENE_FORMAT 等)属模块公共 API,保留。引擎、格式与行为不变
- 回放热录制偏差修复(1.54 / 引擎 1.12.6):线上复验发现——场景已运行一段时间(求解器带热状态)后再录制的回放在双后端均报「有偏差」,Node 复现定责:① 引擎快照此前不保存角速度与睡眠状态,
describeBody/addBody 已补 va 与 sleeping 的往返(双后端同修,金字塔睡眠堆恢复后 300 步逐位一致);② 接触对热启动冲量等状态无法序列化,故 startReplayRecording 在截取起始快照后立即将其重载回实况世界,使录制与回放从同一重建状态出发——热身 300 步的牛顿摆 + 拖拽脚本在双后端均恢复逐位一致。已知边界:回放中途拖动进度条触发的检查点恢复仍会丢失热状态,刚性场景拖动后判定可能报偏差;不中断的完整播放保证精确复现
- 弹簧振子调明显了 + 编辑器摘要实时更新(1.69 / 引擎 1.13.3 不变):1.68 线上核查发现振子振幅小、衰减快,载入几秒后肉眼近静止。探针对比五种(刚度 × 起摆)组合后只动起摆:三球改从自然长度点下 120 px(约平衡点下 94 px)起摆,刚度保持 0.15——无阻尼球首摆 64→175 px、10 秒后仍有 16 px 摆幅,中阻尼 5.2 秒停、重阻尼 2.3 秒停,双后端一致;摆动范围 191–366 px,横梁与地面都碰不到。另修 1.68 另一处小瑕疵:弹簧编辑器底部手感摘要行拖动滑块时不更新,现随滑块实时变(滑块自带数值此前已实时)。引擎零改动,求解数值不变、旧回放不受影响。测试 +2 项(门面预设钉选 + smoke 摘要实时检查)。
- 弹簧是真的弹簧了(1.68 / 引擎 1.13.3):此前软约束进了 30 次迭代求解器,每子步收敛成刚杆——悬吊探针实测 600 步零穿越,刚度 0.05→0.85、阻尼 0→0.5 毫无差别,弹簧名不副实。现 stiffness < 0.99 的约束不再迭代求解,改每子步施一次胡克力 F = −k·C − c·vn,k = 刚度 × 0.22,阻尼按临界阻尼归一(damping = 1 近临界,任何弹簧/质量组合都适用);0.99 以上仍走迭代求解,杆行为零回归。Impulse 在积分前施力(辛欧拉),Matter 侧软约束不再建 M.Constraint、只留描述符。实测:悬吊下垂 31.4 / 7.2 / 3.4 / 1.9 px(刚度 0.05 / 0.22 / 0.5 / 0.85,恰为 g·m/k 平衡),阻尼 0 到 600 步仍在晃、0.5 以上停稳;双后端下垂差 ≤0.5 px。另加弹簧编辑器(点弹簧线打开,刚度/阻尼/自然长度 + 四个手感预设,可跨软硬边界 live 切换)、新预设「弹簧振子」(三种阻尼同场对比)、蹦床预设重调(网簧 0.22→0.85、落体密度降至 0.001——浅 V 链的张力放大使旧参数在任何真实弹簧模型下都塌到底)。求解数值有变,旧回放不再逐比特复现。测试 +23 项(引擎 +6、Native +7、门面 +4、smoke +6)。
- 回放 scrub 不再丢拖拽(1.67 / 引擎 1.13.2):Ryan 报的 bug——中型场景边拖边录,回放时拖了进度条,判定偏离、偏差不大。定责三处,全在快照往返里:(1) 快照根本不带拖拽状态,scrub 恢复后拖拽伺服/约束没了,后续拖拽事件被
world.dragging 门禁丢弃,整段拖拽直接消失——现快照带拖拽状态,Matter 侧连同原始抓取偏移与求解器跟踪的 angleB 一起恢复(angleB 滞后于物体角度,只恢复偏移会把抓取点甩偏数像素,实测次步差 2.5px);Impulse 侧伺服只有目标点,照原样恢复即可。(2) Matter 新建物体的 deltaTime 是 baseDelta、活体是子步 delta,setVelocity 按比值缩放,恢复后 positionPrev 差一倍、次步即偏 0.0018px——现建体时先锁定为子步 delta。(3) 睡眠计数与约束暖启动冲量(postSolveAll 只衰减不归零、次步 preSolveAll 还要应用)此前都丢了,现随快照走。实测:无拖拽 60 步恢复从偏离变精确;中途拖拽 scrub 双后端哈希一致;杆约束/铰链恢复亦精确。已知剩余限制:Matter 接触暖启动冲量在 pairs 表里、未序列化,极混乱场景 scrub 后仍可能因睡眠/唤醒阈值翻转出现小偏差,不 scrub 的播放始终精确。求解数值不变,旧回放不受影响。测试 +14 项(引擎 +6、Native +4、门面 +4)。
- 牛顿摆睡姿 + 发射器工具 + 无损拖拽录制(1.66):三件事,都是 Ryan 点名先做的关键项(控制台命令输入他怕出问题,主动往后托)。A 牛顿摆睡姿:Impulse 里摆排静下来后歪着睡(最大倾角 7.55°)。两个根因:(1) 睡眠规则要求近期接触作支撑,可静下来的摆排有 1px 间隙、零接触,只能在还晃着时睡着——现刚性连杆/铰链连到固定锚点也算支撑;(2) 吊着的物体在偏离重力轴 2° 以上时禁止入睡,须等摆动死透(双锚点物体除外,双绳招牌本就该歪着睡)。深层还有求解器每拍给静触链条泵能量:接触偏置(回弹 + Baumgarte)可超过接近速度,关睡眠实测 KE 0.1 → 9087——现回弹与偏置只在接触诞生时触发、且总量不超过接近速度;唤醒接触的质量重定基也从「仅猛烈接触」放宽到全部(对仍睡着的物体是空操作)。实测:关睡眠漂移 235 → 19,开睡眠 45 → 3,五球在 5247 步全部睡着、最大倾角 0.71°;保龄楔子/金字塔/摆动旧测试全过。求解数值有变,1.66 之前录的回放不再逐比特复现。C 发射器工具:左侧工具栏「创建」组新增发射器按钮(磁铁之后,不占顶栏仅剩的空位),点按放置、拖拽定方向(默认朝下),8 个上限与面板一致;删除工具此前删不了发射器,现已补上(点目标优先于风场/流体区)。D 拖拽录制无损:录制时指针移动不足 1px 就被丢弃,可拖拽伺服跟的是精确指针,手拖回放因此无法逐比特复现;现只要坐标有任何变化就记一笔(连续相同目标仍跳过),新录的手拖回放可逐比特验证。
- 控制台收进画布区 + 可拖高度 + 彩色标签(1.65):Ryan 在 1.64 上线当晚发来标注截图,四点意见,本版逐条落地。(1) 范围:抽屉移进 #stage,左右钉在画布区两边——左侧工具栏与右侧属性栏不再被盖住(他框出的青色区域就是画布区),左右固定不可横向拖动。(2) 高度可拖:顶边加拖动条,高度可在画布高的 17%~45% 之间自由拖动——上限是他划的青框顶边、下限是他图上黑字底部那条线(按截图量得的 56.5% / 82.4% 换算);拖好的高度按比例记住,下次打开恢复。(3) 日志去 emoji:💤/⏰/✦ 前缀全部去掉,每行改用彩色文字标签区分类型(碰撞橙 / 睡眠蓝 / 生成绿 / 系统灰),正文统一浅色。(4) 顶栏预算:顶栏只剩一个空位已记为长期约束,本版不新增任何顶栏按钮。实现:DOM 移位 + CSS 定位改 bottom:0(舞台底边即状态栏之上)+ console.js 新增 clampDrawerHeight 纯函数(run-tests +4 钉死上下限)与顶边拖动;引擎与求解零改动,物理行为与 1.64 完全一致。
- 控制台改悬浮层(1.64):Ryan 在 iPad 上确认 1.63 的掉帧已解决,同时提出:控制台应压缩上限、且不压缩场景——他发来的 796 物体极限场景截图上亲手划了一条线(约在内容区自下而上 38% 处),那就是控制台可达的最高处。实现:抽屉移出 flex 布局流,改为绝对定位悬浮层(锚在状态栏之上,left/right 贴边,高度 min(340px, 38vh),带上浮阴影);打开/关闭不再改变 #main 与画布的任何尺寸(渲染器不会因此 resize,场景一像素不动),代价是打开时它盖住实验室底部一条——这正是「不压缩场景」的取舍,关掉即全露。控制台其余行为(默认关闭、关着零开销、增量渲染)不变。本版仅一条 CSS 规则变更 + 版本物料,引擎与求解零改动。
- 控制台返修 + 顶栏瘦身(1.63):Ryan 实测反馈两条。其一,1.61 的只读控制台不好用:打开状态被 localStorage 记住、每次进实验室自动铺开,占实验室固定 196px 高度挤压画布;且事件订阅常驻——关着时引擎仍在逐步构造事件、跑撞击扫描,应用层 300ms 定时器不停,开着时日志每 300ms 整表重建(≤300 行),极端场景掉 2–20 帧、日常挂 55–60。修法:打开状态不再记忆(进实验室默认关闭,并清除旧键);订阅与两个定时器只在打开时存在(引擎无订阅时 _emit 直接返回、撞击扫描整段跳过——关着的零开销由引擎结构保证,新增退订静默测试钉住);日志改增量渲染(只追加新行、DOM 尾窗 160 行,连续性由「推送只发生在 flush/sys、每次个位数行」保证);统计刷新 1Hz、flush 500ms;抽屉 196→150px。其二,顶栏太挤:录制回放与录制视频合并为一个「录制 ▾」按钮(点开菜单选模式,录制中点按即停,停止态显示对应模式的计时);导出与分享合并为一个「导出 ▾」按钮(菜单内选导出 JSON / 分享场景复制链接)。btnReplay/btnVideo/btnShare 三个按钮退役,btnReplayPlay(播放最近回放)保留。本版不动引擎与求解逻辑。
- MotionLab 有了自己的标识(1.62):实心蓝盘 + 白色轨迹弧与一颗球——B 方案,Ryan 亲选。两轮设计:第一轮六个线条图标(牛顿摆/弹跳轨迹/摆锤/碰撞冲量/轨道/轨迹 M)被 Ryan 判「都不太像商标」(细线条是图标语言,不是商标语言),第二轮改走实心轮廓:A 重力 M(粗块 M + 凹口嵌球,被 Ryan 一眼认出神似 Gmail,落选)、B 轨迹盘、C 摆环(像时钟/仪表盘,误读风险)、D 实心牛顿摆(故事最足、商标感稍弱)。定稿几何与候选稿一致,仅做生产化:主版(蓝盘白弧)、单色版(遮罩镂空、任意背景单色可用)、应用图标版(深色圆角方 + 蓝盘)与多尺寸 PNG 存在设计目录。应用内换装:
icons.js 的 logo 改为实心画法(盘取 currentColor、弧保持白色)、favicon 换成新标的 data URI;顶栏、首页侧栏、欢迎页、设置里的小标共用同一处定义。本版不动任何功能与求解逻辑。
- 只读控制台:把求解器内部摆上台面(1.61 / 引擎 1.13.0):顶栏新增「控制台」开关,实验室下方抽屉分两块——上沿是实时读数(FPS、步数、物体数、睡着数、接触数;Impulse 专属再加唤醒接触闸门、预唤醒、唤醒/睡着/生成的累计计数),下方是事件日志:强撞击(接近速度 ≥8 px/步的新接触对,每子步只报最强一次,带双方名称与速度)、睡着/唤醒(300ms 批量汇总,防一塔睡着刷屏)、发射器生成、场景载入、后端切换、回放校验结论,可按类型过滤、保留最近 300 条、开合状态记忆。引擎侧(1.13.0)新增可观测性接口:双后端同形
stats,Impulse 另有 onEvent 事件流与累计计数(不入快照,resetStats() 清零);Matter 无求解器内部钩子,内部项报 null、其日志只有应用级事件。本版只读,不改任何求解数值,两后端物理行为与 1.60 完全一致。
- 金字塔爆炸二度修复:快速拖拽不再逐层放大(1.60 / 引擎 1.12.12):1.59 的线上验证抓到了本地协议漏检的形状——验证员按真实指针节奏分 8 段跳拖(目标一次跳约 80px)进塔心,第一次尝试即复现爆炸(松手时球被弹飞出世界、方块飞到画面顶 y≈80),第二次却正常,修复不可靠。Node 同协议复现并定位:冲击波在睡着的塔里逐层放大——球以 34 px/步 撞底层,方块速度 58 → 132 → 210 逐层攀升。机制是 1.59 刻意保留的冻结首次接触:对等质量慢速链(牛顿摆)它给出干净传递、且中间球靠睡觉才不漂移(关睡觉实测偏离 235、改全诚实求解 132),但对快速重撞,冲量按「撞墙」算却打在轻身上,就是放大器;静止塔层间零穿透、无既有接触,预唤醒也看不见这道波。修法:接触生成时记录
wakeTouch(恰有一方在睡);求解首轮若该接触接近速度超过 12 px/步,按实时有效质量(诚实值)重算该接触的 imN/imT——温和的唤醒接触保持冻结传递,暴力的切诚实结算。复测:分段跳拖方块峰值 210 → 42.7(同协议 Matter 为 87,拖法本身暴力、求解不再放大);牛顿摆偏离 45 不变;慢压 10.1、滚动撞击 10.1、保龄球回放瓶峰值 3.6 全部与 1.59 一致。Native 测试 +3 项(分段跳拖回归)。注:求解数值变更,旧版本录制的 Native 回放按录制时引擎校验。
- 金字塔爆炸修复:睡着的堆被拖压不再引爆(1.59 / 引擎 1.12.11):Ryan 实录——把拆除球拖进睡着的方块金字塔,整塔被炸飞、方块飞到画面顶部。定责为 Impulse 后端的唤醒时序:接触在
_collide 里生成时被撞的物体还在睡,其零逆质量被烘焙进接触的有效质量(实测 imN 8.49,真实值约 1.66);同一步内的撞击唤醒把它叫醒后,求解按「不可动质量」算出的过量冲量逐轮泵能(单子步内 vn 在 −8/+48.6 间翻转、冲量 ±98),整塔被扰动的方块又逐个以冻结接触唤醒下一个,连环引爆。修法:新增预唤醒——上一子步的接触表明某睡眠体仍在被运动物体压着的,在 _collide 之前先唤醒,持续接触一律按真实质量生成。首次接触的冻结求解刻意保留:它正是牛顿摆链条获得干净等质量传递的原因(改成唤醒后重算有效质量,牛顿摆偏离 45 → 132;给拖拽伺服加接触限速更糟,峰值 181——慢速液压式压入反而最大化穿透累积)。复测(金字塔预设几何 + 同款拖压):方块峰值速度 34.1 → 10.1,最高方块不再越过塔顶自有高度;牛顿摆偏离保持 45 不变;保龄球真实回放(应用回放路径)瓶峰值 3.6 前后不变。Native 测试 +3 项。注:求解数值变更,旧版本录制的 Native 回放按录制时引擎校验。
- 自研后端正式命名 Impulse(冲量)+ 求解器稳定性(1.58 / 引擎 1.12.10):后端注册名由开发代号 Native 正式改为 Impulse(后端 id 仍为 native,存档与回放不受影响;内部代号 Native67),并随本版稳定性修复由 experimental 毕业为 stable。牛顿摆在 Native 下跑一阵中间球就散开——牛顿摆在 Native 下跑一阵中间球就散开——定责为接触求解的单向扫描偏置:一排紧贴的球里,每次撞击传递都系统性偏向后求解的接触,中间球被逐周期泵走(600 步偏离 184px、2400 步整排散架;Matter 同期 35px)。会入睡的堆叠场景不受影响(金字塔 2400 步位移 0)。修法三件:① 接触求解改双向交替扫描(对称 Gauss-Seidel)抵消方向偏置;② 求解迭代 10 → 30;③ 弹性改回应热启动预压之前采样的接近速度(1.12.9 的接触生成采样会让链式接触「饿死」,而热启动之后的实时速度正是 1.57 弹飞的元凶——新采样点在两者之间)。复测:牛顿摆偏离 184 → 45px 且 3600 步保持平稳;保龄球真实回放瓶峰值速度 2.46 → 0.87(弹飞修复更稳);弹性 0.8 下落回弹仍精确为 e²·h(205px);300 物体堆叠步进耗时约 +10%。Native 测试 +2 项(牛顿摆 1200 步不散 + 末球仍正常摆出)。注:求解数值再次变更,旧版本录制的 Native 回放按录制时引擎校验。
- Native 求解器修复:轻物体不再被弹飞(1.57 / 引擎 1.12.9):保龄球场景实测——重球以 2.4 px/步慢速挤进三角瓶金字塔时,一只瓶曾被以 19.6 px/步弹到右墙根(约为动量守恒上限的 4 倍)。定责:求解器第一轮迭代读到的接触点法向速度被热启动冲量与楔形几何放大到 vn=−61(瓶的真实速度只有 0.72),弹性项照单全收;同时 16 px 的深重叠又让穿透偏置开出 12.6 的分离速度。修法:弹性改回应接触生成时捕获的真实接近速度(Box2D 的标准做法),穿透偏置速度封顶 4 px/步、深重叠交由位置修正分几步化解。复测:瓶峰值速度 19.6 → 2.5,球正常穿进瓶堆;弹性 0.8 的下落回弹实测 205 px 与理论 e²·h 分毫不差,真实弹跳不受影响。仅 Native 后端求解器变更,Matter 与发射器不动;注意旧版本录制的 Native 回放按录制时的引擎校验。
- 发射器(定点喷物体)+ 快照载入 id 守卫(1.56 / 引擎 1.12.8):① 引擎新增
addEmitter:发射器是一个固定喷口 {位置、方向、速率(个/秒)、形状(圆/方)、大小、初速、上限、启用},在每个固定步的末尾按 round(60/rate) 步间隔喷出一个物体——喷发日程只是模拟步序号的函数、模拟时钟随快照走,所以录制的回放会一颗不差地重演(双后端均有逐位一致测试守门)。喷出的物体在描述符里带 emitter 标记(随快照往返,上限计数在恢复后依然准确);达到上限时回收最早喷出的一颗,喷泉不会无限涨;全场 1500 物体的硬顶之上不再喷发。场景格式新增 emitters 数组(≤8 个,随场景保存/分享/导入校验),实验室在场景属性里添加、列表点选、画布点选与拖动,编辑面板可调位置/形状/速率/大小/初速/方向(度)/上限/启用,录制回放时发射器的增删改随 regions 事件一同记录。② 顺带修掉一个引擎老 bug:把快照 load() 进一个全新引擎后,再以自动 id 添加物体,新 id 会撞上已载入条目的 id、把对方从索引 Map 里顶掉——对方还留在物理世界里模拟,却从此查不到、删不掉(发射器的快照连续性测试把它揪了出来:连撞 5 个)。修法:load 结束时把 id 序号推进到全部已载入 id 的最大编号之后,双后端同修,并有回归测试守门。
- 多米诺连锁修复、静态渲染签名、触控板缩放(1.55 / 引擎 1.12.7):① 多米诺预设在默认后端整排冻在半倒状态——实测定责:睡眠机制在慢速倾倒中途把牌冻住(1 号牌睡在 42°、2 号牌 2.6°),且默认密度下撞击只是准静态倚靠、传不动能。修法:引擎新增
noSleep 描述符(双后端永不入睡,Matter 走 sleepThreshold ∞、Native 睡眠遍跳过),预设牌身密度 0.001→0.004、间距 62→52、气阻 0.002 并标记 noSleep——双后端均全倒(Matter 约 470 步 / Native 约 170 步,常驻回归测试守门)。② 静态物体改尺寸后画面不变:静态层缓存的失效签名只有 id/位置/角度/类型/磁极,漏了尺寸——签名补入包围盒尺寸与顶点数,缩放静态物即时重烘(渲染测试新增 1 项)。③ 触控板缩放:滚轮处理原先只看 deltaY 符号、每事件固定 ±10%,触控板捏合/双指滚动一秒几十个小事件全是满格跳变——改按 delta 实际大小比例缩放(deltaMode 归一化、ctrlKey 捏合单独增益、单事件限幅),鼠标滚轮一档仍约 ×1.17/×0.85
- Native 大场景健壮性(1.43):修复 Native 在大场景中途崩溃冻结(碰撞裁剪对精确对齐的堆叠不再出错,796 物体极限压测可完整跑完);休眠判定平滑化让大堆积更快静下来;场景属性的「引擎」一行改为显示当前后端、切换即更新
- Native 物体不显示已修(1.42):Native 的圆形物体补齐顶点多边形(宿主契约:每个刚体必须暴露非空 vertices),修好 1.41 里 Native 下画布只剩网格的问题
- 主界面工作台(1.40):主界面改版为工作台式布局(深色侧栏 + 场景/预设列表 + 右侧详情检查器);后端接口同时正式化为注册表(见上「后端注册表」)
- 场景导入加固(1.39):导入文件上限 2 MB(含分享链接解压后),物体 ≤2000、约束/铰链各 ≤500、流体/风场各 ≤20,逐项校验坐标与尺寸范围;坏文件整体拒绝并说明原因,当前场景不受影响
- 捏合缩放流畅化(1.38):缩放/平移时缓存层改用贴图变换、不再逐帧重烘焙,钉板场景相机移动时每帧绘制调用减少约 81%
- 种子要看得见效果(1.37):「刷新种子」现在会立刻按新种子重演场景——动态物体的起始位置按种子重新微偏(钉板换个种子,球的落点分布就变);手动填种子后点「按种子重演」同理。同一种子、同一场景,重演结果一模一样
- 随机种子(1.36):场景属性里新增「随机种子」——引擎的随机流(1.21 起就有)第一次接入界面:种子随场景保存/分享,载入即生效;点「刷新种子」换一轮随机;配套动作「随机扰动」用当前种子给每个动态物体一次随机冲量,同一种子扰动结果可完全重演
- 渲染再优化(1.35):背景网格也进离屏缓存——网格只随相机变化,以前每帧重画约 240 笔;现在和静态层一样烘焙后贴图。高尔顿钉板每帧绘制调用继 1.33 后再降约 46%(535 → 290)
- 小修(1.34):「拖动静态物体」开关不再被误点画布空白解除——开关现在属于物体本身,点空一次再抓同一物体照样能拖
- 渲染优化(1.33):静态层离屏缓存——钉板这类静态物多的场景,静态物只在场景变化时重绘一次,平时每帧直接贴图;实测高尔顿钉板每帧绘制调用减少约三分之二,画面更跟手
- 浮力讲条件(1.32):浮力现在按物体真实的浸没面积算——横着跨在水域边缘的只算浸到的那部分,圆形和斜放的物体按真实形状;浮力作用在浮心上,斜放的浮木会自己回正;而且液体要能进到物体底面之下浮力才成立——贴紧池底的轻块不会再自己浮起来
- 模块联动(1.31):水里的阻尼现在同时拖慢旋转——风车加水后会被明显刹住(此前只拖平移、质心不动的转子几乎无感);流体可以设流速,物体顺流而下;风场吹过水面会带出表面水流,水里的物体会跟着漂(水面区域里能看到流向箭头)
- 风车与阵风(1.30):新预设「风车」没有马达——一块只盖住轮子上半部的风场把帆叶逐片吹过顶部,轮子就转起来了;风场新增「阵风」:风速一阵强一阵弱(编辑器里可调强度与周期),风车会跟着忽快忽慢
- 修复与静态拖动(1.29):摩天轮的十字臂不再散架、座舱保持直立、轮子匀速转动;选中静态物体时,属性面板新增「拖动静态物体」开关,开启后运行中也能直接在画布上拖动它改位置(动态物体仍用物理拖拽)
- 公式库(1.4.0):
Formulas 是纯函数集:动能、动量、冲量、万有引力、轨道/逃逸速度、胡克定律、单摆周期、浮力、阻力、摩擦、抛射程、向心加速度等;引擎实例还有现成的 bodyKineticEnergy() / totalMomentum() / centerOfMass() 量活世界
- 稳定性(1.4.0):
PhysicsEngine.validateDescriptor(desc) 静态校验描述符并列出问题;位置/速度等 setter 忽略 NaN 等非法输入,不让一个坏值毒化整个世界;构造选项 maxSpeed 给速度封顶,防单次失控冲量把场景炸穿
- 交互:
pick(x, y) 拾取;beginDrag(body, x, y) / moveDrag(x, y) / endDrag() 物理拖拽(可甩掷);onCollision((a, b, pair) => …) 碰撞回调
- 改属性:
setVelocity / setPosition / setAngleDeg / setDensity / setFriction / setRestitution / setStatic / setLockRotation / setMagnet / stopMotion,都以单个 body 为单位,修改时会自动唤醒休眠物体
四、约定
- 坐标单位为像素,y 轴向下;角度用弧度(
setAngleDeg 除外,它收角度)。
- 核心不做渲染:宿主每帧读取
body.position 与 body.angle 自行绘制;MotionLab 本身就是用这套核心搭的,它的 js/physics.js 只是场景格式适配层。
- 同一核心还有一份独立打包(含说明与测试)在本机
~/workspace/physics-engine/,与站内版本保持同步。
五、PF 引擎调用方式(平台格斗)
PFLab 背后的 PF 引擎(js/pf/,版本 PFEngine.VERSION)建立在 PhysicsEngine 之上:角色控制器、战斗判定与确定性 AI 状态机都只经适配层调用引擎公开 API。推荐用门面 PFEngine 接入:
import { PFEngine } from './js/pf/pf-lab.js';
// 无头对局(无 DOM,可在工具/测试里跑)
const match = PFEngine.createMatch({ ai: 'normal' }); // 'calm' | 'normal' | 'sharp' 或覆盖对象
match.step({ move: 1, jump: false, attack: false, dash: false }); // 每步喂一个意图
match.state; // 'fight' | 'over';match.winner 看胜负
match.debugInfo(); // 双方状态/伤害/速度、AI 状态、步数、最近命中
// 调参(作用于共享参数表)
PFEngine.tune({ attack: { damage: 9 } });
- 意图接口:玩家与 AI 同构——
{ move: -1|0|1, jump, attack, dash, face },后三者为按下那一步触发。
- AI 档位:
calm(决策 16 步/攻击冷却 48)、normal(10/30)、sharp(6/18);也可传任意覆盖对象,只影响该 AI 实例。
- UI 壳:
PFEngine.createLab(onExit) 得到 MotionLab 同款全屏界面(需要页面带有 #pfLab 标记),enter() 打开、exit() 退出并释放全部资源。
- 完整文档(含参数表与 PhysicsEngine 全部 API)见仓库
docs/DEVELOPER.md,在 GitHub 上可直接阅读。
MotionLab's physics layer is a general-purpose core, PhysicsEngine, with no ties to this project: it consumes plain data descriptors and knows nothing about the DOM, rendering, or any file format. You can download it into your own project and build physics simulations with the same API. The core files are physics-engine.js (the engine and backend registry, an ES module), native-engine.js (the self-developed Native backend since 1.12.0, imported by physics-engine.js) and matter.min.js (Matter.js 0.20, used by the default backend).
Current versions: MotionLab — · PhysicsEngine — · Matter.js —. The engine version is readable in code as PhysicsEngine.VERSION (the module also exports a VERSION constant); Settings → About shows the same set.
1. Download
2. Minimal example
Matter must load first as a global via a classic script; the engine is an ES module imported with type="module". Alternatively inject it with PhysicsEngine.setMatter(Matter) or the { matter } constructor option.
<script src="matter.min.js"></script>
<script type="module">
import { PhysicsEngine } from './physics-engine.js';
const pe = new PhysicsEngine({ enableSleeping: true, substeps: 2 });
// static ground
pe.addBody({ kind: 'rect', x: 400, y: 560, width: 800, height: 40, isStatic: true });
// a bouncy ball
pe.addBody({ kind: 'circle', x: 400, y: 120, radius: 18, restitution: 0.6 });
let last = performance.now();
function frame(now) {
pe.advance(now - last); // fixed-timestep advance
last = now;
// draw each body from pe.allBodies() using position / angle
requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
</script>
3. API at a glance
- Construction:
new PhysicsEngine({ gravity: { x: 0, y: 1 }, enableSleeping, fixedDt, maxSteps, substeps, seed, maxSpeed, gravitation }); setGravity(x, y, enabled) changes gravity.
- Bodies:
addBody(desc) / removeBody(id) / clear() / allBodies() / count. Descriptor fields: kind ('circle' | 'rect' | 'polygon'), x, y, radius, width, height, sides, density, friction, frictionAir, restitution, isStatic, lockRotation, vx, vy, angle (radians), magnet (pole strength), userData (passed through untouched).
- Constraints (springs / rods):
addConstraint({ bodyA, bodyB, pointA, pointB, stiffness, damping, length }). bodyA: null anchors to the world point pointA; stiffness near 1 behaves as a rigid rod; removeConstraint(id) removes one, and removing a body cleans up its constraints automatically.
- Stepping:
advance(elapsedMs, speed) fixed-step accumulator (stable at any refresh rate); stepOnce() single step; setSubsteps(1–8) anti-tunnelling substeps (except while dragging).
- Snapshots:
snapshot() exports plain JSON { bodies, constraints, hinges, fluids, winds, rng }; load(data) restores it, including the random stream position.
- Backend registry (1.11.0; Native landed in 1.12.0):
PhysicsEngine.BACKENDS lists the solver backends behind the API (matter active / native self-developed, experimental); PhysicsEngine.create({ backend }) constructs through the registry and instances report backendId. Hosts code against the API only — an unavailable backend throws plainly instead of silently falling back. The Settings "Physics backend" picker switches live, replaying the current scene.
- Queries & impulses (1.2.0):
queryRegion(x, y, w, h); raycast(x1, y1, x2, y2) (nearest first, with hit points); addVelocity(body, dvx, dvy); applyRadialImpulse(cx, cy, { radius, base, power, filter }) (magnitude = base + power×(1 − distance/radius), returns how many bodies were pushed).
- Seeded RNG (1.3.0): pass
{ seed } and random() / randomRange(min, max) / randomInt(min, max) / choice(arr) / shuffle(arr) draw from the engine's own reproducible stream — same seed, same sequence. Without a seed one is chosen for you; read it back via pe.seed; setSeed(n) resets the stream and syncs Matter's internal seed.
- Named bodies (1.4.0): descriptors may carry
name (duplicates allowed); find with getBodyByName(name) / getBodiesByName(name), rename with renameBody(bodyOrId, name), read with nameOf(body). Names persist in snapshots. In MotionLab, a body's label is its engine name.
- Pairwise gravitation (1.4.0):
setGravitation(G, { softening }) turns on Newtonian attraction between every pair of bodies (softening avoids singularities; static bodies weigh area × density) — ideal for planets and orbits. setGravitation(0) turns it off.
- Fluid buoyancy (1.4.0):
addFluid({ x, y, width, height, density, drag }) defines a fluid region (center coordinates; the top edge is the surface). Bodies feel buoyancy ∝ density ratio × submerged fraction, plus in-fluid drag — light bodies float, heavy ones sink. removeFluid(id) removes a region; fluids persist in snapshots.
- Magnetism (1.5.0): the descriptor field
magnet (−100..100; positive = N pole, negative = S pole) — like poles repel, opposite poles attract, and magnets pull unmagnetised iron bodies; range 320, momentum-conserving. Tune or disable globally with setMagnetism(K, { range, softening }), change one body with setMagnet(body, v); the pure form is Formulas.magneticForce.
- Wind fields (1.5.0):
addWind({ x, y, width, height, vx, vy, power }) defines a wind region (center coordinates); bodies inside are blown toward the wind velocity — lighter bodies go faster, iron barely stirs. removeWind(id) removes a region; winds persist in snapshots. 1.5.0 also speeds up the pairwise-force pass (one unified traversal for gravitation + magnetism, ≈40% faster on an isolated benchmark).
- Hinges & motors (1.7.0):
addHinge({ bodyA, bodyB, pointA, pointB, motorSpeed, motorPower }) pins two bodies (or a body to a fixed mount with bodyA: null) at one shared point so they can only rotate around it; motorSpeed is the motor's target relative angular velocity (rad/step, ±0.3), acceleration-capped, with the reaction split by inverse inertia. Parts of one machine never collide with each other (a hinge cluster shares a negative collision group), so folding and spinning never jam; motor-driven bodies never fall asleep. setHingeMotor(id, v) retunes a motor, hingeAnchors() returns pin points for rendering/picking, and hinges persist in snapshots.
- Use it right in the lab (1.23, expanded in 1.25/1.26): with nothing selected, the Scene panel's "World Effects" section sets gravitation G and adds/edits fluid and wind regions; fluid and wind regions can be dragged on the canvas to move them. The Magnet tool in the left rail (or the button in World Effects) places a fixed magnet directly; select any body to rename it, set its magnetism in the Material section, or apply a one-tap material preset (foam / wood / rubber / ice / iron). The top-bar Share button packs a whole scene into a link that opens right into that scene, and the My Projects home has its own Import Scene entry. The "Orbital Gravitation", "Buoyancy Pool", "Magnet Array", "Wind Tunnel", "Materials Lab" and "Magnet Swing" and "Motor Windmill" / "Ferris Wheel" presets load ready-made demos.
- Machinery & recording (1.28): the left rail gains a Hinge tool — tap the pin point on a first body, then a second body to hinge them (empty space = fixed mount); tap a hinge pin marker on the canvas to set its motor speed or delete it. The top-bar Record button captures the canvas animation as a looping GIF (up to 20 s) — no screen recording needed for posts and demos
- Sleepers wake when support vanishes (1.44): sleeping bodies re-check their support every 15 steps — delete the base of a sleeping tower or drag a support away and the bodies above wake and fall instead of hovering (both backends); being hung from a spring/hinge or immersed in a fluid counts as support, and zero gravity skips the check
- Challenges & deterministic replay (1.50): the home sidebar gains Challenge Mode — 6 levels, fixed building budgets, hold-in-zone goal tracking and 3-star ratings (
js/challenges.js, DOM-free). GIF recording is replaced by deterministic replay: a recording is the starting engine snapshot plus every input stamped by simulation step; the exported .replay.json replays with scrub/speed controls and a final state-hash verdict (js/replay.js). The same scripted run reproduces bit-identical hashes live vs replayed on BOTH backends, proven by Node tests. Note: engine snapshots omit gravity, so replay files carry the scene settings separately
- Performance pass & UI tidy-up (1.51 / engine 1.12.5): profiling found the every-15-steps orphan-sleeper probe (1.44) eating ~31% of all step time on the Matter backend at ~800 bodies — its candidate search was O(sleepers x bodies). Both backends now use a uniform grid (touch predicate and support semantics unchanged): on a 777-body stress scene the average step went 4.9→3.5 ms and the p95 spike 25→10 ms. Native also drops template-string contact-sort / warm-start keys for numeric keys, reuses solver scratch vectors, marks support with a per-substep stamp, and skips sleeping bodies in the post-solve shape sync. Replay checkpoints measured ~0.4 ms — not a bottleneck, left alone. UI: the lab Scene Properties panel loses its Challenge entry and the in-lab challenge list; Challenge Mode is entered only from the home hub, and the card's "All challenges" goes straight there
- Replay scrub fix & video recording (1.52): the replay seek bar is now asynchronous —
scrubPlayback only records the target step and the frame loop catches up with a ~16 ms-per-frame stepping budget, rendering as it goes (backward seeks restore the nearest checkpoint first); checkpoint spacing tightened 300 → 120 steps (at most ~90 for a max-length 3-minute replay; one snapshot of ~780 bodies measures ~323 KB JSON-equivalent). New js/video.js: real-time recording via canvas.captureStream + MediaRecorder, MIME probed mp4 → webm (pickVideoMime is a pure, tested helper), 60 s cap. Video is a live capture (frame rate follows the scene); deterministic replay remains the lossless format. Without MediaRecorder the button honestly toasts "unsupported" (the jsdom smoke covers that path)
- Code cleanup (1.53): a whole-repo audit removed provably unreferenced leftovers —
hasStoredLang (i18n.js), TOOL_LABELS (icons.js; tool names come from i18n now), lab3DIsRunning (lab3d.js), WORLD_SIZE (pf-stage.js, plus its now-unused WORLD import), clearAutosave/clearVisited (storage.js; superseded by resetAllData) — and 11 dead CSS rules for the old scene-picker dialog (.scene-item etc.) and the lab challenge list removed in 1.51 (.chal-row etc.). Internally used format constants (SCENE_FORMAT and kin) are module public API and stay. Engine, formats and behaviour unchanged
- Warm-recording replay divergence fixed (1.54 / engine 1.12.6): live verification found that a replay recorded after the scene had already been running (solver warm) reported "diverged" on both backends. Node reproduction assigned the causes: (1) engine snapshots did not carry angular velocity or sleep state —
describeBody/addBody now round-trip va and sleeping on both backends (a restored sleeping pile tracks the original bit-for-bit for 300 steps); (2) contact-pair warm-start impulses cannot be serialized, so startReplayRecording now reloads the captured snapshot into the live world, making the recorded run and its replay start from the same rebuilt state — a Newton's cradle warmed for 300 steps plus a scripted drag reproduces bit-identically on both backends again. Known limit: a checkpoint restore triggered by scrubbing mid-playback still loses warm-start state, so the verdict can report divergence after a scrub on stiff scenes; an uninterrupted full playback is guaranteed exact
- Spring Oscillator made visible + editor summary goes live (1.69 / engine 1.13.3 unchanged): the 1.68 live check found the oscillator's swing small and fast-decaying — near-still to the eye seconds after load. A probe comparing five (stiffness × start) combinations settled on moving only the start: the three balls now start 120 px below the rest-length point (≈94 px below equilibrium), stiffness kept at 0.15 — the undamped ball's first swing grows 64→175 px and still swings 16 px past 10 seconds, the medium-damped one settles in 5.2 s, the heavy one in 2.3 s, identical on both backends; the swing spans 191–366 px, touching neither beam nor ground. Also fixes the other 1.68 nit: the feel-summary line at the bottom of the spring editor now follows the sliders live (the sliders' own readouts were already live). No engine change: solver numerics unchanged, older replays unaffected. Tests +2 (facade preset pin + smoke live-summary check).
- Springs are real springs now (1.68 / engine 1.13.3): soft constraints used to enter the 30-iteration solver and converge into rigid rods every substep — a hang probe measured zero crossings over 600 steps, identical for stiffness 0.05→0.85 and damping 0→0.5, so springs were springs in name only. Constraints with stiffness < 0.99 no longer iterate; each substep applies one Hooke force F = −k·C − c·vn, with k = stiffness × 0.22 and damping normalized to critical (damping = 1 is near-critical for any spring/mass combination); 0.99 and above keeps the iterative solve, so rod behaviour has zero regression. Impulse applies the force before integration (symplectic Euler); on the Matter side a soft constraint builds no M.Constraint and keeps only its descriptor. Measured: hang sag 31.4 / 7.2 / 3.4 / 1.9 px (stiffness 0.05 / 0.22 / 0.5 / 0.85, exactly the g·m/k equilibrium), damping 0 still swinging at step 600, 0.5 and above settled; cross-backend sag within 0.5 px. Also new: a spring editor (tap a spring line; stiffness/damping/rest length plus four feel presets, switching representation live across the soft/rigid boundary), a Spring Oscillator preset (three dampings side by side), and a retuned trampoline (net springs 0.22→0.85, load densities down to 0.001 — tension amplification in a shallow-V chain collapsed the old tuning under any honest spring model). Solver numerics changed; older replays no longer verify bit-exactly. Tests +23 (engine +6, native +7, facade +4, smoke +6).
- Scrubbing a replay no longer drops the drag (1.67 / engine 1.13.2): Ryan's report — a medium scene recorded while dragging, scrubbed mid-drag, ended diverged with a small deviation. Three gaps, all in the snapshot round-trip: (1) snapshots carried no drag state, so after a scrub restore the drag servo/constraint was gone and every later drag event was dropped by the
world.dragging guard — the whole drag vanished. Snapshots now carry the drag: on Matter with the original grab offset AND the solver-tracked angleB (angleB lags the body angle; restoring the offset alone swings the grab point by whole pixels — measured 2.5 px on the next step); on Impulse the servo is just a target and restores as-is. (2) A fresh Matter body's deltaTime is the baseDelta while a live body's is the substep delta, and setVelocity scales by the ratio — the restored positionPrev was off by 2x and the very next step diverged by 0.0018 px; bodies are now pinned to the substep delta at creation. (3) Sleep counters and the constraint warm-start impulse (postSolveAll decays it instead of zeroing it; preSolveAll applies it next step) were lost; both round-trip now. Measured: a no-drag restore at step 60 went from diverged to exact; mid-drag scrub hashes match on both backends; rod-constraint and motor-hinge restores are exact too. Remaining known limit: Matter's contact warm-start impulses live in the pairs table and are not serialized, so extremely chaotic scenes may still show a small deviation after scrubbing when a sleep/wake threshold flips; unscrubbed playback stays exact. Solver numerics unchanged — older replays are unaffected. Tests +14 (engine +6, native +4, facade +4).
- Cradle sleep pose + emitter tool + lossless drag recording (1.66): three items, all Ryan's picks as the critical ones (he deferred the console command input himself, worried it could cause trouble). A — the cradle sleep pose: on Impulse the row dozed mid-pose at up to 7.55°. Two causes: (1) the sleep rule demanded a recent contact as support, but a settled row has 1 px gaps and zero contacts, so it could only sleep while still swinging — a rigid link or hinge to a fixed anchor now counts as support; (2) a hanging body may not sleep while its hang direction is more than 2° off the gravity axis — it must wait until the swing dies (bodies with two fixed anchors are exempt: a two-rope sign rests tilted by design). Deeper, the solver pumped energy into touching chains every substep: the contact bias (restitution + Baumgarte) could exceed the approach speed (measured KE 0.1 → 9087 with sleeping off), so restitution and the bias now fire on contact birth only and their total never exceeds the approach speed; the wake-touch mass re-base widened from violent touches to all of them (a no-op for bodies still asleep). Measured: drift 235 → 19 with sleeping off, 45 → 3 with it on; all five balls asleep by step 5247 at 0.71° max tilt; the wedge, pyramid and swing guards all still pass. Solver numerics changed — replays recorded before 1.66 no longer verify bit-exactly. C — the emitter tool: a new button in the rail's create group (after the magnet, costing none of the top bar's last free slot); tap to place, drag to aim (down by default), same 8-emitter cap as the panel; the delete tool, which could not remove emitters, now can (point targets win over wind/fluid regions). D — lossless drag recording: the recorder dropped pointer moves under 1 px while the drag servo followed the exact pointer, so hand-dragged replays could never verify bit-exactly; every exact change is now recorded (identical consecutive targets still skipped), and newly recorded hand-dragged replays verify.
- Console confined to the stage, drag-resizable, coloured tags (1.65): Ryan sent an annotated screenshot the night 1.64 shipped, with four notes; this release lands all four. (1) Extent: the drawer moves inside #stage, pinned left/right to the canvas area — the tool rail and the property panel are never covered (the cyan box he drew is exactly the stage), and it cannot be dragged sideways. (2) Draggable height: a handle on the top edge resizes it between 17% and 45% of the stage height — the ceiling is his cyan top line, the floor is the bottom of his annotation text (measured off the screenshot at 56.5% / 82.4% of screen height); the dragged height is remembered as a fraction and restored on open. (3) No more emoji in the log: the 💤/⏰/✦ prefixes are gone; each line carries a coloured text tag instead (impacts orange, sleep blue, spawns green, system grey) over uniform body text. (4) Top-bar budget: the bar has exactly one free slot left, now recorded as a standing constraint — this release adds no top-bar buttons. Implementation: a DOM move, bottom:0 positioning (the stage’s bottom edge sits right above the status bar), a pure clampDrawerHeight helper in console.js (pinned by +4 run-tests) and pointer-drag wiring on the top handle; no engine or solver changes, physics identical to 1.64.
- The console becomes an overlay (1.64): Ryan confirmed on his iPad that 1.63 fixed the frame drops, and asked for the console's extent to be capped without compressing the scene — on his screenshot of the 796-body stress scene he drew the ceiling line himself (about 38% up from the bottom of the content area). Implementation: the drawer leaves the flex flow and becomes an absolutely-positioned overlay anchored above the status bar (left/right flush, height min(340px, 38vh), a soft top shadow); opening or closing it no longer changes #main or the canvas by a single pixel (the renderer never resizes for it) — the trade is that while open it covers a bottom strip of the lab, which is exactly what "don't compress the scene" means; close it and everything is visible again. All other console behaviour (starts closed, zero cost while closed, incremental log) is unchanged. One CSS rule plus release bookkeeping; no engine or solver changes.
- Console rework + a slimmer top bar (1.63), both from Ryan's field report. (1) The 1.61 console misbehaved: its open state was persisted and restored on every lab entry (196px of lab height, squeezing the stage), the event subscription was permanent (engine built event objects and ran its impact scan every step even while closed; a 300ms timer cycled in the background), and while open the log rebuilt all ≤300 lines every 300ms — costing 2–20 FPS in extreme scenes and a few frames otherwise (55–60). Fixes: open state no longer persisted (the lab starts closed; the stale key is removed); the subscription and both timers exist only while open (with no subscribers the engine's _emit returns immediately and the impact scan is skipped wholesale — zero cost when closed is structural, now pinned by an unsubscribe-silence test); the log renders incrementally (append-only, 160-line DOM tail window; continuity is guaranteed because pushes happen only in flush/sys, a handful per interval); stats at 1 Hz, flush at 500ms; drawer 196→150px. (2) The top bar was cramped: Record Replay and Record Video merge into one Record ▾ button (menu chooses the mode; while recording, the button is that recording's stop control with its timer), and Export and Share merge into one Export ▾ button (menu: Export JSON / Share scene by copied link). btnReplay/btnVideo/btnShare retired; btnReplayPlay stays. No engine or solver changes.
- MotionLab has its own logo (1.62): a solid blue disc with a white trajectory swoosh and ball — candidate B, picked by Ryan. Two design rounds: round one's six line icons (cradle / bounce / pendulum / impact / orbit / trajectory-M) were judged "not trademark-like" (hairlines are icon language, not trademark language); round two went solid-silhouette: A Gravity M (a blocky M with a ball in its notch — Ryan spotted its Gmail resemblance on sight; out), B Trajectory Disc, C Pendulum Ring (reads as a clock — misread risk), D Solid Cradle (best story, weaker trademark feel). The final geometry matches the candidate exactly; production assets add a primary (blue/white), a mono (mask-knockout, any background, one colour) and an app-icon variant (dark rounded square + blue disc), plus sized PNGs, kept in the design folder. In-app: the
icons.js logo is now drawn filled (disc takes currentColor, swoosh stays white) and the favicon is the new mark as a data URI; top bar, hub sidebar, landing and the settings mini-logo share the one definition. No behaviour changes in this release.
- Read-only console: solver internals on the table (1.61 / engine 1.13.0): a Console toggle in the top bar opens a drawer under the lab. Along the top, live readouts (FPS, steps, bodies, sleeping, contacts — plus, on Impulse, cumulative wake-touch gate / pre-wake / wake / sleep / spawn counters); below, an event log: strong impacts (new contact pairs approaching at ≥8 px/step, strongest per substep, with both names and the speed), sleep/wake (batched over 300 ms so a whole tower falling asleep doesn't flood it), emitter spawns, scene loads, backend switches and replay verdicts — filterable by type, keeping the last 300 lines, open state remembered. Engine side, 1.13.0 adds an observability surface with the same shape on both backends: a
stats getter, and on Impulse an onEvent stream plus cumulative counters (never serialized; resetStats() zeroes them); Matter has no solver-internal hooks, so its internal fields report null and its log carries app-level events only. Read-only release — no solver numerics change; physics on both backends is identical to 1.60.
- Pyramid detonation, second fix: fast drags no longer amplify row by row (1.60 / engine 1.12.12): live verification of 1.59 caught the shape the local protocol had missed — the verifier dragged in 8 chunk jumps (~80px per jump, the cadence of real pointer events) to the tower's centre and the first attempt detonated exactly as before (ball ejected out of the world on release, a box at y≈80 near the stage top), while a second identical attempt behaved: unreliable. Reproduced in Node under the same protocol and traced: the shock wave amplified through the sleeping rows — ball arriving at 34 px/step, box speeds climbing 58 → 132 → 210. The mechanism is the frozen first-touch solve 1.59 kept deliberately: for gentle equal-mass chains (Newton's cradle) it gives a clean transfer and the middle balls' sleep is what stops drift (sleep disabled measures 235; a fully honest wake solve measures 132), but for a fast, heavy impact the impulse is sized against a wall and delivered to a light body — an amplifier; and resting rows have zero penetration, so no contact exists for the pre-wake pass to see the wave coming. Fix: contacts record
wakeTouch (exactly one body asleep at creation); on the solve's first iteration, a wake-touch approaching faster than 12 px/step has its imN/imT re-based on the honest live effective mass — gentle wake-touches keep the frozen transfer, violent ones settle honestly. Re-test: chunked-drag peak box speed 210 → 42.7 (Matter measures 87 under the same protocol — the drag is violent; the solver no longer multiplies it); cradle drift unchanged at 45; slow press 10.1, rolling impact 10.1, bowling replay peak pin 3.6 — all identical to 1.59. Native tests +3 (chunked-drag regression). Note: solver numerics changed — Native replays recorded on older versions verify against their recording engine.
- Pyramid detonation fixed: pressing into a slept stack no longer explodes it (1.59 / engine 1.12.11): recorded by Ryan — drag the wrecking ball into a sleeping box pyramid and the whole tower detonates, boxes flying to the top of the stage. Root cause is wake timing in the Impulse backend: contacts are created in
_collide while the struck body is still asleep, so its zero inverse mass is baked into the contact's effective mass (measured imN 8.49 vs the true ~1.66); the wake-on-impact pass then wakes it within the same substep, and the solve pumps energy with the immovable-body impulses (vn flipping −8/+48.6, impulses ±98 inside one substep), chain-detonating as each disturbed box wakes the next through a frozen contact. Fix: a pre-wake pass — a sleeper that last substep's contacts say is still being pressed by a moving body wakes BEFORE _collide, so sustained contacts are always created with honest masses. The first-touch frozen solve is kept deliberately: it is what hands a Newton's-cradle chain its clean equal-mass transfer (recomputing masses at the wake instead measured cradle drift 45 → 132; a drag-servo contact cap measured worse still, peak box 181 — a slow hydraulic press maximises penetration build-up). Re-test (Pyramid preset geometry, same servo press): peak box speed 34.1 → 10.1, no box rises above the tower's own top row; cradle drift unchanged at 45; the real bowling replay (app playback path) unchanged at peak pin 3.6. Native tests +3. Note: solver numerics changed — Native replays recorded on older versions verify against their recording engine.
- Self-developed backend formally named Impulse + solver stability (1.58 / engine 1.12.10): the backend's registry name graduates from the dev codename Native to Impulse (backend id stays 'native', so saves and replays are unaffected; internal codename Native67), and it leaves experimental status for stable with this release. Newton's cradle on the Native backend fell apart within seconds — root cause is the one-directional contact sweep: in a touching row, every impact transfer systematically favours the contacts solved last, pumping the middle balls a little further each cycle (184px drift in 600 steps, row destroyed by 2400; Matter stays at 35px). Sleeping stacks were never affected (pyramid displacement 0 over 2400 steps). The fix is three parts: (1) symmetric Gauss-Seidel — the contact sweep alternates direction every iteration, cancelling the bias; (2) solver iterations 10 → 30; (3) restitution answers the approach velocity sampled before warm-start pre-application (1.12.9's collide-time sample starved chains, while the post-warm-start live velocity is what launched pins in 1.57 — the new sample point sits between the two failure modes). Re-test: cradle drift 184 → 45px and flat out to 3600 steps; peak pin speed in the real bowling replay 2.46 → 0.87 (the launch fix is strengthened, not traded away); a restitution-0.8 drop still rebounds to exactly e²·h (205px); a 300-body pile costs about +10% step time. Native tests +2 (cradle holds 1200 steps + end ball still swings out). Note: solver numerics changed again — Native replays recorded on older versions verify against their recording engine.
- Native solver fix: light bodies are no longer launched (1.57 / engine 1.12.9): in the bowling scene a heavy ball wedging into a stacked triangle pyramid at 2.4 px/step once sent a pin flying at 19.6 px/step into the side wall (about 4x the momentum ceiling). Root cause: the contact-point normal velocity read at the first solver iteration had been inflated by warm-start impulses and wedge geometry to vn=−61 (the pin’s true speed was 0.72), and restitution believed it; a 16 px deep overlap also demanded a 12.6 separating velocity from the penetration bias. Fix: restitution now answers the approach velocity captured when the contact is created (the Box2D approach), and the penetration bias is capped at 4 px/step with deep overlap left to positional correction over a few steps. Re-test: peak pin speed 19.6 → 2.5 and the ball ploughs into the stack; a restitution-0.8 drop still rebounds to exactly e²·h (205 px measured), so honest bounces are unaffected. Native solver only — Matter and emitters untouched; note replays recorded on older engines verify against their recording engine.
- Emitters (point spawners) + a snapshot-load id guard (1.56 / engine 1.12.8): (1) New engine
addEmitter: an emitter is a fixed nozzle {position, angle, rate (per second), kind (circle/rect), size, speed, cap, enabled} that spawns one body at the END of every round(60/rate)-th fixed step — the schedule is a pure function of the step index and the sim clock rides snapshots, so recorded replays re-fire identically (bit-identical tests on both backends). Spawned bodies carry an emitter descriptor tag (round-trips through snapshots, so cap counting stays exact after a restore); at the cap the oldest spawned body is recycled, and a hard 1500-body world ceiling stops spawning. The scene format gains an emitters array (max 8, saved/shared/validated with the scene); the lab adds emitters from Scene Properties, lists and selects them, supports canvas pick + drag, and edits position/kind/rate/size/speed/direction (degrees)/cap/enabled in a dedicated panel — emitter changes also ride the replay regions event while recording. (2) An old engine bug fell out of the emitter snapshot tests: loading a snapshot into a FRESH engine and then adding auto-id bodies could reissue a loaded entry’s id and silently evict it from the id map — the body kept simulating but was unfindable and undeletable (five collisions in a row in the failing test). Loads now advance the id sequence past every loaded id, on both backends, guarded by a regression test.
- Domino cascade, static-render signature, trackpad zoom (1.55 / engine 1.12.7): (1) The domino preset froze mid-fall on the default backend — measured cause: sleep caught the slow tipping motion (tile 1 asleep at 42°, tile 2 at 2.6°), and at the default density the strike was a quasi-static lean that passed no momentum. Fix: a new engine
noSleep descriptor (never sleeps on either backend — Matter via sleepThreshold ∞, Native by skipping it in the sleep pass), and the preset's tiles are denser (0.001→0.004), spaced 62→52, air drag 0.002, flagged noSleep — all 11 fall on both backends (~470 steps Matter / ~170 Native, guarded by a standing regression test). (2) A resized static body kept rendering at its old size: the static-layer cache signature held id/pose/type/magnet but no size — it now mixes the bounds extent and vertex count, so a resize rebakes immediately (1 new render check). (3) Trackpad zoom: the wheel handler used the delta's sign only (a fixed ±10% per event), so a pinch or two-finger scroll — dozens of small events per second — jumped in full steps; zoom is now proportional to the actual delta (deltaMode normalised, a dedicated gain for ctrlKey pinches, per-event clamping), with a mouse notch still landing near ×1.17 / ×0.85
- Native large-scene robustness (1.43): fixed Native crashing and freezing mid-run in large scenes (contact clipping no longer fails on exactly-aligned stacks — the 796-body stress scene runs to completion); a smoothed sleep metric settles big piles faster; the scene panel's Engine row now shows the live backend and follows switching
- Native bodies render again (1.42): Native circles now expose a vertices polygon (host contract: every body must expose non-empty vertices), fixing 1.41's grid-only canvas under Native
- Workbench home hub (1.40): the home hub is now a workbench (dark sidebar + scene/preset list + right-hand inspector); the backend interface was formalised into the registry at the same time (see "Backend registry" above)
- Scene import hardening (1.39): import files are capped at 2 MB (including decompressed share links), with budgets of 2000 bodies, 500 constraints, 500 hinges and 20 fluids/winds, and per-field range validation; a bad file is rejected whole with a stated reason and the current scene is untouched
- Smoother pinch zoom (1.38): while the camera moves, the cached layers are blitted with a transform instead of being rebaked every frame — about 81% fewer canvas calls per frame on the Galton board
- Seeds you can see (1.37): Refresh Seed now immediately replays the scene under the new seed — dynamic bodies' starting positions are re-jittered from the seed (a new seed changes where the Galton balls land); Seeded Replay does the same for a hand-typed seed. Same seed, same scene, identical replay
- Random seed (1.36): the scene panel gains a Random Seed — the engine's seeded RNG (present since 1.21) finally has a UI: the seed is saved/shared with the scene and applied on load, Refresh Seed re-rolls it, and the new Random Jitter action kicks every dynamic body from the seeded stream, so the same seed replays the exact same jitter
- Rendering, round two (1.35): the background grid is cached offscreen too — it only changes with the camera but was redrawn every frame (~240 path calls); Galton-board draw calls per frame drop another ~46% after 1.33 (535 → 290)
- Small fix (1.34): the Drag Static Body toggle is no longer disarmed by a stray click on empty canvas — the arm belongs to the body, so re-grabbing the same body still drags it
- Rendering optimization (1.33): the static layer is cached offscreen — in static-heavy scenes like the Galton board, statics are repainted only when the scene changes and blitted each frame; measured canvas draw calls per frame drop by about two thirds
- Buoyancy obeys its preconditions (1.32): buoyancy now uses the body's true submerged area — a body straddling the water's edge only counts the part that is in, and circles and rotated bodies use their real shape; it acts at the centre of buoyancy, so a tilted floater rights itself; and it needs fluid to reach the underside — a light block sitting flush on the pool floor no longer floats up on its own
- Module coupling (1.31): in-fluid drag now also brakes rotation — add water to the Pinwheel and it visibly slows (before, drag only touched translation, so a rotor whose centre barely moved felt nothing). Fluids can have a flow velocity that carries bodies downstream, and wind blowing over a fluid drives a surface current in it — submerged bodies drift with it, and the current shows as arrows in the water
- Pinwheel & gusts (1.30): the new Pinwheel preset has no motor — a wind region covering only the top half of the wheel blows each sail across the top, and the wheel turns. Wind regions gain gusts: the wind breathes stronger and weaker on a cycle (strength and period adjustable in the editor), and the pinwheel surges and settles with it
- Ferris fix & static dragging (1.29): the Ferris wheel's cross no longer folds, its cabins stay upright and the wheel turns at a steady speed. With a static body selected, the properties panel gains a Drag Static Body toggle — when on, you can drag that body directly on the canvas to reposition it, even while running (dynamic bodies still use physics dragging)
- Formulas (1.4.0):
Formulas is a set of pure functions — kinetic energy, momentum, impulse, gravitational force, orbital/escape velocity, Hooke's law, pendulum period, buoyancy, drag, friction, projectile range, centripetal acceleration — plus live measurements on the instance: bodyKineticEnergy() / totalMomentum() / centerOfMass().
- Stability (1.4.0):
PhysicsEngine.validateDescriptor(desc) checks a descriptor and lists problems; position/velocity setters ignore NaN and other non-finite input so one bad value can't poison the world; the maxSpeed option caps velocity so a single wild impulse can't blow the scene apart.
- Interaction:
pick(x, y); beginDrag(body, x, y) / moveDrag(x, y) / endDrag() physics dragging (bodies can be thrown); onCollision((a, b, pair) => …) collision callbacks.
- Mutators:
setVelocity / setPosition / setAngleDeg / setDensity / setFriction / setRestitution / setStatic / setLockRotation / setMagnet / stopMotion — all per body, and all wake sleeping bodies.
4. Conventions
- Units are pixels, y grows downward; angles are radians (except
setAngleDeg, which takes degrees).
- The core does no rendering: read
body.position and body.angle each frame and draw yourself. MotionLab itself is built on this core — its js/physics.js is only a scene-format adapter.
- The same core ships as a standalone package (with docs and tests) that is kept in sync with the in-app copy.
5. PF engine (platform fighter)
Behind PFLab, the PF engine (js/pf/, version PFEngine.VERSION) is layered on PhysicsEngine: the character controller, combat resolution and the deterministic AI state machine only ever call the engine's public API through an adapter. Prefer the PFEngine facade:
import { PFEngine } from './js/pf/pf-lab.js';
// Headless match (no DOM — run it in tools/tests)
const match = PFEngine.createMatch({ ai: 'normal' }); // 'calm' | 'normal' | 'sharp' or an overrides object
match.step({ move: 1, jump: false, attack: false, dash: false }); // feed one intent per step
match.state; // 'fight' | 'over'; match.winner tells who won
match.debugInfo(); // both fighters' state/damage/velocity, AI state, step count, last hit
// Tuning (applies to the shared tables)
PFEngine.tune({ attack: { damage: 9 } });
- Intent interface: player and AI are symmetric —
{ move: -1|0|1, jump, attack, dash, face }; the last three trigger on the step they are pressed.
- AI profiles:
calm (decides every 16 steps / attack cooldown 48), normal (10/30), sharp (6/18); or pass an overrides object that affects only that AI instance.
- UI shell:
PFEngine.createLab(onExit) returns the same full-screen UI MotionLab uses (the page needs a #pfLab element); enter() opens it, exit() leaves and releases all resources.
- Full documentation (parameter tables and the complete PhysicsEngine API) lives in the repo at
docs/DEVELOPER-EN.md, readable directly on GitHub.