载入中...
搜索中...
未找到
GlslCompiler.cpp
浏览该文件的文档.
2
3#include <cerrno>
4#include <cstdio>
5#include <cstring>
6#include <stdexcept>
7
8#if defined(EVE_HAS_SHADERC)
9#include <shaderc/shaderc.h>
10#endif
11
12#if defined(_WIN32)
13#include <windows.h>
14#else
15#include <sys/wait.h>
16#include <unistd.h>
17#endif
18
19namespace eve::graphics {
20namespace {
21
23constexpr std::uint32_t kSpirvMagic = 0x07230203u;
24
25std::runtime_error compileFailure(const std::string &message) { return std::runtime_error(message); }
26
28std::vector<std::uint32_t> spirvWords(const void *data, std::size_t size) {
29 if (!data || size < 4 || (size % 4) != 0)
30 throw compileFailure("compiled SPIR-V has an invalid size");
31 const auto *words = static_cast<const std::uint32_t *>(data);
32 if (words[0] != kSpirvMagic) throw compileFailure("compiled SPIR-V has a bad magic number");
33 return std::vector<std::uint32_t>(words, words + size / 4);
34}
35
37const char *stageName(GlslStage stage) {
38 switch (stage) {
39 case GlslStage::eVertex: return "vertex";
40 case GlslStage::eFragment: return "fragment";
41 case GlslStage::eCompute: return "compute";
42 }
43 return "shader";
44}
45
46#if !defined(EVE_HAS_SHADERC)
47
49const char *stageArgument(GlslStage stage) {
50 switch (stage) {
51 case GlslStage::eVertex: return "vert";
52 case GlslStage::eFragment: return "frag";
53 case GlslStage::eCompute: return "comp";
54 }
55 return "frag";
56}
57
59std::vector<std::uint32_t> readCompiledFile(const std::string &path, bool remove) {
60 FILE *file = nullptr;
61#if defined(_WIN32)
62 if (fopen_s(&file, path.c_str(), "rb") != 0) file = nullptr;
63#else
64 file = fopen(path.c_str(), "rb");
65#endif
66 if (!file) {
67 if (remove) std::remove(path.c_str());
68 throw compileFailure("failed to open compiled SPIR-V");
69 }
70 std::fseek(file, 0, SEEK_END);
71 const long size = std::ftell(file);
72 std::fseek(file, 0, SEEK_SET);
73 std::vector<std::uint8_t> bytes(static_cast<std::size_t>(size > 0 ? size : 0));
74 const bool shortRead =
75 size > 0 && std::fread(bytes.data(), 1, static_cast<std::size_t>(size), file) != static_cast<std::size_t>(size);
76 std::fclose(file);
77 if (remove) std::remove(path.c_str());
78 if (shortRead) throw compileFailure("failed to read compiled SPIR-V");
79 return spirvWords(bytes.data(), bytes.size());
80}
81
82#if defined(_WIN32)
83
85std::string findGlslc() {
86 if (const char *sdk = std::getenv("VULKAN_SDK"); sdk && *sdk) {
87 for (const char *sub : {"\\bin\\glslc.exe", "\\Bin\\glslc.exe"}) {
88 std::string path = std::string(sdk) + sub;
89 if (GetFileAttributesA(path.c_str()) != INVALID_FILE_ATTRIBUTES) return path;
90 }
91 }
92 // C:\VulkanSDK<version>\Bin\glslc.exe
93 WIN32_FIND_DATAA entry{};
94 HANDLE find = FindFirstFileA("C:\\VulkanSDK\\*", &entry);
95 if (find != INVALID_HANDLE_VALUE) {
96 do {
97 if (entry.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
98 std::string path = std::string("C:\\VulkanSDK\\") + entry.cFileName + "\\Bin\\glslc.exe";
99 if (GetFileAttributesA(path.c_str()) != INVALID_FILE_ATTRIBUTES) {
100 FindClose(find);
101 return path;
102 }
103 }
104 } while (FindNextFileA(find, &entry));
105 FindClose(find);
106 }
107 FILE *pipe = _popen("where glslc 2>nul", "r");
108 if (pipe) {
109 char buffer[512];
110 std::string first;
111 // `where` lists every match on its own line and only the first path is usable as
112 // an application name, so stop at the first non-empty line instead of
113 // concatenating the remaining matches into a value with embedded newlines.
114 while (first.empty() && fgets(buffer, sizeof(buffer), pipe)) {
115 first = buffer;
116 while (!first.empty() && (first.back() == '\r' || first.back() == '\n')) first.pop_back();
117 }
118 const int status = _pclose(pipe);
119 if (status == 0 && !first.empty()) return first;
120 }
121 return {};
122}
123
131std::vector<std::uint32_t> compileWithExternalGlslc(const std::string &source, GlslStage stage,
132 const std::string &debugName) {
133 const std::string glslc = findGlslc();
134 if (glslc.empty())
135 throw compileFailure(
136 "no GLSL compiler available: this build has no in-process shaderc and no "
137 "glslc.exe was found (install the Vulkan SDK or set VULKAN_SDK)");
138
139 char tempDir[MAX_PATH];
140 if (GetTempPathA(MAX_PATH, tempDir) == 0) throw compileFailure("GetTempPath failed");
141 char inputPath[MAX_PATH];
142 if (GetTempFileNameA(tempDir, "eve", 0, inputPath) == 0) throw compileFailure("GetTempFileName failed");
143 const std::string outputPath = std::string(inputPath) + ".spv";
144 const std::string errorPath = outputPath + ".err";
145 struct TemporaryFiles {
146 const char *input;
147 const std::string &output;
148 const std::string &error;
149 ~TemporaryFiles() {
150 DeleteFileA(error.c_str());
151 DeleteFileA(output.c_str());
152 // Reserve the unique basename until both sidecars are consumed.
153 DeleteFileA(input);
154 }
155 } temporary{inputPath, outputPath, errorPath};
156
157 {
158 FILE *file = nullptr;
159 if (fopen_s(&file, inputPath, "wb") != 0 || !file) throw compileFailure("failed to write temp GLSL");
160 // A short write (disk full, for instance) must not reach the compiler as a
161 // truncated shader; the POSIX branch fails on the same condition.
162 const size_t written = fwrite(source.data(), 1, source.size(), file);
163 const bool flushed = fflush(file) == 0;
164 const bool closed = fclose(file) == 0;
165 if (written != source.size() || !flushed || !closed)
166 throw compileFailure("failed to write the complete temp GLSL");
167 }
168
169 std::string command = "\"" + glslc + "\" -fshader-stage=" + stageArgument(stage) + " \"" + inputPath +
170 "\" -o \"" + outputPath + "\"";
171 STARTUPINFOEXA startup{};
172 startup.StartupInfo.cb = sizeof(startup);
173 PROCESS_INFORMATION process{};
174 SECURITY_ATTRIBUTES security{};
175 security.nLength = sizeof(security);
176 security.bInheritHandle = TRUE;
177 HANDLE diagnostics =
178 CreateFileA(errorPath.c_str(), GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_DELETE, &security, CREATE_ALWAYS,
179 FILE_ATTRIBUTE_NORMAL, nullptr);
180 HANDLE input =
181 CreateFileA("NUL", GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, &security, OPEN_EXISTING,
182 FILE_ATTRIBUTE_NORMAL, nullptr);
183 if (diagnostics == INVALID_HANDLE_VALUE || input == INVALID_HANDLE_VALUE) {
184 if (diagnostics != INVALID_HANDLE_VALUE) CloseHandle(diagnostics);
185 if (input != INVALID_HANDLE_VALUE) CloseHandle(input);
186 throw compileFailure("failed to create compiler standard handles");
187 }
188 struct StandardHandles {
189 HANDLE output, input;
190 ~StandardHandles() {
191 CloseHandle(output);
192 CloseHandle(input);
193 }
194 } handles{diagnostics, input};
195 // Without an explicit list, concurrent CreateProcess calls inherit other
196 // jobs' temporary-file handles and can prevent glslc from opening its input.
197 SIZE_T attributeBytes = 0;
198 InitializeProcThreadAttributeList(nullptr, 1, 0, &attributeBytes);
199 std::vector<std::uint8_t> attributes(attributeBytes);
200 startup.lpAttributeList = reinterpret_cast<LPPROC_THREAD_ATTRIBUTE_LIST>(attributes.data());
201 if (!InitializeProcThreadAttributeList(startup.lpAttributeList, 1, 0, &attributeBytes))
202 throw compileFailure("failed to initialize process attributes");
203 struct AttributeList {
204 LPPROC_THREAD_ATTRIBUTE_LIST value;
205 ~AttributeList() { DeleteProcThreadAttributeList(value); }
206 } attributeList{startup.lpAttributeList};
207 HANDLE inherited[] = {diagnostics, input};
208 if (!UpdateProcThreadAttribute(startup.lpAttributeList, 0, PROC_THREAD_ATTRIBUTE_HANDLE_LIST, inherited,
209 sizeof(inherited), nullptr, nullptr))
210 throw compileFailure("failed to restrict compiler handle inheritance");
211 startup.StartupInfo.dwFlags = STARTF_USESTDHANDLES;
212 startup.StartupInfo.hStdInput = input;
213 startup.StartupInfo.hStdOutput = diagnostics;
214 startup.StartupInfo.hStdError = diagnostics;
215 if (!CreateProcessA(glslc.c_str(), command.data(), nullptr, nullptr, TRUE,
216 CREATE_NO_WINDOW | EXTENDED_STARTUPINFO_PRESENT, nullptr, nullptr, &startup.StartupInfo,
217 &process)) {
218 throw compileFailure("failed to launch glslc (error " + std::to_string(GetLastError()) + ")");
219 }
220 WaitForSingleObject(process.hProcess, INFINITE);
221 DWORD exitCode = 0;
222 GetExitCodeProcess(process.hProcess, &exitCode);
223 CloseHandle(process.hProcess);
224 CloseHandle(process.hThread);
225 if (exitCode != 0) {
226 std::string errors;
227 HANDLE reader =
228 CreateFileA(errorPath.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
229 nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
230 if (reader != INVALID_HANDLE_VALUE) {
231 char buffer[512];
232 DWORD count = 0;
233 while (ReadFile(reader, buffer, sizeof(buffer), &count, nullptr) && count)
234 errors.append(buffer, count);
235 CloseHandle(reader);
236 }
237 throw compileFailure("glslc failed for " + debugName + " (exit " + std::to_string(exitCode) +
238 "):\n" + errors);
239 }
240 return readCompiledFile(outputPath, false);
241}
242
243#else // !_WIN32
244
246std::vector<std::uint32_t> compileWithExternalGlslc(const std::string &source, GlslStage stage,
247 const std::string &debugName) {
248 char inputPath[] = "/tmp/eve_shader_XXXXXX";
249 const int descriptor = mkstemp(inputPath);
250 if (descriptor < 0) throw compileFailure("mkstemp failed");
251 const std::string outputPath = std::string(inputPath) + ".spv";
252 {
253 const ssize_t written = write(descriptor, source.data(), source.size());
254 close(descriptor);
255 if (written < 0 || static_cast<std::size_t>(written) != source.size()) {
256 unlink(inputPath);
257 throw compileFailure("failed to write temp GLSL");
258 }
259 }
260
261 const std::string command = std::string("exec glslc -fshader-stage=") + stageArgument(stage) + " \"" + inputPath +
262 "\" -o \"" + outputPath + "\" 2>&1";
263 FILE *pipe = popen(command.c_str(), "r");
264 if (!pipe) {
265 unlink(inputPath);
266 throw compileFailure("glslc not available (popen failed)");
267 }
268 char buffer[256];
269 std::string errors;
270 while (fgets(buffer, sizeof(buffer), pipe)) errors += buffer;
271 const int status = pclose(pipe);
272 const int waitError = errno;
273 unlink(inputPath);
274 if (status != 0) {
275 unlink(outputPath.c_str());
276 std::string outcome;
277 if (status == -1)
278 outcome = "wait failed: " + std::string(std::strerror(waitError));
279 else if (WIFSIGNALED(status))
280 outcome = "signal " + std::to_string(WTERMSIG(status));
281 else if (WIFEXITED(status))
282 outcome = "exit " + std::to_string(WEXITSTATUS(status));
283 else
284 outcome = "wait status " + std::to_string(status);
285 throw compileFailure("glslc failed for " + debugName + " (" + outcome + "):\n" + errors);
286 }
287 return readCompiledFile(outputPath, true);
288}
289
291bool externalGlslcAvailable() {
292 FILE *pipe = popen("command -v glslc >/dev/null 2>&1", "r");
293 if (!pipe) return false;
294 return pclose(pipe) == 0;
295}
296
297#endif // _WIN32
298
299#endif // !EVE_HAS_SHADERC
300
301#if defined(EVE_HAS_SHADERC)
302std::vector<std::uint32_t> compileInProcess(const std::string &source, GlslStage stage, const std::string &debugName) {
303 struct CompilerContext {
304 shaderc_compiler_t compiler = shaderc_compiler_initialize();
305 shaderc_compile_options_t options = nullptr;
306 CompilerContext() {
307 if (!compiler) throw compileFailure("shaderc_compiler_initialize failed");
308 options = shaderc_compile_options_initialize();
309 if (!options) {
310 shaderc_compiler_release(compiler);
311 throw compileFailure("shaderc_compile_options_initialize failed");
312 }
313 shaderc_compile_options_set_target_env(options, shaderc_target_env_vulkan, shaderc_env_version_vulkan_1_0);
314 shaderc_compile_options_set_target_spirv(options, shaderc_spirv_version_1_0);
315 }
316 ~CompilerContext() {
317 shaderc_compile_options_release(options);
318 shaderc_compiler_release(compiler);
319 }
320 };
321 // Keep glslang's compiler/built-in state alive across jobs and graph segments.
322 // Each CPU thread owns its context; no device references survive here.
323 thread_local CompilerContext context;
324 shaderc_shader_kind kind = shaderc_glsl_vertex_shader;
325 switch (stage) {
326 case GlslStage::eVertex: kind = shaderc_glsl_vertex_shader; break;
327 case GlslStage::eFragment: kind = shaderc_glsl_fragment_shader; break;
328 case GlslStage::eCompute: kind = shaderc_glsl_compute_shader; break;
329 }
330 shaderc_compilation_result_t result = shaderc_compile_into_spv(
331 context.compiler, source.data(), source.size(), kind, debugName.c_str(), "main", context.options);
332 if (!result) throw compileFailure("shaderc returned no compilation result");
333 struct CompilationResult {
334 shaderc_compilation_result_t value;
335 ~CompilationResult() { shaderc_result_release(value); }
337 if (shaderc_result_get_compilation_status(result) != shaderc_compilation_status_success)
338 throw compileFailure("shaderc failed:\n" + std::string(shaderc_result_get_error_message(result)));
339 const std::size_t length = shaderc_result_get_length(result);
340 return spirvWords(shaderc_result_get_bytes(result), length);
341}
342#endif
343
344} // namespace
345
347#if defined(EVE_HAS_SHADERC)
348 return true;
349#elif defined(_WIN32)
350 // findGlslc() walks the SDK directories and may spawn `where`, so probe once.
351 static const bool available = !findGlslc().empty();
352 return available;
353#else
354 static const bool available = externalGlslcAvailable();
355 return available;
356#endif
357}
358
359std::vector<std::uint32_t> compileGlslToSpirv(const std::string &source, GlslStage stage,
360 const std::string &debugName) {
361 if (source.empty()) throw compileFailure(std::string("empty ") + stageName(stage) + " GLSL source");
362#if defined(EVE_HAS_SHADERC)
363 return compileInProcess(source, stage, debugName);
364#else
365 return compileWithExternalGlslc(source, stage, debugName);
366#endif
367}
368
369} // namespace eve::graphics
std::string output
std::string descriptor
EvpackChunkInput input
Definition Evpack.cpp:170
std::string message
wgpu::PopErrorScopeStatus status
std::int32_t first
float length
std::function< void(b3JointId, const Numbers &)> write
Poco::JSON::Object::Ptr result
std::uint64_t bytes
onnx_detail::CompilerQueue compiler
Definition OnnxGpgpu.cpp:45
std::unique_ptr< gpgpu::GpuBuffer > buffer
Definition OnnxGpgpu.cpp:26
std::string error
Definition Package.cpp:174
std::string path
Definition PlayHost.cpp:111
std::string file
Object::Ptr value
std::map< std::string, double > attributes
std::string_view source
std::string kind
const SquirrelValueOptions & options
int count
float size
Definition TreeMesh.cpp:158
const VegetationPresetContext & context
ssq::Table ownedResult(HSQUIRRELVM vm, Result< T > result)
卡牌游戏 UI 工具模块:工厂 + 脚本绑定入口。 功能参考 ycarowr/UiCard:扇形手牌布局、抽牌/洗牌、悬浮放大、拖拽到落牌区、 敌方手牌(背面/偷看)、费用不足置灰,以及可实时调节的布局...
Definition Animation.h:25
bool glslRuntimeCompilationAvailable()
Whether this build can compile GLSL text to SPIR-V at runtime.
std::vector< std::uint32_t > compileGlslToSpirv(const std::string &source, GlslStage stage, const std::string &debugName)
Compile GLSL text to SPIR-V words.
GlslStage
GLSL stage accepted by compileGlslToSpirv.
Vec3 sub(Vec3 a, Vec3 b)