Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
75 commits
Select commit Hold shift + click to select a range
4242aac
[MeshSdfPerformance_tests] Suppress compiler warning for deprecated f…
3dJan Apr 27, 2026
cef45b7
[MeshSdfPerformance_tests] Add environment variable check for GPU ben…
3dJan Apr 27, 2026
8a75c2b
Merge branch 'meshexport_memory_saving' of github.com:3dJan/gladius_p…
3dJan May 4, 2026
7abff65
Improving nanovdb based sdf queries
3dJan May 13, 2026
fca3910
always write newly allocated glimagebuffers to clear memory
3dJan May 13, 2026
54e4f6e
RealtimeRaymarchingController
3dJan May 14, 2026
f985242
Introduction of FramePresentationController
3dJan May 14, 2026
5d386f0
Frame presentation test coverage
3dJan May 14, 2026
fce5f8a
Improving renderupdatecoordinator
3dJan May 14, 2026
91b9470
improved state machine
3dJan May 14, 2026
96fc953
Fix UI preview and Auto realtime jitter during camera evaluation gaps
3dJan May 14, 2026
df58a78
Bug fix for AsyncRenderController
3dJan May 14, 2026
6c297db
updating spec for render update behavior
3dJan May 15, 2026
5d8d5af
[RenderWindow, RenderUpdateCoordinator, RenderModeUpdatePolicy] Refac…
3dJan May 15, 2026
a9ee9d2
[RenderUpdateCoordinator] Address Force mode parameter interaction is…
3dJan May 16, 2026
868565a
[RenderWindow, AsyncRenderController, FramePresentationController] Im…
3dJan May 16, 2026
7eef28f
[FramePresentationTypes.h, RenderUpdateCoordinator.h, RenderWorkflowC…
3dJan May 16, 2026
5192633
[DisplayFrameSelector] Add display frame selection logic and buffer s…
3dJan May 16, 2026
8b1cde8
[RenderWindow, RenderWorkflowController, PreviewResultAcceptancePolic…
3dJan May 16, 2026
f6d2446
[RenderWindow, DisplayFrameSelector, PreviewResultAcceptancePolicy] E…
3dJan May 16, 2026
288fd5c
[RenderWindow, InteractiveRenderPathPolicy, RenderModeUpdatePolicy, R…
3dJan May 16, 2026
0c92ed6
[RenderWindow, RenderModeUpdatePolicy, DisplayFrameSelector_tests] Re…
3dJan May 16, 2026
f4acd0a
[AsyncRenderController, RealtimeRaymarchController, RenderUpdateCoord…
3dJan May 16, 2026
560b68a
[RenderWindow, AsyncRenderController, RenderUpdateCoordinator] Refact…
3dJan May 16, 2026
f9a9291
[RenderWindow] Implement waitForEventBlocking to handle OpenCL event …
3dJan May 17, 2026
cef61b3
[GpuAccessCoordination] Add documentation for GPU access coordination…
3dJan May 17, 2026
270826d
[GpuAccessCoordinator] Implement GPU access coordination for resource…
3dJan May 17, 2026
395aa7b
[ComputeContext] Enable GPU access safe mode by default and remove en…
3dJan May 17, 2026
71da1ab
[Model] Enhance output port lookup to handle stale unique names and l…
3dJan May 21, 2026
15f88be
[RenderWindow] Refactor render decision logic to improve handling of …
3dJan May 25, 2026
9edeb19
[RenderWindow] Add m_asyncStaticFullFrameJobInFlight flag to manage p…
3dJan May 25, 2026
9cc886c
[ModelEditor] Extract example constants from library file and create …
3dJan May 25, 2026
d0056e5
[LibraryExampleExtractor] Add extraction functionality for example co…
3dJan May 25, 2026
32e4ece
[LibraryExampleExtractor] Add support for extracting matrix constants…
3dJan May 25, 2026
79cffca
[CMakeLists.txt] Add precompiled headers and increase MSVC heap size …
3dJan May 27, 2026
8744bf9
Merge branch 'rendering' into develop
3dJan May 27, 2026
c4371a9
Merge branch 'build_optimization_msvc' into develop
3dJan May 27, 2026
3f8692e
[CMakePresets.json] Reduce parallel build level to improve stability …
3dJan May 27, 2026
49c78ca
[Document] Improve non-blocking compilation checks and model refresh …
3dJan May 28, 2026
2b4b68f
[Importer3mf] Add boolean object processing and SDF generation method…
3dJan May 28, 2026
fc56c95
[CMakeLists.txt] Enhance MSVC build settings for Ninja generator and …
3dJan May 28, 2026
6e64bc7
[CLProgram] Enable OpenCL dump based on environment variables; improv…
3dJan May 28, 2026
a5a16ab
[CMakeLists.txt] Adjust precompiled header handling for non-Windows b…
3dJan May 28, 2026
80a8361
[Document] Ensure proper destruction by joining in-flight async worke…
3dJan May 30, 2026
2de8d8d
[RenderWindow] Add high-quality progressive render progress tracking …
3dJan May 30, 2026
21759ec
[OrbitalCamera] Introduce snapToTarget method to immediately apply ta…
3dJan May 30, 2026
b593222
[RenderWindow] Refactor render state checks and add view epoch tracki…
3dJan May 30, 2026
b13bc05
[ProgressiveTearReproduction_tests.cpp] Add unit tests for progressiv…
3dJan Jun 8, 2026
e7ef200
[RenderWindow] Adjust adaptive preview resize threshold percentage to…
3dJan Jun 9, 2026
dc72bbe
[OrbitalCamera] Increase tolerance value in update method to improve …
3dJan Jun 9, 2026
b804ee5
[Library] Add new 3D model files for mechanical components and primit…
3dJan Jun 12, 2026
47e07e0
[Library Extension] Add quick start guide, research findings, and fea…
3dJan Jun 14, 2026
28f80ce
[copilot-instructions.md] Add RTK (Rust Token Killer) command usage g…
3dJan Jun 22, 2026
0ef4acf
[ShellThicknessPartition] Add ShellThicknessPartition class for manag…
3dJan Jun 22, 2026
216ba64
[OpenVdbShellGenerator] Implement OpenVDB shell generator for constan…
3dJan Jun 22, 2026
b1603c7
[OpenVdbShellGenerator] Add variable shell signed distance evaluation…
3dJan Jun 23, 2026
93dac53
[PaletteExtractor] Refactor palette extraction to support multiple su…
3dJan Jun 23, 2026
a9f69bd
[ShellMaterialOrdering] Add ShellMaterialOrdering class for managing …
3dJan Jun 23, 2026
19e4815
[ColorToThicknessDialog] Update color conversion to use linear to sRG…
3dJan Jun 23, 2026
1937213
[manifold_dual_contouring.cl] Change inline functions to static inlin…
3dJan Jun 24, 2026
063a40d
[GpuAccessCoordinator] Refactor access check to use a reference for r…
3dJan Jun 26, 2026
377777c
[RenderWindow] Add camera idle time tracking for interaction end debo…
3dJan Jun 26, 2026
406113a
[RenderWindow] Update adaptive preview resize threshold from 0.5% to …
3dJan Jun 26, 2026
396d32d
[BeamLatticeView, ResourceView] Refactor resource deletion handling t…
3dJan Jun 27, 2026
8af3b0a
Impoved shell thickness solver + benchmark
3dJan Jun 28, 2026
7dda96b
Optimized shell ordering
3dJan Jun 28, 2026
7ff360e
[MainWindow] Implement Save As overwrite confirmation dialog and logic
3dJan Jul 3, 2026
42fabdb
[Document, Validator, IssueList] Add GraphSyncError type and update v…
3dJan Jul 11, 2026
4d75652
[CMakeLists.txt] Add warning as error flag for GCC/Clang and enable a…
3dJan Jul 11, 2026
ac73c2f
[GpuAccessCoordinator] Refactor access check logic to use current res…
3dJan Jul 11, 2026
7c19c92
[Document, Writer3mf, MainWindow] Implement asynchronous 3MF save fun…
3dJan Jul 11, 2026
ead2ac4
[Document, ComputeCore, ProgramManager, RenderSceneState, Writer3mf] …
3dJan Jul 11, 2026
040461e
[RenderSceneGeneration] Implement RenderSceneGeneration class to mana…
3dJan Jul 17, 2026
3d4fcad
[ModelEditor] Refactor argument iteration to improve readability and …
3dJan Jul 17, 2026
fd73156
[CMakeLists.txt] Simplify precompiled header handling for executable;…
3dJan Jul 18, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 45 additions & 2 deletions .github/copilot-instructions.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@

No explanations, just the code.

# C++ Coding Guidelines

Expand Down Expand Up @@ -87,4 +87,47 @@
- **FIXME**: Use `// FIXME: description` for known issues that need fixing.
- **Documentatioon**: Only add comments that add additional value. Avoid stating the obvious.

By following these guidelines, you can ensure clean, efficient, and maintainable C++ code.
By following these guidelines, you can ensure clean, efficient, and maintainable C++ code.

<!-- headroom:rtk-instructions -->
# RTK (Rust Token Killer) - Token-Optimized Commands

When running shell commands, **always prefix with `rtk`**. This reduces context
usage by 60-90% with zero behavior change. If rtk has no filter for a command,
it passes through unchanged — so it is always safe to use.

## Key Commands
```bash
# Git (59-80% savings)
rtk git status rtk git diff rtk git log

# Files & Search (60-75% savings)
rtk ls <path> rtk read <file> rtk grep <pattern>
rtk find <pattern> rtk diff <file>

# Test (90-99% savings) — shows failures only
rtk pytest tests/ rtk cargo test rtk test <cmd>

# Build & Lint (80-90% savings) — shows errors only
rtk tsc rtk lint rtk cargo build
rtk prettier --check rtk mypy rtk ruff check

# Analysis (70-90% savings)
rtk err <cmd> rtk log <file> rtk json <file>
rtk summary <cmd> rtk deps rtk env

# GitHub (26-87% savings)
rtk gh pr view <n> rtk gh run list rtk gh issue list

# Infrastructure (85% savings)
rtk docker ps rtk kubectl get rtk docker logs <c>

# Package managers (70-90% savings)
rtk pip list rtk pnpm install rtk npm run <script>
```

## Rules
- In command chains, prefix each segment: `rtk git add . && rtk git commit -m "msg"`
- For debugging, use raw command without rtk prefix
- `rtk proxy <cmd>` runs command without filtering but tracks usage
<!-- /headroom:rtk-instructions -->
49 changes: 49 additions & 0 deletions .serena/memories/library-best-practices.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# 3MF Library Best Practices

## What Makes a Good Library Item?

### Required Metadata
- **Name**: lower_snake_case, descriptive, no spaces or special chars except hyphens/underscores
- **Description**: One sentence explaining what the item does and key parameters
- **Tags**: Minimum 5 relevant keywords for discoverability (e.g., "primitive", "cone", "taper", "basic")
- **Tagged Function**: Exactly one function marked as tagged. Return type depends on purpose:
- `float shape` for SDF primitives/modifiers
- `vec3 result` for position transformations (symmetry, rotation, etc.)
- `vec3 color` for textures/materials
Comment on lines +5 to +12

### Code Quality
- Clean bounding box suitable for thumbnail rendering
- Well-named parameters with meaningful defaults where appropriate
- A `main` function demonstrating typical usage
- No duplicate function definitions (each name should have unique ID)
- Proper dependency ordering in program snippet

### Visual Appeal (for Thumbnails)
- Geometry fills 70-85% of thumbnail frame
- Isometric camera angle showing 3D form clearly
- Consistent lighting: directional light from upper-left, ambient fill
- Neutral background (light gray or white)
- Characteristic features visible at thumbnail size (256x256 minimum)

## Anti-Patterns to Avoid
- Empty entries (no description/tags/tagged functions)
- Missing tags on any entry
- Duplicate function names within same file
- Nearly duplicate entries (e.g., unionWithColor vs union_with_color)

## Naming Conventions
- Primitives: `sphere`, `cylinder`, `cone`, etc.
- Modifiers: `round`, `shell`, `offset` (verb-based)
- Operations: `polar_repetition`, `symmetryX` (noun-based with parameter suffix)
- Mechanical: `helix_spring`, `involute_gear` (compound nouns)

## Category Structure
```
primitives/ - Basic SDF shapes (sphere, cylinder, cone, etc.)
csg/ - Boolean operations (union, intersection, subtraction)
modifiers/ - Shape deformations (round, shell, offset)
operations/ - Domain transformations (symmetryX, polar_repetition)
lattices/ - Periodic structures (gyroid, honeycomb)
mechanical/ - Engineering parts (gear, spring, thread)
textures/ - Procedural textures (WoodTexture)
```
53 changes: 53 additions & 0 deletions docs/architecture/gpu_access_coordination.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
# GPU Access Coordination

Gladius uses multiple OpenCL command queues: one lazily-created queue per calling thread plus explicit worker queues for async rendering. OpenCL queues do not implicitly synchronize with each other, so shared buffers/images must be ordered explicitly.

## Core invariant

Every shared OpenCL memory-object access across queues must be ordered by one of:

1. an event wait list produced by `GpuAccessCoordinator`, or
2. an explicit host wait that is reported back to the coordinator.

Host-side mutexes are not sufficient unless they are held until the GPU command using the protected resource has completed.

## Main types

- `GpuAccessCoordinator` is the pure, GPU-free state model. It tracks resource IDs, generations, read/write leases, fake/production event IDs, stale generations, and deferred retirement.
- `OpenClEventRegistry` maps coordinator event IDs to `cl::Event` objects and polls or waits for completion.
- `GpuKernelAccessGuard` is the production RAII bridge. It begins one or more resource accesses, converts dependency IDs to OpenCL wait lists, and records the returned kernel event when the enqueue succeeds.
- `RenderPayloadSnapshot` captures the generation handles for the common render payload: primitive metadata, primitive data, precomputed SDF, parameter buffer, and command buffer.

## Published generations

Each `Buffer<T>` and `ImageImpl<T>` owns a stable coordinator resource ID and a current generation. Host writes, buffer reallocations, image reallocations, and clears retire the previous generation before mutating or releasing the backing OpenCL object.

A kernel launch should use the generation handles captured at launch time. If a later host write advances a generation, stale snapshots can be rejected instead of silently reading mixed old/new state.

## Conservative first-slice policy

The first implementation is whole-resource based:

- reads can overlap with reads;
- writes wait for previous readers and writers;
- reads wait for the previous writer;
- `Primitives::data` is tracked as one conservative resource even though it contains several logical regions;
- old generations are not released until known events have completed.

This is intentionally safer than region-level aliasing. Region-level optimization can be added later once workflow tests prove the invariants.

The current production rollout also prefers conservative generation retirement over immediate physical double-buffering. Host writes and reallocations wait for tracked readers/writers before mutating the backing object, so the implementation is safe even when only one physical buffer exists. Targeted double buffers can still be introduced later for performance/overlap (`PreComputedSdf`, `DistanceInitBuffer`, low-res preview images, and small parameter/command buffers), but they are no longer required to prevent cross-queue memory-object races.

## Safe mode

Guarded GPU access uses the conservative serialized mode by default. Each guarded launch drains tracked GPU work before enqueue and waits for its own returned event before returning. This is slower than maximally overlapping command queues, but it keeps the production behavior deterministic and avoids environment-dependent synchronization semantics.

## Adding a new kernel launch

1. Identify every shared OpenCL buffer/image argument.
2. Capture the relevant generation handles before enqueue.
3. Create a `GpuKernelAccessGuard` with read/write modes.
4. Pass `guard.waitEvents()` into `CLProgram::runNonBlockingWithWaitList(...)`.
5. Call `guard.complete(returnedEvent)` immediately after a successful enqueue.

If a launch cannot declare all shared resources yet, prefer a conservative whole-resource access over leaving the path untracked.
19 changes: 18 additions & 1 deletion gladius/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,21 @@ include(cmake/Coverage.cmake)
set(CMAKE_SKIP_INSTALL_ALL_DEPENDENCY OFF)

if (MSVC)
add_compile_options(/bigobj /utf-8 /Zc:__cplusplus)
# /Zm200 gives MSVC more internal compiler heap for large template-heavy translation units.
# Keep it global so executable-only sources such as the MCP tools get the same protection as libraries.
add_compile_options(/bigobj /utf-8 /Zc:__cplusplus /Zm200 /WX)

if(CMAKE_GENERATOR MATCHES "Ninja")
set(GLADIUS_MSVC_COMPILE_JOBS "2" CACHE STRING "Maximum concurrent MSVC compile jobs for Ninja builds")
set(GLADIUS_MSVC_HEAVY_COMPILE_JOBS "1" CACHE STRING "Maximum concurrent memory-heavy MSVC compile jobs for Ninja builds")

set_property(GLOBAL PROPERTY JOB_POOLS
gladius_msvc_compile_pool=${GLADIUS_MSVC_COMPILE_JOBS}
gladius_msvc_heavy_compile_pool=${GLADIUS_MSVC_HEAVY_COMPILE_JOBS}
gladius_msvc_link_pool=1)
set(CMAKE_JOB_POOL_COMPILE gladius_msvc_compile_pool)
set(CMAKE_JOB_POOL_LINK gladius_msvc_link_pool)
endif()

if (CMAKE_BUILD_TYPE STREQUAL "Debug")
add_compile_options(/RTC1)
Expand All @@ -123,6 +137,9 @@ if (MSVC)

# no console
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} /SUBSYSTEM:WINDOWS /ENTRY:mainCRTStartup")
else()
# Treat all compiler warnings as errors on GCC/Clang to keep the Linux build clean.
add_compile_options(-Werror)
endif()
add_definitions(-DTBB_SUPPRESS_DEPRECATED_MESSAGES -DNOMINMAX)

Expand Down
60 changes: 58 additions & 2 deletions gladius/CMakePresets.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,10 @@
"VCPKG_TARGET_TRIPLET": "x64-windows-gladius",
"VCPKG_OVERLAY_TRIPLETS": "${sourceDir}/vcpkg-triplets",
"VCPKG_OVERLAY_PORTS": "${sourceDir}/vcpkg-overlay-ports",
"CMAKE_BUILD_PARALLEL_LEVEL": "8",
"CMAKE_EXPORT_COMPILE_COMMANDS": "ON"
},
"environment": {
"CMAKE_BUILD_PARALLEL_LEVEL": "8"
}
},
{
Expand Down Expand Up @@ -111,7 +113,9 @@
"VCPKG_OVERLAY_PORTS": "${sourceDir}/vcpkg-overlay-ports",
"CMAKE_EXPORT_COMPILE_COMMANDS": "ON",
"ENABLE_COVERAGE": "OFF",
"ENABLE_TRACY": "TRUE",
"ENABLE_TRACY": "TRUE"
},
"environment": {
"CMAKE_BUILD_PARALLEL_LEVEL": "8"
}
},
Expand Down Expand Up @@ -154,6 +158,58 @@
}
],
"version": 3,
"buildPresets": [
{
"name": "x64-debug",
"displayName": "x64 Debug",
"configurePreset": "x64-debug",
"jobs": 2
},
{
"name": "x64-release",
"displayName": "x64 Release",
"configurePreset": "x64-release",
"jobs": 2
},
{
"name": "x64-release-debug",
"displayName": "x64 Release with Debug",
"configurePreset": "x64-release-debug",
"jobs": 2
},
{
"name": "x64-release-debug-asan",
"displayName": "x64 Release with Debug and ASAN",
"configurePreset": "x64-release-debug-asan",
"jobs": 2
},
{
"name": "x64-release-debug-noOpenCL",
"displayName": "x64 Release with Debug (No OpenCL Tests)",
"configurePreset": "x64-release-debug-noOpenCL",
"jobs": 2
},
{
"name": "linux-debug",
"configurePreset": "linux-debug",
"jobs": 8
},
{
"name": "linux-release",
"configurePreset": "linux-release",
"jobs": 8
},
{
"name": "linux-releaseWithDebug",
"configurePreset": "linux-releaseWithDebug",
"jobs": 8
},
{
"name": "linux-releaseWithDebug-noOpenCL",
"configurePreset": "linux-releaseWithDebug-noOpenCL",
"jobs": 8
}
],
"testPresets": [
{
"name": "ReleaseWithDebug",
Expand Down
Binary file added gladius/library/mechanical/helix_spring.3mf
Binary file not shown.
Binary file modified gladius/library/mechanical/involute_gear.3mf
Binary file not shown.
Binary file modified gladius/library/mechanical/iso_external_thread.3mf
Binary file not shown.
Binary file added gladius/library/mechanical/metric_nut.3mf
Binary file not shown.
Binary file added gladius/library/mechanical/socket_cap_screw.3mf
Binary file not shown.
Binary file added gladius/library/mechanical/tube.3mf
Binary file not shown.
Binary file added gladius/library/operations/polar_repetition.3mf
Binary file not shown.
Binary file added gladius/library/operations/twist.3mf
Binary file not shown.
Binary file added gladius/library/primitives/capsule.3mf
Binary file not shown.
Binary file added gladius/library/primitives/cone.3mf
Binary file not shown.
Binary file added gladius/library/primitives/cylinder.3mf
Binary file not shown.
Binary file added gladius/library/primitives/diamond.3mf
Binary file not shown.
Binary file added gladius/library/primitives/ellipsoid.3mf
Binary file not shown.
Binary file added gladius/library/primitives/hexagon.3mf
Binary file not shown.
Binary file added gladius/library/primitives/rounded_box.3mf
Binary file not shown.
Binary file added gladius/library/primitives/sphere.3mf
Binary file not shown.
Binary file added gladius/library/primitives/torus.3mf
Binary file not shown.
Binary file added gladius/library/primitives/triangular_prism.3mf
Binary file not shown.
Binary file added gladius/library/primitives/truncated_cone.3mf
Binary file not shown.
54 changes: 50 additions & 4 deletions gladius/src/Buffer.h
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
#include "ComputeContext.h"
#include <cmath>
#include <iostream>
#include <stdexcept>
#include <typeinfo>
#include <vector>

Expand All @@ -14,19 +15,31 @@ namespace gladius
public:
explicit Buffer(ComputeContext & context)
: m_ComputeContext(context)
, m_gpuResource(m_ComputeContext.gpuAccessCoordinator().registerResource(
GpuResourceKind::Buffer, typeid(T).name()))
{
}
Comment on lines 16 to 21

~Buffer()
{
// Release tracked bytes when buffer goes out of scope
if (m_buffer && m_size > 0)
try
{
m_ComputeContext.onBufferReleased(sizeof(T) * m_size);
// Release tracked bytes only after known GPU users have completed.
if (m_buffer && m_size > 0)
{
m_ComputeContext.waitForGpuResourceIdle(m_gpuResource);
m_ComputeContext.onBufferReleased(sizeof(T) * m_size);
}
}
catch (...)
{
// Destructors must not throw.
}
}
Buffer(Buffer const & other)
: m_ComputeContext(other.m_ComputeContext)
, m_gpuResource(m_ComputeContext.gpuAccessCoordinator().registerResource(
GpuResourceKind::Buffer, typeid(T).name()))
, m_data(other.m_data)
{
create();
Expand All @@ -44,6 +57,7 @@ namespace gladius
{
throw std::runtime_error("Failed to read, device buffer could not be created");
}
m_ComputeContext.waitForGpuResourceIdle(m_gpuResource);
m_data.resize(m_size);
CL_ERROR(m_ComputeContext.GetQueue().enqueueReadBuffer(
*m_buffer.get(), CL_TRUE, 0, sizeof(T) * m_size, &m_data[0]));
Expand All @@ -59,6 +73,7 @@ namespace gladius
// If there was a previous allocation, release its accounting first
if (m_buffer && m_size > 0)
{
retireCurrentGpuGeneration();
m_ComputeContext.onBufferReleased(sizeof(T) * m_size);
}

Expand All @@ -73,6 +88,7 @@ namespace gladius
m_data.clear();
if (m_buffer && m_size > 0)
{
retireCurrentGpuGeneration();
m_ComputeContext.onBufferReleased(sizeof(T) * m_size);
}
m_size = 0;
Expand All @@ -95,6 +111,7 @@ namespace gladius
throw std::runtime_error("Failed to write, device buffer could not be created");
}

retireCurrentGpuGeneration();
CL_ERROR(m_ComputeContext.GetQueue().enqueueWriteBuffer(
*m_buffer.get(), CL_TRUE, 0, sizeof(T) * m_data.size(), &m_data[0]));

Expand Down Expand Up @@ -139,10 +156,39 @@ namespace gladius
return *m_buffer.get();
}

[[nodiscard]] GpuResourceHandle gpuResourceHandle() const noexcept
{
return m_gpuResource;
}

private:
void retireCurrentGpuGeneration()
{
m_ComputeContext.waitForGpuResourceIdle(m_gpuResource);

auto retirement = m_ComputeContext.gpuAccessCoordinator().retireCurrentGeneration(
m_gpuResource.resourceId);
if (retirement.status == GpuAccessStatus::PendingAccessWithoutEvent)
{
m_ComputeContext.waitForGpuResourceIdle(m_gpuResource);
retirement = m_ComputeContext.gpuAccessCoordinator().retireCurrentGeneration(
m_gpuResource.resourceId);
}

if (!retirement.granted())
{
throw std::runtime_error("Failed to retire GPU buffer generation safely");
}

m_ComputeContext.waitForGpuEvents(retirement.waitEvents);
m_ComputeContext.gpuAccessCoordinator().collectCompletedRetirements();
m_gpuResource = retirement.newGeneration;
}

ComputeContext & m_ComputeContext;
GpuResourceHandle m_gpuResource{};
std::vector<T> m_data;
size_t m_size = 0;
ComputeContext & m_ComputeContext;
std::unique_ptr<cl::Buffer> m_buffer;
};
}
Loading
Loading