チャレンジ:Metal-cppでの描画
2022年6月8日

Metalは、Appleプラットフォームでのグラフィックスや処理能力を高速化する基盤となります。C++に慣れ親しんだ方なら、驚異的なパワーをご覧になれる絶好のチャンスです。今回のチャレンジでは、Metal-cppを使って、Xcodeで三角形、球、メッシュのレンダリングをしてみましょう。
また、日中にグラフィックスとゲームのStudy Hallを訪問して、このチャレンジを共同研究してみるのも良いでしょう。質問を交わしたり、他の開発者とのつながりを作ったり、自分の制作をシェアしたりしてみましょう。
チャレンジを始める
始める前に、「Program Metal in C++ with metal-cpp」をご覧いただき、一連のC++サンプルを含むLearnMetalCPPプロジェクトをダウンロードしておく必要があります。
Program Metal in C++ with metal-cpp
Your C++ games and apps can now tap into the power of Metal. We'll show you how metal-cpp helps you bridge your C++ code to Metal, explore how each manages object lifecycles, and demonstrate utilities that can help these language cooperate in your app. We'll also share best practices for designing...
Download the LearnMetalCPP project
Xcodeでプロジェクトを開き、ベースコードは00-window.cppを選択します。画像をレンダリングするには、プロジェクト内でいくつかの設定を行う必要があります。
まず、「MTL::RenderPipelineDescriptor」を備えた「MTL::RenderPipelineState」オブジェクトを作成します。これを行う場合、「buildShaders()」などの関数を作成しておく必要があります。次のコードスニペットでは、単一の三角形をレンダリングするのに必要なシェーダコードを提供しています。
void Renderer::buildShaders()
{
using NS::StringEncoding::UTF8StringEncoding;
const char shaderSrc = R"(
#include <metal_stdlib>
using namespace metal;
struct AAPLVertex
{
float3 position;
half3 color;
};
// Welcome to modify the mesh as you want
constant AAPLVertex triangles[] = {
{ float3{ -0.8f, 0.8f, 0.0f }, half3{ 1.0, 0.3f, 0.2f } },
{ float3{ 0.0f, -0.8f, 0.0f }, half3{ 0.8f, 1.0, 0.0f } },
{ float3{ +0.8f, 0.8f, 0.0f }, half3{ 0.8f, 0.0f, 1.0 } }
};
struct v2f
{
float4 position [[position]];
half3 color;
};
v2f vertex vertexMain( uint vertexId [[vertex_id]])
{
v2f o;
o.position = float4( triangles[ vertexId ].position, 1.0 );
o.color = half3 ( triangles[ vertexId ].color );
return o;
}
half4 fragment fragmentMain( v2f in [[stage_in]] )
{
return half4( in.color, 1.0 );
}
)";
// TODO: Create a MTL::RenderPipelineDescriptor
// TODO: Allocate a MTL::RenderPipelineState object
}次に「MTL::RenderPipelineState」を設定し、ドローコールを挿入して、「Renderer::draw( MTK::View pView)」関数を拡張します。
void Renderer::draw( MTK::View pView )
{
...
// TODO: Set MTL::RenderPipelineState
// TODO: Draw a single triangle or more!
...
}その次に:
-「MTL::RenderPipelineDescriptor」オブジェクトを作成して、プロパティをいくつか設定します。
-「MTL::RenderPipelineState」オブジェクトを作成します。
-ヒント:オブジェクトのライフサイクルに注意してください。
Metal-cppアートをコミュニティと共有する準備はできましたか?自分で作成したものをTwitterにハッシュタグ「#WWDC22Challenges」付きで投稿したり、グラフィックスとゲームのStudy Hallで共有したりしてみましょう。また、このチャレンジや他のグラフィックスとゲームに関するトピックで意見交換をしてみたい方は、WWDC22の期間中に開催されるイベントにご参加ください。