roamwright 0.4.0 → 0.20.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (139) hide show
  1. package/CONTRIBUTING.md +3 -1
  2. package/README.md +11 -34
  3. package/geometry/bedding.js +141 -0
  4. package/geometry/builder-cells.js +42 -0
  5. package/geometry/builder-frame.js +47 -0
  6. package/geometry/builder.js +189 -177
  7. package/geometry/cell-mask.js +25 -0
  8. package/geometry/creased-sheet.js +34 -34
  9. package/geometry/ear.js +36 -36
  10. package/geometry/erosion.js +65 -42
  11. package/geometry/face-grid.js +65 -65
  12. package/geometry/foliage.js +10 -10
  13. package/geometry/hair-gathers.js +41 -41
  14. package/geometry/hair-locks.js +41 -41
  15. package/geometry/hair-patch.js +18 -18
  16. package/geometry/hair-shell.js +31 -31
  17. package/geometry/head-profile.js +15 -15
  18. package/geometry/head-shape.js +77 -77
  19. package/geometry/heightfield.js +27 -18
  20. package/geometry/index-parts.js +2 -2
  21. package/geometry/instance-visibility.js +12 -12
  22. package/geometry/instances.js +15 -15
  23. package/geometry/outline-grid.js +7 -7
  24. package/geometry/part-ranges.js +3 -3
  25. package/geometry/path-field.js +63 -33
  26. package/geometry/placement.js +52 -52
  27. package/geometry/point-buckets.js +50 -0
  28. package/geometry/primitives.js +63 -47
  29. package/geometry/sagging-tube.js +27 -27
  30. package/geometry/sampled-surface.js +109 -77
  31. package/geometry/scatter-grid.js +46 -6
  32. package/geometry/sculpt.js +93 -93
  33. package/geometry/shore-grid.js +77 -34
  34. package/geometry/strata-field.js +92 -92
  35. package/geometry/strata-tiles.js +91 -91
  36. package/geometry/stream.js +70 -48
  37. package/geometry/terrain-chunks.js +87 -82
  38. package/geometry/terrain-extension.js +6 -6
  39. package/index.js +5 -0
  40. package/math/cell-edge.js +16 -16
  41. package/math/cell-key.js +6 -0
  42. package/math/circle-clearances.js +19 -0
  43. package/math/cloth-textures.js +6 -6
  44. package/math/cloud-textures.js +20 -20
  45. package/math/color.js +14 -14
  46. package/math/curve.js +22 -22
  47. package/math/mountain-ranges.js +216 -165
  48. package/math/noise.js +101 -49
  49. package/math/particle-noise.js +28 -28
  50. package/math/periodic.js +5 -5
  51. package/math/random.js +24 -15
  52. package/math/rectangles.js +52 -0
  53. package/math/rock-texture.js +7 -7
  54. package/math/scalar.js +5 -5
  55. package/math/surface-textures.js +54 -54
  56. package/motion/arm-reach.js +24 -24
  57. package/motion/ballistic-arc.js +11 -0
  58. package/motion/biped-cycle.js +44 -0
  59. package/motion/biped-leg.js +37 -0
  60. package/motion/biped-stride.js +98 -122
  61. package/motion/contact-transition.js +33 -0
  62. package/motion/crowd-alarms.js +39 -39
  63. package/motion/crowd-routine.js +94 -65
  64. package/motion/daily-clock.js +9 -9
  65. package/motion/deck-surface.js +38 -0
  66. package/motion/ground-lookahead.js +5 -5
  67. package/motion/instance-sight.js +8 -8
  68. package/motion/player.js +36 -28
  69. package/motion/quadruped.js +155 -155
  70. package/motion/spaces.js +32 -32
  71. package/motion/weather.js +73 -24
  72. package/motion/wind.js +32 -13
  73. package/package.json +7 -3
  74. package/rendering/caster-motion.js +5 -5
  75. package/rendering/cell-lod.js +138 -82
  76. package/rendering/cloud-dome.js +28 -28
  77. package/rendering/cloud-field.js +2 -2
  78. package/rendering/compilation-schedule.js +68 -11
  79. package/rendering/contact-shadows.js +2 -2
  80. package/rendering/context.js +12 -0
  81. package/rendering/crowd-skinning.js +13 -13
  82. package/rendering/crust.js +18 -12
  83. package/rendering/daylight.js +3 -3
  84. package/rendering/detail-range.js +28 -0
  85. package/rendering/dispose-meshes.js +18 -0
  86. package/rendering/dof.js +9 -9
  87. package/rendering/eye-adapt.js +14 -14
  88. package/rendering/far-shadow.js +8 -8
  89. package/rendering/flocks.js +78 -78
  90. package/rendering/garment-material.js +17 -17
  91. package/rendering/glow-lines.js +13 -13
  92. package/rendering/hair-strands.js +20 -20
  93. package/rendering/height-probe.js +149 -19
  94. package/rendering/label-layout.js +46 -0
  95. package/rendering/label-range.js +38 -0
  96. package/rendering/light-budget.js +52 -52
  97. package/rendering/light-shafts.js +23 -23
  98. package/rendering/local-lights.js +15 -4
  99. package/rendering/material-lod.js +49 -49
  100. package/rendering/particle-emitters.js +90 -90
  101. package/rendering/particles.js +78 -67
  102. package/rendering/piece-batch.js +17 -6
  103. package/rendering/planar-reflection.js +38 -38
  104. package/rendering/post-shaders.js +17 -13
  105. package/rendering/post.js +71 -71
  106. package/rendering/rain-streaks.js +67 -0
  107. package/rendering/road-surface.js +11 -11
  108. package/rendering/sea-shaders.js +11 -11
  109. package/rendering/shader-warmup.js +29 -16
  110. package/rendering/shadow-alignment.js +4 -4
  111. package/rendering/shadow-depth.js +7 -7
  112. package/rendering/sky-occlusion.js +16 -16
  113. package/rendering/sky.js +16 -6
  114. package/rendering/stage-lights.js +6 -6
  115. package/rendering/static-point-shadow.js +3 -3
  116. package/rendering/still-casters.js +1 -1
  117. package/rendering/strata-material.js +10 -10
  118. package/rendering/stream-flow.js +10 -10
  119. package/rendering/taa.js +26 -26
  120. package/rendering/talus.js +15 -15
  121. package/rendering/terrain-rock.js +7 -7
  122. package/rendering/texture-fills.js +8 -8
  123. package/rendering/textures.js +28 -28
  124. package/rendering/wakes.js +24 -24
  125. package/rendering/water-material.js +36 -23
  126. package/rendering/world-matrices.js +38 -38
  127. package/runtime/diagnostic-log.js +2 -2
  128. package/runtime/first-use.js +33 -28
  129. package/runtime/frame-pacing.js +33 -0
  130. package/runtime/gpu-timing.js +7 -7
  131. package/runtime/grid-cache.js +1 -1
  132. package/runtime/grid-rows.js +44 -5
  133. package/runtime/hand-over.js +41 -23
  134. package/runtime/pool.js +58 -16
  135. package/runtime/quality-fit.js +1 -1
  136. package/runtime/search.js +22 -22
  137. package/runtime/spatial-audio.js +13 -13
  138. package/runtime/withdrawable-task.js +35 -0
  139. package/runtime/worker.js +7 -0
@@ -10,41 +10,41 @@ import { clamp } from '../math/scalar.js';
10
10
  export function createArmReach({ elbowDirection, minBend, maxBend }) {
11
11
  const _to = new THREE.Vector3(), // scratch
12
12
  _end = new THREE.Vector3(),
13
- _g = new THREE.Vector3(),
13
+ localGrip = new THREE.Vector3(),
14
14
  _elbow = new THREE.Vector3(),
15
15
  _want = new THREE.Vector3(),
16
- _a = new THREE.Vector3(),
17
- _b = new THREE.Vector3(),
16
+ armDirection = new THREE.Vector3(),
17
+ targetDirection = new THREE.Vector3(),
18
18
  _size = new THREE.Vector3(),
19
19
  _hand = new THREE.Matrix4(),
20
20
  _item = new THREE.Matrix4(),
21
21
  _inv = new THREE.Matrix4(),
22
- _q = new THREE.Quaternion(),
22
+ shoulderRotation = new THREE.Quaternion(),
23
23
  _swivel = new THREE.Quaternion(),
24
- _x = new THREE.Quaternion(),
24
+ elbowRotation = new THREE.Quaternion(),
25
25
  NONE = new THREE.Quaternion(),
26
26
  X_AXIS = new THREE.Vector3(1, 0, 0);
27
27
 
28
- // Turns the upper arm `arm` and the forearm `fore` of one side (s: 1 the right, -1 the left) by weight k toward the pose in which
28
+ // Turns the upper arm `arm` and the forearm `fore` of one side (side is 1 for right, −1 for left) by the given weight toward the pose in which
29
29
  // the point `grip` (in the own space of the bone of what the hand `hand` holds, taken at its place `rest` and unturned)
30
30
  // comes to `target` in the world. The arm's parent's world matrix must be current.
31
- function reachArm(arm, fore, hand, rest, grip, target, s, k) {
32
- if (k <= 0) return;
31
+ function reachArm(arm, fore, hand, rest, grip, target, side, weight) {
32
+ if (weight <= 0) return;
33
33
  // the target from the shoulder, in the frame the arm hangs in
34
34
  _inv.copy(arm.parent.matrixWorld).invert();
35
35
  _to.copy(target).applyMatrix4(_inv).sub(arm.position);
36
36
  // what the hand holds at `grip`, in the forearm's frame: through the hand as it is turned, and the held bone as it rests
37
37
  hand.updateMatrix();
38
38
  _item.compose(rest, NONE, _size.setScalar(1 / hand.scale.x)); // what is held keeps its own size in a larger hand, shown or not
39
- _g.copy(grip).applyMatrix4(_item).applyMatrix4(_hand.copy(hand.matrix));
39
+ localGrip.copy(grip).applyMatrix4(_item).applyMatrix4(_hand.copy(hand.matrix));
40
40
  // the elbow's bend that puts the grip as far from the shoulder as the target is (or as far as the arm reaches)
41
41
  const l1 = -fore.position.y,
42
- rho = Math.hypot(_g.y, _g.z),
43
- phi = Math.atan2(_g.z, _g.y);
42
+ rho = Math.hypot(localGrip.y, localGrip.z),
43
+ phi = Math.atan2(localGrip.z, localGrip.y);
44
44
  if (l1 <= 0 || rho <= Number.EPSILON) return;
45
45
  const far = _to.length(),
46
- c = clamp((_g.x * _g.x + l1 * l1 + rho * rho - far * far) / (2 * l1 * rho), -1, 1),
47
- turn = Math.acos(c);
46
+ cosReachAngle = clamp((localGrip.x * localGrip.x + l1 * l1 + rho * rho - far * far) / (2 * l1 * rho), -1, 1),
47
+ turn = Math.acos(cosReachAngle);
48
48
  let bend = turn - phi;
49
49
  bend = Math.atan2(Math.sin(bend), Math.cos(bend));
50
50
  if (bend > maxBend || bend < minBend) {
@@ -54,21 +54,21 @@ export function createArmReach({ elbowDirection, minBend, maxBend }) {
54
54
  bend = clamp(bend, minBend, maxBend);
55
55
  // the end of the arm so bent, in the upper arm's own frame, turned onto the target, then swung about the line to the target
56
56
  // until the elbow is as near as it gets to where an elbow goes
57
- _x.setFromAxisAngle(X_AXIS, bend);
58
- _end.copy(_g).applyQuaternion(_x).add(fore.position);
59
- _q.setFromUnitVectors(_a.copy(_end).normalize(), _b.copy(_to).normalize());
60
- _elbow.copy(fore.position).applyQuaternion(_q);
61
- _want.set(s * elbowDirection[0], elbowDirection[1], elbowDirection[2]);
62
- _elbow.addScaledVector(_b, -_elbow.dot(_b));
63
- _want.addScaledVector(_b, -_want.dot(_b));
57
+ elbowRotation.setFromAxisAngle(X_AXIS, bend);
58
+ _end.copy(localGrip).applyQuaternion(elbowRotation).add(fore.position);
59
+ shoulderRotation.setFromUnitVectors(armDirection.copy(_end).normalize(), targetDirection.copy(_to).normalize());
60
+ _elbow.copy(fore.position).applyQuaternion(shoulderRotation);
61
+ _want.set(side * elbowDirection[0], elbowDirection[1], elbowDirection[2]);
62
+ _elbow.addScaledVector(targetDirection, -_elbow.dot(targetDirection));
63
+ _want.addScaledVector(targetDirection, -_want.dot(targetDirection));
64
64
  if (_elbow.lengthSq() > 1e-10 && _want.lengthSq() > 1e-10) {
65
65
  _elbow.normalize();
66
66
  _want.normalize();
67
- const swing = Math.atan2(_a.crossVectors(_elbow, _want).dot(_b), _elbow.dot(_want));
68
- _q.premultiply(_swivel.setFromAxisAngle(_b, swing));
67
+ const swing = Math.atan2(armDirection.crossVectors(_elbow, _want).dot(targetDirection), _elbow.dot(_want));
68
+ shoulderRotation.premultiply(_swivel.setFromAxisAngle(targetDirection, swing));
69
69
  }
70
- arm.quaternion.slerp(_q, k);
71
- fore.rotation.x += (bend - fore.rotation.x) * k;
70
+ arm.quaternion.slerp(shoulderRotation, weight);
71
+ fore.rotation.x += (bend - fore.rotation.x) * weight;
72
72
  }
73
73
  return reachArm;
74
74
  }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Position between two endpoints at a fraction of the flight duration.
3
+ * Coordinates use positive y up and gravity is a positive acceleration.
4
+ * The destination may move between samples. The supplied vector is reused.
5
+ */
6
+ export function sampleBallisticArc(position, from, to, phase, duration, gravity = 9.81) {
7
+ const progress = Math.min(1, Math.max(0, phase));
8
+ position.lerpVectors(from, to, progress);
9
+ position.y += 0.5 * gravity * duration * duration * progress * (1 - progress);
10
+ return position;
11
+ }
@@ -0,0 +1,44 @@
1
+ import { sstep } from '../math/scalar.js';
2
+ import { ankleOffset, solePitch, solveBipedLeg } from './biped-leg.js';
3
+
4
+ /**
5
+ * Sample either a live or baked stride without frame history. Rig lengths, hip
6
+ * height, stride (distance per complete cycle), swing clearance and standing
7
+ * stagger are in the same units. Grade is rise per unit forward; duty is the
8
+ * fraction each foot supports the body. Angles rotate about +X, forward is +Z.
9
+ * The result and both legs are reused until the next call.
10
+ */
11
+ export function createBipedCycle({ rig, foot }) {
12
+ const leg = () => ({ thigh: 0, knee: 0, foot: 0, forward: 0, height: 0 });
13
+ const pose = { hipHeight: 0, left: leg(), right: leg() };
14
+ const ankle = [0, 0], angles = [0, 0];
15
+ const reach = rig.thigh + rig.shin - 0.0005;
16
+
17
+ function target(leg, phase, stride, duty, clearance, grade, slope, roll, stagger) {
18
+ const swing = Math.max(0, (phase - duty) / (1 - duty));
19
+ // Match ground velocity on both sides of the swing boundary.
20
+ const track = stagger + stride * (duty / 2 - phase + sstep(0, 1, swing));
21
+ const pitch = roll * solePitch(foot, phase, duty, false, foot.heelStrike, foot.pushOff);
22
+ ankleOffset(ankle, rig, pitch, slope);
23
+ const arch = Math.sin(Math.PI * swing);
24
+ leg.forward = track + ankle[0];
25
+ leg.height = grade * track + ankle[1] + clearance * arch * arch;
26
+ leg.foot = pitch + slope;
27
+ pose.hipHeight = Math.min(pose.hipHeight, leg.height + Math.sqrt(Math.max(0, reach * reach - leg.forward * leg.forward)));
28
+ }
29
+ function solve(leg) {
30
+ solveBipedLeg(angles, rig, leg.forward, leg.height - pose.hipHeight);
31
+ leg.thigh = angles[0];
32
+ leg.knee = angles[1];
33
+ leg.foot -= leg.thigh + leg.knee;
34
+ }
35
+ return function sample(phase, stride, duty, clearance, grade, hipHeight, roll = 1, stagger = 0) {
36
+ const cyclePhase = phase - Math.floor(phase), slope = -Math.atan(grade);
37
+ pose.hipHeight = hipHeight;
38
+ target(pose.left, cyclePhase, stride, duty, clearance, grade, slope, roll, -stagger);
39
+ target(pose.right, (cyclePhase + 0.5) % 1, stride, duty, clearance, grade, slope, roll, stagger);
40
+ solve(pose.left);
41
+ solve(pose.right);
42
+ return pose;
43
+ };
44
+ }
@@ -0,0 +1,37 @@
1
+ import { clamp, lerp, sstep } from '../math/scalar.js';
2
+
3
+ // Two-bone leg from hip to ankle in the fore-and-aft plane: for an ankle at (forward, up) from the hip, the thigh's and the
4
+ // knee's rotation, written into out.
5
+ export function solveBipedLeg(out, rig, forward, up, minReach = Math.abs(rig.thigh - rig.shin)) {
6
+ const reach = clamp(Math.sqrt(forward * forward + up * up), minReach, rig.thigh + rig.shin - 1e-4),
7
+ bend = Math.acos(clamp((reach * reach - rig.thigh * rig.thigh - rig.shin * rig.shin) / (2 * rig.thigh * rig.shin), -1, 1));
8
+ out[0] = -(Math.atan2(forward, -up) + Math.atan2(rig.shin * Math.sin(bend), rig.thigh + rig.shin * Math.cos(bend)));
9
+ out[1] = bend;
10
+ }
11
+ // The pitch of a foot's sole (toes down is more) at share u of its stride: it lands on its heel with the toes up by `strike`,
12
+ // lies flat while the body passes over it, rolls up onto its toes until the heel has risen by `push`, and in the air comes
13
+ // round from toes down to toes up. A step backwards (`back`) does it the other way round.
14
+ export function solePitch(foot, u, duty, back, strike, push) {
15
+ const planted = u < duty;
16
+ let s = planted ? u / duty : (u - duty) / (1 - duty);
17
+ if (back) s = 1 - s;
18
+ return planted ? push * sstep(foot.riseAt, 1, s) - strike * sstep(foot.flatAt, 0, s) : lerp(push, -strike, sstep(0.08, 0.8, s));
19
+ }
20
+ // Where a foot's ankle is from the point of its sole under the ankle when it lies flat, written into out (forward, up), for a
21
+ // sole pitched by `pitch` (about the ball of the foot with the heel up, about the heel with the toes up) on ground that itself
22
+ // pitches by `slope` (both radians, toes down is more).
23
+ export function ankleOffset(out, rig, pitch, slope) {
24
+ const cosPitch = Math.cos(pitch),
25
+ sinPitch = Math.sin(pitch),
26
+ forward = pitch >= 0 ? rig.ballOffset - rig.ballOffset * cosPitch + rig.ankleHeight * sinPitch : -rig.heelOffset + rig.heelOffset * cosPitch + rig.ankleHeight * sinPitch,
27
+ up = pitch >= 0 ? rig.ballOffset * sinPitch + rig.ankleHeight * cosPitch : -rig.heelOffset * sinPitch + rig.ankleHeight * cosPitch;
28
+ if (slope) {
29
+ const cosSlope = Math.cos(slope),
30
+ sinSlope = Math.sin(slope);
31
+ out[0] = forward * cosSlope + up * sinSlope;
32
+ out[1] = up * cosSlope - forward * sinSlope;
33
+ } else {
34
+ out[0] = forward;
35
+ out[1] = up;
36
+ }
37
+ }
@@ -1,6 +1,17 @@
1
+ /**
2
+ * Stateful foot placement and leg poses for bipeds moving over sampled ground.
3
+ * @module
4
+ */
5
+
1
6
  import { TAU, clamp, lerp, sstep } from '../math/scalar.js';
7
+ import { ankleOffset, solePitch, solveBipedLeg } from './biped-leg.js';
2
8
 
3
- /** Create one stride solver for a rig, ground sampler and motion profile. */
9
+ /**
10
+ * Create a stride solver for a rig and motion profile. The ground callback takes
11
+ * world X/Z coordinates and returns the surface height. Pass elapsed seconds to
12
+ * the solver on each update. It stores foot contacts on the actor and reuses the
13
+ * returned pose, so copy any values needed after the next call.
14
+ */
4
15
  export function createBipedStride({ rig, foot, pace, ground }) {
5
16
  const reach = rig.thigh + rig.shin - 0.0005;
6
17
  const _leg = [0, 0],
@@ -30,67 +41,32 @@ export function createBipedStride({ rig, foot, pace, ground }) {
30
41
  roll: 0,
31
42
  };
32
43
 
33
- // Two-bone leg from hip to ankle in the fore-and-aft plane: for an ankle at (forward, up) from the hip, the thigh's and the
34
- // knee's rotation, written into _leg.
35
- function solveLeg(forward, up) {
36
- const D = clamp(Math.sqrt(forward * forward + up * up), 0.3, rig.thigh + rig.shin - 1e-4),
37
- bend = Math.acos(clamp((D * D - rig.thigh * rig.thigh - rig.shin * rig.shin) / (2 * rig.thigh * rig.shin), -1, 1));
38
- _leg[0] = -(Math.atan2(forward, -up) + Math.atan2(rig.shin * Math.sin(bend), rig.thigh + rig.shin * Math.cos(bend)));
39
- _leg[1] = bend;
40
- }
41
- // The pitch of a foot's sole (toes down is more) at share u of its stride: it lands on its heel with the toes up by `strike`,
42
- // lies flat while the body passes over it, rolls up onto its toes until the heel has risen by `push`, and in the air comes
43
- // round from toes down to toes up. A step backwards (`back`) does it the other way round.
44
- function soleAt(u, duty, back, strike, push) {
45
- const planted = u < duty;
46
- let s = planted ? u / duty : (u - duty) / (1 - duty);
47
- if (back) s = 1 - s;
48
- return planted ? push * sstep(foot.riseAt, 1, s) - strike * sstep(foot.flatAt, 0, s) : lerp(push, -strike, sstep(0.08, 0.8, s));
49
- }
50
- // Where a foot's ankle is from the point of its sole under the ankle when it lies flat, written into _ankle (forward, up), for a
51
- // sole pitched by `pitch` (about the ball of the foot with the heel up, about the heel with the toes up) on ground that itself
52
- // pitches by `slope` (both radians, toes down is more).
53
- function ankleAt(pitch, slope) {
54
- const c = Math.cos(pitch),
55
- s = Math.sin(pitch),
56
- forward = pitch >= 0 ? rig.ballOffset - rig.ballOffset * c + rig.ankleHeight * s : -rig.heelOffset + rig.heelOffset * c + rig.ankleHeight * s,
57
- up = pitch >= 0 ? rig.ballOffset * s + rig.ankleHeight * c : -rig.heelOffset * s + rig.ankleHeight * c;
58
- if (slope) {
59
- const cs = Math.cos(slope),
60
- ss = Math.sin(slope);
61
- _ankle[0] = forward * cs + up * ss;
62
- _ankle[1] = up * cs - forward * ss;
63
- } else {
64
- _ankle[0] = forward;
65
- _ankle[1] = up;
66
- }
67
- }
68
44
  // One foot (0 the left, 1 the right) at share u of its stride, kept in a.feet as how far forward of the middle it is and how
69
45
  // high. Striding, a foot on the ground stays where it was set down, so it is carried back as the body goes forward, and a foot
70
46
  // in the air swings from where it left the ground to where it will land; `drift` makes it leave and meet the ground moving as
71
47
  // the ground does. Standing, a foot that is not where the pose wants it steps there (`mayStep`: one foot at a time).
72
- function footAt(a, i, u, duty, landing, drift, lift, gone, striding, stance, mayStep, dt) {
73
- const F = a.feet;
48
+ function footAt(actor, i, u, duty, landing, drift, lift, gone, striding, stance, mayStep, deltaSeconds) {
49
+ const feet = actor.feet;
74
50
  let air = 0;
75
51
  if (striding) {
76
52
  const back = gone < 0;
77
53
  if (u < duty) {
78
- F[i] -= gone;
79
- F[i + 2] = F[i];
54
+ feet[i] -= gone;
55
+ feet[i + 2] = feet[i];
80
56
  } else {
81
57
  const s = back ? 1 - (u - duty) / (1 - duty) : (u - duty) / (1 - duty),
82
58
  s2 = s * s,
83
59
  s3 = s2 * s;
84
- F[i] = F[i + 2] + (landing - F[i + 2]) * (3 * s2 - 2 * s3) + drift * (2 * s3 - 3 * s2 + s);
60
+ feet[i] = feet[i + 2] + (landing - feet[i + 2]) * (3 * s2 - 2 * s3) + drift * (2 * s3 - 3 * s2 + s);
85
61
  air = lift * Math.sin(Math.PI * Math.pow(s, 0.8));
86
62
  }
87
63
  } else {
88
- const off = stance - F[i];
89
- if (mayStep) F[i] += clamp(off, -foot.settleSpeed * dt, foot.settleSpeed * dt);
64
+ const off = stance - feet[i];
65
+ if (mayStep) feet[i] += clamp(off, -foot.settleSpeed * deltaSeconds, foot.settleSpeed * deltaSeconds);
90
66
  air = mayStep ? Math.min(foot.settleLift, Math.abs(off) * 0.45) : 0;
91
- F[i + 2] = F[i];
67
+ feet[i + 2] = feet[i];
92
68
  }
93
- F[i + 4] += (air - F[i + 4]) * Math.min(1, dt * 22);
69
+ feet[i + 4] += (air - feet[i + 4]) * Math.min(1, deltaSeconds * 22);
94
70
  }
95
71
  const fraction = x => ((x % 1) + 1) % 1;
96
72
  const GROUND_KEPT = 0.04, // metres a foot's spot may move before the ground under it is looked up again
@@ -98,8 +74,8 @@ export function createBipedStride({ rig, foot, pace, ground }) {
98
74
  // The ground at (x, z) under foot k (0 left, 1 right; 2 and 3 under their toes) of actor a, looked up again only once the foot
99
75
  // has moved (or now and then): a planted or standing foot keeps its height, and no number is made for the garbage each frame
100
76
  // (a.footGround: x, z, y and the lookups since, a spot).
101
- function groundUnder(a, k, x, z) {
102
- const g = a.footGround || (a.footGround = new Float64Array(16).fill(NaN)),
77
+ function groundUnder(actor, k, x, z) {
78
+ const g = actor.footGround || (actor.footGround = new Float64Array(16).fill(NaN)),
103
79
  i = k * 4;
104
80
  if (!(Math.abs(x - g[i]) <= GROUND_KEPT && Math.abs(z - g[i + 1]) <= GROUND_KEPT && g[i + 3] < GROUND_FRESH)) {
105
81
  g[i] = x;
@@ -112,78 +88,78 @@ export function createBipedStride({ rig, foot, pace, ground }) {
112
88
  }
113
89
  // A step's length on a stair: one tread, as far as actor a is on one (kept with the feet: how far on a stair, its tread in
114
90
  // metres, and the seconds since an edge of it was seen); `len` otherwise, the walk's own, which a stair's is never longer than.
115
- function treadStep(a, len, h) {
116
- const F = a.feet;
117
- return F && F[13] > 0.01 ? lerp(len, Math.min(len, F[14] / h), F[13]) : len;
91
+ function treadStep(actor, len, h) {
92
+ const feet = actor.feet;
93
+ return feet && feet[13] > 0.01 ? lerp(len, Math.min(len, feet[14] / h), feet[13]) : len;
118
94
  }
119
95
  // Notes a step's edge of `riser` metres seen under a foot: on a climb or a descent it is a stair's, whose tread is the riser
120
96
  // over the slope walked.
121
- function stairSeen(a, riser) {
122
- const steep = Math.abs(a.slope),
123
- F = a.feet;
97
+ function stairSeen(actor, riser) {
98
+ const steep = Math.abs(actor.slope),
99
+ feet = actor.feet;
124
100
  if (steep < foot.stairSlope) return;
125
- F[14] += (clamp(riser / steep, foot.treadRange[0], foot.treadRange[1]) - F[14]) * 0.25;
126
- F[15] = foot.stairMemory;
101
+ feet[14] += (clamp(riser / steep, foot.treadRange[0], foot.treadRange[1]) - feet[14]) * 0.25;
102
+ feet[15] = foot.stairMemory;
127
103
  }
128
104
  // The legs of someone on their feet this frame, written into `step`. lean: the trunk's lean forward; sink: how far the pose
129
105
  // lowers the hips; hipZ: how far it shifts them forward; stanceL, stanceR: where the pose plants each foot, forward of the
130
106
  // middle; free: standing on open ground (the ground under each foot is then looked up, and a.y set between them); list: how
131
107
  // far the hips list as their owner stands with the weight on one leg (the left side down is more).
132
- function stride(a, dt, h, lean, sink, hipZ, stanceL, stanceR, free, list, strideScale = 1, liftScale = 1, hipScale = 1) {
133
- const v = a.fwd / h,
108
+ function stride(actor, deltaSeconds, h, lean, sink, hipZ, stanceL, stanceR, free, list, strideScale = 1, liftScale = 1, hipScale = 1) {
109
+ const v = actor.fwd / h,
134
110
  speed = Math.abs(v),
135
111
  go = sstep(0.06, 0.5, speed), // how much of a stride the legs take
136
112
  run = sstep(pace.runFrom, pace.runFull, speed),
137
- shuffle = Math.max(go, 0.45 * Math.max(sstep(0.15, 0.7, a.side / h), sstep(0.6, 2.4, Math.abs(a.spin)))), // feet also lift to turn and to step aside
113
+ shuffle = Math.max(go, 0.45 * Math.max(sstep(0.15, 0.7, actor.side / h), sstep(0.6, 2.4, Math.abs(actor.spin)))), // feet also lift to turn and to step aside
138
114
  striding = shuffle > 0.02,
139
115
  len = treadStep(
140
- a,
141
- Math.min(pace.maxStep, pace.baseStep + pace.stepGain * speed) * strideScale * (1 - 0.35 * Math.min(1, Math.abs(a.slope) * 2.2)),
116
+ actor,
117
+ Math.min(pace.maxStep, pace.baseStep + pace.stepGain * speed) * strideScale * (1 - 0.35 * Math.min(1, Math.abs(actor.slope) * 2.2)),
142
118
  h,
143
119
  ),
144
120
  duty = lerp(pace.walkDuty, pace.runDuty, run),
145
121
  sweep = 2 * len * duty * go,
146
- lift = (lerp(pace.walkLift, pace.runLift, run) * liftScale + Math.max(0, a.slope) * len * 0.45) * shuffle,
147
- tip = run * go * pace.runLean + go * clamp(a.slope * 0.2, -0.06, 0.12); // a runner leans into the run, a climber into the hill
122
+ lift = (lerp(pace.walkLift, pace.runLift, run) * liftScale + Math.max(0, actor.slope) * len * 0.45) * shuffle,
123
+ tip = run * go * pace.runLean + go * clamp(actor.slope * 0.2, -0.06, 0.12); // a runner leans into the run, a climber into the hill
148
124
  // each foot: where it is forward of the middle, where it left the ground, how high it is, its sole's pitch in the stride
149
125
  // and the pitch of the ground it stands on; then the roll of both, and the ground each foot goes by (metres)
150
126
  // then how far they are on a stair, its tread, and the seconds a stair is still underfoot
151
- if (!a.feet) a.feet = [stanceL, stanceR, stanceL, stanceR, 0, 0, 0, 0, 0, 0, 0, NaN, NaN, 0, 0.3, 0];
152
- if (striding && !a.striding) a.phase = TAU * (duty - 0.5 + 0.02 + (a.seed > 0.5 ? 0.5 : 0)); // setting off: one foot has just taken the weight, the other leaves the ground
153
- a.striding = striding;
154
- a.phase += striding
155
- ? (Math.PI * dt * (v + (1 - go) * (a.side / h) * 1.4)) / len + (1 - go) * Math.abs(a.spin) * dt * 1.6
156
- : dt * pace.idleRate;
127
+ if (!actor.feet) actor.feet = [stanceL, stanceR, stanceL, stanceR, 0, 0, 0, 0, 0, 0, 0, NaN, NaN, 0, 0.3, 0];
128
+ if (striding && !actor.striding) actor.phase = TAU * (duty - 0.5 + 0.02 + (actor.seed > 0.5 ? 0.5 : 0)); // setting off: one foot has just taken the weight, the other leaves the ground
129
+ actor.striding = striding;
130
+ actor.phase += striding
131
+ ? (Math.PI * deltaSeconds * (v + (1 - go) * (actor.side / h) * 1.4)) / len + (1 - go) * Math.abs(actor.spin) * deltaSeconds * 1.6
132
+ : deltaSeconds * pace.idleRate;
157
133
  lean += tip;
158
- const uL = fraction(a.phase / TAU),
134
+ const uL = fraction(actor.phase / TAU),
159
135
  uR = fraction(uL + 0.5),
160
136
  sinL = Math.sin(lean),
161
137
  cosL = Math.cos(lean),
162
138
  hipAt = rig.hipHeight * sinL + hipZ, // the hips forward of the point between the feet; a stride is taken under them
163
139
  landing = hipAt * go + (v < 0 ? -sweep : sweep) / 2,
164
140
  drift = ((v < 0 ? sweep : -sweep) * (1 - duty)) / duty,
165
- gone = (a.fwd * dt) / h,
166
- F = a.feet,
167
- leftFirst = Math.abs(stanceL - F[0]) >= Math.abs(stanceR - F[1]); // of two feet out of place, the one further out steps first
168
- footAt(a, 0, uL, duty, landing, drift, lift, gone, striding, stanceL, leftFirst || Math.abs(stanceR - F[1]) < 0.03, dt);
169
- footAt(a, 1, uR, duty, landing, drift, lift, gone, striding, stanceR, !leftFirst || Math.abs(stanceL - F[0]) < 0.03, dt);
141
+ gone = (actor.fwd * deltaSeconds) / h,
142
+ feet = actor.feet,
143
+ leftFirst = Math.abs(stanceL - feet[0]) >= Math.abs(stanceR - feet[1]); // of two feet out of place, the one further out steps first
144
+ footAt(actor, 0, uL, duty, landing, drift, lift, gone, striding, stanceL, leftFirst || Math.abs(stanceR - feet[1]) < 0.03, deltaSeconds);
145
+ footAt(actor, 1, uR, duty, landing, drift, lift, gone, striding, stanceR, !leftFirst || Math.abs(stanceL - feet[0]) < 0.03, deltaSeconds);
170
146
  // the hips turn with the leg that leads and drop on the side of the one in the air, which carries each leg's joint forward
171
147
  // or back and up or down: the legs are solved from where their joints then are, so the feet stay where they are planted
172
148
  const turn = Math.cos(TAU * uL) * go * lerp(pace.hipTurn[0], pace.hipTurn[1], run) * hipScale,
173
149
  listed = list - Math.cos(TAU * (uL - duty / 2)) * go * pace.hipDrop * hipScale,
174
- jointZ = a.lx * Math.sin(turn), // the left leg's joint forward of the hips' middle, and the right one's behind it
175
- jointY = a.lx * Math.sin(listed), // the right leg's joint above the hips' middle, and the left one's below it
176
- zL = F[0],
177
- zR = F[1],
178
- airL = F[4],
179
- airR = F[5],
180
- soleEase = Math.min(1, dt * foot.response),
150
+ jointZ = actor.lx * Math.sin(turn), // the left leg's joint forward of the hips' middle, and the right one's behind it
151
+ jointY = actor.lx * Math.sin(listed), // the right leg's joint above the hips' middle, and the left one's below it
152
+ zL = feet[0],
153
+ zR = feet[1],
154
+ airL = feet[4],
155
+ airR = feet[5],
156
+ soleEase = Math.min(1, deltaSeconds * foot.response),
181
157
  roll = go * (v < 0 ? foot.reverseRoll : 1),
182
158
  strike = roll * lerp(foot.heelStrike[0], foot.heelStrike[1], run),
183
159
  push = roll * lerp(foot.pushOff[0], foot.pushOff[1], run);
184
160
  // each sole rolls from heel to toe through its stride
185
- F[6] += ((striding ? soleAt(uL, duty, v < 0, strike, push) : 0) - F[6]) * soleEase;
186
- F[7] += ((striding ? soleAt(uR, duty, v < 0, strike, push) : 0) - F[7]) * soleEase;
161
+ feet[6] += ((striding ? solePitch(foot, uL, duty, v < 0, strike, push) : 0) - feet[6]) * soleEase;
162
+ feet[7] += ((striding ? solePitch(foot, uR, duty, v < 0, strike, push) : 0) - feet[7]) * soleEase;
187
163
  let groundL = 0,
188
164
  groundR = 0,
189
165
  over = 0,
@@ -191,77 +167,77 @@ export function createBipedStride({ rig, foot, pace, ground }) {
191
167
  slopeR = 0,
192
168
  across = 0;
193
169
  if (free) {
194
- const cy = Math.cos(a.yaw),
195
- sy = Math.sin(a.yaw),
196
- wide = a.lx * h,
170
+ const cy = Math.cos(actor.yaw),
171
+ sy = Math.sin(actor.yaw),
172
+ wide = actor.lx * h,
197
173
  ahead = foot.sampleAhead * h,
198
- xL = a.x - cy * wide + sy * zL * h,
199
- xR = a.x + cy * wide + sy * zR * h,
200
- atL = a.z + sy * wide + cy * zL * h,
201
- atR = a.z - sy * wide + cy * zR * h,
202
- gL = groundUnder(a, 0, xL, atL),
203
- gR = groundUnder(a, 1, xR, atR);
174
+ xL = actor.x - cy * wide + sy * zL * h,
175
+ xR = actor.x + cy * wide + sy * zR * h,
176
+ atL = actor.z + sy * wide + cy * zL * h,
177
+ atR = actor.z - sy * wide + cy * zR * h,
178
+ gL = groundUnder(actor, 0, xL, atL),
179
+ gR = groundUnder(actor, 1, xR, atR);
204
180
  // the ground each foot goes by follows what is under it: at once under a foot that stands, over a moment under one in the
205
181
  // air, so that a step's edge crossed in mid-stride (a stair, a kerb) carries the foot and the hips up to it instead of
206
182
  // jerking them there, and the foot is lifted higher to clear it
207
- if (!(Math.abs(gL - F[11]) < foot.snapHeight)) F[11] = gL;
208
- if (!(Math.abs(gR - F[12]) < foot.snapHeight)) F[12] = gR;
209
- F[11] += (gL - F[11]) * Math.min(1, dt * foot.groundResponse[airL < 0.004 ? 0 : 1]);
210
- F[12] += (gR - F[12]) * Math.min(1, dt * foot.groundResponse[airR < 0.004 ? 0 : 1]);
211
- a.y = (F[11] + F[12]) / 2;
212
- groundL = clamp((F[11] - a.y) / h, -0.3, 0.3);
183
+ if (!(Math.abs(gL - feet[11]) < foot.snapHeight)) feet[11] = gL;
184
+ if (!(Math.abs(gR - feet[12]) < foot.snapHeight)) feet[12] = gR;
185
+ feet[11] += (gL - feet[11]) * Math.min(1, deltaSeconds * foot.groundResponse[airL < 0.004 ? 0 : 1]);
186
+ feet[12] += (gR - feet[12]) * Math.min(1, deltaSeconds * foot.groundResponse[airR < 0.004 ? 0 : 1]);
187
+ actor.y = (feet[11] + feet[12]) / 2;
188
+ groundL = clamp((feet[11] - actor.y) / h, -0.3, 0.3);
213
189
  groundR = -groundL;
214
190
  over = lift > 0.01 ? Math.min(foot.stepClearance[1], (Math.abs(gL - gR) / h) * foot.stepClearance[0]) / lift : 0;
215
191
  // a planted sole lies along the ground under it: the slope from the ankle's line to the toes, unless that is a step's
216
192
  // edge; a foot in the air keeps the slope it left
217
- slopeL = F[8];
218
- slopeR = F[9];
193
+ slopeL = feet[8];
194
+ slopeR = feet[9];
219
195
  if (airL < 0.01) {
220
- const grade = (groundUnder(a, 2, xL + sy * ahead, atL + cy * ahead) - gL) / ahead;
196
+ const grade = (groundUnder(actor, 2, xL + sy * ahead, atL + cy * ahead) - gL) / ahead;
221
197
  slopeL = Math.abs(grade) < foot.edgeSlope ? -Math.atan(grade) : 0;
222
- if (!slopeL && grade) stairSeen(a, Math.abs(grade) * ahead);
198
+ if (!slopeL && grade) stairSeen(actor, Math.abs(grade) * ahead);
223
199
  }
224
200
  if (airR < 0.01) {
225
- const grade = (groundUnder(a, 3, xR + sy * ahead, atR + cy * ahead) - gR) / ahead;
201
+ const grade = (groundUnder(actor, 3, xR + sy * ahead, atR + cy * ahead) - gR) / ahead;
226
202
  slopeR = Math.abs(grade) < foot.edgeSlope ? -Math.atan(grade) : 0;
227
- if (!slopeR && grade) stairSeen(a, Math.abs(grade) * ahead);
203
+ if (!slopeR && grade) stairSeen(actor, Math.abs(grade) * ahead);
228
204
  }
229
205
  across = Math.abs(gR - gL) < foot.edgeSlope * 2 * wide ? Math.atan((gR - gL) / (2 * wide)) : 0;
230
206
  }
231
- F[15] = Math.max(0, F[15] - dt);
232
- F[13] += ((F[15] > 0 && striding ? 1 : 0) - F[13]) * Math.min(1, dt * foot.stairResponse);
233
- F[8] += (clamp(slopeL, -foot.maxSlopeAngle, foot.maxSlopeAngle) - F[8]) * soleEase;
234
- F[9] += (clamp(slopeR, -foot.maxSlopeAngle, foot.maxSlopeAngle) - F[9]) * soleEase;
235
- F[10] += (clamp(across, -foot.maxSlopeAngle, foot.maxSlopeAngle) - F[10]) * soleEase;
207
+ feet[15] = Math.max(0, feet[15] - deltaSeconds);
208
+ feet[13] += ((feet[15] > 0 && striding ? 1 : 0) - feet[13]) * Math.min(1, deltaSeconds * foot.stairResponse);
209
+ feet[8] += (clamp(slopeL, -foot.maxSlopeAngle, foot.maxSlopeAngle) - feet[8]) * soleEase;
210
+ feet[9] += (clamp(slopeR, -foot.maxSlopeAngle, foot.maxSlopeAngle) - feet[9]) * soleEase;
211
+ feet[10] += (clamp(across, -foot.maxSlopeAngle, foot.maxSlopeAngle) - feet[10]) * soleEase;
236
212
  // where each ankle then is: forward of the middle, and above the ground
237
- ankleAt(F[6], F[8]);
213
+ ankleOffset(_ankle, rig, feet[6], feet[8]);
238
214
  const ankleZL = zL + _ankle[0],
239
215
  ankleYL = groundL + airL * (1 + over) + _ankle[1];
240
- ankleAt(F[7], F[9]);
216
+ ankleOffset(_ankle, rig, feet[7], feet[9]);
241
217
  const ankleZR = zR + _ankle[0],
242
218
  ankleYR = groundR + airR * (1 + over) + _ankle[1];
243
219
  // the hips ride as high as the pose asks and the planted legs allow
244
220
  let hip = rig.hipHeight * cosL + sink + run * go * (pace.runDip - pace.runBob * Math.cos(2 * TAU * (uL - duty / 2)));
245
221
  if (airL < 0.004) hip = Math.min(hip, ankleYL + jointY + Math.sqrt(Math.max(0.05, reach * reach - (ankleZL - hipAt - jointZ) ** 2)));
246
222
  if (airR < 0.004) hip = Math.min(hip, ankleYR - jointY + Math.sqrt(Math.max(0.05, reach * reach - (ankleZR - hipAt + jointZ) ** 2)));
247
- a.hip = Number.isNaN(a.hip) ? hip : a.hip + (hip - a.hip) * Math.min(1, dt * pace.hipResponse);
223
+ actor.hip = Number.isNaN(actor.hip) ? hip : actor.hip + (hip - actor.hip) * Math.min(1, deltaSeconds * pace.hipResponse);
248
224
  // each leg from the hip to its ankle, in the leaning trunk's own frame
249
225
  let z = ankleZL - hipAt - jointZ,
250
- y = ankleYL - a.hip + jointY;
251
- solveLeg(z * cosL - y * sinL, y * cosL + z * sinL);
226
+ y = ankleYL - actor.hip + jointY;
227
+ solveBipedLeg(_leg, rig, z * cosL - y * sinL, y * cosL + z * sinL, 0.3);
252
228
  step.thighL = _leg[0];
253
229
  step.kneeL = _leg[1];
254
230
  z = ankleZR - hipAt + jointZ;
255
- y = ankleYR - a.hip - jointY;
256
- solveLeg(z * cosL - y * sinL, y * cosL + z * sinL);
231
+ y = ankleYR - actor.hip - jointY;
232
+ solveBipedLeg(_leg, rig, z * cosL - y * sinL, y * cosL + z * sinL, 0.3);
257
233
  step.thighR = _leg[0];
258
234
  step.kneeR = _leg[1];
259
- step.soleL = F[6] + F[8] - lean; // against the leaning trunk the legs are solved in
260
- step.soleR = F[7] + F[9] - lean;
261
- step.toesL = -Math.max(0, F[6]) * sstep(foot.toeReleaseHeight, 0, airL); // the toes stay on the ground while the heel rises
262
- step.toesR = -Math.max(0, F[7]) * sstep(foot.toeReleaseHeight, 0, airR);
263
- step.roll = F[10];
264
- step.rise = a.hip - rig.hipHeight * cosL;
235
+ step.soleL = feet[6] + feet[8] - lean; // against the leaning trunk the legs are solved in
236
+ step.soleR = feet[7] + feet[9] - lean;
237
+ step.toesL = -Math.max(0, feet[6]) * sstep(foot.toeReleaseHeight, 0, airL); // the toes stay on the ground while the heel rises
238
+ step.toesR = -Math.max(0, feet[7]) * sstep(foot.toeReleaseHeight, 0, airR);
239
+ step.roll = feet[10];
240
+ step.rise = actor.hip - rig.hipHeight * cosL;
265
241
  step.swing = Math.cos(TAU * uL) * go; // 1 as the left foot lands ahead, -1 as the right does
266
242
  step.arms = Math.cos(TAU * (uL - pace.armLag)) * go; // the arms' swing against it: 1 with the left arm furthest back
267
243
  step.bearing = Math.cos(TAU * (uL - duty / 2)) * go * (1 - run); // 1 with the weight over the left foot, -1 over the right
@@ -0,0 +1,33 @@
1
+ import { sstep } from '../math/scalar.js';
2
+
3
+ /**
4
+ * Reach a target, transfer an object once while in contact, then withdraw.
5
+ * Fractions specify the end of the approach, the transfer, and the start of
6
+ * withdrawal. Supply pose(weight, approach, phase) to drive a rig and transfer() to
7
+ * change ownership. Advance the returned function with elapsed seconds.
8
+ * It returns true when finished. Drop it to cancel without a late transfer.
9
+ */
10
+ export function createContactTransition({
11
+ duration, pose, transfer, arriveAt = 0.48, transferAt = 0.55, leaveAt = 0.64,
12
+ }) {
13
+ if (!(Number.isFinite(duration) && duration > 0 && 0 < arriveAt && arriveAt <= transferAt &&
14
+ transferAt <= leaveAt && leaveAt < 1)) throw new RangeError('Expected positive duration and ordered contact fractions');
15
+ let elapsed = 0, transferred = false;
16
+ return function advance(deltaSeconds) {
17
+ if (elapsed === duration) return true;
18
+ elapsed = Math.min(duration, elapsed + Math.max(0, deltaSeconds));
19
+ const phase = elapsed / duration;
20
+ const approach = sstep(0, arriveAt, phase);
21
+ const weight = approach * (1 - sstep(leaveAt, 1, phase));
22
+ if (!transferred && phase >= transferAt) {
23
+ // A slow frame can cross the entire hold. Establish contact before releasing.
24
+ pose(1, 1, weight === 1 ? phase : transferAt);
25
+ transferred = true;
26
+ transfer();
27
+ if (weight < 1) pose(weight, approach, phase);
28
+ } else {
29
+ pose(weight, approach, phase);
30
+ }
31
+ return elapsed === duration;
32
+ };
33
+ }