Skip to main content

Texture

Struct Texture 

Source
pub struct Texture { /* private fields */ }
Expand description

Format-agnostic GPU texture container

Texture is the central interchange object used by every format-specific parser and writer in the library. It owns a contiguous pixel-data buffer and a mip chain describing the layout of every mip level and layer.

Use the static factory methods (create2D, create3D, createCube) to allocate a new texture, or obtain one from a parser.

Supports in-place and copying format conversion between all PixelFormat values (uncompressed ↔ BCn) via format() and copyAsFormat().

Uses the PImpl (Pointer to Implementation) idiom to hide internals.

Implementations§

Source§

impl Texture

Source

pub fn new() -> Self

§Panics

Panics if the native allocation fails.

Source

pub fn convert_to(&mut self, new_fmt: PixelFormat)

Convert this texture to a new pixel format in-place.

Replaces the internal data with the converted result. Equivalent to *this = copyAsFormat(new_fmt).

@param new_fmt Target pixel format.

Source

pub fn format(&self) -> PixelFormat

@return The pixel format of the stored data.

Source

pub fn copy_as_format( &self, new_fmt: PixelFormat, pool: Option<&HostWorkerPool>, ) -> Option<Texture>

Return a copy of this texture converted to a different pixel format.

Conversion path: - Same format → plain copy. - BCn → decoded to native format (R8 for BC4, RG8 for BC5, RGBA32F for BC6H, RGBA8 for others), then recurse. - Uncompressed → uncompressed → per-pixel conversion. - Uncompressed → BCn → encode via the appropriate codec.

@param new_fmt Target pixel format. @param pool Optional WorkerPool for parallel BCn encode/decode work. Ignored for purely uncompressed-to-uncompressed conversions. @return A new Texture with the converted data.

Source

pub fn swap_channels(&mut self, a: Channel, b: Channel) -> bool

Swap two channels in-place across all mip levels and array layers.

Operates directly on the stored pixel data without any intermediate copy. Supports all uncompressed PixelFormats (R*, RG*, RGBA*).

Failure conditions (returns false): - The texture uses a BCn block-compressed format. - Either channel is not present in the current pixel format (e.g. Channel::B on an RG8 texture).

@param a First channel to swap. @param b Second channel to swap. @return true on success (including when @p a == @p b, which is a no-op), false when the operation is not valid for this texture.

Source

pub fn invert_channel(&mut self, ch: Channel) -> bool

Invert a single channel in-place across all mip levels and array layers.

Each sample value @c v is replaced with @c max_value - v, where @c max_value is the maximum representable value for the channel’s underlying type (255 for u8, 65535 for u16, 1.0 for f32).

Operates directly on the stored pixel data without any intermediate copy. Supports all uncompressed PixelFormats (R*, RG*, RGBA*).

Failure conditions (returns false): - The texture uses a BCn block-compressed format. - The requested channel is not present in the current pixel format (e.g. Channel::B on an RG8 texture).

@param ch Channel to invert. @return true on success, false when the operation is not valid for this texture.

Source

pub fn expand_normal( &mut self, x_channel: Channel, y_channel: Channel, z_channel: Channel, ) -> bool

Reconstruct the Z component of a tangent-space normal map in-place.

Interprets channels @p a and @p b as the packed X and Y components of a unit normal vector, computes Z = sqrt(max(0, 1 - x² - y²)), and writes the result back to channel @p c.

Channel values are decoded from the UNORM [0, 1] storage convention to the signed [-1, 1] range before the computation (i.e. x = 2v - 1), and the reconstructed Z is re-encoded as (z + 1) / 2 before being written. This matches the encoding used by all other normal-map utilities in the library.

Operates directly on the stored pixel data without any intermediate copy. Supports all uncompressed PixelFormats (R*, RG*, RGBA*).

Failure conditions (returns false): - The texture uses a BCn block-compressed format. - Any of the three channel indices is not present in the current pixel format (e.g. Channel::B on an RG8 texture).

@param xChannel Channel storing the packed X component (source, read-only). @param yChannel Channel storing the packed Y component (source, read-only). @param zChannel Channel to receive the reconstructed Z component (write target). @return true on success, false when the operation is not valid for this texture.

Source

pub fn fill_channel(&mut self, target: Channel, value: f32) -> bool

Fill a single channel with a constant value across all mip levels and array layers.

The floating-point value is quantised to the channel’s underlying type (clamped to [0, 255] for u8, [0, 65535] for u16, stored directly for f32).

Returns false for BCn formats or if the channel index exceeds the format’s channel count.

@param target Channel to fill. @param value Value to write (interpreted as [0, 1] for integer formats). @return true on success, false when the operation is not valid.

Source

pub fn split_channels(&self, channels: &[Channel]) -> Option<TextureList>

Split selected channels into individual single-channel textures.

Each requested channel produces a separate Texture with a single-channel format matching the source bit depth (R8, R16, or R32F). All mip levels and layers are copied. The returned textures inherit the source’s sRGB flag but their kind is set to TextureKind::Other.

Returns std::nullopt if the source is BCn-compressed or if any requested channel index exceeds the source channel count.

@param channels Channels to extract (e.g. {Channel::R, Channel::G}). @return One Texture per requested channel, or std::nullopt on failure.

Source

pub fn merge_channels( sources: &[&Texture], target_channels: &[Channel], ) -> Option<Texture>

Merge single-channel textures into one multi-channel texture.

Each source texture is written into the corresponding target channel of a new RGBA-width texture whose bit depth matches the sources (RGBA8, RGBA16, or RGBA32F). All sources must share the same format, dimensions, mip count, and texture type. Channels not covered by the input list are zero-filled.

@param sources Single-channel textures to combine. @param targetChannels Destination channel for each source (same length as @p sources). @return The combined RGBA texture, or std::nullopt on failure.

Source

pub fn copy_from_normal_to_rgba( &self, pool: Option<&HostWorkerPool>, ) -> Option<Texture>

Return a copy of a 2-channel normal map expanded to RGBA8.

Only supported for textures whose kind() is TextureKind::Normal and whose format is RG8, RG16, RG32F, or BC5. The returned texture keeps the original shape, mip chain, kind, and sRGB flag, but stores data as RGBA8 with Z reconstructed from the packed X/Y normal in R/G.

@param pool Optional WorkerPool for parallel BCn decode work when the source texture is compressed. @return Expanded RGBA8 texture, or std::nullopt when unsupported.

Source

pub fn generate_mipmaps( &mut self, new_mip_count: u32, pool: Option<&HostWorkerPool>, ) -> Option<String>

Generate all mip levels from the base image (mip 0).

Every mip level is generated directly from the original full-resolution image using an appropriately-sized filter kernel, rather than cascading from the previous mip level. This eliminates cumulative blur.

Selects the best filter and pipeline for the texture’s kind(): - Diffuse / Albedo — Lanczos3; sRGB linearize/delinearize when isSrgb() is true. - Normal — Kaiser(β=6) with unpack / Toksvig / renormalize / pack. - Specular — Kaiser(β=6); sRGB linearize/delinearize when isSrgb(). - Roughness — Kaiser(β=6.5) variance-preserving: r→r², filter, √. - Gloss — convert to roughness, apply variance filter, convert back. - Metalness — Kaiser(β=5.5) mean filtering. - AmbientOcclusion — Kaiser(β=6) mean filtering. - Emissive — Lanczos3; sRGB linearize/delinearize when isSrgb(). - ORM (deprecated) — same as Multikind with R=AO/G=Roughness/B=Metalness. - Multikind — per-channel kind-appropriate pipeline; each channel’s kind is queried via channelKind(). Unused channels use a box filter. - AlphaMask — Box filter; no sRGB conversion (linear mask data). - Lightmap — Lanczos3; clamp channels to [0, ∞) (no sRGB). - EnvironmentPBR — GGX importance-sampled convolution (equirectangular); roughness increases with each mip level. - EnvironmentLegacy — Solid-angle-weighted spherical Kaiser convolution (equirectangular); no roughness encoding. - Other — Box filter; sRGB linearize/delinearize when isSrgb().

The texture must use an uncompressed pixel format. BCn textures should be decompressed first. No-op if the texture has ≤ 1 mip.

@param newMipCount Desired number of mip levels in the output texture. Pass kKeepMipCount (0) to preserve the existing mip count. Must be between 1 and computeMaxMipCount(width, height, depth). When 1, the mip chain is truncated to the base level only and the function returns immediately. @param pool Optional WorkerPool used to parallelize mip generation across mip levels and layers. If null, generation runs on the calling thread. @return std::nullopt on success; std::optional<std::string> with error message on failure. No exceptions are thrown.

Source

pub fn generate_mipmaps_default( &mut self, pool: Option<&HostWorkerPool>, ) -> Option<String>

@overload Preserves existing mip count; optional worker pool.

Source

pub fn downscale( &mut self, levels: u32, pool: Option<&HostWorkerPool>, ) -> Option<String>

Downscale the texture by dropping leading mip levels.

Increases the mip count by @p levels (clamped to the maximum), regenerates all mip levels from the base image, then drops the first @p levels mips — effectively halving the resolution @p levels times while preserving the original mip chain length.

The texture must use an uncompressed pixel format (same requirement as generateMipmaps). Returns an error if @p levels would reduce every dimension to zero.

@param levels Number of mip levels to drop (default 1). @param pool Optional WorkerPool for parallel mip generation. @return std::nullopt on success; error message on failure.

Source

pub fn create_2d( fmt: PixelFormat, width: u32, height: u32, mip_count: u32, ) -> Option<Texture>

Create a 2D texture. @param fmt Pixel format. @param width Width in pixels. @param height Height in pixels. @param mipCount Number of mip levels (0 = auto-compute full chain). @return A zero-filled Texture with the requested layout.

Source

pub fn create_3d( fmt: PixelFormat, width: u32, height: u32, depth: u32, mip_count: u32, ) -> Option<Texture>

Create a 3D (volume) texture. @param fmt Pixel format. @param width Width in pixels. @param height Height in pixels. @param depth Depth in slices. @param mipCount Number of mip levels (0 = auto-compute full chain). @return A zero-filled Texture with the requested layout.

Source

pub fn create_cube( fmt: PixelFormat, size: u32, mip_count: u32, ) -> Option<Texture>

Create a cube-map texture. @param fmt Pixel format. @param size Face edge length in pixels (faces are square). @param mipCount Number of mip levels (0 = auto-compute full chain). @return A zero-filled Texture with 6 layers.

Source

pub fn create_2d_array( fmt: PixelFormat, width: u32, height: u32, array_size: u32, mip_count: u32, ) -> Option<Texture>

Create a 2D texture array. @param fmt Pixel format. @param width Width in pixels. @param height Height in pixels. @param arraySize Number of array slices (must be ≥ 1). @param mipCount Number of mip levels (0 = auto-compute full chain). @return A zero-filled Texture with @p arraySize layers.

Source

pub fn create_cube_array( fmt: PixelFormat, size: u32, array_size: u32, mip_count: u32, ) -> Option<Texture>

Create a cube-map texture array. @param fmt Pixel format. @param size Face edge length in pixels (faces are square). @param arraySize Number of cube-map entries in the array (must be ≥ 1). The final layer count is 6 × @p arraySize. @param mipCount Number of mip levels (0 = auto-compute full chain). @return A zero-filled Texture with 6 × arraySize layers.

Source

pub fn texture_type(&self) -> TextureType

@return The texture dimensionality / topology.

Source

pub fn kind(&self) -> TextureKind

@return The semantic kind of this texture.

Source

pub fn set_kind(&mut self, k: TextureKind)

Set the semantic kind of this texture. @note TextureKind::Unused is not valid as a top-level kind; use setChannelKind() on a Multikind texture for per-channel Unused.

Source

pub fn channel_kind(&self, ch: Channel) -> TextureKind

@return The per-channel kind for channel @p ch.

Only meaningful when kind() == TextureKind::Multikind. Returns TextureKind::Other by default for all other kinds. @param ch Channel to query (R/G/B/A).

Source

pub fn set_channel_kind(&mut self, ch: Channel, kind: TextureKind)

Set the per-channel kind for channel @p ch.

Only meaningful when kind() == TextureKind::Multikind. TextureKind::Unused is permitted here to mark a channel as unused. @param ch Channel to configure. @param kind Kind to assign, including TextureKind::Unused.

Source

pub fn channel_default(&self, ch: Channel) -> f32

@return The default fill value for channel @p ch.

This value is used by consumers (e.g. channel merging, material baking) when the channel carries no source data. Defaults to 1.0f for all channels. @param ch Channel to query (R/G/B/A).

Source

pub fn set_channel_default(&mut self, ch: Channel, value: f32)

Set the default fill value for channel @p ch.

The value is stored as-is (normalised [0, 1] float for integer formats, linear scale for f32 formats). No clamping is applied at storage time. @param ch Channel to configure (R/G/B/A). @param value Default fill value; 1.0f by convention.

Source

pub fn is_srgb(&self) -> bool

@return True if the texture data is in sRGB colour space.

Source

pub fn set_srgb(&mut self, srgb: bool)

Mark the texture as sRGB or linear.

Source

pub fn width(&self) -> u32

@return Base mip width in pixels.

Source

pub fn height(&self) -> u32

@return Base mip height in pixels.

Source

pub fn depth(&self) -> u32

@return Base mip depth (1 for 2D / cube textures).

Source

pub fn layer_count(&self) -> u32

@return Number of array layers. - Texture2D / Texture3D: 1. - TextureCube: 6. - Texture2DArray: arraySize(). - TextureCubeArray: 6 × arraySize().

Source

pub fn array_size(&self) -> u32

@return Number of array slices (1 for non-array textures). For a TextureCubeArray, this is the number of cube-maps in the array (the layer count is 6 × this value).

Source

pub fn mip_count(&self) -> u32

@return Number of mip levels per layer.

Source

pub fn mip_level(&self, mip: u32, layer: u32) -> Option<MipLevel>

Get the mip-level descriptor for a given mip index and layer. @param mip Mip level index (0 = base). @param layer Array layer index (0 for 2D / 3D textures). @return Reference to the MipLevel struct.

Source

pub fn data_size(&self) -> u64

@return Total byte size of the pixel-data buffer.

Source

pub fn data(&self) -> BorrowedSlice<'_>

@return Read-only span over the entire pixel-data buffer.

Source

pub fn mip_data(&self, mip: u32, layer: u32) -> BorrowedSlice<'_>

Get a read-only span for a specific mip / layer. @param mip Mip level index. @param layer Array layer (default 0).

Source

pub fn take_data(&mut self) -> Bytes

Move the data vector out of the texture (destructive).

After this call the texture’s dimensions and mip chain are cleared. @return The owned pixel-data buffer.

Source

pub fn set_data(&mut self, new_data: &[u8])

Replace the pixel-data buffer.

The new buffer must match the existing allocation size. @param new_data Replacement data.

Source§

impl Texture

Source

pub fn data_mut(&mut self) -> &mut [u8]

Mutable, zero-copy view of the underlying buffer.

Writes land directly in the C++ allocation — nothing is marshalled. The borrow of self is what makes that safe: the buffer cannot be resized or freed while this slice exists.

Source

pub fn mip_data_mut(&mut self, mip: u32, layer: u32) -> &mut [u8]

Mutable, zero-copy view of the underlying buffer.

Writes land directly in the C++ allocation — nothing is marshalled. The borrow of self is what makes that safe: the buffer cannot be resized or freed while this slice exists.

Trait Implementations§

Source§

impl Debug for Texture

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Texture

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl Drop for Texture

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

fn pin_drop(self: Pin<&mut Self>)

🔬This is a nightly-only experimental API. (pin_ergonomics)
Execute the destructor for this type, but different to Drop::drop, it requires self to be pinned. Read more
Source§

impl Send for Texture

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.