ACMX 2.139.0
Dual-Backend Real-Time GPU Video Synthesis
Loading...
Searching...
No Matches
shader-manifest.cpp
Go to the documentation of this file.
1#include "shader-manifest.hpp"
3
4#include <QFile>
5#include <QFileInfo>
6#include <QJsonArray>
7#include <QJsonDocument>
8#include <QJsonObject>
9#include <QJsonParseError>
10#include <QRegularExpression>
11#include <QSaveFile>
12#include <QTextStream>
13#include <algorithm>
14#include <cmath>
15#include <vector>
16
17namespace {
18 constexpr auto JSON_MANIFEST_NAME = "library.json";
19 constexpr auto TEXT_MANIFEST_NAME = "index.txt";
20
21 bool valid_custom_uniform_name(const QString &name) {
22 static const QRegularExpression identifier(QStringLiteral("^[A-Za-z_][A-Za-z0-9_]*$"));
23 return identifier.match(name).hasMatch() && !name.startsWith("gl_") && name.toUtf8().size() < static_cast<int>(acmx2::ipc::kShaderSelectionMaxUniformName);
24 }
25
26 bool nearly_equal(double left, double right) {
27 const double scale = std::max({1.0, std::abs(left), std::abs(right)});
28 return std::abs(left - right) <= 1.0e-12 * scale;
29 }
30
31 QString json_entry_file(const QJsonValue &value) {
32 if (value.isString())
33 return value.toString().trimmed();
34 if (value.isObject())
35 return value.toObject().value("file").toString().trimmed();
36 return {};
37 }
38
39 bool load_json_document(const QString &path, QJsonDocument &document, QString &error) {
40 QFile file(path);
41 if (!file.open(QIODevice::ReadOnly)) {
42 error = QObject::tr("Could not open %1: %2").arg(path, file.errorString());
43 return false;
44 }
45
46 QJsonParseError parseError;
47 document = QJsonDocument::fromJson(file.readAll(), &parseError);
48 if (parseError.error != QJsonParseError::NoError || !document.isObject()) {
49 error = QObject::tr("Could not parse %1 at offset %2: %3").arg(path).arg(parseError.offset).arg(parseError.errorString());
50 return false;
51 }
52 if (!document.object().value("shaders").isArray()) {
53 error = QObject::tr("%1 must contain a 'shaders' array.").arg(path);
54 return false;
55 }
56 return true;
57 }
58
59 bool write_json_document(const QString &path, const QJsonDocument &document, QString &error) {
60 QSaveFile file(path);
61 if (!file.open(QIODevice::WriteOnly)) {
62 error = QObject::tr("Could not write %1: %2").arg(path, file.errorString());
63 return false;
64 }
65 const QByteArray json = document.toJson(QJsonDocument::Indented);
66 if (file.write(json) != json.size() || !file.commit()) {
67 error = QObject::tr("Could not finish writing %1: %2").arg(path, file.errorString());
68 return false;
69 }
70 return true;
71 }
72} // namespace
73
74namespace acmx2 {
75 QString shader_manifest_path(const QString &directory) {
76 const QString jsonPath = directory + "/" + JSON_MANIFEST_NAME;
77 if (QFileInfo(jsonPath).isFile())
78 return jsonPath;
79 const QString textPath = directory + "/" + TEXT_MANIFEST_NAME;
80 if (QFileInfo(textPath).isFile())
81 return textPath;
82 return {};
83 }
84
85 bool shader_manifest_exists(const QString &directory) { return !shader_manifest_path(directory).isEmpty(); }
86
87 QDateTime shader_manifest_last_modified(const QString &directory) { return QFileInfo(shader_manifest_path(directory)).lastModified(); }
88
89 std::optional<Backend> shader_manifest_backend(const QString &directory, QString &error) {
90 error.clear();
91 const QString path = shader_manifest_path(directory);
92 if (path.isEmpty()) {
93 error = QObject::tr("No library.json or index.txt found in %1.").arg(directory);
94 return std::nullopt;
95 }
96 if (!path.endsWith(QStringLiteral(".json"), Qt::CaseInsensitive))
97 return std::nullopt;
98
99 QJsonDocument document;
100 if (!load_json_document(path, document, error))
101 return std::nullopt;
102 const QJsonValue value = document.object().value(QStringLiteral("backend"));
103 if (value.isUndefined() || value.isNull())
104 return std::nullopt;
105 if (!value.isString()) {
106 error = QObject::tr("%1 has a non-string 'backend' value.").arg(path);
107 return std::nullopt;
108 }
109 const std::optional<Backend> backend = backend_from_id(value.toString());
110 if (!backend) {
111 error = QObject::tr("%1 has an unsupported backend '%2'.").arg(path, value.toString());
112 }
113 return backend;
114 }
115
116 std::optional<ShaderLibraryType> shader_manifest_library_type(const QString &directory, QString &error) {
117 error.clear();
118 const QString path = shader_manifest_path(directory);
119 if (path.isEmpty()) {
120 error = QObject::tr("No library.json or index.txt found in %1.").arg(directory);
121 return std::nullopt;
122 }
123 if (!path.endsWith(QStringLiteral(".json"), Qt::CaseInsensitive))
124 return std::nullopt;
125
126 QJsonDocument document;
127 if (!load_json_document(path, document, error))
128 return std::nullopt;
129 const QJsonValue value = document.object().value(QStringLiteral("library_type"));
130 if (value.isUndefined() || value.isNull())
131 return std::nullopt;
132 if (!value.isString()) {
133 error = QObject::tr("%1 has a non-string 'library_type' value.").arg(path);
134 return std::nullopt;
135 }
136 const QString type = value.toString().trimmed().toLower();
137 if (type == QStringLiteral("source"))
139 if (type == QStringLiteral("runtime"))
141 error = QObject::tr("%1 has an unsupported library_type '%2'.").arg(path, value.toString());
142 return std::nullopt;
143 }
144
145 bool load_shader_manifest(const QString &directory, QStringList &shaders, QString &error) {
146 shaders.clear();
147 error.clear();
148 const QString path = shader_manifest_path(directory);
149 if (path.isEmpty()) {
150 error = QObject::tr("No library.json or index.txt found in %1.").arg(directory);
151 return false;
152 }
153
154 if (path.endsWith(".json", Qt::CaseInsensitive)) {
155 QJsonDocument document;
156 if (!load_json_document(path, document, error))
157 return false;
158 const QJsonArray entries = document.object().value("shaders").toArray();
159 for (const QJsonValue &entry : entries) {
160 const QString file = json_entry_file(entry);
161 if (file.isEmpty()) {
162 error = QObject::tr("%1 contains a shader entry without a file name.").arg(path);
163 return false;
164 }
165 shaders.append(file);
166 }
167 return true;
168 }
169
170 QFile file(path);
171 if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
172 error = QObject::tr("Could not open %1: %2").arg(path, file.errorString());
173 return false;
174 }
175 QTextStream input(&file);
176 while (!input.atEnd())
177 shaders.append(input.readLine().trimmed());
178 return true;
179 }
180
181 bool write_shader_manifest(const QString &directory, const QStringList &shaders, QString &error) {
182 error.clear();
183 const QString path = shader_manifest_path(directory);
184 if (path.isEmpty()) {
185 error = QObject::tr("No library.json or index.txt found in %1.").arg(directory);
186 return false;
187 }
188
189 if (path.endsWith(".json", Qt::CaseInsensitive)) {
190 QJsonDocument document;
191 if (!load_json_document(path, document, error))
192 return false;
193
194 QJsonObject root = document.object();
195 const QJsonArray previousEntries = root.value("shaders").toArray();
196 QJsonArray updatedEntries;
197 for (const QString &shader : shaders) {
198 QJsonValue preservedEntry;
199 bool found = false;
200 for (const QJsonValue &entry : previousEntries) {
201 if (json_entry_file(entry).compare(shader, Qt::CaseInsensitive) == 0) {
202 preservedEntry = entry;
203 found = true;
204 break;
205 }
206 }
207 updatedEntries.append(found ? preservedEntry : QJsonValue(shader));
208 }
209 if (!root.contains("version"))
210 root.insert("version", 1);
211 root.insert("shaders", updatedEntries);
212 return write_json_document(path, QJsonDocument(root), error);
213 }
214
215 QSaveFile file(path);
216 if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
217 error = QObject::tr("Could not write %1: %2").arg(path, file.errorString());
218 return false;
219 }
220 QTextStream output(&file);
221 for (const QString &shader : shaders)
222 output << shader << "\n";
223 output.flush();
224 if (output.status() != QTextStream::Ok || !file.commit()) {
225 error = QObject::tr("Could not finish writing %1: %2").arg(path, file.errorString());
226 return false;
227 }
228 return true;
229 }
230
231 bool append_shader_manifest(const QString &directory, const QString &shader, QString &error) {
232 QStringList shaders;
233 if (!load_shader_manifest(directory, shaders, error))
234 return false;
235 if (!shaders.contains(shader, Qt::CaseInsensitive))
236 shaders.append(shader);
237 return write_shader_manifest(directory, shaders, error);
238 }
239
240 bool remove_shader_manifest_entry(const QString &directory, const QString &shader, QString &error) {
241 QStringList shaders;
242 if (!load_shader_manifest(directory, shaders, error))
243 return false;
244
245 bool removed = false;
246 for (auto it = shaders.begin(); it != shaders.end();) {
247 if (it->compare(shader, Qt::CaseInsensitive) == 0) {
248 it = shaders.erase(it);
249 removed = true;
250 } else {
251 ++it;
252 }
253 }
254 if (!removed) {
255 error = QObject::tr("Shader '%1' is not present in the library manifest.").arg(shader);
256 return false;
257 }
258 return write_shader_manifest(directory, shaders, error);
259 }
260
261 bool migrate_index_manifest_to_json(const QString &directory, bool &created, QString &error) {
262 created = false;
263 error.clear();
264
265 const QString jsonPath = directory + "/" + JSON_MANIFEST_NAME;
266 if (QFileInfo(jsonPath).isFile())
267 return true;
268
269 const QString textPath = directory + "/" + TEXT_MANIFEST_NAME;
270 QFile file(textPath);
271 if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
272 error = QObject::tr("Could not open %1: %2").arg(textPath, file.errorString());
273 return false;
274 }
275
276 QStringList shaders;
277 QTextStream input(&file);
278 while (!input.atEnd()) {
279 const QString shader = input.readLine().trimmed();
280 if (!shader.isEmpty())
281 shaders.append(shader);
282 }
283
284 if (!create_shader_manifest(directory, ShaderManifestFormat::Json, shaders, error))
285 return false;
286 created = true;
287 return true;
288 }
289
290 bool create_shader_manifest(const QString &directory, ShaderManifestFormat format, const QStringList &shaders, QString &error) {
291 error.clear();
292 if (format == ShaderManifestFormat::Json) {
293 QJsonArray entries;
294 for (const QString &shader : shaders)
295 entries.append(shader);
296 QJsonObject root;
297 root.insert("version", 1);
298 root.insert("backend", QStringLiteral("acmx2"));
299 root.insert("library_type", QStringLiteral("source"));
300 root.insert("shaders", entries);
301 return write_json_document(directory + "/" + JSON_MANIFEST_NAME, QJsonDocument(root), error);
302 }
303
304 QSaveFile file(directory + "/" + TEXT_MANIFEST_NAME);
305 if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
306 error = QObject::tr("Could not create index.txt: %1").arg(file.errorString());
307 return false;
308 }
309 QTextStream output(&file);
310 for (const QString &shader : shaders)
311 output << shader << "\n";
312 output.flush();
313 if (output.status() != QTextStream::Ok || !file.commit()) {
314 error = QObject::tr("Could not finish creating index.txt: %1").arg(file.errorString());
315 return false;
316 }
317 return true;
318 }
319
320 bool load_custom_uniforms(const QString &directory, QList<CustomUniformDefinition> &uniforms, QString &error) {
321 uniforms.clear();
322 error.clear();
323 const QString path = directory + "/" + JSON_MANIFEST_NAME;
324 if (!QFileInfo(path).isFile()) {
325 error = QObject::tr("Custom uniforms require %1.").arg(path);
326 return false;
327 }
328
329 QJsonDocument document;
330 if (!load_json_document(path, document, error))
331 return false;
332
333 const QJsonValue value = document.object().value("custom_uniforms");
334 if (value.isUndefined() || value.isNull())
335 return true;
336 if (!value.isObject()) {
337 error = QObject::tr("%1 field 'custom_uniforms' must be an object.").arg(path);
338 return false;
339 }
340
341 const QJsonObject entries = value.toObject();
342 bool hasExplicitSlots = false;
343 bool hasImplicitSlots = false;
344 std::vector<int> occupiedSlots;
345 for (auto it = entries.constBegin(); it != entries.constEnd(); ++it) {
346 if (!it.value().isObject()) {
347 error = QObject::tr("Custom uniform '%1' must be an object.").arg(it.key());
348 return false;
349 }
350 const QJsonObject entry = it.value().toObject();
352 uniform.name = it.key();
353 if (!valid_custom_uniform_name(uniform.name)) {
354 error = QObject::tr("Custom uniform '%1' is not a valid GLSL identifier.").arg(uniform.name);
355 return false;
356 }
357 uniform.minimum = entry.value("minimum").toDouble(0.0);
358 uniform.maximum = entry.value("maximum").toDouble(1.0);
359 uniform.step = entry.value("step").toDouble(0.01);
360 uniform.value = entry.value("value").toDouble(uniform.minimum);
361 const QJsonValue slotValue = entry.value("slot");
362 if (!slotValue.isUndefined() && !slotValue.isNull()) {
363 const double numericSlot = slotValue.toDouble(-1.0);
364 uniform.slot = static_cast<int>(numericSlot);
365 if (!slotValue.isDouble() || numericSlot != uniform.slot || uniform.slot < 0 || uniform.slot >= static_cast<int>(ipc::kShaderSelectionMaxCustomUniforms) || std::find(occupiedSlots.begin(), occupiedSlots.end(), uniform.slot) != occupiedSlots.end()) {
366 error = QObject::tr("Custom uniform '%1' has an invalid or duplicate slot.").arg(uniform.name);
367 return false;
368 }
369 occupiedSlots.push_back(uniform.slot);
370 hasExplicitSlots = true;
371 } else {
372 hasImplicitSlots = true;
373 }
374 if (!std::isfinite(uniform.minimum) || !std::isfinite(uniform.maximum) || !std::isfinite(uniform.step) || !std::isfinite(uniform.value) || uniform.maximum <= uniform.minimum || uniform.step <= 0.0) {
375 error = QObject::tr("Custom uniform '%1' has an invalid range or value.").arg(uniform.name);
376 return false;
377 }
378 uniform.value = std::clamp(uniform.value, uniform.minimum, uniform.maximum);
379 uniforms.append(uniform);
380 }
381 if (hasExplicitSlots && hasImplicitSlots) {
382 error = QObject::tr("Custom uniforms must either all specify slots or all omit them.");
383 return false;
384 }
385 if (hasExplicitSlots) {
386 std::sort(uniforms.begin(), uniforms.end(), [](const CustomUniformDefinition &left, const CustomUniformDefinition &right) { return left.slot < right.slot; });
387 for (int index = 0; index < uniforms.size(); ++index) {
388 if (uniforms.at(index).slot != index) {
389 error = QObject::tr("Custom-uniform slots must be contiguous from zero.");
390 return false;
391 }
392 }
393 }
394 return true;
395 }
396
397 bool write_custom_uniforms(const QString &directory, const QList<CustomUniformDefinition> &uniforms, QString &error) {
398 error.clear();
399 if (uniforms.size() > static_cast<int>(ipc::kShaderSelectionMaxCustomUniforms)) {
400 error = QObject::tr("A library can contain at most %1 custom uniforms.").arg(ipc::kShaderSelectionMaxCustomUniforms);
401 return false;
402 }
403 const QString path = directory + "/" + JSON_MANIFEST_NAME;
404 QJsonDocument document;
405 if (!load_json_document(path, document, error))
406 return false;
407
408 QJsonObject entries;
409 const bool hasExplicitSlots = std::any_of(uniforms.cbegin(), uniforms.cend(), [](const CustomUniformDefinition &uniform) { return uniform.slot >= 0; });
410 std::vector<int> writtenSlots;
411 QStringList writtenNames;
412 for (const CustomUniformDefinition &uniform : uniforms) {
413 if (!valid_custom_uniform_name(uniform.name)) {
414 error = QObject::tr("Custom uniform '%1' is not a valid GLSL identifier.").arg(uniform.name);
415 return false;
416 }
417 if (writtenNames.contains(uniform.name, Qt::CaseSensitive)) {
418 error = QObject::tr("Duplicate custom uniform '%1'.").arg(uniform.name);
419 return false;
420 }
421 writtenNames.append(uniform.name);
422 if (!std::isfinite(uniform.minimum) || !std::isfinite(uniform.maximum) || !std::isfinite(uniform.step) || !std::isfinite(uniform.value) || uniform.maximum <= uniform.minimum || uniform.step <= 0.0) {
423 error = QObject::tr("Custom uniform '%1' has an invalid range or value.").arg(uniform.name);
424 return false;
425 }
426 if ((hasExplicitSlots && uniform.slot < 0) || (!hasExplicitSlots && uniform.slot >= 0)) {
427 error = QObject::tr("Custom uniforms must either all specify slots or all omit them.");
428 return false;
429 }
430 if (hasExplicitSlots && (uniform.slot >= static_cast<int>(ipc::kShaderSelectionMaxCustomUniforms) || std::find(writtenSlots.begin(), writtenSlots.end(), uniform.slot) != writtenSlots.end())) {
431 error = QObject::tr("Custom uniform '%1' has an invalid or duplicate slot.").arg(uniform.name);
432 return false;
433 }
434 if (hasExplicitSlots)
435 writtenSlots.push_back(uniform.slot);
436 QJsonObject entry;
437 if (hasExplicitSlots)
438 entry.insert("slot", uniform.slot);
439 entry.insert("minimum", uniform.minimum);
440 entry.insert("maximum", uniform.maximum);
441 entry.insert("step", uniform.step);
442 entry.insert("value", std::clamp(uniform.value, uniform.minimum, uniform.maximum));
443 entries.insert(uniform.name, entry);
444 }
445 if (hasExplicitSlots) {
446 std::sort(writtenSlots.begin(), writtenSlots.end());
447 for (std::size_t index = 0; index < writtenSlots.size(); ++index) {
448 if (writtenSlots[index] != static_cast<int>(index)) {
449 error = QObject::tr("Custom-uniform slots must be contiguous from zero.");
450 return false;
451 }
452 }
453 }
454
455 QJsonObject root = document.object();
456 if (entries.isEmpty())
457 root.remove("custom_uniforms");
458 else
459 root.insert("custom_uniforms", entries);
460 return write_json_document(path, QJsonDocument(root), error);
461 }
462
463 bool custom_uniform_metadata_matches(const QString &leftDirectory, const QString &rightDirectory, bool &matches, QString &error) {
464 matches = false;
465 QList<CustomUniformDefinition> leftUniforms;
466 QList<CustomUniformDefinition> rightUniforms;
467 if (!load_custom_uniforms(leftDirectory, leftUniforms, error) || !load_custom_uniforms(rightDirectory, rightUniforms, error)) {
468 return false;
469 }
470 if (leftUniforms.size() != rightUniforms.size()) {
471 matches = false;
472 return true;
473 }
474 for (int index = 0; index < leftUniforms.size(); ++index) {
475 const CustomUniformDefinition &left = leftUniforms.at(index);
476 const CustomUniformDefinition &right = rightUniforms.at(index);
477 if (left.name != right.name || left.slot != right.slot || !nearly_equal(left.minimum, right.minimum) || !nearly_equal(left.maximum, right.maximum) || !nearly_equal(left.step, right.step) || !nearly_equal(left.value, right.value)) {
478 matches = false;
479 return true;
480 }
481 }
482 matches = true;
483 return true;
484 }
485} // namespace acmx2
constexpr std::uint32_t kShaderSelectionMaxUniformName
constexpr std::uint32_t kShaderSelectionMaxCustomUniforms
QString shader_manifest_path(const QString &directory)
Resolve library.json first, then fall back to index.txt.
bool custom_uniform_metadata_matches(const QString &leftDirectory, const QString &rightDirectory, bool &matches, QString &error)
Compare two manifests' custom-uniform ABI and numeric metadata.
QDateTime shader_manifest_last_modified(const QString &directory)
Return the selected manifest's modification time.
bool load_custom_uniforms(const QString &directory, QList< CustomUniformDefinition > &uniforms, QString &error)
Load custom float-uniform controls from library.json.
std::optional< ShaderLibraryType > shader_manifest_library_type(const QString &directory, QString &error)
Read and validate an optional top-level library_type value.
bool remove_shader_manifest_entry(const QString &directory, const QString &shader, QString &error)
Remove one shader from the preferred manifest, without deleting its file.
bool shader_manifest_exists(const QString &directory)
Return true when either supported manifest exists.
bool load_shader_manifest(const QString &directory, QStringList &shaders, QString &error)
Load shader filenames from the preferred manifest in a directory.
bool append_shader_manifest(const QString &directory, const QString &shader, QString &error)
Add one shader to the preferred manifest if it is not already present.
std::optional< Backend > backend_from_id(const QString &value)
Definition backend.hpp:24
bool migrate_index_manifest_to_json(const QString &directory, bool &created, QString &error)
Create library.json from index.txt when a JSON manifest is absent.
bool write_custom_uniforms(const QString &directory, const QList< CustomUniformDefinition > &uniforms, QString &error)
Rewrite custom float-uniform controls while preserving all other JSON fields.
bool create_shader_manifest(const QString &directory, ShaderManifestFormat format, const QStringList &shaders, QString &error)
Create a new manifest in the requested format.
bool write_shader_manifest(const QString &directory, const QStringList &shaders, QString &error)
Rewrite the preferred manifest, preserving JSON fields when possible.
std::optional< Backend > shader_manifest_backend(const QString &directory, QString &error)
Read an optional top-level backend hint from library.json.
bool valid_custom_uniform_name(const QString &name)
bool nearly_equal(double left, double right)
bool load_json_document(const QString &path, QJsonDocument &document, QString &error)
bool write_json_document(const QString &path, const QJsonDocument &document, QString &error)
QString json_entry_file(const QJsonValue &value)
Optional JSON and legacy text shader-library manifests.