microworlds/graphics/graphics.go

80 lines
1.7 KiB
Go

package graphics
import (
"fmt"
"git.openprivacy.ca/sarah/microworlds/core"
"github.com/veandco/go-sdl2/sdl"
"math"
"os"
"strconv"
)
type Graphics struct {
window *sdl.Window
renderer *sdl.Renderer
width, height int32
t int
}
func NewGraphics(width, height int32) *Graphics {
graphics := new(Graphics)
graphics.width = width
graphics.height= height
window, err := sdl.CreateWindow("Microworlds", sdl.WINDOWPOS_UNDEFINED, sdl.WINDOWPOS_UNDEFINED,
width, height, sdl.WINDOW_SHOWN)
if err != nil {
panic(err)
}
graphics.window = window
surface,_ := window.GetSurface()
renderer, err := sdl.CreateSoftwareRenderer(surface)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to create renderer: %s\n", err)
panic(err)
}
graphics.renderer = renderer
return graphics
}
func (g* Graphics) Render(env *core.Environment, turtles []*core.Turtle) {
g.renderer.SetDrawColor(0x00,0x00,0x00,0x00)
g.renderer.FillRect(&sdl.Rect{0,0,600,600})
for x:=0;x<int(g.width);x++ {
for y:=0;y<int(g.height);y++ {
amount := math.Min(float64(env.Sniff(x,y)), 255)
if amount > 0 {
col := uint8(amount*0x81)
if col > 0x81 {
col = 0x81
}
g.renderer.SetDrawColor(col,0,col, uint8(255) )
g.renderer.DrawPoint(int32(x), int32(y))
}
if env.HasValue(x,y) {
g.renderer.SetDrawColor(255,255,255, uint8(255) )
g.renderer.DrawPoint(int32(x), int32(y))
}
}
}
g.renderer.SetDrawColor(0xF3,0x81,0,0x00)
for _,t := range turtles {
x,y := t.Pos()
g.renderer.DrawPoint(int32(x),int32(y))
t.Run(env)
}
env.Evaporate(0.95)
g.renderer.Present()
g.window.UpdateSurface()
surface,_ := g.window.GetSurface()
surface.SaveBMP("./images/"+ strconv.Itoa(g.t)+".bmp")
g.t++;
}