### Creating Time-Based Animations in ShaderGraphCoder with Swift Source: https://context7.com/praeclarum/shadergraphcoder/llms.txt This section shows how to create animated shaders using `SGValue.time` and `SGValue.frame` in Swift. It includes examples for pulsing materials, cycling colors through hue, and basic frame-based animation. These techniques are essential for dynamic visual effects. ```Swift import ShaderGraphCoder // Pulsing blue material func pulsingBlueMaterial() async throws -> ShaderGraphMaterial { let frequency = SGValue.floatParameter(name: "Frequency", defaultValue: 2) let pulse = sin(SGValue.time * frequency * (2 * Float.pi)) let color: SGColor = .color3f([0, 0, 1]) * pulse let surface = pbrSurface(baseColor: color) return try await ShaderGraphMaterial(surface: surface) } // Color cycling through hue func rainbowMaterial() async throws -> ShaderGraphMaterial { let hue = fract(SGValue.time * 0.1) // Cycle through hue over 10 seconds let saturation: SGScalar = .float(1.0) let value: SGScalar = .float(1.0) let hsvColor: SGColor = .color3f(hue, saturation, value) let rgbColor = hsvToRGB(hsvColor) return try await ShaderGraphMaterial(surface: pbrSurface(baseColor: rgbColor)) } // Frame-based animation let frameBasedValue = SGValue.frame * 0.016 // Approximate time from frame count ``` -------------------------------- ### Color Space Definition and Manipulation Source: https://context7.com/praeclarum/shadergraphcoder/llms.txt Demonstrates how to initialize colors with specific color spaces and perform common color space conversions and adjustments. These functions are essential for procedural texture generation and material styling in RealityKit. ```swift import ShaderGraphCoder // Create color with explicit color space let linearColor = SGValue.color3f([0.5, 0.5, 0.5], colorSpace: .linearSRGB) let srgbColor = SGValue.color3f([0.5, 0.5, 0.5], colorSpace: .textureSRGB) // HSV to RGB conversion let hsvColor: SGColor = .color3f(0.5, 1.0, 1.0) // Hue, Saturation, Value let rgbFromHsv = hsvToRGB(hsvColor) // RGB to HSV conversion let rgbColor: SGColor = .color3f([1, 0, 0]) let hsvFromRgb = rgbToHSV(rgbColor) // HSV adjustments (hue shift, saturation, value) let adjusted = hsvAdjust(rgbColor, amount: .vector3f(0.1, 0.2, 0.0)) // Saturation adjustment let saturated = saturate(rgbColor, amount: .float(1.5)) // Contrast adjustment let contrasted = contrast(rgbColor, amount: .float(1.2)) // Luminance calculation let luma = luminance(rgbColor) ``` -------------------------------- ### Preview Shaders with ShaderGraphPreview Source: https://context7.com/praeclarum/shadergraphcoder/llms.txt Demonstrates how to integrate shader previews into SwiftUI views. This allows developers to visualize shader output on geometry directly within the Xcode canvas. ```swift import SwiftUI import ShaderGraphCoder struct MaterialPreviewView: View { let surface = SGValue.color3f([0.2, 0.5, 0.8]).pbrSurface() var body: some View { ShaderGraphPreview(surface: surface) } } #Preview { let metallicSurface = pbrSurface(baseColor: .color3f([0.8, 0.8, 0.8]), roughness: .float(0.2), metallic: .float(1.0)) return ShaderGraphPreview(surface: metallicSurface) } #Preview("Pulsing") { let pulse = sin(SGValue.time * 2 * Float.pi) * 0.5 + 0.5 let color: SGColor = .color3f([1, 0, 0]) * pulse return ShaderGraphPreview(surface: pbrSurface(baseColor: color)) } ``` -------------------------------- ### World and Model Space Sources Source: https://context7.com/praeclarum/shadergraphcoder/llms.txt Access vertex and fragment shader inputs including positions, normals, UV coordinates, camera position, and transformation matrices. ```APIDOC ## World and Model Space Sources ### Description Access vertex and fragment shader inputs including positions, normals, UV coordinates, camera position, and transformation matrices. ### Method N/A (Code examples for accessing shader inputs) ### Endpoint N/A ### Parameters N/A ### Request Example ```swift import ShaderGraphCoder // Position sources let modelPos: SGVector = SGValue.modelPosition // Position in model space let worldPos: SGVector = SGValue.worldPosition // Position in world space let objectPos: SGVector = SGValue.objectPosition // Position in object space // Normal vectors let modelNormal: SGVector = SGValue.modelNormal // Normal in model space let worldNormal: SGVector = SGValue.worldNormal // Normal in world space // UV texture coordinates let uv0: SGVector = SGValue.uv0 // First UV set let uv1: SGVector = SGValue.uv1 // Second UV set let uvCustom: SGVector = SGValue.uv(index: 2) // Custom UV index // Camera and view information let cameraPos: SGVector = SGValue.worldCameraPosition let viewDir: SGVector = SGValue.worldViewDirection // Tangent space vectors let tangent: SGVector = SGValue.worldTangent0 let bitangent: SGVector = SGValue.worldBitangent0 // Transformation matrices let modelToWorld: SGMatrix = SGValue.surfaceModelToWorld let worldToView: SGMatrix = SGValue.surfaceWorldToView let viewToProjection: SGMatrix = SGValue.surfaceViewToProjection ``` ### Response N/A ``` -------------------------------- ### Create Texture Mapped Material (Swift) Source: https://github.com/praeclarum/shadergraphcoder/blob/main/README.md This function demonstrates creating a material by sampling a texture. It uses the UV coordinates to map the texture onto the surface. ```swift func textureMap(textureLocalURL: URL) async throws -> ShaderGraphMaterial { let surface = SGValue .texture(contentsOf: textureLocalURL) .sampleColor3f(texcoord: SGValue.uv0) .pbrSurface() return try await ShaderGraphMaterial(surface: surface) } ``` -------------------------------- ### SGColor Values and Parameters in Swift Source: https://context7.com/praeclarum/shadergraphcoder/llms.txt Demonstrates the usage of SGColor for RGB and RGBA values, including constants, runtime parameters, and computed colors. Shows how to create colors from components and access their individual channels. ```swift import ShaderGraphCoder // Constant colors let red: SGColor = .color3f([1, 0, 0]) let green: SGColor = .color3f(0, 1, 0) let transparentBlue: SGColor = .color4f(0, 0, 1, 0.5) // Predefined color constants let black = SGValue.black // RGB(0, 0, 0) let white = SGValue.white // RGB(1, 1, 1) let opaqueRed = SGValue.opaqueRed // RGBA(1, 0, 0, 1) // Runtime parameter (can be modified after material creation) let tintColor = SGValue.color3fParameter( name: "TintColor", defaultValue: [1, 1, 1] ) // Color from separate scalar components let r = SGValue.float(0.5) let g = SGValue.float(0.3) let b = SGValue.float(0.8) let customColor: SGColor = .color3f(r, g, b) // Accessing color components let colorValue: SGColor = .color3f([0.2, 0.5, 0.8]) let redChannel: SGScalar = colorValue.r let greenChannel: SGScalar = colorValue.g let blueChannel: SGScalar = colorValue.b let rgbOnly: SGColor = colorValue.rgb ``` -------------------------------- ### Texture Sampling in Swift Source: https://context7.com/praeclarum/shadergraphcoder/llms.txt Details how to load and sample textures using SGTexture in Swift for shader graphs. Shows loading textures from URLs and application bundles, defining texture parameters for runtime assignment, and sampling texture colors in RGB and RGBA formats. It also covers advanced sampling with custom UV coordinates, wrap modes (e.g., .repeated), and filtering options (.linear, .nearest). Dependencies include ShaderGraphCoder and RealityKit. ```swift import ShaderGraphCoder import RealityKit // Load texture from URL let textureURL = URL(fileURLWithPath: "/path/to/texture.png") let texture = SGValue.texture(contentsOf: textureURL) // Load texture from bundle let bundleTexture = SGValue.texture(named: "MyTexture", in: Bundle.main) // Texture parameter for runtime assignment let textureParam = SGValue.textureParameter(name: "MainTexture") // Sample texture as RGB color let sampledColor: SGColor = texture.sampleColor3f(texcoord: SGValue.uv0) // Sample texture as RGBA color let sampledColorAlpha: SGColor = texture.sampleColor4f(texcoord: SGValue.uv0) // Sample with custom UV and filtering options let customSample: SGColor = texture.sampleColor3f( texcoord: SGValue.uv0, uWrapMode: .repeated, vWrapMode: .repeated, magFilter: .linear, minFilter: .linear, mipFilter: .linear ) // Create textured PBR surface let texturedSurface = texture.sampleColor3f(texcoord: SGValue.uv0).pbrSurface() ``` -------------------------------- ### Create Solid Red Material (Swift) Source: https://github.com/praeclarum/shadergraphcoder/blob/main/README.md This function demonstrates how to create a basic solid red material for visionOS using ShaderGraphCoder. It defines a red color and applies it to a PBR surface. ```swift func solidRed() async throws -> ShaderGraphMaterial { let color: SGColor = .color3f([1, 0, 0]) let surface = pbrSurface(baseColor: color) return try await ShaderGraphMaterial(surface: surface) } ``` -------------------------------- ### Scalar Values and Math Operations in Swift Source: https://context7.com/praeclarum/shadergraphcoder/llms.txt Illustrates the use of SGScalar for representing and manipulating floating-point numbers in Swift. Includes creating constant scalars, utilizing predefined constants like zero, one, and pi, defining runtime float parameters, and performing basic arithmetic operations (addition, subtraction, multiplication, division, modulo). Also covers common mathematical functions such as absolute value, square root, power, sine, cosine, clamp, floor, ceil, round, and fract. Requires the ShaderGraphCoder library. ```swift import ShaderGraphCoder // Constant scalars let value: SGScalar = .float(0.5) let intValue: SGScalar = .int(42) // Predefined constants let zero = SGValue.zero let one = SGValue.one let pi = SGValue.pi let degToRad = SGValue.degToRad let radToDeg = SGValue.radToDeg // Runtime parameter let intensity = SGValue.floatParameter(name: "Intensity", defaultValue: 1.0) // Basic arithmetic let a: SGScalar = .float(10) let b: SGScalar = .float(3) let sum = a + b // 13 let diff = a - b // 7 let product = a * b // 30 let quotient = a / b // 3.333... let remainder = a % b // 1 // Math functions let absolute = abs(SGValue.float(-5)) // 5 let squareRoot = sqrt(SGValue.float(16)) // 4 let power = pow(SGValue.float(2), 3) // 8 let sine = sin(SGValue.time) // Animated sine wave let cosine = cos(SGValue.time * 2 * Float.pi) let clamped = clamp(value, min: 0.0, max: 1.0) let floored = floor(SGValue.float(3.7)) // 3 let ceiled = ceil(SGValue.float(3.2)) // 4 let rounded = round(SGValue.float(3.5)) // 4 let fractional = fract(SGValue.float(3.7)) // 0.7 ``` -------------------------------- ### Create Pulsing Blue Material (Swift) Source: https://github.com/praeclarum/shadergraphcoder/blob/main/README.md This function shows how to create a dynamic pulsing blue material. It utilizes time and a frequency parameter to animate the color's intensity. ```swift func pulsingBlue() async throws -> ShaderGraphMaterial { let frequency = SGValue.floatParameter(name: "Frequency", defaultValue: 2) let color: SGColor = .color3f([0, 0, 1]) * sin(SGValue.time * frequency * (2*Float.pi)) let surface = pbrSurface(baseColor: color) return try await ShaderGraphMaterial(surface: surface) } ``` -------------------------------- ### Use Method Chaining API Source: https://context7.com/praeclarum/shadergraphcoder/llms.txt Demonstrates the fluent, chainable syntax for SGValue types. This allows for cleaner, more readable code when applying multiple transformations to scalars, vectors, or colors. ```swift import ShaderGraphCoder let processedScalar = SGValue.half(1).add(.half(2)).divide(.half(2)).clamp(min: .float(0), max: .float(1)) let processedVector = SGValue.vector3f(1, 2, 3).add(.vector3f(4, 5, 6)).divide(.float(2)).normalize() let chainedSurface = SGValue.texture(contentsOf: URL(fileURLWithPath: "/texture.png")).sampleColor3f(texcoord: SGValue.uv0).pbrSurface() let processedColor = SGValue.color3f([0.5, 0.5, 0.5]).saturate(amount: .float(1.2)).contrast(amount: .float(1.1)).hsvAdjust(amount: .vector3f(0.1, 0, 0)) ``` -------------------------------- ### PBR Surface Shader Creation in Swift Source: https://context7.com/praeclarum/shadergraphcoder/llms.txt Creates a physically-based rendering surface shader supporting various properties like base color, emissive color, normals, roughness, and more. Can be created with multiple properties or simplified using method chaining. ```swift import ShaderGraphCoder // Full PBR surface with multiple properties let surface = pbrSurface( baseColor: .color3f([0.8, 0.2, 0.1]), // Red-orange base emissiveColor: .color3f([0.1, 0.0, 0.0]), // Slight red glow roughness: .float(0.3), // Fairly smooth metallic: .float(0.9), // Highly metallic ambientOcclusion: .float(1.0), // Full ambient light specular: .float(0.5), // Medium specular clearcoat: .float(0.8), // Strong clearcoat clearcoatRoughness: .float(0.1) // Smooth clearcoat ) // Simplified PBR using method chaining on color let simpleSurface = SGValue.color3f([0, 0, 1]).pbrSurface() ``` -------------------------------- ### Shader Preview using SwiftUI (Swift) Source: https://github.com/praeclarum/shadergraphcoder/blob/main/README.md This snippet shows how to preview a ShaderGraphCoder material directly within a SwiftUI view using the ShaderGraphPreview component. It can be embedded in existing views or used with the #Preview macro. ```swift import SwiftUI import ShaderGraphCoder struct MyView: View { let blueSurface = SGValue.color3f([0, 0, 1]).pbrSurface() var body: some View { ShaderGraphPreview(surface: blueSurface) } } ``` ```swift #Preview { let blueSurface = SGValue.color3f([0, 0, 1]).pbrSurface() return ShaderGraphPreview(surface: blueSurface) } ``` -------------------------------- ### Implement Conditional Branching in ShaderGraphCoder Source: https://context7.com/praeclarum/shadergraphcoder/llms.txt Shows how to perform runtime branching using comparison functions. Since standard if/else statements are not supported in shader graphs, these functions allow for conditional logic based on thresholds. ```swift import ShaderGraphCoder let value: SGScalar = .float(0.7) let threshold: SGScalar = .float(0.5) let result1 = ifGreaterOrEqual(value, threshold, trueResult: 1.0, falseResult: 0.0) let colorA: SGColor = .color3f([1, 0, 0]) let colorB: SGColor = .color3f([0, 1, 0]) let result2 = ifGreaterOrEqual(value, threshold, trueResult: colorA, falseResult: colorB) let less = ifLess(value, threshold, trueResult: 1.0, falseResult: 0.0) let lessOrEqual = ifLessOrEqual(value, threshold, trueResult: 1.0, falseResult: 0.0) let greater = ifGreater(value, threshold, trueResult: 1.0, falseResult: 0.0) let equal = ifEqual(value, threshold, trueResult: 1.0, falseResult: 0.0) let smoothTransition = smoothStep(value, low: .float(0.3), high: .float(0.7)) ``` -------------------------------- ### Vector Values and Operations in Swift Source: https://context7.com/praeclarum/shadergraphcoder/llms.txt Demonstrates how to create and manipulate 2D, 3D, and 4D vectors using SGVector in Swift. Covers constant vector creation, accessing components (x, y, z, xy, xyz), building vectors from scalars, and performing common vector math operations like addition, scalar multiplication, dot product, cross product, normalization, and length calculation. Dependencies include the ShaderGraphCoder library. ```swift import ShaderGraphCoder // Constant vectors let vec2: SGVector = .vector2f(0.5, 0.5) let vec3: SGVector = .vector3f(1, 2, 3) let vec4: SGVector = .vector4f(1, 2, 3, 1) // Vector parameter for runtime modification let offset = SGValue.vector3fParameter( name: "PositionOffset", defaultValue: [0, 0, 0] ) // Component access let position: SGVector = .vector3f(1, 2, 3) let x: SGScalar = position.x let y: SGScalar = position.y let z: SGScalar = position.z let xy: SGVector = position.xy // Extract 2D vector let xyz: SGVector = position.xyz // Extract 3D vector // Build vector from scalars let combined: SGVector = .vector3f( SGValue.float(1.0), SGValue.float(2.0), SGValue.float(3.0) ) // Vector math operations let a: SGVector = .vector3f(1, 2, 3) let b: SGVector = .vector3f(4, 5, 6) let sum = a + b // Vector addition let scaled = a * 2.0 // Scalar multiplication let dotProduct = dot(a, b) // Dot product let crossProduct = cross(a, b) // Cross product let normalized = normalize(a) // Unit vector let magnitude = length(a) // Vector length ``` -------------------------------- ### Generating Procedural Noise Patterns with ShaderGraphCoder in Swift Source: https://context7.com/praeclarum/shadergraphcoder/llms.txt This code demonstrates how to generate various procedural noise patterns using ShaderGraphCoder in Swift, including Perlin-style, cellular, fractal, and Worley noise. It also shows how to create a noisy material using these functions. Noise functions are fundamental for creating organic and detailed textures. ```Swift import ShaderGraphCoder // 3D Perlin-style noise let noiseValue = noise3D( amplitude: SGValue.float(1.0), pivot: .float(0.5), position: SGValue.worldPosition ) // Cellular noise for Voronoi patterns let cellNoise = cellNoise3D(position: SGValue.worldPosition) // Fractal noise (multiple octaves) let fractalNoise = fractal3D( amplitude: .float(1.0), octaves: 4, lacunarity: .float(2.0), diminish: .float(0.5), position: SGValue.worldPosition ) // Worley noise variations let worleyFloat = worleyNoise3DFloat(position: SGValue.worldPosition, jitter: .float(1.0)) let worleyVec2 = worleyNoise3DVector2(position: SGValue.worldPosition, jitter: .float(1.0)) // Create a noisy material func noisyMaterial() async throws -> ShaderGraphMaterial { let noise = noise3D( amplitude: SGValue.float(0.5), position: SGValue.worldPosition * 5 ) as! SGScalar let color: SGColor = .color3f(noise, noise, noise) return try await ShaderGraphMaterial(surface: pbrSurface(baseColor: color)) } ``` -------------------------------- ### Create ShaderGraphMaterial in Swift Source: https://context7.com/praeclarum/shadergraphcoder/llms.txt Initializes a RealityKit material from shader graph tokens. Supports both surface and optional geometry modifiers. The material is compiled from SGValue types and operators. ```swift import SwiftUI import RealityKit import ShaderGraphCoder // Create a solid red PBR material func createRedMaterial() async throws -> ShaderGraphMaterial { let color: SGColor = .color3f([1, 0, 0]) let surface = pbrSurface(baseColor: color) return try await ShaderGraphMaterial(surface: surface) } // Create a material with both surface and geometry modifier func createAnimatedMaterial() async throws -> ShaderGraphMaterial { let surface = pbrSurface(baseColor: .color3f([0.5, 0.5, 1.0])) let offset = SGValue.modelPosition * sin(SGValue.time) let geom = geometryModifier(modelPositionOffset: offset) return try await ShaderGraphMaterial(surface: surface, geometryModifier: geom) } ``` -------------------------------- ### Matrix Operations Source: https://context7.com/praeclarum/shadergraphcoder/llms.txt Work with 2x2, 3x3, and 4x4 matrices for transformations, rotations, and projections. ```APIDOC ## Matrix Operations Work with 2x2, 3x3, and 4x4 matrices for transformations, rotations, and projections. ### Description Supports creation of identity matrices, custom matrices, and matrix parameters. Includes operations like multiplication, addition, inversion, transposition, and determinant calculation, as well as point and normal transformations. ### Usage Examples ```swift import ShaderGraphCoder // Identity matrices let identity2 = SGValue.identity2d let identity3 = SGValue.identity3d let identity4 = SGValue.identity4d // Custom matrix let rotation2d = SGValue.matrix2d( col0: [cos(0.5), sin(0.5)], col1: [-sin(0.5), cos(0.5)] ) // Matrix parameter let transformParam = SGValue.matrix4dParameter( name: "CustomTransform", defaultValue: simd_float4x4(1) // Identity ) // Matrix operations let matA = SGValue.identity3d let matB = SGValue.identity3d let product = matA * matB let sum = matA + matB let scaled = matA * 2.0 let inverted = invertMatrix(matA) let transposed = transpose(matA) let det = determinant(matA) // Transform operations let point: SGVector = .vector3f(1, 2, 3) let transformed = transformPoint(point, fromspace: .object, tospace: .world) let transformedNormal = transformNormal(SGValue.modelNormal, fromspace: .object, tospace: .world) ``` ``` -------------------------------- ### Time-Based Animation Source: https://context7.com/praeclarum/shadergraphcoder/llms.txt Use `SGValue.time` and `SGValue.frame` to create animated shaders that change over time. ```APIDOC ## Time-Based Animation ### Description Use `SGValue.time` and `SGValue.frame` to create animated shaders that change over time. ### Method N/A (Code examples for time-based animation) ### Endpoint N/A ### Parameters N/A ### Request Example ```swift import ShaderGraphCoder // Pulsing blue material func pulsingBlueMaterial() async throws -> ShaderGraphMaterial { let frequency = SGValue.floatParameter(name: "Frequency", defaultValue: 2) let pulse = sin(SGValue.time * frequency * (2 * Float.pi)) let color: SGColor = .color3f([0, 0, 1]) * pulse let surface = pbrSurface(baseColor: color) return try await ShaderGraphMaterial(surface: surface) } // Color cycling through hue func rainbowMaterial() async throws -> ShaderGraphMaterial { let hue = fract(SGValue.time * 0.1) // Cycle through hue over 10 seconds let saturation: SGScalar = .float(1.0) let value: SGScalar = .float(1.0) let hsvColor: SGColor = .color3f(hue, saturation, value) let rgbColor = hsvToRGB(hsvColor) return try await ShaderGraphMaterial(surface: pbrSurface(baseColor: rgbColor)) } // Frame-based animation let frameBasedValue = SGValue.frame * 0.016 // Approximate time from frame count ``` ### Response N/A ``` -------------------------------- ### Color Space and Conversion API Source: https://context7.com/praeclarum/shadergraphcoder/llms.txt Functions for converting between color spaces and applying color adjustments to shader values. ```APIDOC ## Color Space Conversion and Adjustment ### Description Provides methods to define colors in specific color spaces and perform mathematical adjustments to color properties like hue, saturation, and luminance. ### Methods - **hsvToRGB**: Converts an HSV color value to RGB. - **rgbToHSV**: Converts an RGB color value to HSV. - **hsvAdjust**: Applies shifts to hue, saturation, and value. - **saturate**: Adjusts the saturation of a color. - **contrast**: Adjusts the contrast of a color. - **luminance**: Calculates the luminance of an RGB color. ### Request Example (Swift) ```swift let linearColor = SGValue.color3f([0.5, 0.5, 0.5], colorSpace: .linearSRGB) let rgbFromHsv = hsvToRGB(hsvColor) let luma = luminance(rgbColor) ``` ### Response Returns an `SGValue` or `SGColor` object representing the transformed color or scalar value. ``` -------------------------------- ### ShaderGraphPreview SwiftUI View Source: https://context7.com/praeclarum/shadergraphcoder/llms.txt Preview shaders in Xcode's canvas using the `ShaderGraphPreview` SwiftUI view, which displays the shader on a box and sphere. ```APIDOC ## ShaderGraphPreview SwiftUI View Preview shaders in Xcode's canvas using the `ShaderGraphPreview` SwiftUI view, which displays the shader on a box and sphere. ### Description Integrates shader previews directly into SwiftUI views and Xcode's canvas. Useful for rapid iteration and visualization of shader effects. ### Usage Examples ```swift import SwiftUI import ShaderGraphCoder // Embed preview in a SwiftUI view struct MaterialPreviewView: View { let surface = SGValue.color3f([0.2, 0.5, 0.8]).pbrSurface() var body: some View { ShaderGraphPreview(surface: surface) } } // Use with #Preview macro for Xcode canvas #Preview { let metallicSurface = pbrSurface( baseColor: .color3f([0.8, 0.8, 0.8]), roughness: .float(0.2), metallic: .float(1.0) ) return ShaderGraphPreview(surface: metallicSurface) } // Preview animated shader #Preview("Pulsing") { let pulse = sin(SGValue.time * 2 * Float.pi) * 0.5 + 0.5 let color: SGColor = .color3f([1, 0, 0]) * pulse return ShaderGraphPreview(surface: pbrSurface(baseColor: color)) } ``` ``` -------------------------------- ### Perform Blend Operations in ShaderGraphCoder Source: https://context7.com/praeclarum/shadergraphcoder/llms.txt Demonstrates how to combine colors and values using various blend modes like linear interpolation, additive, multiply, and alpha compositing. These operations are essential for layering textures and colors within a shader graph. ```swift import ShaderGraphCoder let fg: SGColor = .color3f([1, 0, 0]) let bg: SGColor = .color3f([0, 0, 1]) let mixFactor: SGScalar = .float(0.5) let mixed = mix(fg: fg, bg: bg, mix: mixFactor) let added = plus(fg: fg, bg: bg, mix: mixFactor) let multiplied = multiply(fg, bg) let screened = screen(fg: fg, bg: bg, mix: mixFactor) let overlayed = overlay(fg: fg, bg: bg, mix: mixFactor) let dodged = dodge(fg: fg, bg: bg, mix: mixFactor) let burned = burn(fg: fg, bg: bg, mix: mixFactor) let difference = difference(fg: fg, bg: bg, mix: mixFactor) let over = over(fg: .color4f(1, 0, 0, 0.5), bg: .color4f(0, 0, 1, 1)) let mask = mask(fg: fg, bg: bg, mix: mixFactor) ``` -------------------------------- ### Shader Graph Coder Operators Source: https://github.com/praeclarum/shadergraphcoder/blob/main/README.md A comprehensive list of supported operators for shader graph operations. ```APIDOC ## Shader Graph Coder Operators ### Description This section lists the available operators for manipulating shader graph values like scalars, vectors, colors, and matrices. These operators range from basic arithmetic to complex image processing and noise generation functions. ### Operators **Arithmetic Operators:** - `+` (Addition) - `-` (Subtraction) - `*` (Multiplication) - `/` (Division) - `%` (Modulo) **Logical Operators:** - `&&` (Logical And) - `||` (Logical Or) - `^^` (Logical Xor) - `logicalAnd(in1, in2)` - `logicalOr(in1, in2)` - `logicalXor(in1, in2)` - `logicalNot(in1)` **Conditional Operators:** - `ifGreaterOrEqual(value1, value2, ...)`: Executes logic based on a greater than or equal to condition. - `ifLess(value1, value2, ...)`: Executes logic based on a less than condition. - `ifEqual(value1, value2, ...)`: Executes logic based on an equal to condition. - `switchValue(in1, in2, ...)`: Selects a value based on an input. **Vector and Matrix Operators:** - `add(in1, in2)`: Adds two vectors or matrices. - `subtract(in1, in2)`: Subtracts two vectors or matrices. - `multiply(in1, in2)`: Multiplies two vectors or matrices. - `divide(in1, in2)`: Divides two vectors or matrices. - `cross(in1, in2)`: Computes the cross product of two vectors. - `dot(in1, in2)`: Computes the dot product of two vectors. - `determinant(in1)`: Computes the determinant of a matrix. - `invertMatrix(in1)`: Inverts a matrix. - `normalize(in1)`: Normalizes a vector. - `length(in1)`: Computes the magnitude (length) of a vector. - `extract(in1, index)`: Extracts a component from a vector or matrix. - `rotate2D(in1, amount)`: Rotates a 2D vector. - `rotate3D(in1, amount, ...)`: Rotates a 3D vector. **Image and Texture Operators:** - `image(file, defaultValue, ...)`: Reads from an image file. - `sample(file, uWrapMode, ...)`: Samples a 2D image. - `sampleCube(file, uWrapMode, ...)`: Samples a cube map. - `sampleGradient(file, uWrapMode, ...)`: Samples a 2D gradient image. - `tiledImage(file, defaultValue, ...)`: Reads from a tiled image. - `pixel(file, uWrapMode, ...)`: Reads a single pixel from a 2D image. - `normalMap(in1, space, ...)`: Converts a texture to a normal map. - `normalMapDecode(in1)`: Decodes a normal map texture. - `heightToNormal(in1, scale)`: Generates a normal map from a height map. **Color and HSV Operators:** - `hsvAdjust(in1, amount)`: Adjusts HSV values of a color. - `hsvToRGB(in1)`: Converts HSV color to RGB. - `rgbToHSV(in1)`: Converts RGB color to HSV. **Noise and Procedural Operators:** - `cellNoise2D(texcoord)`: Generates 2D cellular noise. - `cellNoise3D(position)`: Generates 3D cellular noise. - `noise2D(amplitude, pivot, ...)`: Generates 2D noise. - `noise3D(amplitude, pivot, ...)`: Generates 3D noise. - `fractal3D(amplitude, octaves, ...)`: Generates 3D fractal noise. **Utility and Mathematical Operators:** - `abs(in1)`: Absolute value. - `acos(in1)`: Arc cosine. - `asin(in1)`: Arc sine. - `atan2(iny, inx)`: Arc tangent 2. - `blur(in1, size, ...)`: Blurs an image. - `ceil(in1)`: Ceiling function. - `clamp(in1, min, ...)`: Clamps a value within a range. - `cos(in1)`: Cosine. - `exp(in1)`: Exponential function. - `floor(in1)`: Floor function. - `fract(in1)`: Fractional part of a number. - `log(in1)`: Natural logarithm. - `max(in1, in2)`: Maximum of two values. - `min(in1, in2)`: Minimum of two values. - `mix(fg, bg, ...)`: Linear interpolation. - `pow(in1, in2)`: Power function. - `reflect(in1, normal)`: Computes reflection. - `refract(in1, normal, ...)`: Computes refraction. - `remap(in1, inlow, ...)`: Remaps a value from one range to another. - `round(in1)`: Rounds a number. - `safePow(in1, in2)`: Safe power function. - `sign(in1)`: Sign of a number. - `sin(in1)`: Sine. - `smoothStep(in1, low, ...)`: Smooth step function. - `sqrt(in1)`: Square root. - `step(in1, edge)`: Step function. - `tan(in1)`: Tangent. - `oneMinus(in1)`: Computes 1 - value. - `premult(in1)`: Premultiplies alpha. - `luminance(in1, lumacoeffs)`: Computes luminance. - `range(in1, inlow, ...)`: Maps a value to a specific range. - `saturate(in1, amount, ...)`: Saturates a value. - `geometryModifier(modelPositionOffset, color, ...)`: Modifies geometry. - `geometrySwitchCameraIndex(mono, left, ...)`: Switches based on camera index. - `inside(in1, mask)`: Checks if a point is inside a mask. - `outside(in1, mask)`: Checks if a point is outside a mask. **Compositing Operators:** - `burn(fg, bg, ...)`: Burn blend mode. - `difference(fg, bg, ...)`: Difference blend mode. - `disjointover(fg, bg, ...)`: Disjoint Over blend mode. - `dodge(fg, bg, ...)`: Dodge blend mode. - `mask(fg, bg, ...)`: Mask blend mode. - `matte(fg, bg, ...)`: Matte blend mode. - `mixColor(fg, bg, ...)`: Mix Color blend mode. - `minus(fg, bg, ...)`: Subtractive Mix blend mode. - `out(fg, bg, ...)`: Out blend mode. - `over(fg, bg, ...)`: Over blend mode. - `overlay(fg, bg, ...)`: Overlay blend mode. - `plus(fg, bg, ...)`: Additive Mix blend mode. - `screen(fg, bg, ...)`: Screen blend mode. ``` -------------------------------- ### Conditional Operations Source: https://context7.com/praeclarum/shadergraphcoder/llms.txt Implement runtime branching using comparison operations, as traditional if/else statements are not supported in shader graphs. ```APIDOC ## Conditional Operations Implement runtime branching using comparison operations since traditional if/else is not supported in shader graphs. ### Description Provides functions for conditional logic based on comparisons (e.g., greater than, less than, equal to). Useful for creating dynamic shader effects and controlling values based on conditions. ### Usage Examples ```swift import ShaderGraphCoder let value: SGScalar = .float(0.7) let threshold: SGScalar = .float(0.5) // If value >= threshold, return 1.0, else return 0.0 let result1 = ifGreaterOrEqual(value, threshold, trueResult: 1.0, falseResult: 0.0) // Compare with typed results let colorA: SGColor = .color3f([1, 0, 0]) let colorB: SGColor = .color3f([0, 1, 0]) let result2 = ifGreaterOrEqual(value, threshold, trueResult: colorA, falseResult: colorB) // Other comparison operations let less = ifLess(value, threshold, trueResult: 1.0, falseResult: 0.0) let lessOrEqual = ifLessOrEqual(value, threshold, trueResult: 1.0, falseResult: 0.0) let greater = ifGreater(value, threshold, trueResult: 1.0, falseResult: 0.0) let equal = ifEqual(value, threshold, trueResult: 1.0, falseResult: 0.0) // Smooth step for gradual transitions let smoothTransition = smoothStep(value, low: .float(0.3), high: .float(0.7)) ``` ``` -------------------------------- ### Method Chaining API Source: https://context7.com/praeclarum/shadergraphcoder/llms.txt Many operations can be called as methods on SGValue types for a fluent, chainable syntax. ```APIDOC ## Method Chaining API Many operations can be called as methods on SGValue types for a fluent, chainable syntax. ### Description Allows for a more readable and concise way to express complex shader operations by chaining method calls. Applicable to scalars, vectors, colors, and texture sampling. ### Usage Examples ```swift import ShaderGraphCoder // Chain operations on scalars let processedScalar = SGValue.half(1) .add(.half(2)) .divide(.half(2)) .clamp(min: .float(0), max: .float(1)) // Chain operations on vectors let processedVector = SGValue.vector3f(1, 2, 3) .add(.vector3f(4, 5, 6)) .divide(.float(2)) .normalize() // Chain to create surface from color let chainedSurface = SGValue .texture(contentsOf: URL(fileURLWithPath: "/texture.png")) .sampleColor3f(texcoord: SGValue.uv0) .pbrSurface() // Chain color operations let processedColor = SGValue.color3f([0.5, 0.5, 0.5]) .saturate(amount: .float(1.2)) .contrast(amount: .float(1.1)) .hsvAdjust(amount: .vector3f(0.1, 0, 0)) ``` ``` -------------------------------- ### Texture Sampling API Source: https://context7.com/praeclarum/shadergraphcoder/llms.txt API for loading textures and sampling them with custom UV coordinates and filtering modes. ```APIDOC ## Texture Sampling ### Description Provides functionality to load textures from URLs or bundles and sample them into colors using specified UV coordinates and filtering parameters. ### Usage - **Loading**: `SGValue.texture(contentsOf:)` or `SGValue.texture(named:in:)`. - **Sampling**: Use `sampleColor3f` or `sampleColor4f` with `texcoord`. ### Request Example let color = texture.sampleColor3f(texcoord: SGValue.uv0, magFilter: .linear) ### Response - **Result**: Returns an `SGColor` object derived from the texture sample. ``` -------------------------------- ### Perform Matrix Operations in ShaderGraphCoder Source: https://context7.com/praeclarum/shadergraphcoder/llms.txt Covers matrix creation, arithmetic, and coordinate space transformations. This is used for handling 2x2, 3x3, and 4x4 matrices for rotations, scaling, and projections. ```swift import ShaderGraphCoder let identity2 = SGValue.identity2d let identity3 = SGValue.identity3d let identity4 = SGValue.identity4d let rotation2d = SGValue.matrix2d(col0: [cos(0.5), sin(0.5)], col1: [-sin(0.5), cos(0.5)]) let transformParam = SGValue.matrix4dParameter(name: "CustomTransform", defaultValue: simd_float4x4(1)) let matA = SGValue.identity3d let matB = SGValue.identity3d let product = matA * matB let sum = matA + matB let scaled = matA * 2.0 let inverted = invertMatrix(matA) let transposed = transpose(matA) let det = determinant(matA) let point: SGVector = .vector3f(1, 2, 3) let transformed = transformPoint(point, fromspace: .object, tospace: .world) let transformedNormal = transformNormal(SGValue.modelNormal, fromspace: .object, tospace: .world) ``` -------------------------------- ### Mathematical and Trigonometric Functions in ShaderGraph Coder Source: https://github.com/praeclarum/shadergraphcoder/blob/main/README.md Provides a comprehensive set of mathematical and trigonometric functions such as absolute value, sine, cosine, tangent, logarithm, exponentiation, and rounding. These are essential for a wide range of shader computations. ```ShaderGraph abs(in1) acos(in1) asin(in1) atan2(iny, inx) ceil(in1) cos(in1) exp(in1) floor(in1) fract(in1) log(in1) pow(in1, in2) round(in1) sign(in1) sin(in1) sqrt(in1) tan(in1) smoothStep(in1, low, high) step(in1, edge) ``` -------------------------------- ### Conditional Logic Operators in ShaderGraph Coder Source: https://github.com/praeclarum/shadergraphcoder/blob/main/README.md Provides conditional operators like 'ifGreaterOrEqual' and 'ifLess' for implementing runtime logic within shaders, which is essential as RealityKit does not support runtime conditionals directly. These operators take a condition and return one of two values based on the condition's outcome. ```ShaderGraph ifGreaterOrEqual(value1, value2, valueIfTrue, valueIfFalse) ifLess(value1, value2, valueIfTrue, valueIfFalse) ifEqual(value1, value2, valueIfTrue, valueIfFalse) ifGreater(value1, value2, valueIfTrue, valueIfFalse) ``` -------------------------------- ### Accessing World and Model Space Shader Inputs in Swift Source: https://context7.com/praeclarum/shadergraphcoder/llms.txt This snippet demonstrates how to access various vertex and fragment shader inputs using ShaderGraphCoder in Swift. It covers positions, normals, UV coordinates, camera information, and transformation matrices. These values are crucial for manipulating geometry and rendering effects. ```Swift import ShaderGraphCoder // Position sources let modelPos: SGVector = SGValue.modelPosition // Position in model space let worldPos: SGVector = SGValue.worldPosition // Position in world space let objectPos: SGVector = SGValue.objectPosition // Position in object space // Normal vectors let modelNormal: SGVector = SGValue.modelNormal // Normal in model space let worldNormal: SGVector = SGValue.worldNormal // Normal in world space // UV texture coordinates let uv0: SGVector = SGValue.uv0 // First UV set let uv1: SGVector = SGValue.uv1 // Second UV set let uvCustom: SGVector = SGValue.uv(index: 2) // Custom UV index // Camera and view information let cameraPos: SGVector = SGValue.worldCameraPosition let viewDir: SGVector = SGValue.worldViewDirection // Tangent space vectors let tangent: SGVector = SGValue.worldTangent0 let bitangent: SGVector = SGValue.worldBitangent0 // Transformation matrices let modelToWorld: SGMatrix = SGValue.surfaceModelToWorld let worldToView: SGMatrix = SGValue.surfaceWorldToView let viewToProjection: SGMatrix = SGValue.surfaceViewToProjection ``` -------------------------------- ### Unlit Surface Shader Creation in Swift Source: https://context7.com/praeclarum/shadergraphcoder/llms.txt Creates a surface shader that bypasses lighting calculations, suitable for UI elements or stylized rendering. Supports color, opacity, and tone mapping options. Can be created directly or via method chaining. ```swift import ShaderGraphCoder // Basic unlit surface let unlitSurface = unlitSurface( color: .color3f([1, 0, 1]), // Magenta color opacity: .float(0.8), // Semi-transparent applyPostProcessToneMap: true, // Apply tone mapping hasPremultipliedAlpha: false // Standard alpha ) // Unlit surface using method chaining let chainedUnlit = SGValue.color3f([0.2, 0.8, 0.3]).unlitSurface(opacity: .float(1.0)) ```