 ! Factor port of the raytracer benchmark from
-! http://www.ffconsultancy.com/free/ray_tracer/languages.html
+! http://www.ffconsultancy.com/languages/ray_tracer/index.html
 
 USING: arrays accessors io io.files io.files.temp
 io.encodings.binary kernel math math.constants math.functions
-math.vectors math.vectors.simd math.vectors.simd.cords math.parser
-make sequences sequences.private words hints classes.struct ;
-QUALIFIED-WITH: alien.c-types c
+math.vectors math.vectors.simd math.vectors.simd.cords
+math.parser make sequences words combinators ;
 IN: benchmark.raytracer-simd
+
+<< SYNTAX: no-compile word t "no-compile" set-word-prop ; >>
 
 ! parameters
 

    ] [
        [ sray-intersect lambda>> 1/0. = ] keep swap
        [ ray-g neg ] [ drop 0.0 ] if
    ] if ; inline

: create-center ( c r d -- c2 )
    [ 3.0 12.0 sqrt / * ] dip n*v v+ ; inline

DEFER: create ( level c r -- scene )

: create-step ( level c r d -- scene )
    over [ create-center ] dip 2.0 / [ 1 - ] 2dip create ;

: create-offsets ( quot -- )
    {
        double-4{ -1.0 1.0 -1.0 0.0 }
        double-4{ 1.0 1.0 -1.0 0.0 }
        double-4{ -1.0 1.0 1.0 0.0 }
        double-4{ 1.0 1.0 1.0 0.0 }
    } swap each ; inline

: create-bound ( c r -- sphere ) 3.0 * <sphere> ;

: create-group ( level c r -- scene )
    2dup create-bound [
        2dup <sphere> ,
        [ [ 3dup ] dip create-step , ] create-offsets 3drop
    ] make-group ;

: create ( level c r -- scene )
    pick 1 = [ <sphere> nip ] [ create-group ] if ;

: ss-point ( dx dy -- point )
    [ oversampling /f ] bi@ 0.0 0.0 double-4-boa ;

: ss-grid ( -- ss-grid )
    oversampling iota [ oversampling iota [ ss-point ] with map ] map ;

: ray-grid ( point ss-grid -- ray-grid )
    [
        [ v+ normalize double-4{ 0.0 0.0 -4.0 0.0 } swap <ray> ] with map
    ] with map ;

: ray-pixel ( scene point -- n )
    ss-grid ray-grid [ 0.0 ] 2dip
    [ [ swap cast-ray + ] with each ] with each ;

: pixel-grid ( -- grid )
    size iota reverse [
        size iota [
            [ size 0.5 * - ] bi@ swap size
            0.0 double-4-boa
        ] with map
    ] map ;

: pgm-header ( w h -- )
    "P5\n" % swap # " " % # "\n255\n" % ;

: pgm-pixel ( n -- ) 255 * 0.5 + >fixnum , ;

: ray-trace ( scene -- pixels )
    pixel-grid [ [ ray-pixel ] with map ] with map ;

: run ( -- string )
    levels double-4{ 0.0 -1.0 0.0 0.0 } 1.0 create ray-trace [


CONSTANT: size 200

: delta ( -- n ) epsilon sqrt ; inline no-compile

TUPLE: ray { orig double-4 read-only } { dir double-4 read-only } ;

