Setting up indexed faces

This commit is contained in:
Carlos Sanchez 2024-08-05 03:25:58 -04:00
parent 8a79445b42
commit 0f235dba74
12 changed files with 1712 additions and 0 deletions

4
renderer4/.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
renderer4
renderer3
renderer2
renderer

284
renderer4/generation.go Normal file
View File

@ -0,0 +1,284 @@
package main
import (
"image"
"image/color"
"log"
"math"
"math/rand"
"renderer4/hrend"
)
func Checkerboard(cols []color.Color, size int) image.Image {
result := image.NewRGBA(image.Rect(0, 0, size, size))
for y := range size {
for x := range size {
result.Set(x, y, cols[(x+y)%len(cols)])
}
}
return result
}
// Returns a sizexsize*3 texture where the top is the top color,
// bottom is bottom color, middle is gradient
func Gradient(bottom color.Color, top color.Color, size int) image.Image {
result := image.NewRGBA(image.Rect(0, 0, size, size*3))
br, bg, bb, ba := bottom.RGBA()
tr, tg, tb, ta := top.RGBA()
for y := range size {
for x := range size {
lerp := float32(y) / float32(size-1)
result.Set(x, y, top)
result.Set(x, y+size, color.RGBA{
R: byte(float32(tr>>8)*(1-lerp) + float32(br>>8)*lerp),
G: byte(float32(tg>>8)*(1-lerp) + float32(bg>>8)*lerp),
B: byte(float32(tb>>8)*(1-lerp) + float32(bb>>8)*lerp),
A: byte(float32(ta>>8)*(1-lerp) + float32(ba>>8)*lerp),
})
result.Set(x, y+size*2, bottom)
}
}
return result
}
// Returns a 1px wide gradient where top is top color, bottom is bottom color
func Gradient1px(bottom color.Color, top color.Color, size int) image.Image {
result := image.NewRGBA(image.Rect(0, 0, 1, size))
br, bg, bb, ba := bottom.RGBA()
tr, tg, tb, ta := top.RGBA()
for y := range size {
lerp := float32(y) / float32(size-1)
result.Set(0, y, color.RGBA{
R: byte(float32(tr>>8)*(1-lerp) + float32(br>>8)*lerp),
G: byte(float32(tg>>8)*(1-lerp) + float32(bg>>8)*lerp),
B: byte(float32(tb>>8)*(1-lerp) + float32(bb>>8)*lerp),
A: byte(float32(ta>>8)*(1-lerp) + float32(ba>>8)*lerp),
})
}
return result
}
// Skybox for now assumes a 1px gradient
func Skybox() *hrend.ObjModel {
v := make([]hrend.Vec3f, 8)
vt := make([]hrend.Vec3f, 2)
f := make([]hrend.Facei, 12)
// Assuming 1px gradient, these are the only two texture points you need
vt[0] = hrend.Vec3f{X: 0, Y: 0.001, Z: 0}
vt[1] = hrend.Vec3f{X: 0, Y: 1, Z: 0}
vvt := []uint16{
0, 0, 0, 0, 1, 1, 1, 1,
//vt[0], vt[0], vt[0], vt[0], vt[1], vt[1], vt[1], vt[1],
}
// Cube faces are weird, I guess just manually do them? ugh
// First 4 are the bottom vertices. We can make two faces out of these
v[0] = hrend.Vec3f{X: float32(-1), Y: float32(-1), Z: float32(-1)}
v[1] = hrend.Vec3f{X: float32(1), Y: float32(-1), Z: float32(-1)}
v[2] = hrend.Vec3f{X: float32(1), Y: float32(-1), Z: float32(1)}
v[3] = hrend.Vec3f{X: float32(-1), Y: float32(-1), Z: float32(1)}
// Now the top 4 vertices, same order as bottom
v[4] = hrend.Vec3f{X: float32(-1), Y: float32(1), Z: float32(-1)}
v[5] = hrend.Vec3f{X: float32(1), Y: float32(1), Z: float32(-1)}
v[6] = hrend.Vec3f{X: float32(1), Y: float32(1), Z: float32(1)}
v[7] = hrend.Vec3f{X: float32(-1), Y: float32(1), Z: float32(1)}
// These are our 12 faces
fv := [][3]uint16{
{0, 2, 1}, // bottom
{0, 3, 2},
{4, 5, 6}, // top
{6, 7, 4},
{0, 1, 5}, // south
{5, 4, 0},
{1, 2, 6}, // east
{6, 5, 1},
{2, 3, 7}, // North
{7, 6, 2},
{3, 0, 4}, // west
{4, 7, 3},
}
for i, face := range fv {
for j := range 3 {
f[i][j].Posi = face[j] //= hrend.Vertex{Pos: face[j], Tex: vvt[face[j]]}
f[i][j].Texi = vvt[face[j]] //= hrend.Vertex{Pos: face[j], Tex: vvt[face[j]]}
}
}
// Ugh and now the sides... so complicated
return &hrend.ObjModel{
Vertices: v,
VTexture: vt,
Faces: f,
}
}
// Reset all faces and regenerate them using the vertices as a square mesh
func RegenerateSquareMesh(size int, obj *hrend.ObjModel) {
obj.VTexture = make([]hrend.Vec3f, 4)
// For the simple square terrain, there aren't a lot of texture coords...
// If you want something more complicated, replace this
obj.VTexture[0] = hrend.Vec3f{X: 0, Y: 0, Z: 0}
obj.VTexture[1] = hrend.Vec3f{X: 1, Y: 0, Z: 0}
obj.VTexture[2] = hrend.Vec3f{X: 0, Y: 1, Z: 0}
obj.VTexture[3] = hrend.Vec3f{X: 1, Y: 1, Z: 0}
obj.Faces = nil // Clear old faces
width := size + size + 1
// Faces are slightly different; we generate two for every "cell" inside the vertices
for z := 0; z < width-1; z++ {
for x := 0; x < width-1; x++ {
topleft := uint16(x + z*width)
topright := uint16(x + 1 + z*width)
bottomleft := uint16(x + (z+1)*width)
bottomright := uint16(x + 1 + (z+1)*width)
// remember to wind counter-clockwise
obj.Faces = append(obj.Faces, hrend.Facei{
{Posi: topleft, Texi: 0},
{Posi: bottomleft, Texi: 2},
{Posi: topright, Texi: 1},
}, hrend.Facei{
{Posi: topright, Texi: 1},
{Posi: bottomleft, Texi: 2},
{Posi: bottomright, Texi: 3},
})
}
}
}
func FlatTerrain(size int) *hrend.ObjModel {
result := hrend.ObjModel{
Vertices: make([]hrend.Vec3f, 0),
VTexture: make([]hrend.Vec3f, 4),
Faces: make([]hrend.Facei, 0),
}
// Generate all the simple vertices along the plane at y=0
for z := -size; z <= size; z++ {
for x := -size; x <= size; x++ {
result.Vertices = append(result.Vertices, hrend.Vec3f{X: float32(x), Y: 0, Z: float32(z)})
}
}
RegenerateSquareMesh(size, &result)
return &result
}
func DiamondSquareTerrain(size int, roughness float32, scale float32) *hrend.ObjModel {
result := hrend.ObjModel{
Vertices: make([]hrend.Vec3f, 0),
VTexture: make([]hrend.Vec3f, 4),
Faces: make([]hrend.Facei, 0),
}
dsterra := DiamondSquare(size+size+1, float64(roughness))
// Generate all the simple vertices along the plane at y=0
for z := -size; z <= size; z++ {
for x := -size; x <= size; x++ {
//result.Vertices = append(result.Vertices, hrend.Vec3f{X: float32(x), Y: float32(float64(scale) * dsterra[0][0]), Z: float32(z)})
result.Vertices = append(result.Vertices, hrend.Vec3f{X: float32(x), Y: float32(float64(scale) * dsterra[z+size][x+size]), Z: float32(z)})
}
}
RegenerateSquareMesh(size, &result)
return &result
}
// CHATGPT -----------------------------------------
func DiamondSquare(size int, roughness float64) [][]float64 {
// Initialize the array
terrain := make([][]float64, size)
for i := range terrain {
terrain[i] = make([]float64, size)
}
// Seed the corners
terrain[0][0] = rand.Float64()
terrain[0][size-1] = rand.Float64()
terrain[size-1][0] = rand.Float64()
terrain[size-1][size-1] = rand.Float64()
log.Print("DS Seeded corners")
// Size of the step
stepSize := size - 1
for stepSize > 1 {
halfStep := stepSize / 2
// Diamond step
for y := halfStep; y < size; y += stepSize {
for x := halfStep; x < size; x += stepSize {
diamondStep(terrain, x, y, halfStep, roughness)
}
}
// Square step
for y := 0; y < size; y += halfStep {
for x := (y + halfStep) % stepSize; x < size; x += stepSize {
squareStep(terrain, x, y, halfStep, roughness)
}
}
stepSize = halfStep
}
log.Printf("DS finished squares and diamonds")
// Normalize to [0, 1]
normalize(terrain)
log.Printf("DS normalize (complete)")
return terrain
}
// Diamond step of the algorithm
func diamondStep(terrain [][]float64, x, y, halfStep int, roughness float64) {
sum := terrain[y-halfStep][x-halfStep] +
terrain[y-halfStep][x+halfStep] +
terrain[y+halfStep][x-halfStep] +
terrain[y+halfStep][x+halfStep]
avg := sum / 4
terrain[y][x] = avg + (rand.Float64()*2-1)*roughness
}
// Square step of the algorithm
func squareStep(terrain [][]float64, x, y, halfStep int, roughness float64) {
avg := 0.0
count := 0
if x-halfStep >= 0 {
avg += terrain[y][x-halfStep]
count++
}
if x+halfStep < len(terrain) {
avg += terrain[y][x+halfStep]
count++
}
if y-halfStep >= 0 {
avg += terrain[y-halfStep][x]
count++
}
if y+halfStep < len(terrain) {
avg += terrain[y+halfStep][x]
count++
}
avg /= float64(count)
terrain[y][x] = avg + (rand.Float64()*2-1)*roughness
}
// Normalize the array to range [0, 1]
func normalize(terrain [][]float64) {
minVal, maxVal := math.Inf(1), math.Inf(-1)
for _, row := range terrain {
for _, value := range row {
if value < minVal {
minVal = value
}
if value > maxVal {
maxVal = value
}
}
}
rangeVal := maxVal - minVal
for i, row := range terrain {
for j := range row {
terrain[i][j] = (terrain[i][j] - minVal) / rangeVal
}
}
}

11
renderer4/go.mod Normal file
View File

@ -0,0 +1,11 @@
module renderer4
go 1.22.5
require github.com/gen2brain/raylib-go/raylib v0.0.0-20240628125141-62016ee92fc0
require (
github.com/ebitengine/purego v0.7.1 // indirect
golang.org/x/exp v0.0.0-20240506185415-9bf2ced13842 // indirect
golang.org/x/sys v0.20.0 // indirect
)

8
renderer4/go.sum Normal file
View File

@ -0,0 +1,8 @@
github.com/ebitengine/purego v0.7.1 h1:6/55d26lG3o9VCZX8lping+bZcmShseiqlh2bnUDiPA=
github.com/ebitengine/purego v0.7.1/go.mod h1:ah1In8AOtksoNK6yk5z1HTJeUkC1Ez4Wk2idgGslMwQ=
github.com/gen2brain/raylib-go/raylib v0.0.0-20240628125141-62016ee92fc0 h1:mhWZabwn9WvzqMBgiuW8ewuQ4Zg+PfW+XbNnTtIX1FY=
github.com/gen2brain/raylib-go/raylib v0.0.0-20240628125141-62016ee92fc0/go.mod h1:BaY76bZk7nw1/kVOSQObPY1v1iwVE1KHAGMfvI6oK1Q=
golang.org/x/exp v0.0.0-20240506185415-9bf2ced13842 h1:vr/HnozRka3pE4EsMEg1lgkXJkTFJCVUX+S/ZT6wYzM=
golang.org/x/exp v0.0.0-20240506185415-9bf2ced13842/go.mod h1:XtvwrStGgqGPLc4cjQfWqZHG1YFdYs6swckp8vpsjnc=
golang.org/x/sys v0.20.0 h1:Od9JTbYCk261bKm4M/mw7AklTlFYIa0bIp9BgSm1S8Y=
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=

View File

@ -0,0 +1,27 @@
package hrend
import (
"time"
)
// Sum up and average frame times at desired intervals. Average and sum
// should be seconds
type FrameTimer struct {
Sum time.Duration
TotalTime time.Duration
Count int
TotalCount int
LastAverage time.Duration
}
func (ft *FrameTimer) Add(t time.Duration, avgcount int) {
ft.Sum += t
ft.TotalTime += t
ft.Count += 1
ft.TotalCount += 1
if ft.Count%avgcount == 0 {
ft.LastAverage = ft.Sum / time.Duration(ft.Count)
ft.Sum = 0
ft.Count = 0
}
}

197
renderer4/hrend/image.go Normal file
View File

@ -0,0 +1,197 @@
package hrend
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)
}
// A simple buffer where you can set pixels
type Framebuffer interface {
Set(x uint, y uint, r byte, g byte, b byte)
Get(x uint, y uint) (byte, byte, byte)
GetUv(u float32, v float32) (byte, byte, byte)
Dims() (uint, uint)
}
// Turn framebuffer into image, useful for processing into individual frames
func ToImage(fb Framebuffer) *image.RGBA {
width, height := fb.Dims()
result := image.NewRGBA(image.Rect(0, 0, int(width), int(height)))
for y := range height {
for x := range width {
c := color.RGBA{A: 255}
c.R, c.G, c.G = fb.Get(x, y)
result.Set(int(x), int(y), c)
}
}
return result
}
// Color is in RGB (alpha not used right now)
type SimpleFramebuffer struct {
Data []byte
Width uint
Height uint
}
func (fb *SimpleFramebuffer) Dims() (uint, uint) {
return fb.Width, fb.Height
}
// Sure hope this gets inlined...
func (fb *SimpleFramebuffer) Set(x uint, y uint, r byte, g byte, b byte) {
if x >= fb.Width || y >= fb.Height {
return
}
fb.Data[(x+y*fb.Width)*3] = r
fb.Data[(x+y*fb.Width)*3+1] = g
fb.Data[(x+y*fb.Width)*3+2] = b
}
func (fb *SimpleFramebuffer) Get(x uint, y uint) (byte, byte, byte) {
if x >= fb.Width || y >= fb.Height {
return 0, 0, 0
}
return fb.Data[(x+y*fb.Width)*3],
fb.Data[(x+y*fb.Width)*3+1],
fb.Data[(x+y*fb.Width)*3+2]
}
func (fb *SimpleFramebuffer) GetUv(u float32, v float32) (byte, byte, byte) {
x := uint(float32(fb.Width)*u) & (fb.Width - 1)
y := uint(float32(fb.Height)*(1-v)) & (fb.Height - 1)
i := (x + y*fb.Width) * 3
return fb.Data[i], fb.Data[i+1], fb.Data[i+2]
// return fb.Data[(x+y*fb.Width)*3],
// fb.Data[(x+y*fb.Width)*3+1],
// fb.Data[(x+y*fb.Width)*3+2]
}
func NewSimpleFramebuffer(width uint, height uint) *SimpleFramebuffer {
return &SimpleFramebuffer{
Data: make([]byte, width*height*3),
Width: width,
Height: height,
}
}
type RenderBuffer struct {
Data Framebuffer
ZBuffer []float32 //uint16 // Apparently 16 bit z-buffers are used
Width uint
Height uint
}
// Create a new framebuffer for the given width and height.
func NewRenderbuffer(d Framebuffer, width uint, height uint) RenderBuffer {
return RenderBuffer{
Data: d,
ZBuffer: make([]float32, width*height),
Width: width,
Height: height,
}
}
func NewTexture(texture image.Image, stride int) *SimpleFramebuffer {
bounds := texture.Bounds()
width := bounds.Dx() / stride
height := bounds.Dy() / stride
result := NewSimpleFramebuffer(uint(width), uint(height))
wlog := math.Log2(float64(width))
hlog := math.Log2(float64(height))
if wlog != math.Floor(wlog) || hlog != math.Floor(hlog) {
panic("Texture must be power of two")
}
for y := bounds.Min.Y; y < bounds.Max.Y; y += stride {
for x := bounds.Min.X; x < bounds.Max.X; x += stride {
col := texture.At(x, y)
r, g, b, _ := col.RGBA()
result.Set(uint(x/stride), uint(y/stride), byte(r>>8), byte(g>>8), byte(b>>8))
}
}
return result
}
// Fill zbuffer with pixels that are max distance away
func (fb *RenderBuffer) ResetZBuffer() {
for i := range fb.ZBuffer {
fb.ZBuffer[i] = 65535 //math.MaxFloat32
}
}
// Given some image data, return a string that is the ppm of it
func (fb *RenderBuffer) 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 := fb.Data.Get(x, y)
result.WriteString(fmt.Sprintf("%d %d %d\t", r, g, b))
}
result.WriteRune('\n')
}
return result.String()
}
func (fb *RenderBuffer) 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 y := range fb.Height {
for x := range fb.Width {
r, g, b := fb.Data.Get(x, y)
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 *RenderBuffer) 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()
}

382
renderer4/hrend/math.go Normal file
View File

@ -0,0 +1,382 @@
package hrend
// This is the linear algebra junk? Vectors, matrices, etc
import (
//"log"
"math"
)
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
}
}
// Multiply the entire matrix by the given value
func (m *Mat44f) MultiplySelf(f float32) {
for i := range m {
m[i] *= f
}
}
// Copied from https://github.com/go-gl/mathgl/blob/master/mgl32/matrix.go
func (m *Mat44f) Determinant() float32 {
return m[0]*m[5]*m[10]*m[15] - m[0]*m[5]*m[11]*m[14] - m[0]*m[6]*m[9]*m[15] + m[0]*m[6]*m[11]*m[13] + m[0]*m[7]*m[9]*m[14] - m[0]*m[7]*m[10]*m[13] - m[1]*m[4]*m[10]*m[15] + m[1]*m[4]*m[11]*m[14] + m[1]*m[6]*m[8]*m[15] - m[1]*m[6]*m[11]*m[12] - m[1]*m[7]*m[8]*m[14] + m[1]*m[7]*m[10]*m[12] + m[2]*m[4]*m[9]*m[15] - m[2]*m[4]*m[11]*m[13] - m[2]*m[5]*m[8]*m[15] + m[2]*m[5]*m[11]*m[12] + m[2]*m[7]*m[8]*m[13] - m[2]*m[7]*m[9]*m[12] - m[3]*m[4]*m[9]*m[14] + m[3]*m[4]*m[10]*m[13] + m[3]*m[5]*m[8]*m[14] - m[3]*m[5]*m[10]*m[12] - m[3]*m[6]*m[8]*m[13] + m[3]*m[6]*m[9]*m[12]
}
// Copied from https://github.com/go-gl/mathgl/blob/master/mgl32/matrix.go
func (m *Mat44f) Inverse() *Mat44f {
det := m.Determinant()
if det == float32(0.0) {
return &Mat44f{}
}
// How the hell am I supposed to know if this is correct? Oh well...
result := Mat44f{
-m[7]*m[10]*m[13] + m[6]*m[11]*m[13] + m[7]*m[9]*m[14] - m[5]*m[11]*m[14] - m[6]*m[9]*m[15] + m[5]*m[10]*m[15],
m[3]*m[10]*m[13] - m[2]*m[11]*m[13] - m[3]*m[9]*m[14] + m[1]*m[11]*m[14] + m[2]*m[9]*m[15] - m[1]*m[10]*m[15],
-m[3]*m[6]*m[13] + m[2]*m[7]*m[13] + m[3]*m[5]*m[14] - m[1]*m[7]*m[14] - m[2]*m[5]*m[15] + m[1]*m[6]*m[15],
m[3]*m[6]*m[9] - m[2]*m[7]*m[9] - m[3]*m[5]*m[10] + m[1]*m[7]*m[10] + m[2]*m[5]*m[11] - m[1]*m[6]*m[11],
m[7]*m[10]*m[12] - m[6]*m[11]*m[12] - m[7]*m[8]*m[14] + m[4]*m[11]*m[14] + m[6]*m[8]*m[15] - m[4]*m[10]*m[15],
-m[3]*m[10]*m[12] + m[2]*m[11]*m[12] + m[3]*m[8]*m[14] - m[0]*m[11]*m[14] - m[2]*m[8]*m[15] + m[0]*m[10]*m[15],
m[3]*m[6]*m[12] - m[2]*m[7]*m[12] - m[3]*m[4]*m[14] + m[0]*m[7]*m[14] + m[2]*m[4]*m[15] - m[0]*m[6]*m[15],
-m[3]*m[6]*m[8] + m[2]*m[7]*m[8] + m[3]*m[4]*m[10] - m[0]*m[7]*m[10] - m[2]*m[4]*m[11] + m[0]*m[6]*m[11],
-m[7]*m[9]*m[12] + m[5]*m[11]*m[12] + m[7]*m[8]*m[13] - m[4]*m[11]*m[13] - m[5]*m[8]*m[15] + m[4]*m[9]*m[15],
m[3]*m[9]*m[12] - m[1]*m[11]*m[12] - m[3]*m[8]*m[13] + m[0]*m[11]*m[13] + m[1]*m[8]*m[15] - m[0]*m[9]*m[15],
-m[3]*m[5]*m[12] + m[1]*m[7]*m[12] + m[3]*m[4]*m[13] - m[0]*m[7]*m[13] - m[1]*m[4]*m[15] + m[0]*m[5]*m[15],
m[3]*m[5]*m[8] - m[1]*m[7]*m[8] - m[3]*m[4]*m[9] + m[0]*m[7]*m[9] + m[1]*m[4]*m[11] - m[0]*m[5]*m[11],
m[6]*m[9]*m[12] - m[5]*m[10]*m[12] - m[6]*m[8]*m[13] + m[4]*m[10]*m[13] + m[5]*m[8]*m[14] - m[4]*m[9]*m[14],
-m[2]*m[9]*m[12] + m[1]*m[10]*m[12] + m[2]*m[8]*m[13] - m[0]*m[10]*m[13] - m[1]*m[8]*m[14] + m[0]*m[9]*m[14],
m[2]*m[5]*m[12] - m[1]*m[6]*m[12] - m[2]*m[4]*m[13] + m[0]*m[6]*m[13] + m[1]*m[4]*m[14] - m[0]*m[5]*m[14],
-m[2]*m[5]*m[8] + m[1]*m[6]*m[8] + m[2]*m[4]*m[9] - m[0]*m[6]*m[9] - m[1]*m[4]*m[10] + m[0]*m[5]*m[10],
}
result.MultiplySelf(1 / det)
//log.Print(m)
//log.Print(result)
return &result
}
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, aspect 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))
// OK apparently I suck, let's use somebody else's projection matrix:
m.ZeroFill()
// fov = fov / 180 * math.Pi // Convert to radians
// e := float32(1 / math.Tan(float64(fov/2)))
// m.Set(0, 0, e/aspect)
// m.Set(1, 1, e)
// m.Set(2, 2, (far+near)/(near-far))
// m.Set(2, 3, 2*far*near/(near-far))
// m.Set(3, 2, -1) // Might need to be swapped
DEG2RAD := math.Acos(-1.0) / 180.0
tangent := math.Tan(float64(fov/2.0) * DEG2RAD) // tangent of half fovY
top := near * float32(tangent) // half height of near plane
right := top * aspect // half width of near plane
// Column major maybe???
// n/r 0 0 0
// 0 n/t 0 0
// 0 0 -(f+n)/(f-n) -1
// 0 0 -(2fn)/(f-n) 0
m.Set(0, 0, near/right)
m.Set(1, 1, near/top)
m.Set(2, 2, -(far+near)/(far-near))
m.Set(3, 2, -1)
m.Set(2, 3, -(2*far*near)/(far-near))
}
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, 1) //(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)
}
// Convert the point to a viewport point
func (v *Vec3f) ViewportSelf(width, height int) {
v.X = (v.X + 1) / 2 * float32(width)
v.Y = (1 - (v.Y+1)/2) * float32(height)
// Don't touch Z
}
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)
}
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) ScaleSelf(scale float32) {
m.Set(0, 0, m.Get(0, 0)*scale)
m.Set(1, 1, m.Get(1, 1)*scale)
m.Set(2, 2, m.Get(2, 2)*scale)
}
func (m *Mat44f) SetRotationX(radang float32) {
m.SetIdentity()
m[5] = float32(math.Cos(float64(radang)))
m[10] = m[5]
m[6] = float32(math.Sin(float64(radang)))
m[9] = -m[6]
}
func (m *Mat44f) SetRotationY(radang float32) {
m.SetIdentity()
m[0] = float32(math.Cos(float64(radang)))
m[10] = m[0]
m[8] = float32(math.Sin(float64(radang)))
m[2] = -m[8]
}
func (m *Mat44f) SetRotationZ(radang float32) {
m.SetIdentity()
m[0] = float32(math.Cos(float64(radang)))
m[5] = m[0]
m[4] = float32(math.Sin(float64(radang)))
m[2] = -m[4]
}
// Camera is easier to deal with using yaw and pitch, since we're not supporting roll
func (m *Mat44f) SetCamera(loc *Vec3f, yaw float32, pitch float32, up *Vec3f) Vec3f {
// Use sphere equation to compute lookat vector through the two
// player-controled angles (pitch and yaw)
lookvec := Vec3f{
Z: float32(-math.Sin(float64(pitch)) * math.Cos(float64(yaw))),
X: float32(math.Sin(float64(pitch)) * math.Sin(float64(yaw))),
Y: float32(math.Cos(float64(pitch))),
}
m.SetLookAt(loc, loc.Add(&lookvec), up)
return lookvec
}
// Note: use {0,1,0} for up for normal use
func (m *Mat44f) SetLookAt(from *Vec3f, to *Vec3f, up *Vec3f) {
forward := from.Sub(to).Normalize()
// IDK if you have to normalize but whatever
right := up.CrossProduct(forward).Normalize()
realup := forward.CrossProduct(right)
m.SetIdentity()
m.Set(0, 0, right.X)
m.Set(1, 0, right.Y)
m.Set(2, 0, right.Z)
m.Set(0, 1, realup.X)
m.Set(1, 1, realup.Y)
m.Set(2, 1, realup.Z)
m.Set(0, 2, forward.X)
m.Set(1, 2, forward.Y)
m.Set(2, 2, forward.Z)
m.Set(0, 3, from.X)
m.Set(1, 3, from.Y)
m.Set(2, 3, from.Z)
}
// Homogenous vec3f
type HVec3f struct {
Pos Vec3f
W float32
}
func (h *HVec3f) MakeConventional() Vec3f {
r := h.Pos
if h.W != 1 {
r.X /= h.W
r.Y /= h.W
r.Z /= h.W
}
return r
}
// Multiply the given point by our vector. Remember this is row-major order.
// Point is NOT scaled back
func (m *Mat44f) MultiplyPoint3(p Vec3f) HVec3f {
var out HVec3f
// We hope very much that Go will optimize the function calls for us,
// along with computing the constants.
out.Pos.X = p.X*m.Get(0, 0) + p.Y*m.Get(0, 1) + p.Z*m.Get(0, 2) + m.Get(0, 3)
out.Pos.Y = p.X*m.Get(1, 0) + p.Y*m.Get(1, 1) + p.Z*m.Get(1, 2) + m.Get(1, 3)
out.Pos.Z = p.X*m.Get(2, 0) + p.Y*m.Get(2, 1) + p.Z*m.Get(2, 2) + m.Get(2, 3)
out.W = p.X*m.Get(3, 0) + p.Y*m.Get(3, 1) + p.Z*m.Get(3, 2) + m.Get(3, 3)
return out
}
// Multiply two 4x4 matrices together (not optimized). May
// mess with garbage collector?? IDK
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
}
// Multiply two matrices, storing the result in the first one
// func (m *Mat44f) MultiplyInto(m2 *Mat44f) {
// var orig Mat44f
// for i := 0; i < 16; i++ {
// orig[i] = m[i]
// }
// // This is the x and y of our resulting matrix
// for y := 0; y < 4; y++ {
// for x := 0; x < 4; x++ {
// m[x+y*4] = 0
// for i := 0; i < 4; i++ {
// m[x+y*4] += orig[i+y*4] * m2[x+i*4]
// }
// }
// }
// return &result
// }
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) Add(v1 *Vec3f) *Vec3f {
return &Vec3f{
X: v0.X + v1.X,
Y: v0.Y + v1.Y,
Z: v0.Z + v1.Z,
}
}
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) Scale(s float32) *Vec3f {
return &Vec3f{
X: v0.X * s,
Y: v0.Y * s,
Z: v0.Z * s,
}
}
func (v0 *HVec3f) LerpSelf(v1 *HVec3f, t float32) {
v0.Pos.X = (1-t)*v0.Pos.X + t*v1.Pos.X
v0.Pos.Y = (1-t)*v0.Pos.Y + t*v1.Pos.Y
v0.Pos.Z = (1-t)*v0.Pos.Z + t*v1.Pos.Z
v0.W = (1-t)*v0.W + t*v1.W
}
func LerpVec3f(v0 Vec3f, v1 Vec3f, t float32) Vec3f {
return Vec3f{
X: (1-t)*v0.X + t*v1.X,
Y: (1-t)*v0.Y + t*v1.Y,
Z: (1-t)*v0.Z + t*v1.Z,
}
}
func LerpF32(a, b, t float32) float32 {
return (1-t)*a + t*b
}
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
}
func Clamp[t float32 | int](v, minv, maxv t) t {
if v < minv {
return minv
} else if v > maxv {
return maxv
} else {
return v
}
}

117
renderer4/hrend/obj.go Normal file
View File

@ -0,0 +1,117 @@
package hrend
// This reads obj files?
import (
"bufio"
"fmt"
"io"
"log"
"strings"
)
// A single vertex generally has multiple items associated with it
// when it's part of a face.
// type Vertex struct {
// Pos Vec3f
// Tex Vec3f
// }
// Facei stores indexes into a model or some other structure
type Facei [3]struct {
Posi uint16
Texi uint16
}
type Facef [3]struct {
Pos Vec3f
Tex Vec3f
}
type ObjModel struct {
Vertices []Vec3f
VTexture []Vec3f
Faces []Facei
}
// func (o *ObjModel) ClearCachedVertexInfo() {
// o.Vertices = nil
// o.VTexture = nil
// }
// 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),
VTexture: make([]Vec3f, 0),
Faces: make([]Facei, 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 Facei
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 || vi[i] > 65536 {
return nil, fmt.Errorf("Face vertex index out of bounds: %d", vi[i])
}
face[i].Posi = uint16(vi[i] - 1)
if vti[i] > len(result.VTexture) || vti[i] < 1 || vti[i] > 65536 {
return nil, fmt.Errorf("Face vertex texture index out of bounds: %d", vti[i])
}
face[i].Texi = uint16(vti[i] - 1)
}
result.Faces = append(result.Faces, face)
}
}
log.Printf("Obj had %d vertices, %d faces", len(result.Vertices), len(result.Faces))
return &result, nil
}

327
renderer4/hrend/render.go Normal file
View File

@ -0,0 +1,327 @@
package hrend
import (
// "log"
// "math"
)
type ObjectDef struct {
Model *ObjModel
Texture Framebuffer // This needs to go somewhere else eventually!
Pos Vec3f
LookVec Vec3f
Color Vec3f
Scale float32
Lighting bool
}
func (o *ObjectDef) FV(f *Facei, i int) *Vec3f {
return &o.Model.Vertices[f[i].Posi] //o.ModelFaces[i][f].Posi]
}
func NewObjectDef(model *ObjModel, texture Framebuffer) *ObjectDef {
result := ObjectDef{
Model: model,
Texture: texture,
LookVec: Vec3f{X: 0, Y: 0, Z: -1},
Scale: 1,
Lighting: true,
}
return &result
}
// 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)}
}
func ComputeBoundingBoxF(v0, v1, v2 Vec3f) (Vec3f, Vec3f) {
return Vec3f{min(v0.X, v1.X, v2.X), min(v0.Y, v1.Y, v2.Y), min(v0.Z, v1.Z, v2.Z)},
Vec3f{max(v0.X, v1.X, v2.X), max(v0.Y, v1.Y, v2.Y), max(v0.Z, v1.Z, v2.Z)}
}
// 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 Vec3f) 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 Vec3f) (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 ZClip(v0f Vec3f, v1f Vec3f, v2f Vec3f) bool {
maxz := max(v0f.Z, v1f.Z, v2f.Z)
return maxz < -1 || maxz > 1
}
func TriangleFlat(fb *RenderBuffer, color *Vec3f, v0f Vec3f, v1f Vec3f, v2f Vec3f) {
v0 := v0f.ToVec2i()
v1 := v1f.ToVec2i()
v2 := v2f.ToVec2i()
//r, g, b := Uint2Col(color)
boundsTL, boundsBR := ComputeBoundingBox(v0, v1, v2)
if boundsBR.X < 0 || boundsBR.Y < 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}
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)
r := byte(255 * color.X)
g := byte(255 * color.Y)
b := byte(255 * color.Z)
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 := w0a*v0f.Z + w1a*v1f.Z + w2a*v2f.Z
if pz < fb.ZBuffer[x+y*fb.Width] {
fb.ZBuffer[x+y*fb.Width] = pz
fb.Data.Set(x, y, r, g, b)
}
}
w0 += w0_xi
w1 += w1_xi
w2 += w2_xi
}
w0_y += w0_yi
w1_y += w1_yi
w2_y += w2_yi
}
}
func TriangleTextured(fb *RenderBuffer, texture Framebuffer, intensity float32, face *Facef) {
v0v := face[0]
v1v := face[1]
v2v := face[2]
// min, max
boundsTLf, boundsBRf := ComputeBoundingBoxF(face[0].Pos, face[1].Pos, face[2].Pos)
// The triangle is fully out of bounds; we don't have a proper clipper, so this
// check still needs to be performed
if boundsBRf.Y < 0 || boundsBRf.X < 0 || boundsTLf.X >= float32(fb.Width) || boundsTLf.Y >= float32(fb.Height) { //||
return
}
v0 := face[0].Pos.ToVec2i()
v1 := face[1].Pos.ToVec2i()
v2 := face[2].Pos.ToVec2i()
parea := EdgeFunctioni(v0, v1, v2)
// Don't even bother with drawing backfaces or degenerate triangles;
// don't even give the user the option
if parea <= 0 {
return
}
boundsTL := Vec2i{
X: int(max(boundsTLf.X, 0)),
Y: int(max(boundsTLf.Y, 0)),
}
boundsBR := Vec2i{
X: int(min(boundsBRf.X, float32(fb.Width-1))),
Y: int(min(boundsBRf.Y, float32(fb.Height-1))),
}
// Where to start our scanning
pstart := Vec2i{boundsTL.X, boundsTL.Y}
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 {
//if w0 >= 0 && w1 >= 0 && w2 >= 0 {
w0a := float32(w0) * invarea
w1a := float32(w1) * invarea
w2a := float32(w2) * invarea
pz := 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
r, g, b := 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),
)
fb.Data.Set(x, y, byte(float32(r)*intensity), byte(float32(g)*intensity), byte(float32(b)*intensity))
}
}
w0 += w0_xi
w1 += w1_xi
w2 += w2_xi
}
w0_y += w0_yi
w1_y += w1_yi
w2_y += w2_yi
}
}
// Return true if the face should be culled
func BackfaceCull(v1, v2, v3 Vec3f) bool {
// This is what it essentially is
// e1 := v1.Sub(&v2)
// e2 := v1.Sub(&v3)
// // If viewing front face, it should be pointing in the positive z direction
// return e1.CrossProduct(e2).Z <= 0
// But we know we can just use x and y since this is post projection
return (v1.X-v2.X)*(v3.Y-v2.Y)-(v1.Y-v2.Y)*(v3.X-v2.X) >= 0
}
func conditionalAddTriangle(sc []HVec3f, tx []Vec3f, out []Facef) []Facef {
var f Facef
// The triangle is fine
for i := range 3 {
f[i].Pos = sc[i].MakeConventional()
f[i].Tex = tx[i]
}
// Backface culling: no need to do anything with triangles facing the wrong way
if EdgeFunction(f[0].Pos, f[1].Pos, f[2].Pos) <= 0 {
out = append(out, f)
}
return out
}
// Apply perspective projection to all vertices, but don't convert homegenous
// coordinates yet
func PerspectiveAll(in []Vec3f, matrix3d *Mat44f, out []HVec3f) []HVec3f {
out = out[:len(in)]
for i := range in {
out[i] = matrix3d.MultiplyPoint3(in[i])
}
return out
}
func ClipFace(face Facei, vecs []HVec3f, texs []Vec3f) []Facef {
outfaces := make([]Facef, 0, 2)
outers := make([]int, 0, 3)
inners := make([]int, 0, 3)
var hf [3]HVec3f
var tx [3]Vec3f
var d [3]float32
for i := range 3 {
hf[i] = vecs[face[i].Posi]
tx[i] = texs[face[i].Texi]
d[i] = hf[i].Pos.Z + hf[i].W
if d[i] < 0.001 {
outers = append(outers, i)
} else {
inners = append(inners, i)
}
}
if len(outers) == 2 { // The one triangle thing
ai := inners[0]
bi := outers[0]
ci := outers[1]
// Calc how far along we are on each of these lines. These are the new points
tba := d[bi] / (d[bi] - d[ai])
tca := d[ci] / (d[ci] - d[ai])
// The two points that aren't a need to be the interpolated values
hf[bi].LerpSelf(&hf[ai], tba) // lerp b between it and a, store in self.
hf[ci].LerpSelf(&hf[ai], tca)
tx[bi] = LerpVec3f(tx[bi], tx[ai], tba)
tx[ci] = LerpVec3f(tx[ci], tx[ai], tca)
outfaces = conditionalAddTriangle(hf[:], tx[:], outfaces)
} else if len(outers) == 1 { // The two triangle thing, two new corners
ai := outers[0]
bi := inners[0]
ci := inners[1]
tab := d[ai] / (d[ai] - d[bi])
tac := d[ai] / (d[ai] - d[ci])
hfa := hf[ai]
txa := tx[ai]
// This time, we're generating two new points. But,
// Only ONE point needs to be modified: the one outer. Remember that
// tab and tac are the distance to that point itself, so a still needs
// to be the first value here
hf[ai].LerpSelf(&hf[bi], tab)
tx[ai] = LerpVec3f(tx[ai], tx[bi], tab)
outfaces = conditionalAddTriangle(hf[:], tx[:], outfaces)
// Now that we've replaced the far point, we also need to replace
// the original B point that we used, since that's part of the other
// triangle. But simply replacing it will make the triangle invisible,
// since it inverts the winding order (I think)
//hfa.LerpSelf(hf[ci], tac)
hf[bi] = hfa
hf[bi].LerpSelf(&hf[ci], tac)
tx[bi] = LerpVec3f(txa, tx[ci], tac)
//sct[bi].Pos = LerpVec3f(sc[ai].Pos, sc[ci].Pos, tac)
//sct[bi].Tex = LerpVec3f(sc[ai].Tex, sc[ci].Tex, tac)
//w[bi] = LerpF32(wa, w[ci], tac)
// Now swap the a and b (or we could swap c and b)
hf[ai], hf[bi] = hf[bi], hf[ai]
tx[ai], tx[bi] = tx[bi], tx[ai]
//w[ai], w[bi] = w[bi], w[ai]
//sct[ai], sct[bi] = sct[bi], sct[ai]
//outfaces = conditionalAddTriangle(sct, w, outfaces)
outfaces = conditionalAddTriangle(hf[:], tx[:], outfaces)
} else if len(outers) != 3 { // Output the face itself, no modification
outfaces = conditionalAddTriangle(hf[:], tx[:], outfaces)
}
return outfaces
// TODO: Now that we're here doing it like this, might as well remove faces
// that are fully outside the other clipping zones. No need to do actual clipping...
// just full rejections. This saves a BIT of processing... though not much
// NOTE: Uh no... this is too much effort. Two points could be outside individual
// planes and thus still intersect the screen.
}

282
renderer4/main.go Normal file
View File

@ -0,0 +1,282 @@
package main
import (
"flag"
"fmt"
"image"
"image/color"
"log"
"math"
"os"
"path/filepath"
"renderer4/hrend"
"runtime/pprof" // For performance profiling (unnecessary)
"time"
_ "image/jpeg"
rl "github.com/gen2brain/raylib-go/raylib"
)
const (
NearClip = 0.0001
FarClip = 10
Movement = 1.0
Rotation = 0.25
LookLock = math.Pi / 32
)
func must(err error) {
if err != nil {
panic(err)
}
}
func loadObject(name string) (*hrend.ObjModel, hrend.Framebuffer) {
ofile := filepath.Join("../", name+".obj")
tfile := filepath.Join("../", name+".jpg")
log.Printf("Loading obj %s, texture %s", ofile, tfile)
of, err := os.Open(ofile)
must(err)
defer of.Close()
o, err := hrend.ParseObj(of)
must(err)
// We also get rid of cached vertex info from the file
//o.ClearCachedVertexInfo()
jf, err := os.Open(tfile)
must(err)
defer jf.Close()
timg, _, err := image.Decode(jf)
must(err)
texture := hrend.NewTexture(timg, 4)
return o, texture
}
// However flag works... idk
var cpuprofile = flag.String("cpuprofile", "", "write cpu profile to file")
var width = flag.Int("width", 640, "width of window or frame")
var height = flag.Int("height", 480, "height of window or frame")
var renderout = flag.String("renderout", "", "If set, rendering is done to a file instead of realtime")
var renderinput = flag.String("renderinput", "", "If not realtime, the inputs are taken from here.")
var xofs = flag.Float64("xofs", 0, "starting x-offset")
var zofs = flag.Float64("zofs", 0, "starting z-offset")
var yofs = flag.Float64("yofs", 0.5, "starting y-offset")
var fov = flag.Float64("fov", 90, "the horizontal fov")
var fps = flag.Int("fps", 60, "fps to run (realtime only)")
var minlight = flag.Float64("minlight", 0.5, "Minimum light level")
// var renderconfig = flag.String("renderconfig", "", "if set, rendering is written out")
func IsRealtime() bool {
return *renderout == ""
}
// Do next inputs, whether they come from raylib or a file
func CameraInput(yaw, pitch float32) (float32, float32, hrend.Vec3f) {
Fps := float32(*fps)
mouse := rl.GetMouseDelta()
pitch += Rotation * mouse.Y / Fps
yaw += Rotation * mouse.X / Fps
pitch = hrend.Clamp(pitch, LookLock, math.Pi-LookLock)
newcamtrans := hrend.Vec3f{X: 0, Y: 0, Z: 0}
move := float32(Movement)
if rl.IsMouseButtonDown(rl.MouseButtonLeft) {
move *= 6
}
if rl.IsKeyDown(rl.KeyD) {
newcamtrans.X += move / Fps
}
if rl.IsKeyDown(rl.KeyA) {
newcamtrans.X -= move / Fps
}
// Moving forward moves in the negative z direction, since we FACE
// the -z axis (the camera does anyway)
if rl.IsKeyDown(rl.KeyW) {
newcamtrans.Z -= move / Fps
}
if rl.IsKeyDown(rl.KeyS) {
newcamtrans.Z += move / Fps
}
if rl.IsKeyDown(rl.KeySpace) {
newcamtrans.Y += move / Fps
}
if rl.IsKeyDown(rl.KeyLeftShift) {
newcamtrans.Y -= move / Fps
}
// translate the new camera movement based on the yaw
var moverot hrend.Mat44f
moverot.SetRotationY(-yaw)
hnewcamtrans := moverot.MultiplyPoint3(newcamtrans)
return yaw, pitch, hnewcamtrans.MakeConventional()
}
// --------------------------------------------
//
// MAIN
//
// --------------------------------------------
func main() {
log.Printf("Program start")
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()
}
Width := uint(*width)
Height := uint(*height)
var timer hrend.FrameTimer
var fb hrend.Framebuffer
var drawFunc func()
if IsRealtime() {
rl.InitWindow(int32(Width), int32(Height), "Simple renderer with raylib")
defer rl.CloseWindow()
rl.SetTargetFPS(int32(*fps))
rl.DisableCursor()
rfb := NewRaylibBuffer(Width, Height)
defer rl.UnloadTexture(rfb.Texture)
defer rl.UnloadImageColors(rfb.Data)
defer rl.UnloadImage(rfb.Image)
fb = rfb
drawFunc = func() {
rl.UpdateTexture(rfb.Texture, rfb.Data)
rl.BeginDrawing()
rl.ClearBackground(rl.RayWhite)
rl.DrawTexture(rfb.Texture, 0, 0, rl.White)
rl.DrawText(fmt.Sprintf("Frame: %.2fms", timer.LastAverage.Seconds()*1000), 5, 5, 20, rl.Red)
rl.EndDrawing()
}
} else {
}
rb := hrend.NewRenderbuffer(fb, Width, Height)
// Generate world
wtexraw := Checkerboard([]color.Color{color.RGBA{R: 0, G: 255, B: 0, A: 255}, color.RGBA{R: 50, G: 150, B: 0, A: 255}}, 32)
wtex := hrend.NewTexture(wtexraw, 1)
world := DiamondSquareTerrain(32, 0.05, 9) // must be power of two
// Generate skybox
skyraw := Gradient1px(color.RGBA{R: 100, G: 100, B: 255, A: 255}, color.RGBA{R: 0, G: 0, B: 25, A: 255}, 32)
skytex := hrend.NewTexture(skyraw, 1)
sky := Skybox()
// Some static models we could put in the scene
modnames := []string{"head", "diablo"}
models := make([]*hrend.ObjModel, len(modnames))
textures := make([]hrend.Framebuffer, len(modnames))
for i, name := range modnames {
models[i], textures[i] = loadObject(name)
}
// And the actual objects for the scene. We also put the world in there
objects := make([]*hrend.ObjectDef, 0)
objects = append(objects, hrend.NewObjectDef(world, wtex))
worldobj := objects[len(objects)-1]
worldobj.Pos.Y -= 5
worldobj.Color = hrend.Vec3f{X: 0.0, Y: 1.0, Z: 0.0}
objects = append(objects, hrend.NewObjectDef(sky, skytex)) // the actual skybox
skyobj := objects[len(objects)-1]
skyobj.Scale = 50
skyobj.Lighting = false
skyobj.Color = hrend.Vec3f{X: 0.5, Y: 0.5, Z: 1.0}
objects = append(objects, hrend.NewObjectDef(models[1], textures[1]))
diabloobj := objects[len(objects)-1]
diabloobj.Pos.Y += 1
diabloobj.Pos.Z -= 2
diabloobj.Color = hrend.Vec3f{X: 1.0, Y: 0.0, Z: 0.0}
//diabloobj.Lighting = false
// These don't really change
var projection hrend.Mat44f
projection.SetProjection(float32(*fov), float32(Width)/float32(Height), NearClip, FarClip)
var camera hrend.Mat44f
var newcamtrans hrend.Vec3f
camtrans := hrend.Vec3f{X: float32(*xofs), Y: float32(*yofs), Z: float32(*zofs)}
camup := hrend.Vec3f{X: 0, Y: 1, Z: 0}
lightang := -math.Pi / 4 // Angle offset from "straight down"
light := hrend.Vec3f{X: 0, Y: float32(-math.Cos(lightang)), Z: float32(math.Sin(lightang))}
// In our system, 0 degree yaw is facing -Z, into the scene
yaw := float32(0)
pitch := float32(math.Pi / 2) // Start looking flat
log.Printf("Starting render loop")
for !rl.WindowShouldClose() {
start := time.Now()
yaw, pitch, newcamtrans = CameraInput(yaw, pitch)
camtrans = *camtrans.Add(&newcamtrans)
_ = camera.SetCamera(&camtrans, yaw, pitch, &camup)
screenmat := camera.Inverse().Multiply(&projection)
rb.ResetZBuffer()
for y := range Height {
for x := range Width {
fb.Set(x, y, 0, 0, 0)
}
}
var modelmat hrend.Mat44f
var intensity float32
outvecs := make([]hrend.HVec3f, 0, 65536)
for _, o := range objects {
// Create the final matrix
modelmat.SetLookAt(&o.Pos, o.Pos.Add(&o.LookVec), &camup)
modelmat.ScaleSelf(o.Scale)
matrix3d := modelmat.Multiply(screenmat)
outvecs = hrend.PerspectiveAll(o.Model.Vertices, matrix3d, outvecs)
for _, f := range o.Model.Faces {
// Generate the new amount of triangles for each face (could be clipped)
//func ClipFace(face Facei, vecs []HVec3f, texs []Vec3f) []Facef {
for _, sc := range hrend.ClipFace(f, outvecs, o.Model.VTexture) {
for i := range 3 {
// Screen coord mapping
sc[i].Pos.ViewportSelf(*width, *height)
}
//log.Print(sc[0].Pos, sc[1].Pos, sc[2].Pos, matrix3d)
if o.Lighting {
l1 := o.FV(&f, 2).Sub(o.FV(&f, 0))
n := l1.CrossProduct(o.FV(&f, 1).Sub(o.FV(&f, 0)))
n = n.Normalize()
// light = lookvec // use this for weird things
intensity = n.MultSimp(&light)
if intensity < 0 {
intensity = 0 // Don't just not draw the triangle: it should be black
}
intensity = (intensity + float32(*minlight)) / (1 + float32(*minlight))
} else {
intensity = 1.0
}
hrend.TriangleTextured(&rb, o.Texture, intensity, &sc) //sc[0], sc[1], sc[2])
//hrend.TriangleFlat(&rb, o.Color.Scale(intensity), sc[0].Pos, sc[1].Pos, sc[2].Pos)
}
//break // only render one face
//hrend.TriangleFlat(&rb, hrend.Col2Uint(byte(255*intensity), byte(255*intensity), byte(255*intensity)), sc[0].Pos, sc[1].Pos, sc[2].Pos)
}
//break // only render one object
}
//log.Print(minz, maxz)
timer.Add(time.Since(start), 10)
drawFunc()
}
}

70
renderer4/raybuffer.go Normal file
View File

@ -0,0 +1,70 @@
package main
import (
rl "github.com/gen2brain/raylib-go/raylib"
"log"
)
type RaylibBuffer struct {
Data []rl.Color
Image *rl.Image
Texture rl.Texture2D
Width uint
Height uint
}
func NewRaylibBuffer(width uint, height uint) *RaylibBuffer {
log.Printf("Creating new raylib framebuffer using texture + image")
//rl.NewTexture2D(1, Width, Height, 0, )
rlimage := rl.GenImageColor(int(width), int(height), rl.Black)
rl.ImageFormat(rlimage, rl.UncompressedR8g8b8a8)
log.Printf("Generated baseline image: %v", rlimage)
rltexture := rl.LoadTextureFromImage(rlimage)
log.Printf("Generated texture from image")
data := rl.LoadImageColors(rlimage)
log.Printf("Generated pixel data from image")
return &RaylibBuffer{
Data: data,
Image: rlimage,
Texture: rltexture,
Width: width,
Height: height,
}
}
func (fb *RaylibBuffer) Dims() (uint, uint) {
return fb.Width, fb.Height
}
// Sure hope this gets inlined...
func (fb *RaylibBuffer) Set(x uint, y uint, r byte, g byte, b byte) {
// if x >= fb.Width || y >= fb.Height {
// return
// }
// fb.Data[x+y*fb.Width].R = r
// fb.Data[x+y*fb.Width].G = g
// fb.Data[x+y*fb.Width].B = b
c := &fb.Data[x+y*fb.Width]
c.R = r
c.G = g
c.B = b
}
func (fb *RaylibBuffer) Get(x uint, y uint) (byte, byte, byte) {
if x >= fb.Width || y >= fb.Height {
return 0, 0, 0
}
return fb.Data[x+y*fb.Width].R,
fb.Data[x+y*fb.Width].G,
fb.Data[x+y*fb.Width].B
}
func (fb *RaylibBuffer) GetUv(u float32, v float32) (byte, byte, byte) {
x := uint(float32(fb.Width)*u) & (fb.Width - 1)
y := uint(float32(fb.Height)*(1-v)) & (fb.Height - 1)
c := &fb.Data[x+y*fb.Width]
return c.R, c.G, c.B
// fb.Data[x+y*fb.Width].R,
// fb.Data[x+y*fb.Width].G,
// fb.Data[x+y*fb.Width].B
}

3
renderer4/runopengl21.sh Executable file
View File

@ -0,0 +1,3 @@
#!/bin/sh
go build -tags opengl21 -o renderer
./renderer