Skip to content

Add zero-allocation texture encoding support#1

Open
Cosmin-B wants to merge 1 commit intomainfrom
feature/texture-encoding-support
Open

Add zero-allocation texture encoding support#1
Cosmin-B wants to merge 1 commit intomainfrom
feature/texture-encoding-support

Conversation

@Cosmin-B
Copy link
Owner

Summary

This PR adds support for encoding textures to various image formats (PNG, JPG, TGA, EXR) with zero managed memory allocations by exposing Unity's internal encoding methods.

Features Added

  • BlittableArrayWrapper: Wraps Unity's native memory for encoded image data
  • NativeArray-based encoding: Returns NativeArray<byte> for full control over memory lifetime
  • Span-based encoding: Returns Span<byte> for temporary access to encoded data
  • Multiple formats supported: PNG, JPG (with quality), TGA, and EXR (with HDR flags)

Implementation Details

  • Extended UnityExposed with encoding method stubs (EncodeToPNG_Injected, etc.)
  • Created ImageEncodingExtensions with user-friendly extension methods
  • Updated Cecil processor to handle BlittableArrayWrapper conversion between Unity's internal type and our exposed type
  • Added comprehensive test suite (TestTextureEncoding.cs) covering all formats

Performance Benefits

  • Zero allocations: No managed byte[] arrays created during encoding
  • Direct native memory access: Work directly with Unity's encoded data
  • GC pressure reduction: Especially beneficial for frequent encoding operations
  • Job System compatible: NativeArray results can be used in Unity Jobs

Testing

Tested successfully on:

  • Unity Editor (Mono)
  • IL2CPP builds (Development and Release)
  • All supported platforms

Usage Example

// Encode to NativeArray (caller manages lifetime)
using (NativeArray<byte> pngData = texture.EncodeToPNGNative(Allocator.Temp))
{
    // Use encoded data...
}

// Encode to Span (temporary access)
Span<byte> jpgData = texture.EncodeToJPGSpan(quality: 90);

Compatibility

  • Unity 6000.0.31f1+
  • Full IL2CPP support
  • All platforms supported

Closes #[issue_number] (if applicable)

- Implement BlittableArrayWrapper for Unity's native memory handling
- Add encoding methods for PNG, JPG, TGA, and EXR formats
- Provide NativeArray and Span-based APIs to avoid allocations
- Update Cecil processor to handle encoding method IL injection
- Add comprehensive test suite for all encoding formats

This feature enables high-performance texture encoding directly to
NativeArray<byte> or Span<byte>, eliminating managed array allocations
and GC pressure during image export operations.
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