<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ivan Babkov on Medium]]></title>
        <description><![CDATA[Stories by Ivan Babkov on Medium]]></description>
        <link>https://medium.com/@i_babkov?source=rss-b16ba5accef3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*VtlJ8myExXZpxVd0ixTr3w.jpeg</url>
            <title>Stories by Ivan Babkov on Medium</title>
            <link>https://medium.com/@i_babkov?source=rss-b16ba5accef3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 10:13:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@i_babkov/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Three.js Architecture: MVC]]></title>
            <link>https://medium.com/@i_babkov/three-js-architecture-mvc-faa316e390b3?source=rss-b16ba5accef3------2</link>
            <guid isPermaLink="false">https://medium.com/p/faa316e390b3</guid>
            <category><![CDATA[threejs]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[webgl]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Ivan Babkov]]></dc:creator>
            <pubDate>Thu, 19 Mar 2026 02:01:08 GMT</pubDate>
            <atom:updated>2026-03-22T17:51:29.674Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uqB78BhDBpKEm-wr9t52Gw.png" /></figure><p>It’s easy to start a <a href="https://github.com/mrdoob/three.js/">Three.js</a> project, but keeping it maintainable as features grow is a different story. Many developers find themselves with massive files where input, physics, and rendering are all mixed together. When your logic is this tangled, even small changes can break parts of the app that seem unrelated.</p><p>We often use structured patterns like <a href="https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller">MVC</a> or <a href="https://www.oreilly.com/library/view/clean-architecture-a/9780134494272/">Clean Architecture</a> in web and mobile apps, but for some reason, we forget them once we enter a 3D scene. Instead of clean separation, we default to global variables or deeply nested classes. In my <a href="https://dev.to/i_babkov/threejs-architecture-ecs-3fg2">previous article on ECS</a>, we explored how a data-driven approach can help. However, if you are more comfortable with traditional patterns, MVC is an excellent way to organize a Three.js codebase.</p><p>In this article, we’ll build a Three.js application using the Model-View-Controller pattern. We’ll separate our application state from the 3D visuals. This will keep the logic predictable, maintainable, and easier to test.</p><p>🔗 The Final Result: <a href="https://github.com/ibabkov/threejs-mvc-example">GitHub</a> • <a href="https://ibabkov.github.io/threejs-mvc-example/">Demo</a></p><h3>Three.js Architecture Series</h3><ul><li><a href="https://medium.com/@i_babkov/three-js-architecture-ecs-685768c7d91f">Three.js Architecture: ECS</a></li><li><a href="https://medium.com/@i_babkov/three-js-architecture-mvc-faa316e390b3">Three.js Architecture: MVC</a></li><li><a href="https://medium.com/@i_babkov">All Articles</a></li></ul><h3>The MVC Pattern</h3><p>MVC splits the application into three roles. This separation keeps the app state independent from the 3D visuals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*Gv3K2YOUz9U77rbS" /></figure><ul><li><strong>Controllers</strong>: They process the logic. A Controller listens for user input and updates the Model. It doesn’t touch the View directly. It just changes the data, which then triggers a View update.</li><li><strong>Models</strong>: They hold the data. A Model stores properties like position or color, but knows nothing about Three.js meshes. It maintains the state and notifies other parts when it changes.</li><li><strong>Views</strong>: They handle the visual side. A View creates Three.js objects (meshes, lights, or cameras) and adds them to the scene. It watches the Model and updates the 3D objects to match the current data.</li></ul><p>This keeps the scene graph relatively clean. You don’t have to hunt for logic buried inside 3D objects. You can check if your logic works by looking at Model values, even without a rendering loop. So it simplifies testing as well as maintenance.</p><h3>Bootstrapping our app</h3><p>We start with a standard Three.js boilerplate, but instead of putting everything into one function, we split it across models, views, and a controller from the start. This gives us a rendering loop, a camera, some lights, and an environment texture. I won’t go too deep into Three.js itself because we are here to learn about MVC.</p><p><strong>Controllers</strong></p><p>First, we need a rendering loop. The RenderController takes a callback and calls it every frame using requestAnimationFrame. It just makes sure we keep rendering.</p><pre>// src/controllers/RenderController.ts<br>export class RenderController {<br>  private onRender: () =&gt; void;<br><br>  constructor(onRender: () =&gt; void) {<br>    this.onRender = onRender;<br>  }<br><br>  private update = () =&gt; {<br>    this.onRender();<br>    requestAnimationFrame(this.update);<br>  }<br><br>  public start() {<br>    this.update();<br>  }<br>}</pre><p><strong>Models</strong></p><p>All of our models extend a common BaseModel. It uses Three.js&#39;s EventDispatcher, which gives us a way to notify other parts of the app when data changes.</p><pre>// src/models/BaseModel.ts<br>import { EventDispatcher } from &#39;three&#39;;<br><br>export class BaseModel&lt;TEventMap extends {} = {}&gt; extends EventDispatcher&lt;TEventMap&gt; {<br>  constructor() { super(); }<br>}</pre><p>The SceneModel keeps track of objects in the scene. It stores them in a private _objects map and exposes add, get, and getAll methods. We use a private map instead of a public array to prevent outside code from mutating the collection directly. This ensures that all modifications happen through controlled methods. Later, when we add events, the add method is where we&#39;ll notify the rest of the app that a new object appeared in the scene.</p><pre>// src/models/SceneModel.ts<br>import type { SceneObjectModel } from &#39;./SceneObjectModel&#39;;<br>import { BaseModel } from &#39;./BaseModel&#39;;<br><br>export class SceneModel extends BaseModel {<br>  private _objects: Map&lt;string, SceneObjectModel&gt; = new Map();<br><br>  constructor() { super(); }<br><br>  add(object: SceneObjectModel, parent?: SceneObjectModel) {<br>    this._objects.set(object.id, object);<br>  }<br><br>  get(id: string): SceneObjectModel | undefined {<br>    return this._objects.get(id);<br>  }<br><br>  getAll(): SceneObjectModel[] {<br>    return Array.from(this._objects.values());<br>  }<br>}</pre><p>Now we need models for the camera, lights, and environment. Same idea as _objects above: private fields, public getters. No outside code can silently overwrite a camera&#39;s FOV or a light&#39;s color. When we need to change those values later, we&#39;ll add setter methods that validate input and dispatch change events. For now, the getters are read-only, which is all our boilerplate needs.</p><pre>// src/models/CameraModel.ts<br>import { Vector3 } from &#39;three&#39;;<br><br>import { BaseModel } from &#39;./BaseModel&#39;;<br><br>export class CameraModel extends BaseModel {<br>  private _position: Vector3  = new Vector3(0, 0, 5);<br>  private _fov: number = 70;<br>  private _near: number = 0.1;<br>  private _far: number = 10;<br><br>  constructor() { super(); }<br><br>  public get position() { return this._position; }<br><br>  public get fov() { return this._fov; }<br><br>  public get near() { return this._near; }<br><br>  public get far() { return this._far; }<br>}</pre><pre>// src/models/LightsModel.ts<br>import { Vector3 } from &#39;three&#39;;<br><br>import { BaseModel } from &#39;./BaseModel&#39;;<br><br>export class LightsModel extends BaseModel {<br>  private _ambientLightColor = &#39;#ffffff&#39;;<br>  private _ambientLightIntensity = 2;<br>  private _directionalLightColor = &#39;#ffffff&#39;;<br>  private _directionalLightIntensity = 2;<br>  private _directionalLightPosition = new Vector3(2, 2, 2);<br><br>  constructor() { super(); }<br><br>  public get ambientLightColor() {<br>      return this._ambientLightColor;<br>  }<br><br>  public get ambientLightIntensity() {<br>      return this._ambientLightIntensity;<br>  }<br><br>  public get directionalLightColor() {<br>      return this._directionalLightColor;<br>  }<br><br>  public get directionalLightIntensity() {<br>      return this._directionalLightIntensity;<br>  }<br><br>  public get directionalLightPosition() {<br>      return this._directionalLightPosition;<br>  }<br>}</pre><pre>// src/models/EnvironmentModel.ts<br>import { BaseModel } from &#39;./BaseModel&#39;;<br><br>export class EnvironmentModel extends BaseModel {<br>    private _backgroundColor = &#39;#0d1117&#39;;<br>    private _textureURL = new URL(<br>        &#39;../assets/env_1k.hdr&#39;,<br>        import.meta.url,<br>    );<br><br>    constructor() { super(); }<br><br>    public get backgroundColor() { return this._backgroundColor; }<br><br>    public get textureURL() { return this._textureURL.toString(); }<br>}</pre><p>Storing these values in models rather than hardcoding them in the Three.js setup allows us to update the application state at runtime. The views can then react to these changes automatically. The models act as the source of truth, and the views read from them.</p><p><strong>Views</strong></p><p>Now we can create our first view to represent the data we store in the models. Wrapping the PerspectiveCamera in a CameraView keeps the Three.js rendering logic separate from our application data. PerspectiveCamera is a Three.js object that belongs to the rendering side. The CameraModel holds the data (FOV, position, clipping planes), while CameraView turns that data into an actual camera. This setup makes it easier to change how the camera is built or to react to model updates without searching through the whole project.</p><pre>// src/views/CameraView.ts<br>import { PerspectiveCamera } from &#39;three&#39;;<br><br>import type { CameraModel } from &#39;../models/CameraModel&#39;;<br><br>export class CameraView {<br>    private _camera: PerspectiveCamera;<br>    private _model: CameraModel<br><br>    constructor(model: CameraModel) {<br>        this._model = model;<br>        this._camera = new PerspectiveCamera(<br>            this._model.fov,<br>            window.innerWidth / window.innerHeight,<br>            this._model.near,<br>            this._model.far<br>        );<br><br>        this._camera.position.copy(this._model.position);<br>    }<br><br>    public getCamera(): PerspectiveCamera {<br>        return this._camera;<br>    }<br>}</pre><p>SceneView is where the actual 3D scene lives. It owns the WebGLRenderer and the Three.js Scene. The constructor reads from LightsModel and EnvironmentModel to set up lights and the HDR environment texture, and it keeps a reference to CameraView for rendering. It also appends the renderer&#39;s canvas to the DOM. The update method gets called every frame and tells the renderer to draw the scene from the camera&#39;s point of view.</p><pre>// src/views/SceneView.ts<br>import {<br>    Scene,<br>    WebGLRenderer,<br>    Color,<br>    AmbientLight,<br>    DirectionalLight,<br>    EquirectangularReflectionMapping,<br>} from &#39;three&#39;;<br>import { HDRLoader } from &#39;three/examples/jsm/loaders/HDRLoader&#39;;<br><br>import type { CameraView } from &#39;./CameraView&#39;;<br>import type { SceneModel } from &#39;../models/SceneModel&#39;;<br>import type { LightsModel } from &#39;../models/LightsModel&#39;;<br>import type { EnvironmentModel } from &#39;../models/EnvironmentModel&#39;;<br><br>export class SceneView {<br>    scene: Scene;<br>    private renderer: WebGLRenderer;<br>    private sceneModel: SceneModel;<br>    private cameraView: CameraView;<br><br>    constructor(<br>        sceneModel: SceneModel,<br>        lightsModel: LightsModel,<br>        environmentModel: EnvironmentModel,<br>        cameraView: CameraView<br>    ) {<br>        this.sceneModel = sceneModel;<br>        this.scene = new Scene();<br>        this.cameraView = cameraView;<br>        this.renderer = this.setupRenderer();<br>        this.scene = this.setupScene(environmentModel);<br>        this.setupLights(lightsModel);<br>        this.setupEnvironment(environmentModel);<br><br>        document<br>            .querySelector(&#39;#app&#39;)!<br>            .appendChild(this.renderer.domElement);<br>    }<br><br>    private setupRenderer(): WebGLRenderer {<br>        const renderer = new WebGLRenderer({<br>            antialias: true,<br>            powerPreference: &#39;high-performance&#39;<br>        });<br><br>        renderer.setSize(window.innerWidth, window.innerHeight);<br>        renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));<br><br>        return renderer;<br>    }<br><br>    private setupScene(environmentModel: EnvironmentModel): Scene {<br>        const scene = new Scene();<br>        scene.background = new Color(environmentModel.backgroundColor);<br><br>        return scene;<br>    }<br><br>    private setupLights(lightsModel: LightsModel) {<br>        const ambient = new AmbientLight(<br>            lightsModel.ambientLightColor,<br>            lightsModel.ambientLightIntensity,<br>        );<br>        this.scene.add(ambient);<br><br>        const directional = new DirectionalLight(<br>            lightsModel.directionalLightColor,<br>            lightsModel.directionalLightIntensity,<br>        );<br>        directional.position.copy(lightsModel.directionalLightPosition);<br>        this.scene.add(directional);<br>    }<br><br>    private setupEnvironment(environmentModel: EnvironmentModel) {<br>        new HDRLoader().load(environmentModel.textureURL, (texture) =&gt; {<br>            texture.mapping = EquirectangularReflectionMapping;<br>            this.scene.environment = texture;<br>        });<br>    }<br><br>    public update() {<br>        this.renderer.render(this.scene, this.cameraView.getCamera());<br>    }<br><br>    public get domElement() { return this.renderer.domElement; }<br>}</pre><p>Now the Application class in our entry point wires everything together. The constructor first creates all the models: SceneModel, CameraModel, LightsModel, EnvironmentModel. At this point, there are no Three.js meshes yet, just data. Then it creates the views. CameraView gets the CameraModel and builds a PerspectiveCamera from it. SceneView gets the rest and sets up the renderer, scene, lights, and environment. Last, it creates the RenderController and passes it the update method as a per-frame callback. update calls this.sceneView.update(), which does a single render pass. start kicks off the loop through renderController.start().</p><pre>// src/index.ts<br>import { SceneModel } from &#39;./models/SceneModel&#39;;<br>import { CameraModel } from &#39;./models/CameraModel&#39;;<br>import { LightsModel } from &#39;./models/LightsModel&#39;;<br>import { EnvironmentModel } from &#39;./models/EnvironmentModel&#39;;<br><br>import { SceneView } from &#39;./views/SceneView&#39;;<br>import { CameraView } from &#39;./views/CameraView&#39;;<br><br>import { RenderController } from &#39;./controllers/RenderController&#39;;<br><br>export class Application {<br>    private sceneModel: SceneModel;<br>    private cameraModel: CameraModel;<br>    private lightsModel: LightsModel;<br>    private environmentModel: EnvironmentModel;<br><br>    private sceneView: SceneView;<br>    private cameraView: CameraView;<br><br>    private renderController: RenderController;<br><br>    constructor() {<br>        // Create models<br>        this.sceneModel = new SceneModel();<br>        this.cameraModel = new CameraModel();<br>        this.lightsModel = new LightsModel();<br>        this.environmentModel = new EnvironmentModel();<br><br>        // Create views<br>        this.cameraView = new CameraView(this.cameraModel);<br>        this.sceneView = new SceneView(<br>            this.sceneModel,<br>            this.lightsModel,<br>            this.environmentModel,<br>            this.cameraView,<br>        );<br><br>        // Create controllers<br>        this.renderController = new RenderController(this.update);<br>    }<br><br>    private update = () =&gt; {<br>        this.sceneView.update();<br>    }<br><br>    public start() {<br>        this.renderController.start();<br>    }<br>}<br><br>const app = new Application();<br><br>app.start();</pre><h3>Adding 3D objects</h3><p>In a typical Three.js project, you’d create a mesh, set its properties, and add it to the scene all in one place. With MVC, we split that process: models define what the object is, and views turn that definition into something Three.js can render. More boilerplate? Yes. But once the project has dozens of objects, you’ll be glad the data and the rendering code don’t live in the same place.</p><p><strong>Events</strong></p><p>Before we add any objects, we need a way for models to tell views that something happened. When a new object gets added to the scene model, the scene view needs to know about it so it can create the matching mesh. We’ll define an event type for this. The parent field is optional because not every object has a parent in the hierarchy.</p><pre>// src/types/events.ts<br>import type { SceneObjectModel } from &#39;../models/SceneObjectModel&#39;;<br><br>export type SceneModelEvents = {<br>    &#39;object-added&#39;: {<br>        object: SceneObjectModel,<br>        parent?: SceneObjectModel,<br>    };<br>}</pre><p><strong>Models</strong></p><p>Every 3D object in our scene needs position, rotation, scale, and material data. Instead of duplicating these fields across every model, we put them in a SceneObjectModel base class. It takes an id string and an optional material config. The concrete models will extend it with their own geometry parameters.</p><pre>// src/models/SceneObjectModel.ts<br>import { Euler, Vector3 } from &#39;three&#39;;<br><br>import { BaseModel } from &#39;./BaseModel&#39;;<br>import type { MapColorPropertiesToColorRepresentations } from &#39;three/src/materials/Material&#39;;<br><br><br>export class SceneObjectModel&lt;T = Partial&lt;MapColorPropertiesToColorRepresentations&lt;{}&gt;&gt;&gt; extends BaseModel {<br>    public readonly id;<br>    _position: Vector3;<br>    _rotation: Euler;<br>    _scale: Vector3;<br>    _material: Partial&lt;MapColorPropertiesToColorRepresentations&lt;T&gt;&gt;;<br><br>    constructor(<br>        id: string,<br>        material: Partial&lt;MapColorPropertiesToColorRepresentations&lt;T&gt;&gt; = {}<br>    ) {<br>        super();<br>        this.id = id;<br>        this._position = new Vector3(0, 0, 0);<br>        this._rotation = new Euler(0, 0, 0);<br>        this._scale = new Vector3(1, 1, 1);<br>        this._material = { ...material };<br>    }<br><br>    public get position(): Vector3 { return this._position; }<br><br>    public get rotation(): Euler { return this._rotation; }<br><br>    public get scale(): Vector3 { return this._scale; }<br><br>    public get material(): Partial&lt;MapColorPropertiesToColorRepresentations&lt;T&gt;&gt; {<br>        return this._material;<br>    }<br>}</pre><p>CubeModel extends SceneObjectModel with a size field and sets up a wireframe material. All the geometry and material data live here in the model, not in the view.</p><pre>// src/models/CubeModel.ts<br>import {MathUtils, Vector3} from &#39;three&#39;;<br>import type { MeshBasicMaterialProperties } from &#39;three&#39;;<br><br>import { SceneObjectModel } from &#39;./SceneObjectModel&#39;;<br><br>export class CubeModel extends SceneObjectModel&lt;MeshBasicMaterialProperties&gt; {<br>    private _size = 1.5;<br><br>    constructor(id: string) {<br>        super(id, {<br>            color: &#39;#44aaff&#39;,<br>            wireframe: true<br>        });<br><br>        this.rotation.y = MathUtils.degToRad(45);<br>    }<br><br>    get size() { return this._size; }<br>}</pre><p>TorusModel follows the same idea but with parameters specific to a torus knot geometry: radius, tube thickness, and segment counts. The material here is a MeshStandardMaterial with metalness and roughness, so we&#39;ll get reflections from the HDR environment we set up earlier.</p><pre>// src/models/TorusModel.ts<br>import type { MeshStandardMaterial } from &#39;three&#39;;<br><br>import { SceneObjectModel } from &#39;./SceneObjectModel&#39;;<br><br>export class TorusModel extends SceneObjectModel&lt;MeshStandardMaterial&gt; {<br>    private _radius: number = 0.3;<br>    private _tube: number = 0.08;<br>    private _tubularSegments: number = 128;<br>    private _radialSegments: number = 16;<br><br>    constructor(id: string) {<br>        super(id, {<br>            color: &#39;#4e8ab3&#39;,<br>            metalness: 1,<br>            roughness: 0.1<br>        });<br>    }<br><br>    public get radius() { return this._radius; }<br><br>    public get tube() { return this._tube; }<br><br>    public get tubularSegments() { return this._tubularSegments; }<br><br>    public get radialSegments() { return this._radialSegments; }<br>}</pre><p><strong>Views</strong></p><p>On the view side, we need the same kind of base class. SceneObjectView is abstract. It takes a model, calls createMesh (which subclasses implement), and syncs the mesh&#39;s transform to match the model&#39;s position, rotation, and scale. This way, every object view starts in the right place without repeating the same copy logic.</p><pre>// src/views/SceneObjectView.ts<br>import type { Mesh } from &#39;three&#39;;<br><br>import { SceneObjectModel } from &#39;../models/SceneObjectModel&#39;;<br><br>export abstract class SceneObjectView&lt;T extends SceneObjectModel = SceneObjectModel&gt; {<br>    private _mesh!: Mesh;<br>    private _model: T;<br><br>    constructor(model: T) {<br>        this._model = model;<br>        this.createMesh();<br>        this.syncTransform();<br>    }<br><br>    protected abstract createMesh(): void;<br><br>    get mesh(): Mesh { return this._mesh; }<br><br>    set mesh(mesh: Mesh) { this._mesh = mesh; }<br><br>    get model(): T { return this._model; }<br><br>    private syncTransform() {<br>        this.mesh.position.copy(this._model.position);<br>        this.mesh.rotation.copy(this._model.rotation);<br>        this.mesh.scale.copy(this._model.scale);<br>    }<br>}</pre><p>CubeView implements createMesh by reading the model&#39;s size and material properties to build a BoxGeometry and MeshBasicMaterial. The view doesn&#39;t decide what color the cube is or how big it should be. It just reads from the model.</p><pre>// src/views/CubeView.ts<br>import { BoxGeometry, MeshBasicMaterial, Mesh } from &#39;three&#39;;<br><br>import { SceneObjectView } from &#39;./SceneObjectView&#39;;<br>import { CubeModel } from &#39;../models/CubeModel&#39;;<br><br>export class CubeView extends SceneObjectView&lt;CubeModel&gt; {<br>    constructor(model: CubeModel) {<br>        super(model);<br>    }<br><br>    protected createMesh() {<br>        const geometry = new BoxGeometry(<br>            this.model.size,<br>            this.model.size,<br>            this.model.size,<br>        );<br>        const material = new MeshBasicMaterial({<br>            color: this.model.material.color,<br>            wireframe: this.model.material.wireframe,<br>        });<br>        this.mesh = new Mesh(geometry, material);<br>    }<br>}</pre><p>TorusView does the same thing for a torus knot. Different geometry, different material type, but the same pattern: read from the model, build the mesh.</p><pre>// src/views/TorusView.ts<br>import { TorusKnotGeometry, MeshStandardMaterial, Mesh } from &#39;three&#39;;<br><br>import { SceneObjectView } from &#39;./SceneObjectView&#39;;<br>import { TorusModel } from &#39;../models/TorusModel&#39;;<br><br>export class TorusView extends SceneObjectView&lt;TorusModel&gt; {<br>    constructor(model: TorusModel) {<br>        super(model);<br>    }<br><br>    protected createMesh() {<br>        const geometry = new TorusKnotGeometry(<br>            this.model.radius,<br>            this.model.tube,<br>            this.model.tubularSegments,<br>            this.model.radialSegments,<br>        );<br>        const material = new MeshStandardMaterial({<br>            color: this.model.material.color,<br>            metalness: this.model.material.metalness,<br>            roughness: this.model.material.roughness<br>        });<br>        this.mesh = new Mesh(geometry, material);<br>    }<br>}</pre><p><strong>Wiring it up</strong></p><p>Now we need to connect these pieces. First, SceneModel gets updated to dispatch an &#39;object-added&#39; event whenever a new object is registered. This is the bridge between models and views: the model doesn&#39;t know about views at all, it just announces that something changed.</p><pre>// src/models/SceneModel.ts<br>import type { SceneObjectModel } from &#39;./SceneObjectModel&#39;;<br>import { BaseModel } from &#39;./BaseModel&#39;;<br>import type { SceneModelEvents } from &#39;../types/events&#39;;<br><br>export class SceneModel extends BaseModel&lt;SceneModelEvents&gt; {<br>    // ... _objects map, get, and getAll remain the same<br><br>    add(object: SceneObjectModel, parent?: SceneObjectModel) {<br>        this._objects.set(object.id, object);<br>        this.dispatchEvent({ type: &#39;object-added&#39;, object, parent });<br>    }<br>}</pre><p>SceneView listens for that event. When it fires, the view checks what kind of model it got and creates the right view class for it. It also handles parent-child hierarchy: if the object has a parent, the mesh gets added to the parent&#39;s mesh instead of the scene root. The objectViews map keeps track of all created views so we can look up parents.</p><pre>// src/views/SceneView.ts<br>// ... existing three.js imports remain the same<br>import { CubeView } from &#39;./CubeView&#39;;<br>import { TorusView } from &#39;./TorusView&#39;;<br>import type { CameraView } from &#39;./CameraView&#39;;<br>import type { SceneObjectView } from &#39;./SceneObjectView&#39;;<br>import type { SceneModel } from &#39;../models/SceneModel&#39;;<br>import type { LightsModel } from &#39;../models/LightsModel&#39;;<br>import type { EnvironmentModel } from &#39;../models/EnvironmentModel&#39;;<br>import { CubeModel } from &#39;../models/CubeModel&#39;;<br>import { TorusModel } from &#39;../models/TorusModel&#39;;<br><br>export class SceneView {<br>    // ... scene, renderer, sceneModel, cameraView remain the same<br>    private objectViews: Map&lt;string, SceneObjectView&gt; = new Map();<br><br>    constructor(<br>        sceneModel: SceneModel,<br>        lightsModel: LightsModel,<br>        environmentModel: EnvironmentModel,<br>        cameraView: CameraView<br>    ) {<br>        // ... existing setup remains the same<br>        this.addEventListeners();<br>    }<br><br>    // ... setupRenderer, setupScene, setupLights,<br>    // setupEnvironment, update, domElement remain the same<br><br>    private addEventListeners() {<br>        this.sceneModel.addEventListener(&#39;object-added&#39;, (event) =&gt; {<br>            let view: SceneObjectView;<br><br>            if (event.object instanceof CubeModel) {<br>                view = new CubeView(event.object);<br>            } else if (event.object instanceof TorusModel) {<br>                view = new TorusView(event.object);<br>            } else {<br>                return;<br>            }<br><br>            this.objectViews.set(event.object.id, view);<br>            const parentView = event.parent<br>                &amp;&amp; this.objectViews.get(event.parent.id);<br>            const parent = parentView?.mesh || this.scene;<br>            parent.add(view.mesh);<br>        });<br>    }<br>}</pre><p>The last piece is spawning the actual objects. We add a spawnInitialObjects method to the Application class. It creates a CubeModel and a TorusModel, then adds them to the SceneModel. Because we pass cube as the parent of the torus, the torus mesh will be nested inside the cube mesh in the Three.js scene graph. The event system takes care of the rest: SceneModel.add fires &#39;object-added&#39;, SceneView picks it up, and the meshes appear.</p><pre>// src/index.ts<br>// ... existing imports remain the same<br>import { CubeModel } from &#39;./models/CubeModel&#39;;<br>import { TorusModel } from &#39;./models/TorusModel&#39;;<br><br>export class Application {<br>    // ... existing model, view, and controller fields remain the same<br><br>    constructor() {<br>        // ... existing model, view,<br>        // and controller creation remains the same<br>        this.spawnInitialObjects();<br>    }<br><br>    // ... update and start methods remain the same<br><br>    private spawnInitialObjects() {<br>        const cube = new CubeModel(&#39;cube-1&#39;);<br>        const torus = new TorusModel(&#39;torus-1&#39;);<br><br>        this.sceneModel.add(cube);<br>        this.sceneModel.add(torus, cube);<br>    }<br>}<br><br>// ... app creation and start remain the same</pre><p>At this point, the wireframe cube and the metallic torus knot are visible in the scene:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*btZx4eZH-R5kDz43" /><figcaption>Three.js Architecture: MVC / Basic 3D Visualization</figcaption></figure><p>Data flows in one direction: models hold the state, views read from it. Neither side knows about the other’s internals because events are the only thing connecting them.</p><h3>Bringing Interactivity</h3><p>We have objects on screen, but they sit there. The whole point of splitting models and views is that we can change data at runtime and have the visuals follow. In MVC, user input doesn’t touch the views directly. It goes through a controller, which updates a model, which fires an event, which the view picks up. That sounds like a long chain for “move the mouse and rotate a cube,” but the rotation logic never imports anything from Three.js, and the rendering code never sees a pointer event.</p><p><strong>Events</strong></p><p>We need two more event types. SceneObjectEvents carries a rotation-changed payload so views can react when a model&#39;s rotation updates. InputModelEvents carries normalized pointer coordinates whenever the user moves the mouse.</p><pre>// src/types/events.ts<br>import type { Vector2, Euler } from &#39;three&#39;;<br><br>import type { SceneObjectModel } from &#39;../models/SceneObjectModel&#39;;<br><br>export type SceneObjectEvents = {<br>    &#39;rotation-changed&#39;: { rotation: Euler };<br>}<br><br>export type InputModelEvents = {<br>    &#39;input-changed&#39;: { position: Vector2 };<br>}<br><br>// ... SceneModelEvents remains the same</pre><p><strong>Models</strong></p><p>SceneObjectModel needs to use the new SceneObjectEvents type so it can dispatch rotation-changed. The only change from before is the generic parameter passed to BaseModel.</p><pre>// src/models/SceneObjectModel.ts<br>// ... existing imports remain the same<br>import type { SceneObjectEvents } from &#39;../types/events&#39;;<br><br><br>export class SceneObjectModel&lt;T = Partial&lt;MapColorPropertiesToColorRepresentations&lt;{}&gt;&gt;&gt; extends BaseModel&lt;SceneObjectEvents&gt; {<br>    // ... everything else remains the same<br>}</pre><p>InputModel is small. It stores a 2D position vector and exposes an update method. When called, it sets the new coordinates and fires &#39;input-changed&#39;. That&#39;s it. No DOM references and no knowledge of what will consume the event.</p><pre>// src/models/InputModel.ts<br>import { Vector2 } from &#39;three&#39;;<br><br>import { BaseModel } from &#39;./BaseModel&#39;;<br>import { InputModelEvents } from &#39;../types/events&#39;;<br><br>export class InputModel extends BaseModel&lt;InputModelEvents&gt; {<br>    private _position: Vector2;<br><br>    constructor() {<br>        super();<br>        this._position = new Vector2(0, 0);<br>    }<br><br>    public update(x: number, y: number) {<br>        this._position.set(x, y);<br>        this.dispatchEvent({<br>            type: &#39;input-changed&#39;,<br>            position: this._position,<br>        });<br>    }<br>}</pre><p><strong>Views</strong></p><p>SceneObjectView gets one new method: addEventListeners. It subscribes to &#39;rotation-changed&#39; on its model and copies the new rotation onto the mesh. The constructor now calls this method after syncTransform.</p><pre>// src/views/SceneObjectView.ts<br>import type { Mesh } from &#39;three&#39;;<br><br>import { SceneObjectModel } from &#39;../models/SceneObjectModel&#39;;<br><br>export abstract class SceneObjectView&lt;T extends SceneObjectModel = SceneObjectModel&gt; {<br>    private _mesh!: Mesh;<br>    private _model: T;<br><br>    constructor(model: T) {<br>        this._model = model;<br>        this.createMesh();<br>        this.syncTransform();<br>        this.addEventListeners();<br>    }<br><br>    protected abstract createMesh(): void;<br><br>    get mesh(): Mesh { return this._mesh; }<br><br>    set mesh(mesh: Mesh) { this._mesh = mesh; }<br><br>    get model(): T { return this._model; }<br><br>    private syncTransform() {<br>        this.mesh.position.copy(this._model.position);<br>        this.mesh.rotation.copy(this._model.rotation);<br>        this.mesh.scale.copy(this._model.scale);<br>    }<br><br>    private addEventListeners() {<br>        this._model.addEventListener(&#39;rotation-changed&#39;, (event) =&gt; {<br>            this.mesh.rotation.set(<br>                event.rotation.x, <br>                event.rotation.y,<br>                event.rotation.z,<br>                event.rotation.order,<br>            );<br>        });<br>    }<br>}</pre><p><strong>Controllers</strong></p><p>Controllers sit between user input and models. They read events from one model and write changes to another. No rendering code, no DOM manipulation beyond the initial listener setup.</p><p>InputController listens for pointermove and pointerdown on the renderer&#39;s canvas. When a pointer event fires, it normalizes the coordinates to a -1 to 1 range and calls inputModel.update. The controller doesn&#39;t care what happens after that.</p><pre>// src/controllers/InputController.ts<br>import type { InputModel } from &#39;../models/InputModel&#39;;<br><br>export class InputController {<br>    private inputModel: InputModel;<br>    private domElement: HTMLElement;<br><br>    constructor(inputModel: InputModel, domElement: HTMLElement) {<br>        this.inputModel = inputModel;<br>        this.domElement = domElement;<br><br>        this.setupListeners();<br>    }<br><br>    private handlePointer = (e: PointerEvent) =&gt; {<br>        if (<br>            !e.isPrimary ||<br>            !(e.currentTarget instanceof HTMLElement)<br>        ) return;<br><br>        const rect = e.currentTarget.getBoundingClientRect();<br>        const x = ((e.clientX - rect.left) / rect.width) * 2 - 1;<br>        const y = -(((e.clientY - rect.top) / rect.height) * 2 - 1);<br><br>        this.inputModel.update(x, y);<br>    }<br><br>    private setupListeners() {<br>        this.domElement.addEventListener(&#39;pointermove&#39;, this.handlePointer);<br>        this.domElement.addEventListener(&#39;pointerdown&#39;, this.handlePointer);<br>    }<br>}</pre><p>TransformController connects the input to the scene objects. It listens for &#39;input-changed&#39; on the InputModel, iterates over all objects in the SceneModel, and dispatches &#39;rotation-changed&#39; on each one. The cube rotates on the Y axis based on horizontal pointer position, and the torus rotates on the X axis based on vertical position. The controller decides the mapping, but the model owns the data, and the view owns the rendering.</p><pre>// src/controllers/TransformController.ts<br>import type { SceneModel } from &#39;../models/SceneModel&#39;;<br>import type { InputModel } from &#39;../models/InputModel&#39;;<br>import { CubeModel } from &#39;../models/CubeModel&#39;;<br>import { TorusModel } from &#39;../models/TorusModel&#39;;<br><br>export class TransformController {<br>    private sceneModel: SceneModel;<br>    private inputModel: InputModel;<br><br>    constructor(sceneModel: SceneModel, inputModel: InputModel) {<br>        this.sceneModel = sceneModel;<br>        this.inputModel = inputModel;<br><br>        this.setupListeners();<br>    }<br><br>    private setupListeners() {<br>        this.inputModel.addEventListener(<br>            &#39;input-changed&#39;,<br>            ({ position }) =&gt; {<br>                const objects = this.sceneModel.getAll();<br>                objects.forEach((obj) =&gt; {<br>                    const rotation = obj.rotation;<br>                    if (obj instanceof CubeModel) {<br>                        rotation.y = position.x * Math.PI;<br>                        obj.dispatchEvent({<br>                            type: &#39;rotation-changed&#39;,<br>                            rotation,<br>                        });<br>                    } else if (obj instanceof TorusModel) {<br>                        rotation.x = position.y * Math.PI;<br>                        obj.dispatchEvent({<br>                            type: &#39;rotation-changed&#39;,<br>                            rotation,<br>                        });<br>                    }<br>                });<br>            }<br>        );<br>    }<br>}</pre><p><strong>Wiring it all together</strong></p><p>The Application class now creates all three controllers and wires them to the right models and views. InputController needs the canvas element from SceneView for pointer events. TransformController sits between SceneModel and InputModel, translating pointer coordinates into rotation updates. RenderController still calls SceneView.update() every frame.</p><pre>// src/index.ts<br>import { SceneModel } from &#39;./models/SceneModel&#39;;<br>import { CubeModel } from &#39;./models/CubeModel&#39;;<br>import { TorusModel } from &#39;./models/TorusModel&#39;;<br>import { CameraModel } from &#39;./models/CameraModel&#39;;<br>import { InputModel } from &#39;./models/InputModel&#39;;<br>import { LightsModel } from &#39;./models/LightsModel&#39;;<br><br>import { SceneView } from &#39;./views/SceneView&#39;;<br>import { CameraView } from &#39;./views/CameraView&#39;;<br><br>import { InputController } from &#39;./controllers/InputController&#39;;<br>import { TransformController } from &#39;./controllers/TransformController&#39;;<br>import { RenderController } from &#39;./controllers/RenderController&#39;;<br>import { EnvironmentModel } from &#39;./models/EnvironmentModel&#39;;<br><br><br>export class Application {<br>    private sceneModel: SceneModel;<br>    private cameraModel: CameraModel;<br>    private inputModel: InputModel;<br>    private lightsModel: LightsModel;<br>    private environmentModel: EnvironmentModel;<br><br>    private sceneView: SceneView;<br>    private cameraView: CameraView;<br><br>    private inputController: InputController;<br>    private transformController: TransformController;<br>    private renderController: RenderController;<br><br><br>    constructor() {<br>        // Create models<br>        this.sceneModel = new SceneModel();<br>        this.cameraModel = new CameraModel();<br>        this.inputModel = new InputModel();<br>        this.lightsModel = new LightsModel();<br>        this.environmentModel = new EnvironmentModel();<br><br>        // Create views<br>        this.cameraView = new CameraView(this.cameraModel);<br>        this.sceneView = new SceneView(<br>            this.sceneModel,<br>            this.lightsModel,<br>            this.environmentModel,<br>            this.cameraView,<br>        );<br><br>        // Create controllers<br>        this.renderController = new RenderController(this.update);<br>        this.inputController = new InputController(<br>            this.inputModel,<br>            this.sceneView.domElement<br>        );<br>        this.transformController = new TransformController(<br>            this.sceneModel,<br>            this.inputModel,<br>        );<br><br>        this.spawnInitialObjects();<br>    }<br><br>    private update = () =&gt; {<br>        this.sceneView.update();<br>    }<br><br>    private spawnInitialObjects() {<br>        const cube = new CubeModel(&#39;cube-1&#39;);<br>        const torus = new TorusModel(&#39;torus-1&#39;);<br><br>        this.sceneModel.add(cube);<br>        this.sceneModel.add(torus, cube);<br>    }<br><br>    public start() {<br>        this.renderController.start();<br>    }<br>}<br><br>const app = new Application();<br><br>app.start();</pre><p>The data flow for a single pointer move looks like this: PointerEvent → InputController → InputModel (fires &#39;input-changed&#39;) → TransformController → CubeModel/TorusModel (fires &#39;rotation-changed&#39;) → SceneObjectView (updates mesh rotation). Every link in the chain only knows about the interface it talks to, not the full pipeline.</p><p>Now, let’s check the final result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vYmBAVbn42su-fniWYKm9g.gif" /><figcaption>Three.js Architecture: MVC / Final 3D Visualization</figcaption></figure><p>🔗 <a href="https://github.com/ibabkov/threejs-mvc-example">GitHub</a> • <a href="https://ibabkov.github.io/threejs-mvc-example/">Demo</a></p><pre>src/<br>├── controllers/<br>│   ├── InputController.ts<br>│   ├── RenderController.ts<br>│   └── TransformController.ts<br>├── models/<br>│   ├── CameraModel.ts<br>│   ├── CubeModel.ts<br>│   ├── EnvironmentModel.ts<br>│   ├── InputModel.ts<br>│   ├── LightsModel.ts<br>│   ├── SceneModel.ts<br>│   ├── SceneObjectModel.ts<br>│   └── TorusModel.ts<br>├── types/<br>│   └── events.ts<br>├── views/<br>│   ├── CameraView.ts<br>│   ├── CubeView.ts<br>│   ├── SceneObjectView.ts<br>│   ├── SceneView.ts<br>│   └── TorusView.ts<br>├── index.ts</pre><h3>Benchmarks</h3><p>Now let’s validate the results for different numbers of objects. For this purpose, I have to use an InstancedMesh instead of the regular Mesh, which is outside the scope of the article. The architecture remains the same. Performance profiling over a 10-second interval on a Steam Deck (SteamOS 3.7.19, Chrome 146.0, WebGPU: Off, WebGL 2) yields the following results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z__63zuqcuAKZYgwwEoiqA.png" /></figure><pre>Metric                        | 1000    | 25k         | 50k     | 100k<br>------------------------------|---------|-------------|---------|---------<br>FPS (Avg/Min/Max)             | 120     | 59          | 33      | 19<br>Input &gt; Render Latency (Avg)  | 0.47ms  | 0.87ms      | 1.45ms  | 2.2ms<br>Input &gt; Render Latency (Max)  | 1.1ms   | 9.9ms       | 18.6ms  | 23.2ms<br>Memory Footprint              | 17 MB   | 18 MB       | 19 MB   | 21 MB</pre><p>The results confirm that the overhead associated with the MVC abstraction layer is negligible. The application remains responsive even at the 100,000 entity mark, with average input-to-render latency staying under 2.2ms. The memory footprint scales efficiently from 17 MB to 21 MB, demonstrating the effectiveness of the InstancedMesh implementation within the MVC structure.</p><h3>Beyond Basic MVC</h3><p><strong>Centralizing event communication</strong></p><p>Our models and views currently rely on direct event attachments. We can replace this by routing all messages through a single central dispatcher. Controllers and models send updates to this central hub, and views subscribe only to the specific data they need. You should do this when your app gets large. It prevents you from having to debug complex webs of direct component subscriptions.</p><p><strong>Choosing between MVVM and MVP</strong></p><p>Many of us need to build a React or Vue interface on top of a 3D scene. Passing data between traditional MVC controllers and a reactive UI often creates duplicate state. We can shift to a <a href="https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93viewmodel">Model-View-ViewModel</a> pattern to solve this. The view model transforms the 3D data into a format the DOM easily understands. We should use this pattern when the application relies heavily on HTML configuration panels. Alternatively, MVC and MVVM can cause frame drops if thousands of objects recalculate positions every frame. We can restructure into a <a href="https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93presenter">Model-View-Presenter</a> layout to protect performance. The view becomes completely passive in this pattern. The presenter calculates the math for all entities and manually batches the WebGL updates. This approach is necessary when the scene is massive and a stable frame rate is our absolute top priority.</p><p><strong>SOLID</strong></p><p>While MVC organizes the app, <a href="https://en.wikipedia.org/wiki/SOLID">SOLID</a> principles keep it extensible. Without them, controllers often end up importing concrete classes, and views begin branching on object types. This eventually breaks the clean layering we established.</p><p>In TransformController, we see this tight coupling:</p><pre>// src/controllers/TransformController.ts<br><br>if (obj instanceof CubeModel) {<br>    rotation.y = position.x * Math.PI;<br>    obj.dispatchEvent({ type: &#39;rotation-changed&#39;, rotation });<br>} else if (obj instanceof TorusModel) {<br>    rotation.x = position.y * Math.PI;<br>    obj.dispatchEvent({ type: &#39;rotation-changed&#39;, rotation });<br>}</pre><p>And SceneView.addEventListeners:</p><pre>// src/views/SceneView.ts<br><br>if (event.object instanceof CubeModel) {<br>    view = new CubeView(event.object);<br>} else if (event.object instanceof TorusModel) {<br>    view = new TorusView(event.object);<br>}</pre><p>These instanceof chains demonstrate exactly where the coupling occurs. I used them here to keep the data flow obvious, but they violate the Open/Closed Principle, adding a new object type would require modifying both classes. They also break the Dependency Inversion Principle because high-level controllers and views should not depend on concrete model implementations. In a larger project, the rotation logic should be moved into the models, and a view factory should be used to keep the architecture extensible and decoupled.</p><h3>Conclusion</h3><p>Using an MVC architecture separates core logic from rendering, making both easier to test and maintain. The benchmarks show that this structure has minimal impact on performance, with stable frame rates and low latency.</p><h3><strong>Pros</strong></h3><p><strong>Predictability</strong>: The strict separation means your data is isolated from the rendering loop. You can modify your application state without accidentally breaking the WebGL context.</p><p><strong>Testability</strong>: You can run unit tests on your controllers and models in a standard Node environment. You do not need to mock a canvas or a WebGL renderer to verify your logic.</p><p><strong>Performance</strong>: The event-driven architecture has a very low footprint. Our tests show that MVC overhead remains minimal as the scene scales, maintaining a low memory footprint and low latency across 1,000 to 100,000 entities.</p><h3><strong>Cons</strong></h3><p><strong>Boilerplate</strong>: You have to write significantly more code to get the first object on the screen. Creating a model, a view, and event listeners takes more time than simply adding a mesh to a scene.</p><p><strong>Data duplication</strong>: You often need to keep properties synchronized between your models and the actual Three.js objects. This means maintaining position and rotation data in two places at once.</p><p><strong>Strict discipline</strong>: You have to strictly maintain the MVC pattern and SOLID principles as the application grows. Letting logic slip into views or allowing controllers to bypass models will break the entire architecture and defeat the purpose of the setup.</p><h3>What’s Next</h3><p>We proved MVC works well for our immediate needs, but it is just one way to organize a Three.js codebase. In upcoming posts, I’ll walk through a few other patterns, so we can look at the practical trade-offs they bring to web-based 3D.</p><p><strong>About the Author</strong> Ivan Babkov — 2D/3D Graphics Software Engineer from Canada, building interactive web experiences | 3D, WebGL, GLTF, Three.js</p><p><a href="https://www.linkedin.com/in/ivan-babkov/">LinkedIn</a> • <a href="https://www.ibabkov.com/projects/">Portfolio</a> • <a href="https://github.com/ibabkov">GitHub</a></p><p><em>Originally published at </em><a href="https://gist.github.com/ibabkov/7c3debfa53d7af2d7fbfcdbe635cbb08"><em>http://github.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=faa316e390b3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Three.js Architecture: ECS]]></title>
            <link>https://medium.com/@i_babkov/three-js-architecture-ecs-685768c7d91f?source=rss-b16ba5accef3------2</link>
            <guid isPermaLink="false">https://medium.com/p/685768c7d91f</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[threejs]]></category>
            <category><![CDATA[webgl]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Ivan Babkov]]></dc:creator>
            <pubDate>Thu, 19 Feb 2026 14:16:01 GMT</pubDate>
            <atom:updated>2026-03-22T17:52:03.647Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o1rW9Cr69-I6Xm9r8IfOXw.png" /></figure><p>Over the last decade of my career, I’ve seen too many <a href="https://github.com/mrdoob/three.js/">Three.js</a> projects collapse, becoming impossible to maintain as they scale. In practice, it means that logic for input, physics, and rendering gets tangled up in a single requestAnimationFrame loop, making the codebase fragile. Sure, adding helper classes separates the logic for a while, but the structure eventually breaks down as feature requirements grow.</p><p>Most of the time, I’ve found the problem is less about the library we use and more about how we architect our applications and enforce the architecture. Strangely, developers often abandon the predictable architecture patterns they use in frontend/backend/native apps when they enter a 3D field. They default to deep inheritance chains and/or massive <a href="https://en.wikipedia.org/wiki/God_object">“God Objects”</a>. In this series of articles, I want to explore different solutions to this problem.</p><p>This article covers building a Three.js application using the <a href="https://en.wikipedia.org/wiki/Entity_component_system">Entity Component System (ECS)</a> architecture. This isn’t just a different way to organize files. It specifically enforces <a href="https://en.wikipedia.org/wiki/Composition_over_inheritance">composition over inheritance</a> and keeps concerns separated. ECS usually stores data in flat arrays to optimize memory access and allows us to swap features without rewriting the core loop.</p><p>🔗 The Final Result: <a href="https://github.com/ibabkov/threejs-koota-ecs-example">GitHub</a> • <a href="https://ibabkov.github.io/threejs-koota-ecs-example/">Demo</a></p><h3>Three.js Architecture Series</h3><ul><li><a href="https://medium.com/@i_babkov/three-js-architecture-ecs-685768c7d91f">Three.js Architecture: ECS</a></li><li><a href="https://medium.com/@i_babkov/three-js-architecture-mvc-faa316e390b3">Three.js Architecture: MVC</a></li><li><a href="https://medium.com/@i_babkov">All Articles</a></li></ul><h3>The ECS Pattern</h3><p>ECS stands for Entity, Component, and System. It is the standard for many high-performance game engines and is equally effective for complex web apps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*qZ6T5JmGZWCdBkZVXK6Jqw.png" /></figure><ul><li><strong>Entities</strong>: These are global identifiers (Integers). They contain no logic and no data. An entity represents a general-purpose object (e.g., Cube, 3D model, camera, etc.).</li><li><strong>Components(Traits)</strong>: These are raw data containers. For example, Position stores coordinates, and Velocity stores a vector. They contain no logic.</li><li><strong>Systems</strong>: These are the functions that execute logic on subsets of data. A MovementSystem queries entities with Position and Velocity, then transforms them.</li></ul><p>It separates the application state from the Three.js scene graph. You can add a new behavior by creating a new system without touching your existing code. Testing becomes a matter of validating pure functions against static data.</p><h3>The Project</h3><p>We are building a TypeScript application where users rotate objects by dragging the pointer. We will move from a basic setup to a functional 3D scene. Along the way, we will explore the pros and cons of ECS and when to use it.</p><h3>Bootstrapping our app</h3><p>We start with a standard Three.js boilerplate. This includes a renderer, a scene, some lights, and an environment texture. I’ll keep it minimalistic because diving deeper into Three.js isn’t a goal of this article. We are here to learn more about architecture, particularly the ECS.</p><pre>import * as THREE from &quot;three&quot;;<br>import { HDRLoader } from &quot;three/examples/jsm/loaders/HDRLoader&quot;;<br><br>function createScene() {<br>  // Prepare our Renderer, Scene, and Camera<br>  const renderer = new THREE.WebGLRenderer({<br>    antialias: true,<br>    powerPreference: &#39;high-performance&#39;,<br>  });<br>  renderer.setSize(window.innerWidth, window.innerHeight);<br>  renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));<br>  const scene = new THREE.Scene();<br>  const aspect = window.innerWidth / window.innerHeight;<br>  const camera = new THREE.PerspectiveCamera(70, aspect, 0.1, 100);<br>  camera.position.z = 5;<br><br>  // Set up a few lights to make our future objects visible<br>  const ambient = new THREE.AmbientLight(0xffffff, 2);<br>  const directionalLight = new THREE.DirectionalLight(0xffffff, 2);<br>  directionalLight.position.set(2, 2, 2);<br>  scene.add(ambient);<br>  scene.add(directionalLight);<br><br>  // Set a background and add a texture for reflections<br>  const envUrl = new URL(&quot;./assets/env_1k.hdr&quot;, import.meta.url);<br>  new HDRLoader().load(envUrl.toString(), (texture) =&gt; {<br>    texture.mapping = THREE.EquirectangularReflectionMapping;<br>    scene.environment = texture;<br>  });<br>  scene.background = new THREE.Color(0x0d1117);<br><br>  document.querySelector(&quot;#app&quot;)!.appendChild(renderer.domElement);<br><br>  return { scene, camera, renderer };<br>}<br><br>function createApp() {<br>  const { scene, camera, renderer } = createScene();<br><br>  function update() {<br>    renderer.render(scene, camera);<br>    requestAnimationFrame(update);<br>  }<br>  requestAnimationFrame(update);<br>}<br><br>createApp();</pre><h3>Setting up the World</h3><p>Now we have to choose which ECS implementation to use. For the purposes of this article, let’s choose an existing library, since building an optimized entity query system from scratch is out of scope. I think <a href="https://github.com/pmndrs/koota">Koota</a> is a good candidate — it’s a modern library with a big community ( <a href="https://github.com/pmndrs">pmndrs</a>), and its functional design avoids the class-heavy boilerplate of traditional ECS frameworks.</p><p>According to the ECS philosophy, every non-static object in the scene should be represented by an entity (simple ID). But in order to create new entities, we need a container to store them. We call this container world.</p><pre>// file: src/traits/world.ts<br><br>import { createWorld } from &#39;koota&#39;;<br><br>const world = createWorld();<br>export { world };<br></pre><h3>Adding 3D objects</h3><p>Standard Three.js implementations often involve creating classes that extend THREE.Mesh or THREE.Object3D. This couples the logic directly to the visual object. This is an inheritance-based design.</p><p>In ECS, we favor composition over inheritance by decoupling state (Components) from logic (Systems), using Entities only as unique identifiers. We use Entities as unique IDs and Components as pure data containers. A System is then responsible for the logic, such as spawning these objects into the scene. This separation ensures that our rendering and business logic remain decoupled and easy to extend.</p><p>We define a MeshRef trait (Koota&#39;s term for component) to hold the Three.js mesh instance.</p><pre>// file: src/traits/mesh.ts<br><br>import * as THREE from &#39;three&#39;;<br>import { trait } from &#39;koota&#39;;<br><br>export const MeshRef = trait(() =&gt; new THREE.Mesh());</pre><p>In Three.js, we nest objects to create parent-child relationships. In ECS, we use relations to define this hierarchy. To link objects and query children based on their parents, we use a ChildOf Relation. This allows systems to handle hierarchy without embedding behavior directly into the entities.</p><pre>// file: src/traits/world.ts<br><br>import { createWorld } from &quot;koota&quot;;<br><br>const world = createWorld();<br>export { world };</pre><p>Now we need a place to handle our spawning logic. In ECS, it’s the system’s responsibility. We can run a system once, twice, or every frame — it doesn’t matter. The major restriction — every system should operate on ECS data. So let’s create a spawnSystem. The spawnSystem is the function that actually puts our objects into the world using the world.spawn method from koota. It creates Three.js geometries, spawns entities with their associated traits, establishes a hierarchy based on our relations, and uses MeshRef as a bridge between logic and rendering.</p><pre>// file: src/systems/spawnSystem.ts<br><br>import * as THREE from &quot;three&quot;;<br><br>import { world } from &quot;../traits/world&quot;;<br>import * as MeshTraits from &quot;../traits/mesh&quot;;<br>import * as GlobalTraits from &quot;../traits/global&quot;;<br><br>export function spawnSystem(scene: THREE.Scene) {<br>  // Create the visual representation of a cube and a torus<br>  const cubeMesh = new THREE.Mesh(<br>    new THREE.BoxGeometry(1.5, 1.5, 1.5),<br>    new THREE.MeshBasicMaterial({ color: 0x44aaff, wireframe: true }),<br>  );<br><br>  const torusMesh = new THREE.Mesh(<br>    new THREE.TorusKnotGeometry(0.3, 0.08, 128, 16),<br>    new THREE.MeshStandardMaterial({<br>      color: 0x4e8ab3,<br>      metalness: 1,<br>      roughness: 0.1,<br>    }),<br>  );<br><br>  // Spawn entities and attach traits<br>  const cubeEntity = world.spawn(MeshTraits.MeshRef(cubeMesh));<br>  world.spawn(<br>    MeshTraits.MeshRef(torusMesh),<br>    GlobalTraits.ChildOf(cubeEntity),<br>  );<br><br>  // Add the meshes to our three.js scene<br>  cubeMesh.add(torusMesh);<br>  scene.add(cubeMesh);<br>}</pre><p>To make these objects appear, we execute spawnSystem once during initialization.</p><pre>// file: src/index.ts<br><br>// ... existing imports<br>import { spawnSystem } from &#39;./systems/spawnSystem&#39;;<br><br>function createScene() {<br> // ... createScene function remains the same<br>}<br><br>function createApp() {<br> const { scene, camera, renderer } = createScene();<br><br> // We execute the spawn system once to initialize our entities.<br> spawnSystem(scene);<br><br> function update() {<br> // ... update function remains the same<br> }<br> requestAnimationFrame(update);<br>}</pre><p>The cube and torus are now visible:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TWyhQtRTssG1e8Pu" /></figure><h3>Bringing Interactivity</h3><p>With static objects rendered, the next step is adding motion. The traditional inheritance approach often attaches event listeners directly inside the component class, coupling interaction logic to visual objects. In contrast, ECS treats input as pure data. Since there is only one pointer, we store its state globally. Any system can read it, eliminating the need for prop drilling.</p><p>Let’s define an Input trait for normalized coordinates and a Rotation trait to track orientation.</p><pre>// file: src/traits/global.ts<br><br>import { trait, relation } from &#39;koota&#39;;<br><br>export const ChildOf = relation();<br>// Input is a singleton because we only have one pointer<br>export const Input = trait({ x: 0, y: 0, deltaX: 0, deltaY: 0 });</pre><pre>// file: src/traits/mesh.ts<br><br>import * as THREE from &quot;three&quot;;<br>import { trait } from &quot;koota&quot;;<br><br>export const MeshRef = trait(() =&gt; new THREE.Mesh());<br>export const Rotation = trait({ x: 0, y: 0, z: 0 });</pre><p>We have the data structures, and now we need a system to populate them. The new inputSystem adds an Input singleton trait to the world, listens to DOM events, and updates the trait.</p><p>The event handler retrieves the current Input state via world.get to calculate deltas from previous coordinates. world.set pushes the new values back to the store, making changes immediately visible to other systems.</p><pre>// file: src/systems/inputSystem.ts<br><br>import type * as THREE from &#39;three&#39;;<br>import { world } from &#39;../traits/world&#39;;<br>import * as GlobalTraits from &#39;../traits/global&#39;;<br><br>export function inputSystem(renderer: THREE.WebGLRenderer) {<br>  const calculatePointer = (e: PointerEvent) =&gt; ({<br>    x: (e.clientX / window.innerWidth) * 2 - 1,<br>    y: -(e.clientY / window.innerHeight) * 2 + 1,<br>  });<br><br>  const handlePointerMove = (e: PointerEvent) =&gt; {<br>    if (!e.isPrimary) return;<br><br>    const { x, y } = calculatePointer(e);<br><br>    world.set(GlobalTraits.Input, { x, y });<br>  };<br><br>  world.add(GlobalTraits.Input);<br><br>  renderer.domElement.addEventListener(<br>    &#39;pointermove&#39;,<br>    handlePointerMove,<br>  );<br>}</pre><p>With the input data in place, we use it to rotate the objects. The movementSystem reads the Input and updates the Rotation trait. It uses world.onChange to create a reactive subscription, triggering only on data changes. It avoids wasted CPU cycles polling for static pointers.</p><p>We will apply different logic based on relations. The parent cube rotates on the Y axis while the child torus rotates on the X axis. The callback uses world.query rather than world.get. Note the distinction: get retrieves specific entities by ID, while query operates on all entities that match the criteria. Here, we want to find everything with the Rotation trait. The system functions regardless of whether the entity is a cube or a torus. Any entity with Rotation is updated.</p><p>I would like to highlight that this system focuses entirely on changing the rotation based on the input. ECS mandates that each system has a single responsibility. This enforces separation of concerns, ensuring high scalability and maintainability.</p><pre>// file: src/systems/movementSystem.ts<br><br>import { world } from &#39;../traits/world&#39;;<br>import * as MeshTraits from &#39;../traits/mesh&#39;;<br>import * as GlobalTraits from &#39;../traits/global&#39;;<br><br>export function movementSystem() {<br>  // Reactively run when Input changes<br>  world.onChange(GlobalTraits.Input, () =&gt; {<br>    const handleMovement = (<br>      [rotation]: [typeof MeshTraits.Rotation[&#39;schema&#39;]],<br>      e: Entity,<br>    ) =&gt; {<br>      const { x, y } = world.get(GlobalTraits.Input)!;<br><br>      if (Boolean(e.targetFor(GlobalTraits.ChildOf))) {<br>        // Rotate the torus horizontally<br>        rotation.x = y * Math.PI;<br>      } else {<br>        // Rotate the cube vertically<br>        rotation.y = x * Math.PI;<br>      }<br>    };<br><br>    world<br>      .query(MeshTraits.MeshRef, MeshTraits.Rotation)<br>      .select(MeshTraits.Rotation)<br>      .updateEach(handleMovement);<br>  });<br>}</pre><p>The next step is syncing ECS data with Three.js. The new transformSystem runs every frame, using world.query to locate entities with both MeshRef (visual) and Rotation (data).</p><p>This system has a distinct concern from the previous one. movementSystem handles the <em>simulation</em> (changing numbers), while transformSystem handles the <em>side effects</em> (updating the scene graph).</p><pre>// file: src/systems/transformSystem.ts<br>import { world } from &#39;../traits/world&#39;;<br>import * as MeshTraits from &#39;../traits/mesh&#39;;<br><br>export function transformSystem() {<br>  world.query(MeshTraits.MeshRef, MeshTraits.Rotation)<br>    .updateEach(([mesh, rotation]) =&gt; {<br>      mesh.rotation.set(rotation.x, rotation.y, rotation.z);<br>    });<br>}</pre><p>The final step is wire everything up in our entry point. The entry point initializes the spawn, input, and movement systems once. The transform system runs inside the loop to sync the visual state.</p><pre>// file: src/index.ts<br><br>// ... existing imports<br>import { inputSystem } from &#39;./systems/inputSystem&#39;;<br>import { movementSystem } from &#39;./systems/movementSystem&#39;;<br>import { transformSystem } from &#39;./systems/transformSystem&#39;;<br><br>function createScene() {<br> // ... createScene function remains the same<br>}`<br><br>function createApp() {<br>  const { scene, camera, renderer } = createScene();<br><br>  // Initialize Systems<br>  inputSystem(renderer);<br>  spawnSystem(scene);<br>  movementSystem();<br><br>  function update() {<br>    transformSystem(); // Sync ECS data to Three.js objects<br>    renderer.render(scene, camera);<br>    requestAnimationFrame(update);<br>  }<br>  requestAnimationFrame(update);<br>}</pre><p>Now, let’s check the final result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yp_m8M2ejiMv2-ykmDcFVg.gif" /></figure><p><a href="https://github.com/ibabkov/threejs-koota-ecs-example">GitHub</a> • <a href="https://ibabkov.github.io/threejs-koota-ecs-example/">Demo</a></p><h3>Final File Structure</h3><pre>src/<br>├── systems/<br>│   ├── inputSystem.ts<br>│   ├── movementSystem.ts<br>│   ├── spawnSystem.ts<br>│   └── transformSystem.ts<br>├── traits/<br>│   ├── global.ts<br>│   ├── mesh.ts<br>│   └── world.ts<br>└── index.ts</pre><h3>Benchmarks</h3><p>Now let’s validate the results for different numbers of objects. For this purpose, I have to use an InstancedMesh instead of the regular Mesh, which is outside the scope of the article. The architecture remains the same, but high-object-count scenes require InstancedMesh for the rendering layer to keep up with the ECS logic. Performance profiling over a 10-second interval on a Steam Deck LCD (SteamOS 3.7.19, Chrome 146.0, WebGPU: Off, WebGL 2) yields the following results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z__63zuqcuAKZYgwwEoiqA.png" /></figure><pre>Metric                        | 1000    | 25k         | 50k     | 100k<br>------------------------------|---------|-------------|---------|---------<br>FPS (Avg/Min/Max)             | 120     | 61          | 33      | 18<br>Input &gt; Render Latency (Avg)  | 0.52ms  | 4.42ms      | 9.96ms  | 18.36ms<br>Input &gt; Render Latency (Max)  | 1.3ms   | 14.4ms      | 26.5ms  | 38.1ms<br>Memory Footprint              | 17 MB   | 19 MB       | 21 MB   | 23 MB</pre><p>The results confirm that the overhead associated with the abstraction layers of Koota and ECS is negligible at this scale. The application maintains a stable 120 FPS with sub-millisecond input latency for 1,000 entities. Even with 100,000 entities, the memory footprint remains extremely low, increasing by only 6 MB. While the frame rate naturally drops as the scene complexity grows, the ECS logic remains efficient, demonstrating the scalability of this architecture.</p><h3>Beyond Basic ECS</h3><p>While the functional approach with Koota is efficient, complex production applications often require more granular control over the system architecture:</p><ul><li><strong>System Groups:</strong> Grouping systems (e.g., PhysicsGroup, RenderGroup) dictates when logic blocks execute.</li><li><strong>Execution Order:</strong> Priorities are strictly ordered in the pipeline: Input &gt; Movement &gt; Rendering.</li><li><strong>Lifecycle Methods:</strong> Class-based ECS implementations can support init(), update(), and destroy() methods for each system/group for precise resource management.</li></ul><h3>Conclusion</h3><p>We moved beyond a simple demo. By abandoning standard inheritance in favor of an Entity Component System (ECS) architecture, we gained a codebase where logic and rendering exist in separate, testable units.</p><p>Benchmarks indicate that this structure incurs almost no performance penalty, maintaining high frame rates and low latency even as the number of entities scales to the thousands.</p><h3>Pros</h3><p><strong>Strict Structure:</strong> The architecture enforces a strict structure, preventing logic-rendering coupling.</p><p><strong>Separation of Concerns:</strong> Systems remain isolated. Modifying one leaves others intact.</p><p><strong>Testability:</strong> Testing pure functions against static data is simpler than testing stateful classes.</p><p><strong>Performance:</strong> The abstraction layer is lightweight, creating efficient data pipeline processing.</p><h3>Cons</h3><p><strong>Paradigm Shift:</strong> Requires shifting from Object-Oriented to Data-Oriented thinking.</p><p><strong>Indirectness:</strong> Execution flow is implicit. Debugging involves tracing data changes rather than the call stack.</p><p><strong>Setup Cost:</strong> The initial boilerplate (world, queries, systems) is substantial for simple scenes.</p><h3>What’s Next</h3><p>ECS is a powerful tool, but it is not the only valid architecture for Three.js. In future articles of this series, we’ll explore alternative patterns that offer different trade-offs for web applications.</p><p><strong>About the Author: </strong>Ivan Babkov — 2D/3D Graphics Software Engineer from Canada, building interactive web experiences with design, animation, and visual effects.</p><p><a href="https://www.linkedin.com/in/ivan-babkov/">LinkedIn</a> • <a href="https://www.ibabkov.com/projects/">Portfolio</a> • <a href="https://github.com/ibabkov">GitHub</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=685768c7d91f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>