-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCLIPipeline.cpp
More file actions
5360 lines (4844 loc) · 223 KB
/
CLIPipeline.cpp
File metadata and controls
5360 lines (4844 loc) · 223 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "CLIPipeline.h"
#include "Manager.h"
#include "MeshImporterExporter.h"
#include "AnimationMerger.h"
#include "MeshValidator.h"
#include "MeshLodController.h"
#include "SelectionSet.h"
#include "SentryReporter.h"
#include "ScanConfig.h"
#include "ScanEngine.h"
#include "FBX/FBXExporter.h"
#include "MaterialPresetLibrary.h"
#include "TextureChannelPacker.h"
#include "TextureAtlasPacker.h"
#include "ApplyAtlas.h"
#include "NormalMapGenerator.h"
#include "MemoryEstimator.h"
#include "DrawCallAnalyzer.h"
#include "VertexCacheOptimizer.h"
#include "MeshDecimator.h"
#include "EditableMesh.h"
#include "TexturePaintBuffer.h"
#include "VertexColorBaker.h"
#include "VATBaker.h"
#include "MorphAnimationManager.h"
#include "NodeAnimationManager.h"
#include "PoseLibrary.h"
#include "QtMeshCloudClient.h"
#include <OgreMaterialSerializer.h>
#include <QApplication>
#include <QWidget>
#include <QDir>
#include <QFileInfo>
#include <QJsonDocument>
#include <QMap>
#include <QDebug>
#include <QTextStream>
#include <QLocale>
#include <QSysInfo>
#include <assimp/Importer.hpp>
#include <assimp/Exporter.hpp>
#include <assimp/postprocess.h>
#include <assimp/scene.h>
#include <OgreSubMesh.h>
#include <unordered_map>
#include <vector>
#include <memory>
#include <set>
#include <cstdio>
#ifndef Q_OS_WIN
#include <unistd.h>
#else
#include <io.h>
#endif
// Saved original stdout fd — Ogre's stdout gets redirected to stderr
// so that Ogre debug output doesn't contaminate CLI pipeline output.
static int s_savedStdoutFd = -1;
/// Write a string to the CLI output stream (original stdout before redirect).
static void cliWrite(const QString& text)
{
QByteArray utf8 = text.toUtf8();
#ifndef Q_OS_WIN
if (s_savedStdoutFd >= 0) {
::write(s_savedStdoutFd, utf8.constData(), utf8.size());
} else
#endif
{
fwrite(utf8.constData(), 1, utf8.size(), stdout);
fflush(stdout);
}
}
// ---------------------------------------------------------------------------
// Animation-only export helpers (no mesh artifacts)
// ---------------------------------------------------------------------------
static aiMatrix4x4 ogreTransformToAi(const Ogre::Vector3& pos,
const Ogre::Quaternion& rot,
const Ogre::Vector3& scale)
{
// Assimp uses row-major aiMatrix4x4; build from SRT.
aiMatrix4x4 s;
s.a1 = scale.x; s.b2 = scale.y; s.c3 = scale.z;
s.d4 = 1.0f;
Ogre::Matrix3 r3;
rot.ToRotationMatrix(r3);
aiMatrix4x4 r;
r.a1 = r3[0][0]; r.a2 = r3[0][1]; r.a3 = r3[0][2];
r.b1 = r3[1][0]; r.b2 = r3[1][1]; r.b3 = r3[1][2];
r.c1 = r3[2][0]; r.c2 = r3[2][1]; r.c3 = r3[2][2];
r.d4 = 1.0f;
aiMatrix4x4 t;
t.a4 = pos.x;
t.b4 = pos.y;
t.c4 = pos.z;
t.d4 = 1.0f;
return t * r * s;
}
static aiScene* buildAnimOnlyAiSceneFromSkeleton(const Ogre::Skeleton* skel)
{
if (!skel)
return nullptr;
auto* scene = new aiScene();
// Root node
scene->mRootNode = new aiNode();
scene->mRootNode->mName = aiString("RootNode");
scene->mRootNode->mTransformation = aiMatrix4x4(); // identity
// Build bone node tree.
std::unordered_map<const Ogre::Bone*, aiNode*> boneToNode;
boneToNode.reserve(skel->getNumBones());
auto makeNodeForBone = [&](const Ogre::Bone* b) -> aiNode* {
auto it = boneToNode.find(b);
if (it != boneToNode.end())
return it->second;
auto* n = new aiNode();
n->mName = aiString(b->getName().c_str());
n->mTransformation = ogreTransformToAi(b->getPosition(), b->getOrientation(), b->getScale());
boneToNode[b] = n;
return n;
};
// Attach root bones under scene root; attach children under parents.
std::vector<aiNode*> rootBones;
rootBones.reserve(skel->getNumBones());
for (unsigned short i = 0; i < skel->getNumBones(); ++i) {
const Ogre::Bone* b = skel->getBone(i);
if (!b)
continue;
aiNode* node = makeNodeForBone(b);
const Ogre::Node* parent = b->getParent();
const Ogre::Bone* parentBone = dynamic_cast<const Ogre::Bone*>(parent);
if (!parentBone) {
rootBones.push_back(node);
continue;
}
aiNode* parentNode = makeNodeForBone(parentBone);
// Append as child
aiNode** newChildren = new aiNode*[parentNode->mNumChildren + 1];
for (unsigned int ci = 0; ci < parentNode->mNumChildren; ++ci)
newChildren[ci] = parentNode->mChildren[ci];
newChildren[parentNode->mNumChildren] = node;
delete[] parentNode->mChildren;
parentNode->mChildren = newChildren;
parentNode->mNumChildren += 1;
node->mParent = parentNode;
}
if (!rootBones.empty()) {
scene->mRootNode->mChildren = new aiNode*[rootBones.size()];
scene->mRootNode->mNumChildren = static_cast<unsigned int>(rootBones.size());
for (unsigned int i = 0; i < scene->mRootNode->mNumChildren; ++i) {
scene->mRootNode->mChildren[i] = rootBones[i];
rootBones[i]->mParent = scene->mRootNode;
}
}
// Animations
scene->mNumAnimations = skel->getNumAnimations();
scene->mAnimations = scene->mNumAnimations ? new aiAnimation*[scene->mNumAnimations] : nullptr;
for (unsigned short ai = 0; ai < skel->getNumAnimations(); ++ai) {
const Ogre::Animation* anim = skel->getAnimation(ai);
auto* a = new aiAnimation();
a->mName = aiString(anim->getName().c_str());
a->mDuration = anim->getLength();
a->mTicksPerSecond = 1.0; // key times are in seconds
// Collect bone tracks.
std::vector<const Ogre::NodeAnimationTrack*> tracks;
tracks.reserve(anim->getNumNodeTracks());
for (unsigned short ti = 0; ti < anim->getNumNodeTracks(); ++ti) {
const Ogre::NodeAnimationTrack* t = anim->getNodeTrack(ti);
if (t)
tracks.push_back(t);
}
a->mNumChannels = static_cast<unsigned int>(tracks.size());
a->mChannels = a->mNumChannels ? new aiNodeAnim*[a->mNumChannels] : nullptr;
for (unsigned int ci = 0; ci < a->mNumChannels; ++ci) {
const Ogre::NodeAnimationTrack* t = tracks[ci];
const Ogre::Node* target = t->getAssociatedNode();
const Ogre::Bone* bone = dynamic_cast<const Ogre::Bone*>(target);
auto* ch = new aiNodeAnim();
ch->mNodeName = aiString(bone ? bone->getName().c_str() : "Unknown");
const unsigned short kCount = t->getNumKeyFrames();
ch->mNumPositionKeys = kCount;
ch->mNumRotationKeys = kCount;
ch->mNumScalingKeys = kCount;
ch->mPositionKeys = kCount ? new aiVectorKey[kCount] : nullptr;
ch->mRotationKeys = kCount ? new aiQuatKey[kCount] : nullptr;
ch->mScalingKeys = kCount ? new aiVectorKey[kCount] : nullptr;
for (unsigned short ki = 0; ki < kCount; ++ki) {
const Ogre::TransformKeyFrame* kf = t->getNodeKeyFrame(ki);
const double time = kf->getTime();
const Ogre::Vector3 p = kf->getTranslate();
const Ogre::Quaternion r = kf->getRotation();
const Ogre::Vector3 s = kf->getScale();
ch->mPositionKeys[ki].mTime = time;
ch->mPositionKeys[ki].mValue = aiVector3D(p.x, p.y, p.z);
ch->mRotationKeys[ki].mTime = time;
ch->mRotationKeys[ki].mValue = aiQuaternion(r.w, r.x, r.y, r.z);
ch->mScalingKeys[ki].mTime = time;
ch->mScalingKeys[ki].mValue = aiVector3D(s.x, s.y, s.z);
}
a->mChannels[ci] = ch;
}
scene->mAnimations[ai] = a;
}
return scene;
}
static QString assimpExportFormatIdForAnimOnlyPath(const QString& outputPath)
{
const QString fmt = CLIPipeline::formatForExtension(outputPath);
static const QMap<QString, QString> kUiToAssimp = {
{QStringLiteral("Collada (*.dae)"), QStringLiteral("collada")},
{QStringLiteral("X (*.x)"), QStringLiteral("x")},
{QStringLiteral("OBJ (*.obj)"), QStringLiteral("obj")},
{QStringLiteral("STL (*.stl)"), QStringLiteral("stl")},
{QStringLiteral("PLY (*.ply)"), QStringLiteral("ply")},
{QStringLiteral("3DS (*.3ds)"), QStringLiteral("3ds")},
{QStringLiteral("glTF 2.0 (*.gltf)"), QStringLiteral("gltf2")},
{QStringLiteral("glTF 2.0 (*.gltf2)"), QStringLiteral("gltf2")},
{QStringLiteral("glTF 2.0 Binary (*.glb)"), QStringLiteral("glb2")},
{QStringLiteral("glTF 2.0 Binary (*.glb2)"), QStringLiteral("glb2")},
{QStringLiteral("VRM / glTF 2.0 (*.vrm)"), QStringLiteral("gltf2")},
{QStringLiteral("FBX Binary (*.fbx)"), QStringLiteral("fbx")},
{QStringLiteral("Assimp Binary (*.assbin)"), QStringLiteral("assbin")},
};
if (auto it = kUiToAssimp.find(fmt); it != kUiToAssimp.end())
return it.value();
const QString suf = QFileInfo(outputPath).suffix().toLower();
static const QMap<QString, QString> kExtToAssimp = {
{QStringLiteral("fbx"), QStringLiteral("fbx")},
{QStringLiteral("dae"), QStringLiteral("collada")},
{QStringLiteral("obj"), QStringLiteral("obj")},
{QStringLiteral("stl"), QStringLiteral("stl")},
{QStringLiteral("ply"), QStringLiteral("ply")},
{QStringLiteral("3ds"), QStringLiteral("3ds")},
{QStringLiteral("gltf"), QStringLiteral("gltf2")},
{QStringLiteral("glb"), QStringLiteral("glb2")},
{QStringLiteral("vrm"), QStringLiteral("gltf2")},
{QStringLiteral("assbin"), QStringLiteral("assbin")},
{QStringLiteral("x"), QStringLiteral("x")},
};
return kExtToAssimp.value(suf, QStringLiteral("fbx"));
}
static bool exportAnimOnlyViaAssimp(const Ogre::SkeletonPtr& skel, const QString& outputPath, QString* outError = nullptr)
{
if (!skel) {
if (outError) *outError = QStringLiteral("No skeleton");
return false;
}
std::unique_ptr<aiScene> scene(buildAnimOnlyAiSceneFromSkeleton(skel.get()));
if (!scene) {
if (outError) *outError = QStringLiteral("Failed to build animation-only scene");
return false;
}
const QString formatId = assimpExportFormatIdForAnimOnlyPath(outputPath);
const unsigned int exportFlags =
(formatId == QLatin1String("x")) ? 0u : aiProcess_ConvertToLeftHanded;
Assimp::Exporter exporter;
const aiReturn r = exporter.Export(scene.get(), formatId.toStdString().c_str(),
outputPath.toStdString().c_str(), exportFlags);
if (r != AI_SUCCESS) {
if (outError)
*outError = QString::fromUtf8(exporter.GetErrorString());
return false;
}
return true;
}
static bool exportAnimOnly(const Ogre::SkeletonPtr& skel, const QString& outputPath, QString* outError = nullptr)
{
const QString suf = QFileInfo(outputPath).suffix().toLower();
if (suf == QStringLiteral("fbx") || suf == QStringLiteral("fbxa")) {
if (!skel) {
if (outError) *outError = QStringLiteral("No skeleton");
return false;
}
if (!FBXExporter::exportSkeletonOnlyFBX(skel.get(), outputPath)) {
if (outError) *outError = QStringLiteral("Custom FBX exporter failed");
return false;
}
return true;
}
return exportAnimOnlyViaAssimp(skel, outputPath, outError);
}
static bool cliSupportsColor()
{
if (qEnvironmentVariableIsSet("NO_COLOR"))
return false;
const QByteArray forceColor = qgetenv("CLICOLOR_FORCE");
if (!forceColor.isEmpty() && forceColor != "0")
return true;
#ifdef Q_OS_WIN
const int fd = (s_savedStdoutFd >= 0) ? s_savedStdoutFd : _fileno(stdout);
return fd >= 0 && _isatty(fd);
#else
const int fd = (s_savedStdoutFd >= 0) ? s_savedStdoutFd : fileno(stdout);
return fd >= 0 && ::isatty(fd);
#endif
}
static QString colorizeWord(const QString& text, const char* ansiColor, bool enabled)
{
if (!enabled)
return text;
return QStringLiteral("\x1b[%1m%2\x1b[0m").arg(QString::fromLatin1(ansiColor), text);
}
static QString colorizeIconWhenPositive(const QString& icon, int value, const char* ansiColor, bool enabled)
{
if (value <= 0)
return icon;
return colorizeWord(icon, ansiColor, enabled);
}
static QString scanStatusLabel(bool hasError, bool hasWarning, bool colorize)
{
if (hasError)
return colorizeWord("ERROR", "31", colorize);
if (hasWarning)
return colorizeWord("WARN", "33", colorize);
return colorizeWord("OK", "32", colorize);
}
static QString findingSeverityTag(const Finding& f)
{
if (f.fixed)
return "fixed";
if (f.skipped)
return "skipped";
switch (f.severity) {
case Severity::Error: return "error";
case Severity::Warning: return "warn";
case Severity::Info: return "info";
}
return "info";
}
static QString formatScanAssetLine(const AssetInfo& asset, const QList<Finding>& findings, bool colorize)
{
bool hasError = false;
bool hasWarning = false;
for (const auto& f : findings) {
if (f.fixed)
continue;
if (f.skipped) {
continue;
}
if (f.severity == Severity::Error)
hasError = true;
else if (f.severity == Severity::Warning)
hasWarning = true;
}
QString out;
QTextStream s(&out);
const QString status = scanStatusLabel(hasError, hasWarning, colorize);
if (!hasError && !hasWarning)
s << " " << status << " " << asset.relativePath << "\n";
else if (hasWarning)
s << status << " " << asset.relativePath << "\n";
else
s << status << " " << asset.relativePath << "\n";
for (const auto& f : findings) {
s << " [" << findingSeverityTag(f) << "] "
<< f.rule << ": " << f.message << "\n";
}
return out;
}
static QString formatScanSummary(const ScanResult& result, bool colorize)
{
QString out;
QTextStream s(&out);
const QString passIcon = colorizeIconWhenPositive(QStringLiteral("✓"), result.passed, "32", colorize);
const QString warnIcon = colorizeIconWhenPositive(QStringLiteral("▲"), result.warnings, "33", colorize);
const QString errorIcon = colorizeIconWhenPositive(QStringLiteral("✗"), result.errors, "31", colorize);
const QString infoIcon = colorizeIconWhenPositive(QStringLiteral("ℹ"), result.infos, "36", colorize);
const QString fixedIcon = colorizeIconWhenPositive(QStringLiteral("🔧"), result.fixed, "32", colorize);
const QString savedIcon = colorizeIconWhenPositive(QStringLiteral("📉"), result.bytesSaved > 0 ? 1 : 0, "32", colorize);
const QString keysIcon = colorizeIconWhenPositive(QStringLiteral("🧹"), result.keysRemoved > 0 ? 1 : 0, "32", colorize);
const QString skippedIcon = colorizeWord(QStringLiteral("⏭"), "90", colorize);
const QString timeIcon = colorizeWord(QStringLiteral("⏱"), "34", colorize);
s << "\n";
s << "Summary:\n";
s << " • Scanned: " << result.scanned << "\n";
s << " " << passIcon << " Passed: " << result.passed << "\n";
s << " " << warnIcon << " Warnings: " << result.warnings << "\n";
s << " " << errorIcon << " Errors: " << result.errors << "\n";
if (result.infos > 0)
s << " " << infoIcon << " Info: " << result.infos << "\n";
if (result.fixed > 0)
s << " " << fixedIcon << " Fixed: " << result.fixed << "\n";
if (result.bytesSaved > 0)
s << " " << savedIcon << " Saved: " << QString::number(result.bytesSaved / (1024.0 * 1024.0), 'f', 2) << " MB\n";
if (result.keysRemoved > 0) {
const QString n = QLocale::system().toString(result.keysRemoved);
s << " " << keysIcon << " Keys removed: " << n << "\n";
}
if (result.skipped > 0)
s << " " << skippedIcon << " Skipped: " << result.skipped << "\n";
s << " " << timeIcon << " Time: " << QString::number(result.elapsedMs / 1000.0, 'f', 1) << "s\n";
QString utcStart, utcEnd;
ScanEngine::scanReportUtcTimes(result, &utcStart, &utcEnd);
s << " UTC start: " << utcStart << "\n";
s << " UTC end: " << utcEnd << "\n";
return out;
}
static QTextStream& err()
{
static QTextStream s(stderr);
return s;
}
/// Ingest token: `--token` overrides `QTMESH_TOKEN`, then `QTMESH_CLOUD_TOKEN`.
static QString resolveIngestToken(const QString& flagToken)
{
const QString trimmed = flagToken.trimmed();
if (!trimmed.isEmpty())
return trimmed;
const QByteArray a = qgetenv("QTMESH_TOKEN");
if (!a.isEmpty())
return QString::fromUtf8(a);
const QByteArray b = qgetenv("QTMESH_CLOUD_TOKEN");
if (!b.isEmpty())
return QString::fromUtf8(b);
return {};
}
#ifndef QTMESH_CLOUD_WEB_URL
#define QTMESH_CLOUD_WEB_URL "https://qtmesh.dev"
#endif
/// One-line nudge pointing users at QtMesh Cloud so they can track
/// historical scan results and mesh info. Skipped when a token is already
/// configured (the user has signed up — passes flagToken so the per-command
/// `--token` value short-circuits the same as env vars), or when the caller
/// is emitting machine-readable JSON we mustn't pollute.
static void maybePrintCloudPromo(bool jsonOutput, const QString& flagToken = {})
{
if (jsonOutput) return;
if (!resolveIngestToken(flagToken).isEmpty()) return;
err() << "Tip: sign up at " << QTMESH_CLOUD_WEB_URL
<< " to track your scans and view results in the dashboard."
<< Qt::endl;
}
static bool s_verbose = false;
static bool s_noTelemetry = false;
/// Suppress qDebug/qInfo/qWarning in non-verbose mode.
/// qCritical and qFatal always pass through.
static void cliMessageHandler(QtMsgType type, const QMessageLogContext& ctx, const QString& msg)
{
Q_UNUSED(ctx);
if (s_verbose || type == QtCriticalMsg || type == QtFatalMsg) {
fprintf(stderr, "%s\n", qPrintable(msg));
}
}
/// Redirect stdout to stderr so Ogre/Qt debug output doesn't pollute
/// CLI output. Actual CLI output uses the saved original stdout fd.
static void redirectStdout()
{
#ifndef Q_OS_WIN
s_savedStdoutFd = dup(STDOUT_FILENO);
dup2(STDERR_FILENO, STDOUT_FILENO);
#endif
qInstallMessageHandler(cliMessageHandler);
}
void CLIPipeline::printVersion()
{
cliWrite(QString("qtmesh %1\n").arg(QTMESHEDITOR_VERSION));
}
void CLIPipeline::printUsage()
{
cliWrite(
"Usage: qtmesh <command> [options]\n"
"\n"
"Commands:\n"
" info <file> [--json] Show mesh information\n"
" fix <file> [-o <output>] [flags] Fix/optimize a mesh (overwrites input if no -o)\n"
" convert <file> -o <output> Convert between 3D formats\n"
" anim <file> --list [--json] List animations\n"
" anim <file> --rename <old> <new> [-o <output>]\n"
" Rename an animation (overwrites input if no -o)\n"
" anim <file> --merge <f1> [f2...] [-o <output>]\n"
" Merge animations from other files into base\n"
" (overwrites input if no -o)\n"
" anim <file> --resample N [-o <output>] [--animation <name>]\n"
" Resample to exactly N evenly-spaced keyframes\n"
" anim <file> --decimate-step S [-o <output>] [--animation <name>]\n"
" Keep every Sth keyframe (plus first and last)\n"
" anim <file> --simplify [--preset {conservative|balanced|aggressive}] [--tolerance T] [--rotation-tolerance-deg D] [-o <output>] [--animation <name>]\n"
" Remove redundant keyframes (tolerance-based, preserves sharp keys)\n"
" Default preset: conservative (~0.1mm / 0.05°) — destructive, so the safe default.\n"
" Use --preset balanced / aggressive for more aggressive reduction.\n"
" --tolerance T sets translation+scale tolerance (world units)\n"
" anim <file> --bake-fps N [-o <output>] [--animation <name>]\n"
" Re-grid to exactly N keyframes per second (uniform)\n"
" Common values: 10, 15, 30, 60. Mixamo / pipeline export.\n"
" anim <file> --analyze [--json] [--preset ...] [--tolerance T] [--rotation-tolerance-deg D]\n"
" Report % redundant keyframes and projected file-size savings\n"
" validate <file> [--json] Validate mesh geometry (exit 1 if errors found)\n"
" lod <file> --count N [--reductions r,...] [-o output]\n"
" Generate N LOD levels; exports <base>_lod1.<ext> etc.\n"
" lod <file> --auto [-o output] Auto-generate LOD levels\n"
" lod <file> --remove [-o output] Remove LOD levels (overwrites input if no -o)\n"
" lod <file> --info [--json] Show LOD level info\n"
" pose <file> --animation <name> --time <t> -o <output>\n"
" Export a single posed frame as static mesh\n"
" pose <file> --animation <name> --count N -o <pattern>\n"
" Export N evenly spaced frames (use %02d in pattern)\n"
" pose <library.poselib> --library list [--json]\n"
" List pose names in a `.poselib` sidecar JSON file.\n"
" No mesh load needed; reads the file directly.\n"
" pose <mesh> --library apply --lib <lib.poselib> --apply <name> -o <out>\n"
" Load mesh, apply named pose from sidecar to the\n"
" skeleton, export the posed mesh. Requires a skinned mesh.\n"
" scan [path] [options] Scan directory for 3D asset issues (default path: .)\n"
" material <file> --preset <name> [-o <output>]\n"
" Apply a built-in material preset to every sub-entity\n"
" (Plastic/Metal/Wood/Glass/Unlit/Wireframe + PBR templates:\n"
" Metallic-Roughness, Specular-Glossiness, Unlit PBR)\n"
" material --list-presets List the built-in preset names\n"
"\n"
"Scan options:\n"
" --config <file> Config file (default: qtmesh.yml, qtmesh.json)\n"
" --json Output as JSON\n"
" --report <file> Write JSON report to file\n"
" --sarif <file> Write SARIF report to file\n"
" --fix Enable auto-fixes\n"
" --dry-run Show what fixes would be applied\n"
" --include <patterns> File patterns, comma-separated (e.g. *.fbx,*.glb)\n"
" --exclude <patterns> Exclude patterns, comma-separated\n"
" --allowed-formats <list> Allowed formats CSV (e.g. fbx,glb,obj)\n"
" --forbidden-extensions <list> Forbidden formats CSV\n"
" --max-file-size-mb <n> Override max_file_size_mb (0 = no limit)\n"
" --min-file-size-mb <n> Override min_file_size_mb (0 = no limit)\n"
" --max-meshes <n> Override max_mesh_count (0 = no limit)\n"
" --min-meshes <n> Override min_mesh_count (0 = no limit)\n"
" --max-materials <n> Override max_material_count (0 = no limit)\n"
" --min-materials <n> Override min_material_count (0 = no limit)\n"
" --max-vertices <n> Override max_vertex_count (0 = no limit)\n"
" --min-vertices <n> Override min_vertex_count (0 = no limit)\n"
" --max-acmr <n> Override max_acmr (0 = no limit, e.g. 1.5)\n"
" --require-skeleton / --no-require-skeleton\n"
" Override require_skeleton\n"
" --require-animations / --no-require-animations\n"
" Override require_animations\n"
" --allow-embedded-textures / --disallow-embedded-textures\n"
" Override allow_embedded_textures\n"
" --require-textures-exist / --no-require-textures-exist\n"
" Override require_textures_exist\n"
" --allow-missing-materials / --disallow-missing-materials\n"
" Override allow_missing_materials\n"
" --file-name-case <name> snake_case, kebab-case, camelCase, PascalCase, lowercase\n"
" --max-anim-keyframes <n> Override max_anim_keyframes (0 = no limit)\n"
" --min-anim-keyframes <n> Override min_anim_keyframes (0 = no limit)\n"
" --max-anim-duration <n> Override max_anim_duration seconds (0 = no limit)\n"
" --min-anim-duration <n> Override min_anim_duration seconds (0 = no limit)\n"
" --require-animation-names <list> Required animation names/patterns CSV\n"
" --require-bone-names <list> Required bone names/patterns CSV\n"
"\n"
" Quality rules (config only — set in qtmesh.yml):\n"
" max_texture_resolution: <px> Largest texture edge ceiling (e.g. 2048)\n"
" require_uv_channels: <n> Min UV sets per submesh (1=any, 2=lightmap)\n"
" detect_zero_weight_bones: true Flag Mixamo-style unused bones (info)\n"
" detect_overlapping_uvs_pct: <n> Warn at >= n% overlapping UV0 AABBs\n"
" detect_non_manifold_edges_pct: <n> Warn at >= n% non-manifold edges\n"
" redundant_keyframes_pct: <n> Warn at >= n% redundant anim keys (fixable)\n"
"\n"
" --fail-on <level> Exit 1 threshold: info, warning, error, never\n"
" --token <token> Ingest token (overrides QTMESH_TOKEN / QTMESH_CLOUD_TOKEN)\n"
" --no-upload Skip POSTing scan JSON to QtMesh Cloud when a token is set\n"
" --strict-upload Exit 1 if cloud upload fails (default: warn only)\n"
"\n"
" Cloud rules: if no --config and QTMESH_TOKEN or --token is set, remote rules are\n"
" fetched first (local qtmesh.yml is ignored). If the API fails, built-in defaults apply.\n"
" Without a token, qtmesh.yml|yaml|json in the cwd is used if present.\n"
" --config always wins. Scan JSON uploads when a token is set (unless --no-upload).\n"
" Override API base with QTMESH_API_BASE.\n"
"\n"
"Fix flags:\n"
" --remove-degenerates Remove degenerate triangles\n"
" --merge-materials Remove redundant materials\n"
" --all Apply all extra fixes\n"
" (no flags) Standard import/export (joins vertices, smooths normals, optimizes)\n"
"\n"
" memory <file> [--json] [--budget <size>] [--token <t>] [--no-cloud]\n"
" Report per-mesh GPU bytes and per-texture VRAM bytes\n"
" --budget accepts e.g. 50MB, 1GB; exit 1 if exceeded\n"
" If --budget omitted and a token is set, the project's\n"
" memory_budget_mb is fetched from QtMesh Cloud rules.\n"
" --no-cloud opts out.\n"
" analyze <file> [--json] Analyze draw calls: per-material grouping plus\n"
" merge suggestions for entities sharing a material.\n"
" vertex-cache <file> [-o <output>] [--json]\n"
" Reorder index buffers via Forsyth's algorithm; reports\n"
" before/after ACMR. Without -o, only analyzes (read-only).\n"
" decimate <file> -o <output> (--reduction <r> | --target-tris N | --target-verts N) [--json]\n"
" Single-pass mesh decimation. Choose one target:\n"
" --reduction 0.5 (drop half the triangles),\n"
" --target-tris 5000, or --target-verts 2500.\n"
" atlas --inputs <csv> -o <atlas.png> [--size N] [--width N --height N] [--padding N]\n"
" [--manifest <atlas.json>]\n"
" Pack N textures into a single atlas + JSON manifest of\n"
" per-tile UV remaps. Shelf bin-pack; deterministic. Useful\n"
" for consolidating per-prop textures into one binding to\n"
" reduce GPU draw-call count.\n"
" atlas-apply <file> -o <output> --manifest <atlas.json> --atlas <atlas.png>\n"
" [--match {basename|fullpath}] [--no-clamp]\n"
" [--keep-extras] [--json]\n"
" Apply a previously-packed atlas to a mesh: rewrite UV0\n"
" into each tile's sub-rect and rebind the diffuse TUS to the\n"
" atlas texture. By default normal/AO/emissive TUSes are\n"
" stripped from affected materials because they sample UV0,\n"
" which is now diffuse-atlas-relative — pass --keep-extras\n"
" when you have pre-atlased auxiliary maps to match.\n"
" Counterpart to `atlas`.\n"
" optimize <file> -o <output> [flags] [--json]\n"
" Batch-optimize a single asset. Defaults to\n"
" --vertex-cache --simplify-anim when no flags are given.\n"
" Add --reduction <r> / --target-tris N / --target-verts N\n"
" to also decimate. --all enables vertex-cache + simplify-anim\n"
" together (decimation still requires an explicit target).\n"
" Anim simplify tolerances (Conservative preset by default —\n"
" simplify is destructive, so the safe choice. Use\n"
" larger values for Balanced (1e-3 / 0.5° / 1e-3) or\n"
" Aggressive (1e-2 / 1° / 1e-2) reduction):\n"
" --simplify-translation-tol T default 0.0001 (world units, ~0.1mm)\n"
" --simplify-rotation-deg-tol D default 0.05 (degrees)\n"
" --simplify-scale-tol S default 0.0001\n"
" --simplify-preset P shorthand for the three tolerances;\n"
" P = conservative | balanced | aggressive\n"
" bake-vertex-colors <file> -o <out.png> [--resolution N] [--dilation N] [--json]\n"
" Bake vertex colors to a UV-space PNG. Walks every UV-mapped\n"
" triangle, rasterizes barycentric-interpolated vertex colors,\n"
" then dilates outward by N pixels to mask seam bleed at MIP time.\n"
" Default resolution=1024, dilation=4. Output PNG is RGBA.\n"
" vat <file> --anim <name> [--fps N] [--encoding rgba8|rgba16]\n"
" [--target agnostic|unity|unreal|godot] [--normals] [-o <dir>] [--json]\n"
" Bake a skeletal animation into a Vertex Animation Texture\n"
" (position PNG + JSON sidecar; optional normal PNG). Engine\n"
" targets: agnostic (default), unity (.meta + UV-V flip),\n"
" unreal (Y/Z axis swap), godot (.gdshader template).\n"
" morph <file> --list [--json] List morph targets / blend shapes on a mesh. (Set/add/delete\n"
" land in follow-up slices once authoring is in place.)\n"
" nodeanim <file> --list [--json] List node-animation clips on a scene (props, doors, machinery,\n"
" animated lights — anything non-skeletal). Authoring on the CLI\n"
" side needs the C5 glTF/FBX exporter round-trip first.\n"
"\n"
"Global options:\n"
" --help, -h Show this help\n"
" --version, -v Show version\n"
" --verbose Show Ogre/engine debug output\n"
" --no-telemetry Permanently disable anonymous usage data\n"
);
}
QString CLIPipeline::formatForExtension(const QString& path)
{
struct ExtensionFormat {
const char* extension;
const char* format;
};
static const ExtensionFormat extensionFormats[] = {
{".fbx", "FBX Binary (*.fbx)"},
{".glb", "glTF 2.0 Binary (*.glb)"},
{".glb2", "glTF 2.0 Binary (*.glb2)"},
{".gltf", "glTF 2.0 (*.gltf)"},
{".gltf2", "glTF 2.0 (*.gltf2)"},
{".vrm", "VRM / glTF 2.0 (*.vrm)"},
{".dae", "Collada (*.dae)"},
{".obj", "OBJ (*.obj)"},
{".stl", "STL (*.stl)"},
{".ply", "PLY (*.ply)"},
{".3ds", "3DS (*.3ds)"},
{".x", "X (*.x)"},
{".mesh.xml", "Ogre XML (*.mesh.xml)"},
{".mesh", "Ogre Mesh (*.mesh)"},
{".assbin", "Assimp Binary (*.assbin)"},
{".tmd", "PlayStation TMD (*.tmd)"},
{".rsd", "PlayStation RSD (*.rsd)"}
};
for (const ExtensionFormat& entry : extensionFormats) {
if (path.endsWith(QString::fromLatin1(entry.extension), Qt::CaseInsensitive)) {
return QString::fromLatin1(entry.format);
}
}
return "Ogre Mesh (*.mesh)";
}
bool CLIPipeline::initOgreHeadless()
{
// Suppress Ogre log output unless --verbose was given.
// Creating our own LogManager before Root prevents Root from
// creating a default one that writes to ogre.log and stdout.
if (!s_verbose) {
if (!Ogre::LogManager::getSingletonPtr()) {
auto* logMgr = new Ogre::LogManager();
logMgr->createLog("ogre.log", true, false, true); // default, debugOut=false, suppressFile=true
} else {
Ogre::LogManager::getSingleton().getDefaultLog()->setDebugOutputEnabled(false);
}
}
try {
Manager::getSingleton();
} catch (...) {
err() << "Error: Failed to initialize Ogre." << Qt::endl;
return false;
}
// Already have a render window (e.g. from tryInitOgre() in tests) — nothing to do.
auto* root = Manager::getSingleton()->getRoot();
if (root) {
try {
if (root->getRenderTarget("TestHidden") || root->getRenderTarget("CLIHidden"))
return true;
} catch (...) {
// getRenderTarget may throw if not found in some Ogre versions
}
}
static QWidget* hiddenWidget = nullptr;
if (!hiddenWidget) {
hiddenWidget = new QWidget();
hiddenWidget->setAttribute(Qt::WA_DontShowOnScreen);
hiddenWidget->resize(1, 1);
hiddenWidget->show();
}
try {
Ogre::NameValuePairList params;
params["externalWindowHandle"] = Ogre::StringConverter::toString(
static_cast<unsigned long>(hiddenWidget->winId()));
#ifdef Q_OS_MACOS
params["macAPI"] = "cocoa";
params["macAPICocoaUseNSView"] = "true";
#endif
Manager::getSingleton()->getRoot()->createRenderWindow(
"CLIHidden", 1, 1, false, ¶ms);
return true;
} catch (...) {
err() << "Error: Failed to create render window." << Qt::endl;
return false;
}
}
MeshInfo CLIPipeline::extractMeshInfo(const Ogre::Entity* entity, const QString& fileName)
{
MeshInfo info;
info.file = fileName;
if (!entity) return info;
const Ogre::MeshPtr& mesh = entity->getMesh();
if (!mesh) return info;
info.submeshes = mesh->getNumSubMeshes();
// Count vertices
if (mesh->sharedVertexData)
info.vertices += mesh->sharedVertexData->vertexCount;
for (unsigned int i = 0; i < info.submeshes; ++i) {
Ogre::SubMesh* sub = mesh->getSubMesh(i);
if (sub->vertexData)
info.vertices += sub->vertexData->vertexCount;
if (sub->indexData)
info.triangles += sub->indexData->indexCount / 3;
}
// Materials
std::set<std::string, std::less<>> seenMats;
for (unsigned int i = 0; i < entity->getNumSubEntities(); ++i) {
Ogre::SubEntity* subEnt = entity->getSubEntity(i);
if (subEnt && subEnt->getMaterial()) {
auto name = subEnt->getMaterial()->getName();
if (seenMats.insert(name).second)
info.materials << QString::fromStdString(name);
}
}
// Textures. The straightforward pass walks every CONTENT_NAMED
// TextureUnitState. That covers diffuse/albedo/metallic/roughness/ao/
// emissive — every PBR slot MaterialProcessor binds as a plain TUS.
// It does NOT cover the normal map: MaterialProcessor wires that one
// through RTSS's render-state side channel (see RTShaderHelper::
// applyNormalMap), which creates a transient TUS during shader-state
// resolution that's not visible on the base pass. To recover that
// texture name we read the qtme.normal_map UOB hint the importer
// leaves on the pass (the same hint slice #507 added so FBX export
// could round-trip the normal map). Issue #510.
std::set<std::string, std::less<>> seenTex;
const auto collectFromPass = [&](const Ogre::Pass* pass) {
if (!pass) return;
for (auto* tus : pass->getTextureUnitStates()) {
if (tus->getContentType() != Ogre::TextureUnitState::CONTENT_NAMED)
continue;
const auto& name = tus->getTextureName();
if (!name.empty() && seenTex.insert(name).second)
info.textures << QString::fromStdString(name);
}
// Recover RTSS-wired normal map from the UOB hint. Use the
// pointer variant of any_cast (returns nullptr on type mismatch
// — older assets / payload-type drift / a future writer with a
// different shape) so we don't have to catch std::bad_cast just
// to swallow it.
const Ogre::Any& nh =
pass->getUserObjectBindings().getUserAny("qtme.normal_map");
if (!nh.has_value()) return;
if (const Ogre::String* n = Ogre::any_cast<Ogre::String>(&nh)) {
if (!n->empty() && seenTex.insert(*n).second)
info.textures << QString::fromStdString(*n);
}
};
for (unsigned int i = 0; i < entity->getNumSubEntities(); ++i) {
const auto mat = entity->getSubEntity(i)->getMaterial();
if (!mat) continue;
for (const Ogre::Technique* tech : mat->getTechniques())
for (const Ogre::Pass* pass : tech->getPasses())
collectFromPass(pass);
}
// Skeleton & animations
if (entity->hasSkeleton()) {
Ogre::SkeletonPtr skel = mesh->getSkeleton();
if (skel) {
info.skeletonName = QString::fromStdString(skel->getName());
info.boneCount = skel->getNumBones();
for (unsigned short b = 0; b < skel->getNumBones(); ++b)
info.bones << QString::fromStdString(skel->getBone(b)->getName());
for (unsigned short a = 0; a < skel->getNumAnimations(); ++a) {
auto* anim = skel->getAnimation(a);
info.animations.append({
QString::fromStdString(anim->getName()),
anim->getLength()
});
}
}
}
// Bounding box
auto bb = mesh->getBounds();
info.bbMin = bb.getMinimum();
info.bbMax = bb.getMaximum();
return info;
}
QString CLIPipeline::formatMeshInfoText(const MeshInfo& info)
{
QString result;
QTextStream s(&result);
s << "File: " << info.file << "\n";
s << "Coordinate system: "
<< (info.upAxis == 1 ? "Y-up (Mixamo/default)"
: info.upAxis == 2 ? "Z-up (Unreal Engine)"
: "unknown")
<< "\n";
s << "Vertices: " << info.vertices << "\n";
s << "Triangles: " << info.triangles << "\n";
s << "Submeshes: " << info.submeshes << "\n";
s << "Materials: " << (info.materials.isEmpty() ? "(none)" : info.materials.join(", ")) << "\n";
if (!info.textures.isEmpty())
s << "Textures: " << info.textures.join(", ") << "\n";
if (!info.skeletonName.isEmpty()) {
s << "Skeleton: " << info.skeletonName
<< " (" << info.boneCount << " bones)\n";
if (!info.bones.isEmpty()) {
s << "Bones:\n";
for (const auto& bone : info.bones)
s << " " << bone << "\n";
}
if (!info.animations.isEmpty()) {
s << "Animations:\n";
for (const auto& anim : info.animations)
s << " " << anim.name
<< QString(" %1s").arg(anim.duration, 0, 'f', 3) << "\n";
}
}
s << "Bounding Box: ("
<< QString::number(info.bbMin.x, 'f', 2) << ", "
<< QString::number(info.bbMin.y, 'f', 2) << ", "
<< QString::number(info.bbMin.z, 'f', 2) << ") to ("
<< QString::number(info.bbMax.x, 'f', 2) << ", "
<< QString::number(info.bbMax.y, 'f', 2) << ", "
<< QString::number(info.bbMax.z, 'f', 2) << ")\n";
return result;
}
QString CLIPipeline::formatMeshInfoJson(const MeshInfo& info)
{
QJsonObject obj;
obj["file"] = info.file;
obj["upAxis"] = info.upAxis == 1 ? "Y-up" : (info.upAxis == 2 ? "Z-up" : "unknown");
obj["vertices"] = static_cast<int>(info.vertices);
obj["triangles"] = static_cast<int>(info.triangles);
obj["submeshes"] = static_cast<int>(info.submeshes);
QJsonArray mats;
for (const auto& m : info.materials) mats.append(m);
obj["materials"] = mats;
if (!info.textures.isEmpty()) {
QJsonArray texs;
for (const auto& t : info.textures) texs.append(t);
obj["textures"] = texs;
}
if (!info.skeletonName.isEmpty()) {
QJsonObject skel;
skel["name"] = info.skeletonName;
skel["boneCount"] = info.boneCount;
QJsonArray boneArr;
for (const auto& b : info.bones) boneArr.append(b);
skel["bones"] = boneArr;
obj["skeleton"] = skel;
QJsonArray anims;
for (const auto& a : info.animations) {
QJsonObject ao;
ao["name"] = a.name;
ao["duration"] = static_cast<double>(a.duration);
anims.append(ao);
}
obj["animations"] = anims;
}
QJsonObject bb;
bb["min"] = QJsonArray{info.bbMin.x, info.bbMin.y, info.bbMin.z};
bb["max"] = QJsonArray{info.bbMax.x, info.bbMax.y, info.bbMax.z};
obj["boundingBox"] = bb;
return QString::fromUtf8(QJsonDocument(obj).toJson(QJsonDocument::Indented));
}
int CLIPipeline::run(int argc, char* argv[])
{
// Pre-scan for --verbose and --no-telemetry before anything else
for (int i = 1; i < argc; ++i) {
QString arg(argv[i]);
if (arg == "--verbose") s_verbose = true;
if (arg == "--no-telemetry") s_noTelemetry = true;
}