Metal 之旅之MTLLibrary

什么是MSL?

MSL是Metal Shading Language 的简称,为了更好的在GPU执行程序,苹果公司定义了一套类C++的语言(Metal Shading Language ),在GPU运行的程序都是用这个语言来编写的。

什么是MTLLibrary?

.metal后缀的文件编译后会生成metallib文件,MTLLibrary通过metallib文件来创建实例,提供了swift,oc调用metal文件中的函数能力,更多的可以看到做cpu与gpu通信的一个桥梁。

MTLLibrary加载的方式有哪些

MTLLibrary 加载的方式有很多种,这里给大家分享经常使用的两种方式

1,字符串方式加载

代码如下:

复制代码
func createLibrary(_ device:MTLDevice) -> MTLLibrary?{
        let shader = """
        #include <metal_stdlib>
        using namespace metal;

        struct VertexIn {
          float4 position [[ attribute(0) ]];
          float4 color [[ attribute(1) ]];
        };

        struct VertexOut {
            float4 position [[position]];
            float4 color; // 确保输出与片段着色器的输入匹配
        };
        vertex VertexOut vertex_main(const VertexIn in [[stage_in]]) {
            VertexOut out;
            out.position = in.position;
            out.color = in.color; // 将颜色从输入复制到输出
            return out;
        }


        fragment float4 fragment_main([[stage_in]] VertexOut in) {
            // 直接使用顶点着色器传递过来的颜色值
            return in.color;
        }
        """

        // metal使用shader
        do {
            let library = try device.makeLibrary(source: shader, options: nil)
            return library
        } catch let error {
            #if DEBUG
            fatalError()
            #endif
            return nil
        }

    }

特点:使用简单,无需额外创建metal文件,无需担心结构体,方法名重复,适合简单逻辑的处理,缺点是MSL语法错误没有高亮提示,不适合处理复杂逻辑,是运行时编译

2,metal文件方式加载

代码如下:

复制代码
func createLibrary(_ device:MTLDevice) -> MTLLibrary?{
      //项目中已经有了metal文件了
        guard let libraryURL = Bundle.main.url(forResource: "default", withExtension: "metallib") else {
            return nil
        }
        let library = try! device.makeLibrary(URL: libraryURL)
        return library
    }

特点:适合复杂的业务场景,MSL能够高亮显示语法错误,每个业务模块都可以单独创建一个单独的metal文件,通过命令单独编译为独立的metallib文件,避免创建library对象时导入过多不需要的内容,编译好的metallib和在ipa包的目录下,每次创建library时不用再运行时编译了。

注意:默认情况下不论有多少个metal文件,打包时都会编译为默认的default.metallib文件,此时需要注意不同文件中结构体,函数名不要重复,如果通过命令行编译不同的metallib文件则不需要考虑这种问题,使用命令行编译metal文件参考这篇博客《使用 Metal 命令行来构建库》网址:https://blog.csdn.net/SkyNullCode/article/details/122190736

相关推荐
库奇噜啦呼1 天前
【iOS】源码学习-消息流程分析
学习·ios·cocoa
2501_915918411 天前
iOS性能数据监控:从概念到工具实践,让应用运行更流畅
android·macos·ios·小程序·uni-app·cocoa·iphone
aiopencode1 天前
iOS开发中Xcode安装不完整问题解决方案与配置指南
后端·ios
Joseph182 天前
深度拆解 DanceUI:从声明式视图到原生渲染的全链路技术解析
ios·swiftui
人月神话Lee2 天前
【图像处理】颜色科学与灰度化——人眼看到的和数字记录的不一样
ios·ai编程·图像识别
bcbnb2 天前
iOS开发中手动实现代码混淆的完整步骤与示例
后端·ios
2501_915909062 天前
全面解析前端开发中常用的浏览器调试工具及其使用场景
android·ios·小程序·https·uni-app·iphone·webview
择势2 天前
NSProxy 核心原理、消息机制、多继承、AOP、Timer 解耦、快速转发全解
ios
songgeb2 天前
iOS IAP 本地货币展示:从一个需求到搞清楚 priceLocale
ios·swift
MonkeyKing71552 天前
iOS Block 底层深度解析:结构、变量捕获、copy逻辑与循环引用本质
ios·objective-c