Skip to content
Source
Sign inSign up
samwillis/jerry
Open History to see the last commit

ExplorerRig.swift

576 lines29.2 KB

1import AppKit
2import SpriteKit
3import CoreImage
4import ExpeditionCore
5​
6@MainActor
7private func appendSilhouette(_ shape: CGPath, from node: SKNode, to target: SKNode, into result: CGMutablePath) {
8 let origin = node.convert(.zero, to: target)
9 let x = node.convert(.init(x: 1, y: 0), to: target)
10 let y = node.convert(.init(x: 0, y: 1), to: target)
11 let transform = CGAffineTransform(a: x.x - origin.x, b: x.y - origin.y, c: y.x - origin.x, d: y.y - origin.y, tx: origin.x, ty: origin.y)
12 result.addPath(shape, transform: transform)
14​
15@MainActor
16private final class RigLimb: SKNode {
17 private let upperNode = SKNode()
18 let lowerNode = SKNode()
19 private let endNode = SKNode()
20 private let outline = SKShapeNode()
21 private let mask = SKShapeNode()
22 private let cloth = SKCropNode()
23 private let isFoot: Bool
24 private let baseColor: NSColor
25 private let width: CGFloat
26 let upperLength: Double
27 let lowerLength: Double
28​
29 init(upper: Double, lower: Double, color: NSColor, foot: Bool) {
30 upperLength = upper; lowerLength = lower; isFoot = foot
31 baseColor = color
32 width = foot ? 6 : 5
33 super.init()
34 // One rounded, continuous cloth silhouette covers both bones, with no internal cap borders.
35 outline.lineCap = .round
36 outline.lineJoin = .round
37 outline.fillColor = .clear
38 addChild(outline)
39 mask.lineCap = .round
40 mask.lineJoin = .round
41 mask.lineWidth = width
42 mask.strokeColor = .white
43 mask.fillColor = .clear
44 cloth.maskNode = mask
45 cloth.addChild(PaintedPart(rect: CGRect(x: -32, y: -36, width: 64, height: 72), radius: 0, color: color, material: .limbCloth))
46 addChild(cloth)
47 // Keep the articulated hierarchy for the hand/boot attachments.
48 addChild(upperNode)
49 upperNode.addChild(lowerNode)
50 lowerNode.position.y = -upper
51 lowerNode.addChild(endNode)
52 endNode.position.y = -lower
53 let end = PaintedPart(rect: CGRect(x: -3, y: foot ? -3 : -2, width: foot ? 10 : 6, height: 5), radius: 2, color: foot ? ExplorerPalette.boots : ExplorerPalette.skin, material: foot ? .leather : .skin)
54 endNode.addChild(end)
55 setPainted(true)
56 }
57 required init?(coder: NSCoder) { fatalError("Use init(upper:lower:color:foot:)") }
58​
59 func setPainted(_ painted: Bool) {
60 outline.strokeColor = painted
61 ? (baseColor.blended(withFraction: 0.6, of: .black) ?? baseColor).withAlphaComponent(0.9)
62 : NSColor(calibratedWhite: 0.15, alpha: 1)
63 outline.lineWidth = width + (painted ? 1.4 : 2)
64 }
65​
66 func shadowPaths(in target: SKNode) -> [CGPath] {
67 var paths: [CGPath] = []
68 if let line = outline.path {
69 let path = CGMutablePath()
70 appendSilhouette(line.copy(strokingWithWidth: width + 1.4, lineCap: .round, lineJoin: .round, miterLimit: 2), from: self, to: target, into: path)
71 paths.append(path)
72 }
73 for case let part as PaintedPart in endNode.children {
74 let path = CGMutablePath()
75 appendSilhouette(part.silhouettePath, from: part, to: target, into: path)
76 paths.append(path)
77 }
78 return paths
79 }
80​
81 func place(root: WorldPoint, solution: LimbSolution) {
82 position = CGPoint(x: root.x, y: root.y)
83 let a = atan2(solution.joint.y - root.y, solution.joint.x - root.x) + .pi / 2
84 let b = atan2(solution.end.y - solution.joint.y, solution.end.x - solution.joint.x) + .pi / 2
85 upperNode.zRotation = a
86 lowerNode.zRotation = b - a
87 if isFoot { endNode.zRotation = -b }
88 let path = CGMutablePath()
89 path.move(to: .zero)
90 path.addLine(to: CGPoint(x: solution.joint.x - root.x, y: solution.joint.y - root.y))
91 // Rounded stroke caps extend beyond their endpoint. Tuck the sleeve cap
92 // into the palm without moving the hand or changing its contact target.
93 let forearm = hypot(solution.end.x - solution.joint.x, solution.end.y - solution.joint.y)
94 let inset = isFoot ? 0 : min(1.6, forearm)
95 let endX = solution.end.x + (solution.joint.x - solution.end.x) * inset / max(0.001, forearm)
96 let endY = solution.end.y + (solution.joint.y - solution.end.y) * inset / max(0.001, forearm)
97 // Leave the rounded shin cap inside the boot rather than below its sole.
98 path.addLine(to: CGPoint(x: endX - root.x, y: endY - root.y + (isFoot ? 1 : 0)))
99 outline.path = path
100 mask.path = path
101 }
103​
104/// Shared by the desktop and playground. Visual offsets never change the simulation origin.
105@MainActor
106final class ExplorerRig: SKNode {
107 private let shadowCrop = SKCropNode()
108 private let shadowMask = SKShapeNode()
109 private var shadowOccluders: [CGRect]?
110 private let shadow = SKEffectNode()
111 private var shadowPieces: [SKShapeNode] = []
112 private let pivot = SKNode()
113 private let body = SKNode()
114 private let torso = SKNode()
115 private let head = SKNode()
116 private let backpack = SKNode()
117 private let joints = SKNode()
118 private let canopy = SKNode()
119 private let grappleGun = SKNode()
120 private let binoculars = SKNode()
121 var usingBinoculars = false
122 var shoulderHeight: Double { presentedPose.hips.y + 20 }
123 private let canopyFabric = SKNode()
124 private var cords: [(SKShapeNode, CGFloat)] = []
125 private let leftEye = SKShapeNode(rect: CGRect(x: -1, y: -1.5, width: 2, height: 3))
126 private let rightEye = SKShapeNode(rect: CGRect(x: -1, y: -1.5, width: 2, height: 3))
127 private let leftArm = RigLimb(upper: 12, lower: 12, color: ExplorerPalette.jacket, foot: false)
128 private let rightArm = RigLimb(upper: 12, lower: 12, color: ExplorerPalette.jacket, foot: false)
129 private let leftLeg = RigLimb(upper: ExpeditionConfiguration.legSegmentLength, lower: ExpeditionConfiguration.legSegmentLength, color: ExplorerPalette.trousers, foot: true)
130 private let rightLeg = RigLimb(upper: ExpeditionConfiguration.legSegmentLength, lower: ExpeditionConfiguration.legSegmentLength, color: ExplorerPalette.trousers, foot: true)
131 private var animator = RigAnimator()
132 private var expressionTime: Double = 0
133 private var pointerEyeOffset = CGPoint.zero
134 private var pointerHeadTurn = 0.0
135 private var landingTime: Double?
136 private var landingStrength: Double = 1
137 private var presentedPose = ExplorerPose()
138 private var ropeBlendFrom = ExplorerPose()
139 private var ropeBlendTime: Double = 1
140 private var harnessWasUsed = false
141 var synchronizedTime: Double?
142 var ropePose: ExplorerPose?
143 var jumpPose: ExplorerPose?
144 var grappleAim: WorldPoint?
145 var usesHarnessPivot = false
146 var crouchAmount = 0.0
147 var crackPose: ExplorerPose?
148 var handTargets: (WorldPoint, WorldPoint)?
149 var footTargets: (WorldPoint, WorldPoint)?
150 var grabPoint = CGPoint(x: 0, y: 64)
151 var showsJoints = false
152 var tuning: AnimationTuning {
153 get { animator.tuning }
154 set { animator.tuning = newValue }
155 }
156 var motion: ExplorerMotion { animator.motion }
157 var animationTime: Double { animator.time }
158 private(set) var clampedContacts = 0
159​
160 override init() {
161 super.init()
162 shadowCrop.zPosition = -20
163 shadowMask.fillColor = .white; shadowMask.strokeColor = .clear
164 shadowMask.path = CGPath(rect: .init(x: -128, y: -96, width: 256, height: 256), transform: nil)
165 shadowCrop.maskNode = shadowMask
166 shadow.alpha = 0.15
167 shadow.setScale(0.94)
168 shadow.filter = CIFilter(name: "CIGaussianBlur", parameters: [kCIInputRadiusKey: 4.5])
169 // Give the blur transparent breathing room; otherwise SpriteKit clips
170 // it to the silhouette's tight bounds and leaves a hard rectangular edge.
171 let blurPadding = SKSpriteNode(color: .clear, size: .init(width: 120, height: 160))
172 blurPadding.position = .init(x: 0, y: 32)
173 shadow.addChild(blurPadding)
174 shadow.shouldCenterFilter = false
175 shadow.shouldEnableEffects = true
176 shadow.shouldRasterize = false
177 addChild(shadowCrop)
178 shadowCrop.addChild(shadow)
179 addChild(pivot)
180 pivot.addChild(body)
181 body.addChild(backpack)
182 // Canonical left limbs are nearest the camera; mirror the entire stack when facing left.
183 body.addChild(rightLeg)
184 body.addChild(leftLeg)
185 body.addChild(rightArm)
186 body.addChild(torso)
187 body.addChild(head)
188 body.addChild(leftArm)
189 body.addChild(grappleGun)
190 buildGrappleGun()
191 head.addChild(binoculars); binoculars.name = "binoculars"; binoculars.zPosition = 6
192 binoculars.position = .init(x: 0, y: 2)
193 buildBinoculars()
194 body.addChild(canopy)
195 canopy.zPosition = -4
196 body.addChild(joints)
197 joints.zPosition = 10
198 rectangle(CGRect(x: -4, y: 20, width: 8, height: 8), color: ExplorerPalette.skin, parent: torso, material: .skin)
199 rectangle(CGRect(x: -12, y: -1, width: 24, height: 23), color: ExplorerPalette.jacket, parent: torso)
200 rectangle(CGRect(x: -4, y: -10, width: 14, height: 26), color: ExplorerPalette.bag, parent: backpack, material: .canvas)
201 rectangle(CGRect(x: -10, y: -7, width: 20, height: 17), color: ExplorerPalette.skin, parent: head, radius: 6, material: .skin)
202 rectangle(CGRect(x: -12, y: 7, width: 24, height: 8), color: ExplorerPalette.hat, parent: head, material: .felt)
203 rectangle(CGRect(x: -16, y: 6, width: 32, height: 3), color: ExplorerPalette.hat, parent: head, radius: 1, material: .felt)
204 for (eye, x) in [(leftEye, -1.0), (rightEye, 6.0)] {
205 eye.position = CGPoint(x: x, y: 3.5)
206 eye.fillColor = .black
207 eye.strokeColor = NSColor(calibratedWhite: 0.15, alpha: 1)
208 eye.lineWidth = 1
209 head.addChild(eye)
210 }
211 buildParachute()
212 setPainted(true)
213 render(delta: 0)
214 }
215 required init?(coder: NSCoder) { fatalError("Use init()") }
216​
217 private func rectangle(_ rect: CGRect, color: NSColor, parent: SKNode, radius: CGFloat = 3, material: ExplorerMaterial = .cloth) {
218 parent.addChild(PaintedPart(rect: rect, radius: radius, color: color, material: material))
219 }
220​
221 func setPainted(_ painted: Bool) {
222 func update(_ node: SKNode) {
223 (node as? PaintedPart)?.setPainted(painted)
224 (node as? RigLimb)?.setPainted(painted)
225 for child in node.children { update(child) }
226 }
227 update(body)
228 for eye in [leftEye, rightEye] {
229 eye.fillColor = painted ? NSColor(calibratedRed: 0.19, green: 0.13, blue: 0.1, alpha: 1) : .black
230 eye.strokeColor = eye.fillColor
231 eye.lineWidth = painted ? 0.4 : 1
232 }
233 }
234​
235 /// Jerry’s actual head contours, sized for legibility in the menu bar.
236 static func menuBarArtwork() -> NSImage {
237 let rig = ExplorerRig(); rig.render(delta: 0)
238 let paths = rig.head.children.compactMap { node -> CGPath? in
239 guard let part = node as? PaintedPart else { return nil }
240 let path = CGMutablePath()
241 appendSilhouette(part.silhouettePath, from: part, to: rig.head, into: path)
242 return path
243 }
244 let bounds = paths.reduce(CGRect.null) { $0.union($1.boundingBoxOfPath) }
245 let eyeCutouts = CGMutablePath()
246 for eye in [rig.leftEye, rig.rightEye] {
247 if let path = eye.path { appendSilhouette(path, from: eye, to: rig.head, into: eyeCutouts) }
248 }
249 let image = NSImage(size: .init(width: 22, height: 22), flipped: false) { _ in
250 let context = NSGraphicsContext.current!.cgContext
251 let scale = min(20 / bounds.width, 20 / bounds.height)
252 context.saveGState()
253 context.translateBy(x: 11 - bounds.midX * scale, y: 11 - bounds.midY * scale)
254 context.scaleBy(x: scale, y: scale)
255 context.setFillColor(NSColor.black.cgColor)
256 for path in paths { context.addPath(path); context.fillPath() }
257 context.setBlendMode(.clear); context.addPath(eyeCutouts); context.fillPath()
258 context.restoreGState()
259 return true
260 }
261 image.isTemplate = true; image.accessibilityDescription = "Jerry"
262 return image
263 }
264​
265 /// The web logo uses the same silhouette and expression as the running rig.
266 static func runningBrandArtwork() -> (silhouette: CGPath, eyes: CGPath) {
267 let rig = ExplorerRig()
268 rig.select(.running, restart: true)
269 rig.seek(to: 0.174)
270 let paths = rig.bodySilhouettes()
271 let silhouette = paths.dropFirst().reduce(paths[0]) { $0.union($1) }
272 let eyes = CGMutablePath()
273 for eye in [rig.leftEye, rig.rightEye] {
274 if let path = eye.path { appendSilhouette(path, from: eye, to: rig, into: eyes) }
275 }
276 return (silhouette, eyes)
277 }
278​
279 private func buildBinoculars() {
280 let casing = NSColor(calibratedRed: 0.19, green: 0.25, blue: 0.24, alpha: 1)
281 let brass = NSColor(calibratedRed: 0.64, green: 0.53, blue: 0.32, alpha: 1)
282 let glass = NSColor(calibratedRed: 0.12, green: 0.35, blue: 0.39, alpha: 1)
283 rectangle(.init(x: -1, y: -1.8, width: 7, height: 3), color: casing, parent: binoculars, radius: 1, material: .leather)
284 for x: CGFloat in [-1, 6] {
285 rectangle(.init(x: x - 3.7, y: -3.6, width: 7.4, height: 7.2), color: casing, parent: binoculars, radius: 2.4, material: .leather)
286 let rim = SKShapeNode(ellipseIn: .init(x: x - 2.9, y: -3, width: 5.8, height: 6))
287 rim.fillColor = brass; rim.strokeColor = NSColor(calibratedWhite: 0.1, alpha: 1); rim.lineWidth = 0.5; binoculars.addChild(rim)
288 let lens = CGPath(ellipseIn: .init(x: x - 2.15, y: -2.3, width: 4.3, height: 4.6), transform: nil)
289 binoculars.addChild(PaintedPart(path: lens, color: glass, material: .skin, tag: "binocular-glass"))
290 let reflection = CGMutablePath(); reflection.move(to: .init(x: x - 1.1, y: 0.2)); reflection.addQuadCurve(to: .init(x: x + 0.3, y: 1.4), control: .init(x: x - 1.1, y: 1.5))
291 let glint = SKShapeNode(path: reflection); glint.strokeColor = NSColor(calibratedRed: 0.75, green: 0.94, blue: 0.92, alpha: 0.8); glint.lineWidth = 0.65; glint.lineCap = .round; binoculars.addChild(glint)
292 }
293 let focusWheel = SKShapeNode(circleOfRadius: 0.85)
294 focusWheel.fillColor = brass; focusWheel.strokeColor = casing; focusWheel.lineWidth = 0.4; focusWheel.position = .init(x: 2.5, y: -1.2); binoculars.addChild(focusWheel)
295 }
296​
297 private func buildGrappleGun() {
298 func part(_ rect: CGRect, _ color: NSColor, radius: CGFloat = 1) {
299 let shape = SKShapeNode(rect: rect, cornerRadius: radius)
300 shape.fillColor = color; shape.strokeColor = NSColor(calibratedWhite: 0.12, alpha: 1); shape.lineWidth = 0.7
301 grappleGun.addChild(shape)
302 }
303 part(.init(x: -4, y: -4, width: 13, height: 8), NSColor(calibratedRed: 0.27, green: 0.36, blue: 0.37, alpha: 1), radius: 2)
304 part(.init(x: 7, y: -2, width: 10, height: 4), .lightGray)
305 part(.init(x: -2, y: -9, width: 4, height: 6), ExplorerPalette.bag)
306 let spool = SKShapeNode(circleOfRadius: 3)
307 spool.fillColor = ExplorerPalette.jacket; spool.strokeColor = .darkGray; spool.lineWidth = 0.7
308 spool.position = .init(x: 2, y: 0); grappleGun.addChild(spool)
309 grappleGun.zPosition = 4
310 }
311​
312 func grappleMuzzle(in node: SKNode) -> CGPoint { grappleGun.convert(.init(x: 17, y: 0), to: node) }
313​
314 private func buildParachute() {
315 let path = CGMutablePath()
316 path.move(to: CGPoint(x: -34, y: 105))
317 path.addQuadCurve(to: CGPoint(x: 34, y: 105), control: CGPoint(x: 0, y: 155))
318 path.addQuadCurve(to: CGPoint(x: -34, y: 105), control: CGPoint(x: 0, y: 98))
319 let fabric = PaintedPart(path: path, color: NSColor(calibratedRed: 0.93, green: 0.72, blue: 0.22, alpha: 1), material: .canopy, tag: "parachute")
320 canopy.addChild(canopyFabric)
321 canopyFabric.addChild(fabric)
322 for x: CGFloat in [-34, -12, 12, 34] {
323 let line = SKShapeNode()
324 line.strokeColor = .lightGray
325 line.lineWidth = 0.7
326 line.zPosition = -1
327 canopy.addChild(line)
328 cords.append((line, x))
329 }
330 }
331​
332 private func renderParachute(pose: ExplorerPose) {
333 canopy.isHidden = motion != .parachuting || animationTime < RecoveryAnimation.deploymentStart
334 guard !canopy.isHidden else { return }
335 let opening = RecoveryAnimation.deployment(at: animationTime)
336 canopyFabric.xScale = 0.05 + 0.95 * opening
337 canopyFabric.yScale = 0.025 + 0.975 * opening
338 canopyFabric.zRotation = -0.3 * (1 - opening)
339 canopyFabric.position = CGPoint(
340 x: backpack.position.x * (1 - opening) - sin(.pi * opening) * 5,
341 y: backpack.position.y * (1 - opening) + 105 * opening - 105 * canopyFabric.yScale
342 )
343 for (line, x) in cords {
344 let edgeY = 101.5 + 14 * x * x / (68 * 68)
345 let path = CGMutablePath()
346 path.move(to: canopyFabric.convert(CGPoint(x: x, y: edgeY), to: canopy))
347 let hand = x < 0 ? pose.leftHand : pose.rightHand
348 path.addLine(to: CGPoint(x: hand.x, y: hand.y))
349 line.path = path
350 line.alpha = max(0, (opening - 0.2) / 0.8)
351 }
352 }
353​
354 func select(_ motion: ExplorerMotion, restart: Bool = false) {
355 if restart { expressionTime = 0 }
356 if restart || ![ExplorerMotion.idle, .investigating, .landing].contains(motion) { landingTime = nil }
357 if motion != animator.motion { ropeBlendFrom = presentedPose; ropeBlendTime = 0 }
358 animator.select(motion, restart: restart, from: presentedPose)
359 }
360​
361 func land(strength: Double = 1) {
362 landingTime = 0
363 landingStrength = strength
364 }
365​
366 func seek(to time: Double) {
367 animator.seek(to: time)
368 expressionTime = animator.time
369 landingTime = nil
370 render(delta: 0)
371 }
372​
373 func render(delta: Double) {
374 var pose = animator.advance(by: delta, synchronizedTime: synchronizedTime)
375 // Both rope grips must read in front of the jacket, with the line between
376 // the torso and gloves. Restore the usual far-arm stack for other motions.
377 let onRope = usingBinoculars || crouchAmount > 0.001 || motion == .crouching || crackPose != nil || ropePose != nil || [.ropeClimbing, .ropeSwinging, .abseiling].contains(motion)
378 rightArm.zPosition = onRope ? 2 : 0
379 leftArm.zPosition = onRope ? 3 : 0
380 ropeBlendTime += delta.isFinite ? min(max(delta, 0), 0.1) : 0
381 if let ropePose {
382 let t = min(1, ropeBlendTime / 0.15)
383 pose = ropePose.blended(from: ropeBlendFrom, fraction: t * t * (3 - 2 * t))
384 }
385 if let crackPose {
386 let t = min(1, ropeBlendTime / 0.18)
387 pose = crackPose.blended(from: ropeBlendFrom, fraction: t * t * (3 - 2 * t))
388 }
389 if let jumpPose {
390 let t = min(1, ropeBlendTime / 0.04)
391 pose = jumpPose.blended(from: ropeBlendFrom, fraction: t * t * (3 - 2 * t))
392 }
393 pose = CrouchAnimation.apply(to: pose, amount: crouchAmount)
394 grappleGun.isHidden = motion != .grappling && grappleAim == nil
395 if motion == .grappling || grappleAim != nil {
396 let aim = grappleAim ?? .init(x: 80, y: 130)
397 let gunY = 46 - 12 * crouchAmount
398 let angle = atan2(aim.y - gunY, aim.x - 8)
399 grappleGun.position = .init(x: 8, y: gunY); grappleGun.zRotation = angle
400 func hand(_ x: Double, _ y: Double) -> WorldPoint {
401 .init(x: 8 + cos(angle) * x - sin(angle) * y, y: gunY + sin(angle) * x + cos(angle) * y)
402 }
403 pose.leftHand = hand(4, -3); pose.rightHand = hand(-3, -4)
404 pose.headTilt = min(0.15, max(-0.15, angle * 0.12))
405 }
406 binoculars.isHidden = !usingBinoculars
407 let elapsed = delta.isFinite ? min(max(delta, 0), 0.1) : 0
408 expressionTime += elapsed
409 if let time = landingTime {
410 let next = time + elapsed
411 landingTime = next < LandingAnimation.duration ? next : nil
412 pose = LandingAnimation.apply(to: pose, elapsed: next, strength: landingStrength)
413 }
414 if let handTargets { pose.leftHand = handTargets.0; pose.rightHand = handTargets.1 }
415 if let footTargets { pose.leftFoot = footTargets.0; pose.rightFoot = footTargets.1 }
416 if usingBinoculars {
417 func grip(_ x: Double) -> WorldPoint {
418 let y = -2.0, angle = pose.headTilt
419 return .init(x: pose.hips.x + cos(angle) * x - sin(angle) * y,
420 y: pose.hips.y + ExpeditionConfiguration.headOffset + sin(angle) * x + cos(angle) * y)
421 }
422 pose.leftHand = grip(-5.5); pose.rightHand = grip(10.5)
423 pose.elbowPole = .init(x: 0, y: -30); pose.leftElbowBend = nil; pose.rightElbowBend = nil
424 }
425 let held = motion == .held || (motion == .comic && animationTime.truncatingRemainder(dividingBy: 9) >= 5)
426 harnessWasUsed = usesHarnessPivot || (harnessWasUsed && abs(pose.sway) > 0.001 && !held)
427 let origin = held ? grabPoint : CGPoint(x: 0, y: harnessWasUsed ? RopeSession.harnessHeight : 60)
428 presentedPose = pose
429 pivot.position = origin
430 pivot.zRotation = pose.sway
431 body.position = CGPoint(x: -origin.x, y: -origin.y)
432 torso.position = CGPoint(x: pose.hips.x, y: pose.hips.y)
433 head.position = CGPoint(x: pose.hips.x, y: pose.hips.y + ExpeditionConfiguration.headOffset)
434 head.zRotation = pose.headTilt
435 updatePointerAttention(elapsed: elapsed)
436 backpack.position = CGPoint(x: pose.hips.x - 18, y: pose.hips.y + 10)
437 backpack.zRotation = pose.backpackTilt
438 renderParachute(pose: pose)
439 joints.removeAllChildren()
440 joints.isHidden = !showsJoints
441 clampedContacts = 0
442 place(leftArm, root: .init(x: pose.hips.x - 10, y: pose.hips.y + 20), target: pose.leftHand, knee: false, elbowPole: pose.elbowPole, elbowBend: pose.leftElbowBend)
443 place(rightArm, root: .init(x: pose.hips.x + 10, y: pose.hips.y + 20), target: pose.rightHand, knee: false, elbowPole: pose.elbowPole, elbowBend: pose.rightElbowBend)
444 place(leftLeg, root: .init(x: pose.hips.x - 7, y: pose.hips.y), target: pose.leftFoot, knee: true)
445 place(rightLeg, root: .init(x: pose.hips.x + 7, y: pose.hips.y), target: pose.rightFoot, knee: true)
446 updateShadow()
447 }
448​
449 private func bodySilhouettes() -> [CGPath] {
450 var paths: [CGPath] = []
451 for group in [torso, head, backpack] {
452 for case let part as PaintedPart in group.children {
453 let path = CGMutablePath()
454 appendSilhouette(part.silhouettePath, from: part, to: self, into: path)
455 paths.append(path)
456 }
457 }
458 for limb in [leftArm, rightArm, leftLeg, rightLeg] { paths += limb.shadowPaths(in: self) }
459 return paths
460 }
461​
462 private func updateShadow() {
463 var paths = bodySilhouettes()
464 if !grappleGun.isHidden {
465 for case let part as SKShapeNode in grappleGun.children {
466 if let shape = part.path {
467 let path = CGMutablePath()
468 appendSilhouette(shape, from: part, to: self, into: path)
469 paths.append(path)
470 }
471 }
472 }
473 // Opaque pieces form a single mask before blur/opacity. Keeping separate
474 // paths avoids overlapping contours confusing SpriteKit's triangulator.
475 while shadowPieces.count < paths.count {
476 let piece = SKShapeNode()
477 piece.fillColor = .black; piece.strokeColor = .clear
478 shadow.addChild(piece); shadowPieces.append(piece)
479 }
480 for (index, piece) in shadowPieces.enumerated() {
481 piece.isHidden = index >= paths.count
482 if index < paths.count { piece.path = paths[index] }
483 }
484 shadow.position = .init(x: 0, y: -7)
485 }
486​
487 /// Native windows cannot be interleaved inside this floating overlay. Masking
488 /// the finished blur makes a ledge occlude the shadow while the figure stays in front.
489 func setShadowOcclusion(windows: [CGRect], from space: SKNode) {
490 let feet = convert(.zero, to: space)
491 let scaleX = max(0.001, abs(xScale)), scaleY = max(0.001, abs(yScale))
492 let candidates = windows.filter {
493 $0.maxY <= feet.y + 0.75 && $0.maxY >= feet.y - 40 * scaleY
494 && $0.maxX >= feet.x - 80 * scaleX && $0.minX <= feet.x + 80 * scaleX
495 }.map { rect in
496 let a = convert(rect.origin, from: space), b = convert(.init(x: rect.maxX, y: rect.maxY), from: space)
497 return CGRect(x: min(a.x, b.x), y: min(a.y, b.y), width: abs(b.x - a.x), height: abs(b.y - a.y))
498 }
499 guard shadowOccluders != candidates else { return }
500 shadowOccluders = candidates
501 var allowed = CGPath(rect: .init(x: -128, y: -96, width: 256, height: 256), transform: nil)
502 for rect in candidates {
503 // Include the border itself, so blur never paints a dark stripe on the lip.
504 let frame = rect.insetBy(dx: -0.75 / scaleX, dy: -0.75 / scaleY)
505 let window = CGPath(roundedRect: frame, cornerWidth: 10 / scaleX, cornerHeight: 10 / scaleY, transform: nil)
506 allowed = allowed.subtracting(window)
507 }
508 shadowMask.path = allowed
509 }
510 #if DEBUG
511 func shadowIsVisible(at point: CGPoint) -> Bool { shadowMask.path?.contains(point) ?? true }
512 #endif
513​
514 /// Sample the current pointer, without capturing mouse events or keyboard focus.
515 /// Convert through the actual node transforms so mirroring, rope sway, and the
516 /// playground's enlarged rig all keep the eyes aimed in the right direction.
517 private func updatePointerAttention(elapsed: Double) {
518 var desiredEyes = CGPoint.zero
519 var desiredTurn = 0.0
520 let pointer = NSEvent.mouseLocation
521 if let scene, let view = scene.view, let window = view.window,
522 window.isVisible, window.screen?.frame.contains(pointer) == true {
523 let inWindow = window.convertPoint(fromScreen: pointer)
524 let inView = view.convert(inWindow, from: nil)
525 let inScene = scene.convertPoint(fromView: inView)
526 let relative = head.convert(inScene, from: scene)
527 let dx = relative.x - 2.5, dy = relative.y - 3.5
528 let distance = hypot(dx, dy)
529 // Fully engaged close by, with a soft boundary instead of a sudden snap.
530 let fade = min(1, max(0, (220 - distance) / 100))
531 let attention = fade * fade * (3 - 2 * fade)
532 let taskWeight = usingBinoculars ? 0.0 : (motion == .grappling ? 0.3 : 1.0)
533 let weight = attention * taskWeight
534 desiredEyes = .init(x: min(1, max(-1, dx / 55)) * 2.2 * weight,
535 y: min(1, max(-1, dy / 55)) * 1.3 * weight)
536 desiredTurn = min(1, max(-1, dy / (abs(dx) + 30))) * (dx < 0 ? -1 : 1) * 0.12 * weight
537 }
538 // Eyes lead the head slightly; both ease back to their animated neutral pose.
539 let eyeResponse = 1 - exp(-elapsed / 0.09)
540 let headResponse = 1 - exp(-elapsed / 0.22)
541 pointerEyeOffset.x += (desiredEyes.x - pointerEyeOffset.x) * eyeResponse
542 pointerEyeOffset.y += (desiredEyes.y - pointerEyeOffset.y) * eyeResponse
543 pointerHeadTurn += (desiredTurn - pointerHeadTurn) * headResponse
544 head.zRotation += pointerHeadTurn
545 head.position.x += pointerEyeOffset.x * 0.35
546 for (index, eye) in [leftEye, rightEye].enumerated() {
547 let openness = BlinkAnimation.openness(time: expressionTime, eye: index)
548 eye.yScale = openness
549 eye.position = .init(x: (index == 0 ? -1.0 : 6.0) + pointerEyeOffset.x,
550 y: 2 + (1.5 + pointerEyeOffset.y) * openness)
551 }
552 }
553​
554 private func place(_ limb: RigLimb, root: WorldPoint, target: WorldPoint, knee: Bool, elbowPole: WorldPoint = .init(x: -24, y: -6), elbowBend: Double? = nil) {
555 // Toe direction is +x. Mirroring the whole rig flips feet and poles together.
556 let pole = WorldPoint(x: root.x + (knee ? 24 : elbowPole.x), y: root.y + (knee ? -6 : elbowPole.y))
557 // Foot targets mark the sole; the shin ends at an ankle three points inside the boot.
558 let jointTarget = WorldPoint(x: target.x, y: target.y + (knee ? ExpeditionConfiguration.ankleHeight : 0))
559 let solution = TwoBoneIK.solve(root: root, target: jointTarget, upper: limb.upperLength, lower: limb.lowerLength, bend: elbowBend ?? 1, pole: knee || elbowBend != nil ? nil : pole)
560 limb.place(root: root, solution: solution)
561 if solution.isClamped { clampedContacts += 1 }
562 guard showsJoints else { return }
563 for point in [root, solution.joint, solution.end] {
564 let dot = SKShapeNode(circleOfRadius: 1.6)
565 dot.fillColor = .systemCyan
566 dot.strokeColor = .clear
567 dot.position = CGPoint(x: point.x, y: point.y)
568 joints.addChild(dot)
569 }
570 let contact = SKShapeNode(circleOfRadius: 2.5)
571 contact.position = CGPoint(x: target.x, y: target.y)
572 contact.strokeColor = solution.isClamped ? .systemRed : .systemGreen
573 contact.lineWidth = 0.8
574 joints.addChild(contact)
575 }