2336 Commits

Author SHA1 Message Date
Ben Doherty
533294de9a Add support for custom outputs for unlit surface materials (#9912) 2026-04-20 11:46:21 -04:00
Ben Doherty
4787e341d6 Add feature level when outputting raw shaders (#9911) 2026-04-17 13:32:45 -04:00
Mathias Agopian
3a78c78e7c gltfio: Continue if floatsCount is 0 in ResourceLoader.cpp
Address feedback from PR #9896 to avoid zero-sized allocations and potential
out-of-bounds reads.
2026-04-16 09:10:08 -07:00
Mathias Agopian
8bfdc60d68 imageio: Fix vulnerabilities in PSDDecoder from PR #9881
- PSDDecoder: Add dimension limits (max 30,000) to prevent integer
  overflows during LinearImage allocation.
- Add checks for stream failure during pixel decoding to handle truncated
  files safely.
- Follow existing pattern in this file by using std::runtime_error for
  these checks, which are caught and handled by resetting the stream and
  returning an empty image.
- Add comment that LinearImage allocation cannot overflow with the new
  limits.
2026-04-16 09:10:08 -07:00
Mathias Agopian
f8f2280ee3 filaflat, image: Fix vulnerabilities from PR #9879 without aborts
- MaterialChunk: Return false in getTextShader when shaderSize is 0 to
  prevent out-of-bounds write of null terminator.
- Ktx1Bundle: In 3-argument constructor, check if total blobs calculation
  overflows uint32_t.
- Instead of aborting with FILAMENT_CHECK_POSTCONDITION, log a warning and
  set the object to a safe empty state (dimensions set to 0).
2026-04-16 09:10:08 -07:00
Mathias Agopian
e6e7c0325e uberz: Fix vulnerabilities in convertOffsetsToPointers without aborts
- Implement fixes inspired by PR #9853 to make convertOffsetsToPointers
  size-aware and prevent OOB reads and writes.
- Change function signature to return bool instead of void, allowing graceful
  error propagation instead of runtime aborts.
- Replace FILAMENT_CHECK_PRECONDITION with explicit checks that log errors
  and return false.
- Update ArchiveCache in gltfio and main in tools/uberz to handle failure.
- Add unit tests to verify rejection of invalid offsets.
2026-04-16 09:10:08 -07:00
Mathias Agopian
8d16ad8882 gltfio: Fix vulnerabilities in ResourceLoader.cpp
- Implement PR #9878 to add bounds checking in normalizeSkinningWeights,
  preventing heap OOB write by clamping the count to available buffer size.
- Fix 3 similar vulnerabilities in uploadBuffers where accessor->count was
  trusted for malloc allocation before cgltf_accessor_unpack_floats.
- Add overflow checks for allocation sizes in uploadBuffers.
- Clamp accessor count based on available buffer bytes in uploadBuffers to
  prevent OOB read.
2026-04-16 09:10:08 -07:00
Mathias Agopian
a943b57c86 ktxreader: Fix vulnerabilities and memory leaks in Ktx2Reader.cpp
- Implement PR #9842 to fix integer overflows in transcodeImageLevel.
- Fix potential division by zero in transcodeImageLevel if bytesPerPix is 0.
- Fix memory leaks in transcodeImageLevel by freeing allocated buffers on
  failure.
- Fix memory leak in Ktx2Reader::load by deleting PixelBufferDescriptor after
  use.
2026-04-16 09:10:08 -07:00
Mathias Agopian
ffa2886493 gltfio: Fix security and memory corruption issues in Utility.cpp
- Fix potential division by zero in decodeMeshoptCompression when stride is 0.
- Fix ignored errors in release builds for meshopt decoding by returning bool
  and checking the result in ResourceLoader.cpp.
- Fix potential integer underflow in computeBindingSize when count is 0 by
  returning 0.
- Update ResourceLoader.cpp to skip buffer upload when computeBindingSize
  returns 0, preventing potential OOM or OOB reads.
2026-04-16 09:10:08 -07:00
Mathias Agopian
415ba57272 Correctly filter out ESSL1 variants
This fixes a recent breakage of the SSR variant while reducing the
size of featureLevel 0 materials.
2026-04-16 09:08:44 -07:00
Mathias Agopian
eb3d592d18 expose EntityManager::getIndex() publicly
This can be needed for interactions with an outside entity system.
Use with caution.
2026-04-15 09:19:00 -07:00
Mathias Agopian
8ec732dadc FL0 materials are always compile via spirv-cross 2026-04-13 20:53:35 -07:00
Mathias Agopian
84dc1b1c43 Add custom color grading LUT support and test UI in gltf_viewer.
Implemented the custom 3D LUT feature in the ColorGrading API, allowing
users to specify a custom LUT for final color mapping.

To test this feature, added a "Custom LUT" option to the color grading
settings in the gltf_viewer sample. This includes several procedurally
generated LUTs for testing purposes:
- Negative
- Grayscale
- Sepia
- Teal and Orange

Updated settings serialization (Settings.cpp) and the viewer UI
(ViewerGui.cpp) to support these options.

FIXES=[362596936]
2026-04-13 13:40:23 -07:00
Jocelin Cailloux
115c2cf8fe Add missing #include <cstring> and <optional> (#9887) 2026-04-10 18:54:05 +00:00
Mathias Agopian
92dc063a8a filaflat: Fix missing bounds checks in MaterialChunk::getTextShader (#9873)
- Added a bounds check in the DICTIONARY_NUMERIC_FLAG case to prevent a 
  heap buffer overflow when writing decoded numeric literals.

- Tightened the existing bounds check for dictionary strings to use `>=`
  instead of `>`, preventing a potential off-by-one overflow when 
  writing the null terminator.

- Fixed the `MaterialChunkHeapOverflow` and `MaterialChunkOOBReadText` 
  unit tests in `test_filaflat.cpp` by adding missing header fields to 
  the mock payloads so they correctly pass initialization.

Fixes #9871
2026-04-03 16:02:56 -07:00
Powei Feng
e8fe85ee89 filamat: make DryRunner in Flattener not static (#9872)
This enables multiple thread to use MaterialBuilder/Flattener at
the cost of allocating, deallocating a flattener.
2026-04-03 18:41:50 +00:00
Mathias Agopian
57faae4645 postfx materials now support sRGB emulation in FL0 (#9866)
FIXES=[498317018]
2026-04-02 09:08:50 -07:00
Mathias Agopian
bc0a547701 Support Engine::compile overload to generate view-dependent variants (#9857)
* a new tribool type in libutils (header only)

* Support `Engine::compile` overload to generate view-dependent variants

Implemented an `Engine::compile()` method to infer and generate shader 
permutations directly based on feature states from a provided `View` 
alongside `tribool` settings (skinning, shadowReceiver). 

- Added a new `Material::compile()` overload that directly accepts 
  a precalculated `FixedCapacityVector<Variant>`, decoupling the 
  Material compilation process from specific feature flag checks.

FIXES=[468058969]
2026-04-01 17:08:11 -07:00
Powei Feng
dd1f258a66 settings: add missing renderer options (#9863)
- Move the renderer options to be applied before others before view
   and camera options.
 - Add "render" field to the output of the json description of
   the settings (this was missing).
 - This fixes the Scene->Background Color setting for
   Android's gltf_viewer
2026-04-02 00:04:22 +00:00
Mathias Agopian
16a7047372 Strict bounds validation and parsing optimizations in Ktx1Bundle (#9858)
- Upgraded deserialization precondition checks to fail-fast 
  postconditions.

- Added strict OOB bounds tracking for metadata strings and dynamic 
  payload padding to prevent arbitrary memory corruption
  vulnerabilities.

- Mitigated heap buffer overflows by adding integer boundary constraints
  and dry-running contiguous sizes prior to container allocation.

- Flattened nested layer/face loops via `std::fill_n` and contiguous 
  `memcpy` operations to streamline serialization overhead.

- Updated header documentation explicitly detailing assert 
  circumstances on affected public methods.
2026-03-31 20:26:15 -07:00
Mathias Agopian
face013e86 utils: Enforce geometric resize bounds limits in ostream to prevent massive out-of-bounds heap operations 2026-03-31 11:17:03 -07:00
Mathias Agopian
8f11927aae utils: Truncate oversized CString allocations rather than overflowing internal length logic 2026-03-31 11:17:03 -07:00
Mathias Agopian
2cdff4b521 utils: Protect InternPool references from overflowing to 0 and triggering heap UAF 2026-03-31 11:17:03 -07:00
Mathias Agopian
d1192544ca utils: Protect JobSystem from 8-bit ref-count overflow and UAF cascades 2026-03-31 11:17:03 -07:00
Mathias Agopian
8df899b111 utils: Protect CString routines against integer overflow heap corruption 2026-03-31 11:17:03 -07:00
Mathias Agopian
f8337c42cb utils: Prevent Win32 FindFirstFile handle leaks during exception unwinding in Path::listContents 2026-03-31 11:17:03 -07:00
Mathias Agopian
cb552def6c utils: Enforce format string boundaries to prevent stack injection during Panic events 2026-03-31 11:17:03 -07:00
Mathias Agopian
883f5bae4e utils: Prevent stack buffer leaks by safely trapping snprintf error bounds in Systrace 2026-03-31 11:17:03 -07:00
Mathias Agopian
6713c68791 utils: Enforce 64-bit boundaries and gracefully intercept 0 length in partition_point 2026-03-31 11:17:03 -07:00
Mathias Agopian
bdef97d52c utils: Prevent capacity overflow in StructureOfArrays scaling logic 2026-03-31 11:17:03 -07:00
Mathias Agopian
0016c0808b utils: Fix functional capture move-assignment leaks in Invocable wrappers 2026-03-31 11:17:03 -07:00
Mathias Agopian
c96edc2972 utils: Implement UTILS_MUL_OVERFLOW safely protecting allocators from multiplication overflows 2026-03-31 11:17:03 -07:00
Mathias Agopian
5c5c3b5bb1 utils: Implement generation counter to resolve CyclicBarrier Deadlocks 2026-03-31 11:17:03 -07:00
Mathias Agopian
8ac45bb391 utils: Safely handle NULL pointers returned by dladdr 2026-03-31 11:17:03 -07:00
Mathias Agopian
b351086bc4 utils: Fix integer underflow in generic vector ostream operator 2026-03-31 11:17:03 -07:00
Mathias Agopian
a007b59f39 repair matdbg shader editing (#9854)
The new LineDictionary API requires to call resolve().
2026-03-27 22:08:47 -07:00
Mathias Agopian
04270afb83 gltf_viewer should use a SUN light (#9848)
this matches the desktop version.
2026-03-27 16:06:28 -07:00
Mathias Agopian
f0108247d1 Fix various overflow, truncation, and NEON alignment bugs in bitset.h (#9843)
- Fix constant wrap-around: Define `BIT_COUNT`, `BITS_PER_WORD`, and 
  `WORD_COUNT` (fixed typo from `WORLD_COUNT`) as `size_t` rather than 
  `T` to prevent silent overflows on large bitsets using small integer 
  types.

- Fix NEON `all()` truncation: Remove the generic `T` cast to correctly
  evaluate bounds across the full 64-bit vector lanes.

- Fix non-NEON `count()` overflow: Use a `size_t` accumulator rather 
  than `T` to prevent overflow when counting >255 bits on `uint8_t` 
  parameters.

- Fix NEON strict alignment UB: Enforce unconditional `alignas(16)` on 
  `storage` when `BIT_COUNT` satisfies 128-bit vector multiples, adding 
  a compile-time `static_assert` to ensure ABI expectations match NEON 
  load intrinsics.

- Remove dead masking code inside `firstSetBit()`.
2026-03-27 12:51:40 -07:00
Powei Feng
8a9838706e viewer: update sunlight settings (#9846)
Missing the castShadows=true caused the shadows to be missing
on mobile (using the remote settings page).

Update README.md (this will trigger an update to the remote
page's filament.js)
2026-03-27 19:51:28 +00:00
Mathias Agopian
167a91efaa Optimize Shader LineDictionary (#9814)
* Optimize Shader LineDictionary with Variable-Length 3-Streams

This commit completely reorganizes the string dictionary compression
pipeline used by compiled Material Text Chunks and improves matinfo
dictionary output.

1. Multi-Base Variable-Length Scaling:
We replaced the static 16-bit indices overhead with a
bounded payload. Now, indices scale dynamically:
- 0 to 239 evaluate in 1 byte.
- 240 to 3584 leverage 0xF0-0xFD escapes evaluating in 2 bytes.
- 3584+ are locked behind a 0xFF marker to 3 bytes.
This natively eradicated the massive monolithic lengths and zero-padding
issues previously dominating shader packages.

2. Variable-Length 3-Stream Decoding:
To solve the Zstandard/Zlib entropy fragmentation that conventionally
plagues interleaved variable byte lengths (which previously inflated
our `filament.aar` boundary constraint by +2KB), we segregated the encoded
payloads.

By grouping high-entropy string boundaries into a `Base Stream`
and isolating offset digits inside an `Extension Stream`,
predictive LZ77 ZIP sliding-windows perfectly map
over both arrays independently without disruption.

3. Optimize Numeric Stream using LEB128
Prior to this change, numerical suffixes split from shader
variables (e.g., `param_1024` -> `param_` + `1024`) were fed back
into the localized String Dictionary. Because high-frequency numbers were
assigned disjointed localized IDs per shader variant, LZ77
failed to cross-reference their repetitive structures across
shipped `.aar` archives, fracturing compression sequences.

This patch implements a unified 3-Stream topology. It
extracts numerical primitives (< 32768) away from the baseline
String Dictionary, writing them into an isolated, contiguous
LEB128 array.

By using a dedicated `[254]` Escape Token within the primary stream, numerical
variables maintain exact 1-byte (`< 128`) or 2-byte (`>= 128`)
geometric layouts across all permutations.

The resulting deterministic alignment guarantees that Zlib sliding windows
can deduplicate highly repetitive variables across the
entire application binary block.

4. We use the ShaderStage information to create distinct index ranges, which
further help use 1-byte indices.

Verification Metrics:
 `filament-android.aar`: -7,938 B
 `gltfio-android.aar`: -290,939 B
 `libfilament.a`: -18,464 B

* Optimize shader dictionary by decoding '_' for numeric literals

Most numbers extracted from the shader text are preceded by an 
underscore (e.g., from `_`, `hp_copy_`), which previously caused 
standalone `_` strings to heavily pollute the LineDictionary.

This change removes the standalone `_` from the dictionary index:
- `MaterialChunk` rehydrates the `_` prefix when decoding these numeric
literals.

This frees up dictionary indices, yielding massive byte savings across 
uncompressed binaries (e.g., -28.4 KB for volume_masked.filamat).

* Optimize ShaderMinifier to strip explicit spacing

Spirv-cross outputs GLSL with explicit spacing around generic
operators (e.g., ` = `, `, `, ` ) * `). This padding consumes a 
significant amount of uncompressed bytes across large ubershaders. 

By applying targeted string replacements at the end of the `ShaderMinifier` 
pass, we strip this extraneous padding down to its raw tokens 
(e.g., `a=b`, `a,b`, `a*b`). 

This optimization preserves isolating spaces where valuable, ensuring 
line-dictionary tokens (such as raw `=` or `,`)  remain deduplicated 
instead of fusing into unpredictable variables. 

Impact:
This saves roughly ~9.1 KB in `libfilament.a` and ~3.2 KB in 
`volume_masked.filamat` uncompressed, with proportional gains across 
the downstream LZ4 compressed archives.
2026-03-26 22:41:36 -07:00
Mathias Agopian
ab2ece54d7 Fix memory safety vulnerabilities in filaflat parsing components (#9832)
* Fix out-of-bounds string read by verifying null-terminator existence
  during extraction.
* Fix heap buffer overflow by validating dictionary string lengths 
  against target shader buffers before copying.
* Fix out-of-bounds array reads by validating chunk-provided lookup 
  indices against parsed dictionary sizes.
* Fix integer wrapping exploits by replacing pointer addition with 
  offset subtraction during chunk size verifications.

Add unit tests for these vulerabilities.
2026-03-26 11:19:08 -07:00
Powei Feng
541a4feae1 imgdiff: add positional and frequency robustness parameters (#9822)
- Introduce `shiftRadius` to allow positional tolerances by searching
  a local neighborhood, absorbing sub-pixel shifts and MSAA quirks.
- Introduce `blurRadius` to apply local area averaging, ignoring
  high-frequency noise like hardware dithering.
- Enhance `ImageDiffResult` to include an `averageError` array and
  a 10-bin `errorHistogram` for actionable failure debugging.
- Update Android JNI bindings (`ImageDiff.java` and `ImageDiff.cpp`)
  to propagate the new error distribution statistics to Java callers.
- Update C++ unit tests to cover the new heuristic options.
- Document the new parameters and JSON result format in README.md.
- Add synthetic image generation tests in `tools/diffimg/tests/` to
  validate the CLI tool's handling of spatial shifts and dithering.
2026-03-25 00:31:18 +00:00
Moomba
e22588c4e1 Mark provider creator methods as public in TextureProvider.h (#9819) 2026-03-24 23:13:08 +00:00
Powei Feng
a102daed53 Update MATERIAL_VERSION to 70 2026-03-23 15:20:26 -07:00
Patrick Ribas
20aa91edc9 remove sunDisk in skybox at FL0 (#9675) 2026-03-20 10:54:43 -07:00
Mathias Agopian
052092f553 remove the remaining instances of std::string (#9802)
libfilament (including libutils and libmath) are 100% std::string
free.

std::string is pulled in the .so (on android) through libc++ for 
exception handling, even if we're not using them. There is not much
we can do here, but at least, it's not because of us!

utils::ostream still references it but only as an inline function,
so if the inline is not called, std::string won't be pulled in.

It's also referenced from Path.cpp, but that's not included in
libfilament.
2026-03-17 15:27:12 -07:00
Mathias Agopian
7163aaa627 don't output the full shader when matc fails (#9803)
This made it nearly impossible to find the actual error. Now, we
output only the error from the compiler + the material name, variant
and shader stage all in one line.
2026-03-17 13:37:14 -07:00
Mathias Agopian
0c7ff3fcf4 store shadow atlas resolution in frameUniforms (#9804) 2026-03-17 13:36:58 -07:00
Powei Feng
749b03ed2a utils: refactor getopt into utils namespace (#9796)
On certain linux, macOS environment, there is already a system
getopt. This often creates conflict when compiling filament.
Here we alias utils::getopt to either the system getopt (if
present) or third_party/getopt.

Fixes #7551
2026-03-13 17:22:44 -07:00
Mathias Agopian
fd9bcaa735 Fix heap buffer overflow in HDRDecoder RLE decoding (Issue #9748) (#9777)
This commit addresses a critical security vulnerability (OOB write) and 
several stability issues in the Radiance HDR parser.

Primary Fix:
* Fixed a heap buffer overflow in the RLE decoding loop (Issue #9748). 
  The decoder previously failed to verify if a run-length chunk exceeded 
  the remaining space in the scanline buffer. Added strict bounds checking 
  (`num_bytes + run_length > width`) before executing `memset` or 
  `mStream.read` to prevent arbitrary memory corruption.

Additional Security & Stability Improvements:
* Prevented an infinite loop (DoS) in header parsing. Replaced the 
  `do { ... } while(true);` loop with proper stream state checking 
  (`while (mStream.getline(...))`) to handle unexpected EOFs gracefully.
* Mitigated integer overflow and Out-Of-Memory (OOM) vulnerabilities by 
  enforcing maximum sane dimensions (`MAX_IMAGE_DIMENSION` and 
  `MAX_IMAGE_PIXELS`). This prevents catastrophic memory allocations 
  triggered by maliciously crafted width/height values.
* Initialized local variables and buffers (`buf`, `gamma`, `exposure`) to 
  prevent undefined behavior and parsing of stack garbage upon stream read 
  failures.

Fixes #9748
2026-03-06 16:35:24 -08:00