|
| 1 | +// |
| 2 | +// Created by Marc Rousavy on 23.02.24. |
| 3 | +// |
| 4 | + |
| 5 | +#pragma once |
| 6 | + |
| 7 | +#include <filament/Engine.h> |
| 8 | +#include <functional> |
| 9 | +#include <memory> |
| 10 | + |
| 11 | +namespace margelo { |
| 12 | + |
| 13 | +template <typename T> struct References { |
| 14 | +public: |
| 15 | + using CleanupRefFunction = std::function<void(T* ref)>; |
| 16 | + using CleanupEngineRefFunction = std::function<void(std::shared_ptr<filament::Engine> engine, T* ref)>; |
| 17 | + |
| 18 | + struct Deleter { |
| 19 | + public: |
| 20 | + explicit Deleter(const CleanupRefFunction& cleanup) : _cleanup(std::move(cleanup)) {} |
| 21 | + void operator()(T* ref) { |
| 22 | + _cleanup(ref); |
| 23 | + } |
| 24 | + |
| 25 | + private: |
| 26 | + CleanupRefFunction _cleanup; |
| 27 | + }; |
| 28 | + |
| 29 | + /** |
| 30 | + * Adopt a raw reference to T and take over it's memory ownership. |
| 31 | + * When the resulting `shared_ptr` is deleted, `cleanup` will be called with the reference to T, and the caller is expected to properly |
| 32 | + * clean up T. |
| 33 | + * @param value The raw reference to T that will be adopted. |
| 34 | + * @param cleanup The function to run when the shared_ptr's ref count reaches zero. The caller is expected to delete the reference to T |
| 35 | + * here. |
| 36 | + * @return A shared_ptr safely managing the reference to T. |
| 37 | + */ |
| 38 | + static std::shared_ptr<T> adoptRef(T* value, const CleanupRefFunction& cleanup) { |
| 39 | + return std::shared_ptr<T>(value, Deleter(std::move(cleanup))); |
| 40 | + } |
| 41 | + |
| 42 | + /** |
| 43 | + * Same as `adoptRef(T*, CleanupRefFunction)`, but with an additional argument: `Engine`. |
| 44 | + * This is used to clean up children of `Engine`, e.g. via `Engine::destroy(Renderer)`. |
| 45 | + */ |
| 46 | + static std::shared_ptr<T> adoptEngineRef(const std::shared_ptr<filament::Engine>& engine, T* value, CleanupEngineRefFunction cleanup) { |
| 47 | + return adoptRef(value, [engine = std::move(engine), cleanup = std::move(cleanup)](T* ref) { cleanup(engine, ref); }); |
| 48 | + } |
| 49 | +}; |
| 50 | + |
| 51 | +} // namespace margelo |
0 commit comments