diff --git a/changelog.md b/changelog.md index 12808ac830..33ca2335b9 100644 --- a/changelog.md +++ b/changelog.md @@ -9,6 +9,8 @@ when upgrading from a version of rust-sdl2 to another. [PR #1407](https://github.com/Rust-SDL2/rust-sdl2/pull/1407) Add new use_ios_framework for linking to SDL2.framework on iOS +[PR #1439](https://github.com/Rust-SDL2/rust-sdl2/pull/1439) **BREAKING CHANGE** Implement custom blend modes + ### v0.37.0 [PR #1406](https://github.com/Rust-SDL2/rust-sdl2/pull/1406) Update bindings to SDL 2.0.26, add Event.is\_touch() for mouse events, upgrade wgpu to 0.20 in examples diff --git a/sdl2-sys/sdl_bindings.rs b/sdl2-sys/sdl_bindings.rs index c04ce6e54c..59061c661e 100644 --- a/sdl2-sys/sdl_bindings.rs +++ b/sdl2-sys/sdl_bindings.rs @@ -6030,71 +6030,105 @@ extern "C" { Y2: *mut f32, ) -> SDL_bool; } -#[repr(u32)] -#[doc = " \\brief The blend mode used in SDL_RenderCopy() and drawing operations."] -#[derive(Copy, Clone, Hash, PartialEq, Eq)] -pub enum SDL_BlendMode { - #[doc = "< no blending\ndstRGBA = srcRGBA"] - SDL_BLENDMODE_NONE = 0, - #[doc = "< alpha blending\ndstRGB = (srcRGB * srcA) + (dstRGB * (1-srcA))\ndstA = srcA + (dstA * (1-srcA))"] - SDL_BLENDMODE_BLEND = 1, - #[doc = "< additive blending\ndstRGB = (srcRGB * srcA) + dstRGB\ndstA = dstA"] - SDL_BLENDMODE_ADD = 2, - #[doc = "< color modulate\ndstRGB = srcRGB * dstRGB\ndstA = dstA"] - SDL_BLENDMODE_MOD = 4, - #[doc = "< color multiply\ndstRGB = (srcRGB * dstRGB) + (dstRGB * (1-srcA))\ndstA = (srcA * dstA) + (dstA * (1-srcA))"] - SDL_BLENDMODE_MUL = 8, - SDL_BLENDMODE_INVALID = 2147483647, + +/// The blend mode used in SDL_RenderCopy() and drawing operations. +pub type SDL_BlendMode = u32; + +pub mod blend_modes { + /// no blending + /// + /// `dstRGBA = srcRGBA` + pub const NONE: u32 = 0; + /// alpha blending + /// + /// `dstRGB = (srcRGB * srcA) + (dstRGB * (1-srcA))` + /// + /// `dstA = srcA + (dstA * (1-srcA))` + pub const BLEND: u32 = 1; + /// additive blending + /// + /// `dstRGB = (srcRGB * srcA) + dstRGB` + /// + /// `dstA = dstA` + pub const ADD: u32 = 2; + /// color modulate + /// + /// `dstRGB = srcRGB * dstRGB` + /// + /// `dstA = dstA` + pub const MOD: u32 = 4; + /// color multiply + /// + /// `dstRGB = (srcRGB * dstRGB) + (dstRGB * (1-srcA))` + /// + /// `dstA = (srcA * dstA) + (dstA * (1-srcA))` + pub const MUL: u32 = 8; + pub const INVALID: u32 = 2_147_483_647; } + +/// Used for composing custom blend modes: +/// blend operation used when combining source and destination pixel components. #[repr(u32)] -#[doc = " \\brief The blend operation used when combining source and destination pixel components"] -#[derive(Copy, Clone, Hash, PartialEq, Eq)] -pub enum SDL_BlendOperation { - #[doc = "< dst + src: supported by all renderers"] - SDL_BLENDOPERATION_ADD = 1, - #[doc = "< dst - src : supported by D3D9, D3D11, OpenGL, OpenGLES"] - SDL_BLENDOPERATION_SUBTRACT = 2, - #[doc = "< src - dst : supported by D3D9, D3D11, OpenGL, OpenGLES"] - SDL_BLENDOPERATION_REV_SUBTRACT = 3, - #[doc = "< min(dst, src) : supported by D3D9, D3D11"] - SDL_BLENDOPERATION_MINIMUM = 4, - #[doc = "< max(dst, src) : supported by D3D9, D3D11"] - SDL_BLENDOPERATION_MAXIMUM = 5, +#[derive(Clone,Copy,Eq,PartialEq,Debug,Hash)] +pub enum BlendOp { + /// `dst + src` + /// + /// Supported by all renderers. + Add = 1, + /// `dst - src` + /// + /// Supported by D3D9, D3D11, OpenGL, OpenGLES. + Sub = 2, + /// `src - dst` + /// + /// Supported by D3D9, D3D11, OpenGL, OpenGLES. + RevSub = 3, + /// `min(dst, src)` + /// + /// Supported by D3D11. + Min = 4, + /// `max(dst, src)` + /// + /// Supported by D3D11. + Max = 5, } + +/// Used for composing custom blend modes: +/// normalized factor used to multiply pixel components. #[repr(u32)] -#[doc = " \\brief The normalized factor used to multiply pixel components"] -#[derive(Copy, Clone, Hash, PartialEq, Eq)] -pub enum SDL_BlendFactor { - #[doc = "< 0, 0, 0, 0"] - SDL_BLENDFACTOR_ZERO = 1, - #[doc = "< 1, 1, 1, 1"] - SDL_BLENDFACTOR_ONE = 2, - #[doc = "< srcR, srcG, srcB, srcA"] - SDL_BLENDFACTOR_SRC_COLOR = 3, - #[doc = "< 1-srcR, 1-srcG, 1-srcB, 1-srcA"] - SDL_BLENDFACTOR_ONE_MINUS_SRC_COLOR = 4, - #[doc = "< srcA, srcA, srcA, srcA"] - SDL_BLENDFACTOR_SRC_ALPHA = 5, - #[doc = "< 1-srcA, 1-srcA, 1-srcA, 1-srcA"] - SDL_BLENDFACTOR_ONE_MINUS_SRC_ALPHA = 6, - #[doc = "< dstR, dstG, dstB, dstA"] - SDL_BLENDFACTOR_DST_COLOR = 7, - #[doc = "< 1-dstR, 1-dstG, 1-dstB, 1-dstA"] - SDL_BLENDFACTOR_ONE_MINUS_DST_COLOR = 8, - #[doc = "< dstA, dstA, dstA, dstA"] - SDL_BLENDFACTOR_DST_ALPHA = 9, - #[doc = "< 1-dstA, 1-dstA, 1-dstA, 1-dstA"] - SDL_BLENDFACTOR_ONE_MINUS_DST_ALPHA = 10, +#[derive(Clone,Copy,Eq,PartialEq,Debug,Hash)] +pub enum BlendFactor { + /// `(0, 0, 0, 0)` + Zero = 1, + /// `(1, 1, 1, 1)` + One = 2, + /// `(srcR, srcG, srcB, srcA)` + SrcColor = 3, + /// `(1 - srcR, 1 - srcG, 1 - srcB, 1 - srcA)` + OneMinusSrcColor = 4, + /// `(srcA, srcA, srcA, srcA)` + SrcAlpha = 5, + /// `(1 - srcA, 1 - srcA, 1 - srcA, 1 - srcA)` + OneMinusSrcAlpha = 6, + /// `(dstR, dstG, dstB, dstA)` + DstColor = 7, + /// `(1 - dstR, 1 - dstG, 1 - dstB, 1 - dstA)` + OneMinusDstColor = 8, + /// `(dstA, dstA, dstA, dstA)` + DstAlpha = 9, + /// `(1 - dstA, 1 - dstA, 1 - dstA, 1 - dstA)` + OneMinusDstAlpha = 10, } + extern "C" { #[doc = " Compose a custom blend mode for renderers.\n\n The functions SDL_SetRenderDrawBlendMode and SDL_SetTextureBlendMode accept\n the SDL_BlendMode returned by this function if the renderer supports it.\n\n A blend mode controls how the pixels from a drawing operation (source) get\n combined with the pixels from the render target (destination). First, the\n components of the source and destination pixels get multiplied with their\n blend factors. Then, the blend operation takes the two products and\n calculates the result that will get stored in the render target.\n\n Expressed in pseudocode, it would look like this:\n\n ```c\n dstRGB = colorOperation(srcRGB * srcColorFactor, dstRGB * dstColorFactor);\n dstA = alphaOperation(srcA * srcAlphaFactor, dstA * dstAlphaFactor);\n ```\n\n Where the functions `colorOperation(src, dst)` and `alphaOperation(src,\n dst)` can return one of the following:\n\n - `src + dst`\n - `src - dst`\n - `dst - src`\n - `min(src, dst)`\n - `max(src, dst)`\n\n The red, green, and blue components are always multiplied with the first,\n second, and third components of the SDL_BlendFactor, respectively. The\n fourth component is not used.\n\n The alpha component is always multiplied with the fourth component of the\n SDL_BlendFactor. The other components are not used in the alpha\n calculation.\n\n Support for these blend modes varies for each renderer. To check if a\n specific SDL_BlendMode is supported, create a renderer and pass it to\n either SDL_SetRenderDrawBlendMode or SDL_SetTextureBlendMode. They will\n return with an error if the blend mode is not supported.\n\n This list describes the support of custom blend modes for each renderer in\n SDL 2.0.6. All renderers support the four blend modes listed in the\n SDL_BlendMode enumeration.\n\n - **direct3d**: Supports all operations with all factors. However, some\n factors produce unexpected results with `SDL_BLENDOPERATION_MINIMUM` and\n `SDL_BLENDOPERATION_MAXIMUM`.\n - **direct3d11**: Same as Direct3D 9.\n - **opengl**: Supports the `SDL_BLENDOPERATION_ADD` operation with all\n factors. OpenGL versions 1.1, 1.2, and 1.3 do not work correctly with SDL\n 2.0.6.\n - **opengles**: Supports the `SDL_BLENDOPERATION_ADD` operation with all\n factors. Color and alpha factors need to be the same. OpenGL ES 1\n implementation specific: May also support `SDL_BLENDOPERATION_SUBTRACT`\n and `SDL_BLENDOPERATION_REV_SUBTRACT`. May support color and alpha\n operations being different from each other. May support color and alpha\n factors being different from each other.\n - **opengles2**: Supports the `SDL_BLENDOPERATION_ADD`,\n `SDL_BLENDOPERATION_SUBTRACT`, `SDL_BLENDOPERATION_REV_SUBTRACT`\n operations with all factors.\n - **psp**: No custom blend mode support.\n - **software**: No custom blend mode support.\n\n Some renderers do not provide an alpha component for the default render\n target. The `SDL_BLENDFACTOR_DST_ALPHA` and\n `SDL_BLENDFACTOR_ONE_MINUS_DST_ALPHA` factors do not have an effect in this\n case.\n\n \\param srcColorFactor the SDL_BlendFactor applied to the red, green, and\n blue components of the source pixels\n \\param dstColorFactor the SDL_BlendFactor applied to the red, green, and\n blue components of the destination pixels\n \\param colorOperation the SDL_BlendOperation used to combine the red,\n green, and blue components of the source and\n destination pixels\n \\param srcAlphaFactor the SDL_BlendFactor applied to the alpha component of\n the source pixels\n \\param dstAlphaFactor the SDL_BlendFactor applied to the alpha component of\n the destination pixels\n \\param alphaOperation the SDL_BlendOperation used to combine the alpha\n component of the source and destination pixels\n \\returns an SDL_BlendMode that represents the chosen factors and\n operations.\n\n \\since This function is available since SDL 2.0.6.\n\n \\sa SDL_SetRenderDrawBlendMode\n \\sa SDL_GetRenderDrawBlendMode\n \\sa SDL_SetTextureBlendMode\n \\sa SDL_GetTextureBlendMode"] pub fn SDL_ComposeCustomBlendMode( - srcColorFactor: SDL_BlendFactor, - dstColorFactor: SDL_BlendFactor, - colorOperation: SDL_BlendOperation, - srcAlphaFactor: SDL_BlendFactor, - dstAlphaFactor: SDL_BlendFactor, - alphaOperation: SDL_BlendOperation, + srcColorFactor: BlendFactor, + dstColorFactor: BlendFactor, + colorOperation: BlendOp, + srcAlphaFactor: BlendFactor, + dstAlphaFactor: BlendFactor, + alphaOperation: BlendOp, ) -> SDL_BlendMode; } #[repr(C)] diff --git a/src/sdl2/render.rs b/src/sdl2/render.rs index e18e9a06b6..78506ac3eb 100644 --- a/src/sdl2/render.rs +++ b/src/sdl2/render.rs @@ -1,6 +1,6 @@ //! 2D accelerated rendering //! -//! Official C documentation: https://wiki.libsdl.org/CategoryRender +//! Official C documentation: //! # Introduction //! //! This module contains functions for 2D accelerated rendering. @@ -57,6 +57,9 @@ use crate::sys; use crate::sys::SDL_BlendMode; use crate::sys::SDL_TextureAccess; +pub use sys::BlendFactor; +pub use sys::BlendOp; + /// Contains the description of an error returned by SDL #[derive(Debug, Clone)] pub struct SdlError(String); @@ -129,49 +132,176 @@ pub struct RendererInfo { pub max_texture_height: u32, } +/// The intermediary builder type for composing custom blend modes. +#[derive(Clone, Copy, Eq, PartialEq, Debug)] +pub struct BlendModeBuilder { + src_col: BlendFactor, + dst_col: BlendFactor, + src_alpha: BlendFactor, + dst_alpha: BlendFactor, + col_op: BlendOp, + alpha_op: BlendOp, +} + +impl BlendModeBuilder { + /// Instantiate a new `BlendModeBuilder`. + /// + /// The builder has the same values set on instantiation + /// that would produce the effect equivalent to [`BlendMode::None`] + /// when built and used. + /// + /// However, `BlendModeBuilder` only ever outputs [`BlendMode::Custom`] + /// when built, even if the produced blend mode was functionally + /// identical to any of the predefined blend modes. + /// + /// ``` + /// use sdl2::render::{BlendModeBuilder,BlendMode,BlendFactor,BlendOp}; + /// + /// // The following two are equal + /// // and produce equal results when composed + /// let bmb1 = BlendModeBuilder::new(); + /// let bmb2 = BlendModeBuilder::new() + /// .src_dst_col(BlendFactor::One,BlendFactor::Zero) + /// .src_dst_alpha(BlendFactor::One,BlendFactor::Zero) + /// .col_op(BlendOp::Add) + /// .alpha_op(BlendOp::Add); + /// + /// assert_eq!(bmb1,bmb2); + /// assert_eq!(bmb1.build(),bmb2.build()); + /// ``` + pub fn new() -> BlendModeBuilder { + BlendModeBuilder { + src_col: BlendFactor::One, + dst_col: BlendFactor::Zero, + src_alpha: BlendFactor::One, + dst_alpha: BlendFactor::Zero, + col_op: BlendOp::Add, + alpha_op: BlendOp::Add, + } + } + + /// Set source color and destination color blend factors. + pub fn src_dst_col(mut self, src: BlendFactor, dst: BlendFactor) -> BlendModeBuilder { + self.src_col = src; + self.dst_col = dst; + self + } + + /// Set source alpha and destination alpha blend factors. + pub fn src_dst_alpha(mut self, src: BlendFactor, dst: BlendFactor) -> BlendModeBuilder { + self.src_alpha = src; + self.dst_alpha = dst; + self + } + + /// Set color blend operation. + pub fn col_op(mut self, col: BlendOp) -> BlendModeBuilder { + self.col_op = col; + self + } + + /// Set alpha blend operation. + pub fn alpha_op(mut self, alpha: BlendOp) -> BlendModeBuilder { + self.alpha_op = alpha; + self + } + + /// Compose the custom blend mode. + /// + /// The composed blend mode is always of the enum variant [`BlendMode::Custom`], + /// even if its parameters corresponded to any of the predefined blend modes. + pub fn build(&self) -> BlendMode { + let BlendModeBuilder { + src_col, + dst_col, + src_alpha, + dst_alpha, + col_op, + alpha_op, + } = self; + BlendMode::Custom(BlendValue(unsafe { + sys::SDL_ComposeCustomBlendMode( + *src_col, *dst_col, *col_op, *src_alpha, *dst_alpha, *alpha_op, + ) + })) + } +} + +/// An opaque type to represent bit flags for custom blend modes. +/// +/// Only exists as part of [`BlendMode::Custom`]. +/// Cannot be instantiated separately. +#[derive(Clone, Copy, Eq, PartialEq, Debug, Hash)] +pub struct BlendValue(u32); + /// Blend mode for `Canvas`, `Texture` or `Surface`. -#[repr(i32)] -#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)] +#[derive(Clone, Copy, Eq, PartialEq, Debug, Hash)] pub enum BlendMode { - /// no blending (replace destination with source). - None = SDL_BlendMode::SDL_BLENDMODE_NONE as i32, - /// Alpha blending + /// No blending (replace destination with source): + /// + /// `dstRGBA = srcRGBA` + None, + /// Alpha blending: + /// + /// `dstRGB = (srcRGB * srcA) + (dstRGB * (1 - srcA))` + /// + /// `dstA = srcA + (dstA * (1 - srcA))` + Blend, + /// Additive blending: + /// + /// `dstRGB = (srcRGB * srcA) + dstRGB` /// - /// dstRGB = (srcRGB * srcA) + (dstRGB * (1-srcA)) + /// `dstA = dstA` + Add, + /// Color modulation: /// - /// dstA = srcA + (dstA * (1-srcA)) - Blend = SDL_BlendMode::SDL_BLENDMODE_BLEND as i32, - /// Additive blending + /// `dstRGB = srcRGB * dstRGB` /// - /// dstRGB = (srcRGB * srcA) + dstRGB + /// `dstA = dstA` + Mod, + /// Color multiplication: /// - /// dstA = dstA (keep original alpha) - Add = SDL_BlendMode::SDL_BLENDMODE_ADD as i32, - /// Color modulate + /// `dstRGB = (srcRGB * dstRGB) + (dstRGB * (1 - srcA))` /// - /// dstRGB = srcRGB * dstRGB - Mod = SDL_BlendMode::SDL_BLENDMODE_MOD as i32, - /// Color multiply - Mul = SDL_BlendMode::SDL_BLENDMODE_MUL as i32, - /// Invalid blending mode (indicates error) - Invalid = SDL_BlendMode::SDL_BLENDMODE_INVALID as i32, + /// `dstA = dstA` + Mul, + /// Invalid blending mode, indicates error. + Invalid, + /// Custom blend mode, composed using [`BlendModeBuilder::build`]. + Custom(BlendValue), } -impl TryFrom for BlendMode { - type Error = (); +impl Into for BlendMode { + fn into(self) -> u32 { + use self::BlendMode::*; + use sys::blend_modes::*; - fn try_from(n: u32) -> Result { + match self { + None => NONE, + Blend => BLEND, + Add => ADD, + Mod => MOD, + Mul => MUL, + Invalid => INVALID, + Custom(BlendValue(x)) => x, + } + } +} + +impl From for BlendMode { + fn from(n: u32) -> BlendMode { use self::BlendMode::*; - use crate::sys::SDL_BlendMode::*; + use sys::blend_modes::*; - Ok(match unsafe { transmute(n) } { - SDL_BLENDMODE_NONE => None, - SDL_BLENDMODE_BLEND => Blend, - SDL_BLENDMODE_ADD => Add, - SDL_BLENDMODE_MOD => Mod, - SDL_BLENDMODE_MUL => Mul, - SDL_BLENDMODE_INVALID => Invalid, - }) + match n { + NONE => None, + BLEND => Blend, + ADD => Add, + MOD => Mod, + MUL => Mul, + INVALID => Invalid, + x => Custom(BlendValue(x)), + } } } @@ -995,7 +1125,7 @@ impl Canvas { #[doc(alias = "SDL_SetRenderDrawBlendMode")] pub fn set_blend_mode(&mut self, blend: BlendMode) { let ret = - unsafe { sys::SDL_SetRenderDrawBlendMode(self.context.raw, transmute(blend as u32)) }; + unsafe { sys::SDL_SetRenderDrawBlendMode(self.context.raw, Into::::into(blend)) }; // Should only fail on an invalid renderer if ret != 0 { panic!("{}", get_error()) @@ -1012,7 +1142,7 @@ impl Canvas { panic!("{}", get_error()) } else { let blend = unsafe { blend.assume_init() }; - BlendMode::try_from(blend as u32).unwrap() + BlendMode::from(blend) } } @@ -2121,7 +2251,7 @@ impl InternalTexture { #[doc(alias = "SDL_SetTextureBlendMode")] pub fn set_blend_mode(&mut self, blend: BlendMode) { - let ret = unsafe { sys::SDL_SetTextureBlendMode(self.raw, transmute(blend as u32)) }; + let ret = unsafe { sys::SDL_SetTextureBlendMode(self.raw, Into::::into(blend)) }; if ret != 0 { panic!("Error setting blend: {}", get_error()) @@ -2138,7 +2268,7 @@ impl InternalTexture { panic!("{}", get_error()) } else { let blend = unsafe { blend.assume_init() }; - BlendMode::try_from(blend as u32).unwrap() + BlendMode::from(blend) } } diff --git a/src/sdl2/surface.rs b/src/sdl2/surface.rs index 1785a4f731..8f8d1fbb01 100644 --- a/src/sdl2/surface.rs +++ b/src/sdl2/surface.rs @@ -11,8 +11,6 @@ use crate::render::{BlendMode, Canvas}; use crate::render::{Texture, TextureCreator, TextureValueError}; use crate::rwops::RWops; use libc::c_int; -use std::convert::TryFrom; -use std::mem::transmute; use std::ptr; use crate::sys; @@ -596,7 +594,7 @@ impl SurfaceRef { /// The function will fail if the blend mode is not supported by SDL. #[doc(alias = "SDL_SetSurfaceBlendMode")] pub fn set_blend_mode(&mut self, mode: BlendMode) -> Result<(), String> { - let result = unsafe { sys::SDL_SetSurfaceBlendMode(self.raw(), transmute(mode)) }; + let result = unsafe { sys::SDL_SetSurfaceBlendMode(self.raw(), Into::::into(mode)) }; match result { 0 => Ok(()), @@ -606,11 +604,11 @@ impl SurfaceRef { #[doc(alias = "SDL_GetSurfaceBlendMode")] pub fn blend_mode(&self) -> BlendMode { - let mut mode = sys::SDL_BlendMode::SDL_BLENDMODE_NONE; + let mut mode = sys::blend_modes::NONE; let result = unsafe { sys::SDL_GetSurfaceBlendMode(self.raw(), &mut mode) }; match result { - 0 => BlendMode::try_from(mode as u32).unwrap(), + 0 => BlendMode::from(mode), // Should only fail on a null Surface _ => panic!("{}", get_error()), }