add API fallback for engine utils lib

This commit is contained in:
Mike Farrell
2024-10-22 12:58:35 -07:00
parent d23ddc19eb
commit 5bea90ad9a
9 changed files with 128 additions and 28 deletions

4
.gitignore vendored
View File

@ -66,3 +66,7 @@ venv
# electron
out/
# engine wasm utils
src/lib/engine-utils/engine.wasm
src/lib/engine-utils/engine.js

View File

@ -121,9 +121,9 @@ dependencies = [
[[package]]
name = "anyhow"
version = "1.0.89"
version = "1.0.91"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "86fdf8605db99b54d3cd748a44c6d04df638eb5dafb219b135d0149bd0db01f6"
checksum = "c042108f3ed77fd83760a5fd79b53be043192bb3b9dba91d8c574c0ada7850c8"
dependencies = [
"backtrace",
]
@ -1684,9 +1684,9 @@ dependencies = [
[[package]]
name = "kittycad-modeling-cmds"
version = "0.2.68"
version = "0.2.70"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7e3aedfcc1d8ea9995ec3eb78a6743c585c9380475c48701797f107489b696aa"
checksum = "b135696d07a4fab928e5abace4dd05f4976eafab5d73e5747a85dc5a684b936c"
dependencies = [
"anyhow",
"chrono",
@ -3005,9 +3005,9 @@ dependencies = [
[[package]]
name = "serde_json"
version = "1.0.128"
version = "1.0.132"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ff5456707a1de34e7e37f2a6fd3d3f808c318259cbd01ab6377795054b483d8"
checksum = "d726bfaff4b320266d395898905d0eba0345aae23b54aee3a737e260fd46db03"
dependencies = [
"indexmap 2.6.0",
"itoa",

View File

@ -72,7 +72,7 @@ members = [
[workspace.dependencies]
http = "1"
kittycad = { version = "0.3.23", default-features = false, features = ["js", "requests"] }
kittycad-modeling-cmds = { version = "0.2.68", features = ["websocket"] }
kittycad-modeling-cmds = { version = "0.2.70", features = ["websocket"] }
[[test]]
name = "executor"

View File

@ -68,7 +68,7 @@ tokio-tungstenite = { version = "0.24.0", features = ["rustls-tls-native-roots"]
tower-lsp = { version = "0.20.0", features = ["proposed"] }
[features]
default = ["engine"]
default = ["engine"] # add wasm-engine-utils here when we're ready
cli = ["dep:clap"]
# For the lsp server, when run with stdout for rpc we want to disable println.
# This is used for editor extensions that use the lsp server.
@ -77,6 +77,10 @@ engine = []
pyo3 = ["dep:pyo3"]
# Helper functions also used in benchmarks.
lsp-test-util = []
#if enabled, kcl will link directly against a wasm build of the engine utils lib to save latency
wasm-engine-utils = []
#if enabled, kcl will link directly against a native build of the engine utils lib to save latency (not yet functional)
native-engine-utils = []
tabled = ["dep:tabled"]

View File

@ -6,14 +6,52 @@ use crate::{
std::Args,
};
use anyhow::Result;
use std::ffi::{CString, CStr};
use kittycad_modeling_cmds::{length_unit::LengthUnit, shared::Point3d};
mod cpp {
use std::os::raw::c_char;
extern "C" {
pub fn kcEngineUtilsEvaluatePath(sketch: *const c_char, t: f64) -> *const c_char;
}
}
pub fn is_available() -> bool {
false
true
}
pub async fn get_true_path_end_pos(_sketch: String, args: &Args) -> Result<String, KclError> {
Err(KclError::Internal(KclErrorDetails {
message: "Engine utils not yet implemented".into(),
source_ranges: vec![args.source_range],
}))
pub async fn get_true_path_end_pos(sketch: String, args: &Args) -> Result<Point3d<LengthUnit>, KclError> {
let c_string = CString::new(sketch).map_err(|e| {
KclError::Internal(KclErrorDetails {
message: format!("{:?}", e),
source_ranges: vec![args.source_range],
})
})?;
let arg = c_string.into_raw();
let result_string: String;
unsafe {
let result = cpp::kcEngineUtilsEvaluatePath(arg, 1.0);
let result_cstr = CStr::from_ptr(result);
let str_slice: &str = result_cstr.to_str().map_err(|e| {
KclError::Internal(KclErrorDetails {
message: format!("{:?}", e),
source_ranges: vec![args.source_range],
})
})?;
let str_buf: String = str_slice.to_owned();
result_string = str_buf.clone();
let _ = CString::from_raw(arg);
}
let point: Point3d<f64> = serde_json::from_str(&result_string).map_err(|e| {
KclError::Type(KclErrorDetails {
message: format!("Failed to path position from json: {}", e),
source_ranges: vec![args.source_range],
})
})?;
Ok(Point3d::<f64>::from(point).map(LengthUnit))
}

View File

@ -0,0 +1,35 @@
//! Functions for calling into the engine-utils library (a set of C++ utilities containing various logic for client-side CAD processing)
//! Note that this binary may not be available to all builds of kcl, so fallbacks that call the engine API should be implemented
use crate::{
errors::{KclError, KclErrorDetails},
std::Args,
};
use crate::engine::kcmc::{each_cmd as mcmd, ModelingCmd};
use anyhow::Result;
use kittycad_modeling_cmds::{length_unit::LengthUnit, ok_response::OkModelingCmdResponse, shared::Point3d, websocket::OkWebSocketResponseData};
pub fn is_available() -> bool {
true
}
pub async fn get_true_path_end_pos(sketch: String, args: &Args) -> Result<Point3d<LengthUnit>, KclError> {
let id = uuid::Uuid::new_v4();
let resp = args.send_modeling_cmd(id, ModelingCmd::from(mcmd::EngineUtilEvaluatePath {
path_json: sketch,
t: 1.0,
})).await?;
let OkWebSocketResponseData::Modeling {
modeling_response: OkModelingCmdResponse::EngineUtilEvaluatePath(point),
} = &resp
else {
return Err(KclError::Engine(KclErrorDetails {
message: format!("mcmd::EngineUtilEvaluatePath response was not as expected: {:?}", resp),
source_ranges: vec![args.source_range],
}));
};
Ok(point.pos)
}

View File

@ -6,7 +6,7 @@ use crate::{
std::Args,
};
use anyhow::Result;
use kittycad_modeling_cmds::{length_unit::LengthUnit, shared::Point3d};
mod cpp {
use wasm_bindgen::prelude::wasm_bindgen;
@ -42,6 +42,15 @@ where
Ok(result.as_string().unwrap_or_default())
}
pub async fn get_true_path_end_pos(sketch: String, args: &Args) -> Result<String, KclError> {
call_cpp(args, || cpp::get_true_path_end_pos(sketch.into())).await
pub async fn get_true_path_end_pos(sketch: String, args: &Args) -> Result<Point3d<LengthUnit>, KclError> {
let result_str = call_cpp(args, || cpp::get_true_path_end_pos(sketch.into())).await?;
let point: Point3d<f64> = serde_json::from_str(&result_str).map_err(|e| {
KclError::Type(KclErrorDetails {
message: format!("Failed to path position from json: {}", e),
source_ranges: vec![args.source_range],
})
})?;
Ok(Point3d::<f64>::from(point).map(LengthUnit))
}

View File

@ -9,10 +9,16 @@ pub mod conn_mock;
pub mod conn_wasm;
#[cfg(not(target_arch = "wasm32"))]
#[cfg(feature = "native-engine-utils")]
pub mod engine_utils;
#[cfg(target_arch = "wasm32")]
#[cfg(feature = "wasm-engine-utils")]
pub mod engine_utils_wasm;
#[cfg(feature = "engine")]
#[cfg(any(not(target_arch = "wasm32"), all(not(feature = "native-engine-utils"), not(feature = "wasm-engine-utils"))))]
pub mod engine_utils_api;
use std::{
collections::HashMap,
sync::{Arc, Mutex},

View File

@ -6,7 +6,7 @@ use anyhow::Result;
use derive_docs::stdlib;
use kcmc::shared::Point2d as KPoint2d; // Point2d is already defined in this pkg, to impl ts_rs traits.
use kcmc::{each_cmd as mcmd, length_unit::LengthUnit, shared::Angle, ModelingCmd};
use kittycad_modeling_cmds as kcmc;
use kittycad_modeling_cmds::{self as kcmc, units};
use kittycad_modeling_cmds::shared::PathSegment;
use parse_display::{Display, FromStr};
use schemars::JsonSchema;
@ -30,11 +30,17 @@ use crate::{
};
#[cfg(not(target_arch = "wasm32"))]
#[cfg(feature = "native-engine-utils")]
use crate::engine::engine_utils;
#[cfg(target_arch = "wasm32")]
#[cfg(feature = "wasm-engine-utils")]
use crate::engine::engine_utils_wasm as engine_utils;
#[cfg(feature = "engine")]
#[cfg(any(not(target_arch = "wasm32"), all(not(feature = "native-engine-utils"), not(feature = "wasm-engine-utils"))))]
use crate::engine::engine_utils_api as engine_utils;
/// A tag for a face.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, ts_rs::TS, JsonSchema)]
#[ts(export)]
@ -1503,7 +1509,7 @@ pub(crate) async fn inner_arc(
let a_start = Angle::from_degrees(*angle_start);
let a_end = Angle::from_degrees(*angle_end);
let (start, center, mut end) = arc_start_center_and_end(from, a_start, a_end, *radius);
let (_, center, mut end) = arc_start_center_and_end(from, a_start, a_end, *radius);
if engine_utils::is_available() {
let mut path_plus_arc = sketch.clone();
@ -1532,15 +1538,13 @@ pub(crate) async fn inner_arc(
})
})?;
let result_str = engine_utils::get_true_path_end_pos(sketch_json_value, &args).await?;
let result_end: Point2d = serde_json::from_str(&result_str).map_err(|e| {
KclError::Type(KclErrorDetails {
message: format!("Failed to convert arc center from json: {}", e),
source_ranges: vec![args.source_range],
})
})?;
end = result_end;
//???? someone double check me on this unit conversion - mike
let units = units::UnitLength::Millimeters;
let result_end = engine_utils::get_true_path_end_pos(sketch_json_value, &args).await?;
end = Point2d {
x: result_end.x.to_millimeters(units),
y: result_end.y.to_millimeters(units),
};
}
(center, a_start, a_end, *radius, end)