kcl_lib/std/
polar.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
//! Functions related to polar coordinates.

use anyhow::Result;
use derive_docs::stdlib;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

use crate::{
    errors::KclError,
    executor::{ExecState, KclValue},
    std::Args,
};

/// Data for polar coordinates.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, ts_rs::TS, JsonSchema)]
#[ts(export)]
#[serde(rename_all = "camelCase")]
pub struct PolarCoordsData {
    /// The angle of the line (in degrees).
    pub angle: f64,
    /// The length of the line.
    pub length: f64,
}

/// Convert from polar/sphere coordinates to cartesian coordinates.
pub async fn polar(_exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
    let data: PolarCoordsData = args.get_data()?;
    let result = inner_polar(&data)?;

    args.make_user_val_from_f64_array(result.to_vec())
}

/// Convert polar/sphere (azimuth, elevation, distance) coordinates to
/// cartesian (x/y/z grid) coordinates.
///
/// ```no_run
/// const exampleSketch = startSketchOn('XZ')
///   |> startProfileAt([0, 0], %)
///   |> line(polar({angle: 30, length: 5}), %, $thing)
///   |> line([0, 5], %)
///   |> line([segEndX(thing), 0], %)
///   |> line([-20, 10], %)
///   |> close(%)
///  
/// const example = extrude(5, exampleSketch)
/// ```
#[stdlib {
    name = "polar",
}]
fn inner_polar(data: &PolarCoordsData) -> Result<[f64; 2], KclError> {
    let angle = data.angle.to_radians();
    let x = data.length * angle.cos();
    let y = data.length * angle.sin();
    Ok([x, y])
}