dymokomi/luce-cad
Source of release 0.9.1
0.9.1 / src / sphere_chart.lucb
## A sphere's authored poles are not geometric singularities. Small trimmed
## regions can use a rotated angular chart without changing their support.
from luce_std import math
from luce_geocore.geocore import Vector3, invalid
from brep_types import Surface
## Longitude is undefined at either authored pole; a numerically simple UV
## polygon there can still lift to inverted triangles, so do not wait for it
## to fail ear clipping before choosing a nonsingular chart.
pub func touches_pole(s: Surface, points: const Vector3[], ids: const i64[]) -> bool:
for id in ids:
let p = points[(usize)id].subtract(s.origin)
if p.subtract(s.z.multiply_scalar(p.dot(s.z))).length() <= s.radius*1e-8: return true
return false
## Keep the entire sampled trim inside one open chart hemisphere. This avoids
## the artificial longitude jump at an authored pole, not a real trim crossing.
pub func local_sphere(s: Surface, points: const Vector3[], ids: const i64[]) -> Surface!:
var direction = Vector3()
for id in ids: direction = direction.add(points[(usize)id].subtract(s.origin).multiply_scalar(1.0/s.radius))
if direction.length() < 1e-12: error(invalid,"spherical trim requires multiple charts")
var x = try direction.normalized()
if not contains(s,points,ids,x):
# A sample average is density-weighted: a long sampled arc or retraced
# seam can point it away from a short side of a valid spherical patch.
# Move a convex combination toward its nearest point to the origin.
# Its minimum-dot support point supplies a separating cap direction.
# Every accepted result still passes the same full hemisphere margin;
# no tolerance, trim vertex or support geometry changes here.
var closest = direction.multiply_scalar(1.0/(f64)ids.length)
var found = false
for iteration in 0..<256:
var worst = Vector3()
var dot: f64 = 1e100
for id in ids:
let p = points[(usize)id].subtract(s.origin).multiply_scalar(1.0/s.radius)
let value = p.dot(closest)
if value < dot:
dot = value
worst = p
let delta = worst.subtract(closest)
let squared = delta.dot(delta)
if squared <= 1e-30: break
let fraction = math.clamp(-closest.dot(delta)/squared,0.0,1.0)
if fraction == 0.0: break
closest = closest.add(delta.multiply_scalar(fraction))
if closest.length() < 1e-12: break
x = try closest.normalized()
if contains(s,points,ids,x):
found = true
break
if not found: error(invalid,"spherical trim does not fit one local hemisphere")
let reference = s.z if math.abs(s.z.dot(x)) < 0.9 else s.y
let z = try reference.subtract(x.multiply_scalar(reference.dot(x))).normalized()
var controls: Vector3[]
var numbers: f64[]
return try Surface(4,s.origin,x,z,s.radius,0.0,controls,numbers,numbers,numbers,0,0,0,0)
func contains(s: Surface, points: const Vector3[], ids: const i64[], direction: Vector3) -> bool:
for id in ids:
if points[(usize)id].subtract(s.origin).dot(direction) <= s.radius*0.05: return false
return true