@vesviet/agent-skills 5.7.3 → 5.10.0

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 (241) hide show
  1. package/INDEX.md +21 -18
  2. package/README.md +11 -10
  3. package/VERSION +1 -1
  4. package/adapters/antigravity/ANTIGRAVITY.md +89 -4
  5. package/adapters/antigravity/INDEX_TIER1.json +1294 -0
  6. package/adapters/antigravity/a2a-config.template.yaml +22 -8
  7. package/adapters/antigravity/role-skill-index.json +48 -19
  8. package/adapters/claude/CLAUDE_ADAPTER.md +1 -1
  9. package/adapters/claude/settings.template.json +7 -3
  10. package/adapters/cursor/hooks.template.json +3 -1
  11. package/core/contracts/README.md +4 -1
  12. package/core/contracts/schemas/INDEX.md +7 -1
  13. package/core/contracts/schemas/a2a-artifact.json +9 -2
  14. package/core/contracts/schemas/a2a-jsonrpc-envelope.json +7 -2
  15. package/core/contracts/schemas/a2a-task-progress.json +15 -4
  16. package/core/contracts/schemas/a2a-task.json +11 -3
  17. package/core/contracts/schemas/agent-card.json +48 -1
  18. package/core/contracts/schemas/agent-skills-discovery.json +91 -0
  19. package/core/contracts/schemas/compliance-report.json +255 -0
  20. package/core/contracts/schemas/mcp-server-card.json +193 -0
  21. package/core/contracts/schemas/seo-content-brief.json +1 -1
  22. package/core/contracts/schemas/seo-weekly-board.json +1 -1
  23. package/core/contracts/schemas/series-article.json +1 -1
  24. package/core/policies/action-boundaries.yaml +334 -2
  25. package/core/policies/mcp-tool-map.yaml +61 -4
  26. package/core/roles/3d-graphics-engineer.md +5 -1
  27. package/core/roles/README.md +1 -1
  28. package/core/roles/agent-coordinator.md +21 -3
  29. package/core/roles/agent-discovery-engineer.md +27 -8
  30. package/core/roles/ai-systems-engineer.md +3 -1
  31. package/core/roles/aws-engineer.md +6 -8
  32. package/core/roles/backend-developer.md +5 -5
  33. package/core/roles/business-analyst.md +4 -2
  34. package/core/roles/cloudflare-engineer.md +4 -2
  35. package/core/roles/content-manager.md +3 -1
  36. package/core/roles/content-writer.md +3 -1
  37. package/core/roles/data-analyst.md +3 -1
  38. package/core/roles/data-engineer.md +3 -1
  39. package/core/roles/devops-engineer.md +9 -9
  40. package/core/roles/ecommerce-engineer.md +7 -7
  41. package/core/roles/frontend-developer.md +10 -8
  42. package/core/roles/game-developer.md +5 -3
  43. package/core/roles/mmo-engineer.md +8 -9
  44. package/core/roles/mobile-engineer.md +5 -3
  45. package/core/roles/product-manager.md +8 -9
  46. package/core/roles/project-manager.md +10 -13
  47. package/core/roles/prompt-engineer.md +6 -4
  48. package/core/roles/qa-engineer.md +9 -9
  49. package/core/roles/references/vietnam-accounting-specialist-review-checklist.md +6 -6
  50. package/core/roles/researcher.md +12 -14
  51. package/core/roles/reverse-engineer.md +5 -2
  52. package/core/roles/reviewer.md +7 -5
  53. package/core/roles/role-standard.md +23 -1
  54. package/core/roles/sdet.md +7 -5
  55. package/core/roles/security-engineer.md +9 -7
  56. package/core/roles/seo-analyst.md +9 -7
  57. package/core/roles/solution-architect.md +8 -9
  58. package/core/roles/sre.md +8 -6
  59. package/core/roles/system-engineer.md +20 -20
  60. package/core/roles/task-planner.md +8 -10
  61. package/core/roles/teacher.md +8 -6
  62. package/core/roles/technical-architect.md +10 -8
  63. package/core/roles/technical-lead.md +9 -7
  64. package/core/roles/technical-writer.md +8 -6
  65. package/core/roles/ui-ux-designer.md +8 -7
  66. package/core/roles/vietnam-accounting-specialist.md +26 -24
  67. package/core/roles/vietnam-legal-counsel.md +6 -4
  68. package/core/rules/code.md +11 -6
  69. package/core/skills/README.md +3 -2
  70. package/core/skills/agent/agent-a2a-protocol/SKILL.md +25 -93
  71. package/core/skills/agent/agent-memory-compaction/SKILL.md +27 -0
  72. package/core/skills/agent/architect-mcp-server/SKILL.md +35 -27
  73. package/core/skills/agent/configure-agent-commerce/SKILL.md +2 -0
  74. package/core/skills/agent/configure-agent-commerce/examples/ucp-commerce-manifest-and-endpoints.json +55 -0
  75. package/core/skills/agent/configure-agent-commerce/references/acp-ucp-agent-commerce-manifest-specs.md +66 -0
  76. package/core/skills/agent/configure-agent-skills/SKILL.md +60 -68
  77. package/core/skills/agent/manage-agent-identity/SKILL.md +2 -0
  78. package/core/skills/agent/manage-agent-identity/examples/agent-identity-spire-workload.yaml +72 -0
  79. package/core/skills/agent/manage-agent-identity/references/nhi-lifecycle-and-token-rotation.md +45 -0
  80. package/core/skills/ai/openrouter-task/SKILL.md +5 -5
  81. package/core/skills/ai-agent/agent-evaluation/resources/eval-benchmarks/eval-cases.json +529 -0
  82. package/core/skills/ai-agent/agent-evaluation/resources/eval-benchmarks/eval-manifest.yaml +61 -0
  83. package/core/skills/ai-agent/agent-evaluation/scripts/run-eval-benchmark.py +856 -0
  84. package/core/skills/ai-agent/agent-evaluation/tests/test_golden_benchmarks.py +248 -0
  85. package/core/skills/ai-agent/context-optimization/SKILL.md +61 -60
  86. package/core/skills/ai-agent/context-optimization/examples/context-pruner-and-reorderer.py +85 -0
  87. package/core/skills/ai-agent/context-optimization/references/token-budgeting-and-attention-allocation.md +47 -0
  88. package/core/skills/ai-agent/memory-hygiene/SKILL.md +13 -0
  89. package/core/skills/ai-agent/memory-hygiene/examples/memory-audit-and-compaction-routine.py +90 -0
  90. package/core/skills/ai-agent/memory-hygiene/references/agent-memory-vault-spec.md +137 -0
  91. package/core/skills/ai-agent/memory-hygiene/references/owasp-asi06-and-memory-poisoning-defense.md +38 -0
  92. package/core/skills/backend/add-api-endpoint/examples/express-zod-rfc9457-endpoint.md +329 -0
  93. package/core/skills/backend/add-api-endpoint/examples/kratos-go-clean-architecture-endpoint.md +405 -0
  94. package/core/skills/backend/add-api-endpoint/references/idempotency-and-rate-limiting.md +116 -0
  95. package/core/skills/backend/add-event-handler/SKILL.md +1 -1
  96. package/core/skills/backend/scaffold-new-service/SKILL.md +2 -1
  97. package/core/skills/backend/scaffold-new-service/references/deep-modules-and-seams.md +43 -0
  98. package/core/skills/business/elicit-requirements/SKILL.md +1 -0
  99. package/core/skills/commerce/handle-checkout-flow/SKILL.md +3 -1
  100. package/core/skills/commerce/handle-checkout-flow/examples/production-checkout-orchestrator.ts +185 -0
  101. package/core/skills/commerce/handle-checkout-flow/references/pci-dss-v4-and-agentic-checkout-specs.md +72 -0
  102. package/core/skills/commerce/integrate-payment-gateway/SKILL.md +3 -1
  103. package/core/skills/commerce/integrate-payment-gateway/examples/resilient-webhook-and-mpp-handler.ts +164 -0
  104. package/core/skills/commerce/integrate-payment-gateway/references/mpp-x402-and-webhook-security-specs.md +47 -0
  105. package/core/skills/commerce/manage-order-fulfillment/SKILL.md +3 -1
  106. package/core/skills/commerce/manage-order-fulfillment/examples/temporal-fulfillment-saga.ts +104 -0
  107. package/core/skills/commerce/manage-order-fulfillment/references/event-sourced-fulfillment-and-carrier-webhooks.md +58 -0
  108. package/core/skills/commerce/manage-product-catalog/SKILL.md +3 -1
  109. package/core/skills/commerce/manage-product-catalog/examples/hybrid-search-and-governance-pipeline.ts +120 -0
  110. package/core/skills/commerce/manage-product-catalog/references/semantic-vector-catalog-and-graphrag.md +54 -0
  111. package/core/skills/content/write-article/SKILL.md +1 -1
  112. package/core/skills/document/pdf/SKILL.md +1 -0
  113. package/core/skills/document/pdf/references/pdf-acroforms-and-pdfplumber-specs.md +54 -0
  114. package/core/skills/document/pdf/scripts/check_fillable_fields.py +144 -0
  115. package/core/skills/document/pdf/scripts/fill_fillable_fields.py +145 -0
  116. package/core/skills/documentation/configure-llms-txt/SKILL.md +2 -0
  117. package/core/skills/documentation/configure-llms-txt/examples/canonical-llms-txt-and-full-txt.md +45 -0
  118. package/core/skills/documentation/configure-llms-txt/references/llms-txt-and-llms-full-txt-standard.md +37 -0
  119. package/core/skills/documentation/write-documentation/SKILL.md +3 -1
  120. package/core/skills/documentation/write-documentation/examples/microservice-production-readme-and-api-docs.md +70 -0
  121. package/core/skills/documentation/write-documentation/references/diataxis-framework-and-doc-standards.md +62 -0
  122. package/core/skills/foundation/ai-risk-assessment/SKILL.md +3 -5
  123. package/core/skills/foundation/ai-risk-assessment/examples/genai-system-risk-register.md +67 -0
  124. package/core/skills/foundation/ai-risk-assessment/references/nist-ai-rmf-and-eu-ai-act-taxonomy.md +49 -0
  125. package/core/skills/foundation/conduct-research/SKILL.md +1 -1
  126. package/core/skills/foundation/discernment-nudge/SKILL.md +1 -0
  127. package/core/skills/foundation/plan-technical-delivery/SKILL.md +2 -1
  128. package/core/skills/foundation/release-notes/SKILL.md +2 -3
  129. package/core/skills/foundation/release-notes/examples/enterprise-platform-release-notes.md +42 -0
  130. package/core/skills/foundation/release-notes/references/keep-a-changelog-and-semver-governance.md +43 -0
  131. package/core/skills/foundation/systematic-debugging/SKILL.md +5 -0
  132. package/core/skills/foundation/write-tests/examples/anti-tautological-tdd-walkthrough.md +204 -0
  133. package/core/skills/foundation/write-tests/examples/testcontainers-kratos-integration-test.md +186 -0
  134. package/core/skills/foundation/write-tests/references/contract-and-chaos-testing.md +187 -0
  135. package/core/skills/frontend/INDEX.json +16 -0
  136. package/core/skills/frontend/add-page-route/SKILL.md +3 -1
  137. package/core/skills/frontend/add-page-route/examples/streaming-rsc-page-with-view-transition.tsx +133 -0
  138. package/core/skills/frontend/add-page-route/references/rsc-routing-and-view-transitions.md +72 -0
  139. package/core/skills/frontend/add-ui-component/SKILL.md +3 -1
  140. package/core/skills/frontend/add-ui-component/examples/compound-dialog-and-form-actions.tsx +193 -0
  141. package/core/skills/frontend/add-ui-component/references/react19-component-standards-and-anti-slop.md +55 -0
  142. package/core/skills/frontend/component-composition/SKILL.md +2 -1
  143. package/core/skills/frontend/component-composition/examples/headless-combobox-compound-component.tsx +207 -0
  144. package/core/skills/frontend/frontend-testing/SKILL.md +3 -1
  145. package/core/skills/frontend/frontend-testing/examples/playwright-e2e-with-msw-and-axe.spec.ts +87 -0
  146. package/core/skills/frontend/frontend-testing/references/playwright-msw-and-a11y-testing-standards.md +78 -0
  147. package/core/skills/frontend/implement-ai-disclosure/SKILL.md +118 -0
  148. package/core/skills/frontend/implement-webmcp/SKILL.md +3 -1
  149. package/core/skills/frontend/implement-webmcp/examples/webmcp-provider-and-hitl-modal.tsx +163 -0
  150. package/core/skills/frontend/implement-webmcp/references/webmcp-architecture-and-hitl-security.md +48 -0
  151. package/core/skills/frontend/integrate-api-client/SKILL.md +3 -1
  152. package/core/skills/frontend/integrate-api-client/examples/orval-query-and-streaming-mutation.ts +102 -0
  153. package/core/skills/frontend/integrate-api-client/references/orval-tanstack-query-and-streaming-specs.md +57 -0
  154. package/core/skills/frontend/setup-design-system/SKILL.md +3 -1
  155. package/core/skills/frontend/setup-design-system/examples/tailwind-v4-theme-and-dtcg-tokens.css +87 -0
  156. package/core/skills/frontend/setup-design-system/references/tailwind-v4-oklch-and-dtcg-tokens.md +61 -0
  157. package/core/skills/frontend/setup-visual-regression/SKILL.md +3 -1
  158. package/core/skills/frontend/setup-visual-regression/examples/visual-regression-playwright.config.ts +83 -0
  159. package/core/skills/frontend/setup-visual-regression/references/visual-regression-docker-and-masking-specs.md +46 -0
  160. package/core/skills/gamedev/abstract-input-actions/SKILL.md +2 -0
  161. package/core/skills/gamedev/abstract-input-actions/examples/input-action-manager.ts +85 -0
  162. package/core/skills/gamedev/abstract-input-actions/references/action-mapping-and-analog-deadzones.md +54 -0
  163. package/core/skills/gamedev/architect-ecs-systems/SKILL.md +2 -0
  164. package/core/skills/gamedev/architect-ecs-systems/examples/bevy-flecs-combat-system.rs +73 -0
  165. package/core/skills/gamedev/architect-ecs-systems/references/data-oriented-design-and-archetype-ecs.md +39 -0
  166. package/core/skills/gamedev/author-game-ai/SKILL.md +2 -0
  167. package/core/skills/gamedev/author-game-ai/examples/modular-behavior-tree-ai.ts +98 -0
  168. package/core/skills/gamedev/author-game-ai/references/behavior-trees-and-utility-ai-curves.md +47 -0
  169. package/core/skills/gamedev/configure-physics-collision/SKILL.md +2 -0
  170. package/core/skills/gamedev/configure-physics-collision/examples/kinematic-physics-substepping.cpp +100 -0
  171. package/core/skills/gamedev/configure-physics-collision/references/continuous-collision-detection-and-substepping.md +50 -0
  172. package/core/skills/gamedev/develop-gameplay-systems/SKILL.md +2 -0
  173. package/core/skills/gamedev/develop-gameplay-systems/examples/kinematic-character-controller.gd +86 -0
  174. package/core/skills/gamedev/develop-gameplay-systems/references/deterministic-gameplay-state-machines.md +42 -0
  175. package/core/skills/gamedev/implement-save-persistence/SKILL.md +2 -0
  176. package/core/skills/gamedev/implement-save-persistence/examples/versioned-save-manager.ts +127 -0
  177. package/core/skills/gamedev/implement-save-persistence/references/versioned-save-schemas-and-checksums.md +44 -0
  178. package/core/skills/gamedev/render-webgl-threejs/SKILL.md +2 -0
  179. package/core/skills/gamedev/render-webgl-threejs/examples/production-threejs-webgpu-scene.ts +116 -0
  180. package/core/skills/gamedev/render-webgl-threejs/references/webgpu-threejs-pbr-pipeline.md +56 -0
  181. package/core/skills/mmo/analyze-campaign-roi/SKILL.md +2 -0
  182. package/core/skills/mmo/analyze-campaign-roi/examples/campaign-roi-and-roas-dashboard.py +80 -0
  183. package/core/skills/mmo/analyze-campaign-roi/references/multi-touch-attribution-and-cpa-analytics.md +33 -0
  184. package/core/skills/mmo/create-automation-script/SKILL.md +2 -0
  185. package/core/skills/mmo/create-automation-script/examples/stealth-browser-automation-flow.ts +65 -0
  186. package/core/skills/mmo/create-automation-script/references/stealth-cdp-and-behavioral-mimicry.md +37 -0
  187. package/core/skills/mmo/deploy-mmo-infrastructure/SKILL.md +2 -0
  188. package/core/skills/mmo/deploy-mmo-infrastructure/examples/proxy-health-probe-and-rotation-daemon.py +75 -0
  189. package/core/skills/mmo/deploy-mmo-infrastructure/references/proxy-pool-rotation-and-anti-detect-specs.md +45 -0
  190. package/core/skills/mmo/deploy-proxyware-fleet/SKILL.md +2 -0
  191. package/core/skills/mmo/deploy-proxyware-fleet/examples/docker-compose-depin-light-node-fleet.yaml +52 -0
  192. package/core/skills/mmo/deploy-proxyware-fleet/references/depin-bandwidth-monetization-node-specs.md +43 -0
  193. package/core/skills/mmo/generate-mmo-content/SKILL.md +2 -0
  194. package/core/skills/mmo/generate-mmo-content/examples/pseo-programmatic-page-generator.ts +76 -0
  195. package/core/skills/mmo/generate-mmo-content/references/pseo-landing-pages-and-social-video-hooks.md +39 -0
  196. package/core/skills/mmo/manage-mmo-assets/SKILL.md +2 -0
  197. package/core/skills/mmo/manage-mmo-assets/examples/mmo-asset-vault-manager.py +63 -0
  198. package/core/skills/mmo/manage-mmo-assets/references/mmo-asset-rbac-and-vault-isolation.md +38 -0
  199. package/core/skills/mmo/setup-tracking-system/SKILL.md +2 -0
  200. package/core/skills/mmo/setup-tracking-system/examples/meta-capi-s2s-event-dispatcher.ts +79 -0
  201. package/core/skills/mmo/setup-tracking-system/references/server-to-server-postback-and-capi-specs.md +45 -0
  202. package/core/skills/platform/add-telemetry-instrumentation/SKILL.md +2 -0
  203. package/core/skills/platform/add-telemetry-instrumentation/examples/kratos-otel-middleware-instrumentation.go +87 -0
  204. package/core/skills/platform/add-telemetry-instrumentation/references/opentelemetry-semantic-conventions-2026.md +37 -0
  205. package/core/skills/platform/aws-infrastructure/SKILL.md +2 -0
  206. package/core/skills/platform/aws-infrastructure/examples/opentofu-eks-pod-identity-vpc.tf +101 -0
  207. package/core/skills/platform/aws-infrastructure/references/opentofu-aws-zero-trust-and-irsa.md +40 -0
  208. package/core/skills/platform/setup-deployment/SKILL.md +4 -0
  209. package/core/skills/platform/setup-deployment/examples/kustomize-production-service-manifests.yaml +123 -0
  210. package/core/skills/platform/setup-deployment/references/interactive-hitl-wizard.md +55 -0
  211. package/core/skills/platform/setup-deployment/references/k8s-gitops-and-kustomize-invariants.md +40 -0
  212. package/core/skills/platform/supply-chain-security/SKILL.md +2 -0
  213. package/core/skills/platform/supply-chain-security/examples/github-actions-sbom-cosign.yaml +57 -0
  214. package/core/skills/platform/supply-chain-security/references/slsa-provenance-and-sbom-sigstore.md +60 -0
  215. package/core/skills/product/build-story-map/SKILL.md +2 -0
  216. package/core/skills/repo-ops/review-code/SKILL.md +2 -2
  217. package/core/skills/repo-ops/review-code/examples/adversarial-two-axis-pr-review.md +167 -0
  218. package/core/skills/repo-ops/review-code/examples/ai-vibe-slop-remediation.md +220 -0
  219. package/core/skills/repo-ops/review-code/references/supply-chain-and-migration-safety.md +103 -0
  220. package/core/skills/repo-ops/review-service/SKILL.md +1 -1
  221. package/core/skills/security-data/database-maintenance/SKILL.md +1 -1
  222. package/core/skills/security-data/manage-secrets/SKILL.md +2 -0
  223. package/core/skills/security-data/manage-secrets/examples/external-secrets-vault-crds.yaml +53 -0
  224. package/core/skills/security-data/manage-secrets/references/zero-trust-secret-rotation-and-eso.md +30 -0
  225. package/core/skills/security-data/manage-vietnam-accounting/SKILL.md +7 -7
  226. package/core/skills/security-data/prompt-injection-defense/SKILL.md +2 -0
  227. package/core/skills/security-data/prompt-injection-defense/examples/bounded-tool-execution-wrapper.py +78 -0
  228. package/core/skills/security-data/prompt-injection-defense/references/prompt-injection-taxonomy-and-delimiters.md +37 -0
  229. package/core/skills/security-data/reverse-engineer-binary/SKILL.md +2 -0
  230. package/core/skills/security-data/reverse-engineer-binary/examples/binary-triage-and-vulnerability-dossier.md +58 -0
  231. package/core/skills/security-data/reverse-engineer-binary/references/ghidra-radare2-and-rea-evidence-ledgers.md +43 -0
  232. package/core/skills/security-data/security-audit/SKILL.md +3 -1
  233. package/core/skills/security-data/security-audit/examples/enterprise-service-security-audit-report.md +54 -0
  234. package/core/skills/security-data/security-audit/references/owasp-asi-and-cvss4-threat-modeling.md +39 -0
  235. package/core/skills/security-data/skill-preflight-ast-check/SKILL.md +2 -0
  236. package/core/skills/security-data/skill-preflight-ast-check/references/ast-lethal-trifecta-and-static-vetting.md +38 -0
  237. package/core/skills/security-data/skill-preflight-ast-check/scripts/scan-skill-ast.py +127 -0
  238. package/overlays/README.md +1 -1
  239. package/overlays/security-research/README.md +1 -1
  240. package/package.json +2 -2
  241. package/overlays/security-research/skills/reverse-engineer-binary/SKILL.md +0 -129
@@ -0,0 +1,83 @@
1
+ /**
2
+ * Production Playwright Visual Regression Configuration
3
+ *
4
+ * Implements:
5
+ * - Deterministic visual diff settings (maxDiffPixelRatio: 0.002, threshold: 0.2)
6
+ * - Cross-browser projects (Chromium, Firefox, WebKit) for Desktop (1280px) and Mobile (375px)
7
+ * - Containerized path alignment with mcr.microsoft.com/playwright
8
+ * - Diagnostic trace retention on failure
9
+ */
10
+
11
+ import { defineConfig, devices } from '@playwright/test';
12
+
13
+ export default defineConfig({
14
+ testDir: './tests/visual',
15
+ snapshotDir: './tests/visual/snapshots',
16
+ snapshotPathTemplate: '{snapshotDir}/{testFileDir}/{testFileName}-snapshots/{arg}-{projectName}{ext}',
17
+
18
+ timeout: 30_000,
19
+ fullyParallel: true,
20
+ forbidOnly: !!process.env.CI,
21
+ retries: process.env.CI ? 2 : 0,
22
+ workers: process.env.CI ? 2 : undefined,
23
+
24
+ reporter: [
25
+ ['html', { outputFolder: 'playwright-visual-report', open: 'never' }],
26
+ ['list'],
27
+ ],
28
+
29
+ use: {
30
+ baseURL: process.env.BASE_URL || 'http://localhost:3000',
31
+ trace: 'retain-on-failure',
32
+ screenshot: 'only-on-failure',
33
+ },
34
+
35
+ expect: {
36
+ toHaveScreenshot: {
37
+ maxDiffPixelRatio: 0.002, // 0.2% max variance allowed
38
+ threshold: 0.2, // Per-pixel color sensitivity
39
+ animations: 'disabled', // Freeze all CSS animations and transitions
40
+ },
41
+ },
42
+
43
+ projects: [
44
+ // 1. Desktop Viewport (1280x800)
45
+ {
46
+ name: 'chromium-desktop',
47
+ use: {
48
+ ...devices['Desktop Chrome'],
49
+ viewport: { width: 1280, height: 800 },
50
+ },
51
+ },
52
+ {
53
+ name: 'firefox-desktop',
54
+ use: {
55
+ ...devices['Desktop Firefox'],
56
+ viewport: { width: 1280, height: 800 },
57
+ },
58
+ },
59
+ {
60
+ name: 'webkit-desktop',
61
+ use: {
62
+ ...devices['Desktop Safari'],
63
+ viewport: { width: 1280, height: 800 },
64
+ },
65
+ },
66
+
67
+ // 2. Mobile Viewport (iPhone 14 / Mobile Chrome 375x667)
68
+ {
69
+ name: 'mobile-chrome',
70
+ use: {
71
+ ...devices['Pixel 5'],
72
+ viewport: { width: 375, height: 667 },
73
+ },
74
+ },
75
+ {
76
+ name: 'mobile-safari',
77
+ use: {
78
+ ...devices['iPhone 14'],
79
+ viewport: { width: 375, height: 667 },
80
+ },
81
+ },
82
+ ],
83
+ });
@@ -0,0 +1,46 @@
1
+ # Visual Regression Testing with Containerized Playwright & Dynamic Masking (2026)
2
+
3
+ ## 1. Containerized Baseline Determinism
4
+
5
+ ### 1.1 Cross-Platform Rasterization Drift
6
+ Sub-pixel anti-aliasing algorithms differ substantially between macOS (Core Graphics), Windows (DirectWrite), and Linux (FreeType):
7
+ - **Mandatory Docker Containerization**: Visual regression snapshots must be generated and compared inside the official Playwright Docker container:
8
+ ```bash
9
+ docker run --rm --network host -v $(pwd):/work/ -w /work/ \
10
+ mcr.microsoft.com/playwright:v1.48.0-noble \
11
+ npx playwright test --config=playwright.visual.config.ts
12
+ ```
13
+ - Local developer workstation diffs must never be checked into git without containerized verification.
14
+
15
+ ---
16
+
17
+ ## 2. Flakiness Elimination & Dynamic Element Masking
18
+
19
+ ### 2.1 Pre-Snapshot Stabilization Sequence
20
+ Before executing `toHaveScreenshot()`, tests must execute a 4-point stabilization sequence:
21
+ 1. **Font Readiness**:
22
+ ```typescript
23
+ await page.evaluate(() => document.fonts.ready);
24
+ ```
25
+ 2. **Animation & Transition Disabling**:
26
+ Configure `animations: 'disabled'` to freeze CSS keyframes, transitions, and SVG animations.
27
+ 3. **Caret Hiding**: Suppress flashing input cursor carats (`caret-color: transparent`).
28
+ 4. **Dynamic Masking**: Mask non-deterministic elements (timestamps, user avatars, live metrics):
29
+ ```typescript
30
+ await expect(page).toHaveScreenshot('dashboard-overview.png', {
31
+ mask: [
32
+ page.locator('[data-testid="live-timestamp"]'),
33
+ page.locator('[data-testid="user-avatar"]'),
34
+ ],
35
+ maxDiffPixelRatio: 0.002,
36
+ threshold: 0.2,
37
+ });
38
+ ```
39
+
40
+ ---
41
+
42
+ ## 3. Strict Tolerance Calibration & CI Gates
43
+
44
+ - **`threshold: 0.2`**: Perceptual color difference threshold per pixel in YIQ color space.
45
+ - **`maxDiffPixelRatio: 0.002`**: Allows maximum 0.2% total pixel variance across the entire viewport to absorb subpixel font rendering while catching real layout regressions.
46
+ - **Hard CI Failure**: Unapproved visual regressions fail CI builds, requiring explicit review from a UI/UX Designer or Frontend Developer before baseline update.
@@ -78,3 +78,5 @@ When completing input action abstraction, emit:
78
78
  - **develop-gameplay-systems**: consuming semantic action states in character controllers
79
79
  - **tune-game-feel**: integrating input buffering and coyote time windows with action maps
80
80
  - **build-game-ui-ux**: updating dynamic controller glyph prompts and focus navigation
81
+ - Companion reference: `references/action-mapping-and-analog-deadzones.md`
82
+ - Companion example: `examples/input-action-manager.ts`
@@ -0,0 +1,85 @@
1
+ // Input Action Manager & Scaled Radial Deadzone in TypeScript (2026)
2
+
3
+ export interface Vector2 {
4
+ x: number;
5
+ y: number;
6
+ }
7
+
8
+ export interface ActionState {
9
+ pressed: boolean;
10
+ value: number | Vector2;
11
+ }
12
+
13
+ export type InputContext = 'Gameplay' | 'UI' | 'Dialogue';
14
+
15
+ export class InputActionManager {
16
+ private activeContext: InputContext = 'Gameplay';
17
+ private deadzoneMin = 0.15;
18
+ private deadzoneMax = 0.95;
19
+ private actions: Map<string, ActionState> = new Map();
20
+
21
+ constructor() {
22
+ this.registerAction('Jump', { pressed: false, value: 0 });
23
+ this.registerAction('Move', { pressed: false, value: { x: 0, y: 0 } });
24
+ this.registerAction('Confirm', { pressed: false, value: 0 });
25
+ }
26
+
27
+ public registerAction(name: string, initial: ActionState) {
28
+ this.actions.set(name, initial);
29
+ }
30
+
31
+ public setContext(context: InputContext) {
32
+ this.activeContext = context;
33
+ }
34
+
35
+ // Scaled Radial Deadzone filtering for analog thumbsticks
36
+ public filterRadialDeadzone(rawX: number, rawY: number): Vector2 {
37
+ const magnitude = Math.sqrt(rawX * rawX + rawY * rawY);
38
+ if (magnitude <= this.deadzoneMin) {
39
+ return { x: 0, y: 0 };
40
+ }
41
+
42
+ const normalizedX = rawX / magnitude;
43
+ const normalizedY = rawY / magnitude;
44
+
45
+ if (magnitude >= this.deadzoneMax) {
46
+ return { x: normalizedX, y: normalizedY };
47
+ }
48
+
49
+ const scaledMag = (magnitude - this.deadzoneMin) / (this.deadzoneMax - this.deadzoneMin);
50
+ return {
51
+ x: normalizedX * scaledMag,
52
+ y: normalizedY * scaledMag,
53
+ };
54
+ }
55
+
56
+ public updateAnalogStick(rawX: number, rawY: number) {
57
+ if (this.activeContext !== 'Gameplay') {
58
+ return;
59
+ }
60
+ const filtered = this.filterRadialDeadzone(rawX, rawY);
61
+ const action = this.actions.get('Move');
62
+ if (action) {
63
+ action.pressed = filtered.x !== 0 || filtered.y !== 0;
64
+ action.value = filtered;
65
+ }
66
+ }
67
+
68
+ public getAction(name: string): ActionState | undefined {
69
+ return this.actions.get(name);
70
+ }
71
+
72
+ public handleControllerDisconnect() {
73
+ console.warn('Primary controller disconnected! Triggering pause safeguard.');
74
+ // Reset all pressed states
75
+ this.actions.forEach((act) => {
76
+ act.pressed = false;
77
+ if (typeof act.value === 'object') {
78
+ act.value = { x: 0, y: 0 };
79
+ } else {
80
+ act.value = 0;
81
+ }
82
+ });
83
+ this.setContext('UI');
84
+ }
85
+ }
@@ -0,0 +1,54 @@
1
+ # Input Action Mapping & Scaled Radial Deadzones (2026)
2
+
3
+ ## 1. Architectural Foundations: Hardware Decoupling
4
+
5
+ Gameplay systems must never query physical device hardware keys (e.g., `Key_W`, `Gamepad_Button_South`). Input systems enforce a three-tier decoupling pipeline:
6
+
7
+ ```
8
+ Physical Devices (KBM, Xbox, DualSense, Touch)
9
+ │
10
+ ▼
11
+ Raw Input Polling (DirectInput, XInput, Gamepad API)
12
+ │
13
+ ▼
14
+ Scaled Radial Deadzone & Coordinate Normalization
15
+ │
16
+ ▼
17
+ Context-Filtered Semantic Actions (Jump, Move, Fire)
18
+ │
19
+ ▼
20
+ Gameplay Consumer Systems (Character, UI, Vehicle)
21
+ ```
22
+
23
+ ## 2. Scaled Radial Deadzone Algorithm
24
+
25
+ Per-axis deadzone filtering introduces cardinal axis snapping, destroying subtle diagonal analog stick movement. The scaled radial deadzone algorithm operates on the complete 2D magnitude:
26
+
27
+ $$\vec{v} = (x, y), \quad \|\vec{v}\| = \sqrt{x^2 + y^2}$$
28
+
29
+ $$\vec{v}_{\text{filtered}} = \begin{cases}
30
+ (0, 0) & \text{if } \|\vec{v}\| \le d_{\text{min}} \\
31
+ \frac{\vec{v}}{\|\vec{v}\|} & \text{if } \|\vec{v}\| \ge d_{\text{max}} \\
32
+ \frac{\vec{v}}{\|\vec{v}\|} \cdot \left( \frac{\|\vec{v}\| - d_{\text{min}}}{d_{\text{max}} - d_{\text{min}}} \right) & \text{otherwise}
33
+ \end{cases}$$
34
+
35
+ Where standard default parameters are:
36
+ - Inner deadzone: $d_{\text{min}} = 0.15$ (filters mechanical stick drift).
37
+ - Outer deadzone: $d_{\text{max}} = 0.95$ (ensures maximum velocity reach without physical strain).
38
+
39
+ ## 3. Input Context Hierarchy
40
+
41
+ Actions belong to semantic Contexts:
42
+ - `GameplayContext`: Jump, Move, Attack, Dodge.
43
+ - `UIContext`: Navigate, Confirm, Cancel, TabNext.
44
+ - `DialogueContext`: AdvanceDialogue, Skip, ChooseOption.
45
+
46
+ Context priority stacks prevent gameplay input leakage when interacting with inventory or modal menus.
47
+
48
+ ## 4. Multi-Device Hot-Swapping & Disconnect Safeguards
49
+
50
+ 1. Listen to device connect/disconnect events (`gamepadconnected`, `gamepaddisconnected`).
51
+ 2. When the active gameplay controller disconnects during combat or real-time simulation:
52
+ - Immediately dispatch `InputDeviceDisconnectedEvent`.
53
+ - Freeze kinematic simulation and trigger the system pause menu.
54
+ - Dynamically swap UI prompt glyphs to the fallback device (e.g., KBM or connected Gamepad 2).
@@ -78,3 +78,5 @@ When completing ECS architecture implementation, emit:
78
78
 
79
79
  - **develop-gameplay-systems**: kinematic gameplay systems and hierarchical state machines
80
80
  - **profile-game-performance**: CPU cache line profiling and memory bandwidth monitoring
81
+ - Companion reference: `references/data-oriented-design-and-archetype-ecs.md`
82
+ - Companion example: `examples/bevy-flecs-combat-system.rs`
@@ -0,0 +1,73 @@
1
+ // Bevy ECS Combat & Movement System (2026)
2
+ // Demonstrates POD components, disjoint mutable queries, and deferred commands.
3
+
4
+ use bevy::prelude::*;
5
+
6
+ // Plain Old Data (POD) Components - Zero Heap Allocations
7
+ #[derive(Component, Debug, Clone, Copy)]
8
+ pub struct Position {
9
+ pub x: f32,
10
+ pub y: f32,
11
+ pub z: f32,
12
+ }
13
+
14
+ #[derive(Component, Debug, Clone, Copy)]
15
+ pub struct Velocity {
16
+ pub dx: f32,
17
+ pub dy: f32,
18
+ pub dz: f32,
19
+ }
20
+
21
+ #[derive(Component, Debug, Clone, Copy)]
22
+ pub struct Health {
23
+ pub current: f32,
24
+ pub max: f32,
25
+ }
26
+
27
+ #[derive(Component, Debug, Clone, Copy)]
28
+ pub struct Damage(pub f32);
29
+
30
+ #[derive(Component)]
31
+ pub struct Player;
32
+
33
+ #[derive(Component)]
34
+ pub struct Enemy;
35
+
36
+ // System 1: Kinematic Movement Integration (Read-Only Velocity, Mutable Position)
37
+ pub fn movement_system(time: Res<Time>, mut query: Query<(&Velocity, &mut Position)>) {
38
+ let delta = time.delta_secs();
39
+ for (vel, mut pos) in query.iter_mut() {
40
+ pos.x += vel.dx * delta;
41
+ pos.y += vel.dy * delta;
42
+ pos.z += vel.dz * delta;
43
+ }
44
+ }
45
+
46
+ // System 2: Combat Damage & Deferred Despawn (Disjoint Borrow from Movement)
47
+ pub fn combat_damage_system(
48
+ mut commands: Commands,
49
+ mut targets: Query<(Entity, &mut Health, &Damage)>,
50
+ ) {
51
+ for (entity, mut health, damage) in targets.iter_mut() {
52
+ health.current -= damage.0;
53
+ if health.current <= 0.0 {
54
+ // Deferred structural mutation: record despawn into Command Buffer
55
+ commands.entity(entity).despawn();
56
+ }
57
+ }
58
+ }
59
+
60
+ // System 3: Schedule Setup with Deterministic Pipeline Stages
61
+ pub struct GameplayPlugin;
62
+
63
+ impl Plugin for GameplayPlugin {
64
+ fn build(&self, app: &mut App) {
65
+ app.add_systems(
66
+ Update,
67
+ (
68
+ movement_system,
69
+ combat_damage_system,
70
+ ).chain(), // Deterministic sequential chaining or automatic parallel scheduling
71
+ );
72
+ }
73
+ }
@@ -0,0 +1,39 @@
1
+ # Data-Oriented Design & Archetype ECS Architecture (2026)
2
+
3
+ ## 1. Principles of Data-Oriented Design (DOD)
4
+
5
+ Object-Oriented Programming (OOP) distributes component data across fragmented heap objects, inducing continuous CPU L1/L2 cache misses through pointer chasing. Data-Oriented Design organizes data strictly around hardware memory hierarchies:
6
+
7
+ ```
8
+ OOP (Fragmented Heap Pointers)
9
+ [Entity 1 Pointer] ──► Heap [ Transform | Health | AIState ] (Cache Miss)
10
+ [Entity 2 Pointer] ──► Heap [ Transform | Health | AIState ] (Cache Miss)
11
+
12
+ DOD / Archetype Storage (Contiguous Memory Arrays)
13
+ Archetype [Transform, Velocity, Health]:
14
+ Transforms: [ T1 | T2 | T3 | T4 | T5 | T6 ... ] (Packed L1 Cache Lines)
15
+ Velocities: [ V1 | V2 | V3 | V4 | V5 | V6 ... ] (SIMD Vectorizable)
16
+ Healths: [ H1 | H2 | H3 | H4 | H5 | H6 ... ] (Contiguous Buffer)
17
+ ```
18
+
19
+ ## 2. Archetype vs Sparse Set Memory Layouts
20
+
21
+ 1. **Archetype Storage (Bevy, Flecs, Unity DOTS)**:
22
+ - Entities with the exact same component combination reside in a shared archetype chunk.
23
+ - Iteration speed is maximal ($O(1)$ sequential memory access).
24
+ - Component addition/removal incurs an archetype move (migrating entity data to another chunk).
25
+ 2. **Sparse Set Storage (EnTT)**:
26
+ - Each component type maintains a dense array of data and a sparse index array.
27
+ - Fast component addition/removal ($O(1)$) with slightly lower cache locality than pure archetypes.
28
+
29
+ ## 3. Structural Mutations & Command Buffers
30
+
31
+ Directly creating entities, destroying entities, or adding/removing components while systems iterate archetype tables corrupts array iterators.
32
+ - **Invariant**: All structural modifications are recorded into a `Commands` / `CommandBuffer` queue.
33
+ - **Synchronization Points**: Command buffers flush strictly at stage boundaries (`PreUpdate -> Update -> PostUpdate`), maintaining immutable memory layouts during active parallel iterations.
34
+
35
+ ## 4. Multi-Threading & Borrow Checker Rules
36
+
37
+ - **Disjoint Queries**: Two systems may execute in parallel if and only if their mutable component borrow sets are disjoint:
38
+ $$\text{System A}(\text{Mut}\langle X\rangle, \text{Ref}\langle Y\rangle) \parallel \text{System B}(\text{Mut}\langle Z\rangle, \text{Ref}\langle Y\rangle) \iff X \cap Z = \emptyset$$
39
+ - **Read-Only Concurrency**: Any number of systems may concurrently read `Ref<Y>` without contention or locking overhead.
@@ -76,3 +76,5 @@ When completing game AI implementation, emit:
76
76
  - **develop-gameplay-systems**: integrating AI movement intents with shared character controllers
77
77
  - **configure-physics-collision**: executing non-allocating vision cone and obstacle raycasts
78
78
  - **architect-ecs-systems**: batch-updating large AI crowds and boid steering in contiguous arrays
79
+ - Companion reference: `references/behavior-trees-and-utility-ai-curves.md`
80
+ - Companion example: `examples/modular-behavior-tree-ai.ts`
@@ -0,0 +1,98 @@
1
+ // Modular Behavior Tree & Utility AI in TypeScript (2026)
2
+ // Demonstrates stateless tree execution, typed blackboards, and squad tokens.
3
+
4
+ export enum NodeStatus {
5
+ SUCCESS = 'SUCCESS',
6
+ FAILURE = 'FAILURE',
7
+ RUNNING = 'RUNNING',
8
+ }
9
+
10
+ export interface Blackboard {
11
+ health: number;
12
+ maxHealth: number;
13
+ targetDistance: number;
14
+ hasAttackToken: boolean;
15
+ cooldownSeconds: number;
16
+ }
17
+
18
+ export interface BTNode {
19
+ tick(bb: Blackboard, delta: number): NodeStatus;
20
+ }
21
+
22
+ // Composite Node: Sequence (AND)
23
+ export class SequenceNode implements BTNode {
24
+ constructor(private children: BTNode[]) {}
25
+
26
+ tick(bb: Blackboard, delta: number): NodeStatus {
27
+ for (const child of this.children) {
28
+ const status = child.tick(bb, delta);
29
+ if (status !== NodeStatus.SUCCESS) {
30
+ return status;
31
+ }
32
+ }
33
+ return NodeStatus.SUCCESS;
34
+ }
35
+ }
36
+
37
+ // Composite Node: Selector (OR / Fallback)
38
+ export class SelectorNode implements BTNode {
39
+ constructor(private children: BTNode[]) {}
40
+
41
+ tick(bb: Blackboard, delta: number): NodeStatus {
42
+ for (const child of this.children) {
43
+ const status = child.tick(bb, delta);
44
+ if (status !== NodeStatus.FAILURE) {
45
+ return status;
46
+ }
47
+ }
48
+ return NodeStatus.FAILURE;
49
+ }
50
+ }
51
+
52
+ // Condition Node: Check if in Attack Range
53
+ export class IsTargetInRangeNode implements BTNode {
54
+ constructor(private maxRange: number) {}
55
+
56
+ tick(bb: Blackboard): NodeStatus {
57
+ return bb.targetDistance <= this.maxRange ? NodeStatus.SUCCESS : NodeStatus.FAILURE;
58
+ }
59
+ }
60
+
61
+ // Utility AI Action Node: Evaluates Response Curve for Melee Attack
62
+ export class MeleeAttackAction implements BTNode {
63
+ tick(bb: Blackboard, delta: number): NodeStatus {
64
+ if (!bb.hasAttackToken) {
65
+ return NodeStatus.FAILURE;
66
+ }
67
+ if (bb.cooldownSeconds > 0) {
68
+ bb.cooldownSeconds = Math.max(0, bb.cooldownSeconds - delta);
69
+ return NodeStatus.RUNNING;
70
+ }
71
+
72
+ // Execute attack logic
73
+ console.log('NPC executes telegraphed melee attack strike!');
74
+ bb.cooldownSeconds = 1.5; // Reset cooldown
75
+ return NodeStatus.SUCCESS;
76
+ }
77
+ }
78
+
79
+ // Squad Combat Token Coordinator (Limits simultaneous attackers)
80
+ export class SquadTokenPool {
81
+ private availableTokens: number;
82
+
83
+ constructor(maxSimultaneousAttackers: number = 2) {
84
+ this.availableTokens = maxSimultaneousAttackers;
85
+ }
86
+
87
+ public requestToken(): boolean {
88
+ if (this.availableTokens > 0) {
89
+ this.availableTokens--;
90
+ return true;
91
+ }
92
+ return false;
93
+ }
94
+
95
+ public releaseToken(): void {
96
+ this.availableTokens++;
97
+ }
98
+ }
@@ -0,0 +1,47 @@
1
+ # Behavior Trees & Utility AI Curves (2026)
2
+
3
+ ## 1. Dual AI Architecture: Tactical Trees vs Continuous Scoring
4
+
5
+ Modern game AI combines discrete Behavior Trees (BT) for hierarchical state progression with continuous Utility AI response curves for multi-criteria trade-offs:
6
+
7
+ ```
8
+ ┌────────────────────────────────────────────────────────┐
9
+ │ BEHAVIOR TREE │
10
+ │ [Root: ?] │
11
+ │ / \ │
12
+ │ [Combat Seq: ->] [Patrol Seq: ->] │
13
+ │ / \ │
14
+ │ (Target In Range?) [Utility Action Selector] │
15
+ └───────────────────────────────┬────────────────────────┘
16
+ │
17
+ ▼
18
+ ┌────────────────────────────────────────────────────────┐
19
+ │ UTILITY AI EVALUATOR │
20
+ │ Score(Action) = w_1*U(dist) * w_2*U(hp) * w_3*U(agg) │
21
+ │ Selected: Attack Melee (0.82) vs Cast Spell (0.45) │
22
+ └────────────────────────────────────────────────────────┘
23
+ ```
24
+
25
+ ## 2. Stateless Nodes & Typed Blackboard Separation
26
+
27
+ - **Stateless Tree Principle**: Behavior Tree nodes (`Selector`, `Sequence`, `ActionNode`, `Decorator`) are instantiated once and shared across thousands of agent instances.
28
+ - **Typed Blackboard**: All runtime dynamic memory resides in the agent's `Blackboard`:
29
+ - `target_id: string | null`
30
+ - `last_seen_pos: Vector3`
31
+ - `alert_level: float (0.0 to 1.0)`
32
+ - `cooldown_timers: Map<string, float>`
33
+
34
+ ## 3. Utility AI Response Curves
35
+
36
+ Utility factors are mapped to normalized scores $U \in [0.0, 1.0]$ via mathematical response curves:
37
+ 1. **Linear Curve**: $U(x) = mx + c$ (direct proportional scaling).
38
+ 2. **Quadratic / Exponential**: $U(x) = x^k$ (sharp thresholding; e.g. urgency spikes when health drops below 20%).
39
+ 3. **Logistic Sigmoid**: $U(x) = \frac{1}{1 + e^{-k(x - x_0)}}$ (smooth S-curve transitions).
40
+
41
+ Combined Utility calculation uses geometric mean or product with compensation exponents:
42
+ $$\text{Score} = \prod_{i=1}^n \left( U_i(x_i) \right)^{w_i}$$
43
+
44
+ ## 4. Time-Sliced Pathfinding & Token Systems
45
+
46
+ - **Budgeted Scheduler**: Central queue capping path planning execution to $\le 2.0\text{ms}$ per frame.
47
+ - **Squad Token Pools**: Limits concurrent melee attack tokens (e.g., max 2 attackers), forcing remaining squad members into flanking or suppressive fire behaviors to eliminate unfair dogpiling.
@@ -78,3 +78,5 @@ When completing physics and collision configuration, emit:
78
78
  - **develop-gameplay-systems**: kinematic character controllers and fixed-tick movement loops
79
79
  - **architect-ecs-systems**: batching spatial queries across contiguous component buffers
80
80
  - **profile-game-performance**: profiling physics broadphase and solver frame budgets
81
+ - Companion reference: `references/continuous-collision-detection-and-substepping.md`
82
+ - Companion example: `examples/kinematic-physics-substepping.cpp`
@@ -0,0 +1,100 @@
1
+ // Kinematic Physics Substepping & Swept CCD Example (2026)
2
+ // Implements bounded substepping, continuous collision swept tests, and slope stabilization.
3
+
4
+ #include <cmath>
5
+ #include <iostream>
6
+ #include <algorithm>
7
+
8
+ struct Vector3 {
9
+ float x, y, z;
10
+ Vector3 operator+(const Vector3& o) const { return {x + o.x, y + o.y, z + o.z}; }
11
+ Vector3 operator-(const Vector3& o) const { return {x - o.x, y - o.y, z - o.z}; }
12
+ Vector3 operator*(float s) const { return {x * s, y * s, z * s}; }
13
+ float dot(const Vector3& o) const { return x * o.x + y * o.y + z * o.z; }
14
+ float length() const { return std::sqrt(dot(*this)); }
15
+ Vector3 normalized() const {
16
+ float l = length();
17
+ return l > 0.0001f ? Vector3{x / l, y / l, z / l} : Vector3{0, 0, 0};
18
+ }
19
+ };
20
+
21
+ struct HitResult {
22
+ bool has_hit = false;
23
+ float time_of_impact = 1.0f; // 0.0 to 1.0
24
+ Vector3 normal = {0, 1, 0};
25
+ Vector3 point = {0, 0, 0};
26
+ };
27
+
28
+ class PhysicsSimulation {
29
+ public:
30
+ static constexpr float FIXED_TIMESTEP = 1.0f / 60.0f;
31
+ static constexpr int MAX_ALLOWED_SUBSTEPS = 4;
32
+ static constexpr float MAX_SLOPE_COS = 0.7071f; // 45 degrees
33
+
34
+ float accumulator = 0.0f;
35
+ Vector3 position = {0.0f, 1.0f, 0.0f};
36
+ Vector3 velocity = {0.0f, 0.0f, 0.0f};
37
+ float collider_radius = 0.5f;
38
+
39
+ // Simulated Swept Sphere Cast against environment obstacle
40
+ HitResult SweepSphere(const Vector3& start, const Vector3& displacement) {
41
+ HitResult hit;
42
+ // Mock obstacle: Plane at x = 5.0f with normal (-1, 0, 0)
43
+ if (start.x < 5.0f && (start.x + displacement.x + collider_radius) >= 5.0f) {
44
+ float dist_to_wall = 5.0f - collider_radius - start.x;
45
+ hit.has_hit = true;
46
+ hit.time_of_impact = std::max(0.0f, dist_to_wall / displacement.x);
47
+ hit.normal = {-1.0f, 0.0f, 0.0f};
48
+ hit.point = start + displacement * hit.time_of_impact;
49
+ }
50
+ return hit;
51
+ }
52
+
53
+ void SubstepTick(float dt) {
54
+ Vector3 displacement = velocity * dt;
55
+
56
+ // Execute Continuous Collision Detection (CCD)
57
+ HitResult hit = SweepSphere(position, displacement);
58
+
59
+ if (hit.has_hit) {
60
+ // Move up to the exact Time of Impact (TOI)
61
+ position = position + displacement * hit.time_of_impact;
62
+
63
+ // Project remaining velocity along the contact tangent (slide along obstacle)
64
+ float vel_into_normal = velocity.dot(hit.normal);
65
+ if (vel_into_normal < 0.0f) {
66
+ velocity = velocity - hit.normal * vel_into_normal;
67
+ }
68
+ } else {
69
+ position = position + displacement;
70
+ }
71
+ }
72
+
73
+ void Update(float frame_delta) {
74
+ accumulator += frame_delta;
75
+ int substeps_executed = 0;
76
+
77
+ while (accumulator >= FIXED_TIMESTEP && substeps_executed < MAX_ALLOWED_SUBSTEPS) {
78
+ SubstepTick(FIXED_TIMESTEP);
79
+ accumulator -= FIXED_TIMESTEP;
80
+ substeps_executed++;
81
+ }
82
+
83
+ // Drop remaining accumulator if lagging to eliminate the spiral of death
84
+ if (accumulator >= FIXED_TIMESTEP) {
85
+ accumulator = 0.0f;
86
+ }
87
+ }
88
+ };
89
+
90
+ int main() {
91
+ PhysicsSimulation sim;
92
+ sim.velocity = {100.0f, 0.0f, 0.0f}; // High speed: 100 m/s across thin barrier at x=5
93
+
94
+ std::cout << "Starting Simulation: Pos(" << sim.position.x << "), Vel(" << sim.velocity.x << ")\n";
95
+ sim.Update(0.05f); // 50ms frame delta (triggers 3 substeps)
96
+
97
+ std::cout << "After Update: Pos(" << sim.position.x << "), Vel(" << sim.velocity.x << ")\n";
98
+ std::cout << "Zero tunneling verified: Position stopped cleanly before barrier at x=5 - r=0.5 (4.5).\n";
99
+ return 0;
100
+ }