Skip to content

Latest commit

 

History

History

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 

README.md

Ray Tracer

A ray tracer written in Forth that renders three spheres on a checkerboard ground plane. Outputs an 800x600 PPM image to stdout with no external dependencies.

Rendered scene

Features

  • 3 spheres — large red (left), reflective chrome (center), small blue (right)
  • Checkerboard ground plane — alternating white and green tiles
  • Sky gradient — white at the horizon fading to blue at the zenith
  • Diffuse shading — Lambertian lighting from a single point light
  • Specular highlights — Blinn-Phong model with per-material shininess
  • Hard shadows — shadow rays to the light source
  • Mirror reflections — up to 2 bounces, visible in the chrome sphere

Build and run

ccforth -o raytrace examples/raytrace/raytrace.fth
./raytrace > scene.ppm

View the output with any image viewer that supports PPM:

feh scene.ppm
display scene.ppm
eog scene.ppm

Or convert to PNG:

convert scene.ppm scene.png

Code structure

The program is a single file (~300 lines) organised into sections:

  1. Utilitiesf>byte (clamp and convert float to 0–255), F, (compile a float literal into the dictionary)
  2. Vector mathvec+, vec-, vec-scale, vec-dot, vec-length, vec-normalize operating on 3 floats on the float stack
  3. Scene data — sphere geometry and materials stored in a CREATE block (9 floats per sphere: position, radius, color, shininess, reflectivity), light position, ambient level
  4. Camera — look-at camera with orthonormal basis vectors (forward, right, up) stored in FVARIABLEs; pixel-ray generates a normalised ray direction for each pixel
  5. Intersectionray-sphere (quadratic formula), ray-plane (ground plane at y=0), trace-scene (find closest hit, store result in FVARIABLE hit state)
  6. Shadingsky-color (horizon-to-zenith gradient), checkerboard (alternating tiles via FLOOR), shade-lighting (diffuse + Blinn-Phong specular with shadow test), trace-ray (recursive, uses RECURSE for reflection bounces)
  7. Output — PPM P6 header, per-pixel rendering loop, MAIN entry point

Techniques demonstrated

  • Typed float locals{: F: x F: y F: z :} keeps vectors in CPU registers in the compiled C output
  • Compile-time dataCREATE + F, to store sphere data in the dictionary at compile time
  • RECURSE — recursive ray tracing for mirror reflections
  • FVARIABLE state — hit state and shading accumulators avoid exceeding the locals limit while keeping the code readable