mirror of
https://github.com/Theaninova/Bampy.git
synced 2026-05-01 18:28:53 +00:00
Compare commits
4 Commits
cc22dcdfdd
...
5af73ed39a
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5af73ed39a | ||
|
f57e6c3f4e
|
|||
|
8c353107d8
|
|||
|
0e8479af91
|
177
;
Normal file
177
;
Normal file
@@ -0,0 +1,177 @@
|
|||||||
|
use super::{
|
||||||
|
axis::Axis,
|
||||||
|
base_slices::BaseSlice,
|
||||||
|
line::Line3,
|
||||||
|
slice_path::{SlicePath, SurfacePathIterator},
|
||||||
|
triangle::Triangle,
|
||||||
|
FloatValue,
|
||||||
|
};
|
||||||
|
use bvh::{
|
||||||
|
aabb::Aabb,
|
||||||
|
bvh::{Bvh, BvhNode},
|
||||||
|
};
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct Mesh {
|
||||||
|
pub aabb: Aabb<FloatValue, 3>,
|
||||||
|
pub bvh: Bvh<FloatValue, 3>,
|
||||||
|
pub triangles: Vec<Triangle>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<Vec<Triangle>> for Mesh {
|
||||||
|
fn from(mut triangles: Vec<Triangle>) -> Self {
|
||||||
|
Self {
|
||||||
|
aabb: triangles
|
||||||
|
.get(0)
|
||||||
|
.map(|triangle| {
|
||||||
|
let mut aabb = triangle.aabb;
|
||||||
|
for triangle in triangles.iter().skip(1) {
|
||||||
|
aabb.join_mut(&triangle.aabb);
|
||||||
|
}
|
||||||
|
aabb
|
||||||
|
})
|
||||||
|
.unwrap_or_else(|| Aabb::empty()),
|
||||||
|
bvh: Bvh::build(&mut triangles),
|
||||||
|
triangles,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Mesh {
|
||||||
|
pub fn slice_paths<'a>(
|
||||||
|
self: &'a Mesh,
|
||||||
|
axis: Axis,
|
||||||
|
slice_height: FloatValue,
|
||||||
|
) -> impl Iterator<Item = Vec<SlicePath>> + 'a {
|
||||||
|
self.slice_base_slices(axis, slice_height)
|
||||||
|
.map(|slice| slice.find_paths())
|
||||||
|
.filter(|paths| !paths.is_empty())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn slice_surface(&self, axis: Axis, nozzle_width: FloatValue) -> SurfacePathIterator {
|
||||||
|
SurfacePathIterator::new(self, axis, nozzle_width)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn slice_base_slices<'a>(
|
||||||
|
self: &'a Mesh,
|
||||||
|
axis: Axis,
|
||||||
|
slice_height: FloatValue,
|
||||||
|
) -> impl Iterator<Item = BaseSlice> + 'a {
|
||||||
|
let layer_count = ((self.aabb.max[axis as usize] - self.aabb.min[axis as usize])
|
||||||
|
/ slice_height)
|
||||||
|
.floor() as usize;
|
||||||
|
|
||||||
|
(0..layer_count).map(move |i| {
|
||||||
|
let layer = i as FloatValue * slice_height + self.aabb.min[axis as usize];
|
||||||
|
let mut base_slice = BaseSlice {
|
||||||
|
i,
|
||||||
|
d: layer,
|
||||||
|
axis,
|
||||||
|
lines: vec![],
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut stack = Vec::<usize>::with_capacity(self.bvh.nodes.len());
|
||||||
|
stack.push(0);
|
||||||
|
while let Some(i) = stack.pop() {
|
||||||
|
match self.bvh.nodes[i] {
|
||||||
|
BvhNode::Node {
|
||||||
|
parent_index: _,
|
||||||
|
child_l_index,
|
||||||
|
child_l_aabb,
|
||||||
|
child_r_index,
|
||||||
|
child_r_aabb,
|
||||||
|
} => {
|
||||||
|
assert!(child_l_aabb.min[axis as usize] <= child_l_aabb.max[axis as usize]);
|
||||||
|
assert!(child_r_aabb.min[axis as usize] <= child_r_aabb.max[axis as usize]);
|
||||||
|
if layer >= child_l_aabb.min[axis as usize]
|
||||||
|
&& layer <= child_l_aabb.max[axis as usize]
|
||||||
|
{
|
||||||
|
stack.push(child_l_index);
|
||||||
|
}
|
||||||
|
if layer >= child_r_aabb.min[axis as usize]
|
||||||
|
&& layer <= child_r_aabb.max[axis as usize]
|
||||||
|
{
|
||||||
|
stack.push(child_r_index);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
BvhNode::Leaf {
|
||||||
|
parent_index: _,
|
||||||
|
shape_index,
|
||||||
|
} => {
|
||||||
|
for line in self.triangles[shape_index].intersect(layer, axis as usize) {
|
||||||
|
base_slice.lines.push(line);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
base_slice
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn outline_base_slice(&self, axis: Axis) -> BaseSlice {
|
||||||
|
let mut base_slice = BaseSlice {
|
||||||
|
i: 0,
|
||||||
|
d: 0.0,
|
||||||
|
axis,
|
||||||
|
lines: vec![],
|
||||||
|
};
|
||||||
|
'triangle: for (i, triangle) in self.triangles.iter().enumerate() {
|
||||||
|
let mut stack = Vec::<usize>::with_capacity(self.bvh.nodes.len());
|
||||||
|
stack.push(0);
|
||||||
|
let mut ab = false;
|
||||||
|
let mut ac = false;
|
||||||
|
let mut bc = false;
|
||||||
|
while let Some(i) = stack.pop() {
|
||||||
|
match self.bvh.nodes[i] {
|
||||||
|
BvhNode::Node {
|
||||||
|
parent_index: _,
|
||||||
|
child_l_index,
|
||||||
|
child_l_aabb,
|
||||||
|
child_r_index,
|
||||||
|
child_r_aabb,
|
||||||
|
} => {
|
||||||
|
let coords = [triangle.a, triangle.b, triangle.c];
|
||||||
|
macro_rules! match_aabb {
|
||||||
|
($side:expr) => {
|
||||||
|
coords
|
||||||
|
.iter()
|
||||||
|
.map(|point| {
|
||||||
|
$side.approx_contains_eps(point, FloatValue::EPSILON) as i32
|
||||||
|
})
|
||||||
|
.sum::<i32>()
|
||||||
|
>= 2
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if match_aabb!(child_l_aabb) {
|
||||||
|
stack.push(child_l_index);
|
||||||
|
}
|
||||||
|
if match_aabb!(child_r_aabb) {
|
||||||
|
stack.push(child_r_index);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
BvhNode::Leaf {
|
||||||
|
parent_index: _,
|
||||||
|
shape_index,
|
||||||
|
} => {
|
||||||
|
if i == shape_index {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let other = &self.triangles[shape_index];
|
||||||
|
let a = triangle.has_point(other.a);
|
||||||
|
let b = triangle.has_point(other.b);
|
||||||
|
let c = triangle.has_point(other.c);
|
||||||
|
ab = ab || (a && b);
|
||||||
|
ac = ac || (a && c);
|
||||||
|
bc = bc || (b && c);
|
||||||
|
|
||||||
|
if ab && ac && bc {
|
||||||
|
continue 'triangle;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
base_slice
|
||||||
|
}
|
||||||
|
}
|
||||||
215
bampy/src/lib.rs
215
bampy/src/lib.rs
@@ -1,56 +1,29 @@
|
|||||||
|
#![feature(extract_if)]
|
||||||
|
use std::collections::VecDeque;
|
||||||
|
|
||||||
use approx::relative_eq;
|
use approx::relative_eq;
|
||||||
use nalgebra::{vector, Vector3};
|
use nalgebra::{point, vector, Vector3};
|
||||||
use serde::{Deserialize, Serialize};
|
use num::Float;
|
||||||
use tsify::Tsify;
|
use result::{Slice, SliceOptions, SliceResult};
|
||||||
|
use slicer::{axis::Axis, slice_path::SlicePath, trace_surface::trace_surface};
|
||||||
use wasm_bindgen::prelude::wasm_bindgen;
|
use wasm_bindgen::prelude::wasm_bindgen;
|
||||||
|
|
||||||
use crate::slicer::{
|
use crate::slicer::{mesh::Mesh, split_surface::split_surface, triangle::Triangle, FloatValue};
|
||||||
base_slices::create_slices, mesh::Mesh, split_surface::split_surface,
|
|
||||||
trace_surface::trace_surface, triangle::Triangle, FloatValue, SlicerOptions,
|
|
||||||
};
|
|
||||||
|
|
||||||
|
mod result;
|
||||||
mod slicer;
|
mod slicer;
|
||||||
mod util;
|
mod util;
|
||||||
|
|
||||||
const BED_NORMAL: Vector3<f64> = vector![0f64, 0f64, 1f64];
|
const BED_NORMAL: Vector3<f64> = vector![0f64, 0f64, 1f64];
|
||||||
|
|
||||||
#[derive(Tsify, Serialize, Deserialize)]
|
|
||||||
#[serde(rename_all = "camelCase")]
|
|
||||||
#[tsify(from_wasm_abi)]
|
|
||||||
pub struct SliceOptions {
|
|
||||||
#[tsify(type = "Float32Array")]
|
|
||||||
positions: Vec<f32>,
|
|
||||||
layer_height: f64,
|
|
||||||
max_angle: f64,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Tsify, Serialize, Deserialize)]
|
|
||||||
#[serde(rename_all = "camelCase", tag = "type")]
|
|
||||||
#[tsify(into_wasm_abi)]
|
|
||||||
pub enum Slice {
|
|
||||||
Surface {
|
|
||||||
#[tsify(type = "Float32Array")]
|
|
||||||
position: Vec<f32>,
|
|
||||||
},
|
|
||||||
Ring {
|
|
||||||
#[tsify(type = "Float32Array")]
|
|
||||||
position: Vec<f32>,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Tsify, Serialize, Deserialize)]
|
|
||||||
#[serde(rename_all = "camelCase")]
|
|
||||||
#[tsify(into_wasm_abi)]
|
|
||||||
pub struct SliceResult {
|
|
||||||
slices: Vec<Slice>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[wasm_bindgen]
|
#[wasm_bindgen]
|
||||||
pub fn slice(
|
pub fn slice(
|
||||||
SliceOptions {
|
SliceOptions {
|
||||||
positions,
|
positions,
|
||||||
layer_height,
|
layer_height,
|
||||||
max_angle,
|
max_angle,
|
||||||
|
min_surface_path_length,
|
||||||
|
nozzle_diameter,
|
||||||
}: SliceOptions,
|
}: SliceOptions,
|
||||||
) -> SliceResult {
|
) -> SliceResult {
|
||||||
std::panic::set_hook(Box::new(console_error_panic_hook::hook));
|
std::panic::set_hook(Box::new(console_error_panic_hook::hook));
|
||||||
@@ -61,17 +34,17 @@ pub fn slice(
|
|||||||
let mut slicable_triangles = Vec::<Triangle>::with_capacity(positions.len() / 9);
|
let mut slicable_triangles = Vec::<Triangle>::with_capacity(positions.len() / 9);
|
||||||
for i in (0..positions.len()).step_by(9) {
|
for i in (0..positions.len()).step_by(9) {
|
||||||
let triangle = Triangle::new(
|
let triangle = Triangle::new(
|
||||||
vector![
|
point![
|
||||||
positions[i] as FloatValue,
|
positions[i] as FloatValue,
|
||||||
positions[i + 1] as FloatValue,
|
positions[i + 1] as FloatValue,
|
||||||
positions[i + 2] as FloatValue
|
positions[i + 2] as FloatValue
|
||||||
],
|
],
|
||||||
vector![
|
point![
|
||||||
positions[i + 3] as FloatValue,
|
positions[i + 3] as FloatValue,
|
||||||
positions[i + 4] as FloatValue,
|
positions[i + 4] as FloatValue,
|
||||||
positions[i + 5] as FloatValue
|
positions[i + 5] as FloatValue
|
||||||
],
|
],
|
||||||
vector![
|
point![
|
||||||
positions[i + 6] as FloatValue,
|
positions[i + 6] as FloatValue,
|
||||||
positions[i + 7] as FloatValue,
|
positions[i + 7] as FloatValue,
|
||||||
positions[i + 8] as FloatValue
|
positions[i + 8] as FloatValue
|
||||||
@@ -79,42 +52,122 @@ pub fn slice(
|
|||||||
);
|
);
|
||||||
|
|
||||||
slicable_triangles.push(triangle);
|
slicable_triangles.push(triangle);
|
||||||
let angle = triangle.normal.angle(&BED_NORMAL);
|
let mut normal = triangle.normal.clone();
|
||||||
let opposite_angle = std::f64::consts::PI - angle;
|
normal.z = normal.z.abs();
|
||||||
if angle <= max_angle
|
let angle = normal.angle(&BED_NORMAL);
|
||||||
|| relative_eq!(angle, max_angle)
|
if angle <= max_angle || relative_eq!(angle, max_angle) {
|
||||||
|| opposite_angle <= max_angle
|
|
||||||
|| relative_eq!(opposite_angle, max_angle)
|
|
||||||
{
|
|
||||||
surface_triangles.push(triangle);
|
surface_triangles.push(triangle);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
slicable_triangles.shrink_to_fit();
|
slicable_triangles.shrink_to_fit();
|
||||||
surface_triangles.shrink_to_fit();
|
surface_triangles.shrink_to_fit();
|
||||||
|
|
||||||
let slicer_options = SlicerOptions { layer_height };
|
|
||||||
|
|
||||||
console_log!("Creating Surfaces");
|
console_log!("Creating Surfaces");
|
||||||
let surfaces = split_surface(surface_triangles);
|
let min_surface_area = std::f64::consts::PI * (nozzle_diameter / 2.0).powi(2);
|
||||||
|
let mut surfaces = split_surface(surface_triangles)
|
||||||
console_log!("Computing BVH");
|
.into_iter()
|
||||||
let slicable = Mesh::from(slicable_triangles);
|
.filter(|mesh| {
|
||||||
console_log!("Creating Slices");
|
let mut surface_area = 0.0;
|
||||||
let mut slices = create_slices(&slicer_options, &slicable);
|
for triangle in &mesh.triangles {
|
||||||
|
surface_area += triangle.area();
|
||||||
/*console_log!("Tracing Surfaces");
|
if surface_area >= min_surface_area {
|
||||||
let a = max_angle.tan();
|
return true;
|
||||||
for slice in &mut slices {
|
}
|
||||||
for surface in &surfaces {
|
}
|
||||||
if surface.aabb.min.z <= slice.z && surface.aabb.max.z > slice.z {
|
return false;
|
||||||
trace_surface(slice, surface, a);
|
})
|
||||||
|
.map(|mesh| {
|
||||||
|
let outline = mesh
|
||||||
|
.outline_base_slice(Axis::Z)
|
||||||
|
.find_paths()
|
||||||
|
.into_iter()
|
||||||
|
.filter(|path| path.closed)
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
let surface = mesh
|
||||||
|
.slice_surface(Axis::X, nozzle_diameter)
|
||||||
|
.filter(|path| {
|
||||||
|
let mut length = 0.0;
|
||||||
|
for pair in path.path.windows(2) {
|
||||||
|
length += (pair[0].coords - pair[1].coords).norm();
|
||||||
|
if length >= min_surface_path_length {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
(mesh, outline, surface)
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
surfaces
|
||||||
|
.sort_unstable_by(|(a, _, _), (b, _, _)| a.aabb.min.z.partial_cmp(&b.aabb.min.z).unwrap());
|
||||||
|
|
||||||
|
console_log!("Creating Walls");
|
||||||
|
let wallMesh = Mesh::from(slicable_triangles);
|
||||||
|
let mut walls = wallMesh
|
||||||
|
.slice_paths(Axis::Z, layer_height)
|
||||||
|
.flat_map(|paths| paths.into_iter().filter(|path| path.closed))
|
||||||
|
.collect::<VecDeque<_>>();
|
||||||
|
let mut active_surfaces = Vec::new();
|
||||||
|
let mut out = Vec::new();
|
||||||
|
|
||||||
|
console_log!("Resolving dependencies");
|
||||||
|
while let Some(mut wall) = walls.pop_front() {
|
||||||
|
active_surfaces.extend(
|
||||||
|
surfaces
|
||||||
|
.extract_if(|surface| surface.0.aabb.min.z <= wall.aabb.max.z)
|
||||||
|
.map(|surface| (surface, Vec::new())),
|
||||||
|
);
|
||||||
|
|
||||||
|
let deactivate =
|
||||||
|
active_surfaces.extract_if(|element| element.0 .0.aabb.max.z < wall.aabb.min.z);
|
||||||
|
for (surface, surface_walls) in deactivate {
|
||||||
|
for ring in surface.1 {
|
||||||
|
out.push(ring.points);
|
||||||
|
}
|
||||||
|
for path in surface.2 {
|
||||||
|
out.push(path.path);
|
||||||
|
}
|
||||||
|
for wall in surface_walls {
|
||||||
|
walls.push_front(wall);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for surface in active_surfaces.iter_mut() {
|
||||||
|
let held = wall
|
||||||
|
.points
|
||||||
|
.extract_if(|point| !trace_surface(&point, &surface.0 .0, max_angle))
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
if !held.is_empty() {
|
||||||
|
surface.1.push(SlicePath {
|
||||||
|
points: held,
|
||||||
|
..wall
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if !wall.points.is_empty() {
|
||||||
|
out.push(wall.points);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}*/
|
|
||||||
|
|
||||||
console_log!("Done");
|
console_log!("Done");
|
||||||
SliceResult {
|
SliceResult {
|
||||||
slices: slices
|
slices: out
|
||||||
|
.into_iter()
|
||||||
|
.map(|slice| Slice::Ring {
|
||||||
|
position: slice
|
||||||
|
.into_iter()
|
||||||
|
.flat_map(|point| [point.x as f32, point.y as f32, point.z as f32])
|
||||||
|
.collect(),
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
}
|
||||||
|
/*SliceResult {
|
||||||
|
slices: surfaces
|
||||||
|
.into_iter()
|
||||||
|
.flat_map(|(_, outlines, slices)| {
|
||||||
|
outlines
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|slice| Slice::Ring {
|
.map(|slice| Slice::Ring {
|
||||||
position: slice
|
position: slice
|
||||||
@@ -123,27 +176,25 @@ pub fn slice(
|
|||||||
.flat_map(|point| [point.x as f32, point.y as f32, point.z as f32])
|
.flat_map(|point| [point.x as f32, point.y as f32, point.z as f32])
|
||||||
.collect(),
|
.collect(),
|
||||||
})
|
})
|
||||||
.chain(surfaces.into_iter().map(|surface| {
|
.chain(slices.into_iter().map(|slice| {
|
||||||
Slice::Surface {
|
Slice::Ring {
|
||||||
position: surface
|
position: slice
|
||||||
.triangles
|
.path
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.flat_map(|triangle| {
|
.flat_map(|point| [point.x as f32, point.y as f32, point.z as f32])
|
||||||
[
|
.collect(),
|
||||||
triangle.a.x as f32,
|
}
|
||||||
triangle.a.y as f32,
|
}))
|
||||||
triangle.a.z as f32,
|
|
||||||
triangle.b.x as f32,
|
|
||||||
triangle.b.y as f32,
|
|
||||||
triangle.b.z as f32,
|
|
||||||
triangle.c.x as f32,
|
|
||||||
triangle.c.y as f32,
|
|
||||||
triangle.c.z as f32,
|
|
||||||
]
|
|
||||||
})
|
})
|
||||||
|
.chain(walls.flatten().map(|slice| {
|
||||||
|
Slice::Ring {
|
||||||
|
position: slice
|
||||||
|
.points
|
||||||
|
.into_iter()
|
||||||
|
.flat_map(|point| [point.x as f32, point.y as f32, point.z as f32])
|
||||||
.collect(),
|
.collect(),
|
||||||
}
|
}
|
||||||
}))
|
}))
|
||||||
.collect(),
|
.collect(),
|
||||||
}
|
}*/
|
||||||
}
|
}
|
||||||
|
|||||||
39
bampy/src/result.rs
Normal file
39
bampy/src/result.rs
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use tsify::Tsify;
|
||||||
|
|
||||||
|
#[derive(Tsify, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
#[tsify(from_wasm_abi)]
|
||||||
|
pub struct SliceOptions {
|
||||||
|
#[tsify(type = "Float32Array")]
|
||||||
|
pub positions: Vec<f32>,
|
||||||
|
pub layer_height: f64,
|
||||||
|
pub nozzle_diameter: f64,
|
||||||
|
pub max_angle: f64,
|
||||||
|
pub min_surface_path_length: f64,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Tsify, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase", tag = "type")]
|
||||||
|
#[tsify(into_wasm_abi)]
|
||||||
|
pub enum Slice {
|
||||||
|
Surface {
|
||||||
|
#[tsify(type = "Float32Array")]
|
||||||
|
position: Vec<f32>,
|
||||||
|
},
|
||||||
|
Ring {
|
||||||
|
#[tsify(type = "Float32Array")]
|
||||||
|
position: Vec<f32>,
|
||||||
|
},
|
||||||
|
Path {
|
||||||
|
#[tsify(type = "Float32Array")]
|
||||||
|
position: Vec<f32>,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Tsify, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
#[tsify(into_wasm_abi)]
|
||||||
|
pub struct SliceResult {
|
||||||
|
pub slices: Vec<Slice>,
|
||||||
|
}
|
||||||
30
bampy/src/slicer/axis.rs
Normal file
30
bampy/src/slicer/axis.rs
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
use nalgebra::Vector3;
|
||||||
|
|
||||||
|
use super::FloatValue;
|
||||||
|
|
||||||
|
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
|
||||||
|
#[repr(usize)]
|
||||||
|
pub enum Axis {
|
||||||
|
#[default]
|
||||||
|
X = 0,
|
||||||
|
Y = 1,
|
||||||
|
Z = 2,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Axis {
|
||||||
|
pub fn other(&self) -> (Self, Self) {
|
||||||
|
match self {
|
||||||
|
Axis::X => (Axis::Y, Axis::Z),
|
||||||
|
Axis::Y => (Axis::X, Axis::Z),
|
||||||
|
Axis::Z => (Axis::X, Axis::Y),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn normal(&self) -> Vector3<FloatValue> {
|
||||||
|
match self {
|
||||||
|
Axis::X => Vector3::x(),
|
||||||
|
Axis::Y => Vector3::y(),
|
||||||
|
Axis::Z => Vector3::z(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,66 +1,82 @@
|
|||||||
use super::{
|
use super::{aabb_from_points, axis::Axis, line::Line3, slice_path::SlicePath, FloatValue};
|
||||||
line::Line3,
|
use approx::relative_eq;
|
||||||
mesh::Mesh,
|
use nalgebra::Point3;
|
||||||
slice_rings::{find_slice_rings, SliceRing},
|
|
||||||
FloatValue, SlicerOptions,
|
|
||||||
};
|
|
||||||
use bvh::bvh::BvhNode;
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct BaseSlice {
|
pub struct BaseSlice {
|
||||||
pub z: FloatValue,
|
pub i: usize,
|
||||||
|
pub d: FloatValue,
|
||||||
|
pub axis: Axis,
|
||||||
pub lines: Vec<Line3>,
|
pub lines: Vec<Line3>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Creates base slices from the geometry, excluding surfaces.
|
impl BaseSlice {
|
||||||
/// The slicse are not sorted or separated into rings.
|
pub fn find_paths(mut self) -> Vec<SlicePath> {
|
||||||
pub fn create_slices(options: &SlicerOptions, slicable: &Mesh) -> Vec<SliceRing> {
|
let (axis_a, axis_b) = self.axis.other();
|
||||||
let layer_count = (slicable.aabb.max.z / options.layer_height).floor() as usize;
|
|
||||||
let mut rings = vec![];
|
let mut rings = vec![];
|
||||||
let mut layer_index = 0;
|
while let Some(line) = self.lines.pop() {
|
||||||
|
if relative_eq!(line.start, line.end) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let mut right = vec![line.end];
|
||||||
|
let mut left = vec![line.start];
|
||||||
|
let mut previous_len = usize::MAX;
|
||||||
|
let mut closed = false;
|
||||||
|
|
||||||
for i in 0..layer_count {
|
while !closed {
|
||||||
let layer = i as FloatValue * options.layer_height;
|
if previous_len == self.lines.len() {
|
||||||
let mut base_slice = BaseSlice {
|
break;
|
||||||
z: layer,
|
}
|
||||||
lines: vec![],
|
previous_len = self.lines.len();
|
||||||
|
|
||||||
|
self.lines.retain_mut(|line| {
|
||||||
|
if closed {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
let test = |side: &mut Vec<Point3<FloatValue>>| {
|
||||||
|
let last = side.last().unwrap();
|
||||||
|
let s = relative_eq!(line.start, last);
|
||||||
|
let e = relative_eq!(line.end, last);
|
||||||
|
if s && !e {
|
||||||
|
side.push(line.end);
|
||||||
|
} else if !s && e {
|
||||||
|
side.push(line.start);
|
||||||
|
}
|
||||||
|
s || e
|
||||||
};
|
};
|
||||||
|
|
||||||
let mut stack = Vec::<usize>::with_capacity(slicable.bvh.nodes.len());
|
if test(&mut left) || test(&mut right) {
|
||||||
stack.push(0);
|
closed = relative_eq!(left.last().unwrap(), right.last().unwrap());
|
||||||
while let Some(i) = stack.pop() {
|
false
|
||||||
match slicable.bvh.nodes[i] {
|
} else {
|
||||||
BvhNode::Node {
|
true
|
||||||
parent_index: _,
|
|
||||||
child_l_index,
|
|
||||||
child_l_aabb,
|
|
||||||
child_r_index,
|
|
||||||
child_r_aabb,
|
|
||||||
} => {
|
|
||||||
assert!(child_l_aabb.min.z <= child_l_aabb.max.z);
|
|
||||||
assert!(child_r_aabb.min.z <= child_r_aabb.max.z);
|
|
||||||
if layer >= child_l_aabb.min.z && layer <= child_l_aabb.max.z {
|
|
||||||
stack.push(child_l_index);
|
|
||||||
}
|
|
||||||
if layer >= child_r_aabb.min.z && layer <= child_r_aabb.max.z {
|
|
||||||
stack.push(child_r_index);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
BvhNode::Leaf {
|
|
||||||
parent_index: _,
|
|
||||||
shape_index,
|
|
||||||
} => {
|
|
||||||
slicable.triangles[shape_index]
|
|
||||||
.intersect_z(layer)
|
|
||||||
.map(|line| {
|
|
||||||
base_slice.lines.push(line);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
rings.append(&mut find_slice_rings(base_slice, &mut layer_index));
|
left.reverse();
|
||||||
|
left.extend(right);
|
||||||
|
let mut ring = SlicePath {
|
||||||
|
d: self.d,
|
||||||
|
i: self.i,
|
||||||
|
axis: self.axis,
|
||||||
|
closed,
|
||||||
|
aabb: aabb_from_points(left.iter()),
|
||||||
|
points: left,
|
||||||
|
};
|
||||||
|
|
||||||
|
if ring.points.windows(2).fold(0.0, |acc, curr| {
|
||||||
|
acc + (curr[1][axis_a as usize] - curr[0][axis_a as usize])
|
||||||
|
* (curr[1][axis_b as usize] + curr[0][axis_b as usize])
|
||||||
|
}) < 0.0
|
||||||
|
{
|
||||||
|
ring.points.reverse();
|
||||||
|
}
|
||||||
|
|
||||||
|
rings.push(ring);
|
||||||
}
|
}
|
||||||
|
|
||||||
rings
|
rings
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
use nalgebra::Vector3;
|
use nalgebra::{Point3, Vector3};
|
||||||
|
|
||||||
use super::FloatValue;
|
use super::FloatValue;
|
||||||
|
|
||||||
@@ -8,6 +8,20 @@ use super::FloatValue;
|
|||||||
/// meaning the inside is on the right hand side of the line.
|
/// meaning the inside is on the right hand side of the line.
|
||||||
#[derive(Debug, PartialEq, Clone, Copy)]
|
#[derive(Debug, PartialEq, Clone, Copy)]
|
||||||
pub struct Line3 {
|
pub struct Line3 {
|
||||||
pub start: Vector3<FloatValue>,
|
pub start: Point3<FloatValue>,
|
||||||
pub end: Vector3<FloatValue>,
|
pub end: Point3<FloatValue>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Line3 {
|
||||||
|
pub fn new(start: Point3<FloatValue>, end: Point3<FloatValue>) -> Self {
|
||||||
|
Self { start, end }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn norm(&self) -> FloatValue {
|
||||||
|
(self.end - self.start).norm()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn normal(&self) -> Vector3<FloatValue> {
|
||||||
|
(self.end - self.start).normalize()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,15 @@
|
|||||||
use super::{triangle::Triangle, FloatValue};
|
use super::{
|
||||||
use bvh::{aabb::Aabb, bvh::Bvh};
|
axis::Axis,
|
||||||
|
base_slices::BaseSlice,
|
||||||
|
line::Line3,
|
||||||
|
slice_path::{SlicePath, SurfacePathIterator},
|
||||||
|
triangle::Triangle,
|
||||||
|
FloatValue,
|
||||||
|
};
|
||||||
|
use bvh::{
|
||||||
|
aabb::Aabb,
|
||||||
|
bvh::{Bvh, BvhNode},
|
||||||
|
};
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct Mesh {
|
pub struct Mesh {
|
||||||
@@ -26,3 +36,151 @@ impl From<Vec<Triangle>> for Mesh {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl Mesh {
|
||||||
|
pub fn slice_paths<'a>(
|
||||||
|
self: &'a Mesh,
|
||||||
|
axis: Axis,
|
||||||
|
slice_height: FloatValue,
|
||||||
|
) -> impl Iterator<Item = Vec<SlicePath>> + 'a {
|
||||||
|
self.slice_base_slices(axis, slice_height)
|
||||||
|
.map(|slice| slice.find_paths())
|
||||||
|
.filter(|paths| !paths.is_empty())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn slice_surface(&self, axis: Axis, nozzle_width: FloatValue) -> SurfacePathIterator {
|
||||||
|
SurfacePathIterator::new(self, axis, nozzle_width)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn slice_base_slices<'a>(
|
||||||
|
self: &'a Mesh,
|
||||||
|
axis: Axis,
|
||||||
|
slice_height: FloatValue,
|
||||||
|
) -> impl Iterator<Item = BaseSlice> + 'a {
|
||||||
|
let layer_count = ((self.aabb.max[axis as usize] - self.aabb.min[axis as usize])
|
||||||
|
/ slice_height)
|
||||||
|
.floor() as usize;
|
||||||
|
|
||||||
|
(0..=layer_count).map(move |i| {
|
||||||
|
let layer = i as FloatValue * slice_height + self.aabb.min[axis as usize];
|
||||||
|
let mut base_slice = BaseSlice {
|
||||||
|
i,
|
||||||
|
d: layer,
|
||||||
|
axis,
|
||||||
|
lines: vec![],
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut stack = Vec::<usize>::with_capacity(self.bvh.nodes.len());
|
||||||
|
stack.push(0);
|
||||||
|
while let Some(i) = stack.pop() {
|
||||||
|
match self.bvh.nodes[i] {
|
||||||
|
BvhNode::Node {
|
||||||
|
parent_index: _,
|
||||||
|
child_l_index,
|
||||||
|
child_l_aabb,
|
||||||
|
child_r_index,
|
||||||
|
child_r_aabb,
|
||||||
|
} => {
|
||||||
|
assert!(child_l_aabb.min[axis as usize] <= child_l_aabb.max[axis as usize]);
|
||||||
|
assert!(child_r_aabb.min[axis as usize] <= child_r_aabb.max[axis as usize]);
|
||||||
|
if layer >= child_l_aabb.min[axis as usize]
|
||||||
|
&& layer <= child_l_aabb.max[axis as usize]
|
||||||
|
{
|
||||||
|
stack.push(child_l_index);
|
||||||
|
}
|
||||||
|
if layer >= child_r_aabb.min[axis as usize]
|
||||||
|
&& layer <= child_r_aabb.max[axis as usize]
|
||||||
|
{
|
||||||
|
stack.push(child_r_index);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
BvhNode::Leaf {
|
||||||
|
parent_index: _,
|
||||||
|
shape_index,
|
||||||
|
} => {
|
||||||
|
for line in self.triangles[shape_index].intersect(layer, axis as usize) {
|
||||||
|
base_slice.lines.push(line);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
base_slice
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn outline_base_slice(&self, axis: Axis) -> BaseSlice {
|
||||||
|
let mut base_slice = BaseSlice {
|
||||||
|
i: 0,
|
||||||
|
d: 0.0,
|
||||||
|
axis,
|
||||||
|
lines: vec![],
|
||||||
|
};
|
||||||
|
'triangle: for (triangle_index, triangle) in self.triangles.iter().enumerate() {
|
||||||
|
let mut stack = Vec::<usize>::with_capacity(self.bvh.nodes.len());
|
||||||
|
stack.push(0);
|
||||||
|
let mut ab = false;
|
||||||
|
let mut ac = false;
|
||||||
|
let mut bc = false;
|
||||||
|
while let Some(i) = stack.pop() {
|
||||||
|
match self.bvh.nodes[i] {
|
||||||
|
BvhNode::Node {
|
||||||
|
parent_index: _,
|
||||||
|
child_l_index,
|
||||||
|
child_l_aabb,
|
||||||
|
child_r_index,
|
||||||
|
child_r_aabb,
|
||||||
|
} => {
|
||||||
|
let coords = [triangle.a, triangle.b, triangle.c];
|
||||||
|
macro_rules! match_aabb {
|
||||||
|
($side:expr) => {
|
||||||
|
coords
|
||||||
|
.iter()
|
||||||
|
.map(|point| {
|
||||||
|
$side.approx_contains_eps(point, FloatValue::EPSILON) as i32
|
||||||
|
})
|
||||||
|
.sum::<i32>()
|
||||||
|
>= 2
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if match_aabb!(child_l_aabb) {
|
||||||
|
stack.push(child_l_index);
|
||||||
|
}
|
||||||
|
if match_aabb!(child_r_aabb) {
|
||||||
|
stack.push(child_r_index);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
BvhNode::Leaf {
|
||||||
|
parent_index: _,
|
||||||
|
shape_index,
|
||||||
|
} => {
|
||||||
|
if triangle_index == shape_index {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let other = &self.triangles[shape_index];
|
||||||
|
let a = other.has_point(triangle.a);
|
||||||
|
let b = other.has_point(triangle.b);
|
||||||
|
let c = other.has_point(triangle.c);
|
||||||
|
ab = ab || (a && b);
|
||||||
|
ac = ac || (a && c);
|
||||||
|
bc = bc || (b && c);
|
||||||
|
|
||||||
|
if ab && ac && bc {
|
||||||
|
continue 'triangle;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !ab {
|
||||||
|
base_slice.lines.push(Line3::new(triangle.a, triangle.b));
|
||||||
|
}
|
||||||
|
if !ac {
|
||||||
|
base_slice.lines.push(Line3::new(triangle.a, triangle.c));
|
||||||
|
}
|
||||||
|
if !bc {
|
||||||
|
base_slice.lines.push(Line3::new(triangle.b, triangle.c));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
base_slice
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,9 +1,13 @@
|
|||||||
use std::fmt::Debug;
|
use bvh::aabb::{Aabb, Bounded};
|
||||||
|
use bvh::bounding_hierarchy::BHValue;
|
||||||
|
use nalgebra::Point;
|
||||||
|
|
||||||
|
pub mod axis;
|
||||||
pub mod base_slices;
|
pub mod base_slices;
|
||||||
pub mod line;
|
pub mod line;
|
||||||
pub mod mesh;
|
pub mod mesh;
|
||||||
pub mod slice_rings;
|
pub mod sdf;
|
||||||
|
pub mod slice_path;
|
||||||
pub mod split_surface;
|
pub mod split_surface;
|
||||||
pub mod trace_surface;
|
pub mod trace_surface;
|
||||||
pub mod triangle;
|
pub mod triangle;
|
||||||
@@ -11,7 +15,17 @@ pub mod z_projection;
|
|||||||
|
|
||||||
pub type FloatValue = f64;
|
pub type FloatValue = f64;
|
||||||
|
|
||||||
#[derive(Debug)]
|
pub fn aabb_from_points<'a, I, T: BHValue, const D: usize>(mut points: I) -> Aabb<T, D>
|
||||||
pub struct SlicerOptions {
|
where
|
||||||
pub layer_height: FloatValue,
|
I: Iterator<Item = &'a Point<T, D>>,
|
||||||
|
{
|
||||||
|
if let Some(point) = points.next() {
|
||||||
|
let mut aabb = point.aabb();
|
||||||
|
for point in points {
|
||||||
|
aabb.grow_mut(point);
|
||||||
|
}
|
||||||
|
aabb
|
||||||
|
} else {
|
||||||
|
Aabb::empty()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
253
bampy/src/slicer/sdf.rs
Normal file
253
bampy/src/slicer/sdf.rs
Normal file
@@ -0,0 +1,253 @@
|
|||||||
|
/// https://iquilezles.org/articles/distfunctions/
|
||||||
|
use nalgebra::{vector, Point, TAffine, Transform, Vector2, Vector3};
|
||||||
|
|
||||||
|
use super::FloatValue;
|
||||||
|
|
||||||
|
pub trait Sdf<const D: usize> {
|
||||||
|
fn sdf(&self, p: &Point<FloatValue, D>) -> FloatValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy)]
|
||||||
|
pub struct SdfSphere {
|
||||||
|
radius: FloatValue,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SdfSphere {
|
||||||
|
pub fn new(radius: FloatValue) -> Self {
|
||||||
|
Self { radius }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Sdf<3> for SdfSphere {
|
||||||
|
fn sdf(&self, p: &Point<FloatValue, 3>) -> FloatValue {
|
||||||
|
p.coords.norm() - self.radius
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy)]
|
||||||
|
pub struct SdfBox {
|
||||||
|
size: Point<FloatValue, 3>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SdfBox {
|
||||||
|
pub fn new(size: Point<FloatValue, 3>) -> Self {
|
||||||
|
Self { size }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Sdf<3> for SdfBox {
|
||||||
|
fn sdf(&self, p: &Point<FloatValue, 3>) -> FloatValue {
|
||||||
|
let q = p.coords.abs() - self.size.coords;
|
||||||
|
q.sup(&Vector3::zeros()).add_scalar(q.max().min(0.0)).norm()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy)]
|
||||||
|
pub struct SdfInfiniteCone {
|
||||||
|
angle: Vector2<FloatValue>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SdfInfiniteCone {
|
||||||
|
pub fn new(angle: FloatValue) -> Self {
|
||||||
|
Self {
|
||||||
|
angle: vector![angle.sin(), angle.cos()],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Sdf<3> for SdfInfiniteCone {
|
||||||
|
fn sdf(&self, p: &Point<FloatValue, 3>) -> FloatValue {
|
||||||
|
let q = vector![p.coords.xy().norm(), p.z];
|
||||||
|
let d = (q - self.angle.scale(q.dot(&self.angle).max(0.0))).norm();
|
||||||
|
if q.x * self.angle.y - q.y * self.angle.x > 0.0 {
|
||||||
|
d
|
||||||
|
} else {
|
||||||
|
-d
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy)]
|
||||||
|
pub struct SdfTransform<T: Sdf<3>> {
|
||||||
|
sdf: T,
|
||||||
|
transform: Transform<FloatValue, TAffine, 3>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: Sdf<3>> SdfTransform<T> {
|
||||||
|
fn new(sdf: T, transform: Transform<FloatValue, TAffine, 3>) -> Self {
|
||||||
|
Self { sdf, transform }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: Sdf<3>> Sdf<3> for SdfTransform<T> {
|
||||||
|
fn sdf(&self, p: &Point<FloatValue, 3>) -> FloatValue {
|
||||||
|
self.sdf.sdf(&self.transform.inverse_transform_point(p))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy)]
|
||||||
|
pub struct SdfScale<const D: usize, T: Sdf<D>> {
|
||||||
|
sdf: T,
|
||||||
|
scale: FloatValue,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<const D: usize, T: Sdf<D>> SdfScale<D, T> {
|
||||||
|
fn new(sdf: T, scale: FloatValue) -> Self {
|
||||||
|
Self { sdf, scale }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<const D: usize, T: Sdf<D>> Sdf<D> for SdfScale<D, T> {
|
||||||
|
fn sdf(&self, p: &Point<FloatValue, D>) -> FloatValue {
|
||||||
|
self.sdf.sdf(&(p / self.scale)) * self.scale
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy)]
|
||||||
|
pub struct SdfOnion<T: Sdf<3>> {
|
||||||
|
sdf: T,
|
||||||
|
thickness: FloatValue,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: Sdf<3>> SdfOnion<T> {
|
||||||
|
fn new(sdf: T, thickness: FloatValue) -> Self {
|
||||||
|
Self { sdf, thickness }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: Sdf<3>> Sdf<3> for SdfOnion<T> {
|
||||||
|
fn sdf(&self, p: &Point<FloatValue, 3>) -> FloatValue {
|
||||||
|
self.sdf.sdf(p).abs() - self.thickness
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy)]
|
||||||
|
pub struct SdfUnion<const D: usize, T: Sdf<D>, U: Sdf<D>> {
|
||||||
|
sdf_a: T,
|
||||||
|
sdf_b: U,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<const D: usize, T: Sdf<D>, U: Sdf<D>> SdfUnion<D, T, U> {
|
||||||
|
fn new(sdf_a: T, sdf_b: U) -> Self {
|
||||||
|
Self { sdf_a, sdf_b }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<const D: usize, T: Sdf<D>, U: Sdf<D>> Sdf<D> for SdfUnion<D, T, U> {
|
||||||
|
fn sdf(&self, p: &Point<FloatValue, D>) -> FloatValue {
|
||||||
|
self.sdf_a.sdf(p).min(self.sdf_b.sdf(p))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy)]
|
||||||
|
pub struct SdfIntersection<const D: usize, T: Sdf<D>, U: Sdf<D>> {
|
||||||
|
sdf_a: T,
|
||||||
|
sdf_b: U,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<const D: usize, T: Sdf<D>, U: Sdf<D>> SdfIntersection<D, T, U> {
|
||||||
|
fn new(sdf_a: T, sdf_b: U) -> Self {
|
||||||
|
Self { sdf_a, sdf_b }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<const D: usize, T: Sdf<D>, U: Sdf<D>> Sdf<D> for SdfIntersection<D, T, U> {
|
||||||
|
fn sdf(&self, p: &Point<FloatValue, D>) -> FloatValue {
|
||||||
|
self.sdf_a.sdf(p).max(self.sdf_b.sdf(p))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy)]
|
||||||
|
pub struct SdfDifference<const D: usize, T: Sdf<D>, U: Sdf<D>> {
|
||||||
|
sdf_a: T,
|
||||||
|
sdf_b: U,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<const D: usize, T: Sdf<D>, U: Sdf<D>> SdfDifference<D, T, U> {
|
||||||
|
fn new(sdf_a: T, sdf_b: U) -> Self {
|
||||||
|
Self { sdf_a, sdf_b }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<const D: usize, T: Sdf<D>, U: Sdf<D>> Sdf<D> for SdfDifference<D, T, U> {
|
||||||
|
fn sdf(&self, p: &Point<FloatValue, D>) -> FloatValue {
|
||||||
|
self.sdf_a.sdf(p).max(-self.sdf_b.sdf(p))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub trait SdfOperators<const D: usize>: Sdf<D> {
|
||||||
|
fn union(self, other: Self) -> SdfUnion<D, Self, Self>
|
||||||
|
where
|
||||||
|
Self: Sized,
|
||||||
|
{
|
||||||
|
SdfUnion::new(self, other)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn intersection(self, other: Self) -> SdfIntersection<D, Self, Self>
|
||||||
|
where
|
||||||
|
Self: Sized,
|
||||||
|
{
|
||||||
|
SdfIntersection::new(self, other)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn difference(self, other: Self) -> SdfDifference<D, Self, Self>
|
||||||
|
where
|
||||||
|
Self: Sized,
|
||||||
|
{
|
||||||
|
SdfDifference::new(self, other)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<const D: usize, T: Sdf<D>> SdfOperators<D> for T {}
|
||||||
|
|
||||||
|
pub trait Sdf3dModifiers: Sdf<3> {
|
||||||
|
/// exact
|
||||||
|
fn transform(self, transform: Transform<FloatValue, TAffine, 3>) -> SdfTransform<Self>
|
||||||
|
where
|
||||||
|
Self: Sized,
|
||||||
|
{
|
||||||
|
SdfTransform::new(self, transform)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// exact
|
||||||
|
fn translate(self, translation: Point<FloatValue, 3>) -> SdfTransform<Self>
|
||||||
|
where
|
||||||
|
Self: Sized,
|
||||||
|
{
|
||||||
|
self.transform(Transform::from_matrix_unchecked(
|
||||||
|
nalgebra::Matrix4::new_translation(&translation.coords),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// exact
|
||||||
|
fn rotate(self, rotation: nalgebra::UnitQuaternion<FloatValue>) -> SdfTransform<Self>
|
||||||
|
where
|
||||||
|
Self: Sized,
|
||||||
|
{
|
||||||
|
self.transform(Transform::from_matrix_unchecked(rotation.to_homogeneous()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// exact
|
||||||
|
fn scale(self, scale: FloatValue) -> SdfScale<3, Self>
|
||||||
|
where
|
||||||
|
Self: Sized,
|
||||||
|
{
|
||||||
|
SdfScale::new(self, scale)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// exact
|
||||||
|
///
|
||||||
|
/// For carving interiors or giving thickness to primitives,
|
||||||
|
/// without performing expensive boolean operations
|
||||||
|
/// and without distorting the distance field into a bound,
|
||||||
|
/// one can use "onioning".
|
||||||
|
/// You can use it multiple times to create concentric layers in your SDF.
|
||||||
|
fn onion(self, thickness: FloatValue) -> SdfOnion<Self>
|
||||||
|
where
|
||||||
|
Self: Sized,
|
||||||
|
{
|
||||||
|
SdfOnion::new(self, thickness)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: Sdf<3>> Sdf3dModifiers for T {}
|
||||||
183
bampy/src/slicer/slice_path.rs
Normal file
183
bampy/src/slicer/slice_path.rs
Normal file
@@ -0,0 +1,183 @@
|
|||||||
|
use std::{collections::VecDeque, ops::RangeInclusive};
|
||||||
|
|
||||||
|
use approx::relative_eq;
|
||||||
|
use bvh::aabb::Aabb;
|
||||||
|
use nalgebra::Point3;
|
||||||
|
|
||||||
|
use super::{axis::Axis, mesh::Mesh, FloatValue};
|
||||||
|
|
||||||
|
#[derive(Debug, Default)]
|
||||||
|
pub struct SlicePath {
|
||||||
|
pub i: usize,
|
||||||
|
pub d: FloatValue,
|
||||||
|
pub axis: Axis,
|
||||||
|
/// The points of the ring, in clockwise order.
|
||||||
|
pub points: Vec<Point3<FloatValue>>,
|
||||||
|
pub closed: bool,
|
||||||
|
pub aabb: Aabb<FloatValue, 3>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct SurfacePath {
|
||||||
|
pub i: RangeInclusive<usize>,
|
||||||
|
pub d: RangeInclusive<FloatValue>,
|
||||||
|
pub axis: Axis,
|
||||||
|
pub path: Vec<Point3<FloatValue>>,
|
||||||
|
pub aabb: Aabb<FloatValue, 3>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct SurfacePathIterator {
|
||||||
|
slices: Vec<Vec<SlicePath>>,
|
||||||
|
axis: Axis,
|
||||||
|
nozzle_width: FloatValue,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SurfacePathIterator {
|
||||||
|
pub fn new(mesh: &Mesh, axis: Axis, nozzle_width: FloatValue) -> Self {
|
||||||
|
let (h_axis, _) = axis.other();
|
||||||
|
|
||||||
|
Self {
|
||||||
|
slices: mesh
|
||||||
|
.slice_paths(axis, nozzle_width)
|
||||||
|
.map(|mut slice| {
|
||||||
|
for ring in &mut slice {
|
||||||
|
ring.points.sort_unstable_by(|a, b| {
|
||||||
|
a.coords[h_axis as usize]
|
||||||
|
.partial_cmp(&b.coords[h_axis as usize])
|
||||||
|
.unwrap()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
slice.sort_unstable_by(|a, b| {
|
||||||
|
a.points.first().unwrap().coords[h_axis as usize]
|
||||||
|
.partial_cmp(&b.points.first().unwrap().coords[h_axis as usize])
|
||||||
|
.unwrap()
|
||||||
|
});
|
||||||
|
let mut iter = slice.into_iter();
|
||||||
|
let mut out = vec![iter.next().unwrap()];
|
||||||
|
for ring in iter {
|
||||||
|
if relative_eq!(
|
||||||
|
out.last().unwrap().points.last().unwrap(),
|
||||||
|
ring.points.first().unwrap(),
|
||||||
|
epsilon = nozzle_width
|
||||||
|
) {
|
||||||
|
let element = out.last_mut().unwrap();
|
||||||
|
element.points.extend(ring.points);
|
||||||
|
element.aabb.join_mut(&ring.aabb);
|
||||||
|
} else {
|
||||||
|
out.push(ring);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
axis,
|
||||||
|
nozzle_width,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn squish(points: &mut Vec<Point3<FloatValue>>, axis: Axis, d: FloatValue) {
|
||||||
|
macro_rules! ax {
|
||||||
|
($p: expr) => {
|
||||||
|
$p.coords[axis as usize]
|
||||||
|
};
|
||||||
|
}
|
||||||
|
let first = ax!(points.first().unwrap());
|
||||||
|
let left = points.iter().position(|p| first - ax!(p) > d);
|
||||||
|
let last = ax!(points.last().unwrap());
|
||||||
|
let right = points.iter().rposition(|p| ax!(p) - last > d);
|
||||||
|
|
||||||
|
if let (Some(left), Some(right)) = (left, right) {
|
||||||
|
if left > right {
|
||||||
|
// TODO
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let total = ax!(points[left + 1]) - first;
|
||||||
|
let delta = ax!(points[left]) - ax!(points[left + 1]);
|
||||||
|
points.splice(
|
||||||
|
0..left,
|
||||||
|
vec![points[left].lerp(&points[left + 1], (d - total) / delta)],
|
||||||
|
);
|
||||||
|
|
||||||
|
let total = last - ax!(points[right + 1]);
|
||||||
|
let delta = ax!(points[right + 1]) - ax!(points[right]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Iterator for SurfacePathIterator {
|
||||||
|
type Item = SurfacePath;
|
||||||
|
|
||||||
|
fn next(&mut self) -> Option<Self::Item> {
|
||||||
|
self.slices.retain_mut(|slice| !slice.is_empty());
|
||||||
|
|
||||||
|
let (h_axis, _) = self.axis.other();
|
||||||
|
let mut iter = self.slices.iter_mut();
|
||||||
|
|
||||||
|
let mut ring = iter.next()?.pop()?;
|
||||||
|
// TODO: squish(&mut ring.points, h_axis, self.nozzle_width);
|
||||||
|
let mut item = Self::Item {
|
||||||
|
i: ring.i..=ring.i,
|
||||||
|
d: ring.d..=ring.d,
|
||||||
|
axis: ring.axis,
|
||||||
|
aabb: ring.aabb,
|
||||||
|
path: ring.points,
|
||||||
|
};
|
||||||
|
|
||||||
|
for slice in iter {
|
||||||
|
if *item.i.end() != slice[0].i - 1 {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
let last = item.path.last().unwrap();
|
||||||
|
|
||||||
|
let mut d = FloatValue::MAX;
|
||||||
|
let mut needs_reverse = false;
|
||||||
|
let mut index = None;
|
||||||
|
|
||||||
|
for (i, ring) in slice.iter().enumerate() {
|
||||||
|
macro_rules! item {
|
||||||
|
($a:ident, $metric: ident) => {
|
||||||
|
$a.aabb.$metric[h_axis as usize]
|
||||||
|
};
|
||||||
|
}
|
||||||
|
let a = item!(ring, max);
|
||||||
|
let b = item!(item, min);
|
||||||
|
if !(a > b || relative_eq!(a, b, epsilon = 0.1)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let a = item!(ring, min);
|
||||||
|
let b = item!(item, max);
|
||||||
|
if !(a < b || relative_eq!(a, b, epsilon = 0.1)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let d_left = last
|
||||||
|
.coords
|
||||||
|
.metric_distance(&ring.points.first().unwrap().coords);
|
||||||
|
let d_right = last
|
||||||
|
.coords
|
||||||
|
.metric_distance(&ring.points.last().unwrap().coords);
|
||||||
|
let d_min = d_left.min(d_right);
|
||||||
|
if d_min < d {
|
||||||
|
d = d_min;
|
||||||
|
needs_reverse = d_left > d_right;
|
||||||
|
index = Some(i);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(mut ring) = index.map(|i| slice.remove(i)) {
|
||||||
|
// TODO: squish(&mut ring.points, h_axis, self.nozzle_width);
|
||||||
|
if needs_reverse {
|
||||||
|
ring.points.reverse();
|
||||||
|
}
|
||||||
|
|
||||||
|
item.i = *item.i.start()..=ring.i;
|
||||||
|
item.d = *item.d.start()..=ring.d;
|
||||||
|
item.path.append(&mut ring.points);
|
||||||
|
item.aabb.join_mut(&ring.aabb)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Some(item)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,84 +0,0 @@
|
|||||||
use approx::relative_eq;
|
|
||||||
use nalgebra::Vector3;
|
|
||||||
|
|
||||||
use crate::console_log;
|
|
||||||
|
|
||||||
use super::{base_slices::BaseSlice, FloatValue};
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub struct SliceRing {
|
|
||||||
pub z: FloatValue,
|
|
||||||
/// The points of the ring, in clockwise order.
|
|
||||||
pub points: Vec<Vector3<FloatValue>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn find_slice_rings(mut slice: BaseSlice, layer_index: &mut u32) -> Vec<SliceRing> {
|
|
||||||
let mut rings = vec![];
|
|
||||||
while let Some(line) = slice.lines.pop() {
|
|
||||||
if relative_eq!(line.start, line.end) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let mut ring = SliceRing {
|
|
||||||
z: slice.z,
|
|
||||||
points: vec![line.start, line.end],
|
|
||||||
};
|
|
||||||
let mut right_start = ring.points[0];
|
|
||||||
let mut right = ring.points[1];
|
|
||||||
let mut sum_of_edges = (right.x - right_start.x) * (right.y + right_start.y);
|
|
||||||
|
|
||||||
let mut previous_len = usize::MAX;
|
|
||||||
let mut done = false;
|
|
||||||
|
|
||||||
while !done {
|
|
||||||
if previous_len == slice.lines.len() {
|
|
||||||
console_log!(
|
|
||||||
"Error: Could not close ring {}, d = {}, {} items left.",
|
|
||||||
layer_index,
|
|
||||||
ring.points[0].metric_distance(&right),
|
|
||||||
slice.lines.len()
|
|
||||||
);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
previous_len = slice.lines.len();
|
|
||||||
|
|
||||||
slice.lines.retain_mut(|line| {
|
|
||||||
if done {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
macro_rules! add {
|
|
||||||
( $point:expr ) => {
|
|
||||||
if !relative_eq!($point, right_start) {
|
|
||||||
right_start = right;
|
|
||||||
right = $point;
|
|
||||||
ring.points.push(right);
|
|
||||||
sum_of_edges = (right.x - right_start.x) * (right.y + right_start.y);
|
|
||||||
done = relative_eq!(ring.points[0], right);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
let s = relative_eq!(line.start, right);
|
|
||||||
let e = relative_eq!(line.end, right);
|
|
||||||
if s && !e {
|
|
||||||
add!(line.end);
|
|
||||||
false
|
|
||||||
} else if e && !s {
|
|
||||||
add!(line.start);
|
|
||||||
false
|
|
||||||
} else {
|
|
||||||
true
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// The end point is duplicate, so not part of the winding order calculation.
|
|
||||||
if sum_of_edges < 0.0 {
|
|
||||||
ring.points.reverse();
|
|
||||||
}
|
|
||||||
rings.push(ring);
|
|
||||||
*layer_index += 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
rings
|
|
||||||
}
|
|
||||||
@@ -2,6 +2,7 @@ use super::{mesh::Mesh, triangle::Triangle};
|
|||||||
use bvh::bvh::{Bvh, BvhNode};
|
use bvh::bvh::{Bvh, BvhNode};
|
||||||
|
|
||||||
/// Splits a surface into connected surfaces.
|
/// Splits a surface into connected surfaces.
|
||||||
|
/// TODO: self intersections
|
||||||
pub fn split_surface(mut triangles: Vec<Triangle>) -> Vec<Mesh> {
|
pub fn split_surface(mut triangles: Vec<Triangle>) -> Vec<Mesh> {
|
||||||
let mut surfaces = vec![];
|
let mut surfaces = vec![];
|
||||||
while let Some(triangle) = triangles.pop() {
|
while let Some(triangle) = triangles.pop() {
|
||||||
|
|||||||
@@ -1,9 +1,17 @@
|
|||||||
use bvh::bvh::BvhNode;
|
use bvh::bvh::BvhNode;
|
||||||
|
use nalgebra::Point3;
|
||||||
|
|
||||||
use super::{mesh::Mesh, slice_rings::SliceRing, z_projection::ToolpathIntersects, FloatValue};
|
use crate::slicer::sdf::Sdf3dModifiers;
|
||||||
|
|
||||||
pub fn trace_surface(slice: &mut SliceRing, surface: &Mesh, a: FloatValue) {
|
use super::{
|
||||||
slice.points.retain_mut(|point| {
|
mesh::Mesh,
|
||||||
|
sdf::{Sdf, SdfInfiniteCone},
|
||||||
|
z_projection::ToolpathIntersects,
|
||||||
|
FloatValue,
|
||||||
|
};
|
||||||
|
|
||||||
|
pub fn trace_surface(point: &Point3<FloatValue>, surface: &Mesh, a: FloatValue) -> bool {
|
||||||
|
let sdf = SdfInfiniteCone::new(a);
|
||||||
let mut stack = Vec::<usize>::new();
|
let mut stack = Vec::<usize>::new();
|
||||||
stack.push(0);
|
stack.push(0);
|
||||||
while let Some(i) = stack.pop() {
|
while let Some(i) = stack.pop() {
|
||||||
@@ -27,21 +35,14 @@ pub fn trace_surface(slice: &mut SliceRing, surface: &Mesh, a: FloatValue) {
|
|||||||
shape_index,
|
shape_index,
|
||||||
} => {
|
} => {
|
||||||
let triangle = &surface.triangles[shape_index];
|
let triangle = &surface.triangles[shape_index];
|
||||||
macro_rules! check {
|
if sdf.translate(triangle.a).sdf(point) < 0.0
|
||||||
( $var:ident ) => {{
|
|| sdf.translate(triangle.b).sdf(point) < 0.0
|
||||||
let x = point.x - triangle.$var.x;
|
|| sdf.translate(triangle.c).sdf(point) < 0.0
|
||||||
let y = point.y - triangle.$var.y;
|
{
|
||||||
(point.z > triangle.aabb.min.z
|
|
||||||
&& FloatValue::sqrt(x * x + y * y)
|
|
||||||
< (triangle.$var.z - point.z).abs() * a)
|
|
||||||
}};
|
|
||||||
}
|
|
||||||
if check!(a) || check!(b) || check!(c) {
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
true
|
return true;
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,90 +9,59 @@ use super::{line::Line3, FloatValue};
|
|||||||
|
|
||||||
#[derive(Debug, Clone, Copy)]
|
#[derive(Debug, Clone, Copy)]
|
||||||
pub struct Triangle {
|
pub struct Triangle {
|
||||||
pub a: Vector3<FloatValue>,
|
pub a: Point3<FloatValue>,
|
||||||
pub b: Vector3<FloatValue>,
|
pub b: Point3<FloatValue>,
|
||||||
pub c: Vector3<FloatValue>,
|
pub c: Point3<FloatValue>,
|
||||||
pub normal: Vector3<FloatValue>,
|
pub normal: Vector3<FloatValue>,
|
||||||
node_index: usize,
|
node_index: usize,
|
||||||
pub aabb: Aabb<FloatValue, 3>,
|
pub aabb: Aabb<FloatValue, 3>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline(always)]
|
|
||||||
fn vec_inside_aabb(vec: &Vector3<FloatValue>, aabb: &Aabb<FloatValue, 3>) -> bool {
|
|
||||||
macro_rules! within {
|
|
||||||
($axis:ident) => {
|
|
||||||
((vec.$axis >= aabb.min.$axis && vec.$axis <= aabb.max.$axis)
|
|
||||||
|| relative_eq!(vec.$axis, aabb.min.$axis)
|
|
||||||
|| relative_eq!(vec.$axis, aabb.max.$axis))
|
|
||||||
};
|
|
||||||
}
|
|
||||||
within!(x) && within!(y) && within!(z)
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Triangle {
|
impl Triangle {
|
||||||
pub fn new(a: Vector3<FloatValue>, b: Vector3<FloatValue>, c: Vector3<FloatValue>) -> Self {
|
pub fn new(a: Point3<FloatValue>, b: Point3<FloatValue>, c: Point3<FloatValue>) -> Self {
|
||||||
|
let mut aabb = a.aabb();
|
||||||
|
aabb.grow_mut(&b);
|
||||||
|
aabb.grow_mut(&c);
|
||||||
Self {
|
Self {
|
||||||
a,
|
a,
|
||||||
b,
|
b,
|
||||||
c,
|
c,
|
||||||
normal: (b - a).cross(&(c - a)).into(),
|
normal: (b - a).cross(&(c - a)).normalize(),
|
||||||
node_index: 0,
|
node_index: 0,
|
||||||
aabb: Aabb::with_bounds(
|
aabb,
|
||||||
Point3::new(
|
|
||||||
FloatValue::min(FloatValue::max(a.x, b.x), c.x),
|
|
||||||
FloatValue::min(FloatValue::min(a.y, b.y), c.y),
|
|
||||||
FloatValue::min(FloatValue::min(a.z, b.z), c.z),
|
|
||||||
),
|
|
||||||
Point3::new(
|
|
||||||
FloatValue::max(FloatValue::max(a.x, b.x), c.x),
|
|
||||||
FloatValue::max(FloatValue::max(a.y, b.y), c.y),
|
|
||||||
FloatValue::max(FloatValue::max(a.z, b.z), c.z),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn has_point_in_aabb(&self, aabb: &Aabb<FloatValue, 3>) -> bool {
|
pub fn has_point_in_aabb(&self, aabb: &Aabb<FloatValue, 3>) -> bool {
|
||||||
vec_inside_aabb(&self.a, aabb)
|
aabb.contains(&self.a) || aabb.contains(&self.b) || aabb.contains(&self.c)
|
||||||
|| vec_inside_aabb(&self.b, aabb)
|
|
||||||
|| vec_inside_aabb(&self.c, aabb)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn has_vec(&self, vec: Vector3<FloatValue>) -> bool {
|
pub fn has_point(&self, vec: Point3<FloatValue>) -> bool {
|
||||||
relative_eq!(self.a, vec) || relative_eq!(self.b, vec) || relative_eq!(self.c, vec)
|
relative_eq!(self.a, vec) || relative_eq!(self.b, vec) || relative_eq!(self.c, vec)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn shares_point_with_triangle(&self, other: Triangle) -> bool {
|
pub fn shares_point_with_triangle(&self, other: Triangle) -> bool {
|
||||||
self.has_vec(other.a) || self.has_vec(other.b) || self.has_vec(other.c)
|
self.has_point(other.a) || self.has_point(other.b) || self.has_point(other.c)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn shares_edge_with_triangle(&self, other: Triangle) -> bool {
|
pub fn intersect(&self, value: FloatValue, axis: usize) -> Option<Line3> {
|
||||||
let a = self.has_vec(other.a);
|
let mut intersection = Vec::<Point3<FloatValue>>::with_capacity(3);
|
||||||
let b = self.has_vec(other.b);
|
|
||||||
let c = self.has_vec(other.c);
|
|
||||||
a && b || a && c || b && c
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn intersect_z(&self, z: FloatValue) -> Option<Line3> {
|
|
||||||
let mut intersection = Vec::<Vector3<FloatValue>>::with_capacity(3);
|
|
||||||
let mut last = &self.c;
|
let mut last = &self.c;
|
||||||
for point in [self.a, self.b, self.c].iter() {
|
for point in [self.a, self.b, self.c].iter() {
|
||||||
if relative_eq!(point.z, z) {
|
if relative_eq!(point[axis], value) {
|
||||||
intersection.push(Vector3::new(point.x, point.y, z));
|
let mut new_point = *point;
|
||||||
} else if last.z < z && point.z > z {
|
new_point[axis] = value;
|
||||||
let ratio = (z - last.z) / (point.z - last.z);
|
intersection.push(new_point);
|
||||||
intersection.push(Vector3::new(
|
} else if last[axis] < value && point[axis] > value {
|
||||||
last.x + (point.x - last.x) * ratio,
|
let ratio = (value - last[axis]) / (point[axis] - last[axis]);
|
||||||
last.y + (point.y - last.y) * ratio,
|
let mut new_point = last + (point - last) * ratio;
|
||||||
z,
|
new_point[axis] = value;
|
||||||
))
|
intersection.push(new_point);
|
||||||
} else if last.z > z && point.z < z {
|
} else if last[axis] > value && point[axis] < value {
|
||||||
let ratio = (z - point.z) / (last.z - point.z);
|
let ratio = (value - point[axis]) / (last[axis] - point[axis]);
|
||||||
intersection.push(Vector3::new(
|
let mut new_point = point + (last - point) * ratio;
|
||||||
point.x + (last.x - point.x) * ratio,
|
new_point[axis] = value;
|
||||||
point.y + (last.y - point.y) * ratio,
|
intersection.push(new_point);
|
||||||
z,
|
|
||||||
))
|
|
||||||
}
|
}
|
||||||
last = point;
|
last = point;
|
||||||
}
|
}
|
||||||
@@ -105,6 +74,12 @@ impl Triangle {
|
|||||||
None
|
None
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn area(&self) -> FloatValue {
|
||||||
|
let ab = self.b - self.a;
|
||||||
|
let ac = self.c - self.a;
|
||||||
|
0.5 * ab.cross(&ac).norm()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Bounded<FloatValue, 3> for Triangle {
|
impl Bounded<FloatValue, 3> for Triangle {
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
use bvh::aabb::Aabb;
|
use bvh::aabb::Aabb;
|
||||||
use nalgebra::{Point2, Vector2, Vector3};
|
use nalgebra::{Point2, Point3};
|
||||||
|
|
||||||
use super::{triangle::Triangle, FloatValue};
|
use super::{triangle::Triangle, FloatValue};
|
||||||
|
|
||||||
@@ -11,7 +11,7 @@ pub trait ProjectToolpath<T> {
|
|||||||
pub trait ToolpathIntersects<T>: ProjectToolpath<T> {
|
pub trait ToolpathIntersects<T>: ProjectToolpath<T> {
|
||||||
/// Checks if a hypothetical toolpath that draws the object could intersect
|
/// Checks if a hypothetical toolpath that draws the object could intersect
|
||||||
/// with the given point, given the tangent of the angle of the toolhead
|
/// with the given point, given the tangent of the angle of the toolhead
|
||||||
fn toolpath_intersects(&self, point: &Vector3<FloatValue>, a: FloatValue) -> bool;
|
fn toolpath_intersects(&self, point: &Point3<FloatValue>, a: FloatValue) -> bool;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub trait ToolpathIntersection {
|
pub trait ToolpathIntersection {
|
||||||
@@ -38,7 +38,7 @@ impl ProjectToolpath<Aabb<FloatValue, 2>> for Aabb<FloatValue, 3> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl ToolpathIntersects<Aabb<FloatValue, 2>> for Aabb<FloatValue, 3> {
|
impl ToolpathIntersects<Aabb<FloatValue, 2>> for Aabb<FloatValue, 3> {
|
||||||
fn toolpath_intersects(&self, point: &Vector3<FloatValue>, a: FloatValue) -> bool {
|
fn toolpath_intersects(&self, point: &Point3<FloatValue>, a: FloatValue) -> bool {
|
||||||
if let Some(aabb) = self.project_toolpath_onto_z(point.z, a) {
|
if let Some(aabb) = self.project_toolpath_onto_z(point.z, a) {
|
||||||
aabb.approx_contains_eps(&Point2::new(point.x, point.y), FloatValue::EPSILON)
|
aabb.approx_contains_eps(&Point2::new(point.x, point.y), FloatValue::EPSILON)
|
||||||
} else {
|
} else {
|
||||||
@@ -100,7 +100,7 @@ impl ProjectToolpath<Triangle2D> for Triangle {
|
|||||||
mod tests {
|
mod tests {
|
||||||
use approx::assert_relative_eq;
|
use approx::assert_relative_eq;
|
||||||
use bvh::aabb::Aabb;
|
use bvh::aabb::Aabb;
|
||||||
use nalgebra::{Point3, Vector2, Vector3};
|
use nalgebra::{point, Point3};
|
||||||
|
|
||||||
use crate::slicer::{triangle::Triangle, z_projection::ProjectToolpath, FloatValue};
|
use crate::slicer::{triangle::Triangle, z_projection::ProjectToolpath, FloatValue};
|
||||||
|
|
||||||
@@ -129,9 +129,9 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn test_project_triangle_toolpath() {
|
fn test_project_triangle_toolpath() {
|
||||||
let triangle = Triangle::new(
|
let triangle = Triangle::new(
|
||||||
Vector3::new(0.0, 0.0, 0.0),
|
point![0.0, 0.0, 0.0],
|
||||||
Vector3::new(0.0, 1.5, 1.0),
|
point![0.0, 1.5, 1.0],
|
||||||
Vector3::new(-0.6, -1.4, 0.2),
|
point![-0.6, -1.4, 0.2],
|
||||||
);
|
);
|
||||||
let a = FloatValue::to_radians(30.0).tan();
|
let a = FloatValue::to_radians(30.0).tan();
|
||||||
|
|
||||||
|
|||||||
32
flake.nix
32
flake.nix
@@ -4,20 +4,36 @@
|
|||||||
rust-overlay.url = "github:oxalica/rust-overlay";
|
rust-overlay.url = "github:oxalica/rust-overlay";
|
||||||
flake-utils.url = "github:numtide/flake-utils";
|
flake-utils.url = "github:numtide/flake-utils";
|
||||||
};
|
};
|
||||||
outputs = {
|
outputs =
|
||||||
|
{
|
||||||
self,
|
self,
|
||||||
nixpkgs,
|
nixpkgs,
|
||||||
flake-utils,
|
flake-utils,
|
||||||
rust-overlay,
|
rust-overlay,
|
||||||
}:
|
}:
|
||||||
flake-utils.lib.eachDefaultSystem (system: let
|
flake-utils.lib.eachDefaultSystem (
|
||||||
|
system:
|
||||||
|
let
|
||||||
overlays = [ (import rust-overlay) ];
|
overlays = [ (import rust-overlay) ];
|
||||||
pkgs = import nixpkgs { inherit system overlays; };
|
pkgs = import nixpkgs { inherit system overlays; };
|
||||||
rust-bin = pkgs.rust-bin.stable.latest.default.override {
|
rust-bin = pkgs.rust-bin.nightly.latest.default.override {
|
||||||
targets = [ "wasm32-unknown-unknown" ];
|
targets = [ "wasm32-unknown-unknown" ];
|
||||||
extensions = ["rust-src" "rust-std" "clippy" "rust-analyzer"];
|
extensions = [
|
||||||
|
"rust-src"
|
||||||
|
"rust-std"
|
||||||
|
"clippy"
|
||||||
|
"rust-analyzer"
|
||||||
|
];
|
||||||
};
|
};
|
||||||
fontMin = pkgs.python311.withPackages (ps: with ps; [brotli fonttools] ++ (with fonttools.optional-dependencies; [woff]));
|
fontMin = pkgs.python311.withPackages (
|
||||||
|
ps:
|
||||||
|
with ps;
|
||||||
|
[
|
||||||
|
brotli
|
||||||
|
fonttools
|
||||||
|
]
|
||||||
|
++ (with fonttools.optional-dependencies; [ woff ])
|
||||||
|
);
|
||||||
tauriPkgs = nixpkgs.legacyPackages.${system};
|
tauriPkgs = nixpkgs.legacyPackages.${system};
|
||||||
libraries = with tauriPkgs; [
|
libraries = with tauriPkgs; [
|
||||||
webkitgtk
|
webkitgtk
|
||||||
@@ -51,12 +67,14 @@
|
|||||||
# serial plugin
|
# serial plugin
|
||||||
udev
|
udev
|
||||||
]);
|
]);
|
||||||
in {
|
in
|
||||||
|
{
|
||||||
devShell = pkgs.mkShell {
|
devShell = pkgs.mkShell {
|
||||||
buildInputs = packages;
|
buildInputs = packages;
|
||||||
shellHook = ''
|
shellHook = ''
|
||||||
export LD_LIBRARY_PATH=${pkgs.lib.makeLibraryPath libraries}:$LD_LIBRARY_PATH
|
export LD_LIBRARY_PATH=${pkgs.lib.makeLibraryPath libraries}:$LD_LIBRARY_PATH
|
||||||
'';
|
'';
|
||||||
};
|
};
|
||||||
});
|
}
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -37,4 +37,3 @@
|
|||||||
"vite-plugin-wasm": "^3.3.0"
|
"vite-plugin-wasm": "^3.3.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { T, type AsyncWritable } from '@threlte/core';
|
import { T, type AsyncWritable } from '@threlte/core';
|
||||||
import { Gizmo, Grid, MeshLineGeometry, MeshLineMaterial, OrbitControls } from '@threlte/extras';
|
import { Gizmo, Grid, OrbitControls, MeshLineGeometry, MeshLineMaterial } from '@threlte/extras';
|
||||||
import { STLLoader } from 'three/examples/jsm/loaders/STLLoader.js';
|
import { STLLoader } from 'three/examples/jsm/loaders/STLLoader.js';
|
||||||
import { useLoader } from '@threlte/core';
|
import { useLoader } from '@threlte/core';
|
||||||
import {
|
import {
|
||||||
@@ -9,9 +9,7 @@
|
|||||||
Vector3,
|
Vector3,
|
||||||
DoubleSide,
|
DoubleSide,
|
||||||
Color,
|
Color,
|
||||||
BufferGeometryLoader,
|
BufferGeometryLoader
|
||||||
TubeGeometry,
|
|
||||||
CatmullRomCurve3
|
|
||||||
} from 'three';
|
} from 'three';
|
||||||
import { writable } from 'svelte/store';
|
import { writable } from 'svelte/store';
|
||||||
import { onDestroy, onMount } from 'svelte';
|
import { onDestroy, onMount } from 'svelte';
|
||||||
@@ -35,20 +33,18 @@
|
|||||||
progressLayer.set(event.data.layer);
|
progressLayer.set(event.data.layer);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case 'layer': {
|
case 'result': {
|
||||||
layers.update((layers) => {
|
layers.update((layers) => {
|
||||||
const layer = event.data.data;
|
for (const layer of event.data.data.slices) {
|
||||||
if (layer.type === 'ring') {
|
if (layer.type === 'ring' || layer.type === 'path') {
|
||||||
const curve = new CatmullRomCurve3(
|
layers.push(
|
||||||
Array.from({ length: layer.position.length / 3 }, (_, i) =>
|
Array.from({ length: layer.position.length / 3 }, (_, i) =>
|
||||||
new Vector3().fromArray(layer.position, i * 3)
|
new Vector3().fromArray(layer.position, i * 3)
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
const geometry = new TubeGeometry(curve, undefined, 0.1);
|
|
||||||
|
|
||||||
layers.push(geometry);
|
|
||||||
} else if (layer.type === 'surface') {
|
} else if (layer.type === 'surface') {
|
||||||
}
|
}
|
||||||
|
}
|
||||||
return layers;
|
return layers;
|
||||||
});
|
});
|
||||||
break;
|
break;
|
||||||
@@ -63,6 +59,7 @@
|
|||||||
|
|
||||||
export let buildSurface = [300, 300, 300];
|
export let buildSurface = [300, 300, 300];
|
||||||
export let layerHeight = 0.2;
|
export let layerHeight = 0.2;
|
||||||
|
export let nozzleDiameter = 0.4;
|
||||||
export let tolerance = 0.005;
|
export let tolerance = 0.005;
|
||||||
export let progress = writable<number | undefined>(undefined);
|
export let progress = writable<number | undefined>(undefined);
|
||||||
export let progressLayer = writable(0);
|
export let progressLayer = writable(0);
|
||||||
@@ -72,7 +69,7 @@
|
|||||||
export let maxNonPlanarAngle = MathUtils.degToRad(20);
|
export let maxNonPlanarAngle = MathUtils.degToRad(20);
|
||||||
export let bedNormal = new Vector3(0, 0, 1);
|
export let bedNormal = new Vector3(0, 0, 1);
|
||||||
|
|
||||||
let layers = writable<Layer[]>([]);
|
let layers = writable<Vector3[][]>([]);
|
||||||
|
|
||||||
const stl: AsyncWritable<BufferGeometry> = useLoader(STLLoader).load('/benchy.stl');
|
const stl: AsyncWritable<BufferGeometry> = useLoader(STLLoader).load('/benchy.stl');
|
||||||
|
|
||||||
@@ -84,6 +81,8 @@
|
|||||||
layerHeight,
|
layerHeight,
|
||||||
tolerance,
|
tolerance,
|
||||||
maxNonPlanarAngle,
|
maxNonPlanarAngle,
|
||||||
|
nozzleDiameter,
|
||||||
|
minSurfacePathLength: nozzleDiameter * 2,
|
||||||
bedNormal: bedNormal.toArray()
|
bedNormal: bedNormal.toArray()
|
||||||
}
|
}
|
||||||
} satisfies SliceEvent);
|
} satisfies SliceEvent);
|
||||||
@@ -107,12 +106,13 @@
|
|||||||
gridSize={[buildSurface[0], buildSurface[1]]}
|
gridSize={[buildSurface[0], buildSurface[1]]}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{#each $layers as geometry, i}
|
{#each $layers as points, i}
|
||||||
{@const visible = maxZ !== 0 ? i === maxZ : showSlices >= i / $layers.length}
|
{@const visible = maxZ !== 0 ? i === maxZ : showSlices >= i / $layers.length}
|
||||||
{@const color = new Color(Math.random() * 0xffffff)}
|
{@const color = new Color(Math.random() * 0xffffff)}
|
||||||
<!---{@const color = new Color(0, i / $layers.length, 0.2)}-->
|
<!---{@const color = new Color(0, i / $layers.length, 0.2)}-->
|
||||||
<T.Mesh {geometry} {visible}>
|
<T.Mesh {visible}>
|
||||||
<T.MeshMatcapMaterial {color} side={DoubleSide} />
|
<MeshLineGeometry {points} />
|
||||||
|
<MeshLineMaterial width={nozzleDiameter * 0.25} {color} />
|
||||||
</T.Mesh>
|
</T.Mesh>
|
||||||
{/each}
|
{/each}
|
||||||
|
|
||||||
|
|||||||
@@ -6,6 +6,8 @@ export interface SliceArguments {
|
|||||||
maxNonPlanarAngle: number;
|
maxNonPlanarAngle: number;
|
||||||
tolerance: number;
|
tolerance: number;
|
||||||
layerHeight: number;
|
layerHeight: number;
|
||||||
|
nozzleDiameter: number;
|
||||||
|
minSurfacePathLength: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface SliceEvent {
|
export interface SliceEvent {
|
||||||
|
|||||||
@@ -18,13 +18,13 @@ addEventListener('message', async (event: MessageEvent<WorkerEvent>) => {
|
|||||||
const result = slice({
|
const result = slice({
|
||||||
positions: geometry.attributes.position.array as Float32Array,
|
positions: geometry.attributes.position.array as Float32Array,
|
||||||
layerHeight: event.data.data.layerHeight,
|
layerHeight: event.data.data.layerHeight,
|
||||||
maxAngle: event.data.data.maxNonPlanarAngle
|
maxAngle: event.data.data.maxNonPlanarAngle,
|
||||||
|
nozzleDiameter: event.data.data.nozzleDiameter,
|
||||||
|
minSurfacePathLength: event.data.data.minSurfacePathLength
|
||||||
});
|
});
|
||||||
for (const layer of result.slices) {
|
|
||||||
self.postMessage({
|
self.postMessage({
|
||||||
type: 'layer',
|
type: 'result',
|
||||||
data: layer
|
data: result
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user