1pub use bench_api as api;
30pub use serde_json::{self, Value, json};
31
32pub mod panel;
33
34use api::*;
35
36#[doc(hidden)]
37pub mod bindings {
38 wit_bindgen::generate!({
39 world: "workbench",
40 path: "wit",
41 pub_export_macro: true,
42 export_macro_name: "export_workbench",
43 default_bindings_module: "printcad_bench_sdk::bindings",
44 });
45}
46
47pub trait Bench: Default + 'static {
52 fn describe(&self) -> Registration;
54
55 fn feature_info(&self, node: &Node) -> FeatureInfo {
57 FeatureInfo {
58 kind_label: node.kind.clone(),
59 builds_solid: true,
60 ..Default::default()
61 }
62 }
63
64 fn parameters(&self, _node: &Node) -> Vec<Parameter> {
66 Vec::new()
67 }
68
69 fn settle(&self, node: &Node) -> Value {
71 node.data.clone()
72 }
73
74 fn rebuild(&mut self, _request: RebuildRequest) -> Vec<Rebuild> {
76 Vec::new()
77 }
78
79 fn run_command(&mut self, id: &str, _args: Value) -> Result<Value, String> {
81 Err(format!("no command `{id}`"))
82 }
83
84 fn input(&mut self, _input: &Input) -> bool {
87 false
88 }
89
90 fn frame(&mut self, _pointer: &Pointer) -> Frame {
93 Frame::default()
94 }
95
96 fn panel_event(&mut self, _slot: PanelSlot, _event: PanelEvent) {}
100
101 fn task_close(&mut self, _accept: bool) -> Option<String> {
104 None
105 }
106
107 fn menu_items(&mut self, _scope: &MenuScope) -> Vec<MenuItem> {
108 Vec::new()
109 }
110
111 fn menu_command(&mut self, _id: &str, _scope: &MenuScope) -> bool {
112 false
113 }
114
115 fn delete_feature(&mut self, _id: &str) -> bool {
117 false
118 }
119
120 fn settings_panel(&mut self) -> Vec<Widget> {
122 Vec::new()
123 }
124
125 fn settings(&self) -> Option<Value> {
127 None
128 }
129
130 fn apply_settings(&mut self, _settings: Value) {}
131
132 fn suspend(&mut self) -> Option<Vec<u8>> {
134 None
135 }
136
137 fn resume(&mut self, _state: Option<Vec<u8>>) {}
138
139 fn job(_entry: &str, _input: &str) -> Result<String, String> {
143 Err("this bench has no jobs".into())
144 }
145}
146
147pub mod host {
149 use super::bindings::printcad::workbench::host as raw;
150 use super::*;
151
152 pub fn info(message: &str) {
153 raw::log("info", message);
154 }
155
156 pub fn warn(message: &str) {
157 raw::log("warn", message);
158 }
159
160 pub fn error(message: &str) {
161 raw::log("error", message);
162 }
163
164 pub fn feature(id: &str) -> Option<Node> {
166 serde_json::from_str(&raw::feature(id)?).ok()
167 }
168
169 pub fn features() -> Vec<Node> {
171 serde_json::from_str(&raw::features()).unwrap_or_default()
172 }
173
174 pub fn bodies() -> Vec<Body> {
175 serde_json::from_str(&raw::bodies()).unwrap_or_default()
176 }
177
178 pub fn body_mesh(body: &str) -> Option<(Vec<[f32; 3]>, Vec<u32>)> {
180 let mesh = raw::body_mesh(body)?;
181 let positions = mesh.positions.as_chunks::<3>().0.to_vec();
182 Some((positions, mesh.indices))
183 }
184
185 pub fn body_shape(body: &str) -> Option<Vec<u8>> {
187 raw::body_shape(body)
188 }
189
190 pub fn profile(feature: &str) -> Option<api::kernel_api::Profile> {
194 serde_json::from_str(&raw::profile(feature)?).ok()
195 }
196
197 pub fn call(command: &str, args: Value) -> Result<Value, String> {
199 let answer = raw::call(command, &args.to_string())?;
200 serde_json::from_str(&answer).map_err(|e| e.to_string())
201 }
202
203 pub fn request(request: Request) {
204 if let Ok(json) = serde_json::to_string(&request) {
205 raw::request(&json);
206 }
207 }
208
209 pub fn redraw() {
211 raw::redraw();
212 }
213
214 pub fn add_feature(
216 kind: &str,
217 name: &str,
218 body: Option<&str>,
219 data: Value,
220 ) -> Result<String, String> {
221 let answer = call(
222 calls::ADD_FEATURE,
223 json!({"kind": kind, "name": name, "body": body, "data": data}),
224 )?;
225 answer
226 .as_str()
227 .map(str::to_string)
228 .ok_or_else(|| "no id came back".into())
229 }
230
231 pub fn set_feature_data(id: &str, data: Value) -> Result<(), String> {
232 call(calls::SET_FEATURE_DATA, json!({"id": id, "data": data})).map(|_| ())
233 }
234
235 pub fn remove_feature(id: &str) -> Result<(), String> {
236 call(calls::REMOVE_FEATURE, json!({"id": id})).map(|_| ())
237 }
238
239 pub fn remove_body(id: &str) -> Result<(), String> {
243 call(calls::REMOVE_BODY, json!({"id": id})).map(|_| ())
244 }
245
246 pub fn create_body(name: Option<&str>) -> Result<String, String> {
248 let answer = call(calls::CREATE_BODY, json!({"name": name}))?;
249 answer
250 .as_str()
251 .map(str::to_string)
252 .ok_or_else(|| "no id came back".into())
253 }
254
255 pub fn start_job(entry: &str, input: &str) -> Result<u64, String> {
258 call(calls::JOB_START, json!({"entry": entry, "input": input}))?
259 .as_u64()
260 .ok_or_else(|| "no job number came back".into())
261 }
262
263 pub fn cancel_job(job: u64) {
264 let _ = call(calls::JOB_CANCEL, json!({ "job": job }));
265 }
266
267 pub fn progress(done: u64, total: u64) {
269 raw::progress(done, total);
270 }
271
272 pub fn cancelled() -> bool {
274 raw::cancelled()
275 }
276
277 pub fn helper(name: &str, input: &[u8]) -> Result<Vec<u8>, String> {
282 raw::helper(name, input)
283 }
284
285 pub fn helper_open(name: &str) -> Result<u64, String> {
290 raw::helper_open(name)
291 }
292
293 pub fn helper_send(handle: u64, line: &str) -> Result<(), String> {
295 raw::helper_send(handle, line)
296 }
297
298 pub fn helper_receive(handle: u64, wait_ms: u32) -> Result<Option<String>, String> {
302 raw::helper_receive(handle, wait_ms)
303 }
304
305 pub fn helper_close(handle: u64) {
306 raw::helper_close(handle);
307 }
308
309 pub fn mesh_create(
312 positions: &[[f32; 3]],
313 indices: &[u32],
314 colors: &[[f32; 3]],
315 ) -> Result<u64, String> {
316 raw::mesh_create(positions.as_flattened(), indices, colors.as_flattened())
317 }
318
319 pub fn mesh_update(
322 handle: u64,
323 first: u32,
324 positions: &[[f32; 3]],
325 colors: &[[f32; 3]],
326 ) -> Result<(), String> {
327 raw::mesh_update(
328 handle,
329 first,
330 positions.as_flattened(),
331 colors.as_flattened(),
332 )
333 }
334
335 pub fn mesh_remove(handle: u64) {
336 raw::mesh_remove(handle);
337 }
338}
339
340pub struct HeightField {
346 handle: u64,
347 origin: [f32; 3],
348 cols: u32,
349 rows: u32,
350 pitch: f32,
351}
352
353impl HeightField {
354 pub fn new(
357 origin: [f32; 3],
358 cols: u32,
359 rows: u32,
360 pitch: f32,
361 heights: &[f32],
362 colors: &[[f32; 3]],
363 ) -> Result<Self, String> {
364 if cols < 2 || rows < 2 || heights.len() != (cols * rows) as usize {
365 return Err("a field has at least 2 × 2 points and a height for each".into());
366 }
367 let field = |handle| Self {
368 handle,
369 origin,
370 cols,
371 rows,
372 pitch,
373 };
374 let shape = field(0);
375 let positions: Vec<[f32; 3]> = (0..rows)
376 .flat_map(|r| (0..cols).map(move |c| (c, r)))
377 .zip(heights)
378 .map(|((c, r), h)| shape.point(c, r, *h))
379 .collect();
380 let mut indices = Vec::with_capacity(((cols - 1) * (rows - 1) * 6) as usize);
381 for r in 0..rows - 1 {
382 for c in 0..cols - 1 {
383 let at = r * cols + c;
384 indices.extend([at, at + 1, at + cols, at + 1, at + cols + 1, at + cols]);
385 }
386 }
387 host::mesh_create(&positions, &indices, colors).map(field)
388 }
389
390 pub fn handle(&self) -> u64 {
391 self.handle
392 }
393
394 fn point(&self, col: u32, row: u32, height: f32) -> [f32; 3] {
395 [
396 self.origin[0] + col as f32 * self.pitch,
397 self.origin[1] + row as f32 * self.pitch,
398 self.origin[2] + height,
399 ]
400 }
401
402 pub fn update(
405 &self,
406 col: u32,
407 row: u32,
408 width: u32,
409 height: u32,
410 heights: &[f32],
411 colors: &[[f32; 3]],
412 ) -> Result<(), String> {
413 if col + width > self.cols
414 || row + height > self.rows
415 || heights.len() != (width * height) as usize
416 || !(colors.is_empty() || colors.len() == heights.len())
417 {
418 return Err("the rectangle and its heights fit the field".into());
419 }
420 for r in 0..height {
421 let line = (r * width) as usize..((r + 1) * width) as usize;
422 let positions: Vec<[f32; 3]> = (0..width)
423 .zip(&heights[line.clone()])
424 .map(|(c, h)| self.point(col + c, row + r, *h))
425 .collect();
426 let colors = if colors.is_empty() {
427 &[][..]
428 } else {
429 &colors[line]
430 };
431 host::mesh_update(self.handle, (row + r) * self.cols + col, &positions, colors)?;
432 }
433 Ok(())
434 }
435}
436
437impl Drop for HeightField {
438 fn drop(&mut self) {
439 host::mesh_remove(self.handle);
440 }
441}
442
443#[doc(hidden)]
444pub mod adapter {
445 use std::any::Any;
446 use std::cell::RefCell;
447
448 use super::bindings::exports::printcad::workbench::bench::Guest;
449 use super::*;
450
451 thread_local! {
452 static BENCH: RefCell<Option<Box<dyn Any>>> = const { RefCell::new(None) };
453 }
454
455 fn with<B: Bench, R>(f: impl FnOnce(&mut B) -> R) -> R {
456 BENCH.with(|cell| {
457 let mut slot = cell.borrow_mut();
458 let bench = slot.get_or_insert_with(|| Box::new(B::default()));
459 f(bench.downcast_mut::<B>().expect("one bench per component"))
460 })
461 }
462
463 fn read<T: serde::de::DeserializeOwned>(json: &str) -> Option<T> {
467 match serde_json::from_str(json) {
468 Ok(value) => Some(value),
469 Err(e) if e.to_string().starts_with("unknown variant") => None,
470 Err(e) => {
471 host::error(&format!("the app sent what this bench cannot read: {e}"));
472 None
473 }
474 }
475 }
476
477 fn write<T: serde::Serialize>(value: &T) -> String {
478 serde_json::to_string(value).unwrap_or_default()
479 }
480
481 pub struct Exports<B>(std::marker::PhantomData<B>);
483
484 impl<B: Bench> Guest for Exports<B> {
485 fn describe() -> String {
486 with::<B, _>(|b| write(&b.describe()))
487 }
488
489 fn feature_info(node: String) -> String {
490 match read::<Node>(&node) {
491 Some(node) => with::<B, _>(|b| write(&b.feature_info(&node))),
492 None => String::new(),
493 }
494 }
495
496 fn parameters(node: String) -> String {
497 match read::<Node>(&node) {
498 Some(node) => with::<B, _>(|b| write(&b.parameters(&node))),
499 None => "[]".into(),
500 }
501 }
502
503 fn settle(node: String) -> String {
504 match read::<Node>(&node) {
505 Some(node) => with::<B, _>(|b| write(&b.settle(&node))),
506 None => String::new(),
507 }
508 }
509
510 fn rebuild(request: String) -> String {
511 match read::<RebuildRequest>(&request) {
512 Some(request) => with::<B, _>(|b| write(&b.rebuild(request))),
513 None => "[]".into(),
514 }
515 }
516
517 fn run_command(id: String, args: String) -> Result<String, String> {
518 let args: Value = serde_json::from_str(&args).unwrap_or(Value::Null);
519 with::<B, _>(|b| b.run_command(&id, args)).map(|v| v.to_string())
520 }
521
522 fn input(input: String) -> bool {
523 match read::<Input>(&input) {
524 Some(input) => with::<B, _>(|b| b.input(&input)),
525 None => false,
526 }
527 }
528
529 fn frame(pointer: String) -> String {
530 let pointer = read::<Pointer>(&pointer).unwrap_or_default();
531 with::<B, _>(|b| write(&b.frame(&pointer)))
532 }
533
534 fn panel_event(slot: String, event: String) {
535 let slot = match slot.as_str() {
536 "settings" => PanelSlot::Settings,
537 "transport" => PanelSlot::Transport,
538 "card" => PanelSlot::Card,
539 _ => PanelSlot::Task,
540 };
541 if let Some(event) = read::<PanelEvent>(&event) {
542 with::<B, _>(|b| b.panel_event(slot, event));
543 }
544 }
545
546 fn task_close(accept: bool) -> Option<String> {
547 with::<B, _>(|b| b.task_close(accept))
548 }
549
550 fn menu_items(scope: String) -> String {
551 match read::<MenuScope>(&scope) {
552 Some(scope) => with::<B, _>(|b| write(&b.menu_items(&scope))),
553 None => "[]".into(),
554 }
555 }
556
557 fn menu_command(id: String, scope: String) -> bool {
558 match read::<MenuScope>(&scope) {
559 Some(scope) => with::<B, _>(|b| b.menu_command(&id, &scope)),
560 None => false,
561 }
562 }
563
564 fn delete_feature(id: String) -> bool {
565 with::<B, _>(|b| b.delete_feature(&id))
566 }
567
568 fn settings_panel() -> String {
569 with::<B, _>(|b| write(&b.settings_panel()))
570 }
571
572 fn settings() -> Option<String> {
573 with::<B, _>(|b| b.settings()).map(|v| v.to_string())
574 }
575
576 fn apply_settings(settings: String) {
577 if let Ok(value) = serde_json::from_str(&settings) {
578 with::<B, _>(|b| b.apply_settings(value));
579 }
580 }
581
582 fn suspend() -> Option<Vec<u8>> {
583 with::<B, _>(|b| b.suspend())
584 }
585
586 fn resume(state: Option<Vec<u8>>) {
587 with::<B, _>(|b| b.resume(state));
588 }
589
590 fn job_run(entry: String, input: String) -> Result<String, String> {
591 B::job(&entry, &input)
592 }
593 }
594}
595
596#[macro_export]
598macro_rules! bench {
599 ($bench:ty) => {
600 type __PrintcadBenchExports = $crate::adapter::Exports<$bench>;
601 $crate::bindings::export_workbench!(__PrintcadBenchExports with_types_in $crate::bindings);
602 };
603}