Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

12.1 KB
Raw Blame
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
 * @file    RenderContext.cpp
 * @brief   Rendering context implementation
 *
 * @author  ESEngine Team
 * @date    2026
 *
 * @copyright Copyright (c) 2026 ESEngine Team
 *            Licensed under the Apache License, Version 2.0.
 */

#include "./RenderContext.hpp"
#include "./RippleNormals.hpp"
#include "../rhi/GfxDevice.hpp"
#include "./FrameConstants.hpp"
#include "../RenderOrigin.hpp"
#include "../draw/DrawParams.hpp"
#include "../store/SkinConstants.hpp"
#include "../store/MorphConstants.hpp"
#include "../store/PlanarConstants.hpp"
#include "../store/InstanceConstants.hpp"
#include "../store/ProbeConstants.hpp"
#include "../../core/Log.hpp"

#include <cmath>
#include <vector>

#include <glm/gtc/type_ptr.hpp>

namespace esengine {

RenderContext::RenderContext(GfxDevice& device)
    : device_(device) {
}

RenderContext::~RenderContext() {
    if (initialized_) {
        shutdown();
    }
}

void RenderContext::init() {
    if (initialized_) {
        ES_LOG_WARN("RenderContext already initialized");
        return;
    }

    device_.init();
    initDefaultTextures();
    initFrameUbo();
    materials_.setDevice(&device_);
    materials_.setBuiltinDefaults(whiteTexture_, blackTexture_, flatNormalTexture_, ripplesTexture_);
    materials_.setBuiltinDefaultArrays(whiteArrayTexture_, blackArrayTexture_, flatNormalArrayTexture_);
    lights_.setDevice(&device_);

    initialized_ = true;
}

void RenderContext::shutdown() {
    if (!initialized_) {
        return;
    }

    for (TextureHandle* tex : {&whiteTexture_, &blackTexture_, &flatNormalTexture_, &ripplesTexture_, &whiteArrayTexture_,
                             &blackArrayTexture_, &flatNormalArrayTexture_}) {
        if (*tex != TextureHandle::Invalid) {
            device_.deleteTexture(*tex);
            *tex = TextureHandle::Invalid;
        }
    }

    if (frameUbo_ != BufferHandle::Invalid) {
        device_.deleteBuffer(frameUbo_);
        frameUbo_ = BufferHandle::Invalid;
    }
    if (timeUbo_ != BufferHandle::Invalid) {
        device_.deleteBuffer(timeUbo_);
        timeUbo_ = BufferHandle::Invalid;
    }
    if (drawParamsFallback_ != BufferHandle::Invalid) {
        device_.deleteBuffer(drawParamsFallback_);
        drawParamsFallback_ = BufferHandle::Invalid;
    }
    skinBlocks_.shutdown();
    morphBlocks_.shutdown();
    probeBlocks_.shutdown();
    instanceBlocks_.shutdown();
    planarBlocks_.shutdown();

    materials_.clear();  // free per-material UBOs while the device is still valid
    materials_.setResourceManager(nullptr);
    lights_.free();      // free the lighting UBO while the device is still valid

    device_.shutdown();
    initialized_ = false;
    ES_LOG_INFO("RenderContext shutdown");
}

TextureHandle RenderContext::make1x1Texture(u32 rgba, u32 layers) {
    TextureDesc desc;
    desc.width = 1;
    desc.height = 1;
    desc.layers = layers;
    desc.minFilter = TextureFilter::Nearest;
    desc.magFilter = TextureFilter::Nearest;
    const std::vector<u32> texels(layers, rgba);
    return device_.createTexture(desc, GfxContent::retained(), texels.data());
}

namespace {
/// Content this context builds from nothing but code, and builds again after a loss: the device keeps no copy of it.
constexpr u32 BUILTIN_CONTENT_PROVIDER = 0x4255494C;
constexpr u32 BUILTIN_RIPPLES = 1;
}  // namespace

TextureHandle RenderContext::makeRipplesTexture() {
    TextureDesc desc;
    desc.width = RIPPLE_NORMALS_SIZE;
    desc.height = RIPPLE_NORMALS_SIZE;
    desc.wrapS = TextureWrap::Repeat;
    desc.wrapT = TextureWrap::Repeat;
    desc.mipmaps = true;
    const std::vector<u8> pixels = buildRippleNormals();
    const TextureHandle texture =
        device_.createTexture(desc, GfxContent::sourced(BUILTIN_CONTENT_PROVIDER, BUILTIN_RIPPLES), pixels.data());
    if (texture != TextureHandle::Invalid) device_.generateMipmaps(texture);
    return texture;
}

void RenderContext::restoreBuiltinContent() {
    for (const GfxOwedContent& owed : device_.owedContent()) {
        if (owed.kind != GfxOwedContent::Kind::Texture || owed.provider != BUILTIN_CONTENT_PROVIDER) continue;
        if (owed.key != BUILTIN_RIPPLES || ripplesTexture_ == TextureHandle::Invalid) {
            device_.forgoContent(owed);
            continue;
        }
        const std::vector<u8> pixels = buildRippleNormals();
        device_.updateTexture(ripplesTexture_, 0, 0, RIPPLE_NORMALS_SIZE, RIPPLE_NORMALS_SIZE, pixels.data(), false);
        device_.restoreContent(owed);
    }
}

void RenderContext::initDefaultTextures() {
    // Byte order in memory is R,G,B,A; these u32s are little-endian (so 0xAABBGGRR).
    whiteTexture_ = make1x1Texture(0xFFFFFFFF);       // RGBA(255,255,255,255)
    blackTexture_ = make1x1Texture(0xFF000000);       // RGBA(0,0,0,255)
    flatNormalTexture_ = make1x1Texture(0xFFFF8080);  // RGB(128,128,255) → normal (0,0,1)
    whiteArrayTexture_ = make1x1Texture(0xFFFFFFFF, 2);
    blackArrayTexture_ = make1x1Texture(0xFF000000, 2);
    flatNormalArrayTexture_ = make1x1Texture(0xFFFF8080, 2);
    ripplesTexture_ = makeRipplesTexture();
    ES_LOG_DEBUG("Default textures created (white {}, black {}, flatNormal {})",
                 static_cast<u32>(whiteTexture_), static_cast<u32>(blackTexture_),
                 static_cast<u32>(flatNormalTexture_));
}

void RenderContext::initFrameUbo() {
    FrameConstants initial{};
    frameUbo_ = device_.createBuffer(
        {GfxBufferUsage::Uniform, static_cast<u32>(sizeof(FrameConstants)), /*dynamic=*/true},
        GfxContent::retained(), &initial);

    // The binding slot persists for the context lifetime; only the contents change
    // per frame. Every engine shader's FrameConstants block is linked to this slot
    // at compile time (Shader::compile).
    device_.setUniformBuffer(FRAME_CONSTANTS_BINDING, frameUbo_);

    TimeConstants time{};
    timeUbo_ = device_.createBuffer(
        {GfxBufferUsage::Uniform, static_cast<u32>(sizeof(TimeConstants)), /*dynamic=*/true},
        GfxContent::retained(), &time);
    device_.setUniformBuffer(TIME_CONSTANTS_BINDING, timeUbo_);

    // Zeroed fallback for the shared per-draw params slot: a shader whose loose
    // uniforms were lifted into a DrawParams block but whose draw path never
    // commits (e.g. a raw material shader drawn by the batch path) must still
    // find a buffer covering its block there — members then read zero, exactly
    // what their loose-uniform ancestors read.
    const std::vector<u8> zeros(DRAW_PARAMS_FALLBACK_SIZE, 0);
    drawParamsFallback_ = device_.createBuffer(
        {GfxBufferUsage::Uniform, DRAW_PARAMS_FALLBACK_SIZE, /*dynamic=*/false},
        GfxContent::retained(), zeros.data());
    device_.setUniformBuffer(DRAW_PARAMS_BINDING, drawParamsFallback_);

    // A pose, a set of shapes, and the indirect light where a draw stands. A POOL
    // each and not one buffer each, because a block rewritten between two draws of
    // one pass is read by both — see PerDrawBlocks.
    skinBlocks_.init(device_, static_cast<u32>(sizeof(SkinConstants)));
    morphBlocks_.init(device_, static_cast<u32>(sizeof(MorphConstants)));
    // A run per instance, not one for the draw: the block is what a merged draw
    // says about every object in it, and GL wants the whole declared block bound.
    probeBlocks_.init(device_, PROBE_BLOCK_BYTES);
    // An entry per draw of a run where the device draws runs: GL wants the whole declared block bound, and the programs declare
    // the array exactly when the device enabled them (glslMultiDraw).
    instanceBlocks_.init(device_, static_cast<u32>(sizeof(InstanceConstants))
                                      * (device_.supportsMultiDraw() && glslMultiDraw() ? MULTI_DRAW_MAX : 1u));
    planarBlocks_.init(device_, static_cast<u32>(sizeof(PlanarConstants)));
    // What a draw with no shapes and no volume reads. A pose has no zero: geometry
    // without one is drawn by a shader that does not declare the block.
    morphBlocks_.bindZero(MORPH_CONSTANTS_BINDING);
    probeBlocks_.bindZero(PROBE_CONSTANTS_BINDING);
    instanceBlocks_.bindZero(INSTANCE_CONSTANTS_BINDING);
    planarBlocks_.bindZero(PLANAR_CONSTANTS_BINDING);

    ES_LOG_DEBUG("FrameConstants UBO created (handle: {})", static_cast<u32>(frameUbo_));
}

void RenderContext::updateCameraConstants(const glm::mat4& viewProjection) {
    uploadFrameConstants(toClipDepthRange(viewProjection, device_.clipDepthRange()),
                         viewProjection);
}

void RenderContext::updateCameraConstants(const glm::mat4& viewProjection, const glm::vec2& jitterNdc) {
    // Added to clip xy in proportion to w, so it is the same shift in NDC under a
    // perspective divide and under none: row 0 and 1 each gain a multiple of row 3.
    glm::mat4 jittered = viewProjection;
    for (int col = 0; col < 4; ++col) {
        jittered[col][0] += jitterNdc.x * viewProjection[col][3];
        jittered[col][1] += jitterNdc.y * viewProjection[col][3];
    }
    uploadFrameConstants(toClipDepthRange(jittered, device_.clipDepthRange()), viewProjection);
}

void RenderContext::updateFrameConstants(const glm::mat4& viewProjection) {
    uploadFrameConstants(viewProjection, viewProjection);
}

u32 RenderContext::frameConstantsSize() {
    return static_cast<u32>(sizeof(FrameConstants));
}

void RenderContext::useFrameConstants(BufferHandle ubo, const glm::mat4& viewProjection) {
    if (ubo == BufferHandle::Invalid) return;
    const FrameConstants frame{viewProjection, cameraFromViewProjection(viewProjection),
                               glm::inverse(viewProjection), glm::vec4(glm::vec3(renderOrigin()), 0.0f)};
    device_.updateBuffer(ubo, 0, &frame, sizeof(FrameConstants));
    device_.setUniformBuffer(FRAME_CONSTANTS_BINDING, ubo);
    // Same re-arm the frame's own upload does: a previous pass may have left a
    // differently sized params buffer on the shared slot.
    device_.setUniformBuffer(DRAW_PARAMS_BINDING, drawParamsFallback_);
}

// `engine` is the projection in the engine's own convention, which is what the
// viewpoint is read from: the two agree on it, but only one of them is the answer
// to "where is the eye" that the rest of the engine also holds.
void RenderContext::uploadFrameConstants(const glm::mat4& upload, const glm::mat4& engine) {
    viewProjection_ = engine;
    // The viewpoint from `engine` and the un-projection from `upload`: the two
    // agree about where the eye is, but only the uploaded one describes the clip
    // space a shader will hand back.
    const FrameConstants frame{upload, cameraFromViewProjection(engine), glm::inverse(upload), glm::vec4(glm::vec3(renderOrigin()), 0.0f)};
    device_.updateBuffer(frameUbo_, 0, &frame, sizeof(FrameConstants));
    // Take the binding back. A pass that draws several views points this slot at
    // one buffer per view; without this the scene would keep reading whichever
    // view was bound last, having uploaded its own camera to a buffer nothing reads.
    device_.setUniformBuffer(FRAME_CONSTANTS_BINDING, frameUbo_);
    // Re-arm the params fallback for this pass: a post-process or custom-draw
    // commit from the previous pass left its own (differently sized) buffer on
    // the shared slot.
    device_.setUniformBuffer(DRAW_PARAMS_BINDING, drawParamsFallback_);
}

void RenderContext::setFrameTime(f32 elapsedSec, u32 viewportW, u32 viewportH) {
    const f32 dt = (lastElapsed_ > 0.0f && elapsedSec > lastElapsed_) ? elapsedSec - lastElapsed_ : 0.0f;
    lastElapsed_ = elapsedSec;
    const f32 w = static_cast<f32>(viewportW);
    const f32 h = static_cast<f32>(viewportH);
    TimeConstants time{
        glm::vec4(elapsedSec, dt, viewExposure_, 0.0f),
        glm::vec4(w, h, w > 0.0f ? 1.0f / w : 0.0f, h > 0.0f ? 1.0f / h : 0.0f),
    };
    device_.updateBuffer(timeUbo_, 0, &time, sizeof(TimeConstants));

    // The backbuffer follows the viewport from the same size source the frame
    // clock carries: GL tracks the canvas implicitly (no-op), WebGPU
    // reconfigures its fixed-size swapchain when the size changes. Called at
    // the top of the frame, before any pass opens.
    device_.resizeBackbuffer(viewportW, viewportH);
}

}  // namespace esengine