Repository Public License
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Arcade9// File : Games/DominoCity/DominoScene.swift10// Description : Domino City — SpriteKit scene: builds a level, pull-back11// aiming with trajectory preview, physics chain reactions,12// objectives, effects and the autoplay bot.13// Module : Games14// Repository : https://git.spboucher.ai/orix-arcade15// Created : 2026-11-2116// Last Modified : 2026-11-2117//18// =============================================================================19// AUTHOR & PROFESSIONAL AFFILIATION20// =============================================================================21//22// Author : Simon-Pierre Boucher23// Position : Professor of Finance24// Institution : Université du Québec en Outaouais (UQO)25// Department : Département des sciences administratives26// Organization : SP Boucher27//28// Website : https://spboucher.ai29// Git : https://git.spboucher.ai30//31// =============================================================================32// OFFICIAL CONTACT DIRECTORY33// =============================================================================34//35// General : info@spboucher.ai36// Professional : contact@spboucher.ai37// Direct : simon@spboucher.ai38// Research : research@spboucher.ai39// Development : dev@spboucher.ai40// Support : support@spboucher.ai41// Security/Admin : admin@spboucher.ai42// Notifications : notifications@spboucher.ai43//44// Preferred Contact: support@spboucher.ai45//46// =============================================================================47// COPYRIGHT & INTELLECTUAL PROPERTY48// =============================================================================49//50// Copyright (c) 202651// Simon-Pierre Boucher52//53// All rights reserved where applicable.54//55// This file is governed by the applicable project license,56// copyright notices, institutional agreements and relevant law.57//58// Unless expressly authorized by the applicable license or59// rights holder, copying, redistribution, sublicensing,60// publication and commercial exploitation are not permitted.61//62// Existing third-party rights and notices remain unaffected.63//64// =============================================================================65// CONFIDENTIALITY & SECURITY66// =============================================================================67//68// Classification : Public69// Distribution : Public repository; use is governed by the project license70// Security Contact : admin@spboucher.ai71//72// Access to this source does not independently grant permission73// to redistribute or disclose confidential materials.74//75// Do not embed credentials, private keys, access tokens,76// certificates or confidential personal information.77//78// =============================================================================79// LICENSE & MAINTENANCE80// =============================================================================81//82// License : Proprietary, all rights reserved (see license file)83// License File : LICENSE84// Maintainer : Simon-Pierre Boucher85// Technical Contact: dev@spboucher.ai86//87// =============================================================================88// END OF SP BOUCHER SOURCE HEADER89// =============================================================================9091import SpriteKit92import Observation9394/// Live state shared between the scene and the SwiftUI HUD.95@Observable96final class DominoSession {97 let level: DominoLevel98 var targetsHit = 099 var chain = 0100 var gems = 0101 var impulsesLeft: Int102 var canAim = true103 var isAiming = false104 var hasLaunched = false105 var result: DominoResult?106107 init(level: DominoLevel) {108 self.level = level109 impulsesLeft = level.impulses110 }111}112113final class DominoScene: ArcadeScene, @preconcurrency SKPhysicsContactDelegate {114 private enum Phase { case aiming, flying, finished }115116 private enum Category {117 static let fixed: UInt32 = 1118 static let piece: UInt32 = 2119 static let shot: UInt32 = 4120 static let sensor: UInt32 = 8121 }122123 private struct Touch {124 var a: String125 var b: String126 var impulse: CGFloat127 var point: CGPoint128 }129130 let level: DominoLevel131 let session: DominoSession132 /// When set, the bot fires these shots by itself (autoplay, solvability tests).133 var botShots: [DominoShot]?134135 private let stage = SKNode()136 private let cam = SKCameraNode()137 private let sky = SKSpriteNode(texture: DominoArt.sky)138 private var pieceNodes: [Int: SKNode] = [:]139 private var pieces: [Int: DominoPiece] = [:]140 private var startPose: [Int: (position: CGPoint, rotation: CGFloat)] = [:]141 private var ropes: [(ball: SKNode, anchor: CGPoint, line: SKSpriteNode)] = []142 private var shots: [SKNode] = []143 private var pending: [Touch] = []144 private var switchLinked: Set<Int> = []145 private(set) var tracker: DominoRunTracker146 private var phase = Phase.aiming147148 private var clock: TimeInterval = 0149 private var launchClock: TimeInterval = 0150 private var readyClock: TimeInterval = 0151 private var clearedClock: TimeInterval?152 private var stillTime: TimeInterval = 0153 private var botIndex = 0154 private var frameDt: TimeInterval = 1.0 / 60155156 // Aiming.157 private var aimStart: CGPoint?158 private var aim: (angle: Double, power: Double)?159 private var lastPowerStep = 0160 private let launcher = SKNode()161 private let launcherBall = SKSpriteNode(texture: DominoArt.orb(radius: CGFloat(DominoTuning.shotRadius), colorHex: 0xFFE9B0))162 private let launcherRing = SKShapeNode(circleOfRadius: 19)163 private let powerRing = SKShapeNode(circleOfRadius: 19)164 private let band = SKSpriteNode(color: UIColor(hex: 0xFFE9B0), size: CGSize(width: 1, height: 3))165 private var dots: [SKSpriteNode] = []166167 init(services: ArcadeServices, level: DominoLevel, session: DominoSession) {168 self.level = level169 self.session = session170 tracker = DominoRunTracker(level: level)171 super.init(services: services, perfName: "dominoCity-level\(level.id)")172 backgroundColor = UIColor(hex: DominoArt.night)173 physicsWorld.gravity = CGVector(dx: 0, dy: -DominoTuning.gravity / 150)174 physicsWorld.contactDelegate = self175 world.addChild(cam)176 camera = cam177 sky.zPosition = -100178 cam.addChild(sky)179 addChild(stage)180 buildBackdrop()181 buildLauncher()182 buildPieces()183 layout()184 // `-ORIXDominoAim YES` shows the aiming preview of the reference shot (screenshots).185 if LaunchOptions.flag("DominoAim"), let shot = level.solution.first {186 aim = (shot.angle, max(shot.power, 0.35))187 showAim()188 }189 }190191 // MARK: Layout192193 override func layout() {194 guard size.width > 0, size.height > 0 else { return }195 let top = safeInsets.top + 92196 let bottom = safeInsets.bottom + 84197 let available = max(120, size.height - top - bottom)198 let scale = max(CGFloat(DominoTuning.stageWidth) / size.width, CGFloat(DominoTuning.stageHeight) / available)199 cam.setScale(scale)200 // Map the stage centre onto the centre of the free area between the HUD and the bottom controls.201 let screenCentre = CGPoint(x: size.width / 2, y: bottom + available / 2)202 worldRestPosition = .zero203 cam.position = CGPoint(x: CGFloat(DominoTuning.stageWidth) / 2 - (screenCentre.x - size.width / 2) * scale,204 y: CGFloat(DominoTuning.stageHeight) / 2 - (screenCentre.y - size.height / 2) * scale)205 sky.size = CGSize(width: size.width + 60, height: size.height + 60)206 }207208 // MARK: Building209210 private func buildBackdrop() {211 let backdrop = SKNode()212 backdrop.zPosition = -50213 backdrop.addChild(DominoArt.skyline(levelID: level.id))214 let street = SKSpriteNode(color: UIColor(hex: 0x1A1030), size: CGSize(width: 1400, height: 700))215 street.anchorPoint = CGPoint(x: 0.5, y: 1)216 street.position = CGPoint(x: 200, y: DominoTuning.groundTop)217 street.zPosition = -20218 backdrop.addChild(street)219 let curb = SKSpriteNode(color: UIColor(hex: 0xFFB341), size: CGSize(width: 1400, height: 2))220 curb.anchorPoint = CGPoint(x: 0.5, y: 1)221 curb.position = street.position222 curb.zPosition = -19223 backdrop.addChild(curb)224 for i in 0..<12 {225 let dash = SKSpriteNode(color: UIColor.white.withAlphaComponent(0.10), size: CGSize(width: 26, height: 3))226 dash.position = CGPoint(x: -100 + Double(i) * 56, y: DominoTuning.groundTop - 22)227 dash.zPosition = -18228 backdrop.addChild(dash)229 }230 addChild(backdrop)231232 // Solid world bounds: street, side walls.233 let bounds = SKNode()234 let ground = SKPhysicsBody(rectangleOf: CGSize(width: 1400, height: 200), center: CGPoint(x: 200, y: DominoTuning.groundTop - 100))235 let left = SKPhysicsBody(rectangleOf: CGSize(width: 40, height: 1600), center: CGPoint(x: -20, y: 600))236 let right = SKPhysicsBody(rectangleOf: CGSize(width: 40, height: 1600), center: CGPoint(x: DominoTuning.stageWidth + 20, y: 600))237 let body = SKPhysicsBody(bodies: [ground, left, right])238 configureFixed(body)239 bounds.physicsBody = body240 bounds.name = "bounds"241 addChild(bounds)242 }243244 private func configureFixed(_ body: SKPhysicsBody, restitution: CGFloat = 0.08) {245 body.isDynamic = false246 body.friction = 0.85247 body.restitution = restitution248 body.categoryBitMask = Category.fixed249 body.collisionBitMask = Category.piece | Category.shot250 body.contactTestBitMask = 0251 }252253 private func configureSensor(_ body: SKPhysicsBody) {254 body.isDynamic = false255 body.categoryBitMask = Category.sensor256 body.collisionBitMask = 0257 body.contactTestBitMask = Category.piece | Category.shot258 }259260 private func configureDynamic(_ body: SKPhysicsBody, density: CGFloat, friction: CGFloat, restitution: CGFloat) {261 body.density = density262 body.friction = friction263 body.restitution = restitution264 body.linearDamping = 0.05265 body.angularDamping = 0.12266 body.categoryBitMask = Category.piece267 body.collisionBitMask = Category.fixed | Category.piece | Category.shot268 body.contactTestBitMask = Category.fixed | Category.piece | Category.shot | Category.sensor269 body.allowsRotation = true270 }271272 private func buildPieces() {273 switchLinked = Set(level.pieces.filter { $0.kind == .switchPad }.flatMap(\.links))274 for piece in level.pieces {275 pieces[piece.id] = piece276 let node = makeNode(piece)277 node.name = "p\(piece.id)"278 node.position = CGPoint(x: piece.x, y: piece.y)279 node.zRotation = CGFloat(piece.angle * .pi / 180)280 stage.addChild(node)281 pieceNodes[piece.id] = node282 if piece.kind.isDynamic { startPose[piece.id] = (node.position, node.zRotation) }283 if piece.kind == .wreckingBall { attachRope(node, piece) }284 }285 for (id, node) in pieceNodes where pieces[id]?.kind.isDynamic == true { node.physicsBody?.isResting = true }286 }287288 private func makeNode(_ piece: DominoPiece) -> SKNode {289 let size = CGSize(width: piece.w, height: piece.h)290 let variant = DominoArt.palette[(piece.id * 3 + level.id) % DominoArt.palette.count]291 switch piece.kind {292 case .ledge:293 let node = SKSpriteNode(texture: DominoArt.ledge(width: size.width, height: size.height), size: size)294 let body = SKPhysicsBody(rectangleOf: size)295 configureFixed(body)296 node.physicsBody = body297 node.zPosition = 5298 return node299 case .domino, .goldDomino:300 let isGold = piece.kind == .goldDomino301 let node = SKSpriteNode(texture: DominoArt.slab(width: size.width, height: size.height, colorHex: isGold ? DominoArt.gold : variant, gold: isGold), size: size)302 let body = SKPhysicsBody(rectangleOf: size)303 configureDynamic(body, density: 1.2, friction: 0.55, restitution: 0.02)304 node.physicsBody = body305 node.zPosition = 20306 if isGold { addHalo(to: node, radius: 26) }307 return node308 case .block, .goldBlock:309 let isGold = piece.kind == .goldBlock310 let node = SKSpriteNode(texture: DominoArt.slab(width: size.width, height: size.height, colorHex: isGold ? DominoArt.gold : variant, gold: isGold), size: size)311 let body = SKPhysicsBody(rectangleOf: size)312 configureDynamic(body, density: 0.9, friction: 0.8, restitution: 0.02)313 node.physicsBody = body314 node.zPosition = 20315 if isGold { addHalo(to: node, radius: 26) }316 return node317 case .ball:318 let radius = CGFloat(piece.w / 2)319 let node = SKSpriteNode(texture: DominoArt.orb(radius: radius, colorHex: 0x7FD8FF), size: CGSize(width: radius * 2, height: radius * 2))320 let body = SKPhysicsBody(circleOfRadius: radius)321 configureDynamic(body, density: 1.4, friction: 0.35, restitution: 0.12)322 body.angularDamping = 0.05323 body.isDynamic = !piece.held324 node.physicsBody = body325 node.zPosition = 22326 if piece.held, switchLinked.contains(piece.id) { addLatch(to: node, radius: radius) }327 return node328 case .plank:329 let node = SKSpriteNode(texture: DominoArt.plank(width: size.width, height: size.height), size: size)330 let body = SKPhysicsBody(rectangleOf: size)331 configureDynamic(body, density: 0.8, friction: 0.95, restitution: 0.02)332 node.physicsBody = body333 node.zPosition = 18334 return node335 case .bell:336 let node = SKSpriteNode(texture: DominoArt.beacon(lit: false), size: CGSize(width: 36, height: 36))337 let body = SKPhysicsBody(circleOfRadius: 17)338 configureSensor(body)339 node.physicsBody = body340 node.zPosition = 15341 addHalo(to: node, radius: 28)342 return node343 case .gem:344 let node = SKSpriteNode(texture: DominoArt.gem, size: CGSize(width: 22, height: 22))345 let body = SKPhysicsBody(circleOfRadius: 14)346 configureSensor(body)347 node.physicsBody = body348 node.zPosition = 15349 if !reduceMotion {350 node.run(.repeatForever(.sequence([.moveBy(x: 0, y: 4, duration: 0.8), .moveBy(x: 0, y: -4, duration: 0.8)])))351 }352 return node353 case .switchPad:354 let node = SKSpriteNode(texture: DominoArt.switchPad(fired: false), size: CGSize(width: 34, height: 34))355 let body = SKPhysicsBody(circleOfRadius: 16)356 configureSensor(body)357 node.physicsBody = body358 node.zPosition = 15359 return node360 case .gate:361 let node = SKSpriteNode(texture: DominoArt.gate(width: size.width, height: size.height), size: size)362 let body = SKPhysicsBody(rectangleOf: size)363 configureFixed(body)364 node.physicsBody = body365 node.zPosition = 16366 return node367 case .tar:368 let node = SKSpriteNode(texture: DominoArt.tar(width: size.width, height: size.height), size: size)369 let body = SKPhysicsBody(rectangleOf: CGSize(width: max(4, size.width - 6), height: size.height))370 configureSensor(body)371 node.physicsBody = body372 node.zPosition = 6373 return node374 case .bouncer:375 let node = SKSpriteNode(texture: DominoArt.bouncer(width: size.width, height: size.height), size: size)376 let body = SKPhysicsBody(rectangleOf: size)377 configureFixed(body, restitution: 0.4)378 body.contactTestBitMask = Category.piece | Category.shot379 node.physicsBody = body380 node.zPosition = 6381 return node382 case .wreckingBall:383 let radius = CGFloat(piece.w / 2)384 let node = SKSpriteNode(texture: DominoArt.orb(radius: radius, colorHex: 0x8A93B8), size: CGSize(width: radius * 2, height: radius * 2))385 let body = SKPhysicsBody(circleOfRadius: radius)386 configureDynamic(body, density: 3.2, friction: 0.4, restitution: 0.05)387 body.linearDamping = 0.25388 body.isDynamic = !piece.held389 node.physicsBody = body390 node.zPosition = 24391 return node392 }393 }394395 private func addHalo(to node: SKNode, radius: CGFloat) {396 let halo = SKSpriteNode(texture: TextureFactory.softDot, size: CGSize(width: radius * 2.6, height: radius * 2.6))397 halo.color = UIColor(hex: DominoArt.gold)398 halo.colorBlendFactor = 1399 halo.blendMode = .add400 halo.alpha = 0.5401 halo.zPosition = -1402 halo.name = "halo"403 node.addChild(halo)404 if !reduceMotion {405 halo.run(.repeatForever(.sequence([.fadeAlpha(to: 0.22, duration: 0.9), .fadeAlpha(to: 0.5, duration: 0.9)])))406 }407 }408409 /// Small clamp drawn on held balls so it is clear a switch must release them.410 private func addLatch(to node: SKNode, radius: CGFloat) {411 let latch = SKShapeNode(circleOfRadius: radius + 4)412 latch.strokeColor = UIColor(hex: 0xFF5470)413 latch.lineWidth = 2414 latch.fillColor = .clear415 latch.name = "latch"416 latch.zPosition = 1417 node.addChild(latch)418 }419420 private func attachRope(_ node: SKNode, _ piece: DominoPiece) {421 let anchorPoint = CGPoint(x: piece.anchorX, y: piece.anchorY)422 let anchor = SKSpriteNode(color: UIColor(hex: 0x8A93B8), size: CGSize(width: 14, height: 8))423 anchor.position = anchorPoint424 anchor.zPosition = 12425 let anchorBody = SKPhysicsBody(circleOfRadius: 3)426 anchorBody.isDynamic = false427 anchorBody.categoryBitMask = 0428 anchorBody.collisionBitMask = 0429 anchor.physicsBody = anchorBody430 stage.addChild(anchor)431 if let body = node.physicsBody {432 physicsWorld.add(SKPhysicsJointPin.joint(withBodyA: anchorBody, bodyB: body, anchor: anchorPoint))433 }434 let line = SKSpriteNode(color: UIColor(hex: 0x8A93B8), size: CGSize(width: 2.5, height: 1))435 line.anchorPoint = CGPoint(x: 0.5, y: 0)436 line.zPosition = 11437 stage.addChild(line)438 ropes.append((node, anchorPoint, line))439 if piece.held { addLatch(to: node, radius: CGFloat(piece.w / 2)) }440 updateRopes()441 }442443 private func updateRopes() {444 for rope in ropes {445 let dx = rope.ball.position.x - rope.anchor.x, dy = rope.ball.position.y - rope.anchor.y446 rope.line.position = rope.anchor447 rope.line.size.height = hypot(dx, dy)448 rope.line.zRotation = atan2(dy, dx) - .pi / 2449 }450 }451452 private func buildLauncher() {453 launcher.position = CGPoint(x: level.launcherX, y: level.launcherY)454 launcher.zPosition = 40455 launcherRing.strokeColor = UIColor(hex: 0xFFE9B0).withAlphaComponent(0.7)456 launcherRing.lineWidth = 2457 launcherRing.fillColor = UIColor(hex: 0xFFB341).withAlphaComponent(0.12)458 launcher.addChild(launcherRing)459 powerRing.strokeColor = UIColor(hex: 0xFF5E7E)460 powerRing.lineWidth = 3461 powerRing.fillColor = .clear462 powerRing.isHidden = true463 launcher.addChild(powerRing)464 launcher.addChild(launcherBall)465 band.anchorPoint = CGPoint(x: 0, y: 0.5)466 band.alpha = 0.7467 band.isHidden = true468 launcher.addChild(band)469 stage.addChild(launcher)470 for index in 0..<16 {471 let dot = SKSpriteNode(texture: TextureFactory.softDot, size: CGSize(width: 9, height: 9))472 dot.color = UIColor(hex: 0xFFF3C4)473 dot.colorBlendFactor = 1474 dot.alpha = 1 - CGFloat(index) / 20475 dot.zPosition = 39476 dot.isHidden = true477 stage.addChild(dot)478 dots.append(dot)479 }480 pulseLauncher()481 }482483 private func pulseLauncher() {484 launcherRing.removeAllActions()485 launcherRing.setScale(1)486 guard !reduceMotion else { return }487 launcherRing.run(.repeatForever(.sequence([.scale(to: 1.18, duration: 0.7), .scale(to: 1, duration: 0.7)])))488 }489490 // MARK: Restart491492 /// Rebuilds every piece and resets the run. One tap, no loading.493 func restart() {494 physicsWorld.removeAllJoints()495 stage.removeAllChildren()496 pieceNodes.removeAll()497 pieces.removeAll()498 startPose.removeAll()499 ropes.removeAll()500 shots.removeAll()501 pending.removeAll()502 dots.removeAll()503 launcher.removeAllChildren()504 tracker = DominoRunTracker(level: level)505 phase = .aiming506 clock = 0507 launchClock = 0508 readyClock = 0509 clearedClock = nil510 stillTime = 0511 botIndex = 0512 aimStart = nil513 aim = nil514 buildLauncher()515 buildPieces()516 launcherBall.isHidden = false517 session.targetsHit = 0518 session.chain = 0519 session.gems = 0520 session.impulsesLeft = level.impulses521 session.canAim = true522 session.isAiming = false523 session.hasLaunched = false524 session.result = nil525 }526527 // MARK: Input528529 override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {530 guard phase == .aiming, botShots == nil, aimStart == nil, let touch = touches.first, let view else { return }531 aimStart = touch.location(in: view)532 lastPowerStep = 0533 }534535 override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {536 guard phase == .aiming, let start = aimStart, let touch = touches.first, let view else { return }537 let now = touch.location(in: view)538 // Pull back: the launch goes opposite to the drag (view y grows downward).539 let dx = Double(start.x - now.x), dy = Double(now.y - start.y)540 let length = hypot(dx, dy)541 guard length > 22 else {542 aim = nil543 showAim()544 return545 }546 let power = ((length - 22) / 120).clamped(0, 1)547 aim = (atan2(dy, dx) * 180 / .pi, power)548 let step = Int(power * 8)549 if step != lastPowerStep {550 lastPowerStep = step551 services.haptics.play(.select)552 }553 showAim()554 }555556 override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {557 guard aimStart != nil else { return }558 aimStart = nil559 let chosen = aim560 aim = nil561 showAim()562 if phase == .aiming, let chosen { fire(DominoShot(angle: chosen.angle, power: chosen.power)) }563 }564565 override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {566 aimStart = nil567 aim = nil568 showAim()569 }570571 private func showAim() {572 session.isAiming = aim != nil573 guard let aim else {574 dots.forEach { $0.isHidden = true }575 powerRing.isHidden = true576 band.isHidden = true577 return578 }579 let origin = (x: level.launcherX, y: level.launcherY)580 var visible = true581 var previous = CGPoint(x: origin.x, y: origin.y)582 for (index, dot) in dots.enumerated() {583 let p = DominoTuning.trajectoryPoint(from: origin, angleDegrees: aim.angle, power: aim.power, time: Double(index + 1) * 0.055)584 if p.y < DominoTuning.groundTop || p.x < 0 || p.x > DominoTuning.stageWidth { visible = false }585 // The preview ends where the ball would first meet something solid.586 if visible {587 let end = CGPoint(x: p.x, y: p.y)588 physicsWorld.enumerateBodies(alongRayStart: previous, end: end) { body, _, _, stop in589 if body.categoryBitMask & (Category.fixed | Category.piece) != 0 {590 visible = false591 stop.pointee = true592 }593 }594 previous = end595 }596 dot.isHidden = !visible597 dot.position = CGPoint(x: p.x, y: p.y)598 }599 powerRing.isHidden = false600 powerRing.setScale(0.7 + CGFloat(aim.power) * 0.9)601 powerRing.strokeColor = UIColor(hex: 0xFFE9B0).blended(with: UIColor(hex: 0xFF5E7E), CGFloat(aim.power))602 band.isHidden = false603 band.size.width = 14 + CGFloat(aim.power) * 46604 band.zRotation = CGFloat(aim.angle * .pi / 180) + .pi605 }606607 // MARK: Launch608609 /// Fires one impulse from the launcher. Returns `false` when none is available.610 @discardableResult611 func fire(_ shot: DominoShot) -> Bool {612 guard phase == .aiming, tracker.useImpulse() else { return false }613 let radius = CGFloat(DominoTuning.shotRadius)614 let ball = SKSpriteNode(texture: DominoArt.orb(radius: radius, colorHex: 0xFFE9B0), size: CGSize(width: radius * 2, height: radius * 2))615 ball.name = "shot"616 ball.position = launcher.position617 ball.zPosition = 30618 let body = SKPhysicsBody(circleOfRadius: radius)619 body.density = 3620 body.friction = 0.45621 body.restitution = 0.2622 body.linearDamping = 0.02623 body.angularDamping = 0.08624 body.usesPreciseCollisionDetection = true625 body.categoryBitMask = Category.shot626 body.collisionBitMask = Category.fixed | Category.piece | Category.shot627 body.contactTestBitMask = Category.fixed | Category.piece | Category.sensor628 let speed = DominoTuning.launchSpeed(power: shot.power)629 let radians = shot.angle * .pi / 180630 body.velocity = CGVector(dx: cos(radians) * speed, dy: sin(radians) * speed)631 ball.physicsBody = body632 stage.addChild(ball)633 shots.append(ball)634 let glow = SKSpriteNode(texture: TextureFactory.softDot, size: CGSize(width: radius * 4.4, height: radius * 4.4))635 glow.color = UIColor(hex: 0xFFB341)636 glow.colorBlendFactor = 1637 glow.blendMode = .add638 glow.alpha = 0.55639 glow.zPosition = -1640 ball.addChild(glow)641642 phase = .flying643 launchClock = clock644 stillTime = 0645 launcherBall.isHidden = true646 launcherRing.removeAllActions()647 session.impulsesLeft = tracker.impulsesLeft648 session.canAim = false649 session.hasLaunched = true650 services.audio.play(.launch, pitch: Float(0.85 + shot.power * 0.4))651 services.haptics.play(.impact(Float(0.4 + shot.power * 0.6)))652 burst(at: launcher.position, in: stage, color: UIColor(hex: 0xFFE9B0), count: 10, speed: 110, lifetime: 0.35, scale: 0.3, gravity: 0)653 return true654 }655656 // MARK: Simulation657658 override func tick(dt: TimeInterval) {659 frameDt = dt660 guard phase != .finished else { return }661 clock += dt662 if let botShots, phase == .aiming {663 if botIndex < botShots.count {664 if clock - readyClock >= botShots[botIndex].delay {665 fire(botShots[botIndex])666 botIndex += 1667 }668 } else if !tracker.cleared, (stillTime > 1 && clock - readyClock > 2) || clock - readyClock > 16 {669 finish()670 }671 }672 }673674 override func didSimulatePhysics() {675 guard phase != .finished else { return }676 processContacts()677 updateRopes()678 scanPieces()679 advancePhase()680 }681682 private func scanPieces() {683 var fastest: CGFloat = 0684 for (id, node) in pieceNodes {685 guard let start = startPose[id], let body = node.physicsBody, body.isDynamic else { continue }686 if node.position.y < -120 {687 node.removeFromParent()688 pieceNodes[id] = nil689 registerChain(id, at: CGPoint(x: node.position.x, y: DominoTuning.groundTop))690 registerTargetIfNeeded(id, node: node)691 continue692 }693 let moved = hypot(node.position.x - start.position.x, node.position.y - start.position.y)694 let turned = abs(node.zRotation - start.rotation)695 let kind = pieces[id]?.kind696 let rolls = kind == .ball || kind == .wreckingBall697 if moved > 10 || (!rolls && turned > 0.35) { registerChain(id, at: node.position) }698 if kind?.isTarget == true, moved > 22 || turned > 0.6 { registerTargetIfNeeded(id, node: node) }699 let velocity = body.velocity700 fastest = max(fastest, hypot(velocity.dx, velocity.dy) + abs(body.angularVelocity) * 12)701 }702 for shot in shots {703 guard let body = shot.physicsBody else { continue }704 if shot.position.y < -120 { shot.physicsBody = nil; shot.removeFromParent(); continue }705 fastest = max(fastest, hypot(body.velocity.dx, body.velocity.dy))706 }707 shots.removeAll { $0.parent == nil }708 stillTime = fastest < 14 ? stillTime + frameDt : 0709 }710711 private func advancePhase() {712 if tracker.cleared {713 let since = clock - (clearedClock ?? clock)714 if clearedClock == nil { clearedClock = clock }715 if (stillTime > 0.5 && since > 0.9) || since > 3.5 { finish() }716 return717 }718 guard phase == .flying else { return }719 let sinceLaunch = clock - launchClock720 if tracker.impulsesLeft > 0 {721 if sinceLaunch > 1.2 { readyNextImpulse() }722 } else if (stillTime > 0.7 && sinceLaunch > 1.0) || sinceLaunch > 10 {723 finish()724 }725 }726727 private func readyNextImpulse() {728 phase = .aiming729 readyClock = clock730 launcherBall.isHidden = false731 launcherBall.setScale(reduceMotion ? 1 : 0.2)732 launcherBall.run(.scale(to: 1, duration: 0.18))733 pulseLauncher()734 session.canAim = true735 services.audio.play(.tick)736 }737738 private func finish() {739 guard phase != .finished else { return }740 phase = .finished741 aimStart = nil742 aim = nil743 showAim()744 session.canAim = false745 let result = DominoResult(level: level, stats: tracker.stats, duration: clock)746 if result.cleared {747 services.audio.play(.win)748 services.haptics.play(.success)749 } else {750 services.audio.play(.fail)751 services.haptics.play(.failure)752 }753 writePerfReport()754 session.result = result755 }756757 /// Floating score text in the rounded system face.758 private func popText(_ text: String, at point: CGPoint, in parent: SKNode, color: UIColor, size: CGFloat) {759 let base = UIFont.systemFont(ofSize: size, weight: .heavy)760 let font = base.fontDescriptor.withDesign(.rounded).map { UIFont(descriptor: $0, size: size) } ?? base761 let label = SKLabelNode(attributedText: NSAttributedString(string: text, attributes: [762 .font: font, .foregroundColor: color, .strokeColor: UIColor(hex: DominoArt.night), .strokeWidth: -3,763 ]))764 label.position = point765 label.zPosition = 600766 label.verticalAlignmentMode = .center767 parent.addChild(label)768 label.setScale(reduceMotion ? 1 : 0.6)769 label.run(.sequence([770 .group([.moveBy(x: 0, y: reduceMotion ? 0 : 38, duration: 0.8), .scale(to: 1, duration: 0.14),771 .sequence([.wait(forDuration: 0.5), .fadeOut(withDuration: 0.3)])]),772 .removeFromParent(),773 ]))774 }775776 // MARK: Objectives777778 private func registerChain(_ id: Int, at point: CGPoint) {779 guard tracker.registerChain(id) else { return }780 let count = tracker.stats.chain781 session.chain = count782 if count.isMultiple(of: 5) {783 services.audio.play(.combo, pitch: Float(min(1.8, 0.9 + Double(count) * 0.02)))784 services.haptics.play(.combo(count / 5))785 popText("\(count) chain", at: CGPoint(x: point.x, y: point.y + 34), in: stage, color: UIColor(hex: 0x7FD8FF), size: 15)786 }787 }788789 private func registerTargetIfNeeded(_ id: Int, node: SKNode) {790 guard tracker.registerTarget(id) else { return }791 let count = tracker.stats.targetsHit792 session.targetsHit = count793 node.childNode(withName: "halo")?.removeFromParent()794 let point = node.parent == nil ? CGPoint(x: node.position.x.clamped(10, 390), y: DominoTuning.groundTop + 10) : node.position795 burst(at: point, in: stage, color: UIColor(hex: DominoArt.gold), count: 26, speed: 190, lifetime: 0.7, scale: 0.45)796 burst(at: point, in: stage, color: UIColor(hex: DominoArt.gold), count: 10, speed: 120, lifetime: 0.9, scale: 0.5,797 texture: TextureFactory.chip, additive: false)798 popText("+\(DominoRules.targetPoints)", at: CGPoint(x: point.x, y: point.y + 30), in: stage, color: UIColor(hex: DominoArt.gold), size: 19)799 services.audio.play(.star, pitch: Float(0.9 + Double(count) * 0.1))800 services.haptics.play(.combo(3 + count))801 shake(0.3)802 }803804 // MARK: Contacts805806 func didBegin(_ contact: SKPhysicsContact) {807 guard phase != .finished, let a = contact.bodyA.node?.name, let b = contact.bodyB.node?.name else { return }808 pending.append(Touch(a: a, b: b, impulse: contact.collisionImpulse, point: contact.contactPoint))809 }810811 private func pieceID(_ name: String) -> Int? { name.hasPrefix("p") ? Int(name.dropFirst()) : nil }812813 private func processContacts() {814 guard !pending.isEmpty else { return }815 let batch = pending816 pending.removeAll(keepingCapacity: true)817 var loudest: CGFloat = 0818 var loudestPoint = CGPoint.zero819 for touch in batch {820 let idA = pieceID(touch.a), idB = pieceID(touch.b)821 let kindA = idA.flatMap { pieces[$0]?.kind }, kindB = idB.flatMap { pieces[$0]?.kind }822 releaseParkedBall(idA, kindA)823 releaseParkedBall(idB, kindB)824 if let idA, let kindA, handleSpecial(id: idA, kind: kindA, otherName: touch.b, otherKind: kindB, point: touch.point) { continue }825 if let idB, let kindB, handleSpecial(id: idB, kind: kindB, otherName: touch.a, otherKind: kindA, point: touch.point) { continue }826 if touch.impulse > loudest {827 loudest = touch.impulse828 loudestPoint = touch.point829 }830 }831 // One impact sound per frame, from the hardest hit, pitched by how far the chain has run.832 guard loudest > 0.012 else { return }833 let strength = Float(min(1, loudest / 0.5))834 let pitch = Float(0.85 + Double(tracker.stats.chain % 9) * 0.045)835 if strength > 0.55 {836 services.audio.play(.thud, pitch: pitch, volume: strength)837 shake(CGFloat(strength) * 0.35)838 } else {839 services.audio.play(.knock, pitch: pitch, volume: 0.35 + strength)840 }841 if strength > 0.12 { services.haptics.play(.impact(strength)) }842 if strength > 0.2 {843 burst(at: convert(loudestPoint, to: stage), in: stage, color: UIColor(hex: 0xE8D9FF), count: Int(4 + strength * 8), speed: 70,844 lifetime: 0.4, scale: 0.3, gravity: -120, additive: false)845 }846 }847848 /// A parked ball with no switch starts rolling the moment anything touches it.849 private func releaseParkedBall(_ id: Int?, _ kind: DominoPieceKind?) {850 guard let id, kind == .ball, pieces[id]?.held == true, !switchLinked.contains(id),851 let body = pieceNodes[id]?.physicsBody, !body.isDynamic else { return }852 body.isDynamic = true853 body.isResting = false854 }855856 /// Handles sensors, hazards and bouncers. Returns `true` when the contact was one of those.857 private func handleSpecial(id: Int, kind: DominoPieceKind, otherName: String, otherKind: DominoPieceKind?, point: CGPoint) -> Bool {858 guard let node = pieceNodes[id] else { return kind == .bell || kind == .gem || kind == .switchPad || kind == .tar }859 let otherIsBall = otherName == "shot" || otherKind == .ball || otherKind == .wreckingBall860 switch kind {861 case .bell:862 if tracker.targetIDs.contains(id), !tracker.hitTargets.contains(id) {863 (node as? SKSpriteNode)?.texture = DominoArt.beacon(lit: true)864 if !reduceMotion { node.run(.sequence([.scale(to: 1.35, duration: 0.08), .scale(to: 1, duration: 0.18)])) }865 registerTargetIfNeeded(id, node: node)866 }867 return true868 case .gem:869 if tracker.registerGem(id) {870 session.gems = tracker.stats.gems871 burst(at: node.position, in: stage, color: UIColor(hex: 0x7FD8FF), count: 16, speed: 130, lifetime: 0.5, scale: 0.35)872 popText("+\(DominoRules.gemPoints)", at: CGPoint(x: node.position.x, y: node.position.y + 22), in: stage, color: UIColor(hex: 0x7FD8FF), size: 16)873 services.audio.play(.gem)874 services.haptics.play(.select)875 node.physicsBody = nil876 node.removeAllActions()877 node.run(.sequence([.group([.scale(to: 1.8, duration: 0.16), .fadeOut(withDuration: 0.16)]), .removeFromParent()]))878 pieceNodes[id] = nil879 }880 return true881 case .switchPad:882 if tracker.registerSwitch(id) { fireSwitch(id, node: node) }883 return true884 case .tar:885 guard otherIsBall else { return true }886 let victim: SKNode? = otherName == "shot"887 ? shots.filter { $0.physicsBody != nil }.min { abs($0.position.x - point.x) + abs($0.position.y - point.y) < abs($1.position.x - point.x) + abs($1.position.y - point.y) }888 : pieceID(otherName).flatMap { pieceNodes[$0] }889 if let victim, victim.physicsBody != nil {890 if let victimID = victim.name.flatMap(pieceID) {891 registerChain(victimID, at: victim.position)892 pieceNodes[victimID] = nil893 }894 victim.physicsBody = nil895 victim.run(.sequence([.group([.scale(to: 0.2, duration: 0.3), .moveBy(x: 0, y: -8, duration: 0.3), .fadeOut(withDuration: 0.3)]), .removeFromParent()]))896 burst(at: victim.position, in: stage, color: UIColor(hex: 0xC86BFF), count: 16, speed: 120, lifetime: 0.5, scale: 0.4, spread: .pi * 0.7)897 services.audio.play(.hiss)898 services.haptics.play(.warning)899 }900 return true901 case .bouncer:902 guard otherIsBall else { return false }903 let body: SKPhysicsBody? = otherName == "shot"904 ? shots.compactMap(\.physicsBody).min { abs($0.node!.position.x - node.position.x) < abs($1.node!.position.x - node.position.x) }905 : pieceID(otherName).flatMap { pieceNodes[$0]?.physicsBody }906 if let body, let ball = body.node, ball.position.y > node.position.y {907 body.velocity = CGVector(dx: body.velocity.dx, dy: DominoTuning.bouncerSpeed)908 if !reduceMotion { node.run(.sequence([.scaleY(to: 0.55, duration: 0.05), .scaleY(to: 1, duration: 0.16)])) }909 burst(at: CGPoint(x: ball.position.x, y: node.position.y + 6), in: stage, color: UIColor(hex: 0x8CFFE2), count: 12, speed: 150,910 lifetime: 0.4, scale: 0.3, spread: .pi * 0.6)911 services.audio.play(.pass, pitch: 1.5)912 services.haptics.play(.impact(0.7))913 }914 return true915 default:916 return false917 }918 }919920 private func fireSwitch(_ id: Int, node: SKNode) {921 (node as? SKSpriteNode)?.texture = DominoArt.switchPad(fired: true)922 if !reduceMotion { node.run(.sequence([.scale(to: 0.8, duration: 0.06), .scale(to: 1, duration: 0.14)])) }923 burst(at: node.position, in: stage, color: UIColor(hex: 0x4DE3A1), count: 14, speed: 130, lifetime: 0.45, scale: 0.35)924 services.audio.play(.confirm)925 services.haptics.play(.impact(0.8))926 for link in pieces[id]?.links ?? [] {927 guard let target = pieceNodes[link], let piece = pieces[link] else { continue }928 if piece.kind == .gate {929 burst(at: target.position, in: stage, color: UIColor(hex: 0xFF5470), count: 18, speed: 140, lifetime: 0.5, scale: 0.4, additive: false)930 target.physicsBody = nil931 target.run(.sequence([.group([.fadeOut(withDuration: 0.2), .scaleX(to: 0.2, duration: 0.2)]), .removeFromParent()]))932 pieceNodes[link] = nil933 services.audio.play(.crumble)934 } else if piece.held {935 target.childNode(withName: "latch")?.removeFromParent()936 target.physicsBody?.isDynamic = true937 target.physicsBody?.isResting = false938 services.audio.play(.whoosh)939 }940 }941 }942}943