Skip to content
Navigation Menu
{{ message }}
forked from rive-app/rive-runtime
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrive_lua_libs.cpp
More file actions
1107 lines (1005 loc) · 35.2 KB
/
Copy pathrive_lua_libs.cpp
File metadata and controls
1107 lines (1005 loc) · 35.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#ifdef WITH_RIVE_SCRIPTING
#include "rive/lua/rive_lua_libs.hpp"
#include "rive/assets/script_asset.hpp"
#include "rive/async/work_pool.hpp"
#ifdef RIVE_CANVAS
#include "rive/renderer/render_context.hpp"
#endif
#include "lualib.h"
#include <stdio.h>
#include <unordered_map>
#include <unordered_set>
#include <string>
#include <queue>
#include <vector>
#include <algorithm>
using namespace rive;
int luaopen_rive_base(lua_State* L);
int luaopen_rive_math(lua_State* L);
int luaopen_rive_renderer_library(lua_State* L);
int luaopen_rive_properties(lua_State* L);
int luaopen_rive_artboards(lua_State* L);
int luaopen_rive_data_values(lua_State* L);
int luaopen_rive_data_context(lua_State* L);
int luaopen_rive_input(lua_State* L);
int luaopen_rive_contex(lua_State* L);
int luaopen_rive_audio(lua_State* L);
extern "C" int luaopen_rive_buffer_ext(lua_State* L);
std::unordered_map<std::string, int16_t> atoms = {
{"length", (int16_t)LuaAtoms::length},
{"lengthSquared", (int16_t)LuaAtoms::lengthSquared},
{"normalized", (int16_t)LuaAtoms::normalized},
{"distance", (int16_t)LuaAtoms::distance},
{"distanceSquared", (int16_t)LuaAtoms::distanceSquared},
{"dot", (int16_t)LuaAtoms::dot},
{"lerp", (int16_t)LuaAtoms::lerp},
{"moveTo", (int16_t)LuaAtoms::moveTo},
{"lineTo", (int16_t)LuaAtoms::lineTo},
{"quadTo", (int16_t)LuaAtoms::quadTo},
{"cubicTo", (int16_t)LuaAtoms::cubicTo},
{"close", (int16_t)LuaAtoms::close},
{"type", (int16_t)LuaAtoms::type},
{"reset", (int16_t)LuaAtoms::reset},
{"add", (int16_t)LuaAtoms::add},
{"contours", (int16_t)LuaAtoms::contours},
{"measure", (int16_t)LuaAtoms::measure},
{"invert", (int16_t)LuaAtoms::invert},
{"isIdentity", (int16_t)LuaAtoms::isIdentity},
{"width", (int16_t)LuaAtoms::width},
{"height", (int16_t)LuaAtoms::height},
{"clamp", (int16_t)LuaAtoms::clamp},
{"repeat", (int16_t)LuaAtoms::repeat},
{"mirror", (int16_t)LuaAtoms::mirror},
{"bilinear", (int16_t)LuaAtoms::bilinear},
{"nearest", (int16_t)LuaAtoms::nearest},
{"style", (int16_t)LuaAtoms::style},
{"join", (int16_t)LuaAtoms::join},
{"cap", (int16_t)LuaAtoms::cap},
{"thickness", (int16_t)LuaAtoms::thickness},
{"blendMode", (int16_t)LuaAtoms::blendMode},
{"feather", (int16_t)LuaAtoms::feather},
{"gradient", (int16_t)LuaAtoms::gradient},
{"color", (int16_t)LuaAtoms::color},
{"stroke", (int16_t)LuaAtoms::stroke},
{"fill", (int16_t)LuaAtoms::fill},
{"miter", (int16_t)LuaAtoms::miter},
{"round", (int16_t)LuaAtoms::round},
{"bevel", (int16_t)LuaAtoms::bevel},
{"butt", (int16_t)LuaAtoms::butt},
{"square", (int16_t)LuaAtoms::square},
{"srcOver", (int16_t)LuaAtoms::srcOver},
{"screen", (int16_t)LuaAtoms::screen},
{"overlay", (int16_t)LuaAtoms::overlay},
{"darken", (int16_t)LuaAtoms::darken},
{"lighten", (int16_t)LuaAtoms::lighten},
{"colorDodge", (int16_t)LuaAtoms::colorDodge},
{"colorBurn", (int16_t)LuaAtoms::colorBurn},
{"hardLight", (int16_t)LuaAtoms::hardLight},
{"softLight", (int16_t)LuaAtoms::softLight},
{"difference", (int16_t)LuaAtoms::difference},
{"exclusion", (int16_t)LuaAtoms::exclusion},
{"multiply", (int16_t)LuaAtoms::multiply},
{"hue", (int16_t)LuaAtoms::hue},
{"saturation", (int16_t)LuaAtoms::saturation},
{"luminosity", (int16_t)LuaAtoms::luminosity},
{"copy", (int16_t)LuaAtoms::copy},
{"drawPath", (int16_t)LuaAtoms::drawPath},
{"drawImage", (int16_t)LuaAtoms::drawImage},
{"drawImageMesh", (int16_t)LuaAtoms::drawImageMesh},
{"clipPath", (int16_t)LuaAtoms::clipPath},
{"save", (int16_t)LuaAtoms::save},
{"restore", (int16_t)LuaAtoms::restore},
{"transform", (int16_t)LuaAtoms::transform},
{"value", (int16_t)LuaAtoms::value},
{"red", (int16_t)LuaAtoms::red},
{"green", (int16_t)LuaAtoms::green},
{"blue", (int16_t)LuaAtoms::blue},
{"alpha", (int16_t)LuaAtoms::alpha},
{"getNumber", (int16_t)LuaAtoms::getNumber},
{"getTrigger", (int16_t)LuaAtoms::getTrigger},
{"getString", (int16_t)LuaAtoms::getString},
{"getBoolean", (int16_t)LuaAtoms::getBoolean},
{"getColor", (int16_t)LuaAtoms::getColor},
{"getList", (int16_t)LuaAtoms::getList},
{"getViewModel", (int16_t)LuaAtoms::getViewModel},
{"getEnum", (int16_t)LuaAtoms::getEnum},
{"getIndex", (int16_t)LuaAtoms::getIndex},
{"getImage", (int16_t)LuaAtoms::getImage},
{"values", (int16_t)LuaAtoms::values},
{"addListener", (int16_t)LuaAtoms::addListener},
{"removeListener", (int16_t)LuaAtoms::removeListener},
{"fire", (int16_t)LuaAtoms::fire},
{"push", (int16_t)LuaAtoms::push},
{"insert", (int16_t)LuaAtoms::insert},
{"pop", (int16_t)LuaAtoms::pop},
{"swap", (int16_t)LuaAtoms::swap},
{"shift", (int16_t)LuaAtoms::shift},
{"clear", (int16_t)LuaAtoms::clear},
{"draw", (int16_t)LuaAtoms::draw},
{"advance", (int16_t)LuaAtoms::advance},
{"frameOrigin", (int16_t)LuaAtoms::frameOrigin},
{"data", (int16_t)LuaAtoms::data},
{"instance", (int16_t)LuaAtoms::instance},
{"animation", (int16_t)LuaAtoms::animation},
{"new", (int16_t)LuaAtoms::newAtom},
{"bounds", (int16_t)LuaAtoms::bounds},
{"pointerDown", (int16_t)LuaAtoms::pointerDown},
{"pointerUp", (int16_t)LuaAtoms::pointerUp},
{"pointerMove", (int16_t)LuaAtoms::pointerMove},
{"pointerExit", (int16_t)LuaAtoms::pointerExit},
{"isNumber", (int16_t)LuaAtoms::isNumber},
{"isString", (int16_t)LuaAtoms::isString},
{"isBoolean", (int16_t)LuaAtoms::isBoolean},
{"isColor", (int16_t)LuaAtoms::isColor},
{"hit", (int16_t)LuaAtoms::hit},
{"id", (int16_t)LuaAtoms::id},
{"position", (int16_t)LuaAtoms::position},
{"rotation", (int16_t)LuaAtoms::rotation},
{"scale", (int16_t)LuaAtoms::scale},
{"worldTransform", (int16_t)LuaAtoms::worldTransform},
{"scaleX", (int16_t)LuaAtoms::scaleX},
{"scaleY", (int16_t)LuaAtoms::scaleY},
{"decompose", (int16_t)LuaAtoms::decompose},
{"children", (int16_t)LuaAtoms::children},
{"parent", (int16_t)LuaAtoms::parent},
{"node", (int16_t)LuaAtoms::node},
{"paint", (int16_t)LuaAtoms::paint},
{"asPath", (int16_t)LuaAtoms::asPath},
{"asPaint", (int16_t)LuaAtoms::asPaint},
{"addToPath", (int16_t)LuaAtoms::addToPath},
{"positionAndTangent", (int16_t)LuaAtoms::positionAndTangent},
{"warp", (int16_t)LuaAtoms::warp},
{"extract", (int16_t)LuaAtoms::extract},
{"next", (int16_t)LuaAtoms::next},
{"isClosed", (int16_t)LuaAtoms::isClosed},
{"markNeedsUpdate", (int16_t)LuaAtoms::markNeedsUpdate},
{"viewModel", (int16_t)LuaAtoms::viewModel},
{"rootViewModel", (int16_t)LuaAtoms::rootViewModel},
{"dataContext", (int16_t)LuaAtoms::dataContext},
{"image", (int16_t)LuaAtoms::image},
{"blob", (int16_t)LuaAtoms::blob},
{"size", (int16_t)LuaAtoms::size},
{"duration", (int16_t)LuaAtoms::duration},
{"setTime", (int16_t)LuaAtoms::setTime},
{"setTimeFrames", (int16_t)LuaAtoms::setTimeFrames},
{"setTimePercentage", (int16_t)LuaAtoms::setTimePercentage},
{"isPointerEvent", (int16_t)LuaAtoms::isPointerEvent},
{"isKeyboardEvent", (int16_t)LuaAtoms::isKeyboardEvent},
{"isTextInput", (int16_t)LuaAtoms::isTextInput},
{"previousPosition", (int16_t)LuaAtoms::previousPosition},
{"timeStamp", (int16_t)LuaAtoms::timeStamp},
{"isFocus", (int16_t)LuaAtoms::isFocus},
{"isReportedEvent", (int16_t)LuaAtoms::isReportedEvent},
{"isViewModelChange", (int16_t)LuaAtoms::isViewModelChange},
{"isNone", (int16_t)LuaAtoms::isNone},
{"isGamepadConnected", (int16_t)LuaAtoms::isGamepadConnected},
{"isGamepadEvent", (int16_t)LuaAtoms::isGamepadEvent},
{"isGamepadDisconnected", (int16_t)LuaAtoms::isGamepadDisconnected},
{"asPointerEvent", (int16_t)LuaAtoms::asPointerEvent},
{"asKeyboardEvent", (int16_t)LuaAtoms::asKeyboardEvent},
{"asTextInput", (int16_t)LuaAtoms::asTextInput},
{"asFocus", (int16_t)LuaAtoms::asFocus},
{"asReportedEvent", (int16_t)LuaAtoms::asReportedEvent},
{"asViewModelChange", (int16_t)LuaAtoms::asViewModelChange},
{"asGamepadConnected", (int16_t)LuaAtoms::asGamepadConnected},
{"asGamepadEvent", (int16_t)LuaAtoms::asGamepadEvent},
{"asGamepadDisconnected", (int16_t)LuaAtoms::asGamepadDisconnected},
{"gamepadEvent", (int16_t)LuaAtoms::gamepadEvent},
{"gamepadConnected", (int16_t)LuaAtoms::gamepadConnected},
{"gamepadDisconnected", (int16_t)LuaAtoms::gamepadDisconnected},
{"asNone", (int16_t)LuaAtoms::asNone},
{"key", (int16_t)LuaAtoms::key},
{"shift", (int16_t)LuaAtoms::shift},
{"alt", (int16_t)LuaAtoms::alt},
{"control", (int16_t)LuaAtoms::control},
{"meta", (int16_t)LuaAtoms::meta},
{"text", (int16_t)LuaAtoms::text},
{"phase", (int16_t)LuaAtoms::phase},
{"delaySeconds", (int16_t)LuaAtoms::delaySeconds},
{"deviceId", (int16_t)LuaAtoms::deviceId},
{"buttonMask", (int16_t)LuaAtoms::buttonMask},
{"remove", (int16_t)LuaAtoms::remove},
{"removeAt", (int16_t)LuaAtoms::removeAt},
{"removeAllOf", (int16_t)LuaAtoms::removeAllOf},
{"axes", (int16_t)LuaAtoms::axes},
{"gamepadMapping", (int16_t)LuaAtoms::gamepadMapping},
{"mapping", (int16_t)LuaAtoms::mapping},
{"isStandardMapping", (int16_t)LuaAtoms::isStandardMapping},
{"buttons", (int16_t)LuaAtoms::buttons},
{"buttonPressed", (int16_t)LuaAtoms::buttonPressed},
{"buttonValue", (int16_t)LuaAtoms::buttonValue},
{"axis", (int16_t)LuaAtoms::axis},
{"west", (int16_t)LuaAtoms::west},
{"south", (int16_t)LuaAtoms::south},
{"north", (int16_t)LuaAtoms::north},
{"east", (int16_t)LuaAtoms::east},
{"leftShoulder", (int16_t)LuaAtoms::leftShoulder},
{"rightShoulder", (int16_t)LuaAtoms::rightShoulder},
{"back", (int16_t)LuaAtoms::gamepadBack},
{"forward", (int16_t)LuaAtoms::gamepadForward},
{"leftStickButton", (int16_t)LuaAtoms::leftStickButton},
{"rightStickButton", (int16_t)LuaAtoms::rightStickButton},
{"dpadUp", (int16_t)LuaAtoms::dpadUp},
{"dpadDown", (int16_t)LuaAtoms::dpadDown},
{"dpadLeft", (int16_t)LuaAtoms::dpadLeft},
{"dpadRight", (int16_t)LuaAtoms::dpadRight},
{"start", (int16_t)LuaAtoms::start},
{"leftStick", (int16_t)LuaAtoms::leftStick},
{"rightStick", (int16_t)LuaAtoms::rightStick},
{"leftTrigger", (int16_t)LuaAtoms::leftTrigger},
{"rightTrigger", (int16_t)LuaAtoms::rightTrigger},
{"leftTriggerPressed", (int16_t)LuaAtoms::leftTriggerPressed},
{"rightTriggerPressed", (int16_t)LuaAtoms::rightTriggerPressed},
{"changeKind", (int16_t)LuaAtoms::changeKind},
{"changeIndex", (int16_t)LuaAtoms::changeIndex},
{"changeValue", (int16_t)LuaAtoms::changeValue},
{"hasStandardButtonIntent", (int16_t)LuaAtoms::hasStandardButtonIntent},
{"hasStandardAxisIntent", (int16_t)LuaAtoms::hasStandardAxisIntent},
{"intentButton", (int16_t)LuaAtoms::intentButton},
{"intentAxis", (int16_t)LuaAtoms::intentAxis},
{"audio", (int16_t)LuaAtoms::audio},
{"play", (int16_t)LuaAtoms::play},
{"playAtTime", (int16_t)LuaAtoms::playAtTime},
{"playInTime", (int16_t)LuaAtoms::playInTime},
{"playAtFrame", (int16_t)LuaAtoms::playAtFrame},
{"playInFrame", (int16_t)LuaAtoms::playInFrame},
{"stop", (int16_t)LuaAtoms::stop},
{"pause", (int16_t)LuaAtoms::pause},
{"resume", (int16_t)LuaAtoms::resume},
{"seek", (int16_t)LuaAtoms::seek},
{"seekFrame", (int16_t)LuaAtoms::seekFrame},
{"volume", (int16_t)LuaAtoms::volume},
{"completed", (int16_t)LuaAtoms::completed},
{"time", (int16_t)LuaAtoms::time},
{"timeFrame", (int16_t)LuaAtoms::timeFrame},
{"sampleRate", (int16_t)LuaAtoms::sampleRate},
// GPU
{"write", (int16_t)LuaAtoms::write},
{"upload", (int16_t)LuaAtoms::upload},
{"view", (int16_t)LuaAtoms::view},
{"setPipeline", (int16_t)LuaAtoms::setPipeline},
{"setVertexBuffer", (int16_t)LuaAtoms::setVertexBuffer},
{"setIndexBuffer", (int16_t)LuaAtoms::setIndexBuffer},
{"setBindGroup", (int16_t)LuaAtoms::setBindGroup},
{"setViewport", (int16_t)LuaAtoms::setViewport},
{"setScissorRect", (int16_t)LuaAtoms::setScissorRect},
{"setStencilReference", (int16_t)LuaAtoms::setStencilReference},
{"drawIndexed", (int16_t)LuaAtoms::drawIndexed},
{"finish", (int16_t)LuaAtoms::finish},
{"beginRenderPass", (int16_t)LuaAtoms::beginRenderPass},
{"beginFrame", (int16_t)LuaAtoms::beginFrame},
{"endFrame", (int16_t)LuaAtoms::endFrame},
{"colorView", (int16_t)LuaAtoms::colorView},
{"depthView", (int16_t)LuaAtoms::depthView},
{"setBlendColor", (int16_t)LuaAtoms::setBlendColor},
{"resize", (int16_t)LuaAtoms::resize},
{"canvas", (int16_t)LuaAtoms::canvas},
{"gpuCanvas", (int16_t)LuaAtoms::gpuCanvas},
{"features", (int16_t)LuaAtoms::features},
{"drawCanvas", (int16_t)LuaAtoms::drawCanvas},
{"shader", (int16_t)LuaAtoms::shader},
{"format", (int16_t)LuaAtoms::format},
{"andThen", (int16_t)LuaAtoms::andThen},
{"catch", (int16_t)LuaAtoms::catch_},
{"finally", (int16_t)LuaAtoms::finally_},
{"cancel", (int16_t)LuaAtoms::cancel},
{"onCancel", (int16_t)LuaAtoms::onCancel},
{"getStatus", (int16_t)LuaAtoms::getStatus},
{"decodeImage", (int16_t)LuaAtoms::decodeImage},
// Mat4
{"transpose", (int16_t)LuaAtoms::transpose},
{"transformPoint", (int16_t)LuaAtoms::transformPoint},
{"transformVec4", (int16_t)LuaAtoms::transformVec4},
{"writeToBuffer", (int16_t)LuaAtoms::writeToBuffer},
{"invertAffine", (int16_t)LuaAtoms::invertAffine},
};
static const luaL_Reg lualibs[] = {
{"", luaopen_base},
{LUA_TABLIBNAME, luaopen_table},
{LUA_MATHLIBNAME, luaopen_math},
{"rive", luaopen_rive_base},
{LUA_OSLIBNAME, luaopen_os},
{LUA_STRLIBNAME, luaopen_string},
{LUA_UTF8LIBNAME, luaopen_utf8},
{LUA_BUFFERLIBNAME, luaopen_buffer},
{LUA_BITLIBNAME, luaopen_bit32},
{"math", luaopen_rive_math},
{"renderer", luaopen_rive_renderer_library},
{"properties", luaopen_rive_properties},
{"artboard", luaopen_rive_artboards},
{"dataValue", luaopen_rive_data_values},
{"input", luaopen_rive_input},
{"context", luaopen_rive_contex},
{"dataContext", luaopen_rive_data_context},
{"audio", luaopen_rive_audio},
{"promise", luaopen_rive_promise},
{NULL, NULL},
};
namespace rive
{
int luaopen_rive(lua_State* L)
{
lua_callbacks(L)->useratom =
[](lua_State*, const char* s, size_t l) -> int16_t {
auto itr = atoms.find(s);
if (itr != atoms.end())
{
return itr->second;
}
return -1;
};
const luaL_Reg* lib = lualibs;
for (; lib->func; lib++)
{
lua_pushcfunction(L, lib->func, NULL);
lua_pushstring(L, lib->name);
lua_call(L, 1, 0);
}
// Extend the buffer library with SIMD-accelerated functions
// (readf16, writef16, stridedcopy, convert).
luaopen_rive_buffer_ext(L);
return 0;
}
int rive_luaErrorHandler(lua_State* L)
{
ScriptingContext* context =
static_cast<ScriptingContext*>(lua_getthreaddata(L));
context->printError(L);
// Optionally, you can push a new value onto the stack to be returned by
// lua_pcall For example, push a specific error code or a more detailed
// message
const char* error = lua_tostring(L, -1);
lua_pushstring(L, error);
return 1; // Number of return values
// return 0;
}
int rive_lua_pcall(lua_State* state, int nargs, int nresults)
{
ScriptingContext* context =
static_cast<ScriptingContext*>(lua_getthreaddata(state));
int ret = context->pCall(state, nargs, nresults);
#ifdef RIVE_ORE
rive_lua_closeOrphanRenderPass(state);
#endif
return ret;
}
int rive_lua_pcall_with_context(lua_State* state,
ScriptedObject* scriptedObject,
int nargs,
int nresults)
{
ScriptingContext* context =
static_cast<ScriptingContext*>(lua_getthreaddata(state));
ScopedScriptedObjectContext scope(context, scriptedObject);
int ret = context->pCall(state, nargs, nresults);
#ifdef RIVE_ORE
rive_lua_closeOrphanRenderPass(state);
#endif
return ret;
}
int rive_lua_pushRef(lua_State* state, int ref)
{
lua_checkstack(state, 1);
return lua_rawgeti(state, luaRegistryIndex, ref);
}
void rive_lua_pop(lua_State* state, int count)
{
lua_settop(state, -count - 1);
}
static void* l_alloc(void* ud, void* ptr, size_t osize, size_t nsize)
{
(void)ud;
(void)osize;
if (nsize == 0)
{
free(ptr);
// delete[] (uint8_t*)ptr;
return NULL;
}
else
{
// auto nptr = new uint8_t[nsize];
// memcpy(nptr, ptr, std::min(nsize, osize));
// delete[] (uint8_t*)ptr;
// return nptr;
return realloc(ptr, nsize);
}
}
static const char* registeredCacheTableKey = "_MODULES";
static int checkRegisteredModules(lua_State* L, const char* path)
{
luaL_findtable(L, LUA_REGISTRYINDEX, registeredCacheTableKey, 1);
lua_getfield(L, -1, path);
if (lua_isnil(L, -1))
{
lua_pop(L, 2);
return 0;
}
lua_remove(L, -2);
return 1;
}
static int lua_requireinternal(lua_State* L, const char* requirerChunkname)
{
// Discard extra arguments, we only use path
lua_settop(L, 1);
const char* path = luaL_checkstring(L, 1);
if (checkRegisteredModules(L, path) == 1)
{
return 1;
}
// Record missing dependency if we're registering a module
if (requirerChunkname)
{
ScriptingContext* context =
static_cast<ScriptingContext*>(lua_getthreaddata(L));
if (context)
{
context->recordMissingDependency(requirerChunkname, path);
}
}
luaL_error(L, "require could not find a script named %s", path);
return 0;
}
static int lua_require(lua_State* L)
{
lua_Debug ar;
int level = 1;
do
{
if (!lua_getinfo(L, level++, "s", &ar))
{
luaL_error(L, "require is not supported in this context");
}
} while (ar.what[0] == 'C');
return lua_requireinternal(L, ar.source);
}
static int luaR_error(lua_State* L)
{
int level = luaL_optinteger(L, 2, 1);
lua_settop(L, 1);
if (lua_isstring(L, 1) && level > 0)
{
luaL_where(L, level);
lua_pushvalue(L, 1);
lua_concat(L, 2);
}
lua_error(L);
}
static int lua_late(lua_State* L)
{
lua_pushnil(L);
return 1;
}
void ScriptingVM::init(lua_State* state, ScriptingContext* context)
{
luaopen_rive(state);
lua_setthreaddata(state, context);
lua_pushcclosurek(state, lua_require, "require", 0, nullptr);
lua_setglobal(state, "require");
lua_pushcclosurek(state, luaR_error, "error", 0, nullptr);
lua_setglobal(state, "error");
lua_pushcclosurek(state, lua_late, "late", 0, nullptr);
lua_setglobal(state, "late");
luaL_sandbox(state);
luaL_sandboxthread(state);
}
ScriptingVM::ScriptingVM(std::unique_ptr<ScriptingContext> context) :
m_ownedContext(std::move(context))
{
m_state = lua_newstate(l_alloc, nullptr);
init(m_state, m_ownedContext.get());
}
ScriptingVM::~ScriptingVM() { closeLuaState(); }
void ScriptingVM::closeLuaState()
{
if (m_state == nullptr)
{
return;
}
// Cancel async tasks before closing Lua state to prevent callbacks
// from accessing dead state.
if (m_ownedContext)
m_ownedContext->shutdownAsyncForState(m_state);
// Null every registered ScriptedObject's back-pointer before the lua
// teardown cascade. Once m_vm is gone, ScriptedObject::state() returns
// nullptr, so scriptDispose() (called from cascading destruction inside
// lua_close) skips its lua_unref / disposeScriptedContext calls. Those
// calls would otherwise dereference Lua userdatas (ScriptedContext, ref
// tables) that lua_close has already freed in earlier sweep iterations.
for (ScriptedObject* obj : m_scriptedObjects)
{
obj->m_vm = nullptr;
}
m_scriptedObjects.clear();
lua_State* state = m_state;
m_state = nullptr;
lua_close(state);
}
void ScriptingVM::registerScriptedObject(ScriptedObject* obj)
{
if (obj != nullptr)
{
m_scriptedObjects.insert(obj);
}
}
void ScriptingVM::unregisterScriptedObject(ScriptedObject* obj)
{
if (obj != nullptr)
{
m_scriptedObjects.erase(obj);
}
}
void ScriptingVM::replaceContext(std::unique_ptr<ScriptingContext> newContext)
{
#ifdef WITH_RIVE_TOOLS
if (m_ownedContext != nullptr)
{
m_ownedContext->disposeOrphanScriptedProperties();
}
#endif
m_ownedContext = std::move(newContext);
lua_setthreaddata(m_state, m_ownedContext.get());
}
void ScriptingVM::addModule(ModuleDetails* moduleDetails)
{
context()->addModule(moduleDetails);
}
void ScriptingVM::performRegistration()
{
context()->performRegistration(m_state);
}
// Loads bytecode into a sandboxed thread without executing it.
// On success, pushes the module thread (with loaded closure) onto L's stack.
// Returns true on success.
bool ScriptingVM::loadModule(lua_State* L,
const char* name,
Span<uint8_t> bytecode)
{
if (bytecode.empty())
{
return false;
}
// module needs to run in a new thread, isolated from the rest
// note: we create ML on main thread so that it doesn't inherit environment
// of L
lua_State* GL = lua_mainthread(L);
lua_State* ML = lua_newthread(GL);
lua_xmove(GL, L, 1);
// new thread needs to have the globals sandboxed
luaL_sandboxthread(ML);
lua_setthreaddata(ML, lua_getthreaddata(L));
int status =
luau_load(ML, name, (const char*)bytecode.data(), bytecode.size(), 0);
if (status != 0)
{
// luau_load failed — error string is on ML stack
lua_xmove(ML, L, 1);
ScriptingContext* context =
static_cast<ScriptingContext*>(lua_getthreaddata(L));
context->printError(L);
lua_pop(L, 2); // pop error + thread
return false;
}
// Thread with loaded closure is on top of L's stack.
return true;
}
// Executes a previously loaded module thread (on top of L's stack from
// loadModule). On success, replaces the thread with the module result.
// If isUtility, also registers the result in the require cache.
// Returns true on success.
bool ScriptingVM::executeModule(lua_State* L, const char* name, bool isUtility)
{
// The module thread should be on top of the stack.
lua_State* ML = lua_tothread(L, -1);
if (ML == nullptr)
{
return false;
}
int status = lua_resume(ML, L, 0);
if (status == 0)
{
if (lua_gettop(ML) == 0)
{
lua_pushfstring(ML, "%s:1: module must return a value", name);
}
else if (!lua_istable(ML, -1) && !lua_isfunction(ML, -1))
{
lua_pushfstring(ML,
"%s:1: module must return a table or function",
name);
}
}
else if (status == LUA_YIELD)
{
lua_pushfstring(ML, "%s:1: module can not yield", name);
}
else if (!lua_isstring(ML, -1))
{
lua_pushfstring(ML, "%s:1: unknown error while running module", name);
}
// add ML result to L stack
lua_xmove(ML, L, 1);
// An error occurred if the top of the stack is a string.
if (lua_isstring(L, -1))
{
ScriptingContext* context =
static_cast<ScriptingContext*>(lua_getthreaddata(L));
context->printError(L);
lua_pop(L, 2); // pop error + thread
return false;
}
// remove ML thread from L stack
lua_remove(L, -2);
// added one value to L stack: module result
if (isUtility)
{
// Register into the require cache directly.
luaL_findtable(L, LUA_REGISTRYINDEX, registeredCacheTableKey, 1);
lua_pushstring(L, name);
lua_pushvalue(L, -3); // copy module result (below cache table + name)
lua_settable(L, -3); // cache[name] = result
lua_pop(L, 1); // pop cache table
}
return true;
}
static void dump_stack(lua_State* state)
{
int i;
int top = lua_gettop(state);
for (i = 1; i <= top; i++)
{ /* repeat for each level */
int t = lua_type(state, i);
switch (t)
{
case LUA_TSTRING: /* strings */
fprintf(stderr,
" (%i)[STRING] %s\n",
i,
lua_tostring(state, i));
break;
case LUA_TBOOLEAN: /* booleans */
fprintf(stderr,
" (%i)[BOOLEAN] %s\n",
i,
lua_toboolean(state, i) ? "true" : "false");
break;
case LUA_TNUMBER: /* numbers */
fprintf(stderr,
" (%i)[NUMBER] %g\n",
i,
lua_tonumber(state, i));
break;
default: /* other values */
fprintf(stderr, " (%i)[%s]\n", i, lua_typename(state, t));
break;
}
}
fprintf(stderr, "\n"); /* end the listing */
}
void ScriptingVM::dumpStack(lua_State* state) { dump_stack(state); }
void ScriptingContext::addModule(ModuleDetails* moduleDetails)
{
m_modulesToRegister.push_back(moduleDetails);
m_moduleLookup[moduleDetails->moduleName()] = moduleDetails;
}
bool ScriptingContext::tryRegisterModule(lua_State* state,
ModuleDetails* moduleDetails)
{
#ifndef WITH_RIVE_TOOLS
// In production builds, only allow verified (signed) scripts
if (!moduleDetails->verified())
{
return false;
}
#endif
const std::string& name = moduleDetails->moduleName();
bool registerSuccess = false;
int functionRef = 0;
if (moduleDetails->isProtocolScript())
{
if (ScriptingVM::registerScript(state,
name.c_str(),
moduleDetails->moduleBytecode()))
{
// registerScript leaves the function on the stack
if (static_cast<lua_Type>(lua_type(state, -1)) == LUA_TFUNCTION)
{
functionRef = lua_ref(state, -1);
}
lua_pop(state, 1);
registerSuccess = true;
}
}
else
{
if (ScriptingVM::registerModule(state,
name.c_str(),
moduleDetails->moduleBytecode()))
{
registerSuccess = true;
}
}
if (registerSuccess)
{
moduleDetails->registrationComplete(functionRef);
onModuleRegistered(moduleDetails);
return true;
}
return false;
}
void ScriptingContext::performRegistration(lua_State* state)
{
// Loop over all of the modules once. We need do a tryRegister
// pass on each module in order to determine if it has any
// required dependencies
for (ModuleDetails* moduleDetails : m_modulesToRegister)
{
if (moduleDetails == nullptr)
{
continue;
}
std::string moduleName = moduleDetails->moduleName();
// Skip if already registered
if (checkRegisteredModules(state, moduleName.c_str()) == 1)
{
lua_pop(state, 1);
continue;
}
tryRegisterModule(state, moduleDetails);
}
// If any modules had dependencies, resolve their registration order
// and try registering again
if (!m_pendingModules.empty())
{
std::vector<ModuleDetails*> pendingModules;
for (auto module : m_pendingModules)
{
pendingModules.push_back(module);
}
std::vector<ModuleDetails*> sortedModules;
std::unordered_set<ModuleDetails*> visitedModules;
ModuleDetails* module = pendingModules.back();
pendingModules.pop_back();
sortNextModule(module,
&pendingModules,
&sortedModules,
&visitedModules);
// Register modules in sorted order
for (ModuleDetails* moduleDetails : sortedModules)
{
tryRegisterModule(state, moduleDetails);
}
}
m_modulesToRegister.clear();
m_pendingModules.clear();
}
void ScriptingContext::sortNextModule(
ModuleDetails* module,
std::vector<ModuleDetails*>* pendingModules,
std::vector<ModuleDetails*>* sortedModules,
std::unordered_set<ModuleDetails*>* visitedModules)
{
// If already visited, skip
if (visitedModules->find(module) != visitedModules->end())
{
return;
}
auto dependencies = module->missingDependencies();
for (const auto& dependencyName : dependencies)
{
auto lookupIt = m_moduleLookup.find(dependencyName);
if (lookupIt != m_moduleLookup.end())
{
ModuleDetails* dependencyModule = lookupIt->second;
// Recursively process the dependency
sortNextModule(dependencyModule,
pendingModules,
sortedModules,
visitedModules);
}
}
if (std::find(sortedModules->begin(), sortedModules->end(), module) ==
sortedModules->end())
{
sortedModules->push_back(module);
}
visitedModules->insert(module);
if (!pendingModules->empty())
{
ModuleDetails* nextModule = pendingModules->back();
pendingModules->pop_back();
sortNextModule(nextModule,
pendingModules,
sortedModules,
visitedModules);
}
}
void ScriptingContext::recordMissingDependency(
const std::string& requiringModule,
const std::string& missingModule)
{
if (!requiringModule.empty())
{
ModuleDetails* moduleDetails = m_moduleLookup[requiringModule];
if (moduleDetails != nullptr)
{
moduleDetails->addMissingDependency(missingModule);
m_pendingModules.insert(moduleDetails);
}
}
}
void ScriptingContext::onModuleRegistered(ModuleDetails* moduleDetails)
{
for (ModuleDetails* module : m_modulesToRegister)
{
if (!module->missingDependencies().empty())
{
moduleDetails->clearMissingDependency(moduleDetails->moduleName());
}
}
auto it = m_pendingModules.find(moduleDetails);
if (it != m_pendingModules.end())
{
m_pendingModules.erase(it);
}
}
#ifdef WITH_RIVE_TOOLS
void ScriptingContext::registerShaderRstb(std::string name,
std::vector<uint8_t> bytes)
{
m_shaderRstbs[std::move(name)] = std::move(bytes);
}
const std::vector<uint8_t>* ScriptingContext::findShaderRstb(
const std::string& name) const
{
auto it = m_shaderRstbs.find(name);
return it != m_shaderRstbs.end() ? &it->second : nullptr;
}
void ScriptingContext::setGeneratorRef(uint32_t assetId, int ref)
{
m_assetGeneratorRefs[assetId] = ref;
}
int ScriptingContext::getGeneratorRef(uint32_t assetId) const
{
auto it = m_assetGeneratorRefs.find(assetId);
return it != m_assetGeneratorRefs.end() ? it->second : 0;
}
void ScriptingContext::clearGeneratorRefs() { m_assetGeneratorRefs.clear(); }
bool ScriptingContext::hasGeneratorRef(uint32_t assetId) const
{
return m_assetGeneratorRefs.find(assetId) != m_assetGeneratorRefs.end();
}
void ScriptingContext::trackOrphanScriptedProperty(ScriptedProperty* property)
{
if (property != nullptr)
{
m_orphanScriptedProperties.push_back(property);
}
}
void ScriptingContext::untrackOrphanScriptedProperty(ScriptedProperty* property)
{
auto it = std::remove(m_orphanScriptedProperties.begin(),
m_orphanScriptedProperties.end(),
property);
m_orphanScriptedProperties.erase(it, m_orphanScriptedProperties.end());
}
void ScriptingContext::disposeOrphanScriptedProperties()
{
auto orphans = m_orphanScriptedProperties;
for (ScriptedProperty* property : orphans)
{
if (property != nullptr)
{
property->dispose();
}
}
m_orphanScriptedProperties.clear();
}
#endif
// ── WorkPool integration ───────────────────────────────────────────────────
// getGlobalWorkPool() is defined in work_pool.cpp (shared singleton).
WorkPool* ScriptingContext::workPool()
{
if (m_ownerId == 0)
m_ownerId = WorkPool::nextOwnerId();
return getGlobalWorkPool().get();
}
// Forward-declared in lua_image_decode.cpp (WASM only).
#ifdef __EMSCRIPTEN__
extern void wasm_cancelPendingDecodes(lua_State* mainThread);
#endif
void ScriptingContext::shutdownAsync()
{
if (m_ownerId != 0)
{
You can’t perform that action at this time.
