use anyhow::Result;
use kcmc::ModelingCmd;
use kcmc::each_cmd as mcmd;
use kcmc::length_unit::LengthUnit;
use kcmc::shared::Angle;
use kcmc::shared::CutStrategy;
use kcmc::shared::CutTypeV2;
use kcmc::shared::EdgeCutVersion;
use kittycad_modeling_cmds::{self as kcmc};
use super::args::TyF64;
use crate::errors::KclError;
use crate::errors::KclErrorDetails;
use crate::execution::ChamferSurface;
use crate::execution::EdgeCut;
use crate::execution::ExecState;
use crate::execution::ExtrudeSurface;
use crate::execution::GeoMeta;
use crate::execution::KclValue;
use crate::execution::KclVersion;
use crate::execution::ModelingCmdMeta;
use crate::execution::Sketch;
use crate::execution::Solid;
use crate::execution::types::RuntimeType;
use crate::parsing::ast::types::TagNode;
use crate::std::Args;
use crate::std::csg::CsgAlgorithm;
use crate::std::fillet::EdgeReference;
use crate::std::fillet::default_edge_cut_version;
pub(crate) const DEFAULT_TOLERANCE: f64 = 0.0000001;
pub async fn chamfer(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
let solid: Box<Solid> = args.get_unlabeled_kw_arg("solid", &RuntimeType::solid(), exec_state)?;
let length: TyF64 = args.get_kw_arg("length", &RuntimeType::length(), exec_state)?;
let second_length = args.get_kw_arg_opt("secondLength", &RuntimeType::length(), exec_state)?;
let angle = args.get_kw_arg_opt("angle", &RuntimeType::angle(), exec_state)?;
let legacy_csg: Option<bool> = args.get_kw_arg_opt("legacyMethod", &RuntimeType::bool(), exec_state)?;
let csg_algorithm = CsgAlgorithm::legacy(legacy_csg.unwrap_or_default());
let edge_cut_number: Option<u32> = args.get_kw_arg_opt("version", &RuntimeType::count(), exec_state)?;
let tangent_chain: Option<bool> = args.get_kw_arg_opt("tangentChain", &RuntimeType::bool(), exec_state)?;
let tangent_chain = tangent_chain.unwrap_or(exec_state.kcl_version() >= KclVersion::V3Preview);
let edge_cut_version: EdgeCutVersion = edge_cut_number
.map(|num| {
num.try_into().map_err(|()| {
KclError::new_semantic(KclErrorDetails::new(
format!("{} is not a version of the Zoo edge cut algorithm", num),
vec![args.source_range],
))
})
})
.transpose()?
.unwrap_or_else(|| default_edge_cut_version(exec_state.kcl_version()));
let tag = args.get_kw_arg_opt("tag", &RuntimeType::tag_decl(), exec_state)?;
let edge_refs = args.get_kw_arg_opt("edges", &RuntimeType::any_array(), exec_state)?;
let tags = args.kw_arg_edge_array_and_source_opt("tags")?;
let edge_inputs = super::fillet::parse_tagged_edge_inputs(
edge_refs,
tags,
Some(solid.as_ref()),
exec_state,
&args,
"You must provide either 'tags' or 'edges' to chamfer edges",
"You must provide either 'tags' or 'edges' to chamfer edges, not both",
)
.await?;
match edge_inputs {
super::fillet::TaggedEdgeInputs::EngineRefs(edge_refs) => {
let value = inner_chamfer_with_engine_refs(
solid,
length,
edge_refs,
second_length,
angle,
csg_algorithm,
edge_cut_version,
tangent_chain,
tag,
exec_state,
args,
)
.await?;
Ok(KclValue::Solid { value })
}
super::fillet::TaggedEdgeInputs::Tags(tags) => match edge_cut_version {
EdgeCutVersion::V0 | EdgeCutVersion::V1 => {
let value = inner_chamfer(
solid,
length,
tags,
second_length,
angle,
None,
tag,
csg_algorithm,
edge_cut_version,
tangent_chain,
exec_state,
args,
)
.await?;
Ok(KclValue::Solid { value })
}
EdgeCutVersion::V2 | _ => {
let value = inner_chamfer_v2(
solid,
length,
tags,
second_length,
angle,
None,
tag,
csg_algorithm,
edge_cut_version,
tangent_chain,
exec_state,
args,
)
.await?;
Ok(KclValue::Solid { value })
}
},
}
}
#[allow(clippy::too_many_arguments)]
async fn inner_chamfer(
solid: Box<Solid>,
length: TyF64,
tags: Vec<(EdgeReference, crate::SourceRange)>,
second_length: Option<TyF64>,
angle: Option<TyF64>,
custom_profile: Option<Sketch>,
tag: Option<TagNode>,
csg_algorithm: CsgAlgorithm,
edge_cut_version: EdgeCutVersion,
tangent_chain: bool,
exec_state: &mut ExecState,
args: Args,
) -> Result<Box<Solid>, KclError> {
if tag.is_some() && tags.len() > 1 {
return Err(KclError::new_type(KclErrorDetails::new(
"You can only tag one edge at a time with a tagged chamfer. Either delete the tag for the chamfer fn if you don't need it OR separate into individual chamfer functions for each tag.".to_string(),
vec![args.source_range],
)));
}
if angle.is_some() && second_length.is_some() {
return Err(KclError::new_semantic(KclErrorDetails::new(
"Cannot specify both an angle and a second length. Specify only one.".to_string(),
vec![args.source_range],
)));
}
let strategy = if second_length.is_some() || angle.is_some() || custom_profile.is_some() {
CutStrategy::Csg
} else {
Default::default()
};
let second_distance = second_length.map(|x| LengthUnit(x.to_mm()));
let angle = angle.map(|x| Angle::from_degrees(x.to_degrees(exec_state, args.source_range)));
if let Some(angle) = angle
&& (angle.ge(&Angle::quarter_circle()) || angle.le(&Angle::zero()))
{
return Err(KclError::new_semantic(KclErrorDetails::new(
"The angle of a chamfer must be greater than zero and less than 90 degrees.".to_string(),
vec![args.source_range],
)));
}
let cut_type = if let Some(custom_profile) = custom_profile {
exec_state
.batch_modeling_cmd(
ModelingCmdMeta::from_args(exec_state, &args),
ModelingCmd::from(
mcmd::ObjectVisible::builder()
.object_id(custom_profile.id)
.hidden(true)
.build(),
),
)
.await?;
CutTypeV2::Custom {
path: custom_profile.id,
}
} else {
CutTypeV2::Chamfer {
distance: LengthUnit(length.to_mm()),
second_distance,
angle,
swap: false,
}
};
let mut solid = solid.clone();
let mut tag_entries: Vec<crate::execution::DirectTagFilletTagEntry> = Vec::new();
for (edge_ref, source_range) in &tags {
let edge_id = match edge_ref {
EdgeReference::Uuid(u) => *u,
EdgeReference::Tag(t) => args.get_tag_engine_info(exec_state, t)?.id,
};
if crate::runtime_flags::z0006_refactor_metadata_enabled()
&& let Ok(face_ids) = super::edge::get_face_ids_for_edge(exec_state, solid.id, edge_id, &args).await
&& let [a, b] = face_ids.as_slice()
{
let tag_identifier = match edge_ref {
EdgeReference::Tag(t) => t.value.clone(),
EdgeReference::Uuid(_) => String::new(),
};
if !tag_identifier.is_empty() {
tag_entries.push(crate::execution::DirectTagFilletTagEntry {
tag_identifier,
edge_id,
face_ids: [*a, *b],
});
} else {
exec_state.record_edge_refactor_meta_from_pending(edge_id, *source_range, [*a, *b]);
}
}
}
if !tag_entries.is_empty() {
exec_state.record_direct_tag_fillet_meta(crate::execution::DirectTagFilletMeta {
call_source_range: args.source_range,
tags: tag_entries,
});
}
for (edge_tag, _) in tags {
let edge_ids = edge_tag.get_all_engine_ids(exec_state, &args)?;
for edge_id in edge_ids {
let id = exec_state.next_uuid();
exec_state
.batch_edge_cut_cmd(
ModelingCmdMeta::from_args_id(exec_state, &args, id),
ModelingCmd::from(
mcmd::Solid3dCutEdges::builder()
.use_legacy(csg_algorithm.is_legacy())
.edge_ids(vec![edge_id])
.extra_face_ids(vec![])
.strategy(strategy)
.object_id(solid.id)
.tolerance(LengthUnit(DEFAULT_TOLERANCE))
.cut_type(cut_type)
.version(edge_cut_version)
.tangent_chain(tangent_chain)
.build(),
),
)
.await?;
solid.edge_cuts.push(EdgeCut::Chamfer {
id,
edge_id,
length: length.clone(),
tag: Box::new(tag.clone()),
});
if let Some(ref tag) = tag {
solid.value.push(ExtrudeSurface::Chamfer(ChamferSurface {
face_id: id,
tag: Some(tag.clone()),
geo_meta: GeoMeta {
id,
metadata: args.source_range.into(),
},
}));
}
}
}
Ok(solid)
}
#[allow(clippy::too_many_arguments)]
async fn inner_chamfer_v2(
solid: Box<Solid>,
length: TyF64,
tags: Vec<(EdgeReference, crate::SourceRange)>,
second_length: Option<TyF64>,
angle: Option<TyF64>,
custom_profile: Option<Sketch>,
tag: Option<TagNode>,
csg_algorithm: CsgAlgorithm,
edge_cut_version: EdgeCutVersion,
tangent_chain: bool,
exec_state: &mut ExecState,
args: Args,
) -> Result<Box<Solid>, KclError> {
if tag.is_some() && tags.len() > 1 {
return Err(KclError::new_type(KclErrorDetails::new(
"You can only tag one edge at a time with a tagged chamfer. Either delete the tag for the chamfer fn if you don't need it OR separate into individual chamfer functions for each tag.".to_string(),
vec![args.source_range],
)));
}
if tags.is_empty() {
return Err(KclError::new_semantic(KclErrorDetails {
source_ranges: vec![args.source_range],
message: "You must chamfer at least one tag".to_owned(),
backtrace: Default::default(),
}));
}
if angle.is_some() && second_length.is_some() {
return Err(KclError::new_semantic(KclErrorDetails::new(
"Cannot specify both an angle and a second length. Specify only one.".to_string(),
vec![args.source_range],
)));
}
let strategy = if second_length.is_some() || angle.is_some() || custom_profile.is_some() {
CutStrategy::Csg
} else {
Default::default()
};
let second_distance = second_length.map(|x| LengthUnit(x.to_mm()));
let angle = angle.map(|x| Angle::from_degrees(x.to_degrees(exec_state, args.source_range)));
if let Some(angle) = angle
&& (angle.ge(&Angle::quarter_circle()) || angle.le(&Angle::zero()))
{
return Err(KclError::new_semantic(KclErrorDetails::new(
"The angle of a chamfer must be greater than zero and less than 90 degrees.".to_string(),
vec![args.source_range],
)));
}
let cut_type = if let Some(custom_profile) = custom_profile {
exec_state
.batch_modeling_cmd(
ModelingCmdMeta::from_args(exec_state, &args),
ModelingCmd::from(
mcmd::ObjectVisible::builder()
.object_id(custom_profile.id)
.hidden(true)
.build(),
),
)
.await?;
CutTypeV2::Custom {
path: custom_profile.id,
}
} else {
CutTypeV2::Chamfer {
distance: LengthUnit(length.to_mm()),
second_distance,
angle,
swap: false,
}
};
let mut solid = solid.clone();
let mut edge_ids = Vec::new();
let mut tag_entries: Vec<crate::execution::DirectTagFilletTagEntry> = Vec::new();
for (edge_ref, source_range) in &tags {
let ids = edge_ref.get_all_engine_ids(exec_state, &args)?;
edge_ids.extend(ids.iter().copied());
let tag_identifier = match edge_ref {
EdgeReference::Tag(t) => t.value.clone(),
EdgeReference::Uuid(_) => String::new(),
};
for edge_id in ids {
if crate::runtime_flags::z0006_refactor_metadata_enabled()
&& let Ok(face_ids) = super::edge::get_face_ids_for_edge(exec_state, solid.id, edge_id, &args).await
&& let [a, b] = face_ids.as_slice()
{
if !tag_identifier.is_empty() {
tag_entries.push(crate::execution::DirectTagFilletTagEntry {
tag_identifier: tag_identifier.clone(),
edge_id,
face_ids: [*a, *b],
});
} else {
exec_state.record_edge_refactor_meta_from_pending(edge_id, *source_range, [*a, *b]);
}
}
}
}
if !tag_entries.is_empty() {
exec_state.record_direct_tag_fillet_meta(crate::execution::DirectTagFilletMeta {
call_source_range: args.source_range,
tags: tag_entries,
});
}
let id = exec_state.next_uuid();
let num_extra_ids = edge_ids.len().saturating_sub(1);
let mut extra_face_ids = Vec::with_capacity(num_extra_ids);
for _ in 0..num_extra_ids {
extra_face_ids.push(exec_state.next_uuid());
}
exec_state
.batch_edge_cut_cmd(
ModelingCmdMeta::from_args_id(exec_state, &args, id),
ModelingCmd::from(
mcmd::Solid3dCutEdges::builder()
.use_legacy(csg_algorithm.is_legacy())
.edge_ids(edge_ids.clone())
.extra_face_ids(extra_face_ids)
.strategy(strategy)
.object_id(solid.id)
.tolerance(LengthUnit(DEFAULT_TOLERANCE))
.cut_type(cut_type)
.version(edge_cut_version)
.tangent_chain(tangent_chain)
.build(),
),
)
.await?;
let new_edge_cuts = edge_ids.into_iter().map(|edge_id| EdgeCut::Chamfer {
id,
edge_id,
length: length.clone(),
tag: Box::new(tag.clone()),
});
solid.edge_cuts.extend(new_edge_cuts);
if let Some(ref tag) = tag {
solid.value.push(ExtrudeSurface::Chamfer(ChamferSurface {
face_id: id,
tag: Some(tag.clone()),
geo_meta: GeoMeta {
id,
metadata: args.source_range.into(),
},
}));
}
Ok(solid)
}
#[expect(clippy::too_many_arguments)]
async fn inner_chamfer_with_engine_refs(
solid: Box<Solid>,
length: TyF64,
edge_references: Vec<kcmc::shared::EdgeSpecifier>,
second_length: Option<TyF64>,
angle: Option<TyF64>,
csg_algorithm: CsgAlgorithm,
edge_cut_version: EdgeCutVersion,
tangent_chain: bool,
tag: Option<TagNode>,
exec_state: &mut ExecState,
args: Args,
) -> Result<Box<Solid>, KclError> {
if tag.is_some() && edge_references.len() > 1 {
return Err(KclError::new_type(KclErrorDetails::new(
"You can only tag one edge at a time with a tagged chamfer. Either delete the tag for the chamfer fn if you don't need it OR separate into individual chamfer functions for each edgeRef.".to_string(),
vec![args.source_range],
)));
}
if angle.is_some() && second_length.is_some() {
return Err(KclError::new_semantic(KclErrorDetails::new(
"Cannot specify both an angle and a second length. Specify only one.".to_string(),
vec![args.source_range],
)));
}
let strategy = if second_length.is_some() || angle.is_some() {
CutStrategy::Csg
} else {
Default::default()
};
let second_distance = second_length.map(|x| LengthUnit(x.to_mm()));
let angle = angle.map(|x| Angle::from_degrees(x.to_degrees(exec_state, args.source_range)));
if let Some(angle) = angle
&& (angle.ge(&Angle::quarter_circle()) || angle.le(&Angle::zero()))
{
return Err(KclError::new_semantic(KclErrorDetails::new(
"The angle of a chamfer must be greater than zero and less than 90 degrees.".to_string(),
vec![args.source_range],
)));
}
let cut_type = CutTypeV2::Chamfer {
distance: LengthUnit(length.to_mm()),
second_distance,
angle,
swap: false,
};
let id = exec_state.next_uuid();
let num_extra_ids = edge_references.len().saturating_sub(1);
let mut extra_face_ids = Vec::with_capacity(num_extra_ids);
for _ in 0..num_extra_ids {
extra_face_ids.push(exec_state.next_uuid());
}
let mut solid = solid.clone();
exec_state
.batch_edge_cut_cmd(
ModelingCmdMeta::from_args_id(exec_state, &args, id),
ModelingCmd::from(
mcmd::Solid3dCutEdgeReferences::builder()
.object_id(solid.id)
.edges_references(edge_references)
.cut_type(cut_type)
.tolerance(LengthUnit(DEFAULT_TOLERANCE))
.strategy(strategy)
.extra_face_ids(extra_face_ids)
.use_legacy(csg_algorithm.is_legacy())
.version(edge_cut_version)
.tangent_chain(tangent_chain)
.build(),
),
)
.await?;
solid.pending_edge_cut_ids.push(id);
if let Some(ref tag) = tag {
solid.value.push(ExtrudeSurface::Chamfer(ChamferSurface {
face_id: id,
tag: Some(tag.clone()),
geo_meta: GeoMeta {
id,
metadata: args.source_range.into(),
},
}));
}
Ok(solid)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::execution::ExecTestResults;
use crate::execution::parse_execute;
#[tokio::test(flavor = "multi_thread")]
async fn chamfer_default_depends_on_kcl_version() {
assert_eq!(emitted_chamfer_version("2.0", None).await, EdgeCutVersion::V1);
assert_eq!(
emitted_chamfer_version("\"3.0-preview\"", None).await,
EdgeCutVersion::V2
);
}
#[tokio::test(flavor = "multi_thread")]
async fn explicit_chamfer_version_overrides_kcl_default() {
assert_eq!(emitted_chamfer_version("2.0", Some(2)).await, EdgeCutVersion::V2);
}
#[tokio::test(flavor = "multi_thread")]
async fn chamfer_version_is_removed_in_kcl_3() {
let result = run_chamfer("\"3.0-preview\"", Some(1)).await;
assert!(
result
.issues()
.iter()
.any(|issue| {
issue.message
== "`version` is not an argument of `chamfer`; it was removed in KCL 3.0, but this program uses KCL 3.0-preview"
}),
"issues: {:#?}",
result.issues()
);
assert_eq!(emitted_cut_edges_version(&result), EdgeCutVersion::V2);
}
async fn emitted_chamfer_version(kcl_version: &str, explicit_version: Option<u32>) -> EdgeCutVersion {
emitted_cut_edges_version(&run_chamfer(kcl_version, explicit_version).await)
}
async fn run_chamfer(kcl_version: &str, explicit_version: Option<u32>) -> ExecTestResults {
let version_arg = explicit_version
.map(|version| format!(", version = {version}"))
.unwrap_or_default();
let code = format!(
r#"@settings(kclVersion = {kcl_version}, experimentalFeatures = allow)
profile = sketch(on = XY) {{
edge1 = line(start = [var 0mm, var 0mm], end = [var 10mm, var 0mm])
edge2 = line(start = [var 10mm, var 0mm], end = [var 10mm, var 10mm])
edge3 = line(start = [var 10mm, var 10mm], end = [var 0mm, var 10mm])
edge4 = line(start = [var 0mm, var 10mm], end = [var 0mm, var 0mm])
coincident([edge1.end, edge2.start])
coincident([edge2.end, edge3.start])
coincident([edge3.end, edge4.start])
coincident([edge4.end, edge1.start])
}}
profileRegion = region(point = [5mm, 5mm], sketch = profile)
solid = extrude(profileRegion, length = 10mm, tagEnd = $top)
chamfer(solid, tags = [getCommonEdge(faces = [profileRegion.tags.edge1, top])], length = 1mm{version_arg})
"#
);
parse_execute(&code).await.unwrap()
}
fn emitted_cut_edges_version(result: &ExecTestResults) -> EdgeCutVersion {
result
.root_module_artifact_commands()
.iter()
.find_map(|artifact_command| match &artifact_command.command {
ModelingCmd::Solid3dCutEdges(command) => Some(command.version),
_ => None,
})
.expect("chamfer should emit a Solid3dCutEdges command")
}
#[tokio::test(flavor = "multi_thread")]
async fn tangent_chain_requires_kcl_3_and_is_sent_to_engine() {
let body = r#"
profile = sketch(on = XY) {
edge1 = line(start = [var 0mm, var 0mm], end = [var 10mm, var 0mm])
edge2 = line(start = [var 10mm, var 0mm], end = [var 10mm, var 10mm])
edge3 = line(start = [var 10mm, var 10mm], end = [var 0mm, var 10mm])
edge4 = line(start = [var 0mm, var 10mm], end = [var 0mm, var 0mm])
coincident([edge1.end, edge2.start])
coincident([edge2.end, edge3.start])
coincident([edge3.end, edge4.start])
coincident([edge4.end, edge1.start])
}
profileRegion = region(point = [5mm, 5mm], sketch = profile)
solid = extrude(profileRegion, length = 10mm, tagEnd = $top)
chamfer(solid, tags = [getCommonEdge(faces = [profileRegion.tags.edge1, top])], length = 1mm, tangentChain = true)
"#;
let result = parse_execute(&format!("@settings(kclVersion = 2.0)\n{body}"))
.await
.unwrap();
assert!(result.issues().iter().any(|issue| {
issue.message
== "`tangentChain` is not an argument of `chamfer`; it was added in KCL 3.0, but this program uses KCL 2.0"
}));
let result = parse_execute(&format!("@settings(kclVersion = \"3.0-preview\")\n{body}"))
.await
.unwrap();
let tangent_chain = result
.root_module_artifact_commands()
.iter()
.find_map(|artifact_command| match &artifact_command.command {
ModelingCmd::Solid3dCutEdges(command) => Some(command.tangent_chain),
_ => None,
})
.expect("chamfer should emit a Solid3dCutEdges command");
assert!(tangent_chain);
let default_body = body.replace(", tangentChain = true", "");
let result = parse_execute(&format!("@settings(kclVersion = \"3.0-preview\")\n{default_body}"))
.await
.unwrap();
let tangent_chain = result
.root_module_artifact_commands()
.iter()
.find_map(|artifact_command| match &artifact_command.command {
ModelingCmd::Solid3dCutEdges(command) => Some(command.tangent_chain),
_ => None,
})
.expect("chamfer should emit a Solid3dCutEdges command");
assert!(tangent_chain, "tangentChain should default to true after KCL 2");
let disabled_body = body.replace("tangentChain = true", "tangentChain = false");
let result = parse_execute(&format!("@settings(kclVersion = \"3.0-preview\")\n{disabled_body}"))
.await
.unwrap();
let tangent_chain = result
.root_module_artifact_commands()
.iter()
.find_map(|artifact_command| match &artifact_command.command {
ModelingCmd::Solid3dCutEdges(command) => Some(command.tangent_chain),
_ => None,
})
.expect("chamfer should emit a Solid3dCutEdges command");
assert!(!tangent_chain, "an explicit false should override the default");
}
}