Luce packages
LuceLuce BaseLuciaOS

dymokomi/luced-3d

Source of release 0.11.1

0.11.1 / src / gizmo_math.luc

## Camera-ray constraints shared by node gizmos; no geometry evaluation here.
from luce_3d.graphics import Vector3
from workspace import Workspace
from luce_std import math

pub func axis(index: int) -> Vector3:
    return Vector3(1.0 if index == 0 else 0.0, 1.0 if index == 1 else 0.0, 1.0 if index == 2 else 0.0)

pub func project(w: Workspace, p: Vector3, width: float, height: float) -> list[float]!:
    let lens = w.view.camera.projection(math.max(1.0, width) / math.max(1.0, height))
    let d = p.subtract(lens.position)
    let z = -d.dot(lens.backward)
    return [(d.dot(lens.right) * lens.focal / lens.aspect / math.max(z, lens.near) + 1.0) * width * 0.5,
            (1.0 - d.dot(lens.up) * lens.focal / math.max(z, lens.near)) * height * 0.5, z - lens.near]

## The view ray's direction through (x, y), not normalized.
pub func ray(w: Workspace, x: float, y: float, width: float, height: float) -> Vector3!:
    let lens = w.view.camera.projection(math.max(1.0, width) / math.max(1.0, height))
    return lens.right.multiply_scalar((x / width * 2.0 - 1.0) * lens.aspect / lens.focal).add(lens.up.multiply_scalar((1.0 - y / height * 2.0) / lens.focal)).subtract(lens.backward)

pub func plane(w: Workspace, x: float, y: float, width: float, height: float, center: Vector3, normal: Vector3) -> Vector3!:
    let lens = w.view.camera.projection(math.max(1.0, width) / math.max(1.0, height))
    let direction = ray(w, x, y, width, height)
    let denominator = direction.dot(normal)
    if math.abs(denominator) < 0.000001:
        return center
    return lens.position.add(direction.multiply_scalar(center.subtract(lens.position).dot(normal) / denominator))

pub func distance(x: float, y: float, a: list[float], b: list[float]) -> float:
    let dx = b[0] - a[0]
    let dy = b[1] - a[1]
    let t = math.clamp(((x - a[0]) * dx + (y - a[1]) * dy) / math.max(0.000001, dx * dx + dy * dy), 0.0, 1.0)
    return math.hypot(x - a[0] - t * dx, y - a[1] - t * dy)

pub func inside(x: float, y: float, points: list[list[float]]) -> bool:
    var sign = 0.0
    for at in 0..<points.length:
        let a = points[at]
        let b = points[(at + 1) % points.length]
        let cross = (b[0] - a[0]) * (y - a[1]) - (b[1] - a[1]) * (x - a[0])
        if math.abs(cross) < 0.00001:
            continue
        if sign * cross < 0.0:
            return false
        sign = cross
    return math.abs(sign) > 0.00001

pub func snapped(value: float, step: float, enabled: bool) -> float:
    return math.round(value / step) * step if enabled else value