Debian Codegraph @

texmf-dist/tex/latex/lua-tikz3dtools/lua-tikz3dtools-scene.lua

raw
1 --- lua-tikz3dtools-scene.lua
2 --- Scene management, TeX command registration, and rendering for lua-tikz3dtools.
3
4 local Vector
5 local Matrix
6 local Geometry
7
8 local Scene = {}
9 local lua_tikz3dtools = {}
10
11 --- Set class references (called after all modules are loaded).
12 function Scene._set_classes(V, M, G)
13 Vector = V
14 Matrix = M
15 Geometry = G
16 end
17
18
19 -- ================================================================
20 -- Sandboxed evaluation environment
21 -- ================================================================
22
23 local function make_readonly_table(value, label)
24 return setmetatable(value, {
25 __newindex = function(_, key, _)
26 error(("sandbox value '%s' is read-only; cannot assign '%s'")
27 :format(label, tostring(key)), 2)
28 end,
29 __metatable = false,
30 })
31 end
32
33 local function make_readonly_proxy(source, label)
34 return setmetatable({}, {
35 __index = source,
36 __newindex = function(_, key, _)
37 error(("sandbox value '%s' is read-only; cannot assign '%s'")
38 :format(label, tostring(key)), 2)
39 end,
40 __metatable = false,
41 })
42 end
43
44 --- Build the base environment used by all sandbox evaluations.
45 --- User-defined objects are resolved separately so expressions cannot mutate
46 --- shared global state or shadow built-in names.
47 local blocked_globals = {
48 debug = true,
49 dofile = true,
50 load = true,
51 loadfile = true,
52 package = true,
53 require = true,
54 }
55
56 local proxied_tables = {
57 coroutine = true,
58 io = true,
59 math = true,
60 os = true,
61 string = true,
62 table = true,
63 utf8 = true,
64 }
65
66 local function build_base_env()
67 local env = {}
68
69 for key, value in pairs(_G) do
70 if not blocked_globals[key] then
71 if proxied_tables[key] and type(value) == "table" then
72 env[key] = make_readonly_proxy(value, key)
73 else
74 env[key] = value
75 end
76 end
77 end
78
79 env.table = env.table or make_readonly_proxy(table, "table")
80 env.math = env.math or make_readonly_proxy(math, "math")
81
82 -- Expose math entries directly so callers can use sin/cos/etc. without math. prefix
83 for k, v in pairs(math) do
84 if env[k] == nil then
85 env[k] = v
86 end
87 end
88
89 return env
90 end
91
92 local function source_preview(str)
93 local preview = tostring(str or "")
94 :gsub("%s+", " ")
95 :gsub("^%s+", "")
96
97 if #preview > 160 then
98 preview = preview:sub(1, 157) .. "..."
99 end
100
101 return preview
102 end
103
104 local function format_eval_error(kind, label, source, err)
105 return ("%s in %s: %s\nSource: %s")
106 :format(kind, label or "expression", tostring(err), source_preview(source))
107 end
108
109 local function make_eval_env(bindings)
110 bindings = bindings or {}
111
112 return setmetatable({}, {
113 __index = function(_, key)
114 local value = bindings[key]
115 if value ~= nil then
116 return value
117 end
118
119 value = lua_tikz3dtools.objects[key]
120 if value ~= nil then
121 return value
122 end
123
124 return lua_tikz3dtools.base_env[key]
125 end,
126 __newindex = function(_, key, _)
127 error(("sandbox is read-only; cannot assign global '%s'")
128 :format(tostring(key)), 2)
129 end,
130 __metatable = false,
131 })
132 end
133
134 local function evaluate_chunk(source, label, bindings)
135 local chunk, syntax_err = load(source, label or "expression", "t", make_eval_env(bindings))
136
137 if not chunk then
138 error(format_eval_error("Lua syntax error", label, source, syntax_err), 0)
139 end
140
141 local ok, result = pcall(chunk)
142 if not ok then
143 error(format_eval_error("Lua evaluation error", label, source, result), 0)
144 end
145
146 return result
147 end
148
149 local function wrap_user_function(fn, label, source)
150 return function(...)
151 local ok, result = pcall(fn, ...)
152 if not ok then
153 error(format_eval_error("Lua function error", label, source, result), 0)
154 end
155 return result
156 end
157 end
158
159 local statement_keywords = {
160 "return",
161 "local",
162 "if",
163 "for",
164 "while",
165 "repeat",
166 "do",
167 }
168
169 local function starts_with_statement(trimmed)
170 for _, keyword in ipairs(statement_keywords) do
171 if trimmed:match("^" .. keyword .. "%f[%W]") then
172 return true
173 end
174 end
175
176 return false
177 end
178
179 -- ================================================================
180 -- TeX command registration helper
181 -- https://tex.stackexchange.com/a/747040
182 -- ================================================================
183
184 local function register_tex_cmd(name, func, args, protected)
185 name = "__lua_tikztdtools_" .. name .. ":" .. ("n"):rep(#args)
186 local scanners = {}
187 for _, arg in ipairs(args) do
188 scanners[#scanners+1] = token['scan_' .. arg]
189 end
190 local scanning_func = function()
191 local values = {}
192 for _, scanner in ipairs(scanners) do
193 values[#values+1] = scanner()
194 end
195 func(table.unpack(values))
196 end
197 local index = luatexbase.new_luafunction(name)
198 lua.get_functions_table()[index] = scanning_func
199 if protected then
200 token.set_lua(name, index, "protected")
201 else
202 token.set_lua(name, index)
203 end
204 end
205
206 -- ================================================================
207 -- Global scene state
208 -- ================================================================
209
210 lua_tikz3dtools.simplices = {}
211 lua_tikz3dtools.lights = {}
212 lua_tikz3dtools.objects = {}
213 lua_tikz3dtools.base_env = build_base_env()
214
215 local function refresh_base_env()
216 lua_tikz3dtools.base_env.Vector = make_readonly_proxy(Vector, "Vector")
217 lua_tikz3dtools.base_env.Matrix = make_readonly_proxy(Matrix, "Matrix")
218 lua_tikz3dtools.base_env.tau = 2 * math.pi
219 end
220
221 --- Late-init: called after Vector/Matrix are set to update the env table
222 function Scene._init_math_env()
223 refresh_base_env()
224 end
225
226 -- ================================================================
227 -- Expression evaluators (sandboxed)
228 -- ================================================================
229
230 local function single_string_expression(str, label, bindings)
231 return evaluate_chunk(("return %s"):format(str), label, bindings)
232 end
233
234 local function body_expression(str, label, bindings)
235 return evaluate_chunk(str, label, bindings)
236 end
237
238 local function object_expression(str, label, bindings)
239 local trimmed = str:match("^%s*(.-)%s*$") or ""
240 if starts_with_statement(trimmed) then
241 return body_expression(str, label, bindings)
242 end
243 return single_string_expression(str, label, bindings)
244 end
245
246 local function options_string_expression(str, label, bindings)
247 if type(str) ~= "string" or str == "" then
248 return ""
249 end
250
251 local trimmed = str:match("^%s*(.-)%s*$") or ""
252 if trimmed == "" then
253 return ""
254 end
255
256 if starts_with_statement(trimmed) then
257 local value = body_expression(str, label, bindings)
258 assert(type(value) == "string", label .. " must return a string")
259 return value
260 end
261
262 local ok, value_or_err = pcall(object_expression, str, label, bindings)
263 if ok then
264 assert(type(value_or_err) == "string", label .. " must evaluate to a string")
265 return value_or_err
266 end
267
268 if tostring(value_or_err):match("^Lua syntax error") then
269 return str
270 end
271
272 error(value_or_err, 0)
273 end
274
275 local function single_string_function(str, label, bindings)
276 local fn = evaluate_chunk(("return function(u) %s end"):format(str), label, bindings)
277 return wrap_user_function(fn, label, str)
278 end
279
280 local function double_string_function(str, label, bindings)
281 local fn = evaluate_chunk(("return function(u,v) %s end"):format(str), label, bindings)
282 return wrap_user_function(fn, label, str)
283 end
284
285 local function triple_string_function(str, label, bindings)
286 local fn = evaluate_chunk(("return function(u,v,w) %s end"):format(str), label, bindings)
287 return wrap_user_function(fn, label, str)
288 end
289
290 local function is_finite_number(value)
291 return type(value) == "number"
292 and value == value
293 and value ~= math.huge
294 and value ~= -math.huge
295 end
296
297 local function is_finite_numeric_matrix(value)
298 if getmetatable(value) ~= Matrix then
299 return false
300 end
301
302 for i = 1, #value do
303 for j = 1, #value[i] do
304 if not is_finite_number(value[i][j]) then
305 return false
306 end
307 end
308 end
309
310 return true
311 end
312
313 local function is_finite_simplex(simplex)
314 local mt = getmetatable(simplex)
315
316 if mt == Vector then
317 for i = 1, #simplex do
318 if not is_finite_number(simplex[i]) then
319 return false
320 end
321 end
322 return true
323 end
324
325 if mt == Matrix then
326 for i = 1, #simplex do
327 for j = 1, #simplex[i] do
328 if not is_finite_number(simplex[i][j]) then
329 return false
330 end
331 end
332 end
333 return true
334 end
335
336 return false
337 end
338
339 local function project_point(v, transformation, label)
340 if not v then
341 return nil
342 end
343
344 if not is_finite_numeric_matrix(transformation) then
345 return nil
346 end
347
348 local ok, projected = pcall(function()
349 return v:multiply(transformation)
350 end)
351
352 if not ok then
353 error(("Projection failed for %s: %s")
354 :format(label or "point", tostring(projected)), 0)
355 end
356
357 if is_finite_simplex(projected) then
358 return projected
359 end
360
361 return nil
362 end
363
364 local function project_simplex(simplex, transformation, label)
365 if not simplex then
366 return nil
367 end
368
369 if not is_finite_numeric_matrix(transformation) then
370 return nil
371 end
372
373 local ok, projected = pcall(function()
374 return simplex:multiply(transformation):reciprocate_by_homogeneous()
375 end)
376
377 if not ok then
378 error(("Projection failed for %s: %s")
379 :format(label or "simplex", tostring(projected)), 0)
380 end
381
382 if is_finite_simplex(projected) then
383 return projected
384 end
385
386 return nil
387 end
388
389 local function push_simplex(entry)
390 if entry.simplex and is_finite_simplex(entry.simplex) then
391 table.insert(lua_tikz3dtools.simplices, entry)
392 return true
393 end
394
395 return false
396 end
397
398 local function is_nonempty_string(value)
399 return type(value) == "string" and value ~= ""
400 end
401
402 local DEFAULT_ARROW_SCALE = 0.1
403
404 local function resolve_arrow_scale(scale_src, label, fallback)
405 if scale_src == nil or scale_src == "" then
406 return fallback or DEFAULT_ARROW_SCALE
407 end
408
409 local scale = object_expression(scale_src, label)
410 assert(is_finite_number(scale) and scale > 0,
411 label .. " must evaluate to a positive number")
412 return scale
413 end
414
415 local function uv_curve_point(value)
416 if getmetatable(value) ~= Vector or #value < 2 then
417 return nil
418 end
419 if not is_finite_number(value[1]) or not is_finite_number(value[2]) then
420 return nil
421 end
422 return Vector:_new{value[1], value[2], 1}
423 end
424
425 local function uv_curve_point_value(value)
426 if getmetatable(value) == Vector then
427 return uv_curve_point(value)
428 end
429 if type(value) == "table" then
430 return uv_curve_point(Vector:_new(value))
431 end
432 return nil
433 end
434
435 local function append_uv_curve_segment(uv_segments, start_point, stop_point, drawoptions)
436 if start_point and stop_point and start_point:hdistance(stop_point) > 1e-12 then
437 table.insert(uv_segments, {
438 simplex = Matrix:_new{start_point:to_table(), stop_point:to_table()},
439 drawoptions = drawoptions,
440 })
441 end
442 end
443
444 local function append_uv_arrow_segments(uv_segments, tip_point, tail_point, drawoptions, scale)
445 if not is_nonempty_string(drawoptions) then
446 return
447 end
448
449 local direction = tip_point:hsub(tail_point)
450 local length = direction:hnorm()
451 if length <= 1e-12 then
452 return
453 end
454
455 local tip_scale = math.min(scale or DEFAULT_ARROW_SCALE, length)
456 if tip_scale <= 1e-12 then
457 return
458 end
459
460 local U = direction:hnormalize()
461 local V = U:multiply(Matrix:_new{
462 {0, 1, 0},
463 {-1, 0, 0},
464 {0, 0, 1}
465 }):hnormalize()
466 local base_point = tip_point:hsub(U:hscale(tip_scale))
467
468 append_uv_curve_segment(
469 uv_segments,
470 base_point:hadd(V:hscale(tip_scale)),
471 tip_point,
472 drawoptions
473 )
474 append_uv_curve_segment(
475 uv_segments,
476 base_point:hsub(V:hscale(tip_scale)),
477 tip_point,
478 drawoptions
479 )
480 end
481
482 local function explicit_uv_curve_segments(str, label)
483 local segments = body_expression(str, label)
484 local uv_segments = {}
485
486 if type(segments) ~= "table" then
487 return nil
488 end
489
490 for _, segment in ipairs(segments) do
491 if type(segment) == "table" or getmetatable(segment) == Matrix then
492 local P = uv_curve_point_value(segment.start or segment[1])
493 local Q = uv_curve_point_value(segment.stop or segment[2])
494
495 if P and Q and P:hdistance(Q) > 1e-12 then
496 local arrowscale = segment.arrowscale
497 if arrowscale == nil then
498 arrowscale = DEFAULT_ARROW_SCALE
499 end
500 if arrowscale ~= nil then
501 assert(is_finite_number(arrowscale) and arrowscale > 0,
502 label .. ".arrowscale must be a positive number")
503 end
504
505 append_uv_curve_segment(uv_segments, P, Q, segment.drawoptions)
506
507 if is_nonempty_string(segment.arrowtail) then
508 append_uv_arrow_segments(uv_segments, P, Q, segment.arrowtail, arrowscale)
509 end
510
511 if is_nonempty_string(segment.arrowtip) then
512 append_uv_arrow_segments(uv_segments, Q, P, segment.arrowtip, arrowscale)
513 end
514 end
515 end
516 end
517
518 if #uv_segments == 0 then
519 return nil
520 end
521 return uv_segments
522 end
523
524 local function embedded_segments_in_triangle(uv_segments, uv_triangle)
525 if uv_segments == nil then
526 return nil
527 end
528
529 local embedded_segments = {}
530 for _, segment in ipairs(uv_segments) do
531 local orig_start = Vector:_new(segment.simplex[1])
532 local orig_stop = Vector:_new(segment.simplex[2])
533 local clipped = Geometry.hclip_line_segment_to_triangle(segment.simplex, uv_triangle)
534 if clipped ~= nil then
535 local start_bary = Geometry.hpoint_triangle_barycentric(Vector:_new(clipped[1]), uv_triangle)
536 local stop_bary = Geometry.hpoint_triangle_barycentric(Vector:_new(clipped[2]), uv_triangle)
537 if start_bary ~= nil and stop_bary ~= nil then
538 table.insert(embedded_segments, {
539 start = start_bary:to_table(),
540 stop = stop_bary:to_table(),
541 drawoptions = segment.drawoptions,
542 start_cut = Vector:_new(clipped[1]):hdistance(orig_start) > 1e-9,
543 stop_cut = Vector:_new(clipped[2]):hdistance(orig_stop) > 1e-9,
544 })
545 end
546 end
547 end
548
549 if #embedded_segments == 0 then
550 return nil
551 end
552
553 return embedded_segments
554 end
555
556 local function triangle_shading_normal(simplex)
557 local A = Vector:_new(simplex[1])
558 local B = Vector:_new(simplex[2])
559 local C = Vector:_new(simplex[3])
560 local normal = (B:hsub(A)):hhypercross(C:hsub(A))
561
562 if normal:hnorm() <= 1e-12 then
563 return nil
564 end
565
566 return normal:hnormalize()
567 end
568
569 local function light_facing_normal(normal, light_dir)
570 if normal:hinner(light_dir) < 0 then
571 return normal:hscale(-1)
572 end
573 return normal
574 end
575
576
577
578 local function render_embedded_segments(simplex)
579 if simplex.embedded_segments == nil then
580 return
581 end
582
583 local T = simplex.simplex
584 local ax, ay = T[1][1], T[1][2]
585 local bx, by = T[2][1], T[2][2]
586 local cx, cy = T[3][1], T[3][2]
587
588 local max_edge = math.sqrt(math.max(
589 (ax-bx)^2 + (ay-by)^2,
590 (bx-cx)^2 + (by-cy)^2,
591 (cx-ax)^2 + (cy-ay)^2
592 ))
593
594 for _, segment in ipairs(simplex.embedded_segments) do
595 local start_point = Geometry.hpoint_from_triangle_barycentric(
596 T, Vector:_new(segment.start)
597 )
598 local stop_point = Geometry.hpoint_from_triangle_barycentric(
599 T, Vector:_new(segment.stop)
600 )
601
602 if start_point:hdistance(stop_point) > 1e-12 then
603 local sx, sy = start_point[1], start_point[2]
604 local ex, ey = stop_point[1], stop_point[2]
605 local s_cut = segment.start_cut == true
606 local e_cut = segment.stop_cut == true
607
608 if (s_cut or e_cut) and max_edge > 1e-12 then
609 local dx, dy = ex - sx, ey - sy
610 local seg_len = math.sqrt(dx*dx + dy*dy)
611 if seg_len > 1e-12 then
612 local ux, uy = dx / seg_len, dy / seg_len
613 local draw_sx = s_cut and (sx - ux * max_edge) or sx
614 local draw_sy = s_cut and (sy - uy * max_edge) or sy
615 local draw_ex = e_cut and (ex + ux * max_edge) or ex
616 local draw_ey = e_cut and (ey + uy * max_edge) or ey
617 tex.sprint(
618 ("\\begin{scope}\\clip (%f,%f)--(%f,%f)--(%f,%f)--cycle;\\path[%s] (%f,%f)--(%f,%f);\\end{scope}")
619 :format(
620 ax, ay, bx, by, cx, cy,
621 segment.drawoptions or "",
622 draw_sx, draw_sy, draw_ex, draw_ey
623 )
624 )
625 end
626 else
627 tex.sprint(
628 ("\\path[%s] (%f,%f) -- (%f,%f);")
629 :format(
630 segment.drawoptions or "",
631 sx, sy, ex, ey
632 )
633 )
634 end
635 end
636 end
637 end
638
639 local function param_triplet(value, key_name)
640 assert(value and getmetatable(value) == Vector,
641 key_name .. " must return a Vector")
642 assert(value[1] ~= nil and value[2] ~= nil and value[3] ~= nil,
643 key_name .. " must contain start, stop, and samples")
644
645 return value[1], value[2], value[3]
646 end
647
648 local function resolve_axis_params(params_src, key_name)
649 return param_triplet(body_expression(params_src, key_name), key_name)
650 end
651
652 local function append_surface(hash)
653 local ustart, ustop, usamples = resolve_axis_params(hash.uparams, "appendsurface.uparams")
654 local vstart, vstop, vsamples = resolve_axis_params(hash.vparams, "appendsurface.vparams")
655 local transformation = object_expression(hash.transformation, "appendsurface.transformation")
656 local f = double_string_function(hash.v, "appendsurface.v")
657 local filloptions = options_string_expression(hash.filloptions, "appendsurface.filloptions")
658 local filter = hash.filter
659 local uv_curve_segments
660
661 assert(usamples and usamples >= 2, "usamples must be >= 2, got: " .. tostring(usamples))
662 assert(vsamples and vsamples >= 2, "vsamples must be >= 2, got: " .. tostring(vsamples))
663
664 local ustep = (ustop - ustart) / (usamples - 1)
665 local vstep = (vstop - vstart) / (vsamples - 1)
666
667 local function parametric_surface(u, v)
668 return f(u, v)
669 end
670
671 if is_nonempty_string(hash.curve) then
672 uv_curve_segments = explicit_uv_curve_segments(hash.curve, "appendsurface.curve")
673 end
674
675 for i = 0, usamples - 2 do
676 local u = ustart + i * ustep
677 for j = 0, vsamples - 2 do
678 local v = vstart + j * vstep
679 local A = parametric_surface(u, v)
680 local B = parametric_surface(u + ustep, v)
681 local C = parametric_surface(u + ustep, v + vstep)
682 local D = parametric_surface(u, v + vstep)
683 if A and B and C and D then
684 local uvA = Vector:_new{u, v, 1}
685 local uvB = Vector:_new{u + ustep, v, 1}
686 local uvC = Vector:_new{u + ustep, v + vstep, 1}
687 local uvD = Vector:_new{u, v + vstep, 1}
688 if not (
689 Geometry.hpoint_point_intersecting(A, B)
690 or Geometry.hpoint_point_intersecting(B, C)
691 or Geometry.hpoint_point_intersecting(A, C)
692 ) then
693 local simplex1 = project_simplex(
694 Matrix:_new{A:to_table(), B:to_table(), C:to_table()},
695 transformation,
696 "appendsurface.triangle1"
697 )
698 if simplex1 then
699 push_simplex({
700 simplex = simplex1,
701 filloptions = filloptions,
702 type = "triangle",
703 filter = filter,
704 shading_normal = triangle_shading_normal(simplex1),
705 embedded_segments = embedded_segments_in_triangle(
706 uv_curve_segments,
707 Matrix:_new{uvA:to_table(), uvB:to_table(), uvC:to_table()}
708 )
709 })
710 end
711 end
712 if not (
713 Geometry.hpoint_point_intersecting(A, D)
714 or Geometry.hpoint_point_intersecting(D, C)
715 or Geometry.hpoint_point_intersecting(A, C)
716 ) then
717 local simplex2 = project_simplex(
718 Matrix:_new{A:to_table(), D:to_table(), C:to_table()},
719 transformation,
720 "appendsurface.triangle2"
721 )
722 if simplex2 then
723 push_simplex({
724 simplex = simplex2,
725 filloptions = filloptions,
726 type = "triangle",
727 filter = filter,
728 shading_normal = triangle_shading_normal(simplex2),
729 embedded_segments = embedded_segments_in_triangle(
730 uv_curve_segments,
731 Matrix:_new{uvA:to_table(), uvD:to_table(), uvC:to_table()}
732 )
733 })
734 end
735 end
736 end
737 end
738 end
739 end
740
741
742 local function append_projected_arrow_surface(tip_point, tail_point, filloptions, scale, filter, kind)
743 if not is_nonempty_string(filloptions) then
744 return
745 end
746
747 if not (tip_point and tail_point) or tip_point:hdistance(tail_point) <= 1e-12 then
748 return
749 end
750
751 local U = tip_point:hsub(tail_point):hnormalize()
752 local V = U:orthogonal_vector():hnormalize()
753 local W = U:hhypercross(V):hnormalize()
754
755 local transformation_entries = {
756 scale * W[1], scale * W[2], scale * W[3],
757 scale * V[1], scale * V[2], scale * V[3],
758 scale * U[1], scale * U[2], scale * U[3],
759 tip_point[1], tip_point[2], tip_point[3],
760 }
761
762 for _, entry in ipairs(transformation_entries) do
763 if not is_finite_number(entry) then
764 return
765 end
766 end
767
768 local shape_uparams
769 local shape_vparams
770 local shape_v
771
772 if kind == "tail" then
773 shape_uparams = "return Vector:new{0, tau, 6}"
774 shape_vparams = "return Vector:new{pi/2, pi, 2}"
775 shape_v = "return Vector:_new{math.sin(v)*math.cos(u), math.sin(v)*math.sin(u), 0, 1}"
776 else
777 shape_uparams = "return Vector:new{0, 1, 2}"
778 shape_vparams = "return Vector:new{0, 1, 4}"
779 shape_v = "return Vector:_new{u*math.cos(v*tau), u*math.sin(v*tau), -u, 1}"
780 end
781
782 append_surface{
783 uparams = shape_uparams,
784 vparams = shape_vparams,
785 v = shape_v,
786 filloptions = filloptions,
787 transformation = ([[
788 return Matrix:new{
789 {%f,%f,%f,0},{%f,%f,%f,0},{%f,%f,%f,0},{%f,%f,%f,1}
790 }
791 ]]):format(table.unpack(transformation_entries)),
792 filter = filter
793 }
794 end
795
796 -- ================================================================
797 -- Append functions
798 -- ================================================================
799
800 local function append_point(hash)
801 local v = body_expression(hash.v, "appendpoint.v")
802 local transformation = object_expression(hash.transformation, "appendpoint.transformation")
803 local filloptions = options_string_expression(hash.filloptions, "appendpoint.filloptions")
804 local filter = hash.filter
805 if v then
806 local the_simplex = project_point(v, transformation, "appendpoint")
807 if the_simplex then
808 push_simplex({
809 simplex = the_simplex,
810 filloptions = filloptions,
811 type = "point",
812 filter = filter
813 })
814 end
815 end
816 end
817
818 local function append_triangle(hash)
819 local transformation = object_expression(hash.transformation, "appendtriangle.transformation")
820 local filter = hash.filter
821 local filloptions = options_string_expression(hash.filloptions, "appendtriangle.filloptions")
822 assert(hash.m and hash.m ~= "", "appendtriangle.m must return a 3-row Matrix")
823
824 local the_simplex = object_expression(hash.m, "appendtriangle.m")
825 assert(getmetatable(the_simplex) == Matrix, "appendtriangle.m must return a Matrix")
826 assert(#the_simplex == 3, "appendtriangle.m must return a 3-row Matrix")
827
828 local A = Vector:_new(the_simplex[1])
829 local B = Vector:_new(the_simplex[2])
830 local C = Vector:_new(the_simplex[3])
831
832 if not (
833 Geometry.hpoint_point_intersecting(A, B)
834 or Geometry.hpoint_point_intersecting(B, C)
835 or Geometry.hpoint_point_intersecting(C, A)
836 ) then
837 local projected = project_simplex(the_simplex, transformation, "appendtriangle")
838 if projected then
839 push_simplex({
840 simplex = projected,
841 filloptions = filloptions,
842 type = "triangle",
843 filter = filter,
844 shading_normal = triangle_shading_normal(projected)
845 })
846 end
847 end
848 end
849
850 local function append_label(hash)
851 local v = body_expression(hash.v, "appendlabel.v")
852 local filter = hash.filter
853 local text = hash.text
854 local transformation = object_expression(hash.transformation, "appendlabel.transformation")
855 if v then
856 local the_simplex = project_point(v, transformation, "appendlabel")
857 if the_simplex then
858 push_simplex({
859 simplex = the_simplex,
860 text = text,
861 type = "label",
862 filter = filter
863 })
864 end
865 end
866 end
867
868 local function append_light(hash)
869 local v = body_expression(hash.v, "appendlight.v")
870 if v and getmetatable(v) == Vector then
871 table.insert(lua_tikz3dtools.lights, v)
872 else
873 error("Invalid light vector: " .. tostring(v))
874 end
875 end
876
877 local function append_curve(hash)
878 local ustart, ustop, usamples = resolve_axis_params(hash.uparams, "appendcurve.uparams")
879 local transformation = object_expression(hash.transformation, "appendcurve.transformation")
880 local f = single_string_function(hash.v, "appendcurve.v")
881 local filter = hash.filter
882 local drawoptions = options_string_expression(hash.drawoptions, "appendcurve.drawoptions")
883 local arrowoptions = options_string_expression(hash.arrowtip, "appendcurve.arrowtip")
884 local tailoptions = options_string_expression(hash.arrowtail, "appendcurve.arrowtail")
885 local arrowscale = resolve_arrow_scale(hash.arrowscale, "appendcurve.arrowscale", DEFAULT_ARROW_SCALE)
886
887 assert(usamples and usamples >= 2, "usamples must be >= 2, got: " .. tostring(usamples))
888
889 local ustep = (ustop - ustart) / (usamples - 1)
890
891 local function parametric_curve(u)
892 return f(u)
893 end
894
895 for i = 0, usamples - 2 do
896 local u = ustart + i * ustep
897 local A = parametric_curve(u)
898 local B = parametric_curve(u + ustep)
899 if A and B then
900 local simplex = project_simplex(
901 Matrix:_new{A:to_table(), B:to_table()},
902 transformation,
903 "appendcurve.segment"
904 )
905 if simplex then
906 push_simplex({
907 simplex = simplex,
908 drawoptions = drawoptions,
909 type = "line segment",
910 filter = filter
911 })
912 end
913 if i == 0 and is_nonempty_string(tailoptions) then
914 local P = project_point(parametric_curve(ustart), transformation, "appendcurve.arrowtail.start")
915 local Q = project_point(parametric_curve(ustart + ustep), transformation, "appendcurve.arrowtail.stop")
916 append_projected_arrow_surface(P, Q, tailoptions, arrowscale, filter, "tail")
917 end
918 if i == usamples - 2 and is_nonempty_string(arrowoptions) then
919 local P = project_point(parametric_curve(ustop), transformation, "appendcurve.arrowtip.start")
920 local Q = project_point(parametric_curve(ustop - ustep), transformation, "appendcurve.arrowtip.stop")
921 append_projected_arrow_surface(P, Q, arrowoptions, arrowscale, filter, "tip")
922 end
923 end
924 end
925 end
926
927 local function append_solid(hash)
928 local ustart, ustop, usamples = resolve_axis_params(hash.uparams, "appendsolid.uparams")
929 local vstart, vstop, vsamples = resolve_axis_params(hash.vparams, "appendsolid.vparams")
930 local wstart, wstop, wsamples = resolve_axis_params(hash.wparams, "appendsolid.wparams")
931 local filloptions = options_string_expression(hash.filloptions, "appendsolid.filloptions")
932 local filter = hash.filter
933 local transformation = object_expression(hash.transformation, "appendsolid.transformation")
934 local f = triple_string_function(hash.v, "appendsolid.v")
935
936 assert(usamples and usamples >= 2, "usamples must be >= 2, got: " .. tostring(usamples))
937 assert(vsamples and vsamples >= 2, "vsamples must be >= 2, got: " .. tostring(vsamples))
938 assert(wsamples and wsamples >= 2, "wsamples must be >= 2, got: " .. tostring(wsamples))
939
940 local function parametric_solid(u, v, w)
941 return f(u, v, w)
942 end
943
944 local ustep = (ustop - ustart) / (usamples - 1)
945 local vstep = (vstop - vstart) / (vsamples - 1)
946 local wstep = (wstop - wstart) / (wsamples - 1)
947
948 local function tessellate_face(fixed_var, fixed_val, s1_start, s1_step, s1_count, s2_start, s2_step, s2_count)
949 for i = 0, s1_count - 2 do
950 local s1 = s1_start + i * s1_step
951 for j = 0, s2_count - 2 do
952 local s2 = s2_start + j * s2_step
953 local A, B, C, D
954 if fixed_var == "u" then
955 A = parametric_solid(fixed_val, s1, s2)
956 B = parametric_solid(fixed_val, s1 + s1_step, s2)
957 C = parametric_solid(fixed_val, s1 + s1_step, s2 + s2_step)
958 D = parametric_solid(fixed_val, s1, s2 + s2_step)
959 elseif fixed_var == "v" then
960 A = parametric_solid(s1, fixed_val, s2)
961 B = parametric_solid(s1 + s1_step, fixed_val, s2)
962 C = parametric_solid(s1 + s1_step, fixed_val, s2 + s2_step)
963 D = parametric_solid(s1, fixed_val, s2 + s2_step)
964 elseif fixed_var == "w" then
965 A = parametric_solid(s1, s2, fixed_val)
966 B = parametric_solid(s1 + s1_step, s2, fixed_val)
967 C = parametric_solid(s1 + s1_step, s2 + s2_step, fixed_val)
968 D = parametric_solid(s1, s2 + s2_step, fixed_val)
969 end
970 if A and B and D then
971 local simplex = project_simplex(
972 Matrix:_new{A:to_table(), B:to_table(), D:to_table()},
973 transformation,
974 "appendsolid.face1"
975 )
976 if simplex then
977 push_simplex({
978 simplex = simplex,
979 filloptions = filloptions,
980 type = "triangle",
981 filter = filter,
982 shading_normal = triangle_shading_normal(simplex)
983 })
984 end
985 end
986 if B and C and D then
987 local simplex = project_simplex(
988 Matrix:_new{B:to_table(), C:to_table(), D:to_table()},
989 transformation,
990 "appendsolid.face2"
991 )
992 if simplex then
993 push_simplex({
994 simplex = simplex,
995 filloptions = filloptions,
996 type = "triangle",
997 filter = filter,
998 shading_normal = triangle_shading_normal(simplex)
999 })
1000 end
1001 end
1002 end
1003 end
1004 end
1005
1006 tessellate_face("u", ustart, vstart, vstep, vsamples, wstart, wstep, wsamples)
1007 tessellate_face("u", ustop, vstart, vstep, vsamples, wstart, wstep, wsamples)
1008 tessellate_face("v", vstart, ustart, ustep, usamples, wstart, wstep, wsamples)
1009 tessellate_face("v", vstop, ustart, ustep, usamples, wstart, wstep, wsamples)
1010 tessellate_face("w", wstart, ustart, ustep, usamples, vstart, vstep, vsamples)
1011 tessellate_face("w", wstop, ustart, ustep, usamples, vstart, vstep, vsamples)
1012 end
1013
1014 -- ================================================================
1015 -- Filters (sandboxed)
1016 -- ================================================================
1017
1018 local function apply_filters(simplices)
1019 local new_simplices = {}
1020
1021 for _, simplex in ipairs(simplices) do
1022 local bindings = {}
1023
1024 if simplex.type == "point" then
1025 bindings.A = Vector:_new(simplex.simplex:to_table())
1026 elseif simplex.type == "line segment" then
1027 bindings.A = Vector:_new(simplex.simplex[1])
1028 bindings.B = Vector:_new(simplex.simplex[2])
1029 elseif simplex.type == "triangle" then
1030 bindings.A = Vector:_new(simplex.simplex[1])
1031 bindings.B = Vector:_new(simplex.simplex[2])
1032 bindings.C = Vector:_new(simplex.simplex[3])
1033 elseif simplex.type == "label" then
1034 bindings.A = Vector:_new(simplex.simplex:to_table())
1035 end
1036
1037 local filter_body = simplex.filter or "return true"
1038 local filter_label = ("filter[%s]"):format(simplex.type)
1039 local filter_fn = evaluate_chunk(
1040 ("return function()\n%s\nend"):format(filter_body),
1041 filter_label,
1042 bindings
1043 )
1044
1045 if wrap_user_function(filter_fn, filter_label, filter_body)() then
1046 table.insert(new_simplices, simplex)
1047 end
1048 end
1049
1050 return new_simplices
1051 end
1052
1053 -- ================================================================
1054 -- Display / render
1055 -- ================================================================
1056
1057 local function display_simplices()
1058 print("Time:" .. os.date("%X") .. " Displaying " .. #lua_tikz3dtools.simplices .. " simplices.")
1059
1060 -- Pre-compute bbox2 for all simplices
1061 for _, s in ipairs(lua_tikz3dtools.simplices) do
1062 if s.type ~= "point" and s.type ~= "label" then
1063 s.bbox2 = s.simplex:get_bbox2()
1064 end
1065 end
1066
1067 lua_tikz3dtools.simplices = Geometry.partition_simplices_by_parents(
1068 lua_tikz3dtools.simplices,
1069 lua_tikz3dtools.simplices
1070 )
1071 print("Time:" .. os.date("%X") .. " After partitioning, " .. #lua_tikz3dtools.simplices .. " simplices remain.")
1072
1073 lua_tikz3dtools.simplices = apply_filters(lua_tikz3dtools.simplices)
1074 print("Time:" .. os.date("%X") .. " After filtering, " .. #lua_tikz3dtools.simplices .. " simplices remain.")
1075
1076 -- Re-compute bbox2 after filtering (some simplices removed)
1077 for _, s in ipairs(lua_tikz3dtools.simplices) do
1078 if s.type ~= "point" and s.type ~= "label" and not s.bbox2 then
1079 s.bbox2 = s.simplex:get_bbox2()
1080 end
1081 end
1082
1083 lua_tikz3dtools.simplices = Geometry.scc(lua_tikz3dtools.simplices)
1084 print("Time:" .. os.date("%X") .. " After occlusion sorting, " .. #lua_tikz3dtools.simplices .. " simplices remain.")
1085
1086 local labels = {}
1087 for _, simplex in ipairs(lua_tikz3dtools.simplices) do
1088 if simplex.type == "point" then
1089 tex.sprint(
1090 ("\\path[%s] (%f,%f) circle[radius = 0.06];")
1091 :format(simplex.filloptions, simplex.simplex[1], simplex.simplex[2])
1092 )
1093 elseif simplex.type == "line segment" then
1094 tex.sprint(
1095 ("\\path[%s] (%f,%f) -- (%f,%f);")
1096 :format(
1097 simplex.drawoptions,
1098 simplex.simplex[1][1], simplex.simplex[1][2],
1099 simplex.simplex[2][1], simplex.simplex[2][2]
1100 )
1101 )
1102 elseif simplex.type == "triangle" then
1103 local num_lights = #lua_tikz3dtools.lights
1104 if num_lights > 0 then
1105 local normal = simplex.shading_normal or triangle_shading_normal(simplex.simplex)
1106
1107 local total_intensity = 0
1108 if normal then
1109 for _, light in ipairs(lua_tikz3dtools.lights) do
1110 local light_dir = light:hnormalize()
1111 local facing_normal = light_facing_normal(normal, light_dir)
1112 local cos_theta = facing_normal:hinner(light_dir)
1113 if cos_theta > 1 then cos_theta = 1 end
1114 -- Linear falloff: 0° → 1.0, 90° → 0.0
1115 local theta = math.deg(math.acos(cos_theta))
1116 total_intensity = total_intensity + (1 - theta / 90)
1117 end
1118 end
1119
1120 local avg_intensity = math.floor((total_intensity / num_lights) * 100 + 0.01)
1121 tex.sprint(("\\colorlet{ltdtbrightness}{white!%f!black}"):format(avg_intensity))
1122 else
1123 tex.sprint(("\\colorlet{ltdtbrightness}{white!%f!black}"):format(0))
1124 end
1125
1126 tex.sprint(
1127 ("\\path[%s] (%f,%f) -- (%f,%f) -- (%f,%f) -- cycle;")
1128 :format(
1129 simplex.filloptions,
1130 simplex.simplex[1][1], simplex.simplex[1][2],
1131 simplex.simplex[2][1], simplex.simplex[2][2],
1132 simplex.simplex[3][1], simplex.simplex[3][2]
1133 )
1134 )
1135 render_embedded_segments(simplex)
1136 elseif simplex.type == "label" then
1137 table.insert(labels, simplex)
1138 end
1139 end
1140
1141 for _, simplex in ipairs(labels) do
1142 tex.sprint(
1143 ("\\node at (%f,%f) {%s};")
1144 :format(simplex.simplex[1], simplex.simplex[2], simplex.text)
1145 )
1146 end
1147
1148 lua_tikz3dtools.simplices = {}
1149 lua_tikz3dtools.lights = {}
1150 end
1151
1152 -- ================================================================
1153 -- set_object
1154 -- ================================================================
1155
1156 local function set_object(hash)
1157 local object = object_expression(hash.object, "setobject.object")
1158 local name = hash.name
1159
1160 assert(type(name) == "string" and name ~= "", "setobject.name must be a non-empty string")
1161 assert(lua_tikz3dtools.base_env[name] == nil,
1162 ("setobject.name '%s' is reserved and cannot be rebound"):format(name))
1163
1164 lua_tikz3dtools.objects[name] = object
1165 return object
1166 end
1167
1168 -- ================================================================
1169 -- Register all TeX commands
1170 -- ================================================================
1171
1172 --- Read a TeX macro, returning a fallback if undefined.
1173 local function get_macro_or(name, fallback)
1174 local val = token.get_macro(name)
1175 if val == nil or val == "" then return fallback end
1176 return val
1177 end
1178
1179 function Scene.register_commands()
1180 register_tex_cmd("appendpoint", function()
1181 append_point{
1182 v = token.get_macro("luatikztdtools@p@p@v"),
1183 filloptions = get_macro_or("luatikztdtools@p@p@filloptions", "return \"\""),
1184 transformation = get_macro_or("luatikztdtools@p@p@transformation", "return Matrix.identity()"),
1185 filter = get_macro_or("luatikztdtools@p@p@filter", "return true")
1186 }
1187 end, { })
1188
1189 register_tex_cmd("appendsurface", function()
1190 append_surface{
1191 uparams = get_macro_or("luatikztdtools@p@s@uparams", "return Vector:new{0,1,10}"),
1192 vparams = get_macro_or("luatikztdtools@p@s@vparams", "return Vector:new{0,1,10}"),
1193 v = token.get_macro("luatikztdtools@p@s@v"),
1194 curve = token.get_macro("luatikztdtools@p@s@curve"),
1195 transformation = get_macro_or("luatikztdtools@p@s@transformation", "return Matrix.identity()"),
1196 filloptions = get_macro_or("luatikztdtools@p@s@filloptions", "return \"\""),
1197 filter = get_macro_or("luatikztdtools@p@s@filter", "return true"),
1198 }
1199 end, { })
1200
1201 register_tex_cmd("appendtriangle", function()
1202 append_triangle{
1203 m = token.get_macro("luatikztdtools@p@t@m"),
1204 transformation = get_macro_or("luatikztdtools@p@t@transformation", "return Matrix.identity()"),
1205 filloptions = get_macro_or("luatikztdtools@p@t@filloptions", "return \"\""),
1206 filter = get_macro_or("luatikztdtools@p@t@filter", "return true"),
1207 }
1208 end, { })
1209
1210 register_tex_cmd("appendlabel", function()
1211 append_label{
1212 v = token.get_macro("luatikztdtools@p@l@v"),
1213 text = token.get_macro("luatikztdtools@p@l@text"),
1214 transformation = get_macro_or("luatikztdtools@p@l@transformation", "return Matrix.identity()"),
1215 filter = get_macro_or("luatikztdtools@p@l@filter", "return true")
1216 }
1217 end, { })
1218
1219 register_tex_cmd("appendlight", function()
1220 append_light{
1221 v = token.get_macro("luatikztdtools@p@la@v")
1222 }
1223 end, { })
1224
1225 register_tex_cmd("appendcurve", function()
1226 append_curve{
1227 uparams = get_macro_or("luatikztdtools@p@c@uparams", "return Vector:new{0,1,10}"),
1228 v = token.get_macro("luatikztdtools@p@c@v"),
1229 transformation = get_macro_or("luatikztdtools@p@c@transformation", "return Matrix.identity()"),
1230 drawoptions = get_macro_or("luatikztdtools@p@c@drawoptions", "return \"\""),
1231 arrowtip = get_macro_or("luatikztdtools@p@c@arrowtip", "return \"\""),
1232 arrowtail = get_macro_or("luatikztdtools@p@c@arrowtail", "return \"\""),
1233 arrowscale = token.get_macro("luatikztdtools@p@c@arrowscale"),
1234 filter = get_macro_or("luatikztdtools@p@c@filter", "return true")
1235 }
1236 end, { })
1237
1238 register_tex_cmd("appendsolid", function()
1239 append_solid{
1240 uparams = get_macro_or("luatikztdtools@p@solid@uparams", "return Vector:new{0,1,10}"),
1241 vparams = get_macro_or("luatikztdtools@p@solid@vparams", "return Vector:new{0,1,10}"),
1242 wparams = get_macro_or("luatikztdtools@p@solid@wparams", "return Vector:new{0,1,10}"),
1243 v = token.get_macro("luatikztdtools@p@solid@v"),
1244 transformation = get_macro_or("luatikztdtools@p@solid@transformation", "return Matrix.identity()"),
1245 filloptions = get_macro_or("luatikztdtools@p@solid@filloptions", "return \"\""),
1246 filter = get_macro_or("luatikztdtools@p@solid@filter", "return true")
1247 }
1248 end, { })
1249
1250 register_tex_cmd("displaysimplices", function()
1251 display_simplices()
1252 end, { })
1253
1254 register_tex_cmd("setobject", function()
1255 set_object{
1256 name = token.get_macro("luatikztdtools@p@m@name"),
1257 object = token.get_macro("luatikztdtools@p@m@object"),
1258 }
1259 end, { })
1260 end
1261
1262 return Scene