Skip to content
Shane Koester
Back to projects

Interactive 3D Game Engine

A 3D engine built from scratch in Java and OpenGL, with reflective water, real-time shadows, wind in the trees and a live scene editor.

  • Java
  • LWJGL
  • OpenGL
  • GLSL

Two tours of the demo scenes, rendered by the engine itself. Pick a scene above the video.

Engine3D is a 3D game engine written from scratch in Java, using LWJGL for windowing and input and raw OpenGL for everything on screen. There is no game framework underneath it: the engine loads its own models, compiles its own GLSL shaders, and manages its own vertex buffers, textures and frame buffers. It comes with two demo scenes to explore: a low-poly lakeside village and a realistic forest clearing by a lake. You can move the camera around, pick objects up and drag them with the mouse, and change them in a live editor.

Two scenes

The village is built from flat-coloured, low-poly kit models, on ground made to match them. The valley is designed rather than random: one height function shapes the river, the lake, the pond, the hills around the valley and level ground for each landmark. The ground colours and paths are painted from the same function when the scene loads, so moving a landmark also moves the flat ground, the path and the clearing around it. Things move on their own: the windmill and the waterwheel turn, a ship sails a slow loop around the lake, the fountain sprays and chimneys smoke. The hills are covered in hundreds of trees, far too many to draw one by one, so they are baked into one mesh for each eighth of the ring.

The forest is the realistic counterpart, built from photo-scanned models and textures. It is late afternoon with the sun low over the lake, and almost everything moves: wind in every tree, bush, fern and patch of grass, a flickering campfire with smoke and embers, fireflies along the shore, dust in the sunlight, falling leaves and mist drifting over the water.

All the models and textures are free CC0 assets. Small Java tools in the repository turn them into what the engine needs: they merge kit pieces into single meshes, bake materials into one shared texture, read glTF files, and build the forest’s trees from scanned twig and leaf images.

How a frame is drawn

Every frame is drawn in five passes:

  1. The scene is drawn from the sun’s point of view into a shadow map.
  2. It is drawn again from below the water surface, for the water’s reflection.
  3. It is drawn a third time for what lies under the surface, for the refraction.
  4. The main view is drawn into an off-screen buffer with 4× anti-aliasing, together with the water and the particles. Colours in this buffer can go brighter than white.
  5. Post-processing puts the result on screen. The brightest parts are blurred at half and quarter resolution and added back as a glow (bloom), a filmic tone curve brings the colours back into range, and a light colour grade and vignette finish the picture.

Entities that share a model and texture are grouped into batches so each model is bound once per pass, and back-face culling skips triangles that face away from the camera.

Every optional feature can be turned on and off with the number keys while the engine runs: anti-aliasing, anisotropic filtering, linear lighting, water effects, shadows, terrain detail, bloom and normal mapping. 9 turns everything off and 0 turns it all back on, which makes before-and-after comparisons easy.

Light and shadow

Lighting is calculated per pixel in the fragment shaders. Each shader supports up to three lights at once, each with its own colour and distance attenuation, and combines diffuse and specular terms. The maths happens in linear colour, and instead of a flat minimum brightness, ambient light comes from two directions: surfaces facing up pick up the colour of the sky, and surfaces facing down a darker bounce from the ground.

Normal maps add detail to the ground and to the scanned models. For models, the shader works out the surface directions it needs from screen-space derivatives, so meshes need no extra tangent data. Leaves are lit from both sides and let some light through, so they glow when the sun is behind them, and some materials give off light of their own, such as the glass of a lantern, which is bright enough to bloom.

The sun casts real-time shadows. Each frame the scene is drawn from the sun’s direction into a 4096 × 4096 depth map centred on the camera’s focus point. The centre is snapped to whole pixels of the map, so shadow edges don’t crawl as the camera moves. Every pixel on screen is compared with the map at nine nearby points to soften the edges, a small bias stops surfaces from shadowing themselves, and shadows fade out toward the edge of the map. Cut-out leaves cast leaf-shaped shadows, while fine grass receives shadows without casting any.

Distance fog fades far-away geometry into the sky colour, and a cube-mapped skybox fills in everything beyond it.

Wind

Foliage moves in the wind, entirely in the vertex shader. A plant bends more the higher a point is above its base, so it stays rooted to the ground. Gusts come from a slow swell plus two faster waves, neighbouring plants sway slightly out of step, and leaves far from the stem flutter quickly. The shadow pass uses the same function, so shadows sway with their plants.

Water

The water is the most involved effect. For the reflection pass, the camera is moved below the water surface and its pitch is flipped, and a clipping plane discards everything under the water line. For the refraction pass, the clipping plane is reversed so only what is under the water is drawn. To save work, the reflection leaves out fine ground cover, and the refraction only draws objects in or near the water. The water shader then projects both images onto the surface and blends them with a Fresnel term, so the surface is see-through when you look straight down and mirror-like at shallow angles. One large water surface covers everything below the water level, so the shorelines follow the shape of the land.

A scrolling distortion (DuDv) map offsets the texture lookups to create moving ripples, and a matching normal map drives highlights from the sun, which are bright enough to bloom. Fire, sparks and fireflies show up in the reflection too.

The refraction pass also stores depth, which the shader uses to work out how deep the water is at each pixel. Deeper water fades toward a deep-water colour, the way real water absorbs light. Ripples and highlights fade out as the water gets shallow, which gives the shoreline a soft edge instead of a hard line.

Terrain

Each terrain tile is a grid of vertices whose heights come from a function. The engine’s default is a seeded noise function, sampled over several octaves with cosine interpolation, and each scene can supply its own shape instead. Both demo scenes do: their height functions carve out the water, the level ground where things stand and the hills that close the view.

The ground is painted with four textures mixed by a blend map. In both scenes the blend map is painted from the terrain itself when the scene loads, so sand and gravel follow the shoreline and worn paths stay where they were laid out. To hide the repeating pattern of a tiled texture, each one is mixed with a larger copy of itself further away, and brightened or darkened by a blurred, much larger copy.

For the village, the same shader draws low-poly ground instead. The grid is coarser, with squares 16 units across, and each triangle is lit as one flat facet with a slightly different brightness, like a hand-painted one. Each square is split along whichever diagonal follows the contours of the land.

The same height data is used at runtime. A barycentric lookup returns the exact terrain height at any point, on the same triangles that are drawn, which keeps the camera above the ground and the water and lets objects sit on the surface as they move.

Interaction and tools

Mouse picking works by casting a ray. The cursor position is converted from screen space back through the projection and view matrices into a world-space direction, and a binary search along that ray finds where it hits the terrain. Holding the right mouse button on an object drags it across the landscape, following the ground height. Dragging the village’s street lamp takes its light along with it.

Particles are drawn with GPU instancing: one quad is uploaded once, and the per-particle transforms and texture offsets are streamed into a single buffer and drawn in one call. Each particle animates through a texture atlas and blends between frames. The scenes use them for fire, smoke, embers, spray, fireflies, dust, mist and falling leaves. Flames and smoke rise because their gravity is negative, and fire and sparks are brighter than white, so they bloom.

Alongside the 3D window there is a scene editor built with Java Swing. It has tabs for the objects, the lights and the camera, and lets you change position, rotation, scale, light colour and attenuation with sliders and spinners while the engine is running, so changes show up immediately. Models come in through an OBJ loader I wrote, which converts the file into indexed vertex data and handles vertices that share a position but need different texture coordinates.

The engine can also film itself. Camera moves are written as keyframes in a text file and played back along a smooth curve. A recorder renders each shot off-screen, moving the world forward by exactly one frame’s worth of time per frame, and sends the frames to ffmpeg, so the video is perfectly smooth however fast the computer is. The demo videos were made this way.

What I learned

  • A 3D scene is mostly maths that decides where each point lands on a flat screen. Once that clicked, the rest felt far less mysterious.
  • Realistic effects are often simple tricks. The water looks complicated, but it is the same scene drawn two extra times and blended together.
  • Small numbers change everything. Nudging the fog distance or the brightness of a light changes the mood of the whole scene.
  • Building a tool is worth the time. Moving objects with sliders in the editor is much faster than changing numbers in code and restarting.