diff --git a/Package.resolved b/Package.resolved
index a21107159..43375a9c7 100644
--- a/Package.resolved
+++ b/Package.resolved
@@ -7,7 +7,7 @@
"location" : "https://github.com/OpenSwiftUIProject/DarwinPrivateFrameworks.git",
"state" : {
"branch" : "main",
- "revision" : "a0ac60f4d56a9b50fb56c79113497d93fb166e1c"
+ "revision" : "fce1ec863f43767186d58ee4ce26303f444365b2"
}
},
{
@@ -43,7 +43,7 @@
"location" : "https://github.com/OpenSwiftUIProject/OpenRenderBox",
"state" : {
"branch" : "main",
- "revision" : "5f2ba682c0390124aa8a80f3ce5ea7d305ccce48"
+ "revision" : "b26cafb7d68bcb16fd623aa574c17dfd051af71d"
}
},
{
diff --git a/Sources/OpenSwiftUICore/Graphic/Color/Paint.swift b/Sources/OpenSwiftUICore/Graphic/Color/Paint.swift
index 2b4e89770..afb677040 100644
--- a/Sources/OpenSwiftUICore/Graphic/Color/Paint.swift
+++ b/Sources/OpenSwiftUICore/Graphic/Color/Paint.swift
@@ -3,7 +3,7 @@
// OpenSwiftUICore
//
// Audited for 6.5.4
-// Status: Complete (Blocked by ImagePaint and Shader)
+// Status: Complete (Blocked by ImagePaint)
// ID: 1A0B37DF690543DA63A8C3A51910F39C (SwiftUICore)
package import Foundation
@@ -190,7 +190,7 @@ package protocol ResolvedPaintVisitor {
mutating func visitPaint
(_ paint: P) where P: ResolvedPaint
}
-// MARK: - CodableResolvedPaint [WIP: ImagePaint, Shader]
+// MARK: - CodableResolvedPaint [WIP: ImagePaint]
package struct CodableResolvedPaint: ProtobufMessage {
package struct Tag: Equatable, ProtobufTag {
@@ -247,8 +247,8 @@ package struct CodableResolvedPaint: ProtobufMessage {
let rect: CGRect = try decoder.messageField(field)
base = base?.anchorRect(rect)
case Tag.shader.rawValue:
- // TODO: Decode Shader.ResolvedShader.
- _openSwiftUIUnimplementedFailure()
+ let shader: Shader.ResolvedShader = try decoder.messageField(field)
+ base = _AnyResolvedPaint(shader)
case Tag.meshGradient.rawValue:
let paint: MeshGradient._Paint = try decoder.messageField(field)
base = _AnyResolvedPaint(paint)
diff --git a/Sources/OpenSwiftUICore/Graphic/GraphicsContext.swift b/Sources/OpenSwiftUICore/Graphic/GraphicsContext.swift
index 3a78c9e26..de1e434b3 100644
--- a/Sources/OpenSwiftUICore/Graphic/GraphicsContext.swift
+++ b/Sources/OpenSwiftUICore/Graphic/GraphicsContext.swift
@@ -526,6 +526,12 @@ public struct GraphicsContext {
self.storage = storage
}
+ @available(OpenSwiftUI_v5_0, *)
+ @available(watchOS, unavailable) // @_spi_available(watchOS, introduced: 10.0)
+ public static func shader(_ shader: Shader, bounds: CGRect = .zero) -> Shading {
+ Shading(storage: .shader(shader, bounds))
+ }
+
// TODO
/// Creates a shading that fills with a mesh gradient.
@@ -815,3 +821,10 @@ extension GraphicsContext {
_openSwiftUIUnimplementedFailure()
}
}
+
+extension Color.Resolved {
+ func rbColor(in space: ORBColor.ColorSpace) -> ORBColor {
+ let color = ORBColor(red: linearRed, green: linearGreen, blue: linearBlue, alpha: opacity)
+ return space == .linearSRGB ? color : color.fromLinear()
+ }
+}
diff --git a/Sources/OpenSwiftUICore/Graphic/Shader/Shader.swift b/Sources/OpenSwiftUICore/Graphic/Shader/Shader.swift
index 4bb11c4df..294fa0418 100644
--- a/Sources/OpenSwiftUICore/Graphic/Shader/Shader.swift
+++ b/Sources/OpenSwiftUICore/Graphic/Shader/Shader.swift
@@ -3,19 +3,267 @@
// OpenSwiftUICore
//
// Audited for 6.5.4
-// Status: WIP
+// Status: Complete
+// ID: 2BFAEFF753052DBF4DEF07051FF899A7 (SwiftUICore)
-package import Foundation
-package import OpenCoreGraphicsShims
-// package import OpenRenderBoxShims
+public import Foundation
+#if canImport(Dispatch)
+import Dispatch
+#endif
+import OpenAttributeGraphShims
+import OpenCoreGraphicsShims
+package import OpenRenderBoxShims
-// MARK: - Shader [TODO]
+// MARK: - ShaderLibrary
-public struct Shader {
+/// A Metal shader library.
+@available(OpenSwiftUI_v5_0, *)
+@available(watchOS, unavailable) // @_spi_available(watchOS, introduced: 10.0)
+@dynamicMemberLookup
+public struct ShaderLibrary: Equatable, @unchecked Sendable {
+ fileprivate var rbLibrary: ORBShaderLibrary
+
+ /// The default shader library of the app's main bundle.
+ public static let `default` = ShaderLibrary(rbShaderLibrary: .standard)
+
+ /// Returns the default shader library of the specified bundle.
+ public static func bundle(_ bundle: Bundle) -> ShaderLibrary {
+ ShaderLibrary(rbShaderLibrary: .inBundle(bundle))
+ }
+
+ /// Creates a Metal shader library from the contents of a precompiled
+ /// Metal library. Compiled functions stay cached for the lifetime of
+ /// the returned library.
+ public init(data: Data) {
+ rbLibrary = .from(data: data)
+ }
+
+ /// Creates a Metal shader library from the precompiled library at
+ /// `url`. Compiled functions stay cached for the lifetime of the
+ /// returned library.
+ public init(url: URL) {
+ rbLibrary = .from(url: url)
+ }
+
+ /// Returns a reference to the stitchable MSL function named `name`
+ /// in the default shader library.
+ ///
+ /// Use dynamic member syntax to look up a function in that library.
+ ///
+ /// let function = ShaderLibrary.myFunction
+ public static subscript(dynamicMember name: String) -> ShaderFunction {
+ Self.default[dynamicMember: name]
+ }
+
+ /// Returns a reference to the stitchable MSL function named `name`
+ /// in this library.
+ ///
+ /// Use dynamic member syntax to look up a function in the library.
+ ///
+ /// let function = ShaderLibrary.default.myFunction
+ public subscript(dynamicMember name: String) -> ShaderFunction {
+ ShaderFunction(library: self, name: name)
+ }
+
+ public static func == (lhs: ShaderLibrary, rhs: ShaderLibrary) -> Bool {
+ lhs.rbLibrary === rhs.rbLibrary
+ }
+}
+
+extension ShaderLibrary {
+ package init(rbShaderLibrary: ORBShaderLibrary) {
+ rbLibrary = rbShaderLibrary
+ }
+
+ package var rbShaderLibrary: ORBShaderLibrary? { rbLibrary }
+}
+
+// MARK: - ShaderFunction
+
+/// A reference to a function in a Metal shader library.
+@available(OpenSwiftUI_v5_0, *)
+@available(watchOS, unavailable) // @_spi_available(watchOS, introduced: 10.0)
+@dynamicCallable
+public struct ShaderFunction: Equatable, Sendable {
+ /// The shader library that contains the function.
+ public var library: ShaderLibrary
+
+ /// The name of the shader function in the library.
+ public var name: String
+
+ /// Creates a reference to a function by library and name.
+ public init(library: ShaderLibrary, name: String) {
+ self.library = library
+ self.name = name
+ }
+
+ /// Returns a shader with the supplied uniform arguments bound to this
+ /// function.
+ ///
+ /// Use function-call syntax to bind the arguments. This call passes
+ /// the value `42` to the first unbound parameter of `myFunction`.
+ ///
+ /// let shader = ShaderLibrary.default.myFunction(.float(42))
+ public func dynamicallyCall(withArguments args: [Shader.Argument]) -> Shader {
+ Shader(function: self, arguments: args)
+ }
+}
+
+// MARK: - Shader
+
+/// A reference to a function in a Metal shader library, along with its
+/// bound uniform argument values.
+///
+/// Apply a shader to a view with ``View/colorEffect(_:isEnabled:)``,
+/// ``View/distortionEffect(_:maxSampleOffset:isEnabled:)``, or
+/// ``View/layerEffect(_:maxSampleOffset:isEnabled:)``.
+///
+/// A shader also conforms to ``ShapeStyle``. Its Metal Shading Language
+/// (MSL) function can provide the color of each pixel in a shape or text
+/// fill. A fill shader has this signature.
+///
+/// [[ stitchable ]] half4 name(float2 position, args...)
+///
+/// The `position` parameter is the pixel's position in user coordinates.
+/// The remaining parameters match the uniform arguments bound to the
+/// shader. Return a premultiplied color in the destination color space,
+/// which is typically extended sRGB.
+@available(OpenSwiftUI_v5_0, *)
+@available(watchOS, unavailable) // @_spi_available(watchOS, introduced: 10.0)
+public struct Shader: Equatable, Sendable {
+
+ /// A uniform argument value passed to a shader function.
+ public struct Argument: Equatable, Sendable {
+ enum Storage: Equatable, Sendable {
+ case float(Float)
+ case float2(Float, Float)
+ case float3(Float, Float, Float)
+ case float4(Float, Float, Float, Float)
+ case floatArray([Float])
+ case boundsRect
+ case color(Color)
+ case colorArray([Color])
+ case image(Image)
+ case data(Data)
+ }
+
+ var storage: Storage
+
+ @usableFromInline
+ static func _float(_ x: Float) -> Argument {
+ Argument(storage: .float(x))
+ }
+
+ @usableFromInline
+ static func _float2(_ x: Float, _ y: Float) -> Argument {
+ Argument(storage: .float2(x, y))
+ }
+
+ @usableFromInline
+ static func _float3(_ x: Float, _ y: Float, _ z: Float) -> Argument {
+ Argument(storage: .float3(x, y, z))
+ }
+
+ @usableFromInline
+ static func _float4(_ x: Float, _ y: Float, _ z: Float, _ w: Float) -> Argument {
+ Argument(storage: .float4(x, y, z, w))
+ }
+
+ /// Returns an argument representing the MSL value `float(x)`.
+ @_alwaysEmitIntoClient
+ public static func float(_ x: T) -> Argument where T: BinaryFloatingPoint {
+ _float(Float(x))
+ }
+
+ /// Returns an argument representing the MSL value `float2(x, y)`.
+ @_alwaysEmitIntoClient
+ public static func float2(_ x: T, _ y: T) -> Argument where T: BinaryFloatingPoint {
+ _float2(Float(x), Float(y))
+ }
+
+ /// Returns an argument representing the MSL value `float3(x, y, z)`.
+ @_alwaysEmitIntoClient
+ public static func float3(_ x: T, _ y: T, _ z: T) -> Argument where T: BinaryFloatingPoint {
+ _float3(Float(x), Float(y), Float(z))
+ }
+
+ /// Returns an argument representing the MSL value `float4(x, y, z, w)`.
+ @_alwaysEmitIntoClient
+ public static func float4(_ x: T, _ y: T, _ z: T, _ w: T) -> Argument where T: BinaryFloatingPoint {
+ _float4(Float(x), Float(y), Float(z), Float(w))
+ }
+
+ /// Returns an argument representing the MSL value
+ /// `float2(point.x, point.y)`.
+ @_alwaysEmitIntoClient
+ public static func float2(_ point: CGPoint) -> Argument {
+ _float2(Float(point.x), Float(point.y))
+ }
+
+ /// Returns an argument representing the MSL value
+ /// `float2(size.width, size.height)`.
+ @_alwaysEmitIntoClient
+ public static func float2(_ size: CGSize) -> Argument {
+ _float2(Float(size.width), Float(size.height))
+ }
+
+ /// Returns an argument representing the MSL value
+ /// `float2(vector.dx, vector.dy)`.
+ @_alwaysEmitIntoClient
+ public static func float2(_ vector: CGVector) -> Argument {
+ _float2(Float(vector.dx), Float(vector.dy))
+ }
+
+ /// Returns an argument for an array of floating-point values.
+ ///
+ /// The MSL function receives the array as two parameters,
+ /// `device const float *ptr` and `int count`.
+ public static func floatArray(_ array: [Float]) -> Argument {
+ Argument(storage: .floatArray(array))
+ }
+
+ /// The bounding rectangle of the shape or view using the shader,
+ /// represented in MSL as `float4(x, y, width, height)`.
+ ///
+ /// This argument requires a natural bounding rectangle. For example,
+ /// it has an undefined value for filter effects drawn into a
+ /// ``GraphicsContext``.
+ public static var boundingRect: Argument {
+ Argument(storage: .boundsRect)
+ }
+
+ /// Returns an argument for a color. The MSL function receives a
+ /// premultiplied `half4` value in the target color space.
+ public static func color(_ color: Color) -> Argument {
+ Argument(storage: .color(color))
+ }
+
+ /// Returns an argument for an array of colors.
+ ///
+ /// The MSL function receives the array as two parameters,
+ /// `device const half4 *ptr` and `int count`.
+ public static func colorArray(_ array: [Color]) -> Argument {
+ Argument(storage: .colorArray(array))
+ }
+
+ /// Returns an argument for an image. The MSL function receives a
+ /// `texture2d` value. Each shader supports one image argument.
+ public static func image(_ image: Image) -> Argument {
+ Argument(storage: .image(image))
+ }
+
+ /// Returns an argument for a block of data.
+ ///
+ /// The MSL function receives the data as two parameters,
+ /// `device const void *ptr` and `int size_in_bytes`.
+ public static func data(_ data: Data) -> Argument {
+ Argument(storage: .data(data))
+ }
+ }
// MARK: - Shader.Options
- package struct Options: OptionSet {
+ package struct Options: OptionSet, Sendable {
package let rawValue: UInt32
package init(rawValue: UInt32) {
@@ -31,9 +279,38 @@ public struct Shader {
package static let alphaOnlyLayer: Options = .init(rawValue: 1 << 3)
}
+ /// The function that the shader calls.
+ public var function: ShaderFunction
+
+ /// The uniform argument values passed to the shader function.
+ public var arguments: [Argument]
+
+ package var options: Options = []
+
+ /// Whether to add dither noise when converting the returned color to the
+ /// output bit depth.
+ ///
+ /// Dithering can reduce visible banding in smooth gradients.
+ public var dithersColor: Bool {
+ get { options.contains(.dithersColor) }
+ set { options.setValue(newValue, for: .dithersColor) }
+ }
+
+ package var alphaOnlyLayer: Bool {
+ get { options.contains(.alphaOnlyLayer) }
+ set { options.setValue(newValue, for: .alphaOnlyLayer) }
+ }
+
+ /// Creates a shader from a function and the uniform argument values
+ /// to bind to it.
+ public init(function: ShaderFunction, arguments: [Argument]) {
+ self.function = function
+ self.arguments = arguments
+ }
+
// MARK: - Shader.ResolvedShader
- package struct ResolvedShader: Equatable {
+ package struct ResolvedShader: Equatable, @unchecked Sendable {
package var rbShader: ORBShader?
package var maxSampleOffset: CGSize
@@ -50,15 +327,253 @@ public struct Shader {
self.options = options
}
}
+
+ private func makeRBShader(in environment: EnvironmentValues?) -> ORBShader {
+ let shader = ORBShader(library: function.library.rbLibrary, function: function.name)
+ for (index, argument) in arguments.enumerated() {
+ argument.apply(to: shader, at: UInt(index), environment: environment)
+ }
+ return shader
+ }
+
+ func resolve(in environment: EnvironmentValues, maxSampleOffset: CGSize = .zero, enabled: Bool = true) -> ResolvedShader {
+ guard enabled else {
+ return ResolvedShader(maxSampleOffset: .zero, options: [])
+ }
+ return ResolvedShader(rbShader: makeRBShader(in: environment), maxSampleOffset: maxSampleOffset, options: options)
+ }
}
-// MARK: - Shader.ResolvedShader + ProtobufMessage [TBA]
+// MARK: - Shader.UsageType
+
+@available(OpenSwiftUI_v6_0, *)
+@available(watchOS, unavailable) // @_spi_available(watchOS, introduced: 11.0)
+extension Shader {
+ /// Attempts to compile a shader function asynchronously to reduce delays
+ /// on its first use.
+ ///
+ /// A shader must compile for the current GPU before it can render.
+ /// Compilation normally occurs on first use and can delay that frame.
+ /// Call this method in advance to prepare the function for rendering.
+ ///
+ /// Select the usage type that matches how you will render the shader.
+ /// Bind arguments of the same types you will supply when rendering.
+ /// Array and data arguments can be empty during compilation.
+ ///
+ /// This example compiles a fill shader when the app launches.
+ ///
+ /// Task {
+ /// let shader = ShaderLibrary.example(.color(.clear), .float(0))
+ /// try await shader.compile(as: .shapeStyle)
+ /// }
+ ///
+ /// The function takes a color and a number. Supply the actual values
+ /// when you use the shader to fill the circle.
+ ///
+ /// Circle().fill(
+ /// ShaderLibrary.example(.color(.orange), .float(32)))
+ ///
+ /// - Parameter type: How the shader will be used for rendering.
+ /// - Throws: An error that describes why compilation failed.
+ public func compile(as type: UsageType) async throws {
+ #if canImport(Dispatch)
+ guard let device = ORBDevice.sharedDefault() else { return }
+ try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in
+ let shader = makeRBShader(in: nil)
+ shader.type = type.base
+ device.compileShader(shader, completionQueue: .main) { error in
+ if let error {
+ continuation.resume(throwing: error)
+ } else {
+ continuation.resume()
+ }
+ }
+ }
+ #endif
+ }
+
+ /// The ways a shader can be used to render.
+ public struct UsageType: Hashable, Sendable {
+ var base: Int32
+
+ /// The shader is used as a ``ShapeStyle``.
+ public static let shapeStyle = UsageType(base: 0)
+
+ /// The shader is used as a color effect.
+ public static let colorEffect = UsageType(base: 1)
+
+ /// The shader is used as a geometric distortion effect.
+ public static let distortionEffect = UsageType(base: 3)
+
+ /// The shader is used as a layer effect.
+ public static let layerEffect = UsageType(base: 2)
+ }
+}
+
+extension Shader: Paint {
+ package func rbShader(in environment: EnvironmentValues) -> ORBShader? {
+ makeRBShader(in: environment)
+ }
+
+ func resolvePaint(in environment: EnvironmentValues) -> ResolvedShader {
+ resolve(in: environment)
+ }
+
+ func fallbackColor(in environment: EnvironmentValues) -> Color? { nil }
+}
+
+// MARK: - View + Shader Effects
+
+@available(OpenSwiftUI_v5_0, *)
+@available(watchOS, unavailable) // @_spi_available(watchOS, introduced: 10.0)
+extension View {
+ /// Applies a shader to the color of each pixel in this view.
+ ///
+ /// A color effect uses an MSL function with this signature.
+ ///
+ /// [[ stitchable ]] half4 name(float2 position, half4 color, args...)
+ ///
+ /// The function receives a pixel's position in user coordinates and
+ /// its premultiplied source color in the destination color space.
+ /// The remaining parameters match the bound uniform arguments.
+ /// Return the modified color.
+ ///
+ /// Views backed by AppKit or UIKit may display a placeholder and log
+ /// a warning when used in a filtered layer.
+ ///
+ /// - Parameters:
+ /// - shader: The shader to apply as a color filter.
+ /// - isEnabled: Whether the effect is enabled.
+ /// - Returns: A view that renders with the shader applied as a color filter.
+ nonisolated public func colorEffect(_ shader: Shader, isEnabled: Bool = true) -> some View {
+ var shader = shader
+ shader.options.insert(.colorFilter)
+ return layerEffect(shader, maxSampleOffset: .zero, isEnabled: isEnabled)
+ }
+
+ /// Applies a shader that changes the position of pixels in this view.
+ ///
+ /// A distortion effect uses an MSL function with this signature.
+ ///
+ /// [[ stitchable ]] float2 name(float2 position, args...)
+ ///
+ /// The function receives the destination pixel's position in user
+ /// coordinates. The remaining parameters match the bound uniform
+ /// arguments. Return the source pixel's position in user coordinates.
+ ///
+ /// Views backed by AppKit or UIKit may display a placeholder and log
+ /// a warning when used in a filtered layer.
+ ///
+ /// - Parameters:
+ /// - shader: The shader to apply as a distortion effect.
+ /// - maxSampleOffset: The maximum distance on each axis between a
+ /// destination position and the source position returned by the shader
+ /// across all pixels.
+ /// - isEnabled: Whether the effect is enabled.
+ /// - Returns: A view that renders with the shader applied as a distortion
+ /// effect.
+ nonisolated public func distortionEffect(
+ _ shader: Shader,
+ maxSampleOffset: CGSize,
+ isEnabled: Bool = true
+ ) -> some View {
+ var shader = shader
+ shader.options.insert(.distortionFilter)
+ return layerEffect(shader, maxSampleOffset: maxSampleOffset, isEnabled: isEnabled)
+ }
+
+ /// Applies a shader to the rasterized contents of this view.
+ ///
+ /// A layer effect uses an MSL function with this signature.
+ ///
+ /// [[ stitchable ]] half4 name(float2 position,
+ /// OpenSwiftUI::Layer layer, args...)
+ ///
+ /// The function receives the destination pixel's position in user
+ /// coordinates and a region of the rasterized view. The remaining
+ /// parameters match the bound uniform arguments.
+ ///
+ /// The `OpenSwiftUI_Metal.h` header defines `OpenSwiftUI::Layer`.
+ /// Its `sample(float2)` method samples the source layer with linear
+ /// filtering and returns a premultiplied RGBA color. Use one or more
+ /// samples to calculate the color of the destination pixel.
+ ///
+ /// Views backed by AppKit or UIKit may display a placeholder and log
+ /// a warning when used in a filtered layer.
+ ///
+ /// - Parameters:
+ /// - shader: The shader to apply as a layer effect.
+ /// - maxSampleOffset: The maximum distance on each axis from the
+ /// destination position to any position sampled by the shader.
+ /// - isEnabled: Whether the effect is enabled.
+ /// - Returns: A view that renders with the shader applied as a layer effect.
+ nonisolated public func layerEffect(
+ _ shader: Shader,
+ maxSampleOffset: CGSize,
+ isEnabled: Bool = true
+ ) -> some View {
+ modifier(_ShaderFilterEffect(shader: shader, maxSampleOffset: maxSampleOffset, enabled: isEnabled))
+ }
+}
+
+// MARK: - _ShaderFilterEffect
+
+@available(OpenSwiftUI_v5_0, *)
+@available(watchOS, unavailable) // @_spi_available(watchOS, introduced: 10.0)
+public struct _ShaderFilterEffect: MultiViewModifier, PrimitiveViewModifier, Sendable {
+ package var shader: Shader
+
+ package var maxSampleOffset: CGSize
+
+ package var enabled: Bool
+
+ package init(shader: Shader, maxSampleOffset: CGSize, enabled: Bool) {
+ self.shader = shader
+ self.maxSampleOffset = maxSampleOffset
+ self.enabled = enabled
+ }
+
+ nonisolated public static func _makeView(
+ modifier: _GraphValue,
+ inputs: _ViewInputs,
+ body: @escaping (_Graph, _ViewInputs) -> _ViewOutputs
+ ) -> _ViewOutputs {
+ let effect = Attribute(
+ ResolvedEffect(modifier: modifier.value, environment: inputs.environment)
+ )
+ return Shader.ResolvedShader.makeRendererEffect(effect: _GraphValue(effect), inputs: inputs, body: body)
+ }
+
+ private struct ResolvedEffect: StatefulRule, AsyncAttribute {
+ @Attribute var modifier: _ShaderFilterEffect
+ @Attribute var environment: EnvironmentValues
+ let tracker = PropertyList.Tracker()
+
+ typealias Value = Shader.ResolvedShader
+
+ func updateValue() {
+ let (modifier, modifierChanged) = $modifier.changedValue()
+ let environment = environment
+ guard !hasValue || modifierChanged || tracker.hasDifferentUsedValues(environment.plist) else {
+ return
+ }
+ tracker.reset()
+ let tracked = EnvironmentValues(environment.plist, tracker: tracker)
+ value = modifier.shader.resolve(in: tracked, maxSampleOffset: modifier.maxSampleOffset, enabled: modifier.enabled)
+ }
+ }
+}
+
+// MARK: - Shader.ResolvedShader + ProtobufMessage
extension Shader.ResolvedShader: ProtobufMessage {
package func encode(to encoder: inout ProtobufEncoder) throws {
- if rbShader != nil {
- // TODO: Encode the RenderBox shader through its archive delegate.
- _openSwiftUIUnimplementedFailure()
+ if let rbShader {
+ try encoder.messageField(1) { attachment in
+ try attachment.encodeAttachedValue(key: rbShader) {
+ try rbShader.encodedData(for: ORBArchiveDelegate(0))
+ }
+ }
}
try encoder.messageField(2, maxSampleOffset, defaultValue: .zero)
encoder.uintField(3, UInt(options.rawValue))
@@ -69,8 +584,19 @@ extension Shader.ResolvedShader: ProtobufMessage {
while let field = try decoder.nextField() {
switch field.tag {
case 1:
- // TODO: Decode the RenderBox shader through its archive delegate.
- _openSwiftUIUnimplementedFailure()
+ rbShader = try decoder.messageField(field) { attachment in
+ while let item = try attachment.nextField() {
+ if item.tag == 2 {
+ let data = try attachment.dataField(item)
+ if let shader = try ORBShader.decodedObject(with: data, delegate: ORBArchiveDelegate(0)) as? ORBShader {
+ return shader
+ }
+ throw ProtobufDecoder.DecodingError.failed
+ }
+ try attachment.skipField(item)
+ }
+ throw ProtobufDecoder.DecodingError.failed
+ }
case 2: maxSampleOffset = try decoder.messageField(field)
case 3: options = .init(rawValue: try decoder.uint32Field(field))
default: try decoder.skipField(field)
@@ -79,5 +605,323 @@ extension Shader.ResolvedShader: ProtobufMessage {
}
}
-// FIXME: RB
-package class ORBShader: NSObject {}
+// MARK: - Shader.ResolvedShader + ResolvedPaint
+
+extension Shader.ResolvedShader: ResolvedPaint {
+ package func draw(path: Path, style: PathDrawingStyle, in context: GraphicsContext, bounds: CGRect?) {
+ context.draw(path, with: .shader(self, bounds ?? path.boundingRect), style: style)
+ }
+
+ package var isCALayerCompatible: Bool { false }
+
+ package static var leafProtobufTag: CodableResolvedPaint.Tag? { .shader }
+
+ package var rbFillFlags: ORBShaderFillFlags {
+ options.contains(.dithersColor) ? .dithersColor : []
+ }
+}
+
+// MARK: - Shader.ResolvedShader + Animatable
+
+extension Shader.ResolvedShader: Animatable {
+ package typealias AnimatableData = ShaderVectorData
+
+ package var animatableData: ShaderVectorData {
+ get { ShaderVectorData(rbShader: rbShader) }
+ set { rbShader = newValue.updating(rbShader: rbShader) }
+ }
+}
+
+// MARK: - Shader.ResolvedShader + RendererEffect
+
+extension Shader.ResolvedShader: RendererEffect {
+ package func effectValue(size: CGSize) -> DisplayList.Effect {
+ .filter(.shader(.init(shader: self, size: size)))
+ }
+
+ package var rbFilterFlags: ORBShaderFilterFlags {
+ var flags: ORBShaderFilterFlags = []
+ if options.contains(.colorFilter) {
+ flags.insert(.color)
+ } else if options.contains(.distortionFilter) {
+ flags.insert(.distortion)
+ }
+ if options.contains(.dithersColor) {
+ flags.insert(.dithersColor)
+ }
+ if options.contains(.alphaOnlyLayer) {
+ flags.insert(.alphaOnlyLayer)
+ }
+ return flags
+ }
+}
+
+// MARK: - Shader.Argument + RenderBox
+
+extension Shader.Argument {
+ @inline(__always)
+ fileprivate func apply(to shader: ORBShader, at index: UInt, environment: EnvironmentValues?) {
+ func setArray(_ values: [T], type: UInt32) {
+ values.withUnsafeBytes { bytes in
+ shader.setBytes(bytes.baseAddress, at: index, type: type, count: UInt(values.count), flags: 3)
+ }
+ }
+ switch storage {
+ case let .float(x):
+ shader.setArgument(x, at: index, type: 1)
+ case let .float2(x, y):
+ shader.setArgument((x, y), at: index, type: 2)
+ case let .float3(x, y, z):
+ shader.setArgument((x, y, z), at: index, type: 3)
+ case let .float4(x, y, z, w):
+ shader.setArgument((x, y, z, w), at: index, type: 4)
+ case let .floatArray(array):
+ setArray(array, type: 1)
+ case let .color(color):
+ let resolved = environment.map { color.resolve(in: $0).rbColor(in: .linearSRGB) } ?? .clear
+ shader.setArgument(resolved, at: index, type: 5)
+ shader.setColorSpace(.linearSRGB, at: index)
+ case let .colorArray(colors):
+ if let environment {
+ setArray(colors.map { $0.resolve(in: environment).rbColor(in: .linearSRGB) }, type: 5)
+ shader.setColorSpace(.linearSRGB, at: index)
+ } else {
+ shader.setBytes(nil, at: index, type: 5, count: 0, flags: 3)
+ }
+ case let .image(image):
+ guard let environment else {
+ shader.setArgument(ORBImage(type: 0, data: nil), at: index, type: 7)
+ return
+ }
+ let resolved = image.resolve(in: ImageResolutionContext(environment: environment)).image
+ switch resolved.contents {
+ case let .ioSurface(surface):
+ withExtendedLifetime(surface) {
+ shader.setArgument(ORBImage(surface: surface), at: index, type: 7)
+ }
+ case let .cgImage(bitmap):
+ withExtendedLifetime(bitmap) {
+ shader.setArgument(ORBImage(bitmap), at: index, type: 7)
+ }
+ case .vectorGlyph, .vectorLayer:
+ if let bitmap = resolved.render(at: resolved.size) {
+ withExtendedLifetime(bitmap) {
+ shader.setArgument(ORBImage(bitmap), at: index, type: 7)
+ }
+ }
+ default:
+ break
+ }
+ case let .data(data):
+ if environment != nil {
+ shader.setData(data, at: index, type: 0, flags: 3)
+ } else {
+ shader.setBytes(nil, at: index, type: 0, count: 0, flags: 3)
+ }
+ case .boundsRect:
+ shader.setBytes(nil, at: index, type: 6, count: 1, flags: 0)
+ }
+ }
+}
+
+extension ORBShader {
+ @inline(__always)
+ fileprivate func setArgument(_ value: T, at index: UInt, type: UInt32, flags: UInt32 = 0) {
+ withUnsafeBytes(of: value) { bytes in
+ setBytes(bytes.baseAddress, at: index, type: type, count: 1, flags: flags)
+ }
+ }
+}
+
+// MARK: - ShaderVectorData
+
+package struct ShaderVectorData: VectorArithmetic {
+ enum Element: Equatable {
+ case float(Float)
+ case float2(Float, Float)
+ case float3(Float, Float, Float)
+ case float4(Float, Float, Float, Float)
+ case array([Float])
+ case zero
+
+ mutating func scale(by rhs: Double) {
+ let factor = Float(rhs)
+ switch self {
+ case let .float(x):
+ self = .float(x * factor)
+ case let .float2(x, y):
+ self = .float2(x * factor, y * factor)
+ case let .float3(x, y, z):
+ self = .float3(x * factor, y * factor, z * factor)
+ case let .float4(x, y, z, w):
+ self = .float4(x * factor, y * factor, z * factor, w * factor)
+ case let .array(values):
+ self = .array(values.map { $0 * factor })
+ case .zero:
+ break
+ }
+ }
+
+ var magnitudeSquared: Double {
+ let squared: Float
+ switch self {
+ case let .float(x):
+ squared = x * x
+ case let .float2(x, y):
+ squared = x * x + y * y
+ case let .float3(x, y, z):
+ squared = x * x + y * y + z * z
+ case let .float4(x, y, z, w):
+ squared = x * x + y * y + z * z + w * w
+ case let .array(values):
+ squared = values.reduce(0) { $0 + $1 * $1 }
+ case .zero:
+ squared = 0
+ }
+ return Double(squared)
+ }
+
+ static func += (lhs: inout Element, rhs: Element) {
+ switch (lhs, rhs) {
+ case let (.float(x), .float(a)):
+ lhs = .float(x + a)
+ case let (.float2(x, y), .float2(a, b)):
+ lhs = .float2(x + a, y + b)
+ case let (.float3(x, y, z), .float3(a, b, c)):
+ lhs = .float3(x + a, y + b, z + c)
+ case let (.float4(x, y, z, w), .float4(a, b, c, d)):
+ lhs = .float4(x + a, y + b, z + c, w + d)
+ case let (.array(values), .array(other)) where values.count == other.count:
+ lhs = .array(zip(values, other).map(+))
+ default:
+ break
+ }
+ }
+
+ static func -= (lhs: inout Element, rhs: Element) {
+ switch (lhs, rhs) {
+ case let (.float(x), .float(a)):
+ lhs = .float(x - a)
+ case let (.float2(x, y), .float2(a, b)):
+ lhs = .float2(x - a, y - b)
+ case let (.float3(x, y, z), .float3(a, b, c)):
+ lhs = .float3(x - a, y - b, z - c)
+ case let (.float4(x, y, z, w), .float4(a, b, c, d)):
+ lhs = .float4(x - a, y - b, z - c, w - d)
+ case let (.array(values), .array(other)) where values.count == other.count:
+ lhs = .array(zip(values, other).map(-))
+ case (.zero, _):
+ lhs = rhs
+ lhs.scale(by: -1)
+ default:
+ break
+ }
+ }
+ }
+
+ var elements: [Element]
+
+ package static let zero = ShaderVectorData(rbShader: nil)
+
+ init(rbShader: ORBShader?) {
+ guard let rbShader else {
+ elements = []
+ return
+ }
+ elements = (0.. ORBShader? {
+ guard let rbShader else { return nil }
+ let shader = rbShader.copy() as! ORBShader
+ for (offset, element) in elements.prefix(Int(rbShader.numberOfArguments)).enumerated() {
+ let index = UInt(offset)
+ let argument = rbShader.argument(at: index)
+ switch (argument.type, element) {
+ case (1, let .float(x)):
+ shader.setArgument(x, at: index, type: 1, flags: argument.flags)
+ case (2, let .float2(x, y)):
+ shader.setArgument((x, y), at: index, type: 2, flags: argument.flags)
+ case (3, let .float3(x, y, z)):
+ shader.setArgument((x, y, z), at: index, type: 3, flags: argument.flags)
+ case (1, let .float4(x, y, z, w)), (5, let .float4(x, y, z, w)):
+ shader.setArgument((x, y, z, w), at: index, type: argument.type, flags: argument.flags)
+ case (1, let .array(values)), (5, let .array(values)):
+ let count = argument.type == 5 ? values.count / 4 : values.count
+ values.withUnsafeBytes { bytes in
+ shader.setBytes(bytes.baseAddress, at: index, type: argument.type, count: UInt(count), flags: argument.flags)
+ }
+ default:
+ break
+ }
+ }
+ return shader
+ }
+
+ package static func += (lhs: inout ShaderVectorData, rhs: ShaderVectorData) {
+ let count = lhs.elements.count
+ if count == rhs.elements.count {
+ for index in 0 ..< count {
+ lhs.elements[index] += rhs.elements[index]
+ }
+ } else if count == 0 {
+ lhs = rhs
+ }
+ }
+
+ package static func -= (lhs: inout ShaderVectorData, rhs: ShaderVectorData) {
+ let count = lhs.elements.count
+ if count == rhs.elements.count {
+ for index in 0 ..< count {
+ lhs.elements[index] -= rhs.elements[index]
+ }
+ } else if count == 0 {
+ lhs = rhs
+ lhs.scale(by: -1)
+ }
+ }
+
+ package static func + (lhs: ShaderVectorData, rhs: ShaderVectorData) -> ShaderVectorData {
+ var result = lhs
+ result += rhs
+ return result
+ }
+
+ package static func - (lhs: ShaderVectorData, rhs: ShaderVectorData) -> ShaderVectorData {
+ var result = lhs
+ result -= rhs
+ return result
+ }
+
+ package mutating func scale(by rhs: Double) {
+ for index in elements.indices {
+ elements[index].scale(by: rhs)
+ }
+ }
+
+ package var magnitudeSquared: Double {
+ elements.reduce(0) { $0 + $1.magnitudeSquared }
+ }
+}
diff --git a/Sources/OpenSwiftUICore/Shape/ShapeStyle/ShapeStylePack.swift b/Sources/OpenSwiftUICore/Shape/ShapeStyle/ShapeStylePack.swift
index 2d3bff3f5..6c353fccb 100644
--- a/Sources/OpenSwiftUICore/Shape/ShapeStyle/ShapeStylePack.swift
+++ b/Sources/OpenSwiftUICore/Shape/ShapeStyle/ShapeStylePack.swift
@@ -3,7 +3,7 @@
// OpenSwiftUICore
//
// Audited for 6.5.4
-// Status: Complete - Blocked by Shader
+// Status: Complete
// ID: 4DBF651155A4B32ED86C55EAB1B96C61 (SwiftUICore)
package import Foundation
@@ -498,8 +498,7 @@ extension _ShapeStyle_Pack.Fill: Animatable {
case ellipticalGradient(EllipticalGradient._Paint.AnimatableData)
case angularGradient(AngularGradient._Paint.AnimatableData)
case meshGradient(MeshGradient._Paint.AnimatableData)
- // TODO: Shader
- // case shader(Shader.ResolvedShader.AnimatableData)
+ case shader(ShaderVectorData)
case colorMatrix(_ColorMatrix)
package init(_ fill: _ShapeStyle_Pack.Fill) {
@@ -559,7 +558,10 @@ extension _ShapeStyle_Pack.Fill: Animatable {
var visitor = PaintSetVisitor(data: data, result: .color(.clear))
anyPaint.visit(&visitor)
fill = visitor.result
- // TODO: Shader
+ case let .shader(data):
+ var visitor = PaintSetVisitor(data: data, result: .color(.clear))
+ anyPaint.visit(&visitor)
+ fill = visitor.result
default:
break
}
@@ -608,6 +610,8 @@ extension _ShapeStyle_Pack.Fill: Animatable {
lhs = .angularGradient(lhsData + rhsData)
case let (.meshGradient(lhsData), .meshGradient(rhsData)):
lhs = .meshGradient(lhsData + rhsData)
+ case let (.shader(lhsData), .shader(rhsData)):
+ lhs = .shader(lhsData + rhsData)
case (.colorMatrix(var lhsData), .colorMatrix(let rhsData)):
lhsData.add(rhsData)
lhs = .colorMatrix(lhsData)
@@ -637,6 +641,8 @@ extension _ShapeStyle_Pack.Fill: Animatable {
lhs = .angularGradient(lhsData - rhsData)
case let (.meshGradient(lhsData), .meshGradient(rhsData)):
lhs = .meshGradient(lhsData - rhsData)
+ case let (.shader(lhsData), .shader(rhsData)):
+ lhs = .shader(lhsData - rhsData)
case (.colorMatrix(var lhsData), .colorMatrix(let rhsData)):
lhsData.subtract(rhsData)
lhs = .colorMatrix(lhsData)
@@ -657,6 +663,8 @@ extension _ShapeStyle_Pack.Fill: Animatable {
self = .angularGradient(.zero - data)
case let .meshGradient(data):
self = .meshGradient(.zero - data)
+ case let .shader(data):
+ self = .shader(.zero - data)
case var .colorMatrix(data):
data.negate()
self = .colorMatrix(data)
@@ -705,6 +713,9 @@ extension _ShapeStyle_Pack.Fill: Animatable {
case var .meshGradient(data):
data.scale(by: rhs)
self = .meshGradient(data)
+ case var .shader(data):
+ data.scale(by: rhs)
+ self = .shader(data)
case var .colorMatrix(data):
data.scale(by: rhs)
self = .colorMatrix(data)
@@ -721,6 +732,7 @@ extension _ShapeStyle_Pack.Fill: Animatable {
case let .ellipticalGradient(data): return data.magnitudeSquared
case let .angularGradient(data): return data.magnitudeSquared
case let .meshGradient(data): return data.magnitudeSquared
+ case let .shader(data): return data.magnitudeSquared
case let .colorMatrix(data): return data.magnitudeSquared
}
}
@@ -735,6 +747,7 @@ extension _ShapeStyle_Pack.Fill: Animatable {
case let (.ellipticalGradient(lhs), .ellipticalGradient(rhs)): return lhs == rhs
case let (.angularGradient(lhs), .angularGradient(rhs)): return lhs == rhs
case let (.meshGradient(lhs), .meshGradient(rhs)): return lhs == rhs
+ case let (.shader(lhs), .shader(rhs)): return lhs == rhs
case let (.colorMatrix(lhs), .colorMatrix(rhs)): return lhs == rhs
default: return false
}
@@ -768,8 +781,9 @@ extension _ShapeStyle_Pack.Fill: Animatable {
result.pointee = .angularGradient(gradient.animatableData)
} else if let gradient = paint as? MeshGradient._Paint {
result.pointee = .meshGradient(gradient.animatableData)
+ } else if let shader = paint as? Shader.ResolvedShader {
+ result.pointee = .shader(shader.animatableData)
}
- // TODO: Shader
}
}
}
diff --git a/Tests/OpenSwiftUICoreTests/Graphics/ShaderTests.swift b/Tests/OpenSwiftUICoreTests/Graphics/ShaderTests.swift
new file mode 100644
index 000000000..9f52c9551
--- /dev/null
+++ b/Tests/OpenSwiftUICoreTests/Graphics/ShaderTests.swift
@@ -0,0 +1,108 @@
+//
+// ShaderTests.swift
+// OpenSwiftUICoreTests
+
+import Foundation
+import OpenRenderBoxShims
+@testable import OpenSwiftUICore
+import Testing
+
+struct ShaderTests {
+ @Test
+ func dynamicLookupSharesLibraryIdentity() throws {
+ let library = ShaderLibrary.bundle(.main)
+ let backend = try #require(library.rbShaderLibrary)
+
+ #expect(library.sample.library == ShaderLibrary(rbShaderLibrary: backend))
+ #expect(ShaderLibrary.sample.library == .default)
+ #expect(library.sample(.float(2)).arguments == [.float(2)])
+ }
+
+ @Test
+ func disabledEffectDropsShaderAndSamplingState() {
+ var shader = ShaderLibrary.sample(.float(2))
+ shader.dithersColor = true
+ shader.alphaOnlyLayer = true
+ shader.options.insert(.distortionFilter)
+ let offset = CGSize(width: 4, height: 6)
+
+ let disabled = shader.resolve(in: EnvironmentValues(), maxSampleOffset: offset, enabled: false)
+ #expect(disabled.rbShader == nil)
+ #expect(disabled.maxSampleOffset == .zero)
+ #expect(disabled.options == [])
+
+ let enabled = shader.resolve(in: EnvironmentValues(), maxSampleOffset: offset)
+ #expect(enabled.maxSampleOffset == offset)
+ #expect(enabled.rbFilterFlags == [.distortion, .dithersColor, .alphaOnlyLayer])
+ #expect(enabled.rbFillFlags == .dithersColor)
+ guard case let .filter(.shader(filter)) = enabled.effectValue(size: CGSize(width: 8, height: 10)) else {
+ Issue.record("Expected a shader filter")
+ return
+ }
+ #expect(filter.size == CGSize(width: 8, height: 10))
+ #expect(filter.shader == enabled)
+ }
+
+ @Test(.enabled(if: renderBoxVendor == .rb))
+ func paintAnimationUpdatesASeparateShader() throws {
+ let shader = ShaderLibrary.sample(
+ .float2(2, 3),
+ .floatArray([4, 5]),
+ .data(Data([6])),
+ .boundingRect
+ )
+ let resolved = shader.resolvePaint(in: EnvironmentValues())
+ let original = try #require(resolved.rbShader)
+ var paint = _ShapeStyle_Pack.Fill.paint(_AnyResolvedPaint(resolved))
+ var animation = paint.animatableData
+ #expect(animation.magnitudeSquared == 54)
+
+ animation.scale(by: 2)
+ paint.animatableData = animation
+
+ guard case let .paint(animated) = paint,
+ let resolved = animated.protobufPaint as? Shader.ResolvedShader else {
+ Issue.record("Expected an animated shader paint")
+ return
+ }
+ let updated = try #require(resolved.rbShader)
+ #expect(updated !== original)
+ #expect(updated.numberOfArguments == 4)
+ #expect(original.argument(at: 0).bytes?.load(as: Float.self) == 2)
+ #expect(updated.argument(at: 0).bytes?.load(as: Float.self) == 4)
+ #expect(updated.argument(at: 1).count == 2)
+ #expect(updated.argument(at: 1).flags == 3)
+ #expect(updated.argument(at: 1).bytes?.load(as: Float.self) == 8)
+ #expect(updated.argument(at: 2).bytes?.load(as: UInt8.self) == 6)
+ #expect(updated.argument(at: 3).type == 6)
+ }
+
+ @Test(.enabled(if: renderBoxVendor == .rb))
+ func resolvedShaderArchivePreservesArgumentsAndOptions() throws {
+ let library = ShaderLibrary(data: Data([1, 2, 3]))
+ var shader = library.sample(.float3(2, 3, 4))
+ shader.dithersColor = true
+ let original = shader.resolve(in: EnvironmentValues(), maxSampleOffset: CGSize(width: 5, height: 6))
+ let data = try ProtobufEncoder.encoding { try original.encode(to: &$0) }
+ var decoder = ProtobufDecoder(data)
+ let decoded = try Shader.ResolvedShader(from: &decoder)
+ let argument = try #require(decoded.rbShader).argument(at: 0)
+
+ #expect(decoded.maxSampleOffset == CGSize(width: 5, height: 6))
+ #expect(decoded.options == [.dithersColor])
+ #expect(argument.type == 3)
+ #expect(argument.bytes?.load(as: Float.self) == 2)
+ }
+
+ #if canImport(ObjectiveC)
+ @Test(.enabled(if: renderBoxVendor == .rb && ORBDevice.sharedDefault() != nil))
+ @available(OpenSwiftUI_v6_0, *)
+ func compileReportsRenderBoxError() async {
+ let shader = ShaderLibrary(data: Data([1, 2, 3])).missingShader(.color(.red))
+
+ await #expect(throws: (any Error).self) {
+ try await shader.compile(as: .shapeStyle)
+ }
+ }
+ #endif
+}