Skip to content

Commit fed517f

Browse files
committed
impl len and distance
Signed-off-by: sagudev <[email protected]>
1 parent 627f1f2 commit fed517f

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

naga/src/proc/constant_evaluator.rs

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1572,6 +1572,57 @@ impl<'a> ConstantEvaluator<'a> {
15721572
Err(ConstantEvaluatorError::InvalidMathArg)
15731573
}
15741574
}
1575+
crate::MathFunction::Length => {
1576+
let e1 = LiteralVector::from_expr(arg, self, span, true)?;
1577+
1578+
fn float_length<F, const CAP: usize>(e: ArrayVec<F, CAP>) -> F
1579+
where
1580+
F: std::ops::Mul<F>,
1581+
F: num_traits::Float + std::iter::Sum,
1582+
{
1583+
e.iter().map(|&ei| ei * ei).sum::<F>().sqrt()
1584+
}
1585+
1586+
LiteralVector::from_literal(match e1 {
1587+
LiteralVector::AbstractFloat(a) => Literal::AbstractFloat(float_length(a)),
1588+
LiteralVector::F32(a) => Literal::F32(float_length(a)),
1589+
_ => return Err(ConstantEvaluatorError::InvalidMathArg),
1590+
})
1591+
.handle(self, span)
1592+
}
1593+
crate::MathFunction::Distance => {
1594+
let e1 = LiteralVector::from_expr(arg, self, span, true)?;
1595+
let e2 = LiteralVector::from_expr(arg1.unwrap(), self, span, true)?;
1596+
if e1.len() != e2.len() {
1597+
return Err(ConstantEvaluatorError::InvalidMathArg);
1598+
}
1599+
1600+
fn float_distance<F, const CAP: usize>(
1601+
a: ArrayVec<F, CAP>,
1602+
b: ArrayVec<F, CAP>,
1603+
) -> F
1604+
where
1605+
F: std::ops::Mul<F>,
1606+
F: num_traits::Float + std::iter::Sum + std::ops::Sub,
1607+
{
1608+
a.iter()
1609+
.zip(b.iter())
1610+
.map(|(&aa, &bb)| aa - bb)
1611+
.map(|ei| ei * ei)
1612+
.sum::<F>()
1613+
.sqrt()
1614+
}
1615+
LiteralVector::from_literal(match (e1, e2) {
1616+
(LiteralVector::AbstractFloat(a), LiteralVector::AbstractFloat(b)) => {
1617+
Literal::AbstractFloat(float_distance(a, b))
1618+
}
1619+
(LiteralVector::F32(a), LiteralVector::F32(b)) => {
1620+
Literal::F32(float_distance(a, b))
1621+
}
1622+
_ => return Err(ConstantEvaluatorError::InvalidMathArg),
1623+
})
1624+
.handle(self, span)
1625+
}
15751626
// computational
15761627
crate::MathFunction::Sign => {
15771628
component_wise_signed!(self, span, [arg], |e| { Ok([e.signum()]) })

0 commit comments

Comments
 (0)