| author | |
| committer | |
| log | f7716eb9e13c156a06b87abbcf3cea3f5200256b |
| tree | 63ad65c8e6067cc9b6724a1e11a052bb1dd15b26 |
| parent | f47b64a586b86f4e9664273aff433a9a71fba92c |
| signature | Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU |
13 files changed, 5069 insertions(+), 282 deletions(-)
Cargo.lock+18-276| ... | @@ -868,14 +868,6 @@ version = "0.5.9" | ... | @@ -868,14 +868,6 @@ version = "0.5.9" |
| 868 | source = "registry+https://github.com/rust-lang/crates.io-index" | 868 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 869 | checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" | 869 | checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" |
| 870 | 870 | ||
| 871 | [[package]] | ||
| 872 | name = "diff" | ||
| 873 | version = "0.1.0" | ||
| 874 | dependencies = [ | ||
| 875 | "highlight", | ||
| 876 | "tree-sitter", | ||
| 877 | ] | ||
| 878 | |||
| 879 | [[package]] | 871 | [[package]] |
| 880 | name = "digest" | 872 | name = "digest" |
| 881 | version = "0.11.3" | 873 | version = "0.11.3" |
| ... | @@ -975,6 +967,7 @@ dependencies = [ | ... | @@ -975,6 +967,7 @@ dependencies = [ |
| 975 | "objc2 0.6.5", | 967 | "objc2 0.6.5", |
| 976 | "objc2-app-kit 0.3.2", | 968 | "objc2-app-kit 0.3.2", |
| 977 | "objc2-foundation 0.3.2", | 969 | "objc2-foundation 0.3.2", |
| 970 | "regex", | ||
| 978 | "text", | 971 | "text", |
| 979 | "unicode-segmentation", | 972 | "unicode-segmentation", |
| 980 | "windows-sys 0.61.2", | 973 | "windows-sys 0.61.2", |
| ... | @@ -1016,6 +1009,7 @@ dependencies = [ | ... | @@ -1016,6 +1009,7 @@ dependencies = [ |
| 1016 | "exr", | 1009 | "exr", |
| 1017 | "fontdb 0.23.0", | 1010 | "fontdb 0.23.0", |
| 1018 | "image", | 1011 | "image", |
| 1012 | "mlua", | ||
| 1019 | "model", | 1013 | "model", |
| 1020 | "png", | 1014 | "png", |
| 1021 | "pollster", | 1015 | "pollster", |
| ... | @@ -1488,35 +1482,6 @@ version = "0.4.3" | ... | @@ -1488,35 +1482,6 @@ version = "0.4.3" |
| 1488 | source = "registry+https://github.com/rust-lang/crates.io-index" | 1482 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 1489 | checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" | 1483 | checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" |
| 1490 | 1484 | ||
| 1491 | [[package]] | ||
| 1492 | name = "highlight" | ||
| 1493 | version = "0.1.0" | ||
| 1494 | dependencies = [ | ||
| 1495 | "streaming-iterator", | ||
| 1496 | "tree-sitter", | ||
| 1497 | "tree-sitter-bash", | ||
| 1498 | "tree-sitter-c", | ||
| 1499 | "tree-sitter-cpp", | ||
| 1500 | "tree-sitter-css", | ||
| 1501 | "tree-sitter-diff", | ||
| 1502 | "tree-sitter-go", | ||
| 1503 | "tree-sitter-html", | ||
| 1504 | "tree-sitter-java", | ||
| 1505 | "tree-sitter-javascript", | ||
| 1506 | "tree-sitter-json", | ||
| 1507 | "tree-sitter-lua", | ||
| 1508 | "tree-sitter-md", | ||
| 1509 | "tree-sitter-python", | ||
| 1510 | "tree-sitter-ruby", | ||
| 1511 | "tree-sitter-rust", | ||
| 1512 | "tree-sitter-sequel", | ||
| 1513 | "tree-sitter-swift", | ||
| 1514 | "tree-sitter-toml-ng", | ||
| 1515 | "tree-sitter-typescript", | ||
| 1516 | "tree-sitter-yaml", | ||
| 1517 | "tree-sitter-zig", | ||
| 1518 | ] | ||
| 1519 | |||
| 1520 | [[package]] | 1485 | [[package]] |
| 1521 | name = "hybrid-array" | 1486 | name = "hybrid-array" |
| 1522 | version = "0.4.15" | 1487 | version = "0.4.15" |
| ... | @@ -3075,8 +3040,6 @@ version = "1.0.154" | ... | @@ -3075,8 +3040,6 @@ version = "1.0.154" |
| 3075 | source = "registry+https://github.com/rust-lang/crates.io-index" | 3040 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 3076 | checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" | 3041 | checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" |
| 3077 | dependencies = [ | 3042 | dependencies = [ |
| 3078 | "foldhash 0.2.0", | ||
| 3079 | "indexmap", | ||
| 3080 | "itoa", | 3043 | "itoa", |
| 3081 | "memchr", | 3044 | "memchr", |
| 3082 | "serde", | 3045 | "serde", |
| ... | @@ -3296,12 +3259,6 @@ version = "1.1.0" | ... | @@ -3296,12 +3259,6 @@ version = "1.1.0" |
| 3296 | source = "registry+https://github.com/rust-lang/crates.io-index" | 3259 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 3297 | checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" | 3260 | checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" |
| 3298 | 3261 | ||
| 3299 | [[package]] | ||
| 3300 | name = "streaming-iterator" | ||
| 3301 | version = "0.1.9" | ||
| 3302 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3303 | checksum = "2b2231b7c3057d5e4ad0156fb3dc807d900806020c5ffa3ee6ff2c8c76fb8520" | ||
| 3304 | |||
| 3305 | [[package]] | 3262 | [[package]] |
| 3306 | name = "strict-num" | 3263 | name = "strict-num" |
| 3307 | version = "0.1.1" | 3264 | version = "0.1.1" |
| ... | @@ -3489,6 +3446,10 @@ dependencies = [ | ... | @@ -3489,6 +3446,10 @@ dependencies = [ |
| 3489 | "syn 3.0.10", | 3446 | "syn 3.0.10", |
| 3490 | ] | 3447 | ] |
| 3491 | 3448 | ||
| 3449 | [[package]] | ||
| 3450 | name = "syntax-tokens" | ||
| 3451 | version = "0.1.0" | ||
| 3452 | |||
| 3492 | [[package]] | 3453 | [[package]] |
| 3493 | name = "target-features" | 3454 | name = "target-features" |
| 3494 | version = "0.1.6" | 3455 | version = "0.1.6" |
| ... | @@ -3544,12 +3505,12 @@ dependencies = [ | ... | @@ -3544,12 +3505,12 @@ dependencies = [ |
| 3544 | name = "theme" | 3505 | name = "theme" |
| 3545 | version = "0.1.0" | 3506 | version = "0.1.0" |
| 3546 | dependencies = [ | 3507 | dependencies = [ |
| 3547 | "diff", | ||
| 3548 | "draw", | 3508 | "draw", |
| 3549 | "flate2", | 3509 | "flate2", |
| 3550 | "highlight", | ||
| 3551 | "memmap2", | 3510 | "memmap2", |
| 3511 | "syntax-tokens", | ||
| 3552 | "text", | 3512 | "text", |
| 3513 | "zstd", | ||
| 3553 | ] | 3514 | ] |
| 3554 | 3515 | ||
| 3555 | [[package]] | 3516 | [[package]] |
| ... | @@ -3752,235 +3713,6 @@ dependencies = [ | ... | @@ -3752,235 +3713,6 @@ dependencies = [ |
| 3752 | "once_cell", | 3713 | "once_cell", |
| 3753 | ] | 3714 | ] |
| 3754 | 3715 | ||
| 3755 | [[package]] | ||
| 3756 | name = "tree-sitter" | ||
| 3757 | version = "0.27.2" | ||
| 3758 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3759 | checksum = "37b2bed8f39a73439f3b0b7ed8f452be5d2911b5e9da69d352ef113bb7448fb8" | ||
| 3760 | dependencies = [ | ||
| 3761 | "cc", | ||
| 3762 | "regex", | ||
| 3763 | "serde_json", | ||
| 3764 | "streaming-iterator", | ||
| 3765 | "tree-sitter-language", | ||
| 3766 | ] | ||
| 3767 | |||
| 3768 | [[package]] | ||
| 3769 | name = "tree-sitter-bash" | ||
| 3770 | version = "0.25.1" | ||
| 3771 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3772 | checksum = "9e5ec769279cc91b561d3df0d8a5deb26b0ad40d183127f409494d6d8fc53062" | ||
| 3773 | dependencies = [ | ||
| 3774 | "cc", | ||
| 3775 | "tree-sitter-language", | ||
| 3776 | ] | ||
| 3777 | |||
| 3778 | [[package]] | ||
| 3779 | name = "tree-sitter-c" | ||
| 3780 | version = "0.24.2" | ||
| 3781 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3782 | checksum = "a9b2eb57a55fed6b00812912e730b7a275cf4fe98bfd6a5d76263d4438371728" | ||
| 3783 | dependencies = [ | ||
| 3784 | "cc", | ||
| 3785 | "tree-sitter-language", | ||
| 3786 | ] | ||
| 3787 | |||
| 3788 | [[package]] | ||
| 3789 | name = "tree-sitter-cpp" | ||
| 3790 | version = "0.23.4" | ||
| 3791 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3792 | checksum = "df2196ea9d47b4ab4a31b9297eaa5a5d19a0b121dceb9f118f6790ad0ab94743" | ||
| 3793 | dependencies = [ | ||
| 3794 | "cc", | ||
| 3795 | "tree-sitter-language", | ||
| 3796 | ] | ||
| 3797 | |||
| 3798 | [[package]] | ||
| 3799 | name = "tree-sitter-css" | ||
| 3800 | version = "0.25.0" | ||
| 3801 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3802 | checksum = "a5cbc5e18f29a2c6d6435891f42569525cf95435a3e01c2f1947abcde178686f" | ||
| 3803 | dependencies = [ | ||
| 3804 | "cc", | ||
| 3805 | "tree-sitter-language", | ||
| 3806 | ] | ||
| 3807 | |||
| 3808 | [[package]] | ||
| 3809 | name = "tree-sitter-diff" | ||
| 3810 | version = "0.1.0" | ||
| 3811 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3812 | checksum = "dfe1e5ca280a65dfe5ba4205c1bcc84edf486464fed315db53dee6da9a335889" | ||
| 3813 | dependencies = [ | ||
| 3814 | "cc", | ||
| 3815 | "tree-sitter-language", | ||
| 3816 | ] | ||
| 3817 | |||
| 3818 | [[package]] | ||
| 3819 | name = "tree-sitter-go" | ||
| 3820 | version = "0.25.0" | ||
| 3821 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3822 | checksum = "c8560a4d2f835cc0d4d2c2e03cbd0dde2f6114b43bc491164238d333e28b16ea" | ||
| 3823 | dependencies = [ | ||
| 3824 | "cc", | ||
| 3825 | "tree-sitter-language", | ||
| 3826 | ] | ||
| 3827 | |||
| 3828 | [[package]] | ||
| 3829 | name = "tree-sitter-html" | ||
| 3830 | version = "0.23.2" | ||
| 3831 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3832 | checksum = "261b708e5d92061ede329babaaa427b819329a9d427a1d710abb0f67bbef63ee" | ||
| 3833 | dependencies = [ | ||
| 3834 | "cc", | ||
| 3835 | "tree-sitter-language", | ||
| 3836 | ] | ||
| 3837 | |||
| 3838 | [[package]] | ||
| 3839 | name = "tree-sitter-java" | ||
| 3840 | version = "0.23.5" | ||
| 3841 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3842 | checksum = "0aa6cbcdc8c679b214e616fd3300da67da0e492e066df01bcf5a5921a71e90d6" | ||
| 3843 | dependencies = [ | ||
| 3844 | "cc", | ||
| 3845 | "tree-sitter-language", | ||
| 3846 | ] | ||
| 3847 | |||
| 3848 | [[package]] | ||
| 3849 | name = "tree-sitter-javascript" | ||
| 3850 | version = "0.25.0" | ||
| 3851 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3852 | checksum = "68204f2abc0627a90bdf06e605f5c470aa26fdcb2081ea553a04bdad756693f5" | ||
| 3853 | dependencies = [ | ||
| 3854 | "cc", | ||
| 3855 | "tree-sitter-language", | ||
| 3856 | ] | ||
| 3857 | |||
| 3858 | [[package]] | ||
| 3859 | name = "tree-sitter-json" | ||
| 3860 | version = "0.24.8" | ||
| 3861 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3862 | checksum = "4d727acca406c0020cffc6cf35516764f36c8e3dc4408e5ebe2cb35a947ec471" | ||
| 3863 | dependencies = [ | ||
| 3864 | "cc", | ||
| 3865 | "tree-sitter-language", | ||
| 3866 | ] | ||
| 3867 | |||
| 3868 | [[package]] | ||
| 3869 | name = "tree-sitter-language" | ||
| 3870 | version = "0.1.9" | ||
| 3871 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3872 | checksum = "d0af592be68c579aa78a16846bd19422978c3c52e438523d45ff5d1bff1f9d4a" | ||
| 3873 | |||
| 3874 | [[package]] | ||
| 3875 | name = "tree-sitter-lua" | ||
| 3876 | version = "0.5.0" | ||
| 3877 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3878 | checksum = "8daaf5f4235188a58603c39760d5fa5d4b920d36a299c934adddae757f32a10c" | ||
| 3879 | dependencies = [ | ||
| 3880 | "cc", | ||
| 3881 | "tree-sitter-language", | ||
| 3882 | ] | ||
| 3883 | |||
| 3884 | [[package]] | ||
| 3885 | name = "tree-sitter-md" | ||
| 3886 | version = "0.5.4" | ||
| 3887 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3888 | checksum = "8ed661bfe3c264961425f77cd89ad2998bf5d629e71ce8bab1e5d7e940d6246e" | ||
| 3889 | dependencies = [ | ||
| 3890 | "cc", | ||
| 3891 | "tree-sitter-language", | ||
| 3892 | ] | ||
| 3893 | |||
| 3894 | [[package]] | ||
| 3895 | name = "tree-sitter-python" | ||
| 3896 | version = "0.25.0" | ||
| 3897 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3898 | checksum = "6bf85fd39652e740bf60f46f4cda9492c3a9ad75880575bf14960f775cb74a1c" | ||
| 3899 | dependencies = [ | ||
| 3900 | "cc", | ||
| 3901 | "tree-sitter-language", | ||
| 3902 | ] | ||
| 3903 | |||
| 3904 | [[package]] | ||
| 3905 | name = "tree-sitter-ruby" | ||
| 3906 | version = "0.23.1" | ||
| 3907 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3908 | checksum = "be0484ea4ef6bb9c575b4fdabde7e31340a8d2dbc7d52b321ac83da703249f95" | ||
| 3909 | dependencies = [ | ||
| 3910 | "cc", | ||
| 3911 | "tree-sitter-language", | ||
| 3912 | ] | ||
| 3913 | |||
| 3914 | [[package]] | ||
| 3915 | name = "tree-sitter-rust" | ||
| 3916 | version = "0.24.2" | ||
| 3917 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3918 | checksum = "439e577dbe07423ec2582ac62c7531120dbfccfa6e5f92406f93dd271a120e45" | ||
| 3919 | dependencies = [ | ||
| 3920 | "cc", | ||
| 3921 | "tree-sitter-language", | ||
| 3922 | ] | ||
| 3923 | |||
| 3924 | [[package]] | ||
| 3925 | name = "tree-sitter-sequel" | ||
| 3926 | version = "0.3.13" | ||
| 3927 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3928 | checksum = "711e236e1ae0708f911d8413c3b5656f522416cba683ea91589aebc49eda1b5a" | ||
| 3929 | dependencies = [ | ||
| 3930 | "cc", | ||
| 3931 | "tree-sitter-language", | ||
| 3932 | ] | ||
| 3933 | |||
| 3934 | [[package]] | ||
| 3935 | name = "tree-sitter-swift" | ||
| 3936 | version = "0.7.4" | ||
| 3937 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3938 | checksum = "2688c06564afa397313e0db17d140a73e2c6a47f3884794614246167c9dd5dfd" | ||
| 3939 | dependencies = [ | ||
| 3940 | "cc", | ||
| 3941 | "tree-sitter-language", | ||
| 3942 | ] | ||
| 3943 | |||
| 3944 | [[package]] | ||
| 3945 | name = "tree-sitter-toml-ng" | ||
| 3946 | version = "0.7.0" | ||
| 3947 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3948 | checksum = "e9adc2c898ae49730e857d75be403da3f92bb81d8e37a2f918a08dd10de5ebb1" | ||
| 3949 | dependencies = [ | ||
| 3950 | "cc", | ||
| 3951 | "tree-sitter-language", | ||
| 3952 | ] | ||
| 3953 | |||
| 3954 | [[package]] | ||
| 3955 | name = "tree-sitter-typescript" | ||
| 3956 | version = "0.23.2" | ||
| 3957 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3958 | checksum = "6c5f76ed8d947a75cc446d5fccd8b602ebf0cde64ccf2ffa434d873d7a575eff" | ||
| 3959 | dependencies = [ | ||
| 3960 | "cc", | ||
| 3961 | "tree-sitter-language", | ||
| 3962 | ] | ||
| 3963 | |||
| 3964 | [[package]] | ||
| 3965 | name = "tree-sitter-yaml" | ||
| 3966 | version = "0.7.2" | ||
| 3967 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3968 | checksum = "53c223db85f05e34794f065454843b0668ebc15d240ada63e2b5939f43ce7c97" | ||
| 3969 | dependencies = [ | ||
| 3970 | "cc", | ||
| 3971 | "tree-sitter-language", | ||
| 3972 | ] | ||
| 3973 | |||
| 3974 | [[package]] | ||
| 3975 | name = "tree-sitter-zig" | ||
| 3976 | version = "1.1.2" | ||
| 3977 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3978 | checksum = "ab11fc124851b0db4dd5e55983bbd9631192e93238389dcd44521715e5d53e28" | ||
| 3979 | dependencies = [ | ||
| 3980 | "cc", | ||
| 3981 | "tree-sitter-language", | ||
| 3982 | ] | ||
| 3983 | |||
| 3984 | [[package]] | 3716 | [[package]] |
| 3985 | name = "tree_magic_mini" | 3717 | name = "tree_magic_mini" |
| 3986 | version = "3.2.2" | 3718 | version = "3.2.2" |
| ... | @@ -4046,6 +3778,7 @@ dependencies = [ | ... | @@ -4046,6 +3778,7 @@ dependencies = [ |
| 4046 | "text", | 3778 | "text", |
| 4047 | "theme", | 3779 | "theme", |
| 4048 | "time", | 3780 | "time", |
| 3781 | "ui-data-derive", | ||
| 4049 | "wgpu", | 3782 | "wgpu", |
| 4050 | "windows-sys 0.61.2", | 3783 | "windows-sys 0.61.2", |
| 4051 | "winit", | 3784 | "winit", |
| ... | @@ -4053,6 +3786,15 @@ dependencies = [ | ... | @@ -4053,6 +3786,15 @@ dependencies = [ |
| 4053 | "zbus", | 3786 | "zbus", |
| 4054 | ] | 3787 | ] |
| 4055 | 3788 | ||
| 3789 | [[package]] | ||
| 3790 | name = "ui-data-derive" | ||
| 3791 | version = "0.1.0" | ||
| 3792 | dependencies = [ | ||
| 3793 | "proc-macro2", | ||
| 3794 | "quote", | ||
| 3795 | "syn 2.0.119", | ||
| 3796 | ] | ||
| 3797 | |||
| 4056 | [[package]] | 3798 | [[package]] |
| 4057 | name = "unicode-bidi" | 3799 | name = "unicode-bidi" |
| 4058 | version = "0.3.18" | 3800 | version = "0.3.18" |
crates/engine/Cargo.toml+1| ... | @@ -22,6 +22,7 @@ zeno.workspace = true | ... | @@ -22,6 +22,7 @@ zeno.workspace = true |
| 22 | 22 | ||
| 23 | [target.'cfg(not(target_arch = "wasm32"))'.dependencies] | 23 | [target.'cfg(not(target_arch = "wasm32"))'.dependencies] |
| 24 | cpal = "0.15" | 24 | cpal = "0.15" |
| 25 | mlua.workspace = true | ||
| 25 | symphonia = { version = "0.5", default-features = false, features = ["wav", "mp3", "flac", "ogg", "aac", "isomp4", "pcm"] } | 26 | symphonia = { version = "0.5", default-features = false, features = ["wav", "mp3", "flac", "ogg", "aac", "isomp4", "pcm"] } |
| 26 | 27 | ||
| 27 | [target.'cfg(target_arch = "wasm32")'.dependencies] | 28 | [target.'cfg(target_arch = "wasm32")'.dependencies] |
crates/engine/src/eval/mod.rs+17-6| ... | @@ -69,8 +69,8 @@ impl Default for DisplaySettings { | ... | @@ -69,8 +69,8 @@ impl Default for DisplaySettings { |
| 69 | } | 69 | } |
| 70 | 70 | ||
| 71 | pub struct Engine { | 71 | pub struct Engine { |
| 72 | device: wgpu::Device, | 72 | pub(crate) device: wgpu::Device, |
| 73 | queue: wgpu::Queue, | 73 | pub(crate) queue: wgpu::Queue, |
| 74 | pipelines: RefCell<ShaderRegistry>, | 74 | pipelines: RefCell<ShaderRegistry>, |
| 75 | pipelines_int16: OnceCell<RefCell<ShaderRegistry>>, | 75 | pipelines_int16: OnceCell<RefCell<ShaderRegistry>>, |
| 76 | pipelines_f16: OnceCell<RefCell<ShaderRegistry>>, | 76 | pipelines_f16: OnceCell<RefCell<ShaderRegistry>>, |
| ... | @@ -83,15 +83,16 @@ pub struct Engine { | ... | @@ -83,15 +83,16 @@ pub struct Engine { |
| 83 | fx_fuses_pipelines: OnceCell<RefCell<fx_fuses::FxFusesPipelines>>, | 83 | fx_fuses_pipelines: OnceCell<RefCell<fx_fuses::FxFusesPipelines>>, |
| 84 | archive_fx2_pipelines: OnceCell<RefCell<archive_fx2::ArchiveFx2Pipelines>>, | 84 | archive_fx2_pipelines: OnceCell<RefCell<archive_fx2::ArchiveFx2Pipelines>>, |
| 85 | motion_blur: crate::motion_blur::MotionBlurPipelines, | 85 | motion_blur: crate::motion_blur::MotionBlurPipelines, |
| 86 | supports_f32_filter: bool, | 86 | pub(crate) supports_f32_filter: bool, |
| 87 | scene3d: crate::scene3d::Scene3DRenderer, | 87 | scene3d: crate::scene3d::Scene3DRenderer, |
| 88 | optflow: std::sync::OnceLock<crate::optflow::OpticalFlowPipelines>, | 88 | optflow: std::sync::OnceLock<crate::optflow::OpticalFlowPipelines>, |
| 89 | tracker: std::sync::OnceLock<crate::tracker::TrackerPipelines>, | 89 | tracker: std::sync::OnceLock<crate::tracker::TrackerPipelines>, |
| 90 | particles: crate::particles::ParticleCache, | 90 | particles: crate::particles::ParticleCache, |
| 91 | custom_shaders: crate::custom_shader::CustomShaderCache, | 91 | custom_shaders: crate::custom_shader::CustomShaderCache, |
| 92 | pub fuse_registry: crate::fuse_runtime::FuseRegistry, | ||
| 92 | sprite_cache: HashMap<(NodeId, u64, i64), (crate::particles::SpriteImage, u64)>, | 93 | sprite_cache: HashMap<(NodeId, u64, i64), (crate::particles::SpriteImage, u64)>, |
| 93 | ram_upload_tex: RefCell<Option<CachedTexture>>, | 94 | ram_upload_tex: RefCell<Option<CachedTexture>>, |
| 94 | dummy: CachedTexture, | 95 | pub(crate) dummy: CachedTexture, |
| 95 | vram_budget_bytes: u64, | 96 | vram_budget_bytes: u64, |
| 96 | last_bg_vram_drops: Cell<u64>, | 97 | last_bg_vram_drops: Cell<u64>, |
| 97 | pub cache: NodeCache, | 98 | pub cache: NodeCache, |
| ... | @@ -201,6 +202,7 @@ impl Engine { | ... | @@ -201,6 +202,7 @@ impl Engine { |
| 201 | tracker: std::sync::OnceLock::new(), | 202 | tracker: std::sync::OnceLock::new(), |
| 202 | particles: crate::particles::ParticleCache::default(), | 203 | particles: crate::particles::ParticleCache::default(), |
| 203 | custom_shaders: crate::custom_shader::CustomShaderCache::new(), | 204 | custom_shaders: crate::custom_shader::CustomShaderCache::new(), |
| 205 | fuse_registry: crate::fuse_runtime::FuseRegistry::new(), | ||
| 204 | sprite_cache: HashMap::new(), | 206 | sprite_cache: HashMap::new(), |
| 205 | ram_upload_tex: RefCell::new(None), | 207 | ram_upload_tex: RefCell::new(None), |
| 206 | dummy, | 208 | dummy, |
| ... | @@ -264,7 +266,7 @@ impl Engine { | ... | @@ -264,7 +266,7 @@ impl Engine { |
| 264 | } | 266 | } |
| 265 | } | 267 | } |
| 266 | 268 | ||
| 267 | fn node_depth(&self, comp: &Comp, node: &Node, time: f64, upstream: Option<BitDepth>) -> BitDepth { | 269 | pub(crate) fn node_depth(&self, comp: &Comp, node: &Node, time: f64, upstream: Option<BitDepth>) -> BitDepth { |
| 268 | if !self.hiq { | 270 | if !self.hiq { |
| 269 | return BitDepth::Int8; | 271 | return BitDepth::Int8; |
| 270 | } | 272 | } |
| ... | @@ -618,7 +620,7 @@ impl Engine { | ... | @@ -618,7 +620,7 @@ impl Engine { |
| 618 | [(w / s).max(1), (h / s).max(1)] | 620 | [(w / s).max(1), (h / s).max(1)] |
| 619 | } | 621 | } |
| 620 | 622 | ||
| 621 | fn eval_node( | 623 | pub(crate) fn eval_node( |
| 622 | &mut self, | 624 | &mut self, |
| 623 | comp: &Comp, | 625 | comp: &Comp, |
| 624 | id: NodeId, | 626 | id: NodeId, |
| ... | @@ -1054,6 +1056,15 @@ impl Engine { | ... | @@ -1054,6 +1056,15 @@ impl Engine { |
| 1054 | } | 1056 | } |
| 1055 | "Renderer3D" => self.eval_renderer3d(comp, node, time, frame_i, comp_dims, enc, visiting, stats), | 1057 | "Renderer3D" => self.eval_renderer3d(comp, node, time, frame_i, comp_dims, enc, visiting, stats), |
| 1056 | other => { | 1058 | other => { |
| 1059 | // Dynamically evaluate any registered Fusion Lua / GPU-DCTL `.fuse` tool before | ||
| 1060 | // falling back to passthrough + unsupported_nodes. | ||
| 1061 | if other.starts_with("Fuse.") | ||
| 1062 | && let Some(tex) = self.eval_fuse_runtime( | ||
| 1063 | comp, node, time, frame_i, comp_dims, enc, visiting, stats, | ||
| 1064 | ) | ||
| 1065 | { | ||
| 1066 | return tex; | ||
| 1067 | } | ||
| 1057 | // Graceful passthrough for preserved/unknown image nodes (e.g. SurfaceTracker, MagicMask, | 1068 | // Graceful passthrough for preserved/unknown image nodes (e.g. SurfaceTracker, MagicMask, |
| 1058 | // Fuse.Cryptomatte, Dimension.OpticalFlow) via standard primary image ports so downstream | 1069 | // Fuse.Cryptomatte, Dimension.OpticalFlow) via standard primary image ports so downstream |
| 1059 | // graphs stay live without mistaking auxiliary sprite/material ports (like pEmitter's | 1070 | // graphs stay live without mistaking auxiliary sprite/material ports (like pEmitter's |
crates/engine/src/fuse_runtime/dctl.rs created+681| ... | @@ -0,0 +1,681 @@ | ||
| 1 | //! Pure-Rust DCTL (DaVinci Color Transform Language / Fusion GPU Fuse) to WGSL | ||
| 2 | //! compute shader transpiler and std430 parameter block layout parser. | ||
| 3 | //! | ||
| 4 | //! Compiles on all targets including `wasm32-unknown-unknown`. | ||
| 5 | |||
| 6 | use std::collections::HashMap; | ||
| 7 | |||
| 8 | /// Scalar / vector field type supported inside a DCTL parameter block. | ||
| 9 | #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] | ||
| 10 | pub enum ParamType { | ||
| 11 | F32, | ||
| 12 | I32, | ||
| 13 | U32, | ||
| 14 | Vec2F, | ||
| 15 | Vec3F, | ||
| 16 | Vec4F, | ||
| 17 | Vec2I, | ||
| 18 | Vec3I, | ||
| 19 | Vec4I, | ||
| 20 | } | ||
| 21 | |||
| 22 | impl ParamType { | ||
| 23 | pub fn from_c_type(s: &str) -> Option<Self> { | ||
| 24 | match s.trim() { | ||
| 25 | "float" | "double" | "half" => Some(Self::F32), | ||
| 26 | "int" | "bool" | "short" | "char" => Some(Self::I32), | ||
| 27 | "uint" | "unsigned int" | "unsigned" => Some(Self::U32), | ||
| 28 | "float2" => Some(Self::Vec2F), | ||
| 29 | "float3" => Some(Self::Vec3F), | ||
| 30 | "float4" => Some(Self::Vec4F), | ||
| 31 | "int2" => Some(Self::Vec2I), | ||
| 32 | "int3" => Some(Self::Vec3I), | ||
| 33 | "int4" => Some(Self::Vec4I), | ||
| 34 | _ => None, | ||
| 35 | } | ||
| 36 | } | ||
| 37 | |||
| 38 | pub fn wgsl_name(self) -> &'static str { | ||
| 39 | match self { | ||
| 40 | Self::F32 => "f32", | ||
| 41 | Self::I32 => "i32", | ||
| 42 | Self::U32 => "u32", | ||
| 43 | Self::Vec2F => "vec2<f32>", | ||
| 44 | Self::Vec3F => "vec3<f32>", | ||
| 45 | Self::Vec4F => "vec4<f32>", | ||
| 46 | Self::Vec2I => "vec2<i32>", | ||
| 47 | Self::Vec3I => "vec3<i32>", | ||
| 48 | Self::Vec4I => "vec4<i32>", | ||
| 49 | } | ||
| 50 | } | ||
| 51 | |||
| 52 | pub fn align(self) -> usize { | ||
| 53 | match self { | ||
| 54 | Self::F32 | Self::I32 | Self::U32 => 4, | ||
| 55 | Self::Vec2F | Self::Vec2I => 8, | ||
| 56 | Self::Vec3F | Self::Vec3I | Self::Vec4F | Self::Vec4I => 16, | ||
| 57 | } | ||
| 58 | } | ||
| 59 | |||
| 60 | pub fn size(self) -> usize { | ||
| 61 | match self { | ||
| 62 | Self::F32 | Self::I32 | Self::U32 => 4, | ||
| 63 | Self::Vec2F | Self::Vec2I => 8, | ||
| 64 | Self::Vec3F | Self::Vec3I => 12, | ||
| 65 | Self::Vec4F | Self::Vec4I => 16, | ||
| 66 | } | ||
| 67 | } | ||
| 68 | |||
| 69 | pub fn elem_stride(self) -> usize { | ||
| 70 | round_up(self.size(), self.align()) | ||
| 71 | } | ||
| 72 | |||
| 73 | pub fn components(self) -> usize { | ||
| 74 | match self { | ||
| 75 | Self::F32 | Self::I32 | Self::U32 => 1, | ||
| 76 | Self::Vec2F | Self::Vec2I => 2, | ||
| 77 | Self::Vec3F | Self::Vec3I => 3, | ||
| 78 | Self::Vec4F | Self::Vec4I => 4, | ||
| 79 | } | ||
| 80 | } | ||
| 81 | |||
| 82 | pub fn is_int(self) -> bool { | ||
| 83 | matches!(self, Self::I32 | Self::U32 | Self::Vec2I | Self::Vec3I | Self::Vec4I) | ||
| 84 | } | ||
| 85 | } | ||
| 86 | |||
| 87 | /// One field in a std430-laid-out DCTL parameter struct. | ||
| 88 | #[derive(Clone, Debug, PartialEq, Eq)] | ||
| 89 | pub struct ParamField { | ||
| 90 | pub name: String, | ||
| 91 | pub ty: ParamType, | ||
| 92 | /// `None` for scalar/vector fields, `Some(n)` for fixed C arrays (`float color[3]`). | ||
| 93 | pub array_len: Option<usize>, | ||
| 94 | pub offset: usize, | ||
| 95 | pub size: usize, | ||
| 96 | pub align: usize, | ||
| 97 | } | ||
| 98 | |||
| 99 | /// Full std430 layout of a DCTL parameter block. | ||
| 100 | #[derive(Clone, Debug, Default, PartialEq, Eq)] | ||
| 101 | pub struct ParamLayout { | ||
| 102 | pub fields: Vec<ParamField>, | ||
| 103 | pub total_size: usize, | ||
| 104 | } | ||
| 105 | |||
| 106 | impl ParamLayout { | ||
| 107 | pub fn field(&self, name: &str) -> Option<&ParamField> { | ||
| 108 | self.fields.iter().find(|f| f.name == name) | ||
| 109 | } | ||
| 110 | |||
| 111 | pub fn buffer_size(&self) -> usize { | ||
| 112 | self.total_size.max(16) | ||
| 113 | } | ||
| 114 | |||
| 115 | /// Emits a WGSL `struct` definition matching this std430 storage layout. | ||
| 116 | pub fn to_wgsl_struct(&self, struct_name: &str) -> String { | ||
| 117 | let mut out = format!("struct {struct_name} {{\n"); | ||
| 118 | if self.fields.is_empty() { | ||
| 119 | out.push_str(" _dctl_pad0: u32,\n _dctl_pad1: u32,\n _dctl_pad2: u32,\n _dctl_pad3: u32,\n"); | ||
| 120 | } else { | ||
| 121 | for f in &self.fields { | ||
| 122 | if let Some(n) = f.array_len { | ||
| 123 | out.push_str(&format!(" {}: array<{}, {n}>,\n", f.name, f.ty.wgsl_name())); | ||
| 124 | } else { | ||
| 125 | out.push_str(&format!(" {}: {},\n", f.name, f.ty.wgsl_name())); | ||
| 126 | } | ||
| 127 | } | ||
| 128 | } | ||
| 129 | out.push_str("}\n"); | ||
| 130 | out | ||
| 131 | } | ||
| 132 | |||
| 133 | /// Writes a single scalar/vector element at `field_name` (and optional `index`) into `buf`. | ||
| 134 | pub fn write_scalar(&self, buf: &mut [u8], field_name: &str, index: Option<usize>, value: f64) { | ||
| 135 | let Some(f) = self.field(field_name) else { | ||
| 136 | return; | ||
| 137 | }; | ||
| 138 | let off = match (f.array_len, index) { | ||
| 139 | (Some(len), Some(idx)) if idx < len => f.offset + idx * f.ty.elem_stride(), | ||
| 140 | (None, None) => f.offset, | ||
| 141 | (None, Some(idx)) if idx < f.ty.components() => f.offset + idx * 4, | ||
| 142 | _ => return, | ||
| 143 | }; | ||
| 144 | if off + 4 > buf.len() { | ||
| 145 | return; | ||
| 146 | } | ||
| 147 | let bytes = match f.ty { | ||
| 148 | ParamType::I32 | ParamType::Vec2I | ParamType::Vec3I | ParamType::Vec4I => { | ||
| 149 | (value.round() as i32).to_le_bytes() | ||
| 150 | } | ||
| 151 | ParamType::U32 => (value.round().max(0.0) as u32).to_le_bytes(), | ||
| 152 | _ => (value as f32).to_le_bytes(), | ||
| 153 | }; | ||
| 154 | buf[off..off + 4].copy_from_slice(&bytes); | ||
| 155 | } | ||
| 156 | |||
| 157 | /// Reads a single scalar/vector element from `buf`. | ||
| 158 | pub fn read_scalar(&self, buf: &[u8], field_name: &str, index: Option<usize>) -> Option<f64> { | ||
| 159 | let f = self.field(field_name)?; | ||
| 160 | let off = match (f.array_len, index) { | ||
| 161 | (Some(len), Some(idx)) if idx < len => f.offset + idx * f.ty.elem_stride(), | ||
| 162 | (None, None) => f.offset, | ||
| 163 | (None, Some(idx)) if idx < f.ty.components() => f.offset + idx * 4, | ||
| 164 | _ => return None, | ||
| 165 | }; | ||
| 166 | let bytes: [u8; 4] = buf.get(off..off + 4)?.try_into().ok()?; | ||
| 167 | let val = match f.ty { | ||
| 168 | ParamType::I32 | ParamType::Vec2I | ParamType::Vec3I | ParamType::Vec4I => { | ||
| 169 | i32::from_le_bytes(bytes) as f64 | ||
| 170 | } | ||
| 171 | ParamType::U32 => u32::from_le_bytes(bytes) as f64, | ||
| 172 | _ => f32::from_le_bytes(bytes) as f64, | ||
| 173 | }; | ||
| 174 | Some(val) | ||
| 175 | } | ||
| 176 | } | ||
| 177 | |||
| 178 | /// Output of `transpile_dctl_to_wgsl`. | ||
| 179 | #[derive(Clone, Debug)] | ||
| 180 | pub struct TranspiledKernel { | ||
| 181 | pub wgsl: String, | ||
| 182 | pub entry_point: String, | ||
| 183 | pub params_struct_name: String, | ||
| 184 | pub param_layout: ParamLayout, | ||
| 185 | pub input_textures: Vec<String>, | ||
| 186 | pub output_textures: Vec<String>, | ||
| 187 | } | ||
| 188 | |||
| 189 | fn round_up(val: usize, align: usize) -> usize { | ||
| 190 | if align <= 1 { | ||
| 191 | val | ||
| 192 | } else { | ||
| 193 | (val + align - 1) & !(align - 1) | ||
| 194 | } | ||
| 195 | } | ||
| 196 | |||
| 197 | pub fn wgsl_storage_format(format: wgpu::TextureFormat) -> &'static str { | ||
| 198 | match format { | ||
| 199 | wgpu::TextureFormat::Rgba16Float => "rgba16float", | ||
| 200 | wgpu::TextureFormat::Rgba32Float => "rgba32float", | ||
| 201 | _ => "rgba8unorm", | ||
| 202 | } | ||
| 203 | } | ||
| 204 | |||
| 205 | /// Parses a DCTL parameter block definition (either bare C fields or `typedef struct { ... } Name;`) | ||
| 206 | /// into a std430 `ParamLayout`. | ||
| 207 | pub fn parse_param_block(def: &str) -> Result<ParamLayout, String> { | ||
| 208 | let cleaned = strip_comments(def); | ||
| 209 | let body = extract_struct_body(&cleaned); | ||
| 210 | let mut layout = ParamLayout::default(); | ||
| 211 | let mut offset = 0usize; | ||
| 212 | let mut max_align = 4usize; | ||
| 213 | |||
| 214 | for raw_stmt in body.split(';') { | ||
| 215 | let stmt = raw_stmt.trim(); | ||
| 216 | if stmt.is_empty() || stmt.starts_with('#') { | ||
| 217 | continue; | ||
| 218 | } | ||
| 219 | let tokens: Vec<&str> = stmt.split_whitespace().collect(); | ||
| 220 | if tokens.len() < 2 { | ||
| 221 | continue; | ||
| 222 | } | ||
| 223 | let (ty_str, rest_start) = if tokens[0] == "unsigned" && tokens.len() >= 3 && tokens[1] == "int" { | ||
| 224 | ("unsigned int", 2) | ||
| 225 | } else if matches!(tokens[0], "const" | "volatile") && tokens.len() >= 3 { | ||
| 226 | (tokens[1], 2) | ||
| 227 | } else { | ||
| 228 | (tokens[0], 1) | ||
| 229 | }; | ||
| 230 | let Some(ty) = ParamType::from_c_type(ty_str) else { | ||
| 231 | return Err(format!("unsupported DCTL param field type `{ty_str}` in `{stmt}`")); | ||
| 232 | }; | ||
| 233 | let rest = tokens[rest_start..].join(" "); | ||
| 234 | for decl in rest.split(',') { | ||
| 235 | let decl = decl.trim(); | ||
| 236 | if decl.is_empty() { | ||
| 237 | continue; | ||
| 238 | } | ||
| 239 | let (name, array_len) = if let Some(b) = decl.find('[') { | ||
| 240 | let end = decl.find(']').ok_or_else(|| format!("unclosed `[` in `{decl}`"))?; | ||
| 241 | let len_str = decl[b + 1..end].trim(); | ||
| 242 | let len: usize = len_str | ||
| 243 | .parse() | ||
| 244 | .map_err(|_| format!("invalid array size `{len_str}` in `{decl}`"))?; | ||
| 245 | (decl[..b].trim(), Some(len.max(1))) | ||
| 246 | } else { | ||
| 247 | (decl, None) | ||
| 248 | }; | ||
| 249 | let align = ty.align(); | ||
| 250 | max_align = max_align.max(align); | ||
| 251 | offset = round_up(offset, align); | ||
| 252 | let size = match array_len { | ||
| 253 | Some(n) => ty.elem_stride() * n, | ||
| 254 | None => ty.size(), | ||
| 255 | }; | ||
| 256 | layout.fields.push(ParamField { | ||
| 257 | name: name.to_owned(), | ||
| 258 | ty, | ||
| 259 | array_len, | ||
| 260 | offset, | ||
| 261 | size, | ||
| 262 | align, | ||
| 263 | }); | ||
| 264 | offset += size; | ||
| 265 | } | ||
| 266 | } | ||
| 267 | layout.total_size = round_up(offset, max_align).max(16); | ||
| 268 | Ok(layout) | ||
| 269 | } | ||
| 270 | |||
| 271 | fn extract_struct_body(src: &str) -> &str { | ||
| 272 | if let (Some(open), Some(close)) = (src.find('{'), src.rfind('}')) | ||
| 273 | && open < close | ||
| 274 | { | ||
| 275 | &src[open + 1..close] | ||
| 276 | } else { | ||
| 277 | src | ||
| 278 | } | ||
| 279 | } | ||
| 280 | |||
| 281 | fn strip_comments(src: &str) -> String { | ||
| 282 | let bytes = src.as_bytes(); | ||
| 283 | let mut out = String::with_capacity(src.len()); | ||
| 284 | let mut i = 0; | ||
| 285 | while i < bytes.len() { | ||
| 286 | if bytes[i] == b'/' && bytes.get(i + 1) == Some(&b'/') { | ||
| 287 | i += 2; | ||
| 288 | while i < bytes.len() && bytes[i] != b'\n' { | ||
| 289 | i += 1; | ||
| 290 | } | ||
| 291 | } else if bytes[i] == b'/' && bytes.get(i + 1) == Some(&b'*') { | ||
| 292 | i += 2; | ||
| 293 | while i + 1 < bytes.len() && !(bytes[i] == b'*' && bytes[i + 1] == b'/') { | ||
| 294 | i += 1; | ||
| 295 | } | ||
| 296 | i = (i + 2).min(bytes.len()); | ||
| 297 | out.push(' '); | ||
| 298 | } else { | ||
| 299 | let ch = src[i..].chars().next().unwrap(); | ||
| 300 | out.push(ch); | ||
| 301 | i += ch.len_utf8(); | ||
| 302 | } | ||
| 303 | } | ||
| 304 | out | ||
| 305 | } | ||
| 306 | |||
| 307 | // --------------------------------------------------------------------------- | ||
| 308 | // Lexer | ||
| 309 | // --------------------------------------------------------------------------- | ||
| 310 | |||
| 311 | #[derive(Clone, Debug, PartialEq, Eq)] | ||
| 312 | pub(super) enum Tok { | ||
| 313 | Ident(String), | ||
| 314 | Float(String), | ||
| 315 | Int(String), | ||
| 316 | Punct(String), | ||
| 317 | } | ||
| 318 | |||
| 319 | pub(super) fn lex_dctl(src: &str) -> Vec<Tok> { | ||
| 320 | let stripped = strip_comments(src); | ||
| 321 | let mut defines: HashMap<String, Vec<Tok>> = HashMap::new(); | ||
| 322 | let mut body = String::with_capacity(stripped.len()); | ||
| 323 | |||
| 324 | for line in stripped.lines() { | ||
| 325 | let trimmed = line.trim_start(); | ||
| 326 | if let Some(rest) = trimmed.strip_prefix("#define") | ||
| 327 | && rest.starts_with(char::is_whitespace) | ||
| 328 | { | ||
| 329 | let rest = rest.trim_start(); | ||
| 330 | let mut parts = rest.splitn(2, char::is_whitespace); | ||
| 331 | if let (Some(name), Some(val)) = (parts.next(), parts.next()) | ||
| 332 | && !name.contains('(') | ||
| 333 | && !val.trim().is_empty() | ||
| 334 | { | ||
| 335 | defines.insert(name.to_owned(), lex_raw(val)); | ||
| 336 | } | ||
| 337 | } else if trimmed.starts_with('#') { | ||
| 338 | // Skip #include, #ifdef, #endif, #pragma, etc. | ||
| 339 | } else { | ||
| 340 | body.push_str(line); | ||
| 341 | body.push('\n'); | ||
| 342 | } | ||
| 343 | } | ||
| 344 | |||
| 345 | let raw = lex_raw(&body); | ||
| 346 | if defines.is_empty() { | ||
| 347 | return raw; | ||
| 348 | } | ||
| 349 | let mut expanded = Vec::with_capacity(raw.len()); | ||
| 350 | for tok in raw { | ||
| 351 | if let Tok::Ident(ref name) = tok | ||
| 352 | && let Some(rep) = defines.get(name) | ||
| 353 | { | ||
| 354 | expanded.extend(rep.iter().cloned()); | ||
| 355 | continue; | ||
| 356 | } | ||
| 357 | expanded.push(tok); | ||
| 358 | } | ||
| 359 | expanded | ||
| 360 | } | ||
| 361 | |||
| 362 | fn lex_raw(src: &str) -> Vec<Tok> { | ||
| 363 | let b = src.as_bytes(); | ||
| 364 | let mut toks = Vec::new(); | ||
| 365 | let mut i = 0; | ||
| 366 | while i < b.len() { | ||
| 367 | let c = b[i]; | ||
| 368 | if c.is_ascii_whitespace() { | ||
| 369 | i += 1; | ||
| 370 | continue; | ||
| 371 | } | ||
| 372 | if c.is_ascii_alphabetic() || c == b'_' { | ||
| 373 | let start = i; | ||
| 374 | i += 1; | ||
| 375 | while i < b.len() && (b[i].is_ascii_alphanumeric() || b[i] == b'_') { | ||
| 376 | i += 1; | ||
| 377 | } | ||
| 378 | toks.push(Tok::Ident(src[start..i].to_owned())); | ||
| 379 | continue; | ||
| 380 | } | ||
| 381 | if c.is_ascii_digit() || (c == b'.' && b.get(i + 1).is_some_and(u8::is_ascii_digit)) { | ||
| 382 | let start = i; | ||
| 383 | let mut is_float = c == b'.'; | ||
| 384 | if c == b'0' && matches!(b.get(i + 1), Some(b'x' | b'X')) { | ||
| 385 | i += 2; | ||
| 386 | while i < b.len() && b[i].is_ascii_hexdigit() { | ||
| 387 | i += 1; | ||
| 388 | } | ||
| 389 | while i < b.len() && matches!(b[i], b'u' | b'U' | b'l' | b'L') { | ||
| 390 | i += 1; | ||
| 391 | } | ||
| 392 | let s = src[start..i].trim_end_matches(['u', 'U', 'l', 'L']); | ||
| 393 | toks.push(Tok::Int(s.to_owned())); | ||
| 394 | continue; | ||
| 395 | } | ||
| 396 | while i < b.len() && b[i].is_ascii_digit() { | ||
| 397 | i += 1; | ||
| 398 | } | ||
| 399 | if i < b.len() && b[i] == b'.' { | ||
| 400 | is_float = true; | ||
| 401 | i += 1; | ||
| 402 | while i < b.len() && b[i].is_ascii_digit() { | ||
| 403 | i += 1; | ||
| 404 | } | ||
| 405 | } | ||
| 406 | if i < b.len() && matches!(b[i], b'e' | b'E') { | ||
| 407 | is_float = true; | ||
| 408 | i += 1; | ||
| 409 | if i < b.len() && matches!(b[i], b'+' | b'-') { | ||
| 410 | i += 1; | ||
| 411 | } | ||
| 412 | while i < b.len() && b[i].is_ascii_digit() { | ||
| 413 | i += 1; | ||
| 414 | } | ||
| 415 | } | ||
| 416 | let num_end = i; | ||
| 417 | let mut has_f = false; | ||
| 418 | while i < b.len() && matches!(b[i], b'f' | b'F' | b'h' | b'H' | b'u' | b'U' | b'l' | b'L') { | ||
| 419 | if matches!(b[i], b'f' | b'F' | b'h' | b'H') { | ||
| 420 | has_f = true; | ||
| 421 | } | ||
| 422 | i += 1; | ||
| 423 | } | ||
| 424 | let raw = &src[start..num_end]; | ||
| 425 | if is_float || has_f { | ||
| 426 | let mut norm = raw.to_owned(); | ||
| 427 | if norm.starts_with('.') { | ||
| 428 | norm.insert(0, '0'); | ||
| 429 | } | ||
| 430 | if norm.ends_with('.') { | ||
| 431 | norm.push('0'); | ||
| 432 | } | ||
| 433 | if !norm.contains('.') && !norm.contains('e') && !norm.contains('E') { | ||
| 434 | norm.push_str(".0"); | ||
| 435 | } | ||
| 436 | norm.push('f'); | ||
| 437 | toks.push(Tok::Float(norm)); | ||
| 438 | } else { | ||
| 439 | toks.push(Tok::Int(raw.to_owned())); | ||
| 440 | } | ||
| 441 | continue; | ||
| 442 | } | ||
| 443 | // Two-character operators | ||
| 444 | if i + 1 < b.len() { | ||
| 445 | let two = &src[i..i + 2]; | ||
| 446 | if matches!( | ||
| 447 | two, | ||
| 448 | "->" | "==" | ||
| 449 | | "!=" | ||
| 450 | | "<=" | ||
| 451 | | ">=" | ||
| 452 | | "&&" | ||
| 453 | | "||" | ||
| 454 | | "++" | ||
| 455 | | "--" | ||
| 456 | | "+=" | ||
| 457 | | "-=" | ||
| 458 | | "*=" | ||
| 459 | | "/=" | ||
| 460 | | "%=" | ||
| 461 | | "<<" | ||
| 462 | | ">>" | ||
| 463 | | "&=" | ||
| 464 | | "|=" | ||
| 465 | | "^=" | ||
| 466 | ) { | ||
| 467 | toks.push(Tok::Punct(two.to_owned())); | ||
| 468 | i += 2; | ||
| 469 | continue; | ||
| 470 | } | ||
| 471 | } | ||
| 472 | toks.push(Tok::Punct((c as char).to_string())); | ||
| 473 | i += 1; | ||
| 474 | } | ||
| 475 | toks | ||
| 476 | } | ||
| 477 | |||
| 478 | // --------------------------------------------------------------------------- | ||
| 479 | // Type Mapping | ||
| 480 | // --------------------------------------------------------------------------- | ||
| 481 | |||
| 482 | pub(super) fn c_type_to_wgsl(name: &str) -> Option<&'static str> { | ||
| 483 | match name { | ||
| 484 | "float" | "double" | "half" => Some("f32"), | ||
| 485 | "int" | "short" | "char" => Some("i32"), | ||
| 486 | "uint" | "unsigned" => Some("u32"), | ||
| 487 | "bool" => Some("bool"), | ||
| 488 | "void" => Some("void"), | ||
| 489 | "float2" => Some("vec2<f32>"), | ||
| 490 | "float3" => Some("vec3<f32>"), | ||
| 491 | "float4" => Some("vec4<f32>"), | ||
| 492 | "int2" => Some("vec2<i32>"), | ||
| 493 | "int3" => Some("vec3<i32>"), | ||
| 494 | "int4" => Some("vec4<i32>"), | ||
| 495 | "uint2" => Some("vec2<u32>"), | ||
| 496 | "uint3" => Some("vec3<u32>"), | ||
| 497 | "uint4" => Some("vec4<u32>"), | ||
| 498 | "float2x2" => Some("mat2x2<f32>"), | ||
| 499 | "float3x3" => Some("mat3x3<f32>"), | ||
| 500 | "float4x4" => Some("mat4x4<f32>"), | ||
| 501 | _ => None, | ||
| 502 | } | ||
| 503 | } | ||
| 504 | |||
| 505 | pub(super) fn is_c_qualifier(s: &str) -> bool { | ||
| 506 | matches!( | ||
| 507 | s, | ||
| 508 | "const" | ||
| 509 | | "volatile" | ||
| 510 | | "inline" | ||
| 511 | | "static" | ||
| 512 | | "__CONSTANT__" | ||
| 513 | | "__CONSTANTREF__" | ||
| 514 | | "__GLOBAL__" | ||
| 515 | | "__LOCAL__" | ||
| 516 | | "__PRIVATE__" | ||
| 517 | ) | ||
| 518 | } | ||
| 519 | |||
| 520 | |||
| 521 | use super::dctl_parse::Transpiler; | ||
| 522 | |||
| 523 | /// Transpiles a DCTL source string into a complete WebGPU-safe WGSL compute shader | ||
| 524 | /// (`@compute @workgroup_size(8, 8)`). | ||
| 525 | pub fn transpile_dctl_to_wgsl( | ||
| 526 | source: &str, | ||
| 527 | kernel_name: &str, | ||
| 528 | params_name: Option<&str>, | ||
| 529 | params_def: Option<&str>, | ||
| 530 | storage_format: wgpu::TextureFormat, | ||
| 531 | ) -> Result<TranspiledKernel, String> { | ||
| 532 | let toks = lex_dctl(source); | ||
| 533 | let mut tr = Transpiler::new(toks); | ||
| 534 | if let Some(pname) = params_name | ||
| 535 | && !pname.is_empty() | ||
| 536 | { | ||
| 537 | tr.known_structs.insert(pname.to_owned()); | ||
| 538 | } | ||
| 539 | tr.parse_program()?; | ||
| 540 | |||
| 541 | let kernel = tr | ||
| 542 | .kernels | ||
| 543 | .iter() | ||
| 544 | .find(|k| k.name == kernel_name) | ||
| 545 | .or_else(|| tr.kernels.first()) | ||
| 546 | .ok_or_else(|| format!("no `__KERNEL__` function `{kernel_name}` found in DCTL source"))?; | ||
| 547 | |||
| 548 | let resolved_params_name = params_name | ||
| 549 | .filter(|s| !s.is_empty()) | ||
| 550 | .map(str::to_owned) | ||
| 551 | .or_else(|| kernel.params_type.clone()) | ||
| 552 | .unwrap_or_else(|| "DctlParams".to_owned()); | ||
| 553 | |||
| 554 | let param_layout = if let Some(def) = params_def.filter(|s| !s.trim().is_empty()) { | ||
| 555 | parse_param_block(def)? | ||
| 556 | } else if let Some(inline) = tr.inline_param_structs.get(&resolved_params_name) { | ||
| 557 | inline.clone() | ||
| 558 | } else { | ||
| 559 | ParamLayout { | ||
| 560 | fields: Vec::new(), | ||
| 561 | total_size: 16, | ||
| 562 | } | ||
| 563 | }; | ||
| 564 | |||
| 565 | let fmt = wgsl_storage_format(storage_format); | ||
| 566 | let mut wgsl = String::with_capacity(source.len() * 2 + 1024); | ||
| 567 | |||
| 568 | // 1. Meta uniform struct & parameter struct(s) | ||
| 569 | wgsl.push_str( | ||
| 570 | "struct _DctlMeta {\n\ | ||
| 571 | \x20 width: u32,\n\ | ||
| 572 | \x20 height: u32,\n\ | ||
| 573 | \x20 normalized: u32,\n\ | ||
| 574 | \x20 linear_filter: u32,\n\ | ||
| 575 | }\n\n", | ||
| 576 | ); | ||
| 577 | |||
| 578 | let mut emitted_params_struct = false; | ||
| 579 | for (sname, sdef) in &tr.struct_defs { | ||
| 580 | if *sname == resolved_params_name { | ||
| 581 | wgsl.push_str(&param_layout.to_wgsl_struct(&resolved_params_name)); | ||
| 582 | wgsl.push('\n'); | ||
| 583 | emitted_params_struct = true; | ||
| 584 | } else { | ||
| 585 | wgsl.push_str(sdef); | ||
| 586 | wgsl.push('\n'); | ||
| 587 | } | ||
| 588 | } | ||
| 589 | if !emitted_params_struct { | ||
| 590 | wgsl.push_str(&param_layout.to_wgsl_struct(&resolved_params_name)); | ||
| 591 | wgsl.push('\n'); | ||
| 592 | } | ||
| 593 | |||
| 594 | // 2. Bindings: 0 = params storage, 1 = sampler, 2 = meta uniform, 3.. = inputs, 3+N.. = outputs | ||
| 595 | wgsl.push_str(&format!( | ||
| 596 | "@group(0) @binding(0) var<storage, read> {}: {};\n", | ||
| 597 | kernel.params_var, resolved_params_name | ||
| 598 | )); | ||
| 599 | wgsl.push_str("@group(0) @binding(1) var _dctl_sampler: sampler;\n"); | ||
| 600 | wgsl.push_str("@group(0) @binding(2) var<uniform> _dctl_meta: _DctlMeta;\n"); | ||
| 601 | |||
| 602 | let mut binding = 3u32; | ||
| 603 | for tex in &kernel.input_textures { | ||
| 604 | wgsl.push_str(&format!("@group(0) @binding({binding}) var {tex}: texture_2d<f32>;\n")); | ||
| 605 | binding += 1; | ||
| 606 | } | ||
| 607 | for dst in &kernel.output_textures { | ||
| 608 | wgsl.push_str(&format!( | ||
| 609 | "@group(0) @binding({binding}) var {dst}: texture_storage_2d<{fmt}, write>;\n" | ||
| 610 | )); | ||
| 611 | binding += 1; | ||
| 612 | } | ||
| 613 | wgsl.push('\n'); | ||
| 614 | |||
| 615 | // 3. Built-in DCTL helper functions | ||
| 616 | wgsl.push_str( | ||
| 617 | "fn _dctl_pow(base: f32, exp_v: f32) -> f32 {\n\ | ||
| 618 | \x20 if (base <= 0.0) { return select(0.0, 1.0, exp_v == 0.0); }\n\ | ||
| 619 | \x20 return pow(base, exp_v);\n\ | ||
| 620 | }\n\ | ||
| 621 | fn _dctl_fmod(x: f32, y: f32) -> f32 {\n\ | ||
| 622 | \x20 if (y == 0.0) { return 0.0; }\n\ | ||
| 623 | \x20 return x - y * trunc(x / y);\n\ | ||
| 624 | }\n\ | ||
| 625 | fn _dctl_copysign(x: f32, y: f32) -> f32 {\n\ | ||
| 626 | \x20 return select(-abs(x), abs(x), y >= 0.0);\n\ | ||
| 627 | }\n\ | ||
| 628 | fn _dctl_tex2d(t: texture_2d<f32>, fx: f32, fy: f32) -> vec4<f32> {\n\ | ||
| 629 | \x20 let dims = textureDimensions(t);\n\ | ||
| 630 | \x20 if (_dctl_meta.normalized != 0u) {\n\ | ||
| 631 | \x20 return textureSampleLevel(t, _dctl_sampler, vec2<f32>(fx, 1.0 - fy), 0.0);\n\ | ||
| 632 | \x20 }\n\ | ||
| 633 | \x20 if (_dctl_meta.linear_filter != 0u) {\n\ | ||
| 634 | \x20 let uv = vec2<f32>((fx + 0.5) / f32(dims.x), 1.0 - (fy + 0.5) / f32(dims.y));\n\ | ||
| 635 | \x20 return textureSampleLevel(t, _dctl_sampler, uv, 0.0);\n\ | ||
| 636 | \x20 }\n\ | ||
| 637 | \x20 let ix = clamp(i32(round(fx)), 0, i32(dims.x) - 1);\n\ | ||
| 638 | \x20 let iy = clamp(i32(dims.y) - 1 - i32(round(fy)), 0, i32(dims.y) - 1);\n\ | ||
| 639 | \x20 return textureLoad(t, vec2<i32>(ix, iy), 0);\n\ | ||
| 640 | }\n\ | ||
| 641 | fn _dctl_tex2d_n(t: texture_2d<f32>, fx: f32, fy: f32, comp_order: i32) -> vec4<f32> {\n\ | ||
| 642 | \x20 let c = _dctl_tex2d(t, fx, fy);\n\ | ||
| 643 | \x20 if (comp_order == 1) { return vec4<f32>(c.w, c.w, c.w, c.w); }\n\ | ||
| 644 | \x20 return c;\n\ | ||
| 645 | }\n\n", | ||
| 646 | ); | ||
| 647 | |||
| 648 | // 4. Global constants and `__DEVICE__` helper functions | ||
| 649 | for g in &tr.globals_wgsl { | ||
| 650 | wgsl.push_str(g); | ||
| 651 | } | ||
| 652 | for h in &tr.helpers_wgsl { | ||
| 653 | wgsl.push_str(h); | ||
| 654 | wgsl.push('\n'); | ||
| 655 | } | ||
| 656 | |||
| 657 | // 5. Compute entry point | ||
| 658 | let entry_point = "dctl_main".to_owned(); | ||
| 659 | let dims_expr = if let Some(dst0) = kernel.output_textures.first() { | ||
| 660 | format!("textureDimensions({dst0})") | ||
| 661 | } else { | ||
| 662 | "vec2<u32>(_dctl_meta.width, _dctl_meta.height)".to_owned() | ||
| 663 | }; | ||
| 664 | wgsl.push_str(&format!( | ||
| 665 | "@compute @workgroup_size(8, 8)\n\ | ||
| 666 | fn {entry_point}(@builtin(global_invocation_id) _dctl_gid: vec3<u32>) {{\n\ | ||
| 667 | \x20 let _dctl_dims = {dims_expr};\n\ | ||
| 668 | \x20 if (_dctl_gid.x >= _dctl_dims.x || _dctl_gid.y >= _dctl_dims.y) {{ return; }}\n" | ||
| 669 | )); | ||
| 670 | wgsl.push_str(&kernel.body_wgsl); | ||
| 671 | wgsl.push_str("}\n"); | ||
| 672 | |||
| 673 | Ok(TranspiledKernel { | ||
| 674 | wgsl, | ||
| 675 | entry_point, | ||
| 676 | params_struct_name: resolved_params_name, | ||
| 677 | param_layout, | ||
| 678 | input_textures: kernel.input_textures.clone(), | ||
| 679 | output_textures: kernel.output_textures.clone(), | ||
| 680 | }) | ||
| 681 | } | ||
crates/engine/src/fuse_runtime/dctl_expr.rs created+446| ... | @@ -0,0 +1,446 @@ | ||
| 1 | //! DCTL expression parser and intrinsic-to-WGSL rewriter. | ||
| 2 | |||
| 3 | use super::dctl::Tok; | ||
| 4 | use super::dctl_parse::Transpiler; | ||
| 5 | |||
| 6 | impl Transpiler { | ||
| 7 | // ----------------------------------------------------------------------- | ||
| 8 | // Expressions | ||
| 9 | // ----------------------------------------------------------------------- | ||
| 10 | |||
| 11 | fn looks_boolean(&self, expr: &str) -> bool { | ||
| 12 | let t = expr.trim(); | ||
| 13 | if t == "true" || t == "false" || self.bool_vars.contains(t) { | ||
| 14 | return true; | ||
| 15 | } | ||
| 16 | if t.starts_with('!') { | ||
| 17 | return true; | ||
| 18 | } | ||
| 19 | // Check top-level (paren-depth 0) comparison or logical operator | ||
| 20 | let b = t.as_bytes(); | ||
| 21 | let mut depth = 0i32; | ||
| 22 | let mut i = 0; | ||
| 23 | while i < b.len() { | ||
| 24 | match b[i] { | ||
| 25 | b'(' | b'[' => depth += 1, | ||
| 26 | b')' | b']' => depth -= 1, | ||
| 27 | _ if depth == 0 => { | ||
| 28 | if i + 1 < b.len() { | ||
| 29 | let two = &t[i..i + 2]; | ||
| 30 | if matches!(two, "==" | "!=" | "<=" | ">=" | "&&" | "||") { | ||
| 31 | return true; | ||
| 32 | } | ||
| 33 | } | ||
| 34 | if matches!(b[i], b'<' | b'>') { | ||
| 35 | // Avoid matching `<f32>` inside `vec3<f32>` | ||
| 36 | let prev_alpha = i > 0 && (b[i - 1].is_ascii_alphanumeric() || b[i - 1] == b'_'); | ||
| 37 | if !prev_alpha || b[i] == b'>' { | ||
| 38 | if b[i] == b'<' && !prev_alpha { | ||
| 39 | return true; | ||
| 40 | } | ||
| 41 | if b[i] == b'>' && !t[..i].ends_with("f32") && !t[..i].ends_with("i32") && !t[..i].ends_with("u32") { | ||
| 42 | return true; | ||
| 43 | } | ||
| 44 | } | ||
| 45 | } | ||
| 46 | } | ||
| 47 | _ => {} | ||
| 48 | } | ||
| 49 | i += 1; | ||
| 50 | } | ||
| 51 | // Unwrap outer parentheses and check recursively | ||
| 52 | if t.starts_with('(') && t.ends_with(')') { | ||
| 53 | let mut d = 0i32; | ||
| 54 | let mut wraps_all = true; | ||
| 55 | for (idx, &ch) in b.iter().enumerate() { | ||
| 56 | if ch == b'(' { | ||
| 57 | d += 1; | ||
| 58 | } else if ch == b')' { | ||
| 59 | d -= 1; | ||
| 60 | if d == 0 && idx + 1 < b.len() { | ||
| 61 | wraps_all = false; | ||
| 62 | break; | ||
| 63 | } | ||
| 64 | } | ||
| 65 | } | ||
| 66 | if wraps_all { | ||
| 67 | return self.looks_boolean(&t[1..t.len() - 1]); | ||
| 68 | } | ||
| 69 | } | ||
| 70 | false | ||
| 71 | } | ||
| 72 | |||
| 73 | pub(super) fn parse_bool_expr(&mut self) -> Result<String, String> { | ||
| 74 | let e = self.parse_expr()?; | ||
| 75 | if self.looks_boolean(&e) { | ||
| 76 | Ok(e) | ||
| 77 | } else { | ||
| 78 | Ok(format!("(({e}) != 0)")) | ||
| 79 | } | ||
| 80 | } | ||
| 81 | |||
| 82 | pub(super) fn parse_expr(&mut self) -> Result<String, String> { | ||
| 83 | self.parse_assign() | ||
| 84 | } | ||
| 85 | |||
| 86 | fn parse_assign(&mut self) -> Result<String, String> { | ||
| 87 | let lhs = self.parse_ternary()?; | ||
| 88 | for op in ["=", "+=", "-=", "*=", "/=", "%=", "&=", "|=", "^="] { | ||
| 89 | if self.eat_punct(op) { | ||
| 90 | let rhs = self.parse_assign()?; | ||
| 91 | return Ok(format!("{lhs} {op} {rhs}")); | ||
| 92 | } | ||
| 93 | } | ||
| 94 | Ok(lhs) | ||
| 95 | } | ||
| 96 | |||
| 97 | fn parse_ternary(&mut self) -> Result<String, String> { | ||
| 98 | let cond = self.parse_logical_or()?; | ||
| 99 | if self.eat_punct("?") { | ||
| 100 | let then_e = self.parse_expr()?; | ||
| 101 | self.expect_punct(":")?; | ||
| 102 | let else_e = self.parse_ternary()?; | ||
| 103 | let bcond = if self.looks_boolean(&cond) { | ||
| 104 | cond | ||
| 105 | } else { | ||
| 106 | format!("(({cond}) != 0)") | ||
| 107 | }; | ||
| 108 | Ok(format!("select({else_e}, {then_e}, {bcond})")) | ||
| 109 | } else { | ||
| 110 | Ok(cond) | ||
| 111 | } | ||
| 112 | } | ||
| 113 | |||
| 114 | fn parse_logical_or(&mut self) -> Result<String, String> { | ||
| 115 | let mut lhs = self.parse_logical_and()?; | ||
| 116 | while self.eat_punct("||") { | ||
| 117 | let rhs = self.parse_logical_and()?; | ||
| 118 | lhs = format!("({lhs} || {rhs})"); | ||
| 119 | } | ||
| 120 | Ok(lhs) | ||
| 121 | } | ||
| 122 | |||
| 123 | fn parse_logical_and(&mut self) -> Result<String, String> { | ||
| 124 | let mut lhs = self.parse_bit_or()?; | ||
| 125 | while self.eat_punct("&&") { | ||
| 126 | let rhs = self.parse_bit_or()?; | ||
| 127 | lhs = format!("({lhs} && {rhs})"); | ||
| 128 | } | ||
| 129 | Ok(lhs) | ||
| 130 | } | ||
| 131 | |||
| 132 | fn parse_bit_or(&mut self) -> Result<String, String> { | ||
| 133 | let mut lhs = self.parse_bit_xor()?; | ||
| 134 | while self.eat_punct("|") { | ||
| 135 | let rhs = self.parse_bit_xor()?; | ||
| 136 | lhs = format!("({lhs} | {rhs})"); | ||
| 137 | } | ||
| 138 | Ok(lhs) | ||
| 139 | } | ||
| 140 | |||
| 141 | fn parse_bit_xor(&mut self) -> Result<String, String> { | ||
| 142 | let mut lhs = self.parse_bit_and()?; | ||
| 143 | while self.eat_punct("^") { | ||
| 144 | let rhs = self.parse_bit_and()?; | ||
| 145 | lhs = format!("({lhs} ^ {rhs})"); | ||
| 146 | } | ||
| 147 | Ok(lhs) | ||
| 148 | } | ||
| 149 | |||
| 150 | fn parse_bit_and(&mut self) -> Result<String, String> { | ||
| 151 | let mut lhs = self.parse_eq()?; | ||
| 152 | while self.eat_punct("&") { | ||
| 153 | let rhs = self.parse_eq()?; | ||
| 154 | lhs = format!("({lhs} & {rhs})"); | ||
| 155 | } | ||
| 156 | Ok(lhs) | ||
| 157 | } | ||
| 158 | |||
| 159 | fn parse_eq(&mut self) -> Result<String, String> { | ||
| 160 | let mut lhs = self.parse_rel()?; | ||
| 161 | loop { | ||
| 162 | if self.eat_punct("==") { | ||
| 163 | let rhs = self.parse_rel()?; | ||
| 164 | lhs = format!("({lhs} == {rhs})"); | ||
| 165 | } else if self.eat_punct("!=") { | ||
| 166 | let rhs = self.parse_rel()?; | ||
| 167 | lhs = format!("({lhs} != {rhs})"); | ||
| 168 | } else { | ||
| 169 | break; | ||
| 170 | } | ||
| 171 | } | ||
| 172 | Ok(lhs) | ||
| 173 | } | ||
| 174 | |||
| 175 | fn parse_rel(&mut self) -> Result<String, String> { | ||
| 176 | let mut lhs = self.parse_shift()?; | ||
| 177 | loop { | ||
| 178 | let op = if self.eat_punct("<=") { | ||
| 179 | "<=" | ||
| 180 | } else if self.eat_punct(">=") { | ||
| 181 | ">=" | ||
| 182 | } else if self.eat_punct("<") { | ||
| 183 | "<" | ||
| 184 | } else if self.eat_punct(">") { | ||
| 185 | ">" | ||
| 186 | } else { | ||
| 187 | break; | ||
| 188 | }; | ||
| 189 | let rhs = self.parse_shift()?; | ||
| 190 | lhs = format!("({lhs} {op} {rhs})"); | ||
| 191 | } | ||
| 192 | Ok(lhs) | ||
| 193 | } | ||
| 194 | |||
| 195 | fn parse_shift(&mut self) -> Result<String, String> { | ||
| 196 | let mut lhs = self.parse_add()?; | ||
| 197 | loop { | ||
| 198 | let op = if self.eat_punct("<<") { | ||
| 199 | "<<" | ||
| 200 | } else if self.eat_punct(">>") { | ||
| 201 | ">>" | ||
| 202 | } else { | ||
| 203 | break; | ||
| 204 | }; | ||
| 205 | let rhs = self.parse_add()?; | ||
| 206 | lhs = format!("({lhs} {op} {rhs})"); | ||
| 207 | } | ||
| 208 | Ok(lhs) | ||
| 209 | } | ||
| 210 | |||
| 211 | fn parse_add(&mut self) -> Result<String, String> { | ||
| 212 | let mut lhs = self.parse_mul()?; | ||
| 213 | loop { | ||
| 214 | let op = if self.eat_punct("+") { | ||
| 215 | "+" | ||
| 216 | } else if self.eat_punct("-") { | ||
| 217 | "-" | ||
| 218 | } else { | ||
| 219 | break; | ||
| 220 | }; | ||
| 221 | let rhs = self.parse_mul()?; | ||
| 222 | lhs = format!("({lhs} {op} {rhs})"); | ||
| 223 | } | ||
| 224 | Ok(lhs) | ||
| 225 | } | ||
| 226 | |||
| 227 | fn parse_mul(&mut self) -> Result<String, String> { | ||
| 228 | let mut lhs = self.parse_unary()?; | ||
| 229 | loop { | ||
| 230 | let op = if self.eat_punct("*") { | ||
| 231 | "*" | ||
| 232 | } else if self.eat_punct("/") { | ||
| 233 | "/" | ||
| 234 | } else if self.eat_punct("%") { | ||
| 235 | "%" | ||
| 236 | } else { | ||
| 237 | break; | ||
| 238 | }; | ||
| 239 | let rhs = self.parse_unary()?; | ||
| 240 | lhs = format!("({lhs} {op} {rhs})"); | ||
| 241 | } | ||
| 242 | Ok(lhs) | ||
| 243 | } | ||
| 244 | |||
| 245 | fn try_parse_c_cast(&mut self) -> Option<String> { | ||
| 246 | if !self.is_punct("(") { | ||
| 247 | return None; | ||
| 248 | } | ||
| 249 | let (ty, consumed) = self.peek_type_at(self.pos + 1)?; | ||
| 250 | if matches!(self.toks.get(self.pos + 1 + consumed), Some(Tok::Punct(p)) if p == ")") { | ||
| 251 | self.pos += 2 + consumed; | ||
| 252 | return Some(ty); | ||
| 253 | } | ||
| 254 | None | ||
| 255 | } | ||
| 256 | |||
| 257 | pub(super) fn parse_unary(&mut self) -> Result<String, String> { | ||
| 258 | if let Some(cast_ty) = self.try_parse_c_cast() { | ||
| 259 | let inner = self.parse_unary()?; | ||
| 260 | return Ok(format!("{cast_ty}({inner})")); | ||
| 261 | } | ||
| 262 | if self.eat_punct("-") { | ||
| 263 | let inner = self.parse_unary()?; | ||
| 264 | return Ok(format!("(-{inner})")); | ||
| 265 | } | ||
| 266 | if self.eat_punct("+") { | ||
| 267 | return self.parse_unary(); | ||
| 268 | } | ||
| 269 | if self.eat_punct("!") { | ||
| 270 | let inner = self.parse_unary()?; | ||
| 271 | if self.looks_boolean(&inner) { | ||
| 272 | return Ok(format!("(!({inner}))")); | ||
| 273 | } | ||
| 274 | return Ok(format!("(({inner}) == 0)")); | ||
| 275 | } | ||
| 276 | if self.eat_punct("~") { | ||
| 277 | let inner = self.parse_unary()?; | ||
| 278 | return Ok(format!("(~{inner})")); | ||
| 279 | } | ||
| 280 | if self.eat_punct("*") { | ||
| 281 | let inner = self.parse_unary()?; | ||
| 282 | return Ok(format!("(*{inner})")); | ||
| 283 | } | ||
| 284 | if self.eat_punct("&") { | ||
| 285 | let inner = self.parse_unary()?; | ||
| 286 | return Ok(format!("(&{inner})")); | ||
| 287 | } | ||
| 288 | self.parse_postfix() | ||
| 289 | } | ||
| 290 | |||
| 291 | fn parse_postfix(&mut self) -> Result<String, String> { | ||
| 292 | let mut expr = self.parse_primary()?; | ||
| 293 | loop { | ||
| 294 | if self.eat_punct("(") { | ||
| 295 | let mut args = Vec::new(); | ||
| 296 | while !self.is_punct(")") && self.pos < self.toks.len() { | ||
| 297 | args.push(self.parse_expr()?); | ||
| 298 | if !self.eat_punct(",") { | ||
| 299 | break; | ||
| 300 | } | ||
| 301 | } | ||
| 302 | self.expect_punct(")")?; | ||
| 303 | expr = rewrite_dctl_call(&expr, &args); | ||
| 304 | } else if self.eat_punct("[") { | ||
| 305 | let idx = self.parse_expr()?; | ||
| 306 | self.expect_punct("]")?; | ||
| 307 | expr = format!("{expr}[{idx}]"); | ||
| 308 | } else if self.eat_punct(".") || self.eat_punct("->") { | ||
| 309 | let field = self.expect_ident()?; | ||
| 310 | expr = format!("{expr}.{field}"); | ||
| 311 | } else { | ||
| 312 | break; | ||
| 313 | } | ||
| 314 | } | ||
| 315 | Ok(expr) | ||
| 316 | } | ||
| 317 | |||
| 318 | fn parse_primary(&mut self) -> Result<String, String> { | ||
| 319 | match self.bump() { | ||
| 320 | Some(Tok::Float(s)) => Ok(s), | ||
| 321 | Some(Tok::Int(s)) => Ok(s), | ||
| 322 | Some(Tok::Ident(id)) => Ok(match id.as_str() { | ||
| 323 | "M_PI" | "CUDART_PI_F" => "3.141592653589793f".to_owned(), | ||
| 324 | "M_PI_2" => "1.5707963267948966f".to_owned(), | ||
| 325 | "M_PI_4" => "0.7853981633974483f".to_owned(), | ||
| 326 | "M_2PI" | "M_TWOPI" => "6.283185307179586f".to_owned(), | ||
| 327 | "M_1_PI" => "0.3183098861837907f".to_owned(), | ||
| 328 | "M_E" => "2.718281828459045f".to_owned(), | ||
| 329 | "M_SQRT2" => "1.4142135623730951f".to_owned(), | ||
| 330 | _ => id, | ||
| 331 | }), | ||
| 332 | Some(Tok::Punct(p)) if p == "(" => { | ||
| 333 | let inner = self.parse_expr()?; | ||
| 334 | self.expect_punct(")")?; | ||
| 335 | Ok(format!("({inner})")) | ||
| 336 | } | ||
| 337 | other => Err(format!("unexpected token in expression: {other:?}")), | ||
| 338 | } | ||
| 339 | } | ||
| 340 | } | ||
| 341 | |||
| 342 | fn rewrite_dctl_call(name: &str, args: &[String]) -> String { | ||
| 343 | let a = |i: usize| args.get(i).map(String::as_str).unwrap_or("0.0"); | ||
| 344 | match name { | ||
| 345 | // Vector constructors | ||
| 346 | "to_float2" | "make_float2" => match args.len() { | ||
| 347 | 1 => format!("vec2<f32>(f32({}))", a(0)), | ||
| 348 | _ => format!("vec2<f32>(f32({}), f32({}))", a(0), a(1)), | ||
| 349 | }, | ||
| 350 | "to_float3" | "make_float3" => match args.len() { | ||
| 351 | 1 => format!("vec3<f32>(f32({}))", a(0)), | ||
| 352 | 2 => format!("vec3<f32>({}, f32({}))", a(0), a(1)), | ||
| 353 | _ => format!("vec3<f32>(f32({}), f32({}), f32({}))", a(0), a(1), a(2)), | ||
| 354 | }, | ||
| 355 | "to_float4" | "make_float4" => match args.len() { | ||
| 356 | 1 => format!("vec4<f32>(f32({}))", a(0)), | ||
| 357 | 2 => format!("vec4<f32>({}, f32({}))", a(0), a(1)), | ||
| 358 | 3 => format!("vec4<f32>({}, f32({}), f32({}))", a(0), a(1), a(2)), | ||
| 359 | _ => format!( | ||
| 360 | "vec4<f32>(f32({}), f32({}), f32({}), f32({}))", | ||
| 361 | a(0), | ||
| 362 | a(1), | ||
| 363 | a(2), | ||
| 364 | a(3) | ||
| 365 | ), | ||
| 366 | }, | ||
| 367 | "to_float2_s" => format!("vec2<f32>(f32({}))", a(0)), | ||
| 368 | "to_float3_s" => format!("vec3<f32>(f32({}))", a(0)), | ||
| 369 | "to_float4_s" => format!("vec4<f32>(f32({}))", a(0)), | ||
| 370 | "to_float2_v" => format!("vec2<f32>({0}[0], {0}[1])", a(0)), | ||
| 371 | "to_float3_v" => format!("vec3<f32>({0}[0], {0}[1], {0}[2])", a(0)), | ||
| 372 | "to_float4_v" => format!("vec4<f32>({0}[0], {0}[1], {0}[2], {0}[3])", a(0)), | ||
| 373 | "to_float3_aw" => format!("vec3<f32>({}, f32({}))", a(0), a(1)), | ||
| 374 | "to_float4_aw" => format!("vec4<f32>({}, f32({}))", a(0), a(1)), | ||
| 375 | "to_int2" | "make_int2" => format!("vec2<i32>(i32({}), i32({}))", a(0), a(1)), | ||
| 376 | "to_int3" | "make_int3" => format!("vec3<i32>(i32({}), i32({}), i32({}))", a(0), a(1), a(2)), | ||
| 377 | "to_int4" | "make_int4" => format!( | ||
| 378 | "vec4<i32>(i32({}), i32({}), i32({}), i32({}))", | ||
| 379 | a(0), | ||
| 380 | a(1), | ||
| 381 | a(2), | ||
| 382 | a(3) | ||
| 383 | ), | ||
| 384 | |||
| 385 | // Swizzles | ||
| 386 | "swi2" if args.len() == 3 => format!("(({}).{}{})", a(0), a(1), a(2)), | ||
| 387 | "swi3" if args.len() == 4 => format!("(({}).{}{}{})", a(0), a(1), a(2), a(3)), | ||
| 388 | "swi4" if args.len() == 5 => format!("(({}).{}{}{}{})", a(0), a(1), a(2), a(3), a(4)), | ||
| 389 | |||
| 390 | // Texture reads & writes | ||
| 391 | "_tex2DVecN" if args.len() >= 4 => { | ||
| 392 | format!("_dctl_tex2d_n({}, f32({}), f32({}), i32({}))", a(0), a(1), a(2), a(3)) | ||
| 393 | } | ||
| 394 | "_tex2DVec4" if args.len() >= 3 => { | ||
| 395 | format!("_dctl_tex2d({}, f32({}), f32({}))", a(0), a(1), a(2)) | ||
| 396 | } | ||
| 397 | "_tex2DVec4Write" if args.len() >= 4 => format!( | ||
| 398 | "textureStore({0}, vec2<i32>(i32({1}), i32(textureDimensions({0}).y) - 1 - i32({2})), {3})", | ||
| 399 | a(0), | ||
| 400 | a(1), | ||
| 401 | a(2), | ||
| 402 | a(3) | ||
| 403 | ), | ||
| 404 | |||
| 405 | // Math intrinsics | ||
| 406 | "_sinf" => format!("sin({})", a(0)), | ||
| 407 | "_cosf" => format!("cos({})", a(0)), | ||
| 408 | "_tanf" => format!("tan({})", a(0)), | ||
| 409 | "_asinf" => format!("asin({})", a(0)), | ||
| 410 | "_acosf" => format!("acos({})", a(0)), | ||
| 411 | "_atanf" => format!("atan({})", a(0)), | ||
| 412 | "_atan2f" => format!("atan2({}, {})", a(0), a(1)), | ||
| 413 | "_sinhf" => format!("sinh({})", a(0)), | ||
| 414 | "_coshf" => format!("cosh({})", a(0)), | ||
| 415 | "_tanhf" => format!("tanh({})", a(0)), | ||
| 416 | "_sqrtf" => format!("sqrt(max({}, 0.0))", a(0)), | ||
| 417 | "_rsqrtf" => format!("inverseSqrt(max({}, 1e-12))", a(0)), | ||
| 418 | "_powf" => format!("_dctl_pow({}, {})", a(0), a(1)), | ||
| 419 | "_fabs" | "_fabsf" => format!("abs({})", a(0)), | ||
| 420 | "_fmod" | "_fmodf" => format!("_dctl_fmod({}, {})", a(0), a(1)), | ||
| 421 | "_floorf" | "_floor" => format!("floor({})", a(0)), | ||
| 422 | "_ceilf" | "_ceil" => format!("ceil({})", a(0)), | ||
| 423 | "_round" | "_roundf" => format!("round({})", a(0)), | ||
| 424 | "_truncf" => format!("trunc({})", a(0)), | ||
| 425 | "_fractf" | "_fract" => format!("fract({})", a(0)), | ||
| 426 | "_fminf" => format!("min({}, {})", a(0), a(1)), | ||
| 427 | "_fmaxf" => format!("max({}, {})", a(0), a(1)), | ||
| 428 | "_clampf" => format!("clamp({}, {}, {})", a(0), a(1), a(2)), | ||
| 429 | "_mix" => format!("mix({}, {}, {})", a(0), a(1), a(2)), | ||
| 430 | "_saturatef" => format!("clamp({}, 0.0, 1.0)", a(0)), | ||
| 431 | "_expf" => format!("exp({})", a(0)), | ||
| 432 | "_exp2f" => format!("exp2({})", a(0)), | ||
| 433 | "_logf" => format!("log(max({}, 1e-12))", a(0)), | ||
| 434 | "_log2f" => format!("log2(max({}, 1e-12))", a(0)), | ||
| 435 | "_log10f" => format!("(log(max({}, 1e-12)) * 0.4342944819032518)", a(0)), | ||
| 436 | "_copysignf" => format!("_dctl_copysign({}, {})", a(0), a(1)), | ||
| 437 | "_hypotf" => format!("length(vec2<f32>({}, {}))", a(0), a(1)), | ||
| 438 | "_fdivide" => format!("(({}) / ({}))", a(0), a(1)), | ||
| 439 | "_fmaf" => format!("fma({}, {}, {})", a(0), a(1), a(2)), | ||
| 440 | "_smoothstep" => format!("smoothstep({}, {}, {})", a(0), a(1), a(2)), | ||
| 441 | "_step" => format!("step({}, {})", a(0), a(1)), | ||
| 442 | "_sign" => format!("sign({})", a(0)), | ||
| 443 | _ => format!("{name}({})", args.join(", ")), | ||
| 444 | } | ||
| 445 | } | ||
| 446 | |||
crates/engine/src/fuse_runtime/dctl_parse.rs created+695| ... | @@ -0,0 +1,695 @@ | ||
| 1 | //! DCTL top-level declaration and statement parser/emitter. | ||
| 2 | |||
| 3 | use std::collections::{HashMap, HashSet}; | ||
| 4 | |||
| 5 | use super::dctl::{ParamLayout, Tok, c_type_to_wgsl, is_c_qualifier, parse_param_block}; | ||
| 6 | |||
| 7 | // --------------------------------------------------------------------------- | ||
| 8 | // Parser & WGSL Emitter | ||
| 9 | // --------------------------------------------------------------------------- | ||
| 10 | |||
| 11 | pub(super) struct KernelInfo { | ||
| 12 | pub(super) name: String, | ||
| 13 | pub(super) params_type: Option<String>, | ||
| 14 | pub(super) params_var: String, | ||
| 15 | pub(super) input_textures: Vec<String>, | ||
| 16 | pub(super) output_textures: Vec<String>, | ||
| 17 | pub(super) body_wgsl: String, | ||
| 18 | } | ||
| 19 | |||
| 20 | pub(super) struct Transpiler { | ||
| 21 | pub(super) toks: Vec<Tok>, | ||
| 22 | pub(super) pos: usize, | ||
| 23 | pub(super) known_structs: HashSet<String>, | ||
| 24 | pub(super) struct_defs: Vec<(String, String)>, | ||
| 25 | pub(super) inline_param_structs: HashMap<String, ParamLayout>, | ||
| 26 | pub(super) globals_wgsl: Vec<String>, | ||
| 27 | pub(super) helpers_wgsl: Vec<String>, | ||
| 28 | pub(super) kernels: Vec<KernelInfo>, | ||
| 29 | pub(super) bool_vars: HashSet<String>, | ||
| 30 | /// Variables in current function that hold a pointer (`*p`). | ||
| 31 | ptr_vars: HashSet<String>, | ||
| 32 | /// Variables that are `__CONSTANTREF__` struct refs (accessed via `.` after `->`). | ||
| 33 | struct_ref_vars: HashSet<String>, | ||
| 34 | } | ||
| 35 | |||
| 36 | impl Transpiler { | ||
| 37 | pub(super) fn new(toks: Vec<Tok>) -> Self { | ||
| 38 | Self { | ||
| 39 | toks, | ||
| 40 | pos: 0, | ||
| 41 | known_structs: HashSet::new(), | ||
| 42 | struct_defs: Vec::new(), | ||
| 43 | inline_param_structs: HashMap::new(), | ||
| 44 | globals_wgsl: Vec::new(), | ||
| 45 | helpers_wgsl: Vec::new(), | ||
| 46 | kernels: Vec::new(), | ||
| 47 | bool_vars: HashSet::new(), | ||
| 48 | ptr_vars: HashSet::new(), | ||
| 49 | struct_ref_vars: HashSet::new(), | ||
| 50 | } | ||
| 51 | } | ||
| 52 | |||
| 53 | pub(super) fn peek(&self) -> Option<&Tok> { | ||
| 54 | self.toks.get(self.pos) | ||
| 55 | } | ||
| 56 | |||
| 57 | fn peek_n(&self, n: usize) -> Option<&Tok> { | ||
| 58 | self.toks.get(self.pos + n) | ||
| 59 | } | ||
| 60 | |||
| 61 | pub(super) fn bump(&mut self) -> Option<Tok> { | ||
| 62 | let t = self.toks.get(self.pos)?.clone(); | ||
| 63 | self.pos += 1; | ||
| 64 | Some(t) | ||
| 65 | } | ||
| 66 | |||
| 67 | pub(super) fn is_punct(&self, p: &str) -> bool { | ||
| 68 | matches!(self.peek(), Some(Tok::Punct(s)) if s == p) | ||
| 69 | } | ||
| 70 | |||
| 71 | fn is_ident(&self, id: &str) -> bool { | ||
| 72 | matches!(self.peek(), Some(Tok::Ident(s)) if s == id) | ||
| 73 | } | ||
| 74 | |||
| 75 | pub(super) fn eat_punct(&mut self, p: &str) -> bool { | ||
| 76 | if self.is_punct(p) { | ||
| 77 | self.pos += 1; | ||
| 78 | true | ||
| 79 | } else { | ||
| 80 | false | ||
| 81 | } | ||
| 82 | } | ||
| 83 | |||
| 84 | pub(super) fn expect_punct(&mut self, p: &str) -> Result<(), String> { | ||
| 85 | if self.eat_punct(p) { | ||
| 86 | Ok(()) | ||
| 87 | } else { | ||
| 88 | Err(format!("expected `{p}` near {:?}", self.peek())) | ||
| 89 | } | ||
| 90 | } | ||
| 91 | |||
| 92 | pub(super) fn expect_ident(&mut self) -> Result<String, String> { | ||
| 93 | match self.bump() { | ||
| 94 | Some(Tok::Ident(s)) => Ok(s), | ||
| 95 | other => Err(format!("expected identifier, got {other:?}")), | ||
| 96 | } | ||
| 97 | } | ||
| 98 | |||
| 99 | fn skip_qualifiers(&mut self) -> bool { | ||
| 100 | let mut saw_const = false; | ||
| 101 | while let Some(Tok::Ident(s)) = self.peek() { | ||
| 102 | if is_c_qualifier(s) { | ||
| 103 | if s == "const" || s == "__CONSTANT__" { | ||
| 104 | saw_const = true; | ||
| 105 | } | ||
| 106 | self.pos += 1; | ||
| 107 | } else { | ||
| 108 | break; | ||
| 109 | } | ||
| 110 | } | ||
| 111 | saw_const | ||
| 112 | } | ||
| 113 | |||
| 114 | pub(super) fn peek_type_at(&self, idx: usize) -> Option<(String, usize)> { | ||
| 115 | let Tok::Ident(first) = self.toks.get(idx)? else { | ||
| 116 | return None; | ||
| 117 | }; | ||
| 118 | if first == "unsigned" { | ||
| 119 | if let Some(Tok::Ident(second)) = self.toks.get(idx + 1) | ||
| 120 | && second == "int" | ||
| 121 | { | ||
| 122 | return Some(("u32".to_owned(), 2)); | ||
| 123 | } | ||
| 124 | return Some(("u32".to_owned(), 1)); | ||
| 125 | } | ||
| 126 | if first == "struct" { | ||
| 127 | if let Some(Tok::Ident(sname)) = self.toks.get(idx + 1) { | ||
| 128 | return Some((sname.clone(), 2)); | ||
| 129 | } | ||
| 130 | return None; | ||
| 131 | } | ||
| 132 | if let Some(wgsl) = c_type_to_wgsl(first) { | ||
| 133 | return Some((wgsl.to_owned(), 1)); | ||
| 134 | } | ||
| 135 | if self.known_structs.contains(first) { | ||
| 136 | return Some((first.clone(), 1)); | ||
| 137 | } | ||
| 138 | None | ||
| 139 | } | ||
| 140 | |||
| 141 | fn parse_type(&mut self) -> Result<String, String> { | ||
| 142 | let Some((ty, consumed)) = self.peek_type_at(self.pos) else { | ||
| 143 | return Err(format!("expected type near {:?}", self.peek())); | ||
| 144 | }; | ||
| 145 | self.pos += consumed; | ||
| 146 | Ok(ty) | ||
| 147 | } | ||
| 148 | |||
| 149 | pub(super) fn parse_program(&mut self) -> Result<(), String> { | ||
| 150 | while self.pos < self.toks.len() { | ||
| 151 | if self.eat_punct(";") { | ||
| 152 | continue; | ||
| 153 | } | ||
| 154 | if self.is_ident("typedef") { | ||
| 155 | self.parse_typedef_struct()?; | ||
| 156 | } else if self.is_ident("struct") { | ||
| 157 | self.parse_struct_def()?; | ||
| 158 | } else if self.is_ident("__KERNEL__") { | ||
| 159 | self.pos += 1; | ||
| 160 | self.parse_kernel()?; | ||
| 161 | } else if self.is_ident("__DEVICE__") { | ||
| 162 | self.pos += 1; | ||
| 163 | self.parse_device_fn()?; | ||
| 164 | } else { | ||
| 165 | // Could be a global const or unmarked helper function. | ||
| 166 | let save = self.pos; | ||
| 167 | let _ = self.skip_qualifiers(); | ||
| 168 | if self.peek_type_at(self.pos).is_some() { | ||
| 169 | let _ty = self.parse_type()?; | ||
| 170 | if matches!(self.peek(), Some(Tok::Ident(_))) | ||
| 171 | && matches!(self.peek_n(1), Some(Tok::Punct(p)) if p == "(") | ||
| 172 | { | ||
| 173 | self.pos = save; | ||
| 174 | self.parse_device_fn()?; | ||
| 175 | continue; | ||
| 176 | } | ||
| 177 | self.pos = save; | ||
| 178 | self.parse_global_const()?; | ||
| 179 | } else { | ||
| 180 | // Skip unknown top-level token safely. | ||
| 181 | self.pos += 1; | ||
| 182 | } | ||
| 183 | } | ||
| 184 | } | ||
| 185 | Ok(()) | ||
| 186 | } | ||
| 187 | |||
| 188 | fn parse_typedef_struct(&mut self) -> Result<(), String> { | ||
| 189 | self.pos += 1; // typedef | ||
| 190 | if !self.is_ident("struct") { | ||
| 191 | while self.pos < self.toks.len() && !self.eat_punct(";") { | ||
| 192 | self.pos += 1; | ||
| 193 | } | ||
| 194 | return Ok(()); | ||
| 195 | } | ||
| 196 | self.pos += 1; // struct | ||
| 197 | // Optional tag name before `{` | ||
| 198 | if matches!(self.peek(), Some(Tok::Ident(_))) { | ||
| 199 | self.pos += 1; | ||
| 200 | } | ||
| 201 | let body_text = self.collect_brace_raw_text()?; | ||
| 202 | let name = self.expect_ident()?; | ||
| 203 | let _ = self.eat_punct(";"); | ||
| 204 | let layout = parse_param_block(&body_text)?; | ||
| 205 | let wgsl = layout.to_wgsl_struct(&name); | ||
| 206 | self.known_structs.insert(name.clone()); | ||
| 207 | self.inline_param_structs.insert(name.clone(), layout); | ||
| 208 | self.struct_defs.push((name, wgsl)); | ||
| 209 | Ok(()) | ||
| 210 | } | ||
| 211 | |||
| 212 | fn parse_struct_def(&mut self) -> Result<(), String> { | ||
| 213 | self.pos += 1; // struct | ||
| 214 | let name = self.expect_ident()?; | ||
| 215 | let body_text = self.collect_brace_raw_text()?; | ||
| 216 | let _ = self.eat_punct(";"); | ||
| 217 | let layout = parse_param_block(&body_text)?; | ||
| 218 | let wgsl = layout.to_wgsl_struct(&name); | ||
| 219 | self.known_structs.insert(name.clone()); | ||
| 220 | self.inline_param_structs.insert(name.clone(), layout); | ||
| 221 | self.struct_defs.push((name, wgsl)); | ||
| 222 | Ok(()) | ||
| 223 | } | ||
| 224 | |||
| 225 | fn collect_brace_raw_text(&mut self) -> Result<String, String> { | ||
| 226 | self.expect_punct("{")?; | ||
| 227 | let mut depth = 1usize; | ||
| 228 | let mut s = String::new(); | ||
| 229 | while self.pos < self.toks.len() && depth > 0 { | ||
| 230 | match self.bump().unwrap() { | ||
| 231 | Tok::Punct(p) if p == "{" => { | ||
| 232 | depth += 1; | ||
| 233 | s.push_str("{ "); | ||
| 234 | } | ||
| 235 | Tok::Punct(p) if p == "}" => { | ||
| 236 | depth -= 1; | ||
| 237 | if depth > 0 { | ||
| 238 | s.push_str("} "); | ||
| 239 | } | ||
| 240 | } | ||
| 241 | Tok::Ident(id) => { | ||
| 242 | s.push_str(&id); | ||
| 243 | s.push(' '); | ||
| 244 | } | ||
| 245 | Tok::Int(n) | Tok::Float(n) => { | ||
| 246 | s.push_str(&n); | ||
| 247 | s.push(' '); | ||
| 248 | } | ||
| 249 | Tok::Punct(p) => { | ||
| 250 | s.push_str(&p); | ||
| 251 | if p == ";" { | ||
| 252 | s.push('\n'); | ||
| 253 | } | ||
| 254 | } | ||
| 255 | } | ||
| 256 | } | ||
| 257 | Ok(s) | ||
| 258 | } | ||
| 259 | |||
| 260 | fn parse_global_const(&mut self) -> Result<(), String> { | ||
| 261 | let _ = self.skip_qualifiers(); | ||
| 262 | let ty = self.parse_type()?; | ||
| 263 | let name = self.expect_ident()?; | ||
| 264 | let arr_len = if self.eat_punct("[") { | ||
| 265 | let n = if let Some(Tok::Int(s)) = self.peek() { | ||
| 266 | let s = s.clone(); | ||
| 267 | self.pos += 1; | ||
| 268 | Some(s) | ||
| 269 | } else { | ||
| 270 | None | ||
| 271 | }; | ||
| 272 | self.expect_punct("]")?; | ||
| 273 | n | ||
| 274 | } else { | ||
| 275 | None | ||
| 276 | }; | ||
| 277 | self.expect_punct("=")?; | ||
| 278 | if let Some(len) = arr_len { | ||
| 279 | let items = self.parse_brace_init_list()?; | ||
| 280 | self.expect_punct(";")?; | ||
| 281 | self.globals_wgsl.push(format!( | ||
| 282 | "const {name}: array<{ty}, {len}> = array<{ty}, {len}>({});\n", | ||
| 283 | items.join(", ") | ||
| 284 | )); | ||
| 285 | } else { | ||
| 286 | let expr = self.parse_expr()?; | ||
| 287 | self.expect_punct(";")?; | ||
| 288 | self.globals_wgsl | ||
| 289 | .push(format!("const {name}: {ty} = {expr};\n")); | ||
| 290 | } | ||
| 291 | Ok(()) | ||
| 292 | } | ||
| 293 | |||
| 294 | fn parse_device_fn(&mut self) -> Result<(), String> { | ||
| 295 | let _ = self.skip_qualifiers(); | ||
| 296 | let ret_ty = self.parse_type()?; | ||
| 297 | let name = self.expect_ident()?; | ||
| 298 | self.expect_punct("(")?; | ||
| 299 | |||
| 300 | let mut wgsl_params = Vec::new(); | ||
| 301 | let mut prelude = Vec::new(); | ||
| 302 | self.bool_vars.clear(); | ||
| 303 | self.ptr_vars.clear(); | ||
| 304 | self.struct_ref_vars.clear(); | ||
| 305 | |||
| 306 | while !self.is_punct(")") && self.pos < self.toks.len() { | ||
| 307 | let mut is_const_ref = false; | ||
| 308 | while let Some(Tok::Ident(s)) = self.peek() { | ||
| 309 | if s == "__CONSTANTREF__" { | ||
| 310 | is_const_ref = true; | ||
| 311 | self.pos += 1; | ||
| 312 | } else if is_c_qualifier(s) { | ||
| 313 | self.pos += 1; | ||
| 314 | } else { | ||
| 315 | break; | ||
| 316 | } | ||
| 317 | } | ||
| 318 | if self.is_ident("void") && matches!(self.peek_n(1), Some(Tok::Punct(p)) if p == ")") { | ||
| 319 | self.pos += 1; | ||
| 320 | break; | ||
| 321 | } | ||
| 322 | let pty = self.parse_type()?; | ||
| 323 | let is_ptr = self.eat_punct("*"); | ||
| 324 | let pname = self.expect_ident()?; | ||
| 325 | if pty == "bool" { | ||
| 326 | self.bool_vars.insert(pname.clone()); | ||
| 327 | } | ||
| 328 | if is_const_ref && is_ptr { | ||
| 329 | wgsl_params.push(format!("_p_{pname}: {pty}")); | ||
| 330 | prelude.push(format!(" let {pname} = _p_{pname};\n")); | ||
| 331 | self.struct_ref_vars.insert(pname); | ||
| 332 | } else if is_ptr { | ||
| 333 | wgsl_params.push(format!("{pname}: ptr<function, {pty}>")); | ||
| 334 | self.ptr_vars.insert(pname); | ||
| 335 | } else { | ||
| 336 | wgsl_params.push(format!("_p_{pname}: {pty}")); | ||
| 337 | prelude.push(format!(" var {pname}: {pty} = _p_{pname};\n")); | ||
| 338 | } | ||
| 339 | if !self.eat_punct(",") { | ||
| 340 | break; | ||
| 341 | } | ||
| 342 | } | ||
| 343 | self.expect_punct(")")?; | ||
| 344 | if self.eat_punct(";") { | ||
| 345 | // Forward prototype — WGSL does not need forward declarations. | ||
| 346 | return Ok(()); | ||
| 347 | } | ||
| 348 | let body = self.parse_block_inner()?; | ||
| 349 | let ret_clause = if ret_ty == "void" { | ||
| 350 | String::new() | ||
| 351 | } else { | ||
| 352 | format!(" -> {ret_ty}") | ||
| 353 | }; | ||
| 354 | let mut fn_wgsl = format!("fn {name}({}){ret_clause} {{\n", wgsl_params.join(", ")); | ||
| 355 | for line in prelude { | ||
| 356 | fn_wgsl.push_str(&line); | ||
| 357 | } | ||
| 358 | fn_wgsl.push_str(&body); | ||
| 359 | fn_wgsl.push_str("}\n"); | ||
| 360 | self.helpers_wgsl.push(fn_wgsl); | ||
| 361 | Ok(()) | ||
| 362 | } | ||
| 363 | |||
| 364 | fn parse_kernel(&mut self) -> Result<(), String> { | ||
| 365 | let _ = self.skip_qualifiers(); | ||
| 366 | let _ret = self.parse_type()?; // void | ||
| 367 | let name = self.expect_ident()?; | ||
| 368 | self.expect_punct("(")?; | ||
| 369 | |||
| 370 | let mut params_type = None; | ||
| 371 | let mut params_var = "params".to_owned(); | ||
| 372 | let mut input_textures = Vec::new(); | ||
| 373 | let mut output_textures = Vec::new(); | ||
| 374 | self.bool_vars.clear(); | ||
| 375 | self.ptr_vars.clear(); | ||
| 376 | self.struct_ref_vars.clear(); | ||
| 377 | |||
| 378 | while !self.is_punct(")") && self.pos < self.toks.len() { | ||
| 379 | if self.is_ident("__CONSTANTREF__") { | ||
| 380 | self.pos += 1; | ||
| 381 | let _ = self.skip_qualifiers(); | ||
| 382 | let ty = self.expect_ident()?; | ||
| 383 | let _ = self.eat_punct("*"); | ||
| 384 | let var = self.expect_ident()?; | ||
| 385 | self.known_structs.insert(ty.clone()); | ||
| 386 | self.struct_ref_vars.insert(var.clone()); | ||
| 387 | params_type = Some(ty); | ||
| 388 | params_var = var; | ||
| 389 | } else if self.is_ident("__TEXTURE2D__") { | ||
| 390 | self.pos += 1; | ||
| 391 | let var = self.expect_ident()?; | ||
| 392 | input_textures.push(var); | ||
| 393 | } else if self.is_ident("__TEXTURE2D_WRITE__") { | ||
| 394 | self.pos += 1; | ||
| 395 | let var = self.expect_ident()?; | ||
| 396 | output_textures.push(var); | ||
| 397 | } else { | ||
| 398 | // Skip optional extra kernel arguments cleanly | ||
| 399 | let _ = self.skip_qualifiers(); | ||
| 400 | let _ = self.bump(); | ||
| 401 | let _ = self.eat_punct("*"); | ||
| 402 | if matches!(self.peek(), Some(Tok::Ident(_))) { | ||
| 403 | self.pos += 1; | ||
| 404 | } | ||
| 405 | } | ||
| 406 | if !self.eat_punct(",") { | ||
| 407 | break; | ||
| 408 | } | ||
| 409 | } | ||
| 410 | self.expect_punct(")")?; | ||
| 411 | let body_wgsl = self.parse_block_inner()?; | ||
| 412 | self.kernels.push(KernelInfo { | ||
| 413 | name, | ||
| 414 | params_type, | ||
| 415 | params_var, | ||
| 416 | input_textures, | ||
| 417 | output_textures, | ||
| 418 | body_wgsl, | ||
| 419 | }); | ||
| 420 | Ok(()) | ||
| 421 | } | ||
| 422 | |||
| 423 | fn parse_block_inner(&mut self) -> Result<String, String> { | ||
| 424 | self.expect_punct("{")?; | ||
| 425 | let mut out = String::new(); | ||
| 426 | while !self.is_punct("}") && self.pos < self.toks.len() { | ||
| 427 | self.parse_stmt(&mut out, 1)?; | ||
| 428 | } | ||
| 429 | self.expect_punct("}")?; | ||
| 430 | Ok(out) | ||
| 431 | } | ||
| 432 | |||
| 433 | fn parse_stmt_or_block(&mut self, out: &mut String, indent: usize) -> Result<(), String> { | ||
| 434 | if self.is_punct("{") { | ||
| 435 | self.pos += 1; | ||
| 436 | while !self.is_punct("}") && self.pos < self.toks.len() { | ||
| 437 | self.parse_stmt(out, indent)?; | ||
| 438 | } | ||
| 439 | self.expect_punct("}")?; | ||
| 440 | } else { | ||
| 441 | self.parse_stmt(out, indent)?; | ||
| 442 | } | ||
| 443 | Ok(()) | ||
| 444 | } | ||
| 445 | |||
| 446 | fn parse_stmt(&mut self, out: &mut String, indent: usize) -> Result<(), String> { | ||
| 447 | let pad = " ".repeat(indent); | ||
| 448 | if self.eat_punct(";") { | ||
| 449 | return Ok(()); | ||
| 450 | } | ||
| 451 | if self.is_punct("{") { | ||
| 452 | out.push_str(&format!("{pad}{{\n")); | ||
| 453 | self.parse_stmt_or_block(out, indent + 1)?; | ||
| 454 | out.push_str(&format!("{pad}}}\n")); | ||
| 455 | return Ok(()); | ||
| 456 | } | ||
| 457 | if self.is_ident("DEFINE_KERNEL_ITERATORS_XY") { | ||
| 458 | self.pos += 1; | ||
| 459 | self.expect_punct("(")?; | ||
| 460 | let x_var = self.expect_ident()?; | ||
| 461 | self.expect_punct(",")?; | ||
| 462 | let y_var = self.expect_ident()?; | ||
| 463 | self.expect_punct(")")?; | ||
| 464 | let _ = self.eat_punct(";"); | ||
| 465 | out.push_str(&format!( | ||
| 466 | "{pad}var {x_var}: i32 = i32(_dctl_gid.x);\n\ | ||
| 467 | {pad}var {y_var}: i32 = i32(_dctl_dims.y - 1u - _dctl_gid.y);\n" | ||
| 468 | )); | ||
| 469 | return Ok(()); | ||
| 470 | } | ||
| 471 | if self.is_ident("if") { | ||
| 472 | self.pos += 1; | ||
| 473 | self.expect_punct("(")?; | ||
| 474 | let cond = self.parse_bool_expr()?; | ||
| 475 | self.expect_punct(")")?; | ||
| 476 | out.push_str(&format!("{pad}if ({cond}) {{\n")); | ||
| 477 | self.parse_stmt_or_block(out, indent + 1)?; | ||
| 478 | out.push_str(&format!("{pad}}}")); | ||
| 479 | if self.is_ident("else") { | ||
| 480 | self.pos += 1; | ||
| 481 | if self.is_ident("if") { | ||
| 482 | out.push_str(" else "); | ||
| 483 | let mut nested = String::new(); | ||
| 484 | self.parse_stmt(&mut nested, indent)?; | ||
| 485 | out.push_str(nested.trim_start()); | ||
| 486 | } else { | ||
| 487 | out.push_str(" else {\n"); | ||
| 488 | self.parse_stmt_or_block(out, indent + 1)?; | ||
| 489 | out.push_str(&format!("{pad}}}\n")); | ||
| 490 | } | ||
| 491 | } else { | ||
| 492 | out.push('\n'); | ||
| 493 | } | ||
| 494 | return Ok(()); | ||
| 495 | } | ||
| 496 | if self.is_ident("for") { | ||
| 497 | self.pos += 1; | ||
| 498 | self.expect_punct("(")?; | ||
| 499 | let init = if self.is_punct(";") { | ||
| 500 | self.pos += 1; | ||
| 501 | String::new() | ||
| 502 | } else if self.is_var_decl_ahead() { | ||
| 503 | self.parse_single_var_decl_inline()? | ||
| 504 | } else { | ||
| 505 | let e = self.parse_expr_stmt_inline()?; | ||
| 506 | self.expect_punct(";")?; | ||
| 507 | e | ||
| 508 | }; | ||
| 509 | let cond = if self.is_punct(";") { | ||
| 510 | self.pos += 1; | ||
| 511 | String::new() | ||
| 512 | } else { | ||
| 513 | let c = self.parse_bool_expr()?; | ||
| 514 | self.expect_punct(";")?; | ||
| 515 | c | ||
| 516 | }; | ||
| 517 | let step = if self.is_punct(")") { | ||
| 518 | String::new() | ||
| 519 | } else { | ||
| 520 | self.parse_expr_stmt_inline()? | ||
| 521 | }; | ||
| 522 | self.expect_punct(")")?; | ||
| 523 | out.push_str(&format!("{pad}for ({init}; {cond}; {step}) {{\n")); | ||
| 524 | self.parse_stmt_or_block(out, indent + 1)?; | ||
| 525 | out.push_str(&format!("{pad}}}\n")); | ||
| 526 | return Ok(()); | ||
| 527 | } | ||
| 528 | if self.is_ident("while") { | ||
| 529 | self.pos += 1; | ||
| 530 | self.expect_punct("(")?; | ||
| 531 | let cond = self.parse_bool_expr()?; | ||
| 532 | self.expect_punct(")")?; | ||
| 533 | out.push_str(&format!("{pad}while ({cond}) {{\n")); | ||
| 534 | self.parse_stmt_or_block(out, indent + 1)?; | ||
| 535 | out.push_str(&format!("{pad}}}\n")); | ||
| 536 | return Ok(()); | ||
| 537 | } | ||
| 538 | if self.is_ident("do") { | ||
| 539 | self.pos += 1; | ||
| 540 | out.push_str(&format!("{pad}loop {{\n")); | ||
| 541 | self.parse_stmt_or_block(out, indent + 1)?; | ||
| 542 | if !self.is_ident("while") { | ||
| 543 | return Err("expected `while` after `do` block".to_owned()); | ||
| 544 | } | ||
| 545 | self.pos += 1; | ||
| 546 | self.expect_punct("(")?; | ||
| 547 | let cond = self.parse_bool_expr()?; | ||
| 548 | self.expect_punct(")")?; | ||
| 549 | let _ = self.eat_punct(";"); | ||
| 550 | out.push_str(&format!("{pad} if (!({cond})) {{ break; }}\n{pad}}}\n")); | ||
| 551 | return Ok(()); | ||
| 552 | } | ||
| 553 | if self.is_ident("return") { | ||
| 554 | self.pos += 1; | ||
| 555 | if self.eat_punct(";") { | ||
| 556 | out.push_str(&format!("{pad}return;\n")); | ||
| 557 | } else { | ||
| 558 | let e = self.parse_expr()?; | ||
| 559 | self.expect_punct(";")?; | ||
| 560 | out.push_str(&format!("{pad}return {e};\n")); | ||
| 561 | } | ||
| 562 | return Ok(()); | ||
| 563 | } | ||
| 564 | if self.is_ident("break") { | ||
| 565 | self.pos += 1; | ||
| 566 | self.expect_punct(";")?; | ||
| 567 | out.push_str(&format!("{pad}break;\n")); | ||
| 568 | return Ok(()); | ||
| 569 | } | ||
| 570 | if self.is_ident("continue") { | ||
| 571 | self.pos += 1; | ||
| 572 | self.expect_punct(";")?; | ||
| 573 | out.push_str(&format!("{pad}continue;\n")); | ||
| 574 | return Ok(()); | ||
| 575 | } | ||
| 576 | if self.is_var_decl_ahead() { | ||
| 577 | self.parse_var_decl_stmt(out, &pad)?; | ||
| 578 | return Ok(()); | ||
| 579 | } | ||
| 580 | let expr_stmt = self.parse_expr_stmt_inline()?; | ||
| 581 | self.expect_punct(";")?; | ||
| 582 | out.push_str(&format!("{pad}{expr_stmt};\n")); | ||
| 583 | Ok(()) | ||
| 584 | } | ||
| 585 | |||
| 586 | fn is_var_decl_ahead(&self) -> bool { | ||
| 587 | let mut idx = self.pos; | ||
| 588 | while let Some(Tok::Ident(s)) = self.toks.get(idx) { | ||
| 589 | if is_c_qualifier(s) { | ||
| 590 | idx += 1; | ||
| 591 | } else { | ||
| 592 | break; | ||
| 593 | } | ||
| 594 | } | ||
| 595 | let Some((_, consumed)) = self.peek_type_at(idx) else { | ||
| 596 | return false; | ||
| 597 | }; | ||
| 598 | let next_idx = idx + consumed; | ||
| 599 | matches!(self.toks.get(next_idx), Some(Tok::Ident(_))) | ||
| 600 | } | ||
| 601 | |||
| 602 | fn parse_var_decl_stmt(&mut self, out: &mut String, pad: &str) -> Result<(), String> { | ||
| 603 | let is_const = self.skip_qualifiers(); | ||
| 604 | let ty = self.parse_type()?; | ||
| 605 | let kw = if is_const { "let" } else { "var" }; | ||
| 606 | loop { | ||
| 607 | let name = self.expect_ident()?; | ||
| 608 | if ty == "bool" { | ||
| 609 | self.bool_vars.insert(name.clone()); | ||
| 610 | } | ||
| 611 | let arr_len = if self.eat_punct("[") { | ||
| 612 | let n = if let Some(Tok::Int(s)) = self.peek() { | ||
| 613 | let s = s.clone(); | ||
| 614 | self.pos += 1; | ||
| 615 | Some(s) | ||
| 616 | } else { | ||
| 617 | None | ||
| 618 | }; | ||
| 619 | self.expect_punct("]")?; | ||
| 620 | n | ||
| 621 | } else { | ||
| 622 | None | ||
| 623 | }; | ||
| 624 | if self.eat_punct("=") { | ||
| 625 | if let Some(len) = arr_len { | ||
| 626 | let items = self.parse_brace_init_list()?; | ||
| 627 | out.push_str(&format!( | ||
| 628 | "{pad}{kw} {name}: array<{ty}, {len}> = array<{ty}, {len}>({});\n", | ||
| 629 | items.join(", ") | ||
| 630 | )); | ||
| 631 | } else { | ||
| 632 | let init = self.parse_expr()?; | ||
| 633 | out.push_str(&format!("{pad}{kw} {name}: {ty} = {init};\n")); | ||
| 634 | } | ||
| 635 | } else if let Some(len) = arr_len { | ||
| 636 | out.push_str(&format!("{pad}var {name}: array<{ty}, {len}>;\n")); | ||
| 637 | } else { | ||
| 638 | out.push_str(&format!("{pad}var {name}: {ty};\n")); | ||
| 639 | } | ||
| 640 | if !self.eat_punct(",") { | ||
| 641 | break; | ||
| 642 | } | ||
| 643 | } | ||
| 644 | self.expect_punct(";")?; | ||
| 645 | Ok(()) | ||
| 646 | } | ||
| 647 | |||
| 648 | fn parse_single_var_decl_inline(&mut self) -> Result<String, String> { | ||
| 649 | let _ = self.skip_qualifiers(); | ||
| 650 | let ty = self.parse_type()?; | ||
| 651 | let name = self.expect_ident()?; | ||
| 652 | let res = if self.eat_punct("=") { | ||
| 653 | let init = self.parse_expr()?; | ||
| 654 | format!("var {name}: {ty} = {init}") | ||
| 655 | } else { | ||
| 656 | format!("var {name}: {ty}") | ||
| 657 | }; | ||
| 658 | self.expect_punct(";")?; | ||
| 659 | Ok(res) | ||
| 660 | } | ||
| 661 | |||
| 662 | fn parse_expr_stmt_inline(&mut self) -> Result<String, String> { | ||
| 663 | // Handle prefix `++x` / `--x` as statement -> `x += 1` / `x -= 1` | ||
| 664 | if self.eat_punct("++") { | ||
| 665 | let lhs = self.parse_unary()?; | ||
| 666 | return Ok(format!("{lhs} += 1")); | ||
| 667 | } | ||
| 668 | if self.eat_punct("--") { | ||
| 669 | let lhs = self.parse_unary()?; | ||
| 670 | return Ok(format!("{lhs} -= 1")); | ||
| 671 | } | ||
| 672 | let lhs = self.parse_expr()?; | ||
| 673 | if self.eat_punct("++") { | ||
| 674 | return Ok(format!("{lhs} += 1")); | ||
| 675 | } | ||
| 676 | if self.eat_punct("--") { | ||
| 677 | return Ok(format!("{lhs} -= 1")); | ||
| 678 | } | ||
| 679 | Ok(lhs) | ||
| 680 | } | ||
| 681 | |||
| 682 | fn parse_brace_init_list(&mut self) -> Result<Vec<String>, String> { | ||
| 683 | self.expect_punct("{")?; | ||
| 684 | let mut items = Vec::new(); | ||
| 685 | while !self.is_punct("}") && self.pos < self.toks.len() { | ||
| 686 | items.push(self.parse_expr()?); | ||
| 687 | if !self.eat_punct(",") { | ||
| 688 | break; | ||
| 689 | } | ||
| 690 | } | ||
| 691 | self.expect_punct("}")?; | ||
| 692 | Ok(items) | ||
| 693 | } | ||
| 694 | |||
| 695 | } | ||
crates/engine/src/fuse_runtime/lua_bridge.rs created+287| ... | @@ -0,0 +1,287 @@ | ||
| 1 | //! GPU + Comp host bridge shared with the sandboxed Fusion Lua runtime. | ||
| 2 | |||
| 3 | use std::cell::RefCell; | ||
| 4 | use std::collections::HashMap; | ||
| 5 | use std::rc::Rc; | ||
| 6 | use std::sync::{Arc, Mutex}; | ||
| 7 | |||
| 8 | use model::{BitDepth, Gradient}; | ||
| 9 | |||
| 10 | use crate::cache::CachedTexture; | ||
| 11 | use crate::eval::create_texture_dod_fmt; | ||
| 12 | |||
| 13 | use super::lua_types::ImageInner; | ||
| 14 | use super::{DctlPipelineCache, FuseMeta}; | ||
| 15 | |||
| 16 | /// Pre-evaluated Fusion parameter value passed from `Comp` / `Node` into the Lua host. | ||
| 17 | #[derive(Clone, Debug)] | ||
| 18 | pub enum EvalParam { | ||
| 19 | Number(f64), | ||
| 20 | Point([f64; 2]), | ||
| 21 | Text(String), | ||
| 22 | Gradient(Gradient), | ||
| 23 | } | ||
| 24 | |||
| 25 | /// GPU + Comp bridge stored in `Lua` app data during a single Fuse execution. | ||
| 26 | pub struct HostBridge { | ||
| 27 | pub device: wgpu::Device, | ||
| 28 | pub queue: wgpu::Queue, | ||
| 29 | pub encoder: Option<wgpu::CommandEncoder>, | ||
| 30 | pub dummy_tex: CachedTexture, | ||
| 31 | pub pipeline_cache: Arc<Mutex<DctlPipelineCache>>, | ||
| 32 | pub supports_f32_filter: bool, | ||
| 33 | pub hiq: bool, | ||
| 34 | pub default_depth: BitDepth, | ||
| 35 | pub comp_dims: [u32; 2], | ||
| 36 | pub time: f64, | ||
| 37 | pub global_range: [i64; 2], | ||
| 38 | pub render_range: [i64; 2], | ||
| 39 | pub upstream_images: HashMap<String, CachedTexture>, | ||
| 40 | pub main_input: Option<CachedTexture>, | ||
| 41 | pub params: HashMap<String, EvalParam>, | ||
| 42 | pub fuse_meta: FuseMeta, | ||
| 43 | pub output_image: Option<Rc<RefCell<ImageInner>>>, | ||
| 44 | pub tool_data: HashMap<String, String>, | ||
| 45 | pub content_hash_seed: u64, | ||
| 46 | } | ||
| 47 | |||
| 48 | impl HostBridge { | ||
| 49 | pub(super) fn format_for_depth(&self, depth: BitDepth) -> wgpu::TextureFormat { | ||
| 50 | let eff = if self.hiq { depth } else { BitDepth::Int8 }; | ||
| 51 | match eff { | ||
| 52 | BitDepth::Int8 => wgpu::TextureFormat::Rgba8Unorm, | ||
| 53 | BitDepth::Int16 | BitDepth::Float16 => wgpu::TextureFormat::Rgba16Float, | ||
| 54 | BitDepth::Float32 => { | ||
| 55 | if self.supports_f32_filter { | ||
| 56 | wgpu::TextureFormat::Rgba32Float | ||
| 57 | } else { | ||
| 58 | wgpu::TextureFormat::Rgba16Float | ||
| 59 | } | ||
| 60 | } | ||
| 61 | } | ||
| 62 | } | ||
| 63 | |||
| 64 | pub(super) fn alloc_gpu_tex(&self, size: [u32; 2], depth: BitDepth, hash: u64) -> CachedTexture { | ||
| 65 | let eff = if self.hiq { depth } else { BitDepth::Int8 }; | ||
| 66 | let fmt = self.format_for_depth(eff); | ||
| 67 | create_texture_dod_fmt(&self.device, size, [0, 0], size, eff, fmt, hash) | ||
| 68 | } | ||
| 69 | |||
| 70 | /// Flushes any pending GPU commands so subsequent CPU readbacks observe upstream writes. | ||
| 71 | fn flush_encoder(&mut self) { | ||
| 72 | if let Some(enc) = self.encoder.take() { | ||
| 73 | let sub = self.queue.submit(Some(enc.finish())); | ||
| 74 | let _ = self.device.poll(wgpu::PollType::Wait { | ||
| 75 | submission_index: Some(sub), | ||
| 76 | timeout: Some(std::time::Duration::from_secs(10)), | ||
| 77 | }); | ||
| 78 | self.encoder = Some(self.device.create_command_encoder( | ||
| 79 | &wgpu::CommandEncoderDescriptor { | ||
| 80 | label: Some("fuse-runtime-post-flush"), | ||
| 81 | }, | ||
| 82 | )); | ||
| 83 | } | ||
| 84 | } | ||
| 85 | |||
| 86 | /// Reads back a `CachedTexture` (Fission Y-down) into Fusion Y-up linear `Vec<[f32; 4]>`. | ||
| 87 | pub(super) fn readback_gpu_to_fusion_y_up(&mut self, tex: &CachedTexture) -> Result<Vec<[f32; 4]>, String> { | ||
| 88 | self.flush_encoder(); | ||
| 89 | let [w, h] = tex.size; | ||
| 90 | let bpp: u32 = match tex.format { | ||
| 91 | wgpu::TextureFormat::Rgba32Float => 16, | ||
| 92 | wgpu::TextureFormat::Rgba16Float => 8, | ||
| 93 | wgpu::TextureFormat::Rgba8Unorm => 4, | ||
| 94 | other => return Err(format!("unsupported format for Fuse CPU readback: {other:?}")), | ||
| 95 | }; | ||
| 96 | let unpadded_bpr = w * bpp; | ||
| 97 | let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT; | ||
| 98 | let padded_bpr = unpadded_bpr.div_ceil(align) * align; | ||
| 99 | let buf_size = u64::from(padded_bpr) * u64::from(h); | ||
| 100 | let staging = self.device.create_buffer(&wgpu::BufferDescriptor { | ||
| 101 | label: Some("fuse-cpu-readback"), | ||
| 102 | size: buf_size.max(4), | ||
| 103 | usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, | ||
| 104 | mapped_at_creation: false, | ||
| 105 | }); | ||
| 106 | let mut enc = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { | ||
| 107 | label: Some("fuse-readback-copy"), | ||
| 108 | }); | ||
| 109 | enc.copy_texture_to_buffer( | ||
| 110 | tex.texture.as_image_copy(), | ||
| 111 | wgpu::TexelCopyBufferInfo { | ||
| 112 | buffer: &staging, | ||
| 113 | layout: wgpu::TexelCopyBufferLayout { | ||
| 114 | offset: 0, | ||
| 115 | bytes_per_row: Some(padded_bpr), | ||
| 116 | rows_per_image: Some(h), | ||
| 117 | }, | ||
| 118 | }, | ||
| 119 | wgpu::Extent3d { | ||
| 120 | width: w, | ||
| 121 | height: h, | ||
| 122 | depth_or_array_layers: 1, | ||
| 123 | }, | ||
| 124 | ); | ||
| 125 | let sub = self.queue.submit(Some(enc.finish())); | ||
| 126 | let slice = staging.slice(..); | ||
| 127 | let (tx, rx) = std::sync::mpsc::channel(); | ||
| 128 | slice.map_async(wgpu::MapMode::Read, move |res| { | ||
| 129 | let _ = tx.send(res); | ||
| 130 | }); | ||
| 131 | let _ = self.device.poll(wgpu::PollType::Wait { | ||
| 132 | submission_index: Some(sub), | ||
| 133 | timeout: Some(std::time::Duration::from_secs(10)), | ||
| 134 | }); | ||
| 135 | rx.recv() | ||
| 136 | .map_err(|e| e.to_string())? | ||
| 137 | .map_err(|e| format!("{e:?}"))?; | ||
| 138 | |||
| 139 | let mapped = slice.get_mapped_range().map_err(|e| format!("{e:?}"))?; | ||
| 140 | let mut pixels = vec![[0.0f32; 4]; (w as usize) * (h as usize)]; | ||
| 141 | for ty in 0..h as usize { | ||
| 142 | let fy = (h as usize) - 1 - ty; // flip Y-down -> Fusion Y-up | ||
| 143 | let row = &mapped[ty * padded_bpr as usize..ty * padded_bpr as usize + unpadded_bpr as usize]; | ||
| 144 | let dst_row = &mut pixels[fy * w as usize..(fy + 1) * w as usize]; | ||
| 145 | match tex.format { | ||
| 146 | wgpu::TextureFormat::Rgba8Unorm => { | ||
| 147 | for (x, c) in row.chunks_exact(4).enumerate() { | ||
| 148 | dst_row[x] = [ | ||
| 149 | f32::from(c[0]) / 255.0, | ||
| 150 | f32::from(c[1]) / 255.0, | ||
| 151 | f32::from(c[2]) / 255.0, | ||
| 152 | f32::from(c[3]) / 255.0, | ||
| 153 | ]; | ||
| 154 | } | ||
| 155 | } | ||
| 156 | wgpu::TextureFormat::Rgba16Float => { | ||
| 157 | for (x, c) in row.chunks_exact(8).enumerate() { | ||
| 158 | dst_row[x] = [ | ||
| 159 | ::exr::prelude::f16::from_bits(u16::from_le_bytes([c[0], c[1]])).to_f32(), | ||
| 160 | ::exr::prelude::f16::from_bits(u16::from_le_bytes([c[2], c[3]])).to_f32(), | ||
| 161 | ::exr::prelude::f16::from_bits(u16::from_le_bytes([c[4], c[5]])).to_f32(), | ||
| 162 | ::exr::prelude::f16::from_bits(u16::from_le_bytes([c[6], c[7]])).to_f32(), | ||
| 163 | ]; | ||
| 164 | } | ||
| 165 | } | ||
| 166 | wgpu::TextureFormat::Rgba32Float => { | ||
| 167 | for (x, c) in row.chunks_exact(16).enumerate() { | ||
| 168 | dst_row[x] = [ | ||
| 169 | f32::from_le_bytes([c[0], c[1], c[2], c[3]]), | ||
| 170 | f32::from_le_bytes([c[4], c[5], c[6], c[7]]), | ||
| 171 | f32::from_le_bytes([c[8], c[9], c[10], c[11]]), | ||
| 172 | f32::from_le_bytes([c[12], c[13], c[14], c[15]]), | ||
| 173 | ]; | ||
| 174 | } | ||
| 175 | } | ||
| 176 | _ => {} | ||
| 177 | } | ||
| 178 | } | ||
| 179 | drop(mapped); | ||
| 180 | staging.unmap(); | ||
| 181 | Ok(pixels) | ||
| 182 | } | ||
| 183 | |||
| 184 | /// Uploads a Fusion Y-up `Vec<[f32; 4]>` buffer into a Fission Y-down GPU `CachedTexture`. | ||
| 185 | pub(super) fn upload_fusion_y_up_to_gpu( | ||
| 186 | &self, | ||
| 187 | width: u32, | ||
| 188 | height: u32, | ||
| 189 | depth: BitDepth, | ||
| 190 | pixels: &[[f32; 4]], | ||
| 191 | hash: u64, | ||
| 192 | ) -> CachedTexture { | ||
| 193 | let tex = self.alloc_gpu_tex([width, height], depth, hash); | ||
| 194 | let w = width as usize; | ||
| 195 | let h = height as usize; | ||
| 196 | match tex.format { | ||
| 197 | wgpu::TextureFormat::Rgba8Unorm => { | ||
| 198 | let mut raw = vec![0u8; w * h * 4]; | ||
| 199 | for ty in 0..h { | ||
| 200 | let fy = h - 1 - ty; | ||
| 201 | for x in 0..w { | ||
| 202 | let p = pixels[fy * w + x]; | ||
| 203 | let o = (ty * w + x) * 4; | ||
| 204 | raw[o] = (p[0].clamp(0.0, 1.0) * 255.0).round() as u8; | ||
| 205 | raw[o + 1] = (p[1].clamp(0.0, 1.0) * 255.0).round() as u8; | ||
| 206 | raw[o + 2] = (p[2].clamp(0.0, 1.0) * 255.0).round() as u8; | ||
| 207 | raw[o + 3] = (p[3].clamp(0.0, 1.0) * 255.0).round() as u8; | ||
| 208 | } | ||
| 209 | } | ||
| 210 | self.queue.write_texture( | ||
| 211 | tex.texture.as_image_copy(), | ||
| 212 | &raw, | ||
| 213 | wgpu::TexelCopyBufferLayout { | ||
| 214 | offset: 0, | ||
| 215 | bytes_per_row: Some(width * 4), | ||
| 216 | rows_per_image: Some(height), | ||
| 217 | }, | ||
| 218 | wgpu::Extent3d { | ||
| 219 | width, | ||
| 220 | height, | ||
| 221 | depth_or_array_layers: 1, | ||
| 222 | }, | ||
| 223 | ); | ||
| 224 | } | ||
| 225 | wgpu::TextureFormat::Rgba16Float => { | ||
| 226 | let mut raw = vec![0u8; w * h * 8]; | ||
| 227 | for ty in 0..h { | ||
| 228 | let fy = h - 1 - ty; | ||
| 229 | for x in 0..w { | ||
| 230 | let p = pixels[fy * w + x]; | ||
| 231 | let o = (ty * w + x) * 8; | ||
| 232 | for (c, &val) in p.iter().enumerate() { | ||
| 233 | let bits = ::exr::prelude::f16::from_f32(val).to_bits().to_le_bytes(); | ||
| 234 | raw[o + c * 2] = bits[0]; | ||
| 235 | raw[o + c * 2 + 1] = bits[1]; | ||
| 236 | } | ||
| 237 | } | ||
| 238 | } | ||
| 239 | self.queue.write_texture( | ||
| 240 | tex.texture.as_image_copy(), | ||
| 241 | &raw, | ||
| 242 | wgpu::TexelCopyBufferLayout { | ||
| 243 | offset: 0, | ||
| 244 | bytes_per_row: Some(width * 8), | ||
| 245 | rows_per_image: Some(height), | ||
| 246 | }, | ||
| 247 | wgpu::Extent3d { | ||
| 248 | width, | ||
| 249 | height, | ||
| 250 | depth_or_array_layers: 1, | ||
| 251 | }, | ||
| 252 | ); | ||
| 253 | } | ||
| 254 | wgpu::TextureFormat::Rgba32Float => { | ||
| 255 | let mut raw = vec![0u8; w * h * 16]; | ||
| 256 | for ty in 0..h { | ||
| 257 | let fy = h - 1 - ty; | ||
| 258 | for x in 0..w { | ||
| 259 | let p = pixels[fy * w + x]; | ||
| 260 | let o = (ty * w + x) * 16; | ||
| 261 | for (c, &val) in p.iter().enumerate() { | ||
| 262 | raw[o + c * 4..o + c * 4 + 4].copy_from_slice(&val.to_le_bytes()); | ||
| 263 | } | ||
| 264 | } | ||
| 265 | } | ||
| 266 | self.queue.write_texture( | ||
| 267 | tex.texture.as_image_copy(), | ||
| 268 | &raw, | ||
| 269 | wgpu::TexelCopyBufferLayout { | ||
| 270 | offset: 0, | ||
| 271 | bytes_per_row: Some(width * 16), | ||
| 272 | rows_per_image: Some(height), | ||
| 273 | }, | ||
| 274 | wgpu::Extent3d { | ||
| 275 | width, | ||
| 276 | height, | ||
| 277 | depth_or_array_layers: 1, | ||
| 278 | }, | ||
| 279 | ); | ||
| 280 | } | ||
| 281 | _ => {} | ||
| 282 | } | ||
| 283 | tex | ||
| 284 | } | ||
| 285 | } | ||
| 286 | |||
| 287 | |||
crates/engine/src/fuse_runtime/lua_dvip.rs created+459| ... | @@ -0,0 +1,459 @@ | ||
| 1 | //! Fusion `DVIPComputeNode` and `ParamBlock` GPU DCTL compilation and dispatch. | ||
| 2 | |||
| 3 | use std::cell::RefCell; | ||
| 4 | use std::collections::hash_map::DefaultHasher; | ||
| 5 | use std::hash::{Hash, Hasher}; | ||
| 6 | use std::rc::Rc; | ||
| 7 | use std::sync::Arc; | ||
| 8 | |||
| 9 | use mlua::{MetaMethod, Result as LuaResult, UserData, UserDataMethods, Value}; | ||
| 10 | |||
| 11 | use crate::cache::CachedTexture; | ||
| 12 | |||
| 13 | use super::CompiledDctlPipeline; | ||
| 14 | use super::dctl::{ParamLayout, parse_param_block, transpile_dctl_to_wgsl}; | ||
| 15 | use super::lua_host::{HostBridge, val_to_f64}; | ||
| 16 | use super::lua_types::{ImageBacking, ImageInner, LuaImage}; | ||
| 17 | |||
| 18 | // --------------------------------------------------------------------------- | ||
| 19 | // DVIPComputeNode + ParamBlock (GPU DCTL execution) | ||
| 20 | // --------------------------------------------------------------------------- | ||
| 21 | |||
| 22 | struct ParamBlockInner { | ||
| 23 | layout: ParamLayout, | ||
| 24 | bytes: Vec<u8>, | ||
| 25 | } | ||
| 26 | |||
| 27 | #[derive(Clone)] | ||
| 28 | struct LuaParamBlock(Rc<RefCell<ParamBlockInner>>); | ||
| 29 | |||
| 30 | #[derive(Clone)] | ||
| 31 | struct LuaParamArrayView { | ||
| 32 | inner: Rc<RefCell<ParamBlockInner>>, | ||
| 33 | field_name: String, | ||
| 34 | } | ||
| 35 | |||
| 36 | impl UserData for LuaParamArrayView { | ||
| 37 | fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) { | ||
| 38 | methods.add_meta_method(MetaMethod::Index, |_, this, key: Value| { | ||
| 39 | let idx = key_to_elem_index(&key)?; | ||
| 40 | let inner = this.inner.borrow(); | ||
| 41 | Ok(inner.layout.read_scalar(&inner.bytes, &this.field_name, Some(idx)).unwrap_or(0.0)) | ||
| 42 | }); | ||
| 43 | methods.add_meta_method(MetaMethod::NewIndex, |_, this, (key, val): (Value, Value)| { | ||
| 44 | let idx = key_to_elem_index(&key)?; | ||
| 45 | let num = val_to_f64(&val); | ||
| 46 | let mut inner = this.inner.borrow_mut(); | ||
| 47 | let layout = inner.layout.clone(); | ||
| 48 | layout.write_scalar(&mut inner.bytes, &this.field_name, Some(idx), num); | ||
| 49 | Ok(()) | ||
| 50 | }); | ||
| 51 | } | ||
| 52 | } | ||
| 53 | |||
| 54 | impl UserData for LuaParamBlock { | ||
| 55 | fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) { | ||
| 56 | methods.add_meta_method(MetaMethod::Index, |lua, this, key: String| { | ||
| 57 | let inner = this.0.borrow(); | ||
| 58 | if let Some(f) = inner.layout.field(&key) { | ||
| 59 | if f.array_len.is_some() || f.ty.components() > 1 { | ||
| 60 | let view = LuaParamArrayView { | ||
| 61 | inner: this.0.clone(), | ||
| 62 | field_name: key, | ||
| 63 | }; | ||
| 64 | return Ok(Value::UserData(lua.create_userdata(view)?)); | ||
| 65 | } | ||
| 66 | let v = inner.layout.read_scalar(&inner.bytes, &key, None).unwrap_or(0.0); | ||
| 67 | return Ok(Value::Number(v)); | ||
| 68 | } | ||
| 69 | Ok(Value::Nil) | ||
| 70 | }); | ||
| 71 | methods.add_meta_method(MetaMethod::NewIndex, |_, this, (key, val): (String, Value)| { | ||
| 72 | let mut inner = this.0.borrow_mut(); | ||
| 73 | let layout = inner.layout.clone(); | ||
| 74 | if let Some(f) = layout.field(&key) { | ||
| 75 | match val { | ||
| 76 | Value::Table(tbl) => { | ||
| 77 | let count = f.array_len.unwrap_or_else(|| f.ty.components()); | ||
| 78 | let zero_based = tbl.get::<Value>(0).ok().is_some_and(|v| !matches!(v, Value::Nil)); | ||
| 79 | for i in 0..count { | ||
| 80 | let k = if zero_based { i as i64 } else { (i + 1) as i64 }; | ||
| 81 | if let Ok(v) = tbl.get::<f64>(k) { | ||
| 82 | layout.write_scalar(&mut inner.bytes, &key, Some(i), v); | ||
| 83 | } | ||
| 84 | } | ||
| 85 | } | ||
| 86 | other => { | ||
| 87 | layout.write_scalar(&mut inner.bytes, &key, None, val_to_f64(&other)); | ||
| 88 | } | ||
| 89 | } | ||
| 90 | } | ||
| 91 | Ok(()) | ||
| 92 | }); | ||
| 93 | } | ||
| 94 | } | ||
| 95 | |||
| 96 | fn key_to_elem_index(key: &Value) -> LuaResult<usize> { | ||
| 97 | match key { | ||
| 98 | Value::Integer(i) if *i >= 0 => Ok(*i as usize), | ||
| 99 | Value::Number(n) if *n >= 0.0 => Ok(*n as usize), | ||
| 100 | Value::String(s) => match s.to_str()?.as_ref() { | ||
| 101 | "x" | "X" | "r" | "R" => Ok(0), | ||
| 102 | "y" | "Y" | "g" | "G" => Ok(1), | ||
| 103 | "z" | "Z" | "b" | "B" => Ok(2), | ||
| 104 | "w" | "W" | "a" | "A" => Ok(3), | ||
| 105 | other => Err(mlua::Error::RuntimeError(format!("unknown vector component `{other}`"))), | ||
| 106 | }, | ||
| 107 | _ => Err(mlua::Error::RuntimeError("invalid param array index".into())), | ||
| 108 | } | ||
| 109 | } | ||
| 110 | |||
| 111 | pub(super) struct DvipNodeInner { | ||
| 112 | pub(super) kernel_name: String, | ||
| 113 | pub(super) source: String, | ||
| 114 | pub(super) params_name: String, | ||
| 115 | pub(super) params_def: String, | ||
| 116 | pub(super) param_bytes: Vec<u8>, | ||
| 117 | pub(super) inputs: Vec<(String, Rc<RefCell<ImageInner>>)>, | ||
| 118 | pub(super) outputs: Vec<(String, Rc<RefCell<ImageInner>>)>, | ||
| 119 | pub(super) normalized_coords: bool, | ||
| 120 | pub(super) linear_filter: bool, | ||
| 121 | pub(super) address_mode: u32, | ||
| 122 | pub(super) error_log: String, | ||
| 123 | } | ||
| 124 | |||
| 125 | #[derive(Clone)] | ||
| 126 | pub(super) struct LuaDvipNode(pub(super) Rc<RefCell<DvipNodeInner>>); | ||
| 127 | |||
| 128 | impl UserData for LuaDvipNode { | ||
| 129 | fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) { | ||
| 130 | methods.add_method("GetParamBlock", |_, this, def_override: Option<String>| { | ||
| 131 | let def = def_override.unwrap_or_else(|| this.0.borrow().params_def.clone()); | ||
| 132 | let layout = parse_param_block(&def).map_err(mlua::Error::RuntimeError)?; | ||
| 133 | let bytes = vec![0u8; layout.buffer_size()]; | ||
| 134 | Ok(LuaParamBlock(Rc::new(RefCell::new(ParamBlockInner { layout, bytes })))) | ||
| 135 | }); | ||
| 136 | methods.add_method("SetParamBlock", |_, this, params: mlua::UserDataRef<LuaParamBlock>| { | ||
| 137 | let bytes = params.0.borrow().bytes.clone(); | ||
| 138 | this.0.borrow_mut().param_bytes = bytes; | ||
| 139 | Ok(()) | ||
| 140 | }); | ||
| 141 | methods.add_method( | ||
| 142 | "AddSampler", | ||
| 143 | |_, this, (_name, filter, addr, norm): (String, Option<i32>, Option<i32>, Option<i32>)| { | ||
| 144 | let mut n = this.0.borrow_mut(); | ||
| 145 | if let Some(f) = filter { | ||
| 146 | n.linear_filter = f != 0; | ||
| 147 | } | ||
| 148 | if let Some(a) = addr { | ||
| 149 | n.address_mode = a.max(0) as u32; | ||
| 150 | } | ||
| 151 | if let Some(nc) = norm { | ||
| 152 | n.normalized_coords = nc != 0; | ||
| 153 | } | ||
| 154 | Ok(()) | ||
| 155 | }, | ||
| 156 | ); | ||
| 157 | methods.add_method("AddInput", |_, this, (name, img): (String, mlua::UserDataRef<LuaImage>)| { | ||
| 158 | let mut n = this.0.borrow_mut(); | ||
| 159 | if let Some(slot) = n.inputs.iter_mut().find(|(k, _)| k == &name) { | ||
| 160 | slot.1 = img.0.clone(); | ||
| 161 | } else { | ||
| 162 | n.inputs.push((name, img.0.clone())); | ||
| 163 | } | ||
| 164 | Ok(()) | ||
| 165 | }); | ||
| 166 | methods.add_method("AddOutput", |_, this, (name, img): (String, mlua::UserDataRef<LuaImage>)| { | ||
| 167 | let mut n = this.0.borrow_mut(); | ||
| 168 | if let Some(slot) = n.outputs.iter_mut().find(|(k, _)| k == &name) { | ||
| 169 | slot.1 = img.0.clone(); | ||
| 170 | } else { | ||
| 171 | n.outputs.push((name, img.0.clone())); | ||
| 172 | } | ||
| 173 | Ok(()) | ||
| 174 | }); | ||
| 175 | methods.add_method("GetErrorLog", |_, this, ()| Ok(this.0.borrow().error_log.clone())); | ||
| 176 | methods.add_method("RunSession", |lua, this, _req: Value| { | ||
| 177 | let mut bridge = lua | ||
| 178 | .app_data_mut::<HostBridge>() | ||
| 179 | .ok_or_else(|| mlua::Error::RuntimeError("missing HostBridge".into()))?; | ||
| 180 | let res = run_dvip_session(&mut this.0.borrow_mut(), &mut bridge); | ||
| 181 | match res { | ||
| 182 | Ok(()) => Ok(true), | ||
| 183 | Err(msg) => { | ||
| 184 | this.0.borrow_mut().error_log = msg; | ||
| 185 | Ok(false) | ||
| 186 | } | ||
| 187 | } | ||
| 188 | }); | ||
| 189 | } | ||
| 190 | } | ||
| 191 | |||
| 192 | fn run_dvip_session(node: &mut DvipNodeInner, bridge: &mut HostBridge) -> Result<(), String> { | ||
| 193 | if node.outputs.is_empty() { | ||
| 194 | return Err("DVIPComputeNode has no registered outputs".to_owned()); | ||
| 195 | } | ||
| 196 | let (dst_size, dst_depth) = { | ||
| 197 | let out0 = node.outputs[0].1.borrow(); | ||
| 198 | ([out0.width.max(1), out0.height.max(1)], out0.depth) | ||
| 199 | }; | ||
| 200 | let dst_format = bridge.format_for_depth(dst_depth); | ||
| 201 | |||
| 202 | // 1. Lookup or compile cached WGSL compute pipeline | ||
| 203 | let mut hasher = DefaultHasher::new(); | ||
| 204 | node.source.hash(&mut hasher); | ||
| 205 | node.kernel_name.hash(&mut hasher); | ||
| 206 | node.params_name.hash(&mut hasher); | ||
| 207 | node.params_def.hash(&mut hasher); | ||
| 208 | let cache_key = (hasher.finish(), dst_format); | ||
| 209 | |||
| 210 | let compiled: Arc<CompiledDctlPipeline> = { | ||
| 211 | let mut cache = bridge | ||
| 212 | .pipeline_cache | ||
| 213 | .lock() | ||
| 214 | .map_err(|_| "DCTL pipeline cache poisoned".to_owned())?; | ||
| 215 | if let Some(hit) = cache.get(&cache_key) { | ||
| 216 | hit | ||
| 217 | } else { | ||
| 218 | let transpiled = transpile_dctl_to_wgsl( | ||
| 219 | &node.source, | ||
| 220 | &node.kernel_name, | ||
| 221 | Some(&node.params_name), | ||
| 222 | Some(&node.params_def), | ||
| 223 | dst_format, | ||
| 224 | )?; | ||
| 225 | let compiled = compile_dctl_pipeline(&bridge.device, &transpiled, dst_format)?; | ||
| 226 | let arc = Arc::new(compiled); | ||
| 227 | cache.insert(cache_key, arc.clone()); | ||
| 228 | arc | ||
| 229 | } | ||
| 230 | }; | ||
| 231 | |||
| 232 | // 2. Ensure GPU textures for all kernel inputs (zero CPU roundtrip!) | ||
| 233 | let mut input_texs: Vec<CachedTexture> = Vec::with_capacity(compiled.input_textures.len()); | ||
| 234 | for (idx, tex_name) in compiled.input_textures.iter().enumerate() { | ||
| 235 | let found = node | ||
| 236 | .inputs | ||
| 237 | .iter() | ||
| 238 | .find(|(k, _)| k == tex_name) | ||
| 239 | .or_else(|| node.inputs.get(idx)); | ||
| 240 | if let Some((_, img_rc)) = found { | ||
| 241 | let tex = img_rc.borrow_mut().ensure_gpu(bridge, bridge.content_hash_seed ^ (idx as u64 + 1)); | ||
| 242 | input_texs.push(tex); | ||
| 243 | } else { | ||
| 244 | input_texs.push(bridge.dummy_tex.clone()); | ||
| 245 | } | ||
| 246 | } | ||
| 247 | |||
| 248 | // 3. Allocate GPU output textures and attach them back onto the Lua output Image handles | ||
| 249 | let mut output_texs: Vec<CachedTexture> = Vec::with_capacity(compiled.output_textures.len()); | ||
| 250 | for (idx, dst_name) in compiled.output_textures.iter().enumerate() { | ||
| 251 | let found = node | ||
| 252 | .outputs | ||
| 253 | .iter() | ||
| 254 | .find(|(k, _)| k == dst_name) | ||
| 255 | .or_else(|| node.outputs.get(idx)); | ||
| 256 | let out_tex = if let Some((_, img_rc)) = found { | ||
| 257 | let mut inner = img_rc.borrow_mut(); | ||
| 258 | let sz = [inner.width.max(1), inner.height.max(1)]; | ||
| 259 | let tex = bridge.alloc_gpu_tex(sz, inner.depth, bridge.content_hash_seed ^ (0xF000 + idx as u64)); | ||
| 260 | inner.backing = ImageBacking::Gpu(tex.clone()); | ||
| 261 | tex | ||
| 262 | } else { | ||
| 263 | bridge.alloc_gpu_tex(dst_size, dst_depth, bridge.content_hash_seed ^ (0xF000 + idx as u64)) | ||
| 264 | }; | ||
| 265 | output_texs.push(out_tex); | ||
| 266 | } | ||
| 267 | |||
| 268 | // 4. Upload params storage buffer & meta uniform buffer | ||
| 269 | let required_param_bytes = compiled.param_layout.buffer_size(); | ||
| 270 | let mut param_data = node.param_bytes.clone(); | ||
| 271 | param_data.resize(required_param_bytes, 0); | ||
| 272 | let param_buf = bridge.device.create_buffer(&wgpu::BufferDescriptor { | ||
| 273 | label: Some("dctl-params-buf"), | ||
| 274 | size: required_param_bytes as u64, | ||
| 275 | usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST, | ||
| 276 | mapped_at_creation: false, | ||
| 277 | }); | ||
| 278 | bridge.queue.write_buffer(&param_buf, 0, &param_data); | ||
| 279 | |||
| 280 | let meta: [u32; 4] = [ | ||
| 281 | dst_size[0], | ||
| 282 | dst_size[1], | ||
| 283 | u32::from(node.normalized_coords), | ||
| 284 | u32::from(node.linear_filter), | ||
| 285 | ]; | ||
| 286 | let meta_buf = bridge.device.create_buffer(&wgpu::BufferDescriptor { | ||
| 287 | label: Some("dctl-meta-buf"), | ||
| 288 | size: 16, | ||
| 289 | usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, | ||
| 290 | mapped_at_creation: false, | ||
| 291 | }); | ||
| 292 | bridge.queue.write_buffer(&meta_buf, 0, bytemuck::cast_slice(&meta)); | ||
| 293 | |||
| 294 | let addr_mode = match node.address_mode { | ||
| 295 | 2 => wgpu::AddressMode::Repeat, | ||
| 296 | 3 => wgpu::AddressMode::MirrorRepeat, | ||
| 297 | _ => wgpu::AddressMode::ClampToEdge, | ||
| 298 | }; | ||
| 299 | let filter = if node.linear_filter { | ||
| 300 | wgpu::FilterMode::Linear | ||
| 301 | } else { | ||
| 302 | wgpu::FilterMode::Nearest | ||
| 303 | }; | ||
| 304 | let sampler = bridge.device.create_sampler(&wgpu::SamplerDescriptor { | ||
| 305 | label: Some("dctl-sampler"), | ||
| 306 | address_mode_u: addr_mode, | ||
| 307 | address_mode_v: addr_mode, | ||
| 308 | mag_filter: filter, | ||
| 309 | min_filter: filter, | ||
| 310 | ..Default::default() | ||
| 311 | }); | ||
| 312 | |||
| 313 | // 5. Build bind group & dispatch compute pass onto the shared CommandEncoder! | ||
| 314 | let mut entries: Vec<wgpu::BindGroupEntry<'_>> = Vec::with_capacity(3 + input_texs.len() + output_texs.len()); | ||
| 315 | entries.push(wgpu::BindGroupEntry { | ||
| 316 | binding: 0, | ||
| 317 | resource: param_buf.as_entire_binding(), | ||
| 318 | }); | ||
| 319 | entries.push(wgpu::BindGroupEntry { | ||
| 320 | binding: 1, | ||
| 321 | resource: wgpu::BindingResource::Sampler(&sampler), | ||
| 322 | }); | ||
| 323 | entries.push(wgpu::BindGroupEntry { | ||
| 324 | binding: 2, | ||
| 325 | resource: meta_buf.as_entire_binding(), | ||
| 326 | }); | ||
| 327 | let mut binding = 3u32; | ||
| 328 | for t in &input_texs { | ||
| 329 | entries.push(wgpu::BindGroupEntry { | ||
| 330 | binding, | ||
| 331 | resource: wgpu::BindingResource::TextureView(&t.view), | ||
| 332 | }); | ||
| 333 | binding += 1; | ||
| 334 | } | ||
| 335 | for t in &output_texs { | ||
| 336 | entries.push(wgpu::BindGroupEntry { | ||
| 337 | binding, | ||
| 338 | resource: wgpu::BindingResource::TextureView(&t.view), | ||
| 339 | }); | ||
| 340 | binding += 1; | ||
| 341 | } | ||
| 342 | let bg = bridge.device.create_bind_group(&wgpu::BindGroupDescriptor { | ||
| 343 | label: Some("dctl-bg"), | ||
| 344 | layout: &compiled.bgl, | ||
| 345 | entries: &entries, | ||
| 346 | }); | ||
| 347 | |||
| 348 | let enc = bridge | ||
| 349 | .encoder | ||
| 350 | .as_mut() | ||
| 351 | .ok_or_else(|| "missing active CommandEncoder".to_owned())?; | ||
| 352 | let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { | ||
| 353 | label: Some("dctl-compute-pass"), | ||
| 354 | timestamp_writes: None, | ||
| 355 | }); | ||
| 356 | pass.set_pipeline(&compiled.pipeline); | ||
| 357 | pass.set_bind_group(0, &bg, &[]); | ||
| 358 | pass.dispatch_workgroups(dst_size[0].div_ceil(8), dst_size[1].div_ceil(8), 1); | ||
| 359 | Ok(()) | ||
| 360 | } | ||
| 361 | |||
| 362 | /// Compiles a transpiled DCTL WGSL shader into a validated `wgpu::ComputePipeline` inside | ||
| 363 | /// `push_error_scope` so malformed Fuses never panic. | ||
| 364 | pub fn compile_dctl_pipeline( | ||
| 365 | device: &wgpu::Device, | ||
| 366 | transpiled: &super::dctl::TranspiledKernel, | ||
| 367 | dst_format: wgpu::TextureFormat, | ||
| 368 | ) -> Result<CompiledDctlPipeline, String> { | ||
| 369 | let mut layout_entries = vec![ | ||
| 370 | wgpu::BindGroupLayoutEntry { | ||
| 371 | binding: 0, | ||
| 372 | visibility: wgpu::ShaderStages::COMPUTE, | ||
| 373 | ty: wgpu::BindingType::Buffer { | ||
| 374 | ty: wgpu::BufferBindingType::Storage { read_only: true }, | ||
| 375 | has_dynamic_offset: false, | ||
| 376 | min_binding_size: None, | ||
| 377 | }, | ||
| 378 | count: None, | ||
| 379 | }, | ||
| 380 | wgpu::BindGroupLayoutEntry { | ||
| 381 | binding: 1, | ||
| 382 | visibility: wgpu::ShaderStages::COMPUTE, | ||
| 383 | ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), | ||
| 384 | count: None, | ||
| 385 | }, | ||
| 386 | wgpu::BindGroupLayoutEntry { | ||
| 387 | binding: 2, | ||
| 388 | visibility: wgpu::ShaderStages::COMPUTE, | ||
| 389 | ty: wgpu::BindingType::Buffer { | ||
| 390 | ty: wgpu::BufferBindingType::Uniform, | ||
| 391 | has_dynamic_offset: false, | ||
| 392 | min_binding_size: None, | ||
| 393 | }, | ||
| 394 | count: None, | ||
| 395 | }, | ||
| 396 | ]; | ||
| 397 | let mut binding = 3u32; | ||
| 398 | for _ in &transpiled.input_textures { | ||
| 399 | layout_entries.push(wgpu::BindGroupLayoutEntry { | ||
| 400 | binding, | ||
| 401 | visibility: wgpu::ShaderStages::COMPUTE, | ||
| 402 | ty: wgpu::BindingType::Texture { | ||
| 403 | sample_type: wgpu::TextureSampleType::Float { filterable: true }, | ||
| 404 | view_dimension: wgpu::TextureViewDimension::D2, | ||
| 405 | multisampled: false, | ||
| 406 | }, | ||
| 407 | count: None, | ||
| 408 | }); | ||
| 409 | binding += 1; | ||
| 410 | } | ||
| 411 | for _ in &transpiled.output_textures { | ||
| 412 | layout_entries.push(wgpu::BindGroupLayoutEntry { | ||
| 413 | binding, | ||
| 414 | visibility: wgpu::ShaderStages::COMPUTE, | ||
| 415 | ty: wgpu::BindingType::StorageTexture { | ||
| 416 | access: wgpu::StorageTextureAccess::WriteOnly, | ||
| 417 | format: dst_format, | ||
| 418 | view_dimension: wgpu::TextureViewDimension::D2, | ||
| 419 | }, | ||
| 420 | count: None, | ||
| 421 | }); | ||
| 422 | binding += 1; | ||
| 423 | } | ||
| 424 | |||
| 425 | let scope = device.push_error_scope(wgpu::ErrorFilter::Validation); | ||
| 426 | let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { | ||
| 427 | label: Some("dctl-bgl"), | ||
| 428 | entries: &layout_entries, | ||
| 429 | }); | ||
| 430 | let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { | ||
| 431 | label: Some("dctl-pl"), | ||
| 432 | bind_group_layouts: &[Some(&bgl)], | ||
| 433 | immediate_size: 0, | ||
| 434 | }); | ||
| 435 | let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { | ||
| 436 | label: Some("dctl-shader"), | ||
| 437 | source: wgpu::ShaderSource::Wgsl(transpiled.wgsl.as_str().into()), | ||
| 438 | }); | ||
| 439 | let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { | ||
| 440 | label: Some("dctl-compute-pipeline"), | ||
| 441 | layout: Some(&pl), | ||
| 442 | module: &module, | ||
| 443 | entry_point: Some(&transpiled.entry_point), | ||
| 444 | compilation_options: Default::default(), | ||
| 445 | cache: None, | ||
| 446 | }); | ||
| 447 | if let Some(err) = pollster::block_on(scope.pop()) { | ||
| 448 | return Err(format!("WGSL validation failed: {err}")); | ||
| 449 | } | ||
| 450 | |||
| 451 | Ok(CompiledDctlPipeline { | ||
| 452 | pipeline, | ||
| 453 | bgl, | ||
| 454 | param_layout: transpiled.param_layout.clone(), | ||
| 455 | input_textures: transpiled.input_textures.clone(), | ||
| 456 | output_textures: transpiled.output_textures.clone(), | ||
| 457 | }) | ||
| 458 | } | ||
| 459 | |||
crates/engine/src/fuse_runtime/lua_host.rs created+669| ... | @@ -0,0 +1,669 @@ | ||
| 1 | //! Sandboxed `mlua` Lua 5.4 host implementing Fusion's Fuse API and GPU-accelerated | ||
| 2 | //! `DVIPComputeNode` execution. | ||
| 3 | |||
| 4 | use std::cell::RefCell; | ||
| 5 | use std::rc::Rc; | ||
| 6 | |||
| 7 | use mlua::{ | ||
| 8 | Function, HookTriggers, Lua, LuaOptions, MultiValue, Result as LuaResult, StdLib, Table, | ||
| 9 | UserData, UserDataFields, UserDataMethods, Value, | ||
| 10 | }; | ||
| 11 | use model::Gradient; | ||
| 12 | |||
| 13 | use crate::cache::CachedTexture; | ||
| 14 | |||
| 15 | use super::dctl::parse_param_block; | ||
| 16 | pub use super::lua_bridge::{EvalParam, HostBridge}; | ||
| 17 | pub use super::lua_dvip::compile_dctl_pipeline; | ||
| 18 | use super::lua_dvip::{DvipNodeInner, LuaDvipNode}; | ||
| 19 | use super::lua_types::{ | ||
| 20 | ImageBacking, ImageInner, LuaGradient, LuaImage, LuaImgRectI, LuaMatrix4, LuaPixel, LuaPoint, | ||
| 21 | LuaVector4, fusion_imdp_to_depth, | ||
| 22 | }; | ||
| 23 | |||
| 24 | const MAX_LUA_HOOK_STEPS: usize = 25_000; // 25_000 * 10_000 = 250M instructions | ||
| 25 | |||
| 26 | // --------------------------------------------------------------------------- | ||
| 27 | // Input / Output / Request / Tool handles | ||
| 28 | // --------------------------------------------------------------------------- | ||
| 29 | |||
| 30 | #[derive(Clone)] | ||
| 31 | struct LuaInput { | ||
| 32 | id: String, | ||
| 33 | data_type: String, | ||
| 34 | default_num: f64, | ||
| 35 | default_pt: [f64; 2], | ||
| 36 | default_str: String, | ||
| 37 | link_main: Option<i32>, | ||
| 38 | } | ||
| 39 | |||
| 40 | impl LuaInput { | ||
| 41 | fn eval_value(&self, lua: &Lua) -> LuaResult<Value> { | ||
| 42 | let bridge = lua | ||
| 43 | .app_data_ref::<HostBridge>() | ||
| 44 | .ok_or_else(|| mlua::Error::RuntimeError("missing HostBridge".into()))?; | ||
| 45 | match self.data_type.as_str() { | ||
| 46 | "Image" => { | ||
| 47 | let tex_opt = bridge | ||
| 48 | .upstream_images | ||
| 49 | .get(&self.id) | ||
| 50 | .cloned() | ||
| 51 | .or_else(|| { | ||
| 52 | if self.link_main == Some(1) { | ||
| 53 | bridge.main_input.clone() | ||
| 54 | } else { | ||
| 55 | None | ||
| 56 | } | ||
| 57 | }); | ||
| 58 | match tex_opt { | ||
| 59 | Some(tex) => { | ||
| 60 | let img = LuaImage(Rc::new(RefCell::new(ImageInner { | ||
| 61 | width: tex.size[0], | ||
| 62 | height: tex.size[1], | ||
| 63 | depth: tex.depth, | ||
| 64 | x_scale: 1.0, | ||
| 65 | y_scale: 1.0, | ||
| 66 | is_mask: false, | ||
| 67 | backing: ImageBacking::Gpu(tex), | ||
| 68 | }))); | ||
| 69 | Ok(Value::UserData(lua.create_userdata(img)?)) | ||
| 70 | } | ||
| 71 | None => Ok(Value::Nil), | ||
| 72 | } | ||
| 73 | } | ||
| 74 | "Point" => { | ||
| 75 | let pt = match bridge.params.get(&self.id) { | ||
| 76 | Some(EvalParam::Point(p)) => *p, | ||
| 77 | _ => self.default_pt, | ||
| 78 | }; | ||
| 79 | Ok(Value::UserData(lua.create_userdata(LuaPoint { x: pt[0], y: pt[1] })?)) | ||
| 80 | } | ||
| 81 | "Text" | "FuID" => { | ||
| 82 | let s = match bridge.params.get(&self.id) { | ||
| 83 | Some(EvalParam::Text(s)) => s.clone(), | ||
| 84 | _ => self.default_str.clone(), | ||
| 85 | }; | ||
| 86 | let tbl = lua.create_table()?; | ||
| 87 | tbl.set("Value", s)?; | ||
| 88 | Ok(Value::Table(tbl)) | ||
| 89 | } | ||
| 90 | "Gradient" => { | ||
| 91 | let g = match bridge.params.get(&self.id) { | ||
| 92 | Some(EvalParam::Gradient(g)) => g.clone(), | ||
| 93 | _ => Gradient::default(), | ||
| 94 | }; | ||
| 95 | Ok(Value::UserData(lua.create_userdata(LuaGradient(g))?)) | ||
| 96 | } | ||
| 97 | _ => { | ||
| 98 | let num = match bridge.params.get(&self.id) { | ||
| 99 | Some(EvalParam::Number(n)) => *n, | ||
| 100 | _ => self.default_num, | ||
| 101 | }; | ||
| 102 | let tbl = lua.create_table()?; | ||
| 103 | tbl.set("Value", num)?; | ||
| 104 | Ok(Value::Table(tbl)) | ||
| 105 | } | ||
| 106 | } | ||
| 107 | } | ||
| 108 | } | ||
| 109 | |||
| 110 | impl UserData for LuaInput { | ||
| 111 | fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) { | ||
| 112 | methods.add_method("GetValue", |lua, this, _req: Value| this.eval_value(lua)); | ||
| 113 | methods.add_method("GetSource", |lua, this, (_t, _flags): (Option<f64>, Option<i32>)| { | ||
| 114 | this.eval_value(lua) | ||
| 115 | }); | ||
| 116 | methods.add_method("SetAttrs", |_, _, _attrs: Value| Ok(())); | ||
| 117 | } | ||
| 118 | } | ||
| 119 | |||
| 120 | #[derive(Clone)] | ||
| 121 | struct LuaOutput; | ||
| 122 | |||
| 123 | impl UserData for LuaOutput { | ||
| 124 | fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) { | ||
| 125 | methods.add_method("Set", |lua, _, (_req, val): (Value, Value)| { | ||
| 126 | if let Value::UserData(ud) = val | ||
| 127 | && let Ok(img) = ud.borrow::<LuaImage>() | ||
| 128 | { | ||
| 129 | if let Some(mut bridge) = lua.app_data_mut::<HostBridge>() { | ||
| 130 | bridge.output_image = Some(img.0.clone()); | ||
| 131 | } | ||
| 132 | } | ||
| 133 | Ok(()) | ||
| 134 | }); | ||
| 135 | } | ||
| 136 | } | ||
| 137 | |||
| 138 | #[derive(Clone, Copy)] | ||
| 139 | struct LuaRequest { | ||
| 140 | time: f64, | ||
| 141 | precalc: bool, | ||
| 142 | width: i32, | ||
| 143 | height: i32, | ||
| 144 | } | ||
| 145 | |||
| 146 | impl UserData for LuaRequest { | ||
| 147 | fn add_fields<F: UserDataFields<Self>>(fields: &mut F) { | ||
| 148 | fields.add_field_method_get("Time", |_, this| Ok(this.time)); | ||
| 149 | } | ||
| 150 | |||
| 151 | fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) { | ||
| 152 | methods.add_method("IsPreCalc", |_, this, ()| Ok(this.precalc)); | ||
| 153 | methods.add_method("IsQuick", |_, _, ()| Ok(false)); | ||
| 154 | methods.add_method("IsNoMotionBlur", |_, _, ()| Ok(false)); | ||
| 155 | methods.add_method("IsStampOnly", |_, _, ()| Ok(false)); | ||
| 156 | methods.add_method("IsFailed", |_, _, ()| Ok(false)); | ||
| 157 | methods.add_method("GetPri", |_, _, ()| Ok(0i32)); | ||
| 158 | methods.add_method("GetRoI", |_, _, ()| Ok(Value::Nil)); | ||
| 159 | methods.add_method("GetDoD", |_, this, ()| { | ||
| 160 | Ok(LuaImgRectI { left: 0, bottom: 0, right: this.width, top: this.height }) | ||
| 161 | }); | ||
| 162 | methods.add_method("GetInputDoD", |_, this, _inp: Value| { | ||
| 163 | Ok(LuaImgRectI { left: 0, bottom: 0, right: this.width, top: this.height }) | ||
| 164 | }); | ||
| 165 | methods.add_method("SetInputRoI", |_, _, (_inp, _rect): (Value, Value)| Ok(())); | ||
| 166 | } | ||
| 167 | } | ||
| 168 | |||
| 169 | struct LuaToolSelf; | ||
| 170 | |||
| 171 | impl UserData for LuaToolSelf { | ||
| 172 | fn add_fields<F: UserDataFields<Self>>(fields: &mut F) { | ||
| 173 | fields.add_field_method_get("Status", |_, _| Ok("OK".to_owned())); | ||
| 174 | fields.add_field_method_get("Comp", |lua, _| { | ||
| 175 | let bridge = lua | ||
| 176 | .app_data_ref::<HostBridge>() | ||
| 177 | .ok_or_else(|| mlua::Error::RuntimeError("missing HostBridge".into()))?; | ||
| 178 | let comp_tbl = lua.create_table()?; | ||
| 179 | comp_tbl.set("CurrentTime", bridge.time)?; | ||
| 180 | comp_tbl.set("GlobalStart", bridge.global_range[0])?; | ||
| 181 | comp_tbl.set("GlobalEnd", bridge.global_range[1])?; | ||
| 182 | comp_tbl.set("RenderStart", bridge.render_range[0])?; | ||
| 183 | comp_tbl.set("RenderEnd", bridge.render_range[1])?; | ||
| 184 | let dims = bridge.comp_dims; | ||
| 185 | comp_tbl.set( | ||
| 186 | "GetPrefs", | ||
| 187 | lua.create_function(move |lua, (_self, key): (Value, Option<String>)| { | ||
| 188 | if let Some(k) = key | ||
| 189 | && k.contains("Width") | ||
| 190 | { | ||
| 191 | return Ok(Value::Integer(i64::from(dims[0]))); | ||
| 192 | } | ||
| 193 | let t = lua.create_table()?; | ||
| 194 | Ok(Value::Table(t)) | ||
| 195 | })?, | ||
| 196 | )?; | ||
| 197 | Ok(comp_tbl) | ||
| 198 | }); | ||
| 199 | } | ||
| 200 | |||
| 201 | fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) { | ||
| 202 | methods.add_method("AddInput", |_, _, (_label, id, attrs): (String, String, Option<Table>)| { | ||
| 203 | let mut data_type = "Number".to_owned(); | ||
| 204 | let mut default_num = 0.0f64; | ||
| 205 | let mut default_pt = [0.5f64, 0.5f64]; | ||
| 206 | let mut default_str = String::new(); | ||
| 207 | let mut link_main = None; | ||
| 208 | if let Some(t) = attrs { | ||
| 209 | if let Ok(dt) = t.get::<String>("LINKID_DataType") { | ||
| 210 | data_type = dt; | ||
| 211 | } | ||
| 212 | if let Ok(v) = t.get::<f64>("INP_Default") { | ||
| 213 | default_num = v; | ||
| 214 | } | ||
| 215 | if let Ok(v) = t.get::<f64>("INP_DefaultX") { | ||
| 216 | default_pt[0] = v; | ||
| 217 | } | ||
| 218 | if let Ok(v) = t.get::<f64>("INP_DefaultY") { | ||
| 219 | default_pt[1] = v; | ||
| 220 | } | ||
| 221 | if let Ok(s) = t.get::<String>("INPID_DefaultID") { | ||
| 222 | default_str = s; | ||
| 223 | } else if let Ok(s) = t.get::<String>("INPS_DefaultText") { | ||
| 224 | default_str = s; | ||
| 225 | } | ||
| 226 | if let Ok(lm) = t.get::<i32>("LINK_Main") { | ||
| 227 | link_main = Some(lm); | ||
| 228 | } | ||
| 229 | } | ||
| 230 | Ok(LuaInput { id, data_type, default_num, default_pt, default_str, link_main }) | ||
| 231 | }); | ||
| 232 | methods.add_method("AddOutput", |_, _, (_label, _id, _attrs): (String, String, Option<Table>)| { | ||
| 233 | Ok(LuaOutput) | ||
| 234 | }); | ||
| 235 | methods.add_method("BeginControlNest", |_, _, _: MultiValue| Ok(())); | ||
| 236 | methods.add_method("EndControlNest", |_, _, _: MultiValue| Ok(())); | ||
| 237 | methods.add_method("AddControlPage", |_, _, _: MultiValue| Ok(())); | ||
| 238 | methods.add_method("SetProgress", |_, _, _p: Option<f64>| Ok(())); | ||
| 239 | methods.add_method("SetData", |lua, _, (k, v): (String, Value)| { | ||
| 240 | if let Some(mut b) = lua.app_data_mut::<HostBridge>() { | ||
| 241 | b.tool_data.insert(k, format!("{v:?}")); | ||
| 242 | } | ||
| 243 | Ok(()) | ||
| 244 | }); | ||
| 245 | methods.add_method("GetData", |lua, _, k: String| { | ||
| 246 | if let Some(b) = lua.app_data_ref::<HostBridge>() { | ||
| 247 | if let Some(v) = b.tool_data.get(&k) { | ||
| 248 | return Ok(Value::String(lua.create_string(v)?)); | ||
| 249 | } | ||
| 250 | } | ||
| 251 | Ok(Value::Nil) | ||
| 252 | }); | ||
| 253 | methods.add_method( | ||
| 254 | "DoMultiProcess", | ||
| 255 | |lua, _, (init_fn, args_tbl, count, func): (Option<Function>, Option<Table>, i32, Function)| { | ||
| 256 | let saved = apply_temp_globals(lua, args_tbl.as_ref())?; | ||
| 257 | if let Some(init) = init_fn { | ||
| 258 | init.call::<()>(())?; | ||
| 259 | } | ||
| 260 | for y in 0..count.max(0) { | ||
| 261 | func.call::<()>(y)?; | ||
| 262 | } | ||
| 263 | restore_temp_globals(lua, saved)?; | ||
| 264 | Ok(()) | ||
| 265 | }, | ||
| 266 | ); | ||
| 267 | } | ||
| 268 | } | ||
| 269 | |||
| 270 | |||
| 271 | // --------------------------------------------------------------------------- | ||
| 272 | // Helpers & Entry Point | ||
| 273 | // --------------------------------------------------------------------------- | ||
| 274 | |||
| 275 | pub(super) fn val_to_f64(v: &Value) -> f64 { | ||
| 276 | match v { | ||
| 277 | Value::Number(n) => *n, | ||
| 278 | Value::Integer(i) => *i as f64, | ||
| 279 | Value::Boolean(b) => if *b { 1.0 } else { 0.0 }, | ||
| 280 | _ => 0.0, | ||
| 281 | } | ||
| 282 | } | ||
| 283 | |||
| 284 | pub(super) fn val_to_i32(v: &Value) -> i32 { | ||
| 285 | val_to_f64(v).round() as i32 | ||
| 286 | } | ||
| 287 | |||
| 288 | pub(super) fn apply_temp_globals(lua: &Lua, tbl: Option<&Table>) -> LuaResult<Vec<(String, Value)>> { | ||
| 289 | let mut saved = Vec::new(); | ||
| 290 | let Some(t) = tbl else { | ||
| 291 | return Ok(saved); | ||
| 292 | }; | ||
| 293 | let globals = lua.globals(); | ||
| 294 | for pair in t.pairs::<String, Value>() { | ||
| 295 | let (k, v) = pair?; | ||
| 296 | let prev = globals.get::<Value>(k.as_str())?; | ||
| 297 | saved.push((k.clone(), prev)); | ||
| 298 | globals.set(k, v)?; | ||
| 299 | } | ||
| 300 | Ok(saved) | ||
| 301 | } | ||
| 302 | |||
| 303 | pub(super) fn restore_temp_globals(lua: &Lua, saved: Vec<(String, Value)>) -> LuaResult<()> { | ||
| 304 | let globals = lua.globals(); | ||
| 305 | for (k, v) in saved { | ||
| 306 | globals.set(k, v)?; | ||
| 307 | } | ||
| 308 | Ok(()) | ||
| 309 | } | ||
| 310 | |||
| 311 | /// Executes a `.fuse` script inside a sandboxed Lua 5.4 environment, running | ||
| 312 | /// `FuRegisterClass`, `Create()`, and `Process(req)`. | ||
| 313 | /// | ||
| 314 | /// Always returns the (possibly refreshed) `CommandEncoder` alongside the execution result. | ||
| 315 | pub fn execute_fuse( | ||
| 316 | source: &str, | ||
| 317 | bridge: HostBridge, | ||
| 318 | ) -> (Result<Option<CachedTexture>, String>, wgpu::CommandEncoder) { | ||
| 319 | let result = execute_fuse_inner(source, bridge); | ||
| 320 | match result { | ||
| 321 | Ok((tex, enc)) => (Ok(tex), enc), | ||
| 322 | Err((msg, enc)) => (Err(msg), enc), | ||
| 323 | } | ||
| 324 | } | ||
| 325 | |||
| 326 | fn execute_fuse_inner( | ||
| 327 | source: &str, | ||
| 328 | bridge: HostBridge, | ||
| 329 | ) -> Result<(Option<CachedTexture>, wgpu::CommandEncoder), (String, wgpu::CommandEncoder)> { | ||
| 330 | let device_fallback = bridge.device.clone(); | ||
| 331 | let stdlib = StdLib::TABLE | StdLib::STRING | StdLib::MATH | StdLib::UTF8 | StdLib::COROUTINE; | ||
| 332 | let lua = match Lua::new_with(stdlib, LuaOptions::default()) { | ||
| 333 | Ok(l) => l, | ||
| 334 | Err(e) => { | ||
| 335 | let enc = bridge.encoder.unwrap_or_else(|| { | ||
| 336 | device_fallback.create_command_encoder(&Default::default()) | ||
| 337 | }); | ||
| 338 | return Err((format!("failed to create Lua VM: {e}"), enc)); | ||
| 339 | } | ||
| 340 | }; | ||
| 341 | |||
| 342 | // Instruction budget guard against infinite loops in untrusted Fuses | ||
| 343 | let steps = Rc::new(RefCell::new(0usize)); | ||
| 344 | let steps_hook = steps.clone(); | ||
| 345 | lua.set_hook(HookTriggers::new().every_nth_instruction(10_000), move |_, _| { | ||
| 346 | let mut c = steps_hook.borrow_mut(); | ||
| 347 | *c += 1; | ||
| 348 | if *c > MAX_LUA_HOOK_STEPS { | ||
| 349 | return Err(mlua::Error::RuntimeError("Fuse exceeded Lua instruction budget".into())); | ||
| 350 | } | ||
| 351 | Ok(mlua::VmState::Continue) | ||
| 352 | }); | ||
| 353 | |||
| 354 | let time = bridge.time; | ||
| 355 | let comp_dims = bridge.comp_dims; | ||
| 356 | let main_dims = bridge.main_input.as_ref().map_or(comp_dims, |t| t.size); | ||
| 357 | lua.set_app_data(bridge); | ||
| 358 | |||
| 359 | let run_res: LuaResult<Option<CachedTexture>> = (|| { | ||
| 360 | register_fusion_globals(&lua)?; | ||
| 361 | // Execute top-level Fuse script (runs FuRegisterClass and defines Create / Process) | ||
| 362 | lua.load(source).exec()?; | ||
| 363 | |||
| 364 | let globals = lua.globals(); | ||
| 365 | globals.set("self", LuaToolSelf)?; | ||
| 366 | |||
| 367 | // For CT_SourceTool fuses (like HexagonTiles.fuse), Fusion pre-creates OutImage & Width/Height globals. | ||
| 368 | let (src_w, src_h, is_source) = { | ||
| 369 | let b = lua.app_data_ref::<HostBridge>().unwrap(); | ||
| 370 | let w = match b.params.get("Width") { | ||
| 371 | Some(EvalParam::Number(n)) if *n >= 1.0 => *n as u32, | ||
| 372 | _ => b.comp_dims[0], | ||
| 373 | }; | ||
| 374 | let h = match b.params.get("Height") { | ||
| 375 | Some(EvalParam::Number(n)) if *n >= 1.0 => *n as u32, | ||
| 376 | _ => b.comp_dims[1], | ||
| 377 | }; | ||
| 378 | (w, h, b.fuse_meta.class_type == "SourceTool") | ||
| 379 | }; | ||
| 380 | if is_source { | ||
| 381 | globals.set("OutImage", LuaOutput)?; | ||
| 382 | } | ||
| 383 | globals.set("Width", src_w as f64)?; | ||
| 384 | globals.set("Height", src_h as f64)?; | ||
| 385 | globals.set("Scale", 1.0f64)?; | ||
| 386 | globals.set("XAspect", 1.0f64)?; | ||
| 387 | globals.set("YAspect", 1.0f64)?; | ||
| 388 | globals.set("SourceDepth", 0i32)?; | ||
| 389 | |||
| 390 | if let Ok(create_fn) = globals.get::<Function>("Create") { | ||
| 391 | create_fn.call::<()>(())?; | ||
| 392 | } | ||
| 393 | |||
| 394 | let req = LuaRequest { | ||
| 395 | time, | ||
| 396 | precalc: false, | ||
| 397 | width: main_dims[0] as i32, | ||
| 398 | height: main_dims[1] as i32, | ||
| 399 | }; | ||
| 400 | if let Ok(process_fn) = globals.get::<Function>("Process") { | ||
| 401 | process_fn.call::<()>(req)?; | ||
| 402 | } else { | ||
| 403 | return Err(mlua::Error::RuntimeError("Fuse defines no Process(req) function".into())); | ||
| 404 | } | ||
| 405 | |||
| 406 | let out_rc = lua | ||
| 407 | .app_data_ref::<HostBridge>() | ||
| 408 | .and_then(|b| b.output_image.clone()); | ||
| 409 | if let Some(img_rc) = out_rc { | ||
| 410 | let bridge = lua.app_data_ref::<HostBridge>().unwrap(); | ||
| 411 | let hash = bridge.content_hash_seed; | ||
| 412 | let tex = img_rc.borrow_mut().ensure_gpu(&bridge, hash); | ||
| 413 | Ok(Some(tex)) | ||
| 414 | } else { | ||
| 415 | Ok(None) | ||
| 416 | } | ||
| 417 | })(); | ||
| 418 | |||
| 419 | let enc = lua | ||
| 420 | .remove_app_data::<HostBridge>() | ||
| 421 | .and_then(|b| b.encoder) | ||
| 422 | .unwrap_or_else(|| device_fallback.create_command_encoder(&Default::default())); | ||
| 423 | |||
| 424 | match run_res { | ||
| 425 | Ok(tex) => Ok((tex, enc)), | ||
| 426 | Err(e) => Err((e.to_string(), enc)), | ||
| 427 | } | ||
| 428 | } | ||
| 429 | |||
| 430 | fn register_fusion_globals(lua: &Lua) -> LuaResult<()> { | ||
| 431 | let g = lua.globals(); | ||
| 432 | |||
| 433 | // Constants | ||
| 434 | g.set("CT_Tool", "Tool")?; | ||
| 435 | g.set("CT_SourceTool", "SourceTool")?; | ||
| 436 | g.set("CT_ParticleTool", "ParticleTool")?; | ||
| 437 | g.set("CT_Modifier", "Modifier")?; | ||
| 438 | g.set("IMDP_8bitInt", 5i32)?; | ||
| 439 | g.set("IMDP_16bitInt", 6i32)?; | ||
| 440 | g.set("IMDP_16bitFloat", 7i32)?; | ||
| 441 | g.set("IMDP_32bitFloat", 8i32)?; | ||
| 442 | g.set("IMDP_32bitInt", 5i32)?; | ||
| 443 | g.set("IMDP_64bitInt", 6i32)?; | ||
| 444 | g.set("IMDP_64bitFloat", 7i32)?; | ||
| 445 | g.set("IMDP_128bitFloat", 8i32)?; | ||
| 446 | |||
| 447 | g.set("TEX_FILTER_MODE_POINT", 0i32)?; | ||
| 448 | g.set("TEX_FILTER_MODE_LINEAR", 1i32)?; | ||
| 449 | g.set("TEX_ADDRESS_MODE_CLAMP", 0i32)?; | ||
| 450 | g.set("TEX_ADDRESS_MODE_BORDER", 1i32)?; | ||
| 451 | g.set("TEX_ADDRESS_MODE_WRAP", 2i32)?; | ||
| 452 | g.set("TEX_ADDRESS_MODE_MIRROR", 3i32)?; | ||
| 453 | g.set("TEX_ADDRESS_MODE_DUPLICATE", 0i32)?; | ||
| 454 | g.set("TEX_NORMALIZED_COORDS_FALSE", 0i32)?; | ||
| 455 | g.set("TEX_NORMALIZED_COORDS_TRUE", 1i32)?; | ||
| 456 | |||
| 457 | g.set("FuPLATFORM_MAC", cfg!(target_os = "macos"))?; | ||
| 458 | g.set("FuPLATFORM_WINDOWS", cfg!(target_os = "windows"))?; | ||
| 459 | g.set("FuPLATFORM_LINUX", cfg!(target_os = "linux"))?; | ||
| 460 | |||
| 461 | // Compatibility helpers (no-op dump/print/collectgarbage, unpack alias) | ||
| 462 | g.set("print", lua.create_function(|_, _: MultiValue| Ok(()))?)?; | ||
| 463 | g.set("dump", lua.create_function(|_, _: MultiValue| Ok(()))?)?; | ||
| 464 | g.set("collectgarbage", lua.create_function(|_, _: MultiValue| Ok(0))?)?; | ||
| 465 | if let Ok(tbl_mod) = g.get::<Table>("table") | ||
| 466 | && let Ok(unpack_fn) = tbl_mod.get::<Function>("unpack") | ||
| 467 | { | ||
| 468 | g.set("unpack", unpack_fn)?; | ||
| 469 | } | ||
| 470 | |||
| 471 | // FuRegisterClass(id, class_type, attrs) | ||
| 472 | g.set( | ||
| 473 | "FuRegisterClass", | ||
| 474 | lua.create_function(|lua, (id, class_type, attrs): (String, String, Option<Table>)| { | ||
| 475 | if let Some(mut b) = lua.app_data_mut::<HostBridge>() { | ||
| 476 | b.fuse_meta.id = id.clone(); | ||
| 477 | b.fuse_meta.class_type = class_type; | ||
| 478 | b.fuse_meta.name = id; | ||
| 479 | if let Some(t) = attrs { | ||
| 480 | if let Ok(n) = t.get::<String>("REGS_Name") { | ||
| 481 | b.fuse_meta.name = n; | ||
| 482 | } else if let Ok(n) = t.get::<String>("REG_Name") { | ||
| 483 | b.fuse_meta.name = n; | ||
| 484 | } | ||
| 485 | if let Ok(v) = t.get::<bool>("REG_OpNoMask") { | ||
| 486 | b.fuse_meta.op_no_mask = v; | ||
| 487 | } | ||
| 488 | if let Ok(v) = t.get::<bool>("REG_TimeVariant") { | ||
| 489 | b.fuse_meta.time_variant = v; | ||
| 490 | } | ||
| 491 | } | ||
| 492 | } | ||
| 493 | Ok(()) | ||
| 494 | })?, | ||
| 495 | )?; | ||
| 496 | |||
| 497 | // Pixel({ R, G, B, A }) or Pixel(r, g, b, a) | ||
| 498 | g.set( | ||
| 499 | "Pixel", | ||
| 500 | lua.create_function(|_, args: MultiValue| { | ||
| 501 | let vals: Vec<Value> = args.into_iter().collect(); | ||
| 502 | let mut p = LuaPixel::default(); | ||
| 503 | if let Some(Value::Table(t)) = vals.first() { | ||
| 504 | if let Ok(v) = t.get::<f64>("R") { p.r = v as f32; } | ||
| 505 | if let Ok(v) = t.get::<f64>("G") { p.g = v as f32; } | ||
| 506 | if let Ok(v) = t.get::<f64>("B") { p.b = v as f32; } | ||
| 507 | if let Ok(v) = t.get::<f64>("A") { p.a = v as f32; } | ||
| 508 | } else if !vals.is_empty() { | ||
| 509 | p.r = val_to_f64(&vals[0]) as f32; | ||
| 510 | if vals.len() > 1 { p.g = val_to_f64(&vals[1]) as f32; } | ||
| 511 | if vals.len() > 2 { p.b = val_to_f64(&vals[2]) as f32; } | ||
| 512 | if vals.len() > 3 { p.a = val_to_f64(&vals[3]) as f32; } | ||
| 513 | } | ||
| 514 | Ok(p) | ||
| 515 | })?, | ||
| 516 | )?; | ||
| 517 | |||
| 518 | // Point(x, y) | ||
| 519 | g.set( | ||
| 520 | "Point", | ||
| 521 | lua.create_function(|_, (x, y): (Option<f64>, Option<f64>)| { | ||
| 522 | Ok(LuaPoint { x: x.unwrap_or(0.0), y: y.unwrap_or(0.0) }) | ||
| 523 | })?, | ||
| 524 | )?; | ||
| 525 | |||
| 526 | // Vector4(x, y, z, w) | ||
| 527 | g.set( | ||
| 528 | "Vector4", | ||
| 529 | lua.create_function(|_, (x, y, z, w): (Option<f64>, Option<f64>, Option<f64>, Option<f64>)| { | ||
| 530 | Ok(LuaVector4 { | ||
| 531 | x: x.unwrap_or(0.0), | ||
| 532 | y: y.unwrap_or(0.0), | ||
| 533 | z: z.unwrap_or(0.0), | ||
| 534 | w: w.unwrap_or(1.0), | ||
| 535 | }) | ||
| 536 | })?, | ||
| 537 | )?; | ||
| 538 | |||
| 539 | // ImgRectI / FuRectInt | ||
| 540 | let make_rect = lua.create_function( | ||
| 541 | |_, (l, b, r, t): (Option<f64>, Option<f64>, Option<f64>, Option<f64>)| { | ||
| 542 | Ok(LuaImgRectI { | ||
| 543 | left: l.unwrap_or(0.0).round() as i32, | ||
| 544 | bottom: b.unwrap_or(0.0).round() as i32, | ||
| 545 | right: r.unwrap_or(0.0).round() as i32, | ||
| 546 | top: t.unwrap_or(0.0).round() as i32, | ||
| 547 | }) | ||
| 548 | }, | ||
| 549 | )?; | ||
| 550 | g.set("ImgRectI", make_rect.clone())?; | ||
| 551 | g.set("FuRectInt", make_rect)?; | ||
| 552 | |||
| 553 | // Matrix4() | ||
| 554 | g.set("Matrix4", lua.create_function(|_, ()| Ok(LuaMatrix4::identity()))?)?; | ||
| 555 | |||
| 556 | // Gradient("GP_SolidWhite" | "GP_SolidBlack") | ||
| 557 | g.set( | ||
| 558 | "Gradient", | ||
| 559 | lua.create_function(|_, preset: Option<String>| { | ||
| 560 | let g = match preset.as_deref() { | ||
| 561 | Some("GP_SolidBlack") => Gradient { | ||
| 562 | stops: vec![model::GradientStop { pos: 0.0, rgba: [0.0, 0.0, 0.0, 1.0] }], | ||
| 563 | }, | ||
| 564 | _ => Gradient::default(), | ||
| 565 | }; | ||
| 566 | Ok(LuaGradient(g)) | ||
| 567 | })?, | ||
| 568 | )?; | ||
| 569 | |||
| 570 | // Image(attrs) | ||
| 571 | g.set( | ||
| 572 | "Image", | ||
| 573 | lua.create_function(|lua, attrs: Option<Table>| { | ||
| 574 | let (mut width, mut height, mut depth) = { | ||
| 575 | let b = lua.app_data_ref::<HostBridge>().unwrap(); | ||
| 576 | (b.comp_dims[0], b.comp_dims[1], b.default_depth) | ||
| 577 | }; | ||
| 578 | let mut x_scale = 1.0; | ||
| 579 | let mut y_scale = 1.0; | ||
| 580 | let mut defer_alloc = false; | ||
| 581 | |||
| 582 | if let Some(t) = attrs { | ||
| 583 | if let Ok(Value::UserData(like_ud)) = t.get::<Value>("IMG_Like") | ||
| 584 | && let Ok(like) = like_ud.borrow::<LuaImage>() | ||
| 585 | { | ||
| 586 | let lb = like.0.borrow(); | ||
| 587 | width = lb.width; | ||
| 588 | height = lb.height; | ||
| 589 | depth = lb.depth; | ||
| 590 | x_scale = lb.x_scale; | ||
| 591 | y_scale = lb.y_scale; | ||
| 592 | } | ||
| 593 | if let Ok(w) = t.get::<f64>("IMG_Width") | ||
| 594 | && w >= 1.0 | ||
| 595 | { | ||
| 596 | width = w.round() as u32; | ||
| 597 | } | ||
| 598 | if let Ok(h) = t.get::<f64>("IMG_Height") | ||
| 599 | && h >= 1.0 | ||
| 600 | { | ||
| 601 | height = h.round() as u32; | ||
| 602 | } | ||
| 603 | if let Ok(d) = t.get::<i32>("IMG_Depth") | ||
| 604 | && let Some(bd) = fusion_imdp_to_depth(d) | ||
| 605 | { | ||
| 606 | depth = bd; | ||
| 607 | } | ||
| 608 | if let Ok(xs) = t.get::<f64>("IMG_XScale") { x_scale = xs; } | ||
| 609 | if let Ok(ys) = t.get::<f64>("IMG_YScale") { y_scale = ys; } | ||
| 610 | if let Ok(da) = t.get::<bool>("IMG_DeferAlloc") { defer_alloc = da; } | ||
| 611 | if let Ok(nd) = t.get::<bool>("IMG_NoData") | ||
| 612 | && nd | ||
| 613 | { | ||
| 614 | defer_alloc = true; | ||
| 615 | } | ||
| 616 | } | ||
| 617 | |||
| 618 | let backing = if defer_alloc { | ||
| 619 | ImageBacking::Deferred | ||
| 620 | } else { | ||
| 621 | ImageBacking::Cpu(vec![[0.0; 4]; (width as usize) * (height as usize)]) | ||
| 622 | }; | ||
| 623 | Ok(LuaImage(Rc::new(RefCell::new(ImageInner { | ||
| 624 | width: width.max(1), | ||
| 625 | height: height.max(1), | ||
| 626 | depth, | ||
| 627 | x_scale, | ||
| 628 | y_scale, | ||
| 629 | is_mask: false, | ||
| 630 | backing, | ||
| 631 | })))) | ||
| 632 | })?, | ||
| 633 | )?; | ||
| 634 | |||
| 635 | // DVIPComputeNode(req, kernel_name, source, params_name, params_def) | ||
| 636 | g.set( | ||
| 637 | "DVIPComputeNode", | ||
| 638 | lua.create_function( | ||
| 639 | |_, (_req, kernel_name, source, params_name, params_def): ( | ||
| 640 | Value, | ||
| 641 | String, | ||
| 642 | String, | ||
| 643 | Option<String>, | ||
| 644 | Option<String>, | ||
| 645 | )| { | ||
| 646 | let pdef = params_def.unwrap_or_default(); | ||
| 647 | let pname = params_name.unwrap_or_else(|| "DctlParams".to_owned()); | ||
| 648 | let init_bytes = parse_param_block(&pdef) | ||
| 649 | .map(|l| vec![0u8; l.buffer_size()]) | ||
| 650 | .unwrap_or_else(|_| vec![0u8; 16]); | ||
| 651 | Ok(LuaDvipNode(Rc::new(RefCell::new(DvipNodeInner { | ||
| 652 | kernel_name, | ||
| 653 | source, | ||
| 654 | params_name: pname, | ||
| 655 | params_def: pdef, | ||
| 656 | param_bytes: init_bytes, | ||
| 657 | inputs: Vec::new(), | ||
| 658 | outputs: Vec::new(), | ||
| 659 | normalized_coords: false, | ||
| 660 | linear_filter: false, | ||
| 661 | address_mode: 0, | ||
| 662 | error_log: String::new(), | ||
| 663 | })))) | ||
| 664 | }, | ||
| 665 | )?, | ||
| 666 | )?; | ||
| 667 | |||
| 668 | Ok(()) | ||
| 669 | } | ||
crates/engine/src/fuse_runtime/lua_types.rs created+636| ... | @@ -0,0 +1,636 @@ | ||
| 1 | //! Fusion Lua data types (`Pixel`, `Point`, `Vector4`, `ImgRectI`, `Matrix4`, `Gradient`, `Image`). | ||
| 2 | |||
| 3 | use std::cell::RefCell; | ||
| 4 | use std::rc::Rc; | ||
| 5 | |||
| 6 | use mlua::{ | ||
| 7 | Function, Lua, MetaMethod, MultiValue, Result as LuaResult, UserData, UserDataFields, | ||
| 8 | UserDataMethods, Value, | ||
| 9 | }; | ||
| 10 | use model::{BitDepth, Gradient}; | ||
| 11 | |||
| 12 | use crate::cache::CachedTexture; | ||
| 13 | |||
| 14 | use super::lua_host::{HostBridge, apply_temp_globals, restore_temp_globals, val_to_i32}; | ||
| 15 | |||
| 16 | // --------------------------------------------------------------------------- | ||
| 17 | // Backing types for Fusion Lua UserData | ||
| 18 | // --------------------------------------------------------------------------- | ||
| 19 | |||
| 20 | #[derive(Clone, Copy, Debug, Default)] | ||
| 21 | pub(super) struct LuaPixel { | ||
| 22 | pub(super) r: f32, | ||
| 23 | pub(super) g: f32, | ||
| 24 | pub(super) b: f32, | ||
| 25 | pub(super) a: f32, | ||
| 26 | } | ||
| 27 | |||
| 28 | impl UserData for LuaPixel { | ||
| 29 | fn add_fields<F: UserDataFields<Self>>(fields: &mut F) { | ||
| 30 | fields.add_field_method_get("R", |_, this| Ok(f64::from(this.r))); | ||
| 31 | fields.add_field_method_set("R", |_, this, v: f64| { | ||
| 32 | this.r = v as f32; | ||
| 33 | Ok(()) | ||
| 34 | }); | ||
| 35 | fields.add_field_method_get("G", |_, this| Ok(f64::from(this.g))); | ||
| 36 | fields.add_field_method_set("G", |_, this, v: f64| { | ||
| 37 | this.g = v as f32; | ||
| 38 | Ok(()) | ||
| 39 | }); | ||
| 40 | fields.add_field_method_get("B", |_, this| Ok(f64::from(this.b))); | ||
| 41 | fields.add_field_method_set("B", |_, this, v: f64| { | ||
| 42 | this.b = v as f32; | ||
| 43 | Ok(()) | ||
| 44 | }); | ||
| 45 | fields.add_field_method_get("A", |_, this| Ok(f64::from(this.a))); | ||
| 46 | fields.add_field_method_set("A", |_, this, v: f64| { | ||
| 47 | this.a = v as f32; | ||
| 48 | Ok(()) | ||
| 49 | }); | ||
| 50 | } | ||
| 51 | |||
| 52 | fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) { | ||
| 53 | methods.add_method_mut("Clear", |_, this, ()| { | ||
| 54 | *this = LuaPixel::default(); | ||
| 55 | Ok(()) | ||
| 56 | }); | ||
| 57 | } | ||
| 58 | } | ||
| 59 | |||
| 60 | #[derive(Clone, Copy, Debug)] | ||
| 61 | pub(super) struct LuaPoint { | ||
| 62 | pub(super) x: f64, | ||
| 63 | pub(super) y: f64, | ||
| 64 | } | ||
| 65 | |||
| 66 | impl UserData for LuaPoint { | ||
| 67 | fn add_fields<F: UserDataFields<Self>>(fields: &mut F) { | ||
| 68 | fields.add_field_method_get("X", |_, this| Ok(this.x)); | ||
| 69 | fields.add_field_method_set("X", |_, this, v: f64| { | ||
| 70 | this.x = v; | ||
| 71 | Ok(()) | ||
| 72 | }); | ||
| 73 | fields.add_field_method_get("Y", |_, this| Ok(this.y)); | ||
| 74 | fields.add_field_method_set("Y", |_, this, v: f64| { | ||
| 75 | this.y = v; | ||
| 76 | Ok(()) | ||
| 77 | }); | ||
| 78 | } | ||
| 79 | |||
| 80 | fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) { | ||
| 81 | methods.add_meta_method(MetaMethod::Add, |_, a, b: mlua::UserDataRef<LuaPoint>| { | ||
| 82 | Ok(LuaPoint { x: a.x + b.x, y: a.y + b.y }) | ||
| 83 | }); | ||
| 84 | methods.add_meta_method(MetaMethod::Sub, |_, a, b: mlua::UserDataRef<LuaPoint>| { | ||
| 85 | Ok(LuaPoint { x: a.x - b.x, y: a.y - b.y }) | ||
| 86 | }); | ||
| 87 | methods.add_meta_method(MetaMethod::Mul, |_, a, s: f64| { | ||
| 88 | Ok(LuaPoint { x: a.x * s, y: a.y * s }) | ||
| 89 | }); | ||
| 90 | } | ||
| 91 | } | ||
| 92 | |||
| 93 | #[derive(Clone, Copy, Debug)] | ||
| 94 | pub(super) struct LuaVector4 { | ||
| 95 | pub(super) x: f64, | ||
| 96 | pub(super) y: f64, | ||
| 97 | pub(super) z: f64, | ||
| 98 | pub(super) w: f64, | ||
| 99 | } | ||
| 100 | |||
| 101 | impl UserData for LuaVector4 { | ||
| 102 | fn add_fields<F: UserDataFields<Self>>(fields: &mut F) { | ||
| 103 | fields.add_field_method_get("X", |_, this| Ok(this.x)); | ||
| 104 | fields.add_field_method_get("Y", |_, this| Ok(this.y)); | ||
| 105 | fields.add_field_method_get("Z", |_, this| Ok(this.z)); | ||
| 106 | fields.add_field_method_get("W", |_, this| Ok(this.w)); | ||
| 107 | fields.add_field_method_set("X", |_, this, v: f64| { this.x = v; Ok(()) }); | ||
| 108 | fields.add_field_method_set("Y", |_, this, v: f64| { this.y = v; Ok(()) }); | ||
| 109 | fields.add_field_method_set("Z", |_, this, v: f64| { this.z = v; Ok(()) }); | ||
| 110 | fields.add_field_method_set("W", |_, this, v: f64| { this.w = v; Ok(()) }); | ||
| 111 | } | ||
| 112 | |||
| 113 | fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) { | ||
| 114 | methods.add_meta_method(MetaMethod::Mul, |_, v, rhs: Value| match rhs { | ||
| 115 | Value::UserData(ud) => { | ||
| 116 | if let Ok(m) = ud.borrow::<LuaMatrix4>() { | ||
| 117 | Ok(m.mul_row_vec(*v)) | ||
| 118 | } else { | ||
| 119 | Err(mlua::Error::RuntimeError("unsupported Vector4 multiplication".into())) | ||
| 120 | } | ||
| 121 | } | ||
| 122 | Value::Number(s) => Ok(LuaVector4 { x: v.x * s, y: v.y * s, z: v.z * s, w: v.w * s }), | ||
| 123 | Value::Integer(s) => { | ||
| 124 | let s = s as f64; | ||
| 125 | Ok(LuaVector4 { x: v.x * s, y: v.y * s, z: v.z * s, w: v.w * s }) | ||
| 126 | } | ||
| 127 | _ => Err(mlua::Error::RuntimeError("unsupported Vector4 multiplication".into())), | ||
| 128 | }); | ||
| 129 | } | ||
| 130 | } | ||
| 131 | |||
| 132 | #[derive(Clone, Copy, Debug)] | ||
| 133 | pub(super) struct LuaImgRectI { | ||
| 134 | pub(super) left: i32, | ||
| 135 | pub(super) bottom: i32, | ||
| 136 | pub(super) right: i32, | ||
| 137 | pub(super) top: i32, | ||
| 138 | } | ||
| 139 | |||
| 140 | impl LuaImgRectI { | ||
| 141 | fn intersect(self, o: Self) -> Self { | ||
| 142 | let l = self.left.max(o.left); | ||
| 143 | let b = self.bottom.max(o.bottom); | ||
| 144 | let r = self.right.min(o.right).max(l); | ||
| 145 | let t = self.top.min(o.top).max(b); | ||
| 146 | Self { left: l, bottom: b, right: r, top: t } | ||
| 147 | } | ||
| 148 | |||
| 149 | fn union(self, o: Self) -> Self { | ||
| 150 | Self { | ||
| 151 | left: self.left.min(o.left), | ||
| 152 | bottom: self.bottom.min(o.bottom), | ||
| 153 | right: self.right.max(o.right), | ||
| 154 | top: self.top.max(o.top), | ||
| 155 | } | ||
| 156 | } | ||
| 157 | } | ||
| 158 | |||
| 159 | impl UserData for LuaImgRectI { | ||
| 160 | fn add_fields<F: UserDataFields<Self>>(fields: &mut F) { | ||
| 161 | fields.add_field_method_get("left", |_, this| Ok(this.left)); | ||
| 162 | fields.add_field_method_get("bottom", |_, this| Ok(this.bottom)); | ||
| 163 | fields.add_field_method_get("right", |_, this| Ok(this.right)); | ||
| 164 | fields.add_field_method_get("top", |_, this| Ok(this.top)); | ||
| 165 | fields.add_field_method_set("left", |_, this, v: i32| { this.left = v; Ok(()) }); | ||
| 166 | fields.add_field_method_set("bottom", |_, this, v: i32| { this.bottom = v; Ok(()) }); | ||
| 167 | fields.add_field_method_set("right", |_, this, v: i32| { this.right = v; Ok(()) }); | ||
| 168 | fields.add_field_method_set("top", |_, this, v: i32| { this.top = v; Ok(()) }); | ||
| 169 | fields.add_field_method_get("ValidWindow", |_, this| Ok(*this)); | ||
| 170 | } | ||
| 171 | |||
| 172 | fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) { | ||
| 173 | methods.add_method("Width", |_, this, ()| Ok((this.right - this.left).max(0))); | ||
| 174 | methods.add_method("Height", |_, this, ()| Ok((this.top - this.bottom).max(0))); | ||
| 175 | methods.add_method("IsEmpty", |_, this, ()| { | ||
| 176 | Ok(this.right <= this.left || this.top <= this.bottom) | ||
| 177 | }); | ||
| 178 | methods.add_method("Intersect", |_, this, o: mlua::UserDataRef<LuaImgRectI>| { | ||
| 179 | Ok(this.intersect(*o)) | ||
| 180 | }); | ||
| 181 | methods.add_method("Union", |_, this, o: mlua::UserDataRef<LuaImgRectI>| { | ||
| 182 | Ok(this.union(*o)) | ||
| 183 | }); | ||
| 184 | methods.add_method_mut("Inflate", |_, this, (dx, dy): (f64, f64)| { | ||
| 185 | let ix = dx.ceil() as i32; | ||
| 186 | let iy = dy.ceil() as i32; | ||
| 187 | this.left -= ix; | ||
| 188 | this.right += ix; | ||
| 189 | this.bottom -= iy; | ||
| 190 | this.top += iy; | ||
| 191 | Ok(()) | ||
| 192 | }); | ||
| 193 | methods.add_method_mut("Offset", |_, this, (dx, dy): (i32, i32)| { | ||
| 194 | this.left += dx; | ||
| 195 | this.right += dx; | ||
| 196 | this.bottom += dy; | ||
| 197 | this.top += dy; | ||
| 198 | Ok(()) | ||
| 199 | }); | ||
| 200 | } | ||
| 201 | } | ||
| 202 | |||
| 203 | /// Row-major 4x4 matrix matching Fusion's `Matrix4` (`v * m` row-vector convention). | ||
| 204 | #[derive(Clone, Copy, Debug)] | ||
| 205 | pub(super) struct LuaMatrix4 { | ||
| 206 | m: [f64; 16], | ||
| 207 | } | ||
| 208 | |||
| 209 | impl LuaMatrix4 { | ||
| 210 | pub(super) fn identity() -> Self { | ||
| 211 | Self { | ||
| 212 | m: [ | ||
| 213 | 1.0, 0.0, 0.0, 0.0, | ||
| 214 | 0.0, 1.0, 0.0, 0.0, | ||
| 215 | 0.0, 0.0, 1.0, 0.0, | ||
| 216 | 0.0, 0.0, 0.0, 1.0, | ||
| 217 | ], | ||
| 218 | } | ||
| 219 | } | ||
| 220 | |||
| 221 | fn mul(&self, rhs: &Self) -> Self { | ||
| 222 | let mut out = [0.0f64; 16]; | ||
| 223 | for r in 0..4 { | ||
| 224 | for c in 0..4 { | ||
| 225 | let mut sum = 0.0; | ||
| 226 | for k in 0..4 { | ||
| 227 | sum += self.m[r * 4 + k] * rhs.m[k * 4 + c]; | ||
| 228 | } | ||
| 229 | out[r * 4 + c] = sum; | ||
| 230 | } | ||
| 231 | } | ||
| 232 | Self { m: out } | ||
| 233 | } | ||
| 234 | |||
| 235 | fn mul_row_vec(&self, v: LuaVector4) -> LuaVector4 { | ||
| 236 | let m = &self.m; | ||
| 237 | LuaVector4 { | ||
| 238 | x: v.x * m[0] + v.y * m[4] + v.z * m[8] + v.w * m[12], | ||
| 239 | y: v.x * m[1] + v.y * m[5] + v.z * m[9] + v.w * m[13], | ||
| 240 | z: v.x * m[2] + v.y * m[6] + v.z * m[10] + v.w * m[14], | ||
| 241 | w: v.x * m[3] + v.y * m[7] + v.z * m[11] + v.w * m[15], | ||
| 242 | } | ||
| 243 | } | ||
| 244 | |||
| 245 | fn inverse(&self) -> Self { | ||
| 246 | // Gauss-Jordan inversion for 4x4 matrix | ||
| 247 | let mut a = [[0.0f64; 8]; 4]; | ||
| 248 | for r in 0..4 { | ||
| 249 | for c in 0..4 { | ||
| 250 | a[r][c] = self.m[r * 4 + c]; | ||
| 251 | } | ||
| 252 | a[r][4 + r] = 1.0; | ||
| 253 | } | ||
| 254 | for col in 0..4 { | ||
| 255 | let mut pivot = col; | ||
| 256 | for r in (col + 1)..4 { | ||
| 257 | if a[r][col].abs() > a[pivot][col].abs() { | ||
| 258 | pivot = r; | ||
| 259 | } | ||
| 260 | } | ||
| 261 | a.swap(col, pivot); | ||
| 262 | let div = a[col][col]; | ||
| 263 | if div.abs() < 1e-12 { | ||
| 264 | return Self::identity(); | ||
| 265 | } | ||
| 266 | for item in &mut a[col] { | ||
| 267 | *item /= div; | ||
| 268 | } | ||
| 269 | for r in 0..4 { | ||
| 270 | if r != col { | ||
| 271 | let f = a[r][col]; | ||
| 272 | for c in 0..8 { | ||
| 273 | a[r][c] -= f * a[col][c]; | ||
| 274 | } | ||
| 275 | } | ||
| 276 | } | ||
| 277 | } | ||
| 278 | let mut out = [0.0f64; 16]; | ||
| 279 | for r in 0..4 { | ||
| 280 | for c in 0..4 { | ||
| 281 | out[r * 4 + c] = a[r][4 + c]; | ||
| 282 | } | ||
| 283 | } | ||
| 284 | Self { m: out } | ||
| 285 | } | ||
| 286 | } | ||
| 287 | |||
| 288 | impl UserData for LuaMatrix4 { | ||
| 289 | fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) { | ||
| 290 | methods.add_method_mut("Identity", |_, this, ()| { | ||
| 291 | *this = Self::identity(); | ||
| 292 | Ok(()) | ||
| 293 | }); | ||
| 294 | methods.add_method_mut("Move", |_, this, (x, y, z): (f64, f64, f64)| { | ||
| 295 | let mut t = Self::identity(); | ||
| 296 | t.m[12] = x; | ||
| 297 | t.m[13] = y; | ||
| 298 | t.m[14] = z; | ||
| 299 | *this = this.mul(&t); | ||
| 300 | Ok(()) | ||
| 301 | }); | ||
| 302 | methods.add_method_mut("Scale", |_, this, (x, y, z): (f64, f64, f64)| { | ||
| 303 | let mut s = Self::identity(); | ||
| 304 | s.m[0] = x; | ||
| 305 | s.m[5] = y; | ||
| 306 | s.m[10] = z; | ||
| 307 | *this = this.mul(&s); | ||
| 308 | Ok(()) | ||
| 309 | }); | ||
| 310 | methods.add_method_mut("RotX", |_, this, deg: f64| { | ||
| 311 | let (s, c) = deg.to_radians().sin_cos(); | ||
| 312 | let mut r = Self::identity(); | ||
| 313 | r.m[5] = c; r.m[6] = s; r.m[9] = -s; r.m[10] = c; | ||
| 314 | *this = this.mul(&r); | ||
| 315 | Ok(()) | ||
| 316 | }); | ||
| 317 | methods.add_method_mut("RotY", |_, this, deg: f64| { | ||
| 318 | let (s, c) = deg.to_radians().sin_cos(); | ||
| 319 | let mut r = Self::identity(); | ||
| 320 | r.m[0] = c; r.m[2] = -s; r.m[8] = s; r.m[10] = c; | ||
| 321 | *this = this.mul(&r); | ||
| 322 | Ok(()) | ||
| 323 | }); | ||
| 324 | methods.add_method_mut("RotZ", |_, this, deg: f64| { | ||
| 325 | let (s, c) = deg.to_radians().sin_cos(); | ||
| 326 | let mut r = Self::identity(); | ||
| 327 | r.m[0] = c; r.m[1] = s; r.m[4] = -s; r.m[5] = c; | ||
| 328 | *this = this.mul(&r); | ||
| 329 | Ok(()) | ||
| 330 | }); | ||
| 331 | methods.add_method("Inverse", |_, this, ()| Ok(this.inverse())); | ||
| 332 | methods.add_meta_method(MetaMethod::Mul, |_, a, b: mlua::UserDataRef<LuaMatrix4>| { | ||
| 333 | Ok(a.mul(&b)) | ||
| 334 | }); | ||
| 335 | } | ||
| 336 | } | ||
| 337 | |||
| 338 | #[derive(Clone, Debug)] | ||
| 339 | pub(super) struct LuaGradient(pub(super) Gradient); | ||
| 340 | |||
| 341 | impl UserData for LuaGradient { | ||
| 342 | fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) { | ||
| 343 | methods.add_method("QuickEvaluate", |_, this, (pos, _space): (f64, Option<String>)| { | ||
| 344 | let c = this.0.sample(pos); | ||
| 345 | Ok(LuaPixel { r: c[0], g: c[1], b: c[2], a: c[3] }) | ||
| 346 | }); | ||
| 347 | } | ||
| 348 | } | ||
| 349 | |||
| 350 | // --------------------------------------------------------------------------- | ||
| 351 | // Image userdata (zero-copy GPU backing + lazy CPU pixel buffer) | ||
| 352 | // --------------------------------------------------------------------------- | ||
| 353 | |||
| 354 | #[derive(Clone)] | ||
| 355 | pub enum ImageBacking { | ||
| 356 | Gpu(CachedTexture), | ||
| 357 | Cpu(Vec<[f32; 4]>), | ||
| 358 | Deferred, | ||
| 359 | } | ||
| 360 | |||
| 361 | pub struct ImageInner { | ||
| 362 | pub width: u32, | ||
| 363 | pub height: u32, | ||
| 364 | pub depth: BitDepth, | ||
| 365 | pub x_scale: f64, | ||
| 366 | pub y_scale: f64, | ||
| 367 | pub is_mask: bool, | ||
| 368 | pub backing: ImageBacking, | ||
| 369 | } | ||
| 370 | |||
| 371 | impl ImageInner { | ||
| 372 | fn ensure_cpu(&mut self, lua: &Lua) -> LuaResult<&mut Vec<[f32; 4]>> { | ||
| 373 | if let ImageBacking::Gpu(ref tex) = self.backing { | ||
| 374 | let tex_clone = tex.clone(); | ||
| 375 | let pixels = { | ||
| 376 | let mut bridge = lua | ||
| 377 | .app_data_mut::<HostBridge>() | ||
| 378 | .ok_or_else(|| mlua::Error::RuntimeError("missing HostBridge".into()))?; | ||
| 379 | bridge | ||
| 380 | .readback_gpu_to_fusion_y_up(&tex_clone) | ||
| 381 | .map_err(mlua::Error::RuntimeError)? | ||
| 382 | }; | ||
| 383 | self.width = tex_clone.size[0]; | ||
| 384 | self.height = tex_clone.size[1]; | ||
| 385 | self.backing = ImageBacking::Cpu(pixels); | ||
| 386 | } else if matches!(self.backing, ImageBacking::Deferred) { | ||
| 387 | let n = (self.width as usize).saturating_mul(self.height as usize); | ||
| 388 | self.backing = ImageBacking::Cpu(vec![[0.0; 4]; n]); | ||
| 389 | } | ||
| 390 | match &mut self.backing { | ||
| 391 | ImageBacking::Cpu(v) => Ok(v), | ||
| 392 | _ => unreachable!(), | ||
| 393 | } | ||
| 394 | } | ||
| 395 | |||
| 396 | pub fn ensure_gpu(&mut self, bridge: &HostBridge, hash: u64) -> CachedTexture { | ||
| 397 | match &self.backing { | ||
| 398 | ImageBacking::Gpu(tex) => tex.clone(), | ||
| 399 | ImageBacking::Cpu(pixels) => { | ||
| 400 | let tex = bridge.upload_fusion_y_up_to_gpu( | ||
| 401 | self.width, | ||
| 402 | self.height, | ||
| 403 | self.depth, | ||
| 404 | pixels, | ||
| 405 | hash, | ||
| 406 | ); | ||
| 407 | self.backing = ImageBacking::Gpu(tex.clone()); | ||
| 408 | tex | ||
| 409 | } | ||
| 410 | ImageBacking::Deferred => { | ||
| 411 | let tex = bridge.alloc_gpu_tex([self.width, self.height], self.depth, hash); | ||
| 412 | self.backing = ImageBacking::Gpu(tex.clone()); | ||
| 413 | tex | ||
| 414 | } | ||
| 415 | } | ||
| 416 | } | ||
| 417 | } | ||
| 418 | |||
| 419 | #[derive(Clone)] | ||
| 420 | pub(super) struct LuaImage(pub(super) Rc<RefCell<ImageInner>>); | ||
| 421 | |||
| 422 | impl UserData for LuaImage { | ||
| 423 | fn add_fields<F: UserDataFields<Self>>(fields: &mut F) { | ||
| 424 | fields.add_field_method_get("Width", |_, this| Ok(this.0.borrow().width)); | ||
| 425 | fields.add_field_method_get("Height", |_, this| Ok(this.0.borrow().height)); | ||
| 426 | fields.add_field_method_get("OriginalWidth", |_, this| Ok(this.0.borrow().width)); | ||
| 427 | fields.add_field_method_get("OriginalHeight", |_, this| Ok(this.0.borrow().height)); | ||
| 428 | fields.add_field_method_get("XScale", |_, this| Ok(this.0.borrow().x_scale)); | ||
| 429 | fields.add_field_method_get("YScale", |_, this| Ok(this.0.borrow().y_scale)); | ||
| 430 | fields.add_field_method_set("XScale", |_, this, v: f64| { this.0.borrow_mut().x_scale = v; Ok(()) }); | ||
| 431 | fields.add_field_method_set("YScale", |_, this, v: f64| { this.0.borrow_mut().y_scale = v; Ok(()) }); | ||
| 432 | fields.add_field_method_get("Depth", |_, this| Ok(depth_to_fusion_imdp(this.0.borrow().depth))); | ||
| 433 | fields.add_field_method_get("DataWindow", |_, this| { | ||
| 434 | let b = this.0.borrow(); | ||
| 435 | Ok(LuaImgRectI { left: 0, bottom: 0, right: b.width as i32, top: b.height as i32 }) | ||
| 436 | }); | ||
| 437 | fields.add_field_method_get("ValidWindow", |_, this| { | ||
| 438 | let b = this.0.borrow(); | ||
| 439 | Ok(LuaImgRectI { left: 0, bottom: 0, right: b.width as i32, top: b.height as i32 }) | ||
| 440 | }); | ||
| 441 | } | ||
| 442 | |||
| 443 | fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) { | ||
| 444 | methods.add_method("IsMask", |_, this, ()| Ok(this.0.borrow().is_mask)); | ||
| 445 | methods.add_method("GetPixel", |lua, this, (x, y, mut p): (i32, i32, mlua::UserDataRefMut<LuaPixel>)| { | ||
| 446 | let mut inner = this.0.borrow_mut(); | ||
| 447 | let w = inner.width as i32; | ||
| 448 | let h = inner.height as i32; | ||
| 449 | let px = inner.ensure_cpu(lua)?; | ||
| 450 | if x >= 0 && x < w && y >= 0 && y < h { | ||
| 451 | let c = px[(y * w + x) as usize]; | ||
| 452 | p.r = c[0]; p.g = c[1]; p.b = c[2]; p.a = c[3]; | ||
| 453 | } else { | ||
| 454 | *p = LuaPixel::default(); | ||
| 455 | } | ||
| 456 | Ok(()) | ||
| 457 | }); | ||
| 458 | methods.add_method("SetPixel", |lua, this, (x, y, p): (i32, i32, mlua::UserDataRef<LuaPixel>)| { | ||
| 459 | let mut inner = this.0.borrow_mut(); | ||
| 460 | let w = inner.width as i32; | ||
| 461 | let h = inner.height as i32; | ||
| 462 | let px = inner.ensure_cpu(lua)?; | ||
| 463 | if x >= 0 && x < w && y >= 0 && y < h { | ||
| 464 | px[(y * w + x) as usize] = [p.r, p.g, p.b, p.a]; | ||
| 465 | } | ||
| 466 | Ok(()) | ||
| 467 | }); | ||
| 468 | methods.add_method("SamplePixelB", |lua, this, (fx, fy, mut p): (f64, f64, mlua::UserDataRefMut<LuaPixel>)| { | ||
| 469 | let mut inner = this.0.borrow_mut(); | ||
| 470 | let w = inner.width as i32; | ||
| 471 | let h = inner.height as i32; | ||
| 472 | let px = inner.ensure_cpu(lua)?; | ||
| 473 | let x0 = (fx.floor() as i32).clamp(0, w - 1); | ||
| 474 | let y0 = (fy.floor() as i32).clamp(0, h - 1); | ||
| 475 | let x1 = (x0 + 1).min(w - 1); | ||
| 476 | let y1 = (y0 + 1).min(h - 1); | ||
| 477 | let tx = (fx - fx.floor()) as f32; | ||
| 478 | let ty = (fy - fy.floor()) as f32; | ||
| 479 | let c00 = px[(y0 * w + x0) as usize]; | ||
| 480 | let c10 = px[(y0 * w + x1) as usize]; | ||
| 481 | let c01 = px[(y1 * w + x0) as usize]; | ||
| 482 | let c11 = px[(y1 * w + x1) as usize]; | ||
| 483 | let mix = |a: f32, b: f32, t: f32| a + (b - a) * t; | ||
| 484 | p.r = mix(mix(c00[0], c10[0], tx), mix(c01[0], c11[0], tx), ty); | ||
| 485 | p.g = mix(mix(c00[1], c10[1], tx), mix(c01[1], c11[1], tx), ty); | ||
| 486 | p.b = mix(mix(c00[2], c10[2], tx), mix(c01[2], c11[2], tx), ty); | ||
| 487 | p.a = mix(mix(c00[3], c10[3], tx), mix(c01[3], c11[3], tx), ty); | ||
| 488 | Ok(()) | ||
| 489 | }); | ||
| 490 | methods.add_method("Fill", |lua, this, p: mlua::UserDataRef<LuaPixel>| { | ||
| 491 | let mut inner = this.0.borrow_mut(); | ||
| 492 | let px = inner.ensure_cpu(lua)?; | ||
| 493 | px.fill([p.r, p.g, p.b, p.a]); | ||
| 494 | Ok(()) | ||
| 495 | }); | ||
| 496 | methods.add_method("Clear", |lua, this, ()| { | ||
| 497 | let mut inner = this.0.borrow_mut(); | ||
| 498 | let px = inner.ensure_cpu(lua)?; | ||
| 499 | px.fill([0.0; 4]); | ||
| 500 | Ok(()) | ||
| 501 | }); | ||
| 502 | methods.add_method("CopyOf", |_, this, ()| { | ||
| 503 | let b = this.0.borrow(); | ||
| 504 | Ok(LuaImage(Rc::new(RefCell::new(ImageInner { | ||
| 505 | width: b.width, | ||
| 506 | height: b.height, | ||
| 507 | depth: b.depth, | ||
| 508 | x_scale: b.x_scale, | ||
| 509 | y_scale: b.y_scale, | ||
| 510 | is_mask: b.is_mask, | ||
| 511 | backing: b.backing.clone(), | ||
| 512 | })))) | ||
| 513 | }); | ||
| 514 | methods.add_method("Gain", |lua, this, (r, g, b, a): (f64, f64, f64, f64)| { | ||
| 515 | let mut inner = this.0.borrow_mut(); | ||
| 516 | let px = inner.ensure_cpu(lua)?; | ||
| 517 | for p in px.iter_mut() { | ||
| 518 | p[0] *= r as f32; | ||
| 519 | p[1] *= g as f32; | ||
| 520 | p[2] *= b as f32; | ||
| 521 | p[3] *= a as f32; | ||
| 522 | } | ||
| 523 | Ok(()) | ||
| 524 | }); | ||
| 525 | methods.add_method("Gamma", |lua, this, (r, g, b, a): (f64, f64, f64, f64)| { | ||
| 526 | let mut inner = this.0.borrow_mut(); | ||
| 527 | let px = inner.ensure_cpu(lua)?; | ||
| 528 | let inv = |v: f64| if v.abs() > 1e-6 { (1.0 / v) as f32 } else { 1.0 }; | ||
| 529 | let (ir, ig, ib, ia) = (inv(r), inv(g), inv(b), inv(a)); | ||
| 530 | for p in px.iter_mut() { | ||
| 531 | p[0] = p[0].max(0.0).powf(ir); | ||
| 532 | p[1] = p[1].max(0.0).powf(ig); | ||
| 533 | p[2] = p[2].max(0.0).powf(ib); | ||
| 534 | p[3] = p[3].max(0.0).powf(ia); | ||
| 535 | } | ||
| 536 | Ok(()) | ||
| 537 | }); | ||
| 538 | methods.add_method("MultiProcessPixels", |lua, this, args: MultiValue| { | ||
| 539 | let vals: Vec<Value> = args.into_iter().collect(); | ||
| 540 | if vals.len() < 7 { | ||
| 541 | return Err(mlua::Error::RuntimeError("MultiProcessPixels expects at least 7 arguments".into())); | ||
| 542 | } | ||
| 543 | let init_fn = match &vals[0] { Value::Function(f) => Some(f.clone()), _ => None }; | ||
| 544 | let env_tbl = match &vals[1] { Value::Table(t) => Some(t.clone()), _ => None }; | ||
| 545 | let x0 = val_to_i32(&vals[2]).max(0); | ||
| 546 | let y0 = val_to_i32(&vals[3]).max(0); | ||
| 547 | let rw = val_to_i32(&vals[4]).max(0); | ||
| 548 | let rh = val_to_i32(&vals[5]).max(0); | ||
| 549 | let (img2_opt, func): (Option<LuaImage>, Function) = if vals.len() >= 8 { | ||
| 550 | let img2 = match &vals[6] { | ||
| 551 | Value::UserData(ud) => ud.borrow::<LuaImage>().ok().map(|r| r.clone()), | ||
| 552 | _ => None, | ||
| 553 | }; | ||
| 554 | let f = match &vals[7] { | ||
| 555 | Value::Function(f) => f.clone(), | ||
| 556 | _ => return Err(mlua::Error::RuntimeError("MultiProcessPixels missing callback".into())), | ||
| 557 | }; | ||
| 558 | (img2, f) | ||
| 559 | } else { | ||
| 560 | let f = match &vals[6] { | ||
| 561 | Value::Function(f) => f.clone(), | ||
| 562 | _ => return Err(mlua::Error::RuntimeError("MultiProcessPixels missing callback".into())), | ||
| 563 | }; | ||
| 564 | (None, f) | ||
| 565 | }; | ||
| 566 | |||
| 567 | let saved = apply_temp_globals(lua, env_tbl.as_ref())?; | ||
| 568 | if let Some(init) = init_fn { | ||
| 569 | init.call::<()>(())?; | ||
| 570 | } | ||
| 571 | |||
| 572 | let mut inner = this.0.borrow_mut(); | ||
| 573 | let w = inner.width as i32; | ||
| 574 | let h = inner.height as i32; | ||
| 575 | let px1 = inner.ensure_cpu(lua)?; | ||
| 576 | let px2_opt: Option<(i32, i32, Vec<[f32; 4]>)> = if let Some(ref i2) = img2_opt { | ||
| 577 | let mut b2 = i2.0.borrow_mut(); | ||
| 578 | let w2 = b2.width as i32; | ||
| 579 | let h2 = b2.height as i32; | ||
| 580 | let data = b2.ensure_cpu(lua)?.clone(); | ||
| 581 | Some((w2, h2, data)) | ||
| 582 | } else { | ||
| 583 | None | ||
| 584 | }; | ||
| 585 | |||
| 586 | let y_end = (y0 + rh).min(h); | ||
| 587 | let x_end = (x0 + rw).min(w); | ||
| 588 | for py in y0..y_end { | ||
| 589 | for px in x0..x_end { | ||
| 590 | let c1 = px1[(py * w + px) as usize]; | ||
| 591 | let p1_ud = lua.create_userdata(LuaPixel { r: c1[0], g: c1[1], b: c1[2], a: c1[3] })?; | ||
| 592 | let res: Value = if let Some((w2, h2, ref data2)) = px2_opt { | ||
| 593 | let c2 = if px < w2 && py < h2 { | ||
| 594 | data2[(py * w2 + px) as usize] | ||
| 595 | } else { | ||
| 596 | [0.0; 4] | ||
| 597 | }; | ||
| 598 | let p2_ud = lua.create_userdata(LuaPixel { r: c2[0], g: c2[1], b: c2[2], a: c2[3] })?; | ||
| 599 | func.call((px, py, p1_ud.clone(), p2_ud))? | ||
| 600 | } else { | ||
| 601 | func.call((px, py, p1_ud.clone()))? | ||
| 602 | }; | ||
| 603 | if let Value::UserData(out_ud) = res { | ||
| 604 | if let Ok(p) = out_ud.borrow::<LuaPixel>() { | ||
| 605 | px1[(py * w + px) as usize] = [p.r, p.g, p.b, p.a]; | ||
| 606 | } | ||
| 607 | } else if let Ok(p) = p1_ud.borrow::<LuaPixel>() { | ||
| 608 | px1[(py * w + px) as usize] = [p.r, p.g, p.b, p.a]; | ||
| 609 | } | ||
| 610 | } | ||
| 611 | } | ||
| 612 | restore_temp_globals(lua, saved)?; | ||
| 613 | Ok(()) | ||
| 614 | }); | ||
| 615 | } | ||
| 616 | } | ||
| 617 | |||
| 618 | fn depth_to_fusion_imdp(d: BitDepth) -> i32 { | ||
| 619 | match d { | ||
| 620 | BitDepth::Int8 => 5, | ||
| 621 | BitDepth::Int16 => 6, | ||
| 622 | BitDepth::Float16 => 7, | ||
| 623 | BitDepth::Float32 => 8, | ||
| 624 | } | ||
| 625 | } | ||
| 626 | |||
| 627 | pub(super) fn fusion_imdp_to_depth(v: i32) -> Option<BitDepth> { | ||
| 628 | match v { | ||
| 629 | 1 | 5 => Some(BitDepth::Int8), | ||
| 630 | 2 | 6 => Some(BitDepth::Int16), | ||
| 631 | 3 | 7 => Some(BitDepth::Float16), | ||
| 632 | 4 | 8 => Some(BitDepth::Float32), | ||
| 633 | _ => None, | ||
| 634 | } | ||
| 635 | } | ||
| 636 | |||
crates/engine/src/fuse_runtime/mod.rs created+525| ... | @@ -0,0 +1,525 @@ | ||
| 1 | //! Fusion Lua + GPU-Accelerated DCTL Fuse Runtime. | ||
| 2 | //! | ||
| 3 | //! Provides automatic `.fuse` discovery (`FuseRegistry`), a pure-Rust DCTL→WGSL compute shader | ||
| 4 | //! transpiler ([`dctl`]), a sandboxed Lua 5.4 Fusion API host ([`lua_host`], native-only), and | ||
| 5 | //! `Engine::eval_fuse_runtime(...)` fallback integration for `Fuse.*` nodes. | ||
| 6 | |||
| 7 | pub mod dctl; | ||
| 8 | mod dctl_expr; | ||
| 9 | mod dctl_parse; | ||
| 10 | #[cfg(not(target_arch = "wasm32"))] | ||
| 11 | mod lua_bridge; | ||
| 12 | #[cfg(not(target_arch = "wasm32"))] | ||
| 13 | mod lua_dvip; | ||
| 14 | #[cfg(not(target_arch = "wasm32"))] | ||
| 15 | pub mod lua_host; | ||
| 16 | #[cfg(not(target_arch = "wasm32"))] | ||
| 17 | mod lua_types; | ||
| 18 | #[cfg(test)] | ||
| 19 | mod tests; | ||
| 20 | |||
| 21 | use std::collections::{HashMap, HashSet}; | ||
| 22 | use std::collections::hash_map::DefaultHasher; | ||
| 23 | use std::hash::{Hash, Hasher}; | ||
| 24 | use std::path::{Path, PathBuf}; | ||
| 25 | use std::sync::{Arc, Mutex}; | ||
| 26 | |||
| 27 | use model::{Comp, Node, NodeId}; | ||
| 28 | |||
| 29 | use crate::cache::{CachedTexture, EvalStats}; | ||
| 30 | use crate::eval::Engine; | ||
| 31 | |||
| 32 | use self::dctl::ParamLayout; | ||
| 33 | |||
| 34 | const MAX_DCTL_PIPELINES: usize = 64; | ||
| 35 | |||
| 36 | /// Metadata captured from `FuRegisterClass(id, class_type, attrs)`. | ||
| 37 | #[derive(Clone, Debug, Default)] | ||
| 38 | pub struct FuseMeta { | ||
| 39 | pub id: String, | ||
| 40 | pub name: String, | ||
| 41 | pub class_type: String, | ||
| 42 | pub op_no_mask: bool, | ||
| 43 | pub time_variant: bool, | ||
| 44 | } | ||
| 45 | |||
| 46 | /// Registered `.fuse` script entry inside [`FuseRegistry`]. | ||
| 47 | #[derive(Clone, Debug)] | ||
| 48 | pub struct FuseEntry { | ||
| 49 | pub id: String, | ||
| 50 | pub source: String, | ||
| 51 | pub source_hash: u64, | ||
| 52 | pub path: Option<PathBuf>, | ||
| 53 | } | ||
| 54 | |||
| 55 | /// Cached compiled WGSL compute pipeline for a DCTL kernel. | ||
| 56 | pub struct CompiledDctlPipeline { | ||
| 57 | pub pipeline: wgpu::ComputePipeline, | ||
| 58 | pub bgl: wgpu::BindGroupLayout, | ||
| 59 | pub param_layout: ParamLayout, | ||
| 60 | pub input_textures: Vec<String>, | ||
| 61 | pub output_textures: Vec<String>, | ||
| 62 | } | ||
| 63 | |||
| 64 | /// Bounded cache of compiled DCTL `wgpu::ComputePipeline`s. | ||
| 65 | #[derive(Default)] | ||
| 66 | pub struct DctlPipelineCache { | ||
| 67 | entries: HashMap<(u64, wgpu::TextureFormat), (u64, Arc<CompiledDctlPipeline>)>, | ||
| 68 | tick: u64, | ||
| 69 | } | ||
| 70 | |||
| 71 | impl DctlPipelineCache { | ||
| 72 | pub fn get(&mut self, key: &(u64, wgpu::TextureFormat)) -> Option<Arc<CompiledDctlPipeline>> { | ||
| 73 | self.tick = self.tick.wrapping_add(1); | ||
| 74 | let tick = self.tick; | ||
| 75 | let entry = self.entries.get_mut(key)?; | ||
| 76 | entry.0 = tick; | ||
| 77 | Some(entry.1.clone()) | ||
| 78 | } | ||
| 79 | |||
| 80 | pub fn insert(&mut self, key: (u64, wgpu::TextureFormat), val: Arc<CompiledDctlPipeline>) { | ||
| 81 | self.tick = self.tick.wrapping_add(1); | ||
| 82 | if self.entries.len() >= MAX_DCTL_PIPELINES | ||
| 83 | && let Some(oldest) = self | ||
| 84 | .entries | ||
| 85 | .iter() | ||
| 86 | .min_by_key(|(_, (t, _))| *t) | ||
| 87 | .map(|(k, _)| *k) | ||
| 88 | { | ||
| 89 | self.entries.remove(&oldest); | ||
| 90 | } | ||
| 91 | self.entries.insert(key, (self.tick, val)); | ||
| 92 | } | ||
| 93 | |||
| 94 | pub fn clear(&mut self) { | ||
| 95 | self.entries.clear(); | ||
| 96 | } | ||
| 97 | |||
| 98 | pub fn len(&self) -> usize { | ||
| 99 | self.entries.len() | ||
| 100 | } | ||
| 101 | |||
| 102 | pub fn is_empty(&self) -> bool { | ||
| 103 | self.entries.is_empty() | ||
| 104 | } | ||
| 105 | } | ||
| 106 | |||
| 107 | /// Registry of discovered and programmatically registered `.fuse` scripts plus the shared | ||
| 108 | /// compiled DCTL GPU pipeline cache. | ||
| 109 | pub struct FuseRegistry { | ||
| 110 | entries: HashMap<String, FuseEntry>, | ||
| 111 | #[cfg(not(target_arch = "wasm32"))] | ||
| 112 | scanned_comp_dirs: HashSet<PathBuf>, | ||
| 113 | pub(crate) pipeline_cache: Arc<Mutex<DctlPipelineCache>>, | ||
| 114 | pub last_error: Option<String>, | ||
| 115 | } | ||
| 116 | |||
| 117 | impl Default for FuseRegistry { | ||
| 118 | fn default() -> Self { | ||
| 119 | Self::new() | ||
| 120 | } | ||
| 121 | } | ||
| 122 | |||
| 123 | impl FuseRegistry { | ||
| 124 | /// Creates a registry and automatically discovers `.fuse` scripts from standard Fusion / | ||
| 125 | /// Reactor directories on native platforms. | ||
| 126 | pub fn new() -> Self { | ||
| 127 | #[cfg_attr(target_arch = "wasm32", allow(unused_mut))] | ||
| 128 | let mut reg = Self::empty(); | ||
| 129 | #[cfg(not(target_arch = "wasm32"))] | ||
| 130 | reg.discover_default_dirs(); | ||
| 131 | reg | ||
| 132 | } | ||
| 133 | |||
| 134 | /// Creates an empty registry without scanning disk (useful for isolated tests). | ||
| 135 | pub fn empty() -> Self { | ||
| 136 | Self { | ||
| 137 | entries: HashMap::new(), | ||
| 138 | #[cfg(not(target_arch = "wasm32"))] | ||
| 139 | scanned_comp_dirs: HashSet::new(), | ||
| 140 | pipeline_cache: Arc::new(Mutex::new(DctlPipelineCache::default())), | ||
| 141 | last_error: None, | ||
| 142 | } | ||
| 143 | } | ||
| 144 | |||
| 145 | /// Normalizes a Fuse class name (`"Fuse.Tintensity"` or `"Tintensity"` -> `"tintensity"`). | ||
| 146 | pub fn normalize_key(kind: &str) -> String { | ||
| 147 | let stripped = kind.strip_prefix("Fuse.").unwrap_or(kind); | ||
| 148 | stripped.trim().to_ascii_lowercase() | ||
| 149 | } | ||
| 150 | |||
| 151 | /// Registers an in-memory `.fuse` source under `id` (and also under any `FuRegisterClass` ID | ||
| 152 | /// declared inside `source`). | ||
| 153 | pub fn register_source(&mut self, id: &str, source: &str) { | ||
| 154 | let source_hash = hash_source(source); | ||
| 155 | let reg_id = extract_register_class_id(source); | ||
| 156 | let canonical = if !id.is_empty() { | ||
| 157 | id.strip_prefix("Fuse.").unwrap_or(id).to_owned() | ||
| 158 | } else { | ||
| 159 | reg_id.clone().unwrap_or_default() | ||
| 160 | }; | ||
| 161 | if canonical.is_empty() { | ||
| 162 | return; | ||
| 163 | } | ||
| 164 | let entry = FuseEntry { | ||
| 165 | id: canonical.clone(), | ||
| 166 | source: source.to_owned(), | ||
| 167 | source_hash, | ||
| 168 | path: None, | ||
| 169 | }; | ||
| 170 | self.entries.insert(Self::normalize_key(&canonical), entry.clone()); | ||
| 171 | if let Some(rid) = reg_id { | ||
| 172 | self.entries.insert(Self::normalize_key(&rid), entry); | ||
| 173 | } | ||
| 174 | } | ||
| 175 | |||
| 176 | /// Registers a `.fuse` file from disk. Returns the registered class ID on success. | ||
| 177 | #[cfg(not(target_arch = "wasm32"))] | ||
| 178 | pub fn register_file(&mut self, path: &Path) -> Result<String, String> { | ||
| 179 | let source = std::fs::read_to_string(path) | ||
| 180 | .map_err(|e| format!("failed to read {}: {e}", path.display()))?; | ||
| 181 | let source_hash = hash_source(&source); | ||
| 182 | let stem = path | ||
| 183 | .file_stem() | ||
| 184 | .and_then(|s| s.to_str()) | ||
| 185 | .unwrap_or("") | ||
| 186 | .to_owned(); | ||
| 187 | let reg_id = extract_register_class_id(&source); | ||
| 188 | let canonical = reg_id.clone().unwrap_or_else(|| stem.clone()); | ||
| 189 | if canonical.is_empty() { | ||
| 190 | return Err(format!("could not determine Fuse ID for {}", path.display())); | ||
| 191 | } | ||
| 192 | let entry = FuseEntry { | ||
| 193 | id: canonical.clone(), | ||
| 194 | source, | ||
| 195 | source_hash, | ||
| 196 | path: Some(path.to_path_buf()), | ||
| 197 | }; | ||
| 198 | self.entries.insert(Self::normalize_key(&canonical), entry.clone()); | ||
| 199 | if !stem.is_empty() && Self::normalize_key(&stem) != Self::normalize_key(&canonical) { | ||
| 200 | self.entries.entry(Self::normalize_key(&stem)).or_insert(entry); | ||
| 201 | } | ||
| 202 | Ok(canonical) | ||
| 203 | } | ||
| 204 | |||
| 205 | /// Recursively scans `dir` for `*.fuse` scripts and registers them. | ||
| 206 | #[cfg(not(target_arch = "wasm32"))] | ||
| 207 | pub fn scan_dir(&mut self, dir: &Path) { | ||
| 208 | let Ok(rd) = std::fs::read_dir(dir) else { | ||
| 209 | return; | ||
| 210 | }; | ||
| 211 | for item in rd.flatten() { | ||
| 212 | let p = item.path(); | ||
| 213 | if p.is_dir() { | ||
| 214 | self.scan_dir(&p); | ||
| 215 | } else if p | ||
| 216 | .extension() | ||
| 217 | .and_then(|e| e.to_str()) | ||
| 218 | .is_some_and(|e| e.eq_ignore_ascii_case("fuse")) | ||
| 219 | { | ||
| 220 | let _ = self.register_file(&p); | ||
| 221 | } | ||
| 222 | } | ||
| 223 | } | ||
| 224 | |||
| 225 | /// Discovers Fuses from standard Reactor, system, and user Fusion Fuse directories. | ||
| 226 | #[cfg(not(target_arch = "wasm32"))] | ||
| 227 | pub fn discover_default_dirs(&mut self) { | ||
| 228 | let mut dirs: Vec<PathBuf> = Vec::new(); | ||
| 229 | #[cfg(target_os = "macos")] | ||
| 230 | { | ||
| 231 | dirs.push(PathBuf::from( | ||
| 232 | "/Library/Application Support/Blackmagic Design/Fusion/Reactor/Deploy/Fuses", | ||
| 233 | )); | ||
| 234 | dirs.push(PathBuf::from( | ||
| 235 | "/Library/Application Support/Blackmagic Design/Fusion/Fuses", | ||
| 236 | )); | ||
| 237 | if let Ok(home) = std::env::var("HOME") { | ||
| 238 | dirs.push( | ||
| 239 | PathBuf::from(&home) | ||
| 240 | .join("Library/Application Support/Blackmagic Design/Fusion/Fuses"), | ||
| 241 | ); | ||
| 242 | dirs.push( | ||
| 243 | PathBuf::from(&home) | ||
| 244 | .join("Library/Application Support/Blackmagic Design/Fusion/Reactor/Deploy/Fuses"), | ||
| 245 | ); | ||
| 246 | } | ||
| 247 | } | ||
| 248 | #[cfg(target_os = "linux")] | ||
| 249 | { | ||
| 250 | dirs.push(PathBuf::from( | ||
| 251 | "/var/BlackmagicDesign/Fusion/Reactor/Deploy/Fuses", | ||
| 252 | )); | ||
| 253 | if let Ok(home) = std::env::var("HOME") { | ||
| 254 | dirs.push(PathBuf::from(&home).join(".fusion/BlackmagicDesign/Fusion/Fuses")); | ||
| 255 | } | ||
| 256 | } | ||
| 257 | #[cfg(target_os = "windows")] | ||
| 258 | { | ||
| 259 | if let Ok(prog) = std::env::var("ALLUSERSPROFILE") { | ||
| 260 | dirs.push( | ||
| 261 | PathBuf::from(prog) | ||
| 262 | .join("Blackmagic Design/Fusion/Reactor/Deploy/Fuses"), | ||
| 263 | ); | ||
| 264 | } | ||
| 265 | if let Ok(app) = std::env::var("APPDATA") { | ||
| 266 | dirs.push(PathBuf::from(app).join("Blackmagic Design/Fusion/Fuses")); | ||
| 267 | } | ||
| 268 | } | ||
| 269 | for d in dirs { | ||
| 270 | if d.is_dir() { | ||
| 271 | self.scan_dir(&d); | ||
| 272 | } | ||
| 273 | } | ||
| 274 | } | ||
| 275 | |||
| 276 | /// Lazily scans `<comp_dir>/Fuses` once per comp directory. | ||
| 277 | pub fn scan_comp_local(&mut self, comp_path: Option<&Path>) { | ||
| 278 | #[cfg(not(target_arch = "wasm32"))] | ||
| 279 | if let Some(parent) = comp_path.and_then(Path::parent) { | ||
| 280 | let local_fuses = parent.join("Fuses"); | ||
| 281 | if self.scanned_comp_dirs.insert(local_fuses.clone()) && local_fuses.is_dir() { | ||
| 282 | self.scan_dir(&local_fuses); | ||
| 283 | } | ||
| 284 | } | ||
| 285 | #[cfg(target_arch = "wasm32")] | ||
| 286 | let _ = comp_path; | ||
| 287 | } | ||
| 288 | |||
| 289 | pub fn has_fuse(&self, kind: &str) -> bool { | ||
| 290 | self.entries.contains_key(&Self::normalize_key(kind)) | ||
| 291 | } | ||
| 292 | |||
| 293 | pub fn get(&self, kind: &str) -> Option<&FuseEntry> { | ||
| 294 | self.entries.get(&Self::normalize_key(kind)) | ||
| 295 | } | ||
| 296 | |||
| 297 | pub fn len(&self) -> usize { | ||
| 298 | self.entries.len() | ||
| 299 | } | ||
| 300 | |||
| 301 | pub fn is_empty(&self) -> bool { | ||
| 302 | self.entries.is_empty() | ||
| 303 | } | ||
| 304 | |||
| 305 | pub fn clear_pipeline_cache(&self) { | ||
| 306 | if let Ok(mut c) = self.pipeline_cache.lock() { | ||
| 307 | c.clear(); | ||
| 308 | } | ||
| 309 | } | ||
| 310 | } | ||
| 311 | |||
| 312 | fn hash_source(src: &str) -> u64 { | ||
| 313 | let mut h = DefaultHasher::new(); | ||
| 314 | src.hash(&mut h); | ||
| 315 | h.finish() | ||
| 316 | } | ||
| 317 | |||
| 318 | /// Lightweight parser extracting the class ID string from `FuRegisterClass("MyFuse", ...)`. | ||
| 319 | pub fn extract_register_class_id(source: &str) -> Option<String> { | ||
| 320 | let idx = source.find("FuRegisterClass")?; | ||
| 321 | let after = &source[idx + "FuRegisterClass".len()..]; | ||
| 322 | let open = after.find('(')?; | ||
| 323 | let args = after[open + 1..].trim_start(); | ||
| 324 | let quote = args.as_bytes().first().copied()?; | ||
| 325 | if quote != b'"' && quote != b'\'' { | ||
| 326 | return None; | ||
| 327 | } | ||
| 328 | let rest = &args[1..]; | ||
| 329 | let end = rest.find(quote as char)?; | ||
| 330 | let id = rest[..end].trim(); | ||
| 331 | (!id.is_empty()).then(|| id.to_owned()) | ||
| 332 | } | ||
| 333 | |||
| 334 | // --------------------------------------------------------------------------- | ||
| 335 | // Engine integration | ||
| 336 | // --------------------------------------------------------------------------- | ||
| 337 | |||
| 338 | impl Engine { | ||
| 339 | /// Attempts to evaluate a `Fuse.*` node using the registered Lua / GPU-DCTL Fuse runtime. | ||
| 340 | /// Returns `None` if no matching `.fuse` is registered or if execution fails (allowing the | ||
| 341 | /// caller to fall back cleanly to passthrough + `unsupported_nodes`). | ||
| 342 | #[allow(clippy::too_many_arguments)] | ||
| 343 | pub(crate) fn eval_fuse_runtime( | ||
| 344 | &mut self, | ||
| 345 | comp: &Comp, | ||
| 346 | node: &Node, | ||
| 347 | time: f64, | ||
| 348 | frame_i: i64, | ||
| 349 | comp_dims: [u32; 2], | ||
| 350 | enc: &mut wgpu::CommandEncoder, | ||
| 351 | visiting: &mut HashSet<(NodeId, i64)>, | ||
| 352 | stats: &mut EvalStats, | ||
| 353 | ) -> Option<CachedTexture> { | ||
| 354 | self.eval_fuse_by_id( | ||
| 355 | &node.kind, comp, node, time, frame_i, comp_dims, enc, visiting, stats, | ||
| 356 | ) | ||
| 357 | } | ||
| 358 | |||
| 359 | /// Evaluates `node` using the Fuse registered under `fuse_id`. | ||
| 360 | #[allow(clippy::too_many_arguments)] | ||
| 361 | pub fn eval_fuse_by_id( | ||
| 362 | &mut self, | ||
| 363 | fuse_id: &str, | ||
| 364 | comp: &Comp, | ||
| 365 | node: &Node, | ||
| 366 | time: f64, | ||
| 367 | frame_i: i64, | ||
| 368 | comp_dims: [u32; 2], | ||
| 369 | enc: &mut wgpu::CommandEncoder, | ||
| 370 | visiting: &mut HashSet<(NodeId, i64)>, | ||
| 371 | stats: &mut EvalStats, | ||
| 372 | ) -> Option<CachedTexture> { | ||
| 373 | #[cfg(target_arch = "wasm32")] | ||
| 374 | { | ||
| 375 | let _ = (fuse_id, comp, node, time, frame_i, comp_dims, enc, visiting, stats); | ||
| 376 | None | ||
| 377 | } | ||
| 378 | #[cfg(not(target_arch = "wasm32"))] | ||
| 379 | { | ||
| 380 | self.fuse_registry.scan_comp_local(comp.path.as_deref()); | ||
| 381 | let entry = self.fuse_registry.get(fuse_id)?.clone(); | ||
| 382 | |||
| 383 | // 1. Evaluate all connected flow-node image inputs | ||
| 384 | let mut img_ports: Vec<(String, NodeId)> = Vec::new(); | ||
| 385 | for (port, binding) in &node.inputs { | ||
| 386 | if let Some(src_name) = &binding.source_op | ||
| 387 | && let Some(src_id) = comp.find_node(src_name) | ||
| 388 | { | ||
| 389 | img_ports.push((port.clone(), src_id)); | ||
| 390 | } | ||
| 391 | } | ||
| 392 | img_ports.sort_by(|a, b| a.0.cmp(&b.0)); | ||
| 393 | |||
| 394 | let mut upstream_images: HashMap<String, CachedTexture> = HashMap::new(); | ||
| 395 | for (port, src_id) in &img_ports { | ||
| 396 | let tex = self.eval_node(comp, *src_id, time, enc, visiting, stats); | ||
| 397 | upstream_images.insert(port.clone(), tex); | ||
| 398 | } | ||
| 399 | let main_input = ["Input", "Image", "Background", "Source", "MainInput1", "Image1"] | ||
| 400 | .iter() | ||
| 401 | .find_map(|p| upstream_images.get(*p).cloned()) | ||
| 402 | .or_else(|| { | ||
| 403 | img_ports | ||
| 404 | .iter() | ||
| 405 | .find(|(p, _)| p != "EffectMask") | ||
| 406 | .and_then(|(p, _)| upstream_images.get(p).cloned()) | ||
| 407 | }); | ||
| 408 | |||
| 409 | // 2. Evaluate all scalar / point / text / gradient node parameters at `time` | ||
| 410 | let mut param_keys: Vec<&String> = node.inputs.keys().collect(); | ||
| 411 | param_keys.sort(); | ||
| 412 | let mut eval_params: HashMap<String, lua_host::EvalParam> = HashMap::new(); | ||
| 413 | let mut key_hasher = DefaultHasher::new(); | ||
| 414 | self.cache.gpu_salt.hash(&mut key_hasher); | ||
| 415 | self.hiq.hash(&mut key_hasher); | ||
| 416 | self.cache.node_salt(node.id).hash(&mut key_hasher); | ||
| 417 | "FuseRuntime".hash(&mut key_hasher); | ||
| 418 | entry.source_hash.hash(&mut key_hasher); | ||
| 419 | comp_dims.hash(&mut key_hasher); | ||
| 420 | (if time == 0.0 { 0.0 } else { time }).to_bits().hash(&mut key_hasher); | ||
| 421 | |||
| 422 | for (port, _) in &img_ports { | ||
| 423 | port.hash(&mut key_hasher); | ||
| 424 | if let Some(tex) = upstream_images.get(port) { | ||
| 425 | tex.content_hash.hash(&mut key_hasher); | ||
| 426 | tex.size.hash(&mut key_hasher); | ||
| 427 | } | ||
| 428 | } | ||
| 429 | |||
| 430 | for k in param_keys { | ||
| 431 | let binding = &node.inputs[k]; | ||
| 432 | if binding.source_op.as_deref().is_some_and(|s| comp.find_node(s).is_some()) { | ||
| 433 | continue; | ||
| 434 | } | ||
| 435 | k.hash(&mut key_hasher); | ||
| 436 | match &binding.value { | ||
| 437 | Some(model::ParamValue::Point(def)) => { | ||
| 438 | let pt = comp.eval_point(node, k, time, *def, &self.expr); | ||
| 439 | pt[0].to_bits().hash(&mut key_hasher); | ||
| 440 | pt[1].to_bits().hash(&mut key_hasher); | ||
| 441 | eval_params.insert(k.clone(), lua_host::EvalParam::Point(pt)); | ||
| 442 | } | ||
| 443 | Some(model::ParamValue::Text(s) | model::ParamValue::FuId(s)) => { | ||
| 444 | s.hash(&mut key_hasher); | ||
| 445 | eval_params.insert(k.clone(), lua_host::EvalParam::Text(s.clone())); | ||
| 446 | } | ||
| 447 | Some(model::ParamValue::Gradient(g)) => { | ||
| 448 | g.stops.len().hash(&mut key_hasher); | ||
| 449 | eval_params.insert(k.clone(), lua_host::EvalParam::Gradient(g.clone())); | ||
| 450 | } | ||
| 451 | _ => { | ||
| 452 | let def = binding | ||
| 453 | .value | ||
| 454 | .as_ref() | ||
| 455 | .and_then(model::ParamValue::as_f64) | ||
| 456 | .unwrap_or(0.0); | ||
| 457 | let v = comp.eval_number(node, k, time, def, &self.expr); | ||
| 458 | v.to_bits().hash(&mut key_hasher); | ||
| 459 | eval_params.insert(k.clone(), lua_host::EvalParam::Number(v)); | ||
| 460 | } | ||
| 461 | } | ||
| 462 | } | ||
| 463 | |||
| 464 | let key = key_hasher.finish(); | ||
| 465 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { | ||
| 466 | stats.cache_hits += 1; | ||
| 467 | return Some(hit); | ||
| 468 | } | ||
| 469 | |||
| 470 | // 3. Execute sandboxed Lua + GPU DCTL Fuse | ||
| 471 | let upstream_depth = main_input.as_ref().map(|t| t.depth); | ||
| 472 | let default_depth = self.node_depth(comp, node, time, upstream_depth); | ||
| 473 | let taken_enc = std::mem::replace( | ||
| 474 | enc, | ||
| 475 | self.device | ||
| 476 | .create_command_encoder(&wgpu::CommandEncoderDescriptor { | ||
| 477 | label: Some("fuse-runtime-placeholder"), | ||
| 478 | }), | ||
| 479 | ); | ||
| 480 | let bridge = lua_host::HostBridge { | ||
| 481 | device: self.device.clone(), | ||
| 482 | queue: self.queue.clone(), | ||
| 483 | encoder: Some(taken_enc), | ||
| 484 | dummy_tex: self.dummy.clone(), | ||
| 485 | pipeline_cache: self.fuse_registry.pipeline_cache.clone(), | ||
| 486 | supports_f32_filter: self.supports_f32_filter, | ||
| 487 | hiq: self.hiq, | ||
| 488 | default_depth, | ||
| 489 | comp_dims, | ||
| 490 | time, | ||
| 491 | global_range: comp.global_range, | ||
| 492 | render_range: comp.render_range, | ||
| 493 | upstream_images, | ||
| 494 | main_input, | ||
| 495 | params: eval_params, | ||
| 496 | fuse_meta: FuseMeta::default(), | ||
| 497 | output_image: None, | ||
| 498 | tool_data: HashMap::new(), | ||
| 499 | content_hash_seed: key, | ||
| 500 | }; | ||
| 501 | |||
| 502 | let (res, returned_enc) = lua_host::execute_fuse(&entry.source, bridge); | ||
| 503 | *enc = returned_enc; | ||
| 504 | |||
| 505 | match res { | ||
| 506 | Ok(Some(mut out_tex)) => { | ||
| 507 | self.fuse_registry.last_error = None; | ||
| 508 | out_tex.content_hash = key; | ||
| 509 | stats.cache_misses += 1; | ||
| 510 | stats.nodes_evaluated += 1; | ||
| 511 | self.cache.insert(key, out_tex.clone(), node.id, frame_i); | ||
| 512 | Some(out_tex) | ||
| 513 | } | ||
| 514 | Ok(None) => { | ||
| 515 | self.fuse_registry.last_error = Some("Fuse did not call OutImage:Set".to_owned()); | ||
| 516 | None | ||
| 517 | } | ||
| 518 | Err(e) => { | ||
| 519 | self.fuse_registry.last_error = Some(e); | ||
| 520 | None | ||
| 521 | } | ||
| 522 | } | ||
| 523 | } | ||
| 524 | } | ||
| 525 | } | ||
crates/engine/src/fuse_runtime/tests.rs created+634| ... | @@ -0,0 +1,634 @@ | ||
| 1 | //! Comprehensive tests for DCTL→WGSL transpilation, sandboxed Fusion Lua execution, | ||
| 2 | //! real Reactor `.fuse` execution (GPU DCTL + CPU Lua), and `Engine::evaluate` fallback. | ||
| 3 | |||
| 4 | use super::dctl::{ParamType, parse_param_block, transpile_dctl_to_wgsl}; | ||
| 5 | use super::{FuseRegistry, extract_register_class_id}; | ||
| 6 | use crate::{Engine, EvalStats}; | ||
| 7 | use model::Comp; | ||
| 8 | use std::collections::HashSet; | ||
| 9 | use std::path::Path; | ||
| 10 | |||
| 11 | #[test] | ||
| 12 | fn dctl_param_block_layout_handles_arrays_vectors_and_typedef() { | ||
| 13 | let def = r#" | ||
| 14 | typedef struct { | ||
| 15 | float color[3]; | ||
| 16 | int mode; | ||
| 17 | float2 offset; | ||
| 18 | float4 tint; | ||
| 19 | unsigned int flags; | ||
| 20 | } MyParams; | ||
| 21 | "#; | ||
| 22 | let layout = parse_param_block(def).expect("parse param block"); | ||
| 23 | assert_eq!(layout.fields.len(), 5); | ||
| 24 | assert_eq!(layout.fields[0].name, "color"); | ||
| 25 | assert_eq!(layout.fields[0].array_len, Some(3)); | ||
| 26 | assert_eq!(layout.fields[0].offset, 0); | ||
| 27 | assert_eq!(layout.fields[0].size, 12); | ||
| 28 | |||
| 29 | assert_eq!(layout.fields[1].name, "mode"); | ||
| 30 | assert_eq!(layout.fields[1].ty, ParamType::I32); | ||
| 31 | assert_eq!(layout.fields[1].offset, 12); | ||
| 32 | |||
| 33 | assert_eq!(layout.fields[2].name, "offset"); | ||
| 34 | assert_eq!(layout.fields[2].ty, ParamType::Vec2F); | ||
| 35 | assert_eq!(layout.fields[2].offset, 16); | ||
| 36 | |||
| 37 | assert_eq!(layout.fields[3].name, "tint"); | ||
| 38 | assert_eq!(layout.fields[3].ty, ParamType::Vec4F); | ||
| 39 | assert_eq!(layout.fields[3].offset, 32); | ||
| 40 | |||
| 41 | assert_eq!(layout.fields[4].name, "flags"); | ||
| 42 | assert_eq!(layout.fields[4].ty, ParamType::U32); | ||
| 43 | assert_eq!(layout.fields[4].offset, 48); | ||
| 44 | assert_eq!(layout.total_size, 64); | ||
| 45 | |||
| 46 | let mut buf = vec![0u8; layout.buffer_size()]; | ||
| 47 | layout.write_scalar(&mut buf, "color", Some(0), 0.25); | ||
| 48 | layout.write_scalar(&mut buf, "color", Some(1), 0.50); | ||
| 49 | layout.write_scalar(&mut buf, "color", Some(2), 0.75); | ||
| 50 | layout.write_scalar(&mut buf, "mode", None, 2.0); | ||
| 51 | assert!((layout.read_scalar(&buf, "color", Some(1)).unwrap() - 0.50).abs() < 1e-6); | ||
| 52 | assert_eq!(layout.read_scalar(&buf, "mode", None).unwrap(), 2.0); | ||
| 53 | } | ||
| 54 | |||
| 55 | #[test] | ||
| 56 | fn dctl_transpiler_handles_helpers_intrinsics_swizzles_casts_and_compiles_on_wgpu() { | ||
| 57 | let dctl_src = r#" | ||
| 58 | typedef struct { | ||
| 59 | float gain; | ||
| 60 | float bias[3]; | ||
| 61 | int steps; | ||
| 62 | int compOrder; | ||
| 63 | } FullParams; | ||
| 64 | |||
| 65 | __DEVICE__ float3 adjustColor(float3 c, float g, int steps) { | ||
| 66 | for (int i = 0; i < steps; i++) { | ||
| 67 | c.x = _clampf(c.x * g, 0.0f, 1.0f); | ||
| 68 | } | ||
| 69 | float s = _sinf(c.x) + _cosf(c.y) + _tanf(0.1f) + _atan2f(c.y, c.x + 0.01f); | ||
| 70 | float m = _sqrtf(_fabs(s)) + _powf(_fmaxf(c.z, 0.01f), 0.5f); | ||
| 71 | float f = _fmod(m, 1.0f) + _floorf(0.9f) + _ceilf(0.1f); | ||
| 72 | float e = _expf(0.0f) + _logf(1.0f) + _copysignf(0.1f, -1.0f); | ||
| 73 | float k = _saturatef(_mix(0.0f, 1.0f, 0.5f) + _fminf(f, e) * 0.0f); | ||
| 74 | return to_float3(c.x * k, c.y, c.z); | ||
| 75 | } | ||
| 76 | |||
| 77 | __KERNEL__ void FullKernel(__CONSTANTREF__ FullParams *params, __TEXTURE2D__ src, __TEXTURE2D_WRITE__ dst) { | ||
| 78 | DEFINE_KERNEL_ITERATORS_XY(x, y); | ||
| 79 | float4 col = _tex2DVecN(src, x, y, params->compOrder); | ||
| 80 | float4 direct = _tex2DVec4(src, (float)x, (float)y); | ||
| 81 | float3 rgb = swi3(col, x, y, z); | ||
| 82 | float3 bias = to_float3_v(params->bias); | ||
| 83 | rgb = adjustColor(rgb + bias, params->gain, params->steps); | ||
| 84 | float4 outCol = make_float4(rgb.x, rgb.y, rgb.z, direct.w); | ||
| 85 | float4 swizzled = swi4(outCol, x, y, z, w); | ||
| 86 | if (params->steps > 0) { | ||
| 87 | _tex2DVec4Write(dst, x, y, swizzled); | ||
| 88 | } else { | ||
| 89 | _tex2DVec4Write(dst, x, y, to_float4(0.0f, 0.0f, 0.0f, 1.0f)); | ||
| 90 | } | ||
| 91 | } | ||
| 92 | "#; | ||
| 93 | |||
| 94 | let transpiled = transpile_dctl_to_wgsl( | ||
| 95 | dctl_src, | ||
| 96 | "FullKernel", | ||
| 97 | Some("FullParams"), | ||
| 98 | None, | ||
| 99 | wgpu::TextureFormat::Rgba8Unorm, | ||
| 100 | ) | ||
| 101 | .expect("transpile full DCTL"); | ||
| 102 | |||
| 103 | assert!(transpiled.wgsl.contains("@compute @workgroup_size(8, 8)")); | ||
| 104 | assert!(transpiled.wgsl.contains("fn adjustColor(")); | ||
| 105 | assert!(transpiled.wgsl.contains("params.gain")); | ||
| 106 | assert!(transpiled.wgsl.contains("((col).xyz)")); | ||
| 107 | assert!(transpiled.wgsl.contains("((outCol).xyzw)")); | ||
| 108 | assert!(transpiled.wgsl.contains("f32(x)")); | ||
| 109 | assert!(transpiled.wgsl.contains("textureStore(dst")); | ||
| 110 | assert_eq!(transpiled.input_textures, vec!["src"]); | ||
| 111 | assert_eq!(transpiled.output_textures, vec!["dst"]); | ||
| 112 | |||
| 113 | #[cfg(not(target_arch = "wasm32"))] | ||
| 114 | if let Ok(eng) = Engine::new_headless() { | ||
| 115 | super::lua_host::compile_dctl_pipeline( | ||
| 116 | eng.device(), | ||
| 117 | &transpiled, | ||
| 118 | wgpu::TextureFormat::Rgba8Unorm, | ||
| 119 | ) | ||
| 120 | .expect("WGSL must compile cleanly in wgpu"); | ||
| 121 | } | ||
| 122 | } | ||
| 123 | |||
| 124 | #[cfg(not(target_arch = "wasm32"))] | ||
| 125 | #[test] | ||
| 126 | fn dctl_multi_input_fuse_executes_on_gpu_and_caches_pipeline() { | ||
| 127 | let Ok(mut eng) = Engine::new_headless() else { | ||
| 128 | return; | ||
| 129 | }; | ||
| 130 | let fuse_src = r#" | ||
| 131 | FuRegisterClass("BlendMixDctl", CT_Tool, { | ||
| 132 | REG_Name = "BlendMixDctl", | ||
| 133 | REG_OpNoMask = true, | ||
| 134 | }) | ||
| 135 | |||
| 136 | MixParams = [[ | ||
| 137 | float mixAmt; | ||
| 138 | float tint[3]; | ||
| 139 | int swapRB; | ||
| 140 | ]] | ||
| 141 | |||
| 142 | MixKernel = [[ | ||
| 143 | __DEVICE__ float3 applyTint(float3 c, float3 t) { | ||
| 144 | c.x *= t.x; | ||
| 145 | c.y *= t.y; | ||
| 146 | c.z *= t.z; | ||
| 147 | return c; | ||
| 148 | } | ||
| 149 | |||
| 150 | __KERNEL__ void MixKernel(__CONSTANTREF__ MixParams *params, __TEXTURE2D__ srcA, __TEXTURE2D__ srcB, __TEXTURE2D_WRITE__ dst) { | ||
| 151 | DEFINE_KERNEL_ITERATORS_XY(x, y); | ||
| 152 | float4 a = _tex2DVec4(srcA, x, y); | ||
| 153 | float4 b = _tex2DVec4(srcB, x, y); | ||
| 154 | float3 mixed = to_float3( | ||
| 155 | _mix(a.x, b.x, params->mixAmt), | ||
| 156 | _mix(a.y, b.y, params->mixAmt), | ||
| 157 | _mix(a.z, b.z, params->mixAmt) | ||
| 158 | ); | ||
| 159 | float3 tint = to_float3_v(params->tint); | ||
| 160 | mixed = applyTint(mixed, tint); | ||
| 161 | if (params->swapRB == 1) { | ||
| 162 | mixed = swi3(mixed, z, y, x); | ||
| 163 | } | ||
| 164 | _tex2DVec4Write(dst, x, y, to_float4(mixed.x, mixed.y, mixed.z, 1.0f)); | ||
| 165 | } | ||
| 166 | ]] | ||
| 167 | |||
| 168 | function Create() | ||
| 169 | InMix = self:AddInput("Mix", "Mix", { LINKID_DataType = "Number", INP_Default = 0.5 }) | ||
| 170 | InTintR = self:AddInput("TintR", "TintR", { LINKID_DataType = "Number", INP_Default = 1.0 }) | ||
| 171 | InTintG = self:AddInput("TintG", "TintG", { LINKID_DataType = "Number", INP_Default = 1.0 }) | ||
| 172 | InTintB = self:AddInput("TintB", "TintB", { LINKID_DataType = "Number", INP_Default = 1.0 }) | ||
| 173 | InSwap = self:AddInput("SwapRB", "SwapRB", { LINKID_DataType = "Number", INP_Default = 0 }) | ||
| 174 | InA = self:AddInput("InputA", "InputA", { LINKID_DataType = "Image", LINK_Main = 1 }) | ||
| 175 | InB = self:AddInput("InputB", "InputB", { LINKID_DataType = "Image", LINK_Main = 2 }) | ||
| 176 | OutImage = self:AddOutput("Output", "Output", { LINKID_DataType = "Image", LINK_Main = 1 }) | ||
| 177 | end | ||
| 178 | |||
| 179 | function Process(req) | ||
| 180 | local a = InA:GetValue(req) | ||
| 181 | local b = InB:GetValue(req) | ||
| 182 | local dst = Image{ IMG_Like = a, IMG_DeferAlloc = true } | ||
| 183 | local node = DVIPComputeNode(req, "MixKernel", MixKernel, "MixParams", MixParams) | ||
| 184 | local params = node:GetParamBlock(MixParams) | ||
| 185 | params.mixAmt = InMix:GetValue(req).Value | ||
| 186 | params.tint[0] = InTintR:GetValue(req).Value | ||
| 187 | params.tint[1] = InTintG:GetValue(req).Value | ||
| 188 | params.tint[2] = InTintB:GetValue(req).Value | ||
| 189 | params.swapRB = InSwap:GetValue(req).Value | ||
| 190 | node:SetParamBlock(params) | ||
| 191 | node:AddInput("srcA", a) | ||
| 192 | node:AddInput("srcB", b) | ||
| 193 | node:AddOutput("dst", dst) | ||
| 194 | local ok = node:RunSession(req) | ||
| 195 | if ok then | ||
| 196 | OutImage:Set(req, dst) | ||
| 197 | end | ||
| 198 | end | ||
| 199 | "#; | ||
| 200 | |||
| 201 | eng.fuse_registry.register_source("BlendMixDctl", fuse_src); | ||
| 202 | let comp_src = r#" | ||
| 203 | Composition { | ||
| 204 | CurrentTime = 0, | ||
| 205 | RenderRange = { 0, 1 }, | ||
| 206 | GlobalRange = { 0, 1 }, | ||
| 207 | Tools = ordered() { | ||
| 208 | BgA = Background { | ||
| 209 | Inputs = { | ||
| 210 | Width = Input { Value = 16, }, | ||
| 211 | Height = Input { Value = 16, }, | ||
| 212 | TopLeftRed = Input { Value = 0.8, }, | ||
| 213 | TopLeftGreen = Input { Value = 0.2, }, | ||
| 214 | TopLeftBlue = Input { Value = 0.0, }, | ||
| 215 | TopLeftAlpha = Input { Value = 1.0, }, | ||
| 216 | }, | ||
| 217 | }, | ||
| 218 | BgB = Background { | ||
| 219 | Inputs = { | ||
| 220 | Width = Input { Value = 16, }, | ||
| 221 | Height = Input { Value = 16, }, | ||
| 222 | TopLeftRed = Input { Value = 0.0, }, | ||
| 223 | TopLeftGreen = Input { Value = 0.6, }, | ||
| 224 | TopLeftBlue = Input { Value = 1.0, }, | ||
| 225 | TopLeftAlpha = Input { Value = 1.0, }, | ||
| 226 | }, | ||
| 227 | }, | ||
| 228 | Mix1 = Fuse.BlendMixDctl { | ||
| 229 | Inputs = { | ||
| 230 | InputA = Input { SourceOp = "BgA", Source = "Output", }, | ||
| 231 | InputB = Input { SourceOp = "BgB", Source = "Output", }, | ||
| 232 | Mix = Input { Value = 0.5, }, | ||
| 233 | TintR = Input { Value = 0.5, }, | ||
| 234 | TintG = Input { Value = 1.0, }, | ||
| 235 | TintB = Input { Value = 1.0, }, | ||
| 236 | SwapRB = Input { Value = 1, }, | ||
| 237 | }, | ||
| 238 | }, | ||
| 239 | }, | ||
| 240 | } | ||
| 241 | "#; | ||
| 242 | |||
| 243 | let comp = Comp::from_fusion_str(comp_src).expect("parse multi-input DCTL comp"); | ||
| 244 | let mix_id = comp.find_node("Mix1").unwrap(); | ||
| 245 | let (tex, stats) = eng.evaluate(&comp, mix_id, 0.0); | ||
| 246 | assert!( | ||
| 247 | stats.unsupported_nodes.is_empty(), | ||
| 248 | "Fuse.BlendMixDctl should execute natively, got unsupported: {:?}", | ||
| 249 | stats.unsupported_nodes | ||
| 250 | ); | ||
| 251 | let rgba = eng.readback_rgba(&tex).expect("readback"); | ||
| 252 | // Expected before swap: R = mix(0.8, 0.0, 0.5)*0.5 = 0.20, G = mix(0.2, 0.6, 0.5)*1.0 = 0.40, B = mix(0.0, 1.0, 0.5)*1.0 = 0.50 | ||
| 253 | // After SwapRB=1: R = 0.50 (128), G = 0.40 (102), B = 0.20 (51), A = 1.0 (255) | ||
| 254 | assert!((rgba[0] as i32 - 128).abs() <= 2, "R got {}", rgba[0]); | ||
| 255 | assert!((rgba[1] as i32 - 102).abs() <= 2, "G got {}", rgba[1]); | ||
| 256 | assert!((rgba[2] as i32 - 51).abs() <= 2, "B got {}", rgba[2]); | ||
| 257 | assert_eq!(rgba[3], 255); | ||
| 258 | assert!(eng.fuse_registry.pipeline_cache.lock().unwrap().len() >= 1); | ||
| 259 | } | ||
| 260 | |||
| 261 | #[cfg(not(target_arch = "wasm32"))] | ||
| 262 | #[test] | ||
| 263 | fn real_reactor_tintensity_fuse_executes_on_gpu() { | ||
| 264 | let tintensity_path = Path::new( | ||
| 265 | "/Library/Application Support/Blackmagic Design/Fusion/Reactor/Deploy/Fuses/Color/Tintensity.fuse", | ||
| 266 | ); | ||
| 267 | if !tintensity_path.is_file() { | ||
| 268 | return; | ||
| 269 | } | ||
| 270 | let Ok(mut eng) = Engine::new_headless() else { | ||
| 271 | return; | ||
| 272 | }; | ||
| 273 | assert!( | ||
| 274 | eng.fuse_registry.has_fuse("Fuse.Tintensity"), | ||
| 275 | "FuseRegistry::new() should auto-discover Reactor Tintensity.fuse" | ||
| 276 | ); | ||
| 277 | |||
| 278 | // Input color: (0.2, 0.4, 0.6, 1.0). | ||
| 279 | // With PreGain=1.5, Red=0.5 (color picker adds color.r * col.r), PostGain=1.0: | ||
| 280 | // After PreGain: (0.3, 0.6, 0.9) | ||
| 281 | // After Color Picker (Red=0.5, Green=0, Blue=0): R = 0.3 + 0.5*0.3 = 0.45, G = 0.6, B = 0.9 | ||
| 282 | // Vibrance=0 => EvaluateVibrance adds 0 => (0.45, 0.6, 0.9, 1.0) -> (~115, ~153, ~230, 255) | ||
| 283 | let comp_src = r#" | ||
| 284 | Composition { | ||
| 285 | CurrentTime = 0, | ||
| 286 | RenderRange = { 0, 1 }, | ||
| 287 | GlobalRange = { 0, 1 }, | ||
| 288 | Tools = ordered() { | ||
| 289 | BG = Background { | ||
| 290 | Inputs = { | ||
| 291 | Width = Input { Value = 16, }, | ||
| 292 | Height = Input { Value = 16, }, | ||
| 293 | TopLeftRed = Input { Value = 0.2, }, | ||
| 294 | TopLeftGreen = Input { Value = 0.4, }, | ||
| 295 | TopLeftBlue = Input { Value = 0.6, }, | ||
| 296 | TopLeftAlpha = Input { Value = 1.0, }, | ||
| 297 | }, | ||
| 298 | }, | ||
| 299 | TnT = Fuse.Tintensity { | ||
| 300 | Inputs = { | ||
| 301 | Image = Input { SourceOp = "BG", Source = "Output", }, | ||
| 302 | PreGain = Input { Value = 1.5, }, | ||
| 303 | Red = Input { Value = 0.5, }, | ||
| 304 | }, | ||
| 305 | }, | ||
| 306 | }, | ||
| 307 | } | ||
| 308 | "#; | ||
| 309 | let comp = Comp::from_fusion_str(comp_src).expect("parse Tintensity comp"); | ||
| 310 | let tnt_id = comp.find_node("TnT").unwrap(); | ||
| 311 | let (tex, stats) = eng.evaluate(&comp, tnt_id, 0.0); | ||
| 312 | assert!( | ||
| 313 | stats.unsupported_nodes.is_empty(), | ||
| 314 | "Fuse.Tintensity should execute natively on GPU, got unsupported: {:?}", | ||
| 315 | stats.unsupported_nodes | ||
| 316 | ); | ||
| 317 | let rgba = eng.readback_rgba(&tex).expect("readback Tintensity"); | ||
| 318 | assert!((rgba[0] as i32 - 115).abs() <= 3, "Tintensity R got {}", rgba[0]); | ||
| 319 | assert!((rgba[1] as i32 - 153).abs() <= 3, "Tintensity G got {}", rgba[1]); | ||
| 320 | assert!((rgba[2] as i32 - 230).abs() <= 3, "Tintensity B got {}", rgba[2]); | ||
| 321 | assert_eq!(rgba[3], 255); | ||
| 322 | } | ||
| 323 | |||
| 324 | #[cfg(not(target_arch = "wasm32"))] | ||
| 325 | #[test] | ||
| 326 | fn cpu_lua_fuse_image_pixel_apis_and_sandboxing_work() { | ||
| 327 | let Ok(mut eng) = Engine::new_headless() else { | ||
| 328 | return; | ||
| 329 | }; | ||
| 330 | let fuse_src = r#" | ||
| 331 | FuRegisterClass("CpuPixelDemo", CT_Tool, { | ||
| 332 | REG_Name = "CpuPixelDemo", | ||
| 333 | REG_TimeVariant = true, | ||
| 334 | }) | ||
| 335 | |||
| 336 | function Create() | ||
| 337 | InBoost = self:AddInput("Boost", "Boost", { LINKID_DataType = "Number", INP_Default = 0.25 }) | ||
| 338 | InImg = self:AddInput("Input", "Input", { LINKID_DataType = "Image", LINK_Main = 1 }) | ||
| 339 | OutImage = self:AddOutput("Output", "Output", { LINKID_DataType = "Image", LINK_Main = 1 }) | ||
| 340 | end | ||
| 341 | |||
| 342 | function Process(req) | ||
| 343 | -- Verify sandboxing: io and os are unavailable | ||
| 344 | assert(io == nil, "io must be sandboxed") | ||
| 345 | assert(os == nil, "os must be sandboxed") | ||
| 346 | |||
| 347 | -- Verify Matrix4 and ImgRectI APIs | ||
| 348 | local m = Matrix4() | ||
| 349 | m:Identity() | ||
| 350 | m:Move(2, 3, 0) | ||
| 351 | local v = Vector4(1, 2, 0, 1) * m | ||
| 352 | assert(math.abs(v.X - 3) < 1e-6 and math.abs(v.Y - 5) < 1e-6) | ||
| 353 | local r = ImgRectI(0, 0, 8, 8):Intersect(ImgRectI(2, 2, 10, 10)) | ||
| 354 | assert(r:Width() == 6 and r:Height() == 6) | ||
| 355 | |||
| 356 | local src = InImg:GetValue(req) | ||
| 357 | local boost = InBoost:GetValue(req).Value | ||
| 358 | local dst = Image({ IMG_Width = src.Width, IMG_Height = src.Height }) | ||
| 359 | dst:Fill(Pixel({ R = 0, G = 0, B = 0, A = 1 })) | ||
| 360 | local copy = dst:CopyOf() | ||
| 361 | copy:Clear() | ||
| 362 | local p = Pixel({ R = 0, G = 0, B = 0, A = 1 }) | ||
| 363 | for y = 0, src.Height - 1 do | ||
| 364 | for x = 0, src.Width - 1 do | ||
| 365 | src:GetPixel(x, y, p) | ||
| 366 | -- Flip R and B, add boost + frame-time nudge to G | ||
| 367 | local nr = p.B | ||
| 368 | local ng = math.min(1.0, p.G + boost + req.Time * 0.1) | ||
| 369 | local nb = p.R | ||
| 370 | p.R = nr | ||
| 371 | p.G = ng | ||
| 372 | p.B = nb | ||
| 373 | p.A = 1.0 | ||
| 374 | copy:SetPixel(x, y, p) | ||
| 375 | end | ||
| 376 | end | ||
| 377 | local rows_seen = 0 | ||
| 378 | self:DoMultiProcess(nil, {}, 2, function(y) rows_seen = rows_seen + 1 end) | ||
| 379 | assert(rows_seen == 2) | ||
| 380 | copy:MultiProcessPixels(nil, { delta = 0.0 }, 0, 0, src.Width, src.Height, function(x, y, px) | ||
| 381 | px.G = px.G + delta | ||
| 382 | return px | ||
| 383 | end) | ||
| 384 | OutImage:Set(req, copy) | ||
| 385 | end | ||
| 386 | "#; | ||
| 387 | eng.fuse_registry.register_source("CpuPixelDemo", fuse_src); | ||
| 388 | |||
| 389 | let comp_src = r#" | ||
| 390 | Composition { | ||
| 391 | CurrentTime = 0, | ||
| 392 | RenderRange = { 0, 2 }, | ||
| 393 | GlobalRange = { 0, 2 }, | ||
| 394 | Tools = ordered() { | ||
| 395 | BG = Background { | ||
| 396 | Inputs = { | ||
| 397 | Width = Input { Value = 16, }, | ||
| 398 | Height = Input { Value = 16, }, | ||
| 399 | TopLeftRed = Input { Value = 0.2, }, | ||
| 400 | TopLeftGreen = Input { Value = 0.3, }, | ||
| 401 | TopLeftBlue = Input { Value = 0.8, }, | ||
| 402 | TopLeftAlpha = Input { Value = 1.0, }, | ||
| 403 | }, | ||
| 404 | }, | ||
| 405 | Demo = Fuse.CpuPixelDemo { | ||
| 406 | Inputs = { | ||
| 407 | Input = Input { SourceOp = "BG", Source = "Output", }, | ||
| 408 | Boost = Input { Value = 0.2, }, | ||
| 409 | }, | ||
| 410 | }, | ||
| 411 | }, | ||
| 412 | } | ||
| 413 | "#; | ||
| 414 | let comp = Comp::from_fusion_str(comp_src).expect("parse CPU Lua comp"); | ||
| 415 | let demo_id = comp.find_node("Demo").unwrap(); | ||
| 416 | |||
| 417 | // Frame 0: R=0.8 (204), G=0.3+0.2=0.5 (128), B=0.2 (51) | ||
| 418 | let (tex0, stats0) = eng.evaluate(&comp, demo_id, 0.0); | ||
| 419 | assert!( | ||
| 420 | stats0.unsupported_nodes.is_empty(), | ||
| 421 | "CpuPixelDemo failed: {:?}", | ||
| 422 | eng.fuse_registry.last_error | ||
| 423 | ); | ||
| 424 | let px0 = eng.readback_rgba(&tex0).expect("readback frame 0"); | ||
| 425 | assert!((px0[0] as i32 - 204).abs() <= 2, "R0 got {}", px0[0]); | ||
| 426 | assert!((px0[1] as i32 - 128).abs() <= 2, "G0 got {}", px0[1]); | ||
| 427 | assert!((px0[2] as i32 - 51).abs() <= 2, "B0 got {}", px0[2]); | ||
| 428 | |||
| 429 | // Frame 2: G = 0.3 + 0.2 + 0.2 = 0.7 (179) | ||
| 430 | let (tex2, _) = eng.evaluate(&comp, demo_id, 2.0); | ||
| 431 | let px2 = eng.readback_rgba(&tex2).expect("readback frame 2"); | ||
| 432 | assert!((px2[1] as i32 - 179).abs() <= 2, "G2 got {}", px2[1]); | ||
| 433 | } | ||
| 434 | |||
| 435 | #[cfg(not(target_arch = "wasm32"))] | ||
| 436 | #[test] | ||
| 437 | fn real_reactor_hexagon_tiles_cpu_lua_matches_native_gpu_shader() { | ||
| 438 | let hex_path = Path::new( | ||
| 439 | "/Library/Application Support/Blackmagic Design/Fusion/Reactor/Deploy/Fuses/Creator/HexagonTiles.fuse", | ||
| 440 | ); | ||
| 441 | if !hex_path.is_file() { | ||
| 442 | return; | ||
| 443 | } | ||
| 444 | let Ok(mut eng) = Engine::new_headless() else { | ||
| 445 | return; | ||
| 446 | }; | ||
| 447 | assert!(eng.fuse_registry.has_fuse("HexagonTiles")); | ||
| 448 | |||
| 449 | let comp_src = r#" | ||
| 450 | Composition { | ||
| 451 | CurrentTime = 0, | ||
| 452 | RenderRange = { 0, 0 }, | ||
| 453 | GlobalRange = { 0, 0 }, | ||
| 454 | Tools = ordered() { | ||
| 455 | Hex = Fuse.HexagonTiles { | ||
| 456 | Inputs = { | ||
| 457 | Width = Input { Value = 32, }, | ||
| 458 | Height = Input { Value = 32, }, | ||
| 459 | Size = Input { Value = 4.0, }, | ||
| 460 | BorderSize = Input { Value = 2.0, }, | ||
| 461 | Red1 = Input { Value = 0.2, }, | ||
| 462 | Green1 = Input { Value = 0.4, }, | ||
| 463 | Blue1 = Input { Value = 0.8, }, | ||
| 464 | Red2 = Input { Value = 0.9, }, | ||
| 465 | Green2 = Input { Value = 0.1, }, | ||
| 466 | Blue2 = Input { Value = 0.2, }, | ||
| 467 | }, | ||
| 468 | }, | ||
| 469 | }, | ||
| 470 | } | ||
| 471 | "#; | ||
| 472 | let comp = Comp::from_fusion_str(comp_src).expect("parse HexagonTiles comp"); | ||
| 473 | let hex_id = comp.find_node("Hex").unwrap(); | ||
| 474 | |||
| 475 | // 1. Native fast-path GPU HexagonTiles output | ||
| 476 | let (gpu_tex, _) = eng.evaluate(&comp, hex_id, 0.0); | ||
| 477 | let gpu_rgba = eng.readback_rgba(&gpu_tex).expect("readback GPU HexagonTiles"); | ||
| 478 | |||
| 479 | // 2. Real HexagonTiles.fuse executed via sandboxed Lua CPU runtime | ||
| 480 | let mut enc = eng.device().create_command_encoder(&Default::default()); | ||
| 481 | let mut visiting = HashSet::new(); | ||
| 482 | let mut stats = EvalStats::default(); | ||
| 483 | let lua_tex = eng | ||
| 484 | .eval_fuse_by_id( | ||
| 485 | "HexagonTiles", | ||
| 486 | &comp, | ||
| 487 | comp.node(hex_id), | ||
| 488 | 0.0, | ||
| 489 | 0, | ||
| 490 | [32, 32], | ||
| 491 | &mut enc, | ||
| 492 | &mut visiting, | ||
| 493 | &mut stats, | ||
| 494 | ) | ||
| 495 | .expect("HexagonTiles.fuse must succeed via Lua runtime"); | ||
| 496 | eng.queue().submit(Some(enc.finish())); | ||
| 497 | let lua_rgba = eng.readback_rgba(&lua_tex).expect("readback Lua HexagonTiles"); | ||
| 498 | |||
| 499 | assert_eq!(gpu_rgba.len(), lua_rgba.len()); | ||
| 500 | // Allow rare float boundary tie on exact hexagon edge (<= 2% of pixels); interior must match within 2/255. | ||
| 501 | let mut mismatched = 0usize; | ||
| 502 | for (g, l) in gpu_rgba.chunks_exact(4).zip(lua_rgba.chunks_exact(4)) { | ||
| 503 | if (0..4).any(|c| (g[c] as i32 - l[c] as i32).abs() > 2) { | ||
| 504 | mismatched += 1; | ||
| 505 | } | ||
| 506 | } | ||
| 507 | let total = (32 * 32) as usize; | ||
| 508 | assert!( | ||
| 509 | mismatched * 100 <= total * 2, | ||
| 510 | "HexagonTiles.fuse Lua runtime diverged from GPU fast path on {mismatched}/{total} pixels" | ||
| 511 | ); | ||
| 512 | } | ||
| 513 | |||
| 514 | #[cfg(not(target_arch = "wasm32"))] | ||
| 515 | #[test] | ||
| 516 | fn engine_evaluate_fallback_runs_custom_dctl_and_gracefully_handles_broken_fuses() { | ||
| 517 | let Ok(mut eng) = Engine::new_headless() else { | ||
| 518 | return; | ||
| 519 | }; | ||
| 520 | let custom_demo = r#" | ||
| 521 | FuRegisterClass("CustomDemoDctl", CT_Tool, { REG_Name = "CustomDemoDctl" }) | ||
| 522 | DemoParams = [[ | ||
| 523 | float scaleR; | ||
| 524 | float addB; | ||
| 525 | ]] | ||
| 526 | DemoKernel = [[ | ||
| 527 | __KERNEL__ void DemoKernel(__CONSTANTREF__ DemoParams *params, __TEXTURE2D__ src, __TEXTURE2D_WRITE__ dst) { | ||
| 528 | DEFINE_KERNEL_ITERATORS_XY(x, y); | ||
| 529 | float4 c = _tex2DVec4(src, x, y); | ||
| 530 | c.x = _saturatef(c.x * params->scaleR); | ||
| 531 | c.z = _saturatef(c.z + params->addB); | ||
| 532 | _tex2DVec4Write(dst, x, y, c); | ||
| 533 | } | ||
| 534 | ]] | ||
| 535 | function Create() | ||
| 536 | InScaleR = self:AddInput("ScaleR", "ScaleR", { LINKID_DataType = "Number", INP_Default = 1.0 }) | ||
| 537 | InAddB = self:AddInput("AddB", "AddB", { LINKID_DataType = "Number", INP_Default = 0.0 }) | ||
| 538 | InImg = self:AddInput("Input", "Input", { LINKID_DataType = "Image", LINK_Main = 1 }) | ||
| 539 | OutImage = self:AddOutput("Output", "Output", { LINKID_DataType = "Image", LINK_Main = 1 }) | ||
| 540 | end | ||
| 541 | function Process(req) | ||
| 542 | local src = InImg:GetValue(req) | ||
| 543 | local dst = Image{ IMG_Like = src, IMG_DeferAlloc = true } | ||
| 544 | local node = DVIPComputeNode(req, "DemoKernel", DemoKernel, "DemoParams", DemoParams) | ||
| 545 | local p = node:GetParamBlock(DemoParams) | ||
| 546 | p.scaleR = InScaleR:GetValue(req).Value | ||
| 547 | p.addB = InAddB:GetValue(req).Value | ||
| 548 | node:SetParamBlock(p) | ||
| 549 | node:AddInput("src", src) | ||
| 550 | node:AddOutput("dst", dst) | ||
| 551 | if node:RunSession(req) then | ||
| 552 | OutImage:Set(req, dst) | ||
| 553 | end | ||
| 554 | end | ||
| 555 | "#; | ||
| 556 | let broken_dctl = r#" | ||
| 557 | FuRegisterClass("BrokenDemoDctl", CT_Tool, {}) | ||
| 558 | function Create() | ||
| 559 | InImg = self:AddInput("Input", "Input", { LINKID_DataType = "Image", LINK_Main = 1 }) | ||
| 560 | OutImage = self:AddOutput("Output", "Output", { LINKID_DataType = "Image", LINK_Main = 1 }) | ||
| 561 | end | ||
| 562 | function Process(req) | ||
| 563 | local src = InImg:GetValue(req) | ||
| 564 | local dst = Image{ IMG_Like = src, IMG_DeferAlloc = true } | ||
| 565 | local node = DVIPComputeNode(req, "Bad", "__KERNEL__ void Bad(__TEXTURE2D__ src, __TEXTURE2D_WRITE__ dst) { this is invalid wgsl syntax ???; }", "P", "") | ||
| 566 | node:AddInput("src", src) | ||
| 567 | node:AddOutput("dst", dst) | ||
| 568 | if node:RunSession(req) then | ||
| 569 | OutImage:Set(req, dst) | ||
| 570 | end | ||
| 571 | end | ||
| 572 | "#; | ||
| 573 | |||
| 574 | eng.fuse_registry.register_source("CustomDemoDctl", custom_demo); | ||
| 575 | eng.fuse_registry.register_source("BrokenDemoDctl", broken_dctl); | ||
| 576 | assert_eq!(extract_register_class_id(custom_demo).as_deref(), Some("CustomDemoDctl")); | ||
| 577 | |||
| 578 | let comp_src = r#" | ||
| 579 | Composition { | ||
| 580 | CurrentTime = 0, | ||
| 581 | RenderRange = { 0, 0 }, | ||
| 582 | GlobalRange = { 0, 0 }, | ||
| 583 | Tools = ordered() { | ||
| 584 | BG = Background { | ||
| 585 | Inputs = { | ||
| 586 | Width = Input { Value = 16, }, | ||
| 587 | Height = Input { Value = 16, }, | ||
| 588 | TopLeftRed = Input { Value = 0.25, }, | ||
| 589 | TopLeftGreen = Input { Value = 0.50, }, | ||
| 590 | TopLeftBlue = Input { Value = 0.10, }, | ||
| 591 | TopLeftAlpha = Input { Value = 1.0, }, | ||
| 592 | }, | ||
| 593 | }, | ||
| 594 | Demo = Fuse.CustomDemoDctl { | ||
| 595 | Inputs = { | ||
| 596 | Input = Input { SourceOp = "BG", Source = "Output", }, | ||
| 597 | ScaleR = Input { Value = 3.0, }, | ||
| 598 | AddB = Input { Value = 0.4, }, | ||
| 599 | }, | ||
| 600 | }, | ||
| 601 | Broken = Fuse.BrokenDemoDctl { | ||
| 602 | Inputs = { | ||
| 603 | Input = Input { SourceOp = "BG", Source = "Output", }, | ||
| 604 | }, | ||
| 605 | }, | ||
| 606 | }, | ||
| 607 | } | ||
| 608 | "#; | ||
| 609 | let comp = Comp::from_fusion_str(comp_src).expect("parse fallback comp"); | ||
| 610 | |||
| 611 | // 1. Registered CustomDemoDctl executes on GPU via fallback | ||
| 612 | let (tex, stats) = eng.evaluate(&comp, comp.find_node("Demo").unwrap(), 0.0); | ||
| 613 | assert!(stats.unsupported_nodes.is_empty()); | ||
| 614 | let px = eng.readback_rgba(&tex).expect("readback CustomDemoDctl"); | ||
| 615 | // R = 0.25*3 = 0.75 (191), G = 0.50 (128), B = 0.10+0.40 = 0.50 (128) | ||
| 616 | assert!((px[0] as i32 - 191).abs() <= 2, "R got {}", px[0]); | ||
| 617 | assert!((px[1] as i32 - 128).abs() <= 2, "G got {}", px[1]); | ||
| 618 | assert!((px[2] as i32 - 128).abs() <= 2, "B got {}", px[2]); | ||
| 619 | |||
| 620 | // 2. Broken Fuse never panics and falls back cleanly to passthrough + unsupported_nodes | ||
| 621 | let (b_tex, b_stats) = eng.evaluate(&comp, comp.find_node("Broken").unwrap(), 0.0); | ||
| 622 | assert!( | ||
| 623 | b_stats.unsupported_nodes.iter().any(|s| s == "Fuse.BrokenDemoDctl"), | ||
| 624 | "broken fuse should be recorded in unsupported_nodes: {:?}", | ||
| 625 | b_stats.unsupported_nodes | ||
| 626 | ); | ||
| 627 | let b_px = eng.readback_rgba(&b_tex).expect("readback passthrough"); | ||
| 628 | assert!((b_px[0] as i32 - 64).abs() <= 2, "passthrough R got {}", b_px[0]); | ||
| 629 | assert!((b_px[1] as i32 - 128).abs() <= 2, "passthrough G got {}", b_px[1]); | ||
| 630 | |||
| 631 | // 3. FuseRegistry::empty() starts empty | ||
| 632 | let empty_reg = FuseRegistry::empty(); | ||
| 633 | assert!(empty_reg.is_empty()); | ||
| 634 | } | ||
crates/engine/src/lib.rs+1| ... | @@ -6,6 +6,7 @@ pub mod custom_shader; | ... | @@ -6,6 +6,7 @@ pub mod custom_shader; |
| 6 | pub mod eval; | 6 | pub mod eval; |
| 7 | #[cfg(not(target_arch = "wasm32"))] | 7 | #[cfg(not(target_arch = "wasm32"))] |
| 8 | pub mod export; | 8 | pub mod export; |
| 9 | pub mod fuse_runtime; | ||
| 9 | pub mod media; | 10 | pub mod media; |
| 10 | pub mod motion_blur; | 11 | pub mod motion_blur; |
| 11 | pub mod optflow; | 12 | pub mod optflow; |