Project Icon

Inferno

SwiftUI开源GPU图形特效库

Inferno是一个为SwiftUI设计的开源Fragment Shader集合。它提供水波纹、黑洞、闪光等GPU加速视觉效果,代码易读易懂。项目包含iOS和macOS示例应用。开发者只需复制相关Metal文件即可使用这些特效,简化SwiftUI应用的视觉设计。适用于iOS 17.0+和macOS 14.0+。

Inferno logo

Twitter: @twostraws

Inferno is an open-source collection of fragment shaders designed for SwiftUI apps. The shaders are designed to be easy to read and understand, even for relative beginners, so you’ll find each line of code rephrased in plain English as well as an overall explanation of the algorithm used at the top of each file.

If you’re already comfortable with shaders then please download one or more that interest you and get going. If not, most of the remainder of this README acts as a primer for using shaders in SwiftUI.

See it in action

This repository contains a cross-platform sample project demonstrating all the shaders in action. The sample project is built using SwiftUI and requires iOS 17 and macOS 14.

The sample project contains a lot of extra helper code to demonstrate all the shaders in various ways. To use the shaders in your own project, you just need to copy the relevant Metal files across, and optionally also Transitions.swift if you're using a transition shader.

The Inferno Sandbox app demonstrating the simple loupe shader.

How to use Inferno in your project

If you use SwiftUI, you can add special effects from Inferno to add water ripples, spinning black holes, flashing lights, embossing, noise, gradients, and more – all done on the GPU for maximum speed.

To use a shader from here, copy the appropriate .metal file into your project, then start with sample code for that shader shown below. If you're using an Inferno transition, you should also copy Transitions.swift to your project.

To find out more, click below to watch my YouTube video about building shaders for use with SwiftUI.

Video: SwiftUI + Metal – Learn to build your own shaders

What are shaders?

Details (Click to expand)

Fragment shaders are tiny programs that operate on individual elements of a SwiftUI layer. They are sometimes called “pixel shaders” – it’s not a wholly accurate name, but it does make them easier to understand.

Effectively, a fragment shader gets run on every pixel in a SwiftUI view, and can transform that pixel however it wants. That might sound slow, but it isn’t – all the fragment shaders here run at 60fps on all phones that support iOS 17, and 120fps on all ProMotion devices.

The transformation process can recolor the pixel however it wants. Users can customize the process by passing various parameters into each shader, and SwiftUI also provides some values for us to work with, such as the coordinate for the pixel being modified and its current color.

How are shaders written?

Details (Click to expand)

Shaders are written in the Metal Shading Language (MSL), which is a simple, fast, and extremely efficient language based on C++ that is optimized for high-performance GPU operations. Metal shaders are compiled at build-time and linked into a .metallib file. When you activate a shader in your app, the corresponding Metal function is loaded from the metallib and is then used to create a program to be executed on the GPU.

SwiftUI is able to work with a variety of Metal shaders, depending on what kind of effect you're trying to create.

MSL comes with a wide variety of built-in data types and functions, many of which operate on more than one data types. The data types used in Inferno are nice and simple:

  • bool: A Boolean, i.e. true or false.
  • float: A floating-point number.
  • float2: A two-component floating-point vector, used to hold things like X and Y coordinates or width and height.
  • half: A half-precision floating-point number.
  • half2: A two-component half-precision floating-point number.
  • half3: A three-component floating-point vector, used to hold RGB values.
  • half4: A four-component floating-point vector, used to hold RGBA values.
  • uint2: A two-component integer vector, used to hold X and Y coordinates or width and height.

Shaders commonly move fluidly between float, float2, half3, and half4 as needed. For example, if you create a half4 from a float then the number will just get repeated for each component in the vector. You’ll also frequently see code to create a half4 by using a half3 for the first three values (usually RGB) and specifying a fourth value as a float. Converting between half and float is free.

Be mindful when choosing the type of your variables: the GPU is heavily optimized for performing floating-point operations, and (especially on iOS), half-precision floating-point operations. That means you should prefer to use the half data types whenever the precision requirements allow it. This will also save register space and increase the so-called "occupancy" of the shader program, effectively letting more GPU cores run your shader simultaneously. Check out the Learn performance best practices for Metal shaders tech talk for more details.

Also, be careful with scalar numbers in your shader code. Make sure to use the correct type of number for an operation. For example, float y = (x - 1) / 2 works, but 1 and 2 are int here and are needlessly converted to float at runtime. Instead, write float y = (x - 1.0) / 2.0. Number literals for the corresponding types look like this:

  • float: 0.5, 0.5f, or 0.5F
  • half: 0.5h or 0.5H
  • int: 42
  • uint: 42u or 42U

Here are the functions used in Inferno:

  • abs() calculates the absolute value of a number, which is its non-negative value. So, positive values such as 1, 5, and 500 remain as they are, but negative values such as -3 or -3000 have their signs removed, making them 3 or 3000. If you pass it a vector (e.g. float2) this will be done for each component.
  • ceil() rounds a number up to its nearest integer. If you pass it a vector (e.g. float2) this will be done for each component.
  • cos() calculates the cosine of a value in radians. The cosine will always fall between -1 and 1. If you provide cos() with a vector (e.g. vec3) it will calculate the cosine of each component in the vector and return a vector of the same size containing the results.
  • distance() calculates the distance between two values. For example, if you provide it with a pair vec2 you’ll get the length of the vector created by subtracting one from the other. This always returns a single number no matter what data type you give it.
  • dot() calculates the dot product of two values. This means multiplying each component of the first value by the respective component in the second value, then adding the result.
  • floor() rounds a number down to its nearest integer. If you pass it a vector (e.g. float2) this will be done for each component.
  • fmod() calculates the remainder of a division operation. For example, fmod(10.5, 3.0) is 1.5.
  • fract() returns the fractional component of a value. For example, fract(12.5) is 0.5. If you pass this a vector then the operation will be performed component-wise, and a new vector will be returned containing the results.
  • min() is used to find the lower of two values. If you pass vectors, this is done component-wise, meaning that the resulting vector will evaluate each component in the vector and place the lowest in the resulting vector.
  • max() is used to find the higher of two values. If you pass vectors, this is done component-wise, meaning that the resulting vector will evaluate each component in the vector and place the highest in the resulting vector.
  • mix() smooth interpolates between two values based on a third value that’s specified between 0 and 1, providing a linear curve.
  • pow() calculates one value raised to the power of another, for example pow(2.0, 3.0) evaluates to 2 * 2 * 2, giving 8. As well as operating on a float, pow() can also calculate component-wise exponents – it raises the first item in the first vector to the power of the first item in the second vector, and so on.
  • sin() calculates the sine of a value in radians. The sine will always fall between -1 and 1. If you provide sin() with a vector (e.g. float2) it will calculate the sine of each component in the vector and return a vector of the same size containing the results.
  • smoothstep() interpolates between two values based on a third value that’s specified between 0 and 1, providing an S-curve shape. That is, the interpolation starts slow (values near 0.0), picks up speed (values near 0.5), then slows down towards the end (values near 1.0).
  • sample() provides the color value of a SwiftUI layer at a specific location. This is most commonly used to read the current pixel’s color.

More about all of this can be found in the Metal Shading Language Specification.

Sending values to shaders

Details (Click to expand)

Many shaders can operate without any special input from the user – it can manipulate the data it was sent by SwiftUI, then send back new data.

Because SwiftUI uses dynamic member lookup to find shader functions at runtime, this means a simple shader can be applied like this:

Image(systemName: "figure.walk.circle")
    .font(.system(size: 300))
    .colorEffect(
        ShaderLibrary.yourShaderFunction()
    )

However, often you’ll want to customize the way shaders work, a bit like passing in parameters to a function. Shaders are a little more complicated because these values need to be uploaded to the GPU, but the principle is the same.

SwiftUI handles this data transfer using helper methods that convert common Swift and SwiftUI data types to their Metal equivalents. For example, if you want to pass a Float, CGFloat, or Double from Swift to Metal, you'd do this:

Image(systemName: "figure.walk.circle")
    .font(.system(size: 300))
    .colorEffect(
        ShaderLibrary.yourShaderFunction(
            .float(someNumber)
        )
    )

SwiftUI provides three modifiers that let us apply Metal shaders to view hierarchies. Each one provides different input to your shader function, but each can also accept any number of further values to customize the way your shader works.

  • The colorEffect() modifier passes in the current pixel's position in user space (i.e., based on the actual size of your layer, measured in points), and its current color.
  • The distortionEffect() modifier passes in just the current pixel's position in user space.
  • The layerEffect() modifier passes in the current pixel's position in user space, and also the SwiftUI layer itself so you can read values from there freely.

In the documentation below, shader parameters are listed without the ones SwiftUI passes in automatically – you just see the ones you actually need to pass yourself.

Tip: When writing more complex shaders, you'll often find yourself needing to optimize your code for maximum efficiency. One of the best places to start with this is by looking into shader uniforms: rather than calculating a value that is the same for every fragment inside a shader, instead precompute values on the CPU and pass them directly into the shader. This means such calculations are done once per draw, rather than once per fragment.

Reading the shader code

Details (Click to expand)

All the shaders in Inferno were specifically written for readability. Specifically, they:

  1. Start with a brief comment outlining what each shader does.
  2. List all input parameters (where they are used), along with ranges and a suggested starting point.
  3. Have an explanation of the algorithm used.
  4. Provide detailed line-by-line English translations of what the code means.

The combination of what the code does (the interlinear comments) and what the code means (the algorithm introduction) should hopefully make these shaders comprehensible to everyone.

One small note: you will commonly see final color values multiplied by the original color’s alpha, just to make sure we get very smooth edges where this is transparency.

Shaders included in Inferno

Details (Click to expand)

Inferno provides a selection of shaders, most of which allow some customization using input parameters.

Animated Gradient Fill

Details (Click to expand)

An animated gradient fill shader.

A colorEffect() shader that generates a constantly cycling color gradient, centered on the input view.

Parameters:

  • size: The size of the whole image, in user-space.
  • time: The number of elapsed seconds since the shader was created.

Example code:

struct ContentView: View {
    @State private var startTime = Date.now

    var body: some View {
        TimelineView(.animation) { timeline in
            let elapsedTime = startTime.distance(to: timeline.date)

            Image(systemName: "figure.walk.circle")
                .font(.system(size: 300))
                .visualEffect { content, proxy in
                    content
                        .colorEffect(
                            ShaderLibrary.animatedGradientFill(
                                .float2(proxy.size),
                                .float(elapsedTime)
                        )
                    )
                }
        }
    }
}

Checkerboard

Details (Click to expand)

A checkerboard shader.

A colorEffect() shader that replaces the current image with a checkerboard pattern, flipping between the original color and a replacement.

Parameters:

  • replacement: The replacement color to be used for checkered squares.
  • size: The size of the checker squares.

Example code:

Image(systemName: "figure.walk.circle")
    .font(.system(size: 300))
    .colorEffect(
        ShaderLibrary.checkerboard(
            .color(.red),
            .float(50)
        )
    )

Circle Wave

Details (Click to expand)

A circle wave shader.

A colorEffect() shader that generates circular waves moving out or in, with varying size, brightness, speed, strength, and more.

Parameters:

  • size: The size of the whole image, in user-space.
  • time: The number of elapsed seconds since the shader was created.
  • brightness: How bright the colors should be. Ranges from 0 to 5 work best; try starting with 0.5 and experiment.
  • speed: How fast the wave should travel. Ranges from -2 to 2 work best, where negative numbers cause waves to come inwards; try starting with 1.
  • strength: How intense the waves should be. Ranges from 0.02 to 5 work best; try starting with 2.
  • density: How large each wave should be. Ranges from 20 to 500 work best; try starting with 100.
  • center: The center of the effect, where 0.5/0.5 is dead center
  • circleColor: The color to use for the waves. Use darker colors to create a less intense core.

Example code:

struct ContentView: View {
    @State private var startTime = Date.now

    var body: some View {
        TimelineView(.animation) { timeline in
            let elapsedTime = startTime.distance(to: timeline.date)

            Image(systemName: "figure.walk.circle")
                .font(.system(size: 300))
                .padding()
                .drawingGroup()
                .visualEffect { content, proxy in
                    content
                        .colorEffect(
                            ShaderLibrary.circleWave(
                                .float2(proxy.size),
                                .float(elapsedTime),
                                .float(0.5),
                                .float(1),
                                .float(2),
                                .float(100),
                                .float2(0.5, 0.5),
                                .color(.blue)
                           
项目侧边栏1项目侧边栏2
推荐项目
Project Cover

豆包MarsCode

豆包 MarsCode 是一款革命性的编程助手,通过AI技术提供代码补全、单测生成、代码解释和智能问答等功能,支持100+编程语言,与主流编辑器无缝集成,显著提升开发效率和代码质量。

Project Cover

AI写歌

Suno AI是一个革命性的AI音乐创作平台,能在短短30秒内帮助用户创作出一首完整的歌曲。无论是寻找创作灵感还是需要快速制作音乐,Suno AI都是音乐爱好者和专业人士的理想选择。

Project Cover

有言AI

有言平台提供一站式AIGC视频创作解决方案,通过智能技术简化视频制作流程。无论是企业宣传还是个人分享,有言都能帮助用户快速、轻松地制作出专业级别的视频内容。

Project Cover

Kimi

Kimi AI助手提供多语言对话支持,能够阅读和理解用户上传的文件内容,解析网页信息,并结合搜索结果为用户提供详尽的答案。无论是日常咨询还是专业问题,Kimi都能以友好、专业的方式提供帮助。

Project Cover

阿里绘蛙

绘蛙是阿里巴巴集团推出的革命性AI电商营销平台。利用尖端人工智能技术,为商家提供一键生成商品图和营销文案的服务,显著提升内容创作效率和营销效果。适用于淘宝、天猫等电商平台,让商品第一时间被种草。

Project Cover

吐司

探索Tensor.Art平台的独特AI模型,免费访问各种图像生成与AI训练工具,从Stable Diffusion等基础模型开始,轻松实现创新图像生成。体验前沿的AI技术,推动个人和企业的创新发展。

Project Cover

SubCat字幕猫

SubCat字幕猫APP是一款创新的视频播放器,它将改变您观看视频的方式!SubCat结合了先进的人工智能技术,为您提供即时视频字幕翻译,无论是本地视频还是网络流媒体,让您轻松享受各种语言的内容。

Project Cover

美间AI

美间AI创意设计平台,利用前沿AI技术,为设计师和营销人员提供一站式设计解决方案。从智能海报到3D效果图,再到文案生成,美间让创意设计更简单、更高效。

Project Cover

AIWritePaper论文写作

AIWritePaper论文写作是一站式AI论文写作辅助工具,简化了选题、文献检索至论文撰写的整个过程。通过简单设定,平台可快速生成高质量论文大纲和全文,配合图表、参考文献等一应俱全,同时提供开题报告和答辩PPT等增值服务,保障数据安全,有效提升写作效率和论文质量。

投诉举报邮箱: service@vectorlightyear.com
@2024 懂AI·鲁ICP备2024100362号-6·鲁公网安备37021002001498号