Move clipping to triangle drawing

This commit is contained in:
Carlos Sanchez 2024-07-31 01:17:09 -04:00
parent 4a399c7bb7
commit 6dce4e3a83
2 changed files with 23 additions and 19 deletions

View File

@ -36,7 +36,15 @@ 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 < 0 || maxz > 1
}
func TriangleFlat(fb *RenderBuffer, color uint, v0f Vec3f, v1f Vec3f, v2f Vec3f) {
if ZClip(v0f, v1f, v2f) {
return
}
v0 := v0f.ToVec2i()
v1 := v1f.ToVec2i()
v2 := v2f.ToVec2i()
@ -103,6 +111,9 @@ func TriangleFlat(fb *RenderBuffer, color uint, v0f Vec3f, v1f Vec3f, v2f Vec3f)
}
func TriangleTextured(fb *RenderBuffer, texture Framebuffer, intensity float32, v0v Vertex, v1v Vertex, v2v Vertex) {
if ZClip(v0v.Pos, v1v.Pos, v2v.Pos) {
return
}
v0 := v0v.Pos.ToVec2i()
v1 := v1v.Pos.ToVec2i()
v2 := v2v.Pos.ToVec2i()

View File

@ -5,7 +5,6 @@ import (
"fmt"
"image"
"log"
"math"
"os"
"renderer1/hrend"
"runtime/pprof" // For performance profiling (unnecessary)
@ -91,11 +90,11 @@ func main() {
rb := hrend.NewRenderbuffer(fb, Width, Height)
o, texture := loadDefault()
light := hrend.Vec3f{
X: 0,
Y: 0,
Z: -1,
}
// light := hrend.Vec3f{
// X: 0,
// Y: 0,
// Z: -1,
// }
var thing hrend.Vec2i
log.Print(thing)
@ -158,24 +157,18 @@ func main() {
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]hrend.Vec3f
maxz := float32(-math.MaxFloat32)
//var fpt [3]hrend.Vec3f
for i := range 3 { // Triangles, bro
sc[i] = f[i]
sc[i].Pos = screenmat.MultiplyPoint3(f[i].Pos)
fpt[i] = worldToCamera.MultiplyPoint3(f[i].Pos)
maxz = max(maxz, sc[i].Pos.Z)
//fpt[i] = worldToCamera.MultiplyPoint3(f[i].Pos)
}
if maxz < 0 || maxz > 1 {
//log.Printf("Clipping %f %f %f", sc[0].Pos.Z, sc[1].Pos.Z, sc[2].Pos.Z)
continue
}
l1 := fpt[2].Sub(fpt[0])
n := l1.CrossProduct(fpt[1].Sub(fpt[0]))
n = n.Normalize()
intensity := n.MultSimp(&light)
//l1 := fpt[2].Sub(fpt[0])
//n := l1.CrossProduct(fpt[1].Sub(fpt[0]))
//n = n.Normalize()
//intensity := n.MultSimp(&light)
intensity := float32(1.0)
if intensity > 0 {
hrend.TriangleTextured(&rb, texture, intensity, sc[0], sc[1], sc[2])
//hrend.TriangleFlat(&rb, hrend.Col2Uint(byte(255*intensity), byte(255*intensity), byte(255*intensity)), sc[0].Pos, sc[1].Pos, sc[2].Pos)