Fork of three.js that can render to real windows using @kmamal/sdl, @kmamal/gl (WebGL2) and @kmamal/gpu (WebGPU).
Install the fork and the packages for the renderers you use:
{
"dependencies": {
"@kmamal/three": "*",
"@kmamal/sdl": "*",
"@kmamal/gl": "*",
"@kmamal/gpu": "*"
}
}You only need @kmamal/gl for WebGLRenderer and @kmamal/gpu for WebGPU.
Add @kmamal/audio for audio and @kmamal/lil-gui for the GUI.
Pass the SDL window to the renderer instead of a canvas.
import sdl from '@kmamal/sdl'
import * as THREE from '@kmamal/three/webgpu'
const window = sdl.video.createWindow({ title: "Hello, Three!", webgpu: true, resizable: true })
const renderer = new THREE.WebGPURenderer({ window })
await renderer.init()
renderer.setClearColor(0xff0000)
const scene = new THREE.Scene()
const camera = new THREE.PerspectiveCamera()
renderer.setAnimationLoop(() => {
renderer.render(scene, camera)
})
window.on('close', () => {
renderer.dispose()
})For WebGLRenderer, create the window with opengl: true and import from '@kmamal/three'.
WebGPURenderer also works with forceWebGL: true on an opengl: true window.
render()presents the frame by itself. There is noswap()to call.- Resizing is up to you, as in a browser: call
renderer.setSize(window.pixelWidth, window.pixelHeight, false)and update the camera aspect from the window'sresizeevent. renderer.dispose()does not destroy the window.antialias: trueworks on both renderers.
renderer.domElement is an object with the parts of the DOM that three.js addons use: addEventListener, getBoundingClientRect(), clientWidth, ownerDocument, setPointerCapture() and so on.
SDL mouse, wheel and keyboard events arrive as pointerdown, pointermove, pointerup, pointercancel, wheel, keydown and keyup, followed by the compatibility events a browser sends: mousedown, mousemove, mouseup, click, dblclick, auxclick and contextmenu (canceling pointerdown suppresses the mouse* ones, as in a browser).
Each event is a single object dispatched to the canvas, then ownerDocument, then ownerDocument.defaultView; target stays the canvas and stopPropagation() ends the walk.
key comes from the keyboard layout and code from the physical key (the SDL scancode), so KeyW is the same key on every layout.
requestPointerLock() on the canvas or on document.body turns on the window's relative mouse mode and sets document.pointerLockElement; pointer events then target the locked element and carry movementX/movementY. document.exitPointerLock(), Escape and losing focus release it, and pointerlockchange fires on the document each time.
OrbitControls, MapControls, TrackballControls, ArcballControls, FlyControls, FirstPersonControls and TransformControls respond to SDL input. Dragging a TransformControls gizmo handle translates and scales objects along the picked axis, with snapping.
Touch input arrives as single-pointer mouse events.
SDL captures the mouse while a button is held, so a drag that leaves the window keeps delivering pointermove events (with coordinates outside the window) and ends with a pointerup. setPointerCapture() itself is a no-op.
- Images are decoded with
sharp, soTextureLoader,ImageLoader,CubeTextureLoaderandGLTFLoaderread PNG, JPEG, WebP, GIF, TIFF, SVG and HEIF fromhttp(s):,file:,data:andblob:URLs, and from plain file paths relative to the current directory. FileLoaderreads local files too.- XML loaders work:
SVGLoader,ColladaLoader,3MFLoader,AMFLoaderandKMZLoaderare tested on the sample models, as isFileLoaderwithresponseType: 'document'.VTKLoader(XML PolyData with ASCII arrays) andMaterialXLoader(all sample files) are tested too.UltraHDRLoaderis tested against Ultra HDR JPEGs generated by the test suite (gain map range, gamma, offsets, little- and big-endian MPF, upsampled gain maps); it decodes throughplatform.createImageBitmap.new platform.DOMParser()is a parser built on@xmldom/xmldom, with the namespace-aware queries, CSS selectors,style,sheetandidmembers these loaders use. Large files are parsed in JavaScript, at roughly 7 MB/s for element-dense XML and much faster for text-heavy files such as Collada float arrays: a 20 MB 3MF model loads in about 4 seconds and a 14 MB 3MF with textures in about 3. DRACOLoaderandKTX2Loaderrun their decoders inworker_threads. Give them an absolute path ending in/forsetDecoderPath()orsetTranscoderPath(), for example theexamples/jsm/libs/draco/directory of this package.Rhino3dmLoaderworks with therhino3dmlibrary (setloader.setLibraryPath()to the directory of the installed package, with a trailing/). Text dots become sprites whose label canvas is sized byplatform.devicePixelRatio, the pixel ratio of the first window (or thescaleof the first display before any window exists).ImageBitmapLoaderworks andGLTFLoaderuses it. Bitmaps are decoded bysharpand honorimageOrientation: 'flipY'andpremultiplyAlpha: 'premultiply';platform.createImageBitmapandplatform.isImageBitmapare the hooks.new platform.Worker(url),platform.fetch(url, init)and the other hooks are exported asplatformfrom'@kmamal/three'.platform.setFetchRoot(dir)makesplatform.fetchresolve paths starting with/, such as/models/a.glb, underdir, like a web server root. The real absolute path is not tried while a root is set.file:URLs and relative paths are unaffected.platform.setFetchRoot(null)turns this off again.
document.createElement('canvas') and new OffscreenCanvas() are available through the platform, backed by @napi-rs/canvas (Skia).
Use createCanvasElement() or platform.createElement('canvas') to create one, and platform.OffscreenCanvas and platform.ImageData for the other classes.
CanvasTextureworks on all renderers, including text drawn withfillText(), alpha, and redrawing withneedsUpdate.ImageUtils.getDataURL(), texture and scene JSON serialization,GLTFExporter(binary and JSON) andSVGLoadergradients work.- Text uses the system fonts that Skia finds. Register more with
GlobalFontsfrom@napi-rs/canvas. - Addons that create canvases through
platform.createElement()includeGLTFExporter,USDZExporter,SVGLoader,Lut,FlakesTexture,UVsDebug,ViewHelper,LUTImageLoader,LightProbeGenerator,VolumeSliceand the shadow map viewers. - Addons that need a real DOM do not work:
HTMLMesh,AsciiEffect,Text2D, and the helpers that draw a renderer's own canvas into a 2D canvas.
examples/jsm/libs/lil-gui.module.js re-exports @kmamal/lil-gui, which implements the lil-gui API (add, addColor, addFolder, onChange, listen, save/load and so on) for SDL.
Install it next to @kmamal/three to use the GUI in the examples or in your own code.
Each root new GUI() opens its own window, and folders share their root's window.
GUI.destroyAll() closes every GUI window, and the windows keep the process alive like any SDL window.
See its README for the details.
Ported examples are plain Node scripts next to the original HTML, for example examples/webgl_geometry_cube.mjs. Run them with node examples/webgl_geometry_cube.mjs from any directory.
The .mjs files are generated from the untouched upstream HTML by utils/port-examples.js, plus small hand-written patches in utils/port-examples/patches/ for examples that need more than the mechanical conversion (multiple windows, for example). npm run port-examples regenerates them and npm run port-examples-check fails if a file drifted; after editing an example by hand, run node utils/port-examples.js --update-patches <name>.
Examples that use npm packages which import three (three-mesh-bvh, postprocessing and others) rely on node_modules/three being utils/three-alias, a package named three whose files are this package's, so both names load the same modules.
They open their window through examples/jsm/utils/SDLWindow.js:
import * as THREE from '@kmamal/three';
import { createWindow, window } from '@kmamal/three/addons/utils/SDLWindow.js';
const sdlWindow = createWindow( { title: 'three.js webgl - geometry - cube', api: 'webgl' } );
const renderer = new THREE.WebGLRenderer( { antialias: true, window: sdlWindow } );
renderer.setSize( window.innerWidth, window.innerHeight );
window.addEventListener( 'resize', () => renderer.setSize( window.innerWidth, window.innerHeight ) );createWindow()takesapi: 'webgl'for aWebGLRendererandapi: 'webgpu'for aWebGPURenderer. PassforceWebGL: trueif theWebGPURendereris created withforceWebGL.windowanddocumentare the same objects the renderer canvas dispatches input events to.windowhasinnerWidth,innerHeight,devicePixelRatio,requestAnimationFrame(), firesresizewhen the SDL window changes size andloadonce the script has run, and callsonresize/onloadstyle handlers. They refer to the first window created, likeplatform.windowandplatform.document.location.searchcomes from the command line:node examples/webgpu_compile_async.mjs count=10sees?count=10. Assigninglocation.hreforlocation.search, or callinglocation.reload(), restarts the script with the new arguments.alert(),confirm()andprompt()print their message;confirm()returnsfalseandprompt()its default value.- Relative asset paths resolve from the
examples/directory and paths starting with/from the package root, as when the HTML was served from the repository root. Statsfromlibs/stats.module.jskeeps its API and shows the frame rate in the window title, for examplethree.js webgl - geometry - cube - 60 fps, 16 ms.setStatus()andsetTitle()change the title directly.new GUI()windows are closed and the process exits when any example window closes.- A
WebGLRendererwindow works together with GUI windows because the GUI uses a software renderer. Under i3 the example window stays tiled and the GUI windows float.
src/platform/Platform.js is a registry of everything three.js used to take from browser globals: requestAnimationFrame, navigator.gpu, fetch, presenting a frame, canvas and element creation, and the browser classes (platform.Image, ImageBitmap, OffscreenCanvas, ImageData, DOMParser, FileReader, Worker, ProgressEvent) and navigator.clipboard (platform.clipboard, backed by the SDL clipboard). Ported code replaces a global with the same name on platform, for example new DOMParser() becomes new platform.DOMParser() and window.innerWidth becomes platform.window.innerWidth. The GPUBufferUsage, GPUTextureUsage and GPUMapMode constants are plain numbers in WebGPUConstants.js, so importing the WebGPU renderer does not load @kmamal/gpu until it is used.
There is no browser implementation: platform is backed by src/platform/sdl/, which provides an SDLCanvas, the event bridge, image decoding, a fetch for local files, and a worker shim. setPlatform() can still override individual hooks, for example to stub them in tests. The package entry points (@kmamal/three, @kmamal/three/webgpu, @kmamal/three/tsl) resolve straight to src/, so addons that import '@kmamal/three' always share this one instance.
- The window surface for
WebGPURendererisbgra8unorm, like a browser canvas. - Audio runs on
@kmamal/audio, a Web Audio API implementation over@kmamal/sdl.platform.AudioContextandplatform.Audiocome from it (the ported examples use them instead of browser globals), and itsfetchis routed through the platform sonew platform.Audio('sounds/x.mp3')resolves like the other example assets. Rendering happens on the main thread, so long stalls cause dropouts. There are no video textures, no XR, noHTMLTextureand no CSS renderers. @kmamal/glexposes the S3TC, ETC2, ASTC, BPTC and RGTC compressed texture extensions that the GPU driver supports, soKTX2Loaderpicks a compressed format. Without support it falls back to uncompressed RGBA.
npm test # lint, upstream unit tests (the TSL/GPU ones in hidden windows), platform unit tests
npm run test-platform # the SDL platform layer and the GUI, no display or GPU needed
npm run test-platform-window # real windows: resizing, controls driven by SDL events, context loss
npm run test-e2e # every example against its browser screenshot, see test/e2e/README.mdThe window tests need a display and a GPU, and skip themselves otherwise.
On a tiling window manager, windows are made floating through i3-msg when I3SOCK is set, so the resize tests can run.
Tests for @kmamal/gl and @kmamal/gpu features live in those packages.