Working on object parser

This commit is contained in:
Carlos Sanchez 2024-07-23 22:27:01 -04:00
parent ff7ea1cf25
commit 64d3525a2a
5 changed files with 6429 additions and 0 deletions

View File

@ -1,3 +1,5 @@
module tinyrender1 module tinyrender1
go 1.22.5 go 1.22.5
require github.com/udhos/gwob v1.0.0

2
tinyrender1/go.sum Normal file
View File

@ -0,0 +1,2 @@
github.com/udhos/gwob v1.0.0 h1:P9br9SLca7H5Hr/WuEcO9+ViUm+wlQnr4vxpPU6c6ww=
github.com/udhos/gwob v1.0.0/go.mod h1:xj4qGbkwL1sTPm1V17NfcIhkgG2rjfb8cUv9YIqE6DE=

6357
tinyrender1/head.obj Normal file

File diff suppressed because it is too large Load Diff

View File

@ -6,6 +6,8 @@ import (
"log" "log"
"os" "os"
"runtime/pprof" // For performance whatever "runtime/pprof" // For performance whatever
"github.com/udhos/gwob"
) )
const ( const (

66
tinyrender1/obj.go Normal file
View File

@ -0,0 +1,66 @@
package main
// This reads obj files?
import (
"bufio"
"fmt"
"io"
"strings"
)
type Vec3f struct {
X, Y, Z float32
}
type Facef [3]Vec3f
type ObjModel struct {
Vertices []Vec3f
Faces []Facef
}
func ParseObj(reader io.Reader) (*ObjModel, error) {
result := ObjModel{
Vertices: make([]Vec3f, 0),
Faces: make([]Facef, 0),
}
scanner := bufio.NewScanner(reader)
for scanner.Scan() {
// Scan a line
line := strings.Trim(scanner.Text(), " \t")
// 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 {
return nil, err
}
line = line[len(t):]
if t == "v" {
// Read a vertex, should be just three floats
var vertex Vec3f
_, err := fmt.Sscan(line, vertex.X, vertex.Y, vertex.Z)
if err != nil {
return nil, err
}
result.Vertices = append(result.Vertices, vertex)
} 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
for i := range 3 {
var vi, ti0, ti1 int
_, err := fmt.Sscanf(line, "%d/%d/%d", vi, ti0, ti1)
if err != nil {
return nil, err
}
if vi > len(result.Vertices) || vi < 1 {
return nil, fmt.Errorf("Face vertex index out of bounds: %d", vi)
}
face[i] = result.Vertices[vi-1]
}
result.Faces = append(result.Faces, face)
}
}
return &result, nil
}