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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
94 changes: 80 additions & 14 deletions bun.lock

Large diffs are not rendered by default.

18 changes: 9 additions & 9 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,19 +29,19 @@
"urdf-loader": "^0.13.1"
},
"peerDependencies": {
"@pascal-app/core": ">=1.0.0-beta.4 <1.0.0",
"@pascal-app/editor": ">=1.0.0-beta.4 <1.0.0",
"@pascal-app/viewer": ">=1.0.0-beta.4 <1.0.0",
"@pascal-app/core": ">=1.0.0-beta.4 <2.0.0",
"@pascal-app/editor": ">=1.0.0-beta.4 <2.0.0",
"@pascal-app/viewer": ">=1.0.0-beta.4 <2.0.0",
"@react-three/fiber": "^9",
"react": "^18 || ^19",
"three": "^0.185",
"three": "^0.185 || ^0.186",
"zod": "^4",
"zustand": "^5"
},
"devDependencies": {
"@pascal-app/core": "1.0.0-beta.4",
"@pascal-app/editor": "1.0.0-beta.4",
"@pascal-app/viewer": "1.0.0-beta.4",
"@pascal-app/core": "1.0.3",
"@pascal-app/editor": "1.0.3",
"@pascal-app/viewer": "1.0.3",
"@react-three/fiber": "^9.5.0",
"@types/bun": "^1.3.5",
"@types/blob-stream": "^0.1.33",
Expand All @@ -50,10 +50,10 @@
"@types/pdfkit": "^0.17.3",
"@types/react": "^19.2.2",
"@types/react-dom": "^19.2.2",
"@types/three": "^0.185.0",
"@types/three": "0.184.1",
"react": "^19.2.4",
"react-dom": "^19.2.4",
"three": "^0.185.0",
"three": "0.186.0",
"typescript": "6.0.3",
"zod": "^4.3.6",
"zustand": "^5.0.11"
Expand Down
43 changes: 43 additions & 0 deletions src/animation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,49 @@ describe('Articraft GLB animation export', () => {
expect(fixedTarget.position.toArray()).toEqual([0, 0, 0])
})

test('bakes a continuous joint as a full turn over the loop, seamless at the seam', () => {
const root = new Group()
const wheelTarget = new Group()
markArticraftJointTarget(wheelTarget, 'wheel_spin')
root.add(wheelTarget)
const node = ArticraftAssetNode.parse({
id: 'articraft_spin_test',
catalogId: 'spin-test',
title: 'Spin test',
source: 'generated',
artifact: { format: 'usdz', url: 'https://assets.example/model.usdz' },
joints: [
{
name: 'wheel_spin',
type: 'continuous',
parent: 'base',
child: 'wheel',
axis: [0, 1, 0],
origin: { xyz: [0, 0, 0], rpy: [0, 0, 0] },
limits: null,
},
],
attribution: {
creator: 'Articraft authors',
license: 'CC-BY-4.0',
sourceUrl: 'https://example.com/source',
},
})

const track = bakeArticraftAnimation(node, root)?.tracks[0]
expect(track?.ValueTypeName).toBe('quaternion')
const rest = new Quaternion()
const at = (sample: number) =>
new Quaternion().fromArray(Array.from(track?.values.slice(sample * 4, sample * 4 + 4) ?? []))
// 32 samples per loop: a quarter loop is a quarter turn, half a loop half a turn.
expect(at(8).angleTo(rest)).toBeCloseTo(Math.PI / 2, 6)
expect(at(16).angleTo(rest)).toBeCloseTo(Math.PI, 6)
expect(at(24).angleTo(rest)).toBeCloseTo(Math.PI / 2, 6)
expect(at(32).angleTo(rest)).toBeCloseTo(0, 6)
const quarter = new Quaternion().setFromAxisAngle(new Vector3(0, 1, 0), Math.PI / 2)
expect(at(8).angleTo(quarter)).toBeLessThan(1e-3)
})

test('does not emit an animation without a resolved movable joint target', () => {
const node = ArticraftAssetNode.parse({
id: 'articraft_static_test',
Expand Down
7 changes: 3 additions & 4 deletions src/animation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,11 @@ import {
Vector3,
VectorKeyframeTrack,
} from 'three'
import { motionValueAtTime } from './motion'
import { MOTION_PERIOD_SECONDS, motionValueAtTime } from './motion'
import type { ArticraftAssetNode } from './schema'
import type { ArticraftJoint } from './types'

const JOINT_TARGET_KEY = '__articraftJointTarget'
const MOTION_DURATION_SECONDS = (Math.PI * 2) / 1.4
const MOTION_SAMPLES = 32

type JointTargetMarker = {
Expand All @@ -36,7 +35,7 @@ export function bakeArticraftAnimation(
const tracks = [] as Array<QuaternionKeyframeTrack | VectorKeyframeTrack>
const times = Array.from(
{ length: MOTION_SAMPLES + 1 },
(_, step) => (step / MOTION_SAMPLES) * MOTION_DURATION_SECONDS,
(_, step) => (step / MOTION_SAMPLES) * MOTION_PERIOD_SECONDS,
)
let motionIndex = 0

Expand Down Expand Up @@ -66,7 +65,7 @@ export function bakeArticraftAnimation(
}

if (tracks.length === 0) return null
const clip = new AnimationClip(`${node.id}: loop`, MOTION_DURATION_SECONDS, tracks)
const clip = new AnimationClip(`${node.id}: loop`, MOTION_PERIOD_SECONDS, tracks)
clip.userData = { loop: true }
return clip
}
Expand Down
22 changes: 22 additions & 0 deletions src/joint-controls.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { describe, expect, test } from 'bun:test'
import { runProbe } from './test-support/host-stubs'

describe('Articraft inspector', () => {
test('every slider drag commits as one undo step (restoreOnCommit left on)', () => {
const sliders = runProbe<Array<{ label: string; restoreOnCommit: unknown }>>(
new URL('./test-support/joint-controls-probe.tsx', import.meta.url).pathname,
)
expect(sliders.map((slider) => slider.label)).toEqual([
'Scale',
'Position X',
'Position Y',
'Position Z',
'Rotation X',
'Rotation Y',
'Rotation Z',
'lid',
'drawer',
])
expect(sliders.filter((slider) => slider.restoreOnCommit === false)).toEqual([])
})
})
4 changes: 0 additions & 4 deletions src/joint-controls.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,6 @@ export default function ArticraftJointControls() {
min={0.05}
onChange={setScale}
precision={2}
restoreOnCommit={false}
step={0.05}
value={node.scale}
/>
Expand All @@ -85,7 +84,6 @@ export default function ArticraftJointControls() {
min={-100}
onChange={(value) => setVector('position', index, value)}
precision={2}
restoreOnCommit={false}
step={0.05}
unit="m"
value={node.position[index]}
Expand All @@ -99,7 +97,6 @@ export default function ArticraftJointControls() {
min={-180}
onChange={(value) => setVector('rotation', index, value)}
precision={1}
restoreOnCommit={false}
step={1}
unit="°"
value={toDegrees(node.rotation[index])}
Expand All @@ -126,7 +123,6 @@ export default function ArticraftJointControls() {
min={displayRange[0]}
onChange={(value) => setJoint(joint, angular ? toRadians(value) : value)}
precision={angular ? 1 : 3}
restoreOnCommit={false}
step={angular ? 1 : 0.001}
unit={angular ? '°' : 'm'}
value={angular
Expand Down
12 changes: 12 additions & 0 deletions src/motion.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,18 @@ describe('persistent articulation motion', () => {
expect(motionValueAtTime(hinge, 0, Math.PI / 2 / 1.4)).toBeCloseTo(1.5, 8)
})

test('spins a continuous joint one full turn per loop instead of rocking it', () => {
const wheel: ArticraftJoint = { ...hinge, type: 'continuous', limits: null }
const period = (Math.PI * 2) / 1.4
const samples = Array.from({ length: 9 }, (_, step) =>
motionValueAtTime(wheel, 0, (step / 8) * period),
)
for (const [step, value] of samples.entries()) {
expect(value).toBeCloseTo((step / 8) * Math.PI * 2, 8)
}
expect(motionValueAtTime(wheel, 0, period * 3)).toBeCloseTo(Math.PI * 6, 8)
})

test('provides a bounded fallback for joints without limits', () => {
expect(motionRange({ ...hinge, type: 'continuous', limits: null })).toEqual([
-Math.PI,
Expand Down
9 changes: 8 additions & 1 deletion src/motion.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,11 @@ export function usePrefersReducedMotion(): boolean {
)
}

/** Motion rate in radians per second: the sweep's angular frequency, and how fast continuous joints turn. */
export const MOTION_RATE = 1.4
/** One sweep of the limited joints, and one full turn of the continuous ones. */
export const MOTION_PERIOD_SECONDS = (Math.PI * 2) / MOTION_RATE

export function motionRange(joint: ArticraftJoint): [number, number] {
if (joint.limits && joint.limits.upper > joint.limits.lower) {
return [joint.limits.lower, joint.limits.upper]
Expand All @@ -51,6 +56,8 @@ export function motionValueAtTime(
index: number,
elapsedSeconds: number,
): number {
// A wheel, fan or knob turns without end; sweeping it back and forth over ±π rocks it instead.
if (joint.type === 'continuous') return elapsedSeconds * MOTION_RATE
const hasLimits = joint.limits && joint.limits.upper > joint.limits.lower
const lower = hasLimits
? joint.limits!.lower
Expand All @@ -62,6 +69,6 @@ export function motionValueAtTime(
: joint.type === 'prismatic'
? 1
: Math.PI
const progress = (Math.sin(elapsedSeconds * 1.4 + index * 0.7) + 1) / 2
const progress = (Math.sin(elapsedSeconds * MOTION_RATE + index * 0.7) + 1) / 2
return lower + (upper - lower) * progress
}
37 changes: 37 additions & 0 deletions src/package.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { describe, expect, test } from 'bun:test'
import { readFileSync } from 'node:fs'

const manifest = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')) as {
peerDependencies: Record<string, string>
}

// The host ships Pascal 1.x on three 0.186 (@pascal-app/core 1.0.3 pins `three ^0.186`);
// strict installs refuse the plugin when a peer range excludes them.
const shippedHost = {
'@pascal-app/core': ['1.0.0-beta.4', '1.0.3', '1.9.0'],
'@pascal-app/editor': ['1.0.0-beta.4', '1.0.3', '1.9.0'],
'@pascal-app/viewer': ['1.0.0-beta.4', '1.0.3', '1.9.0'],
three: ['0.185.0', '0.186.0', '0.186.1'],
} as const

describe('peer ranges', () => {
for (const [name, versions] of Object.entries(shippedHost)) {
test(`${name} accepts ${versions.join(', ')}`, () => {
const range = manifest.peerDependencies[name]
expect(range).toBeDefined()
for (const version of versions) {
expect({ version, accepted: Bun.semver.satisfies(version, range ?? '') }).toEqual({
version,
accepted: true,
})
}
})
}

test('does not claim the next major', () => {
for (const name of ['@pascal-app/core', '@pascal-app/editor', '@pascal-app/viewer']) {
expect(Bun.semver.satisfies('2.0.0', manifest.peerDependencies[name] ?? '')).toBe(false)
}
expect(Bun.semver.satisfies('0.187.0', manifest.peerDependencies.three ?? '')).toBe(false)
})
})
26 changes: 26 additions & 0 deletions src/test-support/host-stubs.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { plugin } from 'bun'

/**
* Replaces the host packages (`@pascal-app/core`, `editor`, `viewer`) with
* stubs for a probe script. Module stubs are process-global, so probes run in
* a child process (see `runProbe`) and never inside the test runner.
*/
export function stubHostModules(stubs: Record<string, Record<string, unknown>>): void {
plugin({
name: 'articraft-host-stubs',
setup(build) {
for (const [specifier, exports] of Object.entries(stubs)) {
build.module(specifier, () => ({ exports, loader: 'object' }))
}
},
})
}

/** Runs a probe script in a child process and returns the JSON it prints. */
export function runProbe<T>(probe: string): T {
const result = Bun.spawnSync([process.execPath, probe], { stderr: 'pipe', stdout: 'pipe' })
if (result.exitCode !== 0) {
throw new Error(`${probe} failed:\n${result.stderr.toString()}`)
}
return JSON.parse(result.stdout.toString()) as T
}
61 changes: 61 additions & 0 deletions src/test-support/joint-controls-probe.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import { renderToStaticMarkup } from 'react-dom/server'
import { stubHostModules } from './host-stubs'

// Renders the Articraft inspector against stubbed host packages and prints
// the props every SliderControl received.
const NODE_ID = 'articraft_probe'
const node = {
id: NODE_ID,
type: 'articraft:asset',
position: [0, 0, 0],
rotation: [0, 0, 0],
scale: 1,
joints: [
{
name: 'lid',
type: 'revolute',
parent: 'base',
child: 'lid',
axis: [0, 0, 1],
origin: { xyz: [0, 0, 0], rpy: [0, 0, 0] },
limits: { lower: 0, upper: 1.5 },
},
{
name: 'drawer',
type: 'prismatic',
parent: 'base',
child: 'drawer',
axis: [1, 0, 0],
origin: { xyz: [0, 0, 0], rpy: [0, 0, 0] },
limits: { lower: 0, upper: 0.4 },
},
],
jointValues: {},
motionEnabled: false,
attribution: { creator: 'Articraft authors', license: 'CC-BY-4.0', sourceUrl: 'https://x.test' },
}
const sliders: Array<{ label: string; restoreOnCommit: unknown }> = []
const state = { nodes: { [NODE_ID]: node }, updateNode: () => undefined }

stubHostModules({
'@pascal-app/core': {
useScene: Object.assign((select: (value: typeof state) => unknown) => select(state), {
getState: () => state,
}),
},
'@pascal-app/editor': {
PanelSection: ({ children }: { children?: unknown }) => children,
SliderControl: (props: { label: string; restoreOnCommit?: boolean }) => {
sliders.push({ label: props.label, restoreOnCommit: props.restoreOnCommit ?? 'default' })
return null
},
},
'@pascal-app/viewer': {
useViewer: (select: (value: unknown) => unknown) =>
select({ selection: { selectedIds: [NODE_ID] } }),
},
})

const { default: ArticraftJointControls } = await import('../joint-controls')
renderToStaticMarkup(<ArticraftJointControls />)
console.log(JSON.stringify(sliders))
Loading