Files
EVEngine/test/graphics_font.cpp
T
西风逍遥游 34d1fdb63b refactor(modules): clear remaining back-edges and split the largest TUs (#127)
* chore(ci): add clang-format gate, CODEOWNERS and agent collaboration rules

* refactor(modules): clear remaining back-edges and split the largest TUs

Three known dependency back-edges are gone (module_depgraph.py KNOWN_BACK_EDGES
is now empty; --check passes with 0 violations, 0 cycles):

- window -> graphics: window queries the new IWindowSurfaceHost capability
  (common/WindowSurfaceHost.h) instead of holding a Graphics pointer;
  Window::setGraphics was removed and all call sites updated.
- window -> image: Window::setIcon was replaced by setIconRGBA(const uint8_t*,
  w, h); the window no longer decodes ImageData.
- scene -> graphics: pickScreenAt / collectFrustumIdsAt implementations moved
  to graphics/ScenePicking.cpp (graphics -> scene is a legal downward edge);
  scene now depends only on spatial.

TU splits (pure moves, verified identical method sets and brace balance):

- vulkan/Graphics.cpp (5118 lines) -> Graphics.cpp (lifecycle), GraphicsPipeline,
  Graphics2D, Graphics3D, GraphicsMesh + shared GraphicsInternal.h.
- scene/Scene.cpp -> Scene.cpp (script layer / host lifecycle / serialization)
  + SceneNodes.cpp + shared SceneInternal.h.

Verified with a real build (MSVC 19.51, prebuilt third-party): full build green;
window.* and Scene.* suites pass, including scene picking/culling and GPU cases.

* refactor(graphics): narrow Graphics interfaces and clear public-header leaks

Step 4 — interface segregation:
- New lean interfaces: IGraphics2D, IGraphics3D, IResourceFactory, IPostFX
  (pure virtuals, forward-declared types only; graphics/Color.h extracted from
  Canvas.h so modules that only need the color type stop pulling Canvas.h).
- Graphics now implements all four facets; consumers can depend on the narrow
  interface they use instead of the 129-method god class.
- Migrated voxel (VoxelWorld::drawVisible -> IGraphics3D*) and model3d
  (ModelRenderer::buildRenderable(s) -> IResourceFactory&).
- Graphics.h slims from 24 sub-header includes to a handful of small type
  headers + forward declarations; the destructor moved out-of-line so
  unique_ptr effect members are destroyed where types are complete.

Step 5 — header leaks (module_depgraph.py '*' marks: 14 -> 7):
- map/TileLayer.h, particles/ParticleEmitter.h, avatar/AvatarInstance.h,
  animation/SpineAnim.h, map/TileSystem.h, model3d/ModelData.h,
  model3d/ModelRenderer.h, audio/Audio.h + Source.h, image/ImageData.h +
  Image.h, dialogue/Dialogue.h, procgen Palette/OutputSpec/TextureRecipe/
  PbrMaterial -> forward declarations, includes moved to .cpp.
- voxel/VoxelWorld.h: terrain sampler Pimpl'd (unique_ptr + out-of-line
  destructor), removing the procgen header dependency.
- gpgpu/vulkan backend headers stop pulling graphics/vulkan/Graphics.h.
- Remaining '*' marks are deliberate: tiny POD/enum headers (GridConfig,
  MapObject, BlendMode, Color), an internal backend header
  (GraphicsInternal.h -> filesystem), and lean interface references.

Verified with a full clean build (MSVC) and tests: window/Scene/voxel/
RenderSystem/Quad/shader/TextureSampler/resourceLifetime pass; broad suite
only shows the pre-existing PHYSFS-init filesystem-environment failures.

* feat(resources): revive ResourceManager as unified IAssetReloader-backed cache

* fix(resources): leak ResourceManager singleton to avoid exit-time teardown crashes

Cached CPU resources may own third-party handles (FreeType faces, Assimp
scenes, image decode handlers) whose libraries are torn down at process
exit in an unspecified TU order; destroying cached entries from the
singleton destructor can segfault at exit (seen on CI Windows in
model3d.materialApi.objMtl). Keep the singleton alive until OS reclaim;
explicit unload()/clear() still release entries during the run.

* refactor(devtools): consume business modules through capability interfaces

DevTools / cmdline no longer include business-module headers, so trimming
scene / physics / procgen / particles / audio / ui / graphics no longer
requires disabling devtools, and devtools can be switched off with
-DEVENGINE_MODULE_DEVTOOLS=OFF.

New capability interfaces in common/:
- ISceneQuery (scene) - host/node inspection + mutation + transform sync
- IRenderCapture (graphics) - render status, PNG capture, camera control,
  visible-entity snapshot, entity-ID mask, G-buffer PNGs
- IPhysicsQuery (physics) - 2D world lifecycle + ray casts
- IProcgenQuery (procgen) - recipe listing, map/mesh generation
- IParticlesQuery (particles) - emitter status + one-shot emit
- IAudioQuery (audio) - volume / stop-all
- IEditorHost (ui) - declarative editor host (used by cmdline too)

Providers register in their module constructors. DevTools rewires McpServer
(render/scene/procgen/physics/particles/audio/host tools), SceneInspect
(now delegates to ISceneQuery + IRenderCapture) and RenderVision (uses
IRenderCapture::capturePngDataUrl); cmdline/Mcp.cpp uses IEditorHost.

manifest: devtools DEPS graphics scene physics procgen particles audio ui
image event filesystem -> event; cmdline DEPS filesystem ui -> filesystem.

Verified: full build green; devtools.mcp.* tests pass; broad suite shows
only the pre-existing PHYSFS-init filesystem-environment failures.

* style: apply clang-format to changed lines after dev merge

* fix(webgpu): include RenderControl/TextureSampler explicitly after Graphics.h slimming

* fix(webgpu): provide newFont/print stubs to satisfy IGraphics2D/IResourceFactory vtables

* fix(common): make ProcgenQuery.h self-sufficient (cstdint/utility for GCC)
2026-08-20 05:53:33 +08:00

203 lines
6.7 KiB
C++

#include "zeroerr/assert.h"
#include "zeroerr/unittest.h"
#include "common/Exception.h"
#include "data/ByteData.h"
#include "font/Font.h"
#include "font/FontData.h"
#include "graphics/AmbientOcclusion.h"
#include "graphics/AntiAliasing.h"
#include "graphics/Canvas.h"
#include "graphics/DrawItem2D.h"
#include "graphics/Font.h"
#include "graphics/GBuffer.h"
#include "graphics/GlobalIllumination.h"
#include "graphics/Graphics.h"
#include "graphics/Grass.h"
#include "graphics/Light.h"
#include "graphics/Material.h"
#include "graphics/Mesh.h"
#include "graphics/Outline.h"
#include "graphics/Quad.h"
#include "graphics/RenderControl.h"
#include "graphics/ScreenSpaceReflection.h"
#include "graphics/Shader.h"
#include "graphics/Texture.h"
#include "graphics/Volumetric.h"
#include "graphics/Water.h"
#include "graphics/Waterfall.h"
#include "image/ImageData.h"
#include "window/Window.h"
#include <SDL2/SDL.h>
#include <fstream>
#include <functional>
#include <memory>
#include <string>
#include <vector>
using namespace eve::graphics;
namespace {
// Same fixture used by test/font.cpp: FontAwesome, which only has icon
// glyphs (no printable ASCII) — its one well-known bitmap lives at U+F000.
constexpr int kIconCodepoint = 0xF000;
constexpr const char *kIconUtf8 = "\xEF\x80\x80"; // UTF-8 for U+F000
#include "PathBesideSource.h"
// Color lives in eve::graphics (see graphics/Canvas.h); keep the unqualified form.
using eve::graphics::Color;
EVE_DEFINE_PATH_BESIDE_SOURCE()
std::vector<char> readBinaryFile(const std::string &path) {
std::ifstream in(path, std::ios::binary);
if (!in) return {};
return std::vector<char>((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
}
std::unique_ptr<eve::font::FontData> loadFontAwesome(int size = 32) {
auto raw = readBinaryFile(pathBesideThisSource("fonts/FontAwesome.ttf"));
if (raw.empty()) return nullptr;
eve::data::ByteData data(raw.data(), raw.size());
return std::unique_ptr<eve::font::FontData>(eve::font::Font::create()->newFontData(&data, size));
}
// Prepares a small headless window + Graphics pair, matching the pattern
// used by test/RenderSystem.cpp's GraphicsSmoke.* cases.
struct GraphicsFixture {
eve::window::Window *win = nullptr;
Graphics *gfx = nullptr;
GraphicsFixture(int w = 320, int h = 240) {
win = eve::window::Window::create();
gfx = Graphics::create();
eve::window::WindowSettings s;
s.width = static_cast<uint16_t>(w);
s.height = static_cast<uint16_t>(h);
s.centered = true;
win->setWindowSettings(s);
}
~GraphicsFixture() { win->close(); }
};
bool expectException(const std::function<void()> &fn) {
try {
fn();
} catch (const eve::Exception &) {
return true;
}
return false;
}
} // namespace
TEST_CASE("graphics.font.newFontBuildsAtlasForCharset") {
auto fontData = loadFontAwesome(32);
REQUIRE(fontData.get() != nullptr);
GraphicsFixture fx;
REQUIRE(fx.gfx != nullptr);
std::unique_ptr<Font> gfont(fx.gfx->newFont(fontData.get(), kIconUtf8));
REQUIRE(gfont.get() != nullptr);
REQUIRE(gfont->getTexture() != nullptr);
CHECK(gfont->getTexture()->getWidth() > 0);
CHECK(gfont->getTexture()->getHeight() > 0);
CHECK(gfont->getHeight() > 0.f);
CHECK(gfont->getAscent() > 0.f);
CHECK(gfont->getBaseline() > 0.f);
CHECK(gfont->getWidth(kIconUtf8) > 0.f);
// In the atlas (built only for kIconUtf8's codepoint), the icon is present
// but an arbitrary ASCII letter is not — even though FontData itself might
// resolve it differently; atlas coverage is what Font::hasGlyph reports.
CHECK(gfont->hasGlyph(kIconCodepoint));
CHECK(!gfont->hasGlyph(static_cast<int>('A')));
const Font::Glyph *g = gfont->findGlyph(kIconCodepoint);
REQUIRE(g != nullptr);
CHECK(g->width > 0);
CHECK(g->height > 0);
CHECK(g->advance > 0);
CHECK(gfont->findGlyph(static_cast<int>('A')) == nullptr);
}
TEST_CASE("graphics.font.newFontDefaultCharsetDoesNotCrash") {
auto fontData = loadFontAwesome(24);
REQUIRE(fontData.get() != nullptr);
GraphicsFixture fx;
// FontAwesome has no printable ASCII glyphs, so most/all of the default
// charset will be skipped — this exercises the "no glyphs rasterized"
// fallback path (a valid 1x1 placeholder atlas) without throwing.
std::unique_ptr<Font> gfont(fx.gfx->newFont(fontData.get()));
REQUIRE(gfont.get() != nullptr);
REQUIRE(gfont->getTexture() != nullptr);
}
TEST_CASE("graphics.print.throwsWithoutFont") {
GraphicsFixture fx;
fx.gfx->setFont(nullptr);
CHECK(fx.gfx->getFont() == nullptr);
CHECK(expectException([&] { fx.gfx->print("hello", 0, 0); }));
}
TEST_CASE("graphics.print.rendersGlyphPixelsOnCanvas") {
auto fontData = loadFontAwesome(32);
REQUIRE(fontData.get() != nullptr);
GraphicsFixture fx;
std::unique_ptr<Font> gfont(fx.gfx->newFont(fontData.get(), kIconUtf8));
REQUIRE(gfont.get() != nullptr);
fx.gfx->setFont(gfont.get());
CHECK(fx.gfx->getFont() == gfont.get());
Canvas *rt = fx.gfx->newCanvas(64, 64);
REQUIRE(rt != nullptr);
fx.gfx->setCanvas(rt);
fx.gfx->clear(Color(0.f, 0.f, 0.f, 1.f), std::nullopt, std::nullopt);
fx.gfx->print(kIconUtf8, 4.f, 4.f, Color(1.f, 1.f, 1.f, 1.f));
fx.gfx->setCanvas();
std::unique_ptr<eve::image::ImageData> img(rt->newImageData());
REQUIRE(img.get() != nullptr);
const auto *px = static_cast<const unsigned char *>(img->getData());
const int w = img->getWidth();
const int h = img->getHeight();
// The glyph should have lit up at least some pixels away from the
// all-black clear color somewhere in the canvas.
long long litPixels = 0;
for (int y = 0; y < h; ++y) {
for (int x = 0; x < w; ++x) {
const unsigned char *p = px + (static_cast<size_t>(y) * w + x) * 4;
if (p[0] > 40 || p[1] > 40 || p[2] > 40) ++litPixels;
}
}
CHECK(litPixels > 0);
// Hold the window open so the glyph is visible while debugging (~2s).
// Left: magnified canvas from the assert above. Right: live print at 3x.
fx.gfx->setBackgroundColorRGBA(0.08f, 0.08f, 0.1f, 1.f);
for (int frame = 0; frame < 60; ++frame) {
fx.gfx->clearScreen();
fx.gfx->drawTexturedRect(rt->getTexture(), 16.f, 16.f, 128.f, 128.f,
Color(1.f, 1.f, 1.f, 1.f));
fx.gfx->print(kIconUtf8, 160.f, 40.f, Color(1.f, 1.f, 1.f, 1.f), 3.f);
fx.gfx->present();
SDL_Event e;
while (SDL_PollEvent(&e)) {
if (e.type == SDL_QUIT) break;
}
SDL_Delay(16);
}
// Reset so other tests don't inherit this font.
fx.gfx->setFont(nullptr);
}