doodle/level/chunk.go
Noah Petherbridge 279a980106 WIP Texture Caching
NOTICE: Chunk size set to 100 for visual testing!
NOTICE: guitest references a bmp file that isn't checked in!

BUGS REMAINING:
- When scrolling the level in Edit Mode, some of the chunks will pop
  out of existence randomly.
- When clicking-dragging to draw in Edit Mode, if the scroll position
  is not at 0,0 then the pixels drawn will be offset from the cursor.
- These are to do with the Scroll position and chunk coordinate calc
  functions probably.

Implements a texture caching interface to stop redrawing everything
pixel by pixel on every frame.

The texture caching workflow is briefly:

- The uix.Canvas widget's Present() function iterates over the list of
  Chunk Coordinates that are visible inside of the current viewport
  (i.e. viewable on screen)
- For each Chunk:
  - Make it render and/or return its cached Texture object.
  - Work out how much of the Chunk will be visible and how to crop the
    boxes for the Copy()
  - Copy the cached Texture instead of drawing all the pixels every
    time like we were doing before.
- The Chunk.Texture() function that returns said Texture:
  - It calls Chunk.ToBitmap() to save a bitmap on disk.
  - It calls Engine.NewBitmap() to get a Texture it can hang onto.
  - It hangs onto the Texture and returns it on future calls.
  - Any call to Set() or Delete() a pixel will invalidate the cache
    (mark the Chunk "dirty") and Texture() will rebuild next call.

The interface `render.Texturer` provides a way for rendering backends
(SDL2, OpenGL) to transport a "texture" of their own kind without
exposing the type details to the user.

The interface `render.Engine` adds two new methods:

* NewBitmap(filename string) (Texturer, error)
* Copy(t Texturer, src, dst Rect)

NewBitmap should open a bitmap image on disk and return it wrapped in a
Texturer (really it's an SDL2 Texture). This is for caching purposes.
Next the Copy() function blits the texture onto the screen renderer
using the source and destination rectangles.

The uix.Canvas widget orchestrates the caching for the drawing it's
responsible for. It queries which chunks are viewable in the Canvas
viewport (scroll and bounding boxes), has each chunk render out their
entire bitmap image to then cache them as SDL textures and then only
_those_ need to be copied out to the renderer each frame.

The frame rate now sits at a decent 60 FPS even when the drawing gets
messy and full of lines. Each unique version of each chunk needs to
render only one time and then it's a fast copy operation for future
ticks.

Other changes:

- Chunker now assigns each Chunk what their coordinate and size are, so
  that the chunk can self reference that information. This info is
  considered read-only but that isn't really enforced.
- Add Chunker.IterViewportChunks() that returns a channel of Chunk
  Coordinates that are visible in your viewport, rather than iterating
  over all of the pixels in all of those chunks.
- Add Chunk.ToBitmap(filename) that causes a Chunk to render its pixels
  to a bitmap image on disk. SDL2 can natively speak Bitmaps for texture
  caching. Currently these go to files in /tmp but will soon go into your
  $XDG_CACHE_FOLDER instead.
- Add Chunk.Texture() that causes a Chunk to render and then return a
  cached bitmap texture of the pixels it's responsible for. The texture
  is cached until the Chunk is next modified with Set() or Delete().
- UI: add an Image widget that currently just shows a bitmap image. It
  was the first test for caching bitmap images for efficiency. Can show
  any *.bmp file on disk!
- Editor UI: make the StatusBar boxes dynamically build from an array
  of string pointers to make it SUPER EASY to add/remove labels.
2018-10-17 20:52:44 -07:00

230 lines
5.1 KiB
Go

package level
import (
"encoding/json"
"fmt"
"image"
"math"
"os"
"git.kirsle.net/apps/doodle/render"
"golang.org/x/image/bmp"
)
// Types of chunks.
const (
MapType int = iota
GridType
)
// Chunk holds a single portion of the pixel canvas.
type Chunk struct {
Type int // map vs. 2D array.
Accessor
// Values told to it from higher up, not stored in JSON.
Point render.Point
Size int
// Texture cache properties so we don't redraw pixel-by-pixel every frame.
texture render.Texturer
dirty bool
}
// JSONChunk holds a lightweight (interface-free) copy of the Chunk for
// unmarshalling JSON files from disk.
type JSONChunk struct {
Type int `json:"type"`
Data json.RawMessage `json:"data"`
}
// Accessor provides a high-level API to interact with absolute pixel coordinates
// while abstracting away the details of how they're stored.
type Accessor interface {
Inflate(*Palette) error
Iter() <-chan Pixel
IterViewport(viewport render.Rect) <-chan Pixel
Get(render.Point) (*Swatch, error)
Set(render.Point, *Swatch) error
Delete(render.Point) error
Len() int
MarshalJSON() ([]byte, error)
UnmarshalJSON([]byte) error
}
// NewChunk creates a new chunk.
func NewChunk() *Chunk {
return &Chunk{
Type: MapType,
Accessor: NewMapAccessor(),
}
}
// Texture will return a cached texture for the rendering engine for this
// chunk's pixel data. If the cache is dirty it will be rebuilt in this func.
func (c *Chunk) Texture(e render.Engine, name string) render.Texturer {
if c.texture == nil || c.dirty {
err := c.ToBitmap("/tmp/" + name + ".bmp")
if err != nil {
log.Error("Texture: %s", err)
}
tex, err := e.NewBitmap("/tmp/" + name + ".bmp")
if err != nil {
log.Error("Texture: %s", err)
}
c.texture = tex
c.dirty = false
}
return c.texture
}
// ToBitmap exports the chunk's pixels as a bitmap image.
func (c *Chunk) ToBitmap(filename string) error {
canvas := c.SizePositive()
imgSize := image.Rectangle{
Min: image.Point{},
Max: image.Point{
X: c.Size,
Y: c.Size,
},
}
if imgSize.Max.X == 0 {
imgSize.Max.X = int(canvas.W)
}
if imgSize.Max.Y == 0 {
imgSize.Max.Y = int(canvas.H)
}
img := image.NewRGBA(imgSize)
// Blank out the pixels.
for x := 0; x < img.Bounds().Max.X; x++ {
for y := 0; y < img.Bounds().Max.Y; y++ {
img.Set(x, y, render.RGBA(255, 255, 0, 153).ToColor())
}
}
// Pixel coordinate offset to map the Chunk World Position to the
// smaller image boundaries.
pointOffset := render.Point{
X: int32(math.Abs(float64(c.Point.X * int32(c.Size)))),
Y: int32(math.Abs(float64(c.Point.Y * int32(c.Size)))),
}
// Blot all the pixels onto it.
for px := range c.Iter() {
img.Set(
int(px.X-pointOffset.X),
int(px.Y-pointOffset.Y),
px.Swatch.Color.ToColor(),
)
}
fh, err := os.Create(filename)
if err != nil {
return err
}
defer fh.Close()
return bmp.Encode(fh, img)
}
// Set proxies to the accessor and flags the texture as dirty.
func (c *Chunk) Set(p render.Point, sw *Swatch) error {
c.dirty = true
return c.Accessor.Set(p, sw)
}
// Delete proxies to the accessor and flags the texture as dirty.
func (c *Chunk) Delete(p render.Point) error {
c.dirty = true
return c.Accessor.Delete(p)
}
// Rect returns the bounding coordinates that the Chunk has pixels for.
func (c *Chunk) Rect() render.Rect {
// Lowest and highest chunks.
var (
lowest render.Point
highest render.Point
)
for coord := range c.Iter() {
if coord.X < lowest.X {
lowest.X = coord.X
}
if coord.Y < lowest.Y {
lowest.Y = coord.Y
}
if coord.X > highest.X {
highest.X = coord.X
}
if coord.Y > highest.Y {
highest.Y = coord.Y
}
}
return render.Rect{
X: lowest.X,
Y: lowest.Y,
W: highest.X,
H: highest.Y,
}
}
// SizePositive returns the Size anchored to 0,0 with only positive
// coordinates.
func (c *Chunk) SizePositive() render.Rect {
S := c.Rect()
return render.Rect{
X: c.Point.X * int32(c.Size),
Y: c.Point.Y * int32(c.Size),
W: int32(math.Abs(float64(S.X))) + S.W,
H: int32(math.Abs(float64(S.Y))) + S.H,
}
}
// Usage returns the percent of free space vs. allocated pixels in the chunk.
func (c *Chunk) Usage(size int) float64 {
return float64(c.Len()) / float64(size)
}
// MarshalJSON writes the chunk to JSON.
func (c *Chunk) MarshalJSON() ([]byte, error) {
data, err := c.Accessor.MarshalJSON()
if err != nil {
return []byte{}, err
}
generic := &JSONChunk{
Type: c.Type,
Data: data,
}
b, err := json.Marshal(generic)
return b, err
}
// UnmarshalJSON loads the chunk from JSON and uses the correct accessor to
// parse the inner details.
func (c *Chunk) UnmarshalJSON(b []byte) error {
// Parse it generically so we can hand off the inner "data" object to the
// right accessor for unmarshalling.
generic := &JSONChunk{}
err := json.Unmarshal(b, generic)
if err != nil {
return fmt.Errorf("Chunk.UnmarshalJSON: failed to unmarshal into generic JSONChunk type: %s", err)
}
switch c.Type {
case MapType:
c.Accessor = NewMapAccessor()
return c.Accessor.UnmarshalJSON(generic.Data)
default:
return fmt.Errorf("Chunk.UnmarshalJSON: unsupported chunk type '%d'", c.Type)
}
}