Drawing
Reference grids
A reference grid is the floor of a CAD program or a 3D plot: lines every metre, a heavier line every ten, and the axes in color. It must look clean at any zoom, from a millimetre to a continent, in perspective and orthographic views, and stay in place far from the world's origin. This page explains how to draw one from a single triangle. The last part shows how RASM does it.
In short
- Draw one triangle over the screen. Each pixel sends its ray to the grid's plane and finds the point it shows there.
- The point's depth goes to the depth test, so objects hide the grid where they stand in front of it.
- Lines have a width in pixels, from the screen derivatives of the plane coordinates. A line thinner than a pixel fades instead of breaking up.
- Cells come in levels (1, 10, 100, ...). Each pixel shows the levels whose cells are wide enough there, and fades between them, so the grid stays crisp at any zoom.
- Far from the origin, split the camera's place on the plane into whole cells and a rest, in doubles on the CPU. The lines stay exact anywhere.
1Why not a mesh of lines
The obvious grid is geometry: a quad per line, or a big textured square. Both break at the edges of what a camera can see.
Lines as geometry
Far lines get thinner than a pixel and flicker; a fine grid turns into moiré; the mesh has an end, and a mesh as big as a planet has no precision left.
A ray per pixel
The grid is a rule, not a mesh: every pixel computes it for its own point. It has no end, no seams, and every line is as wide as it should be on screen.
2A ray per pixel
The triangle covers the whole target. For each pixel the shader builds the ray through the pixel's centre, meets the plane, and computes the hit's coordinates on the plane and its depth.
A perspective camera's rays start at the camera and spread out. An orthographic camera's rays are parallel: they all have the view's direction, and start across the near plane.
Perspective
Ray from the camera through (x / P00, y / P11, −1) in view space.
Orthographic
Ray along −Z from ((x − P03) / P00, (y − P13) / P11, 0): even spacing everywhere.
The plane
h is the camera's height above the plane, so the numbers stay small near the camera.
3Lines a pixel wide
The hit's plane coordinates, counted in cells, are uv. Their change from one pixel to the next, the derivative, says how many cells one pixel covers there. With it, a width in pixels becomes a width in cells.
d = ( |(∂u/∂x, ∂u/∂y)|, |(∂v/∂x, ∂v/∂y)| )
w = widthPixels · d
distance = 1 − |fract(uv) · 2 − 1|
coverage = smoothstep(w + 1.5 d, w − 1.5 d, distance)
- d
- cells per pixel along each axis, from
ddxandddyof uv - w
- the line's width in cells
- distance
- twice the distance to the nearest line, in cells: 0 on a line, 1 halfway between two
- smoothstep
- an edge about a pixel and a half wide: the line is smooth, not stair-stepped
Two more rules keep thin and dense lines quiet (Ben Golus' "pristine grid"):
Thin lines drawn thin
A line 0.3 pixels wide covers some pixel centres and misses others: it breaks into dashes, and they crawl as the view moves.
Clamp to a pixel, then fade
A thin line is drawn a pixel wide and faded by w / d. When cells get near two pixels wide, the result blends to the line's share of the cell, the average a far grid would have.
4Levels: crisp at any zoom
One cell size cannot serve every zoom: zoomed out, 1 cm cells are a gray haze; zoomed in, 1 km cells are empty. So the cells come in levels: cellSize × sk for s subdivisions. Each pixel picks the level whose cells are F pixels wide there, and draws three levels next to each other.
lod = max(0, logs(max(dx, dy) · F))
A = ⌊lod⌋ blend = lod − A
- d
- finest cells per pixel, as above
- F
- the width in pixels where a level's cells are fully shown (32 here)
- blend
- A's lines fade by 1 − blend, B's turn from major to minor, C's fade in by blend
In a perspective view, d grows with distance, so near pixels show fine cells and far pixels coarse ones. In an orthographic view, d is the same everywhere, so the whole view shows the same levels.
5Far from the origin
The lines sit at whole cells of the plane's coordinate. Far from the grid's origin, that coordinate is a big number, and a float cannot hold its fraction.
The fix splits the camera's coordinate on the plane, in doubles, into whole cells n and a rest f in [0, 1). Only n modulo a period matters, and the period can be a power of s, because every level's cells divide it.
camera coordinate / cellSize = n + f
R = n mod sJ (an integer, sJ ≤ 232)
uv at level k = ((R mod sk) + f + q / cellSize) / sk
- q
- the hit relative to the camera, small near the camera, where the fine levels are
- R mod sk
- exact integer math; the sum stays below a few cells of level k, so a float holds it
The camera's height above the plane comes from the CPU in doubles too, so the ray meets the plane at the right place however far both are from the origin.
6Fades and edges
Grazing angles
Where the ray almost runs along the plane, the grid fades out: an edge-on plane is all moiré.
Distance
A perspective view can fade the grid out with distance, so it does not reach the horizon.
A bounded grid
An extent cuts the grid to a rectangle, its edge smoothed over a pixel like a line.
7Pitfalls
- The grid shows through objects
- It was drawn without its own depth. Write the hit's depth and test it against the scene.
- Lines flicker and crawl in the distance
- A fixed width in world units. Use a width in pixels from the derivatives, and fade lines thinner than a pixel.
- A gray haze of moiré far away
- One level of cells for every pixel. Pick levels per pixel from the derivative.
- A sudden jump while zooming
- Levels switch at a threshold. Blend three levels by the fraction of the level of detail.
- Lines step or wobble far from the origin
- The plane coordinate was a float. Split it into whole cells modulo a period and a rest, in doubles on the CPU.
- Black pixels or lines along the horizon
- The derivatives blow up where the ray runs along the plane. Fade by the grazing angle, and take the derivatives before any discard so all four pixels of a quad have them.
8In RASM
A grid belongs to a camera: Renderer::setCameraGrid(camera, Grid) draws it in every shaded view of that camera, so each viewport of a CAD layout can have its own plane. A Grid is the plane (origin in doubles, orientation: its local XZ plane), the finest cellSize, subdivisions, an extent (0: endless), colors and widths, the axes, and a fadeDistance.
RASM_EXPORT_VIEW) sizes given in pixels are multiplied by SceneData::pixelScale (getPixelScale), its ExportDesc::pixelScale, which also divides the LOD's pixels per unit; in every other view it is 1 and the shaders do no work for it. Sizes in metres do not change.| This page | RASM |
|---|---|
| One triangle, a ray per pixel | Renderer::drawGrid (src/renderer/gpuScene.cpp) draws three vertices with shaders/passes/grid.slang, first in the Transparent pass, after the opaque draws and the sky. Not in a debug view, and not in depth-only views. |
| Depth tested, not written | The pipeline has BlendMode::PREMULTIPLIED_ALPHA, depth test on, depth write off; the fragment writes the hit's depth. Its motion is the hit's, from previousViewProjection. |
| Lines in pixels | lineWidth and majorLineWidth; the axes are majorLineWidth + 0.5 pixels, in xAxisColor and zAxisColor (alpha 0 hides one). |
| Levels | F = 32 pixels (FADE_PIXELS in the shader); subdivisions from 2 to 1000, so at least three levels fit in 32 bits. |
| Whole cells and a rest | makeGridData (src/renderer/grid.cpp) writes residueX, residueZ, fractionX, fractionZ and the camera's height above the plane from doubles, every frame, in each view's render space (Large worlds). period is the largest power of subdivisions in 32 bits. |
| Fades and edges | Grazing angle always; fadeDistance in perspective views; extent in world units along the plane's X and Z. |
Code map
| What | Where |
|---|---|
| The API | Grid in include/rasm/grid.h; Renderer::setCameraGrid, Renderer::getCameraGrid; rasm_set_camera_grid in C |
| Per-view data | checkGrid and makeGridData in src/renderer/grid.cpp; gfx::GridData in src/renderer/uberMaterialTypes.h and shaders/lib/core.slang |
| The draw | prepareSceneView fills SceneData::grid (also while the scene's meshes still load); drawGrid in the Transparent pass |
| The shader | shaders/passes/grid.slang: getLineCoverage, getLevelUv, getAxisCoverage |
| Example | examples/27_cad_views/main.cpp: four views, each with a grid in its own plane |
| Tests | tests/gridTests.cpp (the residues against a direct computation, far and near); image tests grid, grid_ortho, grid_msaa4, grid_taa, far_grid, and a bounded grid in ortho |
Every value that depends on where the camera is on the plane comes from makeGridData in doubles. Keep GridData in step on both sides (struct layout). The grid reads only SceneData: no draw, no culling, no pick.
Not yet
- An axis out of the plane (a vertical Y axis over an XZ grid): draw it as a vector line a few pixels wide.
- The grid is not pickable; the ray-plane test of section 2 on the CPU gives its point under the mouse.
Further reading
- Ben Golus, "The Best Darn Grid Shader (Yet)", 2023: line coverage with derivatives and the moiré fade.
- Projection and reversed-Z depth, Large worlds, Transparency, pan and zoom.