dymokomi/luced-3d
Source of release 0.11.4
0.11.4 / src / overlay_lines.lucb
## Viewport overlay lines gathered in Base: world-space endpoint pairs of
## CAD boundaries, control hulls and normal guides, polygon normal guides,
## and Edit kinds' guides (a sketch plane's grid). The Luce side hands over
## a whole CAD overlay, mesh or grid in one call; the points never pass
## through Luce lists. The worker publishes the lines (ComputeChannel.overlay,
## .hull), and without the worker they become a WireBatch directly.
import interop
import memory
from luce_std import math
from luce_geocore.geocore import Vector3, Matrix4, Bounds, Mesh, invalid, mesh_overlay_points
from luce_geocore.core.growing import Growing
from luce_3d.graphics import WireBatch, wire_batch_type
from luce_cad.model import CadOverlay, CadPreviewSet
from luce_cad.sketch import CadSketch, CadProjection, sketch_samples, projection_samples, projection_per_edge, sketch_trim_piece, sketch_offset_preview
from luce_geocore.geocore import GeometrySet, SceneKind, LightShape, Projection, Camera, Light
from luce_geocore.kernel import SceneObjects, scene_flattened
pub struct OverlayLines:
var points: Growing[Vector3]
pub func init():
self.points = Growing[Vector3]()
## Empty lines, owned by the caller.
pub static func make() -> interop.Reference[OverlayLines]!:
return try interop.Reference[OverlayLines].adopt(new OverlayLines() in memory.heap, overlay_lines_type, memory.heap)
## Segments held.
pub func count() -> i64:
return (i64)self.points.count // 2
## The box around every endpoint (a zero box when there are none).
pub func bounds() -> Bounds:
if self.points.count == 0: return Bounds(Vector3(), Vector3())
var low = self.points.items[0]
var high = low
for point in self.points.view():
low = Vector3(math.min(low.x, point.x), math.min(low.y, point.y), math.min(low.z, point.z))
high = Vector3(math.max(high.x, point.x), math.max(high.y, point.y), math.max(high.z, point.z))
return Bounds(low, high)
## Part `part` of `overlay` (0 its boundaries, 1 its hull, 2 its normal
## guides) placed by `matrix`; a guide keeps its length.
pub func add_cad(overlay: interop.Reference[CadOverlay], part: i64, matrix: Matrix4) -> !:
let source = try overlay.get()
let count = source.boundary_count() if part == 0 else (source.hull_count() if part == 1 else source.guide_count())
try self.points.reserve(self.points.count + (usize)count)
if part == 2:
for at in 0..<count // 2:
let start = try source.guide(at * 2)
let delta = (try source.guide(at * 2 + 1)).subtract(start)
let placed = matrix.transform_point(start)
self.points.items[self.points.count] = placed
self.points.items[self.points.count + 1] = placed.add((try matrix.transform_normal(delta)).multiply_scalar(delta.length()))
self.points.count += 2
return
for at in 0..<count:
let point = (try source.boundary(at)) if part == 0 else (try source.hull_point(at))
self.points.items[self.points.count] = matrix.transform_point(point)
self.points.count += 1
## Part `part` of per-face previews (0 their boundaries, 2 their normal
## guides; they have no hull) placed by `matrix`.
pub func add_preview(previews: interop.Reference[CadPreviewSet], part: i64, matrix: Matrix4) -> !:
let source = try previews.get()
if part == 1: return
let count = source.boundary_count() if part == 0 else source.guide_count()
try self.points.reserve(self.points.count + (usize)count)
for at in 0..<(count if part == 0 else count // 2 * 2):
let point = (try source.boundary(at)) if part == 0 else (try source.guide(at))
if part == 2 and at % 2 == 1:
let start = try source.guide(at - 1)
let delta = point.subtract(start)
self.points.items[self.points.count] = self.points.items[self.points.count - 1].add((try matrix.transform_normal(delta)).multiply_scalar(delta.length()))
else:
self.points.items[self.points.count] = matrix.transform_point(point)
self.points.count += 1
## A normal guide per polygon of `mesh` placed by `matrix`.
pub func add_face_guides(mesh: interop.Reference[Mesh], matrix: Matrix4) -> !:
let guides = try mesh_overlay_points(try mesh.get(), matrix, true)
defer:
if guides.length > 0: free(guides) in memory.heap
for point in guides: try self.points.push(point)
## A square grid on the plane through `origin` spanned by unit axes `u`
## and `v`: `divisions` cells across, `half` units each side of the
## origin (Edit Sketch's plane).
pub func add_grid(origin: Vector3, u: Vector3, v: Vector3, half: f64, divisions: i64) -> !:
if divisions < 1 or divisions > 1000 or not (half > 0.0): error(invalid, "a grid needs 1..1000 divisions and a positive size")
try self.points.reserve(self.points.count + (usize)(divisions + 1) * 4)
for line in 0..<divisions + 1:
let t = -half + 2.0 * half * (f64)line / (f64)divisions
try self.points.push(origin.add(u.multiply_scalar(t)).subtract(v.multiply_scalar(half)))
try self.points.push(origin.add(u.multiply_scalar(t)).add(v.multiply_scalar(half)))
try self.points.push(origin.add(v.multiply_scalar(t)).subtract(u.multiply_scalar(half)))
try self.points.push(origin.add(v.multiply_scalar(t)).add(u.multiply_scalar(half)))
## Sketch `sketch`'s curves on the plane through `origin` with its x
## and y along `u` and `v`: `which` 0 the free ones, 1 the fully
## constrained (after CadSketch.analyze), 2 construction (and control
## point splines' nets), 3 entity `entity` alone (a hovered or selected
## one; a point draws nothing).
pub func add_sketch(sketch: interop.Reference[CadSketch], origin: Vector3, u: Vector3, v: Vector3, which: i64, entity: i64 = -1) -> !:
let s = try sketch.get()
for at in 0..<s.entity_count():
let kind = s.kind(at)
if kind == 0: continue
if which == 2 and kind == 4 and not s.fit(at):
for k in 1..<s.part_count(at):
let a = s.part(at, k - 1)
let b = s.part(at, k)
try self.add_segment(planar(origin, u, v, s.x(a), s.y(a)), planar(origin, u, v, s.x(b), s.y(b)))
if which == 3:
if at != entity: continue
elif which == 2:
if not s.construction(at): continue
elif s.construction(at) or s.fixed(at) != (which == 1):
continue
if kind == 1:
let a = s.part(at, 0)
let b = s.part(at, 1)
try self.add_segment(planar(origin, u, v, s.x(a), s.y(a)), planar(origin, u, v, s.x(b), s.y(b)))
continue
if kind > 3:
# A spline, ellipse, conic or text: its samples joined (a
# text's pieces apart, NaN between them).
var samples = Growing[f64]()
defer samples.close()
try sketch_samples(s, at, 128, &samples)
for k in 0..<samples.count // 2 - 1:
if math.is_nan(samples.items[2 * k]) or math.is_nan(samples.items[2 * k + 2]): continue
try self.add_segment(planar(origin, u, v, samples.items[2 * k], samples.items[2 * k + 1]), planar(origin, u, v, samples.items[2 * k + 2], samples.items[2 * k + 3]))
continue
let center = s.part(at, 0)
let cx = s.x(center)
let cy = s.y(center)
var start = 0.0
var sweep = 2.0 * math.pi
if kind == 3:
let first = s.part(at, 1)
let last = s.part(at, 2)
start = math.atan2(s.y(first) - cy, s.x(first) - cx)
sweep = math.atan2(s.y(last) - cy, s.x(last) - cx) - start
while sweep <= 0.0: sweep += 2.0 * math.pi
try self.add_arc(origin, u, v, cx, cy, s.radius(at), start, sweep)
## The piece Trim would take from `curve` round sketch point (`x`, `y`).
pub func add_trim_piece(sketch: interop.Reference[CadSketch], curve: i64, x: f64, y: f64, origin: Vector3, u: Vector3, v: Vector3) -> !:
var points = Growing[f64]()
defer points.close()
try sketch_trim_piece(try sketch.get(), curve, x, y, &points)
try self.add_plane_runs(points.view(), origin, u, v)
## What Offset would make of `curves` `distance` toward (`x`, `y`).
pub func add_offset_preview(sketch: interop.Reference[CadSketch], curves: const i64[], distance: f64, x: f64, y: f64, origin: Vector3, u: Vector3, v: Vector3) -> !:
var points = Growing[f64]()
defer points.close()
try sketch_offset_preview(try sketch.get(), curves, distance, x, y, &points)
try self.add_plane_runs(points.view(), origin, u, v)
## Plane x, y pairs joined in runs (a NaN pair between runs).
func add_plane_runs(points: const f64[], origin: Vector3, u: Vector3, v: Vector3) -> !:
for k in 0..<points.length // 2 - 1:
if math.is_nan(points[2 * k]) or math.is_nan(points[2 * k + 2]): continue
try self.add_segment(planar(origin, u, v, points[2 * k], points[2 * k + 1]), planar(origin, u, v, points[2 * k + 2], points[2 * k + 3]))
## Project's cast edges on the plane through `origin` (axes `u`, `v`):
## every edge, or edge `edge` alone.
pub func add_projection(projection: interop.Reference[CadProjection], origin: Vector3, u: Vector3, v: Vector3, edge: i64 = -1) -> !:
let p = try projection.get()
let samples = projection_samples(p)
let per = projection_per_edge()
for e in 0..<samples.length // (2 * per):
if edge >= 0 and (i64)e != edge: continue
let run = samples[e * 2 * per..<(e + 1) * 2 * per]
for k in 0..<per - 1:
try self.add_segment(planar(origin, u, v, run[2 * k], run[2 * k + 1]), planar(origin, u, v, run[2 * k + 2], run[2 * k + 3]))
## A segment from `a` to `b`.
pub func add_segment(a: Vector3, b: Vector3) -> !:
try self.points.push(a)
try self.points.push(b)
## An arc on the plane through `origin` (axes `u`, `v`) about plane
## point (`cx`, `cy`) of `radius`, from angle `start` sweeping `sweep`
## radians counterclockwise, in segments of at most 3 degrees.
pub func add_arc(origin: Vector3, u: Vector3, v: Vector3, cx: f64, cy: f64, radius: f64, start: f64, sweep: f64) -> !:
let count = (usize)math.max(1.0, math.min(512.0, math.ceil(math.abs(sweep) / (math.pi / 60.0))))
var previous = planar(origin, u, v, cx + radius * math.cos(start), cy + radius * math.sin(start))
for step in 1..<count + 1:
let angle = start + sweep * (f64)step / (f64)count
let next = planar(origin, u, v, cx + radius * math.cos(angle), cy + radius * math.sin(angle))
try self.add_segment(previous, next)
previous = next
## Every camera and light of `set` (and its instances) as viewport
## helpers: a camera's frustum to one unit ahead with an up marker, a
## light's emitter outline with its direction.
pub func add_scene(set: interop.Reference[GeometrySet]) -> !:
var objects = SceneObjects()
defer objects.close()
try scene_flattened(try set.get(), Matrix4(), &objects)
for index in 0..<objects.count():
let item = objects.object(index)
if item.kind == SceneKind.camera: try self.add_camera(item.camera, item.matrix)
else: try self.add_light(item.light, item.matrix)
func segment(matrix: Matrix4, a: Vector3, b: Vector3) -> !:
try self.points.push(matrix.transform_point(a))
try self.points.push(matrix.transform_point(b))
## The closed outline through `corners`.
func loop(matrix: Matrix4, corners: const Vector3[]) -> !:
for at in 0..<corners.length: try self.segment(matrix, corners[at], corners[(at + 1) % corners.length])
## A circle of `radius` in the plane of unit axes `u` and `v`.
func circle(matrix: Matrix4, center: Vector3, u: Vector3, v: Vector3, radius: f64) -> !:
let steps: i64 = 32
for step in 0..<steps:
let a = 2.0 * math.pi * (f64)step / (f64)steps
let b = 2.0 * math.pi * (f64)(step + 1) / (f64)steps
try self.segment(matrix, center.add(u.multiply_scalar(radius * math.cos(a))).add(v.multiply_scalar(radius * math.sin(a))),
center.add(u.multiply_scalar(radius * math.cos(b))).add(v.multiply_scalar(radius * math.sin(b))))
func add_camera(camera: Camera, matrix: Matrix4) -> !:
# Perspective: the film back seen one unit ahead. Orthographic: the
# apertures in tenths of a unit (USD's convention), one unit deep.
let perspective = camera.projection == Projection.perspective
let w = 0.5 * camera.horizontal_aperture / camera.focal_length if perspective else 0.05 * camera.horizontal_aperture
let h = 0.5 * camera.vertical_aperture / camera.focal_length if perspective else 0.05 * camera.vertical_aperture
let far: Vector3[4] = [Vector3(-w, -h, -1.0), Vector3(w, -h, -1.0), Vector3(w, h, -1.0), Vector3(-w, h, -1.0)]
try self.loop(matrix, far)
if perspective:
for corner in far: try self.segment(matrix, Vector3(), corner)
else:
let near: Vector3[4] = [Vector3(-w, -h, 0.0), Vector3(w, -h, 0.0), Vector3(w, h, 0.0), Vector3(-w, h, 0.0)]
try self.loop(matrix, near)
for at in 0..<(usize)4: try self.segment(matrix, near[at], far[at])
let up: Vector3[3] = [Vector3(-0.5 * w, h * 1.1, -1.0), Vector3(0.5 * w, h * 1.1, -1.0), Vector3(0.0, h * 1.5, -1.0)]
try self.loop(matrix, up)
func add_light(light: Light, matrix: Matrix4) -> !:
let x = Vector3(1.0, 0.0, 0.0)
let y = Vector3(0.0, 1.0, 0.0)
let z = Vector3(0.0, 0.0, 1.0)
var reach: f64 = 0.5
if light.shape == LightShape.rect:
let w = 0.5 * light.width
let h = 0.5 * light.height
let corners: Vector3[4] = [Vector3(-w, -h, 0.0), Vector3(w, -h, 0.0), Vector3(w, h, 0.0), Vector3(-w, h, 0.0)]
try self.loop(matrix, corners)
try self.segment(matrix, corners[0], corners[2])
try self.segment(matrix, corners[1], corners[3])
reach = math.max(0.25, math.max(w, h))
elif light.shape == LightShape.disk:
try self.circle(matrix, Vector3(), x, y, light.radius)
reach = math.max(0.25, light.radius)
elif light.shape == LightShape.sphere:
try self.circle(matrix, Vector3(), x, y, light.radius)
try self.circle(matrix, Vector3(), y, z, light.radius)
try self.circle(matrix, Vector3(), z, x, light.radius)
reach = math.max(0.25, light.radius)
else:
# Distant: three parallel rays with an arrowhead on the middle one.
for offset in [-0.2, 0.0, 0.2]: try self.segment(matrix, Vector3(offset, 0.0, 0.0), Vector3(offset, 0.0, -1.0))
try self.segment(matrix, Vector3(0.0, 0.0, -1.0), Vector3(-0.08, 0.0, -0.85))
try self.segment(matrix, Vector3(0.0, 0.0, -1.0), Vector3(0.08, 0.0, -0.85))
return
# Which way it shines: down its local -Z.
try self.segment(matrix, Vector3(), Vector3(0.0, 0.0, -reach))
## A GPU batch of the segments.
pub func batch() -> interop.Reference[WireBatch]!:
return try interop.Reference[WireBatch].adopt(try new WireBatch(self.points.view()) in memory.heap, wire_batch_type, memory.heap)
pub func close():
self.points.close()
## The endpoints of `lines`, for Base consumers (the worker channel).
pub func line_points(lines: const OverlayLines*) -> const Vector3[]:
return lines.points.view()
pub let overlay_lines_type: interop.Type[OverlayLines] = interop.Type[OverlayLines]("OverlayLines", OverlayLines.close, closeable = true)
## Plane coordinates (`x`, `y`) on the plane through `origin` with axes
## `u` and `v`, as a world point.
func planar(origin: Vector3, u: Vector3, v: Vector3, x: f64, y: f64) -> Vector3:
return origin.add(u.multiply_scalar(x)).add(v.multiply_scalar(y))