Trying type parameters instead

This commit is contained in:
Chris Hodapp 2020-02-27 21:51:34 -05:00
parent b454588f41
commit 4c626f6358
2 changed files with 381 additions and 349 deletions

View File

@ -6,52 +6,60 @@ use crate::rule::{Rule, RuleStep, Child};
use crate::prim; use crate::prim;
use crate::util; use crate::util;
fn curve_horn_start() -> RuleStep { struct CurveHorn {
let id = nalgebra::geometry::Transform3::identity().to_homogeneous(); seed: Vec<Vertex>,
let flip180 = nalgebra::geometry::Rotation3::from_axis_angle( id_xform: Mat4,
&nalgebra::Vector3::y_axis(), flip180: Mat4,
std::f32::consts::PI).to_homogeneous(); incr: Mat4,
RuleStep { }
geom: OpenMesh {
verts: vec![ impl CurveHorn {
fn init() -> CurveHorn {
let y = &Vector3::y_axis();
CurveHorn {
seed: vec![
vertex(-0.5, -0.5, 0.0), vertex(-0.5, -0.5, 0.0),
vertex(-0.5, 0.5, 0.0), vertex(-0.5, 0.5, 0.0),
vertex( 0.5, 0.5, 0.0), vertex( 0.5, 0.5, 0.0),
vertex( 0.5, -0.5, 0.0), vertex( 0.5, -0.5, 0.0),
], ],
id_xform: nalgebra::geometry::Transform3::identity().to_homogeneous(),
flip180: nalgebra::geometry::Rotation3::from_axis_angle(
&nalgebra::Vector3::y_axis(),
std::f32::consts::PI).to_homogeneous(),
incr: geometry::Rotation3::from_axis_angle(y, 0.1).to_homogeneous() *
Matrix4::new_scaling(0.95) *
geometry::Translation3::new(0.0, 0.0, 0.2).to_homogeneous(),
}
}
fn start(&self) -> RuleStep<Self> {
RuleStep {
geom: OpenMesh {
verts: self.seed.clone(),
faces: vec![], faces: vec![],
}, },
final_geom: prim::empty_mesh(), final_geom: prim::empty_mesh(),
children: vec![ children: vec![
Child { Child {
rule: Rule::Recurse(curve_horn_thing_rule), rule: Rule::Recurse(Self::recur),
xf: id, xf: self.id_xform,
vmap: vec![0,1,2,3], vmap: vec![0,1,2,3],
}, },
Child { Child {
rule: Rule::Recurse(curve_horn_thing_rule), rule: Rule::Recurse(Self::recur),
xf: flip180, xf: self.flip180,
vmap: vec![3,2,1,0], vmap: vec![3,2,1,0],
}, },
], ],
} }
} }
fn curve_horn_thing_rule() -> RuleStep { fn recur(&self) -> RuleStep<Self> {
let y = &Vector3::y_axis(); let verts = self.seed.clone();
let next_verts: Vec<Vertex> = verts.iter().map(|v| self.incr * v).collect();
let m: Mat4 = geometry::Rotation3::from_axis_angle(y, 0.1).to_homogeneous() *
Matrix4::new_scaling(0.95) *
geometry::Translation3::new(0.0, 0.0, 0.2).to_homogeneous();
let verts = vec![
vertex(-0.5, -0.5, 0.0),
vertex(-0.5, 0.5, 0.0),
vertex( 0.5, 0.5, 0.0),
vertex( 0.5, -0.5, 0.0),
];
let next_verts: Vec<Vertex> = verts.iter().map(|v| m * v).collect();
let geom = OpenMesh { let geom = OpenMesh {
verts: next_verts.clone(), verts: next_verts.clone(),
@ -86,15 +94,25 @@ fn curve_horn_thing_rule() -> RuleStep {
final_geom: final_geom, final_geom: final_geom,
children: vec![ children: vec![
Child { Child {
rule: Rule::Recurse(curve_horn_thing_rule), rule: Rule::Recurse(Self::recur),
xf: m, xf: self.incr,
vmap: vec![0,1,2,3], vmap: vec![0,1,2,3],
}, },
], ],
} }
}
} }
fn cube_thing_rule() -> RuleStep { struct CubeThing {
}
impl CubeThing {
fn init() -> CubeThing {
CubeThing {}
}
fn rec(&self) -> RuleStep<Self> {
let mesh = prim::cube(); let mesh = prim::cube();
@ -114,12 +132,12 @@ fn cube_thing_rule() -> RuleStep {
geometry::Rotation3::from_axis_angle(z, -qtr).to_homogeneous(), geometry::Rotation3::from_axis_angle(z, -qtr).to_homogeneous(),
]; ];
let gen_rulestep = |rot: &Mat4| -> Child { let gen_rulestep = |rot: &Mat4| -> Child<Self> {
let m: Mat4 = rot * let m: Mat4 = rot *
Matrix4::new_scaling(0.5) * Matrix4::new_scaling(0.5) *
geometry::Translation3::new(6.0, 0.0, 0.0).to_homogeneous(); geometry::Translation3::new(6.0, 0.0, 0.0).to_homogeneous();
Child { Child {
rule: Rule::Recurse(cube_thing_rule), rule: Rule::Recurse(Self::rec),
xf: m, xf: m,
vmap: vec![], vmap: vec![],
} }
@ -130,10 +148,20 @@ fn cube_thing_rule() -> RuleStep {
final_geom: prim::empty_mesh(), final_geom: prim::empty_mesh(),
children: turns.iter().map(gen_rulestep).collect(), children: turns.iter().map(gen_rulestep).collect(),
} }
}
} }
// Conversion from Python & automata_scratch struct RamHorn {
fn ram_horn_start() -> RuleStep { }
impl RamHorn {
fn init() -> RamHorn {
RamHorn{}
}
// Conversion from Python & automata_scratch
fn start(&self) -> RuleStep<Self> {
let opening_xform = |i| { let opening_xform = |i| {
let r = std::f32::consts::FRAC_PI_2 * i; let r = std::f32::consts::FRAC_PI_2 * i;
((geometry::Rotation3::from_axis_angle( ((geometry::Rotation3::from_axis_angle(
@ -189,22 +217,22 @@ fn ram_horn_start() -> RuleStep {
final_geom: prim::empty_mesh(), final_geom: prim::empty_mesh(),
children: vec![ children: vec![
Child { Child {
rule: Rule::Recurse(ram_horn), rule: Rule::Recurse(Self::ram_horn),
xf: opening_xform(0.0), xf: opening_xform(0.0),
vmap: vec![5,2,6,8], vmap: vec![5,2,6,8],
}, },
Child { Child {
rule: Rule::Recurse(ram_horn), rule: Rule::Recurse(Self::ram_horn),
xf: opening_xform(1.0), xf: opening_xform(1.0),
vmap: vec![4,1,5,8], vmap: vec![4,1,5,8],
}, },
Child { Child {
rule: Rule::Recurse(ram_horn), rule: Rule::Recurse(Self::ram_horn),
xf: opening_xform(2.0), xf: opening_xform(2.0),
vmap: vec![7,0,4,8], vmap: vec![7,0,4,8],
}, },
Child { Child {
rule: Rule::Recurse(ram_horn), rule: Rule::Recurse(Self::ram_horn),
xf: opening_xform(3.0), xf: opening_xform(3.0),
vmap: vec![6,3,7,8], vmap: vec![6,3,7,8],
}, },
@ -212,9 +240,9 @@ fn ram_horn_start() -> RuleStep {
// Explain *why* they are right. // Explain *why* they are right.
], ],
} }
} }
fn ram_horn() -> RuleStep { fn ram_horn(&self) -> RuleStep<Self> {
let v = Unit::new_normalize(Vector3::new(-1.0, 0.0, 1.0)); let v = Unit::new_normalize(Vector3::new(-1.0, 0.0, 1.0));
let incr: Mat4 = geometry::Translation3::new(0.0, 0.0, 0.8).to_homogeneous() * let incr: Mat4 = geometry::Translation3::new(0.0, 0.0, 0.8).to_homogeneous() *
geometry::Rotation3::from_axis_angle(&v, 0.3).to_homogeneous() * geometry::Rotation3::from_axis_angle(&v, 0.3).to_homogeneous() *
@ -251,53 +279,68 @@ fn ram_horn() -> RuleStep {
final_geom: final_geom, final_geom: final_geom,
children: vec![ children: vec![
Child { Child {
rule: Rule::Recurse(ram_horn), rule: Rule::Recurse(Self::ram_horn),
xf: incr, xf: incr,
vmap: vec![0,1,2,3], vmap: vec![0,1,2,3],
}, },
], ],
} }
}
} }
/* struct Twist {
fn ram_horn_branch() -> RuleStep { seed: Vec<Vertex>,
seed_sub: Vec<Vertex>,
dx0: f32,
dy: f32,
ang: f32,
count: usize,
subdiv: usize,
} }
*/
// Meant to be a copy of twist_from_gen from Python & automata_scratch impl Twist {
pub fn twist_start() -> RuleStep {
//let ang=0.1;
let dx0=2.0;
let count=4;
// TODO: Factor these out (see twist)
let seed = util::subdivide_cycle(&vec![ pub fn init() -> Twist {
let subdiv = 2;
let seed = vec![
vertex(-0.5, 0.0, -0.5), vertex(-0.5, 0.0, -0.5),
vertex( 0.5, 0.0, -0.5), vertex( 0.5, 0.0, -0.5),
vertex( 0.5, 0.0, 0.5), vertex( 0.5, 0.0, 0.5),
vertex(-0.5, 0.0, 0.5), vertex(-0.5, 0.0, 0.5),
], 2); ];
// TODO: Factor out let seed_sub = util::subdivide_cycle(&seed, subdiv);
let n = seed.len(); Twist {
// TODO: Factor out subdiv size dx0: 2.0,
dy: 0.1,
ang: 0.1,
count: 4,
seed: seed,
seed_sub: seed_sub,
subdiv: subdiv,
}
}
// Meant to be a copy of twist_from_gen from Python & automata_scratch
pub fn start(&self) -> RuleStep<Twist> {
let n = self.seed.len();
// Quarter-turn in radians: // Quarter-turn in radians:
let qtr = std::f32::consts::FRAC_PI_2; let qtr = std::f32::consts::FRAC_PI_2;
let y = &Vector3::y_axis(); let y = &Vector3::y_axis();
let xform = |i| { let xform = |i| {
(geometry::Rotation3::from_axis_angle(y, qtr * (i as f32)).to_homogeneous() * (geometry::Rotation3::from_axis_angle(y, qtr * (i as f32)).to_homogeneous() *
geometry::Translation3::new(dx0, 0.0, 0.0).to_homogeneous()) geometry::Translation3::new(self.dx0, 0.0, 0.0).to_homogeneous())
}; };
// First generate 'count' children, each one shifted/rotated // First generate 'count' children, each one shifted/rotated
// differently: // differently:
let children: Vec<Child> = (0..count).map(|i| { let children: Vec<Child<Twist>> = (0..self.count).map(|i| {
let xf = xform(i); let xf = xform(i);
Child { Child {
rule: Rule::Recurse(twist), rule: Rule::Recurse(Self::recur),
xf: xf, xf: xf,
vmap: (n*i..n*(i+count)).collect(), // N.B. vmap: (n*i..n*(i+self.count)).collect(), // N.B.
} }
}).collect(); }).collect();
@ -305,7 +348,7 @@ pub fn twist_start() -> RuleStep {
// this same transform: // this same transform:
let mut verts = vec![]; let mut verts = vec![];
for child in &children { for child in &children {
verts.extend(seed.iter().map(|v| child.xf * v)); verts.extend(self.seed_sub.iter().map(|v| child.xf * v));
} }
RuleStep { RuleStep {
@ -317,44 +360,33 @@ pub fn twist_start() -> RuleStep {
final_geom: prim::empty_mesh(), final_geom: prim::empty_mesh(),
children: children, children: children,
} }
} }
pub fn twist() -> RuleStep {
let ang=0.1;
let dx0=2.0;
let dy=0.1;
// TODO: Factor these out (see twist_start)
pub fn recur(&self) -> RuleStep<Twist> {
let y = &Vector3::y_axis(); let y = &Vector3::y_axis();
let incr = geometry::Translation3::new(-dx0, 0.0, 0.0).to_homogeneous() * let incr = geometry::Translation3::new(-self.dx0, 0.0, 0.0).to_homogeneous() *
geometry::Rotation3::from_axis_angle(y, ang).to_homogeneous() * geometry::Rotation3::from_axis_angle(y, self.ang).to_homogeneous() *
geometry::Translation3::new(dx0, dy, 0.0).to_homogeneous(); geometry::Translation3::new(self.dx0, self.dy, 0.0).to_homogeneous();
let seed_orig = vec![ let seed_orig = self.seed.iter().map(|v| incr * v).collect();
vertex(-0.5, 0.0, -0.5), let seed_sub = util::subdivide_cycle(&seed_orig, self.subdiv);
vertex( 0.5, 0.0, -0.5), let n = seed_sub.len();
vertex( 0.5, 0.0, 0.5),
vertex(-0.5, 0.0, 0.5),
// TODO: Likewise factor these out
].iter().map(|v| incr * v).collect();
let seed = util::subdivide_cycle(&seed_orig, 2);
let n = seed.len();
// TODO: Factor out subdiv size
RuleStep { RuleStep {
geom: OpenMesh { geom: OpenMesh {
verts: seed, verts: seed_sub,
faces: util::parallel_zigzag_faces(n), faces: util::parallel_zigzag_faces(n),
}, },
final_geom: prim::empty_mesh(), // TODO: Close properly final_geom: prim::empty_mesh(), // TODO: Close properly
children: vec![ children: vec![
Child { Child {
rule: Rule::Recurse(twist), rule: Rule::Recurse(Self::recur),
xf: incr, xf: incr,
vmap: (0..n).collect(), vmap: (0..n).collect(),
}, },
], ],
} }
}
} }
pub fn main() { pub fn main() {
@ -371,20 +403,20 @@ pub fn main() {
println!("vs2={:?}", vs2); println!("vs2={:?}", vs2);
} }
let run_test = |r: Rule, iters, name| { fn run_test<A>(a: A, r: Rule<A>, iters: u32, name: &str) {
println!("Running {}...", name); println!("Running {}...", name);
let (mesh, nodes) = r.to_mesh(iters); let (mesh, nodes) = r.to_mesh(&a, iters);
println!("Merged {} nodes", nodes); println!("Merged {} nodes", nodes);
let fname = format!("{}.stl", name); let fname = format!("{}.stl", name);
println!("Writing {}...", fname); println!("Writing {}...", fname);
mesh.write_stl_file(&fname).unwrap(); mesh.write_stl_file(&fname).unwrap();
}; }
run_test(Rule::Recurse(cube_thing_rule), 3, "cube_thing"); run_test(CubeThing::init(), Rule::Recurse(CubeThing::rec), 3, "cube_thing");
// this can't work on its own because the resultant OpenMesh still // this can't work on its own because the resultant OpenMesh still
// has parent references: // has parent references:
//run_test(Rule::Recurse(curve_horn_thing_rule), 100, "curve_horn_thing"); //run_test(Rule::Recurse(recur), 100, "curve_horn_thing");
run_test(Rule::Recurse(curve_horn_start), 100, "curve_horn2"); run_test(CurveHorn::init(), Rule::Recurse(CurveHorn::start), 100, "curve_horn2");
run_test(Rule::Recurse(ram_horn_start), 200, "ram_horn"); run_test(RamHorn::init(), Rule::Recurse(RamHorn::start), 200, "ram_horn");
run_test(Rule::Recurse(twist_start), 200, "twist"); run_test(Twist::init(), Rule::Recurse(Twist::start), 200, "twist");
} }

View File

@ -6,9 +6,9 @@ use crate::prim;
/// - produces geometry when it is evaluated /// - produces geometry when it is evaluated
/// - tells what other rules to invoke, and what to do with their /// - tells what other rules to invoke, and what to do with their
/// geometry /// geometry
pub enum Rule { pub enum Rule<A> {
/// Produce some geometry, and possibly recurse further. /// Produce some geometry, and possibly recurse further.
Recurse(fn () -> RuleStep), Recurse(fn (&A) -> RuleStep<A>),
/// Produce nothing and recurse no further. /// Produce nothing and recurse no further.
EmptyRule, EmptyRule,
} }
@ -28,7 +28,7 @@ pub enum Rule {
/// - if recursion continues, the rules of `children` are evaluated, /// - if recursion continues, the rules of `children` are evaluated,
/// and the resultant geometry is transformed and then connected with /// and the resultant geometry is transformed and then connected with
/// `geom`. /// `geom`.
pub struct RuleStep { pub struct RuleStep<A> {
/// The geometry generated at just this iteration /// The geometry generated at just this iteration
pub geom: OpenMesh, pub geom: OpenMesh,
@ -43,16 +43,16 @@ pub struct RuleStep {
/// The child invocations (used if recursion continues). The /// The child invocations (used if recursion continues). The
/// 'parent' mesh, from the perspective of all geometry produced /// 'parent' mesh, from the perspective of all geometry produced
/// by `children`, is `geom`. /// by `children`, is `geom`.
pub children: Vec<Child>, pub children: Vec<Child<A>>,
} }
/// `Child` evaluations, pairing another `Rule` with the /// `Child` evaluations, pairing another `Rule` with the
/// transformations and parent vertex mappings that should be applied /// transformations and parent vertex mappings that should be applied
/// to it. /// to it.
pub struct Child { pub struct Child<A> {
/// Rule to evaluate to produce geometry /// Rule to evaluate to produce geometry
pub rule: Rule, pub rule: Rule<A>,
/// The transform to apply to all geometry produced by `rule` /// The transform to apply to all geometry produced by `rule`
/// (including its own `geom` and `final_geom` if needed, as well /// (including its own `geom` and `final_geom` if needed, as well
@ -67,7 +67,7 @@ pub struct Child {
pub vmap: Vec<usize>, pub vmap: Vec<usize>,
} }
impl Rule { impl<A> Rule<A> {
// TODO: Do I want to make 'geom' shared somehow, maybe with Rc? I // TODO: Do I want to make 'geom' shared somehow, maybe with Rc? I
// could end up having a lot of identical geometry that need not be // could end up having a lot of identical geometry that need not be
@ -80,14 +80,14 @@ impl Rule {
/// Convert this `Rule` to mesh data, recursively. `iters_left` /// Convert this `Rule` to mesh data, recursively. `iters_left`
/// sets the maximum recursion depth. This returns (geometry, /// sets the maximum recursion depth. This returns (geometry,
/// number of rule evaluations). /// number of rule evaluations).
pub fn to_mesh(&self, iters_left: u32) -> (OpenMesh, u32) { pub fn to_mesh(&self, arg: &A, iters_left: u32) -> (OpenMesh, u32) {
let mut evals: u32 = 1; let mut evals: u32 = 1;
if iters_left <= 0 { if iters_left <= 0 {
match self { match self {
Rule::Recurse(f) => { Rule::Recurse(f) => {
let rs: RuleStep = f(); let rs: RuleStep<A> = f(arg);
return (rs.final_geom, 1); return (rs.final_geom, 1);
} }
Rule::EmptyRule => { Rule::EmptyRule => {
@ -98,13 +98,13 @@ impl Rule {
match self { match self {
Rule::Recurse(f) => { Rule::Recurse(f) => {
let rs: RuleStep = f(); let rs: RuleStep<A> = f(arg);
// TODO: This logic is more or less right, but it // TODO: This logic is more or less right, but it
// could perhaps use some un-tupling or something. // could perhaps use some un-tupling or something.
let subgeom: Vec<(OpenMesh, &Vec<usize>)> = rs.children.iter().map(|sub| { let subgeom: Vec<(OpenMesh, &Vec<usize>)> = rs.children.iter().map(|sub| {
// Get sub-geometry (still un-transformed): // Get sub-geometry (still un-transformed):
let (submesh, eval) = sub.rule.to_mesh(iters_left - 1); let (submesh, eval) = sub.rule.to_mesh(arg, iters_left - 1);
// Tally up eval count: // Tally up eval count:
evals += eval; evals += eval;