ludic/packages/ludic.render3d/actor.ludic
Orkuncakilkaya fd750f3588 render3d: the reflection draws an actor when its mirror image is in view; reflection CPU in R3D_PROF
The water reflection keeps the main camera's frustum planes, and ac_visible tested the actor itself
against them: the town's people, far above the lake with their images far below the frame, all drew
again. The image (2L - y) is what is tested now - town, 69 skinned reflection draws -> 38, the frame
byte-identical; PC camp reflection scene CPU 793 -> about 760 us. R3D_PROF splits the reflection's
CPU into setup, terrain, scene and sky.

Tried and not kept, with the numbers (PC, camp, Vulkan GPU timestamps):
- the ground's cost is its scanned material taps: without them the terrain pass is 555 us of 1568,
  without the photograph 1029; the sun, the noise fields and the grain are 20-100 us each. Moving the
  cheap tier in from 200 m to 60 m changes nothing, so it is the far tier's single taps over the
  mountains. Skipping the normal-map taps past 900 m (where the detail normal is fully faded) saved
  22 us and moved a few pixels - reverted.
- grass: cutting its radius to 300 m barely moves it, so the cost is the near blades' pixels; moving
  their three noise fields to the vertices changed nothing (747 us) - reverted.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-15 18:25:05 +03:00

415 lines
18 KiB
Text

# ============================================================================
# actor.ludic — a model placed once and moved every frame (a character, a prop
# that animates): the counterpart of a scatter Layer for the handful of things
# that are not instanced. Skinned models pose through their Skin (skin.ludic);
# rigid ones take the same path with u_skinned = 0. The game draws them from
# scene_draw / scene_draw_casters through actor_draw / actor_draw_casters.
#
# Uniform locations are looked up once per program (glGetUniformLocation by
# name is slow on this driver, and a hundred actors over five cascades made it
# the frame's biggest CPU cost); the scene's lighting is bound once per program
# per pass, and actors outside the view or beyond their cull distance are skipped.
# ============================================================================
property Actor {
model: Model,
x: int = 0, # float bits, metres
y: int = 0,
z: int = 0,
yaw: int = 0, # radians; 0 faces -z like the camera
scale: int = 0,
tint: words,
rough: int = 0,
mat: words, # the model matrix
visible: bool = true,
casts: bool = true,
id: int = 0,
cutout: bool = false, # alpha-tested (a flame's cards)
emissive: int = 0, # float bits: self-lit strength
skin: Skin, # this instance's own pose (skin_clone); null: the model's
ptint: words, # 4 per primitive: on flag, r, g, b (a part's own colour)
hide: words, # 1 per primitive: skip it (a cap taken off)
radius: int = 0, # float bits: bounding radius for culling (0 = never culled)
cull: int = 0, # float bits: not drawn beyond this distance (0 = always)
outline: int = 0, # float bits: metres of rim drawn around it (0 = none)
ocol: words # the rim's colour (null = white)
}
# a program and its uniform locations
property AcProg {
prog: int = 0,
l_model: int = -1,
l_bones: int = -1,
l_skin: int = -1,
l_lvp: int = -1,
l_tint: int = -1,
l_rough: int = -1,
l_emis: int = -1,
l_view: int = -1,
l_proj: int = -1,
l_out: int = -1,
l_ocol: int = -1,
l_mh: int = -1,
scene_frame: int = -1 # the frame its scene uniforms were bound
}
var ac_lit: AcProg = null
var ac_lit_cut: AcProg = null
var ac_sh: AcProg = null
var ac_sh_cut: AcProg = null
var ac_out: AcProg = null
var ac_out_cut: AcProg = null
var ac_actors: []Actor = null
var ac_next_id: int = 0
var ac_frame: int = 0
function ac_prog_new(vs: string, fs: string, defs: string) -> AcProg {
let a = new AcProg
a.prog = r3d_program(vs, fs, defs)
let p = a.prog
a.l_model = gpu_uniform(p, "u_model"); a.l_skin = gpu_uniform(p, "u_skinned"); a.l_lvp = gpu_uniform(p, "u_light_vp")
a.l_bones = gpu_uniform(p, "u_bones[0]"); if a.l_bones < 0 { a.l_bones = gpu_uniform(p, "u_bones") }
a.l_tint = gpu_uniform(p, "u_tint"); a.l_rough = gpu_uniform(p, "u_rough_scale"); a.l_emis = gpu_uniform(p, "u_emissive")
a.l_view = gpu_uniform(p, "u_view"); a.l_proj = gpu_uniform(p, "u_proj"); a.l_mh = gpu_uniform(p, "u_model_h")
a.l_out = gpu_uniform(p, "u_outline"); a.l_ocol = gpu_uniform(p, "u_outline_col")
# the samplers never move: units 0, 1, 2
gpu_use_program(p)
u_i(gpu_uniform(p, "u_diff"), 0); u_i(gpu_uniform(p, "u_nrm"), 1); u_i(gpu_uniform(p, "u_arm"), 2)
return a
}
function actor_init() -> void {
ac_lit = ac_prog_new("skin.vert", "model.frag", "")
ac_lit_cut = ac_prog_new("skin.vert", "model.frag", "#define ALPHA_TEST\n")
ac_sh = ac_prog_new("skin.vert", "shadow.frag", "#define SHADOW_PASS\n")
ac_sh_cut = ac_prog_new("skin.vert", "shadow.frag", "#define SHADOW_PASS\n#define ALPHA_TEST\n")
ac_out = ac_prog_new("skin.vert", "outline.frag", "#define OUTLINE\n")
ac_out_cut = ac_prog_new("skin.vert", "outline.frag", "#define OUTLINE\n#define ALPHA_TEST\n")
ac_actors = new []Actor
}
function actor_remove(a: Actor) -> void {
if ac_actors == null { return }
let keep = new []Actor
for i in 0 .. len(ac_actors) { if ac_actors[i].id != a.id { push(keep, ac_actors[i]) } }
ac_actors = keep
}
# colour one named part of the model (a material name from the file)
function actor_tint_part(a: Actor, name: string, r: int, g: int, b: int) -> void {
if a.model == null { return }
let n = len(a.model.prims)
if a.ptint == null { a.ptint = words(n * 4); for i in 0 .. n * 4 { a.ptint[i] = 0 } }
for i in 0 .. n { if a.model.prims[i].name == name { a.ptint[i * 4] = 1; a.ptint[i * 4 + 1] = r; a.ptint[i * 4 + 2] = g; a.ptint[i * 4 + 3] = b } }
}
function actor_hide_part(a: Actor, name: string, hidden: bool) -> void {
if a.model == null { return }
let n = len(a.model.prims)
if a.hide == null { a.hide = words(n); for i in 0 .. n { a.hide[i] = 0 } }
var v = 0
if hidden { v = 1 }
for i in 0 .. n { if a.model.prims[i].name == name { a.hide[i] = v } }
}
function actor_new(model: Model) -> Actor {
let a = new Actor
a.model = model
a.scale = F_ONE
a.tint = v3_new(F_ONE, F_ONE, F_ONE)
a.rough = F_ONE
a.mat = m4_new()
ac_next_id += 1; a.id = ac_next_id
if model != null { a.radius = f_add(f_max(model.radius, model.height), F_ONE) }
a.cull = fi(450)
if ac_actors == null { ac_actors = new []Actor }
push(ac_actors, a)
return a
}
function actor_place(a: Actor, x: int, y: int, z: int, yaw: int) -> void {
a.x = x; a.y = y; a.z = z; a.yaw = yaw
m4_trs(a.mat, x, y, z, yaw, a.scale)
}
# the scene's lighting for a lit program, once per frame
function ac_bind_scene(ap: AcProg) -> void {
if ap.scene_frame == ac_frame { return }
ap.scene_frame = ac_frame
let p = ap.prog
gpu_use_program(p)
u_mat4(ap.l_view, cam_view)
u_mat4(ap.l_proj, cam_proj)
u_f(ap.l_mh, F_ZERO)
sky_bind_lighting(p)
shadow_bind(p)
fog_bind(p)
}
function ac_visible(a: Actor, shadow: bool) -> bool {
if not a.visible or a.model == null { return false }
if shadow and not a.casts { return false }
if a.cull != 0 {
let dx = f_sub(a.x, cam_pos[0]); let dz = f_sub(a.z, cam_pos[2])
let d2 = f_add(f_mul(dx, dx), f_mul(dz, dz))
var c = a.cull
if shadow { c = f_min(c, fi(300)) }
if f_gt(d2, f_mul(c, c)) { return false }
}
if not shadow and a.radius != 0 {
let r = f_mul(a.radius, a.scale)
var cy = f_add(a.y, r)
# In the water reflection what reaches the picture is the actor's mirror image, 2L - y. The pass
# keeps the main camera's frustum planes, so the image is what has to be tested against them: the
# actor itself was, and the town's people - far above the lake, their images far below the frame -
# all drew again into the reflection.
if ter_reflect { cy = f_sub(f_mul(F_TWO, water_level), cy) }
if not cam_sphere_visible(a.x, cy, a.z, f_mul(r, fl(1.5))) { return false }
}
return true
}
function actor_draw_one(a: Actor, ap: AcProg, shadow: bool) -> void {
let p = ap.prog
gpu_use_program(p)
u_mat4(ap.l_model, a.mat)
var skinned = F_ZERO
if a.skin != null { skinned = F_ONE; u_mat4n(ap.l_bones, a.skin.n_joints, a.skin.bones) }
else if a.model.skin != null { skinned = F_ONE; u_mat4n(ap.l_bones, a.model.skin.n_joints, a.model.skin.bones) }
u_f(ap.l_skin, skinned)
if not shadow {
u_f(ap.l_emis, a.emissive)
u_f(ap.l_rough, a.rough)
}
gpu_cull(false)
let model = a.model
for i in 0 .. len(model.prims) {
let pr = model.prims[i]
if a.hide != null and a.hide[i] != 0 { continue }
if not shadow {
if a.ptint != null and a.ptint[i * 4] != 0 { u_f3(ap.l_tint, a.ptint[i * 4 + 1], a.ptint[i * 4 + 2], a.ptint[i * 4 + 3]) }
else { u_v3(ap.l_tint, a.tint) }
}
gpu_tex_unit(0); gpu_tex_bind(GPU_TEX2D, pr.diff)
if not shadow {
gpu_tex_unit(1); gpu_tex_bind(GPU_TEX2D, pr.nrm)
gpu_tex_unit(2); gpu_tex_bind(GPU_TEX2D, pr.arm)
}
mesh_draw(pr.mesh)
}
}
# ---- outlining something that is not an actor ---------------------------------------------
# An Actor gets its rim from its own `outline` field. Everything else in a scene - a
# scatter instance, a tile, anything drawn by a system that owns its own transforms - had
# no way to ask for one, because the outline pass walked the actor list and nothing else.
# A tree is the case that matters: instanced scatter has no actor to hull, so a game that
# highlights whatever the crosshair is on could highlight every object in the world except
# the twenty thousand most common ones.
#
# So: a queue. `outline_model` says "put a rim round this model at this transform" from
# anywhere in the frame, and the outline pass flushes it alongside the actors' - which is
# what gets the depth test right, since the rim has to be drawn after the scene it is
# tested against and the caller does not control pass order.
#
# The rim is the model's own geometry swollen along its normals. A layer whose vertex
# shader moves its instances - wind, or standing them on the drawn terrain - will differ
# from the rim by however much that shader moved them, so pass the transform the shader
# would have arrived at (for a grounded layer, the terrain height at that instance).
property OutlineReq {
model: Model,
mat: words,
width: int = 0,
r: int = 0,
g: int = 0,
b: int = 0
}
var ac_oq: []OutlineReq = null
var ac_oq_n: int = 0 # live entries; the array is kept and reused
# A frame is drawn by more than one pass - a shadow map, a water reflection, the scene -
# and actor_draw runs in each of them. An Actor survives that because its rim is a field
# on the actor; a queue does not, if the first pass empties it. So a flush CLOSES the
# batch rather than clearing it, and the next add opens a new one: every pass in a frame
# sees the same requests, and the caller needs no frame hook.
var ac_oq_closed: bool = true
function outline_model(m: Model, mat: words, width: int, r: int, g: int, b: int) -> void {
if m == null or mat == null or width == 0 { return }
if ac_oq_closed { ac_oq_n = 0; ac_oq_closed = false }
if ac_oq == null { ac_oq = new []OutlineReq }
var q: OutlineReq = null
if ac_oq_n < len(ac_oq) { q = ac_oq[ac_oq_n] } else { q = new OutlineReq; q.mat = m4_new(); push(ac_oq, q) }
q.model = m; q.width = width; q.r = r; q.g = g; q.b = b
m4_copy(q.mat, mat)
ac_oq_n += 1
}
function outline_clear() -> void { ac_oq_n = 0; ac_oq_closed = true }
# Called at the top of every frame. A batch the last frame closed and nobody has reopened
# since is stale: the caller stopped asking. Without this it was drawn for ever - flush
# closes a batch but only the NEXT outline_model call empties it, so looking away from a
# highlighted tree left its rim on until something else was highlighted.
function outline_frame() -> void { if ac_oq_closed { ac_oq_n = 0 } }
# R3D_ACTOR_CENSUS=<frame>: at that frame, the lit pass's actors grouped by model - skinned or rigid,
# how many share it, the primitives each draws - so instancing is aimed at what repeats
function actor_census() -> void {
let keys = new []Model
let cnt = new []int
let prims = new []int
let rigid = new []int
for i in 0 .. len(ac_actors) {
let a = ac_actors[i]
if not ac_visible(a, false) { continue }
var k = -1
for j in 0 .. len(keys) { if keys[j] == a.model { k = j } }
if k < 0 { push(keys, a.model); push(cnt, 0); push(prims, 0); var r = 1; if a.model.skin != null { r = 0 }; push(rigid, r); k = len(keys) - 1 }
if a.skin != null { rigid[k] = 0 }
cnt[k] += 1
var shown = 0
for p in 0 .. len(a.model.prims) { if a.hide == null or a.hide[p] == 0 { shown += 1 } }
prims[k] += shown
}
var total = 0
for j in 0 .. len(keys) {
var kind = "skinned"
if rigid[j] == 1 { kind = "rigid" }
print(`actor census: model {j} ({kind}, {len(keys[j].prims)} prims, {keys[j].tris} tris): {cnt[j]} actors, {prims[j]} draws`)
total += prims[j]
}
print(`actor census: {len(keys)} models, {total} lit draws`)
}
var ac_census_at: int = -2
function actor_draw() -> void {
if ac_actors == null { return }
ac_frame += 1
if ac_census_at == -2 { ac_census_at = -1; if Os.has_env("R3D_ACTOR_CENSUS") { ac_census_at = Text.to_int(Os.env("R3D_ACTOR_CENSUS")) } }
if ac_census_at > 0 and ac_frame == ac_census_at { actor_census() }
for i in 0 .. len(ac_actors) {
let a = ac_actors[i]
if not ac_visible(a, false) { continue }
var ap = ac_lit
if a.cutout { ap = ac_lit_cut }
ac_bind_scene(ap)
actor_draw_one(a, ap, false)
}
actor_draw_outlines()
gpu_cull(true)
}
# The rim around a highlighted actor: the model again, its vertices pushed out along their
# normals (skin.vert, OUTLINE) and its front faces culled, so only the far side of the
# swollen shell survives — a silhouette exactly `outline` metres wide. Depth-tested
# against the scene, so anything in front of the actor hides its rim too.
function actor_draw_outlines() -> void {
var any = ac_oq_n > 0
for i in 0 .. len(ac_actors) { if ac_actors[i].outline != 0 and ac_visible(ac_actors[i], false) { any = true; break } }
if not any { return }
gpu_cull(true)
gpu_cull_face(GL_FRONT)
for i in 0 .. len(ac_actors) {
let a = ac_actors[i]
if a.outline == 0 or not ac_visible(a, false) { continue }
var ap = ac_out
if a.cutout { ap = ac_out_cut }
gpu_use_program(ap.prog)
u_mat4(ap.l_view, cam_view); u_mat4(ap.l_proj, cam_proj)
u_f(ap.l_out, f_mul(a.outline, a.scale))
if a.ocol != null { u_v3(ap.l_ocol, a.ocol) } else { u_f3(ap.l_ocol, F_ONE, F_ONE, F_ONE) }
actor_draw_outline_one(a, ap)
}
# and whatever asked for a rim without being an actor
for i in 0 .. ac_oq_n {
let q = ac_oq[i]
let ap = ac_out
gpu_use_program(ap.prog)
u_mat4(ap.l_view, cam_view); u_mat4(ap.l_proj, cam_proj)
u_f(ap.l_out, q.width)
u_f3(ap.l_ocol, q.r, q.g, q.b)
u_mat4(ap.l_model, q.mat)
u_f(ap.l_skin, F_ZERO)
for k in 0 .. len(q.model.prims) { mesh_draw(q.model.prims[k].mesh) }
}
ac_oq_closed = true
gpu_cull_face(GL_BACK)
}
function actor_draw_outline_one(a: Actor, ap: AcProg) -> void {
u_mat4(ap.l_model, a.mat)
var skinned = F_ZERO
if a.skin != null { skinned = F_ONE; u_mat4n(ap.l_bones, a.skin.n_joints, a.skin.bones) }
else if a.model.skin != null { skinned = F_ONE; u_mat4n(ap.l_bones, a.model.skin.n_joints, a.model.skin.bones) }
u_f(ap.l_skin, skinned)
let model = a.model
for i in 0 .. len(model.prims) {
let pr = model.prims[i]
if a.hide != null and a.hide[i] != 0 { continue }
if a.cutout { gpu_tex_unit(0); gpu_tex_bind(GPU_TEX2D, pr.diff) }
mesh_draw(pr.mesh)
}
}
# Is a sphere inside this cascade's light box? The projection is orthographic, so a point's
# clip x and y are the matrix applied to it, and the sphere's reach along each is bounded by the
# three axis offsets. An actor outside the box casts nothing into that layer: skipping it changes no
# depth, only the draw. (Each actor used to draw into every cascade out to 300 m - in town that was
# about 1500 skinned shadow draws a frame against 69 in the lit pass.)
var ac_lp0: words = null
var ac_lpx: words = null
var ac_lpy: words = null
var ac_lpz: words = null
function ac_in_light(vp: words, x: int, y: int, z: int, r: int) -> bool {
if ac_lp0 == null { ac_lp0 = words(3); ac_lpx = words(3); ac_lpy = words(3); ac_lpz = words(3) }
m4_xform_point(ac_lp0, vp, x, y, z)
m4_xform_point(ac_lpx, vp, f_add(x, r), y, z)
m4_xform_point(ac_lpy, vp, x, f_add(y, r), z)
m4_xform_point(ac_lpz, vp, x, y, f_add(z, r))
for k in 0 .. 2 {
let c = ac_lp0[k]
let e = f_add(f_add(ac_abs(f_sub(ac_lpx[k], c)), ac_abs(f_sub(ac_lpy[k], c))), ac_abs(f_sub(ac_lpz[k], c)))
if f_gt(f_sub(ac_abs(c), e), F_ONE) { return false }
}
return true
}
function ac_abs(v: int) -> int { return f_max(v, f_neg(v)) }
function actor_draw_casters(light_vp: words) -> void {
if ac_actors == null { return }
gpu_use_program(ac_sh.prog); u_mat4(ac_sh.l_lvp, light_vp)
gpu_use_program(ac_sh_cut.prog); u_mat4(ac_sh_cut.l_lvp, light_vp)
for i in 0 .. len(ac_actors) {
let a = ac_actors[i]
if not ac_visible(a, true) { continue }
if a.radius != 0 {
# the radius is the horizontal extent: a person is far taller than wide, so the sphere is
# centred at half the model's height and reaches the larger of the two, with a margin for
# the pose (a first version centred it at the radius and dropped a head at a cascade's edge)
let hh = f_mul(f_mul(a.model.height, F_HALF), a.scale)
let r = f_max(f_mul(a.radius, a.scale), hh)
if not ac_in_light(light_vp, a.x, f_add(a.y, hh), a.z, f_mul(r, fl(1.5))) { continue }
}
# Inside the light box is not the same as able to shade anything this cascade covers: every actor
# within 300 m sits inside the far cascades' boxes, whose receivers start 250 and 1100 m out - at
# the camp 160 actors cast 300 draws into each of those, against 41 into the nearest.
let dxa = f_sub(a.x, cam_pos[0]); let dza = f_sub(a.z, cam_pos[2])
let da = f_sqrt(f_add(f_mul(dxa, dxa), f_mul(dza, dza)))
let ra = f_mul(a.radius, a.scale)
if not cast_band_reaches(f_max(f_sub(da, ra), F_ZERO), f_add(da, ra), f_mul(a.model.height, a.scale)) { continue }
var ap = ac_sh
if a.cutout { ap = ac_sh_cut }
if ac_census_at > 0 and ac_frame == ac_census_at { ac_caster_count(a) }
actor_draw_one(a, ap, true)
}
if ac_census_at > 0 and ac_frame == ac_census_at {
print(`actor census, cascade {sh_cascade}: {ac_cc_actors} actors cast {ac_cc_draws} draws ({ac_cc_skinned} of them skinned, {ac_cc_cut} cutout)`)
ac_cc_actors = 0; ac_cc_draws = 0; ac_cc_skinned = 0; ac_cc_cut = 0
}
prof_cpu_mark("shadow actors")
}
var ac_cc_actors: int = 0
var ac_cc_draws: int = 0
var ac_cc_skinned: int = 0
var ac_cc_cut: int = 0
function ac_caster_count(a: Actor) -> void {
var shown = 0
for p in 0 .. len(a.model.prims) { if a.hide == null or a.hide[p] == 0 { shown += 1 } }
ac_cc_actors += 1
ac_cc_draws += shown
if a.skin != null or a.model.skin != null { ac_cc_skinned += shown }
if a.cutout { ac_cc_cut += shown }
}
# every actor off the stage at once, for a world being replaced. Actors own no GL objects;
# their models belong to whoever loaded them.
function actor_clear_all() -> void {
ac_actors = new []Actor
outline_clear()
}