Factored YOrder out of Renderer as it is only an optimization and not directly related to the rendering.

This commit is contained in:
Sascha L. Teichmann
2017-03-01 15:05:51 +01:00
parent 75aeb36c95
commit 956f7b5e8b
3 changed files with 122 additions and 93 deletions

View File

@ -5,7 +5,6 @@
package common
import (
"container/heap"
"image"
"image/color"
"image/draw"
@ -27,92 +26,6 @@ type Renderer struct {
tBuffer []*Span
}
type YOrder struct {
Renderer *Renderer
blocks []*Block
capacity int
}
func NewYOrder(renderer *Renderer, capacity int) *YOrder {
return &YOrder{
Renderer: renderer,
blocks: make([]*Block, 0, capacity),
capacity: capacity}
}
func (yo *YOrder) Reset() {
yo.blocks = yo.blocks[:0]
}
func copyData(data []byte) []byte {
l := len(data)
ndata := make([]byte, l, Max(l, 8*1024))
copy(ndata, data)
return ndata
}
func (yo *YOrder) RenderBlock(block *Block, colors *Colors) (err error) {
var nblock *Block
if len(yo.blocks) == yo.capacity {
oblock := yo.blocks[0]
if oblock.Coord.Y < block.Coord.Y {
// New one is above highest old. Directly render new.
err = yo.Renderer.RenderBlock(block, colors)
return
}
// Render old one. Store copy of new in heap.
heap.Pop(yo)
err = yo.Renderer.RenderBlock(oblock, colors)
l := len(block.Data)
if cap(oblock.Data) < l {
oblock.Data = make([]byte, l, Max(l, 8*1024))
} else {
oblock.Data = oblock.Data[:l]
}
copy(oblock.Data, block.Data)
oblock.Coord = block.Coord
nblock = oblock
} else {
nblock = &Block{Coord: block.Coord, Data: copyData(block.Data)}
}
heap.Push(yo, nblock)
return
}
func (yo *YOrder) Drain(colors *Colors) (err error) {
for len(yo.blocks) > 0 {
if err = yo.Renderer.RenderBlock(heap.Pop(yo).(*Block), colors); err != nil {
return
}
}
return
}
func (yo *YOrder) Len() int {
return len(yo.blocks)
}
func (yo *YOrder) Swap(i, j int) {
yo.blocks[i], yo.blocks[j] = yo.blocks[j], yo.blocks[i]
}
func (yo *YOrder) Less(i, j int) bool {
// Reverse order intented.
return yo.blocks[i].Coord.Y > yo.blocks[j].Coord.Y
}
func (yo *YOrder) Push(x interface{}) {
yo.blocks = append(yo.blocks, x.(*Block))
}
func (yo *YOrder) Pop() (x interface{}) {
l := len(yo.blocks)
x = yo.blocks[l-1]
yo.blocks = yo.blocks[0 : l-1]
return x
}
func NewRenderer(width, height int, transparent bool) (renderer *Renderer) {
dim := width * height
pixSize := dim * 16 * 16