diff --git a/tinyrender1/image.go b/tinyrender1/image.go index c2d2bdf..675df86 100644 --- a/tinyrender1/image.go +++ b/tinyrender1/image.go @@ -31,6 +31,11 @@ func NewFramebuffer(width uint, height uint) Framebuffer { } } +// Sure hope this gets inlined... +func (fb *Framebuffer) Set(x uint, y uint, color uint) { + fb.Data[x+y*fb.Width] = color +} + // Given some image data, return a string that is the ppm of it func (fb *Framebuffer) ExportPPM() string { var result strings.Builder diff --git a/tinyrender1/main.go b/tinyrender1/main.go index 142a7ec..d042517 100644 --- a/tinyrender1/main.go +++ b/tinyrender1/main.go @@ -1,8 +1,11 @@ package main import ( + "flag" "fmt" "log" + "os" + "runtime/pprof" // For performance whatever ) const ( @@ -10,9 +13,41 @@ const ( Height = 512 ) +func must(err error) { + if err != nil { + panic(err) + } +} + +// However flag works... idk +var cpuprofile = flag.String("cpuprofile", "", "write cpu profile to file") + func main() { log.Printf("Program start") + + // Little section for doing cpu profiling. I guess that's all you have to do? + flag.Parse() + if *cpuprofile != "" { + log.Printf("CPU profiling requested, write to %s", *cpuprofile) + f, err := os.Create(*cpuprofile) + must(err) + defer f.Close() + err = pprof.StartCPUProfile(f) + must(err) + defer pprof.StopCPUProfile() + } + fb := NewFramebuffer(Width, Height) + + log.Printf("Running render") + + // Just draw a simple line + LineDumb(&fb, 0xFFFFFF, 100, 100, 350, 200) + LineDumb2(&fb, 0xFF0000, 120, 100, 200, 350) + LineDumb2(&fb, 0xFF0000, 350, 200, 100, 100) // backward first line + + log.Printf("Exporting ppm to stdout") fmt.Print(fb.ExportPPM()) + log.Printf("Program end") } diff --git a/tinyrender1/render.go b/tinyrender1/render.go new file mode 100644 index 0000000..9111bd5 --- /dev/null +++ b/tinyrender1/render.go @@ -0,0 +1,21 @@ +package main + +// Draw a line using dumb +func LineDumb(fb *Framebuffer, color uint, x0 uint, y0 uint, x1 uint, y1 uint) { + var t float32 + for t = 0; t < 1; t += 0.01 { + // Very simple interpolation between x and y + x := x0 + uint(float32(x1-x0)*t) + y := y0 + uint(float32(y1-y0)*t) + fb.Set(x, y, color) + } +} + +func LineDumb2(fb *Framebuffer, color uint, x0 uint, y0 uint, x1 uint, y1 uint) { + for x := x0; x < x1; x++ { + // For each pixel across, compute how far across we are and interpolate y + t := float32(x-x0) / float32(x1-x0) + y := uint(float32(y0)*(1-t) + float32(y1)*t) + fb.Set(x, y, color) + } +} diff --git a/tinyrender1/run.sh b/tinyrender1/run.sh new file mode 100755 index 0000000..657f5a2 --- /dev/null +++ b/tinyrender1/run.sh @@ -0,0 +1,3 @@ +#!/bin/sh + +go build && ./tinyrender1 >image.ppm