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.
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.
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.
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.
</details>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.
</details>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.
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.distortionEffect()
modifier passes in just the current pixel's position in user space.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.
</details>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.
All the shaders in Inferno were specifically written for readability. Specifically, they:
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.
</details>Inferno provides a selection of shaders, most of which allow some customization using input parameters.
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:
</details>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) ) ) } } } }
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:
</details>Image(systemName: "figure.walk.circle") .font(.system(size: 300)) .colorEffect( ShaderLibrary.checkerboard( .color(.red), .float(50) ) )
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 centercircleColor
: 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)
AI辅助编程,代码自动修复
Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。
AI小说写作助手,一站式润色、改写、扩写
蛙蛙写作—国内先进的AI写作平台,涵盖小说、学术、社交媒体等多场景。提供续写、改写、润色等功能,助力创作者高效优化写作流程。界面简洁,功能全面,适合各类写作者提升内容品质和工作效率。
全能AI智能助手,随时解答生活与工作的多样问题
问小白,由元石科技研发的AI智能助手,快速准确地解答各种生活和工作问题,包括但不限于搜索、规划和社交互动,帮助用户在日常生活中提高效率,轻松管理个人事务。
实时语音翻译/同声传译工具
Transly是一个多场景的AI大语言模型驱动的同声传译、专业翻译助手,它拥有超精准的音频识别翻译能力,几乎零延迟的使用体验和支持多国语言可以让你带它走遍全球,无论你是留学生、商务人士、韩剧美剧爱好者,还是出国游玩、多国会议、跨国追星等等,都可以满足你所有需要同传的场景需求,线上线下通用,扫除语言障碍,让全世界的语言交流不再有国界。
一键生成PPT和Word,让学习生活更轻松
讯飞智文是一个利用 AI 技术的项目,能够帮助用户生成 PPT 以及各类文档。无论是商业领域的市场分析报告、年度目标制定,还是学生群体的职业生涯规划、实习避坑指南,亦或是活动策划、旅游攻略等内容,它都能提供支持,帮助用户精准表达,轻松呈现各种信息。
深度推理能力全新升级,全面对标OpenAI o1
科大讯飞的星火大模型,支持语言理解、知识问答和文本创作等多功能,适用于多种文件和业务场景,提升办公和日常生活的效率。讯飞星火是一个提供丰富智能服务的平台,涵盖科技资讯、图像创作、写作辅助、编程解答、科研文献解读等功能,能为不同需求的用户提供便捷高效的帮助,助力用户轻松获取信息、解决问题,满足多样化使用场景。
一种基于大语言模型的高效单流解耦语音令牌文本到语音合成模型
Spark-TTS 是一个基于 PyTorch 的开源文本到语音合成项目,由多个知名机构联合参与。该项目提供了高效的 LLM(大语言模型)驱动的语音合成方案,支持语音克隆和语音创建功能,可通过命令行界面(CLI)和 Web UI 两种方式使用。用户可以根据需求调整语音的性别、音高、速度等参数,生成高质量的语音。该项目适用于多种场景,如有声读物制作、智能语音助手开发等。
AI助力,做PPT更简单!
咔片是一款轻量化在线演示设计工具,借助 AI 技术,实现从内容生成到智能设计的一站式 PPT 制作服务。支持多种文档格式导入生成 PPT,提供海量模板、智能美化、素材替换等功能,适用于销售、教师、学生等各类人群,能高效制作出高品质 PPT,满足不同场景演示需求。
选题、配图、成文,一站式创作,让内容运营更高效
讯飞绘文,一个AI集成平台,支持写作、选题、配图、排版和发布。高效生成适用于各类媒体的定制内容,加速品牌传播,提升内容营销效果。
专业的AI公文写作平台,公文写作神器
AI 材料星,专业的 AI 公文写作辅助平台,为体制内工作人员提供高效的公文写作解决方案。拥有海量公文文库、9 大核心 AI 功能,支持 30 + 文稿类型生成,助力快速完成领导讲话、工作总结、述职报告等材料,提升办公效率,是体制打工人的得力写作神器。
最新AI工具、AI资讯
独家AI资源、AI项目落地
微信扫一扫关注公众号