The SSR branch demonstrates,
- Server Side Rendering (SSR) using Threejs and headless-gl.
- Broadcasting image data to all clients using Socket.IO
- Loading an OBJ from the servers local file system using the OBJLoader.parse method.
Three.js is a renderer designed to run in the client browser first, so making it work server side requires a different way of thinking about it.
Your server will need to be capable of rendering WebGL and you may be able to use the headless-gl library to enable this capability.
Also note that most servers do not have a GPU capable of hardware accelerated WebGL, so the 3D rendering is done using the CPU. This will put significant demand on your server especially if the scene is large and complicated.
Resources, such as models, can be loaded into Three.js using the loaders parse method specific for your model format.
Since the code is running server side, loading the resources over a http connection, such as what happens when you run a loader in the browser, is not required.
The images you see in the example above are rendered server side almost as soon as you see it now. The latest date has been written as text onto the image before sending it to your client browser that you are using now.
In this example, three.js is not loaded client side into the browser, but the image from the servers canvas is drawn into the browsers canvas instead. There is 1 server side canvas being shared to as many client canvasses as your server can support sending the image data to.
One possible use case for SSR is for when you don't want to send geometry data to the client. In this example, no geometry data is sent to the client, only a 2D PNG formatted image that was generated server side.
To run the SSR branch locally, checkout the ssr branch.
git clone https://github.com/Sean-Bradley/Three.js-TypeScript-Boilerplate.git cd Three.js-TypeScript-Boilerplate git checkout ssr npm install npm run dev
When starting, if you see the error
THREE.WebGLRenderer: Error creating WebGL context. then you can try installing libgl1, freeglut3-dev and xvfb onto your server.
# Ubuntu 20.04 LTS apt-get update && apt-get -y install libgl1 freeglut3-dev xvfb