diff --git a/.github/actions/rive-build/action.yml b/.github/actions/rive-build/action.yml new file mode 100644 index 00000000..5b593137 --- /dev/null +++ b/.github/actions/rive-build/action.yml @@ -0,0 +1,164 @@ +name: Rive Build and Commit +description: Clone Rive runtime, build for a platform, optionally upload artifact, and commit changes + +inputs: + platform: + description: Target platform (e.g., x86_64-linux, arm64-macos, arm64-android, ...) + required: true + rive_repo_url: + description: Rive runtime repo URL + required: true + default: https://github.com/rive-app/rive-runtime.git + rive_ref: + description: Rive runtime ref (branch/tag) + required: false + default: "" + rive_sha: + description: Rive runtime commit SHA (overrides ref) + required: false + default: "" + upload_artifact: + description: Upload tarball artifact + required: true + default: "false" + commit_message: + description: Optional commit message suffix + required: false + default: "" + push_changes: + description: Push changes back to the same branch + required: true + default: "true" + +runs: + using: composite + steps: + - name: Clone Rive runtime and set RIVE_ROOT + shell: bash + run: | + set -euo pipefail + RIVE_TMP_DIR=$(mktemp -d) + echo "RIVE_ROOT=${RIVE_TMP_DIR}" >> "$GITHUB_ENV" + url="${{ inputs.rive_repo_url }}" + ref="${{ inputs.rive_ref }}" + sha="${{ inputs.rive_sha }}" + echo "Cloning Rive runtime from: ${url}" + if [ -n "$sha" ]; then + git -c core.autocrlf=false -c core.eol=lf clone --depth 1 "$url" "$RIVE_TMP_DIR" + (cd "$RIVE_TMP_DIR" && git fetch --depth 1 origin "$sha" && git checkout -f "$sha") + elif [ -n "$ref" ]; then + git -c core.autocrlf=false -c core.eol=lf clone --depth 1 --branch "$ref" "$url" "$RIVE_TMP_DIR" + else + git -c core.autocrlf=false -c core.eol=lf clone --depth 1 "$url" "$RIVE_TMP_DIR" + fi + # Double-check repo config to avoid CRLF breaking patch apply + (cd "$RIVE_TMP_DIR" && git config core.autocrlf false && git config core.eol lf) + echo "RIVE_ROOT set to: $RIVE_TMP_DIR" + + - name: Ensure clean Rive repo + shell: bash + run: | + set -euo pipefail + if [ -d "${RIVE_ROOT}/.git" ]; then + cd "${RIVE_ROOT}" + if [ -n "$(git status --porcelain)" ]; then + echo "Pending changes detected; resetting Rive repo" + git reset --hard + else + echo "Rive repo is clean" + fi + fi + + - name: Show context + shell: bash + run: | + echo "Branch: ${GITHUB_REF_NAME:-unknown}" + echo "RIVE_ROOT: ${RIVE_ROOT:-not-set}" + echo "Platform: ${{ inputs.platform }}" + git --version + git status + + - name: Build Rive runtime + shell: bash + env: + INPUT_PLATFORM: ${{ inputs.platform }} + run: | + set -euo pipefail + platform="$INPUT_PLATFORM" + echo "Running: ./utils/build_rive_runtime.sh ${platform} ${RIVE_ROOT}" + bash utils/build_rive_runtime.sh "${platform}" "${RIVE_ROOT}" + + - name: Pack artifacts (optional) + if: ${{ inputs.upload_artifact == 'true' }} + shell: bash + run: | + set -euo pipefail + paths=() + [ -d defold-rive/lib ] && paths+=(defold-rive/lib) + [ -d defold-rive/include ] && paths+=(defold-rive/include) + if [ ${#paths[@]} -eq 0 ]; then + echo "No artifact directories found (defold-rive/lib, defold-rive/include)." + exit 0 + fi + echo "Packing: ${paths[*]}" + tar -czf "branch-artifacts-${GITHUB_REF_NAME}.tgz" "${paths[@]}" + + - name: Upload artifact (optional) + if: ${{ inputs.upload_artifact == 'true' }} + uses: actions/upload-artifact@v4 + with: + name: branch-artifacts-${{ github.ref_name }} + path: branch-artifacts-${{ github.ref_name }}.tgz + if-no-files-found: ignore + + - name: Commit and push changes (optional) + if: ${{ inputs.push_changes == 'true' }} + shell: bash + env: + COMMIT_SUFFIX: ${{ inputs.commit_message }} + run: | + set -euo pipefail + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + add_paths=() + [ -d defold-rive/lib ] && add_paths+=(defold-rive/lib) + [ -d defold-rive/include ] && add_paths+=(defold-rive/include) + if [ ${#add_paths[@]} -gt 0 ]; then + git add -v "${add_paths[@]}" || true + fi + if git diff --cached --quiet; then + echo "No changes to commit." + exit 0 + fi + msg="ci: update artifacts on ${GITHUB_REF_NAME} [skip ci]" + if [ -n "${COMMIT_SUFFIX}" ]; then + msg="$msg - ${COMMIT_SUFFIX}" + fi + git commit -m "$msg" + max_attempts=3 + attempt=1 + until [ $attempt -gt $max_attempts ]; do + echo "Attempt $attempt: rebase + push" + if git pull --rebase origin "${GITHUB_REF_NAME}"; then + if git push origin HEAD:"${GITHUB_REF_NAME}"; then + echo "Push succeeded" + break + fi + else + echo "Rebase failed; aborting and retrying" + git rebase --abort || true + fi + attempt=$((attempt+1)) + sleep $((attempt*2)) + done + if [ $attempt -gt $max_attempts ]; then + echo "Push failed after $max_attempts attempts" + exit 1 + fi + + - name: Post-commit status + if: ${{ always() }} + shell: bash + run: | + git --no-pager log -1 --oneline || true + git status || true diff --git a/.github/workflows/bob.yml b/.github/workflows/bob.yml index 2b6a4b31..3788cece 100644 --- a/.github/workflows/bob.yml +++ b/.github/workflows/bob.yml @@ -19,5 +19,4 @@ jobs: needs: check_shared_dependencies uses: defold/github-actions-common/.github/workflows/bob.yml@master with: - ignored_platforms: '[{"platform": "armv7-android"}]' - + ignored_platforms: '[{"platform": "armv7-android"}, {"platform": "x86-win32"}]' diff --git a/.github/workflows/branch-artifacts.yml b/.github/workflows/branch-artifacts.yml new file mode 100644 index 00000000..ed155d7f --- /dev/null +++ b/.github/workflows/branch-artifacts.yml @@ -0,0 +1,705 @@ +name: Branch Scripts and Artifacts + +on: + workflow_dispatch: + inputs: + platform: + description: "Target platform for Rive build" + required: true + type: choice + options: ["x86_64-linux", "arm64-macos", "x86_64-macos", "arm64-ios", "x86_64-ios", "arm64-android", "armv7-android", "js-web", "wasm-web", "wasm_pthread-web", "x86-win32", "x86_64-win32", "all"] + default: "x86_64-linux" + rive_repo_url: + description: "Rive runtime repo URL (HTTPS)" + required: true + default: "https://github.com/rive-app/rive-runtime.git" + rive_ref: + description: "Rive runtime ref (branch/tag/commit). Leave empty for default." + required: false + default: "" + rive_sha: + description: "Rive runtime commit SHA to checkout (overrides rive_ref)" + required: false + default: "" + upload_artifact: + description: "Upload tarball artifact (defold-rive/lib + include)" + required: true + type: choice + options: ["true", "false"] + default: "false" + commit_message: + description: "Optional commit message suffix" + required: false + default: "" + push_changes: + description: "Push changes back to the same branch" + required: true + type: choice + options: ["true", "false"] + default: "true" + defold_version: + description: "Defold SDK version (defaults to latest stable)" + required: false + default: "latest" + +permissions: + contents: write + +concurrency: + group: branch-artifacts-${{ github.ref_name }} + cancel-in-progress: false + +jobs: + build-linux: + if: ${{ github.event.inputs.platform == 'x86_64-linux' || github.event.inputs.platform == 'all' }} + runs-on: ubuntu-22.04 + strategy: + matrix: + platform: ${{ fromJSON(github.event.inputs.platform == 'all' && '["x86_64-linux"]' || format('["{0}"]', github.event.inputs.platform)) }} + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Install Linux build dependencies (uuid, X11, Xcursor, Xrandr, Xi, Xinerama, Xf86VidMode) + shell: bash + run: | + set -euo pipefail + sudo apt-get update + sudo apt-get install -y uuid-dev libx11-dev libxcursor-dev libxrandr-dev libxi-dev libxinerama-dev libxxf86vm-dev + + - name: Setup LLVM/Clang 17 + uses: KyleMayes/install-llvm-action@v2 + with: + version: 17.0.6 + directory: ${{ runner.temp }}/llvm + + - name: Verify Clang version + shell: bash + run: | + set -euo pipefail + which clang || true + which clang++ || true + clang --version + clang++ --version + + - name: Build, (optionally) upload, and commit + uses: ./.github/actions/rive-build + with: + platform: ${{ matrix.platform }} + rive_repo_url: ${{ github.event.inputs.rive_repo_url }} + rive_ref: ${{ github.event.inputs.rive_ref }} + rive_sha: ${{ github.event.inputs.rive_sha }} + upload_artifact: ${{ github.event.inputs.upload_artifact }} + commit_message: ${{ github.event.inputs.commit_message }} + push_changes: ${{ github.event.inputs.push_changes }} + + build-macos: + if: ${{ github.event.inputs.platform == 'arm64-macos' || github.event.inputs.platform == 'x86_64-macos' || github.event.inputs.platform == 'arm64-ios' || github.event.inputs.platform == 'x86_64-ios' || github.event.inputs.platform == 'all' }} + runs-on: macos-latest + strategy: + matrix: + platform: ${{ fromJSON(github.event.inputs.platform == 'all' && '["arm64-macos","x86_64-macos","arm64-ios","x86_64-ios"]' || format('["{0}"]', github.event.inputs.platform)) }} + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Select Xcode 16.2 + uses: maxim-lobanov/setup-xcode@v1 + with: + xcode-version: '16.2' + + - name: Install tree + shell: bash + run: | + set -euo pipefail + brew install tree + + - name: Build, (optionally) upload, and commit + uses: ./.github/actions/rive-build + with: + platform: ${{ matrix.platform }} + rive_repo_url: ${{ github.event.inputs.rive_repo_url }} + rive_ref: ${{ github.event.inputs.rive_ref }} + rive_sha: ${{ github.event.inputs.rive_sha }} + upload_artifact: ${{ github.event.inputs.upload_artifact }} + commit_message: ${{ github.event.inputs.commit_message }} + push_changes: ${{ github.event.inputs.push_changes }} + + build-android: + if: ${{ github.event.inputs.platform == 'arm64-android' || github.event.inputs.platform == 'armv7-android' || github.event.inputs.platform == 'all' }} + runs-on: macos-latest + strategy: + matrix: + platform: ${{ fromJSON(github.event.inputs.platform == 'all' && '["arm64-android","armv7-android"]' || format('["{0}"]', github.event.inputs.platform)) }} + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Set up Java + uses: actions/setup-java@v4 + with: + distribution: 'temurin' + java-version: '25' + + - name: Set up Android SDK + uses: android-actions/setup-android@v3 + + - name: Install tree + shell: bash + run: | + set -euo pipefail + brew install tree + + - name: Set up Android NDK r25c (25.2.9519653) + id: setup-ndk + uses: nttld/setup-ndk@v1 + with: + ndk-version: r25c + - name: Export ANDROID_NDK env + shell: bash + run: | + echo "ANDROID_NDK=${{ steps.setup-ndk.outputs.ndk-path }}" >> "$GITHUB_ENV" + echo "Using ANDROID_NDK=${{ steps.setup-ndk.outputs.ndk-path }}" + + - name: Configure Android toolchain environment + shell: bash + run: | + set -euo pipefail + echo "ANDROID_NDK_HOME=${ANDROID_NDK}" >> "$GITHUB_ENV" + echo "NDK_PATH=${ANDROID_NDK}" >> "$GITHUB_ENV" + # API 21 is a safe default for arm64 and armv7 toolchains + echo "ANDROID_API=21" >> "$GITHUB_ENV" + - name: Build, (optionally) upload, and commit + uses: ./.github/actions/rive-build + with: + platform: ${{ matrix.platform }} + rive_repo_url: ${{ github.event.inputs.rive_repo_url }} + rive_ref: ${{ github.event.inputs.rive_ref }} + rive_sha: ${{ github.event.inputs.rive_sha }} + upload_artifact: ${{ github.event.inputs.upload_artifact }} + commit_message: ${{ github.event.inputs.commit_message }} + push_changes: ${{ github.event.inputs.push_changes }} + + build-web: + if: ${{ github.event.inputs.platform == 'js-web' || github.event.inputs.platform == 'wasm-web' || github.event.inputs.platform == 'wasm_pthread-web' || github.event.inputs.platform == 'all' }} + runs-on: ubuntu-latest + strategy: + matrix: + platform: ${{ fromJSON(github.event.inputs.platform == 'all' && '["js-web","wasm-web","wasm_pthread-web"]' || format('["{0}"]', github.event.inputs.platform)) }} + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Install Linux dependencies (uuid, glslangValidator, spirv-tools) + shell: bash + run: | + set -euo pipefail + sudo apt-get update + sudo apt-get install -y uuid-dev glslang-tools + sudo apt-get install -y tree + sudo apt-get install -y spirv-tools + + - name: Verify spirv-tools + shell: bash + run: | + set -euo pipefail + spirv-opt --version + + - name: Build, (optionally) upload, and commit + uses: ./.github/actions/rive-build + with: + platform: ${{ matrix.platform }} + rive_repo_url: ${{ github.event.inputs.rive_repo_url }} + rive_ref: ${{ github.event.inputs.rive_ref }} + rive_sha: ${{ github.event.inputs.rive_sha }} + upload_artifact: ${{ github.event.inputs.upload_artifact }} + commit_message: ${{ github.event.inputs.commit_message }} + push_changes: ${{ github.event.inputs.push_changes }} + + # build-windows: + # if: ${{ github.event.inputs.platform == 'x86-win32' || github.event.inputs.platform == 'x86_64-win32' || github.event.inputs.platform == 'all' }} + # runs-on: windows-2022 + # strategy: + # matrix: + # platform: ${{ fromJSON(github.event.inputs.platform == 'all' && '["x86_64-win32"]' || format('["{0}"]', github.event.inputs.platform)) }} + # steps: + # - name: Checkout repository + # uses: actions/checkout@v4 + # with: + # fetch-depth: 0 + + # - name: Install tree + # shell: pwsh + # run: | + # choco install tree -y || true + # tree --version + + # - name: Setup VS DevCmd (x64) + # if: ${{ matrix.platform == 'x86_64-win32' }} + # uses: ilammy/msvc-dev-cmd@v1 + # with: + # arch: x64 + # vsversion: 2022 + # toolset: 14.20 + # sdk: 10.0.22621.0 + + # - name: Setup VS DevCmd (x86) + # if: ${{ matrix.platform == 'x86-win32' }} + # uses: ilammy/msvc-dev-cmd@v1 + # with: + # arch: x86 + # vsversion: 2022 + # toolset: 14.20 + # sdk: 10.0.22621.0 + + # - name: MSBuild sanity check + # shell: pwsh + # run: | + # msbuild -version + # Get-Command msbuild.exe | Format-List -Property Source + + # - name: Install DirectX Shader Compiler (DXC) + # shell: bash + # run: | + # set -euo pipefail + # choco install directxshadercompiler -y || true + # # Verify availability if installed + # dxc.exe -version 2> NUL || true + + # - name: Build, (optionally) upload, and commit + # uses: ./.github/actions/rive-build + # with: + # platform: ${{ matrix.platform }} + # rive_repo_url: ${{ github.event.inputs.rive_repo_url }} + # rive_ref: ${{ github.event.inputs.rive_ref }} + # rive_sha: ${{ github.event.inputs.rive_sha }} + # upload_artifact: ${{ github.event.inputs.upload_artifact }} + # commit_message: ${{ github.event.inputs.commit_message }} + # push_changes: ${{ github.event.inputs.push_changes }} + + + build-windows: + if: ${{ github.event.inputs.platform == 'x86-win32' || github.event.inputs.platform == 'x86_64-win32' || github.event.inputs.platform == 'all' }} + runs-on: ubuntu-22.04 + strategy: + matrix: + platform: ${{ fromJSON(github.event.inputs.platform == 'all' && '["x86_64-win32"]' || format('["{0}"]', github.event.inputs.platform)) }} + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Install Linux build tools + shell: bash + run: | + set -euo pipefail + sudo apt-get update + sudo apt-get install -y tree wget python3-ply + tree --version + + - name: Clone Rive runtime + shell: bash + run: | + set -euo pipefail + RIVE_TMP_DIR=$(mktemp -d) + git clone --depth 1 "${{ github.event.inputs.rive_repo_url }}" "$RIVE_TMP_DIR" + if [ -n "${{ github.event.inputs.rive_sha }}" ]; then + (cd "$RIVE_TMP_DIR" && git fetch --depth 1 origin "${{ github.event.inputs.rive_sha }}" && git checkout --force "${{ github.event.inputs.rive_sha }}") + elif [ -n "${{ github.event.inputs.rive_ref }}" ]; then + (cd "$RIVE_TMP_DIR" && git fetch --depth 1 origin "${{ github.event.inputs.rive_ref }}" && git checkout --force "${{ github.event.inputs.rive_ref }}") + fi + echo "RIVE_TMP_DIR=$RIVE_TMP_DIR" >> "$GITHUB_ENV" + - name: Setup Temurin Java 21 + uses: actions/setup-java@v4 + with: + distribution: 'temurin' + java-version: '21' + + - name: Verify Java + shell: bash + run: | + set -euo pipefail + java --version + + - name: Download Defold SDK + shell: bash + run: | + set -euo pipefail + mkdir -p ./build + DOWNLOADDIR=$(realpath ./build) + echo "DOWNLOADDIR=${DOWNLOADDIR}" >> "$GITHUB_ENV" + ./utils/plugin/download_defoldsdk.sh --channel stable --version "${{ github.event.inputs.defold_version }}" --bob-only --output-sdk "${DOWNLOADDIR}/defoldsdk" + echo "Verifying bob.jar" + ls -la ./bob.jar + + - name: Verify Bob + shell: bash + run: | + set -euo pipefail + java -jar ./bob.jar -version + + - name: Build libraries + shell: bash + run: | + set -euo pipefail + BOB=./bob.jar ./utils/build_pls.sh --rive "$RIVE_TMP_DIR" "${{ matrix.platform }}" + + - name: Commit native libs + if: ${{ github.event.inputs.push_changes == 'true' }} + shell: bash + run: | + set -euo pipefail + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + PLATFORM_DIR="defold-rive/lib/${{ matrix.platform }}" + git add -v "$PLATFORM_DIR" || true + if git diff --cached --quiet; then + echo "No native lib changes to commit." + exit 0 + fi + msg="ci: update native libs (${{ matrix.platform }}) on ${{ github.ref_name }} [skip ci]" + if [ -n "${{ github.event.inputs.commit_message }}" ]; then + msg="$msg - ${{ github.event.inputs.commit_message }}" + fi + git commit -m "$msg" + max_attempts=3 + attempt=1 + until [ $attempt -gt $max_attempts ]; do + echo "Attempt $attempt: rebase + push" + if git pull --rebase origin "${{ github.ref_name }}"; then + if git push origin HEAD:"${{ github.ref_name }}"; then + echo "Push succeeded" + break + fi + else + echo "Rebase failed; aborting and retrying" + git rebase --abort || true + fi + attempt=$((attempt+1)) + sleep $((attempt*2)) + done + if [ $attempt -gt $max_attempts ]; then + echo "Push failed after $max_attempts attempts" + exit 1 + fi + + build-plugin-macos: + if: ${{ github.event.inputs.platform == 'arm64-macos' || github.event.inputs.platform == 'x86_64-macos' || github.event.inputs.platform == 'all' }} + needs: build-macos + runs-on: macos-latest + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Setup Temurin Java 21 + uses: actions/setup-java@v4 + with: + distribution: 'temurin' + java-version: '21' + + - name: Verify Java + shell: bash + run: | + set -euo pipefail + java --version + + - name: Setup CMake 4.1 + uses: lukka/get-cmake@v4.1.1 + + - name: Verify CMake + shell: bash + run: | + set -euo pipefail + cmake --version + + - name: Install jq + shell: bash + run: | + set -euo pipefail + brew update + brew install jq + brew install tree + + - name: Download Defold SDK + shell: bash + run: | + set -euo pipefail + mkdir -p ./build + DOWNLOADDIR=$(realpath ./build) + echo "DOWNLOADDIR=${DOWNLOADDIR}" >> "$GITHUB_ENV" + ./utils/plugin/download_defoldsdk.sh --channel stable --version "${{ github.event.inputs.defold_version }}" --output-sdk "${DOWNLOADDIR}/defoldsdk" + echo "Verifying bin dir: ${DOWNLOADDIR}/defoldsdk" + find ${DOWNLOADDIR}/defoldsdk -iname "protoc*" + + - name: Build editor plugins + shell: bash + env: + DYNAMO_HOME: ${{ env.DOWNLOADDIR }}/defoldsdk/defoldsdk + BOB: ${{ github.workspace }}/bob.jar + run: | + set -euo pipefail + ./utils/build_plugin.sh arm64-macos + ./utils/build_plugin.sh x86_64-macos + + - name: Commit plugin outputs + if: ${{ github.event.inputs.push_changes == 'true' }} + shell: bash + run: | + set -euo pipefail + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + CONFLICT_FILE="defold-rive/plugins/share/pluginRiveExt.jar" + if git ls-files -u "$CONFLICT_FILE" >/dev/null 2>&1; then + git checkout --ours "$CONFLICT_FILE" + fi + git add -v defold-rive/plugins || true + if git diff --cached --quiet; then + echo "No plugin changes to commit." + exit 0 + fi + msg="ci: update editor plugin on ${{ github.ref_name }} [skip ci]" + if [ -n "${{ github.event.inputs.commit_message }}" ]; then + msg="$msg - ${{ github.event.inputs.commit_message }}" + fi + git commit -m "$msg" + max_attempts=3 + attempt=1 + until [ $attempt -gt $max_attempts ]; do + echo "Attempt $attempt: rebase + push" + if git pull --rebase origin "${{ github.ref_name }}"; then + if git push origin HEAD:"${{ github.ref_name }}"; then + echo "Push succeeded" + break + fi + else + echo "Rebase failed; aborting and retrying" + git rebase --abort || true + fi + attempt=$((attempt+1)) + sleep $((attempt*2)) + done + if [ $attempt -gt $max_attempts ]; then + echo "Push failed after $max_attempts attempts" + exit 1 + fi + + build-plugin-linux: + if: ${{ github.event.inputs.platform == 'x86_64-linux' || github.event.inputs.platform == 'all' }} + needs: build-linux + runs-on: ubuntu-22.04 + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Setup Temurin Java 21 + uses: actions/setup-java@v4 + with: + distribution: 'temurin' + java-version: '21' + + - name: Verify Java + shell: bash + run: | + set -euo pipefail + java --version + + - name: Setup CMake 4.1 + uses: lukka/get-cmake@v4.1.1 + + - name: Verify CMake + shell: bash + run: | + set -euo pipefail + cmake --version + + - name: Setup LLVM/Clang 17 + uses: KyleMayes/install-llvm-action@v2 + with: + version: 17.0.6 + directory: ${{ runner.temp }}/llvm + + - name: Verify Clang version + shell: bash + run: | + set -euo pipefail + which clang || true + which clang++ || true + clang --version + clang++ --version + + - name: Install jq + shell: bash + run: | + set -euo pipefail + sudo apt-get update + sudo apt-get install -y jq + sudo apt-get install -y tree + + - name: Download Defold SDK + shell: bash + run: | + set -euo pipefail + mkdir -p ./build + DOWNLOADDIR=$(realpath ./build) + echo "DOWNLOADDIR=${DOWNLOADDIR}" >> "$GITHUB_ENV" + ./utils/plugin/download_defoldsdk.sh --channel stable --version "${{ github.event.inputs.defold_version }}" --output-sdk "${DOWNLOADDIR}/defoldsdk" + + - name: Build linux plugin + shell: bash + env: + DYNAMO_HOME: ${{ env.DOWNLOADDIR }}/defoldsdk/defoldsdk + BOB: ${{ github.workspace }}/bob.jar + run: | + set -euo pipefail + ./utils/build_plugin.sh x86_64-linux + + - name: Commit linux plugin outputs + if: ${{ github.event.inputs.push_changes == 'true' }} + shell: bash + run: | + set -euo pipefail + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + CONFLICT_FILE="defold-rive/plugins/share/pluginRiveExt.jar" + if git ls-files -u "$CONFLICT_FILE" >/dev/null 2>&1; then + git checkout --ours "$CONFLICT_FILE" + fi + git add -v defold-rive/plugins || true + if git diff --cached --quiet; then + echo "No plugin changes to commit." + exit 0 + fi + msg="ci: update linux plugin on ${{ github.ref_name }} [skip ci]" + if [ -n "${{ github.event.inputs.commit_message }}" ]; then + msg="$msg - ${{ github.event.inputs.commit_message }}" + fi + git commit -m "$msg" + max_attempts=3 + attempt=1 + until [ $attempt -gt $max_attempts ]; do + echo "Attempt $attempt: rebase + push" + if git pull --rebase origin "${{ github.ref_name }}"; then + if git push origin HEAD:"${{ github.ref_name }}"; then + echo "Push succeeded" + break + fi + else + echo "Rebase failed; aborting and retrying" + git rebase --abort || true + fi + attempt=$((attempt+1)) + sleep $((attempt*2)) + done + if [ $attempt -gt $max_attempts ]; then + echo "Push failed after $max_attempts attempts" + exit 1 + fi + + build-plugin-windows: + if: ${{ github.event.inputs.platform == 'x86_64-win32' || github.event.inputs.platform == 'all' }} + needs: build-windows + runs-on: windows-2022 + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Setup Temurin Java 21 + uses: actions/setup-java@v4 + with: + distribution: 'temurin' + java-version: '21' + + - name: Verify Java + shell: pwsh + run: | + java --version + + - name: Setup CMake 4.1 + uses: lukka/get-cmake@v4.1.1 + + - name: Verify CMake + shell: pwsh + run: | + cmake --version + + - name: Install jq and tree + shell: pwsh + run: | + choco install jq tree -y || true + jq --version + tree --version + + - name: Download Defold SDK + shell: bash + run: | + set -euo pipefail + mkdir -p ./build + DOWNLOADDIR=$(realpath ./build) + echo "DOWNLOADDIR=${DOWNLOADDIR}" >> "$GITHUB_ENV" + ./utils/plugin/download_defoldsdk.sh --channel stable --version "${{ github.event.inputs.defold_version }}" --output-sdk "${DOWNLOADDIR}/defoldsdk" + + - name: Build windows plugin + shell: bash + env: + DYNAMO_HOME: ${{ env.DOWNLOADDIR }}/defoldsdk/defoldsdk + BOB: ${{ github.workspace }}/bob.jar + run: | + set -euo pipefail + ./utils/build_plugin.sh x86_64-win32 + + - name: Commit windows plugin outputs + if: ${{ github.event.inputs.push_changes == 'true' }} + shell: bash + run: | + set -euo pipefail + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + CONFLICT_FILE="defold-rive/plugins/share/pluginRiveExt.jar" + if git ls-files -u "$CONFLICT_FILE" >/dev/null 2>&1; then + git checkout --ours "$CONFLICT_FILE" + fi + git add -v defold-rive/plugins || true + if git diff --cached --quiet; then + echo "No plugin changes to commit." + exit 0 + fi + msg="ci: update windows plugin on ${{ github.ref_name }} [skip ci]" + if [ -n "${{ github.event.inputs.commit_message }}" ]; then + msg="$msg - ${{ github.event.inputs.commit_message }}" + fi + git commit -m "$msg" + max_attempts=3 + attempt=1 + until [ $attempt -gt $max_attempts ]; do + echo "Attempt $attempt: rebase + push" + if git pull --rebase origin "${{ github.ref_name }}"; then + if git push origin HEAD:"${{ github.ref_name }}"; then + echo "Push succeeded" + break + fi + else + echo "Rebase failed; aborting and retrying" + git rebase --abort || true + fi + attempt=$((attempt+1)) + sleep $((attempt*2)) + done + if [ $attempt -gt $max_attempts ]; then + echo "Push failed after $max_attempts attempts" + exit 1 + fi diff --git a/.gitignore b/.gitignore index 73d40f42..a981531d 100644 --- a/.gitignore +++ b/.gitignore @@ -8,12 +8,7 @@ Thumbs.db .project .cproject builtins -/utils/build -/utils/rive-cpp/build -/utils/rive-cpp/rive-cpp* -/utils/rive-cpp/earcut* -/utils/rive-cpp/libtess2* -/utils/rive-cpp/*.zip +/utils/**/build /bundle* bob.jar /defold-rive/lib/**/ext.settings diff --git a/README.md b/README.md index abe0362a..e2225482 100644 --- a/README.md +++ b/README.md @@ -9,3 +9,10 @@ Defold [native extension](https://www.defold.com/manuals/extensions/) for intera # Platform support All platforms are supported except WebGL1, Android with armv7 and consoles. WebGL2 and arm64 for Android are supported however. + + +# Credits + +* https://rive.app/marketplace/14447-40690-game-achievement-badge-data-binding/ (CC-BY 4.0) + + * By https://rive.app/@setyosn/ diff --git a/assets/rive/404.riv b/assets/rive/404.riv deleted file mode 100644 index c7a33a13..00000000 Binary files a/assets/rive/404.riv and /dev/null differ diff --git a/assets/rive/clipped_circle_star_2.riv b/assets/rive/clipped_circle_star_2.riv deleted file mode 100644 index 41726400..00000000 Binary files a/assets/rive/clipped_circle_star_2.riv and /dev/null differ diff --git a/assets/rive/control.riv b/assets/rive/control.riv deleted file mode 100644 index 3f7b0443..00000000 Binary files a/assets/rive/control.riv and /dev/null differ diff --git a/assets/rive/juice.riv b/assets/rive/juice.riv deleted file mode 100644 index 5df55e4e..00000000 Binary files a/assets/rive/juice.riv and /dev/null differ diff --git a/assets/rive/marty.riv b/assets/rive/marty.riv deleted file mode 100644 index abc309f3..00000000 Binary files a/assets/rive/marty.riv and /dev/null differ diff --git a/assets/rive/marty_v2.riv b/assets/rive/marty_v2.riv deleted file mode 100644 index 774fee69..00000000 Binary files a/assets/rive/marty_v2.riv and /dev/null differ diff --git a/assets/rive/off_road_car.riv b/assets/rive/off_road_car.riv deleted file mode 100644 index 81202cb8..00000000 Binary files a/assets/rive/off_road_car.riv and /dev/null differ diff --git a/assets/rive/polygon_party.riv b/assets/rive/polygon_party.riv deleted file mode 100644 index 04c51487..00000000 Binary files a/assets/rive/polygon_party.riv and /dev/null differ diff --git a/assets/rive/rotate_square.riv b/assets/rive/rotate_square.riv deleted file mode 100644 index eba670a2..00000000 Binary files a/assets/rive/rotate_square.riv and /dev/null differ diff --git a/assets/rive/runner.riv b/assets/rive/runner.riv deleted file mode 100644 index b6a0febd..00000000 Binary files a/assets/rive/runner.riv and /dev/null differ diff --git a/assets/rive/runner_boy.riv b/assets/rive/runner_boy.riv deleted file mode 100644 index f4b37806..00000000 Binary files a/assets/rive/runner_boy.riv and /dev/null differ diff --git a/assets/rive/simple_stroke_only.riv b/assets/rive/simple_stroke_only.riv deleted file mode 100644 index 8fc84f14..00000000 Binary files a/assets/rive/simple_stroke_only.riv and /dev/null differ diff --git a/assets/rive/zombie_leg.riv b/assets/rive/zombie_leg.riv deleted file mode 100644 index 5df4bdfd..00000000 Binary files a/assets/rive/zombie_leg.riv and /dev/null differ diff --git a/defold-rive/api/rive.lua b/defold-rive/api/rive.lua new file mode 100644 index 00000000..0336029f --- /dev/null +++ b/defold-rive/api/rive.lua @@ -0,0 +1,464 @@ +-- Auto generated from utils/update_script_api.py +-- WARNING: Do not edit manually. + +--[[ +Rive API documentation +Functions and constants for interacting with Rive models +--]] + +---@meta +---@diagnostic disable: lowercase-global +---@diagnostic disable: missing-return +---@diagnostic disable: duplicate-doc-param +---@diagnostic disable: duplicate-set-field +---@diagnostic disable: args-after-dots + +---@alias ArtboardHandle integer +---@alias AudioSourceHandle integer +---@alias FileHandle integer +---@alias FontHandle integer +---@alias RenderImageHandle integer +---@alias StateMachineHandle integer +---@alias ViewModelInstanceHandle integer + +--- @class rive +rive = {} + +--- Lua wrapper for pointer movement. +---@param url url Component receiving the pointer move. +---@param x number Pointer x coordinate in component space. +---@param y number Pointer y coordinate in component space. +function rive.pointer_move(url, x, y) end + +--- Lua wrapper for pointer up events. +---@param url url Component receiving the pointer release. +---@param x number Pointer x coordinate. +---@param y number Pointer y coordinate. +function rive.pointer_up(url, x, y) end + +--- Lua wrapper for pointer down events. +---@param url url Component receiving the pointer press. +---@param x number Pointer x coordinate. +---@param y number Pointer y coordinate. +function rive.pointer_down(url, x, y) end + +--- Lua wrapper for pointer exit events. +---@param url url Component receiving the pointer leave. +---@param x number Pointer x coordinate. +---@param y number Pointer y coordinate. +function rive.pointer_exit(url, x, y) end + +--- Returns the projection matrix in render coordinates. +---@return vmath.matrix4 matrix Current projection matrix for the window. +function rive.get_projection_matrix() end + +--- Sets or clears the global file listener callback. +---@param callback? fun(self, event, data) Callback invoked for file system events; pass nil to disable. +---@param callback_self object The calling script instance. +---@param callback_event string One of: onFileLoaded, onFileDeleted, onFileError, onArtboardsListed, onViewModelsListed, onViewModelInstanceNamesListed, onViewModelPropertiesListed, onViewModelEnumsListed +---@param callback_data table Additional fields vary by event. Common keys include: +---@param callback_data_file FileHandle File handle involved in the event. +---@param callback_data_viewModelName string View model name for the request, when applicable. +---@param callback_data_instanceNames table Array of instance name strings. +---@param callback_data_artboardNames table Array of artboard name strings. +---@param callback_data_properties table Array of property metadata tables. +---@param callback_data_enums table Array of enum definitions. +---@param callback_data_error string Error message when a failure occurs. +function rive.set_file_listener(callback) end + +--- Sets or clears the artboard listener callback. +---@param callback? fun(self, event, data) Callback invoked for artboard-related events; pass nil to disable. +---@param callback_self object The calling script instance. +---@param callback_event string One of: onArtboardError, onDefaultViewModelInfoReceived, onArtboardDeleted, onStateMachinesListed +---@param callback_data table Additional data per event, typically: +---@param callback_data_artboard ArtboardHandle Artboard handle involved. +---@param callback_data_viewModelName string View model name for defaults (received event). +---@param callback_data_instanceName string Instance name for defaults. +---@param callback_data_stateMachineNames table Array of state machine name strings. +---@param callback_data_error string Error message when an error event fires. +function rive.set_artboard_listener(callback) end + +--- Sets or clears the state machine listener callback. +---@param callback? fun(self, event, data) Callback invoked for state machine events; pass nil to disable. +---@param callback_self object The calling script instance. +---@param callback_event string One of: onStateMachineError, onStateMachineDeleted, onStateMachineSettled +---@param callback_data table Event-specific details: +---@param callback_data_stateMachine StateMachineHandle Active state machine handle. +---@param callback_data_error string Error message when an error occurs. +function rive.set_state_machine_listener(callback) end + +--- Sets or clears the view model instance listener callback. +---@param callback? fun(self, event, data) Callback invoked for view model instance events; pass nil to disable. +---@param callback_self object The calling script instance. +---@param callback_event string One of: onViewModelInstanceError, onViewModelDeleted, onViewModelDataReceived, onViewModelListSizeReceived +---@param callback_data table Additional payload per event: +---@param callback_data_viewModel ViewModelInstanceHandle Handle of the affected view model instance. +---@param callback_data_error string Error description when an error fires. +---@param callback_data_path string Path being inspected when list size arrives. +---@param callback_data_size number List size value for list-size events. +function rive.set_view_model_instance_listener(callback) end + +--- Sets or clears the render image listener callback. +---@param callback? fun(self, event, data) Callback invoked for render image events; pass nil to disable. +---@param callback_self object The calling script instance. +---@param callback_event string One of: onRenderImageDecoded, onRenderImageError, onRenderImageDeleted +---@param callback_data table Additional fields: +---@param callback_data_renderImage RenderImageHandle Handle of the render image. +---@param callback_data_error string Error message for the failure event. +function rive.set_render_image_listener(callback) end + +--- Sets or clears the audio source listener callback. +---@param callback? fun(self, event, data) Callback invoked for audio source events; pass nil to disable. +---@param callback_self object The calling script instance. +---@param callback_event string One of: onAudioSourceDecoded, onAudioSourceError, onAudioSourceDeleted +---@param callback_data table Additional fields: +---@param callback_data_audioSource AudioSourceHandle Audio source handle for the event. +---@param callback_data_error string Error message when provided. +function rive.set_audio_source_listener(callback) end + +--- Sets or clears the font listener callback. +---@param callback? fun(self, event, data) Callback invoked for font events; pass nil to disable. +---@param callback_self object The calling script instance. +---@param callback_event string One of: onFontDecoded, onFontError, onFontDeleted +---@param callback_data table Additional fields: +---@param callback_data_font FontHandle Font handle for the associated event. +---@param callback_data_error string Error message for failure events. +function rive.set_font_listener(callback) end + +--- Returns the Rive file handle tied to the component. +---@param url url Component whose file handle to query. +---@return FileHandle file_handle Handle identifying the loaded Rive file. +function rive.get_file(url) end + +--- Switches the active artboard for the component. +---@param url url Component using the artboard. +---@param name? string Name of the artboard to create and set. Pass nil to create a default artboard. +---@return ArtboardHandle artboard Old artboard handle +function rive.set_artboard(url, name) end + +--- Queries the current artboard handle for the component. +---@param url url Component whose artboard handle to return. +---@return ArtboardHandle artboard Active artboard handle. +function rive.get_artboard(url) end + +--- Selects a state machine by name on the component. +---@param url url Component owning the state machine. +---@param name? string Name of the state machine to create and set. Pass nil to create a default state machine. +---@return StateMachineHandle state_machine Old state machine handle +function rive.set_state_machine(url, name) end + +--- Returns the active state machine handle for the component. +---@param url url Component whose active state machine to query. +---@return StateMachineHandle state_machine Current state machine handle. +function rive.get_state_machine(url) end + +--- Selects a view model instance by name. +---@param url url Component owning the view model instance. +---@param name string View model instance name to activate. +---@return boolean success True if the view model instance was activated. +function rive.set_view_model_instance(url, name) end + +--- Returns the handle of the currently bound view model instance. +---@param url url Component whose view model instance handle to query. +---@return ViewModelInstanceHandle view_model_instance_handle Handle for the active view model instance. +function rive.get_view_model_instance(url) end + +--- @class rive.cmd +rive.cmd = {} + +--- Returns the artboard handle created for the named view model. +---@param file_handle FileHandle Handle to a previously loaded Rive file. +---@param viewmodel_name string Name of the view model to instantiate. +---@return ArtboardHandle artboard_handle Artboard handle created for the named view model. +function rive.cmd.instantiateArtboardNamed(file_handle, viewmodel_name) end + +--- Returns the default artboard handle for the file. +---@param file_handle FileHandle Handle to a previously loaded Rive file. +---@return ArtboardHandle artboard_handle Default artboard handle for the file. +function rive.cmd.instantiateDefaultArtboard(file_handle) end + +--- Returns a blank view model instance handle for the given artboard or view model. +---@param file_handle FileHandle Handle to a previously loaded Rive file. +---@param artboard_or_viewmodel ArtboardHandle|string Artboard handle or view model name that identifies where to instantiate. +---@return ViewModelInstanceHandle view_model_instance_handle Blank view model instance handle. +function rive.cmd.instantiateBlankViewModelInstance(file_handle, artboard_or_viewmodel) end + +--- Returns a default-populated view model instance handle for the given artboard or view model. +---@param file_handle FileHandle Handle to a previously loaded Rive file. +---@param artboard_or_viewmodel ArtboardHandle|string Artboard handle or view model name the instance should derive from. +---@return ViewModelInstanceHandle view_model_instance_handle Default view model instance handle. +function rive.cmd.instantiateDefaultViewModelInstance(file_handle, artboard_or_viewmodel) end + +--- Creates a named view model instance and returns its handle. +---@param file_handle FileHandle Handle to a previously loaded Rive file. +---@param artboard_or_viewmodel ArtboardHandle|string Artboard handle or view model name that will host the instance. +---@param instance_name string Name to assign to the new view model instance. +---@return ViewModelInstanceHandle view_model_instance_handle Named view model instance handle. +function rive.cmd.instantiateViewModelInstanceNamed(file_handle, artboard_or_viewmodel, instance_name) end + +--- Returns a handle to the nested view model at the given path. +---@param view_model_handle ViewModelInstanceHandle Parent view model instance handle. +---@param path string Dot-delimited path to the nested view model. +---@return ViewModelInstanceHandle view_model_handle Handle to the nested view model. +function rive.cmd.referenceNestedViewModelInstance(view_model_handle, path) end + +--- Returns the handle for the list entry at the specified path and index. +---@param view_model_handle ViewModelInstanceHandle Parent view model instance handle. +---@param path string Dot-delimited path to the list view model. +---@param index number Index within the list entry to reference. +---@return ViewModelInstanceHandle view_model_handle Handle to the referenced list entry. +function rive.cmd.referenceListViewModelInstance(view_model_handle, path, index) end + +--- Deletes an instantiated artboard. +---@param artboard_handle ArtboardHandle Handle to the artboard that should be removed. +function rive.cmd.deleteArtboard(artboard_handle) end + +--- Creates a named state machine for the provided artboard. +---@param artboard_handle ArtboardHandle Artboard where the state machine resides. +---@param name string Name to assign to the new state machine. +---@return StateMachineHandle state_machine_handle Handle referencing the created state machine. +function rive.cmd.instantiateStateMachineNamed(artboard_handle, name) end + +--- Creates the default state machine for an artboard. +---@param artboard_handle ArtboardHandle Artboard used as the source for the state machine. +---@return StateMachineHandle state_machine_handle Handle referencing the created state machine. +function rive.cmd.instantiateDefaultStateMachine(artboard_handle) end + +--- Advances the state machine by the requested delta time. +---@param state_machine_handle StateMachineHandle State machine to advance. +---@param delta number Time in seconds to advance the state machine. +function rive.cmd.advanceStateMachine(state_machine_handle, delta) end + +--- Deletes a created state machine. +---@param state_machine_handle StateMachineHandle Handle to the state machine to delete. +function rive.cmd.deleteStateMachine(state_machine_handle) end + +--- Replaces the nested view model at the given path with the supplied handle. +---@param view_model_handle ViewModelInstanceHandle View model instance whose nested child is updated. +---@param path string Path to the nested view model. +---@param nested_handle ViewModelInstanceHandle Handle of the nested view model to attach. +function rive.cmd.setViewModelInstanceNestedViewModel(view_model_handle, path, nested_handle) end + +--- Inserts a nested view model into the list at the given index. +---@param view_model_handle ViewModelInstanceHandle View model instance owning the list. +---@param path string Path to the target list. +---@param nested_handle ViewModelInstanceHandle Handle of the view model to insert. +---@param index number Destination index for the insertion. +function rive.cmd.insertViewModelInstanceListViewModel(view_model_handle, path, nested_handle, index) end + +--- Appends a nested view model to the list at the specified path. +---@param view_model_handle ViewModelInstanceHandle View model instance owning the list. +---@param path string Path to the target list. +---@param nested_handle ViewModelInstanceHandle Handle of the view model to append. +function rive.cmd.appendViewModelInstanceListViewModel(view_model_handle, path, nested_handle) end + +--- Swaps two entries in the nested list. +---@param view_model_handle ViewModelInstanceHandle View model instance that owns the list. +---@param path string Path to the nested list. +---@param indexa number First index to swap. +---@param indexb number Second index to swap. +function rive.cmd.swapViewModelInstanceListValues(view_model_handle, path, indexa, indexb) end + +--- Removes the entry at the supplied index from the nested list. +---@param view_model_handle ViewModelInstanceHandle View model instance owning the list. +---@param path string Path to the target list. +---@param index number Index of the entry to remove. +function rive.cmd.removeViewModelInstanceListViewModelIndex(view_model_handle, path, index) end + +--- Removes the specified nested view model from the list at the path. +---@param view_model_handle ViewModelInstanceHandle View model instance owning the list. +---@param path string Path to the target list. +---@param nested_handle ViewModelInstanceHandle Handle of the view model to remove. +function rive.cmd.removeViewModelInstanceListViewModel(view_model_handle, path, nested_handle) end + +--- Binds the state machine to the provided view model instance. +---@param state_machine_handle StateMachineHandle State machine handle. +---@param view_model_handle ViewModelInstanceHandle View model instance handle. +function rive.cmd.bindViewModelInstance(state_machine_handle, view_model_handle) end + +--- Deletes the view model instance handle. +---@param view_model_handle ViewModelInstanceHandle View model instance to delete. +function rive.cmd.deleteViewModelInstance(view_model_handle) end + +--- Fires a trigger on the view model instance. +---@param view_model_handle ViewModelInstanceHandle View model instance handle. +---@param trigger_path string Trigger path to activate. +function rive.cmd.fireViewModelTrigger(view_model_handle, trigger_path) end + +--- Updates the boolean property at the path. +---@param view_model_handle ViewModelInstanceHandle View model instance handle. +---@param path string Path to the boolean property. +---@param value boolean New boolean value. +function rive.cmd.setViewModelInstanceBool(view_model_handle, path, value) end + +--- Updates the numeric property at the path. +---@param view_model_handle ViewModelInstanceHandle View model instance handle. +---@param path string Path to the numeric property. +---@param value number New numeric value. +function rive.cmd.setViewModelInstanceNumber(view_model_handle, path, value) end + +--- Updates the color property using the supplied vector. +---@param view_model_handle ViewModelInstanceHandle View model instance handle. +---@param path string Path to the color property. +---@param vector4_color vector4 Color encoded as a Defold Vector4 (WXYZ). +function rive.cmd.setViewModelInstanceColor(view_model_handle, path, vector4_color) end + +--- Updates the enum property at the path. +---@param view_model_handle ViewModelInstanceHandle View model instance handle. +---@param path string Path to the enum property. +---@param enum_string string Enum name to select. +function rive.cmd.setViewModelInstanceEnum(view_model_handle, path, enum_string) end + +--- Updates the string property at the path. +---@param view_model_handle ViewModelInstanceHandle View model instance handle. +---@param path string Path to the string property. +---@param string_value string New string value. +function rive.cmd.setViewModelInstanceString(view_model_handle, path, string_value) end + +--- Updates the image property at the path. +---@param view_model_handle ViewModelInstanceHandle View model instance handle. +---@param path string Path to the image property. +---@param render_image_handle RenderImageHandle Render image handle to assign. +function rive.cmd.setViewModelInstanceImage(view_model_handle, path, render_image_handle) end + +--- Updates the artboard reference at the path. +---@param view_model_handle ViewModelInstanceHandle View model instance handle. +---@param path string Path to the artboard reference. +---@param artboard_handle ArtboardHandle Artboard handle to assign. +function rive.cmd.setViewModelInstanceArtboard(view_model_handle, path, artboard_handle) end + +--- Subscribes for updates to the named property. +---@param view_model_handle ViewModelInstanceHandle View model instance handle. +---@param path string Path to the property to subscribe. +---@param data_type enum Data type identifier from rive::DataType. +function rive.cmd.subscribeToViewModelProperty(view_model_handle, path, data_type) end + +--- Cancels a previous subscription. +---@param view_model_handle ViewModelInstanceHandle View model instance handle. +---@param path string Path to the property. +---@param data_type enum Data type identifier previously subscribed. +function rive.cmd.unsubscribeToViewModelProperty(view_model_handle, path, data_type) end + +--- Loads Rive bytes and returns a file handle. +---@param riv_bytes string Raw Rive file data. +---@return FileHandle file_handle Loaded Rive file handle. +function rive.cmd.loadFile(riv_bytes) end + +--- Deletes the runtime file handle. +---@param file_handle FileHandle File handle to delete. +function rive.cmd.deleteFile(file_handle) end + +--- Decodes image bytes and returns a render image handle. +---@param image_bytes string Encoded image data. +---@return RenderImageHandle render_image_handle Decoded render image handle. +function rive.cmd.decodeImage(image_bytes) end + +--- Deletes the render image handle. +---@param image_handle RenderImageHandle Render image handle to delete. +function rive.cmd.deleteImage(image_handle) end + +--- Decodes audio bytes and returns an audio source handle. +---@param audio_bytes string Encoded audio data. +---@return AudioSourceHandle audio_handle Decoded audio source handle. +function rive.cmd.decodeAudio(audio_bytes) end + +--- Deletes the audio source handle. +---@param audio_handle AudioSourceHandle Audio source handle to delete. +function rive.cmd.deleteAudio(audio_handle) end + +--- Decodes font bytes and returns a font handle. +---@param font_bytes string Encoded font data. +---@return FontHandle font_handle Decoded font handle. +function rive.cmd.decodeFont(font_bytes) end + +--- Deletes the font handle. +---@param font_handle FontHandle Font handle to delete. +function rive.cmd.deleteFont(font_handle) end + +--- Registers a global image asset. +---@param asset_name string Name used to reference the global asset. +---@param render_image_handle RenderImageHandle Render image handle to register. +function rive.cmd.addGlobalImageAsset(asset_name, render_image_handle) end + +--- Unregisters the named global image asset. +---@param asset_name string Name of the asset to remove. +function rive.cmd.removeGlobalImageAsset(asset_name) end + +--- Registers a global audio asset. +---@param asset_name string Name used to reference the global audio. +---@param audio_handle AudioSourceHandle Audio source handle to register. +function rive.cmd.addGlobalAudioAsset(asset_name, audio_handle) end + +--- Unregisters the named global audio asset. +---@param asset_name string Name of the audio asset to remove. +function rive.cmd.removeGlobalAudioAsset(asset_name) end + +--- Registers a global font asset. +---@param asset_name string Name used to reference the global font. +---@param font_handle FontHandle Font handle to register. +function rive.cmd.addGlobalFontAsset(asset_name, font_handle) end + +--- Unregisters the named global font asset. +---@param asset_name string Name of the font asset to remove. +function rive.cmd.removeGlobalFontAsset(asset_name) end + +--- Requests view model names for the file. +---@param file_handle FileHandle File handle whose view models to query. +function rive.cmd.requestViewModelNames(file_handle) end + +--- Requests artboard names for the file. +---@param file_handle FileHandle File handle whose artboards to query. +function rive.cmd.requestArtboardNames(file_handle) end + +--- Requests enum definitions for the file. +---@param file_handle FileHandle File handle whose enums to query. +function rive.cmd.requestViewModelEnums(file_handle) end + +--- Requests property definitions for the view model. +---@param file_handle FileHandle File handle whose view models to query. +---@param viewmodel_name string View model name whose property metadata to request. +function rive.cmd.requestViewModelPropertyDefinitions(file_handle, viewmodel_name) end + +--- Requests instance names for the view model. +---@param file_handle FileHandle File handle whose view models to query. +---@param viewmodel_name string View model name to inspect. +function rive.cmd.requestViewModelInstanceNames(file_handle, viewmodel_name) end + +--- Requests the boolean value for the property. +---@param instance_handle ViewModelInstanceHandle View model instance handle. +---@param property_name string Name of the bool property. +function rive.cmd.requestViewModelInstanceBool(instance_handle, property_name) end + +--- Requests the numeric value for the property. +---@param instance_handle ViewModelInstanceHandle View model instance handle. +---@param property_name string Name of the numeric property. +function rive.cmd.requestViewModelInstanceNumber(instance_handle, property_name) end + +--- Requests the color value for the property. +---@param instance_handle ViewModelInstanceHandle View model instance handle. +---@param property_name string Name of the color property. +function rive.cmd.requestViewModelInstanceColor(instance_handle, property_name) end + +--- Requests the enum value for the property. +---@param instance_handle ViewModelInstanceHandle View model instance handle. +---@param property_name string Name of the enum property. +function rive.cmd.requestViewModelInstanceEnum(instance_handle, property_name) end + +--- Requests the string value for the property. +---@param instance_handle ViewModelInstanceHandle View model instance handle. +---@param property_name string Name of the string property. +function rive.cmd.requestViewModelInstanceString(instance_handle, property_name) end + +--- Requests the list size for the property. +---@param instance_handle ViewModelInstanceHandle View model instance handle. +---@param property_name string Name of the list property. +function rive.cmd.requestViewModelInstanceListSize(instance_handle, property_name) end + +--- Requests state machine names for the artboard. +---@param artboard_handle ArtboardHandle Artboard handle to query. +function rive.cmd.requestStateMachineNames(artboard_handle) end + +--- Requests metadata about the default view model or artboard. +---@param artboard_handle ArtboardHandle Artboard handle to query. +---@param file_handle FileHandle File handle providing metadata. +function rive.cmd.requestDefaultViewModelInfo(artboard_handle, file_handle) end diff --git a/defold-rive/api/rive.script_api b/defold-rive/api/rive.script_api index 1f6abdc2..89881b0d 100644 --- a/defold-rive/api/rive.script_api +++ b/defold-rive/api/rive.script_api @@ -1,474 +1,1199 @@ - name: rive type: table - desc: Functions and constants for interacting with Rive models + desc: Rive animation helpers exposed to Lua scripts members: - - name: play_anim + - name: pointer_move type: function - desc: Plays the specified animation on a Rive model + desc: Lua wrapper for pointer movement. + parameters: + - name: url + type: url + desc: Component receiving the pointer move. + - name: x + type: number + desc: Pointer x coordinate in component space. + - name: y + type: number + desc: Pointer y coordinate in component space. + +#***************************************************************************************************** + - name: pointer_up + type: function + desc: Lua wrapper for pointer up events. parameters: - name: url type: url - desc: The Rive model component for which to play an animation + desc: Component receiving the pointer release. + - name: x + type: number + desc: Pointer x coordinate. + - name: y + type: number + desc: Pointer y coordinate. - - name: anim_id - type: hash - desc: Id of the animation to play +#***************************************************************************************************** - - name: playback + - name: pointer_down + type: function + desc: Lua wrapper for pointer down events. + parameters: + - name: url + type: url + desc: Component receiving the pointer press. + - name: x + type: number + desc: Pointer x coordinate. + - name: y type: number - desc: Playback mode of the animation (from go.PLAYBACK_*) + desc: Pointer y coordinate. - - name: options - type: table - desc: Playback options - parameters: - - name: offset - type: number - desc: The normalized initial value of the animation cursor when the animation starts playing +#***************************************************************************************************** - - name: playback_rate - type: constant - desc: The rate with which the animation will be played. Must be positive. + - name: pointer_exit + type: function + desc: Lua wrapper for pointer exit events. + parameters: + - name: url + type: url + desc: Component receiving the pointer leave. + - name: x + type: number + desc: Pointer x coordinate. + - name: y + type: number + desc: Pointer y coordinate. + +#***************************************************************************************************** + + - name: get_projection_matrix + type: function + desc: Returns the projection matrix in render coordinates. + return: + - name: matrix + type: vmath.matrix4 + desc: Current projection matrix for the window. + +#***************************************************************************************************** - - name: complete_function - type: function - desc: function to call when the animation has completed + - name: set_file_listener + type: function + desc: Sets or clears the global file listener callback. + parameters: + - name: callback + type: function(self, event, data)|nil + desc: Callback invoked for file system events; pass nil to disable. parameters: - name: self type: object - desc: The context of the calling script + desc: The calling script instance. + - name: event + type: string + desc: "One of: onFileLoaded, onFileDeleted, onFileError, onArtboardsListed, onViewModelsListed, onViewModelInstanceNamesListed, onViewModelPropertiesListed, onViewModelEnumsListed" + - name: data + type: table + desc: Additional fields vary by event. Common keys include + parameters: + - name: file + type: FileHandle + desc: File handle involved in the event. + - name: viewModelName + type: string + desc: View model name for the request, when applicable. + - name: instanceNames + type: table + desc: Array of instance name strings. + - name: artboardNames + type: table + desc: Array of artboard name strings. + - name: properties + type: table + desc: Array of property metadata tables. + - name: enums + type: table + desc: Array of enum definitions. + - name: error + type: string + desc: Error message when a failure occurs. - - name: message_id - type: hash - desc: The name of the completion message ("rive_animation_done") +#***************************************************************************************************** - - name: message + - name: set_artboard_listener + type: function + desc: Sets or clears the artboard listener callback. + parameters: + - name: callback + type: function(self, event, data)|nil + desc: Callback invoked for artboard-related events; pass nil to disable. + parameters: + - name: self + type: object + desc: The calling script instance. + - name: event + type: string + desc: "One of: onArtboardError, onDefaultViewModelInfoReceived, onArtboardDeleted, onStateMachinesListed" + - name: data type: table - desc: A table that contains the response + desc: Additional data per event, typically parameters: - - name: animation_id - type: hash - desc: the animation that was completed + - name: artboard + type: ArtboardHandle + desc: Artboard handle involved. + - name: viewModelName + type: string + desc: View model name for defaults (received event). + - name: instanceName + type: string + desc: Instance name for defaults. + - name: stateMachineNames + type: table + desc: Array of state machine name strings. + - name: error + type: string + desc: Error message when an error event fires. - - name: playback - type: constant - desc: the playback mode for the animation +#***************************************************************************************************** - - name: sender - type: url - desc: The invoker of the callback - the Rive model component + - name: set_state_machine_listener + type: function + desc: Sets or clears the state machine listener callback. + parameters: + - name: callback + type: function(self, event, data)|nil + desc: Callback invoked for state machine events; pass nil to disable. + parameters: + - name: self + type: object + desc: The calling script instance. + - name: event + type: string + desc: "One of: onStateMachineError, onStateMachineDeleted, onStateMachineSettled" + - name: data + type: table + desc: Event-specific details + parameters: + - name: stateMachine + type: StateMachineHandle + desc: Active state machine handle. + - name: error + type: string + desc: Error message when an error occurs. #***************************************************************************************************** - - name: play_state_machine + - name: set_view_model_instance_listener type: function - desc: Plays the specified animation on a Rive model - + desc: Sets or clears the view model instance listener callback. parameters: - - name: url - type: url - desc: The Rive model component for which to play an animation + - name: callback + type: function(self, event, data)|nil + desc: Callback invoked for view model instance events; pass nil to disable. + parameters: + - name: self + type: object + desc: The calling script instance. + - name: event + type: string + desc: "One of: onViewModelInstanceError, onViewModelDeleted, onViewModelDataReceived, onViewModelListSizeReceived" + - name: data + type: table + desc: Additional payload per event + parameters: + - name: viewModel + type: ViewModelInstanceHandle + desc: Handle of the affected view model instance. + - name: error + type: string + desc: Error description when an error fires. + - name: path + type: string + desc: Path being inspected when list size arrives. + - name: size + type: number + desc: List size value for list-size events. - - name: state_machine_id - type: hash - desc: Id of the state machine to play +#***************************************************************************************************** - - name: options - type: table - desc: Playback options + - name: set_render_image_listener + type: function + desc: Sets or clears the render image listener callback. + parameters: + - name: callback + type: function(self, event, data)|nil + desc: Callback invoked for render image events; pass nil to disable. parameters: - - name: playback_rate - type: constant - desc: The rate with which the animation will be played. Must be positive. + - name: self + type: object + desc: The calling script instance. + - name: event + type: string + desc: "One of: onRenderImageDecoded, onRenderImageError, onRenderImageDeleted" + - name: data + type: table + desc: Additional fields + parameters: + - name: renderImage + type: RenderImageHandle + desc: Handle of the render image. + - name: error + type: string + desc: Error message for the failure event. + +#***************************************************************************************************** - - name: callback_function - type: function - desc: function to call when a playback event occurs + - name: set_audio_source_listener + type: function + desc: Sets or clears the audio source listener callback. + parameters: + - name: callback + type: function(self, event, data)|nil + desc: Callback invoked for audio source events; pass nil to disable. parameters: - name: self type: object - desc: The context of the calling script + desc: The calling script instance. + - name: event + type: string + desc: "One of: onAudioSourceDecoded, onAudioSourceError, onAudioSourceDeleted" + - name: data + type: table + desc: Additional fields + parameters: + - name: audioSource + type: AudioSourceHandle + desc: Audio source handle for the event. + - name: error + type: string + desc: Error message when provided. - - name: message_id - type: hash - desc: The name of the event +#***************************************************************************************************** - - name: message + - name: set_font_listener + type: function + desc: Sets or clears the font listener callback. + parameters: + - name: callback + type: function(self, event, data)|nil + desc: Callback invoked for font events; pass nil to disable. + parameters: + - name: self + type: object + desc: The calling script instance. + - name: event + type: string + desc: "One of: onFontDecoded, onFontError, onFontDeleted" + - name: data type: table - desc: A table that contains the event properties + desc: Additional fields + parameters: + - name: font + type: FontHandle + desc: Font handle for the associated event. + - name: error + type: string + desc: Error message for failure events. #***************************************************************************************************** - - name: cancel + - name: get_file type: function - desc: Cancels all running animations on a specified spine model component + desc: Returns the Rive file handle tied to the component. + parameters: + - name: url + type: url + desc: Component whose file handle to query. + return: + - name: file_handle + type: FileHandle + desc: Handle identifying the loaded Rive file. +#***************************************************************************************************** + + - name: set_artboard + type: function + desc: Switches the active artboard for the component. parameters: - name: url type: url - desc: The Rive model component for which to cancel the animation + desc: Component using the artboard. + - name: name + type: string|nil + desc: Name of the artboard to create and set. Pass nil to create a default artboard. + return: + - name: artboard + type: ArtboardHandle + desc: Old artboard handle #***************************************************************************************************** - - name: get_go + - name: get_artboard type: function - desc: Returns the id of the game object that corresponds to a specified skeleton bone. + desc: Queries the current artboard handle for the component. + parameters: + - name: url + type: url + desc: Component whose artboard handle to return. + return: + - name: artboard + type: ArtboardHandle + desc: Active artboard handle. +#***************************************************************************************************** + + - name: set_state_machine + type: function + desc: Selects a state machine by name on the component. parameters: - name: url type: url - desc: The Rive model component to query + desc: Component owning the state machine. + - name: name + type: string|nil + desc: Name of the state machine to create and set. Pass nil to create a default state machine. + return: + - name: state_machine + type: StateMachineHandle + desc: Old state machine handle - - name: bone_id - type: hash - desc: Id of the corresponding bone +#***************************************************************************************************** + - name: get_state_machine + type: function + desc: Returns the active state machine handle for the component. + parameters: + - name: url + type: url + desc: Component whose active state machine to query. return: - - name: id - type: hash - desc: Id of the game object + - name: state_machine + type: StateMachineHandle + desc: Current state machine handle. #***************************************************************************************************** - - name: pointer_move + - name: set_view_model_instance type: function - desc: Forward mouse/touch movement to a component + desc: Selects a view model instance by name. + parameters: + - name: url + type: url + desc: Component owning the view model instance. + - name: name + type: string + desc: View model instance name to activate. + return: + - name: success + type: boolean + desc: True if the view model instance was activated. +#***************************************************************************************************** + + - name: get_view_model_instance + type: function + desc: Returns the handle of the currently bound view model instance. parameters: - name: url type: url - desc: The Rive model component + desc: Component whose view model instance handle to query. + return: + - name: view_model_instance_handle + type: ViewModelInstanceHandle + desc: Handle for the active view model instance. - - name: x - type: number - desc: Horizontal position +#***************************************************************************************************** - - name: y - type: number - desc: Vertical position +- name: rive.cmd + type: table + desc: Command queue helpers for interacting with the Rive runtime + + members: + + - name: instantiateArtboardNamed + type: function + desc: Returns the artboard handle created for the named view model. + parameters: + - name: file_handle + type: FileHandle + desc: Handle to a previously loaded Rive file. + - name: viewmodel_name + type: string + desc: Name of the view model to instantiate. + return: + - name: artboard_handle + type: ArtboardHandle + desc: Artboard handle created for the named view model. #***************************************************************************************************** - - name: pointer_up + - name: instantiateDefaultArtboard type: function - desc: Forward mouse/touch release event to a component + desc: Returns the default artboard handle for the file. + parameters: + - name: file_handle + type: FileHandle + desc: Handle to a previously loaded Rive file. + return: + - name: artboard_handle + type: ArtboardHandle + desc: Default artboard handle for the file. +#***************************************************************************************************** + + - name: instantiateBlankViewModelInstance + type: function + desc: Returns a blank view model instance handle for the given artboard or view model. parameters: - - name: url - type: url - desc: The Rive model component + - name: file_handle + type: FileHandle + desc: Handle to a previously loaded Rive file. + - name: artboard_or_viewmodel + type: ArtboardHandle|string + desc: Artboard handle or view model name that identifies where to instantiate. + return: + - name: view_model_instance_handle + type: ViewModelInstanceHandle + desc: Blank view model instance handle. - - name: x - type: number - desc: Horizontal position +#***************************************************************************************************** - - name: y - type: number - desc: Vertical position + - name: instantiateDefaultViewModelInstance + type: function + desc: Returns a default-populated view model instance handle for the given artboard or view model. + parameters: + - name: file_handle + type: FileHandle + desc: Handle to a previously loaded Rive file. + - name: artboard_or_viewmodel + type: ArtboardHandle|string + desc: Artboard handle or view model name the instance should derive from. + return: + - name: view_model_instance_handle + type: ViewModelInstanceHandle + desc: Default view model instance handle. #***************************************************************************************************** - - name: pointer_down + - name: instantiateViewModelInstanceNamed type: function - desc: Forward mouse/touch press event to a component + desc: Creates a named view model instance and returns its handle. + parameters: + - name: file_handle + type: FileHandle + desc: Handle to a previously loaded Rive file. + - name: artboard_or_viewmodel + type: ArtboardHandle|string + desc: Artboard handle or view model name that will host the instance. + - name: instance_name + type: string + desc: Name to assign to the new view model instance. + return: + - name: view_model_instance_handle + type: ViewModelInstanceHandle + desc: Named view model instance handle. + +#***************************************************************************************************** + - name: referenceNestedViewModelInstance + type: function + desc: Returns a handle to the nested view model at the given path. parameters: - - name: url - type: url - desc: The Rive model component + - name: view_model_handle + type: ViewModelInstanceHandle + desc: Parent view model instance handle. + - name: path + type: string + desc: Dot-delimited path to the nested view model. + return: + - name: view_model_handle + type: ViewModelInstanceHandle + desc: Handle to the nested view model. - - name: x - type: number - desc: Horizontal position +#***************************************************************************************************** - - name: y + - name: referenceListViewModelInstance + type: function + desc: Returns the handle for the list entry at the specified path and index. + parameters: + - name: view_model_handle + type: ViewModelInstanceHandle + desc: Parent view model instance handle. + - name: path + type: string + desc: Dot-delimited path to the list view model. + - name: index type: number - desc: Vertical position + desc: Index within the list entry to reference. + return: + - name: view_model_handle + type: ViewModelInstanceHandle + desc: Handle to the referenced list entry. #***************************************************************************************************** - - name: get_text_run + - name: deleteArtboard type: function - desc: Gets the text run of a specified text component from within the Rive artboard assigned to the component. - + desc: Deletes an instantiated artboard. parameters: - - name: url - type: url - desc: The Rive model component for which to get the text run from + - name: artboard_handle + type: ArtboardHandle + desc: Handle to the artboard that should be removed. +#***************************************************************************************************** + + - name: instantiateStateMachineNamed + type: function + desc: Creates a named state machine for the provided artboard. + parameters: + - name: artboard_handle + type: ArtboardHandle + desc: Artboard where the state machine resides. - name: name type: string - desc: The name of the text run from the Rive artboard. + desc: Name to assign to the new state machine. + return: + - name: state_machine_handle + type: StateMachineHandle + desc: Handle referencing the created state machine. - - name: nested_artboard - type: string - desc: (OPTIONAL) If specified, the text run will be retrieved from the specified nested artboard +#***************************************************************************************************** + - name: instantiateDefaultStateMachine + type: function + desc: Creates the default state machine for an artboard. + parameters: + - name: artboard_handle + type: ArtboardHandle + desc: Artboard used as the source for the state machine. return: - - name: text_run + - name: state_machine_handle + type: StateMachineHandle + desc: Handle referencing the created state machine. + +#***************************************************************************************************** + + - name: advanceStateMachine + type: function + desc: Advances the state machine by the requested delta time. + parameters: + - name: state_machine_handle + type: StateMachineHandle + desc: State machine to advance. + - name: delta + type: number + desc: Time in seconds to advance the state machine. + +#***************************************************************************************************** + + - name: deleteStateMachine + type: function + desc: Deletes a created state machine. + parameters: + - name: state_machine_handle + type: StateMachineHandle + desc: Handle to the state machine to delete. + +#***************************************************************************************************** + + - name: setViewModelInstanceNestedViewModel + type: function + desc: Replaces the nested view model at the given path with the supplied handle. + parameters: + - name: view_model_handle + type: ViewModelInstanceHandle + desc: View model instance whose nested child is updated. + - name: path type: string - desc: The text run text + desc: Path to the nested view model. + - name: nested_handle + type: ViewModelInstanceHandle + desc: Handle of the nested view model to attach. #***************************************************************************************************** - - name: set_text_run + - name: insertViewModelInstanceListViewModel type: function - desc: Set the text run of a specified text component from within the Rive artboard assigned to the component. + desc: Inserts a nested view model into the list at the given index. + parameters: + - name: view_model_handle + type: ViewModelInstanceHandle + desc: View model instance owning the list. + - name: path + type: string + desc: Path to the target list. + - name: nested_handle + type: ViewModelInstanceHandle + desc: Handle of the view model to insert. + - name: index + type: number + desc: Destination index for the insertion. +#***************************************************************************************************** + + - name: appendViewModelInstanceListViewModel + type: function + desc: Appends a nested view model to the list at the specified path. parameters: - - name: url - type: url - desc: The Rive model component for which to set the text run for + - name: view_model_handle + type: ViewModelInstanceHandle + desc: View model instance owning the list. + - name: path + type: string + desc: Path to the target list. + - name: nested_handle + type: ViewModelInstanceHandle + desc: Handle of the view model to append. - - name: name +#***************************************************************************************************** + + - name: swapViewModelInstanceListValues + type: function + desc: Swaps two entries in the nested list. + parameters: + - name: view_model_handle + type: ViewModelInstanceHandle + desc: View model instance that owns the list. + - name: path type: string - desc: The name of the text run from the Rive artboard. + desc: Path to the nested list. + - name: indexa + type: number + desc: First index to swap. + - name: indexb + type: number + desc: Second index to swap. + +#***************************************************************************************************** - - name: text_run + - name: removeViewModelInstanceListViewModelIndex + type: function + desc: Removes the entry at the supplied index from the nested list. + parameters: + - name: view_model_handle + type: ViewModelInstanceHandle + desc: View model instance owning the list. + - name: path type: string - desc: The text run contents to update with. + desc: Path to the target list. + - name: index + type: number + desc: Index of the entry to remove. - - name: nested_artboard +#***************************************************************************************************** + + - name: removeViewModelInstanceListViewModel + type: function + desc: Removes the specified nested view model from the list at the path. + parameters: + - name: view_model_handle + type: ViewModelInstanceHandle + desc: View model instance owning the list. + - name: path type: string - desc: (OPTIONAL) If specified, the text run will be set in the specified nested artboard + desc: Path to the target list. + - name: nested_handle + type: ViewModelInstanceHandle + desc: Handle of the view model to remove. #***************************************************************************************************** - - name: get_projection_matrix + - name: bindViewModelInstance type: function - desc: Get an orthographic projection matrix that can be used to project regular Defold components into the same coordinate space as the rive model when using the 'fullscreen' coordinate space. + desc: Binds the state machine to the provided view model instance. + parameters: + - name: state_machine_handle + type: StateMachineHandle + desc: State machine handle. + - name: view_model_handle + type: ViewModelInstanceHandle + desc: View model instance handle. - return: - - name: matrix - type: vmath.matrix4 - desc: The projection matrix +#***************************************************************************************************** + + - name: deleteViewModelInstance + type: function + desc: Deletes the view model instance handle. + parameters: + - name: view_model_handle + type: ViewModelInstanceHandle + desc: View model instance to delete. #***************************************************************************************************** - - name: get_state_machine_input + - name: fireViewModelTrigger type: function - desc: Get the input values from a state machine input, either from the current top-level artboard, or from a nested artboard inside the Rive model artboard. Note that trigger inputs will not generate a value! + desc: Fires a trigger on the view model instance. + parameters: + - name: view_model_handle + type: ViewModelInstanceHandle + desc: View model instance handle. + - name: trigger_path + type: string + desc: Trigger path to activate. +#***************************************************************************************************** + + - name: setViewModelInstanceBool + type: function + desc: Updates the boolean property at the path. parameters: - - name: url - type: url - desc: The Rive model component + - name: view_model_handle + type: ViewModelInstanceHandle + desc: View model instance handle. + - name: path + type: string + desc: Path to the boolean property. + - name: value + type: boolean + desc: New boolean value. - - name: name +#***************************************************************************************************** + + - name: setViewModelInstanceNumber + type: function + desc: Updates the numeric property at the path. + parameters: + - name: view_model_handle + type: ViewModelInstanceHandle + desc: View model instance handle. + - name: path type: string - desc: The name of the input + desc: Path to the numeric property. + - name: value + type: number + desc: New numeric value. - - name: nested_artboard +#***************************************************************************************************** + + - name: setViewModelInstanceColor + type: function + desc: Updates the color property using the supplied vector. + parameters: + - name: view_model_handle + type: ViewModelInstanceHandle + desc: View model instance handle. + - name: path type: string - desc: (OPTIONAL) If specified, the input will be queried for the specified nested artboard + desc: Path to the color property. + - name: vector4_color + type: vector4 + desc: Color encoded as a Defold Vector4 (WXYZ). - return: - - name: value - type: number|bool - desc: The value of the input +#***************************************************************************************************** + + - name: setViewModelInstanceEnum + type: function + desc: Updates the enum property at the path. + parameters: + - name: view_model_handle + type: ViewModelInstanceHandle + desc: View model instance handle. + - name: path + type: string + desc: Path to the enum property. + - name: enum_string + type: string + desc: Enum name to select. #***************************************************************************************************** - - name: set_state_machine_input + - name: setViewModelInstanceString type: function - desc: Set the input values from a state machine input, either from the current top-level artboard, or from a nested artboard inside the Rive model artboard. Note - To set input for a trigger, use a bool value. + desc: Updates the string property at the path. + parameters: + - name: view_model_handle + type: ViewModelInstanceHandle + desc: View model instance handle. + - name: path + type: string + desc: Path to the string property. + - name: string_value + type: string + desc: New string value. + +#***************************************************************************************************** + - name: setViewModelInstanceImage + type: function + desc: Updates the image property at the path. parameters: - - name: url - type: url - desc: The Rive model component + - name: view_model_handle + type: ViewModelInstanceHandle + desc: View model instance handle. + - name: path + type: string + desc: Path to the image property. + - name: render_image_handle + type: RenderImageHandle + desc: Render image handle to assign. - - name: name +#***************************************************************************************************** + + - name: setViewModelInstanceArtboard + type: function + desc: Updates the artboard reference at the path. + parameters: + - name: view_model_handle + type: ViewModelInstanceHandle + desc: View model instance handle. + - name: path type: string - desc: The name of the input + desc: Path to the artboard reference. + - name: artboard_handle + type: ArtboardHandle + desc: Artboard handle to assign. - - name: value - type: number|bool - desc: The value of the input to set +#***************************************************************************************************** - - name: nested_artboard + - name: subscribeToViewModelProperty + type: function + desc: Subscribes for updates to the named property. + parameters: + - name: view_model_handle + type: ViewModelInstanceHandle + desc: View model instance handle. + - name: path + type: string + desc: Path to the property to subscribe. + - name: data_type + type: enum + desc: Data type identifier from rive::DataType. + +#***************************************************************************************************** + + - name: unsubscribeToViewModelProperty + type: function + desc: Cancels a previous subscription. + parameters: + - name: view_model_handle + type: ViewModelInstanceHandle + desc: View model instance handle. + - name: path type: string - desc: (OPTIONAL) If specified, the input will be queried for the specified nested artboard + desc: Path to the property. + - name: data_type + type: enum + desc: Data type identifier previously subscribed. #***************************************************************************************************** - - name: riv_swap_asset + - name: loadFile type: function - desc: Replace an asset in runtime. - Rive doc: https://rive.app/docs/game-runtimes/unreal/runtime-asset-swapping + desc: Loads Rive bytes and returns a file handle. + parameters: + - name: riv_bytes + type: string + desc: Raw Rive file data. + return: + - name: file_handle + type: FileHandle + desc: Loaded Rive file handle. +#***************************************************************************************************** + + - name: deleteFile + type: function + desc: Deletes the runtime file handle. parameters: - - name: riv_path - type: string,hash - desc: The Rive (.rivc) path. E.g. "/path/to/file.rivc" + - name: file_handle + type: FileHandle + desc: File handle to delete. - - name: asset_name +#***************************************************************************************************** + + - name: decodeImage + type: function + desc: Decodes image bytes and returns a render image handle. + parameters: + - name: image_bytes type: string - desc: The name of the FileAsset inside the .riv file + desc: Encoded image data. + return: + - name: render_image_handle + type: RenderImageHandle + desc: Decoded render image handle. - - name: options - type: table - desc: A table of options containing +#***************************************************************************************************** - members: + - name: deleteImage + type: function + desc: Deletes the render image handle. + parameters: + - name: image_handle + type: RenderImageHandle + desc: Render image handle to delete. - - name: path - type: string - desc: The path of the asset file to replace with. E.g. "/path/to/file.png" +#***************************************************************************************************** - - name: payload - type: string - desc: The payload of the asset file to replace with. E.g. a .png binary file. - Takes precedence over the `path` option. + - name: decodeAudio + type: function + desc: Decodes audio bytes and returns an audio source handle. + parameters: + - name: audio_bytes + type: string + desc: Encoded audio data. + return: + - name: audio_handle + type: AudioSourceHandle + desc: Decoded audio source handle. - - name: databind - type: table - desc: Functions and constants for interacting with Rive data bindings +#***************************************************************************************************** - members: - - name: create_view_model_instance_runtime - type: function - desc: Creates a ViewModelInstanceRuntime + - name: deleteAudio + type: function + desc: Deletes the audio source handle. + parameters: + - name: audio_handle + type: AudioSourceHandle + desc: Audio source handle to delete. - parameters: - - name: url - type: url - desc: The Rive model component +#***************************************************************************************************** - - name: name - type: string, hash - desc: The name of the view model to instantiate + - name: decodeFont + type: function + desc: Decodes font bytes and returns a font handle. + parameters: + - name: font_bytes + type: string + desc: Encoded font data. + return: + - name: font_handle + type: FontHandle + desc: Decoded font handle. - return: - - name: handle - type: integer - desc: The handle to the ViewModelInstanceRuntime instance +#***************************************************************************************************** - - name: error - type: string|nil - desc: The error message if something went wrong + - name: deleteFont + type: function + desc: Deletes the font handle. + parameters: + - name: font_handle + type: FontHandle + desc: Font handle to delete. - - name: destroy_view_model_instance_runtime - type: function - desc: Releases the previously created ViewModelInstanceRuntime +#***************************************************************************************************** - parameters: - - name: url - type: url - desc: The Rive model component + - name: addGlobalImageAsset + type: function + desc: Registers a global image asset. + parameters: + - name: asset_name + type: string + desc: Name used to reference the global asset. + - name: render_image_handle + type: RenderImageHandle + desc: Render image handle to register. - - name: handle - type: integer - desc: The handle to the ViewModelInstanceRuntime instance +#***************************************************************************************************** - - name: set_view_model_instance_runtime - type: function - desc: Sets the current ViewModelInstanceRuntime + - name: removeGlobalImageAsset + type: function + desc: Unregisters the named global image asset. + parameters: + - name: asset_name + type: string + desc: Name of the asset to remove. - parameters: - - name: url - type: url - desc: The Rive model component +#***************************************************************************************************** - - name: handle - type: integer - desc: The handle to the ViewModelInstanceRuntime instance + - name: addGlobalAudioAsset + type: function + desc: Registers a global audio asset. + parameters: + - name: asset_name + type: string + desc: Name used to reference the global audio. + - name: audio_handle + type: AudioSourceHandle + desc: Audio source handle to register. - - name: get_view_model_instance_runtime - type: function - desc: Gets the current ViewModelInstanceRuntime +#***************************************************************************************************** - parameters: - - name: url - type: url - desc: The Rive model component + - name: removeGlobalAudioAsset + type: function + desc: Unregisters the named global audio asset. + parameters: + - name: asset_name + type: string + desc: Name of the audio asset to remove. - return: - - name: handle - type: integer - desc: The handle to the currently set ViewModelInstanceRuntime instance +#***************************************************************************************************** + - name: addGlobalFontAsset + type: function + desc: Registers a global font asset. + parameters: + - name: asset_name + type: string + desc: Name used to reference the global font. + - name: font_handle + type: FontHandle + desc: Font handle to register. - - name: set_properties - type: function - desc: Sets properties to the ViewModelInstanceRuntime instance +#***************************************************************************************************** - parameters: - - name: url - type: url - desc: The Rive model component + - name: removeGlobalFontAsset + type: function + desc: Unregisters the named global font asset. + parameters: + - name: asset_name + type: string + desc: Name of the font asset to remove. - - name: handle - type: integer - desc: The handle to the ViewModelInstanceRuntime instance +#***************************************************************************************************** - - name: properties - type: table - desc: A table of properties, where each key is a Rive "path", and the values are mapped to the corresponding property value type. + - name: requestViewModelNames + type: function + desc: Requests view model names for the file. + parameters: + - name: file_handle + type: FileHandle + desc: File handle whose view models to query. - - name: get_property - type: function - desc: Gets a property from the ViewModelInstanceRuntime instance +#***************************************************************************************************** - parameters: - - name: url - type: url - desc: The Rive model component + - name: requestArtboardNames + type: function + desc: Requests artboard names for the file. + parameters: + - name: file_handle + type: FileHandle + desc: File handle whose artboards to query. - - name: handle - type: integer - desc: The handle to the ViewModelInstanceRuntime instance +#***************************************************************************************************** - - name: path - type: string - desc: The path to the property + - name: requestViewModelEnums + type: function + desc: Requests enum definitions for the file. + parameters: + - name: file_handle + type: FileHandle + desc: File handle whose enums to query. - return: - - name: result - type: string,number,vmath.vector4 - desc: The value of the selected property. Raises error if property doesn't exist. +#***************************************************************************************************** - - name: list_add_instance - type: function - desc: Add a ViewModelInstanceRuntime instance to a list property + - name: requestViewModelPropertyDefinitions + type: function + desc: Requests property definitions for the view model. + parameters: + - name: file_handle + type: FileHandle + desc: File handle whose view models to query. + - name: viewmodel_name + type: string + desc: View model name whose property metadata to request. - parameters: - - name: url - type: url - desc: The Rive model component +#***************************************************************************************************** - - name: handle - type: integer - desc: The handle to the ViewModelInstanceRuntime instance + - name: requestViewModelInstanceNames + type: function + desc: Requests instance names for the view model. + parameters: + - name: file_handle + type: FileHandle + desc: File handle whose view models to query. + - name: viewmodel_name + type: string + desc: View model name to inspect. - - name: path - type: string - desc: The path to the list property +#***************************************************************************************************** + + - name: requestViewModelInstanceBool + type: function + desc: Requests the boolean value for the property. + parameters: + - name: instance_handle + type: ViewModelInstanceHandle + desc: View model instance handle. + - name: property_name + type: string + desc: Name of the bool property. - - name: instance_handle - type: integer - desc: The handle to the ViewModelInstanceRuntime instance to add to the list +#***************************************************************************************************** - - name: list_remove_instance - type: function - desc: Remove a ViewModelInstanceRuntime instance from a list property + - name: requestViewModelInstanceNumber + type: function + desc: Requests the numeric value for the property. + parameters: + - name: instance_handle + type: ViewModelInstanceHandle + desc: View model instance handle. + - name: property_name + type: string + desc: Name of the numeric property. - parameters: - - name: url - type: url - desc: The Rive model component +#***************************************************************************************************** - - name: handle - type: integer - desc: The handle to the ViewModelInstanceRuntime instance + - name: requestViewModelInstanceColor + type: function + desc: Requests the color value for the property. + parameters: + - name: instance_handle + type: ViewModelInstanceHandle + desc: View model instance handle. + - name: property_name + type: string + desc: Name of the color property. - - name: path - type: string - desc: The path to the list property +#***************************************************************************************************** + + - name: requestViewModelInstanceEnum + type: function + desc: Requests the enum value for the property. + parameters: + - name: instance_handle + type: ViewModelInstanceHandle + desc: View model instance handle. + - name: property_name + type: string + desc: Name of the enum property. + +#***************************************************************************************************** + + - name: requestViewModelInstanceString + type: function + desc: Requests the string value for the property. + parameters: + - name: instance_handle + type: ViewModelInstanceHandle + desc: View model instance handle. + - name: property_name + type: string + desc: Name of the string property. + +#***************************************************************************************************** - - name: instance_handle - type: integer - desc: The handle to the ViewModelInstanceRuntime instance to add to the list + - name: requestViewModelInstanceListSize + type: function + desc: Requests the list size for the property. + parameters: + - name: instance_handle + type: ViewModelInstanceHandle + desc: View model instance handle. + - name: property_name + type: string + desc: Name of the list property. + +#***************************************************************************************************** + + - name: requestStateMachineNames + type: function + desc: Requests state machine names for the artboard. + parameters: + - name: artboard_handle + type: ArtboardHandle + desc: Artboard handle to query. + +#***************************************************************************************************** + + - name: requestDefaultViewModelInfo + type: function + desc: Requests metadata about the default view model or artboard. + parameters: + - name: artboard_handle + type: ArtboardHandle + desc: Artboard handle to query. + - name: file_handle + type: FileHandle + desc: File handle providing metadata. diff --git a/defold-rive/commonsrc/atlas.cpp b/defold-rive/commonsrc/atlas.cpp index 8024f680..aab1d7d5 100644 --- a/defold-rive/commonsrc/atlas.cpp +++ b/defold-rive/commonsrc/atlas.cpp @@ -237,8 +237,8 @@ namespace dmRive { } AtlasNameResolver::AtlasNameResolver(dmResource::HFactory factory, HRenderContext context) - : m_Factory(factory) - , m_RiveRenderContext(context) + : m_RiveRenderContext(context) + , m_Factory(factory) { } @@ -246,34 +246,36 @@ namespace dmRive { { DEBUGLOG("loadContents"); - if (m_Assets.Full()) - { - m_Assets.OffsetCapacity(8); - } - m_Assets.Push(&_asset); + dmLogError("MAWE TODO UNIMPLEMENTED: %s", __FUNCTION__); - bool out_of_band = inBandBytes.size() == 0; - if (_asset.is()) - { - rive::ImageAsset* asset = _asset.as(); - const std::string& name = asset->name(); + // if (m_Assets.Full()) + // { + // m_Assets.OffsetCapacity(8); + // } + // m_Assets.Push(&_asset); - rive::rcp image; + // bool out_of_band = inBandBytes.size() == 0; + // if (_asset.is()) + // { + // rive::ImageAsset* asset = _asset.as(); + // const std::string& name = asset->name(); - if (out_of_band) - { - image = LoadImageFromFactory(m_Factory, m_RiveRenderContext, name.c_str()); - } + // rive::rcp image; - if (!image) - { - image = CreateRiveRenderImage(m_RiveRenderContext, (void*) inBandBytes.data(), inBandBytes.size()); - DEBUGLOG(" In band asset: file: '%s' data: %u bytes", name.c_str(), (uint32_t)inBandBytes.size()); - } + // if (out_of_band) + // { + // image = LoadImageFromFactory(m_Factory, m_RiveRenderContext, name.c_str()); + // } - asset->renderImage(image); - return (bool)image; - } + // if (!image) + // { + // image = CreateRiveRenderImage(m_RiveRenderContext, (void*) inBandBytes.data(), inBandBytes.size()); + // DEBUGLOG(" In band asset: file: '%s' data: %u bytes", name.c_str(), (uint32_t)inBandBytes.size()); + // } + + // asset->renderImage(image); + // return (bool)image; + // } return false; } diff --git a/defold-rive/commonsrc/commands.cpp b/defold-rive/commonsrc/commands.cpp new file mode 100644 index 00000000..ed882a76 --- /dev/null +++ b/defold-rive/commonsrc/commands.cpp @@ -0,0 +1,123 @@ +// Copyright 2020-2025 The Defold Foundation +// Licensed under the Defold License version 1.0 (the "License"); you may not use +// this file except in compliance with the License. +// +// You may obtain a copy of the License, together with FAQs at +// https://www.defold.com/license +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#include + +#include +#include +#include + +#include +#include +#include + +#include +#include + + +namespace dmRiveCommands { + +struct Context +{ + dmThread::Thread m_Thread; + int32_atomic_t m_Run; + + dmRive::HRenderContext m_RenderContext; + rive::Factory* m_Factory; + rive::CommandServer* m_CommandServer; + rive::rcp m_CommandQueue; +}; + +Context* g_Context = 0; + +// static void RiveCommandThread(void* _ctx) +// { +// Context* ctx = (Context*)_ctx; + +// while (dmAtomicGet32(&g_Context->m_Run)) +// { + +// } +// } + +Result Initialize(InitParams* params) +{ + assert(g_Context == 0); + + g_Context = new Context; + memset(g_Context, 0, sizeof(*g_Context)); + + if (params->m_UseThreads) + { + // dmAtomicAdd32(&g_Context->m_Run, 1); + // g_Context->m_Thread = dmThread::New(RiveCommandThread, 1 * 1024*1024, g_Context, "RiveCommandThread"); + // if (!g_Context->m_Thread) + // { + // return RESULT_FAILED_CREATE_THREAD; + // } + } + + g_Context->m_RenderContext = params->m_RenderContext; + g_Context->m_Factory = params->m_Factory; + + g_Context->m_CommandQueue = rive::make_rcp(); + g_Context->m_CommandServer = new rive::CommandServer(g_Context->m_CommandQueue, g_Context->m_Factory); + + return RESULT_OK; +} + +Result Finalize() +{ + assert(g_Context != 0); + + if (dmAtomicGet32(&g_Context->m_Run)) + { + dmAtomicSub32(&g_Context->m_Run, 1); + dmThread::Join(g_Context->m_Thread); + g_Context->m_Thread = 0; + } + + g_Context->m_CommandQueue.reset(); + delete g_Context->m_CommandServer; + + delete g_Context; + g_Context = 0; + return RESULT_OK; +} + +rive::rcp GetCommandQueue() +{ + return g_Context->m_CommandQueue; +} + +rive::Factory* GetFactory() +{ + assert(g_Context != 0); + return g_Context->m_Factory; +} + +dmRive::HRenderContext GetDefoldRenderContext() +{ + assert(g_Context != 0); + return g_Context->m_RenderContext; +} + +Result ProcessMessages() +{ + assert(g_Context != 0); + g_Context->m_CommandServer->processCommands(); + g_Context->m_CommandQueue->processMessages(); + return RESULT_OK; +} + + +} // namespace diff --git a/defold-rive/src/private/renderer_context.h b/defold-rive/commonsrc/renderer/renderer_context.h similarity index 100% rename from defold-rive/src/private/renderer_context.h rename to defold-rive/commonsrc/renderer/renderer_context.h diff --git a/defold-rive/src/private/renderer_context_metal.mm b/defold-rive/commonsrc/renderer/renderer_context_metal.mm similarity index 100% rename from defold-rive/src/private/renderer_context_metal.mm rename to defold-rive/commonsrc/renderer/renderer_context_metal.mm diff --git a/defold-rive/src/private/renderer_context_opengl.cpp b/defold-rive/commonsrc/renderer/renderer_context_opengl.cpp similarity index 99% rename from defold-rive/src/private/renderer_context_opengl.cpp rename to defold-rive/commonsrc/renderer/renderer_context_opengl.cpp index 966d65a5..eae1079c 100644 --- a/defold-rive/src/private/renderer_context_opengl.cpp +++ b/defold-rive/commonsrc/renderer/renderer_context_opengl.cpp @@ -1,5 +1,5 @@ -#ifdef DM_RIVE_USE_OPENGL +#if defined(DM_RIVE_USE_OPENGL) && !defined(DM_HEADLESS) #if defined(RIVE_ANDROID) || defined(RIVE_WEBGL) diff --git a/defold-rive/src/private/renderer_context_webgpu.cpp b/defold-rive/commonsrc/renderer/renderer_context_webgpu.cpp similarity index 94% rename from defold-rive/src/private/renderer_context_webgpu.cpp rename to defold-rive/commonsrc/renderer/renderer_context_webgpu.cpp index 7cded07a..f1a3d602 100644 --- a/defold-rive/src/private/renderer_context_webgpu.cpp +++ b/defold-rive/commonsrc/renderer/renderer_context_webgpu.cpp @@ -3,23 +3,21 @@ #include "renderer_context.h" -#if RIVE_WEBGPU == 1 - #include - #include -#elif RIVE_WEBGPU == 2 - #include - #include -#else - #error "Unsupported value for RIVE_WEBGPU!" -#endif +#include +#include #include #include #include +#if defined(RIVE_WAGYU) && !defined(DM_GRAPHICS_WEBGPU_WAGYU) + #define DM_GRAPHICS_WEBGPU_WAGYU +#endif + #include #include #include +#include #include @@ -30,6 +28,10 @@ namespace dmRive public: DefoldRiveRendererWebGPU() { +#if defined(DM_GRAPHICS_WEBGPU_WAGYU) + // Making sure we're keeping track of the webgpu.h verssions + DM_STATIC_ASSERT(WGPUTextureFormat_RG16Snorm == 0x12, Invalid_webgpu_header); +#endif dmGraphics::HContext graphics_context = dmGraphics::GetInstalledContext(); assert(graphics_context); @@ -44,7 +46,7 @@ namespace dmRive m_Device = wgpu::Device(webgpu_device); m_Queue = wgpu::Queue(webgpu_queue); - dmLogInfo("Before creating WebGPU context. (RIVE_WEBGPU=%d)", RIVE_WEBGPU); + dmLogInfo("Before creating WebGPU context"); rive::gpu::RenderContextWebGPUImpl::ContextOptions contextOptions; m_RenderContext = rive::gpu::RenderContextWebGPUImpl::MakeContext(m_Adapter, m_Device, m_Queue, contextOptions); diff --git a/defold-rive/src/private/renderer_private.cpp b/defold-rive/commonsrc/renderer/renderer_private.cpp similarity index 97% rename from defold-rive/src/private/renderer_private.cpp rename to defold-rive/commonsrc/renderer/renderer_private.cpp index 04189771..af744558 100644 --- a/defold-rive/src/private/renderer_private.cpp +++ b/defold-rive/commonsrc/renderer/renderer_private.cpp @@ -17,6 +17,17 @@ #include + +#if defined(DM_HEADLESS) +namespace dmRive +{ + rive::rcp CreateRiveRenderImage(HRenderContext context, void* bytes, uint32_t byte_count) + { + return rive::rcp(); + } +} +#else + namespace dmResource { void IncRef(HFactory factory, void* resource); @@ -126,6 +137,7 @@ namespace dmRive } int samples = (int) params.m_DoFinalBlit ? 0 : params.m_BackbufferSamples; + (void)samples; #if defined(DM_PLATFORM_MACOS) || defined(DM_PLATFORM_IOS) if (!params.m_DoFinalBlit) @@ -136,6 +148,7 @@ namespace dmRive } #endif + renderer->m_RenderContext->BeginFrame({ .renderTargetWidth = width, .renderTargetHeight = height, @@ -274,3 +287,5 @@ namespace dmRive return viewTransform; } } + +#endif // DM_HEADLESS diff --git a/defold-rive/commonsrc/rive_ddf.proto b/defold-rive/commonsrc/rive_ddf.proto index 4908ba1e..50235255 100644 --- a/defold-rive/commonsrc/rive_ddf.proto +++ b/defold-rive/commonsrc/rive_ddf.proto @@ -57,7 +57,7 @@ message RiveModelDesc } required string scene = 1 [(resource)=true]; - required string default_animation = 2; + optional string default_animation = 2; // Deprecated optional string material = 3 [(resource)=true, default="/defold-rive/assets/rivemodel.material"]; optional BlendMode blend_mode = 4 [default = BLEND_MODE_ALPHA]; optional string default_state_machine = 5; @@ -73,42 +73,3 @@ message RiveModelDesc optional string blit_material = 13 [(resource)=true, default="/defold-rive/assets/shader-library/rivemodel_blit.material"]; } -message RivePlayAnimation -{ - required uint64 animation_id = 1; - required uint32 playback = 2; // matches dmGameObject::Playback in gameobject.h - optional float offset = 3 [default = 0.0]; - optional float playback_rate = 4 [default = 1.0]; - optional bool is_state_machine = 5 [default = false]; -} - -message RiveCancelAnimation -{ -} - -message RiveAnimationDone -{ - required uint64 animation_id = 1; - required uint32 playback = 2; // matches dmGameObject::Playback in gameobject.h -} - -message RiveEventTrigger -{ - required string name = 1; - optional float number = 2; - optional bool trigger = 3; - optional string text = 4; -} - -// Function wrapper documented in gamesys_script.cpp -message SetConstantRiveModel -{ - required uint64 name_hash = 1; - required dmMath.Vector4 value = 2; -} - -// Function wrapper documented in gamesys_script.cpp -message ResetConstantRiveModel -{ - required uint64 name_hash = 1; -} diff --git a/defold-rive/commonsrc/tess_renderer.cpp b/defold-rive/commonsrc/tess_renderer.cpp index 692e7c8b..8cc9d9fd 100644 --- a/defold-rive/commonsrc/tess_renderer.cpp +++ b/defold-rive/commonsrc/tess_renderer.cpp @@ -408,12 +408,12 @@ namespace dmRive m_Projection[15] = 1.0f; } - static void print_mat2d(const rive::Mat2D& m) - { - dmLogInfo( - "[%f,%f\n %f,%f\n %f,%f]", - m[0], m[1], m[2], m[3], m[4], m[5]); - } + // static void print_mat2d(const rive::Mat2D& m) + // { + // dmLogInfo( + // "[%f,%f\n %f,%f\n %f,%f]", + // m[0], m[1], m[2], m[3], m[4], m[5]); + // } void DefoldTessRenderer::putImage(DrawDescriptor& draw_desc, dmRive::Region* region, const rive::Mat2D& uv_transform) { @@ -491,7 +491,7 @@ namespace dmRive VsUniforms vs_params = {}; vs_params.world = transform(); - FsUniforms fs_uniforms = {0}; + FsUniforms fs_uniforms = {}; fs_uniforms.fillType = (int) FillType::FILL_TYPE_TEXTURED; fs_uniforms.colors[0][3] = opacity; @@ -528,9 +528,9 @@ namespace dmRive rive::BlendMode blendMode, float opacity) { + /* DefoldRenderImage* image = (DefoldRenderImage*)_image; - /* dmRive::Region* region = dmRive::FindAtlasRegion(m_Atlas, image->m_NameHash); if (!region) { @@ -606,8 +606,10 @@ namespace dmRive } } - VsUniforms vs_uniforms = { .fillType = 0 }; - FsUniforms fs_uniforms = {0}; + + + VsUniforms vs_uniforms; + FsUniforms fs_uniforms; // Decr any paths from the last clip that are gone. std::unordered_set alreadyApplied; diff --git a/defold-rive/commonsrc/vertices.cpp b/defold-rive/commonsrc/vertices.cpp index f6bfad3c..d181bb12 100644 --- a/defold-rive/commonsrc/vertices.cpp +++ b/defold-rive/commonsrc/vertices.cpp @@ -31,13 +31,10 @@ void ApplyDrawMode(dmRender::RenderObject& ro, dmRive::DrawMode draw_mode, uint8 stencil.m_ColorBufferMask = 0; stencil.m_SeparateFaceStates = 0; - stencil.m_Front = { - .m_Func = dmGraphics::COMPARE_FUNC_ALWAYS, - .m_OpSFail = dmGraphics::STENCIL_OP_KEEP, - .m_OpDPFail = dmGraphics::STENCIL_OP_KEEP, - .m_OpDPPass = dmGraphics::STENCIL_OP_DECR_WRAP, - }; - + stencil.m_Front.m_Func = dmGraphics::COMPARE_FUNC_ALWAYS; + stencil.m_Front.m_OpSFail = dmGraphics::STENCIL_OP_KEEP; + stencil.m_Front.m_OpDPFail = dmGraphics::STENCIL_OP_KEEP; + stencil.m_Front.m_OpDPPass = dmGraphics::STENCIL_OP_DECR_WRAP; break; case dmRive::DRAW_MODE_CLIP_INCR: stencil.m_Ref = 0x0; @@ -46,12 +43,10 @@ void ApplyDrawMode(dmRender::RenderObject& ro, dmRive::DrawMode draw_mode, uint8 stencil.m_ColorBufferMask = 0; stencil.m_SeparateFaceStates = 0; - stencil.m_Front = { - .m_Func = dmGraphics::COMPARE_FUNC_ALWAYS, - .m_OpSFail = dmGraphics::STENCIL_OP_KEEP, - .m_OpDPFail = dmGraphics::STENCIL_OP_KEEP, - .m_OpDPPass = dmGraphics::STENCIL_OP_INCR_WRAP, - }; + stencil.m_Front.m_Func = dmGraphics::COMPARE_FUNC_ALWAYS; + stencil.m_Front.m_OpSFail = dmGraphics::STENCIL_OP_KEEP; + stencil.m_Front.m_OpDPFail = dmGraphics::STENCIL_OP_KEEP; + stencil.m_Front.m_OpDPPass = dmGraphics::STENCIL_OP_INCR_WRAP; break; case dmRive::DRAW_MODE_DEFAULT: stencil.m_Ref = clipIndex; @@ -68,7 +63,6 @@ void ApplyDrawMode(dmRender::RenderObject& ro, dmRive::DrawMode draw_mode, uint8 void CopyVertices(const dmRive::DrawDescriptor& draw_desc, uint32_t vertex_offset, RiveVertex* out_vertices, uint16_t* out_indices) { uint32_t vertex_count = draw_desc.m_VerticesCount; - uint32_t tc_count = draw_desc.m_TexCoordsCount; bool has_texcoords = draw_desc.m_TexCoords != 0; for (int i = 0; i < vertex_count; ++i) diff --git a/defold-rive/include/common/commands.h b/defold-rive/include/common/commands.h new file mode 100644 index 00000000..ef9429a5 --- /dev/null +++ b/defold-rive/include/common/commands.h @@ -0,0 +1,53 @@ +// Copyright 2020-2025 The Defold Foundation +// Licensed under the Defold License version 1.0 (the "License"); you may not use +// this file except in compliance with the License. +// +// You may obtain a copy of the License, together with FAQs at +// https://www.defold.com/license +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#include + +#include +#include + +namespace rive +{ + class Factory; +} + +namespace dmRiveCommands +{ + enum Result + { + RESULT_OK = 0, + RESULT_FAILED_CREATE_THREAD = -1, + }; + + struct InitParams + { + dmRive::HRenderContext m_RenderContext; + rive::Factory* m_Factory; + bool m_UseThreads; + + InitParams() + : m_RenderContext(0) + , m_Factory(0) + , m_UseThreads(false) + {} + }; + + Result Initialize(InitParams* params); // Once per session + Result Finalize(); // Once per session + + Result ProcessMessages(); + + // Getters + rive::Factory* GetFactory(); + dmRive::HRenderContext GetDefoldRenderContext(); + rive::rcp GetCommandQueue(); +} diff --git a/defold-rive/include/defold/rive.h b/defold-rive/include/defold/rive.h new file mode 100644 index 00000000..4137975f --- /dev/null +++ b/defold-rive/include/defold/rive.h @@ -0,0 +1,27 @@ +// Copyright 2020-2025 The Defold Foundation +// Licensed under the Defold License version 1.0 (the "License"); you may not use +// this file except in compliance with the License. +// +// You may obtain a copy of the License, together with FAQs at +// https://www.defold.com/license +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#ifndef DM_RIVE_H +#define DM_RIVE_H + +#if defined(__linux__) && defined(None) + #undef None +#endif + +#include +#include + +#include +#include + + +#endif // DM_RIVE_H diff --git a/defold-rive/include/defold/rive_version.h b/defold-rive/include/defold/rive_version.h index e6b62fd1..186fd53c 100644 --- a/defold-rive/include/defold/rive_version.h +++ b/defold-rive/include/defold/rive_version.h @@ -1,9 +1,11 @@ // Generated. Do not edit! See ./build_version_header.sh -//fix(webgpu): Fix Y orientation on GL zero and nonzero FBOs (#10623) 454b0d2db1 +//Nnnnn fix memory lua issues (#11412) ba94f03ad0 +//* push scripted drawable to stack twice to ensure it is not destroyed before use +//* code improvements // -//Co-authored-by: Chris Dalton <99840794+csmartdalton@users.noreply.github.com> +//Co-authored-by: hernan -const char* RIVE_RUNTIME_AUTHOR="csmartdalton"; -const char* RIVE_RUNTIME_DATE="2025-09-19T02:18:27+00:00"; -const char* RIVE_RUNTIME_SHA1="e54883d9099f87ed6d87c678793fd619b5594e2c"; +const char* RIVE_RUNTIME_AUTHOR="bodymovin"; +const char* RIVE_RUNTIME_DATE="2026-01-09T07:54:52Z"; +const char* RIVE_RUNTIME_SHA1="3a5b5058aca009b823154ed7f92c11d599c00ae3"; diff --git a/defold-rive/include/rive/advancing_component.hpp b/defold-rive/include/rive/advancing_component.hpp index 7f9dd9f9..dc04653f 100644 --- a/defold-rive/include/rive/advancing_component.hpp +++ b/defold-rive/include/rive/advancing_component.hpp @@ -13,7 +13,7 @@ class AdvancingComponent float elapsedSeconds, AdvanceFlags flags = AdvanceFlags::Animate | AdvanceFlags::NewFrame) = 0; - static AdvancingComponent* from(Component* component); + static AdvancingComponent* from(Core* component); }; } // namespace rive diff --git a/defold-rive/include/rive/animation/blend_animation_direct.hpp b/defold-rive/include/rive/animation/blend_animation_direct.hpp index 4c8433e7..82416e81 100644 --- a/defold-rive/include/rive/animation/blend_animation_direct.hpp +++ b/defold-rive/include/rive/animation/blend_animation_direct.hpp @@ -15,6 +15,7 @@ enum class DirectBlendSource : unsigned int class BlendAnimationDirect : public BlendAnimationDirectBase { public: + ~BlendAnimationDirect(); StatusCode onAddedDirty(CoreContext* context) override; StatusCode onAddedClean(CoreContext* context) override; StatusCode import(ImportStack& importStack) override; diff --git a/defold-rive/include/rive/animation/nested_state_machine.hpp b/defold-rive/include/rive/animation/nested_state_machine.hpp index 59e860d6..df8daae1 100644 --- a/defold-rive/include/rive/animation/nested_state_machine.hpp +++ b/defold-rive/include/rive/animation/nested_state_machine.hpp @@ -24,12 +24,14 @@ class NestedStateMachine : public NestedStateMachineBase void initializeAnimation(ArtboardInstance*) override; StateMachineInstance* stateMachineInstance(); - HitResult pointerMove(Vec2D position, float timeStamp = 0); - HitResult pointerDown(Vec2D position); - HitResult pointerUp(Vec2D position); - HitResult pointerExit(Vec2D position); - HitResult dragStart(Vec2D position, float timeStamp = 0); - HitResult dragEnd(Vec2D position, float timeStamp = 0); + HitResult pointerMove(Vec2D position, + float timeStamp = 0, + int pointerId = 0); + HitResult pointerDown(Vec2D position, int pointerId = 0); + HitResult pointerUp(Vec2D position, int pointerId = 0); + HitResult pointerExit(Vec2D position, int pointerId = 0); + HitResult dragStart(Vec2D position, float timeStamp = 0, int pointerId = 0); + HitResult dragEnd(Vec2D position, float timeStamp = 0, int pointerId = 0); bool tryChangeState(); bool hitTest(Vec2D position) const; diff --git a/defold-rive/include/rive/animation/state_machine_fire_trigger.hpp b/defold-rive/include/rive/animation/state_machine_fire_trigger.hpp index 0758890e..76f7e7f0 100644 --- a/defold-rive/include/rive/animation/state_machine_fire_trigger.hpp +++ b/defold-rive/include/rive/animation/state_machine_fire_trigger.hpp @@ -1,19 +1,19 @@ #ifndef _RIVE_STATE_MACHINE_FIRE_TRIGGER_HPP_ #define _RIVE_STATE_MACHINE_FIRE_TRIGGER_HPP_ #include "rive/generated/animation/state_machine_fire_trigger_base.hpp" +#include "rive/data_bind_path_referencer.hpp" #include namespace rive { -class StateMachineFireTrigger : public StateMachineFireTriggerBase +class StateMachineFireTrigger : public StateMachineFireTriggerBase, + public DataBindPathReferencer { public: void perform(StateMachineInstance* stateMachineInstance) const override; void decodeViewModelPathIds(Span value) override; void copyViewModelPathIds( const StateMachineFireTriggerBase& object) override; - -protected: - std::vector m_viewModelPathIdsBuffer; + StatusCode import(ImportStack& importStack) override; }; } // namespace rive diff --git a/defold-rive/include/rive/animation/state_machine_instance.hpp b/defold-rive/include/rive/animation/state_machine_instance.hpp index 908521ba..840c77e4 100644 --- a/defold-rive/include/rive/animation/state_machine_instance.hpp +++ b/defold-rive/include/rive/animation/state_machine_instance.hpp @@ -13,6 +13,8 @@ #include "rive/listener_type.hpp" #include "rive/nested_animation.hpp" #include "rive/scene.hpp" +#include "rive/data_bind/data_bind_container.hpp" +#include "rive/input/focusable.hpp" namespace rive { @@ -38,6 +40,7 @@ class DataBind; class BindableProperty; class HitDrawable; class ListenerViewModel; +typedef void (*DataBindChanged)(); #ifdef WITH_RIVE_TOOLS class StateMachineInstance; @@ -46,7 +49,8 @@ typedef void (*InputChanged)(StateMachineInstance*, uint64_t); class StateMachineInstance : public Scene, public NestedEventNotifier, - public NestedEventListener + public NestedEventListener, + public DataBindContainer { friend class SMIInput; friend class KeyedProperty; @@ -58,6 +62,7 @@ class StateMachineInstance : public Scene, /// pointer position too. HitResult updateListeners(Vec2D position, ListenerType hitListener, + int pointerId = 0, float timeStamp = 0); template @@ -110,7 +115,8 @@ class StateMachineInstance : public Scene, void bindViewModelInstance( rcp viewModelInstance) override; void dataContext(DataContext* dataContext); - DataContext* dataContext() { return m_DataContext; }; + DataContext* dataContext() const { return m_DataContext; } + void rebind() override; size_t currentAnimationCount() const; const LinearAnimationInstance* currentAnimationByIndex(size_t index) const; @@ -128,14 +134,24 @@ class StateMachineInstance : public Scene, void advancedDataContext(); void reset(); std::string name() const override; - HitResult pointerMove(Vec2D position, float timeStamp = 0) override; - HitResult pointerDown(Vec2D position) override; - HitResult pointerUp(Vec2D position) override; - HitResult pointerExit(Vec2D position) override; + HitResult pointerMove(Vec2D position, + float timeStamp = 0, + int pointerId = 0) override; + HitResult pointerDown(Vec2D position, int pointerId = 0) override; + HitResult pointerUp(Vec2D position, int pointerId = 0) override; + HitResult pointerExit(Vec2D position, int pointerId = 0) override; HitResult dragStart(Vec2D position, float timeStamp = 0, - bool disablePointer = true); - HitResult dragEnd(Vec2D position, float timeStamp = 0); + bool disablePointer = true, + int pointerId = 0); + HitResult dragEnd(Vec2D position, float timeStamp = 0, int pointerId = 0); + + bool keyInput(Key value, + KeyModifiers modifiers, + bool isPressed, + bool isRepeat); + bool textInput(const std::string& text); + bool tryChangeState(); bool hitTest(Vec2D position) const; @@ -201,9 +217,8 @@ class StateMachineInstance : public Scene, } const LayerState* layerState(size_t index); #endif - void updateDataBinds(); - void enablePointerEvents(); - void disablePointerEvents(); + void enablePointerEvents(int pointerId = 0); + void disablePointerEvents(int pointerId = 0); private: std::vector m_reportedEvents; @@ -254,11 +269,14 @@ class HitComponent virtual HitResult processEvent(Vec2D position, ListenerType hitType, bool canHit, - float timeStamp = 0) = 0; - virtual void prepareEvent(Vec2D position, ListenerType hitType) = 0; + float timeStamp = 0, + int pointerId = 0) = 0; + virtual void prepareEvent(Vec2D position, + ListenerType hitType, + int pointerId) = 0; virtual bool hitTest(Vec2D position) const = 0; - virtual void enablePointerEvents() {} - virtual void disablePointerEvents() {} + virtual void enablePointerEvents(int pointerId = 0) {} + virtual void disablePointerEvents(int pointerId = 0) {} #ifdef TESTING int earlyOutCount = 0; #endif diff --git a/defold-rive/include/rive/animation/state_machine_listener.hpp b/defold-rive/include/rive/animation/state_machine_listener.hpp index c0688603..27e62f6c 100644 --- a/defold-rive/include/rive/animation/state_machine_listener.hpp +++ b/defold-rive/include/rive/animation/state_machine_listener.hpp @@ -3,6 +3,7 @@ #include "rive/generated/animation/state_machine_listener_base.hpp" #include "rive/listener_type.hpp" #include "rive/math/vec2d.hpp" +#include "rive/data_bind_path_referencer.hpp" namespace rive { @@ -10,7 +11,8 @@ class Shape; class StateMachineListenerImporter; class ListenerAction; class StateMachineInstance; -class StateMachineListener : public StateMachineListenerBase +class StateMachineListener : public StateMachineListenerBase, + public DataBindPathReferencer { friend class StateMachineListenerImporter; @@ -32,13 +34,7 @@ class StateMachineListener : public StateMachineListenerBase Vec2D previousPosition) const; void decodeViewModelPathIds(Span value) override; void copyViewModelPathIds(const StateMachineListenerBase& object) override; - std::vector viewModelPathIdsBuffer() const - { - return m_viewModelPathIdsBuffer; - } - -protected: - std::vector m_viewModelPathIdsBuffer; + std::vector viewModelPathIdsBuffer() const; private: void addAction(std::unique_ptr); diff --git a/defold-rive/include/rive/animation/transition_comparator.hpp b/defold-rive/include/rive/animation/transition_comparator.hpp index 337811ad..ff9b7e18 100644 --- a/defold-rive/include/rive/animation/transition_comparator.hpp +++ b/defold-rive/include/rive/animation/transition_comparator.hpp @@ -13,49 +13,9 @@ class TransitionComparator : public TransitionComparatorBase { public: StatusCode import(ImportStack& importStack) override; - virtual bool compare(TransitionComparator* comparand, - TransitionConditionOp operation, - const StateMachineInstance* stateMachineInstance, - StateMachineLayerInstance* layerInstance); virtual void useInLayer(const StateMachineInstance* stateMachineInstance, - StateMachineLayerInstance* layerInstance) const - {} - -protected: - bool compareNumbers(float left, float right, TransitionConditionOp op); - bool compareBooleans(bool left, bool right, TransitionConditionOp op); - bool compareEnums(uint16_t left, uint16_t right, TransitionConditionOp op); - bool compareColors(int left, int right, TransitionConditionOp op); - bool compareStrings(std::string left, - std::string right, - TransitionConditionOp op); - bool compareTriggers(uint32_t left, - uint32_t right, - TransitionConditionOp op); - bool compareIds(uint32_t left, uint32_t right, TransitionConditionOp op); - template - bool compareComparables(T left, T right, TransitionConditionOp op) - { - switch (op) - { - case TransitionConditionOp::equal: - return left == right; - case TransitionConditionOp::notEqual: - return left != right; - case TransitionConditionOp::lessThanOrEqual: - return left <= right; - case TransitionConditionOp::lessThan: - return left < right; - case TransitionConditionOp::greaterThanOrEqual: - return left >= right; - case TransitionConditionOp::greaterThan: - return left > right; - default: - return false; - } - } + StateMachineLayerInstance* layerInstance) const {}; }; } // namespace rive - #endif \ No newline at end of file diff --git a/defold-rive/include/rive/animation/transition_property_artboard_comparator.hpp b/defold-rive/include/rive/animation/transition_property_artboard_comparator.hpp index 448f498d..9efd06e6 100644 --- a/defold-rive/include/rive/animation/transition_property_artboard_comparator.hpp +++ b/defold-rive/include/rive/animation/transition_property_artboard_comparator.hpp @@ -7,16 +7,7 @@ namespace rive class Artboard; class TransitionPropertyArtboardComparator : public TransitionPropertyArtboardComparatorBase -{ -public: - bool compare(TransitionComparator* comparand, - TransitionConditionOp operation, - const StateMachineInstance* stateMachineInstance, - StateMachineLayerInstance* layerInstance) override; - -private: - float propertyValue(const StateMachineInstance* stateMachineInstance); -}; +{}; } // namespace rive #endif \ No newline at end of file diff --git a/defold-rive/include/rive/animation/transition_property_viewmodel_comparator.hpp b/defold-rive/include/rive/animation/transition_property_viewmodel_comparator.hpp index 87fe6d1c..2df37024 100644 --- a/defold-rive/include/rive/animation/transition_property_viewmodel_comparator.hpp +++ b/defold-rive/include/rive/animation/transition_property_viewmodel_comparator.hpp @@ -12,10 +12,6 @@ class TransitionPropertyViewModelComparator public: ~TransitionPropertyViewModelComparator(); StatusCode import(ImportStack& importStack) override; - bool compare(TransitionComparator* comparand, - TransitionConditionOp operation, - const StateMachineInstance* stateMachineInstance, - StateMachineLayerInstance* layerInstance) override; template U value(const StateMachineInstance* stateMachineInstance) { @@ -31,10 +27,9 @@ class TransitionPropertyViewModelComparator } return T::defaultValue; }; - float valueToFloat(const StateMachineInstance* stateMachineInstance); void useInLayer(const StateMachineInstance* stateMachineInstance, StateMachineLayerInstance* layerInstance) const override; - DataType instanceDataType(const StateMachineInstance* stateMachineInstance); + BindableProperty* bindableProperty() { return m_bindableProperty; } protected: BindableProperty* m_bindableProperty; diff --git a/defold-rive/include/rive/animation/transition_value_artboard_comparator.hpp b/defold-rive/include/rive/animation/transition_value_artboard_comparator.hpp new file mode 100644 index 00000000..ea3e03ad --- /dev/null +++ b/defold-rive/include/rive/animation/transition_value_artboard_comparator.hpp @@ -0,0 +1,12 @@ +#ifndef _RIVE_TRANSITION_VALUE_ARTBOARD_COMPARATOR_HPP_ +#define _RIVE_TRANSITION_VALUE_ARTBOARD_COMPARATOR_HPP_ +#include "rive/generated/animation/transition_value_artboard_comparator_base.hpp" +#include +namespace rive +{ +class TransitionValueArtboardComparator + : public TransitionValueArtboardComparatorBase +{}; +} // namespace rive + +#endif \ No newline at end of file diff --git a/defold-rive/include/rive/animation/transition_value_boolean_comparator.hpp b/defold-rive/include/rive/animation/transition_value_boolean_comparator.hpp index 9bc9f5dd..1ccaf321 100644 --- a/defold-rive/include/rive/animation/transition_value_boolean_comparator.hpp +++ b/defold-rive/include/rive/animation/transition_value_boolean_comparator.hpp @@ -6,13 +6,7 @@ namespace rive { class TransitionValueBooleanComparator : public TransitionValueBooleanComparatorBase -{ -public: - bool compare(TransitionComparator* comparand, - TransitionConditionOp operation, - const StateMachineInstance* stateMachineInstance, - StateMachineLayerInstance* layerInstance) override; -}; +{}; } // namespace rive #endif \ No newline at end of file diff --git a/defold-rive/include/rive/animation/transition_value_color_comparator.hpp b/defold-rive/include/rive/animation/transition_value_color_comparator.hpp index 389979f2..3f4c46d1 100644 --- a/defold-rive/include/rive/animation/transition_value_color_comparator.hpp +++ b/defold-rive/include/rive/animation/transition_value_color_comparator.hpp @@ -5,13 +5,7 @@ namespace rive { class TransitionValueColorComparator : public TransitionValueColorComparatorBase -{ -public: - bool compare(TransitionComparator* comparand, - TransitionConditionOp operation, - const StateMachineInstance* stateMachineInstance, - StateMachineLayerInstance* layerInstance) override; -}; +{}; } // namespace rive #endif \ No newline at end of file diff --git a/defold-rive/include/rive/animation/transition_value_id_comparator.hpp b/defold-rive/include/rive/animation/transition_value_id_comparator.hpp index 6eea53ba..f4bd07fb 100644 --- a/defold-rive/include/rive/animation/transition_value_id_comparator.hpp +++ b/defold-rive/include/rive/animation/transition_value_id_comparator.hpp @@ -5,9 +5,7 @@ namespace rive { class TransitionValueIdComparator : public TransitionValueIdComparatorBase -{ -public: -}; +{}; } // namespace rive #endif \ No newline at end of file diff --git a/defold-rive/include/rive/animation/transition_value_number_comparator.hpp b/defold-rive/include/rive/animation/transition_value_number_comparator.hpp index 649768ff..a752e304 100644 --- a/defold-rive/include/rive/animation/transition_value_number_comparator.hpp +++ b/defold-rive/include/rive/animation/transition_value_number_comparator.hpp @@ -6,13 +6,7 @@ namespace rive { class TransitionValueNumberComparator : public TransitionValueNumberComparatorBase -{ -public: - bool compare(TransitionComparator* comparand, - TransitionConditionOp operation, - const StateMachineInstance* stateMachineInstance, - StateMachineLayerInstance* layerInstance) override; -}; +{}; } // namespace rive #endif \ No newline at end of file diff --git a/defold-rive/include/rive/animation/transition_value_string_comparator.hpp b/defold-rive/include/rive/animation/transition_value_string_comparator.hpp index 4288c7e2..8b647e1b 100644 --- a/defold-rive/include/rive/animation/transition_value_string_comparator.hpp +++ b/defold-rive/include/rive/animation/transition_value_string_comparator.hpp @@ -6,13 +6,7 @@ namespace rive { class TransitionValueStringComparator : public TransitionValueStringComparatorBase -{ -public: - bool compare(TransitionComparator* comparand, - TransitionConditionOp operation, - const StateMachineInstance* stateMachineInstance, - StateMachineLayerInstance* layerInstance) override; -}; +{}; } // namespace rive #endif \ No newline at end of file diff --git a/defold-rive/include/rive/animation/transition_viewmodel_condition.hpp b/defold-rive/include/rive/animation/transition_viewmodel_condition.hpp index 88914073..9fa981bd 100644 --- a/defold-rive/include/rive/animation/transition_viewmodel_condition.hpp +++ b/defold-rive/include/rive/animation/transition_viewmodel_condition.hpp @@ -2,16 +2,566 @@ #define _RIVE_TRANSITION_VIEW_MODEL_CONDITION_HPP_ #include "rive/generated/animation/transition_viewmodel_condition_base.hpp" #include "rive/animation/transition_comparator.hpp" +#include "rive/animation/transition_property_artboard_comparator.hpp" +#include "rive/animation/transition_property_viewmodel_comparator.hpp" #include "rive/animation/transition_condition_op.hpp" #include "rive/animation/state_machine_instance.hpp" +#include "rive/data_bind/bindable_property.hpp" +#include "rive/data_bind/bindable_property_artboard.hpp" +#include "rive/data_bind/bindable_property_asset.hpp" +#include "rive/data_bind/bindable_property_boolean.hpp" +#include "rive/data_bind/bindable_property_color.hpp" +#include "rive/data_bind/bindable_property_enum.hpp" +#include "rive/data_bind/bindable_property_integer.hpp" +#include "rive/data_bind/bindable_property_number.hpp" +#include "rive/data_bind/bindable_property_string.hpp" +#include "rive/data_bind/bindable_property_trigger.hpp" +#include "rive/animation/transition_self_comparator.hpp" +#include "rive/animation/transition_value_artboard_comparator.hpp" +#include "rive/animation/transition_value_asset_comparator.hpp" +#include "rive/animation/transition_value_number_comparator.hpp" +#include "rive/animation/transition_value_boolean_comparator.hpp" +#include "rive/animation/transition_value_string_comparator.hpp" +#include "rive/animation/transition_value_color_comparator.hpp" +#include "rive/animation/transition_value_enum_comparator.hpp" +#include "rive/animation/transition_value_trigger_comparator.hpp" +#include "rive/animation/artboard_property.hpp" #include namespace rive { + +class ConditionOperation +{ +public: + virtual ~ConditionOperation() {} + virtual bool compareNumbers(float a, float b) { return false; }; + virtual bool compareBooleans(bool a, bool b) { return false; } + virtual bool compareStrings(const std::string& a, const std::string& b) + { + return false; + } + virtual bool compareInts(int a, int b) { return false; } + virtual bool compareUints32(uint32_t a, uint32_t b) { return false; } + +protected: + template bool equal(T left, T right) { return left == right; } + template bool notEqual(T left, T right) + { + return left != right; + } + template bool lessThanOrEqual(T left, T right) + { + return left <= right; + } + template bool lessThan(T left, T right) + { + return left < right; + } + template bool greaterThanOrEqual(T left, T right) + { + return left >= right; + } + template bool greaterThan(T left, T right) + { + return left > right; + } +}; +class ConditionOperationEqual : public ConditionOperation +{ +public: + bool compareNumbers(float a, float b) override + { + return equal(a, b); + } + bool compareBooleans(bool a, bool b) override { return equal(a, b); } + bool compareStrings(const std::string& a, const std::string& b) override + { + return equal(a, b); + } + bool compareInts(int a, int b) override { return equal(a, b); } + bool compareUints32(uint32_t a, uint32_t b) override + { + return equal(a, b); + } +}; +class ConditionOperationNotEqual : public ConditionOperation +{ +public: + bool compareNumbers(float a, float b) override + { + return notEqual(a, b); + } + bool compareBooleans(bool a, bool b) override + { + return notEqual(a, b); + } + bool compareStrings(const std::string& a, const std::string& b) override + { + return notEqual(a, b); + } + bool compareInts(int a, int b) override { return notEqual(a, b); } + bool compareUints32(uint32_t a, uint32_t b) override + { + return notEqual(a, b); + } +}; +class ConditionOperationLessThanOrEqual : public ConditionOperation +{ +public: + bool compareNumbers(float a, float b) override + { + return lessThanOrEqual(a, b); + } +}; +class ConditionOperationLessThan : public ConditionOperation +{ +public: + bool compareNumbers(float a, float b) override + { + return lessThan(a, b); + } +}; +class ConditionOperationGreaterThanOrEqual : public ConditionOperation +{ +public: + bool compareNumbers(float a, float b) override + { + return greaterThanOrEqual(a, b); + } +}; +class ConditionOperationGreaterThan : public ConditionOperation +{ +public: + bool compareNumbers(float a, float b) override + { + return greaterThan(a, b); + } +}; +class ConditionComparand +{}; + +class ConditionComparandNumber : public ConditionComparand +{ +public: + virtual ~ConditionComparandNumber() {} + virtual float value(const StateMachineInstance* stateMachineInstance) = 0; +}; +class ConditionComparandNumberBindable : public ConditionComparandNumber +{ +public: + ConditionComparandNumberBindable(BindablePropertyNumber* property) : + m_bindableProperty(property) + {} + float value(const StateMachineInstance* stateMachineInstance) override + { + auto bindableInstance = + stateMachineInstance->bindablePropertyInstance(m_bindableProperty); + if (bindableInstance) + { + return bindableInstance->as() + ->propertyValue(); + } + return 0; + } + +private: + BindablePropertyNumber* m_bindableProperty; +}; +class ConditionComparandArtboardProperty : public ConditionComparandNumber +{ +public: + ConditionComparandArtboardProperty( + TransitionPropertyArtboardComparator* property) : + m_transitionPropertyArtboardComparator(property) + {} + float value(const StateMachineInstance* stateMachineInstance) override + { + + auto artboard = stateMachineInstance->artboard(); + if (artboard != nullptr) + { + auto property = static_cast( + m_transitionPropertyArtboardComparator->propertyType()); + switch (property) + { + case ArtboardProperty::width: + return artboard->layoutWidth(); + break; + case ArtboardProperty::height: + return artboard->layoutHeight(); + break; + case ArtboardProperty::ratio: + return artboard->layoutWidth() / artboard->layoutHeight(); + break; + + default: + break; + } + } + return 0; + } + +private: + TransitionPropertyArtboardComparator* + m_transitionPropertyArtboardComparator; +}; + +class ConditionComparandNumberBindableInteger : public ConditionComparandNumber +{ +public: + ConditionComparandNumberBindableInteger(BindablePropertyInteger* property) : + m_bindableProperty(property) + {} + float value(const StateMachineInstance* stateMachineInstance) override + { + auto bindableInstance = + stateMachineInstance->bindablePropertyInstance(m_bindableProperty); + if (bindableInstance) + { + + return (float)bindableInstance->as() + ->propertyValue(); + } + return 0; + } + +private: + BindablePropertyInteger* m_bindableProperty; +}; +class ConditionComparandNumberValue : public ConditionComparandNumber +{ +public: + ConditionComparandNumberValue(TransitionValueNumberComparator* value) : + m_value(value) + {} + float value(const StateMachineInstance* stateMachineInstance) override + { + return m_value->value(); + } + +private: + TransitionValueNumberComparator* m_value; +}; + +class ConditionComparandBoolean : public ConditionComparand +{ +public: + virtual ~ConditionComparandBoolean() {} + virtual bool value(const StateMachineInstance* stateMachineInstance) = 0; +}; +class ConditionComparandBooleanBindable : public ConditionComparandBoolean +{ +public: + ConditionComparandBooleanBindable(BindablePropertyBoolean* property) : + m_bindableProperty(property) + {} + bool value(const StateMachineInstance* stateMachineInstance) override + { + auto bindableInstance = + stateMachineInstance->bindablePropertyInstance(m_bindableProperty); + if (bindableInstance) + { + return bindableInstance->as() + ->propertyValue(); + } + return false; + } + +private: + BindablePropertyBoolean* m_bindableProperty; +}; +class ConditionComparandBooleanValue : public ConditionComparandBoolean +{ +public: + ConditionComparandBooleanValue(TransitionValueBooleanComparator* value) : + m_value(value) + {} + bool value(const StateMachineInstance* stateMachineInstance) override + { + return m_value->value(); + } + +private: + TransitionValueBooleanComparator* m_value; +}; + +class ConditionComparandString : public ConditionComparand +{ +public: + virtual ~ConditionComparandString() {} + virtual std::string value( + const StateMachineInstance* stateMachineInstance) = 0; +}; +class ConditionComparandStringBindable : public ConditionComparandString +{ +public: + ConditionComparandStringBindable(BindablePropertyString* property) : + m_bindableProperty(property) + {} + std::string value(const StateMachineInstance* stateMachineInstance) override + { + auto bindableInstance = + stateMachineInstance->bindablePropertyInstance(m_bindableProperty); + if (bindableInstance) + { + return bindableInstance->as() + ->propertyValue(); + } + return std::string{}; + } + +private: + BindablePropertyString* m_bindableProperty; +}; +class ConditionComparandStringValue : public ConditionComparandString +{ +public: + ConditionComparandStringValue(TransitionValueStringComparator* value) : + m_value(value) + {} + std::string value(const StateMachineInstance* stateMachineInstance) override + { + return m_value->value(); + } + +private: + TransitionValueStringComparator* m_value; +}; + +class ConditionComparandColor : public ConditionComparand +{ +public: + virtual ~ConditionComparandColor() {} + virtual int value(const StateMachineInstance* stateMachineInstance) = 0; +}; +class ConditionComparandColorBindable : public ConditionComparandColor +{ +public: + ConditionComparandColorBindable(BindablePropertyColor* property) : + m_bindableProperty(property) + {} + int value(const StateMachineInstance* stateMachineInstance) override + { + auto bindableInstance = + stateMachineInstance->bindablePropertyInstance(m_bindableProperty); + if (bindableInstance) + { + return bindableInstance->as() + ->propertyValue(); + } + return 0; + } + +private: + BindablePropertyColor* m_bindableProperty; +}; +class ConditionComparandColorValue : public ConditionComparandColor +{ +public: + ConditionComparandColorValue(TransitionValueColorComparator* value) : + m_value(value) + {} + int value(const StateMachineInstance* stateMachineInstance) override + { + return m_value->value(); + } + +private: + TransitionValueColorComparator* m_value; +}; + +class ConditionComparandUint32 : public ConditionComparand +{ +public: + virtual ~ConditionComparandUint32() {} + virtual uint32_t value( + const StateMachineInstance* stateMachineInstance) = 0; +}; +class ConditionComparandEnumBindable : public ConditionComparandUint32 +{ +public: + ConditionComparandEnumBindable(BindablePropertyEnum* property) : + m_bindableProperty(property) + {} + uint32_t value(const StateMachineInstance* stateMachineInstance) override + { + auto bindableInstance = + stateMachineInstance->bindablePropertyInstance(m_bindableProperty); + if (bindableInstance) + { + return bindableInstance->as() + ->propertyValue(); + } + return 0; + } + +private: + BindablePropertyEnum* m_bindableProperty; +}; +class ConditionComparandEnumValue : public ConditionComparandUint32 +{ +public: + ConditionComparandEnumValue(TransitionValueEnumComparator* value) : + m_value(value) + {} + uint32_t value(const StateMachineInstance* stateMachineInstance) override + { + return m_value->value(); + } + +private: + TransitionValueEnumComparator* m_value; +}; +class ConditionComparandTriggerBindable : public ConditionComparandUint32 +{ +public: + ConditionComparandTriggerBindable(BindablePropertyTrigger* property) : + m_bindableProperty(property) + {} + uint32_t value(const StateMachineInstance* stateMachineInstance) override + { + auto bindableInstance = + stateMachineInstance->bindablePropertyInstance(m_bindableProperty); + if (bindableInstance) + { + return bindableInstance->as() + ->propertyValue(); + } + return 0; + } + +private: + BindablePropertyTrigger* m_bindableProperty; +}; +class ConditionComparandTriggerValue : public ConditionComparandUint32 +{ +public: + ConditionComparandTriggerValue(TransitionValueTriggerComparator* value) : + m_value(value) + {} + uint32_t value(const StateMachineInstance* stateMachineInstance) override + { + return m_value->value(); + } + +private: + TransitionValueTriggerComparator* m_value; +}; +class ConditionComparandIntegerBindable : public ConditionComparandUint32 +{ +public: + ConditionComparandIntegerBindable(BindablePropertyInteger* property) : + m_bindableProperty(property) + {} + uint32_t value(const StateMachineInstance* stateMachineInstance) override + { + auto bindableInstance = + stateMachineInstance->bindablePropertyInstance(m_bindableProperty); + if (bindableInstance) + { + return bindableInstance->as() + ->propertyValue(); + } + return 0; + } + +private: + BindablePropertyInteger* m_bindableProperty; +}; +class ConditionComparandAssetBindable : public ConditionComparandUint32 +{ +public: + ConditionComparandAssetBindable(BindablePropertyAsset* property) : + m_bindableProperty(property) + {} + uint32_t value(const StateMachineInstance* stateMachineInstance) override + { + auto bindableInstance = + stateMachineInstance->bindablePropertyInstance(m_bindableProperty); + if (bindableInstance) + { + return bindableInstance->as() + ->propertyValue(); + } + return 0; + } + +private: + BindablePropertyAsset* m_bindableProperty; +}; +class ConditionComparandAssetValue : public ConditionComparandUint32 +{ +public: + ConditionComparandAssetValue(TransitionValueAssetComparator* value) : + m_value(value) + {} + uint32_t value(const StateMachineInstance* stateMachineInstance) override + { + return m_value->value(); + } + +private: + TransitionValueAssetComparator* m_value; +}; +class ConditionComparandArtboardBindable : public ConditionComparandUint32 +{ +public: + ConditionComparandArtboardBindable(BindablePropertyArtboard* property) : + m_bindableProperty(property) + {} + uint32_t value(const StateMachineInstance* stateMachineInstance) override + { + auto bindableInstance = + stateMachineInstance->bindablePropertyInstance(m_bindableProperty); + if (bindableInstance) + { + return bindableInstance->as() + ->propertyValue(); + } + return 0; + } + +private: + BindablePropertyArtboard* m_bindableProperty; +}; +class ConditionComparandArtboardValue : public ConditionComparandUint32 +{ +public: + ConditionComparandArtboardValue(TransitionValueArtboardComparator* value) : + m_value(value) + {} + uint32_t value(const StateMachineInstance* stateMachineInstance) override + { + return m_value->value(); + } + +private: + TransitionValueArtboardComparator* m_value; +}; + +class ConditionComparison +{ +public: + ConditionComparison(ConditionOperation* op) : m_operation(op) {} + virtual ~ConditionComparison() { delete m_operation; } + virtual bool compare(const StateMachineInstance* stateMachineInstance, + StateMachineLayerInstance* layerInstance) = 0; + + bool compareNumbers(float left, float right); + bool compareBooleans(bool left, bool right); + bool compareStrings(const std::string& left, const std::string& right); + bool compareColors(int left, int right); + bool compareUints32(uint32_t left, uint32_t right); + +protected: + ConditionOperation* m_operation; +}; class TransitionViewModelCondition : public TransitionViewModelConditionBase { protected: TransitionComparator* m_leftComparator; TransitionComparator* m_rightComparator; + ConditionComparison* m_comparison = nullptr; public: ~TransitionViewModelCondition(); @@ -36,6 +586,8 @@ class TransitionViewModelCondition : public TransitionViewModelConditionBase { return (TransitionConditionOp)opValue(); } + ConditionOperation* operation(TransitionConditionOp op); + void initialize(); }; } // namespace rive diff --git a/defold-rive/include/rive/artboard.hpp b/defold-rive/include/rive/artboard.hpp index 351b1c8b..18db9ecc 100644 --- a/defold-rive/include/rive/artboard.hpp +++ b/defold-rive/include/rive/artboard.hpp @@ -6,9 +6,8 @@ #include "rive/animation/linear_animation.hpp" #include "rive/animation/state_machine.hpp" #include "rive/core_context.hpp" -#include "rive/data_bind/data_bind.hpp" #include "rive/data_bind/data_context.hpp" -#include "rive/data_bind/data_bind_context.hpp" +#include "rive/data_bind/data_bind_container.hpp" #include "rive/viewmodel/viewmodel_instance_value.hpp" #include "rive/viewmodel/viewmodel_instance_viewmodel.hpp" #include "rive/generated/artboard_base.hpp" @@ -48,6 +47,9 @@ class SMIBool; class SMIInput; class SMINumber; class SMITrigger; +class DataBind; +class DataBindContainer; +class ScriptedObject; #ifdef WITH_RIVE_TOOLS typedef void (*ArtboardCallback)(void*); @@ -59,7 +61,8 @@ typedef float (*RootTransformCallback)(void*, float, float, bool); class Artboard : public ArtboardBase, public CoreContext, public Virtualizable, - public ResettingComponent + public ResettingComponent, + public DataBindContainer { friend class File; friend class ArtboardImporter; @@ -67,18 +70,20 @@ class Artboard : public ArtboardBase, private: std::vector m_Objects; + std::vector m_invalidObjects; std::vector m_Animations; std::vector m_StateMachines; std::vector m_DependencyOrder; std::vector m_Drawables; + std::vector m_clippingShapes; std::vector m_DrawTargets; std::vector m_NestedArtboards; std::vector m_ComponentLists; std::vector m_ArtboardHosts; std::vector m_Joysticks; std::vector m_Resettables; - std::vector m_DataBinds; - std::vector m_AllDataBinds; + std::vector m_ScriptedObjects; + std::vector m_advancingComponents; DataContext* m_DataContext = nullptr; bool m_ownsDataContext = false; bool m_JoysticksApplyBeforeUpdate = true; @@ -93,12 +98,16 @@ class Artboard : public ArtboardBase, float m_originalWidth = 0; float m_originalHeight = 0; bool m_updatesOwnLayout = true; + bool m_hostTransformMarkedDirty = false; + bool m_didChange = true; Artboard* parentArtboard() const; ArtboardHost* m_host = nullptr; + static uint64_t sm_frameId; bool sharesLayoutWithHost() const; void cloneObjectDataBinds(const Core* object, Core* clone, Artboard* artboard) const; + void initScriptedObjects(); // Variable that tracks whenever the draw order changes. It is used by the // state machine controllers to sort their hittable components when they are @@ -115,11 +124,18 @@ class Artboard : public ArtboardBase, void sortDependencies(); void sortDrawOrder(); + void clearRedundantOperations(); void updateRenderPath() override; void update(ComponentDirt value) override; public: - void updateDataBinds(); + static uint64_t frameId() { return sm_frameId; } +#ifdef TESTING + static void incFrameId() { sm_frameId++; } +#elif WITH_RIVE_TOOLS + static void incFrameId() { sm_frameId++; } +#endif + void updateDataBinds(bool applyTargetToSource = true) override; void host(ArtboardHost* artboardHost); ArtboardHost* host() const; @@ -131,6 +147,7 @@ class Artboard : public ArtboardBase, Component* virtualizableComponent() override { return this; } bool updatesOwnLayout() { return m_updatesOwnLayout; } StatusCode onAddedClean(CoreContext* context) override; + void addDirtyDataBind(DataBind*) override; private: #ifdef TESTING @@ -146,6 +163,7 @@ class Artboard : public ArtboardBase, ~Artboard() override; bool validateObjects(); StatusCode initialize(); + bool didChange() { return m_didChange; } Core* resolve(uint32_t id) const override; #ifdef WITH_RIVE_TOOLS @@ -157,7 +175,10 @@ class Artboard : public ArtboardBase, { m_artboardSource = artboard; } - const Artboard* artboardSource() const { return m_artboardSource; } + const Artboard* artboardSource() const + { + return isInstance() ? m_artboardSource : this; + } bool isAncestor(const Artboard* artboard); /// Find the id of a component in the artboard the object in the artboard. @@ -193,6 +214,7 @@ class Artboard : public ArtboardBase, void updateWorldTransform() override {} void markLayoutDirty(LayoutComponent* layoutComponent); + void markHostTransformDirty(); void cleanLayout(LayoutComponent* layoutComponent); LayoutData* takeLayoutData(); @@ -212,17 +234,14 @@ class Artboard : public ArtboardBase, void reset() override; uint8_t drawOrderChangeCounter() { return m_drawOrderChangeCounter; } Drawable* firstDrawable() { return m_FirstDrawable; }; + void addScriptedObject(ScriptedObject* object); - enum class DrawOption - { - kNormal, - kHideBG, - kHideFG, - }; - void draw(Renderer* renderer, DrawOption option); + void drawInternal(Renderer* renderer); void draw(Renderer* renderer) override; void addToRenderPath(RenderPath* path, const Mat2D& transform); + void addToRawPath(RawPath& path, const Mat2D* transform); + void changed(); #ifdef TESTING ShapePaintPath* clipPath() { return &m_worldPath; } ShapePaintPath* backgroundPath() { return &m_localPath; } @@ -243,8 +262,6 @@ class Artboard : public ArtboardBase, { return m_ComponentLists; } - const std::vector dataBinds() const { return m_DataBinds; } - const std::vector allDataBinds() const { return m_AllDataBinds; } DataContext* dataContext() { return m_DataContext; } NestedArtboard* nestedArtboard(const std::string& name) const; NestedArtboard* nestedArtboardAtPath(const std::string& path) const; @@ -261,6 +278,12 @@ class Artboard : public ArtboardBase, void xChanged() override; void yChanged() override; + void resetSize() + { + width(m_originalWidth); + height(m_originalHeight); + } + // Can we hide these from the public? (they use playable) bool isTranslucent() const; bool isTranslucent(const LinearAnimation*) const; @@ -269,11 +292,10 @@ class Artboard : public ArtboardBase, void internalDataContext(DataContext* dataContext); void clearDataContext(); void unbind(); + void rebind() override; void bindViewModelInstance(rcp viewModelInstance, DataContext* parent); void bindViewModelInstance(rcp viewModelInstance); - void addDataBind(DataBind* dataBind); - void sortDataBinds(); bool hasAudio() const; @@ -472,6 +494,7 @@ class Artboard : public ArtboardBase, #ifdef WITH_RIVE_TOOLS ArtboardCallback m_layoutChangedCallback = nullptr; ArtboardCallback m_layoutDirtyCallback = nullptr; + ArtboardCallback m_transformDirtyCallback = nullptr; TestBoundsCallback m_testBoundsCallback = nullptr; IsAncestorCallback m_isAncestorCallback = nullptr; RootTransformCallback m_rootTransformCallback = nullptr; @@ -487,6 +510,11 @@ class Artboard : public ArtboardBase, m_layoutDirtyCallback = callback; addDirt(ComponentDirt::Components); } + void onTransformDirty(ArtboardCallback callback) + { + m_transformDirtyCallback = callback; + addDirt(ComponentDirt::Components); + } void onTestBounds(TestBoundsCallback callback) { m_testBoundsCallback = callback; diff --git a/defold-rive/include/rive/artboard_component_list.hpp b/defold-rive/include/rive/artboard_component_list.hpp index eacc74e2..437b1a28 100644 --- a/defold-rive/include/rive/artboard_component_list.hpp +++ b/defold-rive/include/rive/artboard_component_list.hpp @@ -8,6 +8,7 @@ #include "rive/artboard.hpp" #include "rive/constraints/constrainable_list.hpp" #include "rive/property_recorder.hpp" +#include "rive/file.hpp" #include "rive/artboard_host.hpp" #include "rive/data_bind/data_bind_list_item_consumer.hpp" #include "rive/layout/layout_node_provider.hpp" @@ -17,7 +18,6 @@ #include namespace rive { -class File; class LayoutComponent; class ScrollConstraint; @@ -59,6 +59,7 @@ class ArtboardComponentList : public ArtboardComponentListBase, void updateWorldTransform() override; void updateList(std::vector>* list) override; void draw(Renderer* renderer) override; + bool willDraw() override; Core* hitTest(HitInfo*, const Mat2D&) override; void update(ComponentDirt value) override; void updateConstraints() override; @@ -129,10 +130,10 @@ class ArtboardComponentList : public ArtboardComponentListBase, void linkStateMachineToArtboard(StateMachineInstance* stateMachineInstance, ArtboardInstance* artboard); void computeLayoutBounds(); - void createArtboardRecorders(Artboard*); - void applyRecorders(Artboard* artboard, Artboard* sourceArtboard); + void createArtboardRecorders(const Artboard*); + void applyRecorders(Artboard* artboard, const Artboard* sourceArtboard); void applyRecorders(StateMachineInstance* stateMachineInstance, - Artboard* sourceArtboard); + const Artboard* sourceArtboard); mutable std::unordered_map m_artboardsMap; std::unordered_map, std::unique_ptr> @@ -146,7 +147,7 @@ class ArtboardComponentList : public ArtboardComponentListBase, std::unordered_map>> m_stateMachinesPool; - std::unordered_map> + std::unordered_map> m_propertyRecordersMap; std::unordered_map m_artboardTransforms; Vec2D artboardPosition(ArtboardInstance* artboard); diff --git a/defold-rive/include/rive/artboard_host.hpp b/defold-rive/include/rive/artboard_host.hpp index 74f1d49f..32657a68 100644 --- a/defold-rive/include/rive/artboard_host.hpp +++ b/defold-rive/include/rive/artboard_host.hpp @@ -1,6 +1,8 @@ #ifndef _RIVE_ARTBOARD_HOST_HPP_ #define _RIVE_ARTBOARD_HOST_HPP_ #include "rive/refcnt.hpp" +#include "rive/file.hpp" +#include "rive/data_bind_path_referencer.hpp" #include namespace rive { @@ -8,14 +10,12 @@ class ArtboardInstance; class DataBind; class DataContext; class ViewModelInstance; -class File; -class ArtboardHost +class ArtboardHost : public DataBindPathReferencer { public: virtual size_t artboardCount() = 0; virtual ArtboardInstance* artboardInstance(int index = 0) = 0; - virtual std::vector dataBindPathIds() { return {}; } virtual void internalDataContext(DataContext* dataContext) = 0; virtual void bindViewModelInstance(rcp viewModelInstance, DataContext* parent) = 0; diff --git a/defold-rive/include/rive/assets/file_asset.hpp b/defold-rive/include/rive/assets/file_asset.hpp index 66886889..680f484a 100644 --- a/defold-rive/include/rive/assets/file_asset.hpp +++ b/defold-rive/include/rive/assets/file_asset.hpp @@ -16,6 +16,9 @@ class FileAsset : public FileAssetBase, public RefCnt std::vector m_cdnUuid; std::vector m_fileAssetReferencers; +protected: + virtual bool addsToBackboard() { return true; } + public: Span cdnUuid() const; std::string cdnUuidStr() const; diff --git a/defold-rive/include/rive/assets/file_asset_contents.hpp b/defold-rive/include/rive/assets/file_asset_contents.hpp index 67457c02..d4c4b2d7 100644 --- a/defold-rive/include/rive/assets/file_asset_contents.hpp +++ b/defold-rive/include/rive/assets/file_asset_contents.hpp @@ -10,12 +10,16 @@ class FileAssetContents : public FileAssetContentsBase { public: SimpleArray& bytes(); + SimpleArray& signature(); StatusCode import(ImportStack& importStack) override; void decodeBytes(Span value) override; void copyBytes(const FileAssetContentsBase& object) override; + void decodeSignature(Span value) override; + void copySignature(const FileAssetContentsBase& object) override; private: SimpleArray m_bytes; + SimpleArray m_signature; }; } // namespace rive diff --git a/defold-rive/include/rive/assets/file_asset_referencer.hpp b/defold-rive/include/rive/assets/file_asset_referencer.hpp index df123e03..44f59883 100644 --- a/defold-rive/include/rive/assets/file_asset_referencer.hpp +++ b/defold-rive/include/rive/assets/file_asset_referencer.hpp @@ -15,6 +15,7 @@ class FileAssetReferencer public: virtual ~FileAssetReferencer() = 0; virtual void setAsset(rcp asset); + const rcp asset() { return m_fileAsset; } virtual uint32_t assetId() = 0; StatusCode registerReferencer(ImportStack& importStack); virtual void assetUpdated() {} diff --git a/defold-rive/include/rive/assets/manifest_asset.hpp b/defold-rive/include/rive/assets/manifest_asset.hpp new file mode 100644 index 00000000..2489dc2e --- /dev/null +++ b/defold-rive/include/rive/assets/manifest_asset.hpp @@ -0,0 +1,31 @@ +#ifndef _RIVE_MANIFEST_ASSET_HPP_ +#define _RIVE_MANIFEST_ASSET_HPP_ +#include "rive/generated/assets/manifest_asset_base.hpp" +#include "rive/data_resolver.hpp" +#include +#include +#include +namespace rive +{ +class ManifestAsset : public ManifestAssetBase, public DataResolver +{ +private: + std::unordered_map m_names; + std::unordered_map> m_paths; + static const std::string empty; + static const std::vector emptyIntVector; + bool decodeNames(BinaryReader& reader); + bool decodePaths(BinaryReader& reader); + +protected: + bool addsToBackboard() override { return false; } + +public: + bool decode(SimpleArray&, Factory*) override; + std::string fileExtension() const override; + const std::string& resolveName(int id) override; + const std::vector& resolvePath(int id) override; +}; +} // namespace rive + +#endif \ No newline at end of file diff --git a/defold-rive/include/rive/assets/script_asset.hpp b/defold-rive/include/rive/assets/script_asset.hpp new file mode 100644 index 00000000..ae41646a --- /dev/null +++ b/defold-rive/include/rive/assets/script_asset.hpp @@ -0,0 +1,182 @@ +#ifndef _RIVE_SCRIPT_ASSET_HPP_ +#define _RIVE_SCRIPT_ASSET_HPP_ +#ifdef WITH_RIVE_SCRIPTING +#include "rive/lua/rive_lua_libs.hpp" +#endif +#include "rive/file.hpp" +#include "rive/generated/assets/script_asset_base.hpp" +#include "rive/simple_array.hpp" +#include +namespace rive +{ +class Artboard; +class Component; +class DataBind; +class ScriptedObject; + +enum ScriptProtocol +{ + utility, + node, + layout, + converter, + pathEffect +}; + +#ifdef WITH_RIVE_SCRIPTING +class ScriptAssetImporter; +#endif + +class ScriptInput +{ +protected: + ScriptedObject* m_scriptedObject = nullptr; + DataBind* m_dataBind = nullptr; + +public: + virtual ~ScriptInput() {}; + virtual void initScriptedValue(); + virtual bool validateForScriptInit() = 0; + static ScriptInput* from(Core* component); + DataBind* dataBind() { return m_dataBind; } + void dataBind(DataBind* dataBind) { m_dataBind = dataBind; } + ScriptedObject* scriptedObject() { return m_scriptedObject; } + void scriptedObject(ScriptedObject* object) { m_scriptedObject = object; } +}; + +class OptionalScriptedMethods +{ +private: + static const int m_advancesBit = 1 << 0; + static const int m_updatesBit = 1 << 1; + static const int m_measuresBit = 1 << 2; + static const int m_wantsPointerDownBit = 1 << 3; + static const int m_wantsPointerMoveBit = 1 << 4; + static const int m_wantsPointerUpBit = 1 << 5; + static const int m_wantsPointerExitBit = 1 << 6; + static const int m_wantsPointerCancelBit = 1 << 7; + static const int m_drawsBit = 1 << 8; + static const int m_initsBit = 1 << 9; + + int m_implementedMethods = 0; + +protected: + bool verifyImplementation(ScriptedObject* object, LuaState* luaState); + +public: + int implementedMethods() { return m_implementedMethods; } + void implementedMethods(int implemented) + { + m_implementedMethods = implemented; + } + bool listensToPointerEvents() + { + return (m_implementedMethods & + (m_wantsPointerDownBit | m_wantsPointerMoveBit | + m_wantsPointerUpBit | m_wantsPointerExitBit | + m_wantsPointerCancelBit)) != 0; + } + bool advances() { return (m_implementedMethods & m_advancesBit) != 0; } + bool updates() { return (m_implementedMethods & m_updatesBit) != 0; } + bool measures() { return (m_implementedMethods & m_measuresBit) != 0; } + bool wantsPointerDown() + { + return (m_implementedMethods & m_wantsPointerDownBit) != 0; + } + bool wantsPointerMove() + { + return (m_implementedMethods & m_wantsPointerMoveBit) != 0; + } + bool wantsPointerUp() + { + return (m_implementedMethods & m_wantsPointerUpBit) != 0; + } + bool wantsPointerExit() + { + return (m_implementedMethods & m_wantsPointerExitBit) != 0; + } + bool wantsPointerCancel() + { + return (m_implementedMethods & m_wantsPointerCancelBit) != 0; + } + bool draws() { return (m_implementedMethods & m_drawsBit) != 0; } + bool inits() { return (m_implementedMethods & m_initsBit) != 0; } +}; + +class ModuleDetails +{ +public: + virtual ~ModuleDetails() = default; + virtual std::string moduleName() = 0; + virtual void registrationComplete(int ref) {} + virtual Span moduleBytecode() { return Span(); } + virtual bool isProtocolScript() = 0; + virtual bool verified() const { return false; } + void addMissingDependency(std::string name) { m_dependencies.insert(name); } + void clearMissingDependency(std::string name) + { + auto it = m_dependencies.find(name); + if (it != m_dependencies.end()) + { + m_dependencies.erase(it); + } + } + std::unordered_set missingDependencies() + { + return m_dependencies; + } + +private: + std::unordered_set m_dependencies; +}; + +class ScriptAsset : public ScriptAssetBase, + public OptionalScriptedMethods, + public ModuleDetails +{ + +public: +#ifdef WITH_RIVE_SCRIPTING + friend class ScriptAssetImporter; + + bool verified() const override { return m_verified; } + Span moduleBytecode() override { return m_bytecode; } +#endif + + bool initScriptedObject(ScriptedObject* object); + + /// Sets the bytecode from data with header format: + /// [flags:1] [signature:64 if signed] [luau_bytecode:N] + /// Flags byte: bits 0-6 = version, bit 7 = isSigned + /// Returns true if bytecode was set (verification is separate from return). + bool bytecode(Span data); + + /// Bytecode provided via decode should only happen with in-band bytecode. + /// The signature will later be verified once file loading completes, so it + /// is immediately marked as unverified. + bool decode(SimpleArray& data, Factory* factory) override; + + std::string fileExtension() const override { return "lua"; } + void file(File* value) { m_file = value; } + File* file() const { return m_file; } +#ifdef WITH_RIVE_SCRIPTING + LuaState* vm(); + void registrationComplete(int ref) override; +#endif + std::string moduleName() override { return name(); } + bool isProtocolScript() override { return !isModule(); } + +private: + File* m_file = nullptr; +#ifdef WITH_RIVE_SCRIPTING + bool m_scriptRegistered = false; + bool m_verified = false; + SimpleArray m_bytecode; + bool m_initted = false; +#endif + + bool initScriptedObjectWith(ScriptedObject* object); +}; +} // namespace rive + +#endif \ No newline at end of file diff --git a/defold-rive/include/rive/bindable_artboard.hpp b/defold-rive/include/rive/bindable_artboard.hpp new file mode 100644 index 00000000..fac7888f --- /dev/null +++ b/defold-rive/include/rive/bindable_artboard.hpp @@ -0,0 +1,23 @@ +#ifndef _RIVE_BINDABLE_ARTBOARD_HPP_ +#define _RIVE_BINDABLE_ARTBOARD_HPP_ +#include "rive/refcnt.hpp" +#include "rive/file.hpp" +#include "rive/artboard.hpp" + +namespace rive +{ + +class BindableArtboard : public RefCnt +{ +public: + BindableArtboard(rcp file, + std::unique_ptr artboard); + ArtboardInstance* artboard() { return m_artboard.get(); } + +private: + rcp m_file; + std::unique_ptr m_artboard; +}; +} // namespace rive + +#endif diff --git a/defold-rive/include/rive/bytecode_header.hpp b/defold-rive/include/rive/bytecode_header.hpp new file mode 100644 index 00000000..1ac4cd2b --- /dev/null +++ b/defold-rive/include/rive/bytecode_header.hpp @@ -0,0 +1,80 @@ +#ifndef _RIVE_BYTECODE_HEADER_HPP_ +#define _RIVE_BYTECODE_HEADER_HPP_ + +#include "rive/span.hpp" +#include +#include + +namespace rive +{ + +/// Size of the signature in bytes (hydro_sign_BYTES from libhydrogen). +static constexpr size_t kSignatureSize = 64; + +/// Lightweight view into bytecode data with header. +/// Does not copy the underlying data - just provides accessors. +/// +/// Header format: +/// [flags:1] [signature:64 if signed] [luau_bytecode:N] +/// +/// Flags byte layout: +/// Bits 0-6: Version number (0-127) +/// Bit 7: isSigned flag +class BytecodeHeader +{ +public: + /// Constructs a BytecodeHeader from raw data (header + bytecode). + /// The data must outlive this object. + explicit BytecodeHeader(Span data) : m_data(data) + { + if (!data.empty()) + { + m_flags = data[0]; + } + } + + /// @returns true if the header indicates the bytecode is signed + bool isSigned() const { return (m_flags & 0x80) != 0; } + + /// @returns the version number from the header (0-127) + uint8_t version() const { return m_flags & 0x7F; } + + /// @returns true if the data is valid (has at least the header byte and + /// enough bytes for signature if signed) + bool isValid() const { return m_data.size() >= bytecodeOffset(); } + + /// @returns the offset where bytecode starts (1 if unsigned, 65 if signed) + size_t bytecodeOffset() const + { + return isSigned() ? (1 + kSignatureSize) : 1; + } + + /// @returns a span of the signature bytes, or empty span if not signed + Span signature() const + { + if (!isSigned() || m_data.size() < 1 + kSignatureSize) + { + return Span(); + } + return Span(m_data.data() + 1, kSignatureSize); + } + + /// @returns a span of the actual bytecode (without header) + Span bytecode() const + { + size_t offset = bytecodeOffset(); + if (m_data.size() < offset) + { + return Span(); + } + return Span(m_data.data() + offset, + m_data.size() - offset); + } + +private: + Span m_data; + uint8_t m_flags = 0; +}; + +} // namespace rive +#endif diff --git a/defold-rive/include/rive/command_queue.hpp b/defold-rive/include/rive/command_queue.hpp index 9e730438..77051af5 100644 --- a/defold-rive/include/rive/command_queue.hpp +++ b/defold-rive/include/rive/command_queue.hpp @@ -327,6 +327,14 @@ class CommandQueue : public RefCnt return instantiateArtboardNamed(fileHandle, "", listener, requestId); } + void setArtboardSize(ArtboardHandle, + float width, + float height, + float scale = 1, + uint64_t requestId = 0); + + void resetArtboardSize(ArtboardHandle, uint64_t requestId = 0); + void deleteArtboard(ArtboardHandle, uint64_t requestId = 0); ViewModelInstanceHandle instantiateBlankViewModelInstance( @@ -518,6 +526,7 @@ class CommandQueue : public RefCnt Vec2D screenBounds; // the bounds of coordinate system of the cursor Vec2D position; // the cursor position float scaleFactor = 1.0f; // scale factor for things like retina display + int pointerId = 0; // stable pointer identifier for multitouch }; // All pointer events will automatically convert between artboard and screen @@ -778,6 +787,8 @@ class CommandQueue : public RefCnt removeFontFileAsset, instantiateArtboard, deleteArtboard, + setArtboardSize, + resetArtboardSize, instantiateViewModel, refNestedViewModel, refListViewModel, diff --git a/defold-rive/include/rive/command_server.hpp b/defold-rive/include/rive/command_server.hpp index b9f968c3..2f217f55 100644 --- a/defold-rive/include/rive/command_server.hpp +++ b/defold-rive/include/rive/command_server.hpp @@ -29,9 +29,12 @@ class CommandServer AudioSource* getAudioSource(AudioSourceHandle) const; Font* getFont(FontHandle) const; ArtboardInstance* getArtboardInstance(ArtboardHandle) const; + rcp getBindableArtboard(ArtboardHandle) const; StateMachineInstance* getStateMachineInstance(StateMachineHandle) const; ViewModelInstanceRuntime* getViewModelInstance( ViewModelInstanceHandle) const; + ViewModelInstanceHandle getHandleForInstance( + ViewModelInstanceRuntime*) const; // Wait for queue to not be empty, then returns pollMessages. bool waitCommands(); // Returns imidiatly after checking messages. If there are none just returns @@ -187,8 +190,7 @@ class CommandServer std::unordered_map> m_fonts; std::unordered_map> m_images; std::unordered_map> m_audioSources; - std::unordered_map> - m_artboards; + std::unordered_map> m_artboards; std::unordered_map> m_viewModels; std::unordered_map m_collapsables; protected: ComponentDirt m_Dirt = ComponentDirt::Filthy; + void updateCollapsables(); public: DependencyHelper m_DependencyHelper; @@ -33,6 +36,7 @@ class Component : public ComponentBase bool validate(CoreContext* context) override; StatusCode onAddedDirty(CoreContext* context) override; inline ContainerComponent* parent() const { return m_Parent; } + void addCollapsable(DataBind* collapsable); const std::vector& dependents() const { return m_DependencyHelper.dependents(); @@ -68,6 +72,9 @@ class Component : public ComponentBase virtual bool hitTestPoint(const Vec2D& position, bool skipOnUnclipped, bool isPrimaryHit); +#ifdef TESTING + ComponentDirt dirt() { return m_Dirt; } +#endif }; } // namespace rive diff --git a/defold-rive/include/rive/component_dirt.hpp b/defold-rive/include/rive/component_dirt.hpp index 68e5d6fd..2487023c 100644 --- a/defold-rive/include/rive/component_dirt.hpp +++ b/defold-rive/include/rive/component_dirt.hpp @@ -69,6 +69,13 @@ enum class ComponentDirt : unsigned short /// their render paths, mesh, points, etc. NSlicer = 1 << 13, + /// Set when a ScriptedObject needs to call update on the scripted + /// interface. + ScriptUpdate = 1 << 14, + + /// Clipping needs to be recalculated + Clipping = 1 << 15, + /// All dirty. Every flag (apart from Collapsed) is set. Filthy = 0xFFFE }; diff --git a/defold-rive/include/rive/constraints/constraint.hpp b/defold-rive/include/rive/constraints/constraint.hpp index bb29fb21..40c3444e 100644 --- a/defold-rive/include/rive/constraints/constraint.hpp +++ b/defold-rive/include/rive/constraints/constraint.hpp @@ -11,7 +11,7 @@ class Constraint : public ConstraintBase { public: void strengthChanged() override; - StatusCode onAddedClean(CoreContext* context) override; + StatusCode onAddedDirty(CoreContext* context) override; virtual void markConstraintDirty(); virtual void constrain(TransformComponent* component) = 0; void buildDependencies() override; diff --git a/defold-rive/include/rive/constraints/draggable_constraint.hpp b/defold-rive/include/rive/constraints/draggable_constraint.hpp index e72f2047..c748e791 100644 --- a/defold-rive/include/rive/constraints/draggable_constraint.hpp +++ b/defold-rive/include/rive/constraints/draggable_constraint.hpp @@ -1,11 +1,16 @@ #ifndef _RIVE_DRAGGABLE_CONSTRAINT_HPP_ #define _RIVE_DRAGGABLE_CONSTRAINT_HPP_ #include "rive/generated/constraints/draggable_constraint_base.hpp" +#include "rive/animation/state_machine_listener.hpp" #include "rive/drawable.hpp" +#include "rive/listener_group.hpp" #include "rive/math/vec2d.hpp" +#include "rive/process_event_result.hpp" #include namespace rive { +class HitComponent; + enum class DraggableConstraintDirection : uint8_t { horizontal, @@ -21,13 +26,14 @@ class DraggableProxy public: virtual ~DraggableProxy() {} virtual bool isOpaque() { return false; } - virtual void startDrag(Vec2D mousePosition, float timeStamp = 0) = 0; - virtual void drag(Vec2D mousePosition, float timeStamp = 0) = 0; - virtual void endDrag(Vec2D mousePosition, float timeStamp = 0) = 0; + virtual bool startDrag(Vec2D mousePosition, float timeStamp = 0) = 0; + virtual bool drag(Vec2D mousePosition, float timeStamp = 0) = 0; + virtual bool endDrag(Vec2D mousePosition, float timeStamp = 0) = 0; Drawable* hittable() { return m_hittable; } }; -class DraggableConstraint : public DraggableConstraintBase +class DraggableConstraint : public DraggableConstraintBase, + public ListenerGroupProvider { public: DraggableConstraint() {} @@ -49,6 +55,52 @@ class DraggableConstraint : public DraggableConstraintBase return dir == DraggableConstraintDirection::vertical || dir == DraggableConstraintDirection::all; } + std::vector listenerGroups() override; + std::vector hitComponents(StateMachineInstance* sm) override + { + return {}; + } +}; + +class DraggableConstraintListenerGroup : public ListenerGroup +{ +public: + DraggableConstraintListenerGroup(const StateMachineListener* listener, + DraggableConstraint* constraint, + DraggableProxy* draggable) : + ListenerGroup(listener), + m_constraint(constraint), + m_draggable(draggable) + {} + ~DraggableConstraintListenerGroup() + { + delete listener(); + delete m_draggable; + } + + void enable(int pointerId = 0) override {} + void disable(int pointerId = 0) override {} + + DraggableConstraint* constraint() { return m_constraint; } + + bool canEarlyOut(Component* drawable) override { return false; } + + bool needsDownListener(Component* drawable) override { return true; } + + bool needsUpListener(Component* drawable) override { return true; } + ProcessEventResult processEvent( + Component* component, + Vec2D position, + int pointerId, + ListenerType hitEvent, + bool canHit, + float timeStamp, + StateMachineInstance* stateMachineInstance) override; + +private: + DraggableConstraint* m_constraint; + DraggableProxy* m_draggable; + bool m_hasScrolled = false; }; } // namespace rive diff --git a/defold-rive/include/rive/constraints/scrolling/scroll_bar_constraint_proxy.hpp b/defold-rive/include/rive/constraints/scrolling/scroll_bar_constraint_proxy.hpp index 5a8229b3..68ad7095 100644 --- a/defold-rive/include/rive/constraints/scrolling/scroll_bar_constraint_proxy.hpp +++ b/defold-rive/include/rive/constraints/scrolling/scroll_bar_constraint_proxy.hpp @@ -21,9 +21,12 @@ class ThumbDraggableProxy : public DraggableProxy } ~ThumbDraggableProxy() {} bool isOpaque() override { return true; } - void startDrag(Vec2D mousePosition, float timeStamp = 0) override; - void drag(Vec2D mousePosition, float timeStamp = 0) override; - void endDrag(Vec2D mousePosition, float timeStamp = 0) override {} + bool startDrag(Vec2D mousePosition, float timeStamp = 0) override; + bool drag(Vec2D mousePosition, float timeStamp = 0) override; + bool endDrag(Vec2D mousePosition, float timeStamp = 0) override + { + return true; + } }; class TrackDraggableProxy : public DraggableProxy @@ -38,10 +41,15 @@ class TrackDraggableProxy : public DraggableProxy m_hittable = hittable; } ~TrackDraggableProxy() {} - bool isOpaque() override { return true; } - void startDrag(Vec2D mousePosition, float timeStamp = 0) override; - void drag(Vec2D mousePosition, float timeStamp = 0) override {} - void endDrag(Vec2D mousePosition, float timeStamp = 0) override {} + bool startDrag(Vec2D mousePosition, float timeStamp = 0) override; + bool drag(Vec2D mousePosition, float timeStamp = 0) override + { + return true; + } + bool endDrag(Vec2D mousePosition, float timeStamp = 0) override + { + return true; + } }; } // namespace rive diff --git a/defold-rive/include/rive/constraints/scrolling/scroll_constraint_proxy.hpp b/defold-rive/include/rive/constraints/scrolling/scroll_constraint_proxy.hpp index 08791050..5ec5ca82 100644 --- a/defold-rive/include/rive/constraints/scrolling/scroll_constraint_proxy.hpp +++ b/defold-rive/include/rive/constraints/scrolling/scroll_constraint_proxy.hpp @@ -12,6 +12,7 @@ class ViewportDraggableProxy : public DraggableProxy private: ScrollConstraint* m_constraint; Vec2D m_lastPosition; + bool m_isDragging = false; public: ViewportDraggableProxy(ScrollConstraint* constraint, Drawable* hittable) : @@ -21,9 +22,9 @@ class ViewportDraggableProxy : public DraggableProxy } ~ViewportDraggableProxy() {} bool isOpaque() override { return false; } - void startDrag(Vec2D mousePosition, float timeStamp = 0) override; - void drag(Vec2D mousePosition, float timeStamp = 0) override; - void endDrag(Vec2D mousePosition, float timeStamp = 0) override; + bool startDrag(Vec2D mousePosition, float timeStamp = 0) override; + bool drag(Vec2D mousePosition, float timeStamp = 0) override; + bool endDrag(Vec2D mousePosition, float timeStamp = 0) override; }; } // namespace rive diff --git a/defold-rive/include/rive/custom_property_container.hpp b/defold-rive/include/rive/custom_property_container.hpp new file mode 100644 index 00000000..160a70ab --- /dev/null +++ b/defold-rive/include/rive/custom_property_container.hpp @@ -0,0 +1,27 @@ +#ifndef _RIVE_CUSTOM_PROPERTY_CONTAINER_HPP_ +#define _RIVE_CUSTOM_PROPERTY_CONTAINER_HPP_ +#include +#include +namespace rive +{ +class Component; +class CustomProperty; + +class CustomPropertyContainer +{ +protected: + std::vector m_customProperties; + void syncCustomProperties(); + +public: + virtual void addProperty(CustomProperty* prop); + virtual void removeProperty(CustomProperty* prop); + virtual const std::vector& containerChildren() const + { + static const std::vector emptyVec; + return emptyVec; + } +}; +} // namespace rive + +#endif \ No newline at end of file diff --git a/defold-rive/include/rive/custom_property_group.hpp b/defold-rive/include/rive/custom_property_group.hpp index 80115e37..9a801a1f 100644 --- a/defold-rive/include/rive/custom_property_group.hpp +++ b/defold-rive/include/rive/custom_property_group.hpp @@ -1,10 +1,12 @@ #ifndef _RIVE_CUSTOM_PROPERTY_GROUP_HPP_ #define _RIVE_CUSTOM_PROPERTY_GROUP_HPP_ +#include "rive/custom_property_container.hpp" #include "rive/generated/custom_property_group_base.hpp" #include namespace rive { -class CustomPropertyGroup : public CustomPropertyGroupBase +class CustomPropertyGroup : public CustomPropertyGroupBase, + public CustomPropertyContainer { public: }; diff --git a/defold-rive/include/rive/data_bind/bindable_property_artboard.hpp b/defold-rive/include/rive/data_bind/bindable_property_artboard.hpp index 724ee474..45d2dde6 100644 --- a/defold-rive/include/rive/data_bind/bindable_property_artboard.hpp +++ b/defold-rive/include/rive/data_bind/bindable_property_artboard.hpp @@ -7,6 +7,7 @@ namespace rive class BindablePropertyArtboard : public BindablePropertyArtboardBase { public: + constexpr static uint32_t defaultValue = -1; }; } // namespace rive diff --git a/defold-rive/include/rive/data_bind/bindable_property_asset.hpp b/defold-rive/include/rive/data_bind/bindable_property_asset.hpp index 58b89ff6..d7594258 100644 --- a/defold-rive/include/rive/data_bind/bindable_property_asset.hpp +++ b/defold-rive/include/rive/data_bind/bindable_property_asset.hpp @@ -1,13 +1,24 @@ #ifndef _RIVE_BINDABLE_PROPERTY_ASSET_HPP_ #define _RIVE_BINDABLE_PROPERTY_ASSET_HPP_ #include "rive/generated/data_bind/bindable_property_asset_base.hpp" +#include "rive/assets/image_asset.hpp" #include namespace rive { class BindablePropertyAsset : public BindablePropertyAssetBase { public: + BindablePropertyAsset() : m_fileAsset(rcp(new ImageAsset())) {} constexpr static uint32_t defaultValue = -1; + rcp fileAsset() { return m_fileAsset; } + void imageValue(RenderImage* image) + { + m_fileAsset->renderImage(ref_rcp(image)); + } + RenderImage* imageValue() { return m_fileAsset->renderImage(); } + +private: + rcp m_fileAsset = nullptr; }; } // namespace rive diff --git a/defold-rive/include/rive/data_bind/context/context_value.hpp b/defold-rive/include/rive/data_bind/context/context_value.hpp index f420df04..25e8632f 100644 --- a/defold-rive/include/rive/data_bind/context/context_value.hpp +++ b/defold-rive/include/rive/data_bind/context/context_value.hpp @@ -37,39 +37,43 @@ class DataBindContextValue return false; }; void syncSourceValue(); - template - U getDataValue(DataValue* input, DataBind* dataBind) + DataValue* calculateUntypedDataValue(DataValue* input, + bool isMainDirection, + DataBind* dataBind) { auto converter = dataBind->converter(); + auto dataValue = converter != nullptr + ? isMainDirection + ? converter->convert(input, dataBind) + : converter->reverseConvert(input, dataBind) + : input; + return dataValue; + } + template + DataValue* calculateDataValue(DataValue* input, + bool isMainDirection, + DataBind* dataBind) + { auto dataValue = - converter != nullptr ? converter->convert(input, dataBind) : input; + calculateUntypedDataValue(input, isMainDirection, dataBind); if (dataValue->is()) { - return dataValue->as()->value(); + return dataValue; } - return T::defaultValue; + return nullptr; }; + template - U getReverseDataValue(DataValue* input, DataBind* dataBind) + U calculateValue(DataValue* input, bool isMainDirection, DataBind* dataBind) { - auto converter = dataBind->converter(); - auto dataValue = converter != nullptr - ? converter->reverseConvert(input, dataBind) - : input; - if (dataValue->is()) + auto dataValue = + calculateDataValue(input, isMainDirection, dataBind); + if (dataValue && dataValue->template is()) { - return dataValue->as()->value(); + return dataValue->template as()->value(); } return T::defaultValue; }; - template - U calculateValue(DataValue* input, bool isMainDirection, DataBind* dataBind) - { - auto value = isMainDirection - ? getDataValue(input, dataBind) - : getReverseDataValue(input, dataBind); - return value; - }; template @@ -79,15 +83,19 @@ class DataBindContextValue if (m_targetValue.syncTargetValue() || !m_isValid) { // Calculate new value after converters are applied - auto value = calculateValue(m_targetValue.dataValue(), - isMainDirection, - m_dataBind); - // Apply value to source - m_dataBind->suppressDirt(true); - auto source = m_dataBind->source(); - source->as()->propertyValue(value); - m_dataBind->suppressDirt(false); - m_isValid = true; + auto value = calculateDataValue(m_targetValue.dataValue(), + isMainDirection, + m_dataBind); + if (value) + { + + // Apply value to source + m_dataBind->suppressDirt(true); + auto source = m_dataBind->source(); + source->as()->applyValue(value->template as()); + m_dataBind->suppressDirt(false); + m_isValid = true; + } } }; }; diff --git a/defold-rive/include/rive/data_bind/context/context_value_any.hpp b/defold-rive/include/rive/data_bind/context/context_value_any.hpp new file mode 100644 index 00000000..d9afe0ad --- /dev/null +++ b/defold-rive/include/rive/data_bind/context/context_value_any.hpp @@ -0,0 +1,17 @@ +#ifndef _RIVE_DATA_BIND_CONTEXT_VALUE_ANY_HPP_ +#define _RIVE_DATA_BIND_CONTEXT_VALUE_ANY_HPP_ +#include "rive/data_bind/context/context_value.hpp" +namespace rive +{ +class DataBindContextValueAny : public DataBindContextValue +{ + +public: + DataBindContextValueAny(DataBind* m_dataBind); + void apply(Core* component, + uint32_t propertyKey, + bool isMainDirection) override; +}; +} // namespace rive + +#endif \ No newline at end of file diff --git a/defold-rive/include/rive/data_bind/converters/data_converter.hpp b/defold-rive/include/rive/data_bind/converters/data_converter.hpp index c5acf4fd..86e3db82 100644 --- a/defold-rive/include/rive/data_bind/converters/data_converter.hpp +++ b/defold-rive/include/rive/data_bind/converters/data_converter.hpp @@ -3,11 +3,12 @@ #include "rive/generated/data_bind/converters/data_converter_base.hpp" #include "rive/data_bind/data_values/data_value.hpp" #include "rive/data_bind/data_context.hpp" +#include "rive/data_bind/data_bind_container.hpp" #include namespace rive { class DataBind; -class DataConverter : public DataConverterBase +class DataConverter : public DataConverterBase, public DataBindContainer { public: ~DataConverter(); @@ -21,18 +22,14 @@ class DataConverter : public DataConverterBase }; virtual DataType outputType() { return DataType::none; }; virtual void bindFromContext(DataContext* dataContext, DataBind* dataBind); - virtual void initialize(DataType inputType) {} virtual void unbind(); StatusCode import(ImportStack& importStack) override; - void addDataBind(DataBind* dataBind); - std::vector dataBinds() const { return m_dataBinds; } void markConverterDirty(); virtual void update(); void copy(const DataConverter& object); virtual bool advance(float elapsedTime); - -private: - std::vector m_dataBinds; + void addDirtyDataBind(DataBind*) override; + virtual void reset() {}; protected: DataBind* m_parentDataBind; diff --git a/defold-rive/include/rive/data_bind/converters/data_converter_formula.hpp b/defold-rive/include/rive/data_bind/converters/data_converter_formula.hpp index 17141222..598eebc9 100644 --- a/defold-rive/include/rive/data_bind/converters/data_converter_formula.hpp +++ b/defold-rive/include/rive/data_bind/converters/data_converter_formula.hpp @@ -28,7 +28,6 @@ class DataConverterFormula : public DataConverterFormulaBase, public Dirtyable Core* clone() const override; void bindFromContext(DataContext* dataContext, DataBind* dataBind) override; void unbind() override; - void update() override; private: int getPrecedence(FormulaToken*); diff --git a/defold-rive/include/rive/data_bind/converters/data_converter_group.hpp b/defold-rive/include/rive/data_bind/converters/data_converter_group.hpp index 1437c5d3..b6829a75 100644 --- a/defold-rive/include/rive/data_bind/converters/data_converter_group.hpp +++ b/defold-rive/include/rive/data_bind/converters/data_converter_group.hpp @@ -34,10 +34,10 @@ class DataConverterGroup : public DataConverterGroupBase const std::vector& items() { return m_items; } Core* clone() const override; void bindFromContext(DataContext* dataContext, DataBind* dataBind) override; - void initialize(DataType inputType) override; void unbind() override; void update() override; bool advance(float elapsedSeconds) override; + void reset() override; private: std::vector m_items; diff --git a/defold-rive/include/rive/data_bind/converters/data_converter_interpolator.hpp b/defold-rive/include/rive/data_bind/converters/data_converter_interpolator.hpp index 3dadfb6c..93027acf 100644 --- a/defold-rive/include/rive/data_bind/converters/data_converter_interpolator.hpp +++ b/defold-rive/include/rive/data_bind/converters/data_converter_interpolator.hpp @@ -28,6 +28,7 @@ class InterpolatorAnimationData } void dispose() { + elapsedSeconds = 0; if (from != nullptr) { delete from; @@ -44,12 +45,14 @@ class InterpolatorAdvancer template void initialize(DataConverterInterpolator* converter) { + m_initialized = true; m_converter = converter; m_animationDataA.initialize(); m_animationDataB.initialize(); m_currentValue = new T(); } + bool initialized() { return m_initialized; } void dispose(); void resetValues(DataValue* input) { @@ -58,6 +61,12 @@ class InterpolatorAdvancer input->copyValue(animationData->to); input->copyValue(m_currentValue); } + void reset() + { + dispose(); + m_isSmoothingAnimation = false; + m_initialized = false; + } void updateValues(DataValue* input) { auto animationData = currentAnimationData(); @@ -93,6 +102,7 @@ class InterpolatorAdvancer InterpolatorAnimationData m_animationDataB; InterpolatorAnimationData* currentAnimationData(); bool m_isSmoothingAnimation = false; + bool m_initialized = false; DataValue* m_currentValue = nullptr; DataConverterInterpolator* m_converter = nullptr; }; @@ -110,14 +120,18 @@ class DataConverterInterpolator : public DataConverterInterpolatorBase DataValue* convert(DataValue* value, DataBind* dataBind) override; DataValue* reverseConvert(DataValue* value, DataBind* dataBind) override; bool advance(float elapsedTime) override; + void reset() override; void copy(const DataConverterInterpolatorBase& object); void durationChanged() override; template void startAdvancer() { + if (m_output != nullptr) + { + delete m_output; + } m_output = new T(); m_advancer.initialize(this); } - void initialize(DataType inputType) override; private: DataValue* m_output = nullptr; diff --git a/defold-rive/include/rive/data_bind/converters/data_converter_number_to_list.hpp b/defold-rive/include/rive/data_bind/converters/data_converter_number_to_list.hpp index 7f3183ee..0f01946c 100644 --- a/defold-rive/include/rive/data_bind/converters/data_converter_number_to_list.hpp +++ b/defold-rive/include/rive/data_bind/converters/data_converter_number_to_list.hpp @@ -6,10 +6,10 @@ #include "rive/refcnt.hpp" #include "rive/viewmodel/viewmodel.hpp" #include "rive/viewmodel/viewmodel_instance_list_item.hpp" +#include "rive/file.hpp" #include namespace rive { -class File; class DataConverterNumberToList : public DataConverterNumberToListBase { diff --git a/defold-rive/include/rive/data_bind/converters/formula/formula_token.hpp b/defold-rive/include/rive/data_bind/converters/formula/formula_token.hpp index b648eb88..8747c7c6 100644 --- a/defold-rive/include/rive/data_bind/converters/formula/formula_token.hpp +++ b/defold-rive/include/rive/data_bind/converters/formula/formula_token.hpp @@ -7,23 +7,15 @@ #include namespace rive { +class DataConverterFormula; class FormulaToken : public FormulaTokenBase { public: - ~FormulaToken(); StatusCode import(ImportStack& importStack) override; - - virtual void bindFromContext(DataContext* dataContext, DataBind* dataBind); - virtual void unbind(); - virtual void update(); - void markDirty(); void addDataBind(DataBind* dataBind); - void copy(const FormulaTokenBase& object); - std::vector dataBinds() const { return m_dataBinds; } private: - std::vector m_dataBinds; - DataBind* m_parentDataBind; + DataConverterFormula* m_formula = nullptr; }; } // namespace rive diff --git a/defold-rive/include/rive/data_bind/data_bind.hpp b/defold-rive/include/rive/data_bind/data_bind.hpp index 35d4ecfd..59680107 100644 --- a/defold-rive/include/rive/data_bind/data_bind.hpp +++ b/defold-rive/include/rive/data_bind/data_bind.hpp @@ -10,8 +10,9 @@ #include namespace rive { -class File; class DataBindContextValue; +class DataBindContainer; +class File; #ifdef WITH_RIVE_TOOLS class DataBind; typedef void (*DataBindChanged)(); @@ -24,6 +25,7 @@ class DataBind : public DataBindBase, public Dirtyable StatusCode import(ImportStack& importStack) override; virtual void updateSourceBinding(bool invalidate = false); virtual void update(ComponentDirt value); + void updateDependents(); Core* target() const { return m_target; }; void target(Core* value) { m_target = value; }; virtual void bind(); @@ -38,15 +40,23 @@ class DataBind : public DataBindBase, public Dirtyable void clearSource(); bool toSource(); bool toTarget(); + bool isNameBased(); bool canSkip(); bool isMainToSource(); bool sourceToTargetRunsFirst(); bool advance(float elapsedTime); void suppressDirt(bool value) { m_suppressDirt = value; }; - void file(File* value) { m_file = value; }; - File* file() const { return m_file; }; + void file(File* value); + File* file() const; DataType outputType(); DataType sourceOutputType(); + void container(DataBindContainer*); + DataBindContainer* m_container = nullptr; + void collapse(bool collapsed); + void initialize(); + +private: + bool m_isCollapsed = false; protected: ComponentDirt m_Dirt = ComponentDirt::Filthy; diff --git a/defold-rive/include/rive/data_bind/data_bind_container.hpp b/defold-rive/include/rive/data_bind/data_bind_container.hpp new file mode 100644 index 00000000..510bbf23 --- /dev/null +++ b/defold-rive/include/rive/data_bind/data_bind_container.hpp @@ -0,0 +1,35 @@ +#ifndef _RIVE_DATA_BIND_CONTAINER_HPP_ +#define _RIVE_DATA_BIND_CONTAINER_HPP_ +#include + +namespace rive +{ +class DataContext; +class DataBind; +class DataBindContainer +{ +public: + virtual void updateDataBinds(bool applyTargetToSource = true); + void addDataBind(DataBind* dataBind); + const std::vector dataBinds() const { return m_dataBinds; } + virtual void addDirtyDataBind(DataBind* dataBind); + virtual void rebind() {}; + +protected: + void deleteDataBinds(); + bool advanceDataBinds(float); + void bindDataBindsFromContext(DataContext*); + void unbindDataBinds(); + void sortDataBinds(); + +private: + void updateDataBind(DataBind* dataBind, bool applyTargetToSource); + std::vector m_dataBinds; + std::vector m_persistingDataBinds; + std::vector m_dirtyDataBinds; + std::vector m_pendingDirtyDataBinds; + bool m_isProcessing = false; +}; +} // namespace rive + +#endif \ No newline at end of file diff --git a/defold-rive/include/rive/data_bind/data_bind_context.hpp b/defold-rive/include/rive/data_bind/data_bind_context.hpp index 45b069e0..818f8e75 100644 --- a/defold-rive/include/rive/data_bind/data_bind_context.hpp +++ b/defold-rive/include/rive/data_bind/data_bind_context.hpp @@ -17,6 +17,10 @@ class DataBindContext : public DataBindContextBase void decodeSourcePathIds(Span value) override; void copySourcePathIds(const DataBindContextBase& object) override; void bindFromContext(DataContext* dataContext); + +private: + void resolvePath(); + bool m_isPathResolved = false; }; } // namespace rive diff --git a/defold-rive/include/rive/data_bind/data_bind_path.hpp b/defold-rive/include/rive/data_bind/data_bind_path.hpp new file mode 100644 index 00000000..589d2914 --- /dev/null +++ b/defold-rive/include/rive/data_bind/data_bind_path.hpp @@ -0,0 +1,29 @@ +#ifndef _RIVE_DATA_BIND_PATH_HPP_ +#define _RIVE_DATA_BIND_PATH_HPP_ +#include "rive/generated/data_bind/data_bind_path_base.hpp" +#include +namespace rive +{ +class File; +class DataBindPath : public DataBindPathBase +{ +public: + void decodePath(Span value) override; + void copyPath(const DataBindPathBase& object) override; + StatusCode import(ImportStack& importStack) override; + std::vector& path() { return m_pathBuffer; } + const std::vector& resolvedPath(); + void file(File* value); + File* file() { return m_file; }; + void resolved(bool value) { m_resolved = value; } + +protected: + std::vector m_pathBuffer; + +private: + File* m_file = nullptr; + bool m_resolved = false; +}; +} // namespace rive + +#endif \ No newline at end of file diff --git a/defold-rive/include/rive/data_bind/data_context.hpp b/defold-rive/include/rive/data_bind/data_context.hpp index 9329bb70..1b3c3691 100644 --- a/defold-rive/include/rive/data_bind/data_context.hpp +++ b/defold-rive/include/rive/data_bind/data_context.hpp @@ -2,10 +2,12 @@ #define _RIVE_DATA_CONTEXT_HPP_ #include "rive/viewmodel/viewmodel_instance_value.hpp" #include "rive/viewmodel/viewmodel_instance.hpp" +#include "rive/data_resolver.hpp" #include "rive/refcnt.hpp" namespace rive { +class DataBindPath; class DataContext { private: @@ -19,8 +21,16 @@ class DataContext void parent(DataContext* value) { m_Parent = value; } ViewModelInstanceValue* getViewModelProperty( const std::vector path) const; + ViewModelInstanceValue* getRelativeViewModelProperty( + const std::vector path, + DataResolver* resolver) const; + ViewModelInstanceValue* getViewModelProperty(DataBindPath* dataBindPath); rcp getViewModelInstance( const std::vector path) const; + rcp getViewModelInstance(DataBindPath*) const; + rcp getRelativeViewModelInstance( + const std::vector path, + DataResolver* resolver) const; void viewModelInstance(rcp value); void advanced(); rcp viewModelInstance() { return m_ViewModelInstance; }; diff --git a/defold-rive/include/rive/data_bind/data_values/data_type.hpp b/defold-rive/include/rive/data_bind/data_values/data_type.hpp index 91ed9415..2e7debe3 100644 --- a/defold-rive/include/rive/data_bind/data_values/data_type.hpp +++ b/defold-rive/include/rive/data_bind/data_values/data_type.hpp @@ -45,7 +45,9 @@ enum class DataType : unsigned int artboard = 12, /// Special case, this type is used to indicate it uses the input type. - input = 99 + input = 99, + + any = 100 }; } // namespace rive #endif \ No newline at end of file diff --git a/defold-rive/include/rive/data_bind/data_values/data_value_asset_image.hpp b/defold-rive/include/rive/data_bind/data_values/data_value_asset_image.hpp index 9e4c2172..2ee9da6c 100644 --- a/defold-rive/include/rive/data_bind/data_values/data_value_asset_image.hpp +++ b/defold-rive/include/rive/data_bind/data_values/data_value_asset_image.hpp @@ -1,6 +1,8 @@ #ifndef _RIVE_DATA_VALUE_ASSET_IMAGE_HPP_ #define _RIVE_DATA_VALUE_ASSET_IMAGE_HPP_ #include "rive/data_bind/data_values/data_value_integer.hpp" +#include "rive/assets/image_asset.hpp" +#include "rive/renderer.hpp" #include namespace rive @@ -8,14 +10,26 @@ namespace rive class DataValueAssetImage : public DataValueInteger { public: - DataValueAssetImage(uint32_t value) : DataValueInteger(value) {}; - DataValueAssetImage() : DataValueInteger(-1) {}; + DataValueAssetImage(uint32_t value) : + DataValueInteger(value), + m_fileAsset(rcp(new ImageAsset())) {}; + DataValueAssetImage() : + DataValueInteger(-1), m_fileAsset(rcp(new ImageAsset())) {}; static const DataType typeKey = DataType::assetImage; bool isTypeOf(DataType typeKey) const override { return typeKey == DataType::assetImage || typeKey == DataType::integer; }; constexpr static uint32_t defaultValue = -1; + rcp fileAsset() { return m_fileAsset; } + void imageValue(RenderImage* image) + { + m_fileAsset->renderImage(ref_rcp(image)); + } + RenderImage* imageValue() { return m_fileAsset->renderImage(); } + +private: + rcp m_fileAsset = nullptr; }; } // namespace rive #endif \ No newline at end of file diff --git a/defold-rive/include/rive/data_bind/data_values/data_value_color.hpp b/defold-rive/include/rive/data_bind/data_values/data_value_color.hpp index 4565a1e5..d204d9a2 100644 --- a/defold-rive/include/rive/data_bind/data_values/data_value_color.hpp +++ b/defold-rive/include/rive/data_bind/data_values/data_value_color.hpp @@ -21,6 +21,14 @@ class DataValueColor : public DataValue } int value() { return m_value; }; void value(int value) { m_value = value; }; + int alpha() { return (m_value >> 24) & 0xFF; } + int red() { return (m_value >> 16) & 0xFF; } + int green() { return (m_value >> 8) & 0xFF; } + int blue() { return m_value & 0xFF; } + void alpha(int value) { m_value = (m_value & 0x00FFFFFF) | (value << 24); } + void red(int value) { m_value = (m_value & 0xFF00FFFF) | (value << 16); } + void green(int value) { m_value = (m_value & 0xFFFF00FF) | (value << 8); } + void blue(int value) { m_value = (m_value & 0xFFFFFF00) | value; } bool compare(DataValue* comparand) override { if (comparand->is()) diff --git a/defold-rive/include/rive/data_bind/data_values/data_value_string.hpp b/defold-rive/include/rive/data_bind/data_values/data_value_string.hpp index 09ad9062..0a6fd3b4 100644 --- a/defold-rive/include/rive/data_bind/data_values/data_value_string.hpp +++ b/defold-rive/include/rive/data_bind/data_values/data_value_string.hpp @@ -18,7 +18,7 @@ class DataValueString : public DataValue { return typeKey == DataType::string; }; - std::string value() { return m_value; }; + const std::string& value() { return m_value; }; void value(std::string value) { m_value = value; }; constexpr static const char* defaultValue = ""; }; diff --git a/defold-rive/include/rive/data_bind_flags.hpp b/defold-rive/include/rive/data_bind_flags.hpp index 61b8e86e..fc15e2ed 100644 --- a/defold-rive/include/rive/data_bind_flags.hpp +++ b/defold-rive/include/rive/data_bind_flags.hpp @@ -19,6 +19,9 @@ enum class DataBindFlags : unsigned short /// Whether source to target runs before target to source SourceToTargetRunsFirst = 1 << 3, + /// Whether source to target runs before target to source + NameBased = 1 << 4, + /// Flag if set to target ToTarget = 0, diff --git a/defold-rive/include/rive/data_bind_path_referencer.hpp b/defold-rive/include/rive/data_bind_path_referencer.hpp new file mode 100644 index 00000000..429a61f6 --- /dev/null +++ b/defold-rive/include/rive/data_bind_path_referencer.hpp @@ -0,0 +1,23 @@ +#ifndef _RIVE_DATA_BIND_PATH_REFERENCER_HPP_ +#define _RIVE_DATA_BIND_PATH_REFERENCER_HPP_ +#include +#include "rive/data_bind/data_bind_path.hpp" +namespace rive +{ +class File; +class DataBindPathReferencer +{ +public: + ~DataBindPathReferencer(); + DataBindPath* dataBindPath() const { return m_dataBindPath; } + + void copyDataBindPath(DataBindPath* dataBindPath); + void importDataBindPath(ImportStack& importStack); + void decodeDataBindPath(Span& value); + +protected: + DataBindPath* m_dataBindPath = nullptr; +}; +} // namespace rive + +#endif \ No newline at end of file diff --git a/defold-rive/include/rive/data_resolver.hpp b/defold-rive/include/rive/data_resolver.hpp new file mode 100644 index 00000000..75d47643 --- /dev/null +++ b/defold-rive/include/rive/data_resolver.hpp @@ -0,0 +1,15 @@ +#ifndef _RIVE_DATA_RESOLVER_HPP_ +#define _RIVE_DATA_RESOLVER_HPP_ +#include +#include +namespace rive +{ +class DataResolver +{ +public: + virtual const std::string& resolveName(int id) = 0; + virtual const std::vector& resolvePath(int id) = 0; +}; +} // namespace rive + +#endif \ No newline at end of file diff --git a/defold-rive/include/rive/drawable.hpp b/defold-rive/include/rive/drawable.hpp index b2024c28..33cc56ab 100644 --- a/defold-rive/include/rive/drawable.hpp +++ b/defold-rive/include/rive/drawable.hpp @@ -27,9 +27,11 @@ class Drawable : public DrawableBase Drawable* prev = nullptr; Drawable* next = nullptr; +protected: + bool m_needsSaveOperation = true; + public: BlendMode blendMode() const { return (BlendMode)blendModeValue(); } - ClipResult applyClip(Renderer* renderer) const; virtual void draw(Renderer* renderer) = 0; virtual Core* hitTest(HitInfo*, const Mat2D&) = 0; bool hitTestPoint(const Vec2D& position, @@ -55,12 +57,19 @@ class Drawable : public DrawableBase } virtual bool isProxy() { return false; } + virtual bool isClipStart() { return false; } + virtual bool isClipEnd() { return false; } + virtual bool willClip() { return false; } + virtual bool willDraw(); + void needsSaveOperation(bool value) { m_needsSaveOperation = value; } bool isChildOfLayout(LayoutComponent* layout); StatusCode onAddedDirty(CoreContext* context) override; virtual Drawable* hittableComponent() { return this; } + + virtual int emptyClipCount() { return 0; } }; class ProxyDrawing diff --git a/defold-rive/include/rive/file.hpp b/defold-rive/include/rive/file.hpp index 6a40305e..93215f82 100644 --- a/defold-rive/include/rive/file.hpp +++ b/defold-rive/include/rive/file.hpp @@ -5,6 +5,8 @@ #include "rive/backboard.hpp" #include "rive/factory.hpp" #include "rive/file_asset_loader.hpp" +#include "rive/assets/manifest_asset.hpp" +#include "rive/lua/lua_state.hpp" #include "rive/viewmodel/data_enum.hpp" #include "rive/viewmodel/viewmodel_component.hpp" #include "rive/viewmodel/viewmodel_instance.hpp" @@ -12,7 +14,9 @@ #include "rive/viewmodel/viewmodel_instance_viewmodel.hpp" #include "rive/viewmodel/viewmodel_instance_list_item.hpp" #include "rive/animation/keyframe_interpolator.hpp" +#include "rive/data_bind/converters/data_converter.hpp" #include "rive/refcnt.hpp" +#include "rive/data_resolver.hpp" #include #include #include @@ -22,11 +26,21 @@ /// namespace rive { +#ifdef WITH_RIVE_TOOLS +class ViewModelInstance; +typedef void (*ViewModelInstanceCreated)(ViewModelInstance* instance); +#endif class BinaryReader; +class DataBind; class RuntimeHeader; class Factory; class ScrollPhysics; class ViewModelRuntime; +class BindableArtboard; +#ifdef WITH_RIVE_SCRIPTING +class CPPRuntimeScriptingContext; +class ScriptingVM; +#endif /// /// Tracks the success/failure result when importing a Rive file. @@ -92,6 +106,9 @@ class File : public RefCnt std::unique_ptr artboardDefault() const; std::unique_ptr artboardAt(size_t index) const; std::unique_ptr artboardNamed(std::string name) const; + rcp bindableArtboardNamed(std::string name) const; + rcp bindableArtboardDefault() const; + rcp internalBindableArtboardFromArtboard(Artboard*) const; Artboard* artboard() const; @@ -155,6 +172,37 @@ class File : public RefCnt std::vector artboards() { return m_artboards; }; + // When the runtime is hosted in the editor, we get a pointer + // to the VM that we can use. If this is nullptr, we can assume + // we are running in the runtime and should instance our own VMs + // and pass them down to the root +#ifdef WITH_RIVE_SCRIPTING + void scriptingVM(LuaState* vm) + { + cleanupScriptingVM(); + m_luaState = vm; + } + LuaState* scriptingVM() + { + // For now, if we don't have a vm, create one. In the future, we + // may need a way to create multiple vms in parallel + if (m_luaState == nullptr) + { + makeScriptingVM(); + } + return m_luaState; + } +#endif + + DataResolver* dataResolver() + { + if (m_manifest) + { + return m_manifest.get()->as(); + } + return nullptr; + } + #ifdef WITH_RIVE_TOOLS /// Strips FileAssetContents for FileAssets of given typeKeys. /// @param data the raw data of the file. @@ -173,6 +221,16 @@ class File : public RefCnt return m_assetLoader.get(); } #endif +#ifdef WITH_RIVE_TOOLS + void onViewModelInstanceCreated(ViewModelInstanceCreated callback) + { + m_viewmodelInstanceCreatedCallback = callback; + } + void triggerViewModelCreatedCallback(bool value) + { + m_triggerViewModelCreatedCallback = value; + } +#endif private: ImportResult read(BinaryReader&, const RuntimeHeader&); @@ -211,6 +269,15 @@ class File : public RefCnt /// with the file. rcp m_assetLoader; +#ifdef WITH_RIVE_SCRIPTING + LuaState* m_luaState = nullptr; + std::unique_ptr m_scriptingContext; + std::unique_ptr m_scriptingVM; + void makeScriptingVM(); + void cleanupScriptingVM(); + void registerScripts(); +#endif + rcp copyViewModelInstance( ViewModelInstance* viewModelInstance, std::unordered_map>& @@ -219,6 +286,12 @@ class File : public RefCnt rcp createViewModelRuntime(ViewModel* viewModel) const; uint32_t findViewModelId(ViewModel* search) const; +#ifdef WITH_RIVE_TOOLS + ViewModelInstanceCreated m_viewmodelInstanceCreatedCallback = nullptr; + bool m_triggerViewModelCreatedCallback = false; +#endif + + rcp m_manifest = nullptr; }; } // namespace rive #endif diff --git a/defold-rive/include/rive/generated/animation/transition_value_artboard_comparator_base.hpp b/defold-rive/include/rive/generated/animation/transition_value_artboard_comparator_base.hpp new file mode 100644 index 00000000..cc9f8d9f --- /dev/null +++ b/defold-rive/include/rive/generated/animation/transition_value_artboard_comparator_base.hpp @@ -0,0 +1,38 @@ +#ifndef _RIVE_TRANSITION_VALUE_ARTBOARD_COMPARATOR_BASE_HPP_ +#define _RIVE_TRANSITION_VALUE_ARTBOARD_COMPARATOR_BASE_HPP_ +#include "rive/animation/transition_value_id_comparator.hpp" +namespace rive +{ +class TransitionValueArtboardComparatorBase : public TransitionValueIdComparator +{ +protected: + typedef TransitionValueIdComparator Super; + +public: + static const uint16_t typeKey = 630; + + /// Helper to quickly determine if a core object extends another without + /// RTTI at runtime. + bool isTypeOf(uint16_t typeKey) const override + { + switch (typeKey) + { + case TransitionValueArtboardComparatorBase::typeKey: + case TransitionValueIdComparatorBase::typeKey: + case TransitionValueComparatorBase::typeKey: + case TransitionComparatorBase::typeKey: + return true; + default: + return false; + } + } + + uint16_t coreType() const override { return typeKey; } + + Core* clone() const override; + +protected: +}; +} // namespace rive + +#endif \ No newline at end of file diff --git a/defold-rive/include/rive/generated/assets/file_asset_contents_base.hpp b/defold-rive/include/rive/generated/assets/file_asset_contents_base.hpp index aff6735f..0c5402c7 100644 --- a/defold-rive/include/rive/generated/assets/file_asset_contents_base.hpp +++ b/defold-rive/include/rive/generated/assets/file_asset_contents_base.hpp @@ -29,13 +29,21 @@ class FileAssetContentsBase : public Core uint16_t coreType() const override { return typeKey; } static const uint16_t bytesPropertyKey = 212; + static const uint16_t signaturePropertyKey = 911; public: virtual void decodeBytes(Span value) = 0; virtual void copyBytes(const FileAssetContentsBase& object) = 0; + virtual void decodeSignature(Span value) = 0; + virtual void copySignature(const FileAssetContentsBase& object) = 0; + Core* clone() const override; - void copy(const FileAssetContentsBase& object) { copyBytes(object); } + void copy(const FileAssetContentsBase& object) + { + copyBytes(object); + copySignature(object); + } bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { @@ -44,12 +52,16 @@ class FileAssetContentsBase : public Core case bytesPropertyKey: decodeBytes(CoreBytesType::deserialize(reader)); return true; + case signaturePropertyKey: + decodeSignature(CoreBytesType::deserialize(reader)); + return true; } return false; } protected: virtual void bytesChanged() {} + virtual void signatureChanged() {} }; } // namespace rive diff --git a/defold-rive/include/rive/generated/assets/manifest_asset_base.hpp b/defold-rive/include/rive/generated/assets/manifest_asset_base.hpp new file mode 100644 index 00000000..de7a7f90 --- /dev/null +++ b/defold-rive/include/rive/generated/assets/manifest_asset_base.hpp @@ -0,0 +1,37 @@ +#ifndef _RIVE_MANIFEST_ASSET_BASE_HPP_ +#define _RIVE_MANIFEST_ASSET_BASE_HPP_ +#include "rive/assets/file_asset.hpp" +namespace rive +{ +class ManifestAssetBase : public FileAsset +{ +protected: + typedef FileAsset Super; + +public: + static const uint16_t typeKey = 642; + + /// Helper to quickly determine if a core object extends another without + /// RTTI at runtime. + bool isTypeOf(uint16_t typeKey) const override + { + switch (typeKey) + { + case ManifestAssetBase::typeKey: + case FileAssetBase::typeKey: + case AssetBase::typeKey: + return true; + default: + return false; + } + } + + uint16_t coreType() const override { return typeKey; } + + Core* clone() const override; + +protected: +}; +} // namespace rive + +#endif \ No newline at end of file diff --git a/defold-rive/include/rive/generated/assets/script_asset_base.hpp b/defold-rive/include/rive/generated/assets/script_asset_base.hpp new file mode 100644 index 00000000..34b1577d --- /dev/null +++ b/defold-rive/include/rive/generated/assets/script_asset_base.hpp @@ -0,0 +1,94 @@ +#ifndef _RIVE_SCRIPT_ASSET_BASE_HPP_ +#define _RIVE_SCRIPT_ASSET_BASE_HPP_ +#include "rive/assets/file_asset.hpp" +#include "rive/core/field_types/core_bool_type.hpp" +#include "rive/core/field_types/core_uint_type.hpp" +namespace rive +{ +class ScriptAssetBase : public FileAsset +{ +protected: + typedef FileAsset Super; + +public: + static const uint16_t typeKey = 529; + + /// Helper to quickly determine if a core object extends another without + /// RTTI at runtime. + bool isTypeOf(uint16_t typeKey) const override + { + switch (typeKey) + { + case ScriptAssetBase::typeKey: + case FileAssetBase::typeKey: + case AssetBase::typeKey: + return true; + default: + return false; + } + } + + uint16_t coreType() const override { return typeKey; } + + static const uint16_t generatorFunctionRefPropertyKey = 893; + static const uint16_t isModulePropertyKey = 914; + +protected: + uint32_t m_GeneratorFunctionRef = 0; + bool m_IsModule = false; + +public: + inline uint32_t generatorFunctionRef() const + { + return m_GeneratorFunctionRef; + } + void generatorFunctionRef(uint32_t value) + { + if (m_GeneratorFunctionRef == value) + { + return; + } + m_GeneratorFunctionRef = value; + generatorFunctionRefChanged(); + } + + inline bool isModule() const { return m_IsModule; } + void isModule(bool value) + { + if (m_IsModule == value) + { + return; + } + m_IsModule = value; + isModuleChanged(); + } + + Core* clone() const override; + void copy(const ScriptAssetBase& object) + { + m_GeneratorFunctionRef = object.m_GeneratorFunctionRef; + m_IsModule = object.m_IsModule; + FileAsset::copy(object); + } + + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override + { + switch (propertyKey) + { + case generatorFunctionRefPropertyKey: + m_GeneratorFunctionRef = CoreUintType::deserialize(reader); + return true; + case isModulePropertyKey: + m_IsModule = CoreBoolType::deserialize(reader); + return true; + } + return FileAsset::deserialize(propertyKey, reader); + } + +protected: + virtual void generatorFunctionRefChanged() {} + virtual void isModuleChanged() {} +}; +} // namespace rive + +#endif \ No newline at end of file diff --git a/defold-rive/include/rive/generated/constraints/scrolling/scroll_constraint_base.hpp b/defold-rive/include/rive/generated/constraints/scrolling/scroll_constraint_base.hpp index f2113649..14f6f66c 100644 --- a/defold-rive/include/rive/generated/constraints/scrolling/scroll_constraint_base.hpp +++ b/defold-rive/include/rive/generated/constraints/scrolling/scroll_constraint_base.hpp @@ -42,6 +42,8 @@ class ScrollConstraintBase : public DraggableConstraint static const uint16_t physicsIdPropertyKey = 726; static const uint16_t virtualizePropertyKey = 850; static const uint16_t infinitePropertyKey = 851; + static const uint16_t interactivePropertyKey = 891; + static const uint16_t thresholdPropertyKey = 894; protected: float m_ScrollOffsetX = 0.0f; @@ -51,6 +53,8 @@ class ScrollConstraintBase : public DraggableConstraint uint32_t m_PhysicsId = -1; bool m_Virtualize = false; bool m_Infinite = false; + bool m_Interactive = true; + float m_Threshold = 0.0f; public: inline float scrollOffsetX() const { return m_ScrollOffsetX; } @@ -166,6 +170,28 @@ class ScrollConstraintBase : public DraggableConstraint infiniteChanged(); } + inline bool interactive() const { return m_Interactive; } + void interactive(bool value) + { + if (m_Interactive == value) + { + return; + } + m_Interactive = value; + interactiveChanged(); + } + + inline float threshold() const { return m_Threshold; } + void threshold(float value) + { + if (m_Threshold == value) + { + return; + } + m_Threshold = value; + thresholdChanged(); + } + Core* clone() const override; void copy(const ScrollConstraintBase& object) { @@ -176,6 +202,8 @@ class ScrollConstraintBase : public DraggableConstraint m_PhysicsId = object.m_PhysicsId; m_Virtualize = object.m_Virtualize; m_Infinite = object.m_Infinite; + m_Interactive = object.m_Interactive; + m_Threshold = object.m_Threshold; DraggableConstraint::copy(object); } @@ -204,6 +232,12 @@ class ScrollConstraintBase : public DraggableConstraint case infinitePropertyKey: m_Infinite = CoreBoolType::deserialize(reader); return true; + case interactivePropertyKey: + m_Interactive = CoreBoolType::deserialize(reader); + return true; + case thresholdPropertyKey: + m_Threshold = CoreDoubleType::deserialize(reader); + return true; } return DraggableConstraint::deserialize(propertyKey, reader); } @@ -219,6 +253,8 @@ class ScrollConstraintBase : public DraggableConstraint virtual void physicsIdChanged() {} virtual void virtualizeChanged() {} virtual void infiniteChanged() {} + virtual void interactiveChanged() {} + virtual void thresholdChanged() {} }; } // namespace rive diff --git a/defold-rive/include/rive/generated/core_registry.hpp b/defold-rive/include/rive/generated/core_registry.hpp index 141f0f64..c0469f8d 100644 --- a/defold-rive/include/rive/generated/core_registry.hpp +++ b/defold-rive/include/rive/generated/core_registry.hpp @@ -74,6 +74,7 @@ #include "rive/animation/transition_property_viewmodel_comparator.hpp" #include "rive/animation/transition_self_comparator.hpp" #include "rive/animation/transition_trigger_condition.hpp" +#include "rive/animation/transition_value_artboard_comparator.hpp" #include "rive/animation/transition_value_asset_comparator.hpp" #include "rive/animation/transition_value_boolean_comparator.hpp" #include "rive/animation/transition_value_color_comparator.hpp" @@ -96,6 +97,8 @@ #include "rive/assets/folder.hpp" #include "rive/assets/font_asset.hpp" #include "rive/assets/image_asset.hpp" +#include "rive/assets/manifest_asset.hpp" +#include "rive/assets/script_asset.hpp" #include "rive/audio_event.hpp" #include "rive/backboard.hpp" #include "rive/bones/bone.hpp" @@ -178,6 +181,7 @@ #include "rive/data_bind/converters/formula/formula_token_value.hpp" #include "rive/data_bind/data_bind.hpp" #include "rive/data_bind/data_bind_context.hpp" +#include "rive/data_bind/data_bind_path.hpp" #include "rive/draw_rules.hpp" #include "rive/draw_target.hpp" #include "rive/drawable.hpp" @@ -199,6 +203,17 @@ #include "rive/nested_artboard_leaf.hpp" #include "rive/node.hpp" #include "rive/open_url_event.hpp" +#include "rive/script_input_artboard.hpp" +#include "rive/script_input_boolean.hpp" +#include "rive/script_input_color.hpp" +#include "rive/script_input_number.hpp" +#include "rive/script_input_string.hpp" +#include "rive/script_input_trigger.hpp" +#include "rive/script_input_viewmodel_property.hpp" +#include "rive/scripted/scripted_data_converter.hpp" +#include "rive/scripted/scripted_drawable.hpp" +#include "rive/scripted/scripted_layout.hpp" +#include "rive/scripted/scripted_path_effect.hpp" #include "rive/shapes/clipping_shape.hpp" #include "rive/shapes/contour_mesh_vertex.hpp" #include "rive/shapes/cubic_asymmetric_vertex.hpp" @@ -215,11 +230,13 @@ #include "rive/shapes/paint/feather.hpp" #include "rive/shapes/paint/fill.hpp" #include "rive/shapes/paint/gradient_stop.hpp" +#include "rive/shapes/paint/group_effect.hpp" #include "rive/shapes/paint/linear_gradient.hpp" #include "rive/shapes/paint/radial_gradient.hpp" #include "rive/shapes/paint/shape_paint.hpp" #include "rive/shapes/paint/solid_color.hpp" #include "rive/shapes/paint/stroke.hpp" +#include "rive/shapes/paint/target_effect.hpp" #include "rive/shapes/paint/trim_path.hpp" #include "rive/shapes/parametric_path.hpp" #include "rive/shapes/path.hpp" @@ -372,10 +389,16 @@ class CoreRegistry return new ViewModelInstanceAssetImage(); case DataEnumValueBase::typeKey: return new DataEnumValue(); + case CustomPropertyTriggerBase::typeKey: + return new CustomPropertyTrigger(); + case ScriptInputTriggerBase::typeKey: + return new ScriptInputTrigger(); case DrawTargetBase::typeKey: return new DrawTarget(); case CustomPropertyNumberBase::typeKey: return new CustomPropertyNumber(); + case ScriptInputViewModelPropertyBase::typeKey: + return new ScriptInputViewModelProperty(); case DistanceConstraintBase::typeKey: return new DistanceConstraint(); case FollowPathConstraintBase::typeKey: @@ -412,6 +435,16 @@ class CoreRegistry return new CustomPropertyColor(); case SoloBase::typeKey: return new Solo(); + case ScriptedDrawableBase::typeKey: + return new ScriptedDrawable(); + case ScriptedDataConverterBase::typeKey: + return new ScriptedDataConverter(); + case ScriptedLayoutBase::typeKey: + return new ScriptedLayout(); + case ScriptedPathEffectBase::typeKey: + return new ScriptedPathEffect(); + case ScriptInputNumberBase::typeKey: + return new ScriptInputNumber(); case NestedArtboardLayoutBase::typeKey: return new NestedArtboardLayout(); case NSlicerTileModeBase::typeKey: @@ -536,6 +569,8 @@ class CoreRegistry return new TransitionValueEnumComparator(); case KeyFrameCallbackBase::typeKey: return new KeyFrameCallback(); + case TransitionValueArtboardComparatorBase::typeKey: + return new TransitionValueArtboardComparator(); case TransitionValueStringComparatorBase::typeKey: return new TransitionValueStringComparator(); case NestedRemapAnimationBase::typeKey: @@ -552,6 +587,10 @@ class CoreRegistry return new StateMachineBool(); case BlendAnimation1DBase::typeKey: return new BlendAnimation1D(); + case GroupEffectBase::typeKey: + return new GroupEffect(); + case TargetEffectBase::typeKey: + return new TargetEffect(); case DashPathBase::typeKey: return new DashPath(); case LinearGradientBase::typeKey: @@ -610,10 +649,14 @@ class CoreRegistry return new CustomPropertyGroup(); case EventBase::typeKey: return new Event(); - case DrawRulesBase::typeKey: - return new DrawRules(); case CustomPropertyBooleanBase::typeKey: return new CustomPropertyBoolean(); + case ScriptInputBooleanBase::typeKey: + return new ScriptInputBoolean(); + case ScriptInputColorBase::typeKey: + return new ScriptInputColor(); + case DrawRulesBase::typeKey: + return new DrawRules(); case LayoutComponentBase::typeKey: return new LayoutComponent(); case ArtboardBase::typeKey: @@ -624,8 +667,14 @@ class CoreRegistry return new Backboard(); case OpenUrlEventBase::typeKey: return new OpenUrlEvent(); + case CustomPropertyStringBase::typeKey: + return new CustomPropertyString(); + case ScriptInputStringBase::typeKey: + return new ScriptInputString(); case BindablePropertyArtboardBase::typeKey: return new BindablePropertyArtboard(); + case DataBindPathBase::typeKey: + return new DataBindPath(); case BindablePropertyIntegerBase::typeKey: return new BindablePropertyInteger(); case BindablePropertyTriggerBase::typeKey: @@ -752,10 +801,12 @@ class CoreRegistry return new TextValueRun(); case CustomPropertyEnumBase::typeKey: return new CustomPropertyEnum(); - case CustomPropertyStringBase::typeKey: - return new CustomPropertyString(); case FolderBase::typeKey: return new Folder(); + case ScriptAssetBase::typeKey: + return new ScriptAsset(); + case ManifestAssetBase::typeKey: + return new ManifestAsset(); case ImageAssetBase::typeKey: return new ImageAsset(); case FontAssetBase::typeKey: @@ -766,8 +817,8 @@ class CoreRegistry return new FileAssetContents(); case AudioEventBase::typeKey: return new AudioEvent(); - case CustomPropertyTriggerBase::typeKey: - return new CustomPropertyTrigger(); + case ScriptInputArtboardBase::typeKey: + return new ScriptInputArtboard(); } return nullptr; } @@ -831,6 +882,9 @@ class CoreRegistry case ViewModelInstanceAssetBase::propertyValuePropertyKey: object->as()->propertyValue(value); break; + case CustomPropertyTriggerBase::propertyValuePropertyKey: + object->as()->propertyValue(value); + break; case DrawTargetBase::drawableIdPropertyKey: object->as()->drawableId(value); break; @@ -892,6 +946,15 @@ class CoreRegistry case SoloBase::activeComponentIdPropertyKey: object->as()->activeComponentId(value); break; + case ScriptedDrawableBase::scriptAssetIdPropertyKey: + object->as()->scriptAssetId(value); + break; + case ScriptedDataConverterBase::scriptAssetIdPropertyKey: + object->as()->scriptAssetId(value); + break; + case ScriptedPathEffectBase::scriptAssetIdPropertyKey: + object->as()->scriptAssetId(value); + break; case NestedArtboardLayoutBase::instanceWidthUnitsValuePropertyKey: object->as()->instanceWidthUnitsValue( value); @@ -1234,6 +1297,9 @@ class CoreRegistry case ShapePaintBase::blendModeValuePropertyKey: object->as()->blendModeValue(value); break; + case TargetEffectBase::targetIdPropertyKey: + object->as()->targetId(value); + break; case StrokeBase::capPropertyKey: object->as()->cap(value); break; @@ -1457,11 +1523,14 @@ class CoreRegistry case FileAssetBase::assetIdPropertyKey: object->as()->assetId(value); break; + case ScriptAssetBase::generatorFunctionRefPropertyKey: + object->as()->generatorFunctionRef(value); + break; case AudioEventBase::assetIdPropertyKey: object->as()->assetId(value); break; - case CustomPropertyTriggerBase::propertyValuePropertyKey: - object->as()->propertyValue(value); + case ScriptInputArtboardBase::artboardIdPropertyKey: + object->as()->artboardId(value); break; } } @@ -1487,6 +1556,9 @@ class CoreRegistry case DataEnumValueBase::valuePropertyKey: object->as()->value(value); break; + case DataConverterBase::namePropertyKey: + object->as()->name(value); + break; case AnimationBase::namePropertyKey: object->as()->name(value); break; @@ -1502,8 +1574,8 @@ class CoreRegistry case OpenUrlEventBase::urlPropertyKey: object->as()->url(value); break; - case DataConverterBase::namePropertyKey: - object->as()->name(value); + case CustomPropertyStringBase::propertyValuePropertyKey: + object->as()->propertyValue(value); break; case DataConverterStringPadBase::textPropertyKey: object->as()->text(value); @@ -1520,9 +1592,6 @@ class CoreRegistry case TextValueRunBase::textPropertyKey: object->as()->text(value); break; - case CustomPropertyStringBase::propertyValuePropertyKey: - object->as()->propertyValue(value); - break; case AssetBase::namePropertyKey: object->as()->name(value); break; @@ -1606,9 +1675,15 @@ class CoreRegistry case ScrollConstraintBase::infinitePropertyKey: object->as()->infinite(value); break; + case ScrollConstraintBase::interactivePropertyKey: + object->as()->interactive(value); + break; case ScrollBarConstraintBase::autoSizePropertyKey: object->as()->autoSize(value); break; + case NestedArtboardBase::isPausedPropertyKey: + object->as()->isPaused(value); + break; case AxisBase::normalizedPropertyKey: object->as()->normalized(value); break; @@ -1677,6 +1752,9 @@ class CoreRegistry case LayoutComponentBase::clipPropertyKey: object->as()->clip(value); break; + case DataBindPathBase::isRelativePropertyKey: + object->as()->isRelative(value); + break; case BindablePropertyBooleanBase::propertyValuePropertyKey: object->as()->propertyValue(value); break; @@ -1692,6 +1770,9 @@ class CoreRegistry case TextBase::fitFromBaselinePropertyKey: object->as()->fitFromBaseline(value); break; + case ScriptAssetBase::isModulePropertyKey: + object->as()->isModule(value); + break; } } static void setDouble(Core* object, int propertyKey, float value) @@ -1757,6 +1838,9 @@ class CoreRegistry case ScrollConstraintBase::scrollIndexPropertyKey: object->as()->scrollIndex(value); break; + case ScrollConstraintBase::thresholdPropertyKey: + object->as()->threshold(value); + break; case ElasticScrollPhysicsBase::frictionPropertyKey: object->as()->friction(value); break; @@ -1816,6 +1900,12 @@ class CoreRegistry case NodeBase::computedHeightPropertyKey: object->as()->computedHeight(value); break; + case NestedArtboardBase::speedPropertyKey: + object->as()->speed(value); + break; + case NestedArtboardBase::quantizePropertyKey: + object->as()->quantize(value); + break; case NestedArtboardLayoutBase::instanceWidthPropertyKey: object->as()->instanceWidth(value); break; @@ -2357,15 +2447,15 @@ class CoreRegistry { switch (propertyKey) { + case CustomPropertyTriggerBase::firePropertyKey: + object->as()->fire(value); + break; case NestedTriggerBase::firePropertyKey: object->as()->fire(value); break; case EventBase::triggerPropertyKey: object->as()->trigger(value); break; - case CustomPropertyTriggerBase::firePropertyKey: - object->as()->fire(value); - break; } } static uint32_t getUint(Core* object, int propertyKey) @@ -2415,6 +2505,8 @@ class CoreRegistry case ViewModelInstanceAssetBase::propertyValuePropertyKey: return object->as() ->propertyValue(); + case CustomPropertyTriggerBase::propertyValuePropertyKey: + return object->as()->propertyValue(); case DrawTargetBase::drawableIdPropertyKey: return object->as()->drawableId(); case DrawTargetBase::placementValuePropertyKey: @@ -2457,6 +2549,12 @@ class CoreRegistry return object->as()->animationId(); case SoloBase::activeComponentIdPropertyKey: return object->as()->activeComponentId(); + case ScriptedDrawableBase::scriptAssetIdPropertyKey: + return object->as()->scriptAssetId(); + case ScriptedDataConverterBase::scriptAssetIdPropertyKey: + return object->as()->scriptAssetId(); + case ScriptedPathEffectBase::scriptAssetIdPropertyKey: + return object->as()->scriptAssetId(); case NestedArtboardLayoutBase::instanceWidthUnitsValuePropertyKey: return object->as() ->instanceWidthUnitsValue(); @@ -2707,6 +2805,8 @@ class CoreRegistry ->exitBlendAnimationId(); case ShapePaintBase::blendModeValuePropertyKey: return object->as()->blendModeValue(); + case TargetEffectBase::targetIdPropertyKey: + return object->as()->targetId(); case StrokeBase::capPropertyKey: return object->as()->cap(); case StrokeBase::joinPropertyKey: @@ -2861,10 +2961,12 @@ class CoreRegistry return object->as()->enumId(); case FileAssetBase::assetIdPropertyKey: return object->as()->assetId(); + case ScriptAssetBase::generatorFunctionRefPropertyKey: + return object->as()->generatorFunctionRef(); case AudioEventBase::assetIdPropertyKey: return object->as()->assetId(); - case CustomPropertyTriggerBase::propertyValuePropertyKey: - return object->as()->propertyValue(); + case ScriptInputArtboardBase::artboardIdPropertyKey: + return object->as()->artboardId(); } return 0; } @@ -2885,6 +2987,8 @@ class CoreRegistry return object->as()->key(); case DataEnumValueBase::valuePropertyKey: return object->as()->value(); + case DataConverterBase::namePropertyKey: + return object->as()->name(); case AnimationBase::namePropertyKey: return object->as()->name(); case StateMachineComponentBase::namePropertyKey: @@ -2896,8 +3000,8 @@ class CoreRegistry ->value(); case OpenUrlEventBase::urlPropertyKey: return object->as()->url(); - case DataConverterBase::namePropertyKey: - return object->as()->name(); + case CustomPropertyStringBase::propertyValuePropertyKey: + return object->as()->propertyValue(); case DataConverterStringPadBase::textPropertyKey: return object->as()->text(); case DataConverterToStringBase::colorFormatPropertyKey: @@ -2909,8 +3013,6 @@ class CoreRegistry return object->as()->text(); case TextValueRunBase::textPropertyKey: return object->as()->text(); - case CustomPropertyStringBase::propertyValuePropertyKey: - return object->as()->propertyValue(); case AssetBase::namePropertyKey: return object->as()->name(); case FileAssetBase::cdnBaseUrlPropertyKey: @@ -2976,8 +3078,12 @@ class CoreRegistry return object->as()->virtualize(); case ScrollConstraintBase::infinitePropertyKey: return object->as()->infinite(); + case ScrollConstraintBase::interactivePropertyKey: + return object->as()->interactive(); case ScrollBarConstraintBase::autoSizePropertyKey: return object->as()->autoSize(); + case NestedArtboardBase::isPausedPropertyKey: + return object->as()->isPaused(); case AxisBase::normalizedPropertyKey: return object->as()->normalized(); case LayoutComponentStyleBase::intrinsicallySizedValuePropertyKey: @@ -3025,6 +3131,8 @@ class CoreRegistry return object->as()->propertyValue(); case LayoutComponentBase::clipPropertyKey: return object->as()->clip(); + case DataBindPathBase::isRelativePropertyKey: + return object->as()->isRelative(); case BindablePropertyBooleanBase::propertyValuePropertyKey: return object->as() ->propertyValue(); @@ -3036,6 +3144,8 @@ class CoreRegistry return object->as()->orient(); case TextBase::fitFromBaselinePropertyKey: return object->as()->fitFromBaseline(); + case ScriptAssetBase::isModulePropertyKey: + return object->as()->isModule(); } return false; } @@ -3088,6 +3198,8 @@ class CoreRegistry return object->as()->scrollPercentY(); case ScrollConstraintBase::scrollIndexPropertyKey: return object->as()->scrollIndex(); + case ScrollConstraintBase::thresholdPropertyKey: + return object->as()->threshold(); case ElasticScrollPhysicsBase::frictionPropertyKey: return object->as()->friction(); case ElasticScrollPhysicsBase::speedMultiplierPropertyKey: @@ -3129,6 +3241,10 @@ class CoreRegistry return object->as()->computedWidth(); case NodeBase::computedHeightPropertyKey: return object->as()->computedHeight(); + case NestedArtboardBase::speedPropertyKey: + return object->as()->speed(); + case NestedArtboardBase::quantizePropertyKey: + return object->as()->quantize(); case NestedArtboardLayoutBase::instanceWidthPropertyKey: return object->as()->instanceWidth(); case NestedArtboardLayoutBase::instanceHeightPropertyKey: @@ -3513,6 +3629,7 @@ class CoreRegistry case ViewModelInstanceSymbolListIndexBase::propertyValuePropertyKey: case ViewModelInstanceViewModelBase::propertyValuePropertyKey: case ViewModelInstanceAssetBase::propertyValuePropertyKey: + case CustomPropertyTriggerBase::propertyValuePropertyKey: case DrawTargetBase::drawableIdPropertyKey: case DrawTargetBase::placementValuePropertyKey: case TargetedConstraintBase::targetIdPropertyKey: @@ -3532,6 +3649,9 @@ class CoreRegistry case ArtboardComponentListBase::listSourcePropertyKey: case NestedAnimationBase::animationIdPropertyKey: case SoloBase::activeComponentIdPropertyKey: + case ScriptedDrawableBase::scriptAssetIdPropertyKey: + case ScriptedDataConverterBase::scriptAssetIdPropertyKey: + case ScriptedPathEffectBase::scriptAssetIdPropertyKey: case NestedArtboardLayoutBase::instanceWidthUnitsValuePropertyKey: case NestedArtboardLayoutBase::instanceHeightUnitsValuePropertyKey: case NestedArtboardLayoutBase::instanceWidthScaleTypePropertyKey: @@ -3634,6 +3754,7 @@ class CoreRegistry case ElasticInterpolatorBase::easingValuePropertyKey: case BlendStateTransitionBase::exitBlendAnimationIdPropertyKey: case ShapePaintBase::blendModeValuePropertyKey: + case TargetEffectBase::targetIdPropertyKey: case StrokeBase::capPropertyKey: case StrokeBase::joinPropertyKey: case FeatherBase::spaceValuePropertyKey: @@ -3707,8 +3828,9 @@ class CoreRegistry case CustomPropertyEnumBase::propertyValuePropertyKey: case CustomPropertyEnumBase::enumIdPropertyKey: case FileAssetBase::assetIdPropertyKey: + case ScriptAssetBase::generatorFunctionRefPropertyKey: case AudioEventBase::assetIdPropertyKey: - case CustomPropertyTriggerBase::propertyValuePropertyKey: + case ScriptInputArtboardBase::artboardIdPropertyKey: return CoreUintType::id; case ViewModelComponentBase::namePropertyKey: case DataEnumCustomBase::namePropertyKey: @@ -3716,18 +3838,18 @@ class CoreRegistry case ComponentBase::namePropertyKey: case DataEnumValueBase::keyPropertyKey: case DataEnumValueBase::valuePropertyKey: + case DataConverterBase::namePropertyKey: case AnimationBase::namePropertyKey: case StateMachineComponentBase::namePropertyKey: case KeyFrameStringBase::valuePropertyKey: case TransitionValueStringComparatorBase::valuePropertyKey: case OpenUrlEventBase::urlPropertyKey: - case DataConverterBase::namePropertyKey: + case CustomPropertyStringBase::propertyValuePropertyKey: case DataConverterStringPadBase::textPropertyKey: case DataConverterToStringBase::colorFormatPropertyKey: case BindablePropertyStringBase::propertyValuePropertyKey: case TextInputBase::textPropertyKey: case TextValueRunBase::textPropertyKey: - case CustomPropertyStringBase::propertyValuePropertyKey: case AssetBase::namePropertyKey: case FileAssetBase::cdnBaseUrlPropertyKey: return CoreStringType::id; @@ -3753,7 +3875,9 @@ class CoreRegistry case ScrollConstraintBase::snapPropertyKey: case ScrollConstraintBase::virtualizePropertyKey: case ScrollConstraintBase::infinitePropertyKey: + case ScrollConstraintBase::interactivePropertyKey: case ScrollBarConstraintBase::autoSizePropertyKey: + case NestedArtboardBase::isPausedPropertyKey: case AxisBase::normalizedPropertyKey: case LayoutComponentStyleBase::intrinsicallySizedValuePropertyKey: case LayoutComponentStyleBase::linkCornerRadiusPropertyKey: @@ -3776,11 +3900,13 @@ class CoreRegistry case ClippingShapeBase::isVisiblePropertyKey: case CustomPropertyBooleanBase::propertyValuePropertyKey: case LayoutComponentBase::clipPropertyKey: + case DataBindPathBase::isRelativePropertyKey: case BindablePropertyBooleanBase::propertyValuePropertyKey: case TextModifierRangeBase::clampPropertyKey: case TextFollowPathModifierBase::radialPropertyKey: case TextFollowPathModifierBase::orientPropertyKey: case TextBase::fitFromBaselinePropertyKey: + case ScriptAssetBase::isModulePropertyKey: return CoreBoolType::id; case ViewModelInstanceNumberBase::propertyValuePropertyKey: case CustomPropertyNumberBase::propertyValuePropertyKey: @@ -3800,6 +3926,7 @@ class CoreRegistry case ScrollConstraintBase::scrollPercentXPropertyKey: case ScrollConstraintBase::scrollPercentYPropertyKey: case ScrollConstraintBase::scrollIndexPropertyKey: + case ScrollConstraintBase::thresholdPropertyKey: case ElasticScrollPhysicsBase::frictionPropertyKey: case ElasticScrollPhysicsBase::speedMultiplierPropertyKey: case ElasticScrollPhysicsBase::elasticFactorPropertyKey: @@ -3821,6 +3948,8 @@ class CoreRegistry case NodeBase::computedRootYPropertyKey: case NodeBase::computedWidthPropertyKey: case NodeBase::computedHeightPropertyKey: + case NestedArtboardBase::speedPropertyKey: + case NestedArtboardBase::quantizePropertyKey: case NestedArtboardLayoutBase::instanceWidthPropertyKey: case NestedArtboardLayoutBase::instanceHeightPropertyKey: case AxisBase::offsetPropertyKey: @@ -3999,14 +4128,17 @@ class CoreRegistry case DrawableAssetBase::widthPropertyKey: case ExportAudioBase::volumePropertyKey: return CoreDoubleType::id; + case ScriptInputViewModelPropertyBase::dataBindPathIdsPropertyKey: case NestedArtboardBase::dataBindPathIdsPropertyKey: case StateMachineFireTriggerBase::viewModelPathIdsPropertyKey: case StateMachineListenerBase::viewModelPathIdsPropertyKey: case MeshBase::triangleIndexBytesPropertyKey: + case DataBindPathBase::pathPropertyKey: case DataConverterOperationViewModelBase::sourcePathIdsPropertyKey: case DataBindContextBase::sourcePathIdsPropertyKey: case FileAssetBase::cdnUuidPropertyKey: case FileAssetContentsBase::bytesPropertyKey: + case FileAssetContentsBase::signaturePropertyKey: return CoreBytesType::id; default: return -1; @@ -4016,9 +4148,9 @@ class CoreRegistry { switch (propertyKey) { + case CustomPropertyTriggerBase::firePropertyKey: case NestedTriggerBase::firePropertyKey: case EventBase::triggerPropertyKey: - case CustomPropertyTriggerBase::firePropertyKey: return true; default: return false; @@ -4061,6 +4193,8 @@ class CoreRegistry return object->is(); case ViewModelInstanceAssetBase::propertyValuePropertyKey: return object->is(); + case CustomPropertyTriggerBase::propertyValuePropertyKey: + return object->is(); case DrawTargetBase::drawableIdPropertyKey: return object->is(); case DrawTargetBase::placementValuePropertyKey: @@ -4099,6 +4233,12 @@ class CoreRegistry return object->is(); case SoloBase::activeComponentIdPropertyKey: return object->is(); + case ScriptedDrawableBase::scriptAssetIdPropertyKey: + return object->is(); + case ScriptedDataConverterBase::scriptAssetIdPropertyKey: + return object->is(); + case ScriptedPathEffectBase::scriptAssetIdPropertyKey: + return object->is(); case NestedArtboardLayoutBase::instanceWidthUnitsValuePropertyKey: return object->is(); case NestedArtboardLayoutBase::instanceHeightUnitsValuePropertyKey: @@ -4298,6 +4438,8 @@ class CoreRegistry return object->is(); case ShapePaintBase::blendModeValuePropertyKey: return object->is(); + case TargetEffectBase::targetIdPropertyKey: + return object->is(); case StrokeBase::capPropertyKey: return object->is(); case StrokeBase::joinPropertyKey: @@ -4444,10 +4586,12 @@ class CoreRegistry return object->is(); case FileAssetBase::assetIdPropertyKey: return object->is(); + case ScriptAssetBase::generatorFunctionRefPropertyKey: + return object->is(); case AudioEventBase::assetIdPropertyKey: return object->is(); - case CustomPropertyTriggerBase::propertyValuePropertyKey: - return object->is(); + case ScriptInputArtboardBase::artboardIdPropertyKey: + return object->is(); case ViewModelComponentBase::namePropertyKey: return object->is(); case DataEnumCustomBase::namePropertyKey: @@ -4460,6 +4604,8 @@ class CoreRegistry return object->is(); case DataEnumValueBase::valuePropertyKey: return object->is(); + case DataConverterBase::namePropertyKey: + return object->is(); case AnimationBase::namePropertyKey: return object->is(); case StateMachineComponentBase::namePropertyKey: @@ -4470,8 +4616,8 @@ class CoreRegistry return object->is(); case OpenUrlEventBase::urlPropertyKey: return object->is(); - case DataConverterBase::namePropertyKey: - return object->is(); + case CustomPropertyStringBase::propertyValuePropertyKey: + return object->is(); case DataConverterStringPadBase::textPropertyKey: return object->is(); case DataConverterToStringBase::colorFormatPropertyKey: @@ -4482,8 +4628,6 @@ class CoreRegistry return object->is(); case TextValueRunBase::textPropertyKey: return object->is(); - case CustomPropertyStringBase::propertyValuePropertyKey: - return object->is(); case AssetBase::namePropertyKey: return object->is(); case FileAssetBase::cdnBaseUrlPropertyKey: @@ -4530,8 +4674,12 @@ class CoreRegistry return object->is(); case ScrollConstraintBase::infinitePropertyKey: return object->is(); + case ScrollConstraintBase::interactivePropertyKey: + return object->is(); case ScrollBarConstraintBase::autoSizePropertyKey: return object->is(); + case NestedArtboardBase::isPausedPropertyKey: + return object->is(); case AxisBase::normalizedPropertyKey: return object->is(); case LayoutComponentStyleBase::intrinsicallySizedValuePropertyKey: @@ -4576,6 +4724,8 @@ class CoreRegistry return object->is(); case LayoutComponentBase::clipPropertyKey: return object->is(); + case DataBindPathBase::isRelativePropertyKey: + return object->is(); case BindablePropertyBooleanBase::propertyValuePropertyKey: return object->is(); case TextModifierRangeBase::clampPropertyKey: @@ -4586,6 +4736,8 @@ class CoreRegistry return object->is(); case TextBase::fitFromBaselinePropertyKey: return object->is(); + case ScriptAssetBase::isModulePropertyKey: + return object->is(); case ViewModelInstanceNumberBase::propertyValuePropertyKey: return object->is(); case CustomPropertyNumberBase::propertyValuePropertyKey: @@ -4622,6 +4774,8 @@ class CoreRegistry return object->is(); case ScrollConstraintBase::scrollIndexPropertyKey: return object->is(); + case ScrollConstraintBase::thresholdPropertyKey: + return object->is(); case ElasticScrollPhysicsBase::frictionPropertyKey: return object->is(); case ElasticScrollPhysicsBase::speedMultiplierPropertyKey: @@ -4662,6 +4816,10 @@ class CoreRegistry return object->is(); case NodeBase::computedHeightPropertyKey: return object->is(); + case NestedArtboardBase::speedPropertyKey: + return object->is(); + case NestedArtboardBase::quantizePropertyKey: + return object->is(); case NestedArtboardLayoutBase::instanceWidthPropertyKey: return object->is(); case NestedArtboardLayoutBase::instanceHeightPropertyKey: @@ -5016,12 +5174,12 @@ class CoreRegistry return object->is(); case ExportAudioBase::volumePropertyKey: return object->is(); + case CustomPropertyTriggerBase::firePropertyKey: + return object->is(); case NestedTriggerBase::firePropertyKey: return object->is(); case EventBase::triggerPropertyKey: return object->is(); - case CustomPropertyTriggerBase::firePropertyKey: - return object->is(); } return false; } diff --git a/defold-rive/include/rive/generated/data_bind/data_bind_path_base.hpp b/defold-rive/include/rive/generated/data_bind/data_bind_path_base.hpp new file mode 100644 index 00000000..03627df3 --- /dev/null +++ b/defold-rive/include/rive/generated/data_bind/data_bind_path_base.hpp @@ -0,0 +1,80 @@ +#ifndef _RIVE_DATA_BIND_PATH_BASE_HPP_ +#define _RIVE_DATA_BIND_PATH_BASE_HPP_ +#include "rive/core.hpp" +#include "rive/core/field_types/core_bool_type.hpp" +#include "rive/core/field_types/core_bytes_type.hpp" +#include "rive/span.hpp" +namespace rive +{ +class DataBindPathBase : public Core +{ +protected: + typedef Core Super; + +public: + static const uint16_t typeKey = 643; + + /// Helper to quickly determine if a core object extends another without + /// RTTI at runtime. + bool isTypeOf(uint16_t typeKey) const override + { + switch (typeKey) + { + case DataBindPathBase::typeKey: + return true; + default: + return false; + } + } + + uint16_t coreType() const override { return typeKey; } + + static const uint16_t pathPropertyKey = 920; + static const uint16_t isRelativePropertyKey = 921; + +protected: + bool m_IsRelative = false; + +public: + virtual void decodePath(Span value) = 0; + virtual void copyPath(const DataBindPathBase& object) = 0; + + inline bool isRelative() const { return m_IsRelative; } + void isRelative(bool value) + { + if (m_IsRelative == value) + { + return; + } + m_IsRelative = value; + isRelativeChanged(); + } + + Core* clone() const override; + void copy(const DataBindPathBase& object) + { + copyPath(object); + m_IsRelative = object.m_IsRelative; + } + + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override + { + switch (propertyKey) + { + case pathPropertyKey: + decodePath(CoreBytesType::deserialize(reader)); + return true; + case isRelativePropertyKey: + m_IsRelative = CoreBoolType::deserialize(reader); + return true; + } + return false; + } + +protected: + virtual void pathChanged() {} + virtual void isRelativeChanged() {} +}; +} // namespace rive + +#endif \ No newline at end of file diff --git a/defold-rive/include/rive/generated/nested_artboard_base.hpp b/defold-rive/include/rive/generated/nested_artboard_base.hpp index 4b37dd82..eb9fb8c6 100644 --- a/defold-rive/include/rive/generated/nested_artboard_base.hpp +++ b/defold-rive/include/rive/generated/nested_artboard_base.hpp @@ -1,6 +1,8 @@ #ifndef _RIVE_NESTED_ARTBOARD_BASE_HPP_ #define _RIVE_NESTED_ARTBOARD_BASE_HPP_ +#include "rive/core/field_types/core_bool_type.hpp" #include "rive/core/field_types/core_bytes_type.hpp" +#include "rive/core/field_types/core_double_type.hpp" #include "rive/core/field_types/core_uint_type.hpp" #include "rive/drawable.hpp" #include "rive/span.hpp" @@ -37,9 +39,15 @@ class NestedArtboardBase : public Drawable static const uint16_t artboardIdPropertyKey = 197; static const uint16_t dataBindPathIdsPropertyKey = 582; + static const uint16_t isPausedPropertyKey = 895; + static const uint16_t speedPropertyKey = 907; + static const uint16_t quantizePropertyKey = 908; protected: uint32_t m_ArtboardId = -1; + bool m_IsPaused = false; + float m_Speed = 1.0f; + float m_Quantize = -1.0f; public: inline uint32_t artboardId() const { return m_ArtboardId; } @@ -56,11 +64,47 @@ class NestedArtboardBase : public Drawable virtual void decodeDataBindPathIds(Span value) = 0; virtual void copyDataBindPathIds(const NestedArtboardBase& object) = 0; + inline bool isPaused() const { return m_IsPaused; } + void isPaused(bool value) + { + if (m_IsPaused == value) + { + return; + } + m_IsPaused = value; + isPausedChanged(); + } + + inline float speed() const { return m_Speed; } + void speed(float value) + { + if (m_Speed == value) + { + return; + } + m_Speed = value; + speedChanged(); + } + + inline float quantize() const { return m_Quantize; } + void quantize(float value) + { + if (m_Quantize == value) + { + return; + } + m_Quantize = value; + quantizeChanged(); + } + Core* clone() const override; void copy(const NestedArtboardBase& object) { m_ArtboardId = object.m_ArtboardId; copyDataBindPathIds(object); + m_IsPaused = object.m_IsPaused; + m_Speed = object.m_Speed; + m_Quantize = object.m_Quantize; Drawable::copy(object); } @@ -74,6 +118,15 @@ class NestedArtboardBase : public Drawable case dataBindPathIdsPropertyKey: decodeDataBindPathIds(CoreBytesType::deserialize(reader)); return true; + case isPausedPropertyKey: + m_IsPaused = CoreBoolType::deserialize(reader); + return true; + case speedPropertyKey: + m_Speed = CoreDoubleType::deserialize(reader); + return true; + case quantizePropertyKey: + m_Quantize = CoreDoubleType::deserialize(reader); + return true; } return Drawable::deserialize(propertyKey, reader); } @@ -81,6 +134,9 @@ class NestedArtboardBase : public Drawable protected: virtual void artboardIdChanged() {} virtual void dataBindPathIdsChanged() {} + virtual void isPausedChanged() {} + virtual void speedChanged() {} + virtual void quantizeChanged() {} }; } // namespace rive diff --git a/defold-rive/include/rive/generated/script_input_artboard_base.hpp b/defold-rive/include/rive/generated/script_input_artboard_base.hpp new file mode 100644 index 00000000..1482b563 --- /dev/null +++ b/defold-rive/include/rive/generated/script_input_artboard_base.hpp @@ -0,0 +1,72 @@ +#ifndef _RIVE_SCRIPT_INPUT_ARTBOARD_BASE_HPP_ +#define _RIVE_SCRIPT_INPUT_ARTBOARD_BASE_HPP_ +#include "rive/core/field_types/core_uint_type.hpp" +#include "rive/custom_property.hpp" +namespace rive +{ +class ScriptInputArtboardBase : public CustomProperty +{ +protected: + typedef CustomProperty Super; + +public: + static const uint16_t typeKey = 621; + + /// Helper to quickly determine if a core object extends another without + /// RTTI at runtime. + bool isTypeOf(uint16_t typeKey) const override + { + switch (typeKey) + { + case ScriptInputArtboardBase::typeKey: + case CustomPropertyBase::typeKey: + case ComponentBase::typeKey: + return true; + default: + return false; + } + } + + uint16_t coreType() const override { return typeKey; } + + static const uint16_t artboardIdPropertyKey = 876; + +protected: + uint32_t m_ArtboardId = -1; + +public: + inline uint32_t artboardId() const { return m_ArtboardId; } + void artboardId(uint32_t value) + { + if (m_ArtboardId == value) + { + return; + } + m_ArtboardId = value; + artboardIdChanged(); + } + + Core* clone() const override; + void copy(const ScriptInputArtboardBase& object) + { + m_ArtboardId = object.m_ArtboardId; + CustomProperty::copy(object); + } + + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override + { + switch (propertyKey) + { + case artboardIdPropertyKey: + m_ArtboardId = CoreUintType::deserialize(reader); + return true; + } + return CustomProperty::deserialize(propertyKey, reader); + } + +protected: + virtual void artboardIdChanged() {} +}; +} // namespace rive + +#endif \ No newline at end of file diff --git a/defold-rive/include/rive/generated/script_input_boolean_base.hpp b/defold-rive/include/rive/generated/script_input_boolean_base.hpp new file mode 100644 index 00000000..e350391e --- /dev/null +++ b/defold-rive/include/rive/generated/script_input_boolean_base.hpp @@ -0,0 +1,38 @@ +#ifndef _RIVE_SCRIPT_INPUT_BOOLEAN_BASE_HPP_ +#define _RIVE_SCRIPT_INPUT_BOOLEAN_BASE_HPP_ +#include "rive/custom_property_boolean.hpp" +namespace rive +{ +class ScriptInputBooleanBase : public CustomPropertyBoolean +{ +protected: + typedef CustomPropertyBoolean Super; + +public: + static const uint16_t typeKey = 631; + + /// Helper to quickly determine if a core object extends another without + /// RTTI at runtime. + bool isTypeOf(uint16_t typeKey) const override + { + switch (typeKey) + { + case ScriptInputBooleanBase::typeKey: + case CustomPropertyBooleanBase::typeKey: + case CustomPropertyBase::typeKey: + case ComponentBase::typeKey: + return true; + default: + return false; + } + } + + uint16_t coreType() const override { return typeKey; } + + Core* clone() const override; + +protected: +}; +} // namespace rive + +#endif \ No newline at end of file diff --git a/defold-rive/include/rive/generated/script_input_color_base.hpp b/defold-rive/include/rive/generated/script_input_color_base.hpp new file mode 100644 index 00000000..e776eec0 --- /dev/null +++ b/defold-rive/include/rive/generated/script_input_color_base.hpp @@ -0,0 +1,38 @@ +#ifndef _RIVE_SCRIPT_INPUT_COLOR_BASE_HPP_ +#define _RIVE_SCRIPT_INPUT_COLOR_BASE_HPP_ +#include "rive/custom_property_color.hpp" +namespace rive +{ +class ScriptInputColorBase : public CustomPropertyColor +{ +protected: + typedef CustomPropertyColor Super; + +public: + static const uint16_t typeKey = 626; + + /// Helper to quickly determine if a core object extends another without + /// RTTI at runtime. + bool isTypeOf(uint16_t typeKey) const override + { + switch (typeKey) + { + case ScriptInputColorBase::typeKey: + case CustomPropertyColorBase::typeKey: + case CustomPropertyBase::typeKey: + case ComponentBase::typeKey: + return true; + default: + return false; + } + } + + uint16_t coreType() const override { return typeKey; } + + Core* clone() const override; + +protected: +}; +} // namespace rive + +#endif \ No newline at end of file diff --git a/defold-rive/include/rive/generated/script_input_number_base.hpp b/defold-rive/include/rive/generated/script_input_number_base.hpp new file mode 100644 index 00000000..72b0f684 --- /dev/null +++ b/defold-rive/include/rive/generated/script_input_number_base.hpp @@ -0,0 +1,38 @@ +#ifndef _RIVE_SCRIPT_INPUT_NUMBER_BASE_HPP_ +#define _RIVE_SCRIPT_INPUT_NUMBER_BASE_HPP_ +#include "rive/custom_property_number.hpp" +namespace rive +{ +class ScriptInputNumberBase : public CustomPropertyNumber +{ +protected: + typedef CustomPropertyNumber Super; + +public: + static const uint16_t typeKey = 611; + + /// Helper to quickly determine if a core object extends another without + /// RTTI at runtime. + bool isTypeOf(uint16_t typeKey) const override + { + switch (typeKey) + { + case ScriptInputNumberBase::typeKey: + case CustomPropertyNumberBase::typeKey: + case CustomPropertyBase::typeKey: + case ComponentBase::typeKey: + return true; + default: + return false; + } + } + + uint16_t coreType() const override { return typeKey; } + + Core* clone() const override; + +protected: +}; +} // namespace rive + +#endif \ No newline at end of file diff --git a/defold-rive/include/rive/generated/script_input_string_base.hpp b/defold-rive/include/rive/generated/script_input_string_base.hpp new file mode 100644 index 00000000..36492a23 --- /dev/null +++ b/defold-rive/include/rive/generated/script_input_string_base.hpp @@ -0,0 +1,38 @@ +#ifndef _RIVE_SCRIPT_INPUT_STRING_BASE_HPP_ +#define _RIVE_SCRIPT_INPUT_STRING_BASE_HPP_ +#include "rive/custom_property_string.hpp" +namespace rive +{ +class ScriptInputStringBase : public CustomPropertyString +{ +protected: + typedef CustomPropertyString Super; + +public: + static const uint16_t typeKey = 627; + + /// Helper to quickly determine if a core object extends another without + /// RTTI at runtime. + bool isTypeOf(uint16_t typeKey) const override + { + switch (typeKey) + { + case ScriptInputStringBase::typeKey: + case CustomPropertyStringBase::typeKey: + case CustomPropertyBase::typeKey: + case ComponentBase::typeKey: + return true; + default: + return false; + } + } + + uint16_t coreType() const override { return typeKey; } + + Core* clone() const override; + +protected: +}; +} // namespace rive + +#endif \ No newline at end of file diff --git a/defold-rive/include/rive/generated/script_input_trigger_base.hpp b/defold-rive/include/rive/generated/script_input_trigger_base.hpp new file mode 100644 index 00000000..49f7de4a --- /dev/null +++ b/defold-rive/include/rive/generated/script_input_trigger_base.hpp @@ -0,0 +1,38 @@ +#ifndef _RIVE_SCRIPT_INPUT_TRIGGER_BASE_HPP_ +#define _RIVE_SCRIPT_INPUT_TRIGGER_BASE_HPP_ +#include "rive/custom_property_trigger.hpp" +namespace rive +{ +class ScriptInputTriggerBase : public CustomPropertyTrigger +{ +protected: + typedef CustomPropertyTrigger Super; + +public: + static const uint16_t typeKey = 618; + + /// Helper to quickly determine if a core object extends another without + /// RTTI at runtime. + bool isTypeOf(uint16_t typeKey) const override + { + switch (typeKey) + { + case ScriptInputTriggerBase::typeKey: + case CustomPropertyTriggerBase::typeKey: + case CustomPropertyBase::typeKey: + case ComponentBase::typeKey: + return true; + default: + return false; + } + } + + uint16_t coreType() const override { return typeKey; } + + Core* clone() const override; + +protected: +}; +} // namespace rive + +#endif \ No newline at end of file diff --git a/defold-rive/include/rive/generated/script_input_viewmodel_property_base.hpp b/defold-rive/include/rive/generated/script_input_viewmodel_property_base.hpp new file mode 100644 index 00000000..e0f72149 --- /dev/null +++ b/defold-rive/include/rive/generated/script_input_viewmodel_property_base.hpp @@ -0,0 +1,63 @@ +#ifndef _RIVE_SCRIPT_INPUT_VIEW_MODEL_PROPERTY_BASE_HPP_ +#define _RIVE_SCRIPT_INPUT_VIEW_MODEL_PROPERTY_BASE_HPP_ +#include "rive/core/field_types/core_bytes_type.hpp" +#include "rive/custom_property.hpp" +#include "rive/span.hpp" +namespace rive +{ +class ScriptInputViewModelPropertyBase : public CustomProperty +{ +protected: + typedef CustomProperty Super; + +public: + static const uint16_t typeKey = 612; + + /// Helper to quickly determine if a core object extends another without + /// RTTI at runtime. + bool isTypeOf(uint16_t typeKey) const override + { + switch (typeKey) + { + case ScriptInputViewModelPropertyBase::typeKey: + case CustomPropertyBase::typeKey: + case ComponentBase::typeKey: + return true; + default: + return false; + } + } + + uint16_t coreType() const override { return typeKey; } + + static const uint16_t dataBindPathIdsPropertyKey = 866; + +public: + virtual void decodeDataBindPathIds(Span value) = 0; + virtual void copyDataBindPathIds( + const ScriptInputViewModelPropertyBase& object) = 0; + + Core* clone() const override; + void copy(const ScriptInputViewModelPropertyBase& object) + { + copyDataBindPathIds(object); + CustomProperty::copy(object); + } + + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override + { + switch (propertyKey) + { + case dataBindPathIdsPropertyKey: + decodeDataBindPathIds(CoreBytesType::deserialize(reader)); + return true; + } + return CustomProperty::deserialize(propertyKey, reader); + } + +protected: + virtual void dataBindPathIdsChanged() {} +}; +} // namespace rive + +#endif \ No newline at end of file diff --git a/defold-rive/include/rive/generated/scripted/scripted_data_converter_base.hpp b/defold-rive/include/rive/generated/scripted/scripted_data_converter_base.hpp new file mode 100644 index 00000000..2b81818d --- /dev/null +++ b/defold-rive/include/rive/generated/scripted/scripted_data_converter_base.hpp @@ -0,0 +1,71 @@ +#ifndef _RIVE_SCRIPTED_DATA_CONVERTER_BASE_HPP_ +#define _RIVE_SCRIPTED_DATA_CONVERTER_BASE_HPP_ +#include "rive/core/field_types/core_uint_type.hpp" +#include "rive/data_bind/converters/data_converter.hpp" +namespace rive +{ +class ScriptedDataConverterBase : public DataConverter +{ +protected: + typedef DataConverter Super; + +public: + static const uint16_t typeKey = 629; + + /// Helper to quickly determine if a core object extends another without + /// RTTI at runtime. + bool isTypeOf(uint16_t typeKey) const override + { + switch (typeKey) + { + case ScriptedDataConverterBase::typeKey: + case DataConverterBase::typeKey: + return true; + default: + return false; + } + } + + uint16_t coreType() const override { return typeKey; } + + static const uint16_t scriptAssetIdPropertyKey = 892; + +protected: + uint32_t m_ScriptAssetId = -1; + +public: + inline uint32_t scriptAssetId() const { return m_ScriptAssetId; } + void scriptAssetId(uint32_t value) + { + if (m_ScriptAssetId == value) + { + return; + } + m_ScriptAssetId = value; + scriptAssetIdChanged(); + } + + Core* clone() const override; + void copy(const ScriptedDataConverterBase& object) + { + m_ScriptAssetId = object.m_ScriptAssetId; + DataConverter::copy(object); + } + + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override + { + switch (propertyKey) + { + case scriptAssetIdPropertyKey: + m_ScriptAssetId = CoreUintType::deserialize(reader); + return true; + } + return DataConverter::deserialize(propertyKey, reader); + } + +protected: + virtual void scriptAssetIdChanged() {} +}; +} // namespace rive + +#endif \ No newline at end of file diff --git a/defold-rive/include/rive/generated/scripted/scripted_drawable_base.hpp b/defold-rive/include/rive/generated/scripted/scripted_drawable_base.hpp new file mode 100644 index 00000000..aca02638 --- /dev/null +++ b/defold-rive/include/rive/generated/scripted/scripted_drawable_base.hpp @@ -0,0 +1,76 @@ +#ifndef _RIVE_SCRIPTED_DRAWABLE_BASE_HPP_ +#define _RIVE_SCRIPTED_DRAWABLE_BASE_HPP_ +#include "rive/core/field_types/core_uint_type.hpp" +#include "rive/drawable.hpp" +namespace rive +{ +class ScriptedDrawableBase : public Drawable +{ +protected: + typedef Drawable Super; + +public: + static const uint16_t typeKey = 603; + + /// Helper to quickly determine if a core object extends another without + /// RTTI at runtime. + bool isTypeOf(uint16_t typeKey) const override + { + switch (typeKey) + { + case ScriptedDrawableBase::typeKey: + case DrawableBase::typeKey: + case NodeBase::typeKey: + case TransformComponentBase::typeKey: + case WorldTransformComponentBase::typeKey: + case ContainerComponentBase::typeKey: + case ComponentBase::typeKey: + return true; + default: + return false; + } + } + + uint16_t coreType() const override { return typeKey; } + + static const uint16_t scriptAssetIdPropertyKey = 848; + +protected: + uint32_t m_ScriptAssetId = -1; + +public: + inline uint32_t scriptAssetId() const { return m_ScriptAssetId; } + void scriptAssetId(uint32_t value) + { + if (m_ScriptAssetId == value) + { + return; + } + m_ScriptAssetId = value; + scriptAssetIdChanged(); + } + + Core* clone() const override; + void copy(const ScriptedDrawableBase& object) + { + m_ScriptAssetId = object.m_ScriptAssetId; + Drawable::copy(object); + } + + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override + { + switch (propertyKey) + { + case scriptAssetIdPropertyKey: + m_ScriptAssetId = CoreUintType::deserialize(reader); + return true; + } + return Drawable::deserialize(propertyKey, reader); + } + +protected: + virtual void scriptAssetIdChanged() {} +}; +} // namespace rive + +#endif \ No newline at end of file diff --git a/defold-rive/include/rive/generated/scripted/scripted_layout_base.hpp b/defold-rive/include/rive/generated/scripted/scripted_layout_base.hpp new file mode 100644 index 00000000..f4a8a904 --- /dev/null +++ b/defold-rive/include/rive/generated/scripted/scripted_layout_base.hpp @@ -0,0 +1,42 @@ +#ifndef _RIVE_SCRIPTED_LAYOUT_BASE_HPP_ +#define _RIVE_SCRIPTED_LAYOUT_BASE_HPP_ +#include "rive/scripted/scripted_drawable.hpp" +namespace rive +{ +class ScriptedLayoutBase : public ScriptedDrawable +{ +protected: + typedef ScriptedDrawable Super; + +public: + static const uint16_t typeKey = 637; + + /// Helper to quickly determine if a core object extends another without + /// RTTI at runtime. + bool isTypeOf(uint16_t typeKey) const override + { + switch (typeKey) + { + case ScriptedLayoutBase::typeKey: + case ScriptedDrawableBase::typeKey: + case DrawableBase::typeKey: + case NodeBase::typeKey: + case TransformComponentBase::typeKey: + case WorldTransformComponentBase::typeKey: + case ContainerComponentBase::typeKey: + case ComponentBase::typeKey: + return true; + default: + return false; + } + } + + uint16_t coreType() const override { return typeKey; } + + Core* clone() const override; + +protected: +}; +} // namespace rive + +#endif \ No newline at end of file diff --git a/defold-rive/include/rive/generated/scripted/scripted_path_effect_base.hpp b/defold-rive/include/rive/generated/scripted/scripted_path_effect_base.hpp new file mode 100644 index 00000000..1c7cbd06 --- /dev/null +++ b/defold-rive/include/rive/generated/scripted/scripted_path_effect_base.hpp @@ -0,0 +1,72 @@ +#ifndef _RIVE_SCRIPTED_PATH_EFFECT_BASE_HPP_ +#define _RIVE_SCRIPTED_PATH_EFFECT_BASE_HPP_ +#include "rive/container_component.hpp" +#include "rive/core/field_types/core_uint_type.hpp" +namespace rive +{ +class ScriptedPathEffectBase : public ContainerComponent +{ +protected: + typedef ContainerComponent Super; + +public: + static const uint16_t typeKey = 640; + + /// Helper to quickly determine if a core object extends another without + /// RTTI at runtime. + bool isTypeOf(uint16_t typeKey) const override + { + switch (typeKey) + { + case ScriptedPathEffectBase::typeKey: + case ContainerComponentBase::typeKey: + case ComponentBase::typeKey: + return true; + default: + return false; + } + } + + uint16_t coreType() const override { return typeKey; } + + static const uint16_t scriptAssetIdPropertyKey = 912; + +protected: + uint32_t m_ScriptAssetId = -1; + +public: + inline uint32_t scriptAssetId() const { return m_ScriptAssetId; } + void scriptAssetId(uint32_t value) + { + if (m_ScriptAssetId == value) + { + return; + } + m_ScriptAssetId = value; + scriptAssetIdChanged(); + } + + Core* clone() const override; + void copy(const ScriptedPathEffectBase& object) + { + m_ScriptAssetId = object.m_ScriptAssetId; + ContainerComponent::copy(object); + } + + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override + { + switch (propertyKey) + { + case scriptAssetIdPropertyKey: + m_ScriptAssetId = CoreUintType::deserialize(reader); + return true; + } + return ContainerComponent::deserialize(propertyKey, reader); + } + +protected: + virtual void scriptAssetIdChanged() {} +}; +} // namespace rive + +#endif \ No newline at end of file diff --git a/defold-rive/include/rive/generated/shapes/paint/group_effect_base.hpp b/defold-rive/include/rive/generated/shapes/paint/group_effect_base.hpp new file mode 100644 index 00000000..8d711d5c --- /dev/null +++ b/defold-rive/include/rive/generated/shapes/paint/group_effect_base.hpp @@ -0,0 +1,37 @@ +#ifndef _RIVE_GROUP_EFFECT_BASE_HPP_ +#define _RIVE_GROUP_EFFECT_BASE_HPP_ +#include "rive/container_component.hpp" +namespace rive +{ +class GroupEffectBase : public ContainerComponent +{ +protected: + typedef ContainerComponent Super; + +public: + static const uint16_t typeKey = 645; + + /// Helper to quickly determine if a core object extends another without + /// RTTI at runtime. + bool isTypeOf(uint16_t typeKey) const override + { + switch (typeKey) + { + case GroupEffectBase::typeKey: + case ContainerComponentBase::typeKey: + case ComponentBase::typeKey: + return true; + default: + return false; + } + } + + uint16_t coreType() const override { return typeKey; } + + Core* clone() const override; + +protected: +}; +} // namespace rive + +#endif \ No newline at end of file diff --git a/defold-rive/include/rive/generated/shapes/paint/target_effect_base.hpp b/defold-rive/include/rive/generated/shapes/paint/target_effect_base.hpp new file mode 100644 index 00000000..b8069c17 --- /dev/null +++ b/defold-rive/include/rive/generated/shapes/paint/target_effect_base.hpp @@ -0,0 +1,71 @@ +#ifndef _RIVE_TARGET_EFFECT_BASE_HPP_ +#define _RIVE_TARGET_EFFECT_BASE_HPP_ +#include "rive/component.hpp" +#include "rive/core/field_types/core_uint_type.hpp" +namespace rive +{ +class TargetEffectBase : public Component +{ +protected: + typedef Component Super; + +public: + static const uint16_t typeKey = 644; + + /// Helper to quickly determine if a core object extends another without + /// RTTI at runtime. + bool isTypeOf(uint16_t typeKey) const override + { + switch (typeKey) + { + case TargetEffectBase::typeKey: + case ComponentBase::typeKey: + return true; + default: + return false; + } + } + + uint16_t coreType() const override { return typeKey; } + + static const uint16_t targetIdPropertyKey = 922; + +protected: + uint32_t m_TargetId = -1; + +public: + inline uint32_t targetId() const { return m_TargetId; } + void targetId(uint32_t value) + { + if (m_TargetId == value) + { + return; + } + m_TargetId = value; + targetIdChanged(); + } + + Core* clone() const override; + void copy(const TargetEffectBase& object) + { + m_TargetId = object.m_TargetId; + Component::copy(object); + } + + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override + { + switch (propertyKey) + { + case targetIdPropertyKey: + m_TargetId = CoreUintType::deserialize(reader); + return true; + } + return Component::deserialize(propertyKey, reader); + } + +protected: + virtual void targetIdChanged() {} +}; +} // namespace rive + +#endif \ No newline at end of file diff --git a/defold-rive/include/rive/importers/backboard_importer.hpp b/defold-rive/include/rive/importers/backboard_importer.hpp index 46c0b53c..3dae1434 100644 --- a/defold-rive/include/rive/importers/backboard_importer.hpp +++ b/defold-rive/include/rive/importers/backboard_importer.hpp @@ -18,6 +18,7 @@ class FileAssetReferencer; class DataConverter; class DataBind; class DataConverterGroupItem; +class ScriptInputArtboard; class ScrollPhysics; class BackboardImporter : public ImportStackObject { @@ -32,6 +33,7 @@ class BackboardImporter : public ImportStackObject std::vector m_DataConverterGroupItemReferencers; std::vector m_interpolators; std::vector m_physics; + std::vector m_scriptInputArtboards; int m_NextArtboardId; File* m_file; @@ -48,6 +50,7 @@ class BackboardImporter : public ImportStackObject DataConverterGroupItem* referencer); void addInterpolator(KeyFrameInterpolator* interpolator); void addPhysics(ScrollPhysics* physics); + void addScriptInputArtboard(ScriptInputArtboard* input); std::vector physics() { return m_physics; } std::vector>* assets() { return &m_FileAssets; } void file(File* value); diff --git a/defold-rive/include/rive/importers/data_bind_path_importer.hpp b/defold-rive/include/rive/importers/data_bind_path_importer.hpp new file mode 100644 index 00000000..9902e20d --- /dev/null +++ b/defold-rive/include/rive/importers/data_bind_path_importer.hpp @@ -0,0 +1,20 @@ +#ifndef _RIVE_DATA_BIND_PATH_IMPORTER_HPP_ +#define _RIVE_DATA_BIND_PATH_IMPORTER_HPP_ + +#include "rive/importers/import_stack.hpp" + +namespace rive +{ +class Core; +class DataBindPath; +class DataBindPathImporter : public ImportStackObject +{ +private: + DataBindPath* m_dataBindPath; + +public: + DataBindPathImporter(DataBindPath* object); + DataBindPath* claim(); +}; +} // namespace rive +#endif diff --git a/defold-rive/include/rive/importers/file_asset_importer.hpp b/defold-rive/include/rive/importers/file_asset_importer.hpp index 9e824635..0594baca 100644 --- a/defold-rive/include/rive/importers/file_asset_importer.hpp +++ b/defold-rive/include/rive/importers/file_asset_importer.hpp @@ -12,20 +12,20 @@ class FileAsset; class FileAssetContents; class FileAssetLoader; class Factory; - class FileAssetImporter : public ImportStackObject { -private: - FileAsset* m_FileAsset; - rcp m_FileAssetLoader; - Factory* m_Factory; - // we will delete this when we go out of scope - std::unique_ptr m_Content; - public: FileAssetImporter(FileAsset*, rcp, Factory*); - void onFileAssetContents(std::unique_ptr contents); + virtual void onFileAssetContents( + std::unique_ptr contents); StatusCode resolve() override; + +protected: + FileAsset* m_fileAsset; + rcp m_fileAssetLoader; + Factory* m_factory; + // we will delete this when we go out of scope + std::unique_ptr m_content; }; } // namespace rive #endif diff --git a/defold-rive/include/rive/importers/script_asset_importer.hpp b/defold-rive/include/rive/importers/script_asset_importer.hpp new file mode 100644 index 00000000..e6e7c72d --- /dev/null +++ b/defold-rive/include/rive/importers/script_asset_importer.hpp @@ -0,0 +1,49 @@ +#ifdef WITH_RIVE_SCRIPTING +#ifndef _RIVE_SCRIPT_ASSET_IMPORTER_HPP_ +#define _RIVE_SCRIPT_ASSET_IMPORTER_HPP_ + +#include "rive/importers/file_asset_importer.hpp" +#include "rive/simple_array.hpp" +#include + +namespace rive +{ +class ScriptAsset; +class ScriptAssetImporter; + +class InBandByteCode +{ + friend class ScriptAssetImporter; + +public: + InBandByteCode(ScriptAsset* asset, SimpleArray& bytes); + +private: + ScriptAsset* m_scriptAsset; + SimpleArray m_bytes; +}; + +class ScriptAssetImporter : public FileAssetImporter +{ +public: + ScriptAssetImporter(ScriptAsset*, + rcp, + Factory*, + std::vector*); + StatusCode resolve() override; + void onFileAssetContents( + std::unique_ptr contents) override; + + ScriptAsset* scriptAsset(); + +private: + // The set of scripts which are signed together. + std::vector* m_scriptVerificationSet; +}; + +// Public key for script signature verification (32 bytes) +// TODO: Replace with permanent production public key. +extern const uint8_t g_scriptVerificationPublicKey[32]; +} // namespace rive +#endif +#endif \ No newline at end of file diff --git a/defold-rive/include/rive/importers/scripted_object_importer.hpp b/defold-rive/include/rive/importers/scripted_object_importer.hpp new file mode 100644 index 00000000..da5a4035 --- /dev/null +++ b/defold-rive/include/rive/importers/scripted_object_importer.hpp @@ -0,0 +1,23 @@ +#ifndef _RIVE_SCRIPTED_OBJECT_IMPORTER_HPP_ +#define _RIVE_SCRIPTED_OBJECT_IMPORTER_HPP_ + +#include "rive/importers/import_stack.hpp" + +namespace rive +{ +class Core; +class CustomProperty; +class ScriptedObject; + +class ScriptedObjectImporter : public ImportStackObject +{ +private: + ScriptedObject* m_scriptedObject; + +public: + ScriptedObjectImporter(ScriptedObject* object); + void addInput(CustomProperty* input); + StatusCode resolve() override; +}; +} // namespace rive +#endif \ No newline at end of file diff --git a/defold-rive/include/rive/importers/transition_viewmodel_condition_importer.hpp b/defold-rive/include/rive/importers/transition_viewmodel_condition_importer.hpp index 7cf92bdc..45dda8cd 100644 --- a/defold-rive/include/rive/importers/transition_viewmodel_condition_importer.hpp +++ b/defold-rive/include/rive/importers/transition_viewmodel_condition_importer.hpp @@ -18,6 +18,7 @@ class TransitionViewModelConditionImporter : public ImportStackObject TransitionViewModelConditionImporter( TransitionViewModelCondition* transitionViewModelCondition); void setComparator(TransitionComparator* comparator); + StatusCode resolve() override; }; } // namespace rive #endif \ No newline at end of file diff --git a/defold-rive/include/rive/input/focusable.hpp b/defold-rive/include/rive/input/focusable.hpp new file mode 100644 index 00000000..94281e4b --- /dev/null +++ b/defold-rive/include/rive/input/focusable.hpp @@ -0,0 +1,161 @@ +#ifndef _RIVE_FOCUSABLE_HPP_ +#define _RIVE_FOCUSABLE_HPP_ + +#include "rive/enum_bitset.hpp" + +namespace rive +{ +enum class KeyModifiers : uint8_t +{ + none = 0, + shift = 1 << 0, + ctrl = 1 << 1, + alt = 1 << 2, + meta = 1 << 3 + +}; + +inline KeyModifiers operator|(const KeyModifiers& a, const KeyModifiers& b) +{ + return (KeyModifiers)((uint8_t)a | (uint8_t)b); +} +inline KeyModifiers operator&(const KeyModifiers& a, const KeyModifiers& b) +{ + return (KeyModifiers)((uint8_t)a & (uint8_t)b); +} + +enum class Key : uint16_t +{ + space = 32, + apostrophe = 39, // ' + comma = 44, // , + minus = 45, // - + period = 46, // . + slash = 47, // / + key0 = 48, + key1 = 49, + key2 = 50, + key3 = 51, + key4 = 52, + key5 = 53, + key6 = 54, + key7 = 55, + key8 = 56, + key9 = 57, + semicolon = 59, // ; + equal = 61, // = + a = 65, + b = 66, + c = 67, + d = 68, + e = 69, + f = 70, + g = 71, + h = 72, + i = 73, + j = 74, + k = 75, + l = 76, + m = 77, + n = 78, + o = 79, + p = 80, + q = 81, + r = 82, + s = 83, + t = 84, + u = 85, + v = 86, + w = 87, + x = 88, + y = 89, + z = 90, + leftBracket = 91, // [ + backslash = 92, // "\" + rightBracket = 93, // ] + graveAccent = 96, // ` + world1 = 161, // non-US #1 + world2 = 162, // non-US #2 + escape = 256, + enter = 257, + tab = 258, + backspace = 259, + insert = 260, + deleteKey = 261, + right = 262, + left = 263, + down = 264, + up = 265, + pageUp = 266, + pageDown = 267, + home = 268, + end = 269, + capsLock = 280, + scrollLock = 281, + numLock = 282, + printScreen = 283, + pause = 284, + f1 = 290, + f2 = 291, + f3 = 292, + f4 = 293, + f5 = 294, + f6 = 295, + f7 = 296, + f8 = 297, + f9 = 298, + f10 = 299, + f11 = 300, + f12 = 301, + f13 = 302, + f14 = 303, + f15 = 304, + f16 = 305, + f17 = 306, + f18 = 307, + f19 = 308, + f20 = 309, + f21 = 310, + f22 = 311, + f23 = 312, + f24 = 313, + f25 = 314, + kp0 = 320, + kp1 = 321, + kp2 = 322, + kp3 = 323, + kp4 = 324, + kp5 = 325, + kp6 = 326, + kp7 = 327, + kp8 = 328, + kp9 = 329, + kpDecimal = 330, + kpDivide = 331, + kpMultiply = 332, + kpSubtract = 333, + kpAdd = 334, + kpEnter = 335, + kpEqual = 336, + leftShift = 340, + leftControl = 341, + leftAlt = 342, + leftSuper = 343, + rightShift = 344, + rightControl = 345, + rightAlt = 346, + rightSuper = 347, + menu = 348, +}; + +class Focusable +{ +public: + virtual bool keyInput(Key value, + KeyModifiers modifiers, + bool isPressed, + bool isRepeat) = 0; + virtual bool textInput(const std::string& text) = 0; +}; +} // namespace rive +#endif \ No newline at end of file diff --git a/defold-rive/include/rive/layout_component.hpp b/defold-rive/include/rive/layout_component.hpp index 8b1822ef..bd97006e 100644 --- a/defold-rive/include/rive/layout_component.hpp +++ b/defold-rive/include/rive/layout_component.hpp @@ -155,6 +155,8 @@ class LayoutComponent : public LayoutComponentBase, float m_forcedWidth = NAN; float m_forcedHeight = NAN; bool m_forceUpdateLayoutBounds = false; + bool m_positionLeftChanged = true; + bool m_positionTopChanged = true; #ifdef WITH_RIVE_LAYOUT protected: @@ -294,6 +296,9 @@ class LayoutComponent : public LayoutComponentBase, void directionChanged(); LayoutDirection actualDirection(); #endif + + void markPositionLeftChanged() { m_positionLeftChanged = true; } + void markPositionTopChanged() { m_positionTopChanged = true; } void buildDependencies() override; void markLayoutNodeDirty( diff --git a/defold-rive/include/rive/listener_group.hpp b/defold-rive/include/rive/listener_group.hpp new file mode 100644 index 00000000..d860b7ca --- /dev/null +++ b/defold-rive/include/rive/listener_group.hpp @@ -0,0 +1,108 @@ +#ifndef _RIVE_LISTENER_GROUP_HPP_ +#define _RIVE_LISTENER_GROUP_HPP_ + +#include +#include +#include "rive/animation/state_machine_instance.hpp" +#include "rive/core.hpp" +#include "rive/gesture_click_phase.hpp" +#include "rive/listener_type.hpp" +#include "rive/math/vec2d.hpp" +#include "rive/process_event_result.hpp" + +namespace rive +{ +class Component; +class HitComponent; +class StateMachineListener; + +class _PointerData +{ +public: + bool isHovered = false; + bool isPrevHovered = false; + GestureClickPhase phase = GestureClickPhase::out; + Vec2D* previousPosition() { return &m_previousPosition; } + +private: + // A vector storing the previous position for this pointer data + Vec2D m_previousPosition = Vec2D(0, 0); +}; + +class ListenerGroup +{ +public: + ListenerGroup(const StateMachineListener* listener) : m_listener(listener) + {} + virtual ~ListenerGroup(); + _PointerData* pointerData(int id); + void consume() { m_isConsumed = true; } + void hover(int id); + void reset(int pointerId); + void releaseEvent(int pointerId); + virtual void enable(int pointerId = 0); + virtual void disable(int pointerId = 0); + bool isConsumed() { return m_isConsumed; } + virtual bool canEarlyOut(Component* drawable); + virtual bool needsDownListener(Component* drawable); + virtual bool needsUpListener(Component* drawable); + + virtual ProcessEventResult processEvent( + Component* component, + Vec2D position, + int pointerId, + ListenerType hitEvent, + bool canHit, + float timeStamp, + StateMachineInstance* stateMachineInstance); + const StateMachineListener* listener() const { return m_listener; }; + +private: + // Consumed listeners aren't processed again in the current frame + bool m_isConsumed = false; + bool m_hasDragged = false; + const StateMachineListener* m_listener; + std::unordered_map m_pointers; + std::vector<_PointerData*> m_pointersPool; +}; + +class HitTarget +{ +private: + Component* m_component = nullptr; + bool m_isOpaque = false; + +public: + HitTarget(Component* component, bool isOpaque) : + m_component(component), m_isOpaque(isOpaque) + {} + Component* component() { return m_component; } + bool isOpaque() { return m_isOpaque; } +}; + +class ListenerGroupWithTargets +{ +private: + ListenerGroup* m_group = nullptr; + std::vector m_targets; + +public: + ListenerGroupWithTargets(ListenerGroup* group, + std::vector targets) : + m_group(group), m_targets(targets) + {} + ListenerGroup* group() { return m_group; } + std::vector targets() { return m_targets; } +}; + +class ListenerGroupProvider +{ +public: + static ListenerGroupProvider* from(Core* component); + virtual std::vector listenerGroups() = 0; + virtual std::vector hitComponents( + StateMachineInstance* sm) = 0; +}; + +} // namespace rive +#endif diff --git a/defold-rive/include/rive/listener_type.hpp b/defold-rive/include/rive/listener_type.hpp index 63e890a3..0ad9fbd9 100644 --- a/defold-rive/include/rive/listener_type.hpp +++ b/defold-rive/include/rive/listener_type.hpp @@ -11,11 +11,12 @@ enum class ListenerType : int move = 4, event = 5, click = 6, - draggableConstraint = 7, + componentProvided = 7, textInput = 8, dragStart = 9, dragEnd = 10, viewModel = 11, + drag = 12, }; } #endif \ No newline at end of file diff --git a/defold-rive/include/rive/lua/lua_state.hpp b/defold-rive/include/rive/lua/lua_state.hpp new file mode 100644 index 00000000..ad4c6e6a --- /dev/null +++ b/defold-rive/include/rive/lua/lua_state.hpp @@ -0,0 +1,26 @@ +#ifndef _RIVE_LUA_STATE_HPP_ +#define _RIVE_LUA_STATE_HPP_ + +#ifdef WITH_RIVE_SCRIPTING +#include "lua.h" +#endif +#include + +namespace rive +{ +class ViewModel; +class LuaState +{ +public: +#ifdef WITH_RIVE_SCRIPTING + + LuaState(lua_State* state) : state(state) {} + ~LuaState() { state = nullptr; } + void initializeData(std::vector&); + + lua_State* state; +#endif +}; + +} // namespace rive +#endif \ No newline at end of file diff --git a/defold-rive/include/rive/lua/rive_lua_libs.hpp b/defold-rive/include/rive/lua/rive_lua_libs.hpp index 7448fa84..4b62c89d 100644 --- a/defold-rive/include/rive/lua/rive_lua_libs.hpp +++ b/defold-rive/include/rive/lua/rive_lua_libs.hpp @@ -3,28 +3,58 @@ #define _RIVE_LUA_LIBS_HPP_ #include "lua.h" #include "lualib.h" +#include "rive/assets/script_asset.hpp" +#include "rive/lua/lua_state.hpp" #include "rive/math/raw_path.hpp" #include "rive/renderer.hpp" #include "rive/math/vec2d.hpp" +#include "rive/math/contour_measure.hpp" +#include "rive/math/path_measure.hpp" #include "rive/shapes/paint/image_sampler.hpp" +#include "rive/viewmodel/viewmodel_instance_boolean.hpp" +#include "rive/viewmodel/viewmodel_instance_color.hpp" +#include "rive/viewmodel/viewmodel_instance_enum.hpp" #include "rive/viewmodel/viewmodel_instance_value.hpp" #include "rive/viewmodel/viewmodel_instance_viewmodel.hpp" +#include "rive/viewmodel/viewmodel_instance_color.hpp" #include "rive/viewmodel/viewmodel_instance_number.hpp" +#include "rive/viewmodel/viewmodel_instance_string.hpp" #include "rive/viewmodel/viewmodel_instance_trigger.hpp" #include "rive/viewmodel/viewmodel_instance_list.hpp" +#include "rive/data_bind/data_values/data_value.hpp" +#include "rive/data_bind/data_values/data_value_boolean.hpp" +#include "rive/data_bind/data_values/data_value_color.hpp" +#include "rive/data_bind/data_values/data_value_list.hpp" +#include "rive/data_bind/data_values/data_value_number.hpp" +#include "rive/data_bind/data_values/data_value_string.hpp" #include "rive/viewmodel/viewmodel.hpp" -#include "rive/artboard.hpp" -#include "rive/file.hpp" -#include "rive/animation/state_machine_instance.hpp" +#include "rive/hit_result.hpp" +#include "rive/refcnt.hpp" +#include #include +#include +#include +#include +#include + +static const int maxCStack = 8000; +static const int luaGlobalsIndex = -maxCStack - 2002; +static const int luaRegistryIndex = -maxCStack - 2000; namespace rive { +class Artboard; +class ArtboardInstance; class Factory; +class File; +class ModuleDetails; +class ScriptedObject; +class StateMachineInstance; +class TransformComponent; enum class LuaAtoms : int16_t { - // Vec2D + // Vector length, lengthSquared, normalized, @@ -41,6 +71,12 @@ enum class LuaAtoms : int16_t close, reset, add, + contours, + measure, + + // Path Command + type, + points, // Mat2D invert, @@ -54,7 +90,7 @@ enum class LuaAtoms : int16_t clamp, repeat, mirror, - trilinear, + bilinear, nearest, // Paint @@ -102,18 +138,72 @@ enum class LuaAtoms : int16_t // Scripted Properties value, + red, + green, + blue, + alpha, getNumber, getTrigger, + getString, + getBoolean, + getColor, + getList, addListener, removeListener, fire, + push, + insert, + shift, + pop, + swap, // Artboards draw, advance, frameOrigin, data, - instance + instance, + newAtom, + bounds, + pointerDown, + pointerMove, + pointerUp, + pointerExit, + addToPath, + name, + + // Scripted DataValues + isNumber, + isString, + isBoolean, + isColor, + + // inputs + hit, + id, + position, + + // nodes + rotation, + scale, + worldTransform, + scaleX, + scaleY, + decompose, + children, + parent, + node, + + // PathMeasure/ContourMeasure + positionAndTangent, + warp, + extract, + next, + isClosed, + + // Scripted Context + markNeedsUpdate, + viewModel, }; struct ScriptedMat2D @@ -134,21 +224,53 @@ struct ScriptedMat2D static_assert(std::is_trivially_destructible::value, "ScriptedMat2D must be trivially destructible"); -class ScriptedPath +class ScriptedPathCommand { public: - RawPath rawPath; - RenderPath* renderPath(lua_State* L); - static constexpr uint8_t luaTag = LUA_T_COUNT + 2; - static constexpr const char* luaName = "Path"; + ScriptedPathCommand(std::string type, std::vector points = {}) : + m_type(type), m_points(points) + {} + static constexpr uint8_t luaTag = LUA_T_COUNT + 29; + static constexpr const char* luaName = "PathCommand"; static constexpr bool hasMetatable = true; + std::string type() { return m_type; } + std::vector points() { return m_points; } +private: + std::string m_type; + std::vector m_points; +}; + +class ScriptedPathData +{ +public: + ScriptedPathData() {} + ScriptedPathData(const RawPath* path); + int totalCommands(); void markDirty() { m_isRenderPathDirty = true; } + RawPath rawPath; + static constexpr uint8_t luaTag = LUA_T_COUNT + 30; + static constexpr const char* luaName = "PathData"; + static constexpr bool hasMetatable = true; + RenderPath* renderPath(lua_State* L); -private: +protected: rcp m_renderPath; bool m_isRenderPathDirty = true; + +private: + uint64_t m_renderFrameId = 0; +}; + +class ScriptedPath : public ScriptedPathData +{ +public: + ScriptedPath() {} + ScriptedPath(const RawPath* path) : ScriptedPathData(path) {} + static constexpr uint8_t luaTag = LUA_T_COUNT + 2; + static constexpr const char* luaName = "Path"; + static constexpr bool hasMetatable = true; }; class ScriptedGradient @@ -301,7 +423,7 @@ class ScriptedRenderer void save(lua_State* L); void restore(lua_State* L); void transform(lua_State* L, const Mat2D& mat2d); - void clipPath(lua_State* L, ScriptedPath* path); + void clipPath(lua_State* L, ScriptedPathData* path); Renderer* validate(lua_State* L); static constexpr uint8_t luaTag = LUA_T_COUNT + 9; @@ -314,40 +436,63 @@ class ScriptedRenderer uint32_t m_saveCount = 0; }; +class ScriptReffedArtboard : public RefCnt +{ +public: + ScriptReffedArtboard(rcp file, + std::unique_ptr&& artboardInstance); + + ~ScriptReffedArtboard(); + rive::rcp file(); + Artboard* artboard(); + StateMachineInstance* stateMachine(); + rcp viewModelInstance() { return m_viewModelInstance; } + +private: + rcp m_file; + std::unique_ptr m_artboard; + std::unique_ptr m_stateMachine; + rcp m_viewModelInstance; +}; + class ScriptedArtboard { public: - ScriptedArtboard(rcp file, + ScriptedArtboard(lua_State* L, + rcp file, std::unique_ptr&& artboardInstance); - - ~ScriptedArtboard() - { - // Make sure artboard is deleted before file. - m_artboard = nullptr; - m_file = nullptr; - } + ~ScriptedArtboard(); static constexpr uint8_t luaTag = LUA_T_COUNT + 10; static constexpr const char* luaName = "Artboard"; static constexpr bool hasMetatable = true; - Artboard* artboard() { return m_artboard.get(); } + Artboard* artboard() { return m_scriptReffedArtboard->artboard(); } + StateMachineInstance* stateMachine() + { + return m_scriptReffedArtboard->stateMachine(); + } + rcp viewModelInstance() + { + return m_scriptReffedArtboard->viewModelInstance(); + } + + rcp scriptReffedArtboard() + { + return m_scriptReffedArtboard; + } + int pushData(lua_State* L); int instance(lua_State* L); bool advance(float seconds); + void cleanupDataRef(lua_State* L); + private: - rcp m_file; - std::unique_ptr m_artboard; - std::unique_ptr m_stateMachine; - rcp m_viewModelInstance; + lua_State* m_state; + rcp m_scriptReffedArtboard; int m_dataRef = 0; - // std::vector m_dataBinds; - - // for parent data context - // internalDataContext() - // bindViewModelInstance on state machine }; struct ScriptedListener @@ -390,8 +535,13 @@ class ScriptedViewModel static constexpr const char* luaName = "ViewModel"; static constexpr bool hasMetatable = true; int pushValue(const char* name, int coreType = 0); + int instance(lua_State* L); const lua_State* state() const { return m_state; } + rcp viewModelInstance() const + { + return m_viewModelInstance; + } private: lua_State* m_state; @@ -450,31 +600,67 @@ class ScriptedPropertyList : public ScriptedProperty int pushLength(); int pushValue(int index); void valueChanged() override; + void append(ViewModelInstance*); private: bool m_changed = false; std::unordered_map m_propertyRefs; }; +class ScriptedPropertyColor : public ScriptedProperty +{ +public: + ScriptedPropertyColor(lua_State* L, rcp value); + static constexpr uint8_t luaTag = LUA_T_COUNT + 16; + static constexpr const char* luaName = "PropertyColor"; + static constexpr bool hasMetatable = true; + + int pushValue(); + void setValue(unsigned value); +}; + +class ScriptedPropertyString : public ScriptedProperty +{ +public: + ScriptedPropertyString(lua_State* L, rcp value); + static constexpr uint8_t luaTag = LUA_T_COUNT + 17; + static constexpr const char* luaName = "PropertyString"; + static constexpr bool hasMetatable = true; + + int pushValue(); + void setValue(const std::string& value); +}; + +class ScriptedPropertyBoolean : public ScriptedProperty +{ +public: + ScriptedPropertyBoolean(lua_State* L, rcp value); + static constexpr uint8_t luaTag = LUA_T_COUNT + 18; + static constexpr const char* luaName = "Property"; + static constexpr bool hasMetatable = true; + + int pushValue(); + void setValue(bool value); +}; + +class ScriptedPropertyEnum : public ScriptedProperty +{ +public: + ScriptedPropertyEnum(lua_State* L, rcp value); + static constexpr uint8_t luaTag = LUA_T_COUNT + 19; + static constexpr const char* luaName = "Property"; + static constexpr bool hasMetatable = true; + + int pushValue(); + void setValue(const std::string& value); +}; + // Make // ScriptedPropertyViewModel // - Nullable ViewModelInstanceValue (ViewModelInstanceViewModel) // - Requires ViewModel to know which properties to expect -// ScriptedPropertyEnum -// - Nullable ViewModelInstanceValue (ViewModelInstanceEnum) -// - Requires DataEnum for expected types -// ScriptedPropertyNumber -// - Nullable ViewModelInstanceValue (ViewModelInstanceNumber) -// ScriptedPropertyString -// - Nullable ViewModelInstanceValue (ViewModelInstanceString) -// ScriptedPropertyTrigger -// - Nullable ViewModelInstanceValue (ViewModelInstanceTrigger) // ScriptedPropertyArtboard // - Nullable ViewModelInstanceValue (ViewModelInstanceArtboard) -// ScriptedPropertyColor -// - Nullable ViewModelInstanceValue (ViewModelInstanceColor) -// ScriptedPropertyList -// - Nullable ViewModelInstanceValue (ViewModelInstanceList) // Make renderer: return lua_newrive(L, renderer); template @@ -544,6 +730,10 @@ inline void lua_pushvec2d(lua_State* L, Vec2D vec) } int luaopen_rive(lua_State* L); +int rive_luaErrorHandler(lua_State* L); +int rive_lua_pcall(lua_State* state, int nargs, int nresults); +int rive_lua_pushRef(lua_State* state, int ref); +void rive_lua_pop(lua_State* state, int count); class ScriptingContext { @@ -555,9 +745,32 @@ class ScriptingContext virtual void printBeginLine(lua_State* state) = 0; virtual void print(Span data) = 0; virtual void printEndLine() = 0; + virtual int pCall(lua_State* state, int nargs, int nresults) = 0; + + // Add a module to be registered later via performRegistration() + void addModule(ModuleDetails* moduleDetails); + // Perform registration of all added modules, handling dependencies and + // retries + void performRegistration(lua_State* state); + // Called when a module is required but not found during registration + void recordMissingDependency(const std::string& requiringModule, + const std::string& missingModule); + +private: + bool tryRegisterModule(lua_State* state, ModuleDetails* moduleDetails); + void sortNextModule(ModuleDetails* module, + std::vector* pendingModules, + std::vector* sortedModules, + std::unordered_set* visitedModules); + // Called when a module successfully registers + void onModuleRegistered(ModuleDetails* moduleDetails); private: Factory* m_factory; + std::vector m_modulesToRegister; + std::unordered_map m_moduleLookup; + + std::unordered_set m_pendingModules; }; class ScriptingVM @@ -570,6 +783,17 @@ class ScriptingVM lua_State* state() { return m_state; } static void init(lua_State* state, ScriptingContext* context); + + // Add a module to be registered later via performRegistration() + void addModule(ModuleDetails* moduleDetails) + { + m_context->addModule(moduleDetails); + } + + // Perform registration of all added modules, handling dependencies and + // retries + void performRegistration() { m_context->performRegistration(m_state); } + static bool registerModule(lua_State* state, const char* name, Span bytecode); @@ -583,11 +807,231 @@ class ScriptingVM bool registerScript(const char* name, Span bytecode); + static void dumpStack(lua_State* state); + private: lua_State* m_state; ScriptingContext* m_context; }; +class ScriptedDataValue +{ +public: + ScriptedDataValue(lua_State* L) { m_state = L; } + virtual ~ScriptedDataValue(); + static constexpr const char* luaName = "DataValue"; + DataValue* dataValue() { return m_dataValue; } + virtual bool isNumber() { return false; } + virtual bool isString() { return false; } + virtual bool isBoolean() { return false; } + virtual bool isColor() { return false; } + + const lua_State* state() const { return m_state; } + +protected: + lua_State* m_state; + DataValue* m_dataValue = nullptr; +}; + +class ScriptedDataValueNumber : public ScriptedDataValue +{ +public: + ScriptedDataValueNumber(lua_State* L, float value) : ScriptedDataValue(L) + { + m_dataValue = new DataValueNumber(value); + } + static constexpr bool hasMetatable = true; + static constexpr uint8_t luaTag = LUA_T_COUNT + 20; + static constexpr const char* luaName = "DataValueNumber"; + bool isNumber() override { return true; } +}; + +class ScriptedDataValueString : public ScriptedDataValue +{ +public: + ScriptedDataValueString(lua_State* L, std::string value) : + ScriptedDataValue(L) + { + m_dataValue = new DataValueString(value); + } + static constexpr bool hasMetatable = true; + static constexpr uint8_t luaTag = LUA_T_COUNT + 21; + static constexpr const char* luaName = "DataValueString"; + bool isString() override { return true; } +}; + +class ScriptedDataValueBoolean : public ScriptedDataValue +{ +public: + ScriptedDataValueBoolean(lua_State* L, bool value) : ScriptedDataValue(L) + { + m_dataValue = new DataValueBoolean(value); + } + static constexpr bool hasMetatable = true; + static constexpr uint8_t luaTag = LUA_T_COUNT + 22; + static constexpr const char* luaName = "DataValueBoolean"; + bool isBoolean() override { return true; } +}; + +class ScriptedDataValueColor : public ScriptedDataValue +{ +public: + ScriptedDataValueColor(lua_State* L, int value) : ScriptedDataValue(L) + { + m_dataValue = new DataValueColor(value); + } + static constexpr bool hasMetatable = true; + static constexpr uint8_t luaTag = LUA_T_COUNT + 23; + static constexpr const char* luaName = "DataValueColor"; + bool isColor() override { return true; } +}; + +class ScriptedPointerEvent +{ +public: + ScriptedPointerEvent(uint8_t id, Vec2D position) : + m_id(id), m_position(position) + {} + + static constexpr uint8_t luaTag = LUA_T_COUNT + 24; + static constexpr const char* luaName = "PointerEvent"; + static constexpr bool hasMetatable = true; + + uint8_t m_id = 0; + Vec2D m_position; + HitResult m_hitResult = HitResult::none; +}; + +class ScriptedNode +{ +public: + ScriptedNode(rcp artboard, + TransformComponent* component); + + static constexpr uint8_t luaTag = LUA_T_COUNT + 25; + static constexpr const char* luaName = "NodeData"; + static constexpr bool hasMetatable = true; + + TransformComponent* component() { return m_component; } + rcp artboard() { return m_artboard; } + +private: + rcp m_artboard; + TransformComponent* m_component; +}; + +class ScriptedContourMeasure +{ +public: + ScriptedContourMeasure(rcp measure, + rcp iter) : + m_measure(measure), m_iter(iter) + {} + + static constexpr uint8_t luaTag = LUA_T_COUNT + 26; + static constexpr const char* luaName = "ContourMeasure"; + static constexpr bool hasMetatable = true; + + ContourMeasure* measure() { return m_measure.get(); } + rcp iter() { return m_iter; } + +private: + rcp m_measure; + rcp m_iter; +}; + +class ScriptedPathMeasure +{ +public: + ScriptedPathMeasure(PathMeasure measure) : m_measure(std::move(measure)) {} + + static constexpr uint8_t luaTag = LUA_T_COUNT + 27; + static constexpr const char* luaName = "PathMeasure"; + static constexpr bool hasMetatable = true; + + PathMeasure* measure() { return &m_measure; } + +private: + PathMeasure m_measure; +}; + +class ScriptedContext +{ +public: + ScriptedContext(ScriptedObject*); + ScriptedObject* scriptedObject() { return m_scriptedObject; } + static constexpr uint8_t luaTag = LUA_T_COUNT + 28; + static constexpr const char* luaName = "Context"; + static constexpr bool hasMetatable = true; + +private: + ScriptedObject* m_scriptedObject = nullptr; +}; + +static void interruptCPP(lua_State* L, int gc); + +class CPPRuntimeScriptingContext : public ScriptingContext +{ +public: + CPPRuntimeScriptingContext(Factory* factory) : ScriptingContext(factory) {} + virtual ~CPPRuntimeScriptingContext() = default; + + std::chrono::time_point executionTime; + + int pCall(lua_State* state, int nargs, int nresults) override; + + void printBeginLine(lua_State* state) override {} + void print(Span data) override + { + auto message = std::string(data.data(), data.size()); + puts(message.c_str()); + } + + void printEndLine() override { puts("\n"); } + + void printError(lua_State* state) override + { + const char* error = lua_tostring(state, -1); + fprintf(stderr, "%s", error); + } + + void startTimedExecution(lua_State* state) + { + lua_Callbacks* cb = lua_callbacks(state); + cb->interrupt = interruptCPP; + executionTime = std::chrono::steady_clock::now(); + } + + void endTimedExecution(lua_State* state) + { + lua_Callbacks* cb = lua_callbacks(state); + cb->interrupt = nullptr; + } +}; + +static void interruptCPP(lua_State* L, int gc) +{ + if (gc >= 0 || !lua_isyieldable(L)) + { + return; + } + + CPPRuntimeScriptingContext* context = + static_cast(lua_getthreaddata(L)); + + const auto now = std::chrono::steady_clock::now(); + auto ms = std::chrono::duration_cast( + now - context->executionTime) + .count(); + if (ms > 50) + { + lua_Callbacks* cb = lua_callbacks(L); + cb->interrupt = nullptr; + // reserve space for error string + lua_rawcheckstack(L, 1); + luaL_error(L, "execution took too long"); + } +} } // namespace rive #endif #endif diff --git a/defold-rive/include/rive/manifest_sections.hpp b/defold-rive/include/rive/manifest_sections.hpp new file mode 100644 index 00000000..3160681d --- /dev/null +++ b/defold-rive/include/rive/manifest_sections.hpp @@ -0,0 +1,12 @@ +#ifndef _RIVE_MANIFEST_FLAGS_HPP_ +#define _RIVE_MANIFEST_FLAGS_HPP_ + +namespace rive +{ +enum class ManifestSections : unsigned char +{ + names = 0, + paths = 1, +}; +} +#endif diff --git a/defold-rive/include/rive/math/contour_measure.hpp b/defold-rive/include/rive/math/contour_measure.hpp index 04356927..b82701c3 100644 --- a/defold-rive/include/rive/math/contour_measure.hpp +++ b/defold-rive/include/rive/math/contour_measure.hpp @@ -132,6 +132,14 @@ class ContourMeasureIter this->rewind(path, tol); } + // Constructor that copies the path, allowing ContourMeasure objects to + // outlive the original path. + ContourMeasureIter(const RawPath& path, float tol = kDefaultTolerance) + { + m_optionalCopy = path; + this->rewind(&m_optionalCopy, tol); + } + void rewind(const RawPath*, float = kDefaultTolerance); // Returns a measure object for each contour in the path @@ -154,6 +162,24 @@ class ContourMeasureIter std::vector m_segmentCounts; }; +// Ref-counted wrapper for ContourMeasureIter, used when the iterator needs +// to outlive stack scope (e.g., in script bindings). +class RefCntContourMeasureIter : public RefCnt +{ +public: + RefCntContourMeasureIter( + const RawPath& path, + float tol = ContourMeasureIter::kDefaultTolerance) : + m_iter(path, tol) + {} + + ContourMeasureIter* get() { return &m_iter; } + ContourMeasureIter* operator->() { return &m_iter; } + +private: + ContourMeasureIter m_iter; +}; + } // namespace rive #endif diff --git a/defold-rive/include/rive/math/path_measure.hpp b/defold-rive/include/rive/math/path_measure.hpp index 5e799017..6a030043 100644 --- a/defold-rive/include/rive/math/path_measure.hpp +++ b/defold-rive/include/rive/math/path_measure.hpp @@ -15,7 +15,13 @@ class PathMeasure ContourMeasure::PosTanDistance atDistance(float distance) const; ContourMeasure::PosTanDistance atPercentage(float percentageDistance) const; + void getSegment(float startDistance, + float endDistance, + RawPath* dst, + bool startWithMove = true) const; + float length() const { return m_length; } + bool isClosed() const; private: float m_length; diff --git a/defold-rive/include/rive/math/simd.hpp b/defold-rive/include/rive/math/simd.hpp index d8d1e913..7d13fb87 100644 --- a/defold-rive/include/rive/math/simd.hpp +++ b/defold-rive/include/rive/math/simd.hpp @@ -83,6 +83,22 @@ template struct boolean_mask_type #define SIMD_NATIVE_GVEC 1 +// NOTE: Due to the build compiling with march=native, on systems with AVX +// or AVX512 support, it will output those vectors from these functions, +// but clang will kick out the following warning: +// AVX vector return of type 'gvec' (vector of +// 32 'signed char' values) without 'avx' enabled changes the ABI +// In release builds, all of the places where these functions are being +// called should be getting inlined so there's not *technically* an ABI +// to be breaking, so disabling this should be fine. +#define DISABLE_CLANG_SIMD_ABI_WARNING() \ + _Pragma("clang diagnostic ignored \"-Wpsabi\"") + +#define PUSH_DISABLE_CLANG_SIMD_ABI_WARNING() \ + _Pragma("clang diagnostic push") DISABLE_CLANG_SIMD_ABI_WARNING() + +#define POP_DISABLE_CLANG_SIMD_ABI_WARNING() _Pragma("clang diagnostic pop") + #else // gvec needs to be polyfilled with templates. @@ -94,6 +110,11 @@ template struct boolean_mask_type #define SIMD_NATIVE_GVEC 0 +// With non-native gvec these don't have to do anything +#define DISABLE_CLANG_SIMD_ABI_WARNING() +#define PUSH_DISABLE_CLANG_SIMD_ABI_WARNING() +#define POP_DISABLE_CLANG_SIMD_ABI_WARNING() + #endif namespace rive @@ -585,6 +606,8 @@ SIMD_ALWAYS_INLINE std:: } #endif +PUSH_DISABLE_CLANG_SIMD_ABI_WARNING() + template SIMD_ALWAYS_INLINE gvec join(gvec a, gvec b) { @@ -696,6 +719,8 @@ SIMD_ALWAYS_INLINE return ret; } +POP_DISABLE_CLANG_SIMD_ABI_WARNING() + ////// Basic linear algebra ////// template diff --git a/defold-rive/include/rive/nested_artboard.hpp b/defold-rive/include/rive/nested_artboard.hpp index abe7c4cd..715ada74 100644 --- a/defold-rive/include/rive/nested_artboard.hpp +++ b/defold-rive/include/rive/nested_artboard.hpp @@ -3,6 +3,7 @@ #include "rive/generated/nested_artboard_base.hpp" #include "rive/artboard_host.hpp" +#include "rive/data_bind_path_referencer.hpp" #include "rive/data_bind/data_context.hpp" #include "rive/viewmodel/viewmodel_instance_value.hpp" #include "rive/hit_info.hpp" @@ -12,6 +13,7 @@ #include "rive/viewmodel/viewmodel_instance_artboard.hpp" #include "rive/refcnt.hpp" #include "rive/file.hpp" +#include namespace rive { @@ -37,18 +39,18 @@ class NestedArtboard : public NestedArtboardBase, DataContext* m_dataContext = nullptr; protected: - std::vector m_DataBindPathIdsBuffer; - private: Artboard* findArtboard( ViewModelInstanceArtboard* viewModelInstanceArtboard); void clearNestedAnimations(); + float m_cumulatedSeconds = 0; public: NestedArtboard(); ~NestedArtboard() override; StatusCode onAddedClean(CoreContext* context) override; void draw(Renderer* renderer) override; + bool willDraw() override; Core* hitTest(HitInfo*, const Mat2D&) override; void addNestedAnimation(NestedAnimation* nestedAnimation); @@ -89,10 +91,6 @@ class NestedArtboard : public NestedArtboardBase, bool worldToLocal(Vec2D world, Vec2D* local); void decodeDataBindPathIds(Span value) override; void copyDataBindPathIds(const NestedArtboardBase& object) override; - std::vector dataBindPathIds() override - { - return m_DataBindPathIdsBuffer; - }; void bindViewModelInstance(rcp viewModelInstance, DataContext* parent) override; void internalDataContext(DataContext* dataContext) override; @@ -100,6 +98,7 @@ class NestedArtboard : public NestedArtboardBase, void unbind() override; void updateDataBinds() override; + float calculateLocalElapsedSeconds(float elapsedSeconds); bool advanceComponent(float elapsedSeconds, AdvanceFlags flags = AdvanceFlags::Animate | AdvanceFlags::NewFrame) override; diff --git a/defold-rive/include/rive/renderer/async_pipeline_manager.hpp b/defold-rive/include/rive/renderer/async_pipeline_manager.hpp index 5caa7cda..545b80b1 100644 --- a/defold-rive/include/rive/renderer/async_pipeline_manager.hpp +++ b/defold-rive/include/rive/renderer/async_pipeline_manager.hpp @@ -8,11 +8,9 @@ #include "rive/renderer/render_context.hpp" #include -#include #include #include #include -#include namespace rive::gpu { @@ -121,11 +119,11 @@ template class AsyncPipelineManager // If requested, synthesize a complete failure to get an ubershader // (i.e. pretend we attempted to load the current shader asynchronously // and tried to fall back on an uber, which failed) (Don't fail on - // "atomicResolve" because if we fail that one the unit test won't see - // the clear color) + // "renderPassResolve" in atomic mode because if we fail that one the + // unit test won't see the clear color.) if (props.synthesizedFailureType == gpu::SynthesizedFailureType::ubershaderLoad && - props.drawType != DrawType::atomicResolve) + props.drawType != DrawType::renderPassResolve) { return nullptr; } @@ -514,4 +512,4 @@ template class AsyncPipelineManager std::condition_variable m_sharedObjectReadyCV; }; -} // namespace rive::gpu \ No newline at end of file +} // namespace rive::gpu diff --git a/defold-rive/include/rive/renderer/d3d/d3d.hpp b/defold-rive/include/rive/renderer/d3d/d3d.hpp index 13c207d1..b5e2c204 100644 --- a/defold-rive/include/rive/renderer/d3d/d3d.hpp +++ b/defold-rive/include/rive/renderer/d3d/d3d.hpp @@ -45,5 +45,6 @@ struct D3DContextOptions bool disableRasterizerOrderedViews = false; // Primarily for testing. bool disableTypedUAVLoadStore = false; // Primarily for testing. bool isIntel = false; + bool isIntelArc = false; }; } // namespace rive::gpu diff --git a/defold-rive/include/rive/renderer/d3d/d3d_utils.hpp b/defold-rive/include/rive/renderer/d3d/d3d_utils.hpp new file mode 100644 index 00000000..eeaee467 --- /dev/null +++ b/defold-rive/include/rive/renderer/d3d/d3d_utils.hpp @@ -0,0 +1,12 @@ +/* + * Copyright 2025 Rive + */ +#include + +namespace rive::gpu +{ +namespace d3d_utils +{ +bool GetWStringFromString(const char*, std::wstring& outString); +}; +}; // namespace rive::gpu diff --git a/defold-rive/include/rive/renderer/d3d11/render_context_d3d_impl.hpp b/defold-rive/include/rive/renderer/d3d11/render_context_d3d_impl.hpp index 4a48a786..409dfbfe 100644 --- a/defold-rive/include/rive/renderer/d3d11/render_context_d3d_impl.hpp +++ b/defold-rive/include/rive/renderer/d3d11/render_context_d3d_impl.hpp @@ -204,7 +204,7 @@ class RenderContextD3DImpl : public RenderContextHelperImpl RenderContextD3DImpl(ComPtr, ComPtr, const D3DCapabilities&, - ShaderCompilationMode); + const D3DContextOptions&); rcp makeRenderBuffer(RenderBufferType, RenderBufferFlags, diff --git a/defold-rive/include/rive/renderer/d3d12/d3d12_utils.hpp b/defold-rive/include/rive/renderer/d3d12/d3d12_utils.hpp index 87eaa12b..a7eb785e 100644 --- a/defold-rive/include/rive/renderer/d3d12/d3d12_utils.hpp +++ b/defold-rive/include/rive/renderer/d3d12/d3d12_utils.hpp @@ -65,6 +65,13 @@ class D3D12DescriptorHeap : public GPUResource UINT numElements, UINT elementByteStride, UINT64 firstElement); + void markSrvToIndex(ID3D12Device* device, + D3D12Buffer* resource, + UINT index, + UINT numElements, + UINT elementByteStride, + UINT gpuByteStride, + UINT64 firstElement); void markUavToIndex(ID3D12Device* device, D3D12Buffer* resource, DXGI_FORMAT format, diff --git a/defold-rive/include/rive/renderer/d3d12/render_context_d3d12_impl.hpp b/defold-rive/include/rive/renderer/d3d12/render_context_d3d12_impl.hpp index 16012acd..8f3b4993 100644 --- a/defold-rive/include/rive/renderer/d3d12/render_context_d3d12_impl.hpp +++ b/defold-rive/include/rive/renderer/d3d12/render_context_d3d12_impl.hpp @@ -274,5 +274,6 @@ class RenderContextD3D12Impl : public RenderContextImpl std::chrono::steady_clock::now(); bool m_isFirstFlushOfFrame = true; + bool m_usesCopyCommandList = false; }; } // namespace rive::gpu diff --git a/defold-rive/include/rive/renderer/draw.hpp b/defold-rive/include/rive/renderer/draw.hpp index 53921988..29a7183c 100644 --- a/defold-rive/include/rive/renderer/draw.hpp +++ b/defold-rive/include/rive/renderer/draw.hpp @@ -204,6 +204,7 @@ class PathDraw : public Draw enum class CoverageType { pixelLocalStorage, // InterlockMode::rasterOrdering and atomics + clockwise, // InterlockMode::clockwise clockwiseAtomic, // InterlockMode::clockwiseAtomic msaa, // InterlockMode::msaa atlas, // Any InterlockMode may opt to use atlas coverage for large diff --git a/defold-rive/include/rive/renderer/gl/gl_state.hpp b/defold-rive/include/rive/renderer/gl/gl_state.hpp index c4b678cf..d083fa25 100644 --- a/defold-rive/include/rive/renderer/gl/gl_state.hpp +++ b/defold-rive/include/rive/renderer/gl/gl_state.hpp @@ -4,6 +4,7 @@ #pragma once +#include "rive/math/aabb.hpp" #include "rive/renderer/gl/gles3.hpp" #include "rive/refcnt.hpp" #include "rive/renderer/gpu.hpp" @@ -23,13 +24,23 @@ class GLState : public RefCnt void invalidate(); + // Set the scissor with a top-down oriented box. (GLState will Y-flip the + // box before passing it to GL, which is why this function needs + // renderTargetHeight.) + void setScissor(IAABB, uint32_t renderTargetHeight); + // Set the scissor with the raw values that will be passed to glScissor(). + void setScissorRaw(uint32_t left, + uint32_t top, + uint32_t width, + uint32_t height); + void disableScissor(); void setDepthStencilEnabled(bool depthEnabled, bool stencilEnabled); void setCullFace(GLenum); - void setBlendEquation(gpu::BlendEquation); - void disableBlending() { setBlendEquation(gpu::BlendEquation::none); } void setWriteMasks(bool colorWriteMask, bool depthWriteMask, uint8_t stencilWriteMask); + void setBlendEquation(gpu::BlendEquation); + void disableBlending() { setBlendEquation(gpu::BlendEquation::none); } void setPipelineState(const gpu::PipelineState&); void bindProgram(GLuint); @@ -42,11 +53,13 @@ class GLState : public RefCnt private: const GLCapabilities m_capabilities; - gpu::BlendEquation m_blendEquation; + std::array m_scissorBox; + bool m_scissorEnabled; bool m_depthTestEnabled; bool m_stencilTestEnabled; bool m_colorWriteMask; bool m_depthWriteMask; + gpu::BlendEquation m_blendEquation; GLuint m_stencilWriteMask; GLenum m_cullFace; GLuint m_boundProgramID; @@ -56,9 +69,11 @@ class GLState : public RefCnt struct { - bool blendEquation : 1; + bool scissorBox : 1; + bool scissorEnabled : 1; bool depthStencilEnabled : 1; bool writeMasks : 1; + bool blendEquation : 1; bool cullFace : 1; bool boundProgramID : 1; bool boundVAO : 1; diff --git a/defold-rive/include/rive/renderer/gl/gles3.hpp b/defold-rive/include/rive/renderer/gl/gles3.hpp index 5a9cc8a7..e66e4998 100644 --- a/defold-rive/include/rive/renderer/gl/gles3.hpp +++ b/defold-rive/include/rive/renderer/gl/gles3.hpp @@ -176,7 +176,10 @@ struct GLCapabilities // local storage corruption issues with our renderer. Using some of the // EXT_shader_pixel_local_storage2 API is an apparent workaround that comes // with worse performance and other, less severe visual artifacts. - bool needsPixelLocalStorage2; + bool usePixelLocalStorage2AsWorkaround; + // ANGLE_shader_pixel_local_storage is currently broken with + // GL_TEXTURE_2D_ARRAY on ANGLE's d3d11 renderer. + bool avoidTexture2DArrayWithWebGLPLS; // Extensions bool ANGLE_base_vertex_base_instance_shader_builtin : 1; diff --git a/defold-rive/include/rive/renderer/gl/load_store_actions_ext.hpp b/defold-rive/include/rive/renderer/gl/load_store_actions_ext.hpp index fbd87af4..bfea10cd 100644 --- a/defold-rive/include/rive/renderer/gl/load_store_actions_ext.hpp +++ b/defold-rive/include/rive/renderer/gl/load_store_actions_ext.hpp @@ -16,14 +16,16 @@ namespace rive::gpu enum class LoadStoreActionsEXT { none = 0, - clearColor = 1, - loadColor = 2, - storeColor = 4, - clearCoverage = 8, - clearClip = 16, + clearColor = 1 << 0, + loadColor = 1 << 1, + storeColor = 1 << 2, + clearCoverage = 1 << 3, + clearClip = 1 << 4, }; RIVE_MAKE_ENUM_BITSET(LoadStoreActionsEXT) +constexpr static uint32_t LOAD_STORE_ACTIONS_EXT_COUNT = 5; + // Determines the specific load actions that need to be emulated for the given // render pass, and unpacks the clear color, if required. LoadStoreActionsEXT BuildLoadActionsEXT(const gpu::FlushDescriptor&, diff --git a/defold-rive/include/rive/renderer/gl/render_context_gl_impl.hpp b/defold-rive/include/rive/renderer/gl/render_context_gl_impl.hpp index 8118137a..ec79f734 100644 --- a/defold-rive/include/rive/renderer/gl/render_context_gl_impl.hpp +++ b/defold-rive/include/rive/renderer/gl/render_context_gl_impl.hpp @@ -114,14 +114,18 @@ class RenderContextGLImpl : public RenderContextHelperImpl public: virtual void init(rcp) {} - virtual bool supportsRasterOrdering(const GLCapabilities&) const = 0; - virtual bool supportsFragmentShaderAtomics( - const GLCapabilities&) const = 0; - - virtual void activatePixelLocalStorage(RenderContextGLImpl*, - const FlushDescriptor&) = 0; - virtual void deactivatePixelLocalStorage(RenderContextGLImpl*, - const FlushDescriptor&) = 0; + // Sets any supported interlock modes in PlatformFeatures to true. + // Leaves the rest unchanged. + virtual void getSupportedInterlockModes(const GLCapabilities&, + PlatformFeatures*) const = 0; + + virtual void resizeTransientPLSBacking(uint32_t width, + uint32_t height, + uint32_t planeCount) + {} + virtual void resizeAtomicCoverageBacking(uint32_t width, + uint32_t height) + {} // Depending on how we handle PLS atomic resolves, the // PixelLocalStorageImpl may require certain flags. @@ -136,6 +140,19 @@ class RenderContextGLImpl : public RenderContextHelperImpl gpu::InterlockMode, std::vector* defines) const = 0; + // Certain PLS draws require implementation-specific pipeline state that + // differs from the general pipeline state. + virtual void applyPipelineStateOverrides(const DrawBatch&, + const FlushDescriptor&, + const PlatformFeatures&, + PipelineState*) const + {} + + virtual void activatePixelLocalStorage(RenderContextGLImpl*, + const FlushDescriptor&) = 0; + virtual void deactivatePixelLocalStorage(RenderContextGLImpl*, + const FlushDescriptor&) = 0; + void ensureRasterOrderingEnabled(RenderContextGLImpl*, const gpu::FlushDescriptor&, bool enabled); @@ -163,7 +180,6 @@ class RenderContextGLImpl : public RenderContextHelperImpl }; class PLSImplEXTNative; - class PLSImplFramebufferFetch; class PLSImplWebGL; class PLSImplRWTexture; @@ -196,6 +212,10 @@ class RenderContextGLImpl : public RenderContextHelperImpl void resizeGradientTexture(uint32_t width, uint32_t height) override; void resizeTessellationTexture(uint32_t width, uint32_t height) override; void resizeAtlasTexture(uint32_t width, uint32_t height) override; + void resizeTransientPLSBacking(uint32_t width, + uint32_t height, + uint32_t planeCount) override; + void resizeAtomicCoverageBacking(uint32_t width, uint32_t height) override; void preBeginFrame(RenderContext*) override; @@ -277,9 +297,9 @@ class RenderContextGLImpl : public RenderContextHelperImpl glutils::Texture m_atlasTexture = glutils::Texture::Zero(); glutils::Framebuffer m_atlasFBO; - // Wraps a compiled GL shader of draw_path.glsl or draw_image_mesh.glsl, - // either vertex or fragment, with a specific set of features enabled via - // #define. The set of features to enable is dictated by ShaderFeatures. + // Wraps a compiled GL "draw" shader, either vertex or fragment, with a + // specific set of features enabled via #define. The set of features to + // enable is dictated by ShaderFeatures. class DrawShader { public: @@ -304,9 +324,9 @@ class RenderContextGLImpl : public RenderContextHelperImpl GLuint m_id = 0; }; - // Wraps a compiled and linked GL program of draw_path.glsl or - // draw_image_mesh.glsl, with a specific set of features enabled via - // #define. The set of features to enable is dictated by ShaderFeatures. + // Wraps a compiled and linked GL "draw" program, with a specific set of + // features enabled via #define. The set of features to enable is dictated + // by ShaderFeatures. class DrawProgram { public: diff --git a/defold-rive/include/rive/renderer/gl/render_target_gl.hpp b/defold-rive/include/rive/renderer/gl/render_target_gl.hpp index cdbaa11c..cafe1a9f 100644 --- a/defold-rive/include/rive/renderer/gl/render_target_gl.hpp +++ b/defold-rive/include/rive/renderer/gl/render_target_gl.hpp @@ -24,31 +24,19 @@ class RenderTargetGL : public RenderTarget, // that targets the texture. virtual void bindDestinationFramebuffer(GLenum target) = 0; - // Ensures backing textures for the internal PLS planes are allocated. - // Does not allocate an offscreen target texture. - // Does not allocate an "scratchColor" texture if InterlockMode is - // experimentalAtomics. - virtual void allocateInternalPLSTextures(gpu::InterlockMode) = 0; - - // Specifies which PLS planes to enable when a render target is bound. - enum class DrawBufferMask - { - color = 1 << 0, - clip = 1 << 1, - scratchColor = 1 << 2, - coverage = 1 << 3, - - rasterOrderingBuffers = color | coverage | clip | scratchColor, - atomicBuffers = color | coverage | clip, - }; - - // Binds a framebuffer with all allocated textures attached as color - // attachments. Used for clearing, blitting, and for rendering with - // EXT_shader_framebuffer_fetch. - // - // 'drawBufferCount' specifies the number of glDrawBuffers to enable, - // starting with GL_COLOR_ATTACHMENT0. Ignored for GL_READ_FRAMEBUFFER. - virtual void bindInternalFramebuffer(GLenum target, DrawBufferMask) = 0; + // Returns a texture handle that can be rendered to (e.g., for rendering via + // shader images, ANGLE_shader_pixel_local_storage, or + // EXT_multisampled_render_to_texture). When rendering to an external + // framebuffer, this is an internal texture allocation that the caller must + // blit back to the main framebuffer at the end of a render pass. Otherwise, + // this is the same target texture provided by the client. + virtual GLuint renderTexture() = 0; + + // Binds a framebuffer with renderTexture() attached. When rendering to an + // external framebuffer, this is an internal FBO that the caller must blit + // back to the main framebuffer at the end of a render pass. Otherwise, it's + // the main framebuffer we render to normally. + virtual void bindTextureFramebuffer(GLenum target) = 0; // Binds a "headless" framebuffer to GL_DRAW_FRAMEBUFFER with no color // attachments and no enabled draw buffers. @@ -61,10 +49,6 @@ class RenderTargetGL : public RenderTarget, // will also be bound to their corresponding pixel local storage planes. virtual void bindHeadlessFramebuffer(const GLCapabilities&) = 0; - // Binds the allocated textures to their corresponding GL image binding - // slots. - virtual void bindAsImageTextures(DrawBufferMask) = 0; - enum class MSAAResolveAction { automatic, // The MSAA framebuffer will be resolved automatically. @@ -83,9 +67,13 @@ class RenderTargetGL : public RenderTarget, const IAABB* preserveBounds = nullptr, bool* isFBO0 = nullptr) = 0; - // Binds the internal framebuffer as a texture that can be used to fetch the - // destination color (for blending). - virtual void bindInternalDstTexture(GLenum activeTexture) = 0; +#ifdef GL_ANGLE_shader_pixel_local_storage + // ANGLE_shader_pixel_local_storage requires all backing textures in a + // render pass to have identical dimensions, so we can't use the context's + // "TransientPLSBacking" resource. Instead, this method ensures backing + // textures of identical width & height to the render target are allocated. + virtual void allocateWebGLPLSBacking(const GLCapabilities&) = 0; +#endif protected: RenderTargetGL(uint32_t width, uint32_t height) : @@ -93,8 +81,6 @@ class RenderTargetGL : public RenderTarget, {} }; -RIVE_MAKE_ENUM_BITSET(RenderTargetGL::DrawBufferMask); - // GL render target that draws to an external texture provided by the client. // // Client must call setTargetTexture() before using this render target. @@ -115,43 +101,42 @@ class TextureRenderTargetGL { m_externalTextureID = externalTextureID; m_framebufferTargetAttachmentDirty = true; - m_framebufferTargetPLSBindingDirty = true; + m_webglPLSBindingsDirty = true; } void bindDestinationFramebuffer(GLenum target) final { - bindInternalFramebuffer(target, DrawBufferMask::color); + bindTextureFramebuffer(target); } - void allocateInternalPLSTextures(gpu::InterlockMode) final; - void bindInternalFramebuffer(GLenum target, DrawBufferMask) final; + GLuint renderTexture() final { return externalTextureID(); } + void bindTextureFramebuffer(GLenum target) final; void bindHeadlessFramebuffer(const GLCapabilities&) final; - void bindAsImageTextures(DrawBufferMask) final; MSAAResolveAction bindMSAAFramebuffer(RenderContextGLImpl*, int sampleCount, const IAABB* preserveBounds, bool* isFBO0) final; - void bindInternalDstTexture(GLenum activeTexture) final; + +#ifdef GL_ANGLE_shader_pixel_local_storage + void allocateWebGLPLSBacking(const GLCapabilities&) final; +#endif private: // Not owned or deleted by us. GLuint m_externalTextureID = 0; glutils::Framebuffer m_framebufferID = glutils::Framebuffer::Zero(); - glutils::Texture m_coverageTexture = glutils::Texture::Zero(); - glutils::Texture m_clipTexture = glutils::Texture::Zero(); - glutils::Texture m_scratchColorTexture = glutils::Texture::Zero(); glutils::Framebuffer m_headlessFramebuffer = glutils::Framebuffer::Zero(); - // GL enables the first drawBuffer by default. - DrawBufferMask m_internalDrawBufferMask = DrawBufferMask::color; - // For framebuffer color attachments. bool m_framebufferTargetAttachmentDirty = false; - bool m_framebufferInternalAttachmentsDirty = false; // For ANGLE_shader_pixel_local_storage attachments. - bool m_framebufferTargetPLSBindingDirty = false; - bool m_framebufferInternalPLSBindingsDirty = false; + glutils::Texture m_webglPLSBackingR32UI = glutils::Texture::Zero(); + // Fallback for when backing PLS planes with GL_TEXTURE_2D_ARRAY is broken + // (i.e., on ANGLE's d3d11 renderer). + glutils::Texture m_webglPLSBackingR32UIFallback = glutils::Texture::Zero(); + glutils::Texture m_webglPLSBackingRGBA8 = glutils::Texture::Zero(); + bool m_webglPLSBindingsDirty = false; glutils::Framebuffer m_msaaFramebuffer = glutils::Framebuffer::Zero(); glutils::Renderbuffer m_msaaColorBuffer = glutils::Renderbuffer::Zero(); @@ -187,15 +172,17 @@ class FramebufferRenderTargetGL void allocateOffscreenTargetTexture(); void bindDestinationFramebuffer(GLenum target) final; - void allocateInternalPLSTextures(gpu::InterlockMode) final; - void bindInternalFramebuffer(GLenum target, DrawBufferMask) final; + GLuint renderTexture() final; + void bindTextureFramebuffer(GLenum target) final; void bindHeadlessFramebuffer(const GLCapabilities&) final; - void bindAsImageTextures(DrawBufferMask) final; MSAAResolveAction bindMSAAFramebuffer(RenderContextGLImpl*, int sampleCount, const IAABB* preserveBounds, bool* isFBO0) final; - void bindInternalDstTexture(GLenum activeTexture) final; + +#ifdef GL_ANGLE_shader_pixel_local_storage + void allocateWebGLPLSBacking(const GLCapabilities&) final; +#endif private: // Ownership of this object is not assumed; the client must delete it when diff --git a/defold-rive/include/rive/renderer/gpu.hpp b/defold-rive/include/rive/renderer/gpu.hpp index 6c9ea93f..2cdc5276 100644 --- a/defold-rive/include/rive/renderer/gpu.hpp +++ b/defold-rive/include/rive/renderer/gpu.hpp @@ -39,6 +39,10 @@ class RenderContextImpl; class RenderTarget; class Texture; +// Global MipMap LOD Bias to apply to samplers. Going lower leads to sharper +// filtering at the expense of potential shimmering. +constexpr static float MIP_MAP_LOD_BIAS = -.5f; + // Tessellate in parametric space until each segment is within 1/4 pixel of the // true curve. constexpr static int kParametricPrecision = 4; @@ -110,15 +114,18 @@ constexpr static float DEPTH_MIN = 0.0f; constexpr static float DEPTH_MAX = 1.0f; constexpr static uint8_t STENCIL_CLEAR = 0u; -// Backend-specific capabilities/workarounds and fine tunin// g. +// Backend-specific capabilities/workarounds and fine tuning. struct PlatformFeatures { - // InterlockMode::rasterOrdering. - bool supportsRasterOrdering = false; - // InterlockMode::atomics. - bool supportsFragmentShaderAtomics = false; - // Experimental rendering mode selected by InterlockMode::clockwiseAtomic. - bool supportsClockwiseAtomicRendering = false; + // Supported InterlockModes. + // FIXME: MSAA is implicit even though it isn't implemented on all backends. + bool supportsRasterOrderingMode = false; + bool supportsAtomicMode = false; + bool supportsClockwiseMode = false; + // InterlockMode::Clockwise with fixedFunctionColorOutput and srcOver blend. + // (Only viable for frames that don't use advanced blend.) + bool supportsClockwiseFixedFunctionMode = false; + bool supportsClockwiseAtomicMode = false; // Use KHR_blend_equation_advanced in msaa mode? bool supportsBlendAdvancedKHR = false; bool supportsBlendAdvancedCoherentKHR = false; @@ -184,8 +191,14 @@ struct PlatformFeatures bool clipSpaceBottomUp = false; bool framebufferBottomUp = false; // Backend cannot initialize PLS with typical clear/load APIs in atomic - // mode. Issue a "DrawType::atomicInitialize" draw instead. - bool atomicPLSMustBeInitializedAsDraw = false; + // mode. Issue a "DrawType::renderPassInitialize" draw instead. + bool atomicPLSInitNeedsDraw = false; + // Backend API does not support initializing our (transient) MSAA color + // buffer with the existing (non-MSAA) target texture at the beginning of a + // render pass. Draw the previous renderTarget contents into it manually via + // DrawType::renderPassInitialize when LoadAction::preserveRenderTarget is + // specified. + bool msaaColorPreserveNeedsDraw = false; // Workaround for precision issues. Determines how far apart we space unique // path IDs when they will be bit-casted to fp16. uint8_t pathIDGranularity = 1; @@ -617,12 +630,6 @@ enum class DrawType : uint8_t imageRect, imageMesh, - // Clear/init PLS data when we can't do it with existing clear/load APIs. - atomicInitialize, - - // Resolve PLS data to the final renderTarget color in atomic mode. - atomicResolve, - // MSAA strokes can't be merged with fills because they require their own // dedicated stencil settings. msaaStrokes, @@ -642,6 +649,18 @@ enum class DrawType : uint8_t // Clear or intersect (based on DrawContents) the stencil clip bit. msaaStencilClipReset, + + // Clear/init render pass data with a fullscreen draw when we can't do it + // with existing clear/load APIs. (e.g., for pixel local storage in buffers + // that don't have copy/clear commands, or preserving existing color data in + // a transient MSAA arrachment). + renderPassInitialize, + + // Resolve render pass data (e.g., by applying the final deferred color in + // atomic mode, or copying an offscreen attachment to the final + // renderTarget). + renderPassResolve, + }; constexpr static bool DrawTypeIsImageDraw(DrawType drawType) @@ -656,8 +675,6 @@ constexpr static bool DrawTypeIsImageDraw(DrawType drawType) case DrawType::outerCurvePatches: case DrawType::interiorTriangulation: case DrawType::atlasBlit: - case DrawType::atomicInitialize: - case DrawType::atomicResolve: case DrawType::msaaStrokes: case DrawType::msaaMidpointFanBorrowedCoverage: case DrawType::msaaMidpointFans: @@ -666,6 +683,8 @@ constexpr static bool DrawTypeIsImageDraw(DrawType drawType) case DrawType::msaaMidpointFanPathsCover: case DrawType::msaaOuterCubics: case DrawType::msaaStencilClipReset: + case DrawType::renderPassInitialize: + case DrawType::renderPassResolve: return false; } RIVE_UNREACHABLE(); @@ -697,9 +716,9 @@ constexpr static uint32_t PatchIndexCount(DrawType drawType) case DrawType::atlasBlit: case DrawType::imageRect: case DrawType::imageMesh: - case DrawType::atomicInitialize: - case DrawType::atomicResolve: case DrawType::msaaStencilClipReset: + case DrawType::renderPassInitialize: + case DrawType::renderPassResolve: RIVE_UNREACHABLE(); } RIVE_UNREACHABLE(); @@ -729,9 +748,9 @@ constexpr static uint32_t PatchBaseIndex(DrawType drawType) case DrawType::atlasBlit: case DrawType::imageRect: case DrawType::imageMesh: - case DrawType::atomicInitialize: - case DrawType::atomicResolve: case DrawType::msaaStencilClipReset: + case DrawType::renderPassInitialize: + case DrawType::renderPassResolve: RIVE_UNREACHABLE(); } RIVE_UNREACHABLE(); @@ -750,6 +769,11 @@ enum class InterlockMode { rasterOrdering, atomics, + // Overrides every path's fill rule with clockwise, and implements the + // clockwise algorithm using raster ordering hardware. + // TODO: Once polished, this mode can be mixed into "rasterOrdering" and + // used selectively for clockwise paths. + clockwise, // Use an experimental path rendering algorithm that utilizes atomics // without barriers. This requires that we override all paths' fill rules // (winding or even/odd) with a "clockwise" fill rule, where only regions @@ -757,7 +781,11 @@ enum class InterlockMode clockwiseAtomic, msaa, }; -constexpr static size_t kInterlockModeCount = 4; +constexpr static size_t INTERLOCK_MODE_COUNT = 5; +// # of bits required to contain an InterlockMode. +constexpr static size_t INTERLOCK_MODE_BIT_COUNT = 3; +static_assert(INTERLOCK_MODE_COUNT <= (1 << INTERLOCK_MODE_BIT_COUNT)); +static_assert(INTERLOCK_MODE_COUNT > (1 << (INTERLOCK_MODE_BIT_COUNT - 1))); // Low-level batch of scissored geometry for rendering to the offscreen atlas. struct AtlasDrawBatch @@ -809,6 +837,8 @@ constexpr static ShaderFeatures ShaderFeaturesMaskFor( return kAllShaderFeatures; case InterlockMode::atomics: return kAllShaderFeatures & ~ShaderFeatures::ENABLE_NESTED_CLIPPING; + case InterlockMode::clockwise: + return kAllShaderFeatures & ~ShaderFeatures::ENABLE_EVEN_ODD; case InterlockMode::clockwiseAtomic: // TODO: shader features aren't fully implemented yet in // clockwiseAtomic mode. @@ -838,27 +868,33 @@ enum class ShaderMiscFlags : uint32_t // get filled. clockwiseFill = 1 << 1, - // clockwiseAtomic mode only. This shader is a prepass that only subtracts - // (counterclockwise) borrowed coverage from the coverage buffer. It doesn't - // output color or clip. - borrowedCoveragePrepass = 1 << 2, + // This shader only renders to the clip buffer. It doesn't output color. + clipUpdateOnly = 1 << 2, - // DrawType::atomicInitialize only. Also store the color clear value to PLS - // when drawing a clear, in addition to clearing the other PLS planes. - storeColorClear = 1 << 3, + // clockwise and clockwiseAtomic modes only. This shader renders a pass that + // only subtracts (counterclockwise) borrowed coverage from the coverage + // buffer. It doesn't output color or clip. + // If drawing interior triangulations, every fragment will be the first of + // the path at its pixel, so it can blindly overwrite coverage without + // reading the buffer and subtracting. + borrowedCoveragePass = 1 << 3, - // DrawType::atomicInitialize only. Swizzle the existing framebuffer + // DrawType::renderPassInitialize only. Also store the color clear value to + // PLS when drawing a clear, in addition to clearing the other PLS planes. + storeColorClear = 1 << 4, + + // DrawType::renderPassInitialize only. Swizzle the existing framebuffer // contents from BGRA to RGBA. (For when this data had to get copied from a // BGRA target.) - swizzleColorBGRAToRGBA = 1 << 4, + swizzleColorBGRAToRGBA = 1 << 5, - // DrawType::atomicResolve only. Optimization for when rendering to an + // DrawType::renderPassResolve only. Optimization for when rendering to an // offscreen texture. // // It renders the final "resolve" operation directly to the renderTarget in // a single pass, instead of (1) resolving the offscreen texture, and then // (2) copying the offscreen texture to back the renderTarget. - coalescedResolveAndTransfer = 1 << 5, + coalescedResolveAndTransfer = 1 << 6, }; RIVE_MAKE_ENUM_BITSET(ShaderMiscFlags) @@ -872,7 +908,7 @@ constexpr static ShaderFeatures ShaderFeaturesMaskFor( case DrawType::imageRect: case DrawType::imageMesh: case DrawType::atlasBlit: - if (interlockMode != gpu::InterlockMode::atomics) + if (interlockMode != InterlockMode::atomics) { mask = ShaderFeatures::ENABLE_CLIPPING | ShaderFeatures::ENABLE_CLIP_RECT | @@ -894,17 +930,40 @@ constexpr static ShaderFeatures ShaderFeaturesMaskFor( case DrawType::msaaMidpointFanPathsStencil: case DrawType::msaaMidpointFanPathsCover: case DrawType::msaaOuterCubics: - case DrawType::atomicResolve: mask = kAllShaderFeatures; break; - case DrawType::atomicInitialize: - assert(interlockMode == gpu::InterlockMode::atomics); - mask = ShaderFeatures::ENABLE_CLIPPING | - ShaderFeatures::ENABLE_ADVANCED_BLEND; - break; case DrawType::msaaStencilClipReset: mask = ShaderFeatures::NONE; break; + case DrawType::renderPassInitialize: + if (interlockMode == InterlockMode::atomics) + { + // Atomic mode initializes clipping and color (when advanced + // blend is active). + mask = ShaderFeatures::ENABLE_CLIPPING | + ShaderFeatures::ENABLE_ADVANCED_BLEND; + } + else + { + assert(interlockMode == InterlockMode::msaa); + // MSAA mode only needs to initialize color, and only when + // preserving the render target but using a transient MSAA + // attachment. + mask = ShaderFeatures::NONE; + } + break; + case DrawType::renderPassResolve: + if (interlockMode == InterlockMode::atomics) + { + mask = kAllShaderFeatures; + } + else + { + assert(interlockMode == InterlockMode::rasterOrdering || + interlockMode == InterlockMode::msaa); + mask = ShaderFeatures::NONE; + } + break; } return mask & ShaderFeaturesMaskFor(interlockMode); } @@ -967,8 +1026,10 @@ enum class DrawContents nonZeroFill = 1 << 4, evenOddFill = 1 << 5, activeClip = 1 << 6, - clipUpdate = 1 << 7, - advancedBlend = 1 << 8, + advancedBlend = 1 << 7, + // Put clip updates last because they use an entirely different shader in + // clockwise mode. + clipUpdate = 1 << 8, }; RIVE_MAKE_ENUM_BITSET(DrawContents) @@ -985,8 +1046,11 @@ enum class BarrierFlags : uint8_t // Pixel-local dependency in the PLS planes. (Atomic mode only.) Ensure // prior draws complete at each pixel before beginning new ones. plsAtomic = 1 << 0, - plsAtomicPostInit = 1 << 1, // Once after the initial clear/load. - plsAtomicPreResolve = 1 << 2, // Once before the final resolve. + plsAtomicPreResolve = 1 << 1, // Once before the final resolve. + + // MSAA needs a special barrier (e.g., subpass transition) after manually + // loading the render target into the transient MSAA attachment. + msaaPostInit = 1 << 2, // Pixel-local dependency in the coverage buffer. (clockwiseAtomic mode // only.) All "borrowed coverage" draws have now been issued. Ensure they @@ -999,9 +1063,14 @@ enum class BarrierFlags : uint8_t // even a full MSAA resolve & blit into a separate texture.) dstBlend = 1 << 4, + // Special barrier (e.g., subpass transition) issued prior to a manual + // render pass resolve. (Only applicable with + // FlushDescriptor::manuallyResolved.) + preManualResolve = 1 << 5, + // Only prevent future DrawBatches from being combined with the current // drawList. (No GPU dependencies.) - drawBatchBreak = 1 << 5, + drawBatchBreak = 1 << 6, }; RIVE_MAKE_ENUM_BITSET(BarrierFlags); @@ -1009,7 +1078,8 @@ RIVE_MAKE_ENUM_BITSET(BarrierFlags); struct DrawBatch { DrawBatch(DrawType drawType_, - gpu::ShaderMiscFlags shaderMiscFlags_, + ShaderMiscFlags shaderMiscFlags_, + DrawContents drawContents_, uint32_t elementCount_, uint32_t baseElement_, rive::BlendMode blendMode_, @@ -1017,6 +1087,7 @@ struct DrawBatch BarrierFlags barrierFlags_) : drawType(drawType_), shaderMiscFlags(shaderMiscFlags_), + drawContents(drawContents_), elementCount(elementCount_), baseElement(baseElement_), firstBlendMode(blendMode_), @@ -1025,13 +1096,13 @@ struct DrawBatch {} const DrawType drawType; - const ShaderMiscFlags shaderMiscFlags; + ShaderMiscFlags shaderMiscFlags; + DrawContents drawContents; uint32_t elementCount; // Vertex, index, or instance count. uint32_t baseElement; // Base vertex, index, or instance. rive::BlendMode firstBlendMode; BarrierFlags barriers; // Barriers to execute before drawing this batch. - DrawContents drawContents = DrawContents::none; ShaderFeatures shaderFeatures = ShaderFeatures::NONE; // DrawType::imageRect and DrawType::imageMesh. @@ -1049,6 +1120,17 @@ struct DrawBatch // bounding boxes needs to be blitted to the "dstRead" texture before // drawing. const Draw* dstReadList = nullptr; + + // Pointer to the next DrawBatchatch in the list that has a + // "BarrierFlags::dstBlend" barrier. + // When we need advanced blend but the underlying graphics API doesn't + // support reading the framebuffer, this can be helpful for breaking up the + // drawList into multiple render passes with framebuffer copies in between. + const DrawBatch* nextDstBlendBarrier = nullptr; + // Link to the next batch to render in the drawList. DrawBatch always exists + // in a linked list. + + const DrawBatch* next = nullptr; }; // Simple gradients only have 2 texels, so we write them to mapped texture @@ -1092,9 +1174,6 @@ struct FlushDescriptor RenderTarget* renderTarget = nullptr; ShaderFeatures combinedShaderFeatures = ShaderFeatures::NONE; InterlockMode interlockMode = InterlockMode::rasterOrdering; - // Atomic mode only: there a no advanced blend modes, so we can render - // directly to the main target with fixed function (src-over) blending. - bool atomicFixedFunctionColorOutput = false; int msaaSampleCount = 0; // (0 unless interlockMode is msaa.) LoadAction colorLoadAction = LoadAction::clear; @@ -1106,6 +1185,18 @@ struct FlushDescriptor IAABB renderTargetUpdateBounds; // drawBounds, or renderTargetBounds if // loadAction == LoadAction::clear. + // True if the drawList ends with a "renderPassResolve" draw, in which case + // the backend may need to perform special setup for a custom resolve. + bool manuallyResolved = false; + + // True if shaders will never read the color buffer, meaning, the render + // pass can use a more efficient setup that renders to a standard color + // attachment and handles all blending via built-in blend state. + // NOTE: This may be false even if all paints use srcOver because some + // rendering modes (e.g., rasterOrdering with evenOdd/nonZero) always read + // the color buffer, regardless of blend mode. + bool fixedFunctionColorOutput = false; + // Physical size of the atlas texture. uint16_t atlasTextureWidth; uint16_t atlasTextureHeight; @@ -1175,6 +1266,7 @@ struct FlushDescriptor // List of draws in the main render pass. These are rendered directly to the // renderTarget. const BlockAllocatedLinkedList* drawList = nullptr; + const DrawBatch* firstDstBlendBarrier = nullptr; }; // Returns the area of the (potentially non-rectangular) quadrilateral that @@ -1254,9 +1346,10 @@ struct FlushUniforms // Spacing between adjacent path IDs (1 if IEEE compliant). WRITEONLY uint32_t m_pathIDGranularity; WRITEONLY float m_vertexDiscardValue; + WRITEONLY float m_mipMapLODBias; WRITEONLY uint32_t m_wireframeEnabled; // Forces coverage to solid. // Uniform blocks must be multiples of 256 bytes in size. - WRITEONLY uint8_t m_padTo256Bytes[256 - 80]; + WRITEONLY uint8_t m_padTo256Bytes[256 - 84]; }; static_assert(sizeof(FlushUniforms) == 256); @@ -1659,10 +1752,10 @@ enum class StencilCompareOp : uint8_t struct StencilFaceOps { - StencilOp failOp; - StencilOp passOp; - StencilOp depthFailOp; - StencilCompareOp compareOp; + StencilOp failOp = StencilOp::keep; + StencilOp passOp = StencilOp::keep; + StencilOp depthFailOp = StencilOp::keep; + StencilCompareOp compareOp = StencilCompareOp::always; }; enum class CullFace : uint8_t @@ -1708,21 +1801,21 @@ enum class BlendEquation : uint8_t struct PipelineState { // Depth. - bool depthTestEnabled; - bool depthWriteEnabled; + bool depthTestEnabled = false; + bool depthWriteEnabled = true; // Stencil. - bool stencilTestEnabled; - uint8_t stencilCompareMask; - uint8_t stencilWriteMask; - uint8_t stencilReference; + bool stencilTestEnabled = false; + uint8_t stencilCompareMask = 0xff; + uint8_t stencilWriteMask = 0xff; + uint8_t stencilReference = 0; StencilFaceOps stencilFrontOps; StencilFaceOps stencilBackOps; - bool stencilDoubleSided; // If true, use stencilFrontOps for both faces. + bool stencilDoubleSided = false; // Use stencilFrontOps for both faces? - CullFace cullFace; - BlendEquation blendEquation; - bool colorWriteEnabled; + CullFace cullFace = CullFace::none; + BlendEquation blendEquation = BlendEquation::none; + bool colorWriteEnabled = true; // 18-bit key that uniquely identifies the pipeline state. constexpr static int UNIQUE_KEY_BIT_COUNT = 18; @@ -1734,6 +1827,9 @@ void get_pipeline_state(const DrawBatch&, const PlatformFeatures&, PipelineState*); +// Default PipelineState values as specified in OpenGL. +constexpr static PipelineState GL_DEFAULT_PIPELINE_STATE = {}; + constexpr static PipelineState COLOR_ONLY_PIPELINE_STATE = { .depthTestEnabled = false, .depthWriteEnabled = false, diff --git a/defold-rive/include/rive/renderer/render_context.hpp b/defold-rive/include/rive/renderer/render_context.hpp index 1557eba8..0194ea00 100644 --- a/defold-rive/include/rive/renderer/render_context.hpp +++ b/defold-rive/include/rive/renderer/render_context.hpp @@ -101,7 +101,7 @@ class RenderContext : public RiveRenderFactory ColorInt clearColor = 0; // If nonzero, the number of MSAA samples to use. // Setting this to a nonzero value forces msaa mode. - int msaaSampleCount = 0; + uint32_t msaaSampleCount = 0; // Use atomic mode (preferred) or msaa instead of rasterOrdering. bool disableRasterOrdering = false; @@ -311,7 +311,7 @@ class RenderContext : public RiveRenderFactory // LogicalFlush::LayoutCounters. struct ResourceAllocationCounts { - constexpr static int NUM_ELEMENTS = 14; + constexpr static int NUM_ELEMENTS = 19; using VecType = simd::gvec; RIVE_ALWAYS_INLINE VecType toVec() const @@ -323,15 +323,16 @@ class RenderContext : public RiveRenderFactory return vec; } - RIVE_ALWAYS_INLINE ResourceAllocationCounts(const VecType& vec) + static RIVE_ALWAYS_INLINE ResourceAllocationCounts + FromVec(const VecType& vec) { - static_assert(sizeof(*this) == sizeof(size_t) * NUM_ELEMENTS); - static_assert(sizeof(VecType) >= sizeof(*this)); - RIVE_INLINE_MEMCPY(this, &vec, sizeof(*this)); + ResourceAllocationCounts allocs; + static_assert(sizeof(allocs) == sizeof(size_t) * NUM_ELEMENTS); + static_assert(sizeof(VecType) >= sizeof(allocs)); + RIVE_INLINE_MEMCPY(&allocs, &vec, sizeof(allocs)); + return allocs; } - ResourceAllocationCounts() = default; - size_t flushUniformBufferCount = 0; size_t imageDrawUniformBufferCount = 0; size_t pathBufferCount = 0; @@ -345,7 +346,12 @@ class RenderContext : public RiveRenderFactory size_t tessTextureHeight = 0; size_t atlasTextureWidth = 0; size_t atlasTextureHeight = 0; - size_t coverageBufferLength = 0; // clockwiseAtomic mode only. + size_t plsTransientBackingWidth = 0; + size_t plsTransientBackingHeight = 0; + size_t plsTransientBackingPlaneCount = 0; + size_t plsAtomicCoverageBackingWidth = 0; // atomic mode only. + size_t plsAtomicCoverageBackingHeight = 0; // atomic mode only. + size_t coverageBufferLength = 0; // clockwiseAtomic mode only. }; // Reallocates GPU resources and updates m_currentResourceAllocations. @@ -561,6 +567,7 @@ class RenderContext : public RiveRenderFactory uint32_t maxTessTextureHeight = 0; uint32_t maxAtlasWidth = 0; uint32_t maxAtlasHeight = 0; + uint32_t maxPLSTransientBackingPlaneCount = 0; size_t maxCoverageBufferLength = 0; }; @@ -769,8 +776,9 @@ class RenderContext : public RiveRenderFactory // gpu::DrawBatch objects during writeResources(). std::vector m_draws; IAABB m_combinedDrawBounds; + gpu::DrawContents m_combinedDrawContents; - // Layout state. + // State computed during layout. uint32_t m_pathPaddingCount; uint32_t m_paintPaddingCount; uint32_t m_paintAuxPaddingCount; @@ -780,12 +788,17 @@ class RenderContext : public RiveRenderFactory uint32_t m_outerCubicTessEndLocation; uint32_t m_outerCubicTessVertexIdx; uint32_t m_midpointFanTessVertexIdx; - gpu::GradTextureLayout m_gradTextureLayout; + gpu::ShaderMiscFlags m_baselineShaderMiscFlags; gpu::FlushDescriptor m_flushDesc; BlockAllocatedLinkedList m_drawList; + const DrawBatch* m_firstDstBlendBarrier; + // Final "next" pointer in the list of DrawBatches that have dstBlend + // barriers. + const DrawBatch** m_dstBlendBarrierListTail; + gpu::ShaderFeatures m_combinedShaderFeatures; // Most recent path and contour state. diff --git a/defold-rive/include/rive/renderer/render_context_impl.hpp b/defold-rive/include/rive/renderer/render_context_impl.hpp index 3e4912f9..683a4a76 100644 --- a/defold-rive/include/rive/renderer/render_context_impl.hpp +++ b/defold-rive/include/rive/renderer/render_context_impl.hpp @@ -69,6 +69,20 @@ class RenderContextImpl virtual void preBeginFrame(RenderContext*) {} + // Returns true if the render context should end the drawList with a batch + // of type DrawType::renderPassResolve (and set "manuallyResolved" in the + // flush descriptor). + // This may be used, e.g., to manually resolve MSAA or to transfer pixels + // from an offscreen texture back to the main render target. + virtual bool wantsManualRenderPassResolve( + gpu::InterlockMode, + const RenderTarget*, + const IAABB& renderTargetUpdateBounds, + gpu::DrawContents combinedDrawContents) const + { + return false; + } + // Perform any bookkeeping or other tasks that need to run before // RenderContext begins accessing GPU resources for the flush. (Update // counters, advance buffer pools, etc.) @@ -113,6 +127,19 @@ class RenderContextImpl // Override this method to support atlas feathering. assert(width == 0 && height == 0); } + // Not all APIs support pure memoryless pixel local storage. This optional + // resource is a space to store PLS data that does not persist outside a + // render pass. (Namely, coverage, clip, and scratch.) + // NOTE: It is specified as a TEXTURE_2D_ARRAY because that gets better + // cache performance on Intel Arc than separate textures. + constexpr static uint32_t PLS_TRANSIENT_BACKING_MAX_PLANE_COUNT = 3; + virtual void resizeTransientPLSBacking(uint32_t width, + uint32_t height, + uint32_t planeCount) + {} + // Used in atomic mode. Similar to transient PLS backing, except it's a + // single 2D resource that also supports atomic operations. + virtual void resizeAtomicCoverageBacking(uint32_t width, uint32_t height) {} virtual void resizeCoverageBuffer(size_t sizeInBytes) { // Override this method to support the experimental clockwiseAtomic diff --git a/defold-rive/include/rive/renderer/stack_vector.hpp b/defold-rive/include/rive/renderer/stack_vector.hpp index 60feec29..e375a8c3 100644 --- a/defold-rive/include/rive/renderer/stack_vector.hpp +++ b/defold-rive/include/rive/renderer/stack_vector.hpp @@ -54,7 +54,11 @@ template class StackVector } const T* data() const { return m_data; } + T* data() { return m_data; } + const T* dataOrNull() const { return m_size != 0 ? m_data : nullptr; } + T* dataOrNull() { return m_size != 0 ? m_data : nullptr; } + const uint32_t size() const { return m_size; } private: diff --git a/defold-rive/include/rive/renderer/trivial_block_allocator.hpp b/defold-rive/include/rive/renderer/trivial_block_allocator.hpp index a0aeb5b2..68b55139 100644 --- a/defold-rive/include/rive/renderer/trivial_block_allocator.hpp +++ b/defold-rive/include/rive/renderer/trivial_block_allocator.hpp @@ -139,16 +139,22 @@ template class BlockAllocatedLinkedList bool empty() const { return count() == 0; } - T& tail() const + T* tail() const { assert(!empty()); - return m_tail->data; + return m_tail; + } + + T* head() const + { + assert(!empty()); + return m_head; } template - T& emplace_back(TrivialBlockAllocator& allocator, Args... args) + T* emplace_back(TrivialBlockAllocator& allocator, Args... args) { - Node* node = allocator.make(std::forward(args)...); + T* node = allocator.make(std::forward(args)...); assert(static_cast(m_head) == static_cast(m_tail)); if (m_head == nullptr) { @@ -160,7 +166,7 @@ template class BlockAllocatedLinkedList } m_tail = node; ++m_count; - return m_tail->data; + return m_tail; } void reset() @@ -170,28 +176,19 @@ template class BlockAllocatedLinkedList m_count = 0; } - struct Node - { - template - Node(Args... args) : data(std::forward(args)...) - {} - T data; - Node* next = nullptr; - }; - template class Iter { public: - Iter(Node* current) : m_current(current) {} + Iter(T* current) : m_current(current) {} bool operator!=(const Iter& other) const { return m_current != other.m_current; } void operator++() { m_current = m_current->next; } - U& operator*() { return m_current->data; } + U& operator*() { return *m_current; } private: - Node* m_current; + const T* m_current; }; Iter begin() { return {m_head}; } Iter end() { return {nullptr}; } @@ -199,8 +196,8 @@ template class BlockAllocatedLinkedList Iter end() const { return {nullptr}; } private: - Node* m_head = nullptr; - Node* m_tail = nullptr; + T* m_head = nullptr; + T* m_tail = nullptr; size_t m_count = 0; }; diff --git a/defold-rive/include/rive/renderer/vulkan/render_context_vulkan_impl.hpp b/defold-rive/include/rive/renderer/vulkan/render_context_vulkan_impl.hpp index 63987574..385a8c2d 100644 --- a/defold-rive/include/rive/renderer/vulkan/render_context_vulkan_impl.hpp +++ b/defold-rive/include/rive/renderer/vulkan/render_context_vulkan_impl.hpp @@ -7,28 +7,50 @@ #ifdef RIVE_VULKAN #include -#include #include -#include "rive/renderer/async_pipeline_manager.hpp" #include "rive/renderer/render_context_impl.hpp" #include "rive/renderer/vulkan/vulkan_context.hpp" -#include "rive/shapes/paint/image_sampler.hpp" namespace rive::gpu { +class DrawPipelineLayoutVulkan; +class RenderTargetVulkan; class RenderTargetVulkanImpl; class PipelineManagerVulkan; +enum class RenderPassOptionsVulkan; class RenderContextVulkanImpl : public RenderContextImpl { public: + struct ContextOptions + { + bool forceAtomicMode = false; + ShaderCompilationMode shaderCompilationMode = + ShaderCompilationMode::standard; + }; + + static std::unique_ptr MakeContext(VkInstance, + VkPhysicalDevice, + VkDevice, + const VulkanFeatures&, + PFN_vkGetInstanceProcAddr, + const ContextOptions&); + static std::unique_ptr MakeContext( - VkInstance, - VkPhysicalDevice, - VkDevice, - const VulkanFeatures&, - PFN_vkGetInstanceProcAddr, - ShaderCompilationMode = ShaderCompilationMode::standard); + VkInstance instance, + VkPhysicalDevice physicalDevice, + VkDevice device, + const VulkanFeatures& vulkanFeatures, + PFN_vkGetInstanceProcAddr fp_vkGetInstanceProcAddr) + { + return MakeContext(instance, + physicalDevice, + device, + vulkanFeatures, + fp_vkGetInstanceProcAddr, + ContextOptions{}); + } + ~RenderContextVulkanImpl(); VulkanContext* vulkanContext() const { return m_vk.get(); } @@ -51,11 +73,16 @@ class RenderContextVulkanImpl : public RenderContextImpl void hotloadShaders(rive::Span spirvData); private: - RenderContextVulkanImpl(rcp, - const VkPhysicalDeviceProperties&); + RenderContextVulkanImpl(rcp, const ContextOptions&); // Called outside the constructor so we can use virtual methods. - void initGPUObjects(ShaderCompilationMode, uint32_t vendorID); + void initGPUObjects(ShaderCompilationMode); + + bool wantsManualRenderPassResolve( + gpu::InterlockMode, + const RenderTarget*, + const IAABB& renderTargetUpdateBounds, + gpu::DrawContents combinedDrawContents) const override; void prepareToFlush(uint64_t nextFrameNumber, uint64_t safeFrameNumber) override; @@ -111,8 +138,38 @@ class RenderContextVulkanImpl : public RenderContextImpl void resizeGradientTexture(uint32_t width, uint32_t height) override; void resizeTessellationTexture(uint32_t width, uint32_t height) override; void resizeAtlasTexture(uint32_t width, uint32_t height) override; + void resizeTransientPLSBacking(uint32_t width, + uint32_t height, + uint32_t planeCount) override; + void resizeAtomicCoverageBacking(uint32_t width, uint32_t height) override; void resizeCoverageBuffer(size_t sizeInBytes) override; + // Lazy accessors for PLS backing resources. These are lazy because our + // Vulkan backend needs different allocations based on interlock mode and + // other factors. + vkutil::Image* plsTransientImageArray(); + vkutil::ImageView* plsTransientCoverageView(); + vkutil::ImageView* plsTransientClipView(); + vkutil::Texture2D* plsTransientScratchColorTexture(); + + // The offscreen color texture is not transient and supports PLS. It is used + // in place of the renderTarget (via copying in and out) when the + // renderTarget doesn't support PLS. + vkutil::Texture2D* accessPLSOffscreenColorTexture( + VkCommandBuffer, + const vkutil::ImageAccess&, + vkutil::ImageAccessAction = + vkutil::ImageAccessAction::preserveContents); + vkutil::Texture2D* clearPLSOffscreenColorTexture( + VkCommandBuffer, + ColorInt, + const vkutil::ImageAccess& dstAccessAfterClear); + vkutil::Texture2D* copyRenderTargetToPLSOffscreenColorTexture( + VkCommandBuffer, + RenderTargetVulkan*, + const IAABB& copyBounds, + const vkutil::ImageAccess& dstAccessAfterCopy); + // Wraps a VkDescriptorPool created specifically for a PLS flush, and tracks // its allocated descriptor sets. class DescriptorSetPool final : public vkutil::Resource @@ -128,6 +185,14 @@ class RenderContextVulkanImpl : public RenderContextImpl VkDescriptorPool m_vkDescriptorPool; }; + const DrawPipelineLayoutVulkan& beginDrawRenderPass( + const FlushDescriptor& desc, + RenderPassOptionsVulkan, + const IAABB& drawBounds, + VkImageView colorImageView, + VkImageView msaaColorSeedImageView, + VkImageView msaaResolveImageView); + void flush(const FlushDescriptor&) override; void postFlush(const RenderContext::FlushResources&) override; @@ -140,6 +205,31 @@ class RenderContextVulkanImpl : public RenderContextImpl const rcp m_vk; + struct DriverWorkarounds + { + // Some early Android tilers are known to crash when a render pass is + // too complex. On these devices, we limit the maximum number of + // instances that can be issued in a single render pass. + uint32_t maxInstancesPerRenderPass = UINT32_MAX; + bool needsInterruptibleRenderPasses() const + { + // If we have a limit on maxInstancesPerRenderPass, then our render + // passes need to be interruptible so we can close them off and + // start new ones in case we encounter too many instances. + return maxInstancesPerRenderPass != UINT32_MAX; + } + // Early Xclipse drivers struggle with our manual msaa resolve, so we + // always do automatic fullscreen resolves on that GPU family. + bool avoidManualMSAAResolves = false; + // Some Android drivers (some Android 12 and earlier Adreno drivers) + // have issues with having both a self-dependency for dst reads and + // resolve attachments. For now we just always manually resolve these + // render passes that use advanced blend on Qualcomm. + bool needsManualMSAAResolveAfterDstRead = true; + }; + + const DriverWorkarounds m_workarounds; + // Rive buffer pools. These don't need to be rcp<> because the destructor of // RenderContextVulkanImpl is already synchronized. vkutil::BufferPool m_flushUniformBufferPool; @@ -170,6 +260,10 @@ class RenderContextVulkanImpl : public RenderContextImpl // Bound when there is not an image paint. rcp m_nullImageTexture; + // Common base class for a pipeline that renders a texture resource at the + // beginning of a flush, which is then read during the main draw pass. + class ResourceTexturePipeline; + // Renders color ramps to the gradient texture. class ColorRampPipeline; std::unique_ptr m_colorRampPipeline; @@ -181,6 +275,7 @@ class RenderContextVulkanImpl : public RenderContextImpl std::unique_ptr m_tessellatePipeline; rcp m_tessSpanIndexBuffer; rcp m_tessTexture; + rcp m_tesselationSyncIssueWorkaroundTexture; rcp m_tessTextureFramebuffer; // Renders feathers to the atlas. @@ -189,6 +284,17 @@ class RenderContextVulkanImpl : public RenderContextImpl rcp m_atlasTexture; rcp m_atlasFramebuffer; + // Pixel local storage backing resources. + VkImageUsageFlags m_plsTransientUsageFlags; + VkExtent3D m_plsExtent = {0, 0, 1}; + uint32_t m_plsTransientPlaneCount = 0; + rcp m_plsTransientImageArray; + rcp m_plsTransientCoverageView; + rcp m_plsTransientClipView; + rcp m_plsTransientScratchColorTexture; + rcp m_plsOffscreenColorTexture; + rcp m_plsAtomicCoverageTexture; + // Coverage buffer used by shaders in clockwiseAtomic mode. rcp m_coverageBuffer; diff --git a/defold-rive/include/rive/renderer/vulkan/render_target_vulkan.hpp b/defold-rive/include/rive/renderer/vulkan/render_target_vulkan.hpp index 5598e3ef..a1f9b708 100644 --- a/defold-rive/include/rive/renderer/vulkan/render_target_vulkan.hpp +++ b/defold-rive/include/rive/renderer/vulkan/render_target_vulkan.hpp @@ -19,16 +19,16 @@ class RenderTargetVulkan : public RenderTarget return m_targetUsageFlags; } - // Returns the target image in the requested layout, performing a pipeline - // barrier if necessary. + // Performs a pipeline barrier and returns the target image in the requested + // layout. virtual VkImage accessTargetImage( VkCommandBuffer, const vkutil::ImageAccess& dstAccess, vkutil::ImageAccessAction = vkutil::ImageAccessAction::preserveContents) = 0; - // Returns the target image view, with its image in the requested layout, - // performing a pipeline barrier if necessary. + // Performs a pipeline barrier, transitions the target image to the + // requested layout, and returns the target image view. virtual VkImageView accessTargetImageView( VkCommandBuffer, const vkutil::ImageAccess& dstAccess, @@ -44,22 +44,29 @@ class RenderTargetVulkan : public RenderTarget VkFormat framebufferFormat, VkImageUsageFlags targetUsageFlags); - // Returns the offscreen texture in the requested layout, performing a - // pipeline barrier if necessary. + // Performs pipeline barriers, clears the target image, transitions the + // target image to the requested layout, and returns target image view. + VkImageView clearTargetImageView( + VkCommandBuffer, + ColorInt clearColor, + const vkutil::ImageAccess& dstAccessAfterClear); + + // Performs a pipeline barrier and returns the offscreen texture in the + // requested layout. vkutil::Texture2D* accessOffscreenColorTexture( VkCommandBuffer, const vkutil::ImageAccess& dstAccess, vkutil::ImageAccessAction = vkutil::ImageAccessAction::preserveContents); - // InterlockMode::rasterOrdering. - vkutil::Texture2D* clipTextureR32UI(); - vkutil::Texture2D* scratchColorTexture(); - vkutil::Texture2D* coverageTexture(); - - // InterlockMode::atomics. - vkutil::Texture2D* clipTextureRGBA8(); - vkutil::Texture2D* coverageAtomicTexture(); + // Performs pipeline barriers, copies the target image into the + // offscreen color texture (for the intended purpose of supporting + // gpu::LoadAction::preserveRenderTarget), and returns the offscreen texture + // in the requested layout. + vkutil::Texture2D* copyTargetImageToOffscreenColorTexture( + VkCommandBuffer, + const vkutil::ImageAccess& dstAccessAfterCopy, + const IAABB& copyBounds); // InterlockMode::msaa. vkutil::Texture2D* msaaColorTexture(); @@ -73,15 +80,6 @@ class RenderTargetVulkan : public RenderTarget // VK_ACCESS_INPUT_ATTACHMENT_READ_BIT rcp m_offscreenColorTexture; - // InterlockMode::rasterOrdering. - rcp m_clipTextureR32UI; - rcp m_scratchColorTexture; - rcp m_coverageTexture; - - // InterlockMode::atomics. - rcp m_clipTextureRGBA8; - rcp m_coverageAtomicTexture; - // InterlockMode::msaa. rcp m_msaaColorTexture; rcp m_msaaDepthStencilTexture; diff --git a/defold-rive/include/rive/renderer/vulkan/vkutil.hpp b/defold-rive/include/rive/renderer/vulkan/vkutil.hpp index 356a1db4..ce390302 100644 --- a/defold-rive/include/rive/renderer/vulkan/vkutil.hpp +++ b/defold-rive/include/rive/renderer/vulkan/vkutil.hpp @@ -22,12 +22,15 @@ class VulkanContext; namespace rive::gpu::vkutil { +const char* string_from_vk_result(VkResult); + inline static void vk_check(VkResult res, const char* file, int line) { if (res != VK_SUCCESS) { fprintf(stderr, - "Vulkan error %i at line: %i in file: %s\n", + "Vulkan error %s (%i) at line: %i in file: %s\n", + string_from_vk_result(res), res, line, file); @@ -147,7 +150,7 @@ class Image : public Resource private: friend class ::rive::gpu::VulkanContext; - Image(rcp, const VkImageCreateInfo&); + Image(rcp, const VkImageCreateInfo&, const char* name); VkImageCreateInfo m_info; VmaAllocation m_vmaAllocation; @@ -169,7 +172,8 @@ class ImageView : public Resource ImageView(rcp, rcp textureRef, - const VkImageViewCreateInfo&); + const VkImageViewCreateInfo&, + const char* name); const rcp m_textureRefOrNull; VkImageViewCreateInfo m_info; @@ -212,7 +216,9 @@ class Texture2D : public rive::gpu::Texture ImageAccess& lastAccess() { return m_lastAccess; } // Deferred mechanism for uploading image data without a command buffer. - void scheduleUpload(const void* imageData, size_t imageDataSizeInBytes); + void scheduleUpload(const void* imageDataRGBAPremul, + size_t imageDataSizeInBytes); + void scheduleUpload(rcp imageBufferRGBAPremul); void barrier(VkCommandBuffer, const ImageAccess& dstAccess, @@ -226,8 +232,27 @@ class Texture2D : public rive::gpu::Texture // point. void generateMipmaps(VkCommandBuffer, const ImageAccess& dstAccess); - // This method is inlined intentionally, in order to avoid function calls in - // the common usecase. + // These methods are inlined intentionally, in order to avoid function calls + // in the common usecase. + inline void prepareForVertexOrFragmentShaderRead( + VkCommandBuffer commandBuffer) + { + if (m_imageUploadBuffer != nullptr) + { + applyImageUploadBuffer(commandBuffer); + } + constexpr static ImageAccess READ_ACCESS = { + .pipelineStages = VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | + VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, + .accessMask = VK_ACCESS_SHADER_READ_BIT, + .layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, + }; + if (m_lastAccess != READ_ACCESS) + { + barrier(commandBuffer, READ_ACCESS); + } + } + inline void prepareForFragmentShaderRead(VkCommandBuffer commandBuffer) { if (m_imageUploadBuffer != nullptr) @@ -270,7 +295,7 @@ class Texture2D : public rive::gpu::Texture void applyImageUploadBuffer(VkCommandBuffer); - Texture2D(rcp vk, VkImageCreateInfo); + Texture2D(rcp vk, VkImageCreateInfo, const char* name); rcp m_image; rcp m_imageView; diff --git a/defold-rive/include/rive/renderer/vulkan/vulkan_context.hpp b/defold-rive/include/rive/renderer/vulkan/vulkan_context.hpp index f943acfa..2965993e 100644 --- a/defold-rive/include/rive/renderer/vulkan/vulkan_context.hpp +++ b/defold-rive/include/rive/renderer/vulkan/vulkan_context.hpp @@ -26,6 +26,12 @@ struct VulkanFeatures // EXT_rasterization_order_attachment_access. bool rasterizationOrderColorAttachmentAccess = false; + + // VK_EXT_fragment_shader_interlock. + bool fragmentShaderPixelInterlock = false; + + // Indicates a nonconformant driver, like MoltenVK. + bool VK_KHR_portability_subset = false; }; // Wraps a VkDevice, function dispatch table, and VMA library instance. @@ -55,7 +61,8 @@ class VulkanContext : public GPUResourceManager #define RIVE_VULKAN_INSTANCE_COMMANDS(F) \ F(GetDeviceProcAddr) \ F(GetPhysicalDeviceFormatProperties) \ - F(GetPhysicalDeviceProperties) + F(GetPhysicalDeviceProperties) \ + F(SetDebugUtilsObjectNameEXT) #define RIVE_VULKAN_DEVICE_COMMANDS(F) \ F(AllocateDescriptorSets) \ @@ -103,18 +110,26 @@ class VulkanContext : public GPUResourceManager VmaAllocator allocator() const { return m_vmaAllocator; } + const VkPhysicalDeviceProperties& physicalDeviceProperties() const + { + return m_physicalDeviceProperties; + } + bool isFormatSupportedWithFeatureFlags(VkFormat, VkFormatFeatureFlagBits); bool supportsD24S8() const { return m_supportsD24S8; } // Resource allocation. rcp makeBuffer(const VkBufferCreateInfo&, vkutil::Mappability); - rcp makeImage(const VkImageCreateInfo&); - rcp makeImageView(rcp); + rcp makeImage(const VkImageCreateInfo&, const char* name); + rcp makeImageView(rcp, const char* name); rcp makeImageView(rcp, - const VkImageViewCreateInfo&); - rcp makeExternalImageView(const VkImageViewCreateInfo&); - rcp makeTexture2D(const VkImageCreateInfo&); + const VkImageViewCreateInfo&, + const char* name); + rcp makeExternalImageView(const VkImageViewCreateInfo&, + const char* name); + rcp makeTexture2D(const VkImageCreateInfo&, + const char* name); rcp makeFramebuffer(const VkFramebufferCreateInfo&); // Helpers. @@ -168,14 +183,24 @@ class VulkanContext : public GPUResourceManager VkDependencyFlags, VkBufferMemoryBarrier); + void clearColorImage(VkCommandBuffer, ColorInt, VkImage, VkImageLayout); + void blitSubRect(VkCommandBuffer commandBuffer, - VkImage src, - VkImage dst, + VkImage srcImage, + VkImageLayout srcImageLayout, + VkImage dstImage, + VkImageLayout dstImageLayout, const IAABB&); + void setDebugNameIfEnabled(uint64_t handle, + VkObjectType objectType, + const char* name); + private: const VmaAllocator m_vmaAllocator; + VkPhysicalDeviceProperties m_physicalDeviceProperties; + // Vulkan spec: must support one of D24S8 and D32S8. bool m_supportsD24S8 = false; }; diff --git a/defold-rive/include/rive/renderer/webgpu/render_context_webgpu_impl.hpp b/defold-rive/include/rive/renderer/webgpu/render_context_webgpu_impl.hpp index 1c2c067c..e2715e82 100644 --- a/defold-rive/include/rive/renderer/webgpu/render_context_webgpu_impl.hpp +++ b/defold-rive/include/rive/renderer/webgpu/render_context_webgpu_impl.hpp @@ -44,6 +44,11 @@ class RenderContextWebGPUImpl : public RenderContextHelperImpl { wgpu::BackendType backendType = wgpu::BackendType::Undefined; #ifdef RIVE_WAGYU + // Driver extensions. + bool VK_EXT_rasterization_order_attachment_access = false; + bool GL_EXT_shader_pixel_local_storage = false; + bool GL_EXT_shader_pixel_local_storage2 = false; + PixelLocalStorageType plsType = PixelLocalStorageType::none; // Rive requires 4 storage buffers in the vertex shader. We polyfill @@ -84,16 +89,42 @@ class RenderContextWebGPUImpl : public RenderContextHelperImpl const ContextOptions&); // Create a standard PLS "draw" pipeline for the current implementation. - wgpu::RenderPipeline makeDrawPipeline(rive::gpu::DrawType drawType, + wgpu::RenderPipeline makeDrawPipeline(rive::gpu::DrawType, + gpu::InterlockMode, + gpu::ShaderMiscFlags, wgpu::TextureFormat framebufferFormat, wgpu::ShaderModule vertexShader, - wgpu::ShaderModule fragmentShader); + wgpu::ShaderModule fragmentShader, + const gpu::PipelineState&); + + // Begin a Rive render pass that uses pixel local storage. + wgpu::RenderPassEncoder beginPLSRenderPass(wgpu::CommandEncoder, + const FlushDescriptor&); + + // Specifies how to load MSAA color/depth/stencil attachments when beginning + // an MSAA render pass. + enum class MSAABeginType : bool + { + primary, + restartAfterDstCopy, + }; + + // Specifies how to store MSAA color/depth/stencil attachments when ending + // an MSAA render pass. + enum class MSAAEndType : bool + { + finish, + breakForDstCopy, + }; + + // Begin a Rive render pass that uses MSAA. + wgpu::RenderPassEncoder beginMSAARenderPass(wgpu::CommandEncoder, + MSAABeginType, + MSAAEndType, + const FlushDescriptor&); - // Create a standard PLS "draw" render pass for the current implementation. - wgpu::RenderPassEncoder makePLSRenderPass(wgpu::CommandEncoder, - const RenderTargetWebGPU*, - wgpu::LoadOp, - const wgpu::Color& clearColor); + // Set the initial render pass state for draws (viewport, bindings, etc.). + void initDrawRenderPass(wgpu::RenderPassEncoder, const FlushDescriptor&); wgpu::PipelineLayout drawPipelineLayout() const { @@ -127,7 +158,7 @@ class RenderContextWebGPUImpl : public RenderContextHelperImpl constexpr static int COLOR_RAMP_BINDINGS_COUNT = 1; constexpr static int TESS_BINDINGS_COUNT = 6; constexpr static int ATLAS_BINDINGS_COUNT = 7; - constexpr static int DRAW_BINDINGS_COUNT = 10; + constexpr static int DRAW_BINDINGS_COUNT = 11; std::array m_perFlushBindingLayouts; @@ -135,7 +166,7 @@ class RenderContextWebGPUImpl : public RenderContextHelperImpl // Draws emulated render-pass load/store actions for // EXT_shader_pixel_local_storage. class LoadStoreEXTPipeline; - std::map m_loadStoreEXTPipelines; + std::map m_loadStoreEXTPipelines; wgpu::ShaderModule m_loadStoreEXTVertexShader; std::unique_ptr m_loadStoreEXTUniforms; #endif @@ -167,7 +198,7 @@ class RenderContextWebGPUImpl : public RenderContextHelperImpl // Draw paths and image meshes using the gradient and tessellation textures. class DrawPipeline; - std::map m_drawPipelines; + std::map m_drawPipelines; wgpu::BindGroupLayout m_drawBindGroupLayouts[4 /*BINDINGS_SET_COUNT*/]; wgpu::Sampler m_linearSampler; wgpu::Sampler m_imageSamplers[ImageSampler::MAX_SAMPLER_PERMUTATIONS]; @@ -181,9 +212,9 @@ class RenderContextWebGPUImpl : public RenderContextHelperImpl wgpu::Texture m_featherTexture; wgpu::TextureView m_featherTextureView; - // Bound when there is not an image paint. - wgpu::Texture m_nullImagePaintTexture; - wgpu::TextureView m_nullImagePaintTextureView; + // Bound when a texture binding is unused. + wgpu::Texture m_nullTexture; + wgpu::TextureView m_nullTextureView; }; class RenderTargetWebGPU : public RenderTarget @@ -194,6 +225,8 @@ class RenderTargetWebGPU : public RenderTarget return m_framebufferFormat; } + wgpu::Texture targetTexture() const { return m_targetTexture; }; + wgpu::TextureView targetTextureView() const { return m_targetTextureView; }; void setTargetTextureView(wgpu::TextureView, wgpu::Texture); protected: @@ -203,20 +236,42 @@ class RenderTargetWebGPU : public RenderTarget uint32_t width, uint32_t height); + // Lazily loaded render pass resources. + wgpu::TextureView coverageTextureView(); + wgpu::TextureView clipTextureView(); + wgpu::TextureView scratchColorTextureView(); + wgpu::TextureView msaaColorTextureView(); + wgpu::TextureView msaaDepthStencilTextureView(); + wgpu::Texture dstColorTexture(); + wgpu::TextureView dstColorTextureView(); + + // Copies a sub-rectangle of the targetTexture to the dstColorTexture for + // shader blending. Shaders can't read from the targetTexture itself because + // it's also the resolveTarget. + void copyTargetToDstColorTexture(wgpu::CommandEncoder, IAABB dstReadBounds); + private: friend class RenderContextWebGPUImpl; + const wgpu::Device m_device; const wgpu::TextureFormat m_framebufferFormat; + wgpu::TextureUsage m_transientPLSUsage; wgpu::Texture m_targetTexture; wgpu::Texture m_coverageTexture; wgpu::Texture m_clipTexture; wgpu::Texture m_scratchColorTexture; + wgpu::Texture m_msaaColorTexture; + wgpu::Texture m_msaaDepthStencilTexture; + wgpu::Texture m_dstColorTexture; wgpu::TextureView m_targetTextureView; wgpu::TextureView m_coverageTextureView; wgpu::TextureView m_clipTextureView; wgpu::TextureView m_scratchColorTextureView; + wgpu::TextureView m_msaaColorTextureView; + wgpu::TextureView m_msaaDepthStencilTextureView; + wgpu::TextureView m_dstColorTextureView; }; class TextureWebGPUImpl : public Texture diff --git a/defold-rive/include/rive/renderer/webgpu/wagyu-port/new/include/webgpu/webgpu.h b/defold-rive/include/rive/renderer/webgpu/wagyu-port/include/webgpu/webgpu.h similarity index 92% rename from defold-rive/include/rive/renderer/webgpu/wagyu-port/new/include/webgpu/webgpu.h rename to defold-rive/include/rive/renderer/webgpu/wagyu-port/include/webgpu/webgpu.h index 921364e0..1655e574 100644 --- a/defold-rive/include/rive/renderer/webgpu/wagyu-port/new/include/webgpu/webgpu.h +++ b/defold-rive/include/rive/renderer/webgpu/wagyu-port/include/webgpu/webgpu.h @@ -31,12 +31,6 @@ #ifndef WEBGPU_H_ #define WEBGPU_H_ -#define WGPU_BREAKING_CHANGE_STRING_VIEW_LABELS -#define WGPU_BREAKING_CHANGE_STRING_VIEW_OUTPUT_STRUCTS -#define WGPU_BREAKING_CHANGE_STRING_VIEW_CALLBACKS -#define WGPU_BREAKING_CHANGE_QUEUE_WORK_DONE_CALLBACK_MESSAGE -#define WGPU_BREAKING_CHANGE_COMPATIBILITY_MODE_LIMITS - #if defined(WGPU_SHARED_LIBRARY) # if defined(_WIN32) # if defined(WGPU_IMPLEMENTATION) @@ -108,10 +102,6 @@ #define WGPU_WHOLE_MAP_SIZE (SIZE_MAX) #define WGPU_WHOLE_SIZE (UINT64_MAX) -#if defined(USE_WGPU_WAGYU_NAMESPACE) || defined(__cppcheck) -namespace wagyu2 { -#endif - typedef struct WGPUStringView { WGPU_NULLABLE char const * data; size_t length; @@ -163,7 +153,7 @@ struct WGPUDawnCompilationMessageUtf16; struct WGPUEmscriptenSurfaceSourceCanvasHTMLSelector; struct WGPUExtent3D; struct WGPUFuture; -struct WGPUInstanceCapabilities; +struct WGPUInstanceLimits; struct WGPUINTERNAL_HAVE_EMDAWNWEBGPU_HEADER; struct WGPUMultisampleState; struct WGPUOrigin3D; @@ -184,6 +174,7 @@ struct WGPUShaderSourceWGSL; struct WGPUStencilFaceState; struct WGPUStorageTextureBindingLayout; struct WGPUSupportedFeatures; +struct WGPUSupportedInstanceFeatures; struct WGPUSupportedWGSLLanguageFeatures; struct WGPUSurfaceCapabilities; struct WGPUSurfaceColorManagement; @@ -192,7 +183,7 @@ struct WGPUSurfaceTexture; struct WGPUTexelCopyBufferLayout; struct WGPUTextureBindingLayout; struct WGPUTextureBindingViewDimensionDescriptor; -struct WGPUTextureViewDescriptor; +struct WGPUTextureComponentSwizzle; struct WGPUVertexAttribute; struct WGPUBindGroupDescriptor; struct WGPUBindGroupLayoutEntry; @@ -210,6 +201,7 @@ struct WGPUShaderModuleDescriptor; struct WGPUSurfaceDescriptor; struct WGPUTexelCopyBufferInfo; struct WGPUTexelCopyTextureInfo; +struct WGPUTextureComponentSwizzleDescriptor; struct WGPUTextureDescriptor; struct WGPUVertexBufferLayout; struct WGPUBindGroupLayoutDescriptor; @@ -218,6 +210,7 @@ struct WGPUCompilationInfo; struct WGPUComputePipelineDescriptor; struct WGPUDeviceDescriptor; struct WGPURenderPassDescriptor; +struct WGPUTextureViewDescriptor; struct WGPUVertexState; struct WGPUFragmentState; struct WGPURenderPipelineDescriptor; @@ -344,6 +337,17 @@ typedef enum WGPUCompilationMessageType { WGPUCompilationMessageType_Force32 = 0x7FFFFFFF } WGPUCompilationMessageType WGPU_ENUM_ATTRIBUTE; +typedef enum WGPUComponentSwizzle { + WGPUComponentSwizzle_Undefined = 0x00000000, + WGPUComponentSwizzle_Zero = 0x00000001, + WGPUComponentSwizzle_One = 0x00000002, + WGPUComponentSwizzle_R = 0x00000003, + WGPUComponentSwizzle_G = 0x00000004, + WGPUComponentSwizzle_B = 0x00000005, + WGPUComponentSwizzle_A = 0x00000006, + WGPUComponentSwizzle_Force32 = 0x7FFFFFFF +} WGPUComponentSwizzle WGPU_ENUM_ATTRIBUTE; + typedef enum WGPUCompositeAlphaMode { WGPUCompositeAlphaMode_Auto = 0x00000000, WGPUCompositeAlphaMode_Opaque = 0x00000001, @@ -401,24 +405,28 @@ typedef enum WGPUFeatureLevel { } WGPUFeatureLevel WGPU_ENUM_ATTRIBUTE; typedef enum WGPUFeatureName { - WGPUFeatureName_DepthClipControl = 0x00000001, - WGPUFeatureName_Depth32FloatStencil8 = 0x00000002, - WGPUFeatureName_TimestampQuery = 0x00000003, + WGPUFeatureName_CoreFeaturesAndLimits = 0x00000001, + WGPUFeatureName_DepthClipControl = 0x00000002, + WGPUFeatureName_Depth32FloatStencil8 = 0x00000003, WGPUFeatureName_TextureCompressionBC = 0x00000004, WGPUFeatureName_TextureCompressionBCSliced3D = 0x00000005, WGPUFeatureName_TextureCompressionETC2 = 0x00000006, WGPUFeatureName_TextureCompressionASTC = 0x00000007, WGPUFeatureName_TextureCompressionASTCSliced3D = 0x00000008, - WGPUFeatureName_IndirectFirstInstance = 0x00000009, - WGPUFeatureName_ShaderF16 = 0x0000000A, - WGPUFeatureName_RG11B10UfloatRenderable = 0x0000000B, - WGPUFeatureName_BGRA8UnormStorage = 0x0000000C, - WGPUFeatureName_Float32Filterable = 0x0000000D, - WGPUFeatureName_Float32Blendable = 0x0000000E, - WGPUFeatureName_ClipDistances = 0x0000000F, - WGPUFeatureName_DualSourceBlending = 0x00000010, - WGPUFeatureName_Subgroups = 0x00000011, - WGPUFeatureName_CoreFeaturesAndLimits = 0x00000012, + WGPUFeatureName_TimestampQuery = 0x00000009, + WGPUFeatureName_IndirectFirstInstance = 0x0000000A, + WGPUFeatureName_ShaderF16 = 0x0000000B, + WGPUFeatureName_RG11B10UfloatRenderable = 0x0000000C, + WGPUFeatureName_BGRA8UnormStorage = 0x0000000D, + WGPUFeatureName_Float32Filterable = 0x0000000E, + WGPUFeatureName_Float32Blendable = 0x0000000F, + WGPUFeatureName_ClipDistances = 0x00000010, + WGPUFeatureName_DualSourceBlending = 0x00000011, + WGPUFeatureName_Subgroups = 0x00000012, + WGPUFeatureName_TextureFormatsTier1 = 0x00000013, + WGPUFeatureName_TextureFormatsTier2 = 0x00000014, + WGPUFeatureName_PrimitiveIndex = 0x00000015, + WGPUFeatureName_TextureComponentSwizzle = 0x00000016, WGPUFeatureName_Unorm16TextureFormats = 0x0005000C, WGPUFeatureName_Snorm16TextureFormats = 0x0005000D, WGPUFeatureName_MultiDrawIndirect = 0x00050034, @@ -446,6 +454,13 @@ typedef enum WGPUIndexFormat { WGPUIndexFormat_Force32 = 0x7FFFFFFF } WGPUIndexFormat WGPU_ENUM_ATTRIBUTE; +typedef enum WGPUInstanceFeatureName { + WGPUInstanceFeatureName_TimedWaitAny = 0x00000001, + WGPUInstanceFeatureName_ShaderSourceSPIRV = 0x00000002, + WGPUInstanceFeatureName_MultipleDevicesPerAdapter = 0x00000003, + WGPUInstanceFeatureName_Force32 = 0x7FFFFFFF +} WGPUInstanceFeatureName WGPU_ENUM_ATTRIBUTE; + typedef enum WGPULoadOp { WGPULoadOp_Undefined = 0x00000000, WGPULoadOp_Load = 0x00000001, @@ -598,6 +613,7 @@ typedef enum WGPUSType { WGPUSType_SurfaceSourceXCBWindow = 0x00000009, WGPUSType_SurfaceColorManagement = 0x0000000A, WGPUSType_RequestAdapterWebXROptions = 0x0000000B, + WGPUSType_TextureComponentSwizzleDescriptor = 0x0000000C, WGPUSType_CompatibilityModeLimits = 0x00020000, WGPUSType_TextureBindingViewDimensionDescriptor = 0x00020001, WGPUSType_EmscriptenSurfaceSourceCanvasHTMLSelector = 0x00040000, @@ -605,14 +621,6 @@ typedef enum WGPUSType { WGPUSType_Force32 = 0x7FFFFFFF } WGPUSType WGPU_ENUM_ATTRIBUTE; -typedef enum WGPUSubgroupMatrixComponentType { - WGPUSubgroupMatrixComponentType_F32 = 0x00000001, - WGPUSubgroupMatrixComponentType_F16 = 0x00000002, - WGPUSubgroupMatrixComponentType_U32 = 0x00000003, - WGPUSubgroupMatrixComponentType_I32 = 0x00000004, - WGPUSubgroupMatrixComponentType_Force32 = 0x7FFFFFFF -} WGPUSubgroupMatrixComponentType WGPU_ENUM_ATTRIBUTE; - typedef enum WGPUSurfaceGetCurrentTextureStatus { WGPUSurfaceGetCurrentTextureStatus_SuccessOptimal = 0x00000001, WGPUSurfaceGetCurrentTextureStatus_SuccessSuboptimal = 0x00000002, @@ -645,97 +653,103 @@ typedef enum WGPUTextureFormat { WGPUTextureFormat_R8Snorm = 0x00000002, WGPUTextureFormat_R8Uint = 0x00000003, WGPUTextureFormat_R8Sint = 0x00000004, - WGPUTextureFormat_R16Uint = 0x00000005, - WGPUTextureFormat_R16Sint = 0x00000006, - WGPUTextureFormat_R16Float = 0x00000007, - WGPUTextureFormat_RG8Unorm = 0x00000008, - WGPUTextureFormat_RG8Snorm = 0x00000009, - WGPUTextureFormat_RG8Uint = 0x0000000A, - WGPUTextureFormat_RG8Sint = 0x0000000B, - WGPUTextureFormat_R32Float = 0x0000000C, - WGPUTextureFormat_R32Uint = 0x0000000D, - WGPUTextureFormat_R32Sint = 0x0000000E, - WGPUTextureFormat_RG16Uint = 0x0000000F, - WGPUTextureFormat_RG16Sint = 0x00000010, - WGPUTextureFormat_RG16Float = 0x00000011, - WGPUTextureFormat_RGBA8Unorm = 0x00000012, - WGPUTextureFormat_RGBA8UnormSrgb = 0x00000013, - WGPUTextureFormat_RGBA8Snorm = 0x00000014, - WGPUTextureFormat_RGBA8Uint = 0x00000015, - WGPUTextureFormat_RGBA8Sint = 0x00000016, - WGPUTextureFormat_BGRA8Unorm = 0x00000017, - WGPUTextureFormat_BGRA8UnormSrgb = 0x00000018, - WGPUTextureFormat_RGB10A2Uint = 0x00000019, - WGPUTextureFormat_RGB10A2Unorm = 0x0000001A, - WGPUTextureFormat_RG11B10Ufloat = 0x0000001B, - WGPUTextureFormat_RGB9E5Ufloat = 0x0000001C, - WGPUTextureFormat_RG32Float = 0x0000001D, - WGPUTextureFormat_RG32Uint = 0x0000001E, - WGPUTextureFormat_RG32Sint = 0x0000001F, - WGPUTextureFormat_RGBA16Uint = 0x00000020, - WGPUTextureFormat_RGBA16Sint = 0x00000021, - WGPUTextureFormat_RGBA16Float = 0x00000022, - WGPUTextureFormat_RGBA32Float = 0x00000023, - WGPUTextureFormat_RGBA32Uint = 0x00000024, - WGPUTextureFormat_RGBA32Sint = 0x00000025, - WGPUTextureFormat_Stencil8 = 0x00000026, - WGPUTextureFormat_Depth16Unorm = 0x00000027, - WGPUTextureFormat_Depth24Plus = 0x00000028, - WGPUTextureFormat_Depth24PlusStencil8 = 0x00000029, - WGPUTextureFormat_Depth32Float = 0x0000002A, - WGPUTextureFormat_Depth32FloatStencil8 = 0x0000002B, - WGPUTextureFormat_BC1RGBAUnorm = 0x0000002C, - WGPUTextureFormat_BC1RGBAUnormSrgb = 0x0000002D, - WGPUTextureFormat_BC2RGBAUnorm = 0x0000002E, - WGPUTextureFormat_BC2RGBAUnormSrgb = 0x0000002F, - WGPUTextureFormat_BC3RGBAUnorm = 0x00000030, - WGPUTextureFormat_BC3RGBAUnormSrgb = 0x00000031, - WGPUTextureFormat_BC4RUnorm = 0x00000032, - WGPUTextureFormat_BC4RSnorm = 0x00000033, - WGPUTextureFormat_BC5RGUnorm = 0x00000034, - WGPUTextureFormat_BC5RGSnorm = 0x00000035, - WGPUTextureFormat_BC6HRGBUfloat = 0x00000036, - WGPUTextureFormat_BC6HRGBFloat = 0x00000037, - WGPUTextureFormat_BC7RGBAUnorm = 0x00000038, - WGPUTextureFormat_BC7RGBAUnormSrgb = 0x00000039, - WGPUTextureFormat_ETC2RGB8Unorm = 0x0000003A, - WGPUTextureFormat_ETC2RGB8UnormSrgb = 0x0000003B, - WGPUTextureFormat_ETC2RGB8A1Unorm = 0x0000003C, - WGPUTextureFormat_ETC2RGB8A1UnormSrgb = 0x0000003D, - WGPUTextureFormat_ETC2RGBA8Unorm = 0x0000003E, - WGPUTextureFormat_ETC2RGBA8UnormSrgb = 0x0000003F, - WGPUTextureFormat_EACR11Unorm = 0x00000040, - WGPUTextureFormat_EACR11Snorm = 0x00000041, - WGPUTextureFormat_EACRG11Unorm = 0x00000042, - WGPUTextureFormat_EACRG11Snorm = 0x00000043, - WGPUTextureFormat_ASTC4x4Unorm = 0x00000044, - WGPUTextureFormat_ASTC4x4UnormSrgb = 0x00000045, - WGPUTextureFormat_ASTC5x4Unorm = 0x00000046, - WGPUTextureFormat_ASTC5x4UnormSrgb = 0x00000047, - WGPUTextureFormat_ASTC5x5Unorm = 0x00000048, - WGPUTextureFormat_ASTC5x5UnormSrgb = 0x00000049, - WGPUTextureFormat_ASTC6x5Unorm = 0x0000004A, - WGPUTextureFormat_ASTC6x5UnormSrgb = 0x0000004B, - WGPUTextureFormat_ASTC6x6Unorm = 0x0000004C, - WGPUTextureFormat_ASTC6x6UnormSrgb = 0x0000004D, - WGPUTextureFormat_ASTC8x5Unorm = 0x0000004E, - WGPUTextureFormat_ASTC8x5UnormSrgb = 0x0000004F, - WGPUTextureFormat_ASTC8x6Unorm = 0x00000050, - WGPUTextureFormat_ASTC8x6UnormSrgb = 0x00000051, - WGPUTextureFormat_ASTC8x8Unorm = 0x00000052, - WGPUTextureFormat_ASTC8x8UnormSrgb = 0x00000053, - WGPUTextureFormat_ASTC10x5Unorm = 0x00000054, - WGPUTextureFormat_ASTC10x5UnormSrgb = 0x00000055, - WGPUTextureFormat_ASTC10x6Unorm = 0x00000056, - WGPUTextureFormat_ASTC10x6UnormSrgb = 0x00000057, - WGPUTextureFormat_ASTC10x8Unorm = 0x00000058, - WGPUTextureFormat_ASTC10x8UnormSrgb = 0x00000059, - WGPUTextureFormat_ASTC10x10Unorm = 0x0000005A, - WGPUTextureFormat_ASTC10x10UnormSrgb = 0x0000005B, - WGPUTextureFormat_ASTC12x10Unorm = 0x0000005C, - WGPUTextureFormat_ASTC12x10UnormSrgb = 0x0000005D, - WGPUTextureFormat_ASTC12x12Unorm = 0x0000005E, - WGPUTextureFormat_ASTC12x12UnormSrgb = 0x0000005F, + WGPUTextureFormat_R16Unorm = 0x00000005, + WGPUTextureFormat_R16Snorm = 0x00000006, + WGPUTextureFormat_R16Uint = 0x00000007, + WGPUTextureFormat_R16Sint = 0x00000008, + WGPUTextureFormat_R16Float = 0x00000009, + WGPUTextureFormat_RG8Unorm = 0x0000000A, + WGPUTextureFormat_RG8Snorm = 0x0000000B, + WGPUTextureFormat_RG8Uint = 0x0000000C, + WGPUTextureFormat_RG8Sint = 0x0000000D, + WGPUTextureFormat_R32Float = 0x0000000E, + WGPUTextureFormat_R32Uint = 0x0000000F, + WGPUTextureFormat_R32Sint = 0x00000010, + WGPUTextureFormat_RG16Unorm = 0x00000011, + WGPUTextureFormat_RG16Snorm = 0x00000012, + WGPUTextureFormat_RG16Uint = 0x00000013, + WGPUTextureFormat_RG16Sint = 0x00000014, + WGPUTextureFormat_RG16Float = 0x00000015, + WGPUTextureFormat_RGBA8Unorm = 0x00000016, + WGPUTextureFormat_RGBA8UnormSrgb = 0x00000017, + WGPUTextureFormat_RGBA8Snorm = 0x00000018, + WGPUTextureFormat_RGBA8Uint = 0x00000019, + WGPUTextureFormat_RGBA8Sint = 0x0000001A, + WGPUTextureFormat_BGRA8Unorm = 0x0000001B, + WGPUTextureFormat_BGRA8UnormSrgb = 0x0000001C, + WGPUTextureFormat_RGB10A2Uint = 0x0000001D, + WGPUTextureFormat_RGB10A2Unorm = 0x0000001E, + WGPUTextureFormat_RG11B10Ufloat = 0x0000001F, + WGPUTextureFormat_RGB9E5Ufloat = 0x00000020, + WGPUTextureFormat_RG32Float = 0x00000021, + WGPUTextureFormat_RG32Uint = 0x00000022, + WGPUTextureFormat_RG32Sint = 0x00000023, + WGPUTextureFormat_RGBA16Unorm = 0x00000024, + WGPUTextureFormat_RGBA16Snorm = 0x00000025, + WGPUTextureFormat_RGBA16Uint = 0x00000026, + WGPUTextureFormat_RGBA16Sint = 0x00000027, + WGPUTextureFormat_RGBA16Float = 0x00000028, + WGPUTextureFormat_RGBA32Float = 0x00000029, + WGPUTextureFormat_RGBA32Uint = 0x0000002A, + WGPUTextureFormat_RGBA32Sint = 0x0000002B, + WGPUTextureFormat_Stencil8 = 0x0000002C, + WGPUTextureFormat_Depth16Unorm = 0x0000002D, + WGPUTextureFormat_Depth24Plus = 0x0000002E, + WGPUTextureFormat_Depth24PlusStencil8 = 0x0000002F, + WGPUTextureFormat_Depth32Float = 0x00000030, + WGPUTextureFormat_Depth32FloatStencil8 = 0x00000031, + WGPUTextureFormat_BC1RGBAUnorm = 0x00000032, + WGPUTextureFormat_BC1RGBAUnormSrgb = 0x00000033, + WGPUTextureFormat_BC2RGBAUnorm = 0x00000034, + WGPUTextureFormat_BC2RGBAUnormSrgb = 0x00000035, + WGPUTextureFormat_BC3RGBAUnorm = 0x00000036, + WGPUTextureFormat_BC3RGBAUnormSrgb = 0x00000037, + WGPUTextureFormat_BC4RUnorm = 0x00000038, + WGPUTextureFormat_BC4RSnorm = 0x00000039, + WGPUTextureFormat_BC5RGUnorm = 0x0000003A, + WGPUTextureFormat_BC5RGSnorm = 0x0000003B, + WGPUTextureFormat_BC6HRGBUfloat = 0x0000003C, + WGPUTextureFormat_BC6HRGBFloat = 0x0000003D, + WGPUTextureFormat_BC7RGBAUnorm = 0x0000003E, + WGPUTextureFormat_BC7RGBAUnormSrgb = 0x0000003F, + WGPUTextureFormat_ETC2RGB8Unorm = 0x00000040, + WGPUTextureFormat_ETC2RGB8UnormSrgb = 0x00000041, + WGPUTextureFormat_ETC2RGB8A1Unorm = 0x00000042, + WGPUTextureFormat_ETC2RGB8A1UnormSrgb = 0x00000043, + WGPUTextureFormat_ETC2RGBA8Unorm = 0x00000044, + WGPUTextureFormat_ETC2RGBA8UnormSrgb = 0x00000045, + WGPUTextureFormat_EACR11Unorm = 0x00000046, + WGPUTextureFormat_EACR11Snorm = 0x00000047, + WGPUTextureFormat_EACRG11Unorm = 0x00000048, + WGPUTextureFormat_EACRG11Snorm = 0x00000049, + WGPUTextureFormat_ASTC4x4Unorm = 0x0000004A, + WGPUTextureFormat_ASTC4x4UnormSrgb = 0x0000004B, + WGPUTextureFormat_ASTC5x4Unorm = 0x0000004C, + WGPUTextureFormat_ASTC5x4UnormSrgb = 0x0000004D, + WGPUTextureFormat_ASTC5x5Unorm = 0x0000004E, + WGPUTextureFormat_ASTC5x5UnormSrgb = 0x0000004F, + WGPUTextureFormat_ASTC6x5Unorm = 0x00000050, + WGPUTextureFormat_ASTC6x5UnormSrgb = 0x00000051, + WGPUTextureFormat_ASTC6x6Unorm = 0x00000052, + WGPUTextureFormat_ASTC6x6UnormSrgb = 0x00000053, + WGPUTextureFormat_ASTC8x5Unorm = 0x00000054, + WGPUTextureFormat_ASTC8x5UnormSrgb = 0x00000055, + WGPUTextureFormat_ASTC8x6Unorm = 0x00000056, + WGPUTextureFormat_ASTC8x6UnormSrgb = 0x00000057, + WGPUTextureFormat_ASTC8x8Unorm = 0x00000058, + WGPUTextureFormat_ASTC8x8UnormSrgb = 0x00000059, + WGPUTextureFormat_ASTC10x5Unorm = 0x0000005A, + WGPUTextureFormat_ASTC10x5UnormSrgb = 0x0000005B, + WGPUTextureFormat_ASTC10x6Unorm = 0x0000005C, + WGPUTextureFormat_ASTC10x6UnormSrgb = 0x0000005D, + WGPUTextureFormat_ASTC10x8Unorm = 0x0000005E, + WGPUTextureFormat_ASTC10x8UnormSrgb = 0x0000005F, + WGPUTextureFormat_ASTC10x10Unorm = 0x00000060, + WGPUTextureFormat_ASTC10x10UnormSrgb = 0x00000061, + WGPUTextureFormat_ASTC12x10Unorm = 0x00000062, + WGPUTextureFormat_ASTC12x10UnormSrgb = 0x00000063, + WGPUTextureFormat_ASTC12x12Unorm = 0x00000064, + WGPUTextureFormat_ASTC12x12UnormSrgb = 0x00000065, WGPUTextureFormat_Force32 = 0x7FFFFFFF } WGPUTextureFormat WGPU_ENUM_ATTRIBUTE; @@ -831,8 +845,6 @@ typedef enum WGPUWGSLLanguageFeatureName { WGPUWGSLLanguageFeatureName_Packed4x8IntegerDotProduct = 0x00000002, WGPUWGSLLanguageFeatureName_UnrestrictedPointerParameters = 0x00000003, WGPUWGSLLanguageFeatureName_PointerCompositeAccess = 0x00000004, - WGPUWGSLLanguageFeatureName_SizedBindingArray = 0x00000005, - WGPUWGSLLanguageFeatureName_TexelBuffers = 0x00000006, WGPUWGSLLanguageFeatureName_Force32 = 0x7FFFFFFF } WGPUWGSLLanguageFeatureName WGPU_ENUM_ATTRIBUTE; @@ -1270,15 +1282,13 @@ typedef struct WGPUFuture { /*.id=*/0 _wgpu_COMMA \ }) -typedef struct WGPUInstanceCapabilities { +typedef struct WGPUInstanceLimits { WGPUChainedStruct * nextInChain; - WGPUBool timedWaitAnyEnable; size_t timedWaitAnyMaxCount; -} WGPUInstanceCapabilities WGPU_STRUCTURE_ATTRIBUTE; +} WGPUInstanceLimits WGPU_STRUCTURE_ATTRIBUTE; -#define WGPU_INSTANCE_CAPABILITIES_INIT _wgpu_MAKE_INIT_STRUCT(WGPUInstanceCapabilities, { \ +#define WGPU_INSTANCE_LIMITS_INIT _wgpu_MAKE_INIT_STRUCT(WGPUInstanceLimits, { \ /*.nextInChain=*/NULL _wgpu_COMMA \ - /*.timedWaitAnyEnable=*/WGPU_FALSE _wgpu_COMMA \ /*.timedWaitAnyMaxCount=*/0 _wgpu_COMMA \ }) @@ -1334,7 +1344,7 @@ typedef struct WGPUPipelineLayoutDescriptor { WGPUChainedStruct * nextInChain; WGPUStringView label; size_t bindGroupLayoutCount; - WGPU_NULLABLE WGPUBindGroupLayout const * bindGroupLayouts; + WGPUBindGroupLayout const * bindGroupLayouts; uint32_t immediateSize; } WGPUPipelineLayoutDescriptor WGPU_STRUCTURE_ATTRIBUTE; @@ -1582,6 +1592,16 @@ typedef struct WGPUSupportedFeatures { /*.features=*/NULL _wgpu_COMMA \ }) +typedef struct WGPUSupportedInstanceFeatures { + size_t featureCount; + WGPUInstanceFeatureName const * features; +} WGPUSupportedInstanceFeatures WGPU_STRUCTURE_ATTRIBUTE; + +#define WGPU_SUPPORTED_INSTANCE_FEATURES_INIT _wgpu_MAKE_INIT_STRUCT(WGPUSupportedInstanceFeatures, { \ + /*.featureCount=*/0 _wgpu_COMMA \ + /*.features=*/NULL _wgpu_COMMA \ +}) + typedef struct WGPUSupportedWGSLLanguageFeatures { size_t featureCount; WGPUWGSLLanguageFeatureName const * features; @@ -1708,30 +1728,18 @@ typedef struct WGPUTextureBindingViewDimensionDescriptor { /*.textureBindingViewDimension=*/WGPUTextureViewDimension_Undefined _wgpu_COMMA \ }) -typedef struct WGPUTextureViewDescriptor { - WGPUChainedStruct * nextInChain; - WGPUStringView label; - WGPUTextureFormat format; - WGPUTextureViewDimension dimension; - uint32_t baseMipLevel; - uint32_t mipLevelCount; - uint32_t baseArrayLayer; - uint32_t arrayLayerCount; - WGPUTextureAspect aspect; - WGPUTextureUsage usage; -} WGPUTextureViewDescriptor WGPU_STRUCTURE_ATTRIBUTE; +typedef struct WGPUTextureComponentSwizzle { + WGPUComponentSwizzle r; + WGPUComponentSwizzle g; + WGPUComponentSwizzle b; + WGPUComponentSwizzle a; +} WGPUTextureComponentSwizzle WGPU_STRUCTURE_ATTRIBUTE; -#define WGPU_TEXTURE_VIEW_DESCRIPTOR_INIT _wgpu_MAKE_INIT_STRUCT(WGPUTextureViewDescriptor, { \ - /*.nextInChain=*/NULL _wgpu_COMMA \ - /*.label=*/WGPU_STRING_VIEW_INIT _wgpu_COMMA \ - /*.format=*/WGPUTextureFormat_Undefined _wgpu_COMMA \ - /*.dimension=*/WGPUTextureViewDimension_Undefined _wgpu_COMMA \ - /*.baseMipLevel=*/0 _wgpu_COMMA \ - /*.mipLevelCount=*/WGPU_MIP_LEVEL_COUNT_UNDEFINED _wgpu_COMMA \ - /*.baseArrayLayer=*/0 _wgpu_COMMA \ - /*.arrayLayerCount=*/WGPU_ARRAY_LAYER_COUNT_UNDEFINED _wgpu_COMMA \ - /*.aspect=*/WGPUTextureAspect_Undefined _wgpu_COMMA \ - /*.usage=*/WGPUTextureUsage_None _wgpu_COMMA \ +#define WGPU_TEXTURE_COMPONENT_SWIZZLE_INIT _wgpu_MAKE_INIT_STRUCT(WGPUTextureComponentSwizzle, { \ + /*.r=*/WGPUComponentSwizzle_Undefined _wgpu_COMMA \ + /*.g=*/WGPUComponentSwizzle_Undefined _wgpu_COMMA \ + /*.b=*/WGPUComponentSwizzle_Undefined _wgpu_COMMA \ + /*.a=*/WGPUComponentSwizzle_Undefined _wgpu_COMMA \ }) typedef struct WGPUVertexAttribute { @@ -1884,12 +1892,16 @@ typedef struct WGPUFutureWaitInfo { typedef struct WGPUInstanceDescriptor { WGPUChainedStruct * nextInChain; - WGPUInstanceCapabilities capabilities; + size_t requiredFeatureCount; + WGPUInstanceFeatureName const * requiredFeatures; + WGPU_NULLABLE WGPUInstanceLimits const * requiredLimits; } WGPUInstanceDescriptor WGPU_STRUCTURE_ATTRIBUTE; #define WGPU_INSTANCE_DESCRIPTOR_INIT _wgpu_MAKE_INIT_STRUCT(WGPUInstanceDescriptor, { \ /*.nextInChain=*/NULL _wgpu_COMMA \ - /*.capabilities=*/WGPU_INSTANCE_CAPABILITIES_INIT _wgpu_COMMA \ + /*.requiredFeatureCount=*/0 _wgpu_COMMA \ + /*.requiredFeatures=*/NULL _wgpu_COMMA \ + /*.requiredLimits=*/NULL _wgpu_COMMA \ }) typedef struct WGPULimits { @@ -2046,6 +2058,20 @@ typedef struct WGPUTexelCopyTextureInfo { /*.aspect=*/WGPUTextureAspect_Undefined _wgpu_COMMA \ }) +// Can be chained in WGPUTextureViewDescriptor +typedef struct WGPUTextureComponentSwizzleDescriptor { + WGPUChainedStruct chain; + WGPUTextureComponentSwizzle swizzle; +} WGPUTextureComponentSwizzleDescriptor WGPU_STRUCTURE_ATTRIBUTE; + +#define WGPU_TEXTURE_COMPONENT_SWIZZLE_DESCRIPTOR_INIT _wgpu_MAKE_INIT_STRUCT(WGPUTextureComponentSwizzleDescriptor, { \ + /*.chain=*/_wgpu_MAKE_INIT_STRUCT(WGPUChainedStruct, { \ + /*.next=*/NULL _wgpu_COMMA \ + /*.sType=*/WGPUSType_TextureComponentSwizzleDescriptor _wgpu_COMMA \ + }) _wgpu_COMMA \ + /*.swizzle=*/WGPU_TEXTURE_COMPONENT_SWIZZLE_INIT _wgpu_COMMA \ +}) + typedef struct WGPUTextureDescriptor { WGPUChainedStruct * nextInChain; WGPUStringView label; @@ -2184,6 +2210,32 @@ typedef struct WGPURenderPassDescriptor { /*.timestampWrites=*/NULL _wgpu_COMMA \ }) +typedef struct WGPUTextureViewDescriptor { + WGPUChainedStruct * nextInChain; + WGPUStringView label; + WGPUTextureFormat format; + WGPUTextureViewDimension dimension; + uint32_t baseMipLevel; + uint32_t mipLevelCount; + uint32_t baseArrayLayer; + uint32_t arrayLayerCount; + WGPUTextureAspect aspect; + WGPUTextureUsage usage; +} WGPUTextureViewDescriptor WGPU_STRUCTURE_ATTRIBUTE; + +#define WGPU_TEXTURE_VIEW_DESCRIPTOR_INIT _wgpu_MAKE_INIT_STRUCT(WGPUTextureViewDescriptor, { \ + /*.nextInChain=*/NULL _wgpu_COMMA \ + /*.label=*/WGPU_STRING_VIEW_INIT _wgpu_COMMA \ + /*.format=*/WGPUTextureFormat_Undefined _wgpu_COMMA \ + /*.dimension=*/WGPUTextureViewDimension_Undefined _wgpu_COMMA \ + /*.baseMipLevel=*/0 _wgpu_COMMA \ + /*.mipLevelCount=*/WGPU_MIP_LEVEL_COUNT_UNDEFINED _wgpu_COMMA \ + /*.baseArrayLayer=*/0 _wgpu_COMMA \ + /*.arrayLayerCount=*/WGPU_ARRAY_LAYER_COUNT_UNDEFINED _wgpu_COMMA \ + /*.aspect=*/WGPUTextureAspect_Undefined _wgpu_COMMA \ + /*.usage=*/WGPUTextureUsage_None _wgpu_COMMA \ +}) + typedef struct WGPUVertexState { WGPUChainedStruct * nextInChain; WGPUShaderModule module; @@ -2246,34 +2298,22 @@ typedef struct WGPURenderPipelineDescriptor { /*.fragment=*/NULL _wgpu_COMMA \ }) -// WGPURenderPassDescriptorMaxDrawCount is deprecated. -// Use WGPURenderPassMaxDrawCount instead. -typedef WGPURenderPassMaxDrawCount WGPURenderPassDescriptorMaxDrawCount; - -// WGPUShaderModuleSPIRVDescriptor is deprecated. -// Use WGPUShaderSourceSPIRV instead. -typedef WGPUShaderSourceSPIRV WGPUShaderModuleSPIRVDescriptor; - -// WGPUShaderModuleWGSLDescriptor is deprecated. -// Use WGPUShaderSourceWGSL instead. -typedef WGPUShaderSourceWGSL WGPUShaderModuleWGSLDescriptor; - -#if defined(__cplusplus) && !defined(USE_WGPU_WAGYU_NAMESPACE) && !defined(__cppcheck) +#ifdef __cplusplus extern "C" { #endif #if !defined(WGPU_SKIP_PROCS) - // TODO(374150686): Remove these Emscripten specific declarations from the // header once they are fully deprecated. -#ifdef __EMSCRIPTEN__ WGPU_EXPORT WGPUDevice emscripten_webgpu_get_device(void); -#endif - +// Global procs typedef WGPUInstance (*WGPUProcCreateInstance)(WGPU_NULLABLE WGPUInstanceDescriptor const * descriptor) WGPU_FUNCTION_ATTRIBUTE; -typedef WGPUStatus (*WGPUProcGetInstanceCapabilities)(WGPUInstanceCapabilities * capabilities) WGPU_FUNCTION_ATTRIBUTE; +typedef void (*WGPUProcGetInstanceFeatures)(WGPUSupportedInstanceFeatures * features) WGPU_FUNCTION_ATTRIBUTE; +typedef WGPUStatus (*WGPUProcGetInstanceLimits)(WGPUInstanceLimits * limits) WGPU_FUNCTION_ATTRIBUTE; +typedef WGPUBool (*WGPUProcHasInstanceFeature)(WGPUInstanceFeatureName feature) WGPU_FUNCTION_ATTRIBUTE; typedef WGPUProc (*WGPUProcGetProcAddress)(WGPUStringView procName) WGPU_FUNCTION_ATTRIBUTE; + // Procs of Adapter typedef void (*WGPUProcAdapterGetFeatures)(WGPUAdapter adapter, WGPUSupportedFeatures * features) WGPU_FUNCTION_ATTRIBUTE; typedef WGPUStatus (*WGPUProcAdapterGetInfo)(WGPUAdapter adapter, WGPUAdapterInfo * info) WGPU_FUNCTION_ATTRIBUTE; @@ -2357,7 +2397,7 @@ typedef void (*WGPUProcComputePipelineRelease)(WGPUComputePipeline computePipeli // Procs of Device typedef WGPUBindGroup (*WGPUProcDeviceCreateBindGroup)(WGPUDevice device, WGPUBindGroupDescriptor const * descriptor) WGPU_FUNCTION_ATTRIBUTE; typedef WGPUBindGroupLayout (*WGPUProcDeviceCreateBindGroupLayout)(WGPUDevice device, WGPUBindGroupLayoutDescriptor const * descriptor) WGPU_FUNCTION_ATTRIBUTE; -typedef WGPUBuffer (*WGPUProcDeviceCreateBuffer)(WGPUDevice device, WGPUBufferDescriptor const * descriptor) WGPU_FUNCTION_ATTRIBUTE; +typedef WGPU_NULLABLE WGPUBuffer (*WGPUProcDeviceCreateBuffer)(WGPUDevice device, WGPUBufferDescriptor const * descriptor) WGPU_FUNCTION_ATTRIBUTE; typedef WGPUCommandEncoder (*WGPUProcDeviceCreateCommandEncoder)(WGPUDevice device, WGPU_NULLABLE WGPUCommandEncoderDescriptor const * descriptor) WGPU_FUNCTION_ATTRIBUTE; typedef WGPUComputePipeline (*WGPUProcDeviceCreateComputePipeline)(WGPUDevice device, WGPUComputePipelineDescriptor const * descriptor) WGPU_FUNCTION_ATTRIBUTE; typedef WGPUFuture (*WGPUProcDeviceCreateComputePipelineAsync)(WGPUDevice device, WGPUComputePipelineDescriptor const * descriptor, WGPUCreateComputePipelineAsyncCallbackInfo callbackInfo) WGPU_FUNCTION_ATTRIBUTE; @@ -2384,11 +2424,11 @@ typedef void (*WGPUProcDeviceRelease)(WGPUDevice device) WGPU_FUNCTION_ATTRIBUTE // Procs of Instance typedef WGPUSurface (*WGPUProcInstanceCreateSurface)(WGPUInstance instance, WGPUSurfaceDescriptor const * descriptor) WGPU_FUNCTION_ATTRIBUTE; -typedef WGPUStatus (*WGPUProcInstanceGetWGSLLanguageFeatures)(WGPUInstance instance, WGPUSupportedWGSLLanguageFeatures * features) WGPU_FUNCTION_ATTRIBUTE; +typedef void (*WGPUProcInstanceGetWGSLLanguageFeatures)(WGPUInstance instance, WGPUSupportedWGSLLanguageFeatures * features) WGPU_FUNCTION_ATTRIBUTE; typedef WGPUBool (*WGPUProcInstanceHasWGSLLanguageFeature)(WGPUInstance instance, WGPUWGSLLanguageFeatureName feature) WGPU_FUNCTION_ATTRIBUTE; typedef void (*WGPUProcInstanceProcessEvents)(WGPUInstance instance) WGPU_FUNCTION_ATTRIBUTE; typedef WGPUFuture (*WGPUProcInstanceRequestAdapter)(WGPUInstance instance, WGPU_NULLABLE WGPURequestAdapterOptions const * options, WGPURequestAdapterCallbackInfo callbackInfo) WGPU_FUNCTION_ATTRIBUTE; -typedef WGPUWaitStatus (*WGPUProcInstanceWaitAny)(WGPUInstance instance, size_t futureCount, WGPUFutureWaitInfo * futures, uint64_t timeoutNS) WGPU_FUNCTION_ATTRIBUTE; +typedef WGPUWaitStatus (*WGPUProcInstanceWaitAny)(WGPUInstance instance, size_t futureCount, WGPU_NULLABLE WGPUFutureWaitInfo * futures, uint64_t timeoutNS) WGPU_FUNCTION_ATTRIBUTE; typedef void (*WGPUProcInstanceAddRef)(WGPUInstance instance) WGPU_FUNCTION_ATTRIBUTE; typedef void (*WGPUProcInstanceRelease)(WGPUInstance instance) WGPU_FUNCTION_ATTRIBUTE; @@ -2480,17 +2520,20 @@ typedef void (*WGPUProcShaderModuleSetLabel)(WGPUShaderModule shaderModule, WGPU typedef void (*WGPUProcShaderModuleAddRef)(WGPUShaderModule shaderModule) WGPU_FUNCTION_ATTRIBUTE; typedef void (*WGPUProcShaderModuleRelease)(WGPUShaderModule shaderModule) WGPU_FUNCTION_ATTRIBUTE; -// Procs of SupportedWGSLLanguageFeatures -typedef void (*WGPUProcSupportedWGSLLanguageFeaturesFreeMembers)(WGPUSupportedWGSLLanguageFeatures supportedWGSLLanguageFeatures) WGPU_FUNCTION_ATTRIBUTE; - // Procs of SupportedFeatures typedef void (*WGPUProcSupportedFeaturesFreeMembers)(WGPUSupportedFeatures supportedFeatures) WGPU_FUNCTION_ATTRIBUTE; +// Procs of SupportedInstanceFeatures +typedef void (*WGPUProcSupportedInstanceFeaturesFreeMembers)(WGPUSupportedInstanceFeatures supportedInstanceFeatures) WGPU_FUNCTION_ATTRIBUTE; + +// Procs of SupportedWGSLLanguageFeatures +typedef void (*WGPUProcSupportedWGSLLanguageFeaturesFreeMembers)(WGPUSupportedWGSLLanguageFeatures supportedWGSLLanguageFeatures) WGPU_FUNCTION_ATTRIBUTE; + // Procs of Surface typedef void (*WGPUProcSurfaceConfigure)(WGPUSurface surface, WGPUSurfaceConfiguration const * config) WGPU_FUNCTION_ATTRIBUTE; typedef WGPUStatus (*WGPUProcSurfaceGetCapabilities)(WGPUSurface surface, WGPUAdapter adapter, WGPUSurfaceCapabilities * capabilities) WGPU_FUNCTION_ATTRIBUTE; typedef void (*WGPUProcSurfaceGetCurrentTexture)(WGPUSurface surface, WGPUSurfaceTexture * surfaceTexture) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcSurfacePresent)(WGPUSurface surface) WGPU_FUNCTION_ATTRIBUTE; +typedef WGPUStatus (*WGPUProcSurfacePresent)(WGPUSurface surface) WGPU_FUNCTION_ATTRIBUTE; typedef void (*WGPUProcSurfaceSetLabel)(WGPUSurface surface, WGPUStringView label) WGPU_FUNCTION_ATTRIBUTE; typedef void (*WGPUProcSurfaceUnconfigure)(WGPUSurface surface) WGPU_FUNCTION_ATTRIBUTE; typedef void (*WGPUProcSurfaceAddRef)(WGPUSurface surface) WGPU_FUNCTION_ATTRIBUTE; @@ -2519,13 +2562,13 @@ typedef void (*WGPUProcTextureViewSetLabel)(WGPUTextureView textureView, WGPUStr typedef void (*WGPUProcTextureViewAddRef)(WGPUTextureView textureView) WGPU_FUNCTION_ATTRIBUTE; typedef void (*WGPUProcTextureViewRelease)(WGPUTextureView textureView) WGPU_FUNCTION_ATTRIBUTE; - #endif // !defined(WGPU_SKIP_PROCS) #if !defined(WGPU_SKIP_DECLARATIONS) - WGPU_EXPORT WGPUInstance wgpuCreateInstance(WGPU_NULLABLE WGPUInstanceDescriptor const * descriptor) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT WGPUStatus wgpuGetInstanceCapabilities(WGPUInstanceCapabilities * capabilities) WGPU_FUNCTION_ATTRIBUTE; +WGPU_EXPORT void wgpuGetInstanceFeatures(WGPUSupportedInstanceFeatures * features) WGPU_FUNCTION_ATTRIBUTE; +WGPU_EXPORT WGPUStatus wgpuGetInstanceLimits(WGPUInstanceLimits * limits) WGPU_FUNCTION_ATTRIBUTE; +WGPU_EXPORT WGPUBool wgpuHasInstanceFeature(WGPUInstanceFeatureName feature) WGPU_FUNCTION_ATTRIBUTE; WGPU_EXPORT WGPUProc wgpuGetProcAddress(WGPUStringView procName) WGPU_FUNCTION_ATTRIBUTE; // Methods of Adapter @@ -2611,7 +2654,7 @@ WGPU_EXPORT void wgpuComputePipelineRelease(WGPUComputePipeline computePipeline) // Methods of Device WGPU_EXPORT WGPUBindGroup wgpuDeviceCreateBindGroup(WGPUDevice device, WGPUBindGroupDescriptor const * descriptor) WGPU_FUNCTION_ATTRIBUTE; WGPU_EXPORT WGPUBindGroupLayout wgpuDeviceCreateBindGroupLayout(WGPUDevice device, WGPUBindGroupLayoutDescriptor const * descriptor) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT WGPUBuffer wgpuDeviceCreateBuffer(WGPUDevice device, WGPUBufferDescriptor const * descriptor) WGPU_FUNCTION_ATTRIBUTE; +WGPU_EXPORT WGPU_NULLABLE WGPUBuffer wgpuDeviceCreateBuffer(WGPUDevice device, WGPUBufferDescriptor const * descriptor) WGPU_FUNCTION_ATTRIBUTE; WGPU_EXPORT WGPUCommandEncoder wgpuDeviceCreateCommandEncoder(WGPUDevice device, WGPU_NULLABLE WGPUCommandEncoderDescriptor const * descriptor) WGPU_FUNCTION_ATTRIBUTE; WGPU_EXPORT WGPUComputePipeline wgpuDeviceCreateComputePipeline(WGPUDevice device, WGPUComputePipelineDescriptor const * descriptor) WGPU_FUNCTION_ATTRIBUTE; WGPU_EXPORT WGPUFuture wgpuDeviceCreateComputePipelineAsync(WGPUDevice device, WGPUComputePipelineDescriptor const * descriptor, WGPUCreateComputePipelineAsyncCallbackInfo callbackInfo) WGPU_FUNCTION_ATTRIBUTE; @@ -2638,11 +2681,11 @@ WGPU_EXPORT void wgpuDeviceRelease(WGPUDevice device) WGPU_FUNCTION_ATTRIBUTE; // Methods of Instance WGPU_EXPORT WGPUSurface wgpuInstanceCreateSurface(WGPUInstance instance, WGPUSurfaceDescriptor const * descriptor) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT WGPUStatus wgpuInstanceGetWGSLLanguageFeatures(WGPUInstance instance, WGPUSupportedWGSLLanguageFeatures * features) WGPU_FUNCTION_ATTRIBUTE; +WGPU_EXPORT void wgpuInstanceGetWGSLLanguageFeatures(WGPUInstance instance, WGPUSupportedWGSLLanguageFeatures * features) WGPU_FUNCTION_ATTRIBUTE; WGPU_EXPORT WGPUBool wgpuInstanceHasWGSLLanguageFeature(WGPUInstance instance, WGPUWGSLLanguageFeatureName feature) WGPU_FUNCTION_ATTRIBUTE; WGPU_EXPORT void wgpuInstanceProcessEvents(WGPUInstance instance) WGPU_FUNCTION_ATTRIBUTE; WGPU_EXPORT WGPUFuture wgpuInstanceRequestAdapter(WGPUInstance instance, WGPU_NULLABLE WGPURequestAdapterOptions const * options, WGPURequestAdapterCallbackInfo callbackInfo) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT WGPUWaitStatus wgpuInstanceWaitAny(WGPUInstance instance, size_t futureCount, WGPUFutureWaitInfo * futures, uint64_t timeoutNS) WGPU_FUNCTION_ATTRIBUTE; +WGPU_EXPORT WGPUWaitStatus wgpuInstanceWaitAny(WGPUInstance instance, size_t futureCount, WGPU_NULLABLE WGPUFutureWaitInfo * futures, uint64_t timeoutNS) WGPU_FUNCTION_ATTRIBUTE; WGPU_EXPORT void wgpuInstanceAddRef(WGPUInstance instance) WGPU_FUNCTION_ATTRIBUTE; WGPU_EXPORT void wgpuInstanceRelease(WGPUInstance instance) WGPU_FUNCTION_ATTRIBUTE; @@ -2734,17 +2777,20 @@ WGPU_EXPORT void wgpuShaderModuleSetLabel(WGPUShaderModule shaderModule, WGPUStr WGPU_EXPORT void wgpuShaderModuleAddRef(WGPUShaderModule shaderModule) WGPU_FUNCTION_ATTRIBUTE; WGPU_EXPORT void wgpuShaderModuleRelease(WGPUShaderModule shaderModule) WGPU_FUNCTION_ATTRIBUTE; -// Methods of SupportedWGSLLanguageFeatures -WGPU_EXPORT void wgpuSupportedWGSLLanguageFeaturesFreeMembers(WGPUSupportedWGSLLanguageFeatures supportedWGSLLanguageFeatures) WGPU_FUNCTION_ATTRIBUTE; - // Methods of SupportedFeatures WGPU_EXPORT void wgpuSupportedFeaturesFreeMembers(WGPUSupportedFeatures supportedFeatures) WGPU_FUNCTION_ATTRIBUTE; +// Methods of SupportedInstanceFeatures +WGPU_EXPORT void wgpuSupportedInstanceFeaturesFreeMembers(WGPUSupportedInstanceFeatures supportedInstanceFeatures) WGPU_FUNCTION_ATTRIBUTE; + +// Methods of SupportedWGSLLanguageFeatures +WGPU_EXPORT void wgpuSupportedWGSLLanguageFeaturesFreeMembers(WGPUSupportedWGSLLanguageFeatures supportedWGSLLanguageFeatures) WGPU_FUNCTION_ATTRIBUTE; + // Methods of Surface WGPU_EXPORT void wgpuSurfaceConfigure(WGPUSurface surface, WGPUSurfaceConfiguration const * config) WGPU_FUNCTION_ATTRIBUTE; WGPU_EXPORT WGPUStatus wgpuSurfaceGetCapabilities(WGPUSurface surface, WGPUAdapter adapter, WGPUSurfaceCapabilities * capabilities) WGPU_FUNCTION_ATTRIBUTE; WGPU_EXPORT void wgpuSurfaceGetCurrentTexture(WGPUSurface surface, WGPUSurfaceTexture * surfaceTexture) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuSurfacePresent(WGPUSurface surface) WGPU_FUNCTION_ATTRIBUTE; +WGPU_EXPORT WGPUStatus wgpuSurfacePresent(WGPUSurface surface) WGPU_FUNCTION_ATTRIBUTE; WGPU_EXPORT void wgpuSurfaceSetLabel(WGPUSurface surface, WGPUStringView label) WGPU_FUNCTION_ATTRIBUTE; WGPU_EXPORT void wgpuSurfaceUnconfigure(WGPUSurface surface) WGPU_FUNCTION_ATTRIBUTE; WGPU_EXPORT void wgpuSurfaceAddRef(WGPUSurface surface) WGPU_FUNCTION_ATTRIBUTE; @@ -2773,15 +2819,10 @@ WGPU_EXPORT void wgpuTextureViewSetLabel(WGPUTextureView textureView, WGPUString WGPU_EXPORT void wgpuTextureViewAddRef(WGPUTextureView textureView) WGPU_FUNCTION_ATTRIBUTE; WGPU_EXPORT void wgpuTextureViewRelease(WGPUTextureView textureView) WGPU_FUNCTION_ATTRIBUTE; - #endif // !defined(WGPU_SKIP_DECLARATIONS) -#if defined(__cplusplus) && !defined(USE_WGPU_WAGYU_NAMESPACE) && !defined(__cppcheck) +#ifdef __cplusplus } // extern "C" #endif -#if defined(USE_WGPU_WAGYU_NAMESPACE) || defined(__cppcheck) -} // namespace wagyu2 -#endif - #endif // WEBGPU_H_ diff --git a/defold-rive/include/rive/renderer/webgpu/wagyu-port/new/include/webgpu/webgpu_cpp.h b/defold-rive/include/rive/renderer/webgpu/wagyu-port/include/webgpu/webgpu_cpp.h similarity index 94% rename from defold-rive/include/rive/renderer/webgpu/wagyu-port/new/include/webgpu/webgpu_cpp.h rename to defold-rive/include/rive/renderer/webgpu/wagyu-port/include/webgpu/webgpu_cpp.h index 1e06db9e..cbd830a8 100644 --- a/defold-rive/include/rive/renderer/webgpu/wagyu-port/new/include/webgpu/webgpu_cpp.h +++ b/defold-rive/include/rive/renderer/webgpu/wagyu-port/include/webgpu/webgpu_cpp.h @@ -180,6 +180,18 @@ enum class CompilationMessageType : uint32_t { static_assert(sizeof(CompilationMessageType) == sizeof(WGPUCompilationMessageType), "sizeof mismatch for CompilationMessageType"); static_assert(alignof(CompilationMessageType) == alignof(WGPUCompilationMessageType), "alignof mismatch for CompilationMessageType"); +enum class ComponentSwizzle : uint32_t { + Undefined = WGPUComponentSwizzle_Undefined, + Zero = WGPUComponentSwizzle_Zero, + One = WGPUComponentSwizzle_One, + R = WGPUComponentSwizzle_R, + G = WGPUComponentSwizzle_G, + B = WGPUComponentSwizzle_B, + A = WGPUComponentSwizzle_A, +}; +static_assert(sizeof(ComponentSwizzle) == sizeof(WGPUComponentSwizzle), "sizeof mismatch for ComponentSwizzle"); +static_assert(alignof(ComponentSwizzle) == alignof(WGPUComponentSwizzle), "alignof mismatch for ComponentSwizzle"); + enum class CompositeAlphaMode : uint32_t { Auto = WGPUCompositeAlphaMode_Auto, Opaque = WGPUCompositeAlphaMode_Opaque, @@ -244,14 +256,15 @@ static_assert(sizeof(FeatureLevel) == sizeof(WGPUFeatureLevel), "sizeof mismatch static_assert(alignof(FeatureLevel) == alignof(WGPUFeatureLevel), "alignof mismatch for FeatureLevel"); enum class FeatureName : uint32_t { + CoreFeaturesAndLimits = WGPUFeatureName_CoreFeaturesAndLimits, DepthClipControl = WGPUFeatureName_DepthClipControl, Depth32FloatStencil8 = WGPUFeatureName_Depth32FloatStencil8, - TimestampQuery = WGPUFeatureName_TimestampQuery, TextureCompressionBC = WGPUFeatureName_TextureCompressionBC, TextureCompressionBCSliced3D = WGPUFeatureName_TextureCompressionBCSliced3D, TextureCompressionETC2 = WGPUFeatureName_TextureCompressionETC2, TextureCompressionASTC = WGPUFeatureName_TextureCompressionASTC, TextureCompressionASTCSliced3D = WGPUFeatureName_TextureCompressionASTCSliced3D, + TimestampQuery = WGPUFeatureName_TimestampQuery, IndirectFirstInstance = WGPUFeatureName_IndirectFirstInstance, ShaderF16 = WGPUFeatureName_ShaderF16, RG11B10UfloatRenderable = WGPUFeatureName_RG11B10UfloatRenderable, @@ -261,7 +274,10 @@ enum class FeatureName : uint32_t { ClipDistances = WGPUFeatureName_ClipDistances, DualSourceBlending = WGPUFeatureName_DualSourceBlending, Subgroups = WGPUFeatureName_Subgroups, - CoreFeaturesAndLimits = WGPUFeatureName_CoreFeaturesAndLimits, + TextureFormatsTier1 = WGPUFeatureName_TextureFormatsTier1, + TextureFormatsTier2 = WGPUFeatureName_TextureFormatsTier2, + PrimitiveIndex = WGPUFeatureName_PrimitiveIndex, + TextureComponentSwizzle = WGPUFeatureName_TextureComponentSwizzle, Unorm16TextureFormats = WGPUFeatureName_Unorm16TextureFormats, Snorm16TextureFormats = WGPUFeatureName_Snorm16TextureFormats, MultiDrawIndirect = WGPUFeatureName_MultiDrawIndirect, @@ -293,6 +309,14 @@ enum class IndexFormat : uint32_t { static_assert(sizeof(IndexFormat) == sizeof(WGPUIndexFormat), "sizeof mismatch for IndexFormat"); static_assert(alignof(IndexFormat) == alignof(WGPUIndexFormat), "alignof mismatch for IndexFormat"); +enum class InstanceFeatureName : uint32_t { + TimedWaitAny = WGPUInstanceFeatureName_TimedWaitAny, + ShaderSourceSPIRV = WGPUInstanceFeatureName_ShaderSourceSPIRV, + MultipleDevicesPerAdapter = WGPUInstanceFeatureName_MultipleDevicesPerAdapter, +}; +static_assert(sizeof(InstanceFeatureName) == sizeof(WGPUInstanceFeatureName), "sizeof mismatch for InstanceFeatureName"); +static_assert(alignof(InstanceFeatureName) == alignof(WGPUInstanceFeatureName), "alignof mismatch for InstanceFeatureName"); + enum class LoadOp : uint32_t { Undefined = WGPULoadOp_Undefined, Load = WGPULoadOp_Load, @@ -455,6 +479,7 @@ enum class SType : uint32_t { SurfaceSourceXCBWindow = WGPUSType_SurfaceSourceXCBWindow, SurfaceColorManagement = WGPUSType_SurfaceColorManagement, RequestAdapterWebXROptions = WGPUSType_RequestAdapterWebXROptions, + TextureComponentSwizzleDescriptor = WGPUSType_TextureComponentSwizzleDescriptor, CompatibilityModeLimits = WGPUSType_CompatibilityModeLimits, TextureBindingViewDimensionDescriptor = WGPUSType_TextureBindingViewDimensionDescriptor, EmscriptenSurfaceSourceCanvasHTMLSelector = WGPUSType_EmscriptenSurfaceSourceCanvasHTMLSelector, @@ -463,15 +488,6 @@ enum class SType : uint32_t { static_assert(sizeof(SType) == sizeof(WGPUSType), "sizeof mismatch for SType"); static_assert(alignof(SType) == alignof(WGPUSType), "alignof mismatch for SType"); -enum class SubgroupMatrixComponentType : uint32_t { - F32 = WGPUSubgroupMatrixComponentType_F32, - F16 = WGPUSubgroupMatrixComponentType_F16, - U32 = WGPUSubgroupMatrixComponentType_U32, - I32 = WGPUSubgroupMatrixComponentType_I32, -}; -static_assert(sizeof(SubgroupMatrixComponentType) == sizeof(WGPUSubgroupMatrixComponentType), "sizeof mismatch for SubgroupMatrixComponentType"); -static_assert(alignof(SubgroupMatrixComponentType) == alignof(WGPUSubgroupMatrixComponentType), "alignof mismatch for SubgroupMatrixComponentType"); - enum class SurfaceGetCurrentTextureStatus : uint32_t { SuccessOptimal = WGPUSurfaceGetCurrentTextureStatus_SuccessOptimal, SuccessSuboptimal = WGPUSurfaceGetCurrentTextureStatus_SuccessSuboptimal, @@ -507,6 +523,8 @@ enum class TextureFormat : uint32_t { R8Snorm = WGPUTextureFormat_R8Snorm, R8Uint = WGPUTextureFormat_R8Uint, R8Sint = WGPUTextureFormat_R8Sint, + R16Unorm = WGPUTextureFormat_R16Unorm, + R16Snorm = WGPUTextureFormat_R16Snorm, R16Uint = WGPUTextureFormat_R16Uint, R16Sint = WGPUTextureFormat_R16Sint, R16Float = WGPUTextureFormat_R16Float, @@ -517,6 +535,8 @@ enum class TextureFormat : uint32_t { R32Float = WGPUTextureFormat_R32Float, R32Uint = WGPUTextureFormat_R32Uint, R32Sint = WGPUTextureFormat_R32Sint, + RG16Unorm = WGPUTextureFormat_RG16Unorm, + RG16Snorm = WGPUTextureFormat_RG16Snorm, RG16Uint = WGPUTextureFormat_RG16Uint, RG16Sint = WGPUTextureFormat_RG16Sint, RG16Float = WGPUTextureFormat_RG16Float, @@ -534,6 +554,8 @@ enum class TextureFormat : uint32_t { RG32Float = WGPUTextureFormat_RG32Float, RG32Uint = WGPUTextureFormat_RG32Uint, RG32Sint = WGPUTextureFormat_RG32Sint, + RGBA16Unorm = WGPUTextureFormat_RGBA16Unorm, + RGBA16Snorm = WGPUTextureFormat_RGBA16Snorm, RGBA16Uint = WGPUTextureFormat_RGBA16Uint, RGBA16Sint = WGPUTextureFormat_RGBA16Sint, RGBA16Float = WGPUTextureFormat_RGBA16Float, @@ -700,8 +722,6 @@ enum class WGSLLanguageFeatureName : uint32_t { Packed4x8IntegerDotProduct = WGPUWGSLLanguageFeatureName_Packed4x8IntegerDotProduct, UnrestrictedPointerParameters = WGPUWGSLLanguageFeatureName_UnrestrictedPointerParameters, PointerCompositeAccess = WGPUWGSLLanguageFeatureName_PointerCompositeAccess, - SizedBindingArray = WGPUWGSLLanguageFeatureName_SizedBindingArray, - TexelBuffers = WGPUWGSLLanguageFeatureName_TexelBuffers, }; static_assert(sizeof(WGSLLanguageFeatureName) == sizeof(WGPUWGSLLanguageFeatureName), "sizeof mismatch for WGSLLanguageFeatureName"); static_assert(alignof(WGSLLanguageFeatureName) == alignof(WGPUWGSLLanguageFeatureName), "alignof mismatch for WGSLLanguageFeatureName"); @@ -935,11 +955,6 @@ class ObjectBase { CType mHandle = nullptr; }; - - - - - class Adapter; class BindGroup; class BindGroupLayout; @@ -978,7 +993,7 @@ struct DawnCompilationMessageUtf16; struct EmscriptenSurfaceSourceCanvasHTMLSelector; struct Extent3D; struct Future; -struct InstanceCapabilities; +struct InstanceLimits; struct INTERNAL_HAVE_EMDAWNWEBGPU_HEADER; struct MultisampleState; struct Origin3D; @@ -999,6 +1014,7 @@ struct ShaderSourceWGSL; struct StencilFaceState; struct StorageTextureBindingLayout; struct SupportedFeatures; +struct SupportedInstanceFeatures; struct SupportedWGSLLanguageFeatures; struct SurfaceCapabilities; struct SurfaceColorManagement; @@ -1007,7 +1023,7 @@ struct SurfaceTexture; struct TexelCopyBufferLayout; struct TextureBindingLayout; struct TextureBindingViewDimensionDescriptor; -struct TextureViewDescriptor; +struct TextureComponentSwizzle; struct VertexAttribute; struct BindGroupDescriptor; struct BindGroupLayoutEntry; @@ -1025,6 +1041,7 @@ struct ShaderModuleDescriptor; struct SurfaceDescriptor; struct TexelCopyBufferInfo; struct TexelCopyTextureInfo; +struct TextureComponentSwizzleDescriptor; struct TextureDescriptor; struct VertexBufferLayout; struct BindGroupLayoutDescriptor; @@ -1033,6 +1050,7 @@ struct CompilationInfo; struct ComputePipelineDescriptor; struct DeviceDescriptor; struct RenderPassDescriptor; +struct TextureViewDescriptor; struct VertexState; struct FragmentState; struct RenderPipelineDescriptor; @@ -1174,21 +1192,21 @@ struct CallbackTypeBase, T> { template -using BufferMapCallback = typename detail::CallbackTypeBase, T...>::Callback; +using BufferMapCallback = typename detail::CallbackTypeBase, T...>::Callback; template -using CompilationInfoCallback = typename detail::CallbackTypeBase, T...>::Callback; +using CompilationInfoCallback = typename detail::CallbackTypeBase, T...>::Callback; template -using CreateComputePipelineAsyncCallback = typename detail::CallbackTypeBase, T...>::Callback; +using CreateComputePipelineAsyncCallback = typename detail::CallbackTypeBase, T...>::Callback; template -using CreateRenderPipelineAsyncCallback = typename detail::CallbackTypeBase, T...>::Callback; +using CreateRenderPipelineAsyncCallback = typename detail::CallbackTypeBase, T...>::Callback; template -using PopErrorScopeCallback = typename detail::CallbackTypeBase, T...>::Callback; +using PopErrorScopeCallback = typename detail::CallbackTypeBase, T...>::Callback; template -using QueueWorkDoneCallback = typename detail::CallbackTypeBase, T...>::Callback; +using QueueWorkDoneCallback = typename detail::CallbackTypeBase, T...>::Callback; template -using RequestAdapterCallback = typename detail::CallbackTypeBase, T...>::Callback; +using RequestAdapterCallback = typename detail::CallbackTypeBase, T...>::Callback; template -using RequestDeviceCallback = typename detail::CallbackTypeBase, T...>::Callback; +using RequestDeviceCallback = typename detail::CallbackTypeBase, T...>::Callback; template using DeviceLostCallback = typename detail::CallbackTypeBase, T...>::Callback; template @@ -1434,7 +1452,7 @@ class Instance : public ObjectBase { using ObjectBase::operator=; inline Surface CreateSurface(SurfaceDescriptor const * descriptor) const; - inline ConvertibleStatus GetWGSLLanguageFeatures(SupportedWGSLLanguageFeatures * features) const; + inline void GetWGSLLanguageFeatures(SupportedWGSLLanguageFeatures * features) const; inline Bool HasWGSLLanguageFeature(WGSLLanguageFeatureName feature) const; inline void ProcessEvents() const; template { inline void Configure(SurfaceConfiguration const * config) const; inline ConvertibleStatus GetCapabilities(Adapter const& adapter, SurfaceCapabilities * capabilities) const; inline void GetCurrentTexture(SurfaceTexture * surfaceTexture) const; - inline void Present() const; + inline ConvertibleStatus Present() const; inline void SetLabel(StringView label) const; inline void Unconfigure() const; @@ -1809,7 +1827,7 @@ struct CompatibilityModeLimits : ChainedStructOut { inline CompatibilityModeLimits(Init&& init); inline operator const WGPUCompatibilityModeLimits&() const noexcept; - static constexpr size_t kFirstMemberAlignment = detail::ConstexprMax(alignof(ChainedStruct), alignof(uint32_t )); + static constexpr size_t kFirstMemberAlignment = detail::ConstexprMax(alignof(ChainedStruct), alignof(uint32_t)); alignas(kFirstMemberAlignment) uint32_t maxStorageBuffersInVertexStage = kLimitU32Undefined; uint32_t maxStorageTexturesInVertexStage = kLimitU32Undefined; uint32_t maxStorageBuffersInFragmentStage = kLimitU32Undefined; @@ -1832,7 +1850,7 @@ struct DawnCompilationMessageUtf16 : ChainedStruct { inline DawnCompilationMessageUtf16(Init&& init); inline operator const WGPUDawnCompilationMessageUtf16&() const noexcept; - static constexpr size_t kFirstMemberAlignment = detail::ConstexprMax(alignof(ChainedStruct), alignof(uint64_t )); + static constexpr size_t kFirstMemberAlignment = detail::ConstexprMax(alignof(ChainedStruct), alignof(uint64_t)); alignas(kFirstMemberAlignment) uint64_t linePos; uint64_t offset; uint64_t length; @@ -1846,7 +1864,7 @@ struct EmscriptenSurfaceSourceCanvasHTMLSelector : ChainedStruct { inline EmscriptenSurfaceSourceCanvasHTMLSelector(Init&& init); inline operator const WGPUEmscriptenSurfaceSourceCanvasHTMLSelector&() const noexcept; - static constexpr size_t kFirstMemberAlignment = detail::ConstexprMax(alignof(ChainedStruct), alignof(StringView )); + static constexpr size_t kFirstMemberAlignment = detail::ConstexprMax(alignof(ChainedStruct), alignof(StringView)); alignas(kFirstMemberAlignment) StringView selector = {}; }; @@ -1864,11 +1882,10 @@ struct Future { uint64_t id; }; -struct InstanceCapabilities { - inline operator const WGPUInstanceCapabilities&() const noexcept; +struct InstanceLimits { + inline operator const WGPUInstanceLimits&() const noexcept; ChainedStructOut * nextInChain = nullptr; - Bool timedWaitAnyEnable = false; size_t timedWaitAnyMaxCount = 0; }; @@ -1984,7 +2001,7 @@ struct RenderPassMaxDrawCount : ChainedStruct { inline RenderPassMaxDrawCount(Init&& init); inline operator const WGPURenderPassMaxDrawCount&() const noexcept; - static constexpr size_t kFirstMemberAlignment = detail::ConstexprMax(alignof(ChainedStruct), alignof(uint64_t )); + static constexpr size_t kFirstMemberAlignment = detail::ConstexprMax(alignof(ChainedStruct), alignof(uint64_t)); alignas(kFirstMemberAlignment) uint64_t maxDrawCount = 50000000; }; @@ -1996,7 +2013,7 @@ struct RequestAdapterWebXROptions : ChainedStruct { inline RequestAdapterWebXROptions(Init&& init); inline operator const WGPURequestAdapterWebXROptions&() const noexcept; - static constexpr size_t kFirstMemberAlignment = detail::ConstexprMax(alignof(ChainedStruct), alignof(Bool )); + static constexpr size_t kFirstMemberAlignment = detail::ConstexprMax(alignof(ChainedStruct), alignof(Bool)); alignas(kFirstMemberAlignment) Bool xrCompatible; }; @@ -2032,7 +2049,7 @@ struct ShaderSourceSPIRV : ChainedStruct { inline ShaderSourceSPIRV(Init&& init); inline operator const WGPUShaderSourceSPIRV&() const noexcept; - static constexpr size_t kFirstMemberAlignment = detail::ConstexprMax(alignof(ChainedStruct), alignof(uint32_t )); + static constexpr size_t kFirstMemberAlignment = detail::ConstexprMax(alignof(ChainedStruct), alignof(uint32_t)); alignas(kFirstMemberAlignment) uint32_t codeSize; uint32_t const * code = nullptr; }; @@ -2045,7 +2062,7 @@ struct ShaderSourceWGSL : ChainedStruct { inline ShaderSourceWGSL(Init&& init); inline operator const WGPUShaderSourceWGSL&() const noexcept; - static constexpr size_t kFirstMemberAlignment = detail::ConstexprMax(alignof(ChainedStruct), alignof(StringView )); + static constexpr size_t kFirstMemberAlignment = detail::ConstexprMax(alignof(ChainedStruct), alignof(StringView)); alignas(kFirstMemberAlignment) StringView code = {}; }; @@ -2084,6 +2101,23 @@ struct SupportedFeatures { static inline void Reset(SupportedFeatures& value); }; +struct SupportedInstanceFeatures { + inline SupportedInstanceFeatures(); + inline ~SupportedInstanceFeatures(); + SupportedInstanceFeatures(const SupportedInstanceFeatures&) = delete; + SupportedInstanceFeatures& operator=(const SupportedInstanceFeatures&) = delete; + inline SupportedInstanceFeatures(SupportedInstanceFeatures&&); + inline SupportedInstanceFeatures& operator=(SupportedInstanceFeatures&&); + inline operator const WGPUSupportedInstanceFeatures&() const noexcept; + + size_t const featureCount = {}; + InstanceFeatureName const * const features = nullptr; + + private: + inline void FreeMembers(); + static inline void Reset(SupportedInstanceFeatures& value); +}; + struct SupportedWGSLLanguageFeatures { inline SupportedWGSLLanguageFeatures(); inline ~SupportedWGSLLanguageFeatures(); @@ -2132,7 +2166,7 @@ struct SurfaceColorManagement : ChainedStruct { inline SurfaceColorManagement(Init&& init); inline operator const WGPUSurfaceColorManagement&() const noexcept; - static constexpr size_t kFirstMemberAlignment = detail::ConstexprMax(alignof(ChainedStruct), alignof(PredefinedColorSpace )); + static constexpr size_t kFirstMemberAlignment = detail::ConstexprMax(alignof(ChainedStruct), alignof(PredefinedColorSpace)); alignas(kFirstMemberAlignment) PredefinedColorSpace colorSpace = {}; ToneMappingMode toneMappingMode = {}; }; @@ -2185,23 +2219,17 @@ struct TextureBindingViewDimensionDescriptor : ChainedStruct { inline TextureBindingViewDimensionDescriptor(Init&& init); inline operator const WGPUTextureBindingViewDimensionDescriptor&() const noexcept; - static constexpr size_t kFirstMemberAlignment = detail::ConstexprMax(alignof(ChainedStruct), alignof(TextureViewDimension )); + static constexpr size_t kFirstMemberAlignment = detail::ConstexprMax(alignof(ChainedStruct), alignof(TextureViewDimension)); alignas(kFirstMemberAlignment) TextureViewDimension textureBindingViewDimension = TextureViewDimension::Undefined; }; -struct TextureViewDescriptor { - inline operator const WGPUTextureViewDescriptor&() const noexcept; +struct TextureComponentSwizzle { + inline operator const WGPUTextureComponentSwizzle&() const noexcept; - ChainedStruct const * nextInChain = nullptr; - StringView label = {}; - TextureFormat format = TextureFormat::Undefined; - TextureViewDimension dimension = TextureViewDimension::Undefined; - uint32_t baseMipLevel = 0; - uint32_t mipLevelCount = kMipLevelCountUndefined; - uint32_t baseArrayLayer = 0; - uint32_t arrayLayerCount = kArrayLayerCountUndefined; - TextureAspect aspect = TextureAspect::Undefined; - TextureUsage usage = TextureUsage::None; + ComponentSwizzle r = ComponentSwizzle::Undefined; + ComponentSwizzle g = ComponentSwizzle::Undefined; + ComponentSwizzle b = ComponentSwizzle::Undefined; + ComponentSwizzle a = ComponentSwizzle::Undefined; }; struct VertexAttribute { @@ -2219,7 +2247,7 @@ struct BindGroupDescriptor { ChainedStruct const * nextInChain = nullptr; StringView label = {}; BindGroupLayout layout = nullptr; - size_t entryCount; + size_t entryCount = 0; BindGroupEntry const * entries = nullptr; }; @@ -2300,7 +2328,9 @@ struct InstanceDescriptor { inline operator const WGPUInstanceDescriptor&() const noexcept; ChainedStruct const * nextInChain = nullptr; - InstanceCapabilities capabilities = {}; + size_t requiredFeatureCount = 0; + InstanceFeatureName const * requiredFeatures = nullptr; + InstanceLimits const * requiredLimits = nullptr; }; struct Limits { @@ -2394,6 +2424,18 @@ struct TexelCopyTextureInfo { TextureAspect aspect = TextureAspect::Undefined; }; +// Can be chained in TextureViewDescriptor +struct TextureComponentSwizzleDescriptor : ChainedStruct { + inline TextureComponentSwizzleDescriptor(); + + struct Init; + inline TextureComponentSwizzleDescriptor(Init&& init); + inline operator const WGPUTextureComponentSwizzleDescriptor&() const noexcept; + + static constexpr size_t kFirstMemberAlignment = detail::ConstexprMax(alignof(ChainedStruct), alignof(TextureComponentSwizzle)); + alignas(kFirstMemberAlignment) TextureComponentSwizzle swizzle = {}; +}; + struct TextureDescriptor { inline operator const WGPUTextureDescriptor&() const noexcept; @@ -2424,7 +2466,7 @@ struct BindGroupLayoutDescriptor { ChainedStruct const * nextInChain = nullptr; StringView label = {}; - size_t entryCount; + size_t entryCount = 0; BindGroupLayoutEntry const * entries = nullptr; }; @@ -2466,6 +2508,21 @@ struct RenderPassDescriptor { PassTimestampWrites const * timestampWrites = nullptr; }; +struct TextureViewDescriptor { + inline operator const WGPUTextureViewDescriptor&() const noexcept; + + ChainedStruct const * nextInChain = nullptr; + StringView label = {}; + TextureFormat format = TextureFormat::Undefined; + TextureViewDimension dimension = TextureViewDimension::Undefined; + uint32_t baseMipLevel = 0; + uint32_t mipLevelCount = kMipLevelCountUndefined; + uint32_t baseArrayLayer = 0; + uint32_t arrayLayerCount = kArrayLayerCountUndefined; + TextureAspect aspect = TextureAspect::Undefined; + TextureUsage usage = TextureUsage::None; +}; + struct VertexState { inline operator const WGPUVertexState&() const noexcept; @@ -2883,20 +2940,18 @@ static_assert(alignof(Future) == alignof(WGPUFuture), "alignof mismatch for Futu static_assert(offsetof(Future, id) == offsetof(WGPUFuture, id), "offsetof mismatch for Future::id"); -// InstanceCapabilities implementation +// InstanceLimits implementation -InstanceCapabilities::operator const WGPUInstanceCapabilities&() const noexcept { - return *reinterpret_cast(this); +InstanceLimits::operator const WGPUInstanceLimits&() const noexcept { + return *reinterpret_cast(this); } -static_assert(sizeof(InstanceCapabilities) == sizeof(WGPUInstanceCapabilities), "sizeof mismatch for InstanceCapabilities"); -static_assert(alignof(InstanceCapabilities) == alignof(WGPUInstanceCapabilities), "alignof mismatch for InstanceCapabilities"); -static_assert(offsetof(InstanceCapabilities, nextInChain) == offsetof(WGPUInstanceCapabilities, nextInChain), - "offsetof mismatch for InstanceCapabilities::nextInChain"); -static_assert(offsetof(InstanceCapabilities, timedWaitAnyEnable) == offsetof(WGPUInstanceCapabilities, timedWaitAnyEnable), - "offsetof mismatch for InstanceCapabilities::timedWaitAnyEnable"); -static_assert(offsetof(InstanceCapabilities, timedWaitAnyMaxCount) == offsetof(WGPUInstanceCapabilities, timedWaitAnyMaxCount), - "offsetof mismatch for InstanceCapabilities::timedWaitAnyMaxCount"); +static_assert(sizeof(InstanceLimits) == sizeof(WGPUInstanceLimits), "sizeof mismatch for InstanceLimits"); +static_assert(alignof(InstanceLimits) == alignof(WGPUInstanceLimits), "alignof mismatch for InstanceLimits"); +static_assert(offsetof(InstanceLimits, nextInChain) == offsetof(WGPUInstanceLimits, nextInChain), + "offsetof mismatch for InstanceLimits::nextInChain"); +static_assert(offsetof(InstanceLimits, timedWaitAnyMaxCount) == offsetof(WGPUInstanceLimits, timedWaitAnyMaxCount), + "offsetof mismatch for InstanceLimits::timedWaitAnyMaxCount"); // INTERNAL_HAVE_EMDAWNWEBGPU_HEADER implementation @@ -3307,6 +3362,54 @@ static_assert(offsetof(SupportedFeatures, featureCount) == offsetof(WGPUSupporte static_assert(offsetof(SupportedFeatures, features) == offsetof(WGPUSupportedFeatures, features), "offsetof mismatch for SupportedFeatures::features"); +// SupportedInstanceFeatures implementation +SupportedInstanceFeatures::SupportedInstanceFeatures() = default; +SupportedInstanceFeatures::~SupportedInstanceFeatures() { + FreeMembers(); +} + +SupportedInstanceFeatures::SupportedInstanceFeatures(SupportedInstanceFeatures&& rhs) + : featureCount(rhs.featureCount), + features(rhs.features){ + Reset(rhs); +} + +SupportedInstanceFeatures& SupportedInstanceFeatures::operator=(SupportedInstanceFeatures&& rhs) { + if (&rhs == this) { + return *this; + } + FreeMembers(); + detail::AsNonConstReference(this->featureCount) = std::move(rhs.featureCount); + detail::AsNonConstReference(this->features) = std::move(rhs.features); + Reset(rhs); + return *this; +} + +void SupportedInstanceFeatures::FreeMembers() { + bool needsFreeing = false; if (this->features != nullptr) { needsFreeing = true; }if (needsFreeing) { + wgpuSupportedInstanceFeaturesFreeMembers( + *reinterpret_cast(this)); + } +} + +// static +void SupportedInstanceFeatures::Reset(SupportedInstanceFeatures& value) { + SupportedInstanceFeatures defaultValue{}; + detail::AsNonConstReference(value.featureCount) = defaultValue.featureCount; + detail::AsNonConstReference(value.features) = defaultValue.features; +} + +SupportedInstanceFeatures::operator const WGPUSupportedInstanceFeatures&() const noexcept { + return *reinterpret_cast(this); +} + +static_assert(sizeof(SupportedInstanceFeatures) == sizeof(WGPUSupportedInstanceFeatures), "sizeof mismatch for SupportedInstanceFeatures"); +static_assert(alignof(SupportedInstanceFeatures) == alignof(WGPUSupportedInstanceFeatures), "alignof mismatch for SupportedInstanceFeatures"); +static_assert(offsetof(SupportedInstanceFeatures, featureCount) == offsetof(WGPUSupportedInstanceFeatures, featureCount), + "offsetof mismatch for SupportedInstanceFeatures::featureCount"); +static_assert(offsetof(SupportedInstanceFeatures, features) == offsetof(WGPUSupportedInstanceFeatures, features), + "offsetof mismatch for SupportedInstanceFeatures::features"); + // SupportedWGSLLanguageFeatures implementation SupportedWGSLLanguageFeatures::SupportedWGSLLanguageFeatures() = default; SupportedWGSLLanguageFeatures::~SupportedWGSLLanguageFeatures() { @@ -3550,34 +3653,22 @@ static_assert(alignof(TextureBindingViewDimensionDescriptor) == alignof(WGPUText static_assert(offsetof(TextureBindingViewDimensionDescriptor, textureBindingViewDimension) == offsetof(WGPUTextureBindingViewDimensionDescriptor, textureBindingViewDimension), "offsetof mismatch for TextureBindingViewDimensionDescriptor::textureBindingViewDimension"); -// TextureViewDescriptor implementation +// TextureComponentSwizzle implementation -TextureViewDescriptor::operator const WGPUTextureViewDescriptor&() const noexcept { - return *reinterpret_cast(this); +TextureComponentSwizzle::operator const WGPUTextureComponentSwizzle&() const noexcept { + return *reinterpret_cast(this); } -static_assert(sizeof(TextureViewDescriptor) == sizeof(WGPUTextureViewDescriptor), "sizeof mismatch for TextureViewDescriptor"); -static_assert(alignof(TextureViewDescriptor) == alignof(WGPUTextureViewDescriptor), "alignof mismatch for TextureViewDescriptor"); -static_assert(offsetof(TextureViewDescriptor, nextInChain) == offsetof(WGPUTextureViewDescriptor, nextInChain), - "offsetof mismatch for TextureViewDescriptor::nextInChain"); -static_assert(offsetof(TextureViewDescriptor, label) == offsetof(WGPUTextureViewDescriptor, label), - "offsetof mismatch for TextureViewDescriptor::label"); -static_assert(offsetof(TextureViewDescriptor, format) == offsetof(WGPUTextureViewDescriptor, format), - "offsetof mismatch for TextureViewDescriptor::format"); -static_assert(offsetof(TextureViewDescriptor, dimension) == offsetof(WGPUTextureViewDescriptor, dimension), - "offsetof mismatch for TextureViewDescriptor::dimension"); -static_assert(offsetof(TextureViewDescriptor, baseMipLevel) == offsetof(WGPUTextureViewDescriptor, baseMipLevel), - "offsetof mismatch for TextureViewDescriptor::baseMipLevel"); -static_assert(offsetof(TextureViewDescriptor, mipLevelCount) == offsetof(WGPUTextureViewDescriptor, mipLevelCount), - "offsetof mismatch for TextureViewDescriptor::mipLevelCount"); -static_assert(offsetof(TextureViewDescriptor, baseArrayLayer) == offsetof(WGPUTextureViewDescriptor, baseArrayLayer), - "offsetof mismatch for TextureViewDescriptor::baseArrayLayer"); -static_assert(offsetof(TextureViewDescriptor, arrayLayerCount) == offsetof(WGPUTextureViewDescriptor, arrayLayerCount), - "offsetof mismatch for TextureViewDescriptor::arrayLayerCount"); -static_assert(offsetof(TextureViewDescriptor, aspect) == offsetof(WGPUTextureViewDescriptor, aspect), - "offsetof mismatch for TextureViewDescriptor::aspect"); -static_assert(offsetof(TextureViewDescriptor, usage) == offsetof(WGPUTextureViewDescriptor, usage), - "offsetof mismatch for TextureViewDescriptor::usage"); +static_assert(sizeof(TextureComponentSwizzle) == sizeof(WGPUTextureComponentSwizzle), "sizeof mismatch for TextureComponentSwizzle"); +static_assert(alignof(TextureComponentSwizzle) == alignof(WGPUTextureComponentSwizzle), "alignof mismatch for TextureComponentSwizzle"); +static_assert(offsetof(TextureComponentSwizzle, r) == offsetof(WGPUTextureComponentSwizzle, r), + "offsetof mismatch for TextureComponentSwizzle::r"); +static_assert(offsetof(TextureComponentSwizzle, g) == offsetof(WGPUTextureComponentSwizzle, g), + "offsetof mismatch for TextureComponentSwizzle::g"); +static_assert(offsetof(TextureComponentSwizzle, b) == offsetof(WGPUTextureComponentSwizzle, b), + "offsetof mismatch for TextureComponentSwizzle::b"); +static_assert(offsetof(TextureComponentSwizzle, a) == offsetof(WGPUTextureComponentSwizzle, a), + "offsetof mismatch for TextureComponentSwizzle::a"); // VertexAttribute implementation @@ -3764,8 +3855,12 @@ static_assert(sizeof(InstanceDescriptor) == sizeof(WGPUInstanceDescriptor), "siz static_assert(alignof(InstanceDescriptor) == alignof(WGPUInstanceDescriptor), "alignof mismatch for InstanceDescriptor"); static_assert(offsetof(InstanceDescriptor, nextInChain) == offsetof(WGPUInstanceDescriptor, nextInChain), "offsetof mismatch for InstanceDescriptor::nextInChain"); -static_assert(offsetof(InstanceDescriptor, capabilities) == offsetof(WGPUInstanceDescriptor, capabilities), - "offsetof mismatch for InstanceDescriptor::capabilities"); +static_assert(offsetof(InstanceDescriptor, requiredFeatureCount) == offsetof(WGPUInstanceDescriptor, requiredFeatureCount), + "offsetof mismatch for InstanceDescriptor::requiredFeatureCount"); +static_assert(offsetof(InstanceDescriptor, requiredFeatures) == offsetof(WGPUInstanceDescriptor, requiredFeatures), + "offsetof mismatch for InstanceDescriptor::requiredFeatures"); +static_assert(offsetof(InstanceDescriptor, requiredLimits) == offsetof(WGPUInstanceDescriptor, requiredLimits), + "offsetof mismatch for InstanceDescriptor::requiredLimits"); // Limits implementation @@ -3942,6 +4037,26 @@ static_assert(offsetof(TexelCopyTextureInfo, origin) == offsetof(WGPUTexelCopyTe static_assert(offsetof(TexelCopyTextureInfo, aspect) == offsetof(WGPUTexelCopyTextureInfo, aspect), "offsetof mismatch for TexelCopyTextureInfo::aspect"); +// TextureComponentSwizzleDescriptor implementation +TextureComponentSwizzleDescriptor::TextureComponentSwizzleDescriptor() + : ChainedStruct { nullptr, SType::TextureComponentSwizzleDescriptor } {} +struct TextureComponentSwizzleDescriptor::Init { + ChainedStruct * const nextInChain; + TextureComponentSwizzle swizzle = {}; +}; +TextureComponentSwizzleDescriptor::TextureComponentSwizzleDescriptor(TextureComponentSwizzleDescriptor::Init&& init) + : ChainedStruct { init.nextInChain, SType::TextureComponentSwizzleDescriptor }, + swizzle(std::move(init.swizzle)){} + +TextureComponentSwizzleDescriptor::operator const WGPUTextureComponentSwizzleDescriptor&() const noexcept { + return *reinterpret_cast(this); +} + +static_assert(sizeof(TextureComponentSwizzleDescriptor) == sizeof(WGPUTextureComponentSwizzleDescriptor), "sizeof mismatch for TextureComponentSwizzleDescriptor"); +static_assert(alignof(TextureComponentSwizzleDescriptor) == alignof(WGPUTextureComponentSwizzleDescriptor), "alignof mismatch for TextureComponentSwizzleDescriptor"); +static_assert(offsetof(TextureComponentSwizzleDescriptor, swizzle) == offsetof(WGPUTextureComponentSwizzleDescriptor, swizzle), + "offsetof mismatch for TextureComponentSwizzleDescriptor::swizzle"); + // TextureDescriptor implementation TextureDescriptor::operator const WGPUTextureDescriptor&() const noexcept { @@ -4079,6 +4194,35 @@ static_assert(offsetof(RenderPassDescriptor, occlusionQuerySet) == offsetof(WGPU static_assert(offsetof(RenderPassDescriptor, timestampWrites) == offsetof(WGPURenderPassDescriptor, timestampWrites), "offsetof mismatch for RenderPassDescriptor::timestampWrites"); +// TextureViewDescriptor implementation + +TextureViewDescriptor::operator const WGPUTextureViewDescriptor&() const noexcept { + return *reinterpret_cast(this); +} + +static_assert(sizeof(TextureViewDescriptor) == sizeof(WGPUTextureViewDescriptor), "sizeof mismatch for TextureViewDescriptor"); +static_assert(alignof(TextureViewDescriptor) == alignof(WGPUTextureViewDescriptor), "alignof mismatch for TextureViewDescriptor"); +static_assert(offsetof(TextureViewDescriptor, nextInChain) == offsetof(WGPUTextureViewDescriptor, nextInChain), + "offsetof mismatch for TextureViewDescriptor::nextInChain"); +static_assert(offsetof(TextureViewDescriptor, label) == offsetof(WGPUTextureViewDescriptor, label), + "offsetof mismatch for TextureViewDescriptor::label"); +static_assert(offsetof(TextureViewDescriptor, format) == offsetof(WGPUTextureViewDescriptor, format), + "offsetof mismatch for TextureViewDescriptor::format"); +static_assert(offsetof(TextureViewDescriptor, dimension) == offsetof(WGPUTextureViewDescriptor, dimension), + "offsetof mismatch for TextureViewDescriptor::dimension"); +static_assert(offsetof(TextureViewDescriptor, baseMipLevel) == offsetof(WGPUTextureViewDescriptor, baseMipLevel), + "offsetof mismatch for TextureViewDescriptor::baseMipLevel"); +static_assert(offsetof(TextureViewDescriptor, mipLevelCount) == offsetof(WGPUTextureViewDescriptor, mipLevelCount), + "offsetof mismatch for TextureViewDescriptor::mipLevelCount"); +static_assert(offsetof(TextureViewDescriptor, baseArrayLayer) == offsetof(WGPUTextureViewDescriptor, baseArrayLayer), + "offsetof mismatch for TextureViewDescriptor::baseArrayLayer"); +static_assert(offsetof(TextureViewDescriptor, arrayLayerCount) == offsetof(WGPUTextureViewDescriptor, arrayLayerCount), + "offsetof mismatch for TextureViewDescriptor::arrayLayerCount"); +static_assert(offsetof(TextureViewDescriptor, aspect) == offsetof(WGPUTextureViewDescriptor, aspect), + "offsetof mismatch for TextureViewDescriptor::aspect"); +static_assert(offsetof(TextureViewDescriptor, usage) == offsetof(WGPUTextureViewDescriptor, usage), + "offsetof mismatch for TextureViewDescriptor::usage"); + // VertexState implementation VertexState::operator const WGPUVertexState&() const noexcept { @@ -4281,15 +4425,15 @@ void DeviceDescriptor::SetUncapturedErrorCallback(L callback) { void Adapter::GetFeatures(SupportedFeatures * features) const { *features = SupportedFeatures(); - wgpuAdapterGetFeatures(Get(), reinterpret_cast(features)); + wgpuAdapterGetFeatures(Get(), reinterpret_cast(features)); } ConvertibleStatus Adapter::GetInfo(AdapterInfo * info) const { *info = AdapterInfo(); - auto result = wgpuAdapterGetInfo(Get(), reinterpret_cast(info)); + auto result = wgpuAdapterGetInfo(Get(), reinterpret_cast(info)); return static_cast(result); } ConvertibleStatus Adapter::GetLimits(Limits * limits) const { - auto result = wgpuAdapterGetLimits(Get(), reinterpret_cast(limits)); + auto result = wgpuAdapterGetLimits(Get(), reinterpret_cast(limits)); return static_cast(result); } Bool Adapter::HasFeature(FeatureName feature) const { @@ -4319,7 +4463,7 @@ Future Adapter::RequestDevice(DeviceDescriptor const * descriptor, CallbackMode } callbackInfo.userdata1 = reinterpret_cast(+callback); callbackInfo.userdata2 = reinterpret_cast(userdata); - auto result = wgpuAdapterRequestDevice(Get(), reinterpret_cast(descriptor), callbackInfo); + auto result = wgpuAdapterRequestDevice(Get(), reinterpret_cast(descriptor), callbackInfo); return Future { result.id }; @@ -4352,7 +4496,7 @@ Future Adapter::RequestDevice(DeviceDescriptor const * descriptor, CallbackMode callbackInfo.userdata1 = reinterpret_cast(lambda); callbackInfo.userdata2 = nullptr; } - auto result = wgpuAdapterRequestDevice(Get(), reinterpret_cast(descriptor), callbackInfo); + auto result = wgpuAdapterRequestDevice(Get(), reinterpret_cast(descriptor), callbackInfo); return Future { result.id }; @@ -4499,7 +4643,7 @@ Future Buffer::MapAsync(MapMode mode, size_t offset, size_t size, CallbackMode c }; } ConvertibleStatus Buffer::ReadMappedRange(size_t offset, void * data, size_t size) const { - auto result = wgpuBufferReadMappedRange(Get(), offset, reinterpret_cast(data), size); + auto result = wgpuBufferReadMappedRange(Get(), offset, reinterpret_cast(data), size); return static_cast(result); } void Buffer::SetLabel(StringView label) const { @@ -4509,7 +4653,7 @@ void Buffer::Unmap() const { wgpuBufferUnmap(Get()); } ConvertibleStatus Buffer::WriteMappedRange(size_t offset, void const * data, size_t size) const { - auto result = wgpuBufferWriteMappedRange(Get(), offset, reinterpret_cast(data), size); + auto result = wgpuBufferWriteMappedRange(Get(), offset, reinterpret_cast(data), size); return static_cast(result); } @@ -4550,11 +4694,11 @@ static_assert(alignof(CommandBuffer) == alignof(WGPUCommandBuffer), "alignof mis // CommandEncoder implementation ComputePassEncoder CommandEncoder::BeginComputePass(ComputePassDescriptor const * descriptor) const { - auto result = wgpuCommandEncoderBeginComputePass(Get(), reinterpret_cast(descriptor)); + auto result = wgpuCommandEncoderBeginComputePass(Get(), reinterpret_cast(descriptor)); return ComputePassEncoder::Acquire(result); } RenderPassEncoder CommandEncoder::BeginRenderPass(RenderPassDescriptor const * descriptor) const { - auto result = wgpuCommandEncoderBeginRenderPass(Get(), reinterpret_cast(descriptor)); + auto result = wgpuCommandEncoderBeginRenderPass(Get(), reinterpret_cast(descriptor)); return RenderPassEncoder::Acquire(result); } void CommandEncoder::ClearBuffer(Buffer const& buffer, uint64_t offset, uint64_t size) const { @@ -4564,16 +4708,16 @@ void CommandEncoder::CopyBufferToBuffer(Buffer const& source, uint64_t sourceOff wgpuCommandEncoderCopyBufferToBuffer(Get(), source.Get(), sourceOffset, destination.Get(), destinationOffset, size); } void CommandEncoder::CopyBufferToTexture(TexelCopyBufferInfo const * source, TexelCopyTextureInfo const * destination, Extent3D const * copySize) const { - wgpuCommandEncoderCopyBufferToTexture(Get(), reinterpret_cast(source), reinterpret_cast(destination), reinterpret_cast(copySize)); + wgpuCommandEncoderCopyBufferToTexture(Get(), reinterpret_cast(source), reinterpret_cast(destination), reinterpret_cast(copySize)); } void CommandEncoder::CopyTextureToBuffer(TexelCopyTextureInfo const * source, TexelCopyBufferInfo const * destination, Extent3D const * copySize) const { - wgpuCommandEncoderCopyTextureToBuffer(Get(), reinterpret_cast(source), reinterpret_cast(destination), reinterpret_cast(copySize)); + wgpuCommandEncoderCopyTextureToBuffer(Get(), reinterpret_cast(source), reinterpret_cast(destination), reinterpret_cast(copySize)); } void CommandEncoder::CopyTextureToTexture(TexelCopyTextureInfo const * source, TexelCopyTextureInfo const * destination, Extent3D const * copySize) const { - wgpuCommandEncoderCopyTextureToTexture(Get(), reinterpret_cast(source), reinterpret_cast(destination), reinterpret_cast(copySize)); + wgpuCommandEncoderCopyTextureToTexture(Get(), reinterpret_cast(source), reinterpret_cast(destination), reinterpret_cast(copySize)); } CommandBuffer CommandEncoder::Finish(CommandBufferDescriptor const * descriptor) const { - auto result = wgpuCommandEncoderFinish(Get(), reinterpret_cast(descriptor)); + auto result = wgpuCommandEncoderFinish(Get(), reinterpret_cast(descriptor)); return CommandBuffer::Acquire(result); } void CommandEncoder::InsertDebugMarker(StringView markerLabel) const { @@ -4630,7 +4774,7 @@ void ComputePassEncoder::PushDebugGroup(StringView groupLabel) const { wgpuComputePassEncoderPushDebugGroup(Get(), *reinterpret_cast(&groupLabel)); } void ComputePassEncoder::SetBindGroup(uint32_t groupIndex, BindGroup const& group, size_t dynamicOffsetCount, uint32_t const * dynamicOffsets) const { - wgpuComputePassEncoderSetBindGroup(Get(), groupIndex, group.Get(), dynamicOffsetCount, reinterpret_cast(dynamicOffsets)); + wgpuComputePassEncoderSetBindGroup(Get(), groupIndex, group.Get(), dynamicOffsetCount, reinterpret_cast(dynamicOffsets)); } void ComputePassEncoder::SetLabel(StringView label) const { wgpuComputePassEncoderSetLabel(Get(), *reinterpret_cast(&label)); @@ -4683,23 +4827,23 @@ static_assert(alignof(ComputePipeline) == alignof(WGPUComputePipeline), "alignof // Device implementation BindGroup Device::CreateBindGroup(BindGroupDescriptor const * descriptor) const { - auto result = wgpuDeviceCreateBindGroup(Get(), reinterpret_cast(descriptor)); + auto result = wgpuDeviceCreateBindGroup(Get(), reinterpret_cast(descriptor)); return BindGroup::Acquire(result); } BindGroupLayout Device::CreateBindGroupLayout(BindGroupLayoutDescriptor const * descriptor) const { - auto result = wgpuDeviceCreateBindGroupLayout(Get(), reinterpret_cast(descriptor)); + auto result = wgpuDeviceCreateBindGroupLayout(Get(), reinterpret_cast(descriptor)); return BindGroupLayout::Acquire(result); } Buffer Device::CreateBuffer(BufferDescriptor const * descriptor) const { - auto result = wgpuDeviceCreateBuffer(Get(), reinterpret_cast(descriptor)); + auto result = wgpuDeviceCreateBuffer(Get(), reinterpret_cast(descriptor)); return Buffer::Acquire(result); } CommandEncoder Device::CreateCommandEncoder(CommandEncoderDescriptor const * descriptor) const { - auto result = wgpuDeviceCreateCommandEncoder(Get(), reinterpret_cast(descriptor)); + auto result = wgpuDeviceCreateCommandEncoder(Get(), reinterpret_cast(descriptor)); return CommandEncoder::Acquire(result); } ComputePipeline Device::CreateComputePipeline(ComputePipelineDescriptor const * descriptor) const { - auto result = wgpuDeviceCreateComputePipeline(Get(), reinterpret_cast(descriptor)); + auto result = wgpuDeviceCreateComputePipeline(Get(), reinterpret_cast(descriptor)); return ComputePipeline::Acquire(result); } template (+callback); callbackInfo.userdata2 = reinterpret_cast(userdata); - auto result = wgpuDeviceCreateComputePipelineAsync(Get(), reinterpret_cast(descriptor), callbackInfo); + auto result = wgpuDeviceCreateComputePipelineAsync(Get(), reinterpret_cast(descriptor), callbackInfo); return Future { result.id }; @@ -4758,25 +4902,25 @@ Future Device::CreateComputePipelineAsync(ComputePipelineDescriptor const * desc callbackInfo.userdata1 = reinterpret_cast(lambda); callbackInfo.userdata2 = nullptr; } - auto result = wgpuDeviceCreateComputePipelineAsync(Get(), reinterpret_cast(descriptor), callbackInfo); + auto result = wgpuDeviceCreateComputePipelineAsync(Get(), reinterpret_cast(descriptor), callbackInfo); return Future { result.id }; } PipelineLayout Device::CreatePipelineLayout(PipelineLayoutDescriptor const * descriptor) const { - auto result = wgpuDeviceCreatePipelineLayout(Get(), reinterpret_cast(descriptor)); + auto result = wgpuDeviceCreatePipelineLayout(Get(), reinterpret_cast(descriptor)); return PipelineLayout::Acquire(result); } QuerySet Device::CreateQuerySet(QuerySetDescriptor const * descriptor) const { - auto result = wgpuDeviceCreateQuerySet(Get(), reinterpret_cast(descriptor)); + auto result = wgpuDeviceCreateQuerySet(Get(), reinterpret_cast(descriptor)); return QuerySet::Acquire(result); } RenderBundleEncoder Device::CreateRenderBundleEncoder(RenderBundleEncoderDescriptor const * descriptor) const { - auto result = wgpuDeviceCreateRenderBundleEncoder(Get(), reinterpret_cast(descriptor)); + auto result = wgpuDeviceCreateRenderBundleEncoder(Get(), reinterpret_cast(descriptor)); return RenderBundleEncoder::Acquire(result); } RenderPipeline Device::CreateRenderPipeline(RenderPipelineDescriptor const * descriptor) const { - auto result = wgpuDeviceCreateRenderPipeline(Get(), reinterpret_cast(descriptor)); + auto result = wgpuDeviceCreateRenderPipeline(Get(), reinterpret_cast(descriptor)); return RenderPipeline::Acquire(result); } template (+callback); callbackInfo.userdata2 = reinterpret_cast(userdata); - auto result = wgpuDeviceCreateRenderPipelineAsync(Get(), reinterpret_cast(descriptor), callbackInfo); + auto result = wgpuDeviceCreateRenderPipelineAsync(Get(), reinterpret_cast(descriptor), callbackInfo); return Future { result.id }; @@ -4835,21 +4979,21 @@ Future Device::CreateRenderPipelineAsync(RenderPipelineDescriptor const * descri callbackInfo.userdata1 = reinterpret_cast(lambda); callbackInfo.userdata2 = nullptr; } - auto result = wgpuDeviceCreateRenderPipelineAsync(Get(), reinterpret_cast(descriptor), callbackInfo); + auto result = wgpuDeviceCreateRenderPipelineAsync(Get(), reinterpret_cast(descriptor), callbackInfo); return Future { result.id }; } Sampler Device::CreateSampler(SamplerDescriptor const * descriptor) const { - auto result = wgpuDeviceCreateSampler(Get(), reinterpret_cast(descriptor)); + auto result = wgpuDeviceCreateSampler(Get(), reinterpret_cast(descriptor)); return Sampler::Acquire(result); } ShaderModule Device::CreateShaderModule(ShaderModuleDescriptor const * descriptor) const { - auto result = wgpuDeviceCreateShaderModule(Get(), reinterpret_cast(descriptor)); + auto result = wgpuDeviceCreateShaderModule(Get(), reinterpret_cast(descriptor)); return ShaderModule::Acquire(result); } Texture Device::CreateTexture(TextureDescriptor const * descriptor) const { - auto result = wgpuDeviceCreateTexture(Get(), reinterpret_cast(descriptor)); + auto result = wgpuDeviceCreateTexture(Get(), reinterpret_cast(descriptor)); return Texture::Acquire(result); } void Device::Destroy() const { @@ -4857,15 +5001,15 @@ void Device::Destroy() const { } ConvertibleStatus Device::GetAdapterInfo(AdapterInfo * adapterInfo) const { *adapterInfo = AdapterInfo(); - auto result = wgpuDeviceGetAdapterInfo(Get(), reinterpret_cast(adapterInfo)); + auto result = wgpuDeviceGetAdapterInfo(Get(), reinterpret_cast(adapterInfo)); return static_cast(result); } void Device::GetFeatures(SupportedFeatures * features) const { *features = SupportedFeatures(); - wgpuDeviceGetFeatures(Get(), reinterpret_cast(features)); + wgpuDeviceGetFeatures(Get(), reinterpret_cast(features)); } ConvertibleStatus Device::GetLimits(Limits * limits) const { - auto result = wgpuDeviceGetLimits(Get(), reinterpret_cast(limits)); + auto result = wgpuDeviceGetLimits(Get(), reinterpret_cast(limits)); return static_cast(result); } Future Device::GetLostFuture() const { @@ -4967,13 +5111,12 @@ static_assert(alignof(Device) == alignof(WGPUDevice), "alignof mismatch for Devi // Instance implementation Surface Instance::CreateSurface(SurfaceDescriptor const * descriptor) const { - auto result = wgpuInstanceCreateSurface(Get(), reinterpret_cast(descriptor)); + auto result = wgpuInstanceCreateSurface(Get(), reinterpret_cast(descriptor)); return Surface::Acquire(result); } -ConvertibleStatus Instance::GetWGSLLanguageFeatures(SupportedWGSLLanguageFeatures * features) const { +void Instance::GetWGSLLanguageFeatures(SupportedWGSLLanguageFeatures * features) const { *features = SupportedWGSLLanguageFeatures(); - auto result = wgpuInstanceGetWGSLLanguageFeatures(Get(), reinterpret_cast(features)); - return static_cast(result); + wgpuInstanceGetWGSLLanguageFeatures(Get(), reinterpret_cast(features)); } Bool Instance::HasWGSLLanguageFeature(WGSLLanguageFeatureName feature) const { auto result = wgpuInstanceHasWGSLLanguageFeature(Get(), static_cast(feature)); @@ -5005,7 +5148,7 @@ Future Instance::RequestAdapter(RequestAdapterOptions const * options, CallbackM } callbackInfo.userdata1 = reinterpret_cast(+callback); callbackInfo.userdata2 = reinterpret_cast(userdata); - auto result = wgpuInstanceRequestAdapter(Get(), reinterpret_cast(options), callbackInfo); + auto result = wgpuInstanceRequestAdapter(Get(), reinterpret_cast(options), callbackInfo); return Future { result.id }; @@ -5038,13 +5181,13 @@ Future Instance::RequestAdapter(RequestAdapterOptions const * options, CallbackM callbackInfo.userdata1 = reinterpret_cast(lambda); callbackInfo.userdata2 = nullptr; } - auto result = wgpuInstanceRequestAdapter(Get(), reinterpret_cast(options), callbackInfo); + auto result = wgpuInstanceRequestAdapter(Get(), reinterpret_cast(options), callbackInfo); return Future { result.id }; } WaitStatus Instance::WaitAny(size_t futureCount, FutureWaitInfo * futures, uint64_t timeoutNS) const { - auto result = wgpuInstanceWaitAny(Get(), futureCount, reinterpret_cast(futures), timeoutNS); + auto result = wgpuInstanceWaitAny(Get(), futureCount, reinterpret_cast(futures), timeoutNS); return static_cast(result); } @@ -5184,13 +5327,13 @@ void Queue::SetLabel(StringView label) const { wgpuQueueSetLabel(Get(), *reinterpret_cast(&label)); } void Queue::Submit(size_t commandCount, CommandBuffer const * commands) const { - wgpuQueueSubmit(Get(), commandCount, reinterpret_cast(commands)); + wgpuQueueSubmit(Get(), commandCount, reinterpret_cast(commands)); } void Queue::WriteBuffer(Buffer const& buffer, uint64_t bufferOffset, void const * data, size_t size) const { - wgpuQueueWriteBuffer(Get(), buffer.Get(), bufferOffset, reinterpret_cast(data), size); + wgpuQueueWriteBuffer(Get(), buffer.Get(), bufferOffset, reinterpret_cast(data), size); } void Queue::WriteTexture(TexelCopyTextureInfo const * destination, void const * data, size_t dataSize, TexelCopyBufferLayout const * dataLayout, Extent3D const * writeSize) const { - wgpuQueueWriteTexture(Get(), reinterpret_cast(destination), reinterpret_cast(data), dataSize, reinterpret_cast(dataLayout), reinterpret_cast(writeSize)); + wgpuQueueWriteTexture(Get(), reinterpret_cast(destination), reinterpret_cast(data), dataSize, reinterpret_cast(dataLayout), reinterpret_cast(writeSize)); } @@ -5242,7 +5385,7 @@ void RenderBundleEncoder::DrawIndirect(Buffer const& indirectBuffer, uint64_t in wgpuRenderBundleEncoderDrawIndirect(Get(), indirectBuffer.Get(), indirectOffset); } RenderBundle RenderBundleEncoder::Finish(RenderBundleDescriptor const * descriptor) const { - auto result = wgpuRenderBundleEncoderFinish(Get(), reinterpret_cast(descriptor)); + auto result = wgpuRenderBundleEncoderFinish(Get(), reinterpret_cast(descriptor)); return RenderBundle::Acquire(result); } void RenderBundleEncoder::InsertDebugMarker(StringView markerLabel) const { @@ -5255,7 +5398,7 @@ void RenderBundleEncoder::PushDebugGroup(StringView groupLabel) const { wgpuRenderBundleEncoderPushDebugGroup(Get(), *reinterpret_cast(&groupLabel)); } void RenderBundleEncoder::SetBindGroup(uint32_t groupIndex, BindGroup const& group, size_t dynamicOffsetCount, uint32_t const * dynamicOffsets) const { - wgpuRenderBundleEncoderSetBindGroup(Get(), groupIndex, group.Get(), dynamicOffsetCount, reinterpret_cast(dynamicOffsets)); + wgpuRenderBundleEncoderSetBindGroup(Get(), groupIndex, group.Get(), dynamicOffsetCount, reinterpret_cast(dynamicOffsets)); } void RenderBundleEncoder::SetIndexBuffer(Buffer const& buffer, IndexFormat format, uint64_t offset, uint64_t size) const { wgpuRenderBundleEncoderSetIndexBuffer(Get(), buffer.Get(), static_cast(format), offset, size); @@ -5308,7 +5451,7 @@ void RenderPassEncoder::EndOcclusionQuery() const { wgpuRenderPassEncoderEndOcclusionQuery(Get()); } void RenderPassEncoder::ExecuteBundles(size_t bundleCount, RenderBundle const * bundles) const { - wgpuRenderPassEncoderExecuteBundles(Get(), bundleCount, reinterpret_cast(bundles)); + wgpuRenderPassEncoderExecuteBundles(Get(), bundleCount, reinterpret_cast(bundles)); } void RenderPassEncoder::InsertDebugMarker(StringView markerLabel) const { wgpuRenderPassEncoderInsertDebugMarker(Get(), *reinterpret_cast(&markerLabel)); @@ -5326,10 +5469,10 @@ void RenderPassEncoder::PushDebugGroup(StringView groupLabel) const { wgpuRenderPassEncoderPushDebugGroup(Get(), *reinterpret_cast(&groupLabel)); } void RenderPassEncoder::SetBindGroup(uint32_t groupIndex, BindGroup const& group, size_t dynamicOffsetCount, uint32_t const * dynamicOffsets) const { - wgpuRenderPassEncoderSetBindGroup(Get(), groupIndex, group.Get(), dynamicOffsetCount, reinterpret_cast(dynamicOffsets)); + wgpuRenderPassEncoderSetBindGroup(Get(), groupIndex, group.Get(), dynamicOffsetCount, reinterpret_cast(dynamicOffsets)); } void RenderPassEncoder::SetBlendConstant(Color const * color) const { - wgpuRenderPassEncoderSetBlendConstant(Get(), reinterpret_cast(color)); + wgpuRenderPassEncoderSetBlendConstant(Get(), reinterpret_cast(color)); } void RenderPassEncoder::SetIndexBuffer(Buffer const& buffer, IndexFormat format, uint64_t offset, uint64_t size) const { wgpuRenderPassEncoderSetIndexBuffer(Get(), buffer.Get(), static_cast(format), offset, size); @@ -5492,18 +5635,19 @@ static_assert(alignof(ShaderModule) == alignof(WGPUShaderModule), "alignof misma // Surface implementation void Surface::Configure(SurfaceConfiguration const * config) const { - wgpuSurfaceConfigure(Get(), reinterpret_cast(config)); + wgpuSurfaceConfigure(Get(), reinterpret_cast(config)); } ConvertibleStatus Surface::GetCapabilities(Adapter const& adapter, SurfaceCapabilities * capabilities) const { *capabilities = SurfaceCapabilities(); - auto result = wgpuSurfaceGetCapabilities(Get(), adapter.Get(), reinterpret_cast(capabilities)); + auto result = wgpuSurfaceGetCapabilities(Get(), adapter.Get(), reinterpret_cast(capabilities)); return static_cast(result); } void Surface::GetCurrentTexture(SurfaceTexture * surfaceTexture) const { - wgpuSurfaceGetCurrentTexture(Get(), reinterpret_cast(surfaceTexture)); + wgpuSurfaceGetCurrentTexture(Get(), reinterpret_cast(surfaceTexture)); } -void Surface::Present() const { - wgpuSurfacePresent(Get()); +ConvertibleStatus Surface::Present() const { + auto result = wgpuSurfacePresent(Get()); + return static_cast(result); } void Surface::SetLabel(StringView label) const { wgpuSurfaceSetLabel(Get(), *reinterpret_cast(&label)); @@ -5529,7 +5673,7 @@ static_assert(alignof(Surface) == alignof(WGPUSurface), "alignof mismatch for Su // Texture implementation TextureView Texture::CreateView(TextureViewDescriptor const * descriptor) const { - auto result = wgpuTextureCreateView(Get(), reinterpret_cast(descriptor)); + auto result = wgpuTextureCreateView(Get(), reinterpret_cast(descriptor)); return TextureView::Acquire(result); } void Texture::Destroy() const { @@ -5607,25 +5751,23 @@ static_assert(alignof(TextureView) == alignof(WGPUTextureView), "alignof mismatc -// RenderPassDescriptorMaxDrawCount is deprecated. -// Use RenderPassMaxDrawCount instead. -using RenderPassDescriptorMaxDrawCount = RenderPassMaxDrawCount; -// ShaderModuleSPIRVDescriptor is deprecated. -// Use ShaderSourceSPIRV instead. -using ShaderModuleSPIRVDescriptor = ShaderSourceSPIRV; -// ShaderModuleWGSLDescriptor is deprecated. -// Use ShaderSourceWGSL instead. -using ShaderModuleWGSLDescriptor = ShaderSourceWGSL; // Free Functions static inline Instance CreateInstance(InstanceDescriptor const * descriptor = nullptr) { - auto result = wgpuCreateInstance(reinterpret_cast(descriptor)); + auto result = wgpuCreateInstance(reinterpret_cast(descriptor)); return Instance::Acquire(result); } -static inline Status GetInstanceCapabilities(InstanceCapabilities * capabilities) { - auto result = wgpuGetInstanceCapabilities(reinterpret_cast(capabilities)); +static inline void GetInstanceFeatures(SupportedInstanceFeatures * features) { + wgpuGetInstanceFeatures(reinterpret_cast(features)); +} +static inline Status GetInstanceLimits(InstanceLimits * limits) { + auto result = wgpuGetInstanceLimits(reinterpret_cast(limits)); return static_cast(result); } +static inline Bool HasInstanceFeature(InstanceFeatureName feature) { + auto result = wgpuHasInstanceFeature(static_cast(feature)); + return result; +} static inline Proc GetProcAddress(StringView procName) { auto result = wgpuGetProcAddress(*reinterpret_cast(&procName)); return reinterpret_cast(result); @@ -5634,6 +5776,7 @@ static inline Proc GetProcAddress(StringView procName) { } // namespace wgpu namespace wgpu { + template<> struct IsWGPUBitmask { static constexpr bool enable = true; @@ -5659,6 +5802,14 @@ struct IsWGPUBitmask { static constexpr bool enable = true; }; + +inline bool operator==(const TextureComponentSwizzle& s1, const TextureComponentSwizzle& s2) { + return s1.r == s2.r && s1.g == s2.g && s1.b == s2.b && s1.a == s2.a; +} +inline bool operator!=(const TextureComponentSwizzle& s1, const TextureComponentSwizzle& s2) { + return !(s1 == s2); +} + } // namespace wgpu namespace std { diff --git a/defold-rive/include/rive/renderer/webgpu/wagyu-port/new/include/webgpu/webgpu_cpp_chained_struct.h b/defold-rive/include/rive/renderer/webgpu/wagyu-port/include/webgpu/webgpu_cpp_chained_struct.h similarity index 100% rename from defold-rive/include/rive/renderer/webgpu/wagyu-port/new/include/webgpu/webgpu_cpp_chained_struct.h rename to defold-rive/include/rive/renderer/webgpu/wagyu-port/include/webgpu/webgpu_cpp_chained_struct.h diff --git a/defold-rive/include/rive/renderer/webgpu/wagyu-port/new/include/webgpu/webgpu_enum_class_bitmasks.h b/defold-rive/include/rive/renderer/webgpu/wagyu-port/include/webgpu/webgpu_enum_class_bitmasks.h similarity index 100% rename from defold-rive/include/rive/renderer/webgpu/wagyu-port/new/include/webgpu/webgpu_enum_class_bitmasks.h rename to defold-rive/include/rive/renderer/webgpu/wagyu-port/include/webgpu/webgpu_enum_class_bitmasks.h diff --git a/defold-rive/include/rive/renderer/webgpu/wagyu-port/new/include/webgpu/webgpu_wagyu.h b/defold-rive/include/rive/renderer/webgpu/wagyu-port/include/webgpu/webgpu_wagyu.h similarity index 71% rename from defold-rive/include/rive/renderer/webgpu/wagyu-port/new/include/webgpu/webgpu_wagyu.h rename to defold-rive/include/rive/renderer/webgpu/wagyu-port/include/webgpu/webgpu_wagyu.h index 6edae5a1..c3e55974 100644 --- a/defold-rive/include/rive/renderer/webgpu/wagyu-port/new/include/webgpu/webgpu_wagyu.h +++ b/defold-rive/include/rive/renderer/webgpu/wagyu-port/include/webgpu/webgpu_wagyu.h @@ -17,20 +17,8 @@ #define WGPU_WAGYU_STRLEN SIZE_MAX #define WGPU_WAGYU_PIXEL_LOCAL_STORAGE_SIZE_UNDEFINED UINT32_MAX -#if defined(USE_WGPU_WAGYU_NAMESPACE) || defined(__cppcheck) -namespace wagyu2 { -#endif - -typedef struct WGPUWagyuRelaxedComplianceImpl *WGPUWagyuRelaxedCompliance WGPU_OBJECT_ATTRIBUTE; typedef struct WGPUWagyuExternalTextureImpl *WGPUWagyuExternalTexture WGPU_OBJECT_ATTRIBUTE; -typedef enum WGPUWagyuDeviceFlushStatus -{ - WGPUWagyuDeviceFlushStatus_Success = 0x00000000, - WGPUWagyuDeviceFlushStatus_Error = 0x00000001, - WGPUWagyuDeviceFlushStatus_Force32 = 0x7FFFFFFF -} WGPUWagyuDeviceFlushStatus WGPU_ENUM_ATTRIBUTE; - // These values extend the WGPUSType enum set from webgpu.h typedef enum WGPUSType_Wagyu { @@ -51,6 +39,22 @@ typedef enum WGPUSType_Wagyu WGPUSType_WagyuForce32 = 0x7FFFFFFF } WGPUSType_Wagyu WGPU_ENUM_ATTRIBUTE; +typedef enum WGPUWagyuDeviceFlushStatus +{ + WGPUWagyuDeviceFlushStatus_Success = 0x00000000, + WGPUWagyuDeviceFlushStatus_Error = 0x00000001, + WGPUWagyuDeviceFlushStatus_Force32 = 0x7FFFFFFF +} WGPUWagyuDeviceFlushStatus WGPU_ENUM_ATTRIBUTE; + +typedef enum WGPUWagyuDevicePipelineBinaryCacheError +{ + WGPUWagyuDevicePipelineBinaryCacheError_Version = 0x00000000, + WGPUWagyuDevicePipelineBinaryCacheError_Corrupt = 0x00000001, + WGPUWagyuDevicePipelineBinaryCacheError_Link = 0x00000002, + WGPUWagyuDevicePipelineBinaryCacheError_Create = 0x00000003, + WGPUWagyuDevicePipelineBinaryCacheError_Force32 = 0x7FFFFFFF +} WGPUWagyuDevicePipelineBinaryCacheError WGPU_ENUM_ATTRIBUTE; + typedef enum WGPUWagyuShaderLanguage { WGPUWagyuShaderLanguage_Detect = 0x00000000, @@ -78,7 +82,17 @@ static const WGPUWagyuFragmentStateFeaturesFlags WGPUWagyuFragmentStateFeaturesF static const WGPUTextureUsage WGPUTextureUsage_WagyuInputAttachment = (WGPUTextureUsage)(0x0000000040000000); static const WGPUTextureUsage WGPUTextureUsage_WagyuTransientAttachment = (WGPUTextureUsage)(0x0000000020000000); +// Forward declarations for callbacks +struct WGPUWagyuDevicePipelineBinaryCacheStatistics; +struct WGPUWagyuDevicePipelineBinaryEvent; +struct WGPUWagyuShaderEntryPointArray; + typedef void (*WGPUWagyuDeviceFlushCallback)(WGPUDevice device, WGPUWagyuDeviceFlushStatus status, void *userdata1, void *userdata2) WGPU_FUNCTION_ATTRIBUTE; +typedef void (*WGPUWagyuExecuteCallback)(void *userdata1, void *userdata2) WGPU_FUNCTION_ATTRIBUTE; +typedef void (*WGPUWagyuPipelineBinaryCacheStatisticsCallback)(WGPUDevice device, WGPUWagyuDeviceFlushStatus status, const struct WGPUWagyuDevicePipelineBinaryCacheStatistics *statistics, void *userdata1, void *userdata2) WGPU_FUNCTION_ATTRIBUTE; +typedef void (*WGPUWagyuPipelineBinaryCallback)(WGPUDevice device, const struct WGPUWagyuDevicePipelineBinaryEvent *event, void *userdata1, void *userdata2) WGPU_FUNCTION_ATTRIBUTE; +typedef void (*WGPUWagyuPipelineBinaryErrorCallback)(WGPUDevice device, WGPUStringView reason, WGPUStringView message, void *userdata1, void *userdata2) WGPU_FUNCTION_ATTRIBUTE; +typedef void (*WGPUWagyuShaderModuleEntryPointsCallback)(WGPUShaderModule shaderModule, WGPUWagyuDeviceFlushStatus status, const struct WGPUWagyuShaderEntryPointArray *entryPoints, void *userdata1, void *userdata2) WGPU_FUNCTION_ATTRIBUTE; typedef struct WGPUWagyuNrdpVersion { @@ -129,15 +143,49 @@ typedef struct WGPUWagyuComputePipelineDescriptor #define WGPU_WAGYU_COMPUTE_PIPELINE_DESCRIPTOR_INIT \ WGPU_WAGYU_MAKE_INIT_STRUCT(WGPUWagyuComputePipelineDescriptor, { /*.chain*/ WGPU_WAGYU_CHAIN_INIT(WGPUSType_WagyuComputePipelineDescriptor) _wgpu_COMMA /*.cacheKey*/ WGPU_STRING_VIEW_INIT _wgpu_COMMA }) +typedef struct WGPUWagyuOrigin2D +{ + uint32_t x; + uint32_t y; +} WGPUWagyuOrigin2D WGPU_STRUCTURE_ATTRIBUTE; + +#define WGPU_WAGYU_ORIGIN_2D_INIT \ + WGPU_WAGYU_MAKE_INIT_STRUCT(WGPUWagyuOrigin2D, { /* .x */ 0 _wgpu_COMMA /* .y */ 0 _wgpu_COMMA }) + +typedef struct WGPUWagyuCopyExternalImageSourceInfo +{ + WGPUStringView source; + WGPUWagyuOrigin2D origin; + WGPUBool flipY; +} WGPUWagyuCopyExternalImageSourceInfo WGPU_STRUCTURE_ATTRIBUTE; + +#define WGPU_COPY_EXTERNAL_IMAGE_SOURCE_INFO_INIT \ + WGPU_WAGYU_MAKE_INIT_STRUCT(WGPUWagyuCopyExternalImageSourceInfo, { /* .source */ WGPU_STRING_VIEW_INIT _wgpu_COMMA /* .origin */ WGPU_WAGYU_ORIGIN_2D_INIT _wgpu_COMMA /* .flipY */ WGPU_FALSE _wgpu_COMMA }) + +typedef struct WGPUWagyuCopyExternalImageDestInfo +{ + WGPUTexture texture; + uint32_t mipLevel; + WGPUOrigin3D origin; + WGPUTextureAspect aspect; + WGPUPredefinedColorSpace colorSpace; + WGPUBool premultipliedAlpha; +} WGPUWagyuCopyExternalImageDestInfo WGPU_STRUCTURE_ATTRIBUTE; + +#define WGPU_COPY_EXTERNAL_IMAGE_DEST_INFO_INIT \ + WGPU_WAGYU_MAKE_INIT_STRUCT(WGPUWagyuCopyExternalImageDestInfo, { /* .texture */ NULL _wgpu_COMMA /* .mipLevel */ 0 _wgpu_COMMA /* .origin */ WGPU_ORIGIN_3D_INIT _wgpu_COMMA /* .aspect */ WGPUTextureAspect_All _wgpu_COMMA /* .colorSpace */ WGPUPredefinedColorSpace_SRGB _wgpu_COMMA /* .premultipliedAlpha */ WGPU_FALSE _wgpu_COMMA }) + typedef struct WGPUWagyuDeviceDescriptor { WGPUChainedStruct chain; - WGPUBool dataBufferNeedsDetach; - WGPUBool wantsIndirectRendering; + WGPUOptionalBool dataBufferNeedsDetach; + WGPUOptionalBool wantsIndirectRendering; + WGPUOptionalBool wantsBufferClear; + WGPUOptionalBool wantsTextureClear; } WGPUWagyuDeviceDescriptor WGPU_STRUCTURE_ATTRIBUTE; #define WGPU_WAGYU_DEVICE_DESCRIPTOR_INIT \ - WGPU_WAGYU_MAKE_INIT_STRUCT(WGPUWagyuDeviceDescriptor, { /*.chain*/ WGPU_WAGYU_CHAIN_INIT(WGPUSType_WagyuDeviceDescriptor) _wgpu_COMMA /*.dataBufferNeedsDetach*/ WGPU_TRUE _wgpu_COMMA /*.wantsIndirectRendering*/ WGPU_FALSE _wgpu_COMMA }) + WGPU_WAGYU_MAKE_INIT_STRUCT(WGPUWagyuDeviceDescriptor, { /*.chain*/ WGPU_WAGYU_CHAIN_INIT(WGPUSType_WagyuDeviceDescriptor) _wgpu_COMMA /*.dataBufferNeedsDetach*/ WGPUOptionalBool_Undefined _wgpu_COMMA /*.wantsIndirectRendering*/ WGPUOptionalBool_Undefined _wgpu_COMMA /*.wantsBufferClear*/ WGPUOptionalBool_Undefined _wgpu_COMMA /*.wantsTextureClear*/ WGPUOptionalBool_Undefined _wgpu_COMMA }) typedef struct WGPUWagyuDeviceFlushCallbackInfo { @@ -148,9 +196,21 @@ typedef struct WGPUWagyuDeviceFlushCallbackInfo void *userdata2; } WGPUWagyuDeviceFlushCallbackInfo WGPU_STRUCTURE_ATTRIBUTE; -#define WGPU_WAGYU_DEVICE_FLUSHCALLBACK_INFO_INIT \ +#define WGPU_WAGYU_DEVICE_FLUSH_CALLBACK_INFO_INIT \ WGPU_WAGYU_MAKE_INIT_STRUCT(WGPUWagyuDeviceFlushCallbackInfo, { /*.nextInChain = */ NULL _wgpu_COMMA /*.mode = */ WGPUCallbackMode_AllowSpontaneous _wgpu_COMMA /*.callback = */ NULL _wgpu_COMMA /*.userdata1 = */ NULL _wgpu_COMMA /*.userdata2 = */ NULL _wgpu_COMMA }) +typedef struct WGPUWagyuExecuteCallbackInfo +{ + WGPUChainedStruct *nextInChain; + WGPUCallbackMode mode; + WGPUWagyuExecuteCallback callback; + void *userdata1; + void *userdata2; +} WGPUWagyuExecuteCallbackInfo WGPU_STRUCTURE_ATTRIBUTE; + +#define WGPU_WAGYU_EXECUTE_CALLBACK_INFO_INIT \ + WGPU_WAGYU_MAKE_INIT_STRUCT(WGPUWagyuExecuteCallbackInfo, { /*.nextInChain = */ NULL _wgpu_COMMA /*.mode = */ WGPUCallbackMode_AllowSpontaneous _wgpu_COMMA /*.callback = */ NULL _wgpu_COMMA /*.userdata1 = */ NULL _wgpu_COMMA /*.userdata2 = */ NULL _wgpu_COMMA }) + typedef struct WGPUWagyuDevicePipelineBinary { size_t binarySize; @@ -179,7 +239,32 @@ typedef struct WGPUWagyuDevicePipelineBinaryCacheKey } WGPUWagyuDevicePipelineBinaryCacheKey WGPU_STRUCTURE_ATTRIBUTE; #define WGPU_WAGYU_DEVICE_PIPELINE_BINARY_CACHE_KEY_INIT \ - WGPU_WAGYU_MAKE_INIT_STRUCT(WGPUWagyuDevicePipelineBinaryCacheKey, { /*.cacheKey*/ WGPU_STRING_VIEW_INIT _wgpu_COMMA /*.blobKeysLength*/ 0 _wgpu_COMMA }) + WGPU_WAGYU_MAKE_INIT_STRUCT(WGPUWagyuDevicePipelineBinaryCacheKey, { /*.cacheKey*/ WGPU_STRING_VIEW_INIT _wgpu_COMMA /*.blobKeysLength*/ 0 _wgpu_COMMA /*.blobKeys*/ NULL _wgpu_COMMA }) + +typedef struct WGPUWagyuDevicePipelineBinaryCacheStatistics +{ + uint32_t hits; + uint32_t misses; + size_t entryCount; + WGPUStringView *entries; + size_t errorCount; + WGPUWagyuDevicePipelineBinaryCacheError *errors; +} WGPUWagyuDevicePipelineBinaryCacheStatistics WGPU_STRUCTURE_ATTRIBUTE; + +#define WGPU_WAGYU_DEVICE_PIPELINE_BINARY_CACHE_STATISTICS_INIT \ + WGPU_WAGYU_MAKE_INIT_STRUCT(WGPUWagyuDevicePipelineBinaryCacheStatistics, { /*.hits*/ 0 _wgpu_COMMA /*.misses*/ 0 _wgpu_COMMA /*.entryCount*/ 0 _wgpu_COMMA /*.entries*/ NULL _wgpu_COMMA /*.errorCount*/ 0 _wgpu_COMMA /*.errors*/ NULL _wgpu_COMMA }) + +typedef struct WGPUWagyuPipelineBinaryCacheStatisticsCallbackInfo +{ + WGPUChainedStruct *nextInChain; + WGPUCallbackMode mode; + WGPUWagyuPipelineBinaryCacheStatisticsCallback callback; + void *userdata1; + void *userdata2; +} WGPUWagyuPipelineBinaryCacheStatisticsCallbackInfo WGPU_STRUCTURE_ATTRIBUTE; + +#define WGPU_WAGYU_PIPELINE_BINARY_CACHE_STATISTICS_CALLBACK_INFO_INIT \ + WGPU_WAGYU_MAKE_INIT_STRUCT(WGPUWagyuPipelineBinaryCacheStatisticsCallbackInfo, { /*.nextInChain = */ NULL _wgpu_COMMA /*.mode = */ WGPUCallbackMode_AllowSpontaneous _wgpu_COMMA /*.callback = */ NULL _wgpu_COMMA /*.userdata1 = */ NULL _wgpu_COMMA /*.userdata2 = */ NULL _wgpu_COMMA }) typedef struct WGPUWagyuDevicePipelineBinaryData { @@ -192,6 +277,17 @@ typedef struct WGPUWagyuDevicePipelineBinaryData #define WGPU_WAGYU_DEVICE_PIPELINE_BINARY_DATA_INIT \ WGPU_WAGYU_MAKE_INIT_STRUCT(WGPUWagyuDevicePipelineBinaryData, { /*.binariesLength*/ 0 _wgpu_COMMA /*.binaries*/ NULL _wgpu_COMMA /*.cacheKeysLength*/ 0 _wgpu_COMMA /*.cacheKeys*/ NULL _wgpu_COMMA }) +typedef struct WGPUWagyuDevicePipelineBinaryEvent +{ + WGPUStringView cacheKey; + WGPUStringView pipelineLabel; + size_t binariesLength; + const WGPUWagyuDevicePipelineBinary *binaries; +} WGPUWagyuDevicePipelineBinaryEvent WGPU_STRUCTURE_ATTRIBUTE; + +#define WGPU_WAGYU_DEVICE_PIPELINE_BINARY_EVENT_INIT \ + WGPU_WAGYU_MAKE_INIT_STRUCT(WGPUWagyuDevicePipelineBinaryEvent, { /*.cacheKey*/ WGPU_STRING_VIEW_INIT _wgpu_COMMA /*.pipelineLabel*/ WGPU_STRING_VIEW_INIT _wgpu_COMMA /*.binariesLength*/ 0 _wgpu_COMMA /*.binaries*/ NULL _wgpu_COMMA }) + typedef struct WGPUWagyuExternalTextureDescriptor { const WGPUChainedStruct *nextInChain; @@ -203,6 +299,18 @@ typedef struct WGPUWagyuExternalTextureDescriptor #define WGPU_WAGYU_EXTERNAL_TEXTURE_DESCRIPTOR_INIT \ WGPU_WAGYU_MAKE_INIT_STRUCT(WGPUWagyuExternalTextureDescriptor, { /*nextInChain = */ NULL _wgpu_COMMA /*label = */ WGPU_STRING_VIEW_INIT _wgpu_COMMA /*source = */ WGPU_STRING_VIEW_INIT _wgpu_COMMA /*colorSpace = */ WGPUPredefinedColorSpace_SRGB _wgpu_COMMA }) +typedef struct WGPUWagyuExternalTextureInfo +{ + uint32_t visibleWidth; + uint32_t visibleHeight; + uint32_t textureWidth; + uint32_t textureHeight; + int64_t pts; +} WGPUWagyuExternalTextureInfo WGPU_STRUCTURE_ATTRIBUTE; + +#define WGPU_WAGYU_EXTERNAL_TEXTURE_INFO_INIT \ + WGPU_WAGYU_MAKE_INIT_STRUCT(WGPUWagyuExternalTextureInfo, { /*.visibleWidth*/ 0 _wgpu_COMMA /*.visibleHeight*/ 0 _wgpu_COMMA /*.textureWidth*/ 0 _wgpu_COMMA /*.textureHeight*/ 0 _wgpu_COMMA /*.pts*/ 0 _wgpu_COMMA }) + typedef struct WGPUWagyuExternalTextureBindingEntry { WGPUChainedStruct chain; @@ -251,6 +359,30 @@ typedef struct WGPUWagyuInputTextureBindingLayout #define WGPU_WAGYU_INPUT_TEXTURE_BINDING_LAYOUT_INIT \ WGPU_WAGYU_MAKE_INIT_STRUCT(WGPUWagyuInputTextureBindingLayout, { /*.chain*/ WGPU_WAGYU_CHAIN_INIT(WGPUSType_WagyuInputTextureBindingLayout) _wgpu_COMMA /*.viewDimension*/ WGPUTextureViewDimension_2D _wgpu_COMMA }) +typedef struct WGPUWagyuPipelineBinaryCallbackInfo +{ + WGPUChainedStruct *nextInChain; + WGPUCallbackMode mode; + WGPUWagyuPipelineBinaryCallback callback; + void *userdata1; + void *userdata2; +} WGPUWagyuPipelineBinaryCallbackInfo WGPU_STRUCTURE_ATTRIBUTE; + +#define WGPU_WAGYU_PIPELINE_BINARY_CALLBACK_INFO_INIT \ + WGPU_WAGYU_MAKE_INIT_STRUCT(WGPUWagyuPipelineBinaryCallbackInfo, { /*.nextInChain = */ NULL _wgpu_COMMA /*.mode = */ WGPUCallbackMode_AllowSpontaneous _wgpu_COMMA /*.callback = */ NULL _wgpu_COMMA /*.userdata1 = */ NULL _wgpu_COMMA /*.userdata2 = */ NULL _wgpu_COMMA }) + +typedef struct WGPUWagyuPipelineBinaryErrorCallbackInfo +{ + WGPUChainedStruct *nextInChain; + WGPUCallbackMode mode; + WGPUWagyuPipelineBinaryErrorCallback callback; + void *userdata1; + void *userdata2; +} WGPUWagyuPipelineBinaryErrorCallbackInfo WGPU_STRUCTURE_ATTRIBUTE; + +#define WGPU_WAGYU_PIPELINE_BINARY_ERROR_CALLBACK_INFO_INIT \ + WGPU_WAGYU_MAKE_INIT_STRUCT(WGPUWagyuPipelineBinaryErrorCallbackInfo, { /*.nextInChain = */ NULL _wgpu_COMMA /*.mode = */ WGPUCallbackMode_AllowSpontaneous _wgpu_COMMA /*.callback = */ NULL _wgpu_COMMA /*.userdata1 = */ NULL _wgpu_COMMA /*.userdata2 = */ NULL _wgpu_COMMA }) + typedef struct WGPUWagyuRect { int32_t x; @@ -294,6 +426,18 @@ typedef struct WGPUWagyuRenderPipelineDescriptor #define WGPU_WAGYU_RENDER_PIPELINE_DESCRIPTOR_INIT \ WGPU_WAGYU_MAKE_INIT_STRUCT(WGPUWagyuRenderPipelineDescriptor, { /* .chain */ WGPU_WAGYU_CHAIN_INIT(WGPUSType_WagyuRenderPipelineDescriptor) _wgpu_COMMA /* .cacheKey */ WGPU_STRING_VIEW_INIT _wgpu_COMMA }) +typedef struct WGPUWagyuShaderModuleEntryPointsCallbackInfo +{ + WGPUChainedStruct *nextInChain; + WGPUCallbackMode mode; + WGPUWagyuShaderModuleEntryPointsCallback callback; + void *userdata1; + void *userdata2; +} WGPUWagyuShaderModuleEntryPointsCallbackInfo WGPU_STRUCTURE_ATTRIBUTE; + +#define WGPU_WAGYU_SHADER_MODULE_ENTRY_POINTS_CALLBACK_INFO_INIT \ + WGPU_WAGYU_MAKE_INIT_STRUCT(WGPUWagyuShaderModuleEntryPointsCallbackInfo, { /*.nextInChain = */ NULL _wgpu_COMMA /*.mode = */ WGPUCallbackMode_AllowSpontaneous _wgpu_COMMA /*.callback = */ NULL _wgpu_COMMA /*.userdata1 = */ NULL _wgpu_COMMA /*.userdata2 = */ NULL _wgpu_COMMA }) + typedef struct WGPUWagyuShaderReflectionStructMember { WGPUStringView name; @@ -382,17 +526,6 @@ typedef struct WGPUWagyuShaderEntryPointArray #define WGPU_WAGYU_SHADER_ENTRY_POINT_ARRAY_INIT \ WGPU_WAGYU_MAKE_INIT_STRUCT(WGPUWagyuShaderEntryPointArray, { /* .entryPointCount */ 0 _wgpu_COMMA /* .entryPoints */ NULL _wgpu_COMMA }) -typedef struct WGPUWagyuRenderPassEncoderClearPixelLocalStorage -{ - uint32_t offset; - size_t valueCount; - WGPU_NULLABLE uint32_t *values; - uint32_t size; -} WGPUWagyuRenderPassEncoderClearPixelLocalStorage WGPU_STRUCTURE_ATTRIBUTE; - -#define WGPU_WAGYU_RENDER_PASS_ENCODER_CLEAR_PIXEL_LOCAL_STORAGE_INIT \ - WGPU_WAGYU_MAKE_INIT_STRUCT(WGPUWagyuRenderPassEncoderClearPixelLocalStorage, { /* .offset */ 0 _wgpu_COMMA /* .valueCount */ 0 _wgpu_COMMA /* .values */ NULL _wgpu_COMMA /* .size */ WGPU_WAGYU_PIXEL_LOCAL_STORAGE_SIZE_UNDEFINED _wgpu_COMMA }) - typedef struct WGPUWagyuShaderModuleCompilationHint { WGPUChainedStruct *nextInChain; @@ -432,10 +565,12 @@ typedef struct WGPUWagyuSurfaceConfiguration { WGPUChainedStruct chain; int32_t *indirectRenderTargets; + WGPUPredefinedColorSpace colorSpace; + WGPUToneMappingMode toneMappingMode; } WGPUWagyuSurfaceConfiguration WGPU_STRUCTURE_ATTRIBUTE; #define WGPU_WAGYU_SURFACE_CONFIGURATION_INIT \ - WGPU_WAGYU_MAKE_INIT_STRUCT(WGPUWagyuSurfaceConfiguration, { /*.chain=*/WGPU_WAGYU_CHAIN_INIT(WGPUSType_WagyuSurfaceConfiguration) _wgpu_COMMA /*.indirectRenderTargets*/ NULL _wgpu_COMMA }) + WGPU_WAGYU_MAKE_INIT_STRUCT(WGPUWagyuSurfaceConfiguration, { /*.chain=*/WGPU_WAGYU_CHAIN_INIT(WGPUSType_WagyuSurfaceConfiguration) _wgpu_COMMA /*.indirectRenderTargets*/ NULL _wgpu_COMMA /*.colorSpace*/ WGPUPredefinedColorSpace_SRGB _wgpu_COMMA /*.toneMappingMode*/ WGPUToneMappingMode_Standard _wgpu_COMMA }) typedef struct WGPUWagyuTextureDescriptor { @@ -455,7 +590,7 @@ typedef struct WGPUWagyuWGSLFeatureTypeArray #define WGPU_WAGYU_WGSL_FEATURE_TYPE_ARRAY_INIT \ WGPU_WAGYU_MAKE_INIT_STRUCT(WGPUWagyuWGSLFeatureTypeArray, { /* .featureCount */ 0 _wgpu_COMMA /* .features */ NULL _wgpu_COMMA }) -#if defined(__cplusplus) && !defined(USE_WGPU_WAGYU_NAMESPACE) && !defined(__cppcheck) +#if defined(__cplusplus) && !defined(__cppcheck) extern "C" { #endif @@ -466,47 +601,49 @@ WGPU_EXPORT void wgpuWagyuAdapterGetName(WGPUAdapter adapter, WGPUStringView *na WGPU_EXPORT WGPUDevice wgpuWagyuAdapterRequestDeviceSync(WGPUAdapter adapter, WGPU_NULLABLE const WGPUDeviceDescriptor *options) WGPU_FUNCTION_ATTRIBUTE; WGPU_EXPORT void wgpuWagyuCommandEncoderBlit(WGPUCommandEncoder commandEncoder, const WGPUTexelCopyTextureInfo *source, const WGPUExtent3D *sourceExtent, const WGPUTexelCopyTextureInfo *destination, const WGPUExtent3D *destinationExtent, WGPUFilterMode filter) WGPU_FUNCTION_ATTRIBUTE; +WGPU_EXPORT void wgpuWagyuCommandEncoderExecuteCallback(WGPUCommandEncoder commandEncoder, WGPUWagyuExecuteCallbackInfo callbackInfo) WGPU_FUNCTION_ATTRIBUTE; WGPU_EXPORT void wgpuWagyuCommandEncoderGenerateMipmap(WGPUCommandEncoder commandEncoder, WGPUTexture texture) WGPU_FUNCTION_ATTRIBUTE; +WGPU_EXPORT void wgpuWagyuComputePassEncoderExecuteCallback(WGPUComputePassEncoder computePassEncoder, WGPUWagyuExecuteCallbackInfo callbackInfo) WGPU_FUNCTION_ATTRIBUTE; + WGPU_EXPORT void wgpuWagyuDeviceClearPipelineBinaryCache(WGPUDevice device) WGPU_FUNCTION_ATTRIBUTE; WGPU_EXPORT void wgpuWagyuDeviceEnableImaginationWorkarounds(WGPUDevice device, WGPUBool enable) WGPU_FUNCTION_ATTRIBUTE; WGPU_EXPORT void wgpuWagyuDeviceGetExtensions(WGPUDevice device, WGPUWagyuStringArray *extensions) WGPU_FUNCTION_ATTRIBUTE; WGPU_EXPORT WGPUFuture wgpuWagyuDeviceFlush(WGPUDevice device, WGPUWagyuDeviceFlushCallbackInfo callbackInfo) WGPU_FUNCTION_ATTRIBUTE; WGPU_EXPORT WGPUWagyuExternalTexture wgpuWagyuDeviceImportExternalTexture(WGPUDevice device, const WGPUWagyuExternalTextureDescriptor *descriptor) WGPU_FUNCTION_ATTRIBUTE; WGPU_EXPORT void wgpuWagyuDeviceIntrospectShaderCode(WGPUDevice device, WGPUShaderStage stages, const WGPUShaderModuleDescriptor *descriptor, WGPUWagyuShaderEntryPointArray *entryPoints) WGPU_FUNCTION_ATTRIBUTE; +WGPU_EXPORT WGPUFuture wgpuWagyuDevicePipelineBinaryCacheStatistics(WGPUDevice device, WGPUWagyuPipelineBinaryCacheStatisticsCallbackInfo callbackInfo) WGPU_FUNCTION_ATTRIBUTE; WGPU_EXPORT void wgpuWagyuDevicePopulatePipelineBinaryCache(WGPUDevice device, const WGPUWagyuDevicePipelineBinaryData *data) WGPU_FUNCTION_ATTRIBUTE; +WGPU_EXPORT void wgpuWagyuDeviceSetPipelineBinaryCallback(WGPUDevice device, WGPUWagyuPipelineBinaryCallbackInfo callbackInfo) WGPU_FUNCTION_ATTRIBUTE; +WGPU_EXPORT void wgpuWagyuDeviceSetPipelineBinaryErrorCallback(WGPUDevice device, WGPUWagyuPipelineBinaryErrorCallbackInfo callbackInfo) WGPU_FUNCTION_ATTRIBUTE; WGPU_EXPORT void wgpuWagyuExternalTextureAddRef(WGPUWagyuExternalTexture externalTexture) WGPU_FUNCTION_ATTRIBUTE; +WGPU_EXPORT void wgpuWagyuExternalTextureGetInfo(WGPUWagyuExternalTexture externalTexture, WGPUWagyuExternalTextureInfo *info) WGPU_FUNCTION_ATTRIBUTE; WGPU_EXPORT void wgpuWagyuExternalTextureRelease(WGPUWagyuExternalTexture externalTexture) WGPU_FUNCTION_ATTRIBUTE; WGPU_EXPORT void wgpuWagyuExternalTextureSetLabel(WGPUWagyuExternalTexture externalTexture, WGPUStringView label) WGPU_FUNCTION_ATTRIBUTE; WGPU_EXPORT void wgpuWagyuInstanceEnableImaginationWorkarounds(WGPUInstance instance, WGPUBool enable) WGPU_FUNCTION_ATTRIBUTE; WGPU_EXPORT uint32_t wgpuWagyuInstanceGetApiVersion(WGPUInstance instance) WGPU_FUNCTION_ATTRIBUTE; WGPU_EXPORT WGPUBackendType wgpuWagyuInstanceGetBackend(WGPUInstance instance) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuWagyuInstanceGetExposeWGSLFeatures(WGPUInstance instance, WGPUWagyuWGSLFeatureTypeArray *wgslFeatures) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT WGPUWagyuRelaxedCompliance wgpuWagyuInstanceGetRelaxedCompliance(WGPUInstance instance) WGPU_FUNCTION_ATTRIBUTE; +WGPU_EXPORT void wgpuWagyuInstanceGetExposedWgslFeatures(WGPUInstance instance, WGPUWagyuWGSLFeatureTypeArray *wgslFeatures) WGPU_FUNCTION_ATTRIBUTE; WGPU_EXPORT WGPUTextureFormat wgpuWagyuInstanceGetScreenDirectFormat(WGPUInstance instance) WGPU_FUNCTION_ATTRIBUTE; WGPU_EXPORT WGPUTextureFormat wgpuWagyuInstanceGetScreenIndirectFormat(WGPUInstance instance) WGPU_FUNCTION_ATTRIBUTE; WGPU_EXPORT WGPUBool wgpuWagyuInstanceGetSync(WGPUInstance instance) WGPU_FUNCTION_ATTRIBUTE; WGPU_EXPORT WGPUAdapter wgpuWagyuInstanceRequestAdapterSync(WGPUInstance instance, WGPU_NULLABLE const WGPURequestAdapterOptions *options) WGPU_FUNCTION_ATTRIBUTE; WGPU_EXPORT void wgpuWagyuInstanceSetCommandBufferLimit(WGPUInstance instance, uint32_t limit) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuWagyuInstanceSetExposeWGSLFeatures(WGPUInstance instance, const WGPUWagyuWGSLFeatureTypeArray *wgslFeatures) WGPU_FUNCTION_ATTRIBUTE; +WGPU_EXPORT void wgpuWagyuInstanceSetExposedWgslFeatures(WGPUInstance instance, const WGPUWagyuWGSLFeatureTypeArray *wgslFeatures) WGPU_FUNCTION_ATTRIBUTE; WGPU_EXPORT void wgpuWagyuInstanceSetImmediate(WGPUInstance instance, WGPUBool enabled) WGPU_FUNCTION_ATTRIBUTE; WGPU_EXPORT void wgpuWagyuInstanceSetRunBarriersOnIncoherent(WGPUInstance instance, WGPUBool run) WGPU_FUNCTION_ATTRIBUTE; WGPU_EXPORT void wgpuWagyuInstanceSetStagingBufferCacheSize(WGPUInstance instance, uint32_t size) WGPU_FUNCTION_ATTRIBUTE; WGPU_EXPORT void wgpuWagyuInstanceSetSync(WGPUInstance instance, WGPUBool sync) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuWagyuRelaxedComplianceAddRef(WGPUWagyuRelaxedCompliance relaxedCompliance) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuWagyuRelaxedComplianceRelease(WGPUWagyuRelaxedCompliance relaxedCompliance) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT WGPUBool wgpuWagyuRelaxedComplianceGetBufferClear(WGPUWagyuRelaxedCompliance relaxedCompliance) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT WGPUBool wgpuWagyuRelaxedComplianceGetTextureClear(WGPUWagyuRelaxedCompliance relaxedCompliance) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuWagyuRelaxedComplianceSetAll(WGPUWagyuRelaxedCompliance relaxedCompliance, WGPUBool enable) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuWagyuRelaxedComplianceSetBufferClear(WGPUWagyuRelaxedCompliance relaxedCompliance, WGPUBool enable) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuWagyuRelaxedComplianceSetTextureClear(WGPUWagyuRelaxedCompliance relaxedCompliance, WGPUBool enable) WGPU_FUNCTION_ATTRIBUTE; +WGPU_EXPORT void wgpuWagyuQueueCopyExternalImageToTexture(WGPUQueue queue, const WGPUWagyuCopyExternalImageSourceInfo *source, const WGPUWagyuCopyExternalImageDestInfo *destination, const WGPUExtent3D *copySize) WGPU_FUNCTION_ATTRIBUTE; WGPU_EXPORT void wgpuWagyuRenderBundleEncoderClearColorAttachments(WGPURenderBundleEncoder renderBundleEncoder, const WGPUWagyuRect *rect, uint32_t baseAttachment, uint32_t numAttachments, const WGPUColor *color, uint32_t baseArrayLayer, uint32_t layerCount) WGPU_FUNCTION_ATTRIBUTE; WGPU_EXPORT void wgpuWagyuRenderBundleEncoderClearDepthAttachment(WGPURenderBundleEncoder renderBundleEncoder, const WGPUWagyuRect *rect, float depth, uint32_t baseArrayLayer, uint32_t layerCount) WGPU_FUNCTION_ATTRIBUTE; +WGPU_EXPORT void wgpuWagyuRenderBundleEncoderClearPixelLocalStorage(WGPURenderBundleEncoder renderBundleEncoder, uint32_t offset, uint32_t size, WGPU_NULLABLE const uint32_t *values) WGPU_FUNCTION_ATTRIBUTE; WGPU_EXPORT void wgpuWagyuRenderBundleEncoderClearStencilAttachment(WGPURenderBundleEncoder renderBundleEncoder, const WGPUWagyuRect *rect, uint32_t stencil, uint32_t baseArrayLayer, uint32_t layerCount) WGPU_FUNCTION_ATTRIBUTE; +WGPU_EXPORT void wgpuWagyuRenderBundleEncoderExecuteCallback(WGPURenderBundleEncoder renderBundleEncoder, WGPUWagyuExecuteCallbackInfo callbackInfo) WGPU_FUNCTION_ATTRIBUTE; WGPU_EXPORT void wgpuWagyuRenderBundleEncoderSetScissorRect(WGPURenderBundleEncoder renderBundleEncoder, uint32_t x, uint32_t y, uint32_t width, uint32_t height) WGPU_FUNCTION_ATTRIBUTE; WGPU_EXPORT void wgpuWagyuRenderBundleEncoderSetScissorRectIndirect(WGPURenderBundleEncoder renderBundleEncoder, uint64_t indirectOffset, const uint32_t *indirectBuffer, size_t indirectBufferCount) WGPU_FUNCTION_ATTRIBUTE; WGPU_EXPORT void wgpuWagyuRenderBundleEncoderSetViewport(WGPURenderBundleEncoder renderBundleEncoder, float x, float y, float width, float height, float minDepth, float maxDepth) WGPU_FUNCTION_ATTRIBUTE; @@ -516,15 +653,17 @@ WGPU_EXPORT void wgpuWagyuRenderBundleEncoderSetViewportWithoutDepthIndirect(WGP WGPU_EXPORT void wgpuWagyuRenderPassEncoderClearColorAttachments(WGPURenderPassEncoder renderPassEncoder, const WGPUWagyuRect *rect, uint32_t baseAttachment, uint32_t numAttachments, const WGPUColor *color, uint32_t baseArrayLayer, uint32_t layerCount) WGPU_FUNCTION_ATTRIBUTE; WGPU_EXPORT void wgpuWagyuRenderPassEncoderClearDepthAttachment(WGPURenderPassEncoder renderPassEncoder, const WGPUWagyuRect *rect, float depth, uint32_t baseArrayLayer, uint32_t layerCount) WGPU_FUNCTION_ATTRIBUTE; WGPU_EXPORT void wgpuWagyuRenderPassEncoderClearStencilAttachment(WGPURenderPassEncoder renderPassEncoder, const WGPUWagyuRect *rect, uint32_t stencil, uint32_t baseArrayLayer, uint32_t layerCount) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuWagyuRenderPassEncoderClearPixelLocalStorage(WGPURenderPassEncoder renderPassEncoder, const WGPUWagyuRenderPassEncoderClearPixelLocalStorage *options) WGPU_FUNCTION_ATTRIBUTE; +WGPU_EXPORT void wgpuWagyuRenderPassEncoderClearPixelLocalStorage(WGPURenderPassEncoder renderPassEncoder, uint32_t offset, uint32_t size, WGPU_NULLABLE const uint32_t *values) WGPU_FUNCTION_ATTRIBUTE; WGPU_EXPORT void wgpuWagyuRenderPassEncoderExecuteBundle(WGPURenderPassEncoder renderPassEncoder, WGPURenderBundle bundle) WGPU_FUNCTION_ATTRIBUTE; +WGPU_EXPORT void wgpuWagyuRenderPassEncoderExecuteCallback(WGPURenderPassEncoder renderPassEncoder, WGPUWagyuExecuteCallbackInfo callbackInfo) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuWagyuShaderEntryPointArrayFreeMembers(WGPUWagyuShaderEntryPointArray value) WGPU_FUNCTION_ATTRIBUTE; +WGPU_EXPORT void wgpuWagyuShaderEntryPointArrayFreeMembers(WGPUWagyuShaderEntryPointArray shaderEntryPointArray) WGPU_FUNCTION_ATTRIBUTE; WGPU_EXPORT void wgpuWagyuShaderModuleDestroy(WGPUShaderModule shaderModule) WGPU_FUNCTION_ATTRIBUTE; +WGPU_EXPORT WGPUFuture wgpuWagyuShaderModuleEntryPoints(WGPUShaderModule shaderModule, uint32_t stage, WGPUWagyuShaderModuleEntryPointsCallbackInfo callbackInfo) WGPU_FUNCTION_ATTRIBUTE; WGPU_EXPORT void wgpuWagyuShaderModuleIntrospect(WGPUShaderModule shaderModule, WGPUShaderStage stages, WGPUWagyuShaderEntryPointArray *shaderEntryPointArray) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT WGPUBool wgpuWagyuTextureIsSwapchain(WGPUTexture texture) WGPU_FUNCTION_ATTRIBUTE; +WGPU_EXPORT void wgpuWagyuStringArrayFreeMembers(WGPUWagyuStringArray stringArray) WGPU_FUNCTION_ATTRIBUTE; WGPU_EXPORT void wgpuWagyuSurfaceDestroy(WGPUSurface surface) WGPU_FUNCTION_ATTRIBUTE; WGPU_EXPORT WGPUTexture wgpuWagyuSurfaceGetCurrentDepthStencilTexture(WGPUSurface surface) WGPU_FUNCTION_ATTRIBUTE; @@ -538,14 +677,13 @@ WGPU_EXPORT void wgpuWagyuSurfaceSetWidth(WGPUSurface surface, float width) WGPU WGPU_EXPORT void wgpuWagyuSurfaceSetX(WGPUSurface surface, float x) WGPU_FUNCTION_ATTRIBUTE; WGPU_EXPORT void wgpuWagyuSurfaceSetY(WGPUSurface surface, float y) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuWagyuWGSLFeatureTypeArrayFreeMembers(WGPUWagyuWGSLFeatureTypeArray value) WGPU_FUNCTION_ATTRIBUTE; +WGPU_EXPORT WGPUBool wgpuWagyuTextureIsSwapchain(WGPUTexture texture) WGPU_FUNCTION_ATTRIBUTE; +WGPU_EXPORT void wgpuWagyuTextureReadPixels(WGPUTexture texture, void *data, size_t dataSize) WGPU_FUNCTION_ATTRIBUTE; -#if defined(__cplusplus) && !defined(USE_WGPU_WAGYU_NAMESPACE) && !defined(__cppcheck) -} // extern "C" -#endif +WGPU_EXPORT void wgpuWagyuWGSLFeatureTypeArrayFreeMembers(WGPUWagyuWGSLFeatureTypeArray wgslFeatureTypeArray) WGPU_FUNCTION_ATTRIBUTE; -#if defined(USE_WGPU_WAGYU_NAMESPACE) || defined(__cppcheck) -} // namespace wagyu2 +#if defined(__cplusplus) && !defined(__cppcheck) +} // extern "C" #endif #endif /* WEBGPU_WAGYU_H */ diff --git a/defold-rive/include/rive/renderer/webgpu/wagyu-port/old/include/webgpu/webgpu.h b/defold-rive/include/rive/renderer/webgpu/wagyu-port/old/include/webgpu/webgpu.h deleted file mode 100644 index 45ea1b07..00000000 --- a/defold-rive/include/rive/renderer/webgpu/wagyu-port/old/include/webgpu/webgpu.h +++ /dev/null @@ -1,1901 +0,0 @@ -// BSD 3-Clause License -// -// Copyright (c) 2019, "WebGPU native" developers -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this -// list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#ifndef WEBGPU_H_ -#define WEBGPU_H_ - -#if defined(WGPU_SHARED_LIBRARY) -# if defined(_WIN32) -# if defined(WGPU_IMPLEMENTATION) -# define WGPU_EXPORT __declspec(dllexport) -# else -# define WGPU_EXPORT __declspec(dllimport) -# endif -# else // defined(_WIN32) -# if defined(WGPU_IMPLEMENTATION) -# define WGPU_EXPORT __attribute__((visibility("default"))) -# else -# define WGPU_EXPORT -# endif -# endif // defined(_WIN32) -#else // defined(WGPU_SHARED_LIBRARY) -# define WGPU_EXPORT -#endif // defined(WGPU_SHARED_LIBRARY) - -#if !defined(WGPU_OBJECT_ATTRIBUTE) -#define WGPU_OBJECT_ATTRIBUTE -#endif -#if !defined(WGPU_ENUM_ATTRIBUTE) -#define WGPU_ENUM_ATTRIBUTE -#endif -#if !defined(WGPU_STRUCTURE_ATTRIBUTE) -#define WGPU_STRUCTURE_ATTRIBUTE -#endif -#if !defined(WGPU_FUNCTION_ATTRIBUTE) -#define WGPU_FUNCTION_ATTRIBUTE -#endif -#if !defined(WGPU_NULLABLE) -#define WGPU_NULLABLE -#endif - -#include -#include - -#if defined(USE_WGPU_WAGYU_NAMESPACE) || defined(__cppcheck) -namespace wagyu1 { -#endif - -#define WGPU_ARRAY_LAYER_COUNT_UNDEFINED UINT32_MAX -#define WGPU_COPY_STRIDE_UNDEFINED UINT32_MAX -#define WGPU_DEPTH_SLICE_UNDEFINED UINT32_MAX -#define WGPU_LIMIT_U32_UNDEFINED UINT32_MAX -#define WGPU_LIMIT_U64_UNDEFINED UINT64_MAX -#define WGPU_MIP_LEVEL_COUNT_UNDEFINED UINT32_MAX -#define WGPU_QUERY_SET_INDEX_UNDEFINED UINT32_MAX -#define WGPU_WHOLE_MAP_SIZE SIZE_MAX -#define WGPU_WHOLE_SIZE UINT64_MAX - -typedef uint32_t WGPUFlags; -typedef uint32_t WGPUBool; - -typedef struct WGPUAdapterImpl* WGPUAdapter WGPU_OBJECT_ATTRIBUTE; -typedef struct WGPUBindGroupImpl* WGPUBindGroup WGPU_OBJECT_ATTRIBUTE; -typedef struct WGPUBindGroupLayoutImpl* WGPUBindGroupLayout WGPU_OBJECT_ATTRIBUTE; -typedef struct WGPUBufferImpl* WGPUBuffer WGPU_OBJECT_ATTRIBUTE; -typedef struct WGPUCommandBufferImpl* WGPUCommandBuffer WGPU_OBJECT_ATTRIBUTE; -typedef struct WGPUCommandEncoderImpl* WGPUCommandEncoder WGPU_OBJECT_ATTRIBUTE; -typedef struct WGPUComputePassEncoderImpl* WGPUComputePassEncoder WGPU_OBJECT_ATTRIBUTE; -typedef struct WGPUComputePipelineImpl* WGPUComputePipeline WGPU_OBJECT_ATTRIBUTE; -typedef struct WGPUDeviceImpl* WGPUDevice WGPU_OBJECT_ATTRIBUTE; -typedef struct WGPUInstanceImpl* WGPUInstance WGPU_OBJECT_ATTRIBUTE; -typedef struct WGPUPipelineLayoutImpl* WGPUPipelineLayout WGPU_OBJECT_ATTRIBUTE; -typedef struct WGPUQuerySetImpl* WGPUQuerySet WGPU_OBJECT_ATTRIBUTE; -typedef struct WGPUQueueImpl* WGPUQueue WGPU_OBJECT_ATTRIBUTE; -typedef struct WGPURenderBundleImpl* WGPURenderBundle WGPU_OBJECT_ATTRIBUTE; -typedef struct WGPURenderBundleEncoderImpl* WGPURenderBundleEncoder WGPU_OBJECT_ATTRIBUTE; -typedef struct WGPURenderPassEncoderImpl* WGPURenderPassEncoder WGPU_OBJECT_ATTRIBUTE; -typedef struct WGPURenderPipelineImpl* WGPURenderPipeline WGPU_OBJECT_ATTRIBUTE; -typedef struct WGPUSamplerImpl* WGPUSampler WGPU_OBJECT_ATTRIBUTE; -typedef struct WGPUShaderModuleImpl* WGPUShaderModule WGPU_OBJECT_ATTRIBUTE; -typedef struct WGPUSurfaceImpl* WGPUSurface WGPU_OBJECT_ATTRIBUTE; -typedef struct WGPUSwapChainImpl* WGPUSwapChain WGPU_OBJECT_ATTRIBUTE; -typedef struct WGPUTextureImpl* WGPUTexture WGPU_OBJECT_ATTRIBUTE; -typedef struct WGPUTextureViewImpl* WGPUTextureView WGPU_OBJECT_ATTRIBUTE; - -// Structure forward declarations -struct WGPUAdapterInfo; -struct WGPUAdapterProperties; -struct WGPUBindGroupEntry; -struct WGPUBlendComponent; -struct WGPUBufferBindingLayout; -struct WGPUBufferDescriptor; -struct WGPUBufferMapCallbackInfo; -struct WGPUColor; -struct WGPUCommandBufferDescriptor; -struct WGPUCommandEncoderDescriptor; -struct WGPUCompilationMessage; -struct WGPUComputePassTimestampWrites; -struct WGPUConstantEntry; -struct WGPUExtent3D; -struct WGPUFuture; -struct WGPUInstanceFeatures; -struct WGPULimits; -struct WGPUMultisampleState; -struct WGPUOrigin3D; -struct WGPUPipelineLayoutDescriptor; -struct WGPUPrimitiveDepthClipControl; -struct WGPUPrimitiveState; -struct WGPUQuerySetDescriptor; -struct WGPUQueueDescriptor; -struct WGPUQueueWorkDoneCallbackInfo; -struct WGPURenderBundleDescriptor; -struct WGPURenderBundleEncoderDescriptor; -struct WGPURenderPassDepthStencilAttachment; -struct WGPURenderPassDescriptorMaxDrawCount; -struct WGPURenderPassTimestampWrites; -struct WGPURequestAdapterCallbackInfo; -struct WGPURequestAdapterOptions; -struct WGPUSamplerBindingLayout; -struct WGPUSamplerDescriptor; -struct WGPUShaderModuleSPIRVDescriptor; -struct WGPUShaderModuleWGSLDescriptor; -struct WGPUShaderModuleDescriptor; -struct WGPUStencilFaceState; -struct WGPUStorageTextureBindingLayout; -struct WGPUSurfaceCapabilities; -struct WGPUSurfaceConfiguration; -struct WGPUSurfaceDescriptor; -struct WGPUSurfaceDescriptorFromCanvasHTMLSelector; -struct WGPUSurfaceTexture; -struct WGPUSwapChainDescriptor; -struct WGPUTextureBindingLayout; -struct WGPUTextureBindingViewDimensionDescriptor; -struct WGPUTextureDataLayout; -struct WGPUTextureViewDescriptor; -struct WGPUVertexAttribute; -struct WGPUBindGroupDescriptor; -struct WGPUBindGroupLayoutEntry; -struct WGPUBlendState; -struct WGPUCompilationInfo; -struct WGPUComputePassDescriptor; -struct WGPUDepthStencilState; -struct WGPUFutureWaitInfo; -struct WGPUImageCopyBuffer; -struct WGPUImageCopyTexture; -struct WGPUInstanceDescriptor; -struct WGPUProgrammableStageDescriptor; -struct WGPURenderPassColorAttachment; -struct WGPURequiredLimits; -struct WGPUSupportedLimits; -struct WGPUTextureDescriptor; -struct WGPUVertexBufferLayout; -struct WGPUBindGroupLayoutDescriptor; -struct WGPUColorTargetState; -struct WGPUComputePipelineDescriptor; -struct WGPUDeviceDescriptor; -struct WGPURenderPassDescriptor; -struct WGPUVertexState; -struct WGPUFragmentState; -struct WGPURenderPipelineDescriptor; - -typedef enum WGPUWGSLFeatureName { - WGPUWGSLFeatureName_Undefined = 0x00000000, - WGPUWGSLFeatureName_ReadonlyAndReadwriteStorageTextures = 0x00000001, - WGPUWGSLFeatureName_Packed4x8IntegerDotProduct = 0x00000002, - WGPUWGSLFeatureName_UnrestrictedPointerParameters = 0x00000003, - WGPUWGSLFeatureName_PointerCompositeAccess = 0x00000004, - WGPUWGSLFeatureName_Force32 = 0x7FFFFFFF -} WGPUWGSLFeatureName WGPU_ENUM_ATTRIBUTE; - -typedef enum WGPUAdapterType { - WGPUAdapterType_DiscreteGPU = 0x00000001, - WGPUAdapterType_IntegratedGPU = 0x00000002, - WGPUAdapterType_CPU = 0x00000003, - WGPUAdapterType_Unknown = 0x00000004, - WGPUAdapterType_Force32 = 0x7FFFFFFF -} WGPUAdapterType WGPU_ENUM_ATTRIBUTE; - -typedef enum WGPUAddressMode { - WGPUAddressMode_Undefined = 0x00000000, - WGPUAddressMode_ClampToEdge = 0x00000001, - WGPUAddressMode_Repeat = 0x00000002, - WGPUAddressMode_MirrorRepeat = 0x00000003, - WGPUAddressMode_Force32 = 0x7FFFFFFF -} WGPUAddressMode WGPU_ENUM_ATTRIBUTE; - -typedef enum WGPUBackendType { - WGPUBackendType_Undefined = 0x00000000, - WGPUBackendType_Null = 0x00000001, - WGPUBackendType_WebGPU = 0x00000002, - WGPUBackendType_D3D11 = 0x00000003, - WGPUBackendType_D3D12 = 0x00000004, - WGPUBackendType_Metal = 0x00000005, - WGPUBackendType_Vulkan = 0x00000006, - WGPUBackendType_OpenGL = 0x00000007, - WGPUBackendType_OpenGLES = 0x00000008, - WGPUBackendType_Force32 = 0x7FFFFFFF -} WGPUBackendType WGPU_ENUM_ATTRIBUTE; - -typedef enum WGPUBlendFactor { - WGPUBlendFactor_Undefined = 0x00000000, - WGPUBlendFactor_Zero = 0x00000001, - WGPUBlendFactor_One = 0x00000002, - WGPUBlendFactor_Src = 0x00000003, - WGPUBlendFactor_OneMinusSrc = 0x00000004, - WGPUBlendFactor_SrcAlpha = 0x00000005, - WGPUBlendFactor_OneMinusSrcAlpha = 0x00000006, - WGPUBlendFactor_Dst = 0x00000007, - WGPUBlendFactor_OneMinusDst = 0x00000008, - WGPUBlendFactor_DstAlpha = 0x00000009, - WGPUBlendFactor_OneMinusDstAlpha = 0x0000000A, - WGPUBlendFactor_SrcAlphaSaturated = 0x0000000B, - WGPUBlendFactor_Constant = 0x0000000C, - WGPUBlendFactor_OneMinusConstant = 0x0000000D, - WGPUBlendFactor_Force32 = 0x7FFFFFFF -} WGPUBlendFactor WGPU_ENUM_ATTRIBUTE; - -typedef enum WGPUBlendOperation { - WGPUBlendOperation_Undefined = 0x00000000, - WGPUBlendOperation_Add = 0x00000001, - WGPUBlendOperation_Subtract = 0x00000002, - WGPUBlendOperation_ReverseSubtract = 0x00000003, - WGPUBlendOperation_Min = 0x00000004, - WGPUBlendOperation_Max = 0x00000005, - WGPUBlendOperation_Force32 = 0x7FFFFFFF -} WGPUBlendOperation WGPU_ENUM_ATTRIBUTE; - -typedef enum WGPUBufferBindingType { - WGPUBufferBindingType_Undefined = 0x00000000, - WGPUBufferBindingType_Uniform = 0x00000001, - WGPUBufferBindingType_Storage = 0x00000002, - WGPUBufferBindingType_ReadOnlyStorage = 0x00000003, - WGPUBufferBindingType_Force32 = 0x7FFFFFFF -} WGPUBufferBindingType WGPU_ENUM_ATTRIBUTE; - -typedef enum WGPUBufferMapAsyncStatus { - WGPUBufferMapAsyncStatus_Success = 0x00000000, - WGPUBufferMapAsyncStatus_ValidationError = 0x00000001, - WGPUBufferMapAsyncStatus_Unknown = 0x00000002, - WGPUBufferMapAsyncStatus_DeviceLost = 0x00000003, - WGPUBufferMapAsyncStatus_DestroyedBeforeCallback = 0x00000004, - WGPUBufferMapAsyncStatus_UnmappedBeforeCallback = 0x00000005, - WGPUBufferMapAsyncStatus_MappingAlreadyPending = 0x00000006, - WGPUBufferMapAsyncStatus_OffsetOutOfRange = 0x00000007, - WGPUBufferMapAsyncStatus_SizeOutOfRange = 0x00000008, - WGPUBufferMapAsyncStatus_Force32 = 0x7FFFFFFF -} WGPUBufferMapAsyncStatus WGPU_ENUM_ATTRIBUTE; - -typedef enum WGPUBufferMapState { - WGPUBufferMapState_Unmapped = 0x00000001, - WGPUBufferMapState_Pending = 0x00000002, - WGPUBufferMapState_Mapped = 0x00000003, - WGPUBufferMapState_Force32 = 0x7FFFFFFF -} WGPUBufferMapState WGPU_ENUM_ATTRIBUTE; - -typedef enum WGPUCallbackMode { - WGPUCallbackMode_WaitAnyOnly = 0x00000000, - WGPUCallbackMode_AllowProcessEvents = 0x00000001, - WGPUCallbackMode_AllowSpontaneous = 0x00000002, - WGPUCallbackMode_Force32 = 0x7FFFFFFF -} WGPUCallbackMode WGPU_ENUM_ATTRIBUTE; - -typedef enum WGPUCompareFunction { - WGPUCompareFunction_Undefined = 0x00000000, - WGPUCompareFunction_Never = 0x00000001, - WGPUCompareFunction_Less = 0x00000002, - WGPUCompareFunction_Equal = 0x00000003, - WGPUCompareFunction_LessEqual = 0x00000004, - WGPUCompareFunction_Greater = 0x00000005, - WGPUCompareFunction_NotEqual = 0x00000006, - WGPUCompareFunction_GreaterEqual = 0x00000007, - WGPUCompareFunction_Always = 0x00000008, - WGPUCompareFunction_Force32 = 0x7FFFFFFF -} WGPUCompareFunction WGPU_ENUM_ATTRIBUTE; - -typedef enum WGPUCompilationInfoRequestStatus { - WGPUCompilationInfoRequestStatus_Success = 0x00000000, - WGPUCompilationInfoRequestStatus_Error = 0x00000001, - WGPUCompilationInfoRequestStatus_DeviceLost = 0x00000002, - WGPUCompilationInfoRequestStatus_Unknown = 0x00000003, - WGPUCompilationInfoRequestStatus_Force32 = 0x7FFFFFFF -} WGPUCompilationInfoRequestStatus WGPU_ENUM_ATTRIBUTE; - -typedef enum WGPUCompilationMessageType { - WGPUCompilationMessageType_Error = 0x00000001, - WGPUCompilationMessageType_Warning = 0x00000002, - WGPUCompilationMessageType_Info = 0x00000003, - WGPUCompilationMessageType_Force32 = 0x7FFFFFFF -} WGPUCompilationMessageType WGPU_ENUM_ATTRIBUTE; - -typedef enum WGPUCompositeAlphaMode { - WGPUCompositeAlphaMode_Auto = 0x00000000, - WGPUCompositeAlphaMode_Opaque = 0x00000001, - WGPUCompositeAlphaMode_Premultiplied = 0x00000002, - WGPUCompositeAlphaMode_Unpremultiplied = 0x00000003, - WGPUCompositeAlphaMode_Inherit = 0x00000004, - WGPUCompositeAlphaMode_Force32 = 0x7FFFFFFF -} WGPUCompositeAlphaMode WGPU_ENUM_ATTRIBUTE; - -typedef enum WGPUCreatePipelineAsyncStatus { - WGPUCreatePipelineAsyncStatus_Success = 0x00000000, - WGPUCreatePipelineAsyncStatus_ValidationError = 0x00000001, - WGPUCreatePipelineAsyncStatus_InternalError = 0x00000002, - WGPUCreatePipelineAsyncStatus_DeviceLost = 0x00000003, - WGPUCreatePipelineAsyncStatus_DeviceDestroyed = 0x00000004, - WGPUCreatePipelineAsyncStatus_Unknown = 0x00000005, - WGPUCreatePipelineAsyncStatus_Force32 = 0x7FFFFFFF -} WGPUCreatePipelineAsyncStatus WGPU_ENUM_ATTRIBUTE; - -typedef enum WGPUCullMode { - WGPUCullMode_Undefined = 0x00000000, - WGPUCullMode_None = 0x00000001, - WGPUCullMode_Front = 0x00000002, - WGPUCullMode_Back = 0x00000003, - WGPUCullMode_Force32 = 0x7FFFFFFF -} WGPUCullMode WGPU_ENUM_ATTRIBUTE; - -typedef enum WGPUDeviceLostReason { - WGPUDeviceLostReason_Undefined = 0x00000001, - WGPUDeviceLostReason_Unknown = 0x00000001, - WGPUDeviceLostReason_Destroyed = 0x00000002, - WGPUDeviceLostReason_Force32 = 0x7FFFFFFF -} WGPUDeviceLostReason WGPU_ENUM_ATTRIBUTE; - -typedef enum WGPUErrorFilter { - WGPUErrorFilter_Validation = 0x00000001, - WGPUErrorFilter_OutOfMemory = 0x00000002, - WGPUErrorFilter_Internal = 0x00000003, - WGPUErrorFilter_Force32 = 0x7FFFFFFF -} WGPUErrorFilter WGPU_ENUM_ATTRIBUTE; - -typedef enum WGPUErrorType { - WGPUErrorType_NoError = 0x00000000, - WGPUErrorType_Validation = 0x00000001, - WGPUErrorType_OutOfMemory = 0x00000002, - WGPUErrorType_Internal = 0x00000003, - WGPUErrorType_Unknown = 0x00000004, - WGPUErrorType_DeviceLost = 0x00000005, - WGPUErrorType_Force32 = 0x7FFFFFFF -} WGPUErrorType WGPU_ENUM_ATTRIBUTE; - -typedef enum WGPUFeatureName { - WGPUFeatureName_Undefined = 0x00000000, - WGPUFeatureName_DepthClipControl = 0x00000001, - WGPUFeatureName_Depth32FloatStencil8 = 0x00000002, - WGPUFeatureName_TimestampQuery = 0x00000003, - WGPUFeatureName_TextureCompressionBC = 0x00000004, - WGPUFeatureName_TextureCompressionETC2 = 0x00000005, - WGPUFeatureName_TextureCompressionASTC = 0x00000006, - WGPUFeatureName_IndirectFirstInstance = 0x00000007, - WGPUFeatureName_ShaderF16 = 0x00000008, - WGPUFeatureName_RG11B10UfloatRenderable = 0x00000009, - WGPUFeatureName_BGRA8UnormStorage = 0x0000000A, - WGPUFeatureName_Float32Filterable = 0x0000000B, - WGPUFeatureName_Force32 = 0x7FFFFFFF -} WGPUFeatureName WGPU_ENUM_ATTRIBUTE; - -typedef enum WGPUFilterMode { - WGPUFilterMode_Undefined = 0x00000000, - WGPUFilterMode_Nearest = 0x00000001, - WGPUFilterMode_Linear = 0x00000002, - WGPUFilterMode_Force32 = 0x7FFFFFFF -} WGPUFilterMode WGPU_ENUM_ATTRIBUTE; - -typedef enum WGPUFrontFace { - WGPUFrontFace_Undefined = 0x00000000, - WGPUFrontFace_CCW = 0x00000001, - WGPUFrontFace_CW = 0x00000002, - WGPUFrontFace_Force32 = 0x7FFFFFFF -} WGPUFrontFace WGPU_ENUM_ATTRIBUTE; - -typedef enum WGPUIndexFormat { - WGPUIndexFormat_Undefined = 0x00000000, - WGPUIndexFormat_Uint16 = 0x00000001, - WGPUIndexFormat_Uint32 = 0x00000002, - WGPUIndexFormat_Force32 = 0x7FFFFFFF -} WGPUIndexFormat WGPU_ENUM_ATTRIBUTE; - -typedef enum WGPULoadOp { - WGPULoadOp_Undefined = 0x00000000, - WGPULoadOp_Clear = 0x00000001, - WGPULoadOp_Load = 0x00000002, - WGPULoadOp_Force32 = 0x7FFFFFFF -} WGPULoadOp WGPU_ENUM_ATTRIBUTE; - -typedef enum WGPUMipmapFilterMode { - WGPUMipmapFilterMode_Undefined = 0x00000000, - WGPUMipmapFilterMode_Nearest = 0x00000001, - WGPUMipmapFilterMode_Linear = 0x00000002, - WGPUMipmapFilterMode_Force32 = 0x7FFFFFFF -} WGPUMipmapFilterMode WGPU_ENUM_ATTRIBUTE; - -typedef enum WGPUPowerPreference { - WGPUPowerPreference_Undefined = 0x00000000, - WGPUPowerPreference_LowPower = 0x00000001, - WGPUPowerPreference_HighPerformance = 0x00000002, - WGPUPowerPreference_Force32 = 0x7FFFFFFF -} WGPUPowerPreference WGPU_ENUM_ATTRIBUTE; - -typedef enum WGPUPresentMode { - WGPUPresentMode_Fifo = 0x00000001, - WGPUPresentMode_Immediate = 0x00000003, - WGPUPresentMode_Mailbox = 0x00000004, - WGPUPresentMode_Force32 = 0x7FFFFFFF -} WGPUPresentMode WGPU_ENUM_ATTRIBUTE; - -typedef enum WGPUPrimitiveTopology { - WGPUPrimitiveTopology_Undefined = 0x00000000, - WGPUPrimitiveTopology_PointList = 0x00000001, - WGPUPrimitiveTopology_LineList = 0x00000002, - WGPUPrimitiveTopology_LineStrip = 0x00000003, - WGPUPrimitiveTopology_TriangleList = 0x00000004, - WGPUPrimitiveTopology_TriangleStrip = 0x00000005, - WGPUPrimitiveTopology_Force32 = 0x7FFFFFFF -} WGPUPrimitiveTopology WGPU_ENUM_ATTRIBUTE; - -typedef enum WGPUQueryType { - WGPUQueryType_Occlusion = 0x00000001, - WGPUQueryType_Timestamp = 0x00000002, - WGPUQueryType_Force32 = 0x7FFFFFFF -} WGPUQueryType WGPU_ENUM_ATTRIBUTE; - -typedef enum WGPUQueueWorkDoneStatus { - WGPUQueueWorkDoneStatus_Success = 0x00000000, - WGPUQueueWorkDoneStatus_Error = 0x00000001, - WGPUQueueWorkDoneStatus_Unknown = 0x00000002, - WGPUQueueWorkDoneStatus_DeviceLost = 0x00000003, - WGPUQueueWorkDoneStatus_Force32 = 0x7FFFFFFF -} WGPUQueueWorkDoneStatus WGPU_ENUM_ATTRIBUTE; - -typedef enum WGPURequestAdapterStatus { - WGPURequestAdapterStatus_Success = 0x00000000, - WGPURequestAdapterStatus_Unavailable = 0x00000001, - WGPURequestAdapterStatus_Error = 0x00000002, - WGPURequestAdapterStatus_Unknown = 0x00000003, - WGPURequestAdapterStatus_Force32 = 0x7FFFFFFF -} WGPURequestAdapterStatus WGPU_ENUM_ATTRIBUTE; - -typedef enum WGPURequestDeviceStatus { - WGPURequestDeviceStatus_Success = 0x00000000, - WGPURequestDeviceStatus_Error = 0x00000001, - WGPURequestDeviceStatus_Unknown = 0x00000002, - WGPURequestDeviceStatus_Force32 = 0x7FFFFFFF -} WGPURequestDeviceStatus WGPU_ENUM_ATTRIBUTE; - -typedef enum WGPUSType { - WGPUSType_Invalid = 0x00000000, - WGPUSType_SurfaceDescriptorFromCanvasHTMLSelector = 0x00000004, - WGPUSType_ShaderModuleSPIRVDescriptor = 0x00000005, - WGPUSType_ShaderModuleWGSLDescriptor = 0x00000006, - WGPUSType_PrimitiveDepthClipControl = 0x00000007, - WGPUSType_RenderPassDescriptorMaxDrawCount = 0x0000000F, - WGPUSType_TextureBindingViewDimensionDescriptor = 0x00000011, - WGPUSType_Force32 = 0x7FFFFFFF -} WGPUSType WGPU_ENUM_ATTRIBUTE; - -typedef enum WGPUSamplerBindingType { - WGPUSamplerBindingType_Undefined = 0x00000000, - WGPUSamplerBindingType_Filtering = 0x00000001, - WGPUSamplerBindingType_NonFiltering = 0x00000002, - WGPUSamplerBindingType_Comparison = 0x00000003, - WGPUSamplerBindingType_Force32 = 0x7FFFFFFF -} WGPUSamplerBindingType WGPU_ENUM_ATTRIBUTE; - -typedef enum WGPUStencilOperation { - WGPUStencilOperation_Undefined = 0x00000000, - WGPUStencilOperation_Keep = 0x00000001, - WGPUStencilOperation_Zero = 0x00000002, - WGPUStencilOperation_Replace = 0x00000003, - WGPUStencilOperation_Invert = 0x00000004, - WGPUStencilOperation_IncrementClamp = 0x00000005, - WGPUStencilOperation_DecrementClamp = 0x00000006, - WGPUStencilOperation_IncrementWrap = 0x00000007, - WGPUStencilOperation_DecrementWrap = 0x00000008, - WGPUStencilOperation_Force32 = 0x7FFFFFFF -} WGPUStencilOperation WGPU_ENUM_ATTRIBUTE; - -typedef enum WGPUStorageTextureAccess { - WGPUStorageTextureAccess_Undefined = 0x00000000, - WGPUStorageTextureAccess_WriteOnly = 0x00000001, - WGPUStorageTextureAccess_ReadOnly = 0x00000002, - WGPUStorageTextureAccess_ReadWrite = 0x00000003, - WGPUStorageTextureAccess_Force32 = 0x7FFFFFFF -} WGPUStorageTextureAccess WGPU_ENUM_ATTRIBUTE; - -typedef enum WGPUStoreOp { - WGPUStoreOp_Undefined = 0x00000000, - WGPUStoreOp_Store = 0x00000001, - WGPUStoreOp_Discard = 0x00000002, - WGPUStoreOp_Force32 = 0x7FFFFFFF -} WGPUStoreOp WGPU_ENUM_ATTRIBUTE; - -typedef enum WGPUSurfaceGetCurrentTextureStatus { - WGPUSurfaceGetCurrentTextureStatus_Success = 0x00000000, - WGPUSurfaceGetCurrentTextureStatus_Timeout = 0x00000001, - WGPUSurfaceGetCurrentTextureStatus_Outdated = 0x00000002, - WGPUSurfaceGetCurrentTextureStatus_Lost = 0x00000003, - WGPUSurfaceGetCurrentTextureStatus_OutOfMemory = 0x00000004, - WGPUSurfaceGetCurrentTextureStatus_DeviceLost = 0x00000005, - WGPUSurfaceGetCurrentTextureStatus_Force32 = 0x7FFFFFFF -} WGPUSurfaceGetCurrentTextureStatus WGPU_ENUM_ATTRIBUTE; - -typedef enum WGPUTextureAspect { - WGPUTextureAspect_Undefined = 0x00000000, - WGPUTextureAspect_All = 0x00000001, - WGPUTextureAspect_StencilOnly = 0x00000002, - WGPUTextureAspect_DepthOnly = 0x00000003, - WGPUTextureAspect_Force32 = 0x7FFFFFFF -} WGPUTextureAspect WGPU_ENUM_ATTRIBUTE; - -typedef enum WGPUTextureDimension { - WGPUTextureDimension_Undefined = 0x00000000, - WGPUTextureDimension_1D = 0x00000001, - WGPUTextureDimension_2D = 0x00000002, - WGPUTextureDimension_3D = 0x00000003, - WGPUTextureDimension_Force32 = 0x7FFFFFFF -} WGPUTextureDimension WGPU_ENUM_ATTRIBUTE; - -typedef enum WGPUTextureFormat { - WGPUTextureFormat_Undefined = 0x00000000, - WGPUTextureFormat_R8Unorm = 0x00000001, - WGPUTextureFormat_R8Snorm = 0x00000002, - WGPUTextureFormat_R8Uint = 0x00000003, - WGPUTextureFormat_R8Sint = 0x00000004, - WGPUTextureFormat_R16Uint = 0x00000005, - WGPUTextureFormat_R16Sint = 0x00000006, - WGPUTextureFormat_R16Float = 0x00000007, - WGPUTextureFormat_RG8Unorm = 0x00000008, - WGPUTextureFormat_RG8Snorm = 0x00000009, - WGPUTextureFormat_RG8Uint = 0x0000000A, - WGPUTextureFormat_RG8Sint = 0x0000000B, - WGPUTextureFormat_R32Float = 0x0000000C, - WGPUTextureFormat_R32Uint = 0x0000000D, - WGPUTextureFormat_R32Sint = 0x0000000E, - WGPUTextureFormat_RG16Uint = 0x0000000F, - WGPUTextureFormat_RG16Sint = 0x00000010, - WGPUTextureFormat_RG16Float = 0x00000011, - WGPUTextureFormat_RGBA8Unorm = 0x00000012, - WGPUTextureFormat_RGBA8UnormSrgb = 0x00000013, - WGPUTextureFormat_RGBA8Snorm = 0x00000014, - WGPUTextureFormat_RGBA8Uint = 0x00000015, - WGPUTextureFormat_RGBA8Sint = 0x00000016, - WGPUTextureFormat_BGRA8Unorm = 0x00000017, - WGPUTextureFormat_BGRA8UnormSrgb = 0x00000018, - WGPUTextureFormat_RGB10A2Uint = 0x00000019, - WGPUTextureFormat_RGB10A2Unorm = 0x0000001A, - WGPUTextureFormat_RG11B10Ufloat = 0x0000001B, - WGPUTextureFormat_RGB9E5Ufloat = 0x0000001C, - WGPUTextureFormat_RG32Float = 0x0000001D, - WGPUTextureFormat_RG32Uint = 0x0000001E, - WGPUTextureFormat_RG32Sint = 0x0000001F, - WGPUTextureFormat_RGBA16Uint = 0x00000020, - WGPUTextureFormat_RGBA16Sint = 0x00000021, - WGPUTextureFormat_RGBA16Float = 0x00000022, - WGPUTextureFormat_RGBA32Float = 0x00000023, - WGPUTextureFormat_RGBA32Uint = 0x00000024, - WGPUTextureFormat_RGBA32Sint = 0x00000025, - WGPUTextureFormat_Stencil8 = 0x00000026, - WGPUTextureFormat_Depth16Unorm = 0x00000027, - WGPUTextureFormat_Depth24Plus = 0x00000028, - WGPUTextureFormat_Depth24PlusStencil8 = 0x00000029, - WGPUTextureFormat_Depth32Float = 0x0000002A, - WGPUTextureFormat_Depth32FloatStencil8 = 0x0000002B, - WGPUTextureFormat_BC1RGBAUnorm = 0x0000002C, - WGPUTextureFormat_BC1RGBAUnormSrgb = 0x0000002D, - WGPUTextureFormat_BC2RGBAUnorm = 0x0000002E, - WGPUTextureFormat_BC2RGBAUnormSrgb = 0x0000002F, - WGPUTextureFormat_BC3RGBAUnorm = 0x00000030, - WGPUTextureFormat_BC3RGBAUnormSrgb = 0x00000031, - WGPUTextureFormat_BC4RUnorm = 0x00000032, - WGPUTextureFormat_BC4RSnorm = 0x00000033, - WGPUTextureFormat_BC5RGUnorm = 0x00000034, - WGPUTextureFormat_BC5RGSnorm = 0x00000035, - WGPUTextureFormat_BC6HRGBUfloat = 0x00000036, - WGPUTextureFormat_BC6HRGBFloat = 0x00000037, - WGPUTextureFormat_BC7RGBAUnorm = 0x00000038, - WGPUTextureFormat_BC7RGBAUnormSrgb = 0x00000039, - WGPUTextureFormat_ETC2RGB8Unorm = 0x0000003A, - WGPUTextureFormat_ETC2RGB8UnormSrgb = 0x0000003B, - WGPUTextureFormat_ETC2RGB8A1Unorm = 0x0000003C, - WGPUTextureFormat_ETC2RGB8A1UnormSrgb = 0x0000003D, - WGPUTextureFormat_ETC2RGBA8Unorm = 0x0000003E, - WGPUTextureFormat_ETC2RGBA8UnormSrgb = 0x0000003F, - WGPUTextureFormat_EACR11Unorm = 0x00000040, - WGPUTextureFormat_EACR11Snorm = 0x00000041, - WGPUTextureFormat_EACRG11Unorm = 0x00000042, - WGPUTextureFormat_EACRG11Snorm = 0x00000043, - WGPUTextureFormat_ASTC4x4Unorm = 0x00000044, - WGPUTextureFormat_ASTC4x4UnormSrgb = 0x00000045, - WGPUTextureFormat_ASTC5x4Unorm = 0x00000046, - WGPUTextureFormat_ASTC5x4UnormSrgb = 0x00000047, - WGPUTextureFormat_ASTC5x5Unorm = 0x00000048, - WGPUTextureFormat_ASTC5x5UnormSrgb = 0x00000049, - WGPUTextureFormat_ASTC6x5Unorm = 0x0000004A, - WGPUTextureFormat_ASTC6x5UnormSrgb = 0x0000004B, - WGPUTextureFormat_ASTC6x6Unorm = 0x0000004C, - WGPUTextureFormat_ASTC6x6UnormSrgb = 0x0000004D, - WGPUTextureFormat_ASTC8x5Unorm = 0x0000004E, - WGPUTextureFormat_ASTC8x5UnormSrgb = 0x0000004F, - WGPUTextureFormat_ASTC8x6Unorm = 0x00000050, - WGPUTextureFormat_ASTC8x6UnormSrgb = 0x00000051, - WGPUTextureFormat_ASTC8x8Unorm = 0x00000052, - WGPUTextureFormat_ASTC8x8UnormSrgb = 0x00000053, - WGPUTextureFormat_ASTC10x5Unorm = 0x00000054, - WGPUTextureFormat_ASTC10x5UnormSrgb = 0x00000055, - WGPUTextureFormat_ASTC10x6Unorm = 0x00000056, - WGPUTextureFormat_ASTC10x6UnormSrgb = 0x00000057, - WGPUTextureFormat_ASTC10x8Unorm = 0x00000058, - WGPUTextureFormat_ASTC10x8UnormSrgb = 0x00000059, - WGPUTextureFormat_ASTC10x10Unorm = 0x0000005A, - WGPUTextureFormat_ASTC10x10UnormSrgb = 0x0000005B, - WGPUTextureFormat_ASTC12x10Unorm = 0x0000005C, - WGPUTextureFormat_ASTC12x10UnormSrgb = 0x0000005D, - WGPUTextureFormat_ASTC12x12Unorm = 0x0000005E, - WGPUTextureFormat_ASTC12x12UnormSrgb = 0x0000005F, - WGPUTextureFormat_Force32 = 0x7FFFFFFF -} WGPUTextureFormat WGPU_ENUM_ATTRIBUTE; - -typedef enum WGPUTextureSampleType { - WGPUTextureSampleType_Undefined = 0x00000000, - WGPUTextureSampleType_Float = 0x00000001, - WGPUTextureSampleType_UnfilterableFloat = 0x00000002, - WGPUTextureSampleType_Depth = 0x00000003, - WGPUTextureSampleType_Sint = 0x00000004, - WGPUTextureSampleType_Uint = 0x00000005, - WGPUTextureSampleType_Force32 = 0x7FFFFFFF -} WGPUTextureSampleType WGPU_ENUM_ATTRIBUTE; - -typedef enum WGPUTextureViewDimension { - WGPUTextureViewDimension_Undefined = 0x00000000, - WGPUTextureViewDimension_1D = 0x00000001, - WGPUTextureViewDimension_2D = 0x00000002, - WGPUTextureViewDimension_2DArray = 0x00000003, - WGPUTextureViewDimension_Cube = 0x00000004, - WGPUTextureViewDimension_CubeArray = 0x00000005, - WGPUTextureViewDimension_3D = 0x00000006, - WGPUTextureViewDimension_Force32 = 0x7FFFFFFF -} WGPUTextureViewDimension WGPU_ENUM_ATTRIBUTE; - -typedef enum WGPUVertexFormat { - WGPUVertexFormat_Undefined = 0x00000000, - WGPUVertexFormat_Uint8x2 = 0x00000001, - WGPUVertexFormat_Uint8x4 = 0x00000002, - WGPUVertexFormat_Sint8x2 = 0x00000003, - WGPUVertexFormat_Sint8x4 = 0x00000004, - WGPUVertexFormat_Unorm8x2 = 0x00000005, - WGPUVertexFormat_Unorm8x4 = 0x00000006, - WGPUVertexFormat_Snorm8x2 = 0x00000007, - WGPUVertexFormat_Snorm8x4 = 0x00000008, - WGPUVertexFormat_Uint16x2 = 0x00000009, - WGPUVertexFormat_Uint16x4 = 0x0000000A, - WGPUVertexFormat_Sint16x2 = 0x0000000B, - WGPUVertexFormat_Sint16x4 = 0x0000000C, - WGPUVertexFormat_Unorm16x2 = 0x0000000D, - WGPUVertexFormat_Unorm16x4 = 0x0000000E, - WGPUVertexFormat_Snorm16x2 = 0x0000000F, - WGPUVertexFormat_Snorm16x4 = 0x00000010, - WGPUVertexFormat_Float16x2 = 0x00000011, - WGPUVertexFormat_Float16x4 = 0x00000012, - WGPUVertexFormat_Float32 = 0x00000013, - WGPUVertexFormat_Float32x2 = 0x00000014, - WGPUVertexFormat_Float32x3 = 0x00000015, - WGPUVertexFormat_Float32x4 = 0x00000016, - WGPUVertexFormat_Uint32 = 0x00000017, - WGPUVertexFormat_Uint32x2 = 0x00000018, - WGPUVertexFormat_Uint32x3 = 0x00000019, - WGPUVertexFormat_Uint32x4 = 0x0000001A, - WGPUVertexFormat_Sint32 = 0x0000001B, - WGPUVertexFormat_Sint32x2 = 0x0000001C, - WGPUVertexFormat_Sint32x3 = 0x0000001D, - WGPUVertexFormat_Sint32x4 = 0x0000001E, - WGPUVertexFormat_Unorm10_10_10_2 = 0x0000001F, - WGPUVertexFormat_Force32 = 0x7FFFFFFF -} WGPUVertexFormat WGPU_ENUM_ATTRIBUTE; - -typedef enum WGPUVertexStepMode { - WGPUVertexStepMode_Undefined = 0x00000000, - WGPUVertexStepMode_VertexBufferNotUsed = 0x00000001, - WGPUVertexStepMode_Vertex = 0x00000002, - WGPUVertexStepMode_Instance = 0x00000003, - WGPUVertexStepMode_Force32 = 0x7FFFFFFF -} WGPUVertexStepMode WGPU_ENUM_ATTRIBUTE; - -typedef enum WGPUWaitStatus { - WGPUWaitStatus_Success = 0x00000000, - WGPUWaitStatus_TimedOut = 0x00000001, - WGPUWaitStatus_UnsupportedTimeout = 0x00000002, - WGPUWaitStatus_UnsupportedCount = 0x00000003, - WGPUWaitStatus_UnsupportedMixedSources = 0x00000004, - WGPUWaitStatus_Unknown = 0x00000005, - WGPUWaitStatus_Force32 = 0x7FFFFFFF -} WGPUWaitStatus WGPU_ENUM_ATTRIBUTE; - -typedef enum WGPUBufferUsage { - WGPUBufferUsage_None = 0x00000000, - WGPUBufferUsage_MapRead = 0x00000001, - WGPUBufferUsage_MapWrite = 0x00000002, - WGPUBufferUsage_CopySrc = 0x00000004, - WGPUBufferUsage_CopyDst = 0x00000008, - WGPUBufferUsage_Index = 0x00000010, - WGPUBufferUsage_Vertex = 0x00000020, - WGPUBufferUsage_Uniform = 0x00000040, - WGPUBufferUsage_Storage = 0x00000080, - WGPUBufferUsage_Indirect = 0x00000100, - WGPUBufferUsage_QueryResolve = 0x00000200, - WGPUBufferUsage_Force32 = 0x7FFFFFFF -} WGPUBufferUsage WGPU_ENUM_ATTRIBUTE; -typedef WGPUFlags WGPUBufferUsageFlags WGPU_ENUM_ATTRIBUTE; - -typedef enum WGPUColorWriteMask { - WGPUColorWriteMask_None = 0x00000000, - WGPUColorWriteMask_Red = 0x00000001, - WGPUColorWriteMask_Green = 0x00000002, - WGPUColorWriteMask_Blue = 0x00000004, - WGPUColorWriteMask_Alpha = 0x00000008, - WGPUColorWriteMask_All = 0x0000000F, - WGPUColorWriteMask_Force32 = 0x7FFFFFFF -} WGPUColorWriteMask WGPU_ENUM_ATTRIBUTE; -typedef WGPUFlags WGPUColorWriteMaskFlags WGPU_ENUM_ATTRIBUTE; - -typedef enum WGPUMapMode { - WGPUMapMode_None = 0x00000000, - WGPUMapMode_Read = 0x00000001, - WGPUMapMode_Write = 0x00000002, - WGPUMapMode_Force32 = 0x7FFFFFFF -} WGPUMapMode WGPU_ENUM_ATTRIBUTE; -typedef WGPUFlags WGPUMapModeFlags WGPU_ENUM_ATTRIBUTE; - -typedef enum WGPUShaderStage { - WGPUShaderStage_None = 0x00000000, - WGPUShaderStage_Vertex = 0x00000001, - WGPUShaderStage_Fragment = 0x00000002, - WGPUShaderStage_Compute = 0x00000004, - WGPUShaderStage_Force32 = 0x7FFFFFFF -} WGPUShaderStage WGPU_ENUM_ATTRIBUTE; -typedef WGPUFlags WGPUShaderStageFlags WGPU_ENUM_ATTRIBUTE; - -typedef enum WGPUTextureUsage { - WGPUTextureUsage_None = 0x00000000, - WGPUTextureUsage_CopySrc = 0x00000001, - WGPUTextureUsage_CopyDst = 0x00000002, - WGPUTextureUsage_TextureBinding = 0x00000004, - WGPUTextureUsage_StorageBinding = 0x00000008, - WGPUTextureUsage_RenderAttachment = 0x00000010, - WGPUTextureUsage_Force32 = 0x7FFFFFFF -} WGPUTextureUsage WGPU_ENUM_ATTRIBUTE; -typedef WGPUFlags WGPUTextureUsageFlags WGPU_ENUM_ATTRIBUTE; - -typedef void (*WGPUBufferMapCallback)(WGPUBufferMapAsyncStatus status, void * userdata) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUCompilationInfoCallback)(WGPUCompilationInfoRequestStatus status, struct WGPUCompilationInfo const * compilationInfo, void * userdata) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUCreateComputePipelineAsyncCallback)(WGPUCreatePipelineAsyncStatus status, WGPUComputePipeline pipeline, char const * message, void * userdata) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUCreateRenderPipelineAsyncCallback)(WGPUCreatePipelineAsyncStatus status, WGPURenderPipeline pipeline, char const * message, void * userdata) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUDeviceLostCallback)(WGPUDeviceLostReason reason, char const * message, void * userdata) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUErrorCallback)(WGPUErrorType type, char const * message, void * userdata) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProc)(void) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUQueueWorkDoneCallback)(WGPUQueueWorkDoneStatus status, void * userdata) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPURequestAdapterCallback)(WGPURequestAdapterStatus status, WGPUAdapter adapter, char const * message, void * userdata) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPURequestDeviceCallback)(WGPURequestDeviceStatus status, WGPUDevice device, char const * message, void * userdata) WGPU_FUNCTION_ATTRIBUTE; - -typedef struct WGPUChainedStruct { - struct WGPUChainedStruct const * next; - WGPUSType sType; -} WGPUChainedStruct WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPUChainedStructOut { - struct WGPUChainedStructOut * next; - WGPUSType sType; -} WGPUChainedStructOut WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPUAdapterInfo { - WGPUChainedStructOut * nextInChain; - char const * vendor; - char const * architecture; - char const * device; - char const * description; - WGPUBackendType backendType; - WGPUAdapterType adapterType; - uint32_t vendorID; - uint32_t deviceID; -} WGPUAdapterInfo WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPUAdapterProperties { - WGPUChainedStructOut * nextInChain; - uint32_t vendorID; - char const * vendorName; - char const * architecture; - uint32_t deviceID; - char const * name; - char const * driverDescription; - WGPUAdapterType adapterType; - WGPUBackendType backendType; - WGPUBool compatibilityMode; -} WGPUAdapterProperties WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPUBindGroupEntry { - WGPUChainedStruct const * nextInChain; - uint32_t binding; - WGPU_NULLABLE WGPUBuffer buffer; - uint64_t offset; - uint64_t size; - WGPU_NULLABLE WGPUSampler sampler; - WGPU_NULLABLE WGPUTextureView textureView; -} WGPUBindGroupEntry WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPUBlendComponent { - WGPUBlendOperation operation; - WGPUBlendFactor srcFactor; - WGPUBlendFactor dstFactor; -} WGPUBlendComponent WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPUBufferBindingLayout { - WGPUChainedStruct const * nextInChain; - WGPUBufferBindingType type; - WGPUBool hasDynamicOffset; - uint64_t minBindingSize; -} WGPUBufferBindingLayout WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPUBufferDescriptor { - WGPUChainedStruct const * nextInChain; - WGPU_NULLABLE char const * label; - WGPUBufferUsageFlags usage; - uint64_t size; - WGPUBool mappedAtCreation; -} WGPUBufferDescriptor WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPUBufferMapCallbackInfo { - WGPUChainedStruct const * nextInChain; - WGPUCallbackMode mode; - WGPUBufferMapCallback callback; - void * userdata; -} WGPUBufferMapCallbackInfo WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPUColor { - double r; - double g; - double b; - double a; -} WGPUColor WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPUCommandBufferDescriptor { - WGPUChainedStruct const * nextInChain; - WGPU_NULLABLE char const * label; -} WGPUCommandBufferDescriptor WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPUCommandEncoderDescriptor { - WGPUChainedStruct const * nextInChain; - WGPU_NULLABLE char const * label; -} WGPUCommandEncoderDescriptor WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPUCompilationMessage { - WGPUChainedStruct const * nextInChain; - WGPU_NULLABLE char const * message; - WGPUCompilationMessageType type; - uint64_t lineNum; - uint64_t linePos; - uint64_t offset; - uint64_t length; - uint64_t utf16LinePos; - uint64_t utf16Offset; - uint64_t utf16Length; -} WGPUCompilationMessage WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPUComputePassTimestampWrites { - WGPUQuerySet querySet; - uint32_t beginningOfPassWriteIndex; - uint32_t endOfPassWriteIndex; -} WGPUComputePassTimestampWrites WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPUConstantEntry { - WGPUChainedStruct const * nextInChain; - char const * key; - double value; -} WGPUConstantEntry WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPUExtent3D { - uint32_t width; - uint32_t height; - uint32_t depthOrArrayLayers; -} WGPUExtent3D WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPUFuture { - uint64_t id; -} WGPUFuture WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPUInstanceFeatures { - WGPUChainedStruct const * nextInChain; - WGPUBool timedWaitAnyEnable; - size_t timedWaitAnyMaxCount; -} WGPUInstanceFeatures WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPULimits { - uint32_t maxTextureDimension1D; - uint32_t maxTextureDimension2D; - uint32_t maxTextureDimension3D; - uint32_t maxTextureArrayLayers; - uint32_t maxBindGroups; - uint32_t maxBindGroupsPlusVertexBuffers; - uint32_t maxBindingsPerBindGroup; - uint32_t maxDynamicUniformBuffersPerPipelineLayout; - uint32_t maxDynamicStorageBuffersPerPipelineLayout; - uint32_t maxSampledTexturesPerShaderStage; - uint32_t maxSamplersPerShaderStage; - uint32_t maxStorageBuffersPerShaderStage; - uint32_t maxStorageTexturesPerShaderStage; - uint32_t maxUniformBuffersPerShaderStage; - uint64_t maxUniformBufferBindingSize; - uint64_t maxStorageBufferBindingSize; - uint32_t minUniformBufferOffsetAlignment; - uint32_t minStorageBufferOffsetAlignment; - uint32_t maxVertexBuffers; - uint64_t maxBufferSize; - uint32_t maxVertexAttributes; - uint32_t maxVertexBufferArrayStride; - uint32_t maxInterStageShaderComponents; - uint32_t maxInterStageShaderVariables; - uint32_t maxColorAttachments; - uint32_t maxColorAttachmentBytesPerSample; - uint32_t maxComputeWorkgroupStorageSize; - uint32_t maxComputeInvocationsPerWorkgroup; - uint32_t maxComputeWorkgroupSizeX; - uint32_t maxComputeWorkgroupSizeY; - uint32_t maxComputeWorkgroupSizeZ; - uint32_t maxComputeWorkgroupsPerDimension; -} WGPULimits WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPUMultisampleState { - WGPUChainedStruct const * nextInChain; - uint32_t count; - uint32_t mask; - WGPUBool alphaToCoverageEnabled; -} WGPUMultisampleState WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPUOrigin3D { - uint32_t x; - uint32_t y; - uint32_t z; -} WGPUOrigin3D WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPUPipelineLayoutDescriptor { - WGPUChainedStruct const * nextInChain; - WGPU_NULLABLE char const * label; - size_t bindGroupLayoutCount; - WGPUBindGroupLayout const * bindGroupLayouts; -} WGPUPipelineLayoutDescriptor WGPU_STRUCTURE_ATTRIBUTE; - -// Can be chained in WGPUPrimitiveState -typedef struct WGPUPrimitiveDepthClipControl { - WGPUChainedStruct chain; - WGPUBool unclippedDepth; -} WGPUPrimitiveDepthClipControl WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPUPrimitiveState { - WGPUChainedStruct const * nextInChain; - WGPUPrimitiveTopology topology; - WGPUIndexFormat stripIndexFormat; - WGPUFrontFace frontFace; - WGPUCullMode cullMode; -} WGPUPrimitiveState WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPUQuerySetDescriptor { - WGPUChainedStruct const * nextInChain; - WGPU_NULLABLE char const * label; - WGPUQueryType type; - uint32_t count; -} WGPUQuerySetDescriptor WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPUQueueDescriptor { - WGPUChainedStruct const * nextInChain; - WGPU_NULLABLE char const * label; -} WGPUQueueDescriptor WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPUQueueWorkDoneCallbackInfo { - WGPUChainedStruct const * nextInChain; - WGPUCallbackMode mode; - WGPUQueueWorkDoneCallback callback; - void * userdata; -} WGPUQueueWorkDoneCallbackInfo WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPURenderBundleDescriptor { - WGPUChainedStruct const * nextInChain; - WGPU_NULLABLE char const * label; -} WGPURenderBundleDescriptor WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPURenderBundleEncoderDescriptor { - WGPUChainedStruct const * nextInChain; - WGPU_NULLABLE char const * label; - size_t colorFormatCount; - WGPUTextureFormat const * colorFormats; - WGPUTextureFormat depthStencilFormat; - uint32_t sampleCount; - WGPUBool depthReadOnly; - WGPUBool stencilReadOnly; -} WGPURenderBundleEncoderDescriptor WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPURenderPassDepthStencilAttachment { - WGPUTextureView view; - WGPULoadOp depthLoadOp; - WGPUStoreOp depthStoreOp; - float depthClearValue; - WGPUBool depthReadOnly; - WGPULoadOp stencilLoadOp; - WGPUStoreOp stencilStoreOp; - uint32_t stencilClearValue; - WGPUBool stencilReadOnly; -} WGPURenderPassDepthStencilAttachment WGPU_STRUCTURE_ATTRIBUTE; - -// Can be chained in WGPURenderPassDescriptor -typedef struct WGPURenderPassDescriptorMaxDrawCount { - WGPUChainedStruct chain; - uint64_t maxDrawCount; -} WGPURenderPassDescriptorMaxDrawCount WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPURenderPassTimestampWrites { - WGPUQuerySet querySet; - uint32_t beginningOfPassWriteIndex; - uint32_t endOfPassWriteIndex; -} WGPURenderPassTimestampWrites WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPURequestAdapterCallbackInfo { - WGPUChainedStruct const * nextInChain; - WGPUCallbackMode mode; - WGPURequestAdapterCallback callback; - void * userdata; -} WGPURequestAdapterCallbackInfo WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPURequestAdapterOptions { - WGPUChainedStruct const * nextInChain; - WGPU_NULLABLE WGPUSurface compatibleSurface; - WGPUPowerPreference powerPreference; - WGPUBackendType backendType; - WGPUBool forceFallbackAdapter; - WGPUBool compatibilityMode; -} WGPURequestAdapterOptions WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPUSamplerBindingLayout { - WGPUChainedStruct const * nextInChain; - WGPUSamplerBindingType type; -} WGPUSamplerBindingLayout WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPUSamplerDescriptor { - WGPUChainedStruct const * nextInChain; - WGPU_NULLABLE char const * label; - WGPUAddressMode addressModeU; - WGPUAddressMode addressModeV; - WGPUAddressMode addressModeW; - WGPUFilterMode magFilter; - WGPUFilterMode minFilter; - WGPUMipmapFilterMode mipmapFilter; - float lodMinClamp; - float lodMaxClamp; - WGPUCompareFunction compare; - uint16_t maxAnisotropy; -} WGPUSamplerDescriptor WGPU_STRUCTURE_ATTRIBUTE; - -// Can be chained in WGPUShaderModuleDescriptor -typedef struct WGPUShaderModuleSPIRVDescriptor { - WGPUChainedStruct chain; - uint32_t codeSize; - uint32_t const * code; -} WGPUShaderModuleSPIRVDescriptor WGPU_STRUCTURE_ATTRIBUTE; - -// Can be chained in WGPUShaderModuleDescriptor -typedef struct WGPUShaderModuleWGSLDescriptor { - WGPUChainedStruct chain; - char const * code; -} WGPUShaderModuleWGSLDescriptor WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPUShaderModuleDescriptor { - WGPUChainedStruct const * nextInChain; - WGPU_NULLABLE char const * label; -} WGPUShaderModuleDescriptor WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPUStencilFaceState { - WGPUCompareFunction compare; - WGPUStencilOperation failOp; - WGPUStencilOperation depthFailOp; - WGPUStencilOperation passOp; -} WGPUStencilFaceState WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPUStorageTextureBindingLayout { - WGPUChainedStruct const * nextInChain; - WGPUStorageTextureAccess access; - WGPUTextureFormat format; - WGPUTextureViewDimension viewDimension; -} WGPUStorageTextureBindingLayout WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPUSurfaceCapabilities { - WGPUChainedStructOut * nextInChain; - size_t formatCount; - WGPUTextureFormat const * formats; - size_t presentModeCount; - WGPUPresentMode const * presentModes; - size_t alphaModeCount; - WGPUCompositeAlphaMode const * alphaModes; -} WGPUSurfaceCapabilities WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPUSurfaceConfiguration { - WGPUChainedStruct const * nextInChain; - WGPUDevice device; - WGPUTextureFormat format; - WGPUTextureUsageFlags usage; - size_t viewFormatCount; - WGPUTextureFormat const * viewFormats; - WGPUCompositeAlphaMode alphaMode; - uint32_t width; - uint32_t height; - WGPUPresentMode presentMode; -} WGPUSurfaceConfiguration WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPUSurfaceDescriptor { - WGPUChainedStruct const * nextInChain; - WGPU_NULLABLE char const * label; -} WGPUSurfaceDescriptor WGPU_STRUCTURE_ATTRIBUTE; - -// Can be chained in WGPUSurfaceDescriptor -typedef struct WGPUSurfaceDescriptorFromCanvasHTMLSelector { - WGPUChainedStruct chain; - char const * selector; -} WGPUSurfaceDescriptorFromCanvasHTMLSelector WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPUSurfaceTexture { - WGPUTexture texture; - WGPUBool suboptimal; - WGPUSurfaceGetCurrentTextureStatus status; -} WGPUSurfaceTexture WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPUSwapChainDescriptor { - WGPUChainedStruct const * nextInChain; - WGPU_NULLABLE char const * label; - WGPUTextureUsageFlags usage; - WGPUTextureFormat format; - uint32_t width; - uint32_t height; - WGPUPresentMode presentMode; -} WGPUSwapChainDescriptor WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPUTextureBindingLayout { - WGPUChainedStruct const * nextInChain; - WGPUTextureSampleType sampleType; - WGPUTextureViewDimension viewDimension; - WGPUBool multisampled; -} WGPUTextureBindingLayout WGPU_STRUCTURE_ATTRIBUTE; - -// Can be chained in WGPUTextureDescriptor -typedef struct WGPUTextureBindingViewDimensionDescriptor { - WGPUChainedStruct chain; - WGPUTextureViewDimension textureBindingViewDimension; -} WGPUTextureBindingViewDimensionDescriptor WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPUTextureDataLayout { - WGPUChainedStruct const * nextInChain; - uint64_t offset; - uint32_t bytesPerRow; - uint32_t rowsPerImage; -} WGPUTextureDataLayout WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPUTextureViewDescriptor { - WGPUChainedStruct const * nextInChain; - WGPU_NULLABLE char const * label; - WGPUTextureFormat format; - WGPUTextureViewDimension dimension; - uint32_t baseMipLevel; - uint32_t mipLevelCount; - uint32_t baseArrayLayer; - uint32_t arrayLayerCount; - WGPUTextureAspect aspect; -} WGPUTextureViewDescriptor WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPUVertexAttribute { - WGPUVertexFormat format; - uint64_t offset; - uint32_t shaderLocation; -} WGPUVertexAttribute WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPUBindGroupDescriptor { - WGPUChainedStruct const * nextInChain; - WGPU_NULLABLE char const * label; - WGPUBindGroupLayout layout; - size_t entryCount; - WGPUBindGroupEntry const * entries; -} WGPUBindGroupDescriptor WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPUBindGroupLayoutEntry { - WGPUChainedStruct const * nextInChain; - uint32_t binding; - WGPUShaderStageFlags visibility; - WGPUBufferBindingLayout buffer; - WGPUSamplerBindingLayout sampler; - WGPUTextureBindingLayout texture; - WGPUStorageTextureBindingLayout storageTexture; -} WGPUBindGroupLayoutEntry WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPUBlendState { - WGPUBlendComponent color; - WGPUBlendComponent alpha; -} WGPUBlendState WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPUCompilationInfo { - WGPUChainedStruct const * nextInChain; - size_t messageCount; - WGPUCompilationMessage const * messages; -} WGPUCompilationInfo WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPUComputePassDescriptor { - WGPUChainedStruct const * nextInChain; - WGPU_NULLABLE char const * label; - WGPU_NULLABLE WGPUComputePassTimestampWrites const * timestampWrites; -} WGPUComputePassDescriptor WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPUDepthStencilState { - WGPUChainedStruct const * nextInChain; - WGPUTextureFormat format; - WGPUBool depthWriteEnabled; - WGPUCompareFunction depthCompare; - WGPUStencilFaceState stencilFront; - WGPUStencilFaceState stencilBack; - uint32_t stencilReadMask; - uint32_t stencilWriteMask; - int32_t depthBias; - float depthBiasSlopeScale; - float depthBiasClamp; -} WGPUDepthStencilState WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPUFutureWaitInfo { - WGPUFuture future; - WGPUBool completed; -} WGPUFutureWaitInfo WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPUImageCopyBuffer { - WGPUChainedStruct const * nextInChain; - WGPUTextureDataLayout layout; - WGPUBuffer buffer; -} WGPUImageCopyBuffer WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPUImageCopyTexture { - WGPUChainedStruct const * nextInChain; - WGPUTexture texture; - uint32_t mipLevel; - WGPUOrigin3D origin; - WGPUTextureAspect aspect; -} WGPUImageCopyTexture WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPUInstanceDescriptor { - WGPUChainedStruct const * nextInChain; - WGPUInstanceFeatures features; -} WGPUInstanceDescriptor WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPUProgrammableStageDescriptor { - WGPUChainedStruct const * nextInChain; - WGPUShaderModule module; - WGPU_NULLABLE char const * entryPoint; - size_t constantCount; - WGPUConstantEntry const * constants; -} WGPUProgrammableStageDescriptor WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPURenderPassColorAttachment { - WGPUChainedStruct const * nextInChain; - WGPU_NULLABLE WGPUTextureView view; - uint32_t depthSlice; - WGPU_NULLABLE WGPUTextureView resolveTarget; - WGPULoadOp loadOp; - WGPUStoreOp storeOp; - WGPUColor clearValue; -} WGPURenderPassColorAttachment WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPURequiredLimits { - WGPUChainedStruct const * nextInChain; - WGPULimits limits; -} WGPURequiredLimits WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPUSupportedLimits { - WGPUChainedStructOut * nextInChain; - WGPULimits limits; -} WGPUSupportedLimits WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPUTextureDescriptor { - WGPUChainedStruct const * nextInChain; - WGPU_NULLABLE char const * label; - WGPUTextureUsageFlags usage; - WGPUTextureDimension dimension; - WGPUExtent3D size; - WGPUTextureFormat format; - uint32_t mipLevelCount; - uint32_t sampleCount; - size_t viewFormatCount; - WGPUTextureFormat const * viewFormats; -} WGPUTextureDescriptor WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPUVertexBufferLayout { - uint64_t arrayStride; - WGPUVertexStepMode stepMode; - size_t attributeCount; - WGPUVertexAttribute const * attributes; -} WGPUVertexBufferLayout WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPUBindGroupLayoutDescriptor { - WGPUChainedStruct const * nextInChain; - WGPU_NULLABLE char const * label; - size_t entryCount; - WGPUBindGroupLayoutEntry const * entries; -} WGPUBindGroupLayoutDescriptor WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPUColorTargetState { - WGPUChainedStruct const * nextInChain; - WGPUTextureFormat format; - WGPU_NULLABLE WGPUBlendState const * blend; - WGPUColorWriteMaskFlags writeMask; -} WGPUColorTargetState WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPUComputePipelineDescriptor { - WGPUChainedStruct const * nextInChain; - WGPU_NULLABLE char const * label; - WGPU_NULLABLE WGPUPipelineLayout layout; - WGPUProgrammableStageDescriptor compute; -} WGPUComputePipelineDescriptor WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPUDeviceDescriptor { - WGPUChainedStruct const * nextInChain; - WGPU_NULLABLE char const * label; - size_t requiredFeatureCount; - WGPUFeatureName const * requiredFeatures; - WGPU_NULLABLE WGPURequiredLimits const * requiredLimits; - WGPUQueueDescriptor defaultQueue; - WGPUDeviceLostCallback deviceLostCallback; - void * deviceLostUserdata; -} WGPUDeviceDescriptor WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPURenderPassDescriptor { - WGPUChainedStruct const * nextInChain; - WGPU_NULLABLE char const * label; - size_t colorAttachmentCount; - WGPURenderPassColorAttachment const * colorAttachments; - WGPU_NULLABLE WGPURenderPassDepthStencilAttachment const * depthStencilAttachment; - WGPU_NULLABLE WGPUQuerySet occlusionQuerySet; - WGPU_NULLABLE WGPURenderPassTimestampWrites const * timestampWrites; -} WGPURenderPassDescriptor WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPUVertexState { - WGPUChainedStruct const * nextInChain; - WGPUShaderModule module; - WGPU_NULLABLE char const * entryPoint; - size_t constantCount; - WGPUConstantEntry const * constants; - size_t bufferCount; - WGPUVertexBufferLayout const * buffers; -} WGPUVertexState WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPUFragmentState { - WGPUChainedStruct const * nextInChain; - WGPUShaderModule module; - WGPU_NULLABLE char const * entryPoint; - size_t constantCount; - WGPUConstantEntry const * constants; - size_t targetCount; - WGPUColorTargetState const * targets; -} WGPUFragmentState WGPU_STRUCTURE_ATTRIBUTE; - -typedef struct WGPURenderPipelineDescriptor { - WGPUChainedStruct const * nextInChain; - WGPU_NULLABLE char const * label; - WGPU_NULLABLE WGPUPipelineLayout layout; - WGPUVertexState vertex; - WGPUPrimitiveState primitive; - WGPU_NULLABLE WGPUDepthStencilState const * depthStencil; - WGPUMultisampleState multisample; - WGPU_NULLABLE WGPUFragmentState const * fragment; -} WGPURenderPipelineDescriptor WGPU_STRUCTURE_ATTRIBUTE; - -#if defined(__cplusplus) && !defined(USE_WGPU_WAGYU_NAMESPACE) && !defined(__cppcheck) -extern "C" { -#endif - -#if !defined(WGPU_SKIP_PROCS) - -typedef void (*WGPUProcAdapterInfoFreeMembers)(WGPUAdapterInfo value) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcAdapterPropertiesFreeMembers)(WGPUAdapterProperties value) WGPU_FUNCTION_ATTRIBUTE; -typedef WGPUInstance (*WGPUProcCreateInstance)(WGPUInstanceDescriptor const * descriptor) WGPU_FUNCTION_ATTRIBUTE; -typedef WGPUBool (*WGPUProcGetInstanceFeatures)(WGPUInstanceFeatures * features) WGPU_FUNCTION_ATTRIBUTE; -typedef WGPUProc (*WGPUProcGetProcAddress)(WGPUDevice device, char const * procName) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcSurfaceCapabilitiesFreeMembers)(WGPUSurfaceCapabilities value) WGPU_FUNCTION_ATTRIBUTE; - -// Procs of Adapter -typedef size_t (*WGPUProcAdapterEnumerateFeatures)(WGPUAdapter adapter, WGPUFeatureName * features) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcAdapterGetInfo)(WGPUAdapter adapter, WGPUAdapterInfo * info) WGPU_FUNCTION_ATTRIBUTE; -typedef WGPUBool (*WGPUProcAdapterGetLimits)(WGPUAdapter adapter, WGPUSupportedLimits * limits) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcAdapterGetProperties)(WGPUAdapter adapter, WGPUAdapterProperties * properties) WGPU_FUNCTION_ATTRIBUTE; -typedef WGPUBool (*WGPUProcAdapterHasFeature)(WGPUAdapter adapter, WGPUFeatureName feature) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcAdapterRequestDevice)(WGPUAdapter adapter, WGPU_NULLABLE WGPUDeviceDescriptor const * descriptor, WGPURequestDeviceCallback callback, void * userdata) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcAdapterReference)(WGPUAdapter adapter) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcAdapterRelease)(WGPUAdapter adapter) WGPU_FUNCTION_ATTRIBUTE; - -// Procs of BindGroup -typedef void (*WGPUProcBindGroupSetLabel)(WGPUBindGroup bindGroup, char const * label) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcBindGroupReference)(WGPUBindGroup bindGroup) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcBindGroupRelease)(WGPUBindGroup bindGroup) WGPU_FUNCTION_ATTRIBUTE; - -// Procs of BindGroupLayout -typedef void (*WGPUProcBindGroupLayoutSetLabel)(WGPUBindGroupLayout bindGroupLayout, char const * label) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcBindGroupLayoutReference)(WGPUBindGroupLayout bindGroupLayout) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcBindGroupLayoutRelease)(WGPUBindGroupLayout bindGroupLayout) WGPU_FUNCTION_ATTRIBUTE; - -// Procs of Buffer -typedef void (*WGPUProcBufferDestroy)(WGPUBuffer buffer) WGPU_FUNCTION_ATTRIBUTE; -typedef void const * (*WGPUProcBufferGetConstMappedRange)(WGPUBuffer buffer, size_t offset, size_t size) WGPU_FUNCTION_ATTRIBUTE; -typedef WGPUBufferMapState (*WGPUProcBufferGetMapState)(WGPUBuffer buffer) WGPU_FUNCTION_ATTRIBUTE; -typedef void * (*WGPUProcBufferGetMappedRange)(WGPUBuffer buffer, size_t offset, size_t size) WGPU_FUNCTION_ATTRIBUTE; -typedef uint64_t (*WGPUProcBufferGetSize)(WGPUBuffer buffer) WGPU_FUNCTION_ATTRIBUTE; -typedef WGPUBufferUsageFlags (*WGPUProcBufferGetUsage)(WGPUBuffer buffer) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcBufferMapAsync)(WGPUBuffer buffer, WGPUMapModeFlags mode, size_t offset, size_t size, WGPUBufferMapCallback callback, void * userdata) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcBufferSetLabel)(WGPUBuffer buffer, char const * label) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcBufferUnmap)(WGPUBuffer buffer) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcBufferReference)(WGPUBuffer buffer) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcBufferRelease)(WGPUBuffer buffer) WGPU_FUNCTION_ATTRIBUTE; - -// Procs of CommandBuffer -typedef void (*WGPUProcCommandBufferSetLabel)(WGPUCommandBuffer commandBuffer, char const * label) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcCommandBufferReference)(WGPUCommandBuffer commandBuffer) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcCommandBufferRelease)(WGPUCommandBuffer commandBuffer) WGPU_FUNCTION_ATTRIBUTE; - -// Procs of CommandEncoder -typedef WGPUComputePassEncoder (*WGPUProcCommandEncoderBeginComputePass)(WGPUCommandEncoder commandEncoder, WGPU_NULLABLE WGPUComputePassDescriptor const * descriptor) WGPU_FUNCTION_ATTRIBUTE; -typedef WGPURenderPassEncoder (*WGPUProcCommandEncoderBeginRenderPass)(WGPUCommandEncoder commandEncoder, WGPURenderPassDescriptor const * descriptor) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcCommandEncoderClearBuffer)(WGPUCommandEncoder commandEncoder, WGPUBuffer buffer, uint64_t offset, uint64_t size) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcCommandEncoderCopyBufferToBuffer)(WGPUCommandEncoder commandEncoder, WGPUBuffer source, uint64_t sourceOffset, WGPUBuffer destination, uint64_t destinationOffset, uint64_t size) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcCommandEncoderCopyBufferToTexture)(WGPUCommandEncoder commandEncoder, WGPUImageCopyBuffer const * source, WGPUImageCopyTexture const * destination, WGPUExtent3D const * copySize) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcCommandEncoderCopyTextureToBuffer)(WGPUCommandEncoder commandEncoder, WGPUImageCopyTexture const * source, WGPUImageCopyBuffer const * destination, WGPUExtent3D const * copySize) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcCommandEncoderCopyTextureToTexture)(WGPUCommandEncoder commandEncoder, WGPUImageCopyTexture const * source, WGPUImageCopyTexture const * destination, WGPUExtent3D const * copySize) WGPU_FUNCTION_ATTRIBUTE; -typedef WGPUCommandBuffer (*WGPUProcCommandEncoderFinish)(WGPUCommandEncoder commandEncoder, WGPU_NULLABLE WGPUCommandBufferDescriptor const * descriptor) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcCommandEncoderInsertDebugMarker)(WGPUCommandEncoder commandEncoder, char const * markerLabel) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcCommandEncoderPopDebugGroup)(WGPUCommandEncoder commandEncoder) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcCommandEncoderPushDebugGroup)(WGPUCommandEncoder commandEncoder, char const * groupLabel) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcCommandEncoderResolveQuerySet)(WGPUCommandEncoder commandEncoder, WGPUQuerySet querySet, uint32_t firstQuery, uint32_t queryCount, WGPUBuffer destination, uint64_t destinationOffset) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcCommandEncoderSetLabel)(WGPUCommandEncoder commandEncoder, char const * label) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcCommandEncoderWriteTimestamp)(WGPUCommandEncoder commandEncoder, WGPUQuerySet querySet, uint32_t queryIndex) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcCommandEncoderReference)(WGPUCommandEncoder commandEncoder) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcCommandEncoderRelease)(WGPUCommandEncoder commandEncoder) WGPU_FUNCTION_ATTRIBUTE; - -// Procs of ComputePassEncoder -typedef void (*WGPUProcComputePassEncoderDispatchWorkgroups)(WGPUComputePassEncoder computePassEncoder, uint32_t workgroupCountX, uint32_t workgroupCountY, uint32_t workgroupCountZ) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcComputePassEncoderDispatchWorkgroupsIndirect)(WGPUComputePassEncoder computePassEncoder, WGPUBuffer indirectBuffer, uint64_t indirectOffset) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcComputePassEncoderEnd)(WGPUComputePassEncoder computePassEncoder) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcComputePassEncoderInsertDebugMarker)(WGPUComputePassEncoder computePassEncoder, char const * markerLabel) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcComputePassEncoderPopDebugGroup)(WGPUComputePassEncoder computePassEncoder) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcComputePassEncoderPushDebugGroup)(WGPUComputePassEncoder computePassEncoder, char const * groupLabel) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcComputePassEncoderSetBindGroup)(WGPUComputePassEncoder computePassEncoder, uint32_t groupIndex, WGPU_NULLABLE WGPUBindGroup group, size_t dynamicOffsetCount, uint32_t const * dynamicOffsets) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcComputePassEncoderSetLabel)(WGPUComputePassEncoder computePassEncoder, char const * label) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcComputePassEncoderSetPipeline)(WGPUComputePassEncoder computePassEncoder, WGPUComputePipeline pipeline) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcComputePassEncoderWriteTimestamp)(WGPUComputePassEncoder computePassEncoder, WGPUQuerySet querySet, uint32_t queryIndex) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcComputePassEncoderReference)(WGPUComputePassEncoder computePassEncoder) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcComputePassEncoderRelease)(WGPUComputePassEncoder computePassEncoder) WGPU_FUNCTION_ATTRIBUTE; - -// Procs of ComputePipeline -typedef WGPUBindGroupLayout (*WGPUProcComputePipelineGetBindGroupLayout)(WGPUComputePipeline computePipeline, uint32_t groupIndex) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcComputePipelineSetLabel)(WGPUComputePipeline computePipeline, char const * label) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcComputePipelineReference)(WGPUComputePipeline computePipeline) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcComputePipelineRelease)(WGPUComputePipeline computePipeline) WGPU_FUNCTION_ATTRIBUTE; - -// Procs of Device -typedef WGPUBindGroup (*WGPUProcDeviceCreateBindGroup)(WGPUDevice device, WGPUBindGroupDescriptor const * descriptor) WGPU_FUNCTION_ATTRIBUTE; -typedef WGPUBindGroupLayout (*WGPUProcDeviceCreateBindGroupLayout)(WGPUDevice device, WGPUBindGroupLayoutDescriptor const * descriptor) WGPU_FUNCTION_ATTRIBUTE; -typedef WGPUBuffer (*WGPUProcDeviceCreateBuffer)(WGPUDevice device, WGPUBufferDescriptor const * descriptor) WGPU_FUNCTION_ATTRIBUTE; -typedef WGPUCommandEncoder (*WGPUProcDeviceCreateCommandEncoder)(WGPUDevice device, WGPU_NULLABLE WGPUCommandEncoderDescriptor const * descriptor) WGPU_FUNCTION_ATTRIBUTE; -typedef WGPUComputePipeline (*WGPUProcDeviceCreateComputePipeline)(WGPUDevice device, WGPUComputePipelineDescriptor const * descriptor) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcDeviceCreateComputePipelineAsync)(WGPUDevice device, WGPUComputePipelineDescriptor const * descriptor, WGPUCreateComputePipelineAsyncCallback callback, void * userdata) WGPU_FUNCTION_ATTRIBUTE; -typedef WGPUPipelineLayout (*WGPUProcDeviceCreatePipelineLayout)(WGPUDevice device, WGPUPipelineLayoutDescriptor const * descriptor) WGPU_FUNCTION_ATTRIBUTE; -typedef WGPUQuerySet (*WGPUProcDeviceCreateQuerySet)(WGPUDevice device, WGPUQuerySetDescriptor const * descriptor) WGPU_FUNCTION_ATTRIBUTE; -typedef WGPURenderBundleEncoder (*WGPUProcDeviceCreateRenderBundleEncoder)(WGPUDevice device, WGPURenderBundleEncoderDescriptor const * descriptor) WGPU_FUNCTION_ATTRIBUTE; -typedef WGPURenderPipeline (*WGPUProcDeviceCreateRenderPipeline)(WGPUDevice device, WGPURenderPipelineDescriptor const * descriptor) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcDeviceCreateRenderPipelineAsync)(WGPUDevice device, WGPURenderPipelineDescriptor const * descriptor, WGPUCreateRenderPipelineAsyncCallback callback, void * userdata) WGPU_FUNCTION_ATTRIBUTE; -typedef WGPUSampler (*WGPUProcDeviceCreateSampler)(WGPUDevice device, WGPU_NULLABLE WGPUSamplerDescriptor const * descriptor) WGPU_FUNCTION_ATTRIBUTE; -typedef WGPUShaderModule (*WGPUProcDeviceCreateShaderModule)(WGPUDevice device, WGPUShaderModuleDescriptor const * descriptor) WGPU_FUNCTION_ATTRIBUTE; -typedef WGPUSwapChain (*WGPUProcDeviceCreateSwapChain)(WGPUDevice device, WGPUSurface surface, WGPUSwapChainDescriptor const * descriptor) WGPU_FUNCTION_ATTRIBUTE; -typedef WGPUTexture (*WGPUProcDeviceCreateTexture)(WGPUDevice device, WGPUTextureDescriptor const * descriptor) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcDeviceDestroy)(WGPUDevice device) WGPU_FUNCTION_ATTRIBUTE; -typedef size_t (*WGPUProcDeviceEnumerateFeatures)(WGPUDevice device, WGPUFeatureName * features) WGPU_FUNCTION_ATTRIBUTE; -typedef WGPUBool (*WGPUProcDeviceGetLimits)(WGPUDevice device, WGPUSupportedLimits * limits) WGPU_FUNCTION_ATTRIBUTE; -typedef WGPUQueue (*WGPUProcDeviceGetQueue)(WGPUDevice device) WGPU_FUNCTION_ATTRIBUTE; -typedef WGPUBool (*WGPUProcDeviceHasFeature)(WGPUDevice device, WGPUFeatureName feature) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcDevicePopErrorScope)(WGPUDevice device, WGPUErrorCallback callback, void * userdata) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcDevicePushErrorScope)(WGPUDevice device, WGPUErrorFilter filter) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcDeviceSetLabel)(WGPUDevice device, char const * label) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcDeviceSetUncapturedErrorCallback)(WGPUDevice device, WGPUErrorCallback callback, void * userdata) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcDeviceReference)(WGPUDevice device) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcDeviceRelease)(WGPUDevice device) WGPU_FUNCTION_ATTRIBUTE; - -// Procs of Instance -typedef WGPUSurface (*WGPUProcInstanceCreateSurface)(WGPUInstance instance, WGPUSurfaceDescriptor const * descriptor) WGPU_FUNCTION_ATTRIBUTE; -typedef WGPUBool (*WGPUProcInstanceHasWGSLLanguageFeature)(WGPUInstance instance, WGPUWGSLFeatureName feature) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcInstanceProcessEvents)(WGPUInstance instance) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcInstanceRequestAdapter)(WGPUInstance instance, WGPU_NULLABLE WGPURequestAdapterOptions const * options, WGPURequestAdapterCallback callback, void * userdata) WGPU_FUNCTION_ATTRIBUTE; -typedef WGPUWaitStatus (*WGPUProcInstanceWaitAny)(WGPUInstance instance, size_t futureCount, WGPUFutureWaitInfo * futures, uint64_t timeoutNS) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcInstanceReference)(WGPUInstance instance) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcInstanceRelease)(WGPUInstance instance) WGPU_FUNCTION_ATTRIBUTE; - -// Procs of PipelineLayout -typedef void (*WGPUProcPipelineLayoutSetLabel)(WGPUPipelineLayout pipelineLayout, char const * label) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcPipelineLayoutReference)(WGPUPipelineLayout pipelineLayout) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcPipelineLayoutRelease)(WGPUPipelineLayout pipelineLayout) WGPU_FUNCTION_ATTRIBUTE; - -// Procs of QuerySet -typedef void (*WGPUProcQuerySetDestroy)(WGPUQuerySet querySet) WGPU_FUNCTION_ATTRIBUTE; -typedef uint32_t (*WGPUProcQuerySetGetCount)(WGPUQuerySet querySet) WGPU_FUNCTION_ATTRIBUTE; -typedef WGPUQueryType (*WGPUProcQuerySetGetType)(WGPUQuerySet querySet) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcQuerySetSetLabel)(WGPUQuerySet querySet, char const * label) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcQuerySetReference)(WGPUQuerySet querySet) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcQuerySetRelease)(WGPUQuerySet querySet) WGPU_FUNCTION_ATTRIBUTE; - -// Procs of Queue -typedef void (*WGPUProcQueueOnSubmittedWorkDone)(WGPUQueue queue, WGPUQueueWorkDoneCallback callback, void * userdata) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcQueueSetLabel)(WGPUQueue queue, char const * label) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcQueueSubmit)(WGPUQueue queue, size_t commandCount, WGPUCommandBuffer const * commands) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcQueueWriteBuffer)(WGPUQueue queue, WGPUBuffer buffer, uint64_t bufferOffset, void const * data, size_t size) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcQueueWriteTexture)(WGPUQueue queue, WGPUImageCopyTexture const * destination, void const * data, size_t dataSize, WGPUTextureDataLayout const * dataLayout, WGPUExtent3D const * writeSize) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcQueueReference)(WGPUQueue queue) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcQueueRelease)(WGPUQueue queue) WGPU_FUNCTION_ATTRIBUTE; - -// Procs of RenderBundle -typedef void (*WGPUProcRenderBundleSetLabel)(WGPURenderBundle renderBundle, char const * label) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcRenderBundleReference)(WGPURenderBundle renderBundle) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcRenderBundleRelease)(WGPURenderBundle renderBundle) WGPU_FUNCTION_ATTRIBUTE; - -// Procs of RenderBundleEncoder -typedef void (*WGPUProcRenderBundleEncoderDraw)(WGPURenderBundleEncoder renderBundleEncoder, uint32_t vertexCount, uint32_t instanceCount, uint32_t firstVertex, uint32_t firstInstance) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcRenderBundleEncoderDrawIndexed)(WGPURenderBundleEncoder renderBundleEncoder, uint32_t indexCount, uint32_t instanceCount, uint32_t firstIndex, int32_t baseVertex, uint32_t firstInstance) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcRenderBundleEncoderDrawIndexedIndirect)(WGPURenderBundleEncoder renderBundleEncoder, WGPUBuffer indirectBuffer, uint64_t indirectOffset) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcRenderBundleEncoderDrawIndirect)(WGPURenderBundleEncoder renderBundleEncoder, WGPUBuffer indirectBuffer, uint64_t indirectOffset) WGPU_FUNCTION_ATTRIBUTE; -typedef WGPURenderBundle (*WGPUProcRenderBundleEncoderFinish)(WGPURenderBundleEncoder renderBundleEncoder, WGPU_NULLABLE WGPURenderBundleDescriptor const * descriptor) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcRenderBundleEncoderInsertDebugMarker)(WGPURenderBundleEncoder renderBundleEncoder, char const * markerLabel) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcRenderBundleEncoderPopDebugGroup)(WGPURenderBundleEncoder renderBundleEncoder) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcRenderBundleEncoderPushDebugGroup)(WGPURenderBundleEncoder renderBundleEncoder, char const * groupLabel) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcRenderBundleEncoderSetBindGroup)(WGPURenderBundleEncoder renderBundleEncoder, uint32_t groupIndex, WGPU_NULLABLE WGPUBindGroup group, size_t dynamicOffsetCount, uint32_t const * dynamicOffsets) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcRenderBundleEncoderSetIndexBuffer)(WGPURenderBundleEncoder renderBundleEncoder, WGPUBuffer buffer, WGPUIndexFormat format, uint64_t offset, uint64_t size) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcRenderBundleEncoderSetLabel)(WGPURenderBundleEncoder renderBundleEncoder, char const * label) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcRenderBundleEncoderSetPipeline)(WGPURenderBundleEncoder renderBundleEncoder, WGPURenderPipeline pipeline) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcRenderBundleEncoderSetVertexBuffer)(WGPURenderBundleEncoder renderBundleEncoder, uint32_t slot, WGPU_NULLABLE WGPUBuffer buffer, uint64_t offset, uint64_t size) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcRenderBundleEncoderReference)(WGPURenderBundleEncoder renderBundleEncoder) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcRenderBundleEncoderRelease)(WGPURenderBundleEncoder renderBundleEncoder) WGPU_FUNCTION_ATTRIBUTE; - -// Procs of RenderPassEncoder -typedef void (*WGPUProcRenderPassEncoderBeginOcclusionQuery)(WGPURenderPassEncoder renderPassEncoder, uint32_t queryIndex) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcRenderPassEncoderDraw)(WGPURenderPassEncoder renderPassEncoder, uint32_t vertexCount, uint32_t instanceCount, uint32_t firstVertex, uint32_t firstInstance) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcRenderPassEncoderDrawIndexed)(WGPURenderPassEncoder renderPassEncoder, uint32_t indexCount, uint32_t instanceCount, uint32_t firstIndex, int32_t baseVertex, uint32_t firstInstance) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcRenderPassEncoderDrawIndexedIndirect)(WGPURenderPassEncoder renderPassEncoder, WGPUBuffer indirectBuffer, uint64_t indirectOffset) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcRenderPassEncoderDrawIndirect)(WGPURenderPassEncoder renderPassEncoder, WGPUBuffer indirectBuffer, uint64_t indirectOffset) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcRenderPassEncoderEnd)(WGPURenderPassEncoder renderPassEncoder) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcRenderPassEncoderEndOcclusionQuery)(WGPURenderPassEncoder renderPassEncoder) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcRenderPassEncoderExecuteBundles)(WGPURenderPassEncoder renderPassEncoder, size_t bundleCount, WGPURenderBundle const * bundles) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcRenderPassEncoderInsertDebugMarker)(WGPURenderPassEncoder renderPassEncoder, char const * markerLabel) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcRenderPassEncoderPopDebugGroup)(WGPURenderPassEncoder renderPassEncoder) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcRenderPassEncoderPushDebugGroup)(WGPURenderPassEncoder renderPassEncoder, char const * groupLabel) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcRenderPassEncoderSetBindGroup)(WGPURenderPassEncoder renderPassEncoder, uint32_t groupIndex, WGPU_NULLABLE WGPUBindGroup group, size_t dynamicOffsetCount, uint32_t const * dynamicOffsets) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcRenderPassEncoderSetBlendConstant)(WGPURenderPassEncoder renderPassEncoder, WGPUColor const * color) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcRenderPassEncoderSetIndexBuffer)(WGPURenderPassEncoder renderPassEncoder, WGPUBuffer buffer, WGPUIndexFormat format, uint64_t offset, uint64_t size) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcRenderPassEncoderSetLabel)(WGPURenderPassEncoder renderPassEncoder, char const * label) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcRenderPassEncoderSetPipeline)(WGPURenderPassEncoder renderPassEncoder, WGPURenderPipeline pipeline) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcRenderPassEncoderSetScissorRect)(WGPURenderPassEncoder renderPassEncoder, uint32_t x, uint32_t y, uint32_t width, uint32_t height) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcRenderPassEncoderSetStencilReference)(WGPURenderPassEncoder renderPassEncoder, uint32_t reference) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcRenderPassEncoderSetVertexBuffer)(WGPURenderPassEncoder renderPassEncoder, uint32_t slot, WGPU_NULLABLE WGPUBuffer buffer, uint64_t offset, uint64_t size) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcRenderPassEncoderSetViewport)(WGPURenderPassEncoder renderPassEncoder, float x, float y, float width, float height, float minDepth, float maxDepth) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcRenderPassEncoderWriteTimestamp)(WGPURenderPassEncoder renderPassEncoder, WGPUQuerySet querySet, uint32_t queryIndex) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcRenderPassEncoderReference)(WGPURenderPassEncoder renderPassEncoder) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcRenderPassEncoderRelease)(WGPURenderPassEncoder renderPassEncoder) WGPU_FUNCTION_ATTRIBUTE; - -// Procs of RenderPipeline -typedef WGPUBindGroupLayout (*WGPUProcRenderPipelineGetBindGroupLayout)(WGPURenderPipeline renderPipeline, uint32_t groupIndex) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcRenderPipelineSetLabel)(WGPURenderPipeline renderPipeline, char const * label) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcRenderPipelineReference)(WGPURenderPipeline renderPipeline) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcRenderPipelineRelease)(WGPURenderPipeline renderPipeline) WGPU_FUNCTION_ATTRIBUTE; - -// Procs of Sampler -typedef void (*WGPUProcSamplerSetLabel)(WGPUSampler sampler, char const * label) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcSamplerReference)(WGPUSampler sampler) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcSamplerRelease)(WGPUSampler sampler) WGPU_FUNCTION_ATTRIBUTE; - -// Procs of ShaderModule -typedef void (*WGPUProcShaderModuleGetCompilationInfo)(WGPUShaderModule shaderModule, WGPUCompilationInfoCallback callback, void * userdata) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcShaderModuleSetLabel)(WGPUShaderModule shaderModule, char const * label) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcShaderModuleReference)(WGPUShaderModule shaderModule) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcShaderModuleRelease)(WGPUShaderModule shaderModule) WGPU_FUNCTION_ATTRIBUTE; - -// Procs of Surface -typedef void (*WGPUProcSurfaceConfigure)(WGPUSurface surface, WGPUSurfaceConfiguration const * config) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcSurfaceGetCapabilities)(WGPUSurface surface, WGPUAdapter adapter, WGPUSurfaceCapabilities * capabilities) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcSurfaceGetCurrentTexture)(WGPUSurface surface, WGPUSurfaceTexture * surfaceTexture) WGPU_FUNCTION_ATTRIBUTE; -typedef WGPUTextureFormat (*WGPUProcSurfaceGetPreferredFormat)(WGPUSurface surface, WGPUAdapter adapter) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcSurfacePresent)(WGPUSurface surface) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcSurfaceUnconfigure)(WGPUSurface surface) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcSurfaceReference)(WGPUSurface surface) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcSurfaceRelease)(WGPUSurface surface) WGPU_FUNCTION_ATTRIBUTE; - -// Procs of SwapChain -typedef WGPUTexture (*WGPUProcSwapChainGetCurrentTexture)(WGPUSwapChain swapChain) WGPU_FUNCTION_ATTRIBUTE; -typedef WGPUTextureView (*WGPUProcSwapChainGetCurrentTextureView)(WGPUSwapChain swapChain) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcSwapChainPresent)(WGPUSwapChain swapChain) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcSwapChainReference)(WGPUSwapChain swapChain) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcSwapChainRelease)(WGPUSwapChain swapChain) WGPU_FUNCTION_ATTRIBUTE; - -// Procs of Texture -typedef WGPUTextureView (*WGPUProcTextureCreateView)(WGPUTexture texture, WGPU_NULLABLE WGPUTextureViewDescriptor const * descriptor) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcTextureDestroy)(WGPUTexture texture) WGPU_FUNCTION_ATTRIBUTE; -typedef uint32_t (*WGPUProcTextureGetDepthOrArrayLayers)(WGPUTexture texture) WGPU_FUNCTION_ATTRIBUTE; -typedef WGPUTextureDimension (*WGPUProcTextureGetDimension)(WGPUTexture texture) WGPU_FUNCTION_ATTRIBUTE; -typedef WGPUTextureFormat (*WGPUProcTextureGetFormat)(WGPUTexture texture) WGPU_FUNCTION_ATTRIBUTE; -typedef uint32_t (*WGPUProcTextureGetHeight)(WGPUTexture texture) WGPU_FUNCTION_ATTRIBUTE; -typedef uint32_t (*WGPUProcTextureGetMipLevelCount)(WGPUTexture texture) WGPU_FUNCTION_ATTRIBUTE; -typedef uint32_t (*WGPUProcTextureGetSampleCount)(WGPUTexture texture) WGPU_FUNCTION_ATTRIBUTE; -typedef WGPUTextureUsageFlags (*WGPUProcTextureGetUsage)(WGPUTexture texture) WGPU_FUNCTION_ATTRIBUTE; -typedef uint32_t (*WGPUProcTextureGetWidth)(WGPUTexture texture) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcTextureSetLabel)(WGPUTexture texture, char const * label) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcTextureReference)(WGPUTexture texture) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcTextureRelease)(WGPUTexture texture) WGPU_FUNCTION_ATTRIBUTE; - -// Procs of TextureView -typedef void (*WGPUProcTextureViewSetLabel)(WGPUTextureView textureView, char const * label) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcTextureViewReference)(WGPUTextureView textureView) WGPU_FUNCTION_ATTRIBUTE; -typedef void (*WGPUProcTextureViewRelease)(WGPUTextureView textureView) WGPU_FUNCTION_ATTRIBUTE; - - -#endif // !defined(WGPU_SKIP_PROCS) - -#if !defined(WGPU_SKIP_DECLARATIONS) - -WGPU_EXPORT void wgpuAdapterInfoFreeMembers(WGPUAdapterInfo value) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuAdapterPropertiesFreeMembers(WGPUAdapterProperties value) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT WGPUInstance wgpuCreateInstance(WGPU_NULLABLE WGPUInstanceDescriptor const * descriptor) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT WGPUBool wgpuGetInstanceFeatures(WGPUInstanceFeatures * features) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT WGPUProc wgpuGetProcAddress(WGPU_NULLABLE WGPUDevice device, char const * procName) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuSurfaceCapabilitiesFreeMembers(WGPUSurfaceCapabilities value) WGPU_FUNCTION_ATTRIBUTE; - -// Methods of Adapter -WGPU_EXPORT size_t wgpuAdapterEnumerateFeatures(WGPUAdapter adapter, WGPUFeatureName * features) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuAdapterGetInfo(WGPUAdapter adapter, WGPUAdapterInfo * info) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT WGPUBool wgpuAdapterGetLimits(WGPUAdapter adapter, WGPUSupportedLimits * limits) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuAdapterGetProperties(WGPUAdapter adapter, WGPUAdapterProperties * properties) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT WGPUBool wgpuAdapterHasFeature(WGPUAdapter adapter, WGPUFeatureName feature) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuAdapterRequestDevice(WGPUAdapter adapter, WGPU_NULLABLE WGPUDeviceDescriptor const * descriptor, WGPURequestDeviceCallback callback, void * userdata) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuAdapterReference(WGPUAdapter adapter) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuAdapterRelease(WGPUAdapter adapter) WGPU_FUNCTION_ATTRIBUTE; - -// Methods of BindGroup -WGPU_EXPORT void wgpuBindGroupSetLabel(WGPUBindGroup bindGroup, char const * label) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuBindGroupReference(WGPUBindGroup bindGroup) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuBindGroupRelease(WGPUBindGroup bindGroup) WGPU_FUNCTION_ATTRIBUTE; - -// Methods of BindGroupLayout -WGPU_EXPORT void wgpuBindGroupLayoutSetLabel(WGPUBindGroupLayout bindGroupLayout, char const * label) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuBindGroupLayoutReference(WGPUBindGroupLayout bindGroupLayout) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuBindGroupLayoutRelease(WGPUBindGroupLayout bindGroupLayout) WGPU_FUNCTION_ATTRIBUTE; - -// Methods of Buffer -WGPU_EXPORT void wgpuBufferDestroy(WGPUBuffer buffer) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void const * wgpuBufferGetConstMappedRange(WGPUBuffer buffer, size_t offset, size_t size) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT WGPUBufferMapState wgpuBufferGetMapState(WGPUBuffer buffer) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void * wgpuBufferGetMappedRange(WGPUBuffer buffer, size_t offset, size_t size) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT uint64_t wgpuBufferGetSize(WGPUBuffer buffer) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT WGPUBufferUsageFlags wgpuBufferGetUsage(WGPUBuffer buffer) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuBufferMapAsync(WGPUBuffer buffer, WGPUMapModeFlags mode, size_t offset, size_t size, WGPUBufferMapCallback callback, void * userdata) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuBufferSetLabel(WGPUBuffer buffer, char const * label) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuBufferUnmap(WGPUBuffer buffer) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuBufferReference(WGPUBuffer buffer) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuBufferRelease(WGPUBuffer buffer) WGPU_FUNCTION_ATTRIBUTE; - -// Methods of CommandBuffer -WGPU_EXPORT void wgpuCommandBufferSetLabel(WGPUCommandBuffer commandBuffer, char const * label) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuCommandBufferReference(WGPUCommandBuffer commandBuffer) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuCommandBufferRelease(WGPUCommandBuffer commandBuffer) WGPU_FUNCTION_ATTRIBUTE; - -// Methods of CommandEncoder -WGPU_EXPORT WGPUComputePassEncoder wgpuCommandEncoderBeginComputePass(WGPUCommandEncoder commandEncoder, WGPU_NULLABLE WGPUComputePassDescriptor const * descriptor) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT WGPURenderPassEncoder wgpuCommandEncoderBeginRenderPass(WGPUCommandEncoder commandEncoder, WGPURenderPassDescriptor const * descriptor) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuCommandEncoderClearBuffer(WGPUCommandEncoder commandEncoder, WGPUBuffer buffer, uint64_t offset, uint64_t size) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuCommandEncoderCopyBufferToBuffer(WGPUCommandEncoder commandEncoder, WGPUBuffer source, uint64_t sourceOffset, WGPUBuffer destination, uint64_t destinationOffset, uint64_t size) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuCommandEncoderCopyBufferToTexture(WGPUCommandEncoder commandEncoder, WGPUImageCopyBuffer const * source, WGPUImageCopyTexture const * destination, WGPUExtent3D const * copySize) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuCommandEncoderCopyTextureToBuffer(WGPUCommandEncoder commandEncoder, WGPUImageCopyTexture const * source, WGPUImageCopyBuffer const * destination, WGPUExtent3D const * copySize) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuCommandEncoderCopyTextureToTexture(WGPUCommandEncoder commandEncoder, WGPUImageCopyTexture const * source, WGPUImageCopyTexture const * destination, WGPUExtent3D const * copySize) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT WGPUCommandBuffer wgpuCommandEncoderFinish(WGPUCommandEncoder commandEncoder, WGPU_NULLABLE WGPUCommandBufferDescriptor const * descriptor) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuCommandEncoderInsertDebugMarker(WGPUCommandEncoder commandEncoder, char const * markerLabel) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuCommandEncoderPopDebugGroup(WGPUCommandEncoder commandEncoder) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuCommandEncoderPushDebugGroup(WGPUCommandEncoder commandEncoder, char const * groupLabel) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuCommandEncoderResolveQuerySet(WGPUCommandEncoder commandEncoder, WGPUQuerySet querySet, uint32_t firstQuery, uint32_t queryCount, WGPUBuffer destination, uint64_t destinationOffset) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuCommandEncoderSetLabel(WGPUCommandEncoder commandEncoder, char const * label) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuCommandEncoderWriteTimestamp(WGPUCommandEncoder commandEncoder, WGPUQuerySet querySet, uint32_t queryIndex) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuCommandEncoderReference(WGPUCommandEncoder commandEncoder) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuCommandEncoderRelease(WGPUCommandEncoder commandEncoder) WGPU_FUNCTION_ATTRIBUTE; - -// Methods of ComputePassEncoder -WGPU_EXPORT void wgpuComputePassEncoderDispatchWorkgroups(WGPUComputePassEncoder computePassEncoder, uint32_t workgroupCountX, uint32_t workgroupCountY, uint32_t workgroupCountZ) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuComputePassEncoderDispatchWorkgroupsIndirect(WGPUComputePassEncoder computePassEncoder, WGPUBuffer indirectBuffer, uint64_t indirectOffset) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuComputePassEncoderEnd(WGPUComputePassEncoder computePassEncoder) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuComputePassEncoderInsertDebugMarker(WGPUComputePassEncoder computePassEncoder, char const * markerLabel) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuComputePassEncoderPopDebugGroup(WGPUComputePassEncoder computePassEncoder) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuComputePassEncoderPushDebugGroup(WGPUComputePassEncoder computePassEncoder, char const * groupLabel) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuComputePassEncoderSetBindGroup(WGPUComputePassEncoder computePassEncoder, uint32_t groupIndex, WGPU_NULLABLE WGPUBindGroup group, size_t dynamicOffsetCount, uint32_t const * dynamicOffsets) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuComputePassEncoderSetLabel(WGPUComputePassEncoder computePassEncoder, char const * label) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuComputePassEncoderSetPipeline(WGPUComputePassEncoder computePassEncoder, WGPUComputePipeline pipeline) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuComputePassEncoderWriteTimestamp(WGPUComputePassEncoder computePassEncoder, WGPUQuerySet querySet, uint32_t queryIndex) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuComputePassEncoderReference(WGPUComputePassEncoder computePassEncoder) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuComputePassEncoderRelease(WGPUComputePassEncoder computePassEncoder) WGPU_FUNCTION_ATTRIBUTE; - -// Methods of ComputePipeline -WGPU_EXPORT WGPUBindGroupLayout wgpuComputePipelineGetBindGroupLayout(WGPUComputePipeline computePipeline, uint32_t groupIndex) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuComputePipelineSetLabel(WGPUComputePipeline computePipeline, char const * label) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuComputePipelineReference(WGPUComputePipeline computePipeline) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuComputePipelineRelease(WGPUComputePipeline computePipeline) WGPU_FUNCTION_ATTRIBUTE; - -// Methods of Device -WGPU_EXPORT WGPUBindGroup wgpuDeviceCreateBindGroup(WGPUDevice device, WGPUBindGroupDescriptor const * descriptor) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT WGPUBindGroupLayout wgpuDeviceCreateBindGroupLayout(WGPUDevice device, WGPUBindGroupLayoutDescriptor const * descriptor) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT WGPUBuffer wgpuDeviceCreateBuffer(WGPUDevice device, WGPUBufferDescriptor const * descriptor) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT WGPUCommandEncoder wgpuDeviceCreateCommandEncoder(WGPUDevice device, WGPU_NULLABLE WGPUCommandEncoderDescriptor const * descriptor) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT WGPUComputePipeline wgpuDeviceCreateComputePipeline(WGPUDevice device, WGPUComputePipelineDescriptor const * descriptor) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuDeviceCreateComputePipelineAsync(WGPUDevice device, WGPUComputePipelineDescriptor const * descriptor, WGPUCreateComputePipelineAsyncCallback callback, void * userdata) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT WGPUPipelineLayout wgpuDeviceCreatePipelineLayout(WGPUDevice device, WGPUPipelineLayoutDescriptor const * descriptor) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT WGPUQuerySet wgpuDeviceCreateQuerySet(WGPUDevice device, WGPUQuerySetDescriptor const * descriptor) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT WGPURenderBundleEncoder wgpuDeviceCreateRenderBundleEncoder(WGPUDevice device, WGPURenderBundleEncoderDescriptor const * descriptor) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT WGPURenderPipeline wgpuDeviceCreateRenderPipeline(WGPUDevice device, WGPURenderPipelineDescriptor const * descriptor) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuDeviceCreateRenderPipelineAsync(WGPUDevice device, WGPURenderPipelineDescriptor const * descriptor, WGPUCreateRenderPipelineAsyncCallback callback, void * userdata) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT WGPUSampler wgpuDeviceCreateSampler(WGPUDevice device, WGPU_NULLABLE WGPUSamplerDescriptor const * descriptor) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT WGPUShaderModule wgpuDeviceCreateShaderModule(WGPUDevice device, WGPUShaderModuleDescriptor const * descriptor) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT WGPUSwapChain wgpuDeviceCreateSwapChain(WGPUDevice device, WGPUSurface surface, WGPUSwapChainDescriptor const * descriptor) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT WGPUTexture wgpuDeviceCreateTexture(WGPUDevice device, WGPUTextureDescriptor const * descriptor) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuDeviceDestroy(WGPUDevice device) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT size_t wgpuDeviceEnumerateFeatures(WGPUDevice device, WGPUFeatureName * features) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT WGPUBool wgpuDeviceGetLimits(WGPUDevice device, WGPUSupportedLimits * limits) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT WGPUQueue wgpuDeviceGetQueue(WGPUDevice device) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT WGPUBool wgpuDeviceHasFeature(WGPUDevice device, WGPUFeatureName feature) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuDevicePopErrorScope(WGPUDevice device, WGPUErrorCallback callback, void * userdata) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuDevicePushErrorScope(WGPUDevice device, WGPUErrorFilter filter) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuDeviceSetLabel(WGPUDevice device, char const * label) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuDeviceSetUncapturedErrorCallback(WGPUDevice device, WGPUErrorCallback callback, void * userdata) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuDeviceReference(WGPUDevice device) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuDeviceRelease(WGPUDevice device) WGPU_FUNCTION_ATTRIBUTE; - -// Methods of Instance -WGPU_EXPORT WGPUSurface wgpuInstanceCreateSurface(WGPUInstance instance, WGPUSurfaceDescriptor const * descriptor) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT WGPUBool wgpuInstanceHasWGSLLanguageFeature(WGPUInstance instance, WGPUWGSLFeatureName feature) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuInstanceProcessEvents(WGPUInstance instance) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuInstanceRequestAdapter(WGPUInstance instance, WGPU_NULLABLE WGPURequestAdapterOptions const * options, WGPURequestAdapterCallback callback, void * userdata) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuInstanceReference(WGPUInstance instance) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuInstanceRelease(WGPUInstance instance) WGPU_FUNCTION_ATTRIBUTE; - -// Methods of PipelineLayout -WGPU_EXPORT void wgpuPipelineLayoutSetLabel(WGPUPipelineLayout pipelineLayout, char const * label) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuPipelineLayoutReference(WGPUPipelineLayout pipelineLayout) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuPipelineLayoutRelease(WGPUPipelineLayout pipelineLayout) WGPU_FUNCTION_ATTRIBUTE; - -// Methods of QuerySet -WGPU_EXPORT void wgpuQuerySetDestroy(WGPUQuerySet querySet) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT uint32_t wgpuQuerySetGetCount(WGPUQuerySet querySet) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT WGPUQueryType wgpuQuerySetGetType(WGPUQuerySet querySet) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuQuerySetSetLabel(WGPUQuerySet querySet, char const * label) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuQuerySetReference(WGPUQuerySet querySet) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuQuerySetRelease(WGPUQuerySet querySet) WGPU_FUNCTION_ATTRIBUTE; - -// Methods of Queue -WGPU_EXPORT void wgpuQueueOnSubmittedWorkDone(WGPUQueue queue, WGPUQueueWorkDoneCallback callback, void * userdata) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuQueueSetLabel(WGPUQueue queue, char const * label) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuQueueSubmit(WGPUQueue queue, size_t commandCount, WGPUCommandBuffer const * commands) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuQueueWriteBuffer(WGPUQueue queue, WGPUBuffer buffer, uint64_t bufferOffset, void const * data, size_t size) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuQueueWriteTexture(WGPUQueue queue, WGPUImageCopyTexture const * destination, void const * data, size_t dataSize, WGPUTextureDataLayout const * dataLayout, WGPUExtent3D const * writeSize) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuQueueReference(WGPUQueue queue) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuQueueRelease(WGPUQueue queue) WGPU_FUNCTION_ATTRIBUTE; - -// Methods of RenderBundle -WGPU_EXPORT void wgpuRenderBundleSetLabel(WGPURenderBundle renderBundle, char const * label) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuRenderBundleReference(WGPURenderBundle renderBundle) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuRenderBundleRelease(WGPURenderBundle renderBundle) WGPU_FUNCTION_ATTRIBUTE; - -// Methods of RenderBundleEncoder -WGPU_EXPORT void wgpuRenderBundleEncoderDraw(WGPURenderBundleEncoder renderBundleEncoder, uint32_t vertexCount, uint32_t instanceCount, uint32_t firstVertex, uint32_t firstInstance) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuRenderBundleEncoderDrawIndexed(WGPURenderBundleEncoder renderBundleEncoder, uint32_t indexCount, uint32_t instanceCount, uint32_t firstIndex, int32_t baseVertex, uint32_t firstInstance) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuRenderBundleEncoderDrawIndexedIndirect(WGPURenderBundleEncoder renderBundleEncoder, WGPUBuffer indirectBuffer, uint64_t indirectOffset) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuRenderBundleEncoderDrawIndirect(WGPURenderBundleEncoder renderBundleEncoder, WGPUBuffer indirectBuffer, uint64_t indirectOffset) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT WGPURenderBundle wgpuRenderBundleEncoderFinish(WGPURenderBundleEncoder renderBundleEncoder, WGPU_NULLABLE WGPURenderBundleDescriptor const * descriptor) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuRenderBundleEncoderInsertDebugMarker(WGPURenderBundleEncoder renderBundleEncoder, char const * markerLabel) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuRenderBundleEncoderPopDebugGroup(WGPURenderBundleEncoder renderBundleEncoder) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuRenderBundleEncoderPushDebugGroup(WGPURenderBundleEncoder renderBundleEncoder, char const * groupLabel) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuRenderBundleEncoderSetBindGroup(WGPURenderBundleEncoder renderBundleEncoder, uint32_t groupIndex, WGPU_NULLABLE WGPUBindGroup group, size_t dynamicOffsetCount, uint32_t const * dynamicOffsets) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuRenderBundleEncoderSetIndexBuffer(WGPURenderBundleEncoder renderBundleEncoder, WGPUBuffer buffer, WGPUIndexFormat format, uint64_t offset, uint64_t size) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuRenderBundleEncoderSetLabel(WGPURenderBundleEncoder renderBundleEncoder, char const * label) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuRenderBundleEncoderSetPipeline(WGPURenderBundleEncoder renderBundleEncoder, WGPURenderPipeline pipeline) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuRenderBundleEncoderSetVertexBuffer(WGPURenderBundleEncoder renderBundleEncoder, uint32_t slot, WGPU_NULLABLE WGPUBuffer buffer, uint64_t offset, uint64_t size) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuRenderBundleEncoderReference(WGPURenderBundleEncoder renderBundleEncoder) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuRenderBundleEncoderRelease(WGPURenderBundleEncoder renderBundleEncoder) WGPU_FUNCTION_ATTRIBUTE; - -// Methods of RenderPassEncoder -WGPU_EXPORT void wgpuRenderPassEncoderBeginOcclusionQuery(WGPURenderPassEncoder renderPassEncoder, uint32_t queryIndex) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuRenderPassEncoderDraw(WGPURenderPassEncoder renderPassEncoder, uint32_t vertexCount, uint32_t instanceCount, uint32_t firstVertex, uint32_t firstInstance) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuRenderPassEncoderDrawIndexed(WGPURenderPassEncoder renderPassEncoder, uint32_t indexCount, uint32_t instanceCount, uint32_t firstIndex, int32_t baseVertex, uint32_t firstInstance) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuRenderPassEncoderDrawIndexedIndirect(WGPURenderPassEncoder renderPassEncoder, WGPUBuffer indirectBuffer, uint64_t indirectOffset) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuRenderPassEncoderDrawIndirect(WGPURenderPassEncoder renderPassEncoder, WGPUBuffer indirectBuffer, uint64_t indirectOffset) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuRenderPassEncoderEnd(WGPURenderPassEncoder renderPassEncoder) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuRenderPassEncoderEndOcclusionQuery(WGPURenderPassEncoder renderPassEncoder) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuRenderPassEncoderExecuteBundles(WGPURenderPassEncoder renderPassEncoder, size_t bundleCount, WGPURenderBundle const * bundles) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuRenderPassEncoderInsertDebugMarker(WGPURenderPassEncoder renderPassEncoder, char const * markerLabel) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuRenderPassEncoderPopDebugGroup(WGPURenderPassEncoder renderPassEncoder) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuRenderPassEncoderPushDebugGroup(WGPURenderPassEncoder renderPassEncoder, char const * groupLabel) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuRenderPassEncoderSetBindGroup(WGPURenderPassEncoder renderPassEncoder, uint32_t groupIndex, WGPU_NULLABLE WGPUBindGroup group, size_t dynamicOffsetCount, uint32_t const * dynamicOffsets) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuRenderPassEncoderSetBlendConstant(WGPURenderPassEncoder renderPassEncoder, WGPUColor const * color) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuRenderPassEncoderSetIndexBuffer(WGPURenderPassEncoder renderPassEncoder, WGPUBuffer buffer, WGPUIndexFormat format, uint64_t offset, uint64_t size) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuRenderPassEncoderSetLabel(WGPURenderPassEncoder renderPassEncoder, char const * label) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuRenderPassEncoderSetPipeline(WGPURenderPassEncoder renderPassEncoder, WGPURenderPipeline pipeline) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuRenderPassEncoderSetScissorRect(WGPURenderPassEncoder renderPassEncoder, uint32_t x, uint32_t y, uint32_t width, uint32_t height) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuRenderPassEncoderSetStencilReference(WGPURenderPassEncoder renderPassEncoder, uint32_t reference) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuRenderPassEncoderSetVertexBuffer(WGPURenderPassEncoder renderPassEncoder, uint32_t slot, WGPU_NULLABLE WGPUBuffer buffer, uint64_t offset, uint64_t size) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuRenderPassEncoderSetViewport(WGPURenderPassEncoder renderPassEncoder, float x, float y, float width, float height, float minDepth, float maxDepth) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuRenderPassEncoderWriteTimestamp(WGPURenderPassEncoder renderPassEncoder, WGPUQuerySet querySet, uint32_t queryIndex) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuRenderPassEncoderReference(WGPURenderPassEncoder renderPassEncoder) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuRenderPassEncoderRelease(WGPURenderPassEncoder renderPassEncoder) WGPU_FUNCTION_ATTRIBUTE; - -// Methods of RenderPipeline -WGPU_EXPORT WGPUBindGroupLayout wgpuRenderPipelineGetBindGroupLayout(WGPURenderPipeline renderPipeline, uint32_t groupIndex) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuRenderPipelineSetLabel(WGPURenderPipeline renderPipeline, char const * label) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuRenderPipelineReference(WGPURenderPipeline renderPipeline) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuRenderPipelineRelease(WGPURenderPipeline renderPipeline) WGPU_FUNCTION_ATTRIBUTE; - -// Methods of Sampler -WGPU_EXPORT void wgpuSamplerSetLabel(WGPUSampler sampler, char const * label) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuSamplerReference(WGPUSampler sampler) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuSamplerRelease(WGPUSampler sampler) WGPU_FUNCTION_ATTRIBUTE; - -// Methods of ShaderModule -WGPU_EXPORT void wgpuShaderModuleGetCompilationInfo(WGPUShaderModule shaderModule, WGPUCompilationInfoCallback callback, void * userdata) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuShaderModuleSetLabel(WGPUShaderModule shaderModule, char const * label) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuShaderModuleReference(WGPUShaderModule shaderModule) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuShaderModuleRelease(WGPUShaderModule shaderModule) WGPU_FUNCTION_ATTRIBUTE; - -// Methods of Surface -WGPU_EXPORT void wgpuSurfaceConfigure(WGPUSurface surface, WGPUSurfaceConfiguration const * config) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuSurfaceGetCapabilities(WGPUSurface surface, WGPUAdapter adapter, WGPUSurfaceCapabilities * capabilities) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuSurfaceGetCurrentTexture(WGPUSurface surface, WGPUSurfaceTexture * surfaceTexture) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT WGPUTextureFormat wgpuSurfaceGetPreferredFormat(WGPUSurface surface, WGPUAdapter adapter) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuSurfacePresent(WGPUSurface surface) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuSurfaceUnconfigure(WGPUSurface surface) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuSurfaceReference(WGPUSurface surface) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuSurfaceRelease(WGPUSurface surface) WGPU_FUNCTION_ATTRIBUTE; - -// Methods of SwapChain -WGPU_EXPORT WGPUTexture wgpuSwapChainGetCurrentTexture(WGPUSwapChain swapChain) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT WGPUTextureView wgpuSwapChainGetCurrentTextureView(WGPUSwapChain swapChain) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuSwapChainPresent(WGPUSwapChain swapChain) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuSwapChainReference(WGPUSwapChain swapChain) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuSwapChainRelease(WGPUSwapChain swapChain) WGPU_FUNCTION_ATTRIBUTE; - -// Methods of Texture -WGPU_EXPORT WGPUTextureView wgpuTextureCreateView(WGPUTexture texture, WGPU_NULLABLE WGPUTextureViewDescriptor const * descriptor) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuTextureDestroy(WGPUTexture texture) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT uint32_t wgpuTextureGetDepthOrArrayLayers(WGPUTexture texture) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT WGPUTextureDimension wgpuTextureGetDimension(WGPUTexture texture) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT WGPUTextureFormat wgpuTextureGetFormat(WGPUTexture texture) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT uint32_t wgpuTextureGetHeight(WGPUTexture texture) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT uint32_t wgpuTextureGetMipLevelCount(WGPUTexture texture) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT uint32_t wgpuTextureGetSampleCount(WGPUTexture texture) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT WGPUTextureUsageFlags wgpuTextureGetUsage(WGPUTexture texture) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT uint32_t wgpuTextureGetWidth(WGPUTexture texture) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuTextureSetLabel(WGPUTexture texture, char const * label) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuTextureReference(WGPUTexture texture) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuTextureRelease(WGPUTexture texture) WGPU_FUNCTION_ATTRIBUTE; - -// Methods of TextureView -WGPU_EXPORT void wgpuTextureViewSetLabel(WGPUTextureView textureView, char const * label) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuTextureViewReference(WGPUTextureView textureView) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuTextureViewRelease(WGPUTextureView textureView) WGPU_FUNCTION_ATTRIBUTE; - - -#endif // !defined(WGPU_SKIP_DECLARATIONS) - -#if defined(__cplusplus) && !defined(USE_WGPU_WAGYU_NAMESPACE) && !defined(__cppcheck) -} // extern "C" -#endif - -#if defined(USE_WGPU_WAGYU_NAMESPACE) || defined(__cppcheck) -} // namespace wagyu -#endif - -#endif // WEBGPU_H_ diff --git a/defold-rive/include/rive/renderer/webgpu/wagyu-port/old/include/webgpu/webgpu_cpp.h b/defold-rive/include/rive/renderer/webgpu/wagyu-port/old/include/webgpu/webgpu_cpp.h deleted file mode 100644 index 046ee395..00000000 --- a/defold-rive/include/rive/renderer/webgpu/wagyu-port/old/include/webgpu/webgpu_cpp.h +++ /dev/null @@ -1,1895 +0,0 @@ -// Copyright 2024 The Dawn & Tint Authors -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this -// list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#ifndef WEBGPU_CPP_H_ -#define WEBGPU_CPP_H_ - -#include "webgpu/webgpu.h" -#include "webgpu/webgpu_cpp_chained_struct.h" -#include "webgpu/webgpu_enum_class_bitmasks.h" -#include -#include -#include -#include - -namespace wgpu { - - namespace detail { - constexpr size_t ConstexprMax(size_t a, size_t b) { - return a > b ? a : b; - } - } // namespace detail - - static constexpr uint32_t kArrayLayerCountUndefined = WGPU_ARRAY_LAYER_COUNT_UNDEFINED; - static constexpr uint32_t kCopyStrideUndefined = WGPU_COPY_STRIDE_UNDEFINED; - static constexpr uint32_t kDepthSliceUndefined = WGPU_DEPTH_SLICE_UNDEFINED; - static constexpr uint32_t kLimitU32Undefined = WGPU_LIMIT_U32_UNDEFINED; - static constexpr uint64_t kLimitU64Undefined = WGPU_LIMIT_U64_UNDEFINED; - static constexpr uint32_t kMipLevelCountUndefined = WGPU_MIP_LEVEL_COUNT_UNDEFINED; - static constexpr uint32_t kQuerySetIndexUndefined = WGPU_QUERY_SET_INDEX_UNDEFINED; - static constexpr size_t kWholeMapSize = WGPU_WHOLE_MAP_SIZE; - static constexpr uint64_t kWholeSize = WGPU_WHOLE_SIZE; - - enum class WGSLFeatureName : uint32_t { - Undefined = 0x00000000, - ReadonlyAndReadwriteStorageTextures = 0x00000001, - Packed4x8IntegerDotProduct = 0x00000002, - UnrestrictedPointerParameters = 0x00000003, - PointerCompositeAccess = 0x00000004, - }; - - enum class AdapterType : uint32_t { - DiscreteGPU = 0x00000001, - IntegratedGPU = 0x00000002, - CPU = 0x00000003, - Unknown = 0x00000004, - }; - - enum class AddressMode : uint32_t { - Undefined = 0x00000000, - ClampToEdge = 0x00000001, - Repeat = 0x00000002, - MirrorRepeat = 0x00000003, - }; - - enum class BackendType : uint32_t { - Undefined = 0x00000000, - Null = 0x00000001, - WebGPU = 0x00000002, - D3D11 = 0x00000003, - D3D12 = 0x00000004, - Metal = 0x00000005, - Vulkan = 0x00000006, - OpenGL = 0x00000007, - OpenGLES = 0x00000008, - }; - - enum class BlendFactor : uint32_t { - Undefined = 0x00000000, - Zero = 0x00000001, - One = 0x00000002, - Src = 0x00000003, - OneMinusSrc = 0x00000004, - SrcAlpha = 0x00000005, - OneMinusSrcAlpha = 0x00000006, - Dst = 0x00000007, - OneMinusDst = 0x00000008, - DstAlpha = 0x00000009, - OneMinusDstAlpha = 0x0000000A, - SrcAlphaSaturated = 0x0000000B, - Constant = 0x0000000C, - OneMinusConstant = 0x0000000D, - }; - - enum class BlendOperation : uint32_t { - Undefined = 0x00000000, - Add = 0x00000001, - Subtract = 0x00000002, - ReverseSubtract = 0x00000003, - Min = 0x00000004, - Max = 0x00000005, - }; - - enum class BufferBindingType : uint32_t { - Undefined = 0x00000000, - Uniform = 0x00000001, - Storage = 0x00000002, - ReadOnlyStorage = 0x00000003, - }; - - enum class BufferMapAsyncStatus : uint32_t { - Success = 0x00000000, - ValidationError = 0x00000001, - Unknown = 0x00000002, - DeviceLost = 0x00000003, - DestroyedBeforeCallback = 0x00000004, - UnmappedBeforeCallback = 0x00000005, - MappingAlreadyPending = 0x00000006, - OffsetOutOfRange = 0x00000007, - SizeOutOfRange = 0x00000008, - }; - - enum class BufferMapState : uint32_t { - Unmapped = 0x00000001, - Pending = 0x00000002, - Mapped = 0x00000003, - }; - - enum class CallbackMode : uint32_t { - WaitAnyOnly = 0x00000000, - AllowProcessEvents = 0x00000001, - AllowSpontaneous = 0x00000002, - }; - - enum class CompareFunction : uint32_t { - Undefined = 0x00000000, - Never = 0x00000001, - Less = 0x00000002, - Equal = 0x00000003, - LessEqual = 0x00000004, - Greater = 0x00000005, - NotEqual = 0x00000006, - GreaterEqual = 0x00000007, - Always = 0x00000008, - }; - - enum class CompilationInfoRequestStatus : uint32_t { - Success = 0x00000000, - Error = 0x00000001, - DeviceLost = 0x00000002, - Unknown = 0x00000003, - }; - - enum class CompilationMessageType : uint32_t { - Error = 0x00000001, - Warning = 0x00000002, - Info = 0x00000003, - }; - - enum class CompositeAlphaMode : uint32_t { - Auto = 0x00000000, - Opaque = 0x00000001, - Premultiplied = 0x00000002, - Unpremultiplied = 0x00000003, - Inherit = 0x00000004, - }; - - enum class CreatePipelineAsyncStatus : uint32_t { - Success = 0x00000000, - ValidationError = 0x00000001, - InternalError = 0x00000002, - DeviceLost = 0x00000003, - DeviceDestroyed = 0x00000004, - Unknown = 0x00000005, - }; - - enum class CullMode : uint32_t { - Undefined = 0x00000000, - None = 0x00000001, - Front = 0x00000002, - Back = 0x00000003, - }; - - enum class DeviceLostReason : uint32_t { - Undefined = 0x00000001, - Unknown = 0x00000001, - Destroyed = 0x00000002, - }; - - enum class ErrorFilter : uint32_t { - Validation = 0x00000001, - OutOfMemory = 0x00000002, - Internal = 0x00000003, - }; - - enum class ErrorType : uint32_t { - NoError = 0x00000000, - Validation = 0x00000001, - OutOfMemory = 0x00000002, - Internal = 0x00000003, - Unknown = 0x00000004, - DeviceLost = 0x00000005, - }; - - enum class FeatureName : uint32_t { - Undefined = 0x00000000, - DepthClipControl = 0x00000001, - Depth32FloatStencil8 = 0x00000002, - TimestampQuery = 0x00000003, - TextureCompressionBC = 0x00000004, - TextureCompressionETC2 = 0x00000005, - TextureCompressionASTC = 0x00000006, - IndirectFirstInstance = 0x00000007, - ShaderF16 = 0x00000008, - RG11B10UfloatRenderable = 0x00000009, - BGRA8UnormStorage = 0x0000000A, - Float32Filterable = 0x0000000B, - }; - - enum class FilterMode : uint32_t { - Undefined = 0x00000000, - Nearest = 0x00000001, - Linear = 0x00000002, - }; - - enum class FrontFace : uint32_t { - Undefined = 0x00000000, - CCW = 0x00000001, - CW = 0x00000002, - }; - - enum class IndexFormat : uint32_t { - Undefined = 0x00000000, - Uint16 = 0x00000001, - Uint32 = 0x00000002, - }; - - enum class LoadOp : uint32_t { - Undefined = 0x00000000, - Clear = 0x00000001, - Load = 0x00000002, - }; - - enum class MipmapFilterMode : uint32_t { - Undefined = 0x00000000, - Nearest = 0x00000001, - Linear = 0x00000002, - }; - - enum class PowerPreference : uint32_t { - Undefined = 0x00000000, - LowPower = 0x00000001, - HighPerformance = 0x00000002, - }; - - enum class PresentMode : uint32_t { - Fifo = 0x00000001, - Immediate = 0x00000003, - Mailbox = 0x00000004, - }; - - enum class PrimitiveTopology : uint32_t { - Undefined = 0x00000000, - PointList = 0x00000001, - LineList = 0x00000002, - LineStrip = 0x00000003, - TriangleList = 0x00000004, - TriangleStrip = 0x00000005, - }; - - enum class QueryType : uint32_t { - Occlusion = 0x00000001, - Timestamp = 0x00000002, - }; - - enum class QueueWorkDoneStatus : uint32_t { - Success = 0x00000000, - Error = 0x00000001, - Unknown = 0x00000002, - DeviceLost = 0x00000003, - }; - - enum class RequestAdapterStatus : uint32_t { - Success = 0x00000000, - Unavailable = 0x00000001, - Error = 0x00000002, - Unknown = 0x00000003, - }; - - enum class RequestDeviceStatus : uint32_t { - Success = 0x00000000, - Error = 0x00000001, - Unknown = 0x00000002, - }; - - enum class SType : uint32_t { - Invalid = 0x00000000, - SurfaceDescriptorFromCanvasHTMLSelector = 0x00000004, - ShaderModuleSPIRVDescriptor = 0x00000005, - ShaderModuleWGSLDescriptor = 0x00000006, - PrimitiveDepthClipControl = 0x00000007, - RenderPassDescriptorMaxDrawCount = 0x0000000F, - TextureBindingViewDimensionDescriptor = 0x00000011, - }; - - enum class SamplerBindingType : uint32_t { - Undefined = 0x00000000, - Filtering = 0x00000001, - NonFiltering = 0x00000002, - Comparison = 0x00000003, - }; - - enum class StencilOperation : uint32_t { - Undefined = 0x00000000, - Keep = 0x00000001, - Zero = 0x00000002, - Replace = 0x00000003, - Invert = 0x00000004, - IncrementClamp = 0x00000005, - DecrementClamp = 0x00000006, - IncrementWrap = 0x00000007, - DecrementWrap = 0x00000008, - }; - - enum class StorageTextureAccess : uint32_t { - Undefined = 0x00000000, - WriteOnly = 0x00000001, - ReadOnly = 0x00000002, - ReadWrite = 0x00000003, - }; - - enum class StoreOp : uint32_t { - Undefined = 0x00000000, - Store = 0x00000001, - Discard = 0x00000002, - }; - - enum class SurfaceGetCurrentTextureStatus : uint32_t { - Success = WGPUSurfaceGetCurrentTextureStatus_Success, - Timeout = WGPUSurfaceGetCurrentTextureStatus_Timeout, - Outdated = WGPUSurfaceGetCurrentTextureStatus_Outdated, - Lost = WGPUSurfaceGetCurrentTextureStatus_Lost, - OutOfMemory = WGPUSurfaceGetCurrentTextureStatus_OutOfMemory, - DeviceLost = WGPUSurfaceGetCurrentTextureStatus_DeviceLost, - }; - - enum class TextureAspect : uint32_t { - Undefined = 0x00000000, - All = 0x00000001, - StencilOnly = 0x00000002, - DepthOnly = 0x00000003, - }; - - enum class TextureDimension : uint32_t { - Undefined = 0x00000000, - e1D = 0x00000001, - e2D = 0x00000002, - e3D = 0x00000003, - }; - - enum class TextureFormat : uint32_t { - Undefined = 0x00000000, - R8Unorm = 0x00000001, - R8Snorm = 0x00000002, - R8Uint = 0x00000003, - R8Sint = 0x00000004, - R16Uint = 0x00000005, - R16Sint = 0x00000006, - R16Float = 0x00000007, - RG8Unorm = 0x00000008, - RG8Snorm = 0x00000009, - RG8Uint = 0x0000000A, - RG8Sint = 0x0000000B, - R32Float = 0x0000000C, - R32Uint = 0x0000000D, - R32Sint = 0x0000000E, - RG16Uint = 0x0000000F, - RG16Sint = 0x00000010, - RG16Float = 0x00000011, - RGBA8Unorm = 0x00000012, - RGBA8UnormSrgb = 0x00000013, - RGBA8Snorm = 0x00000014, - RGBA8Uint = 0x00000015, - RGBA8Sint = 0x00000016, - BGRA8Unorm = 0x00000017, - BGRA8UnormSrgb = 0x00000018, - RGB10A2Uint = 0x00000019, - RGB10A2Unorm = 0x0000001A, - RG11B10Ufloat = 0x0000001B, - RGB9E5Ufloat = 0x0000001C, - RG32Float = 0x0000001D, - RG32Uint = 0x0000001E, - RG32Sint = 0x0000001F, - RGBA16Uint = 0x00000020, - RGBA16Sint = 0x00000021, - RGBA16Float = 0x00000022, - RGBA32Float = 0x00000023, - RGBA32Uint = 0x00000024, - RGBA32Sint = 0x00000025, - Stencil8 = 0x00000026, - Depth16Unorm = 0x00000027, - Depth24Plus = 0x00000028, - Depth24PlusStencil8 = 0x00000029, - Depth32Float = 0x0000002A, - Depth32FloatStencil8 = 0x0000002B, - BC1RGBAUnorm = 0x0000002C, - BC1RGBAUnormSrgb = 0x0000002D, - BC2RGBAUnorm = 0x0000002E, - BC2RGBAUnormSrgb = 0x0000002F, - BC3RGBAUnorm = 0x00000030, - BC3RGBAUnormSrgb = 0x00000031, - BC4RUnorm = 0x00000032, - BC4RSnorm = 0x00000033, - BC5RGUnorm = 0x00000034, - BC5RGSnorm = 0x00000035, - BC6HRGBUfloat = 0x00000036, - BC6HRGBFloat = 0x00000037, - BC7RGBAUnorm = 0x00000038, - BC7RGBAUnormSrgb = 0x00000039, - ETC2RGB8Unorm = 0x0000003A, - ETC2RGB8UnormSrgb = 0x0000003B, - ETC2RGB8A1Unorm = 0x0000003C, - ETC2RGB8A1UnormSrgb = 0x0000003D, - ETC2RGBA8Unorm = 0x0000003E, - ETC2RGBA8UnormSrgb = 0x0000003F, - EACR11Unorm = 0x00000040, - EACR11Snorm = 0x00000041, - EACRG11Unorm = 0x00000042, - EACRG11Snorm = 0x00000043, - ASTC4x4Unorm = 0x00000044, - ASTC4x4UnormSrgb = 0x00000045, - ASTC5x4Unorm = 0x00000046, - ASTC5x4UnormSrgb = 0x00000047, - ASTC5x5Unorm = 0x00000048, - ASTC5x5UnormSrgb = 0x00000049, - ASTC6x5Unorm = 0x0000004A, - ASTC6x5UnormSrgb = 0x0000004B, - ASTC6x6Unorm = 0x0000004C, - ASTC6x6UnormSrgb = 0x0000004D, - ASTC8x5Unorm = 0x0000004E, - ASTC8x5UnormSrgb = 0x0000004F, - ASTC8x6Unorm = 0x00000050, - ASTC8x6UnormSrgb = 0x00000051, - ASTC8x8Unorm = 0x00000052, - ASTC8x8UnormSrgb = 0x00000053, - ASTC10x5Unorm = 0x00000054, - ASTC10x5UnormSrgb = 0x00000055, - ASTC10x6Unorm = 0x00000056, - ASTC10x6UnormSrgb = 0x00000057, - ASTC10x8Unorm = 0x00000058, - ASTC10x8UnormSrgb = 0x00000059, - ASTC10x10Unorm = 0x0000005A, - ASTC10x10UnormSrgb = 0x0000005B, - ASTC12x10Unorm = 0x0000005C, - ASTC12x10UnormSrgb = 0x0000005D, - ASTC12x12Unorm = 0x0000005E, - ASTC12x12UnormSrgb = 0x0000005F, - }; - - enum class TextureSampleType : uint32_t { - Undefined = 0x00000000, - Float = 0x00000001, - UnfilterableFloat = 0x00000002, - Depth = 0x00000003, - Sint = 0x00000004, - Uint = 0x00000005, - }; - - enum class TextureViewDimension : uint32_t { - Undefined = 0x00000000, - e1D = 0x00000001, - e2D = 0x00000002, - e2DArray = 0x00000003, - Cube = 0x00000004, - CubeArray = 0x00000005, - e3D = 0x00000006, - }; - - enum class VertexFormat : uint32_t { - Undefined = 0x00000000, - Uint8x2 = 0x00000001, - Uint8x4 = 0x00000002, - Sint8x2 = 0x00000003, - Sint8x4 = 0x00000004, - Unorm8x2 = 0x00000005, - Unorm8x4 = 0x00000006, - Snorm8x2 = 0x00000007, - Snorm8x4 = 0x00000008, - Uint16x2 = 0x00000009, - Uint16x4 = 0x0000000A, - Sint16x2 = 0x0000000B, - Sint16x4 = 0x0000000C, - Unorm16x2 = 0x0000000D, - Unorm16x4 = 0x0000000E, - Snorm16x2 = 0x0000000F, - Snorm16x4 = 0x00000010, - Float16x2 = 0x00000011, - Float16x4 = 0x00000012, - Float32 = 0x00000013, - Float32x2 = 0x00000014, - Float32x3 = 0x00000015, - Float32x4 = 0x00000016, - Uint32 = 0x00000017, - Uint32x2 = 0x00000018, - Uint32x3 = 0x00000019, - Uint32x4 = 0x0000001A, - Sint32 = 0x0000001B, - Sint32x2 = 0x0000001C, - Sint32x3 = 0x0000001D, - Sint32x4 = 0x0000001E, - Unorm10_10_10_2 = 0x0000001F, - }; - - enum class VertexStepMode : uint32_t { - Undefined = 0x00000000, - VertexBufferNotUsed = 0x00000001, - Vertex = 0x00000002, - Instance = 0x00000003, - }; - - enum class WaitStatus : uint32_t { - Success = 0x00000000, - TimedOut = 0x00000001, - UnsupportedTimeout = 0x00000002, - UnsupportedCount = 0x00000003, - UnsupportedMixedSources = 0x00000004, - Unknown = 0x00000005, - }; - - - enum class BufferUsage : uint32_t { - None = 0x00000000, - MapRead = 0x00000001, - MapWrite = 0x00000002, - CopySrc = 0x00000004, - CopyDst = 0x00000008, - Index = 0x00000010, - Vertex = 0x00000020, - Uniform = 0x00000040, - Storage = 0x00000080, - Indirect = 0x00000100, - QueryResolve = 0x00000200, - }; - - enum class ColorWriteMask : uint32_t { - None = 0x00000000, - Red = 0x00000001, - Green = 0x00000002, - Blue = 0x00000004, - Alpha = 0x00000008, - All = 0x0000000F, - }; - - enum class MapMode : uint32_t { - None = 0x00000000, - Read = 0x00000001, - Write = 0x00000002, - }; - - enum class ShaderStage : uint32_t { - None = 0x00000000, - Vertex = 0x00000001, - Fragment = 0x00000002, - Compute = 0x00000004, - }; - - enum class TextureUsage : uint32_t { - None = 0x00000000, - CopySrc = 0x00000001, - CopyDst = 0x00000002, - TextureBinding = 0x00000004, - StorageBinding = 0x00000008, - RenderAttachment = 0x00000010, - }; - - - using BufferMapCallback = WGPUBufferMapCallback; - using CompilationInfoCallback = WGPUCompilationInfoCallback; - using CreateComputePipelineAsyncCallback = WGPUCreateComputePipelineAsyncCallback; - using CreateRenderPipelineAsyncCallback = WGPUCreateRenderPipelineAsyncCallback; - using DeviceLostCallback = WGPUDeviceLostCallback; - using ErrorCallback = WGPUErrorCallback; - using Proc = WGPUProc; - using QueueWorkDoneCallback = WGPUQueueWorkDoneCallback; - using RequestAdapterCallback = WGPURequestAdapterCallback; - using RequestDeviceCallback = WGPURequestDeviceCallback; - - class Adapter; - class BindGroup; - class BindGroupLayout; - class Buffer; - class CommandBuffer; - class CommandEncoder; - class ComputePassEncoder; - class ComputePipeline; - class Device; - class Instance; - class PipelineLayout; - class QuerySet; - class Queue; - class RenderBundle; - class RenderBundleEncoder; - class RenderPassEncoder; - class RenderPipeline; - class Sampler; - class ShaderModule; - class Surface; - class SwapChain; - class Texture; - class TextureView; - - struct AdapterInfo; - struct AdapterProperties; - struct BindGroupEntry; - struct BlendComponent; - struct BufferBindingLayout; - struct BufferDescriptor; - struct BufferMapCallbackInfo; - struct Color; - struct CommandBufferDescriptor; - struct CommandEncoderDescriptor; - struct CompilationMessage; - struct ComputePassTimestampWrites; - struct ConstantEntry; - struct Extent3D; - struct Future; - struct InstanceFeatures; - struct Limits; - struct MultisampleState; - struct Origin3D; - struct PipelineLayoutDescriptor; - struct PrimitiveDepthClipControl; - struct PrimitiveState; - struct QuerySetDescriptor; - struct QueueDescriptor; - struct QueueWorkDoneCallbackInfo; - struct RenderBundleDescriptor; - struct RenderBundleEncoderDescriptor; - struct RenderPassDepthStencilAttachment; - struct RenderPassDescriptorMaxDrawCount; - struct RenderPassTimestampWrites; - struct RequestAdapterCallbackInfo; - struct RequestAdapterOptions; - struct SamplerBindingLayout; - struct SamplerDescriptor; - struct ShaderModuleSPIRVDescriptor; - struct ShaderModuleWGSLDescriptor; - struct ShaderModuleDescriptor; - struct StencilFaceState; - struct StorageTextureBindingLayout; - struct SurfaceCapabilities; - struct SurfaceConfiguration; - struct SurfaceDescriptor; - struct SurfaceDescriptorFromCanvasHTMLSelector; - struct SurfaceTexture; - struct SwapChainDescriptor; - struct TextureBindingLayout; - struct TextureBindingViewDimensionDescriptor; - struct TextureDataLayout; - struct TextureViewDescriptor; - struct VertexAttribute; - struct BindGroupDescriptor; - struct BindGroupLayoutEntry; - struct BlendState; - struct CompilationInfo; - struct ComputePassDescriptor; - struct DepthStencilState; - struct FutureWaitInfo; - struct ImageCopyBuffer; - struct ImageCopyTexture; - struct InstanceDescriptor; - struct ProgrammableStageDescriptor; - struct RenderPassColorAttachment; - struct RequiredLimits; - struct SupportedLimits; - struct TextureDescriptor; - struct VertexBufferLayout; - struct BindGroupLayoutDescriptor; - struct ColorTargetState; - struct ComputePipelineDescriptor; - struct DeviceDescriptor; - struct RenderPassDescriptor; - struct VertexState; - struct FragmentState; - struct RenderPipelineDescriptor; - - - // Special class for booleans in order to allow implicit conversions. - class Bool { - public: - constexpr Bool() = default; - // NOLINTNEXTLINE(runtime/explicit) allow implicit construction - constexpr Bool(bool value) : mValue(static_cast(value)) {} - // NOLINTNEXTLINE(runtime/explicit) allow implicit construction - Bool(WGPUBool value): mValue(value) {} - - constexpr operator bool() const { return static_cast(mValue); } - - private: - friend struct std::hash; - // Default to false. - WGPUBool mValue = static_cast(false); - }; - - template - class ObjectBase { - public: - ObjectBase() = default; - ObjectBase(CType handle): mHandle(handle) { - if (mHandle) Derived::WGPUReference(mHandle); - } - ~ObjectBase() { - if (mHandle) Derived::WGPURelease(mHandle); - } - - ObjectBase(ObjectBase const& other) - : ObjectBase(other.Get()) { - } - Derived& operator=(ObjectBase const& other) { - if (&other != this) { - if (mHandle) Derived::WGPURelease(mHandle); - mHandle = other.mHandle; - if (mHandle) Derived::WGPUReference(mHandle); - } - - return static_cast(*this); - } - - ObjectBase(ObjectBase&& other) { - mHandle = other.mHandle; - other.mHandle = 0; - } - Derived& operator=(ObjectBase&& other) { - if (&other != this) { - if (mHandle) Derived::WGPURelease(mHandle); - mHandle = other.mHandle; - other.mHandle = 0; - } - - return static_cast(*this); - } - - ObjectBase(std::nullptr_t) {} - Derived& operator=(std::nullptr_t) { - if (mHandle != nullptr) { - Derived::WGPURelease(mHandle); - mHandle = nullptr; - } - return static_cast(*this); - } - - bool operator==(std::nullptr_t) const { - return mHandle == nullptr; - } - bool operator!=(std::nullptr_t) const { - return mHandle != nullptr; - } - - explicit operator bool() const { - return mHandle != nullptr; - } - CType Get() const { - return mHandle; - } - CType MoveToCHandle() { - CType result = mHandle; - mHandle = 0; - return result; - } - static Derived Acquire(CType handle) { - Derived result; - result.mHandle = handle; - return result; - } - - protected: - CType mHandle = nullptr; - }; - - - - class Adapter : public ObjectBase { - public: - using ObjectBase::ObjectBase; - using ObjectBase::operator=; - - size_t EnumerateFeatures(FeatureName * features) const; - void GetInfo(AdapterInfo * info) const; - Bool GetLimits(SupportedLimits * limits) const; - void GetProperties(AdapterProperties * properties) const; - Bool HasFeature(FeatureName feature) const; - void RequestDevice(DeviceDescriptor const * descriptor, RequestDeviceCallback callback, void * userdata) const; - - private: - friend ObjectBase; - static void WGPUReference(WGPUAdapter handle); - static void WGPURelease(WGPUAdapter handle); - }; - - class BindGroup : public ObjectBase { - public: - using ObjectBase::ObjectBase; - using ObjectBase::operator=; - - void SetLabel(char const * label) const; - - private: - friend ObjectBase; - static void WGPUReference(WGPUBindGroup handle); - static void WGPURelease(WGPUBindGroup handle); - }; - - class BindGroupLayout : public ObjectBase { - public: - using ObjectBase::ObjectBase; - using ObjectBase::operator=; - - void SetLabel(char const * label) const; - - private: - friend ObjectBase; - static void WGPUReference(WGPUBindGroupLayout handle); - static void WGPURelease(WGPUBindGroupLayout handle); - }; - - class Buffer : public ObjectBase { - public: - using ObjectBase::ObjectBase; - using ObjectBase::operator=; - - void Destroy() const; - void const * GetConstMappedRange(size_t offset = 0, size_t size = WGPU_WHOLE_MAP_SIZE) const; - BufferMapState GetMapState() const; - void * GetMappedRange(size_t offset = 0, size_t size = WGPU_WHOLE_MAP_SIZE) const; - uint64_t GetSize() const; - BufferUsage GetUsage() const; - void MapAsync(MapMode mode, size_t offset, size_t size, BufferMapCallback callback, void * userdata) const; - void SetLabel(char const * label) const; - void Unmap() const; - - private: - friend ObjectBase; - static void WGPUReference(WGPUBuffer handle); - static void WGPURelease(WGPUBuffer handle); - }; - - class CommandBuffer : public ObjectBase { - public: - using ObjectBase::ObjectBase; - using ObjectBase::operator=; - - void SetLabel(char const * label) const; - - private: - friend ObjectBase; - static void WGPUReference(WGPUCommandBuffer handle); - static void WGPURelease(WGPUCommandBuffer handle); - }; - - class CommandEncoder : public ObjectBase { - public: - using ObjectBase::ObjectBase; - using ObjectBase::operator=; - - ComputePassEncoder BeginComputePass(ComputePassDescriptor const * descriptor = nullptr) const; - RenderPassEncoder BeginRenderPass(RenderPassDescriptor const * descriptor) const; - void ClearBuffer(Buffer const& buffer, uint64_t offset = 0, uint64_t size = WGPU_WHOLE_SIZE) const; - void CopyBufferToBuffer(Buffer const& source, uint64_t sourceOffset, Buffer const& destination, uint64_t destinationOffset, uint64_t size) const; - void CopyBufferToTexture(ImageCopyBuffer const * source, ImageCopyTexture const * destination, Extent3D const * copySize) const; - void CopyTextureToBuffer(ImageCopyTexture const * source, ImageCopyBuffer const * destination, Extent3D const * copySize) const; - void CopyTextureToTexture(ImageCopyTexture const * source, ImageCopyTexture const * destination, Extent3D const * copySize) const; - CommandBuffer Finish(CommandBufferDescriptor const * descriptor = nullptr) const; - void InsertDebugMarker(char const * markerLabel) const; - void PopDebugGroup() const; - void PushDebugGroup(char const * groupLabel) const; - void ResolveQuerySet(QuerySet const& querySet, uint32_t firstQuery, uint32_t queryCount, Buffer const& destination, uint64_t destinationOffset) const; - void SetLabel(char const * label) const; - void WriteTimestamp(QuerySet const& querySet, uint32_t queryIndex) const; - - private: - friend ObjectBase; - static void WGPUReference(WGPUCommandEncoder handle); - static void WGPURelease(WGPUCommandEncoder handle); - }; - - class ComputePassEncoder : public ObjectBase { - public: - using ObjectBase::ObjectBase; - using ObjectBase::operator=; - - void DispatchWorkgroups(uint32_t workgroupCountX, uint32_t workgroupCountY = 1, uint32_t workgroupCountZ = 1) const; - void DispatchWorkgroupsIndirect(Buffer const& indirectBuffer, uint64_t indirectOffset) const; - void End() const; - void InsertDebugMarker(char const * markerLabel) const; - void PopDebugGroup() const; - void PushDebugGroup(char const * groupLabel) const; - void SetBindGroup(uint32_t groupIndex, BindGroup const& group, size_t dynamicOffsetCount = 0, uint32_t const * dynamicOffsets = nullptr) const; - void SetLabel(char const * label) const; - void SetPipeline(ComputePipeline const& pipeline) const; - void WriteTimestamp(QuerySet const& querySet, uint32_t queryIndex) const; - - private: - friend ObjectBase; - static void WGPUReference(WGPUComputePassEncoder handle); - static void WGPURelease(WGPUComputePassEncoder handle); - }; - - class ComputePipeline : public ObjectBase { - public: - using ObjectBase::ObjectBase; - using ObjectBase::operator=; - - BindGroupLayout GetBindGroupLayout(uint32_t groupIndex) const; - void SetLabel(char const * label) const; - - private: - friend ObjectBase; - static void WGPUReference(WGPUComputePipeline handle); - static void WGPURelease(WGPUComputePipeline handle); - }; - - class Device : public ObjectBase { - public: - using ObjectBase::ObjectBase; - using ObjectBase::operator=; - - BindGroup CreateBindGroup(BindGroupDescriptor const * descriptor) const; - BindGroupLayout CreateBindGroupLayout(BindGroupLayoutDescriptor const * descriptor) const; - Buffer CreateBuffer(BufferDescriptor const * descriptor) const; - CommandEncoder CreateCommandEncoder(CommandEncoderDescriptor const * descriptor = nullptr) const; - ComputePipeline CreateComputePipeline(ComputePipelineDescriptor const * descriptor) const; - void CreateComputePipelineAsync(ComputePipelineDescriptor const * descriptor, CreateComputePipelineAsyncCallback callback, void * userdata) const; - PipelineLayout CreatePipelineLayout(PipelineLayoutDescriptor const * descriptor) const; - QuerySet CreateQuerySet(QuerySetDescriptor const * descriptor) const; - RenderBundleEncoder CreateRenderBundleEncoder(RenderBundleEncoderDescriptor const * descriptor) const; - RenderPipeline CreateRenderPipeline(RenderPipelineDescriptor const * descriptor) const; - void CreateRenderPipelineAsync(RenderPipelineDescriptor const * descriptor, CreateRenderPipelineAsyncCallback callback, void * userdata) const; - Sampler CreateSampler(SamplerDescriptor const * descriptor = nullptr) const; - ShaderModule CreateShaderModule(ShaderModuleDescriptor const * descriptor) const; - SwapChain CreateSwapChain(Surface const& surface, SwapChainDescriptor const * descriptor) const; - Texture CreateTexture(TextureDescriptor const * descriptor) const; - void Destroy() const; - size_t EnumerateFeatures(FeatureName * features) const; - Bool GetLimits(SupportedLimits * limits) const; - Queue GetQueue() const; - Bool HasFeature(FeatureName feature) const; - void PopErrorScope(ErrorCallback callback, void * userdata) const; - void PushErrorScope(ErrorFilter filter) const; - void SetLabel(char const * label) const; - void SetUncapturedErrorCallback(ErrorCallback callback, void * userdata) const; - - private: - friend ObjectBase; - static void WGPUReference(WGPUDevice handle); - static void WGPURelease(WGPUDevice handle); - }; - - class Instance : public ObjectBase { - public: - using ObjectBase::ObjectBase; - using ObjectBase::operator=; - - Surface CreateSurface(SurfaceDescriptor const * descriptor) const; - Bool HasWGSLLanguageFeature(WGSLFeatureName feature) const; - void ProcessEvents() const; - void RequestAdapter(RequestAdapterOptions const * options, RequestAdapterCallback callback, void * userdata) const; - - private: - friend ObjectBase; - static void WGPUReference(WGPUInstance handle); - static void WGPURelease(WGPUInstance handle); - }; - - class PipelineLayout : public ObjectBase { - public: - using ObjectBase::ObjectBase; - using ObjectBase::operator=; - - void SetLabel(char const * label) const; - - private: - friend ObjectBase; - static void WGPUReference(WGPUPipelineLayout handle); - static void WGPURelease(WGPUPipelineLayout handle); - }; - - class QuerySet : public ObjectBase { - public: - using ObjectBase::ObjectBase; - using ObjectBase::operator=; - - void Destroy() const; - uint32_t GetCount() const; - QueryType GetType() const; - void SetLabel(char const * label) const; - - private: - friend ObjectBase; - static void WGPUReference(WGPUQuerySet handle); - static void WGPURelease(WGPUQuerySet handle); - }; - - class Queue : public ObjectBase { - public: - using ObjectBase::ObjectBase; - using ObjectBase::operator=; - - void OnSubmittedWorkDone(QueueWorkDoneCallback callback, void * userdata) const; - void SetLabel(char const * label) const; - void Submit(size_t commandCount, CommandBuffer const * commands) const; - void WriteBuffer(Buffer const& buffer, uint64_t bufferOffset, void const * data, size_t size) const; - void WriteTexture(ImageCopyTexture const * destination, void const * data, size_t dataSize, TextureDataLayout const * dataLayout, Extent3D const * writeSize) const; - - private: - friend ObjectBase; - static void WGPUReference(WGPUQueue handle); - static void WGPURelease(WGPUQueue handle); - }; - - class RenderBundle : public ObjectBase { - public: - using ObjectBase::ObjectBase; - using ObjectBase::operator=; - - void SetLabel(char const * label) const; - - private: - friend ObjectBase; - static void WGPUReference(WGPURenderBundle handle); - static void WGPURelease(WGPURenderBundle handle); - }; - - class RenderBundleEncoder : public ObjectBase { - public: - using ObjectBase::ObjectBase; - using ObjectBase::operator=; - - void Draw(uint32_t vertexCount, uint32_t instanceCount = 1, uint32_t firstVertex = 0, uint32_t firstInstance = 0) const; - void DrawIndexed(uint32_t indexCount, uint32_t instanceCount = 1, uint32_t firstIndex = 0, int32_t baseVertex = 0, uint32_t firstInstance = 0) const; - void DrawIndexedIndirect(Buffer const& indirectBuffer, uint64_t indirectOffset) const; - void DrawIndirect(Buffer const& indirectBuffer, uint64_t indirectOffset) const; - RenderBundle Finish(RenderBundleDescriptor const * descriptor = nullptr) const; - void InsertDebugMarker(char const * markerLabel) const; - void PopDebugGroup() const; - void PushDebugGroup(char const * groupLabel) const; - void SetBindGroup(uint32_t groupIndex, BindGroup const& group, size_t dynamicOffsetCount = 0, uint32_t const * dynamicOffsets = nullptr) const; - void SetIndexBuffer(Buffer const& buffer, IndexFormat format, uint64_t offset = 0, uint64_t size = WGPU_WHOLE_SIZE) const; - void SetLabel(char const * label) const; - void SetPipeline(RenderPipeline const& pipeline) const; - void SetVertexBuffer(uint32_t slot, Buffer const& buffer, uint64_t offset = 0, uint64_t size = WGPU_WHOLE_SIZE) const; - - private: - friend ObjectBase; - static void WGPUReference(WGPURenderBundleEncoder handle); - static void WGPURelease(WGPURenderBundleEncoder handle); - }; - - class RenderPassEncoder : public ObjectBase { - public: - using ObjectBase::ObjectBase; - using ObjectBase::operator=; - - void BeginOcclusionQuery(uint32_t queryIndex) const; - void Draw(uint32_t vertexCount, uint32_t instanceCount = 1, uint32_t firstVertex = 0, uint32_t firstInstance = 0) const; - void DrawIndexed(uint32_t indexCount, uint32_t instanceCount = 1, uint32_t firstIndex = 0, int32_t baseVertex = 0, uint32_t firstInstance = 0) const; - void DrawIndexedIndirect(Buffer const& indirectBuffer, uint64_t indirectOffset) const; - void DrawIndirect(Buffer const& indirectBuffer, uint64_t indirectOffset) const; - void End() const; - void EndOcclusionQuery() const; - void ExecuteBundles(size_t bundleCount, RenderBundle const * bundles) const; - void InsertDebugMarker(char const * markerLabel) const; - void PopDebugGroup() const; - void PushDebugGroup(char const * groupLabel) const; - void SetBindGroup(uint32_t groupIndex, BindGroup const& group, size_t dynamicOffsetCount = 0, uint32_t const * dynamicOffsets = nullptr) const; - void SetBlendConstant(Color const * color) const; - void SetIndexBuffer(Buffer const& buffer, IndexFormat format, uint64_t offset = 0, uint64_t size = WGPU_WHOLE_SIZE) const; - void SetLabel(char const * label) const; - void SetPipeline(RenderPipeline const& pipeline) const; - void SetScissorRect(uint32_t x, uint32_t y, uint32_t width, uint32_t height) const; - void SetStencilReference(uint32_t reference) const; - void SetVertexBuffer(uint32_t slot, Buffer const& buffer, uint64_t offset = 0, uint64_t size = WGPU_WHOLE_SIZE) const; - void SetViewport(float x, float y, float width, float height, float minDepth, float maxDepth) const; - void WriteTimestamp(QuerySet const& querySet, uint32_t queryIndex) const; - - private: - friend ObjectBase; - static void WGPUReference(WGPURenderPassEncoder handle); - static void WGPURelease(WGPURenderPassEncoder handle); - }; - - class RenderPipeline : public ObjectBase { - public: - using ObjectBase::ObjectBase; - using ObjectBase::operator=; - - BindGroupLayout GetBindGroupLayout(uint32_t groupIndex) const; - void SetLabel(char const * label) const; - - private: - friend ObjectBase; - static void WGPUReference(WGPURenderPipeline handle); - static void WGPURelease(WGPURenderPipeline handle); - }; - - class Sampler : public ObjectBase { - public: - using ObjectBase::ObjectBase; - using ObjectBase::operator=; - - void SetLabel(char const * label) const; - - private: - friend ObjectBase; - static void WGPUReference(WGPUSampler handle); - static void WGPURelease(WGPUSampler handle); - }; - - class ShaderModule : public ObjectBase { - public: - using ObjectBase::ObjectBase; - using ObjectBase::operator=; - - void GetCompilationInfo(CompilationInfoCallback callback, void * userdata) const; - void SetLabel(char const * label) const; - - private: - friend ObjectBase; - static void WGPUReference(WGPUShaderModule handle); - static void WGPURelease(WGPUShaderModule handle); - }; - - class Surface : public ObjectBase { - public: - using ObjectBase::ObjectBase; - using ObjectBase::operator=; - - void Configure(SurfaceConfiguration const * config) const; - void GetCapabilities(Adapter const& adapter, SurfaceCapabilities * capabilities) const; - void GetCurrentTexture(SurfaceTexture * surfaceTexture) const; - TextureFormat GetPreferredFormat(Adapter const& adapter) const; - void Present() const; - void Unconfigure() const; - - private: - friend ObjectBase; - static void WGPUReference(WGPUSurface handle); - static void WGPURelease(WGPUSurface handle); - }; - - class SwapChain : public ObjectBase { - public: - using ObjectBase::ObjectBase; - using ObjectBase::operator=; - - Texture GetCurrentTexture() const; - TextureView GetCurrentTextureView() const; - void Present() const; - - private: - friend ObjectBase; - static void WGPUReference(WGPUSwapChain handle); - static void WGPURelease(WGPUSwapChain handle); - }; - - class Texture : public ObjectBase { - public: - using ObjectBase::ObjectBase; - using ObjectBase::operator=; - - TextureView CreateView(TextureViewDescriptor const * descriptor = nullptr) const; - void Destroy() const; - uint32_t GetDepthOrArrayLayers() const; - TextureDimension GetDimension() const; - TextureFormat GetFormat() const; - uint32_t GetHeight() const; - uint32_t GetMipLevelCount() const; - uint32_t GetSampleCount() const; - TextureUsage GetUsage() const; - uint32_t GetWidth() const; - void SetLabel(char const * label) const; - - private: - friend ObjectBase; - static void WGPUReference(WGPUTexture handle); - static void WGPURelease(WGPUTexture handle); - }; - - class TextureView : public ObjectBase { - public: - using ObjectBase::ObjectBase; - using ObjectBase::operator=; - - void SetLabel(char const * label) const; - - private: - friend ObjectBase; - static void WGPUReference(WGPUTextureView handle); - static void WGPURelease(WGPUTextureView handle); - }; - - - Instance CreateInstance(InstanceDescriptor const * descriptor = nullptr); - Bool GetInstanceFeatures(InstanceFeatures * features); - Proc GetProcAddress(Device device, char const * procName); - - struct AdapterInfo { - AdapterInfo() = default; - ~AdapterInfo(); - AdapterInfo(const AdapterInfo&) = delete; - AdapterInfo& operator=(const AdapterInfo&) = delete; - AdapterInfo(AdapterInfo&&); - AdapterInfo& operator=(AdapterInfo&&); - ChainedStructOut * nextInChain = nullptr; - char const * const vendor = nullptr; - char const * const architecture = nullptr; - char const * const device = nullptr; - char const * const description = nullptr; - BackendType const backendType = {}; - AdapterType const adapterType = {}; - uint32_t const vendorID = {}; - uint32_t const deviceID = {}; - }; - - struct AdapterProperties { - AdapterProperties() = default; - ~AdapterProperties(); - AdapterProperties(const AdapterProperties&) = delete; - AdapterProperties& operator=(const AdapterProperties&) = delete; - AdapterProperties(AdapterProperties&&); - AdapterProperties& operator=(AdapterProperties&&); - ChainedStructOut * nextInChain = nullptr; - uint32_t const vendorID = {}; - char const * const vendorName = nullptr; - char const * const architecture = nullptr; - uint32_t const deviceID = {}; - char const * const name = nullptr; - char const * const driverDescription = nullptr; - AdapterType const adapterType = {}; - BackendType const backendType = {}; - Bool const compatibilityMode = false; - }; - - struct BindGroupEntry { - ChainedStruct const * nextInChain = nullptr; - uint32_t binding; - Buffer buffer = nullptr; - uint64_t offset = 0; - uint64_t size = WGPU_WHOLE_SIZE; - Sampler sampler = nullptr; - TextureView textureView = nullptr; - }; - - struct BlendComponent { - BlendOperation operation = BlendOperation::Add; - BlendFactor srcFactor = BlendFactor::One; - BlendFactor dstFactor = BlendFactor::Zero; - }; - - struct BufferBindingLayout { - ChainedStruct const * nextInChain = nullptr; - BufferBindingType type = BufferBindingType::Undefined; - Bool hasDynamicOffset = false; - uint64_t minBindingSize = 0; - }; - - struct BufferDescriptor { - ChainedStruct const * nextInChain = nullptr; - char const * label = nullptr; - BufferUsage usage; - uint64_t size; - Bool mappedAtCreation = false; - }; - - struct BufferMapCallbackInfo { - ChainedStruct const * nextInChain = nullptr; - CallbackMode mode; - BufferMapCallback callback; - void * userdata; - }; - - struct Color { - double r; - double g; - double b; - double a; - }; - - struct CommandBufferDescriptor { - ChainedStruct const * nextInChain = nullptr; - char const * label = nullptr; - }; - - struct CommandEncoderDescriptor { - ChainedStruct const * nextInChain = nullptr; - char const * label = nullptr; - }; - - struct CompilationMessage { - ChainedStruct const * nextInChain = nullptr; - char const * message = nullptr; - CompilationMessageType type; - uint64_t lineNum; - uint64_t linePos; - uint64_t offset; - uint64_t length; - uint64_t utf16LinePos; - uint64_t utf16Offset; - uint64_t utf16Length; - }; - - struct ComputePassTimestampWrites { - QuerySet querySet; - uint32_t beginningOfPassWriteIndex = WGPU_QUERY_SET_INDEX_UNDEFINED; - uint32_t endOfPassWriteIndex = WGPU_QUERY_SET_INDEX_UNDEFINED; - }; - - struct ConstantEntry { - ChainedStruct const * nextInChain = nullptr; - char const * key; - double value; - }; - - struct Extent3D { - uint32_t width; - uint32_t height = 1; - uint32_t depthOrArrayLayers = 1; - }; - - struct Future { - uint64_t id; - }; - - struct InstanceFeatures { - ChainedStruct const * nextInChain = nullptr; - Bool timedWaitAnyEnable = false; - size_t timedWaitAnyMaxCount = 0; - }; - - struct Limits { - uint32_t maxTextureDimension1D = WGPU_LIMIT_U32_UNDEFINED; - uint32_t maxTextureDimension2D = WGPU_LIMIT_U32_UNDEFINED; - uint32_t maxTextureDimension3D = WGPU_LIMIT_U32_UNDEFINED; - uint32_t maxTextureArrayLayers = WGPU_LIMIT_U32_UNDEFINED; - uint32_t maxBindGroups = WGPU_LIMIT_U32_UNDEFINED; - uint32_t maxBindGroupsPlusVertexBuffers = WGPU_LIMIT_U32_UNDEFINED; - uint32_t maxBindingsPerBindGroup = WGPU_LIMIT_U32_UNDEFINED; - uint32_t maxDynamicUniformBuffersPerPipelineLayout = WGPU_LIMIT_U32_UNDEFINED; - uint32_t maxDynamicStorageBuffersPerPipelineLayout = WGPU_LIMIT_U32_UNDEFINED; - uint32_t maxSampledTexturesPerShaderStage = WGPU_LIMIT_U32_UNDEFINED; - uint32_t maxSamplersPerShaderStage = WGPU_LIMIT_U32_UNDEFINED; - uint32_t maxStorageBuffersPerShaderStage = WGPU_LIMIT_U32_UNDEFINED; - uint32_t maxStorageTexturesPerShaderStage = WGPU_LIMIT_U32_UNDEFINED; - uint32_t maxUniformBuffersPerShaderStage = WGPU_LIMIT_U32_UNDEFINED; - uint64_t maxUniformBufferBindingSize = WGPU_LIMIT_U64_UNDEFINED; - uint64_t maxStorageBufferBindingSize = WGPU_LIMIT_U64_UNDEFINED; - uint32_t minUniformBufferOffsetAlignment = WGPU_LIMIT_U32_UNDEFINED; - uint32_t minStorageBufferOffsetAlignment = WGPU_LIMIT_U32_UNDEFINED; - uint32_t maxVertexBuffers = WGPU_LIMIT_U32_UNDEFINED; - uint64_t maxBufferSize = WGPU_LIMIT_U64_UNDEFINED; - uint32_t maxVertexAttributes = WGPU_LIMIT_U32_UNDEFINED; - uint32_t maxVertexBufferArrayStride = WGPU_LIMIT_U32_UNDEFINED; - uint32_t maxInterStageShaderComponents = WGPU_LIMIT_U32_UNDEFINED; - uint32_t maxInterStageShaderVariables = WGPU_LIMIT_U32_UNDEFINED; - uint32_t maxColorAttachments = WGPU_LIMIT_U32_UNDEFINED; - uint32_t maxColorAttachmentBytesPerSample = WGPU_LIMIT_U32_UNDEFINED; - uint32_t maxComputeWorkgroupStorageSize = WGPU_LIMIT_U32_UNDEFINED; - uint32_t maxComputeInvocationsPerWorkgroup = WGPU_LIMIT_U32_UNDEFINED; - uint32_t maxComputeWorkgroupSizeX = WGPU_LIMIT_U32_UNDEFINED; - uint32_t maxComputeWorkgroupSizeY = WGPU_LIMIT_U32_UNDEFINED; - uint32_t maxComputeWorkgroupSizeZ = WGPU_LIMIT_U32_UNDEFINED; - uint32_t maxComputeWorkgroupsPerDimension = WGPU_LIMIT_U32_UNDEFINED; - }; - - struct MultisampleState { - ChainedStruct const * nextInChain = nullptr; - uint32_t count = 1; - uint32_t mask = 0xFFFFFFFF; - Bool alphaToCoverageEnabled = false; - }; - - struct Origin3D { - uint32_t x = 0; - uint32_t y = 0; - uint32_t z = 0; - }; - - struct PipelineLayoutDescriptor { - ChainedStruct const * nextInChain = nullptr; - char const * label = nullptr; - size_t bindGroupLayoutCount; - BindGroupLayout const * bindGroupLayouts; - }; - - // Can be chained in PrimitiveState - struct PrimitiveDepthClipControl : ChainedStruct { - PrimitiveDepthClipControl() { - sType = SType::PrimitiveDepthClipControl; - } - static constexpr size_t kFirstMemberAlignment = detail::ConstexprMax(alignof(ChainedStruct), alignof(Bool )); - alignas(kFirstMemberAlignment) Bool unclippedDepth = false; - }; - - struct PrimitiveState { - ChainedStruct const * nextInChain = nullptr; - PrimitiveTopology topology = PrimitiveTopology::TriangleList; - IndexFormat stripIndexFormat = IndexFormat::Undefined; - FrontFace frontFace = FrontFace::CCW; - CullMode cullMode = CullMode::None; - }; - - struct QuerySetDescriptor { - ChainedStruct const * nextInChain = nullptr; - char const * label = nullptr; - QueryType type; - uint32_t count; - }; - - struct QueueDescriptor { - ChainedStruct const * nextInChain = nullptr; - char const * label = nullptr; - }; - - struct QueueWorkDoneCallbackInfo { - ChainedStruct const * nextInChain = nullptr; - CallbackMode mode; - QueueWorkDoneCallback callback; - void * userdata; - }; - - struct RenderBundleDescriptor { - ChainedStruct const * nextInChain = nullptr; - char const * label = nullptr; - }; - - struct RenderBundleEncoderDescriptor { - ChainedStruct const * nextInChain = nullptr; - char const * label = nullptr; - size_t colorFormatCount; - TextureFormat const * colorFormats; - TextureFormat depthStencilFormat = TextureFormat::Undefined; - uint32_t sampleCount = 1; - Bool depthReadOnly = false; - Bool stencilReadOnly = false; - }; - - struct RenderPassDepthStencilAttachment { - TextureView view; - LoadOp depthLoadOp = LoadOp::Undefined; - StoreOp depthStoreOp = StoreOp::Undefined; - float depthClearValue = NAN; - Bool depthReadOnly = false; - LoadOp stencilLoadOp = LoadOp::Undefined; - StoreOp stencilStoreOp = StoreOp::Undefined; - uint32_t stencilClearValue = 0; - Bool stencilReadOnly = false; - }; - - // Can be chained in RenderPassDescriptor - struct RenderPassDescriptorMaxDrawCount : ChainedStruct { - RenderPassDescriptorMaxDrawCount() { - sType = SType::RenderPassDescriptorMaxDrawCount; - } - static constexpr size_t kFirstMemberAlignment = detail::ConstexprMax(alignof(ChainedStruct), alignof(uint64_t )); - alignas(kFirstMemberAlignment) uint64_t maxDrawCount = 50000000; - }; - - struct RenderPassTimestampWrites { - QuerySet querySet; - uint32_t beginningOfPassWriteIndex = WGPU_QUERY_SET_INDEX_UNDEFINED; - uint32_t endOfPassWriteIndex = WGPU_QUERY_SET_INDEX_UNDEFINED; - }; - - struct RequestAdapterCallbackInfo { - ChainedStruct const * nextInChain = nullptr; - CallbackMode mode; - RequestAdapterCallback callback; - void * userdata; - }; - - struct RequestAdapterOptions { - ChainedStruct const * nextInChain = nullptr; - Surface compatibleSurface = nullptr; - PowerPreference powerPreference = PowerPreference::Undefined; - BackendType backendType = BackendType::Undefined; - Bool forceFallbackAdapter = false; - Bool compatibilityMode = false; - }; - - struct SamplerBindingLayout { - ChainedStruct const * nextInChain = nullptr; - SamplerBindingType type = SamplerBindingType::Undefined; - }; - - struct SamplerDescriptor { - ChainedStruct const * nextInChain = nullptr; - char const * label = nullptr; - AddressMode addressModeU = AddressMode::ClampToEdge; - AddressMode addressModeV = AddressMode::ClampToEdge; - AddressMode addressModeW = AddressMode::ClampToEdge; - FilterMode magFilter = FilterMode::Nearest; - FilterMode minFilter = FilterMode::Nearest; - MipmapFilterMode mipmapFilter = MipmapFilterMode::Nearest; - float lodMinClamp = 0.0f; - float lodMaxClamp = 32.0f; - CompareFunction compare = CompareFunction::Undefined; - uint16_t maxAnisotropy = 1; - }; - - // Can be chained in ShaderModuleDescriptor - struct ShaderModuleSPIRVDescriptor : ChainedStruct { - ShaderModuleSPIRVDescriptor() { - sType = SType::ShaderModuleSPIRVDescriptor; - } - static constexpr size_t kFirstMemberAlignment = detail::ConstexprMax(alignof(ChainedStruct), alignof(uint32_t )); - alignas(kFirstMemberAlignment) uint32_t codeSize; - uint32_t const * code; - }; - - // Can be chained in ShaderModuleDescriptor - struct ShaderModuleWGSLDescriptor : ChainedStruct { - ShaderModuleWGSLDescriptor() { - sType = SType::ShaderModuleWGSLDescriptor; - } - static constexpr size_t kFirstMemberAlignment = detail::ConstexprMax(alignof(ChainedStruct), alignof(char const * )); - alignas(kFirstMemberAlignment) char const * code; - }; - - struct ShaderModuleDescriptor { - ChainedStruct const * nextInChain = nullptr; - char const * label = nullptr; - }; - - struct StencilFaceState { - CompareFunction compare = CompareFunction::Always; - StencilOperation failOp = StencilOperation::Keep; - StencilOperation depthFailOp = StencilOperation::Keep; - StencilOperation passOp = StencilOperation::Keep; - }; - - struct StorageTextureBindingLayout { - ChainedStruct const * nextInChain = nullptr; - StorageTextureAccess access = StorageTextureAccess::Undefined; - TextureFormat format = TextureFormat::Undefined; - TextureViewDimension viewDimension = TextureViewDimension::e2D; - }; - - struct SurfaceCapabilities { - SurfaceCapabilities() = default; - ~SurfaceCapabilities(); - SurfaceCapabilities(const SurfaceCapabilities&) = delete; - SurfaceCapabilities& operator=(const SurfaceCapabilities&) = delete; - SurfaceCapabilities(SurfaceCapabilities&&); - SurfaceCapabilities& operator=(SurfaceCapabilities&&); - ChainedStructOut * nextInChain = nullptr; - size_t const formatCount = {}; - TextureFormat const * const formats = {}; - size_t const presentModeCount = {}; - PresentMode const * const presentModes = {}; - size_t const alphaModeCount = {}; - CompositeAlphaMode const * const alphaModes = {}; - }; - - struct SurfaceConfiguration { - ChainedStruct const * nextInChain = nullptr; - Device device; - TextureFormat format; - TextureUsage usage = TextureUsage::RenderAttachment; - size_t viewFormatCount = 0; - TextureFormat const * viewFormats; - CompositeAlphaMode alphaMode = CompositeAlphaMode::Auto; - uint32_t width; - uint32_t height; - PresentMode presentMode = PresentMode::Fifo; - }; - - struct SurfaceDescriptor { - ChainedStruct const * nextInChain = nullptr; - char const * label = nullptr; - }; - - // Can be chained in SurfaceDescriptor - struct SurfaceDescriptorFromCanvasHTMLSelector : ChainedStruct { - SurfaceDescriptorFromCanvasHTMLSelector() { - sType = SType::SurfaceDescriptorFromCanvasHTMLSelector; - } - static constexpr size_t kFirstMemberAlignment = detail::ConstexprMax(alignof(ChainedStruct), alignof(char const * )); - alignas(kFirstMemberAlignment) char const * selector; - }; - - struct SurfaceTexture { - Texture texture; - Bool suboptimal; - SurfaceGetCurrentTextureStatus status; - }; - - struct SwapChainDescriptor { - ChainedStruct const * nextInChain = nullptr; - char const * label = nullptr; - TextureUsage usage; - TextureFormat format; - uint32_t width; - uint32_t height; - PresentMode presentMode; - }; - - struct TextureBindingLayout { - ChainedStruct const * nextInChain = nullptr; - TextureSampleType sampleType = TextureSampleType::Undefined; - TextureViewDimension viewDimension = TextureViewDimension::e2D; - Bool multisampled = false; - }; - - // Can be chained in TextureDescriptor - struct TextureBindingViewDimensionDescriptor : ChainedStruct { - TextureBindingViewDimensionDescriptor() { - sType = SType::TextureBindingViewDimensionDescriptor; - } - static constexpr size_t kFirstMemberAlignment = detail::ConstexprMax(alignof(ChainedStruct), alignof(TextureViewDimension )); - alignas(kFirstMemberAlignment) TextureViewDimension textureBindingViewDimension = TextureViewDimension::Undefined; - }; - - struct TextureDataLayout { - ChainedStruct const * nextInChain = nullptr; - uint64_t offset = 0; - uint32_t bytesPerRow = WGPU_COPY_STRIDE_UNDEFINED; - uint32_t rowsPerImage = WGPU_COPY_STRIDE_UNDEFINED; - }; - - struct TextureViewDescriptor { - ChainedStruct const * nextInChain = nullptr; - char const * label = nullptr; - TextureFormat format = TextureFormat::Undefined; - TextureViewDimension dimension = TextureViewDimension::Undefined; - uint32_t baseMipLevel = 0; - uint32_t mipLevelCount = WGPU_MIP_LEVEL_COUNT_UNDEFINED; - uint32_t baseArrayLayer = 0; - uint32_t arrayLayerCount = WGPU_ARRAY_LAYER_COUNT_UNDEFINED; - TextureAspect aspect = TextureAspect::All; - }; - - struct VertexAttribute { - VertexFormat format; - uint64_t offset; - uint32_t shaderLocation; - }; - - struct BindGroupDescriptor { - ChainedStruct const * nextInChain = nullptr; - char const * label = nullptr; - BindGroupLayout layout; - size_t entryCount; - BindGroupEntry const * entries; - }; - - struct BindGroupLayoutEntry { - ChainedStruct const * nextInChain = nullptr; - uint32_t binding; - ShaderStage visibility; - BufferBindingLayout buffer; - SamplerBindingLayout sampler; - TextureBindingLayout texture; - StorageTextureBindingLayout storageTexture; - }; - - struct BlendState { - BlendComponent color; - BlendComponent alpha; - }; - - struct CompilationInfo { - ChainedStruct const * nextInChain = nullptr; - size_t messageCount; - CompilationMessage const * messages; - }; - - struct ComputePassDescriptor { - ChainedStruct const * nextInChain = nullptr; - char const * label = nullptr; - ComputePassTimestampWrites const * timestampWrites = nullptr; - }; - - struct DepthStencilState { - ChainedStruct const * nextInChain = nullptr; - TextureFormat format; - Bool depthWriteEnabled = false; - CompareFunction depthCompare = CompareFunction::Undefined; - StencilFaceState stencilFront; - StencilFaceState stencilBack; - uint32_t stencilReadMask = 0xFFFFFFFF; - uint32_t stencilWriteMask = 0xFFFFFFFF; - int32_t depthBias = 0; - float depthBiasSlopeScale = 0.0f; - float depthBiasClamp = 0.0f; - }; - - struct FutureWaitInfo { - Future future; - Bool completed = false; - }; - - struct ImageCopyBuffer { - ChainedStruct const * nextInChain = nullptr; - TextureDataLayout layout; - Buffer buffer; - }; - - struct ImageCopyTexture { - ChainedStruct const * nextInChain = nullptr; - Texture texture; - uint32_t mipLevel = 0; - Origin3D origin; - TextureAspect aspect = TextureAspect::All; - }; - - struct InstanceDescriptor { - ChainedStruct const * nextInChain = nullptr; - InstanceFeatures features; - }; - - struct ProgrammableStageDescriptor { - ChainedStruct const * nextInChain = nullptr; - ShaderModule module; - char const * entryPoint = nullptr; - size_t constantCount = 0; - ConstantEntry const * constants; - }; - - struct RenderPassColorAttachment { - ChainedStruct const * nextInChain = nullptr; - TextureView view = nullptr; - uint32_t depthSlice = WGPU_DEPTH_SLICE_UNDEFINED; - TextureView resolveTarget = nullptr; - LoadOp loadOp; - StoreOp storeOp; - Color clearValue; - }; - - struct RequiredLimits { - ChainedStruct const * nextInChain = nullptr; - Limits limits; - }; - - struct SupportedLimits { - ChainedStructOut * nextInChain = nullptr; - Limits limits; - }; - - struct TextureDescriptor { - ChainedStruct const * nextInChain = nullptr; - char const * label = nullptr; - TextureUsage usage; - TextureDimension dimension = TextureDimension::e2D; - Extent3D size; - TextureFormat format; - uint32_t mipLevelCount = 1; - uint32_t sampleCount = 1; - size_t viewFormatCount = 0; - TextureFormat const * viewFormats; - }; - - struct VertexBufferLayout { - uint64_t arrayStride; - VertexStepMode stepMode = VertexStepMode::Vertex; - size_t attributeCount; - VertexAttribute const * attributes; - }; - - struct BindGroupLayoutDescriptor { - ChainedStruct const * nextInChain = nullptr; - char const * label = nullptr; - size_t entryCount; - BindGroupLayoutEntry const * entries; - }; - - struct ColorTargetState { - ChainedStruct const * nextInChain = nullptr; - TextureFormat format; - BlendState const * blend = nullptr; - ColorWriteMask writeMask = ColorWriteMask::All; - }; - - struct ComputePipelineDescriptor { - ChainedStruct const * nextInChain = nullptr; - char const * label = nullptr; - PipelineLayout layout = nullptr; - ProgrammableStageDescriptor compute; - }; - - struct DeviceDescriptor { - ChainedStruct const * nextInChain = nullptr; - char const * label = nullptr; - size_t requiredFeatureCount = 0; - FeatureName const * requiredFeatures = nullptr; - RequiredLimits const * requiredLimits = nullptr; - QueueDescriptor defaultQueue; - DeviceLostCallback deviceLostCallback = nullptr; - void * deviceLostUserdata = nullptr; - }; - - struct RenderPassDescriptor { - ChainedStruct const * nextInChain = nullptr; - char const * label = nullptr; - size_t colorAttachmentCount; - RenderPassColorAttachment const * colorAttachments; - RenderPassDepthStencilAttachment const * depthStencilAttachment = nullptr; - QuerySet occlusionQuerySet = nullptr; - RenderPassTimestampWrites const * timestampWrites = nullptr; - }; - - struct VertexState { - ChainedStruct const * nextInChain = nullptr; - ShaderModule module; - char const * entryPoint = nullptr; - size_t constantCount = 0; - ConstantEntry const * constants; - size_t bufferCount = 0; - VertexBufferLayout const * buffers; - }; - - struct FragmentState { - ChainedStruct const * nextInChain = nullptr; - ShaderModule module; - char const * entryPoint = nullptr; - size_t constantCount = 0; - ConstantEntry const * constants; - size_t targetCount; - ColorTargetState const * targets; - }; - - struct RenderPipelineDescriptor { - ChainedStruct const * nextInChain = nullptr; - char const * label = nullptr; - PipelineLayout layout = nullptr; - VertexState vertex; - PrimitiveState primitive; - DepthStencilState const * depthStencil = nullptr; - MultisampleState multisample; - FragmentState const * fragment = nullptr; - }; - -} // namespace wgpu - -namespace wgpu { - template<> - struct IsWGPUBitmask { - static constexpr bool enable = true; - }; - - template<> - struct IsWGPUBitmask { - static constexpr bool enable = true; - }; - - template<> - struct IsWGPUBitmask { - static constexpr bool enable = true; - }; - - template<> - struct IsWGPUBitmask { - static constexpr bool enable = true; - }; - - template<> - struct IsWGPUBitmask { - static constexpr bool enable = true; - }; - -} // namespace wgpu - -namespace std { -// Custom boolean class needs corresponding hash function so that it appears as a transparent bool. -template <> -struct hash { - public: - size_t operator()(const wgpu::Bool &v) const { - return hash()(v); - } -}; -} // namespace std - -#endif // WEBGPU_CPP_H_ diff --git a/defold-rive/include/rive/renderer/webgpu/wagyu-port/old/include/webgpu/webgpu_cpp_chained_struct.h b/defold-rive/include/rive/renderer/webgpu/wagyu-port/old/include/webgpu/webgpu_cpp_chained_struct.h deleted file mode 100644 index bb3a1be1..00000000 --- a/defold-rive/include/rive/renderer/webgpu/wagyu-port/old/include/webgpu/webgpu_cpp_chained_struct.h +++ /dev/null @@ -1,26 +0,0 @@ -#ifndef WEBGPU_CPP_CHAINED_STRUCT_H_ -#define WEBGPU_CPP_CHAINED_STRUCT_H_ - -#include -#include - -// This header file declares the ChainedStruct structures separately from the WebGPU -// headers so that dependencies can directly extend structures without including the larger header -// which exposes capabilities that may require correctly set proc tables. -namespace wgpu { - - enum class SType : uint32_t; - - struct ChainedStruct { - ChainedStruct const * nextInChain = nullptr; - SType sType = SType(0u); - }; - - struct ChainedStructOut { - ChainedStructOut * nextInChain = nullptr; - SType sType = SType(0u); - }; - -} // namespace wgpu} - -#endif // WEBGPU_CPP_CHAINED_STRUCT_H_ diff --git a/defold-rive/include/rive/renderer/webgpu/wagyu-port/old/include/webgpu/webgpu_enum_class_bitmasks.h b/defold-rive/include/rive/renderer/webgpu/wagyu-port/old/include/webgpu/webgpu_enum_class_bitmasks.h deleted file mode 100644 index e98c8c5d..00000000 --- a/defold-rive/include/rive/renderer/webgpu/wagyu-port/old/include/webgpu/webgpu_enum_class_bitmasks.h +++ /dev/null @@ -1,161 +0,0 @@ -// Copyright 2017 The Dawn & Tint Authors -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this -// list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#ifndef WEBGPU_ENUM_CLASS_BITMASKS_H_ -#define WEBGPU_ENUM_CLASS_BITMASKS_H_ - -#include - -// The operators in wgpu:: namespace need be introduced into other namespaces with -// using-declarations for C++ Argument Dependent Lookup to work. -#define WGPU_IMPORT_BITMASK_OPERATORS \ - using wgpu::operator|; \ - using wgpu::operator&; \ - using wgpu::operator^; \ - using wgpu::operator~; \ - using wgpu::operator&=; \ - using wgpu::operator|=; \ - using wgpu::operator^=; \ - using wgpu::HasZeroOrOneBits; - -namespace wgpu { - -template -struct IsWGPUBitmask { - static constexpr bool enable = false; -}; - -template -struct LowerBitmask { - static constexpr bool enable = false; -}; - -template -struct LowerBitmask::enable>::type> { - static constexpr bool enable = true; - using type = T; - constexpr static T Lower(T t) { return t; } -}; - -template -struct BoolConvertible { - using Integral = typename std::underlying_type::type; - - // NOLINTNEXTLINE(runtime/explicit) - explicit constexpr BoolConvertible(Integral value) : value(value) {} - constexpr operator bool() const { return value != 0; } - constexpr operator T() const { return static_cast(value); } - - Integral value; -}; - -template -struct LowerBitmask> { - static constexpr bool enable = true; - using type = T; - static constexpr type Lower(BoolConvertible t) { return t; } -}; - -template < - typename T1, - typename T2, - typename = typename std::enable_if::enable && LowerBitmask::enable>::type> -constexpr BoolConvertible::type> operator|(T1 left, T2 right) { - using T = typename LowerBitmask::type; - using Integral = typename std::underlying_type::type; - return BoolConvertible(static_cast(LowerBitmask::Lower(left)) | - static_cast(LowerBitmask::Lower(right))); -} - -template < - typename T1, - typename T2, - typename = typename std::enable_if::enable && LowerBitmask::enable>::type> -constexpr BoolConvertible::type> operator&(T1 left, T2 right) { - using T = typename LowerBitmask::type; - using Integral = typename std::underlying_type::type; - return BoolConvertible(static_cast(LowerBitmask::Lower(left)) & - static_cast(LowerBitmask::Lower(right))); -} - -template < - typename T1, - typename T2, - typename = typename std::enable_if::enable && LowerBitmask::enable>::type> -constexpr BoolConvertible::type> operator^(T1 left, T2 right) { - using T = typename LowerBitmask::type; - using Integral = typename std::underlying_type::type; - return BoolConvertible(static_cast(LowerBitmask::Lower(left)) ^ - static_cast(LowerBitmask::Lower(right))); -} - -template -constexpr BoolConvertible::type> operator~(T1 t) { - using T = typename LowerBitmask::type; - using Integral = typename std::underlying_type::type; - return BoolConvertible(~static_cast(LowerBitmask::Lower(t))); -} - -template < - typename T, - typename T2, - typename = typename std::enable_if::enable && LowerBitmask::enable>::type> -constexpr T& operator&=(T& l, T2 right) { - T r = LowerBitmask::Lower(right); - l = l & r; - return l; -} - -template < - typename T, - typename T2, - typename = typename std::enable_if::enable && LowerBitmask::enable>::type> -constexpr T& operator|=(T& l, T2 right) { - T r = LowerBitmask::Lower(right); - l = l | r; - return l; -} - -template < - typename T, - typename T2, - typename = typename std::enable_if::enable && LowerBitmask::enable>::type> -constexpr T& operator^=(T& l, T2 right) { - T r = LowerBitmask::Lower(right); - l = l ^ r; - return l; -} - -template -constexpr bool HasZeroOrOneBits(T value) { - using Integral = typename std::underlying_type::type; - return (static_cast(value) & (static_cast(value) - 1)) == 0; -} - -} // namespace wgpu - -#endif // WEBGPU_ENUM_CLASS_BITMASKS_H_ diff --git a/defold-rive/include/rive/renderer/webgpu/wagyu-port/old/include/webgpu/webgpu_wagyu.h b/defold-rive/include/rive/renderer/webgpu/wagyu-port/old/include/webgpu/webgpu_wagyu.h deleted file mode 100644 index fcfdc5ca..00000000 --- a/defold-rive/include/rive/renderer/webgpu/wagyu-port/old/include/webgpu/webgpu_wagyu.h +++ /dev/null @@ -1,588 +0,0 @@ -#ifndef WEBGPU_WAGYU_H -#define WEBGPU_WAGYU_H - -#include "webgpu/webgpu.h" - -#define WGPU_WAGYU_EXTENSION_LEVEL 1 - -// Reserved range for Wagyu starts at 0x00060000 -// https://github.com/webgpu-native/webgpu-headers/blob/main/doc/articles/Extensions.md#registry-of-prefixes-and-enum-blocks -#define WGPU_WAGYU_RESERVED_RANGE_BASE 0x00060000 - -#if defined(__cplusplus) -#if __cplusplus >= 201103L -#define WGPU_WAGYU_MAKE_INIT_STRUCT(type, value) (type value) -#else -#define WGPU_WAGYU_MAKE_INIT_STRUCT(type, value) value -#endif -#elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L -#define WGPU_WAGYU_MAKE_INIT_STRUCT(type, value) ((type)value) -#else -#define WGPU_WAGYU_MAKE_INIT_STRUCT(type, value) value -#endif - -#define _wgpu_COMMA , - -#define WGPU_WAGYU_CHAIN_INIT(sType) \ - WGPU_WAGYU_MAKE_INIT_STRUCT(WGPUChainedStruct, { /*.next = */ NULL _wgpu_COMMA /*.sType = */ (WGPUSType) sType _wgpu_COMMA }) - -#define WGPU_WAGYU_CHAIN_OUT_INIT(sType) \ - WGPU_WAGYU_MAKE_INIT_STRUCT(WGPUChainedStructOut, { /*.next = */ NULL _wgpu_COMMA /*.sType = */ (WGPUSType) sType _wgpu_COMMA }) - -// This should be equivalent to the type of the same name in the new webgpu.h -#if !defined(WGPUOptionalBool) -#define WGPUOptionalBool int32_t -#define WGPUOptionalBool_False 0x00000000 -#define WGPUOptionalBool_True 0x00000001 -#define WGPUOptionalBool_Undefined 0x00000002 -#define WGPUOptionalBool_Force32 0x7FFFFFFF -#endif - -#define WGPU_WAGYU_STRLEN SIZE_MAX -#define WGPU_WAGYU_PIXEL_LOCAL_STORAGE_SIZE_UNDEFINED UINT32_MAX - -#if defined(USE_WGPU_WAGYU_NAMESPACE) || defined(__cppcheck) -namespace wagyu1 { -#endif - -typedef struct WGPUWagyuRelaxedComplianceImpl *WGPUWagyuRelaxedCompliance WGPU_OBJECT_ATTRIBUTE; -typedef struct WGPUWagyuExternalTextureImpl *WGPUWagyuExternalTexture WGPU_OBJECT_ATTRIBUTE; - -typedef enum WGPUWagyuDeviceFlushStatus -{ - WGPUWagyuDeviceFlushStatus_Success = 0x00000000, - WGPUWagyuDeviceFlushStatus_Error = 0x00000001, - WGPUWagyuDeviceFlushStatus_Force32 = 0x7FFFFFFF -} WGPUWagyuDeviceFlushStatus WGPU_ENUM_ATTRIBUTE; - -// These values extend the WGPUSType enum set from webgpu.h -typedef enum WGPUSType_Wagyu -{ - WGPUSType_WagyuAdapterInfo = WGPU_WAGYU_RESERVED_RANGE_BASE + 0x0001, - WGPUSType_WagyuColorTargetState = WGPU_WAGYU_RESERVED_RANGE_BASE + 0x0002, - WGPUSType_WagyuCommandEncoderDescriptor = WGPU_WAGYU_RESERVED_RANGE_BASE + 0x0003, - WGPUSType_WagyuComputePipelineDescriptor = WGPU_WAGYU_RESERVED_RANGE_BASE + 0x0004, - WGPUSType_WagyuDeviceDescriptor = WGPU_WAGYU_RESERVED_RANGE_BASE + 0x0005, - WGPUSType_WagyuExternalTextureBindingEntry = WGPU_WAGYU_RESERVED_RANGE_BASE + 0x0006, - WGPUSType_WagyuExternalTextureBindingLayout = WGPU_WAGYU_RESERVED_RANGE_BASE + 0x0007, - WGPUSType_WagyuFragmentState = WGPU_WAGYU_RESERVED_RANGE_BASE + 0x0008, - WGPUSType_WagyuInputTextureBindingLayout = WGPU_WAGYU_RESERVED_RANGE_BASE + 0x0009, - WGPUSType_WagyuRenderPassDescriptor = WGPU_WAGYU_RESERVED_RANGE_BASE + 0x000A, - WGPUSType_WagyuRenderPipelineDescriptor = WGPU_WAGYU_RESERVED_RANGE_BASE + 0x000B, - WGPUSType_WagyuShaderModuleDescriptor = WGPU_WAGYU_RESERVED_RANGE_BASE + 0x000C, - WGPUSType_WagyuSurfaceConfiguration = WGPU_WAGYU_RESERVED_RANGE_BASE + 0x000D, - WGPUSType_WagyuTextureDescriptor = WGPU_WAGYU_RESERVED_RANGE_BASE + 0x000E, - WGPUSType_WagyuForce32 = 0x7FFFFFFF -} WGPUSType_Wagyu WGPU_ENUM_ATTRIBUTE; - -typedef enum WGPUWagyuPredefinedColorSpace -{ - WGPUWagyuPredefinedColorSpace_SRGB = 0x00000001, - WGPUWagyuPredefinedColorSpace_DisplayP3 = 0x00000002, - WGPUWagyuPredefinedColorSpace_Force32 = 0x7FFFFFFF -} WGPUWagyuPredefinedColorSpace WGPU_ENUM_ATTRIBUTE; - -typedef enum WGPUWagyuShaderLanguage -{ - WGPUWagyuShaderLanguage_Detect = 0x00000000, - WGPUWagyuShaderLanguage_GLSL = 0x00000001, - WGPUWagyuShaderLanguage_GLSLRAW = 0x00000002, - WGPUWagyuShaderLanguage_WGSL = 0x00000003, - WGPUWagyuShaderLanguage_SPIRV = 0x00000004, - WGPUWagyuShaderLanguage_Force32 = 0x7FFFFFFF -} WGPUWagyuShaderLanguage WGPU_ENUM_ATTRIBUTE; - -typedef enum WGPUWagyuWGSLFeatureType -{ - WGPUWagyuWGSLFeatureType_Testing = 0x00000001, - WGPUWagyuWGSLFeatureType_UnsafeExperimental = 0x00000002, - WGPUWagyuWGSLFeatureType_Experimental = 0x00000004, - WGPUWagyuWGSLFeatureType_All = 0x00000007, - WGPUWagyuWGSLFeatureType_Force32 = 0x7FFFFFFF -} WGPUWagyuWGSLFeatureType WGPU_ENUM_ATTRIBUTE; - -typedef WGPUFlags WGPUWagyuFragmentStateFeaturesFlags; -static const WGPUWagyuFragmentStateFeaturesFlags WGPUWagyuFragmentStateFeaturesFlags_None = 0x00000000; -static const WGPUWagyuFragmentStateFeaturesFlags WGPUWagyuFragmentStateFeaturesFlags_RasterizationOrderAttachmentAccess = 0x00000001; - -// These values extend the WGPUTextureUsage enum set from webgpu.h -static const WGPUTextureUsage WGPUTextureUsage_WagyuInputAttachment = (WGPUTextureUsage)(0x40000000); -static const WGPUTextureUsage WGPUTextureUsage_WagyuTransientAttachment = (WGPUTextureUsage)(0x20000000); - -typedef void (*WGPUWagyuDeviceFlushCallback)(WGPUDevice device, WGPUWagyuDeviceFlushStatus status, void *userdata) WGPU_FUNCTION_ATTRIBUTE; - -typedef struct WGPUWagyuStringView -{ - WGPU_NULLABLE const char *data; - size_t length; -} WGPUWagyuStringView WGPU_STRUCTURE_ATTRIBUTE; - -#define WGPU_WAGYU_STRING_VIEW_INIT \ - WGPU_WAGYU_MAKE_INIT_STRUCT(WGPUWagyuStringView, { /*.data = */ NULL _wgpu_COMMA /*.length = */ 0 _wgpu_COMMA }) - -typedef struct WGPUWagyuNrdpVersion -{ - uint32_t major; - uint32_t minor; - uint32_t patch; - uint32_t rev; -} WGPUWagyuNrdpVersion WGPU_STRUCTURE_ATTRIBUTE; - -#define WGPU_WAGYU_NRDP_VERSION_INIT \ - WGPU_WAGYU_MAKE_INIT_STRUCT(WGPUWagyuNrdpVersion, { /*.major = */ 0 _wgpu_COMMA /*.minor = */ 0 _wgpu_COMMA /*.patch = */ 0 _wgpu_COMMA /*.rev = */ 0 _wgpu_COMMA }) - -typedef struct WGPUWagyuAdapterInfo -{ - WGPUChainedStructOut chain; - uint32_t extensionLevel; - WGPUWagyuNrdpVersion nrdpVersion; -} WGPUWagyuAdapterInfo WGPU_STRUCTURE_ATTRIBUTE; - -#define WGPU_WAGYU_ADAPTER_INFO_INIT \ - WGPU_WAGYU_MAKE_INIT_STRUCT(WGPUWagyuAdapterInfo, { /*.chain*/ WGPU_WAGYU_CHAIN_OUT_INIT(WGPUSType_WagyuAdapterInfo) _wgpu_COMMA /*.level*/ 0 _wgpu_COMMA /*.nrdpVersion*/ WGPU_WAGYU_NRDP_VERSION_INIT _wgpu_COMMA }) - -typedef struct WGPUWagyuColorTargetState -{ - WGPUChainedStruct chain; - WGPUOptionalBool usedAsInput; -} WGPUWagyuColorTargetState WGPU_STRUCTURE_ATTRIBUTE; - -#define WGPU_WAGYU_COLOR_TARGET_STATE_INIT \ - WGPU_WAGYU_MAKE_INIT_STRUCT(WGPUWagyuColorTargetState, \ - { /*.chain*/ WGPU_WAGYU_CHAIN_INIT(WGPUSType_WagyuColorTargetState) _wgpu_COMMA /*.usedAsInput*/ WGPUOptionalBool_Undefined _wgpu_COMMA }) - -typedef struct WGPUWagyuCommandEncoderDescriptor -{ - WGPUChainedStruct chain; - WGPUOptionalBool measureExecutionTime; -} WGPUWagyuCommandEncoderDescriptor WGPU_STRUCTURE_ATTRIBUTE; - -#define WGPU_WAGYU_COMMAND_ENCODER_DESCRIPTOR_INIT \ - WGPU_WAGYU_MAKE_INIT_STRUCT(WGPUWagyuCommandEncoderDescriptor, { /*.chain*/ WGPU_WAGYU_CHAIN_INIT(WGPUSType_WagyuCommandEncoderDescriptor) _wgpu_COMMA /*.measureExecutionTime*/ WGPUOptionalBool_Undefined _wgpu_COMMA }) - -typedef struct WGPUWagyuComputePipelineDescriptor -{ - WGPUChainedStruct chain; - WGPUWagyuStringView cacheKey; -} WGPUWagyuComputePipelineDescriptor WGPU_STRUCTURE_ATTRIBUTE; - -#define WGPU_WAGYU_COMPUTE_PIPELINE_DESCRIPTOR_INIT \ - WGPU_WAGYU_MAKE_INIT_STRUCT(WGPUWagyuComputePipelineDescriptor, { /*.chain*/ WGPU_WAGYU_CHAIN_INIT(WGPUSType_WagyuComputePipelineDescriptor) _wgpu_COMMA /*.cacheKey*/ WGPU_WAGYU_STRING_VIEW_INIT _wgpu_COMMA }) - -typedef struct WGPUWagyuDeviceDescriptor -{ - WGPUChainedStruct chain; - WGPUBool dataBufferNeedsDetach; - WGPUBool wantsIndirectRendering; -} WGPUWagyuDeviceDescriptor WGPU_STRUCTURE_ATTRIBUTE; - -#define WGPU_WAGYU_DEVICE_DESCRIPTOR_INIT \ - WGPU_WAGYU_MAKE_INIT_STRUCT(WGPUWagyuDeviceDescriptor, { /*.chain*/ WGPU_WAGYU_CHAIN_INIT(WGPUSType_WagyuDeviceDescriptor) _wgpu_COMMA /*.dataBufferNeedsDetach*/ 1 _wgpu_COMMA /*.wantsIndirectRendering*/ 0 _wgpu_COMMA }) - -typedef struct WGPUWagyuDeviceFlushCallbackInfo -{ - WGPUChainedStruct *nextInChain; - WGPUCallbackMode mode; - WGPUWagyuDeviceFlushCallback callback; - void *userdata; -} WGPUWagyuDeviceFlushCallbackInfo WGPU_STRUCTURE_ATTRIBUTE; - -#define WGPU_WAGYU_DEVICE_FLUSHCALLBACK_INFO_INIT \ - WGPU_WAGYU_MAKE_INIT_STRUCT(WGPUWagyuDeviceFlushCallbackInfo, { /*.nextInChain = */ NULL _wgpu_COMMA /*.mode = */ WGPUCallbackMode_AllowSpontaneous _wgpu_COMMA /*.callback = */ NULL _wgpu_COMMA /*.userdata1 = */ NULL _wgpu_COMMA /*.userdata2 = */ NULL _wgpu_COMMA }) - -typedef struct WGPUWagyuDevicePipelineBinary -{ - size_t binarySize; - void *binary; - size_t blobKeySize; - void *blobKey; -} WGPUWagyuDevicePipelineBinary WGPU_STRUCTURE_ATTRIBUTE; - -#define WGPU_WAGYU_DEVICE_PIPELINE_BINARY_INIT \ - WGPU_WAGYU_MAKE_INIT_STRUCT(WGPUWagyuDevicePipelineBinary, { /*.binarySize*/ 0 _wgpu_COMMA /*.binary*/ NULL _wgpu_COMMA /*.blobKeySize*/ 0 _wgpu_COMMA /*.blobKey*/ NULL _wgpu_COMMA }) - -typedef struct WGPUWagyuDevicePipelineBinaryBlobKey -{ - size_t size; - const void *data; -} WGPUWagyuDevicePipelineBinaryBlobKey WGPU_STRUCTURE_ATTRIBUTE; - -#define WGPU_WAGYU_DEVICE_PIPELINE_BINARY_BLOB_KEY_INIT \ - WGPU_WAGYU_MAKE_INIT_STRUCT(WGPUWagyuDevicePipelineBinaryBlobKey, { /*.size*/ 0 _wgpu_COMMA /*.data*/ NULL _wgpu_COMMA }) - -typedef struct WGPUWagyuDevicePipelineBinaryCacheKey -{ - WGPUWagyuStringView cacheKey; - size_t blobKeysLength; - WGPUWagyuDevicePipelineBinaryBlobKey *blobKeys; -} WGPUWagyuDevicePipelineBinaryCacheKey WGPU_STRUCTURE_ATTRIBUTE; - -#define WGPU_WAGYU_DEVICE_PIPELINE_BINARY_CACHE_KEY_INIT \ - WGPU_WAGYU_MAKE_INIT_STRUCT(WGPUWagyuDevicePipelineBinaryCacheKey, { /*.cacheKey*/ WGPU_WAGYU_STRING_VIEW_INIT _wgpu_COMMA /*.blobKeysLength*/ 0 _wgpu_COMMA }) - -typedef struct WGPUWagyuDevicePipelineBinaryData -{ - size_t binariesLength; - WGPUWagyuDevicePipelineBinary *binaries; - size_t cacheKeysLength; - WGPUWagyuDevicePipelineBinaryCacheKey *cacheKeys; -} WGPUWagyuDevicePipelineBinaryData WGPU_STRUCTURE_ATTRIBUTE; - -#define WGPU_WAGYU_DEVICE_PIPELINE_BINARY_DATA_INIT \ - WGPU_WAGYU_MAKE_INIT_STRUCT(WGPUWagyuDevicePipelineBinaryData, { /*.binariesLength*/ 0 _wgpu_COMMA /*.binaries*/ NULL _wgpu_COMMA /*.cacheKeysLength*/ 0 _wgpu_COMMA /*.cacheKeys*/ NULL _wgpu_COMMA }) - -typedef struct WGPUWagyuExternalTextureDescriptor -{ - const WGPUChainedStruct *nextInChain; - WGPUWagyuStringView label; - WGPUWagyuStringView source; - WGPUWagyuPredefinedColorSpace colorSpace; -} WGPUWagyuExternalTextureDescriptor WGPU_STRUCTURE_ATTRIBUTE; - -#define WGPU_WAGYU_EXTERNAL_TEXTURE_DESCRIPTOR_INIT \ - WGPU_WAGYU_MAKE_INIT_STRUCT(WGPUWagyuExternalTextureDescriptor, { /*nextInChain = */ NULL _wgpu_COMMA /*label = */ WGPU_WAGYU_STRING_VIEW_INIT _wgpu_COMMA /*source = */ WGPU_WAGYU_STRING_VIEW_INIT _wgpu_COMMA /*colorSpace = */ WGPUWagyuPredefinedColorSpace_SRGB _wgpu_COMMA }) - -typedef struct WGPUWagyuExternalTextureBindingEntry -{ - WGPUChainedStruct chain; - WGPUWagyuExternalTexture externalTexture; -} WGPUWagyuExternalTextureBindingEntry WGPU_STRUCTURE_ATTRIBUTE; - -#define WGPU_WAGYU_EXTERNAL_TEXTURE_BINDING_ENTRY_INIT \ - WGPU_WAGYU_MAKE_INIT_STRUCT(WGPUWagyuExternalTextureBindingEntry, \ - { /*.chain = */ WGPU_WAGYU_CHAIN_INIT(WGPUSType_WagyuExternalTextureBindingEntry) _wgpu_COMMA /*.externalTexture = */ NULL _wgpu_COMMA }) - -typedef struct WGPUWagyuExternalTextureBindingLayout -{ - WGPUChainedStruct chain; -} WGPUWagyuExternalTextureBindingLayout WGPU_STRUCTURE_ATTRIBUTE; - -#define WGPU_WAGYU_EXTERNAL_TEXTURE_BINDING_LAYOUT_INIT \ - WGPU_WAGYU_MAKE_INIT_STRUCT(WGPUWagyuExternalTextureBindingLayout, { /*.chain*/ WGPU_WAGYU_CHAIN_INIT(WGPUSType_WagyuExternalTextureBindingLayout) _wgpu_COMMA }) - -typedef struct WGPUWagyuInputAttachmentState -{ - WGPUTextureFormat format; - WGPUOptionalBool usedAsColor; -} WGPUWagyuInputAttachmentState WGPU_STRUCTURE_ATTRIBUTE; - -#define WGPU_WAGYU_INPUT_ATTACHMENT_STATE_INIT \ - WGPU_WAGYU_MAKE_INIT_STRUCT(WGPUWagyuInputAttachmentState, \ - { /*.format*/ WGPUTextureFormat_Undefined _wgpu_COMMA /*.usedAsColor*/ WGPUOptionalBool_Undefined _wgpu_COMMA }) - -typedef struct WGPUWagyuFragmentState -{ - WGPUChainedStruct chain; - size_t inputCount; - WGPU_NULLABLE WGPUWagyuInputAttachmentState *inputs; - WGPUWagyuFragmentStateFeaturesFlags featureFlags; -} WGPUWagyuFragmentState WGPU_STRUCTURE_ATTRIBUTE; - -#define WGPU_WAGYU_FRAGMENT_STATE_INIT \ - WGPU_WAGYU_MAKE_INIT_STRUCT(WGPUWagyuFragmentState, { /*.chain*/ WGPU_WAGYU_CHAIN_INIT(WGPUSType_WagyuFragmentState) _wgpu_COMMA /*.inputCount*/ 0 _wgpu_COMMA /*.inputs*/ NULL _wgpu_COMMA /*.featureFlags*/ WGPUWagyuFragmentStateFeaturesFlags_None _wgpu_COMMA }) - -typedef struct WGPUWagyuInputTextureBindingLayout -{ - WGPUChainedStruct chain; - WGPUTextureViewDimension viewDimension; -} WGPUWagyuInputTextureBindingLayout WGPU_STRUCTURE_ATTRIBUTE; - -#define WGPU_WAGYU_INPUT_TEXTURE_BINDING_LAYOUT_INIT \ - WGPU_WAGYU_MAKE_INIT_STRUCT(WGPUWagyuInputTextureBindingLayout, { /*.chain*/ WGPU_WAGYU_CHAIN_INIT(WGPUSType_WagyuInputTextureBindingLayout) _wgpu_COMMA /*.viewDimension*/ WGPUTextureViewDimension_2D _wgpu_COMMA }) - -typedef struct WGPUWagyuRect -{ - int32_t x; - int32_t y; - uint32_t width; - uint32_t height; -} WGPUWagyuRect WGPU_STRUCTURE_ATTRIBUTE; - -#define WGPU_WAGYU_RECT_INIT \ - WGPU_WAGYU_MAKE_INIT_STRUCT(WGPUWagyuRect, { /* .x */ 0 _wgpu_COMMA /* .y */ 0 _wgpu_COMMA /* .width */ 0 _wgpu_COMMA /* .height */ 0 _wgpu_COMMA }) - -typedef struct WGPUWagyuRenderPassInputAttachment -{ - WGPUTextureView view; - WGPU_NULLABLE WGPUColor *clearValue; - WGPULoadOp loadOp; - WGPUStoreOp storeOp; -} WGPUWagyuRenderPassInputAttachment WGPU_STRUCTURE_ATTRIBUTE; - -#define WGPU_WAGYU_RENDER_PASS_INPUT_ATTACHMENT_INIT \ - WGPU_WAGYU_MAKE_INIT_STRUCT(WGPUWagyuRenderPassInputAttachment, { /* .view */ NULL _wgpu_COMMA /* .clearValue */ NULL _wgpu_COMMA /* .loadOp */ WGPULoadOp_Undefined _wgpu_COMMA /* .storeOp */ WGPUStoreOp_Undefined _wgpu_COMMA }) - -typedef struct WGPUWagyuRenderPassDescriptor -{ - WGPUChainedStruct chain; - size_t inputAttachmentCount; - WGPU_NULLABLE WGPUWagyuRenderPassInputAttachment *inputAttachments; - WGPUOptionalBool pixelLocalStorageEnabled; - uint32_t pixelLocalStorageSize; -} WGPUWagyuRenderPassDescriptor WGPU_STRUCTURE_ATTRIBUTE; - -#define WGPU_WAGYU_RENDER_PASS_DESCRIPTOR_INIT \ - WGPU_WAGYU_MAKE_INIT_STRUCT(WGPUWagyuRenderPassDescriptor, { /* .chain */ WGPU_WAGYU_CHAIN_INIT(WGPUSType_WagyuRenderPassDescriptor) _wgpu_COMMA /* .inputAttachmentCount */ 0 _wgpu_COMMA /* .inputAttachments */ NULL _wgpu_COMMA /* .pixelLocalStorageEnabled */ WGPUOptionalBool_Undefined _wgpu_COMMA /* .pixelLocalStorageSize */ WGPU_WAGYU_PIXEL_LOCAL_STORAGE_SIZE_UNDEFINED _wgpu_COMMA }) - -typedef struct WGPUWagyuRenderPipelineDescriptor -{ - WGPUChainedStruct chain; - WGPUWagyuStringView cacheKey; -} WGPUWagyuRenderPipelineDescriptor WGPU_STRUCTURE_ATTRIBUTE; - -#define WGPU_WAGYU_RENDER_PIPELINE_DESCRIPTOR_INIT \ - WGPU_WAGYU_MAKE_INIT_STRUCT(WGPUWagyuRenderPipelineDescriptor, { /* .chain */ WGPU_WAGYU_CHAIN_INIT(WGPUSType_WagyuRenderPipelineDescriptor) _wgpu_COMMA /* .cacheKey */ WGPU_WAGYU_STRING_VIEW_INIT _wgpu_COMMA }) - -typedef struct WGPUWagyuShaderReflectionStructMember -{ - WGPUWagyuStringView name; - uint32_t group; - uint32_t binding; - uint32_t offset; - uint32_t size; - uint32_t type; - WGPUBool imageMultisampled; - WGPUTextureViewDimension imageDimension; - WGPUTextureFormat imageFormat; -} WGPUWagyuShaderReflectionStructMember WGPU_STRUCTURE_ATTRIBUTE; - -#define WGPU_WAGYU_SHADER_REFLECTION_STRUCT_MEMBER_INIT \ - WGPU_WAGYU_MAKE_INIT_STRUCT(WGPUWagyuShaderReflectionStructMember, { /* .name */ WGPU_WAGYU_STRING_VIEW_INIT _wgpu_COMMA /* .group */ 0 _wgpu_COMMA /* .binding */ 0 _wgpu_COMMA /* .offset */ 0 _wgpu_COMMA /* .size */ 0 _wgpu_COMMA /* .type */ 0 _wgpu_COMMA /* .imageMultisampled */ 0 _wgpu_COMMA /* .imageDimension */ WGPUTextureViewDimension_Undefined _wgpu_COMMA /* .imageFormat */ WGPUTextureFormat_Undefined _wgpu_COMMA }) - -typedef struct WGPUWagyuShaderReflectionLocation -{ - WGPUWagyuStringView name; - uint32_t location; - uint32_t size; - uint32_t type; -} WGPUWagyuShaderReflectionLocation WGPU_STRUCTURE_ATTRIBUTE; - -#define WGPU_WAGYU_SHADER_REFLECTION_LOCATION_INIT \ - WGPU_WAGYU_MAKE_INIT_STRUCT(WGPUWagyuShaderReflectionLocation, { /* .name */ WGPU_WAGYU_STRING_VIEW_INIT _wgpu_COMMA /* .location */ 0 _wgpu_COMMA /* .size */ 0 _wgpu_COMMA /* .type */ 0 _wgpu_COMMA }) - -typedef struct WGPUWagyuShaderReflectionResource -{ - WGPUWagyuStringView name; - uint32_t group; - uint32_t binding; - uint32_t bindingType; - WGPUBool multisampled; - WGPUTextureViewDimension dimension; - WGPUTextureFormat format; - uint64_t bufferSize; -} WGPUWagyuShaderReflectionResource WGPU_STRUCTURE_ATTRIBUTE; - -#define WGPU_WAGYU_SHADER_REFLECTION_RESOURCE_INIT \ - WGPU_WAGYU_MAKE_INIT_STRUCT(WGPUWagyuShaderReflectionResource, { /* .name */ WGPU_WAGYU_STRING_VIEW_INIT _wgpu_COMMA /* .group */ 0 _wgpu_COMMA /* .binding */ 0 _wgpu_COMMA /* .bindingType */ 0 _wgpu_COMMA /* .multisampled */ 0 _wgpu_COMMA /* .dimension */ WGPUTextureViewDimension_Undefined _wgpu_COMMA /* .format */ WGPUTextureFormat_Undefined _wgpu_COMMA /* .bufferSize */ 0 _wgpu_COMMA }) - -typedef struct WGPUWagyuShaderReflectionSpecializationConstant -{ - uint32_t id; - uint32_t internalId; - uint32_t type; - WGPUWagyuStringView name; -} WGPUWagyuShaderReflectionSpecializationConstant WGPU_STRUCTURE_ATTRIBUTE; - -#define WGPU_WAGYU_SHADER_REFLECTION_SPECIALIZATION_CONSTANT_INIT \ - WGPU_WAGYU_MAKE_INIT_STRUCT(WGPUWagyuShaderReflectionSpecializationConstant, { /* .id */ 0 _wgpu_COMMA /* .internalId */ 0 _wgpu_COMMA /* .type */ 0 _wgpu_COMMA /* .name */ WGPU_WAGYU_STRING_VIEW_INIT _wgpu_COMMA }) - -typedef struct WGPUWagyuShaderReflectionData -{ - size_t resourceCount; - WGPUWagyuShaderReflectionResource *resources; - size_t constantCount; - WGPUWagyuShaderReflectionSpecializationConstant *constants; - size_t uniformCount; - WGPUWagyuShaderReflectionStructMember *uniforms; - size_t attributeCount; - WGPUWagyuShaderReflectionLocation *attributes; - WGPUWagyuStringView wgsl; -} WGPUWagyuShaderReflectionData WGPU_STRUCTURE_ATTRIBUTE; - -#define WGPU_WAGYU_SHADER_REFLECTION_DATA_INIT \ - WGPU_WAGYU_MAKE_INIT_STRUCT(WGPUWagyuShaderReflectionData, { /* .resourceCount */ 0 _wgpu_COMMA /* .resources */ NULL _wgpu_COMMA /* .constantCount */ 0 _wgpu_COMMA /* .constants */ NULL _wgpu_COMMA /* .uniformCount */ 0 _wgpu_COMMA /* .uniforms */ NULL _wgpu_COMMA /* .attributeCount */ 0 _wgpu_COMMA /* .attributes */ NULL _wgpu_COMMA /* .wgsl */ WGPU_WAGYU_STRING_VIEW_INIT _wgpu_COMMA }) - -typedef struct WGPUWagyuShaderEntryPoint -{ - WGPUWagyuStringView entryPoint; - WGPUShaderStage stage; - WGPUWagyuShaderReflectionData reflection; -} WGPUWagyuShaderEntryPoint WGPU_STRUCTURE_ATTRIBUTE; - -#define WGPU_WAGYU_SHADER_ENTRY_POINT_INIT \ - WGPU_WAGYU_MAKE_INIT_STRUCT(WGPUWagyuShaderEntryPoint, { /* .entryPoint */ WGPU_WAGYU_STRING_VIEW_INIT _wgpu_COMMA /* .stage */ WGPUShaderStage_NONE _wgpu_COMMA /* .reflection */ WGPU_WAGYU_SHADER_REFLECTION_DATA_INIT _wgpu_COMMA }) - -typedef struct WGPUWagyuShaderEntryPointArray -{ - size_t entryPointCount; - WGPUWagyuShaderEntryPoint *entryPoints; -} WGPUWagyuShaderEntryPointArray WGPU_STRUCTURE_ATTRIBUTE; - -#define WGPU_WAGYU_SHADER_ENTRY_POINT_ARRAY_INIT \ - WGPU_WAGYU_MAKE_INIT_STRUCT(WGPUWagyuShaderEntryPointArray, { /* .entryPointCount */ 0 _wgpu_COMMA /* .entryPoints */ NULL _wgpu_COMMA }) - -typedef struct WGPUWagyuRenderPassEncoderClearPixelLocalStorage -{ - uint32_t offset; - size_t valueCount; - WGPU_NULLABLE uint32_t *values; - uint32_t size; -} WGPUWagyuRenderPassEncoderClearPixelLocalStorage WGPU_STRUCTURE_ATTRIBUTE; - -#define WGPU_WAGYU_RENDER_PASS_ENCODER_CLEAR_PIXEL_LOCAL_STORAGE_INIT \ - WGPU_WAGYU_MAKE_INIT_STRUCT(WGPUWagyuRenderPassEncoderClearPixelLocalStorage, { /* .offset */ 0 _wgpu_COMMA /* .valueCount */ 0 _wgpu_COMMA /* .values */ NULL _wgpu_COMMA /* .size */ WGPU_WAGYU_PIXEL_LOCAL_STORAGE_SIZE_UNDEFINED _wgpu_COMMA }) - -typedef struct WGPUWagyuShaderModuleCompilationHint -{ - WGPUChainedStruct *nextInChain; - WGPUWagyuStringView entryPoint; - /** - * If set to NULL, it will be treated as "auto" - */ - WGPUPipelineLayout layout; -} WGPUWagyuShaderModuleCompilationHint; - -#define WGPU_WAGYU_SHADER_MODULE_COMPILATION_HINT_INIT \ - WGPU_WAGYU_MAKE_INIT_STRUCT(WGPUWagyuShaderModuleCompilationHint, { /* .nextInChain */ NULL _wgpu_COMMA /* .entryPoint */ WGPU_WAGYU_STRING_VIEW_INIT _wgpu_COMMA /* .layout */ NULL _wgpu_COMMA }) - -typedef struct WGPUWagyuShaderModuleDescriptor -{ - WGPUChainedStruct chain; - size_t codeSize; // bytes - const void *code; - WGPUWagyuShaderLanguage language; - size_t compilationHintCount; - const struct WGPUWagyuShaderModuleCompilationHint *compilationHints; -} WGPUWagyuShaderModuleDescriptor WGPU_STRUCTURE_ATTRIBUTE; - -#define WGPU_WAGYU_SHADER_MODULE_DESCRIPTOR_INIT \ - WGPU_WAGYU_MAKE_INIT_STRUCT(WGPUWagyuShaderModuleDescriptor, { /*.chain=*/WGPU_WAGYU_CHAIN_INIT(WGPUSType_WagyuShaderModuleDescriptor) _wgpu_COMMA /*.codeSize*/ 0 _wgpu_COMMA /*.code*/ NULL _wgpu_COMMA /*.language*/ WGPUWagyuShaderLanguage_Detect _wgpu_COMMA /*.compilationHintCount*/ 0 _wgpu_COMMA /*.compilationHints*/ NULL _wgpu_COMMA }) - -typedef struct WGPUWagyuStringArray -{ - size_t stringCount; - WGPU_NULLABLE WGPUWagyuStringView *strings; -} WGPUWagyuStringArray WGPU_STRUCTURE_ATTRIBUTE; - -#define WGPU_WAGYU_STRING_ARRAY_INIT \ - WGPU_WAGYU_MAKE_INIT_STRUCT(WGPUWagyuStringArray, { /* .stringCount */ 0 _wgpu_COMMA /* .strings */ NULL _wgpu_COMMA }) - -typedef struct WGPUWagyuSurfaceConfiguration -{ - WGPUChainedStruct chain; - int32_t *indirectRenderTargets; -} WGPUWagyuSurfaceConfiguration WGPU_STRUCTURE_ATTRIBUTE; - -#define WGPU_WAGYU_SURFACE_CONFIGURATION_INIT \ - WGPU_WAGYU_MAKE_INIT_STRUCT(WGPUWagyuSurfaceConfiguration, { /*.chain=*/WGPU_WAGYU_CHAIN_INIT(WGPUSType_WagyuSurfaceConfiguration) _wgpu_COMMA /*.indirectRenderTargets*/ NULL _wgpu_COMMA }) - -typedef struct WGPUWagyuTextureDescriptor -{ - WGPUChainedStruct chain; - WGPUBool useSurfaceCache; -} WGPUWagyuTextureDescriptor WGPU_STRUCTURE_ATTRIBUTE; - -#define WGPU_WAGYU_TEXTURE_DESCRIPTOR_INIT \ - WGPU_WAGYU_MAKE_INIT_STRUCT(WGPUWagyuTextureDescriptor, { /*.chain = */ WGPU_WAGYU_CHAIN_INIT(WGPUSType_WagyuTextureDescriptor) _wgpu_COMMA /*.useSurfaceCache = */ 1 _wgpu_COMMA }) - -typedef struct WGPUWagyuWGSLFeatureTypeArray -{ - size_t featureCount; - WGPU_NULLABLE WGPUWagyuWGSLFeatureType *features; -} WGPUWagyuWGSLFeatureTypeArray WGPU_STRUCTURE_ATTRIBUTE; - -#define WGPU_WAGYU_WGSL_FEATURE_TYPE_ARRAY_INIT \ - WGPU_WAGYU_MAKE_INIT_STRUCT(WGPUWagyuWGSLFeatureTypeArray, { /* .featureCount */ 0 _wgpu_COMMA /* .features */ NULL _wgpu_COMMA }) - -#if defined(__cplusplus) && !defined(USE_WGPU_WAGYU_NAMESPACE) && !defined(__cppcheck) -extern "C" { -#endif - -WGPU_EXPORT WGPUBackendType wgpuWagyuAdapterGetBackend(WGPUAdapter adapter) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuWagyuAdapterGetExtensions(WGPUAdapter adapter, WGPUWagyuStringArray *extensions) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuWagyuAdapterGetGraphicsReport(WGPUAdapter adapter, WGPUWagyuStringView *graphicsReport) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuWagyuAdapterGetName(WGPUAdapter adapter, WGPUWagyuStringView *name) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT WGPUDevice wgpuWagyuAdapterRequestDeviceSync(WGPUAdapter adapter, WGPU_NULLABLE const WGPUDeviceDescriptor *options) WGPU_FUNCTION_ATTRIBUTE; - -WGPU_EXPORT void wgpuWagyuCommandEncoderBlit(WGPUCommandEncoder commandEncoder, const WGPUImageCopyTexture *source, const WGPUExtent3D *sourceExtent, const WGPUImageCopyTexture *destination, const WGPUExtent3D *destinationExtent, WGPUFilterMode filter) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuWagyuCommandEncoderGenerateMipmap(WGPUCommandEncoder commandEncoder, WGPUTexture texture) WGPU_FUNCTION_ATTRIBUTE; - -WGPU_EXPORT void wgpuWagyuDeviceClearPipelineBinaryCache(WGPUDevice device) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuWagyuDeviceEnableImaginationWorkarounds(WGPUDevice device, WGPUBool enable) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuWagyuDeviceGetExtensions(WGPUDevice device, WGPUWagyuStringArray *extensions) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuWagyuDeviceFlush(WGPUDevice device, WGPUWagyuDeviceFlushCallback callback, void *userdata) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT WGPUWagyuExternalTexture wgpuWagyuDeviceImportExternalTexture(WGPUDevice device, const WGPUWagyuExternalTextureDescriptor *descriptor) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuWagyuDeviceIntrospectShaderCode(WGPUDevice device, WGPUShaderStage stages, const WGPUShaderModuleDescriptor *descriptor, WGPUWagyuShaderEntryPointArray *entryPoints) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuWagyuDevicePopulatePipelineBinaryCache(WGPUDevice device, const WGPUWagyuDevicePipelineBinaryData *data) WGPU_FUNCTION_ATTRIBUTE; - -WGPU_EXPORT void wgpuWagyuExternalTextureReference(WGPUWagyuExternalTexture externalTexture) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuWagyuExternalTextureRelease(WGPUWagyuExternalTexture externalTexture) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuWagyuExternalTextureSetLabel(WGPUWagyuExternalTexture externalTexture, const char *label) WGPU_FUNCTION_ATTRIBUTE; - -WGPU_EXPORT void wgpuWagyuInstanceEnableImaginationWorkarounds(WGPUInstance instance, WGPUBool enable) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT uint32_t wgpuWagyuInstanceGetApiVersion(WGPUInstance instance) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT WGPUBackendType wgpuWagyuInstanceGetBackend(WGPUInstance instance) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuWagyuInstanceGetExposeWGSLFeatures(WGPUInstance instance, WGPUWagyuWGSLFeatureTypeArray *wgslFeatures) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT WGPUWagyuRelaxedCompliance wgpuWagyuInstanceGetRelaxedCompliance(WGPUInstance instance) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT WGPUTextureFormat wgpuWagyuInstanceGetScreenDirectFormat(WGPUInstance instance) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT WGPUTextureFormat wgpuWagyuInstanceGetScreenIndirectFormat(WGPUInstance instance) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT WGPUBool wgpuWagyuInstanceGetSync(WGPUInstance instance) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT WGPUAdapter wgpuWagyuInstanceRequestAdapterSync(WGPUInstance instance, WGPU_NULLABLE const WGPURequestAdapterOptions *options) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuWagyuInstanceSetCommandBufferLimit(WGPUInstance instance, uint32_t limit) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuWagyuInstanceSetExposeWGSLFeatures(WGPUInstance instance, const WGPUWagyuWGSLFeatureTypeArray *wgslFeatures) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuWagyuInstanceSetImmediate(WGPUInstance instance, WGPUBool enabled) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuWagyuInstanceSetRunBarriersOnIncoherent(WGPUInstance instance, WGPUBool run) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuWagyuInstanceSetStagingBufferCacheSize(WGPUInstance instance, uint32_t size) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuWagyuInstanceSetSync(WGPUInstance instance, WGPUBool sync) WGPU_FUNCTION_ATTRIBUTE; - -WGPU_EXPORT void wgpuWagyuRelaxedComplianceReference(WGPUWagyuRelaxedCompliance relaxedCompliance) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuWagyuRelaxedComplianceRelease(WGPUWagyuRelaxedCompliance relaxedCompliance) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT WGPUBool wgpuWagyuRelaxedComplianceGetBufferClear(WGPUWagyuRelaxedCompliance relaxedCompliance) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT WGPUBool wgpuWagyuRelaxedComplianceGetTextureClear(WGPUWagyuRelaxedCompliance relaxedCompliance) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuWagyuRelaxedComplianceSetAll(WGPUWagyuRelaxedCompliance relaxedCompliance, WGPUBool enable) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuWagyuRelaxedComplianceSetBufferClear(WGPUWagyuRelaxedCompliance relaxedCompliance, WGPUBool enable) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuWagyuRelaxedComplianceSetTextureClear(WGPUWagyuRelaxedCompliance relaxedCompliance, WGPUBool enable) WGPU_FUNCTION_ATTRIBUTE; - -WGPU_EXPORT void wgpuWagyuRenderBundleEncoderClearColorAttachments(WGPURenderBundleEncoder renderBundleEncoder, const WGPUWagyuRect *rect, uint32_t baseAttachment, uint32_t numAttachments, const WGPUColor *color, uint32_t baseArrayLayer, uint32_t layerCount) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuWagyuRenderBundleEncoderClearDepthAttachment(WGPURenderBundleEncoder renderBundleEncoder, const WGPUWagyuRect *rect, float depth, uint32_t baseArrayLayer, uint32_t layerCount) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuWagyuRenderBundleEncoderClearStencilAttachment(WGPURenderBundleEncoder renderBundleEncoder, const WGPUWagyuRect *rect, uint32_t stencil, uint32_t baseArrayLayer, uint32_t layerCount) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuWagyuRenderBundleEncoderSetScissorRect(WGPURenderBundleEncoder renderBundleEncoder, uint32_t x, uint32_t y, uint32_t width, uint32_t height) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuWagyuRenderBundleEncoderSetScissorRectIndirect(WGPURenderBundleEncoder renderBundleEncoder, uint64_t indirectOffset, const uint32_t *indirectBuffer, size_t indirectBufferCount) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuWagyuRenderBundleEncoderSetViewport(WGPURenderBundleEncoder renderBundleEncoder, float x, float y, float width, float height, float minDepth, float maxDepth) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuWagyuRenderBundleEncoderSetViewportWithDepthIndirect(WGPURenderBundleEncoder renderBundleEncoder, uint64_t indirectOffset, const float *indirectBuffer, size_t indirectBufferCount) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuWagyuRenderBundleEncoderSetViewportWithoutDepthIndirect(WGPURenderBundleEncoder renderBundleEncoder, uint64_t indirectOffset, const float *indirectBuffer, size_t indirectBufferCount) WGPU_FUNCTION_ATTRIBUTE; - -WGPU_EXPORT void wgpuWagyuRenderPassEncoderClearColorAttachments(WGPURenderPassEncoder renderPassEncoder, const WGPUWagyuRect *rect, uint32_t baseAttachment, uint32_t numAttachments, const WGPUColor *color, uint32_t baseArrayLayer, uint32_t layerCount) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuWagyuRenderPassEncoderClearDepthAttachment(WGPURenderPassEncoder renderPassEncoder, const WGPUWagyuRect *rect, float depth, uint32_t baseArrayLayer, uint32_t layerCount) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuWagyuRenderPassEncoderClearStencilAttachment(WGPURenderPassEncoder renderPassEncoder, const WGPUWagyuRect *rect, uint32_t stencil, uint32_t baseArrayLayer, uint32_t layerCount) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuWagyuRenderPassEncoderClearPixelLocalStorage(WGPURenderPassEncoder renderPassEncoder, const WGPUWagyuRenderPassEncoderClearPixelLocalStorage *options) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuWagyuRenderPassEncoderExecuteBundle(WGPURenderPassEncoder renderPassEncoder, WGPURenderBundle bundle) WGPU_FUNCTION_ATTRIBUTE; - -WGPU_EXPORT void wgpuWagyuShaderEntryPointArrayFreeMembers(WGPUWagyuShaderEntryPointArray value) WGPU_FUNCTION_ATTRIBUTE; - -WGPU_EXPORT void wgpuWagyuShaderModuleDestroy(WGPUShaderModule shaderModule) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuWagyuShaderModuleIntrospect(WGPUShaderModule shaderModule, WGPUShaderStage stages, WGPUWagyuShaderEntryPointArray *shaderEntryPointArray) WGPU_FUNCTION_ATTRIBUTE; - -WGPU_EXPORT void wgpuWagyuSurfaceDestroy(WGPUSurface surface) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT WGPUTexture wgpuWagyuSurfaceGetCurrentDepthStencilTexture(WGPUSurface surface) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT float wgpuWagyuSurfaceGetHeight(WGPUSurface surface) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT float wgpuWagyuSurfaceGetWidth(WGPUSurface surface) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT float wgpuWagyuSurfaceGetX(WGPUSurface surface) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT float wgpuWagyuSurfaceGetY(WGPUSurface surface) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuWagyuSurfacePresent(WGPUSurface surface, WGPUTexture target) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuWagyuSurfaceSetHeight(WGPUSurface surface, float height) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuWagyuSurfaceSetWidth(WGPUSurface surface, float width) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuWagyuSurfaceSetX(WGPUSurface surface, float x) WGPU_FUNCTION_ATTRIBUTE; -WGPU_EXPORT void wgpuWagyuSurfaceSetY(WGPUSurface surface, float y) WGPU_FUNCTION_ATTRIBUTE; - -WGPU_EXPORT void wgpuWagyuWGSLFeatureTypeArrayFreeMembers(WGPUWagyuWGSLFeatureTypeArray value) WGPU_FUNCTION_ATTRIBUTE; - -#if defined(__cplusplus) && !defined(USE_WGPU_WAGYU_NAMESPACE) && !defined(__cppcheck) -} // extern "C" -#endif - -#if defined(USE_WGPU_WAGYU_NAMESPACE) || defined(__cppcheck) -} // namespace wagyu1 -#endif - -#endif /* WEBGPU_WAGYU_H */ diff --git a/defold-rive/include/rive/scene.hpp b/defold-rive/include/rive/scene.hpp index 22ab5ee8..100da442 100644 --- a/defold-rive/include/rive/scene.hpp +++ b/defold-rive/include/rive/scene.hpp @@ -52,10 +52,12 @@ class Scene : public KeyedCallbackReporter, public CallbackContext virtual void bindViewModelInstance( rcp viewModelInstance); - virtual HitResult pointerDown(Vec2D); - virtual HitResult pointerMove(Vec2D position, float timeStamp = 0); - virtual HitResult pointerUp(Vec2D); - virtual HitResult pointerExit(Vec2D); + virtual HitResult pointerDown(Vec2D, int pointerId = 0); + virtual HitResult pointerMove(Vec2D position, + float timeStamp = 0, + int pointerId = 0); + virtual HitResult pointerUp(Vec2D, int pointerId = 0); + virtual HitResult pointerExit(Vec2D, int pointerId = 0); virtual size_t inputCount() const; virtual SMIInput* input(size_t index) const; diff --git a/defold-rive/include/rive/script_input_artboard.hpp b/defold-rive/include/rive/script_input_artboard.hpp new file mode 100644 index 00000000..e8f1c1e0 --- /dev/null +++ b/defold-rive/include/rive/script_input_artboard.hpp @@ -0,0 +1,39 @@ +#ifndef _RIVE_SCRIPT_INPUT_ARTBOARD_HPP_ +#define _RIVE_SCRIPT_INPUT_ARTBOARD_HPP_ +#include "rive/generated/script_input_artboard_base.hpp" +#include "rive/assets/script_asset.hpp" +#include "rive/scripted/scripted_object.hpp" +#include +namespace rive +{ +class Artboard; + +class ScriptInputArtboard : public ScriptInputArtboardBase, public ScriptInput +{ +private: + Artboard* m_artboard = nullptr; + +public: + ~ScriptInputArtboard(); + void artboard(Artboard* artboard) { m_artboard = artboard; } + void initScriptedValue() override + { + ScriptInput::initScriptedValue(); + if (m_artboard == nullptr) + { + return; + } + auto obj = scriptedObject(); + if (obj) + { + obj->setArtboardInput(name(), m_artboard); + } + } + bool validateForScriptInit() override { return m_artboard != nullptr; } + StatusCode import(ImportStack& importStack) override; + Core* clone() const override; + StatusCode onAddedClean(CoreContext* context) override; +}; +} // namespace rive + +#endif \ No newline at end of file diff --git a/defold-rive/include/rive/script_input_boolean.hpp b/defold-rive/include/rive/script_input_boolean.hpp new file mode 100644 index 00000000..12190581 --- /dev/null +++ b/defold-rive/include/rive/script_input_boolean.hpp @@ -0,0 +1,31 @@ +#ifndef _RIVE_SCRIPT_INPUT_BOOLEAN_HPP_ +#define _RIVE_SCRIPT_INPUT_BOOLEAN_HPP_ +#include "rive/generated/script_input_boolean_base.hpp" +#include "rive/assets/script_asset.hpp" +#include "rive/scripted/scripted_object.hpp" +#include +namespace rive +{ +class ScriptInputBoolean : public ScriptInputBooleanBase, public ScriptInput +{ +protected: + void propertyValueChanged() override; + +public: + ~ScriptInputBoolean(); + void initScriptedValue() override + { + ScriptInput::initScriptedValue(); + auto obj = scriptedObject(); + if (obj) + { + obj->setBooleanInput(name(), propertyValue()); + } + } + bool validateForScriptInit() override { return true; } + StatusCode import(ImportStack& importStack) override; + StatusCode onAddedClean(CoreContext* context) override; +}; +} // namespace rive + +#endif \ No newline at end of file diff --git a/defold-rive/include/rive/script_input_color.hpp b/defold-rive/include/rive/script_input_color.hpp new file mode 100644 index 00000000..6e703af5 --- /dev/null +++ b/defold-rive/include/rive/script_input_color.hpp @@ -0,0 +1,31 @@ +#ifndef _RIVE_SCRIPT_INPUT_COLOR_HPP_ +#define _RIVE_SCRIPT_INPUT_COLOR_HPP_ +#include "rive/generated/script_input_color_base.hpp" +#include "rive/assets/script_asset.hpp" +#include "rive/scripted/scripted_object.hpp" +#include +namespace rive +{ +class ScriptInputColor : public ScriptInputColorBase, public ScriptInput +{ +protected: + void propertyValueChanged() override; + +public: + ~ScriptInputColor(); + void initScriptedValue() override + { + ScriptInput::initScriptedValue(); + auto obj = scriptedObject(); + if (obj) + { + obj->setIntegerInput(name(), propertyValue()); + } + } + bool validateForScriptInit() override { return true; } + StatusCode import(ImportStack& importStack) override; + StatusCode onAddedClean(CoreContext* context) override; +}; +} // namespace rive + +#endif \ No newline at end of file diff --git a/defold-rive/include/rive/script_input_number.hpp b/defold-rive/include/rive/script_input_number.hpp new file mode 100644 index 00000000..95db330d --- /dev/null +++ b/defold-rive/include/rive/script_input_number.hpp @@ -0,0 +1,31 @@ +#ifndef _RIVE_SCRIPT_INPUT_NUMBER_HPP_ +#define _RIVE_SCRIPT_INPUT_NUMBER_HPP_ +#include "rive/generated/script_input_number_base.hpp" +#include "rive/assets/script_asset.hpp" +#include "rive/scripted/scripted_object.hpp" +#include +namespace rive +{ +class ScriptInputNumber : public ScriptInputNumberBase, public ScriptInput +{ +protected: + void propertyValueChanged() override; + +public: + ~ScriptInputNumber(); + void initScriptedValue() override + { + ScriptInput::initScriptedValue(); + auto obj = scriptedObject(); + if (obj) + { + obj->setNumberInput(name(), propertyValue()); + } + } + StatusCode onAddedClean(CoreContext* context) override; + bool validateForScriptInit() override { return true; } + StatusCode import(ImportStack& importStack) override; +}; +} // namespace rive + +#endif \ No newline at end of file diff --git a/defold-rive/include/rive/script_input_string.hpp b/defold-rive/include/rive/script_input_string.hpp new file mode 100644 index 00000000..2d7e227c --- /dev/null +++ b/defold-rive/include/rive/script_input_string.hpp @@ -0,0 +1,31 @@ +#ifndef _RIVE_SCRIPT_INPUT_STRING_HPP_ +#define _RIVE_SCRIPT_INPUT_STRING_HPP_ +#include "rive/generated/script_input_string_base.hpp" +#include "rive/assets/script_asset.hpp" +#include "rive/scripted/scripted_object.hpp" +#include +namespace rive +{ +class ScriptInputString : public ScriptInputStringBase, public ScriptInput +{ +protected: + void propertyValueChanged() override; + +public: + ~ScriptInputString(); + void initScriptedValue() override + { + ScriptInput::initScriptedValue(); + auto obj = scriptedObject(); + if (obj) + { + obj->setStringInput(name(), propertyValue()); + } + } + bool validateForScriptInit() override { return true; } + StatusCode import(ImportStack& importStack) override; + StatusCode onAddedClean(CoreContext* context) override; +}; +} // namespace rive + +#endif \ No newline at end of file diff --git a/defold-rive/include/rive/script_input_trigger.hpp b/defold-rive/include/rive/script_input_trigger.hpp new file mode 100644 index 00000000..1d817872 --- /dev/null +++ b/defold-rive/include/rive/script_input_trigger.hpp @@ -0,0 +1,22 @@ +#ifndef _RIVE_SCRIPT_INPUT_TRIGGER_HPP_ +#define _RIVE_SCRIPT_INPUT_TRIGGER_HPP_ +#include "rive/generated/script_input_trigger_base.hpp" +#include "rive/assets/script_asset.hpp" +#include "rive/scripted/scripted_object.hpp" +#include +namespace rive +{ +class ScriptInputTrigger : public ScriptInputTriggerBase, public ScriptInput +{ +protected: + void propertyValueChanged() override; + +public: + ~ScriptInputTrigger(); + bool validateForScriptInit() override { return true; } + StatusCode import(ImportStack& importStack) override; + StatusCode onAddedClean(CoreContext* context) override; +}; +} // namespace rive + +#endif \ No newline at end of file diff --git a/defold-rive/include/rive/script_input_viewmodel_property.hpp b/defold-rive/include/rive/script_input_viewmodel_property.hpp new file mode 100644 index 00000000..cf0bfe3a --- /dev/null +++ b/defold-rive/include/rive/script_input_viewmodel_property.hpp @@ -0,0 +1,31 @@ +#ifndef _RIVE_SCRIPT_INPUT_VIEW_MODEL_PROPERTY_HPP_ +#define _RIVE_SCRIPT_INPUT_VIEW_MODEL_PROPERTY_HPP_ +#include "rive/generated/script_input_viewmodel_property_base.hpp" +#include "rive/assets/script_asset.hpp" +#include "rive/scripted/scripted_object.hpp" +#include "rive/data_bind_path_referencer.hpp" +#include +namespace rive +{ +class ViewModelInstanceValue; + +class ScriptInputViewModelProperty : public ScriptInputViewModelPropertyBase, + public ScriptInput, + public DataBindPathReferencer +{ +private: + ViewModelInstanceValue* m_viewModelInstanceValue; + +public: + ~ScriptInputViewModelProperty(); + void decodeDataBindPathIds(Span value) override; + void copyDataBindPathIds( + const ScriptInputViewModelPropertyBase& object) override; + void initScriptedValue() override; + bool validateForScriptInit() override; + StatusCode import(ImportStack& importStack) override; + StatusCode onAddedClean(CoreContext* context) override; +}; +} // namespace rive + +#endif \ No newline at end of file diff --git a/defold-rive/include/rive/scripted/scripted_data_converter.hpp b/defold-rive/include/rive/scripted/scripted_data_converter.hpp new file mode 100644 index 00000000..769e973e --- /dev/null +++ b/defold-rive/include/rive/scripted/scripted_data_converter.hpp @@ -0,0 +1,70 @@ +#ifndef _RIVE_SCRIPTED_DATA_CONVERTER_HPP_ +#define _RIVE_SCRIPTED_DATA_CONVERTER_HPP_ +#ifdef WITH_RIVE_SCRIPTING +#include "rive/lua/rive_lua_libs.hpp" +#endif +#include "rive/generated/scripted/scripted_data_converter_base.hpp" +#include "rive/advancing_component.hpp" +#include "rive/scripted/scripted_object.hpp" +#include +namespace rive +{ +class DataBind; +class DataContext; +class DataValue; + +class ScriptedDataConverter : public ScriptedDataConverterBase, + public ScriptedObject, + public AdvancingComponent +{ +private: + DataContext* m_dataContext = nullptr; + DataValue* m_dataValue = nullptr; + template void storeData(DataValue* input) + { + if (m_dataValue && !m_dataValue->is()) + { + delete m_dataValue; + } + if (!m_dataValue) + { + m_dataValue = new T(); + } + m_dataValue->as()->value(input->as()->value()); + }; + virtual void disposeScriptInputs() override; +#ifdef WITH_RIVE_SCRIPTING + DataValue* applyConversion(DataValue* value, const std::string& method); +#endif + +public: + ~ScriptedDataConverter(); +#ifdef WITH_RIVE_SCRIPTING + bool scriptInit(LuaState* state) override; + DataValue* convert(DataValue* value, DataBind* dataBind) override; + DataValue* reverseConvert(DataValue* value, DataBind* dataBind) override; +#endif + void bindFromContext(DataContext* dataContext, DataBind* dataBind) override; + DataContext* dataContext() override { return m_dataContext; } + DataType outputType() override { return DataType::any; } + uint32_t assetId() override { return scriptAssetId(); } + bool advanceComponent(float elapsedSeconds, + AdvanceFlags flags = AdvanceFlags::Animate | + AdvanceFlags::NewFrame) override; + StatusCode import(ImportStack& importStack) override; + void addProperty(CustomProperty* prop) override; + Core* clone() const override; + bool addScriptedDirt(ComponentDirt value, bool recurse = false) override + { + markConverterDirty(); + return true; + } + ScriptProtocol scriptProtocol() override + { + return ScriptProtocol::converter; + } + Component* component() override { return nullptr; } +}; +} // namespace rive + +#endif \ No newline at end of file diff --git a/defold-rive/include/rive/scripted/scripted_drawable.hpp b/defold-rive/include/rive/scripted/scripted_drawable.hpp new file mode 100644 index 00000000..382c1057 --- /dev/null +++ b/defold-rive/include/rive/scripted/scripted_drawable.hpp @@ -0,0 +1,97 @@ +#ifndef _RIVE_SCRIPTED_DRAWABLE_HPP_ +#define _RIVE_SCRIPTED_DRAWABLE_HPP_ +#ifdef WITH_RIVE_SCRIPTING +#include "rive/lua/rive_lua_libs.hpp" +#endif +#include "rive/generated/scripted/scripted_drawable_base.hpp" +#include "rive/animation/state_machine_instance.hpp" +#include "rive/advancing_component.hpp" +#include "rive/assets/script_asset.hpp" +#include "rive/listener_group.hpp" +#include "rive/scripted/scripted_object.hpp" +#include "rive/custom_property_group.hpp" +#include +namespace rive +{ +class Component; +class HitComponent; +class HitScriptedDrawable; + +class ScriptedDrawable : public ScriptedDrawableBase, + public ScriptedObject, + public AdvancingComponent, + public ListenerGroupProvider +{ +public: +#ifdef WITH_RIVE_SCRIPTING + bool scriptInit(LuaState* state) override; +#endif + void draw(Renderer* renderer) override; + void update(ComponentDirt value) override; + Core* hitTest(HitInfo*, const Mat2D&) override; + uint32_t assetId() override { return scriptAssetId(); } + StatusCode onAddedDirty(CoreContext* context) override; + bool advanceComponent(float elapsedSeconds, + AdvanceFlags flags = AdvanceFlags::Animate | + AdvanceFlags::NewFrame) override; + StatusCode import(ImportStack& importStack) override; + Core* clone() const override; + const std::vector& containerChildren() const override + { + return children(); + } + void addProperty(CustomProperty* prop) override; + bool addScriptedDirt(ComponentDirt value, bool recurse = false) override; + DataContext* dataContext() override + { + if (artboard() != nullptr) + { + return artboard()->dataContext(); + } + return nullptr; + } + ScriptProtocol scriptProtocol() override { return ScriptProtocol::node; } + std::vector listenerGroups() override + { + return {}; + } + std::vector hitComponents(StateMachineInstance* sm) override; + bool worldToLocal(Vec2D world, Vec2D* local); + void markNeedsUpdate() override; + bool willDraw() override; + Component* component() override { return this; } + +private: + bool m_isAdvanceActive = true; +}; + +class HitScriptedDrawable : public HitComponent +{ +private: + ScriptedDrawable* m_drawable; + bool handlesEvent(bool canHit, ListenerType hitEvent); + std::string methodName(bool canHit, ListenerType hitEvent); + +public: + HitScriptedDrawable(ScriptedDrawable* drawable, + StateMachineInstance* stateMachineInstance) : + HitComponent(drawable, stateMachineInstance) + { + this->m_drawable = drawable; + } + + bool hitTest(Vec2D position) const override { return true; } + void prepareEvent(Vec2D position, + ListenerType hitType, + int pointerId) override + {} + + HitResult processEvent(Vec2D position, + ListenerType hitType, + bool canHit, + float timeStamp, + int pointerId) override; +}; +} // namespace rive + +#endif \ No newline at end of file diff --git a/defold-rive/include/rive/scripted/scripted_layout.hpp b/defold-rive/include/rive/scripted/scripted_layout.hpp new file mode 100644 index 00000000..311aad6f --- /dev/null +++ b/defold-rive/include/rive/scripted/scripted_layout.hpp @@ -0,0 +1,39 @@ +#ifndef _RIVE_SCRIPTED_LAYOUT_HPP_ +#define _RIVE_SCRIPTED_LAYOUT_HPP_ +#ifdef WITH_RIVE_SCRIPTING +#include "rive/lua/rive_lua_libs.hpp" +#endif +#include "rive/layout/layout_enums.hpp" +#include "rive/layout/layout_measure_mode.hpp" +#include "rive/generated/scripted/scripted_layout_base.hpp" +#include +namespace rive +{ +class ScriptedLayout : public ScriptedLayoutBase +{ +private: + Vec2D m_size; +#ifdef WITH_RIVE_SCRIPTING + void callScriptedResize(Vec2D size); +#endif + +public: +#ifdef WITH_RIVE_SCRIPTING + bool scriptInit(LuaState* luaState) override; +#endif + Vec2D measureLayout(float width, + LayoutMeasureMode widthMode, + float height, + LayoutMeasureMode heightMode) override; + + void controlSize(Vec2D size, + LayoutScaleType widthScaleType, + LayoutScaleType heightScaleType, + LayoutDirection direction) override; + void addProperty(CustomProperty* prop) override; + Core* clone() const override; + ScriptProtocol scriptProtocol() override { return ScriptProtocol::layout; } +}; +} // namespace rive + +#endif \ No newline at end of file diff --git a/defold-rive/include/rive/scripted/scripted_object.hpp b/defold-rive/include/rive/scripted/scripted_object.hpp new file mode 100644 index 00000000..c4c94ad0 --- /dev/null +++ b/defold-rive/include/rive/scripted/scripted_object.hpp @@ -0,0 +1,61 @@ +#ifndef _RIVE_SCRIPTED_OBJECT_HPP_ +#define _RIVE_SCRIPTED_OBJECT_HPP_ +#ifdef WITH_RIVE_SCRIPTING +#include "rive/lua/rive_lua_libs.hpp" +#endif +#include "rive/assets/file_asset_referencer.hpp" +#include "rive/assets/script_asset.hpp" +#include "rive/custom_property.hpp" +#include "rive/custom_property_container.hpp" +#include "rive/refcnt.hpp" +#include "rive/generated/assets/script_asset_base.hpp" +#include +namespace rive +{ +class Artboard; +class Component; +class DataContext; +class ViewModelInstanceValue; + +class ScriptedObject : public FileAssetReferencer, + public CustomPropertyContainer, + public OptionalScriptedMethods +{ +protected: + int m_self = 0; + int m_context = 0; + virtual void disposeScriptInputs(); +#ifdef WITH_RIVE_SCRIPTING + LuaState* m_state = nullptr; +#endif + +public: + virtual ~ScriptedObject() { scriptDispose(); } + ScriptAsset* scriptAsset() const; + void setArtboardInput(std::string name, Artboard* artboard); + void setBooleanInput(std::string name, bool value); + void setIntegerInput(std::string name, int value); + void setNumberInput(std::string name, float value); + void setStringInput(std::string name, std::string value); + void setViewModelInput(std::string name, ViewModelInstanceValue* value); + void trigger(std::string name); + bool scriptAdvance(float elapsedSeconds); + void scriptUpdate(); + void reinit(); + virtual void markNeedsUpdate(); + virtual DataContext* dataContext() { return nullptr; } +#ifdef WITH_RIVE_SCRIPTING + virtual bool scriptInit(LuaState* state); + LuaState* state() { return m_state; } +#endif + void scriptDispose(); + virtual bool addScriptedDirt(ComponentDirt value, bool recurse = false) = 0; + void setAsset(rcp asset) override; + static ScriptedObject* from(Core* object); + virtual ScriptProtocol scriptProtocol() = 0; + int self() { return m_self; } + virtual Component* component() = 0; +}; +} // namespace rive + +#endif \ No newline at end of file diff --git a/defold-rive/include/rive/scripted/scripted_path_effect.hpp b/defold-rive/include/rive/scripted/scripted_path_effect.hpp new file mode 100644 index 00000000..51c1986e --- /dev/null +++ b/defold-rive/include/rive/scripted/scripted_path_effect.hpp @@ -0,0 +1,66 @@ +#ifndef _RIVE_SCRIPTED_PATH_EFFECT_HPP_ +#define _RIVE_SCRIPTED_PATH_EFFECT_HPP_ +#include "rive/generated/scripted/scripted_path_effect_base.hpp" +#include "rive/scripted/scripted_object.hpp" +#include "rive/advancing_component.hpp" +#include "rive/shapes/paint/shape_paint.hpp" +#include "rive/shapes/paint/stroke_effect.hpp" +#include +namespace rive +{ + +class ScriptedEffectPath : public EffectPath +{ +public: + void invalidateEffect() override; + ShapePaintPath* path() override { return &m_path; } + +private: + ShapePaintPath m_path; +}; +class ScriptedPathEffect : public ScriptedPathEffectBase, + public ScriptedObject, + public AdvancingComponent, + public StrokeEffect +{ +public: +#ifdef WITH_RIVE_SCRIPTING + bool scriptInit(LuaState* state) override; +#endif + void addProperty(CustomProperty* prop) override; + StatusCode onAddedClean(CoreContext* context) override; + StatusCode onAddedDirty(CoreContext* context) override; + uint32_t assetId() override { return scriptAssetId(); } + bool advanceComponent(float elapsedSeconds, + AdvanceFlags flags = AdvanceFlags::Animate | + AdvanceFlags::NewFrame) override; + bool addScriptedDirt(ComponentDirt value, bool recurse = false) override; + void buildDependencies() override; + void update(ComponentDirt value) override; + DataContext* dataContext() override + { + if (artboard() != nullptr) + { + return artboard()->dataContext(); + } + return nullptr; + } + ScriptProtocol scriptProtocol() override + { + return ScriptProtocol::pathEffect; + } + void updateEffect(PathProvider* pathProvider, + const ShapePaintPath* source, + ShapePaintType shapePaintType) override; + StatusCode import(ImportStack& importStack) override; + Core* clone() const override; + void markNeedsUpdate() override; + Component* component() override { return this; } + EffectsContainer* parentPaint() override; + +protected: + virtual EffectPath* createEffectPath() override; +}; +} // namespace rive + +#endif \ No newline at end of file diff --git a/defold-rive/include/rive/shape_paint_type.hpp b/defold-rive/include/rive/shape_paint_type.hpp new file mode 100644 index 00000000..10e92c49 --- /dev/null +++ b/defold-rive/include/rive/shape_paint_type.hpp @@ -0,0 +1,11 @@ +#ifndef _RIVE_SHAPE_PAINT_TYPE_HPP_ +#define _RIVE_SHAPE_PAINT_TYPE_HPP_ +namespace rive +{ +enum class ShapePaintType : unsigned int +{ + stroke = 0, + fill = 1, +}; +} +#endif diff --git a/defold-rive/include/rive/shapes/clipping_shape.hpp b/defold-rive/include/rive/shapes/clipping_shape.hpp index a93a11e0..cab469d5 100644 --- a/defold-rive/include/rive/shapes/clipping_shape.hpp +++ b/defold-rive/include/rive/shapes/clipping_shape.hpp @@ -3,6 +3,7 @@ #include "rive/renderer.hpp" #include "rive/generated/shapes/clipping_shape_base.hpp" #include "rive/shapes/shape_paint_path.hpp" +#include "rive/drawable.hpp" #include namespace rive @@ -10,21 +11,124 @@ namespace rive class Shape; class Node; class RenderPath; +class ClippingShapeStart; +class ClippingShapeEnd; + +class ClippingShapeOperation +{ +public: + virtual ~ClippingShapeOperation() = default; + virtual void draw(Renderer* renderer, bool needsSaveOperation) = 0; + virtual int emptyClipCount() = 0; + void clippingShape(ClippingShape* shape) { m_clippingShape = shape; } + virtual bool isStart() { return false; } + virtual bool isVisible() { return true; } + +protected: + ClippingShape* m_clippingShape = nullptr; +}; + +class ClippingShapeStart : public ClippingShapeOperation +{ +public: + void draw(Renderer* renderer, bool needsSaveOperation) override; + int emptyClipCount() override; + bool isStart() override { return true; } + bool isVisible() override; +}; + +class ClippingShapeEnd : public ClippingShapeOperation +{ + void draw(Renderer* renderer, bool needsSaveOperation) override; + int emptyClipCount() override; +}; + +class ClippingShapeProxyDrawable : public Drawable +{ +public: + ClippingShapeProxyDrawable(ClippingShapeOperation* operation) : + m_clippingShapeOperation(operation) + {} + void draw(Renderer* renderer) override + { + m_clippingShapeOperation->draw(renderer, m_needsSaveOperation); + } + + int emptyClipCount() override + { + return m_clippingShapeOperation->emptyClipCount(); + } + + bool isHidden() const override { return false; } + + Drawable* hittableComponent() override { return nullptr; }; + + bool isTargetOpaque() override { return false; }; + + Core* hitTest(HitInfo*, const Mat2D&) override { return nullptr; } + + void operation(ClippingShapeOperation* value) + { + m_clippingShapeOperation = value; + } + + bool isProxy() override { return true; } + + bool isClipStart() override { return m_clippingShapeOperation->isStart(); } + bool isClipEnd() override { return !m_clippingShapeOperation->isStart(); } + bool willClip() override { return m_clippingShapeOperation->isVisible(); } + +private: + ClippingShapeOperation* m_clippingShapeOperation = nullptr; +}; + class ClippingShape : public ClippingShapeBase { private: std::vector m_Shapes; + std::vector m_proxyDrawables; + std::vector m_pooledProxyDrawables; Node* m_Source = nullptr; public: + ~ClippingShape(); Node* source() const { return m_Source; } const std::vector& shapes() const { return m_Shapes; } StatusCode onAddedClean(CoreContext* context) override; StatusCode onAddedDirty(CoreContext* context) override; void buildDependencies() override; void update(ComponentDirt value) override; + void isVisibleChanged() override; ShapePaintPath* path() { return m_clipPath; } + void resetDrawables() + { + m_pooledProxyDrawables.insert(m_pooledProxyDrawables.end(), + m_proxyDrawables.begin(), + m_proxyDrawables.end()); + m_proxyDrawables.clear(); + } + + ClippingShapeProxyDrawable* createProxyDrawable( + ClippingShapeOperation* operation) + { + ClippingShapeProxyDrawable* drawable; + if (m_pooledProxyDrawables.size() > 0) + { + drawable = m_pooledProxyDrawables.back(); + drawable->operation(operation); + drawable->needsSaveOperation(true); + m_pooledProxyDrawables.pop_back(); + } + else + { + drawable = new ClippingShapeProxyDrawable(operation); + } + m_proxyDrawables.push_back(drawable); + return drawable; + } + ClippingShapeStart clipStart; + ClippingShapeEnd clipEnd; private: ShapePaintPath m_path; diff --git a/defold-rive/include/rive/shapes/image.hpp b/defold-rive/include/rive/shapes/image.hpp index 637d8380..77d35c6b 100644 --- a/defold-rive/include/rive/shapes/image.hpp +++ b/defold-rive/include/rive/shapes/image.hpp @@ -26,6 +26,7 @@ class Image : public ImageBase, public FileAssetReferencer void setMesh(MeshDrawable* mesh); ImageAsset* imageAsset() const; void draw(Renderer* renderer) override; + bool willDraw() override; Core* hitTest(HitInfo*, const Mat2D&) override; StatusCode import(ImportStack& importStack) override; void setAsset(rcp) override; diff --git a/defold-rive/include/rive/shapes/paint/dash.hpp b/defold-rive/include/rive/shapes/paint/dash.hpp index 444c7536..b3ba9378 100644 --- a/defold-rive/include/rive/shapes/paint/dash.hpp +++ b/defold-rive/include/rive/shapes/paint/dash.hpp @@ -10,7 +10,7 @@ class Dash : public DashBase Dash(); Dash(float value, bool percentage); - float normalizedLength(float length) const; + float normalizedLength(float length, bool wraps) const; StatusCode onAddedClean(CoreContext* context) override; diff --git a/defold-rive/include/rive/shapes/paint/dash_path.hpp b/defold-rive/include/rive/shapes/paint/dash_path.hpp index e8e52907..f507be09 100644 --- a/defold-rive/include/rive/shapes/paint/dash_path.hpp +++ b/defold-rive/include/rive/shapes/paint/dash_path.hpp @@ -2,37 +2,49 @@ #define _RIVE_DASH_PATH_HPP_ #include "rive/generated/shapes/paint/dash_path_base.hpp" +#include "rive/shapes/paint/shape_paint.hpp" #include "rive/shapes/paint/stroke_effect.hpp" #include "rive/shapes/paint/stroke_effect.hpp" #include "rive/shapes/shape_paint_path.hpp" #include "rive/renderer.hpp" #include "rive/math/raw_path.hpp" -#include "rive/math/contour_measure.hpp" +#include "rive/math/path_measure.hpp" #include namespace rive { class Dash; + +class DashEffectPath : public EffectPath +{ +public: + void invalidateEffect() override; + PathMeasure& pathMeasure() { return m_pathMeasure; } + void createPathMeasure(const RawPath*); + ShapePaintPath* path() override { return &m_path; } + +private: + ShapePaintPath m_path; + PathMeasure m_pathMeasure; +}; class PathDasher { friend class Dash; protected: - void invalidateSourcePath(); virtual void invalidateDash(); - ShapePaintPath* dash(const RawPath* source, + ShapePaintPath* dash(ShapePaintPath* destination, + const RawPath* source, + PathMeasure* pathMeasure, Dash* offset, Span dashes); - ShapePaintPath* applyDash(const RawPath* source, + ShapePaintPath* applyDash(ShapePaintPath* destination, + const RawPath* source, + PathMeasure* pathMeasure, Dash* offset, Span dashes); -protected: - ShapePaintPath m_path; - std::vector> m_contours; - public: - float pathLength() const; virtual ~PathDasher() {} }; @@ -40,12 +52,14 @@ class DashPath : public DashPathBase, public PathDasher, public StrokeEffect { public: StatusCode onAddedClean(CoreContext* context) override; - void invalidateEffect() override; void offsetChanged() override; void offsetIsPercentageChanged() override; - void updateEffect(const ShapePaintPath* source) override; - ShapePaintPath* effectPath() override; + void updateEffect(PathProvider* pathProvider, + const ShapePaintPath* source, + ShapePaintType shapePaintType) override; void invalidateDash() override; + EffectsContainer* parentPaint() override; + virtual EffectPath* createEffectPath() override; private: std::vector m_dashes; diff --git a/defold-rive/include/rive/shapes/paint/effects_container.hpp b/defold-rive/include/rive/shapes/paint/effects_container.hpp new file mode 100644 index 00000000..07c29cb9 --- /dev/null +++ b/defold-rive/include/rive/shapes/paint/effects_container.hpp @@ -0,0 +1,37 @@ +#ifndef _RIVE_EFFECTS_CONTAINER_HPP_ +#define _RIVE_EFFECTS_CONTAINER_HPP_ +#include "rive/refcnt.hpp" +#include "rive/shapes/path_flags.hpp" +#include "rive/shapes/shape_paint_path.hpp" +#include "rive/math/mat2d.hpp" +#include + +namespace rive +{ +class StrokeEffect; +class PathProvider; + +class EffectsContainer +{ + +public: + static EffectsContainer* from(Component* component); + virtual void addStrokeEffect(StrokeEffect* effect); + virtual void invalidateEffects(StrokeEffect* invalidatingEffect); + virtual void invalidateEffects(); + ShapePaintPath* lastEffectPath(PathProvider*); +#ifdef TESTING + StrokeEffect* effect() + { + return m_effects.size() > 0 ? m_effects.back() : nullptr; + } +#endif + +protected: + std::vector* effects() { return &m_effects; } + +private: + std::vector m_effects; +}; +} // namespace rive +#endif diff --git a/defold-rive/include/rive/shapes/paint/fill.hpp b/defold-rive/include/rive/shapes/paint/fill.hpp index 37f9fe9e..64bea784 100644 --- a/defold-rive/include/rive/shapes/paint/fill.hpp +++ b/defold-rive/include/rive/shapes/paint/fill.hpp @@ -11,6 +11,8 @@ class Fill : public FillBase PathFlags pathFlags() const override; void applyTo(RenderPaint* renderPaint, float opacityModifier) override; ShapePaintPath* pickPath(ShapePaintContainer* shape) const override; + ShapePaintType paintType() override { return ShapePaintType::fill; } + void buildDependencies() override; }; } // namespace rive diff --git a/defold-rive/include/rive/shapes/paint/group_effect.hpp b/defold-rive/include/rive/shapes/paint/group_effect.hpp new file mode 100644 index 00000000..6a732c56 --- /dev/null +++ b/defold-rive/include/rive/shapes/paint/group_effect.hpp @@ -0,0 +1,33 @@ +#ifndef _RIVE_GROUP_EFFECT_HPP_ +#define _RIVE_GROUP_EFFECT_HPP_ +#include "rive/generated/shapes/paint/group_effect_base.hpp" +#include "rive/shapes/paint/effects_container.hpp" +#include "rive/shapes/paint/stroke_effect.hpp" +#include +namespace rive +{ +class TargetEffect; +class StrokeEffect; +class GroupEffect : public GroupEffectBase, + public EffectsContainer, + public StrokeEffect +{ +public: + void addTargetEffect(TargetEffect* effect); + void invalidateEffects(StrokeEffect* effect) override; + void invalidateEffects() override; + void updateEffect(PathProvider* pathProvider, + const ShapePaintPath* source, + ShapePaintType shapePaintType) override; + EffectsContainer* parentPaint() override; + void addPathProvider(PathProvider* component) override; + void addStrokeEffect(StrokeEffect* effect) override; + void invalidateEffect(PathProvider* effect) override; + void buildDependencies() override; + +private: + std::vector m_targetEffects; +}; +} // namespace rive + +#endif \ No newline at end of file diff --git a/defold-rive/include/rive/shapes/paint/image_sampler.hpp b/defold-rive/include/rive/shapes/paint/image_sampler.hpp index 8fe04c77..e929a420 100644 --- a/defold-rive/include/rive/shapes/paint/image_sampler.hpp +++ b/defold-rive/include/rive/shapes/paint/image_sampler.hpp @@ -7,11 +7,10 @@ namespace rive { enum class ImageFilter : uint8_t { - // High fidelity linear filter in all 3 directions: x, y, and between mip - // levels - trilinear = 0, + // High fidelity linear filter in all 2 directions: x, y + bilinear = 0, // Sample with low fidelity, good for things like pixel art. - nearest = 1 + nearest = 1, }; constexpr size_t NUM_IMAGE_FILTERS = 2; @@ -27,7 +26,7 @@ enum class ImageWrap : uint8_t mirror = 2, }; -constexpr size_t NUM_IMAGE_WRAP = 4; +constexpr size_t NUM_IMAGE_WRAP = 3; struct ImageSampler { @@ -38,7 +37,7 @@ struct ImageSampler ImageWrap wrapX = ImageWrap::clamp; ImageWrap wrapY = ImageWrap::clamp; // How to sample the texture, this will be for both MIN and MAG filtering. - ImageFilter filter = ImageFilter::trilinear; + ImageFilter filter = ImageFilter::bilinear; bool operator==(const ImageSampler other) const { @@ -54,14 +53,15 @@ struct ImageSampler // The maximum number of possible combinations of sampler options. Used for // array length in implementations. static constexpr size_t MAX_SAMPLER_PERMUTATIONS = - NUM_IMAGE_FILTERS * NUM_IMAGE_FILTERS * NUM_IMAGE_WRAP; + NUM_IMAGE_FILTERS * NUM_IMAGE_WRAP * NUM_IMAGE_WRAP; // Convert struct to a key that can be used to index an array to get a // unique sampler that represents these options. const uint8_t asKey() const { - return static_cast(wrapX) + (static_cast(wrapY) * 3) + - (static_cast(filter) * 9); + return static_cast(wrapX) + + (static_cast(wrapY) * NUM_IMAGE_WRAP) + + (static_cast(filter) * NUM_IMAGE_WRAP * NUM_IMAGE_WRAP); } static ImageSampler SamplerFromKey(uint8_t key) @@ -79,17 +79,18 @@ struct ImageSampler static ImageWrap GetWrapXOptionFromKey(uint8_t key) { - return static_cast(key % 3); + return static_cast(key % NUM_IMAGE_WRAP); } static ImageWrap GetWrapYOptionFromKey(uint8_t key) { - return static_cast((key % 9) / 3); + return static_cast((key / NUM_IMAGE_WRAP) % NUM_IMAGE_WRAP); } static ImageFilter GetFilterOptionFromKey(uint8_t key) { - return static_cast((key - (key % 9)) % 2); + return static_cast(key / + (NUM_IMAGE_WRAP * NUM_IMAGE_WRAP)); } }; } // namespace rive diff --git a/defold-rive/include/rive/shapes/paint/shape_paint.hpp b/defold-rive/include/rive/shapes/paint/shape_paint.hpp index cb98ed15..37ce44c4 100644 --- a/defold-rive/include/rive/shapes/paint/shape_paint.hpp +++ b/defold-rive/include/rive/shapes/paint/shape_paint.hpp @@ -1,11 +1,13 @@ #ifndef _RIVE_SHAPE_PAINT_HPP_ #define _RIVE_SHAPE_PAINT_HPP_ #include "rive/generated/shapes/paint/shape_paint_base.hpp" +#include "rive/shapes/paint/effects_container.hpp" #include "rive/renderer.hpp" #include "rive/shapes/paint/blend_mode.hpp" #include "rive/shapes/paint/shape_paint_mutator.hpp" #include "rive/shapes/path_flags.hpp" #include "rive/shapes/shape_paint_path.hpp" +#include "rive/shapes/paint/stroke_effect.hpp" #include "rive/math/raw_path.hpp" namespace rive @@ -14,20 +16,28 @@ class RenderPaint; class ShapePaintMutator; class Feather; class ShapePaintContainer; -class ShapePaint : public ShapePaintBase +class ShapePaint : public ShapePaintBase, + public EffectsContainer, + public PathProvider { protected: rcp m_RenderPaint; ShapePaintMutator* m_PaintMutator = nullptr; + virtual ShapePaintType paintType() = 0; public: StatusCode onAddedClean(CoreContext* context) override; + void invalidateEffects(StrokeEffect* effect) override; + void invalidateEffects() override; + virtual void invalidateRendering(); float renderOpacity() const { return m_PaintMutator->renderOpacity(); } void renderOpacity(float value) { m_PaintMutator->renderOpacity(value); } void blendMode(BlendMode value); + void addStrokeEffect(StrokeEffect* effect) override; + /// Creates a RenderPaint object for the provided ShapePaintMutator*. /// This should be called only once as the ShapePaint manages the /// lifecycle of the RenderPaint. @@ -43,7 +53,8 @@ class ShapePaint : public ShapePaintBase ShapePaintPath* shapePaintPath, const Mat2D& transform, bool usePathFillRule = false, - RenderPaint* overridePaint = nullptr); + RenderPaint* overridePaint = nullptr, + bool needsSaveOperation = true); RenderPaint* renderPaint() { return m_RenderPaint.get(); } @@ -70,6 +81,7 @@ class ShapePaint : public ShapePaintBase Feather* feather() const; virtual ShapePaintPath* pickPath(ShapePaintContainer* shape) const = 0; + void update(ComponentDirt value) override; private: Feather* m_feather = nullptr; diff --git a/defold-rive/include/rive/shapes/paint/stroke.hpp b/defold-rive/include/rive/shapes/paint/stroke.hpp index b6778588..e3c5c379 100644 --- a/defold-rive/include/rive/shapes/paint/stroke.hpp +++ b/defold-rive/include/rive/shapes/paint/stroke.hpp @@ -8,34 +8,21 @@ class StrokeEffect; class Stroke : public StrokeBase { private: - StrokeEffect* m_Effect = nullptr; - public: RenderPaint* initRenderPaint(ShapePaintMutator* mutator) override; PathFlags pathFlags() const override; - void addStrokeEffect(StrokeEffect* effect); - bool hasStrokeEffect() { return m_Effect != nullptr; } - void invalidateEffects(); bool isVisible() const override; - void invalidateRendering(); void applyTo(RenderPaint* renderPaint, float opacityModifier) override; ShapePaintPath* pickPath(ShapePaintContainer* shape) const override; - void draw(Renderer* renderer, - ShapePaintPath* shapePaintPath, - const Mat2D& transform, - bool usePathFillRule, - RenderPaint* overridePaint) override; void buildDependencies() override; - void update(ComponentDirt value) override; -#ifdef TESTING - StrokeEffect* effect() { return m_Effect; } -#endif + void invalidateRendering() override; protected: void thicknessChanged() override; void capChanged() override; void joinChanged() override; + ShapePaintType paintType() override { return ShapePaintType::stroke; } }; } // namespace rive diff --git a/defold-rive/include/rive/shapes/paint/stroke_effect.hpp b/defold-rive/include/rive/shapes/paint/stroke_effect.hpp index e73ba9ea..544cc761 100644 --- a/defold-rive/include/rive/shapes/paint/stroke_effect.hpp +++ b/defold-rive/include/rive/shapes/paint/stroke_effect.hpp @@ -2,21 +2,58 @@ #define _RIVE_STROKE_EFFECT_HPP_ #include "rive/rive_types.hpp" +#include "rive/shape_paint_type.hpp" +#include namespace rive { class Factory; class RenderPath; class RawPath; +class ShapePaint; class ShapePaintPath; +class EffectsContainer; + +// A EffectPath is a reference that any StrokeEffect holds to identify each +// ShapePaint that is being affected by it. +class EffectPath +{ +public: + virtual ~EffectPath() = default; + virtual void invalidateEffect() {} + virtual ShapePaintPath* path() { return nullptr; } +}; + +// A PathProvider is any object that will be used to map a unique EffectPath. +// It allows to disambiguate path effect updates and invalidations without +// modifying any other instance that an effect is affecting. ShapePaints are +// PathProviders, but also TargetEffects. A TargetEffect needs to create a +// PathProvider proxy because the same ShapePaint can be targetting multiple +// times the same group effect and invalidating one doesn't need to invalidate +// the other one. +class PathProvider +{}; class StrokeEffect { public: - virtual ~StrokeEffect() {} - virtual void updateEffect(const ShapePaintPath* source) = 0; - virtual ShapePaintPath* effectPath() = 0; - virtual void invalidateEffect() = 0; + virtual ~StrokeEffect(); + virtual void updateEffect(PathProvider* pathProvider, + const ShapePaintPath* source, + ShapePaintType shapePaintType) = 0; + virtual void invalidateEffect(PathProvider* pathProvider); + virtual EffectsContainer* parentPaint() = 0; + virtual void addPathProvider(PathProvider* component) + { + m_effectPaths[component] = createEffectPath(); + } + + virtual ShapePaintPath* effectPath(PathProvider* pathProvider); + virtual void invalidateEffectFromLocal(); + +protected: + virtual EffectPath* createEffectPath() { return new EffectPath(); } + std::unordered_map m_effectPaths; }; } // namespace rive #endif \ No newline at end of file diff --git a/defold-rive/include/rive/shapes/paint/target_effect.hpp b/defold-rive/include/rive/shapes/paint/target_effect.hpp new file mode 100644 index 00000000..b26a47da --- /dev/null +++ b/defold-rive/include/rive/shapes/paint/target_effect.hpp @@ -0,0 +1,38 @@ +#ifndef _RIVE_TARGET_EFFECT_HPP_ +#define _RIVE_TARGET_EFFECT_HPP_ +#include "rive/generated/shapes/paint/target_effect_base.hpp" +#include "rive/shapes/paint/stroke_effect.hpp" +#include +namespace rive +{ +class GroupEffect; +class TargetEffectPath : public EffectPath +{ +public: + PathProvider* pathProviderProxy() { return &m_pathProviderProxy; } + +private: + PathProvider m_pathProviderProxy; +}; +class TargetEffect : public TargetEffectBase, public StrokeEffect +{ +public: + StatusCode onAddedClean(CoreContext* context) override; + + void updateEffect(PathProvider* pathProvider, + const ShapePaintPath* source, + ShapePaintType shapePaintType) override; + ShapePaintPath* effectPath(PathProvider* pathProvider) override; + EffectsContainer* parentPaint() override; + void addPathProvider(PathProvider* component) override; + void invalidateEffect(PathProvider* component) override; + +protected: + virtual EffectPath* createEffectPath() override; + +private: + GroupEffect* m_groupEffect = nullptr; +}; +} // namespace rive + +#endif \ No newline at end of file diff --git a/defold-rive/include/rive/shapes/paint/trim_path.hpp b/defold-rive/include/rive/shapes/paint/trim_path.hpp index 2b026671..a23051a5 100644 --- a/defold-rive/include/rive/shapes/paint/trim_path.hpp +++ b/defold-rive/include/rive/shapes/paint/trim_path.hpp @@ -1,6 +1,7 @@ #ifndef _RIVE_TRIM_PATH_HPP_ #define _RIVE_TRIM_PATH_HPP_ #include "rive/generated/shapes/paint/trim_path_base.hpp" +#include "rive/shapes/paint/shape_paint.hpp" #include "rive/shapes/shape_paint_path.hpp" #include "rive/shapes/paint/stroke_effect.hpp" #include "rive/renderer.hpp" @@ -16,14 +17,27 @@ enum class TrimPathMode : uint8_t }; +class TrimEffectPath : public EffectPath +{ +public: + void invalidateEffect() override; + std::vector>& contours() { return m_contours; } + ShapePaintPath* path() override { return &m_path; } + +private: + ShapePaintPath m_path; + std::vector> m_contours; +}; + class TrimPath : public TrimPathBase, public StrokeEffect { public: StatusCode onAddedClean(CoreContext* context) override; - void invalidateEffect() override; - void updateEffect(const ShapePaintPath* source) override; - ShapePaintPath* effectPath() override; + void updateEffect(PathProvider* pathProvider, + const ShapePaintPath* source, + ShapePaintType shapePaintType) override; + EffectsContainer* parentPaint() override; void startChanged() override; void endChanged() override; @@ -34,13 +48,12 @@ class TrimPath : public TrimPathBase, public StrokeEffect StatusCode onAddedDirty(CoreContext* context) override; - const ShapePaintPath& path() const { return m_path; } - protected: - void invalidateTrim(); - void trimPath(const RawPath* source); - ShapePaintPath m_path; - std::vector> m_contours; + void trimPath(ShapePaintPath* destination, + std::vector>& contours, + const RawPath* source, + ShapePaintType shapePaintType); + virtual EffectPath* createEffectPath() override; }; } // namespace rive diff --git a/defold-rive/include/rive/shapes/shape.hpp b/defold-rive/include/rive/shapes/shape.hpp index 8129e696..751600d9 100644 --- a/defold-rive/include/rive/shapes/shape.hpp +++ b/defold-rive/include/rive/shapes/shape.hpp @@ -35,12 +35,14 @@ class Shape : public ShapeBase, public ShapePaintContainer bool canDeferPathUpdate(); void addPath(Path* path); void addToRenderPath(RenderPath* commandPath, const Mat2D& transform); + void addToRawPath(RawPath& rawPath, const Mat2D* transform); std::vector& paths() { return m_Paths; } bool wantDifferencePath() const { return m_WantDifferencePath; } void update(ComponentDirt value) override; void draw(Renderer* renderer) override; + bool willDraw() override; Core* hitTest(HitInfo*, const Mat2D&) override; const PathComposer* pathComposer() const { return &m_PathComposer; } diff --git a/defold-rive/include/rive/solo.hpp b/defold-rive/include/rive/solo.hpp index baf4b860..4e3cd8cf 100644 --- a/defold-rive/include/rive/solo.hpp +++ b/defold-rive/include/rive/solo.hpp @@ -10,7 +10,7 @@ class Solo : public SoloBase StatusCode onAddedClean(CoreContext* context) override; bool collapse(bool value) override; void updateByIndex(size_t index); - void updateByName(std::string& name); + void updateByName(const std::string& name); int getActiveChildIndex(); std::string getActiveChildName(); diff --git a/defold-rive/include/rive/text/text_input.hpp b/defold-rive/include/rive/text/text_input.hpp index e550c529..af79d703 100644 --- a/defold-rive/include/rive/text/text_input.hpp +++ b/defold-rive/include/rive/text/text_input.hpp @@ -4,11 +4,13 @@ #include "rive/generated/text/text_input_base.hpp" #include "rive/text/raw_text_input.hpp" #include "rive/text/text_interface.hpp" +#include "rive/input/focusable.hpp" namespace rive { class TextStyle; -class TextInput : public TextInputBase, public TextInterface +class ScrollConstraint; +class TextInput : public TextInputBase, public TextInterface, public Focusable { public: void draw(Renderer* renderer) override; @@ -34,6 +36,12 @@ class TextInput : public TextInputBase, public TextInterface LayoutScaleType heightScaleType, LayoutDirection direction) override; + bool keyInput(Key value, + KeyModifiers modifiers, + bool isPressed, + bool isRepeat) override; + bool textInput(const std::string& text) override; + protected: void textChanged() override; void selectionRadiusChanged() override; @@ -41,6 +49,8 @@ class TextInput : public TextInputBase, public TextInterface private: AABB m_worldBounds; TextStyle* m_textStyle = nullptr; + ScrollConstraint* m_scrollConstraint = nullptr; + #ifdef WITH_RIVE_TEXT RawTextInput m_rawTextInput; #endif diff --git a/defold-rive/include/rive/text/text_input_drawable.hpp b/defold-rive/include/rive/text/text_input_drawable.hpp index f0219fd8..790bb5b9 100644 --- a/defold-rive/include/rive/text/text_input_drawable.hpp +++ b/defold-rive/include/rive/text/text_input_drawable.hpp @@ -21,6 +21,7 @@ class TextInputDrawable : public TextInputDrawableBase, TextInput* textInput() const; Component* pathBuilder() override { return parent(); } void draw(Renderer* renderer) override; + bool willDraw() override; }; } // namespace rive diff --git a/defold-rive/include/rive/text/text_style.hpp b/defold-rive/include/rive/text/text_style.hpp index 23d3b119..68e6b467 100644 --- a/defold-rive/include/rive/text/text_style.hpp +++ b/defold-rive/include/rive/text/text_style.hpp @@ -34,7 +34,7 @@ class TextStyle : public TextStyleBase, public FileAssetReferencer Core* clone() const override; void addVariation(TextStyleAxis* axis); void addFeature(TextStyleFeature* feature); - void updateVariableFont(); + void updateVariableFont() const; StatusCode onAddedClean(CoreContext* context) override; void onDirty(ComponentDirt dirt) override; bool validate(CoreContext* context) override; @@ -47,12 +47,12 @@ class TextStyle : public TextStyleBase, public FileAssetReferencer private: std::unique_ptr m_variationHelper; - rcp m_variableFont; + mutable rcp m_variableFont; - std::vector m_coords; + mutable std::vector m_coords; std::vector m_variations; std::vector m_styleFeatures; - std::vector m_features; + mutable std::vector m_features; TextInterface* m_text = nullptr; }; } // namespace rive diff --git a/defold-rive/include/rive/text_engine.hpp b/defold-rive/include/rive/text_engine.hpp index e9d5e85e..02b0b2b7 100644 --- a/defold-rive/include/rive/text_engine.hpp +++ b/defold-rive/include/rive/text_engine.hpp @@ -331,6 +331,11 @@ struct GlyphRun // Bidi level (even is LTR, odd is RTL) uint8_t level; + // List of indices where words are joined by a word-joiner character. + // During text breaking, these joins should be honored and not split at + // those points + SimpleArray joiners; + TextDirection dir() const { return level & 1 ? TextDirection::rtl : TextDirection::ltr; diff --git a/defold-rive/include/rive/viewmodel/runtime/viewmodel_instance_artboard_runtime.hpp b/defold-rive/include/rive/viewmodel/runtime/viewmodel_instance_artboard_runtime.hpp index 4f337f7c..fb512fc7 100644 --- a/defold-rive/include/rive/viewmodel/runtime/viewmodel_instance_artboard_runtime.hpp +++ b/defold-rive/include/rive/viewmodel/runtime/viewmodel_instance_artboard_runtime.hpp @@ -5,6 +5,7 @@ #include #include "rive/viewmodel/runtime/viewmodel_instance_value_runtime.hpp" #include "rive/viewmodel/viewmodel_instance_artboard.hpp" +#include "rive/bindable_artboard.hpp" namespace rive { @@ -17,11 +18,11 @@ class ViewModelInstanceArtboardRuntime : public ViewModelInstanceValueRuntime ViewModelInstanceArtboard* viewModelInstance) : ViewModelInstanceValueRuntime(viewModelInstance) {} - void value(Artboard* artboard); + void value(rcp bindableArtboard); const DataType dataType() override { return DataType::artboard; } #ifdef TESTING - Artboard* testing_value(); + rcp testing_value(); #endif }; } // namespace rive diff --git a/defold-rive/include/rive/viewmodel/runtime/viewmodel_instance_list_runtime.hpp b/defold-rive/include/rive/viewmodel/runtime/viewmodel_instance_list_runtime.hpp index 96a5f3be..7fb82ea0 100644 --- a/defold-rive/include/rive/viewmodel/runtime/viewmodel_instance_list_runtime.hpp +++ b/defold-rive/include/rive/viewmodel/runtime/viewmodel_instance_list_runtime.hpp @@ -19,7 +19,7 @@ class ViewModelInstanceListRuntime : public ViewModelInstanceValueRuntime ViewModelInstanceListRuntime(ViewModelInstanceList* viewModelInstance) : ViewModelInstanceValueRuntime(viewModelInstance) {} - ViewModelInstanceRuntime* instanceAt(int index); + rcp instanceAt(int index); void addInstance(ViewModelInstanceRuntime*); bool addInstanceAt(ViewModelInstanceRuntime*, int); void removeInstance(ViewModelInstanceRuntime*); diff --git a/defold-rive/include/rive/viewmodel/runtime/viewmodel_instance_runtime.hpp b/defold-rive/include/rive/viewmodel/runtime/viewmodel_instance_runtime.hpp index b8f8752a..6da29210 100644 --- a/defold-rive/include/rive/viewmodel/runtime/viewmodel_instance_runtime.hpp +++ b/defold-rive/include/rive/viewmodel/runtime/viewmodel_instance_runtime.hpp @@ -43,7 +43,8 @@ class ViewModelInstanceRuntime : public RefCnt ViewModelInstanceTriggerRuntime* propertyTrigger( const std::string& path) const; ViewModelInstanceListRuntime* propertyList(const std::string& path) const; - ViewModelInstanceRuntime* propertyViewModel(const std::string& path) const; + rcp propertyViewModel( + const std::string& path) const; ViewModelInstanceAssetImageRuntime* propertyImage( const std::string& path) const; ViewModelInstanceArtboardRuntime* propertyArtboard( diff --git a/defold-rive/include/rive/viewmodel/runtime/viewmodel_runtime.hpp b/defold-rive/include/rive/viewmodel/runtime/viewmodel_runtime.hpp index 3546c127..77f6f0e2 100644 --- a/defold-rive/include/rive/viewmodel/runtime/viewmodel_runtime.hpp +++ b/defold-rive/include/rive/viewmodel/runtime/viewmodel_runtime.hpp @@ -27,11 +27,11 @@ class ViewModelRuntime : public RefCnt const std::string& name() const; size_t instanceCount() const; size_t propertyCount() const; - ViewModelInstanceRuntime* createInstanceFromIndex(size_t index) const; - ViewModelInstanceRuntime* createInstanceFromName( + rcp createInstanceFromIndex(size_t index) const; + rcp createInstanceFromName( const std::string& name) const; - ViewModelInstanceRuntime* createDefaultInstance() const; - ViewModelInstanceRuntime* createInstance() const; + rcp createDefaultInstance() const; + rcp createInstance() const; std::vector properties(); static std::vector buildPropertiesData( std::vector& properties); @@ -40,9 +40,7 @@ class ViewModelRuntime : public RefCnt private: ViewModel* m_viewModel; const File* m_file; - mutable std::vector> - m_viewModelInstanceRuntimes; - ViewModelInstanceRuntime* createRuntimeInstance( + rcp createRuntimeInstance( rcp instance) const; }; } // namespace rive diff --git a/defold-rive/include/rive/viewmodel/viewmodel.hpp b/defold-rive/include/rive/viewmodel/viewmodel.hpp index aebcddbf..2bef90c6 100644 --- a/defold-rive/include/rive/viewmodel/viewmodel.hpp +++ b/defold-rive/include/rive/viewmodel/viewmodel.hpp @@ -8,11 +8,13 @@ #include namespace rive { +class File; class ViewModel : public ViewModelBase, public RefCnt { private: std::vector m_Properties; std::vector m_Instances; + File* m_file = nullptr; public: ~ViewModel(); @@ -23,6 +25,11 @@ class ViewModel : public ViewModelBase, public RefCnt void addInstance(ViewModelInstance* value); ViewModelInstance* instance(size_t index); ViewModelInstance* instance(const std::string& name); + rcp createInstance(); + void file(File* value) { m_file = value; }; +#ifdef WITH_RIVE_TOOLS + File* file() { return m_file; }; +#endif ViewModelInstance* defaultInstance(); size_t instanceCount() const; std::vector properties() { return m_Properties; } diff --git a/defold-rive/include/rive/viewmodel/viewmodel_instance.hpp b/defold-rive/include/rive/viewmodel/viewmodel_instance.hpp index 3aac3a03..f3c5ec0c 100644 --- a/defold-rive/include/rive/viewmodel/viewmodel_instance.hpp +++ b/defold-rive/include/rive/viewmodel/viewmodel_instance.hpp @@ -3,6 +3,7 @@ #include "rive/generated/viewmodel/viewmodel_instance_base.hpp" #include "rive/viewmodel/viewmodel_instance_value.hpp" #include "rive/viewmodel/symbol_type.hpp" +#include "rive/data_bind/data_bind_container.hpp" #include "rive/component.hpp" #include "rive/refcnt.hpp" #include @@ -14,7 +15,10 @@ class ViewModelInstance : public ViewModelInstanceBase, { private: std::vector m_PropertyValues; + std::vector m_parents; + std::vector m_dependents; ViewModel* m_ViewModel; + void rebindDependents(); public: ~ViewModelInstance(); @@ -36,6 +40,14 @@ class ViewModelInstance : public ViewModelInstanceBase, Core* clone() const override; StatusCode import(ImportStack& importStack) override; void advanced(); + void addParent(ViewModelInstance*); + void removeParent(ViewModelInstance*); + void addDependent(DataBindContainer*); + void removeDependent(DataBindContainer*); +#ifdef TESTING + std::vector dependents() { return m_dependents; } + std::vector parents() { return m_parents; } +#endif }; } // namespace rive diff --git a/defold-rive/include/rive/viewmodel/viewmodel_instance_artboard.hpp b/defold-rive/include/rive/viewmodel/viewmodel_instance_artboard.hpp index ca0176c4..ac225037 100644 --- a/defold-rive/include/rive/viewmodel/viewmodel_instance_artboard.hpp +++ b/defold-rive/include/rive/viewmodel/viewmodel_instance_artboard.hpp @@ -1,6 +1,8 @@ #ifndef _RIVE_VIEW_MODEL_INSTANCE_ARTBOARD_HPP_ #define _RIVE_VIEW_MODEL_INSTANCE_ARTBOARD_HPP_ #include "rive/generated/viewmodel/viewmodel_instance_artboard_base.hpp" +#include "rive/data_bind/data_values/data_value_integer.hpp" +#include "rive/bindable_artboard.hpp" #include namespace rive { @@ -15,11 +17,12 @@ class ViewModelInstanceArtboard : public ViewModelInstanceArtboardBase void propertyValueChanged() override; public: - void asset(Artboard* value); - Artboard* asset() { return m_artboard; } + void asset(rcp value); + rcp asset() { return m_bindableArtboard; } + void applyValue(DataValueInteger*); private: - Artboard* m_artboard = nullptr; + rcp m_bindableArtboard = nullptr; #ifdef WITH_RIVE_TOOLS public: void onChanged(ViewModelArtboardChanged callback) diff --git a/defold-rive/include/rive/viewmodel/viewmodel_instance_asset_image.hpp b/defold-rive/include/rive/viewmodel/viewmodel_instance_asset_image.hpp index 86ae9465..6c98f3a9 100644 --- a/defold-rive/include/rive/viewmodel/viewmodel_instance_asset_image.hpp +++ b/defold-rive/include/rive/viewmodel/viewmodel_instance_asset_image.hpp @@ -3,6 +3,7 @@ #include "rive/generated/viewmodel/viewmodel_instance_asset_image_base.hpp" #include "rive/renderer.hpp" #include "rive/refcnt.hpp" +#include "rive/data_bind/data_values/data_value_integer.hpp" #include "rive/assets/image_asset.hpp" #include namespace rive @@ -17,9 +18,10 @@ class ViewModelInstanceAssetImage : public ViewModelInstanceAssetImageBase void value(RenderImage* image); rcp asset() { return m_imageAsset; } Core* clone() const override; + void applyValue(DataValueInteger*); private: - rcp m_imageAsset; + rcp m_imageAsset = nullptr; }; } // namespace rive diff --git a/defold-rive/include/rive/viewmodel/viewmodel_instance_boolean.hpp b/defold-rive/include/rive/viewmodel/viewmodel_instance_boolean.hpp index 26ec4eeb..a8b2d0fd 100644 --- a/defold-rive/include/rive/viewmodel/viewmodel_instance_boolean.hpp +++ b/defold-rive/include/rive/viewmodel/viewmodel_instance_boolean.hpp @@ -1,6 +1,7 @@ #ifndef _RIVE_VIEW_MODEL_INSTANCE_BOOLEAN_HPP_ #define _RIVE_VIEW_MODEL_INSTANCE_BOOLEAN_HPP_ #include "rive/generated/viewmodel/viewmodel_instance_boolean_base.hpp" +#include "rive/data_bind/data_values/data_value_boolean.hpp" #include namespace rive { @@ -13,14 +14,16 @@ class ViewModelInstanceBoolean : public ViewModelInstanceBooleanBase { protected: void propertyValueChanged() override; -#ifdef WITH_RIVE_TOOLS + public: +#ifdef WITH_RIVE_TOOLS void onChanged(ViewModelBooleanChanged callback) { m_changedCallback = callback; } ViewModelBooleanChanged m_changedCallback = nullptr; #endif + void applyValue(DataValueBoolean*); }; } // namespace rive diff --git a/defold-rive/include/rive/viewmodel/viewmodel_instance_color.hpp b/defold-rive/include/rive/viewmodel/viewmodel_instance_color.hpp index 045dd611..00b2eb71 100644 --- a/defold-rive/include/rive/viewmodel/viewmodel_instance_color.hpp +++ b/defold-rive/include/rive/viewmodel/viewmodel_instance_color.hpp @@ -1,6 +1,7 @@ #ifndef _RIVE_VIEW_MODEL_INSTANCE_COLOR_HPP_ #define _RIVE_VIEW_MODEL_INSTANCE_COLOR_HPP_ #include "rive/generated/viewmodel/viewmodel_instance_color_base.hpp" +#include "rive/data_bind/data_values/data_value_color.hpp" #include namespace rive { @@ -13,13 +14,13 @@ class ViewModelInstanceColor : public ViewModelInstanceColorBase public: void propertyValueChanged() override; #ifdef WITH_RIVE_TOOLS -public: void onChanged(ViewModelColorChanged callback) { m_changedCallback = callback; } ViewModelColorChanged m_changedCallback = nullptr; #endif + void applyValue(DataValueColor*); }; } // namespace rive diff --git a/defold-rive/include/rive/viewmodel/viewmodel_instance_enum.hpp b/defold-rive/include/rive/viewmodel/viewmodel_instance_enum.hpp index 65db7278..f538297a 100644 --- a/defold-rive/include/rive/viewmodel/viewmodel_instance_enum.hpp +++ b/defold-rive/include/rive/viewmodel/viewmodel_instance_enum.hpp @@ -1,6 +1,7 @@ #ifndef _RIVE_VIEW_MODEL_INSTANCE_ENUM_HPP_ #define _RIVE_VIEW_MODEL_INSTANCE_ENUM_HPP_ #include "rive/generated/viewmodel/viewmodel_instance_enum_base.hpp" +#include "rive/data_bind/data_values/data_value_integer.hpp" #include namespace rive { @@ -14,6 +15,7 @@ class ViewModelInstanceEnum : public ViewModelInstanceEnumBase public: bool value(std::string name); bool value(uint32_t index); + void applyValue(DataValueInteger*); protected: void propertyValueChanged() override; diff --git a/defold-rive/include/rive/viewmodel/viewmodel_instance_list.hpp b/defold-rive/include/rive/viewmodel/viewmodel_instance_list.hpp index 453de1eb..23378661 100644 --- a/defold-rive/include/rive/viewmodel/viewmodel_instance_list.hpp +++ b/defold-rive/include/rive/viewmodel/viewmodel_instance_list.hpp @@ -5,6 +5,10 @@ #include namespace rive { +#ifdef WITH_RIVE_TOOLS +class ViewModelInstanceList; +typedef void (*ViewModelListChanged)(ViewModelInstanceList* vmi); +#endif class ViewModelInstanceList : public ViewModelInstanceListBase { public: @@ -17,12 +21,32 @@ class ViewModelInstanceList : public ViewModelInstanceListBase Span> listItems() { return m_ListItems; } rcp item(uint32_t index); void swap(uint32_t index1, uint32_t index2); + rcp pop(); + rcp shift(); Core* clone() const override; void advanced() override; + void parentViewModelInstance(ViewModelInstance* parent) + { + m_parentViewModelInstance = parent; + } + ViewModelInstance* parentViewModelInstance() + { + return m_parentViewModelInstance; + } +#ifdef WITH_RIVE_TOOLS + void onChanged(ViewModelListChanged callback) + { + m_changedCallback = callback; + } + ViewModelListChanged m_changedCallback = nullptr; +#endif protected: std::vector> m_ListItems; void propertyValueChanged(); + +private: + ViewModelInstance* m_parentViewModelInstance = nullptr; }; } // namespace rive diff --git a/defold-rive/include/rive/viewmodel/viewmodel_instance_number.hpp b/defold-rive/include/rive/viewmodel/viewmodel_instance_number.hpp index 7e85b526..73f42a6c 100644 --- a/defold-rive/include/rive/viewmodel/viewmodel_instance_number.hpp +++ b/defold-rive/include/rive/viewmodel/viewmodel_instance_number.hpp @@ -1,6 +1,7 @@ #ifndef _RIVE_VIEW_MODEL_INSTANCE_NUMBER_HPP_ #define _RIVE_VIEW_MODEL_INSTANCE_NUMBER_HPP_ #include "rive/generated/viewmodel/viewmodel_instance_number_base.hpp" +#include "rive/data_bind/data_values/data_value_number.hpp" #include namespace rive { @@ -13,14 +14,16 @@ class ViewModelInstanceNumber : public ViewModelInstanceNumberBase { protected: void propertyValueChanged() override; -#ifdef WITH_RIVE_TOOLS + public: +#ifdef WITH_RIVE_TOOLS void onChanged(ViewModelNumberChanged callback) { m_changedCallback = callback; } ViewModelNumberChanged m_changedCallback = nullptr; #endif + void applyValue(DataValueNumber*); }; } // namespace rive diff --git a/defold-rive/include/rive/viewmodel/viewmodel_instance_string.hpp b/defold-rive/include/rive/viewmodel/viewmodel_instance_string.hpp index a579298a..706588d9 100644 --- a/defold-rive/include/rive/viewmodel/viewmodel_instance_string.hpp +++ b/defold-rive/include/rive/viewmodel/viewmodel_instance_string.hpp @@ -1,6 +1,7 @@ #ifndef _RIVE_VIEW_MODEL_INSTANCE_STRING_HPP_ #define _RIVE_VIEW_MODEL_INSTANCE_STRING_HPP_ #include "rive/generated/viewmodel/viewmodel_instance_string_base.hpp" +#include "rive/data_bind/data_values/data_value_string.hpp" #include namespace rive { @@ -14,13 +15,13 @@ class ViewModelInstanceString : public ViewModelInstanceStringBase public: void propertyValueChanged() override; #ifdef WITH_RIVE_TOOLS -public: void onChanged(ViewModelStringChanged callback) { m_changedCallback = callback; } ViewModelStringChanged m_changedCallback = nullptr; #endif + void applyValue(DataValueString*); }; } // namespace rive diff --git a/defold-rive/include/rive/viewmodel/viewmodel_instance_symbol_list_index.hpp b/defold-rive/include/rive/viewmodel/viewmodel_instance_symbol_list_index.hpp index 23d71519..7175a637 100644 --- a/defold-rive/include/rive/viewmodel/viewmodel_instance_symbol_list_index.hpp +++ b/defold-rive/include/rive/viewmodel/viewmodel_instance_symbol_list_index.hpp @@ -1,6 +1,7 @@ #ifndef _RIVE_VIEW_MODEL_INSTANCE_SYMBOL_LIST_INDEX_HPP_ #define _RIVE_VIEW_MODEL_INSTANCE_SYMBOL_LIST_INDEX_HPP_ #include "rive/generated/viewmodel/viewmodel_instance_symbol_list_index_base.hpp" +#include "rive/data_bind/data_values/data_value_integer.hpp" #include namespace rive { @@ -15,14 +16,16 @@ class ViewModelInstanceSymbolListIndex { protected: void propertyValueChanged() override; -#ifdef WITH_RIVE_TOOLS + public: +#ifdef WITH_RIVE_TOOLS void onChanged(ViewModelSymbolListIndexChanged callback) { m_changedCallback = callback; } ViewModelSymbolListIndexChanged m_changedCallback = nullptr; #endif + void applyValue(DataValueInteger*); }; } // namespace rive diff --git a/defold-rive/include/rive/viewmodel/viewmodel_instance_trigger.hpp b/defold-rive/include/rive/viewmodel/viewmodel_instance_trigger.hpp index 4d5bb889..8016fc56 100644 --- a/defold-rive/include/rive/viewmodel/viewmodel_instance_trigger.hpp +++ b/defold-rive/include/rive/viewmodel/viewmodel_instance_trigger.hpp @@ -2,6 +2,7 @@ #define _RIVE_VIEW_MODEL_INSTANCE_TRIGGER_HPP_ #include "rive/generated/viewmodel/viewmodel_instance_trigger_base.hpp" #include "rive/animation/state_machine_input_instance.hpp" +#include "rive/data_bind/data_values/data_value_integer.hpp" #include namespace rive { @@ -26,6 +27,7 @@ class ViewModelInstanceTrigger : public ViewModelInstanceTriggerBase #endif void trigger() { propertyValue(propertyValue() + 1); } + void applyValue(DataValueInteger*); }; } // namespace rive diff --git a/defold-rive/include/rive/viewmodel/viewmodel_instance_viewmodel.hpp b/defold-rive/include/rive/viewmodel/viewmodel_instance_viewmodel.hpp index e1407ca1..2652343f 100644 --- a/defold-rive/include/rive/viewmodel/viewmodel_instance_viewmodel.hpp +++ b/defold-rive/include/rive/viewmodel/viewmodel_instance_viewmodel.hpp @@ -9,18 +9,36 @@ namespace rive class ViewModelInstanceViewModel : public ViewModelInstanceViewModelBase { private: - rcp m_referenceViewModelInstance; + rcp m_referenceViewModelInstance = nullptr; + ViewModelInstance* m_parentViewModelInstance = nullptr; public: ~ViewModelInstanceViewModel(); void referenceViewModelInstance(rcp value) { + if (m_referenceViewModelInstance && m_parentViewModelInstance) + { + m_referenceViewModelInstance->removeParent( + m_parentViewModelInstance); + } m_referenceViewModelInstance = value; + if (m_referenceViewModelInstance && m_parentViewModelInstance) + { + m_referenceViewModelInstance->addParent(m_parentViewModelInstance); + } }; rcp referenceViewModelInstance() { return m_referenceViewModelInstance; } + void parentViewModelInstance(ViewModelInstance* parent) + { + m_parentViewModelInstance = parent; + } + ViewModelInstance* parentViewModelInstance() + { + return m_parentViewModelInstance; + } void setRoot(rcp value) override; void advanced() override; }; diff --git a/defold-rive/include/utils/compile_time_string_hash.hpp b/defold-rive/include/utils/compile_time_string_hash.hpp index e0203a09..2b43076f 100644 --- a/defold-rive/include/utils/compile_time_string_hash.hpp +++ b/defold-rive/include/utils/compile_time_string_hash.hpp @@ -50,26 +50,26 @@ static constexpr unsigned int crc_table[256] = { 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d}; -template +template constexpr uint32_t combine_crc32(const char* str, uint32_t part) { return (part >> 8) ^ crc_table[(part ^ str[IDX]) & 0x000000FF]; } -template constexpr uint32_t crc32(const char* str) +template constexpr uint32_t crc32(const char* str) { return combine_crc32(str, crc32(str)); } // This is the stop-recursion function -template <> constexpr uint32_t crc32(const char* str) +template <> constexpr uint32_t crc32(const char* str) { return 0xFFFFFFFF; } } // namespace detail -template constexpr uint32_t ctcrc32(const char (&str)[LEN]) +template constexpr uint32_t ctcrc32(const char (&str)[LEN]) { // LEN-1 is to remove the null terminator at the end of the string const. return detail::crc32(str) ^ 0xFFFFFFFF; diff --git a/defold-rive/lib/arm64-android/liblibpng.a b/defold-rive/lib/arm64-android/liblibpng.a index 12cb7450..fe720b54 100644 Binary files a/defold-rive/lib/arm64-android/liblibpng.a and b/defold-rive/lib/arm64-android/liblibpng.a differ diff --git a/defold-rive/lib/arm64-android/librive.a b/defold-rive/lib/arm64-android/librive.a index 30736b02..eeb900cb 100644 Binary files a/defold-rive/lib/arm64-android/librive.a and b/defold-rive/lib/arm64-android/librive.a differ diff --git a/defold-rive/lib/arm64-android/librive_decoders.a b/defold-rive/lib/arm64-android/librive_decoders.a index e3432a8f..40557ef4 100644 Binary files a/defold-rive/lib/arm64-android/librive_decoders.a and b/defold-rive/lib/arm64-android/librive_decoders.a differ diff --git a/defold-rive/lib/arm64-android/librive_harfbuzz.a b/defold-rive/lib/arm64-android/librive_harfbuzz.a index f89b1535..973b094a 100644 Binary files a/defold-rive/lib/arm64-android/librive_harfbuzz.a and b/defold-rive/lib/arm64-android/librive_harfbuzz.a differ diff --git a/defold-rive/lib/arm64-android/librive_pls_renderer.a b/defold-rive/lib/arm64-android/librive_pls_renderer.a index 6b4d24a2..2280b078 100644 Binary files a/defold-rive/lib/arm64-android/librive_pls_renderer.a and b/defold-rive/lib/arm64-android/librive_pls_renderer.a differ diff --git a/defold-rive/lib/arm64-ios/liblibjpeg.a b/defold-rive/lib/arm64-ios/liblibjpeg.a index 8c26a72f..645859b7 100644 Binary files a/defold-rive/lib/arm64-ios/liblibjpeg.a and b/defold-rive/lib/arm64-ios/liblibjpeg.a differ diff --git a/defold-rive/lib/arm64-ios/liblibpng.a b/defold-rive/lib/arm64-ios/liblibpng.a index c6acad3e..583a5c48 100644 Binary files a/defold-rive/lib/arm64-ios/liblibpng.a and b/defold-rive/lib/arm64-ios/liblibpng.a differ diff --git a/defold-rive/lib/arm64-ios/liblibwebp.a b/defold-rive/lib/arm64-ios/liblibwebp.a index b8b4b76a..f4e42867 100644 Binary files a/defold-rive/lib/arm64-ios/liblibwebp.a and b/defold-rive/lib/arm64-ios/liblibwebp.a differ diff --git a/defold-rive/lib/arm64-ios/libminiaudio.a b/defold-rive/lib/arm64-ios/libminiaudio.a index dfb4ba43..ab10cc4b 100644 Binary files a/defold-rive/lib/arm64-ios/libminiaudio.a and b/defold-rive/lib/arm64-ios/libminiaudio.a differ diff --git a/defold-rive/lib/arm64-ios/librive.a b/defold-rive/lib/arm64-ios/librive.a index 29454867..6d06a620 100644 Binary files a/defold-rive/lib/arm64-ios/librive.a and b/defold-rive/lib/arm64-ios/librive.a differ diff --git a/defold-rive/lib/arm64-ios/librive_decoders.a b/defold-rive/lib/arm64-ios/librive_decoders.a index 77b24acf..f13d5d53 100644 Binary files a/defold-rive/lib/arm64-ios/librive_decoders.a and b/defold-rive/lib/arm64-ios/librive_decoders.a differ diff --git a/defold-rive/lib/arm64-ios/librive_harfbuzz.a b/defold-rive/lib/arm64-ios/librive_harfbuzz.a index 33b8834f..eab20059 100644 Binary files a/defold-rive/lib/arm64-ios/librive_harfbuzz.a and b/defold-rive/lib/arm64-ios/librive_harfbuzz.a differ diff --git a/defold-rive/lib/arm64-ios/librive_pls_renderer.a b/defold-rive/lib/arm64-ios/librive_pls_renderer.a index 03017da7..c6e98361 100644 Binary files a/defold-rive/lib/arm64-ios/librive_pls_renderer.a and b/defold-rive/lib/arm64-ios/librive_pls_renderer.a differ diff --git a/defold-rive/lib/arm64-ios/librive_sheenbidi.a b/defold-rive/lib/arm64-ios/librive_sheenbidi.a index 348d29c0..e5e21a2e 100644 Binary files a/defold-rive/lib/arm64-ios/librive_sheenbidi.a and b/defold-rive/lib/arm64-ios/librive_sheenbidi.a differ diff --git a/defold-rive/lib/arm64-ios/librive_yoga.a b/defold-rive/lib/arm64-ios/librive_yoga.a index 33550e8b..a4e4489a 100644 Binary files a/defold-rive/lib/arm64-ios/librive_yoga.a and b/defold-rive/lib/arm64-ios/librive_yoga.a differ diff --git a/defold-rive/lib/arm64-ios/libzlib.a b/defold-rive/lib/arm64-ios/libzlib.a index d1f79c1f..ac48ee5b 100644 Binary files a/defold-rive/lib/arm64-ios/libzlib.a and b/defold-rive/lib/arm64-ios/libzlib.a differ diff --git a/defold-rive/lib/arm64-osx/liblibjpeg.a b/defold-rive/lib/arm64-osx/liblibjpeg.a index 59b95863..a134c8cf 100644 Binary files a/defold-rive/lib/arm64-osx/liblibjpeg.a and b/defold-rive/lib/arm64-osx/liblibjpeg.a differ diff --git a/defold-rive/lib/arm64-osx/liblibpng.a b/defold-rive/lib/arm64-osx/liblibpng.a index 529311fa..1d3c1529 100644 Binary files a/defold-rive/lib/arm64-osx/liblibpng.a and b/defold-rive/lib/arm64-osx/liblibpng.a differ diff --git a/defold-rive/lib/arm64-osx/liblibwebp.a b/defold-rive/lib/arm64-osx/liblibwebp.a index 1fbb7657..31e99600 100644 Binary files a/defold-rive/lib/arm64-osx/liblibwebp.a and b/defold-rive/lib/arm64-osx/liblibwebp.a differ diff --git a/defold-rive/lib/arm64-osx/libminiaudio.a b/defold-rive/lib/arm64-osx/libminiaudio.a index 3069cf6e..a86f96d2 100644 Binary files a/defold-rive/lib/arm64-osx/libminiaudio.a and b/defold-rive/lib/arm64-osx/libminiaudio.a differ diff --git a/defold-rive/lib/arm64-osx/librive.a b/defold-rive/lib/arm64-osx/librive.a index 15bb929a..e340188c 100644 Binary files a/defold-rive/lib/arm64-osx/librive.a and b/defold-rive/lib/arm64-osx/librive.a differ diff --git a/defold-rive/lib/arm64-osx/librive_decoders.a b/defold-rive/lib/arm64-osx/librive_decoders.a index 9b206608..0b4c3d97 100644 Binary files a/defold-rive/lib/arm64-osx/librive_decoders.a and b/defold-rive/lib/arm64-osx/librive_decoders.a differ diff --git a/defold-rive/lib/arm64-osx/librive_harfbuzz.a b/defold-rive/lib/arm64-osx/librive_harfbuzz.a index f5b5ba65..ff0f866c 100644 Binary files a/defold-rive/lib/arm64-osx/librive_harfbuzz.a and b/defold-rive/lib/arm64-osx/librive_harfbuzz.a differ diff --git a/defold-rive/lib/arm64-osx/librive_pls_renderer.a b/defold-rive/lib/arm64-osx/librive_pls_renderer.a index 33c3004a..d28bda6e 100644 Binary files a/defold-rive/lib/arm64-osx/librive_pls_renderer.a and b/defold-rive/lib/arm64-osx/librive_pls_renderer.a differ diff --git a/defold-rive/lib/arm64-osx/librive_sheenbidi.a b/defold-rive/lib/arm64-osx/librive_sheenbidi.a index 71a34a61..553d1f85 100644 Binary files a/defold-rive/lib/arm64-osx/librive_sheenbidi.a and b/defold-rive/lib/arm64-osx/librive_sheenbidi.a differ diff --git a/defold-rive/lib/arm64-osx/librive_yoga.a b/defold-rive/lib/arm64-osx/librive_yoga.a index 05390f00..e9fac66e 100644 Binary files a/defold-rive/lib/arm64-osx/librive_yoga.a and b/defold-rive/lib/arm64-osx/librive_yoga.a differ diff --git a/defold-rive/lib/arm64-osx/libzlib.a b/defold-rive/lib/arm64-osx/libzlib.a index db1b86e7..dce73d85 100644 Binary files a/defold-rive/lib/arm64-osx/libzlib.a and b/defold-rive/lib/arm64-osx/libzlib.a differ diff --git a/defold-rive/lib/armv7-android/liblibpng.a b/defold-rive/lib/armv7-android/liblibpng.a index 145a52c4..4513593a 100644 Binary files a/defold-rive/lib/armv7-android/liblibpng.a and b/defold-rive/lib/armv7-android/liblibpng.a differ diff --git a/defold-rive/lib/armv7-android/librive.a b/defold-rive/lib/armv7-android/librive.a index f56a8fff..577cdbbb 100644 Binary files a/defold-rive/lib/armv7-android/librive.a and b/defold-rive/lib/armv7-android/librive.a differ diff --git a/defold-rive/lib/armv7-android/librive_decoders.a b/defold-rive/lib/armv7-android/librive_decoders.a index 1416fae5..3126d3a8 100644 Binary files a/defold-rive/lib/armv7-android/librive_decoders.a and b/defold-rive/lib/armv7-android/librive_decoders.a differ diff --git a/defold-rive/lib/armv7-android/librive_harfbuzz.a b/defold-rive/lib/armv7-android/librive_harfbuzz.a index c658117d..e2e1d0a7 100644 Binary files a/defold-rive/lib/armv7-android/librive_harfbuzz.a and b/defold-rive/lib/armv7-android/librive_harfbuzz.a differ diff --git a/defold-rive/lib/armv7-android/librive_pls_renderer.a b/defold-rive/lib/armv7-android/librive_pls_renderer.a index 278dc53e..1be73f2a 100644 Binary files a/defold-rive/lib/armv7-android/librive_pls_renderer.a and b/defold-rive/lib/armv7-android/librive_pls_renderer.a differ diff --git a/defold-rive/lib/js-web/liblibpng.a b/defold-rive/lib/js-web/liblibpng.a index 0ba60820..5b625dec 100644 Binary files a/defold-rive/lib/js-web/liblibpng.a and b/defold-rive/lib/js-web/liblibpng.a differ diff --git a/defold-rive/lib/js-web/librive.a b/defold-rive/lib/js-web/librive.a index 38f62c09..b99e228d 100644 Binary files a/defold-rive/lib/js-web/librive.a and b/defold-rive/lib/js-web/librive.a differ diff --git a/defold-rive/lib/js-web/librive_decoders.a b/defold-rive/lib/js-web/librive_decoders.a index 848584cc..888c28ee 100644 Binary files a/defold-rive/lib/js-web/librive_decoders.a and b/defold-rive/lib/js-web/librive_decoders.a differ diff --git a/defold-rive/lib/js-web/librive_harfbuzz.a b/defold-rive/lib/js-web/librive_harfbuzz.a index 167eadb1..fdfaf8ab 100644 Binary files a/defold-rive/lib/js-web/librive_harfbuzz.a and b/defold-rive/lib/js-web/librive_harfbuzz.a differ diff --git a/defold-rive/lib/js-web/librive_pls_renderer.a b/defold-rive/lib/js-web/librive_pls_renderer.a index a8054960..26cdc953 100644 Binary files a/defold-rive/lib/js-web/librive_pls_renderer.a and b/defold-rive/lib/js-web/librive_pls_renderer.a differ diff --git a/defold-rive/lib/wasm-web/liblibpng.a b/defold-rive/lib/wasm-web/liblibpng.a index 0d267d1e..ba3ca251 100644 Binary files a/defold-rive/lib/wasm-web/liblibpng.a and b/defold-rive/lib/wasm-web/liblibpng.a differ diff --git a/defold-rive/lib/wasm-web/librive.a b/defold-rive/lib/wasm-web/librive.a index c93ca410..855e48b3 100644 Binary files a/defold-rive/lib/wasm-web/librive.a and b/defold-rive/lib/wasm-web/librive.a differ diff --git a/defold-rive/lib/wasm-web/librive_decoders.a b/defold-rive/lib/wasm-web/librive_decoders.a index bb0b6f34..77782eba 100644 Binary files a/defold-rive/lib/wasm-web/librive_decoders.a and b/defold-rive/lib/wasm-web/librive_decoders.a differ diff --git a/defold-rive/lib/wasm-web/librive_harfbuzz.a b/defold-rive/lib/wasm-web/librive_harfbuzz.a index 6590a00a..06322f9d 100644 Binary files a/defold-rive/lib/wasm-web/librive_harfbuzz.a and b/defold-rive/lib/wasm-web/librive_harfbuzz.a differ diff --git a/defold-rive/lib/wasm-web/librive_pls_renderer.a b/defold-rive/lib/wasm-web/librive_pls_renderer.a index b2a4c904..85d7c35a 100644 Binary files a/defold-rive/lib/wasm-web/librive_pls_renderer.a and b/defold-rive/lib/wasm-web/librive_pls_renderer.a differ diff --git a/defold-rive/lib/wasm-web/librive_renderer_wagyu.a b/defold-rive/lib/wasm-web/librive_renderer_wagyu.a index 5651f339..29e28cb0 100644 Binary files a/defold-rive/lib/wasm-web/librive_renderer_wagyu.a and b/defold-rive/lib/wasm-web/librive_renderer_wagyu.a differ diff --git a/defold-rive/lib/wasm_pthread-web/librive.a b/defold-rive/lib/wasm_pthread-web/librive.a index 255b72d6..855e48b3 100644 Binary files a/defold-rive/lib/wasm_pthread-web/librive.a and b/defold-rive/lib/wasm_pthread-web/librive.a differ diff --git a/defold-rive/lib/wasm_pthread-web/librive_harfbuzz.a b/defold-rive/lib/wasm_pthread-web/librive_harfbuzz.a index 548c2c88..06322f9d 100644 Binary files a/defold-rive/lib/wasm_pthread-web/librive_harfbuzz.a and b/defold-rive/lib/wasm_pthread-web/librive_harfbuzz.a differ diff --git a/defold-rive/lib/wasm_pthread-web/librive_pls_renderer.a b/defold-rive/lib/wasm_pthread-web/librive_pls_renderer.a index 284e824e..85d7c35a 100644 Binary files a/defold-rive/lib/wasm_pthread-web/librive_pls_renderer.a and b/defold-rive/lib/wasm_pthread-web/librive_pls_renderer.a differ diff --git a/defold-rive/lib/wasm_pthread-web/librive_renderer_wagyu.a b/defold-rive/lib/wasm_pthread-web/librive_renderer_wagyu.a index 9b545712..29e28cb0 100644 Binary files a/defold-rive/lib/wasm_pthread-web/librive_renderer_wagyu.a and b/defold-rive/lib/wasm_pthread-web/librive_renderer_wagyu.a differ diff --git a/defold-rive/lib/x86_64-ios/liblibjpeg.a b/defold-rive/lib/x86_64-ios/liblibjpeg.a index e5a99678..db090974 100644 Binary files a/defold-rive/lib/x86_64-ios/liblibjpeg.a and b/defold-rive/lib/x86_64-ios/liblibjpeg.a differ diff --git a/defold-rive/lib/x86_64-ios/liblibpng.a b/defold-rive/lib/x86_64-ios/liblibpng.a index 232b1afe..a1ab349d 100644 Binary files a/defold-rive/lib/x86_64-ios/liblibpng.a and b/defold-rive/lib/x86_64-ios/liblibpng.a differ diff --git a/defold-rive/lib/x86_64-ios/liblibwebp.a b/defold-rive/lib/x86_64-ios/liblibwebp.a index 7c93b210..4570790d 100644 Binary files a/defold-rive/lib/x86_64-ios/liblibwebp.a and b/defold-rive/lib/x86_64-ios/liblibwebp.a differ diff --git a/defold-rive/lib/x86_64-ios/libminiaudio.a b/defold-rive/lib/x86_64-ios/libminiaudio.a index 4fb92876..c600c027 100644 Binary files a/defold-rive/lib/x86_64-ios/libminiaudio.a and b/defold-rive/lib/x86_64-ios/libminiaudio.a differ diff --git a/defold-rive/lib/x86_64-ios/librive.a b/defold-rive/lib/x86_64-ios/librive.a index 298c1ff8..5e337de1 100644 Binary files a/defold-rive/lib/x86_64-ios/librive.a and b/defold-rive/lib/x86_64-ios/librive.a differ diff --git a/defold-rive/lib/x86_64-ios/librive_decoders.a b/defold-rive/lib/x86_64-ios/librive_decoders.a index ab55d5ce..37ed7e14 100644 Binary files a/defold-rive/lib/x86_64-ios/librive_decoders.a and b/defold-rive/lib/x86_64-ios/librive_decoders.a differ diff --git a/defold-rive/lib/x86_64-ios/librive_harfbuzz.a b/defold-rive/lib/x86_64-ios/librive_harfbuzz.a index 52ff827a..3b017dac 100644 Binary files a/defold-rive/lib/x86_64-ios/librive_harfbuzz.a and b/defold-rive/lib/x86_64-ios/librive_harfbuzz.a differ diff --git a/defold-rive/lib/x86_64-ios/librive_pls_renderer.a b/defold-rive/lib/x86_64-ios/librive_pls_renderer.a index 1c38ac2b..fbc1ad2c 100644 Binary files a/defold-rive/lib/x86_64-ios/librive_pls_renderer.a and b/defold-rive/lib/x86_64-ios/librive_pls_renderer.a differ diff --git a/defold-rive/lib/x86_64-ios/librive_sheenbidi.a b/defold-rive/lib/x86_64-ios/librive_sheenbidi.a index 0f3fb98b..02ff51db 100644 Binary files a/defold-rive/lib/x86_64-ios/librive_sheenbidi.a and b/defold-rive/lib/x86_64-ios/librive_sheenbidi.a differ diff --git a/defold-rive/lib/x86_64-ios/librive_yoga.a b/defold-rive/lib/x86_64-ios/librive_yoga.a index d7fdf57b..77b11370 100644 Binary files a/defold-rive/lib/x86_64-ios/librive_yoga.a and b/defold-rive/lib/x86_64-ios/librive_yoga.a differ diff --git a/defold-rive/lib/x86_64-ios/libzlib.a b/defold-rive/lib/x86_64-ios/libzlib.a index 20631b7b..ef5d678c 100644 Binary files a/defold-rive/lib/x86_64-ios/libzlib.a and b/defold-rive/lib/x86_64-ios/libzlib.a differ diff --git a/defold-rive/lib/x86_64-linux/liblibjpeg.a b/defold-rive/lib/x86_64-linux/liblibjpeg.a index 9df5003f..f61acb48 100644 Binary files a/defold-rive/lib/x86_64-linux/liblibjpeg.a and b/defold-rive/lib/x86_64-linux/liblibjpeg.a differ diff --git a/defold-rive/lib/x86_64-linux/liblibpng.a b/defold-rive/lib/x86_64-linux/liblibpng.a index eea8eb5b..094fadb5 100644 Binary files a/defold-rive/lib/x86_64-linux/liblibpng.a and b/defold-rive/lib/x86_64-linux/liblibpng.a differ diff --git a/defold-rive/lib/x86_64-linux/liblibwebp.a b/defold-rive/lib/x86_64-linux/liblibwebp.a index 0899c565..80204619 100644 Binary files a/defold-rive/lib/x86_64-linux/liblibwebp.a and b/defold-rive/lib/x86_64-linux/liblibwebp.a differ diff --git a/defold-rive/lib/x86_64-linux/libminiaudio.a b/defold-rive/lib/x86_64-linux/libminiaudio.a index 0a3e1742..836d997c 100644 Binary files a/defold-rive/lib/x86_64-linux/libminiaudio.a and b/defold-rive/lib/x86_64-linux/libminiaudio.a differ diff --git a/defold-rive/lib/x86_64-linux/librive.a b/defold-rive/lib/x86_64-linux/librive.a index 53da094f..8434cd95 100644 Binary files a/defold-rive/lib/x86_64-linux/librive.a and b/defold-rive/lib/x86_64-linux/librive.a differ diff --git a/defold-rive/lib/x86_64-linux/librive_decoders.a b/defold-rive/lib/x86_64-linux/librive_decoders.a index f6528b90..6a1ab1dd 100644 Binary files a/defold-rive/lib/x86_64-linux/librive_decoders.a and b/defold-rive/lib/x86_64-linux/librive_decoders.a differ diff --git a/defold-rive/lib/x86_64-linux/librive_harfbuzz.a b/defold-rive/lib/x86_64-linux/librive_harfbuzz.a index 585ae283..d956061d 100644 Binary files a/defold-rive/lib/x86_64-linux/librive_harfbuzz.a and b/defold-rive/lib/x86_64-linux/librive_harfbuzz.a differ diff --git a/defold-rive/lib/x86_64-linux/librive_pls_renderer.a b/defold-rive/lib/x86_64-linux/librive_pls_renderer.a index c9790153..015e1ec9 100644 Binary files a/defold-rive/lib/x86_64-linux/librive_pls_renderer.a and b/defold-rive/lib/x86_64-linux/librive_pls_renderer.a differ diff --git a/defold-rive/lib/x86_64-linux/librive_sheenbidi.a b/defold-rive/lib/x86_64-linux/librive_sheenbidi.a index a32086f4..e9b1c986 100644 Binary files a/defold-rive/lib/x86_64-linux/librive_sheenbidi.a and b/defold-rive/lib/x86_64-linux/librive_sheenbidi.a differ diff --git a/defold-rive/lib/x86_64-linux/librive_yoga.a b/defold-rive/lib/x86_64-linux/librive_yoga.a index c72b24ae..d5e51dd6 100644 Binary files a/defold-rive/lib/x86_64-linux/librive_yoga.a and b/defold-rive/lib/x86_64-linux/librive_yoga.a differ diff --git a/defold-rive/lib/x86_64-linux/libzlib.a b/defold-rive/lib/x86_64-linux/libzlib.a index 3a4a6fec..092545d1 100644 Binary files a/defold-rive/lib/x86_64-linux/libzlib.a and b/defold-rive/lib/x86_64-linux/libzlib.a differ diff --git a/defold-rive/lib/x86_64-osx/liblibjpeg.a b/defold-rive/lib/x86_64-osx/liblibjpeg.a index 35a9b4f5..2e604325 100644 Binary files a/defold-rive/lib/x86_64-osx/liblibjpeg.a and b/defold-rive/lib/x86_64-osx/liblibjpeg.a differ diff --git a/defold-rive/lib/x86_64-osx/liblibpng.a b/defold-rive/lib/x86_64-osx/liblibpng.a index 8e9b8eb7..4f51b6f3 100644 Binary files a/defold-rive/lib/x86_64-osx/liblibpng.a and b/defold-rive/lib/x86_64-osx/liblibpng.a differ diff --git a/defold-rive/lib/x86_64-osx/liblibwebp.a b/defold-rive/lib/x86_64-osx/liblibwebp.a index 5fd94e65..0ebdf4c2 100644 Binary files a/defold-rive/lib/x86_64-osx/liblibwebp.a and b/defold-rive/lib/x86_64-osx/liblibwebp.a differ diff --git a/defold-rive/lib/x86_64-osx/libminiaudio.a b/defold-rive/lib/x86_64-osx/libminiaudio.a index b05998fe..d89e5f0e 100644 Binary files a/defold-rive/lib/x86_64-osx/libminiaudio.a and b/defold-rive/lib/x86_64-osx/libminiaudio.a differ diff --git a/defold-rive/lib/x86_64-osx/librive.a b/defold-rive/lib/x86_64-osx/librive.a index 2aa96305..ba2c10e9 100644 Binary files a/defold-rive/lib/x86_64-osx/librive.a and b/defold-rive/lib/x86_64-osx/librive.a differ diff --git a/defold-rive/lib/x86_64-osx/librive_decoders.a b/defold-rive/lib/x86_64-osx/librive_decoders.a index 5a38c6db..96df548e 100644 Binary files a/defold-rive/lib/x86_64-osx/librive_decoders.a and b/defold-rive/lib/x86_64-osx/librive_decoders.a differ diff --git a/defold-rive/lib/x86_64-osx/librive_harfbuzz.a b/defold-rive/lib/x86_64-osx/librive_harfbuzz.a index 198d2781..ba0abf14 100644 Binary files a/defold-rive/lib/x86_64-osx/librive_harfbuzz.a and b/defold-rive/lib/x86_64-osx/librive_harfbuzz.a differ diff --git a/defold-rive/lib/x86_64-osx/librive_pls_renderer.a b/defold-rive/lib/x86_64-osx/librive_pls_renderer.a index 5a7a071e..5943fb27 100644 Binary files a/defold-rive/lib/x86_64-osx/librive_pls_renderer.a and b/defold-rive/lib/x86_64-osx/librive_pls_renderer.a differ diff --git a/defold-rive/lib/x86_64-osx/librive_sheenbidi.a b/defold-rive/lib/x86_64-osx/librive_sheenbidi.a index 3a5aa046..2b4b5cb1 100644 Binary files a/defold-rive/lib/x86_64-osx/librive_sheenbidi.a and b/defold-rive/lib/x86_64-osx/librive_sheenbidi.a differ diff --git a/defold-rive/lib/x86_64-osx/librive_yoga.a b/defold-rive/lib/x86_64-osx/librive_yoga.a index cdb34662..63557ce8 100644 Binary files a/defold-rive/lib/x86_64-osx/librive_yoga.a and b/defold-rive/lib/x86_64-osx/librive_yoga.a differ diff --git a/defold-rive/lib/x86_64-osx/libzlib.a b/defold-rive/lib/x86_64-osx/libzlib.a index 7ba3b3c1..b6210b4a 100644 Binary files a/defold-rive/lib/x86_64-osx/libzlib.a and b/defold-rive/lib/x86_64-osx/libzlib.a differ diff --git a/defold-rive/lib/x86_64-win32/harfbuzz.lib b/defold-rive/lib/x86_64-win32/harfbuzz.lib index 4eb260a8..35112268 100644 Binary files a/defold-rive/lib/x86_64-win32/harfbuzz.lib and b/defold-rive/lib/x86_64-win32/harfbuzz.lib differ diff --git a/defold-rive/lib/x86_64-win32/rive.lib b/defold-rive/lib/x86_64-win32/rive.lib index 8e7883bf..055f5090 100644 Binary files a/defold-rive/lib/x86_64-win32/rive.lib and b/defold-rive/lib/x86_64-win32/rive.lib differ diff --git a/defold-rive/lib/x86_64-win32/rive_renderer.lib b/defold-rive/lib/x86_64-win32/rive_renderer.lib index e97d9bfe..b43d20f9 100644 Binary files a/defold-rive/lib/x86_64-win32/rive_renderer.lib and b/defold-rive/lib/x86_64-win32/rive_renderer.lib differ diff --git a/defold-rive/lib/x86_64-win32/rivetess.lib b/defold-rive/lib/x86_64-win32/rivetess.lib index 357af399..fe9d72ba 100644 Binary files a/defold-rive/lib/x86_64-win32/rivetess.lib and b/defold-rive/lib/x86_64-win32/rivetess.lib differ diff --git a/defold-rive/lib/x86_64-win32/sheenbidi.lib b/defold-rive/lib/x86_64-win32/sheenbidi.lib index cb4bdc42..f0e726d8 100644 Binary files a/defold-rive/lib/x86_64-win32/sheenbidi.lib and b/defold-rive/lib/x86_64-win32/sheenbidi.lib differ diff --git a/defold-rive/lib/x86_64-win32/tess2.lib b/defold-rive/lib/x86_64-win32/tess2.lib index cc40e082..eae62f05 100644 Binary files a/defold-rive/lib/x86_64-win32/tess2.lib and b/defold-rive/lib/x86_64-win32/tess2.lib differ diff --git a/defold-rive/lib/x86_64-win32/yoga.lib b/defold-rive/lib/x86_64-win32/yoga.lib index e0ebe3ec..7b2de203 100644 Binary files a/defold-rive/lib/x86_64-win32/yoga.lib and b/defold-rive/lib/x86_64-win32/yoga.lib differ diff --git a/defold-rive/plugins/lib/arm64-osx/libRiveExt.dylib b/defold-rive/plugins/lib/arm64-osx/libRiveExt.dylib index ed29520e..60c1a77d 100644 Binary files a/defold-rive/plugins/lib/arm64-osx/libRiveExt.dylib and b/defold-rive/plugins/lib/arm64-osx/libRiveExt.dylib differ diff --git a/defold-rive/plugins/lib/x86_64-linux/libRiveExt.so b/defold-rive/plugins/lib/x86_64-linux/libRiveExt.so index 3100a0ea..07b3f279 100644 Binary files a/defold-rive/plugins/lib/x86_64-linux/libRiveExt.so and b/defold-rive/plugins/lib/x86_64-linux/libRiveExt.so differ diff --git a/defold-rive/plugins/lib/x86_64-osx/libRiveExt.dylib b/defold-rive/plugins/lib/x86_64-osx/libRiveExt.dylib index 9f9cdece..c1c120bd 100644 Binary files a/defold-rive/plugins/lib/x86_64-osx/libRiveExt.dylib and b/defold-rive/plugins/lib/x86_64-osx/libRiveExt.dylib differ diff --git a/defold-rive/plugins/lib/x86_64-win32/libRiveExt.dll b/defold-rive/plugins/lib/x86_64-win32/libRiveExt.dll index 8d890afb..bb494597 100644 Binary files a/defold-rive/plugins/lib/x86_64-win32/libRiveExt.dll and b/defold-rive/plugins/lib/x86_64-win32/libRiveExt.dll differ diff --git a/defold-rive/plugins/share/pluginRiveExt.jar b/defold-rive/plugins/share/pluginRiveExt.jar index d35a5c81..1a0e8da6 100644 Binary files a/defold-rive/plugins/share/pluginRiveExt.jar and b/defold-rive/plugins/share/pluginRiveExt.jar differ diff --git a/defold-rive/pluginsrc/rive_renderer_null.cpp b/defold-rive/pluginsrc/rive_renderer_null.cpp deleted file mode 100644 index b8ecc539..00000000 --- a/defold-rive/pluginsrc/rive_renderer_null.cpp +++ /dev/null @@ -1,12 +0,0 @@ - -#include - -#include - -namespace dmRive -{ - rive::rcp CreateRiveRenderImage(HRenderContext context, void* bytes, uint32_t byte_count) - { - return nullptr; - } -} \ No newline at end of file diff --git a/defold-rive/src/comp_rive.cpp b/defold-rive/src/comp_rive.cpp index ff687be7..9711c2cc 100644 --- a/defold-rive/src/comp_rive.cpp +++ b/defold-rive/src/comp_rive.cpp @@ -1,4 +1,4 @@ -// Copyright 2020 The Defold Foundation +// Copyright 2020-2025 The Defold Foundation // Licensed under the Defold License version 1.0 (the "License"); you may not use // this file except in compliance with the License. // @@ -14,22 +14,6 @@ #include // memset - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include // Artboard -#include -#include - // Rive extension #include "comp_rive.h" #include "comp_rive_private.h" @@ -38,10 +22,12 @@ #include "res_rive_model.h" #include +#include #include #include // Defold Rive Renderer +#include #include // DMSDK @@ -80,12 +66,12 @@ namespace dmRive { using namespace dmVMath; - static const dmhash_t PROP_ANIMATION = dmHashString64("animation"); - static const dmhash_t PROP_CURSOR = dmHashString64("cursor"); - static const dmhash_t PROP_PLAYBACK_RATE = dmHashString64("playback_rate"); - static const dmhash_t PROP_MATERIAL = dmHashString64("material"); - static const dmhash_t MATERIAL_EXT_HASH = dmHashString64("materialc"); - static const dmhash_t PROP_RIVE_FILE = dmHashString64("rive_file"); + static const dmhash_t PROP_ARTBOARD = dmHashString64("artboard"); + static const dmhash_t PROP_STATE_MACHINE = dmHashString64("state_machine"); + static const dmhash_t PROP_PLAYBACK_RATE = dmHashString64("playback_rate"); + static const dmhash_t PROP_MATERIAL = dmHashString64("material"); + static const dmhash_t MATERIAL_EXT_HASH = dmHashString64("materialc"); + static const dmhash_t PROP_RIVE_FILE = dmHashString64("rive_file"); static float g_DisplayFactor = 0.0f; static float g_OriginalWindowWidth = 0.0f; @@ -110,6 +96,7 @@ namespace dmRive dmRender::HRenderContext m_RenderContext; dmGraphics::HContext m_GraphicsContext; dmGraphics::HTexture m_NullTexture; + HRenderContext m_RiveRenderContext; uint32_t m_MaxInstanceCount; }; @@ -127,6 +114,55 @@ namespace dmRive bool m_DidWork; // did we get any batch workload ? }; + class SimpleArtboardListener : public rive::CommandQueue::ArtboardListener + { + public: + virtual void onStateMachinesListed(const rive::ArtboardHandle fileHandle, uint64_t requestId, + std::vector stateMachineNames) override + { + // we can guarantee that this is the only listener that will receive + // this callback, so it's fine to move the params + //m_stateMachineNames = std::move(stateMachineNames); + } + + RiveComponent* m_Component; + + //std::vector m_stateMachineNames; + }; + + static inline rive::Fit DDFToRiveFit(dmRiveDDF::RiveModelDesc::Fit fit) + { + switch(fit) + { + case dmRiveDDF::RiveModelDesc::FIT_FILL: return rive::Fit::fill; + case dmRiveDDF::RiveModelDesc::FIT_CONTAIN: return rive::Fit::contain; + case dmRiveDDF::RiveModelDesc::FIT_COVER: return rive::Fit::cover; + case dmRiveDDF::RiveModelDesc::FIT_FIT_WIDTH: return rive::Fit::fitWidth; + case dmRiveDDF::RiveModelDesc::FIT_FIT_HEIGHT: return rive::Fit::fitHeight; + case dmRiveDDF::RiveModelDesc::FIT_NONE: return rive::Fit::none; + case dmRiveDDF::RiveModelDesc::FIT_SCALE_DOWN: return rive::Fit::scaleDown; + case dmRiveDDF::RiveModelDesc::FIT_LAYOUT: return rive::Fit::layout; + } + return rive::Fit::none; + } + + static inline rive::Alignment DDFToRiveAlignment(dmRiveDDF::RiveModelDesc::Alignment alignment) + { + switch(alignment) + { + case dmRiveDDF::RiveModelDesc::ALIGNMENT_TOP_LEFT: return rive::Alignment::topLeft; + case dmRiveDDF::RiveModelDesc::ALIGNMENT_TOP_CENTER: return rive::Alignment::topCenter; + case dmRiveDDF::RiveModelDesc::ALIGNMENT_TOP_RIGHT: return rive::Alignment::topRight; + case dmRiveDDF::RiveModelDesc::ALIGNMENT_CENTER_LEFT: return rive::Alignment::centerLeft; + case dmRiveDDF::RiveModelDesc::ALIGNMENT_CENTER: return rive::Alignment::center; + case dmRiveDDF::RiveModelDesc::ALIGNMENT_CENTER_RIGHT: return rive::Alignment::centerRight; + case dmRiveDDF::RiveModelDesc::ALIGNMENT_BOTTOM_LEFT: return rive::Alignment::bottomLeft; + case dmRiveDDF::RiveModelDesc::ALIGNMENT_BOTTOM_CENTER: return rive::Alignment::bottomCenter; + case dmRiveDDF::RiveModelDesc::ALIGNMENT_BOTTOM_RIGHT: return rive::Alignment::bottomRight; + } + return rive::Alignment::center; + } + dmGameObject::CreateResult CompRiveNewWorld(const dmGameObject::ComponentNewWorldParams& params) { CompRiveContext* context = (CompRiveContext*)params.m_Context; @@ -139,6 +175,7 @@ namespace dmRive world->m_RenderConstants.SetSize(context->m_MaxInstanceCount); world->m_BlitMaterial = 0; world->m_DidWork = false; + world->m_RiveRenderContext = context->m_RiveRenderContext; float bottom = 0.0f; float top = 1.0f; @@ -188,20 +225,6 @@ namespace dmRive return dmGameObject::CREATE_RESULT_OK; } - RiveArtboardIdList* FindArtboardIdList(rive::Artboard* artboard, dmRive::RiveSceneData* data) - { - dmhash_t artboard_id = dmHashString64(artboard->name().c_str()); - - for (int i = 0; i < data->m_ArtboardIdLists.Size(); ++i) - { - if (data->m_ArtboardIdLists[i]->m_ArtboardNameHash == artboard_id) - { - return data->m_ArtboardIdLists[i]; - } - } - return 0x0; - } - static inline dmGameSystem::MaterialResource* GetMaterialResource(const RiveComponent* component, const RiveModelResource* resource) { return component->m_Material ? component->m_Material : resource->m_Material; @@ -225,12 +248,12 @@ namespace dmRive HashState32 state; bool reverse = false; RiveModelResource* resource = component->m_Resource; - dmRiveDDF::RiveModelDesc* ddf = resource->m_DDF; + //dmRiveDDF::RiveModelDesc* ddf = resource->m_DDF; dmRender::HMaterial material = GetMaterial(component, resource); dmGameSystem::TextureSetResource* texture_set = resource->m_Scene->m_TextureSet; dmHashInit32(&state, reverse); dmHashUpdateBuffer32(&state, &material, sizeof(material)); - dmHashUpdateBuffer32(&state, &ddf->m_BlendMode, sizeof(ddf->m_BlendMode)); + //dmHashUpdateBuffer32(&state, &ddf->m_BlendMode, sizeof(ddf->m_BlendMode)); // not currently used if (texture_set) dmHashUpdateBuffer32(&state, &texture_set, sizeof(texture_set)); component->m_MixedHash = dmHashFinal32(&state); @@ -249,24 +272,113 @@ namespace dmRive return GetComponentFromIndex(world, index); } - static void InstantiateArtboard(RiveComponent* component) + rive::FileHandle CompRiveGetFile(RiveComponent* component) + { + RiveSceneData* resource = GetRiveResource(component, component->m_Resource); + return resource->m_File; + } + + rive::ArtboardHandle CompRiveGetArtboard(RiveComponent* component) + { + return component->m_Artboard; + } + + rive::ArtboardHandle CompRiveSetArtboard(RiveComponent* component, const char* artboard_name) { dmRive::RiveSceneData* data = (dmRive::RiveSceneData*) component->m_Resource->m_Scene->m_Scene; + rive::FileHandle file = data->m_File; + rive::rcp queue = dmRiveCommands::GetCommandQueue(); + + rive::ArtboardHandle old_handle = component->m_Artboard; + + if (artboard_name && artboard_name[0] != '\0') + { + component->m_Artboard = queue->instantiateArtboardNamed(file, artboard_name); + if (!component->m_Artboard) + { + dmLogWarning("Could not find artboard with name '%s'", artboard_name); + } + } + + if (!component->m_Artboard) + { + component->m_Artboard = queue->instantiateDefaultArtboard(file); + } + + return old_handle; + } + + rive::StateMachineHandle CompRiveGetStateMachine(RiveComponent* component) + { + return component->m_StateMachine; + } + + rive::ViewModelInstanceHandle CompRiveGetViewModelInstance(RiveComponent* component) + { + return component->m_ViewModelInstance; + } + + static void BindViewModelInstance(RiveComponent* component) + { + rive::rcp queue = dmRiveCommands::GetCommandQueue(); + queue->bindViewModelInstance(component->m_StateMachine, component->m_ViewModelInstance); + } + + rive::StateMachineHandle CompRiveSetStateMachine(RiveComponent* component, const char* state_machine_name) + { + rive::ArtboardHandle artboard = component->m_Artboard; + rive::rcp queue = dmRiveCommands::GetCommandQueue(); - if (component->m_Resource->m_DDF->m_Artboard && component->m_Resource->m_DDF->m_Artboard[0] != '\0') + rive::StateMachineHandle old_handle = component->m_StateMachine; + + if (state_machine_name && state_machine_name[0] != '\0') { - component->m_ArtboardInstance = data->m_File->artboardNamed(component->m_Resource->m_DDF->m_Artboard); + component->m_StateMachine = queue->instantiateStateMachineNamed(artboard, state_machine_name); + if (!component->m_StateMachine) + { + dmLogWarning("Could not find state_machine with name '%s'", state_machine_name); + } + } + + if (!component->m_StateMachine) + { + component->m_StateMachine = queue->instantiateDefaultStateMachine(artboard); + } + + component->m_Enabled = component->m_StateMachine != 0; + + if (component->m_StateMachine && component->m_Resource->m_DDF->m_AutoBind) + { + CompRiveSetViewModelInstance(component, 0); + BindViewModelInstance(component); + } + + return old_handle; + } - if (!component->m_ArtboardInstance) + rive::ViewModelInstanceHandle CompRiveSetViewModelInstance(RiveComponent* component, const char* viewmodel_name) + { + rive::FileHandle file = CompRiveGetFile(component); + rive::rcp queue = dmRiveCommands::GetCommandQueue(); + + rive::ViewModelInstanceHandle old_handle = component->m_ViewModelInstance; + + if (viewmodel_name && viewmodel_name[0] != '\0') + { + component->m_ViewModelInstance = queue->instantiateDefaultViewModelInstance(file, viewmodel_name); + if (!component->m_ViewModelInstance) { - dmLogWarning("Could not find artboard with name '%s'", component->m_Resource->m_DDF->m_Artboard); + dmLogWarning("Could not find view model instance with name '%s'", viewmodel_name); } } - if (!component->m_ArtboardInstance) + if (!component->m_ViewModelInstance) { - component->m_ArtboardInstance = data->m_File->artboardDefault(); + component->m_ViewModelInstance = queue->instantiateDefaultViewModelInstance(file, component->m_Artboard); } + + component->m_Enabled = component->m_ViewModelInstance != 0; + return old_handle; } dmGameObject::CreateResult CompRiveCreate(const dmGameObject::ComponentCreateParams& params) @@ -291,116 +403,57 @@ namespace dmRive CompRiveAnimationReset(component); dmMessage::ResetURL(&component->m_Listener); + rive::rcp queue = dmRiveCommands::GetCommandQueue(); + component->m_ComponentIndex = params.m_ComponentIndex; component->m_Enabled = 1; component->m_World = Matrix4::identity(); component->m_DoRender = 0; component->m_RenderConstants = 0; component->m_CurrentViewModelInstanceRuntime = INVALID_HANDLE; - component->m_HandleCounter = 0; - - InstantiateArtboard(component); + component->m_DrawKey = queue->createDrawKey(); - component->m_ArtboardInstance->advance(0.0f); + dmRiveDDF::RiveModelDesc* ddf = component->m_Resource->m_DDF; - if (component->m_Resource->m_CreateGoBones) + component->m_Fullscreen = ddf->m_CoordinateSystem == dmRiveDDF::RiveModelDesc::COORDINATE_SYSTEM_FULLSCREEN; + component->m_Fit = rive::Fit::layout; + component->m_Alignment = rive::Alignment::center; + if (!component->m_Fullscreen) { - dmRive::GetAllBones(component->m_ArtboardInstance.get(), &component->m_Bones); - CreateBones(world, component); - UpdateBones(component); + component->m_Fit = DDFToRiveFit(ddf->m_ArtboardFit); + component->m_Alignment = DDFToRiveAlignment(ddf->m_ArtboardAlignment); } - dmhash_t empty_id = dmHashString64(""); - dmhash_t anim_id = dmHashString64(component->m_Resource->m_DDF->m_DefaultAnimation); - dmhash_t state_machine_id = dmHashString64(component->m_Resource->m_DDF->m_DefaultStateMachine); + CompRiveSetArtboard(component, ddf->m_Artboard); + CompRiveSetStateMachine(component, ddf->m_DefaultStateMachine); - dmRiveDDF::RivePlayAnimation ddf; - ddf.m_Offset = 0.0; - ddf.m_PlaybackRate = 1.0; - - bool use_default_state_machine = component->m_ArtboardInstance->defaultStateMachineIndex() >= 0; - if (empty_id != state_machine_id || use_default_state_machine) - { - ddf.m_Playback = dmGameObject::PLAYBACK_NONE; - ddf.m_AnimationId = use_default_state_machine ? 0 : state_machine_id; - ddf.m_IsStateMachine = true; - if (!CompRivePlayStateMachine(component, &ddf, 0)) - { - dmLogError("Couldn't play state machine named '%s'", dmHashReverseSafe64(state_machine_id)); - } - } - else - { - ddf.m_AnimationId = anim_id; // May be 0 - ddf.m_Playback = dmGameObject::PLAYBACK_LOOP_FORWARD; - ddf.m_IsStateMachine = false; - if (!CompRivePlayAnimation(component, &ddf, 0)) - { - dmLogError("Couldn't play animation named '%s'", dmHashReverseSafe64(anim_id)); - } - } - - component->m_CurrentViewModelInstanceRuntime = 0xFFFFFFFF; - if (component->m_Resource->m_DDF->m_AutoBind) - { - component->m_CurrentViewModelInstanceRuntime = CompRiveCreateViewModelInstanceRuntime(component, 0); - if (component->m_CurrentViewModelInstanceRuntime != dmRive::INVALID_HANDLE) - { - CompRiveSetViewModelInstanceRuntime(component, component->m_CurrentViewModelInstanceRuntime); - } - } component->m_ReHash = 1; *params.m_UserData = (uintptr_t)index; return dmGameObject::CREATE_RESULT_OK; } - static void CompRiveRunCallback(RiveComponent* component, const dmDDF::Descriptor* desc, const char* data, const dmMessage::URL* sender) - { - dmScript::LuaCallbackInfo* cbk = component->m_Callback; - if (!dmScript::IsCallbackValid(cbk)) - { - dmLogError("Rive callback is invalid."); - return; - } - - lua_State* L = dmScript::GetCallbackLuaContext(cbk); - DM_LUA_STACK_CHECK(L, 0); - - if (!dmScript::SetupCallback(cbk)) - { - dmLogError("Failed to setup Rive callback"); - return; - } - - dmScript::PushHash(L, desc->m_NameHash); - dmScript::PushDDF(L, desc, data, false); - dmScript::PushURL(L, *sender); - int ret = dmScript::PCall(L, 4, 0); - (void)ret; - dmScript::TeardownCallback(cbk); - } - - static void CompRiveClearCallback(RiveComponent* component) - { - if (component->m_Callback) - { - dmScript::DestroyCallback(component->m_Callback); - component->m_Callback = 0x0; - } - } - static void DestroyComponent(RiveWorld* world, uint32_t index) { + rive::rcp queue = dmRiveCommands::GetCommandQueue(); + RiveComponent* component = GetComponentFromIndex(world, index); - dmGameObject::DeleteBones(component->m_Instance); + //dmGameObject::DeleteBones(component->m_Instance); if (component->m_RenderConstants) dmGameSystem::DestroyRenderConstants(component->m_RenderConstants); - component->m_ArtboardInstance.reset(); - component->m_AnimationInstance.reset(); - component->m_StateMachineInstance.reset(); + if (component->m_ViewModelInstance) + queue->deleteViewModelInstance(component->m_ViewModelInstance); + component->m_ViewModelInstance = 0; + + if (component->m_StateMachine) + queue->deleteStateMachine(component->m_StateMachine); + component->m_StateMachine = 0; + + if (component->m_Artboard) + queue->deleteArtboard(component->m_Artboard); + component->m_Artboard = 0; delete component; world->m_Components.Free(index, true); @@ -415,9 +468,6 @@ namespace dmRive if (component->m_Material) { dmResource::Release(ctx->m_Factory, (void*)component->m_Material); } - if (component->m_Callback) { - CompRiveClearCallback(component); - } DestroyComponent(world, index); return dmGameObject::CREATE_RESULT_OK; } @@ -457,6 +507,7 @@ namespace dmRive { if (world->m_RiveRenderContext) { + dmRiveCommands::ProcessMessages(); // Flush any draw() messages RenderEnd(world->m_RiveRenderContext); if (g_RenderBeginParams.m_DoFinalBlit) @@ -477,55 +528,25 @@ namespace dmRive } } - static inline rive::Fit DDFToRiveFit(dmRiveDDF::RiveModelDesc::Fit fit) - { - switch(fit) - { - case dmRiveDDF::RiveModelDesc::FIT_FILL: return rive::Fit::fill; - case dmRiveDDF::RiveModelDesc::FIT_CONTAIN: return rive::Fit::contain; - case dmRiveDDF::RiveModelDesc::FIT_COVER: return rive::Fit::cover; - case dmRiveDDF::RiveModelDesc::FIT_FIT_WIDTH: return rive::Fit::fitWidth; - case dmRiveDDF::RiveModelDesc::FIT_FIT_HEIGHT: return rive::Fit::fitHeight; - case dmRiveDDF::RiveModelDesc::FIT_NONE: return rive::Fit::none; - case dmRiveDDF::RiveModelDesc::FIT_SCALE_DOWN: return rive::Fit::scaleDown; - case dmRiveDDF::RiveModelDesc::FIT_LAYOUT: return rive::Fit::layout; - } - return rive::Fit::none; - } - - static inline rive::Alignment DDFToRiveAlignment(dmRiveDDF::RiveModelDesc::Alignment alignment) - { - switch(alignment) - { - case dmRiveDDF::RiveModelDesc::ALIGNMENT_TOP_LEFT: return rive::Alignment::topLeft; - case dmRiveDDF::RiveModelDesc::ALIGNMENT_TOP_CENTER: return rive::Alignment::topCenter; - case dmRiveDDF::RiveModelDesc::ALIGNMENT_TOP_RIGHT: return rive::Alignment::topRight; - case dmRiveDDF::RiveModelDesc::ALIGNMENT_CENTER_LEFT: return rive::Alignment::centerLeft; - case dmRiveDDF::RiveModelDesc::ALIGNMENT_CENTER: return rive::Alignment::center; - case dmRiveDDF::RiveModelDesc::ALIGNMENT_CENTER_RIGHT: return rive::Alignment::centerRight; - case dmRiveDDF::RiveModelDesc::ALIGNMENT_BOTTOM_LEFT: return rive::Alignment::bottomLeft; - case dmRiveDDF::RiveModelDesc::ALIGNMENT_BOTTOM_CENTER: return rive::Alignment::bottomCenter; - case dmRiveDDF::RiveModelDesc::ALIGNMENT_BOTTOM_RIGHT: return rive::Alignment::bottomRight; - } - return rive::Alignment::center; - } - static void RenderBatch(RiveWorld* world, dmRender::HRenderContext render_context, dmRender::RenderListEntry *buf, uint32_t* begin, uint32_t* end) { RiveComponent* first = (RiveComponent*) buf[*begin].m_UserData; dmRive::RiveSceneResource* scene_res = first->m_Resource->m_Scene; dmRive::RiveSceneData* data = (dmRive::RiveSceneData*) scene_res->m_Scene; - world->m_RiveRenderContext = data->m_RiveRenderContext; RenderBegin(world->m_RiveRenderContext, world->m_Ctx->m_Factory, g_RenderBeginParams); uint32_t width, height; GetDimensions(world->m_RiveRenderContext, &width, &height); + uint32_t window_height = dmGraphics::GetWindowHeight(world->m_Ctx->m_GraphicsContext); + rive::Mat2D viewTransform = GetViewTransform(world->m_RiveRenderContext, render_context); rive::Renderer* renderer = GetRiveRenderer(world->m_RiveRenderContext); - uint32_t window_height = dmGraphics::GetWindowHeight(world->m_Ctx->m_GraphicsContext); + float display_factor = g_DisplayFactor; + + rive::rcp queue = dmRiveCommands::GetCommandQueue(); for (uint32_t *i=begin;i!=end;i++) { @@ -537,49 +558,72 @@ namespace dmRive RiveModelResource* resource = c->m_Resource; dmRiveDDF::RiveModelDesc* ddf = resource->m_DDF; - renderer->save(); + // From command_buffer_example.cpp - rive::AABB bounds = c->m_ArtboardInstance->bounds(); + const rive::ArtboardHandle artboardHandle = c->m_Artboard; + rive::Fit fit = c->m_Fit; + rive::Alignment alignment = c->m_Alignment; + bool fullscreen = c->m_Fullscreen; - if (ddf->m_CoordinateSystem == dmRiveDDF::RiveModelDesc::COORDINATE_SYSTEM_FULLSCREEN) + rive::Mat2D transform; + if (fullscreen) { - // Apply the world matrix from the component to the artboard transform - rive::Mat2D transform; Mat4ToMat2D(c->m_World, transform); - - rive::Mat2D centerAdjustment = rive::Mat2D::fromTranslate(-bounds.width() / 2.0f, -bounds.height() / 2.0f); - rive::Mat2D scaleDpi = rive::Mat2D::fromScale(1,-1); - rive::Mat2D invertAdjustment = rive::Mat2D::fromScaleAndTranslation(g_DisplayFactor, -g_DisplayFactor, 0, window_height); - rive::Mat2D rendererTransform = invertAdjustment * viewTransform * transform * scaleDpi * centerAdjustment; - - renderer->transform(rendererTransform); - c->m_InverseRendererTransform = rendererTransform.invertOrIdentity(); } - else if (ddf->m_CoordinateSystem == dmRiveDDF::RiveModelDesc::COORDINATE_SYSTEM_RIVE) + + auto drawLoop = [artboardHandle, + renderer, + fullscreen, + fit, + alignment, + transform, + viewTransform, + width, + height, + window_height, + display_factor, + c](rive::DrawKey drawKey, rive::CommandServer* server) { - rive::Fit rive_fit = DDFToRiveFit(ddf->m_ArtboardFit); - rive::Alignment rive_align = DDFToRiveAlignment(ddf->m_ArtboardAlignment); + rive::ArtboardInstance* artboard = server->getArtboardInstance(artboardHandle); + if (artboard == nullptr) + { + return; + } + + rive::Factory* factory = server->factory(); + renderer->save(); + + rive::AABB bounds = artboard->bounds(); - if (rive_fit == rive::Fit::layout) + if (fullscreen) { - c->m_ArtboardInstance->width(width / g_DisplayFactor); - c->m_ArtboardInstance->height(height / g_DisplayFactor); + // Apply the world matrix from the component to the artboard transform + rive::Mat2D centerAdjustment = rive::Mat2D::fromTranslate(-bounds.width() / 2.0f, -bounds.height() / 2.0f); + rive::Mat2D scaleDpi = rive::Mat2D::fromScale(1,-1); + rive::Mat2D invertAdjustment = rive::Mat2D::fromScaleAndTranslation(display_factor, -display_factor, 0, window_height); + rive::Mat2D rendererTransform = invertAdjustment * viewTransform * transform * scaleDpi * centerAdjustment; + + renderer->transform(rendererTransform); + c->m_InverseRendererTransform = rendererTransform.invertOrIdentity(); } + else + { + if (fit == rive::Fit::layout) + { + artboard->width(width / display_factor); + artboard->height(height / display_factor); + } - rive::Mat2D rendererTransform = rive::computeAlignment(rive_fit, rive_align, rive::AABB(0, 0, width, height), bounds, g_DisplayFactor); - renderer->transform(rendererTransform); - c->m_InverseRendererTransform = rendererTransform.invertOrIdentity(); - } + rive::Mat2D rendererTransform = rive::computeAlignment(fit, alignment, rive::AABB(0, 0, width, height), bounds, display_factor); + renderer->transform(rendererTransform); + c->m_InverseRendererTransform = rendererTransform.invertOrIdentity(); + } - if (c->m_StateMachineInstance) { - c->m_StateMachineInstance->draw(renderer); - } else if (c->m_AnimationInstance) { - c->m_AnimationInstance->draw(renderer); - } else { - c->m_ArtboardInstance->draw(renderer); - } + artboard->draw(renderer); + renderer->restore(); + }; - renderer->restore(); + queue->draw(c->m_DrawKey, drawLoop); } } @@ -633,142 +677,12 @@ namespace dmRive component->m_AnimationIndex = 0xff; component->m_AnimationPlaybackRate = 1.0f; component->m_AnimationPlayback = dmGameObject::PLAYBACK_NONE; - - component->m_AnimationInstance.reset(); - component->m_StateMachineInstance.reset(); - component->m_StateMachineInputs.SetSize(0); - } - - static void CompRiveAnimationDoneCallback(RiveComponent* component) - { - assert(component->m_AnimationInstance); - - dmMessage::URL sender; - dmMessage::URL receiver = component->m_Listener; - if (!GetSender(component, &sender)) - { - dmLogError("Could not send animation_done to listener because of incomplete component."); - return; - } - - dmRive::RiveSceneData* data = (dmRive::RiveSceneData*) component->m_Resource->m_Scene->m_Scene; - - RiveArtboardIdList* id_list = FindArtboardIdList(component->m_ArtboardInstance.get(), data); - - dmRiveDDF::RiveAnimationDone message; - message.m_AnimationId = id_list->m_LinearAnimations[component->m_AnimationIndex]; - message.m_Playback = component->m_AnimationPlayback; - - if (component->m_Callback) - { - uint32_t id = component->m_CallbackId; - CompRiveRunCallback(component, dmRiveDDF::RiveAnimationDone::m_DDFDescriptor, (const char*)&message, &sender); - - // Make sure we're clearing the same callback as we ran above and not a new - // callback that was started from the original callback - if (id == component->m_CallbackId) - { - CompRiveClearCallback(component); - } - } - else - { - dmGameObject::Result result = dmGameObject::PostDDF(&message, &sender, &receiver, 0, true); - if (result != dmGameObject::RESULT_OK) - { - dmLogError("Could not send animation_done to listener: %d", result); - } - } - } - - static bool CompRiveHandleEventTrigger(RiveComponent* component, dmRiveDDF::RiveEventTrigger message) - { - dmMessage::URL sender; - dmMessage::URL receiver = component->m_Listener; - if (!GetSender(component, &sender)) - { - dmLogError("Could not send event_trigger to listener because of incomplete component."); - return false; - } - - if (component->m_Callback) - { - dmScript::LuaCallbackInfo* callback = component->m_Callback; - CompRiveRunCallback(component, dmRiveDDF::RiveEventTrigger::m_DDFDescriptor, (const char*)&message, &sender); - - // note that we are not clearing the callback here since multiple events can fire at - // different times during the playback - } - else - { - dmGameObject::Result result = dmGameObject::PostDDF(&message, &sender, &receiver, 0, true); - if (result != dmGameObject::RESULT_OK) - { - dmLogError("Could not send event_trigger to listener: %d", result); - return false; - } - } - return true; - } - - static void CompRiveEventTriggerCallback(RiveComponent* component, rive::Event* event) - { - dmRiveDDF::RiveEventTrigger event_message; - event_message.m_Name = event->name().c_str(); - event_message.m_Trigger = 0; - event_message.m_Text = ""; - event_message.m_Number = 0.0f; - if (!CompRiveHandleEventTrigger(component, event_message)) - { - return; - } - - // trigger event once per event property - for (auto child : event->children()) - { - if (child->is()) - { - if (!child->name().empty()) - { - dmRiveDDF::RiveEventTrigger property_message; - property_message.m_Name = child->name().c_str(); - property_message.m_Trigger = 0; - property_message.m_Text = ""; - property_message.m_Number = 0.0f; - switch (child->coreType()) - { - case rive::CustomPropertyBoolean::typeKey: - { - bool b = child->as()->propertyValue(); - property_message.m_Trigger = b; - break; - } - case rive::CustomPropertyString::typeKey: - { - const char* s = child->as()->propertyValue().c_str(); - property_message.m_Text = s; - break; - } - case rive::CustomPropertyNumber::typeKey: - { - float f = child->as()->propertyValue(); - property_message.m_Number = f; - break; - } - } - if (!CompRiveHandleEventTrigger(component, property_message)) - { - return; - } - } - } - } } dmGameObject::UpdateResult CompRiveUpdate(const dmGameObject::ComponentsUpdateParams& params, dmGameObject::ComponentsUpdateResult& update_result) { DM_PROFILE("RiveModel"); - RiveWorld* world = (RiveWorld*)params.m_World; + RiveWorld* world = (RiveWorld*)params.m_World; float dt = params.m_UpdateContext->m_DT; @@ -776,6 +690,8 @@ namespace dmRive const uint32_t count = components.Size(); DM_PROPERTY_ADD_U32(rmtp_RiveComponents, count); + rive::rcp queue = dmRiveCommands::GetCommandQueue(); + for (uint32_t i = 0; i < count; ++i) { RiveComponent& component = *components[i]; @@ -786,64 +702,10 @@ namespace dmRive continue; } - // RIVE UPDATE - dmRive::RiveSceneData* data = (dmRive::RiveSceneData*) component.m_Resource->m_Scene->m_Scene; - rive::File* f = data->m_File; - rive::Artboard* artboard = f->artboard(); - - if (!artboard) - { - component.m_Enabled = false; - continue; - } - rive::AABB artboard_bounds = artboard->bounds(); - - if (component.m_StateMachineInstance) - { - size_t event_count = component.m_StateMachineInstance->reportedEventCount(); - for (size_t i = 0; i < event_count; i++) - { - rive::EventReport reported_event = component.m_StateMachineInstance->reportedEventAt(i); - rive::Event* event = reported_event.event(); - CompRiveEventTriggerCallback(&component, event); - } - - component.m_StateMachineInstance->advanceAndApply(dt * component.m_AnimationPlaybackRate); - } - else if (component.m_AnimationInstance) - { - component.m_AnimationInstance->advanceAndApply(dt * component.m_AnimationPlaybackRate); - - if (component.m_AnimationInstance->didLoop()) - { - bool did_finish = false; - switch(component.m_AnimationPlayback) - { - case dmGameObject::PLAYBACK_ONCE_FORWARD: - did_finish = true; - break; - case dmGameObject::PLAYBACK_ONCE_BACKWARD: - did_finish = true; - break; - case dmGameObject::PLAYBACK_ONCE_PINGPONG: - did_finish = component.m_AnimationInstance->direction() > 0; - break; - default:break; - } - - if (did_finish) - { - CompRiveAnimationDoneCallback(&component); - CompRiveAnimationReset(&component); - } - } - } - else { - component.m_ArtboardInstance->advance(dt * component.m_AnimationPlaybackRate); - } + queue->advanceStateMachine(component.m_StateMachine, dt * component.m_AnimationPlaybackRate); - if (component.m_Resource->m_CreateGoBones) - UpdateBones(&component); // after the artboard->advance(); + // if (component.m_Resource->m_CreateGoBones) + // UpdateBones(&component); // after the artboard->advance(); if (component.m_ReHash || (component.m_RenderConstants && dmGameSystem::AreRenderConstantsUpdated(component.m_RenderConstants))) { @@ -853,6 +715,8 @@ namespace dmRive component.m_DoRender = 1; } + dmRiveCommands::ProcessMessages(); // Update the command server + // If the child bones have been updated, we need to return true update_result.m_TransformsUpdated = false; @@ -964,156 +828,6 @@ namespace dmRive return -1; } - static rive::LinearAnimation* FindAnimation(rive::Artboard* artboard, dmRive::RiveSceneData* data, int* animation_index, dmhash_t anim_id) - { - RiveArtboardIdList* id_list = FindArtboardIdList(artboard, data); - if (!id_list) - { - return 0; - } - - int index = FindAnimationIndex(id_list->m_LinearAnimations.Begin(), id_list->m_LinearAnimations.Size(), anim_id); - if (index == -1) { - return 0; - } - *animation_index = index; - return artboard->animation(index); - } - - bool CompRivePlayAnimation(RiveComponent* component, dmRiveDDF::RivePlayAnimation* ddf, dmScript::LuaCallbackInfo* callback_info) - { - dmRive::RiveSceneData* data = (dmRive::RiveSceneData*) component->m_Resource->m_Scene->m_Scene; - dmhash_t anim_id = ddf->m_AnimationId; - dmGameObject::Playback playback_mode = (dmGameObject::Playback)ddf->m_Playback; - float offset = ddf->m_Offset; - float playback_rate = ddf->m_PlaybackRate; - - if (playback_mode == dmGameObject::PLAYBACK_NONE) - { - return true; - } - - int animation_index; - rive::LinearAnimation* animation = 0; - if (anim_id != 0) - { - animation = FindAnimation(component->m_ArtboardInstance.get(), data, &animation_index, anim_id); - - if (!animation) { - dmLogError("Failed to find animation '%s'", dmHashReverseSafe64(anim_id)); - return false; - } - } - else - { - animation_index = 0; - animation = component->m_ArtboardInstance->animation(animation_index); // Default animation - } - - CompRiveAnimationReset(component); - CompRiveClearCallback(component); - - rive::Loop loop_value = rive::Loop::oneShot; - int play_direction = 1; - float play_time = animation->startSeconds(); - float offset_value = animation->durationSeconds() * offset; - - switch(playback_mode) - { - case dmGameObject::PLAYBACK_ONCE_FORWARD: - loop_value = rive::Loop::oneShot; - break; - case dmGameObject::PLAYBACK_ONCE_BACKWARD: - loop_value = rive::Loop::oneShot; - play_direction = -1; - play_time = animation->endSeconds(); - offset_value = -offset_value; - break; - case dmGameObject::PLAYBACK_ONCE_PINGPONG: - loop_value = rive::Loop::pingPong; - break; - case dmGameObject::PLAYBACK_LOOP_FORWARD: - loop_value = rive::Loop::loop; - break; - case dmGameObject::PLAYBACK_LOOP_BACKWARD: - loop_value = rive::Loop::loop; - play_direction = -1; - play_time = animation->endSeconds(); - offset_value = -offset_value; - break; - case dmGameObject::PLAYBACK_LOOP_PINGPONG: - loop_value = rive::Loop::pingPong; - break; - default:break; - } - - component->m_Callback = callback_info; - component->m_CallbackId++; - component->m_AnimationIndex = animation_index; - component->m_AnimationPlaybackRate = playback_rate; - component->m_AnimationPlayback = playback_mode; - component->m_StateMachineInstance = nullptr; - component->m_AnimationInstance = component->m_ArtboardInstance->animationAt(animation_index); - component->m_AnimationInstance->inputCount(); - component->m_AnimationInstance->time(play_time + offset_value); - component->m_AnimationInstance->loopValue((int)loop_value); - component->m_AnimationInstance->direction(play_direction); - return true; - } - - bool CompRivePlayStateMachine(RiveComponent* component, dmRiveDDF::RivePlayAnimation* ddf, dmScript::LuaCallbackInfo* callback_info) - { - dmRive::RiveSceneData* data = (dmRive::RiveSceneData*) component->m_Resource->m_Scene->m_Scene; - dmhash_t anim_id = ddf->m_AnimationId; - float playback_rate = ddf->m_PlaybackRate; - - int default_state_machine_index = component->m_ArtboardInstance->defaultStateMachineIndex(); - int state_machine_index = -1; - if (anim_id != 0) - { - rive::StateMachine* state_machine = FindStateMachine(component->m_ArtboardInstance.get(), data, &state_machine_index, anim_id); - - if (!state_machine) { - dmLogError("Failed to play state machine with id '%s'", dmHashReverseSafe64(anim_id)); - return false; - } - } - else - { - state_machine_index = default_state_machine_index; - } - - CompRiveAnimationReset(component); - CompRiveClearCallback(component); - - // For now, we need to create a new state machine instance when playing a state machine, because of nested artboards+state machine events - InstantiateArtboard(component); - - component->m_CallbackId++; - component->m_Callback = callback_info; - component->m_AnimationInstance = nullptr; - component->m_AnimationPlaybackRate = playback_rate; - - component->m_StateMachineInstance = component->m_ArtboardInstance->stateMachineAt(state_machine_index); - - if (!component->m_StateMachineInstance.get()) - { - dmLogError("Failed to start state machine '%s' at index %d", dmHashReverseSafe64(anim_id), state_machine_index); - return false; - } - - if (component->m_CurrentViewModelInstanceRuntime != INVALID_HANDLE) - { - CompRiveSetViewModelInstanceRuntime(component, component->m_CurrentViewModelInstanceRuntime); - } - - // update the list of current state machine inputs - GetStateMachineInputNames(component->m_StateMachineInstance.get(), component->m_StateMachineInputs); - - component->m_StateMachineInstance->advanceAndApply(0); - return true; - } - dmGameObject::UpdateResult CompRiveOnMessage(const dmGameObject::ComponentOnMessageParams& params) { RiveWorld* world = (RiveWorld*)params.m_World; @@ -1126,34 +840,6 @@ namespace dmRive { component->m_Enabled = 0; } - else if (params.m_Message->m_Descriptor != 0x0) - { - if (params.m_Message->m_Id == dmRiveDDF::RivePlayAnimation::m_DDFDescriptor->m_NameHash) - { - dmRiveDDF::RivePlayAnimation* ddf = (dmRiveDDF::RivePlayAnimation*)params.m_Message->m_Data; - if (ddf->m_IsStateMachine) - { - bool result = CompRivePlayStateMachine(component, ddf, 0); - if (!result) - { - dmLogError("Couldn't play state machine named '%s'", dmHashReverseSafe64(ddf->m_AnimationId)); - } - } - else - { - bool result = CompRivePlayAnimation(component, ddf, 0); - if (!result) - { - dmLogError("Couldn't play animation named '%s'", dmHashReverseSafe64(ddf->m_AnimationId)); - } - } - } - else if (params.m_Message->m_Id == dmRiveDDF::RiveCancelAnimation::m_DDFDescriptor->m_NameHash) - { - CompRiveAnimationReset(component); - } - } - return dmGameObject::UPDATE_RESULT_OK; } @@ -1180,24 +866,14 @@ namespace dmRive RiveComponent* component = GetComponentFromIndex(world, *params.m_UserData); dmRive::RiveSceneData* data = (dmRive::RiveSceneData*) component->m_Resource->m_Scene->m_Scene; - RiveArtboardIdList* id_list = FindArtboardIdList(component->m_ArtboardInstance.get(), data); - - if (params.m_PropertyId == PROP_ANIMATION) + if (params.m_PropertyId == PROP_ARTBOARD) { - if (component->m_AnimationInstance && component->m_AnimationIndex < id_list->m_LinearAnimations.Size()) - { - out_value.m_Variant = dmGameObject::PropertyVar(id_list->m_LinearAnimations[component->m_AnimationIndex]); - } + out_value.m_Variant = dmGameObject::PropertyVar((dmhash_t)component->m_Artboard); return dmGameObject::PROPERTY_RESULT_OK; } - else if (params.m_PropertyId == PROP_CURSOR) + else if (params.m_PropertyId == PROP_STATE_MACHINE) { - if (component->m_AnimationInstance) - { - const rive::LinearAnimation* animation = component->m_AnimationInstance->animation(); - float cursor_value = (component->m_AnimationInstance->time() - animation->startSeconds()) / animation->durationSeconds(); - out_value.m_Variant = dmGameObject::PropertyVar(cursor_value); - } + out_value.m_Variant = dmGameObject::PropertyVar((dmhash_t)component->m_StateMachine); return dmGameObject::PROPERTY_RESULT_OK; } else if (params.m_PropertyId == PROP_PLAYBACK_RATE) @@ -1215,17 +891,6 @@ namespace dmRive RiveSceneData* resource = GetRiveResource(component, component->m_Resource); return dmGameSystem::GetResourceProperty(context->m_Factory, resource, out_value); } - else - { - if (component->m_StateMachineInstance) - { - int index = FindStateMachineInputIndex(component, params.m_PropertyId); - if (index >= 0) - { - return GetStateMachineInput(component, index, params, out_value); - } - } - } return dmGameSystem::GetMaterialConstant(GetMaterial(component, component->m_Resource), params.m_PropertyId, params.m_Options.m_Index, out_value, false, CompRiveGetConstantCallback, component); } @@ -1233,21 +898,9 @@ namespace dmRive { RiveWorld* world = (RiveWorld*)params.m_World; RiveComponent* component = world->m_Components.Get(*params.m_UserData); - if (params.m_PropertyId == PROP_CURSOR) - { - if (params.m_Value.m_Type != dmGameObject::PROPERTY_TYPE_NUMBER) - return dmGameObject::PROPERTY_RESULT_TYPE_MISMATCH; + rive::rcp queue = dmRiveCommands::GetCommandQueue(); - if (component->m_AnimationInstance) - { - const rive::LinearAnimation* animation = component->m_AnimationInstance->animation(); - float cursor = params.m_Value.m_Number * animation->durationSeconds() + animation->startSeconds(); - component->m_AnimationInstance->time(cursor); - } - - return dmGameObject::PROPERTY_RESULT_OK; - } - else if (params.m_PropertyId == PROP_PLAYBACK_RATE) + if (params.m_PropertyId == PROP_PLAYBACK_RATE) { if (params.m_Value.m_Type != dmGameObject::PROPERTY_TYPE_NUMBER) return dmGameObject::PROPERTY_RESULT_TYPE_MISMATCH; @@ -1261,15 +914,6 @@ namespace dmRive dmGameObject::PropertyResult res = dmGameSystem::SetResourceProperty(context->m_Factory, params.m_Value, MATERIAL_EXT_HASH, (void**)&component->m_Material); component->m_ReHash |= res == dmGameObject::PROPERTY_RESULT_OK; return res; - } else { - if (component->m_StateMachineInstance) - { - int index = FindStateMachineInputIndex(component, params.m_PropertyId); - if (index >= 0) - { - return SetStateMachineInput(component, index, params); - } - } } return dmGameSystem::SetMaterialConstant(GetMaterial(component, component->m_Resource), params.m_PropertyId, params.m_Value, params.m_Options.m_Index, CompRiveSetConstantCallback, component); } @@ -1299,6 +943,9 @@ namespace dmRive static dmGameObject::Result ComponentTypeCreate(const dmGameObject::ComponentTypeCreateCtx* ctx, dmGameObject::ComponentType* type) { CompRiveContext* rivectx = new CompRiveContext; + rivectx->m_RiveRenderContext = dmRiveCommands::GetDefoldRenderContext(); + assert(rivectx->m_RiveRenderContext != 0); + rivectx->m_Factory = ctx->m_Factory; rivectx->m_GraphicsContext = *(dmGraphics::HContext*)ctx->m_Contexts.Get(dmHashString64("graphics")); rivectx->m_RenderContext = *(dmRender::HRenderContext*)ctx->m_Contexts.Get(dmHashString64("render")); @@ -1336,6 +983,7 @@ namespace dmRive ComponentTypeSetDestroyFn(type, CompRiveDestroy); ComponentTypeSetAddToUpdateFn(type, CompRiveAddToUpdate); ComponentTypeSetUpdateFn(type, CompRiveUpdate); + // ComponentTypeSetLateUpdateFn(type, CompRiveLateUpdate); ComponentTypeSetRenderFn(type, CompRiveRender); ComponentTypeSetOnMessageFn(type, CompRiveOnMessage); // ComponentTypeSetOnInputFn(type, CompRiveOnInput); @@ -1355,142 +1003,147 @@ namespace dmRive return dmGameObject::RESULT_OK; } - static void DeleteBones(RiveComponent* component) - { - dmGameObject::HInstance rive_instance = component->m_Instance; - dmGameObject::HCollection collection = dmGameObject::GetCollection(rive_instance); + // static void DeleteBones(RiveComponent* component) + // { + // dmLogOnceError("MAWE Missing implementation; %s", __FUNCTION__); - uint32_t num_bones = component->m_BoneGOs.Size(); - for (uint32_t i = 0; i < num_bones; ++i) - { - dmGameObject::HInstance bone_instance = component->m_BoneGOs[i]; - if (bone_instance) - { - dmGameObject::Delete(collection, bone_instance, false); - } - } - component->m_BoneGOs.SetSize(0); - } + // // dmGameObject::HInstance rive_instance = component->m_Instance; + // // dmGameObject::HCollection collection = dmGameObject::GetCollection(rive_instance); - static void UpdateBones(RiveComponent* component) - { - rive::Artboard* artboard = component->m_ArtboardInstance.get(); + // // uint32_t num_bones = component->m_BoneGOs.Size(); + // // for (uint32_t i = 0; i < num_bones; ++i) + // // { + // // dmGameObject::HInstance bone_instance = component->m_BoneGOs[i]; + // // if (bone_instance) + // // { + // // dmGameObject::Delete(collection, bone_instance, false); + // // } + // // } + // // component->m_BoneGOs.SetSize(0); + // } - rive::AABB bounds = artboard->bounds(); - float cx = (bounds.maxX - bounds.minX) * 0.5f; - float cy = (bounds.maxY - bounds.minY) * 0.5f; + // static void UpdateBones(RiveComponent* component) + // { + // dmLogOnceError("MAWE Missing implementation; %s", __FUNCTION__); + // // rive::Artboard* artboard = component->m_Artboard.get(); - uint32_t num_bones = component->m_BoneGOs.Size(); - DM_PROPERTY_ADD_U32(rmtp_RiveBones, num_bones); + // // rive::AABB bounds = artboard->bounds(); + // // float cx = (bounds.maxX - bounds.minX) * 0.5f; + // // float cy = (bounds.maxY - bounds.minY) * 0.5f; - dmVMath::Point3 go_pos = dmGameObject::GetPosition(component->m_Instance); + // // uint32_t num_bones = component->m_BoneGOs.Size(); + // // DM_PROPERTY_ADD_U32(rmtp_RiveBones, num_bones); - for (uint32_t i = 0; i < num_bones; ++i) - { - dmGameObject::HInstance bone_instance = component->m_BoneGOs[i]; - rive::Bone* bone = component->m_Bones[i]; + // // dmVMath::Point3 go_pos = dmGameObject::GetPosition(component->m_Instance); - const rive::Mat2D& rt = bone->worldTransform(); + // // for (uint32_t i = 0; i < num_bones; ++i) + // // { + // // dmGameObject::HInstance bone_instance = component->m_BoneGOs[i]; + // // rive::Bone* bone = component->m_Bones[i]; - dmVMath::Vector4 x_axis(rt.xx(), rt.xy(), 0, 0); - dmVMath::Vector4 y_axis(rt.yx(), rt.yy(), 0, 0); + // // const rive::Mat2D& rt = bone->worldTransform(); - float scale_x = length(x_axis); - float scale_y = length(y_axis); - dmVMath::Vector3 scale(scale_x, scale_y, 1); + // // dmVMath::Vector4 x_axis(rt.xx(), rt.xy(), 0, 0); + // // dmVMath::Vector4 y_axis(rt.yx(), rt.yy(), 0, 0); - float angle = atan2f(x_axis.getY(), x_axis.getX()); - Quat rotation = Quat::rotationZ(-angle); + // // float scale_x = length(x_axis); + // // float scale_y = length(y_axis); + // // dmVMath::Vector3 scale(scale_x, scale_y, 1); - // Since the Rive space is different, we need to flip the y axis - dmVMath::Vector3 pos(rt.tx() - cx, -rt.ty() + cy, 0); + // // float angle = atan2f(x_axis.getY(), x_axis.getX()); + // // Quat rotation = Quat::rotationZ(-angle); - dmVMath::Matrix4 world_transform(rotation, pos); + // // // Since the Rive space is different, we need to flip the y axis + // // dmVMath::Vector3 pos(rt.tx() - cx, -rt.ty() + cy, 0); - dmTransform::Transform transform = dmTransform::ToTransform(world_transform); + // // dmVMath::Matrix4 world_transform(rotation, pos); - dmGameObject::SetPosition(bone_instance, Point3(transform.GetTranslation())); - dmGameObject::SetRotation(bone_instance, transform.GetRotation()); - dmGameObject::SetScale(bone_instance, transform.GetScale()); - } - } + // // dmTransform::Transform transform = dmTransform::ToTransform(world_transform); - static bool CreateBones(RiveWorld* world, RiveComponent* component) - { - dmGameObject::HInstance rive_instance = component->m_Instance; - dmGameObject::HCollection collection = dmGameObject::GetCollection(rive_instance); + // // dmGameObject::SetPosition(bone_instance, Point3(transform.GetTranslation())); + // // dmGameObject::SetRotation(bone_instance, transform.GetRotation()); + // // dmGameObject::SetScale(bone_instance, transform.GetScale()); + // // } + // } - uint32_t num_bones = component->m_Bones.Size(); + // static bool CreateBones(RiveWorld* world, RiveComponent* component) + // { + // dmLogOnceError("MAWE Missing implementation; %s", __FUNCTION__); - component->m_BoneGOs.SetCapacity(num_bones); - component->m_BoneGOs.SetSize(num_bones); + // // dmGameObject::HInstance rive_instance = component->m_Instance; + // // dmGameObject::HCollection collection = dmGameObject::GetCollection(rive_instance); - for (uint32_t i = 0; i < num_bones; ++i) - { - dmGameObject::HInstance bone_instance = dmGameObject::New(collection, 0x0); - if (bone_instance == 0x0) { - DeleteBones(component); - return false; - } + // // uint32_t num_bones = component->m_Bones.Size(); - component->m_BoneGOs[i] = bone_instance; + // // component->m_BoneGOs.SetCapacity(num_bones); + // // component->m_BoneGOs.SetSize(num_bones); - uint32_t index = dmGameObject::AcquireInstanceIndex(collection); - if (index == dmGameObject::INVALID_INSTANCE_POOL_INDEX) - { - DeleteBones(component); - return false; - } + // // for (uint32_t i = 0; i < num_bones; ++i) + // // { + // // dmGameObject::HInstance bone_instance = dmGameObject::New(collection, 0x0); + // // if (bone_instance == 0x0) { + // // DeleteBones(component); + // // return false; + // // } - dmhash_t id = dmGameObject::CreateInstanceId(); - dmGameObject::AssignInstanceIndex(index, bone_instance); + // // component->m_BoneGOs[i] = bone_instance; - dmGameObject::Result result = dmGameObject::SetIdentifier(collection, bone_instance, id); - if (dmGameObject::RESULT_OK != result) - { - DeleteBones(component); - return false; - } + // // uint32_t index = dmGameObject::AcquireInstanceIndex(collection); + // // if (index == dmGameObject::INVALID_INSTANCE_POOL_INDEX) + // // { + // // DeleteBones(component); + // // return false; + // // } - dmGameObject::SetBone(bone_instance, true); + // // dmhash_t id = dmGameObject::CreateInstanceId(); + // // dmGameObject::AssignInstanceIndex(index, bone_instance); - // Since we're given the "world" coordinates from the rive bones, - // we don't really need a full hierarchy. So we use the actual game object as parent - dmGameObject::SetParent(bone_instance, rive_instance); - } + // // dmGameObject::Result result = dmGameObject::SetIdentifier(collection, bone_instance, id); + // // if (dmGameObject::RESULT_OK != result) + // // { + // // DeleteBones(component); + // // return false; + // // } - return true; - } + // // dmGameObject::SetBone(bone_instance, true); + + // // // Since we're given the "world" coordinates from the rive bones, + // // // we don't really need a full hierarchy. So we use the actual game object as parent + // // dmGameObject::SetParent(bone_instance, rive_instance); + // // } + + // return true; + // } // ****************************************************************************** // SCRIPTING HELPER FUNCTIONS // ****************************************************************************** - bool CompRiveGetBoneID(RiveComponent* component, dmhash_t bone_name, dmhash_t* id) - { - uint32_t num_bones = component->m_Bones.Size(); + // bool CompRiveGetBoneID(RiveComponent* component, dmhash_t bone_name, dmhash_t* id) + // { + // uint32_t num_bones = component->m_Bones.Size(); - // We need the arrays to be matching 1:1 (for lookup using the same indices) - if (num_bones == 0 || component->m_BoneGOs.Size() != num_bones) { - return false; - } + // // We need the arrays to be matching 1:1 (for lookup using the same indices) + // if (num_bones == 0 || component->m_BoneGOs.Size() != num_bones) { + // return false; + // } - for (uint32_t i = 0; i < num_bones; ++i) - { - rive::Bone* bone = component->m_Bones[i]; + // for (uint32_t i = 0; i < num_bones; ++i) + // { + // rive::Bone* bone = component->m_Bones[i]; - // Getting bones by name is rare, so I think it is ok to do the hash now, as opposed to have an array in each of the components. - dmhash_t name_hash = dmHashString64(bone->name().c_str()); - if (bone_name == name_hash) - { - dmGameObject::HInstance bone_instance = component->m_BoneGOs[i]; - *id = dmGameObject::GetIdentifier(bone_instance); - return true; - } - } + // // Getting bones by name is rare, so I think it is ok to do the hash now, as opposed to have an array in each of the components. + // dmhash_t name_hash = dmHashString64(bone->name().c_str()); + // if (bone_name == name_hash) + // { + // dmGameObject::HInstance bone_instance = component->m_BoneGOs[i]; + // *id = dmGameObject::GetIdentifier(bone_instance); + // return true; + // } + // } - return false; - } + // return false; + // } float CompRiveGetDisplayScaleFactor() { @@ -1509,47 +1162,41 @@ namespace dmRive float normalized_y = 1 - (y / g_OriginalWindowHeight); rive::Vec2D p_local = component->m_InverseRendererTransform * rive::Vec2D(normalized_x * window_width, normalized_y * window_height); + //rive::Vec2D p_local = rive::Vec2D(normalized_x * window_width, normalized_y * window_height); return p_local; } - static inline rive::TextValueRun* GetTextRun(rive::ArtboardInstance* artboard, const char* name, const char* nested_artboard_path) + static void FillPointerEvent(RiveComponent* component, rive::CommandQueue::PointerEvent& event, rive::Vec2D& pos) { - if (nested_artboard_path) - { - auto nested = artboard->nestedArtboardAtPath(nested_artboard_path); - auto nested_instance = nested ? nested->artboardInstance() : 0; + dmGraphics::HContext graphics_context = dmGraphics::GetInstalledContext(); + float window_width = (float) dmGraphics::GetWindowWidth(graphics_context); + float window_height = (float) dmGraphics::GetWindowHeight(graphics_context); - if (nested_instance) - { - return nested_instance->find(name); - } - } - else - { - return artboard->find(name); - } - return 0; - } + event.fit = component->m_Fit; + event.alignment = component->m_Alignment; + event.screenBounds.x = window_width; + event.screenBounds.y = window_height; + event.position = pos; + event.scaleFactor = CompRiveGetDisplayScaleFactor(); - bool CompRiveSetTextRun(RiveComponent* component, const char* name, const char* text_run, const char* nested_artboard_path) - { - rive::TextValueRun* text_run_value = GetTextRun(component->m_ArtboardInstance.get(), name, nested_artboard_path); - if (!text_run_value) - { - return false; - } - text_run_value->text(text_run); - return true; + //printf(" FillEvent: w/h: %f, %f fit: %d align: %f,%f\n", window_width, window_height, (int)event.fit, event.alignment.x(), event.alignment.y()); } - const char* CompRiveGetTextRun(RiveComponent* component, const char* name, const char* nested_artboard_path) + void CompRivePointerAction(RiveComponent* component, dmRive::PointerAction action, float x, float y) { - rive::TextValueRun* text_run_value = GetTextRun(component->m_ArtboardInstance.get(), name, nested_artboard_path); - if (!text_run_value) + + rive::rcp queue = dmRiveCommands::GetCommandQueue(); + rive::Vec2D p = WorldToLocal(component, x, y); + rive::CommandQueue::PointerEvent event; + FillPointerEvent(component, event, p); + + switch(action) { - return 0; + case dmRive::PointerAction::POINTER_MOVE: queue->pointerMove(component->m_StateMachine, event); break; + case dmRive::PointerAction::POINTER_UP: queue->pointerUp(component->m_StateMachine, event); break; + case dmRive::PointerAction::POINTER_DOWN: queue->pointerDown(component->m_StateMachine, event); break; + case dmRive::PointerAction::POINTER_EXIT: queue->pointerExit(component->m_StateMachine, event); break; } - return text_run_value->text().c_str(); } void CompRiveDebugSetBlitMode(bool value) diff --git a/defold-rive/src/comp_rive.h b/defold-rive/src/comp_rive.h index 813a805c..be14ef9e 100644 --- a/defold-rive/src/comp_rive.h +++ b/defold-rive/src/comp_rive.h @@ -23,6 +23,8 @@ #include "rive_ddf.h" +#include // handles + namespace dmRive { ///////////////////////////////////////////////////////////////////////////////////// @@ -61,25 +63,31 @@ namespace dmRive // Get the game object identifier bool CompRiveGetBoneID(RiveComponent* component, dmhash_t bone_name, dmhash_t* id); - bool CompRivePlayStateMachine(RiveComponent* component, dmRiveDDF::RivePlayAnimation* ddf, dmScript::LuaCallbackInfo* callback_info); - bool CompRivePlayAnimation(RiveComponent* component, dmRiveDDF::RivePlayAnimation* ddf, dmScript::LuaCallbackInfo* callback_info); - const char* CompRiveGetTextRun(RiveComponent* component, const char* name, const char* nested_artboard_path); bool CompRiveSetTextRun(RiveComponent* component, const char* name, const char* text_run, const char* nested_artboard_path); float CompRiveGetDisplayScaleFactor(); void CompRiveDebugSetBlitMode(bool value); - // state machine impl - StateMachineInputData::Result CompRiveGetStateMachineInput(RiveComponent* component, const char* input_name, const char* nested_artboard_path, StateMachineInputData& data); - StateMachineInputData::Result CompRiveSetStateMachineInput(RiveComponent* component, const char* input_name, const char* nested_artboard_path, const StateMachineInputData& data); - void CompRivePointerMove(RiveComponent* component, float x, float y); - void CompRivePointerUp(RiveComponent* component, float x, float y); - void CompRivePointerDown(RiveComponent* component, float x, float y); + // Scripting + rive::FileHandle CompRiveGetFile(RiveComponent* component); + rive::ArtboardHandle CompRiveSetArtboard(RiveComponent* component, const char* name); + rive::ArtboardHandle CompRiveGetArtboard(RiveComponent* component); + rive::StateMachineHandle CompRiveSetStateMachine(RiveComponent* component, const char* name); + rive::StateMachineHandle CompRiveGetStateMachine(RiveComponent* component); + + rive::ViewModelInstanceHandle CompRiveSetViewModelInstance(RiveComponent* component, const char* name); + rive::ViewModelInstanceHandle CompRiveGetViewModelInstance(RiveComponent* component); + + enum PointerAction + { + POINTER_MOVE, + POINTER_DOWN, + POINTER_UP, + POINTER_EXIT, + }; - // bool CompRiveSetIKTargetInstance(RiveComponent* component, dmhash_t constraint_id, float mix, dmhash_t instance_id); - // bool CompRiveSetIKTargetPosition(RiveComponent* component, dmhash_t constraint_id, float mix, Vectormath::Aos::Point3 position); - // bool CompRiveResetIKTarget(RiveComponent* component, dmhash_t constraint_id); + void CompRivePointerAction(RiveComponent* component, PointerAction cmd, float x, float y); } #endif // DM_GAMESYS_COMP_RIVE_H diff --git a/defold-rive/src/comp_rive_databinding.cpp b/defold-rive/src/comp_rive_databinding.cpp deleted file mode 100644 index 1b097f64..00000000 --- a/defold-rive/src/comp_rive_databinding.cpp +++ /dev/null @@ -1,405 +0,0 @@ -// Copyright 2020 The Defold Foundation -// Licensed under the Defold License version 1.0 (the "License"); you may not use -// this file except in compliance with the License. -// -// You may obtain a copy of the License, together with FAQs at -// https://www.defold.com/license -// -// Unless required by applicable law or agreed to in writing, software distributed -// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -// CONDITIONS OF ANY KIND, either express or implied. See the License for the -// specific language governing permissions and limitations under the License. - -#if !defined(DM_RIVE_UNSUPPORTED) - -#include - -#include "comp_rive.h" -#include "comp_rive_private.h" -#include "res_rive_data.h" -#include "res_rive_scene.h" -#include "res_rive_model.h" - -#include -#include -#include -#include -#include -#include - -//debug -#include -#include - -namespace dmRive -{ - -#define CHECK_VMIR(VMIR, HANDLE) \ - if (!(VMIR)) { \ - dmLogError("%s:%d: No viewmodel runtime instance with handle '%u'", __FUNCTION__, __LINE__, (HANDLE)); \ - return false; \ - } - -#define CHECK_PROP_RESULT(PROP, TYPE, PATH) \ - if (!(PROP)) { \ - dmLogError("%s:%d: No property of type '%s', with path '%s'", __FUNCTION__, __LINE__, (TYPE), (PATH)); \ - return false; \ - } - -static rive::ViewModelInstanceRuntime* FromHandle(RiveComponent* component, uint32_t handle) -{ - rive::ViewModelInstanceRuntime** pvmir = component->m_ViewModelInstanceRuntimes.Get(handle); - return pvmir ? *pvmir : 0; -} - -static rive::ViewModelRuntime* FindViewModelRuntimeByHash(RiveComponent* component, dmhash_t name_hash) -{ - dmRive::RiveSceneData* data = (dmRive::RiveSceneData*) component->m_Resource->m_Scene->m_Scene; - rive::File* file = data->m_File; - - size_t n = file->viewModelCount(); - for (size_t i = 0; i < n; ++i) - { - rive::ViewModelRuntime* vmr = file->viewModelByIndex(i); - dmhash_t hash = dmHashString64(vmr->name().c_str()); - if (hash == name_hash) - return vmr; - } - return 0; -} - -static rive::ViewModelInstanceRuntime* CreateViewModelInstanceRuntimeByHash(RiveComponent* component, dmhash_t name_hash) -{ - dmRive::RiveSceneData* data = component->m_Resource->m_Scene->m_Scene; - rive::File* file = data->m_File; - - if (name_hash != 0) - { - rive::ViewModelRuntime* vmr = FindViewModelRuntimeByHash(component, name_hash); - return vmr ? vmr->createInstance() : 0; - } - - // Create a default view model instance - if (!component->m_ArtboardInstance) - return 0; - - rive::ViewModelRuntime* vmr = file->defaultArtboardViewModel(component->m_ArtboardInstance.get()); - if (vmr) - { - return vmr->createDefaultInstance(); - } - return 0; -} - -void SetViewModelInstanceRuntime(RiveComponent* component, rive::ViewModelInstanceRuntime* vmir) -{ - if (component->m_ArtboardInstance) - { - component->m_ArtboardInstance->bindViewModelInstance(vmir->instance()); - } - - if (component->m_StateMachineInstance) - { - component->m_StateMachineInstance->bindViewModelInstance(vmir->instance()); - } -} - -void DebugModelViews(RiveComponent* component) -{ - dmRive::RiveSceneData* data = (dmRive::RiveSceneData*) component->m_Resource->m_Scene->m_Scene; - - size_t num_viewmodels = data->m_File->viewModelCount(); - for (size_t i = 0; i < num_viewmodels; ++i) - { - rive::ViewModelRuntime* vmr = data->m_File->viewModelByIndex(i); - - dmLogInfo("NAME: '%s'\n", vmr->name().c_str()); - - size_t num_properties = vmr->propertyCount(); - std::vector pdatas = vmr->properties(); - for (size_t j = 0; j < num_properties; ++j) - { - rive::PropertyData& property = pdatas[j]; - dmLogInfo(" DATA: %d '%s'\n", (int)property.type, property.name.c_str()); - } - - size_t num_instances = vmr->instanceCount(); - dmLogInfo(" #instances: %u\n", (uint32_t)num_instances); - std::vector names = vmr->instanceNames(); - for (size_t j = 0; j < names.size(); ++j) - { - dmLogInfo(" INST: '%s'\n", names[j].c_str()); - } - } -} - -void DebugVMIR(rive::ViewModelInstanceRuntime* vmir) -{ - printf("NAME: '%s'\n", vmir->name().c_str()); - - size_t num_properties = vmir->propertyCount(); - std::vector pdatas = vmir->properties(); - for (size_t j = 0; j < num_properties; ++j) - { - rive::PropertyData& property = pdatas[j]; - printf(" DATA: %d '%s'\n", (int)property.type, property.name.c_str()); - } - - printf(" instance: '%s' %p\n", vmir->instance()->name().c_str(), vmir->instance().get()); -} - -// Scripting api + helpers - -bool CompRiveSetViewModelInstanceRuntime(RiveComponent* component, uint32_t handle) -{ - dmLogInfo("Setting ViewModelInstanceRuntime"); - rive::ViewModelInstanceRuntime* vmir = FromHandle(component, handle); - CHECK_VMIR(vmir, handle); - - dmRive::SetViewModelInstanceRuntime(component, vmir); - component->m_CurrentViewModelInstanceRuntime = handle; - return true; -} - -uint32_t CompRiveGetViewModelInstanceRuntime(RiveComponent* component) -{ - return component->m_CurrentViewModelInstanceRuntime; -} - -uint32_t CompRiveCreateViewModelInstanceRuntime(RiveComponent* component, dmhash_t name_hash) -{ - uint32_t handle = dmRive::INVALID_HANDLE; - rive::ViewModelInstanceRuntime* vmir = dmRive::CreateViewModelInstanceRuntimeByHash(component, name_hash); - if (vmir) - { - handle = component->m_HandleCounter++; - - if (component->m_ViewModelInstanceRuntimes.Full()) - component->m_ViewModelInstanceRuntimes.OffsetCapacity(4); - component->m_ViewModelInstanceRuntimes.Put(handle, vmir); - } - else - { - dmLogError("Failed to create ViewModelInstance of name '%s'", dmHashReverseSafe64(name_hash)); - } - - //dmRive::DebugModelViews(component); - return handle; -} - -bool CompRiveDestroyViewModelInstanceRuntime(RiveComponent* component, uint32_t handle) -{ - rive::ViewModelInstanceRuntime* vmir = FromHandle(component, handle); - CHECK_VMIR(vmir, handle); - - // According to the Rive team, there is no need to free the pointer, as it belongs to runtime - component->m_ViewModelInstanceRuntimes.Erase(handle); - return true; -} - -// ************************************************************************************************************** -// PROPERTIES - -static rive::DataType GetDataType(rive::ViewModelInstanceRuntime* vmir, const char* path) -{ - rive::ViewModelInstanceValueRuntime* prop = vmir->property(path); - if (prop) - return prop->dataType(); - return rive::DataType::none; -}; - -bool GetPropertyDataType(RiveComponent* component, uint32_t handle, const char* path, rive::DataType* type) -{ - rive::ViewModelInstanceRuntime* vmir = FromHandle(component, handle); - if (!vmir) - { - return false; - } - - *type = GetDataType(vmir, path); - return *type != rive::DataType::none; -} - -bool CompRiveRuntimeSetPropertyBool(RiveComponent* component, uint32_t handle, const char* path, bool value) -{ - rive::ViewModelInstanceRuntime* vmir = FromHandle(component, handle); - CHECK_VMIR(vmir, handle); - - rive::ViewModelInstanceBooleanRuntime* prop = vmir->propertyBoolean(path); - CHECK_PROP_RESULT(prop, "boolean", path); - prop->value(value); - return true; -} - -bool CompRiveRuntimeSetPropertyF32(RiveComponent* component, uint32_t handle, const char* path, float value) -{ - rive::ViewModelInstanceRuntime* vmir = FromHandle(component, handle); - CHECK_VMIR(vmir, handle); - - rive::ViewModelInstanceNumberRuntime* prop = vmir->propertyNumber(path); - CHECK_PROP_RESULT(prop, "number", path); - if (!prop) - { - dmLogError("No property of type number, with path '%s'", path); - return false; - } - - prop->value(value); - return true; -} - -bool CompRiveRuntimeSetPropertyColor(RiveComponent* component, uint32_t handle, const char* path, dmVMath::Vector4* color) -{ - rive::ViewModelInstanceRuntime* vmir = FromHandle(component, handle); - CHECK_VMIR(vmir, handle); - - rive::ViewModelInstanceColorRuntime* prop = vmir->propertyColor(path); - CHECK_PROP_RESULT(prop, "color", path); - - prop->argb(255 * color->getW(), 255 * color->getX(), 255 * color->getY(), 255 * color->getZ()); - return true; -} - -bool CompRiveRuntimeSetPropertyString(RiveComponent* component, uint32_t handle, const char* path, const char* value) -{ - rive::ViewModelInstanceRuntime* vmir = FromHandle(component, handle); - CHECK_VMIR(vmir, handle); - - rive::ViewModelInstanceStringRuntime* prop = vmir->propertyString(path); - CHECK_PROP_RESULT(prop, "string", path); - - prop->value(value); - return true; -} - -bool CompRiveRuntimeSetPropertyEnum(RiveComponent* component, uint32_t handle, const char* path, const char* value) -{ - rive::ViewModelInstanceRuntime* vmir = FromHandle(component, handle); - CHECK_VMIR(vmir, handle); - - rive::ViewModelInstanceEnumRuntime* prop = vmir->propertyEnum(path); - CHECK_PROP_RESULT(prop, "enum", path); - - prop->value(value); - return true; -} - -bool CompRiveRuntimeSetPropertyTrigger(RiveComponent* component, uint32_t handle, const char* path) -{ - rive::ViewModelInstanceRuntime* vmir = FromHandle(component, handle); - CHECK_VMIR(vmir, handle); - - rive::ViewModelInstanceTriggerRuntime* prop = vmir->propertyTrigger(path); - CHECK_PROP_RESULT(prop, "trigger", path); - - prop->trigger(); - return true; -} - -bool CompRiveRuntimeSetPropertyImage(RiveComponent* component, uint32_t handle, const char* path, rive::RenderImage* image) -{ - rive::ViewModelInstanceRuntime* vmir = FromHandle(component, handle); - CHECK_VMIR(vmir, handle); - - rive::ViewModelInstanceAssetImageRuntime* prop = vmir->propertyImage(path); - CHECK_PROP_RESULT(prop, "image", path); - - prop->value(image); - return true; -} - -bool CompRiveRuntimeGetPropertyBool(RiveComponent* component, uint32_t handle, const char* path, bool* value) -{ - rive::ViewModelInstanceRuntime* vmir = FromHandle(component, handle); - CHECK_VMIR(vmir, handle); - - rive::ViewModelInstanceBooleanRuntime* prop = vmir->propertyBoolean(path); - CHECK_PROP_RESULT(prop, "boolean", path); - *value = prop->value(); - return true; -} - -bool CompRiveRuntimeGetPropertyF32(RiveComponent* component, uint32_t handle, const char* path, float* value) -{ - rive::ViewModelInstanceRuntime* vmir = FromHandle(component, handle); - CHECK_VMIR(vmir, handle); - - rive::ViewModelInstanceNumberRuntime* prop = vmir->propertyNumber(path); - CHECK_PROP_RESULT(prop, "number", path); - *value = prop->value(); - return true; -} - -bool CompRiveRuntimeGetPropertyColor(RiveComponent* component, uint32_t handle, const char* path, dmVMath::Vector4* color) -{ - rive::ViewModelInstanceRuntime* vmir = FromHandle(component, handle); - CHECK_VMIR(vmir, handle); - - rive::ViewModelInstanceColorRuntime* prop = vmir->propertyColor(path); - CHECK_PROP_RESULT(prop, "color", path); - - uint32_t argb = (uint32_t)prop->value(); - float a = ((argb >> 24) & 0xFF) / 255.0f; - float r = ((argb >> 16) & 0xFF) / 255.0f; - float g = ((argb >> 8) & 0xFF) / 255.0f; - float b = ((argb >> 0) & 0xFF) / 255.0f; - *color = dmVMath::Vector4(r, g, b, a); - return true; -} - -bool CompRiveRuntimeGetPropertyString(RiveComponent* component, uint32_t handle, const char* path, const char** value) -{ - rive::ViewModelInstanceRuntime* vmir = FromHandle(component, handle); - CHECK_VMIR(vmir, handle); - - rive::ViewModelInstanceStringRuntime* prop = vmir->propertyString(path); - CHECK_PROP_RESULT(prop, "string", path); - - *value = prop->value().c_str(); // the temp string is not for storage - return true; -} - -bool CompRiveRuntimeGetPropertyEnum(RiveComponent* component, uint32_t handle, const char* path, const char** value) -{ - rive::ViewModelInstanceRuntime* vmir = FromHandle(component, handle); - CHECK_VMIR(vmir, handle); - - rive::ViewModelInstanceEnumRuntime* prop = vmir->propertyEnum(path); - CHECK_PROP_RESULT(prop, "enum", path); - - *value = prop->value().c_str(); // the temp string is not for storage - return true; -} - -// LISTS - -bool CompRiveRuntimeListAddInstance(RiveComponent* component, uint32_t handle, const char* path, uint32_t instance) -{ - rive::ViewModelInstanceRuntime* vmir = FromHandle(component, handle); - CHECK_VMIR(vmir, handle); - - rive::ViewModelInstanceListRuntime* prop = vmir->propertyList(path); - CHECK_PROP_RESULT(prop, "list", path); - - rive::ViewModelInstanceRuntime* instance_vmir = FromHandle(component, instance); - prop->addInstance(instance_vmir); - return true; -} - -bool CompRiveRuntimeListRemoveInstance(RiveComponent* component, uint32_t handle, const char* path, uint32_t instance) -{ - rive::ViewModelInstanceRuntime* vmir = FromHandle(component, handle); - CHECK_VMIR(vmir, handle); - - rive::ViewModelInstanceListRuntime* prop = vmir->propertyList(path); - CHECK_PROP_RESULT(prop, "list", path); - - rive::ViewModelInstanceRuntime* instance_vmir = FromHandle(component, instance); - prop->removeInstance(instance_vmir); - return true; -} - - -} // namespace - -#endif // DM_RIVE_UNSUPPORTED diff --git a/defold-rive/src/comp_rive_private.h b/defold-rive/src/comp_rive_private.h index b1364d4f..52a37bb8 100644 --- a/defold-rive/src/comp_rive_private.h +++ b/defold-rive/src/comp_rive_private.h @@ -27,20 +27,8 @@ #include "rive_ddf.h" #include - -namespace rive -{ - class Artboard; - class ArtboardInstance; - class Bone; - class LinearAnimationInstance; - class StateMachine; - class StateMachineInstance; - class ViewModelInstance; - class ViewModelInstanceRuntime; - class RenderImage; - enum class DataType : unsigned int; -} +#include +#include namespace dmGameObject { @@ -70,23 +58,21 @@ namespace dmRive dmMessage::URL m_Listener; dmGameSystem::HComponentRenderConstants m_RenderConstants; dmGameSystem::MaterialResource* m_Material; - dmScript::LuaCallbackInfo* m_Callback; - uint32_t m_CallbackId; rive::Mat2D m_InverseRendererTransform; - std::unique_ptr m_ArtboardInstance; - std::unique_ptr m_AnimationInstance; - std::unique_ptr m_StateMachineInstance; - dmHashTable32 m_ViewModelInstanceRuntimes; - - dmArray> m_AllSMSInstances; + rive::ArtboardHandle m_Artboard; + rive::StateMachineHandle m_StateMachine; + rive::ViewModelInstanceHandle m_ViewModelInstance; + rive::DrawKey m_DrawKey; dmGameObject::Playback m_AnimationPlayback; float m_AnimationPlaybackRate; - dmArray m_Bones; - dmArray m_BoneGOs; - dmArray m_StateMachineInputs; // A list of the hashed names for the state machine inputs. Index corresponds 1:1 to the statemachine inputs + // dmArray m_Bones; + // dmArray m_BoneGOs; + + rive::Fit m_Fit; + rive::Alignment m_Alignment; uint32_t m_VertexCount; uint32_t m_IndexCount; @@ -99,55 +85,14 @@ namespace dmRive uint8_t m_DoRender : 1; uint8_t m_AddedToUpdate : 1; uint8_t m_ReHash : 1; + uint8_t m_Fullscreen : 1; }; static const uint32_t INVALID_HANDLE = 0xFFFFFFFF; // Math - rive::Vec2D WorldToLocal(RiveComponent* component, float x, float y); - - // animations - RiveArtboardIdList* FindArtboardIdList(rive::Artboard* artboard, dmRive::RiveSceneData* data); - int FindAnimationIndex(dmhash_t* entries, uint32_t num_entries, dmhash_t anim_id); - - // State machine - rive::StateMachine* FindStateMachine(rive::Artboard* artboard, dmRive::RiveSceneData* data, int* state_machine_index, dmhash_t anim_id); - int FindStateMachineInputIndex(RiveComponent* component, dmhash_t property_name); - void GetStateMachineInputNames(rive::StateMachineInstance* smi, dmArray& names); - - dmGameObject::PropertyResult SetStateMachineInput(RiveComponent* component, int index, const dmGameObject::ComponentSetPropertyParams& params); - dmGameObject::PropertyResult GetStateMachineInput(RiveComponent* component, int index, - const dmGameObject::ComponentGetPropertyParams& params, dmGameObject::PropertyDesc& out_value); - - // Data bindings - void DebugModelViews(RiveComponent* component); - - // script api - uint32_t CompRiveCreateViewModelInstanceRuntime(RiveComponent* component, dmhash_t name_hash); - bool CompRiveDestroyViewModelInstanceRuntime(RiveComponent* component, uint32_t handle); - bool CompRiveSetViewModelInstanceRuntime(RiveComponent* component, uint32_t handle); - uint32_t CompRiveGetViewModelInstanceRuntime(RiveComponent* component); - - bool GetPropertyDataType(RiveComponent* component, uint32_t handle, const char* path, rive::DataType* type); - - bool CompRiveRuntimeSetPropertyBool(RiveComponent* component, uint32_t handle, const char* path, bool value); - bool CompRiveRuntimeSetPropertyF32(RiveComponent* component, uint32_t handle, const char* path, float value); - bool CompRiveRuntimeSetPropertyColor(RiveComponent* component, uint32_t handle, const char* path, dmVMath::Vector4* color); - bool CompRiveRuntimeSetPropertyString(RiveComponent* component, uint32_t handle, const char* path, const char* value); - bool CompRiveRuntimeSetPropertyEnum(RiveComponent* component, uint32_t handle, const char* path, const char* value); - bool CompRiveRuntimeSetPropertyTrigger(RiveComponent* component, uint32_t handle, const char* path); - bool CompRiveRuntimeSetPropertyImage(RiveComponent* component, uint32_t handle, const char* path, rive::RenderImage* image); - - bool CompRiveRuntimeGetPropertyBool(RiveComponent* component, uint32_t handle, const char* path, bool* value); - bool CompRiveRuntimeGetPropertyF32(RiveComponent* component, uint32_t handle, const char* path, float* value); - bool CompRiveRuntimeGetPropertyColor(RiveComponent* component, uint32_t handle, const char* path, dmVMath::Vector4* color); - bool CompRiveRuntimeGetPropertyString(RiveComponent* component, uint32_t handle, const char* path, const char** value); - bool CompRiveRuntimeGetPropertyEnum(RiveComponent* component, uint32_t handle, const char* path, const char** value); - - bool CompRiveRuntimeListAddInstance(RiveComponent* component, uint32_t handle, const char* path, uint32_t instance); - bool CompRiveRuntimeListRemoveInstance(RiveComponent* component, uint32_t handle, const char* path, uint32_t instance); - - RiveSceneData* CompRiveGetRiveSceneData(RiveComponent* component); + rive::Vec2D WorldToLocal(RiveComponent* component, float x, float y); + RiveSceneData* CompRiveGetRiveSceneData(RiveComponent* component); } #endif //DM_COMP_RIVE_PRIVATE_H diff --git a/defold-rive/src/comp_rive_statemachine.cpp b/defold-rive/src/comp_rive_statemachine.cpp deleted file mode 100644 index cf9974f9..00000000 --- a/defold-rive/src/comp_rive_statemachine.cpp +++ /dev/null @@ -1,288 +0,0 @@ -// Copyright 2020 The Defold Foundation -// Licensed under the Defold License version 1.0 (the "License"); you may not use -// this file except in compliance with the License. -// -// You may obtain a copy of the License, together with FAQs at -// https://www.defold.com/license -// -// Unless required by applicable law or agreed to in writing, software distributed -// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -// CONDITIONS OF ANY KIND, either express or implied. See the License for the -// specific language governing permissions and limitations under the License. - -#if !defined(DM_RIVE_UNSUPPORTED) - -#include "comp_rive.h" -#include "comp_rive_private.h" -#include "res_rive_data.h" - -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -namespace dmRive -{ - rive::StateMachine* FindStateMachine(rive::Artboard* artboard, dmRive::RiveSceneData* data, int* state_machine_index, dmhash_t anim_id) - { - RiveArtboardIdList* id_list = FindArtboardIdList(artboard, data); - if (!id_list) - { - return 0; - } - - int index = FindAnimationIndex(id_list->m_StateMachines.Begin(), id_list->m_StateMachines.Size(), anim_id); - if (index == -1) { - return 0; - } - *state_machine_index = index; - return artboard->stateMachine(index); - } - - int FindStateMachineInputIndex(RiveComponent* component, dmhash_t property_name) - { - uint32_t count = component->m_StateMachineInputs.Size(); - for (uint32_t i = 0; i < count; ++i) - { - if (component->m_StateMachineInputs[i] == property_name) - { - return (int)i; - } - } - return -1; - } - - void GetStateMachineInputNames(rive::StateMachineInstance* smi, dmArray& names) - { - uint32_t count = smi->inputCount(); - if (count > names.Capacity()) - { - names.SetCapacity(count); - } - names.SetSize(count); - - for (uint32_t i = 0; i < count; ++i) - { - const rive::SMIInput* input = smi->input(i); - names[i] = dmHashString64(input->name().c_str()); - } - } - - dmGameObject::PropertyResult SetStateMachineInput(RiveComponent* component, int index, const dmGameObject::ComponentSetPropertyParams& params) - { - const rive::StateMachine* state_machine = component->m_StateMachineInstance->stateMachine(); - const rive::StateMachineInput* input = state_machine->input(index); - rive::SMIInput* input_instance = component->m_StateMachineInstance->input(index); - - if (input->is()) - { - if (params.m_Value.m_Type != dmGameObject::PROPERTY_TYPE_BOOLEAN) - { - dmLogError("Found property %s of type trigger, but didn't receive a boolean", input->name().c_str()); - return dmGameObject::PROPERTY_RESULT_TYPE_MISMATCH; - } - - // The trigger can only respond to the value "true" - if (!params.m_Value.m_Bool) - { - dmLogError("Found property %s of type trigger, but didn't receive a boolean of true", input->name().c_str()); - return dmGameObject::PROPERTY_RESULT_TYPE_MISMATCH; - } - - rive::SMITrigger* trigger = (rive::SMITrigger*)input_instance; - trigger->fire(); - } - else if (input->is()) - { - if (params.m_Value.m_Type != dmGameObject::PROPERTY_TYPE_BOOLEAN) - { - dmLogError("Found property %s of type bool, but didn't receive a boolean", input->name().c_str()); - return dmGameObject::PROPERTY_RESULT_TYPE_MISMATCH; - } - - rive::SMIBool* v = (rive::SMIBool*)input_instance; - v->value(params.m_Value.m_Bool); - } - else if (input->is()) - { - if (params.m_Value.m_Type != dmGameObject::PROPERTY_TYPE_NUMBER) - { - dmLogError("Found property %s of type number, but didn't receive a number", input->name().c_str()); - return dmGameObject::PROPERTY_RESULT_TYPE_MISMATCH; - } - - rive::SMINumber* v = (rive::SMINumber*)input_instance; - v->value(params.m_Value.m_Number); - } - - return dmGameObject::PROPERTY_RESULT_OK; - } - - dmGameObject::PropertyResult GetStateMachineInput(RiveComponent* component, int index, - const dmGameObject::ComponentGetPropertyParams& params, dmGameObject::PropertyDesc& out_value) - { - const rive::StateMachine* state_machine = component->m_StateMachineInstance->stateMachine(); - const rive::StateMachineInput* input = state_machine->input(index); - rive::SMIInput* input_instance = component->m_StateMachineInstance->input(index); - - if (input->is()) - { - dmLogError("Cannot get value of input type trigger ( %s )", input->name().c_str()); - return dmGameObject::PROPERTY_RESULT_TYPE_MISMATCH; - } - else if (input->is()) - { - rive::SMIBool* v = (rive::SMIBool*)input_instance; - out_value.m_Variant = dmGameObject::PropertyVar(v->value()); - } - else if (input->is()) - { - rive::SMINumber* v = (rive::SMINumber*)input_instance; - out_value.m_Variant = dmGameObject::PropertyVar(v->value()); - } - - return dmGameObject::PROPERTY_RESULT_OK; - } - - - StateMachineInputData::Result CompRiveSetStateMachineInput(RiveComponent* component, const char* input_name, const char* nested_artboard_path, const StateMachineInputData& value) - { - rive::ArtboardInstance* artboard = component->m_ArtboardInstance.get(); - rive::SMIInput* input_instance = 0x0; - - if (nested_artboard_path) - { - input_instance = artboard->input(input_name, nested_artboard_path); - } - else - { - dmhash_t input_hash = dmHashString64(input_name); - int index = FindStateMachineInputIndex(component, input_hash); - if (index >= 0) - { - input_instance = component->m_StateMachineInstance->input(index); - } - } - - if (input_instance) - { - const rive::StateMachineInput* input = input_instance->input(); - - if (input->is()) - { - if (value.m_Type != StateMachineInputData::TYPE_BOOL) - { - return StateMachineInputData::RESULT_TYPE_MISMATCH; - } - rive::SMITrigger* trigger = (rive::SMITrigger*)input_instance; - trigger->fire(); - return StateMachineInputData::RESULT_OK; - } - else if (input->is()) - { - if (value.m_Type != StateMachineInputData::TYPE_BOOL) - { - return StateMachineInputData::RESULT_TYPE_MISMATCH; - } - rive::SMIBool* v = (rive::SMIBool*)input_instance; - v->value(value.m_BoolValue); - return StateMachineInputData::RESULT_OK; - } - else if (input->is()) - { - if (value.m_Type != StateMachineInputData::TYPE_NUMBER) - { - return StateMachineInputData::RESULT_TYPE_MISMATCH; - } - rive::SMINumber* v = (rive::SMINumber*)input_instance; - v->value(value.m_NumberValue); - return StateMachineInputData::RESULT_OK; - } - } - - return StateMachineInputData::RESULT_NOT_FOUND; - } - - StateMachineInputData::Result CompRiveGetStateMachineInput(RiveComponent* component, const char* input_name, const char* nested_artboard_path, StateMachineInputData& out_value) - { - rive::ArtboardInstance* artboard = component->m_ArtboardInstance.get(); - rive::SMIInput* input_instance = 0x0; - - if (nested_artboard_path) - { - input_instance = artboard->input(input_name, nested_artboard_path); - } - else - { - dmhash_t input_hash = dmHashString64(input_name); - int index = FindStateMachineInputIndex(component, input_hash); - if (index >= 0) - { - input_instance = component->m_StateMachineInstance->input(index); - } - } - - out_value.m_Type = StateMachineInputData::TYPE_INVALID; - - if (input_instance) - { - const rive::StateMachineInput* input = input_instance->input(); - - if (input->is()) - { - return StateMachineInputData::RESULT_TYPE_UNSUPPORTED; - } - else if (input->is()) - { - rive::SMIBool* v = (rive::SMIBool*)input_instance; - out_value.m_Type = StateMachineInputData::TYPE_BOOL; - out_value.m_BoolValue = v->value(); - return StateMachineInputData::RESULT_OK; - } - else if (input->is()) - { - rive::SMINumber* v = (rive::SMINumber*)input_instance; - out_value.m_Type = StateMachineInputData::TYPE_NUMBER; - out_value.m_NumberValue = v->value(); - return StateMachineInputData::RESULT_OK; - } - } - - return StateMachineInputData::RESULT_NOT_FOUND; - } - - void CompRivePointerMove(RiveComponent* component, float x, float y) - { - if (component->m_StateMachineInstance) - { - rive::Vec2D p = WorldToLocal(component, x, y); - component->m_StateMachineInstance->pointerMove(p); - } - } - - void CompRivePointerUp(RiveComponent* component, float x, float y) - { - if (component->m_StateMachineInstance) - { - rive::Vec2D p = WorldToLocal(component, x, y); - component->m_StateMachineInstance->pointerUp(p); - } - } - - void CompRivePointerDown(RiveComponent* component, float x, float y) - { - if (component->m_StateMachineInstance) - { - rive::Vec2D p = WorldToLocal(component, x, y); - component->m_StateMachineInstance->pointerDown(p); - } - } -} - -#endif diff --git a/defold-rive/src/extension.cpp b/defold-rive/src/extension.cpp index 96c801b6..a88d22f3 100644 --- a/defold-rive/src/extension.cpp +++ b/defold-rive/src/extension.cpp @@ -1,12 +1,30 @@ +// Copyright 2020-2025 The Defold Foundation +// Licensed under the Defold License version 1.0 (the "License"); you may not use +// this file except in compliance with the License. +// +// You may obtain a copy of the License, together with FAQs at +// https://www.defold.com/license +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. #if defined(DM_UNSUPPORTED_PLATFORM) #error "This platform is not supported" #endif #include +#include #include + #include "script_rive.h" #include +#include "defold/renderer.h" + +#include + +dmRive::HRenderContext g_RenderContext = 0; static dmExtension::Result AppInitializeRive(dmExtension::AppParams* params) { @@ -15,20 +33,37 @@ static dmExtension::Result AppInitializeRive(dmExtension::AppParams* params) static dmExtension::Result InitializeRive(dmExtension::Params* params) { -#if !defined(DM_RIVE_UNSUPPORTED) + g_RenderContext = dmRive::NewRenderContext(); + assert(g_RenderContext != 0); + + dmRiveCommands::InitParams cmd_params; + cmd_params.m_UseThreads = true; // TODO: Use define and/or config flag + cmd_params.m_RenderContext = g_RenderContext; + cmd_params.m_Factory = dmRive::GetRiveFactory(g_RenderContext); + dmRiveCommands::Initialize(&cmd_params); + + // relies on the command queue for registering listeners dmResource::HFactory factory = dmExtension::GetContextAsType(params, "factory"); dmRive::ScriptRegister(params->m_L, factory); + dmLogInfo("Registered Rive extension: %s %s\n", RIVE_RUNTIME_DATE, RIVE_RUNTIME_SHA1); -#endif return dmExtension::RESULT_OK; } -static dmExtension::Result AppFinalizeRive(dmExtension::AppParams* params) +static dmExtension::Result FinalizeRive(dmExtension::Params* params) { + dmResource::HFactory factory = dmExtension::GetContextAsType(params, "factory"); + dmRive::ScriptUnregister(params->m_L, factory); + + dmRiveCommands::Finalize(); + + dmRive::DeleteRenderContext(g_RenderContext); + g_RenderContext = 0; + return dmExtension::RESULT_OK; } -static dmExtension::Result FinalizeRive(dmExtension::Params* params) +static dmExtension::Result AppFinalizeRive(dmExtension::AppParams* params) { return dmExtension::RESULT_OK; } diff --git a/defold-rive/src/res_rive_data.cpp b/defold-rive/src/res_rive_data.cpp index 1fe8fcd2..fb988a33 100644 --- a/defold-rive/src/res_rive_data.cpp +++ b/defold-rive/src/res_rive_data.cpp @@ -14,121 +14,69 @@ #include #include +#include #include -// Rive includes -#include -#include -#include -#include -#include -#include -#include - // Extension includes #include "res_rive_data.h" +#include "script_rive.h" #include "defold/renderer.h" #include #include #include +#include + +#include +#include namespace dmRive { - static void SetupData(RiveSceneData* scene_data, rive::File* file, const char* path, HRenderContext rive_render_context) + static rive::FileHandle LoadFile(rive::rcp queue, const char* path, const void* data, uint32_t data_size, RiveSceneData* scene_data) { - scene_data->m_File = file; - scene_data->m_RiveRenderContext = rive_render_context; - scene_data->m_ArtboardDefault = scene_data->m_File->artboardDefault(); - if (!scene_data->m_ArtboardDefault.get()) - { - return; - } - - size_t artboard_count = scene_data->m_File->artboardCount(); - - scene_data->m_ArtboardIdLists.SetCapacity(artboard_count); - scene_data->m_ArtboardIdLists.SetSize(artboard_count); - - for (int i = 0; i < artboard_count; ++i) - { - rive::Artboard* artboard = scene_data->m_File->artboard(i); + // RIVE: Currently their api doesn't support passing the bytes directly, but require you to make a copy of it. + const uint8_t* _data = (const uint8_t*)data; + std::vector rive_data(_data, _data + data_size); - RiveArtboardIdList* id_list = new RiveArtboardIdList(); - scene_data->m_ArtboardIdLists[i] = id_list; - - id_list->m_ArtboardNameHash = dmHashString64(artboard->name().c_str()); - - // Setup state machine ID lists - uint32_t state_machine_count = (uint32_t)artboard->stateMachineCount(); - if (state_machine_count) - { - id_list->m_StateMachines.SetCapacity(state_machine_count); - id_list->m_StateMachines.SetSize(state_machine_count); - - for (int j = 0; j < state_machine_count; ++j) - { - rive::StateMachine* state_machine = artboard->stateMachine(j); - id_list->m_StateMachines[j] = dmHashString64(state_machine->name().c_str()); - } - } - - // Setup animation ID lists - uint32_t animation_count = (uint32_t)artboard->animationCount(); - if (animation_count) - { - id_list->m_LinearAnimations.SetCapacity(animation_count); - id_list->m_LinearAnimations.SetSize(animation_count); + rive::FileHandle file = queue->loadFile(rive_data, 0, (uint64_t)(uintptr_t)scene_data); + return file; + } - for (int j = 0; j < animation_count; ++j) - { - rive::LinearAnimation* animation = artboard->animation(j); - id_list->m_LinearAnimations[j] = dmHashString64(animation->name().c_str()); - } - } - } + static void SetupData(RiveSceneData* scene_data, rive::FileHandle file, const char* path, HRenderContext rive_render_context) + { + scene_data->m_PathHash = dmHashString64(path); + scene_data->m_File = file; + scene_data->m_RiveRenderContext = rive_render_context; } static dmResource::Result ResourceType_RiveData_Create(const dmResource::ResourceCreateParams* params) { HRenderContext render_context_res = (HRenderContext) params->m_Context; - rive::Factory* rive_factory = GetRiveFactory(render_context_res); + rive::rcp queue = dmRiveCommands::GetCommandQueue(); + rive::Factory* rive_factory = dmRiveCommands::GetFactory(); assert(rive_factory); - rive::Span data((const uint8_t*)params->m_Buffer, params->m_BufferSize); - - // Creates DefoldRenderImage with a hashed name for each image resource - rive::rcp atlas_resolver(new AtlasNameResolver(params->m_Factory, render_context_res)); - - rive::ImportResult result; - rive::rcp file = rive::File::import(data, - rive_factory, - &result, - atlas_resolver); - - if (result != rive::ImportResult::success) + RiveSceneData* scene_data = new RiveSceneData(); + scene_data->m_File = LoadFile(queue, params->m_Filename, params->m_Buffer, params->m_BufferSize, scene_data); + if (!scene_data->m_File) { - dmResource::SetResource(params->m_Resource, 0); + dmLogError("Failed to load '%s'", params->m_Filename); + delete scene_data; return dmResource::RESULT_INVALID_DATA; } - RiveSceneData* scene_data = new RiveSceneData(); - scene_data->m_FileAssets.Swap(atlas_resolver->GetAssets()); - SetupData(scene_data, file.release(), params->m_Filename, render_context_res); + SetupData(scene_data, scene_data->m_File, params->m_Filename, render_context_res); dmResource::SetResource(params->m_Resource, scene_data); - dmResource::SetResourceSize(params->m_Resource, 0); + dmResource::SetResourceSize(params->m_Resource, params->m_BufferSize); return dmResource::RESULT_OK; } static void DeleteData(RiveSceneData* scene_data) { - for (int i = 0; i < scene_data->m_ArtboardIdLists.Size(); ++i) - { - delete scene_data->m_ArtboardIdLists[i]; - } - delete scene_data->m_File; + rive::rcp queue = dmRiveCommands::GetCommandQueue(); + queue->deleteFile(scene_data->m_File); delete scene_data; } @@ -142,45 +90,38 @@ namespace dmRive static dmResource::Result ResourceType_RiveData_Recreate(const dmResource::ResourceRecreateParams* params) { HRenderContext render_context_res = (HRenderContext) params->m_Context; - rive::Span data((uint8_t*)params->m_Buffer, params->m_BufferSize); - - rive::Factory* rive_factory = GetRiveFactory(render_context_res); - - rive::rcp atlas_resolver(new AtlasNameResolver(params->m_Factory, render_context_res)); + rive::rcp queue = dmRiveCommands::GetCommandQueue(); - rive::ImportResult result; - rive::rcp file = rive::File::import(data, - rive_factory, - &result, - atlas_resolver); - - if (result != rive::ImportResult::success) + RiveSceneData* scene_data = new RiveSceneData(); + scene_data->m_File = LoadFile(queue, params->m_Filename, params->m_Buffer, params->m_BufferSize, scene_data); + if (!scene_data->m_File) { - // If we cannot load the new file, let's keep the old one + dmLogError("Failed to load '%s'", params->m_Filename); + delete scene_data; return dmResource::RESULT_INVALID_DATA; } RiveSceneData* old_data = (RiveSceneData*)dmResource::GetResource(params->m_Resource); - if (old_data != 0) - { - dmResource::SetResource(params->m_Resource, 0); - DeleteData(old_data); - } + assert(old_data == 0); - RiveSceneData* scene_data = new RiveSceneData(); + // We don't want to delete the old resource, as the pointer may be "live" + rive::FileHandle tmp_handle = scene_data->m_File; + scene_data->m_File = old_data->m_File; + old_data->m_File = tmp_handle; - scene_data->m_FileAssets.Swap(atlas_resolver->GetAssets()); - SetupData(scene_data, file.release(), params->m_Filename, render_context_res); + DeleteData(scene_data); - dmResource::SetResource(params->m_Resource, scene_data); - dmResource::SetResourceSize(params->m_Resource, 0); + SetupData(old_data, scene_data->m_File, params->m_Filename, render_context_res); + + dmResource::SetResourceSize(params->m_Resource, params->m_BufferSize); return dmResource::RESULT_OK; } static ResourceResult RegisterResourceType_RiveData(HResourceTypeContext ctx, HResourceType type) { - HRenderContext rive_render_context = NewRenderContext(); + HRenderContext rive_render_context = dmRiveCommands::GetDefoldRenderContext(); + assert(rive_render_context != 0); return (ResourceResult)dmResource::SetupType(ctx, type, @@ -195,111 +136,8 @@ namespace dmRive static ResourceResult DeregisterResourceType_RiveData(HResourceTypeContext ctx, HResourceType type) { - HRenderContext context = (HRenderContext)ResourceTypeGetContext(type); - DeleteRenderContext(context); return RESOURCE_RESULT_OK; } - - // Scripting functions - - static rive::FileAsset* FindAsset(RiveSceneData* resource, const char* asset_name) - { - for (uint32_t i = 0; i < resource->m_FileAssets.Size(); ++i) - { - rive::FileAsset* _asset = resource->m_FileAssets[i]; - const std::string& name = _asset->name(); - const char* name_str = name.c_str(); - if (strcmp(asset_name, name_str) == 0) - return _asset; - } - return 0; - } - - dmResource::Result ResRiveDataSetAssetFromMemory(RiveSceneData* resource, const char* asset_name, void* payload, uint32_t payload_size) - { - rive::FileAsset* _asset = FindAsset(resource, asset_name); - if (!_asset) - { - dmLogError("Rive scene doesn't have asset named '%s'", asset_name); - return dmResource::RESULT_INVALID_DATA; - } - - if (_asset->is()) - { - rive::ImageAsset* asset = _asset->as(); - rive::rcp image = dmRive::LoadImageFromMemory(resource->m_RiveRenderContext, payload, payload_size); - if (!image) - { - dmLogError("Failed to load asset '%s' from payload.", asset_name); - return dmResource::RESULT_INVALID_DATA; - } - - asset->renderImage(image); - return dmResource::RESULT_OK; - } - else if (_asset->is()) - { - rive::FontAsset* asset = _asset->as(); - rive::rcp font = dmRive::LoadFontFromMemory(resource->m_RiveRenderContext, payload, payload_size); - if (!font) - { - dmLogError("Failed to load font asset '%s' from payload.", asset_name); - return dmResource::RESULT_INVALID_DATA; - } - - asset->font(font); - return dmResource::RESULT_OK; - } - - dmLogError("We currently don't support swapping the asset type of '%s'", asset_name); - return dmResource::RESULT_NOT_SUPPORTED; - } - - dmResource::Result ResRiveDataSetAsset(dmResource::HFactory factory, RiveSceneData* resource, const char* asset_name, const char* path) - { - rive::FileAsset* _asset = FindAsset(resource, asset_name); - if (!_asset) - { - dmLogError("Rive scene doesn't have asset named '%s'", asset_name); - return dmResource::RESULT_INVALID_DATA; - } - - if (_asset->is()) - { - rive::ImageAsset* asset = _asset->as(); - rive::rcp image = dmRive::LoadImageFromFactory(factory, resource->m_RiveRenderContext, path); - if (!image) - { - dmLogError("Failed to load asset '%s' with path '%s'", asset_name, path); - return dmResource::RESULT_INVALID_DATA; - } - - asset->renderImage(image); - return dmResource::RESULT_OK; - } - else if (_asset->is()) - { - rive::FontAsset* asset = _asset->as(); - rive::rcp font = dmRive::LoadFontFromFactory(factory, resource->m_RiveRenderContext, path); - if (!font) - { - dmLogError("Failed to load font asset '%s' with path '%s'", asset_name, path); - return dmResource::RESULT_INVALID_DATA; - } - - asset->font(font); - return dmResource::RESULT_OK; - } - - dmLogError("We currently don't support swapping the asset type of '%s'", asset_name); - return dmResource::RESULT_NOT_SUPPORTED; - } - - rive::RenderImage* ResRiveDataCreateRenderImage(dmResource::HFactory factory, RiveSceneData* resource, uint8_t* data, uint32_t data_length) - { - rive::rcp image = dmRive::LoadImageFromMemory(resource->m_RiveRenderContext, data, data_length); - return image.release(); - } } diff --git a/defold-rive/src/res_rive_data.h b/defold-rive/src/res_rive_data.h index 0332f8b7..3b79ac85 100644 --- a/defold-rive/src/res_rive_data.h +++ b/defold-rive/src/res_rive_data.h @@ -14,40 +14,19 @@ #define DM_RES_RIVE_DATA_H #include -#include -#include #include "defold/renderer.h" -namespace rive -{ - class File; - class FileAsset; - class ArtboardInstance; -} +#include +#include namespace dmRive { - struct RiveBone; - - struct RiveArtboardIdList - { - dmhash_t m_ArtboardNameHash; - dmArray m_LinearAnimations; - dmArray m_StateMachines; - }; - struct RiveSceneData { - rive::File* m_File; - HRenderContext m_RiveRenderContext; - std::unique_ptr m_ArtboardDefault; - dmArray m_ArtboardIdLists; - dmArray m_FileAssets; // For runtime swapping + dmhash_t m_PathHash; + rive::FileHandle m_File; + HRenderContext m_RiveRenderContext; }; - - dmResource::Result ResRiveDataSetAssetFromMemory(RiveSceneData* resource, const char* asset_name, void* payload, uint32_t payload_size); - dmResource::Result ResRiveDataSetAsset(dmResource::HFactory factory, RiveSceneData* resource, const char* asset_name, const char* path); - rive::RenderImage* ResRiveDataCreateRenderImage(dmResource::HFactory factory, RiveSceneData* resource, uint8_t* data, uint32_t data_length); } #endif // DM_RES_RIVE_DATA_H diff --git a/defold-rive/src/res_rive_scene.cpp b/defold-rive/src/res_rive_scene.cpp index 58f7e206..2a69eacb 100644 --- a/defold-rive/src/res_rive_scene.cpp +++ b/defold-rive/src/res_rive_scene.cpp @@ -37,6 +37,11 @@ namespace dmRive if (resource->m_DDF->m_Atlas[0] != 0) { dmResource::Result result = dmResource::Get(factory, resource->m_DDF->m_Atlas, (void**) &resource->m_TextureSet); // .atlas -> .texturesetc + if (result != dmResource::RESULT_OK) + { + return result; + } + resource->m_Atlas = dmRive::CreateAtlas(resource->m_TextureSet->m_TextureSet); } diff --git a/defold-rive/src/script_defold.cpp b/defold-rive/src/script_defold.cpp new file mode 100644 index 00000000..16ab9520 --- /dev/null +++ b/defold-rive/src/script_defold.cpp @@ -0,0 +1,102 @@ +// Copyright 2020 The Defold Foundation +// Licensed under the Defold License version 1.0 (the "License"); you may not use +// this file except in compliance with the License. +// +// You may obtain a copy of the License, together with FAQs at +// https://www.defold.com/license +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + + +#include + +namespace dmRive +{ + +int PushFromMetaMethods(lua_State* L, int obj_index, int key_index) +{ + if (lua_getmetatable(L, obj_index)) + { + lua_getfield(L, -1, "__methods"); + lua_pushvalue(L, key_index); + lua_rawget(L, -2); + lua_remove(L, -2); // pop methods table + lua_remove(L, -2); // pop metatable + return 1; + } + // No metatable or no __methods — push nil + lua_pushnil(L); + return 1; +} + + +// Helper: set functions from a luaL_reg array onto table at top of stack +static void SetFuncs(lua_State* L, const luaL_reg* funcs) +{ + if (!funcs) return; + for (const luaL_reg* r = funcs; r->name; ++r) + { + lua_pushcfunction(L, r->func); + lua_setfield(L, -2, r->name); + } +} + +void RegisterUserType(lua_State* L, const char* class_name, const char* metatable_name, const luaL_reg methods[], const luaL_reg meta[]) +{ + // Methods table + lua_newtable(L); + int methods_idx = lua_gettop(L); + SetFuncs(L, methods); + + // Metatable + luaL_newmetatable(L, metatable_name); + int mt = lua_gettop(L); + // Store methods table on metatable for generic __index helpers + lua_pushvalue(L, methods_idx); + lua_setfield(L, mt, "__methods"); + + // Apply/override metamethods from provided list + SetFuncs(L, meta); + + // pop metatable + lua_pop(L, 1); + + // Pop methods table + lua_pop(L, 1); +} + +static void* luaL_testudata(lua_State* L, int idx, const char* tname) +{ + void* p = lua_touserdata(L, idx); + if (p == NULL) + { + return NULL; + } + if (!lua_getmetatable(L, idx)) + { + return NULL; + } + luaL_getmetatable(L, tname); + int equal = lua_rawequal(L, -1, -2); + lua_pop(L, 2); + if (!equal) + { + return NULL; + } + return p; +} + +void* ToUserType(lua_State* L, int idx, const char* metatable_name) +{ + return luaL_testudata(L, idx, metatable_name); +} + +void* CheckUserType(lua_State* L, int idx, const char* metatable_name) +{ + return luaL_checkudata(L, idx, metatable_name); +} + +} diff --git a/defold-rive/src/script_defold.h b/defold-rive/src/script_defold.h new file mode 100644 index 00000000..a57e5202 --- /dev/null +++ b/defold-rive/src/script_defold.h @@ -0,0 +1,32 @@ +// Copyright 2020 The Defold Foundation +// Licensed under the Defold License version 1.0 (the "License"); you may not use +// this file except in compliance with the License. +// +// You may obtain a copy of the License, together with FAQs at +// https://www.defold.com/license +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#ifndef DM_GAMESYS_SCRIPT_DEFOLD_H +#define DM_GAMESYS_SCRIPT_DEFOLD_H + +extern "C" { + #include + #include +} + +namespace dmRive +{ + +void RegisterUserType(lua_State* L, const char* class_name, const char* metatable_name, const luaL_reg methods[], const luaL_reg meta[]); +void* ToUserType(lua_State* L, int user_data_index, const char* metatable_name); +void* CheckUserType(lua_State* L, int user_data_index, const char* metatable_name); + +// Helper to call methods from within an __index function +int PushFromMetaMethods(lua_State* L, int obj_index, int key_index); +} + +#endif // DM_GAMESYS_SCRIPT_DEFOLD_H diff --git a/defold-rive/src/script_rive.cpp b/defold-rive/src/script_rive.cpp index a89c5334..147c7c52 100644 --- a/defold-rive/src/script_rive.cpp +++ b/defold-rive/src/script_rive.cpp @@ -12,10 +12,15 @@ #if !defined(DM_RIVE_UNSUPPORTED) -#include -#include -#include -#include +/*# Rive model API documentation + * + * Functions and messages for interacting with the 'Rive' + * animation system. + * + * @document + * @name Rive + * @namespace rive + */ #include #include @@ -31,509 +36,523 @@ #include "rive_ddf.h" #include "res_rive_data.h" +#include "script_rive.h" +#include "script_rive_cmd.h" +#include "script_rive_listeners.h" +#include "script_rive_handles.h" + +#include namespace dmRive { - static const char* RIVE_EXT = "rivc"; - static const dmhash_t RIVE_EXT_HASH = dmHashString64(RIVE_EXT); - - static dmResource::HFactory g_Factory = 0; - - /*# Rive model API documentation - * - * Functions and messages for interacting with the 'Rive' - * animation system. - * - * @document - * @name Rive - * @namespace rive - */ - - /*# play an animation on a rive model - * Plays a specified animation on a rive model component with specified playback - * mode and parameters. - */ - static int RiveComp_PlayAnim(lua_State* L) - { - DM_LUA_STACK_CHECK(L, 0); - int top = lua_gettop(L); - - RiveComponent* component = 0; - dmScript::GetComponentFromLua(L, 1, dmRive::RIVE_MODEL_EXT, 0, (void**)&component, 0); - - dmRiveDDF::RivePlayAnimation ddf; - ddf.m_AnimationId = dmScript::CheckHashOrString(L, 2);; - ddf.m_Playback = luaL_checkinteger(L, 3); - ddf.m_Offset = 0.0; - ddf.m_PlaybackRate = 1.0; - ddf.m_IsStateMachine = false; - - if (top > 3) // table with args - { - if (lua_istable(L, 4)) - { - luaL_checktype(L, 4, LUA_TTABLE); - lua_pushvalue(L, 4); - - lua_getfield(L, -1, "offset"); - ddf.m_Offset = lua_isnil(L, -1) ? 0.0 : luaL_checknumber(L, -1); - lua_pop(L, 1); - - lua_getfield(L, -1, "playback_rate"); - ddf.m_PlaybackRate = lua_isnil(L, -1) ? 1.0 : luaL_checknumber(L, -1); - lua_pop(L, 1); - - lua_pop(L, 1); - } - } - - dmScript::LuaCallbackInfo* cbk = 0x0; - if (top > 4) // completed cb - { - if (lua_isfunction(L, 5)) - { - cbk = dmScript::CreateCallback(L, 5); - } - } - - if (!CompRivePlayAnimation(component, &ddf, cbk)) - { - if (cbk) - { - dmScript::DestroyCallback(cbk); - } - } +static const char* RIVE_EXT = "rivc"; +static const dmhash_t RIVE_EXT_HASH = dmHashString64(RIVE_EXT); - return 0; - } +static dmResource::HFactory g_Factory = 0; - /*# play a state machine on a rive model - * Plays a specified state machine on a rive model component with specified playback - * mode and parameters. - */ - static int RiveComp_PlayStateMachine(lua_State* L) - { - DM_LUA_STACK_CHECK(L, 0); - int top = lua_gettop(L); - - RiveComponent* component = 0; - dmScript::GetComponentFromLua(L, 1, dmRive::RIVE_MODEL_EXT, 0, (void**)&component, 0); - - dmRiveDDF::RivePlayAnimation ddf; - ddf.m_AnimationId = dmScript::CheckHashOrString(L, 2); - ddf.m_Playback = 0; - ddf.m_Offset = 0.0; - ddf.m_PlaybackRate = 1.0; - ddf.m_IsStateMachine = true; - - if (top > 2) // table with args - { - if (lua_istable(L, 3)) - { - luaL_checktype(L, 3, LUA_TTABLE); - lua_pushvalue(L, 3); - - lua_getfield(L, -1, "offset"); - ddf.m_Offset = lua_isnil(L, -1) ? 0.0 : luaL_checknumber(L, -1); - lua_pop(L, 1); - - lua_getfield(L, -1, "playback_rate"); - ddf.m_PlaybackRate = lua_isnil(L, -1) ? 1.0 : luaL_checknumber(L, -1); - lua_pop(L, 1); - - lua_pop(L, 1); - } - } - - dmScript::LuaCallbackInfo* cbk = 0x0; - if (top > 3) // completed cb - { - if (lua_isfunction(L, 4)) - { - cbk = dmScript::CreateCallback(L, 4); - } - } - - if (!CompRivePlayStateMachine(component, &ddf, cbk)) - { - if (cbk) - { - dmScript::DestroyCallback(cbk); - } - } +FileListener g_FileListener; +ArtboardListener g_ArtboardListener; +StateMachineListener g_StateMachineListener; +ViewModelInstanceListener g_ViewModelInstanceListener; +RenderImageListener g_RenderImageListener; +AudioSourceListener g_AudioSourceListener; +FontListener g_FontListener; - return 0; - } - - // Can cancel both a single animation and a state machine playing - static int RiveComp_Cancel(lua_State* L) - { - DM_LUA_STACK_CHECK(L, 0); +static int Script_PointerAction(lua_State* L, dmRive::PointerAction action) +{ + DM_LUA_STACK_CHECK(L, 0); - dmGameObject::HInstance instance = dmScript::CheckGOInstance(L); + RiveComponent* component = 0; + dmScript::GetComponentFromLua(L, 1, dmRive::RIVE_MODEL_EXT, 0, (void**)&component, 0); + lua_Number x = luaL_checknumber(L, 2); + lua_Number y = luaL_checknumber(L, 3); - dmMessage::URL receiver; - dmMessage::URL sender; - dmScript::ResolveURL(L, 1, &receiver, &sender); + CompRivePointerAction(component, action, x, y); + return 0; +} - dmRiveDDF::RiveCancelAnimation msg; - dmMessage::Post(&sender, &receiver, dmRiveDDF::RiveCancelAnimation::m_DDFDescriptor->m_NameHash, (uintptr_t)instance, 0, (uintptr_t)dmRiveDDF::RiveCancelAnimation::m_DDFDescriptor, &msg, sizeof(msg), 0); - return 0; - } +/** + * Lua wrapper for pointer movement. + * @name rive.pointer_move(component, x, y) + * @param url [type: url] Component receiving the pointer move. + * @param x [type: number] Pointer x coordinate in component space. + * @param y [type: number] Pointer y coordinate in component space. + */ +static int Script_PointerMove(lua_State* L) +{ + return Script_PointerAction(L, dmRive::PointerAction::POINTER_MOVE); +} - /*# retrieve the game object corresponding to a rive artboard skeleton bone - * Returns the id of the game object that corresponds to a specified skeleton bone. - * The returned game object can be used for parenting and transform queries. - * This function has complexity `O(n)`, where `n` is the number of bones in the rive model skeleton. - * Game objects corresponding to a rive model skeleton bone can not be individually deleted. - * - * @name rive.get_go - * @param url [type:string|hash|url] the rive model to query - * @param bone_id [type:string|hash] id of the corresponding bone - * @return id [type:hash] id of the game object - * @examples - * - * The following examples assumes that the rive model has id "rivemodel". - * - * How to parent the game object of the calling script to the "right_hand" bone of the rive model in a player game object: - * - * ```lua - * function init(self) - * local parent = rive.get_go("player#rivemodel", "right_hand") - * msg.post(".", "set_parent", {parent_id = parent}) - * end - * ``` - */ - static int RiveComp_GetGO(lua_State* L) - { - DM_LUA_STACK_CHECK(L, 1); +/** + * Lua wrapper for pointer up events. + * @name rive.pointer_up(component, x, y) + * @param url [type: url] Component receiving the pointer release. + * @param x [type: number] Pointer x coordinate. + * @param y [type: number] Pointer y coordinate. + */ +static int Script_PointerUp(lua_State* L) +{ + return Script_PointerAction(L, dmRive::PointerAction::POINTER_UP); +} - RiveComponent* component = 0; - dmScript::GetComponentFromLua(L, 1, dmRive::RIVE_MODEL_EXT, 0, (void**)&component, 0); +/** + * Lua wrapper for pointer down events. + * @name rive.pointer_down(component, x, y) + * @param url [type: url] Component receiving the pointer press. + * @param x [type: number] Pointer x coordinate. + * @param y [type: number] Pointer y coordinate. + */ +static int Script_PointerDown(lua_State* L) +{ + return Script_PointerAction(L, dmRive::PointerAction::POINTER_DOWN); +} - dmhash_t bone_name = dmScript::CheckHashOrString(L, 2); +/** + * Lua wrapper for pointer exit events. + * @name rive.pointer_exit(component, x, y) + * @param url [type: url] Component receiving the pointer leave. + * @param x [type: number] Pointer x coordinate. + * @param y [type: number] Pointer y coordinate. + */ +static int Script_PointerExit(lua_State* L) +{ + return Script_PointerAction(L, dmRive::PointerAction::POINTER_EXIT); +} - dmhash_t instance_id = 0; - if (!CompRiveGetBoneID(component, bone_name, &instance_id)) { - return DM_LUA_ERROR("the bone '%s' could not be found", dmHashReverseSafe64(bone_name)); - } +/** + * Returns the projection matrix in render coordinates. + * @name rive.get_projection_matrix() + * @return matrix [type: vmath.matrix4] Current projection matrix for the window. + */ +static int Script_GetProjectionMatrix(lua_State* L) +{ + DM_LUA_STACK_CHECK(L, 1); - dmScript::PushHash(L, instance_id); - return 1; - } + dmGraphics::HContext graphics_context = dmGraphics::GetInstalledContext(); - static int RiveComp_PointerMove(lua_State* L) - { - DM_LUA_STACK_CHECK(L, 0); + float scale_factor = CompRiveGetDisplayScaleFactor(); + float right = (float) dmGraphics::GetWindowWidth(graphics_context) / scale_factor; + float top = (float) dmGraphics::GetWindowHeight(graphics_context) / scale_factor; - RiveComponent* component = 0; - dmScript::GetComponentFromLua(L, 1, dmRive::RIVE_MODEL_EXT, 0, (void**)&component, 0); - lua_Number x = luaL_checknumber(L, 2); - lua_Number y = luaL_checknumber(L, 3); + dmScript::PushMatrix4(L, dmVMath::Matrix4::orthographic(0, right, 0, top, -1, 1)); - CompRivePointerMove(component, x, y); + return 1; +} - return 0; - } +// This is an "all bets are off" mode. +static int Script_DebugSetBlitMode(lua_State* L) +{ + DM_LUA_STACK_CHECK(L, 0); - static int RiveComp_PointerUp(lua_State* L) + if (!lua_isboolean(L, 1)) { - DM_LUA_STACK_CHECK(L, 0); - - RiveComponent* component = 0; - dmScript::GetComponentFromLua(L, 1, dmRive::RIVE_MODEL_EXT, 0, (void**)&component, 0); - lua_Number x = luaL_checknumber(L, 2); - lua_Number y = luaL_checknumber(L, 3); - - CompRivePointerUp(component, x, y); - - return 0; + return DM_LUA_ERROR("The first argument must be a boolean."); } + bool value = lua_toboolean(L, 1); + CompRiveDebugSetBlitMode(value); + return 0; +} - static int RiveComp_PointerDown(lua_State* L) - { - DM_LUA_STACK_CHECK(L, 0); - - RiveComponent* component = 0; - dmScript::GetComponentFromLua(L, 1, dmRive::RIVE_MODEL_EXT, 0, (void**)&component, 0); - lua_Number x = luaL_checknumber(L, 2); - lua_Number y = luaL_checknumber(L, 3); +// **************************************************************************** - CompRivePointerDown(component, x, y); +template +static int SetListenerCallback(lua_State* L, LISTENER* listener) +{ + if (listener->m_Callback) + dmScript::DestroyCallback(listener->m_Callback); + listener->m_Callback = 0; + if (lua_isnil(L, 1)) + { return 0; } + listener->m_Callback = dmScript::CreateCallback(L, 1); - static int RiveComp_GetTextRun(lua_State* L) + if (!dmScript::IsCallbackValid(listener->m_Callback)) { - DM_LUA_STACK_CHECK(L, 1); - - RiveComponent* component = 0; - dmScript::GetComponentFromLua(L, 1, dmRive::RIVE_MODEL_EXT, 0, (void**)&component, 0); - - const char* name = luaL_checkstring(L, 2); - const char* nested_artboard_path = 0; - - if (lua_isstring(L, 3)) - { - nested_artboard_path = lua_tostring(L, 3); - } - - const char* text_run = CompRiveGetTextRun(component, name, nested_artboard_path); - - if (!text_run) - { - return DM_LUA_ERROR("The text-run '%s' could not be found.", name); - } - - lua_pushstring(L, text_run); - return 1; + listener->m_Callback = 0; + return luaL_error(L, "Failed to create callback"); } + return 0; +} - static int RiveComp_SetTextRun(lua_State* L) - { - DM_LUA_STACK_CHECK(L, 0); +/** + * Sets or clears the global file listener callback. + * @name rive.set_file_listener(callback) + * @param callback [type:function(self, event, data)|nil] Callback invoked for file system events; pass nil to disable. + * + * `self` + * : [type:object] The calling script instance. + * + * `event` + * : [type: string] One of: + * - `onFileLoaded` + * - `onFileDeleted` + * - `onFileError` + * - `onArtboardsListed` + * - `onViewModelsListed` + * - `onViewModelInstanceNamesListed` + * - `onViewModelPropertiesListed` + * - `onViewModelEnumsListed` + * + * `data` + * : [type:table] Additional fields vary by event. Common keys include: + * - `file`: [type:handle] File handle involved in the event. + * - `viewModelName`: [type:string] View model name for the request, when applicable. + * - `instanceNames`: [type:table] Array of instance name strings. + * - `artboardNames`: [type:table] Array of artboard name strings. + * - `properties`: [type:table] Array of property metadata tables. + * - `enums`: [type:table] Array of enum definitions. + * - `error`: [type:string] Error message when a failure occurs. + */ +static int Script_SetFileListener(lua_State* L) +{ + return SetListenerCallback(L, &g_FileListener); +} + +/** + * Sets or clears the artboard listener callback. + * @name rive.set_artboard_listener(callback) + * @param callback [type:function(self, event, data)|nil] Callback invoked for artboard-related events; pass nil to disable. + * + * `self` + * : [type:object] The calling script instance. + * + * `event` + * : [type: string] One of: + * - `onArtboardError` + * - `onDefaultViewModelInfoReceived` + * - `onArtboardDeleted` + * - `onStateMachinesListed` + * + * `data` + * : [type:table] Additional data per event, typically: + * - `artboard`: [type:handle] Artboard handle involved. + * - `viewModelName`: [type:string] View model name for defaults (received event). + * - `instanceName`: [type:string] Instance name for defaults. + * - `stateMachineNames`: [type:table] Array of state machine name strings. + * - `error`: [type:string] Error message when an error event fires. + */ +static int Script_SetArtboardListener(lua_State* L) +{ + return SetListenerCallback(L, &g_ArtboardListener); +} - RiveComponent* component = 0; - dmScript::GetComponentFromLua(L, 1, dmRive::RIVE_MODEL_EXT, 0, (void**)&component, 0); +/** + * Sets or clears the state machine listener callback. + * @name rive.set_state_machine_listener(callback) + * @param callback [type:function(self, event, data)|nil] Callback invoked for state machine events; pass nil to disable. + * + * `self` + * : [type:object] The calling script instance. + * + * `event` + * : [type: string] One of: + * - `onStateMachineError` + * - `onStateMachineDeleted` + * - `onStateMachineSettled` + * + * `data` + * : [type:table] Event-specific details: + * - `stateMachine`: [type:handle] Active state machine handle. + * - `error`: [type:string] Error message when an error occurs. + */ +static int Script_SetStateMachineListener(lua_State* L) +{ + return SetListenerCallback(L, &g_StateMachineListener); +} - const char* name = luaL_checkstring(L, 2); - const char* text_run = luaL_checkstring(L, 3); - const char* nested_artboard_path = 0; +/** + * Sets or clears the view model instance listener callback. + * @name rive.set_view_model_instance_listener(callback) + * @param callback [type:function(self, event, data)|nil] Callback invoked for view model instance events; pass nil to disable. + * + * `self` + * : [type:object] The calling script instance. + * + * `event` + * : [type: string] One of: + * - `onViewModelInstanceError` + * - `onViewModelDeleted` + * - `onViewModelDataReceived` + * - `onViewModelListSizeReceived` + * + * `data` + * : [type:table] Additional payload per event: + * - `viewModel`: [type:handle] Handle of the affected view model instance. + * - `error`: [type:string] Error description when an error fires. + * - `path`: [type:string] Path being inspected when list size arrives. + * - `size`: [type:number] List size value for list-size events. + */ +static int Script_SetViewModelInstanceListener(lua_State* L) +{ + return SetListenerCallback(L, &g_ViewModelInstanceListener); +} - if (lua_isstring(L, 4)) - { - nested_artboard_path = lua_tostring(L, 4); - } +/** + * Sets or clears the render image listener callback. + * @name rive.set_render_image_listener(callback) + * @param callback [type:function(self, event, data)|nil] Callback invoked for render image events; pass nil to disable. + * + * `self` + * : [type:object] The calling script instance. + * + * `event` + * : [type: string] One of: + * - `onRenderImageDecoded` + * - `onRenderImageError` + * - `onRenderImageDeleted` + * + * `data` + * : [type:table] Additional fields: + * - `renderImage`: [type:handle] Handle of the render image. + * - `error`: [type:string] Error message for the failure event. + */ +static int Script_SetRenderImageListener(lua_State* L) +{ + return SetListenerCallback(L, &g_RenderImageListener); +} - if (!CompRiveSetTextRun(component, name, text_run, nested_artboard_path)) - { - return DM_LUA_ERROR("The text-run '%s' could not be found.", name); - } +/** + * Sets or clears the audio source listener callback. + * @name rive.set_audio_source_listener(callback) + * @param callback [type:function(self, event, data)|nil] Callback invoked for audio source events; pass nil to disable. + * + * `self` + * : [type:object] The calling script instance. + * + * `event` + * : [type: string] One of: + * - `onAudioSourceDecoded` + * - `onAudioSourceError` + * - `onAudioSourceDeleted` + * + * `data` + * : [type:table] Additional fields: + * - `audioSource`: [type:handle] Audio source handle for the event. + * - `error`: [type:string] Error message when provided. + */ +static int Script_SetAudioSourceListener(lua_State* L) +{ + return SetListenerCallback(L, &g_AudioSourceListener); +} - return 0; - } +/** + * Sets or clears the font listener callback. + * @name rive.set_font_listener(callback) + * @param callback [type:function(self, event, data)|nil] Callback invoked for font events; pass nil to disable. + * + * `self` + * : [type:object] The calling script instance. + * + * `event` + * : [type: string] One of: + * - `onFontDecoded` + * - `onFontError` + * - `onFontDeleted` + * + * `data` + * : [type:table] Additional fields: + * - `font`: [type:handle] Font handle for the associated event. + * - `error`: [type:string] Error message for failure events. + */ +static int Script_SetFontListener(lua_State* L) +{ + return SetListenerCallback(L, &g_FontListener); +} - static int RiveComp_GetProjectionMatrix(lua_State* L) - { - DM_LUA_STACK_CHECK(L, 1); +// **************************************************************************** - dmGraphics::HContext graphics_context = dmGraphics::GetInstalledContext(); +/** + * Returns the Rive file handle tied to the component. + * @name rive.get_file(component) + * @param url [type: url] Component whose file handle to query. + * @return file_handle [type: FileHandle] Handle identifying the loaded Rive file. + */ +static int Script_GetFile(lua_State* L) +{ + DM_LUA_STACK_CHECK(L, 1); + RiveComponent* component = 0; + dmScript::GetComponentFromLua(L, 1, dmRive::RIVE_MODEL_EXT, 0, (void**)&component, 0); + dmRive::PushFileHandle(L, CompRiveGetFile(component)); + return 1; +} - float scale_factor = CompRiveGetDisplayScaleFactor(); - float right = (float) dmGraphics::GetWindowWidth(graphics_context) / scale_factor; - float top = (float) dmGraphics::GetWindowHeight(graphics_context) / scale_factor; +/** + * Switches the active artboard for the component. + * @name rive.set_artboard(component, name) + * @param url [type: url] Component using the artboard. + * @param name [type: string|nil] Name of the artboard to create and set. Pass nil to create a default artboard. + * @return artboard [type: ArtboardHandle] Old artboard handle + */ +static int Script_SetArtboard(lua_State* L) +{ + DM_LUA_STACK_CHECK(L, 1); + RiveComponent* component = 0; + dmScript::GetComponentFromLua(L, 1, dmRive::RIVE_MODEL_EXT, 0, (void**)&component, 0); + const char* name; + if (lua_isnil(L, 2)) + name = 0; + else + name = luaL_checkstring(L, 2); + rive::ArtboardHandle old_handle = CompRiveSetArtboard(component, name); + dmRive::PushArtboardHandle(L, old_handle); + return 1; +} - dmScript::PushMatrix4(L, dmVMath::Matrix4::orthographic(0, right, 0, top, -1, 1)); +/** + * Queries the current artboard handle for the component. + * @name rive.get_artboard(component) + * @param url [type: url] Component whose artboard handle to return. + * @return artboard [type: ArtboardHandle] Active artboard handle. + */ +static int Script_GetArtboard(lua_State* L) +{ + DM_LUA_STACK_CHECK(L, 1); + RiveComponent* component = 0; + dmScript::GetComponentFromLua(L, 1, dmRive::RIVE_MODEL_EXT, 0, (void**)&component, 0); + dmRive::PushArtboardHandle(L, CompRiveGetArtboard(component)); + return 1; +} - return 1; - } +/** + * Selects a state machine by name on the component. + * @name rive.set_state_machine(component, name) + * @param url [type: url] Component owning the state machine. + * @param name [type: string|nil] Name of the state machine to create and set. Pass nil to create a default state machine. + * @return state_machine [type: StateMachineHandle] Old state machine handle + */ +static int Script_SetStateMachine(lua_State* L) +{ + DM_LUA_STACK_CHECK(L, 1); + RiveComponent* component = 0; + dmScript::GetComponentFromLua(L, 1, dmRive::RIVE_MODEL_EXT, 0, (void**)&component, 0); + const char* name; + if (lua_isnil(L, 2)) + name = 0; + else + name = luaL_checkstring(L, 2); + rive::StateMachineHandle old_handle = CompRiveSetStateMachine(component, name); + dmRive::PushStateMachineHandle(L, old_handle); + return 1; +} - static int RiveComp_SetStateMachineInput(lua_State* L) - { - DM_LUA_STACK_CHECK(L, 0); - - RiveComponent* component = 0; - dmScript::GetComponentFromLua(L, 1, dmRive::RIVE_MODEL_EXT, 0, (void**)&component, 0); - - const char* input_name = luaL_checkstring(L, 2); - const char* nested_artboard_path = 0; // optional - - StateMachineInputData data = {}; - - if (lua_isnumber(L, 3)) - { - data.m_Type = StateMachineInputData::TYPE_NUMBER; - data.m_NumberValue = lua_tonumber(L,3); - } - else if (lua_isboolean(L,3)) - { - data.m_Type = StateMachineInputData::TYPE_BOOL; - data.m_BoolValue = lua_toboolean(L,3); - } - else - { - return DM_LUA_ERROR("Cannot set input '%s' with an unsupported type.", input_name); - } - - if (lua_isstring(L, 4)) - { - nested_artboard_path = lua_tostring(L, 4); - } - - StateMachineInputData::Result res = CompRiveSetStateMachineInput(component, input_name, nested_artboard_path, data); - if (res != StateMachineInputData::RESULT_OK) - { - if (res == StateMachineInputData::RESULT_TYPE_MISMATCH) - { - return DM_LUA_ERROR("Type mismatch for input '%s'.", input_name); - } - assert(res == StateMachineInputData::RESULT_NOT_FOUND); - return DM_LUA_ERROR("The input '%s' could not be found (or an unknown error happened).", input_name); - } - return 0; - } +/** + * Returns the active state machine handle for the component. + * @name rive.get_state_machine(component) + * @param url [type: url] Component whose active state machine to query. + * @return state_machine [type: StateMachineHandle] Current state machine handle. + */ +static int Script_GetStateMachine(lua_State* L) +{ + DM_LUA_STACK_CHECK(L, 1); + RiveComponent* component = 0; + dmScript::GetComponentFromLua(L, 1, dmRive::RIVE_MODEL_EXT, 0, (void**)&component, 0); + dmRive::PushStateMachineHandle(L, CompRiveGetStateMachine(component)); + return 1; +} - static int RiveComp_GetStateMachineInput(lua_State* L) - { - DM_LUA_STACK_CHECK(L, 1); - - RiveComponent* component = 0; - dmScript::GetComponentFromLua(L, 1, dmRive::RIVE_MODEL_EXT, 0, (void**)&component, 0); - - const char* input_name = luaL_checkstring(L, 2); - const char* nested_artboard_path = 0; // optional - - if (lua_isstring(L, 3)) - { - nested_artboard_path = lua_tostring(L, 3); - } - - StateMachineInputData data; - StateMachineInputData::Result res = CompRiveGetStateMachineInput(component, input_name, nested_artboard_path, data); - - if (res != StateMachineInputData::RESULT_OK) - { - if (res == StateMachineInputData::RESULT_TYPE_UNSUPPORTED) - { - return DM_LUA_ERROR("The input '%s' has an unsupported type.", input_name); - } - assert(res == StateMachineInputData::RESULT_NOT_FOUND); - return DM_LUA_ERROR("The input '%s' could not be found (or an unknown error happened).", input_name); - } - - switch(data.m_Type) - { - case StateMachineInputData::TYPE_BOOL: - lua_pushboolean(L, data.m_BoolValue); - break; - case StateMachineInputData::TYPE_NUMBER: - lua_pushnumber(L, data.m_NumberValue); - break; - case StateMachineInputData::TYPE_INVALID: - break; - } - return 1; - } +/** + * Selects a view model instance by name. + * @name rive.set_view_model_instance(component, name) + * @param url [type: url] Component owning the view model instance. + * @param name [type: string] View model instance name to activate. + * @return success [type: boolean] True if the view model instance was activated. + */ +static int Script_SetViewModelInstance(lua_State* L) +{ + DM_LUA_STACK_CHECK(L, 1); + RiveComponent* component = 0; + dmScript::GetComponentFromLua(L, 1, dmRive::RIVE_MODEL_EXT, 0, (void**)&component, 0); + const char* name = luaL_checkstring(L, 2); + bool result = CompRiveSetViewModelInstance(component, name); + lua_pushboolean(L, result); + return 1; +} - const char* GetString(lua_State* L, int index, const char* key, uint32_t* out_length) - { - const char* result = 0; - lua_getfield(L, -1, key); - if (lua_isstring(L, -1)) - { - size_t len = 0; - result = lua_tolstring(L, index, &len); - if (out_length) - *out_length = (uint32_t)len; - } - lua_pop(L, 1); - return result; - } +/** + * Returns the handle of the currently bound view model instance. + * @name rive.get_view_model_instance(component) + * @param url [type: url] Component whose view model instance handle to query. + * @return view_model_instance_handle [type: ViewModelInstanceHandle] Handle for the active view model instance. + */ +static int Script_GetViewModelInstance(lua_State* L) +{ + DM_LUA_STACK_CHECK(L, 1); + RiveComponent* component = 0; + dmScript::GetComponentFromLua(L, 1, dmRive::RIVE_MODEL_EXT, 0, (void**)&component, 0); + dmRive::PushViewModelInstanceHandle(L, CompRiveGetViewModelInstance(component)); + return 1; +} - static int RiveComp_RivSwapAsset(lua_State* L) - { - DM_LUA_STACK_CHECK(L, 0); - - dmhash_t rivc_path_hash = dmScript::CheckHashOrString(L, 1); // path to .rivc - const char* riv_asset_name = luaL_checkstring(L, 2); // Name of asset inside the .riv file - - const char* path = 0; - const char* payload = 0; - uint32_t payload_size = 0; - - luaL_checktype(L, 3, LUA_TTABLE); - lua_pushvalue(L, 3); - - path = GetString(L, -1, "path", 0); - payload = GetString(L, -1, "payload", &payload_size); - - lua_pop(L, 1); - - if (path == 0 && (payload == 0 || payload_size == 0)) - { - return DM_LUA_ERROR("You must specify either a path or a payload"); - } - - // Temporarily get a reference to the file - dmRive::RiveSceneData* resource; - dmResource::Result r = dmResource::Get(g_Factory, rivc_path_hash, (void**)&resource); - if (dmResource::RESULT_OK != r) - { - return DM_LUA_ERROR("Resource was not found: '%s'", dmHashReverseSafe64(rivc_path_hash)); - } - - if (payload) - r = dmRive::ResRiveDataSetAssetFromMemory(resource, riv_asset_name, (void*)payload, payload_size); - else - r = dmRive::ResRiveDataSetAsset(g_Factory, resource, riv_asset_name, path); - - if (dmResource::RESULT_OK != r) - { - if (dmResource::RESULT_NOT_SUPPORTED == r) - { - return DM_LUA_ERROR("Asset type not supported: '%s'", riv_asset_name); - } - - if (payload) - { - return DM_LUA_ERROR("Failed to load payload for asset: '%s'", riv_asset_name); - } - else - { - return DM_LUA_ERROR("Failed to load asset: '%s' with path: '%s'", riv_asset_name, path); - } - } - - dmResource::Release(g_Factory, resource); - return 0; - } - // This is an "all bets are off" mode. - static int RiveComp_DebugSetBlitMode(lua_State* L) - { - DM_LUA_STACK_CHECK(L, 0); - - if (!lua_isboolean(L, 1)) - { - return DM_LUA_ERROR("The first argument must be a boolean."); - } - bool value = lua_toboolean(L, 1); - CompRiveDebugSetBlitMode(value); - return 0; - } +static const luaL_reg RIVE_FUNCTIONS[] = +{ + {"pointer_move", Script_PointerMove}, + {"pointer_up", Script_PointerUp}, + {"pointer_down", Script_PointerDown}, + {"pointer_exit", Script_PointerExit}, + {"get_projection_matrix", Script_GetProjectionMatrix}, + + {"set_file_listener", Script_SetFileListener}, + {"set_artboard_listener", Script_SetArtboardListener}, + {"set_state_machine_listener", Script_SetStateMachineListener}, + {"set_view_model_instance_listener",Script_SetViewModelInstanceListener}, + {"set_render_image_listener", Script_SetRenderImageListener}, + {"set_audio_source_listener", Script_SetAudioSourceListener}, + {"set_font_listener", Script_SetFontListener}, + + {"get_file", Script_GetFile}, + {"set_artboard", Script_SetArtboard}, + {"get_artboard", Script_GetArtboard}, + {"set_state_machine", Script_SetStateMachine}, + {"get_state_machine", Script_GetStateMachine}, + {"set_view_model_instance", Script_SetViewModelInstance}, + {"get_view_model_instance", Script_GetViewModelInstance}, + + // debug + {"debug_set_blit_mode", Script_DebugSetBlitMode}, + + {0, 0} +}; + +void ScriptRegister(lua_State* L, dmResource::HFactory factory) +{ + // Setup the global listeners + rive::rcp queue = dmRiveCommands::GetCommandQueue(); + queue->setGlobalFileListener(&g_FileListener); + queue->setGlobalArtboardListener(&g_ArtboardListener); + queue->setGlobalStateMachineListener(&g_StateMachineListener); + queue->setGlobalViewModelInstanceListener(&g_ViewModelInstanceListener); + queue->setGlobalRenderImageListener(&g_RenderImageListener); + queue->setGlobalAudioSourceListener(&g_AudioSourceListener); + queue->setGlobalFontListener(&g_FontListener); + + dmRive::RegisterScriptRiveHandles(L); + + luaL_register(L, "rive", RIVE_FUNCTIONS); + ScriptCmdRegister(L, factory); + lua_pop(L, 1); + + g_Factory = factory; +} - static const luaL_reg RIVE_FUNCTIONS[] = - { - {"play_anim", RiveComp_PlayAnim}, - {"play_state_machine", RiveComp_PlayStateMachine}, - {"cancel", RiveComp_Cancel}, - {"get_go", RiveComp_GetGO}, - {"pointer_move", RiveComp_PointerMove}, - {"pointer_up", RiveComp_PointerUp}, - {"pointer_down", RiveComp_PointerDown}, - {"set_text_run", RiveComp_SetTextRun}, - {"get_text_run", RiveComp_GetTextRun}, - {"get_projection_matrix", RiveComp_GetProjectionMatrix}, - {"get_state_machine_input", RiveComp_GetStateMachineInput}, - {"set_state_machine_input", RiveComp_SetStateMachineInput}, - {"debug_set_blit_mode", RiveComp_DebugSetBlitMode}, - - {"riv_swap_asset", RiveComp_RivSwapAsset}, - {0, 0} - }; - - extern void ScriptInitializeDataBinding(lua_State* L, dmResource::HFactory factory); - - void ScriptRegister(lua_State* L, dmResource::HFactory factory) - { - luaL_register(L, "rive", RIVE_FUNCTIONS); - ScriptInitializeDataBinding(L, factory); - lua_pop(L, 1); +void ScriptUnregister(lua_State* L, dmResource::HFactory factory) +{ + rive::rcp queue = dmRiveCommands::GetCommandQueue(); + queue->setGlobalFileListener(0); + queue->setGlobalArtboardListener(0); + queue->setGlobalStateMachineListener(0); + queue->setGlobalViewModelInstanceListener(0); + queue->setGlobalRenderImageListener(0); + queue->setGlobalAudioSourceListener(0); + queue->setGlobalFontListener(0); + + ScriptCmdUnregister(L, factory); + g_Factory = 0; +} - g_Factory = factory; - } } #endif // DM_RIVE_UNSUPPORTED diff --git a/defold-rive/src/script_rive.h b/defold-rive/src/script_rive.h index dc5ca099..3a7adf61 100644 --- a/defold-rive/src/script_rive.h +++ b/defold-rive/src/script_rive.h @@ -18,6 +18,7 @@ namespace dmRive { void ScriptRegister(lua_State* L, dmResource::HFactory factory); + void ScriptUnregister(lua_State* L, dmResource::HFactory factory); } #endif // DM_GAMESYS_SCRIPT_RIVE_H diff --git a/defold-rive/src/script_rive_cmd.cpp b/defold-rive/src/script_rive_cmd.cpp new file mode 100644 index 00000000..334d558b --- /dev/null +++ b/defold-rive/src/script_rive_cmd.cpp @@ -0,0 +1,1169 @@ +// Copyright 2021 The Defold Foundation +// Licensed under the Defold License version 1.0 (the "License"); you may not use +// this file except in compliance with the License. +// +// You may obtain a copy of the License, together with FAQs at +// https://www.defold.com/license +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#if !defined(DM_RIVE_UNSUPPORTED) + +#include + +#include +#include +#include + +#include + +#include "script_rive_handles.h" + +#include + +namespace dmRive +{ + +static dmResource::HFactory g_ResourceFactory = 0; + +static bool CheckBoolean(lua_State* L, int index) +{ + if (lua_isboolean(L, index)) + { + return lua_toboolean(L, index); + } + return luaL_error(L, "Argument %d must be a boolean", index); +} + +static void CheckStringOrArtboard(lua_State* L, int index, const char** string, rive::ArtboardHandle* handle) +{ + if (lua_type(L, index) == LUA_TSTRING) + *string = luaL_checkstring(L, index); + else + *handle = CheckArtboardHandle(L, index); +} + +// ************************************************************************************************* + +/** + * Deletes an instantiated artboard. + * @name cmd.deleteArtboard(artboard_handle) + * @param artboard_handle [type: ArtboardHandle] Handle to the artboard that should be removed. + */ +static int Script_deleteArtboard(lua_State* L) +{ + DM_LUA_STACK_CHECK(L, 0); + rive::ArtboardHandle handle = CheckArtboardHandle(L, 1); + rive::rcp queue = dmRiveCommands::GetCommandQueue(); + queue->deleteArtboard(handle); + return 0; +} + +/** + * Returns the artboard handle created for the named view model. + * @name cmd.instantiateArtboardNamed(file_handle, viewmodel_name) + * @param file_handle [type: FileHandle] Handle to a previously loaded Rive file. + * @param viewmodel_name [type: string] Name of the view model to instantiate. + * @return artboard_handle [type: ArtboardHandle] Artboard handle created for the named view model. + */ +static int Script_instantiateArtboardNamed(lua_State* L) +{ + DM_LUA_STACK_CHECK(L, 1); + rive::FileHandle file = CheckFileHandle(L, 1); + const char* viewmodel_name = luaL_checkstring(L, 2); + + rive::rcp queue = dmRiveCommands::GetCommandQueue(); + rive::ArtboardHandle handle = queue->instantiateArtboardNamed(file, viewmodel_name); + + dmRive::PushArtboardHandle(L, handle); + return 1; +} + +/** + * Returns the default artboard handle for the file. + * @name cmd.instantiateDefaultArtboard(file_handle) + * @param file_handle [type: FileHandle] Handle to a previously loaded Rive file. + * @return artboard_handle [type: ArtboardHandle] Default artboard handle for the file. + */ +static int Script_instantiateDefaultArtboard(lua_State* L) +{ + DM_LUA_STACK_CHECK(L, 1); + rive::FileHandle file = CheckFileHandle(L, 1); + + rive::rcp queue = dmRiveCommands::GetCommandQueue(); + rive::ArtboardHandle handle = queue->instantiateDefaultArtboard(file); + + PushArtboardHandle(L, handle); + return 1; +} + +// ******************************************************************************************************* + +/** + * Creates the default state machine for an artboard. + * @name cmd.instantiateDefaultStateMachine(artboard_handle) + * @param artboard_handle [type: ArtboardHandle] Artboard used as the source for the state machine. + * @return state_machine_handle [type: StateMachineHandle] Handle referencing the created state machine. + */ +static int Script_instantiateDefaultStateMachine(lua_State* L) +{ + DM_LUA_STACK_CHECK(L, 1); + rive::ArtboardHandle artboard = CheckArtboardHandle(L, 1); + + rive::rcp queue = dmRiveCommands::GetCommandQueue(); + rive::StateMachineHandle handle = queue->instantiateDefaultStateMachine(artboard); + PushStateMachineHandle(L, handle); + return 1; +} + +/** + * Creates a named state machine for the provided artboard. + * @name cmd.instantiateStateMachineNamed(artboard_handle, name) + * @param artboard_handle [type: ArtboardHandle] Artboard where the state machine resides. + * @param name [type: string] Name to assign to the new state machine. + * @return state_machine_handle [type: StateMachineHandle] Handle referencing the created state machine. + */ +static int Script_instantiateStateMachineNamed(lua_State* L) +{ + DM_LUA_STACK_CHECK(L, 1); + rive::ArtboardHandle artboard = CheckArtboardHandle(L, 1); + const char* name = luaL_checkstring(L, 2); + + rive::rcp queue = dmRiveCommands::GetCommandQueue(); + rive::StateMachineHandle handle = queue->instantiateStateMachineNamed(artboard, name); + PushStateMachineHandle(L, handle); + return 1; +} + +/** + * Advances the state machine by the requested delta time. + * @name cmd.advanceStateMachine(state_machine_handle, delta) + * @param state_machine_handle [type: StateMachineHandle] State machine to advance. + * @param delta [type: number] Time in seconds to advance the state machine. + */ +static int Script_advanceStateMachine(lua_State* L) +{ + DM_LUA_STACK_CHECK(L, 0); + rive::StateMachineHandle state_machine = CheckStateMachineHandle(L, 1); + float dt = (float)luaL_checknumber(L, 2); + + rive::rcp queue = dmRiveCommands::GetCommandQueue(); + queue->advanceStateMachine(state_machine, dt); + return 0; +} + +/** + * Deletes a created state machine. + * @name cmd.deleteStateMachine(state_machine_handle) + * @param state_machine_handle [type: StateMachineHandle] Handle to the state machine to delete. + */ +static int Script_deleteStateMachine(lua_State* L) +{ + DM_LUA_STACK_CHECK(L, 0); + rive::StateMachineHandle handle = CheckStateMachineHandle(L, 1); + rive::rcp queue = dmRiveCommands::GetCommandQueue(); + queue->deleteStateMachine(handle); + return 0; +} + +// ******************************************************************************************************* + +/** + * Returns a blank view model instance handle for the given artboard or view model. + * @name cmd.instantiateBlankViewModelInstance(file_handle, artboard_or_viewmodel) + * @param file_handle [type: FileHandle] Handle to a previously loaded Rive file. + * @param artboard_or_viewmodel [type: ArtboardHandle|string] Artboard handle or view model name that identifies where to instantiate. + * @return view_model_instance_handle [type: ViewModelInstanceHandle] Blank view model instance handle. + */ +static int Script_instantiateBlankViewModelInstance(lua_State* L) +{ + DM_LUA_STACK_CHECK(L, 1); + rive::FileHandle file = CheckFileHandle(L, 1); + + if (lua_isnil(L, 2) || lua_isnone(L, 2)) + { + return luaL_error(L, "Argument #2 must be an integer (artboard handle) or a string (view model name)"); + } + + rive::ArtboardHandle artboard = 0; + const char* viewmodel_name = 0; + CheckStringOrArtboard(L, 2, &viewmodel_name, &artboard); + + rive::rcp queue = dmRiveCommands::GetCommandQueue(); + rive::ViewModelInstanceHandle handle = 0; + if (viewmodel_name) + handle = queue->instantiateBlankViewModelInstance(file, viewmodel_name); + else + handle = queue->instantiateBlankViewModelInstance(file, artboard); + + PushViewModelInstanceHandle(L, handle); + return 1; +} + +/** + * Returns a default-populated view model instance handle for the given artboard or view model. + * @name cmd.instantiateDefaultViewModelInstance(file_handle, artboard_or_viewmodel) + * @param file_handle [type: FileHandle] Handle to a previously loaded Rive file. + * @param artboard_or_viewmodel [type: ArtboardHandle|string] Artboard handle or view model name the instance should derive from. + * @return view_model_instance_handle [type: ViewModelInstanceHandle] Default view model instance handle. + */ +static int Script_instantiateDefaultViewModelInstance(lua_State* L) +{ + DM_LUA_STACK_CHECK(L, 1); + rive::FileHandle file = CheckFileHandle(L, 1); + + if (lua_isnil(L, 2) || lua_isnone(L, 2)) + { + return luaL_error(L, "Argument #2 must be an integer (artboard handle) or a string (view model name)"); + } + + rive::ArtboardHandle artboard = 0; + const char* viewmodel_name = 0; + CheckStringOrArtboard(L, 2, &viewmodel_name, &artboard); + + rive::rcp queue = dmRiveCommands::GetCommandQueue(); + rive::ViewModelInstanceHandle handle = 0; + if (viewmodel_name) + handle = queue->instantiateDefaultViewModelInstance(file, viewmodel_name); + else + handle = queue->instantiateDefaultViewModelInstance(file, artboard); + + PushViewModelInstanceHandle(L, handle); + return 1; +} + +/** + * Creates a named view model instance and returns its handle. + * @name cmd.instantiateViewModelInstanceNamed(file_handle, artboard_or_viewmodel, instance_name) + * @param file_handle [type: FileHandle] Handle to a previously loaded Rive file. + * @param artboard_or_viewmodel [type: ArtboardHandle|string] Artboard handle or view model name that will host the instance. + * @param instance_name [type: string] Name to assign to the new view model instance. + * @return view_model_instance_handle [type: ViewModelInstanceHandle] Named view model instance handle. + */ +static int Script_instantiateViewModelInstanceNamed(lua_State* L) +{ + DM_LUA_STACK_CHECK(L, 1); + rive::FileHandle file = CheckFileHandle(L, 1); + + if (lua_isnil(L, 2) || lua_isnone(L, 2)) + { + return luaL_error(L, "Argument #2 must be an integer (artboard handle) or a string (view model name)"); + } + + rive::ArtboardHandle artboard = 0; + const char* viewmodel_name = 0; + CheckStringOrArtboard(L, 2, &viewmodel_name, &artboard); + + const char* view_model_instance_name = luaL_checkstring(L, 3); + + rive::rcp queue = dmRiveCommands::GetCommandQueue(); + rive::ViewModelInstanceHandle handle = 0; + if (viewmodel_name) + handle = queue->instantiateViewModelInstanceNamed(file, viewmodel_name, view_model_instance_name); + else + handle = queue->instantiateViewModelInstanceNamed(file, artboard, view_model_instance_name); + + PushViewModelInstanceHandle(L, handle); + return 1; +} + +/** + * Returns a handle to the nested view model at the given path. + * @name cmd.referenceNestedViewModelInstance(view_model_handle, path) + * @param view_model_handle [type: ViewModelInstanceHandle] Parent view model instance handle. + * @param path [type: string] Dot-delimited path to the nested view model. + * @return view_model_handle [type: ViewModelInstanceHandle] Handle to the nested view model. + */ +static int Script_referenceNestedViewModelInstance(lua_State* L) +{ + DM_LUA_STACK_CHECK(L, 1); + rive::ViewModelInstanceHandle handle = CheckViewModelInstanceHandle(L, 1); + const char* path = luaL_checkstring(L, 2); + + rive::rcp queue = dmRiveCommands::GetCommandQueue(); + handle = queue->referenceNestedViewModelInstance(handle, path); + PushViewModelInstanceHandle(L, handle); + return 1; +} + +/** + * Returns the handle for the list entry at the specified path and index. + * @name cmd.referenceListViewModelInstance(view_model_handle, path, index) + * @param view_model_handle [type: ViewModelInstanceHandle] Parent view model instance handle. + * @param path [type: string] Dot-delimited path to the list view model. + * @param index [type: number] Index within the list entry to reference. + * @return view_model_handle [type: ViewModelInstanceHandle] Handle to the referenced list entry. + */ +static int Script_referenceListViewModelInstance(lua_State* L) +{ + DM_LUA_STACK_CHECK(L, 1); + rive::ViewModelInstanceHandle handle = CheckViewModelInstanceHandle(L, 1); + const char* path = luaL_checkstring(L, 2); + int index = luaL_checkinteger(L, 3); + + rive::rcp queue = dmRiveCommands::GetCommandQueue(); + handle = queue->referenceListViewModelInstance(handle, path, index); + PushViewModelInstanceHandle(L, handle); + return 1; +} + +/** + * Replaces the nested view model at the given path with the supplied handle. + * @name cmd.setViewModelInstanceNestedViewModel(view_model_handle, path, nested_handle) + * @param view_model_handle [type: ViewModelInstanceHandle] View model instance whose nested child is updated. + * @param path [type: string] Path to the nested view model. + * @param nested_handle [type: ViewModelInstanceHandle] Handle of the nested view model to attach. + */ +static int Script_setViewModelInstanceNestedViewModel(lua_State* L) +{ + DM_LUA_STACK_CHECK(L, 0); + rive::ViewModelInstanceHandle handle = CheckViewModelInstanceHandle(L, 1); + rive::ViewModelInstanceHandle value = CheckViewModelInstanceHandle(L, 3); + const char* path = luaL_checkstring(L, 2); + + rive::rcp queue = dmRiveCommands::GetCommandQueue(); + queue->setViewModelInstanceNestedViewModel(handle, path, value); + return 0; +} + +/** + * Inserts a nested view model into the list at the given index. + * @name cmd.insertViewModelInstanceListViewModel(view_model_handle, path, nested_handle, index) + * @param view_model_handle [type: ViewModelInstanceHandle] View model instance owning the list. + * @param path [type: string] Path to the target list. + * @param nested_handle [type: ViewModelInstanceHandle] Handle of the view model to insert. + * @param index [type: number] Destination index for the insertion. + */ +static int Script_insertViewModelInstanceListViewModel(lua_State* L) +{ + DM_LUA_STACK_CHECK(L, 0); + rive::ViewModelInstanceHandle handle = CheckViewModelInstanceHandle(L, 1); + rive::ViewModelInstanceHandle value = CheckViewModelInstanceHandle(L, 3); + const char* path = luaL_checkstring(L, 2); + int index = luaL_checkinteger(L, 4); + + rive::rcp queue = dmRiveCommands::GetCommandQueue(); + queue->insertViewModelInstanceListViewModel(handle, path, value, index); + return 0; +} + +/** + * Appends a nested view model to the list at the specified path. + * @name cmd.appendViewModelInstanceListViewModel(view_model_handle, path, nested_handle) + * @param view_model_handle [type: ViewModelInstanceHandle] View model instance owning the list. + * @param path [type: string] Path to the target list. + * @param nested_handle [type: ViewModelInstanceHandle] Handle of the view model to append. + */ +static int Script_appendViewModelInstanceListViewModel(lua_State* L) +{ + DM_LUA_STACK_CHECK(L, 0); + rive::ViewModelInstanceHandle handle = CheckViewModelInstanceHandle(L, 1); + rive::ViewModelInstanceHandle value = CheckViewModelInstanceHandle(L, 3); + const char* path = luaL_checkstring(L, 2); + + rive::rcp queue = dmRiveCommands::GetCommandQueue(); + queue->appendViewModelInstanceListViewModel(handle, path, value); + return 0; +} + +/** + * Removes the entry at the supplied index from the nested list. + * @name cmd.removeViewModelInstanceListViewModelIndex(view_model_handle, path, index) + * @param view_model_handle [type: ViewModelInstanceHandle] View model instance owning the list. + * @param path [type: string] Path to the target list. + * @param index [type: number] Index of the entry to remove. + */ +static int Script_removeViewModelInstanceListViewModelIndex(lua_State* L) +{ + DM_LUA_STACK_CHECK(L, 0); + rive::ViewModelInstanceHandle handle = CheckViewModelInstanceHandle(L, 1); + const char* path = luaL_checkstring(L, 2); + int index = luaL_checkinteger(L, 3); + + rive::rcp queue = dmRiveCommands::GetCommandQueue(); + queue->removeViewModelInstanceListViewModel(handle, path, index, RIVE_NULL_HANDLE); + return 0; +} + +/** + * Removes the specified nested view model from the list at the path. + * @name cmd.removeViewModelInstanceListViewModel(view_model_handle, path, nested_handle) + * @param view_model_handle [type: ViewModelInstanceHandle] View model instance owning the list. + * @param path [type: string] Path to the target list. + * @param nested_handle [type: ViewModelInstanceHandle] Handle of the view model to remove. + */ +static int Script_removeViewModelInstanceListViewModel(lua_State* L) +{ + DM_LUA_STACK_CHECK(L, 0); + rive::ViewModelInstanceHandle handle = CheckViewModelInstanceHandle(L, 1); + rive::ViewModelInstanceHandle value = CheckViewModelInstanceHandle(L, 3); + const char* path = luaL_checkstring(L, 2); + + rive::rcp queue = dmRiveCommands::GetCommandQueue(); + queue->removeViewModelInstanceListViewModel(handle, path, value); + return 0; +} + +/** + * Deletes the view model instance handle. + * @name cmd.deleteViewModelInstance(view_model_handle) + * @param view_model_handle [type: ViewModelInstanceHandle] View model instance to delete. + */ +static int Script_deleteViewModelInstance(lua_State* L) +{ + DM_LUA_STACK_CHECK(L, 0); + rive::ViewModelInstanceHandle handle = CheckViewModelInstanceHandle(L, 1); + + rive::rcp queue = dmRiveCommands::GetCommandQueue(); + queue->deleteViewModelInstance(handle); + return 0; +} + +/** + * Swaps two entries in the nested list. + * @name cmd.swapViewModelInstanceListValues(view_model_handle, path, indexa, indexb) + * @param view_model_handle [type: ViewModelInstanceHandle] View model instance that owns the list. + * @param path [type: string] Path to the nested list. + * @param indexa [type: number] First index to swap. + * @param indexb [type: number] Second index to swap. + */ +static int Script_swapViewModelInstanceListValues(lua_State* L) +{ + DM_LUA_STACK_CHECK(L, 0); + rive::ViewModelInstanceHandle handle = CheckViewModelInstanceHandle(L, 1); + const char* path = luaL_checkstring(L, 2); + int indexa = luaL_checkinteger(L, 3); + int indexb = luaL_checkinteger(L, 4); + + rive::rcp queue = dmRiveCommands::GetCommandQueue(); + queue->swapViewModelInstanceListValues(handle, path, indexa, indexb); + return 0; +} + +// ***************************************************************************************** + + +/** + * Binds the state machine to the provided view model instance. + * @name cmd.bindViewModelInstance(state_machine_handle, view_model_handle) + * @param state_machine_handle [type: StateMachineHandle] State machine handle. + * @param view_model_handle [type: ViewModelInstanceHandle] View model instance handle. + */ +static int Script_bindViewModelInstance(lua_State* L) +{ + DM_LUA_STACK_CHECK(L, 0); + rive::StateMachineHandle state_machine = CheckStateMachineHandle(L, 1); + rive::ViewModelInstanceHandle view_model = CheckViewModelInstanceHandle(L, 2); + + rive::rcp queue = dmRiveCommands::GetCommandQueue(); + queue->bindViewModelInstance(state_machine, view_model); + return 0; +} + + +// ***************************************************************************************** + + +/** + * Fires a trigger on the view model instance. + * @name cmd.fireViewModelTrigger(view_model_handle, trigger_path) + * @param view_model_handle [type: ViewModelInstanceHandle] View model instance handle. + * @param trigger_path [type: string] Trigger path to activate. + */ +static int Script_fireViewModelTrigger(lua_State* L) +{ + DM_LUA_STACK_CHECK(L, 0); + rive::ViewModelInstanceHandle handle = CheckViewModelInstanceHandle(L, 1); + const char* path = luaL_checkstring(L, 2); + + rive::rcp queue = dmRiveCommands::GetCommandQueue(); + queue->fireViewModelTrigger(handle, path); + return 0; +} + +/** + * Updates the boolean property at the path. + * @name cmd.setViewModelInstanceBool(view_model_handle, path, value) + * @param view_model_handle [type: ViewModelInstanceHandle] View model instance handle. + * @param path [type: string] Path to the boolean property. + * @param value [type: boolean] New boolean value. + */ +static int Script_setViewModelInstanceBool(lua_State* L) +{ + DM_LUA_STACK_CHECK(L, 0); + rive::ViewModelInstanceHandle handle = CheckViewModelInstanceHandle(L, 1); + bool value = CheckBoolean(L, 3); + const char* path = luaL_checkstring(L, 2); + + rive::rcp queue = dmRiveCommands::GetCommandQueue(); + queue->setViewModelInstanceBool(handle, path, value); + return 0; +} + +/** + * Updates the numeric property at the path. + * @name cmd.setViewModelInstanceNumber(view_model_handle, path, value) + * @param view_model_handle [type: ViewModelInstanceHandle] View model instance handle. + * @param path [type: string] Path to the numeric property. + * @param value [type: number] New numeric value. + */ +static int Script_setViewModelInstanceNumber(lua_State* L) +{ + DM_LUA_STACK_CHECK(L, 0); + rive::ViewModelInstanceHandle handle = CheckViewModelInstanceHandle(L, 1); + lua_Number value = luaL_checknumber(L, 3); + const char* path = luaL_checkstring(L, 2); + + rive::rcp queue = dmRiveCommands::GetCommandQueue(); + queue->setViewModelInstanceNumber(handle, path, value); + return 0; +} + +/** + * Updates the color property using the supplied vector. + * @name cmd.setViewModelInstanceColor(view_model_handle, path, vector4_color) + * @param view_model_handle [type: ViewModelInstanceHandle] View model instance handle. + * @param path [type: string] Path to the color property. + * @param vector4_color [type: vector4] Color encoded as a Defold Vector4 (WXYZ). + */ +static int Script_setViewModelInstanceColor(lua_State* L) +{ + DM_LUA_STACK_CHECK(L, 0); + rive::ViewModelInstanceHandle handle = CheckViewModelInstanceHandle(L, 1); + const char* path = luaL_checkstring(L, 2); + dmVMath::Vector4* color = dmScript::CheckVector4(L, 3); + rive::ColorInt value = rive::colorARGB(255 * color->getW(), 255 * color->getX(), 255 * color->getY(), 255 * color->getZ()); + + rive::rcp queue = dmRiveCommands::GetCommandQueue(); + queue->setViewModelInstanceColor(handle, path, value); + return 0; +} + +/** + * Updates the enum property at the path. + * @name cmd.setViewModelInstanceEnum(view_model_handle, path, enum_string) + * @param view_model_handle [type: ViewModelInstanceHandle] View model instance handle. + * @param path [type: string] Path to the enum property. + * @param enum_string [type: string] Enum name to select. + */ +static int Script_setViewModelInstanceEnum(lua_State* L) +{ + DM_LUA_STACK_CHECK(L, 0); + rive::ViewModelInstanceHandle handle = CheckViewModelInstanceHandle(L, 1); + const char* path = luaL_checkstring(L, 2); + const char* value = luaL_checkstring(L, 3); + + rive::rcp queue = dmRiveCommands::GetCommandQueue(); + queue->setViewModelInstanceEnum(handle, path, value); + return 0; +} + +/** + * Updates the string property at the path. + * @name cmd.setViewModelInstanceString(view_model_handle, path, string_value) + * @param view_model_handle [type: ViewModelInstanceHandle] View model instance handle. + * @param path [type: string] Path to the string property. + * @param string_value [type: string] New string value. + */ +static int Script_setViewModelInstanceString(lua_State* L) +{ + DM_LUA_STACK_CHECK(L, 0); + rive::ViewModelInstanceHandle handle = CheckViewModelInstanceHandle(L, 1); + const char* path = luaL_checkstring(L, 2); + const char* value = luaL_checkstring(L, 3); + + rive::rcp queue = dmRiveCommands::GetCommandQueue(); + queue->setViewModelInstanceString(handle, path, value); + return 0; +} + +/** + * Updates the image property at the path. + * @name cmd.setViewModelInstanceImage(view_model_handle, path, render_image_handle) + * @param view_model_handle [type: ViewModelInstanceHandle] View model instance handle. + * @param path [type: string] Path to the image property. + * @param render_image_handle [type: RenderImageHandle] Render image handle to assign. + */ +static int Script_setViewModelInstanceImage(lua_State* L) +{ + DM_LUA_STACK_CHECK(L, 0); + rive::ViewModelInstanceHandle handle = CheckViewModelInstanceHandle(L, 1); + rive::RenderImageHandle value = CheckRenderImageHandle(L, 3); + const char* path = luaL_checkstring(L, 2); + + rive::rcp queue = dmRiveCommands::GetCommandQueue(); + queue->setViewModelInstanceImage(handle, path, value); + return 0; +} + +/** + * Updates the artboard reference at the path. + * @name cmd.setViewModelInstanceArtboard(view_model_handle, path, artboard_handle) + * @param view_model_handle [type: ViewModelInstanceHandle] View model instance handle. + * @param path [type: string] Path to the artboard reference. + * @param artboard_handle [type: ArtboardHandle] Artboard handle to assign. + */ +static int Script_setViewModelInstanceArtboard(lua_State* L) +{ + DM_LUA_STACK_CHECK(L, 0); + rive::ViewModelInstanceHandle handle = CheckViewModelInstanceHandle(L, 1); + rive::ArtboardHandle value = CheckArtboardHandle(L, 3); + const char* path = luaL_checkstring(L, 2); + + rive::rcp queue = dmRiveCommands::GetCommandQueue(); + queue->setViewModelInstanceArtboard(handle, path, value); + return 0; +} + +/** + * Subscribes for updates to the named property. + * @name cmd.subscribeToViewModelProperty(view_model_handle, path, data_type) + * @param view_model_handle [type: ViewModelInstanceHandle] View model instance handle. + * @param path [type: string] Path to the property to subscribe. + * @param data_type [type: enum] Data type identifier from rive::DataType. + */ +static int Script_subscribeToViewModelProperty(lua_State* L) +{ + DM_LUA_STACK_CHECK(L, 0); + rive::ViewModelInstanceHandle handle = CheckViewModelInstanceHandle(L, 1); + const char* path = luaL_checkstring(L, 2); + rive::DataType type = (rive::DataType)luaL_checkinteger(L, 3); + + rive::rcp queue = dmRiveCommands::GetCommandQueue(); + queue->subscribeToViewModelProperty(handle, path, type); + return 0; +} + +/** + * Cancels a previous subscription. + * @name cmd.unsubscribeToViewModelProperty(view_model_handle, path, data_type) + * @param view_model_handle [type: ViewModelInstanceHandle] View model instance handle. + * @param path [type: string] Path to the property. + * @param data_type [type: enum] Data type identifier previously subscribed. + */ +static int Script_unsubscribeToViewModelProperty(lua_State* L) +{ + DM_LUA_STACK_CHECK(L, 0); + rive::ViewModelInstanceHandle handle = CheckViewModelInstanceHandle(L, 1); + const char* path = luaL_checkstring(L, 2); + rive::DataType type = (rive::DataType)luaL_checkinteger(L, 3); + + rive::rcp queue = dmRiveCommands::GetCommandQueue(); + queue->unsubscribeToViewModelProperty(handle, path, type); + return 0; +} + +// ***************************************************************************************** + +/** + * Loads Rive bytes and returns a file handle. + * @name cmd.loadFile(riv_bytes) + * @param riv_bytes [type: string] Raw Rive file data. + * @return file_handle [type: FileHandle] Loaded Rive file handle. + */ +static int Script_loadFile(lua_State* L) +{ + DM_LUA_STACK_CHECK(L, 1); + size_t data_length = 0; + const uint8_t* data = (const uint8_t*)luaL_checklstring(L, 1, &data_length); + std::vector rivBytes(data, data + data_length); + + rive::rcp queue = dmRiveCommands::GetCommandQueue(); + rive::FileHandle file = queue->loadFile(rivBytes); + + PushFileHandle(L, file); + return 1; +} + +/** + * Deletes the runtime file handle. + * @name cmd.deleteFile(file_handle) + * @param file_handle [type: FileHandle] File handle to delete. + */ +static int Script_deleteFile(lua_State* L) +{ + DM_LUA_STACK_CHECK(L, 0); + rive::FileHandle handle = CheckFileHandle(L, 1); + rive::rcp queue = dmRiveCommands::GetCommandQueue(); + queue->deleteFile(handle); + return 0; +} + +/** + * Decodes image bytes and returns a render image handle. + * @name cmd.decodeImage(image_bytes) + * @param image_bytes [type: string] Encoded image data. + * @return render_image_handle [type: RenderImageHandle] Decoded render image handle. + */ +static int Script_decodeImage(lua_State* L) +{ + DM_LUA_STACK_CHECK(L, 1); + size_t data_length = 0; + const uint8_t* data = (const uint8_t*)luaL_checklstring(L, 1, &data_length); + std::vector encodedBytes(data, data + data_length); + + rive::rcp queue = dmRiveCommands::GetCommandQueue(); + rive::RenderImageHandle image = queue->decodeImage(encodedBytes); + + PushRenderImageHandle(L, image); + return 1; +} + +/** + * Deletes the render image handle. + * @name cmd.deleteImage(image_handle) + * @param image_handle [type: RenderImageHandle] Render image handle to delete. + */ +static int Script_deleteImage(lua_State* L) +{ + DM_LUA_STACK_CHECK(L, 0); + rive::RenderImageHandle handle = CheckRenderImageHandle(L, 1); + rive::rcp queue = dmRiveCommands::GetCommandQueue(); + queue->deleteImage(handle); + return 0; +} + +/** + * Decodes audio bytes and returns an audio source handle. + * @name cmd.decodeAudio(audio_bytes) + * @param audio_bytes [type: string] Encoded audio data. + * @return audio_handle [type: AudioSourceHandle] Decoded audio source handle. + */ +static int Script_decodeAudio(lua_State* L) +{ + DM_LUA_STACK_CHECK(L, 1); + size_t data_length = 0; + const uint8_t* data = (const uint8_t*)luaL_checklstring(L, 1, &data_length); + std::vector encodedBytes(data, data + data_length); + + rive::rcp queue = dmRiveCommands::GetCommandQueue(); + rive::AudioSourceHandle handle = queue->decodeAudio(encodedBytes); + + PushAudioSourceHandle(L, handle); + return 1; +} + +/** + * Deletes the audio source handle. + * @name cmd.deleteAudio(audio_handle) + * @param audio_handle [type: AudioSourceHandle] Audio source handle to delete. + */ +static int Script_deleteAudio(lua_State* L) +{ + DM_LUA_STACK_CHECK(L, 0); + rive::AudioSourceHandle handle = CheckAudioSourceHandle(L, 1); + rive::rcp queue = dmRiveCommands::GetCommandQueue(); + queue->deleteAudio(handle); + return 0; +} + +/** + * Decodes font bytes and returns a font handle. + * @name cmd.decodeFont(font_bytes) + * @param font_bytes [type: string] Encoded font data. + * @return font_handle [type: FontHandle] Decoded font handle. + */ +static int Script_decodeFont(lua_State* L) +{ + DM_LUA_STACK_CHECK(L, 1); + size_t data_length = 0; + const uint8_t* data = (const uint8_t*)luaL_checklstring(L, 1, &data_length); + std::vector encodedBytes(data, data + data_length); + + rive::rcp queue = dmRiveCommands::GetCommandQueue(); + rive::FontHandle handle = queue->decodeFont(encodedBytes); + + PushFontHandle(L, handle); + return 1; +} + +/** + * Deletes the font handle. + * @name cmd.deleteFont(font_handle) + * @param font_handle [type: FontHandle] Font handle to delete. + */ +static int Script_deleteFont(lua_State* L) +{ + DM_LUA_STACK_CHECK(L, 0); + rive::FontHandle handle = CheckFontHandle(L, 1); + rive::rcp queue = dmRiveCommands::GetCommandQueue(); + queue->deleteFont(handle); + return 0; +} + +/** + * Registers a global image asset. + * @name cmd.addGlobalImageAsset(asset_name, render_image_handle) + * @param asset_name [type: string] Name used to reference the global asset. + * @param render_image_handle [type: RenderImageHandle] Render image handle to register. + */ +static int Script_addGlobalImageAsset(lua_State* L) +{ + DM_LUA_STACK_CHECK(L, 0); + const char* name = luaL_checkstring(L, 1); + rive::RenderImageHandle handle = CheckRenderImageHandle(L, 2); + rive::rcp queue = dmRiveCommands::GetCommandQueue(); + queue->addGlobalImageAsset(name, handle); + return 0; +} + +/** + * Unregisters the named global image asset. + * @name cmd.removeGlobalImageAsset(asset_name) + * @param asset_name [type: string] Name of the asset to remove. + */ +static int Script_removeGlobalImageAsset(lua_State* L) +{ + DM_LUA_STACK_CHECK(L, 0); + const char* name = luaL_checkstring(L, 1); + rive::rcp queue = dmRiveCommands::GetCommandQueue(); + queue->removeGlobalImageAsset(name); + return 0; +} + +/** + * Registers a global font asset. + * @name cmd.addGlobalFontAsset(asset_name, font_handle) + * @param asset_name [type: string] Name used to reference the global font. + * @param font_handle [type: FontHandle] Font handle to register. + */ +static int Script_addGlobalFontAsset(lua_State* L) +{ + DM_LUA_STACK_CHECK(L, 0); + const char* name = luaL_checkstring(L, 1); + rive::FontHandle handle = CheckFontHandle(L, 2); + rive::rcp queue = dmRiveCommands::GetCommandQueue(); + queue->addGlobalFontAsset(name, handle); + return 0; +} + +/** + * Unregisters the named global font asset. + * @name cmd.removeGlobalFontAsset(asset_name) + * @param asset_name [type: string] Name of the font asset to remove. + */ +static int Script_removeGlobalFontAsset(lua_State* L) +{ + DM_LUA_STACK_CHECK(L, 0); + const char* name = luaL_checkstring(L, 1); + rive::rcp queue = dmRiveCommands::GetCommandQueue(); + queue->removeGlobalFontAsset(name); + return 0; +} + +/** + * Registers a global audio asset. + * @name cmd.addGlobalAudioAsset(asset_name, audio_handle) + * @param asset_name [type: string] Name used to reference the global audio. + * @param audio_handle [type: AudioSourceHandle] Audio source handle to register. + */ +static int Script_addGlobalAudioAsset(lua_State* L) +{ + DM_LUA_STACK_CHECK(L, 0); + const char* name = luaL_checkstring(L, 1); + rive::AudioSourceHandle handle = CheckAudioSourceHandle(L, 2); + rive::rcp queue = dmRiveCommands::GetCommandQueue(); + queue->addGlobalAudioAsset(name, handle); + return 0; +} + +/** + * Unregisters the named global audio asset. + * @name cmd.removeGlobalAudioAsset(asset_name) + * @param asset_name [type: string] Name of the audio asset to remove. + */ +static int Script_removeGlobalAudioAsset(lua_State* L) +{ + DM_LUA_STACK_CHECK(L, 0); + const char* name = luaL_checkstring(L, 1); + rive::rcp queue = dmRiveCommands::GetCommandQueue(); + queue->removeGlobalAudioAsset(name); + return 0; +} + +// ***************************************************************************************** + +/** + * Requests view model names for the file. + * @name cmd.requestViewModelNames(file_handle) + * @param file_handle [type: FileHandle] File handle whose view models to query. + */ +static int Script_requestViewModelNames(lua_State* L) +{ + DM_LUA_STACK_CHECK(L, 0); + rive::FileHandle file = CheckFileHandle(L, 1); + dmRiveCommands::GetCommandQueue()->requestViewModelNames(file); + return 0; +} + +/** + * Requests artboard names for the file. + * @name cmd.requestArtboardNames(file_handle) + * @param file_handle [type: FileHandle] File handle whose artboards to query. + */ +static int Script_requestArtboardNames(lua_State* L) +{ + DM_LUA_STACK_CHECK(L, 0); + rive::FileHandle file = CheckFileHandle(L, 1); + dmRiveCommands::GetCommandQueue()->requestArtboardNames(file); + return 0; +} + +/** + * Requests enum definitions for the file. + * @name cmd.requestViewModelEnums(file_handle) + * @param file_handle [type: FileHandle] File handle whose enums to query. + */ +static int Script_requestViewModelEnums(lua_State* L) +{ + DM_LUA_STACK_CHECK(L, 0); + rive::FileHandle file = CheckFileHandle(L, 1); + dmRiveCommands::GetCommandQueue()->requestViewModelEnums(file); + return 0; +} + +/** + * Requests property definitions for the view model. + * @name cmd.requestViewModelPropertyDefinitions(file_handle, viewmodel_name) + * @param file_handle [type: FileHandle] File handle whose view models to query. + * @param viewmodel_name [type: string] View model name whose property metadata to request. + */ +static int Script_requestViewModelPropertyDefinitions(lua_State* L) +{ + DM_LUA_STACK_CHECK(L, 0); + rive::FileHandle file = CheckFileHandle(L, 1); + const char* viewmodel_name = luaL_checkstring(L, 2); + dmRiveCommands::GetCommandQueue()->requestViewModelPropertyDefinitions(file, viewmodel_name); + return 0; +} + +/** + * Requests instance names for the view model. + * @name cmd.requestViewModelInstanceNames(file_handle, viewmodel_name) + * @param file_handle [type: FileHandle] File handle whose view models to query. + * @param viewmodel_name [type: string] View model name to inspect. + */ +static int Script_requestViewModelInstanceNames(lua_State* L) +{ + DM_LUA_STACK_CHECK(L, 0); + rive::FileHandle file = CheckFileHandle(L, 1); + const char* viewmodel_name = luaL_checkstring(L, 2); + dmRiveCommands::GetCommandQueue()->requestViewModelInstanceNames(file, viewmodel_name); + return 0; +} + +/** + * Requests the boolean value for the property. + * @name cmd.requestViewModelInstanceBool(instance_handle, property_name) + * @param instance_handle [type: ViewModelInstanceHandle] View model instance handle. + * @param property_name [type: string] Name of the bool property. + */ +static int Script_requestViewModelInstanceBool(lua_State* L) +{ + DM_LUA_STACK_CHECK(L, 0); + rive::ViewModelInstanceHandle handle = CheckViewModelInstanceHandle(L, 1); + const char* viewmodel_name = luaL_checkstring(L, 2); + dmRiveCommands::GetCommandQueue()->requestViewModelInstanceBool(handle, viewmodel_name); + return 0; +} + +/** + * Requests the numeric value for the property. + * @name cmd.requestViewModelInstanceNumber(instance_handle, property_name) + * @param instance_handle [type: ViewModelInstanceHandle] View model instance handle. + * @param property_name [type: string] Name of the numeric property. + */ +static int Script_requestViewModelInstanceNumber(lua_State* L) +{ + DM_LUA_STACK_CHECK(L, 0); + rive::ViewModelInstanceHandle handle = CheckViewModelInstanceHandle(L, 1); + const char* viewmodel_name = luaL_checkstring(L, 2); + dmRiveCommands::GetCommandQueue()->requestViewModelInstanceNumber(handle, viewmodel_name); + return 0; +} + +/** + * Requests the color value for the property. + * @name cmd.requestViewModelInstanceColor(instance_handle, property_name) + * @param instance_handle [type: ViewModelInstanceHandle] View model instance handle. + * @param property_name [type: string] Name of the color property. + */ +static int Script_requestViewModelInstanceColor(lua_State* L) +{ + DM_LUA_STACK_CHECK(L, 0); + rive::ViewModelInstanceHandle handle = CheckViewModelInstanceHandle(L, 1); + const char* viewmodel_name = luaL_checkstring(L, 2); + dmRiveCommands::GetCommandQueue()->requestViewModelInstanceColor(handle, viewmodel_name); + return 0; +} + +/** + * Requests the enum value for the property. + * @name cmd.requestViewModelInstanceEnum(instance_handle, property_name) + * @param instance_handle [type: ViewModelInstanceHandle] View model instance handle. + * @param property_name [type: string] Name of the enum property. + */ +static int Script_requestViewModelInstanceEnum(lua_State* L) +{ + DM_LUA_STACK_CHECK(L, 0); + rive::ViewModelInstanceHandle handle = CheckViewModelInstanceHandle(L, 1); + const char* viewmodel_name = luaL_checkstring(L, 2); + dmRiveCommands::GetCommandQueue()->requestViewModelInstanceEnum(handle, viewmodel_name); + return 0; +} + +/** + * Requests the string value for the property. + * @name cmd.requestViewModelInstanceString(instance_handle, property_name) + * @param instance_handle [type: ViewModelInstanceHandle] View model instance handle. + * @param property_name [type: string] Name of the string property. + */ +static int Script_requestViewModelInstanceString(lua_State* L) +{ + DM_LUA_STACK_CHECK(L, 0); + rive::ViewModelInstanceHandle handle = CheckViewModelInstanceHandle(L, 1); + const char* viewmodel_name = luaL_checkstring(L, 2); + dmRiveCommands::GetCommandQueue()->requestViewModelInstanceString(handle, viewmodel_name); + return 0; +} + +/** + * Requests the list size for the property. + * @name cmd.requestViewModelInstanceListSize(instance_handle, property_name) + * @param instance_handle [type: ViewModelInstanceHandle] View model instance handle. + * @param property_name [type: string] Name of the list property. + */ +static int Script_requestViewModelInstanceListSize(lua_State* L) +{ + DM_LUA_STACK_CHECK(L, 0); + rive::ViewModelInstanceHandle handle = CheckViewModelInstanceHandle(L, 1); + const char* viewmodel_name = luaL_checkstring(L, 2); + dmRiveCommands::GetCommandQueue()->requestViewModelInstanceListSize(handle, viewmodel_name); + return 0; +} + +/** + * Requests state machine names for the artboard. + * @name cmd.requestStateMachineNames(artboard_handle) + * @param artboard_handle [type: ArtboardHandle] Artboard handle to query. + */ +static int Script_requestStateMachineNames(lua_State* L) +{ + DM_LUA_STACK_CHECK(L, 0); + rive::ArtboardHandle artboard = CheckArtboardHandle(L, 1); + dmRiveCommands::GetCommandQueue()->requestStateMachineNames(artboard); + return 0; +} + +/** + * Requests metadata about the default view model or artboard. + * @name cmd.requestDefaultViewModelInfo(artboard_handle, file_handle) + * @param artboard_handle [type: ArtboardHandle] Artboard handle to query. + * @param file_handle [type: FileHandle] File handle providing metadata. + */ +static int Script_requestDefaultViewModelInfo(lua_State* L) +{ + DM_LUA_STACK_CHECK(L, 0); + rive::ArtboardHandle artboard = CheckArtboardHandle(L, 1); + rive::FileHandle file = CheckFileHandle(L, 2); + dmRiveCommands::GetCommandQueue()->requestDefaultViewModelInfo(artboard, file); + return 0; +} + +// ***************************************************************************************** + +static const luaL_reg RIVE_COMMAND_FUNCTIONS[] = +{ + {"instantiateArtboardNamed", Script_instantiateArtboardNamed}, + {"instantiateDefaultArtboard", Script_instantiateDefaultArtboard}, + {"deleteArtboard", Script_deleteArtboard}, + + {"instantiateStateMachineNamed", Script_instantiateStateMachineNamed}, + {"instantiateDefaultStateMachine", Script_instantiateDefaultStateMachine}, + {"advanceStateMachine", Script_advanceStateMachine}, + {"bindViewModelInstance", Script_bindViewModelInstance}, + {"deleteStateMachine", Script_deleteStateMachine}, + + {"instantiateBlankViewModelInstance", Script_instantiateBlankViewModelInstance}, + {"instantiateDefaultViewModelInstance", Script_instantiateDefaultViewModelInstance}, + {"instantiateViewModelInstanceNamed", Script_instantiateViewModelInstanceNamed}, + {"referenceNestedViewModelInstance", Script_referenceNestedViewModelInstance}, + {"referenceListViewModelInstance", Script_referenceListViewModelInstance}, + + {"setViewModelInstanceNestedViewModel", Script_setViewModelInstanceNestedViewModel}, + {"insertViewModelInstanceListViewModel", Script_insertViewModelInstanceListViewModel}, + {"appendViewModelInstanceListViewModel", Script_appendViewModelInstanceListViewModel}, + {"swapViewModelInstanceListValues", Script_swapViewModelInstanceListValues}, + + {"removeViewModelInstanceListViewModelIndex",Script_removeViewModelInstanceListViewModelIndex}, + {"removeViewModelInstanceListViewModel", Script_removeViewModelInstanceListViewModel}, + + {"deleteViewModelInstance", Script_deleteViewModelInstance}, + + {"fireViewModelTrigger", Script_fireViewModelTrigger}, + {"setViewModelInstanceBool", Script_setViewModelInstanceBool}, + {"setViewModelInstanceNumber", Script_setViewModelInstanceNumber}, + {"setViewModelInstanceColor", Script_setViewModelInstanceColor}, + {"setViewModelInstanceEnum", Script_setViewModelInstanceEnum}, + {"setViewModelInstanceString", Script_setViewModelInstanceString}, + {"setViewModelInstanceImage", Script_setViewModelInstanceImage}, + {"setViewModelInstanceArtboard",Script_setViewModelInstanceArtboard}, + + {"subscribeToViewModelProperty", Script_subscribeToViewModelProperty}, + {"unsubscribeToViewModelProperty", Script_unsubscribeToViewModelProperty}, + + {"loadFile", Script_loadFile}, + {"deleteFile", Script_deleteFile}, + {"decodeImage", Script_decodeImage}, + {"deleteImage", Script_deleteImage}, + {"decodeAudio", Script_decodeAudio}, + {"deleteAudio", Script_deleteAudio}, + {"decodeFont", Script_decodeFont}, + {"deleteFont", Script_deleteFont}, + + {"addGlobalImageAsset", Script_addGlobalImageAsset}, + {"removeGlobalImageAsset", Script_removeGlobalImageAsset}, + {"addGlobalAudioAsset", Script_addGlobalAudioAsset}, + {"removeGlobalAudioAsset", Script_removeGlobalAudioAsset}, + {"addGlobalFontAsset", Script_addGlobalFontAsset}, + {"removeGlobalFontAsset", Script_removeGlobalFontAsset}, + + {"requestViewModelNames", Script_requestViewModelNames}, + {"requestArtboardNames", Script_requestArtboardNames}, + {"requestViewModelEnums", Script_requestViewModelEnums}, + + {"requestViewModelPropertyDefinitions", Script_requestViewModelPropertyDefinitions}, + {"requestViewModelInstanceNames", Script_requestViewModelInstanceNames}, + {"requestViewModelInstanceBool", Script_requestViewModelInstanceBool}, + {"requestViewModelInstanceNumber", Script_requestViewModelInstanceNumber}, + {"requestViewModelInstanceColor", Script_requestViewModelInstanceColor}, + {"requestViewModelInstanceEnum", Script_requestViewModelInstanceEnum}, + {"requestViewModelInstanceString", Script_requestViewModelInstanceString}, + {"requestViewModelInstanceListSize", Script_requestViewModelInstanceListSize}, + + {"requestStateMachineNames", Script_requestStateMachineNames}, + {"requestDefaultViewModelInfo", Script_requestDefaultViewModelInfo}, + + {0, 0} +}; + +void ScriptCmdRegister(struct lua_State* L, dmResource::HFactory factory) +{ + lua_newtable(L); + luaL_register(L, 0, RIVE_COMMAND_FUNCTIONS); + lua_setfield(L, -2, "cmd"); + + g_ResourceFactory = factory; +} + +void ScriptCmdUnregister(struct lua_State* L, dmResource::HFactory factory) +{ + g_ResourceFactory = 0; +} + +} // namespace dmRive + +#endif // DM_RIVE_UNSUPPORTED diff --git a/defold-rive/src/script_rive_cmd.h b/defold-rive/src/script_rive_cmd.h new file mode 100644 index 00000000..55ed6128 --- /dev/null +++ b/defold-rive/src/script_rive_cmd.h @@ -0,0 +1,25 @@ +// Copyright 2020 The Defold Foundation +// Licensed under the Defold License version 1.0 (the "License"); you may not use +// this file except in compliance with the License. +// +// You may obtain a copy of the License, together with FAQs at +// https://www.defold.com/license +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#ifndef DM_GAMESYS_SCRIPT_RIVE_CMD_H +#define DM_GAMESYS_SCRIPT_RIVE_CMD_H + +#include +#include + +namespace dmRive +{ + void ScriptCmdRegister(lua_State* L, dmResource::HFactory factory); + void ScriptCmdUnregister(lua_State* L, dmResource::HFactory factory); +} + +#endif // DM_GAMESYS_SCRIPT_RIVE_CMD_H diff --git a/defold-rive/src/script_rive_databinding.cpp b/defold-rive/src/script_rive_databinding.cpp deleted file mode 100644 index 2cd756ff..00000000 --- a/defold-rive/src/script_rive_databinding.cpp +++ /dev/null @@ -1,362 +0,0 @@ -// Copyright 2021 The Defold Foundation -// Licensed under the Defold License version 1.0 (the "License"); you may not use -// this file except in compliance with the License. -// -// You may obtain a copy of the License, together with FAQs at -// https://www.defold.com/license -// -// Unless required by applicable law or agreed to in writing, software distributed -// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -// CONDITIONS OF ANY KIND, either express or implied. See the License for the -// specific language governing permissions and limitations under the License. - -#if !defined(DM_RIVE_UNSUPPORTED) - -#include - -#include -#include -#include - -#include "comp_rive.h" -#include "comp_rive_private.h" -#include "res_rive_data.h" - -#include - -namespace dmRive -{ - -static dmResource::HFactory g_ResourceFactory = 0; - -static int CreateViewModelInstanceRuntime(lua_State* L) -{ - DM_LUA_STACK_CHECK(L, 2); - - RiveComponent* component = 0; - dmScript::GetComponentFromLua(L, 1, dmRive::RIVE_MODEL_EXT, 0, (void**)&component, 0); - - dmhash_t name_hash = dmScript::CheckHashOrString(L, 2); - - uint32_t handle = dmRive::CompRiveCreateViewModelInstanceRuntime(component, name_hash); - if (handle != dmRive::INVALID_HANDLE) - { - lua_pushinteger(L, handle); - lua_pushnil(L); - } - else - { - lua_pushnil(L); - char msg[256]; - dmSnPrintf(msg, sizeof(msg), "Failed to create view model instance runtime with name '%s'", dmHashReverseSafe64(name_hash)); - lua_pushstring(L, msg); - } - return 2; -} - -static int DestroyViewModelInstanceRuntime(lua_State* L) -{ - DM_LUA_STACK_CHECK(L, 0); - - RiveComponent* component = 0; - dmScript::GetComponentFromLua(L, 1, dmRive::RIVE_MODEL_EXT, 0, (void**)&component, 0); - - uint32_t handle = luaL_checkinteger(L, 2); - dmRive::CompRiveDestroyViewModelInstanceRuntime(component, handle); - return 0; -} - -static int SetViewModelInstanceRuntime(lua_State* L) -{ - DM_LUA_STACK_CHECK(L, 0); - - RiveComponent* component = 0; - dmScript::GetComponentFromLua(L, 1, dmRive::RIVE_MODEL_EXT, 0, (void**)&component, 0); - - uint32_t handle = luaL_checkinteger(L, 2); - bool result = dmRive::CompRiveSetViewModelInstanceRuntime(component, handle); - if (!result) - { - return DM_LUA_ERROR("Could not set view model instance runtime with handle '%u'", handle); - } - - return 0; -} - -static int GetViewModelInstanceRuntime(lua_State* L) -{ - DM_LUA_STACK_CHECK(L, 1); - RiveComponent* component = 0; - dmScript::GetComponentFromLua(L, 1, dmRive::RIVE_MODEL_EXT, 0, (void**)&component, 0); - uint32_t handle = CompRiveGetViewModelInstanceRuntime(component); - lua_pushinteger(L, handle); - return 1; -} - -#define CHECK_BOOLEAN(PATH, INDEX) \ - if (!lua_isboolean(L, INDEX)) { \ - char buffer[1024]; \ - lua_pushvalue(L, INDEX); \ - dmSnPrintf(buffer, sizeof(buffer), "Property '%s' is not a boolean: '%s'", PATH, lua_tostring(L, -1)); \ - lua_pop(L, lua_gettop(L) - top); \ - return DM_LUA_ERROR("%s", buffer); \ - } - -#define CHECK_RESULT(RESULT, URL, PATH, INDEX) \ - if (!result) { \ - char buffer[1024]; \ - lua_pushvalue(L, INDEX); \ - dmSnPrintf(buffer, sizeof(buffer), "%s has no property with path '%s' that accepts type '%s' (value='%s')", dmScript::UrlToString(URL, buffer, sizeof(buffer)), PATH, lua_typename(L, lua_type(L, -1)), lua_tostring(L, -1)); \ - lua_pop(L, lua_gettop(L) - top); \ - return DM_LUA_ERROR("%s", buffer); \ - } - -static int SetProperties(lua_State* L) -{ - DM_LUA_STACK_CHECK(L, 0); - int top = lua_gettop(L); - - dmMessage::URL url; - RiveComponent* component = 0; - dmScript::GetComponentFromLua(L, 1, dmRive::RIVE_MODEL_EXT, 0, (void**)&component, &url); - - uint32_t handle = luaL_checkinteger(L, 2); - - luaL_checktype(L, 3, LUA_TTABLE); - lua_pushvalue(L, 3); - lua_pushnil(L); - while (lua_next(L, -2)) { - lua_pushvalue(L, -2); // Add a duplicate of the key, as we do a lua_tostring on it - - // Note: This is a "path", as it may refer to a property within a nested structure of view model instance runtimes - const char* path = lua_tostring(L, -1); // the key - - // Check what property type is wanted - rive::DataType data_type = rive::DataType::none; - bool result = dmRive::GetPropertyDataType(component, handle, path, &data_type); - CHECK_RESULT(result, &url, path, -2); - - if (data_type == rive::DataType::number) - { - float value = lua_tonumber(L, -2); - bool result = dmRive::CompRiveRuntimeSetPropertyF32(component, handle, path, value); - CHECK_RESULT(result, &url, path, -2); - } - else if (data_type == rive::DataType::string) - { - const char* value = luaL_checkstring(L, -2); - bool result = dmRive::CompRiveRuntimeSetPropertyString(component, handle, path, value); - CHECK_RESULT(result, &url, path, -2); - } - else if (data_type == rive::DataType::boolean) - { - CHECK_BOOLEAN(path, -2); - bool value = lua_toboolean(L, -2); - bool result = dmRive::CompRiveRuntimeSetPropertyBool(component, handle, path, value); - CHECK_RESULT(result, &url, path, -2); - } - else if (data_type == rive::DataType::trigger) - { - CHECK_BOOLEAN(path, -2); - bool value = lua_toboolean(L, -2); - // Trigger doesn't really use a value. - // But no value would mean nil, and nil would mean it's not in the table to begin with. - // So we use a bool as the "dummy" value! - // However, it would feel strange to trigger() on a false value :/ - if (value) - { - bool result = dmRive::CompRiveRuntimeSetPropertyTrigger(component, handle, path); - CHECK_RESULT(result, &url, path, -2); - } - } - else if (data_type == rive::DataType::color) - { - dmVMath::Vector4* color = dmScript::CheckVector4(L, -2); - bool result = dmRive::CompRiveRuntimeSetPropertyColor(component, handle, path, color); - CHECK_RESULT(result, &url, path, -2); - } - else if (data_type == rive::DataType::enumType) - { - const char* value = luaL_checkstring(L, -2); - result = dmRive::CompRiveRuntimeSetPropertyEnum(component, handle, path, value); - CHECK_RESULT(result, &url, path, -2); - } - else if (data_type == rive::DataType::assetImage) - { - size_t data_length = 0; - const char* data = luaL_checklstring(L, -2, &data_length); - - RiveSceneData* rive_scene_data = dmRive::CompRiveGetRiveSceneData(component); - rive::RenderImage* image = ResRiveDataCreateRenderImage(g_ResourceFactory, rive_scene_data, (uint8_t*)data, (uint32_t)data_length); - result = dmRive::CompRiveRuntimeSetPropertyImage(component, handle, path, image); - CHECK_RESULT(result, &url, path, -2); - } - else - { - dmLogWarning("Datatype %d is not yet supported (path: '%s')", (int)data_type, path); - } - - lua_pop(L, 2); - } - lua_pop(L, 1); - - return 0; -} - -static int GetProperty(lua_State* L) -{ - DM_LUA_STACK_CHECK(L, 1); - int top = lua_gettop(L); - - dmMessage::URL url; - RiveComponent* component = 0; - dmScript::GetComponentFromLua(L, 1, dmRive::RIVE_MODEL_EXT, 0, (void**)&component, &url); - - uint32_t handle = luaL_checkinteger(L, 2); - if (handle == dmRive::INVALID_HANDLE) - { - return DM_LUA_ERROR("Invalid handle: %d (x%08x) at index %d", (int)handle, handle, 2); - } - - // Note: This is a "path", as it may refer to a property within a nested structure of view model instance runtimes - const char* path = lua_tostring(L, 3); // the path - - rive::DataType data_type = rive::DataType::none; - bool result = dmRive::GetPropertyDataType(component, handle, path, &data_type); - CHECK_RESULT(result, &url, path, -2); - - if (data_type == rive::DataType::number) - { - float value = false; - bool result = dmRive::CompRiveRuntimeGetPropertyF32(component, handle, path, &value); - CHECK_RESULT(result, &url, path, -2); - lua_pushnumber(L, value); - } - else if (data_type == rive::DataType::string) - { - const char* value = 0; - bool result = dmRive::CompRiveRuntimeGetPropertyString(component, handle, path, &value); - CHECK_RESULT(result, &url, path, -2); - lua_pushstring(L, value); - } - else if (data_type == rive::DataType::boolean) - { - bool value = false; - bool result = dmRive::CompRiveRuntimeGetPropertyBool(component, handle, path, &value); - CHECK_RESULT(result, &url, path, -2); - lua_pushboolean(L, value); - } - else if (data_type == rive::DataType::enumType) - { - const char* value = 0; - bool result = dmRive::CompRiveRuntimeGetPropertyEnum(component, handle, path, &value); - CHECK_RESULT(result, &url, path, -2); - lua_pushstring(L, value); - } - else if(data_type == rive::DataType::color) - { - dmVMath::Vector4 value(-1, -1, -1, -1); - bool result = dmRive::CompRiveRuntimeGetPropertyColor(component, handle, path, &value); - CHECK_RESULT(result, &url, path, -2); - dmScript::PushVector4(L, value); - } - else if(data_type == rive::DataType::trigger) - { - return DM_LUA_ERROR("Cannot get trigger property value as it is input-only (path: '%s')", path); - } - else - { - return DM_LUA_ERROR("Getting data type %d is not supported (path: '%s')", (int)data_type, path); - } - return 1; -} - -static int ListAddInstanceInternal(lua_State* L, bool add, int index) -{ - DM_LUA_STACK_CHECK(L, 0); - int top = lua_gettop(L); - - dmMessage::URL url; - RiveComponent* component = 0; - dmScript::GetComponentFromLua(L, 1, dmRive::RIVE_MODEL_EXT, 0, (void**)&component, &url); - - uint32_t handle = luaL_checkinteger(L, 2); - if (handle == dmRive::INVALID_HANDLE) - { - return DM_LUA_ERROR("Invalid handle: %d (x%08x) at index %d", (int)handle, handle, 2); - } - - // Note: This is a "path", as it may refer to a property within a nested structure of view model instance runtimes - const char* path = lua_tostring(L, 3); // the path - - uint32_t instance = luaL_checkinteger(L, 4); - if (instance == dmRive::INVALID_HANDLE) - { - return DM_LUA_ERROR("Invalid handle: %d (x%08x) at index %d", (int)instance, instance, 3); - } - - bool result; - if (add) - result = dmRive::CompRiveRuntimeListAddInstance(component, handle, path, instance); - else - result = dmRive::CompRiveRuntimeListRemoveInstance(component, handle, path, instance); - if (!result) - { - if (add) - { - return DM_LUA_ERROR("Failed adding instance to list %s", path); - } - else - { - return DM_LUA_ERROR("Failed removing instance from list %s", path); - } - } - - return 0; -} - -static int ListAddInstance(lua_State* L) -{ - return ListAddInstanceInternal(L, true, -1); -} - -static int ListRemoveInstance(lua_State* L) -{ - return ListAddInstanceInternal(L, false, -1); -} - - -#undef CHECK_RESULT -#undef CHECK_BOOLEAN - - -static int SetListener(lua_State* L) -{ - return 0; -} - -static const luaL_reg RIVE_DATABIND_FUNCTIONS[] = -{ - {"create_view_model_instance_runtime", CreateViewModelInstanceRuntime}, - {"destroy_view_model_instance_runtime", DestroyViewModelInstanceRuntime}, - {"set_view_model_instance_runtime", SetViewModelInstanceRuntime}, - {"get_view_model_instance_runtime", GetViewModelInstanceRuntime}, - {"set_properties", SetProperties}, - {"get_property", GetProperty}, - {"list_add_instance", ListAddInstance}, - {"list_remove_instance", ListRemoveInstance}, - {0, 0} -}; - -void ScriptInitializeDataBinding(struct lua_State* L, dmResource::HFactory factory) -{ - lua_newtable(L); - luaL_register(L, 0, RIVE_DATABIND_FUNCTIONS); - lua_setfield(L, -2, "databind"); - - g_ResourceFactory = factory; -} - -} // namespace dmRive - -#endif // DM_RIVE_UNSUPPORTED diff --git a/defold-rive/src/script_rive_handles.cpp b/defold-rive/src/script_rive_handles.cpp new file mode 100644 index 00000000..71c6af69 --- /dev/null +++ b/defold-rive/src/script_rive_handles.cpp @@ -0,0 +1,193 @@ +// Copyright 2020 The Defold Foundation +// Licensed under the Defold License version 1.0 (the "License"); you may not use +// this file except in compliance with the License. +// +// You may obtain a copy of the License, together with FAQs at +// https://www.defold.com/license +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#include "script_defold.h" +#include "script_rive_handles.h" + +extern "C" +{ +#include +#include +} + +#include + +namespace dmRive +{ + struct HandleUserData + { + uint64_t m_Handle; + }; + + static const char* HandleTypeNames[] = { + "rive.FileHandle", + "rive.ArtboardHandle", + "rive.StateMachineHandle", + "rive.ViewModelInstanceHandle", + "rive.RenderImageHandle", + "rive.AudioSourceHandle", + "rive.FontHandle", + nullptr + }; + + static const char* IdentifyHandleType(lua_State* L, int index) + { + if (!lua_getmetatable(L, index)) + { + return nullptr; + } + int meta = lua_gettop(L); + for (const char** name = HandleTypeNames; *name; ++name) + { + luaL_getmetatable(L, *name); + if (lua_rawequal(L, -1, meta)) + { + lua_pop(L, 2); + return *name; + } + lua_pop(L, 1); + } + lua_pop(L, 1); + return nullptr; + } + + template + struct LuaHandle + { + static const char* s_TypeName; + + static int LuaGC(lua_State* L) + { + (void)Check(L, 1); + return 0; + } + + static int LuaToString(lua_State* L) + { + HandleT handle = Check(L, 1); + uint64_t value = (uint64_t)(uintptr_t)handle; + lua_pushfstring(L, "%s(%p)", s_TypeName, (void*)(uintptr_t)value); + return 1; + } + + static void Register(lua_State* L, const char* name) + { + s_TypeName = name; + static const luaL_reg meta[] = { + { "__gc", LuaGC }, + { "__tostring", LuaToString }, + { 0, 0 } + }; + RegisterUserType(L, name, name, 0, meta); + } + + static void Push(lua_State* L, HandleT handle) + { + HandleUserData* data = (HandleUserData*)lua_newuserdata(L, sizeof(HandleUserData)); + data->m_Handle = (uint64_t)(uintptr_t)handle; + luaL_getmetatable(L, s_TypeName); + lua_setmetatable(L, -2); + } + + static HandleT Check(lua_State* L, int index) + { + HandleUserData* data = (HandleUserData*)ToUserType(L, index, s_TypeName); + if (!data) + { + const char* actual = IdentifyHandleType(L, index); + if (actual) + { + luaL_error(L, "Argument %d expected %s, got %s", index, s_TypeName, actual); + } + luaL_typerror(L, index, s_TypeName); + } + return (HandleT)data->m_Handle; + } + }; + + template + const char* LuaHandle::s_TypeName = nullptr; + + void RegisterScriptRiveHandles(lua_State* L) + { + LuaHandle::Register(L, "rive.FileHandle"); + LuaHandle::Register(L, "rive.ArtboardHandle"); + LuaHandle::Register(L, "rive.StateMachineHandle"); + LuaHandle::Register(L, "rive.ViewModelInstanceHandle"); + LuaHandle::Register(L, "rive.RenderImageHandle"); + LuaHandle::Register(L, "rive.AudioSourceHandle"); + LuaHandle::Register(L, "rive.FontHandle"); + } + + void PushFileHandle(lua_State* L, rive::FileHandle handle) + { + LuaHandle::Push(L, handle); + } + rive::FileHandle CheckFileHandle(lua_State* L, int index) + { + return LuaHandle::Check(L, index); + } + + void PushArtboardHandle(lua_State* L, rive::ArtboardHandle handle) + { + LuaHandle::Push(L, handle); + } + rive::ArtboardHandle CheckArtboardHandle(lua_State* L, int index) + { + return LuaHandle::Check(L, index); + } + + void PushStateMachineHandle(lua_State* L, rive::StateMachineHandle handle) + { + LuaHandle::Push(L, handle); + } + rive::StateMachineHandle CheckStateMachineHandle(lua_State* L, int index) + { + return LuaHandle::Check(L, index); + } + + void PushViewModelInstanceHandle(lua_State* L, rive::ViewModelInstanceHandle handle) + { + LuaHandle::Push(L, handle); + } + rive::ViewModelInstanceHandle CheckViewModelInstanceHandle(lua_State* L, int index) + { + return LuaHandle::Check(L, index); + } + + void PushRenderImageHandle(lua_State* L, rive::RenderImageHandle handle) + { + LuaHandle::Push(L, handle); + } + rive::RenderImageHandle CheckRenderImageHandle(lua_State* L, int index) + { + return LuaHandle::Check(L, index); + } + + void PushAudioSourceHandle(lua_State* L, rive::AudioSourceHandle handle) + { + LuaHandle::Push(L, handle); + } + rive::AudioSourceHandle CheckAudioSourceHandle(lua_State* L, int index) + { + return LuaHandle::Check(L, index); + } + + void PushFontHandle(lua_State* L, rive::FontHandle handle) + { + LuaHandle::Push(L, handle); + } + rive::FontHandle CheckFontHandle(lua_State* L, int index) + { + return LuaHandle::Check(L, index); + } +} // namespace dmRive diff --git a/defold-rive/src/script_rive_handles.h b/defold-rive/src/script_rive_handles.h new file mode 100644 index 00000000..b0a6e935 --- /dev/null +++ b/defold-rive/src/script_rive_handles.h @@ -0,0 +1,46 @@ +// Copyright 2020 The Defold Foundation +// Licensed under the Defold License version 1.0 (the "License"); you may not use +// this file except in compliance with the License. +// +// You may obtain a copy of the License, together with FAQs at +// https://www.defold.com/license +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#ifndef DM_GAMESYS_SCRIPT_RIVE_HANDLES_H +#define DM_GAMESYS_SCRIPT_RIVE_HANDLES_H + +#include + +#include + +namespace dmRive +{ + void RegisterScriptRiveHandles(lua_State* L); + + void PushFileHandle(lua_State* L, rive::FileHandle handle); + rive::FileHandle CheckFileHandle(lua_State* L, int index); + + void PushArtboardHandle(lua_State* L, rive::ArtboardHandle handle); + rive::ArtboardHandle CheckArtboardHandle(lua_State* L, int index); + + void PushStateMachineHandle(lua_State* L, rive::StateMachineHandle handle); + rive::StateMachineHandle CheckStateMachineHandle(lua_State* L, int index); + + void PushViewModelInstanceHandle(lua_State* L, rive::ViewModelInstanceHandle handle); + rive::ViewModelInstanceHandle CheckViewModelInstanceHandle(lua_State* L, int index); + + void PushRenderImageHandle(lua_State* L, rive::RenderImageHandle handle); + rive::RenderImageHandle CheckRenderImageHandle(lua_State* L, int index); + + void PushAudioSourceHandle(lua_State* L, rive::AudioSourceHandle handle); + rive::AudioSourceHandle CheckAudioSourceHandle(lua_State* L, int index); + + void PushFontHandle(lua_State* L, rive::FontHandle handle); + rive::FontHandle CheckFontHandle(lua_State* L, int index); +} // namespace dmRive + +#endif // DM_GAMESYS_SCRIPT_RIVE_HANDLES_H diff --git a/defold-rive/src/script_rive_listeners.cpp b/defold-rive/src/script_rive_listeners.cpp new file mode 100644 index 00000000..48288a61 --- /dev/null +++ b/defold-rive/src/script_rive_listeners.cpp @@ -0,0 +1,361 @@ +// Copyright 2021 The Defold Foundation +// Licensed under the Defold License version 1.0 (the "License"); you may not use +// this file except in compliance with the License. +// +// You may obtain a copy of the License, together with FAQs at +// https://www.defold.com/license +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#if !defined(DM_RIVE_UNSUPPORTED) + +#include "res_rive_data.h" +#include "script_rive_listeners.h" +#include + +namespace dmRive +{ + +static bool SetupCallback(dmScript::LuaCallbackInfo* callback, dmhash_t id, uint64_t requestId) +{ + // TODO: Make sure this is run on the Lua thread! + + if (!callback) + return false; + + lua_State* L = dmScript::GetCallbackLuaContext(callback); + + if (!dmScript::SetupCallback(callback)) + { + return false; + } + + dmScript::PushHash(L, id); // the name of the callback function + lua_newtable(L); + + // TODO: Do we want/need to pass the request id (i.e. exposigin it through all the script api's?) + // lua_pushinteger(L, requestId); + // lua_setfield(L, -2, "requestId"); + + return true; +} + +static void InvokeCallback(lua_State* L, dmScript::LuaCallbackInfo* callback) +{ + // TODO: Make sure this is run on the Lua thread! + + // We assume that the SetupCallback was successful in adding [self, messageName, table] on the stack + dmScript::PCall(L, 3, 0); // self + # user arguments + dmScript::TeardownCallback(callback); +} + +static void PushStringArray(lua_State* L, const char* name, std::vector& array) +{ + uint32_t size = array.size(); + + // An empty table is already on the stack + // Create a new one for the artboard names + lua_createtable(L, size, 0); + + for (uint32_t i = 0; i < size; ++i) + { + lua_pushstring(L, array[i].c_str()); + lua_rawseti(L, -2, i+1); + } + + lua_setfield(L, -2, name); +} + +static void PushPropertiesArray(lua_State* L, const char* name, std::vector& properties) +{ + uint32_t size = properties.size(); + + // An empty table is already on the stack + // Create a new one for the artboard names + lua_createtable(L, size, 0); + + for (uint32_t i = 0; i < size; ++i) + { + lua_createtable(L, 0, 0); + + lua_pushstring(L, properties[i].name.c_str()); + lua_setfield(L, -2, "name"); + + lua_pushstring(L, properties[i].metaData.c_str()); + lua_setfield(L, -2, "metaData"); + + lua_pushinteger(L, (int)properties[i].type); + lua_setfield(L, -2, "type"); + + lua_rawseti(L, -2, i+1); + } + + lua_setfield(L, -2, name); +} + +static void PushEnumsArray(lua_State* L, const char* name, std::vector& enums) +{ + uint32_t size = enums.size(); + + // An empty table is already on the stack + // Create a new one for the artboard names + lua_createtable(L, size, 0); + + for (uint32_t i = 0; i < size; ++i) + { + lua_createtable(L, 0, 0); + + lua_pushstring(L, enums[i].name.c_str()); + lua_setfield(L, -2, "name"); + + PushStringArray(L, "enumerants", enums[i].enumerants); + + lua_rawseti(L, -2, i+1); + } + + lua_setfield(L, -2, name); +} + +// ****************************************************************************************************************************** + +void FileListener::onArtboardsListed(const rive::FileHandle fileHandle, uint64_t requestId, std::vector artboardNames) +{ + static dmhash_t id = dmHashString64("onArtboardsListed"); + + if (m_Callback && SetupCallback(m_Callback, id, requestId)) + { + lua_State* L = dmScript::GetCallbackLuaContext(m_Callback); + PushStringArray(L, "artboardNames", artboardNames); + InvokeCallback(L, m_Callback); + } +} + +void FileListener::onFileError(const rive::FileHandle, uint64_t requestId, std::string error) +{ + RiveSceneData* scene = (RiveSceneData*)requestId; + if (scene) + { + dmLogError("%s: %s", dmHashReverseSafe64(scene->m_PathHash), error.c_str()); + } + else + { + dmLogError("%s", error.c_str()); + } + + static dmhash_t id = dmHashString64("onFileError"); + if (m_Callback && SetupCallback(m_Callback, id, requestId)) + { + lua_State* L = dmScript::GetCallbackLuaContext(m_Callback); + + lua_pushstring(L, error.c_str()); + lua_setfield(L, -2, "artboardNames"); + + InvokeCallback(L, m_Callback); + } +} + +void FileListener::onFileDeleted(const rive::FileHandle file, uint64_t requestId) +{ + static dmhash_t id = dmHashString64("onFileDeleted"); + if (m_Callback && SetupCallback(m_Callback, id, requestId)) + { + lua_State* L = dmScript::GetCallbackLuaContext(m_Callback); + + lua_pushinteger(L, (int)(uintptr_t)file); + lua_setfield(L, -2, "file"); + + InvokeCallback(L, m_Callback); + } +} + +void FileListener::onFileLoaded(const rive::FileHandle file, uint64_t requestId) +{ + static dmhash_t id = dmHashString64("onFileLoaded"); + if (m_Callback && SetupCallback(m_Callback, id, requestId)) + { + lua_State* L = dmScript::GetCallbackLuaContext(m_Callback); + + lua_pushinteger(L, (int)(uintptr_t)file); + lua_setfield(L, -2, "file"); + + InvokeCallback(L, m_Callback); + } +} + +void FileListener::onViewModelsListed(const rive::FileHandle file, uint64_t requestId, std::vector viewModelNames) +{ + static dmhash_t id = dmHashString64("onViewModelsListed"); + if (m_Callback && SetupCallback(m_Callback, id, requestId)) + { + lua_State* L = dmScript::GetCallbackLuaContext(m_Callback); + + lua_pushinteger(L, (int)(uintptr_t)file); + lua_setfield(L, -2, "file"); + PushStringArray(L, "viewModelNames", viewModelNames); + + InvokeCallback(L, m_Callback); + } +} + +void FileListener::onViewModelInstanceNamesListed(const rive::FileHandle file, uint64_t requestId, std::string viewModelName, std::vector instanceNames) +{ + static dmhash_t id = dmHashString64("onViewModelInstanceNamesListed"); + if (m_Callback && SetupCallback(m_Callback, id, requestId)) + { + lua_State* L = dmScript::GetCallbackLuaContext(m_Callback); + + lua_pushinteger(L, (int)(uintptr_t)file); + lua_setfield(L, -2, "file"); + + lua_pushstring(L, viewModelName.c_str()); + lua_setfield(L, -2, "viewModelName"); + + PushStringArray(L, "instanceNames", instanceNames); + + InvokeCallback(L, m_Callback); + } +} + +void FileListener::onViewModelPropertiesListed(const rive::FileHandle file, uint64_t requestId, std::string viewModelName, std::vector properties) +{ + static dmhash_t id = dmHashString64("onViewModelPropertiesListed"); + if (m_Callback && SetupCallback(m_Callback, id, requestId)) + { + lua_State* L = dmScript::GetCallbackLuaContext(m_Callback); + + lua_pushinteger(L, (int)(uintptr_t)file); + lua_setfield(L, -2, "file"); + + lua_pushstring(L, viewModelName.c_str()); + lua_setfield(L, -2, "viewModelName"); + + PushPropertiesArray(L, "properties", properties); + + InvokeCallback(L, m_Callback); + } +} + +void FileListener::onViewModelEnumsListed(const rive::FileHandle file, uint64_t requestId, std::vector enums) +{ + static dmhash_t id = dmHashString64("onViewModelEnumsListed"); + if (m_Callback && SetupCallback(m_Callback, id, requestId)) + { + lua_State* L = dmScript::GetCallbackLuaContext(m_Callback); + + lua_pushinteger(L, (int)(uintptr_t)file); + lua_setfield(L, -2, "file"); + + PushEnumsArray(L, "enums", enums); + + InvokeCallback(L, m_Callback); + } +} + +// ****************************************************************************************************************************** + +void RenderImageListener::onRenderImageDecoded(const rive::RenderImageHandle, uint64_t requestId) +{ + +} +void RenderImageListener::onRenderImageError(const rive::RenderImageHandle, uint64_t requestId, std::string error) +{ + +} +void RenderImageListener::onRenderImageDeleted(const rive::RenderImageHandle, uint64_t requestId) +{ + +} + +// ****************************************************************************************************************************** + +void AudioSourceListener::onAudioSourceDecoded(const rive::AudioSourceHandle, uint64_t requestId) +{ + +} +void AudioSourceListener::onAudioSourceError(const rive::AudioSourceHandle, uint64_t requestId, std::string error) +{ + +} +void AudioSourceListener::onAudioSourceDeleted(const rive::AudioSourceHandle, uint64_t requestId) +{ + +} + +// ****************************************************************************************************************************** + + +void FontListener::onFontDecoded(const rive::FontHandle, uint64_t requestId) +{ + +} +void FontListener::onFontError(const rive::FontHandle, uint64_t requestId, std::string error) +{ + +} +void FontListener::onFontDeleted(const rive::FontHandle, uint64_t requestId) +{ + +} + +// ****************************************************************************************************************************** + +void ArtboardListener::onArtboardError(const rive::ArtboardHandle, uint64_t requestId, std::string error) +{ + +} +void ArtboardListener::onDefaultViewModelInfoReceived(const rive::ArtboardHandle, uint64_t requestId, std::string viewModelName, std::string instanceName) +{ + +} +void ArtboardListener::onArtboardDeleted(const rive::ArtboardHandle, uint64_t requestId) +{ + +} +void ArtboardListener::onStateMachinesListed(const rive::ArtboardHandle, uint64_t requestId, std::vector stateMachineNames) +{ + +} + +// ****************************************************************************************************************************** + +void ViewModelInstanceListener::onViewModelInstanceError(const rive::ViewModelInstanceHandle, uint64_t requestId, std::string error) +{ + +} + +void ViewModelInstanceListener::onViewModelDeleted(const rive::ViewModelInstanceHandle, uint64_t requestId) +{ + +} + +void ViewModelInstanceListener::onViewModelDataReceived(const rive::ViewModelInstanceHandle, uint64_t requestId, rive::CommandQueue::ViewModelInstanceData) +{ + +} + +void ViewModelInstanceListener::onViewModelListSizeReceived(const rive::ViewModelInstanceHandle, uint64_t requestId, std::string path, size_t size) +{ + +} + +// ****************************************************************************************************************************** + +void StateMachineListener::onStateMachineError(const rive::StateMachineHandle, uint64_t requestId, std::string error) +{ + +} +void StateMachineListener::onStateMachineDeleted(const rive::StateMachineHandle, uint64_t requestId) +{ + +} +void StateMachineListener::onStateMachineSettled(const rive::StateMachineHandle, uint64_t requestId) +{ + +} + +} // namespace dmRive + +#endif // DM_RIVE_UNSUPPORTED diff --git a/defold-rive/src/script_rive_listeners.h b/defold-rive/src/script_rive_listeners.h new file mode 100644 index 00000000..a8f68a1e --- /dev/null +++ b/defold-rive/src/script_rive_listeners.h @@ -0,0 +1,99 @@ +// Copyright 2020 The Defold Foundation +// Licensed under the Defold License version 1.0 (the "License"); you may not use +// this file except in compliance with the License. +// +// You may obtain a copy of the License, together with FAQs at +// https://www.defold.com/license +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#ifndef DM_GAMESYS_SCRIPT_RIVE_LISTENERS_H +#define DM_GAMESYS_SCRIPT_RIVE_LISTENERS_H + +#include + +#include + +#include +#include + +namespace dmRive +{ + +class FileListener : public rive::CommandQueue::FileListener +{ +public: + virtual void onArtboardsListed(const rive::FileHandle fileHandle, uint64_t requestId, std::vector artboardNames) override; + virtual void onFileError(const rive::FileHandle, uint64_t requestId, std::string error) override; + virtual void onFileDeleted(const rive::FileHandle, uint64_t requestId) override; + virtual void onFileLoaded(const rive::FileHandle, uint64_t requestId) override; + virtual void onViewModelsListed(const rive::FileHandle, uint64_t requestId, std::vector viewModelNames) override; + virtual void onViewModelInstanceNamesListed(const rive::FileHandle, uint64_t requestId, std::string viewModelName, std::vector instanceNames) override; + virtual void onViewModelPropertiesListed( const rive::FileHandle, uint64_t requestId, std::string viewModelName, std::vector properties) override; + virtual void onViewModelEnumsListed(const rive::FileHandle, uint64_t requestId, std::vector enums) override; + + dmScript::LuaCallbackInfo* m_Callback; +}; + +class RenderImageListener : public rive::CommandQueue::RenderImageListener +{ +public: + virtual void onRenderImageDecoded(const rive::RenderImageHandle, uint64_t requestId) override; + virtual void onRenderImageError(const rive::RenderImageHandle, uint64_t requestId, std::string error) override; + virtual void onRenderImageDeleted(const rive::RenderImageHandle, uint64_t requestId) override; + dmScript::LuaCallbackInfo* m_Callback; +}; + +class AudioSourceListener : public rive::CommandQueue::AudioSourceListener +{ +public: + virtual void onAudioSourceDecoded(const rive::AudioSourceHandle, uint64_t requestId) override; + virtual void onAudioSourceError(const rive::AudioSourceHandle, uint64_t requestId, std::string error) override; + virtual void onAudioSourceDeleted(const rive::AudioSourceHandle, uint64_t requestId) override; + dmScript::LuaCallbackInfo* m_Callback; +}; + +class FontListener : public rive::CommandQueue::FontListener +{ +public: + virtual void onFontDecoded(const rive::FontHandle, uint64_t requestId) override; + virtual void onFontError(const rive::FontHandle, uint64_t requestId, std::string error) override; + virtual void onFontDeleted(const rive::FontHandle, uint64_t requestId) override; + dmScript::LuaCallbackInfo* m_Callback; +}; + +class ArtboardListener : public rive::CommandQueue::ArtboardListener +{ +public: + virtual void onArtboardError(const rive::ArtboardHandle, uint64_t requestId, std::string error) override; + virtual void onDefaultViewModelInfoReceived(const rive::ArtboardHandle, uint64_t requestId, std::string viewModelName, std::string instanceName) override; + virtual void onArtboardDeleted(const rive::ArtboardHandle, uint64_t requestId) override; + virtual void onStateMachinesListed(const rive::ArtboardHandle, uint64_t requestId, std::vector stateMachineNames) override; + dmScript::LuaCallbackInfo* m_Callback; +}; + +class ViewModelInstanceListener : public rive::CommandQueue::ViewModelInstanceListener +{ +public: + virtual void onViewModelInstanceError(const rive::ViewModelInstanceHandle, uint64_t requestId, std::string error) override; + virtual void onViewModelDeleted(const rive::ViewModelInstanceHandle, uint64_t requestId) override; + virtual void onViewModelDataReceived(const rive::ViewModelInstanceHandle, uint64_t requestId, rive::CommandQueue::ViewModelInstanceData) override; + virtual void onViewModelListSizeReceived(const rive::ViewModelInstanceHandle, uint64_t requestId, std::string path, size_t size) override; + dmScript::LuaCallbackInfo* m_Callback; +}; + +class StateMachineListener : public rive::CommandQueue::StateMachineListener +{ +public: + virtual void onStateMachineError(const rive::StateMachineHandle, uint64_t requestId, std::string error) override; + virtual void onStateMachineDeleted(const rive::StateMachineHandle, uint64_t requestId) override; + virtual void onStateMachineSettled(const rive::StateMachineHandle, uint64_t requestId) override; + dmScript::LuaCallbackInfo* m_Callback; +}; + +} // namespace + +#endif // DM_GAMESYS_SCRIPT_RIVE_LISTENERS_H diff --git a/game.project b/game.project index 52a10be9..4d4b4b26 100644 --- a/game.project +++ b/game.project @@ -18,7 +18,7 @@ package = com.defold.extensionrive [project] title = extension-rive bundle_exclude_resources = utils -custom_resources = /main/outofband/walle,/main/outofband/font +custom_resources = /main/outofband/font dependencies#0 = https://github.com/andsve/dirtylarry/archive/master.zip [library] diff --git a/liveupdate.mounts b/liveupdate.mounts deleted file mode 100644 index 8a09a5c5..00000000 --- a/liveupdate.mounts +++ /dev/null @@ -1,2 +0,0 @@ -VERSION@,@1 -MOUNT@,@10@,@files@,@file:. diff --git a/main/bones/bone.go b/main/bones/bone.go deleted file mode 100644 index dbcdb1a4..00000000 --- a/main/bones/bone.go +++ /dev/null @@ -1,20 +0,0 @@ -embedded_components { - id: "sprite" - type: "sprite" - data: "tile_set: \"/assets/main.atlas\"\n" - "default_animation: \"bone\"\n" - "material: \"/builtins/materials/sprite.material\"\n" - "blend_mode: BLEND_MODE_ALPHA\n" - "" - position { - x: 0.0 - y: 0.0 - z: 0.0 - } - rotation { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } -} diff --git a/main/bones/bones.collection b/main/bones/bones.collection deleted file mode 100644 index 78bdcb58..00000000 --- a/main/bones/bones.collection +++ /dev/null @@ -1,38 +0,0 @@ -name: "bones" -instances { - id: "back" - prototype: "/main/menu/back.go" -} -scale_along_z: 0 -embedded_instances { - id: "go" - data: "components {\n" - " id: \"bones\"\n" - " component: \"/main/bones/bones.script\"\n" - "}\n" - "embedded_components {\n" - " id: \"rivemodel\"\n" - " type: \"rivemodel\"\n" - " data: \"scene: \\\"/main/bones/marty.rivescene\\\"\\n" - "default_animation: \\\"Animation1\\\"\\n" - "material: \\\"/defold-rive/assets/rivemodel.material\\\"\\n" - "create_go_bones: true\\n" - "artboard: \\\"New Artboard\\\"\\n" - "\"\n" - "}\n" - "embedded_components {\n" - " id: \"bonefactory\"\n" - " type: \"factory\"\n" - " data: \"prototype: \\\"/main/bones/bone.go\\\"\\n" - "\"\n" - "}\n" - "" - position { - x: 486.0 - y: 271.726 - } - scale3 { - x: 0.5 - y: 0.5 - } -} diff --git a/main/bones/bones.script b/main/bones/bones.script deleted file mode 100644 index 2996f1e1..00000000 --- a/main/bones/bones.script +++ /dev/null @@ -1,45 +0,0 @@ -function init(self) - -- Marty (fixed) - local names = {"hips","Belly","Chest","Neck","Head","Hair","Arm_right","Forearm_right","Hand_right","Arm_left","Forearm_left","Hand_left","Pocket_rignt","Pocket_left","Hoverboard","Shoe_right_foot","Shoe_right","Root Bone R","Shoe_left_foot","Shoe_left","Root Bone L","Hoverboard_ctrl"} - --local names = {"Neck", "hips"} - - --rive.cancel("#rivemodel") - - local pos = go.get_position() - - for _, name in ipairs(names) do - local bone_go = rive.get_go("#rivemodel", name) - - local id = factory.create("#bonefactory", vmath.vector3(0,0,0)) - go.set_parent(id, bone_go, false) - end - - --go.animate(".", "position.x", go.PLAYBACK_LOOP_PINGPONG, pos.x + 100, go.EASING_LINEAR, 2) -end - -function update(self, dt) -end - -function on_message(self, message_id, message, sender) - -- Add message-handling code here - -- Learn more: https://defold.com/manuals/message-passing/ - -- Remove this function if not needed -end - -function on_input(self, action_id, action) - -- Add input-handling code here. The game object this script is attached to - -- must have acquired input focus: - -- - -- msg.post(".", "acquire_input_focus") - -- - -- All mapped input bindings will be received. Mouse and touch input will - -- be received regardless of where on the screen it happened. - -- Learn more: https://defold.com/manuals/input/ - -- Remove this function if not needed -end - -function on_reload(self) - -- Add reload-handling code here - -- Learn more: https://defold.com/manuals/hot-reload/ - -- Remove this function if not needed -end diff --git a/main/bones/marty.riv b/main/bones/marty.riv deleted file mode 100644 index a3b7b249..00000000 Binary files a/main/bones/marty.riv and /dev/null differ diff --git a/main/bones/marty.rivescene b/main/bones/marty.rivescene deleted file mode 100644 index 7abc8f26..00000000 --- a/main/bones/marty.rivescene +++ /dev/null @@ -1,2 +0,0 @@ -scene: "/main/bones/marty.riv" -atlas: "/defold-rive/assets/empty.atlas" diff --git a/main/camera/camera.collection b/main/camera/camera.collection index 73a32211..b3dda269 100644 --- a/main/camera/camera.collection +++ b/main/camera/camera.collection @@ -14,6 +14,7 @@ embedded_instances { "material: \\\"/defold-rive/assets/rivemodel.material\\\"\\n" "default_state_machine: \\\"State Machine 1\\\"\\n" "artboard: \\\"Character\\\"\\n" + "blit_material: \\\"/defold-rive/assets/shader-library/rivemodel_blit.material\\\"\\n" "\"\n" "}\n" "" @@ -32,6 +33,7 @@ embedded_instances { "material: \\\"/defold-rive/assets/rivemodel.material\\\"\\n" "default_state_machine: \\\"State Machine 1\\\"\\n" "artboard: \\\"Death\\\"\\n" + "blit_material: \\\"/defold-rive/assets/shader-library/rivemodel_blit.material\\\"\\n" "\"\n" "}\n" "" diff --git a/main/car/car.collection b/main/car/car.collection deleted file mode 100644 index 65ec9567..00000000 --- a/main/car/car.collection +++ /dev/null @@ -1,35 +0,0 @@ -name: "main" -instances { - id: "back" - prototype: "/main/menu/back.go" -} -scale_along_z: 0 -embedded_instances { - id: "go" - data: "components {\n" - " id: \"test\"\n" - " component: \"/assets/test.rivemodel\"\n" - "}\n" - "components {\n" - " id: \"main\"\n" - " component: \"/main/car/car.script\"\n" - "}\n" - "" - position { - x: 337.7781 - y: 268.6295 - } - scale3 { - x: 0.41 - y: 0.41 - z: 0.82 - } -} -embedded_instances { - id: "gui" - data: "components {\n" - " id: \"gui\"\n" - " component: \"/main/car/gui.gui\"\n" - "}\n" - "" -} diff --git a/main/car/car.riv b/main/car/car.riv deleted file mode 100644 index 81202cb8..00000000 Binary files a/main/car/car.riv and /dev/null differ diff --git a/main/car/car.rivemodel b/main/car/car.rivemodel deleted file mode 100644 index 478174ff..00000000 --- a/main/car/car.rivemodel +++ /dev/null @@ -1,5 +0,0 @@ -scene: "/main/car/car.rivescene" -default_animation: "idle" -material: "/defold-rive/assets/rivemodel.material" -blend_mode: BLEND_MODE_ALPHA -default_state_machine: "" diff --git a/main/car/car.rivescene b/main/car/car.rivescene deleted file mode 100644 index f13b4cd8..00000000 --- a/main/car/car.rivescene +++ /dev/null @@ -1,2 +0,0 @@ -scene: "/assets/rive/off_road_car.riv" -atlas: "/defold-rive/assets/empty.atlas" diff --git a/main/car/car.script b/main/car/car.script deleted file mode 100644 index 1d27e473..00000000 --- a/main/car/car.script +++ /dev/null @@ -1,44 +0,0 @@ -function init(self) - self.v = 0 - self.url = msg.url("#test") - self.anim = 0 - self.cursor = 0 - self.playback = go.PLAYBACK_LOOP_FORWARD -end - -function update(self, dt) - self.v = self.v + dt - self.anim = go.get(self.url, "animation") - self.cursor = go.get(self.url, "cursor") - - if self.anim ~= 0 then - msg.post("/gui#gui", "animation_cursor", { cursor = self.cursor }) - end -end - -local function anim_done(self, message_id, message, sender) - if message_id == hash("rive_animation_done") then - msg.post("/gui#gui", "animation_complete") - end -end - -function play_animation(self, anim, playback, offset, rate) - if anim ~= self.anim or playback ~= self.playback then - print("Playing animation: " .. tostring(anim) .. " with playback mode " .. tostring(playback) .. ", rate " .. tostring(rate) .. ", offset " .. tostring(offset)) - self.anim = anim - self.playback = playback - rive.play_anim(self.url, self.anim, self.playback, { offset = offset, playback_rate = rate }, anim_done) - end -end - -function on_message(self, message_id, message) - if message_id == hash("MSG_CANCEL") then - rive.cancel(self.url) - elseif message_id == hash("MSG_PLAY") then - play_animation(self, message.animation, message.playback, message.offset, message.rate) - elseif message_id == hash("MSG_PLAYBACK_RATE") then - go.set(self.url, "playback_rate", message.rate) - elseif message_id == hash("MSG_PLAYBACK_CURSOR") then - go.set(self.url, "cursor", message.cursor) - end -end \ No newline at end of file diff --git a/main/car/gui.gui b/main/car/gui.gui deleted file mode 100644 index 0c07d6e2..00000000 --- a/main/car/gui.gui +++ /dev/null @@ -1,3178 +0,0 @@ -script: "/main/car/gui.gui_script" -background_color { - x: 0.0 - y: 0.0 - z: 0.0 - w: 0.0 -} -nodes { - position { - x: 0.0 - y: -101.0 - z: 0.0 - w: 1.0 - } - rotation { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - scale { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - size { - x: 200.0 - y: 100.0 - z: 0.0 - w: 1.0 - } - color { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - type: TYPE_BOX - blend_mode: BLEND_MODE_ALPHA - texture: "" - id: "controls" - xanchor: XANCHOR_NONE - yanchor: YANCHOR_NONE - pivot: PIVOT_CENTER - adjust_mode: ADJUST_MODE_FIT - layer: "" - inherit_alpha: true - slice9 { - x: 0.0 - y: 0.0 - z: 0.0 - w: 0.0 - } - clipping_mode: CLIPPING_MODE_NONE - clipping_visible: true - clipping_inverted: false - alpha: 1.0 - template_node_child: false - size_mode: SIZE_MODE_AUTO - custom_type: 0 - enabled: true - visible: false - material: "" -} -nodes { - position { - x: 757.0 - y: 251.0 - z: 0.0 - w: 1.0 - } - rotation { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - scale { - x: 0.5 - y: 0.5 - z: 1.0 - w: 1.0 - } - size { - x: 200.0 - y: 100.0 - z: 0.0 - w: 1.0 - } - color { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - type: TYPE_TEMPLATE - id: "playback_offset" - parent: "controls" - layer: "" - inherit_alpha: true - alpha: 1.0 - template: "/dirtylarry/slider.gui" - template_node_child: false - custom_type: 0 - enabled: true -} -nodes { - position { - x: -32.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - rotation { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - scale { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - size { - x: 364.0 - y: 32.0 - z: 0.0 - w: 1.0 - } - color { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - type: TYPE_BOX - blend_mode: BLEND_MODE_ALPHA - texture: "" - id: "playback_offset/larrysafearea" - xanchor: XANCHOR_NONE - yanchor: YANCHOR_NONE - pivot: PIVOT_W - adjust_mode: ADJUST_MODE_FIT - parent: "playback_offset" - layer: "" - inherit_alpha: true - slice9 { - x: 0.0 - y: 0.0 - z: 0.0 - w: 0.0 - } - clipping_mode: CLIPPING_MODE_NONE - clipping_visible: true - clipping_inverted: false - alpha: 0.0 - template_node_child: true - size_mode: SIZE_MODE_MANUAL - custom_type: 0 - enabled: true - visible: true - material: "" -} -nodes { - position { - x: 32.0 - y: -4.0 - z: 0.0 - w: 1.0 - } - rotation { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - scale { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - size { - x: 300.0 - y: 32.0 - z: 0.0 - w: 1.0 - } - color { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - type: TYPE_BOX - blend_mode: BLEND_MODE_ALPHA - texture: "dirtylarry/button_pressed" - id: "playback_offset/larryslider" - xanchor: XANCHOR_NONE - yanchor: YANCHOR_NONE - pivot: PIVOT_W - adjust_mode: ADJUST_MODE_FIT - parent: "playback_offset/larrysafearea" - layer: "" - inherit_alpha: false - slice9 { - x: 16.0 - y: 16.0 - z: 16.0 - w: 16.0 - } - clipping_mode: CLIPPING_MODE_NONE - clipping_visible: true - clipping_inverted: false - alpha: 1.0 - template_node_child: true - size_mode: SIZE_MODE_MANUAL - custom_type: 0 - enabled: true - visible: true - material: "" -} -nodes { - position { - x: 134.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - rotation { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - scale { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - size { - x: 32.0 - y: 32.0 - z: 0.0 - w: 1.0 - } - color { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - type: TYPE_BOX - blend_mode: BLEND_MODE_ALPHA - texture: "dirtylarry/radio_checked_normal" - id: "playback_offset/larrycursor" - xanchor: XANCHOR_NONE - yanchor: YANCHOR_NONE - pivot: PIVOT_W - adjust_mode: ADJUST_MODE_FIT - parent: "playback_offset/larryslider" - layer: "" - inherit_alpha: true - slice9 { - x: 0.0 - y: 0.0 - z: 0.0 - w: 0.0 - } - clipping_mode: CLIPPING_MODE_NONE - clipping_visible: true - clipping_inverted: false - alpha: 1.0 - template_node_child: true - size_mode: SIZE_MODE_MANUAL - custom_type: 0 - enabled: true - visible: true - material: "" -} -nodes { - position { - x: 306.0 - y: 3.0 - z: 0.0 - w: 1.0 - } - rotation { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - scale { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - size { - x: 200.0 - y: 42.0 - z: 0.0 - w: 1.0 - } - color { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - type: TYPE_TEXT - blend_mode: BLEND_MODE_ALPHA - text: "0.5" - font: "larryfont" - id: "playback_offset/larryvalue" - xanchor: XANCHOR_NONE - yanchor: YANCHOR_NONE - pivot: PIVOT_W - outline { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - shadow { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - adjust_mode: ADJUST_MODE_FIT - line_break: false - parent: "playback_offset/larryslider" - layer: "" - inherit_alpha: true - alpha: 1.0 - outline_alpha: 1.0 - shadow_alpha: 1.0 - template_node_child: true - text_leading: 1.0 - text_tracking: 0.0 - custom_type: 0 - enabled: true - visible: true - material: "" -} -nodes { - position { - x: -8.0 - y: 3.0 - z: 0.0 - w: 1.0 - } - rotation { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - scale { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - size { - x: 200.0 - y: 42.0 - z: 0.0 - w: 1.0 - } - color { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - type: TYPE_TEXT - blend_mode: BLEND_MODE_ALPHA - text: "Playback Offset\n" - "" - font: "larryfont" - id: "playback_offset/larrylabel" - xanchor: XANCHOR_NONE - yanchor: YANCHOR_NONE - pivot: PIVOT_E - outline { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - shadow { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - adjust_mode: ADJUST_MODE_FIT - line_break: false - parent: "playback_offset/larryslider" - layer: "" - inherit_alpha: true - alpha: 1.0 - outline_alpha: 1.0 - shadow_alpha: 1.0 - overridden_fields: 8 - template_node_child: true - text_leading: 1.0 - text_tracking: 0.0 - custom_type: 0 - enabled: true - visible: true - material: "" -} -nodes { - position { - x: 757.0 - y: 282.0 - z: 0.0 - w: 1.0 - } - rotation { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - scale { - x: 0.5 - y: 0.5 - z: 0.5 - w: 1.0 - } - size { - x: 200.0 - y: 100.0 - z: 0.0 - w: 1.0 - } - color { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - type: TYPE_TEMPLATE - id: "playback_rate" - parent: "controls" - layer: "" - inherit_alpha: true - alpha: 1.0 - template: "/dirtylarry/slider.gui" - template_node_child: false - custom_type: 0 - enabled: true -} -nodes { - position { - x: -32.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - rotation { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - scale { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - size { - x: 364.0 - y: 32.0 - z: 0.0 - w: 1.0 - } - color { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - type: TYPE_BOX - blend_mode: BLEND_MODE_ALPHA - texture: "" - id: "playback_rate/larrysafearea" - xanchor: XANCHOR_NONE - yanchor: YANCHOR_NONE - pivot: PIVOT_W - adjust_mode: ADJUST_MODE_FIT - parent: "playback_rate" - layer: "" - inherit_alpha: true - slice9 { - x: 0.0 - y: 0.0 - z: 0.0 - w: 0.0 - } - clipping_mode: CLIPPING_MODE_NONE - clipping_visible: true - clipping_inverted: false - alpha: 0.0 - template_node_child: true - size_mode: SIZE_MODE_MANUAL - custom_type: 0 - enabled: true - visible: true - material: "" -} -nodes { - position { - x: 32.0 - y: -4.0 - z: 0.0 - w: 1.0 - } - rotation { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - scale { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - size { - x: 300.0 - y: 32.0 - z: 0.0 - w: 1.0 - } - color { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - type: TYPE_BOX - blend_mode: BLEND_MODE_ALPHA - texture: "dirtylarry/button_pressed" - id: "playback_rate/larryslider" - xanchor: XANCHOR_NONE - yanchor: YANCHOR_NONE - pivot: PIVOT_W - adjust_mode: ADJUST_MODE_FIT - parent: "playback_rate/larrysafearea" - layer: "" - inherit_alpha: false - slice9 { - x: 16.0 - y: 16.0 - z: 16.0 - w: 16.0 - } - clipping_mode: CLIPPING_MODE_NONE - clipping_visible: true - clipping_inverted: false - alpha: 1.0 - template_node_child: true - size_mode: SIZE_MODE_MANUAL - custom_type: 0 - enabled: true - visible: true - material: "" -} -nodes { - position { - x: 134.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - rotation { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - scale { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - size { - x: 32.0 - y: 32.0 - z: 0.0 - w: 1.0 - } - color { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - type: TYPE_BOX - blend_mode: BLEND_MODE_ALPHA - texture: "dirtylarry/radio_checked_normal" - id: "playback_rate/larrycursor" - xanchor: XANCHOR_NONE - yanchor: YANCHOR_NONE - pivot: PIVOT_W - adjust_mode: ADJUST_MODE_FIT - parent: "playback_rate/larryslider" - layer: "" - inherit_alpha: true - slice9 { - x: 0.0 - y: 0.0 - z: 0.0 - w: 0.0 - } - clipping_mode: CLIPPING_MODE_NONE - clipping_visible: true - clipping_inverted: false - alpha: 1.0 - template_node_child: true - size_mode: SIZE_MODE_MANUAL - custom_type: 0 - enabled: true - visible: true - material: "" -} -nodes { - position { - x: 306.0 - y: 3.0 - z: 0.0 - w: 1.0 - } - rotation { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - scale { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - size { - x: 200.0 - y: 42.0 - z: 0.0 - w: 1.0 - } - color { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - type: TYPE_TEXT - blend_mode: BLEND_MODE_ALPHA - text: "0.5" - font: "larryfont" - id: "playback_rate/larryvalue" - xanchor: XANCHOR_NONE - yanchor: YANCHOR_NONE - pivot: PIVOT_W - outline { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - shadow { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - adjust_mode: ADJUST_MODE_FIT - line_break: false - parent: "playback_rate/larryslider" - layer: "" - inherit_alpha: true - alpha: 1.0 - outline_alpha: 1.0 - shadow_alpha: 1.0 - template_node_child: true - text_leading: 1.0 - text_tracking: 0.0 - custom_type: 0 - enabled: true - visible: true - material: "" -} -nodes { - position { - x: -8.0 - y: 3.0 - z: 0.0 - w: 1.0 - } - rotation { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - scale { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - size { - x: 200.0 - y: 42.0 - z: 0.0 - w: 1.0 - } - color { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - type: TYPE_TEXT - blend_mode: BLEND_MODE_ALPHA - text: "Playback Rate" - font: "larryfont" - id: "playback_rate/larrylabel" - xanchor: XANCHOR_NONE - yanchor: YANCHOR_NONE - pivot: PIVOT_E - outline { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - shadow { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - adjust_mode: ADJUST_MODE_FIT - line_break: false - parent: "playback_rate/larryslider" - layer: "" - inherit_alpha: true - alpha: 1.0 - outline_alpha: 1.0 - shadow_alpha: 1.0 - overridden_fields: 8 - template_node_child: true - text_leading: 1.0 - text_tracking: 0.0 - custom_type: 0 - enabled: true - visible: true - material: "" -} -nodes { - position { - x: 612.0 - y: 613.0 - z: 0.0 - w: 1.0 - } - rotation { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - scale { - x: 0.5 - y: 0.5 - z: 1.0 - w: 1.0 - } - size { - x: 200.0 - y: 100.0 - z: 0.0 - w: 1.0 - } - color { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - type: TYPE_TEMPLATE - id: "playback_once_forward" - parent: "controls" - layer: "" - inherit_alpha: true - alpha: 1.0 - template: "/dirtylarry/radio_label.gui" - template_node_child: false - custom_type: 0 - enabled: true -} -nodes { - position { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - rotation { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - scale { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - size { - x: 64.0 - y: 68.0 - z: 0.0 - w: 1.0 - } - color { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - type: TYPE_BOX - blend_mode: BLEND_MODE_ALPHA - texture: "radio/radio_normal" - id: "playback_once_forward/larryradio" - xanchor: XANCHOR_NONE - yanchor: YANCHOR_NONE - pivot: PIVOT_CENTER - adjust_mode: ADJUST_MODE_FIT - parent: "playback_once_forward" - layer: "" - inherit_alpha: true - slice9 { - x: 0.0 - y: 0.0 - z: 0.0 - w: 0.0 - } - clipping_mode: CLIPPING_MODE_NONE - clipping_visible: true - clipping_inverted: false - alpha: 1.0 - template_node_child: true - size_mode: SIZE_MODE_MANUAL - custom_type: 0 - enabled: true - visible: true - material: "" -} -nodes { - position { - x: 46.0 - y: 3.0 - z: 0.0 - w: 1.0 - } - rotation { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - scale { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - size { - x: 200.0 - y: 50.0 - z: 0.0 - w: 1.0 - } - color { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - type: TYPE_TEXT - blend_mode: BLEND_MODE_ALPHA - text: "Once Forward\n" - "" - font: "larryfont" - id: "playback_once_forward/larrylabel" - xanchor: XANCHOR_NONE - yanchor: YANCHOR_NONE - pivot: PIVOT_W - outline { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - shadow { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - adjust_mode: ADJUST_MODE_FIT - line_break: false - parent: "playback_once_forward" - layer: "" - inherit_alpha: true - alpha: 1.0 - outline_alpha: 1.0 - shadow_alpha: 1.0 - overridden_fields: 8 - template_node_child: true - text_leading: 1.0 - text_tracking: 0.0 - custom_type: 0 - enabled: true - visible: true - material: "" -} -nodes { - position { - x: 612.0 - y: 492.0 - z: 0.0 - w: 1.0 - } - rotation { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - scale { - x: 0.5 - y: 0.5 - z: 1.0 - w: 1.0 - } - size { - x: 200.0 - y: 100.0 - z: 0.0 - w: 1.0 - } - color { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - type: TYPE_TEMPLATE - id: "playback_loop_forward" - parent: "controls" - layer: "" - inherit_alpha: true - alpha: 1.0 - template: "/dirtylarry/radio_label.gui" - template_node_child: false - custom_type: 0 - enabled: true -} -nodes { - position { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - rotation { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - scale { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - size { - x: 64.0 - y: 68.0 - z: 0.0 - w: 1.0 - } - color { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - type: TYPE_BOX - blend_mode: BLEND_MODE_ALPHA - texture: "radio/radio_normal" - id: "playback_loop_forward/larryradio" - xanchor: XANCHOR_NONE - yanchor: YANCHOR_NONE - pivot: PIVOT_CENTER - adjust_mode: ADJUST_MODE_FIT - parent: "playback_loop_forward" - layer: "" - inherit_alpha: true - slice9 { - x: 0.0 - y: 0.0 - z: 0.0 - w: 0.0 - } - clipping_mode: CLIPPING_MODE_NONE - clipping_visible: true - clipping_inverted: false - alpha: 1.0 - template_node_child: true - size_mode: SIZE_MODE_MANUAL - custom_type: 0 - enabled: true - visible: true - material: "" -} -nodes { - position { - x: 46.0 - y: 3.0 - z: 0.0 - w: 1.0 - } - rotation { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - scale { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - size { - x: 200.0 - y: 50.0 - z: 0.0 - w: 1.0 - } - color { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - type: TYPE_TEXT - blend_mode: BLEND_MODE_ALPHA - text: "Loop Forward\n" - "" - font: "larryfont" - id: "playback_loop_forward/larrylabel" - xanchor: XANCHOR_NONE - yanchor: YANCHOR_NONE - pivot: PIVOT_W - outline { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - shadow { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - adjust_mode: ADJUST_MODE_FIT - line_break: false - parent: "playback_loop_forward" - layer: "" - inherit_alpha: true - alpha: 1.0 - outline_alpha: 1.0 - shadow_alpha: 1.0 - overridden_fields: 8 - template_node_child: true - text_leading: 1.0 - text_tracking: 0.0 - custom_type: 0 - enabled: true - visible: true - material: "" -} -nodes { - position { - x: 612.0 - y: 573.0 - z: 0.0 - w: 1.0 - } - rotation { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - scale { - x: 0.5 - y: 0.5 - z: 1.0 - w: 1.0 - } - size { - x: 200.0 - y: 100.0 - z: 0.0 - w: 1.0 - } - color { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - type: TYPE_TEMPLATE - id: "playback_once_backward" - parent: "controls" - layer: "" - inherit_alpha: true - alpha: 1.0 - template: "/dirtylarry/radio_label.gui" - template_node_child: false - custom_type: 0 - enabled: true -} -nodes { - position { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - rotation { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - scale { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - size { - x: 64.0 - y: 68.0 - z: 0.0 - w: 1.0 - } - color { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - type: TYPE_BOX - blend_mode: BLEND_MODE_ALPHA - texture: "radio/radio_normal" - id: "playback_once_backward/larryradio" - xanchor: XANCHOR_NONE - yanchor: YANCHOR_NONE - pivot: PIVOT_CENTER - adjust_mode: ADJUST_MODE_FIT - parent: "playback_once_backward" - layer: "" - inherit_alpha: true - slice9 { - x: 0.0 - y: 0.0 - z: 0.0 - w: 0.0 - } - clipping_mode: CLIPPING_MODE_NONE - clipping_visible: true - clipping_inverted: false - alpha: 1.0 - template_node_child: true - size_mode: SIZE_MODE_MANUAL - custom_type: 0 - enabled: true - visible: true - material: "" -} -nodes { - position { - x: 46.0 - y: 3.0 - z: 0.0 - w: 1.0 - } - rotation { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - scale { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - size { - x: 200.0 - y: 50.0 - z: 0.0 - w: 1.0 - } - color { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - type: TYPE_TEXT - blend_mode: BLEND_MODE_ALPHA - text: "Once Backward" - font: "larryfont" - id: "playback_once_backward/larrylabel" - xanchor: XANCHOR_NONE - yanchor: YANCHOR_NONE - pivot: PIVOT_W - outline { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - shadow { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - adjust_mode: ADJUST_MODE_FIT - line_break: false - parent: "playback_once_backward" - layer: "" - inherit_alpha: true - alpha: 1.0 - outline_alpha: 1.0 - shadow_alpha: 1.0 - overridden_fields: 8 - template_node_child: true - text_leading: 1.0 - text_tracking: 0.0 - custom_type: 0 - enabled: true - visible: true - material: "" -} -nodes { - position { - x: 612.0 - y: 532.0 - z: 0.0 - w: 1.0 - } - rotation { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - scale { - x: 0.5 - y: 0.5 - z: 1.0 - w: 1.0 - } - size { - x: 200.0 - y: 100.0 - z: 0.0 - w: 1.0 - } - color { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - type: TYPE_TEMPLATE - id: "playback_once_pingpong" - parent: "controls" - layer: "" - inherit_alpha: true - alpha: 1.0 - template: "/dirtylarry/radio_label.gui" - template_node_child: false - custom_type: 0 - enabled: true -} -nodes { - position { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - rotation { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - scale { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - size { - x: 64.0 - y: 68.0 - z: 0.0 - w: 1.0 - } - color { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - type: TYPE_BOX - blend_mode: BLEND_MODE_ALPHA - texture: "radio/radio_normal" - id: "playback_once_pingpong/larryradio" - xanchor: XANCHOR_NONE - yanchor: YANCHOR_NONE - pivot: PIVOT_CENTER - adjust_mode: ADJUST_MODE_FIT - parent: "playback_once_pingpong" - layer: "" - inherit_alpha: true - slice9 { - x: 0.0 - y: 0.0 - z: 0.0 - w: 0.0 - } - clipping_mode: CLIPPING_MODE_NONE - clipping_visible: true - clipping_inverted: false - alpha: 1.0 - template_node_child: true - size_mode: SIZE_MODE_MANUAL - custom_type: 0 - enabled: true - visible: true - material: "" -} -nodes { - position { - x: 46.0 - y: 3.0 - z: 0.0 - w: 1.0 - } - rotation { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - scale { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - size { - x: 200.0 - y: 50.0 - z: 0.0 - w: 1.0 - } - color { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - type: TYPE_TEXT - blend_mode: BLEND_MODE_ALPHA - text: "Once Ping Pong\n" - "" - font: "larryfont" - id: "playback_once_pingpong/larrylabel" - xanchor: XANCHOR_NONE - yanchor: YANCHOR_NONE - pivot: PIVOT_W - outline { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - shadow { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - adjust_mode: ADJUST_MODE_FIT - line_break: false - parent: "playback_once_pingpong" - layer: "" - inherit_alpha: true - alpha: 1.0 - outline_alpha: 1.0 - shadow_alpha: 1.0 - overridden_fields: 8 - template_node_child: true - text_leading: 1.0 - text_tracking: 0.0 - custom_type: 0 - enabled: true - visible: true - material: "" -} -nodes { - position { - x: 871.0 - y: 329.0 - z: 0.0 - w: 1.0 - } - rotation { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - scale { - x: 0.5 - y: 0.5 - z: 1.0 - w: 1.0 - } - size { - x: 200.0 - y: 100.0 - z: 0.0 - w: 1.0 - } - color { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - type: TYPE_TEMPLATE - id: "animation_broken" - parent: "controls" - layer: "" - inherit_alpha: true - alpha: 1.0 - template: "/dirtylarry/button.gui" - template_node_child: false - custom_type: 0 - enabled: true -} -nodes { - position { - x: -16.0 - y: 5.0 - z: 0.0 - w: 1.0 - } - rotation { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - scale { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - size { - x: 350.0 - y: 88.0 - z: 0.0 - w: 1.0 - } - color { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - type: TYPE_BOX - blend_mode: BLEND_MODE_ALPHA - texture: "button/button_normal" - id: "animation_broken/larrybutton" - xanchor: XANCHOR_NONE - yanchor: YANCHOR_NONE - pivot: PIVOT_CENTER - adjust_mode: ADJUST_MODE_FIT - parent: "animation_broken" - layer: "" - inherit_alpha: true - slice9 { - x: 32.0 - y: 32.0 - z: 32.0 - w: 32.0 - } - clipping_mode: CLIPPING_MODE_NONE - clipping_visible: true - clipping_inverted: false - alpha: 1.0 - overridden_fields: 1 - overridden_fields: 4 - template_node_child: true - size_mode: SIZE_MODE_MANUAL - custom_type: 0 - enabled: true - visible: true - material: "" -} -nodes { - position { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - rotation { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - scale { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - size { - x: 200.0 - y: 100.0 - z: 0.0 - w: 1.0 - } - color { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - type: TYPE_TEXT - blend_mode: BLEND_MODE_ALPHA - text: "Broken\n" - "" - font: "larryfont" - id: "animation_broken/larrylabel" - xanchor: XANCHOR_NONE - yanchor: YANCHOR_NONE - pivot: PIVOT_CENTER - outline { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - shadow { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - adjust_mode: ADJUST_MODE_FIT - line_break: false - parent: "animation_broken/larrybutton" - layer: "" - inherit_alpha: true - alpha: 1.0 - outline_alpha: 1.0 - shadow_alpha: 1.0 - overridden_fields: 8 - template_node_child: true - text_leading: 1.0 - text_tracking: 0.0 - custom_type: 0 - enabled: true - visible: true - material: "" -} -nodes { - position { - x: 870.0 - y: 496.0 - z: 0.0 - w: 1.0 - } - rotation { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - scale { - x: 0.5 - y: 0.5 - z: 1.0 - w: 1.0 - } - size { - x: 200.0 - y: 100.0 - z: 0.0 - w: 1.0 - } - color { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - type: TYPE_TEMPLATE - id: "animation_idle" - parent: "controls" - layer: "" - inherit_alpha: true - alpha: 1.0 - template: "/dirtylarry/button.gui" - template_node_child: false - custom_type: 0 - enabled: true -} -nodes { - position { - x: -16.0 - y: 5.0 - z: 0.0 - w: 1.0 - } - rotation { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - scale { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - size { - x: 350.0 - y: 88.0 - z: 0.0 - w: 1.0 - } - color { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - type: TYPE_BOX - blend_mode: BLEND_MODE_ALPHA - texture: "button/button_normal" - id: "animation_idle/larrybutton" - xanchor: XANCHOR_NONE - yanchor: YANCHOR_NONE - pivot: PIVOT_CENTER - adjust_mode: ADJUST_MODE_FIT - parent: "animation_idle" - layer: "" - inherit_alpha: true - slice9 { - x: 32.0 - y: 32.0 - z: 32.0 - w: 32.0 - } - clipping_mode: CLIPPING_MODE_NONE - clipping_visible: true - clipping_inverted: false - alpha: 1.0 - overridden_fields: 1 - overridden_fields: 4 - template_node_child: true - size_mode: SIZE_MODE_MANUAL - custom_type: 0 - enabled: true - visible: true - material: "" -} -nodes { - position { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - rotation { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - scale { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - size { - x: 200.0 - y: 100.0 - z: 0.0 - w: 1.0 - } - color { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - type: TYPE_TEXT - blend_mode: BLEND_MODE_ALPHA - text: "Idle" - font: "larryfont" - id: "animation_idle/larrylabel" - xanchor: XANCHOR_NONE - yanchor: YANCHOR_NONE - pivot: PIVOT_CENTER - outline { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - shadow { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - adjust_mode: ADJUST_MODE_FIT - line_break: false - parent: "animation_idle/larrybutton" - layer: "" - inherit_alpha: true - alpha: 1.0 - outline_alpha: 1.0 - shadow_alpha: 1.0 - overridden_fields: 8 - template_node_child: true - text_leading: 1.0 - text_tracking: 0.0 - custom_type: 0 - enabled: true - visible: true - material: "" -} -nodes { - position { - x: 870.0 - y: 605.0 - z: 0.0 - w: 1.0 - } - rotation { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - scale { - x: 0.5 - y: 0.5 - z: 1.0 - w: 1.0 - } - size { - x: 200.0 - y: 100.0 - z: 0.0 - w: 1.0 - } - color { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - type: TYPE_TEMPLATE - id: "animation_label" - parent: "controls" - layer: "" - inherit_alpha: true - alpha: 1.0 - template: "/dirtylarry/button.gui" - template_node_child: false - custom_type: 0 - enabled: true -} -nodes { - position { - x: -16.0 - y: 5.0 - z: 0.0 - w: 1.0 - } - rotation { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - scale { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - size { - x: 350.0 - y: 88.0 - z: 0.0 - w: 1.0 - } - color { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - type: TYPE_BOX - blend_mode: BLEND_MODE_ALPHA - texture: "button/button_normal" - id: "animation_label/larrybutton" - xanchor: XANCHOR_NONE - yanchor: YANCHOR_NONE - pivot: PIVOT_CENTER - adjust_mode: ADJUST_MODE_FIT - parent: "animation_label" - layer: "" - inherit_alpha: true - slice9 { - x: 32.0 - y: 32.0 - z: 32.0 - w: 32.0 - } - clipping_mode: CLIPPING_MODE_NONE - clipping_visible: true - clipping_inverted: false - alpha: 1.0 - overridden_fields: 1 - overridden_fields: 4 - template_node_child: true - size_mode: SIZE_MODE_MANUAL - custom_type: 0 - enabled: true - visible: true - material: "" -} -nodes { - position { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - rotation { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - scale { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - size { - x: 200.0 - y: 100.0 - z: 0.0 - w: 1.0 - } - color { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - type: TYPE_TEXT - blend_mode: BLEND_MODE_ALPHA - text: "Animation:" - font: "larryfont" - id: "animation_label/larrylabel" - xanchor: XANCHOR_NONE - yanchor: YANCHOR_NONE - pivot: PIVOT_CENTER - outline { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - shadow { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - adjust_mode: ADJUST_MODE_FIT - line_break: false - parent: "animation_label/larrybutton" - layer: "" - inherit_alpha: true - alpha: 1.0 - outline_alpha: 1.0 - shadow_alpha: 1.0 - overridden_fields: 8 - template_node_child: true - text_leading: 1.0 - text_tracking: 0.0 - custom_type: 0 - enabled: true - visible: true - material: "" -} -nodes { - position { - x: 871.0 - y: 384.0 - z: 0.0 - w: 1.0 - } - rotation { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - scale { - x: 0.5 - y: 0.5 - z: 1.0 - w: 1.0 - } - size { - x: 200.0 - y: 100.0 - z: 0.0 - w: 1.0 - } - color { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - type: TYPE_TEMPLATE - id: "animation_windshield_wipers" - parent: "controls" - layer: "" - inherit_alpha: true - alpha: 1.0 - template: "/dirtylarry/button.gui" - template_node_child: false - custom_type: 0 - enabled: true -} -nodes { - position { - x: -16.0 - y: 5.0 - z: 0.0 - w: 1.0 - } - rotation { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - scale { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - size { - x: 350.0 - y: 88.0 - z: 0.0 - w: 1.0 - } - color { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - type: TYPE_BOX - blend_mode: BLEND_MODE_ALPHA - texture: "button/button_normal" - id: "animation_windshield_wipers/larrybutton" - xanchor: XANCHOR_NONE - yanchor: YANCHOR_NONE - pivot: PIVOT_CENTER - adjust_mode: ADJUST_MODE_FIT - parent: "animation_windshield_wipers" - layer: "" - inherit_alpha: true - slice9 { - x: 32.0 - y: 32.0 - z: 32.0 - w: 32.0 - } - clipping_mode: CLIPPING_MODE_NONE - clipping_visible: true - clipping_inverted: false - alpha: 1.0 - overridden_fields: 1 - overridden_fields: 4 - template_node_child: true - size_mode: SIZE_MODE_MANUAL - custom_type: 0 - enabled: true - visible: true - material: "" -} -nodes { - position { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - rotation { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - scale { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - size { - x: 200.0 - y: 100.0 - z: 0.0 - w: 1.0 - } - color { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - type: TYPE_TEXT - blend_mode: BLEND_MODE_ALPHA - text: "Windshield Wipers\n" - "" - font: "larryfont" - id: "animation_windshield_wipers/larrylabel" - xanchor: XANCHOR_NONE - yanchor: YANCHOR_NONE - pivot: PIVOT_CENTER - outline { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - shadow { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - adjust_mode: ADJUST_MODE_FIT - line_break: false - parent: "animation_windshield_wipers/larrybutton" - layer: "" - inherit_alpha: true - alpha: 1.0 - outline_alpha: 1.0 - shadow_alpha: 1.0 - overridden_fields: 8 - template_node_child: true - text_leading: 1.0 - text_tracking: 0.0 - custom_type: 0 - enabled: true - visible: true - material: "" -} -nodes { - position { - x: 757.0 - y: 222.0 - z: 0.0 - w: 1.0 - } - rotation { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - scale { - x: 0.5 - y: 0.5 - z: 1.0 - w: 1.0 - } - size { - x: 200.0 - y: 100.0 - z: 0.0 - w: 1.0 - } - color { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - type: TYPE_TEMPLATE - id: "playback_cursor" - parent: "controls" - layer: "" - inherit_alpha: true - alpha: 1.0 - template: "/dirtylarry/slider.gui" - template_node_child: false - custom_type: 0 - enabled: true -} -nodes { - position { - x: -32.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - rotation { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - scale { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - size { - x: 364.0 - y: 32.0 - z: 0.0 - w: 1.0 - } - color { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - type: TYPE_BOX - blend_mode: BLEND_MODE_ALPHA - texture: "" - id: "playback_cursor/larrysafearea" - xanchor: XANCHOR_NONE - yanchor: YANCHOR_NONE - pivot: PIVOT_W - adjust_mode: ADJUST_MODE_FIT - parent: "playback_cursor" - layer: "" - inherit_alpha: true - slice9 { - x: 0.0 - y: 0.0 - z: 0.0 - w: 0.0 - } - clipping_mode: CLIPPING_MODE_NONE - clipping_visible: true - clipping_inverted: false - alpha: 0.0 - template_node_child: true - size_mode: SIZE_MODE_MANUAL - custom_type: 0 - enabled: true - visible: true - material: "" -} -nodes { - position { - x: 32.0 - y: -4.0 - z: 0.0 - w: 1.0 - } - rotation { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - scale { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - size { - x: 300.0 - y: 32.0 - z: 0.0 - w: 1.0 - } - color { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - type: TYPE_BOX - blend_mode: BLEND_MODE_ALPHA - texture: "dirtylarry/button_pressed" - id: "playback_cursor/larryslider" - xanchor: XANCHOR_NONE - yanchor: YANCHOR_NONE - pivot: PIVOT_W - adjust_mode: ADJUST_MODE_FIT - parent: "playback_cursor/larrysafearea" - layer: "" - inherit_alpha: false - slice9 { - x: 16.0 - y: 16.0 - z: 16.0 - w: 16.0 - } - clipping_mode: CLIPPING_MODE_NONE - clipping_visible: true - clipping_inverted: false - alpha: 1.0 - template_node_child: true - size_mode: SIZE_MODE_MANUAL - custom_type: 0 - enabled: true - visible: true - material: "" -} -nodes { - position { - x: 134.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - rotation { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - scale { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - size { - x: 32.0 - y: 32.0 - z: 0.0 - w: 1.0 - } - color { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - type: TYPE_BOX - blend_mode: BLEND_MODE_ALPHA - texture: "dirtylarry/radio_checked_normal" - id: "playback_cursor/larrycursor" - xanchor: XANCHOR_NONE - yanchor: YANCHOR_NONE - pivot: PIVOT_W - adjust_mode: ADJUST_MODE_FIT - parent: "playback_cursor/larryslider" - layer: "" - inherit_alpha: true - slice9 { - x: 0.0 - y: 0.0 - z: 0.0 - w: 0.0 - } - clipping_mode: CLIPPING_MODE_NONE - clipping_visible: true - clipping_inverted: false - alpha: 1.0 - template_node_child: true - size_mode: SIZE_MODE_MANUAL - custom_type: 0 - enabled: true - visible: true - material: "" -} -nodes { - position { - x: 306.0 - y: 3.0 - z: 0.0 - w: 1.0 - } - rotation { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - scale { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - size { - x: 200.0 - y: 42.0 - z: 0.0 - w: 1.0 - } - color { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - type: TYPE_TEXT - blend_mode: BLEND_MODE_ALPHA - text: "0.5" - font: "larryfont" - id: "playback_cursor/larryvalue" - xanchor: XANCHOR_NONE - yanchor: YANCHOR_NONE - pivot: PIVOT_W - outline { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - shadow { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - adjust_mode: ADJUST_MODE_FIT - line_break: false - parent: "playback_cursor/larryslider" - layer: "" - inherit_alpha: true - alpha: 1.0 - outline_alpha: 1.0 - shadow_alpha: 1.0 - template_node_child: true - text_leading: 1.0 - text_tracking: 0.0 - custom_type: 0 - enabled: true - visible: true - material: "" -} -nodes { - position { - x: -8.0 - y: 3.0 - z: 0.0 - w: 1.0 - } - rotation { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - scale { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - size { - x: 200.0 - y: 42.0 - z: 0.0 - w: 1.0 - } - color { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - type: TYPE_TEXT - blend_mode: BLEND_MODE_ALPHA - text: "Playback Cursor" - font: "larryfont" - id: "playback_cursor/larrylabel" - xanchor: XANCHOR_NONE - yanchor: YANCHOR_NONE - pivot: PIVOT_E - outline { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - shadow { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - adjust_mode: ADJUST_MODE_FIT - line_break: false - parent: "playback_cursor/larryslider" - layer: "" - inherit_alpha: true - alpha: 1.0 - outline_alpha: 1.0 - shadow_alpha: 1.0 - overridden_fields: 8 - template_node_child: true - text_leading: 1.0 - text_tracking: 0.0 - custom_type: 0 - enabled: true - visible: true - material: "" -} -nodes { - position { - x: 870.0 - y: 551.0 - z: 0.0 - w: 1.0 - } - rotation { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - scale { - x: 0.5 - y: 0.5 - z: 1.0 - w: 1.0 - } - size { - x: 200.0 - y: 100.0 - z: 0.0 - w: 1.0 - } - color { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - type: TYPE_TEMPLATE - id: "animation_cancel" - parent: "controls" - layer: "" - inherit_alpha: true - alpha: 1.0 - template: "/dirtylarry/button.gui" - template_node_child: false - custom_type: 0 - enabled: true -} -nodes { - position { - x: -16.0 - y: 5.0 - z: 0.0 - w: 1.0 - } - rotation { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - scale { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - size { - x: 350.0 - y: 88.0 - z: 0.0 - w: 1.0 - } - color { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - type: TYPE_BOX - blend_mode: BLEND_MODE_ALPHA - texture: "button/button_normal" - id: "animation_cancel/larrybutton" - xanchor: XANCHOR_NONE - yanchor: YANCHOR_NONE - pivot: PIVOT_CENTER - adjust_mode: ADJUST_MODE_FIT - parent: "animation_cancel" - layer: "" - inherit_alpha: true - slice9 { - x: 32.0 - y: 32.0 - z: 32.0 - w: 32.0 - } - clipping_mode: CLIPPING_MODE_NONE - clipping_visible: true - clipping_inverted: false - alpha: 1.0 - overridden_fields: 1 - overridden_fields: 4 - template_node_child: true - size_mode: SIZE_MODE_MANUAL - custom_type: 0 - enabled: true - visible: true - material: "" -} -nodes { - position { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - rotation { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - scale { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - size { - x: 200.0 - y: 100.0 - z: 0.0 - w: 1.0 - } - color { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - type: TYPE_TEXT - blend_mode: BLEND_MODE_ALPHA - text: "Stop" - font: "larryfont" - id: "animation_cancel/larrylabel" - xanchor: XANCHOR_NONE - yanchor: YANCHOR_NONE - pivot: PIVOT_CENTER - outline { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - shadow { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - adjust_mode: ADJUST_MODE_FIT - line_break: false - parent: "animation_cancel/larrybutton" - layer: "" - inherit_alpha: true - alpha: 1.0 - outline_alpha: 1.0 - shadow_alpha: 1.0 - overridden_fields: 8 - template_node_child: true - text_leading: 1.0 - text_tracking: 0.0 - custom_type: 0 - enabled: true - visible: true - material: "" -} -nodes { - position { - x: 870.0 - y: 439.0 - z: 0.0 - w: 1.0 - } - rotation { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - scale { - x: 0.5 - y: 0.5 - z: 1.0 - w: 1.0 - } - size { - x: 200.0 - y: 100.0 - z: 0.0 - w: 1.0 - } - color { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - type: TYPE_TEMPLATE - id: "animation_bouncing" - parent: "controls" - layer: "" - inherit_alpha: true - alpha: 1.0 - template: "/dirtylarry/button.gui" - template_node_child: false - custom_type: 0 - enabled: true -} -nodes { - position { - x: -16.0 - y: 5.0 - z: 0.0 - w: 1.0 - } - rotation { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - scale { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - size { - x: 350.0 - y: 88.0 - z: 0.0 - w: 1.0 - } - color { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - type: TYPE_BOX - blend_mode: BLEND_MODE_ALPHA - texture: "button/button_normal" - id: "animation_bouncing/larrybutton" - xanchor: XANCHOR_NONE - yanchor: YANCHOR_NONE - pivot: PIVOT_CENTER - adjust_mode: ADJUST_MODE_FIT - parent: "animation_bouncing" - layer: "" - inherit_alpha: true - slice9 { - x: 32.0 - y: 32.0 - z: 32.0 - w: 32.0 - } - clipping_mode: CLIPPING_MODE_NONE - clipping_visible: true - clipping_inverted: false - alpha: 1.0 - overridden_fields: 1 - overridden_fields: 4 - template_node_child: true - size_mode: SIZE_MODE_MANUAL - custom_type: 0 - enabled: true - visible: true - material: "" -} -nodes { - position { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - rotation { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - scale { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - size { - x: 200.0 - y: 100.0 - z: 0.0 - w: 1.0 - } - color { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - type: TYPE_TEXT - blend_mode: BLEND_MODE_ALPHA - text: "Bouncing\n" - "" - font: "larryfont" - id: "animation_bouncing/larrylabel" - xanchor: XANCHOR_NONE - yanchor: YANCHOR_NONE - pivot: PIVOT_CENTER - outline { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - shadow { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - adjust_mode: ADJUST_MODE_FIT - line_break: false - parent: "animation_bouncing/larrybutton" - layer: "" - inherit_alpha: true - alpha: 1.0 - outline_alpha: 1.0 - shadow_alpha: 1.0 - overridden_fields: 8 - template_node_child: true - text_leading: 1.0 - text_tracking: 0.0 - custom_type: 0 - enabled: true - visible: true - material: "" -} -nodes { - position { - x: 612.0 - y: 412.0 - z: 0.0 - w: 1.0 - } - rotation { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - scale { - x: 0.5 - y: 0.5 - z: 1.0 - w: 1.0 - } - size { - x: 200.0 - y: 100.0 - z: 0.0 - w: 1.0 - } - color { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - type: TYPE_TEMPLATE - id: "playback_loop_pingpong" - parent: "controls" - layer: "" - inherit_alpha: true - alpha: 1.0 - template: "/dirtylarry/radio_label.gui" - template_node_child: false - custom_type: 0 - enabled: true -} -nodes { - position { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - rotation { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - scale { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - size { - x: 64.0 - y: 68.0 - z: 0.0 - w: 1.0 - } - color { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - type: TYPE_BOX - blend_mode: BLEND_MODE_ALPHA - texture: "radio/radio_normal" - id: "playback_loop_pingpong/larryradio" - xanchor: XANCHOR_NONE - yanchor: YANCHOR_NONE - pivot: PIVOT_CENTER - adjust_mode: ADJUST_MODE_FIT - parent: "playback_loop_pingpong" - layer: "" - inherit_alpha: true - slice9 { - x: 0.0 - y: 0.0 - z: 0.0 - w: 0.0 - } - clipping_mode: CLIPPING_MODE_NONE - clipping_visible: true - clipping_inverted: false - alpha: 1.0 - template_node_child: true - size_mode: SIZE_MODE_MANUAL - custom_type: 0 - enabled: true - visible: true - material: "" -} -nodes { - position { - x: 46.0 - y: 3.0 - z: 0.0 - w: 1.0 - } - rotation { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - scale { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - size { - x: 200.0 - y: 50.0 - z: 0.0 - w: 1.0 - } - color { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - type: TYPE_TEXT - blend_mode: BLEND_MODE_ALPHA - text: "Loop Ping Pong\n" - "" - font: "larryfont" - id: "playback_loop_pingpong/larrylabel" - xanchor: XANCHOR_NONE - yanchor: YANCHOR_NONE - pivot: PIVOT_W - outline { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - shadow { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - adjust_mode: ADJUST_MODE_FIT - line_break: false - parent: "playback_loop_pingpong" - layer: "" - inherit_alpha: true - alpha: 1.0 - outline_alpha: 1.0 - shadow_alpha: 1.0 - overridden_fields: 8 - template_node_child: true - text_leading: 1.0 - text_tracking: 0.0 - custom_type: 0 - enabled: true - visible: true - material: "" -} -nodes { - position { - x: 612.0 - y: 452.0 - z: 0.0 - w: 1.0 - } - rotation { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - scale { - x: 0.5 - y: 0.5 - z: 1.0 - w: 1.0 - } - size { - x: 200.0 - y: 100.0 - z: 0.0 - w: 1.0 - } - color { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - type: TYPE_TEMPLATE - id: "playback_loop_backward" - parent: "controls" - layer: "" - inherit_alpha: true - alpha: 1.0 - template: "/dirtylarry/radio_label.gui" - template_node_child: false - custom_type: 0 - enabled: true -} -nodes { - position { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - rotation { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - scale { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - size { - x: 64.0 - y: 68.0 - z: 0.0 - w: 1.0 - } - color { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - type: TYPE_BOX - blend_mode: BLEND_MODE_ALPHA - texture: "radio/radio_normal" - id: "playback_loop_backward/larryradio" - xanchor: XANCHOR_NONE - yanchor: YANCHOR_NONE - pivot: PIVOT_CENTER - adjust_mode: ADJUST_MODE_FIT - parent: "playback_loop_backward" - layer: "" - inherit_alpha: true - slice9 { - x: 0.0 - y: 0.0 - z: 0.0 - w: 0.0 - } - clipping_mode: CLIPPING_MODE_NONE - clipping_visible: true - clipping_inverted: false - alpha: 1.0 - template_node_child: true - size_mode: SIZE_MODE_MANUAL - custom_type: 0 - enabled: true - visible: true - material: "" -} -nodes { - position { - x: 46.0 - y: 3.0 - z: 0.0 - w: 1.0 - } - rotation { - x: 0.0 - y: 0.0 - z: 0.0 - w: 1.0 - } - scale { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - size { - x: 200.0 - y: 50.0 - z: 0.0 - w: 1.0 - } - color { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - type: TYPE_TEXT - blend_mode: BLEND_MODE_ALPHA - text: "Loop Backward" - font: "larryfont" - id: "playback_loop_backward/larrylabel" - xanchor: XANCHOR_NONE - yanchor: YANCHOR_NONE - pivot: PIVOT_W - outline { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - shadow { - x: 1.0 - y: 1.0 - z: 1.0 - w: 1.0 - } - adjust_mode: ADJUST_MODE_FIT - line_break: false - parent: "playback_loop_backward" - layer: "" - inherit_alpha: true - alpha: 1.0 - outline_alpha: 1.0 - shadow_alpha: 1.0 - overridden_fields: 8 - template_node_child: true - text_leading: 1.0 - text_tracking: 0.0 - custom_type: 0 - enabled: true - visible: true - material: "" -} -material: "/builtins/materials/gui.material" -adjust_reference: ADJUST_REFERENCE_PARENT -max_nodes: 512 \ No newline at end of file diff --git a/main/car/gui.gui_script b/main/car/gui.gui_script deleted file mode 100644 index de375376..00000000 --- a/main/car/gui.gui_script +++ /dev/null @@ -1,107 +0,0 @@ -local dirtylarry = require "dirtylarry/dirtylarry" - -function init(self) - msg.post(".", "acquire_input_focus") - - self.playback_rate = 1.0 - self.playback_offset = 0.0 - self.playback_cursor = 0.0 - self.playback_value = go.PLAYBACK_LOOP_FORWARD - self.animation_label = gui.get_node("animation_label/larrylabel") - self.cursor_node = gui.get_node("playback_cursor/larrysafearea") - - clear_animation_label(self) -end - -function animation_play(self, anim) - self.anim = anim - gui.set_text(self.animation_label, "Animation: " .. anim) - msg.post("/go#main", "MSG_PLAY", { - animation = hash(anim), - playback = self.playback_value, - rate = self.playback_rate, - offset = self.playback_offset, - }) -end - -function animation_set_rate(self, rate) - msg.post("/go#main", "MSG_PLAYBACK_RATE", { - rate = self.playback_rate, - }) -end - -function animation_set_cursor(self, cursor) - msg.post("/go#main", "MSG_PLAYBACK_CURSOR", { - cursor = self.playback_cursor, - }) -end - -function clear_animation_label(self) - gui.set_text(self.animation_label, "Animation: none") -end - -function animation_cancel(self) - clear_animation_label(self) - msg.post("/go#main", "MSG_CANCEL") -end - -function on_input(self, action_id, action) - local playback_value = self.playback_value - local playback_rate = self.playback_rate - local playback_cursor = self.playback_cursor - - self.playback_value = dirtylarry:radio("playback_once_forward", action_id, action, go.PLAYBACK_ONCE_FORWARD, self.playback_value) - self.playback_value = dirtylarry:radio("playback_once_backward", action_id, action, go.PLAYBACK_ONCE_BACKWARD, self.playback_value) - self.playback_value = dirtylarry:radio("playback_once_pingpong", action_id, action, go.PLAYBACK_ONCE_PINGPONG, self.playback_value) - self.playback_value = dirtylarry:radio("playback_loop_forward", action_id, action, go.PLAYBACK_LOOP_FORWARD, self.playback_value) - self.playback_value = dirtylarry:radio("playback_loop_backward", action_id, action, go.PLAYBACK_LOOP_BACKWARD, self.playback_value) - self.playback_value = dirtylarry:radio("playback_loop_pingpong", action_id, action, go.PLAYBACK_LOOP_PINGPONG, self.playback_value) - - self.playback_rate = dirtylarry:slider("playback_rate", action_id, action, 0.0, 1.0, self.playback_rate) - self.playback_offset = dirtylarry:slider("playback_offset", action_id, action, 0.0, 1.0, self.playback_offset) - self.playback_cursor = dirtylarry:slider("playback_cursor", action_id, action, 0.0, 1.0, self.playback_cursor) - - if self.playback_value ~= playback_value and self.anim ~= nil then - animation_play(self, self.anim) - elseif self.playback_rate ~= playback_rate and self.anim ~= nil then - animation_set_rate(self, self.playback_rate) - end - - if self.playback_cursor ~= playback_cursor and self.anim ~= nil then - animation_set_cursor(self, self.playback_cursor) - end - - dirtylarry:button("animation_cancel", action_id, action, function () - animation_cancel(self) - end) - - dirtylarry:button("animation_idle", action_id, action, function () - animation_play(self, "idle") - end) - - dirtylarry:button("animation_bouncing", action_id, action, function () - animation_play(self, "bouncing") - end) - - dirtylarry:button("animation_windshield_wipers", action_id, action, function () - animation_play(self, "windshield_wipers") - end) - - dirtylarry:button("animation_broken", action_id, action, function () - animation_play(self, "broken") - end) -end - -function on_message(self, message_id, message) - if message_id == hash("animation_complete") then - clear_animation_label(self) - elseif message_id == hash("animation_cursor") then - if dirtylarry.active_node ~= nil and gui.get_id(dirtylarry.active_node) == gui.get_id(self.cursor_node) then - return - end - - self.playback_cursor = message.cursor - self.playback_cursor = dirtylarry:slider("playback_cursor", hash("touch"), { x = -1, y = -1 }, 0.0, 1.0, self.playback_cursor) - end -end - diff --git a/main/cursor/cursor.collection b/main/cursor/cursor.collection deleted file mode 100644 index 4260a650..00000000 --- a/main/cursor/cursor.collection +++ /dev/null @@ -1,31 +0,0 @@ -name: "cursor" -instances { - id: "back" - prototype: "/main/menu/back.go" -} -scale_along_z: 0 -embedded_instances { - id: "go" - data: "components {\n" - " id: \"cursor\"\n" - " component: \"/main/cursor/cursor.script\"\n" - "}\n" - "embedded_components {\n" - " id: \"rivemodel\"\n" - " type: \"rivemodel\"\n" - " data: \"scene: \\\"/main/cursor/emoji.rivescene\\\"\\n" - "default_animation: \\\"Dart_board\\\"\\n" - "material: \\\"/defold-rive/assets/rivemodel.material\\\"\\n" - "artboard: \\\"New Artboard\\\"\\n" - "\"\n" - "}\n" - "" - position { - x: 480.0 - y: 323.0 - } - scale3 { - x: 0.5 - y: 0.5 - } -} diff --git a/main/cursor/cursor.script b/main/cursor/cursor.script deleted file mode 100644 index e8090efb..00000000 --- a/main/cursor/cursor.script +++ /dev/null @@ -1,9 +0,0 @@ -function init(self) - self.url = "#rivemodel" - go.set(self.url, "cursor", 1.0) - go.animate(self.url, "cursor", go.PLAYBACK_LOOP_FORWARD, 0.0, go.EASING_LINEAR, 1) -end - -function update(self, dt) - print("cursor", go.get(self.url, "cursor")) -end diff --git a/main/cursor/emoji.riv b/main/cursor/emoji.riv deleted file mode 100644 index 2d3bdb36..00000000 Binary files a/main/cursor/emoji.riv and /dev/null differ diff --git a/main/cursor/emoji.rivescene b/main/cursor/emoji.rivescene deleted file mode 100644 index 2ca2aeb9..00000000 --- a/main/cursor/emoji.rivescene +++ /dev/null @@ -1,2 +0,0 @@ -scene: "/main/cursor/emoji.riv" -atlas: "/defold-rive/assets/empty.atlas" diff --git a/main/databind/14447-40690-game-achievement-badge-data-binding.riv b/main/databind/14447-40690-game-achievement-badge-data-binding.riv new file mode 100644 index 00000000..364d9621 Binary files /dev/null and b/main/databind/14447-40690-game-achievement-badge-data-binding.riv differ diff --git a/main/databind/achievement.rivescene b/main/databind/achievement.rivescene new file mode 100644 index 00000000..7b89d127 --- /dev/null +++ b/main/databind/achievement.rivescene @@ -0,0 +1,2 @@ +scene: "/main/databind/14447-40690-game-achievement-badge-data-binding.riv" +atlas: "/defold-rive/assets/empty.atlas" diff --git a/main/databind/calc.riv b/main/databind/calc.riv deleted file mode 100644 index 9fa7e3d2..00000000 Binary files a/main/databind/calc.riv and /dev/null differ diff --git a/main/databind/calc.rivemodel b/main/databind/calc.rivemodel deleted file mode 100644 index d70d1a77..00000000 --- a/main/databind/calc.rivemodel +++ /dev/null @@ -1,5 +0,0 @@ -scene: "/main/databind/calc.rivescene" -default_animation: "" -material: "/defold-rive/assets/rivemodel.material" -default_state_machine: "State Machine 1" -artboard: "Artboard" diff --git a/main/databind/calc.rivescene b/main/databind/calc.rivescene deleted file mode 100644 index 6510d441..00000000 --- a/main/databind/calc.rivescene +++ /dev/null @@ -1,2 +0,0 @@ -scene: "/main/databind/calc.riv" -atlas: "/defold-rive/assets/empty.atlas" diff --git a/main/databind/databind.collection b/main/databind/databind.collection index 379d5315..19535069 100644 --- a/main/databind/databind.collection +++ b/main/databind/databind.collection @@ -11,21 +11,19 @@ embedded_instances { " component: \"/main/databind/databind.script\"\n" "}\n" "embedded_components {\n" - " id: \"modal\"\n" + " id: \"rivemodel\"\n" " type: \"rivemodel\"\n" - " data: \"scene: \\\"/main/databind/modal.rivescene\\\"\\n" - "default_animation: \\\"textVariation1\\\"\\n" + " data: \"scene: \\\"/main/databind/achievement.rivescene\\\"\\n" + "default_animation: \\\"\\\"\\n" "material: \\\"/defold-rive/assets/rivemodel.material\\\"\\n" - "default_state_machine: \\\"State Machine 1\\\"\\n" - "artboard: \\\"Main\\\"\\n" + "coordinate_system: COORDINATE_SYSTEM_RIVE\\n" + "artboard_fit: FIT_CONTAIN\\n" + "blit_material: \\\"/defold-rive/assets/shader-library/rivemodel_blit.material\\\"\\n" "\"\n" "}\n" "" position { - x: 477.7781 + x: 476.77814 y: 268.6295 } - scale3 { - z: 0.82 - } } diff --git a/main/databind/databind.script b/main/databind/databind.script index 1f332131..660df311 100644 --- a/main/databind/databind.script +++ b/main/databind/databind.script @@ -1,27 +1,101 @@ --- CREDITS: --- calc.riv is from user https://rive.app/@thefloridianfreak/: --- https://rive.app/marketplace/19344-36364-supplied-mutliplication/ --- dynamic_modal.riv by https://rive.app/@drawsgood/: --- https://rive.app/marketplace/19673-37017-dynamic-modal/ +local function set_listeners(self) + rive.set_file_listener(function (self, message_id, message) + pprint("FILE LISTENER", message_id, message) + end) + + rive.set_artboard_listener(function (self, message_id, message) + pprint("ARTBOARD LISTENER", message_id, message) + end) + + rive.set_state_machine_listener(function (self, message_id, message) + pprint("STATEMACHINE LISTENER", message_id, message) + end) + + rive.set_view_model_instance_listener(function (self, message_id, message) + pprint("VIEWMODEL LISTENER", message_id, message) + end) + + rive.set_render_image_listener(function (self, message_id, message) + pprint("RENDERIMAGE LISTENER", message_id, message) + end) + + rive.set_audio_source_listener(function (self, message_id, message) + pprint("AUDIO SOURCE LISTENER", message_id, message) + end) + + rive.set_font_listener(function (self, message_id, message) + pprint("FONT LISTENER", message_id, message) + end) +end function init(self) msg.post(".", "acquire_input_focus") - self.url = msg.url("#modal") - self.handle, err = rive.databind.create_view_model_instance_runtime(self.url, "") --select the first view model - if self.handle == nil then - print("ERROR:", err) - return - end - rive.databind.set_view_model_instance_runtime(self.url, self.handle) - - self.data = { - menuIsOpen = true, - accentColor = vmath.vector4(1,1,0,1), - modalCopy = "Hello Folks! This is a test of data bindings between the Rive scene and the Defold Game Engine!", - } - rive.databind.set_properties(self.url, self.handle, self.data) + set_listeners(self) + + self.url = msg.url("#rivemodel") + self.file = rive.get_file(self.url) + self.artboard = rive.get_artboard(self.url) + self.state_machine = rive.get_state_machine(self.url) + self.view_model = rive.get_view_model_instance(self.url) + + -- debugging + rive.cmd.requestViewModelNames(self.file) + rive.cmd.requestArtboardNames(self.file) + rive.cmd.requestViewModelEnums(self.file) + rive.cmd.requestStateMachineNames(self.artboard) + rive.cmd.requestDefaultViewModelInfo(self.artboard, self.file) + + rive.cmd.requestViewModelInstanceNames(self.file, "vmAchiementBadge") + rive.cmd.requestViewModelPropertyDefinitions(self.file, "vmAchiementBadge") + + rive.cmd.requestViewModelInstanceNames(self.file, "vmBadge") + rive.cmd.requestViewModelPropertyDefinitions(self.file, "vmBadge") + + rive.cmd.requestViewModelInstanceNames(self.file, "vmRating") + rive.cmd.requestViewModelPropertyDefinitions(self.file, "vmRating") + + -- end debugging + + -- {"requestViewModelNames", Script_requestViewModelNames}, + -- {"requestArtboardNames", Script_requestArtboardNames}, + -- {"requestViewModelEnums", Script_requestViewModelEnums}, + + -- {"requestViewModelPropertyDefinitions", Script_requestViewModelPropertyDefinitions}, + -- {"requestViewModelInstanceNames", Script_requestViewModelInstanceNames}, + -- {"requestViewModelInstanceBool", Script_requestViewModelInstanceBool}, + -- {"requestViewModelInstanceNumber", Script_requestViewModelInstanceNumber}, + -- {"requestViewModelInstanceColor", Script_requestViewModelInstanceColor}, + -- {"requestViewModelInstanceEnum", Script_requestViewModelInstanceEnum}, + -- {"requestViewModelInstanceString", Script_requestViewModelInstanceString}, + -- {"requestViewModelInstanceListSize", Script_requestViewModelInstanceListSize}, + + -- {"requestStateMachineNames", Script_requestStateMachineNames}, + -- {"requestDefaultViewModelInfo", Script_requestDefaultViewModelInfo}, + + + --self.view_model = rive.cmd.instantiateDefaultViewModelInstance(self.file, self.artboard) + self.view_model_flag = rive.cmd.referenceNestedViewModelInstance(self.view_model, "property of vmFlag") + self.view_model_badge = rive.cmd.referenceNestedViewModelInstance(self.view_model, "property of vmBadge") + self.view_model_rating = rive.cmd.referenceNestedViewModelInstance(self.view_model, "property of vmRating") + + -- no need to bind, as it has "autobind" selected + --rive.cmd.bindViewModelInstance(self.state_machine, self.view_model) + + self.isOpen = true + rive.cmd.setViewModelInstanceBool(self.view_model, "isOpen", self.isOpen) + + rive.cmd.setViewModelInstanceString(self.view_model_flag, "flagText", "DEFOLD!") + rive.cmd.setViewModelInstanceColor(self.view_model_flag, "flagColor", vmath.vector4(0.5, 0.3, 0.4, 1.0)) + + -- 1 = "Froggo", + -- 2 = "Skulla", + -- 3 = "Castela" + rive.cmd.setViewModelInstanceEnum(self.view_model_badge, "badgeDesign", "Castela") + + rive.cmd.setViewModelInstanceNumber(self.view_model_rating, "stars", 5) + end function final(self) @@ -44,12 +118,16 @@ end function on_input(self, action_id, action) if not action_id or action_id == hash("touch") then + if action.pressed then - rive.pointer_down(self.url, action.x, action.y) + self.isOpen = not self.isOpen + rive.cmd.setViewModelInstanceBool(self.view_model, "isOpen", self.isOpen) + + --rive.pointer_down(self.url, action.x, action.y) elseif action.released then - rive.pointer_up(self.url, action.x, action.y) + --rive.pointer_up(self.url, action.x, action.y) else - rive.pointer_move(self.url, action.x, action.y) + --rive.pointer_move(self.url, action.x, action.y) end end end diff --git a/main/databind/dynamic_modal.riv b/main/databind/dynamic_modal.riv deleted file mode 100644 index 80693114..00000000 Binary files a/main/databind/dynamic_modal.riv and /dev/null differ diff --git a/main/databind/loader_example_for_data_binding.riv b/main/databind/loader_example_for_data_binding.riv deleted file mode 100644 index 37dd6992..00000000 Binary files a/main/databind/loader_example_for_data_binding.riv and /dev/null differ diff --git a/main/databind/modal.rivescene b/main/databind/modal.rivescene deleted file mode 100644 index ed98c0b6..00000000 --- a/main/databind/modal.rivescene +++ /dev/null @@ -1,2 +0,0 @@ -scene: "/main/databind/dynamic_modal.riv" -atlas: "/defold-rive/assets/empty.atlas" diff --git a/main/databind/progress.rivescene b/main/databind/progress.rivescene deleted file mode 100644 index aeed2c0f..00000000 --- a/main/databind/progress.rivescene +++ /dev/null @@ -1,2 +0,0 @@ -scene: "/main/databind/loader_example_for_data_binding.riv" -atlas: "/defold-rive/assets/empty.atlas" diff --git a/main/egg/egg.rivemodel b/main/egg/egg.rivemodel index 9cb37666..d82de30e 100644 --- a/main/egg/egg.rivemodel +++ b/main/egg/egg.rivemodel @@ -1,5 +1,4 @@ scene: "/main/egg/egg.rivescene" -default_animation: "Motion" +default_animation: "" material: "/defold-rive/assets/rivemodel.material" -default_state_machine: "State Machine 1" -artboard: "Artboard 3" +blit_material: "/defold-rive/assets/shader-library/rivemodel_blit.material" diff --git a/main/fighting-game/fighter_game_player_v6_events.riv b/main/fighting-game/fighter_game_player_v6_events.riv deleted file mode 100644 index 78b495a1..00000000 Binary files a/main/fighting-game/fighter_game_player_v6_events.riv and /dev/null differ diff --git a/main/fighting-game/fighting-game.collection b/main/fighting-game/fighting-game.collection deleted file mode 100644 index 963332fe..00000000 --- a/main/fighting-game/fighting-game.collection +++ /dev/null @@ -1,34 +0,0 @@ -name: "grimley" -instances { - id: "back" - prototype: "/main/menu/back.go" -} -scale_along_z: 0 -embedded_instances { - id: "go" - data: "components {\n" - " id: \"fighting-game\"\n" - " component: \"/main/fighting-game/fighting-game.script\"\n" - "}\n" - "embedded_components {\n" - " id: \"model\"\n" - " type: \"rivemodel\"\n" - " data: \"scene: \\\"/main/fighting-game/fighting-game.rivescene\\\"\\n" - "default_animation: \\\"\\\"\\n" - "material: \\\"/defold-rive/assets/rivemodel.material\\\"\\n" - "default_state_machine: \\\"State Machine 1\\\"\\n" - "artboard: \\\"Main\\\"\\n" - "coordinate_system: COORDINATE_SYSTEM_RIVE\\n" - "artboard_fit: FIT_CONTAIN\\n" - "\"\n" - "}\n" - "" - position { - x: 480.0 - y: 270.0 - } - scale3 { - x: 0.5 - y: 0.5 - } -} diff --git a/main/fighting-game/fighting-game.rivescene b/main/fighting-game/fighting-game.rivescene deleted file mode 100644 index 0ac5f6ab..00000000 --- a/main/fighting-game/fighting-game.rivescene +++ /dev/null @@ -1,2 +0,0 @@ -scene: "/main/fighting-game/fighter_game_player_v6_events.riv" -atlas: "/defold-rive/assets/empty.atlas" diff --git a/main/fighting-game/fighting-game.script b/main/fighting-game/fighting-game.script deleted file mode 100644 index ee26a8c7..00000000 --- a/main/fighting-game/fighting-game.script +++ /dev/null @@ -1,42 +0,0 @@ -function init(self) - msg.post(".", "acquire_input_focus") - - rive.play_state_machine("#model", "State Machine 1", nil, function(self, message_id, message) - print("play_state_machine", message_id) - pprint(message) - end) - - self.player_one_selection = { x = 1, y = 0, selected = false } - self.player_two_selection = { x = 5, y = 0, selected = false } -end - -function clamp_and_get_selection(self, sel) - if sel.x < 1 then sel.x = 1 - elseif sel.x > 5 then sel.x = 5 end - if sel.y < 0 then sel.y = 0 - elseif sel.y > 1 then sel.y = 1 end - return sel.y * 5 + sel.x -end - -function on_input(self, action_id, action) - - if action.released then - if action_id == hash("right") then - self.player_one_selection.x = self.player_one_selection.x + 1 - go.set("#model", "player1MasterSelection", clamp_and_get_selection(self, self.player_one_selection)) - elseif action_id == hash("left") then - self.player_one_selection.x = self.player_one_selection.x - 1 - go.set("#model", "player1MasterSelection", clamp_and_get_selection(self, self.player_one_selection)) - elseif action_id == hash("down") then - self.player_one_selection.y = self.player_one_selection.y + 1 - go.set("#model", "player1MasterSelection", clamp_and_get_selection(self, self.player_one_selection)) - elseif action_id == hash("up") then - self.player_one_selection.y = self.player_one_selection.y - 1 - go.set("#model", "player1MasterSelection", clamp_and_get_selection(self, self.player_one_selection)) - elseif action_id == hash("enter") then - self.player_one_selection.selected = not self.player_one_selection.selected - go.set("#model", "player1MasterConfirmed", self.player_one_selection.selected) - end - end -end - \ No newline at end of file diff --git a/main/ghost/ghost.collection b/main/ghost/ghost.collection index e94c24b1..35089a26 100644 --- a/main/ghost/ghost.collection +++ b/main/ghost/ghost.collection @@ -20,6 +20,7 @@ embedded_instances { "artboard: \\\"New Artboard\\\"\\n" "coordinate_system: COORDINATE_SYSTEM_RIVE\\n" "artboard_fit: FIT_CONTAIN\\n" + "blit_material: \\\"/defold-rive/assets/shader-library/rivemodel_blit.material\\\"\\n" "\"\n" "}\n" "" diff --git a/main/grimley/4951-10031-grimley.riv b/main/grimley/4951-10031-grimley.riv index 383db7f5..621c1a9b 100644 Binary files a/main/grimley/4951-10031-grimley.riv and b/main/grimley/4951-10031-grimley.riv differ diff --git a/main/grimley/grimley.script b/main/grimley/grimley.script index ac27116a..72497cc9 100644 --- a/main/grimley/grimley.script +++ b/main/grimley/grimley.script @@ -1,6 +1,30 @@ +local function rive_listener(self, message_name, data) + pprint("file:", message_name, data) +end + function init(self) - --rive.play_anim("#model", "panelAnimateOn", go.PLAYBACK_LOOP_FORWARD) - --rive.play_anim("#model", "cape", go.PLAYBACK_LOOP_FORWARD) - --rive.play_anim("#model", "bodyLoop", go.PLAYBACK_LOOP_FORWARD) - + msg.post(".", "acquire_input_focus") + + rive.set_file_listener(rive_listener) + + self.url = "#model" + + local artboard = rive.get_artboard(self.url) + local state_machine = rive.get_state_machine(self.url) + print("artboard:", artboard) + print("state_machine:", state_machine) +end + +function on_input(self, action_id, action) + if hash("touch") == action_id then + -- rive.set_artboard("#model", "Dwarf_SeparateExport.psd") + -- rive.set_state_machine("#model", "State Machine 1") + if action.pressed then + rive.pointer_down(self.url, action.x, action.y) + elseif action.released then + rive.pointer_up(self.url, action.x, action.y) + end + elseif action_id == nil then -- mouse move + rive.pointer_move(self.url, action.x, action.y) + end end diff --git a/main/lights/lights.collection b/main/lights/lights.collection deleted file mode 100644 index 6c6747a3..00000000 --- a/main/lights/lights.collection +++ /dev/null @@ -1,22 +0,0 @@ -name: "lights" -instances { - id: "back" - prototype: "/main/menu/back.go" -} -scale_along_z: 0 -embedded_instances { - id: "go" - data: "components {\n" - " id: \"lights\"\n" - " component: \"/main/lights/lights.rivemodel\"\n" - "}\n" - "" - position { - x: 480.0 - y: 270.0 - } - scale3 { - x: 2.0 - y: 2.0 - } -} diff --git a/main/lights/lights.riv b/main/lights/lights.riv deleted file mode 100644 index 637b61ff..00000000 Binary files a/main/lights/lights.riv and /dev/null differ diff --git a/main/lights/lights.rivemodel b/main/lights/lights.rivemodel deleted file mode 100644 index 06628fb7..00000000 --- a/main/lights/lights.rivemodel +++ /dev/null @@ -1,6 +0,0 @@ -scene: "/main/lights/lights.rivescene" -default_animation: "Animation 1" -material: "/defold-rive/assets/rivemodel.material" -artboard: "Lights" -coordinate_system: COORDINATE_SYSTEM_RIVE -artboard_fit: FIT_CONTAIN diff --git a/main/lights/lights.rivescene b/main/lights/lights.rivescene deleted file mode 100644 index df47a872..00000000 --- a/main/lights/lights.rivescene +++ /dev/null @@ -1,2 +0,0 @@ -scene: "/main/lights/lights.riv" -atlas: "/defold-rive/assets/empty.atlas" diff --git a/main/loader.collection b/main/loader.collection index 74984f6a..23c2a4d7 100644 --- a/main/loader.collection +++ b/main/loader.collection @@ -7,36 +7,12 @@ embedded_instances { " component: \"/main/loader.script\"\n" "}\n" "embedded_components {\n" - " id: \"bones\"\n" - " type: \"collectionproxy\"\n" - " data: \"collection: \\\"/main/bones/bones.collection\\\"\\n" - "\"\n" - "}\n" - "embedded_components {\n" - " id: \"car\"\n" - " type: \"collectionproxy\"\n" - " data: \"collection: \\\"/main/car/car.collection\\\"\\n" - "\"\n" - "}\n" - "embedded_components {\n" - " id: \"cursor\"\n" - " type: \"collectionproxy\"\n" - " data: \"collection: \\\"/main/cursor/cursor.collection\\\"\\n" - "\"\n" - "}\n" - "embedded_components {\n" " id: \"menu\"\n" " type: \"collectionproxy\"\n" " data: \"collection: \\\"/main/menu/menu.collection\\\"\\n" "\"\n" "}\n" "embedded_components {\n" - " id: \"lights\"\n" - " type: \"collectionproxy\"\n" - " data: \"collection: \\\"/main/lights/lights.collection\\\"\\n" - "\"\n" - "}\n" - "embedded_components {\n" " id: \"state\"\n" " type: \"collectionproxy\"\n" " data: \"collection: \\\"/main/statemachine/statemachine.collection\\\"\\n" @@ -79,12 +55,6 @@ embedded_instances { "\"\n" "}\n" "embedded_components {\n" - " id: \"fighting-game\"\n" - " type: \"collectionproxy\"\n" - " data: \"collection: \\\"/main/fighting-game/fighting-game.collection\\\"\\n" - "\"\n" - "}\n" - "embedded_components {\n" " id: \"ghost\"\n" " type: \"collectionproxy\"\n" " data: \"collection: \\\"/main/ghost/ghost.collection\\\"\\n" diff --git a/main/menu/menu.gui_script b/main/menu/menu.gui_script index 4be9c9a4..07629200 100644 --- a/main/menu/menu.gui_script +++ b/main/menu/menu.gui_script @@ -2,18 +2,11 @@ local dirtylarry = require "dirtylarry/dirtylarry" local BUTTONS = { - { id = "car", text = "Car" }, - { id = "lights", text = "Lights" }, - --{ id = "bones", text = "Bones" }, - --{ id = "cursor", text = "Cursor" }, - --{ id = "state", text = "State" }, { id = "sophiahud", text = "Sophia" }, { id = "scifihud", text = "Sci-fi" }, - --{ id = "circleui", text = "Circle UI" }, { id = "takethis", text = "Take This!" }, { id = "ac2", text = "Assassin" }, { id = "grimley", text = "Grimley" }, - { id = "fighting-game", text = "Fight!" }, { id = "ghost", text = "Ghost UI" }, { id = "layout", text = "Layouts" }, { id = "egg", text = "Feathering" }, diff --git a/main/outofband/out-of-band.rivescene b/main/outofband/out-of-band.rivescene new file mode 100644 index 00000000..6ac957cc --- /dev/null +++ b/main/outofband/out-of-band.rivescene @@ -0,0 +1,2 @@ +scene: "/main/outofband/out-of-band/out-of-band-assets.riv" +atlas: "/defold-rive/assets/empty.atlas" diff --git a/main/outofband/out-of-band/out-of-band-assets.rev b/main/outofband/out-of-band/out-of-band-assets.rev new file mode 100644 index 00000000..e7842bb7 Binary files /dev/null and b/main/outofband/out-of-band/out-of-band-assets.rev differ diff --git a/main/outofband/out-of-band/out-of-band-assets.riv b/main/outofband/out-of-band/out-of-band-assets.riv new file mode 100644 index 00000000..1974ea38 Binary files /dev/null and b/main/outofband/out-of-band/out-of-band-assets.riv differ diff --git a/main/outofband/outofband.collection b/main/outofband/outofband.collection index f4ba9296..f0ea2915 100644 --- a/main/outofband/outofband.collection +++ b/main/outofband/outofband.collection @@ -13,20 +13,20 @@ embedded_instances { data: "embedded_components {\n" " id: \"rivemodel\"\n" " type: \"rivemodel\"\n" - " data: \"scene: \\\"/main/outofband/walle.rivescene\\\"\\n" - "default_animation: \\\"Animation 1\\\"\\n" + " data: \"scene: \\\"/main/outofband/out-of-band.rivescene\\\"\\n" + "default_animation: \\\"\\\"\\n" "material: \\\"/defold-rive/assets/rivemodel.material\\\"\\n" - "artboard: \\\"New Artboard\\\"\\n" + "blit_material: \\\"/defold-rive/assets/shader-library/rivemodel_blit.material\\\"\\n" "\"\n" "}\n" "" position { - x: 471.745 - y: 251.97 + x: 456.745 + y: 259.97 } scale3 { - x: 0.66 - y: 0.66 + x: 0.372221 + y: 0.368649 z: 0.66 } } @@ -38,24 +38,3 @@ embedded_instances { "}\n" "" } -embedded_instances { - id: "go_rive2" - data: "components {\n" - " id: \"referencedfontassets\"\n" - " component: \"/main/outofband/font/referencedfontassets.rivemodel\"\n" - " position {\n" - " x: 466.66666\n" - " }\n" - "}\n" - "" - position { - x: 471.745 - y: 251.97 - z: -0.1 - } - scale3 { - x: 0.66 - y: 0.66 - z: 0.66 - } -} diff --git a/main/outofband/outofband.script b/main/outofband/outofband.script index 99444b6a..4970f90a 100644 --- a/main/outofband/outofband.script +++ b/main/outofband/outofband.script @@ -1,12 +1,14 @@ -- There are multiple ways to load an image file. --- Note however that, for the "Runtime Asset Swap" feature, it's necessary to provide the raw data as-is. +-- When loading assets via the rive command queue api feature, it's necessary to provide the raw data as-is. -- * Load it via our resource system: -- * Path needs to be mounted (archive file, zip file, loose file) -- * Included as "custom resource" -- * Download using http, to a specific path available to the resource system -- * Pass the payload directly to the rive.riv_swap_asset() function -local URL = "https://defold.com/images/logo/defold/logo_with_text/logo-ver-classic-white-160.png" +-- Example from: https://codesandbox.io/p/sandbox/objective-cohen-sqwh9q + +local URL = "https://defold.com/images/logo/defold/logo/logo-ver-classic-white-320.png" local URL_FONT = "http://themes.googleusercontent.com/static/fonts/abeezee/v1/JYPhMn-3Xw-JGuyB-fEdNA.ttf" -- path to your dlc files. For simplicity, this is at the root of the project @@ -18,97 +20,119 @@ local RIVE_MODEL_2 = "go_rive2#referencedfontassets" local function swap_assets(self) local rivc = go.get(RIVE_MODEL, "rive_file") - rive.riv_swap_asset(rivc, "eve.png", { path = "/main/outofband/walle/eve.png" }) - -- no idea why they named it jpg - rive.riv_swap_asset(rivc, "walle.jpg", { path = "/main/outofband/walle/walle.png" }) + -- rive.riv_swap_asset(rivc, "eve.png", { path = "/main/outofband/walle/eve.png" }) + -- -- no idea why they named it jpg + -- rive.riv_swap_asset(rivc, "walle.jpg", { path = "/main/outofband/walle/walle.png" }) end +local function set_listeners(self) + rive.set_file_listener(function (self, message_id, message) + pprint("FILE LISTENER", message_id, message) + end) + + rive.set_artboard_listener(function (self, message_id, message) + pprint("ARTBOARD LISTENER", message_id, message) + end) + + rive.set_state_machine_listener(function (self, message_id, message) + pprint("STATEMACHINE LISTENER", message_id, message) + end) + + rive.set_view_model_instance_listener(function (self, message_id, message) + pprint("VIEWMODEL LISTENER", message_id, message) + end) + + rive.set_render_image_listener(function (self, message_id, message) + pprint("RENDERIMAGE LISTENER", message_id, message) + end) + + rive.set_audio_source_listener(function (self, message_id, message) + pprint("AUDIO SOURCE LISTENER", message_id, message) + end) + + rive.set_font_listener(function (self, message_id, message) + pprint("FONT LISTENER", message_id, message) + end) +end function init(self) + set_listeners(self) + + msg.post(".", "acquire_input_focus") + local mount_name = "files" local mount_found = false - for _,mount in pairs(liveupdate.get_mounts()) do - if mount.name == mount_name then - mount_found = true - end - end + -- for _,mount in pairs(liveupdate.get_mounts()) do + -- if mount.name == mount_name then + -- mount_found = true + -- end + -- end + + self.url = RIVE_MODEL + self.file = rive.get_file(self.url) + self.artboard = rive.get_artboard(self.url) + self.state_machine = rive.get_state_machine(self.url) + self.view_model = rive.get_view_model_instance(self.url) + + -- debugging + rive.cmd.requestViewModelNames(self.file) + rive.cmd.requestArtboardNames(self.file) + rive.cmd.requestViewModelEnums(self.file) + rive.cmd.requestStateMachineNames(self.artboard) + rive.cmd.requestDefaultViewModelInfo(self.artboard, self.file) + + rive.cmd.requestViewModelInstanceNames(self.file, "vmMain") + rive.cmd.requestViewModelPropertyDefinitions(self.file, "vmMain") + + -- end debugging + + rive.cmd.setViewModelInstanceString(self.view_model, "Text", "DEFOLD GAME ENGINE!") if mount_found then swap_assets(self) else liveupdate.add_mount(mount_name, DLC_FILES, 10, function () print("LU: mounted file provider!") - swap_assets(self) -- Note that there is also the option to save the file to a specific path -- If no path is specified, it will be stored in the http cache - timer.delay(1.0, false, function() + timer.delay(0.5, false, function() print("HTTP REQUEST", URL) http.request(URL, "GET", function (self, _id, response) print(" response.status:", response.status) if response.status == 200 or response.status == 206 or response.status == 304 then - local rivc = go.get(RIVE_MODEL, "rive_file") - rive.riv_swap_asset(rivc, "walle.jpg", { payload = response.response }) + local image = rive.cmd.decodeImage(response.response) + rive.cmd.setViewModelInstanceImage(self.view_model, "Image", image) end end) end) end) end - rive.riv_swap_asset(go.get(RIVE_MODEL_2, "rive_file"), "Inter", { path = "/main/outofband/font/Inter-referenced.ttf" }) - timer.delay(1.0, false, function() + timer.delay(0.5, false, function() print("HTTP REQUEST", URL_FONT) http.request(URL_FONT, "GET", function (self, _id, response) print(" response.status:", response.status) if response.status == 200 or response.status == 206 or response.status == 304 then - local rivc = go.get(RIVE_MODEL_2, "rive_file") - rive.riv_swap_asset(rivc, "Inter", { payload = response.response }) + local font = rive.cmd.decodeFont(response.response) + + print("FONT", font) + + rive.cmd.addGlobalFontAsset("MyFont", font) end end) end) end -function final(self) - -- Add finalization code here - -- Learn more: https://defold.com/manuals/script/ - -- Remove this function if not needed -end - -function update(self, dt) - -- Add update code here - -- Learn more: https://defold.com/manuals/script/ - -- Remove this function if not needed -end - -function fixed_update(self, dt) - -- This function is called if 'Fixed Update Frequency' is enabled in the Engine section of game.project - -- Can be coupled with fixed updates of the physics simulation if 'Use Fixed Timestep' is enabled in - -- Physics section of game.project - -- Add update code here - -- Learn more: https://defold.com/manuals/script/ - -- Remove this function if not needed -end - -function on_message(self, message_id, message, sender) - -- Add message-handling code here - -- Learn more: https://defold.com/manuals/message-passing/ - -- Remove this function if not needed -end - function on_input(self, action_id, action) - -- Add input-handling code here. The game object this script is attached to - -- must have acquired input focus: - -- - -- msg.post(".", "acquire_input_focus") - -- - -- All mapped input bindings will be received. Mouse and touch input will - -- be received regardless of where on the screen it happened. - -- Learn more: https://defold.com/manuals/input/ - -- Remove this function if not needed -end - -function on_reload(self) - -- Add reload-handling code here - -- Learn more: https://defold.com/manuals/hot-reload/ - -- Remove this function if not needed + if not action_id or action_id == hash("touch") then + + if action.pressed then + rive.pointer_down(RIVE_MODEL, action.x, action.y) + elseif action.released then + rive.pointer_up(RIVE_MODEL, action.x, action.y) + else + rive.pointer_move(RIVE_MODEL, action.x, action.y) + end + end end diff --git a/main/outofband/walle.atlas b/main/outofband/walle.atlas deleted file mode 100644 index 7ffd1a1d..00000000 --- a/main/outofband/walle.atlas +++ /dev/null @@ -1,7 +0,0 @@ -images { - image: "/main/outofband/walle/eve.png" -} -images { - image: "/main/outofband/walle/walle.png" -} -extrude_borders: 2 diff --git a/main/outofband/walle.rivescene b/main/outofband/walle.rivescene deleted file mode 100644 index 65995919..00000000 --- a/main/outofband/walle.rivescene +++ /dev/null @@ -1,2 +0,0 @@ -scene: "/main/outofband/walle/walle.riv" -atlas: "/main/outofband/walle.atlas" diff --git a/main/outofband/walle/eve.png b/main/outofband/walle/eve.png deleted file mode 100644 index 221934aa..00000000 Binary files a/main/outofband/walle/eve.png and /dev/null differ diff --git a/main/outofband/walle/walle.png b/main/outofband/walle/walle.png deleted file mode 100644 index a3ac8ee2..00000000 Binary files a/main/outofband/walle/walle.png and /dev/null differ diff --git a/main/outofband/walle/walle.riv b/main/outofband/walle/walle.riv deleted file mode 100644 index bd0edff4..00000000 Binary files a/main/outofband/walle/walle.riv and /dev/null differ diff --git a/main/scifihud/scifihud.collection b/main/scifihud/scifihud.collection index 52b23241..20507256 100644 --- a/main/scifihud/scifihud.collection +++ b/main/scifihud/scifihud.collection @@ -20,6 +20,7 @@ embedded_instances { "artboard: \\\"Main Artboard SciFi_Game_HUD_Scope\\\"\\n" "coordinate_system: COORDINATE_SYSTEM_RIVE\\n" "artboard_fit: FIT_CONTAIN\\n" + "blit_material: \\\"/defold-rive/assets/shader-library/rivemodel_blit.material\\\"\\n" "\"\n" "}\n" "" diff --git a/main/scifihud/scifihud.script b/main/scifihud/scifihud.script index 459a7256..4c5886f3 100644 --- a/main/scifihud/scifihud.script +++ b/main/scifihud/scifihud.script @@ -1,32 +1,34 @@ function init(self) msg.post(".", "acquire_input_focus") - go.set("#hud", "Health", 100) - go.set("#hud", "Shield", 100) - go.animate("#hud", "Health", go.PLAYBACK_LOOP_PINGPONG, 0, go.EASING_INOUTQUAD, 5) - go.animate("#hud", "Shield", go.PLAYBACK_LOOP_PINGPONG, 0, go.EASING_INOUTQUAD, 4, 2) + + self.url = "#hud" + self.file = rive.get_file(self.url) + self.artboard = rive.get_artboard(self.url) + self.state_machine = rive.get_state_machine(self.url) + self.view_model = rive.get_view_model_instance(self.url) end function on_input(self, action_id, action) if action_id == hash("touch") then if action.pressed then - go.set("#hud", "Fire", true) + --rive.cmd.fireViewModelTrigger(self.view_model, "Fire") elseif action.released then - go.set("#hud", "Fire", false) + --go.set(self.url, "Fire", false) end elseif action_id == hash("1") then if action.pressed then print("weapon 1") - go.set("#hud", "Weapon ID", -1) + --go.set(self.url, "Weapon ID", -1) end elseif action_id == hash("2") then if action.pressed then print("weapon 2") - go.set("#hud", "Weapon ID", 0) + --go.set(self.url, "Weapon ID", 0) end elseif action_id == hash("3") then if action.pressed then print("weapon 3") - go.set("#hud", "Weapon ID", 1) + --go.set(self.url, "Weapon ID", 1) end end end diff --git a/main/scrollist/scrollist.script b/main/scrollist/scrollist.script index b4bd41db..3b34676d 100644 --- a/main/scrollist/scrollist.script +++ b/main/scrollist/scrollist.script @@ -8,7 +8,7 @@ local function set_border(self, index, border) end local thumb = self.thumbs[index+1] - rive.databind.set_properties(self.rive_url, thumb, {Border = border}) + rive.cmd.setViewModelInstanceNumber(thumb, "Border", border) end local function set_selected_thumb(self, index) @@ -18,7 +18,7 @@ local function set_selected_thumb(self, index) set_border(self, prev_index, 0) set_border(self, self.thumb_index, 10) - rive.databind.set_properties(self.rive_url, self.modelViewInstanceRuntime, {["List Index"] = self.thumb_index}) + rive.cmd.setViewModelInstanceNumber(self.view_model, "List Index", self.thumb_index) end local function move_left(self) @@ -38,18 +38,26 @@ local function move_right(self) end local function create_thumb(self, image_data) - local thumb, errThumb = rive.databind.create_view_model_instance_runtime(self.rive_url, "ThumbVM") - if thumb == nil then - print("Failed to create view model instance:", errThumb) - return + local viewmodel_name = "ThumbVM" + local thumb = rive.cmd.instantiateDefaultViewModelInstance(self.file, viewmodel_name) + if thumb == 0 then + print("Failed to create view model instance:", viewmodel_name) + return end + + print("thumb:", thumb) table.insert(self.thumbs, thumb) - rive.databind.set_properties(self.rive_url, thumb, {Border = 10, Image = image_data}) - -- add the thumb last in the list - rive.databind.list_add_instance(self.rive_url, self.modelViewInstanceRuntime, self.list_path, thumb) + local image = rive.cmd.decodeImage(image_data) + print("image:", image) + + rive.cmd.setViewModelInstanceNumber(thumb, "Border", 10) + rive.cmd.setViewModelInstanceImage(thumb, "Image", image) + + -- -- add the thumb last in the list + rive.cmd.appendViewModelInstanceListViewModel(self.view_model, self.list_path, thumb) - -- update borders + -- -- update borders set_selected_thumb(self, #self.thumbs - 1) end @@ -67,49 +75,54 @@ end local function request_thumb(self, url) print("Requesting new thumb") - download_image(self.modelViewInstanceRuntime, url) + download_image(self.view_model, url) end local function remove_thumb(self, index) print("Removing thumb at index", index) local thumb = table.remove(self.thumbs, index) - rive.databind.list_remove_instance(self.rive_url, self.modelViewInstanceRuntime, self.list_path, thumb) + --rive.databind.list_remove_instance(self.rive_url, self.view_model, self.list_path, thumb) + rive.cmd.removeViewModelInstanceListViewModel(self.view_model, self.list_path, thumb) + --rive.cmd.removeViewModelInstanceListViewModelIndex(self.view_model, self.list_path, index) set_selected_thumb(self, index-1) end --- Rive events trigger when the splash intro starts and ends and is used to not allow input while the intro is playing. --- The logic is done within the rive statemachine. -local function rive_event_handler(self, message_id, message) - print("received event", message.name) + +local function rive_listener(self, message_name, data) + pprint("file:", message_name, data) end -- Get input focus then start the splash statemachine. function init(self) msg.post(".", "acquire_input_focus") + rive.set_file_listener(rive_listener) + + self.list_path = 'Thumbs' + self.thumbs = {} self.rive_url = msg.url("#scrollist") - self.modelViewInstanceRuntime = rive.databind.get_view_model_instance_runtime(self.rive_url) + self.file = rive.get_file(self.rive_url) + self.artboard = rive.get_artboard(self.rive_url) + self.state_machine = rive.get_state_machine(self.rive_url) + print("file:", self.file) + print("artboard:", self.artboard) + print("state_machine:", self.state_machine) - if self.modelViewInstanceRuntime == 0xFFFFFFFF then - -- auto_bind == false - local main, errMain = rive.databind.create_view_model_instance_runtime(self.rive_url, "MainVM") - if main == nil then - print("Failed to create view model instance:", errMain) - return - end + --self.view_model = rive.cmd.instantiateDefaultViewModelInstance(self.file, self.artboard) + self.view_model = rive.cmd.instantiateBlankViewModelInstance(self.file, self.artboard) + print("viewmodelinstance", self.view_model) - self.modelViewInstanceRuntime = main - rive.databind.set_view_model_instance_runtime(self.rive_url, self.modelViewInstanceRuntime) - end + rive.cmd.bindViewModelInstance(self.state_machine, self.view_model) - self.list_path = 'Thumbs' - self.thumb_index = rive.databind.get_property(self.rive_url, self.modelViewInstanceRuntime, "List Index") - self.thumbs = {} + self.thumb_index = 0 + -- self.thumb_index = rive.databind.get_property(self.rive_url, self.view_model, "List Index") for i=1,MAX_NUM_THUMBS do request_thumb(self, URL) end + + --request_thumb(self, URL) end diff --git a/utils/README.md b/utils/README.md index aa5fb710..89c90b9a 100644 --- a/utils/README.md +++ b/utils/README.md @@ -1,11 +1,15 @@ # Build and desploy steps +* Rive runntime libraries +* Editor plugin (desktop platforms) + ## Build Rive Runtime -*UPDATE 2025-09-20* +*UPDATE 2025-11-23* -For some platforms we now use the build system of the rive runtime. +We now use the build system of the rive runtime to build (most of) the libraries. +We still use the old build steps for x86_64-win32 and x86-win32 libraries. The build scripts do several things: * Removes old headers @@ -16,6 +20,32 @@ The build scripts do several things: **NOTE** The build steps currently apply a small patch to the rive-runtiome in order to successfully build for all targets! See [rive.patch](./utils/rive.patch) for the details. +## Github Actions + +Using Github Actions is the easiest way to update the libraries and editor plugins. +By default, it will push the new headers, and libraries to the repo. + +Once it's done, you should verify that it works to build for all platforms. + +### Create branch + +Start with creating a branch. Use the sha1 name of the rive runtime you wish to use (for clarity) + +`git checkout -b update-` + +### Run the Github Action workflow + +Using Github CLI (`brew install github`), you can invoke the build locally. Replace the sha1 with your version. + +`gh workflow run branch-artifacts.yml -r update- -f platform=all -f push_changes=true -f rive_sha=` + +You can replace the platform `all` with a specific target platform (e.g. `x86_64-win32`) + +Example: + +`gh workflow run branch-artifacts.yml -r update-a228887fa6032efd0e0e23af70455913dee4ac1f -f platform=x86_64-win32 -f push_changes=true -f rive_sha=a228887fa6032efd0e0e23af70455913dee4ac1f` + + ### Prerequisites
@@ -76,59 +106,55 @@ The supported platforms are * armv7-android * js-web * wasm-web +* wasm_pthread-web +* arm64-linux +* x86_64-linux +* x86_64-win32 -## For the engine (old build path) - -This step is needed for each platform+architecture that the runtime should support. - -First, clean out any previous code that may be left since last update. -You only need to do this once for each version update. - - rm -rf ./build - -### Build the rive runtime - -the `build_pls.sh` script copies the files needed for each library, and sends them to our build server, in order to make sure they're built with the SDK's we need. - -For each platform+arch, do: - - ./utils/build_pls.sh - -This updates the folder `./defold-rive/lib` +## CI Workflow Usage -The currently supported platforms: +Use the GitHub Actions workflow to build and optionally commit the generated artifacts back to the same branch. -* arm64-ios -* x86_64-ios -* arm64-macos -* x86_64-macos -* arm64-android -* arm64-linux -* x86_64-linux -* x86_64-win32 -* x86-win32 -* js-web -* wasm-web -* wasm_pthread-web +Steps: -For the more advanced use cases, there are variables that can be modified: +- Go to GitHub → Actions → "Branch Scripts and Artifacts" → Run workflow. +- Pick the target branch in the UI. +- Set inputs: + - `platform`: choose `x86_64-linux`, `arm64-linux`, `arm64-macos`, `x86_64-macos`, `arm64-ios`, `x86_64-ios`, `arm64-android`, `armv7-android`, `js-web`, `wasm-web`, `wasm_pthread-web`, `x86_64-win32`, or `all`.. + - `rive_repo_url`: HTTPS repo for Rive runtime (defaults to `https://github.com/rive-app/rive-runtime.git`). + - `rive_ref` (optional): pin a branch/tag of the runtime. + - `rive_sha` (optional): pin an exact commit SHA (takes precedence over `rive_ref`). + - `commit_message` (optional): suffix for the commit message. + - `push_changes`: `true` to commit/push changes; `false` for a dry run. + - `upload_artifact`: `false` by default; set `true` to upload a tarball in addition to committing changes. - DEFOLDSDK= SERVER= ./utils/build_pls.sh +What it does: -You can specify variables: BOB, SERVER, DEFOLDSDK. +- Checks out your branch and clones the Rive runtime to a temp folder. +- Exports `RIVE_ROOT` to that folder and ensures the repo is clean. +- Runs `./utils/build_rive_runtime.sh ${PLATFORM} ${RIVE_ROOT}`. +- Uploads `branch-artifacts-.tgz` containing `defold-rive/lib` and `defold-rive/include`. +- If `push_changes=true`, commits only `defold-rive/lib` and `defold-rive/include` back to the same branch with `[skip ci]` in the message. +- If `upload_artifact=false`, the tarball upload is skipped. -### Update the Rive headers +Notes: -Once you've successfully built the libraries (for at least one platform), we also need to copy the headers. -Note that it may remove or add headers in the `defold-rive/include/rive` folder. This often happens in their api. +- Runners: `x86_64-linux` runs on `ubuntu-latest`; Apple targets (`arm64-macos`, `x86_64-macos`, `arm64-ios`, `x86_64-ios`) run on `macos-latest` and require Xcode command line tools. +- Android (`arm64-android`, `armv7-android`) runs on `macos-latest`; the workflow sets up the Android SDK and installs NDK r25c (25.2.9519653) via a GitHub Action, and exports `ANDROID_NDK` automatically. + - The workflow also exports `ANDROID_NDK_HOME`, `NDK_PATH`, and sets `ANDROID_API=21` to ensure the correct sysroot is selected by Clang. + - Note: Rive's build compiles a premake-with-ninja internally; no external premake install is required. +- Web (`js-web`, `wasm-web`, `wasm_pthread-web`) runs on `ubuntu-latest`; rive-runtime fetches Emscripten automatically unless you set `EMSDK` or `RIVE_EMSDK_VERSION`. + - The workflow installs `glslangValidator` (package: `glslang-tools`) for shader validation during web builds. +- If you need specific SDKs (e.g., `ANDROID_NDK`, `EMSDK`), set them accordingly before invoking platform-specific builds. +- Concurrency is limited to one workflow per branch; commits include `[skip ci]` to avoid loops. - > ./utils/copy_rive_headers.py +## Plugins for the editor -## For the editor +**NOTE** This step is also handled by the CI build step! -This step is only needed if you've altered some particular extension code itself, namely the pluginsrc/ and commonsrc/ folders. +This step is only necessary if you've altered some particular extension code itself, namely the pluginsrc/ and commonsrc/ folders. For a regular rive-runtime update, this step isn't needed. diff --git a/utils/build_pls.sh b/utils/build_pls.sh index 3c728095..c67258db 100755 --- a/utils/build_pls.sh +++ b/utils/build_pls.sh @@ -255,7 +255,9 @@ if [ -z "$RIVE_DIR" ]; then # https://github.com/rive-app/rive-runtime/commit/ - RIVECPP_VERSION=e54883d9099f87ed6d87c678793fd619b5594e2c + if [ "" == "${RIVECPP_VERSION}" ]; then + RIVECPP_VERSION=a228887fa6032efd0e0e23af70455913dee4ac1f + fi RIVECPP_ZIP=${DOWNLOAD_DIR}/rivecpp-${RIVECPP_VERSION}.zip RIVECPP_URL="https://github.com/rive-app/rive-runtime/archive/${RIVECPP_VERSION}.zip" @@ -481,7 +483,7 @@ for platform in $PLATFORMS; do cp -v ${RIVECPP_ORIGINAL_DIR}/renderer/src/gl/pls_impl_rw_texture.cpp ${RIVECPP_RENDERER_SOURCE_DIR}/src/gl/ cp -v ${RIVECPP_ORIGINAL_DIR}/renderer/glad/*.* ${RIVECPP_RENDERER_SOURCE_DIR}/src/glad - cp -v -r ${RIVECPP_ORIGINAL_DIR}/renderer/glad/include/ ${RIVECPP_RENDERER_SOURCE_DIR}/include + cp -v -r ${RIVECPP_ORIGINAL_DIR}/renderer/glad/include/ ${RIVECPP_RENDERER_SOURCE_DIR} ;; arm64-linux|x86_64-linux) diff --git a/utils/build_plugin.sh b/utils/build_plugin.sh new file mode 100755 index 00000000..00f6c68f --- /dev/null +++ b/utils/build_plugin.sh @@ -0,0 +1,119 @@ +#!/usr/bin/env bash + +set -euo pipefail + +SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )" +REPO_ROOT=$(realpath ${SCRIPT_DIR}/..) + +if [ $# -lt 1 ]; then + echo "Usage: $0 " + exit 1 +fi + +PLATFORM="$1" +CONFIG="RelWithDebInfo" +BUILD_DIR="${SCRIPT_DIR}/cmake/build/out_${PLATFORM}" + +EXTENDER_PLATFORM="${PLATFORM}" +case $PLATFORM in + "arm64-macos") + EXTENDER_PLATFORM="arm64-osx" + ;; + "x86_64-macos") + EXTENDER_PLATFORM="x86_64-osx" + ;; +esac +TARGET_LIB_DIR="${REPO_ROOT}/defold-rive/plugins/lib/${EXTENDER_PLATFORM}" +TARGET_SHARE_DIR="${REPO_ROOT}/defold-rive/plugins/share" + +if [ -z "${DYNAMO_HOME:-}" ]; then + echo "DYNAMO_HOME must be set before running $0" >&2 + exit 1 +fi + +export CMAKE_C_COMPILER="$(which clang)" +export CMAKE_CXX_COMPILER="$(which clang++)" + +DYNAMO_HOME="$(realpath "${DYNAMO_HOME}")" +export DYNAMO_HOME + +if [ -z "${BOB:-}" ]; then + echo "BOB must be set before running $0" >&2 + exit 1 +fi + +BOB="$(realpath "${BOB}")" +if [ ! -f "${BOB}" ]; then + echo "BOB jar not found at ${BOB}" >&2 + exit 1 +fi +export BOB + +case "$(uname -s)" in + Darwin) + if [ "$(uname -m)" = "arm64" ]; then + HOST_PLATFORM="arm64-macos" + else + HOST_PLATFORM="x86_64-macos" + fi + ;; + Linux) + HOST_PLATFORM="x86_64-linux" + ;; + MINGW*|MSYS*|CYGWIN*|Windows_NT) + HOST_PLATFORM="x86_64-win32" + ;; + *) + HOST_PLATFORM="x86_64-linux" + ;; +esac + +CMAKE_GENERATOR_FLAGS=() +if [ "$HOST_PLATFORM" = "x86_64-win32" ]; then + CMAKE_GENERATOR_FLAGS+=("-A" "x64") +fi + + +if [ -n "${PROTOC:-}" ] && [ -x "${PROTOC}" ]; then + PROTOC_DIR="$(dirname "${PROTOC}")" + export PATH="${PROTOC_DIR}:${PATH}" +else + PROTOBUF_BIN="${REPO_ROOT}/build/bin/${HOST_PLATFORM}" + if [ -d "${PROTOBUF_BIN}" ]; then + export PATH="${PROTOBUF_BIN}:${PATH}" + else + echo "Warning: protobuf bin directory not found at ${PROTOBUF_BIN}" >&2 + echo "build folder: ${REPO_ROOT}/build" + ls -la ${REPO_ROOT}/build + tree ${PROTOBUF_BIN} + fi +fi + +mkdir -p "${BUILD_DIR}" + +cmake -S "${SCRIPT_DIR}/plugin" -B "${BUILD_DIR}" \ + -DTARGET_PLATFORM="${PLATFORM}" \ + -DCMAKE_VERBOSE_MAKEFILE=ON \ + -DCMAKE_C_COMPILER="${CMAKE_C_COMPILER}" \ + -DCMAKE_CXX_COMPILER="${CMAKE_CXX_COMPILER}" \ + "${CMAKE_GENERATOR_FLAGS[@]:-}" + +cmake --build "${BUILD_DIR}" --config "${CONFIG}" + +case $PLATFORM in + "arm64-macos"|"x86_64-macos") + cp -v ${BUILD_DIR}/*.dylib ${TARGET_LIB_DIR} + ;; + "arm64-linux"|"x86_64-linux") + cp -v ${BUILD_DIR}/*.so ${TARGET_LIB_DIR} + ;; + "x86_64-win32") + cp -v ${BUILD_DIR}/${CONFIG}/*.dll ${TARGET_LIB_DIR} + ;; +esac + +mkdir -p ${TARGET_SHARE_DIR} +cp -v ${BUILD_DIR}/pluginRiveExt.jar ${TARGET_SHARE_DIR} + + +echo "Done." diff --git a/utils/build_rive_runtime.sh b/utils/build_rive_runtime.sh index e061fc0f..c310c335 100755 --- a/utils/build_rive_runtime.sh +++ b/utils/build_rive_runtime.sh @@ -3,6 +3,7 @@ set -e SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )" +SCRIPT_DIR_UTILS=${SCRIPT_DIR}/buildscripts PLATFORM=$1 shift @@ -24,6 +25,8 @@ function Usage { echo " * x86_64-ios" echo " * arm64-linux" echo " * x86_64-linux" + echo " * x86_64-win32" + echo " * x86-win32" exit 1 } @@ -47,6 +50,8 @@ case $PLATFORM in ;; arm64-linux|x86_64-linux) ;; + x86_64-win32|x86-win32) + ;; *) echo "Platform '${PLATFORM}' is not supported!" @@ -100,14 +105,24 @@ VERSIONHEADER=${PREFIX}/include/defold/rive_version.h # cp -v ${RIVECPP}/build_headers.sh ${SCRIPT_DIR}/ echo "Writing version header ${VERSIONHEADER}" -${SCRIPT_DIR}/build_version_header.sh ${VERSIONHEADER} ${RIVECPP} +${SCRIPT_DIR_UTILS}/build_version_header.sh ${VERSIONHEADER} ${RIVECPP} +# Apply patch RIVEPATCH=${SCRIPT_DIR}/rive.patch -echo "Applying patch ${RIVEPATCH}" -set +e -(cd ${RIVECPP} && git apply ${RIVEPATCH}) -set -e +if [[ "$PLATFORM" == x86_64-win32 || "$PLATFORM" == x86-win32 ]]; then + echo "Skipping patch for windows." + +else + echo "Applying patch ${RIVEPATCH}" + set +e + (cd ${RIVECPP} && git apply ${RIVEPATCH}) + APPLY_RC=$? + set -e + if [ ${APPLY_RC} -ne 0 ]; then + echo "Simple apply failed; attempting 3-way with history..." + fi +fi CONFIGURATION=release @@ -120,7 +135,7 @@ case $PLATFORM in fi # expects ANDROID_NDK to be set - (cd ${RIVECPP} && ${SCRIPT_DIR}/build_android.sh --prefix ${PREFIX} --abis ${ARCH} --config ${CONFIGURATION}) + (cd ${RIVECPP} && ${SCRIPT_DIR_UTILS}/build_android.sh --prefix ${PREFIX} --abis ${ARCH} --config ${CONFIGURATION}) ;; wasm-web|wasm_pthread-web|js-web) @@ -144,11 +159,11 @@ case $PLATFORM in fi echo "Using RIVE_EMSDK_VERSION=${RIVE_EMSDK_VERSION}" fi - (cd ${RIVECPP} && ${SCRIPT_DIR}/build_emscripten.sh --prefix ${PREFIX} --targets ${ARCH} --config ${CONFIGURATION}) + (cd ${RIVECPP} && ${SCRIPT_DIR_UTILS}/build_emscripten.sh --prefix ${PREFIX} --targets ${ARCH} --config ${CONFIGURATION}) if [ "js-web" != "${PLATFORM}" ]; then echo "Building for Wagyu" - (cd ${RIVECPP} && ${SCRIPT_DIR}/build_emscripten.sh --with-wagyu --prefix ${PREFIX} --targets ${ARCH} --config ${CONFIGURATION}) + (cd ${RIVECPP} && ${SCRIPT_DIR_UTILS}/build_emscripten.sh --with-wagyu --prefix ${PREFIX} --targets ${ARCH} --config ${CONFIGURATION}) fi ;; @@ -159,7 +174,7 @@ case $PLATFORM in ARCH=x64 fi - (cd ${RIVECPP} && ${SCRIPT_DIR}/build_darwin.sh --prefix ${PREFIX} --targets macos --archs ${ARCH} --config ${CONFIGURATION}) + (cd ${RIVECPP} && ${SCRIPT_DIR_UTILS}/build_darwin.sh --prefix ${PREFIX} --targets macos --archs ${ARCH} --config ${CONFIGURATION}) ;; arm64-ios|x86_64-ios) @@ -168,7 +183,7 @@ case $PLATFORM in ARCH=x64 fi - (cd ${RIVECPP} && ${SCRIPT_DIR}/build_darwin.sh --prefix ${PREFIX} --targets ios --archs ${ARCH} --config ${CONFIGURATION}) + (cd ${RIVECPP} && ${SCRIPT_DIR_UTILS}/build_darwin.sh --prefix ${PREFIX} --targets ios --archs ${ARCH} --config ${CONFIGURATION}) ;; arm64-linux|x86_64-linux) @@ -177,7 +192,16 @@ case $PLATFORM in ARCH=x64 fi - (cd ${RIVECPP} && ${SCRIPT_DIR}/build_linux.sh --prefix ${PREFIX} --archs ${ARCH} --config ${CONFIGURATION}) + (cd ${RIVECPP} && ${SCRIPT_DIR_UTILS}/build_linux.sh --prefix ${PREFIX} --archs ${ARCH} --config ${CONFIGURATION}) + ;; + + x86_64-win32|x86-win32) + ARCH=x64 + if [ "x86-win32" == "${PLATFORM}" ]; then + ARCH=x86 + fi + + (cd ${RIVECPP} && ${SCRIPT_DIR_UTILS}/build_windows.sh --prefix ${PREFIX} --archs ${ARCH} --config ${CONFIGURATION}) ;; *) @@ -187,4 +211,9 @@ case $PLATFORM in esac +echo "Removing unwanted files:" +# Be resilient if nothing matches; remove quietly if present +find "${SCRIPT_DIR}/../defold-rive/lib" -type f -iname "*glfw3.*" -exec rm -f -v {} + 2>/dev/null || true +find "${SCRIPT_DIR}/../defold-rive/lib" -type f -iname "*path_fiddle.*" -exec rm -f -v {} + 2>/dev/null || true + echo "Done!" diff --git a/utils/build_android.sh b/utils/buildscripts/build_android.sh similarity index 93% rename from utils/build_android.sh rename to utils/buildscripts/build_android.sh index e271e841..3e5ae475 100755 --- a/utils/build_android.sh +++ b/utils/buildscripts/build_android.sh @@ -15,8 +15,12 @@ set -euo pipefail shopt -s nullglob +# Script location (used for shared helper scripts). +SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )" + # Treat the current working directory as the repo root (do not depend on script location). ROOT_DIR="$(pwd -P)" +SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )" PREFIX="" ABIS="arm64" @@ -119,7 +123,7 @@ LIB_ROOT="$PREFIX/lib" mkdir -p "$INCLUDE_DST" "$LIB_ROOT" # Install headers via shared helper -"$ROOT_DIR/build_headers.sh" --prefix "$PREFIX" --root "$ROOT_DIR" +"${SCRIPT_DIR}/build_headers.sh" --prefix "$PREFIX" --root "$ROOT_DIR" # Change into renderer directory before building so premake picks up renderer/premake5.lua BUILD_DIR="$ROOT_DIR/renderer" diff --git a/utils/build_darwin.sh b/utils/buildscripts/build_darwin.sh similarity index 94% rename from utils/build_darwin.sh rename to utils/buildscripts/build_darwin.sh index 98bcef4d..ed434682 100755 --- a/utils/build_darwin.sh +++ b/utils/buildscripts/build_darwin.sh @@ -21,8 +21,12 @@ set -euo pipefail shopt -s nullglob +# Script location (used for shared helper scripts). +SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )" + # Treat the current working directory as the repo root (do not depend on script location). ROOT_DIR="$(pwd -P)" +SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )" PREFIX="" TARGETS="macos" @@ -141,7 +145,7 @@ LIB_ROOT="$PREFIX/lib" mkdir -p "$INCLUDE_DST" "$LIB_ROOT" # Install headers via shared helper -"$ROOT_DIR/build_headers.sh" --prefix "$PREFIX" --root "$ROOT_DIR" +"${SCRIPT_DIR}/build_headers.sh" --prefix "$PREFIX" --root "$ROOT_DIR" # Change into renderer directory before building so premake picks up renderer/premake5.lua BUILD_DIR="$ROOT_DIR/renderer" @@ -197,6 +201,13 @@ build_for_target_arch() { ;; esac + echo + echo "==> Cleaning: $target ${out_dir}" + + if [ -d "${out_dir}" ]; then + rm -rf ${out_dir} + fi + echo echo "==> Building: $target ${arch:+($arch) }($CONFIG)" diff --git a/utils/build_emscripten.sh b/utils/buildscripts/build_emscripten.sh similarity index 94% rename from utils/build_emscripten.sh rename to utils/buildscripts/build_emscripten.sh index 32b1a4dc..e2acbc15 100755 --- a/utils/build_emscripten.sh +++ b/utils/buildscripts/build_emscripten.sh @@ -18,8 +18,12 @@ set -euo pipefail shopt -s nullglob +# Script location (used for shared helper scripts). +SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )" + # Treat the current working directory as the repo root (do not depend on script location). ROOT_DIR="$(pwd -P)" +SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )" PREFIX="" TARGETS="wasm" @@ -41,7 +45,7 @@ Env: EMSDK If set, sources \$EMSDK/emsdk_env.sh and uses that SDK. Examples: - EMSDK=~/dev/emsdk ./build_emscripten.sh --prefix /tmp/rive-emsdk --targets wasm,js --config release + EMSDK=~/dev/emsdk ./build_emscripten.sh --prefix /path/to/extension-rive/defold-rive --targets wasm,js --config release EOF } @@ -132,7 +136,7 @@ LIB_ROOT="$PREFIX/lib" mkdir -p "$INCLUDE_DST" "$LIB_ROOT" # Install headers via shared helper -"$ROOT_DIR/build_headers.sh" --prefix "$PREFIX" --root "$ROOT_DIR" +"${SCRIPT_DIR}/build_headers.sh" --prefix "$PREFIX" --root "$ROOT_DIR" # Change into renderer directory before building so premake picks up renderer/premake5.lua BUILD_DIR="$ROOT_DIR/renderer" diff --git a/utils/build_headers.sh b/utils/buildscripts/build_headers.sh similarity index 100% rename from utils/build_headers.sh rename to utils/buildscripts/build_headers.sh diff --git a/utils/build_linux.sh b/utils/buildscripts/build_linux.sh similarity index 89% rename from utils/build_linux.sh rename to utils/buildscripts/build_linux.sh index 57303da7..09055e60 100755 --- a/utils/build_linux.sh +++ b/utils/buildscripts/build_linux.sh @@ -16,13 +16,16 @@ set -euo pipefail shopt -s nullglob +# Script location (used for shared helper scripts). +SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )" + # Treat the current working directory as the repo root (do not depend on script location). ROOT_DIR="$(pwd -P)" +SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )" PREFIX="" ARCHS="" CONFIG="release" -SYSROOT="" print_help() { cat <-win32" where is x86 or x86_64. + +set -euo pipefail +shopt -s nullglob + +# Treat the current working directory as the repo root (do not depend on script location). +ROOT_DIR="$(pwd -P)" +SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )" + +PREFIX="" +ARCHS="x64,x86" +CONFIG="release" + +print_help() { + cat <&2 + echo >&2 + print_help >&2 + exit 2 + ;; + esac +done + +if [[ -z "$PREFIX" ]]; then + echo "error: --prefix is required" >&2 + echo >&2 + print_help >&2 + exit 2 +fi + +# Ensure PREFIX is an absolute, existing path +mkdir -p "$PREFIX" +PREFIX="$(cd "$PREFIX" && pwd -P)" + +if [[ "$CONFIG" != "release" && "$CONFIG" != "debug" ]]; then + echo "error: --config must be 'release' or 'debug'" >&2 + exit 2 +fi + +BUILD_SCRIPT="$ROOT_DIR/build/build_rive.sh" +if [[ ! -x "$BUILD_SCRIPT" ]]; then + if [[ -f "$BUILD_SCRIPT" ]]; then + chmod +x "$BUILD_SCRIPT" + else + echo "error: build script not found: $BUILD_SCRIPT" >&2 + exit 2 + fi +fi + +# Normalize arch list +IFS="," read -r -a ARCH_LIST_RAW <<< "$ARCHS" +ARCH_LIST=() +for entry in "${ARCH_LIST_RAW[@]}"; do + for a in $entry; do + if [[ -n "$a" ]]; then + case "$a" in + x64|x86) ARCH_LIST+=("$a") ;; + *) echo "error: unsupported arch '$a' (supported: x64, x86)" >&2; exit 2 ;; + esac + fi + done +done + +# Ensure prefix subdirs (headers handled by build_headers.sh) +INCLUDE_DST="$PREFIX/include" +LIB_ROOT="$PREFIX/lib" +mkdir -p "$INCLUDE_DST" "$LIB_ROOT" + +# Install headers via shared helper +"${SCRIPT_DIR}/build_headers.sh" --prefix "$PREFIX" --root "$ROOT_DIR" + +# Change into renderer directory before building so premake picks up renderer/premake5.lua +BUILD_DIR="$ROOT_DIR/renderer" +echo "Changing directory to: $BUILD_DIR" +cd "$BUILD_DIR" + +for ARCH in "${ARCH_LIST[@]}"; do + echo + echo "==> Building: windows $ARCH ($CONFIG)" + + out_dir_rel="out/windows_${ARCH}_${CONFIG}" + out_dir="$BUILD_DIR/$out_dir_rel" + + # Drive build (use windows token and arch) + RIVE_OUT="$out_dir_rel" "$BUILD_SCRIPT" --toolset=msc "$ARCH" "$CONFIG" + + # Collect and install libraries + install_arch="$ARCH" + if [[ "$install_arch" == "x64" ]]; then install_arch="x86_64"; fi + if [[ "$install_arch" == "x86" ]]; then install_arch="x86"; fi + install_dir="$LIB_ROOT/${install_arch}-win32" + mkdir -p "$install_dir" + + libs=( "$out_dir"/lib*.a "$out_dir"/*.lib "$out_dir"/*.dll ) + if (( ${#libs[@]} == 0 )); then + echo "error: no libraries found in $out_dir (expected *.lib or lib*.a)" >&2 + exit 2 + fi + + echo "Installing libraries to $install_dir/:" + for lib in "${libs[@]}"; do + echo " - $(basename "$lib")" + cp -f "$lib" "$install_dir/" + done +done + +echo +echo "Done. Installed to: $PREFIX" diff --git a/utils/plugin/CMakeLists.txt b/utils/plugin/CMakeLists.txt new file mode 100644 index 00000000..f17b56f0 --- /dev/null +++ b/utils/plugin/CMakeLists.txt @@ -0,0 +1,296 @@ +cmake_minimum_required(VERSION 3.24) +project(defold_rive_plugin LANGUAGES C CXX) + +if(POLICY CMP0152) + cmake_policy(SET CMP0152 NEW) +endif() + +set(CMAKE_CONFIGURATION_TYPES "Debug;Release;RelWithDebInfo;MinSizeRel" CACHE STRING "" FORCE) + +if(TARGET_PLATFORM STREQUAL "x86_64-win32") + set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "/O2 /Zi") + set(CMAKE_C_FLAGS_RELWITHDEBINFO "/O2 /Zi") + set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") +endif() + +set(REPO_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/../..") + +option(TARGET_PLATFORM "" "Target platform identifier, e.g. x86_64-linux, x86_64-win32, x86_64-macos, arm64-macos") +if(NOT TARGET_PLATFORM) + message(FATAL_ERROR "TARGET_PLATFORM must be provided (via -DTARGET_PLATFORM=...)") +endif() + +if(NOT DEFINED ENV{DYNAMO_HOME} OR "$ENV{DYNAMO_HOME}" STREQUAL "") + message(FATAL_ERROR "DYNAMO_HOME environment variable is required") +endif() + +set(DYNAMO_HOME "$ENV{DYNAMO_HOME}") + +find_program(JAVA_EXECUTABLE NAMES java) +if(NOT JAVA_EXECUTABLE) + message(FATAL_ERROR "Java executable not found on PATH") +endif() + +find_program(JAVAC_EXECUTABLE NAMES javac) +if(NOT JAVAC_EXECUTABLE) + message(FATAL_ERROR "javac executable not found on PATH") +endif() + +find_program(JAR_EXECUTABLE NAMES jar) +if(NOT JAR_EXECUTABLE) + message(FATAL_ERROR "jar executable not found on PATH") +endif() + +if(NOT DEFINED ENV{BOB} OR "$ENV{BOB}" STREQUAL "") + message(FATAL_ERROR "Environment variable BOB must be set to the bob.jar classpath") +endif() + +set(BOB_JAR "$ENV{BOB}") +if(NOT EXISTS "${BOB_JAR}") + message(FATAL_ERROR "BOB=${BOB_JAR} does not exist") +endif() +message(STATUS "BOB=${BOB_JAR}") + +if(NOT EXISTS "${DYNAMO_HOME}/ext/bin") + message(FATAL_ERROR "Dynamo extension bin directory missing under '${DYNAMO_HOME}/ext/bin'") +endif() + +find_program(PROTOC_EXECUTABLE NAMES protoc) +if(NOT PROTOC_EXECUTABLE) + message(FATAL_ERROR "protoc executable not found on PATH") +endif() +message(STATUS "PROTOC=${PROTOC_EXECUTABLE}") + +execute_process( + COMMAND "${JAVA_EXECUTABLE}" --version + RESULT_VARIABLE JAVA_VERSION_RESULT + OUTPUT_VARIABLE JAVA_VERSION_STDOUT + ERROR_VARIABLE JAVA_VERSION_STDERR + OUTPUT_STRIP_TRAILING_WHITESPACE + ERROR_STRIP_TRAILING_WHITESPACE +) +if(NOT JAVA_VERSION_RESULT EQUAL 0) + message(FATAL_ERROR "Unable to run 'java --version': ${JAVA_VERSION_STDERR}") +endif() + +set(JAVA_VERSION_OUTPUT "${JAVA_VERSION_STDOUT}\n${JAVA_VERSION_STDERR}") +string(REGEX MATCH "21" _JAVA_MATCH "${JAVA_VERSION_OUTPUT}") +if(NOT _JAVA_MATCH) + message(FATAL_ERROR "Java 21 is required (found: ${JAVA_VERSION_OUTPUT})") +endif() + +if(NOT DEFINED ENV{JAVA_HOME} OR "$ENV{JAVA_HOME}" STREQUAL "") + execute_process( + COMMAND "${JAVA_EXECUTABLE}" -XshowSettings:properties -version + RESULT_VARIABLE JAVA_HOME_RESULT + OUTPUT_VARIABLE JAVA_HOME_STDOUT + ERROR_VARIABLE JAVA_HOME_STDERR + OUTPUT_STRIP_TRAILING_WHITESPACE + ERROR_STRIP_TRAILING_WHITESPACE + ) + if(NOT JAVA_HOME_RESULT EQUAL 0) + message(FATAL_ERROR "Failed to resolve JAVA_HOME via 'java -XshowSettings:properties': ${JAVA_HOME_STDERR}") + endif() + string(REGEX MATCH "java\\.home = ([^\r\n]+)" _JAVA_HOME_MATCH "${JAVA_HOME_STDOUT}\n${JAVA_HOME_STDERR}") + if(NOT _JAVA_HOME_MATCH) + message(FATAL_ERROR "Unable to parse java_home from 'java -XshowSettings:properties'") + endif() + set(JAVA_HOME "${CMAKE_MATCH_1}") +else() + set(JAVA_HOME "$ENV{JAVA_HOME}") +endif() + +message(STATUS "JAVA_HOME=${JAVA_HOME}") +message(STATUS "DYNAMO_HOME=${DYNAMO_HOME}") +message(STATUS "TARGET_PLATFORM=${TARGET_PLATFORM}") +if(TARGET_PLATFORM MATCHES "arm64") + set(TARGET_ARCH "arm64") +elseif(TARGET_PLATFORM MATCHES "x86_64") + set(TARGET_ARCH "x86_64") +elseif(TARGET_PLATFORM MATCHES "x86") + set(TARGET_ARCH "x86") +else() + set(TARGET_ARCH "") +endif() +message(STATUS "TARGET_ARCH=${TARGET_ARCH}") + +if(TARGET_ARCH AND CMAKE_HOST_APPLE) + set(CMAKE_OSX_ARCHITECTURES "${TARGET_ARCH}") +endif() + +file(GLOB_RECURSE COMMON_SOURCES + CONFIGURE_DEPENDS + "${REPO_ROOT}/defold-rive/commonsrc/*.c" + "${REPO_ROOT}/defold-rive/commonsrc/*.cpp" + "${REPO_ROOT}/defold-rive/commonsrc/*.cc" + "${REPO_ROOT}/defold-rive/commonsrc/*.cxx" +) + +# Rust file? +file(GLOB_RECURSE GLOB_JAVA_SOURCES + CONFIGURE_DEPENDS + "${REPO_ROOT}/defold-rive/pluginsrc/com/*.java" +) +set(GENERATED_PROTO_DIR "${CMAKE_CURRENT_BINARY_DIR}/generated-java") +set(GENERATED_PROTO_JAVA "${GENERATED_PROTO_DIR}/com/dynamo/rive/proto/Rive.java") +set(PROTO_FILE "${REPO_ROOT}/defold-rive/commonsrc/rive_ddf.proto") + +add_custom_command( + OUTPUT "${GENERATED_PROTO_JAVA}" + COMMAND + "${CMAKE_COMMAND}" -E make_directory "${GENERATED_PROTO_DIR}/com/dynamo/rive/proto" + COMMAND + "${PROTOC_EXECUTABLE}" + --proto_path="${REPO_ROOT}/defold-rive/commonsrc/" + --java_out="${GENERATED_PROTO_DIR}" + "-I${DYNAMO_HOME}/share/proto" + "-I${DYNAMO_HOME}/ext/include" + "${PROTO_FILE}" + DEPENDS "${PROTO_FILE}" + WORKING_DIRECTORY "${REPO_ROOT}" + COMMENT "Generating Java sources via protoc" +) +add_custom_target(plugin_proto ALL DEPENDS "${GENERATED_PROTO_JAVA}") + +set(JAVA_SOURCES ${GLOB_JAVA_SOURCES} "${GENERATED_PROTO_JAVA}") + +file(GLOB_RECURSE PLUGIN_SOURCES + CONFIGURE_DEPENDS + "${REPO_ROOT}/defold-rive/pluginsrc/*.c" + "${REPO_ROOT}/defold-rive/pluginsrc/*.cpp" + "${REPO_ROOT}/defold-rive/pluginsrc/*.cc" + "${REPO_ROOT}/defold-rive/pluginsrc/*.cxx" +) + +set(ALL_SOURCES ${COMMON_SOURCES} ${PLUGIN_SOURCES}) +list(REMOVE_DUPLICATES ALL_SOURCES) + +if(NOT ALL_SOURCES) + message(FATAL_ERROR "No C/C++ sources found under defold-rive/commonsrc or defold-rive/pluginsrc") +endif() + +add_compile_definitions(DLIB_LOG_DOMAIN="RIVE") + +if(JAVA_SOURCES) + set(JAVA_CLASSES_DIR "${CMAKE_CURRENT_BINARY_DIR}/java/classes") + set(PLUGIN_JAR "${CMAKE_CURRENT_BINARY_DIR}/pluginRiveExt.jar") + add_custom_command( + OUTPUT "${PLUGIN_JAR}" + COMMAND "${CMAKE_COMMAND}" -E make_directory "${JAVA_CLASSES_DIR}" + COMMAND "${JAVAC_EXECUTABLE}" -d "${JAVA_CLASSES_DIR}" -classpath "${BOB_JAR}" ${JAVA_SOURCES} + COMMAND "${JAR_EXECUTABLE}" cf "${PLUGIN_JAR}" -C "${JAVA_CLASSES_DIR}" . + DEPENDS ${JAVA_SOURCES} + WORKING_DIRECTORY "${REPO_ROOT}" + COMMENT "Compiling Defold Rive plugin Java sources" + ) + add_custom_target(plugin_java ALL DEPENDS "${PLUGIN_JAR}") + add_dependencies(plugin_java plugin_proto) +else() + set(PLUGIN_JAR "") +endif() + +add_library(rive_plugin SHARED ${ALL_SOURCES}) + +target_include_directories(rive_plugin PRIVATE + "${REPO_ROOT}/defold-rive/include" + "${REPO_ROOT}/defold-rive/commonsrc" + "${REPO_ROOT}/defold-rive/pluginsrc" + "${DYNAMO_HOME}/include" + "${DYNAMO_HOME}/sdk/include" +) + +target_include_directories(rive_plugin PRIVATE + "${JAVA_HOME}/include" +) + +if(TARGET_PLATFORM STREQUAL "x86_64-win32") + target_link_libraries(rive_plugin PRIVATE + libdlib libmbedtls libddf + libprofile_null libprofilerext_null + libplatform_null librender libgraphics_null + librender_font_default libfont + libresource libscript libgamesys libluajit-5.1) + target_link_libraries(rive_plugin PRIVATE Iphlpapi.lib) + + # old libraries built with build_pls.sh + target_link_libraries(rive_plugin PRIVATE rive sheenbidi harfbuzz yoga rivetess tess2) + +else() + target_compile_options(rive_plugin PRIVATE "-std=c++17") + + if(TARGET_PLATFORM MATCHES "linux") + target_link_options(rive_plugin PRIVATE "-fuse-ld=lld") + target_link_libraries(rive_plugin PRIVATE pthread m dl) + endif() + + target_link_libraries(rive_plugin PRIVATE + dlib mbedtls ddf + profile_null profilerext_null + platform_null render graphics_null + resource script gamesys lua) + target_link_libraries(rive_plugin PRIVATE rive rive_sheenbidi rive_harfbuzz rive_yoga zlib rivetess tess2) + +endif() + +set(EXTENDER_PLATFORM "${TARGET_PLATFORM}") +if(TARGET_PLATFORM STREQUAL "arm64-macos") + set(EXTENDER_PLATFORM "arm64-osx") +elseif(TARGET_PLATFORM STREQUAL "x86_64-macos") + set(EXTENDER_PLATFORM "x86_64-osx") +endif() +message(STATUS "EXTENDER_PLATFORM=${EXTENDER_PLATFORM}") + +set(DYNAMO_LINK_DIRS + "${REPO_ROOT}/defold-rive/lib/${EXTENDER_PLATFORM}" + "${DYNAMO_HOME}/lib/${TARGET_PLATFORM}" + "${DYNAMO_HOME}/ext/lib/${TARGET_PLATFORM}" +) + +foreach(dir IN LISTS DYNAMO_LINK_DIRS) + if(EXISTS "${dir}") + target_link_directories(rive_plugin PRIVATE "${dir}") + message("LIBPATH+=${dir}") + else() + message(FATAL_ERROR "Directory doesn't exist: ${dir}") + endif() +endforeach() + +set_target_properties(rive_plugin PROPERTIES + CXX_STANDARD 20 + CXX_STANDARD_REQUIRED ON + POSITION_INDEPENDENT_CODE ON + OUTPUT_NAME "RiveExt" +) + +if(WIN32) + set_target_properties(rive_plugin PROPERTIES PREFIX "lib") +else() + set_target_properties(rive_plugin PROPERTIES PREFIX "lib") +endif() + +if(TARGET_PLATFORM MATCHES "macos") + target_compile_options(rive_plugin PRIVATE "-mmacosx-version-min=10.15") + target_include_directories(rive_plugin PRIVATE + "${REPO_ROOT}/defold-rive/include/osx" + ) + target_link_libraries(rive_plugin PRIVATE "-framework CoreFoundation") + target_link_libraries(rive_plugin PRIVATE "-framework Foundation") + target_link_libraries(rive_plugin PRIVATE "-framework AppKit") + target_compile_options(rive_plugin PRIVATE "-fno-exceptions" "-fno-rtti") + set(JAVA_PLATFORM "darwin") +elseif(TARGET_PLATFORM MATCHES "win32") + target_include_directories(rive_plugin PRIVATE + "${REPO_ROOT}/defold-rive/include/win32" + ) + set(JAVA_PLATFORM "win32") +elseif(TARGET_PLATFORM MATCHES "linux") + target_include_directories(rive_plugin PRIVATE + "${REPO_ROOT}/defold-rive/include/linux" + ) + target_compile_options(rive_plugin PRIVATE "-fno-exceptions" "-fno-rtti") + set(JAVA_PLATFORM "linux") +endif() + +if(MSVC) + target_compile_options(rive_plugin PRIVATE /bigobj) +endif() diff --git a/utils/plugin/download_defoldsdk.sh b/utils/plugin/download_defoldsdk.sh new file mode 100755 index 00000000..905ac309 --- /dev/null +++ b/utils/plugin/download_defoldsdk.sh @@ -0,0 +1,165 @@ +#!/usr/bin/env bash + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(cd "${SCRIPT_DIR}/../.." && pwd)" + +function usage() { + cat </info.json. +EOF + exit 1 +} + +VERSION="" +CHANNEL="stable" +OUTPUT_SDK="" +HOST_PLATFORM="" +BOB_ONLY=0 +ARGS_PROVIDED=0 +while [[ $# -gt 0 ]]; do + case "$1" in + --version) + VERSION="${2:-}" + shift 2 + ARGS_PROVIDED=1 + ;; + --channel) + CHANNEL="${2:-}" + shift 2 + ARGS_PROVIDED=1 + ;; + --output-sdk) + OUTPUT_SDK="${2:-}" + shift 2 + ARGS_PROVIDED=1 + ;; + --host-platform) + HOST_PLATFORM="${2:-}" + shift 2 + ARGS_PROVIDED=1 + ;; + --bob-only) + BOB_ONLY=1 + shift + ARGS_PROVIDED=1 + ;; + -*) + echo "Unknown option: $1" >&2 + usage + ;; + *) + VERSION="$1" + shift + ARGS_PROVIDED=1 + ;; + esac +done + +if [[ ${ARGS_PROVIDED} -eq 0 ]]; then + usage +fi + +if [ -z "${VERSION}" ] || [ "${VERSION}" = "latest" ]; then + if ! command -v jq >/dev/null 2>&1; then + echo "jq is required to fetch the default Defold version" >&2 + exit 1 + fi + + VERSION=$(curl -sSL https://d.defold.com/${CHANNEL}/info.json | jq -r .version) + if [ -z "${VERSION}" ] || [ "${VERSION}" = "null" ]; then + echo "Failed to resolve version from https://d.defold.com/${CHANNEL}/info.json" >&2 + exit 1 + fi +fi + +DOWNLOAD_BASE="https://github.com/defold/defold/releases/download/${VERSION}" +SDK_URL="${DOWNLOAD_BASE}/defoldsdk.zip" +BOB_URL="${DOWNLOAD_BASE}/bob.jar" + +echo "Using Defold version: ${VERSION}" + +DEFOLD_SDK_ZIP="${REPO_ROOT}/defoldsdk-${VERSION}.zip" +BOB_JAR="${REPO_ROOT}/bob.jar" + +OUTPUT_SDK_ROOT="${OUTPUT_SDK:-${REPO_ROOT}/build/defoldsdk}" + +if [ -f "${BOB_JAR}" ]; then + echo "bob.jar already exists at ${BOB_JAR}, skipping download" +else + echo "Downloading bob.jar (${BOB_URL})" + curl -fSL -o "${BOB_JAR}" "${BOB_URL}" + echo "Downloaded ${BOB_JAR}" +fi + +if [ "${BOB_ONLY}" -eq 1 ]; then + echo "bob-only mode: exiting after bob.jar download." + exit 0 +fi + +SDK_PRESENT=0 +if [ -d "${OUTPUT_SDK_ROOT}" ]; then + echo "Defold SDK already extracted at ${OUTPUT_SDK_ROOT}, skipping download/unzip." + SDK_PRESENT=1 +else + echo "Downloading ${SDK_URL} to ${DEFOLD_SDK_ZIP}" + curl -fSL -o "${DEFOLD_SDK_ZIP}" "${SDK_URL}" + echo "Downloaded ${DEFOLD_SDK_ZIP}" + + echo "Extracting ${DEFOLD_SDK_ZIP} into ${OUTPUT_SDK_ROOT}" + mkdir -p "${OUTPUT_SDK_ROOT}" + if command -v unzip >/dev/null 2>&1; then + unzip -q "${DEFOLD_SDK_ZIP}" -d "${OUTPUT_SDK_ROOT}" + else + python - < Dict[str, dict]: + result = {} + pattern = re.compile(r"/\*\*((?:.|\n)*?)\*/\s+static int (Script_\w+)\(", re.MULTILINE) + + for match in pattern.finditer(text): + doc_text = match.group(1) + script_name = match.group(2) + result[script_name] = parse_doc_block(doc_text) + return result + + +def parse_doc_block(doc_text: str) -> dict: + lines = [] + for raw in doc_text.splitlines(): + raw = raw.strip() + if raw.startswith("*"): + raw = raw[1:].lstrip() + lines.append(raw) + description_lines = [] + params = [] + returns = [] + names: List[str] = [] + desc_done = False + i = 0 + while i < len(lines): + line = lines[i] + if line.startswith("@name"): + names_line = line[len("@name"):].strip() + parts = [part.strip() for part in names_line.split("/") if part.strip()] + names.extend(parts) + desc_done = True + i += 1 + continue + if line.startswith("@param"): + desc_done = True + param = parse_typed_line(line[len("@param") :].strip()) + i += 1 + extra = [] + while i < len(lines) and not lines[i].startswith("@"): + extra.append(lines[i]) + i += 1 + param["extras"] = extra + params.append(param) + continue + if line.startswith("@return"): + desc_done = True + returns.append(parse_typed_line(line[len("@return") :].strip())) + i += 1 + continue + if not desc_done and line: + description_lines.append(line) + i += 1 + description = " ".join(description_lines).strip() + for param in params: + apply_type_alias(param) + if param["name"] == "callback": + nested = parse_callback_sections(param.get("extras", [])) + if nested: + param["parameters"] = nested + elif param.get("extras"): + # drop extras for non-callback parameters + pass + for ret in returns: + apply_type_alias(ret) + return { + "description": description, + "parameters": params, + "returns": returns, + "names": names, + } + + +def parse_typed_line(text: str) -> dict: + match = re.match(r"(\w+)\s+\[type:\s*([^\]]+)\]\s*(.*)", text) + if not match: + raise SystemExit(f"Could not parse typed line: {text!r}") + name = match.group(1) + type_text = match.group(2).strip() + desc = match.group(3).strip() + return {"name": name, "type": type_text, "desc": desc} + + +def apply_type_alias(entry: dict): + name = entry["name"] + type_text = entry["type"] + alias = TYPE_ALIAS_BY_NAME.get(name) + if alias: + entry["type"] = alias + return + if type_text in TYPE_ALIAS_BY_NAME: + entry["type"] = TYPE_ALIAS_BY_NAME[type_text] + return + entry["type"] = TYPE_ALIAS_BY_NAME.get(type_text, type_text) + + +def parse_callback_sections(lines: List[str]) -> List[dict]: + sections = [] + current: Optional[dict] = None + bullets: List[str] = [] + for raw in lines: + text = raw.strip() + if not text: + continue + if text.startswith("`") and "`" in text[1:]: + if current: + current["bullets"] = bullets + bullets = [] + key = text.strip("`").strip() + current = {"name": key, "type": "", "desc": "", "bullets": []} + sections.append(current) + continue + if text.startswith(":"): + match = re.match(r":\s*\[type:\s*([^\]]+)\]\s*(.*)", text) + if match and current: + current["type"] = match.group(1).strip() + current["desc"] = match.group(2).strip() + continue + if text.startswith("-"): + bullets.append(text[1:].strip()) + continue + if current: + current["bullets"] = bullets + result = [] + for section in sections: + entry = { + "name": section["name"], + "type": section["type"] or "string", + "desc": section["desc"], + } + if entry["name"] == "event" and section["bullets"]: + extras = ", ".join(b.strip("` ") for b in section["bullets"]) + entry["desc"] = f"{entry['desc']} {extras}".strip() + if entry["name"] == "data" and section["bullets"]: + subparams = [] + for bullet in section["bullets"]: + match = re.match(r"`?([^`]+)`?:\s*\[type:\s*([^\]]+)\]\s*(.*)", bullet) + if not match: + continue + child_name = match.group(1).strip() + child_type = match.group(2).strip() + child_desc = match.group(3).strip() + child_type = TYPE_ALIAS_BY_BULLET.get(child_name, child_type) + subparams.append( + {"name": child_name, "type": child_type, "desc": child_desc} + ) + if subparams: + entry["parameters"] = subparams + result.append(entry) + return result + + +def parse_registration(text: str, symbol: str) -> List[tuple]: + pattern = re.compile( + rf"static const luaL_reg {symbol}\[\]\s*=\s*\{{(.*?)\}};", re.S + ) + match = pattern.search(text) + if not match: + raise SystemExit(f"Registration table {symbol} not found.") + content = match.group(1) + funcs = [] + for item in re.findall(r'\{"([^"]+)",\s*Script_(\w+)\}', content): + funcs.append(item) + return funcs + + +def write_members(members: List[dict]) -> List[str]: + lines = [] + first = True + for member in members: + if not first: + lines.append("") + lines.append("#*****************************************************************************************************") + first = False + lines.append("") + lines.append(f" - name: {member['name']}") + lines.append(" type: function") + lines.append(f" desc: {member['desc']}") + if member.get("parameters"): + lines.append(" parameters:") + for param in member["parameters"]: + lines.extend(format_param(param, 6)) + if member.get("returns"): + lines.append(" return:") + for ret in member["returns"]: + lines.extend( + [ + " - name: {}".format(ret["name"]), + " type: {}".format(ret["type"]), + " desc: {}".format(ret["desc"]), + ] + ) + return lines + + +def format_param(param: dict, indent: int) -> List[str]: + lines = [] + lines.append(" " * indent + f"- name: {param['name']}") + lines.append(" " * (indent + 2) + f"type: {param['type']}") + lines.append(" " * (indent + 2) + f"desc: {param['desc']}") + if param.get("parameters"): + lines.append(" " * (indent + 2) + "parameters:") + for child in param["parameters"]: + lines.extend(format_param(child, indent + 4)) + return lines + + +def build_api(): + rive_text = INPUT_RIVE.read_text() + cmd_text = INPUT_CMD.read_text() + rive_docs = parse_documentation(rive_text) + cmd_docs = parse_documentation(cmd_text) + rive_order = parse_registration(rive_text, "RIVE_FUNCTIONS") + cmd_order = parse_registration(cmd_text, "RIVE_COMMAND_FUNCTIONS") + + rive_members = [] + for lua_name, script_name in rive_order: + doc = rive_docs.get(f"Script_{script_name}") + if not doc: + continue + rive_members.append( + { + "name": lua_name, + "desc": doc["description"] or lua_name, + "parameters": doc["parameters"], + "returns": doc["returns"], + } + ) + + cmd_members = [] + for lua_name, script_name in cmd_order: + doc = cmd_docs.get(f"Script_{script_name}") + if not doc: + continue + cmd_members.append( + { + "name": lua_name, + "desc": doc["description"] or lua_name, + "parameters": doc["parameters"], + "returns": doc["returns"], + } + ) + + lines = [] + lines.append("- name: rive") + lines.append(" type: table") + lines.append(' desc: Rive animation helpers exposed to Lua scripts') + lines.append("") + lines.append(" members:") + lines.extend(write_members(rive_members)) + lines.append("") + lines.append("#*****************************************************************************************************") + lines.append("") + lines.append("- name: rive.cmd") + lines.append(" type: table") + lines.append(" desc: Command queue helpers for interacting with the Rive runtime") + lines.append("") + lines.append(" members:") + lines.extend(write_members(cmd_members)) + lines.append("") + + OUTPUT_API.write_text("\n".join(lines).strip() + "\n") + update_lua_annotations(rive_members, cmd_members) + + +def gather_handle_aliases(members: List[dict]) -> Set[str]: + aliases: Set[str] = set() + for member in members: + for entry in member.get("parameters", []) + member.get("returns", []): + type_name = entry["type"] + if type_name in TYPE_ALIAS_BY_NAME.values(): + aliases.add(type_name) + return aliases + + +def update_lua_annotations(rive_members: List[dict], cmd_members: List[dict]): + lua_lines = [ + "-- Auto generated from utils/update_script_api.py", + "-- WARNING: Do not edit manually.", + "", + "--[[", + "Rive API documentation", + "Functions and constants for interacting with Rive models", + "--]]", + "", + "---@meta", + "---@diagnostic disable: lowercase-global", + "---@diagnostic disable: missing-return", + "---@diagnostic disable: duplicate-doc-param", + "---@diagnostic disable: duplicate-set-field", + "---@diagnostic disable: args-after-dots", + "", + ] + handles = sorted(gather_handle_aliases(rive_members + cmd_members)) + for alias in handles: + lua_lines.append(f"---@alias {alias} integer") + if handles: + lua_lines.append("") + + lua_lines.append("--- @class rive") + lua_lines.append("rive = {}") + lua_lines.append("") + for member in rive_members: + lua_lines.extend(format_lua_function("rive", member)) + lua_lines.append("--- @class rive.cmd") + lua_lines.append("rive.cmd = {}") + lua_lines.append("") + for member in cmd_members: + lua_lines.extend(format_lua_function("rive.cmd", member)) + + OUTPUT_API.parent.mkdir(parents=True, exist_ok=True) + lua_file = OUTPUT_API.with_suffix(".lua") + lua_file.write_text("\n".join(lua_lines).strip() + "\n") + + +def format_lua_function(namespace: str, member: dict) -> List[str]: + lines = [] + lines.append(f"--- {member['desc']}") + for param in member.get("parameters", []): + type_text = param["type"] + optional = False + if "|nil" in type_text: + type_text = type_text.replace("|nil", "") + optional = True + type_text = type_text.strip() + if param.get("parameters"): + inner = ", ".join(entry["name"] for entry in param["parameters"]) + lua_type = f"fun({inner})" + elif "function" in type_text: + lua_type = "function" + else: + lua_type = type_text + param_name = f"{param['name']}?" if optional else param['name'] + lines.append(f"---@param {param_name} {lua_type} {param['desc']}") + if param.get("parameters"): + lines.extend(format_callback_subparams(param["name"], param["parameters"])) + for ret in member.get("returns", []): + lines.append(f"---@return {ret['type']} {ret['name']} {ret['desc']}") + params = ", ".join(param["name"] for param in member.get("parameters", [])) + func_ns = namespace + lines.append(f"function {func_ns}.{member['name']}({params}) end") + lines.append("") + return lines + + +def format_callback_subparams(base: str, entries: List[dict]) -> List[str]: + lines = [] + for entry in entries: + child_name = f"{base}_{entry['name']}" + lines.append(f"---@param {child_name} {entry['type']} {entry['desc']}") + if entry.get("parameters"): + lines.extend(format_callback_subparams(child_name, entry["parameters"])) + return lines + + +if __name__ == "__main__": + build_api() diff --git a/utils/viewer/CMakeLists.txt b/utils/viewer/CMakeLists.txt new file mode 100644 index 00000000..40f53c47 --- /dev/null +++ b/utils/viewer/CMakeLists.txt @@ -0,0 +1,166 @@ +cmake_minimum_required(VERSION 3.16) +project(viewer LANGUAGES CXX) + +set(DYNAMO_HOME $ENV{DYNAMO_HOME}) +if(NOT DYNAMO_HOME) + message(FATAL_ERROR "DYNAMO_HOME environment variable is required") +endif() + +if(NOT TARGET_PLATFORM) + set(TARGET_PLATFORM $ENV{TARGET_PLATFORM}) +endif() + +if(NOT TARGET_PLATFORM) + message(FATAL_ERROR "TARGET_PLATFORM must be supplied as a CMake variable or environment variable") +endif() + +if(${TARGET_PLATFORM} MATCHES "macos") + enable_language(OBJCXX) +endif() + +option(WITH_ASAN "Build viewer with Address Sanitizer" OFF) + +if(NOT CMAKE_BUILD_TYPE) + set(CMAKE_BUILD_TYPE Release CACHE STRING "Build type" FORCE) +endif() + +file(REAL_PATH "${CMAKE_CURRENT_SOURCE_DIR}/../.." EXTENSION_ROOT) + +set(ASAN_SUPPORTED FALSE) +if(CMAKE_CXX_COMPILER_ID MATCHES "Clang|GNU") + set(ASAN_SUPPORTED TRUE) +endif() +if(WITH_ASAN AND NOT ASAN_SUPPORTED) + message(WARNING "Address Sanitizer is not supported for ${CMAKE_CXX_COMPILER_ID}; disabling") + set(WITH_ASAN OFF) +endif() +set(VIEWER_SHADER_SOURCE "${CMAKE_CURRENT_SOURCE_DIR}/shaders.cpp") + +if(${TARGET_PLATFORM} MATCHES "macos") + set(RIVE_BLIT_SHADER_VP "${EXTENSION_ROOT}/defold-rive/assets/shader-library/rivemodel_blit.vp") + set(RIVE_BLIT_SHADER_FP "${EXTENSION_ROOT}/defold-rive/assets/shader-library/rivemodel_blit.fp") + set(RIVE_BLIT_SHADER_OUT "${CMAKE_CURRENT_BINARY_DIR}/shaders.cpp") + set(RIVE_SHADER_GEN_SCRIPT "${CMAKE_CURRENT_SOURCE_DIR}/gen_shaders.py") + + set(BOB_PATH $ENV{BOB}) + if(NOT BOB_PATH) + if(DEFINED ENV{DYNAMO_HOME}) + set(BOB_PATH "$ENV{DYNAMO_HOME}/share/java/bob.jar") + else() + set(BOB_PATH "${EXTENSION_ROOT}/bob.jar") + endif() + endif() + + add_custom_command( + OUTPUT "${RIVE_BLIT_SHADER_OUT}" + COMMAND python3 "${RIVE_SHADER_GEN_SCRIPT}" + --bob "${BOB_PATH}" + --platform "${TARGET_PLATFORM}" + --content-root "${EXTENSION_ROOT}" + --vertex "${RIVE_BLIT_SHADER_VP}" + --fragment "${RIVE_BLIT_SHADER_FP}" + --output "${RIVE_BLIT_SHADER_OUT}" + DEPENDS + "${RIVE_SHADER_GEN_SCRIPT}" + "${RIVE_BLIT_SHADER_VP}" + "${RIVE_BLIT_SHADER_FP}" + VERBATIM + ) + + set(VIEWER_SHADER_SOURCE "${RIVE_BLIT_SHADER_OUT}") +endif() + +add_executable(viewer + "${CMAKE_CURRENT_SOURCE_DIR}/viewer.cpp" + "${VIEWER_SHADER_SOURCE}" +) + +file(GLOB RIVE_COMMON_SRC + "${EXTENSION_ROOT}/defold-rive/commonsrc/*.cpp" + "${EXTENSION_ROOT}/defold-rive/commonsrc/renderer/*.cpp" +) +target_sources(viewer PRIVATE ${RIVE_COMMON_SRC}) + +target_include_directories(viewer PRIVATE + "${EXTENSION_ROOT}/defold-rive/include" + "${DYNAMO_HOME}/sdk/include/${TARGET_PLATFORM}" + "${DYNAMO_HOME}/sdk/include" + "${DYNAMO_HOME}/include/${TARGET_PLATFORM}" + "${DYNAMO_HOME}/include" + "${DYNAMO_HOME}/ext/include/${TARGET_PLATFORM}" + "${DYNAMO_HOME}/ext/include" +) + +target_link_directories(viewer PRIVATE + "${DYNAMO_HOME}/lib/${TARGET_PLATFORM}" + "${DYNAMO_HOME}/ext/lib/${TARGET_PLATFORM}" +) + +if(${TARGET_PLATFORM} MATCHES "macos") + target_link_directories(viewer PRIVATE "${EXTENSION_ROOT}/defold-rive/lib/arm64-osx") +else() + target_link_directories(viewer PRIVATE "${EXTENSION_ROOT}/defold-rive/lib/{TARGET_PLATFORM}") +endif() + +set(TARGET_LIBS + dlib + ddf + profile_null + platform + graphics + + rive + rive_decoders + rive_harfbuzz + rive_pls_renderer + rive_sheenbidi + rive_yoga + libjpeg + libpng + libwebp + miniaudio +) + +if(${TARGET_PLATFORM} MATCHES "macos") + file(GLOB RIVE_COMMON_OBJCXX_SRC + "${EXTENSION_ROOT}/defold-rive/commonsrc/renderer/*.mm" + ) + target_sources(viewer PRIVATE ${RIVE_COMMON_OBJCXX_SRC}) + + list(APPEND TARGET_LIBS + platform_vulkan + graphics_vulkan + glfw3 + MoltenVK + ) + target_link_libraries(viewer PRIVATE + "-framework CoreGraphics" + "-framework CoreFoundation" + "-framework IOKit" + "-framework IOSurface" + "-framework AppKit" + "-framework Metal" + "-framework QuartzCore") + + target_compile_definitions(viewer PRIVATE DM_PLATFORM_MACOS VIEWER_USE_SPIRV=1) +endif() + +target_link_libraries(viewer PRIVATE ${TARGET_LIBS}) + +target_compile_options(viewer PRIVATE + $<$:-O2> + $<$:-g> + $<$>:-O0> + $<$>:-g> +) +if(WITH_ASAN) + target_compile_options(viewer PRIVATE -fsanitize=address) + target_link_options(viewer PRIVATE -fsanitize=address) +endif() + +target_compile_definitions(viewer PRIVATE DLIB_LOG_DOMAIN=\"VIEWER\") + +set_target_properties(viewer PROPERTIES + CXX_STANDARD 17 + CXX_STANDARD_REQUIRED ON +) diff --git a/utils/viewer/README.md b/utils/viewer/README.md new file mode 100644 index 00000000..e69de29b diff --git a/utils/viewer/build.sh b/utils/viewer/build.sh new file mode 100755 index 00000000..9dd32a94 --- /dev/null +++ b/utils/viewer/build.sh @@ -0,0 +1,43 @@ +#!/usr/bin/env bash +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null && pwd)" + +WITH_ASAN=OFF +ARGS=() + +while [[ $# -gt 0 ]]; do + case "$1" in + --with-asan) + WITH_ASAN=ON + shift + ;; + *) + ARGS+=("$1") + shift + ;; + esac +done + +TARGET_PLATFORM="${ARGS[0]:-${TARGET_PLATFORM:-}}" + +if [ -z "${TARGET_PLATFORM}" ]; then + echo "Usage: $0 [--with-asan] " + exit 1 +fi + +ALLOWED_PLATFORMS=("arm64-macos" "x86_64-win32" "x86_64-linux") +if [[ ! " ${ALLOWED_PLATFORMS[*]} " =~ " ${TARGET_PLATFORM} " ]]; then + echo "Unsupported target platform: ${TARGET_PLATFORM}" + echo "Supported platforms: ${ALLOWED_PLATFORMS[*]}" + exit 1 +fi + +BUILD_DIR="${SCRIPT_DIR}/build/${TARGET_PLATFORM}" +mkdir -p "${BUILD_DIR}" + +cmake -S "${SCRIPT_DIR}" -B "${BUILD_DIR}" -G Ninja \ + -DCMAKE_BUILD_TYPE=Release \ + -DTARGET_PLATFORM="${TARGET_PLATFORM}" \ + -DWITH_ASAN=${WITH_ASAN} +cmake --build "${BUILD_DIR}" --target viewer diff --git a/utils/viewer/gen_shaders.py b/utils/viewer/gen_shaders.py new file mode 100644 index 00000000..fbcb2897 --- /dev/null +++ b/utils/viewer/gen_shaders.py @@ -0,0 +1,115 @@ +#!/usr/bin/env python3 +import argparse +import os +import pathlib +import shlex +import subprocess +import sys +import tempfile + + +def resolve_bob_path(cli_bob): + if cli_bob: + return cli_bob + env_bob = os.environ.get("BOB") + if env_bob: + return env_bob + dynamo_home = os.environ.get("DYNAMO_HOME") + if dynamo_home: + return os.path.join(dynamo_home, "share", "java", "bob.jar") + return "" + + +def write_cpp(output_path, spc_bytes, source_paths, command_line): + output_path.parent.mkdir(parents=True, exist_ok=True) + with output_path.open("w", encoding="ascii") as out: + out.write("// Generated by gen_shaders.py. Do not edit.\n") + out.write("// Command: {}\n".format(command_line)) + out.write("// Sources:\n") + for path in source_paths: + out.write("// {}\n".format(path)) + out.write("\n") + out.write("#include \n") + out.write("#include \n") + out.write("#include \n") + out.write("#include \n") + out.write("\n") + out.write("static uint8_t RIVEMODEL_BLIT_SPC[] = {\n") + for i in range(0, len(spc_bytes), 12): + chunk = spc_bytes[i : i + 12] + line = ", ".join("0x{:02x}".format(b) for b in chunk) + out.write(" {},\n".format(line)) + out.write("};\n") + out.write("static const uint32_t RIVEMODEL_BLIT_SPC_SIZE = sizeof(RIVEMODEL_BLIT_SPC);\n") + out.write("\n") + out.write("namespace dmGraphics\n") + out.write("{\n") + out.write(" ShaderDesc* CreateRiveModelBlitShaderDesc()\n") + out.write(" {\n") + out.write(" static ShaderDesc* shader_desc = 0;\n") + out.write(" if (!shader_desc)\n") + out.write(" {\n") + out.write(" void* msg = 0;\n") + out.write(" dmDDF::Result result = dmDDF::LoadMessage(RIVEMODEL_BLIT_SPC,\n") + out.write(" RIVEMODEL_BLIT_SPC_SIZE,\n") + out.write(" ShaderDesc::m_DDFDescriptor,\n") + out.write(" &msg);\n") + out.write(" if (result != dmDDF::RESULT_OK)\n") + out.write(" {\n") + out.write(" return 0;\n") + out.write(" }\n") + out.write(" shader_desc = (ShaderDesc*) msg;\n") + out.write(" }\n") + out.write(" return shader_desc;\n") + out.write(" }\n") + out.write("}\n") + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--bob", default="") + parser.add_argument("--platform", required=True) + parser.add_argument("--content-root", required=True) + parser.add_argument("--vertex", required=True) + parser.add_argument("--fragment", required=True) + parser.add_argument("--output", required=True) + args = parser.parse_args() + + bob_path = resolve_bob_path(args.bob) + if not bob_path or not os.path.isfile(bob_path): + print("bob.jar not found. Set --bob, BOB, or DYNAMO_HOME.", file=sys.stderr) + return 1 + + content_root = pathlib.Path(args.content_root).resolve() + vertex_path = pathlib.Path(args.vertex).resolve() + fragment_path = pathlib.Path(args.fragment).resolve() + output_path = pathlib.Path(args.output).absolute() + + if not vertex_path.is_file() or not fragment_path.is_file(): + print("Shader inputs not found.", file=sys.stderr) + return 1 + + with tempfile.TemporaryDirectory() as tmpdir: + spc_path = pathlib.Path(tmpdir) / "rivemodel_blit.spc" + cmd = [ + "java", + "-classpath", + bob_path, + "com.dynamo.bob.pipeline.ShaderProgramBuilder", + str(vertex_path), + str(fragment_path), + str(spc_path), + args.platform, + str(content_root), + ] + cmd_str = " ".join(shlex.quote(part) for part in cmd) + subprocess.check_call(cmd) + + spc_bytes = spc_path.read_bytes() + write_cpp(output_path, spc_bytes, [vertex_path, fragment_path], cmd_str) + + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/utils/viewer/viewer.cpp b/utils/viewer/viewer.cpp new file mode 100644 index 00000000..f797c819 --- /dev/null +++ b/utils/viewer/viewer.cpp @@ -0,0 +1,626 @@ +// Copyright 2020-2025 The Defold Foundation +// Copyright 2014-2020 King +// Copyright 2009-2014 Ragnar Svensson, Christian Murray +// Licensed under the Defold License version 1.0 (the "License"); you may not use +// this file except in compliance with the License. +// +// You may obtain a copy of the License, together with FAQs at +// https://www.defold.com/license +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +// Creating a small app test for initializing an running a small graphics app + +#include +#include +#include +#include + +#include +#include +#include +#include + + +#include +#include // LogParams +#include // JobThread +#include // ContextParams + +#include +#include + +namespace dmGraphics +{ + ShaderDesc* CreateRiveModelBlitShaderDesc(); +} + +enum UpdateResult +{ + RESULT_OK = 0, + RESULT_REBOOT = 1, + RESULT_EXIT = -1, +}; + +typedef void* (*EngineCreateFn)(int argc, char** argv); +typedef void (*EngineDestroyFn)(void* engine); +typedef UpdateResult (*EngineUpdateFn)(void* engine); +typedef void (*EngineGetResultFn)(void* engine, int* run_action, int* exit_code, int* argc, char*** argv); + + +static const char* s_RiveFilePath = 0; + +static bool ReadFile(const char* path, std::vector& out) +{ + FILE* f = fopen(path, "rb"); + if (!f) + { + fprintf(stderr, "Failed to open '%s'\n", path); + return false; + } + + if (fseek(f, 0, SEEK_END) != 0) + { + fclose(f); + return false; + } + long size = ftell(f); + if (size < 0) + { + fclose(f); + return false; + } + rewind(f); + + out.resize(size); + if (size > 0) + { + size_t read = fread(out.data(), 1, size, f); + if (read != (size_t)size) + { + fclose(f); + return false; + } + } + + fclose(f); + return true; +} + +struct AppCtx +{ + int m_Created; + int m_Destroyed; +}; + +struct EngineCtx +{ + int m_WasCreated; + int m_WasRun; + int m_WasDestroyed; + int m_WasResultCalled; + int m_Running; + bool m_WindowClosed; + + dmJobThread::HContext m_JobThread; + + dmPlatform::HWindow m_Window; + dmGraphics::HContext m_GraphicsContext; + + dmGraphics::HVertexBuffer m_BlitToBackbufferVertexBuffer; + dmGraphics::HVertexDeclaration m_VertexDeclaration; + dmGraphics::HProgram m_BlitProgram; + dmGraphics::HTexture m_Texture; + dmGraphics::HUniformLocation m_SamplerLocation; + + // Rive related + dmRive::HRenderContext m_RenderContext; + + rive::FileHandle m_File; + rive::ArtboardHandle m_Artboard; + rive::StateMachineHandle m_StateMachine; + rive::ViewModelInstanceHandle m_ViewModelInstance; + rive::DrawKey m_DrawKey; +}; + +struct RunLoopParams +{ + int m_Argc; + char** m_Argv; + + void* m_AppCtx; + void (*m_AppCreate)(void* ctx); + void (*m_AppDestroy)(void* ctx); + + EngineCreateFn m_EngineCreate; + EngineDestroyFn m_EngineDestroy; + EngineUpdateFn m_EngineUpdate; + EngineGetResultFn m_EngineGetResult; +}; + +static int RunLoop(const RunLoopParams* params) +{ + if (params->m_AppCreate) + params->m_AppCreate(params->m_AppCtx); + + int argc = params->m_Argc; + char** argv = params->m_Argv; + int exit_code = 0; + void* engine = 0; + UpdateResult result = RESULT_OK; + while (RESULT_OK == result) + { + if (engine == 0) + { + engine = params->m_EngineCreate(argc, argv); + if (!engine) + { + exit_code = 1; + break; + } + } + + result = params->m_EngineUpdate(engine); + + if (RESULT_OK != result) + { + int run_action = 0; + params->m_EngineGetResult(engine, &run_action, &exit_code, &argc, &argv); + + params->m_EngineDestroy(engine); + engine = 0; + + if (RESULT_REBOOT == result) + { + // allows us to reboot + result = RESULT_OK; + } + } + } + + if (params->m_AppDestroy) + params->m_AppDestroy(params->m_AppCtx); + + return exit_code; +} + +static void AppCreate(void* _ctx) +{ + dmLog::LogParams params; + dmLog::LogInitialize(¶ms); + + AppCtx* ctx = (AppCtx*)_ctx; + ctx->m_Created++; +} + +static void AppDestroy(void* _ctx) +{ + AppCtx* ctx = (AppCtx*)_ctx; + ctx->m_Destroyed++; +} + +static dmGraphics::HUniformLocation FindUniformLocation(dmGraphics::HProgram program, const char* name) +{ + uint32_t uniform_count = dmGraphics::GetUniformCount(program); + for (uint32_t i = 0; i < uniform_count; ++i) + { + dmGraphics::Uniform uniform; + dmGraphics::GetUniform(program, i, &uniform); + if (uniform.m_Name && strcmp(uniform.m_Name, name) == 0) + { + return uniform.m_Location; + } + } + + return dmGraphics::INVALID_UNIFORM_LOCATION; +} + +static void DrawFullscreenQuad(EngineCtx* engine, dmGraphics::HTexture texture) +{ + if (engine->m_BlitProgram == 0 || engine->m_BlitProgram == dmGraphics::INVALID_PROGRAM_HANDLE || texture == 0) + { + return; + } + + dmGraphics::HContext context = engine->m_GraphicsContext; + uint32_t window_width = dmGraphics::GetWindowWidth(context); + uint32_t window_height = dmGraphics::GetWindowHeight(context); + dmGraphics::SetViewport(context, 0, 0, window_width, window_height); + dmGraphics::EnableProgram(context, engine->m_BlitProgram); + dmGraphics::EnableVertexDeclaration(context, engine->m_VertexDeclaration, 0, 0, engine->m_BlitProgram); + dmGraphics::EnableVertexBuffer(context, engine->m_BlitToBackbufferVertexBuffer, 0); + + dmGraphics::EnableTexture(context, 0, 0, texture); + if (engine->m_SamplerLocation != dmGraphics::INVALID_UNIFORM_LOCATION) + { + dmGraphics::SetSampler(context, engine->m_SamplerLocation, 0); + } + + dmGraphics::Draw(context, dmGraphics::PRIMITIVE_TRIANGLES, 0, 6, 1); + + dmGraphics::DisableTexture(context, 0, texture); + dmGraphics::DisableVertexBuffer(context, engine->m_BlitToBackbufferVertexBuffer); + dmGraphics::DisableVertexDeclaration(context, engine->m_VertexDeclaration); + dmGraphics::DisableProgram(context); +} + +static bool OnWindowClose(void* user_data) +{ + EngineCtx* engine = (EngineCtx*) user_data; + engine->m_WindowClosed = 1; + return true; +} + +static void* EngineCreate(int argc, char** argv) +{ + EngineCtx* engine = new EngineCtx; + memset(engine, 0, sizeof(*engine)); + engine->m_Window = dmPlatform::NewWindow(); + + dmJobThread::JobThreadCreationParams job_params = {0}; + engine->m_JobThread = dmJobThread::Create(job_params); + + dmPlatform::WindowParams window_params = {}; + window_params.m_Width = 512; + window_params.m_Height = 512; + window_params.m_Title = "Rive Viewer App"; + + window_params.m_GraphicsApi = dmPlatform::PLATFORM_GRAPHICS_API_VULKAN; + window_params.m_CloseCallback = OnWindowClose; + window_params.m_CloseCallbackUserData = (void*) engine; + + if (dmGraphics::GetInstalledAdapterFamily() == dmGraphics::ADAPTER_FAMILY_OPENGL) + { + window_params.m_GraphicsApi = dmPlatform::PLATFORM_GRAPHICS_API_OPENGL; + } + else if (dmGraphics::GetInstalledAdapterFamily() == dmGraphics::ADAPTER_FAMILY_OPENGLES) + { + window_params.m_GraphicsApi = dmPlatform::PLATFORM_GRAPHICS_API_OPENGLES; + } + else if (dmGraphics::GetInstalledAdapterFamily() == dmGraphics::ADAPTER_FAMILY_DIRECTX) + { + window_params.m_GraphicsApi = dmPlatform::PLATFORM_GRAPHICS_API_DIRECTX; + } + + dmPlatform::OpenWindow(engine->m_Window, window_params); + dmPlatform::ShowWindow(engine->m_Window); + + dmGraphics::ContextParams graphics_context_params = {}; + graphics_context_params.m_DefaultTextureMinFilter = dmGraphics::TEXTURE_FILTER_LINEAR_MIPMAP_NEAREST; + graphics_context_params.m_DefaultTextureMagFilter = dmGraphics::TEXTURE_FILTER_LINEAR_MIPMAP_NEAREST; + graphics_context_params.m_VerifyGraphicsCalls = 1; + graphics_context_params.m_UseValidationLayers = 1; + graphics_context_params.m_Window = engine->m_Window; + graphics_context_params.m_Width = 512; + graphics_context_params.m_Height = 512; + graphics_context_params.m_JobThread = engine->m_JobThread; + + engine->m_GraphicsContext = dmGraphics::NewContext(graphics_context_params); + + engine->m_WasCreated++; + engine->m_Running = 1; + + // dmRender::RenderContextParams render_params; + // render_params.m_ScriptContext = 0; + // render_params.m_SystemFontMap = 0; + // render_params.m_ShaderProgramDesc = 0; + // render_params.m_MaxRenderTypes = 16; + // render_params.m_MaxInstances = 2048; + // render_params.m_MaxRenderTargets = 32; + // render_params.m_ShaderProgramDescSize = 0; + // render_params.m_MaxCharacters = 2048 * 4; + // render_params.m_MaxBatches = 128; + // render_params.m_CommandBufferSize = 1024; + // render_params.m_MaxDebugVertexCount = 0; + // engine->m_RenderListContext = dmRender::NewRenderContext(engine->m_GraphicsContext, render_params); + + // Graphics + + float bottom = 0.0f; + float top = 1.0f; + + // Flip texture coordinates on y axis for OpenGL for the final blit: + if (dmGraphics::GetInstalledAdapterFamily() != dmGraphics::ADAPTER_FAMILY_OPENGL) + { + top = 0.0f; + bottom = 1.0f; + } + + const float vertex_data[] = { + -1.0f, -1.0f, 0.0f, bottom, // Bottom-left corner + 1.0f, -1.0f, 1.0f, bottom, // Bottom-right corner + -1.0f, 1.0f, 0.0f, top, // Top-left corner + 1.0f, -1.0f, 1.0f, bottom, // Bottom-right corner + 1.0f, 1.0f, 1.0f, top, // Top-right corner + -1.0f, 1.0f, 0.0f, top // Top-left corner + }; + + engine->m_BlitToBackbufferVertexBuffer = dmGraphics::NewVertexBuffer(engine->m_GraphicsContext, sizeof(vertex_data), (void*) vertex_data, dmGraphics::BUFFER_USAGE_STATIC_DRAW); + + dmGraphics::HVertexStreamDeclaration stream_declaration_vertex = dmGraphics::NewVertexStreamDeclaration(engine->m_GraphicsContext); + dmGraphics::AddVertexStream(stream_declaration_vertex, "position", 2, dmGraphics::TYPE_FLOAT, false); + dmGraphics::AddVertexStream(stream_declaration_vertex, "texcoord0", 2, dmGraphics::TYPE_FLOAT, false); + engine->m_VertexDeclaration = dmGraphics::NewVertexDeclaration(engine->m_GraphicsContext, stream_declaration_vertex); + + dmGraphics::ShaderDesc* shader_desc = dmGraphics::CreateRiveModelBlitShaderDesc(); + char program_error[512] = {}; + engine->m_BlitProgram = dmGraphics::NewProgram(engine->m_GraphicsContext, + shader_desc, + program_error, + sizeof(program_error)); + engine->m_SamplerLocation = dmGraphics::INVALID_UNIFORM_LOCATION; + if (engine->m_BlitProgram == dmGraphics::INVALID_PROGRAM_HANDLE || engine->m_BlitProgram == 0) + { + dmLogError("Failed to create blit program: %s", program_error); + engine->m_BlitProgram = dmGraphics::INVALID_PROGRAM_HANDLE; + } + else + { + engine->m_SamplerLocation = FindUniformLocation(engine->m_BlitProgram, "texture_sampler"); + } + + // Rive + engine->m_RenderContext = dmRive::NewRenderContext(); + + dmRiveCommands::InitParams cmd_params; + cmd_params.m_RenderContext = engine->m_RenderContext; + cmd_params.m_Factory = dmRive::GetRiveFactory(engine->m_RenderContext); + dmRiveCommands::Initialize(&cmd_params); + + if (s_RiveFilePath) + { + printf("Loading '%s'\n", s_RiveFilePath); + + rive::rcp queue = dmRiveCommands::GetCommandQueue(); + std::vector bytes; + if (ReadFile(s_RiveFilePath, bytes)) + { + engine->m_File = queue->loadFile(bytes); + + if (engine->m_File) + { + printf("Loaded file\n"); + + engine->m_Artboard = queue->instantiateDefaultArtboard(engine->m_File); + if (engine->m_Artboard) + { + printf("Created default artboard\n"); + + engine->m_StateMachine = queue->instantiateDefaultStateMachine(engine->m_Artboard); + if (engine->m_StateMachine) + { + printf("Created default state machine\n"); + + engine->m_ViewModelInstance = queue->instantiateDefaultViewModelInstance(engine->m_File, engine->m_Artboard); + if (engine->m_ViewModelInstance) + { + printf("Created default view model instance\n"); + + queue->bindViewModelInstance(engine->m_StateMachine, engine->m_ViewModelInstance); + } + } + } + } + } + + engine->m_DrawKey = queue->createDrawKey(); + } + + return engine; +} + +static void EngineDestroy(void* _engine) +{ + EngineCtx* engine = (EngineCtx*)_engine; + + dmRiveCommands::Finalize(); + dmRive::DeleteRenderContext(engine->m_RenderContext); + + dmJobThread::Destroy(engine->m_JobThread); + + dmGraphics::DeleteVertexBuffer(engine->m_BlitToBackbufferVertexBuffer); + dmGraphics::DeleteVertexDeclaration(engine->m_VertexDeclaration); + if (engine->m_BlitProgram != 0 && engine->m_BlitProgram != dmGraphics::INVALID_PROGRAM_HANDLE) + { + dmGraphics::DeleteProgram(engine->m_GraphicsContext, engine->m_BlitProgram); + } + + dmGraphics::CloseWindow(engine->m_GraphicsContext); + dmGraphics::DeleteContext(engine->m_GraphicsContext); + dmGraphics::Finalize(); + + engine->m_WasDestroyed++; + + delete engine; +} + +static void UpdateRiveScene(EngineCtx* engine) +{ + rive::rcp queue = dmRiveCommands::GetCommandQueue(); + + static uint64_t last_update = dmTime::GetMonotonicTime(); + uint64_t time = dmTime::GetMonotonicTime(); + float dt = (time - last_update) / 1000000.0f; + last_update = time; + queue->advanceStateMachine(engine->m_StateMachine, dt); +} + +static void DrawRiveScene(EngineCtx* engine) +{ + rive::rcp queue = dmRiveCommands::GetCommandQueue(); + + rive::Renderer* renderer = dmRive::GetRiveRenderer(engine->m_RenderContext); + + const rive::ArtboardHandle artboardHandle = engine->m_Artboard; + static rive::Fit s_fit = rive::Fit::contain; + static rive::Alignment s_alignment= rive::Alignment::center; + + rive::Fit fit = s_fit; + rive::Alignment alignment = s_alignment; + + uint32_t width = dmGraphics::GetWindowWidth(engine->m_GraphicsContext); + uint32_t height = dmGraphics::GetWindowHeight(engine->m_GraphicsContext); + float display_factor = dmGraphics::GetDisplayScaleFactor(engine->m_GraphicsContext); + + auto drawLoop = [artboardHandle, + renderer, + fit, + alignment, + width, + height, + display_factor](rive::DrawKey drawKey, rive::CommandServer* server) + { + rive::ArtboardInstance* artboard = server->getArtboardInstance(artboardHandle); + if (artboard == nullptr) + { + return; + } + + rive::Factory* factory = server->factory(); + // Draw the .riv. + renderer->save(); + + rive::AABB bounds = artboard->bounds(); + + bool fullscreen = false; + if (fullscreen) + { + // // Apply the world matrix from the component to the artboard transform + // rive::Mat2D transform = rive::Mat2D::fromTranslate(width / 2.0f, height / 2.0f); + // rive::Mat2D centerAdjustment = rive::Mat2D::fromTranslate(-bounds.width() / 2.0f, -bounds.height() / 2.0f); + // rive::Mat2D scaleDpi = rive::Mat2D::fromScale(1,-1); + // rive::Mat2D invertAdjustment = rive::Mat2D::fromScaleAndTranslation(display_factor, -display_factor, 0, window_height); + // rive::Mat2D rendererTransform = invertAdjustment * viewTransform * transform * scaleDpi * centerAdjustment; + + // renderer->transform(rendererTransform); + // For making input work nicely + //c->m_InverseRendererTransform = rendererTransform.invertOrIdentity(); + } + else + { + if (fit == rive::Fit::layout) + { + artboard->width(width / display_factor); + artboard->height(height / display_factor); + } + + rive::Mat2D rendererTransform = rive::computeAlignment(fit, alignment, rive::AABB(0, 0, width, height), bounds, display_factor); + renderer->transform(rendererTransform); + // For making input work nicely + //c->m_InverseRendererTransform = rendererTransform.invertOrIdentity(); + } + + artboard->draw(renderer); + renderer->restore(); + }; + + queue->draw(engine->m_DrawKey, drawLoop); +} + +static UpdateResult EngineUpdate(void* _engine) +{ + EngineCtx* engine = (EngineCtx*)_engine; + engine->m_WasRun++; + uint64_t t = dmTime::GetMonotonicTime(); + + if (!engine->m_Running) + { + return RESULT_EXIT; + } + + dmJobThread::Update(engine->m_JobThread, 0); // Flush any graphics jobs + + dmPlatform::PollEvents(engine->m_Window); + + if (engine->m_WindowClosed) + { + return RESULT_EXIT; + } + + UpdateRiveScene(engine); + + { + rive::rcp queue = dmRiveCommands::GetCommandQueue(); + + // engine->m_Factory + dmRive::RenderBeginParams render_params; + render_params.m_DoFinalBlit = true; + render_params.m_BackbufferSamples = 0; + dmRive::RenderBegin(engine->m_RenderContext, 0, render_params); + + DrawRiveScene(engine); + + dmRiveCommands::ProcessMessages(); // Making sure any draw call is processed + dmRive::RenderEnd(engine->m_RenderContext); + } + + dmGraphics::BeginFrame(engine->m_GraphicsContext); + dmGraphics::Clear(engine->m_GraphicsContext, dmGraphics::BUFFER_TYPE_COLOR0_BIT, + 0.0f, 0.0f, 0.0f, 0.0f, + 1.0f, 0); + + DrawFullscreenQuad(engine, dmRive::GetBackingTexture(engine->m_RenderContext)); + + dmGraphics::Flip(engine->m_GraphicsContext); + + return RESULT_OK; +} + +static void EngineGetResult(void* _engine, int* run_action, int* exit_code, int* argc, char*** argv) +{ + EngineCtx* ctx = (EngineCtx*)_engine; + ctx->m_WasResultCalled++; +} + +#if defined(__APPLE__) || defined(__linux__) +extern "C" void GraphicsAdapterVulkan(); +#else +extern "C" void GraphicsAdapterOpenGL(); +#endif + +static void dmExportedSymbols() +{ +#if defined(__APPLE__) || defined(__linux__) + GraphicsAdapterVulkan(); +#else + GraphicsAdapterOpenGL(); +#endif +} + +int main(int argc, char **argv) +{ + dmExportedSymbols(); + dmGraphics::InstallAdapter(); + + if (argc > 1) + { + const char* path = argv[argc-1]; + size_t len = strlen(path); + if (len > 4 && strcmp(path + len - 4, ".riv") == 0) + { + s_RiveFilePath = path; + } + else + { + fprintf(stderr, "Must speficy a .riv path"); + return 1; + } + } + + AppCtx ctx; + memset(&ctx, 0, sizeof(ctx)); + + RunLoopParams params; + params.m_AppCtx = &ctx; + params.m_AppCreate = AppCreate; + params.m_AppDestroy = AppDestroy; + params.m_EngineCreate = EngineCreate; + params.m_EngineDestroy = EngineDestroy; + params.m_EngineUpdate = EngineUpdate; + params.m_EngineGetResult = EngineGetResult; + + return RunLoop(¶ms); +} diff --git a/wagyu.appmanifest b/wagyu.appmanifest index 7b60905b..c122b905 100644 --- a/wagyu.appmanifest +++ b/wagyu.appmanifest @@ -1,11 +1,11 @@ platforms: wasm-web: context: - defines: ["DM_RIVE_USE_OPENGL", "RIVE_WEBGL", "RIVE_WEBGPU=2", "RIVE_WAGYU"] + defines: ["DM_RIVE_USE_OPENGL", "RIVE_WEBGL", "RIVE_WEBGPU", "RIVE_WAGYU"] symbols: [GraphicsAdapterWebGPU] excludeLibs: [rive_renderer, graphics_webgpu] libs: [graphics_webgpu_wagyu] flags: ["-std=c++17", "-fno-rtti"] linkFlags: ['-lexports.js', '-lrive_renderer_wagyu'] - externalJsPorts: ["ext/wagyu-port/new/webgpu-port.py:wagyu=true"] + externalJsPorts: ["ext/wagyu-port/webgpu-port.py:wagyu=true"] emscriptenLinkFlags: [WASM_BIGINT=1]