VisuTwin Canvas
C++ 3D Engine — Metal Backend
Loading...
Searching...
No Matches
metalShader.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2025-2026 Arnis Lektauers
3//
4// Created by Arnis Lektauers on 19.10.2025.
5//
6#include "metalShader.h"
7
8#include "spdlog/spdlog.h"
9
10namespace visutwin::canvas
11{
12 MetalShader::MetalShader(GraphicsDevice* graphicsDevice, const ShaderDefinition& definition, std::string sourceCode)
13 : Shader(graphicsDevice, definition), _sourceCode(std::move(sourceCode))
14 {
15 }
16
18 {
19 for (const auto& [_, library] : _libraries) {
20 if (library) {
21 library->release();
22 }
23 }
24 }
25
26 MTL::Library* MetalShader::getLibrary(MTL::Device* device, const NS::Bundle* bundle, NS::Error** error)
27 {
28 (void)bundle;
29 if (!device) {
30 return nullptr;
31 }
32
33 const auto found = _libraries.find(device);
34 if (found != _libraries.end()) {
35 return found->second;
36 }
37
38 if (_sourceCode.empty()) {
39 spdlog::error("MetalShader source is empty. Source-less metallib fallback was removed.");
40 return nullptr;
41 }
42
43 auto* compileOptions = MTL::CompileOptions::alloc()->init();
44 compileOptions->setFastMathEnabled(true);
45 MTL::Library* library = device->newLibrary(NS::String::string(_sourceCode.c_str(), NS::UTF8StringEncoding),
46 compileOptions, error);
47 compileOptions->release();
48
49 if (library) {
50 _libraries[device] = library;
51 } else {
52 const auto errorStr = (error && *error)
53 ? (*error)->localizedDescription()->utf8String()
54 : "unknown error";
55 spdlog::error("Metal shader compilation failed (VS={}, FS={}): {}",
56 vertexEntry(), fragmentEntry(), errorStr);
57 }
58
59 return library;
60 }
61}
Abstract GPU interface for resource creation, state management, and draw submission.
MTL::Library * getLibrary(MTL::Device *device, const NS::Bundle *bundle, NS::Error **error)
MetalShader(GraphicsDevice *graphicsDevice, const ShaderDefinition &definition, std::string sourceCode="")
GraphicsDevice * graphicsDevice() const
Definition shader.h:39
Shader(GraphicsDevice *graphicsDevice, const ShaderDefinition &definition)
Definition shader.cpp:17
const std::string & fragmentEntry() const
Definition shader.h:37
const std::string & vertexEntry() const
Definition shader.h:36