载入中...
搜索中...
未找到
RenderSystem.cpp
浏览该文件的文档.
2#include "common/Assert.h"
3#include "common/Exception.h"
4#include "common/Profile.h"
6#include "common/Status.h"
8#include "graphics/Canvas.h"
9#include "graphics/Graphics.h"
10#include "graphics/Light.h"
11#include "graphics/Quad.h"
12#include "graphics/Shader.h"
13#include "graphics/Texture.h"
14
15#include <algorithm>
16#include <cmath>
17#include <cstdint>
18#include <unordered_map>
19#include <vector>
20
21namespace eve::graphics {
22
23void Renderable2D::release() { ecs::DestroyEntity(this); }
24
25void Renderable2D::setPosition(float x, float y) {
26 transform()->x = x;
27 transform()->y = y;
28}
29float Renderable2D::getX() { return transform()->x; }
30float Renderable2D::getY() { return transform()->y; }
31void Renderable2D::setRotation(float degrees) { transform()->rot = degrees; }
32float Renderable2D::getRotation() { return transform()->rot; }
33void Renderable2D::setScale(float sx, float sy) {
34 transform()->sx = sx;
35 transform()->sy = sy;
36}
37float Renderable2D::getScaleX() { return transform()->sx; }
38float Renderable2D::getScaleY() { return transform()->sy; }
40 if (width < 0.f || height < 0.f)
41 throw Exception("Sprite2D.setSize: width/height must be >= 0");
42 sprite()->width = width;
43 sprite()->height = height;
44}
45float Renderable2D::getWidth() { return sprite()->width; }
46float Renderable2D::getHeight() { return sprite()->height; }
47void Renderable2D::setTexture(Texture *texture) { sprite()->texture = texture; }
48Texture *Renderable2D::getTexture() { return sprite()->texture; }
49void Renderable2D::setNormalTexture(Texture *texture) { sprite()->normalTexture = texture; }
50Texture *Renderable2D::getNormalTexture() { return sprite()->normalTexture; }
51void Renderable2D::setQuad(Quad *quad) { sprite()->quad = quad; }
52Quad *Renderable2D::getQuad() { return sprite()->quad; }
53void Renderable2D::setColor(float r, float g, float b, float a) {
54 sprite()->r = r;
55 sprite()->g = g;
56 sprite()->b = b;
57 sprite()->a = a;
58}
59void Renderable2D::setLayer(int layer) { sprite()->layer = layer; }
60int Renderable2D::getLayer() { return sprite()->layer; }
61void Renderable2D::setVisible(bool visible) { sprite()->visible = visible; }
62bool Renderable2D::getVisible() { return sprite()->visible; }
63void Renderable2D::setReceiveLight(bool receive) { sprite()->receiveLight = receive; }
64bool Renderable2D::getReceiveLight() { return sprite()->receiveLight; }
65void Renderable2D::setBlend(const std::string &blend) {
66 if (blend == "alpha") sprite()->blend = BlendMode::Alpha;
67 else if (blend == "additive" || blend == "add") sprite()->blend = BlendMode::Additive;
68 else if (blend == "opaque") sprite()->blend = BlendMode::Opaque;
69 else if (blend == "premultiplied" || blend == "premultiplied_alpha")
70 sprite()->blend = BlendMode::Premultiplied;
71 else if (blend == "multiply") sprite()->blend = BlendMode::Multiply;
72 else throw Exception(
73 "Sprite2D.setBlend: expected alpha|additive|opaque|premultiplied|multiply");
74}
76 switch (sprite()->blend) {
77 case BlendMode::Additive: return "additive";
78 case BlendMode::Opaque: return "opaque";
79 case BlendMode::Premultiplied: return "premultiplied";
80 case BlendMode::Multiply: return "multiply";
81 default: return "alpha";
82 }
83}
84void Renderable2D::setAnchor(float x, float y) {
85 sprite()->anchorX = x;
86 sprite()->anchorY = y;
87}
88float Renderable2D::getAnchorX() { return sprite()->anchorX; }
89float Renderable2D::getAnchorY() { return sprite()->anchorY; }
90void Renderable2D::setFlip(bool horizontal, bool vertical) {
91 sprite()->flipX = horizontal;
92 sprite()->flipY = vertical;
93}
94bool Renderable2D::getFlipX() { return sprite()->flipX; }
95bool Renderable2D::getFlipY() { return sprite()->flipY; }
96void Renderable2D::setFrameLayout(int sourceW, int sourceH, int trimW, int trimH, int offsetX, int offsetY) {
97 setSize(float(sourceW), float(sourceH));
98 sprite()->trimW = trimW;
99 sprite()->trimH = trimH;
100 sprite()->offsetX = offsetX;
101 sprite()->offsetY = offsetY;
102}
103
104void Camera2D::setAmbient(float r, float g, float b) {
105 auto d = data();
106 d->ambientR = r;
107 d->ambientG = g;
108 d->ambientB = b;
109}
110
111void Camera2D::setPosition(float x, float y) {
112 auto d = data();
113 d->x = x;
114 d->y = y;
115}
116
117float Camera2D::getX() { return data()->x; }
118float Camera2D::getY() { return data()->y; }
119
120void Camera2D::setZoom(float zoom) { data()->zoom = zoom; }
121float Camera2D::getZoom() { return data()->zoom; }
122
123Result<void> Camera2D::setPixelConfig(float pixelsPerUnit, int refWidth, int refHeight) {
124 if (!std::isfinite(pixelsPerUnit) || pixelsPerUnit <= 0.f)
126 DiagnosticCode::InvalidArgument, "pixelsPerUnit must be finite and > 0", "camera2d.pixelsPerUnit"));
127 if (refWidth < 0 || refHeight < 0)
129 "pixel reference size must be >= 0", "camera2d.pixelRef"));
130 if ((refWidth == 0) != (refHeight == 0))
132 "pixel reference width and height must both be set or both 0",
133 "camera2d.pixelRef"));
134 auto d = data();
135 d->pixelsPerUnit = pixelsPerUnit;
136 d->pixelRefWidth = refWidth;
137 d->pixelRefHeight = refHeight;
138 return Result<void>::success();
139}
140
142 auto d = data();
143 d->pixelsPerUnit = 1.f;
144 d->pixelRefWidth = 0;
145 d->pixelRefHeight = 0;
146 d->pixelScale = 1;
147}
148
149void Camera2D::setPixelPerfect(bool enabled) { data()->pixelPerfect = enabled; }
150bool Camera2D::getPixelPerfect() { return data()->pixelPerfect; }
151void Camera2D::setPixelSnap(bool enabled) { data()->pixelSnap = enabled; }
152bool Camera2D::getPixelSnap() { return data()->pixelSnap; }
153
154Result<void> Camera2D::applyPixelPerfect(int viewWidth, int viewHeight) {
155 if (viewWidth <= 0 || viewHeight <= 0)
157 Diagnostic::error(DiagnosticCode::InvalidArgument, "viewport size must be > 0", "camera2d.viewport"));
158 auto d = data();
159 const auto sized =
160 computePixelPerfectScale(d->pixelsPerUnit, d->pixelRefWidth, d->pixelRefHeight, viewWidth, viewHeight);
161 d->pixelPerfect = true;
162 d->pixelScale = sized.scale;
163 d->zoom = sized.zoom2D;
164 if (d->pixelSnap) {
165 d->x = snapWorldToPixel(d->x, d->zoom);
166 d->y = snapWorldToPixel(d->y, d->zoom);
167 }
168 return Result<void>::success();
169}
170
171float Camera2D::getPixelsPerUnit() { return data()->pixelsPerUnit; }
172int Camera2D::getPixelRefWidth() { return data()->pixelRefWidth; }
173int Camera2D::getPixelRefHeight() { return data()->pixelRefHeight; }
174int Camera2D::getPixelScale() { return data()->pixelScale; }
175
176float Camera2D::screenToWorldX(float screenX, float /*screenY*/, float viewW, float /*viewH*/) {
177 auto d = data();
178 float z = d->zoom <= 0.f ? 1e-4f : d->zoom;
179 return (screenX - viewW * 0.5f) / z + d->x;
180}
181
182float Camera2D::screenToWorldY(float /*screenX*/, float screenY, float /*viewW*/, float viewH) {
183 auto d = data();
184 float z = d->zoom <= 0.f ? 1e-4f : d->zoom;
185 return (screenY - viewH * 0.5f) / z + d->y;
186}
187
188float Camera2D::worldToScreenX(float worldX, float /*worldY*/, float viewW, float /*viewH*/) {
189 auto d = data();
190 float z = d->zoom <= 0.f ? 1e-4f : d->zoom;
191 return (worldX - d->x) * z + viewW * 0.5f;
192}
193
194float Camera2D::worldToScreenY(float /*worldX*/, float worldY, float /*viewW*/, float viewH) {
195 auto d = data();
196 float z = d->zoom <= 0.f ? 1e-4f : d->zoom;
197 return (worldY - d->y) * z + viewH * 0.5f;
198}
199
200void Renderable2D::setCastOcclusion(bool cast) { sprite()->castOcclusion = cast; }
201
202bool Renderable2D::getCastOcclusion() { return sprite()->castOcclusion; }
203
204namespace {
205
206float clampZoom(float z) { return z <= 0.f ? 1e-4f : z; }
207
208struct ViewCam {
209 float x = 0.f;
210 float y = 0.f;
211 float zoom = 1.f;
212 bool valid = false;
213 Color clearColor{0.1f, 0.1f, 0.12f, 1.f};
214 float ambientR = 0.15f, ambientG = 0.15f, ambientB = 0.18f;
215};
216
217ViewCam fromEntity(Camera2D *ent, int viewW = 0, int viewH = 0) {
218 ViewCam v;
219 if (!ent) return v;
220 auto d = ent->data();
221 v.valid = true;
222 v.x = d->x;
223 v.y = d->y;
224 v.zoom = d->zoom;
225 if (d->pixelPerfect && viewW > 0 && viewH > 0) {
226 const auto sized =
227 computePixelPerfectScale(d->pixelsPerUnit, d->pixelRefWidth, d->pixelRefHeight, viewW, viewH);
228 d->pixelScale = sized.scale;
229 d->zoom = sized.zoom2D;
230 v.zoom = sized.zoom2D;
231 if (d->pixelSnap) {
232 d->x = snapWorldToPixel(d->x, d->zoom);
233 d->y = snapWorldToPixel(d->y, d->zoom);
234 v.x = d->x;
235 v.y = d->y;
236 }
237 }
238 v.clearColor = Color(d->r, d->g, d->b, d->a);
239 v.ambientR = d->ambientR;
240 v.ambientG = d->ambientG;
241 v.ambientB = d->ambientB;
242 return v;
243}
244
245void applyCamera(float wx, float wy, float ww, float wh, const ViewCam &cam, int viewW, int viewH,
246 float &sx, float &sy, float &sw, float &sh) {
247 if (!cam.valid) {
248 sx = wx;
249 sy = wy;
250 sw = ww;
251 sh = wh;
252 return;
253 }
254 ASSERT_GT(viewW, 0);
255 ASSERT_GT(viewH, 0);
256 const float z = clampZoom(cam.zoom);
257 ASSERT_GT(z, 0.f);
258 sx = (wx - cam.x) * z + float(viewW) * 0.5f;
259 sy = (wy - cam.y) * z + float(viewH) * 0.5f;
260 sw = ww * z;
261 sh = wh * z;
262}
263
264struct PackedLight {
265 Light2D::Data *data = nullptr;
266 bool isPoint = true;
267};
268
269void collectLights(Canvas *canvasKey, std::vector<PackedLight> &out) {
270 out.clear();
271 if (ecs::current()->getManager<Light2D>() == nullptr) return;
272 auto view = ecs::View<Light2D, Light2D::Data>();
273 for (auto it = view.begin(); it != view.end(); ++it) {
274 auto [d] = *it;
275 if (!d->enabled) continue;
276 if (d->volumetricOnly) continue; // emissive proxies skip surface lighting
277 if (d->canvas != canvasKey) continue;
278 PackedLight pl;
279 pl.data = d;
280 pl.isPoint = (d->type != "dir");
281 out.push_back(pl);
282 }
283 std::stable_sort(out.begin(), out.end(), [](const PackedLight &a, const PackedLight &b) {
284 if (a.isPoint != b.isPoint) return a.isPoint && !b.isPoint;
285 return a.data->intensity > b.data->intensity;
286 });
287 if (out.size() > size_t(Lighting2DUBO::kMaxLights))
288 out.resize(size_t(Lighting2DUBO::kMaxLights));
289}
290
291Lighting2DUBO packLights(const std::vector<PackedLight> &lights, const ViewCam &cam, int viewW,
292 int viewH) {
293 Lighting2DUBO ubo{};
294 ubo.ambient = glm::vec4(cam.ambientR, cam.ambientG, cam.ambientB, 0.f);
295 ubo.meta = glm::vec4(float(lights.size()), float(viewW), float(viewH), 0.f);
296 for (size_t i = 0; i < lights.size(); ++i) {
297 const auto *d = lights[i].data;
298 Light2DGpu &g = ubo.lights[i];
299 g.color = glm::vec4(d->r * d->intensity, d->g * d->intensity, d->b * d->intensity, 1.f);
300 g.spot = glm::vec4(0.f, 0.f, -2.f, -2.f);
301 if (lights[i].isPoint) {
302 float lx = d->x, ly = d->y;
303 float lr = d->radius;
304 if (cam.valid) {
305 const float z = clampZoom(cam.zoom);
306 lx = (d->x - cam.x) * z + float(viewW) * 0.5f;
307 ly = (d->y - cam.y) * z + float(viewH) * 0.5f;
308 lr = d->radius * z;
309 }
310 // Spot keeps cone metadata even at radius 0 so shaders/CPU can reject the
311 // directional branch (w<=0 alone is the dir discriminator for point/dir).
312 if (d->type == "spot") {
313 float dx = d->dx, dy = d->dy;
314 const float len = std::sqrt(dx * dx + dy * dy);
315 if (len > 1e-6f) {
316 dx /= len;
317 dy /= len;
318 } else {
319 dx = 0.f;
320 dy = -1.f;
321 }
322 float cosOuter = 0.f, cosInner = 0.f;
323 light2dSpotCosines(d->spotAngleDeg, d->spotSoftness, cosOuter, cosInner);
324 g.spot = glm::vec4(dx, dy, cosOuter, cosInner);
325 }
326 g.posRadius = glm::vec4(lx, ly, 0.f, lr);
327 } else {
328 float dx = d->dx, dy = d->dy;
329 const float len = std::sqrt(dx * dx + dy * dy);
330 if (len > 1e-6f) {
331 dx /= len;
332 dy /= len;
333 } else {
334 dx = 0.f;
335 dy = -1.f;
336 }
337 g.posRadius = glm::vec4(dx, dy, 0.f, 0.f);
338 }
339 }
340 return ubo;
341}
342
343Color modulateUnlit(Color base, float cx, float cy, bool receiveLight, const Lighting2DUBO &ubo) {
344 if (!receiveLight) return base;
345 glm::vec3 lit(ubo.ambient.r, ubo.ambient.g, ubo.ambient.b);
346 const int count = int(ubo.meta.x + 0.5f);
347 for (int i = 0; i < count; ++i) {
348 const auto &L = ubo.lights[i];
349 glm::vec3 col(L.color.r, L.color.g, L.color.b);
350 if (L.posRadius.w <= 0.f) {
351 // Zero-range spots contribute nothing; do not treat position as a dir vector.
352 if (L.spot.z <= -1.5f) {
353 // Directional: approximate as constant contribution for unlit sprites.
354 lit += col * 0.65f;
355 }
356 } else {
357 const float dx = L.posRadius.x - cx;
358 const float dy = L.posRadius.y - cy;
359 const float dist = std::sqrt(dx * dx + dy * dy);
360 float atten = 1.f - dist / std::max(L.posRadius.w, 1.f);
361 if (atten < 0.f) atten = 0.f;
362 atten *= atten;
363 if (L.spot.z > -1.5f) {
364 const float fx = cx - L.posRadius.x;
365 const float fy = cy - L.posRadius.y;
366 const float fl = std::sqrt(fx * fx + fy * fy);
367 float spotAtten = 1.f;
368 if (fl > 1e-4f) {
369 const float beamLen =
370 std::sqrt(L.spot.x * L.spot.x + L.spot.y * L.spot.y);
371 if (beamLen > 1e-6f) {
372 const float cosTheta = (fx * L.spot.x + fy * L.spot.y) / (fl * beamLen);
373 const float t = (cosTheta - L.spot.z) / std::max(L.spot.w - L.spot.z, 1e-4f);
374 spotAtten = std::clamp(t, 0.f, 1.f);
375 spotAtten = spotAtten * spotAtten * (3.f - 2.f * spotAtten);
376 } else {
377 spotAtten = 0.f;
378 }
379 }
380 atten *= spotAtten;
381 }
382 lit += col * atten;
383 }
384 }
385 return Color(base.r * lit.r, base.g * lit.g, base.b * lit.b, base.a);
386}
387
388} // namespace
389
390void RenderSystem::collectSprites(std::vector<DrawItem2D> &out) {
391 std::unordered_map<Canvas *, Camera2D *> defaultCam;
392 if (ecs::current()->getManager<Camera2D>() != nullptr) {
393 auto camView = ecs::View<Camera2D, Camera2D::Data>();
394 for (auto it = camView.begin(); it != camView.end(); ++it) {
395 auto [data] = *it;
396 if (!data->active) continue;
397 ASSERT(data->entity != nullptr);
398 if (!data->entity) continue;
399 Canvas *key = data->canvas;
400 if (defaultCam.find(key) == defaultCam.end()) defaultCam[key] = data->entity;
401 }
402 }
403
404 auto view = ecs::View<Renderable2D, Renderable2D::Transform2D, Renderable2D::Sprite>();
405 for (auto it = view.begin(); it != view.end(); ++it) {
406 auto [xf, sp] = *it;
407 if (!sp->visible) continue;
408
409 Camera2D *camEnt = sp->camera;
410 if (!camEnt) {
411 auto found = defaultCam.find(sp->canvas);
412 camEnt = (found != defaultCam.end()) ? found->second : nullptr;
413 }
414
415 ViewCam cam = fromEntity(camEnt);
416 DrawItem2D item;
417 item.x = xf->x + float(sp->offsetX) * xf->sx;
418 item.y = xf->y + float(sp->offsetY) * xf->sy;
419 item.w = float(sp->trimW > 0 ? sp->trimW : sp->width) * xf->sx;
420 item.h = float(sp->trimH > 0 ? sp->trimH : sp->height) * xf->sy;
421 item.depthY = xf->y + sp->height * xf->sy;
422 item.rotation = xf->rot;
423 item.anchorX = sp->trimW > 0
424 ? (sp->anchorX * sp->width - float(sp->offsetX)) / float(sp->trimW)
425 : sp->anchorX;
426 item.anchorY = sp->trimH > 0
427 ? (sp->anchorY * sp->height - float(sp->offsetY)) / float(sp->trimH)
428 : sp->anchorY;
429 item.flipX = sp->flipX;
430 item.flipY = sp->flipY;
431 item.color = Color(sp->r, sp->g, sp->b, sp->a);
432 item.layer = sp->layer;
433 item.blend = sp->blend;
434 item.texture = sp->texture;
435 item.normal = sp->normalTexture;
436 item.quad = sp->quad;
437 item.shader = sp->shader;
438 item.canvas = sp->canvas;
439 item.camera = camEnt;
440 item.camValid = cam.valid;
441 item.camX = cam.x;
442 item.camY = cam.y;
443 item.camZoom = cam.zoom;
444 item.camClear = cam.clearColor;
445 item.camAmbientR = cam.ambientR;
446 item.camAmbientG = cam.ambientG;
447 item.camAmbientB = cam.ambientB;
448 item.receiveLight = sp->receiveLight;
449 item.litPath = sp->receiveLight && sp->normalTexture != nullptr && sp->texture != nullptr &&
450 sp->shader == nullptr;
451 if (item.quad && item.texture) {
452 item.hasUV = true;
453 item.quad->getUV(item.texture->getWidth(), item.texture->getHeight(), item.u0, item.v0,
454 item.u1, item.v1);
455 }
456 out.push_back(item);
457 }
458}
459
460void RenderSystem::drawItems(Graphics &gfx, std::vector<DrawItem2D> &items, bool present) {
461 eve::debug::RenderPassScope pass("RenderSystem2D");
462 sortDrawItems2D(items);
463
464 std::unordered_map<Canvas *, Camera2D *> defaultCam;
465 if (ecs::current()->getManager<Camera2D>() != nullptr) {
466 auto camView = ecs::View<Camera2D, Camera2D::Data>();
467 for (auto it = camView.begin(); it != camView.end(); ++it) {
468 auto [data] = *it;
469 if (!data->active) continue;
470 if (!data->entity) continue;
471 Canvas *key = data->canvas;
472 if (defaultCam.find(key) == defaultCam.end()) defaultCam[key] = data->entity;
473 }
474 }
475
476 Canvas *current = reinterpret_cast<Canvas *>(static_cast<uintptr_t>(1));
477 Lighting2DUBO currentLights{};
478 for (size_t i = 0; i < items.size(); ++i) {
479 Canvas *next = items[i].canvas;
480 if (i == 0 || next != current) {
481 Color clearCol = gfx.getBackgroundColor();
482 ViewCam groupCam{};
483 auto defIt = defaultCam.find(next);
484 int viewW = next ? next->getWidth() : gfx.getWidth();
485 int viewH = next ? next->getHeight() : gfx.getHeight();
486 if (defIt != defaultCam.end()) {
487 groupCam = fromEntity(defIt->second, viewW, viewH);
488 clearCol = groupCam.clearColor;
489 } else if (items[i].camValid) {
490 groupCam.valid = true;
491 groupCam.x = items[i].camX;
492 groupCam.y = items[i].camY;
493 groupCam.zoom = items[i].camZoom;
494 groupCam.clearColor = items[i].camClear;
495 groupCam.ambientR = items[i].camAmbientR;
496 groupCam.ambientG = items[i].camAmbientG;
497 groupCam.ambientB = items[i].camAmbientB;
498 clearCol = groupCam.clearColor;
499 }
500
501 gfx.setCanvas(next);
502 eve::debug::rtTarget(next ? "canvas" : "screen");
503 // Only clear when presenting a full sprite pass; map-unified draws must not wipe.
504 if (present) gfx.clear(clearCol, std::nullopt, std::nullopt);
505 current = next;
506
507 std::vector<PackedLight> packed;
508 collectLights(next, packed);
509 currentLights = packLights(packed, groupCam, viewW, viewH);
510 gfx.setLighting2D(currentLights);
511 }
512
513 const auto &it = items[i];
514 int viewW = it.canvas ? it.canvas->getWidth() : gfx.getWidth();
515 int viewH = it.canvas ? it.canvas->getHeight() : gfx.getHeight();
516 ViewCam cam{};
517 if (it.camera) {
518 cam = fromEntity(it.camera, viewW, viewH);
519 } else if (it.camValid) {
520 cam.valid = true;
521 cam.x = it.camX;
522 cam.y = it.camY;
523 cam.zoom = it.camZoom;
524 }
525 float sx, sy, sw, sh;
526 applyCamera(it.x, it.y, it.w, it.h, cam, viewW, viewH, sx, sy, sw, sh);
527
528 float u0 = it.hasUV ? it.u0 : 0.f;
529 float v0 = it.hasUV ? it.v0 : 0.f;
530 float u1 = it.hasUV ? it.u1 : 1.f;
531 float v1 = it.hasUV ? it.v1 : 1.f;
532 if (!it.hasUV && it.quad && it.texture)
533 it.quad->getUV(it.texture->getWidth(), it.texture->getHeight(), u0, v0, u1, v1);
534 if (it.flipX) std::swap(u0, u1);
535 if (it.flipY) std::swap(v0, v1);
536
537 const float pivotX = sx + sw * it.anchorX;
538 const float pivotY = sy + sh * it.anchorY;
539 const float radians = it.rotation * 3.14159265358979323846f / 180.f;
540 const float ox = sw * (0.5f - it.anchorX);
541 const float oy = sh * (0.5f - it.anchorY);
542 const float centerX = pivotX + ox * std::cos(radians) - oy * std::sin(radians);
543 const float centerY = pivotY + ox * std::sin(radians) + oy * std::cos(radians);
544
545 if (it.sceneColorDistortion) {
546 eve::debug::rtBind("texture", "distortion");
547 eve::debug::rtBind("texture", "sceneColor");
548 eve::debug::rtDraw("drawSceneColorDistortionUVRotated", "distortion");
549 gfx.drawSceneColorDistortionUVRotated(it.texture, centerX, centerY, sw, sh, it.rotation,
550 u0, v0, u1, v1, it.distortionStrength,
551 it.color.a, it.rotatedUV);
552 } else if (it.litPath) {
553 eve::debug::rtBind("texture", "albedo");
554 eve::debug::rtBind("texture", "normal");
555 if (it.rotation != 0.f) {
556 eve::debug::rtDraw("drawTexturedRectLitUVRotated", "lit2d");
557 gfx.drawTexturedRectLitUVRotated(it.texture, it.normal, centerX, centerY, sw, sh, it.rotation, u0, v0,
558 u1, v1, it.color, it.blend);
559 } else {
560 eve::debug::rtDraw("drawTexturedRectLitUV", "lit2d");
561 gfx.drawTexturedRectLitUV(it.texture, it.normal, sx, sy, sw, sh, u0, v0, u1, v1, it.color, it.blend);
562 }
563 } else if (it.texture) {
564 Color c = it.color;
565 if (it.receiveLight && !it.normal)
566 c = modulateUnlit(c, sx + sw * 0.5f, sy + sh * 0.5f, true, currentLights);
567 eve::debug::rtBind("texture", "sprite");
568 if (it.shader) eve::debug::rtBind("shader", "custom");
569 if (it.rotation != 0.f) {
570 eve::debug::rtDraw("drawTexturedRectShaderUVRotated",
571 it.shader ? "shader" : "textured");
572 gfx.drawTexturedRectShaderUVRotated(it.texture, it.shader, centerX,
573 centerY, sw, sh, it.rotation, u0, v0, u1,
574 v1, c, it.rotatedUV, it.blend);
575 } else {
576 eve::debug::rtDraw("drawTexturedRectShaderUV", it.shader ? "shader" : "textured");
577 gfx.drawTexturedRectShaderUV(it.texture, it.shader, sx, sy, sw, sh, u0, v0, u1, v1, c,
578 it.rotatedUV, it.blend);
579 }
580 } else {
581 Color c = it.color;
582 if (it.receiveLight)
583 c = modulateUnlit(c, sx + sw * 0.5f, sy + sh * 0.5f, true, currentLights);
584 eve::debug::rtDraw("drawSolidRect", "solid");
585 if (it.rotation != 0.f)
586 gfx.drawSolidRectRotated(centerX, centerY, sw, sh, it.rotation, c,
587 it.blend);
588 else
589 gfx.drawSolidRect(sx, sy, sw, sh, c, it.blend);
590 }
591 }
592
593 if (present) {
594 gfx.setCanvas();
595 eve::debug::rtPassBegin("Present");
596 gfx.present();
597 eve::debug::rtPassEnd("Present");
598 }
599}
600
602 EV_PROFILE_MODULE("graphics", "Render2D");
604 std::vector<DrawItem2D> items;
605 collectSprites(items);
606 drawItems(gfx, items, true);
608}
609
610} // namespace eve::graphics
double z
double y
double x
EVEngine assertion entry point, backed by zeroerr.
float cx
Definition CardTypes.cpp:36
float cy
Definition CardTypes.cpp:37
float degrees
Definition CardTypes.cpp:38
SQObjectPtr key
Definition ECS.cpp:155
tensor::Graph g
Definition GpuGraph.cpp:7
std::vector< eve::ProcgenProbeDesc > lights
double r
float v
std::int32_t c
float blend
std::uint32_t height
std::uint32_t width
bool present
bool valid
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
glm::dvec3 dx
OceanSprayView view
Texture * texture
TileLayer * layer
#define EV_PROFILE_MODULE(module, name)
Profile the enclosing scope, tagged with a module for grouping.
Definition Profile.h:158
float d
float t
float zoom
Color clearColor
bool isPoint
float ambientG
float ambientR
float ambientB
bool found
ScriptStructure out
double current
float dy
Definition Shadow.cpp:151
int count
Structured operation status used by the common Result foundation.
float offsetX
float offsetY
bool visible
double oy
double ox
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
EVENGINE_API_FOUNDATION public API.
Definition Exception.h:13
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
RAII pass scope for C++ call sites.
Definition RenderTrace.h:90
Declarative 2D camera (viewport center + zoom).
float screenToWorldY(float screenX, float screenY, float viewW, float viewH)
bool getPixelSnap()
Return whether pixel-grid snapping is enabled.
Result< void > applyPixelPerfect(int viewWidth, int viewHeight)
Resolve integer zoom (and optional position snap) from the live viewport.
int getPixelRefHeight()
Return reference height, or 0 when unset.
int getPixelScale()
Return the last integer upscale from applyPixelPerfect.
float worldToScreenY(float worldX, float worldY, float viewW, float viewH)
void clearPixelConfig()
Clear reference resolution and restore default pixels-per-unit of 1.
int getPixelRefWidth()
Return reference width, or 0 when unset.
float worldToScreenX(float worldX, float worldY, float viewW, float viewH)
float getPixelsPerUnit()
Return configured pixels per world unit.
float screenToWorldX(float screenX, float screenY, float viewW, float viewH)
Convert screen pixel (origin top-left of viewport) to world coordinates. viewW/viewH are the current ...
void setZoom(float zoom)
Result< void > setPixelConfig(float pixelsPerUnit, int refWidth=0, int refHeight=0)
Store perfect-pixel sizing (pixels-per-unit and optional reference resolution).
void setAmbient(float r, float g, float b)
void setPosition(float x, float y)
World-space look-at center and zoom (1 = identity).
void setPixelSnap(bool enabled)
Enable or disable snapping the camera center onto the pixel grid.
void setPixelPerfect(bool enabled)
Enable or disable automatic perfect-pixel zoom resolution.
bool getPixelPerfect()
Return whether perfect-pixel resolution is enabled.
Canvas public API.
Definition Canvas.h:17
virtual void clear(std::optional< Color > color, std::optional< int > stencil, std::optional< double > depth)=0
Clears .
int getWidth() const
Returns the width.
Definition Graphics.h:489
virtual void drawTexturedRectShaderUV(Texture *texture, Shader *shader, float x, float y, float w, float h, float u0, float v0, float u1, float v1, const Color &color, bool rotatedUV=false, BlendMode blend=BlendMode::Alpha)=0
UV draw with an explicit Shader (nullptr = default textured pipeline).
virtual void drawTexturedRectLitUVRotated(Texture *albedo, Texture *normal, float cx, float cy, float w, float h, float degrees, float u0, float v0, float u1, float v1, const Color &color, BlendMode blend=BlendMode::Alpha)=0
Lit 2D draw rotated degrees clockwise (screen Y-down) around (cx, cy). Fragment tangent frame is rebu...
Color getBackgroundColor() const
Returns the background color.
Definition Graphics.h:1555
virtual void setLighting2D(const Lighting2DUBO &ubo)=0
Upload per-frame / per-canvas 2D lighting constants for subsequent lit draws.
virtual SceneColorDistortionStatus drawSceneColorDistortionUVRotated(Texture *displacement, float cx, float cy, float w, float h, float degrees, float u0, float v0, float u1, float v1, float strengthPixels, float opacity, bool rotatedUV=false)
Draws scene color distortion uv rotated.
Definition Graphics.h:795
virtual void drawSolidRect(float x, float y, float w, float h, float r, float g, float b, float a=1.f)
RGBA-float overload matching the script-facing drawSolidRect name.
virtual void drawTexturedRectShaderUVRotated(Texture *texture, Shader *shader, float cx, float cy, float w, float h, float degrees, float u0, float v0, float u1, float v1, const Color &color, bool rotatedUV=false, BlendMode blend=BlendMode::Alpha)=0
UV draw rotated degrees clockwise (screen Y-down) around the rect center. texture may be null → solid...
virtual void drawSolidRectRotated(float cx, float cy, float w, float h, float degrees, const Color &color, BlendMode blend=BlendMode::Alpha)=0
Rotated solid quad degrees clockwise (screen Y-down) around (cx, cy).
virtual void setCanvas(Canvas *canvas)=0
nullptr or this → screen. Switching flushes pending draws to the previous target.
virtual void present()=0
Present.
virtual void drawTexturedRectLitUV(Texture *albedo, Texture *normal, float x, float y, float w, float h, float u0, float v0, float u1, float v1, const Color &color, BlendMode blend=BlendMode::Alpha)=0
Lit 2D draw (albedo + normal map). Uses Lighting2DUBO from setLighting2D. normal may be null → treate...
int getHeight() const
Returns the height.
Definition Graphics.h:491
Pixel-space sub-rectangle of a Texture (atlas cell / sprite frame). UV conversion uses the texture's ...
Definition Quad.h:11
void getUV(int texW, int texH, float &u0, float &v0, float &u1, float &v1) const
Convert pixel rect to normalized UVs for a texture of size texW×texH.
Definition Quad.cpp:18
static void render(Graphics &gfx)
Full sprite pass + present (existing tests / sprite-only scenes).
static void collectSprites(std::vector< DrawItem2D > &out)
Append visible Renderable2D sprites into a shared queue.
static void drawItems(Graphics &gfx, std::vector< DrawItem2D > &items, bool present)
Sort and draw items. If present=true, calls gfx.present() at the end. Map::render uses present=false ...
void setCastOcclusion(bool cast)
Enable or disable volumetric occlusion casting.
void setVisible(bool visible)
Include or exclude the sprite from collection.
float getScaleY()
Return Y scale.
float getRotation()
Return center rotation in degrees.
void setBlend(const std::string &blend)
Set blend mode (alpha or additive).
void setScale(float sx, float sy)
Set independent X/Y scale.
void setPosition(float x, float y)
Set world-space position in pixels.
Texture * getTexture()
Return the assigned texture.
float getX()
Return world-space X position.
bool getReceiveLight()
Return whether the sprite receives 2D lights.
bool getFlipX()
Return horizontal mirror state.
void release() override
Entity.
void setNormalTexture(Texture *texture)
Assign an optional tangent-space normal map for the GPU lit2d path.
void setFrameLayout(int sourceW, int sourceH, int trimW, int trimH, int offsetX, int offsetY)
Apply trimmed-frame layout while preserving the original canvas origin.
void setRotation(float degrees)
Set center rotation in degrees.
void setLayer(int layer)
Set integer painter-order layer.
void setColor(float r, float g, float b, float a=1.f)
Set RGBA tint.
Quad * getQuad()
Return the assigned UV quad.
void setTexture(Texture *texture)
Assign the borrowed sprite texture.
float getScaleX()
Return X scale.
float getWidth()
Return unscaled width.
void setFlip(bool horizontal, bool vertical)
Mirror atlas UVs without changing transform scale.
Texture * getNormalTexture()
Return the assigned normal map, or nullptr when unlit/flat. @ownership Returns a borrowed Texture*; t...
std::string getBlend()
Return blend mode name.
bool getVisible()
Return whether the sprite is visible.
bool getCastOcclusion()
Return whether the sprite casts volumetric occlusion.
void setQuad(Quad *quad)
Assign the borrowed UV quad.
int getLayer()
Return painter-order layer.
void setAnchor(float x, float y)
Set normalized transform pivot; (0,0) top-left, (0.5,0.5) center.
float getAnchorY()
Return normalized vertical pivot.
float getY()
Return world-space Y position.
float getAnchorX()
Return normalized horizontal pivot.
void setSize(float width, float height)
Set unscaled sprite dimensions in pixels.
float getHeight()
Return unscaled height.
void setReceiveLight(bool receive)
Enable or disable 2D light reception.
bool getFlipY()
Return vertical mirror state.
GPU texture created via Graphics::newTexture. Owns GPU resources through an opaque backend handle.
Definition Texture.h:15
int getWidth() const
Returns the width.
Definition Texture.cpp:29
int getHeight() const
Returns the height.
Definition Texture.cpp:34
void rtBind(const char *kind, const char *name)
Rt bind.
Definition RenderTrace.h:69
void rtTarget(const char *name)
Rt target.
Definition RenderTrace.h:65
void rtPassBegin(const char *name)
Rt pass begin.
Definition RenderTrace.h:57
void rtFrameBegin()
Rt frame begin.
Definition RenderTrace.h:49
void rtFrameEnd()
Rt frame end.
Definition RenderTrace.h:53
void rtDraw(const char *api, const char *detail=nullptr)
Rt draw.
Definition RenderTrace.h:73
void rtPassEnd(const char *name)
Rt pass end.
Definition RenderTrace.h:61
卡牌游戏 UI 工具模块:工厂 + 脚本绑定入口。 功能参考 ycarowr/UiCard:扇形手牌布局、抽牌/洗牌、悬浮放大、拖拽到落牌区、 敌方手牌(背面/偷看)、费用不足置灰,以及可实时调节的布局...
Definition Animation.h:25
void light2dSpotCosines(float angleDeg, float softness, float &cosOuter, float &cosInner)
Backward-compatible alias for lightSpotCosines.
Definition Light.h:39
eve::Color Color
RGBA color used by every graphics draw call. Lives inside eve::graphics so including a graphics heade...
Definition Color.h:13
float snapWorldToPixel(float world, float zoom)
Snap a world coordinate onto the pixel grid for the given zoom.
Definition CameraPixel.h:53
void sortDrawItems2D(std::vector< DrawItem2D > &items)
Sort draw items 2 d.
Definition DrawItem2D.h:62
PixelPerfectScale computePixelPerfectScale(float pixelsPerUnit, int refWidth, int refHeight, int viewWidth, int viewHeight)
Compute integer scale and projection spans for a perfect-pixel camera.
Definition CameraPixel.h:31
bool enabled
Shared 2D draw queue item (sprites + tiles).
Definition DrawItem2D.h:19
BlendMode blend
2D quad blending (alpha / additive / opaque).
Definition DrawItem2D.h:37
float camX
Screen-space camera already resolved; if cameraEntity set, RenderSystem resolves.
Definition DrawItem2D.h:55
float anchorX
Normalized transform pivot; (0,0) top-left, (0.5,0.5) center.
Definition DrawItem2D.h:28
float rotation
Degrees, clockwise, around the rectangle center (screen Y-down).
Definition DrawItem2D.h:26
Lighting2DUBO public API.
Definition Light.h:52
static constexpr int kMaxLights
Definition Light.h:53