CV<AdrianYip>::DevLog::get<HackWestern>()
::desc<"Hack Western: ReCast">
::date<2026.11.22>
::project<ReCast>
::stack<Vulkan 1.3, C++20, GLSL, Python>;


Over the past weekend, me, Kaitlyn, and Darren attended Hack Western and got 2nd place overall! Our project, ReCast, lets you take an object from one photo and put it into another photo, with the lighting and shadows matching the scene. I wrote the Vulkan rendering engine, which path traces the object into the photo in real time.

What did we make and why

You pick a scene photo and an object photo, draw a box around the object, and drag it into the scene. Behind that, we rebuild the scene as a rough 3D room, guess where the lights are, turn the object into a 3D mesh, and path trace it into the photo with its shadows and reflections. You can still move, rotate and resize it by hand, switch back to the original photo to compare, and export the result at full resolution.

You can do this in Photoshop, but it's slow and pretty hard to get right, and GenAI is hard to control too. If the object isn't exactly where you want it, you have to send another prompt and hope the next result is closer, and it can lose details in the scene each time. We wanted something lighter, where you just drag the object around.

Moving the glass dragon around the scene
The original scene photo: benches and a small table by a sunlit window with long shadows on a concrete floor The same photo exported from ReCast with a Hack Western light-up sign on the left bench, a wet floor sign on the floor, and a water bottle on the right bench, each casting shadows that match the sun
Left: the original photo. Right: exported from ReCast with the Hack Western sign, the wet floor sign, and the bottle inserted

Like at HTN, the C++ and Python sides talk through files. Python writes out a scene folder and the engine reloads it whenever something in it changes:

// the scene folder, the connection between the two sides
data/<scene_name>/
  scene.json     camera, proxies, lights, SH    (Python, engine adds lights)
  photo.jpg      undistorted scene photo, sRGB  (Python)
  object.glb     the object, metres, +Y up      (Python)
  masks/         one cutout per detected object (Python)
  render.jpg     final composite                (engine)

Vulkan 1.3

Living NPC and RATH both use Vulkan 1.0 (VK_API_VERSION_1_0) because that's what the Vulkan tutorial uses. For ReCast I wanted to try 1.3 instead, since pretty much every Vulkan engine coding video I'd been watching on YouTube was using it. When it picks a GPU, it checks for the 1.2 and 1.3 features it needs:

// vkDevice.cpp - selectPhysicalDevice()
VkPhysicalDeviceVulkan12Features features12 = {
    .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES
};
VkPhysicalDeviceVulkan13Features features13 = {
    .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES,
    .pNext = &features12
};
VkPhysicalDeviceFeatures2 features2 = {
    .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2,
    .pNext = &features13
};
vkGetPhysicalDeviceFeatures2(device, &features2);
if (!features13.dynamicRendering || !features13.synchronization2) {
    reject("no dynamic rendering or synchronization2");
    continue;
}

Dynamic Rendering

With dynamic rendering I didn't have to make any VkRenderPass or VkFramebuffer objects. At HTN I had two render passes, one for the main scene (with an MSAA resolve) and one for shadows, and each one needed attachment descriptions, references, a subpass and a dependency before I could even make a pipeline:

// HTN pipeline.cpp - part of the main render pass
VkSubpassDescription subpass{};
subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
subpass.colorAttachmentCount = 1;
subpass.pColorAttachments = &colorAttachmentRef;
subpass.pDepthStencilAttachment = &depthAttachmentRef;
subpass.pResolveAttachments = &colorResolveRef;
// ...plus 3 attachment descriptions, a subpass dependency,
// a VkRenderPassCreateInfo, and a framebuffer per swapchain image

Now the pipeline only needs to know what formats it draws to. You pass the actual images in when you record the command buffer, so each pass is just a vkCmdBeginRendering call:

// vkPipeline.cpp - pipeline creation with dynamic rendering
VkPipelineRenderingCreateInfo renderingCreateInfo = {
    .sType = VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO,
    .colorAttachmentCount = hasColor ? 1u : 0u,
    .pColorAttachmentFormats = hasColor ? &config.colorFormat : nullptr,
    .depthAttachmentFormat = config.depthFormat,
};

// vkRender.cpp - the scene pass into the HDR target
VkRenderingAttachmentInfo hdrAttachment = {
    .sType = VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO,
    .imageView = hdrImage->getView(),
    .imageLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
    .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR,
    .storeOp = VK_ATTACHMENT_STORE_OP_STORE,
};
VkRenderingInfo sceneRendering = {
    .sType = VK_STRUCTURE_TYPE_RENDERING_INFO,
    .renderArea = { .offset = {0, 0}, .extent = extent },
    .layerCount = 1,
    .colorAttachmentCount = 1,
    .pColorAttachments = &hdrAttachment,
    .pDepthAttachment = &depthAttachment,
};
vkCmdBeginRendering(commandBuffer, &sceneRendering);

This helped a lot because I kept adding passes all weekend, and by the end it had two shadow passes, the scene pass, the path tracer, caustics, four denoise passes and the tonemap, and I never had to make a render pass or framebuffer for any of them.

Synchronization2

Without a render pass handling layout transitions, I had to write a barrier for every one. I used synchronization2, which puts the stage and access masks inside the barrier struct. I think it's a lot easier to read than the old version, especially when the same image goes between compute and graphics in one frame:

// vkRender.cpp - barrier between the path tracer and the tonemap pass
VkImageMemoryBarrier2 hdrToSampled = {
    .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2,
    .srcStageMask = VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT,
    .srcAccessMask = VK_ACCESS_2_SHADER_STORAGE_WRITE_BIT,
    .dstStageMask = VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT,
    .dstAccessMask = VK_ACCESS_2_SHADER_SAMPLED_READ_BIT,
    .oldLayout = VK_IMAGE_LAYOUT_GENERAL,
    .newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
    .image = hdrImage->getImage(),
    .subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1},
};
VkDependencyInfo afterTrace = {
    .sType = VK_STRUCTURE_TYPE_DEPENDENCY_INFO,
    .imageMemoryBarrierCount = 1,
    .pImageMemoryBarriers = &hdrToSampled
};
vkCmdPipelineBarrier2(commandBuffer, &afterTrace);

Bindless Textures and Materials

At HTN every draw call had a push constant struct with 15 fields in it, mostly offsets so the shader could find its data in the shared buffers. For ReCast I used descriptor indexing, so every texture goes into one big sampler2D array and every material goes into one storage buffer. Now a draw only pushes its model matrix, a material index and a tint:

// common.glsl - shared by every shader
struct Material {
    vec4 baseColor;
    vec4 emissive;
    float roughness;
    float metallic;
    uint baseColorTexture; // slot in textures[]
    float specular;
    float transmission;
    float ior;
    // ...
};

layout(std430, set = 0, binding = 1) readonly buffer Materials {
    Material materials[];
};

// Set per GPU by the pipelines (1024 unless the GPU can't bind that many)
layout(constant_id = 0) const uint TEXTURE_CAPACITY = 1024;
layout(set = 0, binding = 2) uniform sampler2D textures[TEXTURE_CAPACITY];

layout(push_constant) uniform Push {
    mat4 model;
    uint materialIndex;
    vec4 tint;
} push;

This made the path tracer a lot easier to write later. When a ray hits a mesh, the shader looks up its material and texture from one index. The size of the texture array is a specialization constant, which comes up again in the debugging section.

Architecture Differences

At HTN I added things to the engine whenever the demo needed them. By the end Device had the swapchain, the depth and MSAA images and the command pool, and the ~830 line Renderer did pretty much everything else. Objects were also made with a create function that writes into an output pointer, which I had carried over from RATH:

// HTN renderer.cpp
Model::createModel(device, std::move(fmodel), &model);

The problem is that the Model exists before it's actually created. Its members have to be pointers, and nothing stops you from using one that was never set up. For ReCast I split things into an engine library and a sandbox that holds the actual project code:

engine/
  platform/     Window (GLFW, input, delta time)
  rhi_vulkan/   Device, Swapchain, Pipeline, Render, Buffer, Image,
                Mesh, AccelerationStructure, descriptor helpers
  assets/       glTF loading (cgltf)
  scene/        Camera
  ui/           ImGui layer
  app/          Application, the only thing the sandbox talks to
sandbox/
  visualizer    ReCast itself: photo view, dragging, lighting, UI
  lighting/     light detection and camera matching
  scene/        scene.json, proxies, picking, placement

RAII

This time every Vulkan wrapper is fully set up by its constructor. Each member comes from a static function that uses the members before it. Things get created in the order of the initializer list and destroyed in reverse automatically:

// vkDevice.cpp - Device constructor
foto::Device::Device(GLFWwindow* window) :
    instance(createInstance()),
    debugMessenger(createDebugMessenger(instance)),
    surface(createSurface(instance, window)),
    physicalDevice(selectPhysicalDevice(instance, surface)),
    queueInfos(findQueueFamilies(physicalDevice, surface).value()),
    rayTracing(rayTracingSuitable(physicalDevice)),
    textureBinding(chooseTextureBinding(physicalDevice)),
    logicalDevice(selectLogicalDevice(physicalDevice, queueInfos,
                                      rayTracing, textureBinding))
{ /* get queues, load ray tracing function pointers */ }

I don't need an init() function anymore, which I'm really happy about since there's no half created object to accidentally use. I use std::unique_ptr for ownership, references for things that always exist, and raw pointers only when something is optional, like the path trace pipeline being nullptr on GPUs that can't ray trace.

The Application API

The sandbox code never calls Vulkan directly. Application runs the main loop, and the sandbox overrides a few virtual functions and uses a small set of functions for making resources and drawing:

// application.hpp (trimmed)
class Application {
public:
    Application(const ApplicationConfig& config);
    void run();

protected:
    virtual void onInit() {}
    virtual void onUpdate(f32 deltaTime) {}
    virtual void onImGui() {}
    virtual void onShutdown() {}

    Mesh* loadModel(const std::string& filePath);
    u32 loadTextureHDR(const std::string& filePath);
    u32 createMaterial(const Material& material);
    Pipeline* createPipeline(GraphicsPipelineConfig config);

    // Queues a draw for the current frame; call from onUpdate
    void draw(Mesh* mesh, const enginemath::Mat4& transform,
              u32 materialOverride = NO_MATERIAL_OVERRIDE,
              Pipeline* pipeline = nullptr,
              ShadowCaster shadowCaster = ShadowCaster::None, ...);

    void setLights(std::span<const Light> lights);
    void setPathTracing(bool enabled, u32 photoMaterial);
    bool exportImage(const std::string& pngPath, const std::string& hdrPath,
                     u32 width, u32 height, u32 samples);
};

draw() just adds a DrawItem to a list, and at the end of the frame Render::drawFrame gets the whole list as a std::span. Because it sees the whole frame at once, the renderer can pick raster or path tracing on its own. The ShadowCaster on each draw tells it which meshes belong to the room in the photo and which one is the object we inserted:

// visualizer.cpp - onUpdate (trimmed)
for (u32 i = 0; i < proxyMeshes.size(); i++)
    draw(proxyMeshes[i], matrix, proxyAlbedoMaterials[i], nullptr,
         foto::ShadowCaster::Static);
draw(objectMesh, objectTransform(i), foto::NO_MATERIAL_OVERRIDE, nullptr,
     foto::ShadowCaster::Dynamic);
setPathTracing(pathTrace && !showOriginal && supportsPathTracing(), photoMaterial);

I did the same thing for pipelines with a GraphicsPipelineConfig struct that has defaults for everything, so making a fullscreen pass or a depth only pass is a few lines instead of copying a 100 line function.

C++20

Living NPC used C++17, and for ReCast I switched to C++20 from the first commit. I mostly just wanted designated initializers. Almost everything in Vulkan is filling in a struct and passing a pointer to it, and in C++17 you have to make an empty struct and set each field one line at a time:

// HTN device.cpp - C++17
VkApplicationInfo appInfo{};
appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
appInfo.pApplicationName = "Living NPC";
appInfo.applicationVersion = HTN_VERSION;
appInfo.pEngineName = "Living NPC Vulkan Engine";
appInfo.engineVersion = HTN_VERSION;
appInfo.apiVersion = VK_API_VERSION_1_0;
// vkDevice.cpp - C++20
VkApplicationInfo appInfo = {
    .sType = VK_STRUCTURE_TYPE_APPLICATION_INFO,
    .pApplicationName = "Photo Visualizer Software",
    .applicationVersion = VK_MAKE_VERSION(1, 0, 0),
    .pEngineName = "Vulkan Custom Engine",
    .engineVersion = VK_MAKE_VERSION(1, 0, 0),
    .apiVersion = VK_API_VERSION_1_3
};

In C++20 I can fill the whole struct in at once, make it const, pass it straight into a function, or return it from a helper. The Device constructor above relies on that. Any field I don't name is zeroed. This helped most with the ray tracing structs, which nest three or four levels deep.

I also ended up using std::span a lot. Meshes, lights, acceleration structure instances and the draw list all get passed as std::span<const T>, and I didn't need the pointer and count pairs I had at HTN.

Rebuilding the Scene

The path tracer needs actual geometry to hit, so the first step is turning the scene photo into a rough 3D room. Phone lenses bend straight lines a bit, and the photo gets undistorted with lensfun[1] first. Then RANSAC groups the straight edges into three vanishing points, which gives the camera's focal length and rotation. It's basically the Hartley and Zisserman[2] method, which is the same thing fSpy does. The floor is the plane y = 0.

Depth

We run two pretrained models locally. OneFormer[3] labels each part of the photo as floor, wall, or a type of furniture, and Depth Anything V2[4] estimates depth for every pixel. Depth Anything's output doesn't actually have real units, but on the floor we already know the real depth from the solved camera, so I fit the model's output to the real floor depth with least squares (throwing out outliers each round) and then used that fit for the rest of the image:

# detect.py - depth_to_metres(): disparity = a / z + b, fit on the floor
t_floor = -cam.position[1] / rays[..., 1]   # ray hits y = 0
z_floor = t_floor * cos
x = 1.0 / z_floor[use]
y = disparity[use]
for _ in range(4):                          # least squares, dropping outliers
    A = np.column_stack([x[keep], np.ones(keep.sum())])
    (a, b), *_ = np.linalg.lstsq(A, y[keep], rcond=None)
    res = y - (a * x + b)
    mad = np.median(np.abs(res[keep])) + 1e-9
    keep = np.abs(res) < 3.0 * 1.4826 * mad
inv_z = (disparity - b) / a                 # every pixel, now in metres

Boxes to Convex Hulls

Each piece of furniture becomes a proxy mesh that the path tracer can actually hit. At first these were just axis aligned boxes around each object's points, which worked badly for round furniture. The box around a swivel chair sticks out way past the actual chair, so the object you were dragging would bump into empty space, and the corners of the box showed up in the shadows, which looked pretty bad.

Left: the scene photo with each detected object coloured and labelled (swivel chair, chair, table, ledge, pillar, sofa). Right: the same photo with the fitted proxy meshes drawn as magenta wireframes and the wall lines in blue
Left: OneFormer's labels. Right: the proxy meshes fitted to each object and the walls
The proxies in the engine's edit room view, where a wrong one can be dragged or resized by hand

I changed them to convex hulls around each object's 3D points. The photo only shows the front of things, so if the camera can't see the top I mirror the points through the middle of the box to fake the back. I also check if the furniture is on legs or a pedestal (the bottom 30% is much narrower or has very few points). If it is, I leave the legs out so light can get underneath:

# detect.py - shape_hull()
open_below = (may_stand_on_legs and 0 < low.sum() and (~low).sum() >= 50 and
              (spread(points[low]) < 0.35 * spread(points[~low])
               or low.sum() < 0.1 * len(points)))
if open_below:
    points = points[~low]
if not top_seen:                     # only its front is seen: mirror for the back
    centre = 0.5 * (lo + hi)
    mirrored = points.copy()
    mirrored[:, [0, 2]] = 2.0 * centre[[0, 2]] - points[:, [0, 2]]
    points = np.vstack([points, mirrored])
if not open_below:                   # add a base so it sits on the floor
    base = points.copy()
    base[:, 1] = lo[1]
    points = np.vstack([points, base])
hull = ConvexHull(np.clip(points, lo, hi))

Convex hulls were better but still basically fill in anything concave, like the space above a seat or between two armrests. For the final version I carve the shape out of a voxel grid instead. A voxel stays only if it's inside the object's cutout and behind the surface the photo sees there. Marching cubes turns that back into a mesh, and I simplify it to about 600 triangles because the light fitting tests against them on the CPU.

Turning the Object into 3D

For the object, we start from a single photo and turn it into a textured glTF mesh. The user draws a box around the object in ReCast, and SAM[5] (ViT-B) uses that box to cut it out with soft edges:

Drawing a box around the object

TripoSR[6] then predicts a 3D shape from the cutout, marching cubes turns that into a mesh, and I simplify it down to 10k faces since every triangle ends up in the path tracer's acceleration structure.

xatlas[7] unwraps the mesh and the texture gets baked from the photo wherever the surface was facing the camera. That texture still has the original photo's lighting in it though, and the engine would end up lighting it a second time. To remove it, I fit order 1 spherical harmonics over the surface normals (Ramamoorthi and Hanrahan[8]), which models brightness as c0 + c · n, and divide that out:

# generated.py - delight()
lum = colors_linear @ np.array([0.2126, 0.7152, 0.0722])
A = np.column_stack([np.ones(len(normals)), normals])   # [1, nx, ny, nz]
keep = lum > 1e-4
for _ in range(3):
    coef, *_ = np.linalg.lstsq(A[keep], lum[keep], rcond=None)
    res = lum - A @ coef
    mad = np.median(np.abs(res[keep])) + 1e-6
    keep = (lum > 1e-4) & (np.abs(res) < 3.0 * 1.4826 * mad)
shading = A @ coef
ratio = np.clip(shading / max(float(np.mean(shading[keep])), 1e-6), 0.5, 2.0)
return np.clip(colors_linear / ratio[:, None], 0.0, 1.0), coef

The ratio is clamped so a bad fit doesn't ruin the texture. TripoSR also assumes the camera was level, so a bottle photographed from above comes out leaning back. upright() fixes this by slicing the mesh horizontally, fitting a line through the centre of each slice, and rotating that line to vertical. We also keep a Python worker running in the background with the models already loaded. That cut making an object from about 45 s to about 20 s.

A photo of large white light-up H and W letters standing against a wood panel wall
The photo used to make the Hack Western sign object

Path Tracing

Acceleration Structures

Ray tracing support is optional, and if a GPU doesn't have it the engine falls back to the raster renderer. Every mesh gets a bottom level acceleration structure (BLAS) when it's created, with one geometry per submesh so I can tell which material a ray hit. I pass the vertex and index buffers in by device address:

// vkAccel.cpp - buildBottomLevel()
VkAccelerationStructureGeometryTrianglesDataKHR triangles = {
    .sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_TRIANGLES_DATA_KHR,
    .vertexFormat = VK_FORMAT_R32G32B32_SFLOAT,
    .vertexData = { .deviceAddress = vertices.getDeviceAddress() },
    .vertexStride = sizeof(Vertex),
    .maxVertex = vertexCount - 1,
    .indexType = VK_INDEX_TYPE_UINT32,
    .indexData = { .deviceAddress = indices.getDeviceAddress() },
};
for (const Submesh& submesh : submeshes) {
    geometries.push_back({ ... .geometry = { .triangles = triangles } ... });
    ranges.push_back({ .primitiveCount = submesh.indexCount / 3,
                       .primitiveOffset = submesh.firstIndex * sizeof(u32) });
}

The top level structure (TLAS) gets rebuilt every frame because the object moves while you drag it. The room proxies get cull mask 1 and the object gets mask 2, so a ray can be traced against just the room, just the object, or both.

Ray Queries in a Compute Shader

I went with ray queries in a compute shader instead of a full ray tracing pipeline. I didn't want to deal with a shader binding table at all, and this way the whole path tracer is one vkCmdDispatch that sits next to the caustics and denoise passes, which are compute shaders too. When a ray hits something, the shader reads that triangle's vertices straight out of the mesh buffers using buffer_reference pointers:

// trace.glsl - traceClosest()
rayQueryEXT query;
rayQueryInitializeEXT(query, scene, gl_RayFlagsOpaqueEXT, mask,
                      origin, 1e-4, direction, 1e30);
while (rayQueryProceedEXT(query)) {}

Geometry geometry = geometries[rayQueryGetIntersectionInstanceCustomIndexEXT(query, true)
                             + rayQueryGetIntersectionGeometryIndexEXT(query, true)];
Indices indices = Indices(geometry.indexAddress);
Floats vertices = Floats(geometry.vertexAddress);
uint first = geometry.firstIndex
           + 3u * uint(rayQueryGetIntersectionPrimitiveIndexEXT(query, true));

vec2 barycentrics = rayQueryGetIntersectionBarycentricsEXT(query, true);
vec3 weights = vec3(1.0 - barycentrics.x - barycentrics.y, barycentrics.x, barycentrics.y);
for (uint k = 0u; k < 3u; k++) {
    uint v = indices.i[first + k] * VERTEX_FLOATS;
    normal += weights[k] * vec3(vertices.f[v + 3u], vertices.f[v + 4u], vertices.f[v + 5u]);
    uv     += weights[k] * vec2(vertices.f[v + 6u], vertices.f[v + 7u]);
}

Differential Rendering

The room itself never gets relit. The proxies are too rough and their materials are basically guesses, so rendering the room from scratch would look nothing like the photo. Instead I followed Debevec[9] and Karsch[10]. Each room pixel is the photo times how much the object changes the light reaching it. The shader works out the light at that point twice, once with only the room and once with everything, and divides them:

// pathtrace.comp - radiance() for a room pixel
vec3 withoutObjects = frame.ambient.rgb
                    + directIrradiance(hit.position, hit.normal, MASK_STATIC, lightSeed);
vec3 withObjects = ambientLight(hit.position, hit.normal, state, lightSeed)
                 + directIrradiance(hit.position, hit.normal, MASK_ALL, lightSeed)
                 + causticIrradiance(pixel, hit, direction);
light = withObjects / max(withoutObjects, vec3(1e-4));
return photo * light;

Both versions use the same random samples, so anywhere the object doesn't block or bounce any light the ratio comes out to exactly 1, and the photo shows through without noise. The object itself uses GGX for gloss, reflects the photo, refracts it if it's glass, and there's a separate photon pass from the lights for caustics.

The wet floor sign's shadow lining up with the benches' real shadows while it is dragged
An indoor seating area by a large window with a glass red dragon inserted on the left and a plastic water bottle inserted on the table
The glass dragon (Khronos sample asset) and a water bottle made from a photo, inserted into a scene

Accumulation and Denoising

While nothing moves, samples accumulate over frames. To know when to start over, the renderer builds a key each frame from the frame uniforms and every shadow casting draw. If the key changes, the count resets. I leave exposure out, since changing it doesn't need new samples:

// vkRender.cpp - updateTraceSamples()
FrameUbo keyUbo = frameUbo;
keyUbo.exposure = {};
keyUbo.whiteBalance = {};
std::vector<u8> key(sizeof(FrameUbo) + sizeof(u32) * 4);
std::memcpy(key.data(), &keyUbo, sizeof(FrameUbo));
// ...photo, materials version, owner and depth textures
for (const DrawItem& item : items) {
    if (!item.mesh || item.shadowCaster == ShadowCaster::None) continue;
    append(&item.mesh, sizeof(item.mesh));
    append(&item.transform, sizeof(item.transform));
    append(&item.materialOverride, sizeof(item.materialOverride));
}
if (key != traceKey) {
    traceKey = std::move(key);
    traceSamples = 0;
}

When you're dragging there's only ever one sample though, so it looks really grainy. For that I implemented the spatial part of SVGF[11], which is four edge aware à-trous passes that use each pixel's normal and depth so they don't blur across edges. It blurs less as more samples come in, since it's based on the variance of the samples so far.

Lights from the Photo

Lights come from the photo too, since I really didn't want people to have to place them by hand. The detection models each room pixel as albedo × (ambient + Σ intensity × geometry × visibility). With the light positions fixed this is linear, and the intensities come from least squares. To find positions, it starts from the brightest spots in the photo plus a grid, and only adds another light if it lowers the error by at least 5%. Each light's size comes from a golden section search on how soft the shadow edges in the photo are.

The object also has to look like it was taken with the same camera. The engine measures the photo's grain with Immerkær's method[12] and its blur from how wide its edges are, then adds the same blur and grain to only the parts the object changed.

Issues and Debugging

Shadow Map Seams

The first version was raster with cube shadow maps. Normally the seams between cube faces are hard to notice, but differential rendering divides the version with the object by the version without it, so any tiny difference shows up as a bright line across the shadow. Traced shadows don't have seams, which is why the path tracer became the default. The raster version is still there as a fallback.

GPUs that can't bind 1024 textures

I originally hard coded 1024 bindless textures, which was fine on my RTX 5060 but just didn't work on Intel integrated graphics. Now the device checks the normal limit, then the update-after-bind limit, uses whichever one is bigger, and passes it into the shaders as TEXTURE_CAPACITY:

// vkDevice.cpp - chooseTextureBinding()
u32 regular = std::min({ limits.maxPerStageDescriptorSamplers,
                         limits.maxPerStageDescriptorSampledImages,
                         limits.maxDescriptorSetSamplers,
                         limits.maxDescriptorSetSampledImages });
if (regular >= MAX_TEXTURES) return { MAX_TEXTURES, false };

if (features12.descriptorBindingSampledImageUpdateAfterBind) {
    u32 updateAfterBind = std::min({ /* the UpdateAfterBind versions */ });
    if (updateAfterBind > regular) return { std::min(updateAfterBind, MAX_TEXTURES), true };
}
return { regular, false };

Removing the Light Editor

Around halfway through, the app had a light editor, sliders for every light, a local calibration toggle, white balance and a demo mode. Adding a light only ever changed the object, the sliders were hard to use, and local calibration made the whole object change brightness while you dragged it over the checkered test floor. It felt overengineered, so I took all of it out and made the lighting fully automatic.

Near the end I added a smaller version back for when the detection gets it wrong. Turning on "Edit lights" shows the lights as markers you can drag around, and you can change brightness, turn a light into a sun, or reset back to what was detected.

Moving a light in edit lights mode

What's Next

I'm pretty happy with how this engine turned out compared to HTN and RATH. RATH is still on Vulkan 1.0 with render passes, and it's gotten messy as it grew, so I'll probably use the engine/ half of ReCast as the starting point for refactoring RATH. That would bring the path tracer and ray queries over too.

Overall Thoughts

This was my third hackathon. At HTN I mainly wanted to try out the JALI and S3 papers, and this time I wanted to see if I could build a Vulkan 1.3 engine properly from the start and get hardware ray tracing working in it. I didn't think we'd actually end up with caustics and a denoiser too by the end of the weekend.


GitHub


References

  1. lensfun - lens correction database and library
  2. Multiple View Geometry in Computer Vision - Hartley, Zisserman
  3. OneFormer: One Transformer to Rule Universal Image Segmentation - Jain et al. (CVPR 2023)
  4. Depth Anything V2 - Yang et al. (NeurIPS 2024)
  5. Segment Anything - Kirillov et al. (ICCV 2023)
  6. TripoSR: Fast 3D Object Reconstruction from a Single Image - Tochilkin et al. (2024)
  7. xatlas - mesh parameterization and UV atlas generation
  8. An Efficient Representation for Irradiance Environment Maps - Ramamoorthi, Hanrahan (SIGGRAPH 2001)
  9. Rendering Synthetic Objects into Real Scenes - Debevec (SIGGRAPH 1998)
  10. Rendering Synthetic Objects into Legacy Photographs - Karsch, Hedau, Forsyth, Hoiem (SIGGRAPH Asia 2011)
  11. Spatiotemporal Variance-Guided Filtering - Schied et al. (HPG 2017)
  12. Fast Noise Variance Estimation - Immerkær (CVIU 1996)

Assets

  1. DragonAttenuation from the Khronos glTF Sample Assets, based on the Stanford Dragon
  2. cgltf - single-file glTF loader by Johannes Kuhlmann
  3. enginemath - custom math library