ombre: Add native vector support to lisp

27db789760bfbb4ea4f92d6b94801c00e42df489
Alexis Sellier committed ago 1 parent 720a0307
ombre/src/lisp/evaluator.rs +229 -1
8 8
use std::{fmt, fs, iter, result};
9 9
10 10
use crate::gfx::Rgba8;
11 11
use crate::lisp::dynamic::{Dynamic, IsDynamic};
12 12
use crate::lisp::list::List;
13 +
use crate::math::{Vector2D, Vector3D, Vector4D};
13 14
14 15
use super::{Parser, Scanner, FILE_EXTENSION};
15 16
16 17
/// Result type for all functions.
17 18
pub type Result<T, E = Error> = result::Result<T, E>;
161 162
    Bool(bool),
162 163
    /// Eg. 'fnord
163 164
    Quoted(Box<Expr>),
164 165
    /// Eg. [1 2 3]
165 166
    Vector(Vec<Expr>),
167 +
    /// Eg. (vec2 x y)
168 +
    Vector2D(Vector2D<f64>),
169 +
    /// Eg. (vec3 x y z)
170 +
    Vector3D(Vector3D<f64>),
171 +
    /// Eg. (vec4 x y z w)
172 +
    Vector4D(Vector4D<f64>),
166 173
    /// Eg. (dict {:a 1 :b 2 :c 3})
167 174
    Dict(HashMap<Key, Expr>),
168 175
    /// Eg. fnord
169 176
    Symbol(Symbol),
170 177
    /// Eg. :yikes
304 311
            _ => Err(expr),
305 312
        }
306 313
    }
307 314
}
308 315
316 +
impl TryFrom<Expr> for Vector2D<f64> {
317 +
    type Error = Expr;
318 +
    fn try_from(expr: Expr) -> Result<Self, Self::Error> {
319 +
        match expr {
320 +
            Expr::Vector2D(v) => Ok(v),
321 +
            _ => Err(expr),
322 +
        }
323 +
    }
324 +
}
325 +
326 +
impl From<Vector2D<f64>> for Expr {
327 +
    fn from(v: Vector2D<f64>) -> Self {
328 +
        Expr::Vector2D(v)
329 +
    }
330 +
}
331 +
332 +
impl TryFrom<Expr> for Vector3D<f64> {
333 +
    type Error = Expr;
334 +
    fn try_from(expr: Expr) -> Result<Self, Self::Error> {
335 +
        match expr {
336 +
            Expr::Vector3D(v) => Ok(v),
337 +
            _ => Err(expr),
338 +
        }
339 +
    }
340 +
}
341 +
342 +
impl From<Vector3D<f64>> for Expr {
343 +
    fn from(v: Vector3D<f64>) -> Self {
344 +
        Expr::Vector3D(v)
345 +
    }
346 +
}
347 +
348 +
impl TryFrom<Expr> for Vector4D<f64> {
349 +
    type Error = Expr;
350 +
    fn try_from(expr: Expr) -> Result<Self, Self::Error> {
351 +
        match expr {
352 +
            Expr::Vector4D(v) => Ok(v),
353 +
            _ => Err(expr),
354 +
        }
355 +
    }
356 +
}
357 +
358 +
impl From<Vector4D<f64>> for Expr {
359 +
    fn from(v: Vector4D<f64>) -> Self {
360 +
        Expr::Vector4D(v)
361 +
    }
362 +
}
363 +
309 364
impl fmt::Display for Expr {
310 365
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
311 366
        match self {
312 367
            Expr::List(list) => {
313 368
                write!(f, "(")?;
331 386
                        write!(f, " {item}")?;
332 387
                    }
333 388
                }
334 389
                write!(f, "]")
335 390
            }
391 +
            Expr::Vector2D(v) => write!(f, "[{} {}]", v.x, v.y),
392 +
            Expr::Vector3D(v) => write!(f, "[{} {} {}]", v.x, v.y, v.z),
393 +
            Expr::Vector4D(v) => write!(f, "[{} {} {} {}]", v.x, v.y, v.z, v.w),
336 394
            Expr::Dict(d) => {
337 395
                write!(f, "{{")?;
338 396
                let mut iter = d.iter();
339 397
                if let Some((k, v)) = iter.next() {
340 398
                    write!(f, "{k} {v}")?;
807 865
        env.intrinsic(
808 866
            "modify!",
809 867
            "Modify a mutable reference in-place using a lambda",
810 868
            intrinsic::modify,
811 869
        );
870 +
        env.intrinsic(
871 +
            "vec2",
872 +
            "Create a 2D vector from x,y components",
873 +
            intrinsic::vec2,
874 +
        );
875 +
        env.intrinsic(
876 +
            "vec3",
877 +
            "Create a 3D vector from x,y,z components",
878 +
            intrinsic::vec3,
879 +
        );
880 +
        env.intrinsic(
881 +
            "vec4",
882 +
            "Create a 4D vector from x,y,z,w components",
883 +
            intrinsic::vec4,
884 +
        );
812 885
        env
813 886
    }
814 887
}
815 888
816 889
/// Iterator over syntax tree which returns evaluated expressions.
1103 1176
        Expr::Vector(v) => v
1104 1177
            .into_iter()
1105 1178
            .map(|e| eval(e, env))
1106 1179
            .collect::<Result<Vec<_>>>()
1107 1180
            .map(Expr::Vector),
1181 +
        Expr::Vector2D(v) => Ok(Expr::Vector2D(v)),
1182 +
        Expr::Vector3D(v) => Ok(Expr::Vector3D(v)),
1183 +
        Expr::Vector4D(v) => Ok(Expr::Vector4D(v)),
1108 1184
        Expr::Dict(d) => d
1109 1185
            .into_iter()
1110 1186
            .map(|(k, v)| eval(v, env).map(|v| (k, v)))
1111 1187
            .collect::<Result<HashMap<_, _>>>()
1112 1188
            .map(Expr::Dict),
1536 1612
        Ok(Expr::Bool(args.all(|a| a == head)))
1537 1613
    }
1538 1614
1539 1615
    /// Addition (+).
1540 1616
    pub fn add(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> {
1541 -
        fold(args, 0, |acc, n| acc + n)
1617 +
        let mut args = args.into_iter();
1618 +
        match args.next() {
1619 +
            Some(Expr::Vector2D(v)) => fold(args, v, |acc, v| acc + v),
1620 +
            Some(Expr::Vector3D(v)) => fold(args, v, |acc, v| acc + v),
1621 +
            Some(Expr::Vector4D(v)) => fold(args, v, |acc, v| acc + v),
1622 +
            Some(first) => fold(iter::once(first).chain(args), 0, |acc, n| acc + n),
1623 +
            None => Ok(Expr::Integer(0)),
1624 +
        }
1542 1625
    }
1543 1626
1544 1627
    /// Multiplication (*).
1545 1628
    pub fn mul(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> {
1546 1629
        fold(args, 1, |acc, n| acc * n)
1584 1667
                if args.peek().is_none() {
1585 1668
                    return Ok(Expr::Integer(-n));
1586 1669
                }
1587 1670
                fold(args, n, |acc, n| acc - n)
1588 1671
            }
1672 +
            Some(Expr::Vector2D(v)) => {
1673 +
                if args.peek().is_none() {
1674 +
                    return Ok(Expr::Vector2D(-v));
1675 +
                }
1676 +
                args.try_fold(v, |acc, v| match v {
1677 +
                    Expr::Vector2D(v) => Ok(acc - v),
1678 +
                    _ => Err(Error::ExpectedValue("vec2")),
1679 +
                })
1680 +
                .map(Expr::Vector2D)
1681 +
            }
1682 +
            Some(Expr::Vector3D(v)) => {
1683 +
                if args.peek().is_none() {
1684 +
                    return Ok(Expr::Vector3D(-v));
1685 +
                }
1686 +
                args.try_fold(v, |acc, v| match v {
1687 +
                    Expr::Vector3D(v) => Ok(acc - v),
1688 +
                    _ => Err(Error::ExpectedValue("vec3")),
1689 +
                })
1690 +
                .map(Expr::Vector3D)
1691 +
            }
1692 +
            Some(Expr::Vector4D(v)) => {
1693 +
                if args.peek().is_none() {
1694 +
                    return Ok(Expr::Vector4D(-v));
1695 +
                }
1696 +
                args.try_fold(v, |acc, v| match v {
1697 +
                    Expr::Vector4D(v) => Ok(acc - v),
1698 +
                    _ => Err(Error::ExpectedValue("vec4")),
1699 +
                })
1700 +
                .map(Expr::Vector4D)
1701 +
            }
1589 1702
            Some(v) => Err(Error::UnexpectedValue(v)),
1590 1703
            None => Err(Error::WrongArgumentCount {
1591 1704
                expected: 1,
1592 1705
                actual: args.len(),
1593 1706
            }),
1744 1857
                Ok(opf(a, b))
1745 1858
            }
1746 1859
            _ => Err(Error::ExpectedValue("number")),
1747 1860
        }
1748 1861
    }
1862 +
1863 +
    /// Create a 2D vector.
1864 +
    pub fn vec2(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> {
1865 +
        let arity = args.len();
1866 +
        let Ok([x, y]) = <[_; 2]>::try_from(args) else {
1867 +
            return Err(Error::WrongArgumentCount {
1868 +
                expected: 2,
1869 +
                actual: arity,
1870 +
            });
1871 +
        };
1872 +
        let x = match x {
1873 +
            Expr::Float(n) => n,
1874 +
            Expr::Integer(n) => n as f64,
1875 +
            _ => return Err(Error::ExpectedValue("number")),
1876 +
        };
1877 +
        let y = match y {
1878 +
            Expr::Float(n) => n,
1879 +
            Expr::Integer(n) => n as f64,
1880 +
            _ => return Err(Error::ExpectedValue("number")),
1881 +
        };
1882 +
        Ok(Expr::Vector2D(Vector2D::new(x, y)))
1883 +
    }
1884 +
1885 +
    /// Create a 3D vector.
1886 +
    pub fn vec3(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> {
1887 +
        let arity = args.len();
1888 +
        let Ok([x, y, z]) = <[_; 3]>::try_from(args) else {
1889 +
            return Err(Error::WrongArgumentCount {
1890 +
                expected: 3,
1891 +
                actual: arity,
1892 +
            });
1893 +
        };
1894 +
        let x = match x {
1895 +
            Expr::Float(n) => n,
1896 +
            Expr::Integer(n) => n as f64,
1897 +
            _ => return Err(Error::ExpectedValue("number")),
1898 +
        };
1899 +
        let y = match y {
1900 +
            Expr::Float(n) => n,
1901 +
            Expr::Integer(n) => n as f64,
1902 +
            _ => return Err(Error::ExpectedValue("number")),
1903 +
        };
1904 +
        let z = match z {
1905 +
            Expr::Float(n) => n,
1906 +
            Expr::Integer(n) => n as f64,
1907 +
            _ => return Err(Error::ExpectedValue("number")),
1908 +
        };
1909 +
        Ok(Expr::Vector3D(Vector3D::new(x, y, z)))
1910 +
    }
1911 +
1912 +
    /// Create a 4D vector.
1913 +
    pub fn vec4(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> {
1914 +
        let arity = args.len();
1915 +
        let Ok([x, y, z, w]) = <[_; 4]>::try_from(args) else {
1916 +
            return Err(Error::WrongArgumentCount {
1917 +
                expected: 4,
1918 +
                actual: arity,
1919 +
            });
1920 +
        };
1921 +
        let x = match x {
1922 +
            Expr::Float(n) => n,
1923 +
            Expr::Integer(n) => n as f64,
1924 +
            _ => return Err(Error::ExpectedValue("number")),
1925 +
        };
1926 +
        let y = match y {
1927 +
            Expr::Float(n) => n,
1928 +
            Expr::Integer(n) => n as f64,
1929 +
            _ => return Err(Error::ExpectedValue("number")),
1930 +
        };
1931 +
        let z = match z {
1932 +
            Expr::Float(n) => n,
1933 +
            Expr::Integer(n) => n as f64,
1934 +
            _ => return Err(Error::ExpectedValue("number")),
1935 +
        };
1936 +
        let w = match w {
1937 +
            Expr::Float(n) => n,
1938 +
            Expr::Integer(n) => n as f64,
1939 +
            _ => return Err(Error::ExpectedValue("number")),
1940 +
        };
1941 +
        Ok(Expr::Vector4D(Vector4D::new(x, y, z, w)))
1942 +
    }
1749 1943
}
1750 1944
1751 1945
#[cfg(test)]
1752 1946
#[allow(clippy::unwrap_used)]
1753 1947
mod tests {
2432 2626
            Expr::Str("world".to_owned()),
2433 2627
        );
2434 2628
        expect(&["(def d (dict [:x 1]))", "(:y d)"], Expr::nil());
2435 2629
    }
2436 2630
2631 +
    #[test]
2632 +
    fn test_vectors() {
2633 +
        expect(&["(vec2 1 2)"], Expr::Vector2D(Vector2D::new(1.0, 2.0)));
2634 +
        expect(
2635 +
            &["(vec3 1.5 2 3.4)"],
2636 +
            Expr::Vector3D(Vector3D::new(1.5, 2.0, 3.4)),
2637 +
        );
2638 +
        expect(
2639 +
            &["(vec4 1 2 3 4)"],
2640 +
            Expr::Vector4D(Vector4D::new(1.0, 2.0, 3.0, 4.0)),
2641 +
        );
2642 +
        expect_err(
2643 +
            &["(vec2 1)"],
2644 +
            Error::WrongArgumentCount {
2645 +
                expected: 2,
2646 +
                actual: 1,
2647 +
            },
2648 +
        );
2649 +
        expect_err(&["(vec2 :x 1)"], Error::ExpectedValue("number"));
2650 +
    }
2651 +
2652 +
    #[test]
2653 +
    fn test_vector_math() {
2654 +
        expect(&["(- (vec2 1 2))"], Expr::Vector2D(Vector2D::new(-1., -2.)));
2655 +
        expect(
2656 +
            &["(- (vec2 2 2) (vec2 1 2))"],
2657 +
            Expr::Vector2D(Vector2D::new(1., 0.)),
2658 +
        );
2659 +
        expect(
2660 +
            &["(+ (vec2 1 2) (vec2 3 4) (vec2 1 1))"],
2661 +
            Expr::Vector2D(Vector2D::new(5., 7.)),
2662 +
        );
2663 +
    }
2664 +
2437 2665
    #[test]
2438 2666
    #[ignore = "not implemented yet"]
2439 2667
    fn test_modules_nested() {
2440 2668
        expect(
2441 2669
            &[
ombre/src/math/algebra.rs +54 -1
5 5
// Most of the code in this module was borrowed from the `cgmath` crate.
6 6
7 7
//! Linear algebra types and functions.
8 8
use std::fmt;
9 9
use std::marker::PhantomData;
10 -
use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Sub, SubAssign};
10 +
use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign};
11 11
12 12
use super::rect::Rect;
13 13
use super::size::Size;
14 14
use super::transform::{coord::Spherical, Transform2D};
15 15
use super::{traits::*, World};
299 299
    fn from(other: Vector3D<S, U>) -> Self {
300 300
        Vector2D::new(other.x, other.y)
301 301
    }
302 302
}
303 303
304 +
impl<S: Neg<Output = S>, U> Neg for Vector2D<S, U> {
305 +
    type Output = Self;
306 +
307 +
    fn neg(self) -> Self {
308 +
        Self {
309 +
            x: -self.x,
310 +
            y: -self.y,
311 +
            unit: PhantomData,
312 +
        }
313 +
    }
314 +
}
315 +
304 316
impl<S, U> Add for Vector2D<S, U>
305 317
where
306 318
    S: Add<Output = S>,
307 319
{
308 320
    type Output = Self;
390 402
    pub y: S,
391 403
    pub z: S,
392 404
    pub unit: PhantomData<U>,
393 405
}
394 406
407 +
impl<S: Copy, U> Vector3D<S, U> {
408 +
    /// Creates a vector with all elements set to `v`.
409 +
    pub fn splat(n: S) -> Self {
410 +
        Self::new(n, n, n)
411 +
    }
412 +
}
413 +
395 414
impl<S: Copy, U> Copy for Vector3D<S, U> {}
396 415
397 416
impl<S: Clone, U> Clone for Vector3D<S, U> {
398 417
    fn clone(&self) -> Self {
399 418
        Vector3D {
563 582
    fn from(array: [T; 3]) -> Self {
564 583
        Vector3D::new(array[0], array[1], array[2])
565 584
    }
566 585
}
567 586
587 +
impl<S: Neg<Output = S>, U> Neg for Vector3D<S, U> {
588 +
    type Output = Self;
589 +
590 +
    fn neg(self) -> Self {
591 +
        Self {
592 +
            x: -self.x,
593 +
            y: -self.y,
594 +
            z: -self.z,
595 +
            unit: PhantomData,
596 +
        }
597 +
    }
598 +
}
599 +
568 600
impl<S, U> Add<Vector3D<S, U>> for Vector3D<S, U>
569 601
where
570 602
    S: Add<Output = S> + Copy,
571 603
{
572 604
    type Output = Self;
623 655
    pub w: S,
624 656
625 657
    unit: PhantomData<U>,
626 658
}
627 659
660 +
impl<S: Copy, U> Vector4D<S, U> {
661 +
    /// Creates a vector with all elements set to `v`.
662 +
    pub fn splat(n: S) -> Self {
663 +
        Self::new(n, n, n, n)
664 +
    }
665 +
}
666 +
628 667
impl From<Vector4D<f32>> for [f32; 4] {
629 668
    fn from(mat: Vector4D<f32>) -> Self {
630 669
        unsafe { std::mem::transmute(mat) }
631 670
    }
632 671
}
649 688
            unit: PhantomData,
650 689
        }
651 690
    }
652 691
}
653 692
693 +
impl<S: Neg<Output = S>, U> Neg for Vector4D<S, U> {
694 +
    type Output = Self;
695 +
696 +
    fn neg(self) -> Self {
697 +
        Self {
698 +
            x: -self.x,
699 +
            y: -self.y,
700 +
            z: -self.z,
701 +
            w: -self.w,
702 +
            unit: PhantomData,
703 +
        }
704 +
    }
705 +
}
706 +
654 707
impl<S, U> Mul<S> for Vector4D<S, U>
655 708
where
656 709
    S: Mul<Output = S> + Copy,
657 710
{
658 711
    type Output = Self;