lm3d
Quick reference for building browser 3D applications with a Three.js-inspired Java scene graph, TeaVM, and WebGL, without a JavaScript 3D library.
Open the interactive WebGL demo or clone lmctl-ai/lm3d. Version 0.1.0 is MIT licensed; TeaVM uses Apache-2.0, and the licenses are compatible.
Build and run
Install Java 21, Maven, Node 24.15 or newer, lmcode-java commit b88d3401ee10210a0a6583991d6a81427d5f112a in the local Maven repository, and LMCode compiler @lmctl-ai/lmctl 0.2.482. The runtime commit and compiler version are pinned for reproducible bytecode and TeaVM compatibility.
git clone https://github.com/lmctl-ai/lm3d.git git clone https://github.com/lmctl-ai/lmcode-java.git (cd lmcode-java && git checkout b88d3401ee10210a0a6583991d6a81427d5f112a && mvn -DskipTests install) cd lm3d npm install --prefix compiler @lmctl-ai/lmctl@0.2.482 export LMCODE_COMPILER_MODULE="$PWD/compiler/node_modules/@lmctl-ai/lmctl/dist/dsl.js" mvn clean package
The build compiles Java to target/demo/teavm.js and copies demo.html, demo.css, boot.js, and the favicon. boot.js contains only main(); it is not a rendering library. To generate assets directly into another static site, use an absolute output directory:
mvn -Ddemo.output=/absolute/site/path clean package
API map
| Package | Types | Purpose |
|---|---|---|
| com.lmctl.lm3d.core | Object3D, Group, Scene, Mesh, Color | Scene hierarchy, visibility, transforms, mesh geometry/material pairing, and RGB colors. |
| com.lmctl.lm3d.math | Vector3f, Matrix4f | Mutable vectors and column-major matrices for transform composition, inversion, projection, and view math. |
| com.lmctl.lm3d.geometry | BufferGeometry, BoxGeometry, SphereGeometry, PlaneGeometry, TorusGeometry | Indexed positions, normals, and triangle geometry. |
| com.lmctl.lm3d.material | MeshBasicMaterial, MeshPhongMaterial | Unlit color or ambient/diffuse/specular lighting with emissive color, shininess, and opacity. |
| com.lmctl.lm3d.light | AmbientLight, DirectionalLight, PointLight | Scene lighting. Point lights support optional distance attenuation. |
| com.lmctl.lm3d.camera | PerspectiveCamera, OrthographicCamera | Projection matrices, camera position, up vector, and look-at target. |
| com.lmctl.lm3d.renderer | WebGLRenderer | Shader compilation, cached GPU buffers, normal matrices, depth testing, alpha blending, and drawing. |
| com.lmctl.lm3d.loader | GltfLoader, GltfModel | Asynchronous glTF 2.x JSON loading, external buffers, node hierarchies, geometry, and material conversion. |
| com.lmctl.lm3d.lmcode | Lm3dHost | Typed LMCode host functions for groups, meshes, transforms, parenting, and Phong materials. |
| com.lmctl.lm3d.controls | OrbitControls | Java pointer-drag rotation, wheel zoom, configurable limits, and reset. |
Create a scene
Construct the scene and camera, add meshes and lights, then render with a canvas obtained through TeaVM JSO. Java fields are intentionally public and mutable, matching the direct manipulation style familiar to Three.js users.
HTMLCanvasElement canvas =
(HTMLCanvasElement) document.getElementById("scene");
Scene scene = new Scene();
PerspectiveCamera camera =
new PerspectiveCamera(48, 16f / 9, 0.1f, 100);
camera.position.set(5, 4, 7);
camera.lookAt(0, 1, 0);
Mesh cube = new Mesh(
new BoxGeometry(2, 2, 2),
new MeshPhongMaterial("#61d6c5"));
cube.position.y = 1.25f;
scene.add(cube);
scene.add(new AmbientLight("#ffffff", 0.4f));
DirectionalLight sun = new DirectionalLight("#ffffff", 1);
sun.position.set(4, 7, 5);
scene.add(sun);
WebGLRenderer renderer = new WebGLRenderer(canvas);
renderer.setSize(960, 540);
renderer.render(scene, camera);
Add the imports shown in the repository README. The renderer updates scene world matrices and the camera view on every render. Set renderer dimensions and camera aspect together when resizing.
Hierarchy and transforms
Object3D owns position, rotation, scale, matrix, matrixWorld, visible, name, and a child list. Add children with parent.add(child), not scene.add(parent).add(child): add returns the receiver, so the chained form adds both nodes to the scene. Euler rotation is expressed in radians. Geometry uses a right-handed coordinate system and cameras look at their target.
Group group = new Group();
group.position.set(2, 0, 0);
group.rotation.y = (float) Math.PI / 4;
Mesh mesh = new Mesh(new BoxGeometry(1, 1, 1), material);
mesh.position.set(1, 1, 0);
scene.add(group);
group.add(mesh);
Geometry contract
BufferGeometry accepts float positions, matching float normals, and char triangle indices. Arrays are cloned on input and output. Every three positions form one vertex, every three indices form one triangle, and indices must reference existing vertices. WebGL 1 limits an indexed geometry to 65,536 vertices.
float[] positions = {0, 0, 0, 1, 0, 0, 0, 1, 0};
float[] normals = {0, 0, 1, 0, 0, 1, 0, 0, 1};
char[] indices = {0, 1, 2};
BufferGeometry triangle =
new BufferGeometry(positions, normals, indices);
BoxGeometry takes width, height, and depth. SphereGeometry takes radius, width segments, and height segments. PlaneGeometry takes width and height in the XY plane. TorusGeometry takes major radius, tube radius, radial segments, and tubular segments.
Load glTF
GltfLoader reads glTF 2.x JSON documents asynchronously. Add the returned root to the scene in the success callback and render again. External buffer URIs resolve relative to the .gltf document and follow normal HTTP CORS rules.
GltfLoader loader = new GltfLoader();
loader.load("models/hierarchy.gltf", model -> {
scene.add(model.root());
renderer.render(scene, camera);
System.out.println(model.meshCount() + " meshes, "
+ model.triangleCount() + " triangles");
}, error -> status.setInnerText(error));
Supported geometry includes FLOAT VEC3 positions and normals, sequential or indexed triangles, interleaved buffer views, accessor strides, and unsigned byte, short, or integer indices within the renderer's 16-bit limit. Missing normals are generated. Node TRS, quaternion rotation, node matrices, and multiple primitives become Java scene nodes and meshes.
Materials map base color, emissive factor, alpha blend, KHR_materials_unlit, and a Phong approximation of metallic/roughness factors. GltfModel exposes root, meshCount, vertexCount, and triangleCount.
Runnable glTF examples
| Demo selection | Files | Demonstrates |
|---|---|---|
| glTF: embedded cube | models/cube-embedded.gltf | Base64 buffer, quaternion rotation, indexed cube geometry. |
| glTF: external-buffer hierarchy | models/hierarchy.gltf and hierarchy.bin | External buffer, parent and children, two materials, generated normals. |
| glTF: interleaved torus | models/torus-interleaved.gltf and torus.bin | Interleaved accessors, byte stride, node matrix, default scene and material. |
The original examples are MIT licensed. Regenerate them with python3 scripts/generate-gltf.py from the repository.
Build scenes with LMCode
Lm3dHost exposes Java scene construction as typed LMCode functions. LMCode holds integer handles; Java owns the actual Object3D instances. The source schema and three annotated handlers are published under lmcode/ in the demo directory.
| Function | Returns | Purpose |
|---|---|---|
| lm3d_group() | int | Create a group handle. |
| lm3d_box(w, h, d, color) | int | Create a Phong box mesh. |
| lm3d_sphere(radius, widthSegments, heightSegments, color) | int | Create a Phong sphere mesh. |
| lm3d_torus(radius, tube, radialSegments, tubularSegments, color) | int | Create a Phong torus mesh. |
| lm3d_add(parent, child) | void | Attach a child node. |
| lm3d_position, lm3d_rotation, lm3d_scale | void | Set a node handle's position, Euler rotation in radians, or scale using x, y, z. |
| lm3d_shininess(node, value) | void | Set Phong shininess. |
| lm3d_specular(node, color), lm3d_emissive(node, color) | void | Set Phong specular or emissive color. |
| lm3d_use(group) | void | Give the completed root to the Java application. |
The demo's LMCode cube option runs this handler from lmcode/scenes.lms:
@cube
fn buildCube() -> void implements SceneHandler {
let root = lm3d_group();
let cube = lm3d_box(2.0, 2.0, 2.0, "#61d6c5");
lm3d_position(cube, 0.0, 1.25, 0.0);
lm3d_rotation(cube, 0.15, 0.4, 0.0);
lm3d_shininess(cube, 72.0);
lm3d_add(root, cube);
lm3d_use(root);
}
Register Lm3dHost with the exact schema, load the compiled program, and call the entry whose annotation is cube, hierarchy, or materials. The Maven build embeds bytecode and exact schema bytes in a generated Java class.
Registry registry = new Registry(false);
Lm3dHost host = new Lm3dHost(registry, scene::add);
Program program = Program.load(bytecode, schemaBytes, registry);
program.call(entryIndex, new Context(), registry, List.of());
The hierarchy handler composes three transformed meshes. The materials handler exercises shininess, specular, and emissive properties. Use host.meshCount() and host.vertexCount() for statistics, and host.used() to verify that the handler supplied a root. The host rejects direct and indirect scene cycles. The failure handler calls lm3d_use and then fails; the demo stages roots and replaces the previous scene only after successful completion.
Animate and orbit
Use TeaVM's Window.requestAnimationFrame. Update object transforms in Java and call render again. Cancel or gate updates when leaving a scene. The demo continues rendering while paused so orbit controls remain responsive, but stops changing object transforms.
OrbitControls controls = new OrbitControls(camera, canvas);
controls.minRadius = 2;
controls.maxRadius = 30;
Window.requestAnimationFrame(timestamp -> {
cube.rotation.y += 0.01f;
renderer.render(scene, camera);
});
The one-argument renderer uses a normal non-preserved drawing buffer. Use new WebGLRenderer(canvas, true) when canvas.toDataURL or gl.readPixels must inspect frames after rendering.
Scope and limits
- lm3d is a focused Three.js-inspired subset, not API-compatible with Three.js and not a port of its source.
- No Three.js code, external JavaScript library, binary GLB container, textures, sparse accessors, non-triangle glTF primitives, skins, glTF animation, shadow map, post-processing, quaternion animation API, or transparent-object sorting is included.
- Meshes render double-sided. All visible ambient lights are accumulated; the first visible directional and point lights are used.
- BufferGeometry is immutable and uploaded once per renderer. Replacing a mesh geometry creates a new cached GPU entry; renderer.dispose releases all cached buffers and the shader program.
- WebGL 1 and GLSL support are required. Display initialization, glTF loading, LMCode compilation, and host dispatch errors through accessible page status rather than failing silently.
Verify an application
mvn clean verify npm ci npx playwright install --with-deps chromium npm test
The 21 JVM tests cover math, cameras, hierarchy, colors, geometry, invalid inputs, LMCode handlers, failure after use, and indirect-cycle rejection. The browser suite checks real WebGL pixels, three procedural geometries, all three glTF examples and external buffers, all three successful LMCode scenes, failure-atomic replacement, animation, pause/resume, keyboard input, orbit, zoom, reset, mobile overflow, local-only runtime resources, and browser errors. Set DEMO_URL to run the same suite against a deployed page.