tinyrender5

This commit is contained in:
Carlos Sanchez 2024-07-29 22:25:23 -04:00
parent 7b86311ff2
commit 78e254cbd5
14 changed files with 7311 additions and 1 deletions

BIN
head.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 202 KiB

View File

@ -19,7 +19,7 @@ const (
NearClip = 0.1 NearClip = 0.1
FarClip = 5 // Because the head is so small and close FarClip = 5 // Because the head is so small and close
ObjectFile = "head.obj" ObjectFile = "head.obj"
TextureFile = "head.jpg" TextureFile = "../head.jpg"
) )
func must(err error) { func must(err error) {

3
tinyrender5/.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
tinyrender1
tinyrender4
render

24
tinyrender5/animation.sh Executable file
View File

@ -0,0 +1,24 @@
#!/bin/sh
if [ $# -ne 1 ]; then
echo "You must pass the basename for the animation folder"
exit 1
fi
echo "Building"
go build -o render
mkdir -p $1
echo "Running"
frame=0
for x in $(seq -3 0.1 3); do
ff=$(printf "%03d" $frame)
./render "-repeat=1" "-xofs=$x" "-zofs=-1.8" "-fov=70" "-p6file=$1/$ff.ppm"
frame=$((frame + 1))
done
echo "Converting animation"
cd $1
convert -delay 5 -loop 0 *.ppm -resize 256x256 anim.gif

3
tinyrender5/go.mod Normal file
View File

@ -0,0 +1,3 @@
module tinyrender4
go 1.22.5

0
tinyrender5/go.sum Normal file
View File

6357
tinyrender5/head.obj Normal file

File diff suppressed because it is too large Load Diff

143
tinyrender5/image.go Normal file
View File

@ -0,0 +1,143 @@
package main
import (
"bytes"
"fmt"
"image"
"image/color"
"log"
//"math"
"strings"
)
// Convert rgb to uint
func Col2Uint(r, g, b byte) uint {
return (uint(r) << 16) | (uint(g) << 8) | uint(b)
}
func Color2Uint(col color.Color) uint {
r, g, b, _ := col.RGBA()
//log.Print(r, g, b)
return uint(((r & 0xff00) << 8) | (g & 0xff00) | ((b & 0xff00) >> 8))
}
// Convert uint to rgb (in that order)
func Uint2Col(col uint) (byte, byte, byte) {
return byte((col >> 16) & 0xFF), byte((col >> 8) & 0xFF), byte(col & 0xFF)
}
// Color is in ARGB (alpha not used right now)
type Framebuffer struct {
Data []uint
ZBuffer []uint16 //[]float32 //uint16 // Apparently 16 bit z-buffers are used
Width uint
Height uint
}
// Create a new framebuffer for the given width and height.
func NewFramebuffer(width uint, height uint) Framebuffer {
return Framebuffer{
Data: make([]uint, width*height),
ZBuffer: make([]uint16, width*height),
Width: width,
Height: height,
}
}
func NewTexture(texture image.Image, skip int) Framebuffer {
bounds := texture.Bounds()
width := bounds.Dx() / skip
height := bounds.Dy() / skip
result := Framebuffer{
Data: make([]uint, width*height),
Width: uint(width),
Height: uint(height),
}
for y := bounds.Min.Y; y < bounds.Max.Y; y += skip {
for x := bounds.Min.X; x < bounds.Max.X; x += skip {
col := texture.At(x, y)
result.Set(uint(x/skip), uint(y/skip), Color2Uint(col))
}
}
return result
}
// Fill zbuffer with pixels that are max distance away
func (fb *Framebuffer) ResetZBuffer() {
for i := range fb.ZBuffer {
fb.ZBuffer[i] = 65535 //math.MaxFloat32
}
}
func (fb *Framebuffer) GetUv(u float32, v float32) uint {
// log.Print(u, v)
x := uint(float32(fb.Width) * u)
y := uint(float32(fb.Height) * (1 - v))
return fb.Data[x+y*fb.Width]
}
// Sure hope this gets inlined...
func (fb *Framebuffer) Set(x uint, y uint, color uint) {
fb.Data[x+y*fb.Width] = color
}
func (fb *Framebuffer) SetSafe(x uint, y uint, color uint) {
if x >= fb.Width || y >= fb.Height {
return
}
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 {
log.Printf("ExportPPM called for framebuffer %dx%d", fb.Width, fb.Height)
var result strings.Builder
result.WriteString(fmt.Sprintf("P3\n%d %d\n255\n", fb.Width, fb.Height))
for y := range fb.Height {
for x := range fb.Width {
r, g, b := Uint2Col(fb.Data[x+y*fb.Width])
result.WriteString(fmt.Sprintf("%d %d %d\t", r, g, b))
}
result.WriteRune('\n')
}
return result.String()
}
func (fb *Framebuffer) ExportPPMP6() []byte {
log.Printf("ExportPPM6 called for framebuffer %dx%d", fb.Width, fb.Height)
var result bytes.Buffer
result.WriteString(fmt.Sprintf("P6\n%d %d\n255\n", fb.Width, fb.Height))
for i := range fb.Data {
r, g, b := Uint2Col(fb.Data[i])
result.Write([]byte{r, g, b})
//result.WriteString(fmt.Sprintf("%d %d %d\t", r, g, b))
}
//result.WriteRune('\n')
return result.Bytes()
}
/*func (fb *Framebuffer) ZBuffer_ExportPPM() string {
var result strings.Builder
mini := float32(math.MaxFloat32)
maxi := float32(-math.MaxFloat32)
for _, f := range fb.ZBuffer {
if f == math.MaxFloat32 {
continue
}
mini = min(f, mini)
maxi = max(f, maxi)
}
result.WriteString(fmt.Sprintf("P2\n%d %d\n255\n", fb.Width, fb.Height))
for y := range fb.Height {
for x := range fb.Width {
if fb.ZBuffer[x+y*fb.Width] == math.MaxFloat32 {
result.WriteString("0 ")
} else {
zp := byte(math.Abs(float64(255 * fb.ZBuffer[x+y*fb.Width] / (maxi - mini))))
result.WriteString(fmt.Sprintf("%d ", zp))
}
}
result.WriteRune('\n')
}
return result.String()
}*/

138
tinyrender5/main.go Normal file
View File

@ -0,0 +1,138 @@
package main
import (
"flag"
"fmt"
"image"
"log"
//"math"
//"math/rand"
"os"
"runtime/pprof" // For performance profiling (unnecessary)
_ "image/jpeg"
)
const (
Width = 512
Height = 512
NearClip = 0.1
FarClip = 100
ObjectFile = "head.obj"
TextureFile = "../head.jpg"
)
func must(err error) {
if err != nil {
panic(err)
}
}
// However flag works... idk
var cpuprofile = flag.String("cpuprofile", "", "write cpu profile to file")
var dozbuf = flag.Bool("zbuffer", false, "Write zbuffer instead of image")
var p6file = flag.String("p6file", "", "Output binary ppm to given file instead")
var fov = flag.Float64("fov", 90, "Horizontal FOV in degrees")
var xofs = flag.Float64("xofs", 0, "Offset image by x")
var zofs = flag.Float64("zofs", -1.5, "Offset image by z (should be negative)")
var repeat = flag.Int("repeat", 60, "Amount of times to repeat render")
// var zcuthigh = flag.Float64("zcuthigh", math.MaxFloat32, "High cutoff for z (values above this will be removed)")
// var zcutlow = flag.Float64("zcutlow", -math.MaxFloat32, "Low cutoff for z (values below are removed)")
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("Loading obj %s, texture %s", ObjectFile, TextureFile)
of, err := os.Open(ObjectFile)
must(err)
defer of.Close()
o, err := ParseObj(of)
must(err)
jf, err := os.Open(TextureFile)
must(err)
defer jf.Close()
timg, _, err := image.Decode(jf)
must(err)
texture := NewTexture(timg, 4)
log.Printf("Running render")
light := Vec3f{0, 0, -1}
var projection Mat44f
var worldToCamera Mat44f
var viewport Mat44f
projection.SetProjection(float32(*fov), NearClip, FarClip)
worldToCamera.SetTranslation(float32(*xofs), 0, float32(*zofs))
viewport.SetViewportSimple(int(fb.Width), int(fb.Height), 65535)
// Premultiply all the translation/etc matrices. Why do we do world to camera THEN
// projection? I guess that makes sense actually, oops... projection is the last step.
screenmat := worldToCamera.Multiply(&projection)
screenmat = screenmat.Multiply(&viewport)
// light = worldToCamera.MultiplyPoint3(light)
// light = light.Normalize()
var sc [3]Vertex
// var hi = float32(fb.Height - 1)
for range *repeat {
fb.ResetZBuffer()
for _, f := range o.Faces {
// Precompute perspective for vertices to save time. Notice Z
// is not considered: is this orthographic projection? Yeah probably...
var fpt [3]Vec3f
for i := range 3 { // Triangles, bro
//fp := screenmat.MultiplyPoint3(f[i].Pos)
sc[i] = f[i]
sc[i].Pos = screenmat.MultiplyPoint3(f[i].Pos)
fpt[i] = worldToCamera.MultiplyPoint3(f[i].Pos)
// sc[i].Pos.X = (fp.X + 1) * halfwidth
// sc[i].Pos.Y = hi - (fp.Y+1)*halfheight
// sc[i].Pos.Z = fp.Z
}
l1 := fpt[2].Sub(fpt[0])
n := l1.CrossProduct(fpt[1].Sub(fpt[0]))
n = n.Normalize()
intensity := n.MultSimp(&light)
// intensity := float32(1)
if intensity > 0 {
Triangle3t(&fb, &texture, intensity, sc[0], sc[1], sc[2])
}
}
}
// log.Print(fb.ZBuffer)
if *dozbuf {
log.Printf("Exporting zbuffer ppm to stdout")
//fmt.Print(fb.ZBuffer_ExportPPM())
} else {
if *p6file != "" {
err := os.WriteFile(*p6file, fb.ExportPPMP6(), 0660)
must(err)
} else {
log.Printf("Exporting ppm to stdout")
fmt.Print(fb.ExportPPM())
}
}
log.Printf("Program end")
}

260
tinyrender5/obj.go Normal file
View File

@ -0,0 +1,260 @@
package main
// This reads obj files?
import (
"bufio"
"fmt"
"io"
"log"
"math"
"strings"
)
type Vec3f struct {
X, Y, Z float32
}
type Vec2i struct {
X, Y int
}
type Vec2f struct {
X, Y float32
}
// A ROW MAJOR matrix
type Mat44f [16]float32
func (m *Mat44f) Set(x int, y int, val float32) {
m[x+y*4] = val
}
func (m *Mat44f) Get(x int, y int) float32 {
return m[x+y*4]
}
func (m *Mat44f) ZeroFill() {
for i := range m {
m[i] = 0
}
}
func (m *Mat44f) SetIdentity() {
m.ZeroFill()
for i := range 4 {
m.Set(i, i, 1)
}
}
// NOTE: we use "Set" instead of "Create" for all these so we reuse the matrix
// instead of creating a new one all the time (garbage collection)
// Compute the projection matrix, filling the given matrix. FOV is in degrees
func (m *Mat44f) SetProjection(fov float32, near float32, far float32) {
// Projection matrix is (ROW MAJOR!)
// S 0 0 0
// 0 S 0 0
// 0 0 -f/(f-n) -1
// 0 0 -fn/(f-n) 0
// where S (scale) is 1 / tan(fov / 2) (assuming fov is radians)
// NOTE: -1 there is actually -1/c, where c is distance from viewer to
// projection plane. We fix it at 1 for now but...
m.ZeroFill()
scale := float32(1 / math.Tan(float64(fov)*0.5*math.Pi/180))
m.Set(0, 0, scale)
m.Set(1, 1, scale)
m.Set(2, 2, -far/(far-near))
m.Set(3, 2, -1)
m.Set(2, 3, -far*near/(far-near))
}
func (m *Mat44f) SetTranslation(x, y, z float32) {
m.SetIdentity()
m.Set(0, 3, x) // Let user decide how to offset x
m.Set(1, 3, y) // Let user decide how to offset x
m.Set(2, 3, z) // Get farther away from the face (user)
}
func (m *Mat44f) SetViewport(tl Vec3f, br Vec3f) { //width, height, depth int) {
m.ZeroFill()
m.Set(0, 0, (br.X-tl.X)/2)
m.Set(1, 1, (tl.Y-br.Y)/2) // Inverted because screen funny
m.Set(2, 2, (br.Z-tl.Z)/2)
m.Set(3, 3, 1)
m.Set(0, 3, (br.X+tl.X)/2)
m.Set(1, 3, (br.Y+tl.Y)/2)
m.Set(2, 3, (br.Z+tl.Z)/2)
}
func (m *Mat44f) SetViewportSimple(width, height, depth int) {
var tl Vec3f // All zero
br := Vec3f{
X: float32(width),
Y: float32(height),
Z: float32(depth),
}
m.SetViewport(tl, br)
}
// Multiply the given point by our vector. Remember this is row-major order
func (m *Mat44f) MultiplyPoint3(p Vec3f) Vec3f {
var out Vec3f
// We hope very much that Go will optimize the function calls for us,
// along with computing the constants.
out.X = p.X*m.Get(0, 0) + p.Y*m.Get(0, 1) + p.Z*m.Get(0, 2) + m.Get(0, 3)
out.Y = p.X*m.Get(1, 0) + p.Y*m.Get(1, 1) + p.Z*m.Get(1, 2) + m.Get(1, 3)
out.Z = p.X*m.Get(2, 0) + p.Y*m.Get(2, 1) + p.Z*m.Get(2, 2) + m.Get(2, 3)
w := p.X*m.Get(3, 0) + p.Y*m.Get(3, 1) + p.Z*m.Get(3, 2) + m.Get(3, 3)
if w != 1 {
out.X /= w
out.Y /= w
out.Z /= w
}
return out
}
// Multiply two 4x4 matrices together (not optimized)
func (m *Mat44f) Multiply(m2 *Mat44f) Mat44f {
var result Mat44f
// This is the x and y of our resulting matrix
for y := 0; y < 4; y++ {
for x := 0; x < 4; x++ {
for i := 0; i < 4; i++ {
result[x+y*4] += m[i+y*4] * m2[x+i*4]
}
}
}
return result
}
// A single vertex generally has multiple items associated with it
// when it's part of a face.
type Vertex struct {
Pos Vec3f
Tex Vec3f
}
type Facef [3]Vertex
// struct {
// Vertices [3]Vec3f
// TextureCoords [3]Vec2i
// }
type ObjModel struct {
Vertices []Vec3f
VTexture []Vec3f
Faces []Facef
}
func (vi *Vec2i) ToF() Vec2f {
return Vec2f{float32(vi.X), float32(vi.Y)}
}
func (vi *Vec3f) ToVec2i() Vec2i {
return Vec2i{int(vi.X), int(vi.Y)}
}
func (v0 *Vec3f) Sub(v1 Vec3f) Vec3f {
return Vec3f{
X: v0.X - v1.X,
Y: v0.Y - v1.Y,
Z: v0.Z - v1.Z,
}
}
func (v0 *Vec3f) CrossProduct(v1 Vec3f) Vec3f {
return Vec3f{
X: v0.Y*v1.Z - v0.Z*v1.Y,
Y: v0.Z*v1.X - v0.X*v1.Z,
Z: v0.X*v1.Y - v0.Y*v1.X,
}
}
//func (v
func (v *Vec3f) Normalize() Vec3f {
l := float32(math.Sqrt(float64(v.MultSimp(v))))
return Vec3f{
X: v.X / l,
Y: v.Y / l,
Z: v.Z / l,
}
}
func (v0 *Vec3f) MultSimp(v1 *Vec3f) float32 {
return v0.X*v1.X + v0.Y*v1.Y + v0.Z*v1.Z
}
// Parse an obj file at the given reader. Only handles v and f right now
func ParseObj(reader io.Reader) (*ObjModel, error) {
result := ObjModel{
Vertices: make([]Vec3f, 0),
Faces: make([]Facef, 0),
}
breader := bufio.NewReader(reader)
done := false
for !done {
// Scan a line
line, err := breader.ReadString('\n')
if err != nil {
if err == io.EOF {
done = true
} else {
log.Printf("NOT EOF ERR?")
return nil, err
}
}
line = strings.Trim(line, " \t\n\r")
if len(line) == 0 {
continue
}
// Find the first "item", whatever that is. This also gets rid of comments
// since we just don't use lines that start with # (no handler
var t string
_, err = fmt.Sscan(line, &t)
if err != nil {
log.Printf("SSCANF ERR")
return nil, err
}
line = line[len(t):]
if t == "v" {
// Read a vertex, should be just three floats
var v Vec3f
_, err := fmt.Sscan(line, &v.X, &v.Y, &v.Z)
if err != nil {
return nil, err
}
result.Vertices = append(result.Vertices, v)
} else if t == "vt" {
// Read a vertex tex coord, should be just three floats too
var vt Vec3f
_, err := fmt.Sscan(line, &vt.X, &vt.Y, &vt.Z)
if err != nil {
return nil, err
}
result.VTexture = append(result.VTexture, vt)
} else if t == "f" {
// Read a face; in our example, it's always three sets.
// For THIS example, we throw away those other values
var face Facef
var vi [3]int
var vti [3]int
var ti int
_, err := fmt.Sscanf(line, "%d/%d/%d %d/%d/%d %d/%d/%d",
&vi[0], &vti[0], &ti, &vi[1], &vti[1], &ti, &vi[2], &vti[2], &ti)
if err != nil {
return nil, err
}
for i := range 3 {
if vi[i] > len(result.Vertices) || vi[i] < 1 {
return nil, fmt.Errorf("Face vertex index out of bounds: %d", vi[i])
}
face[i].Pos = result.Vertices[vi[i]-1]
if vti[i] > len(result.VTexture) || vti[i] < 1 {
return nil, fmt.Errorf("Face vertex texture index out of bounds: %d", vti[i])
}
face[i].Tex = result.VTexture[vti[i]-1]
}
result.Faces = append(result.Faces, face)
}
}
return &result, nil
}

169
tinyrender5/render.go Normal file
View File

@ -0,0 +1,169 @@
package main
import (
// "log"
)
// Figure out the minimum bounding box for a triangle defined by
// these vertices. Returns the top left and bottom right points,
// inclusive
func ComputeBoundingBox(v0, v1, v2 Vec2i) (Vec2i, Vec2i) {
return Vec2i{min(v0.X, v1.X, v2.X), min(v0.Y, v1.Y, v2.Y)},
Vec2i{max(v0.X, v1.X, v2.X), max(v0.Y, v1.Y, v2.Y)}
}
// The generic edge function, returning positive if P is on the right side of
// the line drawn between v1 and v2. This is counter clockwise
func EdgeFunction(v1, v2, p Vec2f) float32 {
return (p.X-v1.X)*(v2.Y-v1.Y) - (p.Y-v1.Y)*(v2.X-v1.X)
}
// This computes the x and y per-pixel increment for the line going
// between v1 and v2 (also counter clockwise)
func EdgeIncrement(v1, v2 Vec2f) (float32, float32) {
return (v2.Y - v1.Y), -(v2.X - v1.X)
}
// The generic edge function, returning positive if P is on the right side of
// the line drawn between v1 and v2. This is counter clockwise
func EdgeFunctioni(v1, v2, p Vec2i) int {
return (p.X-v1.X)*(v2.Y-v1.Y) - (p.Y-v1.Y)*(v2.X-v1.X)
}
// This computes the x and y per-pixel increment for the line going
// between v1 and v2 (also counter clockwise)
func EdgeIncrementi(v1, v2 Vec2i) (int, int) {
return (v2.Y - v1.Y), -(v2.X - v1.X)
}
func Triangle3(fb *Framebuffer, color uint, v0f Vec3f, v1f Vec3f, v2f Vec3f) {
v0 := v0f.ToVec2i()
v1 := v1f.ToVec2i()
v2 := v2f.ToVec2i()
boundsTL, boundsBR := ComputeBoundingBox(v0, v1, v2)
if boundsTL.Y < 0 {
boundsTL.Y = 0
}
if boundsTL.X < 0 {
boundsTL.X = 0
}
if boundsBR.Y >= int(fb.Height) {
boundsBR.Y = int(fb.Height - 1)
}
if boundsBR.X >= int(fb.Width) {
boundsBR.X = int(fb.Width - 1)
}
// Where to start our scanning
pstart := Vec2i{boundsTL.X, boundsTL.Y}
parea := EdgeFunctioni(v0, v1, v2)
// if parea < 0 {
// v1, v2 = v2, v1
// v1f, v2f = v2f, v1f
// parea = EdgeFunctioni(v0, v1, v2)
// }
invarea := 1 / float32(parea)
w0_y := EdgeFunctioni(v1, v2, pstart)
w1_y := EdgeFunctioni(v2, v0, pstart)
w2_y := EdgeFunctioni(v0, v1, pstart)
w0_xi, w0_yi := EdgeIncrementi(v1, v2)
w1_xi, w1_yi := EdgeIncrementi(v2, v0)
w2_xi, w2_yi := EdgeIncrementi(v0, v1)
for y := uint(boundsTL.Y); y <= uint(boundsBR.Y); y++ {
w0 := w0_y
w1 := w1_y
w2 := w2_y
for x := uint(boundsTL.X); x <= uint(boundsBR.X); x++ {
if (w0 | w1 | w2) >= 0 {
//fb.Data[di] = color
//done = true
w0a := float32(w0) * invarea
w1a := float32(w1) * invarea
w2a := float32(w2) * invarea
pz := uint16(w0a*v0f.Z + w1a*v1f.Z + w2a*v2f.Z)
if pz < fb.ZBuffer[x+y*fb.Width] {
//log.Print(pz)
fb.ZBuffer[x+y*fb.Width] = pz
fb.Set(x, y, color)
}
// fb.Set(x, y, Col2Uint(byte(255*w0a), byte(255*w1a), byte(255*w2a)))
}
w0 += w0_xi
w1 += w1_xi
w2 += w2_xi
}
w0_y += w0_yi
w1_y += w1_yi
w2_y += w2_yi
}
}
func Triangle3t(fb *Framebuffer, texture *Framebuffer, intensity float32, v0v Vertex, v1v Vertex, v2v Vertex) {
v0 := v0v.Pos.ToVec2i()
v1 := v1v.Pos.ToVec2i()
v2 := v2v.Pos.ToVec2i()
boundsTL, boundsBR := ComputeBoundingBox(v0, v1, v2)
if boundsBR.Y < 0 || boundsBR.X < 0 || boundsTL.X >= int(fb.Width) || boundsTL.Y >= int(fb.Height) {
return
}
parea := EdgeFunctioni(v0, v1, v2)
if parea == 0 {
return
}
if boundsTL.Y < 0 {
boundsTL.Y = 0
}
if boundsTL.X < 0 {
boundsTL.X = 0
}
if boundsBR.Y >= int(fb.Height) {
boundsBR.Y = int(fb.Height - 1)
}
if boundsBR.X >= int(fb.Width) {
boundsBR.X = int(fb.Width - 1)
}
// Where to start our scanning
pstart := Vec2i{boundsTL.X, boundsTL.Y}
// if parea < 0 {
// v1, v2 = v2, v1
// v1f, v2f = v2f, v1f
// parea = EdgeFunctioni(v0, v1, v2)
// }
invarea := 1 / float32(parea)
w0_y := EdgeFunctioni(v1, v2, pstart)
w1_y := EdgeFunctioni(v2, v0, pstart)
w2_y := EdgeFunctioni(v0, v1, pstart)
w0_xi, w0_yi := EdgeIncrementi(v1, v2)
w1_xi, w1_yi := EdgeIncrementi(v2, v0)
w2_xi, w2_yi := EdgeIncrementi(v0, v1)
for y := uint(boundsTL.Y); y <= uint(boundsBR.Y); y++ {
w0 := w0_y
w1 := w1_y
w2 := w2_y
for x := uint(boundsTL.X); x <= uint(boundsBR.X); x++ {
if (w0 | w1 | w2) >= 0 {
w0a := float32(w0) * invarea
w1a := float32(w1) * invarea
w2a := float32(w2) * invarea
pz := uint16(w0a*v0v.Pos.Z + w1a*v1v.Pos.Z + w2a*v2v.Pos.Z)
if pz < fb.ZBuffer[x+y*fb.Width] {
fb.ZBuffer[x+y*fb.Width] = pz
// if math.IsNaN(v0v.Tex.X) || math.IsNaN(v1v.Tex.X) || math.IsNaN
col := texture.GetUv(
(w0a*v0v.Tex.X + w1a*v1v.Tex.X + w2a*v2v.Tex.X),
(w0a*v0v.Tex.Y + w1a*v1v.Tex.Y + w2a*v2v.Tex.Y),
)
r, g, b := Uint2Col(col)
fb.Set(x, y, Col2Uint(byte(float32(r)*intensity), byte(float32(g)*intensity), byte(float32(b)*intensity))) //uint(texture.Bounds().Dx())
}
}
w0 += w0_xi
w1 += w1_xi
w2 += w2_xi
}
w0_y += w0_yi
w1_y += w1_yi
w2_y += w2_yi
}
}

177
tinyrender5/render_less.go Normal file
View File

@ -0,0 +1,177 @@
package main
import (
//"log"
"math"
)
func Bresenham2(fb *Framebuffer, color uint, x0 int, y0 int, x1 int, y1 int) {
dx := int(math.Abs(float64(x1 - x0)))
sx := -1
if x0 < x1 {
sx = 1
}
dy := -int(math.Abs(float64(y1 - y0)))
sy := -1
if y0 < y1 {
sy = 1
}
err := dx + dy
for {
fb.SetSafe(uint(x0), uint(y0), color)
if x0 == x1 && y0 == y1 {
break
}
e2 := 2 * err
if e2 >= dy {
if x0 == x1 {
break
}
err += dy
x0 += sx
}
if e2 <= dx {
if y0 == y1 {
break
}
err += dx
y0 += sy
}
}
}
func line(fb *Framebuffer, color uint, v0 Vec2i, v1 Vec2i) {
Bresenham2(fb, color, v0.X, v0.Y, v1.X, v1.Y)
}
/*func LineSweep(fb *Framebuffer, color uint, v0 Vec2i, v1 Vec2i, v2 Vec2i) {
}*/
func Triangle1(fb *Framebuffer, color uint, v0 Vec2i, v1 Vec2i, v2 Vec2i) {
// The dude gets rid of "degenerate" triangles so... we do too?
if v2.Y == v1.Y && v1.Y == v0.Y {
return
}
// Very silly manual sorting by Y
if v2.Y < v0.Y {
v0, v2 = v2, v0
}
if v1.Y < v0.Y {
v0, v1 = v1, v0
}
if v2.Y < v1.Y {
v1, v2 = v2, v1
}
var v02step, v01step, v12step, xlong, xshort float32
xlong = float32(v0.X)
xshort = xlong
// The first and last Y CAN'T be equal because sorting!!
if v1.Y == v0.Y {
xshort = float32(v1.X)
}
// We can check just for greater than because we sorted the vertices
// Assume 02 is on the right(?) and 01 on the left
v02step = (float32(v2.X - v0.X)) / (float32(v2.Y-v0.Y) + 0.001) // long side always
v01step = (float32(v1.X - v0.X)) / (float32(v1.Y-v0.Y) + 0.001) // first short side
v12step = (float32(v2.X - v1.X)) / (float32(v2.Y-v1.Y) + 0.001) // second short side
for y := v0.Y; y <= v2.Y; y++ {
xleft := int(xshort)
xright := int(xlong)
if xleft > xright {
xleft, xright = xright, xleft
}
if xleft < 0 || xright >= int(fb.Width) {
continue
}
// Draw a horizontal line from left to right
for x := xleft; x <= xright; x++ {
fb.SetSafe(uint(x), uint(y), color)
}
xlong += v02step
if y < v1.Y {
xshort += v01step
} else {
xshort += v12step
}
}
}
// How does this work? Compare with your
// other barycentric function (in a different repo). In the original
// cpp code, they used an overloaded operator ^ to mean cross product
func Barycentric(v0, v1, v2, p Vec2i) Vec3f {
// WARN: Just not doing this one
u := Vec3f{}
if math.Abs(float64(u.Z)) < 1 {
return Vec3f{-1, 1, 1}
}
return Vec3f{1 - (u.X+u.Y)/u.Z, u.Y / u.Z, u.X / u.Z}
}
func Triangle2(fb *Framebuffer, color uint, v0 Vec2i, v1 Vec2i, v2 Vec2i) {
boundsTL, boundsBR := ComputeBoundingBox(v0, v1, v2)
if boundsTL.Y < 0 {
boundsTL.Y = 0
}
if boundsTL.X < 0 {
boundsTL.X = 0
}
if boundsBR.Y >= int(fb.Height) {
boundsBR.Y = int(fb.Height - 1)
}
if boundsBR.X >= int(fb.Width) {
boundsBR.X = int(fb.Width - 1)
}
// Where to start our scanning
pstart := Vec2i{boundsTL.X, boundsTL.Y}
//log.Print(boundsTL, boundsBR)
// v0f := v0.ToF()
// v1f := v1.ToF()
// v2f := v2.ToF()
// parea := EdgeFunction(v0f, v1f, v2f)
// invarea := 1 / parea
w0_y := EdgeFunctioni(v1, v2, pstart)
w1_y := EdgeFunctioni(v2, v0, pstart)
w2_y := EdgeFunctioni(v0, v1, pstart)
w0_xi, w0_yi := EdgeIncrementi(v1, v2)
w1_xi, w1_yi := EdgeIncrementi(v2, v0)
w2_xi, w2_yi := EdgeIncrementi(v0, v1)
//dyi := int(fb.Width)
//dy := boundsTL.X + dyi*boundsTL.Y
for y := uint(boundsTL.Y); y <= uint(boundsBR.Y); y++ {
w0 := w0_y
w1 := w1_y
w2 := w2_y
//di := dy
//done := false
for x := uint(boundsTL.X); x <= uint(boundsBR.X); x++ {
if (w0 | w1 | w2) >= 0 {
//fb.Data[di] = color
fb.Set(x, y, color)
//done = true
// w0a := w0 * invarea
// w1a := w1 * invarea
// w2a := w2 * invarea
// fb.Set(x, y, Col2Uint(byte(255*w0a), byte(255*w1a), byte(255*w2a)))
} /*else if done {
break
}*/
//di += 1
w0 += w0_xi
w1 += w1_xi
w2 += w2_xi
}
//dy += dyi
w0_y += w0_yi
w1_y += w1_yi
w2_y += w2_yi
}
}

14
tinyrender5/run.sh Executable file
View File

@ -0,0 +1,14 @@
#!/bin/sh
set -e
if [ $# -ne 1 ]; then
echo "You must pass the basename for the .prof and .ppm"
exit 1
fi
echo "Building"
go build -o render
echo "Running"
./render "-cpuprofile=$1.prof" "-p6file=$1.ppm" "-repeat=500"
# ./render "-zbuffer" >"$1_zbuffer.ppm"

22
tinyrender5/slices.sh Executable file
View File

@ -0,0 +1,22 @@
#!/bin/sh
if [ $# -ne 1 ]; then
echo "You must pass the basename for the slices"
exit 1
fi
echo "Building"
go build -o render
mkdir -p $1
frame=0
for x in $(seq -0.7 0.05 0.7); do
ff=$(printf "%03d" $frame)
./render "-p6file=$1/$ff.ppm" "-zcuthigh=$x"
frame=$((frame + 1))
done
echo "Converting animation"
cd $1
convert -delay 10 -loop 0 *.ppm -resize 256x256 anim.gif