microworlds/graphics/graphics.go

90 lines
2.1 KiB
Go
Raw Normal View History

2019-08-03 02:00:33 +00:00
package graphics
import (
"fmt"
"git.openprivacy.ca/sarah/microworlds/core"
"github.com/veandco/go-sdl2/sdl"
"math"
"os"
2019-08-04 00:08:38 +00:00
//"strconv"
2019-08-03 02:00:33 +00:00
)
type Graphics struct {
2019-08-03 05:14:56 +00:00
window *sdl.Window
renderer *sdl.Renderer
2019-08-03 02:00:33 +00:00
width, height int32
2019-08-03 05:14:56 +00:00
t int
colorMap map[string][4]uint8
2019-08-03 02:00:33 +00:00
}
func NewGraphics(width, height int32) *Graphics {
graphics := new(Graphics)
graphics.width = width
2019-08-03 05:14:56 +00:00
graphics.height = height
2019-08-03 02:00:33 +00:00
window, err := sdl.CreateWindow("Microworlds", sdl.WINDOWPOS_UNDEFINED, sdl.WINDOWPOS_UNDEFINED,
width, height, sdl.WINDOW_SHOWN)
if err != nil {
panic(err)
}
graphics.window = window
2019-08-03 05:14:56 +00:00
surface, _ := window.GetSurface()
2019-08-03 02:00:33 +00:00
renderer, err := sdl.CreateSoftwareRenderer(surface)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to create renderer: %s\n", err)
panic(err)
}
graphics.colorMap = make(map[string][4]uint8)
2019-08-03 02:00:33 +00:00
graphics.renderer = renderer
return graphics
}
func (g *Graphics) ColorPheromone(name string, color [4]uint8) {
g.colorMap[name] = color
}
2019-08-03 05:14:56 +00:00
func (g *Graphics) Render(env *core.Environment, turtles []*core.Turtle) {
g.renderer.SetDrawColor(0x00, 0x00, 0x00, 0x00)
g.renderer.FillRect(&sdl.Rect{X: 0, Y: 0, W: 600, H: 600})
2019-08-03 02:00:33 +00:00
2019-08-03 05:14:56 +00:00
for x := 0; x < int(g.width); x++ {
for y := 0; y < int(g.height); y++ {
for name, color := range g.colorMap {
amount := math.Min(float64(env.Sniff(name, x, y)), 255)
2019-08-03 02:00:33 +00:00
if amount > 0 {
2019-08-04 00:08:38 +00:00
// TODO explictly define this scale
scaledamount := uint8(float64(color[0]) * (amount/2))
g.renderer.SetDrawColor(scaledamount,0,scaledamount, uint8(0xF0))
g.renderer.DrawPoint(int32(x), int32(y))
2019-08-03 02:00:33 +00:00
}
}
2019-08-03 05:14:56 +00:00
if env.HasValue(x, y) {
g.renderer.SetDrawColor(255, 255, 255, uint8(255))
2019-08-03 02:00:33 +00:00
g.renderer.DrawPoint(int32(x), int32(y))
}
}
}
2019-08-03 05:14:56 +00:00
g.renderer.SetDrawColor(0xF3, 0x81, 0, 0x00)
for _, t := range turtles {
x, y := t.Pos()
g.renderer.DrawPoint(int32(x), int32(y))
2019-08-03 02:00:33 +00:00
t.Run(env)
}
// TODO: Move this into an environment specification
for name := range g.colorMap {
env.Evaporate(0.95, name)
}
2019-08-03 02:00:33 +00:00
g.renderer.Present()
g.window.UpdateSurface()
2019-08-04 00:08:38 +00:00
// surface, _ := g.window.GetSurface()
// surface.SaveBMP("./images/" + strconv.Itoa(g.t) + ".bmp")
2019-08-03 05:14:56 +00:00
g.t++
}