dymokomi/luced-3d
Source of release 0.11.4
0.11.4 / tests / examples / scripts.luc
# Example scenes for the Script node (Houdini's Python SOP, in Luce Base):
# each is built as a user would, every Script node must build and cook
# without an error, and the scene is saved to examples/scripts/.
from luce_std import files, paths, process, math
from workspace import Workspace
import node_commands
import script_node
import project_file
from luce_ui import ui
## A scene of one displayed Script node (after `input` when given).
class ScriptScene:
let w: Workspace
let name: str
func init(self, name: str, folder: str) -> unit!:
self.name = name
self.w = Workspace()
self.w.network.folder = folder
node_commands.delete_selected(self.w)
## A Script node with `code` and `packages`; its id.
func script(self, code: str, packages: str = "", y: float = 0.0) -> int!:
node_commands.add_node(self.w, "Script", 0.0, y)
let id = self.w.network.selected
if packages != "":
script_node.set_packages(self.w, id, packages)
script_node.set_code(self.w, id, code)
let node = self.w.network.require(id)
if node.failure != "":
error(ui.invalid, f"{self.name}: {node.failure}")
return id
## Display the last node, frame it and save.
func save(self, folder: str) -> unit!:
let last = self.w.network.selected
for node in self.w.network.nodes:
node.output = 1 if node.id == last else -1
node_commands.display_selected(self.w)
self.w.view.yaw = 0.7
self.w.view.pitch = 0.55
self.w.frame_cube()
for node in self.w.network.nodes:
if node.failure != "":
error(ui.invalid, f"{self.name}: {node.name}: {node.failure}")
project_file.save(paths.join(folder, self.name + ".prisma"), self.w, [1.0, 0.0, 0.0])
## Build every Script example into `folder` (examples/scripts); how many.
pub func script_examples(folder: str) -> int!:
# Script builds take luce-geocore and the packages from this checkout's
# siblings.
let root = paths.directory(paths.directory(folder))
process.set_variable("LUCED_GEOCORE", paths.join(paths.directory(root), "luce-geocore"))
files.ensure_directory(folder)
var count = 0
for build in [jpeg_heightfield, csv_points, lsystem_tree, verb_chain, galaxy_fog]:
build(folder)
count += 1
return count
## A JPEG as a colored height field: luce-image reads the file named by a
## file parameter (relative to the project), a grid rises with each pixel's
## brightness and takes its color.
func jpeg_heightfield(folder: str) -> unit!:
let s = ScriptScene("jpeg_heightfield", folder)
let id = s.script("## A JPEG as a colored height field (luce-image reads it).\nfrom luce_geocore.script import Cook, Geometry\nfrom luce_image.image import Image\n\npub func cook(k: Cook*) -> !:\n let path = k.file(\"image\", \"heightfield.jpg\")\n let divisions = k.i32(\"divisions\", 160)\n let height = k.f32(\"height\", 0.5)\n let opened = try Image.open(path)\n defer opened.release()\n let image = try opened.get()\n let w = try image.width()\n let h = try image.height()\n let size: f32 = 4.0\n var grid = try Geometry.grid(size = (f64)size, divisions = (i64)divisions)\n let positions = try grid.positions()\n let colors = try grid.point_vec3s(\"Cd\")\n for i in 0..<positions.length:\n # The grid spans -size/2..size/2 in X and Z: the pixel under the point.\n let u = (usize)(fit(positions[i].x / size + 0.5) * (f32)(w - 1))\n let v = (usize)(fit(positions[i].z / size + 0.5) * (f32)(h - 1))\n let r = (f32)(try image.get_sample(u, v, 0)) / 255.0\n let g = (f32)(try image.get_sample(u, v, 1)) / 255.0\n let b = (f32)(try image.get_sample(u, v, 2)) / 255.0\n positions[i].y = (0.2126 * r + 0.7152 * g + 0.0722 * b) * height\n colors[i].x = r\n colors[i].y = g\n colors[i].z = b\n print(f\"{w} x {h} pixels onto {positions.length} points\")\n try k.set_geometry(grid)\n\n## `t` held to 0..1.\nfunc fit(t: f32) -> f32:\n return 0.0 if t < 0.0 else (1.0 if t > 1.0 else t)\n", "luce-image")
let node = s.w.network.require(id)
assert(node.console.contains("480 x 360 pixels"))
assert((s.w.geometry else trap("geometry")).point_count() == 161 * 161)
s.save(folder)
## A CSV file of x, y, z and mass after a header, as a point cloud: luce-std
## reads the file, Base's strings split it, each row adds a point with a mass,
## a size and a color.
func csv_points(folder: str) -> unit!:
let rows: list[str] = ["x,y,z,mass"]
for i in 0..<400:
let t = float(i) * 0.05
rows.append(f"{math.cos(t * 3.0) * (1.0 + t * 0.1)},{t * 0.15},{math.sin(t * 3.0) * (1.0 + t * 0.1)},{0.5 + 0.5 * math.sin(t * 7.0)}")
files.write_text(paths.join(folder, "points.csv"), rows.join("\n") + "\n")
let s = ScriptScene("csv_points", folder)
_ = s.script("## A CSV of x, y, z and mass (after a header) as a point cloud.\nimport strings\nfrom luce_std import files\nfrom luce_geocore.script import Cook, Geometry\n\npub func cook(k: Cook*) -> !:\n let data = try files.read_text(k.file(\"table\", \"points.csv\"))\n defer data.release()\n let size = k.f32(\"size\", 0.04)\n let lines = try strings.split(data.value, '\\n')\n var g = try Geometry.empty()\n for row in 1..<lines.length:\n if lines[row].length == 0:\n continue\n let cells = try strings.split(lines[row], ',')\n if cells.length < 4:\n k.warning(f\"row {row + 1} has {cells.length} columns\")\n continue\n let point = try g.add_point([try strings.parse_f32(cells[0]), try strings.parse_f32(cells[1]), try strings.parse_f32(cells[2]), 0.0])\n let mass = try strings.parse_f32(cells[3])\n try g.set_point_f32(point, \"mass\", mass)\n try g.set_point_f32(point, \"pscale\", size * (0.5 + mass))\n try g.set_point_vec3(point, \"Cd\", [mass, 0.3, 1.0 - mass, 0.0])\n print(f\"{g.point_count()} points\")\n try g.make_cloud()\n try k.set_geometry(g)\n")
s.save(folder)
## An L-system tree: a string rewritten a few generations (F -> FF-[-F+F+F]+[+F-F-F]),
## then read by a 3D turtle that leaves a tube for every F, thinner with depth.
func lsystem_tree(folder: str) -> unit!:
let s = ScriptScene("lsystem_tree", folder)
_ = s.script("## An L-system tree: rewrite a string, then walk it with a 3D turtle that\n## leaves a six-sided tube for every F, thinner the deeper the branch.\nfrom luce_std import math32\nfrom luce_geocore.script import Cook, Geometry, Domain3\nfrom luce_geocore.core.growing import Growing\n\n## The turtle: where it is, where it heads, its side direction and depth.\nstruct Turtle:\n var at: f32[4]\n var heading: f32[4]\n var side: f32[4]\n var depth: i64\n\npub func cook(k: Cook*) -> !:\n let generations = k.i32(\"generations\", 4)\n let angle = k.f32(\"angle\", 22.5) * math32.pi / 180.0\n let length = k.f32(\"length\", 0.08)\n let radius = k.f32(\"radius\", 0.03)\n # Rewrite: F -> FF-[-F+F+F]+[+F-F-F].\n var text = Growing[u8]()\n try text.push('F')\n for _ in 0..<generations:\n var next = Growing[u8]()\n for c in text.view():\n if c == 'F':\n for r in \"FF-[-F&F+F]+[+F^F-F]\".bytes: try next.push(r)\n else:\n try next.push(c)\n text.close()\n text = next\n var g = try Geometry.empty()\n var stack = Growing[Turtle]()\n var t = Turtle(at = [0.0, 0.0, 0.0, 0.0], heading = [0.0, 1.0, 0.0, 0.0], side = [1.0, 0.0, 0.0, 0.0], depth = 0)\n var tubes: i64 = 0\n for c in text.view():\n if c == 'F':\n let end = t.at + t.heading * length\n try tube(&g, t.at, end, t.heading, radius * math32.pow(0.8, (f32)t.depth))\n t.at = end\n tubes += 1\n elif c == '+' or c == '-':\n t.heading = turned(t.heading, t.side, angle if c == '+' else -angle)\n elif c == '&' or c == '^':\n let axis = cross(t.heading, t.side)\n t.heading = turned(t.heading, axis, angle if c == '&' else -angle)\n t.side = turned(t.side, axis, angle if c == '&' else -angle)\n elif c == '[':\n try stack.push(t)\n t.depth += 1\n elif c == ']':\n stack.count -= 1\n t = stack.items[stack.count]\n # Color by height: brown trunk to green tips.\n let colors = try g.point_vec3s(\"Cd\")\n let positions = try g.positions_view()\n for i in 0..<colors.length:\n let h = positions[i].y / 2.5 if positions[i].y < 2.5 else 1.0\n colors[i].x = 0.35 - 0.2 * h\n colors[i].y = 0.2 + 0.5 * h\n colors[i].z = 0.1\n print(f\"{text.count} symbols, {tubes} tubes\")\n try k.set_geometry(g)\n\n## A tube of six sides from `a` to `b` around `direction`.\nfunc tube(g: Geometry*, a: f32[4], b: f32[4], direction: f32[4], radius: f32) -> !:\n let up: f32[4] = [0.0, 0.0, 1.0, 0.0] if direction[1] > 0.9 or direction[1] < -0.9 else [0.0, 1.0, 0.0, 0.0]\n let u = normalized(cross(direction, up))\n let v = cross(direction, u)\n let first = g.point_count()\n for ring in 0..<2:\n let center = a if ring == 0 else b\n for i in 0..<6:\n let turn = (f32)i * math32.pi / 3.0\n _ = try g.add_point(center + (u * math32.cos(turn) + v * math32.sin(turn)) * radius)\n for i in 0..<6:\n let j = (i + 1) % 6\n let quad: i64[4] = [first + i, first + j, first + 6 + j, first + 6 + i]\n _ = try g.add_polygon(quad)\n\nfunc cross(a: f32[4], b: f32[4]) -> f32[4]:\n return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0], 0.0]\n\nfunc normalized(a: f32[4]) -> f32[4]:\n let length = math32.sqrt(a[0] * a[0] + a[1] * a[1] + a[2] * a[2])\n return a * (1.0 / length) if length > 0.0 else a\n\n## `v` turned by `angle` about the unit `axis` (Rodrigues).\nfunc turned(v: f32[4], axis: f32[4], angle: f32) -> f32[4]:\n let c = math32.cos(angle)\n let s = math32.sin(angle)\n let d = axis[0] * v[0] + axis[1] * v[1] + axis[2] * v[2]\n return normalized(v * c + cross(axis, v) * s + axis * (d * (1.0 - c)))\n")
s.save(folder)
## Verbs from a script (Houdini's hou.Geometry.execute): a sphere, subdivided,
## its upper faces extruded by a verb with parameters and a group, then colored
## by height.
func verb_chain(folder: str) -> unit!:
let s = ScriptScene("verb_chain", folder)
_ = s.script("## Verbs from code: a sphere, subdivided, its upper faces extruded, colored by height.\nfrom luce_geocore.script import Cook, Geometry, Verb, GroupKind\n\npub func cook(k: Cook*) -> !:\n var g = try Geometry.sphere(1.0, 12)\n var subdivide = try Verb.named(\"Subdivide\")\n try subdivide.parm(\"Levels\", (f64)k.i32(\"levels\", 2))\n var smooth = try subdivide.run(&g)\n # The sphere sits on the ground (y 0 to 2): extrude its upper faces, each on its own.\n var extrude = try Verb.named(\"PolyExtrude\")\n try extrude.parm(\"Distance\", (f64)k.f32(\"distance\", 0.15))\n try extrude.parm(\"Inset\", 0.02)\n try extrude.parm(\"Individual faces\", 1.0)\n try extrude.group(\"@P.y>1.3\", GroupKind.prims)\n var spiky = try extrude.run(&smooth)\n # Blue at the bottom to orange at the top.\n let box = try spiky.bounds()\n let low = (f32)box.minimum.y\n let span = (f32)(box.maximum.y - box.minimum.y)\n let colors = try spiky.point_vec3s(\"Cd\")\n let positions = try spiky.positions_view()\n for i in 0..<colors.length:\n let t = (positions[i].y - low) / span\n colors[i].x = t\n colors[i].y = 0.3\n colors[i].z = 1.0 - t\n print(f\"{spiky.prim_count()} faces\")\n try k.set_geometry(spiky)\n")
s.save(folder)
## A volume from a script: a spiral galaxy as a sparse fog grid. Stars are
## scattered along two arms and each is splatted into the voxels around it
## with `get` and `set`, which make leaves only where stars land.
func galaxy_fog(folder: str) -> unit!:
let s = ScriptScene("galaxy_fog", folder)
let id = s.script("## A spiral galaxy as a sparse fog volume: stars scattered along two arms,\n## each splatted into the voxels around it. Leaves are made only where\n## stars land, so the empty space between the arms costs nothing.\nfrom luce_std import math32\nfrom luce_geocore.script import Cook, Geometry, VolumeClass\n\n## The next number of a small deterministic random sequence, in 0..1.\nfunc next(seed: u64*) -> f32:\n *seed = *seed *% 6364136223846793005 +% 1442695040888963407\n return (f32)(*seed >> 40) / 16777216.0\n\npub func cook(k: Cook*) -> !:\n let stars = k.i32(\"stars\", 40000)\n let voxel = k.f32(\"voxel\", 0.03)\n let twist = k.f32(\"twist\", 2.2)\n let glow = k.f32(\"glow\", 0.12)\n var g = try Geometry.empty()\n # Sparse: the box is empty until stars write into it.\n let fog = try g.add_volume(\"density\", VolumeClass.fog, [0.0, 0.0, 0.0, 0.0], [4.0, 1.0, 4.0, 0.0], voxel = (f64)voxel, dense = false)\n var seed: u64 = 7\n for s in 0..<stars:\n # Two arms, denser and thicker toward the core.\n let arm = (f32)(s % 2) * math32.pi\n let r = next(&seed)\n let radius = 0.08 + r * r * 1.8\n let angle = arm + radius * twist + (next(&seed) - 0.5) * 0.9 * (1.0 - r * 0.6)\n let wobble = (next(&seed) - 0.5) * 0.15\n let height = (next(&seed) - 0.5) * 0.25 * (1.0 - r) * (1.0 - r)\n let at = fog.to_index([math32.cos(angle) * (radius + wobble), height, math32.sin(angle) * (radius + wobble), 0.0])\n let ci = (i64)math32.floor(at[0])\n let cj = (i64)math32.floor(at[1])\n let ck = (i64)math32.floor(at[2])\n # A soft blob over the 3x3x3 voxels around the star.\n for dz in 0..<3:\n for dy in 0..<3:\n for dx in 0..<3:\n let i = ci + (i64)dx - 1\n let j = cj + (i64)dy - 1\n let n = ck + (i64)dz - 1\n let ox = at[0] - (f32)i\n let oy = at[1] - (f32)j\n let oz = at[2] - (f32)n\n let weight = math32.exp(-(ox * ox + oy * oy + oz * oz) * 1.2) * glow\n try fog.set(i, j, n, fog.get(i, j, n) + weight)\n # How the viewport draws the grid (its look, as the Volume Visualization\n # node sets it): thick, softly shadowed, tinted smoke.\n try fog.set_look(density = (f64)k.f32(\"density\", 8.0), shadow = 0.4, smoke = k.color(\"tint\", [0.75, 0.8, 1.0, 0.0]))\n print(f\"{stars} stars in {fog.count() // 512} leaves, {fog.active_count()} voxels\")\n try k.set_geometry(g)\n")
let node = s.w.network.require(id)
assert(node.console.contains("40000 stars"), node.console)
s.save(folder)