Generating Interactive Three.js Scenes with Large Language Models
Large Language Models (LLMs) excel at writing code but struggle with generating binary 3D assets. This article explores how to leverage LLMs to create interactive Three.js scenes, covering their capability boundaries, a four-step workflow for modular code generation, a complete HTML example, common troubleshooting solutions, and performance budgets for desktop and mobile deployment.
1. Understand What the Model Can Do
The primary output of Large Language Models (LLMs) is text, which means they are good at writing code but not at directly producing binary 3D assets. In Three.js projects, an LLM can write scene setups, camera controls, lighting configurations, animation loops, and interaction logic. The deliverable is typically a web page, a JavaScript module, or a piece of logic code that can be imported into a game engine.
Models can also generate geometry data files, but it is crucial to distinguish between formats. OBJ is a text format where vertices, normals, UVs, and faces are listed line by line. glTF comes in two forms: .gltf is JSON text with a readable structure, but the referenced buffers and texture paths are prone to errors; .glb is a binary container that packs JSON, geometry buffers, and textures into a single file, making manual modification almost impossible. Models lack a true understanding of vertex coordinates, normal directions, and UV values, often resulting in clipping, disproportionate scales, or missing faces. These files must be opened and checked in a viewer or editor, rather than just verifying if the code runs.
The capability boundaries of the model can be summarized in three points:
- Good at: Building scene structures, writing camera and interaction logic, and generating procedural geometry such as cubes, cylinders, and simple architectural blocks.
- Needs human oversight: Proportions of complex models, visual effects of textures and materials, and actual runtime performance.
- Not good at: Recalling exact dimensions of a real building from memory, or guaranteeing identical visual results across different browsers and devices.
Before delivery, human inspection and code patching are mandatory. API names provided by the model must also be verified against the official documentation, as it might mix interfaces from different versions. The verification method involves opening the documentation page matching the project version (e.g., r160), searching by class or method name, confirming constructor parameters, and checking for deprecations.
When encountering outdated syntax generated by the model, record it in your team’s error list. For example, new THREE.Geometry() was removed after r125, and renderer.outputEncoding from older tutorials was changed to renderer.outputColorSpace in newer versions. Documenting these examples allows future prompts to explicitly specify what to avoid.
2. A Four-Step Workflow
1. Decompose Requirements
Before starting, clearly define three things: visual style, interaction method, and runtime environment. The library name, version number, and loading method should also be specified. Without a version number, the model might provide outdated syntax that fails to run.
An instruction like “make a 3D house” leaves the model guessing. A better approach is to include the version, loading method, geometry, interaction, and lighting in the prompt:
Use Three.js r160, load modules via importmap. Generate a low-poly blue cube using BufferGeometry. Do not use THREE.Geometry. Support mouse drag to rotate the camera, and light the scene with one DirectionalLight and one AmbientLight.
By writing it this way, the model knows which version to use, how to load it, what interactions to implement, and avoids removed interfaces.
2. Step-by-Step Generation and Modular Combination
If you ask the model to generate a complete game with scenes, characters, physics, and audio all at once, the result is usually chaotic. The model tends to miss dependencies or mix two sets of APIs. The correct approach is to break the large task into sub-modules, generate them separately, and then combine them.
Taking a “3D mini-game” as an example, it can be split into five parts: scene, character, control, collision, and UI. Generate each module in a separate conversation and agree on the exposed function names and parameters in the prompt. The prompt for the control module could be written like this:
Please output only the control module. Export the function
createController(camera, domElement)that returns an object containingupdate(dt)anddispose(). Import OrbitControls using thethree/addonspath, and do not include any scene setup code.
After generating each module, verify it individually. Check if the export names match the agreement, if dependencies are injected via parameters instead of global variables, if the unit for update is in seconds, and if dispose removes event listeners and releases geometries and materials. Combining modules only after they pass inspection makes troubleshooting much easier.
3. Run and Troubleshoot
Below is a complete example. It uses Three.js r160, loads modules via importmap, and implements drag rotation with OrbitControls. It does not rely on external model or texture files, but requires an internet connection to load Three.js from a CDN during runtime.
To run it: save the code as index.html in a directory, execute python -m http.server 8000 in that directory, and then visit http://localhost:8000/index.html. Do not double-click the file directly. When a browser opens a page using the file:// protocol, module scripts will fail to load due to CORS restrictions.
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Three.js r160 Interactive Scene</title><style>html, body { margin: 0; height: 100%; overflow: hidden; background: #1e1e24; }canvas { display: block; }</style><script type="importmap">{"imports": {"three": "https://cdn.jsdelivr.net/npm/three@0.160.0/build/three.module.js","three/addons/": "https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/"}}</script></head><body><script type="module">import * as THREE from 'three';import { OrbitControls } from 'three/addons/controls/OrbitControls.js';const scene = new THREE.Scene();scene.background = new THREE.Color(0x1e1e24);const camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 0.1, 100);camera.position.set(3, 2.5, 4);const renderer = new THREE.WebGLRenderer({ antialias: true });renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));renderer.setSize(window.innerWidth, window.innerHeight);document.body.appendChild(renderer.domElement);const controls = new OrbitControls(camera, renderer.domElement);controls.enableDamping = true;controls.target.set(0, 0.5, 0);const ambientLight = new THREE.AmbientLight(0xffffff, 0.4);scene.add(ambientLight);const dirLight = new THREE.DirectionalLight(0xffffff, 1.0);dirLight.position.set(5, 8, 5);scene.add(dirLight);const cubeGeometry = new THREE.BoxGeometry(1, 1, 1);const cubeMaterial = new THREE.MeshStandardMaterial({ color: 0x2f6fed });const cube = new THREE.Mesh(cubeGeometry, cubeMaterial);cube.position.y = 0.5;scene.add(cube);const floorGeometry = new THREE.PlaneGeometry(10, 10);const floorMaterial = new THREE.MeshStandardMaterial({ color: 0x3a3a44 });const floor = new THREE.Mesh(floorGeometry, floorMaterial);floor.rotation.x = -Math.PI / 2;scene.add(floor);const clock = new THREE.Clock();function animate() {const dt = clock.getDelta();cube.rotation.y += dt * 0.5;controls.update();renderer.render(scene, camera);}renderer.setAnimationLoop(animate);function onResize() {camera.aspect = window.innerWidth / window.innerHeight;camera.updateProjectionMatrix();renderer.setSize(window.innerWidth, window.innerHeight);}window.addEventListener('resize', onResize);window.addEventListener('beforeunload', () => {renderer.setAnimationLoop(null);window.removeEventListener('resize', onResize);controls.dispose();cubeGeometry.dispose();cubeMaterial.dispose();floorGeometry.dispose();floorMaterial.dispose();renderer.dispose();});</script></body></html>
In the example, the importmap maps three to a fixed version of three.module.js and three/addons/ to the examples/jsm directory of the same version. This ensures that three/addons/controls/OrbitControls.js matches the core library version. Both version numbers must be identical.
If the page behaves unexpectedly after running, check the following points:
- Open the Network panel in your browser’s developer tools, refresh the page, and check the status code of
three.module.js. A 200 status code indicates successful loading. A 404 usually means the version number or path is incorrect, while a failed request is likely due to network or proxy interception. - If the console shows
Failed to resolve module specifier "three", the importmap did not take effect. Common causes are that the importmap is written after the module script or contains extra commas in the JSON. - If the console shows
does not provide an export named 'OrbitControls', the import path is incorrect. The oldexamples/js/controlspath from older tutorials has been removed in newer versions; you should usethree/addons/controls/OrbitControls.js. - If executing
http.serverpromptsAddress already in use, port 8000 is occupied. Use a different port, such as 8001, and update the access URL accordingly. - If all URLs open but the screen remains blank, check if another page or extension is occupying the WebGL context, or if your graphics driver is too old.
Common issues and solutions are listed below:
| Issue | Common Cause | Solution |
|---|---|---|
Console reports THREE.Geometry is not a constructor |
Using an outdated API removed after r125 | Use BufferGeometry, or use built-in geometries like BoxGeometry directly |
Console reports Failed to resolve module specifier |
Missing importmap, invalid JSON, or script placement | Place the importmap before the module script and verify JSON syntax |
Console reports does not provide an export named |
Incorrect import path or version mismatch | Use the three/addons/ path and ensure the importmap version is consistent |
| Module fails to load after double-clicking HTML | Module scripts are restricted by CORS under the file:// protocol |
Access the page via python -m http.server |
| Model proportions are abnormal or clipping occurs | No unified units for dimensions or unverified coordinates | Use BoxGeometry to mark key dimensions and add a GridHelper for reference |
| Screen is entirely black or material lacks shading | No light source in the scene, or material requires lighting but none is set | Add an AmbientLight and a DirectionalLight |
| Texture colors look gray or too dark | Incorrect color space setting | Set texture.colorSpace to THREE.SRGBColorSpace for color textures |
| Noticeable lag during dragging | Too many draw calls or pixel ratio too high | Limit the upper bound of setPixelRatio, merge geometries, and reduce independent Meshes |
| Video memory continues to grow after repeatedly switching pages | Geometries, materials, or textures are not released | Call dispose on unload and remove event listeners |
| View does not stop smoothly after enabling damping | enableDamping is enabled, but controls.update() is not called in the loop |
Call controls.update() every frame in the animation loop |
4. Performance Budget and Manual Verification
Performance Budget
The values in the table below are starting points, not universal standards. A formal budget should be tested on target devices and adjusted accordingly.
| Metric | Desktop Reference Budget | Mobile Reference Budget | Measurement Method |
|---|---|---|---|
| Draw calls | ≤ 100 | ≤ 50 | Read renderer.info.render.calls after render |
| Triangles | ≤ 200,000 | ≤ 80,000 | Read renderer.info.render.triangles after render |
| Single texture size | ≤ 2048×2048 | ≤ 1024×1024 | Check the asset inventory |
| Frame rate | Stable at 60 FPS | Stable at 30 FPS | Record 5 seconds in Chrome’s Performance panel, or calculate frame intervals in requestAnimationFrame |
| Pixel ratio | Upper limit of 2 | Upper limit of 1.5 | Check the argument in setPixelRatio |
When measuring, keep the conditions constant. Use the same device, browser, and resolution (e.g., 1920×1080), and close other programs and browser extensions that consume GPU resources. Record each metric at least three times and take the median. Draw calls and triangles can be temporarily logged in the animation loop:
renderer.render(scene, camera);console.log(renderer.info.render.calls, renderer.info.render.triangles);
Delete this log line after testing; otherwise, it will output every frame and interfere with measurement results.
Manual Verification Checklist
Before release, check the following items in order:
- Open the page via a local HTTP server. The console shows no red errors and no 404 requests.
- The version numbers for
threeandthree/addons/in the importmap are consistent and match the version specified in the prompt. - All API names have been verified against the official documentation for the corresponding version, with no removed or deprecated interfaces used.
- Model dimensions and proportions are checked against reference drawings or actual data, not just visual observation.
- Materials and lighting have been visually inspected in Chrome, Edge, and Firefox.
- After dragging, zooming, and resizing the window, the aspect ratio and interactions behave normally.
- After leaving the page, memory usage in the Performance panel does not continuously increase.
- Third-party resource licenses have been confirmed. Three.js uses the MIT license, but models, textures, and fonts need separate license verification.
- Performance metrics meet the budget from the previous section, and measurement records are retained for future comparison.
Only deliver to the stakeholders after completing these checks.
