PlayBASIC Math Library Demo - PlayBASIC Math Library Demo - Simple Ray Tracer


This example demonstrates a simple real-time ray tracer written entirely in PlayBASIC, using the new `PB_Vector3` and `PB_Ray` math libraries. Rather than drawing sprites or polygons, the program renders the scene by firing rays into a virtual 3D world and calculating what each ray hits.

While the visuals may look advanced, the goal of this demo is to show how clean and approachable modern 3D techniques become when supported by solid math helpers.







What does this program actually do?

For every pixel on the screen, the program creates a ray that starts at the camera and travels forward into the scene.
Each ray is tested against a small list of spheres to see if it intersects any of them.

If a ray hits a sphere, the program:

* Finds the exact point of impact
* Calculates the surface direction at that point
* Applies lighting, shading, and highlights

If no object is hit, the pixel is coloured with a simple sky gradient.

By repeating this process for every pixel, the program builds a full image entirely from math.




Why vectors are so important

A vector is simply a direction in 3D space. In this example, vectors are used everywhere:

* Ray directions
* Surface normals
* Light direction
* View direction (toward the camera)

The new `PB_Vector3` functions handle all the hard work:
normalising directions, adding vectors, taking dot products, and scaling values.

This lets programmers focus on *what they want to do* instead of *how the math works internally*.




Ray casting and intersections

A ray is defined by two things:
where it starts and which direction it travels.

Using `RayIntersectSphere`, the program checks whether a ray passes through a sphere and, if so, how far away the collision occurs. The closest hit is always chosen, which ensures objects in front correctly block objects behind them.

This same technique is used both for:

* Camera rays (what the viewer sees)
* Shadow rays (checking if a point is in shadow)




Lighting and shadows

Once a ray hits a sphere, lighting calculations take place:

* A small ambient value ensures nothing is completely black
* Diffuse lighting depends on how directly the surface faces the light
* Specular highlights create shiny reflections

To determine shadows, a second ray is fired toward the light source.
If anything blocks it, the point is considered in shadow and only ambient lighting is applied.

This single technique dramatically increases realism while keeping the code understandable.




Why this matters for PlayBASIC users

With the new Vector3 and ray tools, PlayBASIC programmers can now explore:

* Collision detection
* Ray-based picking
* Lighting models
* Physics and camera systems
* Reflection and refraction effects

All of this is possible without leaving BASIC, and without relying on external engines or shaders.

For beginners especially, this example shows that modern graphics techniques are not out of reach—they simply require the right building blocks.

The new math libraries provide exactly that foundation.


  Note: Requires PlayBASIC V1.65C3 Beta 49

PlayBASIC Code:
    Type tSphere
        center as PB_Vector3 
        radius#    
        colour
        specular#
        reflective#
    EndType


    type tLight
        Dir as PB_VEctor3
        NegDir as PB_VEctor3            ; negated light direction
        Colour    
    Endtype


    type tImpactPoint
        Hit        as PB_Vector3    
        Normal    as PB_Vector3    
    Endtype

    Global Width          = 400
    Global Height        = 300
    Global Aspect#    = float(Width)/Height
    Global Fov#        = 60.0
    Global HalfWidth#  = Tan(Fov#*0.5)

    Global HalfHeight# = HalfWidth# / Aspect#

    Dim Spheres(3) as tSphere

    SetupScene()

    Dim Ray as PB_Ray pointer
    Ray = new PB_RAY
    ray.origin.x# = 0
    ray.origin.y# = 0  
    ray.origin.z# = 4

    global ViewDir as PB_Vector3 pointer
    ViewDir = new PB_Vector3

    global halfVec as PB_Vector3 pointer
    halfVec  = new PB_Vector3
    
    global TempVec as PB_Vector3 pointer
    TempVec  = new PB_Vector3

    ; Simple directional light (sun)
    global Light as tLight pointer
        Light = new tLight
        Vector3_Set(LIght.dir , -0.5, -1.0, -0.5)
        Vector3_Normalize(light.Dir)
        Vector3_NegateTo(light.NegDir, light.Dir)
        light.Colour = rgb(255,255,240)
    
        global shadowRay as PB_Ray pointer
          shadowRay = new PB_Ray

        global ImpactPoint as tImpactPoint pointer
        ImpactPoint = new tImpactPoint  

        dim HitResult as PB_HitResult pointer
        HitResult = new PB_HitResult

        SetFps 60

        Screen=NewfxIMage(Width,Height)

        Do

            rendertoimage screen
            lockbuffer
            ThisRGB =point(0,0)
            For y = 0 To Height-1 step 1
                    For x = 0 To Width-1 step 1
                            CastRay(ray, x, y)
                        col = TraceRay(ray, HitResult)
                            fastdot x, y, col
                      Next
                  Next
            unlockbuffer
            
            DisplayScreen(Screen)

            ray.origin.z# -= 0.05
        Sync    
    Loop

Function DisplayScreen(ThisIMAGE)
        rendertoscreen
        ScaleX#=GetScreenWidth()/float(Width)
        ScaleY#=GetScreenHeight()/float(Height)
        drawrotatedimage ThisIMage,0,0,angle#,ScaleX#,scaleY#,0,0,0 
EndFunction 


;=================================================================
Function CastRay(Ray as PB_Ray Pointer,x, y)
    
    u# = ((x + 0.5) / Width ) * 2.0 - 1.0
    v# = ((y + 0.5) / Height) * 2.0 - 1.0
    v# = -v#  ; Y is down in screen space
    
    ray.dir.x# = u# * HalfWidth#
    ray.dir.y# = v# * HalfHeight#
    ray.dir.z# = -1.0
    Vector3_Normalize(ray.dir)
    
EndFunction



Function TraceRay(ray as PB_RAY pointer,  HitResult as PB_HitResult pointer)
    t# = 999999.0
    hitSphere = -1

    ObjectCount = getarrayelements( Spheres())

    ; Find closest sphere intersection from viewer
    For i = 0 To ObjectCOUNT
            result =RayIntersectSphere(ray, Spheres(i).tSphere, HitResult) 
            if result>0
                    dist#=hitresult.t    
                  If dist# > 0.001 And dist# < t#
                        t# = dist#
                            hitSphere = i
                            ;  Copy the impact & Normals 
                            ImpactPoint.hit            = HitResult.Hitpoint
                            ImpactPoint.Normal        = HitResult.Normal
                    EndIf
            endif    
      Next

    ; if the ray misses all objects, we exit
    If hitSphere = -1
        ; Sky gradient
        dirY#    = ray.dir.y# 
        dirY#    = (dirY# + 1.0) * 0.5
        col    = Rgb(255*dirY#, 255*dirY#, 255)
        exitfunction  col
    EndIf


    ; The impact point will be ontop of the sphere surface,
    ; we actually don't want this, So lets move it off
    ; just a little to avoid self detection
    
    Vector3_Scale(TempVec, ImpactPoint.Normal, 0.001)    
    Vector3_Add(ShadowRay.Origin, ImpactPoint.Hit, TempVec)
        
    ; Shadow ray
  ;  inShadow = 0
    shadowRay.dir        = light.negDir  // pre negated / normalized
        
    //  Check for impacts between this ray and existing objects
    For i = 0 To ObjectCOUNT
              result =RayIntersectSphere(ShadowRay, Spheres(i).tSphere, HitResult) 
            if result
                if HitResult.tEnter# >0.001
                    inShadow = 1
                    ExitFor
            EndIf
        EndIf
    Next
    
    materialColour = Spheres(hitSphere).colour

    specular#        = Spheres(hitSphere).specular#

    reflective#    = Spheres(hitSphere).reflective#

    ; Ambient colour
    finalCol# = 0.1
    
    If inShadow = 0
        ; Diffuse
        NdotL# = Vector3_Dot(impactpoint.normal, light.NegDir)
        If NdotL# > 0
            finalCol# += NdotL# * 0.8
        EndIf


        If specular# > 0
            ; Step 1: view direction = -ray.dir (from surface toward camera)
            Vector3_NegateTo(ViewDir, Ray.Dir)  
          
            ; Step 2: half vector = normalize( lightDir + viewDir )
    ;        But lightDir points TOWARD the light, so we want -lightDir (from surface to light)
            Vector3_Add(TempVec, Light.NegDir, ViewDir)    ; TempVec = L + V
            Vector3_NormalizeTo(halfVec, TempVec)          ; halfVec = normalized(L + V)

            ; Step 3: specular term
            d# = Vector3_Dot(ImpactPoint.Normal, halfVec)
            d# = MaxVal#(0.0, d#)
            spec# = d# ^ 32    
            finalCol# = finalCol# + spec# * specular#
        EndIf
    EndIf


        finalCol#    =cliprange#(finalCol#,0,1)
        col            =RgbFade(materialColour,FinalCol#*100 ) 
    
EndFunction Col



Function SetupScene()
    ; Floor sphere (big matte)

    Spheres(0).center.x = 0 
    Spheres(0).center.y = -100.5 
    Spheres(0).center.z = -1

    Spheres(0).radius# = 100
    Spheres(0).colour = rgb(200,200,220)
    Spheres(0).specular# = 0.1
    Spheres(0).reflective# = 0.0
    
    ; Red shiny sphere
    Spheres(1).center.x# = -1.0
    Spheres(1).center.y# = 0
    Spheres(1).center.z# = -1

    Spheres(1).radius# = 0.5
    Spheres(1).colour = rgb(220,50,50)
    Spheres(1).specular# = 0.9
    Spheres(1).reflective# = 0.8
    
    ; Green glass sphere
    Spheres(2).center.x# = 1.0 
    Spheres(2).center.y# = -0.2 
    Spheres(2).center.z# = -0.5
    Spheres(2).radius# = 0.5
    Spheres(2).colour = rgb(50,220,100)
    Spheres(2).specular# = 0.8
    Spheres(2).reflective# = 0.95
    
    ; Metal sphere
    Spheres(3).center.x# = 0 
    Spheres(3).center.y# = 0.3
    Spheres(3).center.z# = -1.5
    Spheres(3).radius# = 0.4
    Spheres(3).colour = rgb(220,220,220)
    Spheres(3).specular# = 1.0
    Spheres(3).reflective# = 0.99
EndFunction