; ReloadTexture Example
; ---------------------

Graphics3D 640,480,0,2
SetBuffer BackBuffer()

SeedRnd MilliSecs()

camera=CreateCamera()
PositionEntity camera,0,0,-4

light=CreateLight()
RotateEntity light,45,45,0

; Write the texture file this example will reload, then load it
PaintFile 30,70,160
crate=CreateCube()
texture=LoadTexture("reload_demo.bmp")
EntityTexture crate,texture

While Not KeyDown(1)

    ; Space repaints the file on disk - the crate does NOT change yet
    If KeyHit(57) Then PaintFile Rand(0,255),Rand(0,255),Rand(0,255)

    ; R decodes the file again and swaps it in atomically on success
    If KeyHit(19) Then ok=ReloadTexture(texture)

    TurnEntity crate,0.5,1,0

    ; Arrow keys move the camera
    If KeyDown(200) Then MoveEntity camera,0,0,0.1
    If KeyDown(208) Then MoveEntity camera,0,0,-0.1
    If KeyDown(203) Then TurnEntity camera,0,1,0
    If KeyDown(205) Then TurnEntity camera,0,-1,0

    RenderWorld

    Text 0,0,"Space: repaint file   R: ReloadTexture   Arrows: camera   Esc: exit"
    Text 0,20,"Repaint first, then press R to pull the new pixels into the scene"
    If ok Then Text 0,40,"Last ReloadTexture(texture) returned True"

    Flip

Wend

; Remove the file this example created
FreeTexture texture
DeleteFile "reload_demo.bmp"

End

; Draw a coloured pattern and save it as the reloadable file on disk
Function PaintFile(red,green,blue)
    scratch=CreateTexture(64,64)
    SetBuffer TextureBuffer(scratch)
    ClsColor red,green,blue
    Cls
    Color 255-red,255-green,255-blue
    Oval 12,12,40,40,True
    SetBuffer BackBuffer()
    Color 255,255,255
    SaveBuffer TextureBuffer(scratch),"reload_demo.bmp"
    FreeTexture scratch
End Function
