package obj
import "core:os"
import "core:path/filepath"
import "core:slice"
import "core:strconv"
import "core:strings"
import rb "../../render_backend"
import "../../renderer"
OBJ_Model :: struct {
meshes: []OBJ_Mesh,
materials: []OBJ_Material,
}
OBJ_Mesh :: struct {
name: string,
geometry: renderer.Mesh_Data,
material_index: int,
}
OBJ_Material :: struct {
name: string,
diffuse_color: [3]f32,
diffuse_map: string,
}
Field_Spec :: enum {
x,
y,
z,
u,
v,
r,
g,
b,
a_vertex,
a_tex_coord,
a_normal,
b_vertex,
b_tex_coord,
b_normal,
c_vertex,
c_tex_coord,
c_normal,
}
Field_Parse_Error :: struct {
line: int,
field: Field_Spec,
}
Missing_Field_Error :: struct {
line: int,
field: Field_Spec,
}
Material_Field_Parse_Error :: struct {
line: int,
field: Field_Spec,
}
Material_Missing_Field_Error :: struct {
line: int,
field: Field_Spec,
}
Invalid_Index_error :: struct {
line: int,
requested: int,
available: int,
field: Field_Spec,
}
File_Error :: struct {
path: string,
cause: os.Error,
}
Error :: union {
Field_Parse_Error,
Missing_Field_Error,
Material_Field_Parse_Error,
Material_Missing_Field_Error,
Invalid_Index_error,
File_Error,
}
load_from_file :: proc(filename: string, allocator := context.allocator) -> (obj_model: OBJ_Model, err: Error) {
context.allocator = allocator
buf, buf_err := os.read_entire_file_from_path(filename, allocator)
ensure(buf_err == nil)
defer delete(buf)
mesh_basepath := filepath.dir(filename)
obj_vertices := make([dynamic][6]f32, 0, 100)
ensure(obj_vertices != nil)
defer delete(obj_vertices)
obj_tex_coords := make([dynamic][2]f32, 0, 100)
ensure(obj_tex_coords != nil)
defer delete(obj_tex_coords)
obj_normals := make([dynamic][3]f32, 0, 100)
ensure(obj_normals != nil)
defer delete(obj_normals)
obj_faces := make([dynamic]Face, 0, 100)
defer delete(obj_faces)
meshes: [dynamic]OBJ_Mesh
materials: [dynamic]OBJ_Material
defer delete(meshes)
defer delete(materials)
mesh: OBJ_Mesh
read_first_mesh := false
strbuf := string(buf)
line_nr: int
for line in strings.split_lines_iterator(&strbuf) {
line_nr += 1
first_space := strings.index(line, " ")
if first_space < 0 {
continue
}
command := line[:first_space]
args := line[first_space + 1:]
switch command {
case "mtllib":
load_mtl_file_data(args, mesh_basepath, &materials) or_return
case "usemtl":
for &m, i in materials {
if m.name == args {
mesh.material_index = i
}
}
case "o":
if read_first_mesh {
mesh.geometry = generate_geometry(obj_vertices, obj_tex_coords, obj_normals, obj_faces, allocator)
append(&meshes, mesh)
clear(&obj_faces)
}
read_first_mesh = true
mesh = {}
mesh.name = strings.clone(args)
mesh.material_index = -1
case "v":
part: string
ok: bool
x, y, z: f32
r, g, b: f32 = 1, 1, 1
iter := line[2:]
if part, ok = strings.split_iterator(&iter, " "); !ok {
return {}, Missing_Field_Error{line = line_nr, field = .x}
}
if x, ok = strconv.parse_f32(part); !ok {
return {}, Field_Parse_Error{line = line_nr, field = .x}
}
if part, ok = strings.split_iterator(&iter, " "); !ok {
return {}, Missing_Field_Error{line = line_nr, field = .y}
}
if y, ok = strconv.parse_f32(part); !ok {
return {}, Field_Parse_Error{line = line_nr, field = .y}
}
if part, ok = strings.split_iterator(&iter, " "); !ok {
return {}, Missing_Field_Error{line = line_nr, field = .z}
}
if z, ok = strconv.parse_f32(part); !ok {
return {}, Field_Parse_Error{line = line_nr, field = .z}
}
if part, ok = strings.split_iterator(&iter, " "); ok {
if r, ok = strconv.parse_f32(part); !ok {
return {}, Field_Parse_Error{line = line_nr, field = .r}
}
if part, ok = strings.split_iterator(&iter, " "); !ok {
return {}, Missing_Field_Error{line = line_nr, field = .g}
}
if g, ok = strconv.parse_f32(part); !ok {
return {}, Field_Parse_Error{line = line_nr, field = .g}
}
if part, ok = strings.split_iterator(&iter, " "); !ok {
return {}, Missing_Field_Error{line = line_nr, field = .b}
}
if b, ok = strconv.parse_f32(part); !ok {
return {}, Field_Parse_Error{line = line_nr, field = .b}
}
}
append(&obj_vertices, {x, y, z, r, g, b})
case "vt":
part: string
ok: bool
u, v: f32
iter := line[3:]
if part, ok = strings.split_iterator(&iter, " "); !ok {
return {}, Missing_Field_Error{line = line_nr, field = .u}
}
if u, ok = strconv.parse_f32(part); !ok {
return {}, Field_Parse_Error{line = line_nr, field = .u}
}
if part, ok = strings.split_iterator(&iter, " "); !ok {
return {}, Missing_Field_Error{line = line_nr, field = .v}
}
if v, ok = strconv.parse_f32(part); !ok {
return {}, Field_Parse_Error{line = line_nr, field = .v}
}
// NOTE: Flip UVs due to "obj silliness"
v = 1.0 - v
append(&obj_tex_coords, {u, v})
case "vn":
part: string
ok: bool
x, y, z: f32
iter := line[3:]
if part, ok = strings.split_iterator(&iter, " "); !ok {
return {}, Missing_Field_Error{line = line_nr, field = .x}
}
if x, ok = strconv.parse_f32(part); !ok {
return {}, Field_Parse_Error{line = line_nr, field = .x}
}
if part, ok = strings.split_iterator(&iter, " "); !ok {
return {}, Missing_Field_Error{line = line_nr, field = .y}
}
if y, ok = strconv.parse_f32(part); !ok {
return {}, Field_Parse_Error{line = line_nr, field = .y}
}
if part, ok = strings.split_iterator(&iter, " "); !ok {
return {}, Missing_Field_Error{line = line_nr, field = .z}
}
if z, ok = strconv.parse_f32(part); !ok {
return {}, Field_Parse_Error{line = line_nr, field = .z}
}
append(&obj_normals, {x, y, z})
case "f":
part: string
fa, fb, fc: int
ta, tb, tc: int
na, nb, nc: int
ok: bool
iter := line[2:]
// Face indice
if part, ok = strings.split_iterator(&iter, " "); !ok {
return {}, Missing_Field_Error{line = line_nr}
}
indices := strings.split(part, "/", allocator)
ensure(indices != nil)
if fa, ok = strconv.parse_int(indices[0]); !ok {
return {}, Field_Parse_Error{line = line_nr}
}
// Texel indice
if ta, ok = strconv.parse_int(indices[1]); !ok {
return {}, Field_Parse_Error{line = line_nr}
}
// Normal indice
if na, ok = strconv.parse_int(indices[2]); !ok {
return {}, Field_Parse_Error{line = line_nr}
}
delete(indices, allocator)
// Face indice
if part, ok = strings.split_iterator(&iter, " "); !ok {
return {}, Missing_Field_Error{line = line_nr}
}
indices = strings.split(part, "/", allocator)
ensure(indices != nil)
if fb, ok = strconv.parse_int(indices[0]); !ok {
return {}, Field_Parse_Error{line = line_nr}
}
// Texel indice
if tb, ok = strconv.parse_int(indices[1]); !ok {
return {}, Field_Parse_Error{line = line_nr}
}
// Normal indice
if nb, ok = strconv.parse_int(indices[2]); !ok {
return {}, Field_Parse_Error{line = line_nr}
}
delete(indices, allocator)
// Face indice
if part, ok = strings.split_iterator(&iter, " "); !ok {
return {}, Missing_Field_Error{line = line_nr}
}
indices = strings.split(part, "/", allocator)
ensure(indices != nil)
if fc, ok = strconv.parse_int(indices[0]); !ok {
return {}, Field_Parse_Error{line = line_nr}
}
// Texel indice
if tc, ok = strconv.parse_int(indices[1]); !ok {
return {}, Field_Parse_Error{line = line_nr}
}
// Normal indice
if nc, ok = strconv.parse_int(indices[2]); !ok {
return {}, Field_Parse_Error{line = line_nr}
}
delete(indices, allocator)
if fa <= 0 || fa > len(obj_vertices) {
return {}, Invalid_Index_error{line = line_nr, requested = fa, available = len(obj_vertices), field = .a_vertex}
}
if ta <= 0 || ta > len(obj_tex_coords) {
return {}, Invalid_Index_error{line = line_nr, requested = ta, available = len(obj_tex_coords), field = .a_tex_coord}
}
if na <= 0 || na > len(obj_normals) {
return {}, Invalid_Index_error{line = line_nr, requested = na, available = len(obj_normals), field = .a_normal}
}
if fb <= 0 || fb > len(obj_vertices) {
return {}, Invalid_Index_error{line = line_nr, requested = fb, available = len(obj_vertices), field = .b_vertex}
}
if tb <= 0 || tb > len(obj_tex_coords) {
return {}, Invalid_Index_error{line = line_nr, requested = tb, available = len(obj_tex_coords), field = .b_tex_coord}
}
if nb <= 0 || nb > len(obj_normals) {
return {}, Invalid_Index_error{line = line_nr, requested = nb, available = len(obj_normals), field = .b_normal}
}
if fc <= 0 || fc > len(obj_vertices) {
return {}, Invalid_Index_error{line = line_nr, requested = fc, available = len(obj_vertices), field = .c_vertex}
}
if tc <= 0 || tc > len(obj_tex_coords) {
return {}, Invalid_Index_error{line = line_nr, requested = tc, available = len(obj_tex_coords), field = .c_tex_coord}
}
if nc <= 0 || nc > len(obj_normals) {
return {}, Invalid_Index_error{line = line_nr, requested = nc, available = len(obj_normals), field = .c_normal}
}
append(
&obj_faces,
{
{vertex = fa, tex = ta, normal = na},
{vertex = fb, tex = tb, normal = nb},
{vertex = fc, tex = tc, normal = nc},
},
)
}
}
// NOTE: This being false would signal there's not even _one_ mesh in the file.
if read_first_mesh {
// NOTE: Final add to make sure all meshes (or the single one) has been stored
mesh.geometry = generate_geometry(obj_vertices, obj_tex_coords, obj_normals, obj_faces, allocator)
append(&meshes, mesh)
obj_model.meshes = slice.clone(meshes[:])
obj_model.materials = slice.clone(materials[:])
}
return
}
destroy :: proc(obj: ^OBJ_Model) {
if obj == nil {
return
}
for &m in obj.materials {
delete(m.name)
delete(m.diffuse_map)
}
delete(obj.materials)
for &m in obj.meshes {
delete(m.name)
delete(m.geometry.vertices)
delete(m.geometry.indices)
}
delete(obj.meshes)
obj.materials = nil
obj.meshes = nil
}
@(private)
generate_geometry :: proc(
obj_vertices: [dynamic][6]f32,
obj_tex_coords: [dynamic][2]f32,
obj_normals: [dynamic][3]f32,
obj_faces: [dynamic]Face,
allocator := context.allocator,
) -> renderer.Mesh_Data {
vertices := make([dynamic]rb.Vertex, 0, 100)
ensure(vertices != nil)
defer delete(vertices)
indices := make([dynamic]u32, 0, 100)
ensure(indices != nil)
defer delete(indices)
lookup: map[Vertex_Key]u32
for face in obj_faces {
for corner in face {
key := Vertex_Key(corner)
index, found := lookup[key]
if !found {
index = u32(len(vertices))
// NOTE: Subtract 1 since obj is 1-indexed
v := obj_vertices[key.vertex - 1]
append(
&vertices,
{
position = {v[0], v[1], v[2]},
tex_coords = obj_tex_coords[key.tex - 1],
// normal = obj_normals[key.normal - 1],
color = {v[3], v[4], v[5], 1},
},
)
lookup[key] = index
}
append(&indices, index)
}
}
cloned_vertices := slice.clone(vertices[:], allocator)
ensure(cloned_vertices != nil)
cloned_indices := slice.clone(indices[:], allocator)
ensure(cloned_indices != nil)
return {vertices = cloned_vertices, indices = cloned_indices}
}
@(private)
load_mtl_file_data :: proc(
filename: string,
basepath: string,
materials: ^[dynamic]OBJ_Material,
allocator := context.allocator,
) -> Error {
mtl_filepath, mtl_err := filepath.join({basepath, filename}, context.temp_allocator)
ensure(mtl_err == nil)
buf, buf_err := os.read_entire_file_from_path(mtl_filepath, allocator)
if buf_err != nil {
return File_Error{path = filename, cause = buf_err}
}
defer delete(buf)
material: OBJ_Material
read_first_material := false
strbuf := string(buf)
line_nr: int
for line in strings.split_lines_iterator(&strbuf) {
line_nr += 1
first_space := strings.index(line, " ")
if first_space < 0 {
continue
}
command := line[:first_space]
args := line[first_space + 1:]
switch command {
case "newmtl":
if read_first_material {
append(materials, material)
}
read_first_material = true
name, name_err := strings.clone(args, allocator)
ensure(name_err == nil)
material = {}
material.name = name
case "Ns":
_, ok := strconv.parse_f32(args)
if !ok {
return Material_Field_Parse_Error{line = line_nr}
}
// material.specular_exp = v
case "Ka":
part: string
ok: bool
r, g, b: f32
iter := args
if part, ok = strings.split_iterator(&iter, " "); !ok {
return Material_Missing_Field_Error{line = line_nr}
}
if r, ok = strconv.parse_f32(part); !ok {
return Material_Field_Parse_Error{line = line_nr}
}
if part, ok = strings.split_iterator(&iter, " "); !ok {
return Material_Missing_Field_Error{line = line_nr}
}
if g, ok = strconv.parse_f32(part); !ok {
return Material_Field_Parse_Error{line = line_nr}
}
if part, ok = strings.split_iterator(&iter, " "); !ok {
return Material_Missing_Field_Error{line = line_nr}
}
if b, ok = strconv.parse_f32(part); !ok {
return Material_Field_Parse_Error{line = line_nr}
}
// material.ambient_color = {r, g, b}
case "Kd":
part: string
ok: bool
r, g, b: f32
iter := args
if part, ok = strings.split_iterator(&iter, " "); !ok {
return Material_Missing_Field_Error{line = line_nr}
}
if r, ok = strconv.parse_f32(part); !ok {
return Material_Field_Parse_Error{line = line_nr}
}
if part, ok = strings.split_iterator(&iter, " "); !ok {
return Material_Missing_Field_Error{line = line_nr}
}
if g, ok = strconv.parse_f32(part); !ok {
return Material_Field_Parse_Error{line = line_nr}
}
if part, ok = strings.split_iterator(&iter, " "); !ok {
return Material_Missing_Field_Error{line = line_nr}
}
if b, ok = strconv.parse_f32(part); !ok {
return Material_Field_Parse_Error{line = line_nr}
}
material.diffuse_color = {r, g, b}
case "Ks":
part: string
ok: bool
r, g, b: f32
iter := args
if part, ok = strings.split_iterator(&iter, " "); !ok {
return Material_Missing_Field_Error{line = line_nr}
}
if r, ok = strconv.parse_f32(part); !ok {
return Material_Field_Parse_Error{line = line_nr}
}
if part, ok = strings.split_iterator(&iter, " "); !ok {
return Material_Missing_Field_Error{line = line_nr}
}
if g, ok = strconv.parse_f32(part); !ok {
return Material_Field_Parse_Error{line = line_nr}
}
if part, ok = strings.split_iterator(&iter, " "); !ok {
return Material_Missing_Field_Error{line = line_nr}
}
if b, ok = strconv.parse_f32(part); !ok {
return Material_Field_Parse_Error{line = line_nr}
}
// material.specular_color = {r, g, b}
case "map_Kd":
diffuse_map, diffuse_err := filepath.join({basepath, args}, context.allocator)
ensure(diffuse_err == nil)
material.diffuse_map = diffuse_map
case "map_Bump":
/*
material.normal_map, err = filepath.join({basepath, args}, context.allocator)
*/
}
}
// NOTE: This being false would signal there's not even _one_ material in the file.
if read_first_material {
// NOTE: Final add to make sure all materials (or the single one) has been stored
append(materials, material)
}
return nil
}
@(private)
Face :: [3]struct {
vertex: int,
tex: int,
normal: int,
}
@(private)
Vertex_Key :: struct {
vertex: int,
tex: int,
normal: int,
}