Code builds with cube_thing_rule. Still has bugs.

This commit is contained in:
Chris Hodapp 2020-02-14 11:41:29 -05:00
parent 4da007943d
commit 9e92a469b8

View File

@ -1,10 +1,9 @@
//use std::io; //use std::io;
use tri_mesh::prelude::*; use tri_mesh::prelude as tm;
//use nalgebra::base::dimension::{U1, U4}; use nalgebra::*;
//use nalgebra::Matrix4;
/// A type for custom mesh vertices. Initialize with [vertex][self::vertex]. /// A type for custom mesh vertices. Initialize with [vertex][self::vertex].
pub type Vertex = nalgebra::Vector4<f32>; pub type Vertex = Vector4<f32>;
/// Initializes a vertex for a custom mesh. /// Initializes a vertex for a custom mesh.
pub fn vertex(x: f32, y: f32, z: f32) -> Vertex { pub fn vertex(x: f32, y: f32, z: f32) -> Vertex {
@ -37,7 +36,7 @@ struct OpenMesh {
impl OpenMesh { impl OpenMesh {
fn transform(&self, xfm: nalgebra::Matrix4<f32>) -> OpenMesh { fn transform(&self, xfm: Matrix4<f32>) -> OpenMesh {
OpenMesh { OpenMesh {
verts: self.verts.iter().map(|v| xfm * v).collect(), verts: self.verts.iter().map(|v| xfm * v).collect(),
faces: self.faces.clone(), // TODO: Use Rc? faces: self.faces.clone(), // TODO: Use Rc?
@ -84,7 +83,7 @@ impl OpenMesh {
} }
} }
fn to_trimesh(&self) -> Result<Mesh, tri_mesh::mesh_builder::Error> { fn to_trimesh(&self) -> Result<tm::Mesh, tri_mesh::mesh_builder::Error> {
let mut v: Vec<f64> = vec![0.0; self.verts.len() * 3]; let mut v: Vec<f64> = vec![0.0; self.verts.len() * 3];
for (i, vert) in self.verts.iter().enumerate() { for (i, vert) in self.verts.iter().enumerate() {
v[3*i] = vert[0].into(); v[3*i] = vert[0].into();
@ -92,7 +91,7 @@ impl OpenMesh {
v[3*i+2] = vert[2].into(); v[3*i+2] = vert[2].into();
} }
let faces: Vec<u32> = self.faces.iter().map(|f| *f as _).collect(); let faces: Vec<u32> = self.faces.iter().map(|f| *f as _).collect();
MeshBuilder::new().with_indices(faces).with_positions(v).build() tm::MeshBuilder::new().with_indices(faces).with_positions(v).build()
} }
// Just assume this is broken // Just assume this is broken
@ -149,84 +148,89 @@ impl OpenMesh {
// TODO: Do I benefit with Rc<Rule> below so Rule can be shared? // TODO: Do I benefit with Rc<Rule> below so Rule can be shared?
enum Rule { enum Rule {
// Recurse further. Input is "seeds" that further geometry should // Produce geometry, and possibly recurse further:
// *replace*. Generated geometry must have the same outer Recurse(fn () -> Vec<RuleStep>),
// boundary as the seeds, and be in the same coordinate space as
// the input.
Recurse(fn (Vec<Mesh>) -> Vec<RuleStep>),
// Stop recursing here: // Stop recursing here:
EmptyRule, EmptyRule,
} }
// TODO: Rename rules? // TODO: Rename rules?
struct RuleStep { struct RuleStep {
// The 'final' geometry generated at this step. // The geometry generated by this rule on its own - and none of
geom: Mesh, // the child rules.
// The 'seed' geometry from this step. If recursion stops geom: OpenMesh,
// (whether because rule is EmptyRule or because recursion depth
// has been hit), this will be transformed with 'xform' and
// appended with 'geom'. If recursion continues, this geometry is
// passed as the input to the next rule. (TODO: rule_to_mesh
// needs to do the 'recursion stops' part.)
//
// This is in the coordinate space that 'rule' should run in -
// thus, if it is transformed with 'xform', it will be in the same
// coordinate space as 'geom'.
seeds: Vec<Mesh>,
// The next rule to run. If EmptyRule, then stop here (and // The next rule to run. If EmptyRule, then stop here (and
// 'xform' is irrelevant). // 'xform' is irrelevant).
rule: Box<Rule>, rule: Box<Rule>,
// The transformation which puts 'seeds' and any geometry from // The transformation to apply to geometry generated by 'rule' and
// 'rule' (if applicable) into the same coordinate space as // any child rules.
// 'geom'. xform: Matrix4<f32>,
xform: Mat4,
} }
// is there a better way to do this? // is there a better way to do this?
fn empty_mesh() -> Mesh { fn empty_mesh() -> OpenMesh {
MeshBuilder::new().with_indices(vec![]).with_positions(vec![]).build().unwrap() OpenMesh {
verts: vec![],
faces: vec![],
idxs_entrance: vec![],
idxs_exit: vec![],
idxs_body: (0, 0),
}
} }
fn curve_horn_start(_v: Vec<Mesh>) -> Vec<RuleStep> { /*
fn curve_horn_start() -> Vec<RuleStep> {
// Seed is a square in XY, sidelength 1, centered at (0,0,0): // Seed is a square in XY, sidelength 1, centered at (0,0,0):
let seed = { let seed = {
let indices: Vec<u32> = vec![0, 1, 2, 0, 2, 3]; let m = OpenMesh {
let positions: Vec<f64> = vec![0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0]; verts: vec![
let mut s = MeshBuilder::new().with_indices(indices).with_positions(positions).build().unwrap(); vertex(0.0, 0.0, 0.0),
s.apply_transformation(Matrix4::from_translation(vec3(-0.5, -0.5, 0.0))); vertex(1.0, 0.0, 0.0),
s vertex(1.0, 1.0, 0.0),
vertex(0.0, 1.0, 0.0),
],
faces: vec![
0, 1, 2,
0, 2, 3,
],
idxs_entrance: vec![0],
idxs_exit: vec![0],
idxs_body: (0, 0),
};
let xform = nalgebra::geometry::Translation3::new(-0.5, -0.5, 0.0).to_homogeneous();
m.transform(xform)
}; };
vec![ vec![
// Since neither of the other two rules *start* with geometry: // Since neither of the other two rules *start* with geometry:
RuleStep { geom: seed.clone(), RuleStep { geom: seed.clone(),
rule: Box::new(Rule::EmptyRule), rule: Box::new(Rule::EmptyRule),
xform: Matrix4::identity(), xform: nalgebra::geometry::Transform3::identity().to_homogeneous(),
seeds: vec![]
}, },
// Recurse in both directions: // Recurse in both directions:
RuleStep { geom: empty_mesh(), RuleStep { geom: seed.clone(),
rule: Box::new(Rule::Recurse(curve_horn_thing_rule)), rule: Box::new(Rule::Recurse(curve_horn_thing_rule)),
xform: Matrix4::identity(), xform: nalgebra::geometry::Transform3::identity().to_homogeneous(),
seeds: vec![seed.clone()],
}, },
RuleStep { geom: empty_mesh(), RuleStep { geom: seed.clone(),
rule: Box::new(Rule::Recurse(curve_horn_thing_rule)), rule: Box::new(Rule::Recurse(curve_horn_thing_rule)),
xform: Matrix4::from_angle_y(Rad::turn_div_2()), xform: nalgebra::geometry::Rotation3::from_axis_angle(
seeds: vec![seed.clone()], &nalgebra::Vector3::y_axis(),
std::f32::consts::FRAC_PI_2).to_homogeneous(),
}, },
] ]
} }
//use std::convert::TryFrom; //use std::convert::TryFrom;
fn curve_horn_thing_rule(v: Vec<Mesh>) -> Vec<RuleStep> { fn curve_horn_thing_rule() -> Vec<RuleStep> {
let gen_geom = |seed: &Mesh| -> RuleStep { let gen_geom = |seed: &Mesh| -> RuleStep {
let mut mesh = seed.clone(); let mut mesh = seed.clone();
let m: Mat4 = Matrix4::from_angle_y(Rad(0.1)) * let m: Mat4 = tm::Matrix4::from_angle_y(Rad(0.1)) *
Matrix4::from_scale(0.95) * tm::Matrix4::from_scale(0.95) *
Matrix4::from_translation(vec3(0.0, 0.0, 0.2)); tm::Matrix4::from_translation(vec3(0.0, 0.0, 0.2));
let r = Rule::Recurse(curve_horn_thing_rule); let r = Rule::Recurse(curve_horn_thing_rule);
mesh.apply_transformation(m); mesh.apply_transformation(m);
@ -279,7 +283,7 @@ fn curve_horn_thing_rule(v: Vec<Mesh>) -> Vec<RuleStep> {
// that I cannot use MeshBuilder this way and then append // that I cannot use MeshBuilder this way and then append
// meshes - it just leads to disconnected geometry // meshes - it just leads to disconnected geometry
let joined = match MeshBuilder::new(). let joined = match tm::MeshBuilder::new().
with_positions(verts). with_positions(verts).
with_indices(idxs). with_indices(idxs).
build() build()
@ -315,7 +319,7 @@ fn points_to_xform(v0: Point3<f64>, v1: Point3<f64>, v2: Point3<f64>) -> Mat4 {
let yn: Vec3 = zn.cross(xn); let yn: Vec3 = zn.cross(xn);
let s = x.magnitude(); let s = x.magnitude();
let _m: Mat4 = Matrix4::from_cols( let _m: Mat4 = tm::Matrix4::from_cols(
(xn*s).extend(0.0), // new X (xn*s).extend(0.0), // new X
(yn*s).extend(0.0), // new Y (yn*s).extend(0.0), // new Y
(zn*s).extend(0.0), // new Z (zn*s).extend(0.0), // new Z
@ -323,41 +327,75 @@ fn points_to_xform(v0: Point3<f64>, v1: Point3<f64>, v2: Point3<f64>) -> Mat4 {
); );
return _m; return _m;
} }
*/
fn cube_thing_rule(_v: Vec<Mesh>) -> Vec<RuleStep> { fn cube() -> OpenMesh {
OpenMesh {
verts: vec![
vertex(0.0, 0.0, 0.0),
vertex(1.0, 0.0, 0.0),
vertex(0.0, 1.0, 0.0),
vertex(1.0, 1.0, 0.0),
vertex(0.0, 0.0, 1.0),
vertex(1.0, 0.0, 1.0),
vertex(0.0, 1.0, 1.0),
vertex(1.0, 1.0, 1.0),
],
faces: vec![
0, 3, 1,
0, 2, 3,
1, 7, 5,
1, 3, 7,
5, 6, 4,
5, 7, 6,
4, 2, 0,
4, 6, 2,
2, 7, 3,
2, 6, 7,
0, 1, 5,
0, 5, 4,
],
idxs_entrance: vec![],
idxs_exit: vec![],
idxs_body: (0, 8),
}.transform(geometry::Translation3::new(-0.5, -0.5, -0.5).to_homogeneous())
}
let mesh = MeshBuilder::new().cube().build().unwrap(); fn cube_thing_rule() -> Vec<RuleStep> {
let mesh = cube();
// Quarter-turn in radians: // Quarter-turn in radians:
let qtr = Rad::turn_div_4(); let qtr = std::f32::consts::FRAC_PI_2;
let y = &Vector3::y_axis();
let z = &Vector3::z_axis();
// Each element of this turns to a branch for the recursion: // Each element of this turns to a branch for the recursion:
let turns: Vec<Mat4> = vec![ let turns: Vec<Matrix4<f32>> = vec![
Matrix4::identity(), geometry::Transform3::identity().to_homogeneous(),
Matrix4::from_angle_y(qtr), geometry::Rotation3::from_axis_angle(y, qtr).to_homogeneous(),
Matrix4::from_angle_y(qtr * 2.0), geometry::Rotation3::from_axis_angle(y, qtr * 2.0).to_homogeneous(),
Matrix4::from_angle_y(qtr * 3.0), geometry::Rotation3::from_axis_angle(y, qtr * 3.0).to_homogeneous(),
Matrix4::from_angle_z(qtr), geometry::Rotation3::from_axis_angle(z, qtr).to_homogeneous(),
Matrix4::from_angle_z(-qtr), geometry::Rotation3::from_axis_angle(z, -qtr).to_homogeneous(),
]; ];
let gen_rulestep = |rot: &Mat4| -> RuleStep { let gen_rulestep = |rot: &Matrix4<f32>| -> RuleStep {
let m: Mat4 = rot * let m: Matrix4<f32> = rot *
Matrix4::from_scale(0.5) * Matrix4::new_scaling(0.5) *
Matrix4::from_translation(vec3(6.0, 0.0, 0.0)); geometry::Translation3::new(6.0, 0.0, 0.0).to_homogeneous();
let r = Rule::Recurse(cube_thing_rule); let r = Rule::Recurse(cube_thing_rule);
let mut m2 = mesh.clone();
m2.apply_transformation(m); let m2 = mesh.transform(m);
RuleStep { geom: m2, rule: Box::new(r), xform: m, seeds: vec![] } RuleStep { geom: m2, rule: Box::new(r), xform: m }
}; };
// TODO: Why is 'mesh' present in each RuleStep? This is just
// duplicate geometry! Either 'm' applies to 'mesh' (and the
// definition of RuleStep changes) - or 'mesh' needs to already be
// transformed.
turns.iter().map(gen_rulestep).collect() turns.iter().map(gen_rulestep).collect()
} }
// Have I any need of this after making OpenMesh?
/*
struct MeshBound<'a> { struct MeshBound<'a> {
m: &'a Mesh, m: &'a Mesh,
start: HalfEdgeID, start: HalfEdgeID,
@ -420,6 +458,7 @@ impl<'a> Iterator for MeshBound<'a> {
} }
} }
*/
//fn mesh_boundary(m: &Mesh) -> Vec<tri_mesh::HalfEdgeID> { //fn mesh_boundary(m: &Mesh) -> Vec<tri_mesh::HalfEdgeID> {
//} //}
@ -432,9 +471,9 @@ impl<'a> Iterator for MeshBound<'a> {
// rather than repeatedly transforming meshes, it stacks // rather than repeatedly transforming meshes, it stacks
// transformations and then applies them all at once. // transformations and then applies them all at once.
fn rule_to_mesh(rule: &Rule, seed: Vec<Mesh>, iters_left: u32) -> (Mesh, u32) { fn rule_to_mesh(rule: &Rule, iters_left: u32) -> (OpenMesh, u32) {
let mut mesh = MeshBuilder::new().with_indices(vec![]).with_positions(vec![]).build().unwrap(); let mut mesh = empty_mesh();
let mut nodes: u32 = 1; let mut nodes: u32 = 1;
@ -444,19 +483,21 @@ fn rule_to_mesh(rule: &Rule, seed: Vec<Mesh>, iters_left: u32) -> (Mesh, u32) {
match rule { match rule {
Rule::Recurse(func) => { Rule::Recurse(func) => {
for step in func(seed) { for step in func() {
let subrule: Rule = *step.rule; let subrule: Rule = *step.rule;
let subxform: Mat4 = step.xform; let subxform: Matrix4<f32> = step.xform;
let geom: Mesh = step.geom; let geom: OpenMesh = step.geom;
mesh.append(&geom); mesh = mesh.connect_single(&geom);
let (mut submesh, subnodes) = rule_to_mesh( let (mut submesh, subnodes) = rule_to_mesh(
&subrule, step.seeds, iters_left - 1); &subrule, iters_left - 1);
submesh.apply_transformation(subxform);
submesh = submesh.transform(subxform);
nodes += subnodes; nodes += subnodes;
mesh.append(&submesh); mesh = mesh.connect_single(&submesh);
} }
} }
Rule::EmptyRule => { Rule::EmptyRule => {
@ -466,17 +507,6 @@ fn rule_to_mesh(rule: &Rule, seed: Vec<Mesh>, iters_left: u32) -> (Mesh, u32) {
(mesh, nodes) (mesh, nodes)
} }
fn print_vector(v: &Vec4) -> String {
return format!("{},{},{},{}", v.x, v.y, v.z, v.w);
}
fn print_matrix(m: &Mat4) {
let mt = m.transpose();
println!("[{}]\n[{}]\n[{}]\n[{}]",
print_vector(&mt.x), print_vector(&mt.y),
print_vector(&mt.z), print_vector(&mt.w));
}
fn main() { fn main() {
println!("DEBUG-------------------------------"); println!("DEBUG-------------------------------");
@ -511,7 +541,7 @@ fn main() {
idxs_body: (4, 4), idxs_body: (4, 4),
}; };
let xform = nalgebra::geometry::Translation3::new(0.0, 0.0, 1.0).to_homogeneous(); let xform = geometry::Translation3::new(0.0, 0.0, 1.0).to_homogeneous();
let m2 = m.transform(xform); let m2 = m.transform(xform);
let m3 = m.connect_single(&m2); let m3 = m.connect_single(&m2);
let m4 = m3.connect_single(&m2.transform(xform)); let m4 = m3.connect_single(&m2.transform(xform));
@ -537,84 +567,31 @@ fn main() {
println!("mesh = {:?}", mesh); println!("mesh = {:?}", mesh);
try_save(&mesh, "openmesh_cube_several.obj"); try_save(&mesh, "openmesh_cube_several.obj");
} }
// Construct any mesh, this time, we will construct a simple icosahedron
let mesh = MeshBuilder::new().icosahedron().build().unwrap();
// Compute the extreme coordinates which defines the axis aligned bounding box..
let (_min_coordinates, _max_coordinates) = mesh.extreme_coordinates();
// .. or construct an actual mesh representing the axis aligned bounding box
let _aabb = mesh.axis_aligned_bounding_box();
let xform = points_to_xform(
Point3::new(0.5, 0.5, 0.0),
Point3::new(-0.5, 0.5, 0.0),
Point3::new(2.0, -4.0, 0.0),
);
println!("points_to_xform:");
print_matrix(&xform);
// Export the bounding box to an obj file
std::fs::write("foo.obj", mesh.parse_as_obj()).unwrap();
let r = Rule::Recurse(cube_thing_rule); let r = Rule::Recurse(cube_thing_rule);
let max_iters = 2; let max_iters = 2;
println!("Running rules..."); println!("Running rules...");
let (cubemesh, nodes) = rule_to_mesh(&r, vec![], max_iters); let (cubemesh_, nodes) = rule_to_mesh(&r, max_iters);
let cubemesh = cubemesh_.to_trimesh().unwrap();
println!("Collected {} nodes, produced {} faces, {} vertices", println!("Collected {} nodes, produced {} faces, {} vertices",
nodes, cubemesh.no_faces(), cubemesh.no_vertices()); nodes, cubemesh.no_faces(), cubemesh.no_vertices());
println!("Writing OBJ..."); println!("Writing OBJ...");
std::fs::write("cubemesh.obj", cubemesh.parse_as_obj()).unwrap(); std::fs::write("cubemesh.obj", cubemesh.parse_as_obj()).unwrap();
/*
let r2 = Rule::Recurse(curve_horn_start); let r2 = Rule::Recurse(curve_horn_start);
println!("Running rules..."); println!("Running rules...");
// Seed: // Seed:
let seed = { let seed = {
let indices: Vec<u32> = vec![0, 1, 2, 2, 1, 3]; let indices: Vec<u32> = vec![0, 1, 2, 2, 1, 3];
let positions: Vec<f64> = vec![0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0]; let positions: Vec<f64> = vec![0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0];
let mut s = MeshBuilder::new().with_indices(indices).with_positions(positions).build().unwrap(); let mut s = tm::MeshBuilder::new().with_indices(indices).with_positions(positions).build().unwrap();
s.apply_transformation(Matrix4::from_translation(vec3(-0.5, -0.5, 0.0))); s.apply_transformation(tm::Matrix4::from_translation(vec3(-0.5, -0.5, 0.0)));
s s
}; };
*/
// TEMP (while I figure shit out) // TEMP (while I figure shit out)
struct VID { val: usize }
fn vertex_id_to_usize(v: VertexID) -> usize {
let v: VID = unsafe { std::mem::transmute(v) };
v.val
}
println!("DEBUG-------------------------------");
let mb = MeshBound::new(&seed).unwrap();
let pos = seed.positions_buffer();
for bound_edge in mb {
let (v1, v2) = seed.edge_vertices(bound_edge);
let v1idx = vertex_id_to_usize(v1);
let v2idx = vertex_id_to_usize(v2);
println!("Boundary edge {}, vertices = {},{}, {:?}",
bound_edge, v1, v2, seed.edge_positions(bound_edge));
println!("v1idx={} pos[...]=[{},{},{}], v2idx={}, pos[...]=[{},{},{}]",
v1idx, pos[3*v1idx], pos[3*v1idx+1], pos[3*v1idx+2],
v2idx, pos[3*v2idx], pos[3*v2idx+1], pos[3*v2idx+2]);
}
println!("DEBUG-------------------------------"); println!("DEBUG-------------------------------");
let (mut mesh, nodes) = rule_to_mesh(&r2, vec![seed], 75);
println!("Collected {} nodes, produced {} faces, {} vertices",
nodes, mesh.no_faces(), mesh.no_vertices());
println!("Trying to merge...");
match mesh.merge_overlapping_primitives() {
Err(e) => {
println!("Couldn't merge overlapping primitives!");
println!("Error: {:?}", e);
}
Ok(_) => {
println!("Merged to {} faces, {} vertices",
mesh.no_faces(), mesh.no_vertices());
}
}
println!("Writing OBJ...");
std::fs::write("curve_horn_thing.obj", mesh.parse_as_obj()).unwrap();
// TODO: Can I make the seed geometry part of the rule itself?
} }