9. Drawing the 3-D world
How a list of ship shapes and positions becomes the picture on the screen, with no 3-D hardware: models, the camera, perspective, hiding the back of things, painting far to near, and the small extras (stars, explosions, radar, text). At the end: what a modern rebuild should keep to look the same.
The screen
- 640 × 350 pixels, 16 colours (EGA/VGA mode 10h). The colours are the standard EGA set; the game never changes them. Models use them in dark/bright pairs (for example magenta 5 and light magenta 13), probably to suggest shading H.
- Pixels are not square. 350 lines fill a 4:3 monitor, so a pixel is about 1.37 times as tall as it is wide. The 3-D projection and the discs correct for this; the instruments, the radar and the texts are laid out in raw pixels and so appear 1.37 times taller than their pixel counts suggest. A rebuild must scale x by width ÷ 640 and y by height ÷ 350 separately to keep their shapes.
- Two pages (chapter 2): the game draws on the hidden page and swaps at the monitor's retrace, so you always see the previous frame's finished picture.
- Drawing coordinates are measured from the screen centre (320, 175), x to the right and y downward.
| EGA colour | Used for (main uses) |
|---|---|
| 0 black | space |
| 15 white | stars, far objects ("+"), laser shots, white model parts, texts |
| 4 red / 12 light red | instrument frames and texts, hit flash, explosion sparks, shot rings |
| 10 light green | highlights, locked sight, gauge bars, alien blips, collision flash |
| 14 yellow | powered shots, enemy missile blips, explosion sparks, powered-hit flash |
| 13 light magenta | pod blips on the radar |
| most colours (1, 2, 4, 5, 7, 8, 9, 10, 12, 13, 15) | the faces of the models |
The /M command-line switch maps everything to greys and white for monochrome monitors.
Models
Every ship, alien, pod, satellite and missile is a model: up to 48 points (vertices) in the object's own frame (x along its right axis, y along its "up" axis, z along its forward axis) and up to 64 faces. A face is a colour plus 2 to 5 vertex numbers: two vertices make a line (antennas, spikes), three or more a flat polygon (in practice triangles and quads). There is no texture and no lighting: each face is one solid colour. The models are in assets/models/ (readable text) and src/data/.
Coordinates are small numbers, at most ±96. One model unit is 2scale world units. The model files all say scale 0 (the stored value), but at start-up the game sets the scale to 1 (two world units) for ships, aliens and pods, so a pod is 384 units tip to tip, and to 2 for one of the title logo models; satellites and missiles keep scale 0 and are half as big.
From the world to the screen, per object
All of this happens in render_object (src/render.c), called for each body right after it moves (chapter 5):
- Where is it, seen from me? Subtract my position from the object's, block-normalise it into a direction plus a distance exponent (chapter 3; bigger exponent = nearer), and dot the direction with my three axes: across (right), along my "up" axis (drawn downward, chapter 3), and ahead (forward). These are its camera coordinates.
- Is it in front of me? The centre must be ahead (z above 512 camera units: in practice, simply in front of you), with |x| ≤ z and |2y| ≤ z, i.e. within ±45° sideways and about ±27° up and down. Otherwise nothing is drawn.
- Very far? If the distance exponent is negative (the largest coordinate difference above 32,768 units for ships, aliens and pods, above 16,384 for satellites and missiles), draw a small white "+" of 5 pixels at its screen position and stop.
- Transform the vertices. Each model point is turned from the object's frame into my camera frame (a 3 × 3 rotation made of dot products between my axes and its axes) and moved to the object's camera position.
- Project. Divide by the depth to get perspective (next section).
- Throw away what cannot be drawn. A vertex too close to the eye (nearer than 512 camera units, which is about 1/16 to 1/32 of the object's own distance, so it happens only within about a ship's length) or behind it makes every face that uses it disappear: there is no clipping against a near plane. Faces seen from behind are dropped (back-face culling, below).
- Queue the remaining faces in the frame's draw list with a depth (below).
Perspective: the projection
A point at camera coordinates (x across, y down, z ahead) lands at
screen x = 320 + 512 · x ÷ z, screen y = 175 + 384 · y ÷ z.
Dividing by z is what makes far things small. The two factors set the field of view: 64° across the 640 pixels and 49° across the 350 lines. The vertical factor is 3/4 of the horizontal one to make up for the tall pixels, so on a 4:3 monitor circles look round (very nearly: the picture is about 3 % taller than a geometrically exact one).
Back-face culling: skip faces that look away
A closed model has faces on its far side that are hidden by those in front. The game skips them cheaply: after projection, it looks at the order of a face's first three corners on the screen. Each model lists the corners of its outward faces clockwise as seen from outside, so a face whose corners appear clockwise on screen faces you and is kept; anticlockwise means you see its back, and it is dropped. (The test is the sign of a 2-D cross product; edge-on faces are kept.) Line faces are never dropped.
The painter's algorithm: far first
There is no depth buffer. Instead every face gets one depth, the distance ahead of its farthest corner, and faces are drawn from the farthest to the nearest, so nearer faces paint over farther ones, like a painter who paints the background first. During the frame each face is inserted into a list kept sorted by depth (the draw list; faces of equal depth stay in the order they were queued), and after all objects have moved, the list is drawn in order (draw_list_flush).
One depth per face is a rough rule: long faces, or two objects that overlap in depth, can be painted in the wrong order for a frame, and a face can flash in front of another. This is part of the original look; a rebuild with a depth buffer will simply not have it.
Lines mode
The "Lines" option (the default on computers older than a 386) draws the edges of the polygons instead of filling them: every polygon edge once per object, in the bright version of the face's colour (colour c below 8 becomes c + 8, and 8 becomes 7; line faces keep their own colour; in monochrome every edge is white). Back faces are still culled, but nothing is sorted, so the front-facing edges of a model show through each other and through other models. The velocity indicator of chapter 1 is not drawn in this mode. Lines mode also shows only 64 of the 256 stars and uses 12 instead of 38 explosion sparks.
Try it
The original rules in a few lines of JavaScript: model scale 1, projection 512/384 onto 640 × 350 with tall pixels (the canvas stretches the picture to 4:3), faces with a vertex too near the eye dropped (the limit is 512 camera units, which in world units depends on the object's distance exponent), back faces culled by winding, one depth per face, far first; Lines mode brightens and does not sort. The model spins slowly. Turn culling off to see the back faces painted over the front ones, or move the Fighter very close (below about 300) to see faces vanish. The demo skips the "is the centre in view" test.
The other things on screen
- Far objects: the white "+" of step 3 is drawn at once, during the simulation, before the stars and the draw list, so stars and anything nearer can cover it.
- Stars: 256 fixed directions at infinite distance (chapter 5); a star is drawn when it is within 43° of the view direction, as one or two white pixels, before the draw list.
- Laser shots: a filled disc (white, yellow when powered) of 32 world units radius, following perspective, visible within ±45° both ways; a hit leaves a red ring for 7 frames. Discs are sorted into the draw list like faces.
- Explosions: up to 38 discs flying apart (chapter 5), sorted into the list as well, drawn within about ±63° of the view.
- The radar, the instruments and texts (chapter 1) are drawn last, on top of everything, as plain lines and an 8 × 8 pixel font; large digits on some screens use a font made of lines.
- Menus and title reuse the same 3-D renderer to show spinning models: the title logo (two models plus two bitmap pictures), the ships in the lobby, the aliens on the level introduction.
- The mouse cursor (a small box in flight, an arrow in menus) is drawn straight onto the page being shown, not the one being drawn, so it can move between frames.
- Discs (shots, sparks) are drawn 4/3 larger than the sphere they stand for, in both directions (still round); they are not drawn when the radius would exceed 128 rows (very near), and a radius of 1 or less is drawn as the small "+".
- Explosion sparks are sorted as if they were twice as far away as they are, so faces behind them can cover them; when the largest coordinate difference to the explosion is between 16,384 and 32,768 units they get depth 0 and are drawn over everything; beyond that the explosion is not drawn at all D.
- A shot's hit ring is sorted 256 units nearer than the shot (probably so it shows over the face it hit H).
- The "is it in view" test uses only the object's centre and is barely wider than the screen vertically: a big object close above or below the view vanishes whole while parts of it would still be visible.
- A face that touches the space just in front of the eye disappears whole (no near clipping), so very close objects lose faces one by one.
Drawing and simulation are one pass
NetWars does not separate "update the world" from "draw the world": each object is moved and immediately measured for drawing, and the measurements (direction, distance exponent, camera coordinates) are stored in the object and reused by the game rules: collisions with you, the radar, the missile lock, missile expiry, the aliens' "how near is the player" (chapters 5 to 7). They are computed for every object every frame, even when it is not drawn (behind you, cloaked, far away).
Keep the look: flat single-colour faces in the 16 EGA colours (light and dark pairs), 1-pixel lines for line faces and instruments (scaled with the resolution), solid discs for shots and sparks, white point stars, the dark background with a one-frame colour flash, and a 64° × 49° view on a 4:3 area. At a higher resolution keep the same field of view and scale every pixel size (discs, "+", lines, font) with it.
Field of view in a modern API: the original maps camera coordinates to normalised screen coordinates as xndc = 1.6 · x ÷ z and yndc = 2.194 · y ÷ z (512/320 and 384/175). In a perspective-matrix function that is a vertical field of view of 49° with an aspect ratio of 1.371 (not 4/3, which would give 62.6° across), drawn into a 4:3 area.
Free to improve: a depth buffer instead of the painter's sort, clipping against a near
plane, per-vertex view tests, interpolated motion between simulation steps (chapter 2). With
WebGL, as long as the picture is not mirrored (camera up = −c, chapter 3), front faces wind
clockwise on screen: gl.frontFace(gl.CW) with gl.cullFace(gl.BACK). Keep
culling on: some models have two-sided fins stored as two opposite faces. Draw line faces as
lines.
Where the remaining geometry is: radar layout in src/radar.c (a trapezoid around a centre at (232, 110) from the screen centre); instrument positions in src/hud.c and src/globals.c; star directions and explosion spark directions in src/globals.c; the 8 × 8 font in assets/fonts/font8x8.txt and the line font in src/effects.c; the title screen (logo models 2500 units ahead, turning 16/2048 per frame, one of them drawn twice, the second copy rolled 180°, plus the two logo pictures in assets/bitmaps/) in src/screens.c. The draw list holds at most 1024 entries.
Keep the coupling: compute each object's camera-relative values every simulation step, for all objects, and feed them to the game rules exactly as the original does, even if your renderer computes its own.
- Camera coordinates and the limits of 512 (the "in front" test and the near-vertex test) are in camera units (chapter 3: world units times 2exponent − scale). A vertex at or below 512 is unusable (≤, not <).
- Vertices are transformed in whole numbers: the model point is multiplied by 2exponent, each camera coordinate is the object's camera coordinate plus three rounded-down Q14 dot products (chapter 3), and the result is a whole number. The back-face test uses the whole-pixel screen points, so a tiny face whose corners fall on the same pixels has a cross product of 0 and is kept.
- The projection divides and truncates toward zero; the screen position may lie outside the screen (the centre test allows ±45° while the screen shows ±32°), and drawing clips it.
- The sort depth of a vertex is its camera depth converted back to world units, a whole number; faces of equal depth keep the order in which they were queued.