载入中...
搜索中...
未找到
SceneVisibility.cpp
浏览该文件的文档.
2#include <algorithm>
3#include <cmath>
4#include <glm/gtc/matrix_transform.hpp>
5#include <map>
6#include <optional>
7#include <set>
8#include <simplesquirrel/simplesquirrel.hpp>
12#include "graphics/ClipSpace.h"
13#include "graphics/Graphics.h"
15#include "graphics/Mesh.h"
17
18namespace eve::graphics {
19namespace {
20const Value* field(const Value& v, const char* key) {
21 const auto* o = v.getIf<Value::Object>();
22 if (!o) return nullptr;
23 auto it = o->find(key);
24 return it == o->end() ? nullptr : &it->second;
25}
26const std::string* text(const Value& v, const char* key) {
27 const auto* item = field(v, key);
28 return item ? item->getIf<std::string>() : nullptr;
29}
30bool number(const Value* v, double& out) {
31 if (!v) return false;
32 if (auto p = v->getIf<double>())
33 out = *p;
34 else if (auto p = v->getIf<std::int64_t>())
35 out = double(*p);
36 else
37 return false;
38 return std::isfinite(out);
39}
40bool array(const Value* v, size_t count) {
41 const auto* a = v ? v->getIf<Value::Array>() : nullptr;
42 if (!a || a->size() != count) return false;
43 for (const auto& item : *a) {
44 double n = 0;
45 if (!number(&item, n) || std::abs(n) > 1e8) return false;
46 }
47 return true;
48}
49glm::vec3 vec(const Value& v) {
50 glm::vec3 out;
51 const auto& a = *v.getIf<Value::Array>();
52 for (int i = 0; i < 3; ++i) {
53 double n = 0;
54 number(&a[i], n);
55 out[i] = float(n);
56 }
57 return out;
58}
59Result<Value> fail(DiagnosticCode code, const char* message) {
61}
62bool validPixels(const VisibilityPixels& pixels, int width, int height) {
63 const auto count = size_t(width) * size_t(height);
64 return pixels.width == width && pixels.height == height && pixels.ids.size() == count &&
65 pixels.depth.size() == count && std::all_of(pixels.depth.begin(), pixels.depth.end(), [](float depth) {
66 return std::isfinite(depth) && depth >= 0 && depth <= 1;
67 });
68}
69bool fields(const Value& v, const std::set<std::string>& allowed) {
70 const auto* o = v.getIf<Value::Object>();
71 if (!o) return false;
72 for (const auto& [k, item] : *o) {
73 (void)item;
74 if (!allowed.contains(k)) return false;
75 }
76 return true;
77}
78} // namespace
80 const auto reject = [] {
83 "Invalid eve.scene.visibility-request v1/v2; bounded viewport, camera, draws and targets required"));
84 };
85 if (!fields(request, {"schemaId", "schemaVersion", "sourceRevision", "candidateGeneration", "camera", "width",
86 "height", "draws", "targets"}))
87 return reject();
88 auto schema = text(request, "schemaId");
89 double version = 0, width = 0, height = 0, revision = 0, generation = 0;
90 if (!schema || *schema != "eve.scene.visibility-request" || !number(field(request, "schemaVersion"), version) ||
91 (version != 1 && version != 2) || !number(field(request, "width"), width) ||
92 !number(field(request, "height"), height) || width < 1 || height < 1 || width > 2048 || height > 2048 ||
93 std::floor(width) != width || std::floor(height) != height || width * height > 1048576 ||
94 !number(field(request, "sourceRevision"), revision) || revision < 0 || std::floor(revision) != revision ||
95 !number(field(request, "candidateGeneration"), generation) || generation < 0 ||
96 std::floor(generation) != generation)
97 return reject();
98 const auto* camera = field(request, "camera");
99 double fov = 0, nearZ = 0, farZ = 0;
100 if (!camera || !fields(*camera, {"eye", "target", "up", "fov", "near", "far"}) ||
101 !array(field(*camera, "eye"), 3) || !array(field(*camera, "target"), 3) || !array(field(*camera, "up"), 3) ||
102 !number(field(*camera, "fov"), fov) || fov <= 1 || fov >= 179 || !number(field(*camera, "near"), nearZ) ||
103 nearZ < 1e-6 || !number(field(*camera, "far"), farZ) || farZ <= nearZ || farZ > 1e8)
104 return reject();
105 auto forward = vec(*field(*camera, "target")) - vec(*field(*camera, "eye"));
106 if (glm::length(forward) < 1e-6f || glm::length(glm::cross(forward, vec(*field(*camera, "up")))) < 1e-6f)
107 return reject();
108 const auto* drawsValue = field(request, "draws");
109 const auto* draws = drawsValue ? drawsValue->getIf<Value::Array>() : nullptr;
110 const auto* targetsValue = field(request, "targets");
111 const auto* targets = targetsValue ? targetsValue->getIf<Value::Array>() : nullptr;
112 if (!draws || draws->empty() || draws->size() > 4096 || !targets || targets->empty() || targets->size() > 16)
113 return reject();
114 std::set<std::string> objects, identities;
115 for (const auto& draw : *draws) {
116 const auto* object = text(draw, "object");
117 double id = 0, gen = 0;
118 if (!fields(draw, {"object", "entityId", "generation", "model"}) || !object || object->empty() ||
119 !number(field(draw, "entityId"), id) || id < 0 || id > UINT32_MAX || std::floor(id) != id ||
120 !number(field(draw, "generation"), gen) || gen < 0 || gen > UINT32_MAX || std::floor(gen) != gen ||
121 !array(field(draw, "model"), 16))
122 return reject();
123 if (!identities.insert(std::to_string(id) + ":" + std::to_string(gen)).second) return reject();
124 const auto& model = *field(draw, "model")->getIf<Value::Array>();
125 double n = 0;
126 for (int i : {3, 7, 11, 15}) {
127 number(&model[i], n);
128 if (n != (i == 15 ? 1 : 0)) return reject();
129 }
130 objects.insert(*object);
131 }
132 std::set<std::pair<std::string, std::string>> unique;
133 for (const auto& target : *targets) {
134 const auto* id = target.getIf<std::string>();
135 std::string regionId;
136 if (!id) {
137 if (version != 2 || !fields(target, {"object", "region"})) return reject();
138 id = text(target, "object");
139 const auto* value = field(target, "region");
140 if (!value) return reject();
142 if (!region.ok()) return Result<SceneVisibilityQuery>::failure(region.status());
143 regionId = region.value().id;
144 }
145 if (!id || !objects.contains(*id) || !unique.emplace(*id, regionId).second) return reject();
146 }
147 if (width * height * (targets->size() + 1) > 4194304) return reject();
149 query.request_ = request;
150 return Result<SceneVisibilityQuery>::success(std::move(query));
151}
153 if (!field(request_, "camera"))
154 return fail(DiagnosticCode::InvalidArgument, "Visibility query is empty or moved from");
155 if (consumed_) return fail(DiagnosticCode::Conflict, "Visibility query has already been consumed");
156 consumed_ = true;
157 double n = 0;
158 number(field(request_, "width"), n);
159 int width = int(n);
160 number(field(request_, "height"), n);
161 int height = int(n);
162 const auto& camera = *field(request_, "camera");
163 double fov = 0, nearZ = 0, farZ = 0;
164 number(field(camera, "fov"), fov);
165 number(field(camera, "near"), nearZ);
166 number(field(camera, "far"), farZ);
167 const auto view =
168 glm::lookAtRH(vec(*field(camera, "eye")), vec(*field(camera, "target")), vec(*field(camera, "up")));
169 const auto projection =
170 perspectiveVulkanRH_ZO(float(fov * 3.141592653589793 / 180), float(width) / height, float(nearZ), float(farZ));
171 std::vector<EntityIdDraw> draws;
172 std::map<std::string, std::uint32_t> mapping;
173 for (const auto& input : *field(request_, "draws")->getIf<Value::Array>()) {
174 number(field(input, "entityId"), n);
175 auto id = std::uint32_t(n);
176 number(field(input, "generation"), n);
177 auto generation = std::uint32_t(n);
178 ecs::EntityHandle handle{ecs::current(), std::type_index(typeid(Renderable3D)), id, generation};
179 auto* entity = dynamic_cast<Renderable3D*>(ecs::try_get(handle));
180 if (!entity) return fail(DiagnosticCode::StaleHandle, "Visibility renderable generation is stale");
181 const auto renderer = entity->meshRenderer();
182 const auto* object = text(input, "object");
183 // Reject any appearance/deformation path this opaque pass cannot reproduce.
184 if (!renderer->mesh || !renderer->mesh->gpuHandle)
185 return fail(DiagnosticCode::StaleHandle, "Visibility mesh is unavailable");
186 if (renderer->material || renderer->texture || renderer->shader || renderer->heightTexture ||
187 renderer->isHair || renderer->a != 1.f || renderer->partCount || renderer->lodCount ||
188 renderer->instances || renderer->xrayHighlight || renderer->mesh->hasGpuSkinning() ||
189 renderer->mesh->isMorphDirty())
190 return fail(DiagnosticCode::Unsupported,
191 "Visibility currently requires untextured opaque static single-part meshes");
192 auto [it, inserted] = mapping.emplace(*object, std::uint32_t(mapping.size() + 1));
193 (void)inserted;
195 draw.mesh = renderer->mesh;
196 const auto& values = *field(input, "model")->getIf<Value::Array>();
197 for (int i = 0; i < 16; ++i) {
198 number(&values[i], n);
199 draw.model[i / 4][i % 4] = float(n);
200 }
201 if (std::abs(glm::determinant(draw.model)) < 1e-10f)
202 return fail(DiagnosticCode::InvalidArgument, "Visibility model is singular");
203 auto packed = it->second;
204 draw.idColor =
205 glm::vec4((packed & 255) / 255.f, ((packed >> 8) & 255) / 255.f, ((packed >> 16) & 255) / 255.f, 1.f);
206 draws.push_back(draw);
207 }
208 auto* capture = graphics.visibilityCapture();
209 if (!capture) return fail(DiagnosticCode::Unsupported, "Backend has no isolated visibility capture");
210 auto scene = capture->captureVisibilityPixels(draws, projection * view, width, height);
211 if (!scene.ok()) return Result<Value>::failure(scene.status());
212 if (!validPixels(scene.value(), width, height))
213 return fail(DiagnosticCode::InvariantViolation, "Invalid scene raster evidence");
214 Value::Array reports;
215 Value::Object objectMap;
216 for (const auto& [object, id] : mapping) objectMap[object] = int(id);
217 constexpr float depthEpsilon = 1e-6f;
218 std::map<std::string, VisibilityPixels> fullCache;
219 std::vector<std::vector<std::uint8_t>> targetMasks;
220 for (const auto& target : *field(request_, "targets")->getIf<Value::Array>()) {
221 const auto& name = target.getIf<std::string>() ? *target.getIf<std::string>() : *text(target, "object");
222 auto id = mapping.at(name);
223 std::vector<EntityIdDraw> isolated;
224 for (const auto& draw : draws)
225 if (std::uint32_t(std::lround(draw.idColor.r * 255)) +
226 (std::uint32_t(std::lround(draw.idColor.g * 255)) << 8) +
227 (std::uint32_t(std::lround(draw.idColor.b * 255)) << 16) ==
228 id)
229 isolated.push_back(draw);
230 if (!fullCache.contains(name)) {
231 auto full = capture->captureVisibilityPixels(isolated, projection * view, width, height);
232 if (!full.ok()) return Result<Value>::failure(full.status());
233 if (!validPixels(full.value(), width, height))
234 return fail(DiagnosticCode::InvariantViolation, "Invalid target raster evidence");
235 fullCache.emplace(name, std::move(full).takeValue());
236 }
237 const auto& full = fullCache.at(name);
238 std::optional<SceneLocalRegion> region;
239 glm::dmat4 inverseClip(1.0);
240 if (!target.getIf<std::string>()) {
241 auto decoded = SceneLocalRegion::fromValue(*field(target, "region"));
242 if (!decoded.ok()) return Result<Value>::failure(decoded.status());
243 region = std::move(decoded).takeValue();
244 for (const auto& draw : isolated)
245 if (draw.model != isolated.front().model)
246 return fail(DiagnosticCode::Unsupported,
247 "Region requires one object-local frame for all target meshes");
248 inverseClip = glm::inverse(glm::dmat4(projection * view * isolated.front().model));
249 }
250 std::vector<std::uint8_t> mask(full.ids.size(), 0);
251 std::int64_t total = 0, visible = 0, ambiguous = 0;
252 std::map<std::uint32_t, std::int64_t> occluders;
253 for (size_t p = 0; p < full.ids.size(); ++p) {
254 if (full.ids[p] != id) continue;
255 if (region) {
256 const auto x = p % size_t(width), y = p / size_t(width);
257 glm::dvec4 local = inverseClip * glm::dvec4(2.0 * (double(x) + 0.5) / width - 1.0,
258 2.0 * (double(y) + 0.5) / height - 1.0, full.depth[p], 1.0);
259 if (!std::isfinite(local.w) || std::abs(local.w) < 1e-12)
260 return fail(DiagnosticCode::InvariantViolation, "Region surface unprojection is singular");
261 local /= local.w;
262 bool inside = true;
263 for (int axis = 0; axis < 3; ++axis) {
264 if (!std::isfinite(local[axis]))
265 return fail(DiagnosticCode::InvariantViolation, "Region surface unprojection is nonfinite");
266 const double epsilon =
267 1e-4 * std::max({1.0, std::abs(region->minimum[axis]), std::abs(region->maximum[axis])});
268 inside = inside && local[axis] >= region->minimum[axis] - epsilon &&
269 local[axis] <= region->maximum[axis] + epsilon;
270 }
271 if (!inside) continue;
272 }
273 mask[p] = 1;
274 ++total;
275 auto front = scene.value().ids[p];
276 if (front == id)
277 ++visible;
278 else if (front && scene.value().depth[p] + depthEpsilon < full.depth[p])
279 ++occluders[front];
280 else
281 ++ambiguous;
282 }
283 Value::Array hiddenBy;
284 for (const auto& [object, other] : mapping)
285 if (occluders.contains(other))
286 hiddenBy.emplace_back(Value::Object{{"object", object},
287 {"pixels", occluders.at(other)},
288 {"fraction", total ? double(occluders.at(other)) / total : 0}});
289 Value::Object report{{"object", name},
290 {"status", total < 4 ? "Unmeasurable"
291 : ambiguous ? "AmbiguousDepth"
292 : "Measured"},
293 {"fullPixels", total},
294 {"visiblePixels", visible},
295 {"visibleFraction", total ? double(visible) / total : 0},
296 {"ambiguousPixels", ambiguous},
297 {"occluders", std::move(hiddenBy)}};
298 if (region) {
299 report["region"] = region->toValue();
300 report["regionBoundaryEpsilonRelative"] = 1e-4;
301 }
302 reports.emplace_back(std::move(report));
303 targetMasks.push_back(std::move(mask));
304 }
305 // Depth-independent intersection of real isolated silhouettes, never bounding rectangles.
306 // Only whole-object partners are emitted; a target may itself be a local region.
307 for (size_t index = 0; index < reports.size(); ++index) {
308 auto& report = *reports[index].getIf<Value::Object>();
309 const auto total = *report.at("fullPixels").getIf<std::int64_t>();
310 Value::Array overlaps;
311 for (size_t other = 0; other < reports.size(); ++other) {
312 const auto& partner = *reports[other].getIf<Value::Object>();
313 if (partner.contains("region") || partner.at("object") == report.at("object")) continue;
314 const auto partnerTotal = *partner.at("fullPixels").getIf<std::int64_t>();
315 std::int64_t intersection = 0;
316 for (size_t pixel = 0; pixel < targetMasks[index].size(); ++pixel)
317 if (targetMasks[index][pixel] && targetMasks[other][pixel]) ++intersection;
318 overlaps.emplace_back(
319 Value::Object{{"object", partner.at("object")},
320 {"status", total >= 4 && partnerTotal >= 4 ? "Measured" : "Unmeasurable"},
321 {"intersectionPixels", intersection},
322 {"referencePixels", total},
323 {"subjectPixels", partnerTotal},
324 {"fraction", total ? double(intersection) / total : 0.0}});
325 }
326 report["projectedOverlaps"] = std::move(overlaps);
327 }
328 static std::int64_t captureGeneration = 0;
329 return Result<Value>::success(Value::Object{{"schemaId", "eve.scene.visibility-evidence"},
330 {"schemaVersion", 3},
331 {"captureId", ++captureGeneration},
332 {"sourceRevision", *field(request_, "sourceRevision")},
333 {"candidateGeneration", *field(request_, "candidateGeneration")},
334 {"camera", camera},
335 {"width", width},
336 {"height", height},
337 {"objectIds", std::move(objectMap)},
338 {"targets", std::move(reports)},
339 {"depthEpsilonNdc", double(depthEpsilon)},
340 {"precision", "opaque-triangle-raster"},
341 {"readbackComplete", true},
342 {"scope", "explicit-authoring-draw-set"},
343 {"request", request_}});
344}
345void exposeSceneVisibility(ssq::Table& table) {
346 const auto vm = table.getHandle();
347 auto cls = table.addClass<SceneVisibilityQuery>(
348 "SceneVisibilityQuery",
349 std::function<SceneVisibilityQuery*()>([]() -> SceneVisibilityQuery* { return nullptr; }), true);
350 cls.addFunc("measure", [vm](SceneVisibilityQuery* query, Graphics* graphics) {
351 if (!graphics)
354 auto result = query->measure(*graphics);
355 if (!result.ok()) return script::projectStatusResult(vm, result.status());
356 return script::projectStatusResult(vm, result.status(), std::move(result).takeValue());
357 });
358 table.addFunc("prepareSceneVisibility", [vm](ssq::Object request) {
360 if (!value.ok()) return script::projectStatusResult(vm, value.status());
361 auto prepared = SceneVisibilityQuery::prepare(value.value());
362 if (!prepared.ok()) return script::projectStatusResult(vm, prepared.status());
363 auto owned = script::makeOwnedSquirrelInstance<SceneVisibilityQuery>(
364 vm, std::make_unique<SceneVisibilityQuery>(std::move(prepared).takeValue()));
365 if (!owned.ok()) return script::projectStatusResult(vm, owned.status());
366 return script::projectStatusResult(vm, owned.status(), std::move(owned).takeValue());
367 });
368}
369} // namespace eve::graphics
double y
double x
LogicalId target
ActiveSource owned
std::uint64_t revision
int mask
glm::vec4 p[6]
HSQUIRRELVM vm
Definition ECS.cpp:38
HSQOBJECT cls
Definition ECS.cpp:39
SQObjectPtr key
Definition ECS.cpp:155
Generation generation
Definition ECS.cpp:40
std::string name
Definition ECS.cpp:154
std::vector< std::string > fields
Definition ECS.cpp:42
EvpackChunkInput input
Definition Evpack.cpp:170
std::vector< FieldTarget > targets
ScriptFieldRegion region
std::string message
DiagnosticCode code
const GltfImportRequest & request
float camera[2]
Entity-ID / isolated visibility capture kept off Graphics.h.
glm::vec3 n
Definition Grass.cpp:63
float v
std::uint32_t height
std::uint32_t width
JointPoint2D axis
std::string local
std::string id
Poco::JSON::Object::Ptr result
MeleePoint3 a
Definition MeleeHit.cpp:40
MeshVfxBatchedDraw draw
std::shared_ptr< OceanRenderer > renderer
OceanSprayView view
std::weak_ptr< PrimitiveScene > scene
PrimitiveHandle handle
std::set< std::string > values
std::set< std::string > identities
Object::Ptr value
uint8_t * pixels
const EntityFact * entity
glm::mat4 model
double number
Graphics * graphics
std::string text
ScriptStructure out
int count
The single Squirrel projection for common Result, Status and Value.
Explicit Value/Owned/Borrowed semantics at the Squirrel boundary.
bool visible
Json object
std::uint32_t depth
uint32_t index
std::vector< char > inside
V forward
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
static Status failure(StatusCode code, Diagnostic diagnostic)
Construct a failed status with one diagnostic.
Definition Status.cpp:28
The canonical owning dynamic value used by data-facing protocols.
Definition Value.h:31
std::map< std::string, Value > Object
Definition Value.h:34
std::vector< Value > Array
Definition Value.h:33
EVENGINE_API_BACKENDS public API.
Single-use, owning visibility request; no ECS/resource pointer survives a call. @thread Prepare and m...
Result< Value > measure(Graphics &graphics)
Consume the request, resolve current generation-qualified meshes and capture private GPU targets....
static Result< SceneVisibilityQuery > prepare(const Value &request)
Validate schema v1/v2 and copy the bounded request without drawing.
StateValue objects
Definition Snapshot.cpp:110
Result< T > fail(std::string message, DiagnosticCode code=DiagnosticCode::InvalidArgument)
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
卡牌游戏 UI 工具模块:工厂 + 脚本绑定入口。 功能参考 ycarowr/UiCard:扇形手牌布局、抽牌/洗牌、悬浮放大、拖拽到落牌区、 敌方手牌(背面/偷看)、费用不足置灰,以及可实时调节的布局...
Definition Animation.h:25
glm::mat4 perspectiveVulkanRH_ZO(float fovyRad, float aspect, float zNear, float zFar)
Right-handed, zero-to-one depth perspective for Vulkan swapchains.
Definition ClipSpace.h:22
void exposeSceneVisibility(ssq::Table &table)
Register the owning two-step visibility query script API, synchronously.
ssq::Table projectStatusResult(HSQUIRRELVM vm, const Status &status)
Project a checked native status that carries no payload.
Result< Value > valueFromSquirrel(HSQUIRRELVM vm, SQInteger index, const SquirrelValueOptions &options)
Convert one Squirrel value into the canonical owning Value tree.
DiagnosticCode
Stable machine-readable diagnostic codes.
Definition Diagnostic.h:47
static Result< SceneLocalRegion > fromValue(const Value &value)
Decode a finite, nonempty local box and immutable geometry revision.
One mesh contribution to an entity-ID or visibility capture pass.