Chapitre -126 · Avant de commencerBefore You Begin
Voor je begint

Espace de travailWorkspace
Werkomgeving

L'API Metal n'a pas son LearnOpenGL.com !The Metal API has no LearnOpenGL.com of its own!
De Metal-API heeft geen eigen LearnOpenGL.com!

En dehors de la documentation d'AppleOutside Apple's documentation
Buiten de documentatie van Apple
— dense, uniquement en anglais,— dense, English-only,
— compact, enkel in het Engels,

Parfois datée et rarement pensée comme un parcours progressif —sometimes dated, and rarely designed as a progressive path —
soms verouderd en zelden opgebouwd als leertraject —

Il n'existe presque aucune ressource surthere is almost no resource on
bestaat er nauwelijks materiaal over
Metal, et en particulier surlet alone on
en zeker niet over
Metal & C++.

Objectif de ce chapitreWhat you’ll learn
Wat je leert
  • Choisir ton environnement de développement (Make ou Xcode)Choose your development environment (Make or Xcode)
    Je ontwikkelomgeving kiezen (Make of Xcode)
  • Créer le projetCreate the project
    Het project aanmaken
  • Supprimer le StoryboardRemove the Storyboard
    Het Storyboard verwijderen
  • Ajouter le flag adapté à ton environnement de travail (-fno-objc-arc ou -fobjc-weak)Add the right flag for your working environment (-fno-objc-arc or -fobjc-weak)
    De juiste flag voor je werkomgeving toevoegen (-fno-objc-arc of -fobjc-weak)
  • Intégrer les wrappers metal-cpp et metal-cpp-extensions à ton projetAdd the metal-cpp and metal-cpp-extensions wrappers to your project
    De wrappers metal-cpp en metal-cpp-extensions aan je project toevoegen
⏱ ~3 min
PrérequisPrerequisites
Vereisten
  • Aucune connaissance préalableNo prior knowledge
    Geen voorkennis
  • Un Mac Apple SiliconAn Apple Silicon Mac
    Een Mac met Apple Silicon

Tu vas apprendre à programmer le GPU directement, en C++ et en MSL, sur Apple Silicon.You are going to learn to program the GPU directly, in C++ and MSL, on Apple Silicon.
Je leert de GPU rechtstreeks programmeren, in C++ en MSL, op Apple Silicon.

Pas de framework tiers, pas d'abstraction opaque —No third-party framework, no opaque abstraction —
Geen externe frameworks, geen ondoorzichtige abstracties —

On utilisera metal-cpp, le wrapper C++ officiel d'Apple :we will use metal-cpp, Apple's official C++ wrapper:
we gebruiken metal-cpp, de officiële C++-wrapper van Apple:

Une fine couche de headers au-dessus de l'API Objective-C native.a thin layer of headers over the native Objective-C API.
een dunne laag headers bovenop de native Objective-C-API.

MêmeSame …
Dezelfde …
ABI, zéro overhead, et on reste en C++ pur.zero overhead, and pure C++ all the way.
geen overhead, en we blijven in puur C++.

Autres langages hôtes possiblesOther possible host languages
Andere mogelijke hosttalen

Swift — bindings natifs, très propres, c'est ce qu'Apple met en avant.native bindings, very clean, and what Apple promotes.
native bindings, erg verzorgd, en wat Apple zelf naar voren schuift.

Objective-C — l'API Metal d'origine, toujours supportée à 100 %.the original Metal API, still fully supported.
de oorspronkelijke Metal-API, nog altijd volledig ondersteund.

🔑 Astuce WikipédiaWikipedia tip
Wikipedia-tip

Ce livre contient de nombreux liens Wikipédia.This book links to many Wikipedia articles.
Dit boek bevat heel wat Wikipedia-links.
Il est recommandé de les consulter en anglais —We recommend reading them in English —
We raden aan ze in het Engels te lezen —

Les articles techniques anglophones sont systématiquement plus complets,English technical articles are consistently more complete,
Engelstalige technische artikels zijn systematisch vollediger,

Mieux sourcés et plus à jour que leurs équivalents français.better sourced, and more up to date than their translations.
beter onderbouwd en actueler dan hun vertalingen.

La très grande majorité de la documentation est également en anglais :The vast majority of the documentation is in English as well:
Het overgrote deel van de documentatie is eveneens in het Engels:
Pages man, Samples Apple Metal, Références C++, PDF de spécification, …man pages, Apple Metal samples, C++ references, specification PDFs, …
man-pagina's, Metal-samples van Apple, C++-referenties, specificaties in pdf, …

De nombreux raccourcis clavier sont répertoriés dans l'onglet Parcours.Plenty of keyboard shortcuts are listed in the Path tab.
Tal van sneltoetsen vind je in het tabblad Traject.

Ce dont tu as besoinWhat You Need
Wat je nodig hebt

MatérielHardware
Hardware

Ce livre est écrit sur un M2 Pro, qui exposeThis book is written on an M2 Pro, which supports
Dit boek is geschreven op een M2 Pro, die
Metal 4 et lesand
en de
Mesh Shaders
— mais pas encore leur accélération matérielle (à partir du M3).— but not yet their hardware acceleration (from the M3 onward).
ondersteunt — maar nog niet hun hardwareversnelling (vanaf de M3).

Tout le code de ce livre est testé sur cette configuration.All the code in this book is tested on this configuration.
Alle code in dit boek is op deze configuratie getest.

Un Mac équipé d'une puceAny Mac with an
Een Mac met een
Apple Silicon M1 ou plus récente suffit.M1 chip or later will do.
M1-chip of recenter volstaat.

Pourquoi Apple Silicon ?Why Apple Silicon?
Waarom Apple Silicon?

Sur les puces M, le CPU et le GPU partagent physiquement la même mémoire.On M-series chips, the CPU and the GPU physically share the same memory.
Op de M-chips delen CPU en GPU fysiek hetzelfde geheugen.

Un buffer GPU n'est pas une copie — c'est le même bloc d'octets.A GPU buffer isn't a copy — it's the same block of bytes.
Een GPU-buffer is geen kopie — het is hetzelfde blok bytes.

Cela change fondamentalement la façon de concevoir un pipeline de données.This fundamentally changes how you design a data pipeline.
Dat verandert fundamenteel hoe je een datapijplijn ontwerpt.

Tu peux également vérifier ta configuration en C++ grâce au programme proposé dans le parcours.You can also check your setup in C++ with the program provided in the path.
Je kunt je configuratie ook in C++ testen met het programma uit het traject.

LogicielSoftware
Software

Xcode (gratuit sur le Mac App Store) — version 27 minimum.(free on the Mac App Store) — version 27 or later.
(gratis in de Mac App Store) — minimaal versie 27.

Terminal (préinstallé). Il te fera gagner un temps considérable.(pre-installed). It will save you a considerable amount of time.
(vooraf geïnstalleerd). Daarmee win je heel wat tijd.

Création du projetCreating the Project
Het project aanmaken

Personnalisé (make)Custom (make)
Op maat (make)

Xcode génère une multitude de fichiers :Xcode generates a whole set of files:
Xcode genereert een hele reeks bestanden:

Ils constituent en réalité un programme que nous réécrirons de zéro.together, they form a program that we will rewrite from scratch.
samen vormen ze een programma dat we van nul af aan herschrijven.

Un Makefile n'est qu'un fichier supplémentaire qui facilite la compilation sans passer par Xcode.A Makefile is just one extra file that lets you build without Xcode.
Een Makefile is gewoon één extra bestand waarmee je compileert zonder Xcode.

C'est la méthode la plus répandue dans le monde du développement — et très satisfaisante.It is the most widespread approach in the programming world — and a very satisfying one.
Het is de meest gebruikte methode in de programmeerwereld — en erg bevredigend.

Parfaite pour démarrer et comprendre ce qui se passe réellement. Le chapitre ↘ MakefilePerfect for getting started and understanding what is really going on. The chapter
Ideaal om te beginnen en te begrijpen wat er echt gebeurt. Het hoofdstuk Makefile

Propose un exemple complet et commenté (en Shell). Attention aux tabulations !provides a complete, annotated example (in Shell). Mind the tabs!
bevat een volledig, toegelicht voorbeeld (in Shell). Let op de tabs!

Également disponible dans le dépôt Git du cursus :Also available in the course's Git repository:
Ook beschikbaar in de Git-repository van de cursus:

# Shell — update:15/10/26
git clone https://github.com/remdal/Metal-x-C---LearnMSL.dev.git learnmsl.dev-repository

Xcode (recommandé pour les projets plus importants)(recommended for larger projects)
(aanbevolen voor grotere projecten)

Profilage GPU, débogueur Metal intégré et documentation accessible en deux clics.GPU profiling, a built-in Metal debugger, and documentation two clicks away.
GPU-profiling, ingebouwde Metal-debugger en documentatie op twee klikken.

Nouveau projetNew Project
Nieuw project
→ MultiplateformeMultiplatform
Multiplatform
→ JeuGame
Game
→ Metal ouor
of
Metal 4 → Objective-C →
Crée un dépôt Git si tu veux sauvegarder ton travail.Create a Git repository if you want to keep track of your work.
Maak een Git-repository aan als je je werk wilt bewaren.

→ Supprime le fichier Main.storyboard généré automatiquement par XcodeDelete the Main.storyboard file that Xcode generates automatically
Verwijder het bestand Main.storyboard dat Xcode automatisch aanmaakt
→
Puis, dans le fichier .plist, supprime l'entrée surlignée en bleu sur la capture d'écranthen, in the .plist file, delete the entry highlighted in blue in the screenshot
verwijder daarna in het .plist-bestand de blauw gemarkeerde regel op de schermafbeelding
→
Main storyboard file base name (macOS).

Nous utiliserons une application partagée, entièrement pilotée depuis le code.We will use a shared application, driven entirely from code.
We gebruiken een gedeelde applicatie die volledig vanuit de code wordt aangestuurd.

Réglages du projet Xcode : l'entrée « Main storyboard file base name (macOS) » à supprimer, surlignée en bleu.
désolé pour le mode sombresorry about the dark mode
sorry voor de donkere modus

Récupérer metal-cpp et ses extensionsGetting metal-cpp and Its Extensions
metal-cpp en de extensies ophalen

Point important concernant laOne important point about
Een belangrijk punt over de
documentation Apple (metal-cpp)Apple's metal-cpp documentation
documentatie van Apple (metal-cpp)
, que tu dois suivre :, which you should follow:
, die je best volgt:

L'archive proposée au téléchargement ne contient pas les wrappers d'extensions (metal-cpp-extensions) de l'API Metal.the archive offered for download does not include the extension wrappers (metal-cpp-extensions) for the Metal API.
het archief dat je kunt downloaden bevat de extensie-wrappers (metal-cpp-extensions) van de Metal-API niet.

Comme tu peux le voir sur la capture d'écran, l'archive metal-cpp_26.4.zip,As you can see in the screenshot, the metal-cpp_26.4.zip archive,
Zoals je op de schermafbeelding ziet, bevat het archief metal-cpp_26.4.zip,

Qui contient le dossier metal-cpp, ne comprend pas les wrappers AppKit & MetalKit.which holds the metal-cpp folder, does not contain the AppKit & MetalKit wrappers.
met daarin de map metal-cpp, geen wrappers voor AppKit & MetalKit.

Deux solutions s'offrent à toi : soit les récupérer dans le projet d'exemple de laYou have two options: either take them from the … sample project,
Je hebt twee mogelijkheden: haal ze uit het voorbeeldproject van …
WWDC 2022,
Soit cloner le dépôt du cours :or clone the course repository:
of kloon de repository van de cursus:

# Shell — update:15/10/26
# Le cursus · The course · De cursus
git clone https://github.com/remdal/Metal-x-C---LearnMSL.dev.git learnmsl.dev-repository

# Les wrappers C++ du dépôt officiel d'Apple — sans metal-cpp-extensions, dont tu auras besoin
# The C++ wrappers from Apple's official repository — without metal-cpp-extensions, which you will need
# De C++-wrappers uit de officiële repository van Apple — zonder metal-cpp-extensions, die je wel nodig hebt
git clone https://github.com/apple/metal-cpp.git metal-cpp

Les wrappers se trouvent dans le dossierThe wrappers live in the …
De wrappers staan in de map …
Frameworks/ du dépôt du cours.folder of the course repository.
van de cursusrepository.

Régler les flags (Xcode uniquement)Setting the Flags (Xcode Only)
De flags instellen (enkel Xcode)

Trois réglages à modifier dans Build Settings, au même endroit que la capture précédente.Three settings to change in Build Settings, in the same place as the previous screenshot.
Drie instellingen om aan te passen in Build Settings, op dezelfde plek als de vorige schermafbeelding.

Utilise le champ de recherche en haut à droite :Use the search field at the top right:
Gebruik het zoekveld rechtsboven:

DansIn
In
Build Settings → RechercheSearch
Zoeken
→ C++

Champ « Other C++ Flags » des Build Settings, contenant le flag -fno-objc-arc.
-fno-objc-arc : metal-cpp gère lui-même les compteurs de références.metal-cpp manages reference counts itself.
metal-cpp beheert de reference counts zelf.

Si tu as plusieurs Targets (macOS & iOS par exemple), répète ces réglages pour chacune.If you have several Targets (macOS & iOS, for example), repeat these settings for each one.
Heb je meerdere Targets (bijvoorbeeld macOS & iOS), herhaal deze instellingen dan voor elk ervan.

À partir du moment où vous incluez Métal dans votre application, le mode de jeu performance s’enclenche.

Quelques rappelsA Few Reminders
Even herhalen

ProgrammeProgram
Programma

Un programme est composé de fichiers source — du texte —A program is made of source files — plain text —
Een programma bestaat uit bronbestanden — tekst —

Que le compilateur traduit en binaire : du code machine exécutable par le processeur.that the compiler translates into binary: machine code the processor can execute.
die de compiler vertaalt naar binaire code: machinecode die de processor kan uitvoeren.

Dans ce cours, deux compilateurs travaillent en parallèle :In this course, two compilers work side by side:
In deze cursus werken twee compilers naast elkaar:

clang compile le C++ et l'Objective-C++ en un exécutable pour le CPU,clang compiles C++ and Objective-C++ into an executable for the CPU,
clang compileert C++ en Objective-C++ tot een uitvoerbaar bestand voor de CPU,

metal compile le MSL en une bibliothèque .metallib pour le GPU.and metal compiles MSL into a .metallib library for the GPU.
metal compileert MSL tot een .metallib-bibliotheek voor de GPU.

Un pixel (picture element) est la plus petite unité adressable d'un écran :A pixel (picture element) is the smallest addressable unit of a screen:
Een pixel (picture element) is de kleinste adresseerbare eenheid van een scherm:

Une case dans une grille 2D — ton framebuffer — qui stocke une couleur.one cell in a 2D grid — your framebuffer — storing a color.
één vakje in een 2D-raster — je framebuffer — dat een kleur bijhoudt.

Un écran 1920×1080 contient 2 073 600 cases ; un écran 1280×720 en contient 921 600.A 1920×1080 screen holds 2,073,600 cells; a 1280×720 screen holds 921,600.
Een scherm van 1920×1080 telt 2.073.600 vakjes; een scherm van 1280×720 telt er 921.600.

Le GPU remplit ces cases à chaque frame.The GPU fills those cells every frame.
De GPU vult die vakjes bij elke frame.

En Metal, ces cases sont alimentées par des fragments :In Metal, those cells are fed by fragments:
In Metal worden die vakjes gevoed door fragments:

Ce que produit la fonction de fragment, un float4 (R, G, B, A).what the fragment function produces, a float4 (R, G, B, A).
wat de fragmentfunctie oplevert, een float4 (R, G, B, A).

Attention, un fragment n'est pas exactement un pixel —Careful, though — a fragment is not exactly a pixel.
Opgelet: een fragment is niet precies een pixel —

Plusieurs fragments peuvent contribuer à la même case (recouvrement,Several fragments can contribute to the same cell (overdraw,
meerdere fragments kunnen bijdragen aan hetzelfde vakje (overlap,
MSAA)
Et certains sont éliminés avant d'être écrits (test de profondeur, discard).and some are discarded before they are ever written (depth test, discard).
en sommige worden weggegooid voor ze geschreven worden (dieptetest, discard).

Sous-pixelsSubpixels
Subpixels

Physiquement, un pixel est composé de troisPhysically, a pixel is made of three
Fysiek bestaat een pixel uit drie
sous-pixelssubpixels
subpixels
— rougered
rood
, vertgreen
groen
, bleublue
blauw
.
C'est leur intensité relative qui produit la couleur perçue.Their relative intensity produces the perceived color.
Hun onderlinge intensiteit bepaalt de waargenomen kleur.

Certains panneaux ajoutent un quatrième sous-pixel blancSome panels add a fourth, white subpixel
Sommige panelen voegen een vierde, witte subpixel toe

(RGBW sur certains LCD, WRGB sur les OLED de téléviseurs) pour gagner en luminosité.(RGBW on some LCDs, WRGB on television OLEDs) to gain brightness.
(RGBW bij sommige lcd-schermen, WRGB bij oled-televisies) voor meer helderheid.

L'alpha, lui, n'existe pas côté écran :Alpha, on the other hand, does not exist on the display side:
Alfa bestaat daarentegen niet aan de kant van het scherm:

C'est une notion purement logicielle qui indique au GPU à quel point un fragment est opaque,it is a purely software notion that tells the GPU how opaque a fragment is,
het is een puur softwarematig begrip dat de GPU vertelt hoe ondoorzichtig een fragment is,
utilisée pour leused for
gebruikt voor
blending.