Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a function to load an OBJ mesh with texture #684

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ backtrace = { version = "0.3.60", optional = true, default-features = false, fea
log = { version = "0.4", optional = true }
quad-snd = { version = "0.2", optional = true }
slotmap = "1.0"
tobj = "4.0.0"

[dev-dependencies]
macroquad-particles = { path = "./particles" }
Expand Down
40 changes: 40 additions & 0 deletions src/models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,46 @@ pub struct Mesh {
pub texture: Option<Texture2D>,
}

pub fn load_mesh<P>(path: P,texture: &Texture2D) -> Mesh
where
P: AsRef<std::path::Path> + std::fmt::Debug,
{
use crate::color;
let meshes = tobj::load_obj(path,&tobj::GPU_LOAD_OPTIONS).expect("can't load file").0;
let mesh = &meshes[0].mesh;
let vertex_positions: Vec<Vec3> = mesh
.positions
.chunks(3)
.map(|x| Vec3::new(x[0],x[1],x[2]))
.collect();
let texcoords: Vec<Vec2> = mesh
.texcoords
.chunks(2)
.map(|x| Vec2::new(x[0],x[1]))
.collect();
// let vertex_colors: Vec<color::Color> = mesh
// .positions
// .chunks(3)
// .map(|x| Color::new(x[0],x[1],x[2],1.0))
// .collect();
let mut vertices = Vec::new();

assert_eq!(vertex_positions.len(),texcoords.len());
for i in 0..vertex_positions.len() {
vertices.push(Vertex {
position: vertex_positions[i],
uv: texcoords[i],
color: color::colors::WHITE,
});
}

Mesh {
vertices,
indices: mesh.indices.iter().map(|x| *x as u16).collect::<Vec<u16>>(),
texture: Some(texture.clone()),
}
}

pub fn draw_mesh(mesh: &Mesh) {
let context = get_context();

Expand Down
Loading