Compare commits
10 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c00c2c71ac | |||
| b37814204f | |||
| e3e161ce52 | |||
| 356f966d01 | |||
| 244b00fa5c | |||
| a760535b92 | |||
| d6a08f7db3 | |||
| b1923a490c | |||
| fec5c08aaa | |||
| 1ea83d9d11 |
@@ -0,0 +1,33 @@
|
||||
name: build-ubuntu
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
workflow_call:
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
configuration: [Debug, Release]
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: recursive
|
||||
- name: setup
|
||||
run: |
|
||||
sudo apt update
|
||||
sudo apt -y install libopencv-dev libglfw3 libglfw3-dev libxkbcommon-dev libxinerama-dev libxcursor-dev libxi-dev doxygen graphviz
|
||||
|
||||
- name: Configure Ubuntu
|
||||
run: cmake -B ${{github.workspace}}/build/gcc-${{ matrix.configuration }} -S . -DCMAKE_BUILD_TYPE=${{ matrix.configuration }}
|
||||
|
||||
- name: Build Ubuntu
|
||||
run: cmake --build ${{github.workspace}}/build/gcc-${{ matrix.configuration }} --config ${{ matrix.configuration }} -- -j 10
|
||||
|
||||
- name: Test Ubuntu
|
||||
run: |
|
||||
cd ${{github.workspace}}/build/gcc-${{ matrix.configuration }}
|
||||
ctest -C ${{ matrix.configuration }}
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
name: build-windows
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
workflow_call:
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: windows-latest
|
||||
strategy:
|
||||
matrix:
|
||||
configuration: [Debug]
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: recursive
|
||||
|
||||
- name: Cacke vcpkg
|
||||
uses: actions/cache@v3
|
||||
with:
|
||||
path: 'C:/vcpkg/installed'
|
||||
key: vcpkg-x64-windows-${{ matrix.configuration }}
|
||||
restore-keys: |
|
||||
vcpkg-x64-windows-${{ matrix.configuration }}
|
||||
|
||||
- name: Install OpenCV vcpkg
|
||||
run: |
|
||||
vcpkg install opencv[core]:x64-windows-static
|
||||
|
||||
- name: Set PATH for vcpkg
|
||||
run: echo "PATH=C:/vcpkg/installed/x64-windows/bin:${{ env.PATH }}" >> $GITHUB_ENV
|
||||
|
||||
- name: Configure Windows
|
||||
run: cmake -B ${{github.workspace}}/build/msvc-${{ matrix.configuration }} -S . -DCMAKE_BUILD_TYPE=${{ matrix.configuration }} -DCMAKE_TOOLCHAIN_FILE=C:/vcpkg/scripts/buildsystems/vcpkg.cmake -DVCPKG_TARGET_TRIPLET=x64-windows-static
|
||||
|
||||
- name: Build Windows
|
||||
run: cmake --build ${{github.workspace}}/build/msvc-${{ matrix.configuration }} --config ${{ matrix.configuration }} -j 10
|
||||
|
||||
- name: Test Windows
|
||||
run: |
|
||||
cd ${{github.workspace}}/build/msvc-${{ matrix.configuration }}
|
||||
ctest -C ${{ matrix.configuration }}
|
||||
@@ -0,0 +1,25 @@
|
||||
name: CI Workflow
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ "main" ]
|
||||
pull_request:
|
||||
branches: [ "main" ]
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
build-ubuntu:
|
||||
uses: ./.github/workflows/build-ubuntu.yml
|
||||
|
||||
build-windows:
|
||||
uses: ./.github/workflows/build-windows.yml
|
||||
|
||||
generate-docs:
|
||||
permissions:
|
||||
id-token: write
|
||||
pages: write
|
||||
uses: ./.github/workflows/generate-docs.yml
|
||||
if: github.ref == 'refs/heads/main'
|
||||
needs:
|
||||
- build-ubuntu
|
||||
- build-windows
|
||||
@@ -1,40 +1,33 @@
|
||||
name: C/C++ CI
|
||||
name: generate-docs
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ "main" ]
|
||||
pull_request:
|
||||
branches: [ "main" ]
|
||||
workflow_dispatch:
|
||||
workflow_call:
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: recursive
|
||||
|
||||
- name: setup
|
||||
run: |
|
||||
sudo apt update
|
||||
sudo apt -y install libopencv-dev libglfw3 libglfw3-dev libxkbcommon-dev libxinerama-dev libxcursor-dev libxi-dev doxygen graphviz
|
||||
- name: configure
|
||||
run: cmake --preset gcc-debug
|
||||
- name: build
|
||||
run: cmake --build build --preset gcc-debug
|
||||
- name: test
|
||||
run: |
|
||||
cd ${{github.workspace}}/build/gcc-debug
|
||||
ctest -C Debug
|
||||
sudo apt -y install doxygen graphviz
|
||||
|
||||
- name: Upload static files as artifact
|
||||
- name: Generate Documentation
|
||||
run: |
|
||||
cmake -S . -B build -DPIXELARIUM_BUILD_DOCS_ONLY=ON
|
||||
cmake --build build
|
||||
|
||||
- name: Upload Documentation Files as Artifacts
|
||||
id: deployment
|
||||
uses: actions/upload-pages-artifact@v3
|
||||
with:
|
||||
path: ${{github.workspace}}/build/gcc-debug/doc/html
|
||||
path: ${{github.workspace}}/build/doc/html
|
||||
|
||||
# Deployment job
|
||||
deploy:
|
||||
environment:
|
||||
name: github-pages
|
||||
@@ -0,0 +1,204 @@
|
||||
# MegaLinter GitHub Action configuration file
|
||||
# More info at https://megalinter.io
|
||||
---
|
||||
name: MegaLinter
|
||||
|
||||
# Trigger mega-linter at every push. Action will also be visible from
|
||||
# Pull Requests to main
|
||||
on:
|
||||
# Comment this line to trigger action only on pull-requests
|
||||
# (not recommended if you don't pay for GH Actions)
|
||||
push:
|
||||
branches: [ "main" ]
|
||||
pull_request:
|
||||
branches: [ "main" ]
|
||||
|
||||
# Comment env block if you do not want to apply fixes
|
||||
env:
|
||||
# Apply linter fixes configuration
|
||||
#
|
||||
# When active, APPLY_FIXES must also be defined as environment variable
|
||||
# (in github/workflows/mega-linter.yml or other CI tool)
|
||||
APPLY_FIXES: none
|
||||
|
||||
# Decide which event triggers application of fixes in a commit or a PR
|
||||
# (pull_request, push, all)
|
||||
APPLY_FIXES_EVENT: pull_request
|
||||
|
||||
# If APPLY_FIXES is used, defines if the fixes are directly committed (commit)
|
||||
# or posted in a PR (pull_request)
|
||||
APPLY_FIXES_MODE: commit
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.ref }}-${{ github.workflow }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
megalinter:
|
||||
name: MegaLinter
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
# Give the default GITHUB_TOKEN write permission to commit and push, comment
|
||||
# issues, and post new Pull Requests; remove the ones you do not need
|
||||
permissions:
|
||||
contents: write
|
||||
issues: write
|
||||
pull-requests: write
|
||||
|
||||
steps:
|
||||
# Git Checkout
|
||||
- name: Checkout Code
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
token: ${{ secrets.PAT || secrets.GITHUB_TOKEN }}
|
||||
|
||||
# If you use VALIDATE_ALL_CODEBASE = true, you can remove this line to
|
||||
# improve performance
|
||||
fetch-depth: 0
|
||||
|
||||
# MegaLinter
|
||||
- name: MegaLinter
|
||||
|
||||
# You can override MegaLinter flavor used to have faster performances
|
||||
# More info at https://megalinter.io/latest/flavors/
|
||||
uses: oxsecurity/megalinter/flavors/c_cpp@v9.1.0
|
||||
|
||||
id: ml
|
||||
|
||||
# All available variables are described in documentation
|
||||
# https://megalinter.io/latest/config-file/
|
||||
env:
|
||||
# Validates all source when push on main, else just the git diff with
|
||||
# main. Override with true if you always want to lint all sources
|
||||
#
|
||||
# To validate the entire codebase, set to:
|
||||
# VALIDATE_ALL_CODEBASE: true
|
||||
#
|
||||
# To validate only diff with main, set to:
|
||||
# VALIDATE_ALL_CODEBASE: >-
|
||||
# ${{
|
||||
# github.event_name == 'push' &&
|
||||
# github.ref == 'refs/heads/main'
|
||||
# }}
|
||||
VALIDATE_ALL_CODEBASE: true
|
||||
|
||||
# Disable LLM Advisor for bot PRs (dependabot, renovate, etc.)
|
||||
LLM_ADVISOR_ENABLED: >-
|
||||
${{
|
||||
github.event_name != 'pull_request' ||
|
||||
(github.event.pull_request.user.login != 'dependabot[bot]' &&
|
||||
github.event.pull_request.user.login != 'renovate[bot]' &&
|
||||
github.event.pull_request.user.login != 'github-actions[bot]' &&
|
||||
!startsWith(github.event.pull_request.user.login, 'dependabot') &&
|
||||
!startsWith(github.event.pull_request.user.login, 'renovate'))
|
||||
}}
|
||||
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
# Uncomment to use ApiReporter (Grafana)
|
||||
# API_REPORTER: true
|
||||
# API_REPORTER_URL: ${{ secrets.API_REPORTER_URL }}
|
||||
# API_REPORTER_BASIC_AUTH_USERNAME: ${{ secrets.API_REPORTER_BASIC_AUTH_USERNAME }}
|
||||
# API_REPORTER_BASIC_AUTH_PASSWORD: ${{ secrets.API_REPORTER_BASIC_AUTH_PASSWORD }}
|
||||
# API_REPORTER_METRICS_URL: ${{ secrets.API_REPORTER_METRICS_URL }}
|
||||
# API_REPORTER_METRICS_BASIC_AUTH_USERNAME: ${{ secrets.API_REPORTER_METRICS_BASIC_AUTH_USERNAME }}
|
||||
# API_REPORTER_METRICS_BASIC_AUTH_PASSWORD: ${{ secrets.API_REPORTER_METRICS_BASIC_AUTH_PASSWORD }}
|
||||
# API_REPORTER_DEBUG: false
|
||||
|
||||
# ADD YOUR CUSTOM ENV VARIABLES HERE TO OVERRIDE VALUES OF
|
||||
# .mega-linter.yml AT THE ROOT OF YOUR REPOSITORY
|
||||
|
||||
# Upload MegaLinter artifacts
|
||||
- name: Archive production artifacts
|
||||
uses: actions/upload-artifact@v4
|
||||
if: success() || failure()
|
||||
with:
|
||||
name: MegaLinter reports
|
||||
include-hidden-files: "true"
|
||||
path: |
|
||||
megalinter-reports
|
||||
mega-linter.log
|
||||
|
||||
# Create pull request if applicable
|
||||
# (for now works only on PR from same repository, not from forks)
|
||||
- name: Create Pull Request with applied fixes
|
||||
uses: peter-evans/create-pull-request@v7
|
||||
id: cpr
|
||||
if: >-
|
||||
steps.ml.outputs.has_updated_sources == 1 &&
|
||||
(
|
||||
env.APPLY_FIXES_EVENT == 'all' ||
|
||||
env.APPLY_FIXES_EVENT == github.event_name
|
||||
) &&
|
||||
env.APPLY_FIXES_MODE == 'pull_request' &&
|
||||
(
|
||||
github.event_name == 'push' ||
|
||||
github.event.pull_request.head.repo.full_name == github.repository
|
||||
) &&
|
||||
!contains(github.event.head_commit.message, 'skip fix')
|
||||
with:
|
||||
token: ${{ secrets.PAT || secrets.GITHUB_TOKEN }}
|
||||
commit-message: "[MegaLinter] Apply linters automatic fixes"
|
||||
title: "[MegaLinter] Apply linters automatic fixes"
|
||||
labels: bot
|
||||
|
||||
- name: Create PR output
|
||||
if: >-
|
||||
steps.ml.outputs.has_updated_sources == 1 &&
|
||||
(
|
||||
env.APPLY_FIXES_EVENT == 'all' ||
|
||||
env.APPLY_FIXES_EVENT == github.event_name
|
||||
) &&
|
||||
env.APPLY_FIXES_MODE == 'pull_request' &&
|
||||
(
|
||||
github.event_name == 'push' ||
|
||||
github.event.pull_request.head.repo.full_name == github.repository
|
||||
) &&
|
||||
!contains(github.event.head_commit.message, 'skip fix')
|
||||
run: |
|
||||
echo "PR Number - ${{ steps.cpr.outputs.pull-request-number }}"
|
||||
echo "PR URL - ${{ steps.cpr.outputs.pull-request-url }}"
|
||||
|
||||
# Push new commit if applicable
|
||||
# (for now works only on PR from same repository, not from forks)
|
||||
- name: Prepare commit
|
||||
if: >-
|
||||
steps.ml.outputs.has_updated_sources == 1 &&
|
||||
(
|
||||
env.APPLY_FIXES_EVENT == 'all' ||
|
||||
env.APPLY_FIXES_EVENT == github.event_name
|
||||
) &&
|
||||
env.APPLY_FIXES_MODE == 'commit' &&
|
||||
github.ref != 'refs/heads/main' &&
|
||||
(
|
||||
github.event_name == 'push' ||
|
||||
github.event.pull_request.head.repo.full_name == github.repository
|
||||
) &&
|
||||
!contains(github.event.head_commit.message, 'skip fix')
|
||||
run: sudo chown -Rc $UID .git/
|
||||
|
||||
- name: Commit and push applied linter fixes
|
||||
uses: stefanzweifel/git-auto-commit-action@v6
|
||||
if: >-
|
||||
steps.ml.outputs.has_updated_sources == 1 &&
|
||||
(
|
||||
env.APPLY_FIXES_EVENT == 'all' ||
|
||||
env.APPLY_FIXES_EVENT == github.event_name
|
||||
) &&
|
||||
env.APPLY_FIXES_MODE == 'commit' &&
|
||||
github.ref != 'refs/heads/main' &&
|
||||
(
|
||||
github.event_name == 'push' ||
|
||||
github.event.pull_request.head.repo.full_name == github.repository
|
||||
) &&
|
||||
!contains(github.event.head_commit.message, 'skip fix')
|
||||
with:
|
||||
branch: >-
|
||||
${{
|
||||
github.event.pull_request.head.ref ||
|
||||
github.head_ref ||
|
||||
github.ref
|
||||
}}
|
||||
commit_message: "[MegaLinter] Apply linters fixes"
|
||||
commit_user_name: megalinter-bot
|
||||
commit_user_email: 129584137+megalinter-bot@users.noreply.github.com
|
||||
@@ -3,3 +3,4 @@ out/
|
||||
.vs/
|
||||
.cache/
|
||||
*~
|
||||
megalinter-reports/
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
# Configuration file for MegaLinter
|
||||
#
|
||||
# See all available variables at https://megalinter.io/latest/config-file/ and in
|
||||
# linters documentation
|
||||
|
||||
# all, none, or list of linter keys
|
||||
APPLY_FIXES: none
|
||||
|
||||
# If you use ENABLE variable, all other languages/formats/tooling-formats will
|
||||
# be disabled by default
|
||||
# ENABLE:
|
||||
|
||||
# If you use ENABLE_LINTERS variable, all other linters will be disabled by
|
||||
# default
|
||||
ENABLE_LINTERS:
|
||||
- SPELL
|
||||
- CPP_CLANG_FORMAT
|
||||
|
||||
# DISABLE:
|
||||
# - COPYPASTE # Uncomment to disable checks of excessive copy-pastes
|
||||
# - SPELL # Uncomment to disable checks of spelling mistakes
|
||||
|
||||
SHOW_ELAPSED_TIME: true
|
||||
|
||||
# Uncomment if you want MegaLinter to detect errors but not block CI to pass
|
||||
DISABLE_ERRORS: true
|
||||
|
||||
FLAVOR_SUGGESTIONS: false
|
||||
+46
-55
@@ -1,10 +1,12 @@
|
||||
cmake_minimum_required(VERSION 3.23)
|
||||
|
||||
project(pixelarium VERSION 0.0.1)
|
||||
project(pixelarium VERSION 0.0.12)
|
||||
|
||||
list(APPEND CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/cmake)
|
||||
|
||||
set(CMAKE_VERBOSE_MAKEFILE ON)
|
||||
set(CXX_STANDARD 20)
|
||||
set(CXX_STANDARD_REQUIRED true)
|
||||
set(CMAKE_CXX_STANDARD 23)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED true)
|
||||
|
||||
# setting global module directories
|
||||
set(glfw3_module_DIR ${PROJECT_SOURCE_DIR}/modules/glfw)
|
||||
@@ -13,40 +15,66 @@ set(imgui_DIR ${PROJECT_SOURCE_DIR}/modules/imgui)
|
||||
set(pfd_DIR ${PROJECT_SOURCE_DIR}/modules/portable-file-dialogs)
|
||||
set(spdlog_DIR ${PROJECT_SOURCE_DIR}/modules/spdlog)
|
||||
|
||||
find_package(OpenGL REQUIRED)
|
||||
|
||||
message(STATUS "GLFW:\t" ${glfw3_module_DIR})
|
||||
message(STATUS "PFD:\t\t" ${pfd_DIR})
|
||||
message(STATUS "SPDLOG:\t" ${spdlog_DIR})
|
||||
|
||||
#====================
|
||||
# Options
|
||||
option(PIXELARIUM_BUILD_UNITTESTS "Generate Unittests" ON)
|
||||
option(PIXELARIUM_BUILD_DOCS "Generate Documentation" ON)
|
||||
option(PIXELARIUM_BUILD_UNITTESTS "Generate Unittests" ON)
|
||||
option(PIXELARIUM_BUILD_DOCS "Generate Documentation" ON)
|
||||
option(PIXELARIUM_BUILD_DOCS_ONLY "Build only Documentation (no compilation)" OFF)
|
||||
option(PIXELARIUM_BUILD_EXAMPLES "Build example projects" ON)
|
||||
#====================
|
||||
|
||||
string(TOUPPER "${CMAKE_PROJECT_NAME}" PIXELARIUM_TITLE)
|
||||
|
||||
if(PIXELARIUM_BUILD_DOCS OR PIXELARIUM_BUILD_DOCS_ONLY)
|
||||
find_package(Doxygen REQUIRED)
|
||||
include(awesomeDoxygen)
|
||||
set(MAINPAGE_FILE "${PROJECT_SOURCE_DIR}/doc/index.md")
|
||||
|
||||
set(DOXYGEN_IN ${PROJECT_SOURCE_DIR}/doc/Doxyfile.in)
|
||||
set(DOXYGEN_OUT ${CMAKE_BINARY_DIR}/Doxyfile)
|
||||
|
||||
configure_file(${DOXYGEN_IN} ${DOXYGEN_OUT} @ONLY)
|
||||
message(STATUS "Building Docs")
|
||||
|
||||
add_custom_target(doxygen ALL
|
||||
COMMAND ${DOXYGEN_EXECUTABLE} ${DOXYGEN_OUT}
|
||||
WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
|
||||
COMMENT "Generating Docs")
|
||||
|
||||
if(PIXELARIUM_BUILD_DOCS_ONLY)
|
||||
message(STATUS "Documentation Generated successful")
|
||||
list(APPEND CMAKE_MESSAGE_INDENT " ")
|
||||
message(STATUS "PIXELARIUM_BUILD_DOCS_ONLY was set to ON. Thus, no compilation will follow.")
|
||||
message(STATUS "If compilation shall occur, set '-DPIXELARIUM_BUILD_DOCS_ONLY=OFF'.")
|
||||
list(POP_BACK CMAKE_MESSAGE_INDENT)
|
||||
|
||||
return()
|
||||
endif()
|
||||
endif()
|
||||
|
||||
find_package(OpenGL REQUIRED)
|
||||
|
||||
if(WIN32)
|
||||
set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
|
||||
if (CMAKE_CXX_COMPILER_ID STREQUAL "MSVC")
|
||||
set(CMAKE_CXX_FLAGS "/std:c++20 /Zi /EHsc")
|
||||
set(CMAKE_CXX_FLAGS "/Zi /EHsc")
|
||||
else()
|
||||
set(CMAKE_CXX_FLAGS "-Wall -Wextra -g --std=c++20")
|
||||
set(CMAKE_CXX_FLAGS "-Wall -Wextra -g")
|
||||
endif()
|
||||
endif()
|
||||
if(UNIX)
|
||||
set(CMAKE_CXX_FLAGS "-Wall -Wextra -g --std=c++20")
|
||||
set(CMAKE_CXX_FLAGS "-Wall -Wextra -g")
|
||||
endif()
|
||||
|
||||
string(TOUPPER "${CMAKE_PROJECT_NAME}" PIXELARIUM_TITLE)
|
||||
|
||||
add_subdirectory(${pfd_DIR})
|
||||
add_subdirectory(${spdlog_DIR})
|
||||
add_subdirectory(${glfw3_module_DIR})
|
||||
add_subdirectory(lib)
|
||||
|
||||
set(SRC
|
||||
src/main.cpp)
|
||||
|
||||
#====================
|
||||
# needed for the spdlogger implementation
|
||||
# this is not nice, but it won't work when, e.g. doing it from lower level cmake files
|
||||
@@ -54,49 +82,12 @@ add_compile_options("$<$<C_COMPILER_ID:MSVC>:/utf-8>")
|
||||
add_compile_options("$<$<CXX_COMPILER_ID:MSVC>:/utf-8>")
|
||||
#====================
|
||||
|
||||
add_executable(${PROJECT_NAME} ${SRC})
|
||||
|
||||
target_link_libraries(${PROJECT_NAME}
|
||||
PRIVATE pixelariumimagelib
|
||||
PRIVATE pixelariumrenderlib
|
||||
PRIVATE pixelariumutilslib
|
||||
PRIVATE pixelariumresourcelib
|
||||
PUBLIC pixelariumapplicationlib)
|
||||
|
||||
target_include_directories(${PROJECT_NAME}
|
||||
PUBLIC ${PROJECT_SOURCE_DIR}/src
|
||||
PUBLIC ${PROJECT_SOURCE_DIR}/lib
|
||||
PUBLIC ${PROJECT_SOURCE_DIR}/lib/imaging
|
||||
PUBLIC ${PROJECT_SOURCE_DIR}/lib/app
|
||||
PUBLIC ${spdlog_DIR}/include
|
||||
PUBLIC ${LIBCZI_INCLUDE_DIR}
|
||||
PUBLIC ${CMAKE_CURRENT_BINARY_DIR})
|
||||
|
||||
if(PIXELARIUM_BUILD_EXAMPLES)
|
||||
add_subdirectory(examples)
|
||||
endif()
|
||||
|
||||
if(PIXELARIUM_BUILD_UNITTESTS)
|
||||
include(CTest)
|
||||
enable_testing()
|
||||
add_subdirectory(tests)
|
||||
endif()
|
||||
|
||||
if(PIXELARIUM_BUILD_DOCS)
|
||||
include(${PROJECT_SOURCE_DIR}/cmake/awesomeDoxygen.cmake)
|
||||
set(MAINPAGE_FILE "doc/index.md")
|
||||
find_package(Doxygen)
|
||||
if (DOXYGEN_FOUND)
|
||||
|
||||
set(DOXYGEN_IN ${PROJECT_SOURCE_DIR}/doc/Doxyfile.in)
|
||||
set(DOXYGEN_OUT ${CMAKE_BINARY_DIR}/Doxyfile)
|
||||
|
||||
configure_file(${DOXYGEN_IN} ${DOXYGEN_OUT} @ONLY)
|
||||
message(STATUS "Building Docs")
|
||||
|
||||
add_custom_target(doxygen ALL
|
||||
COMMAND ${DOXYGEN_EXECUTABLE} ${DOXYGEN_OUT}
|
||||
WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
|
||||
COMMENT "Generating Docs")
|
||||
|
||||
else (DOXYGEN_FOUND)
|
||||
message(FATAL_ERROR "Doxygen need to be installed to generate the doxygen documentation")
|
||||
endif (DOXYGEN_FOUND)
|
||||
endif()
|
||||
|
||||
+4
-3
@@ -16,7 +16,9 @@
|
||||
"FETCHCONTENT_FULLY_DISCONNECTED": "OFF",
|
||||
"CMAKE_VERBOSE_MAKEFILE": "ON",
|
||||
"PIXELARIUM_BUILD_UNITTESTS": "ON",
|
||||
"PIXELARIUM_BUILD_DOCS": "OFF"
|
||||
"PIXELARIUM_BUILD_DOCS": "ON",
|
||||
"PIXELARIUM_BUILD_DOCS_ONLY": "OFF",
|
||||
"PIXELARIUM_BUILD_EXAMPLES": "ON"
|
||||
}
|
||||
},
|
||||
{
|
||||
@@ -52,8 +54,7 @@
|
||||
"cacheVariables": {
|
||||
"CMAKE_C_COMPILER": "gcc",
|
||||
"CMAKE_CXX_COMPILER": "g++",
|
||||
"CMAKE_BUILD_TYPE": "Debug",
|
||||
"PIXELARIUM_BUILD_DOCS": "ON"
|
||||
"CMAKE_BUILD_TYPE": "Debug"
|
||||
}
|
||||
}
|
||||
],
|
||||
|
||||
+54
-1
@@ -6,6 +6,9 @@
|
||||
#+author: Maximilian Kueffner
|
||||
#+exclude_tags: noexport
|
||||
|
||||
[[https://github.com/m-aXimilian/pixelarium/actions/workflows/ci-workflow.yml][file:https://github.com/m-aXimilian/pixelarium/actions/workflows/ci-workflow.yml/badge.svg]]
|
||||
[[https://github.com/m-aXimilian/pixelarium/actions/workflows/mega-linter.yml][file:https://github.com/m-aXimilian/pixelarium/actions/workflows/mega-linter.yml/badge.svg]]
|
||||
|
||||
* Synopsis
|
||||
|
||||
Pixelarium strives to be a batteries-included visualizer application used in conjunction with an externally implemented and linked arbitrary functionality.
|
||||
@@ -14,6 +17,17 @@ It tries to be as flexible as possible.
|
||||
|
||||
This is still work in progress and will change significantly.
|
||||
|
||||
* Supported Types
|
||||
|
||||
Currently, Pixelarium supports the following image file formats:
|
||||
- jpeg
|
||||
- png
|
||||
- tiff
|
||||
- czi
|
||||
|
||||
|
||||
where possible, the [[https://docs.opencv.org/3.4/d4/da8/group__imgcodecs.html][OpenCV codecs]] are used to interpret the respective file type. The czi-format is supported via [[https://github.com/ZEISS/libczi][libCZI]].
|
||||
|
||||
* Prerequisites
|
||||
|
||||
Dependencies are either submodules in the =modules= subdirectory or artifacts of the cmake build process from the =cmake= directory. This repository should therefore be cloned recursively:
|
||||
@@ -60,5 +74,44 @@ If you want to specify compiler settings and options which are not defined in a
|
||||
cmake --build build
|
||||
#+end_src
|
||||
|
||||
* TODO Example
|
||||
* Usage
|
||||
|
||||
All there is to do in order to get an initial window on screen is to create an instance of [[file:lib/app/AppGLFW.hpp][=AppGLFW=]] (or one of its child classes) and start it.
|
||||
|
||||
#+begin_src C++
|
||||
unique_ptr<ILog> logger = make_unique<SpdLogger>("logfile.log", "loggername");
|
||||
ImageResourcePool image_pool;
|
||||
|
||||
auto app {DefaultApp(*logger, image_pool)};
|
||||
app.Start();
|
||||
#+end_src
|
||||
|
||||
This will get the default application on screen which looks like
|
||||
[[file:doc/figures/default-app.png]]
|
||||
|
||||
|
||||
The [[file:examples/][examples]] directory aims to showcase a few usage examples of this project.
|
||||
|
||||
** [[file:examples/simple/][simple]]
|
||||
|
||||
This is the most straight-forward usage of Pixelarium. It simply instantiates a [[file:lib/app/DefaultApp.hpp][=DefaultApp=]] and runs it.
|
||||
|
||||
** [[file:examples/custom_0/][custom_0]]
|
||||
|
||||
This is meant to showcase that [[file:lib/app/DefaultApp.hpp][=DefaultApp=]] ([[file:lib/app/AppGLFW.hpp][=AppGLFW=]] as well) is meant to be customized via inheritance.
|
||||
As a usage example, it implements a simple binary image reader. It can be presented with a binary file of layout
|
||||
#+begin_src C++
|
||||
struct ParsedImage
|
||||
{
|
||||
uint8_t depth;
|
||||
uint8_t channels;
|
||||
uint16_t width;
|
||||
uint16_t height;
|
||||
void* data;
|
||||
};
|
||||
#+end_src
|
||||
i.e., a header encoding 1 byte for the pixel-depth, 1 byte for the channel count, 2 byte each for width and height in pixel followed by the actual pixeldata.
|
||||
|
||||
** [[file:examples/custom_1/][custom_1]]
|
||||
|
||||
An example showcasing how to inject a user defined control into the existing scaffolding of =DefaultApp= using a multiplication filter. This is in many ways similar to the previous example.
|
||||
|
||||
@@ -2,6 +2,7 @@ include(FetchContent)
|
||||
FetchContent_Declare(
|
||||
doxygen-awesome-css
|
||||
URL https://github.com/jothepro/doxygen-awesome-css/archive/refs/heads/main.zip
|
||||
DOWNLOAD_EXTRACT_TIMESTAMP 1
|
||||
)
|
||||
FetchContent_MakeAvailable(doxygen-awesome-css)
|
||||
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
include(FetchContent)
|
||||
FetchContent_Declare(
|
||||
implot
|
||||
URL https://github.com/epezent/implot/archive/refs/tags/v0.17.zip
|
||||
DOWNLOAD_EXTRACT_TIMESTAMP 1)
|
||||
|
||||
FetchContent_MakeAvailable(implot)
|
||||
|
||||
FetchContent_GetProperties(implot SOURCE_DIR IMPLOT_DIR)
|
||||
+10
-6
@@ -3,17 +3,21 @@ include(FetchContent)
|
||||
FetchContent_Declare(
|
||||
libCZI
|
||||
GIT_REPOSITORY https://github.com/ZEISS/libczi.git
|
||||
GIT_TAG 593ee17587214358c535bd036473b1b62945e637
|
||||
GIT_TAG main
|
||||
DOWNLOAD_EXTRACT_TIMESTAMP 1
|
||||
)
|
||||
|
||||
if(NOT libCZI_POPULATED)
|
||||
message(STATUS "Fetching libCZI")
|
||||
FetchContent_MakeAvailable(libCZI)
|
||||
|
||||
set(LIBCZI_BUILD_CZICMD OFF CACHE BOOL "" FORCE)
|
||||
set(LIBCZI_BUILD_DYNLIB OFF CACHE BOOL "" FORCE)
|
||||
set(LIBCZI_BUILD_UNITTESTS OFF CACHE BOOL "" FORCE)
|
||||
set(LIBCZI_DO_NOT_SET_MSVC_RUNTIME_LIBRARY ON CACHE BOOL "" FORCE)
|
||||
set(LIBCZI_BUILD_CZICMD OFF CACHE BOOL "Don't build commandline libCZI." FORCE)
|
||||
set(LIBCZI_BUILD_DYNLIB OFF CACHE BOOL "Don't build libCZI as a shared library." FORCE)
|
||||
set(LIBCZI_BUILD_UNITTESTS OFF CACHE BOOL "Don't build libCZI unit tests." FORCE)
|
||||
set(LIBCZI_BUILD_PREFER_EXTERNALPACKAGE_RAPIDJSON OFF CACHE BOOL "Use internal rapidjson." FORCE)
|
||||
set(LIBCZI_DO_NOT_SET_MSVC_RUNTIME_LIBRARY ON CACHE BOOL "Consumer sets the runtime." FORCE)
|
||||
set(ADDITIONAL_LIBS_REQUIRED_FOR_ATOMIC "" CACHE STRING "Additional atomic libs included." FORCE)
|
||||
|
||||
FetchContent_MakeAvailable(libCZI)
|
||||
endif()
|
||||
|
||||
FetchContent_GetProperties(libCZI)
|
||||
|
||||
@@ -2,10 +2,11 @@ include(FetchContent)
|
||||
FetchContent_Declare(
|
||||
googletest
|
||||
URL https://github.com/google/googletest/archive/refs/tags/v1.14.0.zip
|
||||
DOWNLOAD_EXTRACT_TIMESTAMP 1
|
||||
)
|
||||
|
||||
# From this documentation: https://google.github.io/googletest/quickstart-cmake.html
|
||||
# For Windows: Prevent overriding the parent project's compiler/linker settings
|
||||
|
||||
if(WIN32)
|
||||
set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
|
||||
endif()
|
||||
+14
-8
@@ -2,16 +2,22 @@ PROJECT_NAME = @PIXELARIUM_TITLE@
|
||||
PROJECT_NUMBER = @CMAKE_PROJECT_VERSION@
|
||||
|
||||
OUTPUT_DIRECTORY = @PROJECT_BINARY_DIR@/doc
|
||||
INPUT = @PROJECT_SOURCE_DIR@/lib/app \
|
||||
@PROJECT_SOURCE_DIR@/doc \
|
||||
@PROJECT_SOURCE_DIR@/lib/imaging \
|
||||
@PROJECT_SOURCE_DIR@/lib/imaging/impl \
|
||||
@PROJECT_SOURCE_DIR@/lib/utilities \
|
||||
@PROJECT_SOURCE_DIR@/lib/rendering \
|
||||
@PROJECT_SOURCE_DIR@/lib/resources
|
||||
INPUT = @PROJECT_SOURCE_DIR@/doc/ \
|
||||
@PROJECT_SOURCE_DIR@/lib/app/include \
|
||||
@PROJECT_SOURCE_DIR@/lib/app/rendering/include \
|
||||
@PROJECT_SOURCE_DIR@/lib/imaging/include \
|
||||
@PROJECT_SOURCE_DIR@/lib/imaging/impl/include \
|
||||
@PROJECT_SOURCE_DIR@/lib/utilities/include \
|
||||
@PROJECT_SOURCE_DIR@/lib/resources/include
|
||||
IMAGE_PATH = @PROJECT_SOURCE_DIR@/doc/figures
|
||||
|
||||
DOXYFILE_ENCODING = UTF-8
|
||||
GENERATE_LATEX = NO
|
||||
FULL_PATH_NAMES = NO
|
||||
USE_MDFILE_AS_MAINPAGE = @PROJECT_SOURCE_DIR@/doc/index.md
|
||||
USE_MDFILE_AS_MAINPAGE = @MAINPAGE_FILE@
|
||||
|
||||
|
||||
HTML_EXTRA_STYLESHEET = @AWESOME_CSS_DIR@/doxygen-awesome.css
|
||||
GENERATE_TREEVIEW = YES
|
||||
DISABLE_INDEX = NO
|
||||
FULL_SIDEBAR = NO
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 4.1 MiB |
@@ -52,5 +52,48 @@ If you want to specify compiler settings and options which are not defined in a
|
||||
cmake -B build -S .
|
||||
cmake --build build
|
||||
|
||||
# Usage
|
||||
|
||||
The [examples](https://github.com/m-aXimilian/pixelarium/tree/main/examples) directory aims to showcase a few usage examples of this project.
|
||||
|
||||
All there is to do in order to get an initial window on screen is to create an instance of [`AppGLFW`](https://github.com/m-aXimilian/pixelarium/blob/main/lib/app/include/AppGLFW.hpp) (or one of its child classes) and start it.
|
||||
|
||||
```cpp
|
||||
const auto logger {SpdLogger("logfile.log", "loggername")};
|
||||
ImageResourcePool image_pool;
|
||||
|
||||
auto app {DefaultApp(logger, image_pool)};
|
||||
app.Start();
|
||||
```
|
||||
|
||||
|
||||

|
||||
|
||||
|
||||
## simple
|
||||
|
||||
This is the most straight-forward usage of Pixelarium. It simply instantiates a [`DefaultApp`](https://github.com/m-aXimilian/pixelarium/blob/main/lib/app/include/DefaultApp.hpp) and runs it.
|
||||
|
||||
|
||||
## custom_0
|
||||
|
||||
This is meant to showcase that [`DefaultApp`]((https://github.com/m-aXimilian/pixelarium/blob/main/lib/app/include/DefaultApp.hpp)) ([`AppGLFW`](https://github.com/m-aXimilian/pixelarium/blob/main/lib/app/include/AppGLFW.hpp) as well) can be customized via inheritance.
|
||||
|
||||
As a usage example, it implements a simple binary image reader. It can be presented with a binary file of layout
|
||||
|
||||
```cpp
|
||||
struct ParsedImage
|
||||
{
|
||||
uint8_t depth;
|
||||
uint8_t channels;
|
||||
uint16_t width;
|
||||
uint16_t height;
|
||||
void* data;
|
||||
};
|
||||
```
|
||||
|
||||
i.e., a header encoding 1 byte for the pixel-depth, 1 byte for the channel count, 2 byte each for width and height in pixel followed by the actual pixeldata.
|
||||
|
||||
## custom_1
|
||||
|
||||
An example showcasing how to inject a user defined control into the existing scaffolding of `DefaultApp` using a multiplication filter. This is in many ways similar to the previous example.
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
# Version History
|
||||
|
||||
| Version | Description |
|
||||
|:--------:|:------------------------------------------------------------------------------------------------------------|
|
||||
| 0.0.12 | Build system simplifications, binary image-reader in custom\_0, a simple POC for histograms in views |
|
||||
| 0.0.11 | Miscellaneous refactoring |
|
||||
| 0.0.10 | Adds Tiff-support, in-memory images, and advances usage example "custom_1" |
|
||||
| 0.0.9 | Improve documentation, add example for `DefaultApp` override semantics |
|
||||
| 0.0.8 | Init example projects |
|
||||
| 0.0.7 | Refactors image gallery logic from `DefaultApp` into a separate module |
|
||||
| 0.0.6 | Added documentation-only option `PIXELARIUM_BUILD_DOCS_ONLY`, libCZI upgrade to main branch CI improvements |
|
||||
| 0.0.5 | Compile for C++23 and code style adaptions |
|
||||
| 0.0.4 | Fix MSVC build, some cosmetics, explicit initial window size for images |
|
||||
| 0.0.3 | Fetch subblocks based on the dimension selection sliders |
|
||||
| 0.0.2 | Add Dimension selector sliders to CZI image view |
|
||||
| 0.0.1 | Initiate CZI image view |
|
||||
| 0.0.0 | Initial version |
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
add_subdirectory(simple)
|
||||
add_subdirectory(custom_0)
|
||||
add_subdirectory(custom_1)
|
||||
@@ -0,0 +1,9 @@
|
||||
set(SRC
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/custom_0.cpp)
|
||||
|
||||
set(CUSTOM_0_NAME "${PROJECT_NAME}_custom_app")
|
||||
|
||||
add_executable(${CUSTOM_0_NAME} ${SRC})
|
||||
|
||||
target_link_libraries(${CUSTOM_0_NAME}
|
||||
PRIVATE pixelarium::lib::application_static)
|
||||
@@ -0,0 +1,226 @@
|
||||
#include <opencv2/core/hal/interface.h>
|
||||
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <format>
|
||||
#include <fstream>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
#include "DefaultApp.hpp"
|
||||
#include "ILog.hpp"
|
||||
#include "PixelariumLogger.hpp"
|
||||
#include "PixelariumMem.hpp"
|
||||
#include "imgui.h"
|
||||
#include "implot.h"
|
||||
#include "portable-file-dialogs.h"
|
||||
#include "resource.hpp"
|
||||
|
||||
using namespace pixelarium;
|
||||
using namespace std;
|
||||
using Log = utils::log::ILog;
|
||||
using Pool = resources::ImageResourcePool;
|
||||
|
||||
// setup a logger
|
||||
#ifdef _WIN32
|
||||
auto logger{utils::log::PixelariumLogger("pixellog", string(getenv("APPDATA")) + "/pixelarium/simple_app.log")};
|
||||
#else
|
||||
auto logger{utils::log::PixelariumLogger("pixellog", string(getenv("HOME")) + "/.cache/pixelarium/simple_app.log")};
|
||||
#endif
|
||||
|
||||
// instantiate an image pool for the application
|
||||
resources::ImageResourcePool image_pool;
|
||||
|
||||
constexpr auto ToCVPixelType(size_t depth, size_t chans)
|
||||
{
|
||||
int tp{};
|
||||
switch (depth)
|
||||
{
|
||||
case 8:
|
||||
tp = CV_8U;
|
||||
break;
|
||||
case 16:
|
||||
tp = CV_16U;
|
||||
break;
|
||||
default:
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (chans > 1)
|
||||
{
|
||||
return static_cast<int>(CV_MAKETYPE(tp, chans));
|
||||
}
|
||||
|
||||
return tp;
|
||||
}
|
||||
|
||||
struct StatusReport
|
||||
{
|
||||
const std::function<void(const std::string&)> report_status;
|
||||
const std::function<void()> reset_status;
|
||||
};
|
||||
|
||||
class BinaryReader
|
||||
{
|
||||
private:
|
||||
filesystem::path bin_file{};
|
||||
vector<std::byte> buffer{};
|
||||
uintmax_t file_size;
|
||||
|
||||
#pragma pack(push, 1)
|
||||
struct ParsedImage
|
||||
{
|
||||
uint8_t depth;
|
||||
uint8_t channels;
|
||||
uint16_t width;
|
||||
uint16_t height;
|
||||
void* data;
|
||||
};
|
||||
#pragma pack(pop)
|
||||
|
||||
auto RegisterImage(const ParsedImage& img, string& name, const StatusReport& report) -> void
|
||||
{
|
||||
if (img.width == 0 || img.height == 0 || img.channels == 0 || img.depth == 0 || !img.data)
|
||||
{
|
||||
report.reset_status();
|
||||
report.report_status(
|
||||
format("Parsing {} failed: Dimensions (w: {}, h: {}, d: {}, c: {}) cannot be parsed! The provided "
|
||||
"bin-file is probably corrupted.",
|
||||
name, img.width, img.height, img.depth, img.channels));
|
||||
return;
|
||||
}
|
||||
|
||||
auto tmp_mat =
|
||||
cv::Mat(img.height, img.width, ToCVPixelType(img.depth, img.channels), const_cast<void*>(img.data));
|
||||
// not cloning is a dangling reference once the externally managed data pointer is freed
|
||||
auto mat{tmp_mat.clone()};
|
||||
|
||||
image_pool.SetResource(make_unique<imaging::PixelariumMem>(mat, name.c_str(), logger));
|
||||
}
|
||||
|
||||
auto ReadFile(const filesystem::path& file, const StatusReport& report) -> ParsedImage
|
||||
{
|
||||
uint8_t depth{};
|
||||
uint8_t channels{};
|
||||
uint16_t width{};
|
||||
uint16_t height{};
|
||||
uint64_t pixel_count{};
|
||||
|
||||
if (!filesystem::exists(file)) return {};
|
||||
|
||||
auto sz = filesystem::file_size(file);
|
||||
// header layout of binary file
|
||||
// | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |
|
||||
// | ^ | ^ | ^ | ^ | pixel count in byte |
|
||||
// | |______ |__ |
|
||||
// pixel depth | | height in px
|
||||
// | width in px
|
||||
// channel count
|
||||
constexpr auto header_size{14};
|
||||
|
||||
bool can_read = sz >= header_size;
|
||||
|
||||
if (!can_read) return {};
|
||||
|
||||
if (!buffer.empty())
|
||||
{
|
||||
buffer.clear();
|
||||
}
|
||||
|
||||
ifstream inp_stream(file, ios::binary);
|
||||
if (inp_stream)
|
||||
{
|
||||
inp_stream.read(reinterpret_cast<char*>(&width), sizeof(width));
|
||||
inp_stream.read(reinterpret_cast<char*>(&height), sizeof(height));
|
||||
inp_stream.read(reinterpret_cast<char*>(&depth), sizeof(depth));
|
||||
inp_stream.read(reinterpret_cast<char*>(&channels), sizeof(channels));
|
||||
inp_stream.read(reinterpret_cast<char*>(&pixel_count), sizeof(pixel_count));
|
||||
logger.Info(format("{}(): Pixel count {}", __FUNCTION__, pixel_count));
|
||||
|
||||
if (pixel_count <= sz - header_size)
|
||||
{
|
||||
buffer.resize(pixel_count);
|
||||
inp_stream.read(reinterpret_cast<char*>(buffer.data()), pixel_count);
|
||||
}
|
||||
}
|
||||
|
||||
logger.Info(format("{}: Parsed image with width: {}, height: {}, depth: {}, channels: {}", __PRETTY_FUNCTION__,
|
||||
width, height, depth, channels));
|
||||
report.report_status(
|
||||
format("Parsed image with width: {}, height: {}, depth: {}, channels: {}", width, height, depth, channels));
|
||||
|
||||
return {.depth = depth, .channels = channels, .width = width, .height = height, .data = buffer.data()};
|
||||
}
|
||||
|
||||
public:
|
||||
auto Present(const StatusReport& report) -> void
|
||||
{
|
||||
using namespace ImGui;
|
||||
SetNextWindowSize({256, 124});
|
||||
Begin("Load Binary File");
|
||||
if (Button("Load File"))
|
||||
{
|
||||
auto res{pfd::open_file("Load Inputs", pfd::path::home(), {"Bin Files", "*.bin"}).result()};
|
||||
if (!res.empty()) bin_file = filesystem::path(res.at(0));
|
||||
}
|
||||
|
||||
if (filesystem::exists(bin_file))
|
||||
{
|
||||
file_size = filesystem::file_size(bin_file);
|
||||
Text("File: %s (%ju)", bin_file.filename().c_str(), file_size);
|
||||
if (Button("Parse File"))
|
||||
{
|
||||
auto buff = ReadFile(bin_file, report);
|
||||
auto name = bin_file.filename().string();
|
||||
RegisterImage(buff, name, report);
|
||||
}
|
||||
}
|
||||
|
||||
End();
|
||||
}
|
||||
};
|
||||
|
||||
// create a custom app inheriting from the library's default app
|
||||
class MyApp : public application::DefaultApp
|
||||
{
|
||||
private:
|
||||
BinaryReader bin_read;
|
||||
bool plot_demop_{false};
|
||||
|
||||
public:
|
||||
MyApp(const Log& log, Pool& pool) : application::DefaultApp(log, pool) {}
|
||||
~MyApp() {}
|
||||
|
||||
// override some of the defaults member functions
|
||||
void Run() override;
|
||||
void MenuBarOptionsColumn1() override;
|
||||
void MenuBarOptionsColumn2() override {};
|
||||
};
|
||||
|
||||
int main()
|
||||
{
|
||||
// some initial log message
|
||||
logger.Info(std::format("{}: Starting Application {}", __FUNCTION__, "Pixelarium"));
|
||||
|
||||
// create a custom application, inject its dependencies and start it
|
||||
auto app{MyApp(logger, image_pool)};
|
||||
|
||||
app.Start();
|
||||
}
|
||||
|
||||
void MyApp::Run()
|
||||
{
|
||||
this->gallery_.RenderGallery();
|
||||
this->gallery_.RenderImages();
|
||||
const auto reporter =
|
||||
StatusReport{.report_status = [this](const std::string& msg) { this->SetStatusTimed(msg, 5); },
|
||||
.reset_status = [this]() { this->ResetStatus(); }};
|
||||
bin_read.Present(reporter);
|
||||
|
||||
if (plot_demop_)
|
||||
{
|
||||
ImPlot::ShowDemoWindow(&plot_demop_);
|
||||
}
|
||||
}
|
||||
|
||||
void MyApp::MenuBarOptionsColumn1() { ImGui::MenuItem("Show Plotdemos", NULL, &this->plot_demop_); }
|
||||
@@ -0,0 +1,9 @@
|
||||
set(SRC
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/custom_1.cpp)
|
||||
|
||||
set(CUSTOM_1_NAME "${PROJECT_NAME}_custom1_app")
|
||||
|
||||
add_executable(${CUSTOM_1_NAME} ${SRC})
|
||||
|
||||
target_link_libraries(${CUSTOM_1_NAME}
|
||||
PRIVATE pixelariumapplicationlib)
|
||||
@@ -0,0 +1,147 @@
|
||||
#include <opencv2/core/hal/interface.h>
|
||||
|
||||
#include <ctime>
|
||||
#include <memory>
|
||||
#include <opencv2/core/base.hpp>
|
||||
#include <opencv2/core/mat.hpp>
|
||||
#include <opencv2/imgproc.hpp>
|
||||
#include <string>
|
||||
|
||||
#include "DefaultApp.hpp"
|
||||
#include "ILog.hpp"
|
||||
#include "IPixelariumImage.hpp"
|
||||
#include "PixelariumMem.hpp"
|
||||
#include "SpdLogger.hpp"
|
||||
#include "imgui.h"
|
||||
#include "resource.hpp"
|
||||
|
||||
using namespace pixelarium;
|
||||
using namespace std;
|
||||
using Log = utils::log::ILog;
|
||||
using Pool = resources::ImageResourcePool;
|
||||
|
||||
// setup a logger
|
||||
#ifdef _WIN32
|
||||
unique_ptr<Log> logger{
|
||||
make_unique<utils::log::SpdLogger>(string(getenv("APPDATA")) + "/pixelarium/simple_app.log", "default")};
|
||||
#else
|
||||
unique_ptr<Log> logger{
|
||||
make_unique<utils::log::SpdLogger>(string(getenv("HOME")) + "/.cache/pixelarium/simple_app.log", "default")};
|
||||
#endif
|
||||
|
||||
// instantiate an image pool for the application
|
||||
resources::ImageResourcePool image_pool;
|
||||
|
||||
class Selector
|
||||
{
|
||||
using Pool = resources::ImageResourcePool;
|
||||
Pool& pool_;
|
||||
std::string preview_0_{"None"};
|
||||
std::string preview_1_{"None"};
|
||||
resources::ResourceKey selected_key_0;
|
||||
resources::ResourceKey selected_key_1;
|
||||
int idx_{0};
|
||||
|
||||
public:
|
||||
Selector(resources::ImageResourcePool& pool) : pool_(pool) {}
|
||||
void SelectImage()
|
||||
{
|
||||
ImGui::Begin("Image Multiply");
|
||||
static int selected_idx_0{0};
|
||||
static int selected_idx_1{0};
|
||||
if (ImGui::BeginCombo("Select first image", preview_0_.c_str()))
|
||||
{
|
||||
pool_.Enumerate(
|
||||
[&](resources::ResourceKey key, size_t idx, const imaging::IPixelariumImage<cv::Mat>& img) -> void
|
||||
{
|
||||
const bool is_selected = static_cast<int>(idx) == selected_idx_0;
|
||||
if (ImGui::Selectable(img.Name().c_str(), is_selected))
|
||||
{
|
||||
selected_idx_0 = idx;
|
||||
preview_0_ = img.Name();
|
||||
selected_key_0 = key;
|
||||
}
|
||||
|
||||
if (is_selected)
|
||||
{
|
||||
ImGui::SetItemDefaultFocus();
|
||||
}
|
||||
});
|
||||
|
||||
ImGui::EndCombo();
|
||||
}
|
||||
|
||||
if (ImGui::BeginCombo("Select second image", preview_1_.c_str()))
|
||||
{
|
||||
pool_.Enumerate(
|
||||
[&](resources::ResourceKey key, size_t idx, const imaging::IPixelariumImage<cv::Mat>& img) -> void
|
||||
{
|
||||
const bool is_selected = static_cast<int>(idx) == selected_idx_1;
|
||||
if (ImGui::Selectable(img.Name().c_str(), is_selected))
|
||||
{
|
||||
selected_idx_1 = idx;
|
||||
preview_1_ = img.Name();
|
||||
selected_key_1 = key;
|
||||
}
|
||||
|
||||
if (is_selected)
|
||||
{
|
||||
ImGui::SetItemDefaultFocus();
|
||||
}
|
||||
});
|
||||
|
||||
ImGui::EndCombo();
|
||||
}
|
||||
|
||||
if (ImGui::Button("Process"))
|
||||
{
|
||||
auto img0 = pool_.GetResource(selected_key_0);
|
||||
auto img_mat0 = img0.lock()->TryGetImage();
|
||||
auto img1 = pool_.GetResource(selected_key_1);
|
||||
auto img_mat1 = img1.lock()->TryGetImage();
|
||||
|
||||
if (!img_mat0.has_value() || !img_mat1.has_value() || img_mat0.value().empty() || img_mat1.value().empty())
|
||||
return;
|
||||
|
||||
if (img_mat0->size != img_mat1->size) return;
|
||||
|
||||
cv::multiply(img_mat0.value(), img_mat1.value(), img_mat0.value());
|
||||
|
||||
std::string name{std::format("Multiply_{}", idx_)};
|
||||
pool_.SetResource(std::make_unique<imaging::PixelariumMem>(*img_mat0, name, *logger));
|
||||
|
||||
++idx_;
|
||||
}
|
||||
|
||||
ImGui::End();
|
||||
}
|
||||
};
|
||||
|
||||
// create a custom app inheriting from the library's default app
|
||||
class MyApp : public application::DefaultApp
|
||||
{
|
||||
Selector select_;
|
||||
|
||||
public:
|
||||
MyApp(const Log& log, Pool& pool) : application::DefaultApp(log, pool), select_(pool) {}
|
||||
|
||||
// override some of the defaults member functions
|
||||
void Run() override;
|
||||
};
|
||||
|
||||
int main()
|
||||
{
|
||||
// some initial log message
|
||||
logger->Info(std::format("{}: Starting Application {}", __FUNCTION__, "Pixelarium"));
|
||||
|
||||
// create a custom application, inject its dependencies and start it
|
||||
auto app{MyApp(*logger, image_pool)};
|
||||
|
||||
app.Start();
|
||||
}
|
||||
|
||||
void MyApp::Run()
|
||||
{
|
||||
application::DefaultApp::Run();
|
||||
select_.SelectImage();
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
set(SRC
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/simple.cpp)
|
||||
|
||||
set(SIMPLE_NAME "${PROJECT_NAME}_SIMPLE")
|
||||
|
||||
add_executable(${SIMPLE_NAME} ${SRC})
|
||||
|
||||
target_link_libraries(${SIMPLE_NAME}
|
||||
PRIVATE pixelariumapplicationlib)
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
#include <memory>
|
||||
|
||||
#include "DefaultApp.hpp"
|
||||
#include "ILog.hpp"
|
||||
#include "SpdLogger.hpp"
|
||||
#include "resource.hpp"
|
||||
|
||||
using namespace pixelarium;
|
||||
using namespace std;
|
||||
using Log = utils::log::ILog;
|
||||
using Pool = resources::ImageResourcePool;
|
||||
|
||||
// setup a logger
|
||||
#ifdef _WIN32
|
||||
const auto logger{utils::log::SpdLogger(string(getenv("APPDATA")) + "/pixelarium/simple_app.log", "default")};
|
||||
#else
|
||||
const auto logger{
|
||||
utils::log::SpdLogger(string(getenv("HOME")) + "/.cache/pixelarium/simple_app.log", "default")};
|
||||
#endif
|
||||
|
||||
int main()
|
||||
{
|
||||
// some initial log message and default log level setting
|
||||
logger.Info(format("{}: Starting Application {}", __FUNCTION__, "Pixelarium"));
|
||||
logger.ChangeLevel(utils::log::LogLevel::kDebug);
|
||||
|
||||
// instantiate an image pool for the application
|
||||
resources::ImageResourcePool image_pool;
|
||||
|
||||
// create an application, inject its dependencies and start it
|
||||
auto app{application::DefaultApp(logger, image_pool)};
|
||||
app.Start();
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
add_subdirectory(utilities)
|
||||
add_subdirectory(imaging)
|
||||
add_subdirectory(rendering)
|
||||
add_subdirectory(resources)
|
||||
add_subdirectory(app)
|
||||
|
||||
+74
-18
@@ -4,6 +4,56 @@
|
||||
#include "imgui.h"
|
||||
#include "imgui_impl_glfw.h"
|
||||
#include "imgui_impl_opengl3.h"
|
||||
#include "imgui_internal.h"
|
||||
#include "simple_thread_pool.hpp"
|
||||
|
||||
// see https://github.com/ocornut/imgui/issues/3518
|
||||
bool PixelBeginStatusBar()
|
||||
{
|
||||
using namespace ImGui;
|
||||
ImGuiContext& g = *GImGui;
|
||||
ImGuiViewportP* viewport = (ImGuiViewportP*)(void*)GetMainViewport();
|
||||
|
||||
SetCurrentViewport(NULL, viewport);
|
||||
|
||||
g.NextWindowData.MenuBarOffsetMinVal = ImVec2(
|
||||
g.Style.DisplaySafeAreaPadding.x, ImMax(g.Style.DisplaySafeAreaPadding.y - g.Style.FramePadding.y, 0.0f));
|
||||
ImGuiWindowFlags window_flags =
|
||||
ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_MenuBar;
|
||||
float height = GetFrameHeight();
|
||||
bool is_open = BeginViewportSideBar("##MainStatusBar", viewport, ImGuiDir_Up, height, window_flags);
|
||||
g.NextWindowData.MenuBarOffsetMinVal = ImVec2(0.0f, 0.0f);
|
||||
if (!is_open)
|
||||
{
|
||||
End();
|
||||
return false;
|
||||
}
|
||||
|
||||
g.CurrentWindow->Flags &= ~ImGuiWindowFlags_NoSavedSettings;
|
||||
BeginMenuBar();
|
||||
return is_open;
|
||||
}
|
||||
|
||||
void PixelEndStatusBar()
|
||||
{
|
||||
using namespace ImGui;
|
||||
ImGuiContext& g = *GImGui;
|
||||
if (!g.CurrentWindow->DC.MenuBarAppending)
|
||||
{
|
||||
IM_ASSERT_USER_ERROR(0, "Calling EndMainMenuBar() not from a menu-bar!");
|
||||
return;
|
||||
}
|
||||
|
||||
EndMenuBar();
|
||||
g.CurrentWindow->Flags |= ImGuiWindowFlags_NoSavedSettings;
|
||||
|
||||
if (g.CurrentWindow == g.NavWindow && g.NavLayer == ImGuiNavLayer_Main && !g.NavAnyRequest && g.ActiveId == 0)
|
||||
FocusTopMostWindowUnderOne(
|
||||
g.NavWindow, NULL, NULL,
|
||||
ImGuiFocusRequestFlags_UnlessBelowModal | ImGuiFocusRequestFlags_RestoreFocusedChild);
|
||||
|
||||
End();
|
||||
}
|
||||
|
||||
/// @brief GLFW error callback function.
|
||||
/// @param error The error code.
|
||||
@@ -84,14 +134,10 @@ void pixelarium::application::AppGLFW::InitMainWindow()
|
||||
IMGUI_CHECKVERSION();
|
||||
ImGui::CreateContext();
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
(void)io;
|
||||
io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls
|
||||
io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls
|
||||
io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; // Enable Docking
|
||||
io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable; // Enable Multi-Viewport / Platform
|
||||
// Windows
|
||||
// io.ConfigViewportsNoAutoMerge = true;
|
||||
// io.ConfigViewportsNoTaskBarIcon = true;
|
||||
|
||||
// Setup Dear ImGui style
|
||||
ImGui::StyleColorsDark();
|
||||
@@ -168,20 +214,7 @@ void pixelarium::application::AppGLFW::MenuBar()
|
||||
// main menu
|
||||
if (ImGui::BeginMenu(MAINMENUNAME))
|
||||
{
|
||||
if (ImGui::BeginCombo(LOGLEVELSELECT, LOGLEVELS[log_level_].data()))
|
||||
{
|
||||
for (int n = 0; n < static_cast<int>(LOGLEVELS.size()); n++)
|
||||
{
|
||||
bool is_selected = (LOGLEVELS[log_level_] == LOGLEVELS[n]);
|
||||
if (ImGui::Selectable(LOGLEVELS[n].data(), is_selected))
|
||||
{
|
||||
log_level_ = n;
|
||||
this->logger_.ChangeLevel(static_cast<utils::log::LogLevel>(1 << log_level_));
|
||||
}
|
||||
if (is_selected) ImGui::SetItemDefaultFocus();
|
||||
}
|
||||
ImGui::EndCombo();
|
||||
}
|
||||
LogLevelSelect();
|
||||
|
||||
// consumer main menu bar entries
|
||||
this->MenuBarOptionsColumn1();
|
||||
@@ -197,6 +230,18 @@ void pixelarium::application::AppGLFW::MenuBar()
|
||||
|
||||
ImGui::EndMainMenuBar();
|
||||
}
|
||||
|
||||
if (show_status_ && PixelBeginStatusBar())
|
||||
{
|
||||
if (ImGui::Button("Ok", {20, 20}))
|
||||
{
|
||||
show_status_ = false;
|
||||
status_message_.clear();
|
||||
}
|
||||
|
||||
ImGui::Text("%s", status_message_.c_str());
|
||||
PixelEndStatusBar();
|
||||
}
|
||||
}
|
||||
|
||||
/// @brief Allows the user to select the log level via a combo box.
|
||||
@@ -217,3 +262,14 @@ void pixelarium::application::AppGLFW::LogLevelSelect()
|
||||
ImGui::EndCombo();
|
||||
}
|
||||
}
|
||||
|
||||
void pixelarium::application::AppGLFW::SetStatusTimed(const std::string& status, size_t seconds)
|
||||
{
|
||||
SetStatus(status);
|
||||
utils::pixelarium_pool::enqueue(
|
||||
[this, seconds]()
|
||||
{
|
||||
std::this_thread::sleep_for(std::chrono::seconds(seconds));
|
||||
ResetStatus();
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,37 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <GLFW/glfw3.h>
|
||||
|
||||
#include <memory>
|
||||
|
||||
#include "imgui.h"
|
||||
#include "utilities/ILog.hpp"
|
||||
|
||||
namespace pixelarium::application
|
||||
{
|
||||
class AppGLFW
|
||||
{
|
||||
public:
|
||||
explicit AppGLFW(const utils::log::ILog& log) : logger_(log) { this->InitMainWindow(); }
|
||||
|
||||
void Start() { this->RunLoop(); }
|
||||
|
||||
protected:
|
||||
virtual void MenuBarOptionsColumn1() {}
|
||||
virtual void MenuBarOptionsColumn2() {}
|
||||
virtual void MenuBarOptionsColumn3() {}
|
||||
virtual void MenuBarOptionsColumn4() {}
|
||||
virtual void MenuBarOptionsColumn5() {}
|
||||
virtual void Run() {}
|
||||
|
||||
const utils::log::ILog& logger_;
|
||||
|
||||
private:
|
||||
int RunLoop();
|
||||
void InitMainWindow();
|
||||
void MenuBar();
|
||||
void LogLevelSelect();
|
||||
int log_level_{0};
|
||||
GLFWwindow* window = nullptr;
|
||||
};
|
||||
} // namespace pixelarium::application
|
||||
+56
-16
@@ -1,28 +1,65 @@
|
||||
# Fetch implot
|
||||
include(implot)
|
||||
message(STATUS "IMPLOT sources at ${IMPLOT_DIR}")
|
||||
|
||||
configure_file(${CMAKE_CURRENT_SOURCE_DIR}/app_resources_default.h.in
|
||||
${CMAKE_BINARY_DIR}/app_resources_default.h @ONLY)
|
||||
|
||||
set(IMPLOTSRC
|
||||
"${IMPLOT_DIR}/implot.h"
|
||||
"${IMPLOT_DIR}/implot_internal.h"
|
||||
"${IMPLOT_DIR}/implot_items.cpp"
|
||||
"${IMPLOT_DIR}/implot.cpp"
|
||||
"${IMPLOT_DIR}/implot_demo.cpp"
|
||||
)
|
||||
|
||||
set(IMGUISRC
|
||||
"${imgui_DIR}/imgui.cpp"
|
||||
"${imgui_DIR}/misc/cpp/imgui_stdlib.cpp"
|
||||
"${imgui_DIR}/imgui_demo.cpp"
|
||||
"${imgui_DIR}/imgui_draw.cpp"
|
||||
"${imgui_DIR}/imgui_tables.cpp"
|
||||
"${imgui_DIR}/imgui_widgets.cpp"
|
||||
"${imgui_DIR}/backends/imgui_impl_opengl3.cpp"
|
||||
"${imgui_DIR}/backends/imgui_impl_glfw.cpp")
|
||||
|
||||
set(APPLIBSRC
|
||||
AppGLFW.hpp
|
||||
include/imgui_proxy.hpp
|
||||
include/AppGLFW.hpp
|
||||
include/DefaultApp.hpp
|
||||
include/PixelariumGallery.hpp
|
||||
AppGLFW.cpp
|
||||
DefaultApp.hpp
|
||||
DefaultApp.cpp
|
||||
${imgui_DIR}/imgui.cpp
|
||||
${imgui_DIR}/imgui_demo.cpp
|
||||
${imgui_DIR}/imgui_draw.cpp
|
||||
${imgui_DIR}/imgui_tables.cpp
|
||||
${imgui_DIR}/imgui_widgets.cpp
|
||||
${imgui_DIR}/backends/imgui_impl_opengl3.cpp
|
||||
${imgui_DIR}/backends/imgui_impl_glfw.cpp)
|
||||
PixelariumGallery.cpp)
|
||||
|
||||
set(RENDERSRC
|
||||
rendering/include/RenderHelpers.hpp
|
||||
rendering/include/RenderImageManager.hpp
|
||||
rendering/include/CvMatRender.hpp
|
||||
rendering/include/IPixelariumImageView.hpp
|
||||
rendering/include/PixelariumImageViewDefault.hpp
|
||||
rendering/include/PixelariumImageViewCzi.hpp
|
||||
rendering/include/ImageViewFactory.hpp
|
||||
rendering/RenderHelpers.cpp
|
||||
rendering/CvMatRender.cpp
|
||||
rendering/IPixelariumImageView.cpp
|
||||
rendering/RenderImageManager.cpp
|
||||
rendering/PixelariumImageViewDefault.cpp
|
||||
rendering/PixelariumImageViewCzi.cpp
|
||||
rendering/ImageViewFactory.cpp)
|
||||
|
||||
set(APPLIBNAME pixelariumapplicationlib)
|
||||
|
||||
add_library(${APPLIBNAME}
|
||||
STATIC ${APPLIBSRC})
|
||||
STATIC ${APPLIBSRC} ${IMGUISRC} ${IMPLOTSRC} ${RENDERSRC})
|
||||
|
||||
add_library(pixelarium::lib::application_static ALIAS ${APPLIBNAME})
|
||||
|
||||
target_link_libraries(${APPLIBNAME}
|
||||
PRIVATE pixelariumutilslib
|
||||
PRIVATE pixelariumimagelib
|
||||
PRIVATE pixelariumrenderlib)
|
||||
PUBLIC
|
||||
pixelarium::lib::utilities_static
|
||||
pixelarium::lib::imaging_static
|
||||
pixelarium::lib::resources_static)
|
||||
|
||||
# This needs to be public to let the consumer know about it.
|
||||
if(WIN32)
|
||||
@@ -42,9 +79,12 @@ if(APPLE)
|
||||
endif()
|
||||
|
||||
target_include_directories(${APPLIBNAME}
|
||||
INTERFACE
|
||||
PRIVATE ${CMAKE_BINARY_DIR}
|
||||
PRIVATE ${PROJECT_SOURCE_DIR}/lib
|
||||
PRIVATE ${PROJECT_SOURCE_DIR}/lib/imaging
|
||||
PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/rendering/include
|
||||
PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include
|
||||
PUBLIC ${pfd_DIR}
|
||||
PUBLIC ${imgui_DIR}
|
||||
PUBLIC ${imgui_DIR}/backends)
|
||||
PUBLIC ${imgui_DIR}/misc/cpp
|
||||
PUBLIC ${imgui_DIR}/backends
|
||||
${IMPLOT_DIR})
|
||||
|
||||
+11
-90
@@ -2,124 +2,45 @@
|
||||
|
||||
#include <cstddef>
|
||||
#include <format>
|
||||
#include <memory>
|
||||
|
||||
#include "ILog.hpp"
|
||||
#include "PixelariumImageFactory.hpp"
|
||||
#include "app_resources_default.h"
|
||||
#include "imgui.h"
|
||||
#include "portable-file-dialogs.h"
|
||||
#include "rendering/RenderImageManager.hpp"
|
||||
#include "resources/resource.hpp"
|
||||
#include "utilities/ILog.hpp"
|
||||
#include "resource.hpp"
|
||||
|
||||
using namespace pixelarium::imaging;
|
||||
using namespace pixelarium::application;
|
||||
|
||||
void pixelarium::ui::DefaultApp::MenuBarOptionsColumn1()
|
||||
void DefaultApp::MenuBarOptionsColumn1()
|
||||
{
|
||||
ImGui::MenuItem(SHOWIMGUIDEMOS, NULL, &this->demop_);
|
||||
ImGui::MenuItem(SHOWIMAGEGALLERY, NULL, &this->image_listp_);
|
||||
}
|
||||
|
||||
void pixelarium::ui::DefaultApp::MenuBarOptionsColumn2()
|
||||
void DefaultApp::MenuBarOptionsColumn2()
|
||||
{
|
||||
if (ImGui::BeginMenu(FILEMENUNAME))
|
||||
{
|
||||
if (ImGui::MenuItem(LOADIMAGE))
|
||||
{
|
||||
this->LoadImage();
|
||||
this->LoadImageDialogue();
|
||||
}
|
||||
|
||||
ImGui::EndMenu();
|
||||
}
|
||||
}
|
||||
|
||||
void pixelarium::ui::DefaultApp::Run()
|
||||
void DefaultApp::Run()
|
||||
{
|
||||
if (demop_) ImGui::ShowDemoWindow(&this->demop_);
|
||||
if (image_listp_) this->ImageGalleryRender();
|
||||
if (image_listp_) this->gallery_.RenderGallery();
|
||||
|
||||
this->RenderImages();
|
||||
this->gallery_.RenderImages();
|
||||
}
|
||||
|
||||
void pixelarium::ui::DefaultApp::RenderImages()
|
||||
{
|
||||
this->render_manager_->Enumerate(
|
||||
[&](resources::ResourceKey key, render::RenderImageStateWrapper& render_state)
|
||||
{
|
||||
render_state.view->ShowImage();
|
||||
|
||||
if (!*render_state.view->GetStatus())
|
||||
{
|
||||
this->render_manager_->MarkForDeletion(key);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void pixelarium::ui::DefaultApp::ImageGalleryRender()
|
||||
{
|
||||
ImGui::SetNextWindowSize(ImVec2(300, 550));
|
||||
ImGui::Begin(SHOWIMAGEGALLERY, &this->image_listp_);
|
||||
|
||||
// this updates the render collection
|
||||
// essentially deleting render views that were
|
||||
// marked for deletion
|
||||
this->render_manager_->UpdateCollection();
|
||||
|
||||
static size_t selected_index{0};
|
||||
int highlight_index{-1};
|
||||
|
||||
if (ImGui::BeginListBox("Image List", ImVec2(200, 400)))
|
||||
{
|
||||
pool_.EnumerateResources(
|
||||
[&](size_t id, size_t idx, const imaging::IPixelariumImage& img) -> void
|
||||
{
|
||||
const bool is_selected = selected_index == idx;
|
||||
if (ImGui::Selectable(std::format("{}", img.Name()).c_str(), is_selected))
|
||||
{
|
||||
selected_index = idx;
|
||||
this->selected_image_ = id;
|
||||
}
|
||||
if (highlight_index && ImGui::IsItemHovered()) highlight_index = idx;
|
||||
|
||||
if (is_selected) ImGui::SetItemDefaultFocus();
|
||||
});
|
||||
|
||||
ImGui::EndListBox();
|
||||
}
|
||||
|
||||
ImGui::Checkbox(AUTOSHOWSELECTED, &this->auto_show_selectd_image_);
|
||||
ImGui::SameLine(); // put the button next to the checkbox
|
||||
// note that the button will only show when the checkbox is toggled off
|
||||
// this is intended behavior as the selected image will render automatically
|
||||
// when the checkbox is toggled on
|
||||
if (this->auto_show_selectd_image_ || ImGui::Button(OPENIMAGE))
|
||||
{
|
||||
// Try add the selected index to the manager
|
||||
this->render_manager_->Add(this->selected_image_);
|
||||
}
|
||||
|
||||
if (ImGui::Button(LOADIMAGE))
|
||||
{
|
||||
this->LoadImage();
|
||||
}
|
||||
|
||||
if (ImGui::Button(REMOVEIMAGE))
|
||||
{
|
||||
this->render_manager_->MarkForDeletion(this->selected_image_);
|
||||
this->pool_.DeleteResource(this->selected_image_);
|
||||
}
|
||||
|
||||
ImGui::SameLine();
|
||||
if (ImGui::Button(CLEARALL))
|
||||
{
|
||||
this->render_manager_->Clear();
|
||||
this->pool_.Clear();
|
||||
}
|
||||
|
||||
ImGui::End(); // end gallery window
|
||||
}
|
||||
|
||||
void pixelarium::ui::DefaultApp::LoadImage()
|
||||
void DefaultApp::LoadImageDialogue()
|
||||
{
|
||||
auto res{pfd::open_file("Load Inputs", pfd::path::home(), {"All Files", "*"}, pfd::opt::multiselect).result()};
|
||||
for (auto& p : res)
|
||||
@@ -128,7 +49,7 @@ void pixelarium::ui::DefaultApp::LoadImage()
|
||||
|
||||
try
|
||||
{
|
||||
pool_.SetResource(PixelariumImageFactory::CreateImage(p));
|
||||
pool_.SetResource(PixelariumImageFactory::CreateImage(p, logger_));
|
||||
}
|
||||
catch (pixelarium::resources::empty_resource_exception& e)
|
||||
{
|
||||
|
||||
@@ -1,43 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
#include <memory>
|
||||
|
||||
#include "AppGLFW.hpp"
|
||||
#include "imgui.h"
|
||||
#include "rendering/RenderImageManager.hpp"
|
||||
#include "resources/resource.hpp"
|
||||
#include "utilities/ILog.hpp"
|
||||
|
||||
namespace pixelarium::ui
|
||||
{
|
||||
class DefaultApp : public application::AppGLFW
|
||||
{
|
||||
public:
|
||||
DefaultApp(const utils::log::ILog& log, pixelarium::resources::ImageResourcePool& pool)
|
||||
: application::AppGLFW(log),
|
||||
pool_(pool),
|
||||
render_manager_(std::make_unique<render::RenderImageManager>(pool, log))
|
||||
{
|
||||
}
|
||||
|
||||
protected:
|
||||
void MenuBarOptionsColumn1() override;
|
||||
void MenuBarOptionsColumn2() override;
|
||||
void Run() override;
|
||||
|
||||
private:
|
||||
void LoadImage();
|
||||
void ImageGalleryRender();
|
||||
void RenderImages();
|
||||
|
||||
private:
|
||||
resources::ImageResourcePool& pool_;
|
||||
std::unique_ptr<render::RenderImageManager> render_manager_;
|
||||
bool image_listp_{true};
|
||||
bool auto_show_selectd_image_{true};
|
||||
bool demop_{false};
|
||||
ImVec2 curr_dim_;
|
||||
size_t selected_image_{0};
|
||||
};
|
||||
} // namespace pixelarium::ui
|
||||
@@ -0,0 +1,86 @@
|
||||
#include "PixelariumGallery.hpp"
|
||||
|
||||
#include <format>
|
||||
|
||||
#include "app_resources_default.h"
|
||||
#include "imgui.h"
|
||||
|
||||
using namespace pixelarium::application;
|
||||
|
||||
void PixelariumImageGallery::RenderGallery()
|
||||
{
|
||||
ImGui::SetNextWindowSize(ImVec2(300, 550));
|
||||
ImGui::Begin(SHOWIMAGEGALLERY, &this->image_listp_);
|
||||
|
||||
// this updates the render collection
|
||||
// essentially deleting render views that were
|
||||
// marked for deletion
|
||||
this->render_manager_->UpdateCollection();
|
||||
|
||||
static size_t selected_index{0};
|
||||
int highlight_index{-1};
|
||||
|
||||
if (ImGui::BeginListBox("Image List", ImVec2(200, 400)))
|
||||
{
|
||||
pool_.EnumerateResources(
|
||||
[&](size_t id, size_t idx, const imaging::IPixelariumImage<cv::Mat>& img) -> void
|
||||
{
|
||||
const bool is_selected = selected_index == idx;
|
||||
if (ImGui::Selectable(std::format("{}", img.Name()).c_str(), is_selected))
|
||||
{
|
||||
selected_index = idx;
|
||||
this->selected_image_ = id;
|
||||
}
|
||||
if (highlight_index && ImGui::IsItemHovered()) highlight_index = idx;
|
||||
|
||||
if (is_selected) ImGui::SetItemDefaultFocus();
|
||||
});
|
||||
|
||||
ImGui::EndListBox();
|
||||
}
|
||||
|
||||
ImGui::Checkbox(AUTOSHOWSELECTED, &this->auto_show_selectd_image_);
|
||||
ImGui::SameLine(); // put the button next to the checkbox
|
||||
// note that the button will only show when the checkbox is toggled off
|
||||
// this is intended behavior as the selected image will render automatically
|
||||
// when the checkbox is toggled on
|
||||
if (this->auto_show_selectd_image_ || ImGui::Button(OPENIMAGE))
|
||||
{
|
||||
// Try add the selected index to the manager
|
||||
this->render_manager_->Add(this->selected_image_);
|
||||
}
|
||||
|
||||
if (ImGui::Button(LOADIMAGE))
|
||||
{
|
||||
this->load_image_();
|
||||
}
|
||||
|
||||
if (ImGui::Button(REMOVEIMAGE))
|
||||
{
|
||||
this->render_manager_->MarkForDeletion(this->selected_image_);
|
||||
this->pool_.DeleteResource(this->selected_image_);
|
||||
}
|
||||
|
||||
ImGui::SameLine();
|
||||
if (ImGui::Button(CLEARALL))
|
||||
{
|
||||
this->render_manager_->Clear();
|
||||
this->pool_.Clear();
|
||||
}
|
||||
|
||||
ImGui::End(); // end gallery window
|
||||
}
|
||||
|
||||
void PixelariumImageGallery::RenderImages()
|
||||
{
|
||||
this->render_manager_->Enumerate(
|
||||
[&](resources::ResourceKey key, application::RenderImageStateWrapper& render_state)
|
||||
{
|
||||
render_state.view->ShowImage();
|
||||
|
||||
if (!*render_state.view->GetStatus())
|
||||
{
|
||||
this->render_manager_->MarkForDeletion(key);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -17,6 +17,9 @@
|
||||
#define LOADIMAGE "Load Image"
|
||||
#define REMOVEIMAGE "Remove Image"
|
||||
#define CLEARALL "Clear All"
|
||||
#define SAVEAS "Save As..."
|
||||
// clang-format on
|
||||
|
||||
inline constexpr std::array<std::string_view, 5> LOGLEVELS = {"Trace", "Debug", "Info", "Warning", "Error"};
|
||||
|
||||
inline constexpr auto kInitialWindowWidth {700.0f};
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
#pragma once
|
||||
|
||||
#include <GLFW/glfw3.h>
|
||||
|
||||
#include <format>
|
||||
|
||||
#include "ILog.hpp"
|
||||
#include "imgui_proxy.hpp"
|
||||
|
||||
namespace pixelarium::application
|
||||
{
|
||||
/// @brief Base class providing scaffolding with GLFW and some default
|
||||
/// implementations that can be extended and/or overridden by consumers
|
||||
class AppGLFW
|
||||
{
|
||||
public:
|
||||
explicit AppGLFW(const utils::log::ILog& log) : logger_(log), plot_context_(ImPlot::CreateContext())
|
||||
{
|
||||
this->InitMainWindow();
|
||||
}
|
||||
|
||||
~AppGLFW() { ImPlot::DestroyContext(plot_context_); }
|
||||
|
||||
AppGLFW(AppGLFW&) = delete;
|
||||
AppGLFW(const AppGLFW&) = delete;
|
||||
AppGLFW(AppGLFW&&) = delete;
|
||||
AppGLFW& operator=(AppGLFW&) = delete;
|
||||
AppGLFW& operator=(AppGLFW&&) = delete;
|
||||
|
||||
/// @brief Start the main render loop
|
||||
void Start() { this->RunLoop(); }
|
||||
|
||||
void SetStatusTimed(const std::string& status, size_t second);
|
||||
|
||||
void SetStatus(const std::string& status)
|
||||
{
|
||||
logger_.Info(std::format("{}(): {}", __PRETTY_FUNCTION__, status));
|
||||
status_message_ = status;
|
||||
show_status_ = true;
|
||||
}
|
||||
|
||||
void ResetStatus()
|
||||
{
|
||||
status_message_.clear();
|
||||
show_status_ = false;
|
||||
}
|
||||
|
||||
protected:
|
||||
/// @brief Function implementing the first column of the menu bar (e.g. "Menu")
|
||||
virtual void MenuBarOptionsColumn1() {}
|
||||
|
||||
/// @brief Function implementing the second column of the menu bar (e.g. "File")
|
||||
virtual void MenuBarOptionsColumn2() {}
|
||||
|
||||
/// @brief Function implementing the third column of the menu bar (e.g. "Options")
|
||||
virtual void MenuBarOptionsColumn3() {}
|
||||
|
||||
/// @brief Function implementing the fourth column of the menu bar (e.g. "More")
|
||||
virtual void MenuBarOptionsColumn4() {}
|
||||
|
||||
/// @brief Function implementing the first column of the menu bar (e.g. "Help")
|
||||
virtual void MenuBarOptionsColumn5() {}
|
||||
|
||||
/// @brief Main function that gets called within the render loop.
|
||||
virtual void Run() {}
|
||||
|
||||
const utils::log::ILog& logger_;
|
||||
|
||||
private:
|
||||
int RunLoop();
|
||||
void InitMainWindow();
|
||||
void MenuBar();
|
||||
void LogLevelSelect();
|
||||
int log_level_{0};
|
||||
GLFWwindow* window = nullptr;
|
||||
ImPlotContext* plot_context_ = nullptr;
|
||||
bool show_status_{false};
|
||||
std::string status_message_{};
|
||||
};
|
||||
} // namespace pixelarium::application
|
||||
@@ -0,0 +1,42 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
|
||||
#include "AppGLFW.hpp"
|
||||
#include "ILog.hpp"
|
||||
#include "PixelariumGallery.hpp"
|
||||
#include "imgui_proxy.hpp"
|
||||
#include "resource.hpp"
|
||||
|
||||
namespace pixelarium::application
|
||||
{
|
||||
/// @brief Default implementation of AppGLFW.
|
||||
/// This can either be used as is, as an example or as a base class
|
||||
/// providing some defaults for a more custom implementation.
|
||||
class DefaultApp : public AppGLFW
|
||||
{
|
||||
public:
|
||||
DefaultApp(const utils::log::ILog& log, pixelarium::resources::ImageResourcePool& pool)
|
||||
: application::AppGLFW(log), pool_(pool), gallery_(log, pool)
|
||||
{
|
||||
gallery_.SetLoadFunction([&]() -> void { this->LoadImageDialogue(); });
|
||||
}
|
||||
|
||||
protected:
|
||||
void MenuBarOptionsColumn1() override;
|
||||
void MenuBarOptionsColumn2() override;
|
||||
void Run() override;
|
||||
|
||||
protected:
|
||||
resources::ImageResourcePool& pool_;
|
||||
application::PixelariumImageGallery gallery_;
|
||||
|
||||
protected:
|
||||
void LoadImageDialogue();
|
||||
|
||||
private:
|
||||
bool image_listp_{true};
|
||||
bool demop_{false};
|
||||
ImVec2 curr_dim_;
|
||||
};
|
||||
} // namespace pixelarium::application
|
||||
@@ -0,0 +1,58 @@
|
||||
#pragma once
|
||||
|
||||
#include "ILog.hpp"
|
||||
#include "RenderImageManager.hpp"
|
||||
#include "resource.hpp"
|
||||
|
||||
namespace pixelarium::application
|
||||
{
|
||||
|
||||
/// @brief Defines a concept for a gallery type
|
||||
/// @tparam P The resource pool type of the gallery concept
|
||||
template <typename P, class D>
|
||||
concept GalleryT = requires(P& p) { static_cast<resources::IResourcePool<P, D>&>(p); };
|
||||
|
||||
/// @brief Interface for a Pixelarium gallery.
|
||||
///
|
||||
/// Defines generic functionality for a gallery of a specific
|
||||
/// resource type given by the template argument.
|
||||
/// @tparam GalleryT The type of IResourcePool that the given implementation
|
||||
/// provides a gallery for.
|
||||
template <typename GalleryT>
|
||||
class IPixelariumGallery
|
||||
{
|
||||
public:
|
||||
virtual ~IPixelariumGallery() = default;
|
||||
virtual void RenderGallery() = 0;
|
||||
};
|
||||
|
||||
/// @brief Implements IPixelariumGallery for a ImageResourcePool
|
||||
class PixelariumImageGallery : IPixelariumGallery<resources::ImageResourcePool>
|
||||
{
|
||||
using Pool = resources::ImageResourcePool;
|
||||
using Log = utils::log::ILog;
|
||||
|
||||
public:
|
||||
PixelariumImageGallery(const Log& log, resources::ImageResourcePool& pool)
|
||||
: pool_{pool}, log_{log}, render_manager_(std::make_unique<application::RenderImageManager>(pool, log))
|
||||
{
|
||||
}
|
||||
|
||||
void RenderGallery() override;
|
||||
|
||||
void RenderImages();
|
||||
|
||||
void Add(resources::ResourceKey key) { this->render_manager_->Add(key); }
|
||||
|
||||
void SetLoadFunction(const std::function<void()>& fun) { this->load_image_ = fun; };
|
||||
|
||||
private:
|
||||
std::function<void()> load_image_{};
|
||||
Pool& pool_;
|
||||
const Log& log_;
|
||||
std::unique_ptr<application::RenderImageManager> render_manager_;
|
||||
bool image_listp_{true};
|
||||
bool auto_show_selectd_image_{true};
|
||||
size_t selected_image_{0};
|
||||
};
|
||||
} // namespace pixelarium::application
|
||||
@@ -0,0 +1,5 @@
|
||||
#pragma once
|
||||
|
||||
#include "imgui.h"
|
||||
#include "imgui_stdlib.h"
|
||||
#include "implot.h"
|
||||
@@ -1,17 +1,15 @@
|
||||
#include "CvMatRender.hpp"
|
||||
|
||||
#include <memory>
|
||||
#include <opencv2/core/mat.hpp>
|
||||
#include <opencv2/imgproc.hpp>
|
||||
#include <stdexcept>
|
||||
|
||||
#include "imaging/IPixelariumImage.hpp"
|
||||
#include "IPixelariumImage.hpp"
|
||||
|
||||
using namespace pixelarium::imaging;
|
||||
|
||||
/// @brief Constructor for the CvMatRender class.
|
||||
/// @param img A shared pointer to the PixelariumImage to be rendered.
|
||||
pixelarium::render::CvMatRender::CvMatRender(std::shared_ptr<pixelarium::imaging::IPixelariumImage>& img) : base_(img), texture_(0)
|
||||
pixelarium::application::CvMatRender::CvMatRender(const cv::Mat& img) : base_(img), texture_(0)
|
||||
{
|
||||
// storing a copy of the to-be-rendered image
|
||||
// because it will be resized and filtered eventually which we absolutely
|
||||
@@ -22,7 +20,7 @@ pixelarium::render::CvMatRender::CvMatRender(std::shared_ptr<pixelarium::imaging
|
||||
|
||||
/// @brief Destructor for the CvMatRender class.
|
||||
/// Deallocates the OpenGL texture if it exists.
|
||||
pixelarium::render::CvMatRender::~CvMatRender()
|
||||
pixelarium::application::CvMatRender::~CvMatRender()
|
||||
{
|
||||
if (texture_)
|
||||
{
|
||||
@@ -31,19 +29,10 @@ pixelarium::render::CvMatRender::~CvMatRender()
|
||||
}
|
||||
}
|
||||
|
||||
/// @brief Resets the render image with a new PixelariumImage.
|
||||
/// @param img A shared pointer to the new PixelariumImage.
|
||||
void pixelarium::render::CvMatRender::ResetRenderImage(std::shared_ptr<pixelarium::imaging::IPixelariumImage>& img)
|
||||
{
|
||||
this->base_ = img;
|
||||
this->ResetRenderImage();
|
||||
cv::cvtColor(this->img_, this->img_, cv::COLOR_BGR2RGBA);
|
||||
}
|
||||
|
||||
/// @brief Uploads the current image data to an OpenGL texture.
|
||||
/// @return The ID of the uploaded OpenGL texture.
|
||||
/// @throws std::runtime_error if the image data is empty or if there is an OpenGL error.
|
||||
GLuint pixelarium::render::CvMatRender::uploadTexture()
|
||||
GLuint pixelarium::application::CvMatRender::uploadTexture()
|
||||
{
|
||||
if (img_.empty())
|
||||
{
|
||||
@@ -66,21 +55,25 @@ GLuint pixelarium::render::CvMatRender::uploadTexture()
|
||||
|
||||
const int width = img_.cols;
|
||||
const int height = img_.rows;
|
||||
|
||||
switch (img_.type()) {
|
||||
// see
|
||||
// https://stackoverflow.com/questions/10167534/how-to-find-out-what-type-of-a-mat-object-is-with-mattype-in-opencv
|
||||
// for pixel a pixel type table
|
||||
switch (img_.type())
|
||||
{
|
||||
case CV_8U:
|
||||
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_BYTE, img_.data);
|
||||
break;
|
||||
case CV_16U:
|
||||
case CV_16UC3:
|
||||
case 26:
|
||||
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
|
||||
case CV_16UC4:
|
||||
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_SHORT, img_.data);
|
||||
break;
|
||||
case 5:
|
||||
case 29:
|
||||
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
|
||||
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_FLOAT, img_.data);
|
||||
case CV_32F:
|
||||
case CV_32FC4:
|
||||
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, width, height, 0, GL_DEPTH_COMPONENT, GL_FLOAT,
|
||||
img_.data);
|
||||
break;
|
||||
default:
|
||||
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
|
||||
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, img_.cols, img_.rows, 0, GL_RGBA, GL_UNSIGNED_BYTE, img_.data);
|
||||
break;
|
||||
}
|
||||
@@ -96,18 +89,14 @@ GLuint pixelarium::render::CvMatRender::uploadTexture()
|
||||
|
||||
/// @brief Renders the image by uploading it as a texture.
|
||||
/// @return The ID of the OpenGL texture.
|
||||
GLuint pixelarium::render::CvMatRender::Render() { return this->uploadTexture(); }
|
||||
GLuint pixelarium::application::CvMatRender::Render() { return this->uploadTexture(); }
|
||||
|
||||
/// @brief Renders the image with a specified scaling factor.
|
||||
/// @param factor The scaling factor for resizing the image.
|
||||
/// @return The ID of the OpenGL texture.
|
||||
GLuint pixelarium::render::CvMatRender::Render(float factor)
|
||||
GLuint pixelarium::application::CvMatRender::Render(float factor)
|
||||
{
|
||||
auto res_val {this->base_->TryGetImage()};
|
||||
if (res_val)
|
||||
{
|
||||
cv::resize(*res_val, this->img_, cv::Size(0, 0), factor, factor, cv::INTER_LINEAR_EXACT);
|
||||
}
|
||||
cv::resize(this->base_, this->img_, cv::Size(0, 0), factor, factor, cv::INTER_LINEAR_EXACT);
|
||||
|
||||
return this->uploadTexture();
|
||||
}
|
||||
@@ -116,16 +105,9 @@ GLuint pixelarium::render::CvMatRender::Render(float factor)
|
||||
/// @param width The maximum width of the rendered image.
|
||||
/// @param height The maximum height of the rendered image.
|
||||
/// @return The ID of the OpenGL texture.
|
||||
GLuint pixelarium::render::CvMatRender::Render(size_t width, size_t height)
|
||||
GLuint pixelarium::application::CvMatRender::Render(size_t width, size_t height)
|
||||
{
|
||||
auto res_val {this->base_->TryGetImage()};
|
||||
|
||||
if (!res_val)
|
||||
{
|
||||
return this->Render(1.0f);
|
||||
}
|
||||
|
||||
const auto sz{res_val->size()};
|
||||
const auto sz{this->base_.size()};
|
||||
|
||||
const auto get_factor = [](auto opt1, auto opt2) -> float { return opt1 < opt2 ? opt1 : opt2; };
|
||||
|
||||
@@ -134,20 +116,8 @@ GLuint pixelarium::render::CvMatRender::Render(size_t width, size_t height)
|
||||
return this->Render(factor);
|
||||
}
|
||||
|
||||
void pixelarium::render::CvMatRender::ResetRenderImage()
|
||||
void pixelarium::application::CvMatRender::ResetRenderImage()
|
||||
{
|
||||
if (this->base_ == nullptr)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
auto root_res = this->base_->TryGetImage();
|
||||
|
||||
if (!root_res)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// we copy here
|
||||
this->img_ = root_res->clone();
|
||||
this->img_ = this->base_.clone();
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
#include "IPixelariumImageView.hpp"
|
||||
|
||||
#include <opencv2/imgcodecs.hpp>
|
||||
|
||||
#include "app_resources_default.h"
|
||||
#include "imgui.h"
|
||||
#include "portable-file-dialogs.h"
|
||||
|
||||
auto pixelarium::application::IPixelariumImageView::ImageViewMenuBar() -> void
|
||||
{
|
||||
if (ImGui::BeginMenuBar())
|
||||
{
|
||||
if (ImGui::BeginMenu("File"))
|
||||
{
|
||||
if (ImGui::MenuItem(SAVEAS))
|
||||
{
|
||||
auto dest = pfd::save_file("Save File", ".", {"Image Files", "*.png *.jpg *.jpeg *.tiff"},
|
||||
pfd::opt::force_overwrite)
|
||||
.result();
|
||||
if (!dest.empty())
|
||||
{
|
||||
// this->img_->SaveImage(dest);
|
||||
cv::imwrite(dest, cached_image_);
|
||||
}
|
||||
}
|
||||
|
||||
ImageViewMenuBarAdditions();
|
||||
|
||||
ImGui::EndMenu();
|
||||
}
|
||||
|
||||
ImGui::EndMenuBar();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
#include "ImageViewFactory.hpp"
|
||||
|
||||
#include <format>
|
||||
#include <memory>
|
||||
|
||||
#include "IPixelariumImage.hpp"
|
||||
#include "IPixelariumImageView.hpp"
|
||||
#include "PixelariumImageFactory.hpp"
|
||||
#include "PixelariumImageViewCzi.hpp"
|
||||
#include "PixelariumImageViewDefault.hpp"
|
||||
|
||||
/// @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::application::IPixelariumImageView> pixelarium::application::ImageViewFactory::RenderImage(
|
||||
resources::ResourceKey image_id)
|
||||
{
|
||||
using ImageType = imaging::ImageFileType;
|
||||
auto res{this->image_pool_.GetResource(image_id)};
|
||||
|
||||
const auto img{res.lock()};
|
||||
|
||||
if (img == nullptr)
|
||||
{
|
||||
return {};
|
||||
}
|
||||
|
||||
if (img->Empty())
|
||||
{
|
||||
return {};
|
||||
}
|
||||
|
||||
auto type = imaging::ExtensionToType(img->Uri().extension().string());
|
||||
if (img->Uri().empty())
|
||||
{
|
||||
log_.Info(std::format("{}: empty Uri for {}.", __PRETTY_FUNCTION__, img->Name()));
|
||||
type = ImageType::kMemory;
|
||||
}
|
||||
|
||||
switch (type)
|
||||
{
|
||||
case ImageType::kUnknown:
|
||||
case ImageType::kAbstract:
|
||||
case ImageType::kPng:
|
||||
case ImageType::kJpg:
|
||||
case ImageType::kTiff:
|
||||
case ImageType::kMemory:
|
||||
log_.Info(std::format("{}: Creating a Default View", __PRETTY_FUNCTION__));
|
||||
// beware: here we copy the actual image resource over to the new image
|
||||
try
|
||||
{
|
||||
auto view{std::make_unique<PixelariumImageViewDefault>(img)};
|
||||
return view;
|
||||
}
|
||||
catch (const std::exception& ex)
|
||||
{
|
||||
log_.Error(std::format("{}: Creating view failed: {}", __PRETTY_FUNCTION__, ex.what()));
|
||||
}
|
||||
case ImageType::kCzi:
|
||||
log_.Info(std::format("{}: Creating a CZI View", __PRETTY_FUNCTION__));
|
||||
try
|
||||
{
|
||||
auto view{std::make_unique<PixelariumImageViewCzi>(img, log_)};
|
||||
return view;
|
||||
}
|
||||
catch (const std::exception& ex)
|
||||
{
|
||||
log_.Error(std::format("{}: Creating view failed: {}", __PRETTY_FUNCTION__, ex.what()));
|
||||
}
|
||||
default:
|
||||
return {};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
#include "PixelariumImageViewCzi.hpp"
|
||||
|
||||
#include <format>
|
||||
#include <memory>
|
||||
#include <stdexcept>
|
||||
|
||||
#include "CvMatRender.hpp"
|
||||
#include "IPixelariumImage.hpp"
|
||||
#include "PixelariumCzi.hpp"
|
||||
#include "RenderHelpers.hpp"
|
||||
#include "imgui.h"
|
||||
|
||||
void pixelarium::application::PixelariumImageViewCzi::RefreshCachedImage()
|
||||
{
|
||||
if (this->cached_image_.empty() || this->is_dirty_)
|
||||
{
|
||||
log_.Info(std::format("{}: refreshing image.", __PRETTY_FUNCTION__));
|
||||
imaging::CziParams params;
|
||||
params.dimension_map = this->dimension_map_;
|
||||
this->cached_image_ = this->img_->TryGetImage(params).value_or(cv::Mat{});
|
||||
// Resetting the image while the renderer is possibly accessing the
|
||||
// image at the same time is not a good idea. Therefore, we simply create
|
||||
// a new renderer here.
|
||||
this->render_ = std::make_unique<CvMatRender>(this->cached_image_);
|
||||
this->is_dirty_ = false;
|
||||
}
|
||||
}
|
||||
|
||||
pixelarium::application::PixelariumImageViewCzi::PixelariumImageViewCzi(std::shared_ptr<Image> img, const Log& log)
|
||||
: log_(log)
|
||||
{
|
||||
img_ = img;
|
||||
auto czi_img = std::static_pointer_cast<imaging::PixelariumCzi>(this->img_);
|
||||
|
||||
auto stats = czi_img->GetStatistics();
|
||||
stats.dimBounds.EnumValidDimensions(
|
||||
[&](libCZI::DimensionIndex dim, int start, int) -> bool
|
||||
{
|
||||
this->dimension_map_[dim] = start;
|
||||
return true;
|
||||
});
|
||||
|
||||
auto render_mat = img->TryGetImage();
|
||||
if (render_mat.has_value())
|
||||
{
|
||||
this->render_ = std::make_unique<CvMatRender>(render_mat.value());
|
||||
}
|
||||
else
|
||||
{
|
||||
auto msg{std::format("{}: fetching image failed: {}", __PRETTY_FUNCTION__, img->Name())};
|
||||
log_.Error(msg);
|
||||
throw std::runtime_error(msg);
|
||||
}
|
||||
|
||||
// this->SetInitialSize();
|
||||
log_.Info(std::format("{}: dimension map size: {}", __PRETTY_FUNCTION__, dimension_map_.size()));
|
||||
}
|
||||
|
||||
/// @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::application::PixelariumImageViewCzi::ShowImage()
|
||||
{
|
||||
auto czi_img = std::static_pointer_cast<imaging::PixelariumCzi>(this->img_);
|
||||
|
||||
if (!czi_img) return;
|
||||
|
||||
RefreshCachedImage();
|
||||
|
||||
if (czi_img->Empty() || this->img_->type_ == imaging::ImageFileType::kUnknown || cached_image_.empty() ||
|
||||
czi_img->Name().empty())
|
||||
{
|
||||
// do nothing
|
||||
return;
|
||||
}
|
||||
|
||||
if (first_render_)
|
||||
{
|
||||
first_render_ = false;
|
||||
constexpr auto initial_width{700.0f};
|
||||
const auto cached_width{cached_image_.cols};
|
||||
const auto cached_heigth{cached_image_.rows};
|
||||
const auto ratio{static_cast<float>(cached_heigth) / cached_width};
|
||||
SetInitialSize(initial_width, (initial_width * ratio + 100));
|
||||
}
|
||||
|
||||
ImGui::Begin(this->img_->Name().c_str(), &this->open_p,
|
||||
ImGuiWindowFlags_HorizontalScrollbar | ImGuiWindowFlags_MenuBar);
|
||||
|
||||
ImageViewMenuBar();
|
||||
|
||||
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(cached_image_.cols, cached_image_.rows);
|
||||
|
||||
ImGui::Image(reinterpret_cast<ImTextureID>(reinterpret_cast<void*>(texture)),
|
||||
aspect_const_dimensions(dim, 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::Text("Dimensions");
|
||||
ImGui::Separator();
|
||||
if (ImGui::Button("Update"))
|
||||
{
|
||||
this->ForceUpdate();
|
||||
}
|
||||
|
||||
auto stats = czi_img->GetStatistics();
|
||||
stats.dimBounds.EnumValidDimensions(
|
||||
[&](libCZI::DimensionIndex dim, int start, int size) -> bool
|
||||
{
|
||||
auto dim_char = libCZI::Utils::DimensionToChar(dim);
|
||||
if (ImGui::SliderInt(std::format("{}({}-{})", dim_char, start, size).c_str(), &dimension_map_[dim], start,
|
||||
size - 1))
|
||||
{
|
||||
this->ForceUpdate();
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
|
||||
ImGui::End();
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
#include "PixelariumImageViewDefault.hpp"
|
||||
|
||||
#include <opencv2/core/hal/interface.h>
|
||||
|
||||
#include <cstdio>
|
||||
#include <format>
|
||||
#include <iostream>
|
||||
#include <opencv2/core.hpp>
|
||||
#include <opencv2/imgproc.hpp>
|
||||
#include <ostream>
|
||||
#include <ranges>
|
||||
#include <utility>
|
||||
|
||||
#include "IPixelariumImage.hpp"
|
||||
#include "RenderHelpers.hpp"
|
||||
#include "app_resources_default.h"
|
||||
#include "imgui.h"
|
||||
#include "implot.h"
|
||||
#include "simple_thread_pool.hpp"
|
||||
|
||||
void pixelarium::application::PixelariumImageViewDefault::RefreshCachedImage()
|
||||
{
|
||||
if (this->cached_image_.empty() || this->is_dirty_)
|
||||
{
|
||||
this->cached_image_ = this->img_->TryGetImage().value_or(cv::Mat{});
|
||||
this->is_dirty_ = false;
|
||||
}
|
||||
}
|
||||
|
||||
void pixelarium::application::PixelariumImageViewDefault::ImageViewMenuBarAdditions()
|
||||
{
|
||||
ImGui::MenuItem("Histogram", NULL, &this->show_hists_);
|
||||
}
|
||||
|
||||
/// @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::application::PixelariumImageViewDefault::ShowImage()
|
||||
{
|
||||
RefreshCachedImage();
|
||||
|
||||
if (this->img_->Empty() || this->img_->type_ == imaging::ImageFileType::kUnknown || this->cached_image_.empty() ||
|
||||
this->img_->Name().empty())
|
||||
{
|
||||
// do nothing
|
||||
return;
|
||||
}
|
||||
|
||||
if (first_render_)
|
||||
{
|
||||
first_render_ = false;
|
||||
|
||||
const auto cached_width{cached_image_.cols};
|
||||
const auto cached_heigth{cached_image_.rows};
|
||||
const auto ratio{static_cast<float>(cached_heigth) / cached_width};
|
||||
SetInitialSize(kInitialWindowWidth, (kInitialWindowWidth * ratio + 100));
|
||||
utils::pixelarium_pool::enqueue([this]() { GenerateHistogram(); });
|
||||
}
|
||||
|
||||
ImGui::Begin(this->img_->Name().c_str(), &this->open_p,
|
||||
ImGuiWindowFlags_HorizontalScrollbar | ImGuiWindowFlags_MenuBar);
|
||||
|
||||
ImageViewMenuBar();
|
||||
|
||||
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(cached_image_.cols, cached_image_.rows);
|
||||
|
||||
ImGui::Image(reinterpret_cast<ImTextureID>(reinterpret_cast<void*>(texture)),
|
||||
aspect_const_dimensions(dim, new_dim));
|
||||
|
||||
ImGui::Separator();
|
||||
|
||||
if (show_hists_ && hist_available_)
|
||||
{
|
||||
if (ImPlot::BeginPlot("Histogram"))
|
||||
{
|
||||
ImPlot::SetupAxes(nullptr, nullptr, ImPlotAxisFlags_AutoFit, ImPlotAxisFlags_AutoFit);
|
||||
using style_pair = std::pair<const char*, ImVec4>;
|
||||
|
||||
constexpr std::array<style_pair, 3> names = {
|
||||
{{"Blue", ImVec4(0, 0, 1, 1)}, {"Green", ImVec4(0, 1, 0, 1)}, {"Red", ImVec4(1, 0, 0, 1)}}};
|
||||
// for (auto& e : hist_planes_)
|
||||
// {
|
||||
// ImPlot::PlotHistogram(name.c_str(), e.data, e.rows * e.cols, 16);
|
||||
// for (auto& e : name)
|
||||
// {
|
||||
// e++;
|
||||
// }
|
||||
// }
|
||||
for (size_t i{0}; i < hist_planes_.size(); ++i)
|
||||
{
|
||||
if (hist_planes_.at(i).type() == CV_32F)
|
||||
{
|
||||
// ImPlot::PlotHistogram(names.at(i % 3), reinterpret_cast<float*>(hist_planes_[i].data),
|
||||
// hist_planes_[i].rows * hist_planes_[i].cols, 16, 1.0, ImPlotRange(),
|
||||
// ImPlotHistogramFlags_Horizontal);
|
||||
ImPlot::PushStyleColor(ImPlotCol_Line, names.at(i % 3).second);
|
||||
ImPlot::PlotLine(std::format("{}-line", names.at(i % 3).first).c_str(),
|
||||
reinterpret_cast<float*>(hist_planes_[i].data),
|
||||
hist_planes_[i].rows * hist_planes_[i].cols);
|
||||
ImPlot::PopStyleColor();
|
||||
}
|
||||
}
|
||||
|
||||
ImPlot::PushStyleVar(ImPlotStyleVar_FillAlpha, 0.25f);
|
||||
ImPlot::SetNextMarkerStyle(ImPlotMarker_Square, 6, ImPlot::GetColormapColor(1), IMPLOT_AUTO,
|
||||
ImPlot::GetColormapColor(1));
|
||||
|
||||
ImPlot::EndPlot();
|
||||
}
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
auto pixelarium::application::PixelariumImageViewDefault::GenerateHistogram() -> void
|
||||
{
|
||||
cv::split(cached_image_, bgr_planes_);
|
||||
hist_planes_.resize(bgr_planes_.size());
|
||||
|
||||
int histSize = 256;
|
||||
float range[] = {0, 256}; // the upper boundary is exclusive
|
||||
const float* histRange[] = {range};
|
||||
|
||||
for (auto [bgr, hist] : std::ranges::views::zip(bgr_planes_, hist_planes_))
|
||||
{
|
||||
cv::calcHist(&bgr, 1, 0, cv::Mat(), hist, 1, &histSize, histRange, true, false);
|
||||
// cv::normalize(hist, hist);
|
||||
}
|
||||
|
||||
hist_available_ = true;
|
||||
}
|
||||
@@ -1,12 +1,13 @@
|
||||
#include "RenderHelpers.hpp"
|
||||
|
||||
#include <cstdlib>
|
||||
|
||||
/// @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.
|
||||
bool pixelarium::render::dim_changed_p(const ImVec2& ref_rect, const ImVec2& new_rect)
|
||||
bool pixelarium::application::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))
|
||||
{
|
||||
@@ -20,7 +21,7 @@ bool pixelarium::render::dim_changed_p(const ImVec2& ref_rect, const ImVec2& new
|
||||
/// @param img The input image.
|
||||
/// @param curr_dim The current dimensions.
|
||||
/// @return The calculated dimensions maintaining aspect ratio.
|
||||
ImVec2 pixelarium::render::aspect_const_dimensions(const ImVec2& raw_dim, const ImVec2& curr_dim)
|
||||
ImVec2 pixelarium::application::aspect_const_dimensions(const ImVec2& raw_dim, const ImVec2& curr_dim)
|
||||
{
|
||||
const auto w_fact = (curr_dim.x / raw_dim.x);
|
||||
const auto h_fact = (curr_dim.y / raw_dim.y);
|
||||
@@ -7,7 +7,7 @@ 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()
|
||||
void pixelarium::application::RenderImageManager::UpdateCollection()
|
||||
{
|
||||
for (const auto& key : keys_to_delete_)
|
||||
{
|
||||
@@ -19,7 +19,7 @@ void pixelarium::render::RenderImageManager::UpdateCollection()
|
||||
|
||||
/// @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)
|
||||
void pixelarium::application::RenderImageManager::MarkForDeletion(resources::ResourceKey key)
|
||||
{
|
||||
this->log_.Debug(std::format("{} marking key: \"{}\" for deletion.", __PRETTY_FUNCTION__, key));
|
||||
lock_guard<mutex> guard(this->mut_);
|
||||
@@ -29,7 +29,7 @@ void pixelarium::render::RenderImageManager::MarkForDeletion(resources::Resource
|
||||
/// @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 pixelarium::application::RenderImageManager::Remove(resources::ResourceKey key) noexcept
|
||||
{
|
||||
bool remove_state{false};
|
||||
this->log_.Debug(std::format("{} removing key: \"{}\" from renderlist.", __PRETTY_FUNCTION__, key));
|
||||
@@ -44,16 +44,24 @@ bool pixelarium::render::RenderImageManager::Remove(resources::ResourceKey key)
|
||||
/// @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
|
||||
void pixelarium::application::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)
|
||||
// we don't want to add what's already there, render empty images, or failed keys
|
||||
if (this->render_image_map_.contains(key)
|
||||
// || this->failed_keys_cache_.contains(key)
|
||||
)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
auto current_view = this->view_factory_->RenderImage(key);
|
||||
if (current_view == nullptr)
|
||||
{
|
||||
// failed to create view, cache this key to avoid repeated attempts
|
||||
this->failed_keys_cache_.insert(key);
|
||||
return;
|
||||
}
|
||||
|
||||
this->log_.Debug(std::format("{}: adding key: \"{}\" to renderlist.", __PRETTY_FUNCTION__, key));
|
||||
|
||||
lock_guard<mutex> guard(this->mut_);
|
||||
@@ -72,4 +80,4 @@ void pixelarium::render::RenderImageManager::Add(resources::ResourceKey key) noe
|
||||
|
||||
/// @brief Clears all render images from the manager.
|
||||
/// @note This function is noexcept.
|
||||
void pixelarium::render::RenderImageManager::Clear() noexcept { this->render_image_map_.clear(); }
|
||||
void pixelarium::application::RenderImageManager::Clear() noexcept { this->render_image_map_.clear(); }
|
||||
@@ -2,7 +2,6 @@
|
||||
// windows.h must come before GL/GL.h here.
|
||||
// clang format would change this, effectively rendering the build broken.
|
||||
// clang-format off
|
||||
#include <memory>
|
||||
#ifdef _WIN32
|
||||
#include <windows.h>
|
||||
#include <GL/GL.h>
|
||||
@@ -13,11 +12,12 @@
|
||||
#endif
|
||||
#include <GLFW/glfw3.h> // Will drag system OpenGL headers
|
||||
#endif
|
||||
#include "imaging/IPixelariumImage.hpp"
|
||||
#include <opencv2/core/mat.hpp>
|
||||
// clang-format on
|
||||
|
||||
namespace pixelarium::render
|
||||
namespace pixelarium::application
|
||||
{
|
||||
/// @brief Renders cv::Mat bitmaps as OpenGL textures.
|
||||
class CvMatRender
|
||||
{
|
||||
public:
|
||||
@@ -26,28 +26,27 @@ class CvMatRender
|
||||
// get removed in the future)
|
||||
// as the using AppGLFW constructs it empty as a member
|
||||
// when coming to life.
|
||||
CvMatRender() = default;
|
||||
// CvMatRender() = default;
|
||||
CvMatRender(CvMatRender&) = delete;
|
||||
CvMatRender(const CvMatRender&) = delete;
|
||||
CvMatRender(CvMatRender&&) = delete;
|
||||
CvMatRender& operator=(CvMatRender&) = default;
|
||||
CvMatRender& operator=(CvMatRender&& other) = default;
|
||||
CvMatRender& operator=(CvMatRender&) = delete;
|
||||
CvMatRender& operator=(CvMatRender&& other) = delete;
|
||||
~CvMatRender();
|
||||
explicit CvMatRender(std::shared_ptr<pixelarium::imaging::IPixelariumImage>& img);
|
||||
explicit CvMatRender(const cv::Mat& img);
|
||||
|
||||
public:
|
||||
GLuint Render();
|
||||
GLuint Render(float factor);
|
||||
GLuint Render(size_t width, size_t height);
|
||||
void ResetRenderImage();
|
||||
void ResetRenderImage(std::shared_ptr<pixelarium::imaging::IPixelariumImage>& img);
|
||||
|
||||
private:
|
||||
cv::Mat img_;
|
||||
std::shared_ptr<pixelarium::imaging::IPixelariumImage> base_;
|
||||
const cv::Mat& base_;
|
||||
GLuint texture_;
|
||||
|
||||
GLuint uploadTexture();
|
||||
};
|
||||
|
||||
} // namespace pixelarium::render
|
||||
} // namespace pixelarium::application
|
||||
@@ -0,0 +1,41 @@
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
|
||||
#include "IPixelariumImage.hpp"
|
||||
#include "imgui.h"
|
||||
|
||||
namespace pixelarium::application
|
||||
{
|
||||
/// @brief An interface defining the contract on views to dedicated implementations of IPixelariumImage
|
||||
class IPixelariumImageView
|
||||
{
|
||||
public:
|
||||
virtual ~IPixelariumImageView() = default;
|
||||
virtual void ShowImage() = 0;
|
||||
|
||||
// default implemented
|
||||
public:
|
||||
virtual const bool* GetStatus() const noexcept { return &this->open_p; }
|
||||
virtual void ForceUpdate() noexcept { this->is_dirty_ = true; }
|
||||
|
||||
// this must be called immediately before a "ImGui::Begin" context
|
||||
// as it will affect the next window and result in undeterministic effects
|
||||
// when called "out of sync"
|
||||
virtual void SetInitialSize(float width = 700.0f, float height = 700.0f)
|
||||
{
|
||||
ImGui::SetNextWindowSize({width, height});
|
||||
}
|
||||
|
||||
protected:
|
||||
virtual void ImageViewMenuBar();
|
||||
virtual void ImageViewMenuBarAdditions() {};
|
||||
|
||||
protected:
|
||||
std::shared_ptr<imaging::IPixelariumImageCvMat> img_{};
|
||||
cv::Mat cached_image_{};
|
||||
bool open_p{true};
|
||||
bool is_dirty_{true};
|
||||
bool first_render_{true};
|
||||
};
|
||||
} // namespace pixelarium::application
|
||||
@@ -0,0 +1,25 @@
|
||||
#pragma once
|
||||
|
||||
#include "ILog.hpp"
|
||||
#include "IPixelariumImageView.hpp"
|
||||
#include "resource.hpp"
|
||||
|
||||
namespace pixelarium::application
|
||||
{
|
||||
/// @brief Factory for instantiating matching views to different implementations of IPixelariumImage.
|
||||
class ImageViewFactory
|
||||
{
|
||||
using Image = imaging::IPixelariumImageCvMat;
|
||||
using Pool = resources::ImageResourcePool;
|
||||
using Log = utils::log::ILog;
|
||||
|
||||
public:
|
||||
explicit ImageViewFactory(Pool& pool, const Log& log) : image_pool_(pool), log_(log) {}
|
||||
|
||||
std::unique_ptr<IPixelariumImageView> RenderImage(resources::ResourceKey id);
|
||||
|
||||
private:
|
||||
Pool& image_pool_;
|
||||
const Log& log_;
|
||||
};
|
||||
} // namespace pixelarium::application
|
||||
@@ -0,0 +1,41 @@
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
#include <unordered_map>
|
||||
|
||||
#include "CvMatRender.hpp"
|
||||
#include "ILog.hpp"
|
||||
#include "IPixelariumImage.hpp"
|
||||
#include "IPixelariumImageView.hpp"
|
||||
#include "imgui.h"
|
||||
#include "libCZI_DimCoordinate.h"
|
||||
|
||||
namespace pixelarium::application
|
||||
{
|
||||
/// @brief A CZI-specific implementation of IPixelariumImageView.
|
||||
class PixelariumImageViewCzi : public IPixelariumImageView
|
||||
{
|
||||
using Image = imaging::IPixelariumImageCvMat;
|
||||
using Log = utils::log::ILog;
|
||||
|
||||
public:
|
||||
explicit PixelariumImageViewCzi(std::shared_ptr<Image> img, const Log& log);
|
||||
PixelariumImageViewCzi() = delete;
|
||||
PixelariumImageViewCzi(PixelariumImageViewCzi&) = delete;
|
||||
PixelariumImageViewCzi(const PixelariumImageViewCzi&) = delete;
|
||||
PixelariumImageViewCzi(PixelariumImageViewCzi&&) = delete;
|
||||
PixelariumImageViewCzi& operator=(PixelariumImageViewCzi&) = delete;
|
||||
PixelariumImageViewCzi& operator=(PixelariumImageViewCzi&&) = delete;
|
||||
|
||||
void ShowImage() override;
|
||||
|
||||
private:
|
||||
ImVec2 curr_dim_{};
|
||||
const Log& log_;
|
||||
std::unordered_map<libCZI::DimensionIndex, int> dimension_map_;
|
||||
std::unique_ptr<CvMatRender> render_;
|
||||
|
||||
private:
|
||||
void RefreshCachedImage();
|
||||
};
|
||||
} // namespace pixelarium::application
|
||||
@@ -0,0 +1,46 @@
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
|
||||
#include "CvMatRender.hpp"
|
||||
#include "IPixelariumImage.hpp"
|
||||
#include "IPixelariumImageView.hpp"
|
||||
#include "imgui.h"
|
||||
|
||||
namespace pixelarium::application
|
||||
{
|
||||
/// @brief A default implementation of IPixelariumImageView.
|
||||
/// This is sufficient for single dimension images like png or jpg.
|
||||
class PixelariumImageViewDefault : public IPixelariumImageView
|
||||
{
|
||||
using Image = imaging::IPixelariumImageCvMat;
|
||||
|
||||
public:
|
||||
explicit PixelariumImageViewDefault(std::shared_ptr<Image> img) : render_(*img->TryGetImage()) { img_ = img; }
|
||||
|
||||
PixelariumImageViewDefault() = delete;
|
||||
PixelariumImageViewDefault(PixelariumImageViewDefault&) = delete;
|
||||
PixelariumImageViewDefault(const PixelariumImageViewDefault&) = delete;
|
||||
PixelariumImageViewDefault(PixelariumImageViewDefault&&) = delete;
|
||||
PixelariumImageViewDefault& operator=(PixelariumImageViewDefault&) = delete;
|
||||
PixelariumImageViewDefault& operator=(PixelariumImageViewDefault&&) = delete;
|
||||
|
||||
void ShowImage() override;
|
||||
|
||||
void ImageViewMenuBarAdditions() override;
|
||||
|
||||
void GenerateHistogram();
|
||||
|
||||
private:
|
||||
ImVec2 curr_dim_{};
|
||||
CvMatRender render_;
|
||||
bool show_hists_{false};
|
||||
bool hist_available_{false};
|
||||
std::vector<cv::Mat> bgr_planes_;
|
||||
std::vector<cv::Mat> hist_planes_;
|
||||
|
||||
private:
|
||||
void RefreshCachedImage();
|
||||
};
|
||||
} // namespace pixelarium::application
|
||||
@@ -2,9 +2,9 @@
|
||||
|
||||
#include "imgui.h"
|
||||
|
||||
namespace pixelarium::render
|
||||
namespace pixelarium::application
|
||||
{
|
||||
bool dim_changed_p(const ImVec2& ref_rect, const ImVec2& new_rect);
|
||||
|
||||
ImVec2 aspect_const_dimensions(const ImVec2& raw_dim, const ImVec2& curr_dim);
|
||||
}; // namespace pixelarium::render
|
||||
}; // namespace pixelarium::application
|
||||
+13
-6
@@ -4,15 +4,14 @@
|
||||
#include <unordered_map>
|
||||
#include <unordered_set>
|
||||
|
||||
#include "ILog.hpp"
|
||||
#include "IPixelariumImageView.hpp"
|
||||
#include "ImageViewFactory.hpp"
|
||||
#include "PixelariumImageViewDefault.hpp"
|
||||
#include "rendering/IPixelariumImageView.hpp"
|
||||
#include "resources/resource.hpp"
|
||||
#include "utilities/ILog.hpp"
|
||||
#include "resource.hpp"
|
||||
|
||||
// This is intended as an additional abstraction
|
||||
// aggregating views that should be rendered (or not)
|
||||
namespace pixelarium::render
|
||||
namespace pixelarium::application
|
||||
{
|
||||
/// @brief Instead of directly using the view, we
|
||||
/// proxy it through a wrapper. This allows for arbitrary additional data
|
||||
@@ -23,6 +22,13 @@ struct RenderImageStateWrapper
|
||||
const bool* show_state;
|
||||
};
|
||||
|
||||
/// @brief Manage instances of IPixelariumImageView.
|
||||
///
|
||||
/// This class is used to keep track of what must be rendered.
|
||||
/// It manages a set of IPixelariumImageView instances that can be traversed
|
||||
/// via its Enumerate() function.
|
||||
/// Views that shall not be rendered anymore should be marked for deletion
|
||||
/// with MarkForDeletion()
|
||||
class RenderImageManager
|
||||
{
|
||||
using Pool = resources::ImageResourcePool;
|
||||
@@ -62,7 +68,8 @@ class RenderImageManager
|
||||
std::unique_ptr<ImageViewFactory> view_factory_;
|
||||
std::mutex mut_;
|
||||
std::unordered_set<resources::ResourceKey> keys_to_delete_;
|
||||
std::unordered_set<resources::ResourceKey> failed_keys_cache_;
|
||||
|
||||
const utils::log::ILog& log_;
|
||||
};
|
||||
} // namespace pixelarium::render
|
||||
} // namespace pixelarium::application
|
||||
@@ -1,4 +1,4 @@
|
||||
include(${CMAKE_SOURCE_DIR}/cmake/libCZI.cmake)
|
||||
include(libCZI)
|
||||
|
||||
find_package(OpenCV REQUIRED)
|
||||
|
||||
@@ -6,15 +6,20 @@ message(STATUS "Found opencv: " ${OpenCV_INCLUDE_DIRS})
|
||||
message(STATUS "OpenCV_LIBs from: " ${OpenCV_LIBS})
|
||||
|
||||
set(IMAGELIBSRC
|
||||
IPixelariumImage.hpp
|
||||
PixelariumImageFactory.hpp
|
||||
include/IPixelariumImage.hpp
|
||||
include/PixelariumImageFactory.hpp
|
||||
impl/include/PixelariumJpg.hpp
|
||||
impl/include/PixelariumPng.hpp
|
||||
impl/include/PixelariumCzi.hpp
|
||||
impl/include/PixelariumTiff.hpp
|
||||
impl/include/PixelariumMem.hpp
|
||||
IPixelariumImage.cpp
|
||||
PixelariumImageFactory.cpp
|
||||
impl/PixelariumJpg.hpp
|
||||
impl/PixelariumJpg.cpp
|
||||
impl/PixelariumPng.hpp
|
||||
impl/PixelariumPng.cpp
|
||||
impl/PixelariumCzi.hpp
|
||||
impl/PixelariumCzi.cpp
|
||||
impl/PixelariumTiff.cpp
|
||||
impl/PixelariumMem.cpp
|
||||
)
|
||||
|
||||
set(IMAGELIBLIBNAME pixelariumimagelib)
|
||||
@@ -22,11 +27,19 @@ set(IMAGELIBLIBNAME pixelariumimagelib)
|
||||
add_library(${IMAGELIBLIBNAME}
|
||||
STATIC ${IMAGELIBSRC})
|
||||
|
||||
add_library(pixelarium::lib::imaging_static ALIAS ${IMAGELIBLIBNAME})
|
||||
|
||||
target_compile_definitions(${IMAGELIBLIBNAME} PUBLIC _LIBCZISTATICLIB)
|
||||
|
||||
target_link_libraries(${IMAGELIBLIBNAME}
|
||||
PUBLIC ${OpenCV_LIBS}
|
||||
PUBLIC pixelarium::lib::utilities_static
|
||||
PRIVATE libCZIStatic)
|
||||
|
||||
|
||||
target_include_directories(${IMAGELIBLIBNAME}
|
||||
INTERFACE
|
||||
PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include
|
||||
PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/impl/include
|
||||
PUBLIC ${OpenCV_INCLUDE_DIRS}
|
||||
PUBLIC ${LIBCZI_INCLUDE_DIR})
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
#include "IPixelariumImage.hpp"
|
||||
|
||||
#include <opencv2/imgcodecs.hpp>
|
||||
|
||||
bool pixelarium::imaging::IPixelariumImageCvMat::SaveImage(const std::string& uri)
|
||||
{
|
||||
auto current_image = this->TryGetImage();
|
||||
|
||||
if (!current_image.has_value())
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return cv::imwrite(uri, current_image.value());
|
||||
}
|
||||
@@ -1,90 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <filesystem>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <opencv2/core/mat.hpp>
|
||||
#include <string>
|
||||
|
||||
namespace pixelarium::imaging
|
||||
{
|
||||
using ImageQueryFunctor = std::function<void(const std::string&, void*, int*)>;
|
||||
|
||||
/// @brief Enumeration of supported image file types.
|
||||
enum class ImageFileType
|
||||
{
|
||||
/// @brief Represents an unknown or unsupported file type.
|
||||
UNKNOWN = -10,
|
||||
/// @brief Represents an abstract image type (e.g., a placeholder).
|
||||
ABSTRACT = 0,
|
||||
/// @brief Represents a PNG image file.
|
||||
PNG = 1,
|
||||
/// @brief Represents a JPG image file.
|
||||
JPG = 2,
|
||||
/// @brief Represents a CZI image file.
|
||||
CZI = 3,
|
||||
};
|
||||
|
||||
/// @brief An abstract interface to define a semantic query
|
||||
/// for a multi-dimensional image.
|
||||
struct IImageQuery
|
||||
{
|
||||
virtual ~IImageQuery() = default;
|
||||
};
|
||||
|
||||
/// @brief This aims to be a generic image abstraction
|
||||
/// meant for codec specific implementation.
|
||||
class IPixelariumImage
|
||||
{
|
||||
public:
|
||||
virtual ~IPixelariumImage() = default;
|
||||
|
||||
/// @brief Attempts to retrieve the image.
|
||||
/// @return A unique pointer to a Mat object containing the image data,
|
||||
/// or nullptr if the image is not found or cannot be retrieved.
|
||||
/// May throw exceptions for multidimensional images.
|
||||
virtual std::unique_ptr<cv::Mat> TryGetImage() = 0;
|
||||
|
||||
/// @brief Attempts to retrieve the image.
|
||||
/// @return A unique pointer to a Mat object containing the image data,
|
||||
/// or nullptr if the image is not found or cannot be retrieved.
|
||||
virtual std::unique_ptr<cv::Mat> TryGetImage(const IImageQuery&) = 0;
|
||||
|
||||
/// @brief Attempts to retrieve a collection of images based on a query.
|
||||
/// @param query The query object defining the images to retrieve.
|
||||
/// @return A vector of unique pointers to cv::Mat objects. Each element is an image.
|
||||
/// Returns an empty vector if no images are found or if an error occurs.
|
||||
virtual std::vector<std::unique_ptr<cv::Mat>> TryGetImages(const IImageQuery&) = 0;
|
||||
|
||||
/// @brief Checks if the image is empty.
|
||||
/// @return true if the image is empty, false otherwise.
|
||||
virtual bool Empty() const noexcept = 0;
|
||||
|
||||
// default implemented
|
||||
public:
|
||||
/// @brief Gets the resource identifier as a file path.
|
||||
/// @return @c std::filesystem::path of the underlying resource.
|
||||
virtual std::filesystem::path Uri() const noexcept { return this->uri_; }
|
||||
|
||||
/// @brief Gets the resource name.
|
||||
/// @note Implementations of IPixelariumImage that live in memory
|
||||
/// should override this to get something meaningful as the name
|
||||
/// cannot be fetched from the resource uri in that case.
|
||||
/// @return The name of the underlying resource.
|
||||
virtual std::string Name() const noexcept
|
||||
{
|
||||
if (!this->uri_.empty())
|
||||
{
|
||||
return this->uri_.filename().string();
|
||||
}
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
public:
|
||||
const static ImageFileType type_{ImageFileType::ABSTRACT};
|
||||
|
||||
protected:
|
||||
std::filesystem::path uri_;
|
||||
};
|
||||
} // namespace pixelarium::imaging
|
||||
@@ -1,36 +1,38 @@
|
||||
#include "PixelariumImageFactory.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <memory>
|
||||
|
||||
#include "impl/PixelariumCzi.hpp"
|
||||
#include "impl/PixelariumJpg.hpp"
|
||||
#include "impl/PixelariumPng.hpp"
|
||||
#include "IPixelariumImage.hpp"
|
||||
#include "PixelariumCzi.hpp"
|
||||
#include "PixelariumJpg.hpp"
|
||||
#include "PixelariumMem.hpp"
|
||||
#include "PixelariumPng.hpp"
|
||||
#include "PixelariumTiff.hpp"
|
||||
|
||||
|
||||
/*static*/ std::unique_ptr<pixelarium::imaging::IPixelariumImage>
|
||||
pixelarium::imaging::PixelariumImageFactory::CreateImage(const std::string& uri)
|
||||
/*static*/ std::unique_ptr<pixelarium::imaging::IPixelariumImageCvMat>
|
||||
pixelarium::imaging::PixelariumImageFactory::CreateImage(const std::string& uri, const Log& log)
|
||||
{
|
||||
const auto res{std::filesystem::path(uri)};
|
||||
const auto target_type{ExtensionToType(res.extension().string())};
|
||||
|
||||
switch (target_type)
|
||||
{
|
||||
case ImageFileType::UNKNOWN:
|
||||
case ImageFileType::kUnknown:
|
||||
return {};
|
||||
break;
|
||||
case ImageFileType::ABSTRACT:
|
||||
case ImageFileType::kAbstract:
|
||||
return {};
|
||||
break;
|
||||
case ImageFileType::PNG:
|
||||
case ImageFileType::kPng:
|
||||
return std::make_unique<PixelariumPng>(uri);
|
||||
break;
|
||||
case ImageFileType::JPG:
|
||||
case ImageFileType::kJpg:
|
||||
return std::make_unique<PixelariumJpg>(uri);
|
||||
break;
|
||||
case ImageFileType::CZI:
|
||||
return std::make_unique<PixelariumCzi>(uri);
|
||||
break;
|
||||
case ImageFileType::kCzi:
|
||||
return std::make_unique<PixelariumCzi>(uri, log);
|
||||
case ImageFileType::kTiff:
|
||||
return std::make_unique<PixelariumTiff>(uri, log);
|
||||
case ImageFileType::kMemory:
|
||||
return std::make_unique<PixelariumMem>(cv::Mat(), uri, log);
|
||||
default:
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,34 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
|
||||
#include "IPixelariumImage.hpp"
|
||||
namespace pixelarium::imaging
|
||||
{
|
||||
constexpr pixelarium::imaging::ImageFileType ExtensionToType(const std::string& extension)
|
||||
{
|
||||
std::string lower_ext{extension};
|
||||
std::ranges::transform(extension, lower_ext.begin(), [](const char c) -> char { return std::tolower(c); });
|
||||
|
||||
if (lower_ext == ".jpg" || lower_ext == ".jpeg")
|
||||
{
|
||||
return pixelarium::imaging::ImageFileType::JPG;
|
||||
}
|
||||
if (lower_ext == ".png")
|
||||
{
|
||||
return pixelarium::imaging::ImageFileType::PNG;
|
||||
}
|
||||
if (lower_ext == ".czi")
|
||||
{
|
||||
return pixelarium::imaging::ImageFileType::CZI;
|
||||
}
|
||||
|
||||
return pixelarium::imaging::ImageFileType::UNKNOWN;
|
||||
}
|
||||
|
||||
class PixelariumImageFactory
|
||||
{
|
||||
public:
|
||||
static std::unique_ptr<IPixelariumImage> CreateImage(const std::string& uri);
|
||||
};
|
||||
} // namespace pixelarium::imaging
|
||||
@@ -1,11 +1,125 @@
|
||||
#include "PixelariumCzi.hpp"
|
||||
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <format>
|
||||
#include <memory>
|
||||
#include <opencv2/imgcodecs.hpp>
|
||||
#include <optional>
|
||||
#include <stdexcept>
|
||||
|
||||
#include "ILog.hpp"
|
||||
#include "libCZI.h"
|
||||
#include "libCZI_Pixels.h"
|
||||
|
||||
pixelarium::imaging::PixelariumCzi::PixelariumCzi(const std::string& uri)
|
||||
namespace
|
||||
{
|
||||
bool comp_blockinfo_params(const pixelarium::imaging::CziParams& params, const libCZI::SubBlockInfo& info)
|
||||
{
|
||||
bool res{true};
|
||||
|
||||
info.coordinate.EnumValidDimensions(
|
||||
[&](libCZI::DimensionIndex dim, int start) -> bool
|
||||
{
|
||||
if (params.dimension_map.at(dim) == start)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
res &= false;
|
||||
return true;
|
||||
});
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
constexpr int try_get_index_match(const pixelarium::imaging::CziParams& params, libCZI::ICZIReader& reader)
|
||||
{
|
||||
int index{-1};
|
||||
reader.EnumerateSubBlocks(
|
||||
[&](int idx, const libCZI::SubBlockInfo& info) -> bool
|
||||
{
|
||||
if (comp_blockinfo_params(params, info))
|
||||
{
|
||||
index = idx;
|
||||
// returning false will stop the enumeration
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
|
||||
return index;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
std::optional<cv::Mat> CZISubBlockToCvMat(std::shared_ptr<libCZI::IBitmapData> bitmap, libCZI::PixelType pixeltype,
|
||||
const pixelarium::utils::log::ILog& log)
|
||||
{
|
||||
const auto cv_pixel = GetCVPixelTypeAndSize(pixeltype);
|
||||
|
||||
// ToDo(MAK): fix this makeshift pixel-type-catch
|
||||
if (cv_pixel.size < 0 || cv_pixel.size > 4) return std::nullopt;
|
||||
|
||||
log.Info(std::format("{}: source pixel type {}, target cv pixel type {}, pixel size {}", __PRETTY_FUNCTION__,
|
||||
static_cast<uint8_t>(pixeltype), cv_pixel.type, cv_pixel.size));
|
||||
|
||||
size_t height{bitmap->GetHeight()};
|
||||
size_t width{bitmap->GetWidth()};
|
||||
auto fill_mat = cv::Mat(height, width, cv_pixel.type);
|
||||
|
||||
if (const auto bitmap_info = bitmap->Lock(); bitmap_info.ptrDataRoi)
|
||||
{
|
||||
for (size_t h{0}; h < height; ++h)
|
||||
{
|
||||
unsigned char* source_row = ((unsigned char*)bitmap_info.ptrDataRoi) + bitmap_info.stride * h;
|
||||
unsigned char* target_row = fill_mat.ptr(h);
|
||||
|
||||
for (size_t w{0}; w < width; ++w)
|
||||
{
|
||||
switch (cv_pixel.size)
|
||||
{
|
||||
case 1:
|
||||
target_row[w] = source_row[w];
|
||||
break;
|
||||
case 2:
|
||||
reinterpret_cast<unsigned short*>(target_row)[w] =
|
||||
reinterpret_cast<unsigned short*>(source_row)[w];
|
||||
break;
|
||||
case 3:
|
||||
target_row[3 * w] = source_row[3 * w];
|
||||
target_row[3 * w + 1] = source_row[3 * w + 1];
|
||||
target_row[3 * w + 2] = source_row[3 * w + 2];
|
||||
break;
|
||||
case 4:
|
||||
reinterpret_cast<std::int32_t*>(target_row)[w] = reinterpret_cast<std::int32_t*>(source_row)[w];
|
||||
break;
|
||||
default:
|
||||
throw std::runtime_error("Unknown pixel type requested!");
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// this is outside of the previous if-clause on purpose:
|
||||
// no matter if we reach the inner scope of this clause, we locked the bitmap,
|
||||
// so here it has to be unlocked.
|
||||
bitmap->Unlock();
|
||||
|
||||
return fill_mat;
|
||||
}
|
||||
|
||||
std::optional<cv::Mat> pixelarium::imaging::PixelariumCzi::SubblockToCvMat(int index)
|
||||
{
|
||||
log_.Info(std::format("{}: constructing bitmap with index {}", __PRETTY_FUNCTION__, index));
|
||||
auto block = this->czi_reader_->ReadSubBlock(index);
|
||||
auto bitmap = block->CreateBitmap();
|
||||
return CZISubBlockToCvMat(bitmap, block->GetSubBlockInfo().pixelType, log_);
|
||||
}
|
||||
|
||||
pixelarium::imaging::PixelariumCzi::PixelariumCzi(const std::string& uri, const Log& log) : log_(log)
|
||||
{
|
||||
if (!std::filesystem::exists(uri))
|
||||
{
|
||||
@@ -19,89 +133,26 @@ pixelarium::imaging::PixelariumCzi::PixelariumCzi(const std::string& uri)
|
||||
this->czi_reader_ = libCZI::CreateCZIReader();
|
||||
this->czi_reader_->Open(stream);
|
||||
this->image_statistics_ = this->czi_reader_->GetStatistics();
|
||||
}
|
||||
|
||||
std::unique_ptr<cv::Mat> CZISubBlockToCvMat(std::shared_ptr<libCZI::IBitmapData> bitmap, libCZI::PixelType pixeltype)
|
||||
{
|
||||
size_t pixel_size{0};
|
||||
int target_type;
|
||||
|
||||
switch (pixeltype)
|
||||
{
|
||||
case libCZI::PixelType::Gray8:
|
||||
pixel_size = 1;
|
||||
target_type = CV_8U;
|
||||
break;
|
||||
case libCZI::PixelType::Gray16:
|
||||
pixel_size = 2;
|
||||
target_type = CV_16U;
|
||||
break;
|
||||
case libCZI::PixelType::Bgr24:
|
||||
pixel_size = 3;
|
||||
target_type = CV_8UC3;
|
||||
break;
|
||||
case libCZI::PixelType::Bgra32:
|
||||
target_type = CV_8UC4;
|
||||
case libCZI::PixelType::Gray32:
|
||||
target_type = CV_32S;
|
||||
case libCZI::PixelType::Gray32Float:
|
||||
target_type = CV_32F;
|
||||
pixel_size = 4;
|
||||
break;
|
||||
// case libCZI::PixelType::Gray64ComplexFloat:
|
||||
// case libCZI::PixelType::Gray64Float:
|
||||
// target_type =
|
||||
// pixel_size = 8;
|
||||
// break;
|
||||
default:
|
||||
pixel_size = -1;
|
||||
break;
|
||||
}
|
||||
|
||||
if (pixel_size < 0) return nullptr;
|
||||
|
||||
size_t height{bitmap->GetHeight()};
|
||||
size_t width{bitmap->GetWidth()};
|
||||
auto fill_mat = std::make_unique<cv::Mat>(height, width, target_type);
|
||||
|
||||
auto bitmap_info = bitmap->Lock();
|
||||
|
||||
for (size_t h{0}; h < height; ++h)
|
||||
{
|
||||
unsigned char* source_row = ((unsigned char*)bitmap_info.ptrDataRoi) + bitmap_info.stride * h;
|
||||
unsigned char* target_row = fill_mat->ptr(h);
|
||||
|
||||
for (size_t w{0}; w < width; ++w)
|
||||
this->image_statistics_.dimBounds.EnumValidDimensions(
|
||||
[&](libCZI::DimensionIndex dim, int start, int) -> bool
|
||||
{
|
||||
switch (pixel_size)
|
||||
{
|
||||
case 1:
|
||||
target_row[w] = source_row[w];
|
||||
break;
|
||||
case 2:
|
||||
reinterpret_cast<unsigned short*>(target_row)[w] = reinterpret_cast<unsigned short*>(source_row)[w];
|
||||
break;
|
||||
case 3:
|
||||
target_row[3 * w] = source_row[3 * w];
|
||||
target_row[3 * w + 1] = source_row[3 * w + 1];
|
||||
target_row[3 * w + 2] = source_row[3 * w + 2];
|
||||
break;
|
||||
default:
|
||||
throw std::runtime_error("Unknown pixel type requested!");
|
||||
break;
|
||||
}
|
||||
}
|
||||
this->dimension_map_[dim] = start;
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
std::optional<cv::Mat> pixelarium::imaging::PixelariumCzi::TryGetImage() { return SubblockToCvMat(0); }
|
||||
|
||||
std::optional<cv::Mat> pixelarium::imaging::PixelariumCzi::TryGetImage(const IImageQuery& query)
|
||||
{
|
||||
const auto czi_query = static_cast<const CziParams&>(query);
|
||||
int index = try_get_index_match(czi_query, *this->czi_reader_);
|
||||
|
||||
if (index < 0)
|
||||
{
|
||||
return SubblockToCvMat(0);
|
||||
}
|
||||
|
||||
bitmap->Unlock();
|
||||
return fill_mat;
|
||||
}
|
||||
|
||||
std::unique_ptr<cv::Mat> pixelarium::imaging::PixelariumCzi::TryGetImage()
|
||||
{
|
||||
auto block = this->czi_reader_->ReadSubBlock(0);
|
||||
auto bitmap = block->CreateBitmap();
|
||||
auto res = CZISubBlockToCvMat(bitmap, block->GetSubBlockInfo().pixelType);
|
||||
|
||||
return res;
|
||||
return SubblockToCvMat(index);
|
||||
}
|
||||
|
||||
@@ -1,58 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
#include "../IPixelariumImage.hpp"
|
||||
#include "libCZI.h"
|
||||
|
||||
namespace pixelarium::imaging
|
||||
{
|
||||
struct CziParams : public IImageQuery
|
||||
{
|
||||
|
||||
};
|
||||
|
||||
class PixelariumCzi : public IPixelariumImage
|
||||
{
|
||||
public:
|
||||
explicit PixelariumCzi(const std::string& uri);
|
||||
~PixelariumCzi()
|
||||
{
|
||||
if (this->czi_reader_)
|
||||
this->czi_reader_->Close();
|
||||
}
|
||||
|
||||
// IPixelariumImage member implementations
|
||||
public:
|
||||
std::unique_ptr<cv::Mat> TryGetImage() override;
|
||||
|
||||
std::unique_ptr<cv::Mat> TryGetImage(const IImageQuery&) override
|
||||
{
|
||||
// ToDo: proper error
|
||||
throw std::runtime_error("Not implemented.");
|
||||
}
|
||||
|
||||
std::vector<std::unique_ptr<cv::Mat>> TryGetImages(const IImageQuery&) override
|
||||
{
|
||||
// ToDo: proper error
|
||||
throw std::runtime_error("Not implemented.");
|
||||
}
|
||||
|
||||
bool Empty() const noexcept override { return this->is_empty_; }
|
||||
|
||||
const libCZI::SubBlockStatistics& GetStatistics() const { return this->image_statistics_; }
|
||||
|
||||
public:
|
||||
const static ImageFileType type_{ImageFileType::CZI};
|
||||
|
||||
private:
|
||||
// this should be set by each image getter
|
||||
// after a new cv::Mat could be instantiated
|
||||
bool is_empty_{true};
|
||||
|
||||
libCZI::SubBlockStatistics image_statistics_;
|
||||
|
||||
std::shared_ptr<libCZI::ICZIReader> czi_reader_;
|
||||
};
|
||||
} // namespace pixelarium::imaging
|
||||
@@ -1,7 +1,5 @@
|
||||
#include "PixelariumJpg.hpp"
|
||||
|
||||
#include <filesystem>
|
||||
#include <memory>
|
||||
#include <opencv2/imgcodecs.hpp>
|
||||
#include <string>
|
||||
|
||||
@@ -16,11 +14,11 @@ pixelarium::imaging::PixelariumJpg::PixelariumJpg(const std::string& uri)
|
||||
this->uri_ = std::filesystem::path(uri);
|
||||
}
|
||||
|
||||
std::unique_ptr<cv::Mat> pixelarium::imaging::PixelariumJpg::TryGetImage()
|
||||
std::optional<cv::Mat> pixelarium::imaging::PixelariumJpg::TryGetImage()
|
||||
{
|
||||
try
|
||||
{
|
||||
auto img = std::make_unique<cv::Mat>(cv::imread(this->uri_.string()));
|
||||
auto img = cv::Mat(cv::imread(this->uri_.string()));
|
||||
|
||||
this->is_empty_ = false;
|
||||
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
#include "PixelariumMem.hpp"
|
||||
|
||||
#include <filesystem>
|
||||
#include <memory>
|
||||
#include <opencv2/imgcodecs.hpp>
|
||||
#include <string>
|
||||
|
||||
pixelarium::imaging::PixelariumMem::PixelariumMem(const cv::Mat& img, const std::string& name, const Log& log)
|
||||
: img_(img), log_(log), name_(name)
|
||||
{
|
||||
this->is_empty_ = false;
|
||||
this->uri_ = std::filesystem::path();
|
||||
}
|
||||
|
||||
std::optional<cv::Mat> pixelarium::imaging::PixelariumMem::TryGetImage()
|
||||
{
|
||||
// ToDo: this craving for a revision of the whole concept:
|
||||
// the interface requires a unique_ptr here. This concept was designed to "create an in-memory image on demand" sort
|
||||
// of.
|
||||
// I.e., it only makes sense for the file types that do not already manage a cv::Mat in memory.
|
||||
// PixelariumMem is meant for exactly this in-memory management of a cv::Mat though.
|
||||
// So, returning a unique_ptr from it in the following semantic essentially calls the
|
||||
// copy constructor of cv::Mat. This is potentially not "super bad", but at least it requires attention at some
|
||||
// point.
|
||||
return this->img_;
|
||||
}
|
||||
@@ -16,11 +16,11 @@ pixelarium::imaging::PixelariumPng::PixelariumPng(const std::string& uri)
|
||||
this->uri_ = std::filesystem::path(uri);
|
||||
}
|
||||
|
||||
std::unique_ptr<cv::Mat> pixelarium::imaging::PixelariumPng::TryGetImage()
|
||||
std::optional<cv::Mat> pixelarium::imaging::PixelariumPng::TryGetImage()
|
||||
{
|
||||
try
|
||||
{
|
||||
auto img = std::make_unique<cv::Mat>(cv::imread(this->uri_.string()));
|
||||
auto img = cv::Mat(cv::imread(this->uri_.string()));
|
||||
|
||||
this->is_empty_ = false;
|
||||
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
#include "PixelariumTiff.hpp"
|
||||
|
||||
#include <filesystem>
|
||||
#include <memory>
|
||||
#include <opencv2/imgcodecs.hpp>
|
||||
#include <string>
|
||||
|
||||
pixelarium::imaging::PixelariumTiff::PixelariumTiff(const std::string& uri, const Log& log) : log_(log)
|
||||
{
|
||||
if (!std::filesystem::exists(uri))
|
||||
{
|
||||
throw std::runtime_error("Render file not found.");
|
||||
}
|
||||
|
||||
this->is_empty_ = false;
|
||||
this->uri_ = std::filesystem::path(uri);
|
||||
}
|
||||
|
||||
std::optional<cv::Mat> pixelarium::imaging::PixelariumTiff::TryGetImage()
|
||||
{
|
||||
try
|
||||
{
|
||||
auto img = cv::Mat(cv::imread(this->uri_.string()));
|
||||
|
||||
this->is_empty_ = false;
|
||||
|
||||
return img;
|
||||
}
|
||||
catch (const std::exception& e)
|
||||
{
|
||||
this->is_empty_ = true;
|
||||
return {};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
#include "ILog.hpp"
|
||||
#include "IPixelariumImage.hpp"
|
||||
#include "libCZI.h"
|
||||
#include "libCZI_Pixels.h"
|
||||
|
||||
namespace
|
||||
{
|
||||
struct CvPixelTypeAndSize
|
||||
{
|
||||
int size{-1};
|
||||
int type{-1};
|
||||
};
|
||||
|
||||
template <typename P>
|
||||
[[nodiscard]] constexpr auto GetCVPixelTypeAndSize(P p) noexcept -> CvPixelTypeAndSize
|
||||
{
|
||||
switch (p)
|
||||
{
|
||||
case libCZI::PixelType::Gray8:
|
||||
return {1, CV_8U};
|
||||
case libCZI::PixelType::Gray16:
|
||||
return {2, CV_16U};
|
||||
case libCZI::PixelType::Bgr24:
|
||||
return {3, CV_8UC3};
|
||||
case libCZI::PixelType::Bgra32:
|
||||
return {4, CV_8UC4};
|
||||
case libCZI::PixelType::Gray32:
|
||||
return {4, CV_32S};
|
||||
case libCZI::PixelType::Gray32Float:
|
||||
return {4, CV_32F};
|
||||
default:
|
||||
return {};
|
||||
}
|
||||
}
|
||||
} // namespace
|
||||
|
||||
namespace pixelarium::imaging
|
||||
{
|
||||
/// @brief An implementation of IImageQuery to work on CZI images.
|
||||
/// @note Check the documentation here https://zeiss.github.io/libczi/pages/mainpage.html#czi-in-a-nutshell
|
||||
struct CziParams : public IImageQuery
|
||||
{
|
||||
/// @brief A map providing the start coordinate for each dimension in the CZI
|
||||
std::unordered_map<libCZI::DimensionIndex, int> dimension_map;
|
||||
};
|
||||
|
||||
/// @brief Implements support for .czi-images in the realm of IPixelariumImage
|
||||
class PixelariumCzi : public IPixelariumImageCvMat
|
||||
{
|
||||
using Log = pixelarium::utils::log::ILog;
|
||||
|
||||
public:
|
||||
explicit PixelariumCzi(const std::string& uri, const Log& log);
|
||||
~PixelariumCzi()
|
||||
{
|
||||
if (this->czi_reader_) this->czi_reader_->Close();
|
||||
}
|
||||
|
||||
// IPixelariumImage member implementations
|
||||
public:
|
||||
std::optional<cv::Mat> TryGetImage() override;
|
||||
|
||||
std::optional<cv::Mat> TryGetImage(const IImageQuery&) override;
|
||||
|
||||
std::vector<std::optional<cv::Mat>> TryGetImages(const IImageQuery&) override
|
||||
{
|
||||
// ToDo: proper error
|
||||
throw std::runtime_error("Not implemented.");
|
||||
}
|
||||
|
||||
public:
|
||||
bool Empty() const noexcept override { return this->is_empty_; }
|
||||
|
||||
const libCZI::SubBlockStatistics& GetStatistics() const { return this->image_statistics_; }
|
||||
|
||||
public:
|
||||
const static ImageFileType type_{ImageFileType::kCzi};
|
||||
|
||||
private:
|
||||
std::optional<cv::Mat> SubblockToCvMat(int index);
|
||||
|
||||
private:
|
||||
// this should be set by each image getter
|
||||
// after a new cv::Mat could be instantiated
|
||||
bool is_empty_{true};
|
||||
|
||||
libCZI::SubBlockStatistics image_statistics_;
|
||||
|
||||
std::shared_ptr<libCZI::ICZIReader> czi_reader_;
|
||||
|
||||
std::unordered_map<libCZI::DimensionIndex, int> dimension_map_;
|
||||
|
||||
const Log& log_;
|
||||
};
|
||||
} // namespace pixelarium::imaging
|
||||
@@ -3,35 +3,37 @@
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
|
||||
#include "../IPixelariumImage.hpp"
|
||||
#include "IPixelariumImage.hpp"
|
||||
|
||||
namespace pixelarium::imaging
|
||||
{
|
||||
class PixelariumJpg : public IPixelariumImage
|
||||
/// @brief Implements support for .jpg-images in the realm of IPixelariumImage
|
||||
class PixelariumJpg : public IPixelariumImageCvMat
|
||||
{
|
||||
public:
|
||||
explicit PixelariumJpg(const std::string& url);
|
||||
|
||||
// IPixelariumImage member implementations
|
||||
public:
|
||||
std::unique_ptr<cv::Mat> TryGetImage() override;
|
||||
std::optional<cv::Mat> TryGetImage() override;
|
||||
|
||||
std::unique_ptr<cv::Mat> TryGetImage(const IImageQuery&) override
|
||||
std::optional<cv::Mat> TryGetImage(const IImageQuery&) override
|
||||
{
|
||||
// ToDo: proper error
|
||||
throw std::runtime_error("Not possible with jpg.");
|
||||
}
|
||||
|
||||
std::vector<std::unique_ptr<cv::Mat>> TryGetImages(const IImageQuery&) override
|
||||
std::vector<std::optional<cv::Mat>> TryGetImages(const IImageQuery&) override
|
||||
{
|
||||
// ToDo: proper error
|
||||
throw std::runtime_error("Not possible with jpg.");
|
||||
}
|
||||
|
||||
public:
|
||||
bool Empty() const noexcept override { return this->is_empty_; }
|
||||
|
||||
public:
|
||||
const static ImageFileType type_{ImageFileType::JPG};
|
||||
const static ImageFileType type_{ImageFileType::kJpg};
|
||||
|
||||
private:
|
||||
// this should be set by each image getter
|
||||
@@ -0,0 +1,47 @@
|
||||
#pragma once
|
||||
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
|
||||
#include "ILog.hpp"
|
||||
#include "IPixelariumImage.hpp"
|
||||
|
||||
namespace pixelarium::imaging
|
||||
{
|
||||
/// @brief Implements support for in-memory images in the realm of IPixelariumImage
|
||||
class PixelariumMem : public IPixelariumImageCvMat
|
||||
{
|
||||
using Log = pixelarium::utils::log::ILog;
|
||||
|
||||
public:
|
||||
explicit PixelariumMem(const cv::Mat& img, const std::string& name, const Log& log);
|
||||
|
||||
// IPixelariumImage member implementations
|
||||
public:
|
||||
std::optional<cv::Mat> TryGetImage() override;
|
||||
|
||||
std::optional<cv::Mat> TryGetImage(const IImageQuery&) override { throw std::runtime_error("Not implemented."); }
|
||||
|
||||
std::vector<std::optional<cv::Mat>> TryGetImages(const IImageQuery&) override
|
||||
{
|
||||
throw std::runtime_error("Not implemented.");
|
||||
}
|
||||
|
||||
void SetImage(const cv::Mat& img) { this->img_ = img; }
|
||||
|
||||
std::string Name() const noexcept override { return this->name_; }
|
||||
|
||||
bool Empty() const noexcept override { return this->is_empty_; }
|
||||
|
||||
public:
|
||||
const static ImageFileType type_{ImageFileType::kMemory};
|
||||
|
||||
private:
|
||||
// this should be set by each image getter
|
||||
// after a new cv::Mat could be instantiated
|
||||
bool is_empty_{true};
|
||||
cv::Mat img_;
|
||||
const Log& log_;
|
||||
std::string name_;
|
||||
};
|
||||
} // namespace pixelarium::imaging
|
||||
@@ -3,26 +3,27 @@
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
|
||||
#include "../IPixelariumImage.hpp"
|
||||
#include "IPixelariumImage.hpp"
|
||||
|
||||
namespace pixelarium::imaging
|
||||
{
|
||||
class PixelariumPng : public IPixelariumImage
|
||||
/// @brief Implements support for .png-images in the realm of IPixelariumImage
|
||||
class PixelariumPng : public IPixelariumImageCvMat
|
||||
{
|
||||
public:
|
||||
explicit PixelariumPng(const std::string& url);
|
||||
|
||||
// IPixelariumImage member implementations
|
||||
public:
|
||||
std::unique_ptr<cv::Mat> TryGetImage() override;
|
||||
std::optional<cv::Mat> TryGetImage() override;
|
||||
|
||||
std::unique_ptr<cv::Mat> TryGetImage(const IImageQuery&) override
|
||||
std::optional<cv::Mat> TryGetImage(const IImageQuery&) override
|
||||
{
|
||||
// ToDo: proper error
|
||||
throw std::runtime_error("Not possible with png.");
|
||||
}
|
||||
|
||||
std::vector<std::unique_ptr<cv::Mat>> TryGetImages(const IImageQuery&) override
|
||||
std::vector<std::optional<cv::Mat>> TryGetImages(const IImageQuery&) override
|
||||
{
|
||||
// ToDo: proper error
|
||||
throw std::runtime_error("Not possible with png.");
|
||||
@@ -31,7 +32,7 @@ class PixelariumPng : public IPixelariumImage
|
||||
bool Empty() const noexcept override { return this->is_empty_; }
|
||||
|
||||
public:
|
||||
const static ImageFileType type_{ImageFileType::PNG};
|
||||
const static ImageFileType type_{ImageFileType::kPng};
|
||||
|
||||
private:
|
||||
// this should be set by each image getter
|
||||
@@ -0,0 +1,46 @@
|
||||
#pragma once
|
||||
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
|
||||
#include "ILog.hpp"
|
||||
#include "IPixelariumImage.hpp"
|
||||
|
||||
namespace pixelarium::imaging
|
||||
{
|
||||
/// @brief Implements support for .tiff-images in the realm of IPixelariumImage
|
||||
class PixelariumTiff : public IPixelariumImageCvMat
|
||||
{
|
||||
using Log = pixelarium::utils::log::ILog;
|
||||
|
||||
public:
|
||||
explicit PixelariumTiff(const std::string& uri, const Log& log);
|
||||
|
||||
// IPixelariumImage member implementations
|
||||
public:
|
||||
std::optional<cv::Mat> TryGetImage() override;
|
||||
|
||||
std::optional<cv::Mat> TryGetImage(const IImageQuery&) override
|
||||
{
|
||||
// ToDo: proper error
|
||||
throw std::runtime_error("Not possible with tiff.");
|
||||
}
|
||||
|
||||
std::vector<std::optional<cv::Mat>> TryGetImages(const IImageQuery&) override
|
||||
{
|
||||
// ToDo: proper error
|
||||
throw std::runtime_error("Not possible with tiff.");
|
||||
}
|
||||
|
||||
bool Empty() const noexcept override { return this->is_empty_; }
|
||||
|
||||
public:
|
||||
const static ImageFileType type_{ImageFileType::kTiff};
|
||||
|
||||
private:
|
||||
// this should be set by each image getter
|
||||
// after a new cv::Mat could be instantiated
|
||||
bool is_empty_{true};
|
||||
const Log& log_;
|
||||
};
|
||||
} // namespace pixelarium::imaging
|
||||
@@ -0,0 +1,153 @@
|
||||
#pragma once
|
||||
|
||||
#include <filesystem>
|
||||
#include <functional>
|
||||
#include <opencv2/core/mat.hpp>
|
||||
#include <string>
|
||||
|
||||
namespace pixelarium::imaging
|
||||
{
|
||||
using ImageQueryFunctor = std::function<void(const std::string&, void*, int*)>;
|
||||
|
||||
/// @brief Enumeration of supported image file types.
|
||||
enum class ImageFileType
|
||||
{
|
||||
/// @brief Represents an unknown or unsupported file type.
|
||||
kUnknown = -10,
|
||||
/// @brief Represents an abstract image type (e.g., a placeholder).
|
||||
kAbstract = 0,
|
||||
/// @brief Represents a PNG image file.
|
||||
kPng = 1,
|
||||
/// @brief Represents a JPG image file.
|
||||
kJpg = 2,
|
||||
/// @brief Represents a CZI image file.
|
||||
kCzi = 3,
|
||||
/// @brief Represents a TIFF image file.
|
||||
kTiff = 4,
|
||||
/// @brief Represents an in-memory image.
|
||||
kMemory = 5,
|
||||
};
|
||||
|
||||
/// @brief An abstract interface to define a semantic query
|
||||
/// for a multi-dimensional image.
|
||||
struct IImageQuery
|
||||
{
|
||||
virtual ~IImageQuery() = default;
|
||||
};
|
||||
|
||||
/// @brief This aims to be a generic image abstraction
|
||||
/// meant for codec specific implementation.
|
||||
template <class Data>
|
||||
class IPixelariumImage
|
||||
{
|
||||
public:
|
||||
virtual ~IPixelariumImage() = default;
|
||||
|
||||
/// @brief Attempts to retrieve the image.
|
||||
/// @return A unique pointer to a Mat object containing the image data,
|
||||
/// or nullptr if the image is not found or cannot be retrieved.
|
||||
/// May throw exceptions for multidimensional images.
|
||||
virtual std::optional<Data> TryGetImage() = 0;
|
||||
|
||||
/// @brief Attempts to retrieve the image.
|
||||
/// @param query The query object defining the images to retrieve.
|
||||
/// @return A unique pointer to a Mat object containing the image data,
|
||||
/// or nullptr if the image is not found or cannot be retrieved.
|
||||
virtual std::optional<Data> TryGetImage(const IImageQuery& query) = 0;
|
||||
|
||||
/// @brief Attempts to retrieve a collection of images based on a query.
|
||||
/// @param query The query object defining the images to retrieve.
|
||||
/// @return A vector of unique pointers to cv::Mat objects. Each element is an image.
|
||||
/// Returns an empty vector if no images are found or if an error occurs.
|
||||
virtual std::vector<std::optional<Data>> TryGetImages(const IImageQuery& query) = 0;
|
||||
|
||||
/// @brief Checks if the image is empty.
|
||||
/// @return true if the image is empty, false otherwise.
|
||||
virtual bool Empty() const noexcept = 0;
|
||||
|
||||
// default implemented
|
||||
public:
|
||||
/// @brief Gets the resource identifier as a file path.
|
||||
/// @return @c std::filesystem::path of the underlying resource.
|
||||
virtual std::filesystem::path Uri() const noexcept { return this->uri_; }
|
||||
|
||||
/// @brief Gets the resource name.
|
||||
/// @note Implementations of IPixelariumImage that live in memory
|
||||
/// should override this to get something meaningful as the name
|
||||
/// cannot be fetched from the resource uri in that case.
|
||||
/// @return The name of the underlying resource.
|
||||
virtual std::string Name() const noexcept
|
||||
{
|
||||
if (!this->uri_.empty())
|
||||
{
|
||||
return this->uri_.filename().string();
|
||||
}
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
public:
|
||||
const static ImageFileType type_{ImageFileType::kAbstract};
|
||||
|
||||
protected:
|
||||
std::filesystem::path uri_;
|
||||
};
|
||||
|
||||
/// @brief Interface template specialization of IPixelariumImage
|
||||
/// using cv::Mat as the wrapped data type.
|
||||
class IPixelariumImageCvMat : public IPixelariumImage<cv::Mat>
|
||||
{
|
||||
public:
|
||||
virtual ~IPixelariumImageCvMat() = default;
|
||||
|
||||
/// @brief Attempts to retrieve the image.
|
||||
/// @return A unique pointer to a Mat object containing the image data,
|
||||
/// or nullptr if the image is not found or cannot be retrieved.
|
||||
/// May throw exceptions for multidimensional images.
|
||||
virtual std::optional<cv::Mat> TryGetImage() = 0;
|
||||
|
||||
/// @brief Attempts to retrieve the image.
|
||||
/// @param query The query object defining the images to retrieve.
|
||||
/// @return A unique pointer to a Mat object containing the image data,
|
||||
/// or nullptr if the image is not found or cannot be retrieved.
|
||||
virtual std::optional<cv::Mat> TryGetImage(const IImageQuery& query) = 0;
|
||||
|
||||
/// @brief Attempts to retrieve a collection of images based on a query.
|
||||
/// @param query The query object defining the images to retrieve.
|
||||
/// @return A vector of unique pointers to cv::Mat objects. Each element is an image.
|
||||
/// Returns an empty vector if no images are found or if an error occurs.
|
||||
virtual std::vector<std::optional<cv::Mat>> TryGetImages(const IImageQuery& query) = 0;
|
||||
|
||||
/// @brief Checks if the image is empty.
|
||||
/// @return true if the image is empty, false otherwise.
|
||||
virtual bool Empty() const noexcept = 0;
|
||||
|
||||
/// @brief Saves an image to the resource identifier given by uri.
|
||||
/// @return true if saving was successful, false otherwise.
|
||||
virtual bool SaveImage(const std::string& uri);
|
||||
|
||||
// default implemented
|
||||
public:
|
||||
/// @brief Gets the resource identifier as a file path.
|
||||
/// @return @c std::filesystem::path of the underlying resource.
|
||||
virtual std::filesystem::path Uri() const noexcept { return this->uri_; }
|
||||
|
||||
/// @brief Gets the resource name.
|
||||
/// @note Implementations of IPixelariumImage that live in memory
|
||||
/// should override this to get something meaningful as the name
|
||||
/// cannot be fetched from the resource uri in that case.
|
||||
/// @return The name of the underlying resource.
|
||||
virtual std::string Name() const noexcept
|
||||
{
|
||||
if (!this->uri_.empty())
|
||||
{
|
||||
return this->uri_.filename().string();
|
||||
}
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
public:
|
||||
const static ImageFileType type_{ImageFileType::kAbstract};
|
||||
};
|
||||
} // namespace pixelarium::imaging
|
||||
@@ -0,0 +1,43 @@
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
|
||||
#include "ILog.hpp"
|
||||
#include "IPixelariumImage.hpp"
|
||||
|
||||
namespace pixelarium::imaging
|
||||
{
|
||||
constexpr pixelarium::imaging::ImageFileType ExtensionToType(const std::string& extension)
|
||||
{
|
||||
std::string lower_ext{extension};
|
||||
std::ranges::transform(extension, lower_ext.begin(), [](const char c) -> char { return std::tolower(c); });
|
||||
|
||||
if (lower_ext == ".jpg" || lower_ext == ".jpeg")
|
||||
{
|
||||
return pixelarium::imaging::ImageFileType::kJpg;
|
||||
}
|
||||
if (lower_ext == ".png")
|
||||
{
|
||||
return pixelarium::imaging::ImageFileType::kPng;
|
||||
}
|
||||
if (lower_ext == ".czi")
|
||||
{
|
||||
return pixelarium::imaging::ImageFileType::kCzi;
|
||||
}
|
||||
if (lower_ext == ".tiff" || lower_ext == ".tif")
|
||||
{
|
||||
return pixelarium::imaging::ImageFileType::kTiff;
|
||||
}
|
||||
|
||||
return pixelarium::imaging::ImageFileType::kUnknown;
|
||||
}
|
||||
|
||||
/// @brief Factory for instantiating implementations of IPixelariumImage based on the given file type.
|
||||
class PixelariumImageFactory
|
||||
{
|
||||
using Log = utils::log::ILog;
|
||||
|
||||
public:
|
||||
static std::unique_ptr<IPixelariumImageCvMat> CreateImage(const std::string& uri, const Log& log);
|
||||
};
|
||||
} // namespace pixelarium::imaging
|
||||
@@ -1,26 +0,0 @@
|
||||
set(RENDERLIBNAME pixelariumrenderlib)
|
||||
|
||||
set(RENDERLIBSRC
|
||||
RenderHelpers.hpp
|
||||
RenderHelpers.cpp
|
||||
CvMatRender.hpp
|
||||
CvMatRender.cpp
|
||||
RenderImageManager.hpp
|
||||
RenderImageManager.cpp
|
||||
IPixelariumImageView.hpp
|
||||
PixelariumImageViewDefault.hpp
|
||||
PixelariumImageViewDefault.cpp
|
||||
PixelariumImageViewCzi.hpp
|
||||
PixelariumImageViewCzi.cpp
|
||||
ImageViewFactory.hpp
|
||||
ImageViewFactory.cpp)
|
||||
|
||||
add_library(${RENDERLIBNAME} STATIC
|
||||
${RENDERLIBSRC})
|
||||
|
||||
target_link_libraries(${RENDERLIBNAME}
|
||||
PRIVATE pixelariumimagelib)
|
||||
|
||||
target_include_directories(${RENDERLIBNAME}
|
||||
PRIVATE ${CMAKE_SOURCE_DIR}/lib
|
||||
PRIVATE ${imgui_DIR})
|
||||
@@ -1,28 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
|
||||
#include "imaging/IPixelariumImage.hpp"
|
||||
#include "rendering/CvMatRender.hpp"
|
||||
|
||||
namespace pixelarium::render
|
||||
{
|
||||
class IPixelariumImageView
|
||||
{
|
||||
public:
|
||||
virtual ~IPixelariumImageView() = default;
|
||||
virtual void ShowImage() = 0;
|
||||
|
||||
// default implemented
|
||||
public:
|
||||
virtual const bool* GetStatus() const noexcept { return &this->open_p; }
|
||||
virtual void ForceUpdate() noexcept { this->is_dirty_ = true; }
|
||||
|
||||
protected:
|
||||
std::shared_ptr<imaging::IPixelariumImage> img_{};
|
||||
std::unique_ptr<cv::Mat> cached_image_{};
|
||||
render::CvMatRender render_;
|
||||
bool open_p{true};
|
||||
bool is_dirty_{true};
|
||||
};
|
||||
} // namespace pixelarium::render
|
||||
@@ -1,49 +0,0 @@
|
||||
#include "ImageViewFactory.hpp"
|
||||
|
||||
#include <memory>
|
||||
#include "imaging/PixelariumImageFactory.hpp"
|
||||
#include "rendering/IPixelariumImageView.hpp"
|
||||
#include "rendering/PixelariumImageViewCzi.hpp"
|
||||
#include "rendering/PixelariumImageViewDefault.hpp"
|
||||
|
||||
/// @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::IPixelariumImageView> pixelarium::render::ImageViewFactory::RenderImage(
|
||||
size_t image_id)
|
||||
{
|
||||
auto res{this->image_pool_.GetResource(image_id)};
|
||||
|
||||
auto img{res.lock()};
|
||||
|
||||
if (img == nullptr)
|
||||
{
|
||||
return {};
|
||||
}
|
||||
|
||||
if (img->Empty())
|
||||
{
|
||||
return {};
|
||||
}
|
||||
|
||||
auto type = imaging::ExtensionToType(img->Uri().extension().string());
|
||||
|
||||
switch (type)
|
||||
{
|
||||
case imaging::ImageFileType::UNKNOWN:
|
||||
case imaging::ImageFileType::ABSTRACT:
|
||||
return {};
|
||||
case imaging::ImageFileType::PNG:
|
||||
case imaging::ImageFileType::JPG:
|
||||
log_.Info("Creating a Default View");
|
||||
// beware: here we copy the actual image resource over to the new image
|
||||
return std::make_unique<PixelariumImageViewDefault>(img);
|
||||
case imaging::ImageFileType::CZI:
|
||||
log_.Info("{}: Creating a CZI View");
|
||||
// beware: here we copy the actual image resource over to the new image
|
||||
return std::make_unique<PixelariumImageViewCzi>(img);
|
||||
default:
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "PixelariumImageViewDefault.hpp"
|
||||
#include "rendering/IPixelariumImageView.hpp"
|
||||
#include "resources/resource.hpp"
|
||||
#include "utilities/ILog.hpp"
|
||||
namespace pixelarium::render
|
||||
{
|
||||
class ImageViewFactory
|
||||
{
|
||||
using Image = imaging::IPixelariumImage;
|
||||
using Pool = resources::ImageResourcePool;
|
||||
using Log = utils::log::ILog;
|
||||
|
||||
public:
|
||||
explicit ImageViewFactory(Pool& pool, const Log& log) : image_pool_(pool), log_(log) {}
|
||||
|
||||
std::unique_ptr<IPixelariumImageView> RenderImage(size_t id);
|
||||
|
||||
private:
|
||||
Pool& image_pool_;
|
||||
const Log& log_;
|
||||
};
|
||||
} // namespace pixelarium::render
|
||||
@@ -1,66 +0,0 @@
|
||||
#include "PixelariumImageViewCzi.hpp"
|
||||
|
||||
#include <format>
|
||||
|
||||
#include "RenderHelpers.hpp"
|
||||
#include "imaging/IPixelariumImage.hpp"
|
||||
#include "imaging/impl/PixelariumCzi.hpp"
|
||||
#include "imgui.h"
|
||||
|
||||
/// @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::PixelariumImageViewCzi::ShowImage()
|
||||
{
|
||||
auto czi_img = std::static_pointer_cast<imaging::PixelariumCzi>(this->img_);
|
||||
|
||||
if (!czi_img) return;
|
||||
|
||||
if (!this->cached_image_ || this->is_dirty_)
|
||||
{
|
||||
this->cached_image_ = this->img_->TryGetImage();
|
||||
this->is_dirty_ = false;
|
||||
}
|
||||
|
||||
if (czi_img->Empty() || this->img_->type_ == imaging::ImageFileType::UNKNOWN || !cached_image_ ||
|
||||
czi_img->Name().empty())
|
||||
{
|
||||
// do nothing
|
||||
return;
|
||||
}
|
||||
|
||||
ImGui::Begin(this->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(cached_image_->cols, cached_image_->rows);
|
||||
|
||||
ImGui::Image(reinterpret_cast<ImTextureID>(reinterpret_cast<void*>(texture)),
|
||||
aspect_const_dimensions(dim, 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::Text("Dimensions");
|
||||
ImGui::Separator();
|
||||
|
||||
auto stats = czi_img->GetStatistics();
|
||||
stats.dimBounds.EnumValidDimensions(
|
||||
[&](libCZI::DimensionIndex dim, int start, int size) -> bool
|
||||
{
|
||||
ImGui::Text("%c\t Start: %d\t End: %d", libCZI::Utils::DimensionToChar(dim), start, size);
|
||||
return true;
|
||||
});
|
||||
|
||||
ImGui::End();
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "imgui.h"
|
||||
#include "rendering/IPixelariumImageView.hpp"
|
||||
|
||||
namespace pixelarium::render
|
||||
{
|
||||
class PixelariumImageViewCzi : public IPixelariumImageView
|
||||
{
|
||||
using Image = imaging::IPixelariumImage;
|
||||
using Render = render::CvMatRender;
|
||||
|
||||
public:
|
||||
explicit PixelariumImageViewCzi(std::shared_ptr<Image> img)
|
||||
{
|
||||
img_ = img;
|
||||
render_ = Render(img_);
|
||||
}
|
||||
PixelariumImageViewCzi() = delete;
|
||||
PixelariumImageViewCzi(PixelariumImageViewCzi&) = delete;
|
||||
PixelariumImageViewCzi(const PixelariumImageViewCzi&) = delete;
|
||||
PixelariumImageViewCzi(PixelariumImageViewCzi&&) = delete;
|
||||
PixelariumImageViewCzi& operator=(PixelariumImageViewCzi&) = delete;
|
||||
PixelariumImageViewCzi& operator=(PixelariumImageViewCzi&&) = delete;
|
||||
|
||||
void ShowImage() override;
|
||||
|
||||
private:
|
||||
ImVec2 curr_dim_{};
|
||||
};
|
||||
} // namespace pixelarium::render
|
||||
@@ -1,50 +0,0 @@
|
||||
#include "PixelariumImageViewDefault.hpp"
|
||||
|
||||
#include <format>
|
||||
|
||||
#include "RenderHelpers.hpp"
|
||||
#include "imaging/IPixelariumImage.hpp"
|
||||
#include "imgui.h"
|
||||
/// @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::PixelariumImageViewDefault::ShowImage()
|
||||
{
|
||||
if (!this->cached_image_ || this->is_dirty_)
|
||||
{
|
||||
this->cached_image_ = this->img_->TryGetImage();
|
||||
this->is_dirty_ = false;
|
||||
}
|
||||
|
||||
if (this->img_->Empty() || this->img_->type_ == imaging::ImageFileType::UNKNOWN || !cached_image_ ||
|
||||
this->img_->Name().empty())
|
||||
{
|
||||
// do nothing
|
||||
return;
|
||||
}
|
||||
|
||||
ImGui::Begin(this->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(cached_image_->cols, cached_image_->rows);
|
||||
|
||||
ImGui::Image(reinterpret_cast<ImTextureID>(reinterpret_cast<void*>(texture)),
|
||||
aspect_const_dimensions(dim, 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();
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
|
||||
#include "imaging/IPixelariumImage.hpp"
|
||||
#include "imgui.h"
|
||||
#include "rendering/CvMatRender.hpp"
|
||||
#include "rendering/IPixelariumImageView.hpp"
|
||||
|
||||
namespace pixelarium::render
|
||||
{
|
||||
class PixelariumImageViewDefault : public IPixelariumImageView
|
||||
{
|
||||
using Image = imaging::IPixelariumImage;
|
||||
using Render = render::CvMatRender;
|
||||
|
||||
public:
|
||||
explicit PixelariumImageViewDefault(std::shared_ptr<Image> img)
|
||||
{
|
||||
img_ = img;
|
||||
render_ = Render(img_);
|
||||
}
|
||||
PixelariumImageViewDefault() = delete;
|
||||
PixelariumImageViewDefault(PixelariumImageViewDefault&) = delete;
|
||||
PixelariumImageViewDefault(const PixelariumImageViewDefault&) = delete;
|
||||
PixelariumImageViewDefault(PixelariumImageViewDefault&&) = delete;
|
||||
PixelariumImageViewDefault& operator=(PixelariumImageViewDefault&) = delete;
|
||||
PixelariumImageViewDefault& operator=(PixelariumImageViewDefault&&) = delete;
|
||||
|
||||
void ShowImage() override;
|
||||
|
||||
private:
|
||||
ImVec2 curr_dim_{};
|
||||
};
|
||||
} // namespace pixelarium::render
|
||||
@@ -1,14 +1,17 @@
|
||||
set(RESOURCELIBNAME pixelariumresourcelib)
|
||||
|
||||
set(RESOURCELIBSRC
|
||||
resource.hpp
|
||||
include/resource.hpp
|
||||
resource.cpp)
|
||||
|
||||
add_library(${RESOURCELIBNAME} STATIC
|
||||
${RESOURCELIBSRC})
|
||||
|
||||
add_library(pixelarium::lib::resources_static ALIAS ${RESOURCELIBNAME})
|
||||
|
||||
target_link_libraries(${RESOURCELIBNAME}
|
||||
PRIVATE pixelariumimagelib)
|
||||
PRIVATE pixelarium::lib::imaging_static)
|
||||
|
||||
target_include_directories(${RESOURCELIBNAME}
|
||||
PRIVATE ${CMAKE_SOURCE_DIR}/lib)
|
||||
INTERFACE
|
||||
PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include)
|
||||
|
||||
@@ -6,12 +6,13 @@
|
||||
#include <mutex>
|
||||
#include <unordered_map>
|
||||
|
||||
#include "imaging/IPixelariumImage.hpp"
|
||||
#include "IPixelariumImage.hpp"
|
||||
|
||||
namespace pixelarium::resources
|
||||
{
|
||||
using ResourceKey = size_t;
|
||||
|
||||
/// @brief A dedicated exception to be thrown when a resource of an IResourcePool is empty.
|
||||
struct empty_resource_exception : public std::exception
|
||||
{
|
||||
empty_resource_exception() {};
|
||||
@@ -22,16 +23,22 @@ struct empty_resource_exception : public std::exception
|
||||
std::string message_ = "Empty Resource";
|
||||
};
|
||||
|
||||
|
||||
/// @brief Abstract representation of a Resource.
|
||||
/// This is meant to be implemented by arbitrary explicit resource types and thus
|
||||
/// gives no contract other than the abstract type.
|
||||
struct IResource
|
||||
{
|
||||
virtual ~IResource() = default;
|
||||
};
|
||||
|
||||
/// @brief Defines a concept for a resource type
|
||||
/// @tparam R The resource template parameter
|
||||
template <typename R>
|
||||
concept ResT = requires(R& r) { static_cast<IResource&>(r); };
|
||||
|
||||
template <typename ResT>
|
||||
/// @brief Defines an interface for a resource pool
|
||||
/// @tparam ResT defines the resource type that is accepted by the pool
|
||||
template <typename ResT, class Data>
|
||||
class IResourcePool
|
||||
{
|
||||
public:
|
||||
@@ -41,7 +48,7 @@ class IResourcePool
|
||||
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::IPixelariumImage&)>& func) = 0;
|
||||
const std::function<void(ResourceKey, size_t, const imaging::IPixelariumImage<Data>&)>& func) = 0;
|
||||
virtual size_t GetTotalSize() const = 0;
|
||||
virtual void Clear() = 0;
|
||||
};
|
||||
@@ -51,7 +58,7 @@ class IResourcePool
|
||||
// reside with the =ResourcePool=!
|
||||
// In fact, the intention is, that there is no way back once the =ResourcePool= took ownership of an object.
|
||||
// Callers can get references, but no ownership. A caller might delete a resource though.
|
||||
class ImageResourcePool : public IResourcePool<imaging::IPixelariumImage>
|
||||
class ImageResourcePool : public IResourcePool<imaging::IPixelariumImageCvMat, cv::Mat>
|
||||
{
|
||||
public:
|
||||
ImageResourcePool() = default;
|
||||
@@ -61,17 +68,17 @@ class ImageResourcePool : public IResourcePool<imaging::IPixelariumImage>
|
||||
ImageResourcePool& operator=(ImageResourcePool&) = delete;
|
||||
ImageResourcePool& operator=(ImageResourcePool&&) = delete;
|
||||
|
||||
std::weak_ptr<imaging::IPixelariumImage> GetResource(ResourceKey id) const override;
|
||||
ResourceKey SetResource(std::unique_ptr<imaging::IPixelariumImage> res) override;
|
||||
bool ModifyResource(ResourceKey id, std::unique_ptr<imaging::IPixelariumImage> res) override;
|
||||
std::weak_ptr<imaging::IPixelariumImageCvMat> GetResource(ResourceKey id) const override;
|
||||
ResourceKey SetResource(std::unique_ptr<imaging::IPixelariumImageCvMat> res) override;
|
||||
bool ModifyResource(ResourceKey id, std::unique_ptr<imaging::IPixelariumImageCvMat> res) override;
|
||||
bool DeleteResource(ResourceKey id) override;
|
||||
void Clear() override { this->resources_.clear(); }
|
||||
|
||||
void EnumerateResources(
|
||||
const std::function<void(ResourceKey, size_t, const imaging::IPixelariumImage&)>& func) override;
|
||||
const std::function<void(ResourceKey, size_t, const imaging::IPixelariumImage<cv::Mat>&)>& func) override;
|
||||
|
||||
template <typename Callable>
|
||||
requires std::invocable<Callable, ResourceKey, size_t, const imaging::IPixelariumImage&>
|
||||
requires std::invocable<Callable, ResourceKey, size_t, const imaging::IPixelariumImageCvMat&>
|
||||
void Enumerate(Callable&& func) const
|
||||
{
|
||||
size_t idx{0};
|
||||
@@ -84,7 +91,7 @@ class ImageResourcePool : public IResourcePool<imaging::IPixelariumImage>
|
||||
size_t GetTotalSize() const override { return resources_.size(); }
|
||||
|
||||
private:
|
||||
std::unordered_map<size_t, std::shared_ptr<imaging::IPixelariumImage>> resources_;
|
||||
std::unordered_map<size_t, std::shared_ptr<imaging::IPixelariumImageCvMat>> resources_;
|
||||
std::mutex mut_;
|
||||
};
|
||||
} // namespace pixelarium::resources
|
||||
@@ -5,7 +5,9 @@
|
||||
#include <functional>
|
||||
#include <mutex>
|
||||
|
||||
using pixelarium::imaging::IPixelariumImage;
|
||||
#include "IPixelariumImage.hpp"
|
||||
|
||||
using Image = pixelarium::imaging::IPixelariumImageCvMat;
|
||||
using namespace std;
|
||||
|
||||
namespace
|
||||
@@ -21,7 +23,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::weak_ptr<IPixelariumImage> pixelarium::resources::ImageResourcePool::GetResource(ResourceKey id) const
|
||||
std::weak_ptr<Image> pixelarium::resources::ImageResourcePool::GetResource(ResourceKey id) const
|
||||
{
|
||||
auto search{this->resources_.find(id)};
|
||||
if (search == this->resources_.end()) return {};
|
||||
@@ -32,7 +34,7 @@ std::weak_ptr<IPixelariumImage> pixelarium::resources::ImageResourcePool::GetRes
|
||||
/// @brief Sets a resource in the pool.
|
||||
/// @param res A unique pointer to the resource to set.
|
||||
/// @return The ID of the new resource.
|
||||
size_t pixelarium::resources::ImageResourcePool::SetResource(unique_ptr<IPixelariumImage> res)
|
||||
size_t pixelarium::resources::ImageResourcePool::SetResource(unique_ptr<Image> res)
|
||||
{
|
||||
if (res == nullptr)
|
||||
{
|
||||
@@ -52,8 +54,7 @@ size_t pixelarium::resources::ImageResourcePool::SetResource(unique_ptr<IPixelar
|
||||
/// @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(ResourceKey id,
|
||||
std::unique_ptr<imaging::IPixelariumImage> res)
|
||||
bool pixelarium::resources::ImageResourcePool::ModifyResource(ResourceKey id, std::unique_ptr<Image> res)
|
||||
{
|
||||
auto search{this->resources_.find(id)};
|
||||
if (search == this->resources_.end()) return false;
|
||||
@@ -80,7 +81,7 @@ bool pixelarium::resources::ImageResourcePool::DeleteResource(ResourceKey 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(ResourceKey, size_t, const imaging::IPixelariumImage&)>& func)
|
||||
const std::function<void(ResourceKey, size_t, const imaging::IPixelariumImage<cv::Mat>&)>& func)
|
||||
{
|
||||
size_t idx{0};
|
||||
for (const auto& e : this->resources_)
|
||||
|
||||
@@ -1,12 +1,17 @@
|
||||
set(UTILSLIBNAME pixelariumutilslib)
|
||||
|
||||
set(UTILSLIBSRC
|
||||
ILog.hpp
|
||||
SpdLogger.hpp
|
||||
SpdLogger.cpp)
|
||||
include/ILog.hpp
|
||||
include/SpdLogger.hpp
|
||||
include/PixelariumLogger.hpp
|
||||
include/simple_thread_pool.hpp
|
||||
SpdLogger.cpp
|
||||
PixelariumLogger.cpp)
|
||||
|
||||
add_library(${UTILSLIBNAME} STATIC ${UTILSLIBSRC})
|
||||
|
||||
add_library(pixelarium::lib::utilities_static ALIAS ${UTILSLIBNAME})
|
||||
|
||||
# won't work
|
||||
# target_compile_options(${UTILSLIBNAME}
|
||||
# PRIVATE
|
||||
@@ -14,7 +19,9 @@ add_library(${UTILSLIBNAME} STATIC ${UTILSLIBSRC})
|
||||
# "$<$<CXX_COMPILER_ID:MSVC>:/utf-8>")
|
||||
|
||||
target_include_directories(${UTILSLIBNAME}
|
||||
INTERFACE
|
||||
PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include
|
||||
PRIVATE ${spdlog_DIR}/include)
|
||||
|
||||
target_link_libraries(${UTILSLIBNAME}
|
||||
PRIVATE spdlog::spdlog_header_only)
|
||||
PUBLIC spdlog::spdlog_header_only)
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
#pragma once
|
||||
#include <string>
|
||||
|
||||
namespace pixelarium::utils::log
|
||||
{
|
||||
enum class LogLevel
|
||||
{
|
||||
Trace = 1 << 0,
|
||||
Debug = 1 << 1,
|
||||
Info = 1 << 2,
|
||||
Warn = 1 << 3,
|
||||
Error = 1 << 4,
|
||||
};
|
||||
class ILog
|
||||
{
|
||||
public:
|
||||
virtual void Info(const std::string& msg) const = 0;
|
||||
virtual void Debug(const std::string& msg) const = 0;
|
||||
virtual void Warn(const std::string& msg) const = 0;
|
||||
virtual void Error(const std::string& msg) const = 0;
|
||||
virtual void ChangeLevel(LogLevel lvl) const = 0;
|
||||
|
||||
virtual ~ILog() {}
|
||||
};
|
||||
|
||||
} // namespace pixelarium::utils::log
|
||||
@@ -0,0 +1,73 @@
|
||||
#include "PixelariumLogger.hpp"
|
||||
|
||||
#include <chrono>
|
||||
#include <fstream>
|
||||
#include <memory>
|
||||
#include <ostream>
|
||||
#include <stdexcept>
|
||||
|
||||
using namespace pixelarium::utils::log;
|
||||
|
||||
struct PixelariumLogger::LogStream
|
||||
{
|
||||
LogStream(const std::string& sink)
|
||||
{
|
||||
out_stream_ = std::ofstream(sink, std::ios::app);
|
||||
if (!out_stream_)
|
||||
{
|
||||
throw std::runtime_error("Failed to open log stream");
|
||||
}
|
||||
}
|
||||
|
||||
~LogStream()
|
||||
{
|
||||
if (out_stream_.is_open())
|
||||
{
|
||||
out_stream_.close();
|
||||
}
|
||||
}
|
||||
|
||||
LogStream& operator<<(const std::string& str)
|
||||
{
|
||||
this->out_stream_ << str;
|
||||
return *this;
|
||||
}
|
||||
|
||||
private:
|
||||
std::ofstream out_stream_;
|
||||
};
|
||||
|
||||
PixelariumLogger::PixelariumLogger(const std::string& name, const std::string& file_sink)
|
||||
: name_(name), file_sink_(file_sink)
|
||||
{
|
||||
log_stream_ = std::make_unique<LogStream>(file_sink_);
|
||||
}
|
||||
|
||||
PixelariumLogger::~PixelariumLogger() = default;
|
||||
|
||||
auto PixelariumLogger::Write(LogLevel lvl, const std::string& msg) const -> void
|
||||
{
|
||||
if (lvl < this->level_)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
auto now = std::chrono::system_clock::now();
|
||||
auto time_t = std::chrono::system_clock::to_time_t(now);
|
||||
std::tm tm;
|
||||
#ifdef _WIN32
|
||||
localtime_s(&tm, &time_t);
|
||||
#else
|
||||
localtime_r(&time_t, &tm);
|
||||
#endif
|
||||
|
||||
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()) % 1000;
|
||||
|
||||
auto timestamp = std::format("{:04}-{:02}-{:02} {:02}:{:02}:{:02}.{:03}", tm.tm_year + 1900, tm.tm_mon + 1,
|
||||
tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec, ms.count());
|
||||
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(mutex_);
|
||||
*log_stream_ << std::format("[{}] [{}] [{}] {}\n", timestamp, name_, LogLevelToString(lvl), msg);
|
||||
}
|
||||
}
|
||||
+10
-10
@@ -30,15 +30,15 @@ void SpdLogger::ChangeLevel(LogLevel lvl) const
|
||||
{
|
||||
switch (l)
|
||||
{
|
||||
case LogLevel::Trace:
|
||||
case LogLevel::kTrace:
|
||||
return "Trace";
|
||||
case LogLevel::Debug:
|
||||
case LogLevel::kDebug:
|
||||
return "Debug";
|
||||
case LogLevel::Info:
|
||||
case LogLevel::kInfo:
|
||||
return "Info";
|
||||
case LogLevel::Warn:
|
||||
case LogLevel::kWarn:
|
||||
return "Warn";
|
||||
case LogLevel::Error:
|
||||
case LogLevel::kError:
|
||||
return "Error";
|
||||
default:
|
||||
return "Not Found";
|
||||
@@ -47,23 +47,23 @@ void SpdLogger::ChangeLevel(LogLevel lvl) const
|
||||
|
||||
switch (lvl)
|
||||
{
|
||||
case LogLevel::Trace:
|
||||
case LogLevel::kTrace:
|
||||
this->logger_->set_level(spdlog::level::trace);
|
||||
spdlog::flush_on(spdlog::level::trace);
|
||||
break;
|
||||
case LogLevel::Info:
|
||||
case LogLevel::kInfo:
|
||||
this->logger_->set_level(spdlog::level::info);
|
||||
spdlog::flush_on(spdlog::level::info);
|
||||
break;
|
||||
case LogLevel::Warn:
|
||||
case LogLevel::kWarn:
|
||||
this->logger_->set_level(spdlog::level::warn);
|
||||
spdlog::flush_on(spdlog::level::warn);
|
||||
break;
|
||||
case LogLevel::Error:
|
||||
case LogLevel::kError:
|
||||
this->logger_->set_level(spdlog::level::err);
|
||||
spdlog::flush_on(spdlog::level::err);
|
||||
break;
|
||||
case LogLevel::Debug:
|
||||
case LogLevel::kDebug:
|
||||
default:
|
||||
this->logger_->set_level(spdlog::level::debug);
|
||||
spdlog::flush_on(spdlog::level::debug);
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
#pragma once
|
||||
#include <string>
|
||||
|
||||
#ifdef _WIN32
|
||||
#define __PRETTY_FUNCTION__ __FUNCTION__
|
||||
#endif
|
||||
|
||||
namespace pixelarium::utils::log
|
||||
{
|
||||
enum class LogLevel
|
||||
{
|
||||
kTrace = 1 << 0,
|
||||
kDebug = 1 << 1,
|
||||
kInfo = 1 << 2,
|
||||
kWarn = 1 << 3,
|
||||
kError = 1 << 4,
|
||||
};
|
||||
|
||||
constexpr auto LogLevelToString(LogLevel lvl) -> std::string
|
||||
{
|
||||
switch (lvl)
|
||||
{
|
||||
case LogLevel::kTrace:
|
||||
return "Trace";
|
||||
case LogLevel::kDebug:
|
||||
return "Debug";
|
||||
case LogLevel::kInfo:
|
||||
return "Info";
|
||||
case LogLevel::kWarn:
|
||||
return "Warning";
|
||||
case LogLevel::kError:
|
||||
return "Error";
|
||||
}
|
||||
}
|
||||
|
||||
/// @brief Interface for logging implementations.
|
||||
class ILog
|
||||
{
|
||||
public:
|
||||
virtual void Info(const std::string& msg) const = 0;
|
||||
virtual void Debug(const std::string& msg) const = 0;
|
||||
virtual void Warn(const std::string& msg) const = 0;
|
||||
virtual void Error(const std::string& msg) const = 0;
|
||||
virtual void ChangeLevel(LogLevel lvl) const = 0;
|
||||
|
||||
virtual ~ILog() {}
|
||||
};
|
||||
|
||||
} // namespace pixelarium::utils::log
|
||||
@@ -0,0 +1,36 @@
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
|
||||
#include "ILog.hpp"
|
||||
|
||||
namespace pixelarium::utils::log
|
||||
{
|
||||
class PixelariumLogger : public ILog
|
||||
{
|
||||
private:
|
||||
struct LogStream;
|
||||
|
||||
public:
|
||||
explicit PixelariumLogger(const std::string& name, const std::string& file_sink);
|
||||
~PixelariumLogger();
|
||||
|
||||
void Info(const std::string& msg) const override { this->Write(LogLevel::kInfo, msg); }
|
||||
void Debug(const std::string& msg) const override { this->Write(LogLevel::kDebug, msg); }
|
||||
void Warn(const std::string& msg) const override { this->Write(LogLevel::kWarn, msg); }
|
||||
void Error(const std::string& msg) const override { this->Write(LogLevel::kError, msg); }
|
||||
void ChangeLevel(LogLevel lvl) const override { this->level_ = lvl; }
|
||||
|
||||
private:
|
||||
void Write(LogLevel, const std::string&) const;
|
||||
|
||||
private:
|
||||
std::mutex mutable mutex_;
|
||||
std::string name_;
|
||||
std::string file_sink_;
|
||||
std::unique_ptr<LogStream> log_stream_{};
|
||||
LogLevel mutable level_{LogLevel::kDebug};
|
||||
};
|
||||
} // namespace pixelarium::utils::log
|
||||
@@ -8,6 +8,8 @@
|
||||
#include "ILog.hpp"
|
||||
namespace pixelarium::utils::log
|
||||
{
|
||||
/// @brief Implements ILog using the spdlog library
|
||||
/// see https://github.com/gabime/spdlog
|
||||
class SpdLogger : public ILog
|
||||
{
|
||||
public:
|
||||
@@ -0,0 +1,128 @@
|
||||
#pragma once
|
||||
|
||||
#include <atomic>
|
||||
#include <condition_variable>
|
||||
#include <cstddef>
|
||||
#include <functional>
|
||||
#include <mutex>
|
||||
#include <queue>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
namespace pixelarium::utils
|
||||
{
|
||||
template <size_t N>
|
||||
class simple_thread_pool
|
||||
{
|
||||
public:
|
||||
simple_thread_pool()
|
||||
{
|
||||
static_assert(N > 0, "Pool must have at least one thread.");
|
||||
for (size_t i{0}; i < N; ++i)
|
||||
{
|
||||
workers_.emplace_back(
|
||||
[this]()
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
std::function<void()> job;
|
||||
{
|
||||
std::unique_lock<std::mutex> lck(thread_mutex_);
|
||||
|
||||
cv_.wait(lck, [this]() -> bool { return shutdown_ || !task_queue_.empty(); });
|
||||
|
||||
if (shutdown_ && task_queue_.empty()) return;
|
||||
|
||||
job = std::move(task_queue_.front());
|
||||
task_queue_.pop();
|
||||
++running_tasks_;
|
||||
}
|
||||
|
||||
job();
|
||||
--running_tasks_;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
simple_thread_pool(simple_thread_pool&) = delete;
|
||||
simple_thread_pool(const simple_thread_pool&) = delete;
|
||||
simple_thread_pool(simple_thread_pool&&) = delete;
|
||||
simple_thread_pool& operator=(simple_thread_pool&) = delete;
|
||||
simple_thread_pool& operator=(simple_thread_pool&&) = delete;
|
||||
~simple_thread_pool()
|
||||
{
|
||||
{
|
||||
std::unique_lock<std::mutex> lck(thread_mutex_);
|
||||
shutdown_ = true;
|
||||
}
|
||||
|
||||
cv_.notify_all();
|
||||
for (auto& th : workers_)
|
||||
{
|
||||
th.join();
|
||||
}
|
||||
}
|
||||
|
||||
public:
|
||||
template <typename Callable>
|
||||
requires std::invocable<Callable>
|
||||
auto enqueue(Callable&& fun) -> void
|
||||
{
|
||||
{
|
||||
std::unique_lock<std::mutex> lck(thread_mutex_);
|
||||
task_queue_.emplace(std::forward<Callable>(fun));
|
||||
}
|
||||
|
||||
cv_.notify_one();
|
||||
}
|
||||
|
||||
[[nodiscard]]
|
||||
decltype(auto) RunningTasks() const
|
||||
{
|
||||
return running_tasks_.load();
|
||||
}
|
||||
|
||||
decltype(auto) Joinable() const
|
||||
{
|
||||
std::unique_lock<std::mutex> lck(thread_mutex_);
|
||||
|
||||
return task_queue_.empty() && RunningTasks() == 0;
|
||||
}
|
||||
|
||||
private:
|
||||
std::vector<std::thread> workers_;
|
||||
std::condition_variable cv_;
|
||||
std::mutex mutable thread_mutex_;
|
||||
std::queue<std::function<void()>> task_queue_;
|
||||
bool shutdown_{false};
|
||||
std::atomic_size_t running_tasks_{0};
|
||||
};
|
||||
|
||||
class pixelarium_pool
|
||||
{
|
||||
public:
|
||||
[[nodiscard]]
|
||||
static decltype(auto) RunningTasks()
|
||||
{
|
||||
return pixelarium_pool::instance().RunningTasks();
|
||||
}
|
||||
|
||||
static decltype(auto) Joinable() { return pixelarium_pool::instance().Joinable(); }
|
||||
|
||||
template <typename Callable>
|
||||
requires std::invocable<Callable>
|
||||
static auto enqueue(Callable&& fun) -> void
|
||||
{
|
||||
pixelarium_pool::instance().enqueue(std::forward<Callable>(fun));
|
||||
}
|
||||
|
||||
private:
|
||||
static constexpr auto kThreadCount{20};
|
||||
static simple_thread_pool<kThreadCount>& instance()
|
||||
{
|
||||
static simple_thread_pool<kThreadCount> pixelarium_pool_instance;
|
||||
return pixelarium_pool_instance;
|
||||
}
|
||||
};
|
||||
} // namespace pixelarium::utils
|
||||
@@ -1,26 +0,0 @@
|
||||
#include <memory>
|
||||
|
||||
#include "DefaultApp.hpp"
|
||||
#include "resources/resource.hpp"
|
||||
#include "utilities/ILog.hpp"
|
||||
#include "utilities/SpdLogger.hpp"
|
||||
|
||||
int main(int argc, char** argv)
|
||||
{
|
||||
using namespace pixelarium;
|
||||
using namespace std;
|
||||
unique_ptr<utils::log::ILog> logger;
|
||||
#ifdef _WIN32
|
||||
logger = make_unique<utils::log::SpdLogger>(string(getenv("APPDATA")) + "/pixelarium/logfile.log", "default");
|
||||
#else
|
||||
logger = make_unique<utils::log::SpdLogger>(std::string(getenv("HOME")) + "/.cache/pixelarium/log.log", "default");
|
||||
#endif
|
||||
logger->Info(std::format("{}: Starting Application {}", __FUNCTION__, "Pixelarium"));
|
||||
|
||||
logger->ChangeLevel(utils::log::LogLevel::Debug);
|
||||
auto image_pool{std::make_unique<resources::ImageResourcePool>()};
|
||||
|
||||
pixelarium::ui::DefaultApp app = pixelarium::ui::DefaultApp(*logger, *image_pool);
|
||||
|
||||
app.Start();
|
||||
}
|
||||
+6
-10
@@ -1,17 +1,13 @@
|
||||
include(${PROJECT_SOURCE_DIR}/cmake/googletest.cmake)
|
||||
# this will trigger the FetchContent
|
||||
include(testgoogle)
|
||||
|
||||
add_executable(libpixelarium_UnitTests
|
||||
lib/resources/test_resource.cpp)
|
||||
|
||||
target_include_directories(libpixelarium_UnitTests
|
||||
PUBLIC ${PROJECT_SOURCE_DIR}/lib
|
||||
PUBLIC ${OpenCV_INCLUDE_DIRS}
|
||||
)
|
||||
|
||||
lib/resources/test_resource.cpp
|
||||
lib/utilities/test_simple_thread_pool.cpp)
|
||||
|
||||
target_link_libraries(libpixelarium_UnitTests
|
||||
pixelariumresourcelib
|
||||
pixelariumimagelib
|
||||
pixelarium::lib::resources_static
|
||||
pixelarium::lib::imaging_static
|
||||
GTest::gtest_main
|
||||
GTest::gmock)
|
||||
|
||||
|
||||
@@ -2,20 +2,21 @@
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
#include "resources/resource.hpp"
|
||||
#include "IPixelariumImage.hpp"
|
||||
#include "resource.hpp"
|
||||
|
||||
namespace
|
||||
{
|
||||
|
||||
// A Mock implementation for tests requiring _any_ instance of a IPixelariumImage
|
||||
class DummyImage : public pixelarium::imaging::IPixelariumImage
|
||||
class DummyImage : public pixelarium::imaging::IPixelariumImageCvMat
|
||||
{
|
||||
public:
|
||||
std::unique_ptr<cv::Mat> TryGetImage() override { return {}; }
|
||||
std::optional<cv::Mat> TryGetImage() override { return {}; }
|
||||
|
||||
std::unique_ptr<cv::Mat> TryGetImage(const pixelarium::imaging::IImageQuery&) override { return {}; }
|
||||
std::optional<cv::Mat> TryGetImage(const pixelarium::imaging::IImageQuery&) override { return {}; }
|
||||
|
||||
std::vector<std::unique_ptr<cv::Mat>> TryGetImages(const pixelarium::imaging::IImageQuery&) override { return {}; }
|
||||
std::vector<std::optional<cv::Mat>> TryGetImages(const pixelarium::imaging::IImageQuery&) override { return {}; }
|
||||
|
||||
std::string Name() const noexcept override { return {}; }
|
||||
|
||||
@@ -43,7 +44,7 @@ TEST(ImageResourcePoolTest, SetWrappedRawPointerGet)
|
||||
{
|
||||
ImageResourcePool pool;
|
||||
auto img = new DummyImage();
|
||||
auto id = pool.SetResource(std::unique_ptr<pixelarium::imaging::IPixelariumImage>(img));
|
||||
auto id = pool.SetResource(std::unique_ptr<pixelarium::imaging::IPixelariumImageCvMat>(img));
|
||||
auto res = pool.GetResource(id);
|
||||
auto res_img = res.lock();
|
||||
EXPECT_NE(res_img, nullptr);
|
||||
@@ -95,7 +96,7 @@ TEST(ImageResourcePoolTest, EnumerateResources)
|
||||
auto id2 = pool.SetResource(std::make_unique<DummyImage>());
|
||||
std::vector<size_t> found_ids{};
|
||||
|
||||
pool.EnumerateResources([&found_ids](size_t id, size_t, const pixelarium::imaging::IPixelariumImage&)
|
||||
pool.EnumerateResources([&found_ids](size_t id, size_t, const pixelarium::imaging::IPixelariumImage<cv::Mat>&)
|
||||
{ found_ids.push_back(id); });
|
||||
|
||||
EXPECT_EQ(found_ids.size(), 2);
|
||||
@@ -110,7 +111,7 @@ TEST(ImageResourcePoolTest, TemplatedEnumerate)
|
||||
auto id2 = pool.SetResource(std::make_unique<DummyImage>());
|
||||
std::vector<size_t> found_ids{};
|
||||
|
||||
pool.Enumerate([&found_ids](size_t id, size_t, const pixelarium::imaging::IPixelariumImage&)
|
||||
pool.Enumerate([&found_ids](size_t id, size_t, const pixelarium::imaging::IPixelariumImage<cv::Mat>&)
|
||||
{ found_ids.push_back(id); });
|
||||
|
||||
EXPECT_EQ(found_ids.size(), 2);
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <chrono>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
#include "simple_thread_pool.hpp"
|
||||
|
||||
TEST(SimpleThreadPoolTest, MutatesFromDifferentThread)
|
||||
{
|
||||
using namespace std::chrono_literals;
|
||||
using namespace pixelarium::utils;
|
||||
std::mutex mut;
|
||||
constexpr auto vecsize{10};
|
||||
std::vector<int> mutation_vector(vecsize, 0);
|
||||
|
||||
auto mutate = [&mutation_vector](int val, int loc) -> void { mutation_vector.at(loc) = val; };
|
||||
|
||||
for (auto i{0}; i < vecsize; ++i)
|
||||
{
|
||||
pixelarium_pool::enqueue(
|
||||
[&mutate, i]()
|
||||
{
|
||||
const auto wait = std::chrono::milliseconds(i);
|
||||
std::this_thread::sleep_for(wait);
|
||||
mutate(i, i);
|
||||
});
|
||||
}
|
||||
|
||||
// wait until each spawned task finished
|
||||
while (!pixelarium_pool::Joinable()) std::this_thread::sleep_for(5ms);
|
||||
|
||||
EXPECT_EQ(mutation_vector.size(), vecsize);
|
||||
for (auto i{0}; i < vecsize; ++i)
|
||||
{
|
||||
EXPECT_EQ(mutation_vector.at(i), i);
|
||||
}
|
||||
}
|
||||
|
||||
// TEST(SimpleThreadPoolTest, ZeroThreads)
|
||||
// {
|
||||
// using namespace pixelarium::utils;
|
||||
// // Creating a thread pool with 0 threads should not throw an exception
|
||||
// // and should be joinable immediately.
|
||||
// simple_thread_pool<0> pool;
|
||||
// EXPECT_TRUE(pool.Joinable());
|
||||
|
||||
// // Enqueuing a task on a 0-thread pool should not crash.
|
||||
// // The task will never run, but the enqueue operation should be valid.
|
||||
// pool.enqueue([]() {});
|
||||
// EXPECT_FALSE(pool.Joinable()); // Now it's not joinable because there's a task
|
||||
// EXPECT_EQ(pool.RunningTasks(), 0); // No tasks are running
|
||||
|
||||
// // Destructor should also handle the 0-thread case gracefully.
|
||||
// }
|
||||
Reference in New Issue
Block a user