载入中...
搜索中...
未找到
ShaderResourceScriptBindings.cpp
浏览该文件的文档.
1#include <algorithm>
2#include <bit>
3#include <cmath>
4#include <cstring>
5#include <exception>
6#include <glm/mat4x4.hpp>
7#include <memory>
8#include <simplesquirrel/simplesquirrel.hpp>
9#include <stdexcept>
10#include <vector>
11#include "common/BorrowedRef.h"
13#include "filesystem/FileData.h"
16#include "graphics/Bloom.h"
17#include "graphics/Graphics.h"
18#include "graphics/Mesh.h"
19#include "graphics/Shader.h"
22#include "graphics/shaders/stylized_grass_spv.inc"
23
24// ShaderResourceScriptBindings.cpp
25namespace eve::graphics::detail {
26namespace {
27const Value& field(const Value& object, const std::string& name, Value::Type type) {
28 auto* found = object.find(name);
29 if (!found || found->type() != type) throw std::runtime_error("Missing or invalid image field: " + name);
30 return *found;
31}
32uint32_t number(const Value& object, const std::string& name) {
33 auto value = field(object, name, Value::Type::Int64).asInt();
34 if (value < 0 || uint64_t(value) > UINT32_MAX) throw std::runtime_error("Image integer out of range: " + name);
35 return uint32_t(value);
36}
37std::shared_ptr<const filesystem::FileData> readBytes(const std::string& path, size_t limit) {
38 auto* filesystem = filesystem::Filesystem::create();
39 if (!filesystem) throw std::runtime_error("Filesystem module initialization failed");
41 if (!result) throw std::runtime_error(result.status().describe());
42 return std::move(result).takeValue();
43}
44Result<void> replace(Graphics& graphics, Shader& shader, const std::string& vertex, const std::string& fragment,
45 const Value& descriptions, const std::string& constants, const std::string& instances = {}) {
46 try {
47 if (!descriptions.isArray() || descriptions.arraySize() > 16)
48 throw std::runtime_error("Expected at most 16 image resource descriptions");
49 std::vector<uint32_t> vert;
50 if (!vertex.empty()) {
51 auto stage = readShaderStageFile(vertex);
52 if (!stage) return Result<void>::failure(stage.status());
53 vert = std::move(stage).takeValue();
54 }
55 auto frag = readShaderStageFile(fragment);
56 if (!frag) return Result<void>::failure(frag.status());
57 std::vector<ShaderImageInput> images;
58 std::vector<std::shared_ptr<const filesystem::FileData>> files;
59 constexpr std::string_view keys[] = {"binding", "format", "dimension", "width", "height",
60 "layers", "mips", "path", "filter", "wrapU",
61 "wrapV", "anisotropy", "depth", "wrapW"};
62 constexpr std::pair<std::string_view, ShaderImageFormat> formats[] = {
63 {"r8-unorm", ShaderImageFormat::R8},
64 {"rg8-unorm", ShaderImageFormat::RG8},
65 {"r16-unorm", ShaderImageFormat::R16},
66 {"rgba8-unorm", ShaderImageFormat::RGBA8},
67 {"bgra8-unorm", ShaderImageFormat::BGRA8},
68 {"rgba8-srgb", ShaderImageFormat::RGBA8Srgb},
69 {"bgra8-srgb", ShaderImageFormat::BGRA8Srgb},
70 {"bc3-unorm", ShaderImageFormat::BC3},
71 {"bc1-unorm", ShaderImageFormat::BC1},
72 {"bc1-srgb", ShaderImageFormat::BC1Srgb},
73 {"bc3-srgb", ShaderImageFormat::BC3Srgb},
74 {"bc7-unorm", ShaderImageFormat::BC7},
75 {"bc7-srgb", ShaderImageFormat::BC7Srgb},
76 {"rgba16-unorm", ShaderImageFormat::RGBA16Unorm},
77 {"rgba16-float", ShaderImageFormat::RGBA16Float},
78 {"rgba32-float", ShaderImageFormat::RGBA32Float}};
79 size_t totalBytes = 0;
80 for (size_t i = 0; i < descriptions.arraySize(); ++i) {
81 const auto& row = descriptions.at(i);
82 if (!row.isObject()) throw std::runtime_error("Image description must be an object");
83 for (const auto& key : row.keys())
84 if (std::find(std::begin(keys), std::end(keys), key) == std::end(keys))
85 throw std::runtime_error("Unknown image resource field: " + key);
86 ShaderImageInput image;
87 image.binding = number(row, "binding");
88 image.width = number(row, "width");
89 image.height = number(row, "height");
90 image.layers = number(row, "layers");
91 image.mipLevels = number(row, "mips");
92 const auto format = field(row, "format", Value::Type::String).asString();
93 auto found = std::find_if(std::begin(formats), std::end(formats),
94 [&](const auto& item) { return item.first == format; });
95 if (found == std::end(formats)) throw std::runtime_error("Unknown image format: " + format);
96 image.format = found->second;
97 const auto dimension = field(row, "dimension", Value::Type::String).asString();
98 if (dimension == "2d")
100 else if (dimension == "array2d")
102 else if (dimension == "cube")
104 else if (dimension == "3d")
106 else
107 throw std::runtime_error("Unknown image view dimension: " + dimension);
108 if (row.find("depth") || image.dimension == ShaderImageDimension::Image3D)
109 image.depth = number(row, "depth");
110 auto filter = number(row, "filter");
111 auto wrapU = number(row, "wrapU"), wrapV = number(row, "wrapV");
112 if (filter > 2 || wrapU > 1 || wrapV > 1) throw std::runtime_error("Unknown resource sampler mode");
113 image.sampler.min = image.sampler.mag = filter == 0 ? FilterMode::Nearest : FilterMode::Linear;
114 image.sampler.mipmap = image.mipLevels <= 1 ? MipmapMode::Disabled
117 image.sampler.repeatU = wrapU == 0;
118 image.sampler.repeatV = wrapV == 0;
119 if (row.find("wrapW") || image.dimension == ShaderImageDimension::Image3D) {
120 const auto wrapW = number(row, "wrapW");
121 if (wrapW > 1) throw std::runtime_error("Unknown resource W sampler mode");
122 image.sampler.repeatW = wrapW == 0;
123 }
124 image.sampler.maxAnisotropy = float(number(row, "anisotropy"));
125 const auto path = field(row, "path", Value::Type::String).asString();
126 files.push_back(readBytes(path, 1024ull * 1024 * 1024));
127 const auto& bytes = *files.back();
128 totalBytes += bytes.getSize();
129 if (totalBytes > 2ull * 1024 * 1024 * 1024) throw std::runtime_error("Resource set exceeds 2 GiB");
130 image.bytes = {static_cast<const std::byte*>(bytes.getData()), size_t(bytes.getSize())};
131 image.contentOwner = files.back();
132 images.push_back(image);
133 }
134 std::shared_ptr<const filesystem::FileData> uniform;
135 std::shared_ptr<const filesystem::FileData> matrices;
136 ShaderResourceInputs inputs{images, {}};
137 if (!constants.empty()) {
138 uniform = readBytes(constants, 65536);
139 inputs.constants = {static_cast<const std::byte*>(uniform->getData()), size_t(uniform->getSize())};
140 }
141 if (!instances.empty()) {
142 matrices = readBytes(instances, 64ull * 1024 * 1024);
143 inputs.instanceMatrices = {static_cast<const std::byte*>(matrices->getData()), size_t(matrices->getSize())};
144 }
145 return graphics.replaceMeshShaderResources(shader, vert, frag.value(), inputs);
146 } catch (const std::exception& error) {
148 }
149}
150} // namespace
151void exposeShaderResourceBindings(ssq::Table& table, ssq::Class& cls) {
152 cls.addFunc("captureMesh3DSceneColor", [](Graphics* graphics) {
153 switch (graphics->captureMesh3DSceneColor()) {
154 case Graphics::Mesh3DSceneColorCaptureStatus::ExplicitOverride: return std::string("explicitOverride");
155 case Graphics::Mesh3DSceneColorCaptureStatus::Scheduled: return std::string("scheduled");
156 case Graphics::Mesh3DSceneColorCaptureStatus::Captured: return std::string("captured");
157 case Graphics::Mesh3DSceneColorCaptureStatus::HistoryReuse: return std::string("historyReuse");
158 case Graphics::Mesh3DSceneColorCaptureStatus::Unavailable: return std::string("unavailable");
159 }
160 return std::string("unavailable");
161 });
162 const auto vm = table.getHandle();
163 cls.addFunc("setBloomFilter", [vm](Graphics* graphics, const std::string& mode, float scatter, int iterations,
164 float clamp) {
165 if (!graphics || (mode != "karisTent" && mode != "gaussianScatter" && mode != "gaussianPyramid"))
169 "Expected bloom filter karisTent, gaussianScatter or gaussianPyramid", "graphics.bloom")));
171 : mode == "gaussianPyramid" ? BloomFilter::GaussianPyramid
173 scatter, iterations, clamp};
176 return script::projectResult(vm, graphics->pipelineBloom()->configureFilter(settings));
177 });
178 cls.addFunc("getBloomFilter", [](Graphics* graphics) {
179 return std::string(
180 graphics->pipelineBloom()->filterSettings().filter == BloomFilter::GaussianScatter ? "gaussianScatter"
181 : graphics->pipelineBloom()->filterSettings().filter == BloomFilter::GaussianPyramid ? "gaussianPyramid"
182 : "karisTent");
183 });
184 cls.addFunc("setSceneToneMapping", [vm](Graphics* graphics, const std::string& mode) {
185 if (!graphics || (mode != "none" && mode != "aces" && mode != "filmic"))
188 "Expected scene tone mapping none, aces or filmic",
189 "graphics.presentation")));
191 vm, graphics->setSceneToneMapping(mode == "none" ? Graphics::SceneToneMapping::None
192 : mode == "filmic" ? Graphics::SceneToneMapping::Filmic
194 });
195 cls.addFunc("setScenePhotographicVignette", [vm](Graphics* graphics, float intensity) {
196 return script::projectResult(vm, graphics->setScenePhotographicVignette(intensity));
197 });
198 cls.addFunc("getScenePhotographicVignette",
199 [](Graphics* graphics) { return graphics->getScenePhotographicVignette(); });
200 cls.addFunc("getSceneToneMapping", [](Graphics* graphics) {
201 return std::string(graphics->getSceneToneMapping() == Graphics::SceneToneMapping::None ? "none"
202 : graphics->getSceneToneMapping() == Graphics::SceneToneMapping::Filmic ? "filmic"
203 : "aces");
204 });
205 cls.addFunc("setDisplayOutputMode", [vm](Graphics* graphics, const std::string& mode) {
206 if (!graphics)
209 "graphics.presentation")));
211 if (mode == "sdr")
213 else if (mode == "auto")
215 else if (mode == "hdr10")
217 else if (mode == "scrgb")
219 else
222 "Expected display output mode sdr|auto|hdr10|scrgb",
223 "graphics.presentation")));
224 return script::projectResult(vm, graphics->setDisplayOutputMode(value));
225 });
226 cls.addFunc("getDisplayOutputMode", [](Graphics* graphics) {
227 switch (graphics->getDisplayOutputMode()) {
228 case Graphics::DisplayOutputMode::Auto: return std::string("auto");
229 case Graphics::DisplayOutputMode::Hdr10: return std::string("hdr10");
230 case Graphics::DisplayOutputMode::ScRgb: return std::string("scrgb");
232 default: return std::string("sdr");
233 }
234 });
235 cls.addFunc("setDisplayHdrCalibration", [vm](Graphics* graphics, float paperWhiteNits, float peakNits) {
236 if (!graphics)
239 "graphics.presentation")));
240 return script::projectResult(vm, graphics->setDisplayHdrCalibration(paperWhiteNits, peakNits));
241 });
242 cls.addFunc("getDisplayPaperWhiteNits", &Graphics::getDisplayPaperWhiteNits);
243 cls.addFunc("getDisplayPeakNits", &Graphics::getDisplayPeakNits);
244 cls.addFunc("getActiveDisplayColorSpace", [](Graphics* graphics) {
245 switch (graphics->getActiveDisplayColorSpace()) {
246 case Graphics::DisplayColorSpace::Hdr10: return std::string("hdr10");
247 case Graphics::DisplayColorSpace::ScRgb: return std::string("scrgb");
249 default: return std::string("sdr");
250 }
251 });
252 cls.addFunc("isDisplayHdrActive", &Graphics::isDisplayHdrActive);
253 cls.addFunc("queryDisplayOutputSupport", [vm](Graphics* graphics) {
254 if (!graphics)
256 vm,
258 DiagnosticCode::InvalidArgument, "Graphics must be present", "graphics.presentation")),
261 vm, graphics->queryDisplayOutputSupport(), [](const Graphics::DisplayOutputSupport& support) {
262 return Value::Object{{"sdr", support.sdr}, {"hdr10", support.hdr10}, {"scRgb", support.scRgb}};
263 });
264 });
265 cls.addFunc("drawMeshShaderInstances", [vm](Graphics* graphics, Mesh* mesh, Shader* shader, ssq::Array model,
266 int64_t first, int64_t count) {
267 try {
268 if (!graphics || !mesh || !shader || model.size() != 16 || first < 0 || count < 0 ||
269 uint64_t(first) > UINT32_MAX || uint64_t(count) > UINT32_MAX)
270 throw std::runtime_error("Expected mesh, shader, 16 matrix floats and nonnegative uint32 range");
271 glm::mat4 transform;
272 for (int i = 0; i < 16; ++i) transform[i / 4][i % 4] = model.get<float>(i);
273 return script::projectResult(vm, graphics->drawMeshShaderInstances(*mesh, *shader, transform, Color(1.f),
274 uint32_t(first), uint32_t(count)));
275 } catch (const std::exception& error) {
277 DiagnosticCode::InvalidArgument, error.what(), "graphics.instances")));
278 }
279 });
280 cls.addFunc("replaceMeshShaderResourcesFromFiles", [vm](Graphics* graphics, Shader* shader,
281 const std::string& vertex, const std::string& fragment,
282 ssq::Object images, const std::string& constants) {
283 if (!graphics || !shader)
286 Diagnostic::error(DiagnosticCode::InvalidArgument, "Graphics and Shader must be present")));
287 auto value = script::valueFromSquirrel(images);
289 return script::projectResult(vm, replace(*graphics, *shader, vertex, fragment, value.value(), constants));
290 });
291 cls.addFunc("replaceInstancedMeshShaderResourcesFromFiles",
292 [vm](Graphics* graphics, Shader* shader, const std::string& vertex, const std::string& fragment,
293 ssq::Object images, const std::string& constants, const std::string& instances) {
294 if (!graphics || !shader || instances.empty())
297 "Graphics, Shader and instance file must be present")));
298 auto value = script::valueFromSquirrel(images);
301 vm, replace(*graphics, *shader, vertex, fragment, value.value(), constants, instances));
302 });
303}
304} // namespace eve::graphics::detail
305
306// ShaderResources.cpp
307namespace eve::graphics {
308Result<void> Graphics::replaceMeshShaderResources(Shader&, const std::vector<uint32_t>&, const std::vector<uint32_t>&,
309 const ShaderResourceInputs&) {
311 DiagnosticCode::Unsupported, "Resource mesh programs are unavailable on this backend", "backend"));
312}
313
315 const auto invalid = [](const char* message) {
318 };
319 if (!image.width || !image.height || image.width > 32768 || image.height > 32768 || !image.layers ||
320 image.layers > 2048 || !image.depth || image.depth > 2048 || !image.mipLevels ||
321 image.mipLevels > static_cast<uint32_t>(std::bit_width(std::max({image.width, image.height, image.depth}))) ||
322 image.binding > 31)
323 return invalid("Invalid shader image dimensions, mip count or binding");
324 if (image.dimension != ShaderImageDimension::Image3D && image.depth != 1)
325 return invalid("Non-volume images require depth one");
326 switch (image.dimension) {
328 if (image.layers != 1) return invalid("A 2D image must have one layer");
329 break;
332 if (image.layers != 1 || image.width > 2048 || image.height > 2048)
333 return invalid("A volume requires one layer and at most 2048 texels per dimension");
334 break;
336 if (image.layers != 6 || image.width != image.height) return invalid("A cube image needs six square faces");
337 break;
338 default: return invalid("Unknown image dimension");
339 }
340 std::size_t block = 1, stride = 0;
341 switch (image.format) {
342 case ShaderImageFormat::R8: stride = 1; break;
344 case ShaderImageFormat::R16: stride = 2; break;
348 case ShaderImageFormat::BGRA8Srgb: stride = 4; break;
350 case ShaderImageFormat::RGBA16Float: stride = 8; break;
351 case ShaderImageFormat::RGBA32Float: stride = 16; break;
354 block = 4;
355 stride = 8;
356 break;
361 block = 4;
362 stride = 16;
363 break;
364 default: return invalid("Unknown image format");
365 }
366 if (image.dimension == ShaderImageDimension::Image3D && block != 1)
367 return invalid("Block-compressed volume images are unsupported");
368 if (!std::isfinite(image.sampler.maxAnisotropy) || image.sampler.maxAnisotropy < 1 ||
369 !std::isfinite(image.sampler.lodBias) || !std::isfinite(image.sampler.minLod) ||
370 !std::isfinite(image.sampler.maxLod) || image.sampler.minLod < 0 || image.sampler.maxLod < image.sampler.minLod)
371 return invalid("Invalid shader image sampler");
372 std::vector<ShaderImageRegion> result;
373 std::size_t offset = 0;
374 for (std::uint32_t layer = 0; layer < image.layers; ++layer) {
375 for (std::uint32_t mip = 0; mip < image.mipLevels; ++mip) {
376 const auto width = std::max(1u, image.width >> mip);
377 const auto height = std::max(1u, image.height >> mip);
378 const auto depth = std::max(1u, image.depth >> mip);
379 const uint64_t size =
380 uint64_t((width + block - 1) / block) * ((height + block - 1) / block) * stride * depth;
381 if (size > 1024ull * 1024 * 1024 || offset > 1024ull * 1024 * 1024 - size)
382 return invalid("Shader image exceeds 1 GiB upload limit");
383 result.push_back({layer, mip, width, height, offset, static_cast<size_t>(size), depth});
384 offset += static_cast<size_t>(size);
385 }
386 }
387 if (image.bytes.size() != offset) return invalid("Shader image payload size does not match its layout");
388 return Result<std::vector<ShaderImageRegion>>::success(std::move(result));
389}
391 auto bad = [](const char* message) {
394 };
395 if (bytes.size() % 64 || bytes.size() > 64ull * 1024 * 1024)
396 return bad("Instance matrices require complete 64-byte records, at most 64 MiB");
397 for (std::size_t offset = 0; offset < bytes.size(); offset += 64) {
398 float m[16];
399 std::memcpy(m, bytes.data() + offset, sizeof(m));
400 for (float value : m)
401 if (!std::isfinite(value)) return bad("Nonfinite instance transform");
402 if (m[3] != 0 || m[7] != 0 || m[11] != 0 || m[15] != 1) return bad("Instance transform must be affine");
403 const double determinant = double(m[0]) * (double(m[5]) * m[10] - double(m[9]) * m[6]) -
404 double(m[4]) * (double(m[1]) * m[10] - double(m[9]) * m[2]) +
405 double(m[8]) * (double(m[1]) * m[6] - double(m[5]) * m[2]);
406 if (!std::isfinite(determinant) || determinant == 0) return bad("Instance transform must be invertible");
407 }
408 return Result<std::uint32_t>::success(static_cast<std::uint32_t>(bytes.size() / 64));
409}
410} // namespace eve::graphics
411
412// ShaderScriptBindings.cpp
413namespace eve::graphics {
414namespace {
415Result<Value> buildGrassPoints(double radius, double extent, int seed) {
416 if (!std::isfinite(radius) || !std::isfinite(extent) || radius <= 0 || extent <= 0 || radius < extent / 1000 ||
417 seed < 0)
419 "Invalid bounded grass scatter dimensions or seed", "scatter"));
420 const double cell = radius / std::sqrt(2.0);
421 const int side = int(std::ceil(2 * extent / cell)) + 1;
422 std::vector<int> grid(size_t(side) * size_t(side), -1), active;
423 struct Point {
424 double x, z;
425 };
426 std::vector<Point> points;
427 int64_t state = int64_t(seed) % 2147483646 + 1;
428 auto next = [&]() {
429 state = state * 48271 % 2147483647;
430 return double(state) / 2147483647.0;
431 };
432 auto insert = [&](double x, double z) {
433 const auto id = int(points.size());
434 grid[size_t(int((z + extent) / cell)) * size_t(side) + size_t(int((x + extent) / cell))] = id;
435 points.push_back({x, z});
436 active.push_back(id);
437 };
438 const double firstX = (next() * 2 - 1) * extent, firstZ = (next() * 2 - 1) * extent;
439 insert(firstX, firstZ);
440 while (!active.empty()) {
441 const auto index = size_t(next() * double(active.size()));
442 const auto p = points[size_t(active[index])];
443 bool found = false;
444 for (int trial = 0; trial < 30; ++trial) {
445 const double angle = next() * 6.283185307179586, distance = radius * std::sqrt(1 + 3 * next());
446 const double x = p.x + std::cos(angle) * distance, z = p.z + std::sin(angle) * distance;
447 if (std::abs(x) > extent || std::abs(z) > extent) continue;
448 const int gx = int((x + extent) / cell), gz = int((z + extent) / cell);
449 bool valid = true;
450 for (int dz = -2; dz <= 2 && valid; ++dz)
451 for (int dx = -2; dx <= 2; ++dx) {
452 const int cx = gx + dx, cz = gz + dz;
453 if (cx < 0 || cz < 0 || cx >= side || cz >= side) continue;
454 const auto other = grid[size_t(cz) * size_t(side) + size_t(cx)];
455 if (other < 0) continue;
456 const auto q = points[size_t(other)];
457 const double ox = x - q.x, oz = z - q.z;
458 if (ox * ox + oz * oz < radius * radius) {
459 valid = false;
460 break;
461 }
462 }
463 if (valid) {
464 insert(x, z);
465 found = true;
466 break;
467 }
468 }
469 // Two coordinates per point plus the array container stay inside the
470 // common Squirrel Value projection's 100,000-element limit.
471 if (points.size() > 49999)
473 Diagnostic::error(DiagnosticCode::InvalidArgument, "Grass scatter exceeds 49,999 points", "scatter"));
474 if (!found) {
475 active[index] = active.back();
476 active.pop_back();
477 }
478 }
480 output.reserve(points.size() * 2);
481 for (const auto& p : points) {
482 output.emplace_back(p.x);
483 output.emplace_back(p.z);
484 }
485 return Result<Value>::success(Value(std::move(output)));
486}
487
488// CPU-authored vector blades rasterized once per field. No texture file or
489// shader-time shape generation is involved; RGB remains untinted white.
490std::vector<std::byte> grassMaskPixels() {
491 constexpr int size = 96, width = size * 4, height = size * 2, samples = 3;
492 struct Blade {
493 float root, height, bend, width;
494 };
495 constexpr Blade blades[2][4] = {
496 {{0.18f, 0.65f, -0.17f, 0.075f}, {0.48f, 0.96f, 0.08f, 0.10f}, {0.79f, 0.76f, 0.15f, 0.085f}, {}},
497 {{0.12f, 0.50f, -0.15f, 0.07f},
498 {0.32f, 0.84f, -0.10f, 0.065f},
499 {0.57f, 0.97f, 0.17f, 0.085f},
500 {0.83f, 0.61f, 0.16f, 0.075f}}};
501 std::vector<std::byte> pixels(width * height * 4, std::byte{255});
502 for (int variant = 0; variant < 2; ++variant)
503 for (int frame = 0; frame < 4; ++frame) {
504 constexpr float pi = 3.14159265358979323846f;
505 const float sway = std::sin(float(frame) * pi * 0.5f) * 0.075f;
506 const float flutter = std::cos(float(frame) * pi * 0.5f) * 0.12f;
507 for (int y = 0; y < size; ++y)
508 for (int x = 0; x < size; ++x) {
509 int covered = 0;
510 for (int sy = 0; sy < samples; ++sy)
511 for (int sx = 0; sx < samples; ++sx) {
512 const float u = (float(x) + (float(sx) + 0.5f) / samples) / size;
513 const float v = 1.f - (float(y) + (float(sy) + 0.5f) / samples) / size;
514 for (int leaf = 0; leaf < (variant == 0 ? 3 : 4); ++leaf) {
515 const auto& b = blades[variant][leaf];
516 const float t = v / b.height;
517 if (t < 0.f || t > 1.f) continue;
518 const float center = b.root + (b.bend + sway) * t * t;
519 const float half = b.width * std::pow(1.f - t, 0.8f) * (1.f + flutter * t);
520 if (std::abs(u - center) <= half) {
521 ++covered;
522 break;
523 }
524 }
525 }
526 const auto offset = size_t(((variant * size + y) * width + frame * size + x) * 4 + 3);
527 pixels[offset] = std::byte((covered * 255 + samples * samples / 2) / (samples * samples));
528 }
529 }
530 return pixels;
531}
532
533ResultRef<Shader> buildGrassShader(Graphics& graphics, ssq::Array records, const std::string& pass) {
534 using namespace detail::grass_spv;
535 try {
536 if (graphics.getBackendName() != "vulkan")
538 Diagnostic::error(DiagnosticCode::Unsupported, "Stylized grass requires Vulkan", "backend"));
539 if (pass != "grass" && pass != "ground")
541 Diagnostic::error(DiagnosticCode::InvalidArgument, "Expected grass or ground pass", "pass"));
542 if (records.size() == 0 || records.size() % 16 != 0 || records.size() > 64u * 1024u * 1024u / sizeof(float))
544 DiagnosticCode::InvalidArgument, "Expected nonempty affine matrix records within 64 MiB", "instances"));
545 std::vector<float> matrices;
546 matrices.reserve(records.size());
547 for (size_t i = 0; i < records.size(); ++i) {
548 const auto type = records.get<ssq::Object>(i).getType();
549 if (type != ssq::Type::FLOAT && type != ssq::Type::INTEGER)
551 Diagnostic::error(DiagnosticCode::InvalidArgument, "Matrix elements must be numbers", "instances"));
552 matrices.push_back(type == ssq::Type::INTEGER ? float(records.get<SQInteger>(i)) : records.get<float>(i));
553 }
554 ShaderResourceInputs inputs{};
555 inputs.instanceMatrices = std::as_bytes(std::span(matrices));
556 auto count = shaderInstanceMatrixCount(inputs.instanceMatrices);
557 if (!count) return ResultRef<Shader>::failure(count.status());
558 std::vector<std::byte> pixels;
559 ShaderImageInput image;
560 if (pass == "grass") {
561 pixels = grassMaskPixels();
562 image.binding = 0;
563 image.width = 384;
564 image.height = 192;
565 image.sampler.min = image.sampler.mag = FilterMode::Linear;
566 image.sampler.repeatU = image.sampler.repeatV = false;
567 image.bytes = pixels;
568 inputs.images = std::span(&image, 1);
569 }
570 const std::vector<uint32_t> vertex =
571 pass == "grass" ? std::vector<uint32_t>(std::begin(meadow_vert_spv), std::end(meadow_vert_spv))
572 : std::vector<uint32_t>(std::begin(ground_vert_spv), std::end(ground_vert_spv));
573 const std::vector<uint32_t> fragment =
574 pass == "grass" ? std::vector<uint32_t>(std::begin(meadow_frag_spv), std::end(meadow_frag_spv))
575 : std::vector<uint32_t>(std::begin(ground_frag_spv), std::end(ground_frag_spv));
576 auto* shader = graphics.newMeshShaderFromSpv({std::begin(bootstrap_vert_spv), std::end(bootstrap_vert_spv)},
577 {std::begin(bootstrap_frag_spv), std::end(bootstrap_frag_spv)});
578 if (!shader)
580 Diagnostic::error(DiagnosticCode::Failed, "Shader allocation failed", "shader"));
581 auto uploaded = graphics.replaceMeshShaderResources(*shader, vertex, fragment, inputs);
582 if (!uploaded) return ResultRef<Shader>::failure(uploaded.status());
583 return ResultRef<Shader>::success(std::ref(*shader));
584 } catch (const std::exception& error) {
586 }
587}
588
589Result<std::vector<uint32_t>> shaderWords(ssq::Array array) {
590 std::vector<uint32_t> words;
591 words.reserve(array.size());
592 for (size_t i = 0; i < array.size(); ++i) {
593 if (array.get<ssq::Object>(i).getType() != ssq::Type::INTEGER)
594 return Result<std::vector<uint32_t>>::failure(
595 Diagnostic::error(DiagnosticCode::InvalidArgument, "SPIR-V words must be integers"));
596 const auto word = array.get<SQInteger>(i);
597 if (word < 0 || static_cast<uint64_t>(word) > UINT32_MAX)
598 return Result<std::vector<uint32_t>>::failure(
599 Diagnostic::error(DiagnosticCode::InvalidArgument, "SPIR-V words must be unsigned 32-bit integers"));
600 words.push_back(static_cast<uint32_t>(word));
601 }
602 return Result<std::vector<uint32_t>>::success(std::move(words));
603}
604
605} // namespace
606namespace detail {
608 try {
609 auto* fs = filesystem::Filesystem::create();
610 std::unique_ptr<filesystem::FileData> bytes(fs->read(path));
611 if (!bytes || bytes->getSize() < 20 || bytes->getSize() % 4 != 0)
613 DiagnosticCode::ParseError, "SPIR-V must contain a complete word-aligned header", path));
614 std::vector<std::uint32_t> words(bytes->getSize() / 4);
615 std::memcpy(words.data(), bytes->getData(), bytes->getSize());
616 if (words[0] != 0x07230203)
617 return Result<std::vector<std::uint32_t>>::failure(
618 Diagnostic::error(DiagnosticCode::ParseError, "SPIR-V magic mismatch", path));
619 return Result<std::vector<std::uint32_t>>::success(std::move(words));
620 } catch (const std::exception& error) {
621 return Result<std::vector<std::uint32_t>>::failure(
623 }
624}
625
626} // namespace detail
627namespace {
628// The existing Graphics factory owns the shader; this adapter only borrows it.
629ResultRef<Shader> loadMeshShader(Graphics& graphics, const std::string& vertex, const std::string& fragment) {
630 if (graphics.getBackendName() != "vulkan")
632 DiagnosticCode::Unsupported, "SPIR-V mesh shaders require the Vulkan backend", "backend"));
633 if (fragment.empty())
635 Diagnostic::error(DiagnosticCode::InvalidArgument, "fragment path must not be empty", "fragment"));
636 std::vector<std::uint32_t> vert;
637 if (!vertex.empty()) {
638 auto decoded = detail::readShaderStageFile(vertex);
639 if (!decoded) return ResultRef<Shader>::failure(decoded.status());
640 vert = std::move(decoded).takeValue();
641 }
642 auto frag = detail::readShaderStageFile(fragment);
643 if (!frag) return ResultRef<Shader>::failure(frag.status());
644 try {
645 auto* shader = graphics.newMeshShaderFromSpv(vert, frag.value());
646 if (!shader)
648 Diagnostic::error(DiagnosticCode::Failed, "Mesh shader allocation failed", "shader"));
649 return ResultRef<Shader>::success(std::ref(*shader));
650 } catch (const std::exception& error) {
652 }
653}
654} // namespace
655
656void exposeShaderScriptBindings(ssq::Table& table, ssq::Class& cls) {
658 const auto vm = table.getHandle();
659 cls.addFunc("buildStylizedGrassPoints", [vm](Graphics*, float radius, float extent, int seed) {
660 return eve::script::projectResult(vm, buildGrassPoints(radius, extent, seed),
661 [](const Value& value) { return value; });
662 });
663 cls.addFunc("buildStylizedGrassShader", [vm](Graphics* self, ssq::Array instances, const std::string& pass) {
664 if (!self)
666 DiagnosticCode::InvalidArgument, "Graphics must be present")));
667 auto result = buildGrassShader(*self, instances, pass);
668 if (!result) return eve::script::projectStatusResult(vm, result.status());
669 auto projected = eve::script::projectStatusResult(vm, result.status());
670 projected.set("value", &result.value().get());
672 projected.set("ownership", std::string("borrowed-from-graphics"));
673 return projected;
674 });
675 cls.addFunc(
676 "replaceShaderFromSpv", [vm](Graphics* graphics, Shader* shader, ssq::Array vertex, ssq::Array fragment) {
677 if (!graphics || !shader)
680 "graphics and shader must not be null")));
681 auto vert = shaderWords(vertex);
682 if (!vert.ok()) return eve::script::projectResult(vm, Result<void>::failure(vert.status()));
683 auto frag = shaderWords(fragment);
684 if (!frag.ok()) return eve::script::projectResult(vm, Result<void>::failure(frag.status()));
686 });
687 cls.addFunc("replaceShaderFromGlsl",
688 [vm](Graphics* self, Shader* shader, const std::string& vertex, const std::string& fragment) {
689 if (!self || !shader)
692 DiagnosticCode::InvalidArgument, "graphics and shader must not be null", "shader",
693 {}, "graphics.shader_reload.binding")));
694 return eve::script::projectResult(vm, self->replaceShaderFromGlsl(*shader, vertex, fragment));
695 });
696 cls.addFunc("replaceShaderFromWgsl",
697 [vm](Graphics* self, Shader* shader, const std::string& vertex, const std::string& fragment) {
698 if (!self || !shader)
701 DiagnosticCode::InvalidArgument, "graphics and shader must not be null", "shader",
702 {}, "graphics.shader_reload.binding")));
703 return eve::script::projectResult(vm, self->replaceShaderFromWgsl(*shader, vertex, fragment));
704 });
705
706
707 cls.addFunc("configureMeshShaderSurface",
708 [vm](Graphics* self, Shader* shader, const std::string& name, bool depthWrite, bool doubleSided) {
710 if (name == "alpha")
712 else if (name == "premultiplied")
714 else if (name == "additive")
716 else if (name == "multiply")
718 else if (name != "opaque")
721 "Unknown mesh blend mode", "blend")));
722 if (!self || !shader)
725 "Expected graphics and shader", "shader")));
727 vm, self->configureMeshShaderSurface(*shader, blend, depthWrite, doubleSided));
728 });
729 cls.addFunc("configureMeshShaderRaster", [vm](Graphics* self, Shader* shader, const std::string& compare,
730 float constantBias, float slopeBias, int colorMask) {
732 if (compare == "less")
733 state.depthCompare = MeshDepthCompare::Less;
734 else if (compare == "lessEqual")
735 state.depthCompare = MeshDepthCompare::LessEqual;
736 else if (compare == "always")
737 state.depthCompare = MeshDepthCompare::Always;
738 else
739 colorMask = -1;
740 if (!self || !shader || colorMask < 0 || colorMask > 15)
743 "Invalid shader, depth comparison or RGBA mask",
744 "shader.raster")));
745 state.depthBiasConstant = constantBias;
746 state.depthBiasSlope = slopeBias;
747 state.colorWriteMask = static_cast<std::uint8_t>(colorMask);
749 });
750 cls.addFunc("loadMeshShaderSpv", [vm](Graphics* self, const std::string& vertex, const std::string& fragment) {
751 auto result = loadMeshShader(*self, vertex, fragment);
752 if (!result) return eve::script::projectStatusResult(vm, result.status());
753 auto projected = eve::script::projectStatusResult(vm, result.status());
754 projected.set("value", &result.value().get());
756 projected.set("ownership", std::string("borrowed-from-graphics"));
757 return projected;
758 });
759}
760} // namespace eve::graphics
double z
double y
double m[16]
double x
bool & active
int root
Definition AnimSmr.cpp:119
std::string output
Vocabulary aliases for nullable and checked borrowed references.
std::string variant
float cx
Definition CardTypes.cpp:36
glm::vec4 p[6]
HSQUIRRELVM vm
Definition ECS.cpp:38
HSQOBJECT cls
Definition ECS.cpp:39
SQObjectPtr key
Definition ECS.cpp:155
std::string name
Definition ECS.cpp:154
std::string message
vk::ShaderModule vert
vk::ShaderModule frag
vk::UniqueImage image
float u
Definition Grass.cpp:233
int inputs
Definition GridGraph.cpp:23
std::array< double, 10 > q
float v
std::int32_t first
float blend
std::uint32_t height
std::uint32_t width
size_t offset
std::string id
Poco::JSON::Object::Ptr result
std::uint64_t bytes
bool valid
MeleePoint3 b
Definition MeleeHit.cpp:41
double radius
Definition MeleeHit.cpp:42
float distance
bool doubleSided
OceanWakeSettings settings
OceanMeshSettings mesh
ssq::Object frame
glm::dvec2 center
glm::dvec3 dx
glm::dvec3 dz
std::string error
Definition Package.cpp:174
TileLayer * layer
std::string path
Definition PlayHost.cpp:111
std::shared_ptr< const std::vector< glm::vec2 > > points
Object::Ptr value
int detail
float t
uint8_t * pixels
Shader * shader
glm::mat4 model
double number
bool found
std::string filter
Graphics * graphics
size_t begin
size_t end
int count
The single Squirrel projection for common Result, Status and Value.
Cell cell
int limit
Definition TreeMesh.cpp:166
int iterations
Definition TreeMesh.cpp:448
uint32_t seed
Definition TreeMesh.cpp:276
float size
Definition TreeMesh.cpp:158
std::uint32_t depth
uint32_t index
double ox
int covered
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
Move-only operation result carrying either a value or Status.
Definition Result.h:176
static Result success(T value)
Construct a successful result owning value.
Definition Result.h:185
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
The canonical owning dynamic value used by data-facing protocols.
Definition Value.h:31
std::map< std::string, Value > Object
Definition Value.h:34
Type
Runtime kind of the owned value.
Definition Value.h:38
std::vector< Value > Array
Definition Value.h:33
virtual std::string getBackendName() const =0
Renderer backend id used by sibling modules (e.g. Gpgpu).
virtual Shader * newMeshShaderFromSpv(const std::vector< uint32_t > &vertSpv, const std::vector< uint32_t > &fragSpv)=0
Create a Mesh3D custom shader (MeshVertex + Frame UBO + albedo). Empty vert → default mesh3d....
virtual Result< void > replaceShaderFromGlsl(Shader &shader, const std::string &vertGlsl, const std::string &fragGlsl)=0
Compile GLSL and transactionally replace an existing shader.
virtual float getDisplayPaperWhiteNits() const
Paper-white luminance in nits for HDR present encoding.
virtual float getDisplayPeakNits() const
Peak luminance in nits for HDR present encoding.
virtual bool isDisplayHdrActive() const
True when the live swapchain is scRGB or HDR10.
DisplayOutputMode
Requested swapchain present preference.
Definition Graphics.h:1388
virtual Result< void > replaceMeshShaderResources(Shader &shader, const std::vector< uint32_t > &vertSpv, const std::vector< uint32_t > &fragSpv, const ShaderResourceInputs &resources)
Replace a mesh program and its immutable set-1 resources atomically.
virtual eve::Result< void > configureMeshShaderRaster(Shader &shader, const MeshShaderRasterState &state)
Transactionally configure an owned ordinary mesh shader's raster state.
Definition Graphics.h:1915
virtual eve::Result< void > configureMeshShaderSurface(Shader &, BlendMode, bool, bool)
Prepare a custom mesh shader's blend, depth and culling state.
Definition Graphics.h:1898
virtual Result< void > replaceShaderFromSpv(Shader &shader, const std::vector< uint32_t > &vertSpv, const std::vector< uint32_t > &fragSpv)=0
Transactionally replace an existing shader with SPIR-V stages.
virtual Result< void > replaceShaderFromWgsl(Shader &shader, const std::string &vertWgsl, const std::string &fragWgsl)=0
Transactionally replace an existing shader with WGSL stages.
GPU mesh handle (+ optional CPU morph targets).
Definition Mesh.h:26
Custom GPU program.
Definition Shader.h:41
int asInt(int fallback=0) const
As int.
Definition Json.cpp:393
std::string asString(const std::string &fallback={}) const
As string.
Definition Json.cpp:412
std::string word
const Value * field(const Value &value, const char *key)
Borrow an optional object field.
std::variant< std::monostate, std::int64_t, double, std::string, bool > Value
Definition Database.h:27
Result< std::shared_ptr< const FileData > > readPreparedFile(const std::string &path, size_t limit)
Join a queued read or synchronously read an immutable file snapshot.
void keys(const Value &value, std::initializer_list< const char * > names)
void exposeShaderResourceBindings(ssq::Table &table, ssq::Class &cls)
Expose shader resource bindings.
Result< std::vector< std::uint32_t > > readShaderStageFile(const std::string &path)
Reads shader stage file.
卡牌游戏 UI 工具模块:工厂 + 脚本绑定入口。 功能参考 ycarowr/UiCard:扇形手牌布局、抽牌/洗牌、悬浮放大、拖拽到落牌区、 敌方手牌(背面/偷看)、费用不足置灰,以及可实时调节的布局...
Definition Animation.h:25
eve::Color Color
RGBA color used by every graphics draw call. Lives inside eve::graphics so including a graphics heade...
Definition Color.h:13
EVENGINE_API_BACKENDS Result< std::vector< ShaderImageRegion > > shaderImageRegions(const ShaderImageInput &image)
Validate layout, dimensions, sampler compatibility and exact payload size.
EVENGINE_API_BACKENDS Result< void > validateBloomFilterSettings(const BloomFilterSettings &settings)
Validate enum, finite scatter [0,1], iterations [1,16], and finite clamp (0,65504].
void exposeShaderScriptBindings(ssq::Table &table, ssq::Class &cls)
Register shader loading and binary replacement on the VM owner thread. Borrows both tables for this c...
EVENGINE_API_BACKENDS Result< std::uint32_t > shaderInstanceMatrixCount(std::span< const std::byte > bytes)
Validate packed instance records without GPU access; returns the record count.
constexpr HexDirection next(HexDirection d) noexcept
The next direction clockwise (NW wraps to NE).
Definition HexMetrics.h:76
void markResultHasValue(ssq::Table &result)
Declare that a projected table received a payload the caller attached itself.
ssq::Table projectStatusResult(HSQUIRRELVM vm, const Status &status)
Project a checked native status that carries no payload.
ssq::Table projectResult(HSQUIRRELVM vm, Result< void > &&result)
Consume and project a void native Result using the common schema.
Result< Value > valueFromSquirrel(HSQUIRRELVM vm, SQInteger index, const SquirrelValueOptions &options)
Convert one Squirrel value into the canonical owning Value tree.
WidgetDesc grid(int columns, std::vector< WidgetDesc > children, std::string id)
Fixed-column grid; children are placed in source order.
Definition Widget.cpp:878
WidgetDesc row(std::vector< WidgetDesc > children, std::string id)
Horizontal elastic layout row.
Definition Widget.cpp:870
BlendMode
Render-neutral 2D blend mode shared by graphics-facing modules.
Definition RenderTypes.h:11
Value-owned Gaussian bloom settings, independent of camera intensity and threshold.
Definition Bloom.h:21
Surface present formats the current device/window can offer.
Definition Graphics.h:1392
Value snapshot of custom mesh rasterization state, independent of blending/culling.
Synchronous borrowed input for one immutable shader image. @ownership The caller owns bytes; upload c...
Inputs for descriptor set 1 of a resource mesh program.