Compare commits

...
46 Commits
Author SHA1 Message Date
BZLZHH a54c7b49c9 [Chore] (android-plugin/app, MobileGL, userguide): set the version to 26.11-alpha.2 2026-11-29 12:28:37 +08:00
BZLZHH 13d9317aab [Test] (MG_Test/Buffer): keep the mapping backend alive through adoption checks 2026-11-29 11:56:37 +08:00
BZLZHH bc7e703e23 [Fix] (MobileGL, android-plugin/app): release the test surface before restarting a canceled run 2026-11-29 11:28:16 +08:00
BZLZHH df0e1d3bdd [Fix, Test] (DirectGLES, pipe, tests): isolate server buffer lookup and verify FBO ownership 2026-11-29 11:21:46 +08:00
BZLZHH 04f7faedc1 [Feat] (Android plugin, renderer samples): add interactive tests and external trace replay 2026-11-29 11:10:39 +08:00
BZLZHH 9560cca571 [Fix] (MG_Backend/DirectVulkan): resolve driver properties through the Vulkan instance 2026-11-29 09:43:37 +08:00
BZLZHH 6ac2bb682a [Feat] (Backend selection, configuration, tests): prefer usable hardware Vulkan by default 2026-11-29 09:34:44 +08:00
BZLZHH adfed91a1e [Refactor] (android-plugin/app, MG_Util/SelfTest): simplify Android controls and driver diagnostics 2026-11-29 09:08:03 +08:00
BZLZHH 0059ccdd79 [Fix, Test] (EGL, buffers, wire): preserve context, surface, and buffer lifetimes 2026-11-29 03:49:44 +08:00
swung0x48 434407f1bc [Refactor] (MG_Backend/DirectGLES): move the packed upload gate out of SyncMipmapsToBackend 2026-11-26 07:25:11 -04:00
swung0x48 9538bdbdd3 [Merge] (DirectGLES uploads): take the sparse texture upload and draw-state work 2026-11-26 06:48:06 -04:00
Eurya0x13 86471dfb80 [Refactor] (MG_Impl/Pipe, MG_State/GLState): keep vertex-input memo hints in the emitter
- Use a bounded slot hint table keyed by array lifetime.
- Validate the lifetime and allocator epoch before reusing an entry.
2026-11-26 18:14:25 +08:00
Eurya0x13 6ad3d3f519 [Fix] (MG_Backend/DirectGLES): require raw RGBA8 for packed texture uploads
- Check the shadow format before copying bytes into the staging texture.
- Document the draw-batch scope of sampled-storage tracking.
2026-11-26 18:14:18 +08:00
swung0x48 40cb6bfcfc [Docs] (CONTRIBUTING.md): allow crediting an external project for a non-trivial technique 2026-11-26 05:13:54 -04:00
swung0x48 94d729c493 [Test] (MG_Test/Backend, MG_Test/Util): cover upload packing, box splits and sampled-storage tracking 2026-11-26 04:58:10 -04:00
swung0x48 926e54e28c [Refactor] (MG_Backend/DirectGLES, MG_Util/Texture): move the upload packing helpers to MG_Util 2026-11-26 04:56:56 -04:00
swung0x48 c025f9c4e8 [Fix, Perf] (MG_Backend/DirectGLES): fence packed copies and keep them off sampled storage
- Note committed packed copies as in-place uploads for the image barrier.
- Skip packed copies and split boxes for storage sampled in the batch.
- Keep the scatter rect list on the client-memory path while the ring is up.
- Take the packed path on every ES driver that has glCopyImageSubData.
2026-11-26 04:56:02 -04:00
Eurya0x13 99afafd7cf [Perf] (MG_Backend/DirectGLES): reuse the frame fence wait result
- Retire the already signaled slot without querying its status again.
- Keep polling the other slots to preserve the completion watermark.
2026-11-26 14:14:38 +08:00
Eurya0x13 b897556750 [Perf] (MG_Backend/DirectGLES, MG_Impl/Pipe, MG_State/GLState): reuse draw state
- Reuse the resolved shader record during draw preparation and copies.
- Read the tracked draw framebuffer when preparing a clear.
- Keep one memo slot hint per VAO and validate it by identity and epoch.
2026-11-26 14:13:37 +08:00
Eurya0x13 639ae0f636 [Fix] (MG_Backend/DirectGLES): avoid PBO updates to sampled offscreen textures
- Track sampled storage by native context and draw batch.
- Use the existing client upload for in-place edits to sampled storage.
2026-11-26 14:12:28 +08:00
Eurya0x13 10deb9cea4 [Perf] (MG_Backend/DirectGLES): batch sparse texture uploads on Mali
- Pack dirty rectangles across mip levels into a shared staging texture.
- Keep a bounded fallback when mapped unpack space is busy.
- https://bugzilla.mozilla.org/show_bug.cgi?id=1661528
- https://searchfox.org/firefox-main/source/gfx/wr/webrender/src/renderer/upload.rs#474
2026-11-26 14:10:37 +08:00
swung0x48 83a428d787 [Test] (MG_IntegrationTest/Harness): allow the multiview scissored clear skip 2026-11-24 08:27:47 -04:00
swung0x48 adb2f1b844 [Fix] (MG_IntegrationTest, scripts): register MultiviewScenario on the split arms and baseline its llvmpipe skip
The scenario's surfaces cross the wire (MGPSurface::NumViews), so its cases join the P8-A
ambient list instead of the exemption table; split_coverage.py no longer reports them as
monolith-only.

The skip census baseline gains DirectGLES[.Split|.Spawn|.Tcp|.Verify|.VerifySplit].MultiviewScenario.AScissoredClearAfterADrawReachesEveryView
in every lane that lists the matching ClipDistance skip: the case skips on Espryt over
llvmpipe, whose scissored clear on a multiview framebuffer corrupts the heap at context
destroy.
2026-11-24 08:09:37 -04:00
swung0x48 8c66941c88 [Feat] (...): advertise GL_OVR_multiview and GL_OVR_multiview2 on DirectVulkan
- A multiview attachment draws through a render pass with a view mask over one
  framebuffer layer, behind the device's multiview feature
- A pending clear of other layers of an attachment lands before its pass, not after
2026-11-24 02:30:53 -04:00
swung0x48 bf87d75d70 [Feat] (...): advertise GL_OVR_multiview and GL_OVR_multiview2 on DirectGLES
- Each string follows the driver's own extension; DirectVulkan advertises neither yet
- The attachment's view count crosses the wire in MGPSurface, and num_views reaches
  the ESSL after a capability strip, outside the translation memo
2026-11-24 01:37:51 -04:00
BZLZHH 2bdbe052c6 [Chore] (android-plugin/app, MobileGL, userguide): restore the development version [skip ci] 2026-11-21 12:10:05 +08:00
BZLZHH 9df3600f87 [Chore] (android-plugin/app, MobileGL, userguide): set the version to 26.11-alpha.1 2026-11-21 12:05:38 +08:00
BZLZHH 881dfd7203 [CI, Docs] (.github/workflows, CONTRIBUTING.md, scripts/ci): attach the signed plugin APK to releases 2026-11-21 11:53:25 +08:00
BZLZHH 951f3735cd [CI] (scripts/ci): rank unique release contributors by commit count 2026-11-21 11:35:02 +08:00
BZLZHH 6306b28af5 [CI, Docs] (.github/workflows, CONTRIBUTING.md, scripts/ci): validate and publish version tags 2026-11-21 10:31:27 +08:00
swung0x48 3a1058dbab [CI] (.github/workflows, CONTRIBUTING.md, scripts): compare new branches with the default branch 2026-11-16 02:46:57 -04:00
swung0x48 c9003c89a1 [Test] (MG_Test/Util): hold the drain tests' queue until StopAndDrain takes it 2026-11-16 02:46:56 -04:00
swung0x48 9ce8caa1d0 [Fix, CI] (.github/actions, .github/workflows, scripts/ci): stop creating the swap file over a zram or partition device 2026-11-16 02:46:55 -04:00
swung0x48 8d3d3d13a7 [CI, Tools] (android-plugin): log each shard case's settings, record and transport lines
- The monolith lane fails when the library log shows a split transport
2026-11-15 18:38:03 -04:00
swung0x48 d41563fb8d [CI, Tools] (.github/workflows, scripts/ci, tools/trace_replay): pack emulator shards by measured replay seconds
- Report free disk space around the swap, fixture and AVD steps
- Print the configure command line of the Linux builds
2026-11-15 16:48:24 -04:00
swung0x48 25c984927d [CI] (.github/workflows, docs/ci, scripts/ci): trim setup time in the build and split lane jobs 2026-11-15 11:47:46 -04:00
swung0x48 8165793e0d [CI, Tools] (...): replay only smoke cases on Android monolith and spawn
- Android inproc and all three Linux transports still replay every case
- A manual run with android_full_matrix replays the full emulator matrix
2026-11-15 11:47:38 -04:00
swung0x48 697bcc6d45 [CI, Tools] (...): replay trace cases in shards from one fixture cache 2026-11-15 11:47:18 -04:00
swung0x48 222f6209a0 [CI] (.github/actions, .github/workflows): create swap even when the runner image has none 2026-11-15 05:45:04 -04:00
swung0x48 b2248b240f [CI, Docs] (.github/workflows, userguide): build the dev APK split so it defaults to inproc 2026-11-14 22:07:43 -04:00
swung0x48 8db74d69ae [Chore] (android-plugin/app, MobileGL, userguide): bump the version to 26.11 2026-11-08 20:20:39 -04:00
swung0x48 04c8773d77 [Fix, Test] (MG_Impl/GLImpl, MG_Test/Texture, MG_Util/Converters): report proxy texture level sizes
- Record the size a proxy glTexImage* asks for and answer it from
  glGetTexLevelParameter, or zeros when it passes the texture size limits
- Map GL_PROXY_TEXTURE_1D and GL_PROXY_TEXTURE_3D to their upload targets
2026-11-08 19:43:21 -04:00
swung0x48 8497eee197 [CI] (.github/workflows): run dev in the split CI shape and pin the verify build to monolith 2026-11-07 08:08:50 -04:00
swung0x48 13e9d0df5c [Fix] (MG_Backend/DirectVulkan): take a deferred window clear's sRGB decision at the glClear 2026-11-07 08:08:48 -04:00
swung0x48 4256a66d09 [Fix] (MG_Impl/Pipe): zero the pixel pack record's padding before it is sent 2026-11-07 07:39:14 -04:00
swung0x48 cefb70d1a7 [Fix] (MG_Util/ShaderTranspiler, MG_Util/SelfTest, MG_Test): split clip distance code to fit the size and format checks 2026-11-07 07:27:58 -04:00
211 changed files with 14889 additions and 3494 deletions

No files matched your search

+15
View File
@@ -0,0 +1,15 @@
name: Set swap space
description: Replace the runner's swap with a swap file of the given size
inputs:
swap-size-gb:
description: Size of the swap file in GiB
required: true
runs:
using: composite
steps:
# scripts/ci/set_swap_space.sh says which swap it replaces, where the file goes and when it
# is sized down; it prints the swap state and free space before and after.
- shell: bash
env:
SWAP_SIZE_GB: ${{ inputs.swap-size-gb }}
run: bash "${GITHUB_ACTION_PATH}/../../../scripts/ci/set_swap_space.sh"
+304
View File
@@ -0,0 +1,304 @@
#!/usr/bin/env bash
# One cache entry that holds every Git LFS trace fixture of the CI cases.
#
# key derive the actions/cache key, restore prefix and path of the bundle
# ensure after a cache miss: complete the bundle directory, fetching only the
# cases whose files are missing from it or do not match their pointers
# wait <key> [secs] wait until the cache entry <key> is listed for this ref (needs GH_TOKEN)
# install <case>... move the fixtures of these cases from the restored bundle directory into
# the fixture directory, fetch the cases it does not hold, and check every
# file against its pointer
#
# The key is content-addressed on the pointer oids tracked at HEAD, which a plain checkout
# reads without smudging. The bundle directory is the same path for every revision, so
# `ensure` can start from an older bundle. Fixtures stored in Git itself rather than in Git
# LFS (OpenRA) are not in the bundle; `install` checks that they are real files.
set -euo pipefail
script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=trace-fixture-lib.sh
. "${script_dir}/trace-fixture-lib.sh"
# Bump when the key derivation or the bundle layout changes in a way that must invalidate
# old entries; the content digest alone would not notice a format change.
key_schema="v1"
bundle_dir="trace-fixture-bundle"
fixture_dir="tools/trace_replay/fixtures"
python_bin="${PYTHON:-python3}"
if ! command -v "${python_bin}" >/dev/null 2>&1 && command -v python >/dev/null 2>&1; then
python_bin=python
fi
usage() {
echo "usage: $0 <key|ensure|wait <key> [seconds]|install <trace-case>...>" >&2
exit 2
}
# Writes "name=value" to $GITHUB_OUTPUT when running under Actions, and to stdout as well so
# the script stays runnable off-CI.
emit_output() {
local name="$1"
local value="$2"
if [ -n "${GITHUB_OUTPUT:-}" ]; then
printf '%s=%s\n' "${name}" "${value}" >> "${GITHUB_OUTPUT}"
fi
printf '%s=%s\n' "${name}" "${value}"
}
# "<case><TAB><file>" for every fixture file of every CI case.
ci_fixture_manifest() {
"${python_bin}" tools/trace_replay/trace_cases.py --ci --format fixture-manifest \
--fixture-root "${fixture_dir}" | tr -d '\r'
}
is_lfs_fixture() {
get_lfs_metadata "$1" >/dev/null 2>&1
}
# A fixture that Git stores directly must be a real file, not a pointer left by a wrong
# attribute.
check_plain_fixture() {
local file="$1"
if [ ! -s "${file}" ]; then
echo "fixture file is missing or empty: ${file}" >&2
return 1
fi
if head -n 1 "${file}" | grep -q "version https://git-lfs.github.com/spec/v1"; then
echo "fixture should not be stored as an LFS pointer: ${file}" >&2
return 1
fi
}
# Puts the tracked pointer files back. The smudge filter is skipped so that a clone with Git
# LFS set up does not download the objects here.
restore_pointers() {
GIT_LFS_SKIP_SMUDGE=1 git checkout -- "$@"
}
verify_lfs_fixture() {
local on_disk="$1"
local tracked="$2"
local metadata expected_oid expected_size
metadata="$(get_lfs_metadata "${tracked}")" || return 1
read -r expected_oid expected_size <<< "${metadata}"
verify_fixture_file "${on_disk}" "${tracked}" "${expected_oid}" "${expected_size}"
}
# Moves the given Git LFS fixtures of one case from the bundle directory into the fixture
# directory. Succeeds when every one of them is then in place and matches its pointer.
take_from_bundle() {
local file bundled
local incomplete=0
for file in "$@"; do
bundled="${bundle_dir}/$(basename "${file}")"
# Two cases may share a file; the second finds it already in place.
if [ -f "${bundled}" ]; then
mv -f "${bundled}" "${file}"
fi
if ! verify_lfs_fixture "${file}" "${file}" 2>/dev/null; then
incomplete=1
fi
done
return "${incomplete}"
}
# Downloads the given Git LFS fixtures of one case over their pointers: the mirrors first,
# Git LFS for what no mirror serves. The fetch script verifies what it downloaded.
fetch_case_fixtures() {
local case_name="$1"
shift
local file
for file in "$@"; do
rm -f "${file}" "${file}.tmp"
done
restore_pointers "$@" || return 1
bash "${script_dir}/fetch-trace-fixture-lfs.sh" "${case_name}" "${fixture_dir}"
}
[ "$#" -ge 1 ] || usage
command_name="$1"
shift
case "${command_name}" in
key)
[ "$#" -eq 0 ] || usage
# One "<basename> <oid> <size>" line per bundled file, sorted, each file once.
manifest=""
count=0
while IFS= read -r file; do
[ -n "${file}" ] || continue
if ! metadata="$(get_lfs_metadata "${file}" 2>/dev/null)"; then
continue
fi
read -r expected_oid expected_size <<< "${metadata}"
manifest+="$(basename "${file}") ${expected_oid} ${expected_size}"$'\n'
count=$((count + 1))
done < <(ci_fixture_manifest | cut -f2 | LC_ALL=C sort -u)
if [ "${count}" -eq 0 ]; then
echo "no Git LFS fixture found for the CI trace cases; the bundle would be empty" >&2
exit 1
fi
duplicates="$(printf '%s' "${manifest}" | cut -d' ' -f1 | LC_ALL=C sort | uniq -d)"
if [ -n "${duplicates}" ]; then
echo "two fixture files share a name, so the bundle directory cannot hold both: ${duplicates}" >&2
exit 1
fi
digest="$(printf '%s' "${manifest}" | sha256sum | awk '{ print substr($1, 1, 16) }')"
emit_output "key" "trace-fixture-bundle-${key_schema}-${digest}"
emit_output "restore-prefix" "trace-fixture-bundle-${key_schema}-"
emit_output "path" "${bundle_dir}"
emit_output "files" "${count}"
;;
ensure)
[ "$#" -eq 0 ] || usage
mkdir -p "${bundle_dir}" "${fixture_dir}"
mapfile -t manifest_lines < <(ci_fixture_manifest)
declare -A case_seen=()
case_order=()
for line in "${manifest_lines[@]}"; do
case_name="${line%%$'\t'*}"
if [ -z "${case_seen[${case_name}]:-}" ]; then
case_seen["${case_name}"]=1
case_order+=("${case_name}")
fi
done
fetched=0
reused=0
bundled_files=()
for case_name in "${case_order[@]}"; do
lfs_files=()
for line in "${manifest_lines[@]}"; do
[ "${line%%$'\t'*}" = "${case_name}" ] || continue
file="${line#*$'\t'}"
if is_lfs_fixture "${file}"; then
lfs_files+=("${file}")
else
check_plain_fixture "${file}"
fi
done
[ "${#lfs_files[@]}" -gt 0 ] || continue
# Take what an older bundle already holds, and fetch the case if that is not all of it.
if take_from_bundle "${lfs_files[@]}"; then
reused=$((reused + 1))
else
echo "Fetching trace fixtures of ${case_name}: the bundle does not hold them"
fetch_case_fixtures "${case_name}" "${lfs_files[@]}"
fetched=$((fetched + 1))
fi
bundled_files+=("${lfs_files[@]}")
done
# The bundle is rebuilt from the verified files, so nothing an older bundle carried and
# no case names any more is saved again.
rm -rf "${bundle_dir}"
mkdir -p "${bundle_dir}"
declare -A file_seen=()
saved=0
for file in "${bundled_files[@]}"; do
[ -z "${file_seen[${file}]:-}" ] || continue
file_seen["${file}"]=1
verify_lfs_fixture "${file}" "${file}"
mv -f "${file}" "${bundle_dir}/$(basename "${file}")"
saved=$((saved + 1))
done
if [ "${saved}" -eq 0 ]; then
echo "the trace fixture bundle came out empty" >&2
exit 1
fi
# Leave the working tree as a checkout has it: pointers in the fixture directory.
restore_pointers "${!file_seen[@]}"
echo "Trace fixture bundle: ${saved} file(s), ${reused} case(s) from the restored bundle, ${fetched} case(s) fetched."
emit_output "fetched" "${fetched}"
;;
wait)
[ "$#" -ge 1 ] && [ "$#" -le 2 ] || usage
key="$1"
limit="${2:-300}"
# Another workflow of the same push may be the one saving this key. The replay jobs
# restore the entry, so it has to be listed before this job ends. The caller checks the
# entry itself afterwards; this only waits, and never fails.
#
# The listing is narrowed to the ref of this run. The key is content-addressed, so another
# branch may already hold an entry under it, and that entry cannot be restored from here:
# counting it would end the wait while the entry of this ref is still being uploaded.
query=(-f "key=${key}" -f per_page=100)
if [ -n "${GITHUB_REF:-}" ]; then
query+=(-f "ref=${GITHUB_REF}")
fi
waited=0
refused=0
while :; do
if listed="$(gh api -X GET "repos/${GITHUB_REPOSITORY}/actions/caches" "${query[@]}" \
--jq '[.actions_caches[] | select(.key == "'"${key}"'")] | length' 2>/dev/null)"; then
if [ "${listed:-0}" -ge 1 ]; then
echo "cache entry ${key} is listed after ${waited} s"
break
fi
else
refused=$((refused + 1))
if [ "${refused}" -ge 3 ]; then
echo "the cache listing cannot be read (no token, or no actions: read permission); not waiting"
break
fi
fi
if [ "${waited}" -ge "${limit}" ]; then
echo "cache entry ${key} is not listed after ${waited} s"
break
fi
sleep 10
waited=$((waited + 10))
done
;;
install)
[ "$#" -ge 1 ] || usage
installed=0
fetched=0
for case_name in "$@"; do
mapfile -t files < <(trace_fixture_files "${case_name}" "${fixture_dir}" "${python_bin}")
if [ "${#files[@]}" -eq 0 ]; then
echo "no fixture files declared for trace case: ${case_name}" >&2
exit 1
fi
lfs_files=()
for file in "${files[@]}"; do
if is_lfs_fixture "${file}"; then
lfs_files+=("${file}")
else
check_plain_fixture "${file}"
fi
done
[ "${#lfs_files[@]}" -gt 0 ] || continue
# A bundle that was not restored (the cache entry was evicted, or its download failed)
# or that lacks a file costs this job a download of the case, not the replay.
if ! take_from_bundle "${lfs_files[@]}"; then
echo "::warning::the restored fixture bundle does not hold the trace fixtures of ${case_name}; fetching them"
if ! fetch_case_fixtures "${case_name}" "${lfs_files[@]}"; then
echo "::error::the trace fixtures of ${case_name} are not in the restored bundle and could not be fetched"
exit 1
fi
fetched=$((fetched + 1))
for file in "${lfs_files[@]}"; do
if ! verify_lfs_fixture "${file}" "${file}"; then
echo "::error::trace fixture ${file} of ${case_name} does not match its Git LFS pointer after the fetch"
exit 1
fi
done
fi
installed=$((installed + ${#lfs_files[@]}))
done
# The rest of the bundle belongs to other shards.
rm -rf "${bundle_dir}"
echo "Installed and verified ${installed} Git LFS fixture file(s) for $# trace case(s), ${fetched} case(s) fetched."
;;
*)
usage
;;
esac
-117
View File
@@ -1,117 +0,0 @@
#!/usr/bin/env bash
# Cache-side helper for trace fixtures.
#
# key <case> [fixture-dir] derive the actions/cache key and path list
# verify <case> [fixture-dir] check restored fixtures against their pointers
# reset <case> [fixture-dir] drop restored fixtures, leaving the pointers
#
# The cache key is content-addressed on the Git LFS pointer oids tracked at
# HEAD, which are readable from a plain checkout without smudging. Fixture
# content therefore maps 1:1 onto a key: unchanged content hits, changed
# content is a new key and thus a miss, and the download path handles it. The
# key deliberately carries no restore-keys prefix in the workflow - a fixture
# that does not match the pointer exactly must never be restored.
set -euo pipefail
script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=trace-fixture-lib.sh
. "${script_dir}/trace-fixture-lib.sh"
# Bump when the key derivation changes in a way that must invalidate old
# entries; the content digest alone would not notice a format change.
key_schema="v1"
if [ "$#" -lt 2 ] || [ "$#" -gt 3 ]; then
echo "usage: $0 <key|verify|reset> <trace-case> [fixture-dir]" >&2
exit 2
fi
command_name="$1"
case_name="$2"
fixture_dir="${3:-tools/trace_replay/fixtures}"
python_bin="${PYTHON:-python3}"
if ! command -v "${python_bin}" >/dev/null 2>&1 && command -v python >/dev/null 2>&1; then
python_bin=python
fi
mapfile -t files < <(trace_fixture_files "${case_name}" "${fixture_dir}" "${python_bin}")
if [ "${#files[@]}" -eq 0 ]; then
echo "no fixture files declared for trace case: ${case_name}" >&2
exit 1
fi
# Writes "name=value" to $GITHUB_OUTPUT when running under Actions, and to
# stdout otherwise so the script stays runnable (and testable) off-CI.
emit_output() {
local name="$1"
local value="$2"
if [ -n "${GITHUB_OUTPUT:-}" ]; then
if [[ "${value}" == *$'\n'* ]]; then
local delimiter="ghadelim_$(date +%s%N)_$$"
{
printf '%s<<%s\n' "${name}" "${delimiter}"
printf '%s\n' "${value}"
printf '%s\n' "${delimiter}"
} >> "${GITHUB_OUTPUT}"
else
printf '%s=%s\n' "${name}" "${value}" >> "${GITHUB_OUTPUT}"
fi
fi
printf '%s=%s\n' "${name}" "${value}"
}
sanitize_case() {
printf '%s' "$1" | sed 's/[^A-Za-z0-9._-]/_/g'
}
case "${command_name}" in
key)
manifest=""
for file in "${files[@]}"; do
# A case whose fixtures are committed directly rather than through Git LFS
# (OpenRA) has no pointer oid to key on, and nothing to download either.
# Report it as uncacheable so the workflow skips the cache entirely.
if ! metadata="$(get_lfs_metadata "${file}" 2>/dev/null)"; then
echo "trace case ${case_name} is not stored in Git LFS; skipping fixture cache" >&2
emit_output "cacheable" "false"
emit_output "key" ""
exit 0
fi
read -r expected_oid expected_size <<< "${metadata}"
manifest+="$(basename "${file}") ${expected_oid} ${expected_size}"$'\n'
done
digest="$(printf '%s' "${manifest}" | sha256sum | awk '{ print substr($1, 1, 16) }')"
safe_case="$(sanitize_case "${case_name}")"
emit_output "cacheable" "true"
emit_output "key" "trace-fixture-${key_schema}-${safe_case}-${digest}"
emit_output "paths" "$(printf '%s\n' "${files[@]}")"
;;
verify)
for file in "${files[@]}"; do
metadata="$(get_lfs_metadata "${file}")"
read -r expected_oid expected_size <<< "${metadata}"
verify_fixture_file "${file}" "${file}" "${expected_oid}" "${expected_size}"
done
echo "Verified ${#files[@]} fixture file(s) for ${case_name} against the tracked Git LFS pointers."
;;
reset)
# Put the working tree back to the pointer files a fresh checkout would
# have, so that a rejected cache entry falls through to exactly the same
# download path a cache miss takes.
for file in "${files[@]}"; do
rm -f "${file}" "${file}.tmp"
done
git checkout -- "${files[@]}"
echo "Reset ${#files[@]} fixture file(s) for ${case_name} to their tracked Git LFS pointers."
;;
*)
echo "unknown command: ${command_name}" >&2
exit 2
;;
esac
+1 -1
View File
@@ -2,7 +2,7 @@
# Shared helpers for trace-fixture handling: reading the in-tree Git LFS pointer
# metadata and verifying a fixture file against it. Sourced by
# fetch-trace-fixture-lfs.sh (verify after download) and by
# trace-fixture-cache.sh (cache key derivation and verify after cache restore),
# trace-fixture-bundle.sh (cache key derivation and verify after cache restore),
# so both paths agree on what a valid fixture is.
# Reads the Git LFS pointer tracked at HEAD for a fixture path and prints
+343 -306
View File
@@ -1,4 +1,5 @@
name: MobileGL APK
run-name: ${{ (github.event_name == 'workflow_dispatch' && (github.ref_type == 'tag' || github.ref == 'refs/heads/main')) && format('Release validation ({0})', github.ref) || '' }}
on:
push:
@@ -12,16 +13,44 @@ on:
- feat/disaggregated
- codex/fix-github-ci
- cleanup
# A docs-only push builds nothing this workflow tests (231 emulator legs per run). The Test
# workflow keeps running for docs: it hosts the doc citation lint.
# A push that only touches these paths changes nothing this workflow builds or replays. The
# Test workflow keeps running for docs: it hosts the doc citation lint. The Android build
# compiles none of the unit, integration or benchmark trees, with one exception that keeps
# MobileGL/MG_Benchmark from being listed whole: MG_Util/SelfTest/DriverBenchJni.cpp
# includes MG_Benchmark/Driver/DriverBenchCases.inc.
paths-ignore:
- 'docs/**'
- '**/*.md'
- 'MobileGL/MG_Test/**'
- 'MobileGL/MG_IntegrationTest/**'
- 'MobileGL/MG_Benchmark/CMakeLists.txt'
- 'MobileGL/MG_Benchmark/SanityBench.cpp'
- 'MobileGL/MG_Benchmark/Buffer/**'
- 'MobileGL/MG_Benchmark/Container/**'
- 'MobileGL/MG_Benchmark/Program/**'
- 'MobileGL/MG_Benchmark/ShaderCache/**'
- 'MobileGL/MG_Benchmark/Transpile/**'
- 'tools/cts/**'
- 'tools/device_bench/**'
- '.github/workflows/test.yml'
- '.github/workflows/hygiene.yml'
- '.github/actions/setup-test-runner/**'
workflow_dispatch:
inputs:
android_full_matrix:
description: Replay every trace case on the monolith and spawn emulator lanes too
type: boolean
default: false
env:
# Software-rendered CI submissions may exceed the interactive GPU hang budget.
MOBILEGL_GPU_HANG_BUDGET_MS: "0"
# The emulator replays every trace case on inproc, the transport the launcher ships. On
# monolith and spawn it replays the android_smoke cases of trace_cases.json, because
# test.yml replays every case on all three transports on Linux. A manual run with
# android_full_matrix replays every case on all three emulator lanes. A push has no inputs,
# so it gets the reduced lanes.
MOBILEGL_ANDROID_LANES: ${{ inputs.android_full_matrix && 'full' || 'inproc-full' }}
# ONE LIVE RUN PER BRANCH, as in test.yml: a superseded push is canceled rather than left queued
# behind its successor; a manual dispatch gets a group of its own; dev queues rather than cancels.
@@ -39,16 +68,26 @@ jobs:
CCACHE_BASEDIR: ${{ github.workspace }}
CCACHE_COMPRESS: "true"
CCACHE_DIR: ${{ github.workspace }}/.ccache
CCACHE_MAXSIZE: 4G
# One build's objects (three native configurations) take about 1 GB. The limit leaves
# half of that again for the objects a push replaces, and is what the cleanup before
# the save trims the entry to.
CCACHE_MAXSIZE: 1500M
CCACHE_NOHASHDIR: "true"
MOBILEGL_CMAKE_COMPILER_LAUNCHER: ccache
MOBILEGL_CI_DISAGGREGATED: ${{ (github.ref_name == 'feat/disaggregated' || github.ref_name == 'codex/fix-github-ci' || github.ref_name == 'cleanup') && 'ON' || 'OFF' }}
MOBILEGL_CI_DISAGGREGATED: ${{ (github.ref_name == 'dev' || github.ref_name == 'feat/disaggregated' || github.ref_name == 'codex/fix-github-ci' || github.ref_name == 'cleanup' || (github.event_name == 'workflow_dispatch' && (github.ref_type == 'tag' || github.ref == 'refs/heads/main'))) && 'ON' || 'OFF' }}
steps:
- name: Checkout repo
uses: actions/checkout@v6
with:
submodules: recursive
# Only the submodules the two APKs are built from, shallow and in parallel, in place of a
# recursive checkout of every submodule in the tree: the ones the root CMakeLists.txt
# configures, and apitrace with the directories its thirdparty/CMakeLists.txt requires,
# for the trace APK. The step fails when a file the build reads from one of them did
# not arrive (scripts/ci/checkout_submodules.sh).
- name: Check out build submodules
timeout-minutes: 15
run: bash scripts/ci/checkout_submodules.sh retrace
- name: Set artifact metadata
run: |
@@ -82,6 +121,9 @@ jobs:
sudo apt-get -o Acquire::Retries=3 -o Acquire::http::Timeout=30 update
sudo apt-get -o Acquire::Retries=3 -o Acquire::http::Timeout=30 install -y ccache
ccache --version
# The restored entry carries the counters of every earlier build; zero them so the
# statistics printed after the build are this run's.
ccache --zero-stats
- name: Setup Android SDK
id: netsetup84
@@ -183,11 +225,20 @@ jobs:
if: always()
run: ccache --show-stats
# Rewrite one rolling entry per job and branch. The upload stays cumulative - it
# carries every object restored at the top of this run plus the few TUs that
# changed - but Actions cache keys are immutable, so this branch's superseded
# blob is released first; --ref keeps the delete off other branches' entries.
# Running after the build means a failed build leaves the entry untouched.
# A build served from the cache stores nothing, so nothing would ever evict the objects
# of older source states. Trim to CCACHE_MAXSIZE, least recently used first, before the
# entry is saved; the objects this build hit were just touched and stay.
- name: Trim ccache to its size limit
run: |
ccache --cleanup
ccache --show-stats | grep -i 'cache size' || true
du -sh "${CCACHE_DIR}"
# Rewrite one rolling entry per job and branch. The upload carries the objects this
# build used plus what fits under the size limit, but Actions cache keys are
# immutable, so this branch's superseded blob is released first; --ref keeps the
# delete off other branches' entries. Running after the build means a failed build
# leaves the entry untouched.
- name: Release superseded ccache entry
env:
GH_TOKEN: ${{ github.token }}
@@ -251,10 +302,18 @@ jobs:
name: trace case matrix
runs-on: ubuntu-26.04
env:
MOBILEGL_CI_DISAGGREGATED: ${{ (github.ref_name == 'feat/disaggregated' || github.ref_name == 'codex/fix-github-ci' || github.ref_name == 'cleanup') && 'ON' || 'OFF' }}
MOBILEGL_CI_DISAGGREGATED: ${{ (github.ref_name == 'dev' || github.ref_name == 'feat/disaggregated' || github.ref_name == 'codex/fix-github-ci' || github.ref_name == 'cleanup' || (github.event_name == 'workflow_dispatch' && (github.ref_type == 'tag' || github.ref == 'refs/heads/main'))) && 'ON' || 'OFF' }}
# How much replay one emulator job aims for, in seconds as the duration hints count them.
# A (lane, transport, backend) cell is cut into as many shards as that takes, and its
# cases are spread so the shards of a cell come out even (tools/trace_replay/trace_cases.py,
# shard_matrix). A smaller value gives more and shorter jobs, each of which pays the
# emulator boot again; every case is replayed once per cell whatever the value.
RETRACE_SHARD_SECONDS: "580"
# The most a shard runner may spend on its cases. A shard gets the time in which every
# one of its cases could run to the end of its own time budget, up to this cap.
RETRACE_SHARD_DEADLINE_CAP_SECONDS: "7200"
outputs:
android: ${{ steps.trace-cases.outputs.android }}
names: ${{ steps.trace-cases.outputs.names }}
steps:
- name: Checkout repo
uses: actions/checkout@v6
@@ -263,77 +322,109 @@ jobs:
id: trace-cases
run: |
python3 tools/trace_replay/trace_cases.py --self-test-transport-matrices
matrix_format=github-apk-matrix
# The retrace jobs replay shards: several cases of one (lane, transport, backend) cell
# per emulator boot. The self-test proves every shard matrix replays exactly the rows
# of the per-case matrix it is built from, and trace_cases.py refuses to print one
# that does not.
python3 tools/trace_replay/trace_cases.py --self-test-shard-matrices
matrix_format=github-apk-shard-matrix
if [ "${MOBILEGL_CI_DISAGGREGATED}" = "ON" ]; then
matrix_format=github-apk-transport-matrix
matrix_format=github-apk-transport-shard-matrix
fi
echo "android=$(python3 tools/trace_replay/trace_cases.py --ci --format "${matrix_format}")" >> "$GITHUB_OUTPUT"
echo "names=$(python3 tools/trace_replay/trace_cases.py --ci --format names)" >> "$GITHUB_OUTPUT"
android="$(python3 tools/trace_replay/trace_cases.py --ci --format "${matrix_format}" \
--shard-seconds "${RETRACE_SHARD_SECONDS}" --android-lanes "${MOBILEGL_ANDROID_LANES}")"
# An empty `include` is not an error to GitHub: it skips the retrace job with no red.
shards="$(printf '%s' "${android}" | python3 -c 'import json, sys; print(len(json.load(sys.stdin)["include"]))')"
if [ "${shards}" -lt 1 ]; then
echo "::error::the Android retrace matrix is empty, so the retrace job would be skipped with no red"
exit 1
fi
# The cases of a shard share one job, so a case that hangs spends time the cases after
# it need. retrace_shard_budget.py gives every shard its own deadline_seconds, the
# time in which each of its cases could run to the end of its time budget, capped so
# that a shard whose replays all hang cannot hold a runner for hours, and the
# timeout_minutes of its job. The retrace job reads both from the matrix.
android="$(printf '%s' "${android}" | python3 android-plugin/retrace_shard_budget.py \
--cap-seconds "${RETRACE_SHARD_DEADLINE_CAP_SECONDS}")"
echo "android=${android}" >> "$GITHUB_OUTPUT"
lanes=""
if [ "${matrix_format}" = "github-apk-transport-shard-matrix" ]; then
lanes=" (${MOBILEGL_ANDROID_LANES} lanes)"
fi
echo "Android retrace: ${shards} shard(s) from ${matrix_format}${lanes} at ${RETRACE_SHARD_SECONDS} s per shard"
# One cache entry holds every Git LFS fixture of the CI cases, and each retrace job restores
# that entry itself. This job only makes sure the entry exists. On a hit it downloads
# nothing. On a miss it starts from the newest older bundle, fetches from the mirror the
# cases whose pointers changed, saves the entry under the new key and confirms it is there,
# so that no retrace job has to download fixtures itself. The key, the path and the steps
# are .github/scripts/trace-fixture-bundle.sh's, and test.yml has the same job for the same
# entry: the two workflows of one push look the key up at the same time, and on a miss both
# fetch and both save. The save that loses is not an error, since the entry it wanted to
# write is the one the confirming step then finds. The timeout bounds a fixture download
# that stalls, which would otherwise hold every retrace job behind it.
trace-fixtures:
name: trace fixture (${{ matrix.case }})
name: trace fixtures
runs-on: ubuntu-26.04
needs: trace-cases
strategy:
fail-fast: false
max-parallel: 4
matrix:
case: ${{ fromJSON(needs.trace-cases.outputs.names) }}
timeout-minutes: 30
permissions:
actions: read
contents: read
outputs:
key: ${{ steps.bundle.outputs.key }}
path: ${{ steps.bundle.outputs.path }}
steps:
- name: Checkout repo
uses: actions/checkout@v6
- name: Derive trace fixture cache key
id: fixture-key
run: bash .github/scripts/trace-fixture-cache.sh key '${{ matrix.case }}'
- name: Derive the fixture bundle key
id: bundle
run: bash .github/scripts/trace-fixture-bundle.sh key
- name: Restore trace fixture cache
id: fixture-cache
if: steps.fixture-key.outputs.cacheable == 'true'
- name: Look up the fixture bundle
id: lookup
uses: actions/cache/restore@v5
with:
path: ${{ steps.fixture-key.outputs.paths }}
key: ${{ steps.fixture-key.outputs.key }}
path: ${{ steps.bundle.outputs.path }}
key: ${{ steps.bundle.outputs.key }}
lookup-only: true
- name: Verify restored trace fixture
id: fixture-verify
if: steps.fixture-cache.outputs.cache-hit == 'true'
run: |
if bash .github/scripts/trace-fixture-cache.sh verify '${{ matrix.case }}'; then
echo "ok=true" >> "$GITHUB_OUTPUT"
else
echo "ok=false" >> "$GITHUB_OUTPUT"
echo "::warning::Cached fixture for ${{ matrix.case }} failed verification; falling back to the download path"
bash .github/scripts/trace-fixture-cache.sh reset '${{ matrix.case }}'
fi
- name: Restore the newest older bundle
if: steps.lookup.outputs.cache-hit != 'true'
uses: actions/cache/restore@v5
with:
path: ${{ steps.bundle.outputs.path }}
key: ${{ steps.bundle.outputs.key }}
restore-keys: ${{ steps.bundle.outputs.restore-prefix }}
- name: Fetch trace fixture
if: steps.fixture-verify.outputs.ok != 'true'
run: bash .github/scripts/fetch-trace-fixture-lfs.sh '${{ matrix.case }}'
- name: Complete the fixture bundle
if: steps.lookup.outputs.cache-hit != 'true'
run: bash .github/scripts/trace-fixture-bundle.sh ensure
- name: Save trace fixture cache
if: steps.fixture-key.outputs.cacheable == 'true' && steps.fixture-cache.outputs.cache-hit != 'true'
- name: Save the fixture bundle
if: steps.lookup.outputs.cache-hit != 'true'
continue-on-error: true
uses: actions/cache/save@v5
with:
path: ${{ steps.fixture-key.outputs.paths }}
key: ${{ steps.fixture-key.outputs.key }}
path: ${{ steps.bundle.outputs.path }}
key: ${{ steps.bundle.outputs.key }}
- name: Stage trace fixture
run: |
safe_case="$(printf '%s' '${{ matrix.case }}' | sed 's/[^A-Za-z0-9._-]/_/g')"
stage_dir="trace-fixtures/${safe_case}"
mkdir -p "${stage_dir}"
python3 tools/trace_replay/trace_cases.py --format fixture-files --case '${{ matrix.case }}' |
while IFS= read -r file; do
cp "${file}" "${stage_dir}/"
done
# The Test workflow of the same push may be the one whose save won. Its entry is as good,
# once it is listed.
- name: Wait for the fixture bundle entry
if: steps.lookup.outputs.cache-hit != 'true'
env:
GH_TOKEN: ${{ github.token }}
run: bash .github/scripts/trace-fixture-bundle.sh wait '${{ steps.bundle.outputs.key }}'
- name: Upload trace fixture
uses: actions/upload-artifact@v7
- name: Confirm the fixture bundle entry
if: steps.lookup.outputs.cache-hit != 'true'
uses: actions/cache/restore@v5
with:
name: MobileGL-trace-fixture-${{ matrix.case }}
path: trace-fixtures/**
if-no-files-found: error
path: ${{ steps.bundle.outputs.path }}
key: ${{ steps.bundle.outputs.key }}
lookup-only: true
fail-on-cache-miss: true
android-avd:
name: android avd image
@@ -347,8 +438,33 @@ jobs:
- name: Checkout repo
uses: actions/checkout@v6
# The emulator shard loop and the artifact cleanup, driven by fakes: what each case is
# run with, a verdict for every case, and what stays after a failure. It runs in this
# job because the retrace jobs wait for it and the APK build does not.
- name: Emulator shard runner regression
run: |
python3 android-plugin/test_trace_replay_shard.py
python3 android-plugin/test_retrace_artifact_cleanup.py
# This job only makes sure the cache entry exists; the retrace jobs restore it. A hit
# downloads nothing and skips every step below; a miss builds the AVD, and the post step
# of this action saves it.
- name: Look up Android AVD cache
id: android-avd-cache
uses: actions/cache@v5
with:
lookup-only: true
path: |
${{ env.ANDROID_AVD_HOME }}
${{ env.ANDROID_SDK_ROOT }}/emulator
${{ env.ANDROID_SDK_ROOT }}/platform-tools
${{ env.ANDROID_SDK_ROOT }}/platforms/android-35
${{ env.ANDROID_SDK_ROOT }}/system-images/android-35/google_apis/x86_64
key: ${{ runner.os }}-mobilegl-avd-api35-google_apis-x86_64-pixel_6-v4-${{ hashFiles('android-plugin/run-avd-ci.sh') }}
- name: Setup Android SDK
id: netsetup336
if: steps.android-avd-cache.outputs.cache-hit != 'true'
continue-on-error: true
timeout-minutes: 15
uses: android-actions/setup-android@v4
@@ -367,20 +483,9 @@ jobs:
cmdline-tools-version: 13114758
- name: Accept Android SDK licenses
if: steps.android-avd-cache.outputs.cache-hit != 'true'
run: yes | sdkmanager --licenses >/dev/null
- name: Restore Android AVD cache
id: android-avd-cache
uses: actions/cache@v5
with:
path: |
${{ env.ANDROID_AVD_HOME }}
${{ env.ANDROID_SDK_ROOT }}/emulator
${{ env.ANDROID_SDK_ROOT }}/platform-tools
${{ env.ANDROID_SDK_ROOT }}/platforms/android-35
${{ env.ANDROID_SDK_ROOT }}/system-images/android-35/google_apis/x86_64
key: ${{ runner.os }}-mobilegl-avd-api35-google_apis-x86_64-pixel_6-v4-${{ hashFiles('android-plugin/run-avd-ci.sh') }}
- name: Create AVD
if: steps.android-avd-cache.outputs.cache-hit != 'true'
run: |
@@ -418,16 +523,27 @@ jobs:
fi
du -sh "${ANDROID_AVD_HOME}"
# One job replays a shard: some of the cases of one lane, transport and backend, one after
# another on one emulator boot (android-plugin/trace_replay_shard.py). The shard's step
# summary has a row per case, and a case that did not pass has an error annotation of its own.
retrace:
name: retrace (${{ matrix.backend.name }} / ${{ matrix.transport || 'monolith' }}, ${{ matrix.case.name }})
name: retrace (${{ matrix.backend.name }} / ${{ matrix.transport || 'monolith' }}, shard ${{ matrix.shard }}/${{ matrix.shards }})
runs-on: ubuntu-26.04
needs:
- build
- android-avd
- trace-cases
- trace-fixtures
if: ${{ !cancelled() && needs.build.result == 'success' && needs.android-avd.result == 'success' && needs.trace-cases.result == 'success' }}
timeout-minutes: 75
if: ${{ !cancelled() && needs.build.result == 'success' && needs.android-avd.result == 'success' && needs.trace-cases.result == 'success' && needs.trace-fixtures.result == 'success' }}
# Paired with --deadline-seconds below, and far above what a shard takes when its replays
# end by themselves. Both come from the matrix. The deadline is the smaller of the time in
# which every case of the shard could run to the end of its own time budget
# (trace_replay_shard.py, needed_seconds) and RETRACE_SHARD_DEADLINE_CAP_SECONDS. With
# budgets of up to 1800 s a case the cap is what a shard of several cases gets: about
# three replays can hang to the end of their budgets before a later case is recorded as
# not-run. The minutes between the deadline and this limit are the setup before the
# replays and the uploads after them.
timeout-minutes: ${{ matrix.timeout_minutes }}
env:
MOBILEGL_CI_TRANSPORT: ${{ matrix.transport || 'monolith' }}
MOBILEGL_CI_LANE: ${{ matrix.lane || 'monolith-control' }}
@@ -435,39 +551,60 @@ jobs:
ANDROID_AVD_HOME: ${{ github.workspace }}/.android/avd
ANDROID_HOME: ${{ github.workspace }}/.android/sdk
ANDROID_SDK_ROOT: ${{ github.workspace }}/.android/sdk
# The shard's cases in run order, as the JSON array of case objects the shard runner
# takes: every field of the case in trace_cases.json, with the fixture paths in place.
MOBILEGL_SHARD_CASES: ${{ toJSON(matrix.cases) }}
# Set the repository variable to 1 to cold boot the emulator before every case of a
# shard, should one boot not survive a whole shard of software-rendered replays.
MOBILEGL_SHARD_RESTART_EMULATOR_EACH_CASE: ${{ vars.MOBILEGL_SHARD_RESTART_EMULATOR_EACH_CASE || '0' }}
# The emulator renders on the host with a software rasterizer that can keep compiled
# shaders on disk in the runner's home directory, where neither clearing the app's data
# nor restarting the emulator reaches. Off, so every case of a shard compiles its
# shaders as a job with a fresh machine does.
MESA_SHADER_CACHE_DISABLE: "true"
strategy:
fail-fast: false
# The account runs at most 20 jobs at once, shared with Test. These ~230 emulator jobs are
# the longer of the two runs, so they may take the whole pool: what is minimized is when the
# later of APK and Test finishes, not Test alone.
max-parallel: 20
# No max-parallel: the account's limit of 20 concurrent jobs, shared with Test, already
# bounds this matrix, and a cap below the number of shards only makes the round longer.
matrix: ${{ fromJSON(needs.trace-cases.outputs.android) }}
steps:
- name: Set swap space
uses: pierotofy/set-swap-space@v1.0
with:
swap-size-gb: 8
- name: Checkout repo
uses: actions/checkout@v6
- name: Download trace fixture
uses: actions/download-artifact@v8
with:
name: MobileGL-trace-fixture-${{ matrix.case.name }}
path: trace-fixture-download
- name: Install trace fixture
run: |
mkdir -p tools/trace_replay/fixtures
find trace-fixture-download -type f -exec cp {} tools/trace_replay/fixtures/ \;
# First, so the steps that run whatever happened (diagnostics, stopping the emulator, the
# result upload) have these even when a step before the emulator launch failed.
- name: Set artifact metadata
run: |
echo "date_today=$(date +'%Y-%m-%d')" >> "$GITHUB_ENV"
echo "EMULATOR_LOG=${RUNNER_TEMP}/mobilegl-emulator.log" >> "$GITHUB_ENV"
echo "EMULATOR_PID_FILE=${RUNNER_TEMP}/mobilegl-emulator.pid" >> "$GITHUB_ENV"
# The swap file, the fixture bundle and the AVD image share the runner's disk, and a
# runner that starts short of space fails the whole shard. The two reports say how much
# was free before and after them.
- name: Report free disk space
run: df -h / "${GITHUB_WORKSPACE}"
- name: Set swap space
uses: ./.github/actions/set-swap-space
with:
swap-size-gb: 8
# A miss does not fail the job: the entry may have been evicted since trace-fixtures
# confirmed it (a re-run of failed jobs on an older run does not run that job again).
- name: Restore trace fixtures
uses: actions/cache/restore@v5
with:
path: ${{ needs.trace-fixtures.outputs.path }}
key: ${{ needs.trace-fixtures.outputs.key }}
# Moves this shard's fixtures into place and checks them against their Git LFS pointers.
# A case the restored bundle does not hold is downloaded here, with a warning annotation;
# the timeout bounds a download that stalls.
- name: Install trace fixtures
timeout-minutes: 15
run: bash .github/scripts/trace-fixture-bundle.sh install ${{ join(matrix.names, ' ') }}
- name: Restore Android AVD cache
id: android-avd-cache
uses: actions/cache/restore@v5
@@ -480,6 +617,9 @@ jobs:
${{ env.ANDROID_SDK_ROOT }}/system-images/android-35/google_apis/x86_64
key: ${{ runner.os }}-mobilegl-avd-api35-google_apis-x86_64-pixel_6-v4-${{ hashFiles('android-plugin/run-avd-ci.sh') }}
- name: Report free disk space after the restores
run: df -h / "${GITHUB_WORKSPACE}"
# The cache holds everything a retrace job runs (emulator, adb, image, AVD); the SDK manager
# is only needed to create the AVD when the cache missed.
- name: Use the cached SDK tools
@@ -543,135 +683,44 @@ jobs:
--pid-file "${EMULATOR_PID_FILE}" \
--boot-timeout 300
# One emulator boot replays every case of the shard in order, each in a fresh app process
# with cleared app data and with the settings its case, backend and transport need. The
# runner keeps going after a failing case, on a cold boot so that case cannot touch the
# next one's verdict, retries a case once on a restarted emulator when the emulator
# itself failed, and exits non-zero when a case failed or a verdict is missing. The
# deadline stops it while the steps below can still upload what it has: the job timeout
# less the setup above and the uploads below. A case it stops or never starts is
# recorded as not-run, which is red.
- name: Retrace and validate
env:
MOBILEGL_ESPRYT_USE_ANGLE: ${{ matrix.backend.name == 'DirectGLES' && '1' || '0' }}
MOBILEGL_TRACE_ANGLE_VARIANT: ${{ matrix.case.name == 'minecraft-1.21.4-fabric-iris-bliss-in-world' && '90a62123d794' || 'ec889e6ea831' }}
MOBILEGL_MAGMA_R11G11B10F_FALLBACK: ${{ matrix.backend.name == 'DirectVulkan' && '1' || '0' }}
MOBILEGL_ITRP_FIX: ${{ matrix.case.name == 'minecraft-1.21.4-fabric-iris-iterationrp-in-world' && 'ForceOn' || 'Auto' }}
# Lets the artifact cleanup tell which job a shard's verdicts came from.
MOBILEGL_SHARD_JOB_ID: ${{ job.check_run_id }}
run: |
apk_file="android-retrace-apks/MobileGL-plugin-trace-release-${GITHUB_SHA}.apk"
test -f "${apk_file}"
extra_retrace_args=()
if [ "${MOBILEGL_CI_TRANSPORT}" = "inproc" ]; then
extra_retrace_args+=(
--env "MOBILEGL_TRANSPORT=inproc;MOBILEGL_IPC_ROLE_SPLIT_STATE=1;MOBILEGL_IPC_STRICT_ERRORS=1;MOBILEGL_IPC_RUN_AHEAD=1;MOBILEGL_GPU_HANG_BUDGET_MS=${MOBILEGL_GPU_HANG_BUDGET_MS}"
--require-inproc
)
elif [ "${MOBILEGL_CI_TRANSPORT}" = "spawn" ]; then
# THE SAME CLIENT KNOBS AS inproc, so the two acceptance lanes differ in exactly one
# thing: which PROCESS the server role runs in. They are scrubbed out of the CHILD's
# environment by the launcher and read by the client, which is where they belong.
#
# MOBILEGL_IPC_SERVER_PATH IS DELIBERATELY ABSENT. nativeLibraryDir carries an
# install-time hash, so nothing off the device can spell it; TraceReplayActivity
# resolves it from getApplicationInfo() when the env asks for spawn, and an explicit
# value would override that. --use-pbuffer is NOT optional here: a spawned
# server cannot be handed the client's window, because an ANativeWindow* is a pointer
# into the CLIENT's process and SetWindowHandle is refused on the way across with
# Fatal{UnmigratedSurface, "AndroidNativeWindow:use-MOBILEGL_IPC_SURFACE=server"} (Rule H, permanent;
# a windowed client uses MOBILEGL_IPC_SURFACE=server instead).
extra_retrace_args+=(
--env "MOBILEGL_TRANSPORT=spawn;MOBILEGL_IPC_ROLE_SPLIT_STATE=1;MOBILEGL_IPC_STRICT_ERRORS=1;MOBILEGL_IPC_RUN_AHEAD=1;MOBILEGL_GPU_HANG_BUDGET_MS=${MOBILEGL_GPU_HANG_BUDGET_MS}"
--use-pbuffer
--require-spawn
)
else
extra_retrace_args+=(--env "MOBILEGL_TRANSPORT=monolith;MOBILEGL_GPU_HANG_BUDGET_MS=${MOBILEGL_GPU_HANG_BUDGET_MS}")
fi
# Bliss needs the newer signed ANGLE variant plus sampler mipmap
# min-filter downgrading on ANGLE llvmpipe.
if [ "${{ matrix.backend.name }}" = "DirectGLES" ] && [ "${{ matrix.case.name }}" = "minecraft-1.21.4-fabric-iris-bliss-in-world" ]; then
extra_retrace_args+=(--avoid-angle-llvmpipe-sampler-mipmap-min-filter)
fi
if [ "${{ matrix.backend.name }}" = "DirectGLES" ] && [ "${{ matrix.case.avoid_angle_llvmpipe_explicit_lod_bias || false }}" = "true" ]; then
extra_retrace_args+=(--avoid-angle-llvmpipe-explicit-lod-bias)
fi
if [ "${{ matrix.case.coherent_as_flush || false }}" = "true" ]; then
extra_retrace_args+=(--coherent-as-flush)
fi
run_retrace() {
timeout "$(( ${{ matrix.case.timeout_seconds }} + 300 ))" sh android-plugin/trace-replay-ci.sh \
--apk-file "${apk_file}" \
--package top.mobilegl.plugin.trace \
--backend "${{ matrix.backend.name }}" \
--result-root android-retrace-result \
--fixture-root android-retrace-fixture \
--case "${{ matrix.case.name }}" \
--trace-archive "${{ matrix.case.trace_archive }}" \
--trace-file "${{ matrix.case.trace_file }}" \
--golden "${{ matrix.case.golden }}" \
--alternate-golden "${{ matrix.case.alternate_golden || '' }}" \
--target-call "${{ matrix.case.target_call }}" \
--width "${{ matrix.case.width }}" \
--height "${{ matrix.case.height }}" \
--ssim-threshold "${{ matrix.case.ssim_threshold || '0.99' }}" \
--crop-x "${{ matrix.case.crop_x }}" \
--crop-y "${{ matrix.case.crop_y }}" \
--crop-width "${{ matrix.case.crop_width }}" \
--crop-height "${{ matrix.case.crop_height }}" \
--timeout-seconds "${{ matrix.case.timeout_seconds }}" \
"${extra_retrace_args[@]}"
}
retrace_status=0
run_retrace || retrace_status=$?
if [ "${retrace_status}" -eq 75 ]; then
echo "::warning::Android emulator infrastructure failed; restarting it and retrying this retrace once."
# Surface-lost is retried rather than failed, so it would otherwise
# be invisible. Report it per job - a healthy run prints nothing and
# a rate spike shows up as a row per affected case.
reason_file="android-retrace-result/infrastructure-failure-reason.txt"
surface_lost_retries=0
if [ -f "${reason_file}" ]; then
surface_lost_retries="$(grep -c 'angle-surface-lost' "${reason_file}" || true)"
fi
if [ "${surface_lost_retries}" -gt 0 ]; then
echo "surface-lost retries: ${surface_lost_retries} (${{ matrix.backend.name }}, ${{ matrix.case.name }})" \
>> "${GITHUB_STEP_SUMMARY}"
fi
# The restart truncates EMULATOR_LOG, and the attempt that lost the
# emulator is the one worth reading - the retry usually only shows
# the wreckage. Keep the first attempt's log before it is clobbered.
if [ -f "${EMULATOR_LOG}" ]; then
cp "${EMULATOR_LOG}" "${EMULATOR_LOG}.first-attempt" || true
fi
sh android-plugin/run-avd-ci.sh stop \
--avd-name "${AVD_NAME}" \
--emulator-log "${EMULATOR_LOG}" \
--pid-file "${EMULATOR_PID_FILE}"
adb kill-server || true
sleep 2
sh android-plugin/run-avd-ci.sh start \
--avd-name "${AVD_NAME}" \
--gpu "${{ matrix.backend.gpu }}" \
--emulator-log "${EMULATOR_LOG}" \
--pid-file "${EMULATOR_PID_FILE}" \
--boot-timeout 300
run_retrace
elif [ "${retrace_status}" -ne 0 ]; then
exit "${retrace_status}"
fi
sh android-plugin/trace-replay-shard.sh \
--apk-file "android-retrace-apks/MobileGL-plugin-trace-release-${GITHUB_SHA}.apk" \
--backend "${{ matrix.backend.name }}" \
--gpu "${{ matrix.backend.gpu }}" \
--transport "${MOBILEGL_CI_TRANSPORT}" \
--lane "${MOBILEGL_CI_LANE}" \
--cases-env MOBILEGL_SHARD_CASES \
--deadline-seconds "${{ matrix.deadline_seconds }}"
# Runs whatever happened above, without the device: every case of the shard gets its
# lane.json and golden copies for the summary, and a not-run verdict when the runner was
# killed or never started.
- name: Collect retrace summary inputs
if: always()
env:
MOBILEGL_SHARD_JOB_ID: ${{ job.check_run_id }}
run: |
safe_case="$(printf '%s' '${{ matrix.case.name }}' | sed 's/[^A-Za-z0-9._-]/_/g')"
result_dir="android-retrace-result/${safe_case}-${{ matrix.backend.name }}"
mkdir -p "${result_dir}"
python3 - "${result_dir}/lane.json" <<'PY'
import json, os, sys
from pathlib import Path
Path(sys.argv[1]).write_text(json.dumps({"lane": os.environ["MOBILEGL_CI_LANE"],
"transport": os.environ["MOBILEGL_CI_TRANSPORT"]}, indent=2))
PY
if [ -s "${{ matrix.case.golden }}" ]; then
cp "${{ matrix.case.golden }}" "${result_dir}/${safe_case}-${{ matrix.backend.name }}-golden.png"
fi
if [ -n "${{ matrix.case.alternate_golden || '' }}" ] && [ -s "${{ matrix.case.alternate_golden || '' }}" ]; then
cp "${{ matrix.case.alternate_golden || '' }}" "${result_dir}/${safe_case}-${{ matrix.backend.name }}-alternate-golden.png"
fi
sh android-plugin/trace-replay-shard.sh \
--apk-file "android-retrace-apks/MobileGL-plugin-trace-release-${GITHUB_SHA}.apk" \
--backend "${{ matrix.backend.name }}" \
--gpu "${{ matrix.backend.gpu }}" \
--transport "${MOBILEGL_CI_TRANSPORT}" \
--lane "${MOBILEGL_CI_LANE}" \
--cases-env MOBILEGL_SHARD_CASES \
--finalize
- name: Collect emulator diagnostics
if: always()
@@ -679,12 +728,18 @@ jobs:
mkdir -p android-retrace-result/diagnostics
adb devices -l > android-retrace-result/diagnostics/adb-devices.txt || true
timeout 30 adb logcat -d -t 1000 > android-retrace-result/diagnostics/logcat.txt || true
# What the guest was given; replay time inside the emulator depends on it.
timeout 30 adb shell 'nproc; grep -E "MemTotal|SwapTotal" /proc/meminfo' \
> android-retrace-result/diagnostics/guest-resources.txt 2>&1 || true
cp "${ANDROID_AVD_HOME}/${AVD_NAME}.avd/config.ini" android-retrace-result/diagnostics/avd-config.ini 2>/dev/null || true
# Expected to list nothing: the host rasterizer's on-disk shader cache is disabled.
du -sh "${XDG_CACHE_HOME:-${HOME}/.cache}"/mesa_shader_cache* \
> android-retrace-result/diagnostics/host-shader-cache.txt 2>&1 || true
# The log of the last boot. The shard runner keeps the log of every boot it ended
# as diagnostics/emulator-boot-<n>-*.log before a restart truncates it.
if [ -f "${EMULATOR_LOG}" ]; then
cp "${EMULATOR_LOG}" android-retrace-result/diagnostics/emulator.log
fi
if [ -f "${EMULATOR_LOG}.first-attempt" ]; then
cp "${EMULATOR_LOG}.first-attempt" android-retrace-result/diagnostics/emulator-first-attempt.log
fi
# A vanished emulator looks identical whether the host OOM killer took
# qemu or the renderer faulted. These two say which.
free -h > android-retrace-result/diagnostics/host-memory.txt 2>&1 || true
@@ -704,9 +759,14 @@ jobs:
continue-on-error: true
uses: actions/upload-artifact@v7
with:
name: MobileGL-android-retrace-result-${{ matrix.lane || 'monolith-control' }}-${{ matrix.transport || 'monolith' }}-${{ env.date_today }}-${{ github.sha }}-${{ matrix.backend.name }}-${{ matrix.case.name }}
# The summary job downloads by the lane and transport at the front of this name, and
# its renderer reads the backend and the case from the paths below it, so the name
# ends in the shard number and holds no case name.
name: MobileGL-android-retrace-result-${{ matrix.lane || 'monolith-control' }}-${{ matrix.transport || 'monolith' }}-${{ env.date_today }}-${{ github.sha }}-${{ matrix.backend.name }}-shard${{ matrix.shard }}
path: android-retrace-result/**
if-no-files-found: warn
# A re-run of a failed job replaces the artifact its first attempt kept.
overwrite: true
# The artifact service sometimes times out (ETIMEDOUT on CreateArtifact, one job in 231 on
# 2026-10-18), which turned a passing case red; one delayed retry absorbs that.
@@ -718,7 +778,7 @@ jobs:
if: always() && steps.upload-retrace-result.outcome == 'failure'
uses: actions/upload-artifact@v7
with:
name: MobileGL-android-retrace-result-${{ matrix.lane || 'monolith-control' }}-${{ matrix.transport || 'monolith' }}-${{ env.date_today }}-${{ github.sha }}-${{ matrix.backend.name }}-${{ matrix.case.name }}
name: MobileGL-android-retrace-result-${{ matrix.lane || 'monolith-control' }}-${{ matrix.transport || 'monolith' }}-${{ env.date_today }}-${{ github.sha }}-${{ matrix.backend.name }}-shard${{ matrix.shard }}
path: android-retrace-result/**
if-no-files-found: warn
overwrite: true
@@ -727,46 +787,67 @@ jobs:
name: retrace summary
runs-on: ubuntu-26.04
needs: retrace
if: ${{ !cancelled() }}
# Also runs for a canceled run, where it only downloads the results and deletes the
# intermediate artifacts; the rendering steps are skipped then. The checkout and the
# downloads say so themselves, because a step with no condition is skipped once its job is
# canceled.
if: always()
permissions:
actions: write
contents: read
env:
MOBILEGL_CI_DISAGGREGATED: ${{ (github.ref_name == 'feat/disaggregated' || github.ref_name == 'codex/fix-github-ci' || github.ref_name == 'cleanup') && 'ON' || 'OFF' }}
MOBILEGL_CI_DISAGGREGATED: ${{ (github.ref_name == 'dev' || github.ref_name == 'feat/disaggregated' || github.ref_name == 'codex/fix-github-ci' || github.ref_name == 'cleanup' || (github.event_name == 'workflow_dispatch' && (github.ref_type == 'tag' || github.ref == 'refs/heads/main'))) && 'ON' || 'OFF' }}
steps:
- name: Checkout repo
if: ${{ success() || cancelled() }}
uses: actions/checkout@v6
- name: Set artifact metadata
run: |
echo "date_today=$(date +'%Y-%m-%d')" >> "$GITHUB_ENV"
- name: Set up Node.js
if: ${{ !cancelled() }}
uses: actions/setup-node@v7
with:
node-version: '22'
- name: Download Android monolith control results
if: ${{ success() || cancelled() }}
uses: actions/download-artifact@v8
with:
pattern: MobileGL-android-retrace-result-monolith-control-monolith-*
path: retrace-artifacts/monolith-control
- name: Download Android inproc acceptance results
if: env.MOBILEGL_CI_DISAGGREGATED == 'ON'
if: ${{ (success() || cancelled()) && env.MOBILEGL_CI_DISAGGREGATED == 'ON' }}
uses: actions/download-artifact@v8
with:
pattern: MobileGL-android-retrace-result-inproc-acceptance-inproc-*
path: retrace-artifacts/inproc-acceptance
- name: Download Android spawn acceptance results
if: env.MOBILEGL_CI_DISAGGREGATED == 'ON'
if: ${{ (success() || cancelled()) && env.MOBILEGL_CI_DISAGGREGATED == 'ON' }}
uses: actions/download-artifact@v8
with:
pattern: MobileGL-android-retrace-result-spawn-acceptance-spawn-*
path: retrace-artifacts/spawn-acceptance
# The reduced monolith and spawn lanes replay the android_smoke cases only, so their
# summaries list those cases and no others. A branch outside the split shape replays
# every case on monolith, its only lane.
- name: Select the cases of the reduced lanes
if: ${{ !cancelled() }}
run: |
reduced_lane_cases=""
if [ "${MOBILEGL_CI_DISAGGREGATED}" = "ON" ] && [ "${MOBILEGL_ANDROID_LANES}" = "inproc-full" ]; then
reduced_lane_cases="$(python3 tools/trace_replay/trace_cases.py --format android-smoke-names)"
test -n "${reduced_lane_cases}"
fi
echo "REDUCED_LANE_CASES=${reduced_lane_cases}" >> "$GITHUB_ENV"
- name: Render monolith control summary
if: ${{ !cancelled() }}
run: |
node tools/trace_replay/render_retrace_summary.mjs \
--cases "${REDUCED_LANE_CASES}" \
--input retrace-artifacts/monolith-control \
--output-dir android-retrace-summary/monolith-control \
--title "MobileGL Android monolith control" \
@@ -774,7 +855,7 @@ jobs:
--html mobilegl-android-monolith-control.html
- name: Render inproc acceptance summary
if: env.MOBILEGL_CI_DISAGGREGATED == 'ON'
if: ${{ !cancelled() && env.MOBILEGL_CI_DISAGGREGATED == 'ON' }}
run: |
node tools/trace_replay/render_retrace_summary.mjs \
--input retrace-artifacts/inproc-acceptance \
@@ -784,11 +865,18 @@ jobs:
--html mobilegl-android-inproc-acceptance.html
- name: Render spawn acceptance summary
if: env.MOBILEGL_CI_DISAGGREGATED == 'ON'
if: ${{ !cancelled() && env.MOBILEGL_CI_DISAGGREGATED == 'ON' }}
run: |
node tools/trace_replay/render_retrace_summary.mjs --input retrace-artifacts/spawn-acceptance --output-dir android-retrace-summary/spawn-acceptance --title "MobileGL Android spawn acceptance" --group-label "Android Emulator / spawn acceptance" --html mobilegl-android-spawn-acceptance.html
node tools/trace_replay/render_retrace_summary.mjs \
--cases "${REDUCED_LANE_CASES}" \
--input retrace-artifacts/spawn-acceptance \
--output-dir android-retrace-summary/spawn-acceptance \
--title "MobileGL Android spawn acceptance" \
--group-label "Android Emulator / spawn acceptance" \
--html mobilegl-android-spawn-acceptance.html
- name: Upload Android monolith control summary
if: ${{ !cancelled() }}
uses: actions/upload-artifact@v7
with:
name: MobileGL-android-monolith-control-summary-${{ github.sha }}
@@ -797,7 +885,7 @@ jobs:
if-no-files-found: error
- name: Upload Android inproc acceptance summary
if: env.MOBILEGL_CI_DISAGGREGATED == 'ON'
if: ${{ !cancelled() && env.MOBILEGL_CI_DISAGGREGATED == 'ON' }}
uses: actions/upload-artifact@v7
with:
name: MobileGL-android-inproc-acceptance-summary-${{ github.sha }}
@@ -806,7 +894,7 @@ jobs:
if-no-files-found: error
- name: Upload Android spawn acceptance summary
if: env.MOBILEGL_CI_DISAGGREGATED == 'ON'
if: ${{ !cancelled() && env.MOBILEGL_CI_DISAGGREGATED == 'ON' }}
uses: actions/upload-artifact@v7
with:
name: MobileGL-android-spawn-acceptance-summary-${{ github.sha }}
@@ -814,74 +902,23 @@ jobs:
archive: false
if-no-files-found: error
remove-artifact-clutter:
name: remove artifact clutter
runs-on: ubuntu-26.04
needs: retrace-summary
if: always()
permissions:
actions: write
steps:
# The summaries embed every image they show, so the per-shard results are intermediates
# from here on. This is the last step of the workflow rather than a job of its own, which
# would wait for a runner and start from an empty machine. It keeps what a failure needs,
# read from the shard-status.json of the results downloaded above: the results of every
# shard that ran a case which did not pass somewhere, on all backends and transports, and
# every result when a job failed without saying which cases it ran. Deletes are paced
# below GitHub's limit for mutating requests, and a refused delete is a warning. Skipped
# when a summary step failed, so that re-running this job still finds the results, and
# when a retrace job did not succeed in a run that was not canceled: every result stays
# then, so a shard stopped by its job limit keeps its diagnostics and a re-run of the
# failed jobs renders complete summaries.
- name: Delete intermediate Android retrace artifacts
if: ${{ (success() && needs.retrace.result == 'success') || cancelled() }}
env:
GH_TOKEN: ${{ github.token }}
run: |
# Fail before deletion if either paginated inventory cannot be read.
# 50 rows per page: the jobs endpoint answers HTTP 502 for 90+ rows on a re-run attempt of a run this size.
gh api --paginate "repos/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}/jobs?per_page=50" \
--jq '.jobs[] | select(.name | startswith("retrace (")) | select(.conclusion == "failure" or .conclusion == "canceled" or .conclusion == "timed_out" or .conclusion == "action_required") | .name' \
> "${RUNNER_TEMP}/cleanup-jobs.txt"
gh api --paginate "repos/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}/artifacts?per_page=100" \
--jq '.artifacts[] | select(.name | startswith("MobileGL-trace-fixture-") or startswith("MobileGL-android-retrace-result-") or startswith("trace-fixture-") or startswith("retrace-result-")) | [.id, .name] | @tsv' \
> "${RUNNER_TEMP}/cleanup-artifacts.txt"
declare -A failed_cases=()
while IFS= read -r job_name; do
case_name="${job_name#retrace (*, }"
case_name="${case_name%)}"
failed_cases["${case_name}"]=1
done < "${RUNNER_TEMP}/cleanup-jobs.txt"
if ((${#failed_cases[@]})); then
echo "Retaining fixtures and results for failed retrace case(s):"
printf ' %s\n' "${!failed_cases[@]}"
else
echo "All retrace jobs succeeded; nothing needs to be retained."
fi
deleted=0
retained=0
while IFS=$'\t' read -r artifact_id artifact_name; do
keep=0
if [[ "${artifact_name}" == MobileGL-trace-fixture-* ]]; then
case_name="${artifact_name#MobileGL-trace-fixture-}"
if [[ -v "failed_cases[${case_name}]" ]]; then
keep=1
fi
elif [[ "${artifact_name}" == MobileGL-android-retrace-result-* ]]; then
# The result artifact carries mobilegl.log, retrace.log, logcat,
# the emulator log and the actual/diff images - the only record of
# why a retrace failed. Its name ends in -<backend>-<case>, so a
# suffix match on the case name keeps both backends' results for a
# case that failed on either of them, which is what a comparison
# needs. The match is anchored at the end, so a case name that is a
# prefix of a longer one does not retain the longer one's results.
for case_name in "${!failed_cases[@]}"; do
if [[ "${artifact_name}" == *-"${case_name}" ]]; then
keep=1
break
fi
done
fi
if ((keep)); then
echo "Retaining ${artifact_name} (${artifact_id}) for failed retrace."
((retained += 1))
continue
fi
echo "Deleting ${artifact_name} (${artifact_id})"
gh api --method DELETE "repos/${GITHUB_REPOSITORY}/actions/artifacts/${artifact_id}"
((deleted += 1))
done < "${RUNNER_TEMP}/cleanup-artifacts.txt"
echo "Deleted ${deleted} intermediate Android artifact(s); retained ${retained} failed-retrace fixture(s)."
python3 android-plugin/retrace_artifact_cleanup.py \
--downloads retrace-artifacts/monolith-control \
--downloads retrace-artifacts/inproc-acceptance \
--downloads retrace-artifacts/spawn-acceptance
+2 -1
View File
@@ -18,7 +18,8 @@ jobs:
runs-on: ubuntu-26.04
timeout-minutes: 15
env:
TEXT_HYGIENE_BASE_BRANCH: feat/disaggregated
# A new branch is checked for the commits it adds to the development branch.
TEXT_HYGIENE_BASE_BRANCH: dev
steps:
- name: Checkout repo
uses: actions/checkout@v6
+68
View File
@@ -0,0 +1,68 @@
name: Release
on:
push:
branches: [main]
tags: ['v*']
workflow_dispatch:
permissions: {}
concurrency:
group: release-${{ github.ref }}
cancel-in-progress: false
jobs:
validate:
if: ${{ github.event_name == 'push' && github.ref_type == 'tag' }}
runs-on: ubuntu-26.04
timeout-minutes: 345
permissions:
actions: write
contents: read
outputs:
apk_run_id: ${{ steps.validate.outputs.apk_run_id }}
steps:
- uses: actions/checkout@v6
with:
fetch-depth: 0
persist-credentials: false
- name: Require both workflows
id: validate
env:
GH_TOKEN: ${{ github.token }}
run: python3 scripts/ci/release.py validate
publish:
needs: validate
runs-on: ubuntu-26.04
timeout-minutes: 10
permissions:
actions: read
contents: write
steps:
- uses: actions/checkout@v6
with:
fetch-depth: 0
persist-credentials: false
- name: Publish release with plugin APK
env:
APK_RUN_ID: ${{ needs.validate.outputs.apk_run_id }}
GH_TOKEN: ${{ github.token }}
run: python3 scripts/ci/release.py publish
preflight:
if: ${{ github.ref == 'refs/heads/main' && (github.event_name == 'workflow_dispatch' || github.event.created) }}
runs-on: ubuntu-26.04
timeout-minutes: 345
permissions:
actions: write
contents: write
steps:
- uses: actions/checkout@v6
with:
persist-credentials: false
- name: Exercise release permissions and validation
env:
GH_TOKEN: ${{ github.token }}
run: python3 scripts/ci/release.py preflight
+552 -522
View File
File diff suppressed because it is too large. Load diff
+2
View File
@@ -29,3 +29,5 @@ __pycache__/
*.py[cod]
/.gradle
/.trace-work/
# The restored trace fixture cache entry (.github/scripts/trace-fixture-bundle.sh)
/trace-fixture-bundle/
+4
View File
@@ -452,6 +452,7 @@ set(SOURCE_FILES
MobileGL/MG_Util/SelfTest/DriverBugProbes.cpp
MobileGL/MG_Util/SelfTest/PersistentBufferOrderingProbe.cpp
MobileGL/MG_Util/SelfTest/DriverPost.cpp
MobileGL/MG_Util/SelfTest/DriverPostClipDistance.cpp
MobileGL/MG_Util/SelfTest/DriverPostIterationRPWitness.cpp
MobileGL/MG_Util/SelfTest/PrimitivesGeneratedNoXfbProbe.cpp
@@ -479,6 +480,7 @@ set(SOURCE_FILES
MobileGL/MG_Impl/GLImpl/RenderState/GL_RenderState.cpp
MobileGL/MG_Impl/GLImpl/Framebuffer/Validators.cpp
MobileGL/MG_Impl/GLImpl/Framebuffer/GL_Framebuffer.cpp
MobileGL/MG_Impl/GLImpl/Framebuffer/GL_FramebufferMultiview.cpp
MobileGL/MG_Impl/GLImpl/Program/GL_Program.cpp
MobileGL/MG_Impl/GLImpl/Program/GL_ShaderObjectsARB.cpp
MobileGL/MG_Impl/GLImpl/Program/ProgramInterface.cpp
@@ -655,6 +657,7 @@ list(APPEND SOURCE_FILES
MobileGL/MG_Pipe/MGPipeRenderStateSpans.cpp
MobileGL/MG_Pipe/PipeApply.cpp
MobileGL/MG_Pipe/PipeDeviceLossKnobs.cpp
MobileGL/MG_Pipe/PipeResidentBuffer.cpp
MobileGL/MG_Impl/Pipe/SlotAllocator.cpp
# P4a's contract: the reflection-archive serializer over ProgramArtifacts.h's
# VisitFields tables. Push-only for the same G1 reason as the three above - in
@@ -802,6 +805,7 @@ if (ANDROID)
list(APPEND SOURCE_FILES
MobileGL/MG_Util/SelfTest/DriverPostJni.cpp
MobileGL/MG_Util/SelfTest/DriverBenchJni.cpp
MobileGL/AndroidTestScenes.cpp
)
if (MOBILEGL_BUILD_DISAGGREGATED)
# P12 (on-screen server window): the APK's MobileGLDisplayActivity - the in-process
+17 -2
View File
@@ -31,7 +31,8 @@ Commands below use `python3`. On Windows, run `python` instead.
- A file directly in `MobileGL/` uses `MobileGL`, and a submodule uses its path (`3rdparty/glslang`).
- List every scope the commit touches, comma-separated: `(MG_Backend/DirectGLES, MG_Test/Wire)`. A commit that touches more than three scopes skips this check: summarize the touched areas yourself, for example `(...)`.
- `python3 scripts/check_text_hygiene.py scope` prints the scope for the staged changes.
- **No** planning ids (phase or decision codes such as `P13` or `ID-54`), local paths, external project names or non-English text anywhere in the message.
- **No** planning ids (phase or decision codes such as `P13` or `ID-54`), local paths or non-English text anywhere in the message.
- Name an external project only to credit a non-trivial technique taken from it, with a link to the source. A common technique needs no attribution.
- **Merges** use `[Merge] (area): what the merge takes`. The scope is free text there. Write the subject yourself, since git's default merge message fails the check. The commits a merge brings in are not checked again.
- **Reverts** use `[Fix] (Scope): revert <the reverted subject>`.
@@ -81,7 +82,7 @@ Example:
## Checks
`python3 scripts/check_text_hygiene.py ci` runs what CI runs. It checks the commits on the branch's own line of history since the check was added. The base branch it compares with is `feat/disaggregated`, which you can change with `TEXT_HYGIENE_BASE_BRANCH`.
`python3 scripts/check_text_hygiene.py ci` runs what CI runs. It checks the commits on the branch's own line of history since the check was added. A push that moves a branch forward checks the commits it adds. A new branch, a force push and a run that is not a push check the commits the branch adds to the base branch, which is the development branch `dev`. Set `TEXT_HYGIENE_BASE_BRANCH` to compare with another branch. Another branch that adds nothing to the base branch has only its tree checked, and the base branch at its own tip checks its last commit.
These fail on any violation:
@@ -112,3 +113,17 @@ These are ratchets: each total may only go down.
`python3 scripts/check_structure.py report` lists what each total counts, and `tree --update-baseline` lowers the baseline the same way.
Not checked by CI: the platform, switch and lifetime-id rules, planning ids outside comments, English outside comments, and the regeneration step for generated code.
## Releases
Fast-forward main to the selected dev commit. Create an annotated version tag at
that commit, with the release notes as the tag message. Push main before pushing
the tag. Use v26.11 for a stable release, or a suffix such as -alpha.1 or -rc.1
for a prerelease.
The Release workflow requires Test and MobileGL APK to succeed at the tagged
commit. It reuses matching runs and dispatches missing ones. After reviewing
the linked runs in its summary, rerun a failed validation before retrying
Release. Use a new tag if a fix changes the release commit.
The release includes the signed launcher plugin APK from the passing APK run.
+397
View File
@@ -0,0 +1,397 @@
// MobileGL - MobileGL/AndroidTestScenes.cpp
// Copyright (c) 2025-2026 MobileGL-Dev
// Licensed under the GNU Lesser General Public License v3.0:
// https://www.gnu.org/licenses/gpl-3.0.txt
// https://www.gnu.org/licenses/lgpl-3.0.txt
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
#ifdef __ANDROID__
#include <android/native_window_jni.h>
#include <jni.h>
#include <algorithm>
#include <initializer_list>
#include <chrono>
#include <memory>
#include <string>
#include <string_view>
#include <vector>
#include <Includes.h>
#include <MG_Impl/EGLImpl/EGLImpl.h>
#include <MG_Impl/GLImpl/Buffer/GL_Buffer.h>
#include <MG_Impl/GLImpl/Drawing/GL_Drawing.h>
#include <MG_Impl/GLImpl/Framebuffer/GL_Framebuffer.h>
#include <MG_Impl/GLImpl/Getter/GL_Getter.h>
#include <MG_Impl/GLImpl/Program/GL_Program.h>
#include <MG_Impl/GLImpl/RenderState/GL_RenderState.h>
#include <MG_Impl/GLImpl/Texture/GL_Texture.h>
#include <MG_Impl/GLImpl/VertexArray/GL_VertexArray.h>
namespace {
namespace Egl = MobileGL::MG_Impl::EGLImpl;
namespace Gl = MobileGL::MG_Impl::GLImpl;
using Clock = std::chrono::steady_clock;
#include "MG_Util/SelfTest/AndroidTestLandscapeScenes.inc"
#include "MG_Util/SelfTest/AndroidTestGeometricScenes.inc"
#include "MG_Util/SelfTest/AndroidTestOceanSunrise.inc"
#include "MG_Util/SelfTest/AndroidTestOceanHdr.inc"
#include "MG_Util/SelfTest/AndroidTestApiChurn.inc"
enum class SceneKind {
Fragment,
ApiChurn,
OceanHdr
};
struct Scene {
const char* title;
const char* fragment;
SceneKind kind = SceneKind::Fragment;
};
constexpr Scene kScenes[] = {{"Aurora", kAurora},
{"Ocean Sunset", kOcean},
{"Wind-Swept Dunes", kDunes},
{"Neon Skyline", kCity},
{"Orbital Dawn", kOrbit},
{"Light Tunnel", kTunnel},
{"Kaleidoscope", kKaleidoscope},
{"Starfield", kParticles},
{"Liquid Metaballs", kMetaballs},
{"Rotating Prism", kPrism},
{"API Churn", kApiChurn, SceneKind::ApiChurn},
{"Ocean Sunrise (Stress)", kOceanSunrise},
{"Ocean Sunrise (GL 4.5)", kOceanSunrise, SceneKind::OceanHdr}};
constexpr const char* kVertex = R"glsl(
in vec2 aPosition;
void main() { gl_Position = vec4(aPosition, 0.0, 1.0); }
)glsl";
constexpr const char* kFragmentInputs = R"glsl(
uniform vec2 uExtent;
uniform float uTime;
out vec4 outColor;
)glsl";
constexpr const char* kFragmentMain = R"glsl(
void main() {
vec2 uv = gl_FragCoord.xy / uExtent;
vec2 p = (2.0 * gl_FragCoord.xy - uExtent) / uExtent.y;
outColor = vec4(clamp(scene(p, uv, uTime), 0.0, 1.0), 1.0);
}
)glsl";
std::string JsonString(std::string_view text) {
std::string result = "\"";
for (const unsigned char ch : text) {
if (ch == '"' || ch == '\\') result += '\\';
result += ch < 32 ? ' ' : static_cast<char>(ch);
}
return result + '"';
}
std::string Error(std::string_view message) {
return "{\"error\":" + JsonString(message) + "}";
}
struct SceneWindow {
EGLDisplay display = EGL_NO_DISPLAY;
EGLSurface surface = EGL_NO_SURFACE;
EGLContext context = EGL_NO_CONTEXT;
EGLint width = 0;
EGLint height = 0;
~SceneWindow() {
if (display == EGL_NO_DISPLAY) return;
Egl::MakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
if (context != EGL_NO_CONTEXT) Egl::DestroyContext(display, context);
if (surface != EGL_NO_SURFACE) Egl::DestroySurface(display, surface);
Egl::Terminate(display);
}
void Open(ANativeWindow* window, bool vsync) {
display = Egl::GetDisplay(EGL_DEFAULT_DISPLAY);
if (display == EGL_NO_DISPLAY || !Egl::Initialize(display, nullptr, nullptr)) {
throw MobileGL::RuntimeError("eglInitialize failed");
}
const EGLint configAttributes[] = {
EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_NONE};
EGLConfig config = nullptr;
EGLint count = 0;
if (!Egl::ChooseConfig(display, configAttributes, &config, 1, &count) || count == 0) {
throw MobileGL::RuntimeError("No EGL window config");
}
const EGLint contextAttributes[] = {EGL_CONTEXT_CLIENT_VERSION, 3, EGL_NONE};
context = Egl::CreateContext(display, config, EGL_NO_CONTEXT, contextAttributes);
surface = Egl::CreateWindowSurface(display, config, window, nullptr);
if (context == EGL_NO_CONTEXT || surface == EGL_NO_SURFACE ||
!Egl::MakeCurrent(display, surface, surface, context)) {
throw MobileGL::RuntimeError("Could not bind EGL window context");
}
width = ANativeWindow_getWidth(window);
height = ANativeWindow_getHeight(window);
if (width < 1 || height < 1) throw MobileGL::RuntimeError("Surface has no size");
if (!Egl::SwapInterval(display, vsync ? 1 : 0)) {
throw MobileGL::RuntimeError("eglSwapInterval failed");
}
}
};
GLuint CompileShader(GLenum kind, const std::string& source) {
const GLuint shader = Gl::CreateShader(kind);
const char* sources[] = {source.c_str()};
Gl::ShaderSource(shader, 1, sources, nullptr);
Gl::CompileShader(shader);
GLint compiled = GL_FALSE;
Gl::GetShaderiv(shader, GL_COMPILE_STATUS, &compiled);
if (!compiled) {
char log[512]{};
Gl::GetShaderInfoLog(shader, sizeof log, nullptr, log);
throw MobileGL::RuntimeError(std::string("Shader compile failed: ") + log);
}
return shader;
}
GLuint LinkProgram(std::initializer_list<GLuint> shaders) {
const GLuint program = Gl::CreateProgram();
for (const auto shader : shaders)
Gl::AttachShader(program, shader);
Gl::BindAttribLocation(program, 0, "aPosition");
Gl::LinkProgram(program);
for (const auto shader : shaders)
Gl::DeleteShader(shader);
GLint linked = GL_FALSE;
Gl::GetProgramiv(program, GL_LINK_STATUS, &linked);
if (!linked) {
char log[512]{};
Gl::GetProgramInfoLog(program, sizeof log, nullptr, log);
throw MobileGL::RuntimeError(std::string("Program link failed: ") + log);
}
return program;
}
GLuint BuildProgram(const std::string& version, const std::string& fragment, const char* main) {
const GLuint vertex = CompileShader(GL_VERTEX_SHADER, version + kVertex);
const GLuint pixel = CompileShader(GL_FRAGMENT_SHADER, version + kFragmentInputs + fragment + main);
return LinkProgram({vertex, pixel});
}
struct OceanHdrPasses {
static constexpr int WaveSize = 256;
GLuint spectrumProgram = 0;
GLuint synthesisProgram = 0;
GLuint waterProgram = 0;
GLuint postProgram = 0;
GLuint spectrumBuffer = 0;
GLuint waveImage = 0;
GLuint hdrImage = 0;
GLuint hdrTarget = 0;
GLint spectrumTime = -1;
GLint waterTime = -1;
void Setup(const SceneWindow& egl) {
GLint major = 0;
GLint minor = 0;
Gl::GetIntegerv(GL_MAJOR_VERSION, &major);
Gl::GetIntegerv(GL_MINOR_VERSION, &minor);
if (major < 4 || (major == 4 && minor < 5)) {
throw MobileGL::RuntimeError("Ocean Sunrise requires desktop GL 4.5");
}
const std::string version = "#version 450 core\n";
spectrumProgram = LinkProgram({CompileShader(GL_COMPUTE_SHADER, version + kOceanSpectrum)});
synthesisProgram = LinkProgram({CompileShader(GL_COMPUTE_SHADER, version + kOceanSynthesis)});
waterProgram =
BuildProgram(version, std::string("#define MOBILEGL_OCEAN_HDR\n") + kOceanSunrise, kOceanHdrMain);
postProgram = BuildProgram(version, "", kOceanPost);
spectrumTime = Gl::GetUniformLocation(spectrumProgram, "uTime");
waterTime = Gl::GetUniformLocation(waterProgram, "uTime");
Gl::CreateBuffers(1, &spectrumBuffer);
Gl::NamedBufferStorage(spectrumBuffer, 24 * 4 * sizeof(float), nullptr, 0);
Gl::BindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, spectrumBuffer);
Gl::CreateTextures(GL_TEXTURE_2D, 1, &waveImage);
Gl::TextureStorage2D(waveImage, 1, GL_RGBA32F, WaveSize, WaveSize);
Gl::TextureParameteri(waveImage, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
Gl::TextureParameteri(waveImage, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
Gl::CreateTextures(GL_TEXTURE_2D, 1, &hdrImage);
Gl::TextureStorage2D(hdrImage, 1, GL_RGBA16F, egl.width, egl.height);
Gl::TextureParameteri(hdrImage, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
Gl::TextureParameteri(hdrImage, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
Gl::TextureParameteri(hdrImage, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
Gl::TextureParameteri(hdrImage, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
Gl::CreateFramebuffers(1, &hdrTarget);
Gl::NamedFramebufferTexture(hdrTarget, GL_COLOR_ATTACHMENT0, hdrImage, 0);
if (Gl::CheckNamedFramebufferStatus(hdrTarget, GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
throw MobileGL::RuntimeError("RGBA16F framebuffer unavailable");
}
Gl::UseProgram(waterProgram);
Gl::Uniform2f(Gl::GetUniformLocation(waterProgram, "uExtent"), egl.width, egl.height);
Gl::Uniform1i(Gl::GetUniformLocation(waterProgram, "uCapillaryWaves"), 0);
Gl::UseProgram(postProgram);
Gl::Uniform2f(Gl::GetUniformLocation(postProgram, "uExtent"), egl.width, egl.height);
Gl::Uniform1i(Gl::GetUniformLocation(postProgram, "uRadiance"), 1);
if (Gl::GetError() != GL_NO_ERROR) throw MobileGL::RuntimeError("Ocean GL 4.5 setup failed");
}
void Draw(float time) const {
Gl::UseProgram(spectrumProgram);
Gl::Uniform1f(spectrumTime, time + 4.0f);
Gl::DispatchCompute(1, 1, 1);
Gl::MemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT);
Gl::UseProgram(synthesisProgram);
Gl::BindImageTexture(0, waveImage, 0, GL_FALSE, 0, GL_WRITE_ONLY, GL_RGBA32F);
Gl::DispatchCompute(WaveSize / 8, WaveSize / 8, 1);
Gl::MemoryBarrier(GL_TEXTURE_FETCH_BARRIER_BIT | GL_SHADER_IMAGE_ACCESS_BARRIER_BIT);
Gl::BindFramebuffer(GL_FRAMEBUFFER, hdrTarget);
Gl::UseProgram(waterProgram);
Gl::BindTextureUnit(0, waveImage);
Gl::Uniform1f(waterTime, time);
Gl::DrawArrays(GL_TRIANGLES, 0, 3);
Gl::BindFramebuffer(GL_FRAMEBUFFER, 0);
Gl::UseProgram(postProgram);
Gl::BindTextureUnit(1, hdrImage);
Gl::DrawArrays(GL_TRIANGLES, 0, 3);
}
};
struct SceneCancellation {
JNIEnv* env;
jobject flag;
jmethodID get;
bool Requested() const { return env->CallBooleanMethod(flag, get) == JNI_TRUE; }
};
std::string RunScene(const Scene& scene, ANativeWindow* window, bool vsync, const SceneCancellation& cancellation) {
if (cancellation.Requested()) return Error("Canceled");
SceneWindow egl;
egl.Open(window, vsync);
const auto* renderer = reinterpret_cast<const char*>(Gl::GetString(GL_RENDERER));
const auto* version = reinterpret_cast<const char*>(Gl::GetString(GL_VERSION));
const auto rendererName = JsonString(renderer ? renderer : "Unknown renderer");
const bool oceanHdr = scene.kind == SceneKind::OceanHdr;
OceanHdrPasses ocean;
GLuint program = 0;
GLint timeUniform = -1;
if (oceanHdr) {
ocean.Setup(egl);
} else {
const bool es = version && std::string_view(version).starts_with("OpenGL ES");
program = BuildProgram(es ? "#version 300 es\nprecision highp float;\n" : "#version 330 core\n",
scene.fragment, kFragmentMain);
Gl::UseProgram(program);
Gl::Uniform2f(Gl::GetUniformLocation(program, "uExtent"), egl.width, egl.height);
timeUniform = Gl::GetUniformLocation(program, "uTime");
}
constexpr GLfloat triangle[] = {-1.0f, -1.0f, 3.0f, -1.0f, -1.0f, 3.0f};
GLuint vao = 0;
GLuint vbo = 0;
Gl::GenVertexArrays(1, &vao);
Gl::BindVertexArray(vao);
Gl::GenBuffers(1, &vbo);
Gl::BindBuffer(GL_ARRAY_BUFFER, vbo);
Gl::BufferData(GL_ARRAY_BUFFER, sizeof triangle, triangle, GL_STATIC_DRAW);
Gl::VertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, nullptr);
Gl::EnableVertexAttribArray(0);
Gl::Viewport(0, 0, egl.width, egl.height);
const auto start = Clock::now();
const auto draw = [&] {
const float time = std::chrono::duration<float>(Clock::now() - start).count();
if (oceanHdr) {
ocean.Draw(time);
} else {
Gl::Uniform1f(timeUniform, time);
if (scene.kind == SceneKind::ApiChurn) IssueRedundantCalls(program, vao, vbo, timeUniform, time);
Gl::DrawArrays(GL_TRIANGLES, 0, 3);
}
if (!Egl::SwapBuffers(egl.display, egl.surface)) {
throw MobileGL::RuntimeError("eglSwapBuffers failed");
}
};
for (int i = 0; i < 8; ++i) {
if (cancellation.Requested()) return Error("Canceled");
draw();
}
std::vector<double> frameTimes;
const auto sampleStart = Clock::now();
auto end = sampleStart;
do {
if (cancellation.Requested()) return Error("Canceled");
const auto begin = end;
draw();
end = Clock::now();
frameTimes.push_back(std::chrono::duration<double, std::milli>(end - begin).count());
} while (end - sampleStart < std::chrono::seconds(5));
const GLenum glError = Gl::GetError();
std::sort(frameTimes.begin(), frameTimes.end());
const auto count = frameTimes.size();
const double seconds = std::chrono::duration<double>(end - sampleStart).count();
std::string report = "{\"renderer\":" + rendererName + ",\"frames\":" + std::to_string(count) +
",\"fps\":" + std::to_string(count / seconds) +
",\"medianFrameMs\":" + std::to_string(frameTimes[count / 2]) +
",\"p95FrameMs\":" + std::to_string(frameTimes[(count * 95 + 99) / 100 - 1]) +
",\"glError\":" + std::to_string(glError);
if (scene.kind == SceneKind::ApiChurn) {
report += ",\"redundantCallsPerFrame\":" + std::to_string(kRedundantCallsPerFrame);
}
return report + "}";
}
} // namespace
extern "C" JNIEXPORT jstring JNICALL Java_top_mobilegl_plugin_TestActivity_nativeSampleCatalog(JNIEnv* env, jclass) {
std::string catalog = "[";
for (const auto& scene : kScenes) {
if (catalog.size() > 1) catalog += ',';
catalog += JsonString(scene.title);
}
catalog += ']';
return env->NewStringUTF(catalog.c_str());
}
extern "C" JNIEXPORT jstring JNICALL Java_top_mobilegl_plugin_TestService_nativeRunSample(
JNIEnv* env, jclass, jstring sample, jobject surface, jboolean vsync, jobject canceled) {
const auto flagType = env->GetObjectClass(canceled);
const auto get = env->GetMethodID(flagType, "get", "()Z");
env->DeleteLocalRef(flagType);
if (!get) return nullptr;
const SceneCancellation cancellation{env, canceled, get};
std::unique_ptr<ANativeWindow, decltype(&ANativeWindow_release)> window(
surface ? ANativeWindow_fromSurface(env, surface) : nullptr, ANativeWindow_release);
if (!window) return env->NewStringUTF("{\"error\":\"Surface unavailable\"}");
const char* chars = env->GetStringUTFChars(sample, nullptr);
if (!chars) return nullptr;
const std::string selected(chars);
env->ReleaseStringUTFChars(sample, chars);
std::string result = Error("Unknown scene");
try {
for (const auto& scene : kScenes) {
if (selected == scene.title) {
result = RunScene(scene, window.get(), vsync == JNI_TRUE, cancellation);
break;
}
}
}
catch (const std::exception& error) {
result = Error(error.what());
}
catch (...) {
result = Error("Native rendering failed");
}
return env->NewStringUTF(result.c_str());
}
#endif
+8
View File
@@ -103,6 +103,11 @@ namespace MobileGL {
// GL_EXT_clip_control on DirectGLES. DirectVulkan applies clip control in its own
// position fixup and does not read this.
Bool ClipControl = false;
// GL_OVR_multiview and GL_OVR_multiview2. DirectGLES: each where the driver has that
// same extension (and, for the first, glFramebufferTextureMultiviewOVR). DirectVulkan:
// both where the device was created with the multiview feature.
Bool Multiview = false;
Bool Multiview2 = false;
};
// Coarse GPU vendor identity for gating device-specific quirks. Detected from the
@@ -411,6 +416,9 @@ namespace MobileGL {
Int MaxFragmentShadingRateAttachmentTexelHeight = 0;
Int MaxFragmentShadingRateAttachmentTexelAspectRatio = 0;
Int MaxFragmentShadingRateAttachmentLayers = 0;
// GL_MAX_VIEWS_OVR. Zero means no multiview, which is also why GL_OVR_multiview is not
// advertised then; a backend that has it reports at least the spec minimum of 2.
Int MaxViews = 0;
static constexpr Bool IsSamplePositionCount(Int samples) {
return samples >= 2 && samples <= kMaxSamplePositionCount && (samples & (samples - 1)) == 0;
+2 -1
View File
@@ -14,11 +14,12 @@ namespace MobileGL::MG_Config {
inline const String ProjectName = "MobileGL";
inline const String CoreName = "MobileGL Core";
inline const String CoreVendor = "MobileGL-Dev (BZLZHH, Swung0x48, Tungsten)";
inline const Version CoreVersion = {26, 10, 0, "-dev", VersionType::Development};
inline const Version CoreVersion = {26, 11, 0, "-alpha.2", VersionType::Unstable};
inline const VersionStringFormatAttrib DefaultVersionStringFormatAttrib = {2, 2, 0, true, true};
inline const Uint64 CacheVersion = 0;
extern BackendType ActiveBackendType;
extern Bool AutoSelectBackend;
// Tri-state override for device-specific quirks: Auto lets the detected device decide,
// ForceOn/ForceOff bypass the detection in either direction. ForceOn only bypasses the
+12 -2
View File
@@ -29,6 +29,7 @@ namespace MobileGL::MG_Config {
// Zero/default-initialized at static-init time (all fields have constexpr-friendly
// defaults), so it is safe to read even if MG_ConfigLoader::Init has not run yet.
FeaturesTable Features;
Bool AutoSelectBackend = false;
#if MOBILEGL_BUILD_DISAGGREGATED
// Same contract, and for the same reason: MG_Backend::Init() reads Transport, and a
// build order that put it before MG_ConfigLoader::Init() must see Monolith rather than
@@ -461,16 +462,21 @@ namespace MobileGL::MG_ConfigLoader {
inline void InitBackendType() {
String backendTypeStr;
QueryEnvVariable("MOBILEGL_BACKEND_TYPE", backendTypeStr, "DirectGLES");
constexpr const char* key = "MOBILEGL_BACKEND_TYPE";
const auto configured = acceptedEnvVariablesMap->find(key);
MG_Config::AutoSelectBackend = configured == acceptedEnvVariablesMap->end();
if (!MG_Config::AutoSelectBackend) backendTypeStr = configured->second;
#if defined(__ANDROID__)
// An Android app that hosts the library sets the environment itself, before the library
// loads; the debug property is how a developer picks the backend for such a process
// without rebuilding it (`adb shell setprop debug.mobilegl.backend DirectVulkan`).
char property[PROP_VALUE_MAX] = {};
if (__system_property_get("debug.mobilegl.backend", property) > 0) {
if (!QueryEnvFlag("MOBILEGL_TEST_BACKEND_ENV_PRIORITY") &&
__system_property_get("debug.mobilegl.backend", property) > 0) {
MGLOG_I("Config: debug.mobilegl.backend=%s overrides MOBILEGL_BACKEND_TYPE=%s", property,
backendTypeStr.c_str());
backendTypeStr = property;
MG_Config::AutoSelectBackend = false;
}
#endif
#define ENTRY(backendType) \
@@ -479,6 +485,10 @@ namespace MobileGL::MG_ConfigLoader {
MGLOG_I("Config: Active backend type set to " #backendType); \
return; \
}
if (MG_Config::AutoSelectBackend) {
MG_Config::ActiveBackendType = BackendType::DirectGLES;
return;
}
ENTRY(DirectGLES)
ENTRY(DirectVulkan)
ENTRY(Unknown)
+9
View File
@@ -10,6 +10,7 @@
#include "Config.h"
#include <MG_Backend/BackendObjects.h>
#include <MG_Backend/DirectVulkan/DirectVulkan.h>
#include <MG_Backend/DirectVulkan/Renderer/VulkanRenderer.h>
#include <MG_State/GLState/Core.h>
#include <MG_State/EGLState/Core.h>
#include <MG_Impl/GLImpl/Texture/ProxyTexture.h>
@@ -135,6 +136,14 @@ namespace MobileGL {
MG_Util::Debug::InitFile();
MGLOG_I("Initializing MobileGL...");
MG_ConfigLoader::Init();
if (MG_Config::AutoSelectBackend) {
if (MG_Backend::DirectVulkan::VulkanRenderer::ProbeDefaultBackend()) {
MG_Config::ActiveBackendType = BackendType::DirectVulkan;
MGLOG_I("Config: automatically selected DirectVulkan");
} else {
MGLOG_I("Config: automatically selected DirectGLES");
}
}
MGLOG_I("Config loaded");
// Immediately after the config load and before anything can count: the MGPipe
// boundary counters latch their enable flag here, so every counting site in the
+25
View File
@@ -37,6 +37,31 @@ namespace MobileGL::MG_Backend {
m_egl.ReleaseSurface(surface);
}
Bool BackendObject::CreateEGLWindowSurfaceOnDisplay(EGLDisplay display, EGLSurface surface,
const WindowHandle& handle) {
const auto lock = m_egl.Lock();
const auto previous = m_egl.SetRegistrationDisplay(display);
const Bool created = CreateEGLWindowSurface(surface, handle);
m_egl.SetRegistrationDisplay(previous);
return created;
}
Bool BackendObject::CreateEGLPbufferSurfaceOnDisplay(EGLDisplay display, EGLSurface surface, EGLint width,
EGLint height) {
const auto lock = m_egl.Lock();
const auto previous = m_egl.SetRegistrationDisplay(display);
const Bool created = CreateEGLPbufferSurface(surface, width, height);
m_egl.SetRegistrationDisplay(previous);
return created;
}
void BackendObject::ReleaseEGLDisplay(EGLDisplay display) {
const auto lock = m_egl.Lock();
for (const EGLSurface surface : m_egl.SurfacesOnDisplay(display))
ReleaseEGLSurface(surface);
m_egl.ReleaseDisplay(display);
}
void BackendObject::ReleaseEGLResources() {
m_egl.ReleaseAll();
}
+7
View File
@@ -47,6 +47,13 @@ namespace MobileGL {
virtual void SetEGLSwapInterval(Int interval);
virtual void ReleaseEGLSurface(EGLSurface surface);
virtual void ReleaseEGLResources();
void ReleaseEGLDisplay(EGLDisplay display);
Bool CreateEGLWindowSurfaceOnDisplay(EGLDisplay display, EGLSurface surface, const WindowHandle& handle);
Bool CreateEGLPbufferSurfaceOnDisplay(EGLDisplay display, EGLSurface surface, EGLint width, EGLint height);
virtual void RegisterEGLContext(EGLContext, Uint64, Uint64) {}
virtual void ReleaseEGLContext(Uint64) {}
virtual Uint64 SetEGLObjectShareGroup(Uint64) { return 0; }
virtual void BeginEGLCommands() {}
void SetWindowHandle(const WindowHandle& handle);
@@ -28,6 +28,14 @@
namespace MobileGL::MG_Backend::DirectGLES {
namespace {
Bool UsesLocalEGLContexts() {
#if MOBILEGL_BUILD_DISAGGREGATED
return MG_Config::Transport == MG_Config::TransportMode::Monolith;
#else
return true;
#endif
}
Bool IsReleaseCurrentRequest(EGLDisplay dpy, EGLSurface draw, EGLSurface read, EGLContext ctx) {
(void)dpy;
return draw == EGL_NO_SURFACE && read == EGL_NO_SURFACE && ctx == EGL_NO_CONTEXT;
@@ -903,7 +911,9 @@ namespace MobileGL::MG_Backend::DirectGLES {
capabilities.SupportsTextureView, capabilities.SupportsTextureCubeMapArray,
AdvertisedFeatureSupport{.TessellationShader = capabilities.SupportsTessellationShader,
.CullDistance = capabilities.MaxCullDistances > 0,
.ClipControl = capabilities.SupportsClipControl});
.ClipControl = capabilities.SupportsClipControl,
.Multiview = capabilities.SupportsMultiview,
.Multiview2 = capabilities.SupportsMultiview2});
// Exactly what InitCapabilities forwards into the dynamic parameters: the base
// extension and _primitive when the driver has them, _attachment not yet.
auto& extensions = MutableRendererInfo().RendererGLInfo.Extensions;
@@ -993,6 +1003,14 @@ namespace MobileGL::MG_Backend::DirectGLES {
Bool BackendObject_DirectGLES::InitWindowSurface() {
const EGLSurface activating = EGLRegistry().ActivatingSurface();
if (UsesLocalEGLContexts() && activating != EGL_NO_SURFACE) {
if (m_nativeSurfaces.find(activating) != m_nativeSurfaces.end()) return true;
EGLSurface native = EGL_NO_SURFACE;
auto window = reinterpret_cast<NativeWindowType>(EGLRegistry().CurrentWindowHandle().Handle);
if (!DirectGLES::InitWindowSurface(window, &native)) return false;
m_nativeSurfaces[activating] = native;
return true;
}
if (RebindNativeSurfaceFor(activating)) return true;
// A suspended surface whose placeholder went: another placeholder - never the window, which
// is gone.
@@ -1101,13 +1119,10 @@ namespace MobileGL::MG_Backend::DirectGLES {
// and its objects. ResetRuntimeState still runs because the registry's per-surface
// bookkeeping (which surface is active, which threads made it current) does describe the
// surface that is being replaced.
if (UsesLocalEGLContexts()) return BackendObject::CreateEGLWindowSurface(surface, handle);
#if MOBILEGL_BUILD_DISAGGREGATED
const EGLSurface previous = egl.HasActiveSurface() ? egl.ActiveSurface() : EGL_NO_SURFACE;
const EGLSurface previousNativeDraw = DirectGLES::CurrentContextDrawSurface();
if (egl.HasActiveSurface()) {
egl.ResetRuntimeState();
}
#if MOBILEGL_BUILD_DISAGGREGATED
// ID-54 / ID-67: the surface's creation bound natively (InitWindowSurface -> MakeCurrent);
// the first virtual tuple adopts that bind. On failure nothing is known to be bound. The
// pull arm below is the original statement, byte for byte (G1).
@@ -1143,11 +1158,9 @@ namespace MobileGL::MG_Backend::DirectGLES {
// P14 S4: as for the window surface above - the native context is the (session, context
// token) tuple's and survives a surface switch. This used to be DestroyEGLContext().
if (UsesLocalEGLContexts()) return BackendObject::CreateEGLPbufferSurface(surface, width, height);
const EGLSurface previous = egl.HasActiveSurface() ? egl.ActiveSurface() : EGL_NO_SURFACE;
const EGLSurface previousNativeDraw = DirectGLES::CurrentContextDrawSurface();
if (egl.HasActiveSurface()) {
egl.ResetRuntimeState();
}
// ID-54 / ID-67: as for the window surface - InitPbufferSurface bound natively. The pull
// arm below is the original statement, byte for byte (G1).
@@ -1170,8 +1183,8 @@ namespace MobileGL::MG_Backend::DirectGLES {
if (!record || record->Kind != EGLSurfaceRegistry::SurfaceKind::Pbuffer || native == m_nativeSurfaces.end()) {
return BackendObject::ResizeEGLWindowSurface(surface, width, height);
}
// A pbuffer has no resize: the client surface gets a new native pbuffer at the new size,
// and every context that drew to the old one draws to the new one.
// Replacing a current pbuffer requires a bind on its owning thread.
if (UsesLocalEGLContexts() && EGLRegistry().IsCurrentOnOtherThread(surface)) return false;
const EGLint w = static_cast<EGLint>(std::max<Uint32>(width, 1));
const EGLint h = static_cast<EGLint>(std::max<Uint32>(height, 1));
const EGLSurface replacement = DirectGLES::CreateSessionPbuffer(w, h);
@@ -1179,13 +1192,23 @@ namespace MobileGL::MG_Backend::DirectGLES {
MGLOG_E("ResizeEGLWindowSurface: no %dx%d pbuffer could replace the old drawable", w, h);
return false;
}
DirectGLES::ReplaceSessionSurface(native->second, replacement);
if (!DirectGLES::ReplaceSessionSurface(native->second, replacement)) {
DirectGLES::DestroySessionSurface(replacement);
return false;
}
native->second = replacement;
return BackendObject::ResizeEGLWindowSurface(surface, width, height);
}
Bool BackendObject_DirectGLES::InitPbufferSurface(EGLint width, EGLint height) {
const EGLSurface activating = EGLRegistry().ActivatingSurface();
if (UsesLocalEGLContexts() && activating != EGL_NO_SURFACE) {
if (m_nativeSurfaces.find(activating) != m_nativeSurfaces.end()) return true;
EGLSurface native = EGL_NO_SURFACE;
if (!DirectGLES::InitPbufferSurface(width, height, &native)) return false;
m_nativeSurfaces[activating] = native;
return true;
}
if (RebindNativeSurfaceFor(activating)) return true;
if (!DirectGLES::InitPbufferSurface(width, height)) return false;
if (activating != EGL_NO_SURFACE) {
@@ -1194,6 +1217,33 @@ namespace MobileGL::MG_Backend::DirectGLES {
return true;
}
void BackendObject_DirectGLES::RegisterEGLContext(EGLContext context, Uint64 token, Uint64 shareGroup) {
const auto lock = EGLRegistry().Lock();
m_contexts.insert_or_assign(context, ContextIdentity{token, shareGroup});
}
void BackendObject_DirectGLES::ReleaseEGLContext(Uint64 token) {
const auto lock = EGLRegistry().Lock();
const auto it = std::find_if(m_contexts.begin(), m_contexts.end(),
[token](const auto& entry) { return entry.second.Token == token; });
if (it == m_contexts.end()) return;
const Uint64 shareGroup = it->second.ShareGroup;
m_contexts.erase(it);
const Bool groupLives = std::any_of(m_contexts.begin(), m_contexts.end(), [shareGroup](const auto& entry) {
return entry.second.ShareGroup == shareGroup;
});
if (!groupLives) BufferImpl::OnShareGroupDestroyed(0, shareGroup);
DirectGLES::DestroyNativeContextFor(token);
}
Uint64 BackendObject_DirectGLES::SetEGLObjectShareGroup(Uint64 shareGroup) {
return DirectGLES::SetMonolithObjectShareGroup(shareGroup);
}
void BackendObject_DirectGLES::BeginEGLCommands() {
DirectGLES::BeginMonolithCommands();
}
Bool BackendObject_DirectGLES::MakeEGLCurrent(EGLDisplay dpy, EGLSurface draw, EGLSurface read, EGLContext ctx) {
const auto lock = EGLRegistry().Lock();
if (IsReleaseCurrentRequest(dpy, draw, read, ctx)) {
@@ -1209,19 +1259,41 @@ namespace MobileGL::MG_Backend::DirectGLES {
return false;
}
const EGLSurfaceRegistry& egl = EGLRegistry();
if (!egl.DisplayInitialized() || egl.Display() != dpy) {
if (!egl.DisplayInitialized(dpy)) {
MGLOG_E("MakeEGLCurrent failed: EGL display mismatch or not initialized");
return false;
}
if (!egl.HasActiveSurface()) {
MGLOG_E("MakeEGLCurrent failed: EGL surface is not initialized");
if (!egl.IsRegistered(draw)) {
MGLOG_E("MakeEGLCurrent failed: EGL surface is not registered");
return false;
}
if (draw == EGL_NO_SURFACE || read == EGL_NO_SURFACE || ctx == EGL_NO_CONTEXT) {
if (draw == EGL_NO_SURFACE || draw != read || ctx == EGL_NO_CONTEXT) {
MGLOG_E("MakeEGLCurrent failed: draw/read/context is invalid");
return false;
}
if (const auto identity = m_contexts.find(ctx); identity != m_contexts.end()) {
const auto record = egl.Find(draw);
const auto native = m_nativeSurfaces.find(draw);
if (!record || record->Display != dpy || record->DestroyPending || native == m_nativeSurfaces.end())
return false;
const auto oldBinding = egl.CurrentOn(std::this_thread::get_id());
if (!DirectGLES::BindMonolithNativeContext(identity->second.Token, identity->second.ShareGroup,
native->second))
return false;
if (BackendObject::MakeEGLCurrent(dpy, draw, read, ctx)) return true;
if (oldBinding) {
const auto previous = m_contexts.find(oldBinding->Context);
const auto previousNative = m_nativeSurfaces.find(oldBinding->DrawSurface);
if (previous != m_contexts.end() && previousNative != m_nativeSurfaces.end() &&
DirectGLES::BindMonolithNativeContext(previous->second.Token, previous->second.ShareGroup,
previousNative->second))
return false;
}
(void)DirectGLES::ReleaseCurrent();
return false;
}
#if MOBILEGL_BUILD_DISAGGREGATED
// ID-54 / C7, the native half of "bind once per tuple" (v1, under ID-52/ID-59's grant for
// this file; #if-guarded so the pull build is byte-identical). Under an active transport
@@ -1585,6 +1657,14 @@ namespace MobileGL::MG_Backend::DirectGLES {
if (features.ClipControl) {
extensions.push_back(E_GL_ARB_clip_control);
}
// Multiview attachments go to the driver's glFramebufferTextureMultiviewOVR and
// gl_ViewID_OVR to its own built-in, so each string follows the driver's.
if (features.Multiview) {
extensions.push_back(E_GL_OVR_multiview);
if (features.Multiview2) {
extensions.push_back(E_GL_OVR_multiview2);
}
}
// Minecraft 26.3 checks this prerequisite before it even considers
// GL_ARB_multi_draw_indirect. ES 3.1 supplies both single-draw entry points; the loader
// folds the version and pointer checks into SupportsDrawIndirect.
@@ -2022,6 +2102,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
// the device answers every query. The attachment is not forwarded yet, so it is not
// claimed, whatever the driver offers.
m_dynamicParameters.SupportsFragmentShadingRate = m_GLESCapabilities.SupportsFragmentShadingRate;
m_dynamicParameters.MaxViews = m_GLESCapabilities.SupportsMultiview ? m_GLESCapabilities.MaxViews : 0;
m_dynamicParameters.SupportsPrimitiveFragmentShadingRate =
m_GLESCapabilities.SupportsFragmentShadingRatePrimitive;
m_dynamicParameters.SupportsAttachmentFragmentShadingRate = false;
@@ -60,6 +60,10 @@ namespace MobileGL::MG_Backend::DirectGLES {
Bool ExportNativeFence(int* fence) override;
void ReleaseEGLSurface(EGLSurface surface) override;
void ReleaseEGLResources() override;
void RegisterEGLContext(EGLContext context, Uint64 token, Uint64 shareGroup) override;
void ReleaseEGLContext(Uint64 token) override;
Uint64 SetEGLObjectShareGroup(Uint64 shareGroup) override;
void BeginEGLCommands() override;
// The server window going and coming back: each window surface on it swaps its native EGL
// window surface for a placeholder pbuffer and back (DirectGLES::Suspend/ResumeSessionWindowSurface).
Bool SuspendServerWindow(void* window) override;
@@ -88,6 +92,11 @@ namespace MobileGL::MG_Backend::DirectGLES {
// surface natively; put the previous one back for the context that held it.
void RestoreSurfaceAfterCreation(EGLSurface previousNativeDraw);
struct ContextIdentity {
Uint64 Token;
Uint64 ShareGroup;
};
UnorderedMap<EGLContext, ContextIdentity> m_contexts;
Bool m_initialized = false;
// P14: ONE NATIVE SURFACE PER CLIENT SURFACE, created on its first activation and re-bound
// on every later one. A multi-window client switches surfaces every frame; making a new
+8 -5
View File
@@ -89,8 +89,9 @@ namespace MobileGL::MG_Backend::DirectGLES {
GLenum format);
void GetIntegeri_v(GLenum target, GLuint index, GLint* data);
void ShaderStorageBlockBinding(GLuint program, const GLchar* storageBlockName, GLuint storageBlockBinding);
Bool InitWindowSurface(NativeWindowType window);
Bool InitPbufferSurface(EGLint width, EGLint height);
Bool InitWindowSurface(NativeWindowType window, EGLSurface* unbound = nullptr);
Bool InitPbufferSurface(EGLint width, EGLint height, EGLSurface* unbound = nullptr);
void BeginMonolithCommands();
// The calling thread's session's current native draw surface (the one the last Init*Surface
// created, or the last BindSessionSurface named).
EGLSurface CurrentSessionDrawSurface();
@@ -117,9 +118,9 @@ namespace MobileGL::MG_Backend::DirectGLES {
// A new pbuffer of the calling thread's session, created with the active context's config and
// bound to nothing (EGL: creating a surface changes no binding).
EGLSurface CreateSessionPbuffer(EGLint width, EGLint height);
// Every context of the session that drew to `previous` draws to `replacement` instead, and
// `previous` is destroyed (a pbuffer-backed window's resize).
void ReplaceSessionSurface(EGLSurface previous, EGLSurface replacement);
// Replace an owned surface after rebinding it on the calling thread, if current there.
// On failure both surfaces remain registered and the current binding is unchanged.
Bool ReplaceSessionSurface(EGLSurface previous, EGLSurface replacement);
// The server window going away (screen off): every context of the session that drew to the
// window surface `windowSurface` draws to a new 1x1 placeholder pbuffer instead, and the window
// surface is destroyed - no longer current anywhere once this returns. The contexts and their
@@ -312,6 +313,8 @@ namespace MobileGL::MG_Backend::DirectGLES {
// contexts are untouched; the display is terminated only when the last context in the process
// has gone.
void DestroyNativeContextFor(Uint64 contextToken);
Bool BindMonolithNativeContext(Uint64 token, Uint64 shareGroup, EGLSurface surface);
Uint64 SetMonolithObjectShareGroup(Uint64 shareGroup);
// ---- objects that belong to ONE native context ----
//
@@ -25,12 +25,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
// the dedupe a {slot, gen} compare instead of a raw address compare. An address
// a successor object can reproduce is the identity hazard this whole
// phase is about; a handle cannot be reproduced (Gen moves on reuse).
// the ensure EnsureBufferResourceForHandle(nullptr, Res). The frontend argument
// is only ever used for BufferObject::SyncPersistentMappedRange, which
// that function already skips under a transport (D-N), so passing
// nullptr removes a read rather than dropping work - and (nullptr, h)
// is already the live shape of the indirect-buffer ensure two hundred
// lines below.
// the ensure EnsureBufferResourceForHandle(Res) uses the same handle as the lookup.
//
// The IBO half lives in SyncNeccessaryBuffers beside the legacy one, for the reason it
// always did: the index slot is not part of the configuration (D5).
@@ -70,7 +65,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
// attribute index to re-read attrib.Buffer; here the entry already
// names the resource the record named, so the repair needs nothing the
// walk did not already have.
entry.resource = EnsureBufferResourceForHandle(nullptr, entry.handle);
entry.resource = EnsureBufferResourceForHandle(entry.handle);
}
memo->vboCleanEpoch = allClean ? bufferEpoch : 0;
}
@@ -86,7 +81,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
const Uint syncedBufferCount = ResolveDrawVertexBuffersFromRecord(
st, requests, MG_State::GLState::VertexArrayObject::MAX_VERTEX_ATTRIBS);
for (Uint i = 0; i < syncedBufferCount; ++i) {
auto* resource = EnsureBufferResourceForHandle(nullptr, requests[i].Res);
auto* resource = EnsureBufferResourceForHandle(requests[i].Res);
if (memo) {
auto& entry = memo->entries[i];
// Explicitly cleared rather than left as whatever the previous build of
@@ -175,7 +170,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
} else if (identityHolds && IsBufferDrawCleanByHandle(iboHandle, memo->iboResource, nullptr)) {
memo->iboCleanEpoch = bufferEpoch;
} else {
auto* resource = EnsureBufferResourceForHandle(nullptr, iboHandle);
auto* resource = EnsureBufferResourceForHandle(iboHandle);
if (memo) {
memo->iboHandle = iboHandle;
memo->iboSerial = iboSerial;
@@ -196,7 +191,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
// never read (T2). The twin's ensure is what SyncBoundBuffer's did.
const MG_Pipe::MGPipeHandle handle = MG_Pipe::MGPipeApplier().VerbIndirectBuffer;
if (!MG_Pipe::MGPipeHandleIsNull(handle)) {
auto* resource = EnsureBufferResourceForHandle(nullptr, handle);
auto* resource = EnsureBufferResourceForHandle(handle);
if (resource && resource->id != 0) {
BindBufferId(GL_DRAW_INDIRECT_BUFFER, resource->id);
}
@@ -299,7 +294,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
if (!span || i >= 4) continue;
const auto& range = span->Targets[i];
if (MG_Pipe::MGPipeHandleIsNull(range.Res) || range.Size == 0) continue;
auto* resource = BufferImpl::EnsureBufferResourceForHandle(nullptr, range.Res);
auto* resource = BufferImpl::EnsureBufferResourceForHandle(range.Res);
if (!resource || resource->id == 0) continue;
xfb.targets.push_back({nullptr, resource->id, static_cast<SizeT>(range.Offset),
static_cast<SizeT>(range.Offset + range.Size), i, range.Res});
@@ -911,7 +906,8 @@ namespace MobileGL::MG_Backend::DirectGLES {
BufferImpl::SyncNeccessaryBuffers(currentVAO, vaoTwin, vaoConfigVersion, syncBit & DrawSyncBit::IndexBuffer,
syncBit & DrawSyncBit::IndirectBuffer);
// The draw's integer arrays and the program's narrow-integer seeds (NarrowIntegerSeeds.h).
IntegerAttributePlan integerPlan = ResolveIntegerAttributePlanForDraw(MG_Pipe::MGPipeApplier().DrawProgram);
const MG_Pipe::MGPipeHandle programCso = MG_Pipe::MGPipeApplier().DrawProgram;
IntegerAttributePlan integerPlan = ResolveIntegerAttributePlanForDraw(programCso);
VertexArrayImpl::SyncCurrentVAOFromRecords(vaoTwin, integerPlan);
TextureImpl::SyncNeccessaryTextures(textureKeys);
// A draw reads and writes through its image units too, so the unit bindings have to be
@@ -929,8 +925,8 @@ namespace MobileGL::MG_Backend::DirectGLES {
// at all; the remaining uses of it below are the two callees' own, and both have a
// handle arm of their own. P5e (pa) finished it: the pull itself is gone on that arm and
// `currentProgram` is a null SharedPtr there, which this branch never reaches for.
PrgramImpl::SyncCurrentProgramByHandle(MG_Pipe::MGPipeApplier().DrawProgram, true, &integerPlan);
if (DropRefusedNarrowIntegerSeeds(integerPlan, MG_Pipe::MGPipeApplier().DrawProgram))
const auto* programRecord = PrgramImpl::SyncCurrentProgramByHandle(programCso, true, &integerPlan);
if (DropRefusedNarrowIntegerSeeds(integerPlan, programCso))
VertexArrayImpl::SyncCurrentVAOFromRecords(vaoTwin, integerPlan);
RenderStateImpl::SyncRenderState();
@@ -951,11 +947,11 @@ namespace MobileGL::MG_Backend::DirectGLES {
// a conjunction over four callees; this one is served by the record whenever the PROGRAM
// family is on the handle arm, which includes the mixed A/B where the texture bits are
// off and `currentProgram` above is therefore still a real object.
VertexArrayImpl::SyncCurrentVertexAttributeValues(vaoTwin, MG_Pipe::MGPipeApplier().DrawProgram);
VertexArrayImpl::SyncCurrentVertexAttributeValues(vaoTwin, programCso);
BindCurrentTextures(textureKeys, currentProgram);
BindCurrentProgramWithResources(currentProgram, textureKeys, MG_Pipe::MGPipeApplier().DrawProgram);
PushNarrowIntegerWidthsForDraw(integerPlan, MG_Pipe::MGPipeApplier().DrawProgram);
BindCurrentProgramWithResources(currentProgram, textureKeys, programCso, programRecord);
PushNarrowIntegerWidthsForDraw(integerPlan, programCso);
// Last: opening the capture span needs the program current and the capture
// buffers bound, and ES rejects most binding changes once it is open.
@@ -1368,19 +1364,9 @@ namespace MobileGL::MG_Backend::DirectGLES {
// (its note says so). The parameter stays for the monolith arm, which is ruling ID-81: that
// build keeps this function's frontend text token for token.
void BindCurrentProgramWithResources(const SharedPtr<MG_State::GLState::ProgramObject>& currentProgram,
const TextureImpl::DrawTextureSyncKeys& keys,
MG_Pipe::MGPipeHandle programCso) {
// P5e (pg): THE HANDLE ARM'S GATE, from the record rather than from the object. Hoisted
// out of the `if` below because the whole body's entry condition is "the program linked
// and has SPIR-V", and on this arm both answers are fields of the descriptor
// (Desc.LinkStatus is ID-88's, Desc.SpirvStatus P4a's).
const MG_Pipe::MGPipeShaderCsoRecord* programRecord = nullptr;
programRecord = PrgramImpl::FindShaderCsoRecord(programCso);
if (programRecord != nullptr && (programRecord->Desc.LinkStatus == 0 || programRecord->Desc.SpirvStatus == 0)) {
programRecord = nullptr;
}
const Bool programUsable = programRecord != nullptr;
if (programUsable) {
const TextureImpl::DrawTextureSyncKeys& keys, MG_Pipe::MGPipeHandle programCso,
const MG_Pipe::MGPipeShaderCsoRecord* programRecord) {
if (programRecord != nullptr) {
#ifdef TRACY_ENABLE
ZoneScopedNC("BindCurrentProgram", TRACY_ZONECOLOR_BACKEND);
#endif
@@ -1559,7 +1545,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
BufferImpl::IsBufferDrawCleanByHandle(entry.Res, backendResource, nullptr)) {
backendResource->drawCleanEpoch = bufferEpoch;
} else {
backendResource = BufferImpl::EnsureBufferResourceForHandle(nullptr, entry.Res);
backendResource = BufferImpl::EnsureBufferResourceForHandle(entry.Res);
}
}
if (backendResource && backendResource->id != 0) {
@@ -1045,7 +1045,8 @@ namespace MobileGL::MG_Backend::DirectGLES {
const auto& color = record.Color[i];
if (color.Res == record.ReadSurface.Res && color.Kind == record.ReadSurface.Kind &&
color.Layered == record.ReadSurface.Layered && color.Level == record.ReadSurface.Level &&
color.Layer == record.ReadSurface.Layer && color.UploadTarget == record.ReadSurface.UploadTarget) {
color.NumViews == record.ReadSurface.NumViews && color.Layer == record.ReadSurface.Layer &&
color.UploadTarget == record.ReadSurface.UploadTarget) {
return static_cast<FramebufferAttachmentType>(static_cast<Int>(FramebufferAttachmentType::Color0) +
static_cast<Int>(i));
}
@@ -103,7 +103,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
BindBufferBaseCached(glTarget, static_cast<GLuint>(i), 0);
continue;
}
auto* backendResource = EnsureBufferResourceForHandle(nullptr, entry.Res);
auto* backendResource = EnsureBufferResourceForHandle(entry.Res);
if (!backendResource || backendResource->id == 0) {
MGLOG_E_ONCE("No backend buffer found for %s binding point %zu (handle {%u, %u}).",
MG_Util::ConvertGLEnumToString(glTarget).c_str(), i, entry.Res.Slot, entry.Res.Gen);
@@ -169,7 +169,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
BindBufferBaseCached(GL_SHADER_STORAGE_BUFFER, static_cast<Uint>(esslBinding), 0);
continue;
}
auto* backendResource = EnsureBufferResourceForHandle(nullptr, entry->Res);
auto* backendResource = EnsureBufferResourceForHandle(entry->Res);
if (!backendResource || backendResource->id == 0) {
MGLOG_E_ONCE("No backend buffer found for atomic counter binding point %d "
"(handle {%u, %u}).",
@@ -82,9 +82,8 @@ namespace MobileGL::MG_Backend::DirectGLES {
// draw surface (NoteDrawSurfaceMoved at each `session.Draw =`). Surface creation and destruction
// also move g_nativeRegistryEpoch, which the size memo keys on as well.
std::atomic<Uint64> g_surfaceSizeEpoch{1};
// Never erased while the process lives: a context teardown marks its tuple dead (Context =
// EGL_NO_CONTEXT) instead of freeing it, so a cached pointer is never dangling between the
// epoch bump and the next resolution.
// Context switches and teardown run under the backend command lock. The registry epoch
// invalidates each thread's cached pointer before its next context lookup.
Vector<NativeContextTuple*>& NativeContexts() {
static Vector<NativeContextTuple*>* contexts = new Vector<NativeContextTuple*>();
return *contexts;
@@ -116,8 +115,15 @@ namespace MobileGL::MG_Backend::DirectGLES {
outKey->SessionKey = 0;
outKey->ShareGroupKey = 0;
const TwinKeyResolver resolver = g_twinKeyResolver.load(std::memory_order_acquire);
if (resolver == nullptr) return false;
return resolver(outKey);
if (t_native.monolithShareGroup != 0) {
outKey->ShareGroupKey = t_native.monolithShareGroup;
return true;
}
return resolver != nullptr && resolver(outKey);
}
Uint64 SetMonolithObjectShareGroup(Uint64 shareGroup) {
return std::exchange(t_native.monolithShareGroup, shareGroup);
}
Uint64 CurrentNativeSessionKey() {
@@ -198,13 +204,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
NativeThreadState& tls = t_native;
Uint64 session = 0;
Uint64 token = 0;
if (tls.forcedValid) {
session = tls.forcedSession;
token = tls.forcedToken;
} else {
const NativeContextKeyResolver resolver = g_nativeContextKeyResolver.load(std::memory_order_acquire);
if (resolver != nullptr) (void)resolver(&session, &token);
}
ResolveNativeKey(session, token);
const Uint64 epoch = g_nativeRegistryEpoch.load(std::memory_order_acquire);
if (tls.activeTuple != nullptr && tls.activeEpoch == epoch && tls.activeSession == session &&
tls.activeToken == token) {
@@ -275,6 +275,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
// The display's one-time initialization. Returns false only when there is no EGL to talk to.
static Bool EnsureDisplayInitialized() {
if (g_EGLFuncs.eglBindAPI) g_EGLFuncs.eglBindAPI(EGL_OPENGL_ES_API);
if (g_Display != EGL_NO_DISPLAY) return true;
if (!g_EGLFuncs.eglGetDisplay) return false;
g_Display = g_EGLFuncs.eglGetDisplay(EGL_DEFAULT_DISPLAY);
@@ -283,7 +284,6 @@ namespace MobileGL::MG_Backend::DirectGLES {
g_Display = EGL_NO_DISPLAY;
return false;
}
if (g_EGLFuncs.eglBindAPI) g_EGLFuncs.eglBindAPI(EGL_OPENGL_ES_API);
return true;
}
@@ -313,7 +313,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
}
// P14 S4: the surface is the SESSION's, not the process's - the tuple that draws to it is
// one of the session's contexts.
const EGLSurface surface = ActiveNativeSession().Draw;
const EGLSurface surface = CurrentContextDrawSurface();
if (!g_EGLFuncs.eglQuerySurface || g_Display == EGL_NO_DISPLAY || surface == EGL_NO_SURFACE) {
return false;
}
@@ -715,8 +715,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
DiagnoseEsprytSlotArm();
}
// RESET NOTIFICATION, decided once per process by its first native context (EnsureNativeContext
// says why). MOBILEGL_ESPRYT_RESET_NOTIFICATION=0 keeps the driver's default.
// Split native contexts agree on one reset strategy. Monolith leaves the driver default.
namespace {
// EGL_EXT_create_context_robustness (eglext.h is not part of this file's include set).
@@ -730,6 +729,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
std::atomic<ResetNotification> g_resetNotification{ResetNotification::Undecided};
Bool ResetNotificationWanted() {
if (MG_Config::Transport == MG_Config::TransportMode::Monolith) return false;
const ResetNotification decided = g_resetNotification.load(std::memory_order_acquire);
if (decided != ResetNotification::Undecided) return decided == ResetNotification::On;
if (const char* value = std::getenv("MOBILEGL_ESPRYT_RESET_NOTIFICATION");
@@ -755,6 +755,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
}
void NoteResetNotificationDecided(Bool used) {
if (MG_Config::Transport == MG_Config::TransportMode::Monolith) return;
ResetNotification expected = ResetNotification::Undecided;
const ResetNotification decided = used ? ResetNotification::On : ResetNotification::Off;
if (g_resetNotification.compare_exchange_strong(expected, decided, std::memory_order_acq_rel))
@@ -766,7 +767,8 @@ namespace MobileGL::MG_Backend::DirectGLES {
} // namespace
Bool NativeContextsNotifyResets() {
return g_resetNotification.load(std::memory_order_acquire) == ResetNotification::On;
return MG_Config::Transport != MG_Config::TransportMode::Monolith &&
g_resetNotification.load(std::memory_order_acquire) == ResetNotification::On;
}
static Bool EnsureNativeContext(NativeContextTuple& tuple, EGLint surfaceBit, NativeWindowType window) {
@@ -862,6 +864,33 @@ namespace MobileGL::MG_Backend::DirectGLES {
return true;
}
Bool BindMonolithNativeContext(Uint64 token, Uint64 shareGroup, EGLSurface surface) {
auto& session = ActiveNativeSession();
const auto* drawable = FindSessionSurfaceLocked(session, surface);
if (drawable == nullptr) return false;
const Uint64 previousToken = std::exchange(t_native.monolithToken, token);
const Uint64 previousGroup = SetMonolithObjectShareGroup(shareGroup);
auto& tuple = ActiveNativeContext();
if (tuple.Context == EGL_NO_CONTEXT) {
tuple.Config = drawable->Config;
tuple.ShareGroupToken = shareGroup;
}
const EGLSurface previousDraw = session.Draw;
const EGLSurface previousRead = session.Read;
if (EnsureNativeContext(tuple, EGL_PBUFFER_BIT, static_cast<NativeWindowType>(0)) &&
SelectSessionSurface(surface) && MakeCurrent()) {
PublishDefaultFramebufferDepthStencilFormat();
return true;
}
session.Draw = previousDraw;
session.Read = previousRead;
t_native.monolithToken = previousToken;
SetMonolithObjectShareGroup(previousGroup);
return false;
}
Bool CreateNativeContextFor(Uint64 contextToken, Uint64 shareGroupToken) {
if (contextToken == 0) return false;
const Uint64 sessionKey = CurrentNativeSessionKey();
@@ -893,7 +922,13 @@ namespace MobileGL::MG_Backend::DirectGLES {
if (contextToken == 0) return;
const std::lock_guard<std::mutex> lock(g_nativeRegistryMutex);
NativeContextTuple* tuple = FindNativeContext(sessionKey, contextToken);
if (tuple == nullptr || tuple->Context == EGL_NO_CONTEXT) return;
if (tuple == nullptr) return;
if (tuple->Context == EGL_NO_CONTEXT) {
std::erase(NativeContexts(), tuple);
delete tuple;
g_nativeRegistryEpoch.fetch_add(1, std::memory_order_acq_rel);
return;
}
#if MOBILEGL_BUILD_DISAGGREGATED
// Its last shared-image reads, fenced while it is still current.
if (t_native.boundContext == tuple->Context) SharedImageImpl::PublishPendingReads();
@@ -915,11 +950,8 @@ namespace MobileGL::MG_Backend::DirectGLES {
t_nativeContextThread.BoundSerial = 0;
}
ForgetNativeContextObjects(tuple->Serial);
tuple->Serial = 0;
tuple->Context = EGL_NO_CONTEXT;
tuple->Config = nullptr;
tuple->Draw = EGL_NO_SURFACE;
tuple->Read = EGL_NO_SURFACE;
std::erase(NativeContexts(), tuple);
delete tuple;
g_nativeRegistryEpoch.fetch_add(1, std::memory_order_acq_rel);
if (g_displayUsers > 0) --g_displayUsers;
// NOT WHILE A SESSION STILL HOLDS SURFACES. eglTerminate destroys them with the display, and
@@ -978,7 +1010,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
}
EGLSurface CurrentContextDrawSurface() {
return ActiveNativeContext().Draw;
return t_native.boundDraw;
}
namespace {
@@ -1064,7 +1096,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
if (t_windowBufferFlushIssued) return;
t_windowBufferFlushIssued = true;
NativeSessionState& session = ActiveNativeSession();
const EGLSurface surface = session.Draw;
const EGLSurface surface = CurrentContextDrawSurface();
if (surface == EGL_NO_SURFACE) return;
{
const std::lock_guard<std::mutex> lock(g_nativeRegistryMutex);
@@ -1076,7 +1108,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
Int32 CurrentDrawBufferAge(Bool damageRegionFollows) {
NativeSessionState& session = ActiveNativeSession();
const EGLSurface surface = session.Draw;
const EGLSurface surface = CurrentContextDrawSurface();
if (surface == EGL_NO_SURFACE || g_Display == EGL_NO_DISPLAY) return 0;
Bool window = false;
Uint64 presents = 0;
@@ -1102,7 +1134,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
Bool SetCurrentDrawDamageRegion(const MG_Util::Damage::Region& region) {
NativeSessionState& session = ActiveNativeSession();
const EGLSurface surface = session.Draw;
const EGLSurface surface = CurrentContextDrawSurface();
if (surface == EGL_NO_SURFACE || g_Display == EGL_NO_DISPLAY) return true;
{
const std::lock_guard<std::mutex> lock(g_nativeRegistryMutex);
@@ -1158,14 +1190,18 @@ namespace MobileGL::MG_Backend::DirectGLES {
if (surface == EGL_NO_SURFACE) return EGL_NO_SURFACE;
NativeSessionState& session = ActiveNativeSession();
const std::lock_guard<std::mutex> lock(g_nativeRegistryMutex);
session.Surfaces.push_back({static_cast<NativeWindowType>(0), surface});
session.Surfaces.push_back({static_cast<NativeWindowType>(0), surface, 0, tuple.Config});
g_nativeRegistryEpoch.fetch_add(1, std::memory_order_acq_rel);
return surface;
}
void ReplaceSessionSurface(EGLSurface previous, EGLSurface replacement) {
if (previous == EGL_NO_SURFACE || replacement == EGL_NO_SURFACE || previous == replacement) return;
static Bool MakeCurrentOnSurface(EGLSurface draw, EGLSurface read);
Bool ReplaceSessionSurface(EGLSurface previous, EGLSurface replacement) {
NativeSessionState& session = ActiveNativeSession();
if (!SessionOwnsSurface(session, previous) || !SessionOwnsSurface(session, replacement)) return false;
if (previous == replacement) return true;
if (t_native.boundDraw == previous && !MakeCurrentOnSurface(replacement, replacement)) return false;
{
const std::lock_guard<std::mutex> lock(g_nativeRegistryMutex);
for (auto* tuple : NativeContexts()) {
@@ -1185,11 +1221,9 @@ namespace MobileGL::MG_Backend::DirectGLES {
NoteDrawSurfaceMoved();
}
if (session.Read == previous) session.Read = replacement;
// The calling thread drew to the old one: draw to the new one from here (the old is then
// no longer current, and its destruction below is immediate).
if (t_native.boundDraw == previous && ActiveNativeContext().Context != EGL_NO_CONTEXT) (void)MakeCurrent();
if (g_EGLFuncs.eglDestroySurface && g_Display != EGL_NO_DISPLAY)
g_EGLFuncs.eglDestroySurface(g_Display, previous);
return true;
}
void DestroySessionSurface(EGLSurface surface) {
@@ -1236,7 +1270,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
void ApplyRequestedSwapInterval() {
if (g_requestedSwapInterval < 0) return;
const EGLSurface surface = ActiveNativeSession().Draw;
const EGLSurface surface = CurrentContextDrawSurface();
if (!g_EGLFuncs.eglSwapInterval || g_Display == EGL_NO_DISPLAY || surface == EGL_NO_SURFACE) return;
const EGLBoolean ok = g_EGLFuncs.eglSwapInterval(g_Display, g_requestedSwapInterval);
MGLOG_D("DirectGLES: applied native swap interval %d (%s)", g_requestedSwapInterval, ok ? "ok" : "failed");
@@ -1318,10 +1352,13 @@ namespace MobileGL::MG_Backend::DirectGLES {
reinterpret_cast<void*>(windowSurface), static_cast<unsigned>(error));
return EGL_NO_SURFACE;
}
ReplaceSessionSurface(windowSurface, placeholder);
// The rebind onto the placeholder failed and the window surface is still current here - EGL
// destroys a current surface only once it is not, and the window goes when this returns.
if (t_native.boundDraw == windowSurface) (void)ReleaseCurrent();
if (!ReplaceSessionSurface(windowSurface, placeholder)) {
// Unbind before retiring a window the platform is about to release.
if (!ReleaseCurrent() || !ReplaceSessionSurface(windowSurface, placeholder)) {
DestroySessionSurface(placeholder);
return EGL_NO_SURFACE;
}
}
return placeholder;
}
@@ -1340,11 +1377,13 @@ namespace MobileGL::MG_Backend::DirectGLES {
NativeSessionState& session = ActiveNativeSession();
{
const std::lock_guard<std::mutex> lock(g_nativeRegistryMutex);
session.Surfaces.push_back({window, surface});
session.Surfaces.push_back({window, surface, 0, tuple.Config});
g_nativeRegistryEpoch.fetch_add(1, std::memory_order_acq_rel);
}
if (placeholder != EGL_NO_SURFACE && SessionOwnsSurface(session, placeholder)) {
ReplaceSessionSurface(placeholder, surface);
if (placeholder != EGL_NO_SURFACE && SessionOwnsSurface(session, placeholder) &&
!ReplaceSessionSurface(placeholder, surface)) {
DestroySessionSurface(surface);
return EGL_NO_SURFACE;
}
// Bound, because the publish below reads the default framebuffer.
if (!BindSessionSurface(surface) || t_native.boundDraw != surface) {
@@ -1358,7 +1397,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
return surface;
}
Bool InitWindowSurface(NativeWindowType window) {
Bool InitWindowSurface(NativeWindowType window, EGLSurface* unbound) {
if (!window) return false;
DiagnoseEsprytSlotArmAtBringUp();
@@ -1366,7 +1405,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
NativeContextTuple& tuple = ActiveNativeContext();
if (!EnsureNativeContext(tuple, EGL_WINDOW_BIT, window)) return false;
DestroyStaleSurfacesOnWindow(window);
if (unbound == nullptr) DestroyStaleSurfacesOnWindow(window);
const EGLSurface surface = g_EGLFuncs.eglCreateWindowSurface(g_Display, tuple.Config, window, nullptr);
if (surface == EGL_NO_SURFACE) {
@@ -1376,7 +1415,11 @@ namespace MobileGL::MG_Backend::DirectGLES {
return false;
}
NativeSessionState& session = ActiveNativeSession();
session.Surfaces.push_back({window, surface});
session.Surfaces.push_back({window, surface, 0, tuple.Config});
if (unbound != nullptr) {
*unbound = surface;
return true;
}
session.Draw = surface;
NoteDrawSurfaceMoved();
session.Read = surface;
@@ -1393,7 +1436,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
return true;
}
Bool InitPbufferSurface(EGLint width, EGLint height) {
Bool InitPbufferSurface(EGLint width, EGLint height, EGLSurface* unbound) {
if (width <= 0 || height <= 0) return false;
DiagnoseEsprytSlotArmAtBringUp();
@@ -1405,7 +1448,11 @@ namespace MobileGL::MG_Backend::DirectGLES {
const EGLSurface surface = g_EGLFuncs.eglCreatePbufferSurface(g_Display, tuple.Config, surfaceAttribs);
if (surface == EGL_NO_SURFACE) return false;
NativeSessionState& session = ActiveNativeSession();
session.Surfaces.push_back({static_cast<NativeWindowType>(0), surface});
session.Surfaces.push_back({static_cast<NativeWindowType>(0), surface, 0, tuple.Config});
if (unbound != nullptr) {
*unbound = surface;
return true;
}
session.Draw = surface;
NoteDrawSurfaceMoved();
session.Read = surface;
@@ -1420,7 +1467,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
surface, tuple.Context, width, height);
return true;
}
// The single backend ES context migrates between app threads (FCL/pojav-style
// The backend turn follows the thread whose binding shadows are active (FCL/pojav-style
// LWJGL hands the EGL context from JVM thread to JVM thread). Ownership must
// live in ONE global slot: a per-thread flag can never be cleared on the
// LOSING thread when another thread takes (or destroys/releases) the context,
@@ -1483,13 +1530,13 @@ namespace MobileGL::MG_Backend::DirectGLES {
}
Bool MakeCurrent() {
// P14 S4: the context comes from the calling thread's tuple (the session's bound token),
// the surface from the session. Both halves used to be file-level singletons.
NativeContextTuple& tuple = ActiveNativeContext();
NativeSessionState& session = ActiveNativeSession();
tuple.Draw = session.Draw;
tuple.Read = session.Read;
if (!g_EGLFuncs.eglMakeCurrent || g_Display == EGL_NO_DISPLAY || session.Draw == EGL_NO_SURFACE ||
return MakeCurrentOnSurface(session.Draw, session.Read);
}
static Bool MakeCurrentOnSurface(EGLSurface draw, EGLSurface read) {
NativeContextTuple& tuple = ActiveNativeContext();
if (!g_EGLFuncs.eglMakeCurrent || g_Display == EGL_NO_DISPLAY || draw == EGL_NO_SURFACE ||
tuple.Context == EGL_NO_CONTEXT) {
MGLOG_E_ONCE("DirectGLES::MakeCurrent failed: EGL display/surface/context is not initialized");
return false;
@@ -1500,15 +1547,17 @@ namespace MobileGL::MG_Backend::DirectGLES {
SharedImageImpl::PublishPendingReads();
}
#endif
if (!g_EGLFuncs.eglMakeCurrent(g_Display, session.Draw, session.Draw, tuple.Context)) {
if (!g_EGLFuncs.eglMakeCurrent(g_Display, draw, draw, tuple.Context)) {
const EGLint error = g_EGLFuncs.eglGetError ? g_EGLFuncs.eglGetError() : EGL_SUCCESS;
MGLOG_E_ONCE("DirectGLES::MakeCurrent failed: native eglMakeCurrent returned error 0x%04x", error);
return false;
}
tuple.Draw = draw;
tuple.Read = read;
g_EGLFuncs.eglSwapBuffersWithDamageEXT = MG_Util::BackendLoader::ResolveSwapBuffersWithDamage(g_EGLFuncs);
InvalidateEglVerifiedStamp();
t_native.boundContext = tuple.Context;
t_native.boundDraw = session.Draw;
t_native.boundDraw = draw;
t_nativeContextThread.BoundSerial = tuple.Serial;
g_backendContextOwnerThread.store(std::this_thread::get_id(), std::memory_order_release);
// The ops table may have been unregistered when a previous ES context was
@@ -1535,6 +1584,12 @@ namespace MobileGL::MG_Backend::DirectGLES {
InvalidateNativeBindingShadows();
}
void BeginMonolithCommands() {
if (g_backendContextOwnerThread.load(std::memory_order_acquire) != std::this_thread::get_id()) {
OnBackendTurnHandoff();
}
}
Bool ReleaseCurrent() {
if (!g_EGLFuncs.eglMakeCurrent || g_Display == EGL_NO_DISPLAY) {
InvalidateEglVerifiedStamp();
@@ -1556,6 +1611,8 @@ namespace MobileGL::MG_Backend::DirectGLES {
t_native.boundContext = EGL_NO_CONTEXT;
t_native.boundDraw = EGL_NO_SURFACE;
t_nativeContextThread.BoundSerial = 0;
t_native.monolithToken = 0;
SetMonolithObjectShareGroup(0);
g_backendContextOwnerThread.store(std::thread::id{}, std::memory_order_release);
return true;
}
@@ -35,7 +35,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
// record's handle, never the frontend binding slot or the client allocator.
const MG_Pipe::MGPipeHandle handle = MG_Pipe::MGPipeApplier().VerbDispatchIndirectBuffer;
if (!MG_Pipe::MGPipeHandleIsNull(handle)) {
auto* resource = EnsureBufferResourceForHandle(nullptr, handle);
auto* resource = EnsureBufferResourceForHandle(handle);
if (resource && resource->id != 0) {
BindBufferId(GL_DISPATCH_INDIRECT_BUFFER, resource->id);
}
@@ -107,16 +107,8 @@ namespace MobileGL::MG_Backend::DirectGLES {
// MGPipeApplier().DispatchProgram, which set_dispatch_program carried. A compute-only
// pipeline has no draw program at all, which is why the two applier fields are separate.
const MG_Pipe::MGPipeHandle dispatchCso = MG_Pipe::MGPipeApplier().DispatchProgram;
PrgramImpl::SyncCurrentProgramByHandle(dispatchCso, false);
// The same gate as the frontend one below, from the record: a dispatch of a program
// the frontend reports unlinked, or one whose SPIR-V never arrived, binds nothing.
const auto* const record = PrgramImpl::FindShaderCsoRecord(dispatchCso);
if (record == nullptr || record->Desc.LinkStatus == 0 || record->Desc.SpirvStatus == 0) {
g_GLESFuncs.glUseProgram(0);
PrgramImpl::g_lastUsedBackendProgramId = 0;
return;
}
const auto* programRecord = PrgramImpl::SyncCurrentProgramByHandle(dispatchCso, false);
if (programRecord == nullptr) return;
// Compute shaders sample textures through the same unit bindings as draws
// (e.g. Flywheel's depth-pyramid downsample reads the depth attachment on
@@ -125,7 +117,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
// Compute programs need the same per-program resource sync as draws:
// uniform-block bindings and sampler units only exist through the API
// because layout(binding) is stripped from the transpiled ESSL.
BindCurrentProgramWithResources(currentProgram, textureKeys, dispatchCso);
BindCurrentProgramWithResources(currentProgram, textureKeys, dispatchCso, programRecord);
}
Bool UpdateTextureBindingAtTarget(GLenum target) {
@@ -387,7 +387,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
const auto backendProgram = GetCurrentBackendProgram();
const Int paramsBinding = backendProgram ? backendProgram->GetIndirectParamsBinding() : -1;
if (paramsBinding >= 0) {
auto* resource = BufferImpl::EnsureBufferResourceForHandle(nullptr, verbBufferHandle);
auto* resource = BufferImpl::EnsureBufferResourceForHandle(verbBufferHandle);
if (resource && resource->id != 0) {
BufferImpl::BindBufferBaseCached(GL_SHADER_STORAGE_BUFFER, static_cast<GLuint>(paramsBinding),
resource->id);
@@ -468,7 +468,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
const auto backendProgram = GetCurrentBackendProgram();
const Int paramsBinding = backendProgram ? backendProgram->GetIndirectParamsBinding() : -1;
if (paramsBinding >= 0) {
auto* resource = BufferImpl::EnsureBufferResourceForHandle(nullptr, verbBufferHandle);
auto* resource = BufferImpl::EnsureBufferResourceForHandle(verbBufferHandle);
if (resource && resource->id != 0) {
BufferImpl::BindBufferBaseCached(GL_SHADER_STORAGE_BUFFER, static_cast<GLuint>(paramsBinding),
resource->id);
@@ -582,8 +582,10 @@ namespace MobileGL::MG_Backend::DirectGLES {
const Bool widenedColorClear =
widenedDrawBuffers != 0 && FramebufferImpl::g_integerColorDrawBufferMask == 0;
GLint clearDrawFbo = 0;
g_GLESFuncs.glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &clearDrawFbo);
if ((outOfRange || widenedColorClear) && clearDrawFbo != 0) {
if (outOfRange || widenedColorClear) {
g_GLESFuncs.glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &clearDrawFbo);
}
if (clearDrawFbo != 0) {
GLint maxDrawBuffers = 0;
GLint clearedCount = 0;
GLint firstDb = -1;
@@ -1135,7 +1137,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
const SizeT commandBytes = commandOffset + static_cast<SizeT>(stride) * static_cast<SizeT>(maxdrawcount - 1) +
sizeof(DrawElementsIndirectCommand);
auto* drawResource = BufferImpl::FindBufferResourceForHandle(applierState.VerbIndirectBuffer);
auto* paramResource = BufferImpl::FindBufferResourceForHandle(applierState.VerbIndirectParameterBuffer);
auto* paramResource = BufferImpl::EnsureBufferResourceForHandle(applierState.VerbIndirectParameterBuffer);
// P8-C: the count is CONSUMED here, so the parameter buffer is made current first
// (a store a shader wrote on this side is read back); the command buffer only gets a
// first copy when it has none - its fields are made current by the executor, and
@@ -1247,7 +1249,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
const SizeT commandBytes = commandOffset + static_cast<SizeT>(stride) * static_cast<SizeT>(maxdrawcount - 1) +
sizeof(DrawArraysIndirectCommand);
auto* drawResource = BufferImpl::FindBufferResourceForHandle(applierState.VerbIndirectBuffer);
auto* paramResource = BufferImpl::FindBufferResourceForHandle(applierState.VerbIndirectParameterBuffer);
auto* paramResource = BufferImpl::EnsureBufferResourceForHandle(applierState.VerbIndirectParameterBuffer);
// P8-C: the count is CONSUMED here, so the parameter buffer is made current first
// (a store a shader wrote on this side is read back); the command buffer only gets a
// first copy when it has none - its fields are made current by the executor, and
@@ -387,9 +387,9 @@ namespace MobileGL::MG_Backend::DirectGLES {
const MG_Pipe::MGPipeShaderCsoRecord* ResolveGlobalConstantsRecordForHandle(MG_Pipe::MGPipeHandle handle,
Uint uboSize);
// `plan` (a draw's) arms the program's narrow-integer seeds when it needs them.
void SyncCurrentProgramByHandle(MG_Pipe::MGPipeHandle cso, Bool forDraw,
const IntegerAttributePlan* plan = nullptr);
// Returns the validated record for resource binding in the same draw or dispatch.
const MG_Pipe::MGPipeShaderCsoRecord* SyncCurrentProgramByHandle(MG_Pipe::MGPipeHandle cso, Bool forDraw,
const IntegerAttributePlan* plan = nullptr);
} // namespace PrgramImpl
// Defined with the surface registry, below.
@@ -398,8 +398,8 @@ namespace MobileGL::MG_Backend::DirectGLES {
void BindCurrentFBO(FramebufferTarget target);
void BindCurrentProgramWithResources(const SharedPtr<MG_State::GLState::ProgramObject>& currentProgram,
const TextureImpl::DrawTextureSyncKeys& keys,
MG_Pipe::MGPipeHandle programCso);
const TextureImpl::DrawTextureSyncKeys& keys, MG_Pipe::MGPipeHandle programCso,
const MG_Pipe::MGPipeShaderCsoRecord* programRecord);
void BindCurrentTextures(const TextureImpl::DrawTextureSyncKeys& keys,
const SharedPtr<MG_State::GLState::ProgramObject>& currentProgram);
@@ -504,8 +504,8 @@ namespace MobileGL::MG_Backend::DirectGLES {
void BindCurrentTextures();
void BindCurrentProgramWithResources(const SharedPtr<MG_State::GLState::ProgramObject>& currentProgram,
const TextureImpl::DrawTextureSyncKeys& keys,
MG_Pipe::MGPipeHandle programCso);
const TextureImpl::DrawTextureSyncKeys& keys, MG_Pipe::MGPipeHandle programCso,
const MG_Pipe::MGPipeShaderCsoRecord* programRecord);
PrgramImpl::BackendProgramObjectImpl* GetCurrentBackendProgram();
@@ -945,6 +945,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
// Presents made on this native surface since it was created: a pbuffer's content is
// the last presented frame once there has been one (its buffer age is then 1).
Uint64 Presents = 0;
EGLConfig Config = nullptr;
};
Vector<SurfaceEntry> Surfaces;
// The surface the session currently draws to / reads from - what a bind to another context
@@ -980,6 +981,8 @@ namespace MobileGL::MG_Backend::DirectGLES {
Bool forcedValid = false;
Uint64 forcedSession = 0;
Uint64 forcedToken = 0;
Uint64 monolithToken = 0;
Uint64 monolithShareGroup = 0;
NativeContextTuple* activeTuple = nullptr;
Uint64 activeEpoch = 0;
Uint64 activeSession = 0;
@@ -1002,7 +1005,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
return;
}
outSession = 0;
outToken = 0;
outToken = t_native.monolithToken;
const NativeContextKeyResolver resolver = g_nativeContextKeyResolver.load(std::memory_order_acquire);
if (resolver != nullptr) (void)resolver(&outSession, &outToken);
}
@@ -1434,7 +1434,8 @@ namespace MobileGL::MG_Backend::DirectGLES {
// and the clamp masks, the broadcast count, ImageUnitFormatsStillMatch and the three
// patch clauses are unchanged - they are backend globals, fb's row and VALUE rows of the
// residual block, none of which this family owns.
void SyncCurrentProgramByHandle(MG_Pipe::MGPipeHandle cso, Bool forDraw, const IntegerAttributePlan* plan) {
const MG_Pipe::MGPipeShaderCsoRecord* SyncCurrentProgramByHandle(MG_Pipe::MGPipeHandle cso, Bool forDraw,
const IntegerAttributePlan* plan) {
#ifdef TRACY_ENABLE
ZoneScopedC(TRACY_ZONECOLOR_BACKEND);
#endif
@@ -1453,7 +1454,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
if (record == nullptr || record->Desc.LinkStatus == 0 || record->Desc.SpirvStatus == 0) {
g_GLESFuncs.glUseProgram(0);
g_lastUsedBackendProgramId = 0;
return;
return nullptr;
}
// REFUSED at a draw, record-only at a dispatch: see the policy's own note.
ResolveFragColorBroadcastCount(forDraw ? BroadcastCountPolicy::RefuseFallback
@@ -1466,7 +1467,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
// than a draw with somebody else's shader.
g_GLESFuncs.glUseProgram(0);
g_lastUsedBackendProgramId = 0;
return;
return record;
}
// Sticky for the twin's lifetime: a draw that needs the seeds rebuilds the program once.
if (plan != nullptr && plan->NeedsSeeds()) twin->NarrowIntegerSeeds().wanted = true;
@@ -1488,6 +1489,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
}
g_currentDrawProgramHandle = cso;
g_currentDrawBackendProgram = twin;
return record;
}
} // namespace PrgramImpl
} // namespace MobileGL::MG_Backend::DirectGLES
@@ -17,14 +17,10 @@ namespace MobileGL::MG_Backend::DirectGLES {
Uint contextGeneration = 0;
};
// Backend timer-query handle: a native GL query object name plus the
// ES context generation it was created under. Stale-generation
// handles read as available with a zero result, and deleting them
// only frees the wrapper (the dead ES context already reclaimed the
// query object).
// Query names belong to the native context that allocated them.
struct GLESQueryObject {
GLuint queryId = 0;
Uint contextGeneration = 0;
Uint64 nativeContextSerial = 0;
// Non-zero for the core (non-timer) query targets - occlusion and transform
// feedback primitives - and then holds the glBeginQuery target, which glEndQuery
// needs back. Their results are counts reachable only through the core
@@ -251,12 +247,12 @@ namespace MobileGL::MG_Backend::DirectGLES {
return nullptr;
}
g_GLESFuncs.glBeginQuery(GL_TIME_ELAPSED, queryId);
return new GLESQueryObject{queryId, g_syncContextGeneration};
return new GLESQueryObject{queryId, CurrentNativeContextSerial()};
}
void EndTimeElapsedQuery(BackendQueryHandle handle) {
const auto* query = static_cast<GLESQueryObject*>(handle);
if (query == nullptr || query->contextGeneration != g_syncContextGeneration ||
if (query == nullptr || query->nativeContextSerial != CurrentNativeContextSerial() ||
!IsBackendContextCurrentOnThisThread() || !g_GLESFuncs.glEndQuery) {
return;
}
@@ -275,7 +271,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
return nullptr;
}
g_GLESFuncs.glQueryCounterEXT(queryId, GL_TIMESTAMP);
return new GLESQueryObject{queryId, g_syncContextGeneration};
return new GLESQueryObject{queryId, CurrentNativeContextSerial()};
}
// The core (non-timer) query targets - occlusion and transform feedback primitives.
@@ -296,12 +292,12 @@ namespace MobileGL::MG_Backend::DirectGLES {
return nullptr;
}
g_GLESFuncs.glBeginQuery(target, queryId);
return new GLESQueryObject{queryId, g_syncContextGeneration, target};
return new GLESQueryObject{queryId, CurrentNativeContextSerial(), target};
}
static void EndCoreQuery(BackendQueryHandle handle) {
const auto* query = static_cast<GLESQueryObject*>(handle);
if (query == nullptr || query->coreTarget == 0 || query->contextGeneration != g_syncContextGeneration ||
if (query == nullptr || query->coreTarget == 0 || query->nativeContextSerial != CurrentNativeContextSerial() ||
!IsBackendContextCurrentOnThisThread() || !g_GLESFuncs.glEndQuery) {
return;
}
@@ -344,7 +340,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
// not own the ES context also reports available: GetQueryResult64
// then returns false and the frontend keeps the handle for a later
// read from the owning thread.
if (query == nullptr || query->contextGeneration != g_syncContextGeneration ||
if (query == nullptr || query->nativeContextSerial != CurrentNativeContextSerial() ||
!IsBackendContextCurrentOnThisThread() || !g_GLESFuncs.glGetQueryObjectuiv) {
return true;
}
@@ -362,7 +358,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
// require them): zero is the FINAL result in all three cases, so
// report it as produced and let the frontend cache it and release
// the handle.
if (query == nullptr || query->contextGeneration != g_syncContextGeneration ||
if (query == nullptr || query->nativeContextSerial != CurrentNativeContextSerial() ||
!g_GLESFuncs.glGetQueryObjectuiv || (query->coreTarget == 0 && !g_GLESFuncs.glGetQueryObjectui64vEXT)) {
return true;
}
@@ -418,7 +414,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
if (query == nullptr) {
return;
}
if (query->contextGeneration == g_syncContextGeneration && IsBackendContextCurrentOnThisThread() &&
if (query->nativeContextSerial == CurrentNativeContextSerial() && IsBackendContextCurrentOnThisThread() &&
g_GLESFuncs.glDeleteQueries) {
g_GLESFuncs.glDeleteQueries(1, &query->queryId);
}
@@ -450,7 +446,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
// and the serials are handed out to every native context of every session in turn, so the
// highest signaled serial says nothing about an older fence of another context still
// pending. A serial is complete when no live fence at or below it is pending.
void PollFrameFences() {
void PollFrameFences(const FrameFence* signaled = nullptr) {
if (!g_GLESFuncs.glGetSynciv) return;
Uint64 lowestPending = ~Uint64{0};
for (FrameFence& slot : g_frameFenceRing) {
@@ -460,8 +456,10 @@ namespace MobileGL::MG_Backend::DirectGLES {
continue;
}
GLint status = GL_SIGNALED;
GLsizei length = 0;
g_GLESFuncs.glGetSynciv(slot.sync, GL_SYNC_STATUS, 1, &length, &status);
if (&slot != signaled) {
GLsizei length = 0;
g_GLESFuncs.glGetSynciv(slot.sync, GL_SYNC_STATUS, 1, &length, &status);
}
if (status == GL_SIGNALED) {
if (g_GLESFuncs.glDeleteSync) g_GLESFuncs.glDeleteSync(slot.sync);
slot.sync = nullptr;
@@ -529,6 +527,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
return false;
}
t_deviceLossLatched = true;
BufferImpl::RevokeResidentBuffersForCurrentSession();
(void)MG_Pipe::MGPipeSessionLatch(MG_Pipe::MGPipeFatalFamily::DeviceLost,
"MGPipe: Fatal{BackendDeviceLost, \"Espryt:%s\"} - this session's EGL "
"context was reset (glGetGraphicsResetStatus 0x%x); the session ends "
@@ -611,7 +610,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
// ONLY A WINDOW SURFACE TAKES RECTANGLES: the platform's swap-with-damage hands them to the
// surface's native window, and a pbuffer has none (Android's dereferences it regardless).
NativeSessionState& session = ActiveNativeSession(); // before the lock: it takes it too
const EGLSurface drawSurface = session.Draw;
const EGLSurface drawSurface = CurrentContextDrawSurface();
Bool windowSurface = false;
if (drawSurface != EGL_NO_SURFACE) {
const std::lock_guard<std::mutex> lock(g_nativeRegistryMutex);
@@ -639,6 +638,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
} else if (g_EGLFuncs.eglSwapBuffers != nullptr) {
mglSwapped = g_EGLFuncs.eglSwapBuffers(g_Display, drawSurface);
}
if (mglSwapped == EGL_TRUE) TextureImpl::EndDrawTextureBatch();
NoteDrawSurfaceMoved(); // a window surface takes a new size at its swap
if (drawSurface != EGL_NO_SURFACE) {
const std::lock_guard<std::mutex> lock(g_nativeRegistryMutex);
@@ -653,6 +653,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
// the same bound on the ES driver: after presenting S, wait for S+1-N to complete. The
// platform's own queueBuffer throttle already waits for S-1, so only N = 1 is stricter
// than what Android does by itself; larger N is the same contract stated, not a change.
const FrameFence* signaled = nullptr;
const Uint32 framesInFlight = MG_Config::Features.FramesInFlight;
if (presentedSerial != 0 && framesInFlight != 0 && framesInFlight < static_cast<Uint32>(kFrameFenceRingDepth) &&
g_GLESFuncs.glClientWaitSync && presentedSerial + 1 > framesInFlight) {
@@ -660,11 +661,15 @@ namespace MobileGL::MG_Backend::DirectGLES {
const FrameFence& oldest = g_frameFenceRing[target % kFrameFenceRingDepth];
if (oldest.sync && oldest.serial == target && oldest.contextGeneration == g_syncContextGeneration) {
constexpr Uint64 kFramesInFlightWaitNs = 1000ull * 1000 * 1000;
(void)g_GLESFuncs.glClientWaitSync(oldest.sync, GL_SYNC_FLUSH_COMMANDS_BIT, kFramesInFlightWaitNs);
const GLenum status =
g_GLESFuncs.glClientWaitSync(oldest.sync, GL_SYNC_FLUSH_COMMANDS_BIT, kFramesInFlightWaitNs);
if (status == GL_ALREADY_SIGNALED || status == GL_CONDITION_SATISFIED) {
signaled = &oldest;
}
}
}
if (canFence) PollFrameFences();
if (canFence) PollFrameFences(signaled);
// After the watermark advanced: retire grown-away ring stores and record the
// frame's ring high-water marks for slot reclamation.
@@ -7,9 +7,50 @@
// End of Source File Header
#include "DirectGLESInternal.h"
#include "DrawTextureReads.h"
namespace MobileGL::MG_Backend::DirectGLES {
namespace TextureImpl {
namespace {
PerNativeContext<DrawTextureReads> g_drawTextureReads;
} // namespace
void NoteDrawTextureFramebuffer(Uint framebuffer) {
if (CurrentNativeContextSerial() != 0) g_drawTextureReads.Current().BindFramebuffer(framebuffer);
}
void DeleteDrawTextureFramebuffer(Uint framebuffer) {
if (CurrentNativeContextSerial() != 0) g_drawTextureReads.Current().DeleteFramebuffer(framebuffer);
}
void EndDrawTextureBatch() {
if (CurrentNativeContextSerial() != 0) g_drawTextureReads.Current().EndBatch();
}
Bool WasTextureReadInDrawBatch(MG_Pipe::MGPipeHandle storage) {
return CurrentNativeContextSerial() != 0 && g_drawTextureReads.Current().WasRead(storage.Slot, storage.Gen);
}
void NoteDrawTextureReads() {
if (CurrentNativeContextSerial() == 0) return;
auto& reads = g_drawTextureReads.Current();
const auto& state = MG_Pipe::MGPipeApplier();
if (!reads.NeedsSamplerWalk(state.ContextSerial, state.SamplerViewsSerial)) return;
const SizeT end = std::min<SizeT>(static_cast<SizeT>(state.SamplerViewStart) + state.SamplerViewCount,
state.BoundSamplerViews.size());
for (SizeT unit = state.SamplerViewStart; unit < end; ++unit) {
const auto* texture = PipeTextureRecordForHandle(state.BoundSamplerViews[unit].Texture);
if (!texture) continue;
// A sampler view and an update to its parent address the same texture storage.
if (const auto* storage = PipeTextureStorageRecordForRecord(*texture)) {
const auto handle = storage->Desc.Resource;
reads.NoteRead(handle.Slot, handle.Gen);
}
}
reads.RecordSamplerWalk(state.ContextSerial, state.SamplerViewsSerial);
}
// Identity snapshot of what one texture unit has bound: the object in every binding
// slot plus the unit's sampler object. This - not the context's texture bind
// generation - is what the per-draw texture memos key on: the generation also bumps
@@ -0,0 +1,68 @@
// MobileGL - MobileGL/MG_Backend/DirectGLES/DrawTextureReads.h
// Copyright (c) 2025-2026 MobileGL-Dev
// Licensed under the GNU Lesser General Public License v3.0:
// https://www.gnu.org/licenses/gpl-3.0.txt
// https://www.gnu.org/licenses/lgpl-3.0.txt
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
#pragma once
#include <cstdint>
#include <vector>
namespace MobileGL::MG_Backend::DirectGLES::TextureImpl {
// One instance per native context. Slot generations distinguish reused texture names,
// and batch stamps let us discard a batch without walking its texture slots.
// This upload heuristic follows sampler reads from offscreen draws and the framebuffer
// changes observed by BindCurrentFBO. Compute dispatches do not record reads here.
class DrawTextureReads {
public:
void BindFramebuffer(std::uint32_t framebuffer) {
if (m_drawFramebuffer == framebuffer) return;
m_drawFramebuffer = framebuffer;
EndBatch();
}
void DeleteFramebuffer(std::uint32_t framebuffer) {
if (framebuffer == m_drawFramebuffer) BindFramebuffer(0);
}
void EndBatch() {
m_recordedSamplers = false;
if (++m_batch == 0) {
m_reads.clear();
m_batch = 1;
}
}
bool NeedsSamplerWalk(std::uint64_t context, std::uint64_t views) const {
return m_drawFramebuffer != 0 && (!m_recordedSamplers || context != m_context || views != m_views);
}
void RecordSamplerWalk(std::uint64_t context, std::uint64_t views) {
m_recordedSamplers = true;
m_context = context;
m_views = views;
}
void NoteRead(std::uint32_t slot, std::uint32_t generation) {
if (slot >= m_reads.size()) m_reads.resize(static_cast<std::size_t>(slot) + 1);
m_reads[slot] = Stamp(generation);
}
bool WasRead(std::uint32_t slot, std::uint32_t generation) const {
return m_drawFramebuffer != 0 && slot < m_reads.size() && m_reads[slot] == Stamp(generation);
}
private:
std::uint64_t Stamp(std::uint32_t generation) const { return (std::uint64_t{m_batch} << 32) | generation; }
std::uint32_t m_drawFramebuffer = 0;
std::uint32_t m_batch = 1;
bool m_recordedSamplers = false;
std::uint64_t m_context = 0;
std::uint64_t m_views = 0;
std::vector<std::uint64_t> m_reads;
};
} // namespace MobileGL::MG_Backend::DirectGLES::TextureImpl
+4 -6
View File
@@ -79,7 +79,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
#if MOBILEGL_BUILD_DISAGGREGATED
// P12: raised only while DropEveryTwinForEndedServerSession empties the twin tables, on the
// apply thread that is the only reader of the twins (Managers.h).
Bool g_serverSessionTwinTeardown = false;
thread_local Bool g_serverSessionTwinTeardown = false;
#endif
} // namespace
@@ -231,10 +231,8 @@ namespace MobileGL::MG_Backend::DirectGLES {
buckets += SamplerImpl::g_backendSamplerObjects.DropBucketsOfSession(key.SessionKey);
buckets += TextureImpl::g_backendTextureObjects.DropBucketsOfSession(key.SessionKey);
buckets += RenderbufferImpl::g_backendRenderbufferObjects.DropBucketsOfSession(key.SessionKey);
buckets += BufferImpl::g_backendBufferResources.DropBucketsOfSession(key.SessionKey);
MGLOG_I("DirectGLES: the ended server session dropped %u twin group(s) across eight kinds "
"(no driver call); the other sessions in this process keep theirs",
buckets);
buckets += BufferImpl::DropBuffersForEndedServerSession(&key);
MGLOG_I("DirectGLES: retired %u twin groups of the ended server session", buckets);
} else {
SamplerViewImpl::g_backendSamplerViews.ResetBuckets();
FramebufferImpl::g_backendFramebufferObjects.ResetBuckets();
@@ -243,7 +241,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
SamplerImpl::g_backendSamplerObjects.ResetBuckets();
TextureImpl::g_backendTextureObjects.ResetBuckets();
RenderbufferImpl::g_backendRenderbufferObjects.ResetBuckets();
BufferImpl::g_backendBufferResources.ResetBuckets();
BufferImpl::DropBuffersForEndedServerSession(nullptr);
}
// P12 review fix (major): AND THE UNIT SHADOWS THAT POINT AT THEM. A texture or sampler twin
// scrubs itself out of g_boundTexturesCache / g_boundSamplersCache in its destructor - but
+34 -19
View File
@@ -272,11 +272,16 @@ namespace MobileGL::MG_Backend::DirectGLES {
// re-pushes index 0's state. Takes the count so it can do nothing at all in the common case.
void EndViewportRoutingPasses(Uint passCount);
namespace TextureImpl {
void NoteDrawTextureReads();
} // namespace TextureImpl
// Issue one draw, replayed once per viewport-routing pass. Every application-visible draw
// entry point wraps its native glDraw* call in this; the internal blit and clear helpers
// deliberately do not, because they bind their own programs, which never route.
template <typename IssueDraw>
inline void ForEachViewportRoutingPass(IssueDraw&& issue) {
TextureImpl::NoteDrawTextureReads();
const Uint passCount = BeginViewportRoutingPasses();
for (Uint pass = 0; pass < passCount; ++pass) {
if (passCount > 1) {
@@ -787,7 +792,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
Vector<Uint8> bytes;
};
Vector<PendingResidentWrite> pendingResidentWrites;
std::mutex pendingMutex;
mutable std::mutex pendingMutex;
// Buffer-mutation epoch (see CurrentBufferMutationEpoch) at which this
// resource last probed IsBufferDrawClean == true, 0 = never (epochs start
// at 1). Written only on the draw thread; per-draw resource consumers
@@ -897,12 +902,15 @@ namespace MobileGL::MG_Backend::DirectGLES {
// substitution, the multi-draw index rebase): the R-11 staged copy, or - for a T0 store,
// which has none - this server's own coherent map of the client's AHardwareBuffer, read
// exactly as the monolith arm reads the adopted map through MappedData().
Uint CurrentBufferContextGeneration();
inline const Uint8* SplitHostBytes(const GLESBufferResource& resource) {
if (resource.hostBytes != nullptr) return resource.hostBytes;
// P13 W4a: any coherent persistent store, not only T0's - monolith's record arm donates
// its maps in-process (Ops_H_MapPersistent), and such a store keeps no shadow at all.
// Under split the wire's map_persistent declines, so there this is still T0 alone.
return resource.persistentMapped && resource.persistentPtr != nullptr
return resource.persistentMapped && resource.persistentPtr != nullptr &&
resource.contextGeneration == CurrentBufferContextGeneration()
? static_cast<const Uint8*>(resource.persistentPtr)
: nullptr;
}
@@ -1034,8 +1042,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
// at the definition; passing null means "no live map", not "unknown".
Bool IsBufferDrawCleanByHandle(MG_Pipe::MGPipeHandle res, const GLESBufferResource* resource,
const MG_State::GLState::BufferObject* frontend);
GLESBufferResource* EnsureBufferResourceForHandle(
const SharedPtr<MG_State::GLState::BufferObject>& bufferObject, MG_Pipe::MGPipeHandle res);
GLESBufferResource* EnsureBufferResourceForHandle(MG_Pipe::MGPipeHandle res);
// The applier's stored extent for this resource, 0 when it has no record. The one
// thing outside BufferImpl that needs it is the fp64 narrowing, whose source extent
@@ -1045,12 +1052,6 @@ namespace MobileGL::MG_Backend::DirectGLES {
// record. It is what the narrowed-fp64 memo keys its freshness on now that the
// frontend change serial is gone from the backend's view.
Uint64 ResourceSerialForHandle(MG_Pipe::MGPipeHandle res);
// The ES context generation a twin's driver id must carry to be current. Its one
// consumer is the draw-clean probe's unit test, which has to build a twin that answers
// CLEAN to every question except the one under test - a case that cannot go red for
// that question otherwise. Push-only, like the rest of this block.
Uint CurrentBufferContextGeneration();
// Registered as the frontend's BufferBackendOps at backend init and on
// every MakeCurrent (the ES context can be destroyed and recreated, e.g.
// by the trace replayer's probe context).
@@ -1062,6 +1063,9 @@ namespace MobileGL::MG_Backend::DirectGLES {
// process-wide share group): drops only the ending session's own staged bytes.
void OnServerSessionEndedWithOthersLive();
void OnBackendContextDestroyed();
void OnShareGroupDestroyed(Uint64 sessionKey, Uint64 shareGroupToken);
Uint32 DropBuffersForEndedServerSession(const TwinKey* key);
void RevokeResidentBuffersForCurrentSession();
// Deletes GL buffers whose owning frontend objects died (possibly on a
// thread without a current ES context). Called from draw-time sync.
@@ -1422,6 +1426,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
ResolvedDrawBuffers m_resolvedDrawBuffers;
PendingAttribValueMask m_pendingAttribValueMask;
Uint m_backendVAOId = 0;
Uint64 m_nativeContextSerial = 0;
Array<Uint, MG_State::GLState::VertexArrayObject::MAX_VERTEX_ATTRIBS> m_clientAttributeBufferIds;
// Scratch stores for the buffer-backed GL_DOUBLE narrowing and BGRA swizzle. Deliberately separate
// from m_clientAttributeBufferIds: that one holds the per-draw upload of a
@@ -1832,6 +1837,14 @@ namespace MobileGL::MG_Backend::DirectGLES {
private:
void RecreateBackendTexture();
// SyncMipmapsToBackend's packed path for storage that is unchanged and not sampled in
// the current draw batch. It commits every eligible level or leaves them all pending.
void TryPackedLevelUploads(MG_State::GLState::TextureObjectMipmap* textureMipmapObject,
const MG_Pipe::MGPipeResourceRecord* pushedStorage,
MG_Pipe::MGPipeHandle pushedRes, GLenum target,
const Vector<TextureUploadTarget>& uploadTargets, SizeT mipmapCount,
TextureInternalFormat storageFormat, GLenum glInternalFormat, GLenum glFormat,
GLenum glType);
Uint m_backendTextureId = 0;
// A SECOND buffer-texture name over the SAME buffer object, viewed in the split's
@@ -1878,15 +1891,11 @@ namespace MobileGL::MG_Backend::DirectGLES {
Uint64 m_sharedImageId = 0;
SharedImageImpl::EglImageRef m_sharedImage;
#endif
// Whether the driver texture may hold texels the shadow never saw. Set the first time
// anything other than a texel upload can write it - an application framebuffer
// attachment, a writable image binding, a copy or blit into it, a driver-side mipmap
// generation - and never cleared. Until then the driver holds, outside a level's
// pending writes, exactly the shadow bytes it was last sent, so those writes may go up
// as their union box (one unpack-ring job, which is what Mali needs); from then on
// only the texels the client wrote may go up, since the shadow is stale everywhere
// else. See SyncMipmapsToBackend.
// Once a framebuffer, image binding, copy, or mipmap generation may write this texture,
// the CPU shadow can be stale. Upload only the texels the client wrote from then on.
Bool m_driverMayHoldGpuWrites = false;
// Retry the packed path when the texture's storage changes.
Bool m_packedUploadRejected = false;
// Latches the "this driver has no buffer textures" report to once per texture. The
// report is emitted from the respecify path, which bails before recording the state
// it was asked to apply - so without the latch the texture stays permanently dirty
@@ -2106,6 +2115,10 @@ namespace MobileGL::MG_Backend::DirectGLES {
// issued since the last one. Sampled access from a draw does not take it: that is the
// order every driver keeps on its own, and it is the per-draw hot path.
void NoteInPlaceTextureUpload();
void NoteDrawTextureFramebuffer(Uint framebuffer);
void DeleteDrawTextureFramebuffer(Uint framebuffer);
void EndDrawTextureBatch();
Bool WasTextureReadInDrawBatch(MG_Pipe::MGPipeHandle storage);
// The barrier bits owed for the uploads noted since the last call (0 when none), and
// the note cleared: the caller issues them, folded into any barrier of its own.
GLbitfield TakeInPlaceTextureUploadBarrierBits();
@@ -2163,7 +2176,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
private:
Uint m_backendFBOId = 0;
Uint m_contextGeneration = 0;
Uint64 m_nativeContextSerial = 0;
/* this will save buffers in its original form,
reversion, absence or not consecutive are all allowed, as long as GL spec allows it
@@ -2673,6 +2686,8 @@ namespace MobileGL::MG_Backend::DirectGLES {
// build's (ProgramBuildSource), so the pull build compiles the very same text
// against a ProgramObject and G1's byte identity survives.
Uint GetExternalIndex() const { return Identity; }
// GL_OVR_multiview's num_views of the vertex stage, 0 without one.
Int GetVertexNumViews() const { return Link ? Link->vsNumViews : 0; }
Bool GetLinkStatus() const { return Linked; }
Bool GetSpirvStatus() const { return SpirvUsable; }
Bool GetSpirvValidationEnabled() const { return SpirvValidationEnabled; }
+175 -211
View File
@@ -8,6 +8,8 @@
#include "ManagersInternal.h"
#include <MG_Pipe/MGPipeCallbacks.h>
namespace MobileGL::MG_Backend::DirectGLES {
constexpr Bool PREFER_MAP_BUFFER_RANGE_FOR_BUFFER_SYNC = false;
@@ -251,11 +253,14 @@ namespace MobileGL::MG_Backend::DirectGLES {
// why the test is on initialData rather than on size.
MG_Util::PipeStats::AddBytes(MG_Util::PipeStats::ByteClass::StageBuffer, static_cast<Uint64>(size));
}
resource.storageSize = size;
resource.storageInitialized = true;
resource.pendingRespecify = false;
resource.pendingRanges.clear();
resource.pendingResidentWrites.clear();
{
const std::lock_guard<std::mutex> lock(resource.pendingMutex);
resource.storageSize = size;
resource.storageInitialized = true;
resource.pendingRespecify = false;
resource.pendingRanges.clear();
resource.pendingResidentWrites.clear();
}
resource.syncedChangeSerial = syncedSerial;
// A GROWN store keeps its indexed bindings, and BindBufferBaseCached skips a
// rebind whenever the shadow already records this id at that index - so on a
@@ -335,6 +340,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
void* ahb = nullptr;
Uint generation = 0;
};
std::mutex g_t0RetiredMutex;
Vector<T0RetiredImport> g_t0Retired;
// T0 twins whose destroy found no current context: Ops_OnDestroy queued them on the
// deferred-release list and keeps a second reference here, so the reference is
@@ -342,9 +348,10 @@ namespace MobileGL::MG_Backend::DirectGLES {
// g_deferredBufferReleasesMutex, like the list it shadows.
Vector<SharedPtr<BackendBufferResource>> g_t0DeferredDestroys;
std::atomic<Bool> g_hasT0DeferredDestroys{false};
Uint64 g_t0ImportsLive = 0;
std::atomic<Uint64> g_t0ImportsLive{0};
void SweepT0Retired(Bool contextGone) {
const std::lock_guard<std::mutex> lock(g_t0RetiredMutex);
for (SizeT i = 0; i < g_t0Retired.size();) {
T0RetiredImport& retired = g_t0Retired[i];
const Bool sameContext =
@@ -380,8 +387,11 @@ namespace MobileGL::MG_Backend::DirectGLES {
retired.fence = g_GLESFuncs.glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0);
}
resource.externalAhb = nullptr;
if (g_t0ImportsLive > 0) --g_t0ImportsLive;
g_t0Retired.push_back(retired);
g_t0ImportsLive.fetch_sub(1, std::memory_order_relaxed);
{
const std::lock_guard<std::mutex> lock(g_t0RetiredMutex);
g_t0Retired.push_back(retired);
}
SweepT0Retired(false);
}
#else
@@ -740,6 +750,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
}
if (!resource) return; // lazy: the ensure path full-uploads on creation
if (resource->immutableStorage) {
const std::lock_guard<std::mutex> lock(resource->pendingMutex);
resource->persistentMapped = false;
resource->persistentPtr = nullptr;
if (resource->id != 0 && CanTouchGLNow() &&
@@ -768,12 +779,14 @@ namespace MobileGL::MG_Backend::DirectGLES {
return;
}
if (!CanTouchGLNow() || resource->id == 0 || resource->contextGeneration != g_bufferContextGeneration) {
const std::lock_guard<std::mutex> lock(resource->pendingMutex);
resource->pendingRespecify = true;
resource->pendingRanges.clear();
resource->pendingResidentWrites.clear();
return;
}
if (desc.Width == 0) {
const std::lock_guard<std::mutex> lock(resource->pendingMutex);
resource->storageInitialized = false;
resource->storageSize = 0;
resource->pendingRespecify = false;
@@ -840,7 +853,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
if (CanTouchGLNow() &&
(resource->id == 0 || !resource->storageInitialized || resource->pendingRespecify ||
resource->contextGeneration != g_bufferContextGeneration)) {
resource = EnsureBufferResourceForHandle(nullptr, res);
resource = EnsureBufferResourceForHandle(res);
}
if (resource != nullptr && CanTouchGLNow() && resource->id != 0 && resource->storageInitialized &&
!resource->persistentMapped && !resource->pendingRespecify &&
@@ -917,10 +930,14 @@ namespace MobileGL::MG_Backend::DirectGLES {
const SizeT size = static_cast<SizeT>(MG_Pipe::MGPipeSubDataBufferSize(record));
auto* resource = FindBufferResourceForHandle(res);
if (!resource || size == 0 || bytes == nullptr) return;
// DELIBERATELY not stored as hostBytes: these are the application's staging
// store and are valid for the duration of the call only (BufferObject.h:84-85),
// which is exactly why they are COPIED here rather than referenced later.
const std::lock_guard<std::mutex> lock(resource->pendingMutex);
if (resource->contextGeneration != g_bufferContextGeneration || resource->id == 0 ||
!resource->persistentMapped || resource->persistentPtr == nullptr ||
!resource->storageInitialized || resource->pendingRespecify || offset > resource->storageSize ||
size > resource->storageSize - offset) {
return;
}
// The caller owns the temporary input span; the queued write owns a copy.
auto& write = resource->pendingResidentWrites.emplace_back();
write.offset = offset;
const auto* source = static_cast<const Uint8*>(bytes);
@@ -997,86 +1014,52 @@ namespace MobileGL::MG_Backend::DirectGLES {
resource->syncedChangeSerial = ResourceSerialOf(res);
}
void Ops_H_Readback(MG_Pipe::MGPipeHandle res, const MG_Pipe::MGPReadback& record) {
// An empty capture may conservatively request a writeback before
// any draw materialized this buffer. Resolve its staged resource
// exactly as a GPU consumer would, then return the real bytes.
auto* resource = EnsureBufferResourceForHandle(nullptr, res);
if (!resource || resource->id == 0 || !resource->storageInitialized) return;
if (!CanTouchGLNow() || resource->contextGeneration != g_bufferContextGeneration) return;
if (resource->persistentMapped) {
// Queued resident SubData bytes land first (GPU-ordered), then the finish
// makes them - and any shader writes already queued on this context -
// visible through the coherent mapping the reads use. There is no backend
// copy to read back in this case.
DrainResidentWritesNow(*resource);
if (g_GLESFuncs.glFinish) g_GLESFuncs.glFinish();
return;
Bool Ops_H_Readback(MG_Pipe::MGPipeHandle res, const MG_Pipe::MGPReadback& record) {
// Check the context before ensure, which may allocate driver storage.
if (!CanTouchGLNow()) return false;
auto* resource = EnsureBufferResourceForHandle(res);
if (!resource || resource->id == 0 || !resource->storageInitialized || resource->pendingRespecify ||
resource->contextGeneration != g_bufferContextGeneration) {
return false;
}
if (!g_GLESFuncs.glMapBufferRange || !g_GLESFuncs.glUnmapBuffer) return;
// The map below starts at record.Offset where the legacy arm mapped at literal
// zero, so the clamp has to be against what is left of the BACKEND store past
// that offset: the applier's BufferRangeFault checked the range against
// Desc.Width, and a store that is smaller than the descriptor (a respecify the
// backend has not applied yet) would otherwise be mapped past its end.
const SizeT readOffset = static_cast<SizeT>(record.Offset);
if (readOffset >= resource->storageSize) return;
const SizeT size = std::min<SizeT>(static_cast<SizeT>(record.Size), resource->storageSize - readOffset);
if (size == 0) return;
if (record.Size == 0 || record.Offset > resource->storageSize ||
record.Size > resource->storageSize - record.Offset) {
return false;
}
if (resource->persistentMapped) {
if (resource->persistentPtr == nullptr || !g_GLESFuncs.glFinish) return false;
// The client already owns the coherent bytes. Wait for all queued GPU writes.
DrainResidentWritesNow(*resource);
g_GLESFuncs.glFinish();
return true;
}
const auto writeback = MG_Pipe::gMGPipeCallbacks.OnBufferWriteback;
if (!g_GLESFuncs.glMapBufferRange || !g_GLESFuncs.glUnmapBuffer || writeback == nullptr) return false;
// Queued app writes must land in the backend store before it is read back, or
// the writeback below would revert them in the shadow. Under split every queued
// range must lie inside the server shadow's staged coverage first (R-11 / the
// M-6 ruling): the drain's tier-1 map would otherwise declare live GPU bytes
// dead over a range nothing staged.
MGL_SERVER_STAGED_REQUIRE_PENDING(*resource, resource->hostBytes, ResourceWidthOf(res),
"readback_flush_pending");
FlushPendingRangesFrom(*resource, resource->hostBytes, ResourceWidthOf(res));
BindBufferId(TempBufferTarget, resource->id);
void* mapped = g_GLESFuncs.glMapBufferRange(TempBufferTarget, (GLintptr)record.Offset,
static_cast<GLsizeiptr>(size), GL_MAP_READ_BIT);
const SizeT size = static_cast<SizeT>(record.Size);
const auto* mapped = static_cast<const Uint8*>(
g_GLESFuncs.glMapBufferRange(TempBufferTarget, static_cast<GLintptr>(record.Offset),
static_cast<GLsizeiptr>(size), GL_MAP_READ_BIT));
if (mapped == nullptr) {
MGLOG_E_ONCE("Ops_H_Readback: glMapBufferRange(read) failed for buffer %u", resource->id);
return;
MGLOG_E_ONCE("Buffer readback: glMapBufferRange failed for buffer %u", resource->id);
return false;
}
// The reverse channel replaces BufferObject::WritebackFromBackend: the backend
// no longer reaches into the frontend's address space, it ANSWERS. In monolith
// the client's implementation is one call away, so SyncGpuWrites' caller still
// sees the reconciled shadow on return, exactly as before.
//
// THE ORDER FROM HERE IS A CORRECTNESS RULE, NOT A PREFERENCE
// (ARCHITECTURE.md 8.2: "the writeback's epoch bump must be applied by the server before any
// later command that reads that handle; the reverse channel needs the same ordering guarantees as the
// forward channel"):
// 1. writeback - the client's shadow takes the bytes,
// 2. unmap - the read mapping goes away,
// 3. serial stamp- syncedChangeSerial catches up with the record, so the next
// draw does not re-upload the readback over itself,
// 4. epoch bump - in Ops_H_ReadbackTracked, i.e. strictly AFTER 1-3, so a
// draw-clean memo re-probed by the bump can never observe a
// half-reconciled resource. The bump must NEVER move earlier.
if (MG_Pipe::gMGPipeCallbacks.OnBufferWriteback != nullptr) {
MG_Pipe::gMGPipeCallbacks.OnBufferWriteback(res, record.Offset,
MG_Pipe::MGPBlobRef{reinterpret_cast<Uint64>(mapped),
static_cast<Uint64>(size),
MG_Pipe::kMGHostSpanSegNone, 0});
} else {
MGLOG_E_ONCE("Ops_H_Readback: no reverse channel is installed, so the GPU-written bytes of "
"buffer %u cannot reach the client shadow",
resource->id);
}
g_GLESFuncs.glUnmapBuffer(TempBufferTarget);
// The shadow now matches the backend byte for byte; without this the next draw
// would see a newer serial and re-upload the readback over it.
// If unmap reports corruption, discard the copy before publishing any bytes.
const Vector<Uint8> bytes(mapped, mapped + size);
if (g_GLESFuncs.glUnmapBuffer(TempBufferTarget) == GL_FALSE) return false;
writeback(res, record.Offset,
MG_Pipe::MGPBlobRef{reinterpret_cast<Uint64>(bytes.data()), record.Size,
MG_Pipe::kMGHostSpanSegNone, 0});
resource->syncedChangeSerial = ResourceSerialOf(res);
// P13 W4a: on monolith's record arm the base this twin reads IS the shadow the
// writeback just filled, so a whole-store readback is also the refresh
// SplitHostBytesForCpuRead would owe. (A copying store's copy is not the
// client's shadow, and keeps its mark.)
if (MG_Config::RecordArmAliasesFrontend() && readOffset == 0 && size >= ResourceWidthOf(res)) {
if (MG_Config::RecordArmAliasesFrontend() && record.Offset == 0 && size == ResourceWidthOf(res)) {
resource->serverGpuWritten = false;
}
return true;
}
void Ops_H_Destroy(MG_Pipe::MGPipeHandle res) {
@@ -1218,9 +1201,10 @@ namespace MobileGL::MG_Backend::DirectGLES {
Ops_H_FlushRange(res, record, bytes);
BumpBufferMutationEpoch();
}
void Ops_H_ReadbackTracked(MG_Pipe::MGPipeHandle res, const MG_Pipe::MGPReadback& record) {
Ops_H_Readback(res, record);
Bool Ops_H_ReadbackTracked(MG_Pipe::MGPipeHandle res, const MG_Pipe::MGPReadback& record) {
if (!Ops_H_Readback(res, record)) return false;
BumpBufferMutationEpoch();
return true;
}
void Ops_H_DestroyTracked(MG_Pipe::MGPipeHandle res) {
Ops_H_Destroy(res);
@@ -2037,6 +2021,58 @@ namespace MobileGL::MG_Backend::DirectGLES {
g_hasDeferredBufferReleases.store(false, std::memory_order_release);
}
namespace {
void InvalidateResidentBacking(MG_Pipe::MGPipeHandle handle, GLESBufferResource& resource) {
const std::lock_guard<std::mutex> lock(resource.pendingMutex);
if (resource.persistentPtr != nullptr && resource.externalAhb == nullptr) {
MG_Pipe::MGPipeRevokeResidentBuffer(handle, resource.persistentPtr);
}
resource.persistentMapped = false;
resource.persistentPtr = nullptr;
resource.pendingResidentWrites.clear();
}
void RetireBufferTwin(MG_Pipe::MGPipeHandle handle, const SharedPtr<GLESBufferResource>& twin) {
InvalidateResidentBacking(handle, *twin);
MGL_SERVER_STAGED_DROP(*twin);
twin->hostBytes = nullptr;
twin->storageInitialized = false;
// Session teardown can still have a live native share group. Follow the
// normal driver-deletion and import-retirement paths in that case.
if (twin->id != 0 || twin->externalAhb != nullptr)
Ops_OnDestroy(SharedPtr<BackendBufferResource>(twin));
}
} // namespace
void OnShareGroupDestroyed(Uint64 sessionKey, Uint64 shareGroupToken) {
const TwinKey dying{sessionKey, shareGroupToken};
g_backendBufferResources.ForEachBucket(
[&](const TwinKey& key, MG_Pipe::MGPipeHandle handle, const SharedPtr<GLESBufferResource>& twin) {
if (key == dying) RetireBufferTwin(handle, twin);
});
g_backendBufferResources.Drop(dying);
}
Uint32 DropBuffersForEndedServerSession(const TwinKey* key) {
g_backendBufferResources.ForEachBucket(
[&](const TwinKey& bucket, MG_Pipe::MGPipeHandle handle, const SharedPtr<GLESBufferResource>& twin) {
if (key == nullptr || bucket.SessionKey == key->SessionKey) RetireBufferTwin(handle, twin);
});
if (key != nullptr) return g_backendBufferResources.DropSession(key->SessionKey);
const auto buckets = static_cast<Uint32>(g_backendBufferResources.BucketCount());
g_backendBufferResources.Reset();
return buckets;
}
void RevokeResidentBuffersForCurrentSession() {
const Uint64 sessionKey = CurrentNativeSessionKey();
g_backendBufferResources.ForEachBucket(
[&](const TwinKey& key, MG_Pipe::MGPipeHandle handle, const SharedPtr<GLESBufferResource>& twin) {
if (key.SessionKey == sessionKey) InvalidateResidentBacking(handle, *twin);
});
BumpBufferMutationEpoch();
}
void OnServerSessionEndedWithOthersLive() {
// Only what belongs to the ending session: its staged bytes (both stores are
// session-scoped). The rings, the ops table and the buffer generation are the
@@ -2050,6 +2086,14 @@ namespace MobileGL::MG_Backend::DirectGLES {
void OnBackendContextDestroyed() {
UnregisterBufferBackendOps(); // also bumps the buffer-mutation epoch
++g_bufferContextGeneration;
g_backendBufferResources.ForEachBucket(
[](const TwinKey&, MG_Pipe::MGPipeHandle handle, const SharedPtr<GLESBufferResource>& twin) {
InvalidateResidentBacking(handle, *twin);
// A private or server-owned shadow is about to be freed. Plain aliases
// into a frontend shadow remain valid until the next content record.
if (ServerStaged().HasShadow(twin.get())) twin->hostBytes = nullptr;
twin->serverGpuWritten = false;
});
// The generation moved AFTER the unregister bump above; re-open the
// memos again so no stamp can predate the generation change.
BumpBufferMutationEpoch();
@@ -2116,7 +2160,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
// fence signaled let go of their AHardwareBuffer; a deferred T0 destroy is retired once
// the drain deleted its id (the fence then follows the delete) or its context is gone.
void ProcessDeferredT0Retires() {
if (!g_t0Retired.empty()) SweepT0Retired(false);
SweepT0Retired(false);
if (!g_hasT0DeferredDestroys.load(std::memory_order_acquire)) return;
Vector<SharedPtr<BackendBufferResource>> ready;
{
@@ -2167,6 +2211,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
if (twin == nullptr || twin->get() != resource) return false;
if (resource->contextGeneration != g_bufferContextGeneration) return false;
if (resource->id == 0) return false;
const std::lock_guard<std::mutex> lock(resource->pendingMutex);
if (resource->persistentMapped) {
return resource->persistentPtr != nullptr && resource->pendingResidentWrites.empty();
}
@@ -2197,43 +2242,14 @@ namespace MobileGL::MG_Backend::DirectGLES {
return resource->syncedChangeSerial.load(std::memory_order_acquire) == record->Serial;
}
// The handle arm of the ensure path. Same shape, same order, same branches; the four
// frontend reads become the applier's stored descriptor, its Serial and the shadow base
// the last content-carrying call handed over.
//
// It still takes the frontend object for ONE reason, recorded rather than hidden:
// BufferObject::SyncPersistentMappedRange() is one of the eleven Espryt sites
// ROADMAP/D-N explicitly keeps where it is for P3a (the per-site attribution table is
// P8's to execute). Every other line here is handle-shaped. When P8 moves that call to
// the client this signature loses its last frontend argument.
GLESBufferResource* EnsureBufferResourceForHandle(
const SharedPtr<MG_State::GLState::BufferObject>& bufferObject, MG_Pipe::MGPipeHandle res) {
GLESBufferResource* EnsureBufferResourceForHandle(MG_Pipe::MGPipeHandle res) {
auto* resource = GetOrCreateBufferResourceForHandle(res);
if (!resource) return nullptr;
// The client's shadow base, RE-READ at every use, exactly as the legacy arm re-read
// MappedData() at every use. It is deliberately NOT resource->hostBytes here: two
// ordinary events move or free what a base recorded by an earlier call points at -
// a shadow resize (PipeResource::ResizeShadow is reserve + resize, so a grow past
// the reserve reallocates) and persistent-map adoption (the shadow is cleared and
// shrunk to fit) - and this path still holds the frontend object anyway, because
// D-N keeps SyncPersistentMappedRange here for all of P3a. hostBytes stays the
// fallback for the drains that have NO object (the readback flush), and it is
// nulled at both of those events.
const auto liveHostBase = [&resource, &bufferObject]() -> const Uint8* {
// M-2 / codex 3 / ID-52 item 3: under an ACTIVE TRANSPORT the server's staged
// copy (resource->hostBytes, filled by MGL_SERVER_STAGED_ADOPT in Ops_H_SubData /
// Ops_H_FlushRange) is the ONLY authoritative base. Preferring the frontend
// object's MappedData() here - which under inproc is always non-null, same process
// - meant every reduced-path drain read the CLIENT's shadow and NEVER the server's,
// so a corrupt staged upload rendered the frontend's correct bytes and the R-2.5
// 0xDD audit could not reach a draw. R-2 / table 3: honest inproc is inproc that
// does not read the client object's memory. Under monolith nothing changes.
return resource->hostBytes;
};
if (resource->contextGeneration != g_bufferContextGeneration) {
// The id (if any) belonged to a destroyed ES context.
// A stale driver name cannot be reused in the new context. Keep any
// shadow staged by records that preceded the first use of this twin.
const std::lock_guard<std::mutex> lock(resource->pendingMutex);
resource->id = 0;
resource->storageInitialized = false;
resource->storageSize = 0;
@@ -2244,25 +2260,9 @@ namespace MobileGL::MG_Backend::DirectGLES {
resource->persistentMapped = false;
resource->persistentPtr = nullptr;
resource->immutableStorage = false;
// m-5 / codex 5: OnBackendContextDestroyed ran MGL_SERVER_STAGED_DROP_ALL(), which
// frees every server shadow but does NOT null the hostBytes that name them - so a
// twin that SURVIVES a context loss still carries a base into the freed allocation.
// Null it here, where a surviving twin is re-armed - but ONLY when the shadow is
// really gone. This block also runs on a twin's FIRST ensure (contextGeneration
// starts mismatched), and there the shadow a preceding resource_subdata just staged
// is still live; nulling it then would drop the reduced path's own bytes (it did,
// and TriangleScenario read the wrong VBO). HasShadow is the discriminator: false
// after DropAll, true after an ordinary Adopt.
//
// TRANSPORT-GUARDED like the other two split hunks in this file (review v2 N-7):
// under MONOLITH transport in a disaggregated build the store never copies, Adopt
// never sets m_any, HasShadow answers false for everything, and this null would
// run on every twin's first ensure - harmless there only because liveHostBase()
// prefers MappedData() under monolith, and "under monolith nothing changes" should
// be true by construction rather than by luck.
if (ServerStaged().CopiesIntoServerStorage() && !ServerStaged().HasShadow(resource)) {
resource->hostBytes = nullptr;
}
}
if (resource->id == 0) {
#if defined(__ANDROID__) && MOBILEGL_BUILD_DISAGGREGATED
// P11 B2: A T0 STORE OUTLIVES ITS CONTEXT. Its pages are the client's
// AHardwareBuffer, which this twin still holds, so the store is imported again on
@@ -2283,6 +2283,9 @@ namespace MobileGL::MG_Backend::DirectGLES {
"%s; the store has no GPU backing",
res.Slot, res.Gen, why.c_str());
RetireT0Import(*resource);
(void)MG_Pipe::MGPipeSessionLatch(MG_Pipe::MGPipeFatalFamily::DeviceLost,
"T0 buffer import lost its GPU backing: %s", why.c_str());
return nullptr;
}
}
#endif
@@ -2306,14 +2309,23 @@ namespace MobileGL::MG_Backend::DirectGLES {
return resource;
}
const auto* record = ResourceRecordOf(res);
const SizeT size = record != nullptr ? static_cast<SizeT>(record->Desc.Width) : 0;
// Refresh the borrowed monolith alias after a resize or a revoked mapping.
// Transport consumers use only the bytes staged by records.
std::optional<MG_Pipe::MGPipeLocalBufferShadow> shadow;
if (size != 0 && MG_Config::RecordArmAliasesFrontend() && MG_Pipe::gMGPipeQueryLocalBufferShadow) {
shadow = MG_Pipe::gMGPipeQueryLocalBufferShadow(res, size);
if (shadow) resource->hostBytes = shadow->Bytes;
}
const Uint8* const hostBase = resource->hostBytes;
if (resource->id == 0) {
const SizeT poolSize = ResourceWidthOf(res);
// The pool DECISION is the legacy one, unchanged: extent and residence only.
// An earlier cut added "and a shadow base was recorded", which silently stopped
// a buffer recycling pool ids - a change to D-F's pool behavior, not to "the
// source of bytes" the conversion is allowed to move, and one that moves
// AcquireFromPool call counts StreamedArenaScenario observes.
const Uint reused = (poolSize > 0 && !resource->persistentMapped) ? AcquireFromPool(poolSize) : 0;
const SizeT poolSize = size;
const Uint8* const poolBytes = hostBase;
const Bool canReuse =
poolSize > 0 && !resource->persistentMapped && !resource->immutableStorage && poolBytes != nullptr;
const Uint reused = canReuse ? AcquireFromPool(poolSize) : 0;
if (reused != 0) {
resource->id = reused;
resource->storageSize = poolSize;
@@ -2329,9 +2341,9 @@ namespace MobileGL::MG_Backend::DirectGLES {
// legal (ResourceContentIsDeclared, above). RequireCoverage is a no-op for the
// legacy arm's MappedData() and for a non-copying store.
if (ResourceContentIsDeclared(res)) {
MGL_SERVER_STAGED_REQUIRE(*resource, liveHostBase(), 0, poolSize, "pool_reuse_whole_store");
MGL_SERVER_STAGED_REQUIRE(*resource, poolBytes, 0, poolSize, "pool_reuse_whole_store");
}
g_GLESFuncs.glBufferSubData(TempBufferTarget, 0, (GLsizeiptr)poolSize, liveHostBase());
g_GLESFuncs.glBufferSubData(TempBufferTarget, 0, (GLsizeiptr)poolSize, poolBytes);
if (MG_Util::PipeStats::Enabled()) {
MG_Util::PipeStats::AddBytes(MG_Util::PipeStats::ByteClass::StageBuffer,
static_cast<Uint64>(poolSize));
@@ -2355,69 +2367,19 @@ namespace MobileGL::MG_Backend::DirectGLES {
}
}
// D-N keeps this call here for P3a. It can queue ranges and move the record, so
// everything below is read AFTER it.
// P5c (hd, CONTRACT-P5C §3.8): under an active transport the frontend accessor is a
// layer-1 surface ("buffer-legacy-arm") and the client's own pre-verb
// persistent-map push is the only producer; the call is skipped outright. Under
// monolith D-N's placement stands.
const auto* record = ResourceRecordOf(res);
const SizeT size = record != nullptr ? static_cast<SizeT>(record->Desc.Width) : 0;
if (size == 0) {
return resource;
}
const Uint64 serial = record->Serial;
const GLenum usage = MG_Util::ConvertBufferUsageToGLEnum(static_cast<BufferUsage>(record->Desc.Usage));
// Read AFTER SyncPersistentMappedRange above, and through liveHostBase for the
// reason written where it is declared.
const Uint8* const hostBase = liveHostBase();
// AND PUBLISH IT, because the readers that have NO frontend object read
// resource->hostBytes and nothing else: the readback flush (Ops_H_Readback), the
// kill-switch map arm of Ops_H_FlushRange, and the fp64 narrowing
// (SyncConvertedAttributeByHandle, whose legacy counterpart reads
// bufferObject->MappedData()). A twin is created LAZILY - D-A2's row makes
// Ops_H_Create a no-op - so the very first resource_respecify of a buffer finds
// FindBufferResourceForHandle == nullptr and its base is dropped on the floor; with
// glBufferData(..., data) followed by no further content call (the ordinary static
// vertex array) hostBytes then stayed null for the object's whole life and the fp64
// narrowing refused every draw, disabling the array. This is the one place that both
// holds the object and runs before every draw that uses the store, so it is where the
// base is refreshed. Only reached for a NON-adopted resource (the adopted arm
// returned above), so C-2's rule is intact: an adopted store's hostBytes stays null
// and its bytes are read through persistentPtr.
if (hostBase != nullptr) resource->hostBytes = hostBase;
// "DOES THE SHADOW THIS PATH IS ABOUT TO UPLOAD HOLD MEANINGFUL BYTES?" - and it has
// to be asked of the SAME thing the bytes come from. The legacy arm pairs
// bufferObject.MappedData() with bufferObject.HasDefinedContent() (RespecifyStorageNow)
// and this arm pairs the same two, so the source of the bytes and the statement about
// them can never disagree.
//
// P5c (hd, CONTRACT-P5C §3.6 / B1): with an active transport the answer is the
// DESCRIPTOR's bit - which the client publishes on ResourceCreate/Respecify - OR the
// staged coverage the content records behind it delivered. The coverage half is what
// keeps the answer equal to the frontend flag's in the one case the descriptor alone
// cannot see: an ORPHANING respecify (descriptor clear) followed by glBufferSubData,
// which defines content without a new descriptor - the bytes crossed as
// resource_subdata and the staged store's coverage is exactly "content defined since
// the last orphan". With no coverage and a clear bit the store is undefined by the
// application's own declaration and the upload stays a pure NULL reallocation.
// Upload only surviving host content. Adoption drops the shadow.
const Bool shadowHasContent =
(record->Desc.HasDefinedContent != 0 ||
(ServerStaged().CopiesIntoServerStorage() ? ServerStaged().CoveredRunCount(resource) != 0
: resource->contentSinceRespecify));
shadow ? shadow->HasDefinedContent
: (record->Desc.HasDefinedContent != 0 ||
(ServerStaged().CopiesIntoServerStorage() ? ServerStaged().CoveredRunCount(resource) != 0
: resource->contentSinceRespecify));
const void* initialData = shadowHasContent ? hostBase : nullptr;
// M-3 / codex 4: a RespecifyStorageWith(..., initialData != nullptr) is a WHOLE-STORE
// [0, size) upload from the base, so it owes the same coverage the pending-range drain
// below owes - the two respecify arms were the readers M-6's "never widened" rule did
// not reach. No-op for the legacy arm's MappedData() and for a non-copying store; a
// Fatal{StageSnapshotTooNarrow, "respecify_whole_store"} under split when the
// DESCRIPTOR says the application supplied the content and the shadow's coverage does
// not span the store (a missing record), instead of uploading its zero-fill as content.
// NOT for a store the application orphaned: there `shadowHasContent` is the frontend
// object's flag, which the streaming idiom's partial glBufferSubData flips to true, and
// the bytes it did not write are undefined by its own glBufferData(NULL) - the rule at
// ResourceContentIsDeclared. Round 2 refused that idiom and aborted six joint entries.
const auto requireWholeStoreCoverage = [&]() {
if (initialData != nullptr && record->Desc.HasDefinedContent != 0) {
MGL_SERVER_STAGED_REQUIRE(*resource, static_cast<const Uint8*>(initialData), 0, size,
@@ -2741,16 +2703,9 @@ namespace MobileGL::MG_Backend::DirectGLES {
}
} // namespace
// Bump-allocate `size` bytes out of `ring`.
//
// Fast path: a live store under the current context with room before both
// the wrap boundary and the in-flight tail. Touches no GL and probes no
// frame marks - callers sit behind the ring's availability gate, so the
// context checks have already run for this draw/upload. `tail` may be stale
// here (marks are only retired on Present and on the slow path); staleness
// is conservative - the in-flight span reads too large, the check fails,
// and the slow path retires marks and re-tries.
Bool RingAllocate(PersistentRing& ring, SizeT size, SizeT& outOffset) {
// Allocate within the mapped ring without GL calls or polling fences. A stale tail
// accounts for extra bytes in flight, so it can only make this check more conservative.
static Bool TryAllocateMappedRing(PersistentRing& ring, SizeT size, SizeT& outOffset) {
if (size == 0) return false;
auto& store = ring.store;
if (store.id != 0 && store.contextGeneration == g_bufferContextGeneration) {
@@ -2770,7 +2725,12 @@ namespace MobileGL::MG_Backend::DirectGLES {
return true;
}
}
return RingAllocateSlow(ring, size, outOffset);
return false;
}
Bool RingAllocate(PersistentRing& ring, SizeT size, SizeT& outOffset) {
return TryAllocateMappedRing(ring, size, outOffset) ||
(size != 0 && RingAllocateSlow(ring, size, outOffset));
}
Bool RingAllocateSlow(PersistentRing& ring, SizeT size, SizeT& outOffset) {
@@ -2969,6 +2929,10 @@ namespace MobileGL::MG_Backend::DirectGLES {
return RingAllocate(UnpackRing(), size, outOffset);
}
Bool TryAllocateMappedUnpackRing(SizeT size, SizeT& outOffset) {
return size <= kUnpackRingMaxBytes && TryAllocateMappedRing(UnpackRing(), size, outOffset);
}
void* UnpackRingMappedPtr() {
return UnpackRing().store.mappedPtr;
}
@@ -25,7 +25,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
m_backendColorSlots[i] = GL_COLOR_ATTACHMENT0 + i;
}
g_GLESFuncs.glGenFramebuffers(1, &m_backendFBOId);
m_contextGeneration = g_backendContextGeneration;
m_nativeContextSerial = CurrentNativeContextSerial();
if (m_backendFBOId == 0) {
MGLOG_E_ONCE("Failed to generate framebuffer object.");
MGLOG_E_ONCE("ES glGetError(): %s", MG_Util::ConvertGLEnumToString(g_GLESFuncs.glGetError()).c_str());
@@ -38,14 +38,16 @@ namespace MobileGL::MG_Backend::DirectGLES {
if (InProcessTeardown()) {
return; // see InProcessTeardown(): the driver may be unloaded already
}
if (m_backendFBOId == 0) {
// A different native context can have a framebuffer with the same numeric name.
if (m_backendFBOId == 0 || m_nativeContextSerial != CurrentNativeContextSerial()) {
return;
}
// Scrub the binding shadow whether or not the id can still be deleted: a
// recycled name must never satisfy the shadow's dedup.
NoteFramebufferIdDeleted(m_backendFBOId);
if (m_contextGeneration == g_backendContextGeneration && g_GLESFuncs.glDeleteFramebuffers) {
if (g_GLESFuncs.glDeleteFramebuffers) {
g_GLESFuncs.glDeleteFramebuffers(1, &m_backendFBOId);
TextureImpl::DeleteDrawTextureFramebuffer(m_backendFBOId);
}
m_backendFBOId = 0;
}
@@ -83,6 +85,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
if (bindsDraw) {
g_driverFBOBindings[drawIdx] = id;
g_driverFBOBindingKnown[drawIdx] = true;
if (!drawMatches) TextureImpl::NoteDrawTextureFramebuffer(id);
}
if (bindsRead) {
g_driverFBOBindings[readIdx] = id;
@@ -409,7 +412,21 @@ namespace MobileGL::MG_Backend::DirectGLES {
// texture behind the staged shadow's back (the frontend arm's note, by handle).
TextureImpl::NoteDriverSideTextureWriteByHandle(surface.Res);
const auto uploadTarget = static_cast<TextureUploadTarget>(surface.UploadTarget);
if (surface.Layered != 0) {
if (surface.NumViews != 0) {
// GL_OVR_multiview. The frontend only builds one where the driver has the
// extension, but the record is the untrusted half: a multiview surface on a
// driver without the entry point is refused by name, never called through.
if (!g_GLESCapabilities.SupportsMultiview) {
MGLOG_E_ONCE("MGPipe: attachment surface {%u, %u} is multiview, but this driver has no "
"GL_OVR_multiview - refusing to attach it",
surface.Res.Slot, surface.Res.Gen);
return false;
}
g_GLESFuncs.glFramebufferTextureMultiviewOVR(
glFBOTarget, glBackendAttachment, backendTextureObject->GetBackendTextureId(),
static_cast<GLint>(surface.Level), static_cast<GLint>(surface.Layer),
static_cast<GLsizei>(surface.NumViews));
} else if (surface.Layered != 0) {
g_GLESFuncs.glFramebufferTexture(glFBOTarget, glBackendAttachment,
backendTextureObject->GetBackendTextureId(),
static_cast<GLint>(surface.Level));
@@ -580,7 +597,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
const auto& color = record.Color[i];
if (color.Res == record.ReadSurface.Res && color.Kind == record.ReadSurface.Kind &&
color.Layered == record.ReadSurface.Layered && color.Level == record.ReadSurface.Level &&
color.Layer == record.ReadSurface.Layer &&
color.NumViews == record.ReadSurface.NumViews && color.Layer == record.ReadSurface.Layer &&
color.UploadTarget == record.ReadSurface.UploadTarget) {
pushedReadBuf = static_cast<FramebufferAttachmentType>(
static_cast<Int>(FramebufferAttachmentType::Color0) + static_cast<Int>(i));
@@ -362,8 +362,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
Uint64 ResourceSerialForHandle(MG_Pipe::MGPipeHandle res);
GLESBufferResource* EnsureBufferResourceForHandle(
const SharedPtr<MG_State::GLState::BufferObject>& bufferObject, MG_Pipe::MGPipeHandle res);
GLESBufferResource* EnsureBufferResourceForHandle(MG_Pipe::MGPipeHandle res);
void BindBufferId(GLenum target, Uint id);
@@ -382,6 +381,10 @@ namespace MobileGL::MG_Backend::DirectGLES {
Bool UnpackRingAllocate(SizeT size, SizeT& outOffset);
// Only use space in the current mapping. Optional uploads can fall back
// immediately when the ring would have to grow or wait.
Bool TryAllocateMappedUnpackRing(SizeT size, SizeT& outOffset);
void* UnpackRingMappedPtr();
Uint UnpackRingBufferId();
@@ -1371,6 +1371,14 @@ namespace MobileGL::MG_Backend::DirectGLES {
}
}
// After every validating pass: the module that comes back names ViewIndex without the
// capability, which only SPIRV-Cross reads (see StripMultiviewCapabilityForEssl).
Vector<unsigned int> multiviewStrippedSpirv;
if (MG_Util::ShaderTranspiler::ShaderCompiler::StripMultiviewCapabilityForEssl(*effectiveSpirv,
multiviewStrippedSpirv)) {
effectiveSpirv = &multiviewStrippedSpirv;
}
MG_Util::ShaderTranspiler::SpvcSession spvcSession(*effectiveSpirv,
MG_Util::ShaderTranspiler::SessionUsageBit::Transpile);
@@ -2155,6 +2163,9 @@ namespace MobileGL::MG_Backend::DirectGLES {
!(ViewportArrayEmulationEnabled() && programRoutesViewportIndex) &&
source.find("gl_ViewportIndex") != String::npos;
source = RequestViewportArrayExtension(std::move(source), needsViewportArrayExtension);
// GL_OVR_multiview's directive and num_views, which the memoized ESSL leaves out.
source = RequestMultiviewExtension(std::move(source), glShaderType, src.GetVertexNumViews(),
g_GLESCapabilities.SupportsMultiview2);
// The fourth header-level rewrite, and the same shape as the third: ESSL has no
// gl_PointSize in a tessellation or geometry stage at ANY version - 320 makes the
@@ -7,6 +7,9 @@
// End of Source File Header
#include "ManagersInternal.h"
#include "DirectGLESInternal.h"
#include <MG_Util/Texture/PackedTextureUpload.h>
#include <MG_Util/Texture/TextureUploadBoxes.h>
namespace MobileGL::MG_Backend::DirectGLES {
namespace TextureImpl {
@@ -97,6 +100,149 @@ namespace MobileGL::MG_Backend::DirectGLES {
return reinterpret_cast<const void*>(static_cast<std::uintptr_t>(offset));
}
namespace {
static Bool SplitMipUpload(const MG_Pipe::MGPipeResourceRecord::PendingUpload& pending,
const IntVec3& levelSize, MG_State::GLState::MipmapDirtyRegion* boxes) {
using namespace MG_Util::TextureUploadBoxes;
const auto& bounds = pending.UnionBox;
if (bounds.X < 0 || bounds.Y < 0 || bounds.Z != 0 || bounds.D != 1 || bounds.X >= levelSize.x() ||
bounds.Y >= levelSize.y() || bounds.W > static_cast<Uint>(levelSize.x() - bounds.X) ||
bounds.H > static_cast<Uint>(levelSize.y() - bounds.Y)) {
return false;
}
const Box unionBox{bounds.X, bounds.Y, bounds.X + static_cast<Int>(bounds.W),
bounds.Y + static_cast<Int>(bounds.H)};
if (!WorthSearching(unionBox, pending.Regions.size())) return false;
std::array<Box, MaxRegions> regions;
for (SizeT i = 0; i < pending.Regions.size(); ++i) {
const auto& region = pending.Regions[i];
if (region.X < unionBox.left || region.X >= unionBox.right || region.Y < unionBox.top ||
region.Y >= unionBox.bottom || region.Z != 0 || region.D != 1 || region.W == 0 ||
region.H == 0 || region.W > static_cast<Uint>(unionBox.right - region.X) ||
region.H > static_cast<Uint>(unionBox.bottom - region.Y)) {
return false;
}
regions[i] = {region.X, region.Y, region.X + static_cast<Int>(region.W),
region.Y + static_cast<Int>(region.H)};
}
const auto split = Split(unionBox, regions, pending.Regions.size());
if (!split) return false;
for (SizeT i = 0; i < split->size(); ++i) {
const auto& box = (*split)[i];
boxes[i] = {IntVec3{box.left, box.top, 0}, IntVec3{box.right, box.bottom, 1}};
}
return true;
}
struct PackedUploadPage {
GLuint texture = 0;
Uint generation = 0;
Uint64 context = 0;
Uint64 retireSerial = 0;
};
// The names live in the share group, while reuse is restricted to the
// EGL context that submitted the copies. Any retired context's page
// can be deleted the next time a shared context acquires its slot.
struct PackedUploadPages final : PerNativeContextBase {
std::mutex mutex;
std::array<PackedUploadPage, 4> pages;
void ForgetContext(Uint64 context) override {
const std::lock_guard<std::mutex> lock(mutex);
for (auto& page : pages) {
if (page.context == context) page.context = 0;
}
}
PackedUploadPage* FindIdle(Uint64 context) {
const Uint64 completed = CompletedFrameSerial();
PackedUploadPage* vacant = nullptr;
for (auto& page : pages) {
if (page.generation != g_backendContextGeneration) page = {};
if (page.context == context && page.retireSerial <= completed) return &page;
if (page.context == 0 && vacant == nullptr) vacant = &page;
}
return vacant;
}
};
enum class PackedUploadResult {
Unavailable,
Rejected,
Committed
};
static PackedUploadResult SubmitPackedUpload(const MG_Util::PackedTextureUpload::Batch& batch,
GLuint destination, Uint64 unionTexels) {
const Uint64 context = CurrentNativeContextSerial();
if (context == 0) return PackedUploadResult::Unavailable;
static PackedUploadPages pool;
const std::unique_lock<std::mutex> lock(pool.mutex, std::try_to_lock);
if (!lock.owns_lock()) return PackedUploadResult::Unavailable;
auto* page = pool.FindIdle(context);
if (page == nullptr) return PackedUploadResult::Unavailable;
SizeT offset = 0;
if (!BufferImpl::TryAllocateMappedUnpackRing(batch.ByteSize(), offset)) {
return PackedUploadResult::Unavailable;
}
auto* mapping = static_cast<Uint8*>(BufferImpl::UnpackRingMappedPtr());
MG_Util::PackedTextureUpload::WritePage(batch, mapping + offset);
DrainDriverErrors("packed texture upload");
if (page->context != context) {
if (page->texture != 0) g_GLESFuncs.glDeleteTextures(1, &page->texture);
*page = {0, g_backendContextGeneration, context, 0};
g_GLESFuncs.glGenTextures(1, &page->texture);
if (page->texture == 0) {
*page = {};
return PackedUploadResult::Rejected;
}
g_GLESFuncs.glBindTexture(GL_TEXTURE_2D, page->texture);
g_GLESFuncs.glTexStorage2D(GL_TEXTURE_2D, 1, GL_RGBA8, MG_Util::PackedTextureUpload::PageSide,
MG_Util::PackedTextureUpload::PageSide);
g_GLESFuncs.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
g_GLESFuncs.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
if (g_GLESFuncs.glGetError() != GL_NO_ERROR) {
g_GLESFuncs.glBindTexture(GL_TEXTURE_2D, destination);
g_GLESFuncs.glDeleteTextures(1, &page->texture);
*page = {};
return PackedUploadResult::Rejected;
}
} else {
g_GLESFuncs.glBindTexture(GL_TEXTURE_2D, page->texture);
}
// SyncMipmapsToBackend has the destination bound on the temp unit.
// Restore that raw binding before returning to the cached GL state.
BufferImpl::BindPixelUnpackBufferId(BufferImpl::UnpackRingBufferId());
g_GLESFuncs.glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, batch.width, batch.height, GL_RGBA,
GL_UNSIGNED_BYTE, UnpackRingPixelOffset(offset));
BufferImpl::BindPixelUnpackBufferId(0);
g_GLESFuncs.glBindTexture(GL_TEXTURE_2D, destination);
page->retireSerial = CurrentFrameSerial() + 1;
if (g_GLESFuncs.glGetError() != GL_NO_ERROR) return PackedUploadResult::Rejected;
if (MG_Util::PipeStats::Enabled()) {
MG_Util::PipeStats::AddBytes(MG_Util::PipeStats::ByteClass::StageTexture, batch.ByteSize());
}
for (SizeT i = 0; i < batch.count; ++i) {
const auto& region = batch.regions[i];
const auto& source = batch.offsets[i];
g_GLESFuncs.glCopyImageSubData(page->texture, GL_TEXTURE_2D, 0, source.x, source.y, 0, destination,
GL_TEXTURE_2D, region.level, region.x, region.y, 0, region.width,
region.height, 1);
}
if (g_GLESFuncs.glGetError() != GL_NO_ERROR) return PackedUploadResult::Rejected;
MGLOG_I_ONCE(
"Packed texture upload: %zu regions, %zu packed bytes, %llu bounding-box bytes", batch.count,
batch.ByteSize(),
static_cast<unsigned long long>(unionTexels * MG_Util::PackedTextureUpload::BytesPerTexel));
return PackedUploadResult::Committed;
}
} // namespace
static Uint GetNormFallbackComponentCount(TextureInternalFormat format) {
switch (format) {
case TextureInternalFormat::R8Snorm:
@@ -755,6 +901,94 @@ namespace MobileGL::MG_Backend::DirectGLES {
(pushedStorage != nullptr ? static_cast<TextureStorageType>(pushedStorage->Desc.StorageKind) \
: (obj)->GetStorageType())
static PackedUploadResult TryPackedMipUpload(MG_State::GLState::TextureObjectMipmap* textureMipmapObject,
const MG_Pipe::MGPipeResourceRecord* pushedStorage,
MG_Pipe::MGPipeHandle pushedRes, TextureUploadTarget uploadTarget,
SizeT mipmapCount, GLuint destination) {
using namespace MG_Util::PackedTextureUpload;
Batch batch;
Uint64 unionTexels = 0;
const auto targetCode = static_cast<Uint16>(uploadTarget);
for (SizeT level = 0; level < mipmapCount; ++level) {
const auto levelCode = static_cast<Uint16>(level);
const auto* pending = FindPipeTextureUpload(*pushedStorage, targetCode, levelCode);
if (pending == nullptr) continue;
if (pending->Regions.empty() || pending->Regions.size() > MaxRegions - batch.count) {
return PackedUploadResult::Unavailable;
}
const auto size = MGB_LEVEL_TEXEL_SIZE(textureMipmapObject, uploadTarget, level);
if (size.x() <= 0 || size.y() <= 0 || size.z() > 1 ||
MGB_LEVEL_BYTE_SIZE(textureMipmapObject, uploadTarget, level) !=
static_cast<Uint64>(size.x()) * size.y() * BytesPerTexel) {
return PackedUploadResult::Unavailable;
}
if (MGB_STAGED_TEXTURE_LIVE &&
!MG_Record::ServerStagedTexture().IsCovered(MG_Record::StagedTextureStore::KeyForHandle(pushedRes),
targetCode, levelCode)) {
return PackedUploadResult::Unavailable;
}
const auto* pixels = static_cast<const Uint8*>(
MGB_LEVEL_TEXELS(textureMipmapObject, uploadTarget, level, "packed-dirty-level"));
if (pixels == nullptr) return PackedUploadResult::Unavailable;
const SizeT pitch = static_cast<SizeT>(size.x()) * BytesPerTexel;
for (const auto& region : pending->Regions) {
if (region.Z != 0 || region.D != 1 || region.W == 0 || region.H == 0 || region.W > PageSide ||
region.H > PageSide || region.X < 0 || region.Y < 0 || region.X >= size.x() ||
region.Y >= size.y() || region.W > static_cast<Uint>(size.x() - region.X) ||
region.H > static_cast<Uint>(size.y() - region.Y)) {
return PackedUploadResult::Unavailable;
}
// Read the final shadow using level coordinates. Carried offsets can address smaller slabs.
batch.regions[batch.count++] = {pixels + region.Y * pitch + region.X * BytesPerTexel,
pitch,
static_cast<int>(level),
region.X,
region.Y,
static_cast<int>(region.W),
static_cast<int>(region.H)};
}
unionTexels += static_cast<Uint64>(pending->UnionBox.W) * pending->UnionBox.H;
}
if (!Pack(batch, unionTexels)) return PackedUploadResult::Unavailable;
const auto result = SubmitPackedUpload(batch, destination, unionTexels);
if (result == PackedUploadResult::Committed) {
// The copies rewrite storage the driver already holds, like any in-place level upload.
NoteInPlaceTextureUpload();
for (SizeT level = 0; level < mipmapCount; ++level) {
if (FindPipeTextureUpload(*pushedStorage, targetCode, static_cast<Uint16>(level)) != nullptr) {
MGB_LEVEL_UPLOAD_DONE(textureMipmapObject, uploadTarget, level);
}
}
}
return result;
}
// Pack the small writes across all dirty mip levels before their per-level union boxes can pull
// in untouched atlas texels. The staging page copies the shadow bytes as-is, so both the shadow
// and the driver format must be plain RGBA8: a driver format can also carry converted data.
void BackendTextureObject::TryPackedLevelUploads(MG_State::GLState::TextureObjectMipmap* textureMipmapObject,
const MG_Pipe::MGPipeResourceRecord* pushedStorage,
MG_Pipe::MGPipeHandle pushedRes, GLenum target,
const Vector<TextureUploadTarget>& uploadTargets,
SizeT mipmapCount, TextureInternalFormat storageFormat,
GLenum glInternalFormat, GLenum glFormat, GLenum glType) {
const Bool rawRgba8Copy = storageFormat == TextureInternalFormat::RGBA8 && glInternalFormat == GL_RGBA8 &&
glFormat == GL_RGBA && glType == GL_UNSIGNED_BYTE;
if (!rawRgba8Copy || m_driverMayHoldGpuWrites || m_packedUploadRejected || m_imageBindableStorageRequired ||
target != GL_TEXTURE_2D || pushedStorage == nullptr || uploadTargets.size() != 1 ||
!g_GLESFuncs.glCopyImageSubData || !g_GLESFuncs.glTexStorage2D || !BufferImpl::UnpackRingAvailable()) {
return;
}
const auto result = TryPackedMipUpload(textureMipmapObject, pushedStorage, pushedRes, uploadTargets.front(),
mipmapCount, m_backendTextureId);
if (result != PackedUploadResult::Rejected) return;
// Replay all regions from the shadow after a rejected copy.
DrainDriverErrors("packed texture upload fallback");
m_packedUploadRejected = true;
MGLOG_D("Packed texture upload rejected for texture %u", m_backendTextureId);
}
void BackendTextureObject::SyncMipmapsToBackend(
const SharedPtr<MG_State::GLState::ITextureObject>& stateTextureObject) {
// P5e (tx2): null IS the by-handle arm once a handle has been noted on this twin;
@@ -1038,7 +1272,9 @@ namespace MobileGL::MG_Backend::DirectGLES {
const auto mipmapCount = MGB_STORAGE_LEVELS(textureMipmapObject);
currentTextureInfo.mipmapLevels = mipmapCount;
Bool needsRegeneration = !m_isInitialized || (currentTextureInfo != m_prevTextureInfo);
const Bool stableStorage = m_isInitialized && currentTextureInfo == m_prevTextureInfo;
Bool needsRegeneration = !stableStorage;
if (needsRegeneration) m_packedUploadRejected = false;
if (needsRegeneration && m_backendStorageImmutable) {
RecreateBackendTexture();
Bind(target);
@@ -1429,9 +1665,10 @@ namespace MobileGL::MG_Backend::DirectGLES {
}
const auto mipmapCount = MGB_STORAGE_LEVELS(textureMipmapObject);
const auto storageFormat = MGB_STORAGE_FORMAT(textureMipmapObject);
GLenum glInternalFormat, glType, glFormat;
TextureImpl::GenerateTextureFormatInfo(MGB_STORAGE_FORMAT(textureMipmapObject), &glInternalFormat,
&glFormat, &glType, targetInternal);
TextureImpl::GenerateTextureFormatInfo(storageFormat, &glInternalFormat, &glFormat, &glType,
targetInternal);
// The storage this level is being written into was widened when it was minted
// (see above), so the transfer pair has to describe the carrier here too - ES
// requires glTexSubImage's `format` to match the storage's base internal
@@ -1439,6 +1676,13 @@ namespace MobileGL::MG_Backend::DirectGLES {
ApplyImageBindableStorageWidening(imageWidening, &glInternalFormat, &glFormat, &glType);
const auto& uploadTargets = MGB_UPLOAD_TARGETS(textureMipmapObject);
ScopedDefaultUnpackState unpackState;
// Update sampled storage directly to avoid stalling the current offscreen batch on a PBO.
const Bool useClientUnpack = stableStorage && WasTextureReadInDrawBatch(pushedRes);
// The packed copies write the destination on the GPU too, so sampled storage skips them.
if (stableStorage && !useClientUnpack) {
TryPackedLevelUploads(textureMipmapObject, pushedStorage, pushedRes, target, uploadTargets,
mipmapCount, storageFormat, glInternalFormat, glFormat, glType);
}
// Per-level scratch of the exact-footprint path, hoisted to reuse capacity.
Vector<MG_State::GLState::MipmapDirtyRegion> dirtyFootprint;
Vector<UnpackStagingBlock> stagingBlockOverflow;
@@ -1707,7 +1951,9 @@ namespace MobileGL::MG_Backend::DirectGLES {
MG_State::GLState::MipmapDirtyRegion
dirtyRects[MG_State::GLState::MipmapStorage::kMaxDirtyRects];
SizeT dirtyRectCount = 0;
if (subRectEligible) {
const Bool ringUsable = BufferImpl::UnpackRingAvailable();
// A client-memory upload keeps the scatter refinement, ring or not.
if (subRectEligible && (!ringUsable || useClientUnpack)) {
if (pendingUpload != nullptr) {
// RegionCount == 0 is LEGAL and means "the union box is the
// whole story" (D-D3), which is the same statement the
@@ -1751,23 +1997,26 @@ namespace MobileGL::MG_Backend::DirectGLES {
dirtyRectCount = textureMipmapObject->GetStorageDirtyRects(
uploadTarget, level, dirtyRects,
MG_State::GLState::MipmapStorage::kMaxDirtyRects);
// The scatter refinement pays only on the client-pointer path,
// where fewer bytes mean less driver-side copying. Through the
// unpack ring every glTexSubImage is a GPU copy job (Mali), so
// ~100 sprite rects become ~100 jobs whose fixed cost dwarfs
// the union box's extra bytes - measured +6 ms/frame of GPU
// time in MC's animated-atlas ticks. One box, one job.
if (BufferImpl::UnpackRingAvailable()) {
dirtyRectCount = 0;
}
}
// Everything above - the union box, the ring's one-box rule, the rect
// list with its merges, fold and 3/4 cut-off - may upload shadow texels
// the client did not write, which is only harmless while the driver
// still holds those texels as they were last uploaded. Once it may hold
// GPU writes, the level goes up as exactly the texels written, one box
// (one ring job) each, whatever that costs: more boxes, and a union box
// that spans the whole level no longer means a whole-level upload.
// Bound the unpack-ring fallback to two jobs per level. The
// boxes may include gaps, so require an authoritative CPU shadow.
const Bool splitBoxUpload =
ringUsable && !useClientUnpack && regionsAddressable && stableStorage &&
!m_driverMayHoldGpuWrites && !m_imageBindableStorageRequired &&
target == GL_TEXTURE_2D &&
(glInternalFormat == GL_RGBA8 || glInternalFormat == GL_RGBA) && glFormat == GL_RGBA &&
glType == GL_UNSIGNED_BYTE && bpp == 4 && texelSize.z() == 1 && mipData != nullptr &&
uploadData == mipData && levelRowBytes == static_cast<SizeT>(texelSize.x()) * bpp &&
levelSliceBytes == static_cast<SizeT>(texelSize.y()) * levelRowBytes &&
pendingUpload != nullptr &&
(!MGB_STAGED_TEXTURE_LIVE ||
MG_Record::ServerStagedTexture().IsCovered(
MG_Record::StagedTextureStore::KeyForHandle(pushedRes),
static_cast<Uint16>(uploadTarget), static_cast<Uint16>(level))) &&
SplitMipUpload(*pendingUpload, texelSize, dirtyRects);
if (splitBoxUpload) dirtyRectCount = 2;
// A union or split can include untouched texels while the shadow is authoritative.
// Once the GPU may have written the texture, upload only the exact client footprint.
const MG_State::GLState::MipmapDirtyRegion* uploadRects = dirtyRects;
SizeT uploadRectCount = dirtyRectCount;
if (m_driverMayHoldGpuWrites && regionsAddressable) {
@@ -1816,19 +2065,15 @@ namespace MobileGL::MG_Backend::DirectGLES {
// is the level shadow itself and never a conversion buffer: since dev's 8966d5c2 a converted
// level is sub-rect eligible too, and its rects are cut at the conversion's bpp (rectUploadPtr).
//
// THREE USE SITES, AND THE FIRST OF THEM IS UNREACHABLE (N-5's second half, and the correction
// to what esprytobj-v2.md m-1 claimed): dirtyRectCount is forced to 0 whenever
// UnpackRingAvailable(), and the staging-block loop that takes MGB_RECT_SRC_PTR(r, rect) first
// requires `ringUsable && dirtyRectCount >= 2`. The two conditions cannot both hold. That shape
// is pre-existing (the ring/scatter decision, not this package's), so the loop is left as it
// stands and the count is corrected here instead of the loop being deleted underneath it.
// A pair of bounding boxes need not start at the corresponding recorded region's origin.
// Read those boxes by coordinate, including when ring staging falls back to a client pointer.
//
// A MACRO AND NOT A SECOND LAMBDA, for DV-9's measured reason: this function's nine ErrorLopper
// lambdas are mangled ...::$_N BY POSITION, so one more renumbers every one of them and moves
// the PULL build's symbol set, whose admitted-change set is EMPTY. The pull expansion is the
// pre-P4a call with one pair of parentheses. #undef'd with the rest.
#define MGB_RECT_SRC_PTR(idx, rect) \
((pendingUpload != nullptr && pendingOffsetsAgree && carriedLayoutApplies && \
((!splitBoxUpload && pendingUpload != nullptr && pendingOffsetsAgree && carriedLayoutApplies && \
static_cast<SizeT>(idx) < pendingUpload->Regions.size()) \
? static_cast<const Uint8*>(uploadData) + \
static_cast<SizeT>(pendingUpload->Regions[static_cast<SizeT>(idx)].SrcOffset) \
@@ -1864,8 +2109,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
UnpackStagingBlock stagingBlockArray[MG_State::GLState::MipmapStorage::kMaxDirtyRects];
UnpackStagingBlock* stagingBlocks = stagingBlockArray;
SizeT stagingBlockCount = 0;
const Bool ringUsable = BufferImpl::UnpackRingAvailable();
if (!ringUsable) {
if (!ringUsable || useClientUnpack) {
// Nothing to plan: every branch below keeps the client
// pointer and its ROW_LENGTH striding, unchanged.
} else if (perRectUpload) {
@@ -1925,11 +2169,11 @@ namespace MobileGL::MG_Backend::DirectGLES {
// separately from the bytes on purpose: SSIM is blind to it
// and the +6 ms/frame Mali cliff was a shape regression, not
// a byte regression (plan section 7.3).
const Bool rectShape = subRectEligible && dirtyRectCount >= 2;
const Bool rectShape = perRectUpload;
Uint64 shippedBytes = 0;
if (rectShape) {
for (SizeT r = 0; r < dirtyRectCount; ++r) {
const auto& rect = dirtyRects[r];
for (SizeT r = 0; r < uploadRectCount; ++r) {
const auto& rect = uploadRects[r];
shippedBytes += static_cast<Uint64>(rect.hi.x() - rect.lo.x()) *
static_cast<Uint64>(rect.hi.y() - rect.lo.y()) *
static_cast<Uint64>(std::max(rect.hi.z() - rect.lo.z(), 1)) *
@@ -1940,7 +2184,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
static_cast<Uint64>(regionSize.x()) * static_cast<Uint64>(regionSize.y()) *
static_cast<Uint64>(std::max(regionSize.z(), 1)) * static_cast<Uint64>(bpp);
} else {
shippedBytes = static_cast<Uint64>(byteSize);
shippedBytes = static_cast<Uint64>(uploadBytes == 0 ? byteSize : uploadBytes);
}
MG_Util::PipeStats::AddBytes(MG_Util::PipeStats::ByteClass::StageTexture, shippedBytes);
MG_Util::PipeStats::AddCalls(MG_Util::PipeStats::CallClass::TextureUploadEmissions, 1);
@@ -1949,7 +2193,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
: MG_Util::PipeStats::CallClass::TextureUploadBoxEmissions,
1);
MG_Util::PipeStats::AddCalls(MG_Util::PipeStats::CallClass::TextureUploadJobs,
rectShape ? static_cast<Uint64>(dirtyRectCount) : 1u);
rectShape ? static_cast<Uint64>(uploadRectCount) : 1u);
}
switch (MapToBackendTextureTarget(MGB_TEXTURE_TARGET(stateTextureObject))) {
case TextureTarget::Texture2D:
@@ -2056,15 +2300,6 @@ namespace MobileGL::MG_Backend::DirectGLES {
// BufSize` name the range, so the frontend binding slot below is not read at all
// on the handle arm.
//
// The one thing that argument had to answer is D-A4's `frontend` parameter of
// EnsureBufferResourceForHandle, which existed for the emulated-persistent-map
// question. The E note's reading is confirmed at this head: that function's three
// frontend reads (Managers.cpp's MappedData / SyncPersistentMappedRange /
// HasDefinedContent) are all inside its MONOLITH arm - under an active transport
// it is client-free (kimi audit row 29) - so `nullptr` is not a hole, it is the
// whole of the split answer, and it is what §4.2's Buffer row already prescribes
// (`EnsureBufferResourceForHandle(nullptr, h)`).
//
// WHOLE-VS-RANGE likewise stops asking the buffer object for its size: the
// sentinel kMGPipeWholeBuffer IS "the whole store", which is the question
// `rangeSize == buffer->GetSize()` was spelling the long way round.
@@ -2107,7 +2342,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
Bool needsRegeneration = !m_isInitialized || (currentTextureInfo != m_prevTextureInfo);
// Need to sync texture buffer if not synced yet
auto* backendBufferResource = BufferImpl::EnsureBufferResourceForHandle(buffer, pushedTexBuffer);
auto* backendBufferResource = BufferImpl::EnsureBufferResourceForHandle(pushedTexBuffer);
if (!backendBufferResource || backendBufferResource->id == 0) {
MGLOG_E_ONCE("Failed to sync backing buffer for texture buffer with ID: %u",
MGB_TEXTURE_DIAG_NAME(pushedStorage, stateTextureObject));
@@ -80,7 +80,8 @@ namespace MobileGL::MG_Backend::DirectGLES {
const char* site) {
// A coherent store - T0's import, or (P13 W4a) a map monolith's record arm donated -
// has no copy: its bytes are read through the map once queued writes have landed.
const Bool coherent = resource.persistentMapped && resource.persistentPtr != nullptr;
const Bool coherent = resource.persistentMapped && resource.persistentPtr != nullptr &&
resource.contextGeneration == CurrentBufferContextGeneration();
Bool residentWritesQueued = false;
if (coherent) {
const std::lock_guard<std::mutex> lock(resource.pendingMutex);
@@ -241,6 +242,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
m_clientAttributeBufferIds.fill(0);
m_convertedAttributeBufferIds.fill(0);
g_GLESFuncs.glGenVertexArrays(1, &m_backendVAOId);
m_nativeContextSerial = CurrentNativeContextSerial();
if (m_backendVAOId == 0) {
MGLOG_E_ONCE("Failed to generate vertex array object.");
MGLOG_E_ONCE("ES glGetError(): %s", MG_Util::ConvertGLEnumToString(g_GLESFuncs.glGetError()).c_str());
@@ -253,7 +255,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
if (InProcessTeardown()) {
return; // see InProcessTeardown(): the driver may be unloaded already
}
if (m_backendVAOId != 0) {
if (m_backendVAOId != 0 && m_nativeContextSerial == CurrentNativeContextSerial()) {
NoteVAOIdDeleted(m_backendVAOId);
g_GLESFuncs.glDeleteVertexArrays(1, &m_backendVAOId);
m_backendVAOId = 0;
+2 -2
View File
@@ -215,7 +215,7 @@ namespace MobileGL::MG_Backend::DirectGLES::MultiDrawImpl {
return view;
}
auto* resource = BufferImpl::EnsureBufferResourceForHandle(nullptr, res);
auto* resource = BufferImpl::EnsureBufferResourceForHandle(res);
if (resource == nullptr) RefuseMissingIndexBufferRecord(entry, res, "backend resource");
view.Id = resource->id;
if (question == IndexBufferQuestion::DriverNameAndSize) {
@@ -266,7 +266,7 @@ namespace MobileGL::MG_Backend::DirectGLES::MultiDrawImpl {
Uint BoundDrawIndirectBufferId() {
const MG_Pipe::MGPipeHandle res = MG_Pipe::MGPipeApplier().VerbIndirectBuffer;
if (MG_Pipe::MGPipeHandleIsNull(res)) return 0;
auto* resource = BufferImpl::EnsureBufferResourceForHandle(nullptr, res);
auto* resource = BufferImpl::EnsureBufferResourceForHandle(res);
if (resource == nullptr) {
RefuseMissingIndirectBufferRecord("BoundDrawIndirectBufferId", res);
}
+30
View File
@@ -741,6 +741,36 @@ namespace MobileGL::MG_Backend::DirectGLES {
return glslCode;
}
String RequestMultiviewExtension(String glslCode, GLenum shaderType, Int numViews, Bool driverHasMultiview2) {
const Bool declaresViews = shaderType == GL_VERTEX_SHADER && numViews > 0;
if (!declaresViews && glslCode.find("gl_ViewID_OVR") == String::npos) return glslCode;
const String directive = std::format("#extension {} : require\n",
driverHasMultiview2 ? "GL_OVR_multiview2" : "GL_OVR_multiview");
// The directive goes right after #version; num_views is a declaration, so it goes after
// the LAST directive, where ESSL lets non-preprocessor tokens start.
const SizeT versionPos = glslCode.find("#version");
const SizeT versionEnd = versionPos == String::npos ? String::npos : glslCode.find('\n', versionPos);
glslCode.insert(versionEnd == String::npos ? 0 : versionEnd + 1, directive);
if (!declaresViews) return glslCode;
SizeT insertAt = 0;
for (SizeT lineStart = 0; lineStart < glslCode.size();) {
const SizeT lineEnd = glslCode.find('\n', lineStart);
const SizeT next = lineEnd == String::npos ? glslCode.size() : lineEnd + 1;
const SizeT first = glslCode.find_first_not_of(" \t\r\n", lineStart);
if (first == String::npos) break;
if (first >= next) {
lineStart = next; // a blank line
continue;
}
if (glslCode[first] != '#') break;
insertAt = next;
lineStart = next;
}
if (insertAt > 0 && glslCode[insertAt - 1] != '\n') glslCode.insert(insertAt++, "\n");
glslCode.insert(insertAt, std::format("layout(num_views = {}) in;\n", numViews));
return glslCode;
}
String RequestViewportArrayExtension(String glslCode, Bool needed) {
#ifdef TRACY_ENABLE
ZoneScopedC(TRACY_ZONECOLOR_BACKEND);
+9
View File
@@ -229,6 +229,15 @@ namespace MobileGL::MG_Backend::DirectGLES {
// error, so this is never emitted speculatively. A no-op when not needed or already
// present.
String RequestViewportArrayExtension(String glslCode, Bool needed);
// GL_OVR_multiview: adds `#extension GL_OVR_multiview2 : require` (GL_OVR_multiview where
// the driver has only that one) to a stage that names gl_ViewID_OVR or, in the vertex
// stage, declares `numViews`, and `layout(num_views = numViews) in;` to that vertex stage.
// The SPIR-V reaching SPIRV-Cross carries neither (StripMultiviewCapabilityForEssl), so the
// translation it memoizes stays independent of the view count. Frontend shaders that
// declare only GL_OVR_multiview already keep gl_ViewID_OVR out of every output but
// gl_Position, so asking for the smaller extension on such a driver is honest. A no-op
// for every other stage.
String RequestMultiviewExtension(String glslCode, GLenum shaderType, Int numViews, Bool driverHasMultiview2);
// Adds `#extension <extensionName> : require` when a TESSELLATION or GEOMETRY stage's
// emitted ESSL names gl_PointSize. Desktop GL has that built-in in gl_PerVertex for every
// vertex-processing stage; ESSL does NOT have it in those two at any version - not even
@@ -921,6 +921,15 @@ namespace MobileGL::MG_Backend::DirectVulkan {
if (features.CullDistance) {
extensions.push_back(E_GL_ARB_cull_distance);
}
// Multiview render passes (VkRenderPassMultiviewCreateInfo) and the ViewIndex built-in.
// Vulkan puts no restriction on what ViewIndex may feed, so the second string comes with
// the first.
if (features.Multiview) {
extensions.push_back(E_GL_OVR_multiview);
if (features.Multiview2) {
extensions.push_back(E_GL_OVR_multiview2);
}
}
// Vulkan's drawIndirectFirstInstance feature is optional. Direct base-instance calls work
// without it, but ARB_base_instance also promises non-zero firstInstance in GPU indirect
// commands; the renderer supplies true only when that word is legal and gl_InstanceID can
@@ -1085,6 +1094,9 @@ namespace MobileGL::MG_Backend::DirectVulkan {
}
void BackendObject_DirectVulkan::UpdateAdvertisedExtensions() {
// GL_MAX_VIEWS_OVR beside the strings it decides, so the two cannot disagree.
m_dynamicParameters.MaxViews =
pVulkanRenderer != nullptr ? static_cast<Int>(pVulkanRenderer->GetMultiviewViewCount()) : 0;
// GL_ARB_timer_query gates MC's F3 GPU% (LWJGL checks the extension
// string). InitCapabilities runs after InitWindowSurface has created
// and initialized the renderer, so the advertisement can be gated on
@@ -1105,7 +1117,9 @@ namespace MobileGL::MG_Backend::DirectVulkan {
m_vulkanCaps.SupportsImageCubeArray,
AdvertisedFeatureSupport{.TessellationShader = m_vulkanCaps.SupportsTessellationShader,
.CullDistance =
m_vulkanCaps.SupportsShaderCullDistance && m_vulkanCaps.MaxCullDistances > 0});
m_vulkanCaps.SupportsShaderCullDistance && m_vulkanCaps.MaxCullDistances > 0,
.Multiview = m_dynamicParameters.MaxViews > 0,
.Multiview2 = m_dynamicParameters.MaxViews > 0});
// GL_EXT_fragment_shading_rate rides on VK_KHR_fragment_shading_rate's pipeline rate, and
// its _primitive companion on the primitive rate; both only when the renderer enabled them.
// _attachment is not advertised: no framebuffer carries a rate attachment to this backend.
@@ -1117,6 +1131,28 @@ namespace MobileGL::MG_Backend::DirectVulkan {
}
}
// Without the shaderClipDistance feature the built-in is emulated instead
// (EmulateClipDistancePass: varyings plus a fragment discard, which needs nothing from the
// device), so the frontend can still answer the GL 3.0+ minimum of eight. Every Mali device
// measured so far reports shaderClipDistance = VK_FALSE. MOBILEGL_CLIP_DISTANCE_EMULATION=1
// arms it on a device that has the feature (the pinned integration lane); =0 restores the
// plain zero.
static Bool DecideClipDistanceEmulation(const Bool deviceHasClipDistance) {
switch (MG_Config::Features.ClipDistanceEmulation) {
case MG_Config::QuirkOverride::ForceOn:
MGLOG_I("DirectVulkan: MOBILEGL_CLIP_DISTANCE_EMULATION=1 - emulating gl_ClipDistance even though "
"the device %s shaderClipDistance",
deviceHasClipDistance ? "has" : "lacks");
return true;
case MG_Config::QuirkOverride::ForceOff:
MGLOG_I("DirectVulkan: MOBILEGL_CLIP_DISTANCE_EMULATION=0 - no gl_ClipDistance emulation");
return false;
case MG_Config::QuirkOverride::Auto:
default:
return !deviceHasClipDistance;
}
}
void BackendObject_DirectVulkan::UpdateDynamicBackendParameters() {
const auto mapShaderStages = [](Uint32 vkStages) {
Uint32 glStages = 0;
@@ -1343,40 +1379,20 @@ namespace MobileGL::MG_Backend::DirectVulkan {
// by every device, but declaring ClipDistance in a module needs the shaderClipDistance
// FEATURE, which VulkanRenderer enables exactly where the physical device has it. Without
// it the limit describes a capacity no shader may use, so report none.
//
// Without the feature the built-in is emulated instead (EmulateClipDistancePass: varyings
// plus a fragment discard, which needs nothing from the device), so the frontend can
// still answer the GL 3.0+ minimum of eight. Every Mali device measured so far reports
// shaderClipDistance = VK_FALSE. MOBILEGL_CLIP_DISTANCE_EMULATION=1 arms it on a device
// that has the feature (the pinned integration lane); =0 restores the plain zero.
Bool emulateClipDistance = !m_vulkanCaps.SupportsShaderClipDistance;
switch (MG_Config::Features.ClipDistanceEmulation) {
case MG_Config::QuirkOverride::ForceOn:
emulateClipDistance = true;
MGLOG_I("DirectVulkan: MOBILEGL_CLIP_DISTANCE_EMULATION=1 - emulating gl_ClipDistance even though "
"the device %s shaderClipDistance",
m_vulkanCaps.SupportsShaderClipDistance ? "has" : "lacks");
break;
case MG_Config::QuirkOverride::ForceOff:
emulateClipDistance = false;
MGLOG_I("DirectVulkan: MOBILEGL_CLIP_DISTANCE_EMULATION=0 - no gl_ClipDistance emulation");
break;
case MG_Config::QuirkOverride::Auto:
default:
break;
}
const Bool emulateClipDistance = DecideClipDistanceEmulation(m_vulkanCaps.SupportsShaderClipDistance);
m_dynamicParameters.EmulatesClipDistance = emulateClipDistance;
// Hosted natively, but Vulkan has no per-distance enable state: apply GL_CLIP_DISTANCEi
// in the producing stage instead (EmulateClipDistanceOptions::nativeBuiltin).
m_dynamicParameters.MasksNativeClipDistances = !emulateClipDistance && m_vulkanCaps.SupportsShaderClipDistance;
m_dynamicParameters.MaxClipDistances =
emulateClipDistance ? 8
: (m_vulkanCaps.SupportsShaderClipDistance ? std::max(m_vulkanCaps.MaxClipDistances, 0) : 0);
emulateClipDistance
? 8
: (m_vulkanCaps.SupportsShaderClipDistance ? std::max(m_vulkanCaps.MaxClipDistances, 0) : 0);
MGLOG_I("DirectVulkan: gl_ClipDistance %s (GL_MAX_CLIP_DISTANCES = %d)",
emulateClipDistance ? "EMULATED (varyings + fragment discard)"
: (m_dynamicParameters.MasksNativeClipDistances
? "native, GL_CLIP_DISTANCEi applied in the shader"
: "unsupported"),
emulateClipDistance
? "EMULATED (varyings + fragment discard)"
: (m_dynamicParameters.MasksNativeClipDistances ? "native, GL_CLIP_DISTANCEi applied in the shader"
: "unsupported"),
m_dynamicParameters.MaxClipDistances);
// The cull pair, gated on its own feature. shaderCullDistance is separate from
// shaderClipDistance and VulkanRenderer enables it independently, so it gets its own
@@ -95,23 +95,31 @@ namespace MobileGL::MG_Backend::DirectVulkan {
VkSurfaceKHR surface) {
SwapchainCapabilities swapchainCapabilities{};
VK_VERIFY(
vkGetPhysicalDeviceSurfaceCapabilitiesKHR(physicalDevice, surface, &swapchainCapabilities.capabilities));
if (vkGetPhysicalDeviceSurfaceCapabilitiesKHR(physicalDevice, surface, &swapchainCapabilities.capabilities) !=
VK_SUCCESS)
return {};
Uint32 formatCount = 0;
VK_VERIFY(vkGetPhysicalDeviceSurfaceFormatsKHR(physicalDevice, surface, &formatCount, nullptr));
if (vkGetPhysicalDeviceSurfaceFormatsKHR(physicalDevice, surface, &formatCount, nullptr) != VK_SUCCESS)
return {};
if (formatCount != 0) {
swapchainCapabilities.surfaceFormats.resize(formatCount);
VK_VERIFY(vkGetPhysicalDeviceSurfaceFormatsKHR(physicalDevice, surface, &formatCount,
swapchainCapabilities.surfaceFormats.data()));
if (vkGetPhysicalDeviceSurfaceFormatsKHR(physicalDevice, surface, &formatCount,
swapchainCapabilities.surfaceFormats.data()) != VK_SUCCESS)
return {};
swapchainCapabilities.surfaceFormats.resize(formatCount);
}
Uint32 presentModeCount = 0;
VK_VERIFY(vkGetPhysicalDeviceSurfacePresentModesKHR(physicalDevice, surface, &presentModeCount, nullptr));
if (vkGetPhysicalDeviceSurfacePresentModesKHR(physicalDevice, surface, &presentModeCount, nullptr) !=
VK_SUCCESS)
return {};
if (presentModeCount != 0) {
swapchainCapabilities.presentModes.resize(presentModeCount);
VK_VERIFY(vkGetPhysicalDeviceSurfacePresentModesKHR(physicalDevice, surface, &presentModeCount,
swapchainCapabilities.presentModes.data()));
if (vkGetPhysicalDeviceSurfacePresentModesKHR(physicalDevice, surface, &presentModeCount,
swapchainCapabilities.presentModes.data()) != VK_SUCCESS)
return {};
swapchainCapabilities.presentModes.resize(presentModeCount);
}
return swapchainCapabilities;
@@ -174,8 +182,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
Uint32 graphicsQueueFamily, Uint32 presentQueueFamily, Uint32 minImageCountHint,
Uint32 extraImageCount, VkExtent2D desiredExtent, Optional<Int> swapInterval) {
const auto swapchainCapabilities = GetSwapchainCapabilities(physicalDevice, surface);
MOBILEGL_ASSERT(swapchainCapabilities.IsComplete(),
"SwapchainObject::Create failed: incomplete swapchain capabilities");
if (!swapchainCapabilities.IsComplete()) throw RuntimeError("Incomplete Vulkan swapchain capabilities");
MGLOG_I("Got %d surface formats:", swapchainCapabilities.surfaceFormats.size());
for (const auto& sf : swapchainCapabilities.surfaceFormats) {
@@ -227,8 +234,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
}
createInfo.imageArrayLayers = 1;
const VkImageUsageFlags requiredImageUsage =
VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;
const VkImageUsageFlags requiredImageUsage = RequiredImageUsage;
MOBILEGL_ASSERT((swapchainCaps.supportedUsageFlags & requiredImageUsage) == requiredImageUsage,
"Swapchain does not support required usage flags (COLOR_ATTACHMENT | TRANSFER_DST). "
"supportedUsageFlags=0x%x",
@@ -15,6 +15,9 @@
namespace MobileGL::MG_Backend::DirectVulkan {
class SwapchainObject {
public:
static constexpr VkImageUsageFlags RequiredImageUsage =
VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;
struct SwapchainCapabilities {
VkSurfaceCapabilitiesKHR capabilities;
Vector<VkSurfaceFormatKHR> surfaceFormats;
@@ -134,7 +134,8 @@ namespace MobileGL::MG_Backend::DirectVulkan {
},
.Readback =
[](auto res, const auto& record) {
if (auto* m = WireManager("readback")) m->ReadbackWireBuffer(res, record.Offset, record.Size);
auto* m = WireManager("readback");
return m != nullptr && m->ReadbackWireBuffer(res, record.Offset, record.Size);
},
.Destroy =
[](auto res) {
@@ -712,33 +713,28 @@ namespace MobileGL::MG_Backend::DirectVulkan {
return true;
}
void VkBufferManager::ReadbackWireBuffer(MG_Pipe::MGPipeHandle res, Uint64 offset, Uint64 size) {
// P11 B2: A T0 STORE'S READBACK IS "DONE, NO BYTES". Its pages are the client's
// AHardwareBuffer, so what the client needs before it reads them is this server's GPU
// having finished every write to them - the resident copies WriteWireBuffer recorded and
// any shader write - and nothing crossing SEG_EVENT. The wait is the store's own host-access
// wait (a barrier to host, then the sync point's submission); the reply then says "done".
// One death for both shapes: the store could not be made readable.
Bool VkBufferManager::ReadbackWireBuffer(MG_Pipe::MGPipeHandle res, Uint64 offset, Uint64 size) {
auto* resource = FindWireBuffer(res);
const Bool t0 = resource != nullptr && resource->imported;
Vector<Uint8> bytes(t0 ? 0 : static_cast<SizeT>(size));
if (t0 ? !WaitForWireBufferHostAccess(*resource) : !ReadWireBuffer(res, offset, size, bytes.data())) {
// A lost device: the session is latched and closing; its client reads a lost context.
if (LatchedOnDeviceLoss("buffer-readback")) return;
MGLOG_F("Magma: Fatal{ResourceUnavailable, \"buffer-readback\"} {slot=%u, gen=%u}", res.Slot, res.Gen);
std::abort();
if (resource == nullptr || size == 0 || offset > resource->size || size > resource->size - offset ||
resource->buffer.GetMappedData() == nullptr) {
return false;
}
if (t0) {
return;
if (resource->imported) {
// The frontend reads the shared mapping directly once GPU writes are visible.
if (WaitForWireBufferHostAccess(*resource)) return true;
LatchedOnDeviceLoss("buffer-readback");
return false;
}
if (MG_Pipe::gMGPipeCallbacks.OnBufferWriteback == nullptr) {
MGLOG_F("Magma: Fatal{ResourceUnavailable, \"buffer-writeback-callback\"}");
std::abort();
if (MG_Pipe::gMGPipeCallbacks.OnBufferWriteback == nullptr) return false;
Vector<Uint8> bytes(static_cast<SizeT>(size));
if (!ReadWireBuffer(res, offset, size, bytes.data())) {
LatchedOnDeviceLoss("buffer-readback");
return false;
}
// The reverse producer synchronously copies into SEG_EVENT before
// this owned vector is released; no mapped Vulkan pointer crosses roles.
// The reverse callback copies these bytes before the vector is released.
MG_Pipe::gMGPipeCallbacks.OnBufferWriteback(
res, offset, {reinterpret_cast<Uint64>(bytes.data()), size, MG_Pipe::kMGHostSpanSegNone, 0});
return true;
}
void VkBufferManager::MarkWireBufferGpuWritten(MG_Pipe::MGPipeHandle res, Uint64 offset, Uint64 size) {
@@ -92,7 +92,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
const void* initialBytes);
void WriteWireBuffer(MG_Pipe::MGPipeHandle res, Uint64 offset, Uint64 size, const void* bytes);
void FlushWireBuffer(MG_Pipe::MGPipeHandle res, Uint64 offset, Uint64 size, const void* bytes);
void ReadbackWireBuffer(MG_Pipe::MGPipeHandle res, Uint64 offset, Uint64 size);
Bool ReadbackWireBuffer(MG_Pipe::MGPipeHandle res, Uint64 offset, Uint64 size);
void DestroyWireBuffer(MG_Pipe::MGPipeHandle res);
// P11 B2 (T0): make the client's AHardwareBuffer `ahb` (a BLOB of `size` bytes) buffer
// `res`'s store - a VkBuffer on memory imported through
@@ -45,6 +45,9 @@ namespace MobileGL::MG_Backend::DirectVulkan {
IntVec2 extent = {0, 0};
// VkFramebufferCreateInfo::layers of the entry's framebuffer (>1 for layered GL attachments).
Uint32 layers = 1;
// VkRenderPassMultiviewCreateInfo's view mask, zero when the pass is not multiview. Its
// clear variants carry the same mask, which render-pass compatibility requires.
Uint32 viewMask = 0;
// Frame counter value of the last GetOrCreateRenderPass hit; drives cache eviction.
Uint64 lastUsedFrame = 0;
// P15 S0 (wire passes only): what the render pass was created from, and the render
@@ -69,6 +72,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
std::swap(sampleCount, that.sampleCount);
std::swap(extent, that.extent);
std::swap(layers, that.layers);
std::swap(viewMask, that.viewMask);
std::swap(lastUsedFrame, that.lastUsedFrame);
std::swap(wireAttachments, that.wireAttachments);
std::swap(wireColors, that.wireColors);
@@ -105,6 +109,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
std::swap(sampleCount, that.sampleCount);
std::swap(extent, that.extent);
std::swap(layers, that.layers);
std::swap(viewMask, that.viewMask);
std::swap(lastUsedFrame, that.lastUsedFrame);
std::swap(wireAttachments, that.wireAttachments);
std::swap(wireColors, that.wireColors);
@@ -231,7 +231,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
// only once this backend is the one being brought up, so an Espryt-side bitmask cannot
// kill a Magma run and vice versa.
MagmaPipeValidateSubsystemConfiguration();
CreateInstance();
CreateInstance(m_window != NativeWindowType{});
if (!CreateSurface()) throw RuntimeError("DirectVulkan: the initial surface could not be created");
PickPhysicalDevice();
CreateLogicalDeviceAndQueues();
@@ -445,6 +445,22 @@ namespace MobileGL::MG_Backend::DirectVulkan {
}
void VulkanRenderer::Shutdown() {
if (m_deviceProbe) {
if (m_commandPool) vkDestroyCommandPool(m_device, m_commandPool, nullptr);
DestroyAllocator();
if (m_device) vkDestroyDevice(m_device, nullptr);
if (m_surface) vkDestroySurfaceKHR(m_instance, m_surface, nullptr);
#if defined(VK_USE_PLATFORM_ANDROID_KHR)
if (m_fallbackImageReader) {
const auto deleteReader =
reinterpret_cast<void (*)(void*)>(dlsym(m_platformLibrary, "AImageReader_delete"));
deleteReader(m_fallbackImageReader);
dlclose(m_platformLibrary);
}
#endif
if (m_instance) vkDestroyInstance(m_instance, nullptr);
return;
}
if (m_instance == VK_NULL_HANDLE && m_device == VK_NULL_HANDLE && m_surface == VK_NULL_HANDLE) {
return;
}
@@ -160,6 +160,8 @@ namespace MobileGL::MG_Backend::DirectVulkan {
VulkanRenderer(NativeWindowType window, const VulkanRendererConfig& cfg = {});
~VulkanRenderer();
static Bool ProbeDefaultBackend();
void Initialize();
void Shutdown();
@@ -407,6 +409,9 @@ namespace MobileGL::MG_Backend::DirectVulkan {
// honored rather than accepted-and-ignored.
Bool IsSamplerAnisotropySupported() const { return m_samplerAnisotropyFeatureEnabled; }
const FragmentShadingRateSupport& GetFragmentShadingRateSupport() const { return m_fragmentShadingRate; }
// GL_MAX_VIEWS_OVR: the multiview feature's maxMultiviewViewCount, capped at the 32 views
// a render pass view mask can name; zero when the device was created without multiview.
Uint32 GetMultiviewViewCount() const { return m_multiviewViewCount; }
// ARB_base_instance extends indirect command records with a non-zero firstInstance and
// requires gl_InstanceID to remain zero-based. Vulkan needs both features to honor that
// complete contract: one legalizes the command word, the other enables the shader rebase.
@@ -589,6 +594,9 @@ namespace MobileGL::MG_Backend::DirectVulkan {
// Zero for the default framebuffer, which no arm that reads this ever reaches.
VkImageUsageFlags usageFlags = 0;
Uint32 level = 0, layer = 0, layers = 1, levels = 1;
// GL_OVR_multiview: the surface's view count, zero when it is not multiview. A
// multiview surface's layers are its views, from `layer` on.
Uint32 views = 0;
Bool isDefault = false;
// Set when isDefault: the swapchain image index this role resolved to.
Uint32 swapchainImageIndex = 0;
@@ -633,6 +641,10 @@ namespace MobileGL::MG_Backend::DirectVulkan {
Bool color = false;
VkImageAspectFlags depthStencil = 0;
ClearAttachmentPayload colorPayload{};
// colorPayload against the window format and GL_FRAMEBUFFER_SRGB as they were at the
// glClear (PreCompensateSrgbClearColor): the standalone clear a present or another
// use of the window records later must not read that state again, after the verb.
ClearAttachmentPayload colorPayloadCompensated{};
ClearAttachmentPayload depthStencilPayload{};
Bool Pending() const { return color || depthStencil != 0; }
};
@@ -642,8 +654,9 @@ namespace MobileGL::MG_Backend::DirectVulkan {
void MaterializeDefaultWirePendingClear();
void FoldDefaultWirePendingClear(RenderPassEntry& begun, Uint64& variantKey, VkClearValue* merged);
// Records a clear of `area` of one wire image in a single-attachment pass of its own.
// `colorPreCompensated`: the payload already went through PreCompensateSrgbClearColor.
void RecordWireImageClear(WireImage& image, VkImageAspectFlags aspect, const ClearAttachmentPayload& payload,
const VkRect2D& area, Bool textureSurface);
const VkRect2D& area, Bool textureSurface, Bool colorPreCompensated = false);
static void NoteWirePendingClear(const WireImage& image, VkImageAspectFlags aspects, const VkClearValue& value);
VkRenderPass WireClearVariant(RenderPassEntry& begun, Uint64 variantKey);
Bool BeginWireDrawPassFolding(FrameContext::FrameData& frame, RenderPassEntry& begun, Uint64 variantKey,
@@ -872,6 +885,9 @@ namespace MobileGL::MG_Backend::DirectVulkan {
Vector<Uint32> colorReferences;
Uint32 depthReference = VK_ATTACHMENT_UNUSED;
Uint32 width = 0, height = 0, layers = 1;
// VkRenderPassMultiviewCreateInfo's view mask, zero for a pass that is not multiview
// (whose framebuffer then has `layers` 1).
Uint32 viewMask = 0;
// The rasterization sample count of a pass with no attachments (0 otherwise), where
// nothing else in the key would tell two such passes apart.
Uint32 noAttachmentSamples = 0;
@@ -1257,6 +1273,10 @@ namespace MobileGL::MG_Backend::DirectVulkan {
// Null / all-false on a device without pipelineFragmentShadingRate.
PFN_vkCmdSetFragmentShadingRateKHR s_vkCmdSetFragmentShadingRateKHR = nullptr;
FragmentShadingRateSupport m_fragmentShadingRate{};
// The multiview feature (Vulkan 1.1 core), which backs GL_OVR_multiview: chained into the
// device create info, so it lives as long as the device creation that reads it.
VkPhysicalDeviceMultiviewFeatures m_multiviewFeatures{};
Uint32 m_multiviewViewCount = 0;
// VK_EXT_transform_feedback (GL transform feedback capture)
Bool m_transformFeedbackFeatureEnabled = false;
@@ -1675,7 +1695,8 @@ namespace MobileGL::MG_Backend::DirectVulkan {
// must not allocate.
Vector<VkVertexInputAttributeDescription> m_patchedAttributesScratch;
void CreateInstance();
Bool m_deviceProbe = false;
void CreateInstance(Bool windowSurface);
VkResult SetupDebugMessenger();
VkResult DestroyDebugMessenger();
VkResult SetupDebugReportCallback();
@@ -1738,7 +1759,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
const Vector<VkQueueFamilyProperties>& queueFamilies,
Int preferredFamilyIndex = -1);
static Vector<VkQueueFamilyProperties> GetQueueFamilyFromPhysicalDevice(VkPhysicalDevice device);
static Int GetQueueFamilyIndex(const Vector<VkQueueFamilyProperties>& queueFamilies, VkQueueFlagBits flag);
static Int GetQueueFamilyIndex(const Vector<VkQueueFamilyProperties>& queueFamilies, VkQueueFlags flags);
static Vector<VkExtensionProperties> EnumerateInstanceExtensions();
static Vector<VkExtensionProperties> EnumerateDeviceExtensions(VkPhysicalDevice device);
static Bool IsExtensionSupported(const Vector<VkExtensionProperties>& availableExtensions,
@@ -1747,12 +1768,15 @@ namespace MobileGL::MG_Backend::DirectVulkan {
static Bool EnableOptionalDeviceExtension(const Vector<VkExtensionProperties>& availableExtensions,
Vector<const char*>& inOutEnabledExtensions,
const char* extensionName);
void ChainMultiviewFeature(PFN_vkGetPhysicalDeviceFeatures2 getFeatures2,
PFN_vkGetPhysicalDeviceProperties2 getProperties2,
VkDeviceCreateInfo& deviceCreateInfo);
void ResolveOptionalDeviceExtensions(const Vector<VkExtensionProperties>& availableExtensions,
Vector<const char*>& inOutEnabledExtensions);
static Bool IsNecessaryDeviceExtensionSupported(VkPhysicalDevice device);
static Bool GetMoreCapablePhysicalDevice(VkPhysicalDevice newVkDevice, VkSurfaceKHR surface,
const PhysicalDevice& compareWithDevice,
PhysicalDevice& outBetterDevice);
Bool GetMoreCapablePhysicalDevice(VkPhysicalDevice newVkDevice, VkSurfaceKHR surface,
const PhysicalDevice& compareWithDevice, PhysicalDevice& outBetterDevice,
Bool requireHardware);
static constexpr const char* s_validationLayerNames[] = {"VK_LAYER_KHRONOS_validation"};
// VK_KHR_image_format_list: lets MUTABLE_FORMAT images declare their exact view-format
// set so the driver can keep bandwidth compression (see CreateLogicalDeviceAndQueues).
@@ -70,7 +70,51 @@ namespace MobileGL::MG_Backend::DirectVulkan {
} // namespace
#endif
void VulkanRenderer::CreateInstance() {
namespace {
Bool IsHardwareDevice(VkInstance instance, VkPhysicalDevice device,
const VkPhysicalDeviceProperties& properties) {
if (properties.apiVersion < VK_API_VERSION_1_1 || properties.deviceType == VK_PHYSICAL_DEVICE_TYPE_CPU) {
return false;
}
if (properties.apiVersion >= VK_API_VERSION_1_2) {
VkPhysicalDeviceDriverProperties driver{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES};
VkPhysicalDeviceProperties2 extended{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &driver};
const auto getProperties2 = reinterpret_cast<PFN_vkGetPhysicalDeviceProperties2>(
vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceProperties2"));
if (!getProperties2) return false;
getProperties2(device, &extended);
if (driver.driverID == VK_DRIVER_ID_GOOGLE_SWIFTSHADER || driver.driverID == VK_DRIVER_ID_MESA_LLVMPIPE)
return false;
}
return true;
}
} // namespace
Bool VulkanRenderer::ProbeDefaultBackend() {
VulkanRenderer probe(NativeWindowType{});
probe.m_deviceProbe = true;
probe.m_config.EnableValidationLayers = false;
try {
// The application has not chosen a surface yet. Verify the pbuffer route so
// the process-wide choice also works for applications that never open a window.
probe.CreateInstance(false);
#if !defined(VK_USE_PLATFORM_METAL_EXT)
if (!probe.CreateSurface()) return false;
#endif
probe.PickPhysicalDevice();
probe.CreateLogicalDeviceAndQueues();
probe.CreateAllocator();
probe.CreateCommandPool();
MGLOG_I("DirectVulkan: startup probe passed on %s", probe.m_physicalDevice.properties.deviceName);
return true;
}
catch (const RuntimeError& error) {
MGLOG_I("DirectVulkan: startup probe declined: %s", error.what());
return false;
}
}
void VulkanRenderer::CreateInstance(Bool windowSurface) {
#if defined(VK_USE_PLATFORM_METAL_EXT)
// MoltenVK snapshots its configuration when the loader first discovers the ICD. Set
// this before instance-extension enumeration, while preserving an explicit user value.
@@ -88,7 +132,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
MGLOG_I(" %s (r.%u)", extension.extensionName, extension.specVersion);
}
Bool validationLayerAvailable = CheckValidationLayerSupport();
Bool validationLayerAvailable = !m_deviceProbe && CheckValidationLayerSupport();
MGLOG_I("Validation layers %s.", validationLayerAvailable ? "available" : "not available");
MGLOG_I("Validation layers %s.", m_config.EnableValidationLayers ? "requested" : "not requested");
@@ -136,7 +180,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
// Extensions
Vector<const char*> exts = {VK_KHR_SURFACE_EXTENSION_NAME};
if (!m_window) {
if (!windowSurface) {
#ifdef VK_USE_PLATFORM_METAL_EXT
exts.push_back(VK_EXT_METAL_SURFACE_EXTENSION_NAME);
#elif defined VK_USE_PLATFORM_ANDROID_KHR
@@ -166,6 +210,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
// reported as one below - never papered over with a window.
m_headlessSurfaceSupported = IsExtensionSupported(m_extensions, VK_EXT_HEADLESS_SURFACE_EXTENSION_NAME);
if (!m_headlessSurfaceSupported) {
if (m_deviceProbe) throw RuntimeError("VK_EXT_headless_surface is unavailable");
MGLOG_F("%s is not available from this Vulkan loader, so an offscreen (pbuffer) DirectVulkan "
"surface cannot be created. Refusing to substitute a window: offscreen surfaces must not "
"depend on a window system. Install an ICD that implements it (lavapipe does).",
@@ -214,10 +259,8 @@ namespace MobileGL::MG_Backend::DirectVulkan {
for (const char* ext : exts) {
if (!IsExtensionSupported(m_extensions, ext)) {
MGLOG_E("Required Vulkan instance extension not found: %s", ext);
throw RuntimeError(format("Required Vulkan instance extension not found: {}", ext));
}
MOBILEGL_ASSERT(IsExtensionSupported(m_extensions, ext), "Required Vulkan instance extension not found: %s",
ext);
}
instanceInfo.enabledExtensionCount = exts.size();
@@ -238,7 +281,8 @@ namespace MobileGL::MG_Backend::DirectVulkan {
instanceInfo.pNext = instanceCreatePNext;
VK_VERIFY(vkCreateInstance(&instanceInfo, nullptr, &m_instance), "vkCreateInstance failed");
const VkResult result = vkCreateInstance(&instanceInfo, nullptr, &m_instance);
if (result != VK_SUCCESS) throw RuntimeError(format("vkCreateInstance failed ({})", static_cast<Int>(result)));
if (debugUtilsAvailable) {
VK_VERIFY(SetupDebugMessenger());
@@ -319,8 +363,11 @@ namespace MobileGL::MG_Backend::DirectVulkan {
void VulkanRenderer::PickPhysicalDevice() {
Uint32 deviceCount = 0;
VK_VERIFY(vkEnumeratePhysicalDevices(m_instance, &deviceCount, nullptr));
if (vkEnumeratePhysicalDevices(m_instance, &deviceCount, nullptr) != VK_SUCCESS) {
throw RuntimeError("vkEnumeratePhysicalDevices failed");
}
if (deviceCount == 0) {
if (m_deviceProbe) throw RuntimeError("No Vulkan physical devices available");
// A real, reachable configuration, not a broken invariant: an instance can be
// created from ICDs that load perfectly and then expose no device at all - a
// GPU-less machine with the vendor ICDs installed (RADV/ANV/NVK on a CI runner)
@@ -346,29 +393,26 @@ namespace MobileGL::MG_Backend::DirectVulkan {
// actually written.
const VkResult enumerateResult = vkEnumeratePhysicalDevices(m_instance, &deviceCount, devices.data());
if (enumerateResult != VK_SUCCESS && enumerateResult != VK_INCOMPLETE) {
VK_VERIFY(enumerateResult, "vkEnumeratePhysicalDevices failed");
throw RuntimeError(format("vkEnumeratePhysicalDevices failed ({})", static_cast<Int>(enumerateResult)));
}
devices.resize(deviceCount);
if (devices.empty()) {
MGLOG_F("vkEnumeratePhysicalDevices reported devices and then wrote none");
throw RuntimeError("No Vulkan physical devices available for DirectVulkan");
}
for (Int i = 0; i < deviceCount; i++) {
if (GetMoreCapablePhysicalDevice(devices[i], m_surface, m_physicalDevice, m_physicalDevice))
const Bool requireHardware = m_deviceProbe || MG_Config::AutoSelectBackend;
for (Uint32 i = 0; i < deviceCount; ++i) {
if (GetMoreCapablePhysicalDevice(devices[i], m_surface, m_physicalDevice, m_physicalDevice,
requireHardware))
MGLOG_I("Picked physical device %d.", i);
}
if (m_physicalDevice.handle == VK_NULL_HANDLE) {
m_physicalDevice.handle = devices[0];
vkGetPhysicalDeviceProperties(devices[0], &m_physicalDevice.properties);
MGLOG_I("No suitable physical device picked yet, defaulting to device 0.");
MGLOG_W("No graphics queue found on physical device. Picking a device that doesn't do graphics?");
}
if (!m_physicalDevice.IsComplete()) throw RuntimeError("No suitable DirectVulkan physical device");
}
Bool VulkanRenderer::GetMoreCapablePhysicalDevice(VkPhysicalDevice newVkDevice, VkSurfaceKHR surface,
const PhysicalDevice& otherDevice,
PhysicalDevice& outBetterDevice) {
PhysicalDevice& outBetterDevice, Bool requireHardware) {
const auto deviceTypeToStr = [](VkPhysicalDeviceType type) {
switch (type) {
case VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU:
@@ -396,6 +440,8 @@ namespace MobileGL::MG_Backend::DirectVulkan {
VK_VERSION_MINOR(apiVersion), VK_VERSION_PATCH(apiVersion),
deviceTypeToStr(deviceProperties.deviceType));
if (requireHardware && !IsHardwareDevice(m_instance, newVkDevice, deviceProperties)) return false;
// Check device extensions (including swapchain extension)
Bool deviceExtSupported = IsNecessaryDeviceExtensionSupported(newVkDevice);
if (!deviceExtSupported) {
@@ -406,16 +452,21 @@ namespace MobileGL::MG_Backend::DirectVulkan {
}
// Check swapchain capabilities
auto swapchainCapabilities = SwapchainObject::GetSwapchainCapabilities(newVkDevice, surface);
if (!swapchainCapabilities.IsComplete()) {
outBetterDevice = otherDevice;
MGLOG_I(" Ignored physical device. (Reason: Swapchain capabilities not met)");
return false;
if (surface) {
const auto caps = SwapchainObject::GetSwapchainCapabilities(newVkDevice, surface);
constexpr auto requiredUsage = SwapchainObject::RequiredImageUsage;
if (!caps.IsComplete() ||
(requireHardware && (caps.capabilities.supportedUsageFlags & requiredUsage) != requiredUsage)) {
MGLOG_I(" Ignored physical device. (Reason: Swapchain capabilities not met)");
return false;
}
}
// Check queue families
Vector<VkQueueFamilyProperties> queueFamilies = GetQueueFamilyFromPhysicalDevice(newVkDevice);
newDevice.queueFamilies.graphicsFamily = GetQueueFamilyIndex(queueFamilies, VK_QUEUE_GRAPHICS_BIT);
VkQueueFlags queueFlags = VK_QUEUE_GRAPHICS_BIT;
if (requireHardware) queueFlags |= VK_QUEUE_COMPUTE_BIT;
newDevice.queueFamilies.graphicsFamily = GetQueueFamilyIndex(queueFamilies, queueFlags);
if (newDevice.queueFamilies.graphicsFamily == -1) {
outBetterDevice = otherDevice;
MGLOG_I(" Ignored physical device. (Reason: No graphics queue family)");
@@ -423,7 +474,9 @@ namespace MobileGL::MG_Backend::DirectVulkan {
}
newDevice.queueFamilies.presentFamily =
GetPresentQueueFamilyIndex(newDevice, surface, queueFamilies, newDevice.queueFamilies.graphicsFamily);
surface
? GetPresentQueueFamilyIndex(newDevice, surface, queueFamilies, newDevice.queueFamilies.graphicsFamily)
: newDevice.queueFamilies.graphicsFamily;
if (newDevice.queueFamilies.presentFamily == -1) {
outBetterDevice = otherDevice;
MGLOG_I(" Ignored physical device. (Reason: No present queue family)");
@@ -866,12 +919,10 @@ namespace MobileGL::MG_Backend::DirectVulkan {
VkPhysicalDeviceIndexTypeUint8Features indexTypeUint8Features{};
indexTypeUint8Features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_INDEX_TYPE_UINT8_FEATURES;
if (indexTypeUint8ExtensionName != nullptr) {
if (indexTypeUint8ExtensionName != nullptr && getPhysicalDeviceFeatures2 != nullptr) {
VkPhysicalDeviceFeatures2 featureQuery{};
featureQuery.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
featureQuery.pNext = &indexTypeUint8Features;
MOBILEGL_ASSERT(getPhysicalDeviceFeatures2 != nullptr,
"CreateLogicalDeviceAndQueues: vkGetPhysicalDeviceFeatures2 is unavailable");
getPhysicalDeviceFeatures2(m_physicalDevice.handle, &featureQuery);
if (indexTypeUint8Features.indexTypeUint8 == VK_TRUE) {
if (!IsExtensionAlreadyEnabled(enabledDeviceExtensions, indexTypeUint8ExtensionName)) {
@@ -912,6 +963,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
if (!m_shaderDrawParametersFeatureEnabled) {
MGLOG_W("shaderDrawParameters is unavailable; shaders using gl_DrawID/gl_BaseInstance will not work");
}
ChainMultiviewFeature(getPhysicalDeviceFeatures2, getPhysicalDeviceProperties2, deviceCreateInfo);
// primitiveTopologyListRestart lets primitive restart work on *list* topologies (strip/fan
// restart needs no feature). Optional; enabled via VK_EXT_primitive_topology_list_restart.
@@ -1444,7 +1496,9 @@ namespace MobileGL::MG_Backend::DirectVulkan {
deviceFeatures.drawIndirectFirstInstance ? "true" : "false",
deviceFeatures.multiDrawIndirect ? "true" : "false",
m_shaderDrawParametersFeatureEnabled ? "true" : "false");
VK_VERIFY(vkCreateDevice(m_physicalDevice.handle, &deviceCreateInfo, nullptr, &m_device), "vkCreateDevice");
const VkResult result = vkCreateDevice(m_physicalDevice.handle, &deviceCreateInfo, nullptr, &m_device);
if (result != VK_SUCCESS) throw RuntimeError(format("vkCreateDevice failed ({})", static_cast<Int>(result)));
if (m_deviceProbe) return;
if (wireDepthResolveEnabled) {
m_wireCreateRenderPass2 = reinterpret_cast<PFN_vkCreateRenderPass2>(
@@ -1977,7 +2031,9 @@ namespace MobileGL::MG_Backend::DirectVulkan {
allocatorInfo.pVulkanFunctions = &vulkanFunctions;
allocatorInfo.vulkanApiVersion = VK_API_VERSION_1_0;
VK_VERIFY(vmaCreateAllocator(&allocatorInfo, &m_allocator), "vmaCreateAllocator");
const VkResult result = vmaCreateAllocator(&allocatorInfo, &m_allocator);
if (result != VK_SUCCESS)
throw RuntimeError(format("vmaCreateAllocator failed ({})", static_cast<Int>(result)));
}
void VulkanRenderer::DestroyAllocator() {
@@ -2014,7 +2070,9 @@ namespace MobileGL::MG_Backend::DirectVulkan {
VkCommandPoolCreateInfo createInfo{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO};
createInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
createInfo.queueFamilyIndex = m_physicalDevice.queueFamilies.graphicsFamily;
VK_VERIFY(vkCreateCommandPool(m_device, &createInfo, nullptr, &m_commandPool));
const VkResult result = vkCreateCommandPool(m_device, &createInfo, nullptr, &m_commandPool);
if (result != VK_SUCCESS)
throw RuntimeError(format("vkCreateCommandPool failed ({})", static_cast<Int>(result)));
MGLOG_I("Command pool created");
}
@@ -2108,6 +2166,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
auto* createHeadlessSurface = reinterpret_cast<PFN_vkCreateHeadlessSurfaceEXT>(
vkGetInstanceProcAddr(m_instance, "vkCreateHeadlessSurfaceEXT"));
if (!m_headlessSurfaceSupported || createHeadlessSurface == nullptr) {
if (m_deviceProbe) return false;
MGLOG_F("vkCreateHeadlessSurfaceEXT is unavailable (%s reported as %s) while creating an "
"offscreen DirectVulkan surface",
VK_EXT_HEADLESS_SURFACE_EXTENSION_NAME,
@@ -2115,9 +2174,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
throw RuntimeError("vkCreateHeadlessSurfaceEXT is unavailable for an offscreen DirectVulkan surface");
}
VkHeadlessSurfaceCreateInfoEXT sci{VK_STRUCTURE_TYPE_HEADLESS_SURFACE_CREATE_INFO_EXT};
VK_VERIFY(createHeadlessSurface(m_instance, &sci, nullptr, &m_surface),
"vkCreateHeadlessSurfaceEXT failed");
return true;
return createHeadlessSurface(m_instance, &sci, nullptr, &m_surface) == VK_SUCCESS;
#else
auto* createHeadlessSurface = reinterpret_cast<PFN_vkCreateHeadlessSurfaceEXT>(
vkGetInstanceProcAddr(m_instance, "vkCreateHeadlessSurfaceEXT"));
@@ -2130,9 +2187,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
throw RuntimeError("vkCreateHeadlessSurfaceEXT is unavailable for an offscreen DirectVulkan surface");
}
VkHeadlessSurfaceCreateInfoEXT sci{VK_STRUCTURE_TYPE_HEADLESS_SURFACE_CREATE_INFO_EXT};
VK_VERIFY(createHeadlessSurface(m_instance, &sci, nullptr, &m_surface),
"vkCreateHeadlessSurfaceEXT failed");
return true;
return createHeadlessSurface(m_instance, &sci, nullptr, &m_surface) == VK_SUCCESS;
#endif
}
#if defined VK_USE_PLATFORM_ANDROID_KHR
@@ -2231,10 +2286,9 @@ namespace MobileGL::MG_Backend::DirectVulkan {
return queueFamilies;
}
Int VulkanRenderer::GetQueueFamilyIndex(const Vector<VkQueueFamilyProperties>& queueFamilies,
VkQueueFlagBits flag) {
Int VulkanRenderer::GetQueueFamilyIndex(const Vector<VkQueueFamilyProperties>& queueFamilies, VkQueueFlags flags) {
for (Uint32 i = 0; i < queueFamilies.size(); i++) {
if (queueFamilies[i].queueFlags & flag) {
if (queueFamilies[i].queueCount != 0 && (queueFamilies[i].queueFlags & flags) == flags) {
return i;
}
}
@@ -2274,7 +2328,9 @@ namespace MobileGL::MG_Backend::DirectVulkan {
Vector<VkExtensionProperties> extensions;
for (Uint32 attempt = 0; attempt < 8; ++attempt) {
Uint32 extensionCount = 0;
VK_VERIFY(vkEnumerateInstanceExtensionProperties(nullptr, &extensionCount, nullptr));
if (vkEnumerateInstanceExtensionProperties(nullptr, &extensionCount, nullptr) != VK_SUCCESS) {
throw RuntimeError("vkEnumerateInstanceExtensionProperties failed");
}
extensions.resize(extensionCount);
if (extensionCount == 0) {
return extensions;
@@ -2285,8 +2341,8 @@ namespace MobileGL::MG_Backend::DirectVulkan {
return extensions;
}
if (result != VK_INCOMPLETE) {
VK_VERIFY(result, "vkEnumerateInstanceExtensionProperties failed");
return extensions;
throw RuntimeError(
format("vkEnumerateInstanceExtensionProperties failed ({})", static_cast<Int>(result)));
}
MGLOG_I("vkEnumerateInstanceExtensionProperties returned VK_INCOMPLETE (the loader's list grew "
"mid-enumeration); re-enumerating");
@@ -2298,9 +2354,15 @@ namespace MobileGL::MG_Backend::DirectVulkan {
Vector<VkExtensionProperties> VulkanRenderer::EnumerateDeviceExtensions(VkPhysicalDevice device) {
Uint32 extensionCount = 0;
VK_VERIFY(vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, nullptr));
if (vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, nullptr) != VK_SUCCESS) {
throw RuntimeError("vkEnumerateDeviceExtensionProperties failed");
}
Vector<VkExtensionProperties> extensions(extensionCount);
VK_VERIFY(vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, extensions.data()));
if (extensionCount != 0 &&
vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, extensions.data()) != VK_SUCCESS) {
throw RuntimeError("vkEnumerateDeviceExtensionProperties failed");
}
extensions.resize(extensionCount);
return extensions;
}
@@ -2335,6 +2397,39 @@ namespace MobileGL::MG_Backend::DirectVulkan {
return true;
}
// Multiview for GL_OVR_multiview, on a Vulkan 1.1 device that has it and at least the two views
// GL requires. Only the base feature: GL refuses a multiview draw with a geometry or
// tessellation stage, so their multiview features are never needed.
void VulkanRenderer::ChainMultiviewFeature(PFN_vkGetPhysicalDeviceFeatures2 getFeatures2,
PFN_vkGetPhysicalDeviceProperties2 getProperties2,
VkDeviceCreateInfo& deviceCreateInfo) {
m_multiviewViewCount = 0;
m_multiviewFeatures = {};
m_multiviewFeatures.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_FEATURES;
if (m_physicalDevice.properties.apiVersion < VK_API_VERSION_1_1 || getFeatures2 == nullptr ||
getProperties2 == nullptr)
return;
VkPhysicalDeviceFeatures2 featureQuery{};
featureQuery.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
featureQuery.pNext = &m_multiviewFeatures;
getFeatures2(m_physicalDevice.handle, &featureQuery);
VkPhysicalDeviceMultiviewProperties multiviewProperties{};
multiviewProperties.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_PROPERTIES;
VkPhysicalDeviceProperties2 propertyQuery{};
propertyQuery.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2;
propertyQuery.pNext = &multiviewProperties;
getProperties2(m_physicalDevice.handle, &propertyQuery);
const Bool usable = m_multiviewFeatures.multiview == VK_TRUE && multiviewProperties.maxMultiviewViewCount >= 2;
MGLOG_I("Multiview (GL_OVR_multiview): %s, maxMultiviewViewCount %u", usable ? "enabled" : "unavailable",
multiviewProperties.maxMultiviewViewCount);
if (!usable) return;
m_multiviewFeatures.pNext = const_cast<void*>(deviceCreateInfo.pNext);
m_multiviewFeatures.multiviewGeometryShader = VK_FALSE;
m_multiviewFeatures.multiviewTessellationShader = VK_FALSE;
deviceCreateInfo.pNext = &m_multiviewFeatures;
m_multiviewViewCount = std::min<Uint32>(multiviewProperties.maxMultiviewViewCount, 32u);
}
void VulkanRenderer::ResolveOptionalDeviceExtensions(const Vector<VkExtensionProperties>& availableExtensions,
Vector<const char*>& inOutEnabledExtensions) {
m_drawIndirectCountExtensionEnabled = EnableOptionalDeviceExtension(availableExtensions, inOutEnabledExtensions,
@@ -142,6 +142,17 @@ namespace MobileGL::MG_Backend::DirectVulkan {
return layered(fbo.Depth) || layered(fbo.Stencil);
}
// The multiview chain of a wire draw pass and of its clear variants: one subpass that renders
// the views `viewMask` names. The mask is read through the pointer, so it has to outlive the
// render pass creation, which is why it is taken by reference.
static VkRenderPassMultiviewCreateInfo MakeWireMultiviewInfo(const Uint32& viewMask) {
VkRenderPassMultiviewCreateInfo info{};
info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_MULTIVIEW_CREATE_INFO;
info.subpassCount = 1;
info.pViewMasks = &viewMask;
return info;
}
[[noreturn]] static void WireBufferLegacyFatal() {
MG_Pipe::MGPipeSessionFail(MG_Pipe::MGPipeFatalFamily::RoleViolation,
"MGPipe: Fatal{RoleViolation, \"buffer-legacy-arm\"} (Magma P7 buffer consumer)");
@@ -473,6 +484,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
VkAttachmentReference depth{VK_ATTACHMENT_UNUSED, VK_IMAGE_LAYOUT_GENERAL};
VkExtent2D extent{~0u, ~0u};
Uint32 layers = ~0u;
Uint32 views = 0;
VkSampleCountFlagBits samples = VK_SAMPLE_COUNT_1_BIT;
Uint64 passHash = 0;
auto& passKey = scratch.passKey;
@@ -499,6 +511,18 @@ namespace MobileGL::MG_Backend::DirectVulkan {
image = ResolveWireImage(fbo, surface, aspect, /*isWriteTarget=*/true);
}
if (!image.image) return VK_ATTACHMENT_UNUSED;
// Only a pending clear of exactly this attachment's level and layers can become its
// load op. One of other layers (another layer of a multiview or layered attachment)
// would otherwise stay pending past this pass and land on top of its draws.
if (image.resource != nullptr &&
std::any_of(image.resource->pendingClears.begin(), image.resource->pendingClears.end(),
[&](const VkTextureManager::WirePendingClear& entry) {
return entry.level != image.level || entry.layer != image.layer ||
entry.layers != image.layers;
})) {
MaterializeWirePendingClears(*image.resource);
image.layout = image.resource->layout;
}
m_textureManager->FlushPendingUploads();
m_wirePassMemo.attachments.push_back(
{image.resource, image.storage, surface.Kind == MG_Pipe::kMGPipeSurfaceKindRenderbuffer});
@@ -539,6 +563,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
extent.width = std::min(extent.width, image.extent.width);
extent.height = std::min(extent.height, image.extent.height);
layers = std::min(layers, image.layers);
views = std::max(views, image.views);
samples = image.samples;
passHash = XXH64(&description, sizeof(description), passHash);
// Marked below, once the pass is known: a continued pass repeats the same marks.
@@ -603,6 +628,14 @@ namespace MobileGL::MG_Backend::DirectVulkan {
passKey.noAttachmentSamples = static_cast<Uint32>(samples);
passHash = XXH64(&samples, sizeof(samples), passHash);
}
// GL_OVR_multiview: one view per attachment layer, rendered through a single framebuffer
// layer, which is what a multiview render pass requires of its framebuffer.
const Uint32 viewMask = views == 0 ? 0u : (views >= 32 ? ~0u : (1u << views) - 1u);
if (viewMask != 0) {
layers = 1;
passHash = XXH64(&viewMask, sizeof(viewMask), passHash);
}
passKey.viewMask = viewMask;
passKey.width = extent.width;
passKey.height = extent.height;
passKey.layers = layers;
@@ -623,6 +656,8 @@ namespace MobileGL::MG_Backend::DirectVulkan {
passInfo.pAttachments = attachments.data();
passInfo.subpassCount = 1;
passInfo.pSubpasses = &subpass;
const VkRenderPassMultiviewCreateInfo multiview = MakeWireMultiviewInfo(passKey.viewMask);
if (viewMask != 0) passInfo.pNext = &multiview;
continuing = m_wireDrawPass && m_wireDrawPassKey == passKey;
{
const auto* active = VkRenderPassManager::GetActiveRenderPass();
@@ -665,6 +700,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
created.sampleCount = samples;
created.extent = {static_cast<Int>(extent.width), static_cast<Int>(extent.height)};
created.layers = layers;
created.viewMask = viewMask;
created.hash = created.compatibilityHash =
XXH64(colors.data(), colors.size() * sizeof(colors[0]), passHash);
created.wireAttachments.assign(attachments.begin(), attachments.end());
@@ -709,6 +745,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
for (const auto& color : colors)
pipelinePassKey.colorReferences.push_back(color.attachment);
pipelinePassKey.depthReference = depth.attachment;
pipelinePassKey.viewMask = viewMask;
m_wireDrawPassCompatibilityId = m_wireRenderPassCompatibility.Intern(pipelinePassKey);
}
} // !passContinues
@@ -1401,6 +1438,8 @@ namespace MobileGL::MG_Backend::DirectVulkan {
info.pAttachments = descriptions.data();
info.subpassCount = 1;
info.pSubpasses = &subpass;
const VkRenderPassMultiviewCreateInfo multiview = MakeWireMultiviewInfo(begun.viewMask);
if (begun.viewMask != 0) info.pNext = &multiview;
VkRenderPass variant = VK_NULL_HANDLE;
VK_VERIFY(vkCreateRenderPass(m_device, &info, nullptr, &variant));
begun.clearVariants.push_back({variantKey, variant});
@@ -1464,6 +1503,8 @@ namespace MobileGL::MG_Backend::DirectVulkan {
if (color) {
pending.color = true;
pending.colorPayload = payload;
pending.colorPayloadCompensated = payload;
PreCompensateSrgbClearColor(pending.colorPayloadCompensated, m_swapchainObject.GetSurfaceFormat().format);
m_swapchainObject.SetImageContentDefined(index, true);
}
if (depthStencil & VK_IMAGE_ASPECT_DEPTH_BIT) pending.depthStencilPayload.depth = payload.depth;
@@ -1494,7 +1535,8 @@ namespace MobileGL::MG_Backend::DirectVulkan {
image.image = m_swapchainObject.GetImage(pending.swapchainImageIndex);
image.format = m_swapchainObject.GetSurfaceFormat().format;
image.layout = m_swapchainObject.GetImageLayout(pending.swapchainImageIndex);
RecordWireImageClear(image, VK_IMAGE_ASPECT_COLOR_BIT, pending.colorPayload, area, false);
RecordWireImageClear(image, VK_IMAGE_ASPECT_COLOR_BIT, pending.colorPayloadCompensated, area, false,
/*colorPreCompensated=*/true);
}
if (pending.depthStencil && m_swapchainObject.GetDepthStencilImage(pending.swapchainImageIndex)) {
image.aspect = pending.depthStencil;
@@ -721,6 +721,10 @@ namespace MobileGL::MG_Backend::DirectVulkan {
out.layer = layer;
out.is3D = resource->depth > 1;
out.layers = surface.Layered ? (out.is3D ? std::max(resource->depth >> level, 1u) : availableLayers) : 1;
if (!renderbuffer && surface.NumViews != 0) {
out.views = surface.NumViews;
out.layers = surface.NumViews;
}
const Bool oneDimensional =
resource->viewType == VK_IMAGE_VIEW_TYPE_1D || resource->viewType == VK_IMAGE_VIEW_TYPE_1D_ARRAY;
out.viewType = oneDimensional ? (out.layers > 1 ? VK_IMAGE_VIEW_TYPE_1D_ARRAY : VK_IMAGE_VIEW_TYPE_1D)
@@ -1115,7 +1119,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
void VulkanRenderer::RecordWireImageClear(WireImage& image, VkImageAspectFlags aspect,
const ClearAttachmentPayload& payload, const VkRect2D& area,
Bool textureSurface) {
Bool textureSurface, Bool colorPreCompensated) {
const Bool color = aspect == VK_IMAGE_ASPECT_COLOR_BIT;
const auto layout =
color ? VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL : VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
@@ -1168,7 +1172,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
begin.framebuffer = fb;
begin.renderArea = area;
auto clearPayload = payload;
if (color) PreCompensateSrgbClearColor(clearPayload, image.format);
if (color && !colorPreCompensated) PreCompensateSrgbClearColor(clearPayload, image.format);
VkClearAttachment clear{};
clear.aspectMask = aspect;
clear.clearValue.color = MakeVkClearColorValue(clearPayload, false);
@@ -2298,7 +2302,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
MG_Pipe::MGPSurface surface{};
surface.Kind = MG_Pipe::kMGPipeSurfaceKindTexture;
surface.Res = state.VerbCopyTexDst;
surface.Level = static_cast<Uint16>(level);
surface.Level = static_cast<Uint8>(level);
WireImage source = ResolveWireImage(*read,
aspect & VK_IMAGE_ASPECT_DEPTH_BIT ? read->Depth
: aspect & VK_IMAGE_ASPECT_STENCIL_BIT ? read->Stencil
@@ -11,14 +11,16 @@
#include "../VkIncludes.h"
namespace MobileGL::MG_Backend::DirectVulkan {
// The wire draw pass has one graphics subpass, no input attachments,
// multiview or extensions. Its Vulkan pipeline compatibility is formats,
// sample counts and the ordered attachment references, not native handles,
// image identity, dimensions, load/store operations or image layouts.
// The wire draw pass has one graphics subpass, no input attachments and,
// besides multiview, no extensions. Its Vulkan pipeline compatibility is
// formats, sample counts, the ordered attachment references and the view
// mask, not native handles, image identity, dimensions, load/store
// operations or image layouts.
struct WireRenderPassCompatibilityKey {
Vector<Uint64> attachmentFormatsAndSamples;
Vector<Uint32> colorReferences;
Uint32 depthReference = VK_ATTACHMENT_UNUSED;
Uint32 viewMask = 0;
Bool operator==(const WireRenderPassCompatibilityKey&) const = default;
};
@@ -35,6 +37,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
for (const auto value : key.colorReferences)
mix(value);
mix(key.depthReference);
mix(key.viewMask);
return hash;
}
};
+61 -16
View File
@@ -28,17 +28,8 @@ namespace MobileGL::MG_Backend {
return false;
}
// A DISPLAY IS A CONNECTION, NOT A RESOURCE THIS BACKEND OWNS, and refusing the second one
// refused a caller for a reason that is not there: the surface and context tables are keyed
// by the display each was created on, every operation carries its own display handle, and
// this field has no reader anywhere - it was the whole of the rule.
//
// What the rule cost was a compositor. One asks for the display it will draw into AFTER
// probing another, so the second eglInitialize is the one that matters, and a refusal there
// is reported one layer up as "no usable DRM render device" - the probe having succeeded
// and the real display having failed, with nothing in between that says which was refused.
m_display = dpy;
m_displayInitialized = true;
m_initializedDisplays.insert(dpy);
if (major) {
*major = 1;
}
@@ -79,7 +70,7 @@ namespace MobileGL::MG_Backend {
Bool EGLSurfaceRegistry::RegisterWindowSurface(EGLSurface surface, const WindowHandle& handle) {
const std::lock_guard<std::recursive_mutex> lock(m_mutex);
if (!m_displayInitialized) {
if (!DisplayInitialized(RegistrationDisplay())) {
MGLOG_E("RegisterEGLWindowSurface failed: EGL display is not initialized");
return false;
}
@@ -95,6 +86,7 @@ namespace MobileGL::MG_Backend {
auto& state = m_surfaces[surface];
state = SurfaceState{
.Kind = SurfaceKind::Window,
.Display = RegistrationDisplay(),
.Window = handle,
.Width = static_cast<EGLint>(std::max<Uint32>(handle.Width, 1)),
.Height = static_cast<EGLint>(std::max<Uint32>(handle.Height, 1)),
@@ -104,7 +96,7 @@ namespace MobileGL::MG_Backend {
Bool EGLSurfaceRegistry::RegisterPbufferSurface(EGLSurface surface, EGLint width, EGLint height) {
const std::lock_guard<std::recursive_mutex> lock(m_mutex);
if (!m_displayInitialized) {
if (!DisplayInitialized(RegistrationDisplay())) {
MGLOG_E("RegisterEGLPbufferSurface failed: EGL display is not initialized");
return false;
}
@@ -119,6 +111,7 @@ namespace MobileGL::MG_Backend {
m_surfaces[surface] = SurfaceState{
.Kind = SurfaceKind::Pbuffer,
.Display = RegistrationDisplay(),
.Width = width,
.Height = height,
};
@@ -181,10 +174,15 @@ namespace MobileGL::MG_Backend {
return true;
}
if (!m_displayInitialized || m_display != dpy) {
if (!DisplayInitialized(dpy)) {
MGLOG_E("MakeEGLCurrent failed: EGL display mismatch or not initialized");
return false;
}
const auto* drawState = Registered(draw);
const auto* readState = Registered(read);
if ((drawState && (drawState->Display != dpy || drawState->DestroyPending)) ||
(readState && (readState->Display != dpy || readState->DestroyPending)))
return false;
if (!m_hasActiveSurface) {
if (draw != read || !Activate(draw)) {
MGLOG_E("MakeEGLCurrent failed: EGL surface is not initialized");
@@ -246,7 +244,7 @@ namespace MobileGL::MG_Backend {
Bool EGLSurfaceRegistry::Swap(EGLDisplay dpy, EGLSurface draw) {
const std::lock_guard<std::recursive_mutex> lock(m_mutex);
if (!m_displayInitialized || m_display != dpy) {
if (!DisplayInitialized(dpy)) {
MGLOG_E("SwapEGLBuffers failed: EGL display mismatch or not initialized");
return false;
}
@@ -281,6 +279,15 @@ namespace MobileGL::MG_Backend {
return true;
}
Bool EGLSurfaceRegistry::IsCurrentOnOtherThread(EGLSurface surface) const {
const auto lock = Lock();
const auto thread = CurrentThreadKey();
for (const auto& [owner, current] : m_currentThreads) {
if (owner != thread && (current.DrawSurface == surface || current.ReadSurface == surface)) return true;
}
return false;
}
Bool EGLSurfaceRegistry::IsCurrentOnAnyThread(EGLSurface surface) const {
if (surface == EGL_NO_SURFACE) {
return false;
@@ -345,7 +352,8 @@ namespace MobileGL::MG_Backend {
ResetRuntimeState();
m_surfaces.clear();
m_display = EGL_NO_DISPLAY;
m_displayInitialized = false;
m_initializedDisplays.clear();
m_registrationDisplay = EGL_NO_DISPLAY;
}
void EGLSurfaceRegistry::SetWindowHandle(const WindowHandle& handle) {
@@ -393,7 +401,44 @@ namespace MobileGL::MG_Backend {
Bool EGLSurfaceRegistry::DisplayInitialized() const {
const std::lock_guard<std::recursive_mutex> lock(m_mutex);
return m_displayInitialized;
return !m_initializedDisplays.empty();
}
Bool EGLSurfaceRegistry::DisplayInitialized(EGLDisplay display) const {
const std::lock_guard<std::recursive_mutex> lock(m_mutex);
return m_initializedDisplays.contains(display);
}
EGLDisplay EGLSurfaceRegistry::SetRegistrationDisplay(EGLDisplay display) {
const std::lock_guard<std::recursive_mutex> lock(m_mutex);
return std::exchange(m_registrationDisplay, display);
}
EGLDisplay EGLSurfaceRegistry::RegistrationDisplay() const {
const std::lock_guard<std::recursive_mutex> lock(m_mutex);
return m_registrationDisplay == EGL_NO_DISPLAY ? m_display : m_registrationDisplay;
}
Vector<EGLDisplay> EGLSurfaceRegistry::InitializedDisplays() const {
const std::lock_guard<std::recursive_mutex> lock(m_mutex);
return {m_initializedDisplays.begin(), m_initializedDisplays.end()};
}
Vector<EGLSurface> EGLSurfaceRegistry::SurfacesOnDisplay(EGLDisplay display) const {
const std::lock_guard<std::recursive_mutex> lock(m_mutex);
Vector<EGLSurface> result;
for (const auto& [surface, state] : m_surfaces) {
if (state.Display == display) result.push_back(surface);
}
return result;
}
void EGLSurfaceRegistry::ReleaseDisplay(EGLDisplay display) {
const std::lock_guard<std::recursive_mutex> lock(m_mutex);
m_initializedDisplays.erase(display);
if (m_display == display) {
m_display = m_initializedDisplays.empty() ? EGL_NO_DISPLAY : *m_initializedDisplays.begin();
}
}
EGLDisplay EGLSurfaceRegistry::Display() const {
+10 -1
View File
@@ -48,6 +48,7 @@ namespace MobileGL::MG_Backend {
struct SurfaceState {
SurfaceKind Kind = SurfaceKind::None;
EGLDisplay Display = EGL_NO_DISPLAY;
Bool DestroyPending = false;
// Activated at least once: a re-activation (a multi-window client switching back)
// is a re-bind and does not re-run the backend's capability probe.
@@ -92,6 +93,11 @@ namespace MobileGL::MG_Backend {
Bool MakeCurrent(EGLDisplay dpy, EGLSurface draw, EGLSurface read, EGLContext ctx);
Bool Swap(EGLDisplay dpy, EGLSurface draw);
void ReleaseSurface(EGLSurface surface);
void ReleaseDisplay(EGLDisplay display);
EGLDisplay SetRegistrationDisplay(EGLDisplay display);
EGLDisplay RegistrationDisplay() const;
Vector<EGLDisplay> InitializedDisplays() const;
Vector<EGLSurface> SurfacesOnDisplay(EGLDisplay display) const;
// Every surface, the display and every thread's current state; no hook runs.
void ReleaseAll();
void SetWindowHandle(const WindowHandle& handle);
@@ -117,6 +123,7 @@ namespace MobileGL::MG_Backend {
// ---- queries --------------------------------------------------------------------------
Bool DisplayInitialized() const;
Bool DisplayInitialized(EGLDisplay display) const;
EGLDisplay Display() const;
Bool HasActiveSurface() const;
EGLSurface ActiveSurface() const;
@@ -130,6 +137,7 @@ namespace MobileGL::MG_Backend {
Bool IsRegistered(EGLSurface surface) const;
Optional<SurfaceState> Find(EGLSurface surface) const;
Optional<CurrentState> CurrentOn(std::thread::id thread) const;
Bool IsCurrentOnOtherThread(EGLSurface surface) const;
SizeT CurrentThreadCount() const;
private:
@@ -144,7 +152,8 @@ namespace MobileGL::MG_Backend {
EGLDisplay m_display = EGL_NO_DISPLAY;
EGLSurface m_activeSurface = EGL_NO_SURFACE;
EGLSurface m_activatingSurface = EGL_NO_SURFACE;
Bool m_displayInitialized = false;
std::unordered_set<EGLDisplay> m_initializedDisplays;
EGLDisplay m_registrationDisplay = EGL_NO_DISPLAY;
Bool m_hasActiveSurface = false;
Bool m_capabilitiesInitialized = false;
SurfaceKind m_activeSurfaceKind = SurfaceKind::None;
+172 -81
View File
@@ -187,13 +187,68 @@ namespace MobileGL::MG_Impl::EGLImpl {
#endif
std::recursive_mutex& EGLOperationMutex() {
static std::recursive_mutex mutex;
return mutex;
static auto* mutex = new std::recursive_mutex();
return *mutex;
}
#if MOBILEGL_BUILD_DISAGGREGATED
struct EGLThreadBinding {
Bool Bound = false;
~EGLThreadBinding() {
if (Bound) (void)ReleaseThread();
}
};
EGLThreadBinding& ThreadBinding() {
thread_local EGLThreadBinding binding;
return binding;
}
class ScopedEGLObjectShareGroup {
public:
ScopedEGLObjectShareGroup(MG_Backend::BackendObject* backend, Uint64 group)
: m_backend(backend), m_previous(backend ? backend->SetEGLObjectShareGroup(group) : 0) {}
~ScopedEGLObjectShareGroup() {
if (m_backend) (void)m_backend->SetEGLObjectShareGroup(m_previous);
}
private:
MG_Backend::BackendObject* m_backend;
Uint64 m_previous;
};
void ReleaseContextStandIn(EGLContext context);
void FinishLocalContextDestroy(EGLContext context, Uint64 token, Uint64 group,
SharedPtr<MG_State::GLState::GLContext> glState) {
auto* backend = MG_Backend::pActiveBackendObject.get();
{
const ScopedEGLObjectShareGroup scope(backend, group);
glState.reset();
}
if (backend) backend->ReleaseEGLContext(token);
ReleaseContextStandIn(context);
}
} // namespace
std::recursive_mutex* LockGLCommands(Bool bindStream) {
#if MOBILEGL_BUILD_DISAGGREGATED
if (MG_Remote::Client::RunsAsTheServerRole()) return nullptr;
#endif
auto& mutex = EGLOperationMutex();
mutex.lock();
#if MOBILEGL_BUILD_DISAGGREGATED
if (StreamGateActive()) {
if (bindStream) StreamBindCallingThreadLocked();
return &mutex;
}
#else
(void)bindStream;
#endif
if (auto* backend = MG_Backend::pActiveBackendObject.get()) backend->BeginEGLCommands();
return &mutex;
}
#if MOBILEGL_BUILD_DISAGGREGATED
Bool StreamGateActive() {
return MG_Config::Transport != MG_Config::TransportMode::Monolith && !MG_Remote::Client::RunsAsTheServerRole();
}
@@ -279,7 +334,10 @@ namespace MobileGL::MG_Impl::EGLImpl {
void FinishReapedContexts(MG_State::EGLState::EGLContext* state) {
if (state == nullptr) return;
if (!StreamGateActive()) {
(void)state->TakeReapedContexts(); // dropping them ends their GL state
for (auto& reaped : state->TakeReapedContexts()) {
FinishLocalContextDestroy(reaped.Handle, reaped.ClientContextToken, reaped.ShareGroupToken,
Move(reaped.GLStateObject));
}
return;
}
for (auto& reaped : state->TakeReapedContexts()) {
@@ -291,11 +349,18 @@ namespace MobileGL::MG_Impl::EGLImpl {
namespace {
#else
namespace {
// A monolith has no stream to bind: a context whose deferred destroy completed simply ends.
void FinishReapedContexts(MG_State::EGLState::EGLContext* state) {
if (state != nullptr) (void)state->TakeReapedContexts();
if (state == nullptr) return;
for (auto& reaped : state->TakeReapedContexts()) {
FinishLocalContextDestroy(reaped.Handle, reaped.ClientContextToken, reaped.ShareGroupToken,
Move(reaped.GLStateObject));
}
}
#endif
void TearDownIdleEGL(EGLStateContext* state);
String CurrentThreadIdString() {
std::ostringstream stream;
stream << std::this_thread::get_id();
@@ -366,27 +431,38 @@ namespace MobileGL::MG_Impl::EGLImpl {
return *surfaces;
}
// EGL_KHR_surfaceless_context. The EGL state records a surfaceless binding as exactly that
// (eglGetCurrentSurface answers EGL_NO_SURFACE), but every backend renders into the surface
// it was bound to, and a session's capabilities are published on its first bind to one. So
// the backend is bound to a 1x1 pbuffer of the display's own instead: one per display, made
// on the first surfaceless bind, never handed to the application, and gone with the display
// (eglTerminate). Guarded by EGLOperationMutex.
std::unordered_map<EGLDisplay, EGLSurface>& SurfacelessStandIns() {
static auto* standIns = new std::unordered_map<EGLDisplay, EGLSurface>();
return *standIns;
}
// A private pbuffer backs a surfaceless context. Native contexts that can be
// current concurrently need distinct pbuffers; split clients serialize on one.
// eglCreatePbufferSurface for the stand-in, except that a split client creates it on the
// server as a stand-in, which takes no surface mode there (a server-owned window may follow).
EGLSurface CreateSurfacelessStandInPbuffer(EGLStateContext* state, EGLDisplay dpy, EGLConfig config,
const EGLint* attribs);
// The display's stand-in, made now if it has none (or the one it had did not survive).
// EGL_NO_SURFACE when the backend could not make a pbuffer; the EGL error is then set.
EGLSurface SurfacelessStandIn(EGLStateContext* state, EGLDisplay dpy) {
auto& standIns = SurfacelessStandIns();
if (const auto it = standIns.find(dpy); it != standIns.end()) {
using StandInKey = std::pair<EGLDisplay, EGLContext>;
std::map<StandInKey, EGLSurface>& ContextStandIns() {
static auto* standIns = new std::map<StandInKey, EGLSurface>();
return *standIns;
}
void ReleaseContextStandIn(EGLContext context) {
auto& standIns = ContextStandIns();
const auto it = std::find_if(standIns.begin(), standIns.end(),
[context](const auto& entry) { return entry.first.second == context; });
if (it == standIns.end()) return;
const auto [display, surface] = std::pair(it->first.first, it->second);
standIns.erase(it);
if (auto* state = GetState(); state && state->ValidateSurfaceOnDisplay(display, surface)) {
(void)DestroySurface(display, surface);
}
}
EGLSurface SurfacelessStandIn(EGLStateContext* state, EGLDisplay dpy, EGLContext ctx) {
auto& standIns = ContextStandIns();
#if MOBILEGL_BUILD_DISAGGREGATED
if (StreamGateActive()) ctx = EGL_NO_CONTEXT;
#endif
const StandInKey key{dpy, ctx};
if (const auto it = standIns.find(key); it != standIns.end()) {
if (state->ValidateSurfaceOnDisplay(dpy, it->second)) return it->second;
standIns.erase(it);
}
@@ -399,7 +475,7 @@ namespace MobileGL::MG_Impl::EGLImpl {
}
const EGLint attribs[] = {EGL_WIDTH, 1, EGL_HEIGHT, 1, EGL_NONE};
const EGLSurface standIn = CreateSurfacelessStandInPbuffer(state, dpy, config, attribs);
if (standIn != EGL_NO_SURFACE) standIns[dpy] = standIn;
if (standIn != EGL_NO_SURFACE) standIns[key] = standIn;
return standIn;
}
@@ -469,7 +545,7 @@ namespace MobileGL::MG_Impl::EGLImpl {
if (surface == EGL_NO_SURFACE) return true;
(void)state->ResizeSurface(dpy, surface, width, height);
auto* backendObject = GetBackendObject(state);
if (!backendObject || !backendObject->CreateEGLPbufferSurface(surface, width, height)) {
if (!backendObject || !backendObject->CreateEGLPbufferSurfaceOnDisplay(dpy, surface, width, height)) {
MGLOG_E("eglCreateWindowSurface: the backend refused the %dx%d drawable behind a Wayland window", width,
height);
state->DestroySurface(dpy, surface);
@@ -491,13 +567,15 @@ namespace MobileGL::MG_Impl::EGLImpl {
if (it == WaylandSurfaces().end()) return;
EGLint width = 0;
EGLint height = 0;
if (!it->second->TakeResize(&width, &height)) return;
(void)state->ResizeSurface(dpy, surface, width, height);
if (!it->second->GetPendingResize(&width, &height)) return;
auto* backendObject = MG_Backend::pActiveBackendObject.get();
if (backendObject == nullptr || !backendObject->ResizeEGLWindowSurface(surface, static_cast<Uint32>(width),
static_cast<Uint32>(height))) {
MGLOG_E("Wayland: the drawable behind a %dx%d window could not be resized", width, height);
return;
}
(void)state->ResizeSurface(dpy, surface, width, height);
it->second->CommitResize(width, height);
}
#endif
@@ -615,7 +693,7 @@ namespace MobileGL::MG_Impl::EGLImpl {
if (!RecoverBeforeCreatingSurface(state)) return EGL_NO_SURFACE;
const EGLSurface surface = state->CreatePbufferSurface(dpy, config, attribs);
if (surface == EGL_NO_SURFACE) return EGL_NO_SURFACE;
if (!remote->CreateEGLSurfacelessStandIn(surface, GetAttribValue(attribs, EGL_WIDTH, 1),
if (!remote->CreateEGLSurfacelessStandIn(dpy, surface, GetAttribValue(attribs, EGL_WIDTH, 1),
GetAttribValue(attribs, EGL_HEIGHT, 1))) {
state->DestroySurface(dpy, surface);
state->SetError(EGL_BAD_ALLOC);
@@ -720,7 +798,7 @@ namespace MobileGL::MG_Impl::EGLImpl {
state->DestroySurface(dpy, surface);
return EGL_NO_SURFACE;
}
if (!backendObject->CreateEGLWindowSurface(surface, windowHandle)) {
if (!backendObject->CreateEGLWindowSurfaceOnDisplay(dpy, surface, windowHandle)) {
state->DestroySurface(dpy, surface);
state->SetError(EGL_BAD_NATIVE_WINDOW);
return EGL_NO_SURFACE;
@@ -845,6 +923,7 @@ namespace MobileGL::MG_Impl::EGLImpl {
if (!state) {
return EGL_NO_CONTEXT;
}
const std::lock_guard<std::recursive_mutex> operationLock(EGLOperationMutex());
// The API the context is for, as the dispatcher reports it (SetDispatcherCurrentApiHook):
// an ES context made without an eglBindAPI - or with one of the default - is an ES context.
if (const auto currentApi = g_dispatcherCurrentApi.load()) {
@@ -856,7 +935,6 @@ namespace MobileGL::MG_Impl::EGLImpl {
// session comes up (RecoverLostSession) - before the context's GL state is built, because
// building it already emits the creates of its default objects. Sharing with a lost
// context would share objects no reachable server holds.
const std::lock_guard<std::recursive_mutex> operationLock(EGLOperationMutex());
// The lost share group this context replaces (ReplacementShareContexts), 0 for none.
Uint64 replacedGroup = 0;
if (StreamGateActive()) {
@@ -888,10 +966,18 @@ namespace MobileGL::MG_Impl::EGLImpl {
#else
constexpr Bool splitClient = false;
#endif
EGLContext context = state->CreateContext(dpy, config, shareCtx, attrib_list, splitClient);
EGLContext context =
state->CreateContext(dpy, config, shareCtx, attrib_list, true, ResetNotificationAvailable());
if (context == EGL_NO_CONTEXT) {
return EGL_NO_CONTEXT;
}
if (!splitClient) {
auto* backend = MG_Backend::pActiveBackendObject.get();
const Uint64 group = state->GetContextShareGroupToken(context);
if (backend) backend->RegisterEGLContext(context, state->GetContextClientToken(context), group);
const ScopedEGLObjectShareGroup scope(backend, group);
(void)state->BuildContextGLState(context);
}
#if MOBILEGL_BUILD_DISAGGREGATED
if (replacedGroup != 0) ReplacementShareContexts()[replacedGroup].push_back(context);
#endif
@@ -927,7 +1013,8 @@ namespace MobileGL::MG_Impl::EGLImpl {
replacedGroup = state->GetContextShareGroupToken(shareCtx);
shareCtx = ReplacementShareContext(state, dpy, replacedGroup);
}
context = state->CreateContext(dpy, config, shareCtx, attrib_list, splitClient);
context =
state->CreateContext(dpy, config, shareCtx, attrib_list, true, ResetNotificationAvailable());
}
if (context == EGL_NO_CONTEXT) {
state->SetError(EGL_BAD_ALLOC);
@@ -1012,13 +1099,6 @@ namespace MobileGL::MG_Impl::EGLImpl {
if (!state) {
return EGL_FALSE;
}
// A release (explicit, or the implicit one of binding another context) may complete the
// deferred destroy of the context it releases; that destroy is finished on the way out,
// under the lock, whichever way this call returns.
struct FinishReapedOnExit {
EGLStateContext* State;
~FinishReapedOnExit() { FinishReapedContexts(State); }
} finishReaped{state};
const auto oldDisplay = state->GetCurrentDisplay();
const auto oldDraw = state->GetCurrentSurface(EGL_DRAW);
@@ -1053,26 +1133,27 @@ namespace MobileGL::MG_Impl::EGLImpl {
}
#endif
#if MOBILEGL_WAYLAND_WINDOWS
if (draw != EGL_NO_SURFACE) ApplyWaylandResize(state, dpy, draw);
#endif
if (!state->MakeCurrent(dpy, draw, read, ctx)) {
if (!state->MakeCurrent(dpy, draw, read, ctx, true)) {
const EGLint error = state->ConsumeError();
MGLOG_D("eglMakeCurrent rejected by EGLState thread=%s error=0x%04x", threadId.c_str(), error);
state->SetError(error);
return EGL_FALSE;
}
#if MOBILEGL_WAYLAND_WINDOWS
if (draw != EGL_NO_SURFACE) ApplyWaylandResize(state, dpy, draw);
#endif
const Bool releaseCurrentRequest = draw == EGL_NO_SURFACE && read == EGL_NO_SURFACE && ctx == EGL_NO_CONTEXT;
if (releaseCurrentRequest) {
if (auto* backendObject = MG_Backend::pActiveBackendObject.get()) {
if (!backendObject->MakeEGLCurrent(dpy, draw, read, ctx)) {
MGLOG_E_ONCE("eglMakeCurrent release failed in backend thread=%s", threadId.c_str());
state->MakeCurrent(oldDisplay, oldDraw, oldRead, oldContext);
state->SetError(EGL_BAD_ACCESS);
return EGL_FALSE;
}
}
(void)state->MakeCurrent(dpy, draw, read, ctx);
ThreadBinding().Bound = false;
MGLOG_D("eglMakeCurrent release succeeded thread=%s", threadId.c_str());
#if MOBILEGL_BUILD_DISAGGREGATED
{
@@ -1081,26 +1162,25 @@ namespace MobileGL::MG_Impl::EGLImpl {
EmitContextBinding(state, EGL_NO_CONTEXT, oldContextToken);
}
#endif
FinishReapedContexts(state);
if (oldDisplay != EGL_NO_DISPLAY && !state->IsDisplayInitialized(oldDisplay)) TearDownIdleEGL(state);
return EGL_TRUE;
}
auto* backendObject = GetBackendObject(state);
if (!backendObject) {
MGLOG_E_ONCE("activeBackendObject not initialized!");
state->MakeCurrent(oldDisplay, oldDraw, oldRead, oldContext);
return EGL_FALSE;
}
// A surfaceless binding (EGL_KHR_surfaceless_context; EGLState took it above and records
// EGL_NO_SURFACE): the backend gets the display's stand-in pbuffer to render into.
// The frontend records a surfaceless binding. The backend renders into a private pbuffer.
EGLSurface backendDraw = draw;
EGLSurface backendRead = read;
if (draw == EGL_NO_SURFACE && read == EGL_NO_SURFACE) {
backendDraw = backendRead = SurfacelessStandIn(state, dpy);
backendDraw = backendRead = SurfacelessStandIn(state, dpy, ctx);
if (backendDraw == EGL_NO_SURFACE) {
const EGLint error = state->ConsumeError();
MGLOG_E_ONCE("eglMakeCurrent: no stand-in pbuffer for a surfaceless binding thread=%s (error=0x%04x)",
threadId.c_str(), error);
state->MakeCurrent(oldDisplay, oldDraw, oldRead, oldContext);
state->SetError(error != EGL_SUCCESS ? error : EGL_BAD_ALLOC);
return EGL_FALSE;
}
@@ -1109,14 +1189,17 @@ namespace MobileGL::MG_Impl::EGLImpl {
MGLOG_E_ONCE("eglMakeCurrent backend attach failed thread=%s dpy=%p draw=%p read=%p ctx=%p",
threadId.c_str(), dpy, draw, read, ctx);
state->SetError(EGL_BAD_ACCESS);
state->MakeCurrent(oldDisplay, oldDraw, oldRead, oldContext);
return EGL_FALSE;
}
(void)state->MakeCurrent(dpy, draw, read, ctx);
// Construct the guard after GL-state TLS so it releases the EGL binding first at exit.
ThreadBinding().Bound = true;
MGLOG_D("eglMakeCurrent attach succeeded thread=%s dpy=%p draw=%p read=%p ctx=%p", threadId.c_str(), dpy, draw,
read, ctx);
#if MOBILEGL_BUILD_DISAGGREGATED
EmitContextBinding(state, ctx, oldContextToken);
#endif
FinishReapedContexts(state);
return EGL_TRUE;
}
@@ -1125,7 +1208,6 @@ namespace MobileGL::MG_Impl::EGLImpl {
if (!state) {
return EGL_FALSE;
}
#if MOBILEGL_BUILD_DISAGGREGATED
// Under the operation lock, like every GL call: what ends here writes records.
const std::lock_guard<std::recursive_mutex> destroyLock(EGLOperationMutex());
// P14 S1. Read BEFORE the client's own book drops the context: after DestroyContext
@@ -1138,7 +1220,6 @@ namespace MobileGL::MG_Impl::EGLImpl {
// A LOST CONTEXT IS DESTROYED IN SILENCE. Its objects die here, and a death that reached
// the wire would land on whichever session is current now - a fresh one after a recovery,
// which never created them.
const Bool lost = ContextIsLost(state, ctx);
// The context's GL state, held across the book's drop so that its objects end in
// FinishContextDestroy, under the context's own binding, rather than inside EGLState.
SharedPtr<MG_State::GLState::GLContext> glState = state->GetContextGLState(ctx);
@@ -1146,16 +1227,19 @@ namespace MobileGL::MG_Impl::EGLImpl {
if (!state->DestroyContext(dpy, ctx, &deferred)) {
return EGL_FALSE;
}
// A current context keeps drawing until its owner releases it.
#if MOBILEGL_BUILD_DISAGGREGATED
ForgetReplacementShareContext(ctx);
// CURRENT TO A THREAD (this one or another): EGL destroys it once it is released, and that
// release finishes it (FinishReapedContexts). Until then its thread keeps drawing in it.
#endif
if (deferred) return EGL_TRUE;
FinishContextDestroy(contextToken, shareGroupToken, Move(glState), lost);
#else
if (!state->DestroyContext(dpy, ctx)) {
return EGL_FALSE;
#if MOBILEGL_BUILD_DISAGGREGATED
if (StreamGateActive()) {
const Bool lost = glState && (glState->IsFromEndedWireSession() || ClientSession::SessionLatchedLost());
FinishContextDestroy(contextToken, shareGroupToken, Move(glState), lost);
return EGL_TRUE;
}
#endif
FinishLocalContextDestroy(ctx, contextToken, shareGroupToken, Move(glState));
return EGL_TRUE;
}
@@ -1178,7 +1262,17 @@ namespace MobileGL::MG_Impl::EGLImpl {
return EGL_TRUE;
}
namespace {
void TearDownIdleEGL(EGLStateContext* state) {
if (state->HasAnyInitializedDisplay() || state->HasAnyCurrentContext()) return;
if (auto* backend = MG_Backend::pActiveBackendObject.get()) backend->ReleaseEGLResources();
MG_State::ReleaseProcessDefaultGLContext();
MobileGL::Destroy();
}
} // namespace
EGLBoolean Terminate(EGLDisplay dpy) {
const std::lock_guard<std::recursive_mutex> operationLock(EGLOperationMutex());
auto* state = GetState();
if (!state) {
return EGL_FALSE;
@@ -1186,51 +1280,38 @@ namespace MobileGL::MG_Impl::EGLImpl {
if (!state->TerminateDisplay(dpy)) {
return EGL_FALSE;
}
{
// The display's surfaces went with it, its surfaceless stand-in among them; the backend
// side goes with ReleaseEGLResources below.
const std::lock_guard<std::recursive_mutex> operationLock(EGLOperationMutex());
SurfacelessStandIns().erase(dpy);
}
std::erase_if(ContextStandIns(), [dpy](const auto& entry) { return entry.first.first == dpy; });
FinishReapedContexts(state);
if (auto* backendObject = MG_Backend::pActiveBackendObject.get()) {
// The display's dma-buf EGLImages went with it; so do their shared-image references.
MG_Backend::ClientHooks* client = backendObject->AsClient();
for (const Uint64 sharedImageId : state->TakeOrphanedSharedImages()) {
if (client != nullptr) (void)client->ReleaseSharedImage(sharedImageId);
}
backendObject->ReleaseEGLResources();
}
// The last initialized display is gone and nothing is current on any
// thread: tear the whole library down deterministically inside the
// EGL lifecycle (backend, GL/EGL state, glslang). A later EGL call
// re-initializes lazily via GetStateEnsureInitialized(); process exit
// then has nothing left to destroy.
if (!state->HasAnyInitializedDisplay() && !state->HasAnyCurrentContext()) {
// P14 S3: the process default context (and with it the GL objects the frontend
// built while no EGL context was current) goes before Destroy() does, so nothing
// it owns outlives glslang::FinalizeProcess() through a thread's fallback binding.
MG_State::ReleaseProcessDefaultGLContext();
MobileGL::Destroy();
backendObject->ReleaseEGLDisplay(dpy);
}
TearDownIdleEGL(state);
return EGL_TRUE;
}
EGLBoolean ReleaseThread() {
// Always succeeds (EGL 1.4 §3.11): after the last eglTerminate tore MobileGL down there is
// simply nothing of this thread's left to release.
if (!MG_State::pEGLContext) return EGL_TRUE;
// EGL thread release also runs when an application thread exits.
const std::lock_guard<std::recursive_mutex> operationLock(EGLOperationMutex());
if (!MG_State::pEGLContext) return EGL_TRUE;
auto* state = GetState();
const EGLDisplay oldDisplay = state->GetCurrentDisplay();
if (auto* backendObject = MG_Backend::pActiveBackendObject.get()) {
(void)backendObject->MakeEGLCurrent(EGL_NO_DISPLAY, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
}
state->ReleaseThread();
ThreadBinding().Bound = false;
#if MOBILEGL_BUILD_DISAGGREGATED
// The release edge, as eglMakeCurrent's release sends it: this thread has no context now,
// and the binding must not keep naming the one it had.
EmitContextBinding(state, EGL_NO_CONTEXT, 0);
#endif
FinishReapedContexts(state);
if (oldDisplay != EGL_NO_DISPLAY && !state->IsDisplayInitialized(oldDisplay)) TearDownIdleEGL(state);
return EGL_TRUE;
}
@@ -1405,7 +1486,9 @@ namespace MobileGL::MG_Impl::EGLImpl {
// this query an application reads have to agree: an application that does not see the
// platform extension here never asks for a platform display at all.
if (display == EGL_NO_DISPLAY) return kClientExtensionString;
return SharedImagesAvailable() ? kDisplayExtensionStringWithSharedImages : kDisplayExtensionString;
if (SharedImagesAvailable()) return kDisplayExtensionStringWithSharedImages;
return ResetNotificationAvailable() ? kDisplayExtensionStringWithResetNotification
: kDisplayExtensionString;
default:
state->SetError(EGL_BAD_PARAMETER);
return nullptr;
@@ -1449,7 +1532,7 @@ namespace MobileGL::MG_Impl::EGLImpl {
if (!backendObject) {
return EGL_NO_SURFACE;
}
if (!backendObject->CreateEGLPbufferSurface(surface, width, height)) {
if (!backendObject->CreateEGLPbufferSurfaceOnDisplay(dpy, surface, width, height)) {
state->DestroySurface(dpy, surface);
state->SetError(EGL_BAD_ALLOC);
return EGL_NO_SURFACE;
@@ -1670,6 +1753,14 @@ namespace MobileGL::MG_Impl::EGLImpl {
g_dispatcherCurrentApi.store(hook);
}
Bool ResetNotificationAvailable() {
#if MOBILEGL_BUILD_DISAGGREGATED
return StreamGateActive();
#else
return false;
#endif
}
Bool SharedImagesAvailable() {
#if MOBILEGL_BUILD_DISAGGREGATED
// A split client's backend is the remote one, which forwards the shared-image verbs to
@@ -2000,7 +2091,7 @@ namespace MobileGL::MG_Impl::EGLImpl {
state->DestroySurface(dpy, surface);
return EGL_NO_SURFACE;
}
if (!backendObject->CreateEGLWindowSurface(surface, windowHandle)) {
if (!backendObject->CreateEGLWindowSurfaceOnDisplay(dpy, surface, windowHandle)) {
state->DestroySurface(dpy, surface);
state->SetError(EGL_BAD_NATIVE_WINDOW);
return EGL_NO_SURFACE;
+12 -20
View File
@@ -68,6 +68,8 @@ namespace MobileGL::MG_Impl::EGLImpl {
// a split client's does, a monolith's does not. Decides the dma-buf EGL extensions, the
// Wayland linux-dmabuf presentation and GL_OES_EGL_image.
Bool SharedImagesAvailable();
// Reset reporting is provided by the split client through its session.
Bool ResetNotificationAvailable();
// Whether the server also holds YUV (NV12/P010) images: decides the YUV dma-buf formats and
// GL_OES_EGL_image_external. One round trip the first time it is asked, cached after.
Bool SharedImageYuvAvailable();
@@ -114,15 +116,14 @@ namespace MobileGL::MG_Impl::EGLImpl {
// (a monolith, the server's own apply thread), where no binding crosses. Read under
// StreamMutex(), like the binding itself.
Bool StreamBoundShareGroupToken(Uint64* outToken);
#endif
// Serialize commands that use the same backend binding shadows.
std::recursive_mutex* LockGLCommands(Bool bindStream = true);
class GLStreamScope {
public:
GLStreamScope() {
if (!StreamGateActive()) return;
m_mutex = &StreamMutex();
m_mutex->lock();
StreamBindCallingThreadLocked();
}
GLStreamScope() : m_mutex(LockGLCommands()) {}
~GLStreamScope() {
if (m_mutex != nullptr) m_mutex->unlock();
}
@@ -130,18 +131,13 @@ namespace MobileGL::MG_Impl::EGLImpl {
GLStreamScope& operator=(const GLStreamScope&) = delete;
private:
std::recursive_mutex* m_mutex = nullptr;
std::recursive_mutex* m_mutex;
};
// The lock alone, for every EGL entry point: an EGL call may publish into the ring too (a
// surface forwarder's catch-up wait, a present, a context frame), and a second thread's GL
// record written into the middle of it is a torn record the server latches the session on.
// EGL commands serialize without changing the remote stream's current context.
class StreamLockScope {
public:
StreamLockScope() {
if (!StreamGateActive()) return;
m_mutex = &StreamMutex();
m_mutex->lock();
}
StreamLockScope() : m_mutex(LockGLCommands(false)) {}
~StreamLockScope() {
if (m_mutex != nullptr) m_mutex->unlock();
}
@@ -149,10 +145,6 @@ namespace MobileGL::MG_Impl::EGLImpl {
StreamLockScope& operator=(const StreamLockScope&) = delete;
private:
std::recursive_mutex* m_mutex = nullptr;
std::recursive_mutex* m_mutex;
};
#else
class GLStreamScope {};
class StreamLockScope {};
#endif
} // namespace MobileGL::MG_Impl::EGLImpl
@@ -25,23 +25,19 @@ namespace MobileGL::MG_Impl::EGLImpl {
inline constexpr const char* kPlatformExtensionString =
"EGL_EXT_client_extensions EGL_EXT_platform_base EGL_KHR_platform_base "
"EGL_MESA_platform_surfaceless" MOBILEGL_PLATFORM_WAYLAND_EXTENSIONS;
// EGL_EXT_create_context_robustness: a context may ask for EGL_LOSE_CONTEXT_ON_RESET, and a
// split client's contexts are lost exactly when their server session is (a device loss on the
// server ends that session). An application learns of it through glGetGraphicsResetStatus only
// if it could ask for it here: ANGLE's GL-on-EGL backend mirrors this extension onto its own
// display, and Chrome checks that display for it before it ever queries the reset status.
inline constexpr const char* kDisplayExtensionString =
"EGL_KHR_create_context EGL_KHR_surfaceless_context EGL_KHR_no_config_context EGL_EXT_platform_base "
"EGL_EXT_create_context_robustness EGL_KHR_platform_base "
"EGL_MESA_platform_surfaceless" MOBILEGL_PLATFORM_WAYLAND_EXTENSIONS;
#define MOBILEGL_DISPLAY_EXTENSIONS \
"EGL_KHR_create_context EGL_KHR_surfaceless_context EGL_KHR_no_config_context EGL_EXT_platform_base " \
"EGL_KHR_platform_base EGL_MESA_platform_surfaceless" MOBILEGL_PLATFORM_WAYLAND_EXTENSIONS
inline constexpr const char* kDisplayExtensionString = MOBILEGL_DISPLAY_EXTENSIONS;
// The split client reports a lost server session through glGetGraphicsResetStatus.
inline constexpr const char* kDisplayExtensionStringWithResetNotification =
MOBILEGL_DISPLAY_EXTENSIONS " EGL_EXT_create_context_robustness";
// The display list again, with the dma-buf import a backend with shared images has (a split
// client: the server allocates the images and names the descriptors that come back). A
// monolith has no allocator to recognize a dma-buf with, so it never advertises these. The
// same server answers the buffer age of its surfaces and takes swap damage to its presents.
inline constexpr const char* kDisplayExtensionStringWithSharedImages =
"EGL_KHR_create_context EGL_KHR_surfaceless_context EGL_KHR_no_config_context EGL_EXT_platform_base "
"EGL_EXT_create_context_robustness EGL_KHR_platform_base "
"EGL_MESA_platform_surfaceless" MOBILEGL_PLATFORM_WAYLAND_EXTENSIONS
inline constexpr const char* kDisplayExtensionStringWithSharedImages = MOBILEGL_DISPLAY_EXTENSIONS
" EGL_EXT_create_context_robustness"
" EGL_KHR_image_base EGL_EXT_image_dma_buf_import EGL_EXT_image_dma_buf_import_modifiers"
" EGL_EXT_buffer_age EGL_KHR_partial_update EGL_KHR_swap_buffers_with_damage"
" EGL_EXT_swap_buffers_with_damage"
@@ -49,6 +45,7 @@ namespace MobileGL::MG_Impl::EGLImpl {
// which is also what publishes a context's writes into dma-bufs to the compositor without a
// swap: Chrome's GPU process ends each frame with one rather than a flush.
" EGL_KHR_fence_sync EGL_KHR_wait_sync EGL_ANDROID_native_fence_sync";
#undef MOBILEGL_DISPLAY_EXTENSIONS
inline constexpr const char* kClientExtensionString =
"EGL_EXT_client_extensions EGL_KHR_create_context EGL_EXT_platform_base "
"EGL_KHR_platform_base EGL_MESA_platform_surfaceless" MOBILEGL_PLATFORM_WAYLAND_EXTENSIONS;
+9 -6
View File
@@ -813,17 +813,20 @@ namespace MobileGL::MG_Impl::EGLImpl::Wayland {
return UniquePtr<WindowSurface>(new WindowSurface(std::move(impl)));
}
Bool WindowSurface::TakeResize(EGLint* width, EGLint* height) {
Impl& impl = *m_impl;
Bool WindowSurface::GetPendingResize(EGLint* width, EGLint* height) const {
const Impl& impl = *m_impl;
if (impl.window == nullptr || impl.window->width <= 0 || impl.window->height <= 0) return false;
if (impl.window->width == impl.width && impl.window->height == impl.height) return false;
impl.width = impl.window->width;
impl.height = impl.window->height;
*width = impl.width;
*height = impl.height;
*width = impl.window->width;
*height = impl.window->height;
return true;
}
void WindowSurface::CommitResize(EGLint width, EGLint height) {
m_impl->width = width;
m_impl->height = height;
}
void WindowSurface::OnSessionReplaced() {
Impl& impl = *m_impl;
const Api& api = WaylandApi();
+3 -4
View File
@@ -97,10 +97,9 @@ namespace MobileGL::MG_Impl::EGLImpl::Wayland {
};
PresentResult Present(const MG_Util::Damage::Region& damage, Int swapInterval, Bool (*sessionLost)());
// wl_egl_window_resize's effect, taken: true (with the new size) when the application gave
// its wl_egl_window a size this presentation is not at yet. The presentation adopts it -
// its next buffer is that size - and the caller resizes the drawable behind it.
Bool TakeResize(EGLint* width, EGLint* height);
// Keep a resize pending until the backing drawable has been resized.
Bool GetPendingResize(EGLint* width, EGLint* height) const;
void CommitResize(EGLint width, EGLint height);
// A swap that presents nothing (its context was lost) still commits the application's
// wl_surface, with no new buffer: the frame callback a toolkit asked for just before the
+20 -30
View File
@@ -177,11 +177,16 @@ namespace MobileGL::MG_Impl::GLImpl {
return false;
}
if (bufferObject->IsMapped() && !(bufferObject->GetMappingAccess() & BufferMappingAccessBit::Persistent)) {
const SizeT clearStart = static_cast<SizeT>(offset);
const SizeT clearSize = static_cast<SizeT>(size);
const Range1D mappedRange = bufferObject->GetMappedRange();
if (clearSize != 0 && bufferObject->IsMapped() &&
!(bufferObject->GetMappingAccess() & BufferMappingAccessBit::Persistent) &&
clearStart < mappedRange.end && clearStart + clearSize > mappedRange.start) {
MG_State::pGLContext->RecordError(
ErrorCode::InvalidOperation,
MakeUnique<GenericErrorInfo>("MG_Impl/GLImpl", GetBufferOpName(op),
"Cannot clear a non-persistently mapped buffer object."));
"Clear range overlaps a non-persistently mapped range."));
return false;
}
@@ -267,11 +272,7 @@ namespace MobileGL::MG_Impl::GLImpl {
}
SharedPtr<MG_State::GLState::BufferObject> GetNamedBufferObject(GLuint buffer, BufferOp op) {
if (!BufferImpl::ValidateBufferName(buffer, false)) return nullptr;
if (!MG_State::pGLContext->ValidateBufferObject(buffer)) {
MG_State::pGLContext->CreateBufferObject(buffer);
}
auto& bufferObject = MG_State::pGLContext->GetBufferObject(buffer);
const auto& bufferObject = MG_State::pGLContext->GetBufferObject(buffer);
if (!bufferObject) {
MG_State::pGLContext->RecordError(
ErrorCode::InvalidOperation,
@@ -615,8 +616,7 @@ namespace MobileGL::MG_Impl::GLImpl {
return GL_FALSE;
}
bufferObject->ReleaseMemory();
return GL_TRUE;
return bufferObject->ReleaseMemory() ? GL_TRUE : GL_FALSE;
}
void* MapBufferRange_State(GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access) {
@@ -709,16 +709,11 @@ namespace MobileGL::MG_Impl::GLImpl {
if (!ValidateImmutableMapAccess(bufferObject, accessBits, BufferOp::MapBufferRange)) return nullptr;
if (bufferObject->IsMapped()) {
const auto invalidateFlags =
BufferMappingAccessBit::InvalidateRange | BufferMappingAccessBit::InvalidateBuffer;
if (!(accessBits & invalidateFlags)) {
MG_State::pGLContext->RecordError(
ErrorCode::InvalidOperation,
MakeUnique<GenericErrorInfo>("MG_Impl/GLImpl", "MapBufferRange_State",
"Cannot map a buffer object that is already mapped."));
return nullptr;
}
MG_State::pGLContext->RecordError(
ErrorCode::InvalidOperation,
MakeUnique<GenericErrorInfo>("MG_Impl/GLImpl", "MapBufferRange_State",
"Cannot map a buffer object that is already mapped."));
return nullptr;
}
void* result = bufferObject->AcquireMemoryRange(
@@ -1341,15 +1336,11 @@ namespace MobileGL::MG_Impl::GLImpl {
if (!ValidateImmutableMapAccess(bufferObject, accessBits, BufferOp::MapNamedBufferRange)) return nullptr;
if (bufferObject->IsMapped()) {
const auto invalidateFlags =
BufferMappingAccessBit::InvalidateRange | BufferMappingAccessBit::InvalidateBuffer;
if (!(accessBits & invalidateFlags)) {
MG_State::pGLContext->RecordError(
ErrorCode::InvalidOperation,
MakeUnique<GenericErrorInfo>("MG_Impl/GLImpl", "MapNamedBufferRange_State",
"Cannot map a buffer object that is already mapped."));
return nullptr;
}
MG_State::pGLContext->RecordError(
ErrorCode::InvalidOperation,
MakeUnique<GenericErrorInfo>("MG_Impl/GLImpl", "MapNamedBufferRange_State",
"Cannot map a buffer object that is already mapped."));
return nullptr;
}
return bufferObject->AcquireMemoryRange({static_cast<SizeT>(offset), static_cast<SizeT>(offset + length)},
@@ -1366,8 +1357,7 @@ namespace MobileGL::MG_Impl::GLImpl {
"Cannot unmap a buffer object that is not mapped."));
return GL_FALSE;
}
bufferObject->ReleaseMemory();
return GL_TRUE;
return bufferObject->ReleaseMemory() ? GL_TRUE : GL_FALSE;
}
void FlushMappedNamedBufferRange_State(GLuint buffer, GLintptr offset, GLsizeiptr length) {
@@ -21,6 +21,7 @@
// in FixupGsStripCaptureOrder - for the reason CONTRACT-P5B.md §6.5 gives.
#include <MG_Remote/Client/SlotCaps.h>
#include "../Getter/GL_Getter.h"
#include "../Framebuffer/GL_Framebuffer.h"
namespace MobileGL::MG_Impl::GLImpl {
static Bool ValidateProgramForExecution(const SharedPtr<MG_State::GLState::ProgramObject>& currentProgram,
@@ -87,7 +88,7 @@ namespace MobileGL::MG_Impl::GLImpl {
return false;
}
return true;
return ValidateMultiviewDraw(*currentProgram, functionName);
}
// gl_NumSamples has no SPIR-V built-in, so the source pipeline lowers it onto a reserved
@@ -116,8 +117,7 @@ namespace MobileGL::MG_Impl::GLImpl {
if (!program || !program->UsesReservedClipDistanceEnables()) return;
Uint32 enables = 0;
for (Uint i = 0; i < 8; ++i) {
const auto cap =
static_cast<CapabilityInput>(static_cast<Uint>(CapabilityInput::ClipDistance0) + i);
const auto cap = static_cast<CapabilityInput>(static_cast<Uint>(CapabilityInput::ClipDistance0) + i);
if (MG_State::pGLContext->IsCapabilityEnabled(cap)) enables |= 1u << i;
}
program->WriteReservedClipDistanceEnables(enables);
@@ -2041,6 +2041,8 @@ DECLARE_GL_FUNCTION_STUB_HEAD(void, GetPixelTransformParameterivEXT, GLenum targ
DECLARE_GL_FUNCTION_STUB_HEAD(void, GetPixelTransformParameterfvEXT, GLenum target, GLenum pname, GLfloat* params) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, GetPixelTransformParameterfvEXT, target, pname, params)
DECLARE_GL_FUNCTION_STUB_HEAD(void, PointParameterfEXT, GLenum pname, GLfloat param) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, PointParameterfEXT, pname, param)
DECLARE_GL_FUNCTION_STUB_HEAD(void, PointParameterfvEXT, GLenum pname, const GLfloat* params) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, PointParameterfvEXT, pname, params)
DECLARE_GL_FUNCTION_HEAD(void, FramebufferTextureMultiviewOVR, GLenum target, GLenum attachment, GLuint texture, GLint level, GLint baseViewIndex, GLsizei numViews) DECLARE_GL_FUNCTION_END_NO_RETURN(void, FramebufferTextureMultiviewOVR, target, attachment, texture, level, baseViewIndex, numViews)
DECLARE_GL_FUNCTION_HEAD(void, NamedFramebufferTextureMultiviewOVR, GLuint framebuffer, GLenum attachment, GLuint texture, GLint level, GLint baseViewIndex, GLsizei numViews) DECLARE_GL_FUNCTION_END_NO_RETURN(void, NamedFramebufferTextureMultiviewOVR, framebuffer, attachment, texture, level, baseViewIndex, numViews)
DECLARE_GL_FUNCTION_HEAD(void, GetFragmentShadingRatesEXT, GLsizei samples, GLsizei maxCount, GLsizei* count, GLenum* shadingRates) DECLARE_GL_FUNCTION_END_NO_RETURN(void, GetFragmentShadingRatesEXT, samples, maxCount, count, shadingRates)
DECLARE_GL_FUNCTION_HEAD(void, ShadingRateEXT, GLenum rate) DECLARE_GL_FUNCTION_END_NO_RETURN(void, ShadingRateEXT, rate)
DECLARE_GL_FUNCTION_HEAD(void, ShadingRateCombinerOpsEXT, GLenum combinerOp0, GLenum combinerOp1) DECLARE_GL_FUNCTION_END_NO_RETURN(void, ShadingRateCombinerOpsEXT, combinerOp0, combinerOp1)
@@ -2694,7 +2696,6 @@ DECLARE_GL_FUNCTION_STUB_HEAD(void, VideoCaptureStreamParameterivNV, GLuint vide
DECLARE_GL_FUNCTION_STUB_HEAD(void, VideoCaptureStreamParameterfvNV, GLuint video_capture_slot, GLuint stream, GLenum pname, const GLfloat* params) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, VideoCaptureStreamParameterfvNV, video_capture_slot, stream, pname, params)
DECLARE_GL_FUNCTION_STUB_HEAD(void, VideoCaptureStreamParameterdvNV, GLuint video_capture_slot, GLuint stream, GLenum pname, const GLdouble* params) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, VideoCaptureStreamParameterdvNV, video_capture_slot, stream, pname, params)
DECLARE_GL_FUNCTION_STUB_HEAD(void, ViewportSwizzleNV, GLuint index, GLenum swizzlex, GLenum swizzley, GLenum swizzlez, GLenum swizzlew) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, ViewportSwizzleNV, index, swizzlex, swizzley, swizzlez, swizzlew)
DECLARE_GL_FUNCTION_STUB_HEAD(void, FramebufferTextureMultiviewOVR, GLenum target, GLenum attachment, GLuint texture, GLint level, GLint baseViewIndex, GLsizei numViews) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, FramebufferTextureMultiviewOVR, target, attachment, texture, level, baseViewIndex, numViews)
DECLARE_GL_FUNCTION_STUB_HEAD(void, HintPGI, GLenum target, GLint mode) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, HintPGI, target, mode)
DECLARE_GL_FUNCTION_STUB_HEAD(void, DetailTexFuncSGIS, GLenum target, GLsizei n, const GLfloat* points) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, DetailTexFuncSGIS, target, n, points)
DECLARE_GL_FUNCTION_STUB_HEAD(void, GetDetailTexFuncSGIS, GLenum target, GLfloat* points) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, GetDetailTexFuncSGIS, target, points)
@@ -111,6 +111,7 @@ namespace MobileGL::MG_Impl::GLImpl {
// property no single attachment's state explains.
GLenum IncompleteFramebufferStatus(const MG_State::GLState::FramebufferObject& framebufferObject) {
if (framebufferObject.HasLayerTargetMismatch()) return GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS;
if (framebufferObject.HasViewTargetMismatch()) return GL_FRAMEBUFFER_INCOMPLETE_VIEW_TARGETS_OVR;
return HasDefinedAttachment(framebufferObject) ? GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT
: GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT;
}
@@ -363,6 +364,9 @@ namespace MobileGL::MG_Impl::GLImpl {
Bool TryAnswerAttachmentFormatQuery(const MG_State::GLState::FramebufferAttachmentObject* attachmentObject,
FramebufferAttachmentType attachmentType, Bool depthStencilAlias,
GLenum pname, GLint* params, const char* caller) {
// The two GL_OVR_multiview pnames take the same fallback out of both query switches.
if (FramebufferImpl::TryAnswerMultiviewAttachmentQuery(attachmentObject, pname, params, caller))
return true;
switch (pname) {
case GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE:
case GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE:
@@ -489,72 +493,8 @@ namespace MobileGL::MG_Impl::GLImpl {
}
}
// GL 4.6 core 9.2.8 conditions that depend only on the framebuffer and the attachment
// point. Shared, because glFramebufferTexture / 1D / 2D / 3D / TextureLayer are aliases of
// one another in that section and a CTS case that walks the family must not get five
// different answers - which is exactly what happened when these lived in one helper that
// only two of the five went through.
Bool ValidateFramebufferTextureAttachmentPoint(
const char* functionName, const SharedPtr<MG_State::GLState::FramebufferObject>& framebufferObject,
FramebufferAttachmentType attachmentType) {
// "An INVALID_OPERATION error is generated if COLOR_ATTACHMENTm is used with m greater
// than or equal to MAX_COLOR_ATTACHMENTS."
if (!FramebufferImpl::ValidateColorAttachmentInRange(attachmentType, functionName)) return false;
// "An INVALID_OPERATION error is generated if zero is bound to target." MobileGL keeps
// a real FramebufferObject for framebuffer 0, so a null test can never see this - the
// object is always there, and framebuffer 0 has to be recognized by identity instead,
// the same comparison DrawBuffers_State makes. Without this an attach onto the default
// framebuffer silently REPLACED its color attachment, permanently desynchronizing it
// from what the swapchain keeps publishing.
const auto& defaultFramebufferInfo = FramebufferImpl::pDefaultFramebufferInfo;
if (!framebufferObject ||
(defaultFramebufferInfo && framebufferObject == defaultFramebufferInfo->defaultFBO)) {
MG_State::pGLContext->RecordError(
ErrorCode::InvalidOperation,
MakeUnique<GenericErrorInfo>(
"MG_Impl/GLImpl", functionName,
"No framebuffer object is bound to the target; the default framebuffer's attachments "
"cannot be named."));
return false;
}
return true;
}
// The other half of 9.2.8: "level must be greater than or equal to zero", and for a
// texture with immutable storage it "must be smaller than the number of levels the texture
// has". Split from the attachment-point half because the caller only has a texture object
// once the detach (texture == 0) case is behind it.
Bool ValidateFramebufferTextureLevel(const char* functionName,
const SharedPtr<MG_State::GLState::ITextureObject>& textureObject,
GLint level) {
if (level < 0) {
MG_State::pGLContext->RecordError(ErrorCode::InvalidValue,
MakeUnique<GenericErrorInfo>("MG_Impl/GLImpl", functionName,
"Texture level must be non-negative."));
return false;
}
if (!textureObject || !textureObject->IsImmutable()) {
// A mutable texture has no level bound here: a level it has not specified yet is
// not an error, it just leaves the framebuffer incomplete.
return true;
}
// GetAddressableLevelCount(), NOT GetImmutableLevels(): for a VIEW the latter is
// deliberately the ORIGINAL texture's count (GL 4.6 core 8.18 defines
// TEXTURE_IMMUTABLE_LEVELS on a view that way), which is far too large a bound - a
// two-level view onto a ten-level texture would accept level 5 and attach an image
// nothing can draw into.
const Uint levelBound = textureObject->GetAddressableLevelCount();
if (static_cast<Uint>(level) >= levelBound) {
MG_State::pGLContext->RecordError(
ErrorCode::InvalidValue,
MakeUnique<GenericErrorInfo>(
"MG_Impl/GLImpl", functionName,
std::format("Texture level {} is beyond the {} level(s) this texture has.", level,
levelBound)));
return false;
}
return true;
}
using FramebufferImpl::ValidateFramebufferTextureAttachmentPoint;
using FramebufferImpl::ValidateFramebufferTextureLevel;
void AttachFramebufferTextureWithUploadTarget(const char* functionName, GLenum target, GLenum attachment,
GLuint texture, GLint level,
@@ -2650,6 +2590,8 @@ namespace MobileGL::MG_Impl::GLImpl {
? FramebufferImpl::pDefaultFramebufferInfo->defaultFBO
: GetNamedFramebufferObject_State(drawFramebuffer, "BlitNamedFramebuffer_State");
if (!readObject || !drawObject) return;
if (!FramebufferImpl::ValidateReadFramebufferIsSingleView(readObject.get(), "BlitNamedFramebuffer_State"))
return;
BlitNamedFramebuffer_Backend(readObject, drawObject, srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1,
mask, filter);
@@ -2910,6 +2852,8 @@ namespace MobileGL::MG_Impl::GLImpl {
MakeUnique<GenericErrorInfo>("MG_Impl/GLImpl", "ReadPixels_State", "Framebuffer is incomplete"));
return false;
}
if (!FramebufferImpl::ValidateReadFramebufferIsSingleView(framebufferObject.get(), "ReadPixels_State"))
return false;
// Check for required buffers
if (textureInputFormat == TextureInputFormat::StencilIndex) {
@@ -3364,6 +3308,7 @@ namespace MobileGL::MG_Impl::GLImpl {
void BlitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1,
GLint dstY1, GLbitfield mask, GLenum filter) {
if (!ValidateBlitMaskAndFilter(__func__, mask, filter)) return;
if (!FramebufferImpl::ValidateBoundReadFramebufferIsSingleView(__func__)) return;
BlitFramebuffer_Backend(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter);
}
@@ -11,6 +11,10 @@
#include <Includes.h>
#include <MG_State/GLState/Core.h>
namespace MobileGL::MG_State::GLState {
class ProgramObject;
} // namespace MobileGL::MG_State::GLState
namespace MobileGL::MG_Impl::GLImpl {
/* @INSERTION_POINT:FUNCTION_DECLARATION@ */
void ReadPixels(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void* pixels);
@@ -55,6 +59,25 @@ namespace MobileGL::MG_Impl::GLImpl {
void NamedFramebufferTexture3D(GLuint framebuffer, GLenum attachment, GLenum textarget, GLuint texture, GLint level,
GLint zoffset);
void NamedFramebufferTextureLayer(GLuint framebuffer, GLenum attachment, GLuint texture, GLint level, GLint layer);
// GL_OVR_multiview (GL_FramebufferMultiview.cpp).
void FramebufferTextureMultiviewOVR(GLenum target, GLenum attachment, GLuint texture, GLint level,
GLint baseViewIndex, GLsizei numViews);
void NamedFramebufferTextureMultiviewOVR(GLuint framebuffer, GLenum attachment, GLuint texture, GLint level,
GLint baseViewIndex, GLsizei numViews);
void FramebufferTextureMultiviewOVR_State(GLenum target, GLenum attachment, GLuint texture, GLint level,
GLint baseViewIndex, GLsizei numViews);
void NamedFramebufferTextureMultiviewOVR_State(GLuint framebuffer, GLenum attachment, GLuint texture, GLint level,
GLint baseViewIndex, GLsizei numViews);
// GL_MAX_VIEWS_OVR as the active backend reports it; zero without a backend or without multiview,
// which is exactly when GL_OVR_multiview is not advertised.
Int GetMaxViews_State();
Bool IsMultiviewSupported_State();
// The draw-time rules of GL_OVR_multiview for `program` against the bound draw framebuffer.
// Records INVALID_OPERATION and returns false when the draw must be dropped.
Bool ValidateMultiviewDraw(const MG_State::GLState::ProgramObject& program, const char* functionName);
// The framebuffer object a DSA entry point names, or null with INVALID_OPERATION recorded.
SharedPtr<MG_State::GLState::FramebufferObject> GetNamedFramebufferObject_State(GLuint framebuffer,
const char* caller);
void NamedFramebufferDrawBuffer(GLuint framebuffer, GLenum buf);
void NamedFramebufferDrawBuffers(GLuint framebuffer, GLsizei n, const GLenum* bufs);
void NamedFramebufferReadBuffer(GLuint framebuffer, GLenum src);
@@ -0,0 +1,223 @@
// MobileGL - MobileGL/MG_Impl/GLImpl/Framebuffer/GL_FramebufferMultiview.cpp
// Copyright (c) 2025-2026 MobileGL-Dev
// Licensed under the GNU Lesser General Public License v3.0:
// https://www.gnu.org/licenses/gpl-3.0.txt
// https://www.gnu.org/licenses/lgpl-3.0.txt
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
// GL_OVR_multiview: the two attaching entry points, the attachment queries and the draw-time rules.
// A multiview attachment is a FramebufferAttachmentObject of a 2D array texture whose layer is the
// base view index and whose view count is non-zero; the rest of the framebuffer code reads it
// through FramebufferObject::GetViewCount() and HasViewTargetMismatch().
#include "GL_Framebuffer.h"
#include "Validators.h"
#include <MG_Backend/BackendObjects.h>
#include <MG_Impl/GLImpl/Texture/Validators.h>
#include <MG_Impl/Pipe/FramebufferEmit.h>
#include <MG_State/GLState/ErrorState/Error.h>
#include <MG_State/GLState/ProgramState/ProgramObject.h>
#include <MG_Util/Converters/GLToMG/FramebufferEnumConverter.h>
namespace MobileGL::MG_Impl::GLImpl {
namespace {
void RecordMultiviewError(ErrorCode code, const char* functionName, String detail) {
MG_State::pGLContext->RecordError(
code, MakeUnique<GenericErrorInfo>("MG_Impl/GLImpl", functionName, Move(detail)));
}
const MG_Backend::DynamicBackendParameters& ActiveBackendLimits() {
static const MG_Backend::DynamicBackendParameters kNoBackend{};
return MG_Backend::pActiveBackendObject ? MG_Backend::pActiveBackendObject->GetDynamicParameters()
: kNoBackend;
}
// The checks of the spec that do not depend on the framebuffer object, in its order:
// FramebufferTextureLayer's own errors other than the layer ones, then numViews against
// MAX_VIEWS_OVR, then the texture-dependent ones. Returns the texture to attach, or null
// with `ok` telling a detach (texture 0) apart from a refusal.
SharedPtr<MG_State::GLState::ITextureObject> ValidateMultiviewTexture(const char* functionName, GLuint texture,
GLint level, GLint baseViewIndex,
GLsizei numViews, Bool& ok) {
ok = false;
const Int maxViews = GetMaxViews_State();
if (numViews < 1 || numViews > maxViews) {
RecordMultiviewError(
ErrorCode::InvalidValue, functionName,
std::format("numViews {} is outside [1, GL_MAX_VIEWS_OVR = {}].", numViews, maxViews));
return nullptr;
}
if (texture == 0) {
ok = true;
return nullptr;
}
const auto& textureObject = MG_State::pGLContext->GetTextureObject(texture);
if (!textureObject) {
RecordMultiviewError(ErrorCode::InvalidOperation, functionName,
std::format("Texture object {} is not valid.", texture));
return nullptr;
}
if (textureObject->GetTarget() != TextureTarget::Texture2DArray) {
RecordMultiviewError(ErrorCode::InvalidOperation, functionName,
"A multiview attachment must be a two-dimensional array texture.");
return nullptr;
}
if (!FramebufferImpl::ValidateFramebufferTextureLevel(functionName, textureObject, level)) return nullptr;
if (baseViewIndex < 0) {
RecordMultiviewError(ErrorCode::InvalidValue, functionName, "baseViewIndex must be non-negative.");
return nullptr;
}
const Int maxLayers = ActiveBackendLimits().MaxArrayTextureLayers;
if (static_cast<Int64>(baseViewIndex) + numViews > maxLayers) {
RecordMultiviewError(ErrorCode::InvalidValue, functionName,
std::format("baseViewIndex {} + numViews {} exceeds GL_MAX_ARRAY_TEXTURE_LAYERS "
"({}).",
baseViewIndex, numViews, maxLayers));
return nullptr;
}
ok = true;
return textureObject;
}
// Shared tail of both entry points once the framebuffer object is known. Returns whether
// the framebuffer changed.
Bool AttachMultiview(const char* functionName,
const SharedPtr<MG_State::GLState::FramebufferObject>& framebufferObject,
GLenum attachment, GLuint texture, GLint level, GLint baseViewIndex, GLsizei numViews) {
if (!IsMultiviewSupported_State()) {
RecordMultiviewError(ErrorCode::InvalidOperation, functionName,
"GL_OVR_multiview is not supported by the active backend.");
return false;
}
const Bool depthStencil = attachment == GL_DEPTH_STENCIL_ATTACHMENT;
const FramebufferAttachmentType attachmentType =
depthStencil ? FramebufferAttachmentType::Depth
: MG_Util::ConvertGLEnumToFramebufferAttachmentType(attachment);
if (!FramebufferImpl::ValidateFramebufferAttachmentType(attachmentType)) return false;
if (!FramebufferImpl::ValidateFramebufferTextureAttachmentPoint(functionName, framebufferObject,
attachmentType)) {
return false;
}
Bool ok = false;
const auto textureObject =
ValidateMultiviewTexture(functionName, texture, level, baseViewIndex, numViews, ok);
if (!ok) return false;
const FramebufferAttachmentType stencil = FramebufferAttachmentType::Stencil;
if (!textureObject) {
framebufferObject->Detach(attachmentType);
if (depthStencil) framebufferObject->Detach(stencil);
return true;
}
const auto attach = [&](FramebufferAttachmentType type) {
framebufferObject->AttachTexture(type, textureObject, TextureUploadTarget::Texture2DArray, level,
baseViewIndex, /*layered=*/false, numViews);
};
attach(attachmentType);
if (depthStencil) attach(stencil);
return true;
}
} // namespace
Int GetMaxViews_State() {
return std::max<Int>(ActiveBackendLimits().MaxViews, 0);
}
Bool IsMultiviewSupported_State() {
return MG_Backend::pActiveBackendObject != nullptr && GetMaxViews_State() > 0;
}
void FramebufferTextureMultiviewOVR_State(GLenum target, GLenum attachment, GLuint texture, GLint level,
GLint baseViewIndex, GLsizei numViews) {
if (target == GL_FRAMEBUFFER) target = GL_DRAW_FRAMEBUFFER;
const FramebufferTarget framebufferTarget = MG_Util::ConvertGLEnumToFramebufferTarget(target);
if (!FramebufferImpl::ValidateFramebufferTarget(framebufferTarget)) return;
if (!TextureImpl::ValidateTextureName(texture, true)) return;
const auto& framebufferObject =
MG_State::pGLContext->GetFramebufferBindingSlot(framebufferTarget).GetBoundObject();
AttachMultiview(__func__, framebufferObject, attachment, texture, level, baseViewIndex, numViews);
}
void NamedFramebufferTextureMultiviewOVR_State(GLuint framebuffer, GLenum attachment, GLuint texture, GLint level,
GLint baseViewIndex, GLsizei numViews) {
const auto framebufferObject = GetNamedFramebufferObject_State(framebuffer, __func__);
if (!framebufferObject) return;
if (AttachMultiview(__func__, framebufferObject, attachment, texture, level, baseViewIndex, numViews)) {
// A DSA mutator has no validate point, so the record goes out now (see
// PipePublishFramebufferByName in GL_Framebuffer.cpp).
MG_Pipe::MGPipeFramebufferEmitterInstance().EmitFramebufferByName(*framebufferObject);
}
}
Bool ValidateMultiviewDraw(const MG_State::GLState::ProgramObject& program, const char* functionName) {
// Without backend multiview no framebuffer can be multiview, so a single-view program
// needs no framebuffer walk on every draw.
if (program.GetMultiviewViewCount() == 1 && !IsMultiviewSupported_State()) return true;
const auto& drawFramebuffer =
MG_State::pGLContext->GetFramebufferBindingSlot(FramebufferTarget::Draw).GetBoundObject();
const Int framebufferViews = drawFramebuffer ? drawFramebuffer->GetViewCount() : 1;
const Int programViews = program.GetMultiviewViewCount();
// GL_OVR_multiview 11.1.3.11 / 16.X: the program's num_views (1 without the qualifier)
// must be the draw framebuffer's view count.
if (framebufferViews != programViews) {
RecordMultiviewError(ErrorCode::InvalidOperation, functionName,
std::format("The program renders {} view(s) but the draw framebuffer has {}.",
programViews, framebufferViews));
return false;
}
if (!drawFramebuffer || !drawFramebuffer->IsMultiview()) return true;
// A multiview draw framebuffer takes no geometry or tessellation stage and no active,
// unpaused transform feedback.
if (program.HasLinkedShaderStage(ShaderStage::Geometry) ||
program.HasLinkedShaderStage(ShaderStage::TessControl) ||
program.HasLinkedShaderStage(ShaderStage::TessEval)) {
RecordMultiviewError(ErrorCode::InvalidOperation, functionName,
"A multiview draw cannot run a geometry or tessellation stage.");
return false;
}
if (MG_State::pGLContext->IsTransformFeedbackActive() && !MG_State::pGLContext->IsTransformFeedbackPaused()) {
RecordMultiviewError(ErrorCode::InvalidOperation, functionName,
"A multiview draw cannot capture transform feedback.");
return false;
}
return true;
}
namespace FramebufferImpl {
Bool TryAnswerMultiviewAttachmentQuery(const MG_State::GLState::FramebufferAttachmentObject* attachmentObject,
GLenum pname, GLint* params, const char* caller) {
if (pname != GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_NUM_VIEWS_OVR &&
pname != GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_BASE_VIEW_INDEX_OVR) {
return false;
}
if (!IsMultiviewSupported_State()) return false;
const Bool nothingAttached =
attachmentObject == nullptr || attachmentObject->IsEmpty() || !attachmentObject->IsValid();
if (!nothingAttached && !attachmentObject->IsTexture()) {
RecordMultiviewError(ErrorCode::InvalidEnum, caller,
std::format("pname {:#x} is only defined for a texture attachment.", pname));
return true;
}
// Zero for a texture attachment that is not multiview, as the spec answers for one
// that is not a two-dimensional array texture; FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER
// already reads the base view index.
const Bool multiview = !nothingAttached && attachmentObject->IsMultiview();
if (pname == GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_NUM_VIEWS_OVR) {
*params = multiview ? static_cast<GLint>(attachmentObject->GetNumViews()) : 0;
} else {
*params = multiview ? static_cast<GLint>(attachmentObject->GetTextureLayer()) : 0;
}
return true;
}
} // namespace FramebufferImpl
void FramebufferTextureMultiviewOVR(GLenum target, GLenum attachment, GLuint texture, GLint level,
GLint baseViewIndex, GLsizei numViews) {
FramebufferTextureMultiviewOVR_State(target, attachment, texture, level, baseViewIndex, numViews);
}
void NamedFramebufferTextureMultiviewOVR(GLuint framebuffer, GLenum attachment, GLuint texture, GLint level,
GLint baseViewIndex, GLsizei numViews) {
NamedFramebufferTextureMultiviewOVR_State(framebuffer, attachment, texture, level, baseViewIndex, numViews);
}
} // namespace MobileGL::MG_Impl::GLImpl
@@ -7,6 +7,7 @@
// End of Source File Header
#include "Validators.h"
#include "GL_Framebuffer.h"
#include <MG_Backend/BackendObjects.h>
#include <MG_State/GLState/Core.h>
#include <MG_State/GLState/ErrorState/Error.h>
@@ -178,6 +179,7 @@ namespace MobileGL::MG_Impl::GLImpl::FramebufferImpl {
"Read framebuffer is not framebuffer complete."));
return false;
}
if (!ValidateReadFramebufferIsSingleView(framebufferObject.get(), caller)) return false;
const FramebufferAttachmentType readBuffer = framebufferObject->GetReadBuffer();
if (readBuffer == FramebufferAttachmentType::None || !framebufferObject->GetAttachment(readBuffer).IsValid()) {
@@ -210,4 +212,87 @@ namespace MobileGL::MG_Impl::GLImpl::FramebufferImpl {
return true;
}
Bool ValidateReadFramebufferIsSingleView(const MG_State::GLState::FramebufferObject* framebufferObject,
const char* caller) {
// GL_OVR_multiview 9.3 / 18.2 / 18.3: reading, copying or blitting out of a read
// framebuffer with more than one view is INVALID_FRAMEBUFFER_OPERATION.
if (!framebufferObject || framebufferObject->GetViewCount() <= 1) return true;
MG_State::pGLContext->RecordError(
ErrorCode::InvalidFramebufferOperation,
MakeUnique<GenericErrorInfo>("MG_Impl/GLImpl/FramebufferImpl", caller,
"The read framebuffer has more than one view (GL_OVR_multiview)."));
return false;
}
Bool ValidateBoundReadFramebufferIsSingleView(const char* caller) {
const auto& framebufferObject =
MG_State::pGLContext->GetFramebufferBindingSlot(FramebufferTarget::Read).GetBoundObject();
return ValidateReadFramebufferIsSingleView(framebufferObject.get(), caller);
}
// GL 4.6 core 9.2.8 conditions that depend only on the framebuffer and the attachment
// point. Shared, because glFramebufferTexture / 1D / 2D / 3D / TextureLayer are aliases of
// one another in that section and a CTS case that walks the family must not get five
// different answers - which is exactly what happened when these lived in one helper that
// only two of the five went through.
Bool ValidateFramebufferTextureAttachmentPoint(
const char* functionName, const SharedPtr<MG_State::GLState::FramebufferObject>& framebufferObject,
FramebufferAttachmentType attachmentType) {
// "An INVALID_OPERATION error is generated if COLOR_ATTACHMENTm is used with m greater
// than or equal to MAX_COLOR_ATTACHMENTS."
if (!FramebufferImpl::ValidateColorAttachmentInRange(attachmentType, functionName)) return false;
// "An INVALID_OPERATION error is generated if zero is bound to target." MobileGL keeps
// a real FramebufferObject for framebuffer 0, so a null test can never see this - the
// object is always there, and framebuffer 0 has to be recognized by identity instead,
// the same comparison DrawBuffers_State makes. Without this an attach onto the default
// framebuffer silently REPLACED its color attachment, permanently desynchronizing it
// from what the swapchain keeps publishing.
const auto& defaultFramebufferInfo = FramebufferImpl::pDefaultFramebufferInfo;
if (!framebufferObject || (defaultFramebufferInfo && framebufferObject == defaultFramebufferInfo->defaultFBO)) {
MG_State::pGLContext->RecordError(
ErrorCode::InvalidOperation,
MakeUnique<GenericErrorInfo>(
"MG_Impl/GLImpl", functionName,
"No framebuffer object is bound to the target; the default framebuffer's attachments "
"cannot be named."));
return false;
}
return true;
}
// The other half of 9.2.8: "level must be greater than or equal to zero", and for a
// texture with immutable storage it "must be smaller than the number of levels the texture
// has". Split from the attachment-point half because the caller only has a texture object
// once the detach (texture == 0) case is behind it.
Bool ValidateFramebufferTextureLevel(const char* functionName,
const SharedPtr<MG_State::GLState::ITextureObject>& textureObject,
GLint level) {
if (level < 0) {
MG_State::pGLContext->RecordError(
ErrorCode::InvalidValue,
MakeUnique<GenericErrorInfo>("MG_Impl/GLImpl", functionName, "Texture level must be non-negative."));
return false;
}
if (!textureObject || !textureObject->IsImmutable()) {
// A mutable texture has no level bound here: a level it has not specified yet is
// not an error, it just leaves the framebuffer incomplete.
return true;
}
// GetAddressableLevelCount(), NOT GetImmutableLevels(): for a VIEW the latter is
// deliberately the ORIGINAL texture's count (GL 4.6 core 8.18 defines
// TEXTURE_IMMUTABLE_LEVELS on a view that way), which is far too large a bound - a
// two-level view onto a ten-level texture would accept level 5 and attach an image
// nothing can draw into.
const Uint levelBound = textureObject->GetAddressableLevelCount();
if (static_cast<Uint>(level) >= levelBound) {
MG_State::pGLContext->RecordError(
ErrorCode::InvalidValue,
MakeUnique<GenericErrorInfo>(
"MG_Impl/GLImpl", functionName,
std::format("Texture level {} is beyond the {} level(s) this texture has.", level, levelBound)));
return false;
}
return true;
}
} // namespace MobileGL::MG_Impl::GLImpl::FramebufferImpl
@@ -30,4 +30,24 @@ namespace MobileGL::MG_Impl::GLImpl::FramebufferImpl {
// DEFAULT framebuffer does not answer INVALID_OPERATION. Testing the framebuffer kind first
// would turn GL_FRAMEBUFFER_DEFAULT_WIDTH on framebuffer zero into the wrong error.
Bool ValidateFramebufferParameterPname(GLenum pname, Bool isDefaultFramebuffer, Bool forSetter, const char* caller);
// GL 4.6 core 9.2.8 conditions on the framebuffer and the attachment point that every
// texture-attaching entry point shares: a color attachment beyond GL_MAX_COLOR_ATTACHMENTS, or
// the default framebuffer bound to the target, is INVALID_OPERATION.
Bool ValidateFramebufferTextureAttachmentPoint(
const char* functionName, const SharedPtr<MG_State::GLState::FramebufferObject>& framebufferObject,
FramebufferAttachmentType attachmentType);
// The level half of 9.2.8: negative, or past an immutable texture's levels, is INVALID_VALUE.
Bool ValidateFramebufferTextureLevel(const char* functionName,
const SharedPtr<MG_State::GLState::ITextureObject>& textureObject,
GLint level);
// GL_OVR_multiview: a read framebuffer with more than one view cannot be read, copied or blitted
// from (INVALID_FRAMEBUFFER_OPERATION). A null framebuffer passes; its caller reports that.
Bool ValidateReadFramebufferIsSingleView(const MG_State::GLState::FramebufferObject* framebufferObject,
const char* caller);
Bool ValidateBoundReadFramebufferIsSingleView(const char* caller);
// GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_NUM_VIEWS_OVR / _BASE_VIEW_INDEX_OVR. False when pname is
// neither or GL_OVR_multiview is not supported, so the caller's INVALID_ENUM stands; true when
// the query was answered or refused here. Defined in GL_FramebufferMultiview.cpp.
Bool TryAnswerMultiviewAttachmentQuery(const MG_State::GLState::FramebufferAttachmentObject* attachmentObject,
GLenum pname, GLint* params, const char* caller);
} // namespace MobileGL::MG_Impl::GLImpl::FramebufferImpl
+30 -22
View File
@@ -50,6 +50,9 @@ namespace MobileGL::MG_Impl::GLImpl {
// a free function named BlendEquation, which would hide the ::MobileGL::BlendEquation enum
// this file's blend-state queries name unqualified.
GLboolean IsEnabledi(GLenum target, GLuint index);
// GL_Framebuffer.h, declared here for the same reason.
Int GetMaxViews_State();
Bool IsMultiviewSupported_State();
namespace {
enum class IndexedBufferQueryKind {
@@ -608,7 +611,8 @@ namespace MobileGL::MG_Impl::GLImpl {
MG_State::pEGLContext && MG_State::pEGLContext->GetCurrentContextClientAPI() == EGL_OPENGL_ES_API;
const Bool external =
images && ClientSideExternalImageExtensionsAllowed() && MG_Impl::EGLImpl::SharedImageYuvAvailable();
return ClientSideExtensionList(images, external, EsIdentityActive(), esApi);
return ClientSideExtensionList(images, external, EsIdentityActive(), esApi,
MG_Impl::EGLImpl::ResetNotificationAvailable());
}
// Robust buffer access as GL 4.5 / KHR_robust_buffer_access_behavior define it: the backend
@@ -668,27 +672,24 @@ namespace MobileGL::MG_Impl::GLImpl {
// server's, under split), which cannot know about them:
// * GL_OES_EGL_image binds the EGL side's dma-buf images, which only a backend with
// shared images has (EGLImpl::SharedImagesAvailable);
// * the robustness family - reset notification (glGetGraphicsResetStatus, the contexts'
// EGL reset strategy, GL_CONTEXT_LOST) and the bounded queries (glReadnPixels,
// glGetnUniform*) are this frontend's, whatever the backend. KHR for GL and ES, ARB for
// desktop GL applications that ask for that name, EXT for ES applications that ask for
// that one. Robust buffer ACCESS is a separate promise (GL_CONTEXT_ROBUST_ACCESS) and is
// not implied by any of them.
const Vector<const char*>& ClientSideExtensionList(Bool images, Bool external, Bool es, Bool esApi) {
// * the robustness family includes reset reporting, which the split client provides.
const Vector<const char*>& ClientSideExtensionList(Bool images, Bool external, Bool es, Bool esApi,
Bool robustness) {
// GL_OES_EGL_image_external(_essl3) only where the server samples YUV images: an
// external texture is a 2D texture holding the image converted to RGBA, which needs
// the server to hold the YUV image in the first place (EGLImpl::SharedImageYuvAvailable).
static const auto build = [](Bool images, Bool external, Bool es, Bool esApi) {
static const auto build = [](Bool images, Bool external, Bool es, Bool esApi, Bool robustness) {
Vector<const char*> list;
if (images) list.push_back("GL_OES_EGL_image");
if (images && external) {
list.push_back("GL_OES_EGL_image_external");
list.push_back("GL_OES_EGL_image_external_essl3");
}
// An ES context lists no ARB names (KHR-GLES*.exposed_extensions).
list.push_back("GL_KHR_robustness");
if (!esApi) list.push_back("GL_ARB_robustness");
list.push_back("GL_EXT_robustness");
if (robustness) {
list.push_back("GL_KHR_robustness");
if (!esApi) list.push_back("GL_ARB_robustness");
list.push_back("GL_EXT_robustness");
}
// Under the ES identity (EsIdentityActive) the ES names of what desktop GL has in core:
// BGRA textures, render targets and read-backs. GL_BGRA_EXT / GL_BGRA8_EXT as internal
// formats are taken as RGBA storage (TextureEnumConverter), the byte order being the
@@ -707,14 +708,13 @@ namespace MobileGL::MG_Impl::GLImpl {
}
return list;
};
static const Vector<const char*> lists[16] = {
build(false, false, false, false), build(false, false, false, true), build(false, false, true, false),
build(false, false, true, true), build(false, true, false, false), build(false, true, false, true),
build(false, true, true, false), build(false, true, true, true), build(true, false, false, false),
build(true, false, false, true), build(true, false, true, false), build(true, false, true, true),
build(true, true, false, false), build(true, true, false, true), build(true, true, true, false),
build(true, true, true, true)};
return lists[(images ? 8 : 0) + (external ? 4 : 0) + (es ? 2 : 0) + (esApi ? 1 : 0)];
static const auto lists = [] {
std::array<Vector<const char*>, 32> result;
for (SizeT i = 0; i < result.size(); ++i)
result[i] = build(i & 8, i & 4, i & 2, i & 1, i & 16);
return result;
}();
return lists[(robustness ? 16 : 0) + (images ? 8 : 0) + (external ? 4 : 0) + (es ? 2 : 0) + (esApi ? 1 : 0)];
}
// The external-image names are ES extensions (GL_OES_EGL_image_external_essl3 extends ESSL
@@ -1631,6 +1631,14 @@ namespace MobileGL::MG_Impl::GLImpl {
}
}
// GL_MAX_VIEWS_OVR, answered only where GL_OVR_multiview is advertised; anywhere else it is an
// unknown pname like any other extension's.
static Bool TryGetMultiviewInteger(GLenum pname, GLint* params) {
if (pname != GL_MAX_VIEWS_OVR || !IsMultiviewSupported_State()) return false;
*params = GetMaxViews_State();
return true;
}
// GL_EXT_fragment_shading_rate's state and limits (tables 23.9 / 23.53 of the extension).
// Returns false for any other pname. The tokens belong to the extension, so a context whose
// backend cannot back it answers them like any unknown pname, and the attachment limits the
@@ -1762,7 +1770,7 @@ namespace MobileGL::MG_Impl::GLImpl {
return;
}
if (TryGetFragmentShadingRateInteger(pname, params)) return;
if (TryGetFragmentShadingRateInteger(pname, params) || TryGetMultiviewInteger(pname, params)) return;
switch (pname) {
case GL_ACTIVE_TEXTURE:
+3 -2
View File
@@ -50,8 +50,9 @@ namespace MobileGL::MG_Impl::GLImpl {
// The extensions the frontend appends to the backend's list - one list behind
// glGetString(GL_EXTENSIONS), glGetStringi and GL_NUM_EXTENSIONS - for the given conditions:
// shared images, YUV images that may be advertised (ClientSideExternalImageExtensionsAllowed),
// the ES identity, and a context created for the OpenGL ES API.
const Vector<const char*>& ClientSideExtensionList(Bool images, Bool external, Bool es, Bool esApi);
// the ES identity, a context created for the OpenGL ES API, and supported reset reporting.
const Vector<const char*>& ClientSideExtensionList(Bool images, Bool external, Bool es, Bool esApi,
Bool robustness);
// Whether the current context may list GL_OES_EGL_image_external(_essl3): a context created
// for the OpenGL ES API, or any context outside the strict core-profile rules
// (MG_State::IsRelaxedSemanticsActive).
+25 -12
View File
@@ -2197,7 +2197,7 @@ namespace MobileGL::MG_Impl::GLImpl {
// Allocate in TextureObject
if (isProxy) {
MGLOG_D("%s: isProxy = true, not allocating", __func__);
TextureImpl::pProxyTextureManager->RecordProxyLevel(textureUploadTarget, level, {width, height, depth});
} else {
DiscardMipmapChainOnBaseRespecification(textureMipmapObject, textureUploadTarget, level);
textureMipmapObject->AllocateStorage(textureUploadTarget, level, {{width, height, depth}, internalBytes});
@@ -2345,7 +2345,7 @@ namespace MobileGL::MG_Impl::GLImpl {
// Allocate in TextureObject
if (isProxy) {
MGLOG_D("%s: isProxy = true, not allocating", __func__);
TextureImpl::pProxyTextureManager->RecordProxyLevel(textureUploadTarget, level, {width, height, 1});
} else {
MGLOG_D("%s: Allocating %d bytes at mip %d", __func__, internalBytes, level);
DiscardMipmapChainOnBaseRespecification(textureMipmapObject, textureUploadTarget, level);
@@ -2460,7 +2460,9 @@ namespace MobileGL::MG_Impl::GLImpl {
MOBILEGL_ASSERT(nullptr != static_cast<MG_State::GLState::TextureObjectMipmap*>(textureObject.get()),
"Texture object here should always be an object with mipmap");
auto textureMipmapObject = static_cast<MG_State::GLState::TextureObjectMipmap*>(textureObject.get());
if (!isProxy) {
if (isProxy) {
TextureImpl::pProxyTextureManager->RecordProxyLevel(textureUploadTarget, level, {width, 1, 1});
} else {
DiscardMipmapChainOnBaseRespecification(textureMipmapObject, textureUploadTarget, level);
textureMipmapObject->AllocateStorage(textureUploadTarget, level, {{width, 1, 1}, internalBytes});
// After AllocateStorage, which clears the tag. No block-compressed format has a 1D
@@ -2905,7 +2907,12 @@ namespace MobileGL::MG_Impl::GLImpl {
case GL_TEXTURE_HEIGHT:
case GL_TEXTURE_DEPTH: {
const SizeT axis = pname == GL_TEXTURE_WIDTH ? 0 : (pname == GL_TEXTURE_HEIGHT ? 1 : 2);
if (storageType == TextureStorageType::Mipmap && mipmapObject != nullptr) {
// A proxy level never took storage; its size lives with the proxy manager.
const auto proxySize =
isProxy ? TextureImpl::pProxyTextureManager->GetProxyLevelTexelSize(uploadTarget, level) : std::nullopt;
if (proxySize) {
value = (*proxySize)[axis];
} else if (storageType == TextureStorageType::Mipmap && mipmapObject != nullptr) {
value = mipmapObject->GetMipmapTexelSize(uploadTarget, level)[axis];
} else if (storageType == TextureStorageType::Buffer) {
// A buffer texture is one-dimensional.
@@ -3988,10 +3995,13 @@ namespace MobileGL::MG_Impl::GLImpl {
MG_Util::ConvertGLEnumToTextureInternalFormat(internalformat);
textureObject->SetInternalFormat(textureInternalFormat);
// A proxy records the format and nothing else - it must never take storage, and it must never
// be tagged compressed, or GL_TEXTURE_COMPRESSED_IMAGE_SIZE on a proxy would stop being
// INVALID_OPERATION.
if (isProxy) return;
// A proxy records the format and the level size and nothing else - it must never take
// storage, and it must never be tagged compressed, or GL_TEXTURE_COMPRESSED_IMAGE_SIZE on a
// proxy would stop being INVALID_OPERATION.
if (isProxy) {
TextureImpl::pProxyTextureManager->RecordProxyLevel(textureUploadTarget, level, {width, height, depth});
return;
}
const SizeT internalBpp =
MG_Util::GetInternalBytesPerPixel(textureInternalFormat, TexturePixelDataType::UnsignedByte);
@@ -4072,10 +4082,13 @@ namespace MobileGL::MG_Impl::GLImpl {
MG_Util::ConvertGLEnumToTextureInternalFormat(internalformat);
textureObject->SetInternalFormat(textureInternalFormat);
// A proxy records the format and nothing else - it must never take storage, and it must never
// be tagged compressed, or GL_TEXTURE_COMPRESSED_IMAGE_SIZE on a proxy would stop being
// INVALID_OPERATION.
if (isProxy) return;
// A proxy records the format and the level size and nothing else - it must never take
// storage, and it must never be tagged compressed, or GL_TEXTURE_COMPRESSED_IMAGE_SIZE on a
// proxy would stop being INVALID_OPERATION.
if (isProxy) {
TextureImpl::pProxyTextureManager->RecordProxyLevel(textureUploadTarget, level, {width, height, 1});
return;
}
const SizeT internalBpp =
MG_Util::GetInternalBytesPerPixel(textureInternalFormat, TexturePixelDataType::UnsignedByte);
@@ -7,6 +7,7 @@
// End of Source File Header
#include "ProxyTexture.h"
#include <MG_Backend/BackendObjects.h>
#include <MG_State/GLState/TextureState/TextureObject1D.h>
#include <MG_State/GLState/TextureState/TextureObject2D.h>
#include <MG_State/GLState/TextureState/TextureObject2DCube.h>
@@ -87,4 +88,51 @@ namespace MobileGL::MG_Impl::GLImpl::TextureImpl {
static SharedPtr<MG_State::GLState::ITextureObject> nullTextureObject = nullptr;
return nullTextureObject;
}
namespace {
// Whether the implementation can hold a level of this size on this proxy target. Every
// dimension of a mipmapped image shrinks with the level; array layers do not.
Bool ProxyLevelFits(TextureUploadTarget target, GLint level, IntVec3 size) {
MG_Backend::DynamicBackendParameters limits{};
if (MG_Backend::pActiveBackendObject) limits = MG_Backend::pActiveBackendObject->GetDynamicParameters();
const auto levelLimit = [level](Int limit) { return level < 31 ? std::max(limit >> level, 1) : 1; };
const Int planar = levelLimit(limits.MaxTextureSize);
const Int cube = levelLimit(limits.MaxCubeMapTextureSize);
const Int volume = levelLimit(limits.Max3DTextureSize);
const Int layers = limits.MaxArrayTextureLayers;
switch (target) {
case TextureUploadTarget::ProxyTexture1D:
return size.x() <= planar;
case TextureUploadTarget::ProxyTexture1DArray:
return size.x() <= planar && size.y() <= layers;
case TextureUploadTarget::ProxyTexture2DArray:
return size.x() <= planar && size.y() <= planar && size.z() <= layers;
case TextureUploadTarget::ProxyTexture3D:
return size.x() <= volume && size.y() <= volume && size.z() <= volume;
case TextureUploadTarget::ProxyCubeMap:
return size.x() <= cube && size.y() <= cube;
case TextureUploadTarget::ProxyCubeMapArray:
return size.x() <= cube && size.y() <= cube && size.z() <= layers;
case TextureUploadTarget::ProxyTextureRectangle:
return level == 0 && size.x() <= limits.MaxTextureSize && size.y() <= limits.MaxTextureSize;
default:
return size.x() <= planar && size.y() <= planar;
}
}
} // namespace
void ProxyTextureManager::RecordProxyLevel(TextureUploadTarget target, GLint level, IntVec3 size) {
if (level < 0) return;
auto& levels = m_proxyLevelSizes[target];
if (levels.size() <= static_cast<SizeT>(level)) levels.resize(static_cast<SizeT>(level) + 1);
levels[level] = ProxyLevelFits(target, level, size) ? size : IntVec3{0, 0, 0};
}
Optional<IntVec3> ProxyTextureManager::GetProxyLevelTexelSize(TextureUploadTarget target, GLint level) const {
auto it = m_proxyLevelSizes.find(target);
if (it == m_proxyLevelSizes.end() || level < 0 || it->second.size() <= static_cast<SizeT>(level)) {
return std::nullopt;
}
return it->second[level];
}
} // namespace MobileGL::MG_Impl::GLImpl::TextureImpl
@@ -19,8 +19,15 @@ namespace MobileGL::MG_Impl::GLImpl::TextureImpl {
TextureUploadTarget target);
const SharedPtr<MG_State::GLState::ITextureObject>& GetProxyTextureObject(TextureUploadTarget target);
// The image a proxy glTexImage* or glCompressedTexImage* describes, kept here because a proxy
// never takes storage. A request past the implementation limits records all zeros (GL 4.6
// core 8.22), which is how glGetTexLevelParameter tells the application it cannot be had.
void RecordProxyLevel(TextureUploadTarget target, GLint level, IntVec3 size);
Optional<IntVec3> GetProxyLevelTexelSize(TextureUploadTarget target, GLint level) const;
private:
UnorderedMap<TextureUploadTarget, SharedPtr<MG_State::GLState::ITextureObject>> m_proxyTexturesMap;
UnorderedMap<TextureUploadTarget, Vector<Optional<IntVec3>>> m_proxyLevelSizes;
};
extern UniquePtr<ProxyTextureManager>& pProxyTextureManager;
+1 -1
View File
@@ -1547,7 +1547,7 @@ namespace MobileGL::MG_Impl {
GETPROC(glGetIntegerui64i_vNV, name);
GETPROC(glViewportSwizzleNV, name);
GETPROC(glFramebufferTextureMultiviewOVR, name);
// GETPROC(glNamedFramebufferTextureMultiviewOVR, name);
GETPROC(glNamedFramebufferTextureMultiviewOVR, name);
MGLOG_D("GetProcAddress(%s) = nullptr!", name);
return nullptr;
+4 -1
View File
@@ -109,7 +109,8 @@ namespace MobileGL::MG_Pipe {
surface.Kind = kMGPipeSurfaceKindTexture;
surface.InternalFormat = static_cast<Uint32>(texture->GetFormat());
surface.Layered = attachment.IsLayered() ? 1 : 0;
surface.Level = static_cast<Uint16>(std::max<Int>(attachment.GetTextureLevel(), 0));
surface.Level = static_cast<Uint8>(std::clamp<Int>(attachment.GetTextureLevel(), 0, 0xFF));
surface.NumViews = static_cast<Uint8>(std::clamp<Int>(attachment.GetNumViews(), 0, 0xFF));
surface.Layer = static_cast<Uint32>(std::max<Int>(attachment.GetTextureLayer(), 0));
surface.UploadTarget = static_cast<Uint16>(MGPipeResolveAttachmentUploadTarget(attachment));
// ID-12 DV-5: the field that WAS Pad0, and the size did not move. The four
@@ -126,6 +127,7 @@ namespace MobileGL::MG_Pipe {
surface.InternalFormat = static_cast<Uint32>(renderbuffer->GetInternalFormat());
surface.Layered = 0;
surface.Level = 0;
surface.NumViews = 0;
surface.Layer = 0;
return surface;
}
@@ -179,6 +181,7 @@ namespace MobileGL::MG_Pipe {
dst.Kind = src.Kind;
dst.Layered = src.Layered;
dst.Level = src.Level;
dst.NumViews = src.NumViews;
dst.Layer = src.Layer;
dst.UploadTarget = src.UploadTarget;
// MANDATORY, not optional: TextureTarget is a PipeFields.def row now, so a
+29 -23
View File
@@ -1080,17 +1080,13 @@ namespace MobileGL::MG_Pipe {
MGPipeRouteResourceFlushRange(record, buffer.MappedData() + offset);
}
void MGPipeEmitResourceReadback(BufferObject& buffer) {
// Whole-buffer by contract (BufferObject.h: the op pulls the backend's current
// contents for the WHOLE buffer into the shadow). The split arm's slicing lives in
// the CALLER (BufferObject::SyncGpuWrites): what "whole" costs is decided by the
// event ring's capacity, which this layer does not read.
MGPipeEmitResourceReadbackRange(buffer, 0, buffer.GetSize());
Bool MGPipeEmitResourceReadback(BufferObject& buffer) {
return MGPipeEmitResourceReadbackRange(buffer, 0, buffer.GetSize());
}
void MGPipeEmitResourceReadbackRange(BufferObject& buffer, SizeT offset, SizeT size) {
Bool MGPipeEmitResourceReadbackRange(BufferObject& buffer, SizeT offset, SizeT size) {
const MGPipeHandle handle = ContentHandleFor(buffer, "resource_readback");
if (MGPipeHandleIsNull(handle)) return;
if (MGPipeHandleIsNull(handle)) return false;
MGPReadback record{};
record.Res = handle;
record.Offset = offset;
@@ -1098,20 +1094,11 @@ namespace MobileGL::MG_Pipe {
if (MG_Util::PipeStats::Enabled()) {
MG_Util::PipeStats::AddCalls(MG_Util::PipeStats::CallClass::ResourceReadbacks, 1);
}
// The answer travels back through MGPipeClientOnBufferWriteback, and the server's
// epoch bump happens AFTER that writeback, never before.
MGPipeRouteResourceReadback(record);
return MGPipeRouteResourceReadback(record);
}
// NO UnmapPersistent PRODUCER IN P3a, AND THAT IS DELIBERATE. The catalog has the call
// and wire implemented it, but D-J forbids new behavior and there is nothing to convert:
// BufferBackendOps has seven hooks and none of them is an unmap, and
// PipeResource::ReleasePersistentMap() (BufferObject.cpp, from RedefineStorage) tells the
// backend nothing today - it learns from the Respecify that follows. Emitting
// unmap_persistent here would therefore be a new call to a backend that has never been
// told about a release, so the client emits none and the applier's refusal counter stays
// at 0 for it. The producer lands with the phase that gives the backend an unmap hook.
void* MGPipeEmitMapPersistent(BufferObject& buffer) {
// A storage redefinition ends the donation through the respecify record.
void* MGPipeEmitMapPersistent(BufferObject& buffer, SharedPtr<const std::atomic<Bool>>& lifetime) {
const MGPipeHandle handle = ContentHandleFor(buffer, "map_persistent");
if (MGPipeHandleIsNull(handle)) return nullptr;
MGPipeResourceTrackerInstance().NoteMapPersistent();
@@ -1123,13 +1110,20 @@ namespace MobileGL::MG_Pipe {
if (MG_Util::PipeStats::Enabled()) {
MG_Util::PipeStats::AddCalls(MG_Util::PipeStats::CallClass::MapPersistentRoundtrips, 1);
}
return MGPipeRouteMapPersistent(BufferHandleOnly(handle), buffer.GetSize(), buffer.MappedData());
lifetime = MGPipeWatchResidentBuffer(handle);
void* base = MGPipeRouteMapPersistent(BufferHandleOnly(handle), buffer.GetSize(),
buffer.HasDefinedContent() ? buffer.MappedData() : nullptr);
if (base != nullptr && lifetime->load(std::memory_order_acquire)) return base;
MGPipeRevokeResidentBuffer(handle);
lifetime.reset();
return nullptr;
}
Bool MGPipeEmitResourceDestroyAndFree(BufferObject& buffer) {
MGPipeResourceTracker& tracker = MGPipeResourceTrackerInstance();
const MGPipeHandle handle = tracker.Find(buffer);
if (MGPipeHandleIsNull(handle)) return false;
MGPipeRevokeResidentBuffer(handle);
// THE LATCHED ANSWER, not the live one (m12): create and destroy are gated at two
// different moments, and a buffer constructed while a backend's table was registered
// and destroyed after UnregisterBufferBackendOps() would otherwise free its slot with
@@ -2602,8 +2596,20 @@ namespace MobileGL::MG_Pipe {
// boundary reads unpack state, and the staged-repack upload path does not even issue
// glPixelStorei (ARCHITECTURE.md 4.6 D5).
Uint64 EmitPixelPackState(GLContext& ctx) {
MGPPixelPackState pack{};
pack.Pack = ctx.GetPixelStoreParameters(false);
// Field by field into zeroed bytes: the two bytes of padding after the Bools would
// otherwise carry whatever the context's heap block held, onto the wire and into the
// recorder's hash.
MGPPixelPackState pack;
std::memset(&pack, 0, sizeof(pack));
const PixelStoreParameters live = ctx.GetPixelStoreParameters(false);
pack.Pack.SwapBytes = live.SwapBytes;
pack.Pack.LSBFirst = live.LSBFirst;
pack.Pack.RowLength = live.RowLength;
pack.Pack.ImageHeight = live.ImageHeight;
pack.Pack.SkipPixels = live.SkipPixels;
pack.Pack.SkipRows = live.SkipRows;
pack.Pack.SkipImages = live.SkipImages;
pack.Pack.Alignment = live.Alignment;
MGPipeRouteSetPixelPackState(pack);
return sizeof(MGPPixelPackState);
}
+8
View File
@@ -596,6 +596,13 @@ namespace MobileGL::MG_Pipe {
buffer->MarkGpuWrittenInChannelOrder();
}
inline std::optional<MGPipeLocalBufferShadow> MGPipeClientQueryLocalBufferShadow(MGPipeHandle res, SizeT width) {
const auto* buffer = MGPipeResourceTrackerInstance().Resolve(res);
if (buffer == nullptr) return std::nullopt;
if (buffer->GetSize() != width || buffer->IsBackendPersistentMapped()) return MGPipeLocalBufferShadow{};
return MGPipeLocalBufferShadow{buffer->MappedData(), buffer->HasDefinedContent()};
}
// MONOLITH ONLY (CONTRACT-P5C §4.1): with an active transport the three reverse entries
// of gMGPipeCallbacks are the SERVER session's producer callbacks and the client
// consumers are invoked BY NAME from DrainEventRing - the global table is a
@@ -620,6 +627,7 @@ namespace MobileGL::MG_Pipe {
};
install(gMGPipeCallbacks.OnBufferWriteback, &MGPipeClientOnBufferWriteback, "OnBufferWriteback");
install(gMGPipeCallbacks.OnGpuWritten, &MGPipeClientOnGpuWritten, "OnGpuWritten");
install(gMGPipeQueryLocalBufferShadow, &MGPipeClientQueryLocalBufferShadow, "QueryLocalBufferShadow");
}
// Legacy-object entry for the monolith backend. Transport consumers carry handles
+8 -7
View File
@@ -487,18 +487,19 @@ namespace MobileGL::MG_Pipe {
VaoMemo& MemoFor(const VertexArrayObject& vao) {
const Uint64 lifetimeId = vao.GetLifetimeId();
const Uint64 epoch = MGPipeSlots().ResetEpoch();
// The three emitters of one validate ask for the same array: the last answer's index,
// believed only while that entry still holds this id (a grow or an erase moves entries).
if (m_lastMemoIndex < m_vaoMemo.size() && m_vaoMemo[m_lastMemoIndex].LifetimeId == lifetimeId &&
m_vaoMemo[m_lastMemoIndex].SlotEpoch == epoch)
return m_vaoMemo[m_lastMemoIndex];
// Keep recent slots in the emitter across array switches. Collisions, growth and
// erasure can stale a hint, so check the lifetime and epoch before using it.
SizeT& hint = m_vaoMemoHints[lifetimeId & (m_vaoMemoHints.size() - 1)];
if (hint < m_vaoMemo.size() && m_vaoMemo[hint].LifetimeId == lifetimeId &&
m_vaoMemo[hint].SlotEpoch == epoch)
return m_vaoMemo[hint];
if (m_vaoMemo.empty() || (m_vaoMemoUsed + 1) * 2 > m_vaoMemo.size()) GrowVaoMemo();
const SizeT mask = m_vaoMemo.size() - 1;
SizeT i = VaoMemoHome(lifetimeId, mask);
while (m_vaoMemo[i].LifetimeId != 0 && m_vaoMemo[i].LifetimeId != lifetimeId)
i = (i + 1) & mask;
VaoMemo& memo = m_vaoMemo[i];
m_lastMemoIndex = i;
hint = i;
if (memo.LifetimeId == 0) ++m_vaoMemoUsed;
if (memo.LifetimeId != lifetimeId || memo.SlotEpoch != epoch) {
memo = VaoMemo{};
@@ -527,7 +528,7 @@ namespace MobileGL::MG_Pipe {
}
Vector<VaoMemo> m_vaoMemo;
SizeT m_vaoMemoUsed = 0;
SizeT m_lastMemoIndex = ~SizeT{0};
Array<SizeT, 256> m_vaoMemoHints{};
public:
// The VAO died (MGPipeEmitVertexElementsDestroyAndFree): its entry goes, by backward-shift
@@ -96,6 +96,7 @@ add_executable(MobileGLIntegrationTest
Scenarios/PrimitiveRestartScenario.cpp
Scenarios/FragCoordOriginScenario.cpp
Scenarios/ClipControlScenario.cpp
Scenarios/MultiviewScenario.cpp
Scenarios/ClientVertexArrayScenario.cpp
Scenarios/ClearThenReadPixelsScenario.cpp
# P15 S0: a clear between draws into the same framebuffer (DirectVulkan records it in the pass).
@@ -8,6 +8,8 @@
#include "HeadlessGL.h"
#include <Config.h>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
@@ -140,11 +142,6 @@ namespace MGITest {
#endif
}
std::string EnvOr(const char* name, const char* fallback) {
const char* value = std::getenv(name);
return (value != nullptr && value[0] != '\0') ? std::string(value) : std::string(fallback);
}
// A skip reason is only useful if it says which call failed AND why, so
// every bring-up step reports the EGL error it left behind.
std::string WithEglError(const char* what) {
@@ -564,16 +561,12 @@ namespace MGITest {
// before the pre-flight forks - the child must measure the same platform
// the parent will use.
EnsureHeadlessPlatform();
// The backend that is actually about to come up, which is what every
// `BackendName() == "DirectGLES"` gate in the scenarios means by the question.
// MG_ConfigLoader::InitBackendType defaults an unset MOBILEGL_BACKEND_TYPE to
// DirectGLES, so the same default belongs here; this used to report the literal
// "<unset>" instead. Under ctest the variable is always set by the ENVIRONMENT
// property, which is why that never showed - but run straight from a device
// shell, where nothing sets it, DirectGLES came up and every case gated on the
// NAME DirectGLES skipped as though it had not.
m_backendName = EnvOr("MOBILEGL_BACKEND_TYPE", "DirectGLES");
m_usable = BringUp();
if (m_usable) {
m_backendName = MobileGL::MG_Config::ActiveBackendType == MobileGL::BackendType::DirectVulkan
? "DirectVulkan"
: "DirectGLES";
}
}
bool HeadlessGL::BringUp() {
@@ -201,6 +201,8 @@ DUALBLOCK_CAPABILITY_SKIPS = {
"needs GL_KHR_shader_subgroup basic+arithmetic in compute",
"DirectGLES.Split.IterationRPScratchFixScenario.WideFixtureShapedReductionSumsEveryInvocation":
"needs GL_KHR_shader_subgroup basic+arithmetic in compute",
"DirectGLES.Split.MultiviewScenario.AScissoredClearAfterADrawReachesEveryView":
"ES driver crashes after a scissored clear of a multiview framebuffer",
}
# Outstanding behavior, not a claim that another backend covers these semantics.
@@ -31,6 +31,10 @@ require subgroup width 16..256; local lavapipe exposes 8, so those two have no l
execution coverage. Program203 and ScratchFix have passing Vulkan entries, which
is not proof of the GLES path. The checker reports **capability gaps (not covered)**.
`MultiviewScenario.AScissoredClearAfterADrawReachesEveryView` skips on Espryt over
llvmpipe: the driver corrupts its heap after a scissored clear of a multiview
framebuffer, which surfaces at context destroy. The Vulkan entries of the case pass.
## Optional measurement
`FencePollScenario.PacedFrameFenceWaitsBench` is not part of generic split correctness
@@ -90,6 +90,7 @@ set(MGL_P8A_AMBIENT_CASES
IterationRPScratchFixScenario.*
LayeredAttachmentBarrierScenario.*
LayeredAttachmentShapeScenario.*
MultiviewScenario.*
NarrowIntegerAttributeScenario.*
NonCoreImageFormatScenario.*
OrientationScenario.*
@@ -0,0 +1,215 @@
// MobileGL - MobileGL/MG_IntegrationTest/Scenarios/MultiviewScenario.cpp
// Copyright (c) 2026 MobileGL-Dev
// Licensed under the GNU Lesser General Public License v3.0:
// https://www.gnu.org/licenses/gpl-3.0.txt
// https://www.gnu.org/licenses/lgpl-3.0.txt
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
//
// Scenario - GL_OVR_multiview RENDERS EACH VIEW INTO ITS OWN LAYER.
//
// A two-view attachment of layers 1 and 2 of a three-layer array texture, read back one layer at
// a time through glFramebufferTextureLayer:
//
// - a draw reaches both views, with gl_ViewID_OVR telling them apart in the vertex stage (its
// position and a varying) and in the fragment stage;
// - a clear reaches both views, and layer 0, outside the views, is never written;
// - a scissored clear issued after a draw, while that draw's pass is still open, reaches both
// views too.
//
// Skipped where the backend does not advertise GL_OVR_multiview2.
#include <cstring>
#include <string>
#include "../Harness/HeadlessGL.h"
#include "../Harness/ScenarioFixture.h"
#ifdef GLAPI
#undef GLAPI
#endif
#define GL_GLEXT_PROTOTYPES
#include <GL/gl.h>
#include <GL/glcorearb.h>
#undef GL_GLEXT_PROTOTYPES
namespace MGITest {
namespace {
constexpr int kSize = 32;
// View 0 covers the whole target in red; view 1 only its left half, in green.
constexpr const char* kVaryingVS = R"(#version 330 core
#extension GL_OVR_multiview2 : require
layout(num_views = 2) in;
layout(location = 0) in vec2 aPos;
out vec4 vColor;
void main() {
bool second = gl_ViewID_OVR == 1u;
vColor = second ? vec4(0.0, 1.0, 0.0, 1.0) : vec4(1.0, 0.0, 0.0, 1.0);
float x = second ? aPos.x * 0.5 - 0.5 : aPos.x;
gl_Position = vec4(x, aPos.y, 0.0, 1.0);
}
)";
constexpr const char* kVaryingFS = R"(#version 330 core
in vec4 vColor;
out vec4 o_color;
void main() { o_color = vColor; }
)";
constexpr const char* kPlainVS = R"(#version 330 core
#extension GL_OVR_multiview2 : require
layout(num_views = 2) in;
layout(location = 0) in vec2 aPos;
void main() { gl_Position = vec4(aPos, 0.0, 1.0); }
)";
// The view seen from the fragment stage: red for view 0, green for view 1.
constexpr const char* kViewFS = R"(#version 330 core
#extension GL_OVR_multiview2 : require
out vec4 o_color;
void main() { o_color = gl_ViewID_OVR == 1u ? vec4(0.0, 1.0, 0.0, 1.0) : vec4(1.0, 0.0, 0.0, 1.0); }
)";
bool ExtensionAdvertised(const char* name) {
GLint count = 0;
glGetIntegerv(GL_NUM_EXTENSIONS, &count);
for (GLint i = 0; i < count; ++i) {
const auto* extension = reinterpret_cast<const char*>(glGetStringi(GL_EXTENSIONS, i));
if (extension && std::strcmp(extension, name) == 0) return true;
}
return false;
}
// llvmpipe's OpenGL ES driver corrupts its heap when a multiview framebuffer is cleared
// through a scissor: the context's teardown then crashes, with or without MobileGL in the
// process (reproduced on llvmpipe 25.2 with nothing but the clear and eglDestroyContext).
bool DriverBreaksScissoredMultiviewClears() {
const auto* renderer = reinterpret_cast<const char*>(glGetString(GL_RENDERER));
return renderer && std::strstr(renderer, "Espryt") && std::strstr(renderer, "llvmpipe");
}
void DrawFullScreen(unsigned int program) {
const float quad[] = {-1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f};
GLuint vao = 0, vbo = 0;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(quad), quad, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), nullptr);
glUseProgram(program);
glDrawArrays(GL_TRIANGLES, 0, 6);
glUseProgram(0);
glBindVertexArray(0);
glDeleteBuffers(1, &vbo);
glDeleteVertexArrays(1, &vao);
}
class MultiviewScenario : public ScenarioTest {
protected:
void SetUp() override {
ScenarioTest::SetUp();
if (!Ready()) return;
if (!ExtensionAdvertised("GL_OVR_multiview2")) {
GTEST_SKIP() << "GL_OVR_multiview2 is not advertised by this backend/driver";
}
glGenTextures(1, &m_texture);
glBindTexture(GL_TEXTURE_2D_ARRAY, m_texture);
glTexStorage3D(GL_TEXTURE_2D_ARRAY, 1, GL_RGBA8, kSize, kSize, 3);
glBindTexture(GL_TEXTURE_2D_ARRAY, 0);
glGenFramebuffers(1, &m_readFbo);
glGenFramebuffers(1, &m_multiviewFbo);
// Every layer black first, one at a time, so layer 0 has a known value to keep.
for (GLint layer = 0; layer < 3; ++layer) {
glBindFramebuffer(GL_FRAMEBUFFER, m_readFbo);
glFramebufferTextureLayer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, m_texture, 0, layer);
ClearTo(0.0f, 0.0f, 0.0f, 1.0f);
}
glBindFramebuffer(GL_FRAMEBUFFER, m_multiviewFbo);
glFramebufferTextureMultiviewOVR(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, m_texture, 0, 1, 2);
ASSERT_EQ(glCheckFramebufferStatus(GL_FRAMEBUFFER), static_cast<GLenum>(GL_FRAMEBUFFER_COMPLETE));
glViewport(0, 0, kSize, kSize);
}
void TearDown() override {
if (m_texture == 0) return;
glDisable(GL_SCISSOR_TEST);
BindDefaultFramebuffer();
glDeleteFramebuffers(1, &m_multiviewFbo);
glDeleteFramebuffers(1, &m_readFbo);
glDeleteTextures(1, &m_texture);
}
Image ReadLayer(GLint layer) {
glBindFramebuffer(GL_FRAMEBUFFER, m_readFbo);
glFramebufferTextureLayer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, m_texture, 0, layer);
Image image = ReadPixels(kSize, kSize);
glBindFramebuffer(GL_FRAMEBUFFER, m_multiviewFbo);
return image;
}
::testing::AssertionResult HalvesAre(GLint layer, const char* left, const char* right,
const std::string& when) {
const Image image = ReadLayer(layer);
const std::string where = when + ", layer " + std::to_string(layer);
auto first = RegionIsMostly(image, 2, kSize / 2 - 3, 2, kSize - 3, left, 0.0, where + " (left half)");
if (!first) return first;
return RegionIsMostly(image, kSize / 2 + 2, kSize - 3, 2, kSize - 3, right, 0.0,
where + " (right half)");
}
GLuint m_texture = 0;
GLuint m_readFbo = 0;
GLuint m_multiviewFbo = 0;
};
} // namespace
TEST_F(MultiviewScenario, ADrawReachesEveryViewAndTheVertexStageTellsThemApart) {
if (!Ready() || IsSkipped()) return;
std::string error;
const unsigned int program = CompileProgram(kVaryingVS, kVaryingFS, &error);
ASSERT_NE(program, 0u) << error;
ClearTo(0.0f, 0.0f, 1.0f, 1.0f);
DrawFullScreen(program);
EXPECT_EQ(FirstGLError(), 0u);
EXPECT_TRUE(HalvesAre(0, "black", "black", "outside the views"));
EXPECT_TRUE(HalvesAre(1, "red", "red", "view 0"));
EXPECT_TRUE(HalvesAre(2, "green", "blue", "view 1"));
glDeleteProgram(program);
EXPECT_EQ(FirstGLError(), 0u);
}
TEST_F(MultiviewScenario, TheFragmentStageSeesItsView) {
if (!Ready() || IsSkipped()) return;
std::string error;
const unsigned int program = CompileProgram(kPlainVS, kViewFS, &error);
ASSERT_NE(program, 0u) << error;
DrawFullScreen(program);
EXPECT_EQ(FirstGLError(), 0u);
EXPECT_TRUE(HalvesAre(1, "red", "red", "view 0"));
EXPECT_TRUE(HalvesAre(2, "green", "green", "view 1"));
glDeleteProgram(program);
EXPECT_EQ(FirstGLError(), 0u);
}
TEST_F(MultiviewScenario, AScissoredClearAfterADrawReachesEveryView) {
if (!Ready() || IsSkipped()) return;
if (DriverBreaksScissoredMultiviewClears()) {
GTEST_SKIP() << "llvmpipe's ES driver crashes after a scissored clear of a multiview framebuffer";
}
std::string error;
const unsigned int program = CompileProgram(kPlainVS, kViewFS, &error);
ASSERT_NE(program, 0u) << error;
DrawFullScreen(program);
glEnable(GL_SCISSOR_TEST);
glScissor(kSize / 2, 0, kSize / 2, kSize);
ClearTo(0.0f, 0.0f, 1.0f, 1.0f);
glDisable(GL_SCISSOR_TEST);
EXPECT_EQ(FirstGLError(), 0u);
EXPECT_TRUE(HalvesAre(1, "red", "blue", "view 0"));
EXPECT_TRUE(HalvesAre(2, "green", "blue", "view 1"));
EXPECT_TRUE(HalvesAre(0, "black", "black", "outside the views"));
glDeleteProgram(program);
EXPECT_EQ(FirstGLError(), 0u);
}
} // namespace MGITest
+10
View File
@@ -45,6 +45,16 @@ namespace MobileGL::MG_Pipe {
// Null-initialized: a backend that installs nothing sends nothing.
inline MGPipeCallbacks gMGPipeCallbacks{};
struct MGPipeLocalBufferShadow {
const Uint8* Bytes = nullptr;
Bool HasDefinedContent = false;
};
// Monolith only. The optional is empty for an unknown handle. A known buffer can have
// no shadow at the requested width. The bytes are borrowed for the current buffer sync.
using MGPipeLocalBufferShadowQuery = std::optional<MGPipeLocalBufferShadow> (*)(MGPipeHandle, SizeT);
inline MGPipeLocalBufferShadowQuery gMGPipeQueryLocalBufferShadow = nullptr;
// Size of the SEG_EVENT ring, which bounds one reverse-channel record. OnBufferWriteback
// carries its bytes inline, and the ring producer always refuses a record above half its
// capacity (Transport/Ring.h) with Fatal{EventRingOverflow}, so producers slice wide ranges
+5 -1
View File
@@ -677,7 +677,11 @@ namespace MobileGL::MG_Pipe {
Uint32 InternalFormat;
Uint8 Kind; // kMGPipeSurfaceKind{None,Texture,Renderbuffer}, above
Uint8 Layered;
Uint16 Level;
// A mip level fits a byte: GL_MAX_TEXTURE_SIZE would have to pass 2^255 for it not to.
Uint8 Level;
// GL_OVR_multiview: non-zero on a multiview attachment, which renders views
// [Layer, Layer + NumViews) of a 2D array texture. Layered is then 0.
Uint8 NumViews;
Uint32 Layer;
Uint16 UploadTarget; // static_cast<Uint16>(MobileGL::TextureUploadTarget)
// static_cast<Uint16>(MobileGL::TextureTarget), or kMGPipeSurfaceNoTextureTarget on a
+17 -37
View File
@@ -1631,6 +1631,7 @@ namespace MobileGL::MG_Pipe {
}
void MGPipeSetResourceOps(const MGPipeResourceOps* ops) {
if (g_resourceOps != ops) MGPipeRevokeAllResidentBuffers();
g_resourceOps = ops;
}
const MGPipeResourceOps* MGPipeGetResourceOps() {
@@ -2413,9 +2414,9 @@ namespace MobileGL::MG_Pipe {
}
}
void MGPipeApplyResourceReadback(const MGPReadback& record) {
Bool MGPipeApplyResourceReadback(const MGPReadback& record) {
MGPipeResourceRecord* stored = ResolveResource("resource_readback", record.Res);
if (stored == nullptr) return;
if (stored == nullptr) return false;
const char* fault = BufferRangeFault(record.Offset, record.Size, stored->Desc.Width);
if (fault != nullptr) {
@@ -2425,29 +2426,14 @@ namespace MobileGL::MG_Pipe {
record.Res.Slot, record.Res.Gen, stored->Desc.GlNameForDiag, fault,
static_cast<unsigned long long>(record.Offset),
static_cast<unsigned long long>(record.Size), stored->Desc.Width);
return;
return false;
}
// The readback READS the store this flag describes, so it is one of the calls whose
// answer would change silently the day a producer sets it (D-A4).
PinNoLiveHostWrites(*stored, record.Res, "resource_readback");
// NO SERIAL MOVES. A readback does not mutate the resource; it produces host bytes out
// of it. Bumping here would tell the backend twin its store had changed and buy a
// re-upload of what it had just been read out of.
//
// THE ANSWER TRAVELS BACK THROUGH THE REVERSE CHANNEL, NOT THROUGH THIS FUNCTION, and
// the applier's contribution to that is the ORDER: the hook is called synchronously
// and this returns only once it has finished, so the writeback into the client's
// shadow and the mutation-epoch bump that must follow it have both happened before the
// caller reads. The epoch bump stays server-side and happens AFTER the writeback,
// never before - a rule the reverse channel needs as much as the forward one, because
// a bump that overtook its writeback would leave the draw-clean memo stale behind it.
//
// With no table registered nothing answers, and nothing asks either: the frontend is
// still on the path this call replaces.
if (g_resourceOps != nullptr && g_resourceOps->Readback != nullptr) {
g_resourceOps->Readback(record.Res, record);
}
// Readback changes no resource serial. The synchronous hook delivers the bytes or
// synchronizes shared memory before reporting success.
return g_resourceOps != nullptr && g_resourceOps->Readback != nullptr &&
g_resourceOps->Readback(record.Res, record);
}
void MGPipeApplyResourceDestroy(const MGPHandleOnly& handle) {
@@ -2523,19 +2509,7 @@ namespace MobileGL::MG_Pipe {
PinNoLiveHostWrites(*record, handle.Handle, "map_persistent");
#if MOBILEGL_BUILD_DISAGGREGATED
// R-6: A SPLIT BUILD RUNS AT TIER T2 AND DECLINES EVERY ACQUISITION, ALWAYS.
//
// The mint returns a raw void* that the client stores as the store's base
// (BufferObject.cpp:238 / :603 / :658). Across a process boundary that address is
// meaningless, and under `inproc` it is WORSE than meaningless: it happens to work,
// so a lane that kept adoption alive would be green for a reason spawn cannot
// reproduce, and persistent-map-push - an exit-gate counter - would be structurally
// zero (PipeStats.cpp says so in as many words). Forcing T2 here rather than at the
// three client call sites is what keeps `mpr` identical between the arms: the
// roundtrip is COUNTED above, unconditionally, because a decline costs the same round
// trip as a mint.
//
// The frontend already tolerates a decline in all three places, and has since P3a.
// The emulated tier has its own shadow and never borrows a backend pointer.
if (MG_Config::Transport != MG_Config::TransportMode::Monolith && MG_Remote::Client::AdoptTierIsEmulate()) {
return nullptr;
}
@@ -2554,7 +2528,10 @@ namespace MobileGL::MG_Pipe {
// An adopted store has no live host writer to announce: the client writes the store's
// own memory and tells the applier nothing (BufferObject::NotePersistentMapStateChanged
// sends no falling edge for it), so the rising edge the map published ends here.
if (base != nullptr) record->HasLiveHostWrites = false;
if (base != nullptr) {
record->HasLiveHostWrites = false;
MGPipeNoteResidentMapBase(handle.Handle, base);
}
return base;
}
@@ -2628,7 +2605,10 @@ namespace MobileGL::MG_Pipe {
PinNoLiveHostWrites(*record, handle.Handle, "donate_in_process");
if (g_resourceOps == nullptr || g_resourceOps->DonateInProcess == nullptr) return nullptr;
void* base = g_resourceOps->DonateInProcess(handle.Handle, record->Desc.Width);
if (base != nullptr) record->HasLiveHostWrites = false; // as map_persistent's mint
if (base != nullptr) {
record->HasLiveHostWrites = false;
MGPipeNoteResidentMapBase(handle.Handle, base);
}
return base;
}
#endif
+13 -5
View File
@@ -8,6 +8,7 @@
#pragma once
#include <Includes.h>
#include <atomic>
#include "MGPipeRenderStateSpans.h"
#include "MGPipeTypes.h"
@@ -69,7 +70,8 @@ namespace MobileGL::MG_Pipe {
// the duration of the call only.
void (*SubDataResident)(MGPipeHandle res, const MGPSubData& record, const void* bytes);
void (*FlushRange)(MGPipeHandle res, const MGPFlushRange& record, const void* bytes);
void (*Readback)(MGPipeHandle res, const MGPReadback& record);
// True once the requested bytes are visible to the host.
Bool (*Readback)(MGPipeHandle res, const MGPReadback& record);
void (*Destroy)(MGPipeHandle res);
void* (*MapPersistent)(MGPipeHandle res, Uint64 size, const void* seedBytes);
void (*UnmapPersistent)(MGPipeHandle res);
@@ -117,6 +119,13 @@ namespace MobileGL::MG_Pipe {
void MGPipeSetResourceOps(const MGPipeResourceOps* ops);
const MGPipeResourceOps* MGPipeGetResourceOps();
// Local frontend map lifetimes. Revoke before the owner releases the mapped storage.
SharedPtr<const std::atomic<Bool>> MGPipeWatchResidentBuffer(MGPipeHandle handle);
void MGPipeNoteResidentMapBase(MGPipeHandle handle, const void* base);
Bool MGPipeSeedResidentBuffer(const std::atomic<Bool>& lifetime, void* base, const void* seed, SizeT size);
void MGPipeRevokeResidentBuffer(MGPipeHandle handle, const void* mappedBase = nullptr);
void MGPipeRevokeAllResidentBuffers();
// ---------------------------------------------------------------------------------
// P3a: the applier's own records (D-G4)
// ---------------------------------------------------------------------------------
@@ -1168,10 +1177,9 @@ namespace MobileGL::MG_Pipe {
// resource_flush_range: record.AccessFlags are the application's REAL mapping flags, not
// a normalized subset - the backend reads them per call to choose its upload shape.
void MGPipeApplyResourceFlushRange(const MGPFlushRange& record, const void* bytes);
// resource_readback: whole-buffer by contract. The answer travels back through the
// reverse channel, and the writeback happens BEFORE the mutation epoch bumps, never
// after - the ordering is a correctness rule, not a preference.
void MGPipeApplyResourceReadback(const MGPReadback& record);
// Resource readback returns the backend verdict. Any reverse writeback precedes the
// mutation epoch bump and the successful reply.
Bool MGPipeApplyResourceReadback(const MGPReadback& record);
// resource_destroy: clears Live and drops the record, then the backend frees its twin.
// The CLIENT frees the slot afterwards, in that order, because the allocator forgets the
// lifetime id on free and a notice resolved twice finds nothing the second time.
+2 -2
View File
@@ -100,7 +100,7 @@
// Pad<n>, so the rename without this row is a pipe-gates failure, and the row without the
// rename is one too. A meaning-carrying byte cannot enter this record silently.
#define MGP_FIELDS_MGPSurface(F) \
F(Res) F(InternalFormat) F(Kind) F(Layered) F(Level) F(Layer) F(UploadTarget) F(TextureTarget)
F(Res) F(InternalFormat) F(Kind) F(Layered) F(Level) F(NumViews) F(Layer) F(UploadTarget) F(TextureTarget)
// P4a, D-C2: Pad0 became Uint8 Target, and gen_pipe.py's PADDING_MEMBER_RE only excludes a
// member still NAMED Pad<n> - so the rename without this row is a pipe-gates failure, which
@@ -399,7 +399,7 @@
F(FragmentShadingRateAttachmentWithDefaultFramebuffer) F(FragmentShadingRateMasks) \
F(MinFragmentShadingRateAttachmentTexelWidth) F(MinFragmentShadingRateAttachmentTexelHeight) \
F(MaxFragmentShadingRateAttachmentTexelWidth) F(MaxFragmentShadingRateAttachmentTexelHeight) \
F(MaxFragmentShadingRateAttachmentTexelAspectRatio) F(MaxFragmentShadingRateAttachmentLayers)
F(MaxFragmentShadingRateAttachmentTexelAspectRatio) F(MaxFragmentShadingRateAttachmentLayers) F(MaxViews)
#define MGP_FIELDS_MGHostSpan(F) \
F(Ptr) F(Seg) F(Size) F(Offset)
+6 -3
View File
@@ -17,6 +17,7 @@
// that one field when it belongs to the verb in flight. It never touches the poison stamp, so a
// stamp the fill withheld (negative control B) stays withheld.
#include <MG_Pipe/MGPipe.h>
#include <atomic>
namespace MobileGL::MG_Pipe {
// MG_Impl/Pipe/PipeFill.cpp (the client side, the only place that may spell pGLContext).
// A no-op unless a context is live, a verb has been filled, and `field` is in that verb
@@ -228,15 +229,17 @@ namespace MobileGL::MG_Pipe {
SizeT size);
void MGPipeEmitResourceFlushRange(MG_State::GLState::BufferObject& buffer, SizeT offset, SizeT size,
Uint32 accessFlags);
void MGPipeEmitResourceReadback(MG_State::GLState::BufferObject& buffer);
Bool MGPipeEmitResourceReadback(MG_State::GLState::BufferObject& buffer);
// The ranged form, for the split arm's sliced whole-buffer readback: the writeback's
// bytes travel INLINE in a SEG_EVENT record, so a buffer larger than the ring can hold
// is read back as [offset, offset+size) slices, each its own record. Monolith never
// calls it - the direct callback carries a pointer, not a copy.
void MGPipeEmitResourceReadbackRange(MG_State::GLState::BufferObject& buffer, SizeT offset, SizeT size);
Bool MGPipeEmitResourceReadbackRange(MG_State::GLState::BufferObject& buffer, SizeT offset, SizeT size);
[[noreturn]] void MGPipeFailResourceReadback(Uint buffer, SizeT offset, SizeT size, Bool accepted);
// Returns the coherent host pointer the resource owner donated, or null for a DECLINE -
// which is a real answer. Every call, mint or decline, is one map-persistent roundtrip.
void* MGPipeEmitMapPersistent(MG_State::GLState::BufferObject& buffer);
void* MGPipeEmitMapPersistent(MG_State::GLState::BufferObject& buffer,
SharedPtr<const std::atomic<Bool>>& lifetime);
// ================================================================================
// Birth hooks, one per client path MG_State owns
+79
View File
@@ -0,0 +1,79 @@
// MobileGL - MobileGL/MG_Pipe/PipeResidentBuffer.cpp
// Copyright (c) 2025-2026 MobileGL-Dev
// Licensed under the GNU Lesser General Public License v3.0:
// https://www.gnu.org/licenses/gpl-3.0.txt
// https://www.gnu.org/licenses/lgpl-3.0.txt
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
#include "PipeApply.h"
#include <cstring>
#include <mutex>
namespace MobileGL::MG_Pipe {
namespace {
struct ResidentBufferMap {
WeakPtr<std::atomic<Bool>> Lifetime;
const void* Base = nullptr;
};
struct ResidentBufferMaps {
std::mutex Mutex;
UnorderedMap<Uint64, ResidentBufferMap> ByHandle;
};
ResidentBufferMaps& ResidentMaps() {
static auto* maps = new ResidentBufferMaps();
return *maps;
}
Uint64 ResidentMapKey(MGPipeHandle handle) {
return (static_cast<Uint64>(handle.Gen) << 32) | handle.Slot;
}
} // namespace
void MGPipeNoteResidentMapBase(MGPipeHandle handle, const void* base) {
auto& maps = ResidentMaps();
const std::lock_guard<std::mutex> lock(maps.Mutex);
const auto it = maps.ByHandle.find(ResidentMapKey(handle));
if (it != maps.ByHandle.end()) it->second.Base = base;
}
SharedPtr<const std::atomic<Bool>> MGPipeWatchResidentBuffer(MGPipeHandle handle) {
auto& maps = ResidentMaps();
const std::lock_guard<std::mutex> lock(maps.Mutex);
auto& map = maps.ByHandle[ResidentMapKey(handle)];
if (auto lifetime = map.Lifetime.lock()) return lifetime;
auto lifetime = MakeShared<std::atomic<Bool>>(true);
map = {lifetime, nullptr};
return lifetime;
}
Bool MGPipeSeedResidentBuffer(const std::atomic<Bool>& lifetime, void* base, const void* seed, SizeT size) {
// A same-process donation can be revoked by the apply thread as the reply arrives.
const std::lock_guard<std::mutex> lock(ResidentMaps().Mutex);
if (!lifetime.load(std::memory_order_acquire)) return false;
if (seed != nullptr) std::memcpy(base, seed, size);
return true;
}
void MGPipeRevokeResidentBuffer(MGPipeHandle handle, const void* mappedBase) {
auto& maps = ResidentMaps();
const std::lock_guard<std::mutex> lock(maps.Mutex);
const auto it = maps.ByHandle.find(ResidentMapKey(handle));
if (it == maps.ByHandle.end() || (mappedBase != nullptr && mappedBase != it->second.Base)) return;
if (auto lifetime = it->second.Lifetime.lock()) lifetime->store(false, std::memory_order_release);
maps.ByHandle.erase(it);
}
void MGPipeRevokeAllResidentBuffers() {
auto& maps = ResidentMaps();
const std::lock_guard<std::mutex> lock(maps.Mutex);
for (const auto& entry : maps.ByHandle) {
if (auto lifetime = entry.second.Lifetime.lock()) lifetime->store(false, std::memory_order_release);
}
maps.ByHandle.clear();
}
} // namespace MobileGL::MG_Pipe
+17 -7
View File
@@ -16,6 +16,8 @@
// static-archive link can drop this object), so no MGP_* thunk needs a null check.
#include "PipeRoute.h"
#include "PipeMutation.h"
#include "PipeSessionFail.h"
#include <MG_Util/Debug/Log.h>
#include <Config.h>
@@ -67,6 +69,19 @@ namespace MobileGL::MG_Pipe {
return g_monolithEscapes;
}
void MGPipeFailResourceReadback(Uint buffer, SizeT offset, SizeT size, Bool accepted) {
if (!accepted) {
MGPipeRecordFail(MGFatalFamily::ReadbackDeclined,
"MGPipe: Fatal{ReadbackDeclined, \"buffer-writeback\"} - buffer %u "
"could not read back %zu bytes at offset %zu",
buffer, size, offset);
}
MGPipeRecordFail(MGFatalFamily::UnimplementedWritebackWait,
"MGPipe: Fatal{UnimplementedWritebackWait} - readback for buffer %u "
"succeeded without making its GPU writes visible to the host",
buffer);
}
MGPReplySlot MGPipeMintReplySlot() {
// 1-based, for ReplySlot.h's reason: "Seq is 1-based; 0 means 'no record'". A zero id
// must stay unmintable so an un-posted mailbox is distinguishable from a posted one.
@@ -260,14 +275,9 @@ namespace MobileGL::MG_Pipe {
std::abort();
}
// resource_readback carries kReplySlot but its answer is COMPLETION, not a value: the
// bytes go server -> client through SEG_EVENT's OnBufferWriteback (CONTRACT-P5 table 1
// row 22), and the split decoder posts exactly kStatusOk with a zero-length payload.
// The monolith arm says the same thing, so the two arms hand their caller the same
// answer rather than one of them handing it nothing.
void Mono_ResourceReadback(const MGPReadback* payload, MGPReplySlot* reply) {
MGPipeApplyResourceReadback(*payload);
MGPipePostReply(*reply, 0, 0);
const Bool accepted = MGPipeApplyResourceReadback(*payload);
MGPipePostReply(*reply, accepted ? 0 : 1, accepted ? 1u : 0u);
}
// The three acceptance rows that DO fit a generated signature. Each posts the
+2 -5
View File
@@ -211,13 +211,10 @@ namespace MobileGL::MG_Pipe {
inline void MGPipeRouteResourceFlushRange(const MGPFlushRange& record, const void* bytes) {
gMGPipeRouteEscapes.ResourceFlushRange(&record, bytes);
}
inline void MGPipeRouteResourceReadback(const MGPReadback& record) {
inline Bool MGPipeRouteResourceReadback(const MGPReadback& record) {
MGPReplySlot reply = MGPipeMintReplySlot();
MGP_ResourceReadback(&record, &reply);
// The answer is COMPLETION, not a value: the bytes come back through SEG_EVENT's
// OnBufferWriteback (table 1 row 22). It is still TAKEN, because an untaken mailbox
// entry is what the next row's ReplyOverrun Fatal is looking for.
(void)MGPipeTakeReplyBool(reply, "resource_readback");
return MGPipeTakeReplyBool(reply, "resource_readback");
}
// ---- render state ------------------------------------------------------------------
@@ -142,6 +142,7 @@ inline constexpr WireLayoutMember kMGPipeWireLayoutMembers[] = {
{"MGPSurface.Kind", offsetof(MGPSurface, Kind), sizeof(((MGPSurface*)nullptr)->Kind)},
{"MGPSurface.Layered", offsetof(MGPSurface, Layered), sizeof(((MGPSurface*)nullptr)->Layered)},
{"MGPSurface.Level", offsetof(MGPSurface, Level), sizeof(((MGPSurface*)nullptr)->Level)},
{"MGPSurface.NumViews", offsetof(MGPSurface, NumViews), sizeof(((MGPSurface*)nullptr)->NumViews)},
{"MGPSurface.Layer", offsetof(MGPSurface, Layer), sizeof(((MGPSurface*)nullptr)->Layer)},
{"MGPSurface.UploadTarget", offsetof(MGPSurface, UploadTarget), sizeof(((MGPSurface*)nullptr)->UploadTarget)},
{"MGPSurface.TextureTarget", offsetof(MGPSurface, TextureTarget), sizeof(((MGPSurface*)nullptr)->TextureTarget)},
@@ -685,6 +686,7 @@ inline constexpr WireLayoutMember kMGPipeWireLayoutMembers[] = {
{"DynamicBackendParameters.MaxFragmentShadingRateAttachmentTexelHeight", offsetof(DynamicBackendParameters, MaxFragmentShadingRateAttachmentTexelHeight), sizeof(((DynamicBackendParameters*)nullptr)->MaxFragmentShadingRateAttachmentTexelHeight)},
{"DynamicBackendParameters.MaxFragmentShadingRateAttachmentTexelAspectRatio", offsetof(DynamicBackendParameters, MaxFragmentShadingRateAttachmentTexelAspectRatio), sizeof(((DynamicBackendParameters*)nullptr)->MaxFragmentShadingRateAttachmentTexelAspectRatio)},
{"DynamicBackendParameters.MaxFragmentShadingRateAttachmentLayers", offsetof(DynamicBackendParameters, MaxFragmentShadingRateAttachmentLayers), sizeof(((DynamicBackendParameters*)nullptr)->MaxFragmentShadingRateAttachmentLayers)},
{"DynamicBackendParameters.MaxViews", offsetof(DynamicBackendParameters, MaxViews), sizeof(((DynamicBackendParameters*)nullptr)->MaxViews)},
{"MGHostSpan", 0, sizeof(MGHostSpan)},
{"MGHostSpan.Ptr", offsetof(MGHostSpan, Ptr), sizeof(((MGHostSpan*)nullptr)->Ptr)},
{"MGHostSpan.Seg", offsetof(MGHostSpan, Seg), sizeof(((MGHostSpan*)nullptr)->Seg)},
@@ -201,7 +201,7 @@ namespace MobileGL::MG_Remote::Client {
// P12 (D1): unless the window is the SERVER's - then there is no handle of ours to tell.
if (MG_Config::ServerOwnedWindowSurfaces()) return CreateServerOwnedWindowSurface(surface, handle);
Server::ServerSetWindowHandle(handle);
if (!Server::ServerCreateEGLWindowSurface(surface, handle)) return false;
if (!Server::ServerCreateEGLWindowSurface(surface, handle, EGLRegistry().RegistrationDisplay())) return false;
// The server's surface init published the default framebuffer's shape as a
// surface-changed EVENT (P5c ev): DirectGLES' depth/stencil format, Magma's
// swapchain extent. Apply it NOW - the RPC's return is a moment the apply thread
@@ -281,9 +281,13 @@ namespace MobileGL::MG_Remote::Client {
return CreatePbufferOnServer(surface, width, height, /*standIn=*/false);
}
Bool BackendObject_Remote::CreateEGLSurfacelessStandIn(EGLSurface surface, EGLint width, EGLint height) {
if (!CreatePbufferOnServer(surface, width, height, /*standIn=*/true)) return false;
Bool BackendObject_Remote::CreateEGLSurfacelessStandIn(EGLDisplay display, EGLSurface surface, EGLint width,
EGLint height) {
const auto lock = EGLRegistry().Lock();
const auto previousDisplay = EGLRegistry().SetRegistrationDisplay(display);
const Bool created = CreatePbufferOnServer(surface, width, height, /*standIn=*/true);
EGLRegistry().SetRegistrationDisplay(previousDisplay);
if (!created) return false;
m_standInSurfaces.insert(surface);
return true;
}
@@ -292,7 +296,8 @@ namespace MobileGL::MG_Remote::Client {
WaitForApplyBeforeEglForwarder("CreateEGLPbufferSurface");
Server::SurfaceRefusalCode refusal = Server::SurfaceRefusalCode::None;
if (!Server::ServerCreateEGLPbufferSurface(surface, width, height, &refusal,
standIn ? Server::kPbufferFlagSurfacelessStandIn : 0u)) {
standIn ? Server::kPbufferFlagSurfacelessStandIn : 0u,
EGLRegistry().RegistrationDisplay())) {
if (refusal == Server::SurfaceRefusalCode::SurfaceModeMismatch) {
// P12 (D4), named on THIS side too: the server logged its half.
MGLOG_E("MG_Remote client: SurfaceModeMismatch - eglCreatePbufferSurface (%dx%d) in a session "
@@ -322,8 +327,8 @@ namespace MobileGL::MG_Remote::Client {
Bool BackendObject_Remote::CreateServerOwnedWindowSurface(EGLSurface surface,
const MG_Backend::WindowHandle& handle) {
const Server::ServerOwnedWindowReply reply =
Server::ServerCreateServerOwnedWindowSurface(surface, handle.Width, handle.Height);
const Server::ServerOwnedWindowReply reply = Server::ServerCreateServerOwnedWindowSurface(
surface, handle.Width, handle.Height, EGLRegistry().RegistrationDisplay());
if (!reply.ok) {
// P12: FAILS BY NAME ON THIS SIDE TOO. The server logged its reason; the reply's refusal
// code is what lets this line say the same thing instead of "ok=false".
@@ -498,10 +503,8 @@ namespace MobileGL::MG_Remote::Client {
m_sessionSharedImages.clear();
// The display the application initialized is initialized on the new server too: its
// surfaces and contexts are created against it from here on.
if (EGLRegistry().DisplayInitialized()) {
EGLint major = 0;
EGLint minor = 0;
if (!Server::ServerInitializeEGLDisplay(EGLRegistry().Display(), &major, &minor)) {
for (const EGLDisplay display : EGLRegistry().InitializedDisplays()) {
if (!Server::ServerInitializeEGLDisplay(display, nullptr, nullptr)) {
MGLOG_E("MG_Remote client: the fresh session's server did not initialize the display; "
"surfaces and contexts on it will fail");
}
@@ -522,7 +525,8 @@ namespace MobileGL::MG_Remote::Client {
const char* kind = "pbuffer";
if (state.Kind == MG_Backend::EGLSurfaceRegistry::SurfaceKind::Pbuffer) {
const Uint32 flags = m_standInSurfaces.count(surface) != 0 ? Server::kPbufferFlagSurfacelessStandIn : 0u;
recreated = Server::ServerCreateEGLPbufferSurface(surface, state.Width, state.Height, nullptr, flags);
recreated = Server::ServerCreateEGLPbufferSurface(surface, state.Width, state.Height, nullptr, flags,
state.Display);
} else if (ClientSession::IsServerOwnedWindowSurface(surface)) {
kind = "server-owned window";
// The window is asked for what the application asked for (its own size for a surface
@@ -531,7 +535,7 @@ namespace MobileGL::MG_Remote::Client {
const Uint32 wantWidth = requested != m_serverOwnedRequests.end() ? requested->second.first : 0u;
const Uint32 wantHeight = requested != m_serverOwnedRequests.end() ? requested->second.second : 0u;
const Server::ServerOwnedWindowReply reply =
Server::ServerCreateServerOwnedWindowSurface(surface, wantWidth, wantHeight);
Server::ServerCreateServerOwnedWindowSurface(surface, wantWidth, wantHeight, state.Display);
recreated = reply.ok;
if (recreated && reply.width != 0 && reply.height != 0) {
if (MG_State::pEGLContext) {
@@ -544,7 +548,7 @@ namespace MobileGL::MG_Remote::Client {
} else {
kind = "window";
Server::ServerSetWindowHandle(state.Window);
recreated = Server::ServerCreateEGLWindowSurface(surface, state.Window);
recreated = Server::ServerCreateEGLWindowSurface(surface, state.Window, state.Display);
}
if (!recreated) {
MGLOG_E("MG_Remote client: the %s surface %p (%dx%d) of a lost session could not be re-created on "
@@ -87,7 +87,7 @@ namespace MobileGL::MG_Remote::Client {
// EGL_KHR_surfaceless_context's hidden pbuffer (EGLImpl's SurfacelessStandIn): an ordinary
// pbuffer on this side, created on the server with kPbufferFlagSurfacelessStandIn so it
// takes no surface mode there, and re-created the same way on a fresh session.
Bool CreateEGLSurfacelessStandIn(EGLSurface surface, EGLint width, EGLint height);
Bool CreateEGLSurfacelessStandIn(EGLDisplay display, EGLSurface surface, EGLint width, EGLint height);
protected:
Bool InitPbufferSurface(EGLint width, EGLint height) override;
+11 -13
View File
@@ -34,6 +34,7 @@
#include <MG_Impl/GLImpl/Framebuffer/GL_Framebuffer.h>
#include <MG_Impl/Pipe/ResourceTracker.h>
#include <MG_Pipe/MGPipeCallbacks.h>
#include <MG_Pipe/PipeApply.h>
#include <MG_Pipe/PipeMutation.h>
#include <MG_State/EGLState/Core.h>
#include <MG_State/GLState/Core.h>
@@ -1938,6 +1939,7 @@ namespace MobileGL::MG_Remote::Client {
// process with no session at all - and by then the rings are gone, so the applier a
// monolith adapter runs is a defined no-op rather than a use-after-free.
UninstallClientWireTables();
if (m_started) MG_Pipe::MGPipeRevokeAllResidentBuffers();
if (!m_started) {
m_controlInbox.reset();
if (m_socketTransport) m_socketTransport->Shutdown();
@@ -2027,8 +2029,7 @@ namespace MobileGL::MG_Remote::Client {
// 4. and ONLY NOW may anything an emitter owns be released: a var-tail still
// referenced by an unapplied record is a use-after-free the join is what prevents.
LogMemory("teardown");
// P11 B2: the T0 arm's proof for this session, and the client's references to its stores
// (the server's imports held their own and are gone with the server's backend).
// The server is done with its imports. Release the client's stores.
ResetT0(true);
LogWireLedger();
Transport::LinkMetricsEnd();
@@ -2366,11 +2367,8 @@ namespace MobileGL::MG_Remote::Client {
Transport::LinkMetricsReplyApplied(replyMetricStart);
// THE REVERSE CHANNEL IS DRAINED HERE, and here is the only place it can be: under the
// barrier this is the one instant at which the apply thread is known not to be inside
// the applier, and MGPipeClientOnGpuWritten / OnBufferWriteback write frontend objects.
// It is what gives AwaitBufferWriteback something to have waited FOR: b1's third state
// clears when the writeback lands, and the writeback lands on this ring.
// The barrier makes it safe to apply events that update frontend objects. Drain their
// writebacks before returning the readback verdict to the caller.
DrainEventRing(*m_events);
if (!ownsReplySlot) {
@@ -3076,12 +3074,9 @@ namespace MobileGL::MG_Remote::Client {
return nullptr;
}
// T0 IN ONE PROCESS (kCapAdoptInProcess): the OK answer carries the address of the server's own
// mapping of the store, which becomes this buffer's persistent map - the memory both sides
// already share, as monolith's donation is. The server has drained the GPU's use of the store
// before answering and applies nothing of this client's until this call returns, so the
// shadow is copied in here, by the side that owns it.
// The apply thread drains GPU use before donating its mapping. The client seeds that mapping.
void* ClientSession::AdoptPersistentInProcess(const MG_Pipe::MGPHandleOnly& handle, Uint64 size, const void* seed) {
const auto lifetime = MG_Pipe::MGPipeWatchResidentBuffer(handle.Handle);
Uint64 base = 0;
Uint64 returned = 0;
Int32 status = Wire::ReplySink::kStatusError;
@@ -3102,7 +3097,10 @@ namespace MobileGL::MG_Remote::Client {
"in-process T0 store without the store's address");
}
void* ptr = reinterpret_cast<void*>(static_cast<std::uintptr_t>(base));
if (seed != nullptr) std::memcpy(ptr, seed, static_cast<SizeT>(size));
if (!MG_Pipe::MGPipeSeedResidentBuffer(*lifetime, ptr, seed, static_cast<SizeT>(size))) {
++m_t0Declined;
return nullptr;
}
++m_t0Imported;
m_t0Bytes += size;
// No AHardwareBuffer to hold: the entry only marks the handle T0 (its release is a no-op).
Loaded 100 of 211 files, more files were not shown because too many files have changed in this diff. Show more