diff --git a/.clang-format b/.clang-format new file mode 100644 index 000000000..5e7a0eb82 --- /dev/null +++ b/.clang-format @@ -0,0 +1,4 @@ +BasedOnStyle: Google +IndentWidth: 4 +ColumnLimit: 100 +AllowShortFunctionsOnASingleLine: false diff --git a/.editorconfig b/.editorconfig index 998c7dc75..4ce5fcbc1 100644 --- a/.editorconfig +++ b/.editorconfig @@ -15,9 +15,9 @@ max_line_length = 120 # ------------------------- # C++ / C headers # ------------------------- -[*.{cpp,h}] +[*.{hpp,cpp,c,h}] indent_style = space -indent_size = 2 +indent_size = 4 charset = utf-8 end_of_line = lf trim_trailing_whitespace = true diff --git a/.github/workflows/build-docs.yml b/.github/workflows/build-docs.yml new file mode 100644 index 000000000..b0aef78b5 --- /dev/null +++ b/.github/workflows/build-docs.yml @@ -0,0 +1,40 @@ +name: Build Documentation + +on: + workflow_call: + secrets: + ALGOLIA_APP_ID: + required: true + ALGOLIA_API_KEY: + required: true + ALGOLIA_INDEX_NAME: + required: true + +permissions: + contents: read + +jobs: + build-docs: + name: Build Docusaurus Site + runs-on: ubuntu-latest + container: + image: ryanmillard/img2num-dev:latest + steps: + - name: Checkout code + uses: actions/checkout@v6 + + - name: Install Dependendencies + run: pnpm --filter docs install + + - name: Build Docusaurus + env: + ALGOLIA_APP_ID: ${{ secrets.ALGOLIA_APP_ID }} + ALGOLIA_API_KEY: ${{ secrets.ALGOLIA_API_KEY }} + ALGOLIA_INDEX_NAME: ${{ secrets.ALGOLIA_INDEX_NAME }} + run: pnpm -F docs run build + + - name: Upload Documentation Artifacts + uses: actions/upload-artifact@v4 + with: + name: docs-build + path: docs/build diff --git a/.github/workflows/build-react-app.yml b/.github/workflows/build-react-app.yml new file mode 100644 index 000000000..3a517fe16 --- /dev/null +++ b/.github/workflows/build-react-app.yml @@ -0,0 +1,40 @@ +name: Build React App + +on: + workflow_call: + inputs: + wasm-artifacts-path: + required: false + type: string + +permissions: + contents: read + +jobs: + build-react-app: + name: Build React Example App + runs-on: ubuntu-latest + container: + image: ryanmillard/img2num-dev:latest + steps: + - name: Checkout code + uses: actions/checkout@v6 + + - name: Install Dependendencies + run: pnpm --filter react-example install + + - name: Download WASM artifacts + if: ${{ inputs.wasm-artifacts-path }} + uses: actions/download-artifact@v4 + with: + name: wasm-build + path: ${{ inputs.wasm-artifacts-path }} + + - name: Build React app + run: pnpm -F react-example run build + + - name: Upload React build artifacts + uses: actions/upload-artifact@v4 + with: + name: react-build + path: example-apps/react-js/dist/ diff --git a/.github/workflows/build-wasm.yml b/.github/workflows/build-wasm.yml new file mode 100644 index 000000000..719e8c705 --- /dev/null +++ b/.github/workflows/build-wasm.yml @@ -0,0 +1,29 @@ +name: Build WASM + +on: + workflow_call: + +permissions: + contents: read + +jobs: + build-wasm: + name: Build C++ (Emscripten) + runs-on: ubuntu-latest + container: + image: ryanmillard/img2num-dev:latest + steps: + - name: Checkout code + uses: actions/checkout@v6 + + - name: Run emcmake + run: emcmake cmake -B build-wasm/ . + + - name: Build using Emscripten + run: cmake --build build-wasm/ + + - name: Upload WASM build artifacts + uses: actions/upload-artifact@v4 + with: + name: wasm-build + path: packages/js/build-wasm/ diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 65ebea142..693c85f96 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -6,95 +6,50 @@ on: push: branches: [main] +permissions: + contents: read + jobs: lint: - name: Lint Code + name: Lint & Validate Code runs-on: ubuntu-latest + container: + image: ryanmillard/img2num-dev:latest steps: - name: Checkout code uses: actions/checkout@v6 - - name: Setup Node.js - uses: actions/setup-node@v6 - with: - node-version: "22" - cache: "npm" - - - name: Install dependencies - run: npm ci + - name: Install PNPM dependencies + run: pnpm install - name: Run ESLint - run: npm run lint - - - name: Run format check - run: npm run format:check - - - name: Run editorconfig-checker - run: npm run lint:style - validate-scripts: - runs-on: ubuntu-latest - steps: - # Checkout full history to ensure git diff works - - uses: actions/checkout@v6 - with: - fetch-depth: 0 - # Node.js setup - - name: Setup Node.js - uses: actions/setup-node@v6 - with: - node-version: 22 - # Install dependencies - - name: Install dependencies - run: npm ci - # Detect if scripts changed - - name: Determine if scripts changed - id: check_changes - shell: bash - run: | - echo "Checking for changed scripts..." - if [[ "${{ github.event_name }}" == "pull_request" ]]; then - BASE_SHA="${{ github.event.pull_request.base.sha }}" - else - BASE_SHA="${{ github.event.before }}" - fi - HEAD_SHA="${{ github.sha }}" - # Ensure a valid common ancestor (handles force-pushes) - BASE_SHA=$(git merge-base "$BASE_SHA" "$HEAD_SHA") - files=$(git diff --name-only "$BASE_SHA" "$HEAD_SHA") - echo "Changed files: $files" - match=false - for file in $files; do - if [[ "$file" == "package.json" || "$file" == "docs/package.json" ]]; then - if git diff "$BASE_SHA" "$HEAD_SHA" -- "$file" | grep -q '"scriptsInfo"'; then - match=true - break - fi - elif [[ "$file" == scripts/* || "$file" == docs/scripts/* ]]; then - match=true - break - fi - done - echo "scripts_changed=$match" >> "$GITHUB_OUTPUT" - # Run script validation if scripts changed - - name: Run script validation - id: validate - if: steps.check_changes.outputs.scripts_changed == 'true' - shell: bash - run: | - set -o pipefail - npm run validate-scripts 2>&1 | tee validation.log - echo "validation_exit_code=${PIPESTATUS[0]}" >> $GITHUB_OUTPUT - # Comment on PR if validation fails - - name: Comment on PR if validation fails - if: steps.validate.outputs.validation_exit_code != '0' && github.event_name == 'pull_request' - uses: ./.github/workflows/commenter.yml - with: - issue_number: ${{ github.event.pull_request.number }} - message: | - ⚠️ **Script validation failed!** - The following issues were found with your PR (latest 100 lines): - ``` - $(tail -n 100 validation.log) - ``` - is_pr: true + run: pnpm run eslint + + - name: Validate format + run: pnpm run format:check + + - name: Validate .editorconfig adherance + run: pnpm run editorconfig:check + + - name: Validate scriptsInfo in package.json + run: pnpm run validate-scripts + + build-wasm: + name: Build WASM + uses: ./.github/workflows/build-wasm.yml + + build-react-app: + name: Build React App + uses: ./.github/workflows/build-react-app.yml + needs: build-wasm + with: + wasm-artifacts-path: packages/js/build-wasm/ + + build-docs: + name: Build Documentation Site + uses: ./.github/workflows/build-docs.yml + secrets: + ALGOLIA_APP_ID: ${{ secrets.ALGOLIA_APP_ID }} + ALGOLIA_API_KEY: ${{ secrets.ALGOLIA_API_KEY }} + ALGOLIA_INDEX_NAME: ${{ secrets.ALGOLIA_INDEX_NAME }} diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index d96ceaabe..ab29aa731 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -5,59 +5,64 @@ on: branches: - main +permissions: + contents: write + jobs: - build-and-deploy: - runs-on: ubuntu-latest + build-wasm: + name: Build WASM + uses: ./.github/workflows/build-wasm.yml + + build-react-app: + name: Build React App + uses: ./.github/workflows/build-react-app.yml + needs: build-wasm + with: + wasm-artifacts-path: packages/js/build-wasm/ + + build-docs: + name: Build Documentation Site + uses: ./.github/workflows/build-docs.yml + secrets: + ALGOLIA_APP_ID: ${{ secrets.ALGOLIA_APP_ID }} + ALGOLIA_API_KEY: ${{ secrets.ALGOLIA_API_KEY }} + ALGOLIA_INDEX_NAME: ${{ secrets.ALGOLIA_INDEX_NAME }} + deploy-react-app: + name: Deploy React App to GitHub Pages + needs: build-react-app + runs-on: ubuntu-latest steps: - - name: Checkout repository - uses: actions/checkout@v6 + - name: Download React build artifacts + uses: actions/download-artifact@v4 + with: + name: react-build + path: ./react-dist + + - name: Deploy React App + uses: peaceiris/actions-gh-pages@4f9cc6602d3f66b9c108549d475ec49e8ef4d45e + with: + github_token: ${{ secrets.GITHUB_TOKEN }} + publish_dir: ./react-dist + user_name: "github-actions[bot]" + user_email: "github-actions[bot]@users.noreply.github.com" - - name: Setup Node.js - uses: actions/setup-node@v6 + deploy-docs: + name: Deploy Documentation to GitHub Pages + needs: build-docs + runs-on: ubuntu-latest + steps: + - name: Download Docs build artifacts + uses: actions/download-artifact@v4 with: - node-version: 20 - - - name: Install npm dependencies - run: npm ci - - - name: Install Emscripten SDK - run: | - # Download and extract EMSDK - curl -sSL https://github.com/emscripten-core/emsdk/archive/refs/tags/4.0.15.tar.gz | tar -xz - cd emsdk-4.0.15 - ./emsdk install latest - ./emsdk activate latest - - # Source into this shell so the build here works - source ./emsdk_env.sh - - # Persist variables for later steps - echo "EMSDK=${GITHUB_WORKSPACE}/emsdk-4.0.15" >> $GITHUB_ENV - echo "EMSDK_NODE=${GITHUB_WORKSPACE}/emsdk-4.0.15/node/22.16.0_64bit/bin/node" >> $GITHUB_ENV - echo "PATH=${GITHUB_WORKSPACE}/emsdk-4.0.15:${GITHUB_WORKSPACE}/emsdk-4.0.15/upstream/emscripten:$PATH" >> $GITHUB_ENV - - - name: Build Vite app - run: npm run build - - - name: Build Docusaurus site - env: - ALGOLIA_APP_ID: ${{ secrets.ALGOLIA_APP_ID }} - ALGOLIA_API_KEY: ${{ secrets.ALGOLIA_API_KEY }} - ALGOLIA_INDEX_NAME: ${{ secrets.ALGOLIA_INDEX_NAME }} - run: | - cd docs - npm ci - npm run build - cd .. - mkdir -p dist/info - cp -r docs/build/* dist/info/ - shell: bash - - - name: Deploy everything to GitHub Pages - uses: peaceiris/actions-gh-pages@v4 + name: docs-build + path: ./docs-dist + + - name: Deploy Documentation + uses: peaceiris/actions-gh-pages@4f9cc6602d3f66b9c108549d475ec49e8ef4d45e with: github_token: ${{ secrets.GITHUB_TOKEN }} - publish_dir: ./dist + publish_dir: ./docs-dist + destination_dir: info user_name: "github-actions[bot]" user_email: "github-actions[bot]@users.noreply.github.com" diff --git a/.gitignore b/.gitignore index 337a18a47..76e57fda2 100644 --- a/.gitignore +++ b/.gitignore @@ -1,15 +1,15 @@ +# pnpm +node_modules/ +.pnpm-store/ + +# cmake +build-wasm/ + +build*/ + # Logs logs *.log -npm-debug.log* -yarn-debug.log* -yarn-error.log* -pnpm-debug.log* -lerna-debug.log* - -node_modules -dist -dist-ssr *.local # Editor directories and files @@ -26,10 +26,4 @@ dist-ssr # OS Files *:Zone.Identifier -src/data/contributor-credits.json - .env -# CMake build artifacts -src/wasm/cmake-build/ -src/wasm/**/CMakeCache.txt -src/wasm/**/CMakeFiles/ diff --git a/.npmrc b/.npmrc new file mode 100644 index 000000000..73375d171 --- /dev/null +++ b/.npmrc @@ -0,0 +1,4 @@ +package-manager=pnpm +engine-strict=true +auto-install-peers=false +strict-peer-dependencies=true diff --git a/.prettierignore b/.prettierignore index 1b8ac8894..f839bdf2c 100644 --- a/.prettierignore +++ b/.prettierignore @@ -1,3 +1,33 @@ -# Ignore artifacts: -build -coverage +packages/js/build-wasm +docs/.docusaurus +docs/build/ +example-apps/react-js/dist/ +.clang-format +.devcontainer +.dockerignore +.editorconfig +.git/ +.gitattributes +.github/ +.gitignore +.prettierignore +.prettierrc +CMakeLists.txt +CODE_OF_CONDUCT.md +CONTRIBUTING.md +Dockerfile.dev +README.md +bindings/ +build*/ +core/ +docker-compose.yml +img2num +img2num.bat +img2num.ps1 +node_modules/ +scripts/ +pnpm-lock.yaml +.pnpm-store/ +docs/static/js/api.json +docs/docs/js/api/ +example-apps/react-js/src/data/contributor-credits.json diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 000000000..ab423d751 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,19 @@ +# ================================================================= +# Img2Num Top-Level +# ================================================================= +cmake_minimum_required(VERSION 3.16) +project(Img2Num LANGUAGES CXX) + +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +# Default build type +if(NOT CMAKE_BUILD_TYPE) + set(CMAKE_BUILD_TYPE Release CACHE STRING "Build type" FORCE) +endif() + +# Core library +add_subdirectory(core) + +# JS bindings +add_subdirectory(bindings/js) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index ede3fd587..60188d1a9 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -2,39 +2,15 @@ Want to contribute to Img2Num? There are a few things you need to know. -We wrote a [contribution guide](https://ryan-millard.github.io/Img2Num/info/docs/guidelines/contributing) to help you get started. +We wrote a [contribution guide](https://ryan-millard.github.io/Img2Num/info/docs/contributing) to help you get started. -## Quick Links +**A few important points:** -- **[Coding Style Guidelines](https://ryan-millard.github.io/Img2Num/info/docs/guidelines/coding-style)** - Code quality and linting standards -- **[CI/CD Workflows](https://ryan-millard.github.io/Img2Num/info/docs/reference/tools/ci-workflows)** - Understanding our automated checks -- **[Commit Guidelines](https://ryan-millard.github.io/Img2Num/info/docs/guidelines/commits)** - How to write good commit messages -- **[Pull Request Guidelines](https://ryan-millard.github.io/Img2Num/info/docs/guidelines/pull-requests)** - Creating and submitting PRs +- **Add tests** with your PR — new features and bug fixes **must** include tests where appropriate. PRs without tests are unlikely to be approved. +- Follow the repository's coding style rules. +- Use the issue and PR templates when filing issues or submitting code. Your PR will be rejected if you don't. -## Code Quality - -Before submitting a PR, ensure your code passes all checks: - -**With Docker:** - -```bash -./img2num npm ci # Install dependencies -./img2num lint # Check JavaScript/React code -./img2num lint:style # Check code style -./img2num npm run format:check # Verify formatting -``` - -**Local Dev:** - -```bash -npm ci # Install dependencies -npm run lint # Check JavaScript/React code -npm run lint:style # Check code style -npm run format:check # Verify formatting -``` - -For detailed information about linting, formatting, and fixing issues, see our -[Coding Style Guidelines](https://ryan-millard.github.io/Img2Num/info/docs/guidelines/coding-style). +If you're unsure what to change, [open a discussion](https://github.com/Ryan-Millard/Img2Num/discussions/new/choose) and someone will assist you. ## Questions? @@ -42,6 +18,6 @@ If you have questions or need help: - Open a [discussion](https://github.com/Ryan-Millard/Img2Num/discussions) - Create an [issue](https://github.com/Ryan-Millard/Img2Num/issues) -- Check existing PRs for examples +- Check existing PRs for ideas Thank you for improving Img2Num! 🎨🚀 diff --git a/Dockerfile.dev b/Dockerfile.dev index 02474aa9b..5809718f3 100644 --- a/Dockerfile.dev +++ b/Dockerfile.dev @@ -6,31 +6,39 @@ FROM node:22-bullseye ENV EMSDK_VERSION=4.0.10 ENV EMSDK_DIR=/opt/emsdk -RUN apt-get update && apt-get install -y --no-install-recommends \ - build-essential \ - cmake \ - python3 \ - git \ - curl \ - unzip \ - pkg-config \ - bash \ - ca-certificates \ - libvips-dev \ - && rm -rf /var/lib/apt/lists/* +RUN apt-get update \ + && apt-get install -y --no-install-recommends \ + build-essential \ + cmake \ + python3 \ + git \ + curl \ + unzip \ + pkg-config \ + bash \ + ca-certificates \ + libvips-dev \ + # graphviz enables diagrams in doxygen + doxygen graphviz \ + && rm -rf /var/lib/apt/lists/* # Install EMSDK once, cached by Docker layers RUN git clone --depth 1 https://github.com/emscripten-core/emsdk.git $EMSDK_DIR \ -&& cd $EMSDK_DIR \ -&& git fetch --tags \ -&& git checkout $EMSDK_VERSION \ -&& ./emsdk install $EMSDK_VERSION \ -&& ./emsdk activate $EMSDK_VERSION - + && cd $EMSDK_DIR \ + && git fetch --tags \ + && git checkout $EMSDK_VERSION \ + && ./emsdk install $EMSDK_VERSION \ + && ./emsdk activate $EMSDK_VERSION ENV PATH=$EMSDK_DIR:$EMSDK_DIR/upstream/emscripten:$PATH ENV EMSDK=$EMSDK_DIR -RUN npm install -g npm@11 +# Install pnpm +RUN corepack enable \ + && corepack prepare pnpm@10.29.1 --activate + +# Corepack installs pnpm here for root +ENV PATH=/root/.local/share/pnpm:$PATH +ENV PNPM_STORE_DIR=/pnpm/store WORKDIR /usr/src/app diff --git a/LICENSE b/LICENSE index 0ad25db4b..e13386ce9 100644 --- a/LICENSE +++ b/LICENSE @@ -1,661 +1,14 @@ - GNU AFFERO GENERAL PUBLIC LICENSE - Version 3, 19 November 2007 +Licensing - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. +This project is **primarily licensed under the MIT License** (see https://github.com/Ryan-Millard/Img2Num/blob/main/LICENSE-MIT). - Preamble +Certain files and folders remain licensed under the **GNU AGPLv3** (see https://github.com/Ryan-Millard/Img2Num/blob/main/LICENSE-AGPL): +- `example-apps/react-js/` (consumer example application built in React) +- `docs/` (project documentation) +- `.github/` (CI/config files) - The GNU Affero General Public License is a free, copyleft license for -software and other kinds of works, specifically designed to ensure -cooperation with the community in the case of network server software. +These AGPL-licensed files **do not affect the use or redistribution of the MIT-licensed packages**. - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -our General Public Licenses are intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. +This is because the project was originally licensed under the GNU AGPLv3. - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - Developers that use our General Public Licenses protect your rights -with two steps: (1) assert copyright on the software, and (2) offer -you this License which gives you legal permission to copy, distribute -and/or modify the software. - - A secondary benefit of defending all users' freedom is that -improvements made in alternate versions of the program, if they -receive widespread use, become available for other developers to -incorporate. Many developers of free software are heartened and -encouraged by the resulting cooperation. However, in the case of -software used on network servers, this result may fail to come about. -The GNU General Public License permits making a modified version and -letting the public access it on a server without ever releasing its -source code to the public. - - The GNU Affero General Public License is designed specifically to -ensure that, in such cases, the modified source code becomes available -to the community. It requires the operator of a network server to -provide the source code of the modified version running there to the -users of that server. Therefore, public use of a modified version, on -a publicly accessible server, gives the public access to the source -code of the modified version. - - An older license, called the Affero General Public License and -published by Affero, was designed to accomplish similar goals. This is -a different license, not a version of the Affero GPL, but Affero has -released a new version of the Affero GPL which permits relicensing under -this license. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU Affero General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Remote Network Interaction; Use with the GNU General Public License. - - Notwithstanding any other provision of this License, if you modify the -Program, your modified version must prominently offer all users -interacting with it remotely through a computer network (if your version -supports such interaction) an opportunity to receive the Corresponding -Source of your version by providing access to the Corresponding Source -from a network server at no charge, through some standard or customary -means of facilitating copying of software. This Corresponding Source -shall include the Corresponding Source for any work covered by version 3 -of the GNU General Public License that is incorporated pursuant to the -following paragraph. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the work with which it is combined will remain governed by version -3 of the GNU General Public License. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU Affero General Public License from time to time. Such new versions -will be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU Affero General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU Affero General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU Affero General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If your software can interact with users remotely through a computer -network, you should also make sure that it provides a way for users to -get its source. For example, if your program is a web application, its -interface could display a "Source" link that leads users to an archive -of the code. There are many ways you could offer source, and different -solutions will be better for different programs; see section 13 for the -specific requirements. - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU AGPL, see -. +Approval for relicensing the bulk of the project under MIT was granted by the relevant contributors in GitHub Discussion #230 (see https://github.com/Ryan-Millard/Img2Num/discussions/230). diff --git a/docs/docs/introduction/license.md b/LICENSE-AGPL similarity index 99% rename from docs/docs/introduction/license.md rename to LICENSE-AGPL index 773e9fd51..d6f45c602 100644 --- a/docs/docs/introduction/license.md +++ b/LICENSE-AGPL @@ -1,10 +1,5 @@ ---- -id: license -title: License -sidebar_position: 2 ---- +Note: This project also contains MIT-licensed files (core packages, scripts, libraries). See top-level LICENSE file for details. -``` GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 2007 @@ -666,4 +661,3 @@ specific requirements. if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see . -``` diff --git a/LICENSE-MIT b/LICENSE-MIT new file mode 100644 index 000000000..7bec07222 --- /dev/null +++ b/LICENSE-MIT @@ -0,0 +1,23 @@ +Note: This project also contains AGPL-licensed files (docs, React example app, CI/config). See top-level LICENSE file for details. + +MIT License + +Copyright (c) 2026 Ryan Millard + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index 54af79dc5..709a5d765 100644 --- a/README.md +++ b/README.md @@ -4,9 +4,7 @@ # Img2Num -[![Site Badge](https://img.shields.io/badge/site-online-blue.svg)](https://ryan-millard.github.io/Img2Num/) -[![Docs Badge](https://img.shields.io/badge/docs-online-blue.svg)](https://ryan-millard.github.io/Img2Num/info/) -[![License Badge](https://img.shields.io/badge/license-AGPLv3-blue.svg)](LICENSE) +[![Deploy to GitHub Pages](https://github.com/Ryan-Millard/Img2Num/actions/workflows/deploy.yml/badge.svg)](https://github.com/Ryan-Millard/Img2Num/actions/workflows/deploy.yml) @@ -61,9 +59,6 @@ Try it out now by [clicking here](https://ryan-millard.github.io/Img2Num/)! --- -> [!IMPORTANT] -> We're in the process of converting the C++ into a self-contained library that is separate from the React app. Stay tuned by watching this repo! - ## What this repository contains (short) - A React frontend that handles image input, preview and in-browser colouring. @@ -71,31 +66,26 @@ Try it out now by [clicking here](https://ryan-millard.github.io/Img2Num/)! This README is intentionally short — full installation steps, guides and references live in the docs site (see **Essential links** below). -## Essential links (docs site) +## Essential links Visit the docs site for full guides, API references and troubleshooting: -- [Quick start](https://ryan-millard.github.io/Img2Num/info/docs/introduction/getting-started) -- [Guidelines](https://ryan-millard.github.io/Img2Num/info/docs/category/-guidelines) - [Documentation](https://ryan-millard.github.io/Img2Num/info/docs/) -- [Reference & Advanced Guides](https://ryan-millard.github.io/Img2Num/info/docs/reference/) +- [Installation & Usage](https://ryan-millard.github.io/Img2Num/info/docs/js/) +- [Internal Documentation](https://ryan-millard.github.io/Img2Num/info/docs/internal/) - [Changelog](https://ryan-millard.github.io/Img2Num/info/changelog) +- [React Example App](https://ryan-millard.github.io/Img2Num/) ## Contributing -We welcome contributions from all places. Please read the [Contribution Guidelines](https://ryan-millard.github.io/Img2Num/info/docs/guidelines/contributing) and the pinned issues before opening issues or pull requests. - -**A few important points:** - -- **Add tests** with your PR — new features and bug fixes **must** include tests where appropriate. PRs without tests are unlikely to be approved. -- Follow the repository's [coding style rules](https://ryan-millard.github.io/Img2Num/info/docs/guidelines/coding-style) and [commit message rules](https://ryan-millard.github.io/Img2Num/info/docs/guidelines/commits). -- Use the issue and PR templates when filing issues or submitting code. Your PR will be rejected if you don't. +See our [CONTIRBUTING.md](https://github.com/Ryan-Millard/Img2Num/blob/main/CONTRIBUTING.md) -If you're unsure what to change, [open a discussion](https://github.com/Ryan-Millard/Img2Num/discussions/new/choose) and someone will assist you. +## License Summary -## License +- **MIT** — core packages, scripts, libraries, build tools, etc. +- **AGPLv3** — docs, example apps, CI/config. -[AGPLv3](https://ryan-millard.github.io/Img2Num/info/docs/license) +See the top-level [LICENSE](https://github.com/Ryan-Millard/Img2Num/blob/main/LICENSE) file for the explanation. ## Can't find something? diff --git a/bindings/LICENSE b/bindings/LICENSE new file mode 100644 index 000000000..6811d89ae --- /dev/null +++ b/bindings/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Ryan Millard + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/bindings/js/CMakeLists.txt b/bindings/js/CMakeLists.txt new file mode 100644 index 000000000..75a1881e1 --- /dev/null +++ b/bindings/js/CMakeLists.txt @@ -0,0 +1,62 @@ +# ================================================================= +# JS/WASM binding using core object library +# ================================================================= +cmake_minimum_required(VERSION 3.16) +project(JSBindings LANGUAGES CXX) + +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +# Must be built with Emscripten +if(NOT EMSCRIPTEN) + message(FATAL_ERROR "Emscripten is required to build JS bindings.") +endif() + +# Collect binding sources +file(GLOB_RECURSE BINDING_SRC "${CMAKE_CURRENT_SOURCE_DIR}/src/*.cpp") +file(GLOB_RECURSE BINDING_HEADERS "${CMAKE_CURRENT_SOURCE_DIR}/include/*.h") + +# Build WASM module +add_executable(img2num_wasm ${BINDING_SRC}) + +# Link core library object files +target_link_libraries(img2num_wasm PRIVATE core) + +# Include directories +target_include_directories(img2num_wasm PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR}/include +) + +# Emscripten options +set(COMMON_FLAGS + "SHELL:-s MODULARIZE=1" + "SHELL:-s EXPORT_ES6=1" + "SHELL:-s ENVIRONMENT=web,worker" + "SHELL:-s EXPORTED_FUNCTIONS=['_malloc','_free']" + "SHELL:-s EXPORTED_RUNTIME_METHODS=['ccall','cwrap','getValue','setValue','HEAPU8','HEAP32','UTF8ToString','stringToUTF8','lengthBytesUTF8']" + "SHELL:-s INITIAL_MEMORY=128MB" + "SHELL:-s MAXIMUM_MEMORY=2048MB" + "SHELL:-s ALLOW_MEMORY_GROWTH=1" + "SHELL:-s EXPORT_NAME=createImg2NumModule" +) + +target_compile_options(img2num_wasm PRIVATE -msimd128) +target_link_options(img2num_wasm PRIVATE ${COMMON_FLAGS} -msimd128) + +# Build type flags +if(CMAKE_BUILD_TYPE STREQUAL "Debug") + target_compile_options(img2num_wasm PRIVATE -O2 -g4) + target_link_options(img2num_wasm PRIVATE "SHELL:-s ASSERTIONS=2" -g4) +else() + target_compile_options(img2num_wasm PRIVATE -O3) + target_link_options(img2num_wasm PRIVATE "SHELL:-s SINGLE_FILE=0") +endif() + +# Output location +set_target_properties(img2num_wasm PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/packages/js/build-wasm" + OUTPUT_NAME "index" + SUFFIX ".js" +) + +message(STATUS "WASM module configured: img2num_wasm") diff --git a/bindings/js/Doxyfile b/bindings/js/Doxyfile new file mode 100644 index 000000000..b09f0bfdd --- /dev/null +++ b/bindings/js/Doxyfile @@ -0,0 +1,7 @@ +@INCLUDE = ../../docs/doxygen/Doxyfile.base + +PROJECT_NAME = "Img2Num JS/WASM Bindings" +PROJECT_NUMBER = dev + +INPUT = src +OUTPUT_DIRECTORY = ../../docs/static/docs/internal/bindings/js/api diff --git a/bindings/js/src/wasm_wrapper.cpp b/bindings/js/src/wasm_wrapper.cpp new file mode 100644 index 000000000..afbd4676d --- /dev/null +++ b/bindings/js/src/wasm_wrapper.cpp @@ -0,0 +1,41 @@ +#include +#include + +extern "C" { +EMSCRIPTEN_KEEPALIVE void gaussian_blur_fft(uint8_t *image, size_t width, size_t height, + double sigma) { + img2num::gaussian_blur_fft(image, width, height, sigma); +} + +EMSCRIPTEN_KEEPALIVE void invert_image(uint8_t *ptr, int width, int height) { + img2num::invert_image(ptr, width, height); +} + +EMSCRIPTEN_KEEPALIVE void threshold_image(uint8_t *ptr, const int width, const int height, + const int num_thresholds) { + img2num::threshold_image(ptr, width, height, num_thresholds); +} + +EMSCRIPTEN_KEEPALIVE void black_threshold_image(uint8_t *ptr, const int width, const int height, + const int num_thresholds) { + img2num::black_threshold_image(ptr, width, height, num_thresholds); +} + +EMSCRIPTEN_KEEPALIVE void kmeans(const uint8_t *data, uint8_t *out_data, int32_t *out_labels, + const int32_t width, const int32_t height, const int32_t k, + const int32_t max_iter, const uint8_t color_space) { + img2num::kmeans(data, out_data, out_labels, width, height, k, max_iter, color_space); +} + +EMSCRIPTEN_KEEPALIVE void bilateral_filter(uint8_t *image, size_t width, size_t height, + double sigma_spatial, double sigma_range, + uint8_t color_space) { + img2num::bilateral_filter(image, width, height, sigma_spatial, sigma_range, color_space); +} + +EMSCRIPTEN_KEEPALIVE char *labels_to_svg(uint8_t *data, int32_t *labels, const int width, + const int height, const int min_area, + const bool draw_contour_borders) { + return img2num::labels_to_svg(data, labels, width, height, min_area, draw_contour_borders); +} +} diff --git a/bindings/py/CMakeLists.txt b/bindings/py/CMakeLists.txt new file mode 100644 index 000000000..39e949139 --- /dev/null +++ b/bindings/py/CMakeLists.txt @@ -0,0 +1,13 @@ +# ================================================================= +# Python bindings via pybind11 +# ================================================================= +find_package(Python COMPONENTS Interpreter Development REQUIRED) +find_package(pybind11 REQUIRED) + +pybind11_add_module(img2num_python + src/python_wrapper.cpp +) + +# Link Python module to shared core library +target_link_libraries(img2num_python PRIVATE img2num_core) +target_include_directories(img2num_python PRIVATE ${CMAKE_SOURCE_DIR}/core/include) diff --git a/bindings/py/src/python_wrapper.cpp b/bindings/py/src/python_wrapper.cpp new file mode 100644 index 000000000..478918b10 --- /dev/null +++ b/bindings/py/src/python_wrapper.cpp @@ -0,0 +1,11 @@ +#include + +#include "img2num.h" + +namespace py = pybind11; + +PYBIND11_MODULE(img2num, m) { + m.doc() = "Img2Num library"; + + // m.def("some_function", &some_function, "A function from Img2Num"); +} diff --git a/src/wasm/.gitignore b/core/.gitignore similarity index 90% rename from src/wasm/.gitignore rename to core/.gitignore index f5539311f..ad9e46aa9 100644 --- a/src/wasm/.gitignore +++ b/core/.gitignore @@ -1,5 +1,5 @@ -# WASM build directory build/ +cmake-build/ # C++ object and binary files *.o diff --git a/core/CMakeLists.txt b/core/CMakeLists.txt new file mode 100644 index 000000000..7abebbd8e --- /dev/null +++ b/core/CMakeLists.txt @@ -0,0 +1,31 @@ +# ================================================================= +# Img2Num Core (Object Library) +# ================================================================= +cmake_minimum_required(VERSION 3.16) +project(CoreLibrary LANGUAGES CXX) + +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +file(GLOB_RECURSE CORE_SRC + "${CMAKE_CURRENT_SOURCE_DIR}/src/*.cpp" +) + +add_library(core OBJECT ${CORE_SRC}) + +# PUBLIC: only expose the directory that contains img2num.h +# PRIVATE: internal headers +target_include_directories(core + PUBLIC + ${CMAKE_CURRENT_SOURCE_DIR} # img2num.h + PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR}/include # internal headers +) + +# Emscripten flags +if(EMSCRIPTEN) + target_compile_options(core PRIVATE -msimd128) + target_link_options(core PRIVATE -msimd128) +endif() + +message(STATUS "Core library configured with ${CORE_SRC}") diff --git a/core/Doxyfile b/core/Doxyfile new file mode 100644 index 000000000..d9fd3ab63 --- /dev/null +++ b/core/Doxyfile @@ -0,0 +1,7 @@ +@INCLUDE = ../docs/doxygen/Doxyfile.base + +PROJECT_NAME = "Img2Num Core" +PROJECT_NUMBER = dev + +INPUT = img2num.h include src +OUTPUT_DIRECTORY = ../docs/static/docs/internal/core/api diff --git a/core/LICENSE b/core/LICENSE new file mode 100644 index 000000000..6811d89ae --- /dev/null +++ b/core/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Ryan Millard + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/core/img2num.h b/core/img2num.h new file mode 100644 index 000000000..d6c52c79c --- /dev/null +++ b/core/img2num.h @@ -0,0 +1,93 @@ +/** @file img2num.h + * @brief Core image processing functions for img2num project. + * @details This file declares functions for image manipulation, clustering, filtering, + * and conversion to SVG. Functions operate on raw image buffers (uint8_t*). + * @defgroup IMG2NUM_H Img2Num Core Functions + */ +#ifndef IMG2NUM_H +#define IMG2NUM_H + +#include +#include + +/// @note All image buffers are assumed to be stored in row-major order, unless otherwise noted. +namespace img2num { + +/// @brief Apply a Gaussian blur to an image using FFT. +/// @ingroup IMG2NUM_H +/// @param image Pointer to the image buffer (grayscale or single-channel). +/// @param width Width of the image in pixels. +/// @param height Height of the image in pixels. +/// @param sigma Standard deviation for Gaussian kernel. +/// @note The operation modifies the image buffer in-place. +void gaussian_blur_fft(uint8_t *image, size_t width, size_t height, double sigma); + +/// @brief Invert the pixel values of an image. +/// @ingroup IMG2NUM_H +/// @param ptr Pointer to the image buffer. +/// @param width Width of the image in pixels. +/// @param height Height of the image in pixels. +/// @note Each pixel value is replaced by 255 - original_value. +void invert_image(uint8_t *ptr, int width, int height); + +/// @brief Apply a thresholding operation to an image. +/// @ingroup IMG2NUM_H +/// @param ptr Pointer to the image buffer. +/// @param width Width of the image in pixels. +/// @param height Height of the image in pixels. +/// @param num_thresholds Number of thresholds to apply. +/// @note Thresholds split pixel intensity ranges into discrete levels. +void threshold_image(uint8_t *ptr, const int width, const int height, const int num_thresholds); + +/// @brief Apply black-thresholding to an image. +/// @ingroup IMG2NUM_H +/// @param ptr Pointer to the image buffer. +/// @param width Width of the image in pixels. +/// @param height Height of the image in pixels. +/// @param num_thresholds Number of thresholds to apply. +/// @note Similar to threshold_image but prioritizes darker pixels. +void black_threshold_image(uint8_t *ptr, const int width, const int height, + const int num_thresholds); + +/// @brief Perform k-means clustering on image data. +/// @ingroup IMG2NUM_H +/// @param data Pointer to input image data buffer. +/// @param out_data Pointer to output buffer where clustered pixel values are stored. +/// @param out_labels Pointer to output buffer for cluster labels per pixel. +/// @param width Width of the image in pixels. +/// @param height Height of the image in pixels. +/// @param k Number of clusters to compute. +/// @param max_iter Maximum number of iterations for the algorithm. +/// @param color_space Color space flag (0 = grayscale, 1 = RGB, etc.). +/// @note The function does not modify the input buffer. +void kmeans(const uint8_t *data, uint8_t *out_data, int32_t *out_labels, const int32_t width, + const int32_t height, const int32_t k, const int32_t max_iter, + const uint8_t color_space); + +/// @brief Apply bilateral filtering to an image. +/// @ingroup IMG2NUM_H +/// @param image Pointer to RGBA pixel buffer. +/// @param width Width of the image in pixels. +/// @param height Height of the image in pixels. +/// @param sigma_spatial Standard deviation for spatial Gaussian (proximity weight). +/// @param sigma_range Standard deviation for range Gaussian (intensity similarity weight). +/// @param color_space Color space flag (0 = grayscale, 1 = RGB, etc.). +/// @note The filter modifies the image buffer in-place. +void bilateral_filter(uint8_t *image, size_t width, size_t height, double sigma_spatial, + double sigma_range, uint8_t color_space); + +/// @brief Convert labeled regions of an image into an SVG string. +/// @ingroup IMG2NUM_H +/// @param data Pointer to image data buffer. +/// @param labels Pointer to label buffer, indicating region for each pixel. +/// @param width Width of the image in pixels. +/// @param height Height of the image in pixels. +/// @param min_area Minimum area (in pixels) for a region to be included in the SVG. +/// @param draw_contour_borders If true, contours of labeled regions will be drawn. +/// @return Pointer to a dynamically allocated C-string containing the SVG data. +/// @note Caller is responsible for freeing the returned string. +char *labels_to_svg(uint8_t *data, int32_t *labels, const int width, const int height, + const int min_area, const bool draw_contour_borders); +} // namespace img2num + +#endif // IMG2NUM_H diff --git a/core/include/Image.h b/core/include/Image.h new file mode 100644 index 000000000..b7ceddad8 --- /dev/null +++ b/core/include/Image.h @@ -0,0 +1,116 @@ +#ifndef IMAGE_H +#define IMAGE_H + +#include +#include +#include +#include + +#include "Pixel.h" +#include "PixelConverter.h" + +namespace ImageLib { +template +class Image { + static_assert(std::is_base_of_v, PixelT>, + "Image: PixelT must derive from Pixel"); + + public: + Image() : width(0), height(0) { + } + Image(int width, int height, PixelT fill = PixelT()) + : width(width), height(height), data(width * height, fill) { + } + + template + void loadFromBuffer(const uint8_t *buffer, int width, int height, + PixelConverter converter) { + // converter.convert must return exactly PixelT + static_assert(std::is_same_v, + "Converter return type must match PixelT"); + + this->width = width; + this->height = height; + const int pixelCount = getPixelCount(); + data.resize(pixelCount); + for (int i = 0; i < pixelCount; ++i) { + data[i] = converter.convert(&buffer[i * converter.bytesPerPixel]); + } + } + + void fill(const PixelT &color) { + std::fill(data.begin(), data.end(), color); + } + + using iter = typename std::vector::iterator; + iter begin() { + return data.begin(); + } + iter end() { + return data.end(); + } + using const_iter = typename std::vector::const_iterator; + const_iter begin() const { + return data.begin(); + } + const_iter end() const { + return data.end(); + } + + int getWidth() const { + return width; + } + int getHeight() const { + return height; + } + int getPixelCount() const { + return width * height; + } + int getSize() const { + return getPixelCount(); + } + + const std::vector &getData() const { + return data; + } + + const PixelT &getPixel(int x, int y) const { + return data[index(x, y)]; + } + PixelT &getPixel(int x, int y) { + return data[index(x, y)]; + } + + void setPixel(int x, int y, const PixelT &p) { + data[index(x, y)] = p; + } + + // Operator[] for flat indexing + PixelT &operator[](int idx) { + return data.at(idx); + } // set + const PixelT &operator[](int idx) const { + return data.at(idx); + } // get + + // Operator() for (x, y) access + PixelT &operator()(int x, int y) { + return data.at(index(x, y)); + } // set + const PixelT &operator()(int x, int y) const { + return data.at(index(x, y)); + } // get + + private: + std::vector data; + int width, height; + + int index(int x, int y) const { + if (x < 0 || y < 0 || x >= width || y >= height) + throw std::out_of_range("Pixel coordinates out of bounds"); + return y * width + x; + } +}; +} // namespace ImageLib + +#endif diff --git a/core/include/LABAPixel.h b/core/include/LABAPixel.h new file mode 100644 index 000000000..24bf46788 --- /dev/null +++ b/core/include/LABAPixel.h @@ -0,0 +1,34 @@ +#ifndef LABAPixel_H +#define LABAPixel_H + +#include "LABPixel.h" + +namespace ImageLib { +template +struct LABAPixel : public ImageLib::LABPixel { + // ----- Members ----- + NumberT alpha; + + // ----- Constructors ----- + constexpr LABAPixel(NumberT l = 0, NumberT a = 0, NumberT b = 0, NumberT alpha = 255) + : LABPixel(l, a, b), alpha(alpha) { + } + + // ----- Modifiers ----- + [[nodiscard]] inline bool operator==(const LABAPixel &other) const { + return LABPixel::operator==(other) && alpha == other.alpha; + } + [[nodiscard]] inline bool operator!=(const LABAPixel &other) const { + return !(*this == other); + } + + // ----- Utilities ----- + inline void setGray(NumberT gray, NumberT alpha = 255) { + LABPixel::setGray(gray); + this->alpha = alpha; + } + +} __attribute__((packed)); +} // namespace ImageLib + +#endif // LABAPixel_H diff --git a/core/include/LABPixel.h b/core/include/LABPixel.h new file mode 100644 index 000000000..85d5b0946 --- /dev/null +++ b/core/include/LABPixel.h @@ -0,0 +1,48 @@ +#ifndef LABPIXEL_H +#define LABPIXEL_H + +#include + +#include "Pixel.h" + +/* +can support signed data types +preferrably float or double +*/ + +namespace ImageLib { +template +struct LABPixel : public Pixel { + // ----- Members ----- + NumberT l, a, b; + + constexpr LABPixel(NumberT l = 0, NumberT a = 0, NumberT b = 0) : l(l), a(a), b(b) { + } + + // ----- Modifiers ----- + [[nodiscard]] inline bool operator==(const LABPixel &other) const { + return l == other.l && a == other.a && b == other.b; + } + [[nodiscard]] inline bool operator!=(const LABPixel &other) const { + return !(*this == other); + } + + // ----- Utilities ----- + inline void setGray(NumberT new_luma) { + l = new_luma; + a = b = 0; + } + + static inline float colorDistance(const LABPixel &a, const LABPixel &b) { + LABPixel af{static_cast(a.l), static_cast(a.a), + static_cast(a.b)}; + LABPixel bf{static_cast(b.l), static_cast(b.a), + static_cast(b.b)}; + return std::sqrt((a.l - b.l) * (a.l - b.l) + (a.a - b.a) * (a.a - b.a) + + (a.b - b.b) * (a.b - b.b)); + } + +} __attribute__((packed)); +} // namespace ImageLib + +#endif // LABPIXEL_H diff --git a/core/include/Pixel.h b/core/include/Pixel.h new file mode 100644 index 000000000..01aea89e0 --- /dev/null +++ b/core/include/Pixel.h @@ -0,0 +1,18 @@ +#ifndef PIXEL_H +#define PIXEL_H + +#include + +namespace ImageLib { +template +struct Pixel { + static_assert(std::is_arithmetic::value, + "Pixel: NumberT must be a numeric type"); + + using value_type = NumberT; + + ~Pixel() = default; +}; +} // namespace ImageLib + +#endif // PIXEL_H diff --git a/core/include/PixelConverter.h b/core/include/PixelConverter.h new file mode 100644 index 000000000..b7063c280 --- /dev/null +++ b/core/include/PixelConverter.h @@ -0,0 +1,20 @@ +#ifndef PIXELCONVERTER_H +#define PIXELCONVERTER_H + +#include +#include // for std::move + +namespace ImageLib { +template + +struct PixelConverter { + ConverterT convert; + uint8_t bytesPerPixel; + + PixelConverter(ConverterT conv, uint8_t bpp) : convert(std::move(conv)), bytesPerPixel(bpp) { + } +}; + +} // namespace ImageLib + +#endif diff --git a/src/wasm/modules/image/include/PixelConverters.h b/core/include/PixelConverters.h similarity index 53% rename from src/wasm/modules/image/include/PixelConverters.h rename to core/include/PixelConverters.h index 74fb382f4..919c4e369 100644 --- a/src/wasm/modules/image/include/PixelConverters.h +++ b/core/include/PixelConverters.h @@ -9,25 +9,23 @@ namespace ImageLib { template inline RGBPixel convertRGB(const uint8_t *p) { - return RGBPixel{static_cast(p[0]), - static_cast(p[1]), - static_cast(p[2])}; + return RGBPixel{static_cast(p[0]), static_cast(p[1]), + static_cast(p[2])}; } template inline RGBAPixel convertRGBA(const uint8_t *p) { - return RGBAPixel{ - static_cast(p[0]), static_cast(p[1]), - static_cast(p[2]), static_cast(p[3])}; + return RGBAPixel{static_cast(p[0]), static_cast(p[1]), + static_cast(p[2]), static_cast(p[3])}; } template -inline const PixelConverter (*)(const uint8_t *)> - RGB_CONVERTER{convertRGB, 3}; // 3 bytes per pixel +inline const PixelConverter (*)(const uint8_t *)> RGB_CONVERTER{ + convertRGB, 3}; // 3 bytes per pixel template -inline const PixelConverter (*)(const uint8_t *)> - RGBA_CONVERTER{convertRGBA, 4}; // 4 bytes per pixel +inline const PixelConverter (*)(const uint8_t *)> RGBA_CONVERTER{ + convertRGBA, 4}; // 4 bytes per pixel -} // namespace ImageLib +} // namespace ImageLib #endif diff --git a/core/include/Point.h b/core/include/Point.h new file mode 100644 index 000000000..f4b65a517 --- /dev/null +++ b/core/include/Point.h @@ -0,0 +1,45 @@ +#ifndef POINT_H +#define POINT_H + +// will start as integer values but can be adjusted to subpixel positions +struct Point { + float x = 0; + float y = 0; + + Point operator+(const Point &other) const { + return Point{x + other.x, y + other.y}; + } + + // Overload the - operator (subtraction) + Point operator-(const Point &other) const { + return Point{x - other.x, y - other.y}; + } + + // Overload the * operator (multiplication by a scalar) + // The left operand is the class object (this), the right is a double. + Point operator*(float scalar) const { + return Point{x * scalar, y * scalar}; + } + + Point operator/(float scalar) const { + return Point{x / scalar, y / scalar}; + } + + // Friend function to allow float * Vector + friend Point operator*(float scalar, const Point &v) { + return Point{v.x * scalar, v.y * scalar}; + ; // Calls the member function for the actual logic + } + + Point &operator+=(const Point &other) { + x += other.x; + y += other.y; + return *this; + } + + static float distSq(Point a, Point b) { + return (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y); + } +}; + +#endif \ No newline at end of file diff --git a/core/include/RGBAPixel.h b/core/include/RGBAPixel.h new file mode 100644 index 000000000..fdd88496b --- /dev/null +++ b/core/include/RGBAPixel.h @@ -0,0 +1,34 @@ +#ifndef RGBAPIXEL_H +#define RGBAPIXEL_H + +#include "RGBPixel.h" + +namespace ImageLib { +template +struct RGBAPixel : public ImageLib::RGBPixel { + // ----- Members ----- + NumberT alpha; + + // ----- Constructors ----- + constexpr RGBAPixel(NumberT red = 0, NumberT green = 0, NumberT blue = 0, NumberT alpha = 255) + : RGBPixel(red, green, blue), alpha(alpha) { + } + + // ----- Modifiers ----- + [[nodiscard]] inline bool operator==(const RGBAPixel &other) const { + return RGBPixel::operator==(other) && alpha == other.alpha; + } + [[nodiscard]] inline bool operator!=(const RGBAPixel &other) const { + return !(*this == other); + } + + // ----- Utilities ----- + inline void setGray(NumberT gray, NumberT alpha = 255) { + RGBPixel::setGray(gray); + this->alpha = alpha; + } + +} __attribute__((packed)); +} // namespace ImageLib + +#endif // RGBAPIXEL_H diff --git a/core/include/RGBPixel.h b/core/include/RGBPixel.h new file mode 100644 index 000000000..9d540faa5 --- /dev/null +++ b/core/include/RGBPixel.h @@ -0,0 +1,44 @@ +#ifndef RGBPIXEL_H +#define RGBPIXEL_H + +#include + +#include "Pixel.h" + +namespace ImageLib { +template +struct RGBPixel : public Pixel { + // ----- Members ----- + NumberT red, green, blue; + + constexpr RGBPixel(NumberT red = 0, NumberT green = 0, NumberT blue = 0) + : red(red), green(green), blue(blue) { + } + + // ----- Modifiers ----- + [[nodiscard]] inline bool operator==(const RGBPixel &other) const { + return red == other.red && green == other.green && blue == other.blue; + } + [[nodiscard]] inline bool operator!=(const RGBPixel &other) const { + return !(*this == other); + } + + // ----- Utilities ----- + inline void setGray(NumberT gray) { + red = green = blue = gray; + } + + static inline float colorDistance(const RGBPixel &a, const RGBPixel &b) { + RGBPixel af{static_cast(a.red), static_cast(a.green), + static_cast(a.blue)}; + RGBPixel bf{static_cast(b.red), static_cast(b.green), + static_cast(b.blue)}; + return std::sqrt((af.red - bf.red) * (af.red - bf.red) + + (af.green - bf.green) * (af.green - bf.green) + + (af.blue - bf.blue) * (af.blue - bf.blue)); + } + +} __attribute__((packed)); +} // namespace ImageLib + +#endif // RGBPIXEL_H diff --git a/core/include/SavitskyGolay.h b/core/include/SavitskyGolay.h new file mode 100644 index 000000000..5c15d2451 --- /dev/null +++ b/core/include/SavitskyGolay.h @@ -0,0 +1,29 @@ +#ifndef SAVITZKYGOLAY_H +#define SAVITZKYGOLAY_H + +#include + +#include "Point.h" + +struct Point; + +class SavitzkyGolay { + private: + int window_size_; + int window_radius_; // half window size + int poly_order_; + std::vector coeffs_; + + std::vector> invert_matrix(std::vector> A); + void compute_coefficients(); + + public: + SavitzkyGolay(int radius, int poly_order); + std::vector filter(const std::vector &data); + std::vector filter_wrap(const std::vector &data); + std::vector get_coeffs() const { + return coeffs_; + } +}; + +#endif // SAVITZKYGOLAY_H diff --git a/src/wasm/modules/image/include/bezier.h b/core/include/bezier.h similarity index 79% rename from src/wasm/modules/image/include/bezier.h rename to core/include/bezier.h index b35937143..6ec4ab626 100644 --- a/src/wasm/modules/image/include/bezier.h +++ b/core/include/bezier.h @@ -4,6 +4,5 @@ #include "contours.h" void fit_curve_reduction(const std::vector> &chains, - std::vector> &results, - float tolerance); + std::vector> &results, float tolerance); #endif \ No newline at end of file diff --git a/src/wasm/modules/image/include/cielab.h b/core/include/cielab.h similarity index 53% rename from src/wasm/modules/image/include/cielab.h rename to core/include/cielab.h index 72e339140..bf60cbca3 100644 --- a/src/wasm/modules/image/include/cielab.h +++ b/core/include/cielab.h @@ -1,39 +1,35 @@ #ifndef CIELAB_H #define CIELAB_H +#include +#include + #include "LABAPixel.h" #include "LABPixel.h" #include "RGBAPixel.h" #include "RGBPixel.h" -#include -#include // templates must be in headers template -void rgb_to_lab(const Tin r_u8, const Tin g_u8, const Tin b_u8, Tout &out_l, - Tout &out_a, Tout &out_b); +void rgb_to_lab(const Tin r_u8, const Tin g_u8, const Tin b_u8, Tout &out_l, Tout &out_a, + Tout &out_b); template -void lab_to_rgb(const Tin L, const Tin A, const Tin B, Tout &r_u8, Tout &g_u8, - Tout &b_u8); +void lab_to_rgb(const Tin L, const Tin A, const Tin B, Tout &r_u8, Tout &g_u8, Tout &b_u8); template -void rgb_to_lab(const ImageLib::RGBAPixel &rgba, - ImageLib::LABAPixel &laba); +void rgb_to_lab(const ImageLib::RGBAPixel &rgba, ImageLib::LABAPixel &laba); template -void rgb_to_lab(const ImageLib::RGBPixel &rgb, - ImageLib::LABPixel &lab); +void rgb_to_lab(const ImageLib::RGBPixel &rgb, ImageLib::LABPixel &lab); template -void lab_to_rgb(const ImageLib::LABAPixel &laba, - ImageLib::RGBAPixel &rgba); +void lab_to_rgb(const ImageLib::LABAPixel &laba, ImageLib::RGBAPixel &rgba); template -void lab_to_rgb(const ImageLib::LABPixel &lab, - ImageLib::RGBPixel &rgb); +void lab_to_rgb(const ImageLib::LABPixel &lab, ImageLib::RGBPixel &rgb); #include "cielab_impl.h" -#endif // CIELAB_H +#endif // CIELAB_H diff --git a/core/include/cielab_impl.h b/core/include/cielab_impl.h new file mode 100644 index 000000000..a1788bd83 --- /dev/null +++ b/core/include/cielab_impl.h @@ -0,0 +1,216 @@ +#ifndef CIELAB_IMPL_H +#define CIELAB_IMPL_H + +#ifndef CIELAB_H +#error "cielab_impl.h should not be included directly; include cielab.h instead" +#endif + +#include +#include + +// ====== Used in xyz_to_lab ======= +constexpr double DELTA{6.0 / 29.0}; // 0.2068966 +constexpr double DELTA_CUBED{DELTA * DELTA * DELTA}; // 0.008856 +constexpr double KAPPA{1.0 / (3.0 * DELTA * DELTA)}; // 7.787 +constexpr double EPSILON{16.0 / 116.0}; // 0.137931 + +// ====== Used in srgb_to_linear ====== +constexpr double SRGB_LINEAR_THRESHOLD{0.04045}; // linear segment boundary +constexpr double SRGB_LINEAR_FACTOR{12.92}; // scale factor for linear segment +constexpr double SRGB_GAMMA_OFFSET{0.055}; // offset for nonlinear segment +constexpr double SRGB_GAMMA{2.4}; // gamma exponent for nonlinear segment +constexpr double SRGB_GAMMA_INV{1.0 / SRGB_GAMMA}; // gamma exponent for nonlinear segment + +/* + * ====== Used in rgb_to_lab ====== + * + * sRGB Khronos/W3C Transformation Matrices (D65 illuminant) + * + * sRGB → CIE XYZ: + * ┌ ┐ ┌ ┐ ┌ ┐ + * │ X │ │ 0.4124564 0.3575761 0.1804375 │ │ R │ + * │ Y │ = │ 0.2126729 0.7151522 0.0721750 │ │ G │ + * │ Z │ │ 0.0193339 0.1191920 0.9503041 │ │ B │ + * └ ┘ └ ┘ └ ┘ + * + * Reference: ITU-R BT.709 / sRGB standard (IEC 61966-2-1:1999) + */ +constexpr double SRGB_R_TO_X{0.4124564}; +constexpr double SRGB_G_TO_X{0.3575761}; +constexpr double SRGB_B_TO_X{0.1804375}; +constexpr double SRGB_R_TO_Y{0.2126729}; +constexpr double SRGB_G_TO_Y{0.7151522}; +constexpr double SRGB_B_TO_Y{0.0721750}; +constexpr double SRGB_R_TO_Z{0.0193339}; +constexpr double SRGB_G_TO_Z{0.1191920}; +constexpr double SRGB_B_TO_Z{0.9503041}; + +/* + * ====== Used in lab_to_rgb ====== + * + * sRGB Khronos/W3C Transformation Matrices (D65 illuminant) + * Inverse transformation (XYZ → sRGB) per Khronos/W3C, D65 white, slightly + * different from original BT.709 inverse. + * + * CIE XYZ → sRGB (inverse): + * ┌ ┐ ┌ ┐ ┌ ┐ + * │ R │ │ 3.240970 -1.537383 -0.498611 │ │ X │ + * │ G │ = │ -0.969244 1.875968 0.041555 │ │ Y │ + * │ B │ │ 0.055630 -0.203977 1.056972 │ │ Z │ + * └ ┘ └ ┘ └ ┘ + * + * Reference: ITU-R BT.709 / sRGB standard (IEC 61966-2-1:1999) + */ +constexpr double SRGB_X_TO_R{3.240970}; +constexpr double SRGB_Y_TO_R{-1.537383}; +constexpr double SRGB_Z_TO_R{-0.498611}; +constexpr double SRGB_X_TO_G{-0.969244}; +constexpr double SRGB_Y_TO_G{1.875968}; +constexpr double SRGB_Z_TO_G{0.041555}; +constexpr double SRGB_X_TO_B{0.055630}; +constexpr double SRGB_Y_TO_B{-0.203977}; +constexpr double SRGB_Z_TO_B{1.056972}; + +// Reference white point for D65 illuminant +constexpr double D65_Xn{0.95047}; +constexpr double D65_Yn{1.0}; +constexpr double D65_Zn{1.08883}; + +constexpr double LAB_L_FACTOR{116.0}; +constexpr double LAB_L_OFFSET{16.0}; +constexpr double LAB_A_FACTOR{500.0}; +constexpr double LAB_B_FACTOR{200.0}; + +// Function for the non-linear XYZ to Lab transformation +inline double xyz_to_lab(const double t) { + // prevent negative due to tiny floating errors + const double safe_t{std::max(0.0, t)}; + return (safe_t > DELTA_CUBED) ? std::cbrt(safe_t) : (KAPPA * safe_t) + EPSILON; +} + +// Function for the non-linear sRGB to linear RGB transformation (inverse gamma +// correction) +inline double srgb_to_linear(const double c) { + const double safe_c{std::clamp(c, 0.0, 1.0)}; + return (safe_c <= SRGB_LINEAR_THRESHOLD) + ? safe_c / SRGB_LINEAR_FACTOR + : std::pow((safe_c + SRGB_GAMMA_OFFSET) / (1.0 + SRGB_GAMMA_OFFSET), SRGB_GAMMA); +} + +template +void rgb_to_lab(const Tin r_u8, const Tin g_u8, const Tin b_u8, Tout &out_l, Tout &out_a, + Tout &out_b) { + // 1. Convert 8-bit RGB [0, 255] to linear RGB [0.0, 1.0] + + double _r = static_cast(r_u8); + double _g = static_cast(g_u8); + double _b = static_cast(b_u8); + + double r{srgb_to_linear(_r / 255.0)}; + double g{srgb_to_linear(_g / 255.0)}; + double b{srgb_to_linear(_b / 255.0)}; + + // 2. Convert linear RGB to CIE XYZ (using D65 white point reference) + // The matrix below is for sRGB to XYZ (D65) + const double x{SRGB_R_TO_X * r + SRGB_G_TO_X * g + SRGB_B_TO_X * b}; + const double y{SRGB_R_TO_Y * r + SRGB_G_TO_Y * g + SRGB_B_TO_Y * b}; + const double z{SRGB_R_TO_Z * r + SRGB_G_TO_Z * g + SRGB_B_TO_Z * b}; + + // Normalize XYZ values by the white point + const double Xr{x / D65_Xn}; + const double Yr{y / D65_Yn}; + const double Zr{z / D65_Zn}; + + // 3. Convert CIE XYZ to CIE L*a*b* + const double fx{xyz_to_lab(Xr)}; + const double fy{xyz_to_lab(Yr)}; + const double fz{xyz_to_lab(Zr)}; + + // 4. Output values + out_l = static_cast(LAB_L_FACTOR * fy - LAB_L_OFFSET); + out_a = static_cast(LAB_A_FACTOR * (fx - fy)); + out_b = static_cast(LAB_B_FACTOR * (fy - fz)); + + out_l = std::clamp(out_l, static_cast(0.0), static_cast(100.0)); +} + +constexpr double inverse_xyz_to_lab(double t) { + return (t > DELTA) ? (t * t * t) : (3 * DELTA * DELTA * (t - EPSILON)); +} + +inline double gamma_encode(double u) { + // Guard against negative values from out-of-gamut colors + u = std::max(0.0, u); + return (u <= SRGB_LINEAR_THRESHOLD / SRGB_LINEAR_FACTOR) + ? SRGB_LINEAR_FACTOR * u + : (1.0 + SRGB_GAMMA_OFFSET) * std::pow(u, SRGB_GAMMA_INV) - SRGB_GAMMA_OFFSET; +} + +template +void lab_to_rgb(const Tin L, const Tin A, const Tin B, Tout &out_r_u8, Tout &out_g_u8, + Tout &out_b_u8) { + const double _L = static_cast(L); + const double _A = static_cast(A); + const double _B = static_cast(B); + + // --- Lab → XYZ (D65 white point) + const double fy{(_L + LAB_L_OFFSET) / LAB_L_FACTOR}; + const double fx{fy + _A / LAB_A_FACTOR}; + const double fz{fy - _B / LAB_B_FACTOR}; + + const double X{D65_Xn * inverse_xyz_to_lab(fx)}; + const double Y{D65_Yn * inverse_xyz_to_lab(fy)}; + const double Z{D65_Zn * inverse_xyz_to_lab(fz)}; + + // --- XYZ → linear RGB (sRGB) + double r{SRGB_X_TO_R * X + SRGB_Y_TO_R * Y + SRGB_Z_TO_R * Z}; + double g{SRGB_X_TO_G * X + SRGB_Y_TO_G * Y + SRGB_Z_TO_G * Z}; + double b{SRGB_X_TO_B * X + SRGB_Y_TO_B * Y + SRGB_Z_TO_B * Z}; + + // --- linear RGB → sRGB (gamma correction) + r = gamma_encode(std::clamp(r, 0.0, 1.0)); + g = gamma_encode(std::clamp(g, 0.0, 1.0)); + b = gamma_encode(std::clamp(b, 0.0, 1.0)); + + // --- Clamp and convert to 8-bit + out_r_u8 = static_cast(std::round(255.0 * std::clamp(r, 0.0, 1.0))); + out_g_u8 = static_cast(std::round(255.0 * std::clamp(g, 0.0, 1.0))); + out_b_u8 = static_cast(std::round(255.0 * std::clamp(b, 0.0, 1.0))); +} + +template +void rgb_to_lab(const ImageLib::RGBAPixel &rgba, ImageLib::LABAPixel &laba) { + Tout l{laba.l}; + Tout a{laba.a}; + Tout b{laba.b}; + + rgb_to_lab(rgba.red, rgba.green, rgba.blue, l, a, b); + + laba.l = l; + laba.a = a; + laba.b = b; + + laba.alpha = static_cast(rgba.alpha); +} + +template +void rgb_to_lab(const ImageLib::RGBPixel &rgb, ImageLib::LABPixel &lab) { + rgb_to_lab(rgb.red, rgb.green, rgb.blue, lab.l, lab.a, lab.b); +} + +template +void lab_to_rgb(const ImageLib::LABAPixel &laba, ImageLib::RGBAPixel &rgba) { + Tout r{rgba.red}; + Tout g{rgba.green}; + Tout b{rgba.blue}; + + lab_to_rgb(laba.l, laba.a, laba.b, r, g, b); + rgba.alpha = static_cast(laba.alpha); +} + +template +void lab_to_rgb(const ImageLib::LABPixel &lab, ImageLib::RGBPixel &rgb) { + lab_to_rgb(lab.l, lab.a, lab.b, rgb.red, rgb.green, rgb.blue); +} + +#endif diff --git a/core/include/contours.h b/core/include/contours.h new file mode 100644 index 000000000..4d50afdb6 --- /dev/null +++ b/core/include/contours.h @@ -0,0 +1,57 @@ +#ifndef CONTOURS_H +#define CONTOURS_H + +#include +#include +#include +#include +#include + +#include "Image.h" +#include "PixelConverters.h" +#include "Point.h" +#include "RGBAPixel.h" +#include "SavitskyGolay.h" + +struct QuadBezier { + Point p0{0, 0}; // Start + Point p1{0, 0}; // Control + Point p2{0, 0}; // End +}; + +struct Rect { + float x, y, width, height; +}; + +struct ContoursResult { + // contours[k] is a sequence of boundary pixels (x,y) in image coordinates + // (0..w-1, 0..h-1) + std::vector> contours; + std::vector> curves; + + // hierarchy[k] = { next_sibling, prev_sibling, first_child, parent } + // -1 means "none" + std::vector> hierarchy; + + // is_hole[k] == true if contour k is a hole border + std::vector is_hole; +}; + +struct ColoredContours : ContoursResult { + // inherits: contours, hierarchy, is_hole + + std::vector> colors; +}; + +namespace contours { +ContoursResult find_contours(const std::vector &binary, int width, int height); + +void stitch_smooth(std::vector &vecA, std::vector &vecB); +void coupled_smooth(std::vector> &contours, Rect bounds); + +void pack_with_boundary_constraints(std::vector> &contours, Rect bounds, + int iterations = 15); + +} // namespace contours + +#endif \ No newline at end of file diff --git a/src/wasm/modules/image/include/fft_iterative.h b/core/include/fft_iterative.h similarity index 87% rename from src/wasm/modules/image/include/fft_iterative.h rename to core/include/fft_iterative.h index 0655505a1..52057d67c 100644 --- a/src/wasm/modules/image/include/fft_iterative.h +++ b/core/include/fft_iterative.h @@ -2,7 +2,7 @@ #define ITERATIVE_FFT_H #include -#include // for size_t +#include // for size_t #include namespace fft { @@ -35,16 +35,14 @@ std::vector fft_copy(const std::vector &input, bool inverse = false); // Parameters: // - data: input/output buffer (modified in-place). // - inverse: false for forward FFT, true for inverse FFT. -void iterative_fft_2d(std::vector &a, size_t width, size_t height, - bool inverse = false); +void iterative_fft_2d(std::vector &a, size_t width, size_t height, bool inverse = false); // Convenience wrapper: return 2D FFT result as a new vector. // Parameters: // - input: const input vector. // - inverse: false for forward FFT, true for inverse FFT. -std::vector iterative_fft_2d_copy(const std::vector &input, - size_t width, size_t height, +std::vector iterative_fft_2d_copy(const std::vector &input, size_t width, size_t height, bool inverse = false); -} // namespace fft +} // namespace fft -#endif // ITERATIVE_FFT_H +#endif // ITERATIVE_FFT_H diff --git a/src/wasm/modules/image/include/graph.h b/core/include/graph.h similarity index 50% rename from src/wasm/modules/image/include/graph.h rename to core/include/graph.h index c3bdc0ae7..96bdb8638 100644 --- a/src/wasm/modules/image/include/graph.h +++ b/core/include/graph.h @@ -1,9 +1,10 @@ #ifndef GRAPH_H #define GRAPH_H -#include "node.h" #include +#include "node.h" + /* Graph and Node classes support conversion of a region divided image into a graph structure. Each Node represents a region of pixels which tracks the color @@ -30,35 +31,37 @@ discover_edges(G, region_labels, width, height); */ class Graph { -protected: - int m_width, m_height; - std::unique_ptr> m_nodes; - std::unordered_map m_node_ids; + protected: + int m_width, m_height; + std::unique_ptr> m_nodes; + std::unordered_map m_node_ids; - void hash_node_ids(void); + void hash_node_ids(void); -public: - inline Graph(std::unique_ptr> &nodes, int width, - int height) - : m_nodes(std::move(nodes)), m_width(width), m_height(height) { - hash_node_ids(); - } + public: + inline Graph(std::unique_ptr> &nodes, int width, int height) + : m_nodes(std::move(nodes)), m_width(width), m_height(height) { + hash_node_ids(); + } - bool add_edge(int32_t node_id1, int32_t node_id2); - bool merge_nodes(const Node_ptr &node_to_keep, - const Node_ptr &node_to_remove); + bool add_edge(int32_t node_id1, int32_t node_id2); + bool merge_nodes(const Node_ptr &node_to_keep, const Node_ptr &node_to_remove); - void clear_unconnected_nodes(); + void clear_unconnected_nodes(); - inline const std::vector &get_nodes() const { return *m_nodes; } + inline const std::vector &get_nodes() const { + return *m_nodes; + } - bool all_areas_bigger_than(int32_t min_area); - inline const size_t size() { return m_nodes->size(); } + bool all_areas_bigger_than(int32_t min_area); + inline const size_t size() { + return m_nodes->size(); + } - void discover_edges(const std::vector ®ion_labels, - const int32_t width, const int32_t height); - void merge_small_area_nodes(const int32_t min_area); - void compute_contours(); + void discover_edges(const std::vector ®ion_labels, const int32_t width, + const int32_t height); + void merge_small_area_nodes(const int32_t min_area); + void compute_contours(); }; #endif diff --git a/core/include/image_utils.h b/core/include/image_utils.h new file mode 100644 index 000000000..db110da44 --- /dev/null +++ b/core/include/image_utils.h @@ -0,0 +1,8 @@ +#ifndef IMAGE_UTILS_H +#define IMAGE_UTILS_H + +#include + +uint8_t quantize(uint8_t value, uint8_t region_size); + +#endif diff --git a/core/include/node.h b/core/include/node.h new file mode 100644 index 000000000..cee3243e0 --- /dev/null +++ b/core/include/node.h @@ -0,0 +1,130 @@ +#ifndef NODE_H +#define NODE_H + +#include +#include +#include +#include +#include + +#include "RGBPixel.h" +#include "contours.h" + +/* + Graph and Node classes support conversion of a region divided image into a +graph structure. Each Node represents a region of pixels which tracks the color +and coordinates (RGBXY) of belonging pixels, and its neighbors as edges. + +usage: + +std::vector nodes; // list of all nodes to be tracked + +std::unique_ptr> p_ptr = +std::make_unique>(); // vector of pixels belonging to this +region Node_ptr n_ptr = std::make_shared(, p_ptr); +nodes.push_back(n_ptr); + +Graph manages a collection of nodes. It will take ownership of `nodes`. +A graph is initialized as a list of disconnected nodes. + +std::unique_ptr> node_ptr = +std::make_unique>(std::move(nodes)); Graph G(node_ptr); + +Given a region image, edges are discovered and recorded: +discover_edges(G, region_labels, width, height); + +*/ + +struct XY { + int32_t x, y; + std::pair xy; + XY(int32_t x_, int32_t y_) : x(x_), y(y_) { + xy = std::make_pair(x, y); + }; + bool operator<(const XY &rhs) const { + return xy < rhs.xy; + }; +}; + +struct RGBXY { + ImageLib::RGBPixel color; + XY position; + + RGBXY(uint8_t r, uint8_t g, uint8_t b, int32_t x, int32_t y) : color(r, g, b), position{x, y} { + } +}; + +class Node; +typedef std::shared_ptr Node_ptr; + +/* + *Node represents a region - collection of pixels, and their neighboring regions + *(edges) + */ + +class Node { + protected: + int32_t m_id; + std::unique_ptr> m_pixels; + std::set m_edges{}; + + // pixels considered for contour tracing but not influencing other + // node properties such as color + std::set m_edge_pixels{}; + + public: + inline Node(int32_t id, std::unique_ptr> &pixels) + : m_id(id), m_pixels(std::move(pixels)) { + } + + XY centroid() const; + ImageLib::RGBPixel color() const; + std::array bounding_box_xywh() const; + std::array create_binary_image(std::vector &binary) const; + + // keep track of its own contour points + // only filled in when compute_contour() is called + // though these are public only Graph should access them + ColoredContours m_contours; + void clear_contour(); + void compute_contour(); + + /* access member variables */ + inline int32_t id() const { + return m_id; + }; + inline size_t area() const { + return m_pixels->size(); + }; + inline const std::set &edges() const { + return m_edges; + } + inline size_t num_edges() const { + return m_edges.size(); + } + inline const std::vector &get_pixels() const { + return *m_pixels; + } + inline ColoredContours &get_contours() { + return m_contours; + } + + /* modify member variables */ + void add_pixels(const std::vector &new_pixels); + void add_edge_pixel(const XY edge_pixel); + void clear_edge_pixels(); + + void clear_all(); + + inline void add_edge(const Node_ptr &node) { + m_edges.insert(node); + } + inline void remove_edge(const Node_ptr &node) { + m_edges.erase(node); + } + inline void remove_all_edges() { + m_edges.clear(); + } +}; + +#endif diff --git a/core/src/SavitskyGolay.cpp b/core/src/SavitskyGolay.cpp new file mode 100644 index 000000000..09c0bc329 --- /dev/null +++ b/core/src/SavitskyGolay.cpp @@ -0,0 +1,135 @@ +#include "SavitskyGolay.h" + +#include +#include +#include +#include + +SavitzkyGolay::SavitzkyGolay(int radius, int poly_order) + : window_radius_(radius), window_size_(2 * radius + 1), poly_order_(poly_order) { + assert(radius >= 0); + assert(window_size_ > poly_order_); + + compute_coefficients(); +} + +std::vector SavitzkyGolay::filter(const std::vector &data) { + if (data.size() < window_size_) { + return data; // Data too short to filter + } + + std::vector result(data.size()); + + // 1. Convolution for the valid range + for (size_t i = window_radius_; i < data.size() - window_radius_; ++i) { + Point val{0.0, 0.0}; + for (int j = -window_radius_; j <= window_radius_; ++j) { + val += data[i + j] * coeffs_[j + window_radius_]; + } + result[i] = val; + } + + // 2. Handle Edges (Simple Repeat/Nearest padding strategy) + // For a robust production app, you might calculate asymmetric kernels here. + for (int i = 0; i < window_radius_; ++i) result[i] = data[i]; + for (size_t i = data.size() - window_radius_; i < data.size(); ++i) result[i] = data[i]; + + return result; +} + +std::vector SavitzkyGolay::filter_wrap(const std::vector &data) { + // wrap around + if (data.size() < window_size_) { + return data; // Data too short to filter + } + + std::vector result(data.size()); + std::copy(data.begin(), data.end(), result.begin()); + + for (size_t i = 0; i < data.size(); ++i) { + Point val{0.0, 0.0}; + for (int j = -window_radius_; j <= window_radius_; ++j) { + int k = i + j; + if (k < 0) { + k = data.size() + k; + } else if (k >= data.size()) { + k = k - data.size(); + } + val = val + data[k] * coeffs_[j + window_radius_]; + } + result[i] = val; + } + + return result; +} + +// Helper: Invert a matrix using Gauss-Jordan Elimination +// A is (N x N), returns A_inv +std::vector> SavitzkyGolay::invert_matrix(std::vector> A) { + int n = A.size(); + std::vector> inv(n, std::vector(n, 0.0)); + + // Initialize inverse as identity + for (int i = 0; i < n; ++i) inv[i][i] = 1.0; + + for (int i = 0; i < n; ++i) { + // Find pivot + float pivot = A[i][i]; + // (Simple pivot check, typically you'd swap rows for stability) + if (std::abs(pivot) < 1e-10) throw std::runtime_error("Matrix singular, cannot invert."); + + // Normalize row + for (int j = 0; j < n; ++j) { + A[i][j] /= pivot; + inv[i][j] /= pivot; + } + + // Eliminate other rows + for (int k = 0; k < n; ++k) { + if (k != i) { + float factor = A[k][i]; + for (int j = 0; j < n; ++j) { + A[k][j] -= factor * A[i][j]; + inv[k][j] -= factor * inv[i][j]; + } + } + } + } + return inv; +} + +void SavitzkyGolay::compute_coefficients() { + // 1. Create the matrix J = (A^T * A) + // Size is (poly_order + 1) x (poly_order + 1) + // Element J[i][j] is the sum of k^(i+j) for k in -m..m + + int rows = poly_order_ + 1; + std::vector> J(rows, std::vector(rows)); + + for (int i = 0; i < rows; ++i) { + for (int j = 0; j < rows; ++j) { + float sum = 0; + for (int k = -window_radius_; k <= window_radius_; ++k) { + sum += std::pow(k, i + j); + } + J[i][j] = sum; + } + } + + // 2. Invert J to solve the normal equations + auto J_inv = invert_matrix(J); + + // 3. Compute the weights + // The smoothed value is the coefficient c_0 of the polynomial. + // c_0 = sum( weight_k * y_k ) + // weight_k = sum( J_inv[0][j] * k^j ) for j=0..order + + coeffs_.resize(window_size_); + for (int k = -window_radius_; k <= window_radius_; ++k) { + float weight = 0.0; + for (int j = 0; j < rows; ++j) { + weight += J_inv[0][j] * std::pow(k, j); + } + coeffs_[k + window_radius_] = weight; + } +} diff --git a/core/src/bezier.cpp b/core/src/bezier.cpp new file mode 100644 index 000000000..86aedc725 --- /dev/null +++ b/core/src/bezier.cpp @@ -0,0 +1,152 @@ +#include "bezier.h" + +#include +#include +#include + +// --- Vector Math Helpers --- +inline float dot(Point a, Point b) { + return a.x * b.x + a.y * b.y; +} +inline float len(Point a, Point b) { + Point c = a - b; + return std::sqrt(c.x * c.x + c.y * c.y); +} + +// --- Evaluate Quadratic Bezier at t --- +Point evalBezier(const QuadBezier &b, float t) { + // B(t) = (1-t)^2 * P0 + 2*t*(1-t) * P1 + t^2 * P2 + float invT = 1.0 - t; + float c0 = invT * invT; + float c1 = 2.0f * t * invT; + float c2 = t * t; + + return c0 * b.p0 + c1 * b.p1 + c2 * b.p2; +} + +// --- Chord Length Parameterization --- +// Assigns a 't' value (0.0 to 1.0) to each point based on distance +std::vector chordLengthParameterize(const std::vector &points) { + std::vector u; + u.reserve(points.size()); + u.push_back(0.0f); + + for (int i = 1; i < points.size(); ++i) { + float dist = len(points[i], points[i - 1]); + u.push_back(u.back() + dist); + } + + float totalLen = u.back(); + if (totalLen == 0) return u; // Should not happen for valid ranges + + for (float &val : u) { + val /= totalLen; + } + return u; +} + +// --- Least Squares Fit for Control Point Q1 --- +// We know Q0 (Start) and Q2 (End). We need to find Q1 that minimizes error. +// Based on equation: P(t) = (1-t)^2 Q0 + 2t(1-t) Q1 + t^2 Q2 +// Rearranged: Q1 * [2t(1-t)] = P(t) - (1-t)^2 Q0 - t^2 Q2 +Point generateQuadBezier(const std::vector &points, const std::vector &u) { + Point Q0 = points.front(); + Point Q2 = points.back(); + + float numX = 0.0, numY = 0.0; + float den = 0.0; + + for (int i = 0; i < u.size(); ++i) { + float t = u[i]; + float invT = 1.0f - t; + + // A = 2t(1-t) + float A = 2.0f * t * invT; + + // V = P_actual - (Contribution of Q0 and Q2) + // V = P[i] - (1-t)^2 * Q0 - t^2 * Q2 + float B0 = invT * invT; + float B2 = t * t; + Point V = points[i] - (Q0 * B0 + Q2 * B2); + + // Least Squares Sums + numX += A * V.x; + numY += A * V.y; + den += A * A; + } + + if (den < 1e-9) { + // Fallback for straight lines (den is 0 if all t are 0 or 1) + return Q0 + (Q2 - Q0) * 0.5; + } + + return {numX / den, numY / den}; +} + +// --- Recursive Fit Function --- +void fitRecursive(const std::vector &points, float errorLimit, + std::vector &outCurves) { + // Base Case: Not enough points, just connect them + if (points.size() <= 2) { + // Just a line segment + Point mid = points.front() + (points.back() - points.front()) * 0.5; + outCurves.push_back({points.front(), mid, points.back()}); + return; + } + + // 1. Parameterize Points + std::vector u = chordLengthParameterize(points); + + // 2. Find Optimal Control Point (Q1) + Point Q1 = generateQuadBezier(points, u); + QuadBezier curve = {points.front(), Q1, points.back()}; + + // 3. Calculate Maximum Error + float maxDistSq = 0.0f; + int splitPoint = 0; + + // Check distance of every intermediate point to the curve + // Note: Technically we should find the nearest point on curve, + // but evaluating at parameter 't' is a standard approximation for speed. + for (int i = 0; i < u.size(); ++i) { + Point P = points[i]; + Point CurveP = evalBezier(curve, u[i]); + float d2 = Point::distSq(P, CurveP); + + if (d2 > maxDistSq) { + maxDistSq = d2; + splitPoint = i; + } + } + + // 4. Check Error Threshold + if (maxDistSq < (errorLimit * errorLimit)) { + outCurves.push_back(curve); // Fit is good! + } else { + // Fit is bad, split at the point of maximum error + // Important: Prevent infinite recursion if split doesn't advance + if (splitPoint == 0 || splitPoint == points.size() - 1) { + // Fallback: simply bisect indices if geometric split fails + splitPoint = points.size() / 2; + } + + std::vector p1(points.begin(), points.begin() + splitPoint + 1); + std::vector p2(points.begin() + splitPoint, points.end()); + + fitRecursive(p1, errorLimit, outCurves); + fitRecursive(p2, errorLimit, outCurves); + } +} + +// --- Main Wrapper --- +void fit_curve_reduction(const std::vector> &chains, + std::vector> &results, float tolerance) { + // if (chain.empty()) return result; + // results.resize(chains.size()); + for (int i = 0; i < chains.size(); ++i) { + // Start recursion on the whole chain + std::vector result; + fitRecursive(chains[i], tolerance, result); + results.push_back(result); + } +} \ No newline at end of file diff --git a/core/src/bilateral_filter.cpp b/core/src/bilateral_filter.cpp new file mode 100644 index 000000000..dbf65fe25 --- /dev/null +++ b/core/src/bilateral_filter.cpp @@ -0,0 +1,219 @@ +#include +#include +#include +#include +#include +#include + +#include "cielab.h" +#include "img2num.h" + +static constexpr double SIGMA_RADIUS_FACTOR{3.0}; // 3 standard deviations +static constexpr int MAX_KERNEL_RADIUS{50}; +// Max possible squared Euclidean distance in a 3-channel 8-bit image: 255^2 * 3 +// = 195075 Means max delta between images (imageA - imageB) in RGB channels +// (255^2 * 3) +static constexpr int MAX_RGB_DIST_SQ{255 * 255 * 3}; +static constexpr uint8_t COLOR_SPACE_OPTION_CIELAB{0}; +static constexpr uint8_t COLOR_SPACE_OPTION_RGB{1}; + +inline double gaussian(double x, double sigma) { + return std::exp(-(x * x) / (2.0 * sigma * sigma)); +} + +/* +The Bilateral Filter applies a composite weight based on both spatial distance +and radiometric difference (intensity) to return an image that is smoothed while +preserving edges. It reduces noise in flat regions while preserving edges by +assigning near-zero weight to pixels across high-contrast boundaries. + +Parameters: +- image: Pointer to RGBA pixel buffer +- width, height: Image dimensions (px) +- sigma_spatial: Gaussian standard deviation for spatial proximity (spatial +decay) +- sigma_range: Gaussian standard deviation for intensity difference (radiometric +decay) +- color_space: Color space selector + ├── 0: CIELAB + └── 1: RGB +*/ + +void _process(const uint8_t *image, const std::vector &cie_image, + std::vector &result, const std::vector &spatial_weights, + const std::vector &range_lut, int radius, double sigma_range, int start_row, + int end_row, size_t height, size_t width, uint8_t color_space) { + int h{static_cast(height)}; + int w{static_cast(width)}; + const int kernel_diameter{2 * radius + 1}; + + for (int y{start_row}; y < end_row; ++y) { + for (int x{0}; x < w; ++x) { + size_t center_idx{(y * width + x) * 4}; + + uint8_t r0{image[center_idx]}; + uint8_t g0{image[center_idx + 1]}; + uint8_t b0{image[center_idx + 2]}; + uint8_t a0{image[center_idx + 3]}; + + // ========= CIELAB-only section start ========= + double L0, A0, B0; + if (color_space == COLOR_SPACE_OPTION_CIELAB) { + L0 = cie_image[center_idx]; + A0 = cie_image[center_idx + 1]; + B0 = cie_image[center_idx + 2]; + } + // ========= CIELAB-only section end ========= + + // in RGB mode represents r,g,b accumulators + // in CIELAB mode represents L,A,B accumulators + double weight_acc_channel_0{0.0}, weight_acc_channel_1{0.0}, weight_acc_channel_2{0.0}; + + double weight_acc{0.0}; + double w_space, w_range; + double dL, dA, dB, dist; + + for (int ky{-radius}; ky <= radius; ++ky) { + int ny{std::clamp(y + ky, 0, h - 1)}; + + for (int kx{-radius}; kx <= radius; ++kx) { + int nx{std::clamp(x + kx, 0, w - 1)}; + + size_t neighbor_idx{(ny * width + nx) * 4}; + + uint8_t r{image[neighbor_idx]}; + uint8_t g{image[neighbor_idx + 1]}; + uint8_t b{image[neighbor_idx + 2]}; + + double L{cie_image[neighbor_idx]}; + double A{cie_image[neighbor_idx + 1]}; + double B{cie_image[neighbor_idx + 2]}; + + w_space = spatial_weights[(ky + radius) * kernel_diameter + (kx + radius)]; + + switch (color_space) { + case COLOR_SPACE_OPTION_RGB: { + const int dr{static_cast(r) - r0}; + const int dg{static_cast(g) - g0}; + const int db{static_cast(b) - b0}; + const int dist_sq{dr * dr + dg * dg + db * db}; + w_range = range_lut[dist_sq]; + + weight_acc_channel_0 += r * w_space * w_range; + weight_acc_channel_1 += g * w_space * w_range; + weight_acc_channel_2 += b * w_space * w_range; + break; + } + case COLOR_SPACE_OPTION_CIELAB: { + dL = L - L0; + dA = A - A0; + dB = B - B0; + + dist = std::sqrt(dL * dL + dA * dA + dB * dB); + w_range = gaussian(dist, sigma_range); + + weight_acc_channel_0 += L * w_space * w_range; + weight_acc_channel_1 += A * w_space * w_range; + weight_acc_channel_2 += B * w_space * w_range; + break; + } + } + + weight_acc += w_space * w_range; + } + } + + switch (color_space) { + case COLOR_SPACE_OPTION_RGB: { + result[center_idx] = static_cast( + std::clamp(weight_acc_channel_0 / weight_acc, 0.0, 255.0)); + result[center_idx + 1] = static_cast( + std::clamp(weight_acc_channel_1 / weight_acc, 0.0, 255.0)); + result[center_idx + 2] = static_cast( + std::clamp(weight_acc_channel_2 / weight_acc, 0.0, 255.0)); + result[center_idx + 3] = a0; + break; + } + case COLOR_SPACE_OPTION_CIELAB: { + double L{weight_acc_channel_0 / weight_acc}; + double A{weight_acc_channel_1 / weight_acc}; + double B{weight_acc_channel_2 / weight_acc}; + uint8_t r, g, b; + lab_to_rgb(L, A, B, r, g, b); + result[center_idx] = r; + result[center_idx + 1] = g; + result[center_idx + 2] = b; + result[center_idx + 3] = a0; + break; + } + } + } + } +} + +namespace img2num { +void bilateral_filter(uint8_t *image, size_t width, size_t height, double sigma_spatial, + double sigma_range, uint8_t color_space) { + // bad data -> return + if (sigma_spatial <= 0.0 || sigma_range <= 0.0 || width <= 0 || height <= 0) return; + if (color_space != COLOR_SPACE_OPTION_CIELAB && color_space != COLOR_SPACE_OPTION_RGB) return; + + const int raw_radius{static_cast(std::ceil(SIGMA_RADIUS_FACTOR * sigma_spatial))}; + const int radius{std::min(raw_radius, MAX_KERNEL_RADIUS)}; + const int kernel_diameter{2 * radius + 1}; + + std::vector result(width * height * 4); + + std::vector spatial_weights(kernel_diameter * kernel_diameter); + + // Precompute Spatial Weights (Gaussian Kernel) + for (int ky{-radius}; ky <= radius; ++ky) { + for (int kx{-radius}; kx <= radius; ++kx) { + const double dist{static_cast(std::sqrt(kx * kx + ky * ky))}; + spatial_weights[(ky + radius) * kernel_diameter + (kx + radius)] = + gaussian(dist, sigma_spatial); + } + } + + // ========= RGB-only section start ========= + // Precompute Range Weights + std::vector range_lut; + if (color_space == COLOR_SPACE_OPTION_RGB) { + range_lut.resize(MAX_RGB_DIST_SQ + 1); + for (int i{0}; i <= MAX_RGB_DIST_SQ; ++i) { + range_lut[i] = gaussian(static_cast(std::sqrt(i)), sigma_range); + } + } + // ========= RGB-only section end ========= + + // ========= CIELAB section start ========= + // Compute full image RGB - CIELAB conversion + std::vector cie_image; + if (color_space == COLOR_SPACE_OPTION_CIELAB) { + cie_image.resize(width * height * 4); + + for (int y{0}; y < height; y++) { + for (int x{0}; x < width; x++) { + int center_idx{(y * static_cast(width) + x) * 4}; + uint8_t r0{image[center_idx]}; + uint8_t g0{image[center_idx + 1]}; + uint8_t b0{image[center_idx + 2]}; + uint8_t a0{image[center_idx + 3]}; + double L0, A0, B0; + rgb_to_lab(r0, g0, b0, L0, A0, B0); + + cie_image[center_idx] = L0; + cie_image[center_idx + 1] = A0; + cie_image[center_idx + 2] = B0; + cie_image[center_idx + 3] = 0.0; // unused but keep for indexing purposes + } + } + } + // ========= CIELAB section end ========= + + _process(image, cie_image, result, spatial_weights, range_lut, radius, sigma_range, 0, + static_cast(height), height, width, color_space); + + std::memcpy(image, result.data(), result.size()); +} +} // namespace img2num diff --git a/core/src/contours.cpp b/core/src/contours.cpp new file mode 100644 index 000000000..e83963e94 --- /dev/null +++ b/core/src/contours.cpp @@ -0,0 +1,850 @@ + +#include "contours.h" + +#include +#include +#include +#include +#include +#include + +namespace contours { + +// 8-neighborhood, clockwise order starting from "right" (dx=+1,dy=0). +// (y increases downward) +static constexpr int DX[8] = {+1, +1, 0, -1, -1, -1, 0, +1}; +static constexpr int DY[8] = {0, +1, +1, +1, 0, -1, -1, -1}; + +// Map (dy,dx) to direction index in [0..7] +static inline int dirIndex(int dy, int dx) { + if (dy == 0 && dx == 1) return 0; + if (dy == 1 && dx == 1) return 1; + if (dy == 1 && dx == 0) return 2; + if (dy == 1 && dx == -1) return 3; + if (dy == 0 && dx == -1) return 4; + if (dy == -1 && dx == -1) return 5; + if (dy == -1 && dx == 0) return 6; + if (dy == -1 && dx == 1) return 7; + return -1; // not a neighbor +} + +static inline int dirIndexFromTo(int y, int x, int ny, int nx) { + return dirIndex(ny - y, nx - x); +} + +// Border following (Algorithm 1, steps 3.1..3.5): +// - f is a padded image (0=background; nonzero=object/labels) +// - (sy,sx) is the border start point (nonzero) +// - (py,px) is the "previous" neighbor used to define search direction (usually +// a 0-pixel) +// - nbd is the new border label +// Returns the contour as points in *unpadded* coordinates (x-1,y-1). +static std::vector traceBorder(std::vector &f, int paddedW, int sy, int sx, int py, + int px, int nbd) { + auto set = [&](int y, int x) -> int & { return f[y * paddedW + x]; }; + auto get = [&](int y, int x) -> int { return f[y * paddedW + x]; }; + + std::vector pts; + + // (3.1) Find first nonzero neighbor around (sy,sx), scanning clockwise from + // (py,px) + const int dStart = dirIndexFromTo(sy, sx, py, px); + if (dStart < 0) { + throw std::runtime_error("traceBorder: invalid previous neighbor (not adjacent)."); + } + + int y1 = 0, x1 = 0; + bool found = false; + for (int t = 0; t < 8; ++t) { + int d = (dStart + t) & 7; // clockwise + int ny = sy + DY[d], nx = sx + DX[d]; + if (get(ny, nx) != 0) { + y1 = ny; + x1 = nx; + found = true; + break; + } + } + + // If isolated pixel: set f(sy,sx) = -NBD and return single-point contour + if (!found) { + set(sy, sx) = -nbd; + pts.push_back(Point{static_cast(sx - 1), static_cast(sy - 1)}); + return pts; + } + + // (3.2) + int y2 = y1, x2 = x1; // previous border pixel + int y3 = sy, x3 = sx; // current border pixel + const int firstY = y1, firstX = x1; + + while (true) { + // (3.3) Search CCW around (y3,x3), starting from "next after (y2,x2) in CCW + // order" + const int dPrev = dirIndexFromTo(y3, x3, y2, x2); + if (dPrev < 0) { + throw std::runtime_error("traceBorder: broken neighbor chain."); + } + + const int d0 = (dPrev + 7) & 7; // one step CCW from dPrev + bool rightZeroExamined = false; + int y4 = y3, x4 = x3; // next border pixel (to be found) + + for (int t = 0; t < 8; ++t) { + int d = (d0 - t) & 7; // scan CCW (decrement index) + int ny = y3 + DY[d], nx = x3 + DX[d]; + + // (3.4a) depends on whether pixel to the right (dx=+1,dy=0 => dir 0) + // was examined during (3.3) and was a 0-pixel + if (d == 0 && get(ny, nx) == 0) { + rightZeroExamined = true; + } + + if (get(ny, nx) != 0) { + y4 = ny; + x4 = nx; + break; + } + } + + // (3.4) Marking policy + if (rightZeroExamined) { + set(y3, x3) = -nbd; + } else { + if (set(y3, x3) == 1) { + set(y3, x3) = nbd; + } + } + + // Record current point in unpadded coordinates + pts.push_back(Point{static_cast(x3 - 1), static_cast(y3 - 1)}); + + // (3.5) Termination check + if (y4 == sy && x4 == sx && y3 == firstY && x3 == firstX) { + break; + } + + // Advance + y2 = y3; + x2 = x3; + y3 = y4; + x3 = x4; + } + + return pts; +} + +ContoursResult find_contours(const std::vector &binary, int width, int height) { + if (width <= 0 || height <= 0) { + return {}; + } + if ((int)binary.size() != width * height) { + throw std::invalid_argument("binary.size() must be width*height"); + } + + // Pad image with a 1-pixel 0-frame + const int paddedW = width + 2; + const int paddedH = height + 2; + std::vector f(static_cast(paddedW) * static_cast(paddedH), 0); + + auto set = [&](int y, int x) -> int & { return f[y * paddedW + x]; }; + auto get = [&](int y, int x) -> int { return f[y * paddedW + x]; }; + + for (int y = 0; y < height; ++y) { + for (int x = 0; x < width; ++x) { + set(y + 1, x + 1) = (binary[y * width + x] != 0) ? 1 : 0; + } + } + + // Border node info stored by border id (NBD). ID=1 is the frame (special hole + // border). + struct NodeInfo { + bool is_hole = false; + int parent_id = 0; // parent border id + std::vector points; // contour points (unpadded coords) + bool used = false; + }; + + int nbd = 1; + std::vector nodes(2); + nodes[1].is_hole = true; // frame is treated as a hole border + nodes[1].parent_id = 1; // self-parent for convenience + nodes[1].used = true; + + // Raster scan (Algorithm 1, step 1..4) + for (int y = 1; y <= height; ++y) { + int lnbd = 1; // reset each row + + for (int x = 1; x <= width; ++x) { + int fij = get(y, x); + if (fij == 0) continue; // Algorithm processes only fij != 0 + + bool startBorder = false; + bool isHole = false; + int py = 0, px = 0; + + // (1a) Outer border start: fij==1 and left is 0 + if (fij == 1 && get(y, x - 1) == 0) { + ++nbd; + startBorder = true; + isHole = false; + py = y; + px = x - 1; + } + // (1b) Hole border start: fij>=1 and right is 0 + else if (fij >= 1 && get(y, x + 1) == 0) { + ++nbd; + startBorder = true; + isHole = true; + py = y; + px = x + 1; + + // LNBD <- fij if fij > 1 (per Appendix I) + if (fij > 1) { + lnbd = fij; + } + } + + if (startBorder) { + if ((int)nodes.size() <= nbd) nodes.resize(nbd + 1); + + nodes[nbd].is_hole = isHole; + nodes[nbd].used = true; + + // (2) Decide parent using Table 1: + // If types match -> parent(B)=parent(B'), else parent(B)=B' + // where B' is border with id LNBD. + const bool bprimeIsHole = nodes[lnbd].is_hole; + const int parent_id = (isHole == bprimeIsHole) ? nodes[lnbd].parent_id : lnbd; + nodes[nbd].parent_id = parent_id; + + // (3) Follow border and mark pixels with +/-NBD + nodes[nbd].points = traceBorder(f, paddedW, y, x, py, px, nbd); + } + + // (4) Update LNBD if fij != 1 (note fij may have changed after tracing) + if (get(y, x) != 1) { + lnbd = std::abs(get(y, x)); + } + } + } + + // Convert from border ids (2..nbd) to compact 0-based contour indices (frame + // excluded) + std::vector idToIdx(nbd + 1, -1); + ContoursResult out; + + out.contours.reserve(std::max(0, nbd - 1)); + out.hierarchy.reserve(std::max(0, nbd - 1)); + out.is_hole.reserve(std::max(0, nbd - 1)); + + for (int id = 2; id <= nbd; ++id) { + if (!nodes[id].used) continue; + idToIdx[id] = (int)out.contours.size(); + out.contours.push_back(nodes[id].points); + out.is_hole.push_back(nodes[id].is_hole); + out.hierarchy.push_back({-1, -1, -1, -1}); + } + + // Fill parent index + for (int id = 2; id <= nbd; ++id) { + if (!nodes[id].used) continue; + const int idx = idToIdx[id]; + const int pid = nodes[id].parent_id; + out.hierarchy[idx][3] = (pid <= 1) ? -1 : idToIdx[pid]; // parent + } + + // Build child/sibling links (first_child, next, prev) + std::vector lastChild(out.contours.size(), -1); + + for (int i = 0; i < (int)out.contours.size(); ++i) { + int p = out.hierarchy[i][3]; + if (p < 0) continue; + + if (out.hierarchy[p][2] == -1) { + out.hierarchy[p][2] = i; // first_child + lastChild[p] = i; + } else { + int last = lastChild[p]; + out.hierarchy[last][0] = i; // next sibling + out.hierarchy[i][1] = last; // prev sibling + lastChild[p] = i; + } + } + + return out; +} + +// Helper: 2D integer coordinate for map keys +struct Coord { + int x, y; + bool operator<(const Coord &other) const { + return std::tie(x, y) < std::tie(other.x, other.y); + } +}; + +// Helper: Normalize a vector +Point normalize(Point p) { + float len = std::sqrt(p.x * p.x + p.y * p.y); + if (len == 0) return {0, 0}; + return {p.x / len, p.y / len}; +} + +// Helper: Calculate Tangent of A at index i using neighbors +Point getTangent(const std::vector &vec, int i) { + int n = vec.size(); + if (n < 2) return {0, 0}; + + // Use previous and next points to determine the "flow" of the line + int prev = (i == 0) ? 0 : i - 1; + int next = (i == n - 1) ? n - 1 : i + 1; + + return normalize(vec[next] - vec[prev]); +} + +// Calculate the closest point on the segment V -> W from point P +// Returns {ClosestPoint, DistanceSquared} +std::pair getClosestPointOnSegment(Point p, Point v, Point w) { + float l2 = Point::distSq(v, w); + if (l2 == 0.0) return {v, Point::distSq(p, v)}; + + // Project p onto line v-w + // t is the parameterized distance along the line (0.0 to 1.0) + float t = ((p.x - v.x) * (w.x - v.x) + (p.y - v.y) * (w.y - v.y)) / l2; + + // Clamp to segment + t = std::max(0.0f, std::min(1.0f, t)); + + Point projection = {v.x + t * (w.x - v.x), v.y + t * (w.y - v.y)}; + return {projection, Point::distSq(p, projection)}; +} + +// Identifies a specific point: {ContourIndex, PointIndex} +struct PointID { + int cIdx; + int pIdx; +}; + +/** + * @brief Computes a smoothed target point using a local quadratic + * Savitzky-Golay filter. + * + * This function smooths a point in a sequence of 2D points by fitting a + * quadratic polynomial to a 5-point window (if possible) and evaluating it at + * the center. Essentially, it is a weighted local average where the reference + * point has the largest weight and neighbors have progressively smaller weights + * the farther they are from the reference. + * + * For points near the boundaries (indices 0, 1, n-2, n-1), where a full 5-point + * window is not available, a 3-point linear smoothing is applied instead. + * + * The 5-point quadratic filter uses the following coefficients: + * [-3, 12, 17, 12, -3] / 35 + * which preserves local peaks and slopes while reducing noise. + * + * @param pts A vector of 2D points (Point struct with x, y floats) to smooth. + * @param i The index of the point to smooth. + * @return The smoothed Point at index i. + * + * @note The function assumes pts has at least 3 points for linear smoothing and + * at least 5 points for quadratic smoothing. + */ + +Point getQuadraticTarget(const std::vector &pts, int i) { + int n{static_cast(pts.size())}; + // Endpoints cannot be smoothed - return as-is + if (i <= 0 || i >= n - 1) { + return pts[i]; + } + + // 1. BOUNDARY FALLBACK: + // If we are too close to the end (indices 1 or n-2), we don't have 5 points. + // Fall back to standard Linear Laplacian (0.25, 0.5, 0.25). + if (i < 2 || i >= n - 2) { + Point prev{pts[i - 1]}; + Point curr{pts[i]}; + Point next{pts[i + 1]}; + return 0.25f * prev + 0.5f * curr + 0.25f * next; + } + + // 2. QUADRATIC FILTER (Savitzky-Golay Window 5, Degree 2): + // Coefficients: [-3, 12, 17, 12, -3] / 35 + // This fits a local parabola and evaluates it at the center. + const Point &p2L{pts[i - 2]}; // 2 Left + const Point &p1L{pts[i - 1]}; // 1 Left + const Point &p{pts[i]}; // Center + const Point &p1R{pts[i + 1]}; // 1 Right + const Point &p2R{pts[i + 2]}; // 2 Right + + return (-3.0f * p2L + 12.0f * p1L + 17.0f * p + 12.0f * p1R - 3.0f * p2R) / 35.0f; +} + +void coupledSmooth(std::vector &contourA, std::vector &contourB) { + std::vector> contours = {contourA, contourB}; + // 1. Build Spatial Grid for O(1) partner lookup + std::map> grid; + for (int c = 0; c < 2; ++c) { + for (int p = 0; p < (int)contours[c].size(); ++p) { + grid[{(int)std::round(contours[c][p].x), (int)std::round(contours[c][p].y)}].push_back( + {c, p}); + } + } + + std::vector> targetPos = {contourA, contourB}; + + // Increased radius slightly to ensure we catch partners even on curves + float pairRadiusSq = 2.0 * 2.0; + + for (int c = 0; c < 2; ++c) { + // Skip endpoints (p=0 and p=last are usually locked anchors) + for (int p = 1; p < (int)contours[c].size() - 1; ++p) { + Point myPos = contours[c][p]; + + // --- STEP A: Calculate My Ideal Position (Quadratic) --- + Point myTarget = getQuadraticTarget(contours[c], p); + + // --- STEP B: Find Partners & Calculate Their Ideal Positions --- + Point sumPartnerTargets = {0, 0}; + int partnerCount = 0; + + int gx = (int)std::round(myPos.x); + int gy = (int)std::round(myPos.y); + + // 3x3 Neighbor Search + for (int dy = -2; dy <= 2; ++dy) { + for (int dx = -2; dx <= 2; ++dx) { + auto it = grid.find({gx + dx, gy + dy}); + if (it == grid.end()) continue; + + for (const auto &neighbor : it->second) { + if (neighbor.cIdx == c) continue; // Ignore self + + Point otherPos = contours[neighbor.cIdx][neighbor.pIdx]; + + // If close enough to be a "Partner" + if (Point::distSq(myPos, otherPos) < pairRadiusSq) { + // Check if partner is constrained + int op = neighbor.pIdx; + const auto &otherContour = contours[neighbor.cIdx]; + + Point oTarget; + if (op > 0 && op < (int)otherContour.size() - 1) { + // Partner is free: Calculate THEIR Quadratic Target + oTarget = getQuadraticTarget(otherContour, op); + } else { + // Partner is locked: They want to stay put + oTarget = otherPos; + } + + sumPartnerTargets += oTarget; + partnerCount++; + } + } + } + } + + // --- STEP C: Consensus Averaging --- + // "I want to be a parabola" vs "My partner wants to be a parabola" + // We average the two perfect quadratic fits. + if (partnerCount > 0) { + targetPos[c][p] = (myTarget + sumPartnerTargets) / (1.0 + partnerCount); + } else { + targetPos[c][p] = myTarget; + } + } + } + + std::copy(targetPos[0].begin(), targetPos[0].end(), contourA.begin()); + std::copy(targetPos[1].begin(), targetPos[1].end(), contourB.begin()); +} + +void stitch_smooth(std::vector &vecA, std::vector &vecB) { + // 1. Map Vector B indices to Grid (Optimization) + // We map a coordinate to the INDEX in vector B + std::map mapB; + for (size_t i = 0; i < vecB.size(); ++i) { + mapB[{(int)std::round(vecB[i].x), (int)std::round(vecB[i].y)}] = i; + } + + // We store the calculated "Target Positions" here. + // We do NOT update in place immediately, or the math for the next point will + // be wrong. + struct Update { + int index; + Point newPos; + }; + std::vector updatesA; + std::vector updatesB; + + // --- Process Vector A (Snap to B's Geometry) --- + for (size_t i = 0; i < vecA.size(); ++i) { + int ax = (int)std::round(vecA[i].x); + int ay = (int)std::round(vecA[i].y); + + float minDst = std::numeric_limits::max(); + Point bestTarget = vecA[i]; + bool foundMatch = false; + + // Search 3x3 Neighborhood + for (int dy = -1; dy <= 1; ++dy) { + for (int dx = -1; dx <= 1; ++dx) { + auto it = mapB.find({ax + dx, ay + dy}); + if (it != mapB.end()) { + int bIdx = it->second; + + // CHECK FORWARD SEGMENT: B[bIdx] -> B[bIdx+1] + if (bIdx < (int)vecB.size() - 1) { + auto res = getClosestPointOnSegment(vecA[i], vecB[bIdx], vecB[bIdx + 1]); + if (res.second < minDst) { + minDst = res.second; + bestTarget = res.first; + foundMatch = true; + } + } + + // CHECK BACKWARD SEGMENT: B[bIdx-1] -> B[bIdx] + if (bIdx > 0) { + auto res = getClosestPointOnSegment(vecA[i], vecB[bIdx - 1], vecB[bIdx]); + if (res.second < minDst) { + minDst = res.second; + bestTarget = res.first; + foundMatch = true; + } + } + } + } + } + + if (foundMatch) { + // Move A to the midpoint between itself and the closest spot on B's line + Point mid = (vecA[i] + bestTarget) * 0.5f; + updatesA.push_back({(int)i, mid}); + } + } + + // --- Process Vector B (Snap to A's Geometry) --- + // (We need a map for A now to do the reverse) + std::map mapA; + for (size_t i = 0; i < vecA.size(); ++i) { + mapA[{(int)std::round(vecA[i].x), (int)std::round(vecA[i].y)}] = i; + } + + for (size_t i = 0; i < vecB.size(); ++i) { + int bx = (int)std::round(vecB[i].x); + int by = (int)std::round(vecB[i].y); + + float minDst = std::numeric_limits::max(); + Point bestTarget = vecB[i]; + bool foundMatch = false; + + for (int dy = -1; dy <= 1; ++dy) { + for (int dx = -1; dx <= 1; ++dx) { + auto it = mapA.find({bx + dx, by + dy}); + if (it != mapA.end()) { + int aIdx = it->second; + + // Check Forward Segment A + if (aIdx < (int)vecA.size() - 1) { + auto res = getClosestPointOnSegment(vecB[i], vecA[aIdx], vecA[aIdx + 1]); + if (res.second < minDst) { + minDst = res.second; + bestTarget = res.first; + foundMatch = true; + } + } + // Check Backward Segment A + if (aIdx > 0) { + auto res = getClosestPointOnSegment(vecB[i], vecA[aIdx - 1], vecA[aIdx]); + if (res.second < minDst) { + minDst = res.second; + bestTarget = res.first; + foundMatch = true; + } + } + } + } + } + + if (foundMatch) { + Point mid = (vecB[i] + bestTarget) * 0.5f; + updatesB.push_back({(int)i, mid}); + } + } + + if ((updatesA.size() == 0) | (updatesB.size() == 0)) { + return; + } + + // --- Apply Updates --- + for (const auto &u : updatesA) vecA[u.index] = u.newPos; + for (const auto &u : updatesB) vecB[u.index] = u.newPos; + + // --- OPTIONAL FINAL POLISH: Laplacian Smooth --- + // This removes any remaining high-frequency noise from the seam + // Only run this on the points that were actually touched/updated + // Formula: P_i = 0.25*P_prev + 0.5*P_curr + 0.25*P_next + + auto smoothVector = [](std::vector &pts, const std::vector &updates) { + std::vector original = pts; + for (const auto &u : updates) { + int i = u.index; + if (i > 0 && i < (int)pts.size() - 1) { + pts[i] = 0.25f * original[i - 1] + 0.5f * original[i] + 0.25f * original[i + 1]; + } + } + }; + + auto laplacianSmooth = [](std::vector &pts, const std::vector &updates) { + std::vector original = pts; + for (const auto &u : updates) { + int i = u.index; + if (i > 0 && i < (int)pts.size() - 1) { + // Heavier weight on self (0.6) to preserve shape, but smooth noise (0.2 + // neighbors) + pts[i] = 0.2f * original[i - 1] + 0.6f * original[i] + 0.2f * original[i + 1]; + } + } + }; + + smoothVector(vecA, updatesA); + smoothVector(vecB, updatesB); +} + +// Project p onto segment v-w. Returns closest point. +Point getClosestPoint(Point p, Point v, Point w) { + float l2 = Point::distSq(v, w); + if (l2 == 0.0f) return v; + + float t = ((p.x - v.x) * (w.x - v.x) + (p.y - v.y) * (w.y - v.y)) / l2; + // Allow slight extension (0.01) to help corners "kiss" + t = std::max(-0.1f, std::min(1.1f, t)); + + return {v.x + t * (w.x - v.x), v.y + t * (w.y - v.y)}; +} + +// --- Step 1: Boundary Locking --- +// Returns a mask: true = Locked (On Boundary), false = Free to move +std::vector> createBoundaryMask(const std::vector> &contours, + Rect bounds) { + std::vector> locked(contours.size()); + float eps = 0.1; // Tolerance for "on the boundary" + + for (size_t c = 0; c < contours.size(); ++c) { + locked[c].resize(contours[c].size(), false); + for (size_t p = 0; p < contours[c].size(); ++p) { + Point pt = contours[c][p]; + // Check Left, Right, Top, Bottom + if (std::abs(pt.x - bounds.x) < eps || + std::abs(pt.x - (bounds.x + bounds.width - 1.0f)) < eps || + std::abs(pt.y - bounds.y) < eps || + std::abs(pt.y - (bounds.y + bounds.height - 1.0f)) < eps) { + locked[c][p] = true; + } + } + } + return locked; +} + +// --- Corner Detection (Feature Preservation) --- +std::vector detectCorners(const std::vector &pts, float angleThresholdDeg = 150.0) { + std::vector isCorner(pts.size(), false); + if (pts.size() < 3) return isCorner; + float threshold = std::cos(angleThresholdDeg * M_PI / 180.0f); + + for (size_t i = 1; i < pts.size() - 1; ++i) { + Point v1 = normalize(pts[i] - pts[i - 1]); + Point v2 = normalize(pts[i + 1] - pts[i]); + if (v1.x * v2.x + v1.y * v2.y < threshold) isCorner[i] = true; + } + // Endpoints are corners + isCorner[0] = true; + isCorner.back() = true; + return isCorner; +} + +// --- Selective Smoothing --- +void selectiveSmooth(std::vector &pts, const std::vector &isLocked) { + std::vector original = pts; + for (size_t i = 1; i < pts.size() - 1; ++i) { + // DO NOT move if it's a Corner OR if it's Locked on the boundary + if (isLocked[i]) continue; + + pts[i] = 0.25f * original[i - 1] + 0.5f * original[i] + 0.25f * original[i + 1]; + } +} + +void coupledSmooth(std::vector> &contours, + const std::vector> &lockedMasks, float pairRadiusSq = 2.25f) { + SavitzkyGolay sg(2, 2); // radius, polynomial order + + // first fit + std::vector> smoothedContours; + for (int c = 0; c < (int)contours.size(); ++c) { + std::vector sc = sg.filter_wrap(contours[c]); + smoothedContours.push_back(sc); + } + + // 1. Build Spatial Grid to find partners quickly + std::map> grid; + for (int c = 0; c < (int)contours.size(); ++c) { + for (int p = 0; p < (int)contours[c].size(); ++p) { + grid[{static_cast(contours[c][p].x), static_cast(contours[c][p].y)}] + .push_back({c, p}); + } + } + + // We calculate ALL targets before applying any updates to maintain stability + std::vector> targetPos = contours; + // float pairRadiusSq = 1.5f * 1.5f; // Radius to define "Connected/Paired" + + for (int c = 0; c < (int)contours.size(); ++c) { + for (int p = 1; p < (int)contours[c].size() - 1; ++p) { + // SKIP Constraints + if (lockedMasks[c][p]) continue; + + Point myPos = contours[c][p]; + Point prev = contours[c][p - 1]; + Point next = contours[c][p + 1]; + + // 1. Calculate My Laplacian Target (Where I want to go to be smooth) + Point myTarget = smoothedContours[c][p]; + + // 2. Find Partners in OTHER contours + Point sumPartnerTargets = {0, 0}; + int partnerCount = 0; + + int gx{static_cast(myPos.x)}; + int gy{static_cast(myPos.y)}; + + // Check 3x3 grid + for (int dy = -1; dy <= 1; ++dy) { + for (int dx = -1; dx <= 1; ++dx) { + auto it = grid.find({gx + dx, gy + dy}); + if (it == grid.end()) continue; + + for (const auto &neighbor : it->second) { + if (neighbor.cIdx == c) continue; // Ignore self + + Point otherPos = contours[neighbor.cIdx][neighbor.pIdx]; + if (Point::distSq(myPos, otherPos) < pairRadiusSq) { + // Found a partner! + // Calculate where the PARTNER wants to go + // (We need safe access to partner's neighbors) + const auto &otherContour = contours[neighbor.cIdx]; + int op = neighbor.pIdx; + + // Only calculate partner target if they are not constrained + if (op > 0 && op < (int)otherContour.size() - 1 && + // !cornerMasks[neighbor.cIdx][op] && + !lockedMasks[neighbor.cIdx][op]) { + Point oPrev = otherContour[op - 1]; + Point oNext = otherContour[op + 1]; + + Point oTarget = smoothedContours[neighbor.cIdx][op]; + + sumPartnerTargets += oTarget; + partnerCount++; + } else { + // If partner is constrained (e.g. corner), + // we should probably snap to THEM, not smooth them. + // For simplicity, we treat their current pos as their target. + sumPartnerTargets += otherPos; + partnerCount++; + } + } + } + } + } + + // 3. Average "My Desire" with "Partners' Desires" + if (partnerCount > 0) { + targetPos[c][p] = (myTarget + sumPartnerTargets) / (1.0f + partnerCount); + } else { + // No partners, just smooth myself + targetPos[c][p] = myTarget; + } + } + } + + contours = targetPos; +} + +void coupled_smooth(std::vector> &contours, Rect bounds) { + auto lockedMasks = createBoundaryMask(contours, bounds); + coupledSmooth(contours, lockedMasks, 1.0f); +} + +// --- Main Solver --- +void pack_with_boundary_constraints(std::vector> &contours, Rect bounds, + int iterations) { + // 1. Identify Locked Points (Boundary Constraint) + auto lockedMasks = createBoundaryMask(contours, bounds); + + // 2. Identify Feature Corners (Shape Constraint) + // std::vector> cornerMasks; + // for (const auto& c : contours) cornerMasks.push_back(detectCorners(c)); + + constexpr float radiusSq = 3.0f * 3.0f; // Search radius + + for (int iter = 0; iter < iterations; ++iter) { + // Build Grid + std::map> grid; + for (int c = 0; c < (int)contours.size(); ++c) { + for (int p = 0; p < (int)contours[c].size(); ++p) { + grid[{static_cast(contours[c][p].x), static_cast(contours[c][p].y)}] + .push_back({c, p}); + } + } + + std::vector> nextContours = contours; + + // Apply Forces + for (int c = 0; c < (int)contours.size(); ++c) { + for (int p = 0; p < (int)contours[c].size(); ++p) { + // CRITICAL CHECK: If on boundary, skip all movement logic + if (lockedMasks[c][p]) continue; + + Point currentPos = contours[c][p]; + Point sumTargets = {0, 0}; + int matchCount = 0; + + // Scan Neighborhood + int gx = static_cast(currentPos.x); + int gy = static_cast(currentPos.y); + + for (int dy = -1; dy <= 1; ++dy) { + for (int dx = -1; dx <= 1; ++dx) { + auto it = grid.find({gx + dx, gy + dy}); + if (it == grid.end()) continue; + + for (const auto &neighbor : it->second) { + if (neighbor.cIdx == c) continue; + const auto &other = contours[neighbor.cIdx]; + int idxB = neighbor.pIdx; + + auto checkSeg = [&](int s, int e) { + Point t = getClosestPoint(currentPos, other[s], other[e]); + if (Point::distSq(currentPos, t) < radiusSq) { + sumTargets += t; + matchCount++; + } + }; + if (idxB < (int)other.size() - 1) checkSeg(idxB, idxB + 1); + if (idxB > 0) checkSeg(idxB - 1, idxB); + } + } + } + + if (matchCount > 0) { + float stiffness{1.5f}; + nextContours[c][p] = + (sumTargets + currentPos * stiffness) / (matchCount + stiffness); + } + } + } + + contours = nextContours; + } +} + +} // namespace contours diff --git a/core/src/fft_iterative.cpp b/core/src/fft_iterative.cpp new file mode 100644 index 000000000..1fe10274b --- /dev/null +++ b/core/src/fft_iterative.cpp @@ -0,0 +1,181 @@ +#include "fft_iterative.h" + +#include +#include + +namespace fft { +using std::size_t; + +// Check if an integer is a power of two. +bool is_power_of_two(size_t n) { + return n && ((n & (n - 1)) == 0); +} + +// Return the next power of two >= n. +size_t next_power_of_two(size_t n) { + if (n == 0) return 1; + --n; + n |= n >> 1; + n |= n >> 2; + n |= n >> 4; + n |= n >> 8; + n |= n >> 16; +#if SIZE_MAX > UINT32_MAX + n |= n >> 32; +#endif + return ++n; +} + +/* + * In-place bit-reversal permutation. + * + * The DFT/FFT naturally orders outputs indexed by bit-reversed indices + * during the divide-and-conquer recursion. For an iterative implementation, + * we first reorder the input array by bit-reversed indices so subsequent + * "butterfly" passes combine the correct elements. + * + * a: input vector of length N = 2^log_n + */ +void bit_reverse_permute(std::vector &a) { + const size_t N = a.size(); + int log_n = 0; // Base 2 + while ((1u << log_n) < N) ++log_n; // Set log_n to the exponent of 2 such that N = 2^log_n + + // Reverse each element + for (size_t i = 0; i < N; ++i) { + // compute bit-reversed index of i with log_n bits + size_t rev = 0; + size_t x = i; + // Reverse element i + for (int b = 0; b < log_n; ++b) { + rev = (rev << 1) | (x & 1); + x >>= 1; + } + if (i < rev) std::swap(a[i], a[rev]); // Avoid swapping twice + } +} + +void pad_to_pow_two(std::vector &a, size_t &N) { + if (is_power_of_two(N)) return; + + size_t N2 = next_power_of_two(N); + a.resize(N2, cd{0.0, 0.0}); + N = N2; +} + +/* + * Iterative in-place FFT. + * + * Engineering convention: + * - forward transform (inverse = false): uses exponent -j*2*pi*k*n/N + * - inverse transform (inverse = true): uses exponent +j*2*pi*k*n/N and + * divides final results by N (normalization). + * + * a: input buffer (modified in-place). After call it contains the transform. + * inverse: false => forward FFT (negative exponent), true => inverse FFT. + * + * Complexity: O(N log N) arithmetic operations, N must be a power of two (or + * will be padded if pad_to_pow2 is true). + */ +void iterative_fft(std::vector &a, bool inverse) { + size_t N{a.size()}; + + pad_to_pow_two(a, N); + + // 1) Bit-reversal permutation + // Reorder a for step 2 + bit_reverse_permute(a); + + // 2) Iterative Danielson-Lanczos (butterfly) stages. + const double PI = std::acos(-1.0); + const double sign = + inverse ? +1.0 : -1.0; // -1 for forward (engineering convention), +1 for inverse + + // len is the current transform length (2, 4, 8, ..., N) + // For a given len, we combine two sub-DFTs of size len/2 into one of size + // len. + for (size_t len = 2; len <= N; len <<= 1) { + // primitive len-th root of unity for this stage: + // w_len = exp(sign * j * 2*pi / len) + const double angle = sign * 2.0 * PI / double(len); + const cd wlen = std::polar(1.0, angle); + + // iterate over blocks of size len + for (size_t i = 0; i < N; i += len) { + cd w = cd{1.0, 0.0}; // w = wlen^0 initially + const size_t half = len >> 1; // len/2 butterflies per block + for (size_t j = 0; j < half; ++j) { + // positions in array corresponding to the DFT indices: + // u = X[i + j] (upper half), v = X[i + j + half] * w (lower half times + // twiddle) + cd u = a[i + j]; + cd v = a[i + j + half] * w; + a[i + j] = u + v; // combined even-frequency part + a[i + j + half] = u - v; // combined odd-frequency part + w *= wlen; // advance twiddle: w = w * wlen + } + } + } + + // 3) If inverse transform, normalize by 1/N to get the true inverse DFT. + if (inverse) { + for (size_t i = 0; i < N; ++i) a[i] /= static_cast(N); + } +} + +/* + * Convenience wrapper: take a const input vector and return the FFT result + * as a new vector. This will optionally pad to power-of-two if requested. + */ +std::vector fft_copy(const std::vector &input, bool inverse) { + std::vector a = input; + iterative_fft(a, inverse); + return a; +} + +// Perform 2D FFT using your iterative FFT on rows and columns +void iterative_fft_2d(std::vector &data, size_t width, size_t height, bool inverse) { + // Determine next power-of-two dimensions + size_t W = fft::next_power_of_two(width); + size_t H = fft::next_power_of_two(height); + + // Pad if necessary + if (W != width || H != height) { + std::vector padded(W * H, {0.0, 0.0}); + for (size_t y = 0; y < height; y++) + for (size_t x = 0; x < width; x++) padded[y * W + x] = data[y * width + x]; + data = std::move(padded); + width = W; + height = H; + } + + // Temporary buffers for row/column FFTs + std::vector temp_row(width); + std::vector temp_col(height); + + // FFT rows + for (size_t y = 0; y < height; y++) { + std::copy(data.begin() + y * width, data.begin() + (y + 1) * width, temp_row.begin()); + fft::iterative_fft(temp_row, inverse); + std::copy(temp_row.begin(), temp_row.end(), data.begin() + y * width); + } + + // FFT columns + for (size_t x = 0; x < width; x++) { + for (size_t y = 0; y < height; y++) temp_col[y] = data[y * width + x]; + fft::iterative_fft(temp_col, inverse); + for (size_t y = 0; y < height; y++) data[y * width + x] = temp_col[y]; + } +} + +/* + * Convenience wrapper: take a const input vector and return the 2D FFT result + * as a new vector. This will optionally pad to power-of-two if requested. + */ +std::vector iterative_fft_2d_copy(const std::vector &input, size_t width, size_t height, + bool inverse) { + std::vector a = input; + iterative_fft_2d(a, width, height, inverse); + return a; +} +} // namespace fft diff --git a/core/src/graph.cpp b/core/src/graph.cpp new file mode 100644 index 000000000..756109787 --- /dev/null +++ b/core/src/graph.cpp @@ -0,0 +1,347 @@ +#include "graph.h" + +#include +#include +#include +#include + +#include "Pixel.h" +#include "bezier.h" +/* + Graph class - manages Node class +*/ + +static inline float colorDistance(const ImageLib::RGBPixel &a, + const ImageLib::RGBPixel &b) { + ImageLib::RGBPixel af{static_cast(a.red), static_cast(a.green), + static_cast(a.blue)}; + ImageLib::RGBPixel bf{static_cast(b.red), static_cast(b.green), + static_cast(b.blue)}; + return std::sqrt((af.red - bf.red) * (af.red - bf.red) + + (af.green - bf.green) * (af.green - bf.green) + + (af.blue - bf.blue) * (af.blue - bf.blue)); +} + +/* +To quickly search m_nodes (std::vector) for the index of a node id +create an std::unordered_map of node id - index pairs +indexing time of std::vector by value is O(N) +lookup time of std::unordered_map by key is O(log(N)) +*/ +void Graph::hash_node_ids() { + for (int32_t i{0}; i < m_nodes->size(); i++) { + const int32_t key{m_nodes->at(i)->id()}; + m_node_ids[key] = i; + } +} + +bool Graph::all_areas_bigger_than(int32_t min_area) { + for (auto &n : *m_nodes) { + if (n->area() < min_area) { + return false; + } + } + + return true; +} + +bool Graph::add_edge(int32_t node_id1, int32_t node_id2) { + auto end_node_ids{m_node_ids.end()}; + auto node1_it{m_node_ids.find(node_id1)}; + auto node2_it{m_node_ids.find(node_id2)}; + + if (node1_it == end_node_ids || node2_it == end_node_ids) { + return false; + } + + const int32_t idx1{node1_it->second}; + const int32_t idx2{node2_it->second}; + + m_nodes->at(idx1)->add_edge(m_nodes->at(idx2)); + m_nodes->at(idx2)->add_edge(m_nodes->at(idx1)); + return true; +} + +bool Graph::merge_nodes(const Node_ptr &node_to_keep, const Node_ptr &node_to_remove) { + auto end_node_ids{m_node_ids.end()}; + auto node1_it{m_node_ids.find(node_to_keep->id())}; + auto node2_it{m_node_ids.find(node_to_remove->id())}; + + if (node1_it == end_node_ids || node2_it == end_node_ids) { + return false; + } + + const int32_t idx_k{node1_it->second}; + const int32_t idx_r{node2_it->second}; + + // transfer edges from node_to_remove to node_to_keep + for (Node_ptr n : m_nodes->at(idx_r)->edges()) { + if (n->id() != node_to_keep->id()) { + // prevents self referencing + n->remove_edge(node_to_remove); + n->add_edge(node_to_keep); + node_to_keep->add_edge(n); + } + } + + node_to_keep->add_pixels(node_to_remove->get_pixels()); + + node_to_remove->clear_all(); + + return true; +} + +void Graph::clear_unconnected_nodes() { + std::vector &nodes{*m_nodes}; + + nodes.erase(std::remove_if(nodes.begin(), nodes.end(), + [](const Node_ptr &n) { return n->area() == 0; }), + nodes.end()); + + hash_node_ids(); +} + +void Graph::discover_edges(const std::vector ®ion_labels, const int32_t width, + const int32_t height) { + // Moore 8-connected neighbourhood + constexpr int8_t dirs[8][2]{{1, 0}, {-1, 0}, {0, 1}, {0, -1}, + {1, 1}, {-1, -1}, {-1, 1}, {1, -1}}; + + int32_t rneigh[8]; + + for (int32_t y{0}; y < height; ++y) { + for (int32_t x{0}; x < width; ++x) { + const int32_t idx{y * width + x}; + const int32_t rid{region_labels[idx]}; + + for (int32_t k{0}; k < 8; ++k) { + const int32_t nx{x + dirs[k][0]}; + const int32_t ny{y + dirs[k][1]}; + + if (nx >= 0 && nx < width && ny >= 0 && ny < height) { + rneigh[k] = region_labels[ny * width + nx]; + } else { + rneigh[k] = rid; // ignore out-of-bounds + } + } + + for (int32_t r : rneigh) { + if (r != rid) { + add_edge(rid, r); + } + } + } + } +} + +void Graph::compute_contours() { + // overlap edge pixels + // then compute contours + + std::set> adjusted_neighbors{}; + + constexpr int8_t dirs[8][2]{{1, 0}, {-1, 0}, {0, 1}, {0, -1}, + {1, 1}, {-1, -1}, {-1, 1}, {1, -1}}; + + for (const Node_ptr &n : get_nodes()) { + if (n->area() == 0) continue; + + std::vector> full_neighborhood; + std::vector> xywh; + + std::vector node_binary; + std::array xywh0 = n->create_binary_image(node_binary); + + full_neighborhood.push_back(node_binary); + xywh.push_back(xywh0); + + std::vector considered_neigbors; + for (const auto &neighbor : n->edges()) { + if (neighbor->area() == 0) continue; + + // check if this neighbor pairing has already been addressed + std::pair id1 = std::make_pair(n->id(), neighbor->id()); + std::pair id2 = std::make_pair(neighbor->id(), n->id()); + auto _end{adjusted_neighbors.end()}; + auto _it1{adjusted_neighbors.find(id1)}; + auto _it2{adjusted_neighbors.find(id2)}; + + if (_it1 != _end || _it2 != _end) { + continue; + } + + considered_neigbors.push_back(neighbor); + + std::vector neighbor_binary; + std::array xywh1 = neighbor->create_binary_image(neighbor_binary); + full_neighborhood.push_back(neighbor_binary); + xywh.push_back(xywh1); + + adjusted_neighbors.insert(id1); + } + + // address overlaps + std::vector neighborhood; + std::array bounds = {std::numeric_limits::max(), + std::numeric_limits::max(), -1, -1}; + for (auto &_xywh : xywh) { + if (_xywh[0] < bounds[0]) { + bounds[0] = _xywh[0]; + } // xmin + if (_xywh[1] < bounds[1]) { + bounds[1] = _xywh[1]; + } // ymin + if (_xywh[2] + _xywh[0] - 1 > bounds[2]) { + bounds[2] = _xywh[2] + _xywh[0] - 1; + } // xmax + if (_xywh[3] + _xywh[1] - 1 > bounds[3]) { + bounds[3] = _xywh[3] + _xywh[1] - 1; + } // ymax + } + + bounds[2] = bounds[2] - bounds[0] + 1; // w + bounds[3] = bounds[3] - bounds[1] + 1; // h + + // build joined neighborhood map + neighborhood.resize( + static_cast(bounds[2]) * static_cast(bounds[3]), 0); + + for (int i = 0; i < full_neighborhood.size(); ++i) { + for (int y = 0; y < xywh[i][3]; ++y) { + for (int x = 0; x < xywh[i][2]; ++x) { + int global_y = y + xywh[i][1] - bounds[1]; + int global_x = x + xywh[i][0] - bounds[0]; + uint8_t val = full_neighborhood[i][y * xywh[i][2] + x]; + if (val != 0) { + neighborhood[global_y * bounds[2] + global_x] = (i + 1); + } + } + } + } + + // 0 = background, 1 = this node, 2+ = neighboring nodes + + // find touching edges + for (int y = 0; y < bounds[3]; ++y) { + for (int x = 0; x < bounds[2]; ++x) { + uint8_t val = neighborhood[y * bounds[2] + x]; + // check neighbors + if (val == 1) { + for (int32_t k{0}; k < 8; ++k) { + int32_t nx{x + dirs[k][0]}; + int32_t ny{y + dirs[k][1]}; + nx = std::clamp(nx, 0, bounds[2] - 1); + ny = std::clamp(ny, 0, bounds[3] - 1); + uint8_t n_val = neighborhood[ny * bounds[2] + nx]; + if ((n_val != val) & (n_val != 0)) { + // need a smarter approach to prevent pinching + bool is_too_thin = false; + // check around (nx,ny) if we can stretch into another region, + // then it's too thin + for (int32_t k{0}; k < 8; ++k) { + int32_t mx{nx + dirs[k][0]}; + int32_t my{ny + dirs[k][1]}; + mx = std::clamp(mx, 0, bounds[2] - 1); + my = std::clamp(my, 0, bounds[3] - 1); + uint8_t m_val = neighborhood[my * bounds[2] + mx]; + + if ((m_val != val) & (m_val != n_val)) { + is_too_thin = true; + } + } + + if (is_too_thin) { + considered_neigbors[n_val - 2]->add_edge_pixel( + XY{x + bounds[0], y + bounds[1]}); + } else { + n->add_edge_pixel(XY{nx + bounds[0], ny + bounds[1]}); + } + } + } + } + } + } + } + + // ask each Node to compute contours + for (const Node_ptr &n : get_nodes()) { + if (n->area() == 0) continue; + n->compute_contour(); + } + + // smoothing + std::vector> all_contours; + for (const Node_ptr &n : get_nodes()) { + if (n->area() == 0) continue; + + ColoredContours *c0 = &n->m_contours; + for (size_t i = 0; i < c0->contours.size(); ++i) { + all_contours.push_back(c0->contours[i]); + } + } + + contours::coupled_smooth( + all_contours, Rect{0.0f, 0.0f, static_cast(m_width), static_cast(m_height)}); + + std::vector> all_curves; + fit_curve_reduction(all_contours, all_curves, 0.5f); + + int j = 0; + for (const Node_ptr &n : get_nodes()) { + if (n->area() == 0) continue; + + ColoredContours *c0 = &n->m_contours; + for (size_t i = 0; i < c0->contours.size(); ++i) { + std::copy(all_contours[j].begin(), all_contours[j].end(), c0->contours[i].begin()); + + c0->curves[i].resize(all_curves[j].size()); + std::copy(all_curves[j].begin(), all_curves[j].end(), c0->curves[i].begin()); + j++; + } + } +} + +void Graph::merge_small_area_nodes(const int32_t min_area) { + int32_t counter{0}; + while (!all_areas_bigger_than(min_area)) { + for (const Node_ptr &n : get_nodes()) { + if (n->area() < min_area) { + std::vector neighbors; + neighbors.reserve(n->num_edges()); + std::copy(n->edges().begin(), n->edges().end(), std::back_inserter(neighbors)); + + ImageLib::RGBPixel col = n->color(); + // sort by size and color similarity + std::sort(neighbors.begin(), neighbors.end(), [col](Node_ptr a, Node_ptr b) { + float cdista = ImageLib::RGBPixel::colorDistance(a->color(), col); + float cdistb = ImageLib::RGBPixel::colorDistance(b->color(), col); + return (static_cast(a->area()) + 10.f * cdista) < + (static_cast(b->area()) + 10.f * cdistb); + }); + + int32_t idx{0}; + // find first non-zero area neighbor + for (Node_ptr &ne : neighbors) { + if (ne->area() > 0) { + break; + } + ++idx; + } + + // no valid neighbor found, skip this node + if (idx >= static_cast(neighbors.size())) { + continue; + } + + if (neighbors[idx]->area() >= n->area()) { + merge_nodes(neighbors[idx], n); + } else { + merge_nodes(n, neighbors[idx]); + } + } + } + + clear_unconnected_nodes(); + ++counter; + } +} diff --git a/core/src/image_utils.cpp b/core/src/image_utils.cpp new file mode 100644 index 000000000..6896519a8 --- /dev/null +++ b/core/src/image_utils.cpp @@ -0,0 +1,148 @@ +#include "image_utils.h" + +#include +#include +#include +#include +#include +#include + +#include "Image.h" +#include "PixelConverters.h" +#include "RGBAPixel.h" +#include "fft_iterative.h" +#include "img2num.h" + +uint8_t quantize(uint8_t value, uint8_t region_size) { + if (region_size == 0) { + return value; + } + + uint8_t bucket = value / region_size; // Narrowing to colour boundary with + // Range [0 : num_thresholds - 1]. + + uint8_t bucket_boundary = (bucket * region_size); + uint8_t bucket_midpoint = + bucket_boundary + (region_size / 2); // Map to threshold region's midpoint. + + // In case of bucket_midpoint overflow: revert to a smaller bucket than the + // largest possible value. + bool overflow = bucket_midpoint < bucket_boundary; + if (overflow) { + bucket_midpoint = ((bucket - 1) * region_size) + + (region_size / 2); // Correction by reducing the bucket value belongs to. + } + + return bucket_midpoint; +} + +namespace img2num { +// image: pointer to RGBA data +// width, height: dimensions +// sigma: standard deviation of Gaussian blur +void gaussian_blur_fft(uint8_t *image, size_t width, size_t height, double sigma_pixels) { + if (!image || width == 0 || height == 0 || sigma_pixels <= 0) return; + + const size_t Npix = width * height; + + // Compute padded dimensions (next power of two) + const size_t W = fft::next_power_of_two(width); + const size_t H = fft::next_power_of_two(height); + const size_t Npix_padded = W * H; + + // Frequency coordinates helper (DC at corner) + auto freq_coord = [](int k, int dim) -> double { + return (k <= dim / 2) ? double(k) / dim : double(k - dim) / dim; + }; + + // Precompute Gaussian factor in frequency domain + const double two_pi2_sigma2 = 2.0 * M_PI * M_PI * sigma_pixels * sigma_pixels; + + for (int channel = 0; channel < 3; channel++) { + // Allocate padded buffer + std::vector data(Npix_padded, {0.0, 0.0}); + + // Copy original image channel into padded buffer + for (size_t y = 0; y < height; y++) + for (size_t x = 0; x < width; x++) + data[y * W + x] = fft::cd(image[(y * width + x) * 4 + channel], 0.0); + + // Forward 2D FFT + fft::iterative_fft_2d(data, W, H, false); + + // Apply Gaussian filter in frequency domain + for (size_t y = 0; y < H; y++) { + double fy2 = freq_coord(y, H) * freq_coord(y, H); + for (size_t x = 0; x < W; x++) { + double fx2 = freq_coord(x, W) * freq_coord(x, W); + double gain = std::exp(-two_pi2_sigma2 * (fx2 + fy2)); + data[y * W + x] *= gain; + } + } + + // Inverse 2D FFT + fft::iterative_fft_2d(data, W, H, true); + + // Copy back only the original width/height and clamp + for (size_t y = 0; y < height; y++) + for (size_t x = 0; x < width; x++) { + double v = data[y * W + x].real(); + v = std::clamp(v, 0.0, 255.0); + image[(y * width + x) * 4 + channel] = static_cast(std::lrint(v)); + } + } + + // Alpha channel remains unchanged +} + +// Called from JS. `ptr` points to RGBA bytes. +void invert_image(uint8_t *ptr, int width, int height) { + ImageLib::Image> img; + img.loadFromBuffer(ptr, width, height, ImageLib::RGBA_CONVERTER); + + for (ImageLib::RGBAPixel &p : img) { + p.red = 255 - p.red; + p.blue = 255 - p.blue; + p.green = 255 - p.green; + } + + const auto &modified = img.getData(); + std::memcpy(ptr, modified.data(), modified.size() * sizeof(ImageLib::RGBAPixel)); +} + +void threshold_image(uint8_t *ptr, const int width, const int height, const int num_thresholds) { + const uint8_t REGION_SIZE(255 / num_thresholds); // Size of buckets per colour + + ImageLib::Image> img; + img.loadFromBuffer(ptr, width, height, ImageLib::RGBA_CONVERTER); + + const auto imgWidth{img.getWidth()}, imgHeight{img.getHeight()}; + for (ImageLib::RGBAPixel &p : img) { + p.red = quantize(p.red, REGION_SIZE); + p.green = quantize(p.green, REGION_SIZE); + p.blue = quantize(p.blue, REGION_SIZE); + } + + const auto &modified = img.getData(); + std::memcpy(ptr, modified.data(), modified.size() * sizeof(ImageLib::RGBAPixel)); +} + +void black_threshold_image(uint8_t *ptr, const int width, const int height, + const int num_thresholds) { + ImageLib::Image> img; + img.loadFromBuffer(ptr, width, height, ImageLib::RGBA_CONVERTER); + + const auto imgWidth{img.getWidth()}, imgHeight{img.getHeight()}; + for (ImageLib::RGBAPixel &p : img) { + const bool R{p.red < num_thresholds}; + const bool G{p.green < num_thresholds}; + const bool B{p.blue < num_thresholds}; + if (R && B && G) { + p.setGray(0); + } + } + + const auto &modified = img.getData(); + std::memcpy(ptr, modified.data(), modified.size() * sizeof(ImageLib::RGBAPixel)); +} +} // namespace img2num diff --git a/core/src/kmeans.cpp b/core/src/kmeans.cpp new file mode 100644 index 000000000..c53809d92 --- /dev/null +++ b/core/src/kmeans.cpp @@ -0,0 +1,236 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "Image.h" +#include "LABAPixel.h" +#include "PixelConverters.h" +#include "RGBAPixel.h" +#include "cielab.h" +#include "img2num.h" + +static constexpr uint8_t COLOR_SPACE_OPTION_CIELAB{0}; +static constexpr uint8_t COLOR_SPACE_OPTION_RGB{1}; + +// The K-Means++ Initialization Function +template +void kMeansPlusPlusInit(const ImageLib::Image &pixels, + ImageLib::Image &out_centroids, int k) { + std::vector centroids; + + int num_pixels = pixels.getSize(); + // Random number generator setup + std::random_device rd; + std::mt19937 gen(rd()); + + // --- Step 1: Choose the first centroid uniformly at random --- + std::uniform_int_distribution<> dis(0, num_pixels - 1); + int first_index = dis(gen); + centroids.push_back(pixels[first_index]); + + // Vector to store the squared distance of each pixel to its NEAREST existing + // centroid. Initialize with max double so the first distance calculation + // always updates it. + std::vector min_dist_sq(num_pixels, std::numeric_limits::max()); + + // --- Step 2 & 3: Repeat until we have k centroids --- + for (int i = 1; i < k; ++i) { + double sum_dist_sq = 0.0; + + // Update distances relative to the LAST added centroid (centroids.back()) + // We don't need to recheck previous centroids; min_dist_sq already holds + // the best distance to them. + for (int j = 0; j < num_pixels; ++j) { + double d = PixelT::colorDistance(pixels[j], centroids.back()); + + // If this new centroid is closer than the previous best, update the min + // distance + if (d < min_dist_sq[j]) { + min_dist_sq[j] = d; + } + sum_dist_sq += min_dist_sq[j]; + } + + // --- Step 3: Choose new center with probability proportional to D(x)^2 --- + // We use a weighted random selection (Roulette Wheel Selection) + std::uniform_real_distribution<> dist_selector(0.0, sum_dist_sq); + double random_value = dist_selector(gen); + + double current_sum = 0.0; + int selected_index = -1; + + // Iterate to find the pixel corresponding to the random_value + for (int j = 0; j < num_pixels; ++j) { + current_sum += min_dist_sq[j]; + if (current_sum >= random_value) { + selected_index = j; + break; + } + } + + // Fallback for floating point rounding errors (pick last one if loop + // finishes) + if (selected_index == -1) { + selected_index = num_pixels - 1; + } + + centroids.push_back(pixels[selected_index]); + } + + std::copy(centroids.begin(), centroids.end(), out_centroids.begin()); +} + +namespace img2num { +void kmeans(const uint8_t *data, uint8_t *out_data, int32_t *out_labels, const int32_t width, + const int32_t height, const int32_t k, const int32_t max_iter, + const uint8_t color_space) { + ImageLib::Image> pixels; + pixels.loadFromBuffer(data, width, height, ImageLib::RGBA_CONVERTER); + const int32_t num_pixels{pixels.getSize()}; + + // width = k, height = 1 + // k centroids, initialized to rgba(0,0,0,255) + // Init of each pixel is from default in Image constructor + ImageLib::Image> centroids{k, 1}; + ImageLib::Image> centroids_lab{k, 1}; + std::vector labels(num_pixels, 0); + + ImageLib::Image> lab(pixels.getWidth(), pixels.getHeight()); + if (color_space == COLOR_SPACE_OPTION_CIELAB) { + for (int i{0}; i < pixels.getSize(); ++i) { + rgb_to_lab(pixels[i], lab[i]); + } + } + + // Step 2: Initialize centroids randomly + + switch (color_space) { + case COLOR_SPACE_OPTION_RGB: { + kMeansPlusPlusInit>(pixels, centroids, k); + break; + } + case COLOR_SPACE_OPTION_CIELAB: { + kMeansPlusPlusInit>(lab, centroids_lab, k); + break; + } + } + + // Step 3: Run k-means iterations + + // Assignment step + for (int32_t iter{0}; iter < max_iter; ++iter) { + bool changed{false}; + + // Iterate over pixels + for (int32_t i{0}; i < num_pixels; ++i) { + float min_color_dist{std::numeric_limits::max()}; + int32_t best_cluster{0}; + + // Iterate over centroids to find centroid with most similar color to + // pixels[i] + float dist; + for (int32_t j{0}; j < k; ++j) { + switch (color_space) { + case COLOR_SPACE_OPTION_RGB: { + dist = ImageLib::RGBAPixel::colorDistance(pixels[i], centroids[j]); + break; + } + case COLOR_SPACE_OPTION_CIELAB: { + dist = ImageLib::LABAPixel::colorDistance(lab[i], centroids_lab[j]); + break; + } + } + if (dist < min_color_dist) { + min_color_dist = dist; + best_cluster = j; + } + } + + if (labels[i] != best_cluster) { + changed = true; + labels[i] = best_cluster; + } + } + + // Stop if no changes + if (!changed) { + break; + } + + // Update step + ImageLib::Image> new_centroids(k, 1, 0); + ImageLib::Image> new_centroids_lab(k, 1, 0); + std::vector counts(k, 0); + + for (int32_t i = 0; i < num_pixels; ++i) { + int32_t cluster = labels[i]; + switch (color_space) { + case COLOR_SPACE_OPTION_RGB: { + new_centroids[cluster].red += pixels[i].red; + new_centroids[cluster].green += pixels[i].green; + new_centroids[cluster].blue += pixels[i].blue; + break; + } + case COLOR_SPACE_OPTION_CIELAB: { + new_centroids_lab[cluster].l += lab[i].l; + new_centroids_lab[cluster].a += lab[i].a; + new_centroids_lab[cluster].b += lab[i].b; + break; + } + } + counts[cluster]++; + } + + for (int32_t j = 0; j < k; ++j) { + /* + A centroid may become a dead centroid if it never gets pixels assigned + to it. May be good idea to reinitialize these dead centroids. + */ + if (counts[j] > 0) { + switch (color_space) { + case COLOR_SPACE_OPTION_RGB: { + centroids[j].red = new_centroids[j].red / counts[j]; + centroids[j].green = new_centroids[j].green / counts[j]; + centroids[j].blue = new_centroids[j].blue / counts[j]; + break; + } + case COLOR_SPACE_OPTION_CIELAB: { + centroids_lab[j].l = new_centroids_lab[j].l / counts[j]; + centroids_lab[j].a = new_centroids_lab[j].a / counts[j]; + centroids_lab[j].b = new_centroids_lab[j].b / counts[j]; + break; + } + } + } + } + } + + if (color_space == COLOR_SPACE_OPTION_CIELAB) { + for (int32_t i{0}; i < k; ++i) { + lab_to_rgb(centroids_lab[i], centroids[i]); + } + } + + // Write the final centroid values to each pixel in the cluster + for (int32_t i = 0; i < num_pixels; ++i) { + const int32_t cluster = labels[i]; + out_data[i * 4 + 0] = + static_cast(std::clamp(centroids[cluster].red, 0.0f, 255.0f)); + out_data[i * 4 + 1] = + static_cast(std::clamp(centroids[cluster].green, 0.0f, 255.0f)); + out_data[i * 4 + 2] = + static_cast(std::clamp(centroids[cluster].blue, 0.0f, 255.0f)); + out_data[i * 4 + 3] = 255; + } + + // Write labels to out_labels + std::memcpy(out_labels, labels.data(), labels.size() * sizeof(int32_t)); +} +} // namespace img2num diff --git a/core/src/labels_to_svg.cpp b/core/src/labels_to_svg.cpp new file mode 100644 index 000000000..0d5178ff4 --- /dev/null +++ b/core/src/labels_to_svg.cpp @@ -0,0 +1,267 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "bezier.h" +#include "contours.h" +#include "graph.h" +#include "img2num.h" + +/* Flood fill */ +int flood_fill(std::vector &label_array, std::vector ®ion_array, + const uint8_t *color_array, int x, int y, int target_value, int label_value, + size_t width, size_t height, std::unique_ptr> &out_pixels) { + std::queue queue; + auto index = [width](int x, int y) { return y * width + x; }; + + int count = 0; + int dirs[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; + + RGBXY pix = + RGBXY{color_array[4 * size_t(index(x, y))], color_array[4 * size_t(index(x, y)) + 1], + color_array[4 * size_t(index(x, y)) + 2], x, y}; + + queue.push({x, y}); + + region_array[size_t(index(x, y))] = label_value; + + out_pixels->push_back(pix); + count++; + + while (!queue.empty()) { + XY c = queue.front(); + queue.pop(); + for (auto &d : dirs) { + int x1 = c.x + d[0]; + int y1 = c.y + d[1]; + + // check conditions + if ((x1 >= 0) && (x1 < int(width)) && (y1 >= 0) && (y1 < int(height)) && + (label_array[size_t(index(x1, y1))] == target_value) && + (region_array[size_t(index(x1, y1))] == -1)) { + RGBXY pix1 = RGBXY{color_array[4 * size_t(index(x1, y1))], + color_array[4 * size_t(index(x1, y1)) + 1], + color_array[4 * size_t(index(x1, y1)) + 2], x1, y1}; + region_array[size_t(index(x1, y1))] = label_value; + out_pixels->push_back(pix1); + count++; + + queue.push({x1, y1}); + } + } + } + + return count; +} + +void region_labeling(const uint8_t *data, std::vector &labels, + std::vector ®ions, int width, int height, + std::vector &nodes) { + auto index = [width](int x, int y) { return y * width + x; }; + + regions.resize(static_cast(height) * static_cast(width), -1); + int r_lbl = -1; + + for (int i = 0; i < width; i++) { + for (int j = 0; j < height; j++) { + int label{labels[size_t(index(i, j))]}; + int rlab{regions[size_t(index(i, j))]}; + + if (rlab == -1) { + r_lbl++; + // track pixels for this region + // std::vector pixels; + std::unique_ptr> p_ptr = std::make_unique>(); + int counts = + flood_fill(labels, regions, data, i, j, label, r_lbl, width, height, p_ptr); + int num_pixels = p_ptr->size(); + + // num_pixels == counts always + Node_ptr n_ptr = std::make_shared(r_lbl, p_ptr); + nodes.push_back(n_ptr); + } + } + } +} + +void visualize_contours(const std::vector> &contours, + ImageLib::Image> &results, int width, + int height, int xmin = 0, int ymin = 0) { + // Random generator for colors + static std::mt19937 rng(std::random_device{}()); + static std::uniform_int_distribution dist(0, 255); + for (const auto &c : contours) { + ImageLib::RGBAPixel rand_color{static_cast(dist(rng)), + static_cast(dist(rng)), + static_cast(dist(rng)), 255}; + + for (const auto &p : c) { + int32_t _x{static_cast(p.x) + xmin}; + int32_t _y{static_cast(p.y) + ymin}; + + // Ensure within bounds + if (_x < 0 || _x >= width || _y < 0 || _y >= height) continue; + + results(_x, _y) = rand_color; + } + } +} + +std::string contourToSVGPath(const std::vector &contour) { + if (contour.empty()) return ""; + + std::ostringstream path; + path << std::fixed << std::setprecision(2); + + // Move to the first point + path << "M " << contour[0].x << " " << contour[0].y << " "; + + // Draw lines to the remaining points + for (size_t i = 1; i < contour.size(); ++i) { + path << "L " << contour[i].x << " " << contour[i].y << " "; + } + + // Close the path + path << "Z"; + return path.str(); +} + +std::string contourToSVGCurve(const std::vector &curves) { + if (curves.empty()) return ""; + + std::ostringstream path; + path << std::fixed << std::setprecision(2); + + for (size_t i = 0; i < curves.size(); ++i) { + const auto &c = curves[i]; + if (i == 0) path << "M " << c.p0.x << " " << c.p0.y << " "; + path << "Q " << c.p1.x << " " << c.p1.y << " " << c.p2.x << " " << c.p2.y << " "; + } + + // Close the path + path << "Z"; + return path.str(); +} + +std::string contoursResultToSVG(const ColoredContours &result, const int width, const int height) { + std::ostringstream svg; + svg << "\n"; + + for (size_t i = 0; i < result.curves.size(); ++i) { + std::string pathData = contourToSVGCurve(result.curves[i]); + + const auto &px = result.colors[i]; + std::ostringstream oss; + oss << "#" << std::hex << std::uppercase << std::setw(2) << std::setfill('0') + << static_cast(px.red) << std::setw(2) << std::setfill('0') + << static_cast(px.green) << std::setw(2) << std::setfill('0') + << static_cast(px.blue); + + // You can optionally style holes differently or rely on fill-rule + svg << " \n"; + } + + svg << "\n"; + return svg.str(); +} + +namespace img2num { +/* +data: uint8_t* -> output image from K-Means (or similar) in RGBA repeating +format ([r,g,b,a, r,g,b,a, ...]) labels: int32_t* -> output of labelled regions +from K-Means, should be 1/4 the size of data since data is RGBA labels : width * +height : number of pixels in image = 1 : 1 : 1 +*/ +char *labels_to_svg(uint8_t *data, int32_t *labels, const int width, const int height, + const int min_area, const bool draw_contour_borders) { + const int32_t num_pixels{width * height}; + std::vector labels_vector{labels, labels + num_pixels}; + std::vector region_labels; + + // 1. enumerate regions and convert to Nodes + std::vector nodes; + region_labeling(data, labels_vector, region_labels, width, height, nodes); + + // 2. initialize Graph from all Nodes + std::unique_ptr> node_ptr = + std::make_unique>(std::move(nodes)); + Graph G(node_ptr, width, height); + + // 3. Discover node adjacencies - add edges to Graph + G.discover_edges(region_labels, width, height); + + // 4. Merge small area nodes until all nodes are minArea or larger + G.merge_small_area_nodes(min_area); + + // 5. recolor image on new regions + ImageLib::Image> results{width, height}; + for (auto &n : G.get_nodes()) { + if (n->area() == 0) continue; + + auto [r, g, b] = n->color(); + for (auto &[_, p] : n->get_pixels()) { + results(p.x, p.y) = {r, g, b}; + } + } + + // 6. Contours + // graph will manage computing contours + G.compute_contours(); + + // accumulate all contours for svg export + ColoredContours all_contours; + for (auto &n : G.get_nodes()) { + if (n->area() == 0) continue; + ColoredContours node_contours = n->get_contours(); + for (auto &c : node_contours.contours) { + all_contours.contours.push_back(c); + } + for (auto &c : node_contours.hierarchy) { + all_contours.hierarchy.push_back(c); + } + for (bool b : node_contours.is_hole) { + all_contours.is_hole.push_back(b); + } + for (auto &c : node_contours.colors) { + all_contours.colors.push_back(c); + } + for (auto &c : node_contours.curves) { + all_contours.curves.push_back(c); + } + } + + // 7. Copy recolored image back + const auto &modified = results.getData(); + std::memcpy(data, modified.data(), modified.size() * sizeof(ImageLib::RGBAPixel)); + + // 8. Return SVG if requested + if (!draw_contour_borders) { + std::string svg{contoursResultToSVG(all_contours, width, height)}; + + // Dynamic C-style allocation (since returned over C ABI) + char *res_svg{static_cast(std::malloc(svg.size() + 1))}; + if (!res_svg) { + return nullptr; // Allocation failed + } + std::memcpy(res_svg, svg.c_str(), svg.size() + 1); + + return res_svg; + } + + return nullptr; // no SVG +} +} // namespace img2num diff --git a/core/src/node.cpp b/core/src/node.cpp new file mode 100644 index 000000000..1e0d68b9f --- /dev/null +++ b/core/src/node.cpp @@ -0,0 +1,182 @@ +#include "node.h" + +#include + +/* + Node class + */ + +XY Node::centroid() const { + XY centroid{0, 0}; + const int32_t m_pixels_size{static_cast(m_pixels->size())}; + + // Guard against division by zero after loop + if (m_pixels_size == 0) { + return centroid; + } + + for (auto &[_, pos] : *m_pixels) { + centroid.x += pos.x; + centroid.y += pos.y; + } + + centroid.x /= m_pixels_size; + centroid.y /= m_pixels_size; + + return centroid; +} + +ImageLib::RGBPixel Node::color() const { + const int32_t m_pixels_size{static_cast(m_pixels->size())}; + + // Guard against division by zero after loop + if (m_pixels_size == 0) { + return {0, 0, 0}; + } + + float r{0}; + float g{0}; + float b{0}; + for (auto &[color, _] : *m_pixels) { + r += color.red; + g += color.green; + b += color.blue; + } + + r /= m_pixels_size; + g /= m_pixels_size; + b /= m_pixels_size; + + // Accept lossy conversion - the difference is very minimal + return {static_cast(r), static_cast(g), static_cast(b)}; +} + +std::array Node::bounding_box_xywh() const { + if (m_pixels->empty()) { + return {0, 0, 0, 0}; + } + + int32_t x_min{INT_MAX}; + int32_t y_min{INT_MAX}; + int32_t x_max{0}; + int32_t y_max{0}; + for (auto &[_, p] : *m_pixels) { + if (p.x < x_min) { + x_min = p.x; + } + if (p.x > x_max) { + x_max = p.x; + } + if (p.y < y_min) { + y_min = p.y; + } + if (p.y > y_max) { + y_max = p.y; + } + } + + for (auto &p : m_edge_pixels) { + if (p.x < x_min) { + x_min = p.x; + } + if (p.x > x_max) { + x_max = p.x; + } + if (p.y < y_min) { + y_min = p.y; + } + if (p.y > y_max) { + y_max = p.y; + } + } + + const int32_t w{x_max - x_min + 1}; + const int32_t h{y_max - y_min + 1}; + + return std::array{x_min, y_min, w, h}; +} + +std::array Node::create_binary_image(std::vector &binary) const { + std::array xywh{bounding_box_xywh()}; + + binary.resize(static_cast(xywh[2]) * static_cast(xywh[3]), 0); + + for (auto &[_, p] : *m_pixels) { + int32_t _x = p.x - xywh[0]; + int32_t _y = p.y - xywh[1]; + binary[_y * xywh[2] + _x] = 1; + } + + // include the edge pixels to ensure contour overlap with neighbor + for (auto &p : m_edge_pixels) { + int32_t _x = p.x - xywh[0]; + int32_t _y = p.y - xywh[1]; + binary[_y * xywh[2] + _x] = 1; + } + + return xywh; +} + +void Node::clear_contour(void) { + m_contours.contours.clear(); + m_contours.hierarchy.clear(); + m_contours.is_hole.clear(); + m_contours.colors.clear(); + m_contours.curves.clear(); +} + +void Node::compute_contour(void) { + // return list of all contours present in Node. + // usually 1 sometimes more if holes are present + + clear_contour(); + + std::vector binary; + std::array xywh{create_binary_image(binary)}; + + int xmin = xywh[0]; + int ymin = xywh[1]; + int bw = xywh[2]; + int bh = xywh[3]; + + ContoursResult contour_res = contours::find_contours(binary, bw, bh); + + for (size_t cidx = 0; cidx < contour_res.contours.size(); ++cidx) { + auto &contour = contour_res.contours[cidx]; + for (auto &p : contour) { + p.x += xmin; + p.y += ymin; + } + + // if (contour_res.is_hole[cidx]) { continue; } + + ImageLib::RGBPixel _col = color(); + ImageLib::RGBAPixel col{_col.red, _col.green, _col.blue, 255}; + m_contours.contours.push_back(contour); + m_contours.hierarchy.push_back(contour_res.hierarchy[cidx]); + m_contours.is_hole.push_back(contour_res.is_hole[cidx]); + m_contours.colors.push_back(col); + } + + m_contours.curves.resize(m_contours.contours.size()); +} + +void Node::add_pixels(const std::vector &new_pixels) { + for (auto &c : new_pixels) { + m_pixels->push_back(c); + } +} + +void Node::add_edge_pixel(const XY edge_pixel) { + m_edge_pixels.insert(edge_pixel); +} + +void Node::clear_edge_pixels() { + m_edge_pixels.clear(); +} + +void Node::clear_all() { + m_edges.clear(); + m_pixels->clear(); + m_edge_pixels.clear(); +} diff --git a/docker-compose.yml b/docker-compose.yml index da81d0e6c..701e2d263 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -8,8 +8,7 @@ services: working_dir: /usr/src/app volumes: - .:/usr/src/app:cached - - node_modules:/usr/src/app/node_modules - - docs_node_modules:/usr/src/app/docs/node_modules + - pnpm-store:/pnpm environment: CHOKIDAR_USEPOLLING: "true" CHOKIDAR_INTERVAL: "100" @@ -21,5 +20,4 @@ services: tty: true volumes: - node_modules: - docs_node_modules: + pnpm-store: diff --git a/docs/.gitignore b/docs/.gitignore index b083ed4f9..c19fd9bae 100644 --- a/docs/.gitignore +++ b/docs/.gitignore @@ -1,5 +1,7 @@ # Dependencies /node_modules +static/docs/internal/**/api/* +!static/docs/internal/**/api/.gitkeep # Production /build @@ -19,3 +21,7 @@ npm-debug.log* yarn-debug.log* yarn-error.log* + +# Auto-generated API docs +docs/js/api/ +static/js/api.json diff --git a/docs/LICENSE b/docs/LICENSE new file mode 100644 index 000000000..d6f45c602 --- /dev/null +++ b/docs/LICENSE @@ -0,0 +1,663 @@ +Note: This project also contains MIT-licensed files (core packages, scripts, libraries). See top-level LICENSE file for details. + + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/docs/docs/introduction/code-of-conduct.md b/docs/docs/contributing/code-of-conduct.md similarity index 99% rename from docs/docs/introduction/code-of-conduct.md rename to docs/docs/contributing/code-of-conduct.md index 71d8ca06d..41f3285e8 100644 --- a/docs/docs/introduction/code-of-conduct.md +++ b/docs/docs/contributing/code-of-conduct.md @@ -1,6 +1,5 @@ --- title: Code of Conduct -sidebar_position: 3 --- ## Our Pledge diff --git a/docs/docs/introduction/img/docker-desktop-homepage.jpg b/docs/docs/contributing/img/docker-desktop-homepage.jpg similarity index 100% rename from docs/docs/introduction/img/docker-desktop-homepage.jpg rename to docs/docs/contributing/img/docker-desktop-homepage.jpg diff --git a/docs/docs/introduction/img/docker-desktop-resources-button-location.jpg b/docs/docs/contributing/img/docker-desktop-resources-button-location.jpg similarity index 100% rename from docs/docs/introduction/img/docker-desktop-resources-button-location.jpg rename to docs/docs/contributing/img/docker-desktop-resources-button-location.jpg diff --git a/docs/docs/introduction/img/docker-desktop-settings-button-location.jpg b/docs/docs/contributing/img/docker-desktop-settings-button-location.jpg similarity index 100% rename from docs/docs/introduction/img/docker-desktop-settings-button-location.jpg rename to docs/docs/contributing/img/docker-desktop-settings-button-location.jpg diff --git a/docs/docs/introduction/img/docker-desktop-wsl-integration-button-location.jpg b/docs/docs/contributing/img/docker-desktop-wsl-integration-button-location.jpg similarity index 100% rename from docs/docs/introduction/img/docker-desktop-wsl-integration-button-location.jpg rename to docs/docs/contributing/img/docker-desktop-wsl-integration-button-location.jpg diff --git a/docs/docs/introduction/img/docker-desktop-wsl-integration-setup.jpg b/docs/docs/contributing/img/docker-desktop-wsl-integration-setup.jpg similarity index 100% rename from docs/docs/introduction/img/docker-desktop-wsl-integration-setup.jpg rename to docs/docs/contributing/img/docker-desktop-wsl-integration-setup.jpg diff --git a/docs/docs/introduction/contributing.md b/docs/docs/contributing/index.md similarity index 81% rename from docs/docs/introduction/contributing.md rename to docs/docs/contributing/index.md index e1e981198..30938fbb4 100644 --- a/docs/docs/introduction/contributing.md +++ b/docs/docs/contributing/index.md @@ -1,7 +1,7 @@ --- id: contributing title: Contributing -sidebar_position: 4 +sidebar_position: 998 --- # Contributing to Img2Num @@ -50,6 +50,6 @@ When a claim expires: ## Development Setup -The [Getting Started](../getting-started) section shows how to clone and run the application for the first time. +The [Setup & Dependencies](../internal/setup-and-dependencies) section shows how to clone and run the application for the first time. -The [Project Scripts](../../reference/tools/scripts/overview) section shows all of the available scripts you may find useful whilst working on Img2Num's source code as well as a helpful way to find specific scripts if you have forgotten one. +The [scripts](../internal/scripts) section shows all of the available scripts you may find useful whilst working on Img2Num's source code as well as a helpful way to find specific scripts if you have forgotten one. diff --git a/docs/docs/index.md b/docs/docs/index.md index c3f828ace..16c3ae46e 100644 --- a/docs/docs/index.md +++ b/docs/docs/index.md @@ -6,26 +6,27 @@ sidebar_position: 1 # Welcome to Img2Num! 🦔 -Img2Num is a lightweight, high-performance C++ library (compiled to WebAssembly) for converting images to numeric representations with ease and speed. +Img2Num is a lightweight, high-performance library for converting raster images to to SVGs with ease and speed. Whether you're a beginner or an advanced user, you'll find everything you need here to get started and master Img2Num. ## Getting Started -Follow the [installation guide](./introduction/getting-started.md) to set up Img2Num quickly. +Follow the relevant installation guide from the following: -## Quick Links +- [JavaScript](./js) -- [Overview](./introduction/getting-started.md) – Project introduction and setup -- [Changelog](/changelog) – Track releases and updates +## Changelog + +Our [changelog](/changelog) is quite empty right now since we haven't had our first release yet, but it is coming soon! --- We hope you enjoy using **Img2Num**! -For issues or contributions, visit our +For issues or contributions, see our [contributors guide](./contributing) or visit our [GitHub repository](https://github.com/Ryan-Millard/Img2Num/issues?q=is%3Aissue%20state%3Aopen%20label%3A%22good%20first%20issue%22). -:::important +:::note If you spot something wrong in the documentation or elsewhere, please help the community by opening an issue for it! Issue links: diff --git a/docs/docs/internal/bindings/_category_.json b/docs/docs/internal/bindings/_category_.json new file mode 100644 index 000000000..3956317d8 --- /dev/null +++ b/docs/docs/internal/bindings/_category_.json @@ -0,0 +1,9 @@ +{ + "label": "bindings", + "link": { + "type": "generated-index", + "title": "C++ Bindings for supported languages & runtimes", + "description": "Documentation for all C++ bindings in Img2Num. This covers how the core library is ported into different langauges.", + "slug": "/internal/bindings" + } +} diff --git a/docs/docs/internal/bindings/js/api-reference.md b/docs/docs/internal/bindings/js/api-reference.md new file mode 100644 index 000000000..cf95c7f4c --- /dev/null +++ b/docs/docs/internal/bindings/js/api-reference.md @@ -0,0 +1,34 @@ +--- +title: C++ API Reference +description: > + This page provides a full-page view of the internal C++ API reference + generated by Doxygen. Use the fullscreen button to expand the view + for easier navigation and code browsing. +--- + +import React from 'react'; +import FullscreenWrapper from '@site/src/components/FullscreenWrapper'; + + +