Describe the real situation
Name the engine, target device, existing setup, desired outcome, and what must not break.
A vague prompt asks AI to guess. A useful prompt gives it context, constraints, quality checks, and a definition of done. Choose the situation you are facing, customize the details, and paste the Markdown into your LLM.
Choose an AI promptContext — engine, genre, platforms, players, and current state.
Constraints — security, performance, style, scope, and tools.
Process — inspect first, plan, implement, test, and document.
Proof — measured results and a clear definition of done.
Name the engine, target device, existing setup, desired outcome, and what must not break.
Ask for conventions, tests, documentation, and pipelines that help with the next asset or feature too.
Quality scores, profiling, telemetry, and test results make improvements easier to verify.
Pick the closest situation. Replace the bracketed details before giving the prompt to your AI assistant.
Create a modular web-game foundation before AI begins adding complete gameplay systems.
You do not need technical knowledge. Pick what sounds familiar. If you are unsure, choose the option that asks the AI to inspect the project and recommend the right answer.
# Task: Create the initial architecture for a scalable Three.js web game
You are a senior web-game architect, Three.js engineer, and TypeScript platform engineer.
## Technology
- Client: Three.js and TypeScript
- Frontend tooling: Vite
- Backend: [INSERT LANGUAGE AND FRAMEWORK, OR NONE FOR AN OFFLINE GAME]
- Package manager: Choose the most appropriate option for the existing workspace
- Testing: Choose appropriate unit, integration, end-to-end, and live-browser testing tools
- Physics: Choose the most appropriate physics library for the game requirements
- Multiplayer: [YES OR NO]
- Target browsers and devices: [DESCRIBE THEM]
Do not build the complete game yet. First create a clean, documented project structure that future AI agents and developers can extend.
## Required architecture
Create separate areas for:
1. Engine
- Renderer
- Camera
- Scene management
- Input
- Time and central game loop
- Movement, locomotion, and animation orchestration
- Audio
- Debugging tools
2. Game
- Game states
- Player
- Enemies
- Worlds or levels
- Items
- Rules
3. Assets
- Asset manifests
- Models
- Textures
- Materials
- Audio
- Video
- Asynchronous loaders
4. Networking
- Client transport
- Server transport
- Shared message schemas
- Connection state
- Server-authoritative validation
5. UI
- Menus
- HUD
- Loading screen
- Settings
6. Tests
- Unit tests
- Integration tests
- Network protocol tests
- Browser tests
Keep reusable engine systems independent from game-specific rules. Use small modules with clear responsibilities. Do not place the entire game inside one file, one Game class, or one global manager.
## Movement and animation audit
Before finalizing the architecture, audit the approved mechanics and core loop to identify every required movement category: character or creature locomotion, starts and stops, turns, jumps and landings, traversal, combat and interaction actions, facial or lip-sync animation, mechanical or vehicle motion, VFX or shader-driven movement, secondary motion, procedural IK, and physics-driven reactions where applicable.
Document which requirements use authored clips, skeletal animation, morph targets, state machines, blend trees, root motion or in-place movement, procedural animation, IK, physics, particles, or shaders. Define how gameplay state drives animation and how animation events synchronize with collisions, footsteps, audio, VFX, camera feedback, and authoritative network state. Keep rendering and animation presentation separate from trusted game rules.
Add the resulting movement and animation architecture, asset needs, state ownership, transition rules, performance budgets, and test strategy to the project documentation before full gameplay implementation begins.
## Collision and hit-detection audit
Design collision as a gameplay system that is separate from render meshes and visual animation. Audit every required movement collider, world blocker, interaction trigger, hurtbox, temporary attack hitbox, projectile or ray test, vehicle or ship collider, moving platform, door, dynamic prop, ragdoll, cloth or hair interaction, and static-world collision surface.
For each category, document the simplest stable representation that preserves the intended play: capsules for characters, boxes or compound primitives for props and vehicles, spheres or swept shapes for fast projectiles and melee, convex hulls only where primitives are insufficient, and triangle-mesh collision only for mostly static world geometry. Define collision layers and masks, broad-phase filtering, trigger versus blocking behavior, continuous collision detection or previous-to-current-frame sweeps, contact ownership, and when expensive physics may activate or sleep.
Keep physics and gameplay state authoritative. Resolve movement and collision before visual animation and rendering. Animation events may request that an attack window, sound, VFX, or trail begin, but gameplay code must enable, validate, deduplicate, and close hit detection. Aim or weapon traces must use the authoritative camera or gameplay aim solution rather than an animated barrel, with a separate obstruction check when required. Document tests for tunneling, frame-rate variation, corners, slopes, stairs, moving platforms, doors, spawn overlap, repeated hit prevention, network reconciliation, and visible animation-to-contact alignment.
## Game UI, menu, HUD, and button architecture
Plan the UI as a game interface rather than a website or admin dashboard. Inventory the HUD, title and pause menus, settings, save/load, inventory, equipment, skills, shop, dialogue, quest tracking, notifications, confirmations, loading, failure, victory, and accessibility screens the approved game actually needs. Give every screen and panel one responsibility, keep game state outside presentation components, and coordinate navigation through small event-driven services instead of one monolithic UI class.
Create a reusable visual and interaction system for typography, spacing, icon language, semantic colors, rarity and danger states, panels, cards, progress bars, input glyphs, focus indicators, and buttons. Every interactive control must define idle, hover, keyboard/controller focus, pressed, disabled, selected, busy/loading, error, and cooldown states where applicable. Menus must have one clear primary action, context-sensitive secondary actions, progressive disclosure, large targets, short 150–300 ms transitions, immediate visual/audio feedback, predictable focus order, no controller dead ends, reliable back navigation, and equivalent mouse, keyboard, controller, and touch behavior where supported.
Document responsive layout, couch-distance readability, safe areas, aspect ratios, localization expansion, text scaling, contrast, reduced motion, color-independent meaning, performance, asset preloading, and UI pooling or virtualization for large collections. Add browser and integration tests for opening, closing, focus restoration, input-method changes, button states, rapid repeated input, modal stacking, resolution changes, safe areas, and every critical menu path. The result must visually belong to the approved game world and art direction rather than looking like generic HTML controls.
If the game includes accounts, multiplayer, purchases, cloud saves, leaderboards, or a persistent economy, keep trusted state on the server and share network schemas without sharing private server logic.
## Documentation
Create:
- README.md
- docs/ARCHITECTURE.md
- docs/GAME_LOOP.md
- docs/ASSET_PIPELINE.md
- docs/NETWORKING.md
- docs/ADDING_A_FEATURE.md
- docs/AI_INSTRUCTIONS.md
AI_INSTRUCTIONS.md must explain:
- Where new files belong
- Which layers may depend on each other
- Naming conventions
- Testing requirements
- Commands that must run after changes
- Files that must not become monolithic
- How architectural decisions are documented
## Definition of done
Include a minimal playable bootstrap that opens a Three.js scene, displays a camera and basic object, handles resizing, and runs through the central game loop.
Do not add advanced gameplay until the architecture compiles, runs, passes its tests, and is documented. Report the final structure, dependency rules, commands run, and remaining decisions.
## Internationalization and localization architecture
Build internationalization into the existing architecture before gameplay and UI content multiply. Do not create a separate localization application or bolt translation onto finished screens.
- Centralize player-facing text behind stable translation keys and locale resources. Do not hard-code display strings in gameplay, menus, tutorials, errors, notifications, subtitles, or content data.
- Define a fallback locale, missing-key behavior, resource ownership, extraction and validation commands, translator notes, and a safe process for adding or updating a language.
- Support Unicode, plural/select rules through an ICU-style message system or the engine's equivalent, locale-aware number/date/time/currency/unit formatting, and invariant internal IDs for saves, networking, analytics, achievements, and game rules.
- Plan for right-to-left layout and bidirectional text, CJK and other line-breaking rules, diacritics, input methods and IME where players type, font fallback and glyph coverage, translated text expansion, subtitles/captions, localized audio or asset variants where required, and runtime language selection with a persisted preference.
- Keep localization data separate from trusted game rules. Servers, SDKs, automation, and analytics should exchange stable language-independent identifiers while clients turn them into localized player-readable text.
- Add pseudolocalization, missing/unused-key validation, fallback-locale tests, long-string and text-expansion tests, right-to-left tests, font/glyph checks, and representative locale screenshots to the normal test and CI strategy.
Document the supported launch locales, later-locale workflow, ownership, file locations, naming rules, formatting rules, font and audio strategy, platform limitations, and exact commands another developer or translator uses.
## Three.js WebGPU and WebGL renderer architecture
If this project uses Three.js, inspect the installed Three.js version and its official documentation before choosing renderer imports or APIs. Do not copy an older WebGPU setup from memory.
- For a new compatible renderer layer, evaluate the current three/webgpu entry point and WebGPURenderer. The current renderer is designed to select a WebGPU backend when available and fall back to a WebGL 2 backend. Do not add a separate hand-written WebGPU-detection branch and a second renderer unless an audited feature incompatibility, target-browser requirement, or current-version limitation makes that necessary.
- Initialize the renderer asynchronously where deterministic initialization, feature inspection, loading flow, or on-demand rendering requires it. Use the renderer's supported animation-loop lifecycle and prevent gameplay simulation, asset upload, resize, input, or UI startup from racing renderer initialization.
- If the project deliberately uses WebGLRenderer, document why. If it uses WebGPURenderer with a forced WebGL backend, document the compatibility reason and test that path separately.
- Build a renderer capability and compatibility matrix for standard materials, shadows, render targets, post-processing, video textures, animation/skinning, particles, picking, WebXR if applicable, custom shaders, device/context loss, screenshots, and every third-party Three.js extension used by the game.
- Use Three.js Shading Language and node materials for new custom shader work that must run across the WebGPU and WebGL backends. Do not silently port raw GLSL, ShaderMaterial, RawShaderMaterial, or onBeforeCompile customizations without proving an equivalent supported path and visual parity.
- Keep renderer selection behind one documented interface so scenes and gameplay systems do not branch throughout the codebase. Record the active backend in development diagnostics and privacy-safe performance telemetry.
- Handle initialization failure, WebGPU device loss, WebGL context loss, unsupported WebGL 2, reduced features, and recovery with a player-readable fallback rather than a blank canvas or raw exception.
Test the exact pinned Three.js version on every supported browser/device. Compare WebGPU and WebGL 2 with the same build, scene, camera, resolution, device-pixel ratio, quality tier, warm-up, and gameplay route before declaring either backend faster or production-ready.
## Three.js geometry, draw-call, and rendering performance
If the project uses Three.js, do not treat a triangle count or WebGPU selection as a universal performance guarantee. Establish per-device and per-quality-tier budgets from measured CPU frame time, GPU frame time, frame pacing, draw calls, visible triangles, shader and material cost, overdraw/fill rate, lights and shadows, post-processing, texture bandwidth, uploads, animation/skinning, physics, memory, loading, and JavaScript allocation behavior.
Use these only as initial planning hypotheses before profiling, never as pass/fail claims:
- Visible scene geometry: roughly 100k–500k triangles for constrained mobile, 500k–2 million for mid-range mobile, 2–5 million for capable mobile, 2–10 million for older desktop hardware, and 10–50 million for capable gaming desktops when the rest of the frame is controlled.
- Asset envelopes: characters around 5k–50k triangles, props around 100–5k, buildings around 1k–20k, terrain around 100k–500k visible, and approximately 1–5 million visible triangles for a broadly compatible complete scene.
- Draw calls: below 500 is a strong initial target, 500–1,000 requires observation, 1,000–2,000 has increasing CPU risk, and more than 2,000 requires explicit evidence on the target hardware and renderer backend.
Replace those hypotheses with project-specific measured budgets as soon as representative content exists. A lower triangle scene can still be slower because of expensive pixels, shaders, state changes, transparency, shadows, post-processing, animation, physics, or JavaScript work.
Prefer the smallest measured combination of InstancedMesh, BatchedMesh, merged static geometry, shared geometry/materials, texture atlases or arrays where appropriate, frustum culling, distance and screen-size LOD, spatial partitioning, bounded object pools, selective updates, compressed KTX2/Basis textures, compressed glTF meshes where justified, asynchronous loading, streaming, and explicit resource disposal. Do not merge objects that need independent culling, animation, selection, collision, or material behavior without measuring the trade-off.
Record renderer.info counters and browser/GPU profiler captures for representative quiet, dense, high-motion, transparent, shadow-heavy, particle-heavy, UI-overlay, and post-processing states. Profile WebGPU and WebGL 2 separately; WebGPU can reduce some CPU submission overhead and enable compute or modern rendering features, but it does not repair excessive allocations, physics, pathfinding, poor scene organization, expensive fragment shading, oversized shadows, or unnecessary post-processing.
For every optimization, capture the same build and gameplay route before and after, verify visual and gameplay parity, and report the actual bottleneck moved—not only the triangle count.
## Three.js multi-device rendering quality and fallback paths
If the project uses Three.js, design and implement capability-based rendering quality paths so the same game remains playable and visually coherent across constrained phones, capable phones and tablets, integrated-GPU laptops, older desktops, and high-end desktops.
Define documented Low, Balanced, High, and Ultra profiles when the supported device range justifies them. Each profile must specify measured budgets and explicit settings for:
- Renderer backend and supported feature path, render scale, device-pixel-ratio cap, target frame rate, antialiasing, output-buffer precision, and post-processing.
- Visible triangle and draw-call budgets, LOD distances or screen-size thresholds, object and vegetation density, terrain detail, decals, particles, transparent effects, reflection quality, and draw distance.
- Texture resolution, KTX2/Basis variants, anisotropy, material and shader complexity, normal/detail maps, environment maps, lighting count, shadow count, shadow-map resolution, cascades, contact shadows, and baked versus dynamic lighting.
- Character and object animation quality: rig and bone budgets, skinned-mesh count, animation sampling/update rate, interpolation, blend layers, facial animation, lip sync, IK, secondary motion, cloth, hair, ragdolls, physics reactions, crowd animation, and update-distance throttling.
- Asset residency, streaming, preload scope, memory ceilings, cache limits, geometry and texture disposal, worker use, and recovery from memory or graphics-device pressure.
Build the quality system from centralized data rather than scattered conditionals. Use measured capabilities and runtime performance—not only user-agent strings—to select a safe default. Let players override the choice when practical, persist the setting, explain costly options simply, and support safe automatic degradation with hysteresis so quality does not rapidly oscillate. Recover upward only after sustained headroom and never during a critical gameplay moment without an approved transition policy.
Create real asset, material, animation, and effect fallback paths instead of only disabling everything globally. Preserve silhouettes, art direction, gameplay readability, telegraphs, interaction feedback, hit timing, collision, input response, UI meaning, localization, accessibility, network authority, saves, and deterministic gameplay across every profile. Ultra may add presentation detail, but it must not reveal gameplay information or mechanics unavailable on Low.
Test cold start, representative gameplay, dense/high-motion scenes, menus, particles, transparency, lighting and shadows, animation-heavy scenes, background/resume, resize, orientation change, device/context loss, and live profile switching on representative devices. Capture comparable screenshots and performance traces for every profile and backend. Report unsupported combinations and fall back to the nearest verified path with a player-readable message rather than a blank canvas, crash, or raw error.
## Player-readable output requirement
Everything shown to a player must be written and presented for a human player, not for a developer or debugger. This includes menus, HUD labels, buttons, prompts, tutorials, objectives, dialogue, tooltips, loading and save states, empty states, confirmations, warnings, errors, rewards, notifications, accessibility messages, and connection or recovery states.
Use concise plain language, the game's established terminology and tone, recognizable icons with text where meaning could be ambiguous, and a clear next action. A player-facing error should explain what happened in useful terms, whether progress is safe, and what the player can do next.
Never expose raw exceptions, stack traces, JSON, database IDs, internal event names, enum or variable names, file paths, debug coordinates, HTTP status codes without explanation, server implementation details, developer TODOs, placeholder text, or raw telemetry on a player-facing surface. Send technical details to development-only logs, diagnostics, telemetry, or an authenticated support view. A short support reference code may be shown to the player only when it helps support locate the private diagnostic record.
Verify representative success, failure, offline, loading, empty, permission, validation, timeout, save, reconnect, and recovery states from the player's perspective. Developer documentation and final engineering reports may remain technical; this requirement applies to anything the game presents to players.
## Required game documentation
Documentation is part of the definition of done for this task.
Before finishing:
1. Read the existing README, docs directory, architecture notes, decision records, and AI instructions that apply to this system.
2. Update the existing relevant documentation instead of creating a competing document or a second source of truth.
3. If no relevant document exists, create a clearly named Markdown document in the game's established documentation directory. Use docs/ when the project has no existing convention.
4. Document the current system, the decisions made, ownership and lifecycle rules, configuration, files or assets changed, commands and tests run, known limitations, and how another developer should extend or troubleshoot the work.
5. Update AI_INSTRUCTIONS.md or the project's equivalent when this task changes architectural boundaries, required workflows, naming rules, or validation commands.
6. Keep documentation accurate to the implementation. Do not claim support, measurements, or test coverage that was not verified.
7. In the final report, list every documentation file created or updated.Give the AI screenshots, profiling results, player behavior, test failures, and specific feedback. Ask it to re-check the same rubric or success metrics after every meaningful change.