// SPDX-License-Identifier: GPL-3.0-only // SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® module; #include "vulkan/vulkan.h" module Nostro.Ui.Shell:Canvas_impl; import std; import Crafter.Graphics; import Crafter.Event; import Nostro.Ui; import :Canvas; using namespace Nostro::Ui; using namespace Nostro::Ui::Shell; namespace fs = std::filesystem; namespace { // A font's file, or the error that names it: the window library reads a file that is not there as an empty font. fs::path Existing(fs::path file) { std::error_code ignored; if(!fs::is_regular_file(file, ignored)) { throw std::runtime_error(std::format("the font {} is missing", file.string())); } return file; } constexpr Crafter::TextAlign Align(TextAlign align) noexcept { switch(align) { case TextAlign::Center: return Crafter::TextAlign::Center; case TextAlign::Right: return Crafter::TextAlign::Right; default: return Crafter::TextAlign::Left; } } } Fonts::Fonts(const fs::path& directory) : regular(Existing(directory / "NotoSans-Regular.ttf")), medium(Existing(directory / "NotoSans-Medium.ttf")) { } Crafter::Font& Fonts::Face(FontFace face) noexcept { // There is no font of symbols yet: what asks for one is set in the text font, which has the few marks in use. return face == FontFace::Medium ? medium : regular; } TextMeasure Fonts::Measure() { return { .advance = [this](FontFace face, std::uint32_t codepoint, float px) { Crafter::Font& font = Face(face); return static_cast(font.AdvanceUnits(codepoint)) * font.ScaleForSize(px); }, .ascent = [this](FontFace face, float px) { return Face(face).AscentPx(px); }, .lineHeight = [this](FontFace face, float px) { return Face(face).LineHeight(px); }, }; } Canvas::Parts::Parts(std::uint32_t width, std::uint32_t height, std::string_view title) : window(width, height, title) { } Canvas::Canvas(Fonts& fonts, const CanvasOptions& options) : fonts(fonts), logicalWidth(static_cast(options.widthDp)), logicalHeight(static_cast(options.heightDp)), pretend(options.scale) { // The device is the process's own and is set up once, whatever number of windows the process makes. static bool deviceReady = false; if(!deviceReady) { std::error_code ignored; fs::create_directories(options.cache, ignored); Crafter::Device::pipelineCachePath = options.cache / "pipeline_cache.bin"; Crafter::Device::Initialize(); deviceReady = true; } // In pixels at a scale of 1; the display's scale is known only once the window is there. parts.emplace(options.widthDp, options.heightDp, options.title); try { Crafter::Window& window = parts->window; window.SetAppId(options.appId); // Before anything is made for the window's size. Reconcile(); const VkCommandBuffer init = window.StartInit(); // A slot for every buffer of the pool, and a few to spare; the renderer's own images and its sampler. constexpr std::uint16_t bufferSlots = (smallPairs + largePairs) * 2 * Crafter::Window::numFrames + 16; parts->heap.Initialize(16, bufferSlots, 4); window.descriptorHeap = &parts->heap; parts->atlas.Initialize(init); parts->renderer.fontAtlas = &parts->atlas; // By their full paths: the library looks for its shaders in the working directory, which is the user's. parts->renderer.Initialize(window, parts->heap, init, options.assets / "ui-quads.comp.spv", options.assets / "ui-circles.comp.spv", options.assets / "ui-images.comp.spv", options.assets / "ui-text.comp.spv", options.assets / "ui-fused.comp.spv"); window.passes.push_back(&parts->renderer); for(FrameSet& set : parts->pool) { MakePairs(set.small, smallPairs, smallBoxes, smallGlyphs); MakePairs(set.large, largePairs, largeBoxes, largeGlyphs); } parts->build.emplace(&parts->renderer.onBuild, [this](Crafter::UIBuildArgs args) { Build(args.cmd, args.frameIdx); }); window.FinishInit(); } catch(...) { Release(); throw; } } Canvas::~Canvas() { Release(); } void Canvas::Release() noexcept { if(!parts) { return; } // The frames still on the GPU read the pool's buffers as they run. vkDeviceWaitIdle(Crafter::Device::device); parts.reset(); // What the parts held is queued for a later frame to free, and none comes. Crafter::Device::DrainDeletions(); } void Canvas::MakePairs(std::vector& pairs, std::uint32_t count, std::uint32_t boxCap, std::uint32_t glyphCap) { constexpr VkBufferUsageFlags2 usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; pairs.reserve(count); for(std::uint32_t i = 0; i < count; i++) { Pair& pair = pairs.emplace_back(); // Memory the host writes, on the device too where there is such a kind: a GPU with memory of its own need not // have one. pair.boxes.Create(usage, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, boxCap, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); pair.glyphs.Create(usage, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, glyphCap, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); pair.boxSlot.emplace(parts->renderer.RegisterBuffer(pair.boxes)); pair.glyphSlot.emplace(parts->renderer.RegisterBuffer(pair.glyphs)); pair.boxCap = boxCap; pair.glyphCap = glyphCap; } } Crafter::Window& Canvas::Native() noexcept { return parts->window; } const Crafter::Window& Canvas::Native() const noexcept { return parts->window; } float Canvas::Scale() const noexcept { const float scale = pretend.value_or(parts->window.scale); return scale > 0 ? scale : 1.0f; } Box Canvas::Bounds() const noexcept { return {0, 0, static_cast(parts->window.width), static_cast(parts->window.height)}; } bool Canvas::Reconcile() { Crafter::Window& window = parts->window; // A frame being recorded draws at the size it began with, and the library sizes the window after it by itself. if(window.recording) { return false; } // What the compositor said since the last look: a size it asks for is the window's from here, and (0, 0), which // leaves the choice to the app, changes nothing. Only its newest word counts, so a size the app asked for after // it stands. At a scale that is not the display's the compositor's sizes mean something else, and are passed over. if(!pretend && (window.pendingLogicalWidth != askedWidth || window.pendingLogicalHeight != askedHeight)) { askedWidth = window.pendingLogicalWidth; askedHeight = window.pendingLogicalHeight; if(askedWidth > 0) { logicalWidth = askedWidth; } if(askedHeight > 0) { logicalHeight = askedHeight; } } // In pixels by the library's own sum, so that a size the library did apply is found applied. const float scale = Scale(); const std::uint32_t width = static_cast(std::ceil(static_cast(logicalWidth) * scale)); const std::uint32_t height = static_cast(std::ceil(static_cast(logicalHeight) * scale)); if(width == 0 || height == 0 || (width == window.width && height == window.height)) { return false; } window.Resize(width, height); return true; } void Canvas::SetSize(std::uint32_t widthDp, std::uint32_t heightDp) noexcept { logicalWidth = static_cast(widthDp); logicalHeight = static_cast(heightDp); } void Canvas::Render(const DrawList& list, Color ground) { drawing = &list; background = ground; try { parts->window.Update(); } catch(...) { drawing = nullptr; throw; } drawing = nullptr; frames++; } void Canvas::Capture(const fs::path& png) { parts->window.CaptureNextFrame(png); } const Canvas::Stats& Canvas::Last() const noexcept { return stats; } std::uint64_t Canvas::Frames() const noexcept { return frames; } std::string Canvas::Device() const { // The name is a C array of the driver's. const std::string_view name(Crafter::Device::deviceProperties.deviceName); return std::format("{} ({})", name, Crafter::Device::descriptorHeapSupported ? "descriptor heap" : "descriptor sets"); } void Canvas::Build(VkCommandBuffer commands, std::uint32_t frameIndex) { FrameSet& set = parts->pool[frameIndex]; set.smallUsed = 0; set.largeUsed = 0; stats = {}; // Nothing clears the window's image, so the ground is the first thing drawn: under the first batch where that // covers the whole window, which saves a pass over it, and by itself otherwise. const RectItem ground{.box = Bounds(), .color = background}; bool grounded = false; if(drawing != nullptr) { for(std::size_t layer = 0; layer < layerCount; layer++) { for(const Batch& batch : drawing->Batches(static_cast(layer))) { if(!grounded && batch.clip) { Submit(commands, set, Batch(), &ground); } Submit(commands, set, batch, grounded ? nullptr : &ground); grounded = true; } } } if(!grounded) { Submit(commands, set, Batch(), &ground); } } Canvas::Pair* Canvas::Take(FrameSet& set, std::size_t boxes, std::size_t glyphs) noexcept { if(boxes <= smallBoxes && glyphs <= smallGlyphs && set.smallUsed < set.small.size()) { return &set.small[set.smallUsed++]; } if(set.largeUsed < set.large.size()) { return &set.large[set.largeUsed++]; } // No large pair left for a batch that wants one: a small one shows the start of it. if(set.smallUsed < set.small.size()) { return &set.small[set.smallUsed++]; } return nullptr; } void Canvas::Submit(VkCommandBuffer commands, FrameSet& set, const Batch& batch, const RectItem* under) { // A glyph per code point at most: enough to choose the buffers by. std::size_t glyphsNeeded = 0; for(const TextItem& text : batch.texts) { glyphsNeeded += CountCodepoints(text.text); } const std::size_t boxesNeeded = batch.rects.size() + batch.circles.size() + (under != nullptr ? 1 : 0); if(boxesNeeded == 0 && glyphsNeeded == 0) { return; } Pair* const pair = Take(set, boxesNeeded, glyphsNeeded); if(pair == nullptr) { stats.overflowed = true; return; } std::uint32_t boxes = 0; const auto box = [this, pair, &boxes](Box at, Color color, Corners corners, float outline, Color outlineColor) { if(boxes >= pair->boxCap) { stats.overflowed = true; return; } // On whole pixels, edge by edge: boxes that share an edge still do, and a hairline is one row of pixels, not // two half-lit ones. const float left = std::round(at.x); const float top = std::round(at.y); const float right = std::round(at.Right()); const float bottom = std::round(at.Bottom()); pair->boxes.value[boxes] = Crafter::QuadItem{left, top, right - left, bottom - top, color.r, color.g, color.b, color.a, corners.topLeft, corners.topRight, corners.bottomRight, corners.bottomLeft, outline, outlineColor.r, outlineColor.g, outlineColor.b}; boxes++; }; if(under != nullptr) { box(under->box, under->color, under->corners, under->outline, under->outlineColor); } for(const RectItem& rect : batch.rects) { box(rect.box, rect.color, rect.corners, rect.outline, rect.outlineColor); } // A circle is a square with its corners rounded all the way, which leaves the batch one kind of shape and one // buffer for it. for(const CircleItem& circle : batch.circles) { box({circle.center.x - circle.radius, circle.center.y - circle.radius, circle.radius * 2, circle.radius * 2}, circle.color, Corners::All(circle.radius), circle.outline, circle.outlineColor); } std::uint32_t glyphs = 0; for(const TextItem& text : batch.texts) { Crafter::Font& font = fonts.Face(text.face); // The baseline on a whole pixel, so that a line of text looks the same wherever it is. glyphs += parts->renderer.ShapeText(font, text.px, text.x, std::round(text.baseline), text.text, {text.color.r, text.color.g, text.color.b, text.color.a}, pair->glyphs.value + glyphs, pair->glyphCap - glyphs, nullptr, Align(text.align)); // A glyph with ink that found no cell in the atlas drew blank, and gets one when a later frame begins: counted, // so that the frame is asked for. for(std::size_t i = 0; i < text.text.size();) { const std::uint32_t codepoint = DecodeUtf8(text.text, i); if(const Crafter::Glyph* glyph = parts->atlas.Lookup(font, codepoint); glyph != nullptr && glyph->w > 0 && !glyph->Resident()) { stats.glyphsWaiting++; } } } if(glyphsNeeded > pair->glyphCap) { stats.overflowed = true; } if(boxes == 0 && glyphs == 0) { return; } if(boxes > 0) { pair->boxes.FlushDevice(commands, VK_ACCESS_SHADER_READ_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT); } if(glyphs > 0) { pair->glyphs.FlushDevice(commands, VK_ACCESS_SHADER_READ_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT); } const std::array clip = batch.clip ? std::array{batch.clip->x, batch.clip->y, batch.clip->w, batch.clip->h} : std::array{0.0f, 0.0f, 1e9f, 1e9f}; parts->renderer.DispatchFused(commands, {*pair->boxSlot, boxes, clip}, {}, {}, {*pair->glyphSlot, glyphs, clip}); stats.batches++; stats.boxes += boxes; stats.glyphs += glyphs; }