Initial project import

This commit is contained in:
Agila Forge Importer committed 2026-07-13 15:20:32 +00:00
commit 23f2d29e32
11957 files changed
+1754577

No files matched your search

@@ -0,0 +1,26 @@
# Blender MTL File: 'None'
# Material Count: 2
newmtl Material.001
Ns 96.078443
Ka 1.000000 1.000000 1.000000
Kd 0.640000 0.640000 0.640000
Ks 0.500000 0.500000 0.500000
Ke 0.000000 0.000000 0.000000
Ni 1.000000
d 1.000000
illum 2
map_Kd apple.png
newmtl Material.002
Ns 96.078443
Ka 1.000000 1.000000 1.000000
Kd 0.640000 0.640000 0.640000
Ks 0.500000 0.500000 0.500000
Ke 0.000000 0.000000 0.000000
Ni 1.000000
d 1.000000
illum 2
map_Kd apple.png
Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

@@ -0,0 +1,12 @@
# Blender MTL File: 'donut.blend'
# Material Count: 1
newmtl Material.001
Ns 225.000000
Ka 1.000000 1.000000 1.000000
Kd 0.800000 0.800000 0.800000
Ks 0.500000 0.500000 0.500000
Ke 0.259059 0.005681 0.342383
Ni 1.450000
d 0.800000
illum 9
@@ -0,0 +1,20 @@
# Blender MTL File: 'v-logo.blend'
# Material Count: 2
newmtl Material.001
Ns 96.078431
Ka 0.2 0.2 0.2
Kd 0.365 0.529 0.749
Ks 0.85 0.85 0.85
Ke 0 0 0
Ni 1
d 1
illum 1
newmtl Material.002
Ns 96.078431
Ka 0.1 0.1 0.1
Kd 0.325 0.42 0.541
Ks 0.85 0.85 0.85
Ke 0 0 0
Ni 1
d 1
illum 1
@@ -0,0 +1,109 @@
//#pragma sokol @ctype mat4 hmm_mat4
#pragma sokol @vs vs
uniform vs_params {
mat4 u_MVMatrix; // A constant representing the combined model/view matrix.
mat4 u_MVPMatrix; // A constant representing the combined model/view/projection matrix.
mat4 u_NMatrix; // A constant representing the Normal Matrix
};
in vec4 a_Position; // Per-vertex position information we will pass in.
in vec3 a_Normal; // Per-vertex normal information we will pass in.
//in vec4 a_Color; // Per-vertex color information we will pass in.
in vec2 a_Texcoord0;
out vec3 v_Position; // This will be passed into the fragment shader.
//out vec4 v_Color; // This will be passed into the fragment shader.
out vec3 v_Normal; // This will be passed into the fragment shader.
out vec3 v_Normal1;
out vec2 uv; // This will be passed into the fragment shader.
// The entry point for our vertex shader.
void main()
{
// Transform the vertex into eye space.
v_Position = vec3(u_MVMatrix * a_Position);
// Pass through the color.
//v_Color = a_Color;
// calc eye space normal
v_Normal = vec3(u_NMatrix * vec4(a_Normal, 1.0));
// texture coord
uv = a_Texcoord0;
v_Normal1 = normalize(vec3(u_MVMatrix * vec4(a_Normal, 1.0)));
// gl_Position is a special variable used to store the final position.
// Multiply the vertex by the matrix to get the final point in normalized screen coordinates.
gl_Position = u_MVPMatrix * a_Position;
}
#pragma sokol @end
#pragma sokol @fs fs
//precision mediump float; // Set the default precision to medium. We don't need as high of a precision in the fragment shader
uniform texture2D tex;
uniform sampler smp;
uniform fs_params {
vec4 u_LightPos; // The position of the light in eye space.
vec4 ambientColor;
vec4 diffuseColor;
vec4 specularColor;
};
in vec3 v_Position; // Interpolated position for this fragment.
//in vec4 v_Color; // This is the color from the vertex shader interpolated across the triangle per fragment.
in vec3 v_Normal; // Interpolated normal for this fragment.
in vec3 v_Normal1;
in vec2 uv;
out vec4 frag_color;
vec3 lightDirection = -u_LightPos.xyz;// vec3(0.0, -0.5, 0.5);
//const vec4 ambientColor = vec4(0.094, 0.0, 0.0, 1.0);
//const vec4 diffuseColor = vec4(0.5, 0.0, 0.0, 1.0);
//const vec4 specularColor = vec4(1.0, 1.0, 1.0, 1.0);
//const float shininess = 10.0;
const vec4 lightColor = vec4(1.0, 1.0, 1.0, 1.0);
vec3 phongBRDF(vec3 lightDir, vec3 viewDir, vec3 normal, vec3 phongDiffuseCol, vec3 phongSpecularCol, float phongShininess) {
vec3 color = phongDiffuseCol;
vec3 reflectDir = reflect(-lightDir, normal);
float specDot = max(dot(reflectDir, viewDir), 0.0);
color += pow(specDot, phongShininess) * phongSpecularCol;
return color;
}
vec4 getPhong(in vec4 diffuseColor) {
vec3 lightDir = normalize(-lightDirection);
vec3 viewDir = normalize(-v_Position);
vec3 n = normalize(v_Normal);
vec3 luminance = ambientColor.rgb * 0.5;
float illuminance = dot(lightDir, n);
if(illuminance > 0.0) {
// we save specular shiness in specularColor.a
vec3 brdf = phongBRDF(lightDir, viewDir, n, diffuseColor.rgb, specularColor.rgb, specularColor.a * 1000);
luminance += brdf * illuminance * lightColor.rgb;
}
vec4 outColor = vec4(luminance,1.0);
return outColor;
}
// The entry point for our fragment shader.
void main()
{
vec4 txt = texture(sampler2D(tex, smp), uv);
// Directional light
float directional = dot(normalize(v_Normal1), normalize(vec3(0,0.5,1))) ;
directional = directional * 0.15;
// Multiply the color by the diffuse illumination level to get final output color.
frag_color = vec4(clamp(directional + txt.rgb * getPhong(diffuseColor).rgb,0,1), txt.a * diffuseColor.a);
}
#pragma sokol @end
#pragma sokol @program gouraud vs fs
@@ -0,0 +1,597 @@
module obj
/**********************************************************************
*
* .obj loader
*
* Copyright (c) 2021 Dario Deledda. All rights reserved.
* Use of this source code is governed by an MIT license
* that can be found in the LICENSE file.
*
* TODO:
**********************************************************************/
import gg.m4
import strconv
enum F_state {
start
first
ints
decimals
exp_start
exp_sign
exp_int
}
// read a int from a string
fn get_int(s string, start_index int) (int, int) {
mut i := start_index
mut res := 0
mut sgn := 1
mut state := F_state.start
for true {
if i >= s.len {
break
}
c := s[i]
if state == .start {
match c {
`+` {
i++
state = .ints
continue
}
`-` {
sgn = -1
i++
state = .ints
continue
}
`0`...`9` {
state = .ints
}
` `, `\t` {
i++
continue
}
else { // no number found
break
}
}
}
if state == .ints {
match c {
`0`...`9` {
// println("${res} => ${(int(c) - 48)}")
res = res * 10 + (int(c) - 48)
i++
continue
}
else {
break
}
}
}
}
// println("---")
return res * sgn, i
}
// reas a float number from a string
fn get_float(s string, start_index int) (f64, int) {
mut i1 := start_index //+ 1
for i1 < s.len && s[i1] in [` `, `\t`] {
i1++
}
mut i := i1
for i < s.len {
if s[i] in [` `, `\t`] {
break
}
i++
}
// println(" get_float: (${start_index},${i}) [${s[start_index..i]}]")
// f_res := strconv.atof_quick(s[start_index..i])
f_res := strconv.atof_quick(s[i1..i])
return f_res, i
}
// read 3 f32 in sequence from a string
fn parse_3f(row string, start_index int) m4.Vec4 {
// println(row)
mut i := start_index //+ 1
mut f1 := f64(0)
mut f2 := f64(0)
f0, mut p := get_float(row, i)
// print("Here f0: ${f0} ${p} ")
f1, p = get_float(row, p + 1)
// print("Here f1: ${f1} ${p} ")
f2, p = get_float(row, p + 1)
// print("Here f2: ${f2} ${p} ")
return m4.Vec4{
e: [f32(f0), f32(f1), f32(f2), 1]!
}
}
// reas a sequence of f32 from a string
fn (mut m ObjPart) parse_floats(row string, start_index int) m4.Vec4 {
mut i := start_index //+ 1
mut res_f := f64(0)
mut res := m4.Vec4{
e: [f32(0), 0, 0, 1]!
}
mut c := 0
for true {
res_f, i = get_float(row, i)
unsafe {
res.e[c] = f32(res_f)
}
c++
i++
if i >= row.len {
break
}
}
return res
}
// read and manage all the faes from an .obj file data
fn (mut p Part) parse_faces(row string, start_index int, obj_part ObjPart) {
mut i := start_index + 1
mut res := [][3]int{}
mut v := 0
mut t := 0
mut n := 0
// println("row: ${row[i..]}")
for true {
t = 0
n = 0
if i >= row.len {
break
}
mut c := row[i]
if (c > `9` || c < `0`) && c != `-` {
i++
continue
}
v, i = get_int(row, i)
if i < row.len && row[i] == `/` {
if row[i + 1] != `/` {
t, i = get_int(row, i + 1)
if i < row.len && row[i] == `/` {
n, i = get_int(row, i + 1)
}
} else {
i++
n, i = get_int(row, i + 1)
}
}
// manage negative indexes
// NOTE: not well suporeted now
if v < 0 {
// println("${obj_part.v.len} ${obj_part.v.len-c}")
v = obj_part.v.len - v + 1
// exit(0)
}
if n < 0 {
n = obj_part.vn.len - n + 1
}
if t < 0 {
t = obj_part.vt.len - t + 1
}
res << [v - 1, n - 1, t - 1]!
}
// println("ok res: ${res}")
// println(p.faces.len)
p.faces << res
}
// parse the obj file, if single_material is true it use only one default material
pub fn (mut obj_part ObjPart) parse_obj_buffer(rows []string, single_material bool) {
mut mat_count := 0
mut row_count := 0
default_part := Part{
name: 'default part'
}
obj_part.part << default_part
// println("OBJ file has ${rows.len} rows")
for c, row in rows {
// println("${c} ${row}")
mut i := 0
row_count++
for true {
if i >= row.len {
break
}
match row[i] {
`s` {
break
}
`m` {
if row[i..i + 6] == 'mtllib' {
obj_part.material_file = row[i + 7..].trim_space()
obj_part.load_materials()
}
break
}
`o`, `g` {
mut part := Part{}
part.name = row[i + 1..].trim_space()
obj_part.part << part
mat_count = 0
break
}
`u` {
if single_material == false && row[i..i + 6] == 'usemtl' {
material := row[i + 7..].trim_space()
// println("material: ${material}")
// manage multiple materials in an part
if obj_part.part[obj_part.part.len - 1].material.len > 0 {
mat_count++
mut part := Part{}
if mat_count > 1 {
li := obj_part.part[obj_part.part.len - 1].name.last_index('_m') or {
obj_part.part[obj_part.part.len - 1].name.len - 1
}
part.name = obj_part.part[obj_part.part.len - 1].name[..li] +
'_m${mat_count:02}'
} else {
part.name = obj_part.part[obj_part.part.len - 1].name + '_m01'
}
obj_part.part << part
}
obj_part.part[obj_part.part.len - 1].material = material
}
break
}
`v` {
i++
match row[i] {
// normals
`n` {
obj_part.vn << parse_3f(row, i + 2)
// println("Vertex line: ${c}")
break
}
// parameters uvw
`p` {
obj_part.vp << parse_3f(row, i + 2)
// println("Vertex line: ${obj_part.vp.len}")
break
}
// texture uvw
`t` {
obj_part.vt << obj_part.parse_floats(row, i + 2)
// println("Vertex line: ${c}")
break
}
else {
obj_part.v << parse_3f(row, i + 1)
// println("${row} => ${obj_part.v[obj_part.v.len-1]}")
break
}
}
}
`f` {
// println("${c} ${row}")
obj_part.part[obj_part.part.len - 1].parse_faces(row, i, obj_part)
// println(obj_part.part[obj_part.part.len - 1].faces.len)
// println("Faces line: ${c}")
break
}
// end of the line, comments
`\n`, `#` {
break
}
else {}
}
i++
}
// if c == 2 { break }
if c % 100000 == 0 && c > 0 {
println('${c} rows parsed')
}
}
println('${row_count} .obj Rows parsed')
// remove default part if empty
if obj_part.part.len > 1 && obj_part.part[0].faces.len == 0 {
obj_part.part = obj_part.part[1..]
}
}
// load the materials if found the .mtl file
fn (mut obj_part ObjPart) load_materials() {
rows := read_lines_from_file(obj_part.material_file)
println('Material file [${obj_part.material_file}] ${rows.len} Rows.')
for row in rows {
// println("${row}")
mut i := 0
for true {
if i >= row.len {
break
}
match row[i] {
`n` {
if row[i..i + 6] == 'newmtl' {
name := row[i + 6..].trim_space()
mut mat := Material{
name: name
}
obj_part.mat << mat
break
}
}
`K` {
if row[i + 1] !in [`a`, `d`, `e`, `s`] {
break
}
k_name := row[i..i + 2]
i += 3
value := parse_3f(row, i)
obj_part.mat[obj_part.mat.len - 1].ks[k_name] = value
break
}
`N` {
n_name := row[i..i + 2]
i += 3
value, _ := get_float(row, i)
obj_part.mat[obj_part.mat.len - 1].ns[n_name] = f32(value)
break
}
`m` {
if row[i..i + 4] == 'map_' {
name := row[i..i + 6]
if (i + 7) < row.len {
file_name := row[i + 7..].trim_space()
obj_part.mat[obj_part.mat.len - 1].maps[name] = file_name
}
break
}
}
// transparency
`d` {
if row[i + 1] == ` ` {
value, _ := get_float(row, i + 2)
obj_part.mat[obj_part.mat.len - 1].ns['Tr'] = f32(value)
}
}
`T` {
if row[i + 1] == `r` {
value, _ := get_float(row, i + 3)
obj_part.mat[obj_part.mat.len - 1].ns['Tr'] = f32(1.0 - value)
}
}
// end of the line, comments
`\n`, `#` {
break
}
` `, `\t` {
i++
continue
}
else {
break
}
}
i++
}
}
// create map material name => material index
for i, m in obj_part.mat {
if m.name !in obj_part.mat_map {
obj_part.mat_map[m.name] = i
}
}
println('Material Loading Done!')
}
//==============================================================================
// Sokol data
//==============================================================================
// vertex data struct
pub struct Vertex_pnct {
pub mut:
x f32 // position
y f32
z f32
nx f32 // normal
ny f32
nz f32
// color u32 = 0xFFFFFFFF // color
u f32 // uv
v f32
// u u16 // for compatibility with D3D11
// v u16 // for compatibility with D3D11
}
// struct used to pass the data to the sokol calls
pub struct Skl_buffer {
pub mut:
vbuf []Vertex_pnct
ibuf []u32
n_vertex u32
}
// transforms data from .obj format to buffer ready to be used in the render
pub fn (mut obj_part ObjPart) get_buffer(in_part_list []int) Skl_buffer {
// in_part := 0
mut v_count_index := 0
mut out_buf := Skl_buffer{}
mut cache := map[string]int{}
mut cache_hit := 0
// has_normals := obj_part.vn.len > 0
// has_uvs := obj_part.vt.len > 0
for in_part in in_part_list {
part := obj_part.part[in_part]
for fc, face in part.faces {
// println("${fc} ${face}")
// default 3 faces
mut v_seq := [0, 1, 2]
if face.len == 4 {
v_seq = [0, 1, 2, 0, 2, 3]
}
// if big faces => use the fan of triangles as solution
// Note: this trick doesn't work with concave faces
if face.len > 4 {
v_seq = []
mut i := 1
for i < (face.len - 1) {
v_seq << 0
v_seq << i
v_seq << (i + 1)
i++
}
// println("BIG FACES! ${fc} ${face.len} v_seq:${v_seq.len}")
}
// no vertex index, generate normals
if face[0][1] == -1 && face.len >= 3 {
mut v_count := 0
v0 := face[v_count + 0][0]
v1 := face[v_count + 1][0]
v2 := face[v_count + 2][0]
vec0 := obj_part.v[v2] - obj_part.v[v1]
vec1 := obj_part.v[v0] - obj_part.v[v1]
tmp_normal := vec0 % vec1
for v_count < face.len {
obj_part.vn << tmp_normal
obj_part.part[in_part].faces[fc][v_count][1] = obj_part.vn.len - 1
v_count++
}
}
for vertex_index in v_seq {
// position
if vertex_index >= face.len {
continue
}
v_index := face[vertex_index][0] // vertex index
n_index := face[vertex_index][1] // normal index
t_index := face[vertex_index][2] // uv texture index
key := '${v_index}_${n_index}_${t_index}'
if key !in cache {
cache[key] = v_count_index
mut pnct := Vertex_pnct{
x: obj_part.v[v_index].e[0]
y: obj_part.v[v_index].e[1]
z: obj_part.v[v_index].e[2]
}
// normal
if n_index >= 0 {
pnct.nx = obj_part.vn[n_index].e[0]
pnct.ny = obj_part.vn[n_index].e[1]
pnct.nz = obj_part.vn[n_index].e[2]
}
// texture uv
if t_index >= 0 {
pnct.u = obj_part.vt[t_index].e[0]
pnct.v = obj_part.vt[t_index].e[1]
}
out_buf.vbuf << pnct
out_buf.ibuf << u32(v_count_index)
v_count_index++
} else {
// println("Cache used! ${key}")
out_buf.ibuf << u32(cache[key])
cache_hit++
}
}
}
}
/*
println("------------")
for c1, x1 in out_buf.vbuf[..10] {
println("${c1} ${x1}")
}
println(out_buf.ibuf[..10])
*/
// println("vbuf size: ${out_buf.vbuf.len} ibuf size: ${out_buf.ibuf.len} Cache hit: ${cache_hit}")
out_buf.n_vertex = u32(out_buf.ibuf.len)
return out_buf
}
//==============================================================================
// Utility
//==============================================================================
// print on the console the summary of the .obj model loaded
pub fn (obj_part ObjPart) summary() {
println('---- Stats ----')
println('vertices: ${obj_part.v.len}')
println('normals : ${obj_part.vn.len}')
println('uv : ${obj_part.vt.len}')
println('parts : ${obj_part.part.len}')
// Parts
println('---- Parts ----')
for c, x in obj_part.part {
println('${c:3} [${x.name:-16}] mat:[${x.material:-10}] ${x.faces.len:7} faces')
}
// Materials
println('---- Materials ----')
println('Material dict: ${obj_part.mat_map.keys()}')
for c, mat in obj_part.mat {
println('${c:3} [${mat.name:-16}]')
for k, v in mat.ks {
print('${k} = ${v}')
}
for k, v in mat.ns {
println('${k} = ${v}')
}
for k, v in mat.maps {
println('${k} = ${v}')
}
}
}
// debug test function, do not remove.
pub fn tst() {
/*
//fname := "capsule.obj"
//fname := "Forklift.obj"
fname := "cube.obj"
//fname := "Orange Robot 3D ObjPart.obj"
mut obj := ObjPart{}
buf := os.read_lines(fname) or { panic(err.msg) }
obj.parse_obj_buffer(buf)
obj.summary()
*/
/*
a :="f 7048 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7003"
mut f1 := 0
mut f2 := 0
f0,mut p := get_int(a,1)
f1, p = get_int(a,p)
f2, p = get_int(a,p)
println("res: ${f0} ${f1} ${f2}")
*/
/*
a :="v -0 0.107769 -0.755914"
println("${parse_3f(a,1)}")
*/
/*
ort := m4.ortho(0,300,0,200,0,0)
println(ort)
a := m4.vec3(0,0,0)
println("a: ${a}")
res := m4.mul_vec(ort, a)
println("res:\n${res}")
*/
s := 'K 1 1 1'
r := strconv.atof_quick(s[1..s.len - 1])
println(r)
}
@@ -0,0 +1,305 @@
/**********************************************************************
*
* .obj loader
*
* Copyright (c) 2021 Dario Deledda. All rights reserved.
* Use of this source code is governed by an MIT license
* that can be found in the LICENSE file.
*
* TODO:
**********************************************************************/
module obj
import sokol.gfx
import gg.m4
import math
import stbi
/******************************************************************************
* Texture functions
******************************************************************************/
pub fn create_texture(w int, h int, buf &u8) (gfx.Image, gfx.Sampler) {
sz := w * h * 4
mut img_desc := gfx.ImageDesc{
width: w
height: h
num_mipmaps: 0
// min_filter: .linear
// mag_filter: .linear
// usage: .dynamic
// wrap_u: .clamp_to_edge
// wrap_v: .clamp_to_edge
label: &char(unsafe { nil })
d3d11_texture: 0
}
// comment if .dynamic is enabled
img_desc.data.subimage[0][0] = gfx.Range{
ptr: buf
size: usize(sz)
}
sg_img := gfx.make_image(&img_desc)
mut smp_desc := gfx.SamplerDesc{
min_filter: .linear
mag_filter: .linear
wrap_u: .clamp_to_edge
wrap_v: .clamp_to_edge
}
sg_smp := gfx.make_sampler(&smp_desc)
return sg_img, sg_smp
}
pub fn destroy_texture(sg_img gfx.Image) {
gfx.destroy_image(sg_img)
}
pub fn load_texture(file_name string) (gfx.Image, gfx.Sampler) {
buffer := read_bytes_from_file(file_name)
stbi.set_flip_vertically_on_load(true)
img := stbi.load_from_memory(buffer.data, buffer.len) or {
eprintln('Texture file: [${file_name}] ERROR!')
exit(0)
}
sg_img, sg_smp := create_texture(int(img.width), int(img.height), img.data)
img.free()
return sg_img, sg_smp
}
/******************************************************************************
* Pipeline
******************************************************************************/
pub fn (mut obj_part ObjPart) create_pipeline(in_part []int, shader gfx.Shader, texture gfx.Image, sampler gfx.Sampler) Render_data {
mut res := Render_data{}
obj_buf := obj_part.get_buffer(in_part)
res.n_vert = obj_buf.n_vertex
res.material = obj_part.part[in_part[0]].material
// vertex buffer
mut vert_buffer_desc := gfx.BufferDesc{}
unsafe { vmemset(&vert_buffer_desc, 0, int(sizeof(vert_buffer_desc))) }
vert_buffer_desc.size = usize(obj_buf.vbuf.len * int(sizeof(Vertex_pnct)))
vert_buffer_desc.data = gfx.Range{
ptr: obj_buf.vbuf.data
size: usize(obj_buf.vbuf.len * int(sizeof(Vertex_pnct)))
}
vert_buffer_desc.type = .vertexbuffer
vert_buffer_desc.label = &char('vertbuf_part_${in_part:03}'.str)
vbuf := gfx.make_buffer(&vert_buffer_desc)
// index buffer
mut index_buffer_desc := gfx.BufferDesc{}
unsafe { vmemset(&index_buffer_desc, 0, int(sizeof(index_buffer_desc))) }
index_buffer_desc.size = usize(obj_buf.ibuf.len * int(sizeof(u32)))
index_buffer_desc.data = gfx.Range{
ptr: obj_buf.ibuf.data
size: usize(obj_buf.ibuf.len * int(sizeof(u32)))
}
index_buffer_desc.type = .indexbuffer
index_buffer_desc.label = &char('indbuf_part_${in_part:03}'.str)
ibuf := gfx.make_buffer(&index_buffer_desc)
mut pipdesc := gfx.PipelineDesc{}
unsafe { vmemset(&pipdesc, 0, int(sizeof(pipdesc))) }
pipdesc.layout.buffers[0].stride = int(sizeof(Vertex_pnct))
// the constants [C.ATTR_vs_a_Position, C.ATTR_vs_a_Color, C.ATTR_vs_a_Texcoord0] are generated by sokol-shdc
pipdesc.layout.attrs[C.ATTR_vs_a_Position].format = .float3 // x,y,z as f32
pipdesc.layout.attrs[C.ATTR_vs_a_Normal].format = .float3 // x,y,z as f32
// pipdesc.layout.attrs[C.ATTR_vs_a_Color].format = .ubyte4n // color as u32
pipdesc.layout.attrs[C.ATTR_vs_a_Texcoord0].format = .float2 // u,v as f32
// pipdesc.layout.attrs[C.ATTR_vs_a_Texcoord0].format = .short2n // u,v as u16
pipdesc.index_type = .uint32
color_state := gfx.ColorTargetState{
blend: gfx.BlendState{
enabled: true
src_factor_rgb: .src_alpha
dst_factor_rgb: .one_minus_src_alpha
}
}
pipdesc.colors[0] = color_state
pipdesc.depth = gfx.DepthState{
write_enabled: true
compare: .less_equal
}
pipdesc.cull_mode = .front
pipdesc.label = &char('pip_part_${in_part:03}'.str)
// shader
pipdesc.shader = shader
res.bind.vertex_buffers[0] = vbuf
res.bind.index_buffer = ibuf
res.bind.fs.images[C.SLOT_tex] = texture
res.bind.fs.samplers[C.SLOT_smp] = sampler
res.pipeline = gfx.make_pipeline(&pipdesc)
// println('Buffers part [${in_part}] init done!')
return res
}
/******************************************************************************
* Render functions
******************************************************************************/
// aggregate all the part by materials
pub fn (mut obj_part ObjPart) init_render_data(texture gfx.Image, sampler gfx.Sampler) {
// create shader
// One shader for all the model
shader := gfx.make_shader(voidptr(C.gouraud_shader_desc(gfx.query_backend())))
mut part_dict := map[string][]int{}
for i, p in obj_part.part {
if p.faces.len > 0 {
part_dict[p.material] << i
}
}
obj_part.rend_data.clear()
// println("Material dict: ${obj_part.mat_map.keys()}")
for k, v in part_dict {
// println("${k} => Parts ${v}")
mut txt := texture
mut smp := sampler
if k in obj_part.mat_map {
mat_map := obj_part.mat[obj_part.mat_map[k]]
if 'map_Kd' in mat_map.maps {
file_name := mat_map.maps['map_Kd']
if file_name in obj_part.texture {
txt = obj_part.texture[file_name]
// println("Texture [${file_name}] => from CACHE")
} else {
txt, smp = load_texture(file_name)
obj_part.texture[file_name] = txt
obj_part.sampler[file_name] = smp
// println("Texture [${file_name}] => LOADED")
}
}
}
// key := obj_part.texture.keys()[0]
// obj_part.rend_data << obj_part.create_pipeline(v, shader, obj_part.texture[key])
obj_part.rend_data << obj_part.create_pipeline(v, shader, txt, smp)
}
// println("Texture array len: ${obj_part.texture.len}")
// println("Calc bounding box.")
obj_part.calc_bbox()
println('init_render_data DONE!')
}
pub fn (obj_part ObjPart) bind_and_draw(rend_data_index int, in_data Shader_data) u32 {
// apply the pipeline and bindings
mut part_render_data := obj_part.rend_data[rend_data_index]
// pass light position
mut tmp_fs_params := Tmp_fs_param{}
tmp_fs_params.light = in_data.fs_data.light
if part_render_data.material in obj_part.mat_map {
mat_index := obj_part.mat_map[part_render_data.material]
mat := obj_part.mat[mat_index]
// ambient
tmp_fs_params.ka = in_data.fs_data.ka
if 'Ka' in mat.ks {
tmp_fs_params.ka = mat.ks['Ka']
}
// specular
tmp_fs_params.ks = in_data.fs_data.ks
if 'Ks' in mat.ks {
tmp_fs_params.ks = mat.ks['Ks']
}
// specular exponent Ns
if 'Ns' in mat.ns {
tmp_fs_params.ks.e[3] = mat.ns['Ns'] / 1000.0
} else {
// default value is 10
tmp_fs_params.ks.e[3] = f32(10) / 1000.0
}
// diffuse
tmp_fs_params.kd = in_data.fs_data.kd
if 'Kd' in mat.ks {
tmp_fs_params.kd = mat.ks['Kd']
}
// alpha/transparency
if 'Tr' in mat.ns {
tmp_fs_params.kd.e[3] = mat.ns['Tr']
}
}
gfx.apply_pipeline(part_render_data.pipeline)
gfx.apply_bindings(part_render_data.bind)
vs_uniforms_range := gfx.Range{
ptr: in_data.vs_data
size: usize(in_data.vs_len)
}
fs_uniforms_range := gfx.Range{
ptr: unsafe { &tmp_fs_params }
size: usize(in_data.fs_len)
}
gfx.apply_uniforms(.vs, C.SLOT_vs_params, &vs_uniforms_range)
gfx.apply_uniforms(.fs, C.SLOT_fs_params, &fs_uniforms_range)
gfx.draw(0, int(part_render_data.n_vert), 1)
return part_render_data.n_vert
}
pub fn (obj_part ObjPart) bind_and_draw_all(in_data Shader_data) u32 {
mut n_vert := u32(0)
// println("Parts: ${obj_part.rend_data.len}")
for i, _ in obj_part.rend_data {
n_vert += obj_part.bind_and_draw(i, in_data)
}
return n_vert
}
pub fn (mut obj_part ObjPart) calc_bbox() {
obj_part.max = m4.Vec4{
e: [f32(-math.max_f32), -math.max_f32, -math.max_f32, 0]!
}
obj_part.min = m4.Vec4{
e: [f32(math.max_f32), math.max_f32, math.max_f32, 0]!
}
for v in obj_part.v {
if v.e[0] > obj_part.max.e[0] {
obj_part.max.e[0] = v.e[0]
}
if v.e[1] > obj_part.max.e[1] {
obj_part.max.e[1] = v.e[1]
}
if v.e[2] > obj_part.max.e[2] {
obj_part.max.e[2] = v.e[2]
}
if v.e[0] < obj_part.min.e[0] {
obj_part.min.e[0] = v.e[0]
}
if v.e[1] < obj_part.min.e[1] {
obj_part.min.e[1] = v.e[1]
}
if v.e[2] < obj_part.min.e[2] {
obj_part.min.e[2] = v.e[2]
}
}
val1 := obj_part.max.mod3()
val2 := obj_part.min.mod3()
if val1 > val2 {
obj_part.radius = f32(val1)
} else {
obj_part.radius = f32(val2)
}
// println("BBox: ${obj_part.min} <=> ${obj_part.max}\nRadius: ${obj_part.radius}")
}
@@ -0,0 +1,106 @@
/**********************************************************************
*
* .obj loader
*
* Copyright (c) 2021 Dario Deledda. All rights reserved.
* Use of this source code is governed by an MIT license
* that can be found in the LICENSE file.
*
* TODO:
**********************************************************************/
module obj
import gg.m4
import sokol.gfx
// part struct maintaining the face indices
pub struct Part {
pub mut:
faces [][][3]int // v n t index order, if -1 not available
name string
material string
}
// material struct, all Ks and Ns are stored as maps of string
pub struct Material {
pub mut:
name string
ks map[string]m4.Vec4
ns map[string]f32
maps map[string]string
}
// render data used for the rendering
pub struct Render_data {
pub mut:
pipeline gfx.Pipeline
bind gfx.Bindings
n_vert u32
material string
}
// base object parts struct
pub struct ObjPart {
pub mut:
v []m4.Vec4 // position
vn []m4.Vec4 // normals
vp []m4.Vec4 // vertex params
vt []m4.Vec4 // textures
name string
part []Part // parts of the ObjPart
mat []Material // list of the materials of the ObjPart
mat_map map[string]int // mapping material name to its material index
texture map[string]gfx.Image // GPU loaded texture map
sampler map[string]gfx.Sampler // GPU loaded sampler
material_file string // .mtl file name for the .obj
rend_data []Render_data // render data used for the rendering
t_m m4.Mat4 = m4.unit_m4() // transform matrix for this ObjPart
// child []ObjPart
// stats
min m4.Vec4 // min 3d position in the ObjPart
max m4.Vec4 // max 3d position in the ObjPart
radius f32 // bounding circle radius of the ObjPart
}
// used in to pass the matrices to the shader
pub struct Mats {
pub mut:
mv m4.Mat4
mvp m4.Mat4
nm m4.Mat4
}
// data passed to the vertex shader
pub struct Tmp_vs_param {
pub mut:
mv m4.Mat4
mvp m4.Mat4
nm m4.Mat4
}
// data passed to the pixel shader
pub struct Tmp_fs_param {
pub mut:
light m4.Vec4
ka m4.Vec4 = m4.Vec4{
e: [f32(0.1), 0.0, 0.0, 1.0]!
}
kd m4.Vec4 = m4.Vec4{
e: [f32(0.5), 0.5, 0.5, 1.0]!
}
ks m4.Vec4 = m4.Vec4{
e: [f32(1.0), 1.0, 1.0, 1.0]!
}
}
// shader data for the rendering
pub struct Shader_data {
pub mut:
vs_data &Tmp_vs_param = unsafe { nil }
vs_len int
fs_data &Tmp_fs_param = unsafe { nil }
fs_len int
}
@@ -0,0 +1,24 @@
module obj
import os
import os.asset
// read a file as single lines
pub fn read_lines_from_file(file_path string) []string {
if os.exists(file_path) {
return os.read_lines(file_path) or { [] }
}
return read_bytes_from_file(file_path).bytestr().split_into_lines()
}
// read a file as []u8
pub fn read_bytes_from_file(file_path string) []u8 {
if os.exists(file_path) {
return os.read_bytes(file_path) or { [] }
}
mpath := 'models/${file_path}'
return asset.read_bytes('assets', mpath) or {
eprintln('Model file NOT FOUND: `${mpath}`')
exit(0)
}
}
@@ -0,0 +1,308 @@
// vtest build: misc-tooling // needs .h files that are produced by `v shader`
/**********************************************************************
*
* .obj viewer
*
* Copyright (c) 2021 Dario Deledda. All rights reserved.
* Use of this source code is governed by an MIT license
* that can be found in the LICENSE file.
*
* Example .obj model of V from SurmanPP
*
* HOW TO COMPILE SHADERS:
* Run `v shader .` in this directory to compile the shaders.
* For more info and help with shader compilation see `docs.md` and `v help shader`.
*
* ALTERNATIVE .OBJ MODELS:
* you can load alternative models putting them in the "assets/model" folder with or without their .mtl file.
* use the program help for further instructions.
*
* TODO:
* - frame counter
**********************************************************************/
import gg
import gg.m4
import math
import sokol.sapp
import sokol.gfx
import sokol.sgl
import time
import os
import obj
// GLSL Include and functions
#include "@VMODROOT/gouraud.h" # It should be generated with `v shader .` (see the instructions at the top of this file)
fn C.gouraud_shader_desc(gfx.Backend) &gfx.ShaderDesc
const win_width = 600
const win_height = 600
const bg_color = gg.white
struct App {
mut:
gg &gg.Context = unsafe { nil }
texture gfx.Image
sampler gfx.Sampler
init_flag bool
frame_count int
mouse_x int = -1
mouse_y int = -1
scroll_y int // mouse wheel value
// time
ticks i64
// model
obj_part &obj.ObjPart = unsafe { nil }
n_vertex u32
// init parameters
file_name string
single_material_flag bool
}
/******************************************************************************
* Draw functions
******************************************************************************/
@[inline]
fn vec4(x f32, y f32, z f32, w f32) m4.Vec4 {
return m4.Vec4{
e: [x, y, z, w]!
}
}
fn calc_matrices(w f32, h f32, rx f32, ry f32, in_scale f32, pos m4.Vec4) obj.Mats {
proj := m4.perspective(60, w / h, 0.01, 100.0) // set far plane to 100 fro the zoom function
view := m4.look_at(vec4(f32(0.0), 0, 6, 0), vec4(f32(0), 0, 0, 0), vec4(f32(0), 1, 0, 0))
view_proj := view * proj
rxm := m4.rotate(m4.rad(rx), vec4(f32(1), 0, 0, 0))
rym := m4.rotate(m4.rad(ry), vec4(f32(0), 1, 0, 0))
model_pos := m4.unit_m4().translate(pos)
model_m := (rym * rxm) * model_pos
scale_m := m4.scale(vec4(in_scale, in_scale, in_scale, 1))
mv := scale_m * model_m // model view
nm := mv.inverse().transpose() // normal matrix
mvp := mv * view_proj // model view projection
return obj.Mats{
mv: mv
mvp: mvp
nm: nm
}
}
fn draw_model(app App, model_pos m4.Vec4) u32 {
if app.init_flag == false {
return 0
}
ws := gg.window_size_real_pixels()
dw := ws.width / 2
dh := ws.height / 2
mut scale := f32(1)
if app.obj_part.radius > 1 {
scale = 1 / (app.obj_part.radius)
} else {
scale = app.obj_part.radius
}
scale *= 3
// *** vertex shader uniforms ***
rot := [f32(app.mouse_y), f32(app.mouse_x)]
mut zoom_scale := scale + f32(app.scroll_y) / (app.obj_part.radius * 4)
mats := calc_matrices(dw, dh, rot[0], rot[1], zoom_scale, model_pos)
mut tmp_vs_param := obj.Tmp_vs_param{
mv: mats.mv
mvp: mats.mvp
nm: mats.nm
}
// *** fragment shader uniforms ***
time_ticks := f32(time.ticks() - app.ticks) / 1000
radius_light := f32(app.obj_part.radius)
x_light := f32(math.cos(time_ticks) * radius_light)
z_light := f32(math.sin(time_ticks) * radius_light)
mut tmp_fs_params := obj.Tmp_fs_param{}
tmp_fs_params.light = m4.vec3(x_light, radius_light, z_light)
sd := obj.Shader_data{
vs_data: unsafe { &tmp_vs_param }
vs_len: int(sizeof(tmp_vs_param))
fs_data: unsafe { &tmp_fs_params }
fs_len: int(sizeof(tmp_fs_params))
}
return app.obj_part.bind_and_draw_all(sd)
}
fn frame(mut app App) {
// clear
mut color_action := gfx.ColorAttachmentAction{
load_action: .clear
clear_value: gfx.Color{
r: 0.0
g: 0.0
b: 0.0
a: 1.0
}
}
mut pass_action := gfx.PassAction{}
pass_action.colors[0] = color_action
pass := sapp.create_default_pass(pass_action)
gfx.begin_pass(&pass)
// render the data
draw_start_glsl(app)
draw_model(app, m4.Vec4{})
// uncomment if you want a raw benchmark mode
/*
mut n_vertex_drawn := u32(0)
n_x_obj := 20
for x in 0..n_x_obj {
for z in 0..30 {
for y in 0..4 {
n_vertex_drawn += draw_model(app, m4.Vec4{e:[f32((x-(n_x_obj>>1))*3),-3 + y*3,f32(-6*z),1]!})
}
}
}
*/
draw_end_glsl(app)
// println("v:${n_vertex_drawn}")
app.frame_count++
}
fn draw_start_glsl(app App) {
if app.init_flag == false {
return
}
ws := gg.window_size_real_pixels()
gfx.apply_viewport(0, 0, ws.width, ws.height, true)
}
fn draw_end_glsl(app App) {
gfx.end_pass()
gfx.commit()
}
/******************************************************************************
* Init / Cleanup
******************************************************************************/
fn my_init(mut app App) {
mut object := &obj.ObjPart{}
obj_file_lines := obj.read_lines_from_file(app.file_name)
object.parse_obj_buffer(obj_file_lines, app.single_material_flag)
object.summary()
app.obj_part = object
// set max vertices,
// for a large number of the same type of object it is better use the instances!!
desc := sapp.create_desc()
gfx.setup(&desc)
sgl_desc := sgl.Desc{
max_vertices: 128 * 65536
}
sgl.setup(&sgl_desc)
// 1x1 pixel white, default texture
unsafe {
tmp_txt := malloc(4)
tmp_txt[0] = u8(0xFF)
tmp_txt[1] = u8(0xFF)
tmp_txt[2] = u8(0xFF)
tmp_txt[3] = u8(0xFF)
app.texture, app.sampler = obj.create_texture(1, 1, tmp_txt)
free(tmp_txt)
}
// glsl
app.obj_part.init_render_data(app.texture, app.sampler)
app.init_flag = true
}
fn cleanup(mut app App) {
/*
for _, mat in app.obj_part.texture {
obj.destroy_texture(mat)
}
*/
}
/******************************************************************************
* events handling
******************************************************************************/
fn my_event_manager(mut ev gg.Event, mut app App) {
if ev.typ == .mouse_move {
app.mouse_x = int(ev.mouse_x)
app.mouse_y = int(ev.mouse_y)
}
if ev.scroll_y != 0 {
app.scroll_y += int(ev.scroll_y)
}
if ev.typ == .touches_began || ev.typ == .touches_moved {
if ev.num_touches > 0 {
touch_point := ev.touches[0]
app.mouse_x = int(touch_point.pos_x)
app.mouse_y = int(touch_point.pos_y)
}
}
}
fn main() {
/*
obj.tst()
exit(0)
*/
// App init
mut app := &App{}
// app.file_name = 'v.obj' // default object is the v logo
app.file_name = 'utahTeapot.obj' // default object is the v logo
app.single_material_flag = false
$if !android {
if os.args.len > 3 || (os.args.len >= 2 && os.args[1] in ['-h', '--help', '\\?', '-?']) {
eprintln('Usage:\nshow_obj [file_name:string] [single_material_flag:(true|false)]\n')
eprintln('file_name : name of the .obj file.')
eprintln(' If no file name is passed the default V logo will be showed.')
eprintln(' Try one of the .obj files in the "assets/models/" folder.')
eprintln("single_material_flag: if true the viewer use for all the model's parts the default material")
exit(0)
}
if os.args.len >= 2 {
app.file_name = os.args[1]
}
if os.args.len >= 3 {
app.single_material_flag = os.args[2].bool()
}
println('Loading model: ${app.file_name}')
println('Using single material: ${app.single_material_flag}')
}
app.gg = gg.new_context(
width: win_width
height: win_height
create_window: true
window_title: 'V Wavefront OBJ viewer - Use the mouse wheel to zoom'
user_data: app
bg_color: bg_color
frame_fn: frame
init_fn: my_init
cleanup_fn: cleanup
event_fn: my_event_manager
)
app.ticks = time.ticks()
app.gg.run()
}
Whitespace-only changes.