72 lines
1.7 KiB
Go
72 lines
1.7 KiB
Go
|
package graphics
|
||
|
|
||
|
import (
|
||
|
"bytes"
|
||
|
"fmt"
|
||
|
"git.openprivacy.ca/sarah/microworlds/core"
|
||
|
"github.com/veandco/go-sdl2/sdl"
|
||
|
"github.com/wcharczuk/go-chart"
|
||
|
"image"
|
||
|
"log"
|
||
|
"os"
|
||
|
)
|
||
|
|
||
|
type Plot struct {
|
||
|
Graphics
|
||
|
GeneratePlot func(*core.Environment, []*core.Turtle) *chart.Chart
|
||
|
}
|
||
|
|
||
|
func NewPlot(title string, width, height, pxsize int32) *Plot {
|
||
|
graphics := new(Plot)
|
||
|
graphics.width = width
|
||
|
graphics.height = height
|
||
|
window, err := sdl.CreateWindow(title, sdl.WINDOWPOS_UNDEFINED, sdl.WINDOWPOS_UNDEFINED,
|
||
|
width, height, sdl.WINDOW_SHOWN|sdl.WINDOW_RESIZABLE)
|
||
|
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.colorMap = make(map[string][4]uint8)
|
||
|
graphics.renderer = renderer
|
||
|
return graphics
|
||
|
}
|
||
|
|
||
|
func (p *Plot) Render(env *core.Environment, turtles []*core.Turtle) {
|
||
|
graph := p.GeneratePlot(env, turtles)
|
||
|
|
||
|
// graph.Elements = []chart.Renderable{chart.Legend(graph)}
|
||
|
w, h := p.window.GetSize()
|
||
|
surface, _ := p.window.GetSurface()
|
||
|
renderer, _ := sdl.CreateSoftwareRenderer(surface)
|
||
|
p.renderer = renderer
|
||
|
graph.Width = int(w)
|
||
|
graph.Height = int(h)
|
||
|
if env.Step > 2 {
|
||
|
buffer := bytes.NewBuffer([]byte{})
|
||
|
err := graph.Render(chart.PNG, buffer)
|
||
|
if err != nil {
|
||
|
log.Fatal(err)
|
||
|
}
|
||
|
|
||
|
graph, _, _ := image.Decode(buffer)
|
||
|
|
||
|
for x := 0; x < int(w); x++ {
|
||
|
for y := 0; y < int(h); y++ {
|
||
|
col := graph.At(x, y)
|
||
|
r, g, b, a := col.RGBA()
|
||
|
p.renderer.SetDrawColor(uint8(r), uint8(g), uint8(b), uint8(a))
|
||
|
p.renderer.DrawPoint(int32(x), int32(y))
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
p.window.UpdateSurface()
|
||
|
}
|