
OpenGL ES 3 renderer and ECS with deferred and clustered forward+ pipelines, metal/roughness PBR, key and point-light shadows, HDR bloom, FXAA, instancing, OBJ/MTL loader.
An OpenGL ES 3 renderer and entity-component system written in Kotlin Multiplatform, running on Android and iOS from one codebase: deferred and clustered forward+ pipelines, metal/roughness PBR, shadow maps for the key light and for point lights, HDR with bloom and tonemapping, FXAA and instancing. The engine, scene, OBJ/MTL loaders, math and the whole renderer are common Kotlin; Android and iOS each contribute only a thin GL binding and an asset reader.
The demo is the Utah teapot on a spinning turntable, circled by three rings of coloured point lights (32 in all); the six above the teapot cast shadows. Drag to orbit, pinch to zoom, double-tap to open the lid, tap to switch between the deferred and forward+ pipelines, long-press to pause.
| Android · deferred | Android · forward+ | iOS simulator · deferred |
|---|---|---|
![]() |
![]() |
![]() |
The two pipelines shade with the same GLSL functions and produce the same image: on the paused frame above, the mean difference is 0.5/255 and no pixel differs by more than 16/255 (the residue is the 8-bit G-buffer). The iOS screenshot comes from CI, which builds the app, runs it in the simulator and captures a frame.
Point light shadows, on and off, same frame. The teapot throws a shadow from each of the six lights above it, and the turntable shadows the floor around its rim:
flowchart LR
pshadow["Point light shadows<br/>cube maps in one atlas"]
shadow["Key light shadow<br/>2048² orthographic"]
subgraph deferred["Deferred"]
gbuf["G-buffer<br/>albedo · normal · emission · depth"]
light["Lighting<br/>ambient + key light, full screen;<br/>one scissored pass per point light"]
gbuf --> light
end
subgraph forward["Forward+ (clustered)"]
clusters["Light clusters<br/>64 px tiles × 16 depth slices,<br/>built on the CPU"]
fwd["One forward pass<br/>loops over its cluster's lights"]
clusters --> fwd
end
trans["Transparent surfaces<br/>forward+, back to front"]
post["Bloom → ACES tonemap → FXAA"]
pshadow --> shadow --> deferred & forward
deferred & forward --> trans --> postPr, Pm, Ke), with a fallback from Blinn-Phong Ns.
Ambient is a sky/ground gradient with Karis' analytic split-sum approximation for its specular part.
Base-colour textures are SRGB8_ALPHA8, so filtering happens in linear space.gl_FragCoord and its view depth. The same pass shades transparent surfaces in the deferred path,
which a G-buffer cannot hold.sampler2DShadow
with hardware comparison and a 3×3 PCF kernel; slope-scaled polygon offset plus a normal offset against acne.castsShadows (up to 8 visible at once) render six cube faces into one
depth atlas, a row per light, because ES 3.0 cannot index an array of cube samplers dynamically. The shader picks
the face by the major axis of the light-to-surface direction and reproduces the face's projection. Faces are rendered
slightly wider than 90° so 3×3 PCF never samples a neighbouring tile, and each light only draws the instances whose
bounding sphere reaches into its own.RGBA16F target. Bloom is a five-level mip chain
(soft-threshold prefilter, 4-tap downsample, tent upsample), followed by exposure, the ACES filmic curve and FXAA.
If the GPU can't render to half-float (EXT_color_buffer_half_float), everything falls back to 8-bit targets
and the renderer reports hdr == false.glDrawArraysInstanced with per-instance model
matrix, normal matrix and tint in a dynamic vertex buffer. The 32 light bulbs are one draw call.Parent links,
with cycle detection. Lights are components (PointLight), as is per-instance colour (Tint): the lid is a child of
the teapot, which is a child of the turntable, and each light is a child of its ring.usemtl splits, generated face normals)
and MTL readers that work on plain text, so they are unit-tested without a device.
Each mesh is uploaded to the GPU once as an interleaved VBO in a VAO.Gl is a ~45-method interface implemented with GLES30 on Android
and Kotlin/Native's platform.gles3 bindings on iOS. The renderer's tests run against a recording fake of it,
checking pass order, instancing, shadow budgets and caster culling, clustering and the half-float fallback
without a GPU.The engine is on Maven Central. In a Kotlin Multiplatform module (Android and iOS targets):
commonMain.dependencies {
implementation("agency.encrypt:glrenderer:0.1.0")
}An Android-only app can use the same line in its dependencies block. A scene is a World of entities, and a RenderLoop turns the platform's GL surface callbacks into
"run the systems, then render". Models are OBJ files with their MTL materials and textures, read through an
AssetSource.
val world = World().apply {
createEntity().add(Transform()).add(ModelRef("models/chair.obj"))
createEntity()
.add(Transform(position = Vec3(0f, 2.5f, 1f)))
.add(PointLight(color = Vec3(6f, 5.4f, 4.5f), radius = 6f, castsShadows = true))
addSystem(TransformSystem()) // last: resolves the hierarchy into WorldTransform for the renderer
}
val camera = OrbitCamera(target = Vec3(0f, 0.5f, 0f), distance = 4f)Android — EngineSurfaceView sets up an OpenGL ES 3 context and drives the loop on its render thread:
class ViewerActivity : Activity() {
private lateinit var view: EngineSurfaceView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val loop = RenderLoop(AndroidGl(), AndroidAssetSource(assets), world, camera) { renderer ->
renderer.pipeline = Pipeline.FORWARD_PLUS // runs again for each new GL context
}
view = EngineSurfaceView(this, loop)
setContentView(view)
}
override fun onResume() { super.onResume(); view.onResume() }
override fun onPause() { view.onPause(); super.onPause() }
}Changes from the UI thread (input, settings) go through view.queueEvent { ... }, onto the render thread.
iOS — build the loop in Kotlin, where default arguments and lambdas are pleasant, and drive it from a
GLKView in Swift (iosApp/Sources/RendererViewController.swift is a complete example):
// iosMain, in your shared module: Viewer.kt
fun createViewer(): RenderLoop = RenderLoop(IosGl(), BundleAssetSource("assets"), world, camera)loop = ViewerKt.createViewer() // with an ES 3 EAGLContext current
loop.surfaceCreated()
override func glkView(_ view: GLKView, drawIn rect: CGRect) {
loop.surfaceChanged(width: Int32(view.drawableWidth), height: Int32(view.drawableHeight))
loop.drawFrame(timeSeconds: CACurrentMediaTime(), maxStepSeconds: 0.1)
}Lifecycle — everything GL happens on the thread that owns the context. A new context (after the app was
backgrounded and the context lost) gets a fresh Renderer; the world and camera carry on.
renderer.unloadModel(path) frees one model's GPU buffers and any textures no other model uses;
loop.dispose() frees everything while the context is still alive.
Extending — Camera is an interface (view matrix, projection, near and far), so any camera works.
Systems are plain functions of the world and the frame time. Gl is the whole GPU surface the renderer uses, which
is also how the tests run it without one.
flowchart LR
subgraph engine[":engine · the library"]
ecs["ecs<br/>World · Entity · System"]
scene["scene<br/>Transform · Parent · Spin<br/>PointLight · Tint · Camera<br/>TransformSystem · OrbitCamera"]
render["render<br/>RenderLoop · Renderer · Shaders<br/>RenderTargets · LightCulling · ClusterGrid"]
assets["assets<br/>ObjParser · MtlParser"]
gl["gl<br/>Gl interface"]
math["math<br/>Vec3 · Mat4"]
android["androidMain<br/>AndroidGl · AndroidAssetSource<br/>EngineSurfaceView"]
ios["iosMain<br/>IosGl · BundleAssetSource"]
end
demo[":demo<br/>DemoApp · DemoScene · LidSystem"]
aapp[":androidApp<br/>activity + gestures"]
iapp["iosApp<br/>GLKView host (Swift)"]
render --> assets & gl & scene & ecs
scene --> math
android -. implements .-> gl
ios -. implements .-> gl
demo --> render
aapp --> demo & android
iapp --> demo & iosEach frame the platform host calls RenderLoop.drawFrame(time): the World runs its systems
(spin → lid animation → transform hierarchy), then Renderer draws every entity with a ModelRef,
lit by every entity with a PointLight. The demo is a separate module on top of the engine's public API,
the same API an app would use.
Android — JDK 17+ and the Android SDK:
./gradlew :androidApp:installDebugiOS — macOS with Xcode and XcodeGen:
cd iosApp && xcodegen generate && open GLRenderer.xcodeprojThe Xcode build runs Gradle to produce the Kotlin GLRendererDemo framework (the demo, exporting the engine).
Tests — the engine tests run on the JVM and on the iOS simulator:
./gradlew :engine:testDebugUnitTest :demo:testDebugUnitTest # any OS
./gradlew :engine:iosSimulatorArm64Test :demo:iosSimulatorArm64Test # macOSOn Windows and Linux the iOS sources are still type-checked (kotlin.native.enableKlibsCrossCompilation);
only linking the framework needs a Mac. CI builds both apps, runs the tests on both platforms and
captures a frame from the iOS simulator.
Releasing — bump VERSION_NAME in gradle.properties and push a matching tag (v0.2.0). The release workflow
tests on macOS and uploads a signed deployment to the Central Portal, where it waits for a manual Publish.
Point light shadows cost six extra passes per light, so they are opt-in per light and capped at eight visible at once. The renderer targets OpenGL ES 3.0, which Apple has deprecated in favour of Metal; it still ships and runs on devices and in the simulator.
assets/ is generated by python tools/generate_assets.py (standard library only):
the teapot and lid are tessellated from Martin Newell's 1975 Bézier patch data
(as distributed with three.js); the turntable, floor and light bulbs are procedural, and the turntable's
texture is drawn in code.
Started in 2020 as an experiment in sharing OpenGL code through Kotlin Multiplatform, and grew an ECS and a model viewer in 2021–22. Rebuilt in 2026 on current Kotlin, AGP and Gradle: GPU buffers uploaded once instead of every frame, ES 3 throughout, a pure-Kotlin matrix library, a real iOS backend, tests and CI; then the deferred and clustered forward+ pipelines, PBR, key and point light shadows, HDR post-processing and instancing.
MIT
An OpenGL ES 3 renderer and entity-component system written in Kotlin Multiplatform, running on Android and iOS from one codebase: deferred and clustered forward+ pipelines, metal/roughness PBR, shadow maps for the key light and for point lights, HDR with bloom and tonemapping, FXAA and instancing. The engine, scene, OBJ/MTL loaders, math and the whole renderer are common Kotlin; Android and iOS each contribute only a thin GL binding and an asset reader.
The demo is the Utah teapot on a spinning turntable, circled by three rings of coloured point lights (32 in all); the six above the teapot cast shadows. Drag to orbit, pinch to zoom, double-tap to open the lid, tap to switch between the deferred and forward+ pipelines, long-press to pause.
| Android · deferred | Android · forward+ | iOS simulator · deferred |
|---|---|---|
![]() |
![]() |
![]() |
The two pipelines shade with the same GLSL functions and produce the same image: on the paused frame above, the mean difference is 0.5/255 and no pixel differs by more than 16/255 (the residue is the 8-bit G-buffer). The iOS screenshot comes from CI, which builds the app, runs it in the simulator and captures a frame.
Point light shadows, on and off, same frame. The teapot throws a shadow from each of the six lights above it, and the turntable shadows the floor around its rim:
flowchart LR
pshadow["Point light shadows<br/>cube maps in one atlas"]
shadow["Key light shadow<br/>2048² orthographic"]
subgraph deferred["Deferred"]
gbuf["G-buffer<br/>albedo · normal · emission · depth"]
light["Lighting<br/>ambient + key light, full screen;<br/>one scissored pass per point light"]
gbuf --> light
end
subgraph forward["Forward+ (clustered)"]
clusters["Light clusters<br/>64 px tiles × 16 depth slices,<br/>built on the CPU"]
fwd["One forward pass<br/>loops over its cluster's lights"]
clusters --> fwd
end
trans["Transparent surfaces<br/>forward+, back to front"]
post["Bloom → ACES tonemap → FXAA"]
pshadow --> shadow --> deferred & forward
deferred & forward --> trans --> postPr, Pm, Ke), with a fallback from Blinn-Phong Ns.
Ambient is a sky/ground gradient with Karis' analytic split-sum approximation for its specular part.
Base-colour textures are SRGB8_ALPHA8, so filtering happens in linear space.gl_FragCoord and its view depth. The same pass shades transparent surfaces in the deferred path,
which a G-buffer cannot hold.sampler2DShadow
with hardware comparison and a 3×3 PCF kernel; slope-scaled polygon offset plus a normal offset against acne.castsShadows (up to 8 visible at once) render six cube faces into one
depth atlas, a row per light, because ES 3.0 cannot index an array of cube samplers dynamically. The shader picks
the face by the major axis of the light-to-surface direction and reproduces the face's projection. Faces are rendered
slightly wider than 90° so 3×3 PCF never samples a neighbouring tile, and each light only draws the instances whose
bounding sphere reaches into its own.RGBA16F target. Bloom is a five-level mip chain
(soft-threshold prefilter, 4-tap downsample, tent upsample), followed by exposure, the ACES filmic curve and FXAA.
If the GPU can't render to half-float (EXT_color_buffer_half_float), everything falls back to 8-bit targets
and the renderer reports hdr == false.glDrawArraysInstanced with per-instance model
matrix, normal matrix and tint in a dynamic vertex buffer. The 32 light bulbs are one draw call.Parent links,
with cycle detection. Lights are components (PointLight), as is per-instance colour (Tint): the lid is a child of
the teapot, which is a child of the turntable, and each light is a child of its ring.usemtl splits, generated face normals)
and MTL readers that work on plain text, so they are unit-tested without a device.
Each mesh is uploaded to the GPU once as an interleaved VBO in a VAO.Gl is a ~45-method interface implemented with GLES30 on Android
and Kotlin/Native's platform.gles3 bindings on iOS. The renderer's tests run against a recording fake of it,
checking pass order, instancing, shadow budgets and caster culling, clustering and the half-float fallback
without a GPU.The engine is on Maven Central. In a Kotlin Multiplatform module (Android and iOS targets):
commonMain.dependencies {
implementation("agency.encrypt:glrenderer:0.1.0")
}An Android-only app can use the same line in its dependencies block. A scene is a World of entities, and a RenderLoop turns the platform's GL surface callbacks into
"run the systems, then render". Models are OBJ files with their MTL materials and textures, read through an
AssetSource.
val world = World().apply {
createEntity().add(Transform()).add(ModelRef("models/chair.obj"))
createEntity()
.add(Transform(position = Vec3(0f, 2.5f, 1f)))
.add(PointLight(color = Vec3(6f, 5.4f, 4.5f), radius = 6f, castsShadows = true))
addSystem(TransformSystem()) // last: resolves the hierarchy into WorldTransform for the renderer
}
val camera = OrbitCamera(target = Vec3(0f, 0.5f, 0f), distance = 4f)Android — EngineSurfaceView sets up an OpenGL ES 3 context and drives the loop on its render thread:
class ViewerActivity : Activity() {
private lateinit var view: EngineSurfaceView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val loop = RenderLoop(AndroidGl(), AndroidAssetSource(assets), world, camera) { renderer ->
renderer.pipeline = Pipeline.FORWARD_PLUS // runs again for each new GL context
}
view = EngineSurfaceView(this, loop)
setContentView(view)
}
override fun onResume() { super.onResume(); view.onResume() }
override fun onPause() { view.onPause(); super.onPause() }
}Changes from the UI thread (input, settings) go through view.queueEvent { ... }, onto the render thread.
iOS — build the loop in Kotlin, where default arguments and lambdas are pleasant, and drive it from a
GLKView in Swift (iosApp/Sources/RendererViewController.swift is a complete example):
// iosMain, in your shared module: Viewer.kt
fun createViewer(): RenderLoop = RenderLoop(IosGl(), BundleAssetSource("assets"), world, camera)loop = ViewerKt.createViewer() // with an ES 3 EAGLContext current
loop.surfaceCreated()
override func glkView(_ view: GLKView, drawIn rect: CGRect) {
loop.surfaceChanged(width: Int32(view.drawableWidth), height: Int32(view.drawableHeight))
loop.drawFrame(timeSeconds: CACurrentMediaTime(), maxStepSeconds: 0.1)
}Lifecycle — everything GL happens on the thread that owns the context. A new context (after the app was
backgrounded and the context lost) gets a fresh Renderer; the world and camera carry on.
renderer.unloadModel(path) frees one model's GPU buffers and any textures no other model uses;
loop.dispose() frees everything while the context is still alive.
Extending — Camera is an interface (view matrix, projection, near and far), so any camera works.
Systems are plain functions of the world and the frame time. Gl is the whole GPU surface the renderer uses, which
is also how the tests run it without one.
flowchart LR
subgraph engine[":engine · the library"]
ecs["ecs<br/>World · Entity · System"]
scene["scene<br/>Transform · Parent · Spin<br/>PointLight · Tint · Camera<br/>TransformSystem · OrbitCamera"]
render["render<br/>RenderLoop · Renderer · Shaders<br/>RenderTargets · LightCulling · ClusterGrid"]
assets["assets<br/>ObjParser · MtlParser"]
gl["gl<br/>Gl interface"]
math["math<br/>Vec3 · Mat4"]
android["androidMain<br/>AndroidGl · AndroidAssetSource<br/>EngineSurfaceView"]
ios["iosMain<br/>IosGl · BundleAssetSource"]
end
demo[":demo<br/>DemoApp · DemoScene · LidSystem"]
aapp[":androidApp<br/>activity + gestures"]
iapp["iosApp<br/>GLKView host (Swift)"]
render --> assets & gl & scene & ecs
scene --> math
android -. implements .-> gl
ios -. implements .-> gl
demo --> render
aapp --> demo & android
iapp --> demo & iosEach frame the platform host calls RenderLoop.drawFrame(time): the World runs its systems
(spin → lid animation → transform hierarchy), then Renderer draws every entity with a ModelRef,
lit by every entity with a PointLight. The demo is a separate module on top of the engine's public API,
the same API an app would use.
Android — JDK 17+ and the Android SDK:
./gradlew :androidApp:installDebugiOS — macOS with Xcode and XcodeGen:
cd iosApp && xcodegen generate && open GLRenderer.xcodeprojThe Xcode build runs Gradle to produce the Kotlin GLRendererDemo framework (the demo, exporting the engine).
Tests — the engine tests run on the JVM and on the iOS simulator:
./gradlew :engine:testDebugUnitTest :demo:testDebugUnitTest # any OS
./gradlew :engine:iosSimulatorArm64Test :demo:iosSimulatorArm64Test # macOSOn Windows and Linux the iOS sources are still type-checked (kotlin.native.enableKlibsCrossCompilation);
only linking the framework needs a Mac. CI builds both apps, runs the tests on both platforms and
captures a frame from the iOS simulator.
Releasing — bump VERSION_NAME in gradle.properties and push a matching tag (v0.2.0). The release workflow
tests on macOS and uploads a signed deployment to the Central Portal, where it waits for a manual Publish.
Point light shadows cost six extra passes per light, so they are opt-in per light and capped at eight visible at once. The renderer targets OpenGL ES 3.0, which Apple has deprecated in favour of Metal; it still ships and runs on devices and in the simulator.
assets/ is generated by python tools/generate_assets.py (standard library only):
the teapot and lid are tessellated from Martin Newell's 1975 Bézier patch data
(as distributed with three.js); the turntable, floor and light bulbs are procedural, and the turntable's
texture is drawn in code.
Started in 2020 as an experiment in sharing OpenGL code through Kotlin Multiplatform, and grew an ECS and a model viewer in 2021–22. Rebuilt in 2026 on current Kotlin, AGP and Gradle: GPU buffers uploaded once instead of every frame, ES 3 throughout, a pure-Kotlin matrix library, a real iOS backend, tests and CI; then the deferred and clustered forward+ pipelines, PBR, key and point light shadows, HDR post-processing and instancing.
MIT