Skip to content

perf(loader): decode embedded 2D textures as ImageBitmap on Chromium(生产代码 +45/-7) - #3270

Open
luzhuang wants to merge 1 commit into
dev/2.0from
perf/loader-imagebitmap-texture-upload
Open

luzhuang wants to merge 1 commit into
dev/2.0from
perf/loader-imagebitmap-texture-upload

Conversation

@luzhuang

@luzhuang luzhuang commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Decodes embedded 2D textures directly via createImageBitmap on Chromium >= 112 instead of round-tripping through HTMLImageElement and blob object URLs (split out from #3266 as an independent, non-breaking PR).

Summary

  • Added ImageDecoder._withTextureSource in packages/loader/src/ImageDecoder.ts:
    • On Chromium >= 112 (createImageBitmap with imageOrientation: "from-image", premultiplyAlpha: "none", colorSpaceConversion: "default"), decodes the typed blob to an ImageBitmap, runs the synchronous upload callback, and closes the bitmap in finally.
    • Falls back to HTMLImageElement (ImageDecoder._decodeElement) if createImageBitmap rejects or on non-Chromium browsers (avoiding WebKit translucent RGB rounding differences).
  • Updated GLTFTextureParser._parseTexture, GLTFContentRestorer.restoreContent, and Texture2DDecoder.decode to upload via ImageDecoder._withTextureSource.
  • Added regression tests in tests/src/loader/ImageDecoder.test.ts verifying bitmap decode/disposal, translucent pixel parity with element decode, and fallback behavior.

Benchmark & Parity Measurements

Measured on a real multi-GLB scene (405 runtime assets, 179 image textures / 235 texSubImage2D calls per startup, 178 images decoded via ImageBitmap, desktop macOS Chromium, identical runtime asset hash 8a67b006...).

Shipped-Code A/B Retest (4 interleaved runs per arm after warmup)

Baseline (HTMLImageElement) vs. candidate (b70511175 + 0587fd6b4, cherry-picked directly into this PR):

Metric (in-iframe Engine startup) Before (HTMLImageElement, 0 bitmaps) After (ImageBitmap, 178 bitmaps) Delta
Sync texSubImage2D sum (235 calls, median) 1,686 ms (1769 / 1670 / 1683 / 1689) 614.5 ms (568 / 661 / 561 / 671) -1,071.5 ms (-63.6%)
Scene load (WebGLEngine.create → scene ready, median) 3,859 ms (3539 / 5144 / 4088 / 3630) 2,769 ms (2515 / 2968 / 2570 / 3111) -1,090 ms (-28.2%)

(In this paired retest, the Editor host also switched preview-prep shader caching in galacean/editor#4776, which only affects pre-iframe preparation; the table above isolates in-iframe Engine metrics. Note that texSubImage2D overlaps with concurrent asset loads.)

Isolated Engine-Only 3-Way Comparison (same Editor, 2 interleaved runs per arm)

Upload Path ImageBitmap / decode() count Sync texSubImage2D sum Scene load
HTMLImageElement (baseline) 0 1,869 / 1,980 ms 5,226 / 4,352 ms
HTMLImageElement.decode() (rejected) 178 3,544 / 4,357 ms 6,002 / 7,088 ms
ImageBitmap (this PR) 178 1,179 / 720 ms 3,630 / 3,679 ms

Pixel, Color-Profile & EXIF Parity

  • Real-scene GPU readback (179 startup textures, 178 via ImageBitmap): 179/179 base-level textures matched by resource, dimensions, format, and chunked SHA-256 with 0 WebGL errors.
  • Color profiles & EXIF orientation (Chromium): untagged, Display P3, and Adobe RGB PNGs (transparent, low-alpha, translucent) plus EXIF orientation 6 JPEG produced byte-for-byte identical WebGL readPixels output and dimensions between HTMLImageElement and ImageBitmap (from-image, premultiplyAlpha: "none", colorSpaceConversion: "default").
  • Alpha 0–255 sweep (Chromium 140, WebGL2): byte-for-byte identical readback across all 256 alpha levels.
  • Desktop WebKit translucent check: HTMLImageElement read back [219, 70, 20, 128] vs. ImageBitmap [219, 69, 19, 128], confirming the Chromium-only gate.
  • Scope note: benchmarked on desktop macOS Chromium and desktop WebKit; mobile devices and mini-game runtimes were not benchmarked separately.

Browser Gating Rationale & Ecosystem Survey

Why Chromium >= 112 UA Gating Instead of Feature / Runtime Probes

  • Pure feature checks (typeof createImageBitmap === "function") are insufficient:
    • They cannot detect support for imageOrientation: "from-image" (added in Chrome 112 / Firefox 111 / Safari 16 per MDN BCD; older Chromium throws TypeError, as seen in CesiumJS #12846).
    • They cannot catch WebKit's translucent premultiplyAlpha: "none" RGB rounding difference or Firefox's slower ImageBitmap decode path.
  • Runtime async pixel probes have worse trade-offs:
    • A 2D-canvas getImageData probe (like CesiumJS Resource.supportsImageBitmapOptions) still cannot verify WebGL non-premultiplied upload parity.
    • A WebGL Texture + RenderTarget + readPixels probe couples ImageDecoder to a live graphics device, adds startup overhead, and races with early asset loads (PlayCanvas tried this in img-alpha-test.js and explicitly removed it in playcanvas/engine#5235 after finding Safari rounded/slowed alpha PNGs and Firefox was slower than <img>).
  • navigator.userAgent vs. navigator.userAgentData: userAgentData is Secure-Context-only (https/localhost) and unavailable on local http dev hosts or some embedded WebViews, whereas Chromium's UA Reduction preserves the major version in navigator.userAgent (Chrome/<major>.0.0.0).

Cross-Engine Comparison

Engine Gating Strategy Options & Scope
PlayCanvas !isSafari && typeof ImageBitmap !== 'undefined' (WebGL; includes Chrome & Firefox) { premultiplyAlpha: 'none', colorSpaceConversion: 'none' } (no imageOrientation); applies to all 2D textures (img.js)
Three.js (GLTFLoader) Enables ImageBitmapLoader except Safari < 17, Firefox < 98, or missing createImageBitmap { colorSpaceConversion: 'none', premultiplyAlpha: 'none' } (opened Safari >= 17 in mrdoob/three.js#28560 primarily to fix Web Worker texture loading)
CesiumJS Async 2D-canvas 1×1 ICC PNG probe (Resource.supportsImageBitmapOptions) Reverted 'from-image' back to 'flipY'/'none' after Chrome < 112 TypeError (#12846)
Babylon.js Backend feature flag (forceBitmapOverHTMLImageElement) WebGL2 stays on HTMLImageElement; createImageBitmap used for WebGPU (fileTools.pure.ts, #18924)
Galacean (this PR) Conservative allowlist: Chromium >= 112 Embedded 2D textures only, with { imageOrientation: "from-image", premultiplyAlpha: "none", colorSpaceConversion: "default" } for exact <img> parity

Mobile & Runtime Coverage

  • Android (enabled on most modern devices): Android Chrome 112+, Android Edge 112+, Android System WebView 112+ (wv + Chrome/<ver>), HarmonyOS NEXT ArkWeb (Chrome/114+), and major in-app WebViews (e.g. WeChat XWeb / Alipay containers) with Blink >= 112 hit createImageBitmap. Older < 112 WebViews, stripped custom UAs, Android Firefox, and mini-game runtimes without createImageBitmap(blob) safely fall back to _decodeElement.
  • iOS / iPadOS (excluded by design): All iOS browsers and WebViews (Safari, CriOS/, EdgiOS/, in-app containers) run on WebKit and do not contain Chrome//Chromium/, keeping them on HTMLImageElement (avoiding WebKit translucent RGB rounding and preserving the iOS rAF object-URL release guard).
  • Future follow-up: Standalone URL 2D textures (TextureLoader) and TextureCubeDecoder remain on HTMLImageElement in this PR and can be evaluated separately.

Verification

  • pnpm build (b:module + b:types + validate:engine-knowledge) passed.
  • eslint (0 errors) and prettier --check passed on the 4 changed loader source files.
  • pnpm vitest run tests/src/loader/ImageDecoder.test.ts tests/src/loader/GLTFLoader.test.ts: 2 files, 24 tests passed (Chromium).

Summary by CodeRabbit

  • Bug Fixes
    • Improved loading and restoration of textures in glTF assets and serialized content, helping preserve image appearance, including transparency.
    • Improved compatibility with browser image-decoding behavior, with a fallback when bitmap decoding is unavailable or fails.

@coderabbitai

coderabbitai Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

Texture decoding now uses a shared callback-based path. On supported Chromium versions, it uses createImageBitmap and falls back to image-element decoding if bitmap creation rejects. glTF parsing, Texture2D decoding, and texture restoration use this path.

Changes

Texture Image Decoding

Layer / File(s) Summary
Bitmap decoding and fallback
packages/loader/src/ImageDecoder.ts, tests/src/loader/ImageDecoder.test.ts
ImageDecoder uses createImageBitmap on Chromium version 112 or later, closes the bitmap after upload, and falls back to image-element decoding if bitmap creation rejects. Blob creation is shared, and decode errors report the blob size. Tests use fixed WebP bytes and check bitmap handling, fallback decoding, and pixel values.
Texture caller integration
packages/loader/src/gltf/parser/GLTFTextureParser.ts, packages/loader/src/resource-deserialize/resources/texture2D/Texture2DDecoder.ts, packages/loader/src/GLTFContentRestorer.ts, tests/src/loader/ImageDecoder.test.ts
glTF buffer-view parsing, non-HDR Texture2D decoding, and non-KTX2 texture restoration use _withTextureSource. Tests check GLB texture pixels before and after resource restoration.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Refactor

Sequence Diagram(s)

sequenceDiagram
  participant GLTFTextureParser
  participant ImageDecoder
  participant createImageBitmap
  participant HTMLImageElement
  GLTFTextureParser->>ImageDecoder: _withTextureSource with image data and MIME type
  ImageDecoder->>createImageBitmap: Decode with bitmap options
  createImageBitmap-->>ImageDecoder: Bitmap or rejection
  ImageDecoder->>ImageDecoder: Upload bitmap and close it
  ImageDecoder->>HTMLImageElement: Decode image if bitmap creation rejects
Loading

Possibly related PRs

  • galacean/engine#3266: Changes the same embedded glTF image and binary Texture2D decode path, including Chromium bitmap decoding and the image-element fallback.

Suggested reviewers: guolei1990, cptbtptpbcptdtptp, zhuxudong

Merge Risk: Minimal · up to e2b66

This change decodes embedded textures through ImageBitmap on newer Chromium and falls back to the image-element path otherwise. No actionable merge-blocking risk was found, and the PR includes tests covering the new decode and fallback behavior.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the main change: embedded 2D textures are decoded as ImageBitmap on Chromium under the perf(loader) scope. The diff matches this, since ImageDecoder adds Chromium 112+ bitmap upload an…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Full details: Title check

Explanation

The title names the main change: embedded 2D textures are decoded as ImageBitmap on Chromium under the perf(loader) scope. The diff matches this, since ImageDecoder adds Chromium 112+ bitmap upload and the three call sites switch to _withTextureSource. The title's trailing '(生产代码 +45/-7)' is a line-count note, which is noise under the title guidance, but it does not change the verdict.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

I’m a rabbit with a pixel to cheer,
Bitmap and fallback both work here.
I nibble a WebP, crisp and bright,
Then check restored pixels look right.
My little paws applaud the decode tonight.

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: a8cd174f-2bb8-4776-870a-c2a9d18bd8a7
Commits

Reviewing files that changed from the base of the PR and between d45e5f4 and e2b668e.

Files selected for processing: 5

  • packages/loader/src/GLTFContentRestorer.ts
  • packages/loader/src/ImageDecoder.ts
  • packages/loader/src/gltf/parser/GLTFTextureParser.ts
  • packages/loader/src/resource-deserialize/resources/texture2D/Texture2DDecoder.ts
  • tests/src/loader/ImageDecoder.test.ts

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 6 remain after this review.

@codecov

codecov Bot commented Nov 25, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.22642% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 89.50%. Comparing base (d45e5f4) to head (e2b668e).

Files with missing lines Patch % Lines
packages/loader/src/ImageDecoder.ts 95.65% 2 Missing ⚠️
Additional details and impacted files
@@           Coverage Diff            @@
##           dev/2.0    #3270   +/-   ##
========================================
  Coverage    89.50%   89.50%           
========================================
  Files          942      942           
  Lines       115593   115639   +46     
  Branches     17928    17935    +7     
========================================
+ Hits        103460   103504   +44     
- Misses       12010    12012    +2     
  Partials       123      123           
Flag Coverage Δ
unittests 89.50% <96.22%> (+<0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant