Second Reality - source code

Just a quick follow-up to my previous note. As mentioned by Michal, Future Crew guys decided to celebrate the 20th anniversary of Second Reality in the best way possible - they released a full source code. Obviously, it’s more of a tidbit than anything else, but it’s still interesting to finally see how certain effects were done. Apparently Fabian is already working on a code analysis article, but in the meantime I’ll only mention two things that caught my eye so far:

  • lots of auto generated code. They have small C programs generating assembly inner loops. Neat idea

  • loop unrolling galore. There’s a neat trick we’ve been using back in the 90s (no longer applicable with modern CPUs). In C/C++ terms it’s an extreme case of Duff’s device - instead of processing 4/8/16/xx, we unroll the whole loop. This means no need for loop counter manipulation and no need to update the data pointer. Example (Gouraud shader, AVIDFILL.ASM, line 458):

        mov	ax,cx
	shl	cx,3
	sub	ax,cx
	;ax=-cx*7
	add	ax,OFFSET @@vdfg_fcode
	mov	bx,cs:vdfg_color2
	sub	bx,dx ;one extra
	jmp	ax

zzz=MAXCOLS
REPT	MAXCOLS+1
	add	bx,dx			;2 bytes
	mov	cs:vdfg_buf[zzz],bh	;5 bytes
	zzz=zzz-1
ENDM
	mov ax,bx			;2 bytes, 1 clock (filler)
@@vdfg_fcode:

(REPT is a macro that’ll repeat code between REPT/ENDM specified number of times) As you can see, the only thing that’s modified in every “iteration” is the BX register, 2 instructions per loop (instead of 4+conditional jump). In order to find jump address we multiply number of pixels to fill (originally in CX) by 7 (bytes per “iteration”) then subtract it from the end address (so we go back “x” iterations).