summaryrefslogtreecommitdiff
path: root/ZAPD/Main.cpp
blob: 3f9b25dc97a454dcbc6e675db25a65ef06a0857d (plain)
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
#include "Globals.h"
#include <Utils/DiskFile.h>
#include <Utils/Path.h>
#include <Utils/Directory.h>
#include "WarningHandler.h"

// Linker Hacks Begin
#include "ZAnimation.h"
ZNormalAnimation nAnim(nullptr);
ZCurveAnimation cAnim(nullptr);
ZLinkAnimation lAnim(nullptr);
ZLegacyAnimation lAnim2(nullptr);

#include "ZArray.h"
ZArray arr(nullptr);

#include "ZAudio.h"
ZAudio audio(nullptr);

#include "ZBackground.h"
ZBackground back(nullptr);

#include "ZBlob.h"
ZBlob blob(nullptr);

#include "ZCollision.h"
ZCollisionHeader colHeader(nullptr);

#include "ZCutscene.h"
ZCutscene cs(nullptr);

#include "ZLimb.h"
ZLimb limb(nullptr);

#include "ZMtx.h"
ZMtx mtx(nullptr);

#include "ZPath.h"
ZPath path(nullptr);

#include "ZPlayerAnimationData.h"
ZPlayerAnimationData pAnimData(nullptr);

#include "ZScalar.h"
ZScalar scalar(nullptr);

#include "ZSkeleton.h"
ZLimbTable limbTbl(nullptr);
ZSkeleton skel(nullptr);

#include "ZString.h"
ZString str(nullptr);

#include "ZSymbol.h"
ZSymbol sym(nullptr);

#include "ZText.h"
ZText txt(nullptr);

#include "ZTextMM.h"
ZTextMM txtMM(nullptr);

#include "ZTexture.h"
ZTexture tex(nullptr);

#include "ZVector.h"
ZVector vec(nullptr);

#include "ZVtx.h"
ZVtx vtx(nullptr);

#include "ZRoom/ZRoom.h"
ZRoom room(nullptr);

#include "ZPointer.h"
ZPointer pointer(nullptr);

#include "ZCKeyFrame.h"
ZKeyFrameSkel kfSKel(nullptr);

#include "ZCkeyFrameAnim.h"
ZKeyFrameAnim kfAnim(nullptr);

// Linker Hacks End

#include "ZFile.h"
#include "ZTexture.h"

#include <functional>
#include "CrashHandler.h"

#include <string>
#include <string_view>
#include "tinyxml2.h"
#include <ctpl_stl.h>

const char gBuildHash[] = "";

using ArgFunc = void (*)(int&, char**);

void Arg_SetOutputPath(int& i, char* argv[]);
void Arg_SetInputPath(int& i, char* argv[]);
void Arg_SetBaseromPath(int& i, char* argv[]);
void Arg_SetSourceOutputPath(int& i, char* argv[]);
void Arg_GenerateSourceFile(int& i, char* argv[]);
void Arg_TestMode(int& i, char* argv[]);
void Arg_LegacyDList(int& i, char* argv[]);
void Arg_EnableProfiling(int& i, char* argv[]);
void Arg_UseExternalResources(int& i, char* argv[]);
void Arg_SetTextureType(int& i, char* argv[]);
void Arg_ReadConfigFile(int& i, char* argv[]);
void Arg_EnableErrorHandler(int& i, char* argv[]);
void Arg_SetVerbosity(int& i, char* argv[]);
void Arg_VerboseUnaccounted(int& i, char* argv[]);
void Arg_SetExporter(int& i, char* argv[]);
void Arg_EnableGCCCompat(int& i, char* argv[]);
void Arg_ForceStatic(int& i, char* argv[]);
void Arg_ForceUnaccountedStatic(int& i, char* argv[]);
void Arg_SetFileListPath(int& i, char* argv[]);
void Arg_SetBuildRawTexture(int& i, char* argv[]);
void Arg_SetNoRomMode(int& i, char* argv[]);
void Arg_SetXMLMode(int& i, char* argv[]);

int main(int argc, char* argv[]);

bool Parse(const fs::path& xmlFilePath, const fs::path& basePath, const fs::path& outPath,
           ZFileMode fileMode, int workerID);

void ParseArgs(int& argc, char* argv[]);

void BuildAssetTexture(const fs::path& pngFilePath, TextureType texType, const fs::path& outPath);
void BuildAssetBackground(const fs::path& imageFilePath, const fs::path& outPath);
void BuildAssetBlob(const fs::path& blobFilePath, const fs::path& outPath);
ZFileMode ParseFileMode(const std::string& buildMode, ExporterSet* exporterSet);
int HandleExtract(ZFileMode fileMode, ExporterSet* exporterSet);
int ExtractFunc(int workerID, int fileListSize, std::string fileListItem, ZFileMode fileMode);

volatile int numWorkersLeft = 0;

extern const char gBuildHash[];

extern void ImportExporters();

extern "C" int zapd_main(int argc, char* argv[])
{
	int returnCode = 0;

	if (argc < 2)
	{
		printf("ZAPD.out (%s) [mode (btex/bovl/bsf/bblb/bmdlintr/bamnintr/e)] ...\n", gBuildHash);
		return 1;
	}

	Globals* g = new Globals();
	WarningHandler::Init(argc, argv);

	for (int i = 1; i < argc; i++)
	{
		if (!strcmp(argv[i], "--version"))
		{
			printf("ZAPD.out %s\n", gBuildHash);
			return 0;
		}
		else if (!strcmp(argv[i], "--help") || !strcmp(argv[i], "-h"))
		{
			printf("Congratulations!\n");
			printf("You just found the (unimplemented and undocumented) ZAPD's help message.\n");
			printf("Feel free to implement it if you want :D\n");

			WarningHandler::PrintHelp();
			return 0;
		}
	}

	ParseArgs(argc, argv);

	// Parse File Mode
	ExporterSet* exporterSet = Globals::Instance->GetExporterSet();

	// We've parsed through our commands once. If an exporter exists, it's been set by now.
	// Now we'll parse through them again but pass them on to our exporter if one is available.
	if (exporterSet != nullptr && exporterSet->parseArgsFunc != nullptr) {
		for (int32_t i = 2; i < argc; i++) {
			exporterSet->parseArgsFunc(argc, argv, i);
		}
	}

	if (Globals::Instance->onlyGenCustomOtr) {
 		if (exporterSet != nullptr) {
 			exporterSet->endProgramFunc();
 		} else {
 			printf("Error: No exporter set, unable to make custom otr.\n");
 		}

 		delete g;
 		return 0;
 	}

	std::string buildMode = argv[1];
	ZFileMode fileMode = ParseFileMode(buildMode, exporterSet);

	if (fileMode == ZFileMode::Invalid)
	{
		printf("Error: Invalid file mode '%s'\n", buildMode.c_str());
		return 1;
	}

	Globals::Instance->fileMode = fileMode;

	if (fileMode == ZFileMode::ExtractDirectory)
		Globals::Instance->rom = new ZRom(Globals::Instance->baseRomPath.string());

	if (Globals::Instance->verbosity >= VerbosityLevel::VERBOSITY_INFO)
		printf("ZAPD: Zelda Asset Processor For Decomp: %s\n", gBuildHash);

	if (Globals::Instance->verbosity >= VerbosityLevel::VERBOSITY_DEBUG)
		WarningHandler::PrintWarningsDebugInfo();

	if (fileMode == ZFileMode::Extract || fileMode == ZFileMode::BuildSourceFile || fileMode == ZFileMode::ExtractDirectory)
		returnCode = HandleExtract(fileMode, exporterSet);
	else if (fileMode == ZFileMode::BuildTexture)
		BuildAssetTexture(Globals::Instance->inputPath, Globals::Instance->texType,
		                  Globals::Instance->outputPath);
	else if (fileMode == ZFileMode::BuildBackground)
		BuildAssetBackground(Globals::Instance->inputPath, Globals::Instance->outputPath);
	else if (fileMode == ZFileMode::BuildBlob)
		BuildAssetBlob(Globals::Instance->inputPath, Globals::Instance->outputPath);

	if (exporterSet != nullptr && exporterSet->endProgramFunc != nullptr)
		exporterSet->endProgramFunc();

	delete g;
	return returnCode;
}

int ExtractFunc(int workerID, int fileListSize, std::string fileListItem, ZFileMode fileMode)
{
	bool parseSuccessful;

	printf("(%i / %i): %s\n", (workerID + 1), fileListSize, fileListItem.c_str());

	for (auto& extFile : Globals::Instance->cfg.externalFiles)
	{
		fs::path externalXmlFilePath = Globals::Instance->cfg.externalXmlFolder / extFile.xmlPath;

		if (Globals::Instance->verbosity >= VerbosityLevel::VERBOSITY_INFO)
		{
			printf("Parsing external file from config: '%s'\n", externalXmlFilePath.c_str());
		}

		parseSuccessful = Parse(externalXmlFilePath, Globals::Instance->baseRomPath,
		                        extFile.outPath, ZFileMode::ExternalFile, workerID);

		if (!parseSuccessful)
			return 1;
	}

	parseSuccessful = Parse(fileListItem, Globals::Instance->baseRomPath,
	                        Globals::Instance->outputPath, fileMode, workerID);

	if (!parseSuccessful)
		return 1;

	if (Globals::Instance->singleThreaded)
	{
		for (int i = 0; i < Globals::Instance->files.size(); i++)
		{
			delete Globals::Instance->files[i];
			Globals::Instance->files.erase(Globals::Instance->files.begin() + i);
			i--;
		}

		Globals::Instance->externalFiles.clear();
		Globals::Instance->segments.clear();
		Globals::Instance->segmentFiles.clear();
		Globals::Instance->cfg.segmentRefFiles.clear();
	}
	else
	{
		for (int i = 0; i < Globals::Instance->workerData[workerID]->files.size(); i++)
		{
			delete Globals::Instance->workerData[workerID]->files[i];
			Globals::Instance->workerData[workerID]->files.erase(
				Globals::Instance->workerData[workerID]->files.begin() +
			                               i);
			i--;
		}

		Globals::Instance->workerData[workerID]->externalFiles.clear();
		Globals::Instance->workerData[workerID]->segments.clear();
		Globals::Instance->workerData[workerID]->segmentFiles.clear();
		Globals::Instance->workerData[workerID]->segmentRefFiles.clear();

		numWorkersLeft--;
	}
	return 0;
}

bool Parse(const fs::path& xmlFilePath, const fs::path& basePath, const fs::path& outPath,
           ZFileMode fileMode, int workerID)
{
	tinyxml2::XMLDocument doc;
	tinyxml2::XMLError eResult = doc.LoadFile(xmlFilePath.string().c_str());

	if (eResult != tinyxml2::XML_SUCCESS)
	{
		// TODO: use XMLDocument::ErrorIDToName to get more specific error messages here
		HANDLE_ERROR(WarningType::InvalidXML,
		             StringHelper::Sprintf("invalid XML file: '%s'", xmlFilePath.c_str()), "");
		return false;
	}

	tinyxml2::XMLNode* root = doc.FirstChild();

	if (root == nullptr)
	{
		HANDLE_WARNING(
			WarningType::InvalidXML,
			StringHelper::Sprintf("missing Root tag in xml file: '%s'", xmlFilePath.c_str()), "");
		return false;
	}

	for (tinyxml2::XMLElement* child = root->FirstChildElement(); child != NULL;
	     child = child->NextSiblingElement())
	{
		if (std::string_view(child->Name()) == "File")
		{
			ZFile* file = new ZFile(fileMode, child, basePath, outPath, "", xmlFilePath, workerID);
			Globals::Instance->AddFile(file, workerID);
			if (fileMode == ZFileMode::ExternalFile)
			{
				Globals::Instance->AddExternalFile(file, workerID);
				file->isExternalFile = true;
			}
		}
		else if (std::string(child->Name()) == "ExternalFile")
		{
			const char* xmlPathValue = child->Attribute("XmlPath");
			if (xmlPathValue == nullptr)
			{
				throw std::runtime_error(StringHelper::Sprintf(
					"Parse: Fatal error in '%s'.\n"
					"\t Missing 'XmlPath' attribute in `ExternalFile` element.\n",
					xmlFilePath.c_str()));
			}
			const char* outPathValue = child->Attribute("OutPath");
			if (outPathValue == nullptr)
			{
				throw std::runtime_error(StringHelper::Sprintf(
					"Parse: Fatal error in '%s'.\n"
					"\t Missing 'OutPath' attribute in `ExternalFile` element.\n",
					xmlFilePath.c_str()));
			}

			fs::path externalXmlFilePath =
				Globals::Instance->cfg.externalXmlFolder / fs::path(xmlPathValue);
			fs::path externalOutFilePath = fs::path(outPathValue);

			if (Globals::Instance->verbosity >= VerbosityLevel::VERBOSITY_INFO)
			{
				printf("Parsing external file: '%s'\n", externalXmlFilePath.c_str());
			}

			// Recursion. What can go wrong?
			Parse(externalXmlFilePath, basePath, externalOutFilePath, ZFileMode::ExternalFile, workerID);
		}
		else
		{
			std::string errorHeader =
				StringHelper::Sprintf("when parsing file '%s'", xmlFilePath.c_str());
			std::string errorBody = StringHelper::Sprintf(
				"Found a resource outside a File element: '%s'", child->Name());
			HANDLE_ERROR(WarningType::InvalidXML, errorHeader, errorBody);
		}
	}

	if (fileMode != ZFileMode::ExternalFile)
	{
		ExporterSet* exporterSet = Globals::Instance->GetExporterSet();

		if (exporterSet != nullptr && exporterSet->beginXMLFunc != nullptr)
			exporterSet->beginXMLFunc();

		std::vector<ZFile*> files;

		if (Globals::Instance->singleThreaded)
			files = Globals::Instance->files;
		else
			files = Globals::Instance->workerData[workerID]->files;

		for (ZFile* file : files)
		{
			if (fileMode == ZFileMode::BuildSourceFile)
				file->BuildSourceFile();
			else
				file->ExtractResources();
		}

		if (exporterSet != nullptr && exporterSet->endXMLFunc != nullptr)
			exporterSet->endXMLFunc();
	}

	return true;
}

void ParseArgs(int& argc, char* argv[])
{
	static const std::unordered_map<std::string, ArgFunc> ArgFuncDictionary = {
		{"-o", &Arg_SetOutputPath},
		{"--outputpath", &Arg_SetOutputPath},
		{"-i", &Arg_SetInputPath},
		{"--inputpath", &Arg_SetInputPath},
		{"-b", &Arg_SetBaseromPath},
		{"--baserompath", &Arg_SetBaseromPath},
		{"-osf", &Arg_SetSourceOutputPath},
		{"-gsf", &Arg_GenerateSourceFile},
		{"-tm", &Arg_TestMode},
		{"-ulzdl", &Arg_LegacyDList},
		{"-profile", &Arg_EnableProfiling},
		{"-uer", &Arg_UseExternalResources},
		{"-tt", &Arg_SetTextureType},
		{"-rconf", &Arg_ReadConfigFile},
		{"-eh", &Arg_EnableErrorHandler},
		{"-v", &Arg_SetVerbosity},
		{"-vu", &Arg_VerboseUnaccounted},
		{"--verbose-unaccounted", &Arg_VerboseUnaccounted},
		{"-se", &Arg_SetExporter},
		{"--set-exporter", &Arg_SetExporter},
		{"--gcc-compat", &Arg_EnableGCCCompat},
		{"-s", &Arg_ForceStatic},
		{"--static", &Arg_ForceStatic},
		{"-us", &Arg_ForceUnaccountedStatic},
		{"--unaccounted-static", &Arg_ForceUnaccountedStatic},
		{"-fl", &Arg_SetFileListPath},
		{"-brt", &Arg_SetBuildRawTexture},
		{"--norom", &Arg_SetNoRomMode},
		{"-oxml", &Arg_SetXMLMode},
	};

	for (int32_t i = 2; i < argc; i++)
	{
		std::string arg = argv[i];

		// Ignore warning args as they have already been parsed
		if (arg.length() > 2 && arg[0] == '-' && arg[1] == 'W' && arg[2] != '\0')
		{
			continue;
		}

		auto it = ArgFuncDictionary.find(arg);
		if (it == ArgFuncDictionary.end())
		{
			fprintf(stderr, "Unsupported argument: %s\n", arg.c_str());
			ExporterSet* exporterSet = Globals::Instance->GetExporterSet();
			if (exporterSet != nullptr)
				exporterSet->parseArgsFunc(argc, argv, i);
			continue;
		}

		std::invoke(it->second, i, argv);
	}
}

ZFileMode ParseFileMode(const std::string& buildMode, ExporterSet* exporterSet)
{
	ZFileMode fileMode = ZFileMode::Invalid;

	if (buildMode == "btex")
		fileMode = ZFileMode::BuildTexture;
	else if (buildMode == "bren")
		fileMode = ZFileMode::BuildBackground;
	else if (buildMode == "bsf")
		fileMode = ZFileMode::BuildSourceFile;
	else if (buildMode == "bblb")
		fileMode = ZFileMode::BuildBlob;
	else if (buildMode == "e")
		fileMode = ZFileMode::Extract;
	else if (buildMode == "ed")
		fileMode = ZFileMode::ExtractDirectory;
	else if (exporterSet != nullptr && exporterSet->parseFileModeFunc != nullptr)
		exporterSet->parseFileModeFunc(buildMode, fileMode);

	return fileMode;
}

void Arg_SetOutputPath(int& i, [[maybe_unused]] char* argv[])
{
	Globals::Instance->outputPath = argv[++i];

	if (Globals::Instance->sourceOutputPath == "")
		Globals::Instance->sourceOutputPath = Globals::Instance->outputPath;
}

void Arg_SetInputPath(int& i, char* argv[])
{
	Globals::Instance->inputPath = argv[++i];
}

void Arg_SetBaseromPath(int& i, char* argv[])
{
	Globals::Instance->baseRomPath = argv[++i];
}

void Arg_SetSourceOutputPath(int& i, char* argv[])
{
	Globals::Instance->sourceOutputPath = argv[++i];
}

void Arg_GenerateSourceFile(int& i, char* argv[])
{
	// Generate source file during extraction
	Globals::Instance->genSourceFile = std::string_view(argv[++i]) == "1";
}

void Arg_TestMode(int& i, char* argv[])
{
	// Test Mode (enables certain experimental features)
	Globals::Instance->testMode = std::string_view(argv[++i]) == "1";
}

void Arg_LegacyDList(int& i, char* argv[])
{
	Globals::Instance->useLegacyZDList = std::string_view(argv[++i]) == "1";
}

void Arg_EnableProfiling(int& i, char* argv[])
{
	Globals::Instance->profile = std::string_view(argv[++i]) == "1";
}

void Arg_UseExternalResources(int& i, char* argv[])
{
	// Split resources into their individual components(enabled by default)
	// TODO: We may wish to make this a part of the config file...
	Globals::Instance->useExternalResources = std::string_view(argv[++i]) == "1";
}

void Arg_SetTextureType(int& i, char* argv[])
{
	Globals::Instance->texType = ZTexture::GetTextureTypeFromString(argv[++i]);
}

void Arg_ReadConfigFile(int& i, char* argv[])
{
	Globals::Instance->cfg.ReadConfigFile(argv[++i]);
}

void Arg_EnableErrorHandler([[maybe_unused]] int& i, [[maybe_unused]] char* argv[])
{
	CrashHandler_Init();
}

void Arg_SetVerbosity(int& i, char* argv[])
{
	Globals::Instance->verbosity = static_cast<VerbosityLevel>(strtol(argv[++i], NULL, 16));
}

void Arg_VerboseUnaccounted([[maybe_unused]] int& i, [[maybe_unused]] char* argv[])
{
	Globals::Instance->verboseUnaccounted = true;
}

void Arg_SetExporter(int& i, char* argv[])
{
	ImportExporters();
	Globals::Instance->currentExporter = argv[++i];
}

void Arg_EnableGCCCompat([[maybe_unused]] int& i, [[maybe_unused]] char* argv[])
{
	Globals::Instance->gccCompat = true;
}

void Arg_ForceStatic([[maybe_unused]] int& i, [[maybe_unused]] char* argv[])
{
	Globals::Instance->forceStatic = true;
}

void Arg_ForceUnaccountedStatic([[maybe_unused]] int& i, [[maybe_unused]] char* argv[])
{
	Globals::Instance->forceUnaccountedStatic = true;
}

void Arg_SetFileListPath(int& i,  char* argv[])
{
	Globals::Instance->fileListPath = argv[++i];
}

void Arg_SetBuildRawTexture([[maybe_unused]] int& i, [[maybe_unused]] char* argv[])
{
	Globals::Instance->buildRawTexture = true;
}

void Arg_SetNoRomMode([[maybe_unused]] int& i, [[maybe_unused]] char* argv[])
{
	Globals::Instance->onlyGenCustomOtr = true;
}

void Arg_SetXMLMode(int& i, char* argv[])
{
	char* xmlList = argv[++i];
	size_t xmlListPos = 0;
	size_t xmlListLen = strlen(xmlList);

	while (xmlListPos < xmlListLen)
	{
		char* nextDelimiterPtr = strchr(&xmlList[xmlListPos], ',');
		if (nextDelimiterPtr == nullptr)
			nextDelimiterPtr = strchr(&xmlList[xmlListPos], 0);

		if (nextDelimiterPtr == nullptr)
			return;

		size_t curModeLen = nextDelimiterPtr - &xmlList[xmlListPos];

		// Audio Sound Font (asf)
		if (strncmp(&xmlList[xmlListPos], "asf", curModeLen) == 0)
			Globals::Instance->xmlExtractModes |= 1 << (int)XMLModeShift::SoundFont;
		// Audio Sample (asp)
		else if (strncmp(&xmlList[xmlListPos], "asp", curModeLen) == 0)
			Globals::Instance->xmlExtractModes |= 1 << (int)XMLModeShift::Sample;
		// Audio Sequence (asq)
		else if (strncmp(&xmlList[xmlListPos], "asq", curModeLen) == 0)
			Globals::Instance->xmlExtractModes |= 1 << (int)XMLModeShift::Sequence;
		
		// We read the 3 chars for the type
		xmlListPos += curModeLen;
				
		if (xmlList[xmlListPos] != ',' && xmlList[xmlListPos] != 0)
			HANDLE_WARNING(
				WarningType::Always, "Invalid Argument",
				"XML Extract mode not separated by ','. This may have unintended side effects.");
		
		xmlListPos++;
	}
}

int HandleExtract(ZFileMode fileMode, ExporterSet* exporterSet)
{
	bool procFileModeSuccess = false;

	if (exporterSet != nullptr && exporterSet->processFileModeFunc != nullptr)
		procFileModeSuccess = exporterSet->processFileModeFunc(fileMode);

	if (!procFileModeSuccess)
	{
		bool parseSuccessful;

		for (auto& extFile : Globals::Instance->cfg.externalFiles)
		{
			if (fileMode == ZFileMode::ExtractDirectory)
			{
				std::vector<std::string> fileList =
					Directory::ListFiles(Globals::Instance->inputPath.string());

				const int num_threads = std::thread::hardware_concurrency();
				ctpl::thread_pool pool(num_threads > 1 ? num_threads / 2 : 1);

				bool parseSuccessful;

				auto start = std::chrono::steady_clock::now();
				int fileListSize = fileList.size();
				Globals::Instance->singleThreaded = false;

				for (int i = 0; i < fileListSize; i++)
					Globals::Instance->workerData[i] = new FileWorker();

				numWorkersLeft = fileListSize;

				for (int i = 0; i < fileListSize; i++)
				{
					if (Globals::Instance->singleThreaded)
					{
						ExtractFunc(i, fileList.size(), fileList[i], fileMode);
					}
					else
					{
						std::string fileListItem = fileList[i];
						pool.push([i, fileListSize, fileListItem, fileMode](int) {
							ExtractFunc(i, fileListSize, fileListItem, fileMode);
						});
					}
				}

				if (!Globals::Instance->singleThreaded)
				{
					while (true)
					{
						if (numWorkersLeft <= 0)
							break;

						std::this_thread::sleep_for(std::chrono::milliseconds(250));
					}
				}

				auto end = std::chrono::steady_clock::now();
				auto diff = std::chrono::duration_cast<std::chrono::seconds>(end - start).count();

				printf("Generated OTR File Data in %i seconds\n", diff);
			}
			else
			{
				fs::path externalXmlFilePath =
					Globals::Instance->cfg.externalXmlFolder / extFile.xmlPath;

				if (Globals::Instance->verbosity >= VerbosityLevel::VERBOSITY_INFO)
					printf("Parsing external file from config: '%s'\n",
					       externalXmlFilePath.c_str());

				parseSuccessful = Parse(externalXmlFilePath, Globals::Instance->baseRomPath,
				                        extFile.outPath, ZFileMode::ExternalFile, 0);

				if (!parseSuccessful)
					return 1;
			}
		}
	}

	return 0;
}

void BuildAssetTexture(const fs::path& pngFilePath, TextureType texType, const fs::path& outPath)
{
	return Globals::Instance->BuildAssetTexture(pngFilePath, texType, outPath);
}

void BuildAssetBackground(const fs::path& imageFilePath, const fs::path& outPath)
{
	ZBackground background(nullptr);
	background.ParseBinaryFile(imageFilePath.string(), false);

	DiskFile::WriteAllText(outPath.string(), background.GetBodySourceCode());
}

void BuildAssetBlob(const fs::path& blobFilePath, const fs::path& outPath)
{
	ZBlob* blob = ZBlob::FromFile(blobFilePath.string());
	std::string name = outPath.stem().string();  // filename without extension

	std::string src = blob->GetBodySourceCode();

	DiskFile::WriteAllText(outPath.string(), src);

	delete blob;
}