Graphics and the GPU
A Sloppy game is written once and draws through whichever of five renderers the machine has. This page explains which one runs where, how your shader code reaches each of them, what is the same and what differs between them, and the three ways of computing on the GPU.
Portable WebGL2 shader limits
WebGL2 guarantees 256 vertex and 224 fragment uniform vectors, 15 varying vectors, 16 vertex attributes, and 16 texture units per stage (32 combined). A desktop GPU may allow much more. Uniform packing follows GLSL ES Appendix A, not uniform-buffer std140 layout. python3 tools/webglbudget.py compiles library and example shaders for the web and checks a conservative bound: each scalar/vector takes a whole row, arrays include every element, and matrices take one row per column. The Linux CI test job runs this audit.
GLSL uniforms are independent fields, declared only in stages that read them. Read-only struct arguments to shader helpers are specialized to those fields; copying an entire struct still reads every field. The native byte layout and the 64-joint skin palette are unchanged. GL/WebGL creates skeletal programs when the first skinned mesh is loaded. Compile/link errors include both entry points and sources, stage and program logs, conservative resource counts, and GPU limits.
No sampler is ever inside a GLSL struct: some phone drivers (Adreno under Chrome's ANGLE) then fail to compile a shader or not depending on the names ANGLE gives its identifiers. A GpuBuffer is two uniforms (its texture and its length), and a struct holding a Texture or a GpuBuffer reaches a helper function as one parameter per field. In shader code such a struct can be passed, read, and named once (m = u.material), but not changed or copied into another (a compile error says so); webglbudget.py fails on any struct holding a sampler. On a page, errors are also sent as a sloppy:error event on window (its detail the text) for a page whose own overlay hides the #log element.
The five renderers
| renderer | where | used when |
|---|---|---|
| Metal 3 | macOS | opt-in while it is new: SLOPPY_METAL=1, on a machine with Metal 3 (else OpenGL) |
| Vulkan 1.3 | Linux, Windows | the driver has Vulkan 1.3 (current drivers for NVIDIA, AMD and Intel GPUs do) |
| OpenGL ES 3 (macOS: 4.1) | Linux, Windows, macOS | macOS: by default; Linux and Windows: there is no usable Vulkan driver, or SLOPPY_VULKAN=0 |
| WebGL 2 | the browser | a game built with --target wasm |
| software | everywhere | there is no GPU driver at all (a virtual machine, a server), or SLOPPY_SOFTWARE=1 |
You do not choose in your program: the library picks the best one when the window opens, and the same program runs on all five. The frame statistics overlay (show_stats(), or SLOPPY_STATS=1) shows which is in use, e.g. vulkan (NVIDIA GeForce GTX 1070), and soft_rendering() tells the program when it is the software renderer (to draw fewer particles, say).
Metal and macOS. CI's macOS runners are virtual machines without Metal 3 or a GPU: there the library falls back to Apple's software OpenGL, which is what CI's render tests check. Metal and Apple's hardware OpenGL are checked on a real Mac with tools/macrender.py (docs/COMPILER.md, Tests), which draws every game and render scene there with each of the three. Metal stays opt-in until it has been used on more Macs than one.
Why Vulkan first. Vulkan lets the library work the way current GPUs work best, after Mason Remaley's mr_gpu: every texture is in one bindless array, buffers are read by their address, shaders fetch their own vertices, frames are recorded without render-pass objects, and each frame's data goes into one block of upload memory. The CPU does less work per draw (Breakwater spends 2.0 ms of CPU time per frame instead of 2.8 with OpenGL), and the GPU can decide what to draw itself (draw_indirect, below).
Why OpenGL stays. Older drivers, some virtual machines and remote desktops have OpenGL but no Vulkan 1.3, and the web has WebGL, which is OpenGL ES. The library's OpenGL path and its Vulkan path draw the same frames: the render tests compare them pixel by pixel.
Why a software renderer. So a game always runs: on a server, in CI, in a VM without 3D acceleration. It draws at half resolution by default (SLOPPY_SOFT_SCALE=1 for full) and runs your shader functions natively on the CPU.
3D cameras
orbit_camera(target, distance) orbits a point with a mouse drag or the right stick; follow_camera(distance = 6, height = 1.5) follows a character with update(cam, player_pos, dt). Call camera3d(cam) before drawing the scene. Both cameras have invert_y and invert_x fields (false by default), which reverse vertical or horizontal mouse and right-stick look. Zoom keeps its usual direction.
While a menu is open, update(cam, player_pos, dt, input = false) continues target smoothing, any supplied chase heading, and recovery after pull_in, without reading mouse, sticks or wheel. For an orbit camera, update(cam, dt, input = false) continues smoothing toward its yaw, pitch and distance. These values can still be set by code. Skip updating to freeze everything.
Shaders are Sloppy functions
A shader is a pair of ordinary functions: a vertex function and a fragment function.
struct V: # what each vertex holds
pos: vec3
struct U: # the uniforms: one value for the whole draw
mvp: mat4
tint: vec4
struct O: # what the vertex function gives each fragment (pos first)
pos: vec4
shade: f32
vs = (v: V, u: U) -> O: O(u.mvp * vec4(v.pos, 1), v.pos.y)
fs = (i: O, u: U) -> vec4: vec4(u.tint.xyz * (0.6 + 0.4 * i.shade), 1)
sh = make_shader(shader(vs, fs))
m = mesh([V(vec3(-1, -1, 0)), V(vec3(1, -1, 0)), V(vec3(0, 1, 0))])
draw = ():
clear()
draw(sh, m, U(mat4(), vec4(1, 0.5, 0.2, 1)))
The compiler translates shader(vs, fs) at compile time: to SPIR-V for Vulkan (the compiler writes it itself, so no shader compiler or SDK is needed), to GLSL ES 3.00 for OpenGL and WebGL, to Metal Shading Language for Metal, and to native code, which the software renderer calls for each vertex and pixel. Helper functions the shader calls are translated with it. A shader cannot allocate: strings, growable arrays, maps and closures are compile errors in shader code; numbers, bools, vectors, mat4, structs, fixed-size arrays (f32[4], also f32[4][4]) and Texture are fine.
The same results everywhere. Shader code follows the CPU's rules for numbers: integer types wrap at their size, unsigned division, remainders, shifts, comparisons and min/max are unsigned, % keeps the dividend's sign, float to integer conversions saturate, a compound assignment computes its target once. The backends are checked against each other by tools/gpufuzz.py, which draws random shader code with all three and requires identical pixels.
What differs. GPU arithmetic is 32-bit: in shader code an int (and i64, u64) wraps at 32 bits and an f64 is an f32. Use i32, u32 and f32 in shaders and the CPU (the software renderer) gives the same answers. Functions such as sin, exp and pow may differ in the last bits between GPUs, as they do in every graphics API.
Effects on 2D drawing. A fragment function of your own can run for everything 2D drawing draws (sprites, shapes, text), as LÖVE's setShader: make it with the library's vertex function, fx = make_shader(shader(effect_vs, my_fs)), then use_effect(fx, params) before the drawing and no_effect() after (effects end with the frame). The fragment function takes a Pixel2D (pos, uv, color) and an Effect2D[P] whose params are yours; base_color(p, u) is the color the pixel would have had:
gray_fs = (p: Pixel2D, u: Effect2D[f32]) -> vec4:
c = base_color(p, u)
g = dot(c.xyz, vec3(0.3, 0.59, 0.11))
vec4(mix(c.xyz, vec3(g, g, g), u.params), c.w)
gray = make_shader(shader(effect_vs, gray_fs))
...
use_effect(gray, f32(1.0))
sprite(enemy, pos)
no_effect()
Draw state
How a draw or draw_instanced goes into the picture is chosen by five setters, in the style of blend(). Each holds until it is changed; each frame starts from the defaults. A setter draws the 2D shapes queued before it first, so they keep the state they were drawn under.
| setter | values | default |
|---|---|---|
blend(b) | .alpha, .add, .multiply, .premultiplied, .screen (1, 1 − source color: lightens, never past white), .none (no blending: color and alpha replace what is there) | .alpha |
depth_test(t) | .off, .nearer, .nearer_or_equal, .farther, .farther_or_equal, .equal, .always | .off |
depth_write(on) | whether a draw leaves its depth (only where depth_test is not .off) | true |
cull(c) | .none, .back (triangles whose corners go clockwise on the screen), .front | .none |
color_write(on) | whether colors are written (false: a depth-only pass) | true |
depth_test(.nearer_or_equal)
depth_write(false)
draw(water, sea, params) # tested against the depth there, leaving none
color_write(false)
depth_write(true)
draw(occluder, walls, params) # depth only
color_write(true)
DepthTest names the meaning, not a GL function: .nearer stays right whatever the depth range. blend applies to 2D shapes too; 2D shapes are always drawn with no depth test and no culling. clear() clears all of the picture whatever color_write and depth_write say; clear_depth() clears only its depth. On Vulkan, warm_up(sh) prepares the pipeline for the state selected when it is called.
What a draw sees. In draw (2D, and a custom draw after camera3d, which is drawn at once, not in the 3D pass): the defaults above. Inside draw_custom's render, the 3D pass's state: blend(.none), depth_test(.nearer_or_equal), depth_write(true), cull(.back), color_write(true); with transparent = true, blend(.alpha), depth_write(false) and cull(.none); with additive = true, the same with blend(.add). Setters called in render change it until render returns; the pass then sets its own again, and the game's selection from before the 3D is back after the pass. render_image draws from the defaults and gives the selection back. The library's own passes (meshes, shadows, the sky, post effects, 2D batches) set what they need. The setters do not see raw glEnable/glDepthFunc/... calls: mixing the two leaves either unsure of the other.
Depth targets that can be sampled
render_target(w, h, depth_texture = true) makes a target whose depth is a texture, rt.depth_texture, sampled like any other: sample(rt.depth_texture, uv).x is the depth, 0 near to 1 far (1 near to 0 far under reversed depth: see Depth, below). Its depth is 32-bit float everywhere (sampled nearest: WebGL does not filter float depth). A target made without it keeps its depth in a renderbuffer, and rt.depth_texture is an empty Texture.
No feedback. A draw may not sample the color or the depth of the target it is drawing into: WebGL refuses it, and elsewhere what it shows is undefined. Such a draw (a draw, a draw_instanced, or a 2D sprite of the target's own texture) panics, on every renderer, saying which. To test against a scene's depth while sampling it, copy it: copy_depth(from, to) copies one target's depth into another of the same size (both made with depth_texture = true): a blit on OpenGL and WebGL, an image copy on Vulkan and Metal, a copy in the software renderer.
scene = render_target(w, h, depth_texture = true)
fog = render_target(w, h, depth_texture = true)
...
draw_to(scene)
... # the scene, depth tested
draw_to(fog)
clear()
copy_depth(scene, fog) # tested against the scene's depth ...
depth_test(.nearer)
draw(fog_sh, quad, FogParams(scene.depth_texture)) # ... while sampling it
The 3D scene's depth. With post effects on, the library draws the 3D into a picture of its own. post_effects(..., scene_depth = true) keeps that picture's depth in a texture, and scene_depth() returns it (an empty Texture with post effects off). A pass of the game's own reads it while drawing into another target (draw_to(rt) first: that also draws the 3D queued so far), not while drawing on the screen, which under post effects is that picture; copy_depth(scene_depth(), rt) gives such a pass a copy to test against.
Several colors from one draw
A fragment function may return a struct of 1 to 4 vec4 fields instead of one vec4: field i is the color written to color i of the render target drawn into. Such a target is made with render_target(w, h, colors = n) (1 to 4); its textures are rt.colors[0] to rt.colors[n - 1] (the others are empty), and rt.texture is rt.colors[0]. draw_target(rt, pos, size, color = i) shows color i (0 by default). A deferred renderer's G-buffer, or a picture and its glow, in one pass:
struct V:
pos: vec2
color: vec4
struct U:
glow: f32
struct O:
pos: vec4
color: vec4
struct Out: # color 0 and color 1
picture: vec4
bright: vec4
vs = (v: V, u: U) -> O: O(vec4(v.pos, 0, 1), v.color)
fs = (i: O, u: U) -> Out: Out(i.color, vec4(i.color.xyz * u.glow, 1))
sh = make_shader(shader(vs, fs))
tri = mesh([V(vec2(-0.8, -0.8), vec4(1, 0.3, 0.2, 1)), V(vec2(0.8, -0.8), vec4(0.2, 1, 0.3, 1)), V(vec2(0, 0.8), vec4(0.3, 0.2, 1, 1))])
rt = render_target(256, 256, colors = 2)
draw = ():
draw_to(rt)
clear()
draw(sh, tri, U(0.5))
draw_to_screen()
clear()
draw_target(rt, vec2(20, 20)) # the picture
draw_target(rt, vec2(300, 20), color = 1) # its bright part
- The struct's fields are all
vec4and there are at most 4 of them (WebGL2 guarantees 4); the same struct cannot also be the vertex function's output. Both are compile errors. - A shader of fewer colors than the target writes its colors and leaves the others as they are: a one-color shader, and all 2D drawing and the library's 3D, write
rt.colors[0]only. A shader of more colors than the target (or the screen, which has one) panics at its draw. blend,color_writeand the rest of the draw state apply to every color alike.clear()clears all of a target's colors.- A draw may not sample any of the colors of the target it draws into (it panics, as for one color);
screenshot()andrender_imageread color 0. - Underneath: GLSL
layout(location = i) out vec4withglDrawBuffers(WebGL:drawBuffers), SPIR-V outputs at locations 0 to 3 with as many color attachments in the Vulkan pipeline (pipelines are kept by the number of colors; a color the shader does not write has a write mask of 0, which needs the device'sindependentBlend, as every desktop GPU and most phones have), Metal[[color(i)]]fields and as many color attachments, and in the software renderer one image per color. - A shader whose fragment function returns a
vec4is translated exactly as before.
Asset loading and failure
load_image, load_png, load_jpeg and load_texture take bytes and return an asset or ImageError. load_font returns Font | FontError, audio load_wav/load_ogg/load_music return the sound/music or AudioError, and load_model returns Model | ModelError. Use read_gltf for CPU-only model data. Path access is a separate checked read_bytes:
read_picture = (path: str) -> Image | FileError | ImageError:
file = read_bytes(path)?
load_image(file)?
result = read_picture("portrait.png")
if result is Image: print(result.width, result.height)
else: eprint(result.message)
embed checks that the named file exists at compile time; decoding still happens at runtime, so an invalid embedded image/font/sound/model returns the same error as other bytes. Use .unwrap() to assert a trusted asset, as the examples below do. Error messages travel with each result; a later load cannot overwrite a previous error.
Music validates its container and headers when opened and decodes audio packets during playback. A detected corrupt packet stops the voice after already accepted samples; once is_playing(voice) is false, music_error(voice) takes its recorded AudioError, once. None means no decode failure was recorded; manually stopping a voice is not a decode error.
An animated glTF scene
sloppy new mygame character creates a complete starter with an embedded CC0 skinned character (24 KB), Idle/Walk/Run crossfades, a follow camera, a small valley built with terrain_mesh, add_box, add_cylinder and custom_mesh (two static meshes, one draw each), sun, fog and shadows, keyboard/gamepad/touch movement and a responsive layout pause menu. It needs no downloads and builds with sloppy build --target wasm mygame/mygame.jo. The generated character-LICENSE.txt records the asset license; tools/makecharacter.py rebuilds the model, rig and animations. Replace character.glb and the clip names to use your own character.
Use an uncompressed glTF 2.0 export (.glb is simplest), with PNG/JPEG textures. For this example, put the Khronos sample Fox.glb at assets/Fox.glb, and a small tone-mapped, equirectangular JPEG or PNG panorama at assets/sky.jpg. Poly Haven offers CC0 panoramas; choose its tone-mapped JPG and reduce it to 1024×512 for a small game. HDR/EXR files are not read. Check each model's license: Fox's model is CC0, but its animation and glTF conversion require CC-BY 4.0 attribution, as its README says.
window("Fox walk", 960, 600)
hero = load_model(embed("assets/Fox.glb")).unwrap()
panorama = load_texture(embed("assets/sky.jpg")).unwrap()
ground = plane_mesh(40)
hero_scale = 1.4 / max(f64(model_size(hero).y), 0.001)
pos = vec3(0, 0, 0)
facing = PI
cam = follow_camera(distance = 7, height = 0.9)
anim: Animator
# Animation names belong to the asset: inspect them before choosing one.
loop clip in hero.animations: print("{clip.name}: {clip.length} seconds")
update = (dt: f64):
global facing
a = input_axis() # WASD/arrows, left stick and d-pad
move = flat_forward(cam) * -a.y + flat_right(cam) * a.x
if length(move) > 0.1:
pos += move * 3.2 * dt
facing = atan2(move.x, move.z) # Fox faces +Z in its own space
anim.play(hero, "Walk", fade = 0.25)
else: anim.play(hero, "Survey", fade = 0.25)
anim.update(hero, dt) # advance once per update
cam.update(pos, dt) # RMB/mouse or right stick looks around
draw = ():
clear()
sky_image(panorama, intensity = 0.7)
sun(vec3(-0.5, 1, -0.3), disc = 0) # panorama supplies the visible sky
shadows(true)
camera3d(cam)
draw_mesh(ground, material = Material(base_color = rgb(0.2, 0.3, 0.18), roughness = 0.9))
draw_model(hero, transform(pos, facing, hero_scale), pose = anim.pose(hero))
text("WASD / left stick: walk; right mouse / right stick: look", vec2(20, 20), 20)
draw_model uses the glTF materials automatically. Assets can arrive at very different scales: inspect model_size(hero), hero.min and hero.max; the example makes Fox 1.4 units tall. Animator.play keeps the current clip running when called again with its name, and crossfades when that name changes. An asset with animated morph weights uses the same Animator/pose_at path; manual weights can also be set per draw.
For a split export use load_model(embed("assets/hero.gltf"), embed_dir("assets")).unwrap(): map keys are relative to the .gltf directory, including subdirectories. The loader does not read files beside the .gltf automatically. embed and embed_dir put those bytes in native and web builds alike. Check texture sizes before sharing: even a tiny model can contain several 2048×2048 images. Build with sloppy build game.jo --target wasm; the result is one HTML file (with --wasm-file, an HTML page and the program's .wasm beside it, which a web server gives faster: see Sharing it). See phones for touch movement and camera controls, and responsive layout for menus and settings.
3D materials
draw_mesh keeps its sun/sky lighting and specular highlight unless given a Material. Imported glTF models use metallic-roughness PBR, including the glTF default (metallic 1, roughness 1). Games can use the same path:
copper = Material(base_color = vec4(0.95, 0.64, 0.54, 1), metallic = 1, roughness = 0.25)
draw_mesh(ball, transform(pos), material = copper)
Material holds base_color, base_texture, metallic, roughness, metallic_roughness, normal_map, normal_scale, occlusion_map, occlusion_strength, emissive_color, emissive_map, alpha_mode, alpha_cutoff, double_sided and unlit. The glTF KHR_materials_unlit extension selects unlit. Its maps use UV set 0 by default; base_uv, metallic_roughness_uv, normal_uv, occlusion_uv and emissive_uv can select set 1. glTF's corresponding fields are loaded automatically. Metallic-roughness textures use G for roughness, B for metal; occlusion uses R. Normal maps use tangent space, with +Y green. normal_scale scales their X/Y components. Occlusion affects ambient light, leaving direct light and emission intact.
Color factors and vertex colors are linear; base-color and emissive texture RGB are decoded from sRGB. Other maps contain linear data. PBR shading is in linear light, followed by the existing ACES tone map and sRGB encoding. The simple path retains its previous color handling. draw_mesh's color multiplies the material factor; its texture is used if the material has no base texture. Its scalar emissive still adds base-colored light; specular belongs to the simple path. Imported parts retain color/texture for inspection and use material for PBR settings and their colored emission.
The BRDF is Cook-Torrance with GGX, Schlick Fresnel (dielectric F0 0.04), separable Smith masking and Lambert diffuse reduced by Fresnel and metalness. Perceptual roughness is squared for GGX and floored at 0.045 to keep highlights finite. The sun and up to eight point lights use this same BRDF, with the existing point-light range fade and sun shadow map. Ambient light uses the sky/ground colors: hemisphere diffuse, a reflected sky gradient blurred toward its average as roughness grows, and an analytic split-sum BRDF fit. This is an inexpensive environment approximation; it has no scene reflections or baked irradiance probes. Post effects work as before. Fog is applied as the simple path applies it, toward fog()'s color before ACES, in the simple path's (display-referred) space: the PBR result, tone-mapped and sRGB-encoded, is taken back through the inverse of ACES, fogged and tone-mapped again. So a PBR and a simple-lit surface that look alike fog alike at the same depth, and in thick fog both become the color the gradient sky shows for that horizon color. Without fog (density 0) the PBR result is unchanged. Sky and ground colors still light PBR surfaces as linear values.
AlphaMode.opaque ignores alpha, .mask discards alpha below alpha_cutoff in both the color and shadow passes, and .blend uses alpha blending without depth writes or shadows. PBR blends sort by their bounds' distance from the camera; intersecting transparent surfaces still need to be split by the asset author. double_sided renders both faces and reverses the back face's lighting normal. Reflected transforms reverse culling; nonuniform scale uses inverse-transpose normals.
Vertex3D and SkinVertex3D have optional tangent (vec4, XYZ along +U, W handedness) and uv1 fields. glTF tangents are retained and skinned with the mesh. Missing tangents are generated using angle-weighted triangle UV derivatives, orthogonalized against the normal, with glTF/MikkTSpace handedness; degenerate UVs get a stable perpendicular. UV/normal seams must use distinct vertices, as exporters normally produce. This is an approximation to MikkTSpace, not a replacement for an exporter's exact bake basis. Mesh generators and custom_mesh generate frames automatically; raw mesh(vertices, indices) callers can use tangents3d(vertices, indices, uv_set = 0) first. No shader compiler extensions are needed: the same shader functions run through Vulkan, OpenGL, WebGL, Metal and the software renderer.
Sky images
sky_image(texture, intensity = 1.0, rotation = 0.0) selects an equirectangular panorama for the background of a 3D scene and for PBR ambient light. A 2:1 PNG or JPEG is usual; its RGB is sRGB. +Y is at the top, -Y at the bottom, +X at the horizontal center and +Z three quarters across. rotation turns the environment about +Y in radians; intensity scales its linear light before tone mapping. The image stays at infinity as the camera moves. Keep its texture alive while selected. sky(...) selects the original gradient again; hide_sky() hides the background while retaining the selected environment's light.
Two 128×64 linear maps are cached on the first 3D pass after selecting an image: GGX importance-sampled convolutions at roughness 0.5 and 1, with 64 directions per texel. Reflections interpolate these and the sharp original by squared roughness. The broad map also approximates diffuse irradiance. This gives smooth rough-metal reflections at modest cost, without a full cubemap mip chain, BRDF lookup texture or HDR image loader. The original sun/sky gradient remains the ambient source when no image is selected. Updating a selected texture's pixels requires sky_image(texture, refresh = true) to rebuild its cached maps; changes to rotation or intensity reuse the maps. The same render-target passes run on the CPU renderer, Vulkan, GLES/WebGL and Metal.
Morph targets
Imported glTF meshes support weighted POSITION, NORMAL and TANGENT deltas, including sparse float deltas. Weights default to the node's weights, then the mesh's, then zeros. They are neither clamped nor normalized. The deltas are blended before skinning and node transforms, following the glTF specification. Tangent W (handedness) stays fixed. Missing base normals are rebuilt as flat normals after blending; missing tangents are regenerated from the deformed geometry and its normal-map UV set. Authored normal/tangent directions are normalized, with a base-frame fallback if a blend cancels them to zero. UV/color morph deltas and sparse base/animation accessors are not read.
Pose.weights[node][target] controls a mesh node's morphs. For a node named Face with a morph target:
p = rest_pose(hero)
p.weights[find_node(hero, "Face")][0] = 0.7
draw_model(hero, pose = p)
pose_at, blend_poses and Animator also blend the weights. Morph-weight animations support STEP, LINEAR and CUBICSPLINE, including Hermite slopes scaled by the key interval. Existing TRS cubic channels retain the loader's linear-key approximation. read_gltf exposes each MeshData.targets; morph_vertices(mesh_data, weights) returns blended CPU vertices without changing the source, for collision or other tools.
Blending is on the CPU, with source data retained only for parts that have targets (ModelPart.morph). Its cost scales with mesh size and active targets. Each queued draw keeps its own vertices and bounds, including the current skin. Vertex data is streamed just before each shadow or color draw, so several instances of the same model can have different weights in one frame. The GPU backends retain each streamed address until its frame finishes; the software renderer consumes each draw immediately. This uses the same shaders and buffer API on all five renderers.
Mipmaps
A texture drawn on a 3D mesh (draw_mesh's texture, a material's maps, a model's) gets mipmaps the first time it is drawn: smaller copies, each half the size of the one before, made by averaging 2×2 texels, and trilinear filtering between them. A floor or a wall running into the distance turns to its average color instead of shimmering and showing moiré. They take a third more memory, for those textures only. A ground that shows it, its texture repeating every 4 meters out to the horizon:
ground = plane_mesh(400, tile = 4)
stones = texture(load_image(embed("stones.png")).unwrap())
set_repeat(stones, true)
draw = ():
camera3d(vec3(0, 3, 8), vec3(0, 0, 0))
draw_mesh(ground, texture = stones)
What stays as it was:
- textures made with
smooth = false, whichpixel_art()makes the default: sharp texels, no mipmaps, near or far; - 2D sprites, text and anything else never drawn on a 3D mesh;
- render targets (
render_target), whose picture changes as they are drawn into; - a
sky_imagepanorama (sampled across its seam, where mipmaps would draw a line).
set_mipmaps(t, true) makes them now: for a texture a custom shader samples (sample then chooses the level; sample_lod picks one), or to pay their cost while loading instead of at the first 3D draw. set_mipmaps(t, false) keeps a texture without them, also on 3D meshes. auto_mipmaps = false turns the automatic ones off. After update_texture the next 3D draw makes them again. A render target's texture has none: set_mipmaps leaves it alone.
How each renderer makes them: OpenGL and WebGL call glGenerateMipmap; Vulkan makes the texture's image again with its levels and blits each level from the one before, filtered; Metal does the same with a blit encoder's generateMipmapsForTexture. The software renderer averages the levels itself and chooses a level for each pixel as a GPU does, from how fast the texture coordinates change from one pixel to the next and to the next row (the coordinates must be one of the shader's inputs as it receives them, such as i.uv; coordinates computed in the shader sample the full-size image). Making them takes 0.9 ms for a 256×256 texture, 5.6 ms for 1024×1024 and 24 ms for 2048×2048 in the software renderer (one core); on a GPU it is a few commands. tests/render/mipmaps.jo and tests/t/mipmaps.jo check them.
Computing on the GPU
There are three levels, from the simplest to the most control. All three also run without a GPU (on the CPU's cores, or in the browser), so a program never needs a fallback of its own.
GPU arrays are for numeric work written as array expressions. gpu(xs) uploads, a dotted expression becomes one GPU program, and cpu(g) downloads:
g = gpu(rand(4_000_000))
h = sin.(g) .* 0.5 .+ g # one GPU program, made at compile time
print(sum(h), max(h)) # reductions run on the GPU too
GPU buffers and compute functions keep your own structs on the GPU and change them there. A compute function is written like a shader and runs once per element:
struct Bug:
pos: vec2
vel: vec2
struct Step:
bugs: GpuBuffer[Bug]
dt: f32
step = (id: int, u: Step): u.bugs[id].pos += u.bugs[id].vel * u.dt
bugs = gpu_buffer(start_bugs) # upload (start_bugs: a Bug[] made on the CPU)
stepper = compute(step)
update = (dt: f64): dispatch(stepper, len(bugs), Step(bugs, f32(dt)))
Shaders read buffers among their uniforms (u.bugs[instance_id()]), so thousands of objects can be moved and drawn without coming back to the CPU. A compute function over a grid takes id: ivec2 or id: ivec3 (dispatch(k, ivec2(w, h), params)). Atomics (atomic_add, atomic_min...) let many invocations change one element. draw_indirect draws as many instances as a compute function decided, and draw_indirect_count takes the number of draws from a buffer too: culling and spawning can happen entirely on the GPU. Barriers between dispatches and draws are automatic.
Subgroup operations combine values across the invocations a GPU runs together (subgroup_add, subgroup_exclusive_add, subgroup_min, subgroup_elect, subgroup_broadcast_first...). A subgroup is 32 invocations on NVIDIA, 64 on some AMD GPUs and 1 on the CPU, so code written for any size (the usual case: one atomic per subgroup instead of one per element) gives the same results everywhere.
Where these run: through Vulkan, buffers are GPU memory and compute functions are compute programs (SPIR-V, made by the compiler). With OpenGL, WebGL or the software renderer, buffers are CPU memory and compute functions run on all CPU cores; shaders still read the buffers. gpu_compute() tells which.
Depth
The depth buffer holds, for each pixel, how far away what was drawn there is, from 0 to 1, so a nearer object hides a farther one whatever order they are drawn in. With the usual depth (what perspective and camera3d give), 0 is the near plane and 1 the far plane, and almost all of the precision is close to the camera: past a few kilometres everything is one depth and surfaces flicker through each other (z-fighting). Two ways out, for a view of hundreds of kilometres:
**Writing the depth yourself: set_depth(d).** In a fragment function, set_depth(d) writes the fragment's depth instead of the interpolated one, on every renderer (GLSL gl_FragDepth, SPIR-V FragDepth, Metal [[depth(any)]], and the software renderer tests and stores what you wrote). The position field of the fragment's input is the window position: i.pos.z is the depth the GPU interpolated and i.pos.w is 1/w, one over the distance along the view, the same on all five renderers. So logarithmic depth is one line, with k = 1 / log2(1 + the farthest distance):
struct V:
pos: vec3
struct U:
mvp: mat4
color: vec4
struct O:
pos: vec4
vs = (v: V, u: U) -> O: O(u.mvp * vec4(v.pos, 1))
fs = (i: O, u: U) -> vec4:
set_depth(log2(1.0 + 1.0 / i.pos.w) * 0.05) # 0.05: about 1 at 1,000 km
u.color
sh = make_shader(shader(vs, fs))
far_away = mesh([V(vec3(-9e5, -9e5, -6e5)), V(vec3(9e5, -9e5, -6e5)), V(vec3(0, 9e5, -6e5))])
draw = ():
clear()
depth_test(.nearer)
p = perspective(1.0, f64(screen_width()) / f64(screen_height()), 0.1, 2000000.0)
draw(sh, far_away, U(p, vec4(0.4, 0.6, 1, 1)))
A path through the function that does not call set_depth keeps the interpolated depth. The cost: a shader that writes its depth turns off the GPU's early depth test, which rejects hidden fragments before their fragment function runs; every fragment of every draw with it is shaded, then tested. Shaders that never call it keep early depth tests (the compiler emits the depth output only for them). Use it for the far scenery, not for everything.
**Reversed depth: reversed_depth().** Depth 1 at the near plane, going to 0 infinitely far away, in float: a float has as much relative precision near 0 as anywhere, so a kilometre is told apart from the next at a million metres, and a millimetre at one metre. Call it once at the start; it returns whether this renderer has it, and when it says false nothing changed:
| renderer | reversed depth |
|---|---|
| Vulkan, Metal, software | always (their depth is already 32-bit float) |
| OpenGL | with glClipControl (GL 4.5, ARB_clip_control, OpenGL ES EXT_clip_control); render targets' depth (and the window's, on Wayland) becomes 32-bit float; on X11 and Windows the window's own depth buffer stays what the system gives (usually 24-bit). Never on macOS (its OpenGL 4.1 has no clip control) |
| WebGL | where the browser has EXT_clip_control; render targets' depth becomes float, the canvas's stays 24-bit |
With it on: clear() and clear_depth() clear the depth to 0, and depth_test(.nearer) and .nearer_or_equal (and .farther, .farther_or_equal) keep their meaning, so drawing code does not change. The flip is in one place, the lowest one: the renderers' glDepthFunc turns LESS into GREATER and LEQUAL into GEQUAL (and back) while reversed depth is on, so a raw glDepthFunc(GL_LESS) means nearer too, and DepthTest maps to GL's functions as usual. A depth texture (depth_texture = true, scene_depth()) holds the reversed values: 1 near, 0 far. camera3d becomes an infinite reversed perspective (perspective_reversed(fov, aspect, near): clip z is near and w the distance, nothing is cut off far away), so draw_mesh, models, particles, the sky and scene_view_proj() follow. The library's shadow maps keep the usual depth. For your own shaders the clip-space convention changes: the vertex function's clip z goes to the depth unit as it is, z / w from 0 (far) to 1 (near), instead of -1 to 1. A projection of your own uses perspective_reversed; a sky or backdrop at the far plane writes far_depth() (0.9999 with the usual depth, 0 with reversed depth) as its clip z with w = 1, passed in its uniforms. Where reversed_depth() says false, use set_depth with logarithmic depth (above) for the same picture: tests/render/reversed_depth.jo does exactly that.
Shader functions and call sites
Sloppy's shader backends never inline or copy a function: a helper called from three places is one function in the GLSL, SPIR-V and Metal. GPU drivers do the opposite: they inline every call, so each call site is another copy of the helper in the final program. On desktops that is free, but on phones the driver's link time grows with the number of copies (a big material function called from four light loops is four materials to optimize). There is no noinline, deliberately: GLSL has no way to ask for it and drivers ignore SPIR-V's DontInline. What works is fewer call sites: put the inputs in a small fixed-size array and call the helper once, in a loop over it, rather than once per input.
Linking shaders on OpenGL and WebGL
On OpenGL and WebGL a shader is compiled and linked at its first draw, not when it is made: make_shader and the library's own shaders (lit, shadow, sky, PBR, post effects, particles) return at once. Linking costs tens of milliseconds a program on a phone (about 60 ms each on an Adreno 650 under Chrome), and a 3D game makes dozens before its first frame, most of them not needed for its title screen. Vulkan, Metal and the software renderer make their programs at once, as before; there these calls do nothing.
shaders_pending() -> int: how many shaders are queued for warm-up and not linked yet.warm_up_shaders(max_count = -1, max_ms = -1.0) -> int: link queued shaders, oldest first: at mostmax_count, starting no new one aftermax_msmilliseconds (at least one is linked). With neither limit it links them all. Returns how many still wait.warm_up()links them all too (and prepares Vulkan's pipelines);warm_up(sh)links one, queued or not.make_shader(src, warm = false): a shader the warm-up leaves alone. It is linked at its first draw or bywarm_up(sh);warm_up_later(sh)queues it (and, with parallel compiling, starts its link).
Only what is queued is linked by a warm-up, so a game that makes all its shaders at start but draws some of them only in one mode, one level or one kind of weather makes those with warm = false and links them when that part comes near: a shader linked and never drawn costs as much as one drawn (seconds, on a phone with a cold shader cache), and a browser keeps only so many programs in its cache, so unused ones can push out the ones a later visit needs.
storm_sh = make_shader(shader(storm_vs, storm_fs), warm = false) # most games see no storm
...
if storm_coming: warm_up_later(storm_sh) # the next warm_up_shaders links it
The library queues its own 3D shaders only while their feature is on, at each warm-up: the lit shader once 3D is drawn; the shadow ones while shadows(true); the gradient sky's while the sky shows and is not sky_image; the instanced ones when draw_mesh_instanced is used; the skinned and PBR ones once a skinned mesh or a material is loaded. Post effects, particles and the image sky make theirs at their first use. A warm-up first makes the library's 3D shaders if the game draws 3D, so warm_up() on a loading screen covers its first 3D frame too.
Making a shader again from the same source (the same stages and layout: a view rebuilt for a new game, a helper that makes its shader each call) gives the program made before, linked once; the two Shader values share it. The program does not depend on the meshes or instance buffers it is drawn with: a mesh's vertex array is set up for each shader it is drawn with (at most four kept per mesh), which links nothing, so there is no per-layout variant to warm up.
The pattern: let the title screen's own shaders link at their first draw; while the screen is dark or a fade hides the frame, feed the rest a few at a time; link whatever is left before gameplay starts, so no gameplay frame waits for a link:
draw = ():
if fading_in: warm_up_shaders(max_ms = 8.0) # a frame nobody watches closely
...
start_game = ():
warm_up_shaders() # all of them, during the loading screen
Where the browser or driver has KHR_parallel_shader_compile (newer desktop Chrome and many Android phones; GL_KHR_parallel_shader_compile in native drivers such as Mesa's), each program starts compiling and linking when it is made, on the driver's own threads, and nothing waits for it. warm_up_shaders with a limit then only finishes the programs the driver says are done (asking costs nothing); a first draw or warm_up_shaders() waits for the rest. Errors are reported as before (the logs, sources and GPU limits, then the panic "shader compilation or linking failed"), but at the first draw or warm-up instead of at make_shader: call warm_up_shaders() after making a new shader to see its errors at once.
Preparing Vulkan pipelines during loading
Vulkan prepares builtin pipelines as the game loads its graphics features and assets. Each feature registers its own shaders at the declaration that already creates them. Graphics helpers use block bodies so the compiler can also defer parsing unused bodies. A 2D game does not compile the 3D renderer, PBR or sky filters; 2D postprocessing loads only its post passes. Classic 3D, PBR materials, skinning, particles and image skies opt in separately. There is no global list of shader functions that every game compiles.
Load meshes, instance buffers, models and shaders before gameplay. Repeated loads of a layout reuse its preparation. Skinned and shadow-skinned pipelines are prepared only once a skinned mesh loads. PBR material draws declare the PBR feature; glTF model uploads prepare it when their materials load. read_gltf remains CPU-only. sky_image prepares its filter pipeline and light maps when a panorama is selected; repeating the same texture reuses them, while refresh = true bakes them again. Sky preparation preserves the selected target, viewport, clipping, buffer bindings and draw state.
Call warm_up() during a loading screen after declaring shaders and loading assets. It revisits only declared programs and loaded layouts. warm_up(mat) prepares shared PBR programs from a custom material-loading path. No list of pipelines is needed. These hooks do no pipeline work on OpenGL, Metal, software or WebGL; on GL/WebGL warm_up() links the shaders still waiting (see the previous section). Assets or shaders created inside draw() still pay their loading cost there. Games that load assets in frame zero may spend more time in that initial loading frame, rather than in a later gameplay frame.
make_shader(shader(vs, fs)) prepares a custom shader's usual triangle states: opaque, alpha, additive, multiply and premultiplied blending, with screen MSAA and ordinary single-sample targets. For an unusual primitive class, attachment format, color mask or depth state, warm_up(sh, mode) prepares the state selected now. For example:
line_shader = make_shader(shader(line_vs, line_fs))
draw_to(target)
blend(.add)
warm_up(line_shader, GL_LINES)
draw_to_screen()
blend(.alpha)
Preparation is synchronous on the render thread. Private 1×1 attachments and a vertex trigger drivers that defer shader JIT until a draw. Builtins retain their original binaries and read zeroed scratch inputs; one vertex cannot form a triangle. Custom shaders get a wrapper that clips this vertex before invoking user code. No game draw callback or custom vertex/fragment function runs during preparation. A driver failure is reported and falls back to normal creation at first use; failed handles are not cached as usable pipelines. Actual draw errors retain normal renderer error handling.
The existing device/driver-validated VkPipelineCache is still saved between runs in ~/.cache/sloppy (%LOCALAPPDATA%\sloppy on Windows). It reduces later loading work, but live pipeline objects must still be created for each process. The screen is RGBA8 and copied to the swapchain, so resizing does not add another drawing-pipeline format. Compute dispatch caching is unchanged.
tests/profile_pipelines.py measures cold startup and the initial frames using isolated caches and a scratch library, without editing game sources. Keep size, MSAA, input and overlay identical between runs. --counter hardware uses inherited CPU instruction counters for a faster run, including live driver threads; the default Callgrind mode also retains an attribution dump. Compile-cost checks are also required when changing these hooks: python3 tools/speedcheck.py --base <revision> (library rows within 1%) and python3 tests/check_graphics_reachability.py check that unused features stay unused.
Switches and troubleshooting
| setting | effect |
|---|---|
SLOPPY_VULKAN=0 | use OpenGL even where Vulkan works (=1: Vulkan, also for tests without a window) |
SLOPPY_SOFTWARE=1 | use the software renderer; SLOPPY_SOFT_SCALE=1 draws it at full resolution |
SLOPPY_NO_GPU=1 | GPU arrays and compute functions run on the CPU |
SLOPPY_VK_DEVICE=n | use the nth Vulkan device (e.g. Mesa's software driver, for testing) |
SLOPPY_VK_VALIDATE=1 | turn on the Khronos validation layer, where it is installed |
SLOPPY_VK_PIPELINE_CACHE=0 | do not keep pipelines between runs |
SLOPPY_STATS=1 | show frame times and the renderer in use (?stats on a web page) |
- Which renderer did I get, and why not Vulkan?
SLOPPY_VK_VALIDATE=1prints the Vulkan device chosen; a game that falls back to OpenGL prints why Vulkan could not be used (no Vulkan 1.3 driver, a missing feature) whenSLOPPY_VULKAN=1asks for it. - The first run of a game starts slower than later ones. With Vulkan, the driver builds a pipeline for each shader and state the first time they are drawn; the library keeps them in
~/.cache/sloppy(%LOCALAPPDATA%\sloppyon Windows), so later runs start drawing at once. - A shader compiles but draws differently on one renderer. That is a bug in Sloppy: please report it with the program.
SLOPPY_VULKAN=0andSLOPPY_SOFTWARE=1let you compare the three on one machine.
Placement and angle conventions
camera3d takes its vertical fov_degrees in degrees, default 60.0. This is a deliberate exception to radians elsewhere: camera3d(cam, fov_degrees = 60) uses the same field of view as perspective(60deg, aspect, near, far). A 60deg literal is already radians; do not pass it as fov_degrees.
Sprite placement keeps the existing conventions:
| Draw operation | Default point at the supplied position |
|---|---|
sprite | Top left (origin = vec2(0, 0)) |
sprite_region, draw_frame, draw_anim, AnimPlayer.draw, draw_tile | Center (origin = vec2(0.5, 0.5)) |
sprite_tiled | Fills its Rect; x/y are its top left |
draw_target | Top left |
origin is a normalized placement anchor before rotation. With draw point P and final size S, the actual center is P + (vec2(0.5, 0.5) - origin) * abs(S); the corners rotate about that center. It is not a fixed rotation pivot: a feet anchor vec2(0.5, 1) places the feet at P only before turning. Mirroring changes the picture, not that anchor offset. To turn about a fixed point, rotate the offset yourself and use a centered origin: pass P + rotate((vec2(0.5, 0.5) - anchor) * abs(S), angle) as the position with origin = vec2(0.5, 0.5). The same formula applies to sheet frames using their scaled size.