Proper image rendering ux (#5)

* can draw from selection

* add light-weight render manager to render many images simultaneously

* [debug me] currently the image close button does not do

* the unselected image can be closed now

* can close images and manually open them on demand

* cosmetic

* image view stuff in render subdirectory

* cosmetic

* generate docs

* review

windows support

some cosmetics

💅 and pin libCZI module
This commit is contained in:
m-aXimilian
2025-09-13 14:49:59 +02:00
committed by Maximilian Kueffner
parent 2990f3313d
commit bce12b0bb4
21 changed files with 436 additions and 131 deletions
+22 -1
View File
@@ -1,15 +1,29 @@
#include "AppGLFW.hpp"
#include "app_resources_default.h"
#include "imgui.h"
#include "imgui_impl_glfw.h"
#include "imgui_impl_opengl3.h"
#include "app_resources_default.h"
/// @brief GLFW error callback function.
/// @param error The error code.
/// @param description A description of the error.
static void glfw_error_callback(int error, const char* description)
{
fprintf(stderr, "GLFW Error %d: %s\n", error, description);
}
/// @brief Initializes the main application window using GLFW.
///
/// This function sets up the GLFW error callback, initializes GLFW,
/// selects appropriate OpenGL and GLSL versions based on platform,
/// creates the main application window, sets up the OpenGL context,
/// enables vsync, and initializes the Dear ImGui context, style, and
/// platform/renderer backends. It uses the primary monitor's workarea
/// to determine the screen resolution but creates a window of a fixed size (1200x800).
///
/// @return void. The function returns void and uses error handling internally to manage GLFW and window creation
/// failures. The application may continue to run in a failed state, but the window will not be initialized.
void pixelarium::application::AppGLFW::InitMainWindow()
{
glfwSetErrorCallback(glfw_error_callback);
@@ -95,6 +109,8 @@ void pixelarium::application::AppGLFW::InitMainWindow()
ImGui_ImplOpenGL3_Init(glsl_version);
}
/// @brief Main application loop. This function handles window events, rendering, and ImGui integration.
/// @return 0 if the application closes successfully.
int pixelarium::application::AppGLFW::RunLoop()
{
ImGuiIO& io = ImGui::GetIO();
@@ -141,6 +157,10 @@ int pixelarium::application::AppGLFW::RunLoop()
return 0;
}
/// @brief Creates and displays the main menu bar.
///
/// This function constructs the application's main menu bar using ImGui. It includes a log level selector
/// and calls other functions to populate additional menu bar sections.
void pixelarium::application::AppGLFW::MenuBar()
{
if (ImGui::BeginMainMenuBar())
@@ -179,6 +199,7 @@ void pixelarium::application::AppGLFW::MenuBar()
}
}
/// @brief Allows the user to select the log level via a combo box.
void pixelarium::application::AppGLFW::LogLevelSelect()
{
if (ImGui::BeginCombo(LOGLEVELSELECT, LOGLEVELS[log_level_].data()))
+1
View File
@@ -13,5 +13,6 @@ pixelarium::imaging::PixelariumImage::PixelariumImage(const std::string& uri)
throw std::runtime_error(std::format("File not {} found", uri));
}
this->uri_ = std::filesystem::path(uri);
this->img_ = std::make_unique<cv::Mat>(cv::imread(uri));
}
+44 -4
View File
@@ -1,45 +1,85 @@
#pragma once
#include <filesystem>
#include <functional>
#include <memory>
#include <opencv2/core/mat.hpp>
#include <string>
namespace pixelarium::imaging
{
using AccessorFunctor = std::function<void(const std::string&, void*, int*)>;
enum class ImageFileType
{
ABSRACT = 0,
PNG = 1,
JPG = 2,
CZI = 3,
};
/// @brief This aims to be a generic image abstraction
/// meant for codec specific implementation.
/// Todo: the above implies that most of the below implementations don't make sense for this class (c.f. cv::Mat
/// generation et.al.)
class PixelariumImage
{
public:
// get back the defaults
// this means, that there has to be and API option to set
// a resource which should trigger some sort of action
// after setting
explicit PixelariumImage(const std::string& uri);
// get back the defaults
PixelariumImage() = default;
PixelariumImage(const PixelariumImage& other)
{
// be ware!!
// we make a copy of the image data here!
img_ = std::make_unique<cv::Mat>(*other.img_);
uri_ = other.uri_;
};
PixelariumImage(PixelariumImage&& other) noexcept
: img_(std::move(other.img_)) {}
// requires a copy ctor which we don't have
PixelariumImage(PixelariumImage&& other) noexcept : img_(std::move(other.img_)) {}
PixelariumImage& operator=(const PixelariumImage& other) = delete;
PixelariumImage& operator=(PixelariumImage&& other) noexcept
{
if (this != &other)
{
img_ = std::move(other.img_);
uri_ = other.uri_;
}
return *this;
}
// this should probably vanish as it makes no sense
// for multidimensional images (more than one frame)
// -> we need some sort of accessor functionality
~PixelariumImage() = default;
const cv::Mat& GetImage() const { return *this->img_.get(); }
const std::string Name() const noexcept
{
if (!this->uri_.empty())
{
return this->uri_.filename().string();
}
return {};
}
bool Empty() const noexcept { return this->img_->empty(); }
static ImageFileType Type() { return PixelariumImage::type_; }
protected:
std::unique_ptr<cv::Mat> img_;
std::filesystem::path uri_;
static ImageFileType type_;
};
} // namespace pixelarium::imaging
+6 -2
View File
@@ -1,7 +1,10 @@
set(RENDERLIBNAME pixelariumrenderlib)
set(RENDERLIBSRC
CvMatRender.cpp)
CvMatRender.cpp
RenderImageManager.cpp
PixelariumImageView.cpp
ImageViewFactory.cpp)
add_library(${RENDERLIBNAME} STATIC
${RENDERLIBSRC})
@@ -10,4 +13,5 @@ target_link_libraries(${RENDERLIBNAME}
PRIVATE pixelariumimagelib)
target_include_directories(${RENDERLIBNAME}
PRIVATE ${CMAKE_SOURCE_DIR}/lib)
PRIVATE ${CMAKE_SOURCE_DIR}/lib
PRIVATE ${imgui_DIR})
+22
View File
@@ -0,0 +1,22 @@
#include "ImageViewFactory.hpp"
#include <memory>
#include <optional>
/// @brief Creates a PixelariumImageView from a resource image.
/// @param image_id The ID of the image resource to render.
/// @return A unique pointer to the PixelariumImageView, or nullptr if the image resource is not found or is empty. The image data is copied.
std::unique_ptr<pixelarium::render::PixelariumImageView> pixelarium::render::ImageViewFactory::RenderImage(
size_t image_id)
{
auto img{this->image_pool_.GetResource(image_id)};
if (!img.has_value() || img.value()->Empty())
{
return nullptr;
}
// beware: here we copy the actual image resource over to the new image
return std::make_unique<PixelariumImageView>(std::make_shared<Image>(*img.value()));
}
+21
View File
@@ -0,0 +1,21 @@
#pragma once
#include "PixelariumImageView.hpp"
#include "imaging/PixelariumImage.hpp"
#include "resources/resource.hpp"
namespace pixelarium::render
{
class ImageViewFactory
{
using Image = imaging::PixelariumImage;
using Pool = resources::ImageResourcePool;
public:
explicit ImageViewFactory(Pool& pool) : image_pool_(pool) {}
std::unique_ptr<PixelariumImageView> RenderImage(size_t id);
private:
Pool& image_pool_;
};
} // namespace pixelarium::render
+70
View File
@@ -0,0 +1,70 @@
#include "PixelariumImageView.hpp"
#include <format>
#include "imgui.h"
/// @brief Checks if the dimensions of two ImVec2 vectors have changed significantly.
/// @param ref_rect The reference ImVec2 vector.
/// @param new_rect The new ImVec2 vector to compare against.
/// @return True if the absolute difference between the y-coordinates is greater than 5 or the x-coordinates are
/// different; otherwise, false.
static bool dim_changed_p(const ImVec2& ref_rect, const ImVec2& new_rect)
{
if (std::abs(ref_rect.y - new_rect.y) > 5 || std::abs(ref_rect.x - new_rect.x))
{
return true;
}
return false;
}
/// @brief Calculates dimensions to maintain aspect ratio.
/// @param img The input image.
/// @param curr_dim The current dimensions.
/// @return The calculated dimensions maintaining aspect ratio.
ImVec2 aspect_const_dimensions(const pixelarium::imaging::PixelariumImage& img, const ImVec2& curr_dim)
{
const auto w_fact = (static_cast<float>(curr_dim.x) / img.GetImage().cols);
const auto h_fact = (static_cast<float>(curr_dim.y) / img.GetImage().rows);
const auto fact = w_fact < h_fact ? w_fact : h_fact;
return ImVec2(img.GetImage().cols * fact, img.GetImage().rows * fact);
}
/// @brief Displays the image in an ImGui window.
///
/// If the image is null, empty, or has an empty name, the function returns immediately. Otherwise, it creates an ImGui
/// window with a horizontal scrollbar and menu bar. The image is rendered using the CvMatRender object, resizing it to
/// fit the available window space. The raw and rendered dimensions are displayed below the image.
void pixelarium::render::PixelariumImageView::ShowImage()
{
if (this->img_ == nullptr || this->img_->Empty() || this->img_->Name().empty())
{
// do nothing
return;
}
ImGui::Begin(img_->Name().c_str(), &this->open_p, ImGuiWindowFlags_HorizontalScrollbar | ImGuiWindowFlags_MenuBar);
this->curr_dim_ = ImGui::GetContentRegionAvail();
auto new_dim = ImGui::GetContentRegionAvail();
auto texture =
dim_changed_p(this->curr_dim_, new_dim)
? this->render_.Render(static_cast<size_t>(this->curr_dim_.x), static_cast<size_t>(this->curr_dim_.y))
: this->render_.Render();
this->curr_dim_ = new_dim;
ImVec2 dim(this->img_->GetImage().cols, this->img_->GetImage().rows);
ImGui::Image(reinterpret_cast<ImTextureID>(reinterpret_cast<void*>(texture)),
aspect_const_dimensions(*this->img_, new_dim));
ImGui::Separator();
ImGui::Text("%s", std::format(" Raw Dimensions W : {}, H: {}", dim.x, dim.y).c_str());
ImGui::Text("%s", std::format("Render Dimensions W : {}, H: {}", curr_dim_.x, curr_dim_.y).c_str());
ImGui::End();
}
+35
View File
@@ -0,0 +1,35 @@
#pragma once
#include <memory>
#include "imaging/PixelariumImage.hpp"
#include "imgui.h"
#include "rendering/CvMatRender.hpp"
namespace pixelarium::render
{
class PixelariumImageView
{
using Image = imaging::PixelariumImage;
using Render = render::CvMatRender;
public:
explicit PixelariumImageView(const std::shared_ptr<Image>& img) : img_(img) { render_ = Render(img_); }
PixelariumImageView() = delete;
PixelariumImageView(PixelariumImageView&) = delete;
PixelariumImageView(const PixelariumImageView&) = delete;
PixelariumImageView(PixelariumImageView&&) = delete;
PixelariumImageView& operator=(PixelariumImageView&) = delete;
PixelariumImageView& operator=(PixelariumImageView&&) = delete;
// void ToggleView(bool target) { open_p = target; }
const bool* GetStatus() const noexcept { return &this->open_p; }
void ShowImage();
private:
const std::shared_ptr<Image> img_;
Render render_;
bool open_p{true};
ImVec2 curr_dim_{};
};
} // namespace pixelarium::render
+76
View File
@@ -0,0 +1,76 @@
#include "RenderImageManager.hpp"
#include <format>
using namespace std;
/// @brief Updates the collection of rendered images by removing images marked for deletion.
/// This function iterates through the \c keys_to_delete_ list and removes the corresponding images from the collection.
/// It does not acquire the mutex to avoid deadlocks with the `Remove` function.
void pixelarium::render::RenderImageManager::UpdateCollection()
{
for (const auto& key : keys_to_delete_)
{
this->Remove(key);
}
keys_to_delete_.clear();
}
/// @brief Marks a resource for deletion.
/// @param key The ID of the resource to mark for deletion.
void pixelarium::render::RenderImageManager::MarkForDeletion(resources::ResourceKey key)
{
this->log_.Debug(std::format("{} marking key: \"{}\" for deletion.", __PRETTY_FUNCTION__, key));
lock_guard<mutex> guard(this->mut_);
keys_to_delete_.insert(key);
}
/// @brief Removes a render image from the manager.
/// @param key The key of the render image to remove.
/// @return True if the render image was removed, false otherwise.
bool pixelarium::render::RenderImageManager::Remove(resources::ResourceKey key) noexcept
{
bool remove_state{false};
this->log_.Debug(std::format("{} removing key: \"{}\" from renderlist.", __PRETTY_FUNCTION__, key));
{
lock_guard<mutex> guard(this->mut_);
remove_state = this->render_image_map_.erase(key) == 1;
}
return remove_state;
}
/// @brief Adds a resource to the render image map.
/// @param key The ID of the resource to add.
/// @return void. No exception is thrown.
void pixelarium::render::RenderImageManager::Add(resources::ResourceKey key) noexcept
{
// we don't want to add what's already there
// or empty render images
auto current_view = this->view_factory_->RenderImage(key);
if (this->render_image_map_.contains(key) || current_view == nullptr)
{
return;
}
this->log_.Debug(std::format("{}: adding key: \"{}\" to renderlist.", __PRETTY_FUNCTION__, key));
lock_guard<mutex> guard(this->mut_);
// clang-format off
this->render_image_map_.insert(
{
key,
RenderImageStateWrapper
{
.view{ std::move(current_view) },
.show_state = current_view->GetStatus(),
}
}
);
// clang-format on
}
/// @brief Clears all render images from the manager.
/// @note This function is noexcept.
void pixelarium::render::RenderImageManager::Clear() noexcept { this->render_image_map_.clear(); }
+64
View File
@@ -0,0 +1,64 @@
#pragma once
#include <memory>
#include <mutex>
#include <unordered_map>
#include <unordered_set>
#include "ImageViewFactory.hpp"
#include "PixelariumImageView.hpp"
#include "resources/resource.hpp"
#include "utilities/ILog.hpp"
// This is intended as an additional abstraction
// aggregating views that should be rendered (or not)
namespace pixelarium::render
{
struct RenderImageStateWrapper
{
std::unique_ptr<PixelariumImageView> view;
const bool* show_state;
};
class RenderImageManager
{
using Pool = resources::ImageResourcePool;
public:
explicit RenderImageManager(Pool& pool, const utils::log::ILog& log)
: view_factory_(std::make_unique<ImageViewFactory>(pool)), log_(log)
{
}
void Clear() noexcept;
void Add(resources::ResourceKey key) noexcept;
bool Remove(resources::ResourceKey key) noexcept;
// can't be const because func mutates the state
template <typename Callable>
requires std::invocable<Callable, resources::ResourceKey, RenderImageStateWrapper&>
void Enumerate(Callable&& func)
{
for (auto& [key, val] : this->render_image_map_)
{
if (val.view != nullptr)
{
func(key, val);
}
}
}
void MarkForDeletion(resources::ResourceKey key);
void UpdateCollection();
private:
std::unordered_map<resources::ResourceKey, RenderImageStateWrapper> render_image_map_;
std::unique_ptr<ImageViewFactory> view_factory_;
std::mutex mut_;
std::unordered_set<resources::ResourceKey> keys_to_delete_;
const utils::log::ILog& log_;
};
} // namespace pixelarium::render
+14 -6
View File
@@ -1,7 +1,9 @@
#include "resource.hpp"
#include <atomic>
#include <cstddef>
#include <functional>
#include <mutex>
#include <optional>
using pixelarium::imaging::PixelariumImage;
@@ -20,7 +22,7 @@ size_t GenerateId() { return id_.fetch_add(1, memory_order_relaxed); }
/// @brief Retrieves a resource from the pool.
/// @param id The ID of the resource to retrieve.
/// @return A pointer to the resource if found, otherwise an empty optional.
std::optional<const PixelariumImage*> pixelarium::resources::ImageResourcePool::GetResource(size_t id) const
std::optional<const PixelariumImage*> pixelarium::resources::ImageResourcePool::GetResource(ResourceKey id) const
{
auto search{this->resources_.find(id)};
if (search == this->resources_.end()) return std::nullopt;
@@ -34,7 +36,10 @@ std::optional<const PixelariumImage*> pixelarium::resources::ImageResourcePool::
size_t pixelarium::resources::ImageResourcePool::SetResource(unique_ptr<PixelariumImage> res)
{
auto key{::GenerateId()};
this->resources_.insert({key, std::move(res)});
{
std::lock_guard<std::mutex> guard(this->mut_);
this->resources_.insert({key, std::move(res)});
}
return key;
}
@@ -43,7 +48,8 @@ size_t pixelarium::resources::ImageResourcePool::SetResource(unique_ptr<Pixelari
/// @param id The ID of the resource to update.
/// @param res A unique pointer to the new resource.
/// @return True if the resource was updated, false otherwise.
bool pixelarium::resources::ImageResourcePool::ModifyResource(size_t id, std::unique_ptr<imaging::PixelariumImage> res)
bool pixelarium::resources::ImageResourcePool::ModifyResource(ResourceKey id,
std::unique_ptr<imaging::PixelariumImage> res)
{
auto search{this->resources_.find(id)};
if (search == this->resources_.end()) return false;
@@ -56,7 +62,7 @@ bool pixelarium::resources::ImageResourcePool::ModifyResource(size_t id, std::un
/// @brief Deletes a resource from the pool.
/// @param id The ID of the resource to delete.
/// @return True if the resource was deleted, false otherwise.
bool pixelarium::resources::ImageResourcePool::DeleteResource(size_t id)
bool pixelarium::resources::ImageResourcePool::DeleteResource(ResourceKey id)
{
auto search{this->resources_.find(id)};
if (search == this->resources_.end()) return false;
@@ -70,10 +76,12 @@ bool pixelarium::resources::ImageResourcePool::DeleteResource(size_t id)
/// @param func A function to call for each resource. The function should accept the resource ID and a const reference
/// to a PixelariumImage.
void pixelarium::resources::ImageResourcePool::EnumerateResources(
const std::function<void(size_t, const imaging::PixelariumImage&)>& func)
const std::function<void(ResourceKey, size_t, const imaging::PixelariumImage&)>& func)
{
size_t idx{0};
for (const auto& e : this->resources_)
{
func(e.first, *e.second);
func(e.first, idx, *e.second);
++idx;
}
}
+15 -11
View File
@@ -3,6 +3,7 @@
#include <concepts>
#include <functional>
#include <memory>
#include <mutex>
#include <optional>
#include <unordered_map>
@@ -10,6 +11,7 @@
namespace pixelarium::resources
{
using ResourceKey = size_t;
struct IResource
{
virtual ~IResource() = default;
@@ -24,10 +26,10 @@ class IResourcePool
public:
virtual ~IResourcePool() = default;
virtual std::optional<const ResT*> GetResource(size_t id) const = 0;
virtual size_t SetResource(std::unique_ptr<ResT> res) = 0;
virtual bool ModifyResource(size_t id, std::unique_ptr<ResT> res) = 0;
virtual bool DeleteResource(size_t id) = 0;
virtual void EnumerateResources(const std::function<void(size_t, const ResT&)>& func) = 0;
virtual ResourceKey SetResource(std::unique_ptr<ResT> res) = 0;
virtual bool ModifyResource(ResourceKey id, std::unique_ptr<ResT> res) = 0;
virtual bool DeleteResource(ResourceKey id) = 0;
virtual void EnumerateResources(const std::function<void(ResourceKey, size_t, const imaging::PixelariumImage&)>& func) = 0;
virtual size_t GetTotalSize() const = 0;
};
@@ -46,20 +48,21 @@ class ImageResourcePool : public IResourcePool<imaging::PixelariumImage>
ImageResourcePool& operator=(ImageResourcePool&) = delete;
ImageResourcePool& operator=(ImageResourcePool&&) = delete;
std::optional<const imaging::PixelariumImage*> GetResource(size_t id) const override;
size_t SetResource(std::unique_ptr<imaging::PixelariumImage> res) override;
bool ModifyResource(size_t id, std::unique_ptr<imaging::PixelariumImage> res) override;
bool DeleteResource(size_t id) override;
std::optional<const imaging::PixelariumImage*> GetResource(ResourceKey id) const override;
ResourceKey SetResource(std::unique_ptr<imaging::PixelariumImage> res) override;
bool ModifyResource(ResourceKey id, std::unique_ptr<imaging::PixelariumImage> res) override;
bool DeleteResource(ResourceKey id) override;
void EnumerateResources(const std::function<void(size_t, const imaging::PixelariumImage&)>& func) override;
void EnumerateResources(const std::function<void(ResourceKey, size_t, const imaging::PixelariumImage&)>& func) override;
template <typename Callable>
requires std::invocable<Callable, size_t, const imaging::PixelariumImage&>
requires std::invocable<Callable, ResourceKey, size_t, const imaging::PixelariumImage&>
void Enumerate(Callable&& func) const
{
size_t idx{0};
for (const auto& e : this->resources_)
{
func(e.first, *e.second);
func(e.first, idx, *e.second);
}
}
@@ -67,5 +70,6 @@ class ImageResourcePool : public IResourcePool<imaging::PixelariumImage>
private:
std::unordered_map<size_t, std::unique_ptr<imaging::PixelariumImage>> resources_;
std::mutex mut_;
};
} // namespace pixelarium::resources