Metal入门---绘制三角形

2020-08-21  本文已影响0人  HardCabbage
Metal绘制三角形效果图
先上demo源码如何使用Metal绘制三角形demo地址
一、简介

WWDC 2014 上,Apple为游戏开发者推出了新的平台技术 Metal,该技术能够为 3D 图像提高 10 倍的渲染性能,并支持大家熟悉的游戏引擎及公司。

Metal 是一种低层次的渲染应用程序编程接口,提供了软件所需的最低层,保证软件可以运行在不同的图形芯片上。Metal 提升了 A7 与 A8 处理器效能,让其性能完全发挥。------来自百度百科

二、重点函数解析以及相关文件解释
工程文件
/*
 介绍:
 头文件包含了 Metal shaders 与C/OBJC 源之间共享的类型和枚举常数
*/
#ifndef BaseShaderTypes_h
#define BaseShaderTypes_h

// 缓存区索引值 共享与 shader 和 C 代码 为了确保Metal Shader缓存区索引能够匹配 Metal API Buffer 设置的集合调用
typedef enum BaseVertexInputIndex
{
    //顶点
    BaseVertexInputIndexVertices     = 0,
    //视图大小
    BaseVertexInputIndexViewportSize = 1,
} BaseVertexInputIndex;


//结构体: 顶点/颜色值
typedef struct
{
    // 像素空间的位置
    // 像素中心点(100,100)
    vector_float4 position;

    // RGBA颜色
    vector_float4 color;
} BaseVertex;
#endif /* BaseShaderTypes_h */
#include <metal_stdlib>
using namespace metal;

#import "BaseShaderTypes.h"

//结构体
typedef struct {
    //处理空间的 顶点信息
    float4 clipSpacePosition [[position]];
    //颜色
    float4 color;
}RasterizerData;

//顶点着色器
vertex RasterizerData
vertexShader(uint vertexID [[vertex_id]],
             constant BaseVertex *vertices [[buffer(BaseVertexInputIndexVertices)]],
             constant vector_uint2 *viewportSizePointer [[buffer(BaseVertexInputIndexViewportSize)]])
{
    /*
     处理顶点数据:
        1) 执行坐标系转换,将生成的顶点剪辑空间写入到返回值中.
        2) 将顶点颜色值传递给返回值
     */
    RasterizerData out;
    out.clipSpacePosition = vertices[vertexID].position;
    out.color = vertices[vertexID].color;
    return out;
}

// 片元函数
//[[stage_in]],片元着色函数使用的单个片元输入数据是由顶点着色函数输出.然后经过光栅化生成的.单个片元输入函数数据可以使用"[[stage_in]]"属性修饰符.
//一个顶点着色函数可以读取单个顶点的输入数据,这些输入数据存储于参数传递的缓存中,使用顶点和实例ID在这些缓存中寻址.读取到单个顶点的数据.另外,单个顶点输入数据也可以通过使用"[[stage_in]]"属性修饰符的产生传递给顶点着色函数.
//被stage_in 修饰的结构体的成员不能是如下这些.Packed vectors 紧密填充类型向量,matrices 矩阵,structs 结构体,references or pointers to type 某类型的引用或指针. arrays,vectors,matrices 标量,向量,矩阵数组.
fragment float4 fragmentShader(RasterizerData in [[stage_in]])
{
    
    //返回输入的片元颜色
    return in.color;
}

在Metal中有两个渲染相关的特别重要的函数分别是- (void)drawInMTKView:(nonnull MTKView *)view- (void)mtkView:(nonnull MTKView *)view drawableSizeWillChange:(CGSize)size;

三、渲染流程
第一步:在初始化BaseRender对象时,配置相关参数
        _device = mtkView.device;
//从bundle中获取.metal文件
        id<MTLLibrary>defaultLibrary = [_device newDefaultLibrary];
        //从库中加载顶点函数
        id<MTLFunction>vertexFunction = [defaultLibrary newFunctionWithName:@"vertexShader"];
        //从库中加载片元函数
        id<MTLFunction>fragmentFunction = [defaultLibrary newFunctionWithName:@"fragmentShader"];
MTLRenderPipelineDescriptor *pipelineDescriptor = [[MTLRenderPipelineDescriptor alloc]init];
        //管道名称
        pipelineDescriptor.label = @"Simple Pipeline";
        //可编程函数,用于处理渲染过程中的各个顶点
        pipelineDescriptor.vertexFunction = vertexFunction;
        //可编程函数,用于处理渲染过程中的各个片元
        pipelineDescriptor.fragmentFunction = fragmentFunction;
        //一组存储颜色的组件
        pipelineDescriptor.colorAttachments[0].pixelFormat = mtkView.colorPixelFormat;
NSError *error;
        _pipelineState = [_device newRenderPipelineStateWithDescriptor:pipelineDescriptor error:&error];
        //判断是否返回错误
        if (!_pipelineState ) {
            //如果我们没有正确设置管道描述符,则管道状态创建可能失败
            NSLog(@"Failed to created pipeline state, error %@", error);
            return nil;
        }
       _commandQueue = [_device newCommandQueue];
第二步:渲染操作
 static const BaseVertex triangleVertices[] =
    {
        //顶点,    RGBA 颜色值
        { {  0.5, -0.25, 0.0, 1.0 }, { 1, 0, 0, 1 } },
        { { -0.5, -0.25, 0.0, 1.0 }, { 0, 1, 0, 1 } },
        { { -0.0f, 0.25, 0.0, 1.0 }, { 0, 0, 1, 1 } },
    };
id<MTLCommandBuffer>commandBuffer = [_commandQueue commandBuffer];
    
    //指定缓存区名字
    commandBuffer.label = @"MyCommand";
    MTLRenderPassDescriptor *renderPassDescriptor = view.currentRenderPassDescriptor;
id<MTLRenderCommandEncoder>renderEncoder = [commandBuffer renderCommandEncoderWithDescriptor:renderPassDescriptor];
        //渲染器名称
        renderEncoder.label = @"MyRenderEncoder";
 MTLViewport viewPort = {
            0.0,0.0,_viewportSize.x,_viewportSize.y,-1.0,1.0
        };
   [renderEncoder setViewport:viewPort];
        [renderEncoder setRenderPipelineState:_pipelineState];
//顶点数据+颜色数据
        //   1) 指向要传递给着色器的内存的指针
        //   2) 我们想要传递的数据的内存大小
        //   3)一个整数索引,它对应于我们的“vertexShader”函数中的缓冲区属性限定符的索引。
        [renderEncoder setVertexBytes:&triangleVertices length:sizeof(triangleVertices) atIndex:BaseVertexInputIndexVertices];
        
        //viewPortSize 数据
        //1) 发送到顶点着色函数中,视图大小
        //2) 视图大小内存空间大小
        //3) 对应的索引
        [renderEncoder setVertexBytes:&_viewportSize
                               length:sizeof(_viewportSize)
                              atIndex:BaseVertexInputIndexViewportSize];
   [renderEncoder drawPrimitives:MTLPrimitiveTypeTriangle vertexStart:0 vertexCount:3];
   [renderEncoder endEncoding];
   [commandBuffer presentDrawable:view.currentDrawable];
    [commandBuffer commit];
上一篇 下一篇

猜你喜欢

热点阅读