# VibeGame Engine A 3D game engine with declarative XML syntax and ECS architecture. Start playing immediately with automatic player, camera, and lighting - just add a ground to prevent falling. ## Core Architecture ### ECS (Entity Component System) - **Entities**: Just numbers (IDs), no data or behavior - **Components**: Pure data containers (position, health, color) - **Systems**: Functions that process entities with specific components - **Queries**: Find entities with specific component combinations ### Plugin System Bevy-inspired modular architecture: - **Components**: Data definitions using bitECS - **Systems**: Logic organized by update phases (setup, fixed, simulation, draw) - **Recipes**: XML entity templates with preset components - **Config**: Defaults, shorthands, enums, validations, parsers ### Update Phases 1. **SetupBatch**: Input gathering and frame setup 2. **FixedBatch**: Physics simulation at fixed timestep (50Hz) 3. **SimulationBatch**: Game logic and state updates 4. **DrawBatch**: Rendering and interpolation ## Critical Rules ⚠️ **Physics Position Override**: Physics bodies override transform positions. Always use `pos` attribute on physics entities, not transform position. ⚠️ **Ground Required**: Always include ground/platforms or the player falls infinitely. ⚠️ **Component Declaration**: Bare attributes mean "include with defaults", not "empty". ## Essential Knowledge ## Instant Playable Game ```html ``` This creates a complete game with: - ✅ Player character (auto-created) - ✅ Orbital camera (auto-created) - ✅ Directional + ambient lighting (auto-created) - ✅ Ground platform (you provide this) - ✅ WASD movement, mouse camera, space to jump ## Development Setup After installation with `npm create vibegame@latest my-game`: ```bash cd my-game bun dev # Start dev server with hot reload ``` ### Project Structure - **TypeScript** - Full TypeScript support with strict type checking - **src/main.ts** - Entry point for your game - **index.html** - HTML template with canvas element - **vite.config.ts** - Build configuration ### Commands - `bun dev` - Development server with hot reload - `bun run build` - Production build - `bun run preview` - Preview production build - `bun run check` - TypeScript type checking - `bun run lint` - Lint code with ESLint - `bun run format` - Format code with Prettier ## Physics Objects ```xml ``` ## CRITICAL: Physics Position vs Transform Position ⚠️ **Physics bodies override transform positions!** Always set position on the body, not the transform, for physics entities. ```xml ``` ## ECS Architecture Explained Unlike traditional game engines with GameObjects, VibeGame uses Entity-Component-System: - **Entities**: Just numbers (IDs), no data or behavior - **Components**: Pure data containers (position, health, color) - **Systems**: Functions that process entities with specific components ```typescript // Component = Data only const Health = GAME.defineComponent({ current: GAME.Types.f32, max: GAME.Types.f32 }); // System = Logic only const healthQuery = GAME.defineQuery([Health]); const DamageSystem: GAME.System = { update: (state) => { const entities = healthQuery(state.world); for (const entity of entities) { Health.current[entity] -= 1 * state.time.deltaTime; if (Health.current[entity] <= 0) { state.destroyEntity(entity); } } } }; ``` ## What's Auto-Created (Game Engine Defaults) The engine automatically creates these if missing: 1. **Player** - Character with physics, controls, and respawn (at 0, 1, 0) 2. **Camera** - Orbital camera following the player 3. **Lighting** - Ambient + directional light with shadows You only need to provide: - **Ground/platforms** - Or the player falls forever - **Game objects** - Whatever makes your game unique ### Override Auto-Creation (When Needed) While auto-creation is recommended, you can manually create these for customization: ```xml ``` **Best Practice**: Use auto-creation unless you specifically need custom positions, properties, or multiple instances. The defaults are well-tuned for most games. ## Post-Processing Effects ```xml ``` ## Common Game Patterns ### Basic Platformer ```xml ``` ### Collectible Coins (Collision-based) ```xml ``` ### Physics Playground ```xml ``` ## Recipe Reference | Recipe | Purpose | Key Attributes | Common Use | |--------|---------|---------------|------------| | `` | Immovable objects | `pos`, `shape`, `size`, `color` | Grounds, walls, platforms | | `` | Gravity-affected objects | `pos`, `shape`, `size`, `color`, `mass` | Balls, crates, falling objects | | `` | Script-controlled physics | `pos`, `shape`, `size`, `color` | Moving platforms, doors | | `` | Player character | `pos`, `speed`, `jump-height` | Main character (auto-created) | | `` | Base entity | Any components via attributes | Custom entities | ### Shape Options - `box` - Rectangular solid (default) - `sphere` - Ball shape - `cylinder` - Cylindrical shape - `capsule` - Pill shape (good for characters) ### Size Attribute - Box: `size="width height depth"` or `size="2 1 2"` - Sphere: `size="diameter"` or `size="1"` - Cylinder: `size="diameter height"` or `size="1 2"` - Broadcast: `size="2"` becomes `size="2 2 2"` ## How Recipes and Shorthands Work ### Everything is an Entity Every XML tag creates an entity. Recipes like `` are just shortcuts for `` with preset components. ```xml ``` ### Component Attributes Components are declared using bare attributes (no value means "use defaults"): ```xml ``` **Important**: Bare attributes like `transform` mean "include this component with default values", NOT "empty" or "disabled". ### Automatic Shorthand Expansion Shorthands expand to ANY component with matching properties: ```xml ``` ### Recipe Internals Recipes are registered component bundles with defaults: ```xml collider renderer respawn > collider renderer="color: 0xff0000" respawn > ``` ### Common Pitfall: Component Requirements ```xml ``` ### Best Practices Summary 1. **Use recipes** (``, ``, etc.) instead of raw `` tags 2. **Use shorthands** (`pos`, `size`, `color`) for cleaner code 3. **Override only what you need** - recipes have good defaults 4. **Mix recipes with custom components** - e.g., `` ## Currently Supported Features ### ✅ What Works Well - **Basic platforming** - Jump puzzles, obstacle courses - **Physics interactions** - Balls, dominoes, stacking - **Moving platforms** - Via kinematic bodies + tweening - **Collectibles** - Using collision detection in systems - **Third-person character control** - WASD + mouse camera - **Gamepad support** - Xbox/PlayStation controllers - **Visual effects** - Tweening colors, positions, rotations - **Post-processing** - Bloom, dithering, and tonemapping effects for visual styling - **Game UI/HUD** - HTML/CSS overlays with GSAP animations, ECS state integration ### Example Prompts That Work - "Create a platformer with moving platforms and collectible coins" - "Make bouncing balls that collide with walls" - "Build an obstacle course with rotating platforms" - "Add falling crates that stack up" - "Create a simple parkour level" - "Add a score display and upgrade menu with animations" - "Create a game with currency system and floating text effects" ### Troubleshooting - **Physics not working?** → Check if ground exists, verify `` tag - **Entity not appearing?** → Verify transform component, check position values - **Movement feels wrong?** → Physics body position overrides transform position - **Player falling forever?** → Add a ground/platform with `` ## Plugin Development Pattern ```typescript // Component Definition export const MyComponent = GAME.defineComponent({ value: GAME.Types.f32, enabled: GAME.Types.ui8 }); // System Definition const myQuery = GAME.defineQuery([MyComponent]); export const MySystem: GAME.System = { group: 'simulation', // or 'setup', 'fixed', 'draw' update: (state) => { const entities = myQuery(state.world); for (const entity of entities) { // System logic MyComponent.value[entity] += state.time.deltaTime; } } }; // Plugin Bundle export const MyPlugin: GAME.Plugin = { components: { MyComponent }, systems: [MySystem], config: { defaults: { "my-component": { value: 1, enabled: 1 } }, shorthands: { "my-val": "my-component.value" } } }; // Registration GAME.withPlugin(MyPlugin).run(); ``` ## State Management Patterns ### Singleton Entities (Game State) ```typescript function getOrCreateGameState(state: GAME.State): number { const query = GAME.defineQuery([GameState]); const entities = query(state.world); if (entities.length > 0) return entities[0]; const entity = state.createEntity(); state.addComponent(entity, GameState, { score: 0, level: 1 }); return entity; } ``` ### Component Access (bitECS style) ```typescript // Direct property access GAME.Transform.posX[entity] = 10; GAME.Transform.posY[entity] = 5; // Read values const x = GAME.Transform.posX[entity]; const health = GAME.Health.current[entity]; ``` ## Features Not Yet Built-In ### ❌ Engine Features Not Available - **Multiplayer/Networking** - No server sync - **Sound/Audio** - No audio system yet - **Save/Load** - No persistence system - **Inventory** - No item management system built-in (but easily implementable with UI) - **Dialog/NPCs** - No conversation system built-in (but easily implementable with UI) - **AI/Pathfinding** - No enemy AI - **Particles** - No particle effects (though UI can create particle-like effects) - **Custom shaders** - Fixed rendering pipeline - **Terrain** - Use box platforms instead ### Recommended Approaches - **Complex UI** → HTML/CSS overlays (this is actually superior to most game engines) - **Animations** → GSAP for smooth transitions and effects - **Level progression** → Reload with different XML or hide/show worlds - **Enemy behavior** → Tweened movement patterns - **Interactions** → Collision detection in custom systems ## Common Mistakes to Avoid ### ❌ Forgetting the Ground ```xml ``` ### ❌ Setting Transform Position on Physics Objects ```xml ``` ### ❌ Missing World Tag ```xml ``` ### ❌ Wrong Physics Type ```xml ``` ## Custom Components and Systems ### Creating a Health System ```typescript import * as GAME from 'vibegame'; // Define the component const Health = GAME.defineComponent({ current: GAME.Types.f32, max: GAME.Types.f32 }); // Create the system const HealthSystem: GAME.System = { update: (state) => { const entities = GAME.defineQuery([Health])(state.world); for (const entity of entities) { // Regenerate health over time if (Health.current[entity] < Health.max[entity]) { Health.current[entity] += 5 * state.time.deltaTime; } } } }; // Bundle as plugin const HealthPlugin: GAME.Plugin = { components: { Health }, systems: [HealthSystem], config: { defaults: { "health": { current: 100, max: 100 } } } }; // Use in game GAME.withPlugin(HealthPlugin).run(); ``` ### Using in XML ```xml ``` ## State API Reference Available in all systems via the `state` parameter: ### Entity Management - `createEntity(): number` - Create new entity - `destroyEntity(entity: number)` - Remove entity - `query(...Components): number[]` - Find entities with components ### Component Operations - `addComponent(entity, Component, data?)` - Add component - `removeComponent(entity, Component)` - Remove component - `hasComponent(entity, Component): boolean` - Check component - `getComponent(name: string): Component | null` - Get by name ### Time - `time.delta: number` - Frame time in seconds - `time.elapsed: number` - Total time in seconds - `time.fixed: number` - Fixed timestep (1/50) ### Physics Helpers - `addComponent(entity, ApplyImpulse, {x, y, z})` - One-time push - `addComponent(entity, ApplyForce, {x, y, z})` - Continuous force - `addComponent(entity, KinematicMove, {x, y, z})` - Move kinematic ## Plugin System ### Using Specific Plugins ```typescript import * as GAME from 'vibegame'; // Start with no plugins GAME .withoutDefaultPlugins() .withPlugin(TransformsPlugin) // Just transforms .withPlugin(RenderingPlugin) // Add rendering .withPlugin(PhysicsPlugin) // Add physics .run(); ``` ### Default Plugin Bundle - **RecipesPlugin** - XML parsing and entity creation - **TransformsPlugin** - Position, rotation, scale, hierarchy - **RenderingPlugin** - Three.js meshes, lights, camera - **PhysicsPlugin** - Rapier physics simulation - **InputPlugin** - Keyboard, mouse, gamepad input - **OrbitCameraPlugin** - Third-person camera - **PlayerPlugin** - Character controller - **TweenPlugin** - Animation system - **RespawnPlugin** - Fall detection and reset - **StartupPlugin** - Auto-create player/camera/lights ## Plugin Reference ### Core Math utilities for interpolation and 3D transformations. ### Functions #### lerp(a, b, t): number Linear interpolation #### slerp(fromX, fromY, fromZ, fromW, toX, toY, toZ, toW, t): Quaternion Quaternion spherical interpolation #### Examples ## Usage Note Math utilities are used internally by systems like tweening and transforms. For animating properties, use the Tween system instead of directly calling interpolation functions. For transformations, use the Transform component's euler angles which are automatically converted to quaternions by the system. ### Animation Procedural character animation with body parts that respond to movement states. ### Components #### AnimatedCharacter - headEntity: eid - torsoEntity: eid - leftArmEntity: eid - rightArmEntity: eid - leftLegEntity: eid - rightLegEntity: eid - phase: f32 - Walk cycle phase (0-1) - jumpTime: f32 - fallTime: f32 - animationState: ui8 - 0=IDLE, 1=WALKING, 2=JUMPING, 3=FALLING, 4=LANDING - stateTransition: f32 #### HasAnimator Tag component (no properties) ### Systems #### AnimatedCharacterInitializationSystem - Group: setup - Creates body part entities for AnimatedCharacter components #### AnimatedCharacterUpdateSystem - Group: simulation - Updates character animation based on movement and physics state #### Examples ## Examples ### Basic Usage ```typescript import * as GAME from 'vibegame'; // Add animated character to a player entity const player = state.createEntity(); state.addComponent(player, GAME.AnimatedCharacter); state.addComponent(player, GAME.CharacterController); state.addComponent(player, GAME.Transform); // The AnimatedCharacterInitializationSystem will automatically // create body parts in the next setup phase ``` ### Accessing Animation State ```typescript import * as GAME from 'vibegame'; const characterQuery = GAME.defineQuery([GAME.AnimatedCharacter]); const MySystem: GAME.System = { update: (state) => { const characters = characterQuery(state.world); for (const entity of characters) { const animState = GAME.AnimatedCharacter.animationState[entity]; if (animState === 2) { // JUMPING console.log('Character is jumping!'); } } } }; ``` ### XML Declaration ```xml ``` ### Input Focus-aware input handling for mouse, keyboard, and gamepad with buffered actions. Keyboard input only responds when canvas has focus. ### Components #### InputState - moveX: f32 - Horizontal axis (-1 left, 1 right) - moveY: f32 - Forward/backward (-1 back, 1 forward) - moveZ: f32 - Vertical axis (-1 down, 1 up) - lookX: f32 - Mouse delta X - lookY: f32 - Mouse delta Y - scrollDelta: f32 - Mouse wheel delta - jump: ui8 - Jump available (0/1) - primaryAction: ui8 - Primary action (0/1) - secondaryAction: ui8 - Secondary action (0/1) - leftMouse: ui8 - Left button (0/1) - rightMouse: ui8 - Right button (0/1) - middleMouse: ui8 - Middle button (0/1) - jumpBufferTime: f32 - primaryBufferTime: f32 - secondaryBufferTime: f32 ### Systems #### InputSystem - Group: simulation - Updates InputState components with current input data ### Functions #### setTargetCanvas(canvas: HTMLCanvasElement | null): void Registers canvas for focus-based keyboard input #### consumeJump(): boolean Consumes buffered jump input #### consumePrimary(): boolean Consumes buffered primary action #### consumeSecondary(): boolean Consumes buffered secondary action #### handleMouseMove(event: MouseEvent): void Processes mouse movement #### handleMouseDown(event: MouseEvent): void Processes mouse button press #### handleMouseUp(event: MouseEvent): void Processes mouse button release #### handleWheel(event: WheelEvent): void Processes mouse wheel ### Constants #### INPUT_CONFIG Default input mappings and sensitivity settings #### Examples ## Examples ### Basic Plugin Registration ```typescript import * as GAME from 'vibegame'; GAME .withPlugin(GAME.InputPlugin) .run(); ``` ### Reading Input in a Custom System ```typescript import * as GAME from 'vibegame'; const playerQuery = GAME.defineQuery([GAME.Player, GAME.InputState]); const PlayerControlSystem: GAME.System = { update: (state) => { const players = playerQuery(state.world); for (const player of players) { // Read movement axes const moveX = GAME.InputState.moveX[player]; const moveY = GAME.InputState.moveY[player]; // Check for jump if (GAME.InputState.jump[player]) { // Jump is available this frame } // Check mouse buttons if (GAME.InputState.leftMouse[player]) { // Left mouse is held } } } }; ``` ### Consuming Buffered Actions ```typescript import * as GAME from 'vibegame'; const CombatSystem: GAME.System = { update: (state) => { // Consume jump if available (prevents double consumption) if (GAME.consumeJump()) { // Perform jump velocity.y = JUMP_FORCE; } // Consume primary action if (GAME.consumePrimary()) { // Fire weapon spawnProjectile(); } } }; ``` ### Custom Input Mappings ```typescript import * as GAME from 'vibegame'; // Modify before starting the game GAME.INPUT_CONFIG.mappings.jump = ['Space', 'KeyX']; GAME.INPUT_CONFIG.mappings.moveForward = ['KeyW', 'KeyZ', 'ArrowUp']; GAME.INPUT_CONFIG.mouseSensitivity.look = 0.3; GAME.run(); ``` ### Manual Event Handling ```typescript import * as GAME from 'vibegame'; // Use the exported handlers directly if needed canvas.addEventListener('mousedown', GAME.handleMouseDown); canvas.addEventListener('mouseup', GAME.handleMouseUp); ``` ### Orbit Camera Orbital camera controller for third-person views and smooth target following. ### Components #### OrbitCamera - target: eid (0) - Target entity ID - current-yaw: f32 (π) - Current horizontal angle - current-pitch: f32 (π/6) - Current vertical angle - current-distance: f32 (4) - Current distance - target-yaw: f32 (π) - Target horizontal angle - target-pitch: f32 (π/6) - Target vertical angle - target-distance: f32 (4) - Target distance - min-distance: f32 (1) - max-distance: f32 (25) - min-pitch: f32 (0) - max-pitch: f32 (π/2) - smoothness: f32 (0.5) - Interpolation speed - offset-x: f32 (0) - offset-y: f32 (1.25) - offset-z: f32 (0) ### Systems #### OrbitCameraSystem - Group: draw - Updates camera position and rotation around target ### Recipes #### camera - Creates orbital camera with default settings - Components: orbit-camera, transform, world-transform, main-camera #### Examples ## Examples ### Basic Camera ```xml ``` ### Camera Following Player ```xml ``` ### Custom Orbit Settings ```xml ``` ### Programmatic Usage ```typescript import * as GAME from 'vibegame'; const cameraQuery = GAME.defineQuery([GAME.OrbitCamera]); const CameraControlSystem = { update: (state) => { const cameras = cameraQuery(state.world); for (const camera of cameras) { // Rotate camera on input if (state.input.mouse.deltaX) { GAME.OrbitCamera.targetYaw[camera] += state.input.mouse.deltaX * 0.01; } // Zoom on scroll if (state.input.mouse.wheel) { GAME.OrbitCamera.targetDistance[camera] = Math.max( GAME.OrbitCamera.minDistance[camera], Math.min( GAME.OrbitCamera.maxDistance[camera], GAME.OrbitCamera.targetDistance[camera] - state.input.mouse.wheel * 0.5 ) ); } } } }; ``` ### Dynamic Target Switching ```typescript import * as GAME from 'vibegame'; // Switch camera target const switchTarget = (state, cameraEntity, newTargetEntity) => { GAME.OrbitCamera.target[cameraEntity] = newTargetEntity; }; ``` ### Physics 3D physics simulation with Rapier including rigid bodies, collisions, and character controllers. ### Constants - DEFAULT_GRAVITY: -60 ### Enums #### BodyType - Dynamic = 0 - Affected by forces - Fixed = 1 - Immovable static - KinematicPositionBased = 2 - Script position - KinematicVelocityBased = 3 - Script velocity #### ColliderShape - Box = 0 - Sphere = 1 - Capsule = 2 ### Components #### PhysicsWorld - gravityX: f32 (0) - gravityY: f32 (-60) - gravityZ: f32 (0) #### Body - type: ui8 - BodyType enum (Fixed) - mass: f32 (1) - linearDamping: f32 (0) - angularDamping: f32 (0) - gravityScale: f32 (1) - ccd: ui8 (0) - lockRotX: ui8 (0) - lockRotY: ui8 (0) - lockRotZ: ui8 (0) - posX, posY, posZ: f32 - rotX, rotY, rotZ, rotW: f32 (rotW=1) - eulerX, eulerY, eulerZ: f32 - velX, velY, velZ: f32 - rotVelX, rotVelY, rotVelZ: f32 - lastPosX, lastPosY, lastPosZ: f32 #### Collider - shape: ui8 - ColliderShape enum (Box) - sizeX, sizeY, sizeZ: f32 (1) - radius: f32 (0.5) - height: f32 (1) - friction: f32 (0.5) - restitution: f32 (0) - density: f32 (1) - isSensor: ui8 (0) - membershipGroups: ui16 (0xffff) - filterGroups: ui16 (0xffff) - posOffsetX, posOffsetY, posOffsetZ: f32 - rotOffsetX, rotOffsetY, rotOffsetZ, rotOffsetW: f32 (rotOffsetW=1) #### CharacterController - offset: f32 (0.08) - maxSlope: f32 (45°) - maxSlide: f32 (30°) - snapDist: f32 (0.5) - autoStep: ui8 (1) - maxStepHeight: f32 (0.3) - minStepWidth: f32 (0.05) - upX, upY, upZ: f32 (upY=1) - moveX, moveY, moveZ: f32 - grounded: ui8 - platform: eid - Entity the character is standing on - platformVelX, platformVelY, platformVelZ: f32 - platformDeltaX, platformDeltaY, platformDeltaZ: f32 #### CharacterMovement - desiredVelX, desiredVelY, desiredVelZ: f32 - velocityY: f32 - actualMoveX, actualMoveY, actualMoveZ: f32 #### InterpolatedTransform - prevPosX, prevPosY, prevPosZ: f32 - prevRotX, prevRotY, prevRotZ, prevRotW: f32 - posX, posY, posZ: f32 - rotX, rotY, rotZ, rotW: f32 #### Force/Impulse Components - ApplyForce: x, y, z (f32) - ApplyTorque: x, y, z (f32) - ApplyImpulse: x, y, z (f32) - ApplyAngularImpulse: x, y, z (f32) - SetLinearVelocity: x, y, z (f32) - SetAngularVelocity: x, y, z (f32) - KinematicMove: x, y, z (f32) - KinematicRotate: x, y, z, w (f32) #### Collision Events - CollisionEvents: activeEvents (ui8) - TouchedEvent: other, handle1, handle2 (ui32) - TouchEndedEvent: other, handle1, handle2 (ui32) ### Systems - PhysicsWorldSystem - Initializes physics world - PhysicsInitializationSystem - Creates bodies and colliders - PhysicsCleanupSystem - Removes physics on entity destroy - PlatformDeltaSystem - Tracks platform position changes - CharacterMovementSystem - Character controller movement with platform sticking - CollisionEventCleanupSystem - Clears collision events - ApplyForcesSystem - Applies forces - ApplyTorquesSystem - Applies torques - ApplyImpulsesSystem - Applies impulses - ApplyAngularImpulsesSystem - Applies angular impulses - SetVelocitySystem - Sets velocities - TeleportationSystem - Instant position changes - KinematicMovementSystem - Kinematic movement - PhysicsStepSystem - Steps simulation - PhysicsRapierSyncSystem - Syncs Rapier to ECS - PhysicsInterpolationSystem - Interpolates for rendering ### Functions #### initializePhysics(): Promise Initializes Rapier WASM physics engine ### Recipes - static-part - Immovable physics objects - dynamic-part - Gravity-affected objects - kinematic-part - Script-controlled objects #### Examples ## Examples ### Basic Usage #### XML Recipes ##### Static Floor ```xml ``` ##### Dynamic Ball ```xml ``` ##### Moving Platform ```xml ``` ##### Character with Controller ```xml ``` #### JavaScript API ##### Create Physics Entity ```typescript import * as GAME from 'vibegame'; // Create a dynamic physics box const entity = state.createEntity(); state.addComponent(entity, GAME.Body, { type: GAME.BodyType.Dynamic, mass: 5, posX: 0, posY: 10, posZ: 0 }); state.addComponent(entity, GAME.Collider, { shape: GAME.ColliderShape.Box, sizeX: 1, sizeY: 1, sizeZ: 1, friction: 0.7, restitution: 0.3 }); // Note: Physics body won't exist until next fixed update // Transform will be overwritten by Body position after initialization ``` ##### Moving Physics Bodies ```typescript import * as GAME from 'vibegame'; // Dynamic bodies - Use forces/impulses for movement if (GAME.Body.type[entity] === GAME.BodyType.Dynamic) { // Apply force for gradual acceleration state.addComponent(entity, GAME.ApplyForce, { x: 10, y: 0, z: 0 }); // Apply impulse for instant velocity change state.addComponent(entity, GAME.ApplyImpulse, { x: 0, y: 50, z: 0 }); // Direct position setting only for teleportation GAME.Body.posX[entity] = 10; // Teleport - use sparingly } // Kinematic bodies - Direct control via movement components if (GAME.Body.type[entity] === GAME.BodyType.KinematicPositionBased) { state.addComponent(entity, GAME.KinematicMove, { x: 5, y: 2, z: 0 }); } if (GAME.Body.type[entity] === GAME.BodyType.KinematicVelocityBased) { state.addComponent(entity, GAME.SetLinearVelocity, { x: 3, y: 0, z: 0 }); } // Never modify Transform directly for physics entities // GAME.Transform.posX[entity] = 10; // ❌ Will be overwritten by Body ``` ##### Apply Forces ```typescript import * as GAME from 'vibegame'; // Apply upward impulse (jump) state.addComponent(entity, GAME.ApplyImpulse, { x: 0, y: 50, z: 0 }); // Apply continuous force state.addComponent(entity, GAME.ApplyForce, { x: 10, y: 0, z: 0 }); // Set velocity directly state.addComponent(entity, GAME.SetLinearVelocity, { x: 0, y: 5, z: 0 }); ``` ##### Handle Collisions ```typescript import * as GAME from 'vibegame'; const touchedQuery = GAME.defineQuery([GAME.TouchedEvent]); const CollisionSystem: GAME.System = { update: (state) => { // Query entities with collision events for (const entity of touchedQuery(state.world)) { const otherEntity = GAME.TouchedEvent.other[entity]; console.log(`Entity ${entity} collided with ${otherEntity}`); // React to collision state.addComponent(entity, GAME.ApplyImpulse, { x: 0, y: 10, z: 0 }); } } }; ``` ##### Character Movement ```typescript import * as GAME from 'vibegame'; const PlayerMovementSystem: GAME.System = { update: (state) => { const movementQuery = GAME.defineQuery([GAME.CharacterMovement, GAME.CharacterController]); for (const entity of movementQuery(state.world)) { // Set desired movement based on input GAME.CharacterMovement.desiredVelX[entity] = input.x * 5; GAME.CharacterMovement.desiredVelZ[entity] = input.z * 5; // Jump if grounded if (GAME.CharacterController.grounded[entity] && input.jump) { GAME.CharacterMovement.velocityY[entity] = 10; } } } }; ``` ##### Custom Plugin Integration ```typescript import * as GAME from 'vibegame'; // Initialize physics before running await GAME.initializePhysics(); // Use with builder GAME .withPlugin(GAME.PhysicsPlugin) .run(); ``` ### Player Complete player character controller with physics movement, jumping, and platform momentum preservation. ### Components #### Player - speed: f32 (5.3) - jumpHeight: f32 (2.3) - rotationSpeed: f32 (10) - canJump: ui8 (1) - isJumping: ui8 (0) - jumpCooldown: f32 (0) - lastGroundedTime: f32 (0) - jumpBufferTime: f32 (-10000) - cameraSensitivity: f32 (0.007) - cameraZoomSensitivity: f32 (1.5) - cameraEntity: eid (0) - inheritedVelX: f32 (0) - Horizontal momentum inherited from platform - inheritedVelZ: f32 (0) - Horizontal momentum inherited from platform ### Systems #### PlayerMovementSystem - Group: fixed - Handles movement, rotation, jumping with platform momentum preservation #### PlayerGroundedSystem - Group: fixed - Tracks grounded state, jump availability, and clears inherited momentum on landing #### PlayerCameraLinkingSystem - Group: simulation - Links player to orbit camera #### PlayerCameraControlSystem - Group: simulation - Camera control via mouse input ### Recipes #### player - Complete player setup with physics - Components: player, character-movement, transform, world-transform, body, collider, character-controller, input-state, respawn ### Functions #### processInput(moveForward, moveRight, cameraYaw): Vector3 Converts input to world-space movement #### handleJump(entity, jumpPressed, currentTime): number Processes jump with buffering #### updateRotation(entity, inputVector, deltaTime, rotationData): Quaternion Smooth rotation towards movement #### Examples ## Examples ### Basic Player Usage (XML) ```xml ``` ### Custom Player Configuration (XML) ```xml ``` ### Accessing Player Component (JavaScript) ```typescript import * as GAME from 'vibegame'; const playerQuery = GAME.defineQuery([GAME.Player]); const MySystem: GAME.System = { update: (state) => { const players = playerQuery(state.world); for (const entity of players) { // Check if player is jumping if (GAME.Player.isJumping[entity]) { console.log('Player is airborne!'); } // Modify player speed GAME.Player.speed[entity] = 10; } } }; ``` ### Creating Player Programmatically ```typescript import * as GAME from 'vibegame'; const PlayerSpawnSystem: GAME.System = { setup: (state) => { // Create player entity const player = state.createEntity(); // Add player recipe components state.addComponent(player, GAME.Player, { speed: 7, jumpHeight: 3.5, cameraSensitivity: 0.01 }); // Add required components state.addComponent(player, GAME.Transform, { posY: 5 }); state.addComponent(player, GAME.Body, { type: GAME.BodyType.KinematicPositionBased }); state.addComponent(player, GAME.CharacterController); state.addComponent(player, GAME.InputState); } }; ``` ### Movement Controls **Keyboard:** - W/S or Arrow Up/Down - Move forward/backward - A/D or Arrow Left/Right - Move left/right - Space - Jump **Mouse:** - Right-click + drag - Rotate camera - Scroll wheel - Zoom in/out ### Plugin Registration ```typescript import * as GAME from 'vibegame'; GAME .withPlugin(GAME.PlayerPlugin) // Included in defaults .run(); ``` ### Rendering Three.js rendering pipeline with meshes, lights, cameras, and post-processing effects. ### Components #### Renderer - shape: ui8 - 0=box, 1=sphere, 2=cylinder, 3=plane - sizeX, sizeY, sizeZ: f32 (1) - color: ui32 (0xffffff) - visible: ui8 (1) #### RenderContext - clearColor: ui32 (0x000000) - hasCanvas: ui8 #### MainCamera Tag component (no properties) #### Ambient - skyColor: ui32 (0x87ceeb) - groundColor: ui32 (0x4a4a4a) - intensity: f32 (0.6) #### Directional - color: ui32 (0xffffff) - intensity: f32 (1) - castShadow: ui8 (1) - shadowMapSize: ui32 (4096) - directionX: f32 (-1) - directionY: f32 (2) - directionZ: f32 (-1) - distance: f32 (30) #### Bloom - intensity: f32 (1.0) - Bloom intensity - luminanceThreshold: f32 (1.0) - Luminance threshold for bloom - luminanceSmoothing: f32 (0.03) - Smoothness of luminance threshold - mipmapBlur: ui8 (1) - Enable mipmap blur - radius: f32 (0.85) - Blur radius for mipmap blur - levels: ui8 (8) - Number of MIP levels for mipmap blur #### Dithering - colorBits: ui8 (4) - Bits per color channel (1-8) - intensity: f32 (1.0) - Effect intensity (0-1) - grayscale: ui8 (0) - Enable grayscale mode (0/1) - scale: f32 (1.0) - Pattern scale (higher = coarser dithering) - noise: f32 (1.0) - Noise threshold intensity ### Systems #### MeshInstanceSystem - Group: draw - Synchronizes transforms with Three.js meshes #### LightSyncSystem - Group: draw - Updates Three.js lights #### CameraSyncSystem - Group: draw - Updates Three.js camera and manages post-processing effects #### WebGLRenderSystem - Group: draw (last) - Renders scene through EffectComposer ### Functions #### setCanvasElement(entity, canvas): void Associates canvas with RenderContext ### Recipes - ambient-light - Ambient hemisphere lighting - directional-light - Directional light with shadows - light - Both ambient and directional #### Examples ## Examples ### Basic Rendering Setup ```xml ``` ### Custom Lighting ```xml ``` ### Imperative Usage ```typescript import * as GAME from 'vibegame'; // Create rendered entity programmatically const entity = state.createEntity(); // Add transform for positioning state.addComponent(entity, GAME.Transform, { posX: 0, posY: 5, posZ: 0 }); // Add renderer component state.addComponent(entity, GAME.Renderer, { shape: 1, // sphere sizeX: 2, sizeY: 2, sizeZ: 2, color: 0xff00ff, visible: 1 }); // Set canvas for rendering context const contextQuery = GAME.defineQuery([GAME.RenderContext]); const contextEntity = contextQuery(state.world)[0]; const canvas = document.getElementById('game-canvas'); GAME.setCanvasElement(contextEntity, canvas); ``` ### Shape Types ```typescript import * as GAME from 'vibegame'; // Available shape enums const shapes = { box: 0, sphere: 1, cylinder: 2, plane: 3 }; // Use in XML // Or with enum names ``` ### Visibility Control ```typescript import * as GAME from 'vibegame'; // Hide/show entities GAME.Renderer.visible[entity] = 0; // Hide GAME.Renderer.visible[entity] = 1; // Show // In XML ``` ### Post-Processing Effects ```xml ``` ### Respawn Automatic respawn system that resets entities when falling below Y=-100. ### Components #### Respawn - posX, posY, posZ: f32 - Spawn position - eulerX, eulerY, eulerZ: f32 - Spawn rotation (degrees) ### Systems #### RespawnSystem - Group: simulation - Resets entities when Y < -100 #### Examples ## Examples ### Player with Respawn (Automatic) The `` recipe automatically includes respawn: ```xml ``` ### Manual Respawn Component ```xml ``` ### Imperative Usage ```typescript import * as GAME from 'vibegame'; // Add respawn to an entity const entity = state.createEntity(); // Set spawn point from current transform state.addComponent(entity, GAME.Transform, { posX: 0, posY: 10, posZ: 0, eulerX: 0, eulerY: 0, eulerZ: 0 }); state.addComponent(entity, GAME.Respawn, { posX: 0, posY: 10, posZ: 0, eulerX: 0, eulerY: 0, eulerZ: 0 }); // Entity will respawn at (0,10,0) when falling ``` ### Update Spawn Point ```typescript import * as GAME from 'vibegame'; // Change respawn position dynamically GAME.Respawn.posX[entity] = 20; GAME.Respawn.posY[entity] = 5; GAME.Respawn.posZ[entity] = -10; ``` ### XML with Transform Sync Position attributes automatically populate the respawn component: ```xml ``` ### Startup Auto-creates player, camera, and lighting entities at startup if missing. ### Systems #### LightingStartupSystem - Group: setup - Creates default lighting if none exists #### CameraStartupSystem - Group: setup - Creates main camera if none exists #### PlayerStartupSystem - Group: setup - Creates player entity if none exists #### PlayerCharacterSystem - Group: setup - Adds animated character to players #### Examples ## Examples ### Basic Usage (Auto-Creation) ```typescript // The plugin automatically creates defaults when included import * as GAME from 'vibegame'; // This will create player, camera, and lighting automatically GAME.run(); // Uses DefaultPlugins which includes StartupPlugin ``` ### Preventing Auto-Creation with XML ```xml ``` ### Manual Plugin Registration ```typescript import * as GAME from 'vibegame'; // Use startup plugin without other defaults GAME.withoutDefaultPlugins() .withPlugin(GAME.TransformsPlugin) .withPlugin(GAME.RenderingPlugin) .withPlugin(GAME.StartupPlugin) .run(); ``` ### System Behavior The startup systems are idempotent - they check for existing entities before creating: ```typescript import * as GAME from 'vibegame'; // First run: Creates player, camera, lights const playerQuery = GAME.defineQuery([GAME.Player]); playerQuery(state.world).length // 0 -> creates player // Subsequent runs: Skips creation playerQuery(state.world).length // 1 -> skips creation ``` ### Transforms 3D transforms with position, rotation, scale, and parent-child hierarchies. ### Components #### Transform - posX, posY, posZ: f32 (0) - rotX, rotY, rotZ, rotW: f32 (rotW=1) - Quaternion - eulerX, eulerY, eulerZ: f32 (0) - Degrees - scaleX, scaleY, scaleZ: f32 (1) #### WorldTransform - Same properties as Transform - Auto-computed from hierarchy (read-only) ### Systems #### TransformHierarchySystem - Group: simulation (last) - Syncs euler/quaternion and computes world transforms #### Examples ## Examples ### Basic Usage #### XML Position and Rotation ```xml ``` #### JavaScript API ```typescript import * as GAME from 'vibegame'; // In a system const MySystem = { update: (state) => { const entity = state.createEntity(); // Add transform component with initial values state.addComponent(entity, GAME.Transform, { posX: 10, posY: 5, posZ: -3, eulerX: 0, eulerY: 45, eulerZ: 0, scaleX: 2, scaleY: 2, scaleZ: 2 }); // Transform system automatically syncs euler to quaternion } }; ``` ### Transform Hierarchy #### Parent-Child Relationships ```xml ``` #### Accessing World Transform ```typescript import * as GAME from 'vibegame'; const transformQuery = GAME.defineQuery([GAME.Transform, GAME.WorldTransform]); const WorldTransformSystem = { update: (state) => { // Query entities with both transforms const entities = transformQuery(state.world); for (const entity of entities) { // Local position const localX = GAME.Transform.posX[entity]; // World position (after parent transforms) const worldX = GAME.WorldTransform.posX[entity]; console.log(`Local: ${localX}, World: ${worldX}`); } } }; ``` ### Common Patterns #### Setting Transform Values ```typescript import * as GAME from 'vibegame'; // Direct property access (bitECS style) GAME.Transform.posX[entity] = 10; GAME.Transform.posY[entity] = 5; GAME.Transform.posZ[entity] = -3; // Using euler angles for rotation GAME.Transform.eulerX[entity] = 0; GAME.Transform.eulerY[entity] = 45; GAME.Transform.eulerZ[entity] = 0; // Quaternion will be auto-synced by TransformHierarchySystem // Uniform scale GAME.Transform.scaleX[entity] = 2; GAME.Transform.scaleY[entity] = 2; GAME.Transform.scaleZ[entity] = 2; ``` #### Transform Interpolation ```typescript import * as GAME from 'vibegame'; // Interpolate between two positions const t = 0.5; // 50% between start and end GAME.Transform.posX[entity] = startX + (endX - startX) * t; GAME.Transform.posY[entity] = startY + (endY - startY) * t; GAME.Transform.posZ[entity] = startZ + (endZ - startZ) * t; ``` ### Tweening Animates component properties with easing functions and loop modes. Kinematic velocity bodies use velocity-based tweening for smooth physics-correct movement. ### Components #### Tween - duration: f32 (1) - Seconds - elapsed: f32 - easingIndex: ui8 - loopMode: ui8 - 0=Once, 1=Loop, 2=PingPong #### TweenValue - source: ui32 - Tween entity - target: ui32 - Target entity - componentId: ui32 - fieldIndex: ui32 - from: f32 - to: f32 - value: f32 - Current value #### KinematicTween - tweenEntity: ui32 - Associated tween entity - targetEntity: ui32 - Kinematic body entity - axis: ui8 - 0=X, 1=Y, 2=Z - from: f32 - Start position - to: f32 - End position - lastPosition: f32 - targetPosition: f32 ### Systems #### KinematicTweenSystem - Group: fixed - Converts position tweens to velocity for kinematic bodies #### TweenSystem - Group: simulation - Interpolates values with easing and auto-cleanup ### Functions #### createTween(state, entity, target, options): number | null Animates component property ### Easing Functions - linear - sine-in, sine-out, sine-in-out - quad-in, quad-out, quad-in-out - cubic-in, cubic-out, cubic-in-out - quart-in, quart-out, quart-in-out - expo-in, expo-out, expo-in-out - circ-in, circ-out, circ-in-out - back-in, back-out, back-in-out - elastic-in, elastic-out, elastic-in-out - bounce-in, bounce-out, bounce-in-out ### Loop Modes - once - Play once and destroy - loop - Repeat indefinitely - ping-pong - Alternate directions ### Shorthand Targets - rotation - body.eulerX/Y/Z - at - body.posX/Y/Z - scale - transform.scaleX/Y/Z #### Examples ## Examples ### Basic XML Tween ```xml ``` ### Multiple Properties ```xml ``` ### Body Physics Properties ```xml ``` ### Programmatic Usage ```typescript import * as GAME from 'vibegame'; // In a system const MySystem = { setup: (state) => { const entity = state.createEntity(); state.addComponent(entity, GAME.Transform); // Create tween programmatically GAME.createTween(state, entity, 'body.pos-y', { from: 0, to: 10, duration: 2, easing: 'bounce-out', loop: 'once' }); } }; ``` ### Complex Animation Sequence ```xml ``` ### Ui Web-native UI system using HTML/CSS overlays positioned over the 3D canvas. Includes GSAP for animations, ECS state synchronization, and external library support. This provides capabilities superior to most game engines' built-in UI systems. ### Components #### UIManager - element: HTMLElement - Root UI container - state: State - ECS state reference for updates - visible: ui8 (1) - UI visibility toggle ### Systems #### UIUpdateSystem - Group: simulation - Updates UI elements from ECS component state #### UIEventSystem - Group: setup - Handles UI event binding and canvas focus management ### Functions #### createUIOverlay(canvas: HTMLCanvasElement): HTMLElement Creates positioned UI overlay container #### bindUIToState(uiManager: UIManager, state: State): void Connects UI updates to ECS state changes #### showFloatingText(x: number, y: number, text: string): void Creates animated floating text at screen coordinates ### Patterns #### Basic UI Setup ```html
0 100
``` #### ECS Integration ```typescript const UISystem = { update: (state) => { // Update UI from game state components const scoreEl = document.getElementById('score'); if (scoreEl) scoreEl.textContent = getScore(state); } }; ``` #### GSAP Animations ```typescript gsap.to("#currency", { scale: 1.2, duration: 0.2, yoyo: true, repeat: 1 }); ``` #### Examples ## Examples ### Basic Game HUD ```html
Score: 0
Coins: 0
``` ### Animated Currency with GSAP ```javascript import gsap from 'gsap'; class AnimatedCounter { constructor(elementId) { this.element = document.getElementById(elementId); this.currentValue = 0; this.displayValue = 0; } setValue(newValue) { this.currentValue = newValue; gsap.to(this, { displayValue: newValue, duration: 0.8, ease: "power2.out", onUpdate: () => { this.element.textContent = Math.floor(this.displayValue); } }); } } // Usage in ECS system const coinCounter = new AnimatedCounter('coins'); const UISystem = { update: (state) => { const coins = getCoinsFromState(state); coinCounter.setValue(coins); } }; ``` ### Floating Damage Text ```javascript function showDamageText(worldX, worldY, worldZ, damage) { // Convert 3D world position to screen coordinates const camera = getMainCamera(state); const screenPos = worldToScreen(worldX, worldY, worldZ, camera); const element = document.createElement('div'); element.textContent = `-${damage}`; element.style.cssText = ` position: fixed; left: ${screenPos.x}px; top: ${screenPos.y}px; color: #ff4444; font-weight: bold; font-size: 24px; pointer-events: none; z-index: 10000; `; document.body.appendChild(element); gsap.timeline() .to(element, { y: screenPos.y - 100, opacity: 0, duration: 1.5, ease: "power2.out" }) .call(() => element.remove()); } // Usage in collision system const DamageSystem = { update: (state) => { // When player takes damage const playerPos = getPlayerPosition(state); showDamageText(playerPos.x, playerPos.y + 2, playerPos.z, 25); } }; ``` ### Menu System with State ```javascript class GameMenu { constructor() { this.isOpen = false; this.element = document.getElementById('main-menu'); } toggle() { this.isOpen = !this.isOpen; if (this.isOpen) { this.show(); } else { this.hide(); } } show() { this.element.style.display = 'block'; gsap.fromTo(this.element, { opacity: 0, scale: 0.8 }, { opacity: 1, scale: 1, duration: 0.3, ease: "back.out(1.7)" } ); } hide() { gsap.to(this.element, { opacity: 0, scale: 0.8, duration: 0.2, onComplete: () => { this.element.style.display = 'none'; } }); } } // Integration with input system const menu = new GameMenu(); const MenuSystem = { update: (state) => { // Check for escape key press if (GAME.consumeInput(state, 'escape')) { menu.toggle(); } } }; ```