Skip to content

建立 AI、Rust 后端、前端引擎三者间的强类型契约,实现跨语言的类型安全。

License

Notifications You must be signed in to change notification settings

MaxelLabs/protocol

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

8 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

System Entry Points & Controllers - Complete Documentation

Documentation Index

This folder contains comprehensive analysis of the Maxellabs 3D Engine system architecture, entry points, and API controllers.

Files Overview

File Purpose Key Content
SYSTEM_ARCHITECTURE.md High-level system design ECS architecture, entry points, module dependencies, request flows
CONTROLLER_ROUTES.md Route mapping and request patterns System-to-query mapping, E2E flows, data flow diagrams
API_REFERENCE.md Complete API documentation Constructor signatures, method parameters, usage examples

Quick Start

What is the Entry Point?

The Engine class is the primary entry point for the application:

import { Engine } from '@maxellabs/engine';

const engine = new Engine({
  canvas: '#canvas',
  antialias: true
});

engine.start();

Location: /Users/mac/Desktop/project/max/runtime/packages/engine/src/engine/engine.ts

What are the Controllers?

In this ECS architecture, Systems act as controllers. They process batches of entities via queries:

class MySystem implements ISystem {
  metadata = {
    name: 'MySystem',
    stage: 'Update',
    priority: 50
  };

  execute(context, query) {
    const q = context.world.query({ all: [Component1, Component2] });
    q.forEach((entity, [comp1, comp2]) => {
      // Process entity
    });
  }
}

engine.scene.scheduler.addSystem(new MySystem());

What are the Routes?

Routes are defined by query filters that match specific component combinations:

Route Query Filter System
Transform Sync all: [LocalTransform] TransformSystem
Camera Update all: [Camera, WorldTransform] CameraSystem
Animation all: [Animator, AnimationClip] AnimationSystem
Rendering all: [MeshInstance, MaterialInstance, WorldTransform] RenderSystem

Architecture Overview

Layered Design

┌──────────────────────────────────────┐
│  Application Layer (Engine)          │
│  - Canvas management                 │
│  - Entity creation helpers           │
│  - Material/geometry factories       │
│  - Rendering loop                    │
└─────────────────┬────────────────────┘
                  │
┌─────────────────▼────────────────────┐
│  Scene Layer (Scene)                 │
│  - Entity lifecycle                  │
│  - System scheduling                 │
│  - Event system                      │
│  - Resource management               │
└─────────────────┬────────────────────┘
                  │
┌─────────────────▼────────────────────┐
│  ECS Layer (World + SystemScheduler) │
│  - Entity ID management              │
│  - Component storage (Archetypes)    │
│  - Query system                      │
│  - System execution                  │
└─────────────────┬────────────────────┘
                  │
┌─────────────────▼────────────────────┐
│  Graphics Layer (Renderer)           │
│  - WebGL abstraction (RHI)           │
│  - Frustum culling                   │
│  - GPU command submission            │
│  - Shader/material management        │
└─────────────────┬────────────────────┘
                  │
┌─────────────────▼────────────────────┐
│  GPU (WebGL Device)                  │
│  - Vertex/index buffers              │
│  - Textures and uniforms             │
│  - Render targets                    │
└──────────────────────────────────────┘

ECS Core Concepts

  • Entity: Unique ID representing a game object
  • Component: Data container (Position, Velocity, MeshInstance, etc.)
  • Archetype: Grouping of entities with identical component signatures (SoA storage)
  • Query: Efficient batch query for entities matching specific components
  • System: Logic that processes queries

Key Files

Core Package

  • ECS World: /Users/mac/Desktop/project/max/runtime/packages/core/src/ecs/world.ts
  • Scene Manager: /Users/mac/Desktop/project/max/runtime/packages/core/src/scene/scene.ts
  • System Scheduler: /Users/mac/Desktop/project/max/runtime/packages/core/src/ecs/systems.ts
  • Built-in Systems: /Users/mac/Desktop/project/max/runtime/packages/core/src/systems/

Engine Package

  • Engine Entry Point: /Users/mac/Desktop/project/max/runtime/packages/engine/src/engine/engine.ts
  • Renderer: /Users/mac/Desktop/project/max/runtime/packages/engine/src/renderers/simple-webgl-renderer.ts
  • Materials: /Users/mac/Desktop/project/max/runtime/packages/engine/src/materials/
  • Loaders: /Users/mac/Desktop/project/max/runtime/packages/engine/src/loaders/

RHI Package

  • WebGL Device: /Users/mac/Desktop/project/max/runtime/packages/rhi/

Request Flow (Example: Render a Frame)

Engine.loop() (per requestAnimationFrame)
  ├─ Scene.update(deltaTime)
  │   ├─ SystemScheduler.execute()
  │   │   ├─ TransformSystem
  │   │   ├─ CameraSystem
  │   │   ├─ AnimationSystem
  │   │   ├─ InteractionSystem
  │   │   └─ RenderSystem
  │   └─ Update query caches
  │
  ├─ Renderer.beginFrame()
  ├─ Scene.render()
  │   ├─ Extract main camera
  │   ├─ Frustum cull meshes
  │   ├─ Update light UBO
  │   └─ Submit draw calls
  ├─ Renderer.endFrame()
  └─ requestAnimationFrame(nextLoop)

Component Model

Data (Components)

// Pure data containers
interface LocalTransform {
  position: Vector3;
  rotation: Quaternion;
  scale: Vector3;
}

interface WorldTransform {
  position: Vector3;
  rotation: Quaternion;
  scale: Vector3;
  matrix: Matrix4;
}

interface MeshInstance {
  vertexBuffer: IRHIBuffer;
  indexBuffer?: IRHIBuffer;
  vertexCount: number;
}

Logic (Systems)

// Pure logic that transforms data
class TransformSystem {
  execute(context, query) {
    const entities = context.world.query({ all: [LocalTransform] });
    entities.forEach((entity, [localTransform]) => {
      const parentTransform = getParentWorldTransform(entity);
      const worldTransform = multiply(parentTransform, localTransform);
      context.world.addComponent(entity, WorldTransform, worldTransform);
    });
  }
}

API Categories

Entity Creation

  • engine.createMesh(geometry, material, options)
  • engine.createCamera(config)
  • engine.createDirectionalLight(config)
  • engine.createPointLight(config)
  • engine.createSpotLight(config)

Geometry

  • engine.createBoxGeometry(w, h, d)
  • engine.createSphereGeometry(radius)
  • engine.createPlaneGeometry(w, h, wSegs, hSegs)
  • engine.createCylinderGeometry(rTop, rBot, h, segs)

Materials

  • engine.createPBRMaterial(config)
  • engine.createUnlitMaterial(config)

Resource Loading

  • engine.loadGLTF(url, options)
  • engine.loadTexture(url) (not yet implemented)
  • engine.loadHDR(url) (not yet implemented)

ECS Operations

  • scene.world.createEntity()
  • scene.world.addComponent(entity, type, data)
  • scene.world.getComponent(entity, type)
  • scene.world.removeComponent(entity, type)
  • scene.world.query(filter)
  • scene.world.destroyEntity(entity)

Systems

  • scene.scheduler.addSystem(system)
  • scene.scheduler.removeSystem(name)

Events

  • scene.on(eventType, listener)
  • scene.off(eventType, listener)

System Execution Order

Systems execute in defined stages with optional priority:

  1. FrameStart (Priority 0-100)

    • InteractionSystem (Input handling)
  2. PreUpdate (Priority 0-100)

  3. Update (Priority 0-100)

    • AnimationSystem (Tween/animation)
  4. PostUpdate (Priority 0-100)

    • TransformSystem (LocalTrans → WorldTrans)
    • LayoutSystem (UI layout)
  5. PreRender (Priority 0-100)

    • Culling, shadow prep
  6. Render (Priority 0-100)

    • RenderSystem (Collect render data)
  7. PostRender (Priority 0-100)

    • UI, debug overlay

Design Patterns

1. ECS (Entity Component System)

  • Entities: ID-based, no data
  • Components: Pure data containers
  • Systems: Pure logic, transforms components

2. Dependency Injection

  • Engine accepts IRHIDevice via constructor
  • Scene receives device for resource management
  • Systems access context (world, scheduler, delta time)

3. Composition

  • Scene = EntityManager + HierarchyManager + EventDispatcher + Renderer + Scheduler
  • No inheritance hierarchies
  • Flexible component combinations

4. Query-Based Processing

  • Systems query entities by component signatures
  • Queries cached and automatically updated
  • Enables SIMD/parallelization

5. Layered Architecture

  • Application ← Scene ← ECS ← Renderer ← GPU
  • Each layer independent and replaceable

Performance Characteristics

Strengths

  • Cache-friendly iteration via archetypes (SoA)
  • Fast entity creation/destruction (ID reuse)
  • Efficient query caching
  • No virtual dispatch per entity
  • Data-driven = easier CPU optimization

Considerations

  • Component iteration order determined by archetype
  • Structural changes (add/remove component) trigger archetype migration
  • Queries must be manually cleaned up (.removeQuery())

Common Tasks

Create an Entity with Components

const entity = engine.scene.createEntity('MyEntity');
engine.scene.world.addComponent(entity, LocalTransform, {...});
engine.scene.world.addComponent(entity, Velocity, {...});

Query and Iterate

const query = engine.scene.world.query({
  all: [LocalTransform, Velocity],
  none: [Disabled]
});

query.forEach((entity, [transform, velocity]) => {
  transform.position.x += velocity.x * deltaTime;
});

Custom System

class MySystem {
  metadata = { name: 'MySystem', stage: 'Update' };
  execute(context, query) {
    // Process entities
  }
}

engine.scene.scheduler.addSystem(new MySystem());

Listen to Events

engine.scene.on('entity-created', (e) => {
  console.log('Created:', e.entityId);
});

engine.scene.on('component-added', (e) => {
  console.log('Added component:', e.componentType);
});

Files Location

All files are located in:

/Users/mac/Desktop/project/max/runtime/packages/
├── core/src/        (ECS, Scene, Systems)
├── engine/src/      (Engine, Renderer, Materials)
└── rhi/             (WebGLDevice implementation)

Next Steps

For detailed information, refer to:


Generated: 2026-01-22

Last Updated: Analysis of 3D WebGL Engine Architecture

About

建立 AI、Rust 后端、前端引擎三者间的强类型契约,实现跨语言的类型安全。

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published