diff --git a/Makefile b/Makefile index ccb21b81ae..12582d24a6 100644 --- a/Makefile +++ b/Makefile @@ -486,10 +486,10 @@ endif ASSET_BIN_DIRS_COMMITTED := $(shell find assets -type d -not -path "assets/xml*" -not -path "assets/audio*" -not -path assets/text) ASSET_BIN_DIRS := $(ASSET_BIN_DIRS_EXTRACTED) $(ASSET_BIN_DIRS_COMMITTED) -ASSET_FILES_BIN_EXTRACTED := $(foreach dir,$(ASSET_BIN_DIRS_EXTRACTED),$(wildcard $(dir)/*.bin)) -ASSET_FILES_BIN_COMMITTED := $(foreach dir,$(ASSET_BIN_DIRS_COMMITTED),$(wildcard $(dir)/*.bin)) -ASSET_FILES_OUT := $(foreach f,$(ASSET_FILES_BIN_EXTRACTED:.bin=.bin.inc.c),$(f:$(EXTRACTED_DIR)/%=$(BUILD_DIR)/%)) \ - $(foreach f,$(ASSET_FILES_BIN_COMMITTED:.bin=.bin.inc.c),$(BUILD_DIR)/$f) +ASSET_FILES_BIN_EXTRACTED := $(foreach dir,$(ASSET_BIN_DIRS_EXTRACTED),$(wildcard $(dir)/*.u8.bin)) +ASSET_FILES_BIN_COMMITTED := $(foreach dir,$(ASSET_BIN_DIRS_COMMITTED),$(wildcard $(dir)/*.u8.bin)) +ASSET_FILES_OUT := $(foreach f,$(ASSET_FILES_BIN_EXTRACTED:.bin=.inc.c),$(f:$(EXTRACTED_DIR)/%=$(BUILD_DIR)/%)) \ + $(foreach f,$(ASSET_FILES_BIN_COMMITTED:.bin=.inc.c),$(BUILD_DIR)/$f) # Find all .o files included in the spec SPEC_O_FILES := $(shell $(CPP) $(CPPFLAGS) -I. $(SPEC) | $(BUILD_DIR_REPLACE) | sed -n -E 's/^[ \t]*include[ \t]*"([a-zA-Z0-9/_.-]+\.o)"/\1/p') @@ -502,10 +502,10 @@ OVL_RELOC_FILES := $(filter %_reloc.o,$(SPEC_O_FILES)) # (Only asm_processor dependencies and reloc dependencies are handled for now) DEP_FILES := $(O_FILES:.o=.d) $(O_FILES:.o=.asmproc.d) $(OVL_RELOC_FILES:.o=.d) $(BUILD_DIR)/spec.d -TEXTURE_FILES_PNG_EXTRACTED := $(foreach dir,$(ASSET_BIN_DIRS_EXTRACTED),$(wildcard $(dir)/*.png)) -TEXTURE_FILES_PNG_COMMITTED := $(foreach dir,$(ASSET_BIN_DIRS_COMMITTED),$(wildcard $(dir)/*.png)) -TEXTURE_FILES_JPG_EXTRACTED := $(foreach dir,$(ASSET_BIN_DIRS_EXTRACTED),$(wildcard $(dir)/*.jpg)) -TEXTURE_FILES_JPG_COMMITTED := $(foreach dir,$(ASSET_BIN_DIRS_COMMITTED),$(wildcard $(dir)/*.jpg)) +TEXTURE_FILES_PNG_EXTRACTED := $(foreach dir,$(ASSET_BIN_DIRS_EXTRACTED),$(wildcard $(dir)/*.u64.png) $(wildcard $(dir)/*.u32.png)) +TEXTURE_FILES_PNG_COMMITTED := $(foreach dir,$(ASSET_BIN_DIRS_COMMITTED),$(wildcard $(dir)/*.u64.png) $(wildcard $(dir)/*.u32.png)) +TEXTURE_FILES_JPG_EXTRACTED := $(foreach dir,$(ASSET_BIN_DIRS_EXTRACTED),$(wildcard $(dir)/*.u64.jpg)) +TEXTURE_FILES_JPG_COMMITTED := $(foreach dir,$(ASSET_BIN_DIRS_COMMITTED),$(wildcard $(dir)/*.u64.jpg)) TEXTURE_FILES_OUT := $(foreach f,$(TEXTURE_FILES_PNG_EXTRACTED:.png=.inc.c),$(f:$(EXTRACTED_DIR)/%=$(BUILD_DIR)/%)) \ $(foreach f,$(TEXTURE_FILES_PNG_COMMITTED:.png=.inc.c),$(BUILD_DIR)/$f) \ $(foreach f,$(TEXTURE_FILES_JPG_EXTRACTED:.jpg=.jpg.inc.c),$(f:$(EXTRACTED_DIR)/%=$(BUILD_DIR)/%)) \ @@ -791,9 +791,9 @@ setup: venv $(MAKE) -C tools $(PYTHON) tools/decompress_baserom.py $(VERSION) $(PYTHON) tools/extract_baserom.py $(BASEROM_DIR)/baserom-decompressed.z64 $(EXTRACTED_DIR)/baserom -v $(VERSION) + $(PYTHON) -m tools.assets.extract $(EXTRACTED_DIR)/baserom $(EXTRACTED_DIR) -v $(VERSION) -j$(N_THREADS) $(PYTHON) tools/extract_incbins.py $(EXTRACTED_DIR)/baserom $(EXTRACTED_DIR)/incbin -v $(VERSION) $(PYTHON) tools/extract_text.py $(EXTRACTED_DIR)/baserom $(EXTRACTED_DIR)/text -v $(VERSION) - $(PYTHON) tools/extract_assets.py $(EXTRACTED_DIR)/baserom $(EXTRACTED_DIR)/assets -v $(VERSION) -j$(N_THREADS) $(PYTHON) tools/extract_audio.py -b $(EXTRACTED_DIR)/baserom -o $(EXTRACTED_DIR) -v $(VERSION) --read-xml disasm: @@ -979,22 +979,26 @@ $(BUILD_DIR)/src/overlays/%_reloc.o: $(BUILD_DIR)/spec $(POSTPROCESS_OBJ) $(@:.o=.s) $(AS) $(ASFLAGS) $(@:.o=.s) -o $@ +# Assets from assets/ + $(BUILD_DIR)/assets/%.inc.c: assets/%.png - $(N64TEXCONV) $(subst .,,$(suffix $*)) "$(findstring u32,$(subst .,,$(suffix $(basename $*))))" $< $@ $(@:.inc.c=.pal.inc.c) + tools/assets/build_from_png/build_from_png $< $(dir $@) assets/$(dir $*) $(wildcard $(EXTRACTED_DIR)/assets/$(dir $*)) -$(BUILD_DIR)/assets/%.inc.c: $(EXTRACTED_DIR)/assets/%.png - $(N64TEXCONV) $(subst .,,$(suffix $*)) "$(findstring u32,$(subst .,,$(suffix $(basename $*))))" $< $@ $(@:.inc.c=.pal.inc.c) - -$(BUILD_DIR)/assets/%.bin.inc.c: assets/%.bin +$(BUILD_DIR)/assets/%.u8.inc.c: assets/%.u8.bin $(BIN2C) -t 1 $< $@ -$(BUILD_DIR)/assets/%.bin.inc.c: $(EXTRACTED_DIR)/assets/%.bin - $(BIN2C) -t 1 $< $@ - -$(BUILD_DIR)/assets/%.jpg.inc.c: assets/%.jpg +$(BUILD_DIR)/assets/%.u64.jpg.inc.c: assets/%.u64.jpg $(N64TEXCONV) JFIF "" $< $@ -$(BUILD_DIR)/assets/%.jpg.inc.c: $(EXTRACTED_DIR)/assets/%.jpg +# Assets from extracted/ + +$(BUILD_DIR)/assets/%.inc.c: $(EXTRACTED_DIR)/assets/%.png + tools/assets/build_from_png/build_from_png $< $(dir $@) $(wildcard assets/$(dir $*)) $(EXTRACTED_DIR)/assets/$(dir $*) + +$(BUILD_DIR)/assets/%.u8.inc.c: $(EXTRACTED_DIR)/assets/%.u8.bin + $(BIN2C) -t 1 $< $@ + +$(BUILD_DIR)/assets/%.u64.jpg.inc.c: $(EXTRACTED_DIR)/assets/%.u64.jpg $(N64TEXCONV) JFIF "" $< $@ # Audio diff --git a/assets/xml/code/fbdemo_circle.xml b/assets/xml/code/fbdemo_circle.xml index 530506369c..618c743314 100644 --- a/assets/xml/code/fbdemo_circle.xml +++ b/assets/xml/code/fbdemo_circle.xml @@ -7,7 +7,6 @@ - - + diff --git a/assets/xml/code/fbdemo_wipe1.xml b/assets/xml/code/fbdemo_wipe1.xml index 74f129776b..87f7e47b6f 100644 --- a/assets/xml/code/fbdemo_wipe1.xml +++ b/assets/xml/code/fbdemo_wipe1.xml @@ -4,7 +4,6 @@ - - + diff --git a/assets/xml/objects/gameplay_keep.xml b/assets/xml/objects/gameplay_keep.xml index 008497601a..1a1077f038 100644 --- a/assets/xml/objects/gameplay_keep.xml +++ b/assets/xml/objects/gameplay_keep.xml @@ -1,5 +1,5 @@ - + diff --git a/assets/xml/objects/gameplay_keep_pal.xml b/assets/xml/objects/gameplay_keep_pal.xml index c7485d73fd..92a7bb06e0 100644 --- a/assets/xml/objects/gameplay_keep_pal.xml +++ b/assets/xml/objects/gameplay_keep_pal.xml @@ -1,5 +1,5 @@ - + diff --git a/assets/xml/objects/object_bdoor.xml b/assets/xml/objects/object_bdoor.xml index e926ae40bd..e15f0f6294 100644 --- a/assets/xml/objects/object_bdoor.xml +++ b/assets/xml/objects/object_bdoor.xml @@ -1,5 +1,5 @@ - + diff --git a/assets/xml/objects/object_demo_6k.xml b/assets/xml/objects/object_demo_6k.xml index 73058d5e46..e2de93db2e 100644 --- a/assets/xml/objects/object_demo_6k.xml +++ b/assets/xml/objects/object_demo_6k.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_demo_kekkai.xml b/assets/xml/objects/object_demo_kekkai.xml index 1b9c9b4027..8b7b739c64 100644 --- a/assets/xml/objects/object_demo_kekkai.xml +++ b/assets/xml/objects/object_demo_kekkai.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_efc_erupc.xml b/assets/xml/objects/object_efc_erupc.xml index 800d9535f1..13cc2ab033 100644 --- a/assets/xml/objects/object_efc_erupc.xml +++ b/assets/xml/objects/object_efc_erupc.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_fish.xml b/assets/xml/objects/object_fish.xml index f5ad4f6da0..2ce27bac3a 100644 --- a/assets/xml/objects/object_fish.xml +++ b/assets/xml/objects/object_fish.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_fz.xml b/assets/xml/objects/object_fz.xml index dad6fec5ce..bbed88b106 100644 --- a/assets/xml/objects/object_fz.xml +++ b/assets/xml/objects/object_fz.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_arrow.xml b/assets/xml/objects/object_gi_arrow.xml index 4b58787a9d..4ce9110cc1 100644 --- a/assets/xml/objects/object_gi_arrow.xml +++ b/assets/xml/objects/object_gi_arrow.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_arrowcase.xml b/assets/xml/objects/object_gi_arrowcase.xml index 267b0a734d..990576428d 100644 --- a/assets/xml/objects/object_gi_arrowcase.xml +++ b/assets/xml/objects/object_gi_arrowcase.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_bean.xml b/assets/xml/objects/object_gi_bean.xml index e74247816f..2c6ce0cf12 100644 --- a/assets/xml/objects/object_gi_bean.xml +++ b/assets/xml/objects/object_gi_bean.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_bomb_1.xml b/assets/xml/objects/object_gi_bomb_1.xml index bae86c11d8..5d7dab6d86 100644 --- a/assets/xml/objects/object_gi_bomb_1.xml +++ b/assets/xml/objects/object_gi_bomb_1.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_bomb_2.xml b/assets/xml/objects/object_gi_bomb_2.xml index 1400c4a4d4..01f3956803 100644 --- a/assets/xml/objects/object_gi_bomb_2.xml +++ b/assets/xml/objects/object_gi_bomb_2.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_bombpouch.xml b/assets/xml/objects/object_gi_bombpouch.xml index 07134748c3..42620ec94d 100644 --- a/assets/xml/objects/object_gi_bombpouch.xml +++ b/assets/xml/objects/object_gi_bombpouch.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_boomerang.xml b/assets/xml/objects/object_gi_boomerang.xml index 3c1a0fe7fc..fef261c489 100644 --- a/assets/xml/objects/object_gi_boomerang.xml +++ b/assets/xml/objects/object_gi_boomerang.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_boots_2.xml b/assets/xml/objects/object_gi_boots_2.xml index 8e9cd1028d..e172bd006c 100644 --- a/assets/xml/objects/object_gi_boots_2.xml +++ b/assets/xml/objects/object_gi_boots_2.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_bosskey.xml b/assets/xml/objects/object_gi_bosskey.xml index e5e4bc86c9..8e93c10d1a 100644 --- a/assets/xml/objects/object_gi_bosskey.xml +++ b/assets/xml/objects/object_gi_bosskey.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_bottle.xml b/assets/xml/objects/object_gi_bottle.xml index 3b0884a03f..0a27562954 100644 --- a/assets/xml/objects/object_gi_bottle.xml +++ b/assets/xml/objects/object_gi_bottle.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_bottle_letter.xml b/assets/xml/objects/object_gi_bottle_letter.xml index 443219caf5..04b08dd673 100644 --- a/assets/xml/objects/object_gi_bottle_letter.xml +++ b/assets/xml/objects/object_gi_bottle_letter.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_bow.xml b/assets/xml/objects/object_gi_bow.xml index 946e9c4965..6e9101b413 100644 --- a/assets/xml/objects/object_gi_bow.xml +++ b/assets/xml/objects/object_gi_bow.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_bracelet.xml b/assets/xml/objects/object_gi_bracelet.xml index 5a0b62a60a..da35c003f8 100644 --- a/assets/xml/objects/object_gi_bracelet.xml +++ b/assets/xml/objects/object_gi_bracelet.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_brokensword.xml b/assets/xml/objects/object_gi_brokensword.xml index 408741ac54..44cae3e100 100644 --- a/assets/xml/objects/object_gi_brokensword.xml +++ b/assets/xml/objects/object_gi_brokensword.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_butterfly.xml b/assets/xml/objects/object_gi_butterfly.xml index 76ac706096..9882d27954 100644 --- a/assets/xml/objects/object_gi_butterfly.xml +++ b/assets/xml/objects/object_gi_butterfly.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_coin.xml b/assets/xml/objects/object_gi_coin.xml index 22e29f255f..f65993465b 100644 --- a/assets/xml/objects/object_gi_coin.xml +++ b/assets/xml/objects/object_gi_coin.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_compass.xml b/assets/xml/objects/object_gi_compass.xml index 076229b11e..10c6fbb63a 100644 --- a/assets/xml/objects/object_gi_compass.xml +++ b/assets/xml/objects/object_gi_compass.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_dekupouch.xml b/assets/xml/objects/object_gi_dekupouch.xml index 3d6d95d98a..25cde931f2 100644 --- a/assets/xml/objects/object_gi_dekupouch.xml +++ b/assets/xml/objects/object_gi_dekupouch.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_egg.xml b/assets/xml/objects/object_gi_egg.xml index 2b2e2847db..ceae8be407 100644 --- a/assets/xml/objects/object_gi_egg.xml +++ b/assets/xml/objects/object_gi_egg.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_eye_lotion.xml b/assets/xml/objects/object_gi_eye_lotion.xml index 5128c5f6ff..86e053cd94 100644 --- a/assets/xml/objects/object_gi_eye_lotion.xml +++ b/assets/xml/objects/object_gi_eye_lotion.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_fire.xml b/assets/xml/objects/object_gi_fire.xml index a57fba6e86..3b81815d5f 100644 --- a/assets/xml/objects/object_gi_fire.xml +++ b/assets/xml/objects/object_gi_fire.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_fish.xml b/assets/xml/objects/object_gi_fish.xml index edb39dc297..75361b32da 100644 --- a/assets/xml/objects/object_gi_fish.xml +++ b/assets/xml/objects/object_gi_fish.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_frog.xml b/assets/xml/objects/object_gi_frog.xml index f180fd267b..8c5d616eb4 100644 --- a/assets/xml/objects/object_gi_frog.xml +++ b/assets/xml/objects/object_gi_frog.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_gerudo.xml b/assets/xml/objects/object_gi_gerudo.xml index 3be8d34620..26dc606ce0 100644 --- a/assets/xml/objects/object_gi_gerudo.xml +++ b/assets/xml/objects/object_gi_gerudo.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_ghost.xml b/assets/xml/objects/object_gi_ghost.xml index 186f4c74b7..e6c631c98e 100644 --- a/assets/xml/objects/object_gi_ghost.xml +++ b/assets/xml/objects/object_gi_ghost.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_glasses.xml b/assets/xml/objects/object_gi_glasses.xml index 63d32ab5ac..4a9cacf086 100644 --- a/assets/xml/objects/object_gi_glasses.xml +++ b/assets/xml/objects/object_gi_glasses.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_gloves.xml b/assets/xml/objects/object_gi_gloves.xml index 1b4282dcaa..fb273e95f4 100644 --- a/assets/xml/objects/object_gi_gloves.xml +++ b/assets/xml/objects/object_gi_gloves.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_goddess.xml b/assets/xml/objects/object_gi_goddess.xml index 50cbdd8918..6339012d47 100644 --- a/assets/xml/objects/object_gi_goddess.xml +++ b/assets/xml/objects/object_gi_goddess.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_grass.xml b/assets/xml/objects/object_gi_grass.xml index ae7834201a..2cc465c959 100644 --- a/assets/xml/objects/object_gi_grass.xml +++ b/assets/xml/objects/object_gi_grass.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_hammer.xml b/assets/xml/objects/object_gi_hammer.xml index feb5c8659d..49da345a93 100644 --- a/assets/xml/objects/object_gi_hammer.xml +++ b/assets/xml/objects/object_gi_hammer.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_heart.xml b/assets/xml/objects/object_gi_heart.xml index 48e78b1b5c..b3576efaad 100644 --- a/assets/xml/objects/object_gi_heart.xml +++ b/assets/xml/objects/object_gi_heart.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_hearts.xml b/assets/xml/objects/object_gi_hearts.xml index d2e763e631..122c898571 100644 --- a/assets/xml/objects/object_gi_hearts.xml +++ b/assets/xml/objects/object_gi_hearts.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_hookshot.xml b/assets/xml/objects/object_gi_hookshot.xml index a6b3b0fdac..513194fa7d 100644 --- a/assets/xml/objects/object_gi_hookshot.xml +++ b/assets/xml/objects/object_gi_hookshot.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_hoverboots.xml b/assets/xml/objects/object_gi_hoverboots.xml index c4a67877b2..9d710662e5 100644 --- a/assets/xml/objects/object_gi_hoverboots.xml +++ b/assets/xml/objects/object_gi_hoverboots.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_insect.xml b/assets/xml/objects/object_gi_insect.xml index 7af5b5b3b2..9467605ce2 100644 --- a/assets/xml/objects/object_gi_insect.xml +++ b/assets/xml/objects/object_gi_insect.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_jewel.xml b/assets/xml/objects/object_gi_jewel.xml index e83c651164..5dc87f53e2 100644 --- a/assets/xml/objects/object_gi_jewel.xml +++ b/assets/xml/objects/object_gi_jewel.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_key.xml b/assets/xml/objects/object_gi_key.xml index a37d45a71c..e38547a32c 100644 --- a/assets/xml/objects/object_gi_key.xml +++ b/assets/xml/objects/object_gi_key.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_ki_tan_mask.xml b/assets/xml/objects/object_gi_ki_tan_mask.xml index f66535af37..e447c8fadf 100644 --- a/assets/xml/objects/object_gi_ki_tan_mask.xml +++ b/assets/xml/objects/object_gi_ki_tan_mask.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_liquid.xml b/assets/xml/objects/object_gi_liquid.xml index 5eeeca0fd2..b3af2b2627 100644 --- a/assets/xml/objects/object_gi_liquid.xml +++ b/assets/xml/objects/object_gi_liquid.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_longsword.xml b/assets/xml/objects/object_gi_longsword.xml index 7161e42e38..bdfffe3b16 100644 --- a/assets/xml/objects/object_gi_longsword.xml +++ b/assets/xml/objects/object_gi_longsword.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_m_arrow.xml b/assets/xml/objects/object_gi_m_arrow.xml index 0fd659ae95..069a1bf1d4 100644 --- a/assets/xml/objects/object_gi_m_arrow.xml +++ b/assets/xml/objects/object_gi_m_arrow.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_magicpot.xml b/assets/xml/objects/object_gi_magicpot.xml index 7623e6353e..070de07fa0 100644 --- a/assets/xml/objects/object_gi_magicpot.xml +++ b/assets/xml/objects/object_gi_magicpot.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_map.xml b/assets/xml/objects/object_gi_map.xml index 8887dd22c9..619b0bc845 100644 --- a/assets/xml/objects/object_gi_map.xml +++ b/assets/xml/objects/object_gi_map.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_medal.xml b/assets/xml/objects/object_gi_medal.xml index d2cb6191d9..5676a9e316 100644 --- a/assets/xml/objects/object_gi_medal.xml +++ b/assets/xml/objects/object_gi_medal.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_melody.xml b/assets/xml/objects/object_gi_melody.xml index b01fca9538..e028bc9463 100644 --- a/assets/xml/objects/object_gi_melody.xml +++ b/assets/xml/objects/object_gi_melody.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_milk.xml b/assets/xml/objects/object_gi_milk.xml index 00b9530d95..3e5cb0cb5a 100644 --- a/assets/xml/objects/object_gi_milk.xml +++ b/assets/xml/objects/object_gi_milk.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_mushroom.xml b/assets/xml/objects/object_gi_mushroom.xml index 5b19bca743..8ee686263c 100644 --- a/assets/xml/objects/object_gi_mushroom.xml +++ b/assets/xml/objects/object_gi_mushroom.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_niwatori.xml b/assets/xml/objects/object_gi_niwatori.xml index 713cc1ce5a..8af44b8708 100644 --- a/assets/xml/objects/object_gi_niwatori.xml +++ b/assets/xml/objects/object_gi_niwatori.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_nuts.xml b/assets/xml/objects/object_gi_nuts.xml index 5508fe8569..d1a8454dbc 100644 --- a/assets/xml/objects/object_gi_nuts.xml +++ b/assets/xml/objects/object_gi_nuts.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_ocarina.xml b/assets/xml/objects/object_gi_ocarina.xml index 7693cc122f..b8714d6e3c 100644 --- a/assets/xml/objects/object_gi_ocarina.xml +++ b/assets/xml/objects/object_gi_ocarina.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_ocarina_0.xml b/assets/xml/objects/object_gi_ocarina_0.xml index 336d338946..caca8f2002 100644 --- a/assets/xml/objects/object_gi_ocarina_0.xml +++ b/assets/xml/objects/object_gi_ocarina_0.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_pachinko.xml b/assets/xml/objects/object_gi_pachinko.xml index 5f808baf92..9967813b3d 100644 --- a/assets/xml/objects/object_gi_pachinko.xml +++ b/assets/xml/objects/object_gi_pachinko.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_powder.xml b/assets/xml/objects/object_gi_powder.xml index fb7dc0155d..4e33b58208 100644 --- a/assets/xml/objects/object_gi_powder.xml +++ b/assets/xml/objects/object_gi_powder.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_prescription.xml b/assets/xml/objects/object_gi_prescription.xml index 081de301c4..9fa16660c7 100644 --- a/assets/xml/objects/object_gi_prescription.xml +++ b/assets/xml/objects/object_gi_prescription.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_rabit_mask.xml b/assets/xml/objects/object_gi_rabit_mask.xml index 75f855550d..a3c07e469c 100644 --- a/assets/xml/objects/object_gi_rabit_mask.xml +++ b/assets/xml/objects/object_gi_rabit_mask.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_redead_mask.xml b/assets/xml/objects/object_gi_redead_mask.xml index 7de08487f8..fe601cab64 100644 --- a/assets/xml/objects/object_gi_redead_mask.xml +++ b/assets/xml/objects/object_gi_redead_mask.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_rupy.xml b/assets/xml/objects/object_gi_rupy.xml index 0a1af96d0f..07b18b82dd 100644 --- a/assets/xml/objects/object_gi_rupy.xml +++ b/assets/xml/objects/object_gi_rupy.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_saw.xml b/assets/xml/objects/object_gi_saw.xml index dcc038b7c1..999b818e8b 100644 --- a/assets/xml/objects/object_gi_saw.xml +++ b/assets/xml/objects/object_gi_saw.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_scale.xml b/assets/xml/objects/object_gi_scale.xml index 1cf5de5b99..c6794b6aea 100644 --- a/assets/xml/objects/object_gi_scale.xml +++ b/assets/xml/objects/object_gi_scale.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_seed.xml b/assets/xml/objects/object_gi_seed.xml index 82c15c82d2..5d3ef9c03f 100644 --- a/assets/xml/objects/object_gi_seed.xml +++ b/assets/xml/objects/object_gi_seed.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_shield_1.xml b/assets/xml/objects/object_gi_shield_1.xml index 2e93695699..867292a4c3 100644 --- a/assets/xml/objects/object_gi_shield_1.xml +++ b/assets/xml/objects/object_gi_shield_1.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_shield_2.xml b/assets/xml/objects/object_gi_shield_2.xml index 176ae025fe..364070d101 100644 --- a/assets/xml/objects/object_gi_shield_2.xml +++ b/assets/xml/objects/object_gi_shield_2.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_shield_3.xml b/assets/xml/objects/object_gi_shield_3.xml index 250bf7fea3..974a2539a9 100644 --- a/assets/xml/objects/object_gi_shield_3.xml +++ b/assets/xml/objects/object_gi_shield_3.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_skj_mask.xml b/assets/xml/objects/object_gi_skj_mask.xml index e6c90f76f1..6479015715 100644 --- a/assets/xml/objects/object_gi_skj_mask.xml +++ b/assets/xml/objects/object_gi_skj_mask.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_soul.xml b/assets/xml/objects/object_gi_soul.xml index 76ffc56852..ee9dbd9570 100644 --- a/assets/xml/objects/object_gi_soul.xml +++ b/assets/xml/objects/object_gi_soul.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_stick.xml b/assets/xml/objects/object_gi_stick.xml index fed89f4659..d974b7ac5d 100644 --- a/assets/xml/objects/object_gi_stick.xml +++ b/assets/xml/objects/object_gi_stick.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_sutaru.xml b/assets/xml/objects/object_gi_sutaru.xml index a2606afbe3..343d301868 100644 --- a/assets/xml/objects/object_gi_sutaru.xml +++ b/assets/xml/objects/object_gi_sutaru.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_sword_1.xml b/assets/xml/objects/object_gi_sword_1.xml index e1119abca0..3bc15dcaf3 100644 --- a/assets/xml/objects/object_gi_sword_1.xml +++ b/assets/xml/objects/object_gi_sword_1.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_ticketstone.xml b/assets/xml/objects/object_gi_ticketstone.xml index 0fa37fe11e..6cdd5ea2f0 100644 --- a/assets/xml/objects/object_gi_ticketstone.xml +++ b/assets/xml/objects/object_gi_ticketstone.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_gi_truth_mask.xml b/assets/xml/objects/object_gi_truth_mask.xml index f28c7cbcad..64bd0939c6 100644 --- a/assets/xml/objects/object_gi_truth_mask.xml +++ b/assets/xml/objects/object_gi_truth_mask.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_god_lgt.xml b/assets/xml/objects/object_god_lgt.xml index 60df9e4693..b630605364 100644 --- a/assets/xml/objects/object_god_lgt.xml +++ b/assets/xml/objects/object_god_lgt.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_kanban.xml b/assets/xml/objects/object_kanban.xml index 9ffc7a2ceb..b989d3572a 100644 --- a/assets/xml/objects/object_kanban.xml +++ b/assets/xml/objects/object_kanban.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_kusa.xml b/assets/xml/objects/object_kusa.xml index 67291a5543..5eaaa99c58 100644 --- a/assets/xml/objects/object_kusa.xml +++ b/assets/xml/objects/object_kusa.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_link_boy.xml b/assets/xml/objects/object_link_boy.xml index 77254f5557..14917fd165 100644 --- a/assets/xml/objects/object_link_boy.xml +++ b/assets/xml/objects/object_link_boy.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_link_child.xml b/assets/xml/objects/object_link_child.xml index 36baf5aa6e..85ed8de950 100644 --- a/assets/xml/objects/object_link_child.xml +++ b/assets/xml/objects/object_link_child.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_medal.xml b/assets/xml/objects/object_medal.xml index eeb433c400..94976bd3f9 100644 --- a/assets/xml/objects/object_medal.xml +++ b/assets/xml/objects/object_medal.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_mori_hineri1.xml b/assets/xml/objects/object_mori_hineri1.xml index a2033a6f97..572eb6e1f3 100644 --- a/assets/xml/objects/object_mori_hineri1.xml +++ b/assets/xml/objects/object_mori_hineri1.xml @@ -1,5 +1,5 @@ - + diff --git a/assets/xml/objects/object_mori_hineri1a.xml b/assets/xml/objects/object_mori_hineri1a.xml index d7e3489044..23e6f5e665 100644 --- a/assets/xml/objects/object_mori_hineri1a.xml +++ b/assets/xml/objects/object_mori_hineri1a.xml @@ -1,5 +1,5 @@ - + diff --git a/assets/xml/objects/object_mori_hineri2.xml b/assets/xml/objects/object_mori_hineri2.xml index 9f1c892afb..d539cd86f0 100644 --- a/assets/xml/objects/object_mori_hineri2.xml +++ b/assets/xml/objects/object_mori_hineri2.xml @@ -1,5 +1,5 @@ - + diff --git a/assets/xml/objects/object_mori_hineri2a.xml b/assets/xml/objects/object_mori_hineri2a.xml index 6fd6818562..0334488567 100644 --- a/assets/xml/objects/object_mori_hineri2a.xml +++ b/assets/xml/objects/object_mori_hineri2a.xml @@ -1,5 +1,5 @@ - + diff --git a/assets/xml/objects/object_mori_objects.xml b/assets/xml/objects/object_mori_objects.xml index aa24a38d70..1844cf6f69 100644 --- a/assets/xml/objects/object_mori_objects.xml +++ b/assets/xml/objects/object_mori_objects.xml @@ -1,5 +1,5 @@ - + diff --git a/assets/xml/objects/object_nwc.xml b/assets/xml/objects/object_nwc.xml index 96ffa32383..abe2be092b 100644 --- a/assets/xml/objects/object_nwc.xml +++ b/assets/xml/objects/object_nwc.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_ny.xml b/assets/xml/objects/object_ny.xml index e2e8187ff8..c81d66ab56 100644 --- a/assets/xml/objects/object_ny.xml +++ b/assets/xml/objects/object_ny.xml @@ -1,10 +1,11 @@ + - - + + diff --git a/assets/xml/objects/object_owl.xml b/assets/xml/objects/object_owl.xml index 24be378985..4ea2006678 100644 --- a/assets/xml/objects/object_owl.xml +++ b/assets/xml/objects/object_owl.xml @@ -61,7 +61,7 @@ - + diff --git a/assets/xml/objects/object_po_composer.xml b/assets/xml/objects/object_po_composer.xml index 2ab8d64d85..17c04fd18b 100644 --- a/assets/xml/objects/object_po_composer.xml +++ b/assets/xml/objects/object_po_composer.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_po_field.xml b/assets/xml/objects/object_po_field.xml index 10b402e2c7..43e1066e3b 100644 --- a/assets/xml/objects/object_po_field.xml +++ b/assets/xml/objects/object_po_field.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_poh.xml b/assets/xml/objects/object_poh.xml index 009d0fca3f..33517945e8 100644 --- a/assets/xml/objects/object_poh.xml +++ b/assets/xml/objects/object_poh.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_ps.xml b/assets/xml/objects/object_ps.xml index 043e232d64..98f548db1b 100644 --- a/assets/xml/objects/object_ps.xml +++ b/assets/xml/objects/object_ps.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_sb.xml b/assets/xml/objects/object_sb.xml index 3adf2c17ee..57a0f7f8f7 100644 --- a/assets/xml/objects/object_sb.xml +++ b/assets/xml/objects/object_sb.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_siofuki.xml b/assets/xml/objects/object_siofuki.xml index a23240a728..f8a9e50d83 100644 --- a/assets/xml/objects/object_siofuki.xml +++ b/assets/xml/objects/object_siofuki.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_sst.xml b/assets/xml/objects/object_sst.xml index c142c50f43..66cf6c8e02 100644 --- a/assets/xml/objects/object_sst.xml +++ b/assets/xml/objects/object_sst.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_sst_pal.xml b/assets/xml/objects/object_sst_pal.xml index 9a9199b58f..138a320324 100644 --- a/assets/xml/objects/object_sst_pal.xml +++ b/assets/xml/objects/object_sst_pal.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_st.xml b/assets/xml/objects/object_st.xml index 9556f081d0..e374b4cb4a 100644 --- a/assets/xml/objects/object_st.xml +++ b/assets/xml/objects/object_st.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_stream.xml b/assets/xml/objects/object_stream.xml index 59b0838e47..6c65f77c34 100644 --- a/assets/xml/objects/object_stream.xml +++ b/assets/xml/objects/object_stream.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_syokudai.xml b/assets/xml/objects/object_syokudai.xml index 11af7e9a3a..6434d923a5 100644 --- a/assets/xml/objects/object_syokudai.xml +++ b/assets/xml/objects/object_syokudai.xml @@ -1,5 +1,5 @@ - + diff --git a/assets/xml/objects/object_toki_objects.xml b/assets/xml/objects/object_toki_objects.xml index 3cada31f89..917d239347 100644 --- a/assets/xml/objects/object_toki_objects.xml +++ b/assets/xml/objects/object_toki_objects.xml @@ -1,4 +1,5 @@  + diff --git a/assets/xml/objects/object_trap.xml b/assets/xml/objects/object_trap.xml index 56195cf41b..1f8f4b5310 100644 --- a/assets/xml/objects/object_trap.xml +++ b/assets/xml/objects/object_trap.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_wood02.xml b/assets/xml/objects/object_wood02.xml index bdcc2d2e38..dcf6d21291 100644 --- a/assets/xml/objects/object_wood02.xml +++ b/assets/xml/objects/object_wood02.xml @@ -1,5 +1,5 @@ - + diff --git a/assets/xml/objects/object_ydan_objects.xml b/assets/xml/objects/object_ydan_objects.xml index baf7ca4c9c..70174a1e70 100644 --- a/assets/xml/objects/object_ydan_objects.xml +++ b/assets/xml/objects/object_ydan_objects.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/objects/object_zf.xml b/assets/xml/objects/object_zf.xml index 7f20eb7866..74e9d45915 100644 --- a/assets/xml/objects/object_zf.xml +++ b/assets/xml/objects/object_zf.xml @@ -1,4 +1,5 @@ + @@ -109,7 +110,7 @@ - + diff --git a/assets/xml/objects/object_zo.xml b/assets/xml/objects/object_zo.xml index 77465760ef..8872cc4c9f 100644 --- a/assets/xml/objects/object_zo.xml +++ b/assets/xml/objects/object_zo.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/overlays/ovl_Boss_Ganon.xml b/assets/xml/overlays/ovl_Boss_Ganon.xml index a6ed9c66eb..d09648d8d7 100644 --- a/assets/xml/overlays/ovl_Boss_Ganon.xml +++ b/assets/xml/overlays/ovl_Boss_Ganon.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/overlays/ovl_Boss_Ganon2.xml b/assets/xml/overlays/ovl_Boss_Ganon2.xml index 00f985786c..b922003dfa 100644 --- a/assets/xml/overlays/ovl_Boss_Ganon2.xml +++ b/assets/xml/overlays/ovl_Boss_Ganon2.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/overlays/ovl_En_Jsjutan.xml b/assets/xml/overlays/ovl_En_Jsjutan.xml index b3b012b1f5..13bbd82199 100644 --- a/assets/xml/overlays/ovl_En_Jsjutan.xml +++ b/assets/xml/overlays/ovl_En_Jsjutan.xml @@ -16,9 +16,6 @@ - - - diff --git a/assets/xml/overlays/ovl_Magic_Dark.xml b/assets/xml/overlays/ovl_Magic_Dark.xml index 965d140db4..37165cebc2 100644 --- a/assets/xml/overlays/ovl_Magic_Dark.xml +++ b/assets/xml/overlays/ovl_Magic_Dark.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/overlays/ovl_Oceff_Storm.xml b/assets/xml/overlays/ovl_Oceff_Storm.xml index 385f56dbff..d9e1f7e65a 100644 --- a/assets/xml/overlays/ovl_Oceff_Storm.xml +++ b/assets/xml/overlays/ovl_Oceff_Storm.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/overlays/ovl_Oceff_Wipe4.xml b/assets/xml/overlays/ovl_Oceff_Wipe4.xml index 6446beedb2..a4ec2c5def 100644 --- a/assets/xml/overlays/ovl_Oceff_Wipe4.xml +++ b/assets/xml/overlays/ovl_Oceff_Wipe4.xml @@ -1,4 +1,5 @@ + diff --git a/assets/xml/scenes/dungeons/MIZUsin.xml b/assets/xml/scenes/dungeons/MIZUsin.xml index e48f534d88..12a124cf09 100644 --- a/assets/xml/scenes/dungeons/MIZUsin.xml +++ b/assets/xml/scenes/dungeons/MIZUsin.xml @@ -7,6 +7,7 @@ + diff --git a/assets/xml/scenes/dungeons/MIZUsin_mq.xml b/assets/xml/scenes/dungeons/MIZUsin_mq.xml index bd0e260ace..cbbe48287e 100644 --- a/assets/xml/scenes/dungeons/MIZUsin_mq.xml +++ b/assets/xml/scenes/dungeons/MIZUsin_mq.xml @@ -7,6 +7,7 @@ + diff --git a/assets/xml/scenes/dungeons/ddan.xml b/assets/xml/scenes/dungeons/ddan.xml index d78f8dabee..295f651739 100644 --- a/assets/xml/scenes/dungeons/ddan.xml +++ b/assets/xml/scenes/dungeons/ddan.xml @@ -19,6 +19,7 @@ + diff --git a/assets/xml/scenes/dungeons/ddan_mq.xml b/assets/xml/scenes/dungeons/ddan_mq.xml index d78f8dabee..295f651739 100644 --- a/assets/xml/scenes/dungeons/ddan_mq.xml +++ b/assets/xml/scenes/dungeons/ddan_mq.xml @@ -19,6 +19,7 @@ + diff --git a/baseroms/gc-eu-mq-dbg/config.yml b/baseroms/gc-eu-mq-dbg/config.yml index 44bbdae424..e457028060 100644 --- a/baseroms/gc-eu-mq-dbg/config.yml +++ b/baseroms/gc-eu-mq-dbg/config.yml @@ -64,7 +64,7 @@ assets: - name: code/fbdemo_circle xml_path: assets/xml/code/fbdemo_circle.xml start_offset: 0x10ED48 - end_offset: 0x10FF68 + end_offset: 0x110038 - name: code/fbdemo_triforce xml_path: assets/xml/code/fbdemo_triforce.xml start_offset: 0x10E1D0 @@ -72,7 +72,7 @@ assets: - name: code/fbdemo_wipe1 xml_path: assets/xml/code/fbdemo_wipe1.xml start_offset: 0x10E2A0 - end_offset: 0x10EC30 + end_offset: 0x10ED28 - name: misc/link_animetion xml_path: assets/xml/misc/link_animetion.xml - name: misc/z_select_static diff --git a/baseroms/gc-eu-mq/config.yml b/baseroms/gc-eu-mq/config.yml index e42e48c75f..0093015d7e 100644 --- a/baseroms/gc-eu-mq/config.yml +++ b/baseroms/gc-eu-mq/config.yml @@ -56,7 +56,7 @@ assets: - name: code/fbdemo_circle xml_path: assets/xml/code/fbdemo_circle.xml start_offset: 0xE90A8 - end_offset: 0xEA2C8 + end_offset: 0xEA398 - name: code/fbdemo_triforce xml_path: assets/xml/code/fbdemo_triforce.xml start_offset: 0xE8530 @@ -64,7 +64,7 @@ assets: - name: code/fbdemo_wipe1 xml_path: assets/xml/code/fbdemo_wipe1.xml start_offset: 0xE8600 - end_offset: 0xE8F90 + end_offset: 0xE9088 - name: misc/link_animetion xml_path: assets/xml/misc/link_animetion.xml - name: misc/z_select_static diff --git a/baseroms/gc-eu/config.yml b/baseroms/gc-eu/config.yml index b6471875f7..9aef9891f9 100644 --- a/baseroms/gc-eu/config.yml +++ b/baseroms/gc-eu/config.yml @@ -56,7 +56,7 @@ assets: - name: code/fbdemo_circle xml_path: assets/xml/code/fbdemo_circle.xml start_offset: 0xE90C8 - end_offset: 0xEA2E8 + end_offset: 0xEA3B8 - name: code/fbdemo_triforce xml_path: assets/xml/code/fbdemo_triforce.xml start_offset: 0xE8550 @@ -64,7 +64,7 @@ assets: - name: code/fbdemo_wipe1 xml_path: assets/xml/code/fbdemo_wipe1.xml start_offset: 0xE8620 - end_offset: 0xE8FB0 + end_offset: 0xE90A8 - name: misc/link_animetion xml_path: assets/xml/misc/link_animetion.xml - name: misc/z_select_static diff --git a/baseroms/gc-jp-ce/config.yml b/baseroms/gc-jp-ce/config.yml index a4592544ff..f3c0541a62 100644 --- a/baseroms/gc-jp-ce/config.yml +++ b/baseroms/gc-jp-ce/config.yml @@ -55,7 +55,7 @@ assets: - name: code/fbdemo_circle xml_path: assets/xml/code/fbdemo_circle.xml start_offset: 0xEB768 - end_offset: 0xEC988 + end_offset: 0xECA58 - name: code/fbdemo_triforce xml_path: assets/xml/code/fbdemo_triforce.xml start_offset: 0xEABF0 @@ -63,7 +63,7 @@ assets: - name: code/fbdemo_wipe1 xml_path: assets/xml/code/fbdemo_wipe1.xml start_offset: 0xEACC0 - end_offset: 0xEB650 + end_offset: 0xEB748 - name: misc/link_animetion xml_path: assets/xml/misc/link_animetion.xml - name: misc/z_select_static diff --git a/baseroms/gc-jp-mq/config.yml b/baseroms/gc-jp-mq/config.yml index 597e2cff66..41d1721f3d 100644 --- a/baseroms/gc-jp-mq/config.yml +++ b/baseroms/gc-jp-mq/config.yml @@ -55,7 +55,7 @@ assets: - name: code/fbdemo_circle xml_path: assets/xml/code/fbdemo_circle.xml start_offset: 0xEB768 - end_offset: 0xEC988 + end_offset: 0xECA58 - name: code/fbdemo_triforce xml_path: assets/xml/code/fbdemo_triforce.xml start_offset: 0xEABF0 @@ -63,7 +63,7 @@ assets: - name: code/fbdemo_wipe1 xml_path: assets/xml/code/fbdemo_wipe1.xml start_offset: 0xEACC0 - end_offset: 0xEB650 + end_offset: 0xEB748 - name: misc/link_animetion xml_path: assets/xml/misc/link_animetion.xml - name: misc/z_select_static diff --git a/baseroms/gc-jp/config.yml b/baseroms/gc-jp/config.yml index 582fd894eb..73285664c6 100644 --- a/baseroms/gc-jp/config.yml +++ b/baseroms/gc-jp/config.yml @@ -55,7 +55,7 @@ assets: - name: code/fbdemo_circle xml_path: assets/xml/code/fbdemo_circle.xml start_offset: 0xEB788 - end_offset: 0xEC9A8 + end_offset: 0xECA78 - name: code/fbdemo_triforce xml_path: assets/xml/code/fbdemo_triforce.xml start_offset: 0xEAC10 @@ -63,7 +63,7 @@ assets: - name: code/fbdemo_wipe1 xml_path: assets/xml/code/fbdemo_wipe1.xml start_offset: 0xEACE0 - end_offset: 0xEB670 + end_offset: 0xEB768 - name: misc/link_animetion xml_path: assets/xml/misc/link_animetion.xml - name: misc/z_select_static diff --git a/baseroms/gc-us-mq/config.yml b/baseroms/gc-us-mq/config.yml index 691aaa1ff9..1057e49b2e 100644 --- a/baseroms/gc-us-mq/config.yml +++ b/baseroms/gc-us-mq/config.yml @@ -55,7 +55,7 @@ assets: - name: code/fbdemo_circle xml_path: assets/xml/code/fbdemo_circle.xml start_offset: 0xEB748 - end_offset: 0xEC968 + end_offset: 0xECA38 - name: code/fbdemo_triforce xml_path: assets/xml/code/fbdemo_triforce.xml start_offset: 0xEABD0 @@ -63,7 +63,7 @@ assets: - name: code/fbdemo_wipe1 xml_path: assets/xml/code/fbdemo_wipe1.xml start_offset: 0xEACA0 - end_offset: 0xEB630 + end_offset: 0xEB728 - name: misc/link_animetion xml_path: assets/xml/misc/link_animetion.xml - name: misc/z_select_static diff --git a/baseroms/gc-us/config.yml b/baseroms/gc-us/config.yml index 9a64c84646..620d550631 100644 --- a/baseroms/gc-us/config.yml +++ b/baseroms/gc-us/config.yml @@ -55,7 +55,7 @@ assets: - name: code/fbdemo_circle xml_path: assets/xml/code/fbdemo_circle.xml start_offset: 0xEB768 - end_offset: 0xEC988 + end_offset: 0xECA58 - name: code/fbdemo_triforce xml_path: assets/xml/code/fbdemo_triforce.xml start_offset: 0xEABF0 @@ -63,7 +63,7 @@ assets: - name: code/fbdemo_wipe1 xml_path: assets/xml/code/fbdemo_wipe1.xml start_offset: 0xEACC0 - end_offset: 0xEB650 + end_offset: 0xEB748 - name: misc/link_animetion xml_path: assets/xml/misc/link_animetion.xml - name: misc/z_select_static diff --git a/baseroms/ique-cn/config.yml b/baseroms/ique-cn/config.yml index af570e0f0a..6236b0cf51 100644 --- a/baseroms/ique-cn/config.yml +++ b/baseroms/ique-cn/config.yml @@ -55,7 +55,7 @@ assets: - name: code/fbdemo_circle xml_path: assets/xml/code/fbdemo_circle.xml start_offset: 0xEBD88 - end_offset: 0xECFA8 + end_offset: 0xED078 - name: code/fbdemo_triforce xml_path: assets/xml/code/fbdemo_triforce.xml start_offset: 0xEB210 @@ -63,7 +63,7 @@ assets: - name: code/fbdemo_wipe1 xml_path: assets/xml/code/fbdemo_wipe1.xml start_offset: 0xEB2E0 - end_offset: 0xEBC70 + end_offset: 0xEBD68 - name: misc/link_animetion xml_path: assets/xml/misc/link_animetion.xml - name: misc/z_select_static diff --git a/baseroms/ntsc-1.0/config.yml b/baseroms/ntsc-1.0/config.yml index 667845d383..948bbd179a 100644 --- a/baseroms/ntsc-1.0/config.yml +++ b/baseroms/ntsc-1.0/config.yml @@ -58,7 +58,7 @@ assets: - name: code/fbdemo_circle xml_path: assets/xml/code/fbdemo_circle.xml start_offset: 0xEC0A8 - end_offset: 0xED2C8 + end_offset: 0xED398 - name: code/fbdemo_triforce xml_path: assets/xml/code/fbdemo_triforce.xml start_offset: 0xEB530 @@ -66,7 +66,7 @@ assets: - name: code/fbdemo_wipe1 xml_path: assets/xml/code/fbdemo_wipe1.xml start_offset: 0xEB600 - end_offset: 0xEBF90 + end_offset: 0xEC088 - name: n64dd/error_textures xml_path: assets/xml/n64dd/error_textures.xml start_offset: 0xC160 diff --git a/baseroms/ntsc-1.1/config.yml b/baseroms/ntsc-1.1/config.yml index 66e74a17a4..2317ae2dac 100644 --- a/baseroms/ntsc-1.1/config.yml +++ b/baseroms/ntsc-1.1/config.yml @@ -58,7 +58,7 @@ assets: - name: code/fbdemo_circle xml_path: assets/xml/code/fbdemo_circle.xml start_offset: 0xEC268 - end_offset: 0xED488 + end_offset: 0xED558 - name: code/fbdemo_triforce xml_path: assets/xml/code/fbdemo_triforce.xml start_offset: 0xEB6F0 @@ -66,7 +66,7 @@ assets: - name: code/fbdemo_wipe1 xml_path: assets/xml/code/fbdemo_wipe1.xml start_offset: 0xEB7C0 - end_offset: 0xEC150 + end_offset: 0xEC248 - name: n64dd/error_textures xml_path: assets/xml/n64dd/error_textures.xml start_offset: 0xC140 diff --git a/baseroms/ntsc-1.2/config.yml b/baseroms/ntsc-1.2/config.yml index 4b3b33db46..6fc7896db0 100644 --- a/baseroms/ntsc-1.2/config.yml +++ b/baseroms/ntsc-1.2/config.yml @@ -58,7 +58,7 @@ assets: - name: code/fbdemo_circle xml_path: assets/xml/code/fbdemo_circle.xml start_offset: 0xEC0B8 - end_offset: 0xED2D8 + end_offset: 0xED3A8 - name: code/fbdemo_triforce xml_path: assets/xml/code/fbdemo_triforce.xml start_offset: 0xEB540 @@ -66,7 +66,7 @@ assets: - name: code/fbdemo_wipe1 xml_path: assets/xml/code/fbdemo_wipe1.xml start_offset: 0xEB610 - end_offset: 0xEBFA0 + end_offset: 0xEC098 - name: n64dd/error_textures xml_path: assets/xml/n64dd/error_textures.xml start_offset: 0xC120 diff --git a/baseroms/pal-1.0/config.yml b/baseroms/pal-1.0/config.yml index 782e4ce152..37ffb7500b 100644 --- a/baseroms/pal-1.0/config.yml +++ b/baseroms/pal-1.0/config.yml @@ -64,7 +64,7 @@ assets: - name: code/fbdemo_circle xml_path: assets/xml/code/fbdemo_circle.xml start_offset: 0xE99C8 - end_offset: 0xEABE8 + end_offset: 0xEACB8 - name: code/fbdemo_triforce xml_path: assets/xml/code/fbdemo_triforce.xml start_offset: 0xE8E50 @@ -72,7 +72,7 @@ assets: - name: code/fbdemo_wipe1 xml_path: assets/xml/code/fbdemo_wipe1.xml start_offset: 0xE8F20 - end_offset: 0xE98B0 + end_offset: 0xE99A8 - name: n64dd/error_textures xml_path: assets/xml/n64dd/error_textures.xml start_offset: 0xC0E0 diff --git a/baseroms/pal-1.1/config.yml b/baseroms/pal-1.1/config.yml index c7f278dfe2..45bf82b877 100644 --- a/baseroms/pal-1.1/config.yml +++ b/baseroms/pal-1.1/config.yml @@ -64,7 +64,7 @@ assets: - name: code/fbdemo_circle xml_path: assets/xml/code/fbdemo_circle.xml start_offset: 0xE9A08 - end_offset: 0xEAC28 + end_offset: 0xEACF8 - name: code/fbdemo_triforce xml_path: assets/xml/code/fbdemo_triforce.xml start_offset: 0xE8E90 @@ -72,7 +72,7 @@ assets: - name: code/fbdemo_wipe1 xml_path: assets/xml/code/fbdemo_wipe1.xml start_offset: 0xE8F60 - end_offset: 0xE98F0 + end_offset: 0xE99E8 - name: n64dd/error_textures xml_path: assets/xml/n64dd/error_textures.xml start_offset: 0xC0E0 diff --git a/docs/assets/extraction.md b/docs/assets/extraction.md new file mode 100644 index 0000000000..a4c342db3b --- /dev/null +++ b/docs/assets/extraction.md @@ -0,0 +1,18 @@ +Assets are not committed to the repo; instead, they are extracted from the ROM files as part of `make setup`. + +Assets are extracted to `extracted/VERSION/assets` (for example `extracted/ntsc-1.0/assets` for the `ntsc-1.0` version), based on the descriptions stored in xml files in `assets/xml/`. + +For details on the xml files contents, see [the assets xml specification file](../../tools/assets/descriptor/spec.md). + +The extraction tool can use [rich](https://github.com/Textualize/rich) if installed to make output prettier. +If you are looking at output or errors from during extraction, consider installing rich for a better experience: `.venv/bin/python3 -m pip install rich` + +To run the extraction outside of `make setup`, use `./tools/extract_assets.sh VERSION`. +- Pass `-f` to force extraction: otherwise only assets for which xmls were modified will be extracted. +- Pass `-j` to use multiprocessing, making extraction quicker. Note that this makes for less readable errors if any error happens. +- Pass `-s name` to extract assets using baserom file `name`. +- Pass `-r -s 'name.*'` to extract assets using baserom files whose name match regular expression `name.*`. + +There currently are various hacks in place in the extraction tool source code to make extraction of some corner cases possible, or to silence extraction warnings. +Some of these hacks check for the name of resources, so renaming a few specific resources may need updating the extraction tool's source too. +The plan is to eventually remove those hardcoded checks from the source and use a `HackMode` attribute in the xmls to trigger the hacks code paths. diff --git a/docs/assets/images.md b/docs/assets/images.md new file mode 100644 index 0000000000..3aefcf1da2 --- /dev/null +++ b/docs/assets/images.md @@ -0,0 +1,64 @@ +# Images + +Images in the rom are in N64 image formats. +On extraction, they are converted to png and written to `extracted/VERSION/`. +On build, they are converted back to N64 formats and written as C arrays to `.inc.c` files in `build/VERSION/`. + +The build system will also pick up images in `assets/`, allowing modders to add or even [replace](#replacing-images) images. + +PNG files have suffixes indicating how they are to be converted. For example, a `gDekuStickTex.i8.u64.png` file will be converted to `i8`. The `.u64` suffix indicates to write the resulting `.inc.c` as an array of `u64` elements. + +The valid formats are `rgba32`, `rgba16`, `i4`, `i8`, `ia4`, `ia8`, `ia16`, `ci4` and `ci8`. + +The valid array element types are `u64` and `u32`. `u32` is only used for unaligned textures. + +The tool implementing png->n64 conversion is [build_from_png](../../tools/assets/build_from_png/build_from_png.c), using [n64texconv](../../tools/assets/n64texconv/) as its backbone. + +# Replacing images + +The contents of `extracted/` are meant to hold the baserom assets and should not be modified. Instead, replacing an image can be done by creating a png file at the same relative path under `assets/` as the image to replace. + +For example, replacing `gLinkHairTex` (`extracted/VERSION/assets/objects/gameplay_keep/gLinkHairTex.rgba16.u64.png`) with the texture for `gHylianMan1BeardedEyeOpenTex` (`extracted/VERSION/assets/objects/object_ahg/gHylianMan1BeardedEyeOpenTex.ci8.tlut_gHylianMan1TLUT_u32.u32.png`): + +```sh +# for VERSION=gc-eu-mq-dbg + +mkdir -p assets/objects/gameplay_keep/ +cp \ + extracted/gc-eu-mq-dbg/assets/objects/object_ahg/gHylianMan1BeardedEyeOpenTex.ci8.tlut_gHylianMan1TLUT_u32.u32.png \ + assets/objects/gameplay_keep/gLinkHairTex.rgba16.u64.png + +# Cause make to rebuild gameplay_keep, where gLinkHairTex is +touch extracted/gc-eu-mq-dbg/assets/objects/gameplay_keep/gameplay_keep.c + +make VERSION=gc-eu-mq-dbg +``` + +# CI images + +CI (Color Indexed) images also have a palette or TLUT (Texture Look-Up Table). + +PNG images to be converted to CI formats may have a `.tlut_gNameTLUT_u64` suffix indicating the name and element type of the TLUT `gNameTLUT.tlut.rgba16.u64.inc.c` file to write the palette to. + +If this suffix is omitted, the TLUT will be written to a `gNameTex.tlut.rgba16.u64.inc.c` file named after the CI image. + +For example without the `.tlut_` suffix, `gGanonHairFringeTex.ci8.u64.png`: + +- extracted to `extracted/VERSION/assets/objects/object_ganon2/gGanonHairFringeTex.ci8.u64.png` +- texture written to `build/VERSION/assets/objects/object_ganon2/gGanonHairFringeTex.ci8.u64.inc.c` +- palette written to `build/VERSION/assets/objects/object_ganon2/gGanonHairFringeTex.tlut.rgba16.u64.inc.c` + +For example with the `.tlut_` suffix, `gCowNoseTex.ci8.tlut_gCowTLUT_u64.u64.png`: + +- extracted to `extracted/gc-eu-mq-dbg/assets/objects/object_cow/gCowNoseTex.ci8.tlut_gCowTLUT_u64.u64.png` +- texture written to `build/gc-eu-mq-dbg/assets/objects/object_cow/gCowNoseTex.ci8.tlut_gCowTLUT_u64.u64.inc.c` +- palette written to `build/gc-eu-mq-dbg/assets/objects/object_cow/gCowTLUT.tlut.rgba16.u64.bin` + +CI images with a `.tlut_` suffix have a shared palette: there are several CI images using the same palette. +The build system (`build_from_png`) will find images sharing the same palette by looking at the `.tlut_` suffixes of png files in the same folder and in the corresponding `assets/` folder. + +In the matching case of shared palettes, all png files have the same palette, which is written out. +Otherwise the images are automatically co-quantized and the resulting images and palette are written out. + +Note the N64 supports CI images with IA16 palettes instead of RGBA16 palettes, but OoT doesn't have such textures. +For simplicity, CI images with IA16 palettes are not supported in the build system, and all CI images are assumed to use RGBA16 palettes. diff --git a/include/z64.h b/include/z64.h deleted file mode 100644 index bb2518e6ec..0000000000 --- a/include/z64.h +++ /dev/null @@ -1,20 +0,0 @@ -#ifndef Z64_H -#define Z64_H - -// TODO: This file still exists ONLY to provide neccesary headers to extracted assets. -// After assets are modified to include the headers they need directly, delete this file. - -#include "array_count.h" -#include "gfx.h" -#include "sequence.h" -#include "sys_matrix.h" -#include "ultra64.h" -#include "z64play.h" -#include "z64animation.h" -#include "z64animation_legacy.h" -#include "z64curve.h" -#include "z64skin.h" -#include "z64player.h" -#include "z64ocarina.h" - -#endif diff --git a/requirements.txt b/requirements.txt index c9c4afed64..bea2fe176c 100644 --- a/requirements.txt +++ b/requirements.txt @@ -2,6 +2,7 @@ crunch64>=0.5.1,<1.0.0 ipl3checksum>=1.2.0,<2.0.0 pyyaml>=6.0.1,<7.0.0 +pygfxd>=1.0.3,<2.0.0 # asm-differ argcomplete diff --git a/src/code/z_actor.c b/src/code/z_actor.c index 721087332e..83105d23ec 100644 --- a/src/code/z_actor.c +++ b/src/code/z_actor.c @@ -35,7 +35,7 @@ #include "assets/objects/gameplay_dangeon_keep/gameplay_dangeon_keep.h" #include "assets/objects/object_bdoor/object_bdoor.h" -#pragma increment_block_number "gc-eu:128 gc-eu-mq:128 gc-jp:0 gc-jp-ce:0 gc-jp-mq:0 gc-us:0 gc-us-mq:0 ntsc-1.0:128" \ +#pragma increment_block_number "gc-eu:128 gc-eu-mq:128 gc-jp:0 gc-jp-ce:0 gc-jp-mq:0 gc-us:0 gc-us-mq:0 ntsc-1.0:0" \ "ntsc-1.1:0 ntsc-1.2:0 pal-1.0:0 pal-1.1:0" CollisionPoly* sCurCeilingPoly; diff --git a/src/code/z_eff_blure.c b/src/code/z_eff_blure.c index 614cfa5b5b..6e2023b67d 100644 --- a/src/code/z_eff_blure.c +++ b/src/code/z_eff_blure.c @@ -9,7 +9,6 @@ #include "z64effect.h" #include "z64skin_matrix.h" -#include "z64.h" // required for gameplay keep, the header doesnt include any external dependencies #include "assets/objects/gameplay_keep/gameplay_keep.h" void EffectBlure_AddVertex(EffectBlure* this, Vec3f* p1, Vec3f* p2) { diff --git a/src/code/z_fbdemo_circle.c b/src/code/z_fbdemo_circle.c index 499867d570..d8aa81df06 100644 --- a/src/code/z_fbdemo_circle.c +++ b/src/code/z_fbdemo_circle.c @@ -3,6 +3,7 @@ #include "color.h" #include "gfx.h" #include "sfx.h" +#include "z64transition.h" typedef enum TransitionCircleDirection { /* 0 */ TRANS_CIRCLE_DIR_IN, @@ -14,34 +15,7 @@ Gfx sTransCircleEmptyDL[] = { gsSPEndDisplayList(), }; -#include "assets/code/fbdemo_circle/z_fbdemo_circle.c" - -Gfx sTransCircleDL[] = { - gsDPPipeSync(), - gsSPClearGeometryMode(G_ZBUFFER | G_SHADE | G_CULL_BOTH | G_FOG | G_LIGHTING | G_TEXTURE_GEN | - G_TEXTURE_GEN_LINEAR | G_LOD | G_SHADING_SMOOTH), - gsSPSetGeometryMode(G_SHADE | G_SHADING_SMOOTH), - gsDPSetOtherMode(G_AD_DISABLE | G_CD_MAGICSQ | G_CK_NONE | G_TC_FILT | G_TF_BILERP | G_TT_NONE | G_TL_TILE | - G_TD_CLAMP | G_TP_PERSP | G_CYC_1CYCLE | G_PM_NPRIMITIVE, - G_AC_NONE | G_ZS_PIXEL | G_RM_XLU_SURF | G_RM_XLU_SURF2), - gsDPSetCombineMode(G_CC_BLENDPEDECALA, G_CC_BLENDPEDECALA), - gsSPTexture(0xFFFF, 0xFFFF, 0, G_TX_RENDERTILE, G_ON), - gsDPLoadTextureBlock(0x08000000, G_IM_FMT_I, G_IM_SIZ_8b, 16, 64, 0, G_TX_NOMIRROR | G_TX_WRAP, - G_TX_NOMIRROR | G_TX_CLAMP, 4, 6, G_TX_NOLOD, G_TX_NOLOD), - gsSPDisplayList(0x09000000), - gsSPVertex(sTransCircleVtx, 32, 0), - gsSP2Triangles(0, 1, 2, 0, 1, 3, 4, 0), - gsSP2Triangles(3, 5, 6, 0, 5, 7, 8, 0), - gsSP2Triangles(7, 9, 10, 0, 9, 11, 12, 0), - gsSP2Triangles(11, 13, 14, 0, 13, 15, 16, 0), - gsSP2Triangles(15, 17, 18, 0, 17, 19, 20, 0), - gsSP2Triangles(19, 21, 22, 0, 21, 23, 24, 0), - gsSP2Triangles(23, 25, 26, 0, 25, 27, 28, 0), - gsSP1Triangle(27, 29, 30, 0), - gsSPVertex(&sTransCircleVtx[31], 3, 0), - gsSP1Triangle(0, 1, 2, 0), - gsSPEndDisplayList(), -}; +#include "assets/code/fbdemo_circle/code.c" void TransitionCircle_Start(void* thisx) { TransitionCircle* this = (TransitionCircle*)thisx; diff --git a/src/code/z_fbdemo_triforce.c b/src/code/z_fbdemo_triforce.c index d844644a29..6624a4373c 100644 --- a/src/code/z_fbdemo_triforce.c +++ b/src/code/z_fbdemo_triforce.c @@ -1,8 +1,10 @@ #include "transition_triforce.h" #include "printf.h" +#include "z64math.h" +#include "z64transition_instances.h" -#include "assets/code/fbdemo_triforce/z_fbdemo_triforce.c" +#include "assets/code/fbdemo_triforce/code.c" void TransitionTriforce_Start(void* thisx) { TransitionTriforce* this = (TransitionTriforce*)thisx; diff --git a/src/code/z_fbdemo_wipe1.c b/src/code/z_fbdemo_wipe1.c index d876b0b730..25b45e7e2c 100644 --- a/src/code/z_fbdemo_wipe1.c +++ b/src/code/z_fbdemo_wipe1.c @@ -9,35 +9,7 @@ typedef enum TransitionWipeDirection { /* 1 */ TRANS_WIPE_DIR_OUT } TransitionWipeDirection; -#include "assets/code/fbdemo_wipe1/z_fbdemo_wipe1.c" - -Gfx sTransWipeDL[] = { - gsDPPipeSync(), - gsSPClearGeometryMode(G_ZBUFFER | G_SHADE | G_CULL_BOTH | G_FOG | G_LIGHTING | G_TEXTURE_GEN | - G_TEXTURE_GEN_LINEAR | G_LOD | G_SHADING_SMOOTH), - gsSPSetGeometryMode(G_ZBUFFER | G_SHADE | G_SHADING_SMOOTH), - gsDPSetOtherMode(G_AD_DISABLE | G_CD_MAGICSQ | G_CK_NONE | G_TC_FILT | G_TF_BILERP | G_TT_NONE | G_TL_TILE | - G_TD_CLAMP | G_TP_PERSP | G_CYC_2CYCLE | G_PM_1PRIMITIVE, - G_AC_NONE | G_ZS_PRIM | G_RM_PASS | G_RM_AA_ZB_TEX_EDGE2), - gsDPSetCombineLERP(TEXEL1, TEXEL0, PRIM_LOD_FRAC, TEXEL0, TEXEL1, TEXEL0, PRIM_LOD_FRAC, TEXEL0, COMBINED, 0, - PRIMITIVE, 0, COMBINED, 0, PRIMITIVE, 0), - gsDPSetPrimDepth(0, 0), - gsDPLoadTextureBlock_4b(sTransWipeTex, G_IM_FMT_I, 64, 64, 0, G_TX_NOMIRROR | G_TX_WRAP, G_TX_MIRROR | G_TX_WRAP, 6, - 6, 11, G_TX_NOLOD), - gsDPLoadMultiBlock_4b(sTransWipeTex, 0x0100, 1, G_IM_FMT_I, 64, 64, 0, G_TX_NOMIRROR | G_TX_WRAP, - G_TX_MIRROR | G_TX_WRAP, 6, 6, 11, 1), - gsDPSetTextureLUT(G_TT_NONE), - gsSPTexture(0xFFFF, 0xFFFF, 0, G_TX_RENDERTILE, G_ON), - gsSPDisplayList(0x08000000), - gsSPVertex(sTransWipeVtx, 25, 0), - gsSP2Triangles(0, 1, 2, 0, 1, 3, 4, 0), - gsSP2Triangles(5, 6, 7, 0, 6, 8, 9, 0), - gsSP2Triangles(8, 10, 11, 0, 10, 12, 13, 0), - gsSP2Triangles(12, 14, 15, 0, 14, 16, 17, 0), - gsSP2Triangles(16, 18, 19, 0, 18, 20, 21, 0), - gsSP2Triangles(20, 22, 23, 0, 22, 0, 24, 0), - gsSPEndDisplayList(), -}; +#include "assets/code/fbdemo_wipe1/code.c" // unused. Gfx sTransWipeSyncDL[] = { diff --git a/src/code/z_kankyo.c b/src/code/z_kankyo.c index 88dcd5e59b..c78fc5de87 100644 --- a/src/code/z_kankyo.c +++ b/src/code/z_kankyo.c @@ -1,5 +1,5 @@ -#pragma increment_block_number "gc-eu:192 gc-eu-mq:192 gc-jp:192 gc-jp-ce:192 gc-jp-mq:192 gc-us:192 gc-us-mq:192" \ - "ique-cn:192 ntsc-1.0:192 ntsc-1.1:192 ntsc-1.2:192 pal-1.0:192 pal-1.1:192" +#pragma increment_block_number "gc-eu:192 gc-eu-mq:192 gc-jp:128 gc-jp-ce:128 gc-jp-mq:128 gc-us:128 gc-us-mq:128" \ + "ique-cn:128 ntsc-1.0:192 ntsc-1.1:192 ntsc-1.2:192 pal-1.0:192 pal-1.1:192" #include "libc64/qrand.h" #include "libu64/gfxprint.h" @@ -238,8 +238,8 @@ s16 sLightningFlashAlpha; s16 sSunDepthTestX; s16 sSunDepthTestY; -#pragma increment_block_number "gc-eu:192 gc-eu-mq:192 gc-jp:192 gc-jp-ce:192 gc-jp-mq:192 gc-us:192 gc-us-mq:192" \ - "ique-cn:160 ntsc-1.0:192 ntsc-1.1:192 ntsc-1.2:192 pal-1.0:192 pal-1.1:192" +#pragma increment_block_number "gc-eu:192 gc-eu-mq:192 gc-jp:128 gc-jp-ce:128 gc-jp-mq:128 gc-us:128 gc-us-mq:128" \ + "ique-cn:128 ntsc-1.0:128 ntsc-1.1:128 ntsc-1.2:128 pal-1.0:192 pal-1.1:192" LightNode* sNGameOverLightNode; LightInfo sNGameOverLightInfo; diff --git a/src/code/z_message.c b/src/code/z_message.c index 046d3ff886..1d6fee156b 100644 --- a/src/code/z_message.c +++ b/src/code/z_message.c @@ -27,7 +27,7 @@ #include "assets/textures/parameter_static/parameter_static.h" #pragma increment_block_number "gc-eu:0 gc-eu-mq:0 gc-jp:0 gc-jp-ce:0 gc-jp-mq:0 gc-us:0 gc-us-mq:0 ntsc-1.0:32" \ - "ntsc-1.1:32 ntsc-1.2:32 pal-1.0:128 pal-1.1:128" + "ntsc-1.1:32 ntsc-1.2:32 pal-1.0:0 pal-1.1:0" #if !PLATFORM_IQUE #define MSG_BUF_DECODED (msgCtx->msgBufDecoded) diff --git a/src/n64dd/n64dd_error_textures.c b/src/n64dd/n64dd_error_textures.c index d115fdd6ef..d5252640a9 100644 --- a/src/n64dd/n64dd_error_textures.c +++ b/src/n64dd/n64dd_error_textures.c @@ -2,18 +2,18 @@ u64 gN64DDError41Texs[2][0x600 / sizeof(u64)] = { { -#include "assets/n64dd/error_textures/n64dd_error_41_jpn.i4.inc.c" +#include "assets/n64dd/error_textures/gN64DDError41JPNTex.i4.u64.inc.c" }, { -#include "assets/n64dd/error_textures/n64dd_error_41_eng.i4.inc.c" +#include "assets/n64dd/error_textures/gN64DDError41ENGTex.i4.u64.inc.c" }, }; u64 gN64DDPleaseReadManualTexs[2][0x2800 / sizeof(u64)] = { { -#include "assets/n64dd/error_textures/n64dd_please_read_manual_jpn.i4.inc.c" +#include "assets/n64dd/error_textures/gN64DDPleaseReadManualJPNTex.i4.u64.inc.c" }, { -#include "assets/n64dd/error_textures/n64dd_please_read_manual_eng.i4.inc.c" +#include "assets/n64dd/error_textures/gN64DDPleaseReadManualENGTex.i4.u64.inc.c" }, }; diff --git a/src/overlays/actors/ovl_Boss_Ganon/z_boss_ganon.c b/src/overlays/actors/ovl_Boss_Ganon/z_boss_ganon.c index 0ca8e3c843..139d684deb 100644 --- a/src/overlays/actors/ovl_Boss_Ganon/z_boss_ganon.c +++ b/src/overlays/actors/ovl_Boss_Ganon/z_boss_ganon.c @@ -132,8 +132,8 @@ static EnGanonMant* sCape; // TODO: There's probably a way to match BSS ordering with less padding by spreading the variables out and moving // data around. It would be easier if we had more options for controlling BSS ordering in debug. -#pragma increment_block_number "gc-eu:192 gc-eu-mq:192 gc-jp:192 gc-jp-ce:192 gc-jp-mq:192 gc-us:192 gc-us-mq:192" \ - "ique-cn:192 ntsc-1.0:128 ntsc-1.1:128 ntsc-1.2:128 pal-1.0:128 pal-1.1:128" +#pragma increment_block_number "gc-eu:128 gc-eu-mq:128 gc-jp:128 gc-jp-ce:128 gc-jp-mq:128 gc-us:128 gc-us-mq:128" \ + "ique-cn:128 ntsc-1.0:128 ntsc-1.1:128 ntsc-1.2:128 pal-1.0:128 pal-1.1:128" static s32 sSeed1; static s32 sSeed2; diff --git a/src/overlays/actors/ovl_Boss_Tw/z_boss_tw.c b/src/overlays/actors/ovl_Boss_Tw/z_boss_tw.c index e2d6eeb3a8..7000900b49 100644 --- a/src/overlays/actors/ovl_Boss_Tw/z_boss_tw.c +++ b/src/overlays/actors/ovl_Boss_Tw/z_boss_tw.c @@ -26,8 +26,8 @@ #include "assets/objects/gameplay_keep/gameplay_keep.h" #include "assets/objects/object_tw/object_tw.h" -#pragma increment_block_number "gc-eu:192 gc-eu-mq:192 gc-jp:192 gc-jp-ce:192 gc-jp-mq:192 gc-us:192 gc-us-mq:192" \ - "ique-cn:192 ntsc-1.0:192 ntsc-1.1:192 ntsc-1.2:192 pal-1.0:192 pal-1.1:192" +#pragma increment_block_number "gc-eu:128 gc-eu-mq:128 gc-jp:128 gc-jp-ce:128 gc-jp-mq:128 gc-us:128 gc-us-mq:128" \ + "ique-cn:128 ntsc-1.0:128 ntsc-1.1:128 ntsc-1.2:128" #define FLAGS \ (ACTOR_FLAG_ATTENTION_ENABLED | ACTOR_FLAG_HOSTILE | ACTOR_FLAG_UPDATE_CULLING_DISABLED | \ diff --git a/src/overlays/actors/ovl_Demo_Kankyo/z_demo_kankyo.c b/src/overlays/actors/ovl_Demo_Kankyo/z_demo_kankyo.c index 35ffa63a36..e975163403 100644 --- a/src/overlays/actors/ovl_Demo_Kankyo/z_demo_kankyo.c +++ b/src/overlays/actors/ovl_Demo_Kankyo/z_demo_kankyo.c @@ -22,8 +22,8 @@ #include "assets/objects/object_efc_star_field/object_efc_star_field.h" #include "assets/objects/object_toki_objects/object_toki_objects.h" -#pragma increment_block_number "gc-eu:0 gc-eu-mq:0 gc-jp:0 gc-jp-ce:0 gc-jp-mq:0 gc-us:0 gc-us-mq:0 ique-cn:0" \ - "ntsc-1.0:0 ntsc-1.1:0 ntsc-1.2:0 pal-1.0:0 pal-1.1:0" +#pragma increment_block_number "gc-eu:128 gc-eu-mq:128 gc-jp:0 gc-jp-ce:0 gc-jp-mq:0 gc-us:0 gc-us-mq:0 ique-cn:128" \ + "ntsc-1.0:128 ntsc-1.1:128 ntsc-1.2:128 pal-1.0:0 pal-1.1:0" #define FLAGS (ACTOR_FLAG_UPDATE_CULLING_DISABLED | ACTOR_FLAG_DRAW_CULLING_DISABLED) diff --git a/src/overlays/actors/ovl_Door_Warp1/z_door_warp1.c b/src/overlays/actors/ovl_Door_Warp1/z_door_warp1.c index 79f4feca86..dc0f0cb92e 100644 --- a/src/overlays/actors/ovl_Door_Warp1/z_door_warp1.c +++ b/src/overlays/actors/ovl_Door_Warp1/z_door_warp1.c @@ -17,8 +17,8 @@ #include "assets/objects/object_warp1/object_warp1.h" -#pragma increment_block_number "gc-eu:192 gc-eu-mq:192 gc-jp:192 gc-jp-ce:192 gc-jp-mq:192 gc-us:192 gc-us-mq:192" \ - "ique-cn:192 ntsc-1.0:192 ntsc-1.1:192 ntsc-1.2:192 pal-1.0:192 pal-1.1:192" +#pragma increment_block_number "gc-eu:128 gc-eu-mq:128 gc-jp:128 gc-jp-ce:128 gc-jp-mq:128 gc-us:128 gc-us-mq:128" \ + "ique-cn:128 ntsc-1.0:128 ntsc-1.1:128 ntsc-1.2:128 pal-1.0:128 pal-1.1:128" #define FLAGS 0 diff --git a/src/overlays/actors/ovl_En_Jsjutan/z_en_jsjutan.c b/src/overlays/actors/ovl_En_Jsjutan/z_en_jsjutan.c index 13ebc48f3e..fce6c4ef03 100644 --- a/src/overlays/actors/ovl_En_Jsjutan/z_en_jsjutan.c +++ b/src/overlays/actors/ovl_En_Jsjutan/z_en_jsjutan.c @@ -38,6 +38,8 @@ ActorProfile En_Jsjutan_Profile = { }; // Shadow texture. 32x64 I8. +#define sShadowTex_WIDTH 32 +#define sShadowTex_HEIGHT 64 static u8 sShadowTex[0x800]; static Vec3s D_80A8EE10[0x90]; diff --git a/src/overlays/actors/ovl_En_Xc/z_en_xc.c b/src/overlays/actors/ovl_En_Xc/z_en_xc.c index 764791e0df..9d2ec13761 100644 --- a/src/overlays/actors/ovl_En_Xc/z_en_xc.c +++ b/src/overlays/actors/ovl_En_Xc/z_en_xc.c @@ -1415,8 +1415,8 @@ void func_80B3F3D8(void) { Sfx_PlaySfxCentered2(NA_SE_PL_SKIP); } -#pragma increment_block_number "gc-eu:128 gc-eu-mq:64 gc-jp:128 gc-jp-ce:128 gc-jp-mq:64 gc-us:128 gc-us-mq:64" \ - "ique-cn:64 ntsc-1.0:128 ntsc-1.1:128 ntsc-1.2:128 pal-1.0:128 pal-1.1:128" +#pragma increment_block_number "gc-eu:64 gc-eu-mq:64 gc-jp:64 gc-jp-ce:64 gc-jp-mq:64 gc-us:64 gc-us-mq:64 ique-cn:64" \ + "ntsc-1.0:128 ntsc-1.1:128 ntsc-1.2:128 pal-1.0:128 pal-1.1:128" void EnXc_PlayDiveSFX(Vec3f* src, PlayState* play) { static Vec3f D_80B42DA0; diff --git a/src/overlays/actors/ovl_Fishing/z_fishing.c b/src/overlays/actors/ovl_Fishing/z_fishing.c index d16fa2fc5f..58929bd248 100644 --- a/src/overlays/actors/ovl_Fishing/z_fishing.c +++ b/src/overlays/actors/ovl_Fishing/z_fishing.c @@ -37,7 +37,7 @@ #include "cic6105.h" #endif -#pragma increment_block_number "gc-eu:32 gc-eu-mq:32 gc-jp:32 gc-jp-ce:32 gc-jp-mq:32 gc-us:32 gc-us-mq:32 ntsc-1.0:0" \ +#pragma increment_block_number "gc-eu:0 gc-eu-mq:0 gc-jp:0 gc-jp-ce:0 gc-jp-mq:0 gc-us:0 gc-us-mq:0 ntsc-1.0:0" \ "ntsc-1.1:0 ntsc-1.2:0 pal-1.0:0 pal-1.1:0" #define FLAGS ACTOR_FLAG_UPDATE_CULLING_DISABLED diff --git a/src/overlays/actors/ovl_player_actor/z_player.c b/src/overlays/actors/ovl_player_actor/z_player.c index 5f93be1107..e8b9428026 100644 --- a/src/overlays/actors/ovl_player_actor/z_player.c +++ b/src/overlays/actors/ovl_player_actor/z_player.c @@ -362,22 +362,22 @@ void Player_Action_CsAction(Player* this, PlayState* play); // .bss part 1 -#pragma increment_block_number "gc-eu:0 gc-eu-mq:0 gc-jp:0 gc-jp-ce:0 gc-jp-mq:0 gc-us:0 gc-us-mq:0 ique-cn:0" \ - "ntsc-1.0:128 ntsc-1.1:128 ntsc-1.2:128 pal-1.0:192 pal-1.1:192" +#pragma increment_block_number "gc-eu:0 gc-eu-mq:0 gc-jp:128 gc-jp-ce:128 gc-jp-mq:128 gc-us:128 gc-us-mq:128" \ + "ique-cn:128 ntsc-1.0:128 ntsc-1.1:128 ntsc-1.2:128 pal-1.0:128 pal-1.1:128" static s32 D_80858AA0; // TODO: There's probably a way to match BSS ordering with less padding by spreading the variables out and moving // data around. It would be easier if we had more options for controlling BSS ordering in debug. -#pragma increment_block_number "gc-eu:128 gc-eu-mq:128 gc-jp:128 gc-jp-ce:128 gc-jp-mq:128 gc-us:128 gc-us-mq:128" \ - "ique-cn:128 ntsc-1.0:192 ntsc-1.1:192 ntsc-1.2:192 pal-1.0:192 pal-1.1:192" +#pragma increment_block_number "gc-eu:128 gc-eu-mq:128 gc-jp:192 gc-jp-ce:192 gc-jp-mq:192 gc-us:192 gc-us-mq:192" \ + "ique-cn:192 ntsc-1.0:192 ntsc-1.1:192 ntsc-1.2:192 pal-1.0:192 pal-1.1:192" static s32 sSavedCurrentMask; static Vec3f sInteractWallCheckResult; static Input* sControlInput; -#pragma increment_block_number "gc-eu:192 gc-eu-mq:192 gc-jp:160 gc-jp-ce:160 gc-jp-mq:160 gc-us:160 gc-us-mq:160" \ - "ique-cn:160 ntsc-1.0:128 ntsc-1.1:128 ntsc-1.2:128 pal-1.0:128 pal-1.1:128" +#pragma increment_block_number "gc-eu:160 gc-eu-mq:160 gc-jp:192 gc-jp-ce:192 gc-jp-mq:192 gc-us:192 gc-us-mq:192" \ + "ique-cn:192 ntsc-1.0:128 ntsc-1.1:128 ntsc-1.2:128 pal-1.0:128 pal-1.1:128" // .data diff --git a/src/overlays/misc/ovl_kaleido_scope/z_kaleido_scope.c b/src/overlays/misc/ovl_kaleido_scope/z_kaleido_scope.c index 2e4bda50cb..cf4c408427 100644 --- a/src/overlays/misc/ovl_kaleido_scope/z_kaleido_scope.c +++ b/src/overlays/misc/ovl_kaleido_scope/z_kaleido_scope.c @@ -39,7 +39,7 @@ #endif #include "assets/textures/icon_item_gameover_static/icon_item_gameover_static.h" -#pragma increment_block_number "gc-eu:128 gc-eu-mq:128 gc-jp:128 gc-jp-ce:128 gc-jp-mq:128 gc-us:128 gc-us-mq:128" \ +#pragma increment_block_number "gc-eu:0 gc-eu-mq:0 gc-jp:128 gc-jp-ce:128 gc-jp-mq:128 gc-us:128 gc-us-mq:128" \ "ntsc-1.0:0 ntsc-1.1:0 ntsc-1.2:0 pal-1.0:0 pal-1.1:0" #if !PLATFORM_GC diff --git a/tools/Makefile b/tools/Makefile index 6e311ab398..7f6eef55a1 100644 --- a/tools/Makefile +++ b/tools/Makefile @@ -35,7 +35,6 @@ ifneq ($(LLD),0) endif all: $(PROGRAMS) $(IDO_RECOMP_5_3_DIR) $(IDO_RECOMP_7_1_DIR) $(EGCS_DIR) - $(MAKE) -C ZAPD $(MAKE) -C fado $(MAKE) -C audio $(MAKE) -C com-plugin @@ -44,7 +43,6 @@ all: $(PROGRAMS) $(IDO_RECOMP_5_3_DIR) $(IDO_RECOMP_7_1_DIR) $(EGCS_DIR) clean: $(RM) $(PROGRAMS) $(addsuffix .exe,$(PROGRAMS)) $(RM) -r ido_recomp egcs - $(MAKE) -C ZAPD clean $(MAKE) -C fado clean $(MAKE) -C audio clean $(MAKE) -C com-plugin clean diff --git a/tools/ZAPD/.clang-format b/tools/ZAPD/.clang-format deleted file mode 100644 index 5ba1c4a955..0000000000 --- a/tools/ZAPD/.clang-format +++ /dev/null @@ -1,84 +0,0 @@ ---- -AccessModifierOffset: -4 -AlignAfterOpenBracket: Align -AlignConsecutiveAssignments: false -AlignConsecutiveDeclarations: false -AlignEscapedNewlinesLeft: false -AlignOperands: true -AlignTrailingComments: true -AllowAllParametersOfDeclarationOnNextLine: true -AllowShortBlocksOnASingleLine: false -AllowShortCaseLabelsOnASingleLine: false -AllowShortFunctionsOnASingleLine: InlineOnly -AllowShortIfStatementsOnASingleLine: false -AllowShortLoopsOnASingleLine: false -AlwaysBreakAfterDefinitionReturnType: None -AlwaysBreakAfterReturnType: None -AlwaysBreakBeforeMultilineStrings: false -AlwaysBreakTemplateDeclarations: true -BinPackArguments: true -BinPackParameters: true -BraceWrapping: - AfterCaseLabel: true - AfterClass: true - AfterControlStatement: true - AfterEnum: true - AfterFunction: true - AfterNamespace: true - AfterStruct: true - AfterUnion: true - BeforeCatch: true - BeforeElse: true - IndentBraces: false -BreakBeforeBinaryOperators: None -BreakBeforeBraces: Custom -BreakBeforeTernaryOperators: false -BreakConstructorInitializersBeforeComma: false -ColumnLimit: 100 -CommentPragmas: '^ (IWYU pragma:|NOLINT)' -ConstructorInitializerAllOnOneLineOrOnePerLine: false -ConstructorInitializerIndentWidth: 4 -ContinuationIndentWidth: 4 -Cpp11BracedListStyle: true -DerivePointerAlignment: false -DisableFormat: false -ForEachMacros: [ ] -IncludeCategories: - - Regex: '^<[Ww]indows\.h>$' - Priority: 1 - - Regex: '^<' - Priority: 2 - - Regex: '^"' - Priority: 3 -IndentCaseLabels: false -IndentWidth: 4 -IndentWrappedFunctionNames: false -KeepEmptyLinesAtTheStartOfBlocks: false -MacroBlockBegin: '' -MacroBlockEnd: '' -MaxEmptyLinesToKeep: 1 -NamespaceIndentation: None -PenaltyBreakBeforeFirstCallParameter: 19 -PenaltyBreakComment: 300 -PenaltyBreakFirstLessLess: 120 -PenaltyBreakString: 1000 -PenaltyExcessCharacter: 1000000 -PenaltyReturnTypeOnItsOwnLine: 60 -PointerAlignment: Left -ReflowComments: true -SortIncludes: false -SpaceAfterCStyleCast: false -SpaceBeforeAssignmentOperators: true -SpaceBeforeParens: ControlStatements -SpaceInEmptyParentheses: false -SpacesBeforeTrailingComments: 2 -SpacesInAngles: false -SpacesInContainerLiterals: true -SpacesInCStyleCastParentheses: false -SpacesInParentheses: false -SpacesInSquareBrackets: false -Standard: Latest -TabWidth: 4 -UseTab: AlignWithSpaces -... - diff --git a/tools/ZAPD/.github/workflows/main.yml b/tools/ZAPD/.github/workflows/main.yml deleted file mode 100644 index 604c18c961..0000000000 --- a/tools/ZAPD/.github/workflows/main.yml +++ /dev/null @@ -1,98 +0,0 @@ -name: Build ZAPD - -on: - push: - pull_request: - branches: - - master - -jobs: - build: - runs-on: self-hosted-runner - - steps: - - name: Checkout repository - uses: actions/checkout@v2 - - - name: Build ZAPD - run: make -j WERROR=1 - - - name: Checkout Repos - run: echo "Checkout Repos" - - - name: Checkout oot - run: | - cd ../ - rm -rf oot/ - git clone https://github.com/zeldaret/oot.git - cd oot - echo $(pwd) - git submodule update --init --recursive - - - name: Checkout mm - run: | - cd ../ - rm -rf mm/ - git clone https://github.com/zeldaret/mm.git - cd mm - echo $(pwd) - - - name: Set up repos - run: echo "Set up repos" - - - name: Setup OOT - run: | - cd ../ - cd oot - echo $(pwd) - mkdir -p baseroms/gc-eu-mq-dbg/segments - cp ~/baserom_original.z64 ./baseroms/gc-eu-mq-dbg/baserom.z64 - cd tools - rm -rf ZAPD/ - ln -s ../../ZAPD - cd ../ - make -j $(nproc) setup - - - name: Setup MM - run: | - cd ../ - cd mm - echo $(pwd) - python3 -m venv .mm-env - source .mm-env/bin/activate - python3 -m pip install -r requirements.txt - cp ~/baserom.mm.us.rev1.z64 ./baserom.mm.us.rev1.z64 - cd tools - rm -rf ZAPD/ - ln -s ../../ZAPD - cd ../ - make -C tools -j - python3 tools/fixbaserom.py - python3 tools/extract_baserom.py - python3 tools/decompress_yars.py - python3 extract_assets.py -j $(nproc) - - - name: Build Repos - run: echo "Build Repos" - - - name: Build oot - run: | - cd ../ - cd oot - echo $(pwd) - make venv - make -j - - - name: Build mm - run: | - cd ../ - cd mm - echo $(pwd) - python3 -m venv .mm-env - source .mm-env/bin/activate - python3 -m pip install -r requirements.txt - make -j disasm - make -j - - - name: Clean workspace - run: git clean -fdX diff --git a/tools/ZAPD/.gitignore b/tools/ZAPD/.gitignore deleted file mode 100644 index 68c502e36a..0000000000 --- a/tools/ZAPD/.gitignore +++ /dev/null @@ -1,341 +0,0 @@ -## Ignore Visual Studio temporary files, build results, and -## files generated by popular Visual Studio add-ons. -## -## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore - -# User-specific files -*.suo -*.user -*.userosscache -*.sln.docstates - -# User-specific files (MonoDevelop/Xamarin Studio) -*.userprefs - -# Build results -[Dd]ebug/ -[Dd]ebugPublic/ -[Rr]elease/ -[Rr]eleases/ -x64/ -x86/ -bld/ -[Bb]in/ -[Oo]bj/ -[Ll]og/ - -# Visual Studio 2015/2017 cache/options directory -.vs/ -# Uncomment if you have tasks that create the project's static files in wwwroot -#wwwroot/ - -# Visual Studio 2017 auto generated files -Generated\ Files/ - -# MSTest test Results -[Tt]est[Rr]esult*/ -[Bb]uild[Ll]og.* - -# NUNIT -*.VisualState.xml -TestResult.xml - -# Build Results of an ATL Project -[Dd]ebugPS/ -[Rr]eleasePS/ -dlldata.c - -# Benchmark Results -BenchmarkDotNet.Artifacts/ - -# .NET Core -project.lock.json -project.fragment.lock.json -artifacts/ -**/Properties/launchSettings.json - -# StyleCop -StyleCopReport.xml - -# Files built by Visual Studio -*_i.c -*_p.c -*_i.h -*.ilk -*.meta -*.obj -*.iobj -*.pch -*.pdb -*.ipdb -*.pgc -*.pgd -*.rsp -*.sbr -*.tlb -*.tli -*.tlh -*.tmp -*.tmp_proj -*.log -*.vspscc -*.vssscc -.builds -*.pidb -*.svclog -*.scc - -# Chutzpah Test files -_Chutzpah* - -# Visual C++ cache files -ipch/ -*.aps -*.ncb -*.opendb -*.opensdf -*.sdf -*.cachefile -*.VC.db -*.VC.VC.opendb - -# Visual Studio profiler -*.psess -*.vsp -*.vspx -*.sap - -# Visual Studio Trace Files -*.e2e - -# TFS 2012 Local Workspace -$tf/ - -# Guidance Automation Toolkit -*.gpState - -# ReSharper is a .NET coding add-in -_ReSharper*/ -*.[Rr]e[Ss]harper -*.DotSettings.user - -# JustCode is a .NET coding add-in -.JustCode - -# TeamCity is a build add-in -_TeamCity* - -# DotCover is a Code Coverage Tool -*.dotCover - -# AxoCover is a Code Coverage Tool -.axoCover/* -!.axoCover/settings.json - -# Visual Studio code coverage results -*.coverage -*.coveragexml - -# NCrunch -_NCrunch_* -.*crunch*.local.xml -nCrunchTemp_* - -# MightyMoose -*.mm.* -AutoTest.Net/ - -# Web workbench (sass) -.sass-cache/ - -# Installshield output folder -[Ee]xpress/ - -# DocProject is a documentation generator add-in -DocProject/buildhelp/ -DocProject/Help/*.HxT -DocProject/Help/*.HxC -DocProject/Help/*.hhc -DocProject/Help/*.hhk -DocProject/Help/*.hhp -DocProject/Help/Html2 -DocProject/Help/html - -# Click-Once directory -publish/ - -# Publish Web Output -*.[Pp]ublish.xml -*.azurePubxml -# Note: Comment the next line if you want to checkin your web deploy settings, -# but database connection strings (with potential passwords) will be unencrypted -*.pubxml -*.publishproj - -# Microsoft Azure Web App publish settings. Comment the next line if you want to -# checkin your Azure Web App publish settings, but sensitive information contained -# in these scripts will be unencrypted -PublishScripts/ - -# NuGet Packages -*.nupkg -# The packages folder can be ignored because of Package Restore -**/[Pp]ackages/* -# except build/, which is used as an MSBuild target. -!**/[Pp]ackages/build/ -# Uncomment if necessary however generally it will be regenerated when needed -#!**/[Pp]ackages/repositories.config -# NuGet v3's project.json files produces more ignorable files -*.nuget.props -*.nuget.targets - -# Microsoft Azure Build Output -csx/ -*.build.csdef - -# Microsoft Azure Emulator -ecf/ -rcf/ - -# Windows Store app package directories and files -AppPackages/ -BundleArtifacts/ -Package.StoreAssociation.xml -_pkginfo.txt -*.appx - -# Visual Studio cache files -# files ending in .cache can be ignored -*.[Cc]ache -# but keep track of directories ending in .cache -!*.[Cc]ache/ - -# Others -ClientBin/ -~$* -*~ -*.dbmdl -*.dbproj.schemaview -*.jfm -*.pfx -*.publishsettings -orleans.codegen.cs - -# Including strong name files can present a security risk -# (https://github.com/github/gitignore/pull/2483#issue-259490424) -#*.snk - -# Since there are multiple workflows, uncomment next line to ignore bower_components -# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) -#bower_components/ - -# RIA/Silverlight projects -Generated_Code/ - -# Backup & report files from converting an old project file -# to a newer Visual Studio version. Backup files are not needed, -# because we have git ;-) -_UpgradeReport_Files/ -Backup*/ -UpgradeLog*.XML -UpgradeLog*.htm -ServiceFabricBackup/ -*.rptproj.bak - -# SQL Server files -*.mdf -*.ldf -*.ndf - -# Business Intelligence projects -*.rdl.data -*.bim.layout -*.bim_*.settings -*.rptproj.rsuser - -# Microsoft Fakes -FakesAssemblies/ - -# GhostDoc plugin setting file -*.GhostDoc.xml - -# Node.js Tools for Visual Studio -.ntvs_analysis.dat -node_modules/ - -# Visual Studio 6 build log -*.plg - -# Visual Studio 6 workspace options file -*.opt - -# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) -*.vbw - -# Visual Studio LightSwitch build output -**/*.HTMLClient/GeneratedArtifacts -**/*.DesktopClient/GeneratedArtifacts -**/*.DesktopClient/ModelManifest.xml -**/*.Server/GeneratedArtifacts -**/*.Server/ModelManifest.xml -_Pvt_Extensions - -# Paket dependency manager -.paket/paket.exe -paket-files/ - -# FAKE - F# Make -.fake/ - -# JetBrains Rider -.idea/ -*.sln.iml - -# CodeRush -.cr/ - -# Python Tools for Visual Studio (PTVS) -__pycache__/ -*.pyc - -# Cake - Uncomment if you are using it -# tools/** -# !tools/packages.config - -# Tabs Studio -*.tss - -# Telerik's JustMock configuration file -*.jmconfig - -# BizTalk build output -*.btp.cs -*.btm.cs -*.odx.cs -*.xsd.cs - -# OpenCover UI analysis results -OpenCover/ - -# Azure Stream Analytics local run output -ASALocalRun/ - -# MSBuild Binary and Structured Log -*.binlog - -# NVidia Nsight GPU debugger configuration file -*.nvuser - -# MFractors (Xamarin productivity tool) working folder -.mfractor/ - -*.out -*.o -*.d -lib/libgfxd/libgfxd.a -ExporterTest/ExporterTest.a -ZAPDUtils/ZAPDUtils.a -.vscode/ -build/ -ZAPDUtils/build/ -ZAPD/BuildInfo.h diff --git a/tools/ZAPD/.gitrepo b/tools/ZAPD/.gitrepo deleted file mode 100644 index 801b2b6383..0000000000 --- a/tools/ZAPD/.gitrepo +++ /dev/null @@ -1,12 +0,0 @@ -; DO NOT EDIT (unless you know what you are doing) -; -; This subdirectory is a git "subrepo", and this file is maintained by the -; git-subrepo command. See https://github.com/git-commands/git-subrepo#readme -; -[subrepo] - remote = https://github.com/zeldaret/ZAPD.git - branch = master - commit = 35ea376daf003fdd3297a2e7355ad82e70ec1e8c - parent = b97a21c2532622a83e9153996e303c3edc2727a8 - method = merge - cmdver = 0.4.6 diff --git a/tools/ZAPD/ExporterTest/CollisionExporter.cpp b/tools/ZAPD/ExporterTest/CollisionExporter.cpp deleted file mode 100644 index 6431a4593c..0000000000 --- a/tools/ZAPD/ExporterTest/CollisionExporter.cpp +++ /dev/null @@ -1,76 +0,0 @@ -#include "CollisionExporter.h" - -void ExporterExample_Collision::Save(ZResource* res, [[maybe_unused]] fs::path outPath, - BinaryWriter* writer) -{ - ZCollisionHeader* col = (ZCollisionHeader*)res; - - writer->Write(col->absMinX); - writer->Write(col->absMinY); - writer->Write(col->absMinZ); - - writer->Write(col->absMaxX); - writer->Write(col->absMaxY); - writer->Write(col->absMaxZ); - - writer->Write(col->numVerts); - writer->Write(col->vtxAddress); - - writer->Write(col->numPolygons); - writer->Write(col->polyAddress); - writer->Write(col->polyTypeDefAddress); - writer->Write(col->camDataAddress); - - writer->Write(col->numWaterBoxes); - writer->Write(col->waterBoxAddress); - - writer->Write(col->vtxSegmentOffset); - writer->Write(col->polySegmentOffset); - writer->Write(col->polyTypeDefSegmentOffset); - writer->Write(col->camDataSegmentOffset); - writer->Write(col->waterBoxSegmentOffset); - - uint32_t oldOffset = writer->GetBaseAddress(); - - writer->Seek(col->vtxSegmentOffset, SeekOffsetType::Start); - - for (uint16_t i = 0; i < col->vertices.size(); i++) - { - for (uint32_t j = 0; j < col->vertices[i].dimensions; j++) - { - writer->Write(col->vertices[i].scalars[j].scalarData.s16); - } - } - - writer->Seek(col->polySegmentOffset, SeekOffsetType::Start); - - for (uint16_t i = 0; i < col->polygons.size(); i++) - { - writer->Write(col->polygons[i].type); - writer->Write(col->polygons[i].vtxA); - writer->Write(col->polygons[i].vtxB); - writer->Write(col->polygons[i].vtxC); - writer->Write(col->polygons[i].normX); - writer->Write(col->polygons[i].normY); - writer->Write(col->polygons[i].normZ); - writer->Write(col->polygons[i].dist); - } - - writer->Seek(col->polyTypeDefSegmentOffset, SeekOffsetType::Start); - - for (const auto& poly : col->polygonTypes) - { - writer->Write(poly.data[0]); - writer->Write(poly.data[1]); - } - writer->Seek(col->camDataSegmentOffset, SeekOffsetType::Start); - - for (auto entry : col->camData->entries) - { - writer->Write(entry.cameraSType); - writer->Write(entry.numData); - writer->Write(entry.cameraPosDataSeg); - } - - writer->Seek(oldOffset, SeekOffsetType::Start); -} diff --git a/tools/ZAPD/ExporterTest/CollisionExporter.h b/tools/ZAPD/ExporterTest/CollisionExporter.h deleted file mode 100644 index 5f48e6557e..0000000000 --- a/tools/ZAPD/ExporterTest/CollisionExporter.h +++ /dev/null @@ -1,10 +0,0 @@ -#pragma once - -#include "ZCollision.h" -#include "ZResource.h" - -class ExporterExample_Collision : public ZResourceExporter -{ -public: - void Save(ZResource* res, fs::path outPath, BinaryWriter* writer) override; -}; \ No newline at end of file diff --git a/tools/ZAPD/ExporterTest/ExporterTest.vcxproj b/tools/ZAPD/ExporterTest/ExporterTest.vcxproj deleted file mode 100644 index 341f72ceb1..0000000000 --- a/tools/ZAPD/ExporterTest/ExporterTest.vcxproj +++ /dev/null @@ -1,160 +0,0 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - 16.0 - Win32Proj - {65608eb0-1a47-45ad-ab66-192fb64c762c} - ExporterTest - 10.0 - ExporterExample - - - - Application - true - v142 - Unicode - - - Application - false - v143 - true - Unicode - - - StaticLibrary - true - v142 - Unicode - - - Application - false - v143 - true - Unicode - - - - - - - - - - - - - - - - - - - - - true - - - false - - - true - $(ProjectDir)..\ZAPD\;$(ProjectDir)..\ZAPDUtils;$(ProjectDir)..\lib\tinyxml2;$(ProjectDir)..\lib\libgfxd;$(ProjectDir)..\lib\elfio;$(ProjectDir)..\lib\stb;$(ProjectDir);$(IncludePath) - - - false - - - - Level3 - true - WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) - true - - - Console - true - - - - - Level3 - true - true - true - WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) - true - - - Console - true - true - true - - - - - Level3 - true - _DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - true - stdcpp17 - stdc11 - MultiThreadedDebug - - - Console - true - - - - - Level3 - true - true - true - NDEBUG;_CONSOLE;%(PreprocessorDefinitions) - true - - - Console - true - true - true - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/tools/ZAPD/ExporterTest/ExporterTest.vcxproj.filters b/tools/ZAPD/ExporterTest/ExporterTest.vcxproj.filters deleted file mode 100644 index 166f563a17..0000000000 --- a/tools/ZAPD/ExporterTest/ExporterTest.vcxproj.filters +++ /dev/null @@ -1,42 +0,0 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms - - - - - Header Files - - - Header Files - - - Header Files - - - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - \ No newline at end of file diff --git a/tools/ZAPD/ExporterTest/Main.cpp b/tools/ZAPD/ExporterTest/Main.cpp deleted file mode 100644 index 07fdbeeced..0000000000 --- a/tools/ZAPD/ExporterTest/Main.cpp +++ /dev/null @@ -1,79 +0,0 @@ -#include "CollisionExporter.h" -#include "Globals.h" -#include "RoomExporter.h" -#include "TextureExporter.h" - -enum class ExporterFileMode -{ - ModeExample1 = (int)ZFileMode::Custom + 1, - ModeExample2 = (int)ZFileMode::Custom + 2, - ModeExample3 = (int)ZFileMode::Custom + 3, -}; - -static void ExporterParseFileMode(const std::string& buildMode, ZFileMode& fileMode) -{ - if (buildMode == "me1") - fileMode = (ZFileMode)ExporterFileMode::ModeExample1; - else if (buildMode == "me2") - fileMode = (ZFileMode)ExporterFileMode::ModeExample2; - else if (buildMode == "me3") - fileMode = (ZFileMode)ExporterFileMode::ModeExample3; -} - -static void ExporterParseArgs([[maybe_unused]] int argc, char* argv[], int& i) -{ - std::string arg = argv[i]; - - if (arg == "--do-x") - { - } - else if (arg == "--do-y") - { - } -} - -static bool ExporterProcessFileMode(ZFileMode fileMode) -{ - // Do whatever work is associated with these custom file modes... - // Return true to indicate one of our own file modes is being processed - if (fileMode == (ZFileMode)ExporterFileMode::ModeExample1) - return true; - else if (fileMode == (ZFileMode)ExporterFileMode::ModeExample2) - return true; - else if (fileMode == (ZFileMode)ExporterFileMode::ModeExample3) - return true; - - return false; -} - -static void ExporterFileBegin(ZFile* file) -{ - printf("ExporterFileBegin() called on ZFile %s.\n", file->GetName().c_str()); -} - -static void ExporterFileEnd(ZFile* file) -{ - printf("ExporterFileEnd() called on ZFile %s.\n", file->GetName().c_str()); -} - -static void ImportExporters() -{ - // In this example we set up a new exporter called "EXAMPLE". - // By running ZAPD with the argument -se EXAMPLE, we tell it that we want to use this exporter - // for our resources. - ExporterSet* exporterSet = new ExporterSet(); - exporterSet->processFileModeFunc = ExporterProcessFileMode; - exporterSet->parseFileModeFunc = ExporterParseFileMode; - exporterSet->parseArgsFunc = ExporterParseArgs; - exporterSet->beginFileFunc = ExporterFileBegin; - exporterSet->endFileFunc = ExporterFileEnd; - exporterSet->exporters[ZResourceType::Texture] = new ExporterExample_Texture(); - exporterSet->exporters[ZResourceType::Room] = new ExporterExample_Room(); - exporterSet->exporters[ZResourceType::CollisionHeader] = new ExporterExample_Collision(); - - Globals::AddExporter("EXAMPLE", exporterSet); -} - -// When ZAPD starts up, it will automatically call the below function, which in turn sets up our -// exporters. -REGISTER_EXPORTER(ImportExporters); diff --git a/tools/ZAPD/ExporterTest/Makefile b/tools/ZAPD/ExporterTest/Makefile deleted file mode 100644 index 98e0475254..0000000000 --- a/tools/ZAPD/ExporterTest/Makefile +++ /dev/null @@ -1,28 +0,0 @@ -# Only used for standalone compilation, usually inherits these from the main makefile -CXXFLAGS ?= -Wall -Wextra -O2 -g -std=c++17 - -SRC_DIRS := $(shell find . -type d -not -path "*build*") -CPP_FILES := $(foreach dir,$(SRC_DIRS),$(wildcard $(dir)/*.cpp)) -H_FILES := $(foreach dir,$(SRC_DIRS),$(wildcard $(dir)/*.h)) - -O_FILES := $(foreach f,$(CPP_FILES:.cpp=.o),build/$f) -LIB := ExporterTest.a - -# create build directories -$(shell mkdir -p $(foreach dir,$(SRC_DIRS),build/$(dir))) - -all: $(LIB) - -clean: - rm -rf build $(LIB) - -format: - clang-format-14 -i $(CPP_FILES) $(H_FILES) - -.PHONY: all clean format - -build/%.o: %.cpp - $(CXX) $(CXXFLAGS) $(OPTFLAGS) -I ./ -I ../ZAPD -I ../ZAPDUtils -I ../lib/tinyxml2 -c $(OUTPUT_OPTION) $< - -$(LIB): $(O_FILES) - $(AR) rcs $@ $^ diff --git a/tools/ZAPD/ExporterTest/RoomExporter.cpp b/tools/ZAPD/ExporterTest/RoomExporter.cpp deleted file mode 100644 index 4cc06b76f5..0000000000 --- a/tools/ZAPD/ExporterTest/RoomExporter.cpp +++ /dev/null @@ -1,372 +0,0 @@ -#include "RoomExporter.h" -#include "CollisionExporter.h" -#include "Utils/BinaryWriter.h" -#include "Utils/File.h" -#include "Utils/MemoryStream.h" -#include "ZRoom/Commands/SetCameraSettings.h" -#include "ZRoom/Commands/SetCollisionHeader.h" -#include "ZRoom/Commands/SetCsCamera.h" -#include "ZRoom/Commands/SetEchoSettings.h" -#include "ZRoom/Commands/SetEntranceList.h" -#include "ZRoom/Commands/SetLightingSettings.h" -#include "ZRoom/Commands/SetMesh.h" -#include "ZRoom/Commands/SetRoomBehavior.h" -#include "ZRoom/Commands/SetRoomList.h" -#include "ZRoom/Commands/SetSkyboxModifier.h" -#include "ZRoom/Commands/SetSkyboxSettings.h" -#include "ZRoom/Commands/SetSoundSettings.h" -#include "ZRoom/Commands/SetSpecialObjects.h" -#include "ZRoom/Commands/SetStartPositionList.h" -#include "ZRoom/Commands/SetTimeSettings.h" -#include "ZRoom/Commands/SetWind.h" - -void ExporterExample_Room::Save(ZResource* res, fs::path outPath, BinaryWriter* writer) -{ - ZRoom* room = dynamic_cast(res); - - // MemoryStream* memStream = new MemoryStream(); - // BinaryWriter* writer = new BinaryWriter(memStream); - - for (size_t i = 0; i < room->commands.size() * 8; i++) - writer->Write((uint8_t)0); - - for (size_t i = 0; i < room->commands.size(); i++) - { - ZRoomCommand* cmd = room->commands[i]; - - writer->Seek(i * 8, SeekOffsetType::Start); - - writer->Write((uint8_t)cmd->cmdID); - - switch (cmd->cmdID) - { - case RoomCommand::SetWind: - { - SetWind* cmdSetWind = (SetWind*)cmd; - - writer->Write((uint8_t)0); // 0x01 - writer->Write((uint8_t)0); // 0x02 - writer->Write((uint8_t)0); // 0x03 - - writer->Write(cmdSetWind->windWest); // 0x04 - writer->Write(cmdSetWind->windVertical); // 0x05 - writer->Write(cmdSetWind->windSouth); // 0x06 - writer->Write(cmdSetWind->clothFlappingStrength); // 0x07 - } - break; - case RoomCommand::SetTimeSettings: - { - SetTimeSettings* cmdTime = (SetTimeSettings*)cmd; - - writer->Write((uint8_t)0); // 0x01 - writer->Write((uint8_t)0); // 0x02 - writer->Write((uint8_t)0); // 0x03 - - writer->Write(cmdTime->hour); // 0x04 - writer->Write(cmdTime->min); // 0x05 - writer->Write(cmdTime->unk); // 0x06 - writer->Write((uint8_t)0); // 0x07 - } - break; - case RoomCommand::SetSkyboxModifier: - { - SetSkyboxModifier* cmdSkybox = (SetSkyboxModifier*)cmd; - - writer->Write((uint8_t)0); // 0x01 - writer->Write((uint8_t)0); // 0x02 - writer->Write((uint8_t)0); // 0x03 - - writer->Write(cmdSkybox->disableSky); // 0x04 - writer->Write(cmdSkybox->disableSunMoon); // 0x05 - writer->Write((uint8_t)0); // 0x06 - writer->Write((uint8_t)0); // 0x07 - } - break; - case RoomCommand::SetEchoSettings: - { - SetEchoSettings* cmdEcho = (SetEchoSettings*)cmd; - - writer->Write((uint8_t)0); // 0x01 - writer->Write((uint8_t)0); // 0x02 - writer->Write((uint8_t)0); // 0x03 - writer->Write((uint8_t)0); // 0x04 - writer->Write((uint8_t)0); // 0x05 - writer->Write((uint8_t)0); // 0x06 - writer->Write((uint8_t)cmdEcho->echo); // 0x07 - } - break; - case RoomCommand::SetSoundSettings: - { - SetSoundSettings* cmdSound = (SetSoundSettings*)cmd; - - writer->Write((uint8_t)cmdSound->reverb); // 0x01 - writer->Write((uint8_t)0); // 0x02 - writer->Write((uint8_t)0); // 0x03 - writer->Write((uint8_t)0); // 0x04 - writer->Write((uint8_t)0); // 0x05 - - writer->Write(cmdSound->nightTimeSFX); // 0x06 - writer->Write(cmdSound->musicSequence); // 0x07 - } - break; - case RoomCommand::SetSkyboxSettings: - { - SetSkyboxSettings* cmdSkybox = (SetSkyboxSettings*)cmd; - - writer->Write((uint8_t)cmdSkybox->unk1); // 0x01 - writer->Write((uint8_t)0); // 0x02 - writer->Write((uint8_t)0); // 0x03 - writer->Write((uint8_t)cmdSkybox->skyboxNumber); // 0x04 - writer->Write((uint8_t)cmdSkybox->cloudsType); // 0x05 - writer->Write((uint8_t)cmdSkybox->isIndoors); // 0x06 - } - break; - case RoomCommand::SetRoomBehavior: - { - SetRoomBehavior* cmdRoom = (SetRoomBehavior*)cmd; - - writer->Write((uint8_t)cmdRoom->gameplayFlags); // 0x01 - writer->Write((uint8_t)0); // 0x02 - writer->Write((uint8_t)0); // 0x03 - writer->Write(cmdRoom->gameplayFlags2); // 0x04 - } - break; - case RoomCommand::SetCsCamera: - { - SetCsCamera* cmdCsCam = (SetCsCamera*)cmd; - - writer->Write((uint8_t)cmdCsCam->cameras.size()); // 0x01 - writer->Write((uint8_t)0); // 0x02 - writer->Write((uint8_t)0); // 0x03 - - writer->Write(cmdCsCam->segmentOffset); // 0x04 - } - break; - case RoomCommand::SetMesh: - { - SetMesh* cmdMesh = (SetMesh*)cmd; - - int baseStreamEnd = writer->GetStream().get()->GetLength(); - - writer->Write((uint8_t)cmdMesh->data); // 0x01 - writer->Write((uint8_t)0); // 0x02 - writer->Write((uint8_t)0); // 0x03 - - writer->Write(baseStreamEnd); // 0x04 - - uint32_t oldOffset = writer->GetBaseAddress(); - writer->Seek(baseStreamEnd, SeekOffsetType::Start); - - // TODO: NOT DONE - - writer->Write(cmdMesh->meshHeaderType); - - if (cmdMesh->meshHeaderType == 0) - { - // writer->Write(cmdMesh->) - } - else if (cmdMesh->meshHeaderType == 1) - { - } - else if (cmdMesh->meshHeaderType == 2) - { - } - - writer->Seek(oldOffset, SeekOffsetType::Start); - } - break; - case RoomCommand::SetCameraSettings: - { - SetCameraSettings* cmdCam = (SetCameraSettings*)cmd; - - writer->Write((uint8_t)cmdCam->cameraMovement); // 0x01 - writer->Write((uint8_t)0); // 0x02 - writer->Write((uint8_t)0); // 0x03 - writer->Write(cmdCam->mapHighlight); // 0x04 - } - break; - case RoomCommand::SetLightingSettings: - { - SetLightingSettings* cmdLight = (SetLightingSettings*)cmd; - - writer->Write((uint8_t)cmdLight->settings.size()); // 0x01 - writer->Write((uint8_t)0); // 0x02 - writer->Write((uint8_t)0); // 0x03 - writer->Write(cmdLight->segmentOffset); // 0x04 - - uint32_t oldOffset = writer->GetBaseAddress(); - writer->Seek(cmdLight->segmentOffset, SeekOffsetType::Start); - - for (LightingSettings setting : cmdLight->settings) - { - writer->Write(setting.ambientClrR); - writer->Write(setting.ambientClrG); - writer->Write(setting.ambientClrB); - - writer->Write(setting.diffuseClrA_R); - writer->Write(setting.diffuseClrA_G); - writer->Write(setting.diffuseClrA_B); - - writer->Write(setting.diffuseDirA_X); - writer->Write(setting.diffuseDirA_Y); - writer->Write(setting.diffuseDirA_Z); - - writer->Write(setting.diffuseClrB_R); - writer->Write(setting.diffuseClrB_G); - writer->Write(setting.diffuseClrB_B); - - writer->Write(setting.diffuseDirB_X); - writer->Write(setting.diffuseDirB_Y); - writer->Write(setting.diffuseDirB_Z); - - writer->Write(setting.fogClrR); - writer->Write(setting.fogClrG); - writer->Write(setting.fogClrB); - - writer->Write(setting.unk); - writer->Write(setting.drawDistance); - } - - writer->Seek(oldOffset, SeekOffsetType::Start); - } - break; - case RoomCommand::SetRoomList: - { - SetRoomList* cmdRoom = (SetRoomList*)cmd; - - writer->Write((uint8_t)cmdRoom->romfile->rooms.size()); // 0x01 - writer->Write((uint8_t)0); // 0x02 - writer->Write((uint8_t)0); // 0x03 - - auto baseStreamEnd = writer->GetLength(); - writer->Write(baseStreamEnd); // 0x04 - - uint32_t oldOffset = writer->GetBaseAddress(); - writer->Seek(baseStreamEnd, SeekOffsetType::Start); - - for (const auto& entry : cmdRoom->romfile->rooms) - { - writer->Write(entry.virtualAddressStart); - writer->Write(entry.virtualAddressEnd); - } - - writer->Seek(oldOffset, SeekOffsetType::Start); - } - break; - case RoomCommand::SetCollisionHeader: - { - SetCollisionHeader* cmdCollHeader = (SetCollisionHeader*)cmd; - - int streamEnd = writer->GetStream().get()->GetLength(); - - writer->Write((uint8_t)0); // 0x01 - writer->Write((uint8_t)0); // 0x02 - writer->Write((uint8_t)0); // 0x03 - writer->Write(streamEnd); // 0x04 - - // TODO: NOT DONE - - uint32_t oldOffset = writer->GetBaseAddress(); - writer->Seek(streamEnd, SeekOffsetType::Start); - - ExporterExample_Collision colExp = ExporterExample_Collision(); - - colExp.Save(cmdCollHeader->collisionHeader, outPath, writer); - - writer->Seek(oldOffset, SeekOffsetType::Start); - } - break; - case RoomCommand::SetEntranceList: - { - SetEntranceList* cmdEntrance = (SetEntranceList*)cmd; - - uint32_t baseStreamEnd = writer->GetStream().get()->GetLength(); - - writer->Write((uint8_t)0); // 0x01 - writer->Write((uint8_t)0); // 0x02 - writer->Write((uint8_t)0); // 0x03 - writer->Write(baseStreamEnd); // 0x04 - - uint32_t oldOffset = writer->GetBaseAddress(); - writer->Seek(baseStreamEnd, SeekOffsetType::Start); - - for (Spawn entry : cmdEntrance->entrances) - { - writer->Write((uint8_t)entry.startPositionIndex); - writer->Write((uint8_t)entry.roomToLoad); - } - - writer->Seek(oldOffset, SeekOffsetType::Start); - } - break; - case RoomCommand::SetSpecialObjects: - { - SetSpecialObjects* cmdSpecObj = (SetSpecialObjects*)cmd; - - writer->Write((uint8_t)cmdSpecObj->elfMessage); // 0x01 - writer->Write((uint8_t)0); // 0x02 - writer->Write((uint8_t)0); // 0x03 - writer->Write((uint8_t)0); // 0x04 - writer->Write((uint8_t)0); // 0x05 - writer->Write((uint16_t)cmdSpecObj->globalObject); // 0x06 - } - break; - case RoomCommand::SetStartPositionList: - { - SetStartPositionList* cmdStartPos = (SetStartPositionList*)cmd; - - uint32_t baseStreamEnd = writer->GetStream().get()->GetLength(); - - writer->Write((uint8_t)cmdStartPos->actors.size()); // 0x01 - writer->Write((uint8_t)0); // 0x02 - writer->Write((uint8_t)0); // 0x03 - writer->Write(baseStreamEnd); // 0x04 - - uint32_t oldOffset = writer->GetBaseAddress(); - writer->Seek(baseStreamEnd, SeekOffsetType::Start); - - for (ActorSpawnEntry entry : cmdStartPos->actors) - { - writer->Write(entry.actorNum); - writer->Write(entry.posX); - writer->Write(entry.posY); - writer->Write(entry.posZ); - writer->Write(entry.rotX); - writer->Write(entry.rotY); - writer->Write(entry.rotZ); - writer->Write(entry.params); - } - - writer->Seek(oldOffset, SeekOffsetType::Start); - } - break; - case RoomCommand::EndMarker: - { - writer->Write((uint8_t)0); // 0x01 - writer->Write((uint8_t)0); // 0x02 - writer->Write((uint8_t)0); // 0x03 - writer->Write((uint8_t)0); // 0x04 - writer->Write((uint8_t)0); // 0x05 - writer->Write((uint8_t)0); // 0x06 - writer->Write((uint8_t)0); // 0x07 - } - break; - default: - printf("UNIMPLEMENTED COMMAND: %i\n", (int)cmd->cmdID); - - writer->Write((uint8_t)0); // 0x01 - writer->Write((uint8_t)0); // 0x02 - writer->Write((uint8_t)0); // 0x03 - writer->Write((uint8_t)0); // 0x04 - writer->Write((uint8_t)0); // 0x05 - writer->Write((uint8_t)0); // 0x06 - writer->Write((uint8_t)0); // 0x07 - - break; - } - } - - // writer->Close(); - // File::WriteAllBytes(StringHelper::Sprintf("%s", res->GetName().c_str()), - // memStream->ToVector()); -} diff --git a/tools/ZAPD/ExporterTest/RoomExporter.h b/tools/ZAPD/ExporterTest/RoomExporter.h deleted file mode 100644 index ee531dc87b..0000000000 --- a/tools/ZAPD/ExporterTest/RoomExporter.h +++ /dev/null @@ -1,10 +0,0 @@ -#pragma once - -#include "ZResource.h" -#include "ZRoom/ZRoom.h" - -class ExporterExample_Room : public ZResourceExporter -{ -public: - void Save(ZResource* res, fs::path outPath, BinaryWriter* writer) override; -}; \ No newline at end of file diff --git a/tools/ZAPD/ExporterTest/TextureExporter.cpp b/tools/ZAPD/ExporterTest/TextureExporter.cpp deleted file mode 100644 index 6488bed3a2..0000000000 --- a/tools/ZAPD/ExporterTest/TextureExporter.cpp +++ /dev/null @@ -1,14 +0,0 @@ -#include "TextureExporter.h" -#include "../ZAPD/ZFile.h" - -void ExporterExample_Texture::Save(ZResource* res, [[maybe_unused]] fs::path outPath, - BinaryWriter* writer) -{ - ZTexture* tex = (ZTexture*)res; - - auto data = tex->parent->GetRawData(); - - for (offset_t i = tex->GetRawDataIndex(); i < tex->GetRawDataIndex() + tex->GetRawDataSize(); - i++) - writer->Write(data[i]); -} diff --git a/tools/ZAPD/ExporterTest/TextureExporter.h b/tools/ZAPD/ExporterTest/TextureExporter.h deleted file mode 100644 index 41c4e79be2..0000000000 --- a/tools/ZAPD/ExporterTest/TextureExporter.h +++ /dev/null @@ -1,11 +0,0 @@ -#pragma once - -#include "Utils/BinaryWriter.h" -#include "ZResource.h" -#include "ZTexture.h" - -class ExporterExample_Texture : public ZResourceExporter -{ -public: - void Save(ZResource* res, fs::path outPath, BinaryWriter* writer) override; -}; \ No newline at end of file diff --git a/tools/ZAPD/Jenkinsfile b/tools/ZAPD/Jenkinsfile deleted file mode 100644 index 48535a51cf..0000000000 --- a/tools/ZAPD/Jenkinsfile +++ /dev/null @@ -1,106 +0,0 @@ -pipeline { - agent { - label 'ZAPD' - } - - stages { - // Non-parallel ZAPD stage - stage('Build ZAPD') { - steps { - sh 'make -j WERROR=1' - } - } - - // CHECKOUT THE REPOS - stage('Checkout Repos') { - parallel { - stage('Checkout oot') { - steps { - dir('oot') { - git url: 'https://github.com/zeldaret/oot.git' - } - } - } - - stage('Checkout mm') { - steps{ - dir('mm') { - git url: 'https://github.com/zeldaret/mm.git' - } - } - } - } - } - - // SETUP THE REPOS - stage('Set up repos') { - parallel { - stage('Setup OOT') { - steps { - dir('oot') { - sh 'cp /usr/local/etc/roms/baserom_oot.z64 baserom_original.z64' - - // Identical to `make setup` except for copying our newer ZAPD.out into oot - sh 'git submodule update --init --recursive' - sh 'make -C tools' - sh 'cp ../ZAPD.out tools/ZAPD/' - sh 'python3 fixbaserom.py' - sh 'python3 extract_baserom.py' - sh 'python3 extract_assets.py' - } - } - } - - stage('Setup MM') { - steps { - dir('mm') { - sh 'cp /usr/local/etc/roms/mm.us.rev1.z64 baserom.mm.us.rev1.z64' - - // Identical to `make setup` except for copying our newer ZAPD.out into mm - sh 'make -C tools' - sh 'cp ../ZAPD.out tools/ZAPD/' - sh 'python3 tools/fixbaserom.py' - sh 'python3 tools/extract_baserom.py' - sh 'python3 extract_assets.py -j $(nproc)' - } - } - } - } - } - - // INSTALL PYTHON DEPENDENCIES, currently MM only - stage('Install Python dependencies') { - steps { - dir('mm') { - sh 'python3 -m pip install -r requirements.txt' - } - } - } - - // BUILD THE REPOS - stage('Build repos') { - parallel { - stage('Build oot') { - steps { - dir('oot') { - sh 'make -j' - } - } - } - stage('Build mm') { - steps { - dir('mm') { - sh 'make -j disasm' - sh 'make -j' - } - } - } - } - } - } - post { - always { - cleanWs() - } - } -} diff --git a/tools/ZAPD/LICENSE b/tools/ZAPD/LICENSE deleted file mode 100644 index 90b734bde8..0000000000 --- a/tools/ZAPD/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2020 Zelda Reverse Engineering Team - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/tools/ZAPD/Makefile b/tools/ZAPD/Makefile deleted file mode 100644 index 36331937a7..0000000000 --- a/tools/ZAPD/Makefile +++ /dev/null @@ -1,151 +0,0 @@ -# use variables in submakes -export -OPTIMIZATION_ON ?= 1 -ASAN ?= 0 -DEPRECATION_ON ?= 1 -DEBUG ?= 0 -COPYCHECK_ARGS ?= -LLD ?= 0 -WERROR ?= 0 - -# On MacOS 10.14, use boost::filesystem, because -# the system doesn't supply std::filesystem. -ifneq ($(OS),Windows_NT) - ifeq ($(shell uname -s),Darwin) - MACOS_VERSION := $(shell sw_vers -productVersion | cut -d . -f 1,2) - ifeq ($(MACOS_VERSION),10.14) - USE_BOOST_FS ?= 1 - endif - endif -endif -USE_BOOST_FS ?= 0 - -# Use clang++ if available, else use g++ -ifeq ($(shell command -v clang++ >/dev/null 2>&1; echo $$?),0) - CXX := clang++ -else - CXX := g++ -endif - -INC := -I ZAPD -I lib/libgfxd -I lib/tinyxml2 -I ZAPDUtils -CXXFLAGS := -fpic -std=c++17 -Wall -Wextra -fno-omit-frame-pointer -OPTFLAGS := - -ifneq ($(DEBUG),0) - OPTIMIZATION_ON = 0 - CXXFLAGS += -g3 -DDEVELOPMENT -D_DEBUG - COPYCHECK_ARGS += --devel - DEPRECATION_ON = 0 -endif - -ifneq ($(WERROR),0) - CXXFLAGS += -Werror -endif - -ifeq ($(OPTIMIZATION_ON),0) - OPTFLAGS := -O0 -else - OPTFLAGS := -O2 -endif - -ifneq ($(ASAN),0) - CXXFLAGS += -fsanitize=address -fsanitize=pointer-compare -fsanitize=pointer-subtract -fsanitize=undefined -endif -ifneq ($(DEPRECATION_ON),0) - CXXFLAGS += -DDEPRECATION_ON -endif -# CXXFLAGS += -DTEXTURE_DEBUG - -LDFLAGS := -lm -ldl -lpng - -ifneq ($(USE_BOOST_FS),0) - CXXFLAGS += -DUSE_BOOST_FS - LDFLAGS += -lboost_filesystem -endif - -# Use LLD if available. Set LLD=0 to not use it -ifeq ($(shell command -v ld.lld >/dev/null 2>&1; echo $$?),0) - LLD := 1 -endif - -ifneq ($(LLD),0) - LDFLAGS += -fuse-ld=lld -endif - -UNAME := $(shell uname) -UNAMEM := $(shell uname -m) -ifneq ($(UNAME), Darwin) - LDFLAGS += -Wl,-export-dynamic -lstdc++fs - EXPORTERS := -Wl,--whole-archive ExporterTest/ExporterTest.a -Wl,--no-whole-archive -else - EXPORTERS := -Wl,-force_load ExporterTest/ExporterTest.a - ifeq ($(UNAMEM),arm64) - ifeq ($(shell brew list libpng > /dev/null 2>&1; echo $$?),0) - LDFLAGS += -L $(shell brew --prefix)/lib - INC += -I $(shell brew --prefix)/include - else - $(error Please install libpng via Homebrew) - endif - endif -endif - - -ZAPD_SRC_DIRS := $(shell find ZAPD -type d) -SRC_DIRS = $(ZAPD_SRC_DIRS) lib/tinyxml2 - -ZAPD_CPP_FILES := $(foreach dir,$(ZAPD_SRC_DIRS),$(wildcard $(dir)/*.cpp)) -ZAPD_H_FILES := $(foreach dir,$(ZAPD_SRC_DIRS),$(wildcard $(dir)/*.h)) - -CPP_FILES += $(ZAPD_CPP_FILES) lib/tinyxml2/tinyxml2.cpp -O_FILES := $(foreach f,$(CPP_FILES:.cpp=.o),build/$f) -O_FILES += build/ZAPD/BuildInfo.o - -# create build directories -$(shell mkdir -p $(foreach dir,$(SRC_DIRS),build/$(dir))) - - -# Main targets -all: ZAPD.out copycheck - -build/ZAPD/BuildInfo.o: - python3 ZAPD/genbuildinfo.py $(COPYCHECK_ARGS) - $(CXX) $(CXXFLAGS) $(OPTFLAGS) $(INC) -c $(OUTPUT_OPTION) build/ZAPD/BuildInfo.cpp - -copycheck: ZAPD.out - python3 copycheck.py - -clean: - rm -rf build ZAPD.out - $(MAKE) -C lib/libgfxd clean - $(MAKE) -C ZAPDUtils clean - $(MAKE) -C ExporterTest clean - -rebuild: clean all - -format: - clang-format-14 -i $(ZAPD_CPP_FILES) $(ZAPD_H_FILES) - $(MAKE) -C ZAPDUtils format - $(MAKE) -C ExporterTest format - -.PHONY: all build/ZAPD/BuildInfo.o copycheck clean rebuild format - -build/%.o: %.cpp - $(CXX) $(CXXFLAGS) $(OPTFLAGS) $(INC) -c $(OUTPUT_OPTION) $< - - -# Submakes -lib/libgfxd/libgfxd.a: - $(MAKE) -C lib/libgfxd - -.PHONY: ExporterTest -ExporterTest: - $(MAKE) -C ExporterTest - -.PHONY: ZAPDUtils -ZAPDUtils: - $(MAKE) -C ZAPDUtils - - -# Linking -ZAPD.out: $(O_FILES) lib/libgfxd/libgfxd.a ExporterTest ZAPDUtils - $(CXX) $(CXXFLAGS) $(O_FILES) lib/libgfxd/libgfxd.a ZAPDUtils/ZAPDUtils.a $(EXPORTERS) $(LDFLAGS) $(OUTPUT_OPTION) diff --git a/tools/ZAPD/README.md b/tools/ZAPD/README.md deleted file mode 100644 index 5006f8d4b5..0000000000 --- a/tools/ZAPD/README.md +++ /dev/null @@ -1,174 +0,0 @@ -# ZAPD: Zelda Asset Processor for Decomp - -## Compiling - -### Dependencies - -ZAPD needs a compiler with C++17 support. - -ZAPD has the following library dependencies: - -- `libpng` - -In a Debian/Ubuntu based environment, those could be installed with the following command: - -```bash -sudo apt install libpng-dev -``` - -On a Mac, you will need to install libpng with Homebrew or MacPorts; we currently only support Homebrew. You can run - -```bash -brew install libpng -``` - -to install it via Homebrew. - -### Building - -#### Linux / *nix - -ZAPD uses the classic `Makefile` approach. To build just run `make` (or even better `make -j` for faster compilations). - -You can configure a bit your ZAPD build with the following options: - -- `OPTIMIZATION_ON`: If set to `0` optimizations will be disabled (compile with `-O0`). Any other value compiles with `-O2`. Defaults to `1`. -- `ASAN`: If it is set to a non-zero then ZAPD will be compiled with Address Sanitizer enabled (`-fsanitize=address`). Defaults to `0`. -- `DEPRECATION_ON`: If it is set to a zero then deprecation warnings will be disabled. Defaults to `1`. -- `DEBUG`: If non-zero, ZAPD will be compiled in _development mode_. This implies the following: - - Debugging symbols enabled (`-g3`). They are disabled by default. - - `OPTIMIZATION_ON=0`: Disables optimizations (`-O0`). - - `DEPRECATION_ON=0`: Disables deprecation warnings. -- `LLD=1`: builds with the LLVM linker `ld.lld` instead of the system default. - -As an example, if you want to build ZAPD with optimizations disabled and use the address sanitizer, you could use the following command: - -```bash -make -j OPTIMIZATION_ON=0 ASAN=1 -``` - -#### Windows - -This repository contains `vcxproj` files for compiling under Visual Studio environments. See `ZAPD/ZAPD.vcxproj`. - -## Invoking ZAPD - -ZAPD needs a _File parsing mode_ to be passed as first parameter. The options are: - -- `e`: "Extraction" mode. - - In this mode, ZAPD expects a XML file as input, a folder as ouput and a path to the baserom files. - - ZAPD will read the XML and use it as a guide to extract the contents of the specified asset file from the baserom folder. - - For more info of the format of those XMLs, see the [ZAPD extraction XML reference](docs/zapd_extraction_xml_reference.md). -- `bsf`: "Build source file" mode. - - This is an experimental mode. - - It was going to be used to let you have XMLs that aren't just for extraction. Might get used, might not. Still need to experiment on that. -- `btex`: "Build texture" mode. - - In this mode, ZAPD expects a PNG file as input, a filename as ouput and a texture type parameter (`-tt`). - - ZAPD will try to convert the given PNG into the contents of a `uint64_t` C array. -- `bren`: "Build (render) background" mode. - - In this mode, ZAPD expects a JPG file as input and a filename as ouput. - - ZAPD will try to convert the given JPG into the contents of a `uint64_t` C array. -- `blb`: "Build blob" mode. - - In this mode, ZAPD expects a BIN file as input and a filename as ouput. - - ZAPD will try to convert the given BIN into the contents of a `uint8_t` C array. - -ZAPD also accepts the following list of extra parameters: - -- `-i PATH` / `--inputpath PATH`: Set input path. -- `-o PATH` / `--outputpath PATH`: Set output path. -- `-b PATH` / `--baserompath`: Set baserom path. - - Can be used only in `e` or `bsf` modes. -- `-osf PATH`: Set source output path. This is the path where the `.c` and `.h` files will be extracted to. If omitted, it will use the value passed to `--outputpath` parameter. -- `-gsf MODE`: Generate source file during extraction. If `MODE` is `1`, C source files will be generated. - - Can be used only in `e` mode. -- `-crc` / `--output-crc`: Outputs a CRC file for each extracted texture. - - Can be used only in `e` or `bsf` modes. -- `-ulzdl MODE`: Use "Legacy ZDisplayList" instead of `libgfxd`. Set `MODE` to `1` to enable it. - - Can be used only in `e` or `bsf` modes. -- `-profile MODE`: Enable profiling. Set `MODE` to `1` to enable it. -- `-uer MODE`: Split resources into their individual components (enabled by default). Set `MODE` to non-`1` to disable it. -- `-tt TYPE`: Set texture type. - - Can be used only in mode `btex`. - - Valid values: - - `rgba32` - - `rgb5a1` - - `i4` - - `i8` - - `ia4` - - `ia8` - - `ia16` - - `ci4` - - `ci8` -- `-rconf PATH` Read Config File. -- `-eh`: Enable error handler. - - Only available in non-Windows environments. -- `-v MODE`: Enable verbosity. Currently there are 3 possible values: - - `0`: Default. Completely silent (except for warnings and errors). - - `1`: Information. - - `2` (and higher): Debug. -- `-wu` / `--warn-unaccounted`: Enable warnings for each unaccounted block of data found. - - Can be used only in `e` or `bsf` modes. -- `-vu` / `--verbose-unaccounted`: Changes how unaccounteds are outputted. Max 4 bytes per line (a word) and add a comment with the offset of each of those lines. - - Could be useful for looking at raw data or testing. - - Can be used only in `e` or `bsf` modes. -- `-tm MODE`: Test Mode (enables certain experimental features). To enable it, set `MODE` to `1`. -- `-se` / `--set-exporter` : Sets which exporter to use. -- `--gcc-compat` : Enables GCC compatibly mode. Slower. -- `-us` / `--unaccounted-static` : Mark unaccounted data as `static` -- `-s` / `--static` : Mark every asset as `static`. - - This behaviour can be overridden per asset using `Static=` in the respective XML node. -- `--cs-float` : How cutscene floats should be extracted. -- Valid values: - - `hex`: `0x42280000` - - `float`: `42.0f` - - `both`: `CS_FLOAT(0x42280000, 42.0f)` - - `hex-commented-left`: `/* 42.0f */ 0x42280000` - - `hex-commented-right`: `0x42280000 /* 42.0f */` -- `--base-address ADDRESS`: Override base virtual address for input files. -- `--start-offset OFFSET`: Override start offset for input files. -- `--end-offset OFFSET`: Override end offset for input files. -- `-W...`: warning flags, see below - -Additionally, you can pass the flag `--version` to see the current ZAPD version. If that flag is passed, ZAPD will ignore any other parameter passed. - -### Warning flags - -ZAPD contains a variety of warning types, with similar syntax to GCC or Clang's compiler warnings. Warnings can have three levels: - -- Off (does not display anything) -- Warn (print a warning but continue processing) -- Err (behave like an error, i.e. print and throw an exception to crash ZAPD when occurs) - -Each warning type uses one of these by default, but can be modified with flags, similarly to GCC or Clang: - -- `-Wfoo` enables warnings of type `foo` -- `-Wno-foo` disables warnings of type `foo` -- `-Werror=foo` escalates `foo` to behave like an error -- `-Weverything` enables all warnings (they may be turned off using `-Wno-` flags afterwards) -- `-Werror` escalates all enabled warnings to errors - -All warning types currently implemented, with their default levels: - -| Warning type | Default level | Description | -| ----------------------------- | ------------- | ------------------------------------------------------------------------ | -| `-Wdeprecated` | Warn | Deprecated features | -| `-Whardcoded-generic-pointer` | Off | A generic segmented pointer must be produced | -| `-Whardcoded-pointer` | Warn | ZAPD lacks the info to make a symbol, so must output a hardcoded pointer | -| `-Wintersection` | Warn | Two assets intersect | -| `-Winvalid-attribute-value` | Err | Attribute declared in XML is wrong | -| `-Winvalid-extracted-data` | Err | Extracted data does not have correct form | -| `-Winvalid-jpeg` | Err | JPEG file does not conform to the game's format requirements | -| `-Winvalid-png` | Err | Issues arising when processing PNG data | -| `-Winvalid-xml` | Err | XML has syntax errors | -| `-Wmissing-attribute` | Warn | Required attribute missing in XML tag | -| `-Wmissing-offsets` | Warn | Offset attribute missing in XML tag | -| `-Wmissing-segment` | Warn | Segment not given in File tag in XML | -| `-Wnot-implemented` | Warn | ZAPD does not currently support this feature | -| `-Wunaccounted` | Off | Large blocks of unaccounted | -| `-Wunknown-attribute` | Warn | Unknown attribute in XML entry tag | - -There are also errors that do not have a type, and cannot be disabled. - -For example, here we have invoked ZAPD in the usual way to extract using a (rather badly-written) XML, but escalating `-Wintersection` to an error: - -![ZAPD warnings example](docs/zapd_warning_example.png?raw=true) diff --git a/tools/ZAPD/ZAPD.sln b/tools/ZAPD/ZAPD.sln deleted file mode 100644 index 82538dd9f4..0000000000 --- a/tools/ZAPD/ZAPD.sln +++ /dev/null @@ -1,82 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.30320.27 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ZAPD", "ZAPD\ZAPD.vcxproj", "{B53F9E5B-0A58-4BAE-9AFE-856C8CBB8D36}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ExporterExample", "ExporterTest\ExporterTest.vcxproj", "{65608EB0-1A47-45AD-AB66-192FB64C762C}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ZAPDUtils", "ZAPDUtils\ZAPDUtils.vcxproj", "{A2E01C3E-D647-45D1-9788-043DEBC1A908}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|x64 = Debug|x64 - Debug|x86 = Debug|x86 - MinSizeRel|x64 = MinSizeRel|x64 - MinSizeRel|x86 = MinSizeRel|x86 - Release|x64 = Release|x64 - Release|x86 = Release|x86 - RelWithDebInfo|x64 = RelWithDebInfo|x64 - RelWithDebInfo|x86 = RelWithDebInfo|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {B53F9E5B-0A58-4BAE-9AFE-856C8CBB8D36}.Debug|x64.ActiveCfg = Debug|x64 - {B53F9E5B-0A58-4BAE-9AFE-856C8CBB8D36}.Debug|x64.Build.0 = Debug|x64 - {B53F9E5B-0A58-4BAE-9AFE-856C8CBB8D36}.Debug|x86.ActiveCfg = Debug|Win32 - {B53F9E5B-0A58-4BAE-9AFE-856C8CBB8D36}.Debug|x86.Build.0 = Debug|Win32 - {B53F9E5B-0A58-4BAE-9AFE-856C8CBB8D36}.MinSizeRel|x64.ActiveCfg = Release|x64 - {B53F9E5B-0A58-4BAE-9AFE-856C8CBB8D36}.MinSizeRel|x64.Build.0 = Release|x64 - {B53F9E5B-0A58-4BAE-9AFE-856C8CBB8D36}.MinSizeRel|x86.ActiveCfg = Release|Win32 - {B53F9E5B-0A58-4BAE-9AFE-856C8CBB8D36}.MinSizeRel|x86.Build.0 = Release|Win32 - {B53F9E5B-0A58-4BAE-9AFE-856C8CBB8D36}.Release|x64.ActiveCfg = Release|x64 - {B53F9E5B-0A58-4BAE-9AFE-856C8CBB8D36}.Release|x64.Build.0 = Release|x64 - {B53F9E5B-0A58-4BAE-9AFE-856C8CBB8D36}.Release|x86.ActiveCfg = Release|Win32 - {B53F9E5B-0A58-4BAE-9AFE-856C8CBB8D36}.Release|x86.Build.0 = Release|Win32 - {B53F9E5B-0A58-4BAE-9AFE-856C8CBB8D36}.RelWithDebInfo|x64.ActiveCfg = Release|x64 - {B53F9E5B-0A58-4BAE-9AFE-856C8CBB8D36}.RelWithDebInfo|x64.Build.0 = Release|x64 - {B53F9E5B-0A58-4BAE-9AFE-856C8CBB8D36}.RelWithDebInfo|x86.ActiveCfg = Release|Win32 - {B53F9E5B-0A58-4BAE-9AFE-856C8CBB8D36}.RelWithDebInfo|x86.Build.0 = Release|Win32 - {65608EB0-1A47-45AD-AB66-192FB64C762C}.Debug|x64.ActiveCfg = Debug|x64 - {65608EB0-1A47-45AD-AB66-192FB64C762C}.Debug|x64.Build.0 = Debug|x64 - {65608EB0-1A47-45AD-AB66-192FB64C762C}.Debug|x86.ActiveCfg = Debug|Win32 - {65608EB0-1A47-45AD-AB66-192FB64C762C}.Debug|x86.Build.0 = Debug|Win32 - {65608EB0-1A47-45AD-AB66-192FB64C762C}.MinSizeRel|x64.ActiveCfg = Debug|x64 - {65608EB0-1A47-45AD-AB66-192FB64C762C}.MinSizeRel|x64.Build.0 = Debug|x64 - {65608EB0-1A47-45AD-AB66-192FB64C762C}.MinSizeRel|x86.ActiveCfg = Debug|Win32 - {65608EB0-1A47-45AD-AB66-192FB64C762C}.MinSizeRel|x86.Build.0 = Debug|Win32 - {65608EB0-1A47-45AD-AB66-192FB64C762C}.Release|x64.ActiveCfg = Release|x64 - {65608EB0-1A47-45AD-AB66-192FB64C762C}.Release|x64.Build.0 = Release|x64 - {65608EB0-1A47-45AD-AB66-192FB64C762C}.Release|x86.ActiveCfg = Release|Win32 - {65608EB0-1A47-45AD-AB66-192FB64C762C}.Release|x86.Build.0 = Release|Win32 - {65608EB0-1A47-45AD-AB66-192FB64C762C}.RelWithDebInfo|x64.ActiveCfg = Release|x64 - {65608EB0-1A47-45AD-AB66-192FB64C762C}.RelWithDebInfo|x64.Build.0 = Release|x64 - {65608EB0-1A47-45AD-AB66-192FB64C762C}.RelWithDebInfo|x86.ActiveCfg = Release|Win32 - {65608EB0-1A47-45AD-AB66-192FB64C762C}.RelWithDebInfo|x86.Build.0 = Release|Win32 - {A2E01C3E-D647-45D1-9788-043DEBC1A908}.Debug|x64.ActiveCfg = Debug|x64 - {A2E01C3E-D647-45D1-9788-043DEBC1A908}.Debug|x64.Build.0 = Debug|x64 - {A2E01C3E-D647-45D1-9788-043DEBC1A908}.Debug|x86.ActiveCfg = Debug|Win32 - {A2E01C3E-D647-45D1-9788-043DEBC1A908}.Debug|x86.Build.0 = Debug|Win32 - {A2E01C3E-D647-45D1-9788-043DEBC1A908}.MinSizeRel|x64.ActiveCfg = Debug|x64 - {A2E01C3E-D647-45D1-9788-043DEBC1A908}.MinSizeRel|x64.Build.0 = Debug|x64 - {A2E01C3E-D647-45D1-9788-043DEBC1A908}.MinSizeRel|x86.ActiveCfg = Debug|Win32 - {A2E01C3E-D647-45D1-9788-043DEBC1A908}.MinSizeRel|x86.Build.0 = Debug|Win32 - {A2E01C3E-D647-45D1-9788-043DEBC1A908}.Release|x64.ActiveCfg = Release|x64 - {A2E01C3E-D647-45D1-9788-043DEBC1A908}.Release|x64.Build.0 = Release|x64 - {A2E01C3E-D647-45D1-9788-043DEBC1A908}.Release|x86.ActiveCfg = Release|Win32 - {A2E01C3E-D647-45D1-9788-043DEBC1A908}.Release|x86.Build.0 = Release|Win32 - {A2E01C3E-D647-45D1-9788-043DEBC1A908}.RelWithDebInfo|x64.ActiveCfg = Release|x64 - {A2E01C3E-D647-45D1-9788-043DEBC1A908}.RelWithDebInfo|x64.Build.0 = Release|x64 - {A2E01C3E-D647-45D1-9788-043DEBC1A908}.RelWithDebInfo|x86.ActiveCfg = Release|Win32 - {A2E01C3E-D647-45D1-9788-043DEBC1A908}.RelWithDebInfo|x86.Build.0 = Release|Win32 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {C2E1CC72-7A50-3249-AFD5-DFF6FE25CDCA} - EndGlobalSection - GlobalSection(Performance) = preSolution - HasPerformanceSessions = true - EndGlobalSection -EndGlobal diff --git a/tools/ZAPD/ZAPD/CRC32.h b/tools/ZAPD/ZAPD/CRC32.h deleted file mode 100644 index 1f82c75c58..0000000000 --- a/tools/ZAPD/ZAPD/CRC32.h +++ /dev/null @@ -1,23 +0,0 @@ -#pragma once - -static uint32_t CRC32B(const unsigned char* message, int32_t size) -{ - int32_t byte, crc; - int32_t mask; - - crc = 0xFFFFFFFF; - - for (int32_t i = 0; i < size; i++) - { - byte = message[i]; - crc = crc ^ byte; - - for (int32_t j = 7; j >= 0; j--) - { - mask = -(crc & 1); - crc = (crc >> 1) ^ (0xEDB88320 & mask); - } - } - - return ~(uint32_t)(crc); -} \ No newline at end of file diff --git a/tools/ZAPD/ZAPD/CrashHandler.cpp b/tools/ZAPD/ZAPD/CrashHandler.cpp deleted file mode 100644 index 7ddec5a7e8..0000000000 --- a/tools/ZAPD/ZAPD/CrashHandler.cpp +++ /dev/null @@ -1,206 +0,0 @@ -#include "CrashHandler.h" -#include "Utils/StringHelper.h" - -#if __has_include() -#define HAS_POSIX 1 -#else -#define HAS_POSIX 0 -#endif - -#include -#include -#include -#include -#include - -#if HAS_POSIX == 1 -#include -#include // for __cxa_demangle -#include // for dladdr -#include -#include -#elif defined(_MSC_VER) -#include -#include - -#include - -#pragma comment(lib, "Dbghelp.lib") -#endif - -// Feel free to add more crash messages. -static std::array crashEasterEgg = { - "\tYou've met with a terrible fate, haven't you?", - "\tSEA BEARS FOAM. SLEEP BEARS DREAMS. \n\tBOTH END IN THE SAME WAY: CRASSSH!", - "\tZAPD has fallen and cannot get up.", - "\tIT'S A SECRET TO EVERYBODY. \n\tBut it shouldn't be, you'd better ask about it!", - "\tI AM ERROR.", - "\tGRUMBLE,GRUMBLE...", - "\tDODONGO DISLIKES SMOKE \n\tAnd ZAPD dislikes whatever you fed it.", - "\tMay the way of the Hero lead \n\tto the debugger.", - "\tTHE WIND FISH SLUMBERS LONG... \n\tTHE HERO'S LIFE GONE... ", - "\tSEA BEARS FOAM, SLEEP BEARS DREAMS. \n\tBOTH END IN THE SAME WAY CRASSSH!", - "\tYou've met with a terrible fate, haven't you?", - "\tMaster, I calculate a 100% probability that ZAPD has crashed. \n\tAdditionally, the " - "batteries in your Wii Remote are nearly depleted.", - "\t CONGRATURATIONS! \n" - "\tAll Pages are displayed.\n" - "\t THANK YOU! \n" - "\t You are great debugger!", - "\tRCP is HUNG UP!!\n" - "\tOh! MY GOD!!", -}; - -#if HAS_POSIX == 1 -void ErrorHandler(int sig) -{ - std::array arr; - constexpr size_t nMaxFrames = arr.size(); - size_t size = backtrace(arr.data(), nMaxFrames); - char** symbols = backtrace_symbols(arr.data(), nMaxFrames); - - fprintf(stderr, "\nZAPD crashed. (Signal: %i)\n", sig); - - srand(time(nullptr)); - auto easterIndex = rand() % crashEasterEgg.size(); - - fprintf(stderr, "\n%s\n\n", crashEasterEgg[easterIndex]); - - fprintf(stderr, "Traceback:\n"); - for (size_t i = 1; i < size; i++) - { - Dl_info info; - uint32_t gotAddress = dladdr(arr[i], &info); - std::string functionName(symbols[i]); - - if (gotAddress != 0 && info.dli_sname != nullptr) - { - int32_t status; - char* demangled = abi::__cxa_demangle(info.dli_sname, nullptr, nullptr, &status); - const char* nameFound = info.dli_sname; - - if (status == 0) - { - nameFound = demangled; - } - - functionName = StringHelper::Sprintf("%s (+0x%X)", nameFound, - (char*)arr[i] - (char*)info.dli_saddr); - free(demangled); - } - - fprintf(stderr, "%-3zd %s\n", i, functionName.c_str()); - } - - fprintf(stderr, "\n"); - - free(symbols); - exit(1); -} -#elif defined(_MSC_VER) - -void printStack(CONTEXT* ctx) -{ - BOOL result; - HANDLE process; - HANDLE thread; - HMODULE hModule; - ULONG frame; - DWORD64 displacement; - DWORD disp; - - srand(time(nullptr)); - auto easterIndex = rand() % crashEasterEgg.size(); - - fprintf(stderr, "\n%s\n\n", crashEasterEgg[easterIndex]); - -#if defined(_M_AMD64) - STACKFRAME64 stack; - memset(&stack, 0, sizeof(STACKFRAME64)); -#else - STACKFRAME stack; - memset(&stack, 0, sizeof(STACKFRAME)); -#endif - - char buffer[sizeof(SYMBOL_INFO) + MAX_SYM_NAME + sizeof(TCHAR)]; - char module[512]; - - PSYMBOL_INFO symbol = (PSYMBOL_INFO)buffer; - - CONTEXT ctx2; - memcpy(&ctx2, ctx, sizeof(CONTEXT)); - - process = GetCurrentProcess(); - thread = GetCurrentThread(); - SymInitialize(process, nullptr, TRUE); - - constexpr DWORD machineType = -#if defined(_M_AMD64) - IMAGE_FILE_MACHINE_AMD64; -#else - IMAGE_FILE_MACHINE_I386; -#endif - - displacement = 0; - - for (frame = 0;; frame++) - { - result = StackWalk(machineType, process, thread, &stack, &ctx2, nullptr, - SymFunctionTableAccess, SymGetModuleBase, nullptr); - if (!result) - { - break; - } - symbol->SizeOfStruct = sizeof(SYMBOL_INFO); - symbol->MaxNameLen = MAX_SYM_NAME; - SymFromAddr(process, (ULONG64)stack.AddrPC.Offset, &displacement, symbol); -#if defined(_M_AMD64) - IMAGEHLP_LINE64 line; - line.SizeOfStruct = sizeof(IMAGEHLP_LINE64); -#else - IMAGEHLP_LINE line; - line.SizeOfStruct = sizeof(IMAGEHLP_LINE); -#endif - if (SymGetLineFromAddr(process, stack.AddrPC.Offset, &disp, &line)) - { - fprintf(stderr, "%u\t %s in %s: line: %lu: \n", frame, symbol->Name, line.FileName, - line.LineNumber); - } - - else - { - fprintf(stderr, "%u\tat % s\n", frame, symbol->Name); - hModule = nullptr; - GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | - GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, - (LPCTSTR)(stack.AddrPC.Offset), &hModule); - - if (hModule != nullptr) - { - GetModuleFileNameA(hModule, module, 512 - 1); - } - fprintf(stderr, "%u\tIn %s\n", frame, module); - } - } -} - -LONG seh_filter(_EXCEPTION_POINTERS* ex) -{ - fprintf(stderr, "EXCEPTION 0x%x occured\n", ex->ExceptionRecord->ExceptionCode); - printStack(ex->ContextRecord); - return EXCEPTION_EXECUTE_HANDLER; -} -#endif - -void CrashHandler_Init() -{ -#if HAS_POSIX == 1 - signal(SIGSEGV, ErrorHandler); - signal(SIGABRT, ErrorHandler); -#elif defined(_MSC_VER) - SetUnhandledExceptionFilter(seh_filter); -#else - HANDLE_WARNING(WarningType::Always, - "tried to set error handler, but this ZAPD build lacks support for one", ""); -#endif -} diff --git a/tools/ZAPD/ZAPD/CrashHandler.h b/tools/ZAPD/ZAPD/CrashHandler.h deleted file mode 100644 index 102778bec1..0000000000 --- a/tools/ZAPD/ZAPD/CrashHandler.h +++ /dev/null @@ -1,6 +0,0 @@ -#ifndef CRASH_HANDLER_H -#define CRASH_HANDLER_H - -void CrashHandler_Init(); - -#endif diff --git a/tools/ZAPD/ZAPD/Declaration.cpp b/tools/ZAPD/ZAPD/Declaration.cpp deleted file mode 100644 index 30863803a2..0000000000 --- a/tools/ZAPD/ZAPD/Declaration.cpp +++ /dev/null @@ -1,236 +0,0 @@ -#include "Declaration.h" - -#include "Globals.h" -#include "Utils/StringHelper.h" - -Declaration::Declaration(offset_t nAddress, DeclarationAlignment nAlignment, size_t nSize, - const std::string& nBody) -{ - address = nAddress; - alignment = nAlignment; - size = nSize; - declBody = nBody; -} - -Declaration* Declaration::Create(offset_t declAddr, DeclarationAlignment declAlign, size_t declSize, - const std::string& declType, const std::string& declName, - const std::string& declBody) -{ - Declaration* decl = new Declaration(declAddr, declAlign, declSize, declBody); - - decl->declType = declType; - decl->declName = declName; - decl->declBody = declBody; - - return decl; -} - -Declaration* Declaration::CreateArray(offset_t declAddr, DeclarationAlignment declAlign, - size_t declSize, const std::string& declType, - const std::string& declName, const std::string& declBody, - size_t declArrayItemCnt, bool isDeclExternal) -{ - Declaration* decl = new Declaration(declAddr, declAlign, declSize, declBody); - - decl->declName = declName; - decl->declType = declType; - decl->arrayItemCnt = declArrayItemCnt; - decl->isExternal = isDeclExternal; - decl->isArray = true; - - return decl; -} - -Declaration* Declaration::CreateArray(offset_t declAddr, DeclarationAlignment declAlign, - size_t declSize, const std::string& declType, - const std::string& declName, const std::string& declBody, - const std::string& declArrayItemCntStr, bool isDeclExternal) -{ - Declaration* decl = new Declaration(declAddr, declAlign, declSize, declBody); - - decl->declName = declName; - decl->declType = declType; - decl->arrayItemCntStr = declArrayItemCntStr; - decl->isExternal = isDeclExternal; - decl->isArray = true; - - return decl; -} - -Declaration* Declaration::CreateInclude(offset_t declAddr, const std::string& includePath, - size_t declSize, const std::string& declType, - const std::string& declName, const std::string& defines) -{ - Declaration* decl = new Declaration(declAddr, DeclarationAlignment::Align4, declSize, ""); - decl->includePath = includePath; - decl->declType = declType; - decl->declName = declName; - decl->defines = defines; - - return decl; -} - -Declaration* Declaration::CreatePlaceholder(offset_t declAddr, const std::string& declName) -{ - Declaration* decl = new Declaration(declAddr, DeclarationAlignment::Align4, 0, ""); - decl->declName = declName; - decl->isPlaceholder = true; - - return decl; -} - -bool Declaration::IsStatic() const -{ - switch (staticConf) - { - case StaticConfig::Off: - return false; - - case StaticConfig::Global: - return Globals::Instance->forceStatic; - - case StaticConfig::On: - return true; - } - - return false; -} - -std::string Declaration::GetNormalDeclarationStr() const -{ - std::string output; - - if (IsStatic()) - { - output += "static "; - } - - if (isArray) - { - bool includeArraySize = (IsStatic() || forceArrayCnt); - - if (includeArraySize) - { - if (arrayItemCntStr != "") - output += StringHelper::Sprintf("%s %s[%s];\n", declType.c_str(), declName.c_str(), - arrayItemCntStr.c_str()); - else - output += StringHelper::Sprintf("%s %s[%i] = {\n", declType.c_str(), - declName.c_str(), arrayItemCnt); - } - else - { - output += StringHelper::Sprintf("%s %s[] = {\n", declType.c_str(), declName.c_str()); - } - - output += declBody + "\n"; - } - else - { - output += StringHelper::Sprintf("%s %s = { ", declType.c_str(), declName.c_str()); - output += declBody; - } - - if (output.back() == '\n') - output += "};"; - else - output += " };"; - - output += "\n"; - - output += "\n"; - - return output; -} - -std::string Declaration::GetExternalDeclarationStr() const -{ - std::string output; - - if (IsStatic()) - output += "static "; - - bool includeArraySize = (IsStatic() || forceArrayCnt); - - if (includeArraySize) - { - if (arrayItemCntStr != "") - output += StringHelper::Sprintf("%s %s[%s] = ", declType.c_str(), declName.c_str(), - arrayItemCntStr.c_str()); - else - output += StringHelper::Sprintf("%s %s[%i] = ", declType.c_str(), declName.c_str(), - arrayItemCnt); - } - else - { - output += StringHelper::Sprintf("%s %s[] = ", declType.c_str(), declName.c_str()); - } - - output += StringHelper::Sprintf("{\n#include \"%s\"\n};", includePath.c_str()); - output += "\n\n"; - - return output; -} - -std::string Declaration::GetExternStr() const -{ - if (IsStatic() || declType == "" || isUnaccounted) - { - return ""; - } - - if (isArray) - { - if (arrayItemCntStr != "" && (IsStatic() || forceArrayCnt)) - { - return StringHelper::Sprintf("extern %s %s[%s];\n", declType.c_str(), declName.c_str(), - arrayItemCntStr.c_str()); - } - else if (arrayItemCnt != 0 && (IsStatic() || forceArrayCnt)) - { - return StringHelper::Sprintf("extern %s %s[%i];\n", declType.c_str(), declName.c_str(), - arrayItemCnt); - } - else - return StringHelper::Sprintf("extern %s %s[];\n", declType.c_str(), declName.c_str()); - } - - return StringHelper::Sprintf("extern %s %s;\n", declType.c_str(), declName.c_str()); -} - -std::string Declaration::GetDefinesStr() const -{ - if (IsStatic() || (declType == "")) - { - return ""; - } - return StringHelper::Sprintf("%s", defines.c_str()); -} - -std::string Declaration::GetStaticForwardDeclarationStr() const -{ - if (!IsStatic() || isUnaccounted) - return ""; - - if (isArray) - { - if (arrayItemCntStr == "" && arrayItemCnt == 0) - { - // Forward declaring static arrays without specifying the size is not allowed. - return ""; - } - - if (arrayItemCntStr != "") - { - return StringHelper::Sprintf("static %s %s[%s];\n", declType.c_str(), declName.c_str(), - arrayItemCntStr.c_str()); - } - else - { - return StringHelper::Sprintf("static %s %s[%i];\n", declType.c_str(), declName.c_str(), - arrayItemCnt); - } - } - - return StringHelper::Sprintf("static %s %s;\n", declType.c_str(), declName.c_str()); -} diff --git a/tools/ZAPD/ZAPD/Declaration.h b/tools/ZAPD/ZAPD/Declaration.h deleted file mode 100644 index d079cb8dce..0000000000 --- a/tools/ZAPD/ZAPD/Declaration.h +++ /dev/null @@ -1,182 +0,0 @@ -#pragma once - -#include -#include -#include - -// TODO: should we drop the `_t` suffix because of UNIX compliance? -typedef uint32_t segptr_t; -typedef uint32_t offset_t; - -#define SEGMENTED_NULL ((segptr_t)0) - -enum class DeclarationAlignment -{ - Align4, - Align8 -}; - -enum class StaticConfig -{ - Off, - Global, - On -}; - -/// -/// A declaration is contains the C contents of a symbol for a file. -/// It contains at a minimum the address where the symbol would be in the binary file, alignment -/// settings, the size of the binary data, and the C code that makes it up. Optionally it can also -/// contain comments. -/// -class Declaration -{ -public: - // Where in the binary file (segment) will this C code end up being? - offset_t address = 0; - - // How is this C code aligned? - DeclarationAlignment alignment = DeclarationAlignment::Align4; - - // How many bytes will this C code take up in the resulting binary when compiled? - size_t size = 0; - - // The C type of this declaration - std::string declType = ""; - - // The C variable name of this declaration - std::string declName = ""; - - // The body of the declaration containing the data. - // In "int j = 7;", "7" would be text. - std::string declBody = ""; - - // #define's to be included in the header - std::string defines = ""; - - std::string includePath = ""; - - // Is this declaration in an external file? (ie. a gameplay_keep reference being found in - // another file that wishes to use its data) - bool isExternal = false; - - bool isArray = false; - - // If true, will ensure that the arrays size is included in the declaration - bool forceArrayCnt = false; - - // If this declaration is an array, how many items make it up? - size_t arrayItemCnt = 0; - - // Overrides the brackets for the arrays size with a custom string - std::string arrayItemCntStr = ""; - - std::vector references; - - // If true, this declaration represents data inside the file which we do not understand it's - // purpose for. It will be outputted as just a byte array. - bool isUnaccounted = false; - - // Is this declaration a placeholder that will be replaced later? - bool isPlaceholder = false; - - // Does this declaration come straight from the XML? - // If false, this means that the declaration was created by ZAPD when it was parsing the - // resources. - bool declaredInXml = false; - - StaticConfig staticConf = StaticConfig::Global; - - /// - /// Creates a regular declaration. - /// - /// The address inside a binary file this declaration will be in when - /// compiled. The alignment of this declaration in the compiled - /// binary file. The size of this declaration when it is compiled - /// to binary data. The C variable type this declaration will be - /// declared as. The C variable name this declaration will be - /// declared as. The contents of the C variable - /// declaration. - static Declaration* Create(offset_t declAddr, DeclarationAlignment declAlign, size_t declSize, - const std::string& declType, const std::string& declName, - const std::string& declBody); - - /// - /// Creates an array declaration. - /// - /// The address inside a binary file this declaration will be in when - /// compiled. The alignment of this declaration in the compiled - /// binary file. The size of this declaration when it is compiled - /// to binary data. The C variable type this declaration will be - /// declared as. The C variable name this declaration will be - /// declared as. The contents of the C variable - /// declaration. The number of items in the - /// array. (Optional) Is this declaration from another - /// segment? - static Declaration* CreateArray(offset_t declAddr, DeclarationAlignment declAlign, - size_t declSize, const std::string& declType, - const std::string& declName, const std::string& declBody, - size_t declArrayItemCnt = 0, bool isDeclExternal = false); - - /// - /// Creates an array declaration who's size in the C code uses a custom string. - /// - /// The address inside a binary file this declaration will be in when - /// compiled. The alignment of this declaration in the compiled - /// binary file. The size of this declaration when it is compiled - /// to binary data. The C variable type this declaration will be - /// declared as. The C variable name this declaration will be - /// declared as. The contents of the C variable - /// declaration. The string to be put in the C array's - /// size inbetween the brackets. (Optional) Is this - /// declaration from another segment? - static Declaration* CreateArray(offset_t declAddr, DeclarationAlignment declAlign, - size_t declSize, const std::string& declType, - const std::string& declName, const std::string& declBody, - const std::string& declArrayItemCntStr, - bool isDeclExternal = false); - - /// - /// Creates a declaration who's body uses a #include to include another file - /// - /// The address inside a binary file this declaration will be in when - /// compiled. The path to the file this declaration will be - /// #including. The size of this declaration when it is compiled - /// to binary data. The C variable type this declaration will be - /// declared as. The C variable name this declaration will be - /// declared as. (Optional) Any #define's we want to have - /// outputted by this declaration. - static Declaration* CreateInclude(offset_t declAddr, const std::string& includePath, - size_t declSize, const std::string& declType, - const std::string& declName, const std::string& defines = ""); - - /// - /// Creates a placeholder declaration to be replaced later. - /// - /// The address inside a binary file this declaration will be in when - /// compiled. The C variable name this declaration will be - /// declared as. - static Declaration* CreatePlaceholder(offset_t declAddr, const std::string& declName); - - bool IsStatic() const; - - // Returns the declaration as C code as it would be in the code file when the body contains the - // needed data - std::string GetNormalDeclarationStr() const; - - // Returns the declaration as C code as it would be in the code file when the body #include's - // another file - std::string GetExternalDeclarationStr() const; - - // Generates the extern for this item to be placed in header files. - std::string GetExternStr() const; - - // Generates any #define's needed - std::string GetDefinesStr() const; - - std::string GetStaticForwardDeclarationStr() const; - -protected: - Declaration(offset_t nAddress, DeclarationAlignment nAlignment, size_t nSize, - const std::string& nBody); -}; diff --git a/tools/ZAPD/ZAPD/ExporterSet.h b/tools/ZAPD/ZAPD/ExporterSet.h deleted file mode 100644 index c4dd93445a..0000000000 --- a/tools/ZAPD/ZAPD/ExporterSet.h +++ /dev/null @@ -1,24 +0,0 @@ -#pragma once - -typedef void (*ExporterSetFunc)(ZFile*); -typedef bool (*ExporterSetFuncBool)(ZFileMode fileMode); -typedef void (*ExporterSetFuncVoid)(int argc, char* argv[], int& i); -typedef void (*ExporterSetFuncVoid2)(const std::string& buildMode, ZFileMode& fileMode); -typedef void (*ExporterSetFuncVoid3)(); -typedef void (*ExporterSetResSave)(ZResource* res, BinaryWriter& writer); - -class ExporterSet -{ -public: - ~ExporterSet(); - - std::map exporters; - ExporterSetFuncVoid parseArgsFunc = nullptr; - ExporterSetFuncVoid2 parseFileModeFunc = nullptr; - ExporterSetFuncBool processFileModeFunc = nullptr; - ExporterSetFunc beginFileFunc = nullptr; - ExporterSetFunc endFileFunc = nullptr; - ExporterSetFuncVoid3 beginXMLFunc = nullptr; - ExporterSetFuncVoid3 endXMLFunc = nullptr; - ExporterSetResSave resSaveFunc = nullptr; -}; \ No newline at end of file diff --git a/tools/ZAPD/ZAPD/GameConfig.cpp b/tools/ZAPD/ZAPD/GameConfig.cpp deleted file mode 100644 index 2140464ec6..0000000000 --- a/tools/ZAPD/ZAPD/GameConfig.cpp +++ /dev/null @@ -1,301 +0,0 @@ -#include "GameConfig.h" - -#include -#include -#include - -#include "Utils/Directory.h" -#include "Utils/File.h" -#include "Utils/Path.h" -#include "ZFile.h" -#include "tinyxml2.h" - -using ConfigFunc = void (GameConfig::*)(const tinyxml2::XMLElement&); - -GameConfig::~GameConfig() -{ - for (auto& declPair : segmentRefFiles) - { - for (auto& file : declPair.second) - { - delete file; - } - } -} - -void GameConfig::ReadTexturePool(const fs::path& texturePoolXmlPath) -{ - tinyxml2::XMLDocument doc; - tinyxml2::XMLError eResult = doc.LoadFile(texturePoolXmlPath.string().c_str()); - - if (eResult != tinyxml2::XML_SUCCESS) - { - fprintf(stderr, "Warning: Unable to read texture pool XML with error code %i\n", eResult); - return; - } - - tinyxml2::XMLNode* root = doc.FirstChild(); - - if (root == nullptr) - return; - - for (tinyxml2::XMLElement* child = root->FirstChildElement(); child != nullptr; - child = child->NextSiblingElement()) - { - if (std::string_view(child->Name()) == "Texture") - { - std::string crcStr = child->Attribute("CRC"); - fs::path texPath = child->Attribute("Path"); - std::string texName; - - uint32_t crc = strtoul(crcStr.c_str(), nullptr, 16); - - texturePool[crc].path = texPath; - } - } -} - -void GameConfig::GenSymbolMap(const fs::path& symbolMapPath) -{ - auto symbolLines = File::ReadAllLines(symbolMapPath); - - for (std::string& symbolLine : symbolLines) - { - auto split = StringHelper::Split(symbolLine, " "); - uint32_t addr = strtoul(split[0].c_str(), nullptr, 16); - std::string symbolName = split[1]; - - symbolMap[addr] = std::move(symbolName); - } -} - -void GameConfig::ConfigFunc_SymbolMap(const tinyxml2::XMLElement& element) -{ - std::string fileName = element.Attribute("File"); - GenSymbolMap(Path::GetDirectoryName(configFilePath) / fileName); -} - -void GameConfig::ConfigFunc_ActorList(const tinyxml2::XMLElement& element) -{ - std::string fileName = element.Attribute("File"); - std::vector lines = - File::ReadAllLines(Path::GetDirectoryName(configFilePath) / fileName); - - for (auto& line : lines) - actorList.emplace_back(std::move(line)); -} - -void GameConfig::ConfigFunc_ObjectList(const tinyxml2::XMLElement& element) -{ - std::string fileName = element.Attribute("File"); - std::vector lines = - File::ReadAllLines(Path::GetDirectoryName(configFilePath) / fileName); - - for (auto& line : lines) - objectList.emplace_back(std::move(line)); -} - -void GameConfig::ConfigFunc_EntranceList(const tinyxml2::XMLElement& element) -{ - std::string fileName = element.Attribute("File"); - std::vector lines = - File::ReadAllLines(Path::GetDirectoryName(configFilePath) / fileName); - - for (auto& line : lines) - entranceList.emplace_back(std::move(line)); -} - -void GameConfig::ConfigFunc_specialEntranceList(const tinyxml2::XMLElement& element) -{ - std::string fileName = element.Attribute("File"); - std::vector lines = - File::ReadAllLines(Path::GetDirectoryName(configFilePath) / fileName); - - for (auto& line : lines) - specialEntranceList.emplace_back(std::move(line)); -} - -void GameConfig::ConfigFunc_TexturePool(const tinyxml2::XMLElement& element) -{ - std::string fileName = element.Attribute("File"); - ReadTexturePool(Path::GetDirectoryName(configFilePath) / fileName); -} - -void GameConfig::ConfigFunc_BGConfig(const tinyxml2::XMLElement& element) -{ - bgScreenWidth = element.IntAttribute("ScreenWidth", 320); - bgScreenHeight = element.IntAttribute("ScreenHeight", 240); - useScreenWidthHeightConstants = element.BoolAttribute("UseScreenWidthHeightConstants", true); -} - -void GameConfig::ConfigFunc_ExternalXMLFolder(const tinyxml2::XMLElement& element) -{ - const char* pathValue = element.Attribute("Path"); - if (pathValue == nullptr) - { - throw std::runtime_error( - StringHelper::Sprintf("Parse: Fatal error in configuration file.\n" - "\t Missing 'Path' attribute in `ExternalXMLFolder` element.\n")); - } - if (externalXmlFolder != "") - { - throw std::runtime_error(StringHelper::Sprintf("Parse: Fatal error in configuration file.\n" - "\t `ExternalXMLFolder` is duplicated.\n")); - } - externalXmlFolder = pathValue; -} - -void GameConfig::ConfigFunc_ExternalFile(const tinyxml2::XMLElement& element) -{ - const char* xmlPathValue = element.Attribute("XmlPath"); - if (xmlPathValue == nullptr) - { - throw std::runtime_error( - StringHelper::Sprintf("Parse: Fatal error in configuration file.\n" - "\t Missing 'XmlPath' attribute in `ExternalFile` element.\n")); - } - const char* outPathValue = element.Attribute("OutPath"); - if (outPathValue == nullptr) - { - throw std::runtime_error( - StringHelper::Sprintf("Parse: Fatal error in configuration file.\n" - "\t Missing 'OutPath' attribute in `ExternalFile` element.\n")); - } - - externalFiles.push_back(ExternalFile(fs::path(xmlPathValue), fs::path(outPathValue))); -} - -void GameConfig::ConfigFunc_EnumData(const tinyxml2::XMLElement& element) -{ - std::string path = Path::GetDirectoryName(configFilePath).string(); - path = path.append("/").append(element.Attribute("File")); - tinyxml2::XMLDocument doc; - tinyxml2::XMLError eResult = doc.LoadFile(path.c_str()); - - if (eResult != tinyxml2::XML_SUCCESS) - { - throw std::runtime_error("Error: Unable to read enum data."); - } - - tinyxml2::XMLNode* root = doc.FirstChild(); - - if (root == nullptr) - return; - - for (tinyxml2::XMLElement* csEnum = root->FirstChildElement(); csEnum != nullptr; - csEnum = csEnum->NextSiblingElement()) - { - for (tinyxml2::XMLElement* item = csEnum->FirstChildElement(); item != nullptr; - item = item->NextSiblingElement()) - { - std::string enumKey = csEnum->Attribute("Key"); - uint16_t itemIndex = atoi(item->Attribute("Index")); - const char* itemID = item->Attribute("ID"); - - // Common - if (enumKey == "cmd") - enumData.cutsceneCmd[itemIndex] = itemID; - - else if (enumKey == "miscType") - enumData.miscType[itemIndex] = itemID; - - else if (enumKey == "textType") - enumData.textType[itemIndex] = itemID; - - else if (enumKey == "fadeOutSeqPlayer") - enumData.fadeOutSeqPlayer[itemIndex] = itemID; - - else if (enumKey == "transitionType") - enumData.transitionType[itemIndex] = itemID; - - else if (enumKey == "destination") - enumData.destination[itemIndex] = itemID; - - else if (enumKey == "naviQuestHintType") - enumData.naviQuestHintType[itemIndex] = itemID; - - else if (enumKey == "ocarinaSongActionId") - enumData.ocarinaSongActionId[itemIndex] = itemID; - - else if (enumKey == "seqId") - enumData.seqId[itemIndex] = itemID; - - else if (enumKey == "playerCueId") - enumData.playerCueId[itemIndex] = itemID; - - // MM - else if (enumKey == "modifySeqType") - enumData.modifySeqType[itemIndex] = itemID; - - else if (enumKey == "chooseCreditsSceneType") - enumData.chooseCreditsSceneType[itemIndex] = itemID; - - else if (enumKey == "destinationType") - enumData.destinationType[itemIndex] = itemID; - - else if (enumKey == "motionBlurType") - enumData.motionBlurType[itemIndex] = itemID; - - else if (enumKey == "transitionGeneralType") - enumData.transitionGeneralType[itemIndex] = itemID; - - else if (enumKey == "rumbleType") - enumData.rumbleType[itemIndex] = itemID; - - else if (enumKey == "spawnFlag") - enumData.spawnFlag[itemIndex] = itemID; - - else if (enumKey == "endSfx") - enumData.endSfx[itemIndex] = itemID; - - else if (enumKey == "csSplineInterpType") - enumData.interpType[itemIndex] = itemID; - - else if (enumKey == "csSplineRelTo") - enumData.relTo[itemIndex] = itemID; - } - } -} - -void GameConfig::ReadConfigFile(const fs::path& argConfigFilePath) -{ - static const std::unordered_map ConfigFuncDictionary = { - {"SymbolMap", &GameConfig::ConfigFunc_SymbolMap}, - {"ActorList", &GameConfig::ConfigFunc_ActorList}, - {"ObjectList", &GameConfig::ConfigFunc_ObjectList}, - {"EntranceList", &GameConfig::ConfigFunc_EntranceList}, - {"SpecialEntranceList", &GameConfig::ConfigFunc_specialEntranceList}, - {"TexturePool", &GameConfig::ConfigFunc_TexturePool}, - {"BGConfig", &GameConfig::ConfigFunc_BGConfig}, - {"EnumData", &GameConfig::ConfigFunc_EnumData}, - {"ExternalXMLFolder", &GameConfig::ConfigFunc_ExternalXMLFolder}, - {"ExternalFile", &GameConfig::ConfigFunc_ExternalFile}, - }; - - configFilePath = argConfigFilePath.string(); - tinyxml2::XMLDocument doc; - tinyxml2::XMLError eResult = doc.LoadFile(configFilePath.c_str()); - - if (eResult != tinyxml2::XML_SUCCESS) - { - throw std::runtime_error("Error: Unable to read config file."); - } - - tinyxml2::XMLNode* root = doc.FirstChild(); - - if (root == nullptr) - return; - - for (tinyxml2::XMLElement* child = root->FirstChildElement(); child != nullptr; - child = child->NextSiblingElement()) - { - auto it = ConfigFuncDictionary.find(child->Name()); - if (it == ConfigFuncDictionary.end()) - { - fprintf(stderr, "Unsupported configuration variable: %s\n", child->Name()); - continue; - } - - std::invoke(it->second, *this, *child); - } -} diff --git a/tools/ZAPD/ZAPD/GameConfig.h b/tools/ZAPD/ZAPD/GameConfig.h deleted file mode 100644 index 4f3b91f8c7..0000000000 --- a/tools/ZAPD/ZAPD/GameConfig.h +++ /dev/null @@ -1,97 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -#include "Utils/Directory.h" -#include "tinyxml2.h" - -struct TexturePoolEntry -{ - fs::path path = ""; // Path to Shared Texture -}; - -class ExternalFile -{ -public: - fs::path xmlPath, outPath; - - ExternalFile(fs::path nXmlPath, fs::path nOutPath); -}; - -// Stores data from the XML file, the integer is the index (via ATOI) and the string is the value -class EnumData -{ -public: - // Common - std::map cutsceneCmd; - std::map miscType; - std::map fadeOutSeqPlayer; - std::map transitionType; - std::map naviQuestHintType; - std::map ocarinaSongActionId; - std::map seqId; - - // OoT - std::map textType; - std::map destination; - std::map playerCueId; - - // MM - std::map modifySeqType; - std::map chooseCreditsSceneType; - std::map destinationType; - std::map motionBlurType; - std::map transitionGeneralType; - std::map rumbleType; - std::map spawnFlag; - std::map endSfx; - std::map interpType; - std::map relTo; -}; - -class ZFile; - -class GameConfig -{ -public: - std::string configFilePath; - std::map> segmentRefFiles; - std::map symbolMap; - std::vector actorList; - std::vector objectList; - std::vector entranceList; - std::vector specialEntranceList; - std::map texturePool; // Key = CRC - EnumData enumData; - - // ZBackground - uint32_t bgScreenWidth = 320, bgScreenHeight = 240; - bool useScreenWidthHeightConstants = true; // If true, ZBackground's will be declared with - // SCREEN_WIDTH * SCREEN_HEIGHT in the C file - - // ExternalFile - fs::path externalXmlFolder; - std::vector externalFiles; - - GameConfig() = default; - ~GameConfig(); - - void ReadTexturePool(const fs::path& texturePoolXmlPath); - void GenSymbolMap(const fs::path& symbolMapPath); - - void ConfigFunc_SymbolMap(const tinyxml2::XMLElement& element); - void ConfigFunc_ActorList(const tinyxml2::XMLElement& element); - void ConfigFunc_ObjectList(const tinyxml2::XMLElement& element); - void ConfigFunc_EntranceList(const tinyxml2::XMLElement& element); - void ConfigFunc_specialEntranceList(const tinyxml2::XMLElement& element); - void ConfigFunc_TexturePool(const tinyxml2::XMLElement& element); - void ConfigFunc_BGConfig(const tinyxml2::XMLElement& element); - void ConfigFunc_ExternalXMLFolder(const tinyxml2::XMLElement& element); - void ConfigFunc_ExternalFile(const tinyxml2::XMLElement& element); - void ConfigFunc_EnumData(const tinyxml2::XMLElement& element); - - void ReadConfigFile(const fs::path& configFilePath); -}; diff --git a/tools/ZAPD/ZAPD/Globals.cpp b/tools/ZAPD/ZAPD/Globals.cpp deleted file mode 100644 index 02380f6902..0000000000 --- a/tools/ZAPD/ZAPD/Globals.cpp +++ /dev/null @@ -1,246 +0,0 @@ -#include "Globals.h" - -#include -#include - -#include "Utils/File.h" -#include "Utils/Path.h" -#include "WarningHandler.h" -#include "tinyxml2.h" - -Globals* Globals::Instance; - -Globals::Globals() -{ - Instance = this; - - game = ZGame::OOT_RETAIL; - genSourceFile = true; - testMode = false; - profile = false; - useLegacyZDList = false; - useExternalResources = true; - verbosity = VerbosityLevel::VERBOSITY_SILENT; - outputPath = Directory::GetCurrentDirectory(); -} - -Globals::~Globals() -{ - auto& exporters = GetExporterMap(); - - for (auto& it : exporters) - { - delete it.second; - } -} - -void Globals::AddSegment(int32_t segment, ZFile* file) -{ - if (std::find(segments.begin(), segments.end(), segment) == segments.end()) - segments.push_back(segment); - if (cfg.segmentRefFiles.find(segment) == cfg.segmentRefFiles.end()) - cfg.segmentRefFiles[segment] = std::vector(); - - cfg.segmentRefFiles[segment].push_back(file); -} - -bool Globals::HasSegment(int32_t segment) -{ - return std::find(segments.begin(), segments.end(), segment) != segments.end(); -} - -std::map& Globals::GetExporterMap() -{ - static std::map exporters; - return exporters; -} - -void Globals::AddExporter(std::string exporterName, ExporterSet* exporterSet) -{ - auto& exporters = GetExporterMap(); - exporters[exporterName] = exporterSet; -} - -ZResourceExporter* Globals::GetExporter(ZResourceType resType) -{ - auto& exporters = GetExporterMap(); - - if (currentExporter != "" && exporters[currentExporter]->exporters.find(resType) != - exporters[currentExporter]->exporters.end()) - return exporters[currentExporter]->exporters[resType]; - else - return nullptr; -} - -ExporterSet* Globals::GetExporterSet() -{ - auto& exporters = GetExporterMap(); - - if (currentExporter != "") - return exporters[currentExporter]; - else - return nullptr; -} - -bool Globals::GetSegmentedPtrName(segptr_t segAddress, ZFile* currentFile, - const std::string& expectedType, std::string& declName, - bool warnIfNotFound) -{ - if (segAddress == SEGMENTED_NULL) - { - declName = "NULL"; - return true; - } - - uint8_t segment = GETSEGNUM(segAddress); - uint32_t offset = Seg2Filespace(segAddress, currentFile->baseAddress); - ZSymbol* sym; - - sym = currentFile->GetSymbolResource(offset); - if (sym != nullptr) - { - if (expectedType == "" || expectedType == sym->GetSourceTypeName()) - { - declName = sym->GetName(); - return true; - } - } - sym = currentFile->GetSymbolResource(segAddress); - if (sym != nullptr) - { - if (expectedType == "" || expectedType == sym->GetSourceTypeName()) - { - declName = sym->GetName(); - return true; - } - } - - if (currentFile->IsSegmentedInFilespaceRange(segAddress)) - { - if (currentFile->GetDeclarationPtrName(segAddress, expectedType, declName)) - return true; - } - else if (HasSegment(segment)) - { - for (auto file : cfg.segmentRefFiles[segment]) - { - offset = Seg2Filespace(segAddress, file->baseAddress); - - sym = file->GetSymbolResource(offset); - if (sym != nullptr) - { - if (expectedType == "" || expectedType == sym->GetSourceTypeName()) - { - declName = sym->GetName(); - return true; - } - } - sym = file->GetSymbolResource(segAddress); - if (sym != nullptr) - { - if (expectedType == "" || expectedType == sym->GetSourceTypeName()) - { - declName = sym->GetName(); - return true; - } - } - - if (file->IsSegmentedInFilespaceRange(segAddress)) - { - if (file->GetDeclarationPtrName(segAddress, expectedType, declName)) - return true; - } - } - } - - const auto& symbolFromMap = Globals::Instance->cfg.symbolMap.find(segAddress); - if (symbolFromMap != Globals::Instance->cfg.symbolMap.end()) - { - declName = "&" + symbolFromMap->second; - return true; - } - - declName = StringHelper::Sprintf("0x%08X", segAddress); - if (warnIfNotFound) - { - WarnHardcodedPointer(segAddress, currentFile, nullptr, -1); - } - return false; -} - -bool Globals::GetSegmentedArrayIndexedName(segptr_t segAddress, size_t elementSize, - ZFile* currentFile, const std::string& expectedType, - std::string& declName, bool warnIfNotFound) -{ - if (segAddress == SEGMENTED_NULL) - { - declName = "NULL"; - return true; - } - - uint8_t segment = GETSEGNUM(segAddress); - - if (currentFile->IsSegmentedInFilespaceRange(segAddress)) - { - bool addressFound = currentFile->GetDeclarationArrayIndexedName(segAddress, elementSize, - expectedType, declName); - if (addressFound) - return true; - } - else if (HasSegment(segment)) - { - for (auto file : cfg.segmentRefFiles[segment]) - { - if (file->IsSegmentedInFilespaceRange(segAddress)) - { - bool addressFound = file->GetDeclarationArrayIndexedName(segAddress, elementSize, - expectedType, declName); - if (addressFound) - return true; - } - } - } - - declName = StringHelper::Sprintf("0x%08X", segAddress); - if (warnIfNotFound) - { - WarnHardcodedPointer(segAddress, currentFile, nullptr, -1); - } - return false; -} - -void Globals::WarnHardcodedPointer(segptr_t segAddress, ZFile* currentFile, ZResource* res, - offset_t currentOffset) -{ - uint8_t segment = GETSEGNUM(segAddress); - - if ((segment >= 2 && segment <= 6) || segment == 0x80) - { - std::string errorHeader = "A hardcoded pointer was found"; - std::string errorBody = StringHelper::Sprintf("Pointer: 0x%08X", segAddress); - - HANDLE_WARNING_RESOURCE(WarningType::HardcodedPointer, currentFile, res, currentOffset, - errorHeader, errorBody); - } - else - { - std::string errorHeader = "A general purpose hardcoded pointer was found"; - std::string errorBody = StringHelper::Sprintf("Pointer: 0x%08X", segAddress); - - HANDLE_WARNING_RESOURCE(WarningType::HardcodedGenericPointer, currentFile, res, - currentOffset, errorHeader, errorBody); - } -} - -ExternalFile::ExternalFile(fs::path nXmlPath, fs::path nOutPath) - : xmlPath{nXmlPath}, outPath{nOutPath} -{ -} - -ExporterSet::~ExporterSet() -{ - for (auto& it : exporters) - { - delete it.second; - } -} diff --git a/tools/ZAPD/ZAPD/Globals.h b/tools/ZAPD/ZAPD/Globals.h deleted file mode 100644 index 2cc9c2d4db..0000000000 --- a/tools/ZAPD/ZAPD/Globals.h +++ /dev/null @@ -1,90 +0,0 @@ -#pragma once - -#include -#include -#include -#include "GameConfig.h" -#include "ZFile.h" -#include "ExporterSet.h" - -class ZRoom; - -enum class VerbosityLevel -{ - VERBOSITY_SILENT, - VERBOSITY_INFO, - VERBOSITY_DEBUG -}; - -enum class CsFloatType -{ - HexOnly, - FloatOnly, - HexAndFloat, - HexAndCommentedFloatLeft, - HexAndCommentedFloatRight, -}; - -class Globals -{ -public: - static Globals* Instance; - - bool genSourceFile; // Used for extraction - bool useExternalResources; - bool testMode; // Enables certain experimental features - bool outputCrc = false; - bool profile; // Measure performance of certain operations - bool useLegacyZDList; - VerbosityLevel verbosity; // ZAPD outputs additional information - ZFileMode fileMode; - fs::path baseRomPath, inputPath, outputPath, sourceOutputPath, cfgPath; - TextureType texType; - CsFloatType floatType = CsFloatType::FloatOnly; - int64_t baseAddress = -1; - int64_t startOffset = -1; - int64_t endOffset = -1; - ZGame game; - GameConfig cfg; - bool verboseUnaccounted = false; - bool gccCompat = false; - bool forceStatic = false; - bool forceUnaccountedStatic = false; - - std::vector files; - std::vector externalFiles; - std::vector segments; - - std::string currentExporter; - static std::map& GetExporterMap(); - static void AddExporter(std::string exporterName, ExporterSet* exporterSet); - - Globals(); - ~Globals(); - - void AddSegment(int32_t segment, ZFile* file); - bool HasSegment(int32_t segment); - - ZResourceExporter* GetExporter(ZResourceType resType); - ExporterSet* GetExporterSet(); - - /** - * Search in every file (and the symbol map) for the `segAddress` passed as parameter. - * If the segment of `currentFile` is the same segment of `segAddress`, then that file will be - * used only, otherwise, the search will be performed in every other file. - * The name of that variable will be stored in the `declName` parameter. - * Returns `true` if the address is found. `false` otherwise, - * in which case `declName` will be set to the address formatted as a pointer. - */ - bool GetSegmentedPtrName(segptr_t segAddress, ZFile* currentFile, - const std::string& expectedType, std::string& declName, - bool warnIfNotFound = true); - - bool GetSegmentedArrayIndexedName(segptr_t segAddress, size_t elementSize, ZFile* currentFile, - const std::string& expectedType, std::string& declName, - bool warnIfNotFound = true); - - // TODO: consider moving to another place - void WarnHardcodedPointer(segptr_t segAddress, ZFile* currentFile, ZResource* res, - offset_t currentOffset); -}; diff --git a/tools/ZAPD/ZAPD/ImageBackend.cpp b/tools/ZAPD/ZAPD/ImageBackend.cpp deleted file mode 100644 index 307945b40e..0000000000 --- a/tools/ZAPD/ZAPD/ImageBackend.cpp +++ /dev/null @@ -1,506 +0,0 @@ -#include "ImageBackend.h" - -#include -#include -#include -#include - -#include "Utils/StringHelper.h" -#include "WarningHandler.h" - -/* ImageBackend */ - -ImageBackend::~ImageBackend() -{ - FreeImageData(); -} - -void ImageBackend::ReadPng(const char* filename) -{ - FreeImageData(); - - FILE* fp = fopen(filename, "rb"); - if (fp == nullptr) - { - std::string errorHeader = StringHelper::Sprintf("could not open file '%s'", filename); - HANDLE_ERROR(WarningType::InvalidPNG, errorHeader, ""); - } - - png_structp png = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr); - if (png == nullptr) - { - HANDLE_ERROR(WarningType::InvalidPNG, "could not create png struct", ""); - } - - png_infop info = png_create_info_struct(png); - if (info == nullptr) - { - HANDLE_ERROR(WarningType::InvalidPNG, "could not create png info", ""); - } - - if (setjmp(png_jmpbuf(png))) - { - // TODO: better warning explanation - HANDLE_ERROR(WarningType::InvalidPNG, "setjmp(png_jmpbuf(png))", ""); - } - - png_init_io(png, fp); - - png_read_info(png, info); - - width = png_get_image_width(png, info); - height = png_get_image_height(png, info); - colorType = png_get_color_type(png, info); - bitDepth = png_get_bit_depth(png, info); - -#ifdef TEXTURE_DEBUG - printf("Width: %u\n", width); - printf("Height: %u\n", height); - printf("ColorType: "); - switch (colorType) - { - case PNG_COLOR_TYPE_RGBA: - printf("PNG_COLOR_TYPE_RGBA\n"); - break; - - case PNG_COLOR_TYPE_RGB: - printf("PNG_COLOR_TYPE_RGB\n"); - break; - - case PNG_COLOR_TYPE_PALETTE: - printf("PNG_COLOR_TYPE_PALETTE\n"); - break; - - default: - printf("%u\n", colorType); - break; - } - printf("BitDepth: %u\n", bitDepth); - printf("\n"); -#endif - - // Read any color_type into 8bit depth, RGBA format. - // See http://www.libpng.org/pub/png/libpng-manual.txt - - if (bitDepth == 16) - png_set_strip_16(png); - - if (colorType == PNG_COLOR_TYPE_PALETTE) - { - // png_set_palette_to_rgb(png); - isColorIndexed = true; - } - - // PNG_COLOR_TYPE_GRAY_ALPHA is always 8 or 16bit depth. - if (colorType == PNG_COLOR_TYPE_GRAY && bitDepth < 8) - png_set_expand_gray_1_2_4_to_8(png); - - /*if (png_get_valid(png, info, PNG_INFO_tRNS)) - png_set_tRNS_to_alpha(png);*/ - - // These color_type don't have an alpha channel then fill it with 0xff. - /*if(*color_type == PNG_COLOR_TYPE_RGB || - *color_type == PNG_COLOR_TYPE_GRAY || - *color_type == PNG_COLOR_TYPE_PALETTE) - png_set_filler(png, 0xFF, PNG_FILLER_AFTER);*/ - - if (colorType == PNG_COLOR_TYPE_GRAY || colorType == PNG_COLOR_TYPE_GRAY_ALPHA) - png_set_gray_to_rgb(png); - - png_read_update_info(png, info); - - size_t rowBytes = png_get_rowbytes(png, info); - pixelMatrix = (uint8_t**)malloc(sizeof(uint8_t*) * height); - for (size_t y = 0; y < height; y++) - { - pixelMatrix[y] = (uint8_t*)malloc(rowBytes); - } - - png_read_image(png, pixelMatrix); - -#ifdef TEXTURE_DEBUG - printf("rowBytes: %zu\n", rowBytes); - - size_t bytePerPixel = GetBytesPerPixel(); - printf("imgData\n"); - for (size_t y = 0; y < height; y++) - { - for (size_t x = 0; x < width; x++) - { - for (size_t z = 0; z < bytePerPixel; z++) - { - printf("%02X ", pixelMatrix[y][x * bytePerPixel + z]); - } - printf(" "); - } - printf("\n"); - } - printf("\n"); -#endif - - fclose(fp); - - png_destroy_read_struct(&png, &info, nullptr); - - hasImageData = true; -} - -void ImageBackend::ReadPng(const fs::path& filename) -{ - ReadPng(filename.c_str()); -} - -void ImageBackend::WritePng(const char* filename) -{ - assert(hasImageData); - - FILE* fp = fopen(filename, "wb"); - if (fp == nullptr) - { - std::string errorHeader = - StringHelper::Sprintf("could not open file '%s' in write mode", filename); - HANDLE_ERROR(WarningType::InvalidPNG, errorHeader, ""); - } - - png_structp png = png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr); - if (png == nullptr) - { - HANDLE_ERROR(WarningType::InvalidPNG, "could not create png struct", ""); - } - - png_infop info = png_create_info_struct(png); - if (info == nullptr) - { - HANDLE_ERROR(WarningType::InvalidPNG, "could not create png info", ""); - } - - if (setjmp(png_jmpbuf(png))) - { - // TODO: better warning description - HANDLE_ERROR(WarningType::InvalidPNG, "setjmp(png_jmpbuf(png))", ""); - } - - png_init_io(png, fp); - - png_set_IHDR(png, info, width, height, - bitDepth, // 8, - colorType, // PNG_COLOR_TYPE_RGBA, - PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT); - - if (isColorIndexed) - { - png_set_PLTE(png, info, static_cast(colorPalette), paletteSize); - -#ifdef TEXTURE_DEBUG - printf("palette\n"); - png_color* aux = (png_color*)colorPalette; - for (size_t y = 0; y < paletteSize; y++) - { - printf("#%02X%02X%02X ", aux[y].red, aux[y].green, aux[y].blue); - if ((y + 1) % 8 == 0) - printf("\n"); - } - printf("\n"); -#endif - - png_set_tRNS(png, info, alphaPalette, paletteSize, nullptr); - } - - png_write_info(png, info); - - // To remove the alpha channel for PNG_COLOR_TYPE_RGB format, - // Use png_set_filler(). - // png_set_filler(png, 0, PNG_FILLER_AFTER); - -#ifdef TEXTURE_DEBUG - size_t bytePerPixel = GetBytesPerPixel(); - printf("imgData\n"); - for (size_t y = 0; y < height; y++) - { - for (size_t x = 0; x < width * bytePerPixel; x++) - { - printf("%02X ", pixelMatrix[y][x]); - } - printf("\n"); - } - printf("\n"); -#endif - - png_write_image(png, pixelMatrix); - png_write_end(png, nullptr); - - fclose(fp); - - png_destroy_write_struct(&png, &info); -} - -void ImageBackend::WritePng(const fs::path& filename) -{ - // Note: The .string() is necessary for MSVC, due to the implementation of std::filesystem - // differing from GCC. Do not remove! - WritePng(filename.string().c_str()); -} - -void ImageBackend::SetTextureData(const std::vector>& texData, - uint32_t nWidth, uint32_t nHeight, uint8_t nColorType, - uint8_t nBitDepth) -{ - FreeImageData(); - - width = nWidth; - height = nHeight; - colorType = nColorType; - bitDepth = nBitDepth; - - size_t bytePerPixel = GetBytesPerPixel(); - - pixelMatrix = static_cast(malloc(sizeof(uint8_t*) * height)); - for (size_t y = 0; y < height; y++) - { - pixelMatrix[y] = static_cast(malloc(sizeof(uint8_t*) * width * bytePerPixel)); - for (size_t x = 0; x < width; x++) - { - pixelMatrix[y][x * bytePerPixel + 0] = texData.at(y).at(x).r; - pixelMatrix[y][x * bytePerPixel + 1] = texData.at(y).at(x).g; - pixelMatrix[y][x * bytePerPixel + 2] = texData.at(y).at(x).b; - - if (colorType == PNG_COLOR_TYPE_RGBA) - pixelMatrix[y][x * bytePerPixel + 3] = texData.at(y).at(x).a; - } - } - hasImageData = true; -} - -void ImageBackend::InitEmptyRGBImage(uint32_t nWidth, uint32_t nHeight, bool alpha) -{ - FreeImageData(); - - width = nWidth; - height = nHeight; - colorType = PNG_COLOR_TYPE_RGB; - if (alpha) - colorType = PNG_COLOR_TYPE_RGBA; - bitDepth = 8; // nBitDepth; - - size_t bytePerPixel = GetBytesPerPixel(); - - pixelMatrix = static_cast(malloc(sizeof(uint8_t*) * height)); - for (size_t y = 0; y < height; y++) - { - pixelMatrix[y] = static_cast(calloc(width * bytePerPixel, sizeof(uint8_t*))); - } - - hasImageData = true; -} - -void ImageBackend::InitEmptyPaletteImage(uint32_t nWidth, uint32_t nHeight) -{ - FreeImageData(); - - width = nWidth; - height = nHeight; - colorType = PNG_COLOR_TYPE_PALETTE; - bitDepth = 8; - - size_t bytePerPixel = GetBytesPerPixel(); - - pixelMatrix = (uint8_t**)malloc(sizeof(uint8_t*) * height); - for (size_t y = 0; y < height; y++) - { - pixelMatrix[y] = static_cast(calloc(width * bytePerPixel, sizeof(uint8_t*))); - } - colorPalette = calloc(paletteSize, sizeof(png_color)); - alphaPalette = static_cast(calloc(paletteSize, sizeof(uint8_t))); - - hasImageData = true; - isColorIndexed = true; -} - -RGBAPixel ImageBackend::GetPixel(size_t y, size_t x) const -{ - assert(y < height); - assert(x < width); - assert(!isColorIndexed); - - RGBAPixel pixel; - size_t bytePerPixel = GetBytesPerPixel(); - pixel.r = pixelMatrix[y][x * bytePerPixel + 0]; - pixel.g = pixelMatrix[y][x * bytePerPixel + 1]; - pixel.b = pixelMatrix[y][x * bytePerPixel + 2]; - if (colorType == PNG_COLOR_TYPE_RGBA) - pixel.a = pixelMatrix[y][x * bytePerPixel + 3]; - return pixel; -} - -uint8_t ImageBackend::GetIndexedPixel(size_t y, size_t x) const -{ - assert(y < height); - assert(x < width); - assert(isColorIndexed); - - return pixelMatrix[y][x]; -} - -void ImageBackend::SetRGBPixel(size_t y, size_t x, uint8_t nR, uint8_t nG, uint8_t nB, uint8_t nA) -{ - assert(hasImageData); - assert(y < height); - assert(x < width); - - size_t bytePerPixel = GetBytesPerPixel(); - pixelMatrix[y][x * bytePerPixel + 0] = nR; - pixelMatrix[y][x * bytePerPixel + 1] = nG; - pixelMatrix[y][x * bytePerPixel + 2] = nB; - if (colorType == PNG_COLOR_TYPE_RGBA) - pixelMatrix[y][x * bytePerPixel + 3] = nA; -} - -void ImageBackend::SetGrayscalePixel(size_t y, size_t x, uint8_t grayscale, uint8_t alpha) -{ - assert(hasImageData); - assert(y < height); - assert(x < width); - - size_t bytePerPixel = GetBytesPerPixel(); - pixelMatrix[y][x * bytePerPixel + 0] = grayscale; - pixelMatrix[y][x * bytePerPixel + 1] = grayscale; - pixelMatrix[y][x * bytePerPixel + 2] = grayscale; - if (colorType == PNG_COLOR_TYPE_RGBA) - pixelMatrix[y][x * bytePerPixel + 3] = alpha; -} - -void ImageBackend::SetIndexedPixel(size_t y, size_t x, uint8_t index, uint8_t grayscale) -{ - assert(hasImageData); - assert(y < height); - assert(x < width); - - size_t bytePerPixel = GetBytesPerPixel(); - pixelMatrix[y][x * bytePerPixel + 0] = index; - - assert(index < paletteSize); - png_color* pal = static_cast(colorPalette); - pal[index].red = grayscale; - pal[index].green = grayscale; - pal[index].blue = grayscale; - alphaPalette[index] = 255; -} - -void ImageBackend::SetPaletteIndex(size_t index, uint8_t nR, uint8_t nG, uint8_t nB, uint8_t nA) -{ - assert(isColorIndexed); - assert(index < paletteSize); - - png_color* pal = static_cast(colorPalette); - pal[index].red = nR; - pal[index].green = nG; - pal[index].blue = nB; - alphaPalette[index] = nA; -} - -void ImageBackend::SetPalette(const ImageBackend& pal, uint32_t offset) -{ - assert(isColorIndexed); - size_t bytePerPixel = pal.GetBytesPerPixel(); - - for (size_t y = 0; y < pal.height; y++) - { - for (size_t x = 0; x < pal.width; x++) - { - size_t index = y * pal.width + x; - if (index >= paletteSize) - { - /* - * Some TLUTs are bigger than 256 colors. - * For those cases, we will only take the first 256 - * to colorize this CI texture. - */ - return; - } - - uint8_t r = pal.pixelMatrix[y][x * bytePerPixel + 0]; - uint8_t g = pal.pixelMatrix[y][x * bytePerPixel + 1]; - uint8_t b = pal.pixelMatrix[y][x * bytePerPixel + 2]; - uint8_t a = pal.pixelMatrix[y][x * bytePerPixel + 3]; - SetPaletteIndex(index + offset, r, g, b, a); - } - } -} - -uint32_t ImageBackend::GetWidth() const -{ - return width; -} - -uint32_t ImageBackend::GetHeight() const -{ - return height; -} - -uint8_t ImageBackend::GetColorType() const -{ - return colorType; -} - -uint8_t ImageBackend::GetBitDepth() const -{ - return bitDepth; -} - -double ImageBackend::GetBytesPerPixel() const -{ - switch (colorType) - { - case PNG_COLOR_TYPE_RGBA: - return 4 * bitDepth / 8; - - case PNG_COLOR_TYPE_RGB: - return 3 * bitDepth / 8; - - case PNG_COLOR_TYPE_PALETTE: - return 1 * bitDepth / 8; - - default: - HANDLE_ERROR(WarningType::InvalidPNG, "invalid color type", ""); - } -} - -void ImageBackend::FreeImageData() -{ - if (hasImageData) - { - for (size_t y = 0; y < height; y++) - free(pixelMatrix[y]); - free(pixelMatrix); - pixelMatrix = nullptr; - } - - if (isColorIndexed) - { - free(colorPalette); - free(alphaPalette); - colorPalette = nullptr; - alphaPalette = nullptr; - isColorIndexed = false; - } - - hasImageData = false; -} - -/* RGBAPixel */ - -void RGBAPixel::SetRGBA(uint8_t nR, uint8_t nG, uint8_t nB, uint8_t nA) -{ - r = nR; - g = nG; - b = nB; - a = nA; -} - -void RGBAPixel::SetGrayscale(uint8_t grayscale, uint8_t alpha) -{ - r = grayscale; - g = grayscale; - b = grayscale; - a = alpha; -} diff --git a/tools/ZAPD/ZAPD/ImageBackend.h b/tools/ZAPD/ZAPD/ImageBackend.h deleted file mode 100644 index 0b1f4806c0..0000000000 --- a/tools/ZAPD/ZAPD/ImageBackend.h +++ /dev/null @@ -1,72 +0,0 @@ -#pragma once - -#include -#include - -#include "Utils/Directory.h" - -class RGBAPixel -{ -public: - RGBAPixel() = default; - - void SetRGBA(uint8_t nR, uint8_t nG, uint8_t nB, uint8_t nA); - void SetGrayscale(uint8_t grayscale, uint8_t alpha = 0); - - uint8_t r = 0; - uint8_t g = 0; - uint8_t b = 0; - uint8_t a = 0; -}; - -class ImageBackend -{ -public: - ImageBackend() = default; - ~ImageBackend(); - - void ReadPng(const char* filename); - void ReadPng(const fs::path& filename); - void WritePng(const char* filename); - void WritePng(const fs::path& filename); - - void SetTextureData(const std::vector>& texData, uint32_t nWidth, - uint32_t nHeight, uint8_t nColorType, uint8_t nBitDepth); - void InitEmptyRGBImage(uint32_t nWidth, uint32_t nHeight, bool alpha); - void InitEmptyPaletteImage(uint32_t nWidth, uint32_t nHeight); - - RGBAPixel GetPixel(size_t y, size_t x) const; - uint8_t GetIndexedPixel(size_t y, size_t x) const; - - void SetRGBPixel(size_t y, size_t x, uint8_t nR, uint8_t nG, uint8_t nB, uint8_t nA = 0); - void SetGrayscalePixel(size_t y, size_t x, uint8_t grayscale, uint8_t alpha = 0); - - void SetIndexedPixel(size_t y, size_t x, uint8_t index, uint8_t grayscale); - void SetIndexedPixel(size_t y, size_t x, uint8_t index, RGBAPixel pixel); - void SetPaletteIndex(size_t index, uint8_t nR, uint8_t nG, uint8_t nB, uint8_t nA); - void SetPalette(const ImageBackend& pal, uint32_t offset = 0); - - uint32_t GetWidth() const; - uint32_t GetHeight() const; - uint8_t GetColorType() const; - uint8_t GetBitDepth() const; - -protected: - uint8_t** pixelMatrix = nullptr; // height * [width * bytePerPixel] - - void* colorPalette = nullptr; - uint8_t* alphaPalette = nullptr; - size_t paletteSize = 16 * 16; - - uint32_t width = 0; - uint32_t height = 0; - uint8_t colorType = 0; - uint8_t bitDepth = 0; - - bool hasImageData = false; - bool isColorIndexed = false; - - double GetBytesPerPixel() const; - - void FreeImageData(); -}; diff --git a/tools/ZAPD/ZAPD/Main.cpp b/tools/ZAPD/ZAPD/Main.cpp deleted file mode 100644 index 19d10d7d96..0000000000 --- a/tools/ZAPD/ZAPD/Main.cpp +++ /dev/null @@ -1,532 +0,0 @@ -#include "Globals.h" -#include "Utils/Directory.h" -#include "Utils/File.h" -#include "Utils/Path.h" -#include "WarningHandler.h" -#include "ZAnimation.h" -#include "ZBackground.h" -#include "ZBlob.h" -#include "ZFile.h" -#include "ZTexture.h" - -#include -#include "CrashHandler.h" - -#include -#include -#include "tinyxml2.h" - -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_CsFloatMode(int& i, char* argv[]); -void Arg_BaseAddress(int& i, char* argv[]); -void Arg_StartOffset(int& i, char* argv[]); -void Arg_EndOffset(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); - -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); - -extern const char gBuildHash[]; - -int 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(); - 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; - } - - // 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->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) - 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); - - delete g; - return returnCode; -} - -bool Parse(const fs::path& xmlFilePath, const fs::path& basePath, const fs::path& outPath, - ZFileMode fileMode) -{ - 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); - Globals::Instance->files.push_back(file); - if (fileMode == ZFileMode::ExternalFile) - { - Globals::Instance->externalFiles.push_back(file); - 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); - } - 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(); - - for (ZFile* file : Globals::Instance->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 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}, - {"--cs-float", &Arg_CsFloatMode}, - {"--base-address", &Arg_BaseAddress}, - {"--start-offset", &Arg_StartOffset}, - {"--end-offset", &Arg_EndOffset}, - }; - - 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()); - 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 (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(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[]) -{ - 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_CsFloatMode([[maybe_unused]] int& i, [[maybe_unused]] char* argv[]) -{ - i++; - if (std::strcmp(argv[i], "hex") == 0) - { - Globals::Instance->floatType = CsFloatType::HexOnly; - } - else if (std::strcmp(argv[i], "float") == 0) - { - Globals::Instance->floatType = CsFloatType::FloatOnly; - } - else if (std::strcmp(argv[i], "both") == 0) - { - Globals::Instance->floatType = CsFloatType::HexAndFloat; - } - else if (std::strcmp(argv[i], "hex-commented-left") == 0) - { - Globals::Instance->floatType = CsFloatType::HexAndCommentedFloatLeft; - } - else if (std::strcmp(argv[i], "hex-commented-right") == 0) - { - Globals::Instance->floatType = CsFloatType::HexAndCommentedFloatRight; - } - else - { - Globals::Instance->floatType = CsFloatType::FloatOnly; - HANDLE_WARNING( - WarningType::Always, "Invalid CS Float Type", - StringHelper::Sprintf("Invalid CS float type entered. Expected \"hex\", \"float\", " - "\"both\", \"hex-commented-left\" or \"hex-commented-right\". " - "Got %s.\n Defaulting to \"float\".", - argv[i])); - } -} - -uint32_t ParseU32Hex(char* str) -{ - static_assert(sizeof(uint32_t) <= sizeof(unsigned long)); - return (uint32_t)std::stoul(str, nullptr, 16); -} - -void Arg_BaseAddress(int& i, char* argv[]) -{ - Globals::Instance->baseAddress = ParseU32Hex(argv[++i]); -} - -void Arg_StartOffset(int& i, char* argv[]) -{ - Globals::Instance->startOffset = ParseU32Hex(argv[++i]); -} - -void Arg_EndOffset(int& i, char* argv[]) -{ - Globals::Instance->endOffset = ParseU32Hex(argv[++i]); -} - -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) - { - 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); - - if (!parseSuccessful) - return 1; - } - - parseSuccessful = Parse(Globals::Instance->inputPath, Globals::Instance->baseRomPath, - Globals::Instance->outputPath, fileMode); - if (!parseSuccessful) - return 1; - } - - return 0; -} - -void BuildAssetTexture(const fs::path& pngFilePath, TextureType texType, const fs::path& outPath) -{ - std::string name = outPath.stem().string(); - - ZTexture tex(nullptr); - - if (name.find("u32") != std::string::npos) - tex.dWordAligned = false; - - tex.FromPNG(pngFilePath.string(), texType); - std::string cfgPath = StringHelper::Split(pngFilePath.string(), ".")[0] + ".cfg"; - - if (File::Exists(cfgPath)) - name = File::ReadAllText(cfgPath); - - std::string src = tex.GetBodySourceCode(); - - File::WriteAllText(outPath.string(), src); -} - -void BuildAssetBackground(const fs::path& imageFilePath, const fs::path& outPath) -{ - ZBackground background(nullptr); - background.ParseBinaryFile(imageFilePath.string(), false); - - File::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(); - - File::WriteAllText(outPath.string(), src); - - delete blob; -} diff --git a/tools/ZAPD/ZAPD/NuGet/libpng.static.txt b/tools/ZAPD/ZAPD/NuGet/libpng.static.txt deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/tools/ZAPD/ZAPD/OtherStructs/CutsceneMM_Commands.cpp b/tools/ZAPD/ZAPD/OtherStructs/CutsceneMM_Commands.cpp deleted file mode 100644 index 960404e598..0000000000 --- a/tools/ZAPD/ZAPD/OtherStructs/CutsceneMM_Commands.cpp +++ /dev/null @@ -1,622 +0,0 @@ -#include "CutsceneMM_Commands.h" - -#include -#include "Globals.h" -#include "Utils/BitConverter.h" -#include "Utils/StringHelper.h" -#include "WarningHandler.h" - -#include "ZCutscene.h" - -/**** GENERIC ****/ - -// Specific for command lists where each entry has size 8 bytes -const std::unordered_map csCommandsDescMM = { - {CutsceneMM_CommandType::CS_CMD_MISC, {"CS_MISC", "(%s, %i, %i, %i)"}}, - {CutsceneMM_CommandType::CS_CMD_LIGHT_SETTING, {"CS_LIGHT_SETTING", "(0x%02X, %i, %i)"}}, - {CutsceneMM_CommandType::CS_CMD_TRANSITION, {"CS_TRANSITION", "(%s, %i, %i)"}}, - {CutsceneMM_CommandType::CS_CMD_MOTION_BLUR, {"CS_MOTION_BLUR", "(%s, %i, %i)"}}, - {CutsceneMM_CommandType::CS_CMD_GIVE_TATL, {"CS_GIVE_TATL", "(%s, %i, %i)"}}, - {CutsceneMM_CommandType::CS_CMD_START_SEQ, {"CS_START_SEQ", "(%s, %i, %i)"}}, - {CutsceneMM_CommandType::CS_CMD_SFX_REVERB_INDEX_2, - {"CS_SFX_REVERB_INDEX_2", "(0x%04X, %i, %i)"}}, - {CutsceneMM_CommandType::CS_CMD_SFX_REVERB_INDEX_1, - {"CS_SFX_REVERB_INDEX_1", "(0x%04X, %i, %i)"}}, - {CutsceneMM_CommandType::CS_CMD_MODIFY_SEQ, {"CS_MODIFY_SEQ", "(%s, %i, %i)"}}, - {CutsceneMM_CommandType::CS_CMD_STOP_SEQ, {"CS_STOP_SEQ", "(%s, %i, %i, %i)"}}, - {CutsceneMM_CommandType::CS_CMD_START_AMBIENCE, {"CS_START_AMBIENCE", "(0x%04X, %i, %i)"}}, - {CutsceneMM_CommandType::CS_CMD_FADE_OUT_AMBIENCE, - {"CS_FADE_OUT_AMBIENCE", "(0x%04X, %i, %i)"}}, - {CutsceneMM_CommandType::CS_CMD_DESTINATION, {"CS_DESTINATION", "(%s, %i, %i)"}}, - {CutsceneMM_CommandType::CS_CMD_CHOOSE_CREDITS_SCENES, - {"CS_CHOOSE_CREDITS_SCENES", "(%s, %i, %i)"}}, -}; - -CutsceneMMSubCommandEntry_GenericCmd::CutsceneMMSubCommandEntry_GenericCmd( - const std::vector& rawData, offset_t rawDataIndex, CutsceneMM_CommandType cmdId) - : CutsceneSubCommandEntry(rawData, rawDataIndex), commandId(cmdId) -{ -} - -std::string CutsceneMMSubCommandEntry_GenericCmd::GetBodySourceCode() const -{ - EnumData* enumData = &Globals::Instance->cfg.enumData; - const auto& element = csCommandsDescMM.find(commandId); - std::string entryFmt = "CS_UNK_DATA(0x%02X, %i, %i, %i)"; - std::string type = ""; - bool isIndexInSeqId = enumData->seqId.find(base - 1) != enumData->seqId.end(); - - if (element != csCommandsDescMM.end()) - { - entryFmt = element->second.cmdMacro; - entryFmt += element->second.args; - } - - if (commandId == CutsceneMM_CommandType::CS_CMD_MISC && - enumData->miscType.find(base) != enumData->miscType.end()) - type = enumData->miscType[base]; - - else if (commandId == CutsceneMM_CommandType::CS_CMD_TRANSITION && - enumData->transitionType.find(base) != enumData->transitionType.end()) - type = enumData->transitionType[base]; - - else if (commandId == CutsceneMM_CommandType::CS_CMD_MOTION_BLUR && - enumData->motionBlurType.find(base) != enumData->motionBlurType.end()) - type = enumData->motionBlurType[base]; - - else if (commandId == CutsceneMM_CommandType::CS_CMD_MODIFY_SEQ && - enumData->modifySeqType.find(base) != enumData->modifySeqType.end()) - type = enumData->modifySeqType[base]; - - else if (commandId == CutsceneMM_CommandType::CS_CMD_DESTINATION && - enumData->destinationType.find(base) != enumData->destinationType.end()) - type = enumData->destinationType[base]; - - else if (commandId == CutsceneMM_CommandType::CS_CMD_CHOOSE_CREDITS_SCENES && - enumData->chooseCreditsSceneType.find(base) != enumData->chooseCreditsSceneType.end()) - type = enumData->chooseCreditsSceneType[base]; - - else if ((commandId == CutsceneMM_CommandType::CS_CMD_START_SEQ || - commandId == CutsceneMM_CommandType::CS_CMD_STOP_SEQ) && - isIndexInSeqId) - type = enumData->seqId[base - 1]; - - else if (commandId == CutsceneMM_CommandType::CS_CMD_GIVE_TATL) - type = base ? "true" : "false"; - - if (type != "") - return StringHelper::Sprintf(entryFmt.c_str(), type.c_str(), startFrame, endFrame, pad); - - if (commandId == CutsceneMM_CommandType::CS_CMD_LIGHT_SETTING || - commandId == CutsceneMM_CommandType::CS_CMD_START_SEQ || - commandId == CutsceneMM_CommandType::CS_CMD_STOP_SEQ) - { - return StringHelper::Sprintf(entryFmt.c_str(), base - 1, startFrame, endFrame, pad); - } - - return StringHelper::Sprintf(entryFmt.c_str(), base, startFrame, endFrame, pad); -} - -CutsceneMMCommand_GenericCmd::CutsceneMMCommand_GenericCmd(const std::vector& rawData, - offset_t rawDataIndex, - CutsceneMM_CommandType cmdId) - : CutsceneCommand(rawData, rawDataIndex) -{ - rawDataIndex += 4; - - commandID = static_cast(cmdId); - - entries.reserve(numEntries); - for (size_t i = 0; i < numEntries; i++) - { - auto* entry = new CutsceneMMSubCommandEntry_GenericCmd(rawData, rawDataIndex, cmdId); - entries.push_back(entry); - rawDataIndex += entry->GetRawSize(); - } -} - -std::string CutsceneMMCommand_GenericCmd::GetCommandMacro() const -{ - const auto& element = csCommandsDescMM.find(static_cast(commandID)); - - if (element != csCommandsDescMM.end()) - { - return StringHelper::Sprintf("%s_LIST(%i)", element->second.cmdMacro, numEntries); - } - - return StringHelper::Sprintf("CS_UNK_DATA_LIST(0x%X, %i)", commandID, numEntries); -} - -/**** CAMERA ****/ - -CutsceneSubCommandEntry_SplineCamPoint::CutsceneSubCommandEntry_SplineCamPoint( - const std::vector& rawData, offset_t rawDataIndex) - : CutsceneSubCommandEntry(rawData, rawDataIndex) -{ - interpType = BitConverter::ToUInt8BE(rawData, rawDataIndex + 0); - weight = BitConverter::ToUInt8BE(rawData, rawDataIndex + 1); - duration = BitConverter::ToUInt16BE(rawData, rawDataIndex + 2); - posX = BitConverter::ToUInt16BE(rawData, rawDataIndex + 4); - posY = BitConverter::ToUInt16BE(rawData, rawDataIndex + 6); - posZ = BitConverter::ToUInt16BE(rawData, rawDataIndex + 8); - relTo = BitConverter::ToUInt16BE(rawData, rawDataIndex + 10); -} - -std::string CutsceneSubCommandEntry_SplineCamPoint::GetBodySourceCode() const -{ - const auto interpTypeMap = &Globals::Instance->cfg.enumData.interpType; - const auto relToMap = &Globals::Instance->cfg.enumData.relTo; - - return StringHelper::Sprintf("CS_CAM_POINT(%s, 0x%02X, 0x%04X, 0x%04X, 0x%04X, 0x%04X, %s)", - interpTypeMap->at(interpType).c_str(), weight, duration, posX, - posY, posZ, relToMap->at(relTo).c_str()); -} - -size_t CutsceneSubCommandEntry_SplineCamPoint::GetRawSize() const -{ - return 0x0C; -} - -CutsceneSubCommandEntry_SplineMiscPoint::CutsceneSubCommandEntry_SplineMiscPoint( - const std::vector& rawData, offset_t rawDataIndex) - : CutsceneSubCommandEntry(rawData, rawDataIndex) -{ - unused0 = BitConverter::ToUInt16BE(rawData, rawDataIndex + 0); - roll = BitConverter::ToUInt16BE(rawData, rawDataIndex + 2); - fov = BitConverter::ToUInt16BE(rawData, rawDataIndex + 4); - unused1 = BitConverter::ToUInt16BE(rawData, rawDataIndex + 6); -} - -std::string CutsceneSubCommandEntry_SplineMiscPoint::GetBodySourceCode() const -{ - return StringHelper::Sprintf("CS_CAM_MISC(0x%04X, 0x%04X, 0x%04X, 0x%04X)", unused0, roll, fov, - unused1); -} - -size_t CutsceneSubCommandEntry_SplineMiscPoint::GetRawSize() const -{ - return 0x08; -} - -CutsceneSubCommandEntry_SplineHeader::CutsceneSubCommandEntry_SplineHeader( - const std::vector& rawData, offset_t rawDataIndex) - : CutsceneSubCommandEntry(rawData, rawDataIndex) -{ - numEntries = BitConverter::ToUInt16BE(rawData, rawDataIndex + 0); - unused0 = BitConverter::ToUInt16BE(rawData, rawDataIndex + 2); - unused1 = BitConverter::ToUInt16BE(rawData, rawDataIndex + 4); - duration = BitConverter::ToUInt16BE(rawData, rawDataIndex + 6); -} - -std::string CutsceneSubCommandEntry_SplineHeader::GetBodySourceCode() const -{ - return StringHelper::Sprintf("CS_CAM_SPLINE(0x%04X, 0x%04X, 0x%04X, 0x%04X)", numEntries, - unused0, unused1, duration); -} - -size_t CutsceneSubCommandEntry_SplineHeader::GetRawSize() const -{ - return 0x08; -} - -CutsceneSubCommandEntry_SplineFooter::CutsceneSubCommandEntry_SplineFooter( - const std::vector& rawData, offset_t rawDataIndex) - : CutsceneSubCommandEntry(rawData, rawDataIndex) -{ - uint16_t firstHalfWord = BitConverter::ToUInt16BE(rawData, rawDataIndex); - uint16_t secondHalfWord = BitConverter::ToUInt16BE(rawData, rawDataIndex + 2); - - if (firstHalfWord != 0xFFFF || secondHalfWord != 4) - { - HANDLE_ERROR(WarningType::InvalidExtractedData, "Invalid Spline Footer", - StringHelper::Sprintf( - "Invalid Spline footer. Was expecting 0xFFFF, 0x0004. Got 0x%04X, 0x%04X", - firstHalfWord, secondHalfWord)); - } -} - -std::string CutsceneSubCommandEntry_SplineFooter::GetBodySourceCode() const -{ - return "CS_CAM_END()"; -} - -size_t CutsceneSubCommandEntry_SplineFooter::GetRawSize() const -{ - return 0x04; -} - -CutsceneMMCommand_Spline::CutsceneMMCommand_Spline(const std::vector& rawData, - offset_t rawDataIndex) - : CutsceneCommand(rawData, rawDataIndex) -{ - numHeaders = 0; - totalCommands = 0; - rawDataIndex += 4; - - while (1) - { - if (BitConverter::ToUInt16BE(rawData, rawDataIndex) == 0xFFFF) - { - break; - } - numHeaders++; - - auto* header = new CutsceneSubCommandEntry_SplineHeader(rawData, rawDataIndex); - rawDataIndex += header->GetRawSize(); - entries.push_back(header); - - totalCommands += header->numEntries; - - for (uint32_t i = 0; i < header->numEntries; i++) - { - auto* entry = new CutsceneSubCommandEntry_SplineCamPoint(rawData, rawDataIndex); - entries.push_back(entry); - rawDataIndex += entry->GetRawSize(); - } - - for (uint32_t i = 0; i < header->numEntries; i++) - { - auto* entry = new CutsceneSubCommandEntry_SplineCamPoint(rawData, rawDataIndex); - entries.push_back(entry); - rawDataIndex += entry->GetRawSize(); - } - - for (uint32_t i = 0; i < header->numEntries; i++) - { - auto* entry = new CutsceneSubCommandEntry_SplineMiscPoint(rawData, rawDataIndex); - entries.push_back(entry); - rawDataIndex += entry->GetRawSize(); - } - } - - auto* footer = new CutsceneSubCommandEntry_SplineFooter(rawData, rawDataIndex); - entries.push_back(footer); - rawDataIndex += footer->GetRawSize(); -} - -std::string CutsceneMMCommand_Spline::GetCommandMacro() const -{ - return StringHelper::Sprintf("CS_CAM_SPLINE_LIST(%i)", numEntries); -} - -size_t CutsceneMMCommand_Spline::GetCommandSize() const -{ - // 8 Bytes once for the spline command, 8 Bytes per spline the header, two groups of size 12, 1 - // group of size 8, 4 bytes for the footer. - return 8 + (8 * numHeaders) + ((totalCommands * 2) * 0xC) + (totalCommands * 8) + 4; -} - -/**** TRANSITION GENERAL ****/ - -CutsceneSubCommandEntry_TransitionGeneral::CutsceneSubCommandEntry_TransitionGeneral( - const std::vector& rawData, offset_t rawDataIndex) - : CutsceneSubCommandEntry(rawData, rawDataIndex) -{ - unk_06 = BitConverter::ToUInt8BE(rawData, rawDataIndex + 0x06); - unk_07 = BitConverter::ToUInt8BE(rawData, rawDataIndex + 0x07); - unk_08 = BitConverter::ToUInt8BE(rawData, rawDataIndex + 0x08); - unk_09 = BitConverter::ToUInt8BE(rawData, rawDataIndex + 0x09); - unk_0A = BitConverter::ToUInt8BE(rawData, rawDataIndex + 0x0A); - unk_0B = BitConverter::ToUInt8BE(rawData, rawDataIndex + 0x0B); -} - -std::string CutsceneSubCommandEntry_TransitionGeneral::GetBodySourceCode() const -{ - EnumData* enumData = &Globals::Instance->cfg.enumData; - - if (enumData->transitionGeneralType.find(base) != enumData->transitionGeneralType.end()) - return StringHelper::Sprintf("CS_TRANSITION_GENERAL(%s, %i, %i, %i, %i, %i)", - enumData->transitionGeneralType[base].c_str(), startFrame, - endFrame, unk_06, unk_07, unk_08); - - return StringHelper::Sprintf("CS_TRANSITION_GENERAL(0x%02X, %i, %i, %i, %i, %i)", base, - startFrame, endFrame, unk_06, unk_07, unk_08); -} - -size_t CutsceneSubCommandEntry_TransitionGeneral::GetRawSize() const -{ - return 0x0C; -} - -CutsceneMMCommand_TransitionGeneral::CutsceneMMCommand_TransitionGeneral( - const std::vector& rawData, offset_t rawDataIndex) - : CutsceneCommand(rawData, rawDataIndex) -{ - rawDataIndex += 4; - - entries.reserve(numEntries); - for (size_t i = 0; i < numEntries; i++) - { - auto* entry = new CutsceneSubCommandEntry_TransitionGeneral(rawData, rawDataIndex); - entries.push_back(entry); - rawDataIndex += entry->GetRawSize(); - } -} - -std::string CutsceneMMCommand_TransitionGeneral::GetCommandMacro() const -{ - return StringHelper::Sprintf("CS_TRANSITION_GENERAL_LIST(%i)", numEntries); -} - -CutsceneSubCommandEntry_FadeOutSeq::CutsceneSubCommandEntry_FadeOutSeq( - const std::vector& rawData, offset_t rawDataIndex) - : CutsceneSubCommandEntry(rawData, rawDataIndex) -{ - unk_08 = BitConverter::ToUInt32BE(rawData, rawDataIndex + 8); -} - -/**** FADE OUT SEQUENCE ****/ - -std::string CutsceneSubCommandEntry_FadeOutSeq::GetBodySourceCode() const -{ - EnumData* enumData = &Globals::Instance->cfg.enumData; - - if (enumData->fadeOutSeqPlayer.find(base) != enumData->fadeOutSeqPlayer.end()) - return StringHelper::Sprintf("CS_FADE_OUT_SEQ(%s, %i, %i)", - enumData->fadeOutSeqPlayer[base].c_str(), startFrame, - endFrame); - - return StringHelper::Sprintf("CS_FADE_OUT_SEQ(%i, %i, %i)", base, startFrame, endFrame); -} - -size_t CutsceneSubCommandEntry_FadeOutSeq::GetRawSize() const -{ - return 0x0C; -} - -CutsceneMMCommand_FadeOutSeq::CutsceneMMCommand_FadeOutSeq(const std::vector& rawData, - offset_t rawDataIndex) - : CutsceneCommand(rawData, rawDataIndex) -{ - rawDataIndex += 4; - - entries.reserve(numEntries); - for (size_t i = 0; i < numEntries; i++) - { - auto* entry = new CutsceneSubCommandEntry_FadeOutSeq(rawData, rawDataIndex); - entries.push_back(entry); - rawDataIndex += entry->GetRawSize(); - } -} - -std::string CutsceneMMCommand_FadeOutSeq::GetCommandMacro() const -{ - return StringHelper::Sprintf("CS_FADE_OUT_SEQ_LIST(%i)", numEntries); -} - -/**** NON IMPLEMENTED ****/ - -CutsceneSubCommandEntry_NonImplemented::CutsceneSubCommandEntry_NonImplemented( - const std::vector& rawData, offset_t rawDataIndex) - : CutsceneSubCommandEntry(rawData, rawDataIndex) -{ -} - -CutsceneMMCommand_NonImplemented::CutsceneMMCommand_NonImplemented( - const std::vector& rawData, offset_t rawDataIndex) - : CutsceneCommand(rawData, rawDataIndex) -{ - rawDataIndex += 4; - - entries.reserve(numEntries); - for (size_t i = 0; i < numEntries; i++) - { - auto* entry = new CutsceneSubCommandEntry_NonImplemented(rawData, rawDataIndex); - entries.push_back(entry); - rawDataIndex += entry->GetRawSize(); - } -} - -/**** RUMBLE ****/ - -CutsceneMMSubCommandEntry_Rumble::CutsceneMMSubCommandEntry_Rumble( - const std::vector& rawData, offset_t rawDataIndex) - : CutsceneSubCommandEntry(rawData, rawDataIndex) -{ - intensity = BitConverter::ToUInt8BE(rawData, rawDataIndex + 0x06); - decayTimer = BitConverter::ToUInt8BE(rawData, rawDataIndex + 0x07); - decayStep = BitConverter::ToUInt8BE(rawData, rawDataIndex + 0x08); -} - -std::string CutsceneMMSubCommandEntry_Rumble::GetBodySourceCode() const -{ - EnumData* enumData = &Globals::Instance->cfg.enumData; - - if (enumData->rumbleType.find(base) != enumData->rumbleType.end()) - return StringHelper::Sprintf("CS_RUMBLE(%s, %i, %i, 0x%02X, 0x%02X, 0x%02X)", - enumData->rumbleType[base].c_str(), startFrame, endFrame, - intensity, decayTimer, decayStep); - - return StringHelper::Sprintf("CS_RUMBLE(0x%04X, %i, %i, 0x%02X, 0x%02X, 0x%02X)", base, - startFrame, endFrame, intensity, decayTimer, decayStep); -} - -size_t CutsceneMMSubCommandEntry_Rumble::GetRawSize() const -{ - return 0x0C; -} - -CutsceneMMCommand_Rumble::CutsceneMMCommand_Rumble(const std::vector& rawData, - offset_t rawDataIndex) - : CutsceneCommand(rawData, rawDataIndex) -{ - rawDataIndex += 4; - - entries.reserve(numEntries); - for (size_t i = 0; i < numEntries; i++) - { - auto* entry = new CutsceneMMSubCommandEntry_Rumble(rawData, rawDataIndex); - entries.push_back(entry); - rawDataIndex += entry->GetRawSize(); - } -} - -std::string CutsceneMMCommand_Rumble::GetCommandMacro() const -{ - return StringHelper::Sprintf("CS_RUMBLE_LIST(%i)", numEntries); -} - -/**** TEXT ****/ - -CutsceneMMSubCommandEntry_Text::CutsceneMMSubCommandEntry_Text(const std::vector& rawData, - offset_t rawDataIndex) - : CutsceneSubCommandEntry(rawData, rawDataIndex) -{ - type = BitConverter::ToUInt16BE(rawData, rawDataIndex + 0x6); - textId1 = BitConverter::ToUInt16BE(rawData, rawDataIndex + 0x8); - textId2 = BitConverter::ToUInt16BE(rawData, rawDataIndex + 0xA); -} - -std::string CutsceneMMSubCommandEntry_Text::GetBodySourceCode() const -{ - EnumData* enumData = &Globals::Instance->cfg.enumData; - - if (type == 0xFFFF) - { - return StringHelper::Sprintf("CS_TEXT_NONE(%i, %i)", startFrame, endFrame); - } - - if (type == 2 && - enumData->ocarinaSongActionId.find(base) != enumData->ocarinaSongActionId.end()) - { - return StringHelper::Sprintf("CS_TEXT_OCARINA_ACTION(%s, %i, %i, 0x%X)", - enumData->ocarinaSongActionId[base].c_str(), startFrame, - endFrame, textId1); - } - - switch (type) - { - case 0: - return StringHelper::Sprintf("CS_TEXT_DEFAULT(0x%X, %i, %i, 0x%X, 0x%X)", base, startFrame, - endFrame, textId1, textId2); - - case 1: - return StringHelper::Sprintf("CS_TEXT_TYPE_1(0x%X, %i, %i, 0x%X, 0x%X)", base, startFrame, - endFrame, textId1, textId2); - - case 3: - return StringHelper::Sprintf("CS_TEXT_TYPE_3(0x%X, %i, %i, 0x%X, 0x%X)", base, startFrame, - endFrame, textId1, textId2); - - case 4: - return StringHelper::Sprintf("CS_TEXT_BOSSES_REMAINS(0x%X, %i, %i, 0x%X)", base, startFrame, - endFrame, textId1); - - case 5: - return StringHelper::Sprintf("CS_TEXT_ALL_NORMAL_MASKS(0x%X, %i, %i, 0x%X)", base, - startFrame, endFrame, textId1); - } - - return nullptr; -} - -size_t CutsceneMMSubCommandEntry_Text::GetRawSize() const -{ - return 0x0C; -} - -CutsceneMMCommand_Text::CutsceneMMCommand_Text(const std::vector& rawData, - offset_t rawDataIndex) - : CutsceneCommand(rawData, rawDataIndex) -{ - rawDataIndex += 4; - - entries.reserve(numEntries); - for (size_t i = 0; i < numEntries; i++) - { - auto* entry = new CutsceneMMSubCommandEntry_Text(rawData, rawDataIndex); - entries.push_back(entry); - rawDataIndex += entry->GetRawSize(); - } -} - -std::string CutsceneMMCommand_Text::GetCommandMacro() const -{ - return StringHelper::Sprintf("CS_TEXT_LIST(%i)", numEntries); -} - -/**** ACTOR CUE ****/ - -CutsceneMMSubCommandEntry_ActorCue::CutsceneMMSubCommandEntry_ActorCue( - const std::vector& rawData, offset_t rawDataIndex) - : CutsceneSubCommandEntry(rawData, rawDataIndex) -{ - rotX = BitConverter::ToUInt16BE(rawData, rawDataIndex + 0x6); - rotY = BitConverter::ToUInt16BE(rawData, rawDataIndex + 0x8); - rotZ = BitConverter::ToUInt16BE(rawData, rawDataIndex + 0xA); - startPosX = BitConverter::ToInt32BE(rawData, rawDataIndex + 0xC); - startPosY = BitConverter::ToInt32BE(rawData, rawDataIndex + 0x10); - startPosZ = BitConverter::ToInt32BE(rawData, rawDataIndex + 0x14); - endPosX = BitConverter::ToInt32BE(rawData, rawDataIndex + 0x18); - endPosY = BitConverter::ToInt32BE(rawData, rawDataIndex + 0x1C); - endPosZ = BitConverter::ToInt32BE(rawData, rawDataIndex + 0x20); - normalX = BitConverter::ToFloatBE(rawData, rawDataIndex + 0x24); - normalY = BitConverter::ToFloatBE(rawData, rawDataIndex + 0x28); - normalZ = BitConverter::ToFloatBE(rawData, rawDataIndex + 0x2C); -} - -std::string CutsceneMMSubCommandEntry_ActorCue::GetBodySourceCode() const -{ - EnumData* enumData = &Globals::Instance->cfg.enumData; - std::string normalXStr = - ZCutscene::GetCsEncodedFloat(normalX, Globals::Instance->floatType, true); - std::string normalYStr = - ZCutscene::GetCsEncodedFloat(normalY, Globals::Instance->floatType, true); - std::string normalZStr = - ZCutscene::GetCsEncodedFloat(normalZ, Globals::Instance->floatType, true); - - if (static_cast(commandID) == CutsceneMM_CommandType::CS_CMD_PLAYER_CUE) - { - return StringHelper::Sprintf("CS_PLAYER_CUE(%s, %i, %i, 0x%04X, 0x%04X, 0x%04X, %i, %i, " - "%i, %i, %i, %i, %s, %s, %s)", - enumData->playerCueId[base].c_str(), startFrame, endFrame, - rotX, rotY, rotZ, startPosX, startPosY, startPosZ, endPosX, - endPosY, endPosZ, normalXStr.c_str(), normalYStr.c_str(), - normalZStr.c_str()); - } - else - { - return StringHelper::Sprintf("CS_ACTOR_CUE(%i, %i, %i, 0x%04X, 0x%04X, 0x%04X, %i, %i, " - "%i, %i, %i, %i, %s, %s, %s)", - base, startFrame, endFrame, rotX, rotY, rotZ, startPosX, - startPosY, startPosZ, endPosX, endPosY, endPosZ, - normalXStr.c_str(), normalYStr.c_str(), normalZStr.c_str()); - } -} - -size_t CutsceneMMSubCommandEntry_ActorCue::GetRawSize() const -{ - return 0x30; -} - -CutsceneMMCommand_ActorCue::CutsceneMMCommand_ActorCue(const std::vector& rawData, - offset_t rawDataIndex) - : CutsceneCommand(rawData, rawDataIndex) -{ - rawDataIndex += 4; - - entries.reserve(numEntries); - for (size_t i = 0; i < numEntries; i++) - { - auto* entry = new CutsceneMMSubCommandEntry_ActorCue(rawData, rawDataIndex); - entries.push_back(entry); - rawDataIndex += entry->GetRawSize(); - } -} - -std::string CutsceneMMCommand_ActorCue::GetCommandMacro() const -{ - EnumData* enumData = &Globals::Instance->cfg.enumData; - - if (static_cast(commandID) == CutsceneMM_CommandType::CS_CMD_PLAYER_CUE) - { - return StringHelper::Sprintf("CS_PLAYER_CUE_LIST(%i)", numEntries); - } - - if (enumData->cutsceneCmd.find(commandID) != enumData->cutsceneCmd.end()) - { - return StringHelper::Sprintf("CS_ACTOR_CUE_LIST(%s, %i)", - enumData->cutsceneCmd[commandID].c_str(), numEntries); - } - return StringHelper::Sprintf("CS_ACTOR_CUE_LIST(0x%03X, %i)", commandID, numEntries); -} diff --git a/tools/ZAPD/ZAPD/OtherStructs/CutsceneMM_Commands.h b/tools/ZAPD/ZAPD/OtherStructs/CutsceneMM_Commands.h deleted file mode 100644 index 597f6788bc..0000000000 --- a/tools/ZAPD/ZAPD/OtherStructs/CutsceneMM_Commands.h +++ /dev/null @@ -1,481 +0,0 @@ -#pragma once - -#include "Cutscene_Common.h" - -// https://github.com/zeldaret/mm/blob/0c7b90cf97f26483c8b6a98ae099a295f61e72ab/include/z64cutscene.h#L294-530 -enum class CutsceneMM_CommandType -{ - /* -2 */ CS_CMD_ACTOR_CUE_POST_PROCESS = -2, - /* -1 */ CS_CAM_STOP, - /* 0x00A */ CS_CMD_TEXT = 10, - /* 0x05A */ CS_CMD_CAMERA_SPLINE = 90, - /* 0x064 */ CS_CMD_ACTOR_CUE_100 = 100, - /* 0x065 */ CS_CMD_ACTOR_CUE_101, - /* 0x066 */ CS_CMD_ACTOR_CUE_102, - /* 0x067 */ CS_CMD_ACTOR_CUE_103, - /* 0x068 */ CS_CMD_ACTOR_CUE_104, - /* 0x069 */ CS_CMD_ACTOR_CUE_105, - /* 0x06A */ CS_CMD_ACTOR_CUE_106, - /* 0x06B */ CS_CMD_ACTOR_CUE_107, - /* 0x06C */ CS_CMD_ACTOR_CUE_108, - /* 0x06D */ CS_CMD_ACTOR_CUE_109, - /* 0x06E */ CS_CMD_ACTOR_CUE_110, - /* 0x06F */ CS_CMD_ACTOR_CUE_111, - /* 0x070 */ CS_CMD_ACTOR_CUE_112, - /* 0x071 */ CS_CMD_ACTOR_CUE_113, - /* 0x072 */ CS_CMD_ACTOR_CUE_114, - /* 0x073 */ CS_CMD_ACTOR_CUE_115, - /* 0x074 */ CS_CMD_ACTOR_CUE_116, - /* 0x075 */ CS_CMD_ACTOR_CUE_117, - /* 0x076 */ CS_CMD_ACTOR_CUE_118, - /* 0x077 */ CS_CMD_ACTOR_CUE_119, - /* 0x078 */ CS_CMD_ACTOR_CUE_120, - /* 0x079 */ CS_CMD_ACTOR_CUE_121, - /* 0x07A */ CS_CMD_ACTOR_CUE_122, - /* 0x07B */ CS_CMD_ACTOR_CUE_123, - /* 0x07C */ CS_CMD_ACTOR_CUE_124, - /* 0x07D */ CS_CMD_ACTOR_CUE_125, - /* 0x07E */ CS_CMD_ACTOR_CUE_126, - /* 0x07F */ CS_CMD_ACTOR_CUE_127, - /* 0x080 */ CS_CMD_ACTOR_CUE_128, - /* 0x081 */ CS_CMD_ACTOR_CUE_129, - /* 0x082 */ CS_CMD_ACTOR_CUE_130, - /* 0x083 */ CS_CMD_ACTOR_CUE_131, - /* 0x084 */ CS_CMD_ACTOR_CUE_132, - /* 0x085 */ CS_CMD_ACTOR_CUE_133, - /* 0x086 */ CS_CMD_ACTOR_CUE_134, - /* 0x087 */ CS_CMD_ACTOR_CUE_135, - /* 0x088 */ CS_CMD_ACTOR_CUE_136, - /* 0x089 */ CS_CMD_ACTOR_CUE_137, - /* 0x08A */ CS_CMD_ACTOR_CUE_138, - /* 0x08B */ CS_CMD_ACTOR_CUE_139, - /* 0x08C */ CS_CMD_ACTOR_CUE_140, - /* 0x08D */ CS_CMD_ACTOR_CUE_141, - /* 0x08E */ CS_CMD_ACTOR_CUE_142, - /* 0x08F */ CS_CMD_ACTOR_CUE_143, - /* 0x090 */ CS_CMD_ACTOR_CUE_144, - /* 0x091 */ CS_CMD_ACTOR_CUE_145, - /* 0x092 */ CS_CMD_ACTOR_CUE_146, - /* 0x093 */ CS_CMD_ACTOR_CUE_147, - /* 0x094 */ CS_CMD_ACTOR_CUE_148, - /* 0x095 */ CS_CMD_ACTOR_CUE_149, - /* 0x096 */ CS_CMD_MISC, - /* 0x097 */ CS_CMD_LIGHT_SETTING, - /* 0x098 */ CS_CMD_TRANSITION, - /* 0x099 */ CS_CMD_MOTION_BLUR, - /* 0x09A */ CS_CMD_GIVE_TATL, - /* 0x09B */ CS_CMD_TRANSITION_GENERAL, - /* 0x09C */ CS_CMD_FADE_OUT_SEQ, - /* 0x09D */ CS_CMD_TIME, - /* 0x0C8 */ CS_CMD_PLAYER_CUE = 200, - /* 0x0C9 */ CS_CMD_ACTOR_CUE_201, - /* 0x0FA */ CS_CMD_UNK_DATA_FA = 0xFA, - /* 0x0FE */ CS_CMD_UNK_DATA_FE = 0xFE, - /* 0x0FF */ CS_CMD_UNK_DATA_FF, - /* 0x100 */ CS_CMD_UNK_DATA_100, - /* 0x101 */ CS_CMD_UNK_DATA_101, - /* 0x102 */ CS_CMD_UNK_DATA_102, - /* 0x103 */ CS_CMD_UNK_DATA_103, - /* 0x104 */ CS_CMD_UNK_DATA_104, - /* 0x105 */ CS_CMD_UNK_DATA_105, - /* 0x108 */ CS_CMD_UNK_DATA_108 = 0x108, - /* 0x109 */ CS_CMD_UNK_DATA_109, - /* 0x12C */ CS_CMD_START_SEQ = 300, - /* 0x12D */ CS_CMD_STOP_SEQ, - /* 0x12E */ CS_CMD_START_AMBIENCE, - /* 0x12F */ CS_CMD_FADE_OUT_AMBIENCE, - /* 0x130 */ CS_CMD_SFX_REVERB_INDEX_2, - /* 0x131 */ CS_CMD_SFX_REVERB_INDEX_1, - /* 0x132 */ CS_CMD_MODIFY_SEQ, - /* 0x15E */ CS_CMD_DESTINATION = 350, - /* 0x15F */ CS_CMD_CHOOSE_CREDITS_SCENES, - /* 0x190 */ CS_CMD_RUMBLE = 400, - /* 0x1C2 */ CS_CMD_ACTOR_CUE_450 = 450, - /* 0x1C3 */ CS_CMD_ACTOR_CUE_451, - /* 0x1C4 */ CS_CMD_ACTOR_CUE_452, - /* 0x1C5 */ CS_CMD_ACTOR_CUE_453, - /* 0x1C6 */ CS_CMD_ACTOR_CUE_454, - /* 0x1C7 */ CS_CMD_ACTOR_CUE_455, - /* 0x1C8 */ CS_CMD_ACTOR_CUE_456, - /* 0x1C9 */ CS_CMD_ACTOR_CUE_457, - /* 0x1CA */ CS_CMD_ACTOR_CUE_458, - /* 0x1CB */ CS_CMD_ACTOR_CUE_459, - /* 0x1CC */ CS_CMD_ACTOR_CUE_460, - /* 0x1CD */ CS_CMD_ACTOR_CUE_461, - /* 0x1CE */ CS_CMD_ACTOR_CUE_462, - /* 0x1CF */ CS_CMD_ACTOR_CUE_463, - /* 0x1D0 */ CS_CMD_ACTOR_CUE_464, - /* 0x1D1 */ CS_CMD_ACTOR_CUE_465, - /* 0x1D2 */ CS_CMD_ACTOR_CUE_466, - /* 0x1D3 */ CS_CMD_ACTOR_CUE_467, - /* 0x1D4 */ CS_CMD_ACTOR_CUE_468, - /* 0x1D5 */ CS_CMD_ACTOR_CUE_469, - /* 0x1D6 */ CS_CMD_ACTOR_CUE_470, - /* 0x1D7 */ CS_CMD_ACTOR_CUE_471, - /* 0x1D8 */ CS_CMD_ACTOR_CUE_472, - /* 0x1D9 */ CS_CMD_ACTOR_CUE_473, - /* 0x1DA */ CS_CMD_ACTOR_CUE_474, - /* 0x1DB */ CS_CMD_ACTOR_CUE_475, - /* 0x1DC */ CS_CMD_ACTOR_CUE_476, - /* 0x1DD */ CS_CMD_ACTOR_CUE_477, - /* 0x1DE */ CS_CMD_ACTOR_CUE_478, - /* 0x1DF */ CS_CMD_ACTOR_CUE_479, - /* 0x1E0 */ CS_CMD_ACTOR_CUE_480, - /* 0x1E1 */ CS_CMD_ACTOR_CUE_481, - /* 0x1E2 */ CS_CMD_ACTOR_CUE_482, - /* 0x1E3 */ CS_CMD_ACTOR_CUE_483, - /* 0x1E4 */ CS_CMD_ACTOR_CUE_484, - /* 0x1E5 */ CS_CMD_ACTOR_CUE_485, - /* 0x1E6 */ CS_CMD_ACTOR_CUE_486, - /* 0x1E7 */ CS_CMD_ACTOR_CUE_487, - /* 0x1E8 */ CS_CMD_ACTOR_CUE_488, - /* 0x1E9 */ CS_CMD_ACTOR_CUE_489, - /* 0x1EA */ CS_CMD_ACTOR_CUE_490, - /* 0x1EB */ CS_CMD_ACTOR_CUE_491, - /* 0x1EC */ CS_CMD_ACTOR_CUE_492, - /* 0x1ED */ CS_CMD_ACTOR_CUE_493, - /* 0x1EE */ CS_CMD_ACTOR_CUE_494, - /* 0x1EF */ CS_CMD_ACTOR_CUE_495, - /* 0x1F0 */ CS_CMD_ACTOR_CUE_496, - /* 0x1F1 */ CS_CMD_ACTOR_CUE_497, - /* 0x1F2 */ CS_CMD_ACTOR_CUE_498, - /* 0x1F3 */ CS_CMD_ACTOR_CUE_499, - /* 0x1F4 */ CS_CMD_ACTOR_CUE_500, - /* 0x1F5 */ CS_CMD_ACTOR_CUE_501, - /* 0x1F6 */ CS_CMD_ACTOR_CUE_502, - /* 0x1F7 */ CS_CMD_ACTOR_CUE_503, - /* 0x1F8 */ CS_CMD_ACTOR_CUE_504, - /* 0x1F9 */ CS_CMD_ACTOR_CUE_SOTCS, - /* 0x1FA */ CS_CMD_ACTOR_CUE_506, - /* 0x1FB */ CS_CMD_ACTOR_CUE_507, - /* 0x1FC */ CS_CMD_ACTOR_CUE_508, - /* 0x1FD */ CS_CMD_ACTOR_CUE_509, - /* 0x1FE */ CS_CMD_ACTOR_CUE_510, - /* 0x1FF */ CS_CMD_ACTOR_CUE_511, - /* 0x200 */ CS_CMD_ACTOR_CUE_512, - /* 0x201 */ CS_CMD_ACTOR_CUE_513, - /* 0x202 */ CS_CMD_ACTOR_CUE_514, - /* 0x203 */ CS_CMD_ACTOR_CUE_515, - /* 0x204 */ CS_CMD_ACTOR_CUE_516, - /* 0x205 */ CS_CMD_ACTOR_CUE_517, - /* 0x206 */ CS_CMD_ACTOR_CUE_518, - /* 0x207 */ CS_CMD_ACTOR_CUE_519, - /* 0x208 */ CS_CMD_ACTOR_CUE_520, - /* 0x209 */ CS_CMD_ACTOR_CUE_521, - /* 0x20A */ CS_CMD_ACTOR_CUE_522, - /* 0x20B */ CS_CMD_ACTOR_CUE_523, - /* 0x20C */ CS_CMD_ACTOR_CUE_524, - /* 0x20D */ CS_CMD_ACTOR_CUE_525, - /* 0x20E */ CS_CMD_ACTOR_CUE_526, - /* 0x20F */ CS_CMD_ACTOR_CUE_527, - /* 0x210 */ CS_CMD_ACTOR_CUE_528, - /* 0x211 */ CS_CMD_ACTOR_CUE_529, - /* 0x212 */ CS_CMD_ACTOR_CUE_530, - /* 0x213 */ CS_CMD_ACTOR_CUE_531, - /* 0x214 */ CS_CMD_ACTOR_CUE_532, - /* 0x215 */ CS_CMD_ACTOR_CUE_533, - /* 0x216 */ CS_CMD_ACTOR_CUE_534, - /* 0x217 */ CS_CMD_ACTOR_CUE_535, - /* 0x218 */ CS_CMD_ACTOR_CUE_536, - /* 0x219 */ CS_CMD_ACTOR_CUE_537, - /* 0x21A */ CS_CMD_ACTOR_CUE_538, - /* 0x21B */ CS_CMD_ACTOR_CUE_539, - /* 0x21C */ CS_CMD_ACTOR_CUE_540, - /* 0x21D */ CS_CMD_ACTOR_CUE_541, - /* 0x21E */ CS_CMD_ACTOR_CUE_542, - /* 0x21F */ CS_CMD_ACTOR_CUE_543, - /* 0x220 */ CS_CMD_ACTOR_CUE_544, - /* 0x221 */ CS_CMD_ACTOR_CUE_545, - /* 0x222 */ CS_CMD_ACTOR_CUE_546, - /* 0x223 */ CS_CMD_ACTOR_CUE_547, - /* 0x224 */ CS_CMD_ACTOR_CUE_548, - /* 0x225 */ CS_CMD_ACTOR_CUE_549, - /* 0x226 */ CS_CMD_ACTOR_CUE_550, - /* 0x227 */ CS_CMD_ACTOR_CUE_551, - /* 0x228 */ CS_CMD_ACTOR_CUE_552, - /* 0x229 */ CS_CMD_ACTOR_CUE_553, - /* 0x22A */ CS_CMD_ACTOR_CUE_554, - /* 0x22B */ CS_CMD_ACTOR_CUE_555, - /* 0x22C */ CS_CMD_ACTOR_CUE_556, - /* 0x22D */ CS_CMD_ACTOR_CUE_557, - /* 0x22E */ CS_CMD_ACTOR_CUE_558, - /* 0x22F */ CS_CMD_ACTOR_CUE_559, - /* 0x230 */ CS_CMD_ACTOR_CUE_560, - /* 0x231 */ CS_CMD_ACTOR_CUE_561, - /* 0x232 */ CS_CMD_ACTOR_CUE_562, - /* 0x233 */ CS_CMD_ACTOR_CUE_563, - /* 0x234 */ CS_CMD_ACTOR_CUE_564, - /* 0x235 */ CS_CMD_ACTOR_CUE_565, - /* 0x236 */ CS_CMD_ACTOR_CUE_566, - /* 0x237 */ CS_CMD_ACTOR_CUE_567, - /* 0x238 */ CS_CMD_ACTOR_CUE_568, - /* 0x239 */ CS_CMD_ACTOR_CUE_569, - /* 0x23A */ CS_CMD_ACTOR_CUE_570, - /* 0x23B */ CS_CMD_ACTOR_CUE_571, - /* 0x23C */ CS_CMD_ACTOR_CUE_572, - /* 0x23D */ CS_CMD_ACTOR_CUE_573, - /* 0x23E */ CS_CMD_ACTOR_CUE_574, - /* 0x23F */ CS_CMD_ACTOR_CUE_575, - /* 0x240 */ CS_CMD_ACTOR_CUE_576, - /* 0x241 */ CS_CMD_ACTOR_CUE_577, - /* 0x242 */ CS_CMD_ACTOR_CUE_578, - /* 0x243 */ CS_CMD_ACTOR_CUE_579, - /* 0x244 */ CS_CMD_ACTOR_CUE_580, - /* 0x245 */ CS_CMD_ACTOR_CUE_581, - /* 0x246 */ CS_CMD_ACTOR_CUE_582, - /* 0x247 */ CS_CMD_ACTOR_CUE_583, - /* 0x248 */ CS_CMD_ACTOR_CUE_584, - /* 0x249 */ CS_CMD_ACTOR_CUE_585, - /* 0x24A */ CS_CMD_ACTOR_CUE_586, - /* 0x24B */ CS_CMD_ACTOR_CUE_587, - /* 0x24C */ CS_CMD_ACTOR_CUE_588, - /* 0x24D */ CS_CMD_ACTOR_CUE_589, - /* 0x24E */ CS_CMD_ACTOR_CUE_590, - /* 0x24F */ CS_CMD_ACTOR_CUE_591, - /* 0x250 */ CS_CMD_ACTOR_CUE_592, - /* 0x251 */ CS_CMD_ACTOR_CUE_593, - /* 0x252 */ CS_CMD_ACTOR_CUE_594, - /* 0x253 */ CS_CMD_ACTOR_CUE_595, - /* 0x254 */ CS_CMD_ACTOR_CUE_596, - /* 0x255 */ CS_CMD_ACTOR_CUE_597, - /* 0x256 */ CS_CMD_ACTOR_CUE_598, - /* 0x257 */ CS_CMD_ACTOR_CUE_599 -}; - -/**** GENERIC ****/ - -class CutsceneMMSubCommandEntry_GenericCmd : public CutsceneSubCommandEntry -{ -public: - CutsceneMM_CommandType commandId; - - CutsceneMMSubCommandEntry_GenericCmd(const std::vector& rawData, offset_t rawDataIndex, - CutsceneMM_CommandType cmdId); - - std::string GetBodySourceCode() const override; -}; - -class CutsceneMMCommand_GenericCmd : public CutsceneCommand -{ -public: - CutsceneMMCommand_GenericCmd(const std::vector& rawData, offset_t rawDataIndex, - CutsceneMM_CommandType cmdId); - - std::string GetCommandMacro() const override; -}; - -/**** CAMERA ****/ - -// TODO: MM cutscene camera command is implemented as a placeholder until we better understand how -// it works - -class CutsceneSubCommandEntry_SplineCamPoint : public CutsceneSubCommandEntry -{ -public: - uint8_t interpType; - uint8_t weight; - uint16_t duration; - - uint16_t posX; - uint16_t posY; - - uint16_t posZ; - uint16_t relTo; - - CutsceneSubCommandEntry_SplineCamPoint(const std::vector& rawData, - offset_t rawDataIndex); - - std::string GetBodySourceCode() const override; - - size_t GetRawSize() const override; -}; - -class CutsceneSubCommandEntry_SplineMiscPoint : public CutsceneSubCommandEntry -{ -public: - uint16_t unused0; - uint16_t roll; - uint16_t fov; - uint16_t unused1; - - CutsceneSubCommandEntry_SplineMiscPoint(const std::vector& rawData, - offset_t rawDataIndex); - - std::string GetBodySourceCode() const override; - - size_t GetRawSize() const override; -}; - -class CutsceneSubCommandEntry_SplineFooter : public CutsceneSubCommandEntry -{ -public: - CutsceneSubCommandEntry_SplineFooter(const std::vector& rawData, - offset_t rawDataIndex); - - std::string GetBodySourceCode() const override; - - size_t GetRawSize() const override; -}; - -class CutsceneSubCommandEntry_SplineHeader : public CutsceneSubCommandEntry -{ -public: - uint16_t numEntries; - uint16_t unused0; - uint16_t unused1; - uint16_t duration; - CutsceneSubCommandEntry_SplineHeader(const std::vector& rawData, - offset_t rawDataIndex); - - std::string GetBodySourceCode() const override; - - size_t GetRawSize() const override; -}; - -class CutsceneMMCommand_Spline : public CutsceneCommand -{ -public: - uint32_t numHeaders; - uint32_t totalCommands; - CutsceneMMCommand_Spline(const std::vector& rawData, offset_t rawDataIndex); - - std::string GetCommandMacro() const override; - size_t GetCommandSize() const override; -}; - -/**** TRANSITION GENERAL ****/ - -class CutsceneSubCommandEntry_TransitionGeneral : public CutsceneSubCommandEntry -{ -public: - uint8_t unk_06; - uint8_t unk_07; - uint8_t unk_08; - uint8_t unk_09; - uint8_t unk_0A; - uint8_t unk_0B; - - CutsceneSubCommandEntry_TransitionGeneral(const std::vector& rawData, - offset_t rawDataIndex); - - std::string GetBodySourceCode() const override; - - size_t GetRawSize() const override; -}; - -class CutsceneMMCommand_TransitionGeneral : public CutsceneCommand -{ -public: - CutsceneMMCommand_TransitionGeneral(const std::vector& rawData, offset_t rawDataIndex); - - std::string GetCommandMacro() const override; -}; - -/**** FADE OUT SEQUENCE ****/ - -class CutsceneSubCommandEntry_FadeOutSeq : public CutsceneSubCommandEntry -{ -public: - uint32_t unk_08; - - CutsceneSubCommandEntry_FadeOutSeq(const std::vector& rawData, offset_t rawDataIndex); - - std::string GetBodySourceCode() const override; - - size_t GetRawSize() const override; -}; - -class CutsceneMMCommand_FadeOutSeq : public CutsceneCommand -{ -public: - CutsceneMMCommand_FadeOutSeq(const std::vector& rawData, offset_t rawDataIndex); - - std::string GetCommandMacro() const override; -}; - -/**** NON IMPLEMENTED ****/ - -class CutsceneSubCommandEntry_NonImplemented : public CutsceneSubCommandEntry -{ -public: - CutsceneSubCommandEntry_NonImplemented(const std::vector& rawData, - offset_t rawDataIndex); -}; - -class CutsceneMMCommand_NonImplemented : public CutsceneCommand -{ -public: - CutsceneMMCommand_NonImplemented(const std::vector& rawData, offset_t rawDataIndex); -}; - -/**** RUMBLE ****/ - -class CutsceneMMSubCommandEntry_Rumble : public CutsceneSubCommandEntry -{ -public: - uint8_t intensity; - uint8_t decayTimer; - uint8_t decayStep; - - CutsceneMMSubCommandEntry_Rumble(const std::vector& rawData, offset_t rawDataIndex); - - std::string GetBodySourceCode() const override; - - size_t GetRawSize() const override; -}; - -class CutsceneMMCommand_Rumble : public CutsceneCommand -{ -public: - CutsceneMMCommand_Rumble(const std::vector& rawData, offset_t rawDataIndex); - - std::string GetCommandMacro() const override; -}; - -/**** TEXT ****/ - -class CutsceneMMSubCommandEntry_Text : public CutsceneSubCommandEntry -{ -public: - uint16_t type; - uint16_t textId1; - uint16_t textId2; - - CutsceneMMSubCommandEntry_Text(const std::vector& rawData, offset_t rawDataIndex); - - std::string GetBodySourceCode() const override; - - size_t GetRawSize() const override; -}; - -class CutsceneMMCommand_Text : public CutsceneCommand -{ -public: - CutsceneMMCommand_Text(const std::vector& rawData, offset_t rawDataIndex); - - std::string GetCommandMacro() const override; -}; - -/**** ACTOR CUE ****/ - -class CutsceneMMSubCommandEntry_ActorCue : public CutsceneSubCommandEntry -{ -public: - uint16_t rotX, rotY, rotZ; - int32_t startPosX, startPosY, startPosZ; - int32_t endPosX, endPosY, endPosZ; - float normalX, normalY, normalZ; - - CutsceneMMSubCommandEntry_ActorCue(const std::vector& rawData, offset_t rawDataIndex); - std::string GetBodySourceCode() const override; - - size_t GetRawSize() const override; -}; - -class CutsceneMMCommand_ActorCue : public CutsceneCommand -{ -public: - CutsceneMMCommand_ActorCue(const std::vector& rawData, offset_t rawDataIndex); - - std::string GetCommandMacro() const override; -}; diff --git a/tools/ZAPD/ZAPD/OtherStructs/CutsceneOoT_Commands.cpp b/tools/ZAPD/ZAPD/OtherStructs/CutsceneOoT_Commands.cpp deleted file mode 100644 index 668657e7aa..0000000000 --- a/tools/ZAPD/ZAPD/OtherStructs/CutsceneOoT_Commands.cpp +++ /dev/null @@ -1,472 +0,0 @@ -#include "CutsceneOoT_Commands.h" - -#include -#include -#include "Globals.h" -#include "Utils/BitConverter.h" -#include "Utils/StringHelper.h" - -#include "ZCutscene.h" - -/**** GENERIC ****/ - -// Specific for command lists where each entry has size 0x30 bytes -const std::unordered_map csCommandsDesc = { - {CutsceneOoT_CommandType::CS_CMD_MISC, - {"CS_MISC", "(%s, %i, %i, %i, %i, %i, %i, %i, %i, %i, %i, %i, %i, %i)"}}, - {CutsceneOoT_CommandType::CS_CMD_LIGHT_SETTING, - {"CS_LIGHT_SETTING", "(0x%02X, %i, %i, %i, %i, %i, %i, %i, %i, %i, %i, %i, %i, %i)"}}, - {CutsceneOoT_CommandType::CS_CMD_START_SEQ, - {"CS_START_SEQ", "(%s, %i, %i, %i, %i, %i, %i, %i, %i, %i, %i)"}}, - {CutsceneOoT_CommandType::CS_CMD_STOP_SEQ, - {"CS_STOP_SEQ", "(%s, %i, %i, %i, %i, %i, %i, %i, %i, %i, %i)"}}, - {CutsceneOoT_CommandType::CS_CMD_FADE_OUT_SEQ, - {"CS_FADE_OUT_SEQ", "(%s, %i, %i, %i, %i, %i, %i, %i, %i, %i, %i)"}}, -}; - -CutsceneOoTSubCommandEntry_GenericCmd::CutsceneOoTSubCommandEntry_GenericCmd( - const std::vector& rawData, offset_t rawDataIndex, CutsceneOoT_CommandType cmdId) - : CutsceneSubCommandEntry(rawData, rawDataIndex), commandId(cmdId) -{ - word0 = BitConverter::ToUInt32BE(rawData, rawDataIndex + 0x0); - word1 = BitConverter::ToUInt32BE(rawData, rawDataIndex + 0x4); - - unused1 = BitConverter::ToUInt32BE(rawData, rawDataIndex + 0x8); - unused2 = BitConverter::ToUInt32BE(rawData, rawDataIndex + 0xC); - unused3 = BitConverter::ToUInt32BE(rawData, rawDataIndex + 0x10); - unused4 = BitConverter::ToUInt32BE(rawData, rawDataIndex + 0x14); - unused5 = BitConverter::ToUInt32BE(rawData, rawDataIndex + 0x18); - unused6 = BitConverter::ToUInt32BE(rawData, rawDataIndex + 0x1C); - unused7 = BitConverter::ToUInt32BE(rawData, rawDataIndex + 0x20); - unused8 = BitConverter::ToUInt32BE(rawData, rawDataIndex + 0x24); - unused9 = BitConverter::ToUInt32BE(rawData, rawDataIndex + 0x28); - unused10 = BitConverter::ToUInt32BE(rawData, rawDataIndex + 0x2C); -} - -std::string CutsceneOoTSubCommandEntry_GenericCmd::GetBodySourceCode() const -{ - EnumData* enumData = &Globals::Instance->cfg.enumData; - const auto& element = csCommandsDesc.find(commandId); - - if (element != csCommandsDesc.end()) - { - bool isIndexInMisc = enumData->miscType.find(base) != enumData->miscType.end(); - bool isIndexInFade = - enumData->fadeOutSeqPlayer.find(base) != enumData->fadeOutSeqPlayer.end(); - bool isIndexInSeqId = enumData->seqId.find(base - 1) != enumData->seqId.end(); - std::string entryFmt = element->second.cmdMacro; - std::string firstArg; - entryFmt += element->second.args; - - if (commandId == CutsceneOoT_CommandType::CS_CMD_MISC && isIndexInMisc) - firstArg = enumData->miscType[base]; - else if (commandId == CutsceneOoT_CommandType::CS_CMD_FADE_OUT_SEQ && isIndexInFade) - firstArg = enumData->fadeOutSeqPlayer[base]; - else if (commandId == CutsceneOoT_CommandType::CS_CMD_START_SEQ && isIndexInSeqId) - firstArg = enumData->seqId[base - 1]; - else if (commandId == CutsceneOoT_CommandType::CS_CMD_STOP_SEQ && isIndexInSeqId) - firstArg = enumData->seqId[base - 1]; - else - { - return StringHelper::Sprintf(entryFmt.c_str(), base - 1, startFrame, endFrame, pad, - unused1, unused2, unused3, unused4, unused5, unused6, - unused7, unused8, unused9, unused10); - } - return StringHelper::Sprintf(entryFmt.c_str(), firstArg.c_str(), startFrame, endFrame, pad, - unused1, unused2, unused3, unused4, unused5, unused6, unused7, - unused8, unused9, unused10); - } - return StringHelper::Sprintf("CS_UNK_DATA(0x%08X, 0x%08X, 0x%08X, 0x%08X, 0x%08X, 0x%08X, " - "0x%08X, 0x%08X, 0x%08X, 0x%08X, 0x%08X, 0x%08X)", - word0, word1, unused1, unused2, unused3, unused4, unused5, unused6, - unused7, unused8, unused9, unused10); -} - -size_t CutsceneOoTSubCommandEntry_GenericCmd::GetRawSize() const -{ - return 0x30; -} - -CutsceneOoTCommand_GenericCmd::CutsceneOoTCommand_GenericCmd(const std::vector& rawData, - offset_t rawDataIndex, - CutsceneOoT_CommandType cmdId) - : CutsceneCommand(rawData, rawDataIndex) -{ - rawDataIndex += 4; - - commandID = static_cast(cmdId); - entries.reserve(numEntries); - - for (size_t i = 0; i < numEntries; i++) - { - auto* entry = new CutsceneOoTSubCommandEntry_GenericCmd(rawData, rawDataIndex, cmdId); - entries.push_back(entry); - rawDataIndex += entry->GetRawSize(); - } -} - -std::string CutsceneOoTCommand_GenericCmd::GetCommandMacro() const -{ - const auto& element = csCommandsDesc.find(static_cast(commandID)); - - if (element != csCommandsDesc.end()) - { - return StringHelper::Sprintf("%s_LIST(%i)", element->second.cmdMacro, numEntries); - } - - return StringHelper::Sprintf("CS_UNK_DATA_LIST(0x%X, %i)", commandID, numEntries); -} - -/**** CAMERA ****/ - -CutsceneOoTCommand_CameraPoint::CutsceneOoTCommand_CameraPoint(const std::vector& rawData, - offset_t rawDataIndex) - : CutsceneSubCommandEntry(rawData, rawDataIndex) -{ - continueFlag = BitConverter::ToInt8BE(rawData, rawDataIndex + 0); - cameraRoll = BitConverter::ToInt8BE(rawData, rawDataIndex + 1); - nextPointFrame = BitConverter::ToInt16BE(rawData, rawDataIndex + 2); - viewAngle = BitConverter::ToFloatBE(rawData, rawDataIndex + 4); - - posX = BitConverter::ToInt16BE(rawData, rawDataIndex + 8); - posY = BitConverter::ToInt16BE(rawData, rawDataIndex + 10); - posZ = BitConverter::ToInt16BE(rawData, rawDataIndex + 12); - - unused = BitConverter::ToInt16BE(rawData, rawDataIndex + 14); -} - -std::string CutsceneOoTCommand_CameraPoint::GetBodySourceCode() const -{ - std::string continueMacro = "CS_CAM_CONTINUE"; - if (continueFlag != 0) - continueMacro = "CS_CAM_STOP"; - - return StringHelper::Sprintf( - "CS_CAM_POINT(%s, 0x%02X, %i, %s, %i, %i, %i, 0x%04X)", continueMacro.c_str(), cameraRoll, - nextPointFrame, - ZCutscene::GetCsEncodedFloat(viewAngle, Globals::Instance->floatType, false).c_str(), posX, - posY, posZ, unused); -} - -size_t CutsceneOoTCommand_CameraPoint::GetRawSize() const -{ - return 0x10; -} - -CutsceneOoTCommand_GenericCameraCmd::CutsceneOoTCommand_GenericCameraCmd( - const std::vector& rawData, offset_t rawDataIndex) - : CutsceneCommand(rawData, rawDataIndex) -{ - base = BitConverter::ToUInt16BE(rawData, rawDataIndex + 0); - startFrame = BitConverter::ToUInt16BE(rawData, rawDataIndex + 2); - endFrame = BitConverter::ToUInt16BE(rawData, rawDataIndex + 4); - unused = BitConverter::ToUInt16BE(rawData, rawDataIndex + 6); - - bool shouldContinue = true; - - uint32_t currentPtr = rawDataIndex + 8; - - while (shouldContinue) - { - CutsceneOoTCommand_CameraPoint* camPoint = - new CutsceneOoTCommand_CameraPoint(rawData, currentPtr); - entries.push_back(camPoint); - - if (camPoint->continueFlag == -1) - shouldContinue = false; - - currentPtr += camPoint->GetRawSize(); - } -} - -std::string CutsceneOoTCommand_GenericCameraCmd::GetCommandMacro() const -{ - std::string result; - const char* listStr; - - if (commandID == (uint32_t)CutsceneOoT_CommandType::CS_CMD_CAM_AT_SPLINE) - { - listStr = "CS_CAM_AT_SPLINE"; - } - else if (commandID == (uint32_t)CutsceneOoT_CommandType::CS_CMD_CAM_AT_SPLINE_REL_TO_PLAYER) - { - listStr = "CS_CAM_AT_SPLINE_REL_TO_PLAYER"; - } - else if (commandID == (uint32_t)CutsceneOoT_CommandType::CS_CMD_CAM_EYE_SPLINE_REL_TO_PLAYER) - { - listStr = "CS_CAM_EYE_SPLINE_REL_TO_PLAYER"; - } - else - { - listStr = "CS_CAM_EYE_SPLINE"; - } - - result += StringHelper::Sprintf("%s(%i, %i)", listStr, startFrame, endFrame); - - return result; -} - -size_t CutsceneOoTCommand_GenericCameraCmd::GetCommandSize() const -{ - return 0x0C + entries.at(0)->GetRawSize() * entries.size(); -} - -/**** RUMBLE ****/ - -CutsceneOoTSubCommandEntry_Rumble::CutsceneOoTSubCommandEntry_Rumble( - const std::vector& rawData, offset_t rawDataIndex) - : CutsceneSubCommandEntry(rawData, rawDataIndex) -{ - sourceStrength = BitConverter::ToUInt8BE(rawData, rawDataIndex + 0x06); - duration = BitConverter::ToUInt8BE(rawData, rawDataIndex + 0x07); - decreaseRate = BitConverter::ToUInt8BE(rawData, rawDataIndex + 0x08); - unk_09 = BitConverter::ToUInt8BE(rawData, rawDataIndex + 0x09); - unk_0A = BitConverter::ToUInt8BE(rawData, rawDataIndex + 0x0A); -} - -std::string CutsceneOoTSubCommandEntry_Rumble::GetBodySourceCode() const -{ - // Note: the first argument is unused - return StringHelper::Sprintf("CS_RUMBLE_CONTROLLER(%i, %i, %i, %i, %i, %i, 0x%02X, 0x%02X)", - base, startFrame, endFrame, sourceStrength, duration, decreaseRate, - unk_09, unk_0A); -} - -size_t CutsceneOoTSubCommandEntry_Rumble::GetRawSize() const -{ - return 0x0C; -} - -CutsceneOoTCommand_Rumble::CutsceneOoTCommand_Rumble(const std::vector& rawData, - offset_t rawDataIndex) - : CutsceneCommand(rawData, rawDataIndex) -{ - rawDataIndex += 4; - - entries.reserve(numEntries); - for (size_t i = 0; i < numEntries; i++) - { - auto* entry = new CutsceneOoTSubCommandEntry_Rumble(rawData, rawDataIndex); - entries.push_back(entry); - rawDataIndex += entry->GetRawSize(); - } -} - -std::string CutsceneOoTCommand_Rumble::GetCommandMacro() const -{ - return StringHelper::Sprintf("CS_RUMBLE_CONTROLLER_LIST(%i)", numEntries); -} - -/**** TEXT ****/ - -CutsceneOoTSubCommandEntry_Text::CutsceneOoTSubCommandEntry_Text( - const std::vector& rawData, offset_t rawDataIndex) - : CutsceneSubCommandEntry(rawData, rawDataIndex) -{ - type = BitConverter::ToUInt16BE(rawData, rawDataIndex + 0x6); - textId1 = BitConverter::ToUInt16BE(rawData, rawDataIndex + 0x8); - textId2 = BitConverter::ToUInt16BE(rawData, rawDataIndex + 0xA); -} - -std::string CutsceneOoTSubCommandEntry_Text::GetBodySourceCode() const -{ - EnumData* enumData = &Globals::Instance->cfg.enumData; - - if (type == 0xFFFF) - { - return StringHelper::Sprintf("CS_TEXT_NONE(%i, %i)", startFrame, endFrame); - } - if (type == 2 && - enumData->ocarinaSongActionId.find(base) != enumData->ocarinaSongActionId.end()) - { - return StringHelper::Sprintf("CS_TEXT_OCARINA_ACTION(%s, %i, %i, 0x%X)", - enumData->ocarinaSongActionId[base].c_str(), startFrame, - endFrame, textId1); - } - - if (enumData->textType.find(type) != enumData->textType.end()) - { - return StringHelper::Sprintf("CS_TEXT(0x%X, %i, %i, %s, 0x%X, 0x%X)", base, startFrame, - endFrame, enumData->textType[type].c_str(), textId1, textId2); - } - - return StringHelper::Sprintf("CS_TEXT(0x%X, %i, %i, %i, 0x%X, 0x%X)", base, startFrame, - endFrame, type, textId1, textId2); -} - -size_t CutsceneOoTSubCommandEntry_Text::GetRawSize() const -{ - return 0x0C; -} - -CutsceneOoTCommand_Text::CutsceneOoTCommand_Text(const std::vector& rawData, - offset_t rawDataIndex) - : CutsceneCommand(rawData, rawDataIndex) -{ - rawDataIndex += 4; - - entries.reserve(numEntries); - for (size_t i = 0; i < numEntries; i++) - { - auto* entry = new CutsceneOoTSubCommandEntry_Text(rawData, rawDataIndex); - entries.push_back(entry); - rawDataIndex += entry->GetRawSize(); - } -} - -std::string CutsceneOoTCommand_Text::GetCommandMacro() const -{ - return StringHelper::Sprintf("CS_TEXT_LIST(%i)", numEntries); -} - -/**** ACTOR CUE ****/ - -CutsceneOoTSubCommandEntry_ActorCue::CutsceneOoTSubCommandEntry_ActorCue( - const std::vector& rawData, offset_t rawDataIndex) - : CutsceneSubCommandEntry(rawData, rawDataIndex) -{ - rotX = BitConverter::ToUInt16BE(rawData, rawDataIndex + 0x6); - rotY = BitConverter::ToUInt16BE(rawData, rawDataIndex + 0x8); - rotZ = BitConverter::ToUInt16BE(rawData, rawDataIndex + 0xA); - startPosX = BitConverter::ToInt32BE(rawData, rawDataIndex + 0xC); - startPosY = BitConverter::ToInt32BE(rawData, rawDataIndex + 0x10); - startPosZ = BitConverter::ToInt32BE(rawData, rawDataIndex + 0x14); - endPosX = BitConverter::ToInt32BE(rawData, rawDataIndex + 0x18); - endPosY = BitConverter::ToInt32BE(rawData, rawDataIndex + 0x1C); - endPosZ = BitConverter::ToInt32BE(rawData, rawDataIndex + 0x20); - normalX = BitConverter::ToFloatBE(rawData, rawDataIndex + 0x24); - normalY = BitConverter::ToFloatBE(rawData, rawDataIndex + 0x28); - normalZ = BitConverter::ToFloatBE(rawData, rawDataIndex + 0x2C); -} -std::string CutsceneOoTSubCommandEntry_ActorCue::GetBodySourceCode() const -{ - EnumData* enumData = &Globals::Instance->cfg.enumData; - - std::string normalXStr = - ZCutscene::GetCsEncodedFloat(normalX, Globals::Instance->floatType, true); - std::string normalYStr = - ZCutscene::GetCsEncodedFloat(normalY, Globals::Instance->floatType, true); - std::string normalZStr = - ZCutscene::GetCsEncodedFloat(normalZ, Globals::Instance->floatType, true); - - if (static_cast(commandID) == - CutsceneOoT_CommandType::CS_CMD_PLAYER_CUE) - { - return StringHelper::Sprintf("CS_PLAYER_CUE(%s, %i, %i, 0x%04X, 0x%04X, 0x%04X, %i, %i, " - "%i, %i, %i, %i, %s, %s, %s)", - enumData->playerCueId[base].c_str(), startFrame, endFrame, - rotX, rotY, rotZ, startPosX, startPosY, startPosZ, endPosX, - endPosY, endPosZ, normalXStr.c_str(), normalYStr.c_str(), - normalZStr.c_str()); - } - else - { - return StringHelper::Sprintf("CS_ACTOR_CUE(%i, %i, %i, 0x%04X, 0x%04X, 0x%04X, %i, %i, " - "%i, %i, %i, %i, %s, %s, %s)", - base, startFrame, endFrame, rotX, rotY, rotZ, startPosX, - startPosY, startPosZ, endPosX, endPosY, endPosZ, - normalXStr.c_str(), normalYStr.c_str(), normalZStr.c_str()); - } -} - -size_t CutsceneOoTSubCommandEntry_ActorCue::GetRawSize() const -{ - return 0x30; -} - -CutsceneOoTCommand_ActorCue::CutsceneOoTCommand_ActorCue(const std::vector& rawData, - offset_t rawDataIndex) - : CutsceneCommand(rawData, rawDataIndex) -{ - rawDataIndex += 4; - - entries.reserve(numEntries); - for (size_t i = 0; i < numEntries; i++) - { - auto* entry = new CutsceneOoTSubCommandEntry_ActorCue(rawData, rawDataIndex); - entries.push_back(entry); - rawDataIndex += entry->GetRawSize(); - } -} - -std::string CutsceneOoTCommand_ActorCue::GetCommandMacro() const -{ - EnumData* enumData = &Globals::Instance->cfg.enumData; - - if (static_cast(commandID) == - CutsceneOoT_CommandType::CS_CMD_PLAYER_CUE) - { - return StringHelper::Sprintf("CS_PLAYER_CUE_LIST(%i)", entries.size()); - } - - if (enumData->cutsceneCmd.find(commandID) != enumData->cutsceneCmd.end()) - { - return StringHelper::Sprintf("CS_ACTOR_CUE_LIST(%s, %i)", - enumData->cutsceneCmd[commandID].c_str(), entries.size()); - } - - return StringHelper::Sprintf("CS_ACTOR_CUE_LIST(0x%04X, %i)", commandID, entries.size()); -} - -/**** DESTINATION ****/ - -CutsceneOoTCommand_Destination::CutsceneOoTCommand_Destination(const std::vector& rawData, - offset_t rawDataIndex) - : CutsceneCommand(rawData, rawDataIndex) -{ - rawDataIndex += 4; - - base = BitConverter::ToUInt16BE(rawData, rawDataIndex + 0); - startFrame = BitConverter::ToUInt16BE(rawData, rawDataIndex + 2); - endFrame = BitConverter::ToUInt16BE(rawData, rawDataIndex + 4); - unknown = BitConverter::ToUInt16BE(rawData, rawDataIndex + 6); // endFrame duplicate -} - -std::string CutsceneOoTCommand_Destination::GenerateSourceCode() const -{ - EnumData* enumData = &Globals::Instance->cfg.enumData; - - if (enumData->destination.find(base) != enumData->destination.end()) - { - return StringHelper::Sprintf("CS_DESTINATION(%s, %i, %i),\n", - enumData->destination[base].c_str(), startFrame, endFrame); - } - - return StringHelper::Sprintf("CS_DESTINATION(%i, %i, %i),\n", base, startFrame, endFrame); -} - -size_t CutsceneOoTCommand_Destination::GetCommandSize() const -{ - return 0x10; -} - -/**** TRANSITION ****/ - -CutsceneOoTCommand_Transition::CutsceneOoTCommand_Transition(const std::vector& rawData, - offset_t rawDataIndex) - : CutsceneCommand(rawData, rawDataIndex) -{ - rawDataIndex += 4; - - base = BitConverter::ToUInt16BE(rawData, rawDataIndex + 0); - startFrame = BitConverter::ToUInt16BE(rawData, rawDataIndex + 2); - endFrame = BitConverter::ToUInt16BE(rawData, rawDataIndex + 4); -} - -std::string CutsceneOoTCommand_Transition::GenerateSourceCode() const -{ - EnumData* enumData = &Globals::Instance->cfg.enumData; - - if (enumData->transitionType.find(base) != enumData->transitionType.end()) - { - return StringHelper::Sprintf("CS_TRANSITION(%s, %i, %i),\n", - enumData->transitionType[base].c_str(), startFrame, endFrame); - } - - return StringHelper::Sprintf("CS_TRANSITION(%i, %i, %i),\n", base, startFrame, endFrame); -} - -size_t CutsceneOoTCommand_Transition::GetCommandSize() const -{ - return 0x10; -} diff --git a/tools/ZAPD/ZAPD/OtherStructs/CutsceneOoT_Commands.h b/tools/ZAPD/ZAPD/OtherStructs/CutsceneOoT_Commands.h deleted file mode 100644 index ff9b6797c3..0000000000 --- a/tools/ZAPD/ZAPD/OtherStructs/CutsceneOoT_Commands.h +++ /dev/null @@ -1,314 +0,0 @@ -#pragma once - -#include "Cutscene_Common.h" - -// https://github.com/zeldaret/oot/blob/7235af2249843fb68740111b70089bad827a4730/include/z64cutscene.h#L35-L165 -enum class CutsceneOoT_CommandType -{ - CS_CMD_CAM_EYE_SPLINE = 0x01, - CS_CMD_CAM_AT_SPLINE, - CS_CMD_MISC, - CS_CMD_LIGHT_SETTING, - CS_CMD_CAM_EYE_SPLINE_REL_TO_PLAYER, - CS_CMD_CAM_AT_SPLINE_REL_TO_PLAYER, - CS_CMD_CAM_EYE, - CS_CMD_CAM_AT, - CS_CMD_RUMBLE_CONTROLLER, - CS_CMD_PLAYER_CUE, - CS_CMD_UNIMPLEMENTED_B, - CS_CMD_UNIMPLEMENTED_D = 0x0D, - CS_CMD_ACTOR_CUE_1_0, - CS_CMD_ACTOR_CUE_0_0, - CS_CMD_ACTOR_CUE_1_1, - CS_CMD_ACTOR_CUE_0_1, - CS_CMD_ACTOR_CUE_0_2, - CS_CMD_TEXT, - CS_CMD_UNIMPLEMENTED_15 = 0x15, - CS_CMD_UNIMPLEMENTED_16, - CS_CMD_ACTOR_CUE_0_3, - CS_CMD_ACTOR_CUE_1_2, - CS_CMD_ACTOR_CUE_2_0, - CS_CMD_UNIMPLEMENTED_1B = 0x1B, - CS_CMD_UNIMPLEMENTED_1C, - CS_CMD_ACTOR_CUE_3_0, - CS_CMD_ACTOR_CUE_4_0, - CS_CMD_ACTOR_CUE_6_0, - CS_CMD_UNIMPLEMENTED_20, - CS_CMD_UNIMPLEMENTED_21, - CS_CMD_ACTOR_CUE_0_4, - CS_CMD_ACTOR_CUE_1_3, - CS_CMD_ACTOR_CUE_2_1, - CS_CMD_ACTOR_CUE_3_1, - CS_CMD_ACTOR_CUE_4_1, - CS_CMD_ACTOR_CUE_0_5, - CS_CMD_ACTOR_CUE_1_4, - CS_CMD_ACTOR_CUE_2_2, - CS_CMD_ACTOR_CUE_3_2, - CS_CMD_ACTOR_CUE_4_2, - CS_CMD_ACTOR_CUE_5_0, - CS_CMD_TRANSITION, - CS_CMD_ACTOR_CUE_0_6, - CS_CMD_ACTOR_CUE_4_3, - CS_CMD_ACTOR_CUE_1_5, - CS_CMD_ACTOR_CUE_7_0, - CS_CMD_ACTOR_CUE_2_3, - CS_CMD_ACTOR_CUE_3_3, - CS_CMD_ACTOR_CUE_6_1, - CS_CMD_ACTOR_CUE_3_4, - CS_CMD_ACTOR_CUE_4_4, - CS_CMD_ACTOR_CUE_5_1, - CS_CMD_ACTOR_CUE_6_2 = 0x39, - CS_CMD_ACTOR_CUE_6_3, - CS_CMD_UNIMPLEMENTED_3B, - CS_CMD_ACTOR_CUE_7_1, - CS_CMD_UNIMPLEMENTED_3D, - CS_CMD_ACTOR_CUE_8_0, - CS_CMD_ACTOR_CUE_3_5, - CS_CMD_ACTOR_CUE_1_6, - CS_CMD_ACTOR_CUE_3_6, - CS_CMD_ACTOR_CUE_3_7, - CS_CMD_ACTOR_CUE_2_4, - CS_CMD_ACTOR_CUE_1_7, - CS_CMD_ACTOR_CUE_2_5, - CS_CMD_ACTOR_CUE_1_8, - CS_CMD_UNIMPLEMENTED_47, - CS_CMD_ACTOR_CUE_2_6, - CS_CMD_UNIMPLEMENTED_49, - CS_CMD_ACTOR_CUE_2_7, - CS_CMD_ACTOR_CUE_3_8, - CS_CMD_ACTOR_CUE_0_7, - CS_CMD_ACTOR_CUE_5_2, - CS_CMD_ACTOR_CUE_1_9, - CS_CMD_ACTOR_CUE_4_5, - CS_CMD_ACTOR_CUE_1_10, - CS_CMD_ACTOR_CUE_2_8, - CS_CMD_ACTOR_CUE_3_9, - CS_CMD_ACTOR_CUE_4_6, - CS_CMD_ACTOR_CUE_5_3, - CS_CMD_ACTOR_CUE_0_8, - CS_CMD_START_SEQ, - CS_CMD_STOP_SEQ, - CS_CMD_ACTOR_CUE_6_4, - CS_CMD_ACTOR_CUE_7_2, - CS_CMD_ACTOR_CUE_5_4, - CS_CMD_ACTOR_CUE_0_9 = 0x5D, - CS_CMD_ACTOR_CUE_1_11, - CS_CMD_ACTOR_CUE_0_10 = 0x69, - CS_CMD_ACTOR_CUE_2_9, - CS_CMD_ACTOR_CUE_0_11, - CS_CMD_ACTOR_CUE_3_10, - CS_CMD_UNIMPLEMENTED_6D, - CS_CMD_ACTOR_CUE_0_12, - CS_CMD_ACTOR_CUE_7_3, - CS_CMD_UNIMPLEMENTED_70, - CS_CMD_UNIMPLEMENTED_71, - CS_CMD_ACTOR_CUE_7_4, - CS_CMD_ACTOR_CUE_6_5, - CS_CMD_ACTOR_CUE_1_12, - CS_CMD_ACTOR_CUE_2_10, - CS_CMD_ACTOR_CUE_1_13, - CS_CMD_ACTOR_CUE_0_13, - CS_CMD_ACTOR_CUE_1_14, - CS_CMD_ACTOR_CUE_2_11, - CS_CMD_ACTOR_CUE_0_14 = 0x7B, - CS_CMD_FADE_OUT_SEQ, - CS_CMD_ACTOR_CUE_1_15, - CS_CMD_ACTOR_CUE_2_12, - CS_CMD_ACTOR_CUE_3_11, - CS_CMD_ACTOR_CUE_4_7, - CS_CMD_ACTOR_CUE_5_5, - CS_CMD_ACTOR_CUE_6_6, - CS_CMD_ACTOR_CUE_1_16, - CS_CMD_ACTOR_CUE_2_13, - CS_CMD_ACTOR_CUE_3_12, - CS_CMD_ACTOR_CUE_7_5, - CS_CMD_ACTOR_CUE_4_8, - CS_CMD_ACTOR_CUE_5_6, - CS_CMD_ACTOR_CUE_6_7, - CS_CMD_ACTOR_CUE_0_15, - CS_CMD_ACTOR_CUE_0_16, - CS_CMD_TIME, - CS_CMD_ACTOR_CUE_1_17, - CS_CMD_ACTOR_CUE_7_6, - CS_CMD_ACTOR_CUE_9_0, - CS_CMD_ACTOR_CUE_0_17, - CS_CMD_DESTINATION = 0x03E8, - CS_CMD_END = 0xFFFF -}; - -/**** GENERIC ****/ - -class CutsceneOoTSubCommandEntry_GenericCmd : public CutsceneSubCommandEntry -{ -public: - CutsceneOoT_CommandType commandId; - - uint32_t word0 = 0; - uint32_t word1 = 0; - - uint32_t unused1 = 0; - uint32_t unused2 = 0; - uint32_t unused3 = 0; - uint32_t unused4 = 0; - uint32_t unused5 = 0; - uint32_t unused6 = 0; - uint32_t unused7 = 0; - uint32_t unused8 = 0; - uint32_t unused9 = 0; - uint32_t unused10 = 0; - - CutsceneOoTSubCommandEntry_GenericCmd(const std::vector& rawData, - offset_t rawDataIndex, CutsceneOoT_CommandType cmdId); - - std::string GetBodySourceCode() const override; - - size_t GetRawSize() const override; -}; - -class CutsceneOoTCommand_GenericCmd : public CutsceneCommand -{ -public: - CutsceneOoTCommand_GenericCmd(const std::vector& rawData, offset_t rawDataIndex, - CutsceneOoT_CommandType cmdId); - - std::string GetCommandMacro() const override; -}; - -/**** CAMERA ****/ - -class CutsceneOoTCommand_CameraPoint : public CutsceneSubCommandEntry -{ -public: - int8_t continueFlag; - int8_t cameraRoll; - int16_t nextPointFrame; - float viewAngle; - int16_t posX, posY, posZ; - int16_t unused; - - CutsceneOoTCommand_CameraPoint(const std::vector& rawData, offset_t rawDataIndex); - - std::string GetBodySourceCode() const override; - - size_t GetRawSize() const override; -}; - -class CutsceneOoTCommand_GenericCameraCmd : public CutsceneCommand -{ -public: - uint16_t base; - uint16_t startFrame; - uint16_t endFrame; - uint16_t unused; - - CutsceneOoTCommand_GenericCameraCmd(const std::vector& rawData, offset_t rawDataIndex); - - std::string GetCommandMacro() const override; - - size_t GetCommandSize() const override; -}; - -/**** TRANSITION ****/ - -class CutsceneOoTCommand_Transition : public CutsceneCommand -{ -public: - uint16_t base; - uint16_t startFrame; - uint16_t endFrame; - - CutsceneOoTCommand_Transition(const std::vector& rawData, offset_t rawDataIndex); - - std::string GenerateSourceCode() const override; - size_t GetCommandSize() const override; -}; - -/**** RUMBLE ****/ - -class CutsceneOoTSubCommandEntry_Rumble : public CutsceneSubCommandEntry -{ -public: - uint8_t sourceStrength; - uint8_t duration; - uint8_t decreaseRate; - uint8_t unk_09; - uint8_t unk_0A; - - CutsceneOoTSubCommandEntry_Rumble(const std::vector& rawData, offset_t rawDataIndex); - - std::string GetBodySourceCode() const override; - - size_t GetRawSize() const override; -}; - -class CutsceneOoTCommand_Rumble : public CutsceneCommand -{ -public: - CutsceneOoTCommand_Rumble(const std::vector& rawData, offset_t rawDataIndex); - - std::string GetCommandMacro() const override; -}; - -/**** TEXT ****/ - -class CutsceneOoTSubCommandEntry_Text : public CutsceneSubCommandEntry -{ -public: - uint16_t type; - uint16_t textId1; - uint16_t textId2; - - CutsceneOoTSubCommandEntry_Text(const std::vector& rawData, offset_t rawDataIndex); - - std::string GetBodySourceCode() const override; - - size_t GetRawSize() const override; -}; - -class CutsceneOoTCommand_Text : public CutsceneCommand -{ -public: - CutsceneOoTCommand_Text(const std::vector& rawData, offset_t rawDataIndex); - - std::string GetCommandMacro() const override; -}; - -/**** ACTOR CUE ****/ - -class CutsceneOoTSubCommandEntry_ActorCue : public CutsceneSubCommandEntry -{ -public: - uint16_t rotX, rotY, rotZ; - int32_t startPosX, startPosY, startPosZ; - int32_t endPosX, endPosY, endPosZ; - float normalX, normalY, normalZ; - - CutsceneOoTSubCommandEntry_ActorCue(const std::vector& rawData, offset_t rawDataIndex); - std::string GetBodySourceCode() const override; - - size_t GetRawSize() const override; -}; - -class CutsceneOoTCommand_ActorCue : public CutsceneCommand -{ -public: - CutsceneOoTCommand_ActorCue(const std::vector& rawData, offset_t rawDataIndex); - - std::string GetCommandMacro() const override; -}; - -/**** DESTINATION ****/ - -class CutsceneOoTCommand_Destination : public CutsceneCommand -{ -public: - uint16_t base; - uint16_t startFrame; - uint16_t endFrame; - uint16_t unknown; - - CutsceneOoTCommand_Destination(const std::vector& rawData, offset_t rawDataIndex); - - std::string GenerateSourceCode() const override; - size_t GetCommandSize() const override; -}; diff --git a/tools/ZAPD/ZAPD/OtherStructs/Cutscene_Common.cpp b/tools/ZAPD/ZAPD/OtherStructs/Cutscene_Common.cpp deleted file mode 100644 index a5ea609af8..0000000000 --- a/tools/ZAPD/ZAPD/OtherStructs/Cutscene_Common.cpp +++ /dev/null @@ -1,128 +0,0 @@ -#include "Cutscene_Common.h" -#include "Utils/BitConverter.h" -#include "Utils/StringHelper.h" - -/* CutsceneSubCommandEntry */ - -CutsceneSubCommandEntry::CutsceneSubCommandEntry(const std::vector& rawData, - offset_t rawDataIndex) -{ - base = BitConverter::ToUInt16BE(rawData, rawDataIndex + 0); - startFrame = BitConverter::ToUInt16BE(rawData, rawDataIndex + 2); - endFrame = BitConverter::ToUInt16BE(rawData, rawDataIndex + 4); - pad = BitConverter::ToUInt16BE(rawData, rawDataIndex + 6); -} - -std::string CutsceneSubCommandEntry::GetBodySourceCode() const -{ - return StringHelper::Sprintf("CMD_HH(0x%04X, 0x%04X), CMD_HH(0x%04X, 0x%04X)", base, startFrame, - endFrame, pad); -} - -size_t CutsceneSubCommandEntry::GetRawSize() const -{ - return 0x08; -} - -/* CutsceneCommand */ - -CutsceneCommand::CutsceneCommand(const std::vector& rawData, offset_t rawDataIndex) -{ - numEntries = BitConverter::ToUInt32BE(rawData, rawDataIndex + 0); -} - -CutsceneCommand::~CutsceneCommand() -{ - for (auto entry : entries) - { - delete entry; - } -} - -std::string CutsceneCommand::GetCommandMacro() const -{ - return StringHelper::Sprintf("CMD_W(0x%08X), CMD_W(0x%08X)", commandID, numEntries); -} - -std::string CutsceneCommand::GenerateSourceCode() const -{ - std::string result; - - result += GetCommandMacro(); - result += ",\n"; - - for (auto& entry : entries) - { - result += " "; - result += entry->GetBodySourceCode(); - result += ",\n"; - } - - return result; -} - -size_t CutsceneCommand::GetCommandSize() const -{ - size_t size = 0; - if (entries.size() > 0) - { - size = entries.at(0)->GetRawSize() * entries.size(); - } - else - { - size = 0x08 * numEntries; - } - return 0x08 + size; -} - -void CutsceneCommand::SetCommandID(uint32_t nCommandID) -{ - commandID = nCommandID; - - for (auto& entry : entries) - { - entry->commandID = commandID; - } -} - -/*** TIME ****/ - -CutsceneSubCommandEntry_SetTime::CutsceneSubCommandEntry_SetTime( - const std::vector& rawData, offset_t rawDataIndex) - : CutsceneSubCommandEntry(rawData, rawDataIndex) -{ - hour = BitConverter::ToUInt8BE(rawData, rawDataIndex + 6); - minute = BitConverter::ToUInt8BE(rawData, rawDataIndex + 7); -} - -std::string CutsceneSubCommandEntry_SetTime::GetBodySourceCode() const -{ - // Note: Both OoT and MM have the first argument unused - return StringHelper::Sprintf("CS_TIME(%i, %i, %i, %i, %i)", base, startFrame, endFrame, hour, - minute); -} - -size_t CutsceneSubCommandEntry_SetTime::GetRawSize() const -{ - return 0x0C; -} - -CutsceneCommand_Time::CutsceneCommand_Time(const std::vector& rawData, - offset_t rawDataIndex) - : CutsceneCommand(rawData, rawDataIndex) -{ - rawDataIndex += 4; - - entries.reserve(numEntries); - for (size_t i = 0; i < numEntries; i++) - { - auto* entry = new CutsceneSubCommandEntry_SetTime(rawData, rawDataIndex); - entries.push_back(entry); - rawDataIndex += entry->GetRawSize(); - } -} - -std::string CutsceneCommand_Time::GetCommandMacro() const -{ - return StringHelper::Sprintf("CS_TIME_LIST(%i)", numEntries); -} diff --git a/tools/ZAPD/ZAPD/OtherStructs/Cutscene_Common.h b/tools/ZAPD/ZAPD/OtherStructs/Cutscene_Common.h deleted file mode 100644 index 9d8dcf63de..0000000000 --- a/tools/ZAPD/ZAPD/OtherStructs/Cutscene_Common.h +++ /dev/null @@ -1,72 +0,0 @@ -#pragma once - -#include -#include -#include -#include "Declaration.h" - -typedef struct CsCommandListDescriptor -{ - const char* cmdMacro; - const char* args; -} CsCommandListDescriptor; - -class CutsceneSubCommandEntry -{ -public: - uint16_t base; - uint16_t startFrame; - uint16_t endFrame; - uint16_t pad; - - uint32_t commandID; - - CutsceneSubCommandEntry(const std::vector& rawData, offset_t rawDataIndex); - virtual ~CutsceneSubCommandEntry() = default; - - virtual std::string GetBodySourceCode() const; - - virtual size_t GetRawSize() const; -}; - -class CutsceneCommand -{ -public: - uint32_t commandID; - uint32_t commandIndex; - - uint32_t numEntries; - std::vector entries; - - CutsceneCommand(const std::vector& rawData, offset_t rawDataIndex); - virtual ~CutsceneCommand(); - - virtual std::string GetCommandMacro() const; - virtual std::string GenerateSourceCode() const; - virtual size_t GetCommandSize() const; - - virtual void SetCommandID(uint32_t nCommandID); -}; - -/**** TIME ****/ - -class CutsceneSubCommandEntry_SetTime : public CutsceneSubCommandEntry -{ -public: - uint8_t hour; - uint8_t minute; - - CutsceneSubCommandEntry_SetTime(const std::vector& rawData, offset_t rawDataIndex); - - std::string GetBodySourceCode() const override; - - size_t GetRawSize() const override; -}; - -class CutsceneCommand_Time : public CutsceneCommand -{ -public: - CutsceneCommand_Time(const std::vector& rawData, offset_t rawDataIndex); - - std::string GetCommandMacro() const override; -}; diff --git a/tools/ZAPD/ZAPD/OtherStructs/SkinLimbStructs.cpp b/tools/ZAPD/ZAPD/OtherStructs/SkinLimbStructs.cpp deleted file mode 100644 index e85bdefe76..0000000000 --- a/tools/ZAPD/ZAPD/OtherStructs/SkinLimbStructs.cpp +++ /dev/null @@ -1,354 +0,0 @@ -#include "SkinLimbStructs.h" - -#include "Globals.h" -#include "Utils/BitConverter.h" -#include "Utils/StringHelper.h" -#include "ZDisplayList.h" -#include "ZFile.h" - -/* SkinVertex */ - -SkinVertex::SkinVertex(ZFile* nParent) : ZResource(nParent) -{ -} - -void SkinVertex::ParseRawData() -{ - const auto& rawData = parent->GetRawData(); - - index = BitConverter::ToUInt16BE(rawData, rawDataIndex + 0x00); - s = BitConverter::ToInt16BE(rawData, rawDataIndex + 0x02); - t = BitConverter::ToInt16BE(rawData, rawDataIndex + 0x04); - normX = BitConverter::ToInt8BE(rawData, rawDataIndex + 0x06); - normY = BitConverter::ToInt8BE(rawData, rawDataIndex + 0x07); - normZ = BitConverter::ToInt8BE(rawData, rawDataIndex + 0x08); - alpha = BitConverter::ToUInt8BE(rawData, rawDataIndex + 0x09); -} - -std::string SkinVertex::GetBodySourceCode() const -{ - return StringHelper::Sprintf("0x%02X, %i, %i, %i, %i, %i, 0x%02X", index, s, t, normX, normY, - normZ, alpha); -} - -std::string SkinVertex::GetSourceTypeName() const -{ - return "SkinVertex"; -} - -ZResourceType SkinVertex::GetResourceType() const -{ - // TODO - return ZResourceType::Error; -} - -size_t SkinVertex::GetRawDataSize() const -{ - return 0x0A; -} - -/* SkinTransformation */ - -SkinTransformation::SkinTransformation(ZFile* nParent) : ZResource(nParent) -{ -} - -void SkinTransformation::ParseRawData() -{ - const auto& rawData = parent->GetRawData(); - - limbIndex = BitConverter::ToUInt8BE(rawData, rawDataIndex + 0x00); - x = BitConverter::ToInt16BE(rawData, rawDataIndex + 0x02); - y = BitConverter::ToInt16BE(rawData, rawDataIndex + 0x04); - z = BitConverter::ToInt16BE(rawData, rawDataIndex + 0x06); - scale = BitConverter::ToUInt8BE(rawData, rawDataIndex + 0x08); -} - -std::string SkinTransformation::GetBodySourceCode() const -{ - return StringHelper::Sprintf("0x%02X, %i, %i, %i, 0x%02X", limbIndex, x, y, z, scale); -} - -std::string SkinTransformation::GetSourceTypeName() const -{ - return "SkinTransformation"; -} - -ZResourceType SkinTransformation::GetResourceType() const -{ - // TODO - return ZResourceType::Error; -} - -size_t SkinTransformation::GetRawDataSize() const -{ - return 0x0A; -} - -/* SkinLimbModif */ - -SkinLimbModif::SkinLimbModif(ZFile* nParent) : ZResource(nParent) -{ -} - -void SkinLimbModif::ParseRawData() -{ - const auto& rawData = parent->GetRawData(); - - vtxCount = BitConverter::ToUInt16BE(rawData, rawDataIndex + 0x00); - transformCount = BitConverter::ToUInt16BE(rawData, rawDataIndex + 0x02); - unk_4 = BitConverter::ToUInt16BE(rawData, rawDataIndex + 0x04); - skinVertices = BitConverter::ToUInt32BE(rawData, rawDataIndex + 0x08); - limbTransformations = BitConverter::ToUInt32BE(rawData, rawDataIndex + 0x0C); - - if (skinVertices != 0 && GETSEGNUM(skinVertices) == parent->segment) - { - uint32_t unk_8_Offset = Seg2Filespace(skinVertices, parent->baseAddress); - - skinVertices_arr.reserve(vtxCount); - for (size_t i = 0; i < vtxCount; i++) - { - SkinVertex skinVertices_data(parent); - skinVertices_data.ExtractFromFile(unk_8_Offset); - skinVertices_arr.push_back(skinVertices_data); - - unk_8_Offset += skinVertices_data.GetRawDataSize(); - } - } - - if (limbTransformations != 0 && GETSEGNUM(skinVertices) == parent->segment) - { - uint32_t unk_C_Offset = Seg2Filespace(limbTransformations, parent->baseAddress); - - limbTransformations_arr.reserve(transformCount); - for (size_t i = 0; i < transformCount; i++) - { - SkinTransformation limbTransformations_data(parent); - limbTransformations_data.ExtractFromFile(unk_C_Offset); - limbTransformations_arr.push_back(limbTransformations_data); - - unk_C_Offset += limbTransformations_data.GetRawDataSize(); - } - } -} - -void SkinLimbModif::DeclareReferences(const std::string& prefix) -{ - std::string varPrefix = prefix; - if (name != "") - varPrefix = name; - - if (skinVertices != 0 && GETSEGNUM(skinVertices) == parent->segment) - { - const auto& res = skinVertices_arr.at(0); - std::string unk_8_Str = res.GetDefaultName(varPrefix); - - size_t arrayItemCnt = skinVertices_arr.size(); - std::string entryStr = ""; - - for (size_t i = 0; i < arrayItemCnt; i++) - { - auto& child = skinVertices_arr[i]; - child.DeclareReferences(varPrefix); - entryStr += StringHelper::Sprintf("\t{ %s },", child.GetBodySourceCode().c_str()); - - if (i < arrayItemCnt - 1) - entryStr += "\n"; - } - - uint32_t skinVertices_Offset = Seg2Filespace(skinVertices, parent->baseAddress); - Declaration* decl = parent->GetDeclaration(skinVertices_Offset); - if (decl == nullptr) - { - parent->AddDeclarationArray(skinVertices_Offset, res.GetDeclarationAlignment(), - arrayItemCnt * res.GetRawDataSize(), - res.GetSourceTypeName(), unk_8_Str, arrayItemCnt, entryStr); - } - else - decl->declBody = entryStr; - } - - if (limbTransformations != 0 && GETSEGNUM(limbTransformations) == parent->segment) - { - const auto& res = limbTransformations_arr.at(0); - std::string unk_C_Str = res.GetDefaultName(varPrefix); - - size_t arrayItemCnt = limbTransformations_arr.size(); - std::string entryStr = ""; - - for (size_t i = 0; i < arrayItemCnt; i++) - { - auto& child = limbTransformations_arr[i]; - child.DeclareReferences(varPrefix); - entryStr += StringHelper::Sprintf("\t{ %s },", child.GetBodySourceCode().c_str()); - - if (i < arrayItemCnt - 1) - entryStr += "\n"; - } - - uint32_t unk_C_Offset = Seg2Filespace(limbTransformations, parent->baseAddress); - Declaration* decl = parent->GetDeclaration(unk_C_Offset); - if (decl == nullptr) - { - parent->AddDeclarationArray(unk_C_Offset, res.GetDeclarationAlignment(), - arrayItemCnt * res.GetRawDataSize(), - res.GetSourceTypeName(), unk_C_Str, arrayItemCnt, entryStr); - } - else - decl->declBody = entryStr; - } -} - -std::string SkinLimbModif::GetBodySourceCode() const -{ - std::string skinVertices_Str; - std::string unk_C_Str; - Globals::Instance->GetSegmentedPtrName(skinVertices, parent, "SkinVertex", skinVertices_Str); - Globals::Instance->GetSegmentedPtrName(limbTransformations, parent, "SkinTransformation", - unk_C_Str); - - std::string entryStr = StringHelper::Sprintf("\n\t\tARRAY_COUNTU(%s), ARRAY_COUNTU(%s),\n", - skinVertices_Str.c_str(), unk_C_Str.c_str()); - entryStr += StringHelper::Sprintf("\t\t%i, %s, %s\n\t", unk_4, skinVertices_Str.c_str(), - unk_C_Str.c_str()); - - return entryStr; -} - -std::string SkinLimbModif::GetSourceTypeName() const -{ - return "SkinLimbModif"; -} - -ZResourceType SkinLimbModif::GetResourceType() const -{ - // TODO - return ZResourceType::Error; -} - -size_t SkinLimbModif::GetRawDataSize() const -{ - return 0x10; -} - -/* SkinAnimatedLimbData */ - -SkinAnimatedLimbData::SkinAnimatedLimbData(ZFile* nParent) : ZResource(nParent) -{ -} - -void SkinAnimatedLimbData::ParseRawData() -{ - const auto& rawData = parent->GetRawData(); - - totalVtxCount = BitConverter::ToUInt16BE(rawData, rawDataIndex + 0x00); - limbModifCount = BitConverter::ToUInt16BE(rawData, rawDataIndex + 0x02); - limbModifications = BitConverter::ToUInt32BE(rawData, rawDataIndex + 0x04); - dlist = BitConverter::ToUInt32BE(rawData, rawDataIndex + 0x08); - - if (limbModifications != 0 && GETSEGNUM(limbModifications) == parent->segment) - { - uint32_t limbModifications_Offset = Seg2Filespace(limbModifications, parent->baseAddress); - - limbModifications_arr.reserve(limbModifCount); - for (size_t i = 0; i < limbModifCount; i++) - { - SkinLimbModif limbModifications_data(parent); - limbModifications_data.ExtractFromFile(limbModifications_Offset); - limbModifications_arr.push_back(limbModifications_data); - - limbModifications_Offset += limbModifications_data.GetRawDataSize(); - } - } -} - -void SkinAnimatedLimbData::DeclareReferences(const std::string& prefix) -{ - std::string varPrefix = prefix; - if (name != "") - varPrefix = name; - - ZResource::DeclareReferences(varPrefix); - - if (limbModifications != SEGMENTED_NULL && GETSEGNUM(limbModifications) == parent->segment) - { - const auto& res = limbModifications_arr.at(0); - std::string limbModifications_Str = res.GetDefaultName(varPrefix); - - size_t arrayItemCnt = limbModifications_arr.size(); - std::string entryStr = ""; - - for (size_t i = 0; i < arrayItemCnt; i++) - { - auto& child = limbModifications_arr[i]; - child.DeclareReferences(varPrefix); - entryStr += StringHelper::Sprintf("\t{ %s },", child.GetBodySourceCode().c_str()); - - if (i < arrayItemCnt - 1) - entryStr += "\n"; - } - - uint32_t limbModifications_Offset = Seg2Filespace(limbModifications, parent->baseAddress); - Declaration* decl = parent->GetDeclaration(limbModifications_Offset); - if (decl == nullptr) - { - parent->AddDeclarationArray(limbModifications_Offset, res.GetDeclarationAlignment(), - arrayItemCnt * res.GetRawDataSize(), - res.GetSourceTypeName(), limbModifications_Str, - arrayItemCnt, entryStr); - } - else - decl->declBody = entryStr; - } - - if (dlist != SEGMENTED_NULL && GETSEGNUM(dlist) == parent->segment) - { - uint32_t dlist_Offset = Seg2Filespace(dlist, parent->baseAddress); - - int32_t dlistLength = ZDisplayList::GetDListLength( - parent->GetRawData(), dlist_Offset, - Globals::Instance->game == ZGame::OOT_SW97 ? DListType::F3DEX : DListType::F3DZEX); - ZDisplayList* dlist_data = new ZDisplayList(parent); - dlist_data->ExtractFromBinary(dlist_Offset, dlistLength); - - std::string dListStr = - StringHelper::Sprintf("%sSkinLimbDL_%06X", varPrefix.c_str(), dlist_Offset); - dlist_data->SetName(dListStr); - dlist_data->DeclareVar(varPrefix, ""); - dlist_data->DeclareReferences(varPrefix); - parent->AddResource(dlist_data); - } -} - -std::string SkinAnimatedLimbData::GetBodySourceCode() const -{ - std::string limbModifications_Str; - std::string dlist_Str; - Globals::Instance->GetSegmentedPtrName(limbModifications, parent, "SkinLimbModif", - limbModifications_Str); - Globals::Instance->GetSegmentedPtrName(dlist, parent, "Gfx", dlist_Str); - - std::string entryStr = "\n"; - entryStr += StringHelper::Sprintf("\t%i, ARRAY_COUNTU(%s),\n", totalVtxCount, - limbModifications_Str.c_str()); - entryStr += - StringHelper::Sprintf("\t%s, %s\n", limbModifications_Str.c_str(), dlist_Str.c_str()); - - return entryStr; -} - -std::string SkinAnimatedLimbData::GetSourceTypeName() const -{ - return "SkinAnimatedLimbData"; -} - -ZResourceType SkinAnimatedLimbData::GetResourceType() const -{ - // TODO - return ZResourceType::Error; -} - -size_t SkinAnimatedLimbData::GetRawDataSize() const -{ - return 0x0C; -} diff --git a/tools/ZAPD/ZAPD/OtherStructs/SkinLimbStructs.h b/tools/ZAPD/ZAPD/OtherStructs/SkinLimbStructs.h deleted file mode 100644 index f338ebeddc..0000000000 --- a/tools/ZAPD/ZAPD/OtherStructs/SkinLimbStructs.h +++ /dev/null @@ -1,111 +0,0 @@ -#pragma once - -#include -#include -#include - -#include "ZResource.h" - -enum class ZLimbSkinType -{ - SkinType_Null, // SkinLimb segment = NULL - SkinType_Animated = 4, // SkinLimb segment = SkinAnimatedLimbData* - SkinType_Normal = 11, // SkinLimb segment = Gfx* -}; - -class SkinVertex : public ZResource -{ -public: - SkinVertex(ZFile* nParent); - - void ParseRawData() override; - - std::string GetBodySourceCode() const override; - - std::string GetSourceTypeName() const override; - ZResourceType GetResourceType() const override; - - size_t GetRawDataSize() const override; - -protected: - uint16_t index; - int16_t s; - int16_t t; - int8_t normX; - int8_t normY; - int8_t normZ; - uint8_t alpha; -}; - -class SkinTransformation : public ZResource -{ -public: - SkinTransformation(ZFile* nParent); - - void ParseRawData() override; - - std::string GetBodySourceCode() const override; - - std::string GetSourceTypeName() const override; - ZResourceType GetResourceType() const override; - - size_t GetRawDataSize() const override; - -protected: - uint8_t limbIndex; - int16_t x; - int16_t y; - int16_t z; - uint8_t scale; -}; - -class SkinLimbModif : public ZResource -{ -public: - SkinLimbModif(ZFile* nParent); - - void ParseRawData() override; - void DeclareReferences(const std::string& prefix) override; - - std::string GetBodySourceCode() const override; - - std::string GetSourceTypeName() const override; - ZResourceType GetResourceType() const override; - - size_t GetRawDataSize() const override; - -protected: - uint16_t vtxCount; // Number of vertices in this modif entry - uint16_t transformCount; // Length of limbTransformations - uint16_t unk_4; // 0 or 1, used as an index for limbTransformations - segptr_t skinVertices; // SkinVertex* - segptr_t limbTransformations; // SkinTransformation* - - std::vector skinVertices_arr; - std::vector limbTransformations_arr; -}; - -class SkinAnimatedLimbData : public ZResource -{ -public: - SkinAnimatedLimbData(ZFile* nParent); - - void ParseRawData() override; - void DeclareReferences(const std::string& prefix) override; - - std::string GetBodySourceCode() const override; - - std::string GetSourceTypeName() const override; - ZResourceType GetResourceType() const override; - - size_t GetRawDataSize() const override; - -protected: - uint16_t totalVtxCount; - uint16_t limbModifCount; // Length of limbModifications - segptr_t limbModifications; // SkinLimbModif* - segptr_t dlist; // Gfx* - - std::vector limbModifications_arr; - // ZDisplayList* unk_8_dlist = nullptr; -}; diff --git a/tools/ZAPD/ZAPD/OutputFormatter.cpp b/tools/ZAPD/ZAPD/OutputFormatter.cpp deleted file mode 100644 index 393ec1936a..0000000000 --- a/tools/ZAPD/ZAPD/OutputFormatter.cpp +++ /dev/null @@ -1,115 +0,0 @@ -#include "OutputFormatter.h" - -void OutputFormatter::Flush() -{ - if (col > lineLimit) - { - str.append(1, '\n'); - str.append(currentIndent, ' '); - - uint32_t newCol = currentIndent + (wordP - word); - - for (uint32_t i = 0; i < wordNests; i++) - nestIndent[nest - i] -= col - newCol; - - col = newCol; - } - else - { - str.append(space, spaceP - space); - } - spaceP = space; - - str.append(word, wordP - word); - wordP = word; - wordNests = 0; -} - -int OutputFormatter::Write(const char* buf, int count) -{ - for (int i = 0; i < count; i++) - { - char c = buf[i]; - - if (c == ' ' || c == '\t' || c == '\n') - { - if (wordP - word != 0) - { - Flush(); - } - - if (c == '\n') - { - col = 0; - *spaceP++ = c; - } - else if (c == '\t') - { - int n = tabSize - (col % tabSize); - col += n; - for (int j = 0; j < n; j++) - *spaceP++ = ' '; - } - else - { - col++; - *spaceP++ = c; - } - - currentIndent = nestIndent[nest]; - } - else - { - col++; - - if (c == '(') - { - nest++; - nestIndent[nest] = col; - wordNests++; - } - else if (c == ')') - { - if (nest > 0) - nest--; - if (wordNests > 0) - wordNests--; - } - - *wordP++ = c; - } - } - - return count; -} - -int OutputFormatter::Write(const std::string& buf) -{ - return Write(buf.data(), buf.size()); -} - -OutputFormatter* OutputFormatter::Instance; - -int OutputFormatter::WriteStatic(const char* buf, int count) -{ - return Instance->Write(buf, count); -} - -int (*OutputFormatter::StaticWriter())(const char* buf, int count) -{ - Instance = this; - return &WriteStatic; -} - -OutputFormatter::OutputFormatter(uint32_t tabSize, uint32_t indentation, uint32_t lineLimit) - : tabSize{tabSize}, lineLimit{lineLimit}, col{0}, nest{0}, nestIndent{indentation}, - currentIndent{indentation}, wordNests(0), wordP{word}, spaceP{space} -{ -} - -std::string OutputFormatter::GetOutput() -{ - Flush(); - - return std::move(str); -} diff --git a/tools/ZAPD/ZAPD/OutputFormatter.h b/tools/ZAPD/ZAPD/OutputFormatter.h deleted file mode 100644 index ec56b654da..0000000000 --- a/tools/ZAPD/ZAPD/OutputFormatter.h +++ /dev/null @@ -1,41 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -class OutputFormatter -{ -private: - const uint32_t tabSize; - const uint32_t lineLimit; - - uint32_t col; - uint32_t nest; - uint32_t nestIndent[8]; - uint32_t currentIndent; - uint32_t wordNests; - - char word[128]; - char space[128]; - char* wordP; - char* spaceP; - - std::string str; - - void Flush(); - - static OutputFormatter* Instance; - static int WriteStatic(const char* buf, int count); - -public: - OutputFormatter(uint32_t tabSize = 4, uint32_t indentation = 4, uint32_t lineLimit = 120); - - int (*StaticWriter())(const char* buf, int count); // Must be `int` due to libgfxd - - int Write(const char* buf, int count); - int Write(const std::string& buf); - - std::string GetOutput(); -}; diff --git a/tools/ZAPD/ZAPD/WarningHandler.cpp b/tools/ZAPD/ZAPD/WarningHandler.cpp deleted file mode 100644 index f416a5b80c..0000000000 --- a/tools/ZAPD/ZAPD/WarningHandler.cpp +++ /dev/null @@ -1,455 +0,0 @@ -/** - * ZAPD Warning- and Error-handling system - * ======================================= - * - * This provides a common standard way to write ZAPD warnings/errors, which should be used for all - * such. It will pretty-print them in a uniform way, with styles defined in the header. - * - * Warnings/errors should be constructed using the macros given in the header; there are now plenty - * of examples in the codebase of how to do this. Their purposes are noted above each category in - * the header. Each warning has a type, one of the ones in warningStringToInitMap, or - * WarningType::Always, which is used for warnings that cannot be disabled and do not display a - * type. - * - * Currently there are three levels of alert a warning can have: - * - Off (does not display anything) - * - Warn (print a warning but continue processing) - * - Err (behave like an error, i.e. print and throw an exception to crash ZAPD when occurs) - * - * Flag use: - * - -Wfoo enables warnings of type foo - * - -Wno-foo disables warnings of type foo - * - -Werror=foo escalates foo to behave like an error - * - -Weverything enables all warnings - * - -Werror escalates all enabled warnings to errors - * - * Errors do not have types, and will always throw an exception; they cannot be disabled. - * - * Format - * === - * Each printed warning/error contains the same three sections: - * - Preamble: automatically generated; the content varies depending on category. It will print the - * file and function that the warning is from, and information about the files being processed - * or extracted. - * - Header: begins with 'warning: ' or 'error:', should contain essential information about the - * warning/error, ends with the warning type if applicable. Printed with emphasis to make it - * stand out. Does not start with a capital letter or end with a '.' - * - Body (optional): indented, should contain further diagnostic information useful for identifying - * and fixing the warning/error. Can be a sentence with captialisation and '.' on the end. - * - * Please think of what the end user will find most useful when writing the header and body, and try - * to keep it brief without sacrificing important information! Also remember that if the user is - * only looking at stderr, they will normally have no other context. - * - * Warning vs error - * === - * The principle that we have operated on so far is - * - issue a warning if ZAPD will still be able to produce a valid, compilable C file that will - * match - * - if this cannot happen, use an error. - * but at the end of the day, it is up to the programmer's discretion what it should be possible to - * disable. - * - * Documentation - * === - * Remember that all warnings also need to be documented in the README.md. The help is generated - * automatically. - */ -#include "WarningHandler.h" - -#include -#include "Globals.h" -#include "Utils/StringHelper.h" - -typedef struct -{ - WarningType type; - WarningLevel defaultLevel; - std::string description; -} WarningInfoInit; - -typedef struct -{ - WarningLevel level; - std::string name; - std::string description; -} WarningInfo; - -/** - * Master list of all default warning types and features - * - * To add a warning type, fill in a new row of this map. Think carefully about what its default - * level should be, and try and make the description both brief and informative: it is used in the - * help message, so again, think about what the end user needs to know. - */ -// clang-format off -static const std::unordered_map warningStringToInitMap = { - {"deprecated", {WarningType::Deprecated, -#ifdef DEPRECATION_ON - WarningLevel::Warn, -#else - WarningLevel::Off, -#endif - "Deprecated features"}}, - {"unaccounted", {WarningType::Unaccounted, WarningLevel::Off, "Large blocks of unaccounted"}}, - {"missing-offsets", {WarningType::MissingOffsets, WarningLevel::Warn, "Offset attribute missing in XML tag"}}, - {"intersection", {WarningType::Intersection, WarningLevel::Warn, "Two assets intersect"}}, - {"missing-attribute", {WarningType::MissingAttribute, WarningLevel::Warn, "Required attribute missing in XML tag"}}, - {"invalid-attribute-value", {WarningType::InvalidAttributeValue, WarningLevel::Err, "Attribute declared in XML is wrong"}}, - {"unknown-attribute", {WarningType::UnknownAttribute, WarningLevel::Warn, "Unknown attribute in XML entry tag"}}, - {"invalid-xml", {WarningType::InvalidXML, WarningLevel::Err, "XML has syntax errors"}}, - {"invalid-jpeg", {WarningType::InvalidJPEG, WarningLevel::Err, "JPEG file does not conform to the game's format requirements"}}, - {"invalid-png", {WarningType::InvalidPNG, WarningLevel::Err, "Issues arising when processing PNG data"}}, - {"invalid-extracted-data", {WarningType::InvalidExtractedData, WarningLevel::Err, "Extracted data does not have correct form"}}, - {"missing-segment", {WarningType::MissingSegment, WarningLevel::Warn, "Segment not given in File tag in XML"}}, - {"hardcoded-generic-pointer", {WarningType::HardcodedGenericPointer, WarningLevel::Off, "A generic segmented pointer must be produced"}}, - {"hardcoded-pointer", {WarningType::HardcodedPointer, WarningLevel::Warn, "ZAPD lacks the info to make a symbol, so must output a hardcoded pointer"}}, - {"not-implemented", {WarningType::NotImplemented, WarningLevel::Warn, "ZAPD does not currently support this feature"}}, -}; - -/** - * Map constructed at runtime to contain the warning features as set by the user using -W flags. - */ -static std::unordered_map warningTypeToInfoMap; - -void WarningHandler::ConstructTypeToInfoMap() { - for (auto& entry : warningStringToInitMap) { - warningTypeToInfoMap[entry.second.type] = {entry.second.defaultLevel, entry.first, entry.second.description}; - } - warningTypeToInfoMap[WarningType::Always] = {WarningLevel::Warn, "always", "you shouldn't be reading this"}; - assert(warningTypeToInfoMap.size() == static_cast(WarningType::Max)); -} - -/** - * Initialises the main warning type map and reads flags passed to set each warning type's level. - */ -void WarningHandler::Init(int argc, char* argv[]) { - ConstructTypeToInfoMap(); - - bool werror = false; - for (int i = 1; i < argc; i++) { - // If it doesn't start with "-W" skip it. - if (argv[i][0] != '-' || argv[i][1] != 'W' || argv[i][2] == '\0') { - continue; - } - - WarningLevel warningTypeOn = WarningLevel::Warn; - size_t startingIndex = 2; - - // "-Wno-" - if (argv[i][2] == 'n' && argv[i][3] == 'o' && argv[i][4] == '-' && argv[i][5] != '\0') { - warningTypeOn = WarningLevel::Off; - startingIndex = 5; - } - - // Read starting after the "-W" or "-Wno-" - std::string_view currentArgv = &argv[i][startingIndex]; - - if (currentArgv == "error") { - werror = warningTypeOn != WarningLevel::Off; - } else if (currentArgv == "everything") { - for (auto& it: warningTypeToInfoMap) { - if (it.second.level <= WarningLevel::Warn) { - it.second.level = warningTypeOn; - } - } - } else { - // "-Werror=" / "-Wno-error=" parser - if (currentArgv.rfind("error=", 0) == 0) { - // Read starting after the "error=" part - currentArgv = &argv[i][startingIndex + 6]; - warningTypeOn = warningTypeOn != WarningLevel::Off ? WarningLevel::Err : WarningLevel::Warn; - } - - auto it = warningStringToInitMap.find(std::string(currentArgv)); - if (it != warningStringToInitMap.end()) { - warningTypeToInfoMap[it->second.type].level = warningTypeOn; - } - else { - HANDLE_WARNING(WarningType::Always, StringHelper::Sprintf("unknown warning flag '%s'", argv[i]), ""); - } - } - } - - if (werror) { - for (auto& it: warningTypeToInfoMap) { - if (it.second.level >= WarningLevel::Warn) { - it.second.level = WarningLevel::Err; - } - } - } -} - -bool WarningHandler::IsWarningEnabled(WarningType warnType) { - assert(static_cast(warnType) >= 0 && warnType < WarningType::Max); - - return warningTypeToInfoMap.at(warnType).level != WarningLevel::Off; -} - -bool WarningHandler::WasElevatedToError(WarningType warnType) { - assert(static_cast(warnType) >= 0 && warnType < WarningType::Max); - - if (!IsWarningEnabled(warnType)) { - return false; - } - - return warningTypeToInfoMap.at(warnType).level >= WarningLevel::Err; -} - -/** - * Print file/line/function info for debugging - */ -void WarningHandler::FunctionPreamble(const char* filename, int32_t line, const char* function) { - bool forcePrint = false; - -#ifdef DEVELOPMENT - forcePrint = true; -#endif - - fprintf(stderr, "\n"); - - if (forcePrint || Globals::Instance->verbosity >= VerbosityLevel::VERBOSITY_DEBUG) { - fprintf(stderr, "%s:%i: in function <%s>:\n", filename, line, function); - } -} - -/** - * Print the information about the file(s) being processed (XML for extraction, png etc. for building) - */ -void WarningHandler::ProcessedFilePreamble() { - if (Globals::Instance->inputPath != "") { - fprintf(stderr, "When processing file %s: ", Globals::Instance->inputPath.c_str()); - } -} - -/** - * Print information about the binary file being extracted - */ -void WarningHandler::ExtractedFilePreamble(const ZFile *parent, const ZResource* res, const uint32_t offset) { - fprintf(stderr, "in input binary file %s, ", parent->GetName().c_str()); - if (res != nullptr) { - fprintf(stderr, "resource '%s' at ", res->GetName().c_str()); - } - if (offset != static_cast(-1)) { - fprintf(stderr, "offset 0x%06X:", offset); - } - fprintf(stderr, "\n\t"); -} - -/** - * Construct the rest of the message, after warning:/error. The message is filled in one character at a time, with indents added after newlines - */ -std::string WarningHandler::ConstructMessage(std::string message, const std::string& header, const std::string& body) { - message.reserve(message.size() + header.size() + body.size() + 10 * (sizeof(HANG_INDT) - 1)); - message += StringHelper::Sprintf(HILITE("%s"), header.c_str()); - message += "\n"; - - if (body == "") { - return message; - } - - message += HANG_INDT; - for (const char* ptr = body.c_str(); *ptr != '\0'; ptr++) { - message += *ptr; - if (*ptr == '\n') { - message += HANG_INDT; - } - } - message += "\n"; - - return message; -} - -/* Error module functions */ - -void WarningHandler::PrintErrorAndThrow(const std::string& header, const std::string& body) { - std::string errorMsg = ERR_FMT("error: "); - throw std::runtime_error(ConstructMessage(errorMsg, header, body)); -} - -/* Error types, to be used via the macros */ - -void WarningHandler::ErrorType(WarningType warnType, const std::string& header, const std::string& body) { - std::string headerMsg = header; - - for (const auto& iter: warningStringToInitMap) { - if (iter.second.type == warnType) { - headerMsg += StringHelper::Sprintf(" [%s]", iter.first.c_str()); - } - } - - PrintErrorAndThrow(headerMsg, body); -} - -void WarningHandler::Error_Plain(const char* filename, int32_t line, const char* function, WarningType warnType, const std::string& header, const std::string& body) { - FunctionPreamble(filename, line, function); - - ErrorType(warnType, header, body); -} - -void WarningHandler::Error_Process(const char* filename, int32_t line, const char* function, WarningType warnType, const std::string& header, const std::string& body) { - FunctionPreamble(filename, line, function); - ProcessedFilePreamble(); - - ErrorType(warnType, header, body); -} - -void WarningHandler::Error_Resource(const char* filename, int32_t line, const char* function, WarningType warnType, const ZFile *parent, const ZResource* res, const uint32_t offset, const std::string& header, const std::string& body) { - assert(parent != nullptr); - - FunctionPreamble(filename, line, function); - ProcessedFilePreamble(); - ExtractedFilePreamble(parent, res, offset); - - ErrorType(warnType, header, body); -} - -/* Warning module functions */ - -void WarningHandler::PrintWarningBody(const std::string& header, const std::string& body) { - std::string errorMsg = WARN_FMT("warning: "); - fprintf(stderr, "%s", ConstructMessage(errorMsg, header, body).c_str()); -} - -void WarningHandler::WarningTypeAndChooseEscalate(WarningType warnType, const std::string& header, const std::string& body) { - std::string headerMsg = header; - - for (const auto& iter: warningStringToInitMap) { - if (iter.second.type == warnType) { - headerMsg += StringHelper::Sprintf(" [-W%s]", iter.first.c_str()); - } - } - - if (WasElevatedToError(warnType)) { - PrintErrorAndThrow(headerMsg, body); - } else { - PrintWarningBody(headerMsg, body); - } -} - - -/* Warning types, to be used via the macros */ - -void WarningHandler::Warning_Plain(const char* filename, int32_t line, const char* function, WarningType warnType, const std::string& header, const std::string& body) { - if (!IsWarningEnabled(warnType)) { - return; - } - - FunctionPreamble(filename, line, function); - - WarningTypeAndChooseEscalate(warnType, header, body); -} - -void WarningHandler::Warning_Process(const char* filename, int32_t line, const char* function, WarningType warnType, const std::string& header, const std::string& body) { - if (!IsWarningEnabled(warnType)) { - return; - } - - FunctionPreamble(filename, line, function); - ProcessedFilePreamble(); - - WarningTypeAndChooseEscalate(warnType, header, body); -} - -void WarningHandler::Warning_Resource(const char* filename, int32_t line, const char* function, WarningType warnType, const ZFile *parent, const ZResource* res, const uint32_t offset, const std::string& header, const std::string& body) { - assert(parent != nullptr); - - if (!IsWarningEnabled(warnType)) { - return; - } - - FunctionPreamble(filename, line, function); - ProcessedFilePreamble(); - ExtractedFilePreamble(parent, res, offset); - - WarningTypeAndChooseEscalate(warnType, header, body); -} - - -/* Help-related functions */ - -#include - -/** - * Print each warning name, default status, and description using the init map - */ -void WarningHandler::PrintHelp() { - std::set sortedKeys; - WarningInfoInit warningInfo; - uint32_t columnWidth = 25; - std::string dt; - - // Sort keys through the magic of `set`, to print in alphabetical order - for (auto& it : warningStringToInitMap) { - sortedKeys.insert(it.first); - } - - printf("\nWarning types ( * means enabled by default)\n"); - for (auto& key : sortedKeys) { - warningInfo = warningStringToInitMap.at(key); - if (warningInfo.defaultLevel <= WarningLevel::Warn) { - dt = "-W"; - dt += key; - if (warningInfo.defaultLevel == WarningLevel::Warn) { - dt += " *"; - } - printf(HELP_DT_INDT "%-*s", columnWidth, dt.c_str()); - - if (dt.length() + 2 > columnWidth) { - printf("\n" HELP_DT_INDT "%-*s", columnWidth, ""); - } - printf("%s\n", warningInfo.description.c_str()); - } - } - - printf("\nDefault errors\n"); - for (auto& key : sortedKeys) { - if (warningInfo.defaultLevel > WarningLevel::Warn) { - dt = "-W"; - dt += key; - printf(HELP_DT_INDT "%-*s", columnWidth, dt.c_str()); - - if (dt.length() + 2 > columnWidth) { - printf("\n" HELP_DT_INDT "%*s", columnWidth, ""); - } - printf("%s\n", warningInfo.description.c_str()); - } - } - - printf("\n"); - printf("Other\n" HELP_DT_INDT "-Weverything will enable all existing warnings.\n" HELP_DT_INDT "-Werror will promote all warnings to errors.\n"); - - printf("\n"); - printf("Warnings can be disabled using -Wno-... instead of -W...; -Weverything will override any -Wno-... flags passed before it.\n"); -} - -/** - * Print which warnings are currently enabled - */ -void WarningHandler::PrintWarningsDebugInfo() -{ - std::string dt; - - printf("Warnings status:\n"); - for (auto& it: warningTypeToInfoMap) { - dt = it.second.name; - dt += ": "; - - printf(HELP_DT_INDT "%-25s", dt.c_str()); - switch (it.second.level) - { - case WarningLevel::Off: - printf(VT_FGCOL(LIGHTGRAY) "Off" VT_RST); - break; - case WarningLevel::Warn: - printf(VT_FGCOL(YELLOW) "Warn" VT_RST); - break; - case WarningLevel::Err: - printf(VT_FGCOL(RED) "Err" VT_RST); - break; - - } - printf("\n"); - } - printf("\n"); -} diff --git a/tools/ZAPD/ZAPD/WarningHandler.h b/tools/ZAPD/ZAPD/WarningHandler.h deleted file mode 100644 index f99330042b..0000000000 --- a/tools/ZAPD/ZAPD/WarningHandler.h +++ /dev/null @@ -1,146 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -#include "Utils/vt.h" -#include "ZFile.h" - -#ifdef _MSC_VER -#define __PRETTY_FUNCTION__ __FUNCSIG__ -#elif not defined(__GNUC__) -#define __PRETTY_FUNCTION__ __func__ -#endif - -// ======================================= -/* Formatting macros */ - -// TODO: move this somewhere else so it can be used by other help -#define HELP_DT_INDT " " - -/* Macros for formatting warnings/errors */ -#define VT_HILITE VT_BOLD_FGCOL(WHITE) -#define VT_WARN VT_BOLD_FGCOL(PURPLE) -#define VT_ERR VT_BOLD_FGCOL(RED) - -#define HILITE(string) (VT_HILITE string VT_RST) -#define WARN_FMT(string) (VT_WARN string VT_RST) -#define ERR_FMT(string) (VT_ERR string VT_RST) - -// Maybe make WARN_LF instead -// Currently 8 spaces -#define WARN_INDT " " -// Currently 16 spaces -#define HANG_INDT " " - -// ======================================= -/* Warning and error macros */ -// TODO: better names - -// General-purpose, plain style (only prints function,file,line in the preamble) -#define HANDLE_ERROR(warningType, header, body) \ - WarningHandler::Error_Plain(__FILE__, __LINE__, __PRETTY_FUNCTION__, warningType, header, body) -#define HANDLE_WARNING(warningType, header, body) \ - WarningHandler::Warning_Plain(__FILE__, __LINE__, __PRETTY_FUNCTION__, warningType, header, \ - body) - -// For processing XMLs or textures/blobs (preamble contains function,file,line; processed file) -#define HANDLE_ERROR_PROCESS(warningType, header, body) \ - WarningHandler::Error_Process(__FILE__, __LINE__, __PRETTY_FUNCTION__, warningType, header, \ - body) -#define HANDLE_WARNING_PROCESS(warningType, header, body) \ - WarningHandler::Warning_Process(__FILE__, __LINE__, __PRETTY_FUNCTION__, warningType, header, \ - body) - -// For ZResource-related stuff (preamble contains function,file,line; processed file; extracted file -// and offset) -#define HANDLE_ERROR_RESOURCE(warningType, parent, resource, offset, header, body) \ - WarningHandler::Error_Resource(__FILE__, __LINE__, __PRETTY_FUNCTION__, warningType, parent, \ - resource, offset, header, body) -#define HANDLE_WARNING_RESOURCE(warningType, parent, resource, offset, header, body) \ - WarningHandler::Warning_Resource(__FILE__, __LINE__, __PRETTY_FUNCTION__, warningType, parent, \ - resource, offset, header, body) - -// ======================================= - -enum class WarningType -{ - Always, // Warnings of this type are always printed, cannot be disabled. - Deprecated, - Unaccounted, - MissingOffsets, - Intersection, - MissingAttribute, - InvalidAttributeValue, - UnknownAttribute, - InvalidXML, - InvalidJPEG, - InvalidPNG, - InvalidExtractedData, - MissingSegment, - HardcodedPointer, - HardcodedGenericPointer, - NotImplemented, - Max, -}; - -enum class WarningLevel -{ - Off, - Warn, - Err, -}; - -class WarningHandler -{ -public: - static void ConstructTypeToInfoMap(); - - static void Init(int argc, char* argv[]); - - static bool IsWarningEnabled(WarningType warnType); - static bool WasElevatedToError(WarningType warnType); - - static void FunctionPreamble(const char* filename, int32_t line, const char* function); - static void ProcessedFilePreamble(); - static void ExtractedFilePreamble(const ZFile* parent, const ZResource* res, - const uint32_t offset); - static std::string ConstructMessage(std::string message, const std::string& header, - const std::string& body); - - [[noreturn]] static void PrintErrorAndThrow(const std::string& header, const std::string& body); - static void PrintWarningBody(const std::string& header, const std::string& body); - - [[noreturn]] static void ErrorType(WarningType warnType, const std::string& header, - const std::string& body); - [[noreturn]] static void Error_Plain(const char* filename, int32_t line, const char* function, - WarningType warnType, const std::string& header, - const std::string& body); - [[noreturn]] static void Error_Process(const char* filename, int32_t line, const char* function, - WarningType warnType, const std::string& header, - const std::string& body); - [[noreturn]] static void Error_Resource(const char* filename, int32_t line, - const char* function, WarningType warnType, - const ZFile* parent, const ZResource* res, - const uint32_t offset, const std::string& header, - const std::string& body); - - static void WarningTypeAndChooseEscalate(WarningType warnType, const std::string& header, - const std::string& body); - - static void Warning_Plain(const char* filename, int32_t line, const char* function, - WarningType warnType, const std::string& header, - const std::string& body); - static void Warning_Process(const char* filename, int32_t line, const char* function, - WarningType warnType, const std::string& header, - const std::string& body); - static void Warning_Resource(const char* filename, int32_t line, const char* function, - WarningType warnType, const ZFile* parent, const ZResource* res, - const uint32_t offset, const std::string& header, - const std::string& body); - - static void PrintHelp(); - static void PrintWarningsDebugInfo(); -}; diff --git a/tools/ZAPD/ZAPD/ZAPD.vcxproj b/tools/ZAPD/ZAPD/ZAPD.vcxproj deleted file mode 100644 index 26a0b70363..0000000000 --- a/tools/ZAPD/ZAPD/ZAPD.vcxproj +++ /dev/null @@ -1,383 +0,0 @@ - - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - 15.0 - {B53F9E5B-0A58-4BAE-9AFE-856C8CBB8D36} - ZAPD - 10.0 - ZAPD - - - - Application - true - v142 - MultiByte - - - Application - false - v142 - true - MultiByte - - - Application - true - v142 - MultiByte - false - - - Application - false - v142 - true - MultiByte - false - - - - - - - - - - - - - - - - - - - - - $(OutDir);$(ProjectDir)..\lib\libgfxd;$(ProjectDir)..\packages\libpng-v142.1.6.37.2\build\native\lib\x64\v142\Debug\;$(LibraryPath) - $(ProjectDir)..\ZAPDUtils;$(ProjectDir)..\lib\tinyxml2;$(ProjectDir)..\lib\libgfxd;$(ProjectDir)..\lib\elfio;$(ProjectDir)..\lib\stb;$(ProjectDir);$(IncludePath) - - - $(IncludePath) - - - $(SolutionDir)ZAPD\lib\tinyxml2;$(SolutionDir)ZAPD\lib\libgfxd;$(SolutionDir)ZAPD\lib\elfio;$(SolutionDir)ZAPD\lib\stb;$(ProjectDir);$(IncludePath) - $(SolutionDir)ZAPD\lib\libgfxd;$(SolutionDir)x64\Debug;$(SolutionDir)packages\libpng.1.6.28.1\build\native\lib\x64\v140\dynamic\Debug;$(LibraryPath) - - - - Level3 - Disabled - true - true - stdcpp17 - stdc11 - _CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - true - - - true - Console - - - cd .. -mkdir build\ZAPD - python ZAPD/genbuildinfo.py - - - - - Level3 - Disabled - true - true - stdcpp17 - _CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - EnableFastChecks - stdc11 - MultiThreadedDebug - true - - - true - ZAPDUtils.lib;/WHOLEARCHIVE:ExporterExample.lib;%(AdditionalDependencies) - false - Console - - - cd .. -mkdir build\ZAPD - python ZAPD/genbuildinfo.py - - - - - Level3 - MaxSpeed - true - true - true - true - true - - - true - true - - - cd .. -mkdir build\ZAPD - python ZAPD/genbuildinfo.py - - - - - Level3 - MaxSpeed - true - true - true - true - stdcpplatest - _CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - true - - - true - true - - - cd .. -mkdir build\ZAPD - python ZAPD/genbuildinfo.py - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - true - - - - - - - - - - - - - - - - - - This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - - - - - - - \ No newline at end of file diff --git a/tools/ZAPD/ZAPD/ZAPD.vcxproj.filters b/tools/ZAPD/ZAPD/ZAPD.vcxproj.filters deleted file mode 100644 index 51723306b4..0000000000 --- a/tools/ZAPD/ZAPD/ZAPD.vcxproj.filters +++ /dev/null @@ -1,605 +0,0 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hh;hpp;hxx;hm;inl;inc;ipp;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms - - - {02148456-5068-4613-8478-f10addc58e70} - - - {bcab3136-95ba-4839-833c-43d78ad6e335} - - - {dc06ed84-f6fe-4277-80f3-d62bd5cdbb98} - - - {6049c045-bc38-4221-b29e-ca6d4d8af4aa} - - - {490e3a08-047b-48d3-ab53-3a860a3b92aa} - - - {26c06845-8e8e-4b79-ad18-07c4f9c0f801} - - - {d45c420d-2378-47ac-92c5-80db9475c195} - - - {03cc56a2-e0e8-4167-80a0-98fb900a959a} - - - {73db0879-6df8-4f6a-8cc2-a1f836e9e796} - - - {be9a5be0-ec6a-4200-8e39-bb58c7da7aa8} - - - {7ee79d97-c6a8-4e82-93ef-37981f4d7838} - - - {85600275-99fe-491d-8189-bcc3dc1a8903} - - - {ba9990b0-1082-48bb-874c-6108534b5455} - - - {ce9d91b0-ba20-4296-bc2d-8630965bb392} - - - {730beb67-6d59-4849-9d9b-702c4a565fc0} - - - - - Source Files - - - Source Files\Z64\ZRoom - - - Source Files\Z64\ZRoom\Commands - - - Source Files\Z64\ZRoom - - - Source Files\Z64\ZRoom\Commands - - - Source Files\Z64\ZRoom\Commands - - - Source Files\Z64\ZRoom\Commands - - - Source Files\Z64\ZRoom\Commands - - - Source Files\Z64\ZRoom\Commands - - - Source Files\Z64\ZRoom\Commands - - - Source Files\Z64\ZRoom\Commands - - - Source Files\Z64\ZRoom\Commands - - - Source Files\Z64\ZRoom\Commands - - - Source Files\Z64\ZRoom\Commands - - - Source Files\Z64\ZRoom\Commands - - - Source Files - - - Source Files\Z64\ZRoom\Commands - - - Source Files\Z64\ZRoom\Commands - - - Source Files\Z64\ZRoom\Commands - - - Source Files\Z64\ZRoom\Commands - - - Source Files\Z64\ZRoom\Commands - - - Source Files\Z64\ZRoom\Commands - - - Source Files\Z64\ZRoom\Commands - - - Source Files\Z64\ZRoom\Commands - - - Source Files\Z64\ZRoom\Commands - - - Source Files\Z64\ZRoom\Commands - - - Source Files\Z64\ZRoom\Commands - - - Source Files\Z64\ZRoom\Commands - - - Source Files\Z64 - - - Source Files\Z64 - - - Source Files\Z64 - - - Source Files\Z64 - - - Source Files\Z64 - - - Source Files\Z64 - - - Source Files\Z64 - - - Source Files\Z64 - - - Source Files\Z64\ZRoom\Commands - - - Source Files\Z64\ZRoom\Commands - - - Source Files\Z64 - - - Source Files\Z64 - - - Source Files\Z64 - - - Source Files\Z64 - - - Source Files\Z64 - - - Source Files\Z64 - - - Source Files - - - Source Files\Z64 - - - Source Files\Libraries\libgfxd - - - Source Files\Libraries\libgfxd - - - Source Files\Libraries\libgfxd - - - Source Files\Libraries\libgfxd - - - Source Files\Libraries\libgfxd - - - Source Files\Libraries\libgfxd - - - Source Files\Libraries\libgfxd - - - Source Files\Z64 - - - Source Files\Z64\ZRoom\Commands - - - Source Files\Z64\ZRoom\Commands - - - Source Files\Z64\ZRoom\Commands - - - Source Files\Z64\ZRoom\Commands - - - Source Files\Z64\ZRoom\Commands - - - Source Files\Z64 - - - Source Files\Z64\ZRoom\Commands - - - Source Files\Z64 - - - Source Files - - - Source Files - - - Source Files\Z64 - - - Source Files - - - Source Files\Z64 - - - Source Files\Z64 - - - Source Files - - - Source Files\Z64 - - - Source Files - - - Source Files\Z64 - - - Source Files\Z64 - - - Source Files - - - Source Files\Z64 - - - Source Files\Z64 - - - Source Files\Z64 - - - Source Files\Z64 - - - Source Files\Z64 - - - Source Files\Z64\ZRoom\Commands - - - Source Files\Z64 - - - Source Files\Z64 - - - - - Header Files\Z64\ZRoom - - - Header Files\Z64\ZRoom - - - Header Files\Z64\ZRoom\Commands - - - Header Files\Z64\ZRoom\Commands - - - Header Files\Z64\ZRoom\Commands - - - Header Files\Z64\ZRoom\Commands - - - Header Files\Z64\ZRoom\Commands - - - Header Files\Z64\ZRoom\Commands - - - Header Files\Z64\ZRoom\Commands - - - Header Files\Z64\ZRoom\Commands - - - Header Files\Z64\ZRoom\Commands - - - Header Files\Z64\ZRoom\Commands - - - Header Files\Z64\ZRoom\Commands - - - Header Files\Z64\ZRoom\Commands - - - Header Files\Libraries\elfio - - - Header Files\Libraries\elfio - - - Header Files\Libraries\elfio - - - Header Files\Libraries\elfio - - - Header Files\Libraries\elfio - - - Header Files\Libraries\elfio - - - Header Files\Libraries\elfio - - - Header Files\Libraries\elfio - - - Header Files\Libraries\elfio - - - Header Files\Libraries\elfio - - - Header Files\Libraries\elfio - - - Header Files\Libraries\elfio - - - Header Files - - - Header Files\Z64\ZRoom\Commands - - - Header Files\Z64\ZRoom\Commands - - - Header Files\Z64\ZRoom\Commands - - - Header Files\Z64\ZRoom\Commands - - - Header Files\Z64\ZRoom\Commands - - - Header Files\Z64\ZRoom\Commands - - - Header Files\Z64\ZRoom\Commands - - - Header Files\Z64\ZRoom\Commands - - - Header Files\Z64\ZRoom\Commands - - - Header Files\Z64\ZRoom\Commands - - - Header Files\Z64\ZRoom\Commands - - - Header Files\Z64\ZRoom\Commands - - - Header Files\Libraries - - - Header Files\Libraries - - - Header Files\Z64 - - - Header Files\Z64 - - - Header Files\Z64 - - - Header Files\Z64 - - - Header Files\Z64 - - - Header Files\Z64 - - - Header Files\Z64 - - - Header Files\Z64 - - - Header Files\Z64\ZRoom\Commands - - - Header Files\Z64\ZRoom\Commands - - - Header Files\Z64 - - - Header Files\Z64 - - - Header Files\Z64 - - - Header Files - - - Header Files\Z64 - - - Header Files\Z64 - - - Header Files - - - Header Files\Z64 - - - Header Files - - - Header Files\Z64 - - - Header Files\Libraries\libgfxd - - - Header Files\Libraries\libgfxd - - - Header Files\Libraries\libgfxd - - - Header Files\Z64 - - - Header Files\Z64\ZRoom\Commands - - - Header Files\Z64\ZRoom\Commands - - - Header Files\Z64\ZRoom\Commands - - - Header Files\Z64\ZRoom\Commands - - - Header Files\Z64\ZRoom\Commands - - - Header Files\Z64 - - - Header Files\Z64\ZRoom\Commands - - - Header Files - - - Header Files\Z64 - - - Header Files - - - Header Files\Z64 - - - Header Files - - - Header Files\Z64 - - - Header Files\Z64 - - - Header Files\Z64 - - - Header Files - - - Header Files\Z64 - - - Header Files\Z64 - - - Header Files - - - Header Files\Z64 - - - Header Files - - - Header Files - - - Header Files - - - Header Files\Z64 - - - Header Files\Z64 - - - Header Files\Z64\ZRoom\Commands - - - Header Files\Z64 - - - Header Files\Z64 - - - - - Resource Files - - - any\any - - - NuGet - - - - - - \ No newline at end of file diff --git a/tools/ZAPD/ZAPD/ZActorList.cpp b/tools/ZAPD/ZAPD/ZActorList.cpp deleted file mode 100644 index ee5cb4d445..0000000000 --- a/tools/ZAPD/ZAPD/ZActorList.cpp +++ /dev/null @@ -1,194 +0,0 @@ -#include "ZActorList.h" - -#include "Globals.h" -#include "Utils/BitConverter.h" -#include "WarningHandler.h" -#include "ZFile.h" -#include "ZRoom/ZNames.h" - -REGISTER_ZFILENODE(ActorList, ZActorList); - -ZActorList::ZActorList(ZFile* nParent) : ZResource(nParent) -{ - RegisterRequiredAttribute("Count"); -} - -void ZActorList::ExtractFromBinary(uint32_t nRawDataIndex, uint8_t nNumActors) -{ - rawDataIndex = nRawDataIndex; - numActors = nNumActors; - - // Don't parse raw data of external files - if (parent->GetMode() == ZFileMode::ExternalFile) - return; - - ParseRawData(); -} - -void ZActorList::ParseXML(tinyxml2::XMLElement* reader) -{ - ZResource::ParseXML(reader); - - numActors = StringHelper::StrToL(registeredAttributes.at("Count").value); - - if (numActors < 1) - { - HANDLE_ERROR_RESOURCE( - WarningType::InvalidAttributeValue, parent, this, rawDataIndex, - StringHelper::Sprintf("invalid value '%d' found for 'NumPaths' attribute", numActors), - "Should be at least '1'"); - } -} - -void ZActorList::ParseRawData() -{ - ZResource::ParseRawData(); - - offset_t currentPtr = rawDataIndex; - size_t largestlength = 0; - - for (size_t i = 0; i < numActors; i++) - { - ActorSpawnEntry entry(parent->GetRawData(), currentPtr); - - currentPtr += entry.GetRawDataSize(); - actors.push_back(entry); - - size_t actorNameLength = ZNames::GetActorName(entry.GetActorId()).size(); - if (actorNameLength > largestlength) - largestlength = actorNameLength; - } - - for (auto& entry : actors) - { - entry.SetLargestActorName(largestlength); - } -} - -Declaration* ZActorList::DeclareVar(const std::string& prefix, const std::string& bodyStr) -{ - std::string auxName = name; - - if (name == "") - auxName = GetDefaultName(prefix); - - Declaration* decl = - parent->AddDeclarationArray(rawDataIndex, GetDeclarationAlignment(), GetRawDataSize(), - GetSourceTypeName(), name, GetActorListArraySize(), bodyStr); - decl->staticConf = staticConf; - - return decl; -} - -std::string ZActorList::GetBodySourceCode() const -{ - std::string declaration; - - size_t index = 0; - for (auto& entry : actors) - { - declaration += StringHelper::Sprintf("\t{ %s },", entry.GetBodySourceCode().c_str()); - - if (index < actors.size() - 1) - declaration += "\n"; - - index++; - } - - return declaration; -} - -std::string ZActorList::GetSourceTypeName() const -{ - return actors.front().GetSourceTypeName(); -} - -ZResourceType ZActorList::GetResourceType() const -{ - return ZResourceType::ActorList; -} - -size_t ZActorList::GetRawDataSize() const -{ - return actors.size() * actors.front().GetRawDataSize(); -} - -size_t ZActorList::GetActorListArraySize() const -{ - size_t actorCount = 0; - - // Doing an else-if here so we only do the loop when the game is SW97. - // Actor 0x22 is removed from SW97, so we need to ensure that we don't increment the actor count - // for it. - if (Globals::Instance->game == ZGame::OOT_SW97) - { - actorCount = 0; - - for (const auto& entry : actors) - if (entry.GetActorId() != 0x22) - actorCount++; - } - else - { - actorCount = actors.size(); - } - - return actorCount; -} - -/* ActorSpawnEntry */ - -ActorSpawnEntry::ActorSpawnEntry(const std::vector& rawData, uint32_t rawDataIndex) -{ - actorNum = BitConverter::ToInt16BE(rawData, rawDataIndex + 0); - posX = BitConverter::ToInt16BE(rawData, rawDataIndex + 2); - posY = BitConverter::ToInt16BE(rawData, rawDataIndex + 4); - posZ = BitConverter::ToInt16BE(rawData, rawDataIndex + 6); - rotX = BitConverter::ToUInt16BE(rawData, rawDataIndex + 8); - rotY = BitConverter::ToUInt16BE(rawData, rawDataIndex + 10); - rotZ = BitConverter::ToUInt16BE(rawData, rawDataIndex + 12); - params = BitConverter::ToInt16BE(rawData, rawDataIndex + 14); -} - -std::string ActorSpawnEntry::GetBodySourceCode() const -{ - std::string body; - - std::string actorNameFmt = StringHelper::Sprintf("%%-%zus ", largestActorName + 1); - body = - StringHelper::Sprintf(actorNameFmt.c_str(), (ZNames::GetActorName(actorNum) + ",").c_str()); - - body += StringHelper::Sprintf("{ %6i, %6i, %6i }, ", posX, posY, posZ); - if (Globals::Instance->game == ZGame::MM_RETAIL) - body += StringHelper::Sprintf("{ SPAWN_ROT_FLAGS(%#5hX, 0x%04X)" - ", SPAWN_ROT_FLAGS(%#5hX, 0x%04X)" - ", SPAWN_ROT_FLAGS(%#5hX, 0x%04X) }, ", - (rotX >> 7) & 0b111111111, rotX & 0b1111111, - (rotY >> 7) & 0b111111111, rotY & 0b1111111, - (rotZ >> 7) & 0b111111111, rotZ & 0b1111111); - else - body += StringHelper::Sprintf("{ %#6hX, %#6hX, %#6hX }, ", rotX, rotY, rotZ); - body += StringHelper::Sprintf("0x%04X", params); - - return body; -} - -std::string ActorSpawnEntry::GetSourceTypeName() const -{ - return "ActorEntry"; -} - -size_t ActorSpawnEntry::GetRawDataSize() const -{ - return 16; -} - -uint16_t ActorSpawnEntry::GetActorId() const -{ - return actorNum; -} - -void ActorSpawnEntry::SetLargestActorName(size_t nameSize) -{ - largestActorName = nameSize; -} diff --git a/tools/ZAPD/ZAPD/ZActorList.h b/tools/ZAPD/ZAPD/ZActorList.h deleted file mode 100644 index 7cc63da2fe..0000000000 --- a/tools/ZAPD/ZAPD/ZActorList.h +++ /dev/null @@ -1,52 +0,0 @@ -#pragma once - -#include "ZResource.h" - -class ActorSpawnEntry -{ -public: - uint16_t actorNum; - int16_t posX; - int16_t posY; - int16_t posZ; - uint16_t rotX; - uint16_t rotY; - uint16_t rotZ; - uint16_t params; - size_t largestActorName = 16; - - ActorSpawnEntry(const std::vector& rawData, uint32_t rawDataIndex); - - std::string GetBodySourceCode() const; - - std::string GetSourceTypeName() const; - size_t GetRawDataSize() const; - - uint16_t GetActorId() const; - void SetLargestActorName(size_t nameSize); -}; - -class ZActorList : public ZResource -{ -public: - std::vector actors; - uint32_t numActors = 0; - - ZActorList(ZFile* nParent); - - void ExtractFromBinary(offset_t nRawDataIndex, uint8_t nNumActors); - - void ParseXML(tinyxml2::XMLElement* reader) override; - void ParseRawData() override; - - Declaration* DeclareVar(const std::string& prefix, const std::string& bodyStr) override; - std::string GetBodySourceCode() const override; - - std::string GetSourceTypeName() const override; - ZResourceType GetResourceType() const override; - - size_t GetRawDataSize() const override; - -protected: - size_t GetActorListArraySize() const; -}; diff --git a/tools/ZAPD/ZAPD/ZAnimation.cpp b/tools/ZAPD/ZAPD/ZAnimation.cpp deleted file mode 100644 index 959fff8291..0000000000 --- a/tools/ZAPD/ZAPD/ZAnimation.cpp +++ /dev/null @@ -1,556 +0,0 @@ -#include "ZAnimation.h" - -#include - -#include "Globals.h" -#include "Utils/BitConverter.h" -#include "Utils/File.h" -#include "Utils/StringHelper.h" -#include "WarningHandler.h" -#include "ZFile.h" - -REGISTER_ZFILENODE(Animation, ZNormalAnimation); -REGISTER_ZFILENODE(PlayerAnimation, ZLinkAnimation); -REGISTER_ZFILENODE(CurveAnimation, ZCurveAnimation); -REGISTER_ZFILENODE(LegacyAnimation, ZLegacyAnimation); - -ZAnimation::ZAnimation(ZFile* nParent) : ZResource(nParent) -{ - frameCount = 0; -} - -void ZAnimation::ParseRawData() -{ - ZResource::ParseRawData(); - - frameCount = BitConverter::ToInt16BE(parent->GetRawData(), rawDataIndex + 0); -} - -ZResourceType ZAnimation::GetResourceType() const -{ - return ZResourceType::Animation; -} - -/* ZNormalAnimation */ - -ZNormalAnimation::ZNormalAnimation(ZFile* nParent) : ZAnimation(nParent) -{ -} - -size_t ZNormalAnimation::GetRawDataSize() const -{ - return 16; -} - -std::string ZNormalAnimation::GetSourceTypeName() const -{ - return "AnimationHeader"; -} - -void ZNormalAnimation::ParseRawData() -{ - ZAnimation::ParseRawData(); - - auto& data = parent->GetRawData(); - - rotationValuesSeg = BitConverter::ToInt32BE(data, rawDataIndex + 4); - rotationIndicesSeg = BitConverter::ToInt32BE(data, rawDataIndex + 8); - limit = BitConverter::ToInt16BE(data, rawDataIndex + 12); - - rotationValuesOffset = Seg2Filespace(rotationValuesSeg, parent->baseAddress); - rotationIndicesOffset = Seg2Filespace(rotationIndicesSeg, parent->baseAddress); - - uint32_t currentPtr = rotationValuesOffset; - - // Read the Rotation Values - for (uint32_t i = 0; i < ((rotationIndicesOffset - rotationValuesOffset) / 2); i++) - { - rotationValues.push_back(BitConverter::ToInt16BE(data, currentPtr)); - currentPtr += 2; - } - - currentPtr = rotationIndicesOffset; - - // Read the Rotation Indices - for (uint32_t i = 0; i < ((rawDataIndex - rotationIndicesOffset) / 6); i++) - { - rotationIndices.push_back(RotationIndex(BitConverter::ToInt16BE(data, currentPtr), - BitConverter::ToInt16BE(data, currentPtr + 2), - BitConverter::ToInt16BE(data, currentPtr + 4))); - currentPtr += 6; - } -} - -void ZNormalAnimation::DeclareReferences(const std::string& prefix) -{ - std::string defaultPrefix = prefix.c_str(); - if (name != "") - defaultPrefix = name; - - // replace g prefix with s for local variables - if (defaultPrefix.at(0) == 'g') - defaultPrefix.replace(0, 1, "s"); - - std::string indicesStr = ""; - std::string valuesStr = " "; - const uint8_t lineLength = 14; - const uint8_t offset = 0; - - for (size_t i = 0; i < rotationValues.size(); i++) - { - valuesStr += StringHelper::Sprintf("0x%04X, ", rotationValues[i]); - - if ((i - offset + 1) % lineLength == 0) - valuesStr += "\n "; - } - - parent->AddDeclarationArray(rotationValuesOffset, DeclarationAlignment::Align4, - rotationValues.size() * 2, "s16", - StringHelper::Sprintf("%sFrameData", defaultPrefix.c_str()), - rotationValues.size(), valuesStr); - - for (size_t i = 0; i < rotationIndices.size(); i++) - { - indicesStr += StringHelper::Sprintf(" { 0x%04X, 0x%04X, 0x%04X },", rotationIndices[i].x, - rotationIndices[i].y, rotationIndices[i].z); - - if (i != (rotationIndices.size() - 1)) - indicesStr += "\n"; - } - - parent->AddDeclarationArray(rotationIndicesOffset, DeclarationAlignment::Align4, - rotationIndices.size() * 6, "JointIndex", - StringHelper::Sprintf("%sJointIndices", defaultPrefix.c_str()), - rotationIndices.size(), indicesStr); -} - -std::string ZNormalAnimation::GetBodySourceCode() const -{ - std::string frameDataName; - Globals::Instance->GetSegmentedPtrName(rotationValuesSeg, parent, "s16", frameDataName); - std::string jointIndicesName; - Globals::Instance->GetSegmentedPtrName(rotationIndicesSeg, parent, "JointIndex", - jointIndicesName); - - std::string headerStr = - StringHelper::Sprintf("\n\t{ %i }, %s,\n", frameCount, frameDataName.c_str()); - headerStr += StringHelper::Sprintf("\t%s, %i\n", jointIndicesName.c_str(), limit); - - return headerStr; -} - -/* ZLinkAnimation */ - -ZLinkAnimation::ZLinkAnimation(ZFile* nParent) : ZAnimation(nParent) -{ - segmentAddress = 0; -} - -size_t ZLinkAnimation::GetRawDataSize() const -{ - return 8; -} - -std::string ZLinkAnimation::GetSourceTypeName() const -{ - if (Globals::Instance->game == ZGame::MM_RETAIL) - return "PlayerAnimationHeader"; - else - return "LinkAnimationHeader"; -} - -void ZLinkAnimation::ParseRawData() -{ - ZAnimation::ParseRawData(); - - const auto& rawData = parent->GetRawData(); - segmentAddress = BitConverter::ToInt32BE(rawData, rawDataIndex + 4); -} - -std::string ZLinkAnimation::GetBodySourceCode() const -{ - std::string segSymbol; - Globals::Instance->GetSegmentedPtrName(segmentAddress, parent, "", segSymbol); - - return StringHelper::Sprintf("\n\t{ %i }, %s\n", frameCount, segSymbol.c_str()); -} - -/* ZCurveAnimation */ - -CurveInterpKnot::CurveInterpKnot(ZFile* parent, const std::vector& rawData, - uint32_t fileOffset) - : parent(parent) -{ - unk_00 = BitConverter::ToUInt16BE(rawData, fileOffset + 0); - unk_02 = BitConverter::ToUInt16BE(rawData, fileOffset + 2); - unk_04 = BitConverter::ToInt16BE(rawData, fileOffset + 4); - unk_06 = BitConverter::ToInt16BE(rawData, fileOffset + 6); - unk_08 = BitConverter::ToFloatBE(rawData, fileOffset + 8); -} - -CurveInterpKnot::CurveInterpKnot(ZFile* parent, const std::vector& rawData, - uint32_t fileOffset, size_t index) - : CurveInterpKnot(parent, rawData, fileOffset + index * GetRawDataSize()) -{ -} - -std::string CurveInterpKnot::GetBody([[maybe_unused]] const std::string& prefix) const -{ - return StringHelper::Sprintf("0x%04X, 0x%04X, %i, %i, %ff", unk_00, unk_02, unk_04, unk_06, - unk_08); -} - -size_t CurveInterpKnot::GetRawDataSize() const -{ - return 0x0C; -} - -std::string CurveInterpKnot::GetSourceTypeName() -{ - return "CurveInterpKnot"; -} - -ZCurveAnimation::ZCurveAnimation(ZFile* nParent) : ZAnimation(nParent) -{ - RegisterOptionalAttribute("SkelOffset"); -} - -void ZCurveAnimation::ParseXML(tinyxml2::XMLElement* reader) -{ - ZAnimation::ParseXML(reader); - - std::string skelOffsetXml = registeredAttributes.at("SkelOffset").value; - if (skelOffsetXml == "") - { - HANDLE_ERROR_RESOURCE(WarningType::MissingAttribute, parent, this, rawDataIndex, - "missing 'SkelOffset' attribute in ", - "You need to provide the offset of the curve skeleton."); - } - skelOffset = StringHelper::StrToL(skelOffsetXml, 0); -} - -void ZCurveAnimation::ParseRawData() -{ - ZAnimation::ParseRawData(); - - const auto& rawData = parent->GetRawData(); - refIndex = BitConverter::ToUInt32BE(rawData, rawDataIndex + 0); - transformData = BitConverter::ToUInt32BE(rawData, rawDataIndex + 4); - copyValues = BitConverter::ToUInt32BE(rawData, rawDataIndex + 8); - unk_0C = BitConverter::ToInt16BE(rawData, rawDataIndex + 12); - unk_10 = BitConverter::ToInt16BE(rawData, rawDataIndex + 14); - - uint32_t limbCountAddress = Seg2Filespace(skelOffset, parent->baseAddress) + 4; - limbCount = BitConverter::ToUInt8BE(rawData, limbCountAddress); - - size_t transformDataSize = 0; - size_t copyValuesSize = 0; - if (refIndex != 0) - { - uint32_t refIndexOffset = Seg2Filespace(refIndex, parent->baseAddress); - for (size_t i = 0; i < 3 * 3 * limbCount; i++) - { - uint8_t ref = BitConverter::ToUInt8BE(rawData, refIndexOffset + i); - if (ref == 0) - copyValuesSize++; - else - transformDataSize += ref; - - refIndexArr.emplace_back(ref); - } - } - - if (transformData != 0) - { - uint32_t transformDataOffset = Seg2Filespace(transformData, parent->baseAddress); - - for (size_t i = 0; i < transformDataSize; i++) - transformDataArr.emplace_back(parent, rawData, transformDataOffset, i); - } - - if (copyValues != 0) - { - uint32_t copyValuesOffset = Seg2Filespace(copyValues, parent->baseAddress); - - for (size_t i = 0; i < copyValuesSize; i++) - copyValuesArr.emplace_back(BitConverter::ToInt16BE(rawData, copyValuesOffset + i * 2)); - } -} - -void ZCurveAnimation::DeclareReferences(const std::string& prefix) -{ - if (refIndex != 0) - { - uint32_t refIndexOffset = Seg2Filespace(refIndex, parent->baseAddress); - std::string refIndexStr = - StringHelper::Sprintf("%sCurveAnime_%s_%06X", prefix.c_str(), "Ref", refIndexOffset); - - std::string entryStr = " "; - uint16_t arrayItemCnt = refIndexArr.size(); - - size_t i = 0; - for (auto& child : refIndexArr) - { - entryStr += StringHelper::Sprintf("0x%02X, %s", child, (i++ % 8 == 7) ? "\n " : ""); - } - - Declaration* decl = parent->GetDeclaration(refIndexOffset); - if (decl == nullptr) - { - parent->AddDeclarationArray(refIndexOffset, DeclarationAlignment::Align4, - arrayItemCnt * 1, "u8", refIndexStr, arrayItemCnt, - entryStr); - } - else - { - decl->declBody = entryStr; - } - } - - if (transformData != 0) - { - uint32_t transformDataOffset = Seg2Filespace(transformData, parent->baseAddress); - std::string transformDataStr = StringHelper::Sprintf( - "%sCurveAnime_%s_%06X", prefix.c_str(), - transformDataArr.at(0).GetSourceTypeName().c_str(), transformDataOffset); - - std::string entryStr; - uint16_t arrayItemCnt = transformDataArr.size(); - - size_t i = 0; - for (auto& child : transformDataArr) - { - entryStr += StringHelper::Sprintf(" { %s },%s", child.GetBody(prefix).c_str(), - (++i < arrayItemCnt) ? "\n" : ""); - } - - Declaration* decl = parent->GetDeclaration(transformDataOffset); - if (decl == nullptr) - { - parent->AddDeclarationArray(transformDataOffset, DeclarationAlignment::Align4, - arrayItemCnt * transformDataArr.at(0).GetRawDataSize(), - transformDataArr.at(0).GetSourceTypeName(), - transformDataStr, arrayItemCnt, entryStr); - } - else - { - decl->declBody = entryStr; - } - } - - if (copyValues != 0) - { - uint32_t copyValuesOffset = Seg2Filespace(copyValues, parent->baseAddress); - std::string copyValuesStr = - StringHelper::Sprintf("%sCurveAnime_%s_%06X", prefix.c_str(), "Copy", copyValuesOffset); - - std::string entryStr = " "; - uint16_t arrayItemCnt = copyValuesArr.size(); - - size_t i = 0; - for (auto& child : copyValuesArr) - { - entryStr += StringHelper::Sprintf("% 6i, %s", child, (i++ % 8 == 7) ? "\n " : ""); - } - - Declaration* decl = parent->GetDeclaration(copyValuesOffset); - if (decl == nullptr) - { - parent->AddDeclarationArray(copyValuesOffset, DeclarationAlignment::Align4, - arrayItemCnt * 2, "s16", copyValuesStr, arrayItemCnt, - entryStr); - } - else - { - decl->declBody = entryStr; - } - } -} - -std::string ZCurveAnimation::GetBodySourceCode() const -{ - std::string refIndexStr; - Globals::Instance->GetSegmentedPtrName(refIndex, parent, "u8", refIndexStr); - std::string transformDataStr; - Globals::Instance->GetSegmentedPtrName(transformData, parent, "CurveInterpKnot", - transformDataStr); - std::string copyValuesStr; - Globals::Instance->GetSegmentedPtrName(copyValues, parent, "s16", copyValuesStr); - - return StringHelper::Sprintf("\n\t%s,\n\t%s,\n\t%s,\n\t%i, %i\n", refIndexStr.c_str(), - transformDataStr.c_str(), copyValuesStr.c_str(), unk_0C, unk_10); -} - -size_t ZCurveAnimation::GetRawDataSize() const -{ - return 0x10; -} - -DeclarationAlignment ZCurveAnimation::GetDeclarationAlignment() const -{ - return DeclarationAlignment::Align4; -} - -std::string ZCurveAnimation::GetSourceTypeName() const -{ - return "CurveAnimationHeader"; -} - -/* ZLegacyAnimation */ - -ZLegacyAnimation::ZLegacyAnimation(ZFile* nParent) : ZAnimation(nParent) -{ -} - -void ZLegacyAnimation::ParseRawData() -{ - ZAnimation::ParseRawData(); - - const auto& rawData = parent->GetRawData(); - limbCount = BitConverter::ToInt16BE(rawData, rawDataIndex + 0x02); - frameData = BitConverter::ToUInt32BE(rawData, rawDataIndex + 0x04); - jointKey = BitConverter::ToUInt32BE(rawData, rawDataIndex + 0x08); - - if (GETSEGNUM(frameData) == parent->segment && GETSEGNUM(jointKey) == parent->segment) - { - uint32_t frameDataOffset = Seg2Filespace(frameData, parent->baseAddress); - uint32_t jointKeyOffset = Seg2Filespace(jointKey, parent->baseAddress); - - uint32_t ptr = frameDataOffset; - for (size_t i = 0; i < (jointKeyOffset - frameDataOffset) / 2; i++) - { - frameDataArray.push_back(BitConverter::ToUInt16BE(rawData, ptr)); - ptr += 2; - } - - ptr = jointKeyOffset; - for (int32_t i = 0; i < limbCount + 1; i++) - { - LegacyJointKey key(parent); - key.ExtractFromFile(ptr); - - jointKeyArray.push_back(key); - ptr += key.GetRawDataSize(); - } - } -} - -void ZLegacyAnimation::DeclareReferences(const std::string& prefix) -{ - std::string varPrefix = prefix; - if (name != "") - varPrefix = name; - - ZAnimation::DeclareReferences(varPrefix); - - if (!frameDataArray.empty()) - { - uint32_t frameDataOffset = Seg2Filespace(frameData, parent->baseAddress); - if (GETSEGNUM(frameData) == parent->segment && !parent->HasDeclaration(frameDataOffset)) - { - std::string frameDataBody = "\t"; - - for (size_t i = 0; i < frameDataArray.size(); i++) - { - frameDataBody += StringHelper::Sprintf("0x%04X, ", frameDataArray[i]); - - if (i % 8 == 7 && i + 1 < frameDataArray.size()) - frameDataBody += "\n\t"; - } - - std::string frameDataName = StringHelper::Sprintf("%sFrameData", varPrefix.c_str()); - parent->AddDeclarationArray(frameDataOffset, DeclarationAlignment::Align4, - frameDataArray.size() * 2, "s16", frameDataName, - frameDataArray.size(), frameDataBody); - } - } - - if (!jointKeyArray.empty()) - { - uint32_t jointKeyOffset = Seg2Filespace(jointKey, parent->baseAddress); - if (GETSEGNUM(jointKey) == parent->segment && !parent->HasDeclaration(jointKeyOffset)) - { - const auto res = jointKeyArray.at(0); - std::string jointKeyBody; - - for (size_t i = 0; i < jointKeyArray.size(); i++) - { - jointKeyBody += StringHelper::Sprintf("\t{ %s },", - jointKeyArray[i].GetBodySourceCode().c_str()); - - if (i + 1 < jointKeyArray.size()) - jointKeyBody += "\n"; - } - - std::string jointKeyName = StringHelper::Sprintf("%sJointKey", varPrefix.c_str()); - parent->AddDeclarationArray(jointKeyOffset, DeclarationAlignment::Align4, - jointKeyArray.size() * res.GetRawDataSize(), - res.GetSourceTypeName(), jointKeyName, jointKeyArray.size(), - jointKeyBody); - } - } -} - -std::string ZLegacyAnimation::GetBodySourceCode() const -{ - std::string body = "\n"; - - std::string frameDataName; - std::string jointKeyName; - Globals::Instance->GetSegmentedPtrName(frameData, parent, "s16", frameDataName); - Globals::Instance->GetSegmentedPtrName(jointKey, parent, "LegacyJointKey", jointKeyName); - - body += StringHelper::Sprintf("\t%i, %i,\n", frameCount, limbCount); - body += StringHelper::Sprintf("\t%s,\n", frameDataName.c_str()); - body += StringHelper::Sprintf("\t%s\n", jointKeyName.c_str()); - - return body; -} - -std::string ZLegacyAnimation::GetSourceTypeName() const -{ - return "LegacyAnimationHeader"; -} - -size_t ZLegacyAnimation::GetRawDataSize() const -{ - return 0x0C; -} - -LegacyJointKey::LegacyJointKey(ZFile* nParent) : ZResource(nParent) -{ -} - -void LegacyJointKey::ParseRawData() -{ - ZResource::ParseRawData(); - - const auto& rawData = parent->GetRawData(); - xMax = BitConverter::ToInt16BE(rawData, rawDataIndex + 0x00); - x = BitConverter::ToInt16BE(rawData, rawDataIndex + 0x02); - yMax = BitConverter::ToInt16BE(rawData, rawDataIndex + 0x04); - y = BitConverter::ToInt16BE(rawData, rawDataIndex + 0x06); - zMax = BitConverter::ToInt16BE(rawData, rawDataIndex + 0x08); - z = BitConverter::ToInt16BE(rawData, rawDataIndex + 0x0A); -} - -std::string LegacyJointKey::GetBodySourceCode() const -{ - return StringHelper::Sprintf("%6i, %6i, %6i, %6i, %6i, %6i", xMax, x, yMax, y, zMax, z); -} - -std::string LegacyJointKey::GetSourceTypeName() const -{ - return "LegacyJointKey"; -} - -ZResourceType LegacyJointKey::GetResourceType() const -{ - // TODO - return ZResourceType::Error; -} - -size_t LegacyJointKey::GetRawDataSize() const -{ - return 0x0C; -} diff --git a/tools/ZAPD/ZAPD/ZAnimation.h b/tools/ZAPD/ZAPD/ZAnimation.h deleted file mode 100644 index 643842b891..0000000000 --- a/tools/ZAPD/ZAPD/ZAnimation.h +++ /dev/null @@ -1,179 +0,0 @@ -#pragma once - -#include -#include -#include -#include "Vec3s.h" -#include "ZResource.h" -#include "ZSkeleton.h" -#include "tinyxml2.h" - -struct RotationIndex -{ - // uint16_t transX, transY, transZ; - uint16_t x, y, z; - - RotationIndex(uint16_t nX, uint16_t nY, uint16_t nZ) : x(nX), y(nY), z(nZ) {} -}; - -class ZAnimation : public ZResource -{ -public: - int16_t frameCount; - - ZAnimation(ZFile* nParent); - - ZResourceType GetResourceType() const override; - -protected: - void ParseRawData() override; -}; - -class ZNormalAnimation : public ZAnimation -{ -public: - std::vector rotationValues; - std::vector rotationIndices; - segptr_t rotationValuesSeg = 0; - segptr_t rotationIndicesSeg = 0; - offset_t rotationValuesOffset = 0; - offset_t rotationIndicesOffset = 0; - int16_t limit = 0; - - ZNormalAnimation(ZFile* nParent); - - void DeclareReferences(const std::string& prefix) override; - - std::string GetBodySourceCode() const override; - - size_t GetRawDataSize() const override; - std::string GetSourceTypeName() const override; - - void ParseRawData() override; -}; - -class ZLinkAnimation : public ZAnimation -{ -public: - segptr_t segmentAddress; - - ZLinkAnimation(ZFile* nParent); - - std::string GetBodySourceCode() const override; - - size_t GetRawDataSize() const override; - std::string GetSourceTypeName() const override; - - void ParseRawData() override; -}; - -class CurveInterpKnot -{ -protected: - ZFile* parent; - - ///* 0x0000 */ u16 unk_00; // appears to be flags - uint16_t unk_00; - ///* 0x0002 */ s16 unk_02; - int16_t unk_02; - ///* 0x0004 */ s16 unk_04; - int16_t unk_04; - ///* 0x0006 */ s16 unk_06; - int16_t unk_06; - ///* 0x0008 */ f32 unk_08; - float unk_08; - -public: - CurveInterpKnot() = default; - CurveInterpKnot(ZFile* parent, const std::vector& rawData, uint32_t fileOffset); - CurveInterpKnot(ZFile* parent, const std::vector& rawData, uint32_t fileOffset, - size_t index); - - [[nodiscard]] std::string GetBody(const std::string& prefix) const; - - size_t GetRawDataSize() const; - std::string GetSourceTypeName(); -}; - -class ZCurveAnimation : public ZAnimation -{ -protected: - segptr_t skelOffset = 0; - - ///* 0x0000 */ u8* refIndex; - segptr_t refIndex = 0; - ///* 0x0004 */ CurveInterpKnot* transformData; - segptr_t transformData = 0; - ///* 0x0008 */ s16* copyValues; - segptr_t copyValues = 0; - ///* 0x000C */ s16 unk_0C; - int16_t unk_0C; - ///* 0x000E */ s16 unk_10; - int16_t unk_10; - - uint8_t limbCount = 0; - - std::vector refIndexArr; - std::vector transformDataArr; - std::vector copyValuesArr; - -public: - ZCurveAnimation(ZFile* nParent); - - void ParseXML(tinyxml2::XMLElement* reader) override; - void ParseRawData() override; - - void DeclareReferences(const std::string& prefix) override; - - std::string GetBodySourceCode() const override; - - size_t GetRawDataSize() const override; - DeclarationAlignment GetDeclarationAlignment() const override; - - std::string GetSourceTypeName() const override; -}; -// CurveAnimationHeader - -/* ZLegacyAnimation */ - -class LegacyJointKey : public ZResource -{ -public: - LegacyJointKey(ZFile* nParent); - - void ParseRawData() override; - std::string GetBodySourceCode() const override; - - std::string GetSourceTypeName() const override; - ZResourceType GetResourceType() const override; - - size_t GetRawDataSize() const override; - -protected: - int16_t xMax, x; - int16_t yMax, y; - int16_t zMax, z; -}; - -class ZLegacyAnimation : public ZAnimation -{ -public: - ZLegacyAnimation(ZFile* nParent); - - void ParseRawData() override; - void DeclareReferences(const std::string& prefix) override; - - std::string GetBodySourceCode() const override; - - std::string GetSourceTypeName() const override; - - size_t GetRawDataSize() const override; - -protected: - int16_t limbCount; - segptr_t frameData; // s16* - segptr_t jointKey; // LegacyJointKey* - - std::vector frameDataArray; - std::vector jointKeyArray; -}; diff --git a/tools/ZAPD/ZAPD/ZArray.cpp b/tools/ZAPD/ZAPD/ZArray.cpp deleted file mode 100644 index 62720bc610..0000000000 --- a/tools/ZAPD/ZAPD/ZArray.cpp +++ /dev/null @@ -1,153 +0,0 @@ -#include "ZArray.h" - -#include - -#include "Globals.h" -#include "Utils/StringHelper.h" -#include "WarningHandler.h" -#include "ZFile.h" - -REGISTER_ZFILENODE(Array, ZArray); - -ZArray::ZArray(ZFile* nParent) : ZResource(nParent) -{ - canHaveInner = true; - RegisterRequiredAttribute("Count"); -} - -ZArray::~ZArray() -{ - for (auto res : resList) - delete res; -} - -void ZArray::ParseXML(tinyxml2::XMLElement* reader) -{ - ZResource::ParseXML(reader); - - arrayCnt = reader->IntAttribute("Count", 0); - if (arrayCnt <= 0) - { - HANDLE_ERROR_RESOURCE(WarningType::InvalidAttributeValue, parent, this, rawDataIndex, - "invalid value found for 'Count' attribute", ""); - } - - tinyxml2::XMLElement* child = reader->FirstChildElement(); - if (child == nullptr) - { - HANDLE_ERROR_RESOURCE(WarningType::InvalidXML, parent, this, rawDataIndex, - " needs one sub-element", ""); - } - - childName = child->Name(); - - auto nodeMap = ZFile::GetNodeMap(); - size_t childIndex = rawDataIndex; - resList.reserve(arrayCnt); - for (size_t i = 0; i < arrayCnt; i++) - { - ZResource* res = nodeMap->at(childName)(parent); - if (!res->DoesSupportArray()) - { - std::string errorHeader = StringHelper::Sprintf( - "resource <%s> does not support being wrapped in an ", childName.c_str()); - HANDLE_ERROR_RESOURCE(WarningType::InvalidXML, parent, this, rawDataIndex, errorHeader, - ""); - } - res->parent = parent; - res->SetInnerNode(true); - res->ExtractWithXML(child, childIndex); - - childIndex += res->GetRawDataSize(); - resList.push_back(res); - } -} - -Declaration* ZArray::DeclareVar(const std::string& prefix, const std::string& bodyStr) -{ - std::string auxName = name; - - if (name == "") - auxName = GetDefaultName(prefix); - - ZResource* res = resList.at(0); - Declaration* decl; - if (res->IsExternalResource()) - { - auto filepath = Globals::Instance->outputPath / name; - std::string includePath = StringHelper::Sprintf("%s.%s.inc", filepath.string().c_str(), - res->GetExternalExtension().c_str()); - decl = parent->AddDeclarationIncludeArray(rawDataIndex, includePath, GetRawDataSize(), - GetSourceTypeName(), name, arrayCnt); - decl->declBody = bodyStr; - decl->isExternal = true; - } - else - { - decl = - parent->AddDeclarationArray(rawDataIndex, GetDeclarationAlignment(), GetRawDataSize(), - GetSourceTypeName(), name, arrayCnt, bodyStr); - } - - decl->staticConf = staticConf; - return decl; -} - -std::string ZArray::GetBodySourceCode() const -{ - std::string output; - - for (size_t i = 0; i < arrayCnt; i++) - { - const auto& res = resList[i]; - output += "\t"; - - switch (res->GetResourceType()) - { - case ZResourceType::Pointer: - case ZResourceType::Scalar: - case ZResourceType::Vertex: - case ZResourceType::CollisionPoly: - case ZResourceType::SurfaceType: - case ZResourceType::Waterbox: - output += resList.at(i)->GetBodySourceCode(); - break; - - default: - output += StringHelper::Sprintf("{ %s }", resList.at(i)->GetBodySourceCode().c_str()); - break; - } - - if (i < arrayCnt - 1 || res->IsExternalResource()) - output += ",\n"; - } - - return output; -} - -size_t ZArray::GetRawDataSize() const -{ - size_t size = 0; - for (const auto res : resList) - size += res->GetRawDataSize(); - return size; -} - -std::string ZArray::GetSourceTypeName() const -{ - return resList.at(0)->GetSourceTypeName(); -} - -ZResourceType ZArray::GetResourceType() const -{ - return ZResourceType::Array; -} - -DeclarationAlignment ZArray::GetDeclarationAlignment() const -{ - if (resList.size() == 0) - { - return DeclarationAlignment::Align4; - } - return resList.at(0)->GetDeclarationAlignment(); -} diff --git a/tools/ZAPD/ZAPD/ZArray.h b/tools/ZAPD/ZAPD/ZArray.h deleted file mode 100644 index b78a8edfd8..0000000000 --- a/tools/ZAPD/ZAPD/ZArray.h +++ /dev/null @@ -1,31 +0,0 @@ -#pragma once - -#include -#include -#include -#include "ZResource.h" -#include "tinyxml2.h" - -class ZArray : public ZResource -{ -public: - ZArray(ZFile* nParent); - ~ZArray(); - - void ParseXML(tinyxml2::XMLElement* reader) override; - - Declaration* DeclareVar(const std::string& prefix, const std::string& bodyStr) override; - std::string GetBodySourceCode() const override; - - size_t GetRawDataSize() const override; - - std::string GetSourceTypeName() const override; - ZResourceType GetResourceType() const override; - - DeclarationAlignment GetDeclarationAlignment() const override; - -protected: - size_t arrayCnt; - std::string childName; - std::vector resList; -}; diff --git a/tools/ZAPD/ZAPD/ZBackground.cpp b/tools/ZAPD/ZAPD/ZBackground.cpp deleted file mode 100644 index fc725637e7..0000000000 --- a/tools/ZAPD/ZAPD/ZBackground.cpp +++ /dev/null @@ -1,197 +0,0 @@ -#include "ZBackground.h" - -#include "Globals.h" -#include "Utils/BitConverter.h" -#include "Utils/File.h" -#include "Utils/Path.h" -#include "Utils/StringHelper.h" -#include "WarningHandler.h" -#include "ZFile.h" - -REGISTER_ZFILENODE(Background, ZBackground); - -#define JPEG_MARKER 0xFFD8FFE0 -#define MARKER_DQT 0xFFDB -#define MARKER_EOI 0xFFD9 - -ZBackground::ZBackground(ZFile* nParent) : ZResource(nParent) -{ -} - -void ZBackground::ParseRawData() -{ - ZResource::ParseRawData(); - - const auto& rawData = parent->GetRawData(); - size_t i = 0; - while (true) - { - uint8_t val = rawData.at(rawDataIndex + i); - data.push_back(val); - - if (BitConverter::ToUInt16BE(rawData, rawDataIndex + i) == MARKER_EOI) - { - data.push_back(rawData.at(rawDataIndex + i + 1)); - break; - } - - i++; - } -} - -void ZBackground::ParseBinaryFile(const std::string& inFolder, bool appendOutName) -{ - fs::path filepath(inFolder); - - if (appendOutName) - filepath = filepath / (outName + "." + GetExternalExtension()); - - data = File::ReadAllBytes(filepath.string()); - - // Add padding. - data.insert(data.end(), GetRawDataSize() - data.size(), 0x00); - CheckValidJpeg(filepath.generic_string()); -} - -void ZBackground::CheckValidJpeg(const std::string& filepath) -{ - std::string filename = outName; - if (filepath != "") - { - filename = filepath; - } - - uint32_t jpegMarker = BitConverter::ToUInt32BE(data, 0); - if (jpegMarker != JPEG_MARKER) - { - HANDLE_WARNING_PROCESS( - WarningType::InvalidJPEG, - StringHelper::Sprintf("missing jpeg marker at beginning of file: '%s'", - filename.c_str()), - "The game will skip this jpeg."); - } - if (data.at(6) != 'J' || data.at(7) != 'F' || data.at(8) != 'I' || data.at(9) != 'F' || - data.at(10) != '\0') - { - std::string jfifIdentifier(data.begin() + 6, data.begin() + 6 + 5); - HANDLE_WARNING_PROCESS( - WarningType::InvalidJPEG, "missing 'JFIF' identifier", - StringHelper::Sprintf( - "This image may be corrupted, or not a jpeg. The identifier found was: '%s'", - jfifIdentifier.c_str())); - } - uint8_t majorVersion = data.at(11); - uint8_t minorVersion = data.at(12); - if (majorVersion != 0x01 || minorVersion != 0x01) - { - HANDLE_WARNING_PROCESS( - WarningType::InvalidJPEG, - StringHelper::Sprintf("wrong JFIF version '%i.%02i'", majorVersion, minorVersion), - "The expected version is '1.01'. The game may be unable to decode this image " - "correctly."); - } - if (BitConverter::ToUInt16BE(data, 20) != MARKER_DQT) - { - // This may happen when creating a custom image with Exif, XMP, thumbnail, progressive, etc. - // enabled. - HANDLE_WARNING_PROCESS(WarningType::InvalidJPEG, - "there seems to be extra data before the image data in this file", - "The game may not be able to decode this image correctly."); - } - if (data.size() > GetRawDataSize()) - { - HANDLE_WARNING_PROCESS( - WarningType::InvalidJPEG, "the image is bigger than the screen buffer", - StringHelper::Sprintf("Image size: %zu bytes\nScreen buffer size: %zu bytes", - data.size(), GetRawDataSize())); - } -} - -size_t ZBackground::GetRawDataSize() const -{ - // Jpgs use the whole sceen buffer, which is a u16 matrix. - return Globals::Instance->cfg.bgScreenHeight * Globals::Instance->cfg.bgScreenWidth * 2; -} - -Declaration* ZBackground::DeclareVar(const std::string& prefix, - [[maybe_unused]] const std::string& bodyStr) -{ - std::string auxName = name; - std::string auxOutName = outName; - - if (auxName == "") - auxName = GetDefaultName(prefix); - - if (auxOutName == "") - auxOutName = GetDefaultName(prefix); - - auto filepath = Globals::Instance->outputPath / fs::path(auxOutName).stem(); - - std::string incStr = - StringHelper::Sprintf("%s.%s.inc.c", filepath.c_str(), GetExternalExtension().c_str()); - - Declaration* decl = parent->AddDeclarationIncludeArray(rawDataIndex, incStr, GetRawDataSize(), - GetSourceTypeName(), auxName, 0); - - if (Globals::Instance->cfg.useScreenWidthHeightConstants) - { - decl->arrayItemCntStr = "SCREEN_WIDTH * SCREEN_HEIGHT / 4"; - decl->forceArrayCnt = true; - } - - decl->staticConf = staticConf; - return decl; -} - -bool ZBackground::IsExternalResource() const -{ - return true; -} - -std::string ZBackground::GetExternalExtension() const -{ - return "jpg"; -} - -void ZBackground::Save(const fs::path& outFolder) -{ - fs::path filepath = outFolder / (outName + "." + GetExternalExtension()); - File::WriteAllBytes(filepath.string(), data); -} - -std::string ZBackground::GetBodySourceCode() const -{ - std::string bodyStr = " "; - - for (size_t i = 0; i < data.size() / 8; ++i) - { - bodyStr += StringHelper::Sprintf("0x%016llX, ", BitConverter::ToUInt64BE(data, i * 8)); - - if (i % 8 == 7) - bodyStr += "\n "; - } - - bodyStr += "\n"; - - return bodyStr; -} - -std::string ZBackground::GetDefaultName(const std::string& prefix) const -{ - return StringHelper::Sprintf("%sBackground_%06X", prefix.c_str(), rawDataIndex); -} - -std::string ZBackground::GetSourceTypeName() const -{ - return "u64"; -} - -ZResourceType ZBackground::GetResourceType() const -{ - return ZResourceType::Background; -} - -DeclarationAlignment ZBackground::GetDeclarationAlignment() const -{ - return DeclarationAlignment::Align8; -} diff --git a/tools/ZAPD/ZAPD/ZBackground.h b/tools/ZAPD/ZAPD/ZBackground.h deleted file mode 100644 index e3728bd984..0000000000 --- a/tools/ZAPD/ZAPD/ZBackground.h +++ /dev/null @@ -1,34 +0,0 @@ -#pragma once - -#include -#include -#include "ZResource.h" - -class ZBackground : public ZResource -{ -protected: - std::vector data; - -public: - ZBackground(ZFile* nParent); - - void ParseBinaryFile(const std::string& inFolder, bool appendOutName); - - void ParseRawData() override; - - Declaration* DeclareVar(const std::string& prefix, const std::string& bodyStr) override; - std::string GetBodySourceCode() const override; - std::string GetDefaultName(const std::string& prefix) const override; - - void Save(const fs::path& outFolder) override; - - bool IsExternalResource() const override; - std::string GetSourceTypeName() const override; - ZResourceType GetResourceType() const override; - std::string GetExternalExtension() const override; - - size_t GetRawDataSize() const override; - DeclarationAlignment GetDeclarationAlignment() const override; - - void CheckValidJpeg(const std::string& filepath); -}; diff --git a/tools/ZAPD/ZAPD/ZBlob.cpp b/tools/ZAPD/ZAPD/ZBlob.cpp deleted file mode 100644 index 6812bfaee9..0000000000 --- a/tools/ZAPD/ZAPD/ZBlob.cpp +++ /dev/null @@ -1,114 +0,0 @@ -#include "ZBlob.h" - -#include "Globals.h" -#include "Utils/BitConverter.h" -#include "Utils/File.h" -#include "Utils/Path.h" -#include "Utils/StringHelper.h" -#include "ZFile.h" - -REGISTER_ZFILENODE(Blob, ZBlob); - -ZBlob::ZBlob(ZFile* nParent) : ZResource(nParent) -{ - RegisterRequiredAttribute("Size"); -} - -ZBlob* ZBlob::FromFile(const std::string& filePath) -{ - ZBlob* blob = new ZBlob(nullptr); - blob->name = StringHelper::Split(Path::GetFileNameWithoutExtension(filePath), ".")[0]; - blob->blobData = File::ReadAllBytes(filePath); - - return blob; -} - -void ZBlob::ParseXML(tinyxml2::XMLElement* reader) -{ - ZResource::ParseXML(reader); - - blobSize = StringHelper::StrToL(registeredAttributes.at("Size").value, 16); -} - -void ZBlob::ParseRawData() -{ - blobData.assign(parent->GetRawData().begin() + rawDataIndex, - parent->GetRawData().begin() + rawDataIndex + blobSize); -} - -Declaration* ZBlob::DeclareVar(const std::string& prefix, - [[maybe_unused]] const std::string& bodyStr) -{ - std::string auxName = name; - std::string auxOutName = outName; - - if (auxName == "") - auxName = GetDefaultName(prefix); - - if (auxOutName == "") - auxOutName = GetDefaultName(prefix); - - std::string path = Path::GetFileNameWithoutExtension(auxOutName); - - std::string assetOutDir = - (Globals::Instance->outputPath / Path::GetFileNameWithoutExtension(GetOutName())).string(); - - std::string incStr = - StringHelper::Sprintf("%s.%s.inc.c", assetOutDir.c_str(), GetExternalExtension().c_str()); - - return parent->AddDeclarationIncludeArray(rawDataIndex, incStr, GetRawDataSize(), - GetSourceTypeName(), auxName, blobData.size()); -} - -std::string ZBlob::GetBodySourceCode() const -{ - std::string sourceOutput; - - for (size_t i = 0; i < blobData.size(); i += 1) - { - if (i % 16 == 0) - sourceOutput += "\t"; - - sourceOutput += StringHelper::Sprintf("0x%02X, ", blobData[i]); - - if (i % 16 == 15) - sourceOutput += "\n"; - } - - // Ensure there's always a trailing line feed to prevent dumb warnings. - // Please don't remove this line, unless you somehow made a way to prevent - // that warning when building the OoT repo. - sourceOutput += "\n"; - - return sourceOutput; -} - -void ZBlob::Save(const fs::path& outFolder) -{ - File::WriteAllBytes((outFolder / (name + ".bin")).string(), blobData); -} - -bool ZBlob::IsExternalResource() const -{ - return true; -} - -std::string ZBlob::GetExternalExtension() const -{ - return "bin"; -} - -std::string ZBlob::GetSourceTypeName() const -{ - return "u8"; -} - -ZResourceType ZBlob::GetResourceType() const -{ - return ZResourceType::Blob; -} - -size_t ZBlob::GetRawDataSize() const -{ - return blobSize; -} diff --git a/tools/ZAPD/ZAPD/ZBlob.h b/tools/ZAPD/ZAPD/ZBlob.h deleted file mode 100644 index d7a7feff12..0000000000 --- a/tools/ZAPD/ZAPD/ZBlob.h +++ /dev/null @@ -1,31 +0,0 @@ -#pragma once - -#include "ZResource.h" -#include "tinyxml2.h" - -class ZBlob : public ZResource -{ -public: - ZBlob(ZFile* nParent); - - static ZBlob* FromFile(const std::string& filePath); - - void ParseXML(tinyxml2::XMLElement* reader) override; - void ParseRawData() override; - - Declaration* DeclareVar(const std::string& prefix, const std::string& bodyStr) override; - std::string GetBodySourceCode() const override; - - void Save(const fs::path& outFolder) override; - - bool IsExternalResource() const override; - std::string GetSourceTypeName() const override; - ZResourceType GetResourceType() const override; - std::string GetExternalExtension() const override; - - size_t GetRawDataSize() const override; - -protected: - std::vector blobData; - size_t blobSize = 0; -}; diff --git a/tools/ZAPD/ZAPD/ZCKeyFrame.cpp b/tools/ZAPD/ZAPD/ZCKeyFrame.cpp deleted file mode 100644 index 3893394f5c..0000000000 --- a/tools/ZAPD/ZAPD/ZCKeyFrame.cpp +++ /dev/null @@ -1,312 +0,0 @@ -#include "ZCKeyFrame.h" - -#include "Globals.h" -#include "Utils/BitConverter.h" -#include "Utils/StringHelper.h" -#include "WarningHandler.h" - -REGISTER_ZFILENODE(KeyFrameSkel, ZKeyFrameSkel); -REGISTER_ZFILENODE(KeyFrameLimbList, ZKeyFrameLimbList); - -ZKeyFrameSkel::ZKeyFrameSkel(ZFile* nParent) : ZResource(nParent) -{ - RegisterRequiredAttribute("LimbType"); -} - -ZKeyFrameSkel::~ZKeyFrameSkel() -{ -} - -ZKeyFrameLimb::ZKeyFrameLimb(ZFile* nParent) : ZResource(nParent) -{ -} - -ZKeyFrameStandardLimb::ZKeyFrameStandardLimb(ZFile* nParent) : ZKeyFrameLimb(nParent) -{ -} - -ZKeyFrameFlexLimb::ZKeyFrameFlexLimb(ZFile* nParent) : ZKeyFrameLimb(nParent) -{ -} - -ZKeyFrameLimbList::ZKeyFrameLimbList(ZFile* nParent) : ZResource(nParent) -{ - RegisterRequiredAttribute("LimbType"); - RegisterRequiredAttribute("LimbCount"); -} - -ZKeyFrameLimbList::ZKeyFrameLimbList(ZFile* nParent, uint32_t limbCount, ZKeyframeSkelType type) - : ZResource(nParent) -{ - numLimbs = limbCount; - limbType = type; -} - -ZKeyFrameLimbList::~ZKeyFrameLimbList() -{ - for (const auto l : limbs) - delete l; -} - -void ZKeyFrameSkel::ParseXML(tinyxml2::XMLElement* reader) -{ - ZResource::ParseXML(reader); - - std::string limbTypeStr = registeredAttributes.at("LimbType").value; - - limbType = ZKeyFrameLimbList::ParseLimbTypeStr(limbTypeStr); - if (limbType == ZKeyframeSkelType::Error) - HANDLE_ERROR_RESOURCE( - WarningType::InvalidXML, parent, this, rawDataIndex, "Invalid limb type", - StringHelper::Sprintf("Invalid limb type. Was expecting 'Flex' or 'Normal'. Got %s.", - limbTypeStr.c_str())); -} -void ZKeyFrameLimbList::ParseXML(tinyxml2::XMLElement* reader) -{ - ZResource::ParseXML(reader); - - std::string limbTypeStr = registeredAttributes.at("LimbType").value; - std::string numLimbStr = registeredAttributes.at("LimbCount").value; - - limbType = ParseLimbTypeStr(limbTypeStr); - - if (limbType == ZKeyframeSkelType::Error) - HANDLE_ERROR_RESOURCE( - WarningType::InvalidXML, parent, this, rawDataIndex, "Invalid limb type", - StringHelper::Sprintf("Invalid limb type. Was expecting 'Flex' or 'Normal'. Got %s.", - limbTypeStr.c_str())); - - numLimbs = (uint8_t)StringHelper::StrToL(numLimbStr); -} - -void ZKeyFrameSkel::ParseRawData() -{ - ZResource::ParseRawData(); - - const auto& rawData = parent->GetRawData(); - limbCount = BitConverter::ToUInt8BE(rawData, rawDataIndex + 0); - dListCount = BitConverter::ToUInt8BE(rawData, rawDataIndex + 1); - limbsPtr = BitConverter::ToUInt32BE(rawData, rawDataIndex + 4); - - limbList = std::make_unique(parent, limbCount, limbType); - limbList->SetRawDataIndex(GETSEGOFFSET(limbsPtr)); - limbList->ParseRawData(); -} - -void ZKeyFrameSkel::DeclareReferences(const std::string& prefix) -{ - std::string defaultPrefix = name; - std::string declaration; - - if (defaultPrefix == "") - defaultPrefix = prefix; - - ZResource::DeclareReferences(defaultPrefix); - declaration += limbList->GetBodySourceCode(); - parent->AddDeclarationArray( - GETSEGOFFSET(limbsPtr), DeclarationAlignment::Align4, limbList->GetRawDataSize(), - limbList->GetSourceTypeName(), - StringHelper::Sprintf("%s_KeyFrameLimbs_%06X", prefix.c_str(), rawDataIndex), - limbList->limbs.size(), declaration); -} - -std::string ZKeyFrameSkel::GetBodySourceCode() const -{ - std::string limbStr; - - if (limbType == ZKeyframeSkelType::Normal) - Globals::Instance->GetSegmentedPtrName(limbsPtr, parent, "KeyFrameStandardLimb", limbStr); - else - Globals::Instance->GetSegmentedPtrName(limbsPtr, parent, "KeyFrameFlexLimb", limbStr); - - return StringHelper::Sprintf("\n\t0x%02X, 0x%02X, %s\n", limbCount, dListCount, - limbStr.c_str()); -} - -size_t ZKeyFrameSkel::GetRawDataSize() const -{ - return 0x8; -} - -std::string ZKeyFrameSkel::GetSourceTypeName() const -{ - switch (limbType) - { - case ZKeyframeSkelType::Normal: - return "KeyFrameSkeleton"; - - case ZKeyframeSkelType::Flex: - return "KeyFrameFlexSkeleton"; - - default: - return "KeyFrameSkeleton"; - } -} - -ZResourceType ZKeyFrameSkel::GetResourceType() const -{ - return ZResourceType::KeyFrameSkel; -} - -size_t ZKeyFrameStandardLimb::GetRawDataSize() const -{ - return 0xC; -} - -size_t ZKeyFrameFlexLimb::GetRawDataSize() const -{ - return 0x8; -} - -size_t ZKeyFrameLimbList::GetRawDataSize() const -{ - size_t limbSize; - if (limbType == ZKeyframeSkelType::Flex) - limbSize = 0x8; - else - limbSize = 0xC; - - return limbSize * numLimbs; -} - -ZKeyframeSkelType ZKeyFrameLimbList::ParseLimbTypeStr(const std::string& typeStr) -{ - if (typeStr == "Flex") - return ZKeyframeSkelType::Flex; - else if (typeStr == "Normal") - return ZKeyframeSkelType::Normal; - else - return ZKeyframeSkelType::Error; -} - -void ZKeyFrameLimb::ParseRawData() -{ - const auto& rawData = parent->GetRawData(); - - dlist = BitConverter::ToUInt32BE(rawData, rawDataIndex + 0x0); - numChildren = BitConverter::ToUInt8BE(rawData, rawDataIndex + 0x4); - flags = BitConverter::ToUInt8BE(rawData, rawDataIndex + 0x5); -} - -void ZKeyFrameStandardLimb::ParseRawData() -{ - const auto& rawData = parent->GetRawData(); - - ZKeyFrameLimb::ParseRawData(); - translation.x = BitConverter::ToUInt16BE(rawData, rawDataIndex + 0x6); - translation.y = BitConverter::ToUInt16BE(rawData, rawDataIndex + 0x8); - translation.z = BitConverter::ToUInt16BE(rawData, rawDataIndex + 0xA); -} - -void ZKeyFrameFlexLimb::ParseRawData() -{ - const auto& rawData = parent->GetRawData(); - - ZKeyFrameLimb::ParseRawData(); - callbackIndex = BitConverter::ToUInt8BE(rawData, rawDataIndex + 0x6); -} - -void ZKeyFrameLimbList::ParseRawData() -{ - limbs.reserve(numLimbs); - rawDataIndex = GetRawDataIndex(); - - for (uint32_t i = 0; i < numLimbs; i++) - { - ZKeyFrameLimb* limb; - if (limbType == ZKeyframeSkelType::Flex) - limb = new ZKeyFrameFlexLimb(parent); - else - limb = new ZKeyFrameStandardLimb(parent); - - limb->SetRawDataIndex(rawDataIndex + (offset_t)(i * limb->GetRawDataSize())); - limb->ParseRawData(); - limbs.push_back(limb); - } -} - -std::string ZKeyFrameLimbList::GetBodySourceCode() const -{ - std::string declaration; - - for (const auto l : limbs) - declaration += StringHelper::Sprintf("\t{ %s },\n", l->GetBodySourceCode().c_str()); - // Remove last newline - return declaration.substr(0, declaration.length() - 1); -} - -std::string ZKeyFrameStandardLimb::GetBodySourceCode() const -{ - std::string declaration; - std::string dlString; - - Globals::Instance->GetSegmentedArrayIndexedName(dlist, 8, parent, "Gfx", dlString); - - declaration += - StringHelper::Sprintf("%s, 0x%02X, 0x%02X, { 0x%04X, 0x%04X, 0x%04X},", dlString.c_str(), - numChildren, flags, translation.x, translation.y, translation.z); - return declaration; -} - -std::string ZKeyFrameFlexLimb::GetBodySourceCode() const -{ - std::string declaration; - - std::string dlString; - - Globals::Instance->GetSegmentedArrayIndexedName(dlist, 8, parent, "Gfx", dlString); - - declaration += StringHelper::Sprintf("%s, 0x%02X, 0x%02X, 0x%02X", dlString.c_str(), - numChildren, flags, callbackIndex); - return declaration; -} - -std::string ZKeyFrameStandardLimb::GetSourceTypeName() const -{ - return "KeyFrameStandardLimb"; -} - -std::string ZKeyFrameFlexLimb::GetSourceTypeName() const -{ - return "KeyFrameFlexLimb"; -} - -std::string ZKeyFrameLimbList::GetSourceTypeName() const -{ - switch (limbType) - { - case ZKeyframeSkelType::Flex: - return "KeyFrameFlexLimb"; - case ZKeyframeSkelType::Normal: - return "KeyFrameStandardLimb"; - default: - HANDLE_ERROR_RESOURCE(WarningType::InvalidXML, parent, this, rawDataIndex, - "Invalid limb type", ""); - break; - } -} - -ZResourceType ZKeyFrameStandardLimb::GetResourceType() const -{ - return ZResourceType::KeyFrameStandardLimb; -} - -ZResourceType ZKeyFrameFlexLimb::GetResourceType() const -{ - return ZResourceType::KeyFrameFlexLimb; -} - -ZResourceType ZKeyFrameLimbList::GetResourceType() const -{ - switch (limbType) - { - case ZKeyframeSkelType::Flex: - return ZResourceType::KeyFrameFlexLimb; - case ZKeyframeSkelType::Normal: - return ZResourceType::KeyFrameStandardLimb; - default: - HANDLE_ERROR_RESOURCE(WarningType::InvalidXML, parent, this, rawDataIndex, - "Invalid limb type", ""); - break; - } -} diff --git a/tools/ZAPD/ZAPD/ZCKeyFrame.h b/tools/ZAPD/ZAPD/ZCKeyFrame.h deleted file mode 100644 index 417d7cc686..0000000000 --- a/tools/ZAPD/ZAPD/ZCKeyFrame.h +++ /dev/null @@ -1,121 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -#include "ZFile.h" - -class ZKeyFrameLimb; - -struct Vec3s -{ - int16_t x; - int16_t y; - int16_t z; -}; - -enum class ZKeyframeSkelType -{ - Normal, - Flex, - Error, -}; - -class ZKeyFrameLimbList : public ZResource -{ -public: - ZKeyFrameLimbList(); - ZKeyFrameLimbList(ZFile* nParent); - ZKeyFrameLimbList(ZFile* nParent, uint32_t limbCount, ZKeyframeSkelType type); - - ~ZKeyFrameLimbList(); - - void ParseRawData() override; - - std::string GetBodySourceCode() const override; - void ParseXML(tinyxml2::XMLElement* reader) override; - - std::string GetSourceTypeName() const override; - ZResourceType GetResourceType() const override; - - size_t GetRawDataSize() const override; - - static ZKeyframeSkelType ParseLimbTypeStr(const std::string& typeStr); - - std::vector limbs; - ZKeyframeSkelType limbType; - uint8_t numLimbs; -}; - -class ZKeyFrameLimb : public ZResource -{ -public: - segptr_t dlist; - uint8_t numChildren; - uint8_t flags; - - ZKeyFrameLimb(ZFile* nParent); - void ParseRawData() override; -}; - -class ZKeyFrameStandardLimb : public ZKeyFrameLimb -{ -public: - Vec3s translation; - - ZKeyFrameStandardLimb(ZFile* nParent); - void ParseRawData() override; - - std::string GetBodySourceCode() const override; - - - std::string GetSourceTypeName() const override; - ZResourceType GetResourceType() const override; - - size_t GetRawDataSize() const override; -}; - -class ZKeyFrameFlexLimb : public ZKeyFrameLimb -{ -public: - uint8_t callbackIndex; - - ZKeyFrameFlexLimb(ZFile* nParent); - // void ParseXML(tinyxml2::XMLElement* reader) override; - void ParseRawData() override; - - std::string GetBodySourceCode() const override; - - // std::string GetSourceOutputHeader(const std::string& prefix) override; - - std::string GetSourceTypeName() const override; - ZResourceType GetResourceType() const override; - - size_t GetRawDataSize() const override; -}; - -class ZKeyFrameSkel : public ZResource -{ -public: - std::unique_ptr limbList; - segptr_t limbsPtr; - ZKeyframeSkelType limbType; - uint8_t limbCount; - uint8_t dListCount; - - ZKeyFrameSkel(ZFile* nParent); - ~ZKeyFrameSkel(); - - void ParseXML(tinyxml2::XMLElement* reader) override; - void ParseRawData() override; - void DeclareReferences(const std::string& prefix) override; - - std::string GetBodySourceCode() const override; - - std::string GetSourceTypeName() const override; - ZResourceType GetResourceType() const override; - - size_t GetRawDataSize() const override; -}; diff --git a/tools/ZAPD/ZAPD/ZCKeyFrameAnim.cpp b/tools/ZAPD/ZAPD/ZCKeyFrameAnim.cpp deleted file mode 100644 index 0b07471333..0000000000 --- a/tools/ZAPD/ZAPD/ZCKeyFrameAnim.cpp +++ /dev/null @@ -1,219 +0,0 @@ -#include "ZCkeyFrameAnim.h" -#include "ZCKeyFrame.h" -#include "Globals.h" - -#include "Utils/BitConverter.h" - -REGISTER_ZFILENODE(KeyFrameAnimation, ZKeyFrameAnim); - -ZKeyFrameAnim::ZKeyFrameAnim(ZFile* nParent) : ZResource(nParent) -{ - RegisterRequiredAttribute("Skel"); -} - -ZKeyFrameAnim::~ZKeyFrameAnim() -{ -} - -void ZKeyFrameAnim::ParseXML(tinyxml2::XMLElement* reader) -{ - ZResource::ParseXML(reader); - - std::string skelAddrStr = registeredAttributes.at("Skel").value; - skelOffset = (offset_t)StringHelper::StrToL(skelAddrStr, 16); -} - -void ZKeyFrameAnim::DeclareReferencesLate(const std::string& prefix) -{ - std::string defaultPrefix = name; - std::string declaration; - - if (defaultPrefix == "") - defaultPrefix = prefix; - - ZResource::DeclareReferences(defaultPrefix); - - declaration += "\t"; - - if (skel->limbType == ZKeyframeSkelType::Normal) - { - for (const auto b : bitFlags) - { - declaration += StringHelper::Sprintf("0x%02X, ", b); - parent->AddDeclarationArray( - GETSEGOFFSET(bitFlagsAddr), DeclarationAlignment::Align4, bitFlags.size(), "u8", - StringHelper::Sprintf("%s_bitFlags_%06X", prefix.c_str(), rawDataIndex), - bitFlags.size(), declaration); - } - } - else - { - for (const auto b : bitFlagsFlex) - { - declaration += StringHelper::Sprintf("0x%04X, ", b); - parent->AddDeclarationArray( - GETSEGOFFSET(bitFlagsAddr), DeclarationAlignment::Align4, bitFlagsFlex.size() * 2, - "u16", StringHelper::Sprintf("%s_flexBitFlags_%06X", prefix.c_str(), rawDataIndex), - bitFlagsFlex.size(), declaration); - } - } - declaration.clear(); - - for (const auto kf : keyFrames) - { - declaration += - StringHelper::Sprintf(" \t { %i, %i, %i, },\n", kf.frame, kf.value, kf.velocity); - } - // Remove last new line to prevent an extra line after the last element - declaration = declaration.substr(0, declaration.length() - 1); - parent->AddDeclarationArray( - GETSEGOFFSET(keyFramesAddr), DeclarationAlignment::Align4, keyFrames.size() * 6, "KeyFrame", - StringHelper::Sprintf("%s_KeyFrame_%06X", prefix.c_str(), rawDataIndex), keyFrames.size(), - declaration); - - declaration.clear(); - - declaration += "\t"; - - for (const auto kfNum : kfNums) - { - declaration += StringHelper::Sprintf("0x%04X, ", kfNum); - } - - parent->AddDeclarationArray( - GETSEGOFFSET(kfNumsAddr), DeclarationAlignment::Align4, kfNums.size() * 2, "s16", - StringHelper::Sprintf("%s_kfNums_%06X", prefix.c_str(), rawDataIndex), kfNums.size(), - declaration); - declaration += "\n"; - - declaration.clear(); - - declaration += "\t"; - - for (const auto pv : presetValues) - { - declaration += StringHelper::Sprintf("0x%04X, ", pv); - } - declaration += "\n"; - parent->AddDeclarationArray( - GETSEGOFFSET(presentValuesAddr), DeclarationAlignment::Align4, presetValues.size() * 2, - "s16", StringHelper::Sprintf("%s_presetValues_%06X", prefix.c_str(), rawDataIndex), - presetValues.size(), declaration); - -} - -// ParseRawDataLate is used because we need to make sure the flex skel has been processed first. -void ZKeyFrameAnim::ParseRawDataLate() -{ - const auto& rawData = parent->GetRawData(); - - skel = static_cast(parent->FindResource(skelOffset)); - size_t numLimbs = skel->limbCount; - - bitFlagsAddr = BitConverter::ToUInt32BE(rawData, rawDataIndex + 0x0); - keyFramesAddr = BitConverter::ToUInt32BE(rawData, rawDataIndex + 0x4); - kfNumsAddr = BitConverter::ToUInt32BE(rawData, rawDataIndex + 0x8); - presentValuesAddr = BitConverter::ToUInt32BE(rawData, rawDataIndex + 0xC); - - uint32_t kfNumsSize = 0; - uint32_t presetValuesSize = 0; - uint32_t keyFramesCount = 0; - if (skel->limbType == ZKeyframeSkelType::Normal) - { - bitFlags.reserve(numLimbs); - for (size_t i = 0; i < numLimbs; i++) - { - uint8_t e = BitConverter::ToUInt8BE(rawData, GETSEGOFFSET(bitFlagsAddr) + i); - bitFlags.push_back(e); - kfNumsSize += GetSetBits((uint8_t)(e & 0b111111)); - presetValuesSize += GetSetBits((uint8_t)((e ^ 0xFF) & 0b111111)); - } - } - else - { - bitFlagsFlex.reserve(numLimbs); - for (size_t i = 0; i < numLimbs; i++) - { - uint16_t e = BitConverter::ToUInt16BE(rawData, GETSEGOFFSET(bitFlagsAddr) + (i * 2)); - bitFlagsFlex.push_back(e); - kfNumsSize += GetSetBits((uint16_t)(e & 0b111111111)); - presetValuesSize += GetSetBits((uint16_t)((e ^ 0xFFFF) & 0b111111111)); - } - } - - kfNums.reserve(kfNumsSize); - for (uint32_t i = 0; i < kfNumsSize; i++) - { - int16_t kfNum = BitConverter::ToUInt16BE(rawData, GETSEGOFFSET(kfNumsAddr) + (i * 2)); - keyFramesCount += kfNum; - kfNums.push_back(kfNum); - } - - keyFrames.reserve(keyFramesCount); - for (uint32_t i = 0; i < keyFramesCount; i++) - { - KeyFrame kf; - kf.frame = BitConverter::ToInt16BE(rawData, (GETSEGOFFSET(keyFramesAddr) + 0) + (i * 6)); - kf.value = BitConverter::ToInt16BE(rawData, (GETSEGOFFSET(keyFramesAddr) + 2) + (i * 6)); - kf.velocity = BitConverter::ToInt16BE(rawData, (GETSEGOFFSET(keyFramesAddr) + 4) + (i * 6)); - keyFrames.push_back(kf); - } - - presetValues.reserve(presetValuesSize); - for (uint32_t i = 0; i < presetValuesSize; i++) - { - presetValues.push_back( - BitConverter::ToInt16BE(rawData, GETSEGOFFSET(presentValuesAddr) + (i * 2))); - } - - unk_10 = BitConverter::ToInt16BE(rawData, GETSEGOFFSET(rawDataIndex) + 0x10); - duration = BitConverter::ToInt16BE(rawData, GETSEGOFFSET(rawDataIndex) + 0x12); -} - -std::string ZKeyFrameAnim::GetBodySourceCode() const -{ - std::string declaration; - - std::string bitFlagsStr; - std::string keyFrameStr; - std::string kfNumsStr; - std::string presetValuesStr; - - Globals::Instance->GetSegmentedPtrName(bitFlagsAddr, parent, "", bitFlagsStr); - Globals::Instance->GetSegmentedPtrName(keyFramesAddr, parent, "", keyFrameStr); - Globals::Instance->GetSegmentedPtrName(kfNumsAddr, parent, "", kfNumsStr); - Globals::Instance->GetSegmentedPtrName(presentValuesAddr, parent, "", presetValuesStr); - - return StringHelper::Sprintf("\n\t%s, %s, %s, %s, 0x%04X, 0x%04X\n", bitFlagsStr.c_str(), - keyFrameStr.c_str(), kfNumsStr.c_str(), presetValuesStr.c_str(), - unk_10, duration); -} - -std::string ZKeyFrameAnim::GetSourceTypeName() const -{ - return "KeyFrameAnimation"; -} - -ZResourceType ZKeyFrameAnim::GetResourceType() const -{ - return ZResourceType::KeyFrameAnimation; -} - -size_t ZKeyFrameAnim::GetRawDataSize() const -{ - return 0x14; -} - -template -uint32_t ZKeyFrameAnim::GetSetBits(T data) const -{ - uint32_t num = 0; - - for (size_t i = 0; i < sizeof(T) * 8; i++) - { - if ((data >> i) & 1) - num++; - } - - return num; -} \ No newline at end of file diff --git a/tools/ZAPD/ZAPD/ZCkeyFrameAnim.h b/tools/ZAPD/ZAPD/ZCkeyFrameAnim.h deleted file mode 100644 index 64f95b13ae..0000000000 --- a/tools/ZAPD/ZAPD/ZCkeyFrameAnim.h +++ /dev/null @@ -1,52 +0,0 @@ -#pragma once -#include -#include -#include -#include - -#include "ZFile.h" - -class ZKeyFrameSkel; - -typedef struct -{ - int16_t frame; - int16_t value; - int16_t velocity; -} KeyFrame; - -class ZKeyFrameAnim : public ZResource -{ -public: - ZKeyFrameSkel* skel; - std::vector bitFlags; // Standard only - std::vector bitFlagsFlex; // Flex only - - std::vector keyFrames; - std::vector kfNums; - std::vector presetValues; - - uint16_t unk_10; - int16_t duration; - - ZKeyFrameAnim(ZFile* nParent); - ~ZKeyFrameAnim(); - void ParseXML(tinyxml2::XMLElement* reader) override; - void DeclareReferencesLate(const std::string& prefix) override; - void ParseRawDataLate() override; - std::string GetBodySourceCode() const override; - - std::string GetSourceTypeName() const override; - ZResourceType GetResourceType() const override; - - size_t GetRawDataSize() const override; - -private: - offset_t skelOffset; - segptr_t bitFlagsAddr; - segptr_t keyFramesAddr; - segptr_t kfNumsAddr; - segptr_t presentValuesAddr; - template - uint32_t GetSetBits(T data) const; -}; diff --git a/tools/ZAPD/ZAPD/ZCollision.cpp b/tools/ZAPD/ZAPD/ZCollision.cpp deleted file mode 100644 index d177e036cb..0000000000 --- a/tools/ZAPD/ZAPD/ZCollision.cpp +++ /dev/null @@ -1,413 +0,0 @@ -#include "ZCollision.h" -#include "ZWaterbox.h" - -#include -#include -#include - -#include "Globals.h" -#include "Utils/BitConverter.h" -#include "Utils/StringHelper.h" - -REGISTER_ZFILENODE(Collision, ZCollisionHeader); - -ZCollisionHeader::ZCollisionHeader(ZFile* nParent) : ZResource(nParent) -{ -} - -ZCollisionHeader::~ZCollisionHeader() -{ - delete camData; -} - -void ZCollisionHeader::ParseRawData() -{ - const auto& rawData = parent->GetRawData(); - - absMinX = BitConverter::ToInt16BE(rawData, rawDataIndex + 0); - absMinY = BitConverter::ToInt16BE(rawData, rawDataIndex + 2); - absMinZ = BitConverter::ToInt16BE(rawData, rawDataIndex + 4); - - absMaxX = BitConverter::ToInt16BE(rawData, rawDataIndex + 6); - absMaxY = BitConverter::ToInt16BE(rawData, rawDataIndex + 8); - absMaxZ = BitConverter::ToInt16BE(rawData, rawDataIndex + 10); - - numVerts = BitConverter::ToUInt16BE(rawData, rawDataIndex + 12); - vtxAddress = BitConverter::ToInt32BE(rawData, rawDataIndex + 16); - - numPolygons = BitConverter::ToUInt16BE(rawData, rawDataIndex + 20); - polyAddress = BitConverter::ToInt32BE(rawData, rawDataIndex + 24); - polyTypeDefAddress = BitConverter::ToInt32BE(rawData, rawDataIndex + 28); - camDataAddress = BitConverter::ToInt32BE(rawData, rawDataIndex + 32); - - numWaterBoxes = BitConverter::ToUInt16BE(rawData, rawDataIndex + 36); - waterBoxAddress = BitConverter::ToInt32BE(rawData, rawDataIndex + 40); - - vtxSegmentOffset = Seg2Filespace(vtxAddress, parent->baseAddress); - polySegmentOffset = Seg2Filespace(polyAddress, parent->baseAddress); - polyTypeDefSegmentOffset = Seg2Filespace(polyTypeDefAddress, parent->baseAddress); - camDataSegmentOffset = Seg2Filespace(camDataAddress, parent->baseAddress); - waterBoxSegmentOffset = Seg2Filespace(waterBoxAddress, parent->baseAddress); - - vertices.reserve(numVerts); - polygons.reserve(numPolygons); - waterBoxes.reserve(numWaterBoxes); - - offset_t currentPtr = vtxSegmentOffset; - - for (uint16_t i = 0; i < numVerts; i++) - { - ZVector vec(parent); - vec.ExtractFromBinary(currentPtr, ZScalarType::ZSCALAR_S16, 3); - - currentPtr += vec.GetRawDataSize(); - vertices.push_back(vec); - } - - for (uint16_t i = 0; i < numPolygons; i++) - { - ZCollisionPoly poly(parent); - poly.SetRawDataIndex(polySegmentOffset + (i * 16)); - poly.ParseRawData(); - polygons.push_back(poly); - } - - uint16_t highestPolyType = 0; - - for (const ZCollisionPoly& poly : polygons) - { - if (poly.type > highestPolyType) - highestPolyType = poly.type; - } - - for (uint16_t i = 0; i < highestPolyType + 1; i++) - { - ZSurfaceType surfaceType(parent); - surfaceType.SetRawDataIndex(polyTypeDefSegmentOffset + (i * 8)); - surfaceType.ParseRawData(); - polygonTypes.push_back(surfaceType); - } - // polygonTypes.push_back( - // BitConverter::ToUInt64BE(rawData, polyTypeDefSegmentOffset + (i * 8))); - - if (camDataAddress != SEGMENTED_NULL) - { - // Try to guess how many elements the CamDataList array has. - // The "guessing algorithm" is basically a "best effort" one and it - // is error-prone. - // This is based mostly on observation of how CollisionHeader data is - // usually ordered. If for some reason the data was in some other funny - // order, this would probably break. - // The most common ordering is: - // - *BgCamInfo* - // - SurfaceType - // - CollisionPoly - // - Vertices - // - WaterBoxes - // - CollisionHeader - offset_t upperCameraBoundary = polyTypeDefSegmentOffset; - if (upperCameraBoundary == SEGMENTED_NULL) - { - upperCameraBoundary = polySegmentOffset; - } - if (upperCameraBoundary == SEGMENTED_NULL) - { - upperCameraBoundary = vtxSegmentOffset; - } - if (upperCameraBoundary == SEGMENTED_NULL) - { - upperCameraBoundary = waterBoxSegmentOffset; - } - if (upperCameraBoundary == SEGMENTED_NULL) - { - upperCameraBoundary = rawDataIndex; - } - - // Sharp Ocarina places the CamDataEntries above the list so we need to calculate the number - // of cameras differently. - if (upperCameraBoundary < camDataSegmentOffset) - { - offset_t offset = camDataSegmentOffset; - while (rawData[offset] == 0x00 && rawData[offset + 0x4] == 0x02) - { - offset += 0x08; - } - upperCameraBoundary = offset; - } - - camData = - new CameraDataList(parent, name, rawData, camDataSegmentOffset, upperCameraBoundary); - } - - for (int32_t i = 0; i < numWaterBoxes; i++) - { - ZWaterbox waterbox(parent); - - waterbox.SetRawDataIndex(waterBoxSegmentOffset + - (i * (Globals::Instance->game == ZGame::OOT_SW97 ? 12 : 16))); - waterbox.ParseRawData(); - waterBoxes.emplace_back(waterbox); - } -} - -void ZCollisionHeader::DeclareReferences(const std::string& prefix) -{ - std::string declaration = ""; - std::string auxName = name; - - if (name == "") - auxName = GetDefaultName(prefix); - - if (waterBoxes.size() > 0) - { - for (size_t i = 0; i < waterBoxes.size(); i++) - { - declaration += - StringHelper::Sprintf("\t{ %s },", waterBoxes[i].GetBodySourceCode().c_str()); - if (i + 1 < waterBoxes.size()) - declaration += "\n"; - } - - parent->AddDeclarationArray(waterBoxSegmentOffset, DeclarationAlignment::Align4, - waterBoxes[0].GetRawDataSize() * waterBoxes.size(), - waterBoxes[0].GetSourceTypeName().c_str(), - StringHelper::Sprintf("%sWaterBoxes", auxName.c_str()), - waterBoxes.size(), declaration); - } - - if (polygons.size() > 0) - { - declaration.clear(); - - for (size_t i = 0; i < polygons.size(); i++) - { - declaration += StringHelper::Sprintf("\t%s,", polygons[i].GetBodySourceCode().c_str()); - if (i + 1 < polygons.size()) - declaration += "\n"; - } - - parent->AddDeclarationArray(polySegmentOffset, DeclarationAlignment::Align4, - polygons.size() * 16, polygons[0].GetSourceTypeName().c_str(), - StringHelper::Sprintf("%sPolygons", auxName.c_str()), - polygons.size(), declaration); - } - - declaration.clear(); - for (const auto& polyType : polygonTypes) - { - declaration += StringHelper::Sprintf("\t%s,", polyType.GetBodySourceCode().c_str()); - } - - if (polyTypeDefAddress != SEGMENTED_NULL) - parent->AddDeclarationArray(polyTypeDefSegmentOffset, DeclarationAlignment::Align4, - polygonTypes.size() * 8, - polygonTypes[0].GetSourceTypeName().c_str(), - StringHelper::Sprintf("%sSurfaceType", auxName.c_str()), - polygonTypes.size(), declaration); - - declaration.clear(); - - if (vertices.size() > 0) - { - declaration.clear(); - - for (size_t i = 0; i < vertices.size(); i++) - { - declaration += - StringHelper::Sprintf("\t{ %s },", vertices[i].GetBodySourceCode().c_str()); - - if (i < vertices.size() - 1) - declaration += "\n"; - } - - const auto& first = vertices.front(); - if (vtxAddress != 0) - parent->AddDeclarationArray( - vtxSegmentOffset, first.GetDeclarationAlignment(), - vertices.size() * first.GetRawDataSize(), first.GetSourceTypeName(), - StringHelper::Sprintf("%sVertices", auxName.c_str()), vertices.size(), declaration); - } -} - -std::string ZCollisionHeader::GetBodySourceCode() const -{ - std::string declaration = ""; - - declaration += "\n"; - - declaration += StringHelper::Sprintf("\t{ %i, %i, %i },\n", absMinX, absMinY, absMinZ); - declaration += StringHelper::Sprintf("\t{ %i, %i, %i },\n", absMaxX, absMaxY, absMaxZ); - - std::string vtxName; - Globals::Instance->GetSegmentedPtrName(vtxAddress, parent, "Vec3s", vtxName); - - if (numVerts > 0) - declaration += - StringHelper::Sprintf("\tARRAY_COUNT(%s), %s,\n", vtxName.c_str(), vtxName.c_str()); - else - declaration += StringHelper::Sprintf("\t%i, %s,\n", numVerts, vtxName.c_str()); - - std::string polyName; - Globals::Instance->GetSegmentedPtrName(polyAddress, parent, "CollisionPoly", polyName); - - if (numPolygons > 0) - declaration += - StringHelper::Sprintf("\tARRAY_COUNT(%s), %s,\n", polyName.c_str(), polyName.c_str()); - else - declaration += StringHelper::Sprintf("\t%i, %s,\n", numPolygons, polyName.c_str()); - - std::string surfaceName; - Globals::Instance->GetSegmentedPtrName(polyTypeDefAddress, parent, "SurfaceType", surfaceName); - declaration += StringHelper::Sprintf("\t%s,\n", surfaceName.c_str()); - - std::string camName; - Globals::Instance->GetSegmentedPtrName(camDataAddress, parent, "BgCamInfo", camName); - declaration += StringHelper::Sprintf("\t%s,\n", camName.c_str()); - - std::string waterBoxName; - Globals::Instance->GetSegmentedPtrName(waterBoxAddress, parent, "WaterBox", waterBoxName); - - if (numWaterBoxes > 0) - declaration += StringHelper::Sprintf("\tARRAY_COUNT(%s), %s\n", waterBoxName.c_str(), - waterBoxName.c_str()); - else - declaration += StringHelper::Sprintf("\t%i, %s\n", numWaterBoxes, waterBoxName.c_str()); - - return declaration; -} - -std::string ZCollisionHeader::GetDefaultName(const std::string& prefix) const -{ - return StringHelper::Sprintf("%sCol_%06X", prefix.c_str(), rawDataIndex); -} - -std::string ZCollisionHeader::GetSourceTypeName() const -{ - return "CollisionHeader"; -} - -ZResourceType ZCollisionHeader::GetResourceType() const -{ - return ZResourceType::CollisionHeader; -} - -size_t ZCollisionHeader::GetRawDataSize() const -{ - return 44; -} - -CameraDataList::CameraDataList(ZFile* parent, const std::string& prefix, - const std::vector& rawData, offset_t rawDataIndex, - offset_t upperCameraBoundary) -{ - std::string declaration; - - // Parse CameraDataEntries - size_t numElements = (upperCameraBoundary - rawDataIndex) / 8; - assert(numElements < 10000); - - offset_t cameraPosDataSeg = rawDataIndex; - uint32_t numDataTotal; - uint32_t cameraPosDataSegEnd = rawDataIndex; - bool isSharpOcarina = false; - - for (size_t i = 0; i < numElements; i++) - { - CameraDataEntry entry; - - entry.cameraSType = - BitConverter::ToInt16BE(rawData, rawDataIndex + (entries.size() * 8) + 0); - entry.numData = BitConverter::ToInt16BE(rawData, rawDataIndex + (entries.size() * 8) + 2); - entry.cameraPosDataSeg = - BitConverter::ToInt32BE(rawData, rawDataIndex + (entries.size() * 8) + 4); - - if (entry.cameraPosDataSeg != 0 && GETSEGNUM(entry.cameraPosDataSeg) != SEGMENT_SCENE) - { - cameraPosDataSeg = rawDataIndex + (entries.size() * 8); - break; - } - - if (rawDataIndex > GETSEGOFFSET(entry.cameraPosDataSeg)) - { - if (entry.cameraPosDataSeg != 0 && - cameraPosDataSeg > GETSEGOFFSET(entry.cameraPosDataSeg)) - cameraPosDataSeg = GETSEGOFFSET(entry.cameraPosDataSeg); - } - else - { - // Sharp Ocarina will place the cam data after the list as opposed to the original maps - // which have it before. - isSharpOcarina = true; - cameraPosDataSeg = rawDataIndex + (numElements * 0x8); - if (cameraPosDataSegEnd < GETSEGOFFSET(entry.cameraPosDataSeg)) - cameraPosDataSegEnd = GETSEGOFFSET(entry.cameraPosDataSeg); - } - - entries.emplace_back(entry); - } - - // Setting cameraPosDataAddr to rawDataIndex give a pos list length of 0 - uint32_t cameraPosDataOffset = GETSEGOFFSET(cameraPosDataSeg); - for (size_t i = 0; i < entries.size(); i++) - { - char camSegLine[2048]; - - if (entries[i].cameraPosDataSeg != 0) - { - uint32_t index = - (GETSEGOFFSET(entries[i].cameraPosDataSeg) - cameraPosDataOffset) / 0x6; - snprintf(camSegLine, 2048, "&%sCamPosData[%i]", prefix.c_str(), index); - } - else - snprintf(camSegLine, 2048, "NULL"); - - declaration += - StringHelper::Sprintf(" { 0x%04X, %i, %s },", entries[i].cameraSType, - entries[i].numData, camSegLine, rawDataIndex + (i * 8)); - - if (i < entries.size() - 1) - declaration += "\n"; - } - - parent->AddDeclarationArray( - rawDataIndex, DeclarationAlignment::Align4, entries.size() * 8, "BgCamInfo", - StringHelper::Sprintf("%sCamDataList", prefix.c_str(), rawDataIndex), entries.size(), - declaration); - - if (!isSharpOcarina) - numDataTotal = (rawDataIndex - cameraPosDataOffset) / 0x6; - else - numDataTotal = ((cameraPosDataSegEnd - cameraPosDataSeg) + 18) / 0x6; - - if (numDataTotal > 0) - { - declaration.clear(); - cameraPositionData.reserve(numDataTotal); - for (uint32_t i = 0; i < numDataTotal; i++) - { - CameraPositionData data = CameraPositionData(rawData, cameraPosDataOffset + (i * 6)); - - declaration += StringHelper::Sprintf("\t{ %6i, %6i, %6i },", data.x, data.y, data.z); - cameraPositionData.emplace_back(data); - if (i + 1 < numDataTotal) - declaration += "\n"; - } - - uint32_t cameraPosDataIndex = GETSEGOFFSET(cameraPosDataSeg); - uint32_t entrySize = numDataTotal * 0x6; - parent->AddDeclarationArray(cameraPosDataIndex, DeclarationAlignment::Align4, entrySize, - "Vec3s", StringHelper::Sprintf("%sCamPosData", prefix.c_str()), - numDataTotal, declaration); - } -} - -CameraDataList::~CameraDataList() -{ -} - -CameraPositionData::CameraPositionData(const std::vector& rawData, uint32_t rawDataIndex) -{ - x = BitConverter::ToInt16BE(rawData, rawDataIndex + 0); - y = BitConverter::ToInt16BE(rawData, rawDataIndex + 2); - z = BitConverter::ToInt16BE(rawData, rawDataIndex + 4); -} diff --git a/tools/ZAPD/ZAPD/ZCollision.h b/tools/ZAPD/ZAPD/ZCollision.h deleted file mode 100644 index 8c73d2eaa1..0000000000 --- a/tools/ZAPD/ZAPD/ZCollision.h +++ /dev/null @@ -1,75 +0,0 @@ -#pragma once - -#include "ZCollisionPoly.h" -#include "ZFile.h" -#include "ZResource.h" -#include "ZRoom/ZRoom.h" -#include "ZSurfaceType.h" -#include "ZVector.h" -#include "ZWaterbox.h" - -class CameraPositionData -{ -public: - int16_t x, y, z; - - CameraPositionData(const std::vector& rawData, uint32_t rawDataIndex); -}; - -class CameraDataEntry -{ -public: - int16_t cameraSType; - int16_t numData; - offset_t cameraPosDataSeg; -}; - -class CameraDataList -{ -public: - std::vector entries; - std::vector cameraPositionData; - - CameraDataList(ZFile* parent, const std::string& prefix, const std::vector& rawData, - offset_t rawDataIndex, offset_t upperCameraBoundary); - ~CameraDataList(); -}; - -class ZCollisionHeader : public ZResource -{ -public: - int16_t absMinX, absMinY, absMinZ; - int16_t absMaxX, absMaxY, absMaxZ; - uint16_t numVerts; - segptr_t vtxAddress; - uint16_t numPolygons; - segptr_t polyAddress; - segptr_t polyTypeDefAddress; - segptr_t camDataAddress; - - int32_t numWaterBoxes; - segptr_t waterBoxAddress; - - uint32_t vtxSegmentOffset, polySegmentOffset, polyTypeDefSegmentOffset, camDataSegmentOffset, - waterBoxSegmentOffset; - - std::vector vertices; - std::vector polygons; - std::vector polygonTypes; - std::vector waterBoxes; - CameraDataList* camData = nullptr; - - ZCollisionHeader(ZFile* nParent); - ~ZCollisionHeader(); - - void ParseRawData() override; - void DeclareReferences(const std::string& prefix) override; - - std::string GetBodySourceCode() const override; - std::string GetDefaultName(const std::string& prefix) const override; - - std::string GetSourceTypeName() const override; - ZResourceType GetResourceType() const override; - - size_t GetRawDataSize() const override; -}; diff --git a/tools/ZAPD/ZAPD/ZCollisionPoly.cpp b/tools/ZAPD/ZAPD/ZCollisionPoly.cpp deleted file mode 100644 index c4eb2d461d..0000000000 --- a/tools/ZAPD/ZAPD/ZCollisionPoly.cpp +++ /dev/null @@ -1,78 +0,0 @@ -#include "ZCollisionPoly.h" - -#include "Globals.h" -#include "Utils/BitConverter.h" -#include "Utils/StringHelper.h" - -REGISTER_ZFILENODE(CollisionPoly, ZCollisionPoly); - -ZCollisionPoly::ZCollisionPoly(ZFile* nParent) : ZResource(nParent) -{ -} - -ZCollisionPoly::~ZCollisionPoly() -{ -} - -void ZCollisionPoly::ParseRawData() -{ - const auto& rawData = parent->GetRawData(); - type = BitConverter::ToUInt16BE(rawData, rawDataIndex + 0); - - vtxA = BitConverter::ToUInt16BE(rawData, rawDataIndex + 2); - vtxB = BitConverter::ToUInt16BE(rawData, rawDataIndex + 4); - vtxC = BitConverter::ToUInt16BE(rawData, rawDataIndex + 6); - - normX = BitConverter::ToUInt16BE(rawData, rawDataIndex + 8); - normY = BitConverter::ToUInt16BE(rawData, rawDataIndex + 10); - normZ = BitConverter::ToUInt16BE(rawData, rawDataIndex + 12); - - dist = BitConverter::ToUInt16BE(rawData, rawDataIndex + 14); -} - -void ZCollisionPoly::DeclareReferences(const std::string& prefix) -{ - std::string declaration; - std::string auxName = name; - - if (name == "") - auxName = GetDefaultName(prefix); - - parent->AddDeclaration(rawDataIndex, DeclarationAlignment::Align4, GetRawDataSize(), - GetSourceTypeName(), name.c_str(), GetBodySourceCode()); -} - -std::string ZCollisionPoly::GetBodySourceCode() const -{ - std::string declaration; - - declaration += - StringHelper::Sprintf("{0x%04X, 0x%04X, 0x%04X, 0x%04X, 0x%04X, 0x%04X, 0x%04X, 0x%04X}", - type, vtxA, vtxB, vtxC, normX, normY, normZ, dist); - return declaration; -} - -std::string ZCollisionPoly::GetDefaultName(const std::string& prefix) const -{ - return StringHelper::Sprintf("%sCollisionPoly_%06X", prefix.c_str(), rawDataIndex); -} - -ZResourceType ZCollisionPoly::GetResourceType() const -{ - return ZResourceType::CollisionPoly; -} - -size_t ZCollisionPoly::GetRawDataSize() const -{ - return 16; -} - -std::string ZCollisionPoly::GetSourceTypeName() const -{ - return "CollisionPoly"; -} - -bool ZCollisionPoly::DoesSupportArray() const -{ - return true; -} \ No newline at end of file diff --git a/tools/ZAPD/ZAPD/ZCollisionPoly.h b/tools/ZAPD/ZAPD/ZCollisionPoly.h deleted file mode 100644 index 64b98ba1d9..0000000000 --- a/tools/ZAPD/ZAPD/ZCollisionPoly.h +++ /dev/null @@ -1,29 +0,0 @@ -#pragma once - -#include "ZFile.h" -#include "ZResource.h" - -class ZCollisionPoly : public ZResource -{ -public: - uint16_t type; - uint16_t vtxA, vtxB, vtxC; - uint16_t normX, normY, normZ; - uint16_t dist; - - ZCollisionPoly(ZFile* nParent); - ~ZCollisionPoly(); - - void ParseRawData() override; - void DeclareReferences(const std::string& prefix) override; - - std::string GetBodySourceCode() const override; - std::string GetDefaultName(const std::string& prefix) const override; - - std::string GetSourceTypeName() const override; - ZResourceType GetResourceType() const override; - - bool DoesSupportArray() const override; - - size_t GetRawDataSize() const override; -}; \ No newline at end of file diff --git a/tools/ZAPD/ZAPD/ZCutscene.cpp b/tools/ZAPD/ZAPD/ZCutscene.cpp deleted file mode 100644 index 636a7d4c73..0000000000 --- a/tools/ZAPD/ZAPD/ZCutscene.cpp +++ /dev/null @@ -1,396 +0,0 @@ -#include "ZCutscene.h" - -#include - -#include "Globals.h" -#include "Utils/BitConverter.h" -#include "Utils/StringHelper.h" -#include "WarningHandler.h" -#include "ZResource.h" - -REGISTER_ZFILENODE(Cutscene, ZCutscene); - -ZCutscene::ZCutscene(ZFile* nParent) : ZResource(nParent) -{ -} - -ZCutscene::~ZCutscene() -{ - for (CutsceneCommand* cmd : commands) - delete cmd; -} - -std::string ZCutscene::GetBodySourceCode() const -{ - std::string output = ""; - - output += StringHelper::Sprintf(" CS_HEADER(%i, %i),\n", numCommands, endFrame); - - for (size_t i = 0; i < commands.size(); i++) - { - CutsceneCommand* cmd = commands[i]; - output += " " + cmd->GenerateSourceCode(); - } - - output += StringHelper::Sprintf(" CS_END_OF_SCRIPT(),"); - - return output; -} - -size_t ZCutscene::GetRawDataSize() const -{ - size_t size = 0; - - // Beginning - size += 8; - - for (size_t i = 0; i < commands.size(); i++) - { - CutsceneCommand* cmd = commands[i]; - - size += cmd->GetCommandSize(); - } - - // End - if (Globals::Instance->game == ZGame::MM_RETAIL) - { - size += 4; - } - else - { - size += 8; - } - - return size; -} - -void ZCutscene::ParseRawData() -{ - ZResource::ParseRawData(); - - const auto& rawData = parent->GetRawData(); - - numCommands = BitConverter::ToInt32BE(rawData, rawDataIndex + 0); - commands = std::vector(); - - endFrame = BitConverter::ToInt32BE(rawData, rawDataIndex + 4); - offset_t currentPtr = rawDataIndex + 8; - commands.reserve(numCommands); - for (int32_t i = 0; i < numCommands; i++) - { - uint32_t id = BitConverter::ToUInt32BE(rawData, currentPtr); - - if (id == 0xFFFFFFFF) - break; - - if (Globals::Instance->verbosity >= VerbosityLevel::VERBOSITY_DEBUG) - { - printf("Cutscene Command: 0x%X (%i)\n", id, id); - } - - currentPtr += 4; - - CutsceneCommand* cmd = nullptr; - - if (Globals::Instance->game == ZGame::MM_RETAIL) - { - cmd = GetCommandMM(id, currentPtr); - } - else - { - cmd = GetCommandOoT(id, currentPtr); - } - - if (cmd == nullptr) - { - HANDLE_WARNING_RESOURCE( - WarningType::NotImplemented, parent, this, rawDataIndex, - StringHelper::Sprintf("Cutscene command not implemented"), - StringHelper::Sprintf("Command ID: 0x%X\nIndex: %d\ncurrentPtr-rawDataIndex: 0x%X", - id, i, currentPtr - rawDataIndex)); - cmd = new CutsceneMMCommand_NonImplemented(rawData, currentPtr); - } - - assert(cmd != nullptr); - - cmd->commandIndex = i; - cmd->SetCommandID(id); - size_t commmandSize = cmd->GetCommandSize(); - if (Globals::Instance->verbosity >= VerbosityLevel::VERBOSITY_DEBUG) - { - printf("\t Command size: 0x%zX (%zu)\n", commmandSize, commmandSize); - } - currentPtr += commmandSize - 4; - - commands.push_back(cmd); - } -} - -CutsceneCommand* ZCutscene::GetCommandOoT(uint32_t id, offset_t currentPtr) const -{ - CutsceneOoT_CommandType cmdID = static_cast(id); - - const auto& rawData = parent->GetRawData(); - - switch (cmdID) - { - case CutsceneOoT_CommandType::CS_CMD_PLAYER_CUE: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_1_0: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_0_0: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_1_1: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_0_1: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_0_2: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_0_3: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_1_2: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_2_0: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_3_0: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_4_0: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_6_0: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_0_4: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_1_3: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_2_1: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_3_1: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_4_1: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_0_5: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_1_4: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_2_2: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_3_2: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_4_2: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_5_0: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_0_6: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_4_3: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_1_5: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_7_0: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_2_3: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_3_3: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_6_1: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_3_4: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_4_4: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_5_1: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_6_2: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_6_3: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_7_1: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_8_0: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_3_5: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_1_6: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_3_6: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_3_7: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_2_4: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_1_7: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_2_5: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_1_8: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_2_6: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_2_7: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_3_8: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_0_7: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_5_2: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_1_9: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_4_5: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_1_10: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_2_8: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_3_9: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_4_6: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_5_3: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_0_8: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_6_4: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_7_2: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_5_4: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_0_9: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_1_11: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_0_10: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_2_9: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_0_11: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_3_10: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_0_12: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_7_3: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_7_4: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_6_5: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_1_12: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_2_10: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_1_13: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_0_13: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_1_14: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_2_11: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_0_14: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_1_15: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_2_12: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_3_11: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_4_7: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_5_5: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_6_6: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_1_16: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_2_13: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_3_12: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_7_5: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_4_8: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_5_6: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_6_7: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_0_15: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_0_16: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_1_17: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_7_6: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_9_0: - case CutsceneOoT_CommandType::CS_CMD_ACTOR_CUE_0_17: - return new CutsceneOoTCommand_ActorCue(rawData, currentPtr); - - case CutsceneOoT_CommandType::CS_CMD_MISC: - case CutsceneOoT_CommandType::CS_CMD_LIGHT_SETTING: - case CutsceneOoT_CommandType::CS_CMD_START_SEQ: - case CutsceneOoT_CommandType::CS_CMD_STOP_SEQ: - case CutsceneOoT_CommandType::CS_CMD_FADE_OUT_SEQ: - return new CutsceneOoTCommand_GenericCmd(rawData, currentPtr, cmdID); - - case CutsceneOoT_CommandType::CS_CMD_CAM_EYE_SPLINE: - case CutsceneOoT_CommandType::CS_CMD_CAM_AT_SPLINE: - case CutsceneOoT_CommandType::CS_CMD_CAM_EYE_SPLINE_REL_TO_PLAYER: - case CutsceneOoT_CommandType::CS_CMD_CAM_AT_SPLINE_REL_TO_PLAYER: - return new CutsceneOoTCommand_GenericCameraCmd(rawData, currentPtr); - - case CutsceneOoT_CommandType::CS_CMD_RUMBLE_CONTROLLER: - return new CutsceneOoTCommand_Rumble(rawData, currentPtr); - - case CutsceneOoT_CommandType::CS_CMD_TEXT: - return new CutsceneOoTCommand_Text(rawData, currentPtr); - - case CutsceneOoT_CommandType::CS_CMD_TRANSITION: - return new CutsceneOoTCommand_Transition(rawData, currentPtr); - - case CutsceneOoT_CommandType::CS_CMD_TIME: - return new CutsceneCommand_Time(rawData, currentPtr); - - case CutsceneOoT_CommandType::CS_CMD_DESTINATION: - return new CutsceneOoTCommand_Destination(rawData, currentPtr); - - case CutsceneOoT_CommandType::CS_CMD_CAM_EYE: - case CutsceneOoT_CommandType::CS_CMD_CAM_AT: - break; - - default: - std::string errorHeader = - StringHelper::Sprintf("Warning: Invalid cutscene command ID: '0x%04X'", cmdID); - return new CutsceneOoTCommand_GenericCmd(rawData, currentPtr, cmdID); - } - - return nullptr; -} - -CutsceneCommand* ZCutscene::GetCommandMM(uint32_t id, offset_t currentPtr) const -{ - CutsceneMM_CommandType cmdID = static_cast(id); - - const auto& rawData = parent->GetRawData(); - - if (((id >= (uint32_t)CutsceneMM_CommandType::CS_CMD_ACTOR_CUE_100) && - (id <= (uint32_t)CutsceneMM_CommandType::CS_CMD_ACTOR_CUE_149)) || - (id == (uint32_t)CutsceneMM_CommandType::CS_CMD_ACTOR_CUE_201) || - ((id >= (uint32_t)CutsceneMM_CommandType::CS_CMD_ACTOR_CUE_450) && - (id <= (uint32_t)CutsceneMM_CommandType::CS_CMD_ACTOR_CUE_599))) - { - return new CutsceneMMCommand_ActorCue(rawData, currentPtr); - } - - switch (cmdID) - { - case CutsceneMM_CommandType::CS_CMD_MISC: - case CutsceneMM_CommandType::CS_CMD_LIGHT_SETTING: - case CutsceneMM_CommandType::CS_CMD_TRANSITION: - case CutsceneMM_CommandType::CS_CMD_MOTION_BLUR: - case CutsceneMM_CommandType::CS_CMD_GIVE_TATL: - case CutsceneMM_CommandType::CS_CMD_START_SEQ: - case CutsceneMM_CommandType::CS_CMD_SFX_REVERB_INDEX_2: - case CutsceneMM_CommandType::CS_CMD_SFX_REVERB_INDEX_1: - case CutsceneMM_CommandType::CS_CMD_MODIFY_SEQ: - case CutsceneMM_CommandType::CS_CMD_STOP_SEQ: - case CutsceneMM_CommandType::CS_CMD_START_AMBIENCE: - case CutsceneMM_CommandType::CS_CMD_FADE_OUT_AMBIENCE: - case CutsceneMM_CommandType::CS_CMD_DESTINATION: - case CutsceneMM_CommandType::CS_CMD_CHOOSE_CREDITS_SCENES: - - case CutsceneMM_CommandType::CS_CMD_UNK_DATA_FA: - case CutsceneMM_CommandType::CS_CMD_UNK_DATA_FE: - case CutsceneMM_CommandType::CS_CMD_UNK_DATA_FF: - case CutsceneMM_CommandType::CS_CMD_UNK_DATA_100: - case CutsceneMM_CommandType::CS_CMD_UNK_DATA_101: - case CutsceneMM_CommandType::CS_CMD_UNK_DATA_102: - case CutsceneMM_CommandType::CS_CMD_UNK_DATA_103: - case CutsceneMM_CommandType::CS_CMD_UNK_DATA_104: - case CutsceneMM_CommandType::CS_CMD_UNK_DATA_105: - case CutsceneMM_CommandType::CS_CMD_UNK_DATA_108: - case CutsceneMM_CommandType::CS_CMD_UNK_DATA_109: - return new CutsceneMMCommand_GenericCmd(rawData, currentPtr, cmdID); - - case CutsceneMM_CommandType::CS_CMD_TEXT: - return new CutsceneMMCommand_Text(rawData, currentPtr); - - case CutsceneMM_CommandType::CS_CMD_CAMERA_SPLINE: - return new CutsceneMMCommand_Spline(rawData, currentPtr); - - case CutsceneMM_CommandType::CS_CMD_TRANSITION_GENERAL: - return new CutsceneMMCommand_TransitionGeneral(rawData, currentPtr); - - case CutsceneMM_CommandType::CS_CMD_FADE_OUT_SEQ: - return new CutsceneMMCommand_FadeOutSeq(rawData, currentPtr); - - case CutsceneMM_CommandType::CS_CMD_TIME: - return new CutsceneCommand_Time(rawData, currentPtr); - - case CutsceneMM_CommandType::CS_CMD_PLAYER_CUE: - return new CutsceneMMCommand_ActorCue(rawData, currentPtr); - - case CutsceneMM_CommandType::CS_CMD_RUMBLE: - return new CutsceneMMCommand_Rumble(rawData, currentPtr); - - default: - std::string errorHeader = - StringHelper::Sprintf("Warning: Invalid cutscene command ID: '0x%04X'", cmdID); - return new CutsceneMMCommand_GenericCmd(rawData, currentPtr, cmdID); - } - - return nullptr; -} - -Declaration* ZCutscene::DeclareVar(const std::string& prefix, const std::string& bodyStr) -{ - std::string auxName = name; - - if (auxName == "") - auxName = GetDefaultName(prefix); - - Declaration* decl = - parent->AddDeclarationArray(rawDataIndex, GetDeclarationAlignment(), GetRawDataSize(), - GetSourceTypeName(), auxName, 0, bodyStr); - decl->staticConf = staticConf; - return decl; -} - -std::string ZCutscene::GetSourceTypeName() const -{ - return "CutsceneData"; -} - -ZResourceType ZCutscene::GetResourceType() const -{ - return ZResourceType::Cutscene; -} - -std::string ZCutscene::GetCsEncodedFloat(float f, CsFloatType type, bool useSciNotation) -{ - uint32_t i; - std::memcpy(&i, &f, sizeof(i)); - - switch (type) - { - default: - // This default case will NEVER be reached, but GCC still gives a warning. - case CsFloatType::HexOnly: - return StringHelper::Sprintf("0x%08X", i); - case CsFloatType::FloatOnly: - return StringHelper::Sprintf(useSciNotation ? "%.8ef" : "%ff", f); - case CsFloatType::HexAndFloat: - return StringHelper::Sprintf(useSciNotation ? "CS_FLOAT(0x%08X, %.8ef)" : "CS_FLOAT(0x%08X, %ff)", i, f); - case CsFloatType::HexAndCommentedFloatLeft: - return StringHelper::Sprintf(useSciNotation ? "/* %.8ef */ 0x%08X" : "/* %ff */ 0x%08X", f, i); - case CsFloatType::HexAndCommentedFloatRight: - return StringHelper::Sprintf(useSciNotation ? "0x%08X /* %.8ef */" : "0x%08X /* %ff */", i, f); - } -} diff --git a/tools/ZAPD/ZAPD/ZCutscene.h b/tools/ZAPD/ZAPD/ZCutscene.h deleted file mode 100644 index 5dbf475c33..0000000000 --- a/tools/ZAPD/ZAPD/ZCutscene.h +++ /dev/null @@ -1,41 +0,0 @@ -#pragma once - -#include -#include -#include -#include "tinyxml2.h" - -#include "OtherStructs/CutsceneOoT_Commands.h" -#include "OtherStructs/CutsceneMM_Commands.h" -#include "ZFile.h" -#include "ZResource.h" - -enum class CsFloatType; - -class ZCutscene : public ZResource -{ -public: - ZCutscene(ZFile* nParent); - ~ZCutscene(); - - void ParseRawData() override; - - Declaration* DeclareVar(const std::string& prefix, const std::string& bodyStr) override; - - std::string GetBodySourceCode() const override; - - size_t GetRawDataSize() const override; - - std::string GetSourceTypeName() const override; - ZResourceType GetResourceType() const override; - - static std::string GetCsEncodedFloat(float f, CsFloatType type, bool useSciNotation); - - int32_t numCommands; - int32_t endFrame; - std::vector commands; - -protected: - CutsceneCommand* GetCommandOoT(uint32_t id, offset_t currentPtr) const; - CutsceneCommand* GetCommandMM(uint32_t id, offset_t currentPtr) const; -}; diff --git a/tools/ZAPD/ZAPD/ZDisplayList.cpp b/tools/ZAPD/ZAPD/ZDisplayList.cpp deleted file mode 100644 index 98c4d0e4a4..0000000000 --- a/tools/ZAPD/ZAPD/ZDisplayList.cpp +++ /dev/null @@ -1,2178 +0,0 @@ -#include "ZDisplayList.h" - -#include -#include -#include -#include -#include - -#include "Globals.h" -#include "OutputFormatter.h" -#include "Utils/BitConverter.h" -#include "Utils/File.h" -#include "Utils/Path.h" -#include "Utils/StringHelper.h" -#include "WarningHandler.h" -#include "gfxd.h" - -REGISTER_ZFILENODE(DList, ZDisplayList); - -ZDisplayList::ZDisplayList(ZFile* nParent) : ZResource(nParent) -{ - lastTexWidth = 0; - lastTexHeight = 0; - lastTexAddr = 0; - lastTexFmt = F3DZEXTexFormats::G_IM_FMT_RGBA; - lastTexSiz = F3DZEXTexSizes::G_IM_SIZ_16b; - lastTexSizTest = F3DZEXTexSizes::G_IM_SIZ_16b; - lastTexLoaded = false; - lastTexIsPalette = false; - dListType = Globals::Instance->game == ZGame::OOT_SW97 ? DListType::F3DEX : DListType::F3DZEX; - RegisterOptionalAttribute("Ucode"); -} - -ZDisplayList::~ZDisplayList() -{ - for (auto o : otherDLists) - { - delete o; - } -} - -// EXTRACT MODE -void ZDisplayList::ExtractWithXML(tinyxml2::XMLElement* reader, uint32_t nRawDataIndex) -{ - rawDataIndex = nRawDataIndex; - ParseXML(reader); - // TODO add error handling here - bool ucodeSet = registeredAttributes.at("Ucode").wasSet; - std::string ucodeValue = registeredAttributes.at("Ucode").value; - if ((Globals::Instance->game == ZGame::OOT_SW97) || (ucodeValue == "f3dex")) - { - dListType = DListType::F3DEX; - } - else if (!ucodeSet || ucodeValue == "f3dex2") - { - dListType = DListType::F3DZEX; - } - else - { - HANDLE_ERROR_RESOURCE( - WarningType::InvalidAttributeValue, parent, this, rawDataIndex, - StringHelper::Sprintf("Invalid ucode type in node: %s\n", reader->Name()), ""); - } - - // Don't parse raw data of external files - if (parent->GetMode() != ZFileMode::ExternalFile) - { - int32_t rawDataSize = - ZDisplayList::GetDListLength(parent->GetRawData(), rawDataIndex, dListType); - numInstructions = rawDataSize / 8; - ParseRawData(); - } - - Declaration* decl = DeclareVar("", ""); - decl->declaredInXml = true; -} - -void ZDisplayList::ExtractFromBinary(uint32_t nRawDataIndex, int32_t rawDataSize) -{ - rawDataIndex = nRawDataIndex; - name = GetDefaultName(parent->GetName()); - numInstructions = rawDataSize / 8; - - // Don't parse raw data of external files - if (parent->GetMode() == ZFileMode::ExternalFile) - return; - - ParseRawData(); -} - -void ZDisplayList::ParseRawData() -{ - const auto& rawData = parent->GetRawData(); - instructions.reserve(numInstructions); - uint32_t ptr = rawDataIndex; - - instructions.reserve(numInstructions); - for (size_t i = 0; i < numInstructions; i++) - { - instructions.push_back(BitConverter::ToUInt64BE(rawData, ptr)); - ptr += 8; - } -} - -Declaration* ZDisplayList::DeclareVar([[maybe_unused]] const std::string& prefix, - const std::string& bodyStr) -{ - Declaration* decl = - parent->AddDeclarationArray(rawDataIndex, GetDeclarationAlignment(), GetRawDataSize(), - GetSourceTypeName(), name, numInstructions, bodyStr); - decl->isExternal = true; - decl->staticConf = staticConf; - return decl; -} - -std::string ZDisplayList::GetDefaultName(const std::string& prefix) const -{ - return StringHelper::Sprintf("%sDL_%06X", prefix.c_str(), rawDataIndex); -} - -void ZDisplayList::ParseF3DZEX(F3DZEXOpcode opcode, uint64_t data, int32_t i, - const std::string& prefix, char* line) -{ - switch (opcode) - { - case F3DZEXOpcode::G_NOOP: - sprintf(line, "gsDPNoOpTag(0x%08" PRIX64 "),", data & 0xFFFFFFFF); - break; - case F3DZEXOpcode::G_DL: - Opcode_G_DL(data, prefix, line); - break; - case F3DZEXOpcode::G_MODIFYVTX: - Opcode_G_MODIFYVTX(data, line); - break; - case F3DZEXOpcode::G_CULLDL: - Opcode_G_CULLDL(data, line); - break; - case F3DZEXOpcode::G_TRI1: - Opcode_G_TRI1(data, line); - break; - case F3DZEXOpcode::G_TRI2: - Opcode_G_TRI2(data, line); - break; - case F3DZEXOpcode::G_QUAD: - { - int32_t aa = ((data & 0x00FF000000000000ULL) >> 48) / 2; - int32_t bb = ((data & 0x0000FF0000000000ULL) >> 40) / 2; - int32_t cc = ((data & 0x000000FF00000000ULL) >> 32) / 2; - int32_t dd = ((data & 0x000000000000FFULL)) / 2; - sprintf(line, "gsSP1Quadrangle(%i, %i, %i, %i, 0),", aa, bb, cc, dd); - } - break; - case F3DZEXOpcode::G_VTX: - Opcode_G_VTX(data, line); - break; - case F3DZEXOpcode::G_SETTIMG: // HOTSPOT - Opcode_G_SETTIMG(data, prefix, line); - break; - case F3DZEXOpcode::G_GEOMETRYMODE: - { - int32_t cccccc = (data & 0x00FFFFFF00000000) >> 32; - int32_t ssssssss = (data & 0xFFFFFFFF); - std::string geoModeStr = "G_TEXTURE_ENABLE"; - - int32_t geoModeParam = ~cccccc; - - if (ssssssss != 0) - geoModeParam = ssssssss; - - if (geoModeParam & 0x00000001) - geoModeStr += " | G_ZBUFFER"; - - if (geoModeParam & 0x00000004) - geoModeStr += " | G_SHADE"; - - if (geoModeParam & 0x00000200) - geoModeStr += " | G_CULL_FRONT"; - - if (geoModeParam & 0x00000400) - geoModeStr += " | G_CULL_BACK"; - - if (geoModeParam & 0x00010000) - geoModeStr += " | G_FOG"; - - if (geoModeParam & 0x00020000) - geoModeStr += " | G_LIGHTING"; - - if (geoModeParam & 0x00040000) - geoModeStr += " | G_TEXTURE_GEN"; - - if (geoModeParam & 0x00080000) - geoModeStr += " | G_TEXTURE_GEN_LINEAR"; - - if (geoModeParam & 0x00200000) - geoModeStr += " | G_SHADING_SMOOTH"; - - if (geoModeParam & 0x00800000) - geoModeStr += " | G_CLIPPING"; - - if (ssssssss != 0) - { - if ((~cccccc & 0xFF000000) != 0) - sprintf(line, "gsSPSetGeometryMode(%s),", geoModeStr.c_str()); - else - sprintf(line, "gsSPLoadGeometryMode(%s),", geoModeStr.c_str()); - } - else - sprintf(line, "gsSPClearGeometryMode(%s),", geoModeStr.c_str()); - } - break; - case F3DZEXOpcode::G_SETPRIMCOLOR: - Opcode_G_SETPRIMCOLOR(data, line); - break; - case F3DZEXOpcode::G_SETOTHERMODE_L: - Opcode_G_SETOTHERMODE_L(data, line); - break; - case F3DZEXOpcode::G_SETOTHERMODE_H: - Opcode_G_SETOTHERMODE_H(data, line); - break; - case F3DZEXOpcode::G_SETTILE: - Opcode_G_SETTILE(data, line); - break; - case F3DZEXOpcode::G_SETTILESIZE: - Opcode_G_SETTILESIZE(data, prefix, line); - break; - case F3DZEXOpcode::G_LOADBLOCK: - Opcode_G_LOADBLOCK(data, line); - break; - case F3DZEXOpcode::G_TEXTURE: - Opcode_G_TEXTURE(data, line); - break; - case F3DZEXOpcode::G_RDPSETOTHERMODE: - { - int32_t hhhhhh = (data & 0x00FFFFFF00000000) >> 32; - int32_t llllllll = (data & 0x00000000FFFFFFFF); - - sprintf(line, "gsDPSetOtherMode(%i, %i),", hhhhhh, llllllll); - } - break; - case F3DZEXOpcode::G_POPMTX: - { - sprintf(line, "gsSPPopMatrix(%" PRIi64 "),", data); - } - break; - case F3DZEXOpcode::G_LOADTLUT: - Opcode_G_LOADTLUT(data, prefix, line); - break; - case F3DZEXOpcode::G_SETENVCOLOR: - { - uint8_t r = (uint8_t)((data & 0xFF000000) >> 24); - uint8_t g = (uint8_t)((data & 0x00FF0000) >> 16); - uint8_t b = (uint8_t)((data & 0xFF00FF00) >> 8); - uint8_t a = (uint8_t)((data & 0x000000FF) >> 0); - - sprintf(line, "gsDPSetEnvColor(%i, %i, %i, %i),", r, g, b, a); - } - break; - case F3DZEXOpcode::G_SETCOMBINE: - { - Opcode_G_SETCOMBINE(data, line); - } - break; - case F3DZEXOpcode::G_RDPLOADSYNC: - sprintf(line, "gsDPLoadSync(),"); - break; - case F3DZEXOpcode::G_RDPPIPESYNC: - sprintf(line, "gsDPPipeSync(),"); - break; - case F3DZEXOpcode::G_RDPTILESYNC: - sprintf(line, "gsDPTileSync(),"); - break; - case F3DZEXOpcode::G_RDPFULLSYNC: - sprintf(line, "gsDPFullSync(),"); - break; - case F3DZEXOpcode::G_ENDDL: - Opcode_G_ENDDL(prefix, line); - break; - case F3DZEXOpcode::G_RDPHALF_1: - { - uint64_t data2 = instructions[i + 1]; - uint32_t h = (data & 0xFFFFFFFF); - F3DZEXOpcode opcode2 = (F3DZEXOpcode)(instructions[i + 1] >> 56); - - if (opcode2 == F3DZEXOpcode::G_BRANCH_Z) - { - uint32_t a = (data2 & 0x00FFF00000000000) >> 44; - uint32_t b = (data2 & 0x00000FFF00000000) >> 32; - uint32_t z = (data2 & 0x00000000FFFFFFFF) >> 0; - - // sprintf(line, "gsDPWord(%i, 0),", h); - sprintf(line, "gsSPBranchLessZraw(%sDlist0x%06X, 0x%02X, 0x%02X),", prefix.c_str(), - h & 0x00FFFFFF, (a / 5) | (b / 2), z); - - ZDisplayList* nList = new ZDisplayList(parent); - nList->ExtractFromBinary( - h & 0x00FFFFFF, GetDListLength(parent->GetRawData(), h & 0x00FFFFFF, dListType)); - nList->SetName(nList->GetDefaultName(prefix)); - otherDLists.push_back(nList); - - i++; - } - } - break; - case F3DZEXOpcode::G_MTX: - Opcode_G_MTX(data, line); - break; - default: - sprintf(line, "// Opcode 0x%02X unimplemented!", (uint32_t)opcode); - break; - } -} - -void ZDisplayList::ParseF3DEX(F3DEXOpcode opcode, uint64_t data, const std::string& prefix, - char* line) -{ - switch (opcode) - { - case F3DEXOpcode::G_NOOP: - sprintf(line, "gsDPNoOpTag(0x%08" PRIX64 "),", data & 0xFFFFFFFF); - break; - case F3DEXOpcode::G_VTX: - Opcode_G_VTX(data, line); - break; - case F3DEXOpcode::G_DL: - Opcode_G_DL(data, prefix, line); - break; - case F3DEXOpcode::G_CULLDL: - Opcode_G_CULLDL(data, line); - break; - case F3DEXOpcode::G_MODIFYVTX: - Opcode_G_MODIFYVTX(data, line); - break; - case F3DEXOpcode::G_MTX: - Opcode_G_MTX(data, line); - break; - case F3DEXOpcode::G_TRI1: - Opcode_G_TRI1(data, line); - break; - case F3DEXOpcode::G_TRI2: - Opcode_G_TRI2(data, line); - break; - case F3DEXOpcode::G_ENDDL: - Opcode_G_ENDDL(prefix, line); - break; - case F3DEXOpcode::G_RDPLOADSYNC: - sprintf(line, "gsDPLoadSync(),"); - break; - case F3DEXOpcode::G_RDPPIPESYNC: - sprintf(line, "gsDPPipeSync(),"); - break; - case F3DEXOpcode::G_RDPTILESYNC: - sprintf(line, "gsDPTileSync(),"); - break; - case F3DEXOpcode::G_RDPFULLSYNC: - sprintf(line, "gsDPFullSync(),"); - break; - case F3DEXOpcode::G_TEXTURE: - Opcode_G_TEXTURE(data, line); - break; - case F3DEXOpcode::G_SETTIMG: - Opcode_G_SETTIMG(data, prefix, line); - break; - case F3DEXOpcode::G_SETTILE: - Opcode_G_SETTILE(data, line); - break; - case F3DEXOpcode::G_SETTILESIZE: - Opcode_G_SETTILESIZE(data, prefix, line); - break; - case F3DEXOpcode::G_LOADBLOCK: - Opcode_G_LOADBLOCK(data, line); - break; - case F3DEXOpcode::G_SETCOMBINE: - Opcode_G_SETCOMBINE(data, line); - break; - case F3DEXOpcode::G_SETPRIMCOLOR: - Opcode_G_SETPRIMCOLOR(data, line); - break; - case F3DEXOpcode::G_SETOTHERMODE_L: - Opcode_G_SETOTHERMODE_L(data, line); - break; - case F3DEXOpcode::G_SETOTHERMODE_H: - Opcode_G_SETOTHERMODE_H(data, line); - break; - case F3DEXOpcode::G_LOADTLUT: - Opcode_G_LOADTLUT(data, prefix, line); - break; - case F3DEXOpcode::G_CLEARGEOMETRYMODE: - case F3DEXOpcode::G_SETGEOMETRYMODE: - { - int32_t cccccc = (data & 0x00FFFFFF00000000) >> 32; - int32_t ssssssss = (data & 0xFFFFFFFF); - std::string geoModeStr = "G_TEXTURE_ENABLE"; - - int32_t geoModeParam = ~cccccc; - - if (ssssssss != 0) - geoModeParam = ssssssss; - - if (geoModeParam & 0x00000002) - geoModeStr += " | G_TEXTURE_ENABLE"; - - if (geoModeParam & 0x00000200) - geoModeStr += " | G_SHADING_SMOOTH"; - - if (geoModeParam & 0x00001000) - geoModeStr += " | G_CULL_FRONT"; - - if (geoModeParam & 0x00002000) - geoModeStr += " | G_CULL_BACK"; - - if (geoModeParam & 0x00000001) - geoModeStr += " | G_ZBUFFER"; - - if (geoModeParam & 0x00000004) - geoModeStr += " | G_SHADE"; - - if (geoModeParam & 0x00010000) - geoModeStr += " | G_FOG"; - - if (geoModeParam & 0x00020000) - geoModeStr += " | G_LIGHTING"; - - if (geoModeParam & 0x00040000) - geoModeStr += " | G_TEXTURE_GEN"; - - if (geoModeParam & 0x00080000) - geoModeStr += " | G_TEXTURE_GEN_LINEAR"; - - if (geoModeParam & 0x00800000) - geoModeStr += " | G_CLIPPING"; - - if (opcode == F3DEXOpcode::G_SETGEOMETRYMODE) - sprintf(line, "gsSPSetGeometryMode(%s),", geoModeStr.c_str()); - else - sprintf(line, "gsSPClearGeometryMode(%s),", geoModeStr.c_str()); - } - break; - default: - sprintf(line, "// Opcode 0x%02X unimplemented!", (uint32_t)opcode); - break; - } -} - -int32_t ZDisplayList::GetDListLength(const std::vector& rawData, uint32_t rawDataIndex, - DListType dListType) -{ - uint8_t endDLOpcode; - uint8_t branchListOpcode; - - if (dListType == DListType::F3DZEX) - { - endDLOpcode = static_cast(F3DZEXOpcode::G_ENDDL); - branchListOpcode = static_cast(F3DZEXOpcode::G_DL); - } - else - { - endDLOpcode = static_cast(F3DEXOpcode::G_ENDDL); - branchListOpcode = static_cast(F3DEXOpcode::G_DL); - } - - uint32_t ptr = rawDataIndex; - size_t rawDataSize = rawData.size(); - while (true) - { - if (ptr >= rawDataSize) - { - std::string errorHeader = - StringHelper::Sprintf("reached end of file when trying to find the end of the " - "DisplayList starting at offset 0x%X", - rawDataIndex); - std::string errorBody = StringHelper::Sprintf("Raw data size: 0x%zX.", rawDataSize); - HANDLE_ERROR_PROCESS(WarningType::Always, errorHeader, errorBody); - } - - uint8_t opcode = rawData.at(ptr); - bool dlNoPush = rawData.at(ptr + 1) == 1; - ptr += 8; - - if (opcode == endDLOpcode || (opcode == branchListOpcode && dlNoPush)) - { - return ptr - rawDataIndex; - } - } -} - -bool ZDisplayList::SequenceCheck(std::vector sequence, int32_t startIndex) -{ - bool success = true; - - for (size_t j = 0; j < sequence.size(); j++) - { - F3DZEXOpcode opcode = (F3DZEXOpcode)(instructions[startIndex + j] >> 56); - - if (sequence[j] != opcode) - { - success = false; - break; - } - } - - if (success) - return true; - - return false; -} - -int32_t ZDisplayList::OptimizationChecks(int32_t startIndex, std::string& output, - const std::string& prefix) -{ - int32_t result = -1; - - result = OptimizationCheck_LoadTextureBlock(startIndex, output, prefix); - - if (result != -1) - return result; - - return -1; -} - -int32_t ZDisplayList::OptimizationCheck_LoadTextureBlock(int32_t startIndex, std::string& output, - [[maybe_unused]] const std::string& prefix) -{ - std::vector sequence = {F3DZEXOpcode::G_SETTIMG, F3DZEXOpcode::G_SETTILE, - F3DZEXOpcode::G_RDPLOADSYNC, F3DZEXOpcode::G_LOADBLOCK, - F3DZEXOpcode::G_RDPPIPESYNC, F3DZEXOpcode::G_SETTILE, - F3DZEXOpcode::G_SETTILESIZE}; - - bool seqRes = SequenceCheck(sequence, startIndex); - - if (seqRes) - { - // gsDPLoadTextureBlock(texAddr, fmt, siz, width, height, pal, cms, cmt, masks, maskt, - // shifts, shiftt) gsDPLoadMultiBlock(texAddr, tmem, rtile, fmt, siz, width, height, pal, - // cms, cmt, masks, maskt, shifts, shiftt) gsDPLoadTextureBlock_4b(texAddr, fmt, width, - // height, pal, cms, cmt, masks, maskt, shifts, shiftt) gsDPLoadMultiBlock_4b(texAddr, tmem, - // rtile, fmt, width, height, pal, cms, cmt, masks, maskt, shifts, shiftt) - - uint32_t texAddr, tmem, rtile, fmt, siz, sizB, width, height, width2, height2, pal, cms, - cmt, masks, maskt, shifts, shiftt; - std::string texStr; - - // gsDPSetTextureImage - { - uint64_t data = instructions[startIndex + 0]; - - int32_t __ = (data & 0x00FF000000000000) >> 48; - // int32_t www = (data & 0x00000FFF00000000) >> 32; - - fmt = (__ & 0xE0) >> 5; - siz = (__ & 0x18) >> 3; - texAddr = Seg2Filespace(data, parent->baseAddress); - uint32_t segmentNumber = GETSEGNUM(data); - - lastTexSeg = segmentNumber; - - Globals::Instance->GetSegmentedPtrName(data & 0xFFFFFFFF, parent, "", texStr); - } - - // gsDPSetTile - { - uint64_t data = instructions[startIndex + 1]; - - tmem = - (data & 0b0000000000000000111111111111111100000000000000000000000000000000) >> 32; - - cmt = (data & 0b0000000000000000000000000000000000000000000011000000000000000000) >> 18; - maskt = - (data & 0b0000000000000000000000000000000000000000000000111100000000000000) >> 14; - shiftt = - (data & 0b0000000000000000000000000000000000000000000000000011110000000000) >> 10; - cms = (data & 0b0000000000000000000000000000000000000000000000000000001100000000) >> 8; - masks = - (data & 0b0000000000000000000000000000000000000000000000000000000011110000) >> 4; - shifts = (data & 0b0000000000000000000000000000000000000000000000000000000000001111); - - // sprintf(line, "gsDPSetTile(%s, %s, %i, %i, %i, %i, %i, %i, %i, %i, %i, %i),", - // fmtTbl[fff].c_str(), sizTbl[ii].c_str(), nnnnnnnnn, mmmmmmmmm, ttt, pppp, cc, aaaa, - // ssss, dd, bbbb, uuuu); - } - - // gsDPLoadSync - - // gsDPLoadBlock - - // gsDPPipeSync - - // gsDPSetTile - { - uint64_t data = instructions[startIndex + 5]; - int32_t __ = (data & 0x00FF000000000000) >> 48; - pal = (data & 0b0000000000000000000000000000000000000000111100000000000000000000) >> 20; - // siz = (__ & 0x18) >> 3; - rtile = - (data & 0b0000000000000000000000000000000011111111000000000000000000000000) >> 24; - sizB = (__ & 0x18) >> 3; - } - - // gsDPSetTileSize - { - uint64_t data = instructions[startIndex + 6]; - int32_t uuu = (data & 0x0000000000FFF000) >> 12; - int32_t vvv = (data & 0x0000000000000FFF); - - int32_t shiftAmtW = 2; - int32_t shiftAmtH = 2; - - if (sizB == (int32_t)F3DZEXTexSizes::G_IM_SIZ_8b && - fmt == (int32_t)F3DZEXTexFormats::G_IM_FMT_IA) - shiftAmtW = 3; - - if (sizB == (int32_t)F3DZEXTexSizes::G_IM_SIZ_4b) - shiftAmtW = 3; - - if (sizB == (int32_t)F3DZEXTexSizes::G_IM_SIZ_4b && - fmt == (int32_t)F3DZEXTexFormats::G_IM_FMT_IA) - shiftAmtH = 3; - - width = (uuu >> shiftAmtW) + 1; - height = (vvv >> shiftAmtH) + 1; - - width2 = (uuu >> 2) + 1; - height2 = (vvv >> 2) + 1; - } - - const char* fmtTbl[] = {"G_IM_FMT_RGBA", "G_IM_FMT_YUV", "G_IM_FMT_CI", "G_IM_FMT_IA", - "G_IM_FMT_I"}; - const char* sizTbl[] = {"G_IM_SIZ_4b", "G_IM_SIZ_8b", "G_IM_SIZ_16b", "G_IM_SIZ_32b"}; - - // output += StringHelper::Sprintf("gsDPLoadTextureBlock(%s, %s, %s, %i, %i, %i, %i, %i, %i, - // %i, %i, %i),", texStr.c_str(), fmtTbl[fmt], sizTbl[siz].c_str(), width, height, - // pal, cms, cmt, masks, maskt, shifts, shiftt); - - if (siz == 2 && sizB == 0) - { - if (tmem != 0) - output += StringHelper::Sprintf( - "gsDPLoadMultiBlock_4b(%s, %i, %i, %s, %i, %i, %i, %i, %i, %i, %i, %i, %i),", - texStr.c_str(), tmem, rtile, fmtTbl[fmt], width2, height2, pal, cms, cmt, masks, - maskt, shifts, shiftt); - else - output += StringHelper::Sprintf( - "gsDPLoadTextureBlock_4b(%s, %s, %i, %i, %i, %i, %i, %i, %i, %i, %i),", - texStr.c_str(), fmtTbl[fmt], width2, height2, pal, cms, cmt, masks, maskt, - shifts, shiftt); - } - else if (siz == 2 && sizB != 0) - { - if (tmem != 0) - output += StringHelper::Sprintf( - "gsDPLoadMultiBlock(%s, %i, %i, %s, %s, %i, %i, %i, %i, %i, %i, %i, %i, %i),", - texStr.c_str(), tmem, rtile, fmtTbl[fmt], sizTbl[sizB], width2, height2, pal, - cms, cmt, masks, maskt, shifts, shiftt); - else - output += StringHelper::Sprintf( - "gsDPLoadTextureBlock(%s, %s, %s, %i, %i, %i, %i, %i, %i, %i, %i, %i),", - texStr.c_str(), fmtTbl[fmt], sizTbl[sizB], width2, height2, pal, cms, cmt, - masks, maskt, shifts, shiftt); - } - else - { - if (siz != sizB) - { - lastTexAddr = texAddr; - lastTexFmt = (F3DZEXTexFormats)fmt; - lastTexWidth = width; - lastTexHeight = height; - lastTexSiz = (F3DZEXTexSizes)siz; - lastTexLoaded = true; - - TextureGenCheck(); - - return -1; - } - - output += StringHelper::Sprintf( - "gsDPLoadMultiBlock(%s, %i, %i, %s, %s, %i, %i, %i, %i, %i, %i, %i, %i, %i),", - texStr.c_str(), tmem, rtile, fmtTbl[fmt], sizTbl[siz], width, height, pal, cms, cmt, - masks, maskt, shifts, shiftt); - } - - lastTexAddr = texAddr; - lastTexFmt = (F3DZEXTexFormats)fmt; - lastTexWidth = width; - lastTexHeight = height; - lastTexSiz = (F3DZEXTexSizes)siz; - lastTexLoaded = true; - - TextureGenCheck(); - - return (int32_t)sequence.size(); - } - - return -1; -} - -void ZDisplayList::Opcode_G_DL(uint64_t data, const std::string& prefix, char* line) -{ - int32_t pp = (data & 0x00FF000000000000) >> 56; - int32_t segNum = GETSEGNUM(data); - - Declaration* dListDecl = nullptr; - - if (parent != nullptr) - dListDecl = parent->GetDeclaration(GETSEGOFFSET(data)); - - if (pp != 0) - { - if (!Globals::Instance->HasSegment(segNum)) - sprintf(line, "gsSPBranchList(0x%08" PRIX64 "),", data & 0xFFFFFFFF); - else if (dListDecl != nullptr) - sprintf(line, "gsSPBranchList(%s),", dListDecl->declName.c_str()); - else - sprintf(line, "gsSPBranchList(%sDlist0x%06" PRIX64 "),", prefix.c_str(), - GETSEGOFFSET(data)); - } - else - { - if (!Globals::Instance->HasSegment(segNum)) - sprintf(line, "gsSPDisplayList(0x%08" PRIX64 "),", data & 0xFFFFFFFF); - else if (dListDecl != nullptr) - sprintf(line, "gsSPDisplayList(%s),", dListDecl->declName.c_str()); - else - sprintf(line, "gsSPDisplayList(%sDlist0x%06" PRIX64 "),", prefix.c_str(), - GETSEGOFFSET(data)); - } - - // if (segNum == 8 || segNum == 9 || segNum == 10 || segNum == 11 || segNum == 12 || segNum == - // 13) // Used for runtime-generated display lists - if (!Globals::Instance->HasSegment(segNum)) - { - if (pp != 0) - sprintf(line, "gsSPBranchList(0x%08" PRIX64 "),", data & 0xFFFFFFFF); - else - sprintf(line, "gsSPDisplayList(0x%08" PRIX64 "),", data & 0xFFFFFFFF); - } - else - { - ZDisplayList* nList = new ZDisplayList(parent); - nList->ExtractFromBinary(GETSEGOFFSET(data), GetDListLength(parent->GetRawData(), - GETSEGOFFSET(data), dListType)); - nList->SetName(nList->GetDefaultName(prefix)); - - otherDLists.push_back(nList); - } -} - -void ZDisplayList::Opcode_G_MODIFYVTX(uint64_t data, char* line) -{ - int32_t ww = (data & 0x00FF000000000000ULL) >> 48; - int32_t nnnn = (data & 0x0000FFFF00000000ULL) >> 32; - int32_t vvvvvvvv = (data & 0x00000000FFFFFFFFULL); - - sprintf(line, "gsSPModifyVertex(%i, %i, %i),", nnnn / 2, ww, vvvvvvvv); -} - -void ZDisplayList::Opcode_G_CULLDL(uint64_t data, char* line) -{ - int32_t vvvv = (data & 0xFFFF00000000) >> 32; - int32_t wwww = (data & 0x0000FFFF); - - sprintf(line, "gsSPCullDisplayList(%i, %i),", vvvv / 2, wwww / 2); -} - -void ZDisplayList::Opcode_G_TRI1(uint64_t data, char* line) -{ - if (dListType == DListType::F3DZEX) - { - int32_t aa = ((data & 0x00FF000000000000ULL) >> 48) / 2; - int32_t bb = ((data & 0x0000FF0000000000ULL) >> 40) / 2; - int32_t cc = ((data & 0x000000FF00000000ULL) >> 32) / 2; - sprintf(line, "gsSP1Triangle(%i, %i, %i, 0),", aa, bb, cc); - } - else - { - int32_t aa = ((data & 0x0000000000FF0000ULL) >> 16) / 2; - int32_t bb = ((data & 0x000000000000FF00ULL) >> 8) / 2; - int32_t cc = ((data & 0x00000000000000FFULL) >> 0) / 2; - sprintf(line, "gsSP1Triangle(%i, %i, %i, 0),", aa, bb, cc); - } -} - -void ZDisplayList::Opcode_G_TRI2(uint64_t data, char* line) -{ - int32_t aa = ((data & 0x00FF000000000000ULL) >> 48) / 2; - int32_t bb = ((data & 0x0000FF0000000000ULL) >> 40) / 2; - int32_t cc = ((data & 0x000000FF00000000ULL) >> 32) / 2; - int32_t dd = ((data & 0x00000000FF0000ULL) >> 16) / 2; - int32_t ee = ((data & 0x0000000000FF00ULL) >> 8) / 2; - int32_t ff = ((data & 0x000000000000FFULL) >> 0) / 2; - sprintf(line, "gsSP2Triangles(%i, %i, %i, 0, %i, %i, %i, 0),", aa, bb, cc, dd, ee, ff); -} - -void ZDisplayList::Opcode_G_MTX(uint64_t data, char* line) -{ - uint32_t pp = 0; - uint32_t mm = (data & 0x00000000FFFFFFFF); - bool push = false; - bool load = false; - bool projection = false; - - if (dListType == DListType::F3DEX) - pp = (data & 0x00FF000000000000) >> 48; - else - pp = (data & 0x000000FF00000000) >> 32; - - std::string matrixRef; - - if (Globals::Instance->cfg.symbolMap.find(mm) != Globals::Instance->cfg.symbolMap.end()) - matrixRef = StringHelper::Sprintf("&%s", Globals::Instance->cfg.symbolMap[mm].c_str()); - else - matrixRef = StringHelper::Sprintf("0x%08X", mm); - - pp ^= 0x01; - - if (pp & 0x01) - push = true; - - if (pp & 0x02) - load = true; - - if (pp & 0x04) - projection = true; - - sprintf(line, "gsSPMatrix(%s, %s | %s | %s),", matrixRef.c_str(), - projection ? "G_MTX_PROJECTION" : "G_MTX_MODELVIEW", - push ? "G_MTX_PUSH" : "G_MTX_NOPUSH", load ? "G_MTX_LOAD" : "G_MTX_MUL"); -} - -void ZDisplayList::Opcode_G_VTX(uint64_t data, char* line) -{ - int32_t nn = (data & 0x000FF00000000000ULL) >> 44; - int32_t aa = (data & 0x000000FF00000000ULL) >> 32; - - uint32_t vtxAddr = Seg2Filespace(data, parent->baseAddress); - - if (dListType == DListType::F3DZEX) - sprintf(line, "gsSPVertex(@r, %i, %i),", nn, ((aa >> 1) - nn)); - else - { - uint32_t hi = data >> 32; - -#define _SHIFTR(v, s, w) (((uint32_t)v >> s) & ((0x01 << w) - 1)) - - nn = _SHIFTR(hi, 10, 6); - - sprintf(line, "gsSPVertex(@r, %i, %i),", nn, _SHIFTR(hi, 17, 7)); - } - - // Hack: Don't extract vertices from a unknown segment. - if (!Globals::Instance->HasSegment(GETSEGNUM(data))) - { - segptr_t segmented = data & 0xFFFFFFFF; - references.push_back(segmented); - parent->AddDeclaration(segmented, DeclarationAlignment::Align8, 16, "Vtx", - StringHelper::Sprintf("0x%08X", segmented), ""); - return; - } - references.push_back(data); - - { - uint32_t currentPtr = Seg2Filespace(data, parent->baseAddress); - Declaration* decl; - - // Check for vertex intersections from other display lists - // TODO: These two could probably be condenced to one... - decl = parent->GetDeclarationRanged(vtxAddr + (nn * 16)); - if (decl != nullptr) - { - int32_t diff = decl->address - vtxAddr; - if (diff > 0) - nn = diff / 16; - else - nn = 0; - } - - decl = parent->GetDeclarationRanged(vtxAddr); - if (decl != nullptr) - { - int32_t diff = decl->address - vtxAddr; - if (diff > 0) - nn = diff / 16; - else - nn = 0; - } - - if (nn > 0) - { - std::vector vtxList; - vtxList.reserve(nn); - - for (int32_t i = 0; i < nn; i++) - { - ZVtx vtx(parent); - vtx.ExtractFromFile(currentPtr); - vtxList.push_back(vtx); - - currentPtr += 16; - } - - vertices[vtxAddr] = vtxList; - } - } -} - -void ZDisplayList::Opcode_G_TEXTURE(uint64_t data, char* line) -{ - int32_t ____ = (data & 0x0000FFFF00000000) >> 32; - int32_t ssss = (data & 0x00000000FFFF0000) >> 16; - int32_t tttt = (data & 0x000000000000FFFF); - int32_t lll = (____ & 0x3800) >> 11; - int32_t ddd = (____ & 0x700) >> 8; - int32_t nnnnnnn = 0; - - if (dListType == DListType::F3DEX) - nnnnnnn = (____ & 0xFF); - else - nnnnnnn = (____ & 0xFE) >> 1; - - sprintf(line, "gsSPTexture(%i, %i, %i, %i, %s),", ssss, tttt, lll, ddd, - nnnnnnn == 1 ? "G_ON" : "G_OFF"); -} - -void ZDisplayList::Opcode_G_SETTIMG(uint64_t data, const std::string& prefix, char* line) -{ - int32_t __ = (data & 0x00FF000000000000) >> 48; - int32_t www = (data & 0x00000FFF00000000) >> 32; - const char* fmtTbl[] = {"G_IM_FMT_RGBA", "G_IM_FMT_YUV", "G_IM_FMT_CI", "G_IM_FMT_IA", - "G_IM_FMT_I"}; - const char* sizTbl[] = {"G_IM_SIZ_4b", "G_IM_SIZ_8b", "G_IM_SIZ_16b", "G_IM_SIZ_32b"}; - - uint32_t fmt = (__ & 0xE0) >> 5; - uint32_t siz = (__ & 0x18) >> 3; - - if (Globals::Instance->verbosity >= VerbosityLevel::VERBOSITY_DEBUG) - printf("TextureGenCheck G_SETTIMG\n"); - - TextureGenCheck(); // HOTSPOT - - lastTexFmt = (F3DZEXTexFormats)fmt; - lastTexSiz = (F3DZEXTexSizes)siz; - lastTexSeg = data; - lastTexAddr = Seg2Filespace(data, parent->baseAddress); - - int32_t segmentNumber = GETSEGNUM(data); - - if (segmentNumber != 2) - { - char texStr[2048]; - int32_t texAddress = Seg2Filespace(data, parent->baseAddress); - Declaration* texDecl = nullptr; - - if (parent != nullptr) - { - if (Globals::Instance->HasSegment(segmentNumber)) - texDecl = parent->GetDeclaration(texAddress); - else - texDecl = parent->GetDeclaration(data); - } - - if (texDecl != nullptr) - sprintf(texStr, "%s", texDecl->declName.c_str()); - else if (data != 0 && Globals::Instance->HasSegment(segmentNumber)) - sprintf(texStr, "%sTex_%06X", prefix.c_str(), texAddress); - else - { - sprintf(texStr, "0x%08" PRIX64, data & 0xFFFFFFFF); - } - - sprintf(line, "gsDPSetTextureImage(%s, %s, %i, %s),", fmtTbl[fmt], sizTbl[siz], www + 1, - texStr); - } - else - { - std::string texName; - Globals::Instance->GetSegmentedPtrName(data, parent, "", texName); - sprintf(line, "gsDPSetTextureImage(%s, %s, %i, %s),", fmtTbl[fmt], sizTbl[siz], www + 1, - texName.c_str()); - } -} - -void ZDisplayList::Opcode_G_SETTILE(uint64_t data, char* line) -{ - int32_t fff = (data & 0b0000000011100000000000000000000000000000000000000000000000000000) >> 53; - int32_t ii = (data & 0b0000000000011000000000000000000000000000000000000000000000000000) >> 51; - int32_t nnnnnnnnn = - (data & 0b0000000000000011111111100000000000000000000000000000000000000000) >> 41; - int32_t mmmmmmmmm = - (data & 0b0000000000000000000000011111111100000000000000000000000000000000) >> 32; - int32_t ttt = (data & 0b0000000000000000000000000000000000000111000000000000000000000000) >> 24; - int32_t pppp = - (data & 0b0000000000000000000000000000000000000000111100000000000000000000) >> 20; - int32_t cc = (data & 0b0000000000000000000000000000000000000000000011000000000000000000) >> 18; - int32_t aaaa = - (data & 0b0000000000000000000000000000000000000000000000111100000000000000) >> 14; - int32_t ssss = - (data & 0b0000000000000000000000000000000000000000000000000011110000000000) >> 10; - int32_t dd = (data & 0b0000000000000000000000000000000000000000000000000000001100000000) >> 8; - int32_t bbbb = (data & 0b0000000000000000000000000000000000000000000000000000000011110000) >> 4; - int32_t uuuu = (data & 0b0000000000000000000000000000000000000000000000000000000000001111); - - const char* fmtTbl[] = {"G_IM_FMT_RGBA", "G_IM_FMT_YUV", "G_IM_FMT_CI", "G_IM_FMT_IA", - "G_IM_FMT_I"}; - const char* sizTbl[] = {"G_IM_SIZ_4b", "G_IM_SIZ_8b", "G_IM_SIZ_16b", "G_IM_SIZ_32b"}; - - if (fff == (int32_t)F3DZEXTexFormats::G_IM_FMT_CI) - lastCISiz = (F3DZEXTexSizes)ii; - - lastTexSizTest = (F3DZEXTexSizes)ii; - - sprintf(line, "gsDPSetTile(%s, %s, %i, %i, %i, %i, %i, %i, %i, %i, %i, %i),", fmtTbl[fff], - sizTbl[ii], nnnnnnnnn, mmmmmmmmm, ttt, pppp, cc, aaaa, ssss, dd, bbbb, uuuu); -} - -void ZDisplayList::Opcode_G_SETTILESIZE(uint64_t data, [[maybe_unused]] const std::string& prefix, - char* line) -{ - int32_t sss = (data & 0x00FFF00000000000) >> 44; - int32_t ttt = (data & 0x00000FFF00000000) >> 32; - int32_t uuu = (data & 0x0000000000FFF000) >> 12; - int32_t vvv = (data & 0x0000000000000FFF); - int32_t i = (data & 0x000000000F000000) >> 24; - - int32_t shiftAmtW = 2; - int32_t shiftAmtH = 2; - - if (lastTexSizTest == F3DZEXTexSizes::G_IM_SIZ_8b && - lastTexFmt == F3DZEXTexFormats::G_IM_FMT_IA) - shiftAmtW = 3; - - // if (lastTexFmt == F3DZEXTexFormats::G_IM_FMT_I || lastTexFmt == - // F3DZEXTexFormats::G_IM_FMT_CI) - if (lastTexSizTest == F3DZEXTexSizes::G_IM_SIZ_4b) - shiftAmtW = 3; - - if (lastTexSizTest == F3DZEXTexSizes::G_IM_SIZ_4b && - lastTexFmt == F3DZEXTexFormats::G_IM_FMT_IA) - shiftAmtH = 3; - - lastTexWidth = (uuu >> shiftAmtW) + 1; - lastTexHeight = (vvv >> shiftAmtH) + 1; - - if (Globals::Instance->verbosity >= VerbosityLevel::VERBOSITY_DEBUG) - printf("lastTexWidth: %i lastTexHeight: %i, lastTexSizTest: 0x%x, lastTexFmt: 0x%x\n", - lastTexWidth, lastTexHeight, (uint32_t)lastTexSizTest, (uint32_t)lastTexFmt); - - if (Globals::Instance->verbosity >= VerbosityLevel::VERBOSITY_DEBUG) - printf("TextureGenCheck G_SETTILESIZE\n"); - - TextureGenCheck(); - - sprintf(line, "gsDPSetTileSize(%i, %i, %i, %i, %i),", i, sss, ttt, uuu, vvv); -} - -void ZDisplayList::Opcode_G_LOADBLOCK(uint64_t data, char* line) -{ - int32_t sss = (data & 0x00FFF00000000000) >> 48; - int32_t ttt = (data & 0x00000FFF00000000) >> 36; - int32_t i = (data & 0x000000000F000000) >> 24; - int32_t xxx = (data & 0x0000000000FFF000) >> 12; - int32_t ddd = (data & 0x0000000000000FFF); - - lastTexLoaded = true; - - sprintf(line, "gsDPLoadBlock(%i, %i, %i, %i, %i),", i, sss, ttt, xxx, ddd); -} - -void ZDisplayList::Opcode_G_SETCOMBINE(uint64_t data, char* line) -{ - int32_t a0 = (data & 0b000000011110000000000000000000000000000000000000000000000000000) >> 52; - int32_t c0 = (data & 0b000000000001111100000000000000000000000000000000000000000000000) >> 47; - int32_t aa0 = (data & 0b00000000000000011100000000000000000000000000000000000000000000) >> 44; - int32_t ac0 = (data & 0b00000000000000000011100000000000000000000000000000000000000000) >> 41; - int32_t a1 = (data & 0b000000000000000000000011110000000000000000000000000000000000000) >> 37; - int32_t c1 = (data & 0b000000000000000000000000001111100000000000000000000000000000000) >> 32; - int32_t b0 = (data & 0b000000000000000000000000000000011110000000000000000000000000000) >> 28; - int32_t b1 = (data & 0b000000000000000000000000000000000001111000000000000000000000000) >> 24; - int32_t aa1 = (data & 0b00000000000000000000000000000000000000111000000000000000000000) >> 21; - int32_t ac1 = (data & 0b00000000000000000000000000000000000000000111000000000000000000) >> 18; - int32_t d0 = (data & 0b000000000000000000000000000000000000000000000111000000000000000) >> 15; - int32_t ab0 = (data & 0b00000000000000000000000000000000000000000000000111000000000000) >> 12; - int32_t ad0 = (data & 0b00000000000000000000000000000000000000000000000000111000000000) >> 9; - int32_t d1 = (data & 0b000000000000000000000000000000000000000000000000000000111000000) >> 6; - int32_t ab1 = (data & 0b00000000000000000000000000000000000000000000000000000000111000) >> 3; - int32_t ad1 = (data & 0b00000000000000000000000000000000000000000000000000000000000111) >> 0; - - const char* modesA[] = {"COMBINED", "TEXEL0", "TEXEL1", "PRIMITIVE", "SHADE", "ENVIRONMENT", - "1", "NOISE", "0", "9", "10", "11", - "12", "13", "14", "0"}; - const char* modesB[] = {"COMBINED", "TEXEL0", "TEXEL1", "PRIMITIVE", "SHADE", "ENVIRONMENT", - "CENTER", "K4", "8", "9", "10", "11", - "12", "13", "14", "0"}; - const char* modesC[] = {"COMBINED", - "TEXEL0", - "TEXEL1", - "PRIMITIVE", - "SHADE", - "ENVIRONMENT", - "1", - "COMBINED_ALPHA", - "TEXEL0_ALPHA", - "TEXEL1_ALPHA", - "PRIMITIVE_ALPHA", - "SHADE_ALPHA", - "ENV_ALPHA", - "LOD_FRACTION", - "PRIM_LOD_FRAC", - "K5", - "16", - "17", - "18", - "19", - "20", - "21", - "22", - "23", - "24", - "25", - "26", - "27", - "28", - "29", - "30", - "0"}; - const char* modesD[] = {"COMBINED", "TEXEL0", "TEXEL1", "PRIMITIVE", - "SHADE", "ENVIRONMENT", "1", "0"}; - - const char* modes2[] = {"COMBINED", "TEXEL0", "TEXEL1", "PRIMITIVE", - "SHADE", "ENVIRONMENT", "1", "0"}; - const char* modes2C[] = {"LOD_FRACTION", "TEXEL0", "TEXEL1", "PRIMITIVE", - "SHADE", "ENVIRONMENT", "PRIM_LOD_FRAC", "0"}; - - sprintf(line, - "gsDPSetCombineLERP(%s, %s, %s, %s, %s, %s, %s, %s,\n %s, %s, " - "%s, %s, %s, %s, %s, %s),", - modesA[a0], modesB[b0], modesC[c0], modesD[d0], modes2[aa0], modes2[ab0], modes2C[ac0], - modes2[ad0], modesA[a1], modesB[b1], modesC[c1], modesD[d1], modes2[aa1], modes2[ab1], - modes2C[ac1], modes2[ad1]); -} - -void ZDisplayList::Opcode_G_SETPRIMCOLOR(uint64_t data, char* line) -{ - int32_t mm = (data & 0x0000FF0000000000) >> 40; - int32_t ff = (data & 0x000000FF00000000) >> 32; - int32_t rr = (data & 0x00000000FF000000) >> 24; - int32_t gg = (data & 0x0000000000FF0000) >> 16; - int32_t bb = (data & 0x000000000000FF00) >> 8; - int32_t aa = (data & 0x00000000000000FF) >> 0; - sprintf(line, "gsDPSetPrimColor(%i, %i, %i, %i, %i, %i),", mm, ff, rr, gg, bb, aa); -} - -void ZDisplayList::Opcode_F3DEX_G_SETOTHERMODE_L(uint64_t data, char* line) -{ - int32_t sft = (data & 0x0000FF0000000000) >> 40; - int32_t len = (data & 0x000000FF00000000) >> 32; - int32_t dat = (data & 0xFFFFFFFF); - - // TODO: Output the correct render modes in data - - sprintf(line, "gsSPSetOtherMode(0xE2, %i, %i, 0x%08X),", sft, len, dat); -} - -void ZDisplayList::Opcode_G_SETOTHERMODE_L(uint64_t data, char* line) -{ - int32_t dd = (data & 0xFFFFFFFF); - int32_t sft = 0; - int32_t len = 0; - - if (dListType == DListType::F3DEX) - { - sft = (data & 0x0000FF0000000000) >> 40; - len = (data & 0x000000FF00000000) >> 32; - } - else - { - int32_t ss = (data & 0x0000FF0000000000) >> 40; - len = ((data & 0x000000FF00000000) >> 32) + 1; - sft = 32 - (len)-ss; - } - - if (sft == G_MDSFT_RENDERMODE) - { - uint32_t mode1 = (dd & 0xCCCC0000) >> 0; - uint32_t mode2 = (dd & 0x3333FFFF); - - // TODO: Jesus Christ This is Messy - - uint32_t tblA[] = {G_RM_FOG_SHADE_A, - G_RM_FOG_PRIM_A, - G_RM_PASS, - G_RM_AA_ZB_OPA_SURF, - G_RM_AA_ZB_XLU_SURF, - G_RM_AA_ZB_OPA_DECAL, - G_RM_AA_ZB_XLU_DECAL, - G_RM_AA_ZB_OPA_INTER, - G_RM_AA_ZB_XLU_INTER, - G_RM_AA_ZB_XLU_LINE, - G_RM_AA_ZB_DEC_LINE, - G_RM_AA_ZB_TEX_EDGE, - G_RM_AA_ZB_TEX_INTER, - G_RM_AA_ZB_SUB_SURF, - G_RM_AA_ZB_PCL_SURF, - G_RM_AA_ZB_OPA_TERR, - G_RM_AA_ZB_TEX_TERR, - G_RM_AA_ZB_SUB_TERR, - G_RM_RA_ZB_OPA_SURF, - G_RM_RA_ZB_OPA_DECAL, - G_RM_RA_ZB_OPA_INTER, - G_RM_AA_OPA_SURF, - G_RM_AA_XLU_SURF, - G_RM_AA_XLU_LINE, - G_RM_AA_DEC_LINE, - G_RM_AA_TEX_EDGE, - G_RM_AA_SUB_SURF, - G_RM_AA_PCL_SURF, - G_RM_AA_OPA_TERR, - G_RM_AA_TEX_TERR, - G_RM_AA_SUB_TERR, - G_RM_RA_OPA_SURF, - G_RM_ZB_OPA_SURF, - G_RM_ZB_XLU_SURF, - G_RM_ZB_OPA_DECAL, - G_RM_ZB_XLU_DECAL, - G_RM_ZB_CLD_SURF, - G_RM_ZB_OVL_SURF, - G_RM_ZB_PCL_SURF, - G_RM_OPA_SURF, - G_RM_XLU_SURF, - G_RM_CLD_SURF, - G_RM_TEX_EDGE, - G_RM_PCL_SURF, - G_RM_ADD, - G_RM_NOOP, - G_RM_VISCVG, - G_RM_OPA_CI}; - - uint32_t tblB[] = {G_RM_AA_ZB_OPA_SURF2, - G_RM_AA_ZB_XLU_SURF2, - G_RM_AA_ZB_OPA_DECAL2, - G_RM_AA_ZB_XLU_DECAL2, - G_RM_AA_ZB_OPA_INTER2, - G_RM_AA_ZB_XLU_INTER2, - G_RM_AA_ZB_XLU_LINE2, - G_RM_AA_ZB_DEC_LINE2, - G_RM_AA_ZB_TEX_EDGE2, - G_RM_AA_ZB_TEX_INTER2, - G_RM_AA_ZB_SUB_SURF2, - G_RM_AA_ZB_PCL_SURF2, - G_RM_AA_ZB_OPA_TERR2, - G_RM_AA_ZB_TEX_TERR2, - G_RM_AA_ZB_SUB_TERR2, - G_RM_RA_ZB_OPA_SURF2, - G_RM_RA_ZB_OPA_DECAL2, - G_RM_RA_ZB_OPA_INTER2, - G_RM_AA_OPA_SURF2, - G_RM_AA_XLU_SURF2, - G_RM_AA_XLU_LINE2, - G_RM_AA_DEC_LINE2, - G_RM_AA_TEX_EDGE2, - G_RM_AA_SUB_SURF2, - G_RM_AA_PCL_SURF2, - G_RM_AA_OPA_TERR2, - G_RM_AA_TEX_TERR2, - G_RM_AA_SUB_TERR2, - G_RM_RA_OPA_SURF2, - G_RM_ZB_OPA_SURF2, - G_RM_ZB_XLU_SURF2, - G_RM_ZB_OPA_DECAL2, - G_RM_ZB_XLU_DECAL2, - G_RM_ZB_CLD_SURF2, - G_RM_ZB_OVL_SURF2, - G_RM_ZB_PCL_SURF2, - G_RM_OPA_SURF2, - G_RM_XLU_SURF2, - G_RM_CLD_SURF2, - G_RM_TEX_EDGE2, - G_RM_PCL_SURF2, - G_RM_ADD2, - G_RM_NOOP2, - G_RM_VISCVG2, - G_RM_OPA_CI2}; - - std::map str = { - {G_RM_FOG_SHADE_A, "G_RM_FOG_SHADE_A"}, - {G_RM_FOG_PRIM_A, "G_RM_FOG_PRIM_A"}, - {G_RM_PASS, "G_RM_PASS"}, - {G_RM_AA_ZB_OPA_SURF, "G_RM_AA_ZB_OPA_SURF"}, - {G_RM_AA_ZB_OPA_SURF2, "G_RM_AA_ZB_OPA_SURF2"}, - {G_RM_AA_ZB_XLU_SURF, "G_RM_AA_ZB_XLU_SURF"}, - {G_RM_AA_ZB_XLU_SURF2, "G_RM_AA_ZB_XLU_SURF2"}, - {G_RM_AA_ZB_OPA_DECAL, "G_RM_AA_ZB_OPA_DECAL"}, - {G_RM_AA_ZB_OPA_DECAL2, "G_RM_AA_ZB_OPA_DECAL2"}, - {G_RM_AA_ZB_XLU_DECAL, "G_RM_AA_ZB_XLU_DECAL"}, - {G_RM_AA_ZB_XLU_DECAL2, "G_RM_AA_ZB_XLU_DECAL2"}, - {G_RM_AA_ZB_OPA_INTER, "G_RM_AA_ZB_OPA_INTER"}, - {G_RM_AA_ZB_OPA_INTER2, "G_RM_AA_ZB_OPA_INTER2"}, - {G_RM_AA_ZB_XLU_INTER, "G_RM_AA_ZB_XLU_INTER"}, - {G_RM_AA_ZB_XLU_INTER2, "G_RM_AA_ZB_XLU_INTER2"}, - {G_RM_AA_ZB_XLU_LINE, "G_RM_AA_ZB_XLU_LINE"}, - {G_RM_AA_ZB_XLU_LINE2, "G_RM_AA_ZB_XLU_LINE2"}, - {G_RM_AA_ZB_DEC_LINE, "G_RM_AA_ZB_DEC_LINE"}, - {G_RM_AA_ZB_DEC_LINE2, "G_RM_AA_ZB_DEC_LINE2"}, - {G_RM_AA_ZB_TEX_EDGE, "G_RM_AA_ZB_TEX_EDGE"}, - {G_RM_AA_ZB_TEX_EDGE2, "G_RM_AA_ZB_TEX_EDGE2"}, - {G_RM_AA_ZB_TEX_INTER, "G_RM_AA_ZB_TEX_INTER"}, - {G_RM_AA_ZB_TEX_INTER2, "G_RM_AA_ZB_TEX_INTER2"}, - {G_RM_AA_ZB_SUB_SURF, "G_RM_AA_ZB_SUB_SURF"}, - {G_RM_AA_ZB_SUB_SURF2, "G_RM_AA_ZB_SUB_SURF2"}, - {G_RM_AA_ZB_PCL_SURF, "G_RM_AA_ZB_PCL_SURF"}, - {G_RM_AA_ZB_PCL_SURF2, "G_RM_AA_ZB_PCL_SURF2"}, - {G_RM_AA_ZB_OPA_TERR, "G_RM_AA_ZB_OPA_TERR"}, - {G_RM_AA_ZB_OPA_TERR2, "G_RM_AA_ZB_OPA_TERR2"}, - {G_RM_AA_ZB_TEX_TERR, "G_RM_AA_ZB_TEX_TERR"}, - {G_RM_AA_ZB_TEX_TERR2, "G_RM_AA_ZB_TEX_TERR2"}, - {G_RM_AA_ZB_SUB_TERR, "G_RM_AA_ZB_SUB_TERR"}, - {G_RM_AA_ZB_SUB_TERR2, "G_RM_AA_ZB_SUB_TERR2"}, - {G_RM_RA_ZB_OPA_SURF, "G_RM_RA_ZB_OPA_SURF"}, - {G_RM_RA_ZB_OPA_SURF2, "G_RM_RA_ZB_OPA_SURF2"}, - {G_RM_RA_ZB_OPA_DECAL, "G_RM_RA_ZB_OPA_DECAL"}, - {G_RM_RA_ZB_OPA_DECAL2, "G_RM_RA_ZB_OPA_DECAL2"}, - {G_RM_RA_ZB_OPA_INTER, "G_RM_RA_ZB_OPA_INTER"}, - {G_RM_RA_ZB_OPA_INTER2, "G_RM_RA_ZB_OPA_INTER2"}, - {G_RM_AA_OPA_SURF, "G_RM_AA_OPA_SURF"}, - {G_RM_AA_OPA_SURF2, "G_RM_AA_OPA_SURF2"}, - {G_RM_AA_XLU_SURF, "G_RM_AA_XLU_SURF"}, - {G_RM_AA_XLU_SURF2, "G_RM_AA_XLU_SURF2"}, - {G_RM_AA_XLU_LINE, "G_RM_AA_XLU_LINE"}, - {G_RM_AA_XLU_LINE2, "G_RM_AA_XLU_LINE2"}, - {G_RM_AA_DEC_LINE, "G_RM_AA_DEC_LINE"}, - {G_RM_AA_DEC_LINE2, "G_RM_AA_DEC_LINE2"}, - {G_RM_AA_TEX_EDGE, "G_RM_AA_TEX_EDGE"}, - {G_RM_AA_TEX_EDGE2, "G_RM_AA_TEX_EDGE2"}, - {G_RM_AA_SUB_SURF, "G_RM_AA_SUB_SURF"}, - {G_RM_AA_SUB_SURF2, "G_RM_AA_SUB_SURF2"}, - {G_RM_AA_PCL_SURF, "G_RM_AA_PCL_SURF"}, - {G_RM_AA_PCL_SURF2, "G_RM_AA_PCL_SURF2"}, - {G_RM_AA_OPA_TERR, "G_RM_AA_OPA_TERR"}, - {G_RM_AA_OPA_TERR2, "G_RM_AA_OPA_TERR2"}, - {G_RM_AA_TEX_TERR, "G_RM_AA_TEX_TERR"}, - {G_RM_AA_TEX_TERR2, "G_RM_AA_TEX_TERR2"}, - {G_RM_AA_TEX_TERR, "G_RM_AA_TEX_TERR"}, - {G_RM_AA_TEX_TERR2, "G_RM_AA_TEX_TERR2"}, - {G_RM_AA_SUB_TERR, "G_RM_AA_SUB_TERR"}, - {G_RM_AA_SUB_TERR2, "G_RM_AA_SUB_TERR2"}, - {G_RM_RA_OPA_SURF, "G_RM_RA_OPA_SURF"}, - {G_RM_RA_OPA_SURF2, "G_RM_RA_OPA_SURF2"}, - {G_RM_ZB_OPA_SURF, "G_RM_ZB_OPA_SURF"}, - {G_RM_ZB_OPA_SURF2, "G_RM_ZB_OPA_SURF2"}, - {G_RM_ZB_XLU_SURF, "G_RM_ZB_XLU_SURF"}, - {G_RM_ZB_XLU_SURF2, "G_RM_ZB_XLU_SURF2"}, - {G_RM_ZB_OPA_DECAL, "G_RM_ZB_OPA_DECAL"}, - {G_RM_ZB_OPA_DECAL2, "G_RM_ZB_OPA_DECAL2"}, - {G_RM_ZB_XLU_DECAL, "G_RM_ZB_XLU_DECAL"}, - {G_RM_ZB_XLU_DECAL2, "G_RM_ZB_XLU_DECAL2"}, - {G_RM_ZB_CLD_SURF, "G_RM_ZB_CLD_SURF"}, - {G_RM_ZB_CLD_SURF2, "G_RM_ZB_CLD_SURF2"}, - {G_RM_ZB_OVL_SURF, "G_RM_ZB_OVL_SURF"}, - {G_RM_ZB_OVL_SURF2, "G_RM_ZB_OVL_SURF2"}, - {G_RM_ZB_PCL_SURF, "G_RM_ZB_PCL_SURF"}, - {G_RM_ZB_PCL_SURF2, "G_RM_ZB_PCL_SURF2"}, - {G_RM_OPA_SURF, "G_RM_OPA_SURF"}, - {G_RM_OPA_SURF2, "G_RM_OPA_SURF2"}, - {G_RM_XLU_SURF, "G_RM_XLU_SURF"}, - {G_RM_XLU_SURF2, "G_RM_XLU_SURF2"}, - {G_RM_CLD_SURF, "G_RM_CLD_SURF"}, - {G_RM_CLD_SURF2, "G_RM_CLD_SURF2"}, - {G_RM_TEX_EDGE, "G_RM_TEX_EDGE"}, - {G_RM_TEX_EDGE2, "G_RM_TEX_EDGE2"}, - {G_RM_PCL_SURF, "G_RM_PCL_SURF"}, - {G_RM_PCL_SURF2, "G_RM_PCL_SURF2"}, - {G_RM_ADD, "G_RM_ADD"}, - {G_RM_ADD2, "G_RM_ADD2"}, - {G_RM_NOOP, "G_RM_NOOP"}, - {G_RM_NOOP2, "G_RM_NOOP2"}, - {G_RM_VISCVG, "G_RM_VISCVG"}, - {G_RM_VISCVG2, "G_RM_VISCVG2"}, - {G_RM_OPA_CI, "G_RM_OPA_CI"}, - {G_RM_OPA_CI2, "G_RM_OPA_CI2"}, - }; - - for (uint32_t k = 0; k < sizeof(tblA) / 4; k++) - { - if ((dd & tblA[k]) == tblA[k]) - { - if (tblA[k] > mode1) - mode1 = tblA[k]; - } - } - - for (uint32_t k = 0; k < sizeof(tblB) / 4; k++) - { - if ((dd & tblB[k]) == tblB[k]) - { - if (tblB[k] > mode2) - mode2 = tblB[k]; - } - } - - std::string mode1Str = str[mode1]; - std::string mode2Str = str[mode2]; - - if (mode1Str == "") - { - mode1Str = StringHelper::Sprintf("0x%08X", mode1); - } - - if (mode2Str == "") - { - if (mode2 & AA_EN) - { - mode2Str += "AA_EN | "; - } - - if (mode2 & Z_CMP) - { - mode2Str += "Z_CMP | "; - } - - if (mode2 & Z_UPD) - { - mode2Str += "Z_UPD | "; - } - - if (mode2 & IM_RD) - { - mode2Str += "IM_RD | "; - } - - if (mode2 & CLR_ON_CVG) - { - mode2Str += "CLR_ON_CVG | "; - } - - if (mode2 & CVG_DST_CLAMP) - { - mode2Str += "CVG_DST_CLAMP | "; - } - - if (mode2 & CVG_DST_WRAP) - { - mode2Str += "CVG_DST_WRAP | "; - } - - if (mode2 & CVG_DST_FULL) - { - mode2Str += "CVG_DST_FULL | "; - } - - if (mode2 & CVG_DST_SAVE) - { - mode2Str += "CVG_DST_SAVE | "; - } - - int32_t zMode = mode2 & 0xC00; - - if (zMode == ZMODE_INTER) - { - mode2Str += "ZMODE_INTER | "; - } - else if (zMode == ZMODE_XLU) - { - mode2Str += "ZMODE_XLU | "; - } - else if (zMode == ZMODE_DEC) - { - mode2Str += "ZMODE_DEC | "; - } - - if (mode2 & CVG_X_ALPHA) - { - mode2Str += "CVG_X_ALPHA | "; - } - - if (mode2 & ALPHA_CVG_SEL) - { - mode2Str += "ALPHA_CVG_SEL | "; - } - - if (mode2 & FORCE_BL) - { - mode2Str += "FORCE_BL | "; - } - - int32_t bp = (mode2 >> 28) & 0b11; - int32_t ba = (mode2 >> 24) & 0b11; - int32_t bm = (mode2 >> 20) & 0b11; - int32_t bb = (mode2 >> 16) & 0b11; - - mode2Str += StringHelper::Sprintf("GBL_c2(%i, %i, %i, %i)", bp, ba, bm, bb); - // mode2Str = StringHelper::Sprintf("0x%08X", mode2); - } - - sprintf(line, "gsDPSetRenderMode(%s, %s),", mode1Str.c_str(), mode2Str.c_str()); - } - else - { - sprintf(line, "gsSPSetOtherMode(0xE2, %i, %i, 0x%08X),", sft, len, dd); - } -} - -void ZDisplayList::Opcode_G_SETOTHERMODE_H(uint64_t data, char* line) -{ - int32_t ss = (data & 0x0000FF0000000000) >> 40; - int32_t nn = (data & 0x000000FF00000000) >> 32; - int32_t dd = (data & 0xFFFFFFFF); - - int32_t sft = 32 - (nn + 1) - ss; - - if (sft == 14) // G_MDSFT_TEXTLUT - { - const char* types[] = {"G_TT_NONE", "G_TT_NONE", "G_TT_RGBA16", "G_TT_IA16"}; - sprintf(line, "gsDPSetTextureLUT(%s),", types[dd >> 14]); - } - else - sprintf(line, "gsSPSetOtherMode(0xE3, %i, %i, 0x%08X),", sft, nn + 1, dd); -} - -void ZDisplayList::Opcode_G_LOADTLUT(uint64_t data, [[maybe_unused]] const std::string& prefix, - char* line) -{ - int32_t t = (data & 0x0000000007000000) >> 24; - int32_t ccc = (data & 0x00000000003FF000) >> 14; - - lastTexWidth = sqrt(ccc + 1); - lastTexHeight = sqrt(ccc + 1); - - lastTexLoaded = true; - lastTexIsPalette = true; - - if (Globals::Instance->verbosity >= VerbosityLevel::VERBOSITY_DEBUG) - printf("TextureGenCheck G_LOADTLUT (lastCISiz: %i)\n", (uint32_t)lastCISiz); - - TextureGenCheck(); - - sprintf(line, "gsDPLoadTLUTCmd(%i, %i),", t, ccc); -} - -void ZDisplayList::Opcode_G_ENDDL([[maybe_unused]] const std::string& prefix, char* line) -{ - sprintf(line, "gsSPEndDisplayList(),"); - - if (Globals::Instance->verbosity >= VerbosityLevel::VERBOSITY_DEBUG) - printf("TextureGenCheck G_ENDDL\n"); - - TextureGenCheck(); -} - -static int32_t GfxdCallback_FormatSingleEntry() -{ - ZDisplayList* self = static_cast(gfxd_udata_get()); - gfxd_puts("\t"); - gfxd_macro_dflt(); - gfxd_puts(","); - - auto macroId = gfxd_macro_id(); - - switch (macroId) - { - case gfxd_SP1Triangle: - case gfxd_SP2Triangles: - if (self->lastTexture != nullptr && self->lastTexture->IsColorIndexed() && - !self->lastTexture->HasTlut()) - { - auto tex = self->lastTexture; - auto tlut = self->lastTlut; - - if (Globals::Instance->verbosity >= VerbosityLevel::VERBOSITY_DEBUG) - { - if (tlut != nullptr) - printf("CI texture '%s' (0x%X), TLUT: '%s' (0x%X)\n", tex->GetName().c_str(), - tex->GetRawDataIndex(), tlut->GetName().c_str(), - tlut->GetRawDataIndex()); - else - printf("CI texture '%s' (0x%X), TLUT: null\n", tex->GetName().c_str(), - tex->GetRawDataIndex()); - } - - if (tlut != nullptr && !tex->HasTlut()) - tex->SetTlut(tlut); - } - break; - } - - // dont print a new line after the last command - switch (macroId) - { - case gfxd_SPEndDisplayList: - case gfxd_SPBranchList: - break; - - default: - gfxd_puts("\n"); - break; - } - - return 0; -} - -static int32_t GfxdCallback_Vtx(uint32_t seg, int32_t count) -{ - ZDisplayList* self = static_cast(gfxd_udata_get()); - uint32_t vtxOffset = Seg2Filespace(seg, self->parent->baseAddress); - - if (GETSEGNUM(seg) == self->parent->segment) - { - Declaration* decl; - - // Check for vertex intersections from other display lists - // TODO: These two could probably be condenced to one... - decl = self->parent->GetDeclarationRanged(vtxOffset + (count * 16)); - if (decl != nullptr) - { - int32_t diff = decl->address - vtxOffset; - - if (diff > 0) - count = diff / 16; - else - count = 0; - } - - decl = self->parent->GetDeclarationRanged(vtxOffset); - if (decl != nullptr) - { - int32_t diff = decl->address - vtxOffset; - - if (diff > 0) - count = diff / 16; - else - count = 0; - } - - if (count > 0) - { - std::vector vtxList; - vtxList.reserve(count); - - uint32_t currentPtr = vtxOffset; - for (int32_t i = 0; i < count; i++) - { - ZVtx vtx(self->parent); - vtx.ExtractFromFile(currentPtr); - - vtxList.push_back(vtx); - currentPtr += 16; - } - - bool keyAlreadyOccupied = self->vertices.find(vtxOffset) != self->vertices.end(); - - // In some cases a vtxList already exists at vtxOffset. Only override the existing list - // if the new one is bigger. - if (!keyAlreadyOccupied || - (keyAlreadyOccupied && vtxList.size() > self->vertices[vtxOffset].size())) - self->vertices[vtxOffset] = vtxList; - } - } - - self->references.push_back(seg); - gfxd_puts("@r"); - - return 1; -} - -static int32_t GfxdCallback_Texture(segptr_t seg, int32_t fmt, int32_t siz, int32_t width, - int32_t height, [[maybe_unused]] int32_t pal) -{ - ZDisplayList* self = static_cast(gfxd_udata_get()); - uint32_t texOffset = Seg2Filespace(seg, self->parent->baseAddress); - - self->lastTexWidth = width; - self->lastTexHeight = height; - self->lastTexAddr = texOffset; - self->lastTexSeg = seg; - self->lastTexFmt = static_cast(fmt); - self->lastTexSiz = static_cast(siz); - self->lastTexLoaded = true; - self->lastTexIsPalette = false; - - self->TextureGenCheck(); - - std::string texName; - Globals::Instance->GetSegmentedPtrName(seg, self->parent, "", texName); - - gfxd_puts(texName.c_str()); - - return 1; -} - -static int32_t GfxdCallback_Palette(uint32_t seg, [[maybe_unused]] int32_t idx, int32_t count) -{ - ZDisplayList* self = static_cast(gfxd_udata_get()); - uint32_t palOffset = Seg2Filespace(seg, self->parent->baseAddress); - - self->lastTexWidth = sqrt(count); - self->lastTexHeight = sqrt(count); - self->lastTexAddr = palOffset; - self->lastTexSeg = seg; - self->lastTexSiz = F3DZEXTexSizes::G_IM_SIZ_16b; - self->lastTexFmt = F3DZEXTexFormats::G_IM_FMT_RGBA; - self->lastTexLoaded = true; - self->lastTexIsPalette = true; - - self->TextureGenCheck(); - - std::string palName; - Globals::Instance->GetSegmentedPtrName(seg, self->parent, "", palName); - - gfxd_puts(palName.c_str()); - - return 1; -} - -static int32_t GfxdCallback_DisplayList(uint32_t seg) -{ - ZDisplayList* self = static_cast(gfxd_udata_get()); - uint32_t dListOffset = GETSEGOFFSET(seg); - uint32_t dListSegNum = GETSEGNUM(seg); - - std::string dListName = ""; - bool addressFound = - Globals::Instance->GetSegmentedPtrName(seg, self->parent, "Gfx", dListName, false); - - if (!addressFound) - { - if (self->parent->segment == dListSegNum) - { - ZDisplayList* newDList = new ZDisplayList(self->parent); - newDList->ExtractFromBinary( - dListOffset, - self->GetDListLength(self->parent->GetRawData(), dListOffset, self->dListType)); - newDList->SetName(newDList->GetDefaultName(self->parent->GetName())); - self->otherDLists.push_back(newDList); - dListName = newDList->GetName(); - } - else - { - Globals::Instance->WarnHardcodedPointer(seg, self->parent, self, - self->GetRawDataIndex()); - } - } - - gfxd_puts(dListName.c_str()); - - return 1; -} - -static int32_t GfxdCallback_Matrix(uint32_t seg) -{ - std::string mtxName; - ZDisplayList* self = static_cast(gfxd_udata_get()); - - bool addressFound = - Globals::Instance->GetSegmentedPtrName(seg, self->parent, "Mtx", mtxName, false); - - if (!addressFound) - { - if (GETSEGNUM(seg) == self->parent->segment) - { - Declaration* decl = - self->parent->GetDeclaration(Seg2Filespace(seg, self->parent->baseAddress)); - if (decl == nullptr) - { - ZMtx mtx(self->parent); - mtx.SetName(mtx.GetDefaultName(self->GetName())); - mtx.ExtractFromFile(Seg2Filespace(seg, self->parent->baseAddress)); - mtx.DeclareVar(self->GetName(), ""); - - mtx.GetSourceOutputCode(self->GetName()); - self->mtxList.push_back(mtx); - mtxName = "&" + mtx.GetName(); - } - } - else - { - Globals::Instance->WarnHardcodedPointer(seg, self->parent, self, - self->GetRawDataIndex()); - } - } - - gfxd_puts(mtxName.c_str()); - - return 1; -} - -void ZDisplayList::DeclareReferences(const std::string& prefix) -{ - std::string sourceOutput; - - if (Globals::Instance->useLegacyZDList) - sourceOutput += ProcessLegacy(prefix); - else - sourceOutput += ProcessGfxDis(prefix); - - // Iterate through our vertex lists, connect intersecting lists. - if (vertices.size() > 0) - { - std::vector>> verticesSorted(vertices.begin(), - vertices.end()); - - for (size_t i = 0; i < verticesSorted.size() - 1; i++) - { - size_t vtxSize = vertices[verticesSorted[i].first].size() * 16; - - if ((verticesSorted[i].first + vtxSize) > verticesSorted[i + 1].first) - { - int32_t intersectAmt = - (verticesSorted[i].first + vtxSize) - verticesSorted[i + 1].first; - int32_t intersectIndex = intersectAmt / 16; - - for (size_t j = intersectIndex; j < verticesSorted[i + 1].second.size(); j++) - vertices[verticesSorted[i].first].push_back(verticesSorted[i + 1].second[j]); - - vertices.erase(verticesSorted[i + 1].first); - verticesSorted.erase(verticesSorted.begin() + i + 1); - - i--; - } - } - - // Generate Vertex Declarations - for (auto& item : vertices) - { - std::string declaration = ""; - - offset_t curAddr = item.first; - auto& firstVtx = item.second.at(0); - - for (auto vtx : item.second) - declaration += StringHelper::Sprintf("\t%s,\n", vtx.GetBodySourceCode().c_str()); - - Declaration* decl = parent->AddDeclarationArray( - curAddr, firstVtx.GetDeclarationAlignment(), - item.second.size() * firstVtx.GetRawDataSize(), firstVtx.GetSourceTypeName(), - firstVtx.GetDefaultName(name), item.second.size(), declaration); - decl->isExternal = true; - } - } - - Declaration* decl = DeclareVar("", sourceOutput); - decl->references = references; - - // Iterate through our vertex lists, connect intersecting lists. - if (vertices.size() > 0) - { - std::vector>> verticesSorted(vertices.begin(), - vertices.end()); - - for (size_t i = 0; i < verticesSorted.size() - 1; i++) - { - // int32_t vtxSize = verticesSorted[i].second.size() * 16; - size_t vtxSize = vertices[verticesSorted[i].first].size() * 16; - - if ((verticesSorted[i].first + vtxSize) > verticesSorted[i + 1].first) - { - int32_t intersectAmt = - (verticesSorted[i].first + vtxSize) - verticesSorted[i + 1].first; - int32_t intersectIndex = intersectAmt / 16; - - for (size_t j = intersectIndex; j < verticesSorted[i + 1].second.size(); j++) - vertices[verticesSorted[i].first].push_back(verticesSorted[i + 1].second[j]); - - vertices.erase(verticesSorted[i + 1].first); - verticesSorted.erase(verticesSorted.begin() + i + 1); - - i--; - } - } - - // Generate Vertex Declarations - std::vector vtxKeys; - vtxKeys.reserve(vertices.size()); - for (auto& item : vertices) - vtxKeys.push_back(item.first); - - // for (pair> item : vertices) - for (size_t i = 0; i < vtxKeys.size(); i++) - { - auto& item = vertices[vtxKeys[i]]; - - std::string declaration; - - for (auto& vtx : item) - declaration += StringHelper::Sprintf("\t%s,\n", vtx.GetBodySourceCode().c_str()); - - // Ensure there's always a trailing line feed to prevent dumb warnings. - // Please don't remove this line, unless you somehow made a way to prevent - // that warning when building the OoT repo. - declaration += "\n"; - - if (parent != nullptr) - { - std::string vtxName; - ZResource* vtxRes = parent->FindResource(vtxKeys[i]); - - if (vtxRes != nullptr) - vtxName = vtxRes->GetName(); - else - vtxName = StringHelper::Sprintf("%sVtx_%06X", prefix.c_str(), vtxKeys[i]); - - auto filepath = Globals::Instance->outputPath / vtxName; - std::string incStr = - StringHelper::Sprintf("%s.%s.inc", filepath.string().c_str(), "vtx"); - - Declaration* vtxDecl = parent->AddDeclarationIncludeArray( - vtxKeys[i], incStr, item.size() * 16, "Vtx", vtxName, item.size()); - vtxDecl->isExternal = true; - } - } - } -} - -std::string ZDisplayList::ProcessLegacy(const std::string& prefix) -{ - char line[4096]; - std::string sourceOutput; - - for (size_t i = 0; i < instructions.size(); i++) - { - uint8_t opcode = (uint8_t)(instructions[i] >> 56); - uint64_t data = instructions[i]; - sourceOutput += " "; - - auto start = std::chrono::steady_clock::now(); - - int32_t optimizationResult = OptimizationChecks(i, sourceOutput, prefix); - - if (optimizationResult != -1) - { - i += optimizationResult - 1; - line[0] = '\0'; - } - else - { - if (dListType == DListType::F3DZEX) - ParseF3DZEX((F3DZEXOpcode)opcode, data, i, prefix, line); - else - ParseF3DEX((F3DEXOpcode)opcode, data, prefix, line); - } - - auto end = std::chrono::steady_clock::now(); - int64_t diff = std::chrono::duration_cast(end - start).count(); - - if (Globals::Instance->verbosity >= VerbosityLevel::VERBOSITY_DEBUG && diff > 5) - printf("F3DOP: 0x%02X, TIME: %" PRIi64 "ms\n", opcode, diff); - - sourceOutput += line; - - if (i < instructions.size() - 1) - sourceOutput += "\n"; - } - - return sourceOutput; -} - -std::string ZDisplayList::ProcessGfxDis([[maybe_unused]] const std::string& prefix) -{ - std::string sourceOutput; - - OutputFormatter outputformatter; - int32_t dListSize = instructions.size() * sizeof(instructions[0]); - - gfxd_input_buffer(instructions.data(), dListSize); - gfxd_endian(gfxd_endian_little, sizeof(uint64_t)); // tell gfxdis what format the data is - - gfxd_macro_fn(GfxdCallback_FormatSingleEntry); // format for each command entry - gfxd_vtx_callback(GfxdCallback_Vtx); // handle vertices - gfxd_timg_callback(GfxdCallback_Texture); // handle textures - gfxd_tlut_callback(GfxdCallback_Palette); // handle palettes - gfxd_dl_callback(GfxdCallback_DisplayList); // handle child display lists - gfxd_mtx_callback(GfxdCallback_Matrix); // handle matrices - gfxd_output_callback( - outputformatter.StaticWriter()); // convert tabs to 4 spaces and enforce 120 line limit - - gfxd_enable(gfxd_emit_dec_color); // use decimal for colors - - // set microcode. see gfxd.h for more options. - if (dListType == DListType::F3DZEX) - gfxd_target(gfxd_f3dex2); - else - gfxd_target(gfxd_f3dex); - - gfxd_udata_set(this); - gfxd_execute(); // generate display list - sourceOutput += outputformatter.GetOutput(); // write formatted display list - - MergeConnectingVertexLists(); - - return sourceOutput; -} - -void ZDisplayList::MergeConnectingVertexLists() -{ - if (vertices.size() > 0) - { - std::vector>> vertexKeys(vertices.begin(), - vertices.end()); - std::pair> lastItem = vertexKeys.at(0); - - for (size_t i = 1; i < vertexKeys.size(); i++) - { - std::pair> curItem = vertexKeys[i]; - - size_t lastItemEnd = lastItem.first + (lastItem.second.size() * 16); - bool lastItemIntersects = lastItemEnd >= curItem.first; - - if (lastItemIntersects) - { - int intersectedVtxStart = (lastItemEnd - curItem.first) / 16; - - for (size_t j = intersectedVtxStart; j < curItem.second.size(); j++) - vertices[lastItem.first].push_back(curItem.second[j]); - - vertices.erase(curItem.first); - vertexKeys.erase(vertexKeys.begin() + i); - - lastItem.second = vertices[lastItem.first]; - - i--; - } - else - lastItem = curItem; - } - } -} - -void ZDisplayList::TextureGenCheck() -{ - if (TextureGenCheck(lastTexWidth, lastTexHeight, lastTexAddr, lastTexSeg, lastTexFmt, - lastTexSiz, lastTexLoaded, lastTexIsPalette, this)) - { - lastTexAddr = 0; - lastTexLoaded = false; - lastTexIsPalette = false; - } -} - -bool ZDisplayList::TextureGenCheck(int32_t texWidth, int32_t texHeight, uint32_t texAddr, - uint32_t texSeg, F3DZEXTexFormats texFmt, F3DZEXTexSizes texSiz, - bool texLoaded, bool texIsPalette, ZDisplayList* self) -{ - uint32_t segmentNumber = GETSEGNUM(texSeg); - - if (!texIsPalette) - self->lastTexture = nullptr; - else - self->lastTlut = nullptr; - - if (Globals::Instance->verbosity >= VerbosityLevel::VERBOSITY_DEBUG) - printf("TextureGenCheck seg=%i width=%i height=%i ispal=%i addr=0x%06X\n", segmentNumber, - texWidth, texHeight, texIsPalette, texAddr); - - if ((texSeg != 0 || texAddr != 0) && texWidth > 0 && texHeight > 0 && texLoaded && - Globals::Instance->HasSegment(segmentNumber)) - { - ZFile* auxParent = nullptr; - if (segmentNumber == self->parent->segment) - { - auxParent = self->parent; - } - else - { - // Try to find a non-external file (i.e., one we are actually extracting) - // which has the same segment number we are looking for. - for (auto& otherFile : Globals::Instance->cfg.segmentRefFiles[segmentNumber]) - { - if (!otherFile->isExternalFile) - { - auxParent = otherFile; - } - } - } - - if (auxParent == nullptr) - { - // We can't declare the texture in any of the files we are extracting. - return false; - } - - if (auxParent->IsOffsetInFileRange(texAddr)) - { - ZTexture* tex = auxParent->GetTextureResource(texAddr); - if (tex != nullptr) - tex->isPalette = texIsPalette; - else - { - tex = new ZTexture(auxParent); - tex->ExtractFromBinary(texAddr, texWidth, texHeight, - TexFormatToTexType(texFmt, texSiz), texIsPalette); - auxParent->AddTextureResource(texAddr, tex); - } - - if (!texIsPalette) - self->lastTexture = tex; - else - self->lastTlut = tex; - - if (auxParent->GetDeclaration(texAddr) == nullptr) - { - tex->DeclareVar(self->GetName(), ""); - } - - return true; - } - } - - return false; -} - -TextureType ZDisplayList::TexFormatToTexType(F3DZEXTexFormats fmt, F3DZEXTexSizes siz) -{ - if (fmt == F3DZEXTexFormats::G_IM_FMT_RGBA) - { - if (siz == F3DZEXTexSizes::G_IM_SIZ_16b) - return TextureType::RGBA16bpp; - else if (siz == F3DZEXTexSizes::G_IM_SIZ_32b) - return TextureType::RGBA32bpp; - } - else if (fmt == F3DZEXTexFormats::G_IM_FMT_CI) - { - if (Globals::Instance->useLegacyZDList) - return TextureType::Palette8bpp; - else - { - if (siz == F3DZEXTexSizes::G_IM_SIZ_4b) - return TextureType::Palette4bpp; - else if (siz == F3DZEXTexSizes::G_IM_SIZ_8b) - return TextureType::Palette8bpp; - } - } - else if (fmt == F3DZEXTexFormats::G_IM_FMT_IA) - { - if (siz == F3DZEXTexSizes::G_IM_SIZ_4b) - return TextureType::GrayscaleAlpha4bpp; - else if (siz == F3DZEXTexSizes::G_IM_SIZ_8b) - return TextureType::GrayscaleAlpha8bpp; - else if (siz == F3DZEXTexSizes::G_IM_SIZ_16b) - return TextureType::GrayscaleAlpha16bpp; - } - else if (fmt == F3DZEXTexFormats::G_IM_FMT_I) - { - if (siz == F3DZEXTexSizes::G_IM_SIZ_4b) - return TextureType::Grayscale4bpp; - else if (siz == F3DZEXTexSizes::G_IM_SIZ_8b) - return TextureType::Grayscale8bpp; - else if (siz == F3DZEXTexSizes::G_IM_SIZ_16b) - return TextureType::Grayscale8bpp; - } - - return TextureType::RGBA16bpp; -} - -bool ZDisplayList::IsExternalResource() const -{ - return false; -} - -std::string ZDisplayList::GetExternalExtension() const -{ - return "dlist"; -} - -std::string ZDisplayList::GetSourceTypeName() const -{ - return "Gfx"; -} - -ZResourceType ZDisplayList::GetResourceType() const -{ - return ZResourceType::DisplayList; -} - -size_t ZDisplayList::GetRawDataSize() const -{ - return instructions.size() * 8; -} - -DeclarationAlignment ZDisplayList::GetDeclarationAlignment() const -{ - return DeclarationAlignment::Align8; -} diff --git a/tools/ZAPD/ZAPD/ZDisplayList.h b/tools/ZAPD/ZAPD/ZDisplayList.h deleted file mode 100644 index 356e89a2be..0000000000 --- a/tools/ZAPD/ZAPD/ZDisplayList.h +++ /dev/null @@ -1,381 +0,0 @@ -#pragma once - -#include "ZMtx.h" -#include "ZResource.h" -#include "ZRoom/ZRoom.h" -#include "ZTexture.h" -#include "ZVtx.h" -#include "tinyxml2.h" - -#include -#include -#include - -enum class F3DEXOpcode -{ - G_SPNOOP = 0x00, - G_MTX = 0x01, - G_MOVEMEM = 0x03, - G_VTX = 0x04, - G_DL = 0x06, - G_LOAD_UCODE = 0xAF, - G_BRANCH_Z = 0xB0, - G_TRI2 = 0xB1, - G_MODIFYVTX = 0xB2, - G_RDPHALF_2 = 0xB3, - G_RDPHALF_1 = 0xB4, - G_QUAD = 0xB5, - G_CLEARGEOMETRYMODE = 0xB6, - G_SETGEOMETRYMODE = 0xB7, - G_ENDDL = 0xB8, - G_SETOTHERMODE_L = 0xB9, - G_SETOTHERMODE_H = 0xBA, - G_TEXTURE = 0xBB, - G_MOVEWORD = 0xBC, - G_POPMTX = 0xBD, - G_CULLDL = 0xBE, - G_TRI1 = 0xBF, - G_NOOP = 0xC0, - G_TEXRECT = 0xE4, - G_TEXRECTFLIP = 0xE5, - G_RDPLOADSYNC = 0xE6, - G_RDPPIPESYNC = 0xE7, - G_RDPTILESYNC = 0xE8, - G_RDPFULLSYNC = 0xE9, - G_SETKEYGB = 0xEA, - G_SETKEYR = 0xEB, - G_SETCONVERT = 0xEC, - G_SETSCISSOR = 0xED, - G_SETPRIMDEPTH = 0xEE, - G_RDPSETOTHERMODE = 0xEF, - G_LOADTLUT = 0xF0, - G_SETTILESIZE = 0xF2, - G_LOADBLOCK = 0xF3, - G_LOADTILE = 0xF4, - G_SETTILE = 0xF5, - G_FILLRECT = 0xF6, - G_SETFILLCOLOR = 0xF7, - G_SETFOGCOLOR = 0xF8, - G_SETBLENDCOLOR = 0xF9, - G_SETPRIMCOLOR = 0xFA, - G_SETENVCOLOR = 0xFB, - G_SETCOMBINE = 0xFC, - G_SETTIMG = 0xFD, - G_SETZIMG = 0xFE, - G_SETCIMG = 0xFF -}; - -enum class F3DZEXOpcode -{ - G_NOOP = 0x00, - G_VTX = 0x01, - G_MODIFYVTX = 0x02, - G_CULLDL = 0x03, - G_BRANCH_Z = 0x04, - G_TRI1 = 0x05, - G_TRI2 = 0x06, - G_QUAD = 0x07, - G_SPECIAL_3 = 0xD3, - G_SPECIAL_2 = 0xD4, - G_SPECIAL_1 = 0xD5, - G_DMA_IO = 0xD6, - G_TEXTURE = 0xD7, - G_POPMTX = 0xD8, - G_GEOMETRYMODE = 0xD9, - G_MTX = 0xDA, - G_MOVEWORD = 0xDB, - G_MOVEMEM = 0xDC, - G_LOAD_UCODE = 0xDD, - G_DL = 0xDE, - G_ENDDL = 0xDF, - G_SPNOOP = 0xE0, - G_RDPHALF_1 = 0xE1, - G_SETOTHERMODE_L = 0xE2, - G_SETOTHERMODE_H = 0xE3, - G_TEXRECT = 0xE4, - G_TEXRECTFLIP = 0xE5, - G_RDPLOADSYNC = 0xE6, - G_RDPPIPESYNC = 0xE7, - G_RDPTILESYNC = 0xE8, - G_RDPFULLSYNC = 0xE9, - G_SETKEYGB = 0xEA, - G_SETKEYR = 0xEB, - G_SETCONVERT = 0xEC, - G_SETSCISSOR = 0xED, - G_SETPRIMDEPTH = 0xEE, - G_RDPSETOTHERMODE = 0xEF, - G_LOADTLUT = 0xF0, - G_RDPHALF_2 = 0xF1, - G_SETTILESIZE = 0xF2, - G_LOADBLOCK = 0xF3, - G_LOADTILE = 0xF4, - G_SETTILE = 0xF5, - G_FILLRECT = 0xF6, - G_SETFILLCOLOR = 0xF7, - G_SETFOGCOLOR = 0xF8, - G_SETBLENDCOLOR = 0xF9, - G_SETPRIMCOLOR = 0xFA, - G_SETENVCOLOR = 0xFB, - G_SETCOMBINE = 0xFC, - G_SETTIMG = 0xFD, - G_SETZIMG = 0xFE, - G_SETCIMG = 0xFF, -}; - -enum class F3DZEXTexFormats -{ - G_IM_FMT_RGBA, - G_IM_FMT_YUV, - G_IM_FMT_CI, - G_IM_FMT_IA, - G_IM_FMT_I -}; - -enum class F3DZEXTexSizes -{ - G_IM_SIZ_4b, - G_IM_SIZ_8b, - G_IM_SIZ_16b, - G_IM_SIZ_32b -}; - -enum class DListType -{ - F3DZEX, - F3DEX, -}; - -enum class OoTSegments -{ - DirectReference = 0, - TitleStatic = 1, - Scene = 2, - Room = 3, - GameplayKeep = 4, - FieldDungeonKeep = 5, - Object = 6, - LinkAnimation = 7, - IconItemStatic = 8, - IconItem24Static = 9, - Unknown10 = 10, - Unknown11 = 11, - Unknown12 = 12, - IconFieldDungeonStatic = 13, - IconItemLanguageStatic = 14, - ZBuffer = 15, - FrameBuffer = 16, -}; - -#define G_MDSFT_ALPHACOMPARE 0 -#define G_MDSFT_ZSRCSEL 2 -#define G_MDSFT_RENDERMODE 3 -#define G_MDSFT_BLENDER 16 - -#define G_RM_FOG_SHADE_A 0xC8000000 -#define G_RM_FOG_PRIM_A 0xC4000000 -#define G_RM_PASS 0x0C080000 -#define G_RM_AA_ZB_OPA_SURF 0x442078 -#define G_RM_AA_ZB_OPA_SURF2 0x112078 -#define G_RM_AA_ZB_XLU_SURF 0x4049D8 -#define G_RM_AA_ZB_XLU_SURF2 0x1049D8 -#define G_RM_AA_ZB_OPA_DECAL 0x442D58 -#define G_RM_AA_ZB_OPA_DECAL2 0x112D58 -#define G_RM_AA_ZB_XLU_DECAL 0x404DD8 -#define G_RM_AA_ZB_XLU_DECAL2 0x104DD8 -#define G_RM_AA_ZB_OPA_INTER 0x442478 -#define G_RM_AA_ZB_OPA_INTER2 0x112478 -#define G_RM_AA_ZB_XLU_INTER 0x4045D8 -#define G_RM_AA_ZB_XLU_INTER2 0x1045D8 -#define G_RM_AA_ZB_XLU_LINE 0x407858 -#define G_RM_AA_ZB_XLU_LINE2 0x107858 -#define G_RM_AA_ZB_DEC_LINE 0x407F58 -#define G_RM_AA_ZB_DEC_LINE2 0x107F58 -#define G_RM_AA_ZB_TEX_EDGE 0x443078 -#define G_RM_AA_ZB_TEX_EDGE2 0x113078 -#define G_RM_AA_ZB_TEX_INTER 0x443478 -#define G_RM_AA_ZB_TEX_INTER2 0x113478 -#define G_RM_AA_ZB_SUB_SURF 0x442878 -#define G_RM_AA_ZB_SUB_SURF2 0x112278 -#define G_RM_AA_ZB_PCL_SURF 0x40007B -#define G_RM_AA_ZB_PCL_SURF2 0x10007B -#define G_RM_AA_ZB_OPA_TERR 0x402078 -#define G_RM_AA_ZB_OPA_TERR2 0x102078 -#define G_RM_AA_ZB_TEX_TERR 0x403078 -#define G_RM_AA_ZB_TEX_TERR2 0x103078 -#define G_RM_AA_ZB_SUB_TERR 0x402278 -#define G_RM_AA_ZB_SUB_TERR2 0x102278 -#define G_RM_RA_ZB_OPA_SURF 0x442038 -#define G_RM_RA_ZB_OPA_SURF2 0x112038 -#define G_RM_RA_ZB_OPA_DECAL 0x442D18 -#define G_RM_RA_ZB_OPA_DECAL2 0x112D18 -#define G_RM_RA_ZB_OPA_INTER 0x442438 -#define G_RM_RA_ZB_OPA_INTER2 0x112438 -#define G_RM_AA_OPA_SURF 0x442048 -#define G_RM_AA_OPA_SURF2 0x112048 -#define G_RM_AA_XLU_SURF 0x4041C8 -#define G_RM_AA_XLU_SURF2 0x1041C8 -#define G_RM_AA_XLU_LINE 0x407048 -#define G_RM_AA_XLU_LINE2 0x107048 -#define G_RM_AA_DEC_LINE 0x407248 -#define G_RM_AA_DEC_LINE2 0x107248 -#define G_RM_AA_TEX_EDGE 0x443048 -#define G_RM_AA_TEX_EDGE2 0x113048 -#define G_RM_AA_SUB_SURF 0x442248 -#define G_RM_AA_SUB_SURF2 0x112248 -#define G_RM_AA_PCL_SURF 0x40004B -#define G_RM_AA_PCL_SURF2 0x10004B -#define G_RM_AA_OPA_TERR 0x402048 -#define G_RM_AA_OPA_TERR2 0x102048 -#define G_RM_AA_TEX_TERR 0x403048 -#define G_RM_AA_TEX_TERR2 0x103048 -#define G_RM_AA_SUB_TERR 0x402248 -#define G_RM_AA_SUB_TERR2 0x102248 -#define G_RM_RA_OPA_SURF 0x442008 -#define G_RM_RA_OPA_SURF2 0x112008 -#define G_RM_ZB_OPA_SURF 0x442230 -#define G_RM_ZB_OPA_SURF2 0x112230 -#define G_RM_ZB_XLU_SURF 0x404A50 -#define G_RM_ZB_XLU_SURF2 0x104A50 -#define G_RM_ZB_OPA_DECAL 0x442E10 -#define G_RM_ZB_OPA_DECAL2 0x112E10 -#define G_RM_ZB_XLU_DECAL 0x404E50 -#define G_RM_ZB_XLU_DECAL2 0x104E50 -#define G_RM_ZB_CLD_SURF 0x404B50 -#define G_RM_ZB_CLD_SURF2 0x104B50 -#define G_RM_ZB_OVL_SURF 0x404F50 -#define G_RM_ZB_OVL_SURF2 0x104F50 -#define G_RM_ZB_PCL_SURF 0x0C080233 -#define G_RM_ZB_PCL_SURF2 0x03020233 -#define G_RM_OPA_SURF 0x0C084000 -#define G_RM_OPA_SURF2 0x03024000 -#define G_RM_XLU_SURF 0x00404200 -#define G_RM_XLU_SURF2 0x00104240 -#define G_RM_CLD_SURF 0x00404340 -#define G_RM_CLD_SURF2 0x00104340 -#define G_RM_TEX_EDGE 0x0C087008 -#define G_RM_TEX_EDGE2 0x03027008 -#define G_RM_PCL_SURF 0x0C084203 -#define G_RM_PCL_SURF2 0x03024203 -#define G_RM_ADD 0x04484340 -#define G_RM_ADD2 0x01124340 -#define G_RM_NOOP 0x00000000 -#define G_RM_NOOP2 0x00000000 -#define G_RM_VISCVG 0x0C844040 -#define G_RM_VISCVG2 0x03214040 -#define G_RM_OPA_CI 0x0C080000 -#define G_RM_OPA_CI2 0x03020000 - -#define AA_EN 0x8 -#define Z_CMP 0x10 -#define Z_UPD 0x20 -#define IM_RD 0x40 -#define CLR_ON_CVG 0x80 -#define CVG_DST_CLAMP 0 -#define CVG_DST_WRAP 0x100 -#define CVG_DST_FULL 0x200 -#define CVG_DST_SAVE 0x300 -#define ZMODE_OPA 0 -#define ZMODE_INTER 0x400 -#define ZMODE_XLU 0x800 -#define ZMODE_DEC 0xc00 -#define CVG_X_ALPHA 0x1000 -#define ALPHA_CVG_SEL 0x2000 -#define FORCE_BL 0x4000 -#define TEX_EDGE 0x0000 - -class ZDisplayList : public ZResource -{ -protected: - static TextureType TexFormatToTexType(F3DZEXTexFormats fmt, F3DZEXTexSizes siz); - - void ParseF3DZEX(F3DZEXOpcode opcode, uint64_t data, int32_t i, const std::string& prefix, - char* line); - void ParseF3DEX(F3DEXOpcode opcode, uint64_t data, const std::string& prefix, char* line); - - // Various Instruction Optimizations - bool SequenceCheck(std::vector sequence, int32_t startIndex); - int32_t OptimizationChecks(int32_t startIndex, std::string& output, const std::string& prefix); - int32_t OptimizationCheck_LoadTextureBlock(int32_t startIndex, std::string& output, - const std::string& prefix); - // int32_t OptimizationCheck_LoadMultiBlock(int32_t startIndex, std::string& output, std::string - // prefix); - - // F3DEX Specific Opcode Values - void Opcode_F3DEX_G_SETOTHERMODE_L(uint64_t data, char* line); - - // Shared Opcodes between F3DZEX and F3DEX - void Opcode_G_DL(uint64_t data, const std::string& prefix, char* line); - void Opcode_G_MODIFYVTX(uint64_t data, char* line); - void Opcode_G_CULLDL(uint64_t data, char* line); - void Opcode_G_TRI1(uint64_t data, char* line); - void Opcode_G_TRI2(uint64_t data, char* line); - void Opcode_G_MTX(uint64_t data, char* line); - void Opcode_G_VTX(uint64_t data, char* line); - void Opcode_G_TEXTURE(uint64_t data, char* line); - void Opcode_G_SETTIMG(uint64_t data, const std::string& prefix, char* line); - void Opcode_G_SETTILE(uint64_t data, char* line); - void Opcode_G_SETTILESIZE(uint64_t data, const std::string& prefix, char* line); - void Opcode_G_LOADBLOCK(uint64_t data, char* line); - void Opcode_G_SETCOMBINE(uint64_t data, char* line); - void Opcode_G_SETPRIMCOLOR(uint64_t data, char* line); - void Opcode_G_SETOTHERMODE_L(uint64_t data, char* line); - void Opcode_G_SETOTHERMODE_H(uint64_t data, char* line); - void Opcode_G_LOADTLUT(uint64_t data, const std::string& prefix, char* line); - void Opcode_G_ENDDL(const std::string& prefix, char* line); - -public: - std::vector instructions; - - int32_t lastTexWidth, lastTexHeight, lastTexAddr, lastTexSeg; - F3DZEXTexFormats lastTexFmt; - F3DZEXTexSizes lastTexSiz, lastTexSizTest, lastCISiz; - bool lastTexLoaded; - bool lastTexIsPalette; - - DListType dListType; - - std::map> vertices; - std::vector otherDLists; - - ZTexture* lastTexture = nullptr; - ZTexture* lastTlut = nullptr; - - std::vector references; - std::vector mtxList; - - ZDisplayList(ZFile* nParent); - ~ZDisplayList(); - - void ExtractWithXML(tinyxml2::XMLElement* reader, uint32_t nRawDataIndex) override; - void ExtractFromBinary(uint32_t nRawDataIndex, int32_t rawDataSize); - - void ParseRawData() override; - - Declaration* DeclareVar(const std::string& prefix, const std::string& bodyStr) override; - std::string GetDefaultName(const std::string& prefix) const override; - - void TextureGenCheck(); - static bool TextureGenCheck(int32_t texWidth, int32_t texHeight, uint32_t texAddr, - uint32_t texSeg, F3DZEXTexFormats texFmt, F3DZEXTexSizes texSiz, - bool texLoaded, bool texIsPalette, ZDisplayList* self); - static int32_t GetDListLength(const std::vector& rawData, uint32_t rawDataIndex, - DListType dListType); - - size_t GetRawDataSize() const override; - DeclarationAlignment GetDeclarationAlignment() const override; - void DeclareReferences(const std::string& prefix) override; - std::string ProcessLegacy(const std::string& prefix); - std::string ProcessGfxDis(const std::string& prefix); - - // Combines vertex lists from the vertices map which touch or intersect - void MergeConnectingVertexLists(); - - bool IsExternalResource() const override; - std::string GetExternalExtension() const override; - std::string GetSourceTypeName() const override; - - ZResourceType GetResourceType() const override; - -protected: - size_t numInstructions; -}; diff --git a/tools/ZAPD/ZAPD/ZFile.cpp b/tools/ZAPD/ZAPD/ZFile.cpp deleted file mode 100644 index 281e6132f7..0000000000 --- a/tools/ZAPD/ZAPD/ZFile.cpp +++ /dev/null @@ -1,1433 +0,0 @@ -#include "ZFile.h" - -#include -#include -#include -#include - -#include "Globals.h" -#include "OutputFormatter.h" -#include "Utils/BinaryWriter.h" -#include "Utils/BitConverter.h" -#include "Utils/Directory.h" -#include "Utils/File.h" -#include "Utils/MemoryStream.h" -#include "Utils/Path.h" -#include "Utils/StringHelper.h" -#include "WarningHandler.h" -#include "ZAnimation.h" -#include "ZArray.h" -#include "ZBackground.h" -#include "ZBlob.h" -#include "ZCollision.h" -#include "ZCutscene.h" -#include "ZDisplayList.h" -#include "ZLimb.h" -#include "ZMtx.h" -#include "ZRoom/ZRoom.h" -#include "ZScalar.h" -#include "ZSkeleton.h" -#include "ZSymbol.h" -#include "ZTexture.h" -#include "ZVector.h" -#include "ZVtx.h" - -ZFile::ZFile() -{ - resources = std::vector(); - basePath = ""; - declarations = std::map(); - defines = ""; - baseAddress = 0; - rangeStart = 0x000000000; - rangeEnd = 0xFFFFFFFF; -} - -ZFile::ZFile(const fs::path& nOutPath, const std::string& nName) : ZFile() -{ - name = nName; - outName = nName; - outputPath = nOutPath; -} - -ZFile::ZFile(ZFileMode nMode, tinyxml2::XMLElement* reader, const fs::path& nBasePath, - const fs::path& nOutPath, const std::string& filename, const fs::path& nXmlFilePath) - : ZFile() -{ - xmlFilePath = nXmlFilePath; - if (nBasePath == "") - basePath = Directory::GetCurrentDirectory(); - else - basePath = nBasePath; - - if (nOutPath == "") - outputPath = Directory::GetCurrentDirectory(); - else - outputPath = nOutPath; - - mode = nMode; - - ParseXML(reader, filename); - if (mode != ZFileMode::ExternalFile) - DeclareResourceSubReferences(); -} - -ZFile::~ZFile() -{ - for (ZResource* res : resources) - delete res; - - for (auto d : declarations) - delete d.second; - - for (auto sym : symbolResources) - delete sym.second; -} - -void ZFile::ParseXML(tinyxml2::XMLElement* reader, const std::string& filename) -{ - assert(mode != ZFileMode::Invalid); - - if (filename == "") - name = reader->Attribute("Name"); - else - name = filename; - - outName = name; - const char* outNameXml = reader->Attribute("OutName"); - if (outNameXml != nullptr) - outName = outNameXml; - - // TODO: This should be a variable on the ZFile, but it is a large change in order to force all - // ZResource types to have a parent ZFile. - const char* gameStr = reader->Attribute("Game"); - if (reader->Attribute("Game") != nullptr) - { - if (std::string_view(gameStr) == "MM") - Globals::Instance->game = ZGame::MM_RETAIL; - else if (std::string_view(gameStr) == "SW97" || std::string_view(gameStr) == "OOTSW97") - Globals::Instance->game = ZGame::OOT_SW97; - else if (std::string_view(gameStr) == "OOT") - Globals::Instance->game = ZGame::OOT_RETAIL; - else - { - std::string errorHeader = - StringHelper::Sprintf("'Game' type '%s' is not supported.", gameStr); - HANDLE_ERROR_PROCESS(WarningType::InvalidAttributeValue, errorHeader, ""); - } - } - - if (reader->Attribute("BaseAddress") != nullptr) - baseAddress = StringHelper::StrToL(reader->Attribute("BaseAddress"), 16); - - if (mode == ZFileMode::Extract && Globals::Instance->baseAddress != -1) - baseAddress = Globals::Instance->baseAddress; - - if (reader->Attribute("RangeStart") != nullptr) - rangeStart = StringHelper::StrToL(reader->Attribute("RangeStart"), 16); - - if (reader->Attribute("RangeEnd") != nullptr) - rangeEnd = StringHelper::StrToL(reader->Attribute("RangeEnd"), 16); - - if (rangeStart > rangeEnd) - HANDLE_ERROR_PROCESS( - WarningType::Always, - StringHelper::Sprintf("'RangeStart' 0x%06X must be before 'RangeEnd' 0x%06X", - rangeStart, rangeEnd), - ""); - - const char* segmentXml = reader->Attribute("Segment"); - if (segmentXml != nullptr) - { - if (!StringHelper::HasOnlyDigits(segmentXml)) - { - HANDLE_ERROR_PROCESS(WarningType::Always, - StringHelper::Sprintf("error: Invalid segment value '%s': must be " - "a decimal between 0 and 15 inclusive", - segmentXml), - ""); - } - - segment = StringHelper::StrToL(segmentXml, 10); - if (segment > 15) - { - if (segment == 128) - { -#ifdef DEPRECATION_ON - HANDLE_WARNING_PROCESS( - WarningType::Always, "warning: segment 128 is deprecated.", - "Remove 'Segment=\"128\"' from the xml to use virtual addresses\n"); -#endif - } - else - { - HANDLE_ERROR_PROCESS( - WarningType::Always, - StringHelper::Sprintf("error: invalid segment value '%s': must be a decimal " - "number between 0 and 15 inclusive", - segmentXml), - ""); - } - } - } - Globals::Instance->AddSegment(segment, this); - - if (Globals::Instance->verbosity >= VerbosityLevel::VERBOSITY_INFO) - { - if (segment == 0x80) - { - printf("File '%s' using virtual addresses.\n", GetName().c_str()); - } - else - { - printf("File '%s' using segment %X.\n", GetName().c_str(), segment); - } - } - - const char* segmentDefines = reader->Attribute("Defines"); - if (segmentDefines != NULL) - { - makeDefines = true; - } - - if (mode == ZFileMode::Extract || mode == ZFileMode::ExternalFile) - { - if (!File::Exists((basePath / name).string())) - { - std::string errorHeader = StringHelper::Sprintf("binary file '%s' does not exist.", - (basePath / name).c_str()); - HANDLE_ERROR_PROCESS(WarningType::Always, errorHeader, ""); - } - - rawData = File::ReadAllBytes((basePath / name).string()); - if (mode == ZFileMode::Extract && Globals::Instance->startOffset != -1 && Globals::Instance->endOffset != -1) - rawData = std::vector(rawData.begin() + Globals::Instance->startOffset, - rawData.begin() + Globals::Instance->endOffset); - - if (reader->Attribute("RangeEnd") == nullptr) - rangeEnd = rawData.size(); - } - - std::unordered_set nameSet; - std::unordered_set outNameSet; - std::unordered_set offsetSet; - - auto nodeMap = *GetNodeMap(); - uint32_t rawDataIndex = 0; - - for (tinyxml2::XMLElement* child = reader->FirstChildElement(); child != nullptr; - child = child->NextSiblingElement()) - { - const char* nameXml = child->Attribute("Name"); - const char* outNameXml = child->Attribute("OutName"); - const char* offsetXml = child->Attribute("Offset"); - - // Check for repeated attributes. - if (offsetXml != nullptr) - { - if (!StringHelper::IsValidOffset(std::string_view(offsetXml))) - { - HANDLE_ERROR(WarningType::InvalidXML, - StringHelper::Sprintf("Invalid offset %s entered", offsetXml), ""); - } - rawDataIndex = strtol(offsetXml, NULL, 16); - - if (offsetSet.find(offsetXml) != offsetSet.end()) - { - std::string errorHeader = - StringHelper::Sprintf("repeated 'Offset' attribute: %s", offsetXml); - HANDLE_ERROR_PROCESS(WarningType::InvalidXML, errorHeader, ""); - } - offsetSet.insert(offsetXml); - } - else - { - HANDLE_WARNING_RESOURCE(WarningType::MissingOffsets, this, nullptr, rawDataIndex, - StringHelper::Sprintf("no offset specified for %s.", nameXml), - ""); - } - - if (Globals::Instance->verbosity >= VerbosityLevel::VERBOSITY_INFO) - printf("%s: 0x%06X\n", nameXml, rawDataIndex); - - if (outNameXml != nullptr) - { - if (outNameSet.find(outNameXml) != outNameSet.end()) - { - std::string errorHeader = - StringHelper::Sprintf("repeated 'OutName' attribute: %s", outNameXml); - HANDLE_ERROR_PROCESS(WarningType::InvalidXML, errorHeader, ""); - } - outNameSet.insert(outNameXml); - } - if (nameXml != nullptr) - { - if (nameSet.find(nameXml) != nameSet.end()) - { - std::string errorHeader = - StringHelper::Sprintf("repeated 'Name' attribute: %s", nameXml); - HANDLE_ERROR_PROCESS(WarningType::InvalidXML, errorHeader, ""); - } - nameSet.insert(nameXml); - } - - std::string nodeName = std::string(child->Name()); - - if (nodeMap.find(nodeName) != nodeMap.end()) - { - ZResource* nRes = nodeMap[nodeName](this); - - if (mode == ZFileMode::Extract || mode == ZFileMode::ExternalFile) - nRes->ExtractWithXML(child, rawDataIndex); - - switch (nRes->GetResourceType()) - { - case ZResourceType::Texture: - AddTextureResource(rawDataIndex, static_cast(nRes)); - break; - - case ZResourceType::Symbol: - AddSymbolResource(rawDataIndex, static_cast(nRes)); - break; - - default: - AddResource(nRes); - break; - } - - rawDataIndex += nRes->GetRawDataSize(); - } - else if (std::string_view(child->Name()) == "File") - { - std::string errorHeader = "Can't declare a inside a "; - HANDLE_ERROR_PROCESS(WarningType::InvalidXML, errorHeader, ""); - } - else - { - std::string errorHeader = StringHelper::Sprintf( - "Unknown element found inside a element: %s", nodeName.c_str()); - HANDLE_ERROR_PROCESS(WarningType::InvalidXML, errorHeader, ""); - } - } -} - -void ZFile::DeclareResourceSubReferences() -{ - for (size_t i = 0; i < resources.size(); i++) - { - resources.at(i)->DeclareReferences(name); - } -} - -void ZFile::BuildSourceFile() -{ - if (mode == ZFileMode::ExternalFile) - return; - - if (!Directory::Exists(outputPath)) - Directory::CreateDirectory(outputPath.string()); - - GenerateSourceFiles(); -} - -std::string ZFile::GetName() const -{ - return name; -} - -std::string ZFile::GetOutName() const -{ - return outName.string(); -} - -ZFileMode ZFile::GetMode() const -{ - return mode; -} - -const fs::path& ZFile::GetXmlFilePath() const -{ - return xmlFilePath; -} - -const std::vector& ZFile::GetRawData() const -{ - return rawData; -} - -void ZFile::ExtractResources() -{ - if (mode == ZFileMode::ExternalFile) - return; - - if (!Directory::Exists(outputPath)) - Directory::CreateDirectory(outputPath.string()); - - if (!Directory::Exists(GetSourceOutputFolderPath())) - Directory::CreateDirectory(GetSourceOutputFolderPath().string()); - - for (size_t i = 0; i < resources.size(); i++) - resources[i]->ParseRawDataLate(); - for (size_t i = 0; i < resources.size(); i++) - resources[i]->DeclareReferencesLate(name); - - if (Globals::Instance->genSourceFile) - GenerateSourceFiles(); - - auto memStreamFile = std::shared_ptr(new MemoryStream()); - BinaryWriter writerFile = BinaryWriter(memStreamFile); - - ExporterSet* exporterSet = Globals::Instance->GetExporterSet(); - - if (exporterSet != nullptr && exporterSet->beginFileFunc != nullptr) - exporterSet->beginFileFunc(this); - - for (ZResource* res : resources) - { - auto memStreamRes = std::shared_ptr(new MemoryStream()); - BinaryWriter writerRes = BinaryWriter(memStreamRes); - - if (Globals::Instance->verbosity >= VerbosityLevel::VERBOSITY_INFO) - printf("Saving resource %s\n", res->GetName().c_str()); - - res->Save(outputPath); - - // Check if we have an exporter "registered" for this resource type - ZResourceExporter* exporter = Globals::Instance->GetExporter(res->GetResourceType()); - if (exporter != nullptr) - { - // exporter->Save(res, Globals::Instance->outputPath.string(), &writerFile); - exporter->Save(res, Globals::Instance->outputPath.string(), &writerRes); - } - - if (exporterSet != nullptr && exporterSet->resSaveFunc != nullptr) - exporterSet->resSaveFunc(res, writerRes); - } - - if (memStreamFile->GetLength() > 0) - { - File::WriteAllBytes(StringHelper::Sprintf("%s%s.bin", - Globals::Instance->outputPath.string().c_str(), - GetName().c_str()), - memStreamFile->ToVector()); - } - - writerFile.Close(); - - if (exporterSet != nullptr && exporterSet->endFileFunc != nullptr) - exporterSet->endFileFunc(this); -} - -void ZFile::AddResource(ZResource* res) -{ - resources.push_back(res); -} - -ZResource* ZFile::FindResource(offset_t rawDataIndex) -{ - for (ZResource* res : resources) - { - if (res->GetRawDataIndex() == rawDataIndex) - return res; - } - - return nullptr; -} - -std::vector ZFile::GetResourcesOfType(ZResourceType resType) -{ - std::vector resList; - resList.reserve(resources.size()); - - for (ZResource* res : resources) - { - if (res->GetResourceType() == resType) - resList.push_back(res); - } - - return resList; -} - -Declaration* ZFile::AddDeclaration(offset_t address, DeclarationAlignment alignment, size_t size, - const std::string& varType, const std::string& varName, - const std::string& body) -{ - bool validOffset = DeclarationSanityChecks(address, varName); - if (!validOffset) - return nullptr; - - Declaration* decl = GetDeclaration(address); - if (decl == nullptr) - { - decl = Declaration::Create(address, alignment, size, varType, varName, body); - declarations[address] = decl; - } - else - { - decl->alignment = alignment; - decl->size = size; - decl->declType = varType; - decl->declName = varName; - decl->declBody = body; - } - - return decl; -} - -Declaration* ZFile::AddDeclarationArray(offset_t address, DeclarationAlignment alignment, - size_t size, const std::string& varType, - const std::string& varName, size_t arrayItemCnt, - const std::string& body) -{ - bool validOffset = DeclarationSanityChecks(address, varName); - if (!validOffset) - return nullptr; - - Declaration* decl = GetDeclaration(address); - if (decl == nullptr) - { - decl = Declaration::CreateArray(address, alignment, size, varType, varName, body, - arrayItemCnt); - - declarations[address] = decl; - } - else - { - if (decl->isPlaceholder) - decl->declName = varName; - - decl->alignment = alignment; - decl->size = size; - decl->declType = varType; - decl->isArray = true; - decl->arrayItemCnt = arrayItemCnt; - decl->declBody = body; - } - - return decl; -} - -Declaration* ZFile::AddDeclarationArray(offset_t address, DeclarationAlignment alignment, - size_t size, const std::string& varType, - const std::string& varName, - const std::string& arrayItemCntStr, const std::string& body) -{ - bool validOffset = DeclarationSanityChecks(address, varName); - if (!validOffset) - return nullptr; - - Declaration* decl = GetDeclaration(address); - if (decl == nullptr) - { - decl = Declaration::CreateArray(address, alignment, size, varType, varName, body, - arrayItemCntStr); - - declarations[address] = decl; - } - else - { - decl->alignment = alignment; - decl->size = size; - decl->declType = varType; - decl->declName = varName; - decl->isArray = true; - decl->arrayItemCntStr = arrayItemCntStr; - decl->declBody = body; - } - return decl; -} - -Declaration* ZFile::AddDeclarationPlaceholder(offset_t address, const std::string& varName) -{ - bool validOffset = DeclarationSanityChecks(address, varName); - if (!validOffset) - return nullptr; - - Declaration* decl; - if (declarations.find(address) == declarations.end()) - { - decl = Declaration::CreatePlaceholder(address, varName); - declarations[address] = decl; - } - else - decl = declarations[address]; - - return decl; -} - -Declaration* ZFile::AddDeclarationInclude(offset_t address, const std::string& includePath, - size_t size, const std::string& varType, - const std::string& varName) -{ - bool validOffset = DeclarationSanityChecks(address, varName); - if (!validOffset) - return nullptr; - - Declaration* decl = GetDeclaration(address); - if (decl == nullptr) - { - decl = Declaration::CreateInclude(address, includePath, size, varType, varName); - declarations[address] = decl; - } - else - { - decl->includePath = includePath; - decl->size = size; - decl->declType = varType; - decl->declName = varName; - } - return decl; -} - -Declaration* ZFile::AddDeclarationIncludeArray(offset_t address, std::string& includePath, - size_t size, const std::string& varType, - const std::string& varName, size_t arrayItemCnt) -{ - bool validOffset = DeclarationSanityChecks(address, varName); - if (!validOffset) - return nullptr; - - if (StringHelper::StartsWith(includePath, "assets/extracted/")) - includePath = "assets/" + StringHelper::Split(includePath, "assets/extracted/")[1]; - if (StringHelper::StartsWith(includePath, "assets/custom/")) - includePath = "assets/" + StringHelper::Split(includePath, "assets/custom/")[1]; - // Hack for OOT: don't prefix include paths with extracted/VERSION/ - if (StringHelper::StartsWith(includePath, "extracted/")) { - std::vector parts = StringHelper::Split(includePath, "/"); - parts.erase(parts.begin(), parts.begin() + 2); - includePath = StringHelper::Join(parts, "/"); - } - - Declaration* decl = GetDeclaration(address); - if (decl == nullptr) - { - decl = Declaration::CreateInclude(address, includePath, size, varType, varName); - - decl->isArray = true; - decl->arrayItemCnt = arrayItemCnt; - - declarations[address] = decl; - } - else - { - decl->includePath = includePath; - decl->declType = varType; - decl->declName = varName; - decl->size = size; - decl->isArray = true; - decl->arrayItemCnt = arrayItemCnt; - } - return decl; -} - -Declaration* ZFile::AddDeclarationIncludeArray(offset_t address, std::string& includePath, - size_t size, const std::string& varType, - const std::string& varName, - const std::string& defines, size_t arrayItemCnt) -{ - bool validOffset = DeclarationSanityChecks(address, varName); - if (!validOffset) - return nullptr; - - if (StringHelper::StartsWith(includePath, "assets/extracted/")) - includePath = "assets/" + StringHelper::Split(includePath, "assets/extracted/")[1]; - if (StringHelper::StartsWith(includePath, "assets/custom/")) - includePath = "assets/" + StringHelper::Split(includePath, "assets/custom/")[1]; - // Hack for OOT: don't prefix include paths with extracted/VERSION/ - if (StringHelper::StartsWith(includePath, "extracted/")) { - std::vector parts = StringHelper::Split(includePath, "/"); - parts.erase(parts.begin(), parts.begin() + 2); - includePath = StringHelper::Join(parts, "/"); - } - - Declaration* decl = GetDeclaration(address); - if (decl == nullptr) - { - decl = Declaration::CreateInclude(address, includePath, size, varType, varName, defines); - - decl->isArray = true; - decl->arrayItemCnt = arrayItemCnt; - - declarations[address] = decl; - } - else - { - decl->includePath = includePath; - decl->declType = varType; - decl->declName = varName; - decl->defines = defines; - decl->size = size; - decl->isArray = true; - decl->arrayItemCnt = arrayItemCnt; - } - return decl; -} - -bool ZFile::DeclarationSanityChecks(uint32_t address, const std::string& varName) -{ - assert(GETSEGNUM(address) == 0); - assert(varName != ""); -#ifdef DEVELOPMENT - if (address == 0x0000) - { - [[maybe_unused]] int32_t bp = 0; - } -#endif - - if (!IsOffsetInFileRange(address)) - { - fprintf(stderr, - "%s: Warning in %s\n" - "\t Tried to declare a variable outside of this file's range. Ignoring...\n" - "\t\t Variable's name: %s\n" - "\t\t Variable's offset: 0x%06X\n", - __PRETTY_FUNCTION__, name.c_str(), varName.c_str(), address); - return false; - } - - return true; -} - -bool ZFile::GetDeclarationPtrName(segptr_t segAddress, const std::string& expectedType, - std::string& declName) const -{ - if (segAddress == 0) - { - declName = "NULL"; - return true; - } - - uint32_t offset = Seg2Filespace(segAddress, baseAddress); - Declaration* decl = GetDeclaration(offset); - if (GETSEGNUM(segAddress) != segment || decl == nullptr) - { - declName = StringHelper::Sprintf("0x%08X", segAddress); - return false; - } - - if (expectedType != "" && expectedType != "void*") - { - if (expectedType != decl->declType && "static " + expectedType != decl->declType) - { - declName = StringHelper::Sprintf("0x%08X", segAddress); - return false; - } - } - - if (!decl->isArray) - declName = "&" + decl->declName; - else - declName = decl->declName; - return true; -} - -bool ZFile::GetDeclarationArrayIndexedName(segptr_t segAddress, size_t elementSize, - const std::string& expectedType, - std::string& declName) const -{ - if (segAddress == 0) - { - declName = "NULL"; - return true; - } - - uint32_t address = Seg2Filespace(segAddress, baseAddress); - Declaration* decl = GetDeclarationRanged(address); - if (GETSEGNUM(segAddress) != segment || decl == nullptr || !decl->isArray) - { - declName = StringHelper::Sprintf("0x%08X", segAddress); - return false; - } - - if (expectedType != "" && expectedType != "void*") - { - if (expectedType != decl->declType && "static " + expectedType != decl->declType) - { - declName = StringHelper::Sprintf("0x%08X", segAddress); - return false; - } - } - - if (decl->address == address) - { - declName = decl->declName; - return true; - } - - if ((address - decl->address) % elementSize != 0 || !(address < decl->address + decl->size)) - { - declName = StringHelper::Sprintf("0x%08X", segAddress); - return false; - } - - uint32_t index = (address - decl->address) / elementSize; - declName = StringHelper::Sprintf("&%s[%u]", decl->declName.c_str(), index); - return true; -} - -Declaration* ZFile::GetDeclaration(offset_t address) const -{ - if (declarations.find(address) != declarations.end()) - return declarations.at(address); - - return nullptr; -} - -Declaration* ZFile::GetDeclarationRanged(offset_t address) const -{ - for (const auto decl : declarations) - { - if (address >= decl.first && address < decl.first + decl.second->size) - return decl.second; - } - - return nullptr; -} - -bool ZFile::HasDeclaration(offset_t address) -{ - assert(GETSEGNUM(address) == 0); - return declarations.find(address) != declarations.end(); -} - -size_t ZFile::GetDeclarationSizeFromNeighbor(uint32_t declarationAddress) -{ - auto currentDecl = declarations.find(declarationAddress); - if (currentDecl == declarations.end()) - return 0; - - auto nextDecl = currentDecl; - std::advance(nextDecl, 1); - if (nextDecl == declarations.end()) - return GetRawData().size() - currentDecl->first; - - return nextDecl->first - currentDecl->first; -} - -void ZFile::GenerateSourceFiles() -{ - std::string sourceOutput; - - sourceOutput += "#include \"ultra64.h\"\n"; - sourceOutput += "#include \"z64.h\"\n"; - sourceOutput += GetHeaderInclude(); - - bool hasZRoom = false; - for (const auto& res : resources) - { - ZResourceType resType = res->GetResourceType(); - if (resType == ZResourceType::Room || resType == ZResourceType::Scene || - resType == ZResourceType::AltHeader) - { - hasZRoom = true; - break; - } - } - - if (hasZRoom) - { - sourceOutput += GetZRoomHeaderInclude(); - } - - sourceOutput += GetExternalFileHeaderInclude(); - - GeneratePlaceholderDeclarations(); - - // Generate Code - for (size_t i = 0; i < resources.size(); i++) - { - ZResource* res = resources.at(i); - res->GetSourceOutputCode(name); - } - - sourceOutput += ProcessDeclarations(); - - fs::path outPath = GetSourceOutputFolderPath() / outName.stem().concat(".c"); - - if (Globals::Instance->verbosity >= VerbosityLevel::VERBOSITY_INFO) - printf("Writing C file: %s\n", outPath.c_str()); - - OutputFormatter formatter; - formatter.Write(sourceOutput); - - File::WriteAllText(outPath, formatter.GetOutput()); - - GenerateSourceHeaderFiles(); -} - -void ZFile::GenerateSourceHeaderFiles() -{ - OutputFormatter formatter; - - std::string guard = StringHelper::ToUpper(outName.stem().string()); - - formatter.Write( - StringHelper::Sprintf("#ifndef %s_H\n#define %s_H 1\n\n", guard.c_str(), guard.c_str())); - - for (ZResource* res : resources) - { - std::string resSrc = res->GetSourceOutputHeader(""); - formatter.Write(resSrc); - - if (resSrc != "") - formatter.Write("\n"); - } - - for (auto& sym : symbolResources) - { - formatter.Write(sym.second->GetSourceOutputHeader("")); - } - - formatter.Write(ProcessExterns()); - - formatter.Write("#endif\n"); - - fs::path headerFilename = GetSourceOutputFolderPath() / outName.stem().concat(".h"); - - if (Globals::Instance->verbosity >= VerbosityLevel::VERBOSITY_INFO) - printf("Writing H file: %s\n", headerFilename.c_str()); - - File::WriteAllText(headerFilename, formatter.GetOutput()); -} - -std::string ZFile::GetHeaderInclude() const -{ - std::string headers = StringHelper::Sprintf( - "#include \"%s.h\"\n", (outName.parent_path() / outName.stem()).string().c_str()); - - return headers; -} - -std::string ZFile::GetZRoomHeaderInclude() const -{ - std::string headers; - headers += "#include \"segment_symbols.h\"\n"; - headers += "#include \"command_macros_base.h\"\n"; - headers += "#include \"z64cutscene_commands.h\"\n"; - /* headers += "#include \"variables.h\"\n"; */ - return headers; -} - -std::string ZFile::GetExternalFileHeaderInclude() const -{ - std::string externalFilesIncludes = ""; - - for (ZFile* externalFile : Globals::Instance->files) - { - if (externalFile != this) - { - fs::path outputFolderPath = externalFile->GetSourceOutputFolderPath(); - if (outputFolderPath == this->GetSourceOutputFolderPath()) - outputFolderPath = externalFile->outName.stem(); - else - outputFolderPath /= externalFile->outName.stem(); - - externalFilesIncludes += - StringHelper::Sprintf("#include \"%s.h\"\n", outputFolderPath.string().c_str()); - } - } - - return externalFilesIncludes; -} - -void ZFile::GeneratePlaceholderDeclarations() -{ - // Generate placeholder declarations - for (ZResource* res : resources) - { - if (GetDeclaration(res->GetRawDataIndex()) != nullptr) - { - continue; - } - - Declaration* decl = res->DeclareVar(GetName(), ""); - decl->staticConf = res->GetStaticConf(); - if (res->GetResourceType() == ZResourceType::Symbol) - { - decl->staticConf = StaticConfig::Off; - } - } -} - -void ZFile::AddTextureResource(uint32_t offset, ZTexture* tex) -{ - for (auto res : resources) - assert(res->GetRawDataIndex() != offset); - - resources.push_back(tex); - texturesResources[offset] = tex; -} - -ZTexture* ZFile::GetTextureResource(uint32_t offset) const -{ - auto tex = texturesResources.find(offset); - if (tex != texturesResources.end()) - return tex->second; - - return nullptr; -} - -void ZFile::AddSymbolResource(uint32_t offset, ZSymbol* sym) -{ - symbolResources[offset] = sym; -} - -ZSymbol* ZFile::GetSymbolResource(uint32_t offset) const -{ - auto sym = symbolResources.find(offset); - if (sym != symbolResources.end()) - return sym->second; - - return nullptr; -} - -ZSymbol* ZFile::GetSymbolResourceRanged(uint32_t offset) const -{ - for (const auto decl : symbolResources) - { - if (offset >= decl.first && offset < decl.first + decl.second->GetRawDataSize()) - return decl.second; - } - - return nullptr; -} - -fs::path ZFile::GetSourceOutputFolderPath() const -{ - return outputPath / outName.parent_path(); -} - -bool ZFile::IsOffsetInFileRange(uint32_t offset) const -{ - if (!(offset < rawData.size())) - return false; - - return rangeStart <= offset && offset < rangeEnd; -} -bool ZFile::IsSegmentedInFilespaceRange(segptr_t segAddress) const -{ - uint8_t segnum = GETSEGNUM(segAddress); - uint32_t offset = Seg2Filespace(segAddress, baseAddress); - - if (segment != segnum) - return false; - - return IsOffsetInFileRange(offset); -} - -std::map* ZFile::GetNodeMap() -{ - static std::map nodeMap; - return &nodeMap; -} - -void ZFile::RegisterNode(std::string nodeName, ZResourceFactoryFunc* nodeFunc) -{ - std::map* nodeMap = GetNodeMap(); - (*nodeMap)[nodeName] = nodeFunc; -} - -std::string ZFile::ProcessDeclarations() -{ - std::string output; - - if (declarations.size() == 0) - return output; - - defines += ProcessTextureIntersections(name); - - // printf("RANGE START: 0x%06X - RANGE END: 0x%06X\n", rangeStart, rangeEnd); - - MergeNeighboringDeclarations(); - - for (std::pair item : declarations) - ProcessDeclarationText(item.second); - - for (std::pair item : declarations) - { - while (item.second->size % 4 != 0) - item.second->size++; - } - - HandleUnaccountedData(); - - // Go through include declarations - // First, handle the prototypes (static only for now) - for (std::pair item : declarations) - { - output += item.second->GetStaticForwardDeclarationStr(); - } - - output += "\n"; - - // Next, output the actual declarations - for (const auto& item : declarations) - { - if (!IsOffsetInFileRange(item.first)) - continue; - - if (item.second->includePath != "") - { - if (item.second->isExternal) - { - // HACK - std::string extType; - - if (item.second->declType == "Gfx") - extType = "dlist"; - else if (item.second->declType == "Vtx") - extType = "vtx"; - - auto filepath = outputPath / item.second->declName; - File::WriteAllText( - StringHelper::Sprintf("%s.%s.inc", filepath.string().c_str(), extType.c_str()), - item.second->declBody); - } - - output += item.second->GetExternalDeclarationStr(); - } - else if (item.second->declType != "") - { - output += item.second->GetNormalDeclarationStr(); - } - } - - return output; -} - -void ZFile::MergeNeighboringDeclarations() -{ - // Optimization: See if there are any arrays side by side that can be merged... - std::vector> declarationKeys(declarations.begin(), - declarations.end()); - - std::pair lastItem = declarationKeys.at(0); - - for (size_t i = 1; i < declarationKeys.size(); i++) - { - std::pair curItem = declarationKeys[i]; - - if (curItem.second->isArray && lastItem.second->isArray) - { - if (curItem.second->declType == lastItem.second->declType) - { - if (!curItem.second->declaredInXml && !lastItem.second->declaredInXml) - { - // TEST: For now just do Vtx declarations... - if (lastItem.second->declType == "Vtx") - { - int32_t sizeDiff = curItem.first - (lastItem.first + lastItem.second->size); - - // Make sure there isn't an unaccounted inbetween these two - if (sizeDiff == 0) - { - lastItem.second->size += curItem.second->size; - lastItem.second->arrayItemCnt += curItem.second->arrayItemCnt; - lastItem.second->declBody += "\n" + curItem.second->declBody; - declarations.erase(curItem.first); - declarationKeys.erase(declarationKeys.begin() + i); - delete curItem.second; - i--; - continue; - } - } - } - } - } - - lastItem = curItem; - } -} - -void ZFile::ProcessDeclarationText(Declaration* decl) -{ - size_t refIndex = 0; - - if (!(decl->references.size() > 0)) - return; - - for (size_t i = 0; i < decl->declBody.size() - 1; i++) - { - char c = decl->declBody[i]; - char c2 = decl->declBody[i + 1]; - - if (c == '@' && c2 == 'r') - { - std::string vtxName; - Globals::Instance->GetSegmentedArrayIndexedName(decl->references[refIndex], 0x10, this, - "Vtx", vtxName); - decl->declBody.replace(i, 2, vtxName); - - refIndex++; - - if (refIndex >= decl->references.size()) - break; - } - } -} - -std::string ZFile::ProcessExterns() -{ - std::string output = ""; - bool hadDefines = true; // Previous declaration included defines. - - for (const auto& item : declarations) - { - if (!IsOffsetInFileRange(item.first)) - { - continue; - } - - std::string itemDefines = item.second->GetDefinesStr(); - // Add a newline above if previous has no defines and this one does. - if (!hadDefines && (itemDefines.length() > 0)) - { - output.push_back('\n'); - } - output += item.second->GetExternStr(); - output += itemDefines; - - // Newline below if this one has defines. - if ((hadDefines = (itemDefines.length() > 0))) - { - output.push_back('\n'); - } - } - - output += defines; - - return output; -} - -std::string ZFile::ProcessTextureIntersections([[maybe_unused]] const std::string& prefix) -{ - if (texturesResources.empty()) - return ""; - - std::string defines; - std::vector> texturesSorted(texturesResources.begin(), - texturesResources.end()); - - for (size_t i = 0; i < texturesSorted.size() - 1; i++) - { - uint32_t currentOffset = texturesSorted[i].first; - uint32_t nextOffset = texturesSorted[i + 1].first; - auto& currentTex = texturesResources.at(currentOffset); - int texSize = currentTex->GetRawDataSize(); - - if (currentTex->WasDeclaredInXml()) - { - // We believe the user is right. - continue; - } - - if ((currentOffset + texSize) > nextOffset) - { - uint32_t offsetDiff = nextOffset - currentOffset; - if (currentTex->isPalette) - { - // Shrink palette so it doesn't overlap - currentTex->SetDimensions(offsetDiff / currentTex->GetPixelMultiplyer(), 1); - declarations.at(currentOffset)->size = currentTex->GetRawDataSize(); - currentTex->DeclareVar(GetName(), ""); - } - else - { - std::string texName; - std::string texNextName; - GetDeclarationPtrName(currentOffset, "", texName); - - Declaration* nextDecl = GetDeclaration(nextOffset); - if (nextDecl == nullptr) - texNextName = texturesResources.at(nextOffset)->GetName(); - else - texNextName = nextDecl->declName; - - defines += StringHelper::Sprintf("#define %s ((u32)%s + 0x%06X)\n", - texNextName.c_str(), texName.c_str(), offsetDiff); - - delete declarations[nextOffset]; - declarations.erase(nextOffset); - texturesResources.erase(nextOffset); - texturesSorted.erase(texturesSorted.begin() + i + 1); - - i--; - } - } - } - - return defines; -} - -void ZFile::HandleUnaccountedData() -{ - uint32_t lastAddr = 0; - uint32_t lastSize = 0; - std::vector declsAddresses; - - declsAddresses.reserve(declarations.size()); - for (const auto& item : declarations) - { - declsAddresses.push_back(item.first); - } - - bool breakLoop = false; - for (offset_t currentAddress : declsAddresses) - { - if (currentAddress >= rangeEnd) - { - breakLoop = true; - break; - } - - if (currentAddress < rangeStart) - { - lastAddr = currentAddress; - continue; - } - - breakLoop = HandleUnaccountedAddress(currentAddress, lastAddr, lastSize); - if (breakLoop) - break; - - lastAddr = currentAddress; - } - - if (!breakLoop) - { - // TODO: change rawData.size() to rangeEnd - // HandleUnaccountedAddress(rangeEnd, lastAddr, lastSize); - HandleUnaccountedAddress(rawData.size(), lastAddr, lastSize); - } -} - -bool ZFile::HandleUnaccountedAddress(offset_t currentAddress, offset_t lastAddr, uint32_t& lastSize) -{ - if (currentAddress != lastAddr && declarations.find(lastAddr) != declarations.end()) - { - Declaration* lastDecl = declarations.at(lastAddr); - lastSize = lastDecl->size; - - if (lastAddr + lastSize > currentAddress) - { - Declaration* currentDecl = declarations.at(currentAddress); - - std::string intersectionInfo = StringHelper::Sprintf( - "Resource from 0x%06X:0x%06X (%s) conflicts with 0x%06X (%s).", lastAddr, - lastAddr + lastSize, lastDecl->declName.c_str(), currentAddress, - currentDecl->declName.c_str()); - HANDLE_WARNING_RESOURCE(WarningType::Intersection, this, nullptr, currentAddress, - "intersection detected", intersectionInfo); - } - } - - uint32_t unaccountedAddress = lastAddr + lastSize; - - if (unaccountedAddress != currentAddress && lastAddr >= rangeStart && - unaccountedAddress < rangeEnd) - { - int diff = currentAddress - unaccountedAddress; - bool nonZeroUnaccounted = false; - - std::string src = " "; - - if (currentAddress > rawData.size()) - { - throw std::runtime_error(StringHelper::Sprintf( - "ZFile::ProcessDeclarations(): Fatal error while processing XML '%s'.\n" - "\t Offset '0x%X' is outside of the limits of file '%s', which has a size of " - "'0x%X'.\n" - "\t Aborting...", - xmlFilePath.c_str(), currentAddress, name.c_str(), rawData.size())); - } - - // Handle Align8 - if (currentAddress % 8 == 0 && diff % 8 != 0) - { - Declaration* currentDecl = GetDeclaration(currentAddress); - - if (currentDecl != nullptr) - { - if (currentDecl->alignment == DeclarationAlignment::Align8) - { - // Check removed bytes are zeroes - if (BitConverter::ToUInt32BE(rawData, unaccountedAddress + diff - 4) == 0) - { - diff -= 4; - } - } - - if (diff == 0) - { - return false; - } - } - } - - for (int i = 0; i < diff; i++) - { - uint8_t val = rawData.at(unaccountedAddress + i); - src += StringHelper::Sprintf("0x%02X, ", val); - if (val != 0x00) - { - nonZeroUnaccounted = true; - } - - if (Globals::Instance->verboseUnaccounted) - { - if ((i % 4 == 3)) - { - src += StringHelper::Sprintf(" // 0x%06X", unaccountedAddress + i - 3); - if (i != (diff - 1)) - { - src += "\n\t"; - } - } - } - else - { - if ((i % 16 == 15) && (i != (diff - 1))) - src += "\n "; - } - } - - if (declarations.find(unaccountedAddress) == declarations.end() && diff > 0) - { - std::string unaccountedPrefix = "unaccounted"; - - if (diff < 16 && !nonZeroUnaccounted) - { - unaccountedPrefix = "possiblePadding"; - - // Strip unnecessary padding at the end of the file. - if (unaccountedAddress + diff >= rawData.size()) - return true; - } - - Declaration* decl = AddDeclarationArray( - unaccountedAddress, DeclarationAlignment::Align4, diff, "u8", - StringHelper::Sprintf("%s_%s_%06X", name.c_str(), unaccountedPrefix.c_str(), - unaccountedAddress), - diff, src); - - decl->isUnaccounted = true; - if (Globals::Instance->forceUnaccountedStatic) - decl->staticConf = StaticConfig::On; - - if (nonZeroUnaccounted) - { - HANDLE_WARNING_RESOURCE(WarningType::Unaccounted, this, nullptr, unaccountedAddress, - "a non-zero unaccounted block was found", - StringHelper::Sprintf("Block size: '0x%X'", diff)); - } - else if (diff >= 16) - { - HANDLE_WARNING_RESOURCE(WarningType::Unaccounted, this, nullptr, unaccountedAddress, - "a big (size>=0x10) zero-only unaccounted block was found", - StringHelper::Sprintf("Block size: '0x%X'", diff)); - } - } - } - - return false; -} diff --git a/tools/ZAPD/ZAPD/ZFile.h b/tools/ZAPD/ZAPD/ZFile.h deleted file mode 100644 index 65b1cc4aa3..0000000000 --- a/tools/ZAPD/ZAPD/ZFile.h +++ /dev/null @@ -1,144 +0,0 @@ -#pragma once - -#include -#include - -#include "ZSymbol.h" -#include "ZTexture.h" -#include "tinyxml2.h" - -enum class ZFileMode -{ - BuildTexture, - BuildOverlay, - BuildBlob, - BuildSourceFile, - BuildBackground, - Extract, - ExternalFile, - Invalid, - Custom = 1000, // Used for exporter file modes -}; - -enum class ZGame -{ - OOT_RETAIL, - OOT_SW97, - MM_RETAIL -}; - -class ZFile -{ -public: - std::map declarations; - std::vector resources; - std::string defines; - - // Default to using virtual addresses - uint32_t segment = 0x80; - uint32_t baseAddress, rangeStart, rangeEnd; - bool isExternalFile = false; - // Whether to make defines for texture dimensions, and possibly more in future - bool makeDefines = false; - - ZFile(const fs::path& nOutPath, const std::string& nName); - ZFile(ZFileMode nMode, tinyxml2::XMLElement* reader, const fs::path& nBasePath, - const fs::path& nOutPath, const std::string& filename, const fs::path& nXmlFilePath); - ~ZFile(); - - std::string GetName() const; - std::string GetOutName() const; - ZFileMode GetMode() const; - const fs::path& GetXmlFilePath() const; - const std::vector& GetRawData() const; - void ExtractResources(); - void BuildSourceFile(); - void AddResource(ZResource* res); - ZResource* FindResource(offset_t rawDataIndex); - std::vector GetResourcesOfType(ZResourceType resType); - - Declaration* AddDeclaration(offset_t address, DeclarationAlignment alignment, size_t size, - const std::string& varType, const std::string& varName, - const std::string& body); - - Declaration* AddDeclarationArray(offset_t address, DeclarationAlignment alignment, size_t size, - const std::string& varType, const std::string& varName, - size_t arrayItemCnt, const std::string& body); - Declaration* AddDeclarationArray(offset_t address, DeclarationAlignment alignment, size_t size, - const std::string& varType, const std::string& varName, - const std::string& arrayItemCntStr, const std::string& body); - - Declaration* AddDeclarationPlaceholder(offset_t address, const std::string& varName); - - Declaration* AddDeclarationInclude(offset_t address, const std::string& includePath, - size_t size, const std::string& varType, - const std::string& varName); - Declaration* AddDeclarationIncludeArray(offset_t address, std::string& includePath, size_t size, - const std::string& varType, const std::string& varName, - size_t arrayItemCnt); - Declaration* AddDeclarationIncludeArray(offset_t address, std::string& includePath, size_t size, - const std::string& varType, const std::string& varName, - const std::string& defines, size_t arrayItemCnt); - - bool GetDeclarationPtrName(segptr_t segAddress, const std::string& expectedType, - std::string& declName) const; - bool GetDeclarationArrayIndexedName(segptr_t segAddress, size_t elementSize, - const std::string& expectedType, - std::string& declName) const; - - Declaration* GetDeclaration(offset_t address) const; - Declaration* GetDeclarationRanged(offset_t address) const; - bool HasDeclaration(offset_t address); - size_t GetDeclarationSizeFromNeighbor(uint32_t declarationAddress); - - std::string GetHeaderInclude() const; - std::string GetZRoomHeaderInclude() const; - std::string GetExternalFileHeaderInclude() const; - - void GeneratePlaceholderDeclarations(); - - void AddTextureResource(uint32_t offset, ZTexture* tex); - ZTexture* GetTextureResource(uint32_t offset) const; - - void AddSymbolResource(uint32_t offset, ZSymbol* sym); - ZSymbol* GetSymbolResource(uint32_t offset) const; - ZSymbol* GetSymbolResourceRanged(uint32_t offset) const; - - fs::path GetSourceOutputFolderPath() const; - - bool IsOffsetInFileRange(uint32_t offset) const; - bool IsSegmentedInFilespaceRange(segptr_t segAddress) const; - - static std::map* GetNodeMap(); - static void RegisterNode(std::string nodeName, ZResourceFactoryFunc* nodeFunc); - -protected: - std::vector rawData; - std::string name; - fs::path outName = ""; - fs::path basePath; - fs::path outputPath; - fs::path xmlFilePath; - - // Keep track of every texture of this ZFile. - // The pointers declared here are "borrowed" (somebody else is the owner), - // so ZFile shouldn't delete/free those textures. - std::map texturesResources; - std::map symbolResources; - ZFileMode mode = ZFileMode::Invalid; - - ZFile(); - void ParseXML(tinyxml2::XMLElement* reader, const std::string& filename); - void DeclareResourceSubReferences(); - void GenerateSourceFiles(); - void GenerateSourceHeaderFiles(); - bool DeclarationSanityChecks(uint32_t address, const std::string& varName); - std::string ProcessDeclarations(); - void MergeNeighboringDeclarations(); - void ProcessDeclarationText(Declaration* decl); - std::string ProcessExterns(); - - std::string ProcessTextureIntersections(const std::string& prefix); - void HandleUnaccountedData(); - bool HandleUnaccountedAddress(offset_t currentAddress, offset_t lastAddr, uint32_t& lastSize); -}; diff --git a/tools/ZAPD/ZAPD/ZLimb.cpp b/tools/ZAPD/ZAPD/ZLimb.cpp deleted file mode 100644 index b3acb940c1..0000000000 --- a/tools/ZAPD/ZAPD/ZLimb.cpp +++ /dev/null @@ -1,412 +0,0 @@ -#include "ZLimb.h" - -#include - -#include "Globals.h" -#include "Utils/BitConverter.h" -#include "Utils/StringHelper.h" -#include "WarningHandler.h" -#include "ZSkeleton.h" - -REGISTER_ZFILENODE(Limb, ZLimb); - -ZLimb::ZLimb(ZFile* nParent) : ZResource(nParent), segmentStruct(nParent) -{ - RegisterOptionalAttribute("EnumName"); - RegisterOptionalAttribute("LimbType"); - RegisterOptionalAttribute("Type"); -} - -void ZLimb::ExtractFromBinary(uint32_t nRawDataIndex, ZLimbType nType) -{ - rawDataIndex = nRawDataIndex; - type = nType; - - // Don't parse raw data of external files - if (parent->GetMode() == ZFileMode::ExternalFile) - return; - - ParseRawData(); -} - -void ZLimb::ParseXML(tinyxml2::XMLElement* reader) -{ - ZResource::ParseXML(reader); - - auto& enumNameXml = registeredAttributes.at("EnumName").value; - if (enumNameXml != "") - { - enumName = enumNameXml; - } - - // Reading from a - std::string limbType = registeredAttributes.at("LimbType").value; - if (limbType == "") // Reading from a - limbType = registeredAttributes.at("Type").value; - - if (limbType == "") - { - HANDLE_ERROR_RESOURCE(WarningType::MissingAttribute, parent, this, rawDataIndex, - "missing 'LimbType' attribute in ", ""); - } - - type = GetTypeByAttributeName(limbType); - if (type == ZLimbType::Invalid) - { - HANDLE_ERROR_RESOURCE(WarningType::InvalidAttributeValue, parent, this, rawDataIndex, - "invalid value found for 'LimbType' attribute", ""); - } -} - -void ZLimb::ParseRawData() -{ - ZResource::ParseRawData(); - const auto& rawData = parent->GetRawData(); - - if (type == ZLimbType::Curve) - { - childIndex = BitConverter::ToUInt8BE(rawData, rawDataIndex + 0); - siblingIndex = BitConverter::ToUInt8BE(rawData, rawDataIndex + 1); - - dListPtr = BitConverter::ToUInt32BE(rawData, rawDataIndex + 4); - dList2Ptr = BitConverter::ToUInt32BE(rawData, rawDataIndex + 8); - return; - } - if (type == ZLimbType::Legacy) - { - dListPtr = BitConverter::ToUInt32BE(rawData, rawDataIndex + 0x00); - legTransX = BitConverter::ToFloatBE(rawData, rawDataIndex + 0x04); - legTransY = BitConverter::ToFloatBE(rawData, rawDataIndex + 0x08); - legTransZ = BitConverter::ToFloatBE(rawData, rawDataIndex + 0x0C); - rotX = BitConverter::ToUInt16BE(rawData, rawDataIndex + 0x10); - rotY = BitConverter::ToUInt16BE(rawData, rawDataIndex + 0x12); - rotZ = BitConverter::ToUInt16BE(rawData, rawDataIndex + 0x14); - childPtr = BitConverter::ToUInt32BE(rawData, rawDataIndex + 0x18); - siblingPtr = BitConverter::ToUInt32BE(rawData, rawDataIndex + 0x1C); - return; - } - - transX = BitConverter::ToInt16BE(rawData, rawDataIndex + 0); - transY = BitConverter::ToInt16BE(rawData, rawDataIndex + 2); - transZ = BitConverter::ToInt16BE(rawData, rawDataIndex + 4); - - childIndex = rawData.at(rawDataIndex + 6); - siblingIndex = rawData.at(rawDataIndex + 7); - - switch (type) - { - case ZLimbType::LOD: - dList2Ptr = BitConverter::ToUInt32BE(rawData, rawDataIndex + 12); - [[fallthrough]]; - case ZLimbType::Standard: - dListPtr = BitConverter::ToUInt32BE(rawData, rawDataIndex + 8); - break; - - case ZLimbType::Skin: - skinSegmentType = - static_cast(BitConverter::ToInt32BE(rawData, rawDataIndex + 8)); - skinSegment = BitConverter::ToUInt32BE(rawData, rawDataIndex + 12); - if (skinSegmentType == ZLimbSkinType::SkinType_Animated) - { - if (skinSegment != 0 && GETSEGNUM(skinSegment) == parent->segment) - { - uint32_t skinSegmentOffset = Seg2Filespace(skinSegment, parent->baseAddress); - segmentStruct.ExtractFromFile(skinSegmentOffset); - } - } - break; - - case ZLimbType::Curve: - case ZLimbType::Legacy: - break; - - case ZLimbType::Invalid: - assert(!"whoops"); - break; - } -} - -void ZLimb::DeclareReferences(const std::string& prefix) -{ - std::string varPrefix = name; - if (varPrefix == "") - varPrefix = prefix; - - ZResource::DeclareReferences(varPrefix); - - std::string suffix; - switch (type) - { - case ZLimbType::Legacy: - if (childPtr != 0 && GETSEGNUM(childPtr) == parent->segment) - { - uint32_t childOffset = Seg2Filespace(childPtr, parent->baseAddress); - if (!parent->HasDeclaration(childOffset)) - { - ZLimb* child = new ZLimb(parent); - child->ExtractFromBinary(childOffset, ZLimbType::Legacy); - child->DeclareVar(varPrefix, ""); - child->DeclareReferences(varPrefix); - parent->AddResource(child); - } - } - if (siblingPtr != 0 && GETSEGNUM(siblingPtr) == parent->segment) - { - uint32_t siblingdOffset = Seg2Filespace(siblingPtr, parent->baseAddress); - if (!parent->HasDeclaration(siblingdOffset)) - { - ZLimb* sibling = new ZLimb(parent); - sibling->ExtractFromBinary(siblingdOffset, ZLimbType::Legacy); - sibling->DeclareVar(varPrefix, ""); - sibling->DeclareReferences(varPrefix); - parent->AddResource(sibling); - } - } - break; - - case ZLimbType::Curve: - case ZLimbType::LOD: - suffix = "Far"; - if (type == ZLimbType::Curve) - suffix = "Curve2"; - DeclareDList(dList2Ptr, varPrefix, suffix); - [[fallthrough]]; - case ZLimbType::Standard: - suffix = ""; - if (type == ZLimbType::Curve) - suffix = "Curve"; - DeclareDList(dListPtr, varPrefix, suffix); - break; - - case ZLimbType::Skin: - switch (skinSegmentType) - { - case ZLimbSkinType::SkinType_Animated: - if (skinSegment != 0 && GETSEGNUM(skinSegment) == parent->segment) - { - segmentStruct.DeclareReferences(varPrefix); - segmentStruct.GetSourceOutputCode(varPrefix); - } - break; - - case ZLimbSkinType::SkinType_Normal: - DeclareDList(skinSegment, varPrefix, ""); - break; - - default: - break; - } - break; - - case ZLimbType::Invalid: - break; - } -} - -size_t ZLimb::GetRawDataSize() const -{ - switch (type) - { - case ZLimbType::Standard: - case ZLimbType::Curve: - return 0x0C; - - case ZLimbType::LOD: - case ZLimbType::Skin: - return 0x10; - - case ZLimbType::Legacy: - return 0x20; - - case ZLimbType::Invalid: - break; - } - - return 0x0C; -} - -std::string ZLimb::GetBodySourceCode() const -{ - std::string dListStr; - std::string dListStr2; - Globals::Instance->GetSegmentedArrayIndexedName(dListPtr, 8, parent, "Gfx", dListStr); - Globals::Instance->GetSegmentedArrayIndexedName(dList2Ptr, 8, parent, "Gfx", dListStr2); - - std::string entryStr = "\n\t"; - if (type == ZLimbType::Legacy) - { - std::string childName; - std::string siblingName; - Globals::Instance->GetSegmentedPtrName(childPtr, parent, "LegacyLimb", childName); - Globals::Instance->GetSegmentedPtrName(siblingPtr, parent, "LegacyLimb", siblingName); - - entryStr += StringHelper::Sprintf("%s,\n", dListStr.c_str()); - entryStr += - StringHelper::Sprintf("\t{ %ff, %ff, %ff },\n", legTransX, legTransY, legTransZ); - entryStr += StringHelper::Sprintf("\t{ 0x%04X, 0x%04X, 0x%04X },\n", rotX, rotY, rotZ); - entryStr += StringHelper::Sprintf("\t%s,\n", childName.c_str()); - entryStr += StringHelper::Sprintf("\t%s\n", siblingName.c_str()); - } - else - { - std::string childStr; - std::string siblingStr; - if (limbsTable != nullptr) - { - childStr = limbsTable->GetLimbEnumName(childIndex); - siblingStr = limbsTable->GetLimbEnumName(siblingIndex); - } - else - { - childStr = StringHelper::Sprintf("0x%02X", childIndex); - siblingStr = StringHelper::Sprintf("0x%02X", siblingIndex); - } - - if (type != ZLimbType::Curve) - { - entryStr += StringHelper::Sprintf("{ %i, %i, %i }, ", transX, transY, transZ); - } - entryStr += StringHelper::Sprintf("%s, %s,\n", childStr.c_str(), siblingStr.c_str()); - - switch (type) - { - case ZLimbType::Standard: - entryStr += StringHelper::Sprintf("\t%s\n", dListStr.c_str()); - break; - - case ZLimbType::LOD: - case ZLimbType::Curve: - entryStr += - StringHelper::Sprintf("\t{ %s, %s }\n", dListStr.c_str(), dListStr2.c_str()); - break; - - case ZLimbType::Skin: - { - std::string skinSegmentStr; - Globals::Instance->GetSegmentedPtrName(skinSegment, parent, "", skinSegmentStr); - entryStr += - StringHelper::Sprintf("\t0x%02X, %s\n", skinSegmentType, skinSegmentStr.c_str()); - } - break; - - case ZLimbType::Legacy: - break; - - case ZLimbType::Invalid: - break; - } - } - - return entryStr; -} - -std::string ZLimb::GetDefaultName(const std::string& prefix) const -{ - return StringHelper::Sprintf("%sLimb_%06X", prefix.c_str(), rawDataIndex); -} - -std::string ZLimb::GetSourceTypeName() const -{ - return GetSourceTypeName(type); -} - -ZResourceType ZLimb::GetResourceType() const -{ - return ZResourceType::Limb; -} - -ZLimbType ZLimb::GetLimbType() -{ - return type; -} - -void ZLimb::SetLimbType(ZLimbType value) -{ - type = value; -} - -const char* ZLimb::GetSourceTypeName(ZLimbType limbType) -{ - switch (limbType) - { - case ZLimbType::Standard: - return "StandardLimb"; - - case ZLimbType::LOD: - return "LodLimb"; - - case ZLimbType::Skin: - return "SkinLimb"; - - case ZLimbType::Curve: - return "SkelCurveLimb"; - - case ZLimbType::Legacy: - return "LegacyLimb"; - - default: - return "StandardLimb"; - } -} - -ZLimbType ZLimb::GetTypeByAttributeName(const std::string& attrName) -{ - if (attrName == "Standard") - { - return ZLimbType::Standard; - } - if (attrName == "LOD") - { - return ZLimbType::LOD; - } - if (attrName == "Skin") - { - return ZLimbType::Skin; - } - if (attrName == "Curve") - { - return ZLimbType::Curve; - } - if (attrName == "Legacy") - { - return ZLimbType::Legacy; - } - return ZLimbType::Invalid; -} - -void ZLimb::SetLimbIndex(uint8_t nLimbIndex) -{ - limbIndex = nLimbIndex; -} - -void ZLimb::DeclareDList(segptr_t dListSegmentedPtr, const std::string& prefix, - const std::string& limbSuffix) -{ - if (dListSegmentedPtr == 0 || GETSEGNUM(dListSegmentedPtr) != parent->segment) - return; - - uint32_t dlistOffset = Seg2Filespace(dListSegmentedPtr, parent->baseAddress); - if (parent->HasDeclaration(dlistOffset)) - return; - - if (!parent->IsOffsetInFileRange(dlistOffset) || dlistOffset >= parent->GetRawData().size()) - return; - - std::string dlistName; - bool declFound = Globals::Instance->GetSegmentedArrayIndexedName(dListSegmentedPtr, 8, parent, - "Gfx", dlistName, false); - if (declFound) - return; - - int32_t dlistLength = ZDisplayList::GetDListLength( - parent->GetRawData(), dlistOffset, - Globals::Instance->game == ZGame::OOT_SW97 ? DListType::F3DEX : DListType::F3DZEX); - ZDisplayList* dlist = new ZDisplayList(parent); - dlist->ExtractFromBinary(dlistOffset, dlistLength); - - std::string dListStr = - StringHelper::Sprintf("%s%sDL_%06X", prefix.c_str(), limbSuffix.c_str(), dlistOffset); - dlist->SetName(dListStr); - dlist->DeclareVar(prefix, ""); - parent->AddResource(dlist); -} diff --git a/tools/ZAPD/ZAPD/ZLimb.h b/tools/ZAPD/ZAPD/ZLimb.h deleted file mode 100644 index 52919bed92..0000000000 --- a/tools/ZAPD/ZAPD/ZLimb.h +++ /dev/null @@ -1,74 +0,0 @@ -#pragma once - -#include -#include -#include - -#include "OtherStructs/SkinLimbStructs.h" -#include "ZDisplayList.h" -#include "ZFile.h" - -enum class ZLimbType -{ - Invalid, - Standard, - LOD, - Skin, - Curve, - Legacy, -}; - -class ZLimbTable; - -class ZLimb : public ZResource -{ -public: - std::string enumName; - ZLimbTable* limbsTable = nullptr; // borrowed pointer, do not delete! - - ZLimbType type = ZLimbType::Standard; - - ZLimbSkinType skinSegmentType = ZLimbSkinType::SkinType_Null; // Skin only - segptr_t skinSegment = 0; // Skin only - SkinAnimatedLimbData segmentStruct; // Skin only - - // Legacy only - float legTransX, legTransY, legTransZ; // Vec3f - uint16_t rotX, rotY, rotZ; // Vec3s - segptr_t childPtr; // LegacyLimb* - segptr_t siblingPtr; // LegacyLimb* - - segptr_t dListPtr = 0; - segptr_t dList2Ptr = 0; // LOD and Curve Only - - int16_t transX, transY, transZ; - uint8_t childIndex, siblingIndex; - - uint8_t limbIndex = 0; - - ZLimb(ZFile* nParent); - - void ExtractFromBinary(uint32_t nRawDataIndex, ZLimbType nType); - - void ParseXML(tinyxml2::XMLElement* reader) override; - void ParseRawData() override; - void DeclareReferences(const std::string& prefix) override; - - std::string GetBodySourceCode() const override; - std::string GetDefaultName(const std::string& prefix) const override; - - size_t GetRawDataSize() const override; - std::string GetSourceTypeName() const override; - ZResourceType GetResourceType() const override; - - ZLimbType GetLimbType(); - void SetLimbType(ZLimbType value); - static const char* GetSourceTypeName(ZLimbType limbType); - static ZLimbType GetTypeByAttributeName(const std::string& attrName); - - void SetLimbIndex(uint8_t nLimbIndex); - -protected: - void DeclareDList(segptr_t dListSegmentedPtr, const std::string& prefix, - const std::string& limbSuffix); -}; diff --git a/tools/ZAPD/ZAPD/ZMtx.cpp b/tools/ZAPD/ZAPD/ZMtx.cpp deleted file mode 100644 index b9ca3f22d2..0000000000 --- a/tools/ZAPD/ZAPD/ZMtx.cpp +++ /dev/null @@ -1,58 +0,0 @@ -#include "ZMtx.h" - -#include "Utils/BitConverter.h" -#include "Utils/StringHelper.h" -#include "ZFile.h" - -REGISTER_ZFILENODE(Mtx, ZMtx); - -ZMtx::ZMtx(ZFile* nParent) : ZResource(nParent) -{ -} - -void ZMtx::ParseRawData() -{ - ZResource::ParseRawData(); - - const auto& rawData = parent->GetRawData(); - for (size_t i = 0; i < 4; ++i) - for (size_t j = 0; j < 4; ++j) - mtx[i][j] = BitConverter::ToInt32BE(rawData, rawDataIndex + (i * 4 + j) * 4); -} - -size_t ZMtx::GetRawDataSize() const -{ - return 64; -} - -std::string ZMtx::GetBodySourceCode() const -{ - std::string bodyStr = "\n"; - - for (const auto& row : mtx) - { - bodyStr += " "; - - for (int32_t val : row) - bodyStr += StringHelper::Sprintf("%-11i, ", val); - - bodyStr += "\n"; - } - - return bodyStr; -} - -std::string ZMtx::GetSourceTypeName() const -{ - return "Mtx"; -} - -ZResourceType ZMtx::GetResourceType() const -{ - return ZResourceType::Mtx; -} - -DeclarationAlignment ZMtx::GetDeclarationAlignment() const -{ - return DeclarationAlignment::Align8; -} diff --git a/tools/ZAPD/ZAPD/ZMtx.h b/tools/ZAPD/ZAPD/ZMtx.h deleted file mode 100644 index eed502374b..0000000000 --- a/tools/ZAPD/ZAPD/ZMtx.h +++ /dev/null @@ -1,24 +0,0 @@ -#pragma once - -#include -#include -#include "ZResource.h" - -class ZMtx : public ZResource -{ -public: - ZMtx(ZFile* nParent); - - void ParseRawData() override; - - std::string GetBodySourceCode() const override; - - std::string GetSourceTypeName() const override; - ZResourceType GetResourceType() const override; - - size_t GetRawDataSize() const override; - DeclarationAlignment GetDeclarationAlignment() const override; - -protected: - std::array, 4> mtx; -}; diff --git a/tools/ZAPD/ZAPD/ZPath.cpp b/tools/ZAPD/ZAPD/ZPath.cpp deleted file mode 100644 index cb8295679f..0000000000 --- a/tools/ZAPD/ZAPD/ZPath.cpp +++ /dev/null @@ -1,218 +0,0 @@ -#include "ZPath.h" - -#include "Globals.h" -#include "Utils/BitConverter.h" -#include "Utils/StringHelper.h" -#include "WarningHandler.h" -#include "ZFile.h" - -REGISTER_ZFILENODE(Path, ZPath); // Old name that is being kept for backwards compatability -REGISTER_ZFILENODE(PathList, ZPath); // New name that may be used in future XMLs - -ZPath::ZPath(ZFile* nParent) : ZResource(nParent) -{ - numPaths = 1; - RegisterOptionalAttribute("NumPaths", "1"); -} - -void ZPath::ParseXML(tinyxml2::XMLElement* reader) -{ - ZResource::ParseXML(reader); - - numPaths = StringHelper::StrToL(registeredAttributes.at("NumPaths").value); - - if (numPaths < 1) - { - HANDLE_ERROR_RESOURCE( - WarningType::InvalidAttributeValue, parent, this, rawDataIndex, - StringHelper::Sprintf("invalid value '%d' found for 'NumPaths' attribute", numPaths), - "Should be at least '1'"); - } -} - -void ZPath::ParseRawData() -{ - ZResource::ParseRawData(); - - uint32_t currentPtr = rawDataIndex; - - pathways.reserve(numPaths); - for (size_t pathIndex = 0; pathIndex < numPaths; pathIndex++) - { - PathwayEntry path(parent); - path.ExtractFromFile(currentPtr); - - if (path.GetListAddress() == 0) - break; - - currentPtr += path.GetRawDataSize(); - pathways.push_back(path); - } -} - -void ZPath::DeclareReferences(const std::string& prefix) -{ - ZResource::DeclareReferences(prefix); - - for (auto& entry : pathways) - entry.DeclareReferences(prefix); -} - -Declaration* ZPath::DeclareVar(const std::string& prefix, const std::string& bodyStr) -{ - std::string auxName = name; - - if (name == "") - auxName = GetDefaultName(prefix); - - Declaration* decl = - parent->AddDeclarationArray(rawDataIndex, GetDeclarationAlignment(), GetRawDataSize(), - GetSourceTypeName(), name, pathways.size(), bodyStr); - decl->staticConf = staticConf; - return decl; -} - -std::string ZPath::GetBodySourceCode() const -{ - std::string declaration; - - size_t index = 0; - for (const auto& entry : pathways) - { - declaration += StringHelper::Sprintf("\t{ %s },", entry.GetBodySourceCode().c_str()); - - if (index < pathways.size() - 1) - declaration += "\n"; - - index++; - } - - return declaration; -} - -std::string ZPath::GetSourceTypeName() const -{ - return "Path"; -} - -ZResourceType ZPath::GetResourceType() const -{ - return ZResourceType::Path; -} - -size_t ZPath::GetRawDataSize() const -{ - return pathways.size() * pathways.at(0).GetRawDataSize(); -} - -void ZPath::SetNumPaths(uint32_t nNumPaths) -{ - numPaths = nNumPaths; -} - -/* PathwayEntry */ - -PathwayEntry::PathwayEntry(ZFile* nParent) : ZResource(nParent) -{ -} - -void PathwayEntry::ParseRawData() -{ - ZResource::ParseRawData(); - auto parentRawData = parent->GetRawData(); - numPoints = parentRawData.at(rawDataIndex + 0); - unk1 = parentRawData.at(rawDataIndex + 1); - unk2 = BitConverter::ToInt16BE(parentRawData, rawDataIndex + 2); - listSegmentAddress = BitConverter::ToInt32BE(parentRawData, rawDataIndex + 4); - - uint32_t currentPtr = GETSEGOFFSET(listSegmentAddress); - - points.reserve(numPoints); - for (int32_t i = 0; i < numPoints; i++) - { - ZVector vec(parent); - vec.ExtractFromBinary(currentPtr, ZScalarType::ZSCALAR_S16, 3); - - currentPtr += vec.GetRawDataSize(); - points.push_back(vec); - } -} - -void PathwayEntry::DeclareReferences(const std::string& prefix) -{ - ZResource::DeclareReferences(prefix); - if (points.empty()) - return; - - std::string pointsName; - bool addressFound = Globals::Instance->GetSegmentedPtrName(listSegmentAddress, parent, "Vec3s", - pointsName, false); - if (addressFound) - return; - - std::string declaration = ""; - - size_t index = 0; - for (const auto& point : points) - { - declaration += StringHelper::Sprintf("\t{ %s },", point.GetBodySourceCode().c_str()); - - if (index < points.size() - 1) - declaration += "\n"; - - index++; - } - - uint32_t pointsOffset = Seg2Filespace(listSegmentAddress, parent->baseAddress); - Declaration* decl = parent->GetDeclaration(pointsOffset); - if (decl == nullptr) - { - pointsName = StringHelper::Sprintf("%sPathwayList_%06X", prefix.c_str(), pointsOffset); - parent->AddDeclarationArray(pointsOffset, points.at(0).GetDeclarationAlignment(), - points.size() * 6, points.at(0).GetSourceTypeName(), pointsName, - points.size(), declaration); - } - else - decl->declBody = declaration; -} - -std::string PathwayEntry::GetBodySourceCode() const -{ - std::string declaration; - std::string listName; - Globals::Instance->GetSegmentedPtrName(listSegmentAddress, parent, "Vec3s", listName); - - if (Globals::Instance->game == ZGame::MM_RETAIL) - declaration += - StringHelper::Sprintf("%i, %i, %i, %s", numPoints, unk1, unk2, listName.c_str()); - else - { - if (numPoints > 0) - declaration += - StringHelper::Sprintf("ARRAY_COUNT(%s), %s", listName.c_str(), listName.c_str()); - else - declaration += StringHelper::Sprintf("%i, %s", numPoints, listName.c_str()); - } - - return declaration; -} - -std::string PathwayEntry::GetSourceTypeName() const -{ - return "Path"; -} - -ZResourceType PathwayEntry::GetResourceType() const -{ - return ZResourceType::Path; -} - -size_t PathwayEntry::GetRawDataSize() const -{ - return 0x08; -} - -segptr_t PathwayEntry::GetListAddress() const -{ - return listSegmentAddress; -} diff --git a/tools/ZAPD/ZAPD/ZPath.h b/tools/ZAPD/ZAPD/ZPath.h deleted file mode 100644 index e519decff4..0000000000 --- a/tools/ZAPD/ZAPD/ZPath.h +++ /dev/null @@ -1,51 +0,0 @@ -#pragma once - -#include "ZResource.h" -#include "ZVector.h" - -class PathwayEntry : public ZResource -{ -public: - PathwayEntry(ZFile* nParent); - - void ParseRawData() override; - void DeclareReferences(const std::string& prefix) override; - - std::string GetBodySourceCode() const override; - - std::string GetSourceTypeName() const override; - ZResourceType GetResourceType() const override; - - size_t GetRawDataSize() const override; - segptr_t GetListAddress() const; - -protected: - int32_t numPoints; - int8_t unk1; // (MM Only) - int16_t unk2; // (MM Only) - segptr_t listSegmentAddress; - std::vector points; -}; - -class ZPath : public ZResource -{ -public: - ZPath(ZFile* nParent); - - void ParseXML(tinyxml2::XMLElement* reader) override; - void ParseRawData() override; - void DeclareReferences(const std::string& prefix) override; - - Declaration* DeclareVar(const std::string& prefix, const std::string& bodyStr) override; - std::string GetBodySourceCode() const override; - - std::string GetSourceTypeName() const override; - ZResourceType GetResourceType() const override; - - size_t GetRawDataSize() const override; - void SetNumPaths(uint32_t nNumPaths); - -protected: - uint32_t numPaths; - std::vector pathways; -}; diff --git a/tools/ZAPD/ZAPD/ZPlayerAnimationData.cpp b/tools/ZAPD/ZAPD/ZPlayerAnimationData.cpp deleted file mode 100644 index ce5425d7e1..0000000000 --- a/tools/ZAPD/ZAPD/ZPlayerAnimationData.cpp +++ /dev/null @@ -1,104 +0,0 @@ -#include "ZPlayerAnimationData.h" - -#include "Utils/BitConverter.h" -#include "Utils/StringHelper.h" -#include "ZFile.h" - -REGISTER_ZFILENODE(PlayerAnimationData, ZPlayerAnimationData); - -ZPlayerAnimationData::ZPlayerAnimationData(ZFile* nParent) : ZResource(nParent) -{ - RegisterRequiredAttribute("FrameCount"); -} - -void ZPlayerAnimationData::ParseXML(tinyxml2::XMLElement* reader) -{ - ZResource::ParseXML(reader); - - std::string& frameCountXml = registeredAttributes.at("FrameCount").value; - - frameCount = StringHelper::StrToL(frameCountXml); -} - -void ZPlayerAnimationData::ParseRawData() -{ - ZResource::ParseRawData(); - - const auto& rawData = parent->GetRawData(); - - size_t totalSize = GetRawDataSize(); - // Divided by 2 because each value is an s16 - limbRotData.reserve(totalSize * frameCount / 2); - - for (size_t i = 0; i < totalSize; i += 2) - { - limbRotData.push_back(BitConverter::ToInt16BE(rawData, rawDataIndex + i)); - } -} - -Declaration* ZPlayerAnimationData::DeclareVar(const std::string& prefix, const std::string& bodyStr) -{ - std::string auxName = name; - - if (auxName == "") - auxName = GetDefaultName(prefix); - - Declaration* decl = - parent->AddDeclarationArray(rawDataIndex, GetDeclarationAlignment(), GetRawDataSize(), - GetSourceTypeName(), name, limbRotData.size(), bodyStr); - decl->staticConf = staticConf; - return decl; -} - -std::string ZPlayerAnimationData::GetBodySourceCode() const -{ - std::string declaration = ""; - - size_t index = 0; - for (const auto entry : limbRotData) - { - if (index % 8 == 0) - { - declaration += "\t"; - } - - if (entry < 0) - { - declaration += StringHelper::Sprintf("-0x%04X, ", -entry); - } - else - { - declaration += StringHelper::Sprintf("0x%04X, ", entry); - } - - if ((index + 1) % 8 == 0) - { - declaration += "\n"; - } - - index++; - } - - return declaration; -} - -std::string ZPlayerAnimationData::GetDefaultName(const std::string& prefix) const -{ - return StringHelper::Sprintf("%sPlayerAnimationData_%06X", prefix.c_str(), rawDataIndex); -} - -std::string ZPlayerAnimationData::GetSourceTypeName() const -{ - return "s16"; -} - -ZResourceType ZPlayerAnimationData::GetResourceType() const -{ - return ZResourceType::PlayerAnimationData; -} - -size_t ZPlayerAnimationData::GetRawDataSize() const -{ - // (sizeof(Vec3s) * limbCount + 2) * frameCount - return (6 * 22 + 2) * frameCount; -} diff --git a/tools/ZAPD/ZAPD/ZPlayerAnimationData.h b/tools/ZAPD/ZAPD/ZPlayerAnimationData.h deleted file mode 100644 index 2923117efc..0000000000 --- a/tools/ZAPD/ZAPD/ZPlayerAnimationData.h +++ /dev/null @@ -1,28 +0,0 @@ -#pragma once - -#include -#include - -#include "ZResource.h" - -class ZPlayerAnimationData : public ZResource -{ -public: - int16_t frameCount = 0; - std::vector limbRotData; - - ZPlayerAnimationData(ZFile* nParent); - - void ParseXML(tinyxml2::XMLElement* reader) override; - void ParseRawData() override; - - Declaration* DeclareVar(const std::string& prefix, const std::string& bodyStr) override; - - std::string GetBodySourceCode() const override; - std::string GetDefaultName(const std::string& prefix) const override; - - std::string GetSourceTypeName() const override; - ZResourceType GetResourceType() const override; - - size_t GetRawDataSize() const override; -}; diff --git a/tools/ZAPD/ZAPD/ZPointer.cpp b/tools/ZAPD/ZAPD/ZPointer.cpp deleted file mode 100644 index 6e6945cada..0000000000 --- a/tools/ZAPD/ZAPD/ZPointer.cpp +++ /dev/null @@ -1,57 +0,0 @@ -#include "ZPointer.h" - -#include "Globals.h" -#include "Utils/BitConverter.h" -#include "Utils/StringHelper.h" -#include "WarningHandler.h" -#include "ZFile.h" - -REGISTER_ZFILENODE(Pointer, ZPointer); - -ZPointer::ZPointer(ZFile* nParent) : ZResource(nParent) -{ - RegisterRequiredAttribute("Type"); -} - -void ZPointer::ParseXML(tinyxml2::XMLElement* reader) -{ - ZResource::ParseXML(reader); - - type = registeredAttributes.at("Type").value; -} - -void ZPointer::ParseRawData() -{ - auto& rawData = parent->GetRawData(); - - ptr = BitConverter::ToUInt32BE(rawData, rawDataIndex); -} - -std::string ZPointer::GetBodySourceCode() const -{ - std::string ptrName; - - Globals::Instance->GetSegmentedPtrName(ptr, parent, "", ptrName); - - return ptrName; -} - -bool ZPointer::DoesSupportArray() const -{ - return true; -} - -std::string ZPointer::GetSourceTypeName() const -{ - return type + "*"; -} - -ZResourceType ZPointer::GetResourceType() const -{ - return ZResourceType::Pointer; -} - -size_t ZPointer::GetRawDataSize() const -{ - return 0x04; -} diff --git a/tools/ZAPD/ZAPD/ZPointer.h b/tools/ZAPD/ZAPD/ZPointer.h deleted file mode 100644 index 8fb5889339..0000000000 --- a/tools/ZAPD/ZAPD/ZPointer.h +++ /dev/null @@ -1,22 +0,0 @@ -#pragma once - -#include "ZResource.h" - -class ZPointer : public ZResource -{ -public: - segptr_t ptr = SEGMENTED_NULL; - std::string type; - - ZPointer(ZFile* nParent); - - void ParseXML(tinyxml2::XMLElement* reader) override; - void ParseRawData() override; - std::string GetBodySourceCode() const override; - - bool DoesSupportArray() const override; - std::string GetSourceTypeName() const override; - ZResourceType GetResourceType() const override; - - size_t GetRawDataSize() const override; -}; diff --git a/tools/ZAPD/ZAPD/ZResource.cpp b/tools/ZAPD/ZAPD/ZResource.cpp deleted file mode 100644 index d991c46539..0000000000 --- a/tools/ZAPD/ZAPD/ZResource.cpp +++ /dev/null @@ -1,339 +0,0 @@ -#include "ZResource.h" - -#include -#include - -#include "Utils/StringHelper.h" -#include "WarningHandler.h" -#include "ZFile.h" - -ZResource::ZResource(ZFile* nParent) -{ - // assert(nParent != nullptr); - parent = nParent; - name = ""; - outName = ""; - sourceOutput = ""; - rawDataIndex = 0; - outputDeclaration = true; - - RegisterRequiredAttribute("Name"); - RegisterOptionalAttribute("OutName"); - RegisterOptionalAttribute("Offset"); - RegisterOptionalAttribute("Custom"); - RegisterOptionalAttribute("Static", "Global"); -} - -void ZResource::ExtractWithXML(tinyxml2::XMLElement* reader, offset_t nRawDataIndex) -{ - rawDataIndex = nRawDataIndex; - declaredInXml = true; - - if (reader != nullptr) - ParseXML(reader); - - // Don't parse raw data of external files - if (parent->GetMode() != ZFileMode::ExternalFile) - { - ParseRawData(); - CalcHash(); - } - - if (!isInner) - { - Declaration* decl = DeclareVar(parent->GetName(), ""); - if (decl != nullptr) - { - decl->declaredInXml = true; - decl->staticConf = staticConf; - } - } -} - -void ZResource::ExtractFromFile(offset_t nRawDataIndex) -{ - rawDataIndex = nRawDataIndex; - - // Don't parse raw data of external files - if (parent->GetMode() == ZFileMode::ExternalFile) - return; - - ParseRawData(); - CalcHash(); -} - -void ZResource::ParseXML(tinyxml2::XMLElement* reader) -{ - if (reader != nullptr) - { - // If it is an inner node, then 'Name' isn't required - if (isInner) - { - registeredAttributes.at("Name").isRequired = false; - } - - auto attrs = reader->FirstAttribute(); - while (attrs != nullptr) - { - std::string attrName = attrs->Name(); - bool attrDeclared = false; - - if (registeredAttributes.find(attrName) != registeredAttributes.end()) - { - registeredAttributes[attrName].value = attrs->Value(); - registeredAttributes[attrName].wasSet = true; - attrDeclared = true; - } - - if (!attrDeclared) - { - HANDLE_WARNING_RESOURCE( - WarningType::UnknownAttribute, parent, this, rawDataIndex, - StringHelper::Sprintf("unexpected '%s' attribute in resource <%s>", - attrName.c_str(), reader->Name()), - ""); - } - attrs = attrs->Next(); - } - - if (!canHaveInner && !reader->NoChildren()) - { - std::string errorHeader = StringHelper::Sprintf( - "resource '%s' with inner element/child detected", reader->Name()); - HANDLE_ERROR_PROCESS(WarningType::InvalidXML, errorHeader, ""); - } - - for (const auto& attr : registeredAttributes) - { - if (attr.second.isRequired && attr.second.value == "") - { - std::string headerMsg = - StringHelper::Sprintf("missing required attribute '%s' in resource <%s>", - attr.first.c_str(), reader->Name()); - HANDLE_ERROR_RESOURCE(WarningType::MissingAttribute, parent, this, rawDataIndex, - headerMsg, ""); - } - } - - name = registeredAttributes.at("Name").value; - - static std::regex r("[a-zA-Z_]+[a-zA-Z0-9_]*", std::regex::icase | std::regex::optimize); - - if (!isInner || (isInner && name != "")) - { - if (!std::regex_match(name, r)) - { - HANDLE_ERROR_RESOURCE(WarningType::InvalidAttributeValue, parent, this, - rawDataIndex, "invalid value found for 'Name' attribute", ""); - } - } - - outName = registeredAttributes.at("OutName").value; - if (outName == "") - outName = name; - - isCustomAsset = registeredAttributes["Custom"].wasSet; - - std::string& staticXml = registeredAttributes["Static"].value; - if (staticXml == "Global") - { - staticConf = StaticConfig::Global; - } - else if (staticXml == "On") - { - staticConf = StaticConfig::On; - } - else if (staticXml == "Off") - { - staticConf = StaticConfig::Off; - } - else - { - HANDLE_ERROR_RESOURCE( - WarningType::InvalidAttributeValue, parent, this, rawDataIndex, - StringHelper::Sprintf("invalid value '%s' for 'Static' attribute", staticConf), ""); - } - - declaredInXml = true; - } -} - -void ZResource::ParseRawData() -{ -} - -void ZResource::DeclareReferences([[maybe_unused]] const std::string& prefix) -{ -} - -void ZResource::ParseRawDataLate() -{ -} - -void ZResource::DeclareReferencesLate([[maybe_unused]] const std::string& prefix) -{ -} - -Declaration* ZResource::DeclareVar(const std::string& prefix, const std::string& bodyStr) -{ - std::string auxName = name; - - if (name == "") - auxName = GetDefaultName(prefix); - - Declaration* decl = - parent->AddDeclaration(rawDataIndex, GetDeclarationAlignment(), GetRawDataSize(), - GetSourceTypeName(), auxName, bodyStr); - decl->staticConf = staticConf; - return decl; -} - -void ZResource::Save([[maybe_unused]] const fs::path& outFolder) -{ -} - -const std::string& ZResource::GetName() const -{ - return name; -} - -const std::string& ZResource::GetOutName() const -{ - return outName; -} - -void ZResource::SetOutName(const std::string& nName) -{ - outName = nName; -} - -void ZResource::SetName(const std::string& nName) -{ - name = nName; -} - -bool ZResource::IsExternalResource() const -{ - return false; -} - -bool ZResource::DoesSupportArray() const -{ - return false; -} - -std::string ZResource::GetExternalExtension() const -{ - return ""; -} - -DeclarationAlignment ZResource::GetDeclarationAlignment() const -{ - return DeclarationAlignment::Align4; -} - -bool ZResource::WasDeclaredInXml() const -{ - return declaredInXml; -} - -StaticConfig ZResource::GetStaticConf() const -{ - return staticConf; -} - -offset_t ZResource::GetRawDataIndex() const -{ - return rawDataIndex; -} - -void ZResource::SetRawDataIndex(offset_t nRawDataIndex) -{ - rawDataIndex = nRawDataIndex; -} - -std::string ZResource::GetBodySourceCode() const -{ - return "ERROR"; -} - -std::string ZResource::GetDefaultName(const std::string& prefix) const -{ - return StringHelper::Sprintf("%s%s_%06X", prefix.c_str(), GetSourceTypeName().c_str(), - rawDataIndex); -} - -void ZResource::GetSourceOutputCode([[maybe_unused]] const std::string& prefix) -{ - std::string bodyStr = GetBodySourceCode(); - - if (bodyStr != "ERROR") - { - Declaration* decl = parent->GetDeclaration(rawDataIndex); - - if (decl == nullptr || decl->isPlaceholder) - decl = DeclareVar(prefix, bodyStr); - else - decl->declBody = bodyStr; - - decl->staticConf = staticConf; - } -} - -std::string ZResource::GetSourceOutputHeader([[maybe_unused]] const std::string& prefix) -{ - return ""; -} - -ZResourceType ZResource::GetResourceType() const -{ - return ZResourceType::Error; -} - -void ZResource::CalcHash() -{ - hash = 0; -} - -void ZResource::SetInnerNode(bool inner) -{ - isInner = inner; -} - -void ZResource::RegisterRequiredAttribute(const std::string& attr) -{ - ResourceAttribute resAtrr; - resAtrr.key = attr; - resAtrr.isRequired = true; - registeredAttributes[attr] = resAtrr; -} - -void ZResource::RegisterOptionalAttribute(const std::string& attr, const std::string& defaultValue) -{ - ResourceAttribute resAtrr; - resAtrr.key = attr; - resAtrr.value = defaultValue; - registeredAttributes[attr] = resAtrr; -} - -offset_t Seg2Filespace(segptr_t segmentedAddress, uint32_t parentBaseAddress) -{ - offset_t currentPtr = GETSEGOFFSET(segmentedAddress); - - if (GETSEGNUM(segmentedAddress) == 0x80) // Is defined in code? - { - uint32_t parentBaseOffset = GETSEGOFFSET(parentBaseAddress); - if (parentBaseOffset > currentPtr) - { - HANDLE_ERROR(WarningType::Always, - StringHelper::Sprintf( - "resource address 0x%08X is smaller than 'BaseAddress' 0x%08X", - segmentedAddress, parentBaseAddress), - "Maybe your 'BaseAddress' is wrong?"); - } - - currentPtr -= parentBaseOffset; - } - - return currentPtr; -} diff --git a/tools/ZAPD/ZAPD/ZResource.h b/tools/ZAPD/ZAPD/ZResource.h deleted file mode 100644 index 768b785441..0000000000 --- a/tools/ZAPD/ZAPD/ZResource.h +++ /dev/null @@ -1,263 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include "Declaration.h" -#include "Utils/BinaryWriter.h" -#include "Utils/Directory.h" -#include "tinyxml2.h" - -#define SEGMENT_SCENE 2 -#define SEGMENT_ROOM 3 -#define SEGMENT_KEEP 4 -#define SEGMENT_FIELDDANGEON_KEEP 5 -#define SEGMENT_OBJECT 6 -#define SEGMENT_LINKANIMETION 7 - -#define GETSEGOFFSET(x) (x & 0x00FFFFFF) -#define GETSEGNUM(x) ((x >> 24) & 0xFF) - -class ZFile; - -enum class ZResourceType -{ - Error, - ActorList, - Animation, - Array, - AltHeader, - Background, - Blob, - CollisionHeader, - CollisionPoly, - Cutscene, - DisplayList, - Limb, - LimbTable, - Mtx, - Path, - PlayerAnimationData, - Pointer, - Room, - RoomCommand, - Scalar, - Scene, - Skeleton, - String, - SurfaceType, - Symbol, - Texture, - TextureAnimation, - TextureAnimationParams, - Vector, - Vertex, - Waterbox, - KeyFrameFlexLimb, - KeyFrameStandardLimb, - KeyFrameSkel, - KeyFrameAnimation, -}; - -class ResourceAttribute -{ -public: - std::string key; - std::string value; - bool isRequired = false; - bool wasSet = false; -}; - -class ZResource -{ -public: - ZFile* parent; - bool outputDeclaration = true; - uint32_t hash = 0; - - /** - * Constructor. - * Child classes should not declare any other constructor besides this one - */ - ZResource(ZFile* nParent); - virtual ~ZResource() = default; - - /// - /// Extracts/Parsees data from binary file using an XML to provide the needed metadata. - /// - /// XML Node we wish to parse from. - /// The offset within the binary file we are going to parse from as - /// indicated by the "Offset" parameter in the XML. - virtual void ExtractWithXML(tinyxml2::XMLElement* reader, offset_t nRawDataIndex); - - /// - /// Extracts/Parses the needed data straight from a binary without the use of an XML. - /// - /// The offset within the binary file we wish to parse from. - virtual void ExtractFromFile(offset_t nRawDataIndex); - - // Misc - /** - * Parses additional attributes of the XML node. - * Extra attritbutes have to be registered using `RegisterRequiredAttribute` or - * `RegisterOptionalAttribute` in the constructor of the ZResource - */ - virtual void ParseXML(tinyxml2::XMLElement* reader); - /** - * Extracts data from the binary file - */ - virtual void ParseRawData(); - /** - * Declares any data pointed by this resource that has not been declared already. - * For example, a Vtx referenced by a Dlist should be declared here if it wasn't - * declared previously by something else - */ - virtual void DeclareReferences(const std::string& prefix); - virtual void ParseRawDataLate(); - virtual void DeclareReferencesLate(const std::string& prefix); - - /** - * Adds this resource as a Declaration of its parent ZFile - */ - virtual Declaration* DeclareVar(const std::string& prefix, const std::string& bodyStr); - /** - * Returns the body of the variable of the extracted resource, without any side-effect - */ - [[nodiscard]] virtual std::string GetBodySourceCode() const; - /** - * Creates an automatically generated variable name for the current resource - */ - [[nodiscard]] virtual std::string GetDefaultName(const std::string& prefix) const; - - virtual void GetSourceOutputCode(const std::string& prefix); - virtual std::string GetSourceOutputHeader(const std::string& prefix); - virtual void CalcHash(); - /** - * Exports the resource to binary format - */ - virtual void Save(const fs::path& outFolder); - - // Properties - /** - * Returns true if the resource will be externalized, and included back to the C file using - * `#include`s - */ - virtual bool IsExternalResource() const; - /** - * Can this type be wrapped in an node? - */ - virtual bool DoesSupportArray() const; - /** - * The type of the resource as a C struct - */ - [[nodiscard]] virtual std::string GetSourceTypeName() const = 0; - /** - * The type in the ZResource enum - */ - [[nodiscard]] virtual ZResourceType GetResourceType() const = 0; - /** - * The filename extension for assets extracted as standalone files - */ - [[nodiscard]] virtual std::string GetExternalExtension() const; - - // Getters/Setters - [[nodiscard]] const std::string& GetName() const; - void SetName(const std::string& nName); - [[nodiscard]] const std::string& GetOutName() const; - void SetOutName(const std::string& nName); - [[nodiscard]] offset_t GetRawDataIndex() const; - void SetRawDataIndex(offset_t nRawDataIndex); - - /** - * The size of the current struct being extracted, not counting data referenced by it - */ - [[nodiscard]] virtual size_t GetRawDataSize() const = 0; - /** - * The alignment of the extracted struct - */ - [[nodiscard]] virtual DeclarationAlignment GetDeclarationAlignment() const; - void SetInnerNode(bool inner); - /** - * Returns `true` if this ZResource was declared using an XML node, - * `false` otherwise (for example, a Vtx extracted indirectly by a DList) - */ - [[nodiscard]] bool WasDeclaredInXml() const; - [[nodiscard]] StaticConfig GetStaticConf() const; - -protected: - std::string name; - std::string outName; - offset_t rawDataIndex; - std::string sourceOutput; - - // Inner is used mostly for nodes - /** - * Is this resource an inner node of another resource? - * (namely inside an ) - */ - bool isInner = false; - /** - * Can this type have an inner node? - */ - bool canHaveInner = false; - - /** - * If set to true, create a reference for the asset in the file, but don't - * actually try to extract it from the file - */ - bool isCustomAsset; - bool declaredInXml = false; - StaticConfig staticConf = StaticConfig::Global; - - // Reading from this XMLs attributes should be performed in the overrided `ParseXML` method. - std::map registeredAttributes; - - // XML attributes registers. - // Registering XML attributes should be done in constructors. - - // The resource needs this attribute. If it is not provided, then the program will throw an - // exception. - void RegisterRequiredAttribute(const std::string& attr); - // Optional attribute. The resource has to do manual checks and manual warnings. It may or may - // not have a value. - void RegisterOptionalAttribute(const std::string& attr, const std::string& defaultValue = ""); -}; - -class ZResourceExporter -{ -public: - ZResourceExporter() = default; - virtual ~ZResourceExporter() = default; - - virtual void Save(ZResource* res, fs::path outPath, BinaryWriter* writer) = 0; -}; - -offset_t Seg2Filespace(segptr_t segmentedAddress, uint32_t parentBaseAddress); - -typedef ZResource*(ZResourceFactoryFunc)(ZFile* nParent); - -#define REGISTER_ZFILENODE(nodeName, zResClass) \ - static ZResource* ZResourceFactory_##zResClass_##nodeName(ZFile* nParent) \ - { \ - return static_cast(new zResClass(nParent)); \ - } \ - \ - class ZRes_##nodeName \ - { \ - public: \ - ZRes_##nodeName() \ - { \ - ZFile::RegisterNode(#nodeName, &ZResourceFactory_##zResClass_##nodeName); \ - } \ - }; \ - static ZRes_##nodeName inst_ZRes_##nodeName - -#define REGISTER_EXPORTER(expFunc) \ - class ZResExp_##expFunc \ - { \ - public: \ - ZResExp_##expFunc() { expFunc(); } \ - }; \ - static ZResExp_##expFunc inst_ZResExp_##expFunc diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/EndMarker.cpp b/tools/ZAPD/ZAPD/ZRoom/Commands/EndMarker.cpp deleted file mode 100644 index 3f64af168f..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/EndMarker.cpp +++ /dev/null @@ -1,20 +0,0 @@ -#include "EndMarker.h" - -EndMarker::EndMarker(ZFile* nParent) : ZRoomCommand(nParent) -{ -} - -std::string EndMarker::GetBodySourceCode() const -{ - return "SCENE_CMD_END()"; -} - -std::string EndMarker::GetCommandCName() const -{ - return "SCmdEndMarker"; -} - -RoomCommand EndMarker::GetRoomCommand() const -{ - return RoomCommand::EndMarker; -} diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/EndMarker.h b/tools/ZAPD/ZAPD/ZRoom/Commands/EndMarker.h deleted file mode 100644 index daa477c945..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/EndMarker.h +++ /dev/null @@ -1,13 +0,0 @@ -#pragma once - -#include "ZRoom/ZRoomCommand.h" - -class EndMarker : public ZRoomCommand -{ -public: - EndMarker(ZFile* nParent); - - std::string GetBodySourceCode() const override; - std::string GetCommandCName() const override; - RoomCommand GetRoomCommand() const override; -}; \ No newline at end of file diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetActorList.cpp b/tools/ZAPD/ZAPD/ZRoom/Commands/SetActorList.cpp deleted file mode 100644 index 4d16f9377e..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetActorList.cpp +++ /dev/null @@ -1,58 +0,0 @@ -#include "SetActorList.h" - -#include - -#include "Globals.h" -#include "Utils/BitConverter.h" -#include "Utils/StringHelper.h" -#include "ZRoom/ZRoom.h" - -SetActorList::SetActorList(ZFile* nParent) : ZRoomCommand(nParent) -{ -} - -void SetActorList::ParseRawData() -{ - ZRoomCommand::ParseRawData(); - numActors = cmdArg1; - - actorList = new ZActorList(parent); - actorList->ExtractFromBinary(segmentOffset, numActors); -} - -void SetActorList::DeclareReferences(const std::string& prefix) -{ - if (parent->HasDeclaration(segmentOffset)) - { - delete actorList; - actorList = static_cast(parent->FindResource(segmentOffset)); - assert(actorList != nullptr); - assert(actorList->GetResourceType() == ZResourceType::ActorList); - return; - } - - if (actorList->GetName() == "") - { - actorList->SetName(actorList->GetDefaultName(prefix)); - } - actorList->DeclareVar(prefix, ""); - parent->AddResource(actorList); -} - -std::string SetActorList::GetBodySourceCode() const -{ - std::string listName; - Globals::Instance->GetSegmentedPtrName(cmdArg2, parent, "ActorEntry", listName); - - return StringHelper::Sprintf("SCENE_CMD_ACTOR_LIST(%i, %s)", numActors, listName.c_str()); -} - -std::string SetActorList::GetCommandCName() const -{ - return "SCmdActorList"; -} - -RoomCommand SetActorList::GetRoomCommand() const -{ - return RoomCommand::SetActorList; -} diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetActorList.h b/tools/ZAPD/ZAPD/ZRoom/Commands/SetActorList.h deleted file mode 100644 index 9122c15bb0..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetActorList.h +++ /dev/null @@ -1,24 +0,0 @@ -#pragma once - -#include "ZActorList.h" -#include "ZRoom/ZRoomCommand.h" - -class SetActorList : public ZRoomCommand -{ -public: - uint32_t numActors; - ZActorList* actorList = nullptr; - - SetActorList(ZFile* nParent); - - void ParseRawData() override; - void DeclareReferences(const std::string& prefix) override; - - std::string GetBodySourceCode() const override; - - RoomCommand GetRoomCommand() const override; - std::string GetCommandCName() const override; - -protected: - size_t GetActorListArraySize() const; -}; diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetAlternateHeaders.cpp b/tools/ZAPD/ZAPD/ZRoom/Commands/SetAlternateHeaders.cpp deleted file mode 100644 index e64b855374..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetAlternateHeaders.cpp +++ /dev/null @@ -1,82 +0,0 @@ -#include "SetAlternateHeaders.h" - -#include "Globals.h" -#include "Utils/BitConverter.h" -#include "Utils/StringHelper.h" -#include "ZFile.h" - -SetAlternateHeaders::SetAlternateHeaders(ZFile* nParent) : ZRoomCommand(nParent) -{ -} - -void SetAlternateHeaders::DeclareReferences([[maybe_unused]] const std::string& prefix) -{ - if (cmdArg2 != 0) - { - std::string varName = - StringHelper::Sprintf("%sAlternateHeaders0x%06X", prefix.c_str(), segmentOffset); - parent->AddDeclarationPlaceholder(segmentOffset, varName); - } -} - -void SetAlternateHeaders::ParseRawDataLate() -{ - size_t numHeaders = zRoom->parent->GetDeclarationSizeFromNeighbor(segmentOffset) / 4; - - headers.reserve(numHeaders); - for (uint32_t i = 0; i < numHeaders; i++) - { - int32_t address = BitConverter::ToInt32BE(parent->GetRawData(), segmentOffset + (i * 4)); - headers.push_back(address); - - if (address != 0 && parent->GetDeclaration(GETSEGOFFSET(address)) == nullptr) - { - ZRoom* altheader = new ZRoom(parent); - altheader->ExtractFromBinary(GETSEGOFFSET(address), zRoom->GetResourceType()); - altheader->DeclareReferences(parent->GetName()); - - parent->resources.push_back(altheader); - } - } -} - -void SetAlternateHeaders::DeclareReferencesLate(const std::string& prefix) -{ - if (!headers.empty()) - { - std::string declaration; - - for (size_t i = 0; i < headers.size(); i++) - { - std::string altHeaderName; - Globals::Instance->GetSegmentedPtrName(headers.at(i), parent, "", altHeaderName); - - declaration += StringHelper::Sprintf("\t%s,", altHeaderName.c_str()); - - if (i + 1 < headers.size()) - declaration += "\n"; - } - - std::string varName = - StringHelper::Sprintf("%sAlternateHeaders0x%06X", prefix.c_str(), segmentOffset); - parent->AddDeclarationArray(segmentOffset, GetDeclarationAlignment(), headers.size() * 4, - "SceneCmd*", varName, headers.size(), declaration); - } -} - -std::string SetAlternateHeaders::GetBodySourceCode() const -{ - std::string listName; - Globals::Instance->GetSegmentedPtrName(cmdArg2, parent, "SceneCmd*", listName); - return StringHelper::Sprintf("SCENE_CMD_ALTERNATE_HEADER_LIST(%s)", listName.c_str()); -} - -std::string SetAlternateHeaders::GetCommandCName() const -{ - return "SCmdAltHeaders"; -} - -RoomCommand SetAlternateHeaders::GetRoomCommand() const -{ - return RoomCommand::SetAlternateHeaders; -} diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetAlternateHeaders.h b/tools/ZAPD/ZAPD/ZRoom/Commands/SetAlternateHeaders.h deleted file mode 100644 index e66df936d5..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetAlternateHeaders.h +++ /dev/null @@ -1,23 +0,0 @@ -#pragma once - -#include "ZRoom/ZRoom.h" -#include "ZRoom/ZRoomCommand.h" - -class SetAlternateHeaders : public ZRoomCommand -{ -public: - std::vector headers; - - SetAlternateHeaders(ZFile* nParent); - - void DeclareReferences(const std::string& prefix) override; - void ParseRawDataLate() override; - void DeclareReferencesLate(const std::string& prefix) override; - - std::string GetBodySourceCode() const override; - - RoomCommand GetRoomCommand() const override; - std::string GetCommandCName() const override; - -private: -}; diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetAnimatedMaterialList.cpp b/tools/ZAPD/ZAPD/ZRoom/Commands/SetAnimatedMaterialList.cpp deleted file mode 100644 index 0b9a67e0ec..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetAnimatedMaterialList.cpp +++ /dev/null @@ -1,48 +0,0 @@ -/** - * File: SetAnimatedMaterialList.cpp - * Description: Defines a class SetAnimatedMaterialList to enable ZRoom to declare - * ZTextureAnimations, using that ZResource to do the work. - */ -#include "SetAnimatedMaterialList.h" - -#include "Globals.h" -#include "Utils/BitConverter.h" -#include "Utils/StringHelper.h" -#include "ZFile.h" -#include "ZRoom/ZRoom.h" -#include "ZTextureAnimation.h" - -SetAnimatedMaterialList::SetAnimatedMaterialList(ZFile* nParent) - : ZRoomCommand(nParent), textureAnimation(nParent) -{ -} - -void SetAnimatedMaterialList::ParseRawData() -{ - ZRoomCommand::ParseRawData(); - textureAnimation.ExtractFromFile(segmentOffset); -} - -void SetAnimatedMaterialList::DeclareReferences(const std::string& prefix) -{ - textureAnimation.SetName(textureAnimation.GetDefaultName(prefix.c_str())); - textureAnimation.DeclareReferences(prefix); - textureAnimation.GetSourceOutputCode(prefix); -} - -std::string SetAnimatedMaterialList::GetBodySourceCode() const -{ - std::string listName; - Globals::Instance->GetSegmentedPtrName(cmdArg2, parent, "AnimatedMaterial", listName); - return StringHelper::Sprintf("SCENE_CMD_ANIMATED_MATERIAL_LIST(%s)", listName.c_str()); -} - -std::string SetAnimatedMaterialList::GetCommandCName() const -{ - return "SCmdTextureAnimations"; -} - -RoomCommand SetAnimatedMaterialList::GetRoomCommand() const -{ - return RoomCommand::SetAnimatedMaterialList; -} diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetAnimatedMaterialList.h b/tools/ZAPD/ZAPD/ZRoom/Commands/SetAnimatedMaterialList.h deleted file mode 100644 index 3dbbf9684a..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetAnimatedMaterialList.h +++ /dev/null @@ -1,21 +0,0 @@ -#pragma once - -#include "ZRoom/ZRoomCommand.h" -#include "ZTextureAnimation.h" - -class SetAnimatedMaterialList : public ZRoomCommand -{ -public: - SetAnimatedMaterialList(ZFile* nParent); - - void ParseRawData() override; - void DeclareReferences(const std::string& prefix) override; - - std::string GetBodySourceCode() const override; - - RoomCommand GetRoomCommand() const override; - std::string GetCommandCName() const override; - -private: - ZTextureAnimation textureAnimation; -}; diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetCameraSettings.cpp b/tools/ZAPD/ZAPD/ZRoom/Commands/SetCameraSettings.cpp deleted file mode 100644 index e30e1b682d..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetCameraSettings.cpp +++ /dev/null @@ -1,36 +0,0 @@ -#include "SetCameraSettings.h" - -#include "Utils/BitConverter.h" -#include "Utils/StringHelper.h" -#include "Globals.h" - -SetCameraSettings::SetCameraSettings(ZFile* nParent) : ZRoomCommand(nParent) -{ -} - -void SetCameraSettings::ParseRawData() -{ - ZRoomCommand::ParseRawData(); - cameraMovement = cmdArg1; - mapHighlight = BitConverter::ToUInt32BE(parent->GetRawData(), rawDataIndex + 4); -} - -std::string SetCameraSettings::GetBodySourceCode() const -{ - if (Globals::Instance->game == ZGame::MM_RETAIL) - return StringHelper::Sprintf("SCENE_CMD_SET_REGION_VISITED(0x%02X, 0x%08X)", cameraMovement, - mapHighlight); - else - return StringHelper::Sprintf("SCENE_CMD_MISC_SETTINGS(0x%02X, 0x%08X)", cameraMovement, - mapHighlight); -} - -std::string SetCameraSettings::GetCommandCName() const -{ - return "SCmdMiscSettings"; -} - -RoomCommand SetCameraSettings::GetRoomCommand() const -{ - return RoomCommand::SetCameraSettings; -} diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetCameraSettings.h b/tools/ZAPD/ZAPD/ZRoom/Commands/SetCameraSettings.h deleted file mode 100644 index a8fed44ec2..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetCameraSettings.h +++ /dev/null @@ -1,21 +0,0 @@ -#pragma once - -#include "ZRoom/ZRoomCommand.h" - -class SetCameraSettings : public ZRoomCommand -{ -public: - uint8_t cameraMovement; - uint32_t mapHighlight; - - SetCameraSettings(ZFile* nParent); - - void ParseRawData() override; - - std::string GetBodySourceCode() const override; - - std::string GetCommandCName() const override; - RoomCommand GetRoomCommand() const override; - -private: -}; diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetCollisionHeader.cpp b/tools/ZAPD/ZAPD/ZRoom/Commands/SetCollisionHeader.cpp deleted file mode 100644 index 03aaa4bbbc..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetCollisionHeader.cpp +++ /dev/null @@ -1,44 +0,0 @@ -#include "SetCollisionHeader.h" - -#include "Globals.h" -#include "Utils/BitConverter.h" -#include "Utils/StringHelper.h" -#include "ZFile.h" -#include "ZRoom/ZRoom.h" - -SetCollisionHeader::SetCollisionHeader(ZFile* nParent) : ZRoomCommand(nParent) -{ -} - -void SetCollisionHeader::ParseRawData() -{ - ZRoomCommand::ParseRawData(); - - collisionHeader = new ZCollisionHeader(parent); - collisionHeader->SetName( - StringHelper::Sprintf("%sCollisionHeader_%06X", parent->GetName().c_str(), segmentOffset)); - collisionHeader->ExtractFromFile(segmentOffset); - parent->AddResource(collisionHeader); -} - -void SetCollisionHeader::DeclareReferences(const std::string& prefix) -{ - collisionHeader->DeclareVar(prefix, ""); -} - -std::string SetCollisionHeader::GetBodySourceCode() const -{ - std::string listName; - Globals::Instance->GetSegmentedPtrName(cmdArg2, parent, "CollisionHeader", listName); - return StringHelper::Sprintf("SCENE_CMD_COL_HEADER(%s)", listName.c_str()); -} - -std::string SetCollisionHeader::GetCommandCName() const -{ - return "SCmdColHeader"; -} - -RoomCommand SetCollisionHeader::GetRoomCommand() const -{ - return RoomCommand::SetCollisionHeader; -} diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetCollisionHeader.h b/tools/ZAPD/ZAPD/ZRoom/Commands/SetCollisionHeader.h deleted file mode 100644 index f7d5ecf358..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetCollisionHeader.h +++ /dev/null @@ -1,20 +0,0 @@ -#pragma once - -#include "ZCollision.h" -#include "ZRoom/ZRoomCommand.h" - -class SetCollisionHeader : public ZRoomCommand -{ -public: - ZCollisionHeader* collisionHeader; - - SetCollisionHeader(ZFile* nParent); - - void ParseRawData() override; - void DeclareReferences(const std::string& prefix) override; - - std::string GetBodySourceCode() const override; - - std::string GetCommandCName() const override; - RoomCommand GetRoomCommand() const override; -}; diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetCsCamera.cpp b/tools/ZAPD/ZAPD/ZRoom/Commands/SetCsCamera.cpp deleted file mode 100644 index 302d638d4c..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetCsCamera.cpp +++ /dev/null @@ -1,154 +0,0 @@ -#include "SetCsCamera.h" - -#include "Globals.h" -#include "Utils/BitConverter.h" -#include "Utils/StringHelper.h" -#include "ZFile.h" -#include "ZRoom/ZRoom.h" - -SetCsCamera::SetCsCamera(ZFile* nParent) : ZRoomCommand(nParent) -{ -} - -void SetCsCamera::ParseRawData() -{ - ZRoomCommand::ParseRawData(); - int numCameras = cmdArg1; - - uint32_t currentPtr = segmentOffset; - int32_t numPoints = 0; - - cameras.reserve(numCameras); - for (int32_t i = 0; i < numCameras; i++) - { - ActorCsCamInfo entry(parent->GetRawData(), currentPtr); - numPoints += entry.GetNumPoints(); - - currentPtr += entry.GetRawDataSize(); - cameras.push_back(entry); - } - - if (numPoints > 0) - { - uint32_t currentPtr = cameras.at(0).GetSegmentOffset(); - - points.reserve(numPoints); - for (int32_t i = 0; i < numPoints; i++) - { - ZVector vec(parent); - vec.ExtractFromBinary(currentPtr, ZScalarType::ZSCALAR_S16, 3); - - currentPtr += vec.GetRawDataSize(); - points.push_back(vec); - } - } -} - -void SetCsCamera::DeclareReferences(const std::string& prefix) -{ - if (points.size() > 0) - { - std::string declaration; - size_t index = 0; - for (auto& point : points) - { - declaration += StringHelper::Sprintf("\t{ %s },", point.GetBodySourceCode().c_str()); - - if (index < points.size() - 1) - declaration += "\n"; - - index++; - } - - uint32_t segOffset = cameras.at(0).GetSegmentOffset(); - - parent->AddDeclarationArray( - segOffset, DeclarationAlignment::Align4, points.size() * points.at(0).GetRawDataSize(), - points.at(0).GetSourceTypeName().c_str(), - StringHelper::Sprintf("%sCsCameraPoints_%06X", prefix.c_str(), segOffset), - points.size(), declaration); - } - - if (!cameras.empty()) - { - std::string camPointsName; - Globals::Instance->GetSegmentedPtrName(cameras.at(0).GetCamAddress(), parent, "Vec3s", - camPointsName); - std::string declaration; - - size_t index = 0; - size_t pointsIndex = 0; - for (const auto& entry : cameras) - { - declaration += - StringHelper::Sprintf("\t{ %i, %i, &%s[%i] },", entry.type, entry.numPoints, - camPointsName.c_str(), pointsIndex); - - if (index < cameras.size() - 1) - declaration += "\n"; - - index++; - pointsIndex += entry.GetNumPoints(); - } - - const auto& entry = cameras.front(); - std::string camTypename = entry.GetSourceTypeName(); - - parent->AddDeclarationArray( - segmentOffset, DeclarationAlignment::Align4, cameras.size() * entry.GetRawDataSize(), - camTypename, - StringHelper::Sprintf("%s%s_%06X", prefix.c_str(), camTypename.c_str(), segmentOffset), - cameras.size(), declaration); - } -} - -std::string SetCsCamera::GetBodySourceCode() const -{ - std::string listName; - Globals::Instance->GetSegmentedPtrName(cmdArg2, parent, "ActorCsCamInfo", listName); - return StringHelper::Sprintf("SCENE_CMD_ACTOR_CUTSCENE_CAM_LIST(%i, %s)", cameras.size(), - listName.c_str()); -} - -std::string SetCsCamera::GetCommandCName() const -{ - return "SCmdCsCameraList"; -} - -RoomCommand SetCsCamera::GetRoomCommand() const -{ - return RoomCommand::SetCsCamera; -} - -ActorCsCamInfo::ActorCsCamInfo(const std::vector& rawData, uint32_t rawDataIndex) - : baseOffset(rawDataIndex), type(BitConverter::ToInt16BE(rawData, rawDataIndex + 0)), - numPoints(BitConverter::ToInt16BE(rawData, rawDataIndex + 2)) -{ - camAddress = BitConverter::ToInt32BE(rawData, rawDataIndex + 4); - segmentOffset = GETSEGOFFSET(camAddress); -} - -std::string ActorCsCamInfo::GetSourceTypeName() const -{ - return "ActorCsCamInfo"; -} - -int32_t ActorCsCamInfo::GetRawDataSize() const -{ - return 8; -} - -int16_t ActorCsCamInfo::GetNumPoints() const -{ - return numPoints; -} - -segptr_t ActorCsCamInfo::GetCamAddress() const -{ - return camAddress; -} - -uint32_t ActorCsCamInfo::GetSegmentOffset() const -{ - return segmentOffset; -} diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetCsCamera.h b/tools/ZAPD/ZAPD/ZRoom/Commands/SetCsCamera.h deleted file mode 100644 index 2ce64e4e05..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetCsCamera.h +++ /dev/null @@ -1,40 +0,0 @@ -#pragma once - -#include "ZRoom/ZRoomCommand.h" -#include "ZVector.h" - -class ActorCsCamInfo -{ -public: - ActorCsCamInfo(const std::vector& rawData, uint32_t rawDataIndex); - - std::string GetSourceTypeName() const; - int32_t GetRawDataSize() const; - - int16_t GetNumPoints() const; - segptr_t GetCamAddress() const; - uint32_t GetSegmentOffset() const; - - int baseOffset; - int16_t type; - int16_t numPoints; - segptr_t camAddress; - uint32_t segmentOffset; -}; - -class SetCsCamera : public ZRoomCommand -{ -public: - std::vector cameras; - std::vector points; - - SetCsCamera(ZFile* nParent); - - void ParseRawData() override; - void DeclareReferences(const std::string& prefix) override; - - std::string GetBodySourceCode() const override; - - RoomCommand GetRoomCommand() const override; - std::string GetCommandCName() const override; -}; diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetCutsceneEntryList.cpp b/tools/ZAPD/ZAPD/ZRoom/Commands/SetCutsceneEntryList.cpp deleted file mode 100644 index 96c50c3be2..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetCutsceneEntryList.cpp +++ /dev/null @@ -1,103 +0,0 @@ -#include "SetCutsceneEntryList.h" - -#include "Globals.h" -#include "Utils/BitConverter.h" -#include "Utils/StringHelper.h" -#include "ZFile.h" -#include "ZRoom/ZRoom.h" - -SetActorCutsceneList::SetActorCutsceneList(ZFile* nParent) : ZRoomCommand(nParent) -{ -} - -void SetActorCutsceneList::ParseRawData() -{ - ZRoomCommand::ParseRawData(); - int numCutscenes = cmdArg1; - offset_t currentPtr = segmentOffset; - - cutscenes.reserve(numCutscenes); - for (int32_t i = 0; i < numCutscenes; i++) - { - CutsceneEntry entry(parent->GetRawData(), currentPtr); - cutscenes.push_back(entry); - - currentPtr += 16; - } -} - -void SetActorCutsceneList::DeclareReferences(const std::string& prefix) -{ - if (cutscenes.size() > 0) - { - std::string declaration; - - for (size_t i = 0; i < cutscenes.size(); i++) - { - const auto& entry = cutscenes.at(i); - declaration += StringHelper::Sprintf(" { %s },", entry.GetBodySourceCode().c_str()); - - if (i + 1 < cutscenes.size()) - { - declaration += "\n"; - } - } - - std::string typeName = cutscenes.at(0).GetSourceTypeName(); - - parent->AddDeclarationArray( - segmentOffset, GetDeclarationAlignment(), cutscenes.size() * 16, typeName, - StringHelper::Sprintf("%s%sList_%06X", prefix.c_str(), typeName.c_str(), segmentOffset), - cutscenes.size(), declaration); - } -} - -std::string SetActorCutsceneList::GetBodySourceCode() const -{ - std::string listName; - Globals::Instance->GetSegmentedPtrName(cmdArg2, parent, "CutsceneEntry", listName); - return StringHelper::Sprintf("SCENE_CMD_ACTOR_CUTSCENE_LIST(%i, %s)", cutscenes.size(), - listName.c_str()); -} - -std::string SetActorCutsceneList::GetCommandCName() const -{ - return "SCmdCutsceneActorList"; -} - -RoomCommand SetActorCutsceneList::GetRoomCommand() const -{ - return RoomCommand::SetActorCutsceneList; -} - -CutsceneEntry::CutsceneEntry(const std::vector& rawData, uint32_t rawDataIndex) - : priority(BitConverter::ToInt16BE(rawData, rawDataIndex + 0)), - length(BitConverter::ToInt16BE(rawData, rawDataIndex + 2)), - csCamId(BitConverter::ToInt16BE(rawData, rawDataIndex + 4)), - scriptIndex(BitConverter::ToInt16BE(rawData, rawDataIndex + 6)), - additionalCsId(BitConverter::ToInt16BE(rawData, rawDataIndex + 8)), - endSfx(rawData[rawDataIndex + 0xA]), customValue(rawData[rawDataIndex + 0xB]), - hudVisibility(BitConverter::ToInt16BE(rawData, rawDataIndex + 0xC)), - endCam(rawData[rawDataIndex + 0xE]), letterboxSize(rawData[rawDataIndex + 0xF]) -{ -} - -std::string CutsceneEntry::GetBodySourceCode() const -{ - EnumData* enumData = &Globals::Instance->cfg.enumData; - - if (enumData->endSfx.find(endSfx) != enumData->endSfx.end()) - return StringHelper::Sprintf("%i, %i, %i, %i, %i, %s, %i, %i, %i, %i", priority, length, - csCamId, scriptIndex, additionalCsId, - enumData->endSfx[endSfx].c_str(), customValue, hudVisibility, - endCam, letterboxSize); - else - return StringHelper::Sprintf("%i, %i, %i, %i, %i, %i, %i, %i, %i, %i", priority, length, - csCamId, scriptIndex, additionalCsId, endSfx, customValue, - hudVisibility, endCam, letterboxSize); -} - -std::string CutsceneEntry::GetSourceTypeName() const -{ - return "CutsceneEntry"; -} diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetCutsceneEntryList.h b/tools/ZAPD/ZAPD/ZRoom/Commands/SetCutsceneEntryList.h deleted file mode 100644 index 6ba6c23abc..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetCutsceneEntryList.h +++ /dev/null @@ -1,42 +0,0 @@ -#pragma once - -#include "ZRoom/ZRoomCommand.h" - -class CutsceneEntry -{ -protected: - int16_t priority; - int16_t length; - int16_t csCamId; - int16_t scriptIndex; - int16_t additionalCsId; - uint8_t endSfx; - uint8_t customValue; - int16_t hudVisibility; - uint8_t endCam; - uint8_t letterboxSize; - -public: - CutsceneEntry(const std::vector& rawData, uint32_t rawDataIndex); - - std::string GetBodySourceCode() const; - std::string GetSourceTypeName() const; -}; - -class SetActorCutsceneList : public ZRoomCommand -{ -public: - std::vector cutscenes; - - SetActorCutsceneList(ZFile* nParent); - - void ParseRawData() override; - void DeclareReferences(const std::string& prefix) override; - - std::string GetBodySourceCode() const override; - - std::string GetCommandCName() const override; - RoomCommand GetRoomCommand() const override; - -private: -}; diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetCutscenes.cpp b/tools/ZAPD/ZAPD/ZRoom/Commands/SetCutscenes.cpp deleted file mode 100644 index d2a1c19561..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetCutscenes.cpp +++ /dev/null @@ -1,134 +0,0 @@ -#include "SetCutscenes.h" - -#include "Globals.h" -#include "Utils/BitConverter.h" -#include "Utils/StringHelper.h" -#include "ZFile.h" -#include "ZRoom/ZRoom.h" - -SetCutscenes::SetCutscenes(ZFile* nParent) : ZRoomCommand(nParent) -{ -} - -void SetCutscenes::ParseRawData() -{ - ZRoomCommand::ParseRawData(); - - numCutscenes = cmdArg1; - - if (Globals::Instance->game == ZGame::MM_RETAIL) - { - int32_t currentPtr = segmentOffset; - - cutsceneEntries.reserve(numCutscenes); - for (uint8_t i = 0; i < numCutscenes; i++) - { - CutsceneScriptEntry entry(parent->GetRawData(), currentPtr); - cutsceneEntries.push_back(entry); - currentPtr += 8; - } - } -} - -void SetCutscenes::DeclareReferences(const std::string& prefix) -{ - EnumData* enumData = &Globals::Instance->cfg.enumData; - std::string varPrefix = name; - if (varPrefix == "") - varPrefix = prefix; - - if (Globals::Instance->game == ZGame::MM_RETAIL) - { - std::string declaration; - size_t i = 0; - - for (const auto& entry : cutsceneEntries) - { - if (entry.segmentPtr != SEGMENTED_NULL && - GETSEGNUM(entry.segmentPtr) == parent->segment) - { - offset_t csOffset = Seg2Filespace(entry.segmentPtr, parent->baseAddress); - if (!parent->HasDeclaration(csOffset)) - { - auto* cutscene = new ZCutscene(parent); - cutscene->ExtractFromFile(csOffset); - cutscene->SetName(cutscene->GetDefaultName(varPrefix)); - cutscene->DeclareVar(varPrefix, ""); - cutscene->DeclareReferences(varPrefix); - parent->AddResource(cutscene); - } - } - - std::string csName; - Globals::Instance->GetSegmentedPtrName(entry.segmentPtr, parent, "CutsceneData", - csName); - - if (enumData->spawnFlag.find(entry.flag) != enumData->spawnFlag.end()) - declaration += StringHelper::Sprintf(" { %s, 0x%04X, 0x%02X, %s },", - csName.c_str(), entry.exit, entry.entrance, - enumData->spawnFlag[entry.flag].c_str()); - else - declaration += - StringHelper::Sprintf(" { %s, 0x%04X, 0x%02X, 0x%02X },", csName.c_str(), - entry.exit, entry.entrance, entry.flag); - if (i + 1 < numCutscenes) - declaration += "\n"; - - i++; - } - - parent->AddDeclarationArray(segmentOffset, DeclarationAlignment::Align4, - cutsceneEntries.size() * 8, "CutsceneScriptEntry", - StringHelper::Sprintf("%sCutsceneScriptEntryList_%06X", - zRoom->GetName().c_str(), segmentOffset), - cutsceneEntries.size(), declaration); - } - else - { - if (cmdArg2 != SEGMENTED_NULL && GETSEGNUM(cmdArg2) == parent->segment) - { - offset_t csOffset = Seg2Filespace(cmdArg2, parent->baseAddress); - if (!parent->HasDeclaration(csOffset)) - { - auto* cutscene = new ZCutscene(parent); - cutscene->ExtractFromFile(csOffset); - cutscene->SetName(cutscene->GetDefaultName(varPrefix)); - cutscene->DeclareVar(varPrefix, ""); - cutscene->DeclareReferences(varPrefix); - parent->AddResource(cutscene); - } - } - } -} - -std::string SetCutscenes::GetBodySourceCode() const -{ - std::string listName; - - if (Globals::Instance->game == ZGame::MM_RETAIL) - { - Globals::Instance->GetSegmentedPtrName(cmdArg2, parent, "CutsceneScriptEntry", listName); - return StringHelper::Sprintf("SCENE_CMD_CUTSCENE_SCRIPT_LIST(%i, %s)", numCutscenes, - listName.c_str()); - } - - Globals::Instance->GetSegmentedPtrName(cmdArg2, parent, "CutsceneData", listName); - return StringHelper::Sprintf("SCENE_CMD_CUTSCENE_DATA(%s)", listName.c_str()); -} - -std::string SetCutscenes::GetCommandCName() const -{ - return "SCmdCutsceneData"; -} - -RoomCommand SetCutscenes::GetRoomCommand() const -{ - return RoomCommand::SetCutscenes; -} - -CutsceneScriptEntry::CutsceneScriptEntry(const std::vector& rawData, uint32_t rawDataIndex) - : segmentPtr(BitConverter::ToInt32BE(rawData, rawDataIndex + 0)), - exit(BitConverter::ToInt16BE(rawData, rawDataIndex + 4)), entrance(rawData[rawDataIndex + 6]), - flag(rawData[rawDataIndex + 7]) -{ -} diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetCutscenes.h b/tools/ZAPD/ZAPD/ZRoom/Commands/SetCutscenes.h deleted file mode 100644 index e6d979d0f6..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetCutscenes.h +++ /dev/null @@ -1,32 +0,0 @@ -#pragma once - -#include "ZCutscene.h" -#include "ZRoom/ZRoomCommand.h" - -class CutsceneScriptEntry -{ -public: - CutsceneScriptEntry(const std::vector& rawData, uint32_t rawDataIndex); - - segptr_t segmentPtr; - uint16_t exit; - uint8_t entrance; - uint8_t flag; -}; - -class SetCutscenes : public ZRoomCommand -{ -public: - std::vector cutsceneEntries; // (MM Only) - uint8_t numCutscenes; // (MM Only) - - SetCutscenes(ZFile* nParent); - - void ParseRawData() override; - void DeclareReferences(const std::string& prefix) override; - - std::string GetBodySourceCode() const override; - - RoomCommand GetRoomCommand() const override; - std::string GetCommandCName() const override; -}; diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetEchoSettings.cpp b/tools/ZAPD/ZAPD/ZRoom/Commands/SetEchoSettings.cpp deleted file mode 100644 index 79a278bc69..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetEchoSettings.cpp +++ /dev/null @@ -1,27 +0,0 @@ -#include "SetEchoSettings.h" -#include "Utils/StringHelper.h" - -SetEchoSettings::SetEchoSettings(ZFile* nParent) : ZRoomCommand(nParent) -{ -} - -void SetEchoSettings::ParseRawData() -{ - ZRoomCommand::ParseRawData(); - echo = parent->GetRawData().at(rawDataIndex + 0x07); -} - -std::string SetEchoSettings::GetBodySourceCode() const -{ - return StringHelper::Sprintf("SCENE_CMD_ECHO_SETTINGS(%i)", echo); -} - -std::string SetEchoSettings::GetCommandCName() const -{ - return "SCmdEchoSettings"; -} - -RoomCommand SetEchoSettings::GetRoomCommand() const -{ - return RoomCommand::SetEchoSettings; -} diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetEchoSettings.h b/tools/ZAPD/ZAPD/ZRoom/Commands/SetEchoSettings.h deleted file mode 100644 index 82b8c27dbc..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetEchoSettings.h +++ /dev/null @@ -1,18 +0,0 @@ -#pragma once - -#include "ZRoom/ZRoomCommand.h" - -class SetEchoSettings : public ZRoomCommand -{ -public: - uint8_t echo; - - SetEchoSettings(ZFile* nParent); - - void ParseRawData() override; - - std::string GetBodySourceCode() const override; - - std::string GetCommandCName() const override; - RoomCommand GetRoomCommand() const override; -}; diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetEntranceList.cpp b/tools/ZAPD/ZAPD/ZRoom/Commands/SetEntranceList.cpp deleted file mode 100644 index 3ffba0ff12..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetEntranceList.cpp +++ /dev/null @@ -1,99 +0,0 @@ -#include "SetEntranceList.h" - -#include "Globals.h" -#include "SetStartPositionList.h" -#include "Utils/BitConverter.h" -#include "Utils/StringHelper.h" -#include "ZFile.h" -#include "ZRoom/ZRoom.h" - -SetEntranceList::SetEntranceList(ZFile* nParent) : ZRoomCommand(nParent) -{ -} - -void SetEntranceList::DeclareReferences([[maybe_unused]] const std::string& prefix) -{ - if (segmentOffset != 0) - { - std::string varName = - StringHelper::Sprintf("%sEntranceList0x%06X", prefix.c_str(), segmentOffset); - parent->AddDeclarationPlaceholder(segmentOffset, varName); - } -} - -void SetEntranceList::ParseRawDataLate() -{ - // Parse Entrances and Generate Declaration - uint32_t numEntrances = zRoom->parent->GetDeclarationSizeFromNeighbor(segmentOffset) / 2; - uint32_t currentPtr = segmentOffset; - - entrances.reserve(numEntrances); - for (uint32_t i = 0; i < numEntrances; i++) - { - Spawn entry(parent->GetRawData(), currentPtr); - entrances.push_back(entry); - - currentPtr += 2; - } -} - -void SetEntranceList::DeclareReferencesLate([[maybe_unused]] const std::string& prefix) -{ - if (!entrances.empty()) - { - std::string declaration; - - size_t index = 0; - for (const auto& entry : entrances) - { - declaration += StringHelper::Sprintf(" { %s },", entry.GetBodySourceCode().c_str()); - if (index + 1 < entrances.size()) - declaration += "\n"; - - index++; - } - - std::string varName = - StringHelper::Sprintf("%sEntranceList0x%06X", prefix.c_str(), segmentOffset); - - if (Globals::Instance->game != ZGame::MM_RETAIL) - parent->AddDeclarationArray(segmentOffset, DeclarationAlignment::Align4, - entrances.size() * 2, "Spawn", varName, entrances.size(), - declaration); - else - parent->AddDeclarationArray(segmentOffset, DeclarationAlignment::Align4, - entrances.size() * 2, "EntranceEntry", varName, - entrances.size(), declaration); - } -} - -std::string SetEntranceList::GetBodySourceCode() const -{ - std::string listName; - if (Globals::Instance->game != ZGame::MM_RETAIL) - Globals::Instance->GetSegmentedPtrName(cmdArg2, parent, "Spawn", listName); - else - Globals::Instance->GetSegmentedPtrName(cmdArg2, parent, "EntranceEntry", listName); - return StringHelper::Sprintf("SCENE_CMD_ENTRANCE_LIST(%s)", listName.c_str()); -} - -std::string SetEntranceList::GetCommandCName() const -{ - return "SCmdEntranceList"; -} - -RoomCommand SetEntranceList::GetRoomCommand() const -{ - return RoomCommand::SetEntranceList; -} - -Spawn::Spawn(const std::vector& rawData, uint32_t rawDataIndex) -{ - startPositionIndex = rawData.at(rawDataIndex + 0); - roomToLoad = rawData.at(rawDataIndex + 1); -} - -std::string Spawn::GetBodySourceCode() const -{ - return StringHelper::Sprintf("0x%02X, 0x%02X", startPositionIndex, roomToLoad); -} diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetEntranceList.h b/tools/ZAPD/ZAPD/ZRoom/Commands/SetEntranceList.h deleted file mode 100644 index 832232e06b..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetEntranceList.h +++ /dev/null @@ -1,31 +0,0 @@ -#pragma once - -#include "ZRoom/ZRoomCommand.h" - -class Spawn -{ -public: - uint8_t startPositionIndex; - uint8_t roomToLoad; - - Spawn(const std::vector& rawData, uint32_t rawDataIndex); - - std::string GetBodySourceCode() const; -}; - -class SetEntranceList : public ZRoomCommand -{ -public: - std::vector entrances; - - SetEntranceList(ZFile* nParent); - - void DeclareReferences(const std::string& prefix) override; - void ParseRawDataLate() override; - void DeclareReferencesLate(const std::string& prefix) override; - - std::string GetBodySourceCode() const override; - - RoomCommand GetRoomCommand() const override; - std::string GetCommandCName() const override; -}; diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetExitList.cpp b/tools/ZAPD/ZAPD/ZRoom/Commands/SetExitList.cpp deleted file mode 100644 index 78bbaa87ed..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetExitList.cpp +++ /dev/null @@ -1,76 +0,0 @@ -#include "SetExitList.h" - -#include "Globals.h" -#include "Utils/BitConverter.h" -#include "Utils/StringHelper.h" -#include "ZFile.h" -#include "ZRoom/ZNames.h" -#include "ZRoom/ZRoom.h" - -SetExitList::SetExitList(ZFile* nParent) : ZRoomCommand(nParent) -{ -} - -void SetExitList::DeclareReferences([[maybe_unused]] const std::string& prefix) -{ - if (segmentOffset != 0) - { - std::string varName = - StringHelper::Sprintf("%sExitList_%06X", prefix.c_str(), segmentOffset); - parent->AddDeclarationPlaceholder(segmentOffset, varName); - } -} - -void SetExitList::ParseRawDataLate() -{ - // Parse Entrances and Generate Declaration - uint32_t numEntrances = zRoom->parent->GetDeclarationSizeFromNeighbor(segmentOffset) / 2; - uint32_t currentPtr = segmentOffset; - - exits.reserve(numEntrances); - for (uint32_t i = 0; i < numEntrances; i++) - { - uint16_t exit = BitConverter::ToUInt16BE(parent->GetRawData(), currentPtr); - exits.push_back(exit); - - currentPtr += 2; - } -} - -void SetExitList::DeclareReferencesLate([[maybe_unused]] const std::string& prefix) -{ - if (!exits.empty()) - { - std::string declaration; - - for (size_t i = 0; i < exits.size(); i++) - { - declaration += - StringHelper::Sprintf(" %s,", ZNames::GetEntranceName(exits[i]).c_str()); - if (i + 1 < exits.size()) - declaration += "\n"; - } - - std::string varName = - StringHelper::Sprintf("%sExitList_%06X", prefix.c_str(), segmentOffset); - parent->AddDeclarationArray(segmentOffset, DeclarationAlignment::Align4, exits.size() * 2, - "u16", varName, exits.size(), declaration); - } -} - -std::string SetExitList::GetBodySourceCode() const -{ - std::string listName; - Globals::Instance->GetSegmentedPtrName(cmdArg2, parent, "u16", listName); - return StringHelper::Sprintf("SCENE_CMD_EXIT_LIST(%s)", listName.c_str()); -} - -std::string SetExitList::GetCommandCName() const -{ - return "SCmdExitList"; -} - -RoomCommand SetExitList::GetRoomCommand() const -{ - return RoomCommand::SetExitList; -} diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetExitList.h b/tools/ZAPD/ZAPD/ZRoom/Commands/SetExitList.h deleted file mode 100644 index 9d2791a83d..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetExitList.h +++ /dev/null @@ -1,20 +0,0 @@ -#pragma once - -#include "ZRoom/ZRoomCommand.h" - -class SetExitList : public ZRoomCommand -{ -public: - std::vector exits; - - SetExitList(ZFile* nParent); - - void DeclareReferences(const std::string& prefix) override; - void ParseRawDataLate() override; - void DeclareReferencesLate(const std::string& prefix) override; - - std::string GetBodySourceCode() const override; - - RoomCommand GetRoomCommand() const override; - std::string GetCommandCName() const override; -}; diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetLightList.cpp b/tools/ZAPD/ZAPD/ZRoom/Commands/SetLightList.cpp deleted file mode 100644 index 0d0f0ff79a..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetLightList.cpp +++ /dev/null @@ -1,99 +0,0 @@ -#include "SetLightList.h" - -#include "Globals.h" -#include "Utils/BitConverter.h" -#include "Utils/StringHelper.h" - -SetLightList::SetLightList(ZFile* nParent) : ZRoomCommand(nParent) -{ -} - -void SetLightList::ParseRawData() -{ - ZRoomCommand::ParseRawData(); - std::string declarations; - - numLights = cmdArg1; - int32_t currentPtr = segmentOffset; - - lights.reserve(this->numLights); - for (int i = 0; i < this->numLights; i++) - { - LightInfo light(parent->GetRawData(), currentPtr); - - currentPtr += light.GetRawDataSize(); - lights.push_back(light); - } -} - -void SetLightList::DeclareReferences(const std::string& prefix) -{ - if (!lights.empty()) - { - std::string declarations; - - for (size_t i = 0; i < lights.size(); i++) - { - declarations += - StringHelper::Sprintf("\t{ %s },", lights.at(i).GetBodySourceCode().c_str()); - - if (i < lights.size() - 1) - declarations += "\n"; - } - - const auto& light = lights.front(); - - parent->AddDeclarationArray( - segmentOffset, DeclarationAlignment::Align4, lights.size() * light.GetRawDataSize(), - light.GetSourceTypeName(), - StringHelper::Sprintf("%sLightInfo0x%06X", prefix.c_str(), segmentOffset), - lights.size(), declarations); - } -} - -std::string SetLightList::GetBodySourceCode() const -{ - std::string listName; - Globals::Instance->GetSegmentedPtrName(cmdArg2, parent, "LightInfo", listName); - return StringHelper::Sprintf("SCENE_CMD_LIGHT_LIST(%i, %s)", numLights, listName.c_str()); -} - -std::string SetLightList::GetCommandCName() const -{ - return "SCmdLightList"; -} - -RoomCommand SetLightList::GetRoomCommand() const -{ - return RoomCommand::SetLightList; -} - -LightInfo::LightInfo(const std::vector& rawData, uint32_t rawDataIndex) -{ - type = BitConverter::ToUInt8BE(rawData, rawDataIndex + 0); - x = BitConverter::ToInt16BE(rawData, rawDataIndex + 2); - y = BitConverter::ToInt16BE(rawData, rawDataIndex + 4); - z = BitConverter::ToInt16BE(rawData, rawDataIndex + 6); - r = BitConverter::ToUInt8BE(rawData, rawDataIndex + 8); - g = BitConverter::ToUInt8BE(rawData, rawDataIndex + 9); - b = BitConverter::ToUInt8BE(rawData, rawDataIndex + 10); - drawGlow = BitConverter::ToUInt8BE(rawData, rawDataIndex + 11); - radius = BitConverter::ToInt16BE(rawData, rawDataIndex + 12); -} - -std::string LightInfo::GetBodySourceCode() const -{ - return StringHelper::Sprintf( - "0x%02X, { %i, %i, %i, { 0x%02X, 0x%02X, 0x%02X }, 0x%02X, 0x%04X }", type, x, y, z, r, g, - b, drawGlow, radius); -} - -std::string LightInfo::GetSourceTypeName() const -{ - return "LightInfo"; -} - -size_t LightInfo::GetRawDataSize() const -{ - return 0x0E; -} diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetLightList.h b/tools/ZAPD/ZAPD/ZRoom/Commands/SetLightList.h deleted file mode 100644 index c089d82a54..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetLightList.h +++ /dev/null @@ -1,42 +0,0 @@ -#pragma once - -#include - -#include "ZFile.h" -#include "ZRoom/ZRoom.h" -#include "ZRoom/ZRoomCommand.h" - -class LightInfo -{ -public: - LightInfo(const std::vector& rawData, uint32_t rawDataIndex); - - std::string GetBodySourceCode() const; - - std::string GetSourceTypeName() const; - size_t GetRawDataSize() const; - -protected: - uint8_t type; - int16_t x, y, z; - uint8_t r, g, b; - uint8_t drawGlow; - int16_t radius; -}; - -class SetLightList : public ZRoomCommand -{ -public: - uint8_t numLights; - std::vector lights; - - SetLightList(ZFile* nParent); - - void ParseRawData() override; - void DeclareReferences(const std::string& prefix) override; - - std::string GetBodySourceCode() const override; - - RoomCommand GetRoomCommand() const override; - std::string GetCommandCName() const override; -}; diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetLightingSettings.cpp b/tools/ZAPD/ZAPD/ZRoom/Commands/SetLightingSettings.cpp deleted file mode 100644 index eaf01cd4c4..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetLightingSettings.cpp +++ /dev/null @@ -1,116 +0,0 @@ -#include "SetLightingSettings.h" - -#include "Globals.h" -#include "Utils/BitConverter.h" -#include "Utils/StringHelper.h" -#include "ZFile.h" -#include "ZRoom/ZRoom.h" - -SetLightingSettings::SetLightingSettings(ZFile* nParent) : ZRoomCommand(nParent) -{ -} - -void SetLightingSettings::ParseRawData() -{ - ZRoomCommand::ParseRawData(); - uint8_t numLights = cmdArg1; - - settings.reserve(numLights); - for (int i = 0; i < numLights; i++) - settings.push_back(LightingSettings(parent->GetRawData(), segmentOffset + (i * 22))); -} - -void SetLightingSettings::DeclareReferences(const std::string& prefix) -{ - if (settings.size() > 0) - { - std::string declaration; - - for (size_t i = 0; i < settings.size(); i++) - { - declaration += - StringHelper::Sprintf("\t{ %s },", settings.at(i).GetBodySourceCode().c_str()); - if (i + 1 < settings.size()) - declaration += "\n"; - } - - if (Globals::Instance->game != ZGame::MM_RETAIL) - parent->AddDeclarationArray( - segmentOffset, DeclarationAlignment::Align4, - settings.size() * settings.front().GetRawDataSize(), "EnvLightSettings", - StringHelper::Sprintf("%sLightSettings0x%06X", prefix.c_str(), segmentOffset), - settings.size(), declaration); - else - parent->AddDeclarationArray( - segmentOffset, DeclarationAlignment::Align4, - settings.size() * settings.front().GetRawDataSize(), "LightSettings", - StringHelper::Sprintf("%sLightSettings0x%06X", prefix.c_str(), segmentOffset), - settings.size(), declaration); - } -} - -std::string SetLightingSettings::GetBodySourceCode() const -{ - std::string listName; - if (Globals::Instance->game != ZGame::MM_RETAIL) - Globals::Instance->GetSegmentedPtrName(cmdArg2, parent, "EnvLightSettings", listName); - else - Globals::Instance->GetSegmentedPtrName(cmdArg2, parent, "LightSettings", listName); - return StringHelper::Sprintf("SCENE_CMD_ENV_LIGHT_SETTINGS(%i, %s)", settings.size(), - listName.c_str()); -} - -std::string SetLightingSettings::GetCommandCName() const -{ - return "SCmdLightSettingList"; -} - -RoomCommand SetLightingSettings::GetRoomCommand() const -{ - return RoomCommand::SetLightingSettings; -} - -LightingSettings::LightingSettings(const std::vector& rawData, uint32_t rawDataIndex) -{ - ambientClrR = rawData.at(rawDataIndex + 0); - ambientClrG = rawData.at(rawDataIndex + 1); - ambientClrB = rawData.at(rawDataIndex + 2); - - diffuseClrA_R = rawData.at(rawDataIndex + 3); - diffuseClrA_G = rawData.at(rawDataIndex + 4); - diffuseClrA_B = rawData.at(rawDataIndex + 5); - - diffuseDirA_X = rawData.at(rawDataIndex + 6); - diffuseDirA_Y = rawData.at(rawDataIndex + 7); - diffuseDirA_Z = rawData.at(rawDataIndex + 8); - - diffuseClrB_R = rawData.at(rawDataIndex + 9); - diffuseClrB_G = rawData.at(rawDataIndex + 10); - diffuseClrB_B = rawData.at(rawDataIndex + 11); - - diffuseDirB_X = rawData.at(rawDataIndex + 12); - diffuseDirB_Y = rawData.at(rawDataIndex + 13); - diffuseDirB_Z = rawData.at(rawDataIndex + 14); - - fogClrR = rawData.at(rawDataIndex + 15); - fogClrG = rawData.at(rawDataIndex + 16); - fogClrB = rawData.at(rawDataIndex + 17); - - unk = BitConverter::ToInt16BE(rawData, rawDataIndex + 18); - drawDistance = BitConverter::ToInt16BE(rawData, rawDataIndex + 20); -} - -std::string LightingSettings::GetBodySourceCode() const -{ - return StringHelper::Sprintf( - "0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, " - "0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%04X, 0x%04X", - ambientClrR, ambientClrG, ambientClrB, diffuseClrA_R, diffuseClrA_G, diffuseClrA_B, - diffuseDirA_X, diffuseDirA_Y, diffuseDirA_Z, diffuseClrB_R, diffuseClrB_G, diffuseClrB_B, - diffuseDirB_X, diffuseDirB_Y, diffuseDirB_Z, fogClrR, fogClrG, fogClrB, unk, drawDistance); -} - -size_t LightingSettings::GetRawDataSize() const -{ - return 0x16; -} diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetLightingSettings.h b/tools/ZAPD/ZAPD/ZRoom/Commands/SetLightingSettings.h deleted file mode 100644 index 29caf4aa6a..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetLightingSettings.h +++ /dev/null @@ -1,38 +0,0 @@ -#pragma once - -#include "ZRoom/ZRoomCommand.h" - -class LightingSettings -{ -public: - uint8_t ambientClrR, ambientClrG, ambientClrB; - uint8_t diffuseClrA_R, diffuseClrA_G, diffuseClrA_B; - uint8_t diffuseDirA_X, diffuseDirA_Y, diffuseDirA_Z; - uint8_t diffuseClrB_R, diffuseClrB_G, diffuseClrB_B; - uint8_t diffuseDirB_X, diffuseDirB_Y, diffuseDirB_Z; - uint8_t fogClrR, fogClrG, fogClrB; - uint16_t unk; - uint16_t drawDistance; - - LightingSettings(const std::vector& rawData, uint32_t rawDataIndex); - - std::string GetBodySourceCode() const; - - size_t GetRawDataSize() const; -}; - -class SetLightingSettings : public ZRoomCommand -{ -public: - std::vector settings; - - SetLightingSettings(ZFile* nParent); - - void ParseRawData() override; - void DeclareReferences(const std::string& prefix) override; - - std::string GetBodySourceCode() const override; - - RoomCommand GetRoomCommand() const override; - std::string GetCommandCName() const override; -}; diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetMesh.cpp b/tools/ZAPD/ZAPD/ZRoom/Commands/SetMesh.cpp deleted file mode 100644 index 9a4d30d516..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetMesh.cpp +++ /dev/null @@ -1,617 +0,0 @@ -#include "SetMesh.h" - -#include "Globals.h" -#include "Utils/BitConverter.h" -#include "Utils/Path.h" -#include "Utils/StringHelper.h" -#include "WarningHandler.h" -#include "ZBackground.h" -#include "ZFile.h" -#include "ZRoom/ZRoom.h" - -void GenDListDeclarations(ZRoom* zRoom, ZFile* parent, ZDisplayList* dList); - -SetMesh::SetMesh(ZFile* nParent) : ZRoomCommand(nParent) -{ -} - -void SetMesh::ParseRawData() -{ - ZRoomCommand::ParseRawData(); - auto& parentRawData = parent->GetRawData(); - meshHeaderType = parentRawData.at(segmentOffset); - - switch (meshHeaderType) - { - case 0: - polyType = std::make_shared(parent, segmentOffset, zRoom); - break; - - case 1: - polyType = std::make_shared(parent, segmentOffset, zRoom); - break; - - case 2: - polyType = std::make_shared(parent, segmentOffset, zRoom); - break; - - default: - HANDLE_ERROR(WarningType::InvalidExtractedData, - StringHelper::Sprintf("unknown meshHeaderType: %i", meshHeaderType), ""); - } - - polyType->ParseRawData(); -} - -void SetMesh::DeclareReferences(const std::string& prefix) -{ - polyType->SetName(polyType->GetDefaultName(prefix)); - polyType->DeclareReferences(prefix); - polyType->DeclareAndGenerateOutputCode(prefix); -} - -// TODO: is this really needed? -void GenDListDeclarations(ZRoom* zRoom, ZFile* parent, ZDisplayList* dList) -{ - if (dList == nullptr) - return; - - dList->DeclareReferences(zRoom->GetName()); - - for (ZDisplayList* otherDList : dList->otherDLists) - GenDListDeclarations(zRoom, parent, otherDList); -} - -std::string SetMesh::GenDListExterns(ZDisplayList* dList) -{ - std::string sourceOutput; - - sourceOutput += StringHelper::Sprintf("extern Gfx %sDL_%06X[];\n", zRoom->GetName().c_str(), - dList->GetRawDataIndex()); - - for (ZDisplayList* otherDList : dList->otherDLists) - sourceOutput += GenDListExterns(otherDList); - - return sourceOutput; -} - -std::string SetMesh::GetBodySourceCode() const -{ - std::string list; - Globals::Instance->GetSegmentedPtrName(cmdArg2, parent, "", list); - return StringHelper::Sprintf("SCENE_CMD_ROOM_SHAPE(%s)", list.c_str()); -} - -std::string SetMesh::GetCommandCName() const -{ - return "SCmdMesh"; -} - -RoomCommand SetMesh::GetRoomCommand() const -{ - return RoomCommand::SetMesh; -} - -RoomShapeDListsEntry::RoomShapeDListsEntry(ZFile* nParent) : ZResource(nParent) -{ -} - -void RoomShapeDListsEntry::ParseRawData() -{ - const auto& rawData = parent->GetRawData(); - switch (polyType) - { - case 2: - x = BitConverter::ToInt16BE(rawData, rawDataIndex + 0); - y = BitConverter::ToInt16BE(rawData, rawDataIndex + 2); - z = BitConverter::ToInt16BE(rawData, rawDataIndex + 4); - unk_06 = BitConverter::ToInt16BE(rawData, rawDataIndex + 6); - - opa = BitConverter::ToUInt32BE(rawData, rawDataIndex + 8); - xlu = BitConverter::ToUInt32BE(rawData, rawDataIndex + 12); - break; - - default: - opa = BitConverter::ToUInt32BE(rawData, rawDataIndex); - xlu = BitConverter::ToUInt32BE(rawData, rawDataIndex + 4); - break; - } -} - -void RoomShapeDListsEntry::DeclareReferences(const std::string& prefix) -{ - opaDList = MakeDlist(opa, prefix); - xluDList = MakeDlist(xlu, prefix); -} - -std::string RoomShapeDListsEntry::GetBodySourceCode() const -{ - std::string bodyStr; - std::string opaStr; - std::string xluStr; - Globals::Instance->GetSegmentedPtrName(opa, parent, "Gfx", opaStr); - Globals::Instance->GetSegmentedPtrName(xlu, parent, "Gfx", xluStr); - - if (polyType == 2) - { - bodyStr += StringHelper::Sprintf("{ %6i, %6i, %6i }, %6i, ", x, y, z, unk_06); - } - - bodyStr += StringHelper::Sprintf("%s, %s", opaStr.c_str(), xluStr.c_str()); - - return bodyStr; -} - -void RoomShapeDListsEntry::GetSourceOutputCode(const std::string& prefix) -{ - std::string bodyStr = StringHelper::Sprintf("\n\t%s\n", GetBodySourceCode().c_str()); - - Declaration* decl = parent->GetDeclaration(rawDataIndex); - - if (decl == nullptr) - DeclareVar(prefix, bodyStr); - else - decl->declBody = bodyStr; -} - -std::string RoomShapeDListsEntry::GetSourceTypeName() const -{ - switch (polyType) - { - case 2: - return "RoomShapeCullableEntry"; - - default: - return "RoomShapeDListsEntry"; - } -} - -ZResourceType RoomShapeDListsEntry::GetResourceType() const -{ - // TODO - return ZResourceType::Error; -} - -size_t RoomShapeDListsEntry::GetRawDataSize() const -{ - switch (polyType) - { - case 2: - return 0x10; - - default: - return 0x08; - } -} - -void RoomShapeDListsEntry::SetPolyType(uint8_t nPolyType) -{ - polyType = nPolyType; -} - -ZDisplayList* RoomShapeDListsEntry::MakeDlist(segptr_t ptr, - [[maybe_unused]] const std::string& prefix) -{ - if (ptr == 0) - { - return nullptr; - } - - uint32_t dlistAddress = Seg2Filespace(ptr, parent->baseAddress); - - int32_t dlistLength = ZDisplayList::GetDListLength( - parent->GetRawData(), dlistAddress, - Globals::Instance->game == ZGame::OOT_SW97 ? DListType::F3DEX : DListType::F3DZEX); - ZDisplayList* dlist = new ZDisplayList(parent); - parent->AddResource(dlist); - dlist->ExtractFromBinary(dlistAddress, dlistLength); - dlist->SetName(dlist->GetDefaultName(prefix)); - GenDListDeclarations(zRoom, parent, dlist); - - return dlist; -} - -/* RoomShapeImageMultiBgEntry */ - -RoomShapeImageMultiBgEntry::RoomShapeImageMultiBgEntry(ZFile* nParent) : ZResource(nParent) -{ -} - -RoomShapeImageMultiBgEntry::RoomShapeImageMultiBgEntry(bool nIsSubStruct, const std::string& prefix, - uint32_t nRawDataIndex, ZFile* nParent) - : RoomShapeImageMultiBgEntry(nParent) -{ - rawDataIndex = nRawDataIndex; - parent = nParent; - isSubStruct = nIsSubStruct; - - name = GetDefaultName(prefix); - - ParseRawData(); - sourceBackground = MakeBackground(source, prefix); -} - -void RoomShapeImageMultiBgEntry::ParseRawData() -{ - size_t pad = 0x00; - const auto& rawData = parent->GetRawData(); - if (!isSubStruct) - { - pad = 0x04; - - unk_00 = BitConverter::ToUInt16BE(rawData, rawDataIndex + 0x00); - id = BitConverter::ToUInt8BE(rawData, rawDataIndex + 0x02); - } - source = BitConverter::ToUInt32BE(rawData, rawDataIndex + pad + 0x00); - unk_0C = BitConverter::ToUInt32BE(rawData, rawDataIndex + pad + 0x04); - tlut = BitConverter::ToUInt32BE(rawData, rawDataIndex + pad + 0x08); - width = BitConverter::ToUInt16BE(rawData, rawDataIndex + pad + 0x0C); - height = BitConverter::ToUInt16BE(rawData, rawDataIndex + pad + 0x0E); - fmt = BitConverter::ToUInt8BE(rawData, rawDataIndex + pad + 0x10); - siz = BitConverter::ToUInt8BE(rawData, rawDataIndex + pad + 0x11); - mode0 = BitConverter::ToUInt16BE(rawData, rawDataIndex + pad + 0x12); - tlutCount = BitConverter::ToUInt16BE(rawData, rawDataIndex + pad + 0x14); -} - -ZBackground* RoomShapeImageMultiBgEntry::MakeBackground(segptr_t ptr, const std::string& prefix) -{ - if (ptr == 0) - return nullptr; - - uint32_t backAddress = Seg2Filespace(ptr, parent->baseAddress); - - ZBackground* background = new ZBackground(parent); - background->ExtractFromFile(backAddress); - - std::string defaultName = background->GetDefaultName(prefix); - background->SetName(defaultName); - background->SetOutName(defaultName); - - background->DeclareVar(prefix, ""); - parent->resources.push_back(background); - - return background; -} - -size_t RoomShapeImageMultiBgEntry::GetRawDataSize() const -{ - return 0x1C; -} - -std::string RoomShapeImageMultiBgEntry::GetBodySourceCode() const -{ - std::string bodyStr = " "; - if (!isSubStruct) - { - bodyStr += "{ \n "; - } - - if (!isSubStruct) - { - bodyStr += StringHelper::Sprintf("0x%04X, ", unk_00); - bodyStr += StringHelper::Sprintf("%i, ", id); - bodyStr += "\n "; - bodyStr += " "; - } - - std::string backgroundName; - Globals::Instance->GetSegmentedPtrName(source, parent, "", backgroundName); - bodyStr += StringHelper::Sprintf("%s, ", backgroundName.c_str()); - bodyStr += "\n "; - if (!isSubStruct) - { - bodyStr += " "; - } - - bodyStr += StringHelper::Sprintf("0x%08X, ", unk_0C); - bodyStr += StringHelper::Sprintf("0x%08X, ", tlut); - bodyStr += "\n "; - if (!isSubStruct) - { - bodyStr += " "; - } - - bodyStr += StringHelper::Sprintf("%i, ", width); - bodyStr += StringHelper::Sprintf("%i, ", height); - bodyStr += "\n "; - if (!isSubStruct) - { - bodyStr += " "; - } - - bodyStr += StringHelper::Sprintf("%i, ", fmt); - bodyStr += StringHelper::Sprintf("%i, ", siz); - bodyStr += "\n "; - if (!isSubStruct) - { - bodyStr += " "; - } - - bodyStr += StringHelper::Sprintf("0x%04X, ", mode0); - bodyStr += StringHelper::Sprintf("0x%04X, ", tlutCount); - if (!isSubStruct) - { - bodyStr += " \n }, "; - } - else - { - bodyStr += "\n"; - } - - return bodyStr; -} - -std::string RoomShapeImageMultiBgEntry::GetSourceTypeName() const -{ - return "RoomShapeImageMultiBgEntry"; -} - -ZResourceType RoomShapeImageMultiBgEntry::GetResourceType() const -{ - // TODO - return ZResourceType::Error; -} - -/* PolygonType section */ - -PolygonTypeBase::PolygonTypeBase(ZFile* nParent, uint32_t nRawDataIndex, ZRoom* nRoom) - : ZResource(nParent), zRoom{nRoom} -{ - rawDataIndex = nRawDataIndex; - type = BitConverter::ToUInt8BE(parent->GetRawData(), rawDataIndex); -} - -void PolygonTypeBase::DeclareAndGenerateOutputCode(const std::string& prefix) -{ - std::string bodyStr = GetBodySourceCode(); - - Declaration* decl = parent->GetDeclaration(rawDataIndex); - if (decl == nullptr) - { - DeclareVar(prefix, bodyStr); - } - else - { - decl->declBody = bodyStr; - } -} - -std::string PolygonTypeBase::GetSourceTypeName() const -{ - switch (type) - { - case 2: - return "RoomShapeCullable"; - - case 1: - return "PolygonType1"; - - default: - return "RoomShapeNormal"; - } -} - -ZResourceType PolygonTypeBase::GetResourceType() const -{ - // TODO - return ZResourceType::Error; -} - -PolygonType1::PolygonType1(ZFile* nParent, uint32_t nRawDataIndex, ZRoom* nRoom) - : PolygonTypeBase(nParent, nRawDataIndex, nRoom), single(nParent) -{ -} - -void PolygonType1::ParseRawData() -{ - const auto& rawData = parent->GetRawData(); - - format = BitConverter::ToUInt8BE(rawData, rawDataIndex + 0x01); - dlist = BitConverter::ToUInt32BE(rawData, rawDataIndex + 0x04); - - if (format == 2) - { - count = BitConverter::ToUInt8BE(rawData, rawDataIndex + 0x08); - list = BitConverter::ToUInt32BE(rawData, rawDataIndex + 0x0C); - } - - if (dlist != 0) - { - RoomShapeDListsEntry polyGfxList(parent); - polyGfxList.zRoom = zRoom; - polyGfxList.SetPolyType(type); - polyGfxList.ExtractFromFile(Seg2Filespace(dlist, parent->baseAddress)); - polyGfxList.DeclareReferences(zRoom->GetName()); - polyDLists.push_back(polyGfxList); - } -} - -void PolygonType1::DeclareReferences(const std::string& prefix) -{ - polyDLists.at(0).GetSourceOutputCode(prefix); - - uint32_t listAddress; - std::string bgImageArrayBody; - switch (format) - { - case 1: - single = RoomShapeImageMultiBgEntry(true, prefix, rawDataIndex + 0x08, parent); - break; - - case 2: - if (list != 0) - { - listAddress = Seg2Filespace(list, parent->baseAddress); - uint32_t auxPtr = listAddress; - - multiList.reserve(count); - for (size_t i = 0; i < count; ++i) - { - RoomShapeImageMultiBgEntry bg(false, prefix, auxPtr, parent); - multiList.push_back(bg); - auxPtr += bg.GetRawDataSize(); - bgImageArrayBody += bg.GetBodySourceCode(); - if (i + 1 < count) - { - bgImageArrayBody += "\n"; - } - } - - Declaration* decl = parent->GetDeclaration(listAddress); - if (decl == nullptr) - { - parent->AddDeclarationArray( - listAddress, DeclarationAlignment::Align4, - count * multiList.at(0).GetRawDataSize(), multiList.at(0).GetSourceTypeName(), - multiList.at(0).GetName().c_str(), count, bgImageArrayBody); - } - } - break; - - default: - HANDLE_ERROR(WarningType::InvalidExtractedData, - StringHelper::Sprintf("unknown format: %i", format), ""); - break; - } -} - -size_t PolygonType1::GetRawDataSize() const -{ - switch (format) - { - case 1: - return 0x20; - - case 2: - return 0x10; - } - return 0x20; -} - -std::string PolygonType1::GetBodySourceCode() const -{ - std::string bodyStr = "\n "; - - bodyStr += "{ "; - bodyStr += StringHelper::Sprintf("%i, %i, ", type, format); - - std::string dlistStr; - Globals::Instance->GetSegmentedPtrName(dlist, parent, "", dlistStr); - - bodyStr += StringHelper::Sprintf("%s, ", dlistStr.c_str()); - bodyStr += "}, \n"; - - std::string listStr = "NULL"; - switch (format) - { - case 1: - bodyStr += single.GetBodySourceCode(); - break; - case 2: - Globals::Instance->GetSegmentedPtrName(list, parent, "RoomShapeImageMultiBgEntry", listStr); - bodyStr += StringHelper::Sprintf(" %i, %s, \n", count, listStr.c_str()); - break; - - default: - break; - } - - return bodyStr; -} - -std::string PolygonType1::GetSourceTypeName() const -{ - switch (format) - { - case 1: - return "RoomShapeImageSingle"; - - case 2: - return "RoomShapeImageMulti"; - } - return "ERROR"; - // return "PolygonType1"; -} - -RoomShapeCullable::RoomShapeCullable(ZFile* nParent, uint32_t nRawDataIndex, ZRoom* nRoom) - : PolygonTypeBase(nParent, nRawDataIndex, nRoom) -{ -} - -void RoomShapeCullable::ParseRawData() -{ - const auto& rawData = parent->GetRawData(); - - num = BitConverter::ToUInt8BE(rawData, rawDataIndex + 0x01); - - start = BitConverter::ToUInt32BE(rawData, rawDataIndex + 0x04); - end = BitConverter::ToUInt32BE(rawData, rawDataIndex + 0x08); - - uint32_t currentPtr = GETSEGOFFSET(start); - - polyDLists.reserve(num); - for (size_t i = 0; i < num; i++) - { - RoomShapeDListsEntry entry(parent); - entry.zRoom = zRoom; - entry.SetPolyType(type); - entry.ExtractFromFile(currentPtr); - entry.DeclareReferences(zRoom->GetName()); - polyDLists.push_back(entry); - currentPtr += entry.GetRawDataSize(); - } -} - -void RoomShapeCullable::DeclareReferences(const std::string& prefix) -{ - if (num > 0) - { - std::string declaration; - - for (size_t i = 0; i < polyDLists.size(); i++) - { - declaration += - StringHelper::Sprintf("\t{ %s },", polyDLists.at(i).GetBodySourceCode().c_str()); - if (i + 1 < polyDLists.size()) - declaration += "\n"; - } - - std::string polyDlistType = polyDLists.at(0).GetSourceTypeName(); - std::string polyDListName; - polyDListName = StringHelper::Sprintf("%s%s_%06X", prefix.c_str(), polyDlistType.c_str(), - GETSEGOFFSET(start)); - - Declaration* decl = parent->AddDeclarationArray( - GETSEGOFFSET(start), DeclarationAlignment::Align4, - polyDLists.size() * polyDLists.at(0).GetRawDataSize(), polyDlistType, polyDListName, - polyDLists.size(), declaration); - decl->forceArrayCnt = true; - } - - parent->AddDeclaration(GETSEGOFFSET(end), DeclarationAlignment::Align4, 4, "s32", - StringHelper::Sprintf("%s_terminatorMaybe_%06X", - parent->GetName().c_str(), GETSEGOFFSET(end)), - "0x01000000"); -} - -std::string RoomShapeCullable::GetBodySourceCode() const -{ - std::string listName; - Globals::Instance->GetSegmentedPtrName(start, parent, "", listName); - - std::string body = StringHelper::Sprintf("\n %i, %i,\n", type, polyDLists.size()); - body += StringHelper::Sprintf(" %s,\n", listName.c_str()); - body += - StringHelper::Sprintf(" %s + ARRAY_COUNTU(%s)\n", listName.c_str(), listName.c_str()); - return body; -} - -size_t RoomShapeCullable::GetRawDataSize() const -{ - return 0x0C; -} - -DeclarationAlignment RoomShapeCullable::GetDeclarationAlignment() const -{ - return DeclarationAlignment::Align4; -} diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetMesh.h b/tools/ZAPD/ZAPD/ZRoom/Commands/SetMesh.h deleted file mode 100644 index c0f15da9d3..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetMesh.h +++ /dev/null @@ -1,160 +0,0 @@ -#pragma once - -#include -#include "ZBackground.h" -#include "ZDisplayList.h" -#include "ZRoom/ZRoomCommand.h" - -class RoomShapeDListsEntry : public ZResource -{ -public: - ZRoom* zRoom; - - uint8_t polyType; - - int16_t x, y, z; // polyType == 2 - int16_t unk_06; // polyType == 2 - - segptr_t opa = 0; // Gfx* - segptr_t xlu = 0; // Gfx* - - ZDisplayList* opaDList = nullptr; // Gfx* - ZDisplayList* xluDList = nullptr; // Gfx* - - RoomShapeDListsEntry(ZFile* nParent); - - void ParseRawData() override; - void DeclareReferences(const std::string& prefix) override; - - std::string GetBodySourceCode() const override; - - void GetSourceOutputCode(const std::string& prefix) override; - - std::string GetSourceTypeName() const override; - ZResourceType GetResourceType() const override; - - size_t GetRawDataSize() const override; - - void SetPolyType(uint8_t nPolyType); - -protected: - ZDisplayList* MakeDlist(segptr_t ptr, const std::string& prefix); -}; - -class RoomShapeImageMultiBgEntry : public ZResource -{ -public: - uint16_t unk_00; - uint8_t id; - segptr_t source; - uint32_t unk_0C; - uint32_t tlut; - uint16_t width; - uint16_t height; - uint8_t fmt; - uint8_t siz; - uint16_t mode0; - uint16_t tlutCount; - - ZBackground* sourceBackground; - - bool isSubStruct; - - RoomShapeImageMultiBgEntry(ZFile* nParent); - RoomShapeImageMultiBgEntry(bool nIsSubStruct, const std::string& prefix, uint32_t nRawDataIndex, - ZFile* nParent); - - void ParseRawData() override; - - std::string GetBodySourceCode() const override; - - std::string GetSourceTypeName() const override; - ZResourceType GetResourceType() const override; - - size_t GetRawDataSize() const override; - -protected: - ZBackground* MakeBackground(segptr_t ptr, const std::string& prefix); -}; - -class PolygonTypeBase : public ZResource -{ -public: - uint8_t type; - std::vector polyDLists; - - PolygonTypeBase(ZFile* nParent, uint32_t nRawDataIndex, ZRoom* nRoom); - - void DeclareAndGenerateOutputCode(const std::string& prefix); - - std::string GetSourceTypeName() const override; - ZResourceType GetResourceType() const override; - -protected: - ZRoom* zRoom; -}; - -class PolygonType1 : public PolygonTypeBase -{ -public: - uint8_t format; - segptr_t dlist; - - // single - RoomShapeImageMultiBgEntry single; - - // multi - uint8_t count; - segptr_t list; // RoomShapeImageMultiBgEntry* - std::vector multiList; - - PolygonType1(ZFile* nParent, uint32_t nRawDataIndex, ZRoom* nRoom); - - void ParseRawData() override; - void DeclareReferences(const std::string& prefix) override; - - std::string GetBodySourceCode() const override; - - std::string GetSourceTypeName() const override; - - size_t GetRawDataSize() const override; -}; - -class RoomShapeCullable : public PolygonTypeBase -{ -public: - uint8_t num; - segptr_t start; - segptr_t end; - - RoomShapeCullable(ZFile* nParent, uint32_t nRawDataIndex, ZRoom* nRoom); - - void ParseRawData() override; - void DeclareReferences(const std::string& prefix) override; - - std::string GetBodySourceCode() const override; - - size_t GetRawDataSize() const override; - DeclarationAlignment GetDeclarationAlignment() const override; -}; - -class SetMesh : public ZRoomCommand -{ -public: - uint8_t data; - uint8_t meshHeaderType; - std::shared_ptr polyType; - - SetMesh(ZFile* nParent); - - void ParseRawData() override; - void DeclareReferences(const std::string& prefix) override; - - std::string GetBodySourceCode() const override; - - RoomCommand GetRoomCommand() const override; - std::string GetCommandCName() const override; - -private: - std::string GenDListExterns(ZDisplayList* dList); -}; diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetMinimapChests.cpp b/tools/ZAPD/ZAPD/ZRoom/Commands/SetMinimapChests.cpp deleted file mode 100644 index b1985f8904..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetMinimapChests.cpp +++ /dev/null @@ -1,82 +0,0 @@ -#include "SetMinimapChests.h" - -#include "Globals.h" -#include "Utils/BitConverter.h" -#include "Utils/StringHelper.h" -#include "ZFile.h" -#include "ZRoom/ZRoom.h" - -SetMinimapChests::SetMinimapChests(ZFile* nParent) : ZRoomCommand(nParent) -{ -} - -void SetMinimapChests::ParseRawData() -{ - ZRoomCommand::ParseRawData(); - int numChests = cmdArg1; - - offset_t currentPtr = segmentOffset; - - chests.reserve(numChests); - for (int32_t i = 0; i < numChests; i++) - { - MinimapChest chest(parent->GetRawData(), currentPtr); - chests.push_back(chest); - - currentPtr += 10; - } -} - -void SetMinimapChests::DeclareReferences(const std::string& prefix) -{ - std::string declaration; - - size_t index = 0; - for (const auto& chest : chests) - { - declaration += StringHelper::Sprintf(" { %s },", chest.GetBodySourceCode().c_str()); - - if (index < chests.size() - 1) - declaration += "\n"; - - index++; - } - - parent->AddDeclarationArray( - segmentOffset, DeclarationAlignment::Align4, chests.size() * 10, "MinimapChest", - StringHelper::Sprintf("%sMinimapChests0x%06X", prefix.c_str(), segmentOffset), - chests.size(), declaration); -} - -std::string SetMinimapChests::GetBodySourceCode() const -{ - std::string listName; - Globals::Instance->GetSegmentedPtrName(cmdArg2, parent, "MinimapChest", listName); - return StringHelper::Sprintf("SCENE_CMD_MINIMAP_COMPASS_ICON_INFO(0x%02X, %s)", chests.size(), - listName.c_str()); -} - -std::string SetMinimapChests::GetCommandCName() const -{ - return "SCmdMinimapChests"; -} - -RoomCommand SetMinimapChests::GetRoomCommand() const -{ - return RoomCommand::SetMinimapChests; -} - -MinimapChest::MinimapChest(const std::vector& rawData, uint32_t rawDataIndex) - : unk0(BitConverter::ToUInt16BE(rawData, rawDataIndex + 0)), - unk2(BitConverter::ToUInt16BE(rawData, rawDataIndex + 2)), - unk4(BitConverter::ToUInt16BE(rawData, rawDataIndex + 4)), - unk6(BitConverter::ToUInt16BE(rawData, rawDataIndex + 6)), - unk8(BitConverter::ToUInt16BE(rawData, rawDataIndex + 8)) -{ -} - -std::string MinimapChest::GetBodySourceCode() const -{ - return StringHelper::Sprintf("0x%04X, 0x%04X, 0x%04X, 0x%04X, 0x%04X", unk0, unk2, unk4, unk6, - unk8); -} diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetMinimapChests.h b/tools/ZAPD/ZAPD/ZRoom/Commands/SetMinimapChests.h deleted file mode 100644 index 0db09a8a25..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetMinimapChests.h +++ /dev/null @@ -1,34 +0,0 @@ -#pragma once - -#include "ZRoom/ZRoomCommand.h" - -class MinimapChest -{ -public: - MinimapChest(const std::vector& rawData, uint32_t rawDataIndex); - - std::string GetBodySourceCode() const; - -protected: - uint16_t unk0; - uint16_t unk2; - uint16_t unk4; - uint16_t unk6; - uint16_t unk8; -}; - -class SetMinimapChests : public ZRoomCommand -{ -public: - std::vector chests; - - SetMinimapChests(ZFile* nParent); - - void ParseRawData() override; - void DeclareReferences(const std::string& prefix) override; - - std::string GetBodySourceCode() const override; - - RoomCommand GetRoomCommand() const override; - std::string GetCommandCName() const override; -}; diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetMinimapList.cpp b/tools/ZAPD/ZAPD/ZRoom/Commands/SetMinimapList.cpp deleted file mode 100644 index a5aac2a543..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetMinimapList.cpp +++ /dev/null @@ -1,96 +0,0 @@ -#include "SetMinimapList.h" - -#include "Globals.h" -#include "Utils/BitConverter.h" -#include "Utils/StringHelper.h" -#include "ZFile.h" -#include "ZRoom/ZRoom.h" - -SetMinimapList::SetMinimapList(ZFile* nParent) : ZRoomCommand(nParent) -{ -} - -void SetMinimapList::ParseRawData() -{ - ZRoomCommand::ParseRawData(); - listSegmentAddr = BitConverter::ToInt32BE(parent->GetRawData(), segmentOffset); - listSegmentOffset = GETSEGOFFSET(listSegmentAddr); - scale = BitConverter::ToInt16BE(parent->GetRawData(), segmentOffset + 4); - - uint32_t currentPtr = listSegmentOffset; - - minimaps.reserve(zRoom->roomCount); - for (int32_t i = 0; i < zRoom->roomCount; i++) - { - MinimapEntry entry(parent->GetRawData(), currentPtr); - minimaps.push_back(entry); - - currentPtr += 10; - } -} - -void SetMinimapList::DeclareReferences(const std::string& prefix) -{ - { - std::string declaration; - - size_t index = 0; - for (const auto& entry : minimaps) - { - declaration += StringHelper::Sprintf(" { %s },", entry.GetBodySourceCode().c_str()); - - if (index < minimaps.size() - 1) - declaration += "\n"; - - index++; - } - - parent->AddDeclarationArray( - listSegmentOffset, DeclarationAlignment::Align4, minimaps.size() * 10, "MinimapEntry", - StringHelper::Sprintf("%sMinimapEntryList0x%06X", prefix.c_str(), listSegmentOffset), - minimaps.size(), declaration); - } - - { - std::string listName; - Globals::Instance->GetSegmentedPtrName(listSegmentAddr, parent, "MinimapEntry", listName); - std::string declaration = StringHelper::Sprintf("\n\t%s, %d\n", listName.c_str(), scale); - - parent->AddDeclaration( - segmentOffset, DeclarationAlignment::Align4, 8, "MinimapList", - StringHelper::Sprintf("%sMinimapList0x%06X", prefix.c_str(), segmentOffset), - declaration); - } -} - -std::string SetMinimapList::GetBodySourceCode() const -{ - std::string listName; - Globals::Instance->GetSegmentedPtrName(cmdArg2, parent, "MinimapList", listName); - return StringHelper::Sprintf("SCENE_CMD_MINIMAP_INFO(%s)", listName.c_str()); -} - -std::string SetMinimapList::GetCommandCName() const -{ - return "SCmdMinimapSettings"; -} - -RoomCommand SetMinimapList::GetRoomCommand() const -{ - return RoomCommand::SetMinimapList; -} - -MinimapEntry::MinimapEntry(const std::vector& rawData, uint32_t rawDataIndex) - : unk0(BitConverter::ToUInt16BE(rawData, rawDataIndex + 0)), - unk2(BitConverter::ToUInt16BE(rawData, rawDataIndex + 2)), - unk4(BitConverter::ToUInt16BE(rawData, rawDataIndex + 4)), - unk6(BitConverter::ToUInt16BE(rawData, rawDataIndex + 6)), - unk8(BitConverter::ToUInt16BE(rawData, rawDataIndex + 8)) -{ -} - -std::string MinimapEntry::GetBodySourceCode() const -{ - return StringHelper::Sprintf("0x%04X, 0x%04X, 0x%04X, 0x%04X, 0x%04X", unk0, unk2, unk4, unk6, - unk8); -} diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetMinimapList.h b/tools/ZAPD/ZAPD/ZRoom/Commands/SetMinimapList.h deleted file mode 100644 index fcf7ad7a6f..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetMinimapList.h +++ /dev/null @@ -1,39 +0,0 @@ -#pragma once - -#include "ZRoom/ZRoomCommand.h" - -class MinimapEntry -{ -public: - MinimapEntry(const std::vector& rawData, uint32_t rawDataIndex); - - std::string GetBodySourceCode() const; - -protected: - uint16_t unk0; - uint16_t unk2; - uint16_t unk4; - uint16_t unk6; - uint16_t unk8; -}; - -class SetMinimapList : public ZRoomCommand -{ -public: - std::vector minimaps; - - SetMinimapList(ZFile* nParent); - - void ParseRawData() override; - void DeclareReferences(const std::string& prefix) override; - - std::string GetBodySourceCode() const override; - - RoomCommand GetRoomCommand() const override; - std::string GetCommandCName() const override; - -private: - segptr_t listSegmentAddr; - uint32_t listSegmentOffset; - int16_t scale; -}; diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetObjectList.cpp b/tools/ZAPD/ZAPD/ZRoom/Commands/SetObjectList.cpp deleted file mode 100644 index 3048aa2d49..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetObjectList.cpp +++ /dev/null @@ -1,67 +0,0 @@ -#include "SetObjectList.h" - -#include "Globals.h" -#include "Utils/BitConverter.h" -#include "Utils/StringHelper.h" -#include "ZFile.h" -#include "ZRoom/ZNames.h" -#include "ZRoom/ZRoom.h" - -SetObjectList::SetObjectList(ZFile* nParent) : ZRoomCommand(nParent) -{ -} - -void SetObjectList::ParseRawData() -{ - ZRoomCommand::ParseRawData(); - uint8_t objectCnt = parent->GetRawData().at(rawDataIndex + 1); - uint32_t currentPtr = segmentOffset; - - objects.reserve(objectCnt); - for (uint8_t i = 0; i < objectCnt; i++) - { - uint16_t objectIndex = BitConverter::ToInt16BE(parent->GetRawData(), currentPtr); - objects.push_back(objectIndex); - currentPtr += 2; - } -} - -void SetObjectList::DeclareReferences(const std::string& prefix) -{ - if (!objects.empty()) - { - std::string declaration; - - for (size_t i = 0; i < objects.size(); i++) - { - uint16_t objectIndex = objects[i]; - declaration += - StringHelper::Sprintf(" %s,", ZNames::GetObjectName(objectIndex).c_str()); - - if (i < objects.size() - 1) - declaration += "\n"; - } - - parent->AddDeclarationArray( - segmentOffset, DeclarationAlignment::Align4, objects.size() * 2, "s16", - StringHelper::Sprintf("%sObjectList_%06X", prefix.c_str(), segmentOffset), - objects.size(), declaration); - } -} - -std::string SetObjectList::GetBodySourceCode() const -{ - std::string listName; - Globals::Instance->GetSegmentedPtrName(cmdArg2, parent, "s16", listName); - return StringHelper::Sprintf("SCENE_CMD_OBJECT_LIST(%i, %s)", objects.size(), listName.c_str()); -} - -std::string SetObjectList::GetCommandCName() const -{ - return "SCmdObjectList"; -} - -RoomCommand SetObjectList::GetRoomCommand() const -{ - return RoomCommand::SetObjectList; -} diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetObjectList.h b/tools/ZAPD/ZAPD/ZRoom/Commands/SetObjectList.h deleted file mode 100644 index 03c159483c..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetObjectList.h +++ /dev/null @@ -1,19 +0,0 @@ -#pragma once - -#include "ZRoom/ZRoomCommand.h" - -class SetObjectList : public ZRoomCommand -{ -public: - std::vector objects; - - SetObjectList(ZFile* nParent); - - void ParseRawData() override; - void DeclareReferences(const std::string& prefix) override; - - std::string GetBodySourceCode() const override; - - std::string GetCommandCName() const override; - RoomCommand GetRoomCommand() const override; -}; diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetPathways.cpp b/tools/ZAPD/ZAPD/ZRoom/Commands/SetPathways.cpp deleted file mode 100644 index 967d10b8d5..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetPathways.cpp +++ /dev/null @@ -1,57 +0,0 @@ -#include "SetPathways.h" - -#include "Globals.h" -#include "Utils/BitConverter.h" -#include "Utils/StringHelper.h" -#include "ZFile.h" -#include "ZRoom/ZRoom.h" - -SetPathways::SetPathways(ZFile* nParent) : ZRoomCommand(nParent), pathwayList(nParent) -{ -} - -void SetPathways::DeclareReferences([[maybe_unused]] const std::string& prefix) -{ - if (segmentOffset != 0) - { - std::string varName = - StringHelper::Sprintf("%sPathway_%06X", prefix.c_str(), segmentOffset); - parent->AddDeclarationPlaceholder(segmentOffset, varName); - } -} - -void SetPathways::ParseRawDataLate() -{ - if (Globals::Instance->game == ZGame::MM_RETAIL) - { - auto numPaths = zRoom->parent->GetDeclarationSizeFromNeighbor(segmentOffset) / 8; - pathwayList.SetNumPaths(numPaths); - } - - pathwayList.ExtractFromFile(segmentOffset); -} - -void SetPathways::DeclareReferencesLate(const std::string& prefix) -{ - std::string varName = StringHelper::Sprintf("%sPathway_%06X", prefix.c_str(), segmentOffset); - pathwayList.SetName(varName); - pathwayList.DeclareReferences(prefix); - pathwayList.GetSourceOutputCode(prefix); -} - -std::string SetPathways::GetBodySourceCode() const -{ - std::string listName; - Globals::Instance->GetSegmentedPtrName(cmdArg2, parent, "Path", listName); - return StringHelper::Sprintf("SCENE_CMD_PATH_LIST(%s)", listName.c_str()); -} - -std::string SetPathways::GetCommandCName() const -{ - return "SCmdPathList"; -} - -RoomCommand SetPathways::GetRoomCommand() const -{ - return RoomCommand::SetPathways; -} diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetPathways.h b/tools/ZAPD/ZAPD/ZRoom/Commands/SetPathways.h deleted file mode 100644 index 9abc93d32e..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetPathways.h +++ /dev/null @@ -1,24 +0,0 @@ -#pragma once - -#include "Vec3s.h" -#include "ZPath.h" -#include "ZResource.h" -#include "ZRoom/ZRoomCommand.h" - -class SetPathways : public ZRoomCommand -{ -public: - ZPath pathwayList; - - SetPathways(ZFile* nParent); - - void DeclareReferences(const std::string& prefix) override; - - void ParseRawDataLate() override; - void DeclareReferencesLate(const std::string& prefix) override; - - std::string GetBodySourceCode() const override; - - RoomCommand GetRoomCommand() const override; - std::string GetCommandCName() const override; -}; diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetRoomBehavior.cpp b/tools/ZAPD/ZAPD/ZRoom/Commands/SetRoomBehavior.cpp deleted file mode 100644 index 8c6f4bf514..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetRoomBehavior.cpp +++ /dev/null @@ -1,50 +0,0 @@ -#include "SetRoomBehavior.h" - -#include "Globals.h" -#include "Utils/BitConverter.h" -#include "Utils/StringHelper.h" - -SetRoomBehavior::SetRoomBehavior(ZFile* nParent) : ZRoomCommand(nParent) -{ -} - -void SetRoomBehavior::ParseRawData() -{ - ZRoomCommand::ParseRawData(); - gameplayFlags = cmdArg1; - gameplayFlags2 = BitConverter::ToInt32BE(parent->GetRawData(), rawDataIndex + 0x04); - - currRoomUnk2 = gameplayFlags2 & 0xFF; - - currRoomUnk5 = showInvisActors = (gameplayFlags2 >> 8) & 1; - - msgCtxUnk = (gameplayFlags2 >> 10) & 1; - - enablePosLights = (gameplayFlags2 >> 11) & 1; - kankyoContextUnkE2 = (gameplayFlags2 >> 12) & 1; -} - -std::string SetRoomBehavior::GetBodySourceCode() const -{ - if (Globals::Instance->game == ZGame::MM_RETAIL) - { - std::string enableLights = StringHelper::BoolStr(enablePosLights); - return StringHelper::Sprintf("SCENE_CMD_ROOM_BEHAVIOR(0x%02X, 0x%02X, %i, %i, %s, %i)", - gameplayFlags, currRoomUnk2, currRoomUnk5, msgCtxUnk, - enableLights.c_str(), kankyoContextUnkE2); - } - std::string showInvisible = StringHelper::BoolStr(showInvisActors); - std::string disableWarps = StringHelper::BoolStr(msgCtxUnk); - return StringHelper::Sprintf("SCENE_CMD_ROOM_BEHAVIOR(0x%02X, 0x%02X, %s, %s)", gameplayFlags, - currRoomUnk2, showInvisible.c_str(), disableWarps.c_str()); -} - -std::string SetRoomBehavior::GetCommandCName() const -{ - return "SCmdRoomBehavior"; -} - -RoomCommand SetRoomBehavior::GetRoomCommand() const -{ - return RoomCommand::SetRoomBehavior; -} diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetRoomBehavior.h b/tools/ZAPD/ZAPD/ZRoom/Commands/SetRoomBehavior.h deleted file mode 100644 index 47b772d77f..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetRoomBehavior.h +++ /dev/null @@ -1,29 +0,0 @@ -#pragma once - -#include "ZRoom/ZRoomCommand.h" - -class SetRoomBehavior : public ZRoomCommand -{ -public: - uint8_t gameplayFlags; - uint32_t gameplayFlags2; - - uint8_t currRoomUnk2; - - uint8_t showInvisActors; - uint8_t currRoomUnk5; - - uint8_t msgCtxUnk; - - uint8_t enablePosLights; - uint8_t kankyoContextUnkE2; - - SetRoomBehavior(ZFile* nParent); - - void ParseRawData() override; - - std::string GetBodySourceCode() const override; - - RoomCommand GetRoomCommand() const override; - std::string GetCommandCName() const override; -}; diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetRoomList.cpp b/tools/ZAPD/ZAPD/ZRoom/Commands/SetRoomList.cpp deleted file mode 100644 index 24969a14d8..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetRoomList.cpp +++ /dev/null @@ -1,155 +0,0 @@ -#include "SetRoomList.h" - -#include "Globals.h" -#include "Utils/BitConverter.h" -#include "Utils/StringHelper.h" -#include "ZFile.h" -#include "ZRoom/ZRoom.h" - -SetRoomList::SetRoomList(ZFile* nParent) : ZRoomCommand(nParent) -{ -} - -void SetRoomList::ParseRawData() -{ - ZRoomCommand::ParseRawData(); - int numRooms = cmdArg1; - - romfile = new RomFile(parent); - romfile->numRooms = numRooms; - romfile->ExtractFromFile(segmentOffset); - - parent->resources.push_back(romfile); - - zRoom->roomCount = numRooms; -} - -void SetRoomList::DeclareReferences(const std::string& prefix) -{ - ZRoomCommand::DeclareReferences(prefix); - - romfile->DeclareVar(prefix, ""); -} - -std::string SetRoomList::GetBodySourceCode() const -{ - std::string listName; - Globals::Instance->GetSegmentedPtrName(cmdArg2, parent, "RomFile", listName); - return StringHelper::Sprintf("SCENE_CMD_ROOM_LIST(%i, %s)", romfile->rooms.size(), - listName.c_str()); -} - -std::string SetRoomList::GetCommandCName() const -{ - return "SCmdRoomList"; -} - -RoomCommand SetRoomList::GetRoomCommand() const -{ - return RoomCommand::SetRoomList; -} - -RomFile::RomFile(ZFile* nParent) : ZResource(nParent) -{ -} - -void RomFile::ParseXML(tinyxml2::XMLElement* reader) -{ - ZResource::ParseXML(reader); - - if (reader->Attribute("NumRooms") != nullptr) - { - numRooms = StringHelper::StrToL(std::string(reader->Attribute("NumRooms"))); - } -} - -void RomFile::ParseRawData() -{ - ZResource::ParseRawData(); - - uint32_t currentPtr = rawDataIndex; - - rooms.reserve(numRooms); - for (int32_t i = 0; i < numRooms; i++) - { - RoomEntry entry(parent->GetRawData(), currentPtr); - rooms.push_back(entry); - - currentPtr += 8; - } -} - -Declaration* RomFile::DeclareVar(const std::string& prefix, const std::string& body) -{ - std::string auxName = name; - if (name == "") - auxName = StringHelper::Sprintf("%sRoomList0x%06X", prefix.c_str(), rawDataIndex); - - return parent->AddDeclarationArray(rawDataIndex, DeclarationAlignment::Align4, - rooms.size() * rooms.at(0).GetRawDataSize(), - GetSourceTypeName(), auxName, rooms.size(), body); -} - -std::string RomFile::GetBodySourceCode() const -{ - std::string declaration; - bool isFirst = true; - - for (ZFile* file : Globals::Instance->files) - { - for (ZResource* res : file->resources) - { - if (res->GetResourceType() == ZResourceType::Room) - { - std::string roomName = res->GetName(); - if (!isFirst) - declaration += "\n"; - - declaration += StringHelper::Sprintf( - "\t{ (uintptr_t)_%sSegmentRomStart, (uintptr_t)_%sSegmentRomEnd },", - roomName.c_str(), roomName.c_str()); - isFirst = false; - } - } - } - - return declaration; -} - -void RomFile::GetSourceOutputCode(const std::string& prefix) -{ - DeclareVar(prefix, GetBodySourceCode()); -} - -std::string RomFile::GetSourceTypeName() const -{ - return "RomFile"; -} - -ZResourceType RomFile::GetResourceType() const -{ - // TODO - return ZResourceType::Error; -} - -size_t RomFile::GetRawDataSize() const -{ - return 8 * rooms.size(); -} - -RoomEntry::RoomEntry(uint32_t nVAS, uint32_t nVAE) -{ - virtualAddressStart = nVAS; - virtualAddressEnd = nVAE; -} - -RoomEntry::RoomEntry(const std::vector& rawData, uint32_t rawDataIndex) - : RoomEntry(BitConverter::ToInt32BE(rawData, rawDataIndex + 0), - BitConverter::ToInt32BE(rawData, rawDataIndex + 4)) -{ -} - -size_t RoomEntry::GetRawDataSize() const -{ - return 0x08; -} diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetRoomList.h b/tools/ZAPD/ZAPD/ZRoom/Commands/SetRoomList.h deleted file mode 100644 index 2ae48b68df..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetRoomList.h +++ /dev/null @@ -1,53 +0,0 @@ -#pragma once - -#include "ZRoom/ZRoomCommand.h" - -class RoomEntry -{ -public: - int32_t virtualAddressStart; - int32_t virtualAddressEnd; - - RoomEntry(uint32_t nVAS, uint32_t nVAE); - RoomEntry(const std::vector& rawData, uint32_t rawDataIndex); - - size_t GetRawDataSize() const; -}; - -class RomFile : public ZResource -{ -public: - RomFile(ZFile* nParent); - - void ParseXML(tinyxml2::XMLElement* reader) override; - void ParseRawData() override; - - Declaration* DeclareVar(const std::string& prefix, const std::string& body) override; - std::string GetBodySourceCode() const override; - void GetSourceOutputCode(const std::string& prefix) override; - - std::string GetSourceTypeName() const override; - virtual ZResourceType GetResourceType() const override; - - virtual size_t GetRawDataSize() const override; - - uint8_t numRooms = 0; - std::vector rooms; -}; - -class SetRoomList : public ZRoomCommand -{ -public: - // Borrowed reference. Don't delete. - RomFile* romfile = nullptr; - - SetRoomList(ZFile* nParent); - - void ParseRawData() override; - void DeclareReferences(const std::string& prefix) override; - - std::string GetBodySourceCode() const override; - - RoomCommand GetRoomCommand() const override; - std::string GetCommandCName() const override; -}; diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetSkyboxModifier.cpp b/tools/ZAPD/ZAPD/ZRoom/Commands/SetSkyboxModifier.cpp deleted file mode 100644 index b16f1355b2..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetSkyboxModifier.cpp +++ /dev/null @@ -1,32 +0,0 @@ -#include "SetSkyboxModifier.h" - -#include "Utils/StringHelper.h" - -SetSkyboxModifier::SetSkyboxModifier(ZFile* nParent) : ZRoomCommand(nParent) -{ -} - -void SetSkyboxModifier::ParseRawData() -{ - ZRoomCommand::ParseRawData(); - disableSky = parent->GetRawData().at(rawDataIndex + 0x04); - disableSunMoon = parent->GetRawData().at(rawDataIndex + 0x05); -} - -std::string SetSkyboxModifier::GetBodySourceCode() const -{ - std::string sky = StringHelper::BoolStr(disableSky); - std::string soonMoon = StringHelper::BoolStr(disableSunMoon); - return StringHelper::Sprintf("SCENE_CMD_SKYBOX_DISABLES(%s, %s)", sky.c_str(), - soonMoon.c_str()); -} - -std::string SetSkyboxModifier::GetCommandCName() const -{ - return "SCmdSkyboxDisables"; -} - -RoomCommand SetSkyboxModifier::GetRoomCommand() const -{ - return RoomCommand::SetSkyboxModifier; -} diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetSkyboxModifier.h b/tools/ZAPD/ZAPD/ZRoom/Commands/SetSkyboxModifier.h deleted file mode 100644 index 65935bf928..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetSkyboxModifier.h +++ /dev/null @@ -1,19 +0,0 @@ -#pragma once - -#include "ZRoom/ZRoomCommand.h" - -class SetSkyboxModifier : public ZRoomCommand -{ -public: - uint8_t disableSky; - uint8_t disableSunMoon; - - SetSkyboxModifier(ZFile* nParent); - - void ParseRawData() override; - - std::string GetBodySourceCode() const override; - - std::string GetCommandCName() const override; - RoomCommand GetRoomCommand() const override; -}; diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetSkyboxSettings.cpp b/tools/ZAPD/ZAPD/ZRoom/Commands/SetSkyboxSettings.cpp deleted file mode 100644 index d5ae7ef761..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetSkyboxSettings.cpp +++ /dev/null @@ -1,36 +0,0 @@ -#include "SetSkyboxSettings.h" -#include "Globals.h" -#include "Utils/StringHelper.h" - -SetSkyboxSettings::SetSkyboxSettings(ZFile* nParent) : ZRoomCommand(nParent) -{ -} - -void SetSkyboxSettings::ParseRawData() -{ - ZRoomCommand::ParseRawData(); - unk1 = cmdArg1; - skyboxNumber = parent->GetRawData().at(rawDataIndex + 0x04); - cloudsType = parent->GetRawData().at(rawDataIndex + 0x05); - isIndoors = parent->GetRawData().at(rawDataIndex + 0x06); -} - -std::string SetSkyboxSettings::GetBodySourceCode() const -{ - std::string indoors = StringHelper::BoolStr(isIndoors); - if (Globals::Instance->game == ZGame::MM_RETAIL) - return StringHelper::Sprintf("SCENE_CMD_SKYBOX_SETTINGS(0x%02X, %i, %i, %s)", unk1, - skyboxNumber, cloudsType, indoors.c_str()); - return StringHelper::Sprintf("SCENE_CMD_SKYBOX_SETTINGS(%i, %i, %s)", skyboxNumber, cloudsType, - indoors.c_str()); -} - -std::string SetSkyboxSettings::GetCommandCName() const -{ - return "SCmdSkyboxSettings"; -} - -RoomCommand SetSkyboxSettings::GetRoomCommand() const -{ - return RoomCommand::SetSkyboxSettings; -} diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetSkyboxSettings.h b/tools/ZAPD/ZAPD/ZRoom/Commands/SetSkyboxSettings.h deleted file mode 100644 index 1c7e01ad40..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetSkyboxSettings.h +++ /dev/null @@ -1,21 +0,0 @@ -#pragma once - -#include "ZRoom/ZRoomCommand.h" - -class SetSkyboxSettings : public ZRoomCommand -{ -public: - uint8_t unk1; // (MM Only) - uint8_t skyboxNumber; - uint8_t cloudsType; - uint8_t isIndoors; - - SetSkyboxSettings(ZFile* nParent); - - void ParseRawData() override; - - std::string GetBodySourceCode() const override; - - std::string GetCommandCName() const override; - RoomCommand GetRoomCommand() const override; -}; diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetSoundSettings.cpp b/tools/ZAPD/ZAPD/ZRoom/Commands/SetSoundSettings.cpp deleted file mode 100644 index 54b91328fb..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetSoundSettings.cpp +++ /dev/null @@ -1,30 +0,0 @@ -#include "SetSoundSettings.h" -#include "Utils/StringHelper.h" - -SetSoundSettings::SetSoundSettings(ZFile* nParent) : ZRoomCommand(nParent) -{ -} - -void SetSoundSettings::ParseRawData() -{ - ZRoomCommand::ParseRawData(); - reverb = cmdArg1; - nightTimeSFX = parent->GetRawData().at(rawDataIndex + 0x06); - musicSequence = parent->GetRawData().at(rawDataIndex + 0x07); -} - -std::string SetSoundSettings::GetBodySourceCode() const -{ - return StringHelper::Sprintf("SCENE_CMD_SOUND_SETTINGS(%i, %i, %i)", reverb, nightTimeSFX, - musicSequence); -} - -std::string SetSoundSettings::GetCommandCName() const -{ - return "SCmdSoundSettings"; -} - -RoomCommand SetSoundSettings::GetRoomCommand() const -{ - return RoomCommand::SetSoundSettings; -} diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetSoundSettings.h b/tools/ZAPD/ZAPD/ZRoom/Commands/SetSoundSettings.h deleted file mode 100644 index f378e5e4ed..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetSoundSettings.h +++ /dev/null @@ -1,20 +0,0 @@ -#pragma once - -#include "ZRoom/ZRoomCommand.h" - -class SetSoundSettings : public ZRoomCommand -{ -public: - uint8_t reverb; - uint8_t nightTimeSFX; - uint8_t musicSequence; - - SetSoundSettings(ZFile* nParent); - - void ParseRawData() override; - - std::string GetBodySourceCode() const override; - - RoomCommand GetRoomCommand() const override; - std::string GetCommandCName() const override; -}; diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetSpecialObjects.cpp b/tools/ZAPD/ZAPD/ZRoom/Commands/SetSpecialObjects.cpp deleted file mode 100644 index 34edf5ae63..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetSpecialObjects.cpp +++ /dev/null @@ -1,40 +0,0 @@ -#include "SetSpecialObjects.h" - -#include "Utils/BitConverter.h" -#include "Utils/StringHelper.h" -#include "ZRoom/ZNames.h" - -SetSpecialObjects::SetSpecialObjects(ZFile* nParent) : ZRoomCommand(nParent) -{ -} - -void SetSpecialObjects::ParseRawData() -{ - ZRoomCommand::ParseRawData(); - elfMessage = cmdArg1; - globalObject = BitConverter::ToUInt16BE(parent->GetRawData(), rawDataIndex + 0x06); -} - -std::string SetSpecialObjects::GetBodySourceCode() const -{ - EnumData* enumData = &Globals::Instance->cfg.enumData; - std::string objectName = ZNames::GetObjectName(globalObject); - - if (enumData->naviQuestHintType.find(elfMessage) != enumData->naviQuestHintType.end()) - return StringHelper::Sprintf("SCENE_CMD_SPECIAL_FILES(%s, %s)", - enumData->naviQuestHintType[elfMessage].c_str(), - objectName.c_str()); - - return StringHelper::Sprintf("SCENE_CMD_SPECIAL_FILES(0x%02X, %s)", elfMessage, - objectName.c_str()); -} - -std::string SetSpecialObjects::GetCommandCName() const -{ - return "SCmdSpecialFiles"; -} - -RoomCommand SetSpecialObjects::GetRoomCommand() const -{ - return RoomCommand::SetSpecialObjects; -} diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetSpecialObjects.h b/tools/ZAPD/ZAPD/ZRoom/Commands/SetSpecialObjects.h deleted file mode 100644 index 3327d44c38..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetSpecialObjects.h +++ /dev/null @@ -1,19 +0,0 @@ -#pragma once - -#include "ZRoom/ZRoomCommand.h" - -class SetSpecialObjects : public ZRoomCommand -{ -public: - uint8_t elfMessage; - uint16_t globalObject; - - SetSpecialObjects(ZFile* nParent); - - void ParseRawData() override; - - std::string GetBodySourceCode() const override; - - RoomCommand GetRoomCommand() const override; - std::string GetCommandCName() const override; -}; diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetStartPositionList.cpp b/tools/ZAPD/ZAPD/ZRoom/Commands/SetStartPositionList.cpp deleted file mode 100644 index 14ca16a962..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetStartPositionList.cpp +++ /dev/null @@ -1,67 +0,0 @@ -#include "SetStartPositionList.h" - -#include "Globals.h" -#include "Utils/BitConverter.h" -#include "Utils/StringHelper.h" -#include "ZFile.h" -#include "ZRoom/ZNames.h" -#include "ZRoom/ZRoom.h" - -SetStartPositionList::SetStartPositionList(ZFile* nParent) : ZRoomCommand(nParent) -{ -} - -void SetStartPositionList::ParseRawData() -{ - ZRoomCommand::ParseRawData(); - uint8_t numActors = cmdArg1; - - offset_t currentPtr = segmentOffset; - - actors.reserve(numActors); - for (uint32_t i = 0; i < numActors; i++) - { - actors.push_back(ActorSpawnEntry(parent->GetRawData(), currentPtr)); - currentPtr += 16; - } -} - -void SetStartPositionList::DeclareReferences(const std::string& prefix) -{ - if (!actors.empty()) - { - std::string declaration; - - size_t index = 0; - for (const auto& entry : actors) - { - declaration += StringHelper::Sprintf(" { %s },", entry.GetBodySourceCode().c_str()); - if (index + 1 < actors.size()) - declaration += "\n"; - - index++; - } - - parent->AddDeclarationArray( - segmentOffset, DeclarationAlignment::Align4, actors.size() * 16, "ActorEntry", - StringHelper::Sprintf("%sStartPositionList0x%06X", prefix.c_str(), segmentOffset), - actors.size(), declaration); - } -} - -std::string SetStartPositionList::GetBodySourceCode() const -{ - std::string listName; - Globals::Instance->GetSegmentedPtrName(cmdArg2, parent, "ActorEntry", listName); - return StringHelper::Sprintf("SCENE_CMD_SPAWN_LIST(%i, %s)", actors.size(), listName.c_str()); -} - -std::string SetStartPositionList::GetCommandCName() const -{ - return "SCmdSpawnList"; -} - -RoomCommand SetStartPositionList::GetRoomCommand() const -{ - return RoomCommand::SetStartPositionList; -} diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetStartPositionList.h b/tools/ZAPD/ZAPD/ZRoom/Commands/SetStartPositionList.h deleted file mode 100644 index 10075adf3c..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetStartPositionList.h +++ /dev/null @@ -1,20 +0,0 @@ -#pragma once - -#include "SetActorList.h" -#include "ZRoom/ZRoomCommand.h" - -class SetStartPositionList : public ZRoomCommand -{ -public: - std::vector actors; - - SetStartPositionList(ZFile* nParent); - - void ParseRawData() override; - void DeclareReferences(const std::string& prefix) override; - - std::string GetBodySourceCode() const override; - - RoomCommand GetRoomCommand() const override; - std::string GetCommandCName() const override; -}; diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetTimeSettings.cpp b/tools/ZAPD/ZAPD/ZRoom/Commands/SetTimeSettings.cpp deleted file mode 100644 index 9d4d356df7..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetTimeSettings.cpp +++ /dev/null @@ -1,30 +0,0 @@ -#include "SetTimeSettings.h" -#include "Utils/BitConverter.h" -#include "Utils/StringHelper.h" - -SetTimeSettings::SetTimeSettings(ZFile* nParent) : ZRoomCommand(nParent) -{ -} - -void SetTimeSettings::ParseRawData() -{ - ZRoomCommand::ParseRawData(); - hour = parent->GetRawData().at(rawDataIndex + 4); - min = parent->GetRawData().at(rawDataIndex + 5); - unk = parent->GetRawData().at(rawDataIndex + 6); -} - -std::string SetTimeSettings::GetBodySourceCode() const -{ - return StringHelper::Sprintf("SCENE_CMD_TIME_SETTINGS(%i, %i, %i)", hour, min, unk); -} - -std::string SetTimeSettings::GetCommandCName() const -{ - return "SCmdTimeSettings"; -} - -RoomCommand SetTimeSettings::GetRoomCommand() const -{ - return RoomCommand::SetTimeSettings; -} diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetTimeSettings.h b/tools/ZAPD/ZAPD/ZRoom/Commands/SetTimeSettings.h deleted file mode 100644 index 7ff2711d4e..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetTimeSettings.h +++ /dev/null @@ -1,20 +0,0 @@ -#pragma once - -#include "ZRoom/ZRoomCommand.h" - -class SetTimeSettings : public ZRoomCommand -{ -public: - uint8_t hour; - uint8_t min; - uint8_t unk; - - SetTimeSettings(ZFile* nParent); - - void ParseRawData() override; - - std::string GetBodySourceCode() const override; - - std::string GetCommandCName() const override; - RoomCommand GetRoomCommand() const override; -}; diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetTransitionActorList.cpp b/tools/ZAPD/ZAPD/ZRoom/Commands/SetTransitionActorList.cpp deleted file mode 100644 index 67e3e4e184..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetTransitionActorList.cpp +++ /dev/null @@ -1,92 +0,0 @@ -#include "SetTransitionActorList.h" - -#include "Globals.h" -#include "Utils/BitConverter.h" -#include "Utils/StringHelper.h" -#include "ZFile.h" -#include "ZRoom/ZNames.h" -#include "ZRoom/ZRoom.h" - -SetTransitionActorList::SetTransitionActorList(ZFile* nParent) : ZRoomCommand(nParent) -{ -} - -void SetTransitionActorList::ParseRawData() -{ - ZRoomCommand::ParseRawData(); - int numActors = cmdArg1; - uint32_t currentPtr = segmentOffset; - - transitionActors.reserve(numActors); - for (int32_t i = 0; i < numActors; i++) - { - TransitionActorEntry entry(parent->GetRawData(), currentPtr); - transitionActors.push_back(entry); - - currentPtr += 16; - } -} - -void SetTransitionActorList::DeclareReferences(const std::string& prefix) -{ - std::string declaration; - - size_t index = 0; - for (const auto& entry : transitionActors) - { - declaration += StringHelper::Sprintf(" { %s },", entry.GetBodySourceCode().c_str()); - if (index + 1 < transitionActors.size()) - { - declaration += "\n"; - } - - index++; - } - - parent->AddDeclarationArray( - segmentOffset, DeclarationAlignment::Align4, transitionActors.size() * 16, - "TransitionActorEntry", - StringHelper::Sprintf("%sTransitionActorList_%06X", prefix.c_str(), segmentOffset), - transitionActors.size(), declaration); -} - -std::string SetTransitionActorList::GetBodySourceCode() const -{ - std::string listName; - Globals::Instance->GetSegmentedPtrName(cmdArg2, parent, "TransitionActorEntry", listName); - return StringHelper::Sprintf("SCENE_CMD_TRANSITION_ACTOR_LIST(%i, %s)", transitionActors.size(), - listName.c_str()); -} - -std::string SetTransitionActorList::GetCommandCName() const -{ - return "SCmdTransiActorList"; -} - -RoomCommand SetTransitionActorList::GetRoomCommand() const -{ - return RoomCommand::SetTransitionActorList; -} - -TransitionActorEntry::TransitionActorEntry(const std::vector& rawData, int rawDataIndex) -{ - frontObjectRoom = rawData[rawDataIndex + 0]; - frontTransitionReaction = rawData[rawDataIndex + 1]; - backObjectRoom = rawData[rawDataIndex + 2]; - backTransitionReaction = rawData[rawDataIndex + 3]; - actorNum = BitConverter::ToInt16BE(rawData, rawDataIndex + 4); - posX = BitConverter::ToInt16BE(rawData, rawDataIndex + 6); - posY = BitConverter::ToInt16BE(rawData, rawDataIndex + 8); - posZ = BitConverter::ToInt16BE(rawData, rawDataIndex + 10); - rotY = BitConverter::ToInt16BE(rawData, rawDataIndex + 12); - initVar = BitConverter::ToInt16BE(rawData, rawDataIndex + 14); -} - -std::string TransitionActorEntry::GetBodySourceCode() const -{ - std::string actorStr = ZNames::GetActorName(actorNum); - - return StringHelper::Sprintf("%i, %i, %i, %i, %s, %i, %i, %i, %i, 0x%04X", frontObjectRoom, - frontTransitionReaction, backObjectRoom, backTransitionReaction, - actorStr.c_str(), posX, posY, posZ, rotY, initVar); -} diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetTransitionActorList.h b/tools/ZAPD/ZAPD/ZRoom/Commands/SetTransitionActorList.h deleted file mode 100644 index a5ce2e66fd..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetTransitionActorList.h +++ /dev/null @@ -1,36 +0,0 @@ -#pragma once - -#include "ZRoom/ZRoomCommand.h" - -class TransitionActorEntry -{ -public: - uint8_t frontObjectRoom; - uint8_t frontTransitionReaction; - uint8_t backObjectRoom; - uint8_t backTransitionReaction; - uint16_t actorNum; - int16_t posX, posY, posZ; - int16_t rotY; - uint16_t initVar; - - TransitionActorEntry(const std::vector& rawData, int rawDataIndex); - - std::string GetBodySourceCode() const; -}; - -class SetTransitionActorList : public ZRoomCommand -{ -public: - std::vector transitionActors; - - SetTransitionActorList(ZFile* nParent); - - void ParseRawData() override; - void DeclareReferences(const std::string& prefix) override; - - std::string GetBodySourceCode() const override; - - RoomCommand GetRoomCommand() const override; - std::string GetCommandCName() const override; -}; diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetWind.cpp b/tools/ZAPD/ZAPD/ZRoom/Commands/SetWind.cpp deleted file mode 100644 index 1893b56018..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetWind.cpp +++ /dev/null @@ -1,32 +0,0 @@ -#include "SetWind.h" -#include "Utils/StringHelper.h" - -SetWind::SetWind(ZFile* nParent) : ZRoomCommand(nParent) -{ -} - -void SetWind::ParseRawData() -{ - ZRoomCommand::ParseRawData(); - auto& parentRawData = parent->GetRawData(); - windWest = parentRawData.at(rawDataIndex + 0x04); - windVertical = parentRawData.at(rawDataIndex + 0x05); - windSouth = parentRawData.at(rawDataIndex + 0x06); - clothFlappingStrength = parentRawData.at(rawDataIndex + 0x07); -} - -std::string SetWind::GetBodySourceCode() const -{ - return StringHelper::Sprintf("SCENE_CMD_WIND_SETTINGS(%i, %i, %i, %i)", windWest, windVertical, - windSouth, clothFlappingStrength); -} - -std::string SetWind::GetCommandCName() const -{ - return "SCmdWindSettings"; -} - -RoomCommand SetWind::GetRoomCommand() const -{ - return RoomCommand::SetWind; -} diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetWind.h b/tools/ZAPD/ZAPD/ZRoom/Commands/SetWind.h deleted file mode 100644 index 05eaafeda8..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetWind.h +++ /dev/null @@ -1,21 +0,0 @@ -#pragma once - -#include "ZRoom/ZRoomCommand.h" - -class SetWind : public ZRoomCommand -{ -public: - uint8_t windWest; - uint8_t windVertical; - uint8_t windSouth; - uint8_t clothFlappingStrength; - - SetWind(ZFile* nParent); - - void ParseRawData() override; - - std::string GetBodySourceCode() const override; - - std::string GetCommandCName() const override; - RoomCommand GetRoomCommand() const override; -}; diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetWorldMapVisited.cpp b/tools/ZAPD/ZAPD/ZRoom/Commands/SetWorldMapVisited.cpp deleted file mode 100644 index fa28547e62..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetWorldMapVisited.cpp +++ /dev/null @@ -1,26 +0,0 @@ -#include "SetWorldMapVisited.h" - -#include "Utils/StringHelper.h" -#include "Globals.h" - -SetWorldMapVisited::SetWorldMapVisited(ZFile* nParent) : ZRoomCommand(nParent) -{ -} - -std::string SetWorldMapVisited::GetBodySourceCode() const -{ - if (Globals::Instance->game == ZGame::MM_RETAIL) - return "SCENE_CMD_SET_REGION_VISITED()"; - else - return "SCENE_CMD_MISC_SETTINGS()"; -} - -std::string SetWorldMapVisited::GetCommandCName() const -{ - return "SCmdWorldMapVisited"; -} - -RoomCommand SetWorldMapVisited::GetRoomCommand() const -{ - return RoomCommand::SetWorldMapVisited; -} diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/SetWorldMapVisited.h b/tools/ZAPD/ZAPD/ZRoom/Commands/SetWorldMapVisited.h deleted file mode 100644 index a7ad93154d..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/SetWorldMapVisited.h +++ /dev/null @@ -1,14 +0,0 @@ -#pragma once - -#include "ZRoom/ZRoomCommand.h" - -class SetWorldMapVisited : public ZRoomCommand -{ -public: - SetWorldMapVisited(ZFile* nParent); - - std::string GetBodySourceCode() const override; - - RoomCommand GetRoomCommand() const override; - std::string GetCommandCName() const override; -}; diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/Unused09.cpp b/tools/ZAPD/ZAPD/ZRoom/Commands/Unused09.cpp deleted file mode 100644 index 9dfcaa5c23..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/Unused09.cpp +++ /dev/null @@ -1,21 +0,0 @@ -#include "Unused09.h" -#include "Utils/StringHelper.h" - -Unused09::Unused09(ZFile* nParent) : ZRoomCommand(nParent) -{ -} - -std::string Unused09::GetBodySourceCode() const -{ - return "SCENE_CMD_UNK_09()"; -} - -std::string Unused09::GetCommandCName() const -{ - return "SceneCmd"; -} - -RoomCommand Unused09::GetRoomCommand() const -{ - return RoomCommand::Unused09; -} diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/Unused09.h b/tools/ZAPD/ZAPD/ZRoom/Commands/Unused09.h deleted file mode 100644 index a38985eeaa..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/Unused09.h +++ /dev/null @@ -1,14 +0,0 @@ -#pragma once - -#include "ZRoom/ZRoomCommand.h" - -class Unused09 : public ZRoomCommand -{ -public: - Unused09(ZFile* nParent); - - std::string GetBodySourceCode() const override; - - RoomCommand GetRoomCommand() const override; - std::string GetCommandCName() const override; -}; diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/Unused1D.cpp b/tools/ZAPD/ZAPD/ZRoom/Commands/Unused1D.cpp deleted file mode 100644 index b8ea13652f..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/Unused1D.cpp +++ /dev/null @@ -1,21 +0,0 @@ -#include "Unused1D.h" -#include "Utils/StringHelper.h" - -Unused1D::Unused1D(ZFile* nParent) : ZRoomCommand(nParent) -{ -} - -std::string Unused1D::GetBodySourceCode() const -{ - return StringHelper::Sprintf("{ %s, 0x00, 0x00 }", GetCommandHex().c_str()); -} - -std::string Unused1D::GetCommandCName() const -{ - return "SceneCmd"; -} - -RoomCommand Unused1D::GetRoomCommand() const -{ - return RoomCommand::Unused1D; -} diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/Unused1D.h b/tools/ZAPD/ZAPD/ZRoom/Commands/Unused1D.h deleted file mode 100644 index dea0f98ee5..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/Unused1D.h +++ /dev/null @@ -1,14 +0,0 @@ -#pragma once - -#include "ZRoom/ZRoomCommand.h" - -class Unused1D : public ZRoomCommand -{ -public: - Unused1D(ZFile* nParent); - - std::string GetBodySourceCode() const override; - - RoomCommand GetRoomCommand() const override; - std::string GetCommandCName() const override; -}; diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/ZRoomCommandUnk.cpp b/tools/ZAPD/ZAPD/ZRoom/Commands/ZRoomCommandUnk.cpp deleted file mode 100644 index a892086c2a..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/ZRoomCommandUnk.cpp +++ /dev/null @@ -1,20 +0,0 @@ -#include "ZRoomCommandUnk.h" -#include "Utils/BitConverter.h" -#include "Utils/StringHelper.h" -#include "ZRoom/ZRoom.h" - -ZRoomCommandUnk::ZRoomCommandUnk(ZFile* nParent) : ZRoomCommand(nParent) -{ -} - -std::string ZRoomCommandUnk::GetBodySourceCode() const -{ - return StringHelper::Sprintf("{ %s, 0x%02X, 0x%06X } /* WARNING: " - "UNIMPLEMENTED ROOM COMMAND */", - GetCommandHex().c_str(), cmdArg1, cmdArg2); -} - -RoomCommand ZRoomCommandUnk::GetRoomCommand() const -{ - return RoomCommand::Error; -} diff --git a/tools/ZAPD/ZAPD/ZRoom/Commands/ZRoomCommandUnk.h b/tools/ZAPD/ZAPD/ZRoom/Commands/ZRoomCommandUnk.h deleted file mode 100644 index e381fe5a52..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/Commands/ZRoomCommandUnk.h +++ /dev/null @@ -1,12 +0,0 @@ -#pragma once -#include "ZRoom/ZRoomCommand.h" - -class ZRoomCommandUnk : public ZRoomCommand -{ -public: - ZRoomCommandUnk(ZFile* nParent); - - std::string GetBodySourceCode() const override; - - RoomCommand GetRoomCommand() const override; -}; diff --git a/tools/ZAPD/ZAPD/ZRoom/ZNames.h b/tools/ZAPD/ZAPD/ZRoom/ZNames.h deleted file mode 100644 index 83c217e999..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/ZNames.h +++ /dev/null @@ -1,68 +0,0 @@ -#pragma once - -#include - -#include "Globals.h" -#include "Utils/StringHelper.h" - -class ZNames -{ -public: - static std::string GetObjectName(size_t id) - { - if (id >= Globals::Instance->cfg.objectList.size()) - return StringHelper::Sprintf("0x%04X", id); - return Globals::Instance->cfg.objectList[id]; - } - - static std::string GetActorName(uint16_t id) - { - switch (Globals::Instance->game) - { - case ZGame::OOT_RETAIL: - case ZGame::OOT_SW97: - if (id < ZNames::GetNumActors()) - return Globals::Instance->cfg.actorList[id]; - else - return StringHelper::Sprintf("0x%04X", id); - case ZGame::MM_RETAIL: - { - int32_t flags = id & 0xF000; - id &= 0xFFF; - std::string name; - if (id < ZNames::GetNumActors()) - name = Globals::Instance->cfg.actorList[id]; - else - name = StringHelper::Sprintf("0x%04X", id); - - if (flags == 0) - return name; - else - return StringHelper::Sprintf("%s | 0x%04X", name.c_str(), flags); - } - } - - return ""; - } - - static std::string GetEntranceName(uint16_t id) - { - if (ZNames::GetNumEntrances() == 0 || ZNames::GetNumSpecialEntrances() == 0) - return StringHelper::Sprintf("0x%04X", id); - - if (id < ZNames::GetNumEntrances()) - return Globals::Instance->cfg.entranceList[id]; - else if ((id >= 0x7FF9 && id <= 0x7FFF) && - !((id - 0x7FF9U) > GetNumSpecialEntrances())) // Special entrances - return Globals::Instance->cfg.specialEntranceList[id - 0x7FF9]; - else - return StringHelper::Sprintf("0x%04X", id); - } - - static size_t GetNumActors() { return Globals::Instance->cfg.actorList.size(); } - static size_t GetNumEntrances() { return Globals::Instance->cfg.entranceList.size(); } - static size_t GetNumSpecialEntrances() - { - return Globals::Instance->cfg.specialEntranceList.size(); - } -}; diff --git a/tools/ZAPD/ZAPD/ZRoom/ZRoom.cpp b/tools/ZAPD/ZAPD/ZRoom/ZRoom.cpp deleted file mode 100644 index a291c36feb..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/ZRoom.cpp +++ /dev/null @@ -1,409 +0,0 @@ -#include "ZRoom.h" -#include -#include -#include -#include -#include - -#include "Commands/EndMarker.h" -#include "Commands/SetCutsceneEntryList.h" -#include "Commands/SetActorList.h" -#include "Commands/SetAlternateHeaders.h" -#include "Commands/SetAnimatedMaterialList.h" -#include "Commands/SetCameraSettings.h" -#include "Commands/SetCollisionHeader.h" -#include "Commands/SetCsCamera.h" -#include "Commands/SetCutscenes.h" -#include "Commands/SetEchoSettings.h" -#include "Commands/SetEntranceList.h" -#include "Commands/SetExitList.h" -#include "Commands/SetLightList.h" -#include "Commands/SetLightingSettings.h" -#include "Commands/SetMesh.h" -#include "Commands/SetMinimapChests.h" -#include "Commands/SetMinimapList.h" -#include "Commands/SetObjectList.h" -#include "Commands/SetPathways.h" -#include "Commands/SetRoomBehavior.h" -#include "Commands/SetRoomList.h" -#include "Commands/SetSkyboxModifier.h" -#include "Commands/SetSkyboxSettings.h" -#include "Commands/SetSoundSettings.h" -#include "Commands/SetSpecialObjects.h" -#include "Commands/SetStartPositionList.h" -#include "Commands/SetTimeSettings.h" -#include "Commands/SetTransitionActorList.h" -#include "Commands/SetWind.h" -#include "Commands/SetWorldMapVisited.h" -#include "Commands/Unused09.h" -#include "Commands/Unused1D.h" -#include "Commands/ZRoomCommandUnk.h" -#include "Globals.h" -#include "Utils/File.h" -#include "Utils/Path.h" -#include "Utils/StringHelper.h" -#include "WarningHandler.h" -#include "ZBlob.h" -#include "ZCutscene.h" -#include "ZFile.h" - -REGISTER_ZFILENODE(Room, ZRoom); -REGISTER_ZFILENODE(Scene, ZRoom); -REGISTER_ZFILENODE(AltHeader, ZRoom); - -ZRoom::ZRoom(ZFile* nParent) : ZResource(nParent) -{ - roomCount = -1; - canHaveInner = true; - RegisterOptionalAttribute("HackMode"); -} - -ZRoom::~ZRoom() -{ - for (ZRoomCommand* cmd : commands) - delete cmd; -} - -void ZRoom::ExtractWithXML(tinyxml2::XMLElement* reader, uint32_t nRawDataIndex) -{ - ZResource::ExtractWithXML(reader, nRawDataIndex); - - if (hackMode == "syotes_room") - SyotesRoomFix(); - else - DeclareVar(name, ""); -} - -void ZRoom::ExtractFromBinary(uint32_t nRawDataIndex, ZResourceType parentType) -{ - rawDataIndex = nRawDataIndex; - name = GetDefaultName(parent->GetName()); - - zroomType = ZResourceType::AltHeader; - switch (parentType) - { - case ZResourceType::Scene: - case ZResourceType::Room: - case ZResourceType::AltHeader: - parentZroomType = parentType; - break; - - default: - // TODO: error message or something - assert(false); - break; - } - - ParseRawData(); - DeclareVar(name, ""); -} - -void ZRoom::ParseXML(tinyxml2::XMLElement* reader) -{ - ZResource::ParseXML(reader); - - // TODO: HACK: remove this specific check when the repo uses the correct HackMode="syotes_room" - if (name == "syotes_room_0") - { - hackMode = "syotes_room"; - } - - std::string nodeName = std::string(reader->Name()); - if (nodeName == "Scene") - { - zroomType = ZResourceType::Scene; - } - else if (nodeName == "Room") - zroomType = ZResourceType::Room; - else if (nodeName == "AltHeader") - zroomType = ZResourceType::AltHeader; - - if (reader->Attribute("HackMode") != nullptr) - { - hackMode = std::string(reader->Attribute("HackMode")); - if (hackMode != "syotes_room") - { - std::string headerError = StringHelper::Sprintf( - "invalid value found for 'HackMode' attribute: '%s'", hackMode.c_str()); - HANDLE_ERROR_RESOURCE(WarningType::InvalidAttributeValue, parent, this, rawDataIndex, - headerError, ""); - } - } -} - -void ZRoom::ParseRawData() -{ - if (hackMode == "syotes_room") - return; - - bool shouldContinue = true; - uint32_t currentIndex = 0; - uint32_t currentPtr = rawDataIndex; - - const auto& rawData = parent->GetRawData(); - while (shouldContinue) - { - RoomCommand opcode = static_cast(rawData.at(currentPtr)); - - ZRoomCommand* cmd = nullptr; - - auto start = std::chrono::steady_clock::now(); - - switch (opcode) - { - case RoomCommand::SetStartPositionList: - cmd = new SetStartPositionList(parent); - break; // 0x00 - case RoomCommand::SetActorList: - cmd = new SetActorList(parent); - break; // 0x01 - case RoomCommand::SetCsCamera: - cmd = new SetCsCamera(parent); - break; // 0x02 (MM-ONLY) - case RoomCommand::SetCollisionHeader: - cmd = new SetCollisionHeader(parent); - break; // 0x03 - case RoomCommand::SetRoomList: - cmd = new SetRoomList(parent); - break; // 0x04 - case RoomCommand::SetWind: - cmd = new SetWind(parent); - break; // 0x05 - case RoomCommand::SetEntranceList: - cmd = new SetEntranceList(parent); - break; // 0x06 - case RoomCommand::SetSpecialObjects: - cmd = new SetSpecialObjects(parent); - break; // 0x07 - case RoomCommand::SetRoomBehavior: - cmd = new SetRoomBehavior(parent); - break; // 0x08 - case RoomCommand::Unused09: - cmd = new Unused09(parent); - break; // 0x09 - case RoomCommand::SetMesh: - cmd = new SetMesh(parent); - break; // 0x0A - case RoomCommand::SetObjectList: - cmd = new SetObjectList(parent); - break; // 0x0B - case RoomCommand::SetLightList: - cmd = new SetLightList(parent); - break; // 0x0C (MM-ONLY) - case RoomCommand::SetPathways: - cmd = new SetPathways(parent); - break; // 0x0D - case RoomCommand::SetTransitionActorList: - cmd = new SetTransitionActorList(parent); - break; // 0x0E - case RoomCommand::SetLightingSettings: - cmd = new SetLightingSettings(parent); - break; // 0x0F - case RoomCommand::SetTimeSettings: - cmd = new SetTimeSettings(parent); - break; // 0x10 - case RoomCommand::SetSkyboxSettings: - cmd = new SetSkyboxSettings(parent); - break; // 0x11 - case RoomCommand::SetSkyboxModifier: - cmd = new SetSkyboxModifier(parent); - break; // 0x12 - case RoomCommand::SetExitList: - cmd = new SetExitList(parent); - break; // 0x13 - case RoomCommand::EndMarker: - cmd = new EndMarker(parent); - break; // 0x14 - case RoomCommand::SetSoundSettings: - cmd = new SetSoundSettings(parent); - break; // 0x15 - case RoomCommand::SetEchoSettings: - cmd = new SetEchoSettings(parent); - break; // 0x16 - case RoomCommand::SetCutscenes: - cmd = new SetCutscenes(parent); - break; // 0x17 - case RoomCommand::SetAlternateHeaders: - cmd = new SetAlternateHeaders(parent); - break; // 0x18 - case RoomCommand::SetCameraSettings: - if (Globals::Instance->game == ZGame::MM_RETAIL) - cmd = new SetWorldMapVisited(parent); - else - cmd = new SetCameraSettings(parent); - break; // 0x19 - case RoomCommand::SetAnimatedMaterialList: - cmd = new SetAnimatedMaterialList(parent); - break; // 0x1A (MM-ONLY) - case RoomCommand::SetActorCutsceneList: - cmd = new SetActorCutsceneList(parent); - break; // 0x1B (MM-ONLY) - case RoomCommand::SetMinimapList: - cmd = new SetMinimapList(parent); - break; // 0x1C (MM-ONLY) - case RoomCommand::Unused1D: - cmd = new Unused1D(parent); - break; // 0x1D - case RoomCommand::SetMinimapChests: - cmd = new SetMinimapChests(parent); - break; // 0x1E (MM-ONLY) - default: - cmd = new ZRoomCommandUnk(parent); - } - - cmd->commandSet = rawDataIndex; - cmd->ExtractCommandFromRoom(this, currentPtr); - - if (Globals::Instance->profile) - { - auto end = std::chrono::steady_clock::now(); - int64_t diff = - std::chrono::duration_cast(end - start).count(); - if (diff > 50) - printf("OP: %s, TIME: %" PRIi64 "ms\n", cmd->GetCommandCName().c_str(), diff); - } - - cmd->cmdIndex = currentIndex; - - commands.push_back(cmd); - - if (opcode == RoomCommand::EndMarker) - shouldContinue = false; - - currentPtr += 8; - currentIndex++; - } -} - -void ZRoom::DeclareReferences(const std::string& prefix) -{ - for (auto& cmd : commands) - cmd->DeclareReferences(prefix); -} - -void ZRoom::ParseRawDataLate() -{ - for (auto& cmd : commands) - cmd->ParseRawDataLate(); -} - -void ZRoom::DeclareReferencesLate(const std::string& prefix) -{ - for (auto& cmd : commands) - cmd->DeclareReferencesLate(prefix); -} - -Declaration* ZRoom::DeclareVar(const std::string& prefix, const std::string& body) -{ - std::string auxName = name; - if (auxName == "") - auxName = GetDefaultName(prefix); - if (zroomType == ZResourceType::Scene || zroomType == ZResourceType::Room) - auxName = StringHelper::Sprintf("%sCommands", name.c_str()); - - Declaration* decl = - parent->AddDeclarationArray(rawDataIndex, GetDeclarationAlignment(), GetRawDataSize(), - GetSourceTypeName(), auxName, commands.size(), body); - decl->staticConf = staticConf; - return decl; -} - -std::string ZRoom::GetBodySourceCode() const -{ - std::string declaration; - - for (size_t i = 0; i < commands.size(); i++) - { - ZRoomCommand* cmd = commands[i]; - declaration += StringHelper::Sprintf("\t%s,", cmd->GetBodySourceCode().c_str()); - - if (i + 1 < commands.size()) - declaration += "\n"; - } - - return declaration; -} - -std::string ZRoom::GetDefaultName(const std::string& prefix) const -{ - return StringHelper::Sprintf("%sSet_%06X", prefix.c_str(), rawDataIndex); -} - -/* - * There is one room in Ocarina of Time that lacks a header. Room 120, "Syotes", dates - * back to very early in the game's development. Since this room is a special case, - * declare automatically the data its contains whitout the need of a header. - */ -void ZRoom::SyotesRoomFix() -{ - RoomShapeCullable poly(parent, 0, this); - - poly.ParseRawData(); - poly.DeclareReferences(GetName()); - parent->AddDeclaration(0, poly.GetDeclarationAlignment(), poly.GetRawDataSize(), - poly.GetSourceTypeName(), poly.GetDefaultName(GetName()), - poly.GetBodySourceCode()); -} - -ZRoomCommand* ZRoom::FindCommandOfType(RoomCommand cmdType) -{ - for (size_t i = 0; i < commands.size(); i++) - { - if (commands[i]->GetRoomCommand() == cmdType) - return commands[i]; - } - - return nullptr; -} - -size_t ZRoom::GetCommandSizeFromNeighbor(ZRoomCommand* cmd) -{ - int32_t cmdIndex = -1; - - for (size_t i = 0; i < commands.size(); i++) - { - if (commands[i] == cmd) - { - cmdIndex = i; - break; - } - } - - if (cmdIndex != -1) - { - if (cmdIndex + 1 < (int32_t)commands.size()) - return commands[cmdIndex + 1]->cmdAddress - commands[cmdIndex]->cmdAddress; - else - return parent->GetRawData().size() - commands[cmdIndex]->cmdAddress; - } - - return 0; -} - -void ZRoom::GetSourceOutputCode([[maybe_unused]] const std::string& prefix) -{ - if (hackMode != "syotes_room") - DeclareVar(prefix, GetBodySourceCode()); -} - -size_t ZRoom::GetRawDataSize() const -{ - size_t size = 0; - - for (ZRoomCommand* cmd : commands) - size += cmd->GetRawDataSize(); - - return size; -} - -std::string ZRoom::GetSourceTypeName() const -{ - return "SceneCmd"; -} - -ZResourceType ZRoom::GetResourceType() const -{ - assert(zroomType == ZResourceType::Scene || zroomType == ZResourceType::Room || - zroomType == ZResourceType::AltHeader); - return zroomType; -} diff --git a/tools/ZAPD/ZAPD/ZRoom/ZRoom.h b/tools/ZAPD/ZAPD/ZRoom/ZRoom.h deleted file mode 100644 index 950dbbb182..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/ZRoom.h +++ /dev/null @@ -1,49 +0,0 @@ -#pragma once - -#include -#include -#include - -#include "ZResource.h" -#include "ZRoomCommand.h" -#include "tinyxml2.h" - -class ZRoom : public ZResource -{ -public: - std::vector commands; - int32_t roomCount; // Only valid for scenes - - std::string hackMode; - - ZResourceType zroomType = ZResourceType::Error; - ZResourceType parentZroomType = ZResourceType::Error; - - ZRoom(ZFile* nParent); - virtual ~ZRoom(); - - void ExtractWithXML(tinyxml2::XMLElement* reader, uint32_t nRawDataIndex) override; - void ExtractFromBinary(uint32_t nRawDataIndex, ZResourceType parentType); - - void ParseXML(tinyxml2::XMLElement* reader) override; - void ParseRawData() override; - void DeclareReferences(const std::string& prefix) override; - void ParseRawDataLate() override; - void DeclareReferencesLate(const std::string& prefix) override; - - Declaration* DeclareVar(const std::string& prefix, const std::string& body) override; - std::string GetBodySourceCode() const override; - - void GetSourceOutputCode(const std::string& prefix) override; - - std::string GetDefaultName(const std::string& prefix) const override; - size_t GetCommandSizeFromNeighbor(ZRoomCommand* cmd); - ZRoomCommand* FindCommandOfType(RoomCommand cmdType); - - size_t GetRawDataSize() const override; - std::string GetSourceTypeName() const override; - ZResourceType GetResourceType() const override; - -protected: - void SyotesRoomFix(); -}; diff --git a/tools/ZAPD/ZAPD/ZRoom/ZRoomCommand.cpp b/tools/ZAPD/ZAPD/ZRoom/ZRoomCommand.cpp deleted file mode 100644 index 711c86a409..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/ZRoomCommand.cpp +++ /dev/null @@ -1,58 +0,0 @@ -#include "ZRoomCommand.h" - -#include "Utils/BitConverter.h" -#include "Utils/StringHelper.h" -#include "ZRoom.h" - -ZRoomCommand::ZRoomCommand(ZFile* nParent) : ZResource(nParent) -{ -} - -void ZRoomCommand::ExtractCommandFromRoom(ZRoom* nZRoom, uint32_t nRawDataIndex) -{ - zRoom = nZRoom; - rawDataIndex = nRawDataIndex; - - ParseRawData(); -} - -void ZRoomCommand::ParseRawData() -{ - auto& parentRawData = parent->GetRawData(); - cmdID = static_cast(parentRawData.at(rawDataIndex)); - cmdAddress = rawDataIndex; - - cmdArg1 = parentRawData.at(rawDataIndex + 1); - cmdArg2 = BitConverter::ToUInt32BE(parentRawData, rawDataIndex + 4); - segmentOffset = Seg2Filespace(cmdArg2, parent->baseAddress); -} - -RoomCommand ZRoomCommand::GetRoomCommand() const -{ - return RoomCommand::Error; -} - -size_t ZRoomCommand::GetRawDataSize() const -{ - return 0x08; -} - -std::string ZRoomCommand::GetSourceTypeName() const -{ - return GetCommandCName(); -} - -ZResourceType ZRoomCommand::GetResourceType() const -{ - return ZResourceType::RoomCommand; -} - -std::string ZRoomCommand::GetCommandCName() const -{ - return "SceneCmd"; -} - -std::string ZRoomCommand::GetCommandHex() const -{ - return StringHelper::Sprintf("0x%02X", static_cast(cmdID)); -} diff --git a/tools/ZAPD/ZAPD/ZRoom/ZRoomCommand.h b/tools/ZAPD/ZAPD/ZRoom/ZRoomCommand.h deleted file mode 100644 index e4029984c9..0000000000 --- a/tools/ZAPD/ZAPD/ZRoom/ZRoomCommand.h +++ /dev/null @@ -1,84 +0,0 @@ -#pragma once - -#include "tinyxml2.h" - -#include -#include - -#include "ZFile.h" -#include "ZResource.h" - -class ZRoom; - -enum class RoomCommand : uint8_t -{ - SetStartPositionList = 0x00, - SetActorList = 0x01, - SetCsCamera = 0x02, - SetCollisionHeader = 0x03, - SetRoomList = 0x04, - SetWind = 0x05, - SetEntranceList = 0x06, - SetSpecialObjects = 0x07, - SetRoomBehavior = 0x08, - Unused09 = 0x09, - SetMesh = 0x0A, - SetObjectList = 0x0B, - SetLightList = 0x0C, - SetPathways = 0x0D, - SetTransitionActorList = 0x0E, - SetLightingSettings = 0x0F, - SetTimeSettings = 0x10, - SetSkyboxSettings = 0x11, - SetSkyboxModifier = 0x12, - SetExitList = 0x13, - EndMarker = 0x14, - SetSoundSettings = 0x15, - SetEchoSettings = 0x16, - SetCutscenes = 0x17, - SetAlternateHeaders = 0x18, - SetCameraSettings = 0x19, - - // MM Commands - SetWorldMapVisited = 0x19, - SetAnimatedMaterialList = 0x1A, - SetActorCutsceneList = 0x1B, - SetMinimapList = 0x1C, - Unused1D = 0x1D, - SetMinimapChests = 0x1E, - - Error = 0xFF -}; - -class ZRoomCommand : public ZResource -{ -public: - int32_t cmdAddress; - uint32_t cmdIndex; - uint32_t commandSet; - RoomCommand cmdID; - offset_t segmentOffset; - - ZRoomCommand(ZFile* nParent); - virtual ~ZRoomCommand() = default; - - virtual void ExtractCommandFromRoom(ZRoom* nZRoom, uint32_t nRawDataIndex); - - void ParseRawData() override; - - std::string GetSourceTypeName() const override; - ZResourceType GetResourceType() const override; - - // Getters/Setters - virtual RoomCommand GetRoomCommand() const = 0; - size_t GetRawDataSize() const final override; - virtual std::string GetCommandCName() const; - - virtual std::string GetCommandHex() const; - -protected: - ZRoom* zRoom; - - uint8_t cmdArg1; - segptr_t cmdArg2; -}; diff --git a/tools/ZAPD/ZAPD/ZScalar.cpp b/tools/ZAPD/ZAPD/ZScalar.cpp deleted file mode 100644 index 7e4be4d57f..0000000000 --- a/tools/ZAPD/ZAPD/ZScalar.cpp +++ /dev/null @@ -1,280 +0,0 @@ -#include "ZScalar.h" - -#include "Globals.h" -#include "Utils/BitConverter.h" -#include "Utils/File.h" -#include "Utils/StringHelper.h" -#include "WarningHandler.h" -#include "ZFile.h" - -REGISTER_ZFILENODE(Scalar, ZScalar); - -ZScalar::ZScalar(ZFile* nParent) : ZResource(nParent) -{ - memset(&scalarData, 0, sizeof(ZScalarData)); - scalarType = ZScalarType::ZSCALAR_NONE; - RegisterRequiredAttribute("Type"); -} - -void ZScalar::ExtractFromBinary(uint32_t nRawDataIndex, ZScalarType nScalarType) -{ - rawDataIndex = nRawDataIndex; - scalarType = nScalarType; - - // Don't parse raw data of external files - if (parent->GetMode() == ZFileMode::ExternalFile) - return; - - ParseRawData(); -} - -void ZScalar::ParseXML(tinyxml2::XMLElement* reader) -{ - ZResource::ParseXML(reader); - - scalarType = ZScalar::MapOutputTypeToScalarType(registeredAttributes.at("Type").value); -} - -ZScalarType ZScalar::MapOutputTypeToScalarType(const std::string& type) -{ - if (type == "s8") - { - return ZScalarType::ZSCALAR_S8; - } - else if (type == "u8") - { - return ZScalarType::ZSCALAR_U8; - } - else if (type == "x8") - { - return ZScalarType::ZSCALAR_X8; - } - else if (type == "s16") - { - return ZScalarType::ZSCALAR_S16; - } - else if (type == "u16") - { - return ZScalarType::ZSCALAR_U16; - } - else if (type == "x16") - { - return ZScalarType::ZSCALAR_X16; - } - else if (type == "s32") - { - return ZScalarType::ZSCALAR_S32; - } - else if (type == "u32") - { - return ZScalarType::ZSCALAR_U32; - } - else if (type == "x32") - { - return ZScalarType::ZSCALAR_X32; - } - else if (type == "s64") - { - return ZScalarType::ZSCALAR_S64; - } - else if (type == "u64") - { - return ZScalarType::ZSCALAR_U64; - } - else if (type == "x64") - { - return ZScalarType::ZSCALAR_X64; - } - else if (type == "f32") - { - return ZScalarType::ZSCALAR_F32; - } - else if (type == "f64") - { - return ZScalarType::ZSCALAR_F64; - } - - return ZScalarType::ZSCALAR_NONE; -} - -std::string ZScalar::MapScalarTypeToOutputType(const ZScalarType scalarType) -{ - switch (scalarType) - { - case ZScalarType::ZSCALAR_S8: - return "s8"; - case ZScalarType::ZSCALAR_U8: - case ZScalarType::ZSCALAR_X8: - return "u8"; - case ZScalarType::ZSCALAR_S16: - return "s16"; - case ZScalarType::ZSCALAR_U16: - case ZScalarType::ZSCALAR_X16: - return "u16"; - case ZScalarType::ZSCALAR_S32: - return "s32"; - case ZScalarType::ZSCALAR_U32: - case ZScalarType::ZSCALAR_X32: - return "u32"; - case ZScalarType::ZSCALAR_S64: - return "s64"; - case ZScalarType::ZSCALAR_U64: - case ZScalarType::ZSCALAR_X64: - return "u64"; - case ZScalarType::ZSCALAR_F32: - return "f32"; - case ZScalarType::ZSCALAR_F64: - return "f64"; - default: - return ""; - } -} - -size_t ZScalar::MapTypeToSize(const ZScalarType scalarType) -{ - switch (scalarType) - { - case ZScalarType::ZSCALAR_S8: - return sizeof(scalarData.s8); - case ZScalarType::ZSCALAR_U8: - case ZScalarType::ZSCALAR_X8: - return sizeof(scalarData.u8); - case ZScalarType::ZSCALAR_S16: - return sizeof(scalarData.s16); - case ZScalarType::ZSCALAR_U16: - case ZScalarType::ZSCALAR_X16: - return sizeof(scalarData.u16); - case ZScalarType::ZSCALAR_S32: - return sizeof(scalarData.s32); - case ZScalarType::ZSCALAR_U32: - case ZScalarType::ZSCALAR_X32: - return sizeof(scalarData.u32); - case ZScalarType::ZSCALAR_S64: - return sizeof(scalarData.s64); - case ZScalarType::ZSCALAR_U64: - case ZScalarType::ZSCALAR_X64: - return sizeof(scalarData.u64); - case ZScalarType::ZSCALAR_F32: - return sizeof(scalarData.f32); - case ZScalarType::ZSCALAR_F64: - return sizeof(scalarData.f64); - default: - return 0; - } -} - -size_t ZScalar::GetRawDataSize() const -{ - return ZScalar::MapTypeToSize(scalarType); -} - -void ZScalar::ParseRawData() -{ - const auto& rawData = parent->GetRawData(); - switch (scalarType) - { - case ZScalarType::ZSCALAR_S8: - scalarData.s8 = BitConverter::ToInt8BE(rawData, rawDataIndex); - break; - case ZScalarType::ZSCALAR_U8: - case ZScalarType::ZSCALAR_X8: - scalarData.u8 = BitConverter::ToUInt8BE(rawData, rawDataIndex); - break; - case ZScalarType::ZSCALAR_S16: - scalarData.s16 = BitConverter::ToInt16BE(rawData, rawDataIndex); - break; - case ZScalarType::ZSCALAR_U16: - case ZScalarType::ZSCALAR_X16: - scalarData.u16 = BitConverter::ToUInt16BE(rawData, rawDataIndex); - break; - case ZScalarType::ZSCALAR_S32: - scalarData.s32 = BitConverter::ToInt32BE(rawData, rawDataIndex); - break; - case ZScalarType::ZSCALAR_U32: - case ZScalarType::ZSCALAR_X32: - scalarData.u32 = BitConverter::ToUInt32BE(rawData, rawDataIndex); - break; - case ZScalarType::ZSCALAR_S64: - scalarData.s64 = BitConverter::ToInt64BE(rawData, rawDataIndex); - break; - case ZScalarType::ZSCALAR_U64: - case ZScalarType::ZSCALAR_X64: - scalarData.u64 = BitConverter::ToUInt64BE(rawData, rawDataIndex); - break; - case ZScalarType::ZSCALAR_F32: - scalarData.f32 = BitConverter::ToFloatBE(rawData, rawDataIndex); - break; - case ZScalarType::ZSCALAR_F64: - scalarData.f64 = BitConverter::ToDoubleBE(rawData, rawDataIndex); - break; - case ZScalarType::ZSCALAR_NONE: - HANDLE_ERROR_RESOURCE(WarningType::InvalidAttributeValue, parent, this, rawDataIndex, - "invalid value found for 'Type' attribute", "Defaulting to ''"); - break; - } -} - -std::string ZScalar::GetSourceTypeName() const -{ - return ZScalar::MapScalarTypeToOutputType(scalarType); -} - -std::string ZScalar::GetBodySourceCode() const -{ - switch (scalarType) - { - case ZScalarType::ZSCALAR_S8: - return StringHelper::Sprintf("%hhd", scalarData.s8); - case ZScalarType::ZSCALAR_U8: - return StringHelper::Sprintf("%hhu", scalarData.u8); - case ZScalarType::ZSCALAR_X8: - return StringHelper::Sprintf("0x%02X", scalarData.u8); - case ZScalarType::ZSCALAR_S16: - return StringHelper::Sprintf("%hd", scalarData.s16); - case ZScalarType::ZSCALAR_U16: - return StringHelper::Sprintf("%hu", scalarData.u16); - case ZScalarType::ZSCALAR_X16: - return StringHelper::Sprintf("0x%04X", scalarData.u16); - case ZScalarType::ZSCALAR_S32: - return StringHelper::Sprintf("%d", scalarData.s32); - case ZScalarType::ZSCALAR_U32: - return StringHelper::Sprintf("%u", scalarData.u32); - case ZScalarType::ZSCALAR_X32: - return StringHelper::Sprintf("0x%08X", scalarData.u32); - case ZScalarType::ZSCALAR_S64: - return StringHelper::Sprintf("%lld", scalarData.s64); - case ZScalarType::ZSCALAR_U64: - return StringHelper::Sprintf("%llu", scalarData.u64); - case ZScalarType::ZSCALAR_X64: - return StringHelper::Sprintf("0x%016X", scalarData.u64); - case ZScalarType::ZSCALAR_F32: - return StringHelper::Sprintf("%f", scalarData.f32); - case ZScalarType::ZSCALAR_F64: - return StringHelper::Sprintf("%lf", scalarData.f64); - default: - return "SCALAR_ERROR"; - } -} - -ZResourceType ZScalar::GetResourceType() const -{ - return ZResourceType::Scalar; -} - -bool ZScalar::DoesSupportArray() const -{ - return true; -} - -DeclarationAlignment ZScalar::GetDeclarationAlignment() const -{ - switch (scalarType) - { - case ZScalarType::ZSCALAR_S64: - case ZScalarType::ZSCALAR_U64: - case ZScalarType::ZSCALAR_F64: - return DeclarationAlignment::Align8; - default: - return DeclarationAlignment::Align4; - } -} diff --git a/tools/ZAPD/ZAPD/ZScalar.h b/tools/ZAPD/ZAPD/ZScalar.h deleted file mode 100644 index 8f98f261d7..0000000000 --- a/tools/ZAPD/ZAPD/ZScalar.h +++ /dev/null @@ -1,68 +0,0 @@ -#pragma once - -#include -#include -#include -#include "ZResource.h" -#include "tinyxml2.h" - -enum class ZScalarType -{ - ZSCALAR_NONE, - ZSCALAR_S8, - ZSCALAR_U8, - ZSCALAR_X8, - ZSCALAR_S16, - ZSCALAR_U16, - ZSCALAR_X16, - ZSCALAR_S32, - ZSCALAR_U32, - ZSCALAR_X32, - ZSCALAR_S64, - ZSCALAR_U64, - ZSCALAR_X64, - ZSCALAR_F32, - ZSCALAR_F64 -}; - -typedef union ZScalarData -{ - uint8_t u8; - int8_t s8; - uint16_t u16; - int16_t s16; - uint32_t u32; - int32_t s32; - uint64_t u64; - int64_t s64; - float f32; - double f64; -} ZScalarData; - -class ZScalar : public ZResource -{ - friend class ZVector; - -public: - ZScalarData scalarData; - ZScalarType scalarType; - - ZScalar(ZFile* nParent); - - void ExtractFromBinary(uint32_t nRawDataIndex, ZScalarType nScalarType); - - void ParseRawData() override; - void ParseXML(tinyxml2::XMLElement* reader) override; - std::string GetBodySourceCode() const override; - - bool DoesSupportArray() const override; - std::string GetSourceTypeName() const override; - ZResourceType GetResourceType() const override; - - size_t GetRawDataSize() const override; - DeclarationAlignment GetDeclarationAlignment() const override; - - static size_t MapTypeToSize(const ZScalarType scalarType); - static ZScalarType MapOutputTypeToScalarType(const std::string& type); - static std::string MapScalarTypeToOutputType(const ZScalarType scalarType); -}; diff --git a/tools/ZAPD/ZAPD/ZSkeleton.cpp b/tools/ZAPD/ZAPD/ZSkeleton.cpp deleted file mode 100644 index 86b578639f..0000000000 --- a/tools/ZAPD/ZAPD/ZSkeleton.cpp +++ /dev/null @@ -1,472 +0,0 @@ -#include "ZSkeleton.h" - -#include - -#include "Globals.h" -#include "Utils/BitConverter.h" -#include "Utils/StringHelper.h" -#include "WarningHandler.h" - -REGISTER_ZFILENODE(Skeleton, ZSkeleton); -REGISTER_ZFILENODE(LimbTable, ZLimbTable); - -ZSkeleton::ZSkeleton(ZFile* nParent) : ZResource(nParent) -{ - RegisterRequiredAttribute("Type"); - RegisterRequiredAttribute("LimbType"); - RegisterOptionalAttribute("EnumName"); - RegisterOptionalAttribute("LimbNone"); - RegisterOptionalAttribute("LimbMax"); -} - -void ZSkeleton::ParseXML(tinyxml2::XMLElement* reader) -{ - ZResource::ParseXML(reader); - - std::string skelTypeXml = registeredAttributes.at("Type").value; - - if (skelTypeXml == "Flex") - type = ZSkeletonType::Flex; - else if (skelTypeXml == "Curve") - type = ZSkeletonType::Curve; - else if (skelTypeXml != "Normal") - { - HANDLE_ERROR_RESOURCE(WarningType::InvalidAttributeValue, parent, this, rawDataIndex, - "invalid value found for 'Type' attribute", ""); - } - - std::string limbTypeXml = registeredAttributes.at("LimbType").value; - limbType = ZLimb::GetTypeByAttributeName(limbTypeXml); - if (limbType == ZLimbType::Invalid) - { - HANDLE_ERROR_RESOURCE( - WarningType::InvalidAttributeValue, parent, this, rawDataIndex, - StringHelper::Sprintf("invalid value '%s' found for 'LimbType' attribute", - limbTypeXml.c_str()), - "Defaulting to 'Standard'."); - } - - enumName = registeredAttributes.at("EnumName").value; - limbNoneName = registeredAttributes.at("LimbNone").value; - limbMaxName = registeredAttributes.at("LimbMax").value; - - if (enumName != "") - { - if (limbNoneName == "" || limbMaxName == "") - { - HANDLE_ERROR_RESOURCE(WarningType::MissingAttribute, parent, this, rawDataIndex, - "'EnumName' attribute was used but either 'LimbNone' or " - "'LimbMax' attribute is missing", - ""); - } - } - - if (limbNoneName != "") - { - if (limbMaxName == "") - { - HANDLE_ERROR_RESOURCE( - WarningType::MissingAttribute, parent, this, rawDataIndex, - "'LimbNone' attribute was used but 'LimbMax' attribute is missing", ""); - } - } - - if (limbMaxName != "") - { - if (limbNoneName == "") - { - HANDLE_ERROR_RESOURCE( - WarningType::MissingAttribute, parent, this, rawDataIndex, - "'LimbMax' attribute was used but 'LimbNone' attribute is missing", ""); - } - } -} - -void ZSkeleton::ParseRawData() -{ - ZResource::ParseRawData(); - - const auto& rawData = parent->GetRawData(); - limbsArrayAddress = BitConverter::ToUInt32BE(rawData, rawDataIndex); - limbCount = BitConverter::ToUInt8BE(rawData, rawDataIndex + 4); - - if (type == ZSkeletonType::Flex) - { - dListCount = BitConverter::ToUInt8BE(rawData, rawDataIndex + 8); - } -} - -void ZSkeleton::DeclareReferences(const std::string& prefix) -{ - std::string defaultPrefix = name; - if (defaultPrefix == "") - defaultPrefix = prefix; - - ZResource::DeclareReferences(defaultPrefix); - - if (limbsArrayAddress != SEGMENTED_NULL && GETSEGNUM(limbsArrayAddress) == parent->segment) - { - offset_t ptr = Seg2Filespace(limbsArrayAddress, parent->baseAddress); - - if (!parent->HasDeclaration(ptr)) - { - limbsTable = new ZLimbTable(parent); - limbsTable->ExtractFromBinary(ptr, limbType, limbCount); - limbsTable->SetName(StringHelper::Sprintf("%sLimbs", defaultPrefix.c_str())); - parent->AddResource(limbsTable); - } - else - { - limbsTable = static_cast(parent->FindResource(ptr)); - } - - if (limbsTable->enumName == "") - { - limbsTable->enumName = enumName; - } - if (limbsTable->limbNoneName == "") - { - limbsTable->limbNoneName = limbNoneName; - } - if (limbsTable->limbMaxName == "") - { - limbsTable->limbMaxName = limbMaxName; - } - } -} - -std::string ZSkeleton::GetBodySourceCode() const -{ - std::string limbArrayName; - Globals::Instance->GetSegmentedPtrName(limbsArrayAddress, parent, "", limbArrayName); - - std::string countStr; - assert(limbsTable != nullptr); - // There are some Skeletons with the wrong limb count on them, so this check is necessary. - if (limbsTable->count == limbCount) - { - countStr = StringHelper::Sprintf("ARRAY_COUNT(%s)", limbArrayName.c_str()); - } - else - { - countStr = StringHelper::Sprintf("%i", limbCount); - } - - switch (type) - { - case ZSkeletonType::Normal: - case ZSkeletonType::Curve: - return StringHelper::Sprintf("\n\t%s, %s\n", limbArrayName.c_str(), countStr.c_str()); - - case ZSkeletonType::Flex: - return StringHelper::Sprintf("\n\t{ %s, %s }, %i\n", limbArrayName.c_str(), - countStr.c_str(), dListCount); - } - - // TODO: Throw exception? - return "ERROR"; -} - -size_t ZSkeleton::GetRawDataSize() const -{ - switch (type) - { - case ZSkeletonType::Flex: - return 0xC; - case ZSkeletonType::Normal: - case ZSkeletonType::Curve: - default: - return 0x8; - } -} - -std::string ZSkeleton::GetSourceTypeName() const -{ - switch (type) - { - case ZSkeletonType::Normal: - return "SkeletonHeader"; - case ZSkeletonType::Flex: - return "FlexSkeletonHeader"; - case ZSkeletonType::Curve: - return "CurveSkeletonHeader"; - } - - return "SkeletonHeader"; -} - -ZResourceType ZSkeleton::GetResourceType() const -{ - return ZResourceType::Skeleton; -} - -DeclarationAlignment ZSkeleton::GetDeclarationAlignment() const -{ - return DeclarationAlignment::Align4; -} - -uint8_t ZSkeleton::GetLimbCount() -{ - return limbCount; -} - -/* ZLimbTable */ - -ZLimbTable::ZLimbTable(ZFile* nParent) : ZResource(nParent) -{ - RegisterRequiredAttribute("LimbType"); - RegisterRequiredAttribute("Count"); - RegisterOptionalAttribute("EnumName"); - RegisterOptionalAttribute("LimbNone"); - RegisterOptionalAttribute("LimbMax"); -} - -void ZLimbTable::ExtractFromBinary(uint32_t nRawDataIndex, ZLimbType nLimbType, size_t nCount) -{ - rawDataIndex = nRawDataIndex; - limbType = nLimbType; - count = nCount; - - ParseRawData(); -} - -void ZLimbTable::ParseXML(tinyxml2::XMLElement* reader) -{ - ZResource::ParseXML(reader); - - std::string limbTypeXml = registeredAttributes.at("LimbType").value; - limbType = ZLimb::GetTypeByAttributeName(limbTypeXml); - if (limbType == ZLimbType::Invalid) - { - HANDLE_WARNING_RESOURCE(WarningType::InvalidAttributeValue, parent, this, rawDataIndex, - "invalid value found for 'LimbType' attribute.", - "Defaulting to 'Standard'."); - limbType = ZLimbType::Standard; - } - - count = StringHelper::StrToL(registeredAttributes.at("Count").value); - - enumName = registeredAttributes.at("EnumName").value; - limbNoneName = registeredAttributes.at("LimbNone").value; - limbMaxName = registeredAttributes.at("LimbMax").value; - - if (enumName != "") - { - if (limbNoneName == "" || limbMaxName == "") - { - HANDLE_ERROR_RESOURCE( - WarningType::MissingAttribute, parent, this, rawDataIndex, - "'EnumName' attribute was used but 'LimbNone'/'LimbMax' attributes is missing", ""); - } - } - - if (limbNoneName != "") - { - if (limbMaxName == "") - { - HANDLE_ERROR_RESOURCE( - WarningType::MissingAttribute, parent, this, rawDataIndex, - "'LimbNone' attribute was used but 'LimbMax' attribute is missing", ""); - } - } - - if (limbMaxName != "") - { - if (limbNoneName == "") - { - HANDLE_ERROR_RESOURCE( - WarningType::MissingAttribute, parent, this, rawDataIndex, - "'LimbMax' attribute was used but 'LimbNone' attribute is missing", ""); - } - } -} - -void ZLimbTable::ParseRawData() -{ - ZResource::ParseRawData(); - - const auto& rawData = parent->GetRawData(); - uint32_t ptr = rawDataIndex; - - limbsAddresses.reserve(count); - for (size_t i = 0; i < count; i++) - { - limbsAddresses.push_back(BitConverter::ToUInt32BE(rawData, ptr)); - ptr += 4; - } -} - -void ZLimbTable::DeclareReferences(const std::string& prefix) -{ - std::string varPrefix = name; - if (varPrefix == "") - varPrefix = prefix; - - ZResource::DeclareReferences(varPrefix); - limbsReferences.reserve(count); - for (size_t i = 0; i < count; i++) - { - segptr_t limbAddress = limbsAddresses[i]; - - if (limbAddress != 0 && GETSEGNUM(limbAddress) == parent->segment) - { - uint32_t limbOffset = Seg2Filespace(limbAddress, parent->baseAddress); - ZLimb* limb; - - if (!parent->HasDeclaration(limbOffset)) - { - limb = new ZLimb(parent); - limb->ExtractFromBinary(limbOffset, limbType); - limb->SetName(limb->GetDefaultName(varPrefix)); - limb->DeclareVar(varPrefix, ""); - limb->DeclareReferences(varPrefix); - parent->AddResource(limb); - } - else - { - limb = static_cast(parent->FindResource(limbOffset)); - assert(limb != nullptr); - assert(limb->GetResourceType() == ZResourceType::Limb); - } - - limb->limbsTable = this; - limb->SetLimbIndex(i + 1); - - limbsReferences.push_back(limb); - } - } -} - -Declaration* ZLimbTable::DeclareVar(const std::string& prefix, const std::string& bodyStr) -{ - std::string auxName = name; - - if (name == "") - auxName = GetDefaultName(prefix); - - Declaration* decl = - parent->AddDeclarationArray(rawDataIndex, GetDeclarationAlignment(), GetRawDataSize(), - GetSourceTypeName(), auxName, limbsAddresses.size(), bodyStr); - decl->staticConf = staticConf; - return decl; -} - -std::string ZLimbTable::GetBodySourceCode() const -{ - std::string body; - - for (size_t i = 0; i < count; i++) - { - std::string limbName; - Globals::Instance->GetSegmentedPtrName(limbsAddresses[i], parent, "", limbName); - body += StringHelper::Sprintf("\t%s,", limbName.c_str()); - - auto& limb = limbsReferences.at(i); - std::string limbEnumName = limb->enumName; - if (limbEnumName != "") - { - body += StringHelper::Sprintf(" /* %s */", limbEnumName.c_str()); - } - - if (i + 1 < count) - body += "\n"; - } - - return body; -} - -std::string ZLimbTable::GetSourceOutputHeader([[maybe_unused]] const std::string& prefix) -{ - if (limbNoneName == "" || limbMaxName == "" || enumName == "") - { - // Don't produce a enum of any of those attributes is missing - return ""; - } - - std::string limbEnum = StringHelper::Sprintf("typedef enum %s {\n", enumName.c_str()); - - // This assumes there isn't any skeleton with more than 0x100 limbs - - limbEnum += StringHelper::Sprintf(" /* 0x00 */ %s,\n", limbNoneName.c_str()); - - size_t i = 0; - for (; i < count; i++) - { - auto& limb = limbsReferences.at(i); - std::string limbEnumName = limb->enumName; - - if (limbEnumName == "") - { - HANDLE_ERROR_RESOURCE( - WarningType::MissingAttribute, parent, this, rawDataIndex, - "Skeleton's enum attributes were used but at least one limb is missing its " - "'LimbName' attribute", - StringHelper::Sprintf("When processing limb %02i, named '%s' at offset '0x%X'", - i + 1, limb->GetName().c_str(), limb->GetRawDataIndex())); - } - - limbEnum += StringHelper::Sprintf(" /* 0x%02X */ %s,\n", i + 1, limbEnumName.c_str()); - } - - limbEnum += StringHelper::Sprintf(" /* 0x%02X */ %s\n", i + 1, limbMaxName.c_str()); - - limbEnum += StringHelper::Sprintf("} %s;\n", enumName.c_str()); - - return limbEnum; -} - -std::string ZLimbTable::GetSourceTypeName() const -{ - switch (limbType) - { - case ZLimbType::Standard: - case ZLimbType::LOD: - case ZLimbType::Skin: - return "void*"; - - case ZLimbType::Curve: - case ZLimbType::Legacy: - return StringHelper::Sprintf("%s*", ZLimb::GetSourceTypeName(limbType)); - - case ZLimbType::Invalid: - // TODO: Proper error message or something. - assert("Invalid limb type.\n"); - } - - return "ERROR"; -} - -ZResourceType ZLimbTable::GetResourceType() const -{ - return ZResourceType::LimbTable; -} - -size_t ZLimbTable::GetRawDataSize() const -{ - return 4 * limbsAddresses.size(); -} - -std::string ZLimbTable::GetLimbEnumName(uint8_t limbIndex) const -{ - if (limbIndex == 0xFF) - { - return "LIMB_DONE"; - } - - if (limbIndex < count) - { - std::string limbEnumName = limbsReferences.at(limbIndex)->enumName; - if (limbEnumName != "") - { - return StringHelper::Sprintf("%s - 1", limbEnumName.c_str()); - } - } - else - { - HANDLE_WARNING_RESOURCE(WarningType::InvalidExtractedData, parent, this, rawDataIndex, - StringHelper::Sprintf("Limb index '%02i' out of range", limbIndex), - ""); - } - - return StringHelper::Sprintf("0x%02X", limbIndex); -} diff --git a/tools/ZAPD/ZAPD/ZSkeleton.h b/tools/ZAPD/ZAPD/ZSkeleton.h deleted file mode 100644 index c437a8484c..0000000000 --- a/tools/ZAPD/ZAPD/ZSkeleton.h +++ /dev/null @@ -1,85 +0,0 @@ -#pragma once - -#include -#include -#include - -#include "ZDisplayList.h" -#include "ZFile.h" -#include "ZLimb.h" - -enum class ZSkeletonType -{ - Normal, - Flex, - Curve, -}; - -class ZLimbTable : public ZResource -{ -public: - ZLimbType limbType = ZLimbType::Standard; - size_t count = 0; - - std::vector limbsAddresses; - std::vector limbsReferences; // borrowed pointers, do not delete! - - // XML attributes - std::string enumName; - std::string limbNoneName; - std::string limbMaxName; - - ZLimbTable(ZFile* nParent); - - void ExtractFromBinary(uint32_t nRawDataIndex, ZLimbType nLimbType, size_t nCount); - - void ParseXML(tinyxml2::XMLElement* reader) override; - void ParseRawData() override; - void DeclareReferences(const std::string& prefix) override; - - Declaration* DeclareVar(const std::string& prefix, const std::string& bodyStr) override; - - std::string GetBodySourceCode() const override; - - std::string GetSourceOutputHeader(const std::string& prefix) override; - - std::string GetSourceTypeName() const override; - ZResourceType GetResourceType() const override; - - size_t GetRawDataSize() const override; - - std::string GetLimbEnumName(uint8_t limbIndex) const; -}; - -class ZSkeleton : public ZResource -{ -public: - ZSkeletonType type = ZSkeletonType::Normal; - ZLimbType limbType = ZLimbType::Standard; - std::string enumName; - std::string limbNoneName; - std::string limbMaxName; - - segptr_t limbsArrayAddress; - uint8_t limbCount = 0; - uint8_t dListCount = 0; // FLEX SKELETON ONLY - - ZSkeleton(ZFile* nParent); - - void ParseXML(tinyxml2::XMLElement* reader) override; - void ParseRawData() override; - void DeclareReferences(const std::string& prefix) override; - - std::string GetBodySourceCode() const override; - - std::string GetSourceTypeName() const override; - ZResourceType GetResourceType() const override; - - size_t GetRawDataSize() const override; - DeclarationAlignment GetDeclarationAlignment() const override; - - uint8_t GetLimbCount(); - -protected: - ZLimbTable* limbsTable = nullptr; // borrowed pointer, do not delete! -}; diff --git a/tools/ZAPD/ZAPD/ZString.cpp b/tools/ZAPD/ZAPD/ZString.cpp deleted file mode 100644 index 965d4d6360..0000000000 --- a/tools/ZAPD/ZAPD/ZString.cpp +++ /dev/null @@ -1,69 +0,0 @@ -#include "ZString.h" - -#include "Utils/File.h" -#include "Utils/StringHelper.h" -#include "ZFile.h" - -REGISTER_ZFILENODE(String, ZString); - -ZString::ZString(ZFile* nParent) : ZResource(nParent) -{ -} - -void ZString::ParseRawData() -{ - size_t size = 0; - const auto& rawData = parent->GetRawData(); - const auto& rawDataArr = rawData.data(); - size_t rawDataSize = rawData.size(); - for (size_t i = rawDataIndex; i < rawDataSize; ++i) - { - ++size; - if (rawDataArr[i] == '\0') - { - break; - } - } - - auto dataStart = rawData.begin() + rawDataIndex; - strData.assign(dataStart, dataStart + size); -} - -Declaration* ZString::DeclareVar(const std::string& prefix, const std::string& bodyStr) -{ - std::string auxName = name; - - if (name == "") - auxName = GetDefaultName(prefix); - - Declaration* decl = - parent->AddDeclarationArray(rawDataIndex, GetDeclarationAlignment(), GetRawDataSize(), - GetSourceTypeName(), auxName, 0, bodyStr); - decl->staticConf = staticConf; - return decl; -} - -std::string ZString::GetBodySourceCode() const -{ - return StringHelper::Sprintf("\t\"%s\"", strData.data()); -} - -std::string ZString::GetSourceOutputHeader([[maybe_unused]] const std::string& prefix) -{ - return StringHelper::Sprintf("#define %s_macro \"%s\"", name.c_str(), strData.data()); -} - -std::string ZString::GetSourceTypeName() const -{ - return "char"; -} - -ZResourceType ZString::GetResourceType() const -{ - return ZResourceType::String; -} - -size_t ZString::GetRawDataSize() const -{ - return strData.size(); -} diff --git a/tools/ZAPD/ZAPD/ZString.h b/tools/ZAPD/ZAPD/ZString.h deleted file mode 100644 index 6c58ebdcb5..0000000000 --- a/tools/ZAPD/ZAPD/ZString.h +++ /dev/null @@ -1,24 +0,0 @@ -#pragma once - -#include "ZResource.h" -#include "tinyxml2.h" - -class ZString : public ZResource -{ -public: - ZString(ZFile* nParent); - - void ParseRawData() override; - - Declaration* DeclareVar(const std::string& prefix, const std::string& bodyStr) override; - std::string GetBodySourceCode() const override; - - std::string GetSourceOutputHeader(const std::string& prefix) override; - std::string GetSourceTypeName() const override; - ZResourceType GetResourceType() const override; - - size_t GetRawDataSize() const override; - -protected: - std::vector strData; -}; diff --git a/tools/ZAPD/ZAPD/ZSurfaceType.cpp b/tools/ZAPD/ZAPD/ZSurfaceType.cpp deleted file mode 100644 index 27e73accc2..0000000000 --- a/tools/ZAPD/ZAPD/ZSurfaceType.cpp +++ /dev/null @@ -1,65 +0,0 @@ -#include "ZSurfaceType.h" - -#include "Globals.h" -#include "Utils/BitConverter.h" -#include "Utils/StringHelper.h" - -REGISTER_ZFILENODE(SurfaceType, ZSurfaceType); - -ZSurfaceType::ZSurfaceType(ZFile* nParent) : ZResource(nParent) -{ -} - -ZSurfaceType::~ZSurfaceType() -{ -} - -void ZSurfaceType::ParseRawData() -{ - const auto& rawData = parent->GetRawData(); - - data[0] = BitConverter::ToUInt32BE(rawData, rawDataIndex + 0); - data[1] = BitConverter::ToUInt32BE(rawData, rawDataIndex + 4); -} - -void ZSurfaceType::DeclareReferences(const std::string& prefix) -{ - std::string declaration; - std::string auxName = name; - - if (name == "") - auxName = GetDefaultName(prefix); - - parent->AddDeclaration(rawDataIndex, DeclarationAlignment::Align4, GetRawDataSize(), - GetSourceTypeName(), name.c_str(), GetBodySourceCode()); -} - -std::string ZSurfaceType::GetBodySourceCode() const -{ - return StringHelper::Sprintf("{0x%08X, 0x%08X}", data[0], data[1]); -} - -std::string ZSurfaceType::GetDefaultName(const std::string& prefix) const -{ - return StringHelper::Sprintf("%sSurfaceType_%06X", prefix.c_str(), rawDataIndex); -} - -ZResourceType ZSurfaceType::GetResourceType() const -{ - return ZResourceType::SurfaceType; -} - -size_t ZSurfaceType::GetRawDataSize() const -{ - return 8; -} - -std::string ZSurfaceType::GetSourceTypeName() const -{ - return "SurfaceType"; -} - -bool ZSurfaceType::DoesSupportArray() const -{ - return true; -} diff --git a/tools/ZAPD/ZAPD/ZSurfaceType.h b/tools/ZAPD/ZAPD/ZSurfaceType.h deleted file mode 100644 index 3bbddee8ce..0000000000 --- a/tools/ZAPD/ZAPD/ZSurfaceType.h +++ /dev/null @@ -1,27 +0,0 @@ -#pragma once - -#include -#include "ZFile.h" -#include "ZResource.h" - -class ZSurfaceType : public ZResource -{ -public: - std::array data; - - ZSurfaceType(ZFile* nParent); - ~ZSurfaceType(); - - void ParseRawData() override; - void DeclareReferences(const std::string& prefix) override; - - std::string GetBodySourceCode() const override; - std::string GetDefaultName(const std::string& prefix) const override; - - std::string GetSourceTypeName() const override; - ZResourceType GetResourceType() const override; - - bool DoesSupportArray() const override; - - size_t GetRawDataSize() const override; -}; diff --git a/tools/ZAPD/ZAPD/ZSymbol.cpp b/tools/ZAPD/ZAPD/ZSymbol.cpp deleted file mode 100644 index eabfc2faae..0000000000 --- a/tools/ZAPD/ZAPD/ZSymbol.cpp +++ /dev/null @@ -1,98 +0,0 @@ -#include "ZSymbol.h" - -#include "Utils/StringHelper.h" -#include "WarningHandler.h" -#include "ZFile.h" - -REGISTER_ZFILENODE(Symbol, ZSymbol); - -ZSymbol::ZSymbol(ZFile* nParent) : ZResource(nParent) -{ - RegisterOptionalAttribute("Type"); - RegisterOptionalAttribute("TypeSize"); - RegisterOptionalAttribute("Count"); -} - -void ZSymbol::ParseXML(tinyxml2::XMLElement* reader) -{ - ZResource::ParseXML(reader); - - std::string typeXml = registeredAttributes.at("Type").value; - - if (typeXml == "") - { - HANDLE_WARNING_RESOURCE(WarningType::MissingAttribute, parent, this, rawDataIndex, - "missing 'Type' attribute in ", "Defaulting to 'void*'."); - type = "void*"; - } - else - { - type = typeXml; - } - - std::string typeSizeXml = registeredAttributes.at("TypeSize").value; - if (typeSizeXml == "") - { - HANDLE_WARNING_RESOURCE(WarningType::MissingAttribute, parent, this, rawDataIndex, - "missing 'TypeSize' attribute in ", "Defaulting to '4'."); - typeSize = 4; // Size of a word. - } - else - { - typeSize = StringHelper::StrToL(typeSizeXml, 0); - } - - if (registeredAttributes.at("Count").wasSet) - { - isArray = true; - - std::string countXml = registeredAttributes.at("Count").value; - if (countXml != "") - count = StringHelper::StrToL(countXml, 0); - } - - if (registeredAttributes.at("Static").value == "On") - { - HANDLE_WARNING_RESOURCE(WarningType::InvalidAttributeValue, parent, this, rawDataIndex, - "a cannot be marked as static", - "Disabling static for this resource."); - } - staticConf = StaticConfig::Off; -} - -Declaration* ZSymbol::DeclareVar([[maybe_unused]] const std::string& prefix, - [[maybe_unused]] const std::string& bodyStr) -{ - return nullptr; -} - -size_t ZSymbol::GetRawDataSize() const -{ - if (isArray) - return count * typeSize; - - return typeSize; -} - -std::string ZSymbol::GetSourceOutputHeader([[maybe_unused]] const std::string& prefix) -{ - if (isArray) - { - if (count == 0) - return StringHelper::Sprintf("extern %s %s[];\n", type.c_str(), name.c_str()); - else - return StringHelper::Sprintf("extern %s %s[%i];\n", type.c_str(), name.c_str(), count); - } - - return StringHelper::Sprintf("extern %s %s;\n", type.c_str(), name.c_str()); -} - -std::string ZSymbol::GetSourceTypeName() const -{ - return type; -} - -ZResourceType ZSymbol::GetResourceType() const -{ - return ZResourceType::Symbol; -} diff --git a/tools/ZAPD/ZAPD/ZSymbol.h b/tools/ZAPD/ZAPD/ZSymbol.h deleted file mode 100644 index 7cb14aa9b4..0000000000 --- a/tools/ZAPD/ZAPD/ZSymbol.h +++ /dev/null @@ -1,27 +0,0 @@ -#pragma once - -#include "ZResource.h" -#include "tinyxml2.h" - -class ZSymbol : public ZResource -{ -protected: - std::string type; - size_t typeSize; - bool isArray = false; - uint32_t count = 0; - -public: - ZSymbol(ZFile* nParent); - - void ParseXML(tinyxml2::XMLElement* reader) override; - - Declaration* DeclareVar(const std::string& prefix, const std::string& bodyStr) override; - - std::string GetSourceOutputHeader(const std::string& prefix) override; - - std::string GetSourceTypeName() const override; - ZResourceType GetResourceType() const override; - - size_t GetRawDataSize() const override; -}; diff --git a/tools/ZAPD/ZAPD/ZTexture.cpp b/tools/ZAPD/ZAPD/ZTexture.cpp deleted file mode 100644 index 0d66ba7da3..0000000000 --- a/tools/ZAPD/ZAPD/ZTexture.cpp +++ /dev/null @@ -1,978 +0,0 @@ -#include "ZTexture.h" - -#include - -#include "CRC32.h" -#include "Globals.h" -#include "Utils/BitConverter.h" -#include "Utils/Directory.h" -#include "Utils/File.h" -#include "Utils/Path.h" -#include "WarningHandler.h" - -REGISTER_ZFILENODE(Texture, ZTexture); - -ZTexture::ZTexture(ZFile* nParent) : ZResource(nParent) -{ - width = 0; - height = 0; - dWordAligned = true; - splitTlut = false; - - RegisterRequiredAttribute("Width"); - RegisterRequiredAttribute("Height"); - RegisterRequiredAttribute("Format"); - RegisterOptionalAttribute("TlutOffset"); - RegisterOptionalAttribute("ExternalTlut"); - RegisterOptionalAttribute("ExternalTlutOffset"); - RegisterOptionalAttribute("SplitTlut"); -} - -void ZTexture::ExtractFromBinary(uint32_t nRawDataIndex, int32_t nWidth, int32_t nHeight, - TextureType nType, bool nIsPalette) -{ - width = nWidth; - height = nHeight; - format = nType; - rawDataIndex = nRawDataIndex; - isPalette = nIsPalette; - name = GetDefaultName(parent->GetName()); - outName = name; - - // Don't parse raw data of external files - if (parent->GetMode() == ZFileMode::ExternalFile) - return; - - ParseRawData(); - CalcHash(); -} - -void ZTexture::FromPNG(const fs::path& pngFilePath, TextureType texType) -{ - format = texType; - name = StringHelper::Split(Path::GetFileNameWithoutExtension(pngFilePath.string()), ".")[0]; - PrepareRawDataFromFile(pngFilePath); -} - -void ZTexture::ParseXML(tinyxml2::XMLElement* reader) -{ - ZResource::ParseXML(reader); - - std::string widthXml = registeredAttributes.at("Width").value; - std::string heightXml = registeredAttributes.at("Height").value; - std::string SplitTlutXml = registeredAttributes.at("SplitTlut").value; - - if (!StringHelper::HasOnlyDigits(widthXml)) - { - std::string errorHeader = StringHelper::Sprintf( - "value of 'Width' attribute has non-decimal digits: '%s'", widthXml.c_str()); - HANDLE_ERROR_RESOURCE(WarningType::InvalidAttributeValue, parent, this, rawDataIndex, - errorHeader, ""); - } - if (!StringHelper::HasOnlyDigits(heightXml)) - { - std::string errorHeader = StringHelper::Sprintf( - "value of 'Height' attribute has non-decimal digits: '%s'", heightXml.c_str()); - HANDLE_ERROR_RESOURCE(WarningType::InvalidAttributeValue, parent, this, rawDataIndex, - errorHeader, ""); - } - - if (!registeredAttributes.at("ExternalTlut").wasSet && - registeredAttributes.at("SplitTlut").wasSet) - { - std::string errorHeader = - StringHelper::Sprintf("SplitTlut set without using an external tlut"); - HANDLE_WARNING_RESOURCE(WarningType::InvalidAttributeValue, parent, this, rawDataIndex, - errorHeader, ""); - } - - if (!SplitTlutXml.empty()) - { - if (!tinyxml2::XMLUtil::ToBool(SplitTlutXml.c_str(), &splitTlut)) - { - std::string errorHeader = StringHelper::Sprintf( - "Invalid value passed to SplitTlut: '%s'. Valid values are true, false, 1, 0", - SplitTlutXml.c_str()); - HANDLE_ERROR_RESOURCE(WarningType::InvalidAttributeValue, parent, this, rawDataIndex, - errorHeader, ""); - } - } - - width = StringHelper::StrToL(widthXml); - height = StringHelper::StrToL(heightXml); - - std::string formatStr = registeredAttributes.at("Format").value; - format = GetTextureTypeFromString(formatStr); - - if (format == TextureType::Error) - { - HANDLE_ERROR_RESOURCE(WarningType::InvalidAttributeValue, parent, this, rawDataIndex, - "invalid value found for 'Format' attribute", ""); - } - - const auto& tlutOffsetAttr = registeredAttributes.at("TlutOffset"); - if (tlutOffsetAttr.wasSet) - { - switch (format) - { - case TextureType::Palette4bpp: - case TextureType::Palette8bpp: - tlutOffset = StringHelper::StrToL(tlutOffsetAttr.value, 16); - break; - - default: - HANDLE_ERROR_RESOURCE(WarningType::InvalidXML, parent, this, rawDataIndex, - "'TlutOffset' declared in non color-indexed (ci4 or ci8) texture", - ""); - break; - } - } -} - -void ZTexture::ParseRawData() -{ - if ((parent->baseAddress + rawDataIndex) % 8 != 0) - dWordAligned = false; - - switch (format) - { - case TextureType::RGBA16bpp: - ConvertN64ToBitmap_RGBA16(); - break; - case TextureType::RGBA32bpp: - ConvertN64ToBitmap_RGBA32(); - break; - case TextureType::Grayscale4bpp: - ConvertN64ToBitmap_Grayscale4(); - break; - case TextureType::Grayscale8bpp: - ConvertN64ToBitmap_Grayscale8(); - break; - case TextureType::GrayscaleAlpha4bpp: - ConvertN64ToBitmap_GrayscaleAlpha4(); - break; - case TextureType::GrayscaleAlpha8bpp: - ConvertN64ToBitmap_GrayscaleAlpha8(); - break; - case TextureType::GrayscaleAlpha16bpp: - ConvertN64ToBitmap_GrayscaleAlpha16(); - break; - case TextureType::Palette4bpp: - ConvertN64ToBitmap_Palette4(); - break; - case TextureType::Palette8bpp: - ConvertN64ToBitmap_Palette8(); - break; - case TextureType::Error: - HANDLE_ERROR_RESOURCE(WarningType::InvalidAttributeValue, parent, this, rawDataIndex, - StringHelper::Sprintf("Invalid texture format", format), ""); - assert(!"TODO"); - break; - } -} - -void ZTexture::ParseRawDataLate() -{ - if (registeredAttributes["ExternalTlut"].wasSet) - { - const std::string externPalette = registeredAttributes["ExternalTlut"].value; - for (const auto& file : Globals::Instance->files) - { - if (file->GetName() == externPalette) - { - offset_t palOffset = 0; - if (registeredAttributes["ExternalTlutOffset"].wasSet) - { - palOffset = - StringHelper::StrToL(registeredAttributes["ExternalTlutOffset"].value, 16); - } - else - { - HANDLE_WARNING_RESOURCE( - WarningType::MissingOffsets, parent, this, rawDataIndex, - StringHelper::Sprintf( - "No ExternalTlutOffset Given. Assuming offset of 0x0"), - ""); - } - for (const auto& res : file->resources) - { - if (res->GetRawDataIndex() == palOffset) - { - ZTexture* palette = (ZTexture*)res; - ZTexture tlutTemp(file); - - tlut = &tlutTemp; - tlut->ExtractFromBinary(palOffset, palette->width, palette->height, - TextureType::RGBA16bpp, true); - SetTlut(tlut); - } - } - } - } - } -} - -void ZTexture::ConvertN64ToBitmap_RGBA16() -{ - textureData.InitEmptyRGBImage(width, height, true); - const auto& parentRawData = parent->GetRawData(); - for (size_t y = 0; y < height; y++) - { - for (size_t x = 0; x < width; x++) - { - int32_t pos = rawDataIndex + ((y * width) + x) * 2; - uint16_t data = parentRawData.at(pos + 1) | (parentRawData.at(pos) << 8); - uint8_t r = (data & 0xF800) >> 11; - uint8_t g = (data & 0x07C0) >> 6; - uint8_t b = (data & 0x003E) >> 1; - uint8_t alpha = data & 0x01; - - textureData.SetRGBPixel(y, x, (r << 3) | (r >> 2), (g << 3) | (g >> 2), - (b << 3) | (b >> 2), alpha * 255); - } - } -} - -void ZTexture::ConvertN64ToBitmap_RGBA32() -{ - textureData.InitEmptyRGBImage(width, height, true); - const auto& parentRawData = parent->GetRawData(); - for (size_t y = 0; y < height; y++) - { - for (size_t x = 0; x < width; x++) - { - size_t pos = rawDataIndex + ((y * width) + x) * 4; - uint8_t r = parentRawData.at(pos + 0); - uint8_t g = parentRawData.at(pos + 1); - uint8_t b = parentRawData.at(pos + 2); - uint8_t alpha = parentRawData.at(pos + 3); - - textureData.SetRGBPixel(y, x, r, g, b, alpha); - } - } -} - -void ZTexture::ConvertN64ToBitmap_Grayscale4() -{ - textureData.InitEmptyRGBImage(width, height, false); - const auto& parentRawData = parent->GetRawData(); - for (size_t y = 0; y < height; y++) - { - for (size_t x = 0; x < width; x += 2) - { - for (uint8_t i = 0; i < 2; i++) - { - size_t pos = rawDataIndex + ((y * width) + x) / 2; - uint8_t grayscale = 0; - - if (i == 0) - grayscale = parentRawData.at(pos) & 0xF0; - else - grayscale = (parentRawData.at(pos) & 0x0F) << 4; - - textureData.SetGrayscalePixel(y, x + i, (grayscale << 4) | grayscale); - } - } - } -} - -void ZTexture::ConvertN64ToBitmap_Grayscale8() -{ - textureData.InitEmptyRGBImage(width, height, false); - const auto& parentRawData = parent->GetRawData(); - for (size_t y = 0; y < height; y++) - { - for (size_t x = 0; x < width; x++) - { - size_t pos = rawDataIndex + ((y * width) + x) * 1; - - textureData.SetGrayscalePixel(y, x, parentRawData.at(pos)); - } - } -} - -void ZTexture::ConvertN64ToBitmap_GrayscaleAlpha4() -{ - textureData.InitEmptyRGBImage(width, height, true); - const auto& parentRawData = parent->GetRawData(); - for (size_t y = 0; y < height; y++) - { - for (size_t x = 0; x < width; x += 2) - { - for (uint16_t i = 0; i < 2; i++) - { - size_t pos = rawDataIndex + ((y * width) + x) / 2; - uint8_t data = 0; - - if (i == 0) - data = (parentRawData.at(pos) & 0xF0) >> 4; - else - data = parentRawData.at(pos) & 0x0F; - - uint8_t grayscale = data & 0b1110; - grayscale = (grayscale << 4) | (grayscale << 1) | (grayscale >> 2); - uint8_t alpha = (data & 0x01) ? 255 : 0; - - textureData.SetGrayscalePixel(y, x + i, grayscale, alpha); - } - } - } -} - -void ZTexture::ConvertN64ToBitmap_GrayscaleAlpha8() -{ - textureData.InitEmptyRGBImage(width, height, true); - const auto& parentRawData = parent->GetRawData(); - for (size_t y = 0; y < height; y++) - { - for (size_t x = 0; x < width; x++) - { - size_t pos = rawDataIndex + ((y * width) + x) * 1; - uint8_t pixel = parentRawData.at(pos); - uint8_t data = (pixel >> 4) & 0xF; - - data = (data << 4) | data; - uint8_t grayscale = data; - uint8_t alpha = (pixel & 0xF); - alpha = (alpha << 4) | alpha; - - textureData.SetGrayscalePixel(y, x, grayscale, alpha); - } - } -} - -void ZTexture::ConvertN64ToBitmap_GrayscaleAlpha16() -{ - textureData.InitEmptyRGBImage(width, height, true); - const auto& parentRawData = parent->GetRawData(); - for (size_t y = 0; y < height; y++) - { - for (size_t x = 0; x < width; x++) - { - size_t pos = rawDataIndex + ((y * width) + x) * 2; - uint8_t grayscale = parentRawData.at(pos + 0); - uint8_t alpha = parentRawData.at(pos + 1); - - textureData.SetGrayscalePixel(y, x, grayscale, alpha); - } - } -} - -void ZTexture::ConvertN64ToBitmap_Palette4() -{ - textureData.InitEmptyPaletteImage(width, height); - const auto& parentRawData = parent->GetRawData(); - for (size_t y = 0; y < height; y++) - { - for (size_t x = 0; x < width; x += 2) - { - for (uint16_t i = 0; i < 2; i++) - { - size_t pos = rawDataIndex + ((y * width) + x) / 2; - uint8_t paletteIndex = 0; - - if (i == 0) - paletteIndex = (parentRawData.at(pos) & 0xF0) >> 4; - else - paletteIndex = (parentRawData.at(pos) & 0x0F); - - textureData.SetIndexedPixel(y, x + i, paletteIndex, paletteIndex * 16); - } - } - } -} - -void ZTexture::ConvertN64ToBitmap_Palette8() -{ - textureData.InitEmptyPaletteImage(width, height); - const auto& parentRawData = parent->GetRawData(); - for (size_t y = 0; y < height; y++) - { - for (size_t x = 0; x < width; x++) - { - size_t pos = rawDataIndex + ((y * width) + x) * 1; - uint8_t grayscale = parentRawData.at(pos); - - textureData.SetIndexedPixel(y, x, grayscale, grayscale); - } - } -} - -void ZTexture::DeclareReferences([[maybe_unused]] const std::string& prefix) -{ - if (tlutOffset != static_cast(-1)) - { - tlut = parent->GetTextureResource(tlutOffset); - if (tlut == nullptr) - { - int32_t tlutDim = 16; - if (format == TextureType::Palette4bpp) - tlutDim = 4; - - tlut = new ZTexture(parent); - tlut->ExtractFromBinary(tlutOffset, tlutDim, tlutDim, TextureType::RGBA16bpp, true); - parent->AddTextureResource(tlutOffset, tlut); - tlut->DeclareVar(prefix, ""); - } - else - { - tlut->isPalette = true; - } - SetTlut(tlut); - } -} - -void ZTexture::PrepareRawDataFromFile(const fs::path& pngFilePath) -{ - textureData.ReadPng(pngFilePath); - - width = textureData.GetWidth(); - height = textureData.GetHeight(); - - textureDataRaw.clear(); - textureDataRaw.resize(ALIGN8(GetRawDataSize())); - - switch (format) - { - case TextureType::RGBA16bpp: - ConvertBitmapToN64_RGBA16(); - break; - case TextureType::RGBA32bpp: - ConvertBitmapToN64_RGBA32(); - break; - case TextureType::Grayscale4bpp: - ConvertBitmapToN64_Grayscale4(); - break; - case TextureType::Grayscale8bpp: - ConvertBitmapToN64_Grayscale8(); - break; - case TextureType::GrayscaleAlpha4bpp: - ConvertBitmapToN64_GrayscaleAlpha4(); - break; - case TextureType::GrayscaleAlpha8bpp: - ConvertBitmapToN64_GrayscaleAlpha8(); - break; - case TextureType::GrayscaleAlpha16bpp: - ConvertBitmapToN64_GrayscaleAlpha16(); - break; - case TextureType::Palette4bpp: - ConvertBitmapToN64_Palette4(); - break; - case TextureType::Palette8bpp: - ConvertBitmapToN64_Palette8(); - break; - case TextureType::Error: - HANDLE_ERROR_PROCESS(WarningType::InvalidPNG, "Input PNG file has invalid format type", ""); - break; - } -} - -void ZTexture::ConvertBitmapToN64_RGBA16() -{ - for (uint16_t y = 0; y < height; y++) - { - for (uint16_t x = 0; x < width; x++) - { - size_t pos = ((y * width) + x) * 2; - RGBAPixel pixel = textureData.GetPixel(y, x); - - uint8_t r = pixel.r >> 3; - uint8_t g = pixel.g >> 3; - uint8_t b = pixel.b >> 3; - - uint8_t alphaBit = pixel.a != 0; - - uint16_t data = (r << 11) | (g << 6) | (b << 1) | alphaBit; - - textureDataRaw[pos + 0] = (data & 0xFF00) >> 8; - textureDataRaw[pos + 1] = (data & 0x00FF); - } - } -} - -void ZTexture::ConvertBitmapToN64_RGBA32() -{ - for (uint16_t y = 0; y < height; y++) - { - for (uint16_t x = 0; x < width; x++) - { - size_t pos = ((y * width) + x) * 4; - RGBAPixel pixel = textureData.GetPixel(y, x); - - textureDataRaw[pos + 0] = pixel.r; - textureDataRaw[pos + 1] = pixel.g; - textureDataRaw[pos + 2] = pixel.b; - textureDataRaw[pos + 3] = pixel.a; - } - } -} - -void ZTexture::ConvertBitmapToN64_Grayscale4() -{ - for (uint16_t y = 0; y < height; y++) - { - for (uint16_t x = 0; x < width; x += 2) - { - size_t pos = ((y * width) + x) / 2; - uint8_t r1 = textureData.GetPixel(y, x).r; - uint8_t r2 = textureData.GetPixel(y, x + 1).r; - - textureDataRaw[pos] = (uint8_t)(((r1 / 16) << 4) + (r2 / 16)); - } - } -} - -void ZTexture::ConvertBitmapToN64_Grayscale8() -{ - for (uint16_t y = 0; y < height; y++) - { - for (uint16_t x = 0; x < width; x++) - { - size_t pos = (y * width) + x; - RGBAPixel pixel = textureData.GetPixel(y, x); - textureDataRaw[pos] = pixel.r; - } - } -} - -void ZTexture::ConvertBitmapToN64_GrayscaleAlpha4() -{ - for (uint16_t y = 0; y < height; y++) - { - for (uint16_t x = 0; x < width; x += 2) - { - size_t pos = ((y * width) + x) / 2; - uint8_t data = 0; - - for (uint16_t i = 0; i < 2; i++) - { - RGBAPixel pixel = textureData.GetPixel(y, x + i); - uint8_t cR = pixel.r; - uint8_t alphaBit = pixel.a != 0; - - if (i == 0) - data = (((cR >> 5) << 1) | alphaBit) << 4; - else - data |= ((cR >> 5) << 1) | alphaBit; - } - - textureDataRaw[pos] = data; - } - } -} - -void ZTexture::ConvertBitmapToN64_GrayscaleAlpha8() -{ - for (uint16_t y = 0; y < height; y++) - { - for (uint16_t x = 0; x < width; x++) - { - size_t pos = ((y * width) + x) * 1; - RGBAPixel pixel = textureData.GetPixel(y, x); - - uint8_t r = (pixel.r >> 4) & 0xF; - uint8_t a = (pixel.a >> 4) & 0xF; - - textureDataRaw[pos] = (r << 4) | a; - } - } -} - -void ZTexture::ConvertBitmapToN64_GrayscaleAlpha16() -{ - for (uint16_t y = 0; y < height; y++) - { - for (uint16_t x = 0; x < width; x++) - { - size_t pos = ((y * width) + x) * 2; - RGBAPixel pixel = textureData.GetPixel(y, x); - - uint8_t cR = pixel.r; - uint8_t aR = pixel.a; - - textureDataRaw[pos + 0] = cR; - textureDataRaw[pos + 1] = aR; - } - } -} - -void ZTexture::ConvertBitmapToN64_Palette4() -{ - for (uint16_t y = 0; y < height; y++) - { - for (uint16_t x = 0; x < width; x += 2) - { - size_t pos = ((y * width) + x) / 2; - - uint8_t cR1 = textureData.GetIndexedPixel(y, x); - uint8_t cR2 = textureData.GetIndexedPixel(y, x + 1); - - textureDataRaw[pos] = (cR1 << 4) | (cR2); - } - } -} - -void ZTexture::ConvertBitmapToN64_Palette8() -{ - for (uint16_t y = 0; y < height; y++) - { - for (uint16_t x = 0; x < width; x++) - { - size_t pos = ((y * width) + x); - uint8_t cR = textureData.GetIndexedPixel(y, x); - - textureDataRaw[pos] = cR; - } - } -} - -float ZTexture::GetPixelMultiplyer() const -{ - switch (format) - { - case TextureType::Grayscale4bpp: - case TextureType::GrayscaleAlpha4bpp: - case TextureType::Palette4bpp: - return 0.5f; - case TextureType::Grayscale8bpp: - case TextureType::GrayscaleAlpha8bpp: - case TextureType::Palette8bpp: - return 1; - case TextureType::GrayscaleAlpha16bpp: - case TextureType::RGBA16bpp: - return 2; - case TextureType::RGBA32bpp: - return 4; - default: - return -1; - } -} - -size_t ZTexture::GetRawDataSize() const -{ - return (width * height * GetPixelMultiplyer()); -} - -std::string ZTexture::GetIMFmtFromType() -{ - switch (format) - { - case TextureType::RGBA32bpp: - case TextureType::RGBA16bpp: - return "G_IM_FMT_RGBA"; - case TextureType::Grayscale4bpp: - case TextureType::Grayscale8bpp: - return "G_IM_FMT_I"; - case TextureType::Palette4bpp: - case TextureType::Palette8bpp: - return "G_IM_FMT_CI"; - case TextureType::GrayscaleAlpha4bpp: - case TextureType::GrayscaleAlpha8bpp: - case TextureType::GrayscaleAlpha16bpp: - return "G_IM_FMT_IA"; - default: - return "ERROR"; - } -} - -std::string ZTexture::GetIMSizFromType() -{ - switch (format) - { - case TextureType::Grayscale4bpp: - case TextureType::Palette4bpp: - case TextureType::GrayscaleAlpha4bpp: - return "G_IM_SIZ_4b"; - case TextureType::Palette8bpp: - case TextureType::Grayscale8bpp: - return "G_IM_SIZ_8b"; - case TextureType::GrayscaleAlpha16bpp: - case TextureType::RGBA16bpp: - return "G_IM_SIZ_16b"; - case TextureType::RGBA32bpp: - return "G_IM_SIZ_32b"; - default: - return "ERROR"; - } -} - -std::string ZTexture::GetDefaultName(const std::string& prefix) const -{ - const char* suffix = "Tex"; - if (isPalette) - suffix = "TLUT"; - return StringHelper::Sprintf("%s%s_%06X", prefix.c_str(), suffix, rawDataIndex); -} - -uint32_t ZTexture::GetWidth() const -{ - return width; -} - -uint32_t ZTexture::GetHeight() const -{ - return height; -} - -void ZTexture::SetDimensions(uint32_t nWidth, uint32_t nHeight) -{ - width = nWidth; - height = nHeight; - ParseRawData(); -} - -TextureType ZTexture::GetTextureType() const -{ - return format; -} - -void ZTexture::Save(const fs::path& outFolder) -{ - // Optionally generate text file containing CRC information. This is going to be a one time - // process for generating the Texture Pool XML. - if (Globals::Instance->outputCrc) - { - File::WriteAllText((Globals::Instance->outputPath / (outName + ".txt")).string(), - StringHelper::Sprintf("%08lX", hash)); - } - - auto outPath = GetPoolOutPath(outFolder); - - if (!Directory::Exists(outPath.string())) - Directory::CreateDirectory(outPath.string()); - - fs::path outFileName; - - if (!dWordAligned) - outFileName = outPath / (outName + ".u32" + "." + GetExternalExtension() + ".png"); - else - outFileName = outPath / (outName + +"." + GetExternalExtension() + ".png"); - -#ifdef TEXTURE_DEBUG - printf("Saving PNG: %s\n", outFileName.c_str()); - printf("\t Var name: %s\n", name.c_str()); - if (tlut != nullptr) - printf("\t TLUT name: %s\n", tlut->name.c_str()); -#endif - - textureData.WritePng(outFileName); - -#ifdef TEXTURE_DEBUG - printf("\n"); -#endif -} - -Declaration* ZTexture::DeclareVar(const std::string& prefix, - [[maybe_unused]] const std::string& bodyStr) -{ - std::string auxName = name; - std::string auxOutName = outName; - std::string incStr; - if (auxName == "") - auxName = GetDefaultName(prefix); - - if (auxOutName == "") - auxOutName = GetDefaultName(prefix); - - auto filepath = Globals::Instance->outputPath / fs::path(auxOutName).stem(); - - if (dWordAligned) - incStr = StringHelper::Sprintf("%s.%s.inc.c", filepath.string().c_str(), - GetExternalExtension().c_str()); - else - incStr = StringHelper::Sprintf("%s.u32.%s.inc.c", filepath.string().c_str(), - GetExternalExtension().c_str()); - - if (!Globals::Instance->cfg.texturePool.empty()) - { - CalcHash(); - - // TEXTURE POOL CHECK - const auto& poolEntry = Globals::Instance->cfg.texturePool.find(hash); - if (poolEntry != Globals::Instance->cfg.texturePool.end()) - { - if (dWordAligned) - incStr = - StringHelper::Sprintf("%s.%s.inc.c", poolEntry->second.path.string().c_str(), - GetExternalExtension().c_str()); - else - incStr = StringHelper::Sprintf("%s.u32.%s.inc.c", - poolEntry->second.path.string().c_str(), - GetExternalExtension().c_str()); - } - } - size_t texSizeDivisor = (dWordAligned) ? 8 : 4; - - Declaration* decl; - - if (parent->makeDefines) - { - decl = parent->AddDeclarationIncludeArray(rawDataIndex, incStr, GetRawDataSize(), - GetSourceTypeName(), auxName, GetHeaderDefines(), - GetRawDataSize() / texSizeDivisor); - } - else - { - decl = parent->AddDeclarationIncludeArray(rawDataIndex, incStr, GetRawDataSize(), - GetSourceTypeName(), auxName, - GetRawDataSize() / texSizeDivisor); - } - decl->staticConf = staticConf; - return decl; -} - -std::string ZTexture::GetBodySourceCode() const -{ - std::string sourceOutput; - size_t texSizeInc = (dWordAligned) ? 8 : 4; - for (size_t i = 0; i < textureDataRaw.size(); i += texSizeInc) - { - if (i % 32 == 0) - sourceOutput += " "; - if (dWordAligned) - sourceOutput += - StringHelper::Sprintf("0x%016llX, ", BitConverter::ToUInt64BE(textureDataRaw, i)); - else - sourceOutput += - StringHelper::Sprintf("0x%08llX, ", BitConverter::ToUInt32BE(textureDataRaw, i)); - if (i % 32 == 24) - sourceOutput += StringHelper::Sprintf(" // 0x%06X \n", rawDataIndex + ((i / 32) * 32)); - } - - // Ensure there's always a trailing line feed to prevent dumb warnings. - // Please don't remove this line, unless you somehow made a way to prevent - // that warning when building the OoT repo. - sourceOutput += "\n"; - - return sourceOutput; -} - -std::string ZTexture::GetHeaderDefines() const -{ - std::string definePrefix = StringHelper::camelCaseTo_SCREAMING_SNAKE_CASE(name.c_str(), true); - std::string ret = StringHelper::Sprintf("#define %s_WIDTH %d\n", definePrefix.c_str(), width); - - ret += StringHelper::Sprintf("#define %s_HEIGHT %d\n", definePrefix.c_str(), height); - ret += StringHelper::Sprintf("#define %s_SIZE 0x%zX\n", definePrefix.c_str(), GetRawDataSize()); - - return ret; -} - -bool ZTexture::IsExternalResource() const -{ - return true; -} - -ZResourceType ZTexture::GetResourceType() const -{ - return ZResourceType::Texture; -} - -std::string ZTexture::GetSourceTypeName() const -{ - return dWordAligned ? "u64" : "u32"; -} - -void ZTexture::CalcHash() -{ - const auto& parentRawData = parent->GetRawData(); - hash = CRC32B(parentRawData.data() + rawDataIndex, GetRawDataSize()); -} - -std::string ZTexture::GetExternalExtension() const -{ - switch (format) - { - case TextureType::RGBA32bpp: - return "rgba32"; - case TextureType::RGBA16bpp: - return "rgba16"; - case TextureType::Grayscale4bpp: - return "i4"; - case TextureType::Grayscale8bpp: - return "i8"; - case TextureType::GrayscaleAlpha4bpp: - return "ia4"; - case TextureType::GrayscaleAlpha8bpp: - return "ia8"; - case TextureType::GrayscaleAlpha16bpp: - return "ia16"; - case TextureType::Palette4bpp: - return "ci4"; - case TextureType::Palette8bpp: - return "ci8"; - default: - return "ERROR"; - } -} - -fs::path ZTexture::GetPoolOutPath(const fs::path& defaultValue) -{ - if (Globals::Instance->cfg.texturePool.find(hash) != Globals::Instance->cfg.texturePool.end()) - return Path::GetDirectoryName(Globals::Instance->cfg.texturePool[hash].path.string()); - - return defaultValue; -} - -TextureType ZTexture::GetTextureTypeFromString(const std::string& str) -{ - TextureType texType = TextureType::Error; - - if (str == "rgba32") - texType = TextureType::RGBA32bpp; - else if (str == "rgba16") - texType = TextureType::RGBA16bpp; - else if (str == "rgb5a1") - { - texType = TextureType::RGBA16bpp; - HANDLE_WARNING(WarningType::Deprecated, - "the texture format 'rgb5a1' is currently deprecated", - "It will be removed in a future version. Use the format 'rgba16' instead."); - } - else if (str == "i4") - texType = TextureType::Grayscale4bpp; - else if (str == "i8") - texType = TextureType::Grayscale8bpp; - else if (str == "ia4") - texType = TextureType::GrayscaleAlpha4bpp; - else if (str == "ia8") - texType = TextureType::GrayscaleAlpha8bpp; - else if (str == "ia16") - texType = TextureType::GrayscaleAlpha16bpp; - else if (str == "ci4") - texType = TextureType::Palette4bpp; - else if (str == "ci8") - texType = TextureType::Palette8bpp; - else - // TODO: handle this case in a more coherent way - HANDLE_WARNING(WarningType::InvalidAttributeValue, - "invalid value found for 'Type' attribute", "Defaulting to ''."); - return texType; -} - -bool ZTexture::IsColorIndexed() const -{ - switch (format) - { - case TextureType::Palette4bpp: - case TextureType::Palette8bpp: - return true; - - default: - return false; - } -} - -void ZTexture::SetTlut(ZTexture* nTlut) -{ - assert(IsColorIndexed()); - assert(nTlut->isPalette); - tlut = nTlut; - - textureData.SetPalette(tlut->textureData, splitTlut ? 128 : 0); -} - -bool ZTexture::HasTlut() const -{ - return tlut != nullptr; -} diff --git a/tools/ZAPD/ZAPD/ZTexture.h b/tools/ZAPD/ZAPD/ZTexture.h deleted file mode 100644 index 1461ff95a6..0000000000 --- a/tools/ZAPD/ZAPD/ZTexture.h +++ /dev/null @@ -1,119 +0,0 @@ -#pragma once - -#include "ImageBackend.h" -#include "ZResource.h" -#include "tinyxml2.h" - -enum class TextureType -{ - Error, - RGBA32bpp, - RGBA16bpp, - Palette4bpp, - Palette8bpp, - Grayscale4bpp, - Grayscale8bpp, - GrayscaleAlpha4bpp, - GrayscaleAlpha8bpp, - GrayscaleAlpha16bpp, -}; - -class ZTexture : public ZResource -{ -protected: - TextureType format = TextureType::Error; - uint32_t width, height; - - ImageBackend textureData; - std::vector textureDataRaw; // When reading from a PNG file. - uint32_t tlutOffset = static_cast(-1); - ZTexture* tlut = nullptr; - bool splitTlut; - - // The following functions convert from N64 binary data to a bitmap to be saved to a PNG. - void ConvertN64ToBitmap_RGBA16(); - void ConvertN64ToBitmap_RGBA32(); - void ConvertN64ToBitmap_Grayscale8(); - void ConvertN64ToBitmap_GrayscaleAlpha8(); - void ConvertN64ToBitmap_Grayscale4(); - void ConvertN64ToBitmap_GrayscaleAlpha4(); - void ConvertN64ToBitmap_GrayscaleAlpha16(); - void ConvertN64ToBitmap_Palette4(); - void ConvertN64ToBitmap_Palette8(); - - // The following functions convert from a bitmap to N64 binary data. - void PrepareRawDataFromFile(const fs::path& inFolder); - void ConvertBitmapToN64_RGBA16(); - void ConvertBitmapToN64_RGBA32(); - void ConvertBitmapToN64_Grayscale4(); - void ConvertBitmapToN64_Grayscale8(); - void ConvertBitmapToN64_GrayscaleAlpha4(); - void ConvertBitmapToN64_GrayscaleAlpha8(); - void ConvertBitmapToN64_GrayscaleAlpha16(); - void ConvertBitmapToN64_Palette4(); - void ConvertBitmapToN64_Palette8(); - -public: - ZTexture(ZFile* nParent); - - bool isPalette = false; - bool dWordAligned = true; - - void ExtractFromBinary(uint32_t nRawDataIndex, int32_t nWidth, int32_t nHeight, - TextureType nType, bool nIsPalette); - void FromPNG(const fs::path& pngFilePath, TextureType texType); - static TextureType GetTextureTypeFromString(const std::string& str); - - void ParseXML(tinyxml2::XMLElement* reader) override; - void ParseRawData() override; - void DeclareReferences(const std::string& prefix) override; - - Declaration* DeclareVar(const std::string& prefix, const std::string& bodyStr) override; - std::string GetBodySourceCode() const override; - - /// - /// Calculates the hash of this texture, for use with the texture pool. - /// - void CalcHash() override; - - void Save(const fs::path& outFolder) override; - - std::string GetHeaderDefines() const; - bool IsExternalResource() const override; - std::string GetSourceTypeName() const override; - ZResourceType GetResourceType() const override; - std::string GetExternalExtension() const override; - - size_t GetRawDataSize() const override; - std::string GetIMFmtFromType(); - std::string GetIMSizFromType(); - std::string GetDefaultName(const std::string& prefix) const override; - uint32_t GetWidth() const; - uint32_t GetHeight() const; - void SetDimensions(uint32_t nWidth, uint32_t nHeight); - - /// - /// Returns how many bytes each pixel takes up. - /// - /// - float GetPixelMultiplyer() const; - - TextureType GetTextureType() const; - - /// - /// Returns the path to the texture pool, taken from the config file. - /// - /// - /// - fs::path GetPoolOutPath(const fs::path& defaultValue); - - /// - /// Returns if this texture uses a palette. - /// - /// - bool IsColorIndexed() const; - - void SetTlut(ZTexture* nTlut); - bool HasTlut() const; - void ParseRawDataLate() override; -}; diff --git a/tools/ZAPD/ZAPD/ZTextureAnimation.cpp b/tools/ZAPD/ZAPD/ZTextureAnimation.cpp deleted file mode 100644 index 0c55b26097..0000000000 --- a/tools/ZAPD/ZAPD/ZTextureAnimation.cpp +++ /dev/null @@ -1,666 +0,0 @@ -/** - * File: ZTextureAnimation.cpp - * ZResources defined: ZTextureAnimation, ZTextureAnimationParams (XML declaration not supported for - * the latter) - * Purpose: extracting texture animating structures from asset files - * Note: data type is exclusive to Majora's Mask - * - * Structure of data: - * A texture animation consists of a main array of data of the form - * `SS 00 00 0T PPPPPPPP`, - * where `S` is the segment that the functionality is sent to (and read by DLists), `T` is the - * "type" (see below), and `P` is a pointer to the type's subsidiary information, which is - * invariably just above this main array. Details of this subsidiary data are given below. - * - * Segment - * === - * The segment starts at 1 and is incremented in each entry; the final one is negated, which is used - * as the indication to stop reading. The actual segment the game will use to draw is S + 7. - * - * Types - * === - * There are 7 values that `T` can take: - * `0`: A single texture scroll (Implemented by Gfx_TexScroll): subsidiary params are given as - * an array with one entry, a struct `XX YY WW HH` containing xStep, yStep, width, height - * (all u8). - * - * `1`: A dual texture scroll (Implementated by Gfx_TwoTexScroll): same as type `0`, but with - * two entries in the params array. - * - * `2`: Color changing: Changes the primColor (with a LOD factor) and envColor - * `KKKK LLLL PPPPPPPP QQQQQQQQ RRRRRRRR` - * - `K` (u16) is the total length of the animation (and in this case, the total number of - * colors) - * - `L` (u16) is seemingly always 0 for this type, and not used in the code - * - `P` segmented pointer to array of augmented primColors - * - `Q` segmented pointer to array of envColors, and can be NULL - * - `R` segmented pointer to array of frameData (u8), which is also seemingly always NULL - * for this type. - * - * envColors take the form `RR GG BB AA` as usual, while primColors have an extra LODFrac - * element: RR GG BB AA LL - * - * `3`: Color changing (LERP): similar to type `2`, but uses linear interpolation. The structure - * is similar to `2`, but - * - `K` is now just the animation length, while - * - `L` is the total number of colors, and - * - the frameData is used to determine which colors to interpolate. - * - * `4`: Color changing (Lagrange interpolation): For extraction purposes identical to type 3. - * Uses a nonlinear interpolation formula to change the colours more smoothly. - * - * `5`: Texture cycle: functions like a gif. Subsidiary params: - * `FFFF 0000 PPPPPPPP QQQQQQQQ` - * where - * - `F` (u16) time between changes in frames - * - `P` pointer to array of segmented pointers to textures to cycle through - * - `Q` array of indices, indicating which texture to use next when a change frame is - * reached. The maximum indicates the number of textures in the texture array. - * - * `6`: This is used to indicate an empty/unimplemented params set. It is ignored by the game's - * function provided that the segment is 0. A generic empty one takes the form - * `00 00 00 06 00000000`, - * and has no extra data. - * - * Implementation - * === - * - ZTextureAnimation requires a declaration in the XML to extract anything. It handles the main - * array. It uses a POD struct for each entry, and declares references to the params structs. - * - * - ZTextureAnimationParams is not (currently) declarable in an XML. It is a parent class for the - * three classes that handle the various cases: - * - TextureScrollingParams for types `0` and `1` - * - TextureColorChangingParams for types `2`,`3`,`4` - * - TextureCyclingParams for type `5` - * Each of these will declare all its subsidiary arrays, using POD structs. - */ -#include "ZTextureAnimation.h" - -#include -#include -#include - -#include "Globals.h" -#include "Utils/BitConverter.h" -#include "WarningHandler.h" -#include "ZFile.h" -#include "ZResource.h" -#include "tinyxml2.h" - -REGISTER_ZFILENODE(TextureAnimation, ZTextureAnimation); - -/* Constructors */ -ZTextureAnimationParams::ZTextureAnimationParams(ZFile* parent) : ZResource::ZResource(parent) -{ -} -TextureScrollingParams::TextureScrollingParams(ZFile* parent) - : ZTextureAnimationParams::ZTextureAnimationParams(parent) -{ -} -TextureColorChangingParams::TextureColorChangingParams(ZFile* parent) - : ZTextureAnimationParams::ZTextureAnimationParams(parent) -{ -} -TextureCyclingParams::TextureCyclingParams(ZFile* parent) - : ZTextureAnimationParams::ZTextureAnimationParams(parent) -{ -} - -/* TextureAnimationParams */ -/* This class only implements the functions common to all or most its inheritors */ - -void ZTextureAnimationParams::ExtractFromBinary(uint32_t nRawDataIndex) -{ - rawDataIndex = nRawDataIndex; - - ParseRawData(); -} - -// Implemented by TextureScrollingParams only -void ZTextureAnimationParams::ExtractFromBinary([[maybe_unused]] uint32_t nRawDataIndex, - [[maybe_unused]] int count) -{ -} - -std::string -ZTextureAnimationParams::GetDefaultName([[maybe_unused]] const std::string& prefix) const -{ - return "ShouldNotBeVIsible"; -} - -ZResourceType ZTextureAnimationParams::GetResourceType() const -{ - return ZResourceType::TextureAnimationParams; -} - -/* TextureScrollingParams */ - -void TextureScrollingParams::ParseRawData() -{ - const auto& rawData = parent->GetRawData(); - - for (int i = 0; i < count; i++) - { - rows[i].xStep = BitConverter::ToUInt8BE(rawData, rawDataIndex + 4 * i); - rows[i].yStep = BitConverter::ToUInt8BE(rawData, rawDataIndex + 4 * i + 1); - rows[i].width = BitConverter::ToUInt8BE(rawData, rawDataIndex + 4 * i + 2); - rows[i].height = BitConverter::ToUInt8BE(rawData, rawDataIndex + 4 * i + 3); - } -} - -void TextureScrollingParams::ExtractFromBinary(uint32_t nRawDataIndex, int nCount) -{ - rawDataIndex = nRawDataIndex; - count = nCount; - - ParseRawData(); -} - -std::string TextureScrollingParams::GetSourceTypeName() const -{ - return "AnimatedMatTexScrollParams"; // TODO: Better name -} - -std::string TextureScrollingParams::GetDefaultName(const std::string& prefix) const -{ - return StringHelper::Sprintf("%sTexScrollParams_%06X", prefix.c_str(), rawDataIndex); -} - -size_t TextureScrollingParams::GetRawDataSize() const -{ - return 4 * count; -} - -/** - * Overrides the parent version to declare an array of the params rather than just one entry. - */ -Declaration* TextureScrollingParams::DeclareVar(const std::string& prefix, - const std::string& bodyStr) -{ - std::string auxName = name; - - if (name == "") - auxName = GetDefaultName(prefix); - - return parent->AddDeclarationArray(rawDataIndex, GetDeclarationAlignment(), GetRawDataSize(), - GetSourceTypeName(), auxName, count, bodyStr); -} - -std::string TextureScrollingParams::GetBodySourceCode() const -{ - std::string bodyStr; - - for (int i = 0; i < count; i++) - { - bodyStr += StringHelper::Sprintf("\t{ %d, %d, 0x%02X, 0x%02X },\n", rows[i].xStep, - rows[i].yStep, rows[i].width, rows[i].height); - } - - bodyStr.pop_back(); - - return bodyStr; -} - -/* TextureColorChangingParams */ - -/** - * Also parses the color and frameData arrays - */ -void TextureColorChangingParams::ParseRawData() -{ - const auto& rawData = parent->GetRawData(); - - animLength = BitConverter::ToUInt16BE(rawData, rawDataIndex); - colorListCount = BitConverter::ToUInt16BE(rawData, rawDataIndex + 2); - - // Handle type 2 separately - uint16_t listLength = - ((type == TextureAnimationParamsType::ColorChange) ? animLength : colorListCount); - - if (listLength == 0) - HANDLE_ERROR_RESOURCE(WarningType::Always, parent, this, rawDataIndex, - "color list length cannot be 0", ""); - - primColorListAddress = BitConverter::ToUInt32BE(rawData, rawDataIndex + 4); - envColorListAddress = BitConverter::ToUInt32BE(rawData, rawDataIndex + 8); - frameDataListAddress = BitConverter::ToUInt32BE(rawData, rawDataIndex + 0xC); - - uint32_t primColorListOffset = Seg2Filespace(primColorListAddress, parent->baseAddress); - uint32_t envColorListOffset = Seg2Filespace(envColorListAddress, parent->baseAddress); - uint32_t frameDataListOffset = Seg2Filespace(frameDataListAddress, parent->baseAddress); - - uint32_t currentPtr; - - F3DPrimColor currentPrimColor; - - for (currentPtr = primColorListOffset; currentPtr < primColorListOffset + 5 * listLength; - currentPtr += 5) - { - currentPrimColor = {BitConverter::ToUInt8BE(rawData, currentPtr), - BitConverter::ToUInt8BE(rawData, currentPtr + 1), - BitConverter::ToUInt8BE(rawData, currentPtr + 2), - BitConverter::ToUInt8BE(rawData, currentPtr + 3), - BitConverter::ToUInt8BE(rawData, currentPtr + 4)}; - primColorList.push_back(currentPrimColor); - } - - F3DEnvColor currentEnvColor; - - for (currentPtr = envColorListOffset; currentPtr < envColorListOffset + 4 * listLength; - currentPtr += 4) - { - currentEnvColor = {BitConverter::ToUInt8BE(rawData, currentPtr), - BitConverter::ToUInt8BE(rawData, currentPtr + 1), - BitConverter::ToUInt8BE(rawData, currentPtr + 2), - BitConverter::ToUInt8BE(rawData, currentPtr + 3)}; - envColorList.push_back(currentEnvColor); - } - - uint16_t currentFrameData; - - for (currentPtr = frameDataListOffset; currentPtr < frameDataListOffset + 2 * listLength; - currentPtr += 2) - { - currentFrameData = BitConverter::ToUInt16BE(rawData, currentPtr); - frameDataList.push_back(currentFrameData); - } -} - -std::string TextureColorChangingParams::GetSourceTypeName() const -{ - return "AnimatedMatColorParams"; // TODO: Better name -} - -std::string TextureColorChangingParams::GetDefaultName(const std::string& prefix) const -{ - return StringHelper::Sprintf("%sColorParams_%06X", prefix.c_str(), rawDataIndex); -} - -size_t TextureColorChangingParams::GetRawDataSize() const -{ - return 0x10; -} - -void TextureColorChangingParams::DeclareReferences([[maybe_unused]] const std::string& prefix) -{ - if (primColorListAddress != 0) // NULL - { - std::string primColorBodyStr; - - for (const auto& color : primColorList) - { - primColorBodyStr += StringHelper::Sprintf("\t{ %d, %d, %d, %d, %d },\n", color.r, - color.g, color.b, color.a, color.lodFrac); - } - - primColorBodyStr.pop_back(); - - parent->AddDeclarationArray( - Seg2Filespace(primColorListAddress, parent->baseAddress), DeclarationAlignment::Align4, - primColorList.size() * 5, "F3DPrimColor", - StringHelper::Sprintf("%sTexColorChangingPrimColors_%06X", parent->GetName().c_str(), - Seg2Filespace(primColorListAddress, parent->baseAddress)), - primColorList.size(), primColorBodyStr); - } - - if (envColorListAddress != 0) // NULL - { - std::string envColorBodyStr; - - for (const auto& color : envColorList) - { - envColorBodyStr += StringHelper::Sprintf("\t{ %d, %d, %d, %d },\n", color.r, color.g, - color.b, color.a); - } - - envColorBodyStr.pop_back(); - - parent->AddDeclarationArray( - Seg2Filespace(envColorListAddress, parent->baseAddress), DeclarationAlignment::Align4, - envColorList.size() * 4, "F3DEnvColor", - StringHelper::Sprintf("%sTexColorChangingEnvColors_%06X", parent->GetName().c_str(), - Seg2Filespace(envColorListAddress, parent->baseAddress)), - envColorList.size(), envColorBodyStr); - } - - if (frameDataListAddress != 0) // NULL - { - std::string frameDataBodyStr = "\t"; - - for (const auto& frame : frameDataList) - { - frameDataBodyStr += StringHelper::Sprintf("%d, ", frame); - } - - frameDataBodyStr.pop_back(); - - parent->AddDeclarationArray( - Seg2Filespace(frameDataListAddress, parent->baseAddress), DeclarationAlignment::Align4, - frameDataList.size() * 2, "u16", - StringHelper::Sprintf("%sTexColorChangingFrameData_%06X", parent->GetName().c_str(), - Seg2Filespace(frameDataListAddress, parent->baseAddress)), - frameDataList.size(), frameDataBodyStr); - } -} - -std::string TextureColorChangingParams::GetBodySourceCode() const -{ - std::string primColorListName; - std::string envColorListName; - std::string frameDataListName; - - Globals::Instance->GetSegmentedPtrName(primColorListAddress, parent, "", primColorListName); - Globals::Instance->GetSegmentedPtrName(envColorListAddress, parent, "", envColorListName); - Globals::Instance->GetSegmentedPtrName(frameDataListAddress, parent, "", frameDataListName); - - std::string bodyStr = StringHelper::Sprintf( - "\n %d, %d, %s, %s, %s,\n", animLength, colorListCount, primColorListName.c_str(), - envColorListName.c_str(), frameDataListName.c_str()); - - return bodyStr; -} - -/* TextureCyclingParams */ - -void TextureCyclingParams::ParseRawData() -{ - const auto& rawData = parent->GetRawData(); - - cycleLength = BitConverter::ToUInt16BE(rawData, rawDataIndex); - if (cycleLength == 0) - HANDLE_ERROR_RESOURCE(WarningType::Always, parent, this, rawDataIndex, - "cycle length cannot be 0", ""); - - textureListAddress = BitConverter::ToUInt32BE(rawData, rawDataIndex + 4); - textureIndexListAddress = BitConverter::ToUInt32BE(rawData, rawDataIndex + 8); - - uint32_t textureListOffset = Seg2Filespace(textureListAddress, parent->baseAddress); - uint32_t textureIndexListOffset = Seg2Filespace(textureIndexListAddress, parent->baseAddress); - - uint32_t currentPtr; - - uint8_t currentIndex; - uint8_t maxIndex = 0; // To find the length of the texture list - - for (currentPtr = textureIndexListOffset; currentPtr < textureIndexListOffset + cycleLength; - currentPtr++) - { - currentIndex = BitConverter::ToUInt8BE(rawData, currentPtr); - textureIndexList.push_back(currentIndex); - if (currentIndex > maxIndex) - maxIndex = currentIndex; - } - - for (currentPtr = textureListOffset; currentPtr <= textureListOffset + 4 * maxIndex; - currentPtr += 4) - { - textureList.push_back(BitConverter::ToUInt32BE(rawData, currentPtr)); - } -} - -std::string TextureCyclingParams::GetSourceTypeName() const -{ - return "AnimatedMatTexCycleParams"; // TODO: Better name -} - -std::string TextureCyclingParams::GetDefaultName(const std::string& prefix) const -{ - return StringHelper::Sprintf("%sTexCycleParams_%06X", prefix.c_str(), rawDataIndex); -} - -size_t TextureCyclingParams::GetRawDataSize() const -{ - return 0xC; -} - -void TextureCyclingParams::DeclareReferences([[maybe_unused]] const std::string& prefix) -{ - if (textureListAddress != 0) // NULL - { - std::string texturesBodyStr; - std::string texName; - std::string comment; - - for (const auto& tex : textureList) - { - bool texFound = Globals::Instance->GetSegmentedPtrName(tex, parent, "", texName); - - // texName is a raw segmented pointer. This occurs if the texture is not declared - // separately since we cannot read the format. In theory we could scan DLists for the - // format on the appropriate segments. - if (!texFound) - { - comment = " // Raw pointer, declare texture in XML to use proper symbol"; - - auto msgHeader = StringHelper::Sprintf( - "TexCycle texture array declared here points to unknown texture at address %s", - texName.c_str()); - HANDLE_WARNING_RESOURCE( - WarningType::HardcodedPointer, parent, this, rawDataIndex, msgHeader, - "Please declare the texture in the XML to use the proper symbol."); - } - texturesBodyStr += StringHelper::Sprintf("\t%s,%s\n", texName.c_str(), comment.c_str()); - } - - texturesBodyStr.pop_back(); - - parent->AddDeclarationArray( - Seg2Filespace(textureListAddress, parent->baseAddress), DeclarationAlignment::Align4, - textureList.size() * 4, "TexturePtr", - StringHelper::Sprintf("%sTexCycleTexPtrs_%06X", parent->GetName().c_str(), - Seg2Filespace(textureListAddress, parent->baseAddress)), - textureList.size(), texturesBodyStr); - } - - if (textureIndexListAddress != 0) // NULL - { - std::string indicesBodyStr = "\t"; - - for (uint8_t index : textureIndexList) - { - indicesBodyStr += StringHelper::Sprintf("%d, ", index); - } - - indicesBodyStr.pop_back(); - - parent->AddDeclarationArray( - Seg2Filespace(textureIndexListAddress, parent->baseAddress), - DeclarationAlignment::Align4, textureIndexList.size(), "u8", - StringHelper::Sprintf("%sTexCycleTexIndices_%06X", parent->GetName().c_str(), - Seg2Filespace(textureIndexListAddress, parent->baseAddress)), - textureIndexList.size(), indicesBodyStr); - } -} - -std::string TextureCyclingParams::GetBodySourceCode() const -{ - std::string textureListName; - std::string textureIndexListName; - - Globals::Instance->GetSegmentedPtrName(textureListAddress, parent, "", textureListName); - Globals::Instance->GetSegmentedPtrName(textureIndexListAddress, parent, "", - textureIndexListName); - - std::string bodyStr = StringHelper::Sprintf( - "\n %d, %s, %s,\n", cycleLength, textureListName.c_str(), textureIndexListName.c_str()); - - return bodyStr; -} - -/* ZTextureAnimation */ - -ZTextureAnimation::ZTextureAnimation(ZFile* nParent) : ZResource(nParent) -{ -} - -/** - * Builds the array of params - */ -void ZTextureAnimation::ParseRawData() -{ - ZResource::ParseRawData(); - - TextureAnimationEntry currentEntry; - auto rawData = parent->GetRawData(); - int16_t type; - - for (uint32_t currentPtr = rawDataIndex;; currentPtr += 8) - { - type = BitConverter::ToInt16BE(rawData, currentPtr + 2); - - currentEntry.segment = BitConverter::ToInt8BE(rawData, currentPtr); - currentEntry.type = (TextureAnimationParamsType)type; - currentEntry.paramsPtr = BitConverter::ToUInt32BE(rawData, currentPtr + 4); - entries.push_back(currentEntry); - - if ((type < 0) || (type > 6)) - { - HANDLE_ERROR_RESOURCE( - WarningType::Always, parent, this, rawDataIndex, - StringHelper::Sprintf( - "unknown TextureAnimationParams type 0x%02X in TextureAnimation", type), - StringHelper::Sprintf( - "Entry reads { 0x%02X, 0x%02X, 0x%08X } , but type should be " - "between 0x00 and 0x06 inclusive.", - currentEntry.segment, type, currentEntry.paramsPtr)); - } - - if (currentEntry.segment <= 0) - break; - } -} - -#include -/** - * For each params entry, - */ -void ZTextureAnimation::DeclareReferences(const std::string& prefix) -{ - std::string varPrefix = name; - if (varPrefix == "") - varPrefix = prefix; - - ZResource::DeclareReferences(varPrefix); - - for (const auto& entry : entries) - { - if (entry.paramsPtr != 0 && GETSEGNUM(entry.paramsPtr) == parent->segment) - { - uint32_t paramsOffset = Seg2Filespace(entry.paramsPtr, parent->baseAddress); - if (!parent->HasDeclaration(paramsOffset)) - { - ZTextureAnimationParams* params; - int count; - switch (entry.type) - { - case TextureAnimationParamsType::SingleScroll: - if (true) - { - count = 1; - // The else now allows SingleScroll to fall through to params = ... without - // touching the code in the else block - } - else - { - // The contents of this block can only be run by jumping into it with the - // case label - [[fallthrough]]; - case TextureAnimationParamsType::DualScroll: - count = 2; - } - params = new TextureScrollingParams(parent); - params->type = entry.type; - params->ExtractFromBinary(paramsOffset, count); - break; - - case TextureAnimationParamsType::ColorChange: - case TextureAnimationParamsType::ColorChangeLERP: - case TextureAnimationParamsType::ColorChangeLagrange: - params = new TextureColorChangingParams(parent); - params->type = entry.type; - params->ExtractFromBinary(paramsOffset); - break; - - case TextureAnimationParamsType::TextureCycle: - params = new TextureCyclingParams(parent); - params->type = entry.type; - params->ExtractFromBinary(paramsOffset); - break; - - case TextureAnimationParamsType::Empty: - HANDLE_WARNING_RESOURCE( - WarningType::InvalidExtractedData, parent, this, rawDataIndex, - "TextureAnimationParams entry has empty type (6), but params pointer is " - "not NULL", - StringHelper::Sprintf("Params read { 0x%02X, 0x%02X, 0x%08X } .", - entry.segment, (int)entry.type, entry.paramsPtr)); - return; - default: - // Because GCC is worried this could happen - assert(entry.type < TextureAnimationParamsType::SingleScroll || - entry.type > TextureAnimationParamsType::Empty); - return; - } - - params->SetName(params->GetDefaultName(varPrefix)); - params->DeclareVar(varPrefix, ""); - parent->AddResource(params); - } - } - } -} - -std::string ZTextureAnimation::GetSourceTypeName() const -{ - return "AnimatedMaterial"; // TODO: Better name -} - -ZResourceType ZTextureAnimation::GetResourceType() const -{ - return ZResourceType::TextureAnimation; -} - -/** - * The size of the main array - */ -size_t ZTextureAnimation::GetRawDataSize() const -{ - return entries.size() * 8; -} - -std::string ZTextureAnimation::GetDefaultName(const std::string& prefix) const -{ - return StringHelper::Sprintf("%sTexAnim_%06X", prefix.c_str(), rawDataIndex); -} - -Declaration* ZTextureAnimation::DeclareVar(const std::string& prefix, const std::string& bodyStr) -{ - std::string auxName = name; - - if (name == "") - auxName = GetDefaultName(prefix); - - Declaration* decl = - parent->AddDeclarationArray(rawDataIndex, GetDeclarationAlignment(), GetRawDataSize(), - GetSourceTypeName(), auxName, entries.size(), bodyStr); - decl->staticConf = staticConf; - return decl; -} - -std::string ZTextureAnimation::GetBodySourceCode() const -{ - std::string bodyStr; - - for (const auto& entry : entries) - { - std::string paramName; - Globals::Instance->GetSegmentedPtrName(entry.paramsPtr, parent, "", paramName); - - bodyStr += StringHelper::Sprintf("\t{ %d, %d, %s },\n", entry.segment, entry.type, - paramName.c_str()); - } - - bodyStr.pop_back(); - - return bodyStr; -} diff --git a/tools/ZAPD/ZAPD/ZTextureAnimation.h b/tools/ZAPD/ZAPD/ZTextureAnimation.h deleted file mode 100644 index 6b03eb7cf4..0000000000 --- a/tools/ZAPD/ZAPD/ZTextureAnimation.h +++ /dev/null @@ -1,151 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -#include "ZResource.h" - -enum class TextureAnimationParamsType -{ - /* 0 */ SingleScroll, - /* 1 */ DualScroll, - /* 2 */ ColorChange, - /* 3 */ ColorChangeLERP, - /* 4 */ ColorChangeLagrange, - /* 5 */ TextureCycle, - /* 6 */ Empty // An empty TextureAnimation has the form 00 00 00 06 00000000 -}; - -class ZTextureAnimationParams : public ZResource -{ -public: - ZTextureAnimationParams(ZFile* parent); - - void ExtractFromBinary(uint32_t nRawDataIndex); - virtual void ExtractFromBinary(uint32_t nRawDataIndex, int count); - - virtual std::string GetDefaultName(const std::string& prefix) const; - ZResourceType GetResourceType() const; - - TextureAnimationParamsType type; -}; - -struct TextureScrollingParamsEntry -{ - int8_t xStep; - int8_t yStep; - uint8_t width; - uint8_t height; -}; - -class TextureScrollingParams : public ZTextureAnimationParams -{ -public: - TextureScrollingParams(ZFile* parent); - - void ParseRawData() override; - void ExtractFromBinary(uint32_t nRawDataIndex, int count) override; - - std::string GetSourceTypeName() const override; - std::string GetDefaultName(const std::string& prefix) const override; - size_t GetRawDataSize() const override; - - Declaration* DeclareVar(const std::string& prefix, const std::string& bodyStr) override; - std::string GetBodySourceCode() const override; - - int count; // 1 for Single, 2 for Dual - TextureScrollingParamsEntry rows[2]; // Too small to make a vector worth it -}; - -struct F3DPrimColor -{ - uint8_t r; - uint8_t g; - uint8_t b; - uint8_t a; - uint8_t lodFrac; -}; - -struct F3DEnvColor -{ - uint8_t r; - uint8_t g; - uint8_t b; - uint8_t a; -}; - -class TextureColorChangingParams : public ZTextureAnimationParams -{ -public: - TextureColorChangingParams(ZFile* parent); - - void ParseRawData() override; - - std::string GetSourceTypeName() const override; - std::string GetDefaultName(const std::string& prefix) const override; - size_t GetRawDataSize() const override; - - void DeclareReferences(const std::string& prefix) override; - - std::string GetBodySourceCode() const override; - - uint16_t animLength; // size of list for type 2 - uint16_t colorListCount; - segptr_t primColorListAddress; - segptr_t envColorListAddress; - segptr_t frameDataListAddress; - std::vector primColorList; - std::vector envColorList; - std::vector frameDataList; -}; - -class TextureCyclingParams : public ZTextureAnimationParams -{ -public: - TextureCyclingParams(ZFile* parent); - - void ParseRawData() override; - - std::string GetSourceTypeName() const override; - std::string GetDefaultName(const std::string& prefix) const override; - size_t GetRawDataSize() const override; - - void DeclareReferences(const std::string& prefix) override; - - std::string GetBodySourceCode() const override; - - uint16_t cycleLength; - segptr_t textureListAddress; - segptr_t textureIndexListAddress; - std::vector textureList; - std::vector textureIndexList; -}; - -struct TextureAnimationEntry -{ - int8_t segment; - TextureAnimationParamsType type; - segptr_t paramsPtr; -}; - -class ZTextureAnimation : public ZResource -{ -public: - ZTextureAnimation(ZFile* nParent); - - void ParseRawData() override; - void DeclareReferences(const std::string& prefix) override; - - std::string GetSourceTypeName() const override; - ZResourceType GetResourceType() const override; - size_t GetRawDataSize() const override; - std::string GetDefaultName(const std::string& prefix) const override; - - Declaration* DeclareVar(const std::string& prefix, const std::string& bodyStr) override; - std::string GetBodySourceCode() const override; - -private: - std::vector entries; -}; diff --git a/tools/ZAPD/ZAPD/ZVector.cpp b/tools/ZAPD/ZAPD/ZVector.cpp deleted file mode 100644 index 607aac86d3..0000000000 --- a/tools/ZAPD/ZAPD/ZVector.cpp +++ /dev/null @@ -1,126 +0,0 @@ -#include "ZVector.h" - -#include - -#include "Globals.h" -#include "Utils/BitConverter.h" -#include "Utils/File.h" -#include "Utils/StringHelper.h" -#include "WarningHandler.h" -#include "ZFile.h" - -REGISTER_ZFILENODE(Vector, ZVector); - -ZVector::ZVector(ZFile* nParent) : ZResource(nParent) -{ - scalarType = ZScalarType::ZSCALAR_NONE; - dimensions = 0; - - RegisterRequiredAttribute("Type"); - RegisterRequiredAttribute("Dimensions"); -} - -void ZVector::ExtractFromBinary(uint32_t nRawDataIndex, ZScalarType nScalarType, - uint32_t nDimensions) -{ - rawDataIndex = nRawDataIndex; - scalarType = nScalarType; - dimensions = nDimensions; - - // Don't parse raw data of external files - if (parent->GetMode() == ZFileMode::ExternalFile) - return; - - ParseRawData(); -} - -void ZVector::ParseXML(tinyxml2::XMLElement* reader) -{ - ZResource::ParseXML(reader); - - this->scalarType = ZScalar::MapOutputTypeToScalarType(registeredAttributes.at("Type").value); - - this->dimensions = StringHelper::StrToL(registeredAttributes.at("Dimensions").value, 16); -} - -void ZVector::ParseRawData() -{ - int32_t currentRawDataIndex = rawDataIndex; - // TODO: this shouldn't be necessary. - scalars.clear(); - scalars.reserve(dimensions); - for (uint32_t i = 0; i < dimensions; i++) - { - ZScalar scalar(parent); - scalar.ExtractFromBinary(currentRawDataIndex, scalarType); - currentRawDataIndex += scalar.GetRawDataSize(); - - scalars.push_back(scalar); - } - - // Ensure the scalars vector has the same number of elements as the vector dimension. - assert(scalars.size() == dimensions); -} - -size_t ZVector::GetRawDataSize() const -{ - size_t size = 0; - - for (size_t i = 0; i < this->scalars.size(); i++) - size += this->scalars[i].GetRawDataSize(); - - return size; -} - -bool ZVector::DoesSupportArray() const -{ - return true; -} - -std::string ZVector::GetSourceTypeName() const -{ - if (dimensions == 3 && scalarType == ZScalarType::ZSCALAR_F32) - return "Vec3f"; - else if (dimensions == 3 && scalarType == ZScalarType::ZSCALAR_S16) - return "Vec3s"; - else if (dimensions == 3 && scalarType == ZScalarType::ZSCALAR_S32) - return "Vec3i"; - else - { - std::string msgHeader = StringHelper::Sprintf( - "encountered unsupported vector type: %d dimensions, %s type", dimensions, - ZScalar::MapScalarTypeToOutputType(scalarType).c_str()); - - HANDLE_ERROR_RESOURCE(WarningType::NotImplemented, parent, this, rawDataIndex, msgHeader, - ""); - } -} - -std::string ZVector::GetBodySourceCode() const -{ - std::string body = ""; - - for (size_t i = 0; i < scalars.size(); i++) - { - body += StringHelper::Sprintf("%6s", scalars[i].GetBodySourceCode().c_str()); - - if (i + 1 < scalars.size()) - body += ", "; - } - - return body; -} - -ZResourceType ZVector::GetResourceType() const -{ - return ZResourceType::Vector; -} - -DeclarationAlignment ZVector::GetDeclarationAlignment() const -{ - if (scalars.size() == 0) - { - return DeclarationAlignment::Align4; - } - return scalars.at(0).GetDeclarationAlignment(); -} diff --git a/tools/ZAPD/ZAPD/ZVector.h b/tools/ZAPD/ZAPD/ZVector.h deleted file mode 100644 index a50d3e8083..0000000000 --- a/tools/ZAPD/ZAPD/ZVector.h +++ /dev/null @@ -1,31 +0,0 @@ -#pragma once - -#include -#include -#include -#include "ZResource.h" -#include "ZScalar.h" -#include "tinyxml2.h" - -class ZVector : public ZResource -{ -public: - std::vector scalars; - ZScalarType scalarType; - uint32_t dimensions; - - ZVector(ZFile* nParent); - - void ExtractFromBinary(uint32_t nRawDataIndex, ZScalarType nScalarType, uint32_t nDimensions); - - void ParseXML(tinyxml2::XMLElement* reader) override; - void ParseRawData() override; - - std::string GetBodySourceCode() const override; - - bool DoesSupportArray() const override; - std::string GetSourceTypeName() const override; - ZResourceType GetResourceType() const override; - size_t GetRawDataSize() const override; - DeclarationAlignment GetDeclarationAlignment() const override; -}; diff --git a/tools/ZAPD/ZAPD/ZVtx.cpp b/tools/ZAPD/ZAPD/ZVtx.cpp deleted file mode 100644 index e4b3d97968..0000000000 --- a/tools/ZAPD/ZAPD/ZVtx.cpp +++ /dev/null @@ -1,86 +0,0 @@ -#include "ZVtx.h" - -#include "Utils/BitConverter.h" -#include "Utils/StringHelper.h" -#include "ZFile.h" - -REGISTER_ZFILENODE(Vtx, ZVtx); - -ZVtx::ZVtx(ZFile* nParent) : ZResource(nParent) -{ - x = 0; - y = 0; - z = 0; - flag = 0; - s = 0; - t = 0; - r = 0; - g = 0; - b = 0; - a = 0; -} - -void ZVtx::ParseRawData() -{ - ZResource::ParseRawData(); - - const auto& rawData = parent->GetRawData(); - x = BitConverter::ToInt16BE(rawData, rawDataIndex + 0); - y = BitConverter::ToInt16BE(rawData, rawDataIndex + 2); - z = BitConverter::ToInt16BE(rawData, rawDataIndex + 4); - flag = BitConverter::ToInt16BE(rawData, rawDataIndex + 6); - s = BitConverter::ToInt16BE(rawData, rawDataIndex + 8); - t = BitConverter::ToInt16BE(rawData, rawDataIndex + 10); - r = rawData[rawDataIndex + 12]; - g = rawData[rawDataIndex + 13]; - b = rawData[rawDataIndex + 14]; - a = rawData[rawDataIndex + 15]; -} - -Declaration* ZVtx::DeclareVar(const std::string& prefix, const std::string& bodyStr) -{ - Declaration* decl = ZResource::DeclareVar(prefix, bodyStr); - decl->isExternal = true; - return decl; -} - -std::string ZVtx::GetBodySourceCode() const -{ - return StringHelper::Sprintf("VTX(%i, %i, %i, %i, %i, %i, %i, %i, %i)", x, y, z, s, t, r, g, b, - a); -} - -size_t ZVtx::GetRawDataSize() const -{ - return 16; -} - -bool ZVtx::DoesSupportArray() const -{ - return true; -} - -ZResourceType ZVtx::GetResourceType() const -{ - return ZResourceType::Vertex; -} - -bool ZVtx::IsExternalResource() const -{ - return true; -} - -std::string ZVtx::GetSourceTypeName() const -{ - return "Vtx"; -} - -std::string ZVtx::GetExternalExtension() const -{ - return "vtx"; -} - -DeclarationAlignment ZVtx::GetDeclarationAlignment() const -{ - return DeclarationAlignment::Align8; -} diff --git a/tools/ZAPD/ZAPD/ZVtx.h b/tools/ZAPD/ZAPD/ZVtx.h deleted file mode 100644 index 511048791d..0000000000 --- a/tools/ZAPD/ZAPD/ZVtx.h +++ /dev/null @@ -1,33 +0,0 @@ -#pragma once - -#include -#include -#include -#include "ZResource.h" -#include "ZScalar.h" -#include "tinyxml2.h" - -class ZVtx : public ZResource -{ -public: - int16_t x, y, z; - uint16_t flag; - int16_t s, t; - uint8_t r, g, b, a; - - ZVtx(ZFile* nParent); - - void ParseRawData() override; - - Declaration* DeclareVar(const std::string& prefix, const std::string& bodyStr) override; - std::string GetBodySourceCode() const override; - - bool IsExternalResource() const override; - bool DoesSupportArray() const override; - std::string GetSourceTypeName() const override; - ZResourceType GetResourceType() const override; - std::string GetExternalExtension() const override; - - size_t GetRawDataSize() const override; - DeclarationAlignment GetDeclarationAlignment() const override; -}; diff --git a/tools/ZAPD/ZAPD/ZWaterbox.cpp b/tools/ZAPD/ZAPD/ZWaterbox.cpp deleted file mode 100644 index 9a289db523..0000000000 --- a/tools/ZAPD/ZAPD/ZWaterbox.cpp +++ /dev/null @@ -1,74 +0,0 @@ -#include "ZWaterbox.h" - -#include "Globals.h" -#include "Utils/BitConverter.h" -#include "Utils/StringHelper.h" - -REGISTER_ZFILENODE(Waterbox, ZWaterbox); - -ZWaterbox::ZWaterbox(ZFile* nParent) : ZResource(nParent) -{ -} - -ZWaterbox::~ZWaterbox() -{ -} - -void ZWaterbox::ParseRawData() -{ - const auto& rawData = parent->GetRawData(); - - xMin = BitConverter::ToInt16BE(rawData, rawDataIndex + 0); - ySurface = BitConverter::ToInt16BE(rawData, rawDataIndex + 2); - zMin = BitConverter::ToInt16BE(rawData, rawDataIndex + 4); - xLength = BitConverter::ToInt16BE(rawData, rawDataIndex + 6); - zLength = BitConverter::ToInt16BE(rawData, rawDataIndex + 8); - - if (Globals::Instance->game == ZGame::OOT_SW97) - properties = BitConverter::ToInt16BE(rawData, rawDataIndex + 10); - else - properties = BitConverter::ToInt32BE(rawData, rawDataIndex + 12); -} - -void ZWaterbox::DeclareReferences(const std::string& prefix) -{ - std::string declaration; - std::string auxName = name; - - if (name == "") - auxName = GetDefaultName(prefix); - - parent->AddDeclaration(rawDataIndex, DeclarationAlignment::Align4, GetRawDataSize(), - GetSourceTypeName(), name.c_str(), GetBodySourceCode()); -} - -std::string ZWaterbox::GetBodySourceCode() const -{ - return StringHelper::Sprintf("%i, %i, %i, %i, %i, 0x%08X", xMin, ySurface, zMin, xLength, - zLength, properties); -} - -std::string ZWaterbox::GetDefaultName(const std::string& prefix) const -{ - return StringHelper::Sprintf("%sWaterBoxes_%06X", prefix.c_str(), rawDataIndex); -} - -ZResourceType ZWaterbox::GetResourceType() const -{ - return ZResourceType::Waterbox; -} - -size_t ZWaterbox::GetRawDataSize() const -{ - return 16; -} - -std::string ZWaterbox::GetSourceTypeName() const -{ - return "WaterBox"; -} - -bool ZWaterbox::DoesSupportArray() const -{ - return true; -} diff --git a/tools/ZAPD/ZAPD/ZWaterbox.h b/tools/ZAPD/ZAPD/ZWaterbox.h deleted file mode 100644 index e190b26a08..0000000000 --- a/tools/ZAPD/ZAPD/ZWaterbox.h +++ /dev/null @@ -1,30 +0,0 @@ -#pragma once - -#include "ZFile.h" -#include "ZResource.h" - -class ZWaterbox : public ZResource -{ -public: - int16_t xMin; - int16_t ySurface; - int16_t zMin; - int16_t xLength; - int16_t zLength; - int32_t properties; - - ZWaterbox(ZFile* nParent); - ~ZWaterbox(); - - void ParseRawData() override; - void DeclareReferences(const std::string& prefix) override; - std::string GetBodySourceCode() const override; - std::string GetDefaultName(const std::string& prefix) const override; - - std::string GetSourceTypeName() const override; - ZResourceType GetResourceType() const override; - - bool DoesSupportArray() const override; - - size_t GetRawDataSize() const override; -}; diff --git a/tools/ZAPD/ZAPD/any/any/zlib.static.txt b/tools/ZAPD/ZAPD/any/any/zlib.static.txt deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/tools/ZAPD/ZAPD/genbuildinfo.py b/tools/ZAPD/ZAPD/genbuildinfo.py deleted file mode 100644 index 3317c42762..0000000000 --- a/tools/ZAPD/ZAPD/genbuildinfo.py +++ /dev/null @@ -1,24 +0,0 @@ -#!/usr/bin/python3 - -import argparse -from datetime import datetime -import getpass -import subprocess - -parser = argparse.ArgumentParser() -parser.add_argument("--devel", action="store_true") -args = parser.parse_args() - -with open("build/ZAPD/BuildInfo.cpp", "w+") as buildFile: - # Get commit hash from git - # If git fails due to a missing .git directory, a default label will be used instead. - try: - label = subprocess.check_output(["git", "describe", "--always"]).strip().decode("utf-8") - except: - label = "GIT_NOT_FOUND" - - now = datetime.now() - if args.devel: - label += " ~ Development version" - buildFile.write("extern const char gBuildHash[] = \"" + label + "\";\n") - #buildFile.write("extern const char gBuildDate[] = \"" + now.strftime("%Y-%m-%d %H:%M:%S") + "\";\n") diff --git a/tools/ZAPD/ZAPD/packages.config b/tools/ZAPD/ZAPD/packages.config deleted file mode 100644 index c387aaed70..0000000000 --- a/tools/ZAPD/ZAPD/packages.config +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - \ No newline at end of file diff --git a/tools/ZAPD/ZAPDUtils/Color3b.h b/tools/ZAPD/ZAPDUtils/Color3b.h deleted file mode 100644 index 507c099f52..0000000000 --- a/tools/ZAPD/ZAPDUtils/Color3b.h +++ /dev/null @@ -1,21 +0,0 @@ -#pragma once - -#include - -struct Color3b -{ - uint8_t r, g, b; - - Color3b() - { - r = 0; - g = 0; - b = 0; - }; - Color3b(uint8_t nR, uint8_t nG, uint8_t nB) - { - r = nR; - g = nG; - b = nB; - }; -}; \ No newline at end of file diff --git a/tools/ZAPD/ZAPDUtils/Makefile b/tools/ZAPD/ZAPDUtils/Makefile deleted file mode 100644 index c0f818bdff..0000000000 --- a/tools/ZAPD/ZAPDUtils/Makefile +++ /dev/null @@ -1,28 +0,0 @@ -# Only used for standalone compilation, usually inherits these from the main makefile -CXXFLAGS ?= -Wall -Wextra -O2 -g -std=c++17 - -SRC_DIRS := $(shell find . -type d -not -path "*build*") -CPP_FILES := $(foreach dir,$(SRC_DIRS),$(wildcard $(dir)/*.cpp)) -H_FILES := $(foreach dir,$(SRC_DIRS),$(wildcard $(dir)/*.h)) - -O_FILES := $(foreach f,$(CPP_FILES:.cpp=.o),build/$f) -LIB := ZAPDUtils.a - -# create build directories -$(shell mkdir -p $(foreach dir,$(SRC_DIRS),build/$(dir))) - -all: $(LIB) - -clean: - rm -rf build $(LIB) - -format: - clang-format-14 -i $(CPP_FILES) $(H_FILES) - -.PHONY: all clean format - -build/%.o: %.cpp - $(CXX) $(CXXFLAGS) $(OPTFLAGS) -c $(OUTPUT_OPTION) $< - -$(LIB): $(O_FILES) - $(AR) rcs $@ $^ diff --git a/tools/ZAPD/ZAPDUtils/StrHash.h b/tools/ZAPD/ZAPDUtils/StrHash.h deleted file mode 100644 index c611bdddad..0000000000 --- a/tools/ZAPD/ZAPDUtils/StrHash.h +++ /dev/null @@ -1,51 +0,0 @@ -#pragma once - -#include -#include -#include - -typedef uint32_t strhash; - -[[maybe_unused]] static strhash CRC32B(unsigned char* message, int32_t size) -{ - int32_t byte = 0, crc = 0; - int32_t mask = 0; - - crc = 0xFFFFFFFF; - - for (int32_t i = 0; i < size; i++) - { - byte = message[i]; - crc = crc ^ byte; - - for (int32_t j = 7; j >= 0; j--) - { - mask = -(crc & 1); - crc = (crc >> 1) ^ (0xEDB88320 & mask); - } - } - - return ~(uint32_t)(crc); -} - -[[maybe_unused]] constexpr static strhash CRC32BCT(const char* message, int32_t size) -{ - int32_t byte = 0, crc = 0; - int32_t mask = 0; - - crc = 0xFFFFFFFF; - - for (int32_t i = 0; i < size; i++) - { - byte = message[i]; - crc = crc ^ byte; - - for (int32_t j = 7; j >= 0; j--) - { - mask = -(crc & 1); - crc = (crc >> 1) ^ (0xEDB88320 & mask); - } - } - - return ~(uint32_t)(crc); -} \ No newline at end of file diff --git a/tools/ZAPD/ZAPDUtils/Utils/BinaryReader.cpp b/tools/ZAPD/ZAPDUtils/Utils/BinaryReader.cpp deleted file mode 100644 index 35412781cc..0000000000 --- a/tools/ZAPD/ZAPDUtils/Utils/BinaryReader.cpp +++ /dev/null @@ -1,148 +0,0 @@ -#include "BinaryReader.h" -#include -#include -#include "Stream.h" - -BinaryReader::BinaryReader(Stream* nStream) -{ - stream.reset(nStream); -} - -void BinaryReader::Close() -{ - stream->Close(); -} - -void BinaryReader::Seek(uint32_t offset, SeekOffsetType seekType) -{ - stream->Seek(offset, seekType); -} - -uint32_t BinaryReader::GetBaseAddress() -{ - return stream->GetBaseAddress(); -} - -void BinaryReader::Read([[maybe_unused]] char* buffer, int32_t length) -{ - stream->Read(length); -} - -char BinaryReader::ReadChar() -{ - return (char)stream->ReadByte(); -} - -int8_t BinaryReader::ReadByte() -{ - return stream->ReadByte(); -} - -uint8_t BinaryReader::ReadUByte() -{ - return (uint8_t)stream->ReadByte(); -} - -int16_t BinaryReader::ReadInt16() -{ - int16_t result = 0; - - stream->Read((char*)&result, sizeof(int16_t)); - return result; -} - -int32_t BinaryReader::ReadInt32() -{ - int32_t result = 0; - - stream->Read((char*)&result, sizeof(int32_t)); - return result; -} - -uint16_t BinaryReader::ReadUInt16() -{ - uint16_t result = 0; - - stream->Read((char*)&result, sizeof(uint16_t)); - return result; -} - -uint32_t BinaryReader::ReadUInt32() -{ - uint32_t result = 0; - - stream->Read((char*)&result, sizeof(uint32_t)); - return result; -} - -uint64_t BinaryReader::ReadUInt64() -{ - uint64_t result = 0; - - stream->Read((char*)&result, sizeof(uint64_t)); - return result; -} - -float BinaryReader::ReadSingle() -{ - float result = NAN; - - stream->Read((char*)&result, sizeof(float)); - - if (std::isnan(result)) - throw std::runtime_error("BinaryReader::ReadSingle(): Error reading stream"); - - return result; -} - -double BinaryReader::ReadDouble() -{ - double result = NAN; - - stream->Read((char*)&result, sizeof(double)); - if (std::isnan(result)) - throw std::runtime_error("BinaryReader::ReadDouble(): Error reading stream"); - - return result; -} - -Vec3f BinaryReader::ReadVec3f() -{ - return Vec3f(); -} - -Vec3s BinaryReader::ReadVec3s() -{ - return Vec3s(0, 0, 0); -} - -Vec3s BinaryReader::ReadVec3b() -{ - return Vec3s(0, 0, 0); -} - -Vec2f BinaryReader::ReadVec2f() -{ - return Vec2f(); -} - -Color3b BinaryReader::ReadColor3b() -{ - return Color3b(); -} - -std::string BinaryReader::ReadString() -{ - std::string res; - char c; - - do - { - c = ReadChar(); - - if (c != 0) - res += c; - } while (c != 0); - - return res; -} \ No newline at end of file diff --git a/tools/ZAPD/ZAPDUtils/Utils/BinaryReader.h b/tools/ZAPD/ZAPDUtils/Utils/BinaryReader.h deleted file mode 100644 index cf0eeb42c9..0000000000 --- a/tools/ZAPD/ZAPDUtils/Utils/BinaryReader.h +++ /dev/null @@ -1,43 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include "../Color3b.h" -#include "../Vec2f.h" -#include "../Vec3f.h" -#include "../Vec3s.h" -#include "Stream.h" - -class BinaryReader -{ -public: - BinaryReader(Stream* nStream); - - void Close(); - - void Seek(uint32_t offset, SeekOffsetType seekType); - uint32_t GetBaseAddress(); - - void Read(char* buffer, int32_t length); - char ReadChar(); - int8_t ReadByte(); - int16_t ReadInt16(); - int32_t ReadInt32(); - uint8_t ReadUByte(); - uint16_t ReadUInt16(); - uint32_t ReadUInt32(); - uint64_t ReadUInt64(); - float ReadSingle(); - double ReadDouble(); - Vec3f ReadVec3f(); - Vec3s ReadVec3s(); - Vec3s ReadVec3b(); - Vec2f ReadVec2f(); - Color3b ReadColor3b(); - std::string ReadString(); - -protected: - std::shared_ptr stream; -}; \ No newline at end of file diff --git a/tools/ZAPD/ZAPDUtils/Utils/BinaryWriter.cpp b/tools/ZAPD/ZAPDUtils/Utils/BinaryWriter.cpp deleted file mode 100644 index 87bc0ac684..0000000000 --- a/tools/ZAPD/ZAPDUtils/Utils/BinaryWriter.cpp +++ /dev/null @@ -1,95 +0,0 @@ -#include "BinaryWriter.h" - -BinaryWriter::BinaryWriter(Stream* nStream) -{ - stream.reset(nStream); -} - -BinaryWriter::BinaryWriter(std::shared_ptr nStream) -{ - stream = nStream; -} - -void BinaryWriter::Close() -{ - stream->Close(); -} - -std::shared_ptr BinaryWriter::GetStream() -{ - return stream; -} - -uint64_t BinaryWriter::GetBaseAddress() -{ - return stream->GetBaseAddress(); -} - -uint64_t BinaryWriter::GetLength() -{ - return stream->GetLength(); -} - -void BinaryWriter::Seek(int32_t offset, SeekOffsetType seekType) -{ - stream->Seek(offset, seekType); -} - -void BinaryWriter::Write(int8_t value) -{ - stream->Write((char*)&value, sizeof(int8_t)); -} - -void BinaryWriter::Write(uint8_t value) -{ - stream->Write((char*)&value, sizeof(uint8_t)); -} - -void BinaryWriter::Write(int16_t value) -{ - stream->Write((char*)&value, sizeof(int16_t)); -} - -void BinaryWriter::Write(uint16_t value) -{ - stream->Write((char*)&value, sizeof(uint16_t)); -} - -void BinaryWriter::Write(int32_t value) -{ - stream->Write((char*)&value, sizeof(int32_t)); -} - -void BinaryWriter::Write(uint32_t value) -{ - stream->Write((char*)&value, sizeof(uint32_t)); -} - -void BinaryWriter::Write(int64_t value) -{ - stream->Write((char*)&value, sizeof(int64_t)); -} - -void BinaryWriter::Write(uint64_t value) -{ - stream->Write((char*)&value, sizeof(uint64_t)); -} - -void BinaryWriter::Write(float value) -{ - stream->Write((char*)&value, sizeof(float)); -} - -void BinaryWriter::Write(double value) -{ - stream->Write((char*)&value, sizeof(double)); -} - -void BinaryWriter::Write(const std::string& str) -{ - int strLen = str.size(); - stream->Write((char*)&strLen, sizeof(int)); - - for (char c : str) - stream->WriteByte(c); -} diff --git a/tools/ZAPD/ZAPDUtils/Utils/BinaryWriter.h b/tools/ZAPD/ZAPDUtils/Utils/BinaryWriter.h deleted file mode 100644 index e224d182e3..0000000000 --- a/tools/ZAPD/ZAPDUtils/Utils/BinaryWriter.h +++ /dev/null @@ -1,35 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include "Stream.h" - -class BinaryWriter -{ -public: - BinaryWriter(Stream* nStream); - BinaryWriter(std::shared_ptr nStream); - - std::shared_ptr GetStream(); - uint64_t GetBaseAddress(); - uint64_t GetLength(); - void Seek(int32_t offset, SeekOffsetType seekType); - void Close(); - - void Write(int8_t value); - void Write(uint8_t value); - void Write(int16_t value); - void Write(uint16_t value); - void Write(int32_t value); - void Write(uint32_t value); - void Write(int64_t value); - void Write(uint64_t value); - void Write(float value); - void Write(double value); - void Write(const std::string& str); - -protected: - std::shared_ptr stream; -}; \ No newline at end of file diff --git a/tools/ZAPD/ZAPDUtils/Utils/BitConverter.h b/tools/ZAPD/ZAPDUtils/Utils/BitConverter.h deleted file mode 100644 index aa41b5b217..0000000000 --- a/tools/ZAPD/ZAPDUtils/Utils/BitConverter.h +++ /dev/null @@ -1,166 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include - -#define ALIGN8(val) (((val) + 7) & ~7) -#define ALIGN16(val) (((val) + 0xF) & ~0xF) -#define ALIGN64(val) (((val) + 0x3F) & ~0x3F) - -#ifdef _MSC_VER -#define __PRETTY_FUNCTION__ __FUNCSIG__ -#endif - -class BitConverter -{ -public: - static inline int8_t ToInt8BE(const std::vector& data, size_t offset) - { - if (offset + 0 > data.size()) - { - fprintf(stderr, "%s\n", __PRETTY_FUNCTION__); - fprintf(stderr, "Error: Trying a out-of-bounds reading from a data buffer\n"); - fprintf(stderr, "\t Buffer size: 0x%zX\n", data.size()); - fprintf(stderr, "\t Trying to read at offset: 0x%zX\n", offset); - } - return (int8_t)data.at(offset + 0); - } - - static inline uint8_t ToUInt8BE(const std::vector& data, size_t offset) - { - if (offset + 0 > data.size()) - { - fprintf(stderr, "%s\n", __PRETTY_FUNCTION__); - fprintf(stderr, "Error: Trying an out-of-bounds reading from a data buffer\n"); - fprintf(stderr, "\t Buffer size: 0x%zX\n", data.size()); - fprintf(stderr, "\t Trying to read at offset: 0x%zX\n", offset); - } - return (uint8_t)data.at(offset + 0); - } - - static inline int16_t ToInt16BE(const std::vector& data, size_t offset) - { - if (offset + 1 > data.size()) - { - fprintf(stderr, "%s\n", __PRETTY_FUNCTION__); - fprintf(stderr, "Error: Trying a out-of-bounds reading from a data buffer\n"); - fprintf(stderr, "\t Buffer size: 0x%zX\n", data.size()); - fprintf(stderr, "\t Trying to read at offset: 0x%zX\n", offset); - } - return ((uint16_t)data.at(offset + 0) << 8) + (uint16_t)data.at(offset + 1); - } - - static inline uint16_t ToUInt16BE(const std::vector& data, size_t offset) - { - if (offset + 1 > data.size()) - { - fprintf(stderr, "%s\n", __PRETTY_FUNCTION__); - fprintf(stderr, "Error: Trying a out-of-bounds reading from a data buffer\n"); - fprintf(stderr, "\t Buffer size: 0x%zX\n", data.size()); - fprintf(stderr, "\t Trying to read at offset: 0x%zX\n", offset); - } - return ((uint16_t)data.at(offset + 0) << 8) + (uint16_t)data.at(offset + 1); - } - - static inline int32_t ToInt32BE(const std::vector& data, size_t offset) - { - if (offset + 3 > data.size()) - { - fprintf(stderr, "%s\n", __PRETTY_FUNCTION__); - fprintf(stderr, "Error: Trying a out-of-bounds reading from a data buffer\n"); - fprintf(stderr, "\t Buffer size: 0x%zX\n", data.size()); - fprintf(stderr, "\t Trying to read at offset: 0x%zX\n", offset); - } - return ((uint32_t)data.at(offset + 0) << 24) + ((uint32_t)data.at(offset + 1) << 16) + - ((uint32_t)data.at(offset + 2) << 8) + (uint32_t)data.at(offset + 3); - } - - static inline uint32_t ToUInt32BE(const std::vector& data, size_t offset) - { - if (offset + 3 > data.size()) - { - fprintf(stderr, "%s\n", __PRETTY_FUNCTION__); - fprintf(stderr, "Error: Trying a out-of-bounds reading from a data buffer\n"); - fprintf(stderr, "\t Buffer size: 0x%zX\n", data.size()); - fprintf(stderr, "\t Trying to read at offset: 0x%zX\n", offset); - } - return ((uint32_t)data.at(offset + 0) << 24) + ((uint32_t)data.at(offset + 1) << 16) + - ((uint32_t)data.at(offset + 2) << 8) + (uint32_t)data.at(offset + 3); - } - - static inline int64_t ToInt64BE(const std::vector& data, size_t offset) - { - if (offset + 7 > data.size()) - { - fprintf(stderr, "%s\n", __PRETTY_FUNCTION__); - fprintf(stderr, "Error: Trying a out-of-bounds reading from a data buffer\n"); - fprintf(stderr, "\t Buffer size: 0x%zX\n", data.size()); - fprintf(stderr, "\t Trying to read at offset: 0x%zX\n", offset); - } - return ((uint64_t)data.at(offset + 0) << 56) + ((uint64_t)data.at(offset + 1) << 48) + - ((uint64_t)data.at(offset + 2) << 40) + ((uint64_t)data.at(offset + 3) << 32) + - ((uint64_t)data.at(offset + 4) << 24) + ((uint64_t)data.at(offset + 5) << 16) + - ((uint64_t)data.at(offset + 6) << 8) + ((uint64_t)data.at(offset + 7)); - } - - static inline uint64_t ToUInt64BE(const std::vector& data, size_t offset) - { - if (offset + 7 > data.size()) - { - fprintf(stderr, "%s\n", __PRETTY_FUNCTION__); - fprintf(stderr, "Error: Trying a out-of-bounds reading from a data buffer\n"); - fprintf(stderr, "\t Buffer size: 0x%zX\n", data.size()); - fprintf(stderr, "\t Trying to read at offset: 0x%zX\n", offset); - } - return ((uint64_t)data.at(offset + 0) << 56) + ((uint64_t)data.at(offset + 1) << 48) + - ((uint64_t)data.at(offset + 2) << 40) + ((uint64_t)data.at(offset + 3) << 32) + - ((uint64_t)data.at(offset + 4) << 24) + ((uint64_t)data.at(offset + 5) << 16) + - ((uint64_t)data.at(offset + 6) << 8) + ((uint64_t)data.at(offset + 7)); - } - - static inline float ToFloatBE(const std::vector& data, size_t offset) - { - if (offset + 3 > data.size()) - { - fprintf(stderr, "%s\n", __PRETTY_FUNCTION__); - fprintf(stderr, "Error: Trying a out-of-bounds reading from a data buffer\n"); - fprintf(stderr, "\t Buffer size: 0x%zX\n", data.size()); - fprintf(stderr, "\t Trying to read at offset: 0x%zX\n", offset); - } - float value; - uint32_t floatData = ((uint32_t)data.at(offset + 0) << 24) + - ((uint32_t)data.at(offset + 1) << 16) + - ((uint32_t)data.at(offset + 2) << 8) + (uint32_t)data.at(offset + 3); - static_assert(sizeof(uint32_t) == sizeof(float), "expected 32-bit float"); - std::memcpy(&value, &floatData, sizeof(value)); - return value; - } - - static inline double ToDoubleBE(const std::vector& data, size_t offset) - { - if (offset + 7 > data.size()) - { - fprintf(stderr, "%s\n", __PRETTY_FUNCTION__); - fprintf(stderr, "Error: Trying a out-of-bounds reading from a data buffer\n"); - fprintf(stderr, "\t Buffer size: 0x%zX\n", data.size()); - fprintf(stderr, "\t Trying to read at offset: 0x%zX\n", offset); - } - double value; - uint64_t floatData = - ((uint64_t)data.at(offset + 0) << 56) + ((uint64_t)data.at(offset + 1) << 48) + - ((uint64_t)data.at(offset + 2) << 40) + ((uint64_t)data.at(offset + 3) << 32) + - ((uint64_t)data.at(offset + 4) << 24) + ((uint64_t)data.at(offset + 5) << 16) + - ((uint64_t)data.at(offset + 6) << 8) + ((uint64_t)data.at(offset + 7)); - static_assert(sizeof(uint64_t) == sizeof(double), "expected 64-bit double"); - // Checks if the float format on the platform the ZAPD binary is running on supports the - // same float format as the object file. - static_assert(std::numeric_limits::is_iec559, - "expected IEC559 doubles on host machine"); - std::memcpy(&value, &floatData, sizeof(value)); - return value; - } -}; diff --git a/tools/ZAPD/ZAPDUtils/Utils/Directory.h b/tools/ZAPD/ZAPDUtils/Utils/Directory.h deleted file mode 100644 index d150f17727..0000000000 --- a/tools/ZAPD/ZAPDUtils/Utils/Directory.h +++ /dev/null @@ -1,55 +0,0 @@ -#pragma once - -#include -#include -#include - -#ifdef USE_BOOST_FS -#include -namespace fs = boost::filesystem; -#elif __has_include() -#include -namespace fs = std::filesystem; -#else -#include -namespace fs = std::experimental::filesystem; -#endif - -#include "StringHelper.h" - -class Directory -{ -public: -#ifdef USE_BOOST_FS - static std::string GetCurrentDirectory() - { - return fs::current_path().string(); - } -#else - static std::string GetCurrentDirectory() - { - return fs::current_path().u8string(); - } -#endif - - static bool Exists(const fs::path& path) - { - return fs::exists(path); - } - - static void CreateDirectory(const std::string& path) - { - std::string curPath; - std::vector split = StringHelper::Split(path, "/"); - - for (std::string s : split) - { - curPath += s + "/"; - - if (!Exists(curPath)) - fs::create_directory(curPath); - } - - // fs::create_directory(path); - } -}; diff --git a/tools/ZAPD/ZAPDUtils/Utils/File.h b/tools/ZAPD/ZAPDUtils/Utils/File.h deleted file mode 100644 index 707b1600fc..0000000000 --- a/tools/ZAPD/ZAPDUtils/Utils/File.h +++ /dev/null @@ -1,97 +0,0 @@ -#pragma once - -#ifdef USE_BOOST_FS -#include -#else -#include -#endif - -#include -#include -#include "Directory.h" -#include "Utils/StringHelper.h" - -class File -{ -#ifdef USE_BOOST_FS - typedef fs::ifstream ifstream; - typedef fs::ofstream ofstream; -#else - typedef std::ifstream ifstream; - typedef std::ofstream ofstream; -#endif - -public: - static bool Exists(const fs::path& filePath) - { - ifstream file(filePath, std::ios::in | std::ios::binary | std::ios::ate); - return file.good(); - } - - static std::vector ReadAllBytes(const fs::path& filePath) - { - ifstream file(filePath, std::ios::in | std::ios::binary | std::ios::ate); - int32_t fileSize = (int32_t)file.tellg(); - file.seekg(0); - char* data = new char[fileSize]; - file.read(data, fileSize); - std::vector result = std::vector(data, data + fileSize); - delete[] data; - file.close(); - - return result; - }; - - static std::string ReadAllText(const fs::path& filePath) - { - ifstream file(filePath, std::ios::in | std::ios::binary | std::ios::ate); - if (!file.is_open()) - return ""; - int32_t fileSize = (int32_t)file.tellg(); - file.seekg(0); - char* data = new char[fileSize + 1]; - memset(data, 0, fileSize + 1); - file.read(data, fileSize); - std::string str = std::string((const char*)data); - delete[] data; - file.close(); - - return str; - }; - - static std::vector ReadAllLines(const fs::path& filePath) - { - std::string text = ReadAllText(filePath); - std::vector lines = StringHelper::Split(text, "\n"); - - return lines; - }; - - static void WriteAllBytes(const fs::path& filePath, const std::vector& data) - { - ofstream file(filePath, std::ios::binary); - file.write((char*)data.data(), data.size()); - file.close(); - }; - - static void WriteAllBytes(const std::string& filePath, const std::vector& data) - { - ofstream file(filePath, std::ios::binary); - file.write((char*)data.data(), data.size()); - file.close(); - }; - - static void WriteAllBytes(const std::string& filePath, const char* data, int dataSize) - { - ofstream file(filePath, std::ios::binary); - file.write((char*)data, dataSize); - file.close(); - }; - - static void WriteAllText(const fs::path& filePath, const std::string& text) - { - ofstream file(filePath, std::ios::out); - file.write(text.c_str(), text.size()); - file.close(); - } -}; diff --git a/tools/ZAPD/ZAPDUtils/Utils/MemoryStream.cpp b/tools/ZAPD/ZAPDUtils/Utils/MemoryStream.cpp deleted file mode 100644 index 6e85c59a04..0000000000 --- a/tools/ZAPD/ZAPDUtils/Utils/MemoryStream.cpp +++ /dev/null @@ -1,96 +0,0 @@ -#include "MemoryStream.h" -#include - -#ifndef _MSC_VER -#define memcpy_s(dest, destSize, source, sourceSize) memcpy(dest, source, destSize) -#endif - -MemoryStream::MemoryStream() -{ - buffer = std::vector(); - bufferSize = 0; - baseAddress = 0; -} - -MemoryStream::MemoryStream(char* nBuffer, size_t nBufferSize) : MemoryStream() -{ - buffer = std::vector(nBuffer, nBuffer + nBufferSize); - bufferSize = nBufferSize; - baseAddress = 0; -} - -MemoryStream::~MemoryStream() -{ -} - -uint64_t MemoryStream::GetLength() -{ - return buffer.size(); -} - -void MemoryStream::Seek(int32_t offset, SeekOffsetType seekType) -{ - if (seekType == SeekOffsetType::Start) - baseAddress = offset; - else if (seekType == SeekOffsetType::Current) - baseAddress += offset; - else if (seekType == SeekOffsetType::End) - baseAddress = bufferSize - 1 - offset; -} - -std::unique_ptr MemoryStream::Read(size_t length) -{ - std::unique_ptr result = std::make_unique(length); - - memcpy_s(result.get(), length, &buffer[baseAddress], length); - baseAddress += length; - - return result; -} - -void MemoryStream::Read(const char* dest, size_t length) -{ - memcpy_s((void*)dest, length, &buffer[baseAddress], length); - baseAddress += length; -} - -int8_t MemoryStream::ReadByte() -{ - return buffer[baseAddress++]; -} - -void MemoryStream::Write(char* srcBuffer, size_t length) -{ - if (baseAddress + length >= buffer.size()) - { - buffer.resize(baseAddress + length); - bufferSize += length; - } - - memcpy_s(&buffer[baseAddress], length, srcBuffer, length); - baseAddress += length; -} - -void MemoryStream::WriteByte(int8_t value) -{ - if (baseAddress >= buffer.size()) - { - buffer.resize(baseAddress + 1); - bufferSize = baseAddress; - } - - buffer[baseAddress++] = value; -} - -std::vector MemoryStream::ToVector() -{ - return buffer; -} - -void MemoryStream::Flush() -{ -} - -void MemoryStream::Close() -{ -} \ No newline at end of file diff --git a/tools/ZAPD/ZAPDUtils/Utils/MemoryStream.h b/tools/ZAPD/ZAPDUtils/Utils/MemoryStream.h deleted file mode 100644 index 5a17bb0c36..0000000000 --- a/tools/ZAPD/ZAPDUtils/Utils/MemoryStream.h +++ /dev/null @@ -1,33 +0,0 @@ -#pragma once - -#include -#include -#include "Stream.h" - -class MemoryStream : public Stream -{ -public: - MemoryStream(); - MemoryStream(char* nBuffer, size_t nBufferSize); - ~MemoryStream(); - - uint64_t GetLength() override; - - void Seek(int32_t offset, SeekOffsetType seekType) override; - - std::unique_ptr Read(size_t length) override; - void Read(const char* dest, size_t length) override; - int8_t ReadByte() override; - - void Write(char* srcBuffer, size_t length) override; - void WriteByte(int8_t value) override; - - std::vector ToVector(); - - void Flush() override; - void Close() override; - -protected: - std::vector buffer; - std::size_t bufferSize; -}; \ No newline at end of file diff --git a/tools/ZAPD/ZAPDUtils/Utils/Path.h b/tools/ZAPD/ZAPDUtils/Utils/Path.h deleted file mode 100644 index 90f55380b4..0000000000 --- a/tools/ZAPD/ZAPDUtils/Utils/Path.h +++ /dev/null @@ -1,53 +0,0 @@ -#pragma once - -#include -#include -#include "Utils/StringHelper.h" - -#ifdef USE_BOOST_FS -#include -namespace fs = boost::filesystem; -#elif __has_include() -#include -namespace fs = std::filesystem; -#else -#include -namespace fs = std::experimental::filesystem; -#endif - -class Path -{ -public: - static std::string GetFileName(const fs::path& input) - { - // https://en.cppreference.com/w/cpp/filesystem/path/filename - return input.filename().string(); - }; - - static std::string GetFileNameWithoutExtension(const fs::path& input) - { - // https://en.cppreference.com/w/cpp/filesystem/path/stem - return input.stem().string(); - }; - - static std::string GetFileNameExtension(const std::string& input) - { - return input.substr(input.find_last_of("."), input.length()); - }; - - static fs::path GetPath(const std::string& input) - { - std::vector split = StringHelper::Split(input, "/"); - fs::path output; - - for (std::string str : split) - { - if (str.find_last_of(".") == std::string::npos) - output /= str; - } - - return output; - }; - - static fs::path GetDirectoryName(const fs::path& path) { return path.parent_path(); }; -}; diff --git a/tools/ZAPD/ZAPDUtils/Utils/Stream.h b/tools/ZAPD/ZAPDUtils/Utils/Stream.h deleted file mode 100644 index e73a9a70d0..0000000000 --- a/tools/ZAPD/ZAPDUtils/Utils/Stream.h +++ /dev/null @@ -1,41 +0,0 @@ -#pragma once - -#include -#include - -enum class SeekOffsetType -{ - Start, - Current, - End -}; - -// TODO: Eventually account for endianess in binaryreader and binarywriter -enum class Endianess -{ - Little = 0, - Big = 1, -}; - -class Stream -{ -public: - virtual ~Stream() = default; - virtual uint64_t GetLength() = 0; - uint64_t GetBaseAddress() { return baseAddress; } - - virtual void Seek(int32_t offset, SeekOffsetType seekType) = 0; - - virtual std::unique_ptr Read(size_t length) = 0; - virtual void Read(const char* dest, size_t length) = 0; - virtual int8_t ReadByte() = 0; - - virtual void Write(char* destBuffer, size_t length) = 0; - virtual void WriteByte(int8_t value) = 0; - - virtual void Flush() = 0; - virtual void Close() = 0; - -protected: - uint64_t baseAddress; -}; \ No newline at end of file diff --git a/tools/ZAPD/ZAPDUtils/Utils/StringHelper.h b/tools/ZAPD/ZAPDUtils/Utils/StringHelper.h deleted file mode 100644 index 942d0bcc9e..0000000000 --- a/tools/ZAPD/ZAPDUtils/Utils/StringHelper.h +++ /dev/null @@ -1,229 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include - -class StringHelper -{ -public: - static std::vector Split(std::string s, const std::string& delimiter) - { - std::vector result; - - size_t pos = 0; - std::string token; - - while ((pos = s.find(delimiter)) != std::string::npos) - { - token = s.substr(0, pos); - result.push_back(token); - s.erase(0, pos + delimiter.length()); - } - - if (s.length() != 0) - result.push_back(s); - - return result; - } - - static std::string Join(const std::vector parts, const std::string& delimiter) - { - std::string result; - - for (size_t i = 0; i < parts.size(); i++) - { - result += parts[i]; - - if (i != parts.size() - 1) - result += delimiter; - } - - return result; - } - - static std::string Strip(std::string s, const std::string& delimiter) - { - size_t pos = 0; - std::string token; - - while ((pos = s.find(delimiter)) != std::string::npos) - { - token = s.substr(0, pos); - s.erase(pos, pos + delimiter.length()); - } - - return s; - } - - static std::string Replace(std::string str, const std::string& from, const std::string& to) - { - size_t start_pos = str.find(from); - - if (start_pos == std::string::npos) - return str; - - str.replace(start_pos, from.length(), to); - return str; - } - - static bool StartsWith(const std::string& s, const std::string& input) - { - return s.rfind(input, 0) == 0; - } - - static bool Contains(const std::string& s, const std::string& input) - { - return s.find(input) != std::string::npos; - } - - static bool EndsWith(const std::string& s, const std::string& input) - { - size_t inputLen = strlen(input.c_str()); - return s.rfind(input) == (s.size() - inputLen); - } - - static std::string Sprintf(const char* format, ...) - { - char buffer[32768]; - // char buffer[2048]; - std::string output; - va_list va; - - va_start(va, format); - vsprintf(buffer, format, va); - va_end(va); - - output = buffer; - return output; - } - - static std::string Implode(std::vector& elements, const char* const separator) - { - return std::accumulate(std::begin(elements), std::end(elements), std::string(), - [separator](std::string& ss, std::string& s) { - return ss.empty() ? s : ss + separator + s; - }); - } - - static int64_t StrToL(const std::string& str, int32_t base = 10) - { - return std::strtoull(str.c_str(), nullptr, base); - } - - static std::string BoolStr(bool b) { return b ? "true" : "false"; } - - static bool HasOnlyDigits(const std::string& str) - { - return std::all_of(str.begin(), str.end(), ::isdigit); - } - - static bool IsValidHex(std::string_view str) - { - if (str.length() < 3) - { - return false; - } - - if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X')) - { - return std::all_of(str.begin() + 2, str.end(), ::isxdigit); - } - - return false; - } - - static bool IsValidOffset(std::string_view str) - { - if (str.length() == 1) - { - // 0 is a valid offset - return isdigit(str[0]); - } - - return IsValidHex(str); - } - - static bool IsValidHex(const std::string& str) - { - return IsValidHex(std::string_view(str.c_str())); - } - - static std::string ToUpper(const std::string& str) - { - std::string buff = str; - std::transform(buff.begin(), buff.end(), buff.begin(), ::toupper); - return buff; - } - - static bool IEquals(const std::string& a, const std::string& b) - { - return std::equal(a.begin(), a.end(), b.begin(), b.end(), - [](char a, char b) { return tolower(a) == tolower(b); }); - } - - /** - * Converts a std::string formatted in camelCase into one in SCREAMING_SNAKE_CASE. Since this - * will mostly be used on symbols that start with either 'g' or 's', an option is included to - * skip these. - */ - static std::string camelCaseTo_SCREAMING_SNAKE_CASE(const std::string& in, bool skipSP) - { - std::string out = ""; - const char* ptr = in.c_str(); - char ch = *ptr; - - // Switch checks for 'g'/'s'/'\0', looks at next character if skipSP enabled and string is - // nonempty. - switch (ch) - { - case 'g': - case 's': - if (skipSP) - { - // Print it anyway if the next character is lowercase, e.g. "gameplay_keep_...". - if (!isupper(ptr[1])) - { - out.push_back(toupper(ch)); - } - if ((ch = *++ptr) == '\0') - { - case '\0': - // This is reached either by the if or the case label, avoiding duplication. - return out; - } - } - [[fallthrough]]; - default: - if (islower(ch)) - { - out.push_back(toupper(ch)); - } - else - { - out.push_back(ch); - } - break; - } - - while ((ch = *++ptr) != '\0') - { - if (islower(ch)) - { - out.push_back(toupper(ch)); - } - else - { - if (isupper(ch) && !(isupper(ptr[1]) && isupper(ptr[-1]))) - { - out.push_back('_'); - } - out.push_back(ch); - } - } - return out; - } -}; diff --git a/tools/ZAPD/ZAPDUtils/Utils/vt.h b/tools/ZAPD/ZAPDUtils/Utils/vt.h deleted file mode 100644 index 23f424442b..0000000000 --- a/tools/ZAPD/ZAPDUtils/Utils/vt.h +++ /dev/null @@ -1,45 +0,0 @@ -#ifndef VT_H -#define VT_H - -// clang-format off -#define VT_COLOR_BLACK 0 -#define VT_COLOR_RED 1 -#define VT_COLOR_GREEN 2 -#define VT_COLOR_YELLOW 3 -#define VT_COLOR_BLUE 4 -#define VT_COLOR_PURPLE 5 -#define VT_COLOR_CYAN 6 -#define VT_COLOR_WHITE 7 -#define VT_COLOR_LIGHTGRAY 8 -#define VT_COLOR_DARKGRAY 9 - -#define VT_COLOR_FOREGROUND 3 -#define VT_COLOR_BACKGROUND 4 -// clang-format on - -#define VT_COLOR_EXPAND0(type, color) #type #color -#define VT_COLOR_EXPAND1(type, color) VT_COLOR_EXPAND0(type, color) -#define VT_COLOR(type, color) VT_COLOR_EXPAND1(VT_COLOR_##type, VT_COLOR_##color) - -#define VT_ESC "\x1b" -#define VT_CSI "[" -#define VT_CUP(x, y) VT_ESC VT_CSI y ";" x "H" -#define VT_ED(n) VT_ESC VT_CSI #n "J" -#define VT_SGR(n) VT_ESC VT_CSI n "m" - -// Add more macros if necessary -#define VT_COL(back, fore) VT_SGR(VT_COLOR(BACKGROUND, back) ";" VT_COLOR(FOREGROUND, fore)) -#define VT_FGCOL(color) VT_SGR(VT_COLOR(FOREGROUND, color)) -#define VT_BGCOL(color) VT_SGR(VT_COLOR(BACKGROUND, color)) - -// Bold -#define VT_BOLD "1" - -// Bold color support -#define VT_BOLD_FGCOL(color) VT_SGR(VT_BOLD ";" VT_COLOR(FOREGROUND, color)) -#define VT_BOLD_BGCOL(color) VT_SGR(VT_BOLD ";" VT_COLOR(BACKGROUND, color)) - -#define VT_RST VT_SGR("") -#define VT_CLS VT_ED(2) - -#endif diff --git a/tools/ZAPD/ZAPDUtils/Vec2f.h b/tools/ZAPD/ZAPDUtils/Vec2f.h deleted file mode 100644 index 73e9259a89..0000000000 --- a/tools/ZAPD/ZAPDUtils/Vec2f.h +++ /dev/null @@ -1,19 +0,0 @@ -#pragma once - -#include - -struct Vec2f -{ - float x, y; - - Vec2f() - { - x = 0; - y = 0; - }; - Vec2f(float nX, float nY) - { - x = nX; - y = nY; - }; -}; \ No newline at end of file diff --git a/tools/ZAPD/ZAPDUtils/Vec3f.h b/tools/ZAPD/ZAPDUtils/Vec3f.h deleted file mode 100644 index d6e9c5568f..0000000000 --- a/tools/ZAPD/ZAPDUtils/Vec3f.h +++ /dev/null @@ -1,21 +0,0 @@ -#pragma once - -#include - -struct Vec3f -{ - float x, y, z; - - Vec3f() - { - x = 0; - y = 0; - z = 0; - }; - Vec3f(float nX, float nY, float nZ) - { - x = nX; - y = nY; - z = nZ; - }; -}; \ No newline at end of file diff --git a/tools/ZAPD/ZAPDUtils/Vec3s.h b/tools/ZAPD/ZAPDUtils/Vec3s.h deleted file mode 100644 index 05816eddb5..0000000000 --- a/tools/ZAPD/ZAPDUtils/Vec3s.h +++ /dev/null @@ -1,21 +0,0 @@ -#pragma once - -#include - -struct Vec3s -{ - int16_t x, y, z; - - Vec3s() - { - x = 0; - y = 0; - z = 0; - }; - Vec3s(int16_t nX, int16_t nY, int16_t nZ) - { - x = nX; - y = nY; - z = nZ; - }; -}; \ No newline at end of file diff --git a/tools/ZAPD/ZAPDUtils/ZAPDUtils.vcxproj b/tools/ZAPD/ZAPDUtils/ZAPDUtils.vcxproj deleted file mode 100644 index 2abbdc9664..0000000000 --- a/tools/ZAPD/ZAPDUtils/ZAPDUtils.vcxproj +++ /dev/null @@ -1,169 +0,0 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - 16.0 - Win32Proj - {a2e01c3e-d647-45d1-9788-043debc1a908} - ZAPDUtils - 10.0 - - - - Application - true - v142 - Unicode - - - Application - false - v143 - true - Unicode - - - StaticLibrary - true - v142 - MultiByte - - - Application - false - v143 - true - Unicode - - - - - - - - - - - - - - - - - - - - - true - - - false - - - true - - - false - - - - Level3 - true - WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) - true - - - Console - true - - - - - Level3 - true - true - true - WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) - true - - - Console - true - true - true - - - - - Level3 - true - _DEBUG;_CONSOLE;%(PreprocessorDefinitions) - true - MultiThreadedDebug - Default - stdcpp17 - - - Console - true - - - - - Level3 - true - true - true - NDEBUG;_CONSOLE;%(PreprocessorDefinitions) - true - - - Console - true - true - true - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/tools/ZAPD/ZAPDUtils/ZAPDUtils.vcxproj.filters b/tools/ZAPD/ZAPDUtils/ZAPDUtils.vcxproj.filters deleted file mode 100644 index 4765ad5d45..0000000000 --- a/tools/ZAPD/ZAPDUtils/ZAPDUtils.vcxproj.filters +++ /dev/null @@ -1,84 +0,0 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms - - - {d8c2c1e7-b065-4b0f-86a2-46ab46eedc0b} - - - {e047919d-7186-49ca-b115-e48fbb5c8743} - - - {3de9dd46-0dfd-4d48-9f20-9f24e5b80fe0} - - - - - Header Files\Utils - - - Header Files\Utils - - - Header Files\Utils - - - Header Files\Utils - - - Header Files\Utils - - - Header Files\Utils - - - Header Files\Utils - - - Header Files\Utils - - - Header Files - - - Header Files\Utils - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - - - Source Files\Utils - - - Source Files\Utils - - - Source Files\Utils - - - Source Files\Libraries - - - \ No newline at end of file diff --git a/tools/ZAPD/copycheck.py b/tools/ZAPD/copycheck.py deleted file mode 100755 index 36288f6853..0000000000 --- a/tools/ZAPD/copycheck.py +++ /dev/null @@ -1,9 +0,0 @@ -#!/usr/bin/env python3 - -import os -from shutil import copyfile - -if (os.environ.get('ZAPD_COPYDIR') != None): - print("Copying ZAPD.out to repo...") - #print(os.environ.get('ZAPD_COPYDIR')) - copyfile("ZAPD.out", os.environ.get('ZAPD_COPYDIR') + "/ZAPD.out") diff --git a/tools/ZAPD/docs/zapd_extraction_xml_reference.md b/tools/ZAPD/docs/zapd_extraction_xml_reference.md deleted file mode 100644 index edbdf857f1..0000000000 --- a/tools/ZAPD/docs/zapd_extraction_xml_reference.md +++ /dev/null @@ -1,680 +0,0 @@ -# ZAPD extraction XML reference - -This document aims to be a small reference of how to create a compatible xml file for ZAPD. - -## Table of contents - -- [ZAPD extraction XML reference](#zapd-extraction-xml-reference) - - [Table of contents](#table-of-contents) - - [Basic XML](#basic-xml) - - [Resources types](#resources-types) - - [File](#file) - - [ExternalFile](#externalfile) - - [Texture](#texture) - - [Background](#background) - - [Blob](#blob) - - [DList](#dlist) - - [TextureAnimation](#textureanimation) - - [Scene and Room](#scene-and-room) - - [AltHeader](#altheader) - - [Animation](#animation) - - [PlayerAnimation](#playeranimation) - - [CurveAnimation](#curveanimation) - - [LegacyAnimation](#legacyanimation) - - [Skeleton](#skeleton) - - [LimbTable](#limbtable) - - [Limb](#limb) - - [Symbol](#symbol) - - [Collision](#collision) - - [Scalar](#scalar) - - [Vector](#vector) - - [Vtx](#vtx) - - [Mtx](#mtx) - - [Cutscene](#cutscene) - - [Array](#array) - - [Path](#path) - - [PlayerAnimationData](#playeranimationdata) - - [Pointer](#pointer) - -## Basic XML - -An example of an object xml: - -```xml - - - - - - - - - - - - - - - - - - - -``` - -Every xml must have a `` tag. It must have at least one `` child. - -## Resources types - -The following is a list of the resources/tags supported by ZAPD, and the attributes needed by each one. - -For most resources inside a `` tag **you should also set an `Offset` attribute**. This is the offset (within the file) of the resource you are exporting. The `Offset` attribute is expected to be in hexadecimal, for example `Offset="0x41F0"`. - -It's worth noting that every tag expects a `Name="gNameOfTheAsset"`. This is will be the name of the extracted variable in the output C code. Every asset must be prefixed with `g` and the suffix should represent the type of the variable. - -Every tag can accept a `Static` attribute to specify if the asset should be marked as `static` or not. -There are 3 valid values (defaults to `Global`): - -- `Global`: Mark static if the flag `--static` was used. -- `On`: Override the global config and **always mark** as `static`. -- `Off`: Override the global config and **don't mark** as `static`. - -This table summarizes if the asset will be marked `static` (✅) or not (❌) -| `Static=""` attribute in XML | Without `--static` flag | With `--static` flag | -| ---------------------------- | ----------------------- | -------------------- | -| `On` | ✅ | ✅ | -| `Global` (default) | ❌ | ✅ | -| `Off` | ❌ | ❌ | - -------------------------- - -### File - -- Example of this tag: - -```xml - -``` - -- Attributes: - - - `Name`: Required. The name of the file in `baserom/` which will be extracted. - - `OutName`: Optional. The output name of the generated C source file. Defaults to the value passed to `Name`. - - `Segment`: Optional. This is the segment number of the current file. Expects a decimal number between 0 and 15 inclusive, usually 6 if it is an object. If not specified, the file will use VRAM instead of segmented addresses. - - `BaseAddress`: Optional. RAM address of the file. Expects a hex number (with `0x` prefix). Default value: `0`. - - `RangeStart`: Optional. File offset where the extraction will begin. Hex. Default value: `0x000000000`. - - `RangeEnd`: Optional. File offset where the extraction will end. Hex. Default value: `0xFFFFFFFF`. - - `Game`: Optional. Valid values: `OOT`, `MM`, `SW97` and `OOTSW97`. Default value: `OOT`. - -------------------------- - -### ExternalFile - -Allows ZAPD to map segmented addresses to variables declared in other files by using its XML. - -It is useful for objects that use variables from `gameplay_keep`, `gameplay_dangeon_keep`, `gameplay_field_keep`, etc. - -This tag can be used in the global `config.xml` file. - -- Example of this tag: - -```xml - -``` - -- Attributes: - - - `XmlPath`: Required. The path of the XML, relative to the value set by `ExternalXMLFolder` in the configuration file. - - `OutPath`: Required. The path were the header for the corresponding external file is. It is used to `#include` it in the generated `.c` file. - -------------------------- - -### Texture - -Textures are extracted as `.png` files. - -- Example: - -```xml - -``` - -Will be defined as: - -```c -u64 gCraterSmokeConeTex[] = { -#include "assets/objects/object_spot17_obj/crater_smoke_cone.ia8.inc.c" -}; -``` - -- Attributes: - - - `Name`: Required. Suffixed by `Tex`, unless it is a palette, in that case it is suffixed by `TLUT`. - - `OutName`: Required. The filename of the extracted `.png` file. - - `Format`: Required. The format of the image. Valid values: `rgba32`, `rgba16`, `i4`, `i8`, `ia4`, `ia8`, `ia16`, `ci4` and `ci8`. - - `Width`: Required. Width in pixels of the image. - - `Height`: Required. Height in pixels of the image. - - `TlutOffset`: Optional. Specifies the tlut's offset used by this texture. This attribute is only valid if `Format` is either `ci4` or `ci8`, otherwise an exception would be thrown. - - `ExternalTlut`: Optional. Specifies that the texture's tlut is in a different file. Takes the filename of the file that contains the tlut. - - `ExternalTlutOffset`: Optional. Specifies the offset in the `ExternalTlut` of the tlut for the given texture. - - `SplitTlut`: Optional. Specifies that the given texture should take from the upper half of the tlut. Takes a bool, i.e. one of `true`, `false`, `1`, `0`. - -The following is a list of the texture formats the Nintendo 64 supports, with their gfxdis names and ZAPD format names. - -| Format name | Typing in `gsDPLoadTextureBlock` | "Format" in xml | -| ----------------------------------------------- | -------------------------------- | --------------- | -| 4-bit intensity (I) | `G_IM_FMT_I, G_IM_SIZ_4b` | `i4` | -| 4-bit intensity with alpha (I/A) (3/1) | `G_IM_FMT_IA, G_IM_SIZ_4b` | `ia4` | -| 4-bit color index (CI) | `G_IM_FMT_CI, G_IM_SIZ_4b` | `ci4` | -| 8-bit I | `G_IM_FMT_I, G_IM_SIZ_8b` | `i8` | -| 8-bit IA (4/4) | `G_IM_FMT_IA, G_IM_SIZ_8b` | `ia8` | -| 8-bit CI | `G_IM_FMT_CI, G_IM_SIZ_8b` | `ci8` | -| 16-bit red, green, blue, alpha (RGBA) (5/5/5/1) | `G_IM_FMT_RGBA, G_IM_SIZ_16b` | `rgba16` | -| 16-bit IA (8/8) | `G_IM_FMT_IA, G_IM_SIZ_16b` | `ia16` | -| 16-bit YUV (Luminance, Blue-Y, Red-Y) | `G_IM_FMT_YUV, G_IM_SIZ_16b` | (not used) | -| 32-bit RGBA (8/8/8/8) | `G_IM_FMT_RGBA, G_IM_SIZ_32b` | `rgba32` | - -If you want to know more about this formats, you can check [`gsDPLoadTextureBlock`](http://n64devkit.square7.ch/n64man/gdp/gDPLoadTextureBlock.htm) for most formats, or [`gDPLoadTextureBlock_4b`](http://n64devkit.square7.ch/n64man/gdp/gDPLoadTextureBlock_4b.htm) for the 4-bit formats. - -------------------------- - -### Background - -- Example: - -```xml - -``` - -- Attributes: - - - `Name`: Required. Suffixed by `Background`. - - `OutName`: Required. The filename of the extracted `.jpg` file. - -※ Explicit use of this tag isn't often necesary because it would probably be extracted automatically by another extracted element. You can use this to name them if you don't like the autogenerated name. - -------------------------- - -### Blob - -Blob are binary data that will be extracted as `.bin` files. - -- Example: - -```xml - -``` - -Will be defined as: - -```c - -u8 gFireTempleBlob_00CCC0[] = { -#include "assets/objects/object_hidan_objects/gFireTempleBlob_00CCC0.bin.inc.c" -}; -``` - -- Attributes: - - - `Name`: Required. Suffixed by `Blob`. - - `Size`: Required. Amount of bytes to extract. Hex. - -※ We usually use blobs when we can't figure out the content's type of chunk of data. - -------------------------- - -### DList - -A.k.a. Display list, or Gfx. - -- Example: - -```xml - -``` - -- Attributes: - - - `Name`: Required. Suffixed by `DL`. - -------------------------- - -### TextureAnimation - -A data type exclusive to Majora's Mask, that has scrolling, color changing, and texture changing capabilities. Declaring the main array will generate everything else; textures for the TextureCycle type must be declared manually in the XML to use symbols. (If it does reference any undeclared textures, ZAPD will warn and give the their offsets.) - -```xml - -``` - -- Attributes: - - - `Name`: Required. Suffixed by `TexAnim`. - -------------------------- - -### Scene and Room - -`Scene`s and `Room`s are a bit special, because `Room`s usually needs assets declared in their respective `Scene` (which is in a different file), so they need to be extracted together. - -To accomplish this, the scene and each of their rooms must be declared in the same XML. - -- Example: - -```xml - - - - - - - - - - - - - - -``` - -- Attributes: - - - `HackMode`: Optional. This is a simple non-hardcoded way to handle some edge cases. Valid values: `syotes_room`. - -------------------------- - -### AltHeader - -Like `Scene`s and `Room`s, `AltHeader`s is special too. It should always be declared in the same `File` as a `Scene` or a `Room`. - -- Example: - -```xml - - - - - - - - - - - - - - -``` - -- Attributes: - - - `Name`: Required. Suffixed by `AltHeader`. - -------------------------- - -### Animation - -- Example: - -```xml - -``` - -- Attributes: - - - `Name`: Required. Suffixed by `Anim`. - -------------------------- - -### PlayerAnimation - -- Example: - -```xml - -``` - -- Attributes: - - - `Name`: Required. Suffixed by `Anim`. - -------------------------- - -### CurveAnimation - -- Example: - -```xml - -``` - -- Attributes: - - - `Name`: Required. Suffixed by `Anim`. - - `SkelOffset`: Required. Offset of the `CurveSkeleton` (I.e. a [`Skeleton`](#skeleton) resource with `Type="Curve"`) related to this animation. - -------------------------- - -### LegacyAnimation - -Useful only for the unused `object_human`'s animation data. - -- Example: - -```xml - -``` - -- Attributes: - - - `Name`: Required. Suffixed by `Anim`. - -------------------------- - -### Skeleton - -- Example: - -```xml - -``` - -- Attributes: - - - `Name`: Required. Suffixed by `Skel`. - - `Type`: Required. Valid values: `Normal`, `Flex` and `Curve`. - - `LimbType`: Required. Valid values: `Standard`, `LOD`, `Skin`, `Curve` and `Legacy`. - - `EnumName`: Optional. The name of `typedef`'d limb enum. - - `LimbNone`: Optional. The name of the limb with index zero in the limb enum. - - `LimbMax`: Optional. The name of the max limb index in the limb enum. - -ZAPD is able to generate a limb enum by itself only if all the required data is provided. Providing some but not all the required data would trigger an error and the execution will halt. - -The required data is providing the `EnumName`, `LimbNone` and `LimbMax` attributes in the `Skeleton` or `LimbTable` node and the `EnumName` attribute in every `Limb` of this skeleton. - -※ There are no restrictions in the `Type` and `LimbType` attributes besides the valid values, so any skeleton type can be combined with any limb type. - -------------------------- - -### LimbTable - -- Example: - -```xml - -``` - -- Attributes: - - - `Name`: Required. Suffixed by `Skel`. - - `LimbType`: Required. Valid values: `Standard`, `LOD`, `Skin`, `Curve` and `Legacy`. - - `Count`: Required. Amount of limbs. Integer. - - `EnumName`: Optional. The name of `typedef`'d limb enum. - - `LimbNone`: Optional. The name of the limb with index zero in the limb enum. - - `LimbMax`: Optional. The name of the max limb index in the limb enum. - -See [Skeleton](#skeleton) for info on the limb enum generation. - -------------------------- - -### Limb - -- Example: - -```xml - -``` - -- Attributes: - - - `Name`: Required. Suffixed by `Limb`. - - `LimbType`: Required. Valid values: `Standard`, `LOD`, `Skin`, `Curve` and `Legacy`. - - `EnumName`: Optional. The name used for this limb in the limbs enum. It must be either present in every limb or in none. - -See [Skeleton](#skeleton) for info on the limb enum generation. - -------------------------- - -### Symbol - -A special element that allows declaring a variable without actually extracting it from the current file. Useful when a resource references an element from another file. The symbol will be declared as `extern`. - -- Example: - -```xml - -``` - -Will be declared as: - -```c -extern u8 gJsjutanShadowTex[2048]; -``` - -- Attributes: - - - `Type`: The type of the declared variable. If missing, it will default to `void*`. - - `TypeSize`: The size in bytes of the type. If missing, it will default to `4` (the size of a word and a pointer). Integer or hex value. - - `Count`: Optional. If it is present, the variable will be declared as an array instead of a plain variable. The value of this attribute specifies the length of the array. If `Count` is present but it has no value (`Count=""`), then the length of the array will not be specified either in the declared variable. Integer or hex value. - - `Static`: This attribute can't be enabled on a Symbol node. A warning will be showed in this case. - -------------------------- - -### Collision - -- Example: - -```xml - -``` - -- Attributes: - - - `Name`: Required. Suffixed by `Col`. - -------------------------- - -### Scalar - -Allows the extraction of a single number. - -- Example: - -```xml - -``` - -Will be extracted as: - -```c -u64 pad34F8 = { 0 }; -``` - -- Attributes: - - - `Name`: Required. Suffixed by ~~`TBD`~~. - - `Type`: Required. Valid values: `s8`, `u8`, `x8`, `s16`, `u16`, `x16`, `s32`, `u32`, `x32`, `s64`, `u64`, `x64`, `f32` and `f64`. - -※ Can be wrapped in an [`Array`](#array) tag. - -------------------------- - -### Vector - -Extracts a vector. - -Current supported types are `Vec3s`, `Vec3i` or `Vec3f`. - -- Example: - -```xml - - - -``` - -Will be extracted as: - -```c -Vec3s D_04002040[24] = { - { -37, 2346, 93 }, - { 0, 11995, 0 }, - { -16385, -305, -16333 }, - { 0, 51, 12 }, - { 3761, 2263, -384 }, - { 0, 0, 3786 }, - { 1594, 1384, -18344 }, - { -2288, -2428, -1562 }, - { 0, 0, 3219 }, - { -2148, -5, -16840 }, - { 15365, -1708, 15611 }, - { 1761, 8365, 17711 }, - { 0, 0, 18859 }, - { 0, 0, 0 }, - { -9392, -9579, 28686 }, - { 0, 0, -7093 }, - { -2748, 685, -14092 }, - { 213, 6553, -32212 }, - { 0, 0, -1877 }, - { 3267, 3309, -16090 }, - { -18101, 25946, -2670 }, - { -104, 0, 0 }, - { 0, 0, 0 }, - { 0, 0, 0 } -}; -``` - -- Attributes: - - - `Name`: Required. Suffixed by ~~`TBD`~~. - - `Type`: Required. Specifies the vector's type (`Vec3s`, `Vec3i` and `Vec3f`). Valid values: `s16`, `s32` and `f32`. - - `Dimensions`: Required. The amount of dimensions of the vector. Valid values: `3`. - -※ Can be wrapped in an [`Array`](#array) tag. - -------------------------- - -### Vtx - -- Example: - -```xml - - - -``` - -- Attributes: - - - `Name`: Required. Suffixed by `Vtx`. - -※ Can be wrapped in an [`Array`](#array) tag. - -------------------------- - -### Mtx - -- Example: - -```xml - -``` - -- Attributes: - - - `Name`: Required. Suffixed by `Mtx`. - -※ Explicit use of this tag isn't often necesary because it would probably be extracted automatically by another extracted element. - -------------------------- - -### Cutscene - -- Example: - -```xml - -``` - -- Attributes: - - - `Name`: Required. Suffixed by `Cs`. - -※ Explicit use of this tag isn't often necesary because it would probably be extracted automatically by another extracted element. - -------------------------- - -### Array - -The `Array` element is special, because it needs an inner element to work. It will declare an array of its inner element. - -Currently, only [`Pointer`](#pointer), [`Scalar`](#scalar), [`Vector`](#vector) and [`Vtx`](#vtx) support being wrapped in an array. - -- Example: - -```xml - - - -``` - -- Attributes: - - - `Name`: Required. How the variable will be named. By our convention it should be prefixed by `g`. The sufix is mandated by the element contained. - - `Count`: Required. Amount of elements. Integer. - -------------------------- - -### Path - -- Example: - -```xml - -``` - -- Attributes: - - - `Name`: Required. Suffixed by `Path`. - - `NumPaths`: Optional. The amount of paths contained in the array. It must be a positive integer. - -------------------------- - -### PlayerAnimationData - -Allows the extraction of the specific data of the player animations which are found in the `link_animetion` file. - -- Example: - -```xml - -``` - -- Attributes: - - - `Name`: Required. Suffixed by `AnimData`. - - `FrameCount`: Required. The length of the animation in frames. It must be a positive integer. - -------------------------- - -### Pointer - -Allows the extraction of a variable that contains a pointer - -- Example: - -```xml - - - -``` - -- Attributes: - - - `Name`: Required. - - `Type`: Required. The type of the extracted pointer. - -※ Can be wrapped in an [`Array`](#array) tag. - -------------------------- diff --git a/tools/ZAPD/docs/zapd_warning_example.png b/tools/ZAPD/docs/zapd_warning_example.png deleted file mode 100644 index a001c64d6a..0000000000 Binary files a/tools/ZAPD/docs/zapd_warning_example.png and /dev/null differ diff --git a/tools/ZAPD/docs/zapd_xml_spec.md b/tools/ZAPD/docs/zapd_xml_spec.md deleted file mode 100644 index 9fcc0d4aab..0000000000 --- a/tools/ZAPD/docs/zapd_xml_spec.md +++ /dev/null @@ -1,55 +0,0 @@ -# ZAPD XML specification - -ZAPD XMLs use a restrictive subset of the XML standard: any ZAPD XML must be a valid XML (All elements starting with `` ending appropriately with ``, single "empty-element" tags with `/` at the end, etc.). - -Reminder that in - -```xml - - - - - - - - - -``` - -``, ``, `` are *children* of ``, but `` is not. `` is a *descendent* of `` and a child of ``. - -- Every XML's outermost element start/end tag is a single ``. -- The children of a `` must be ``s. -- A `` has *resources* as children. A resource is almost always single empty-element tag, and has one of the types - - `` - - `` - - `` - - `` - - `` - - `` - - `` - - `` - - `` - - `` - - `` - - `` - - `` - - `` - - `` - - `` - - `` - - `` - - `` - - `` - - `` - - `` - - `` - - `` - - `` - -- A `` cannot descend from a ``. -- All resources must be children of a ``. -- `` is the only paired resource tag enclosing an element; the element must be a single resource tag, one of - - `` - - `` - - `` diff --git a/tools/ZAPD/lib/libgfxd/.gitrepo b/tools/ZAPD/lib/libgfxd/.gitrepo deleted file mode 100644 index 4c8b7fe768..0000000000 --- a/tools/ZAPD/lib/libgfxd/.gitrepo +++ /dev/null @@ -1,12 +0,0 @@ -; DO NOT EDIT (unless you know what you are doing) -; -; This subdirectory is a git "subrepo", and this file is maintained by the -; git-subrepo command. See https://github.com/git-commands/git-subrepo#readme -; -[subrepo] - remote = git@github.com:glankk/libgfxd.git - branch = master - commit = 008f73dca8ebc9151b205959b17773a19c5bd0da - parent = c92cfda733aa740a53129a21f69c8abb08a465c7 - method = merge - cmdver = 0.4.3 diff --git a/tools/ZAPD/lib/libgfxd/LICENSE b/tools/ZAPD/lib/libgfxd/LICENSE deleted file mode 100644 index a7655f829d..0000000000 --- a/tools/ZAPD/lib/libgfxd/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2016-2021 glank (glankk@github.com) - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/tools/ZAPD/lib/libgfxd/Makefile b/tools/ZAPD/lib/libgfxd/Makefile deleted file mode 100644 index b340ff5c0a..0000000000 --- a/tools/ZAPD/lib/libgfxd/Makefile +++ /dev/null @@ -1,25 +0,0 @@ -CFLAGS = -Wall -O2 -g -UC_OBJ = uc_f3d.o uc_f3db.o uc_f3dex.o uc_f3dexb.o uc_f3dex2.o -OBJ = gfxd.o $(UC_OBJ) -LIB = libgfxd.a - -CPPFLAGS-$(MT) += -DCONFIG_MT -CPPFLAGS += $(CPPFLAGS-y) - -.PHONY: all -all: $(LIB) - -.PHONY: clean -clean: - rm -f $(OBJ) $(LIB) - -.INTERMEDIATE: $(OBJ) - -$(OBJ): gbi.h gfxd.h priv.h -$(UC_OBJ): uc.c uc_argfn.c uc_argtbl.c uc_macrofn.c uc_macrotbl.c - -$(LIB): $(OBJ) - $(AR) rcs $@ $^ - -%.o: %.c - $(COMPILE.c) $(OUTPUT_OPTION) $< diff --git a/tools/ZAPD/lib/libgfxd/README.md b/tools/ZAPD/lib/libgfxd/README.md deleted file mode 100644 index 2e82589439..0000000000 --- a/tools/ZAPD/lib/libgfxd/README.md +++ /dev/null @@ -1,478 +0,0 @@ -## Installing -Run `make` for a single-threaded build, or `make MT=y` for a multi-threaded -build. Copy `libgfxd.a` to your lib directory, and `gfxd.h` to your include -directory. - -## Example usage -Example source code: -``` -#include -#include - -static int macro_fn(void) -{ - /* Print a tab before each macro, and a comma and newline after each - macro */ - gfxd_puts("\t"); - gfxd_macro_dflt(); /* Execute the default macro handler */ - gfxd_puts(",\n"); - - return 0; -} - -int main() -{ - /* Read from stdin and write to stdout */ - gfxd_input_fd(fileno(stdin)); - gfxd_output_fd(fileno(stdout)); - - /* Override the default macro handler to make the output prettier */ - gfxd_macro_fn(macro_fn); - - /* Select F3DEX as the target microcode */ - gfxd_target(gfxd_f3dex); - - /* Set the input endianness to big endian, and the word size to 4 */ - gfxd_endian(gfxd_endian_big, 4); - - /* Print an opening brace */ - gfxd_puts("{\n"); - - /* Execute until the end of input, or until encountering an invalid - command */ - gfxd_execute(); - - /* Print a closing brace */ - gfxd_puts("}\n"); -} -``` - -Example input (binary): -``` -0xe7000000, 0x00000000, -0xfc127e03, 0xfffffdf8, -0xb900031d, 0xc8112078, -0xb6000000, 0x000e0000, -0xb7000000, 0x00012000, -0xfa000000, 0xffffffff, -0x040030bf, 0x000002e0, -0xb1000204, 0x00020604, -0xb1080a0c, 0x000a0e0c, -0xb10a1012, 0x000a120e, -0xb1140200, 0x00140016, -0xb8000000, 0x00000000, -``` - -Example output: -``` -{ - gsDPPipeSync(), - gsDPSetCombineLERP(TEXEL0, 0, SHADE, 0, 0, 0, 0, 1, COMBINED, 0, PRIMITIVE, 0, 0, 0, 0, COMBINED), - gsDPSetRenderMode(G_RM_FOG_SHADE_A, G_RM_AA_ZB_OPA_SURF2), - gsSPClearGeometryMode(G_LIGHTING | G_TEXTURE_GEN | G_TEXTURE_GEN_LINEAR), - gsSPSetGeometryMode(G_CULL_BACK | G_FOG), - gsDPSetPrimColor(0, 0, 0xFF, 0xFF, 0xFF, 0xFF), - gsSPVertex(0x000002E0, 12, 0), - gsSP2Triangles(0, 1, 2, 0, 1, 3, 2, 0), - gsSP2Triangles(4, 5, 6, 0, 5, 7, 6, 0), - gsSP1Quadrangle(5, 8, 9, 7, 0), - gsSP1Quadrangle(10, 1, 0, 11, 0), - gsSPEndDisplayList(), -} -``` - -## Input/output methods -The input consists of any number of `Gfx` packets, and the output is the -decompiled macros in plain-text. The endianness and microcode type of the input -can be set using `gfxd_endian` and `gfxd_target`. - -Several methods of doing I/O are available. No method is selected by default, -meaning there will be no input, and any output will be discarded. - ---- - -##### `void gfxd_input_buffer(const void *buf, int size)` -##### `void gfxd_output_buffer(char *buf, int size)` -Use the buffer pointed to by `buf`, of `size` bytes. - ---- - -##### `void gfxd_input_fd(int fd)` -##### `void gfxd_output_fd(int fd)` -Use `read()` / `write()` with the provided file descriptor, `fd`. - ---- - -##### `typedef int gfxd_input_fn_t(void *buf, int count)` -##### `typedef int gfxd_output_fn_t(const char *buf, int count)` -##### `void gfxd_input_callback(gfxd_input_fn_t *fn)` -##### `void gfxd_output_callback(gfxd_output_fn_t *fn)` -Use the provided callback function, `fn`. `fn` should copy at most `count` -bytes to/from `buf`, and return the number of bytes actually copied. The input -callback should return 0 to signal end of input. - -## Handlers -The macro handler function is responsible for writing the output of each -decompiled macro. The default macro handler is `gfxd_macro_dflt`, but this can -be changed with `gfxd_macro_fn`. The new handler can extend the default -function by calling `gfxd_macro_dflt` within it, or it can override it -completely. - ---- - -##### `int gfxd_macro_dflt()` -The default macro handler. Outputs the macro name, dynamic display list pointer -if one has been specified, and then each argument in order using the function -registered using `gfxd_arg_fn` (`gfxd_arg_dflt` by default), and returns zero. -Because it is designed to be extended, it only outputs the macro text, without -any whitespace or punctuation before or after. When this function is used as -the sole macro handler, it will output the entire display list on one line -without any separation between macros, which is probably not what you want. - ---- - -##### `void gfxd_macro_fn(gfxd_macro_fn_t *fn)` -Set `fn` to be the macro handler function. `fn` can be null, in which case the -handler is reset to the default. - ---- - -##### `void gfxd_arg_dflt(int arg_num)` -The default argument handler for `gfxd_macro_dflt`. For the argument with index -`arg_num`, calls `gfxd_arg_callbacks`, and prints the argument value if the -callback returns zero, or if there is no callback for the given argument. - ---- - -##### `void gfxd_arg_fn(gfxd_arg_fn_t *fn)` -Set `fn` to be the argument handler function, called by `gfxd_macro_dflt`, -for each argument in the current macro, not counting the dynamic display list -pointer if one has been specified. `fn` can be null, in which case the handler -is reset to the default. This only affects the output of `gfxd_macro_dflt`, and -has no observable effect if `gfxd_macro_dflt` is overridden (not extended). - -## Argument callbacks -Callbacks can be registered that will be executed when an argument of a certain -type is encountered. The default argument handler `gfxd_arg_dflt` will execute -callbacks as needed using `gfxd_arg_callbacks`. If a callback returns non-zero, -`gfxd_arg_dflt` will not output anything. This is to allow callbacks to -override the default argument output. Otherwise, `gfxd_arg_dflt` will output -the argument value after the callback function's output. - ---- - -##### `int gfxd_arg_callbacks(int arg_num)` -Examines the argument with index `arg_num` and executes the callback function -for that argument type, if such a callback is supported and has been -registered. This function returns the value that was returned by the callback -function. If no callback function has been registered for the argument type, -zero is returned. - -Most argument callbacks have some extra parameters containing information that -might be relevant to the argument that triggered the callback. The extra -information is extracted only from the current macro, as gfxd does not retain -any context information from previous or subsequent macros. If any of the extra -parameter values is not available in the current macro, the value for that -parameter is substituted with `-1` for signed parameters, and zero for unsigned -parameters. - ---- - -##### `typedef int gfxd_tlut_fn_t(uint32_t tlut, int32_t idx, int32_t count)` -##### `void gfxd_tlut_callback(gfxd_tlut_fn_t *fn)` -Set the callback function for palette arguments. The argument type is -`gfxd_Tlut`. The palette index is in `idx` and the number of colors in `count`. - ---- - -##### `typedef int gfxd_timg_fn_t(uint32_t timg, int32_t fmt, int32_t siz, int32_t width, int32_t height, int32_t pal)` -##### `void gfxd_timg_callback(gfxd_timg_fn_t *fn)` -Set the callback function for texture arguments. The argument type is -`gfxd_Timg`. The image format is in `fmt` and `siz`, the dimensions in `width` -and `height`, and the palette index in `pal`. - ---- - -##### `typedef int gfxd_cimg_fn_t(uint32_t cimg, int32_t fmt, int32_t siz, int32_t width)` -##### `void gfxd_cimg_callback(gfxd_cimg_fn_t *fn)` -Set the callback function for frame buffer arguments. The argument type is -`gfxd_Cimg`. The image format is in `fmt` and `siz`, and the horizontal -resolution in `width`. - ---- - -##### `typedef int gfxd_zimg_fn_t(uint32_t zimg)` -##### `void gfxd_zimg_callback(gfxd_zimg_fn_t *fn)` -Set the callback function for depth buffer arguments. The argument type is -`gfxd_Zimg`. - ---- - -##### `typedef int gfxd_dl_fn_t(uint32_t dl)` -##### `void gfxd_dl_callback(gfxd_dl_fn_t *fn)` -Set the callback function for display list arguments. The argument type is -`gfxd_Dl`. - ---- - -##### `typedef int gfxd_mtx_fn_t(uint32_t mtx)` -##### `void gfxd_mtx_callback(gfxd_mtx_fn_t *fn)` -Set the callback function for matrix arguments. The argument type is -`gfxd_Mtxptr`. - ---- - -##### `typedef int gfxd_lookat_fn_t(uint32_t lookat, int32_t count)` -##### `void gfxd_lookat_callback(gfxd_lookat_fn_t *fn)` -Set the callback function for lookat array arguments. The argument type is -`gfxd_Lookatptr`. The number of lookat structures (1 or 2) is in `count`. - ---- - -##### `typedef int gfxd_light_fn_t(uint32_t light, int32_t count)` -##### `void gfxd_light_callback(gfxd_light_fn_t *fn)` -Set the callback function for light array arguments. The argument type is -`gfxd_Lightptr`. The number of light structures is in `count`. - ---- - -##### `typedef int gfxd_seg_fn_t(uint32_t seg, int32_t num)` -##### `void gfxd_seg_callback(gfxd_seg_fn_t *fn)` -Set the callback function for segment base arguments. The argument type is -`gfxd_Segptr`. The segment number is in `num`. - ---- - -##### `typedef int gfxd_vtx_fn_t(uint32_t vtx, int32_t num)` -##### `void gfxd_vtx_callback(gfxd_vtx_fn_t *fn)` -Set the callback function for vertex array arguments. The argument type is -`gfxd_Vtxptr`. The number of vertex structures is in `num`. - ---- - -##### `typedef int gfxd_vp_fn_t(uint32_t vp)` -##### `void gfxd_vp_callback(gfxd_vp_fn_t *fn)` -Set the callback function for viewport arguments. The argument type is -`gfxd_Vp`. - ---- - -##### `typedef int gfxd_uctext_fn_t(uint32_t text, uint32_t size)` -##### `void gfxd_uctext_callback(gfxd_uctext_fn_t *fn)` -Set the callback function for microcode text arguments. The argument type is -`gfxd_Uctext`. The size of the text segment is in `size`. - ---- - -##### `typedef int gfxd_ucdata_fn_t(uint32_t data, uint32_t size)` -##### `void gfxd_ucdata_callback(gfxd_ucdata_fn_t *fn)` -Set the callback function for microcode data arguments. The argument type is -`gfxd_Ucdata`. The size of the data segment is in `size`. - ---- - -##### `typedef int gfxd_dram_fn_t(uint32_t dram, uint32_t size)` -##### `void gfxd_dram_callback(gfxd_dram_fn_t *fn)` -Set the callback function for generic pointer arguments. The argument type is -`gfxd_Dram`. The size of the data is in `size`. - -## General settings -These functions control general input and output settings. - ---- - -##### `void gfxd_target(gfxd_ucode_t ucode)` -Select `ucode` as the target microcode. `ucode` can be `gfxd_f3d`, `gfxd_f3db`, -`gfxd_f3dex`, `gfxd_f3dexb`, or `gfxd_f3dex2`. The microcode must be selected -before `gfxd_execute`, as no microcode is selected by default. - ---- - -##### `void gfxd_endian(int endian, int wordsize)` -Select `endian` as the endianness of the input, and `wordsize` as the size of -each word in number of bytes. `endian` can be `gfxd_endian_big`, -`gfxd_endian_little`, or `gfxd_endian_host` (the endianness of the host -machine). `wordsize` can be 1, 2, 4, or 8. Big endian is selected by default, -with a word size of 4. - ---- - -##### `void gfxd_dynamic(const char *arg)` -Enable or disable the use of dynamic `g` macros instead of static `gs` macros, -and select the dynamic display list pointer argument to be used. `arg` will be -used by `gfxd_macro_dflt` as the first argument to dynamic macros. If `arg` is -null, dynamic macros are disabled, and `gs` macros are used. Also affects the -result of `gfxd_macro_name`, as it will return either the dynamic or static -version of the macro name as selected by this setting. - ---- - -##### `void gfxd_enable(int cap)` -##### `void gfxd_disable(int cap)` -Enable or disable the feature specified by `cap`. Can be one of the following; -- `gfxd_stop_on_invalid`: Stop execution when encountering an invalid macro. -Enabled by default. -- `gfxd_stop_on_end`: Stop execution when encountering a `SPBranchList` or -`SPEndDisplayList`. Enabled by default. -- `gfxd_emit_dec_color`: Print color components as decimal instead of -hexadecimal. Disabled by default. -- `gfxd_emit_q_macro`: Print fixed-point conversion `q` macros for fixed-point -values. Disabled by default. -- `gfxd_emit_ext_macro`: Emit non-standard macros. Some commands are valid -(though possibly meaningless), but have no macros associated with them, such as -a standalone `G_RDPHALF_1`. When this feature is enabled, such a command will -produce a non-standard `gsDPHalf1` macro instead of a raw hexadecimal command. -Also enables some non-standard multi-packet texture loading macros. Disabled by -default. - ---- - -##### `void gfxd_udata_set(void *ptr)` -##### `void *gfxd_udata_get(void)` -Set or get a generic pointer that can be used to pass user-defined data in and -out of callback functions. - -## Execution -Decompilation is started using the `gfxd_execute` function. When gfxd is -executing (i.e. after `gfxd_execute` has been entered, and before it returns), -the general settings and the I/O settings should not be changed. - ---- - -##### `int gfxd_execute()` -Start executing gfxd with the current settings. For each macro, the macro -handler registered with `gfxd_macro_fn` is called. Execution ends when the -input ends, the macro handler returns non-zero, when an invalid macro is -encountered and `gfxd_stop_on_invalid` is enabled, or when `SPBranchList` or -`SPEndDisplayList` is encountered and `gfxd_stop_on_end` is enabled. If -execution ends due to an invalid macro, `-1` is returned. If execution ends -because the macro handler returns non-zero, the return value from the macro -handler is returned. Otherwise zero is returned. - -## Macro information -The following functions can be used to obtain information about the current -macro and its arguments. They should only be used in custom handlers and -callbacks from within `gfxd_execute`. If used elsewhere, their behavior is -undefined. - ---- - -##### `int gfxd_macro_offset()` -Returns the offset in the input data of the current macro. The offset starts -at zero when `gfxd_execute` is called. - ---- - -##### `int gfxd_macro_packets()` -Returns the number of `Gfx` packets within the current macro. - ---- - -##### `const void *gfxd_macro_data()` -Returns a pointer to the input data for the current macro. The data is not -byte-swapped. The data has a length of `sizeof(Gfx) * gfxd_macro_packets()`. - ---- - -##### `int gfxd_macro_id()` -Returns a number that uniquely identifies the current macro. The number will -be one of the constants in `gfxd.h`. - ---- - -##### `const char *gfxd_macro_name()` -Returns the name of the current macro. If the macro does not have a name (i.e. -it's invalid), null is returned. If a dynamic display list pointer has been -specified, the dynamic `g` version is returned. Otherwise the static `gs` -version is returned. The returned pointer is invalidated by a subsequent call -to `gfxd_macro_name`. - ---- - -##### `int gfxd_arg_count()` -Returns the number of arguments to the current macro, not including a dynamic -display list pointer if one has been specified. - ---- - -##### `int gfxd_arg_type(int arg_num)` -Returns a number that identifies the type of the argument with index `arg_num`. -The number will be one of the constants in `gfxd.h`. - ---- - -##### `const char *gfxd_arg_name(int arg_num)` -Returns the name of the argument with index `arg_num`. Argument names are not -canonical, nor are they needed for macro disassembly, but they can be useful -for informational and diagnostic purposes. - ---- - -##### `int gfxd_arg_fmt(int arg_num)` -Returns the data format of the argument with index `arg_num`. The return value -will be `gfxd_argfmt_i` for `int32_t`, `gfxd_argfmt_u` for `uint32_t`, or -`gfxd_argfmt_f` for `float`. When accessing the value of the argument with -`gfxd_arg_value`, the member with the corresponding type should be used. - ---- - -##### `const gfxd_value_t *gfxd_arg_value(int arg_num)` -Returns a pointer to the value of the argument with index `arg_num`. The value -is a union of type `gfxd_value_t` with the following layout; -``` -typedef union -{ - int32_t i; - uint32_t u; - float f; -} gfxd_value_t -``` - ---- - -##### `const gfxd_value_t *gfxd_value_by_type(int type, int idx)` -Returns a pointer to the value of the argument that is of `type`, and has order -`idx` in all arguments of that type. An `idx` of zero returns the first -argument that has the specified type. If there is no argument with the given -type and order, null is returned. - ---- - -##### `int gfxd_arg_valid(int arg_num)` -Returns non-zero if the argument with index `arg_num` is "valid", for some -definition of valid. An invalid argument generally means that the disassembler -found inconsistencies in the input data, or that the data can not be reproduced -by the current macro type. The argument still has a value that can be printed, -though the value is not guaranteed to make any sense. - -## Custom output -When the default handlers are overridden or extended, the custom handler -functions will want to do some output of their own. The following methods are -available for inserting custom text into the gfxd output. - ---- - -##### `int gfxd_write(const void *buf, int count)` -Insert `count` bytes from the buffer at `buf` into the output. The number of -characters written is returned. - ---- - -##### `int gfxd_puts(const char *str)` -Insert the null-terminated string at `str` into the output. The number of -characters written is returned. - ---- - -##### `int gfxd_printf(const char *fmt, ...)` -Insert the printf-formatted string described by `fmt` and additional arguments -into the output. Limited to 255 characters. The number of characters written is -returned. - ---- - -##### `int gfxd_print_value(int type, const gfxd_value_t *value)` -Insert the type-formatted value into the output. The type should be one of the -constants in `gfxd.h`. The number of characters written is returned. The -macro argument with index `n` can be printed with -`gfxd_print_value(gfxd_arg_type(n), gfxd_arg_value(n))`. diff --git a/tools/ZAPD/lib/libgfxd/gbi.h b/tools/ZAPD/lib/libgfxd/gbi.h deleted file mode 100644 index 69fa7f12e5..0000000000 --- a/tools/ZAPD/lib/libgfxd/gbi.h +++ /dev/null @@ -1,3838 +0,0 @@ -/** - * gbi.h version 0.3.6 - * n64 graphics microcode interface library - * compatible with fast3d, f3dex, f3dex2, s2dex, and s2dex2 - * - * select a microcode with one of these preprocessor definitions; - * #define F3D_GBI - * for fast3d (selected automatically by default), or - * #define F3DEX_GBI - * for f3dex/s2dex, or - * #define F3DEX_GBI_2 - * for f3dex2/s2dex2 - * - * for early versions of fast3d and f3dex, also define the following; - * #define F3D_BETA - * - * ido incompatibilities; - * - use of c99 variadic macros - * - use of c99 fixed-width integer types - * - use of c99 designated initializers - * - use of c99 compound literals - * - use of c11 _Alignas - * - use of gnu c compound expressions - * - use of gnu c __typeof__ - * - * libultra incompatibilities; - * - many private, undocumented, or obsolete macros not commonly used by - * programmers are missing - * - many different implementation details that will produce matching gbi, - * but not matching code -**/ - -#ifndef N64_GBI_H -#define N64_GBI_H - -#include - -/* use fast3d by default */ -#if !defined(F3D_GBI) && !defined(F3DEX_GBI) && !defined(F3DEX_GBI_2) -# define F3D_GBI -#endif - -/* commands for fast3d and f3dex */ -#if defined(F3D_GBI) || defined(F3DEX_GBI) -# define G_SPNOOP 0x00 -# define G_MTX 0x01 -# define G_MOVEMEM 0x03 -# define G_VTX 0x04 -# define G_DL 0x06 -# if defined(F3D_BETA) -# define G_RDPHALF_2 0xB2 -# define G_RDPHALF_1 0xB3 -# define G_PERSPNORM 0xB4 -# else -# define G_RDPHALF_2 0xB3 -# define G_RDPHALF_1 0xB4 -# endif -# define G_LINE3D 0xB5 -# define G_CLEARGEOMETRYMODE 0xB6 -# define G_SETGEOMETRYMODE 0xB7 -# define G_ENDDL 0xB8 -# define G_SETOTHERMODE_L 0xB9 -# define G_SETOTHERMODE_H 0xBA -# define G_TEXTURE 0xBB -# define G_MOVEWORD 0xBC -# define G_POPMTX 0xBD -# define G_CULLDL 0xBE -# define G_TRI1 0xBF -# define G_NOOP 0xC0 -#endif - -/* commands for f3dex */ -#if defined(F3DEX_GBI) -# define G_LOAD_UCODE 0xAF -# define G_BRANCH_Z 0xB0 -# define G_TRI2 0xB1 -# if !defined(F3D_BETA) -# define G_MODIFYVTX 0xB2 -# endif -#endif - -/* commands for f3dex2 */ -#if defined(F3DEX_GBI_2) -# define G_NOOP 0x00 -# define G_VTX 0x01 -# define G_MODIFYVTX 0x02 -# define G_CULLDL 0x03 -# define G_BRANCH_Z 0x04 -# define G_TRI1 0x05 -# define G_TRI2 0x06 -# define G_QUAD 0x07 -# define G_LINE3D 0x08 -# define G_SPECIAL_3 0xD3 -# define G_SPECIAL_2 0xD4 -# define G_SPECIAL_1 0xD5 -# define G_DMA_IO 0xD6 -# define G_TEXTURE 0xD7 -# define G_POPMTX 0xD8 -# define G_GEOMETRYMODE 0xD9 -# define G_MTX 0xDA -# define G_MOVEWORD 0xDB -# define G_MOVEMEM 0xDC -# define G_LOAD_UCODE 0xDD -# define G_DL 0xDE -# define G_ENDDL 0xDF -# define G_SPNOOP 0xE0 -# define G_RDPHALF_1 0xE1 -# define G_SETOTHERMODE_L 0xE2 -# define G_SETOTHERMODE_H 0xE3 -# define G_RDPHALF_2 0xF1 -#endif - -/* rdp commands */ -#define G_TEXRECT 0xE4 -#define G_TEXRECTFLIP 0xE5 -#define G_RDPLOADSYNC 0xE6 -#define G_RDPPIPESYNC 0xE7 -#define G_RDPTILESYNC 0xE8 -#define G_RDPFULLSYNC 0xE9 -#define G_SETKEYGB 0xEA -#define G_SETKEYR 0xEB -#define G_SETCONVERT 0xEC -#define G_SETSCISSOR 0xED -#define G_SETPRIMDEPTH 0xEE -#define G_RDPSETOTHERMODE 0xEF -#define G_LOADTLUT 0xF0 -#define G_SETTILESIZE 0xF2 -#define G_LOADBLOCK 0xF3 -#define G_LOADTILE 0xF4 -#define G_SETTILE 0xF5 -#define G_FILLRECT 0xF6 -#define G_SETFILLCOLOR 0xF7 -#define G_SETFOGCOLOR 0xF8 -#define G_SETBLENDCOLOR 0xF9 -#define G_SETPRIMCOLOR 0xFA -#define G_SETENVCOLOR 0xFB -#define G_SETCOMBINE 0xFC -#define G_SETTIMG 0xFD -#define G_SETZIMG 0xFE -#define G_SETCIMG 0xFF - -/* commands for s2dex */ -#if defined(F3DEX_GBI) -# define G_BG_1CYC 0x01 -# define G_BG_COPY 0x02 -# define G_OBJ_RECTANGLE 0x03 -# define G_OBJ_SPRITE 0x04 -# define G_OBJ_MOVEMEM 0x05 -# define G_SELECT_DL 0xB0 -# define G_OBJ_RENDERMODE 0xB1 -# define G_OBJ_RECTANGLE_R 0xB2 -# define G_OBJ_LOADTXTR 0xC1 -# define G_OBJ_LDTX_SPRITE 0xC2 -# define G_OBJ_LDTX_RECT 0xC3 -# define G_OBJ_LDTX_RECT_R 0xC4 -#endif - -/* commands for s2dex2 */ -#if defined(F3DEX_GBI_2) -# define G_OBJ_RECTANGLE 0x01 -# define G_OBJ_SPRITE 0x02 -# define G_SELECT_DL 0x04 -# define G_OBJ_LOADTXTR 0x05 -# define G_OBJ_LDTX_SPRITE 0x06 -# define G_OBJ_LDTX_RECT 0x07 -# define G_OBJ_LDTX_RECT_R 0x08 -# define G_BG_1CYC 0x09 -# define G_BG_COPY 0x0A -# define G_OBJ_RENDERMODE 0x0B -# define G_OBJ_RECTANGLE_R 0xDA -# define G_OBJ_MOVEMEM 0xDC -#endif - -/* commands for s2dex and s2dex2 */ -#if defined(F3DEX_GBI) || defined(F3DEX_GBI_2) -# define G_RDPHALF_0 0xE4 -#endif - -/* image formats */ -#define G_IM_FMT_RGBA 0 -#define G_IM_FMT_YUV 1 -#define G_IM_FMT_CI 2 -#define G_IM_FMT_IA 3 -#define G_IM_FMT_I 4 -#define G_IM_SIZ_4b 0 -#define G_IM_SIZ_8b 1 -#define G_IM_SIZ_16b 2 -#define G_IM_SIZ_32b 3 - -/* texture settings */ -#define G_TX_NOMIRROR (gI_(0b0) << 0) -#define G_TX_MIRROR (gI_(0b1) << 0) -#define G_TX_WRAP (gI_(0b0) << 1) -#define G_TX_CLAMP (gI_(0b1) << 1) -#define G_TX_NOMASK gI_(0) -#define G_TX_NOLOD gI_(0) -#define G_OFF gI_(0) -#define G_ON gI_(1) - -/* tile indices */ -#define G_TX_LOADTILE 7 -#define G_TX_RENDERTILE 0 - -/* loadblock constants */ -#define G_TX_DXT_FRAC 11 -#define G_TX_LDBLK_MAX_TXL 2047 - -/* geometry mode */ -#define G_ZBUFFER (gI_(0b1) << 0) -#define G_SHADE (gI_(0b1) << 2) -#define G_CULL_BOTH (G_CULL_FRONT | G_CULL_BACK) -#define G_FOG (gI_(0b1) << 16) -#define G_LIGHTING (gI_(0b1) << 17) -#define G_TEXTURE_GEN (gI_(0b1) << 18) -#define G_TEXTURE_GEN_LINEAR (gI_(0b1) << 19) -#define G_LOD (gI_(0b1) << 20) - -/* geometry mode for fast3d */ -#if defined(F3D_GBI) -# define G_CLIPPING (gI_(0b0) << 0) -#endif - -/* geometry mode for fast3d and f3dex */ -#if defined(F3D_GBI) || defined(F3DEX_GBI) -# define G_TEXTURE_ENABLE (gI_(0b1) << 1) -# define G_SHADING_SMOOTH (gI_(0b1) << 9) -# define G_CULL_FRONT (gI_(0b1) << 12) -# define G_CULL_BACK (gI_(0b1) << 13) -#endif - -/* geometry mode for f3dex and f3dex2 */ -#if defined(F3DEX_GBI) || defined(F3DEX_GBI_2) -# define G_CLIPPING (gI_(0b1) << 23) -#endif - -/* geometry mode for f3dex2 */ -#if defined(F3DEX_GBI_2) -# define G_TEXTURE_ENABLE (gI_(0b0) << 0) -# define G_CULL_FRONT (gI_(0b1) << 9) -# define G_CULL_BACK (gI_(0b1) << 10) -# define G_SHADING_SMOOTH (gI_(0b1) << 21) -#endif - -/* othermode lo */ -#define G_MDSFT_ALPHACOMPARE 0 -#define G_MDSFT_ZSRCSEL 2 -#define G_MDSFT_RENDERMODE 3 -#define G_MDSFT_BLENDER 16 -#define G_MDSIZ_ALPHACOMPARE 2 -#define G_MDSIZ_ZSRCSEL 1 -#define G_MDSIZ_RENDERMODE 29 -#define G_MDSIZ_BLENDER 13 - -#define G_AC_NONE (gI_(0b00) << G_MDSFT_ALPHACOMPARE) -#define G_AC_THRESHOLD (gI_(0b01) << G_MDSFT_ALPHACOMPARE) -#define G_AC_DITHER (gI_(0b11) << G_MDSFT_ALPHACOMPARE) -#define G_ZS_PIXEL (gI_(0b0) << G_MDSFT_ZSRCSEL) -#define G_ZS_PRIM (gI_(0b1) << G_MDSFT_ZSRCSEL) -#define AA_EN (gI_(0b1) << (G_MDSFT_RENDERMODE + 0)) -#define Z_CMP (gI_(0b1) << (G_MDSFT_RENDERMODE + 1)) -#define Z_UPD (gI_(0b1) << (G_MDSFT_RENDERMODE + 2)) -#define IM_RD (gI_(0b1) << (G_MDSFT_RENDERMODE + 3)) -#define CLR_ON_CVG (gI_(0b1) << (G_MDSFT_RENDERMODE + 4)) -#define CVG_DST_CLAMP (gI_(0b00) << (G_MDSFT_RENDERMODE + 5)) -#define CVG_DST_WRAP (gI_(0b01) << (G_MDSFT_RENDERMODE + 5)) -#define CVG_DST_FULL (gI_(0b10) << (G_MDSFT_RENDERMODE + 5)) -#define CVG_DST_SAVE (gI_(0b11) << (G_MDSFT_RENDERMODE + 5)) -#define ZMODE_OPA (gI_(0b00) << (G_MDSFT_RENDERMODE + 7)) -#define ZMODE_INTER (gI_(0b01) << (G_MDSFT_RENDERMODE + 7)) -#define ZMODE_XLU (gI_(0b10) << (G_MDSFT_RENDERMODE + 7)) -#define ZMODE_DEC (gI_(0b11) << (G_MDSFT_RENDERMODE + 7)) -#define CVG_X_ALPHA (gI_(0b1) << (G_MDSFT_RENDERMODE + 9)) -#define ALPHA_CVG_SEL (gI_(0b1) << (G_MDSFT_RENDERMODE + 10)) -#define FORCE_BL (gI_(0b1) << (G_MDSFT_RENDERMODE + 11)) - -#define G_BL_1MA gI_(0b00) -#define G_BL_1 gI_(0b10) -#define G_BL_0 gI_(0b11) -#define G_BL_CLR_IN gI_(0b00) -#define G_BL_CLR_MEM gI_(0b01) -#define G_BL_CLR_BL gI_(0b10) -#define G_BL_CLR_FOG gI_(0b11) -#define G_BL_A_IN gI_(0b00) -#define G_BL_A_FOG gI_(0b01) -#define G_BL_A_MEM gI_(0b01) -#define G_BL_A_SHADE gI_(0b10) - -#define GBL_c1(p, a, m, b) \ - ( \ - gF_(p, 2, 30) | \ - gF_(a, 2, 26) | \ - gF_(m, 2, 22) | \ - gF_(b, 2, 18) \ - ) -#define GBL_c2(p, a, m, b) \ - ( \ - gF_(p, 2, 28) | \ - gF_(a, 2, 24) | \ - gF_(m, 2, 20) | \ - gF_(b, 2, 16) \ - ) - -/* render modes */ -#define G_RM_OPA_SURF \ - ( \ - CVG_DST_CLAMP | ZMODE_OPA | FORCE_BL | \ - GBL_c1(G_BL_CLR_IN, G_BL_0, G_BL_CLR_IN, G_BL_1) \ - ) -#define G_RM_OPA_SURF2 \ - ( \ - CVG_DST_CLAMP | ZMODE_OPA | FORCE_BL | \ - GBL_c2(G_BL_CLR_IN, G_BL_0, G_BL_CLR_IN, G_BL_1) \ - ) -#define G_RM_AA_OPA_SURF \ - ( \ - AA_EN | IM_RD | CVG_DST_CLAMP | ZMODE_OPA | ALPHA_CVG_SEL | \ - GBL_c1(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_A_MEM) \ - ) -#define G_RM_AA_OPA_SURF2 \ - ( \ - AA_EN | IM_RD | CVG_DST_CLAMP | ZMODE_OPA | ALPHA_CVG_SEL | \ - GBL_c2(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_A_MEM) \ - ) -#define G_RM_RA_OPA_SURF \ - ( \ - AA_EN | CVG_DST_CLAMP | ZMODE_OPA | ALPHA_CVG_SEL | \ - GBL_c1(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_A_MEM) \ - ) -#define G_RM_RA_OPA_SURF2 \ - ( \ - AA_EN | CVG_DST_CLAMP | ZMODE_OPA | ALPHA_CVG_SEL | \ - GBL_c2(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_A_MEM) \ - ) -#define G_RM_ZB_OPA_SURF \ - ( \ - Z_CMP | Z_UPD | CVG_DST_FULL | ZMODE_OPA | ALPHA_CVG_SEL | \ - GBL_c1(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_A_MEM) \ - ) -#define G_RM_ZB_OPA_SURF2 \ - ( \ - Z_CMP | Z_UPD | CVG_DST_FULL | ZMODE_OPA | ALPHA_CVG_SEL | \ - GBL_c2(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_A_MEM) \ - ) -#define G_RM_AA_ZB_OPA_SURF \ - ( \ - AA_EN | Z_CMP | Z_UPD | IM_RD | CVG_DST_CLAMP | ZMODE_OPA | \ - ALPHA_CVG_SEL | \ - GBL_c1(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_A_MEM) \ - ) -#define G_RM_AA_ZB_OPA_SURF2 \ - ( \ - AA_EN | Z_CMP | Z_UPD | IM_RD | CVG_DST_CLAMP | ZMODE_OPA | \ - ALPHA_CVG_SEL | \ - GBL_c2(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_A_MEM) \ - ) -#define G_RM_RA_ZB_OPA_SURF \ - ( \ - AA_EN | Z_CMP | Z_UPD | CVG_DST_CLAMP | ZMODE_OPA | \ - ALPHA_CVG_SEL | \ - GBL_c1(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_A_MEM) \ - ) -#define G_RM_RA_ZB_OPA_SURF2 \ - ( \ - AA_EN | Z_CMP | Z_UPD | CVG_DST_CLAMP | ZMODE_OPA | \ - ALPHA_CVG_SEL | \ - GBL_c2(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_A_MEM) \ - ) - -#define G_RM_XLU_SURF \ - ( \ - IM_RD | CVG_DST_FULL | ZMODE_OPA | FORCE_BL | \ - GBL_c1(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_1MA) \ - ) -#define G_RM_XLU_SURF2 \ - ( \ - IM_RD | CVG_DST_FULL | ZMODE_OPA | FORCE_BL | \ - GBL_c2(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_1MA) \ - ) -#define G_RM_AA_XLU_SURF \ - ( \ - AA_EN | IM_RD | CLR_ON_CVG | CVG_DST_WRAP | ZMODE_OPA | \ - FORCE_BL | \ - GBL_c1(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_1MA) \ - ) -#define G_RM_AA_XLU_SURF2 \ - ( \ - AA_EN | IM_RD | CLR_ON_CVG | CVG_DST_WRAP | ZMODE_OPA | \ - FORCE_BL | \ - GBL_c2(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_1MA) \ - ) -#define G_RM_ZB_XLU_SURF \ - ( \ - Z_CMP | IM_RD | CVG_DST_FULL | ZMODE_XLU | FORCE_BL | \ - GBL_c1(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_1MA) \ - ) -#define G_RM_ZB_XLU_SURF2 \ - ( \ - Z_CMP | IM_RD | CVG_DST_FULL | ZMODE_XLU | FORCE_BL | \ - GBL_c2(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_1MA) \ - ) -#define G_RM_AA_ZB_XLU_SURF \ - ( \ - AA_EN | Z_CMP | IM_RD | CLR_ON_CVG | CVG_DST_WRAP | \ - ZMODE_XLU | FORCE_BL | \ - GBL_c1(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_1MA) \ - ) -#define G_RM_AA_ZB_XLU_SURF2 \ - ( \ - AA_EN | Z_CMP | IM_RD | CLR_ON_CVG | CVG_DST_WRAP | \ - ZMODE_XLU | FORCE_BL | \ - GBL_c2(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_1MA) \ - ) - -#define G_RM_ZB_OPA_DECAL \ - ( \ - Z_CMP | CVG_DST_FULL | ZMODE_DEC | ALPHA_CVG_SEL | \ - GBL_c1(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_A_MEM) \ - ) -#define G_RM_ZB_OPA_DECAL2 \ - ( \ - Z_CMP | CVG_DST_FULL | ZMODE_DEC | ALPHA_CVG_SEL | \ - GBL_c2(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_A_MEM) \ - ) -#define G_RM_AA_ZB_OPA_DECAL \ - ( \ - AA_EN | Z_CMP | IM_RD | CVG_DST_WRAP | ZMODE_DEC | \ - ALPHA_CVG_SEL | \ - GBL_c1(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_A_MEM) \ - ) -#define G_RM_AA_ZB_OPA_DECAL2 \ - ( \ - AA_EN | Z_CMP | IM_RD | CVG_DST_WRAP | ZMODE_DEC | \ - ALPHA_CVG_SEL | \ - GBL_c2(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_A_MEM) \ - ) -#define G_RM_RA_ZB_OPA_DECAL \ - ( \ - AA_EN | Z_CMP | CVG_DST_WRAP | ZMODE_DEC | ALPHA_CVG_SEL | \ - GBL_c1(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_A_MEM) \ - ) -#define G_RM_RA_ZB_OPA_DECAL2 \ - ( \ - AA_EN | Z_CMP | CVG_DST_WRAP | ZMODE_DEC | ALPHA_CVG_SEL | \ - GBL_c2(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_A_MEM) \ - ) - -#define G_RM_ZB_XLU_DECAL \ - ( \ - Z_CMP | IM_RD | CVG_DST_FULL | ZMODE_DEC | FORCE_BL | \ - GBL_c1(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_1MA) \ - ) -#define G_RM_ZB_XLU_DECAL2 \ - ( \ - Z_CMP | IM_RD | CVG_DST_FULL | ZMODE_DEC | FORCE_BL | \ - GBL_c2(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_1MA) \ - ) -#define G_RM_AA_ZB_XLU_DECAL \ - ( \ - AA_EN | Z_CMP | IM_RD | CLR_ON_CVG | CVG_DST_WRAP | \ - ZMODE_DEC | FORCE_BL | \ - GBL_c1(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_1MA) \ - ) -#define G_RM_AA_ZB_XLU_DECAL2 \ - ( \ - AA_EN | Z_CMP | IM_RD | CLR_ON_CVG | CVG_DST_WRAP | \ - ZMODE_DEC | FORCE_BL | \ - GBL_c2(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_1MA) \ - ) - -#define G_RM_AA_ZB_OPA_INTER \ - ( \ - AA_EN | Z_CMP | Z_UPD | IM_RD | CVG_DST_CLAMP | ZMODE_INTER | \ - ALPHA_CVG_SEL | \ - GBL_c1(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_A_MEM) \ - ) -#define G_RM_AA_ZB_OPA_INTER2 \ - ( \ - AA_EN | Z_CMP | Z_UPD | IM_RD | CVG_DST_CLAMP | ZMODE_INTER | \ - ALPHA_CVG_SEL | \ - GBL_c2(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_A_MEM) \ - ) -#define G_RM_RA_ZB_OPA_INTER \ - ( \ - AA_EN | Z_CMP | Z_UPD | CVG_DST_CLAMP | ZMODE_INTER | \ - ALPHA_CVG_SEL | \ - GBL_c1(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_A_MEM) \ - ) -#define G_RM_RA_ZB_OPA_INTER2 \ - ( \ - AA_EN | Z_CMP | Z_UPD | CVG_DST_CLAMP | ZMODE_INTER | \ - ALPHA_CVG_SEL | \ - GBL_c2(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_A_MEM) \ - ) - -#define G_RM_AA_ZB_XLU_INTER \ - ( \ - AA_EN | Z_CMP | IM_RD | CLR_ON_CVG | CVG_DST_WRAP | \ - ZMODE_INTER | FORCE_BL | \ - GBL_c1(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_1MA) \ - ) -#define G_RM_AA_ZB_XLU_INTER2 \ - ( \ - AA_EN | Z_CMP | IM_RD | CLR_ON_CVG | CVG_DST_WRAP | \ - ZMODE_INTER | FORCE_BL | \ - GBL_c2(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_1MA) \ - ) - -#define G_RM_AA_XLU_LINE \ - ( \ - AA_EN | IM_RD | CVG_DST_CLAMP | ZMODE_OPA | CVG_X_ALPHA | \ - ALPHA_CVG_SEL | FORCE_BL | \ - GBL_c1(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_1MA) \ - ) -#define G_RM_AA_XLU_LINE2 \ - ( \ - AA_EN | IM_RD | CVG_DST_CLAMP | ZMODE_OPA | CVG_X_ALPHA | \ - ALPHA_CVG_SEL | FORCE_BL | \ - GBL_c2(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_1MA) \ - ) -#define G_RM_AA_ZB_XLU_LINE \ - ( \ - AA_EN | Z_CMP | IM_RD | CVG_DST_CLAMP | ZMODE_XLU | \ - CVG_X_ALPHA | ALPHA_CVG_SEL | FORCE_BL | \ - GBL_c1(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_1MA) \ - ) -#define G_RM_AA_ZB_XLU_LINE2 \ - ( \ - AA_EN | Z_CMP | IM_RD | CVG_DST_CLAMP | ZMODE_XLU | \ - CVG_X_ALPHA | ALPHA_CVG_SEL | FORCE_BL | \ - GBL_c2(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_1MA) \ - ) - -#define G_RM_AA_DEC_LINE \ - ( \ - AA_EN | IM_RD | CVG_DST_FULL | ZMODE_OPA | CVG_X_ALPHA | \ - ALPHA_CVG_SEL | FORCE_BL | \ - GBL_c1(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_1MA) \ - ) -#define G_RM_AA_DEC_LINE2 \ - ( \ - AA_EN | IM_RD | CVG_DST_FULL | ZMODE_OPA | CVG_X_ALPHA | \ - ALPHA_CVG_SEL | FORCE_BL | \ - GBL_c2(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_1MA) \ - ) -#define G_RM_AA_ZB_DEC_LINE \ - ( \ - AA_EN | Z_CMP | IM_RD | CVG_DST_SAVE | ZMODE_DEC | \ - CVG_X_ALPHA | ALPHA_CVG_SEL | FORCE_BL | \ - GBL_c1(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_1MA) \ - ) -#define G_RM_AA_ZB_DEC_LINE2 \ - ( \ - AA_EN | Z_CMP | IM_RD | CVG_DST_SAVE | ZMODE_DEC | \ - CVG_X_ALPHA | ALPHA_CVG_SEL | FORCE_BL | \ - GBL_c2(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_1MA) \ - ) - - -#define G_RM_TEX_EDGE \ - ( \ - AA_EN | CVG_DST_CLAMP | ZMODE_OPA | CVG_X_ALPHA | \ - ALPHA_CVG_SEL | FORCE_BL | \ - GBL_c1(G_BL_CLR_IN, G_BL_0, G_BL_CLR_IN, G_BL_1) \ - ) -#define G_RM_TEX_EDGE2 \ - ( \ - AA_EN | CVG_DST_CLAMP | ZMODE_OPA | CVG_X_ALPHA | \ - ALPHA_CVG_SEL | FORCE_BL | \ - GBL_c2(G_BL_CLR_IN, G_BL_0, G_BL_CLR_IN, G_BL_1) \ - ) -#define G_RM_AA_TEX_EDGE \ - ( \ - AA_EN | IM_RD | CVG_DST_CLAMP | ZMODE_OPA | CVG_X_ALPHA | \ - ALPHA_CVG_SEL | \ - GBL_c1(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_A_MEM) \ - ) -#define G_RM_AA_TEX_EDGE2 \ - ( \ - AA_EN | IM_RD | CVG_DST_CLAMP | ZMODE_OPA | CVG_X_ALPHA | \ - ALPHA_CVG_SEL | \ - GBL_c2(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_A_MEM) \ - ) -#define G_RM_AA_ZB_TEX_EDGE \ - ( \ - AA_EN | Z_CMP | Z_UPD | IM_RD | CVG_DST_CLAMP | ZMODE_OPA | \ - CVG_X_ALPHA | ALPHA_CVG_SEL | \ - GBL_c1(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_A_MEM) \ - ) -#define G_RM_AA_ZB_TEX_EDGE2 \ - ( \ - AA_EN | Z_CMP | Z_UPD | IM_RD | CVG_DST_CLAMP | ZMODE_OPA | \ - CVG_X_ALPHA | ALPHA_CVG_SEL | \ - GBL_c2(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_A_MEM) \ - ) - -#define G_RM_AA_ZB_TEX_INTER \ - ( \ - AA_EN | Z_CMP | Z_UPD | IM_RD | CVG_DST_CLAMP | ZMODE_INTER | \ - CVG_X_ALPHA | ALPHA_CVG_SEL | \ - GBL_c1(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_A_MEM) \ - ) -#define G_RM_AA_ZB_TEX_INTER2 \ - ( \ - AA_EN | Z_CMP | Z_UPD | IM_RD | CVG_DST_CLAMP | ZMODE_INTER | \ - CVG_X_ALPHA | ALPHA_CVG_SEL | \ - GBL_c2(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_A_MEM) \ - ) - -#define G_RM_AA_SUB_SURF \ - ( \ - AA_EN | IM_RD | CVG_DST_FULL | ZMODE_OPA | ALPHA_CVG_SEL | \ - GBL_c1(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_A_MEM) \ - ) -#define G_RM_AA_SUB_SURF2 \ - ( \ - AA_EN | IM_RD | CVG_DST_FULL | ZMODE_OPA | ALPHA_CVG_SEL | \ - GBL_c2(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_A_MEM) \ - ) -#define G_RM_AA_ZB_SUB_SURF \ - ( \ - AA_EN | Z_CMP | Z_UPD | IM_RD | CVG_DST_FULL | ZMODE_OPA | \ - ALPHA_CVG_SEL | \ - GBL_c1(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_A_MEM) \ - ) -#define G_RM_AA_ZB_SUB_SURF2 \ - ( \ - AA_EN | Z_CMP | Z_UPD | IM_RD | CVG_DST_FULL | ZMODE_OPA | \ - ALPHA_CVG_SEL | \ - GBL_c2(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_A_MEM) \ - ) - -#define G_RM_PCL_SURF \ - ( \ - G_AC_DITHER | CVG_DST_FULL | ZMODE_OPA | FORCE_BL | \ - GBL_c1(G_BL_CLR_IN, G_BL_0, G_BL_CLR_IN, G_BL_1) \ - ) -#define G_RM_PCL_SURF2 \ - ( \ - G_AC_DITHER | CVG_DST_FULL | ZMODE_OPA | FORCE_BL | \ - GBL_c2(G_BL_CLR_IN, G_BL_0, G_BL_CLR_IN, G_BL_1) \ - ) -#define G_RM_AA_PCL_SURF \ - ( \ - G_AC_DITHER | AA_EN | IM_RD | CVG_DST_CLAMP | ZMODE_OPA | \ - GBL_c1(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_1MA) \ - ) -#define G_RM_AA_PCL_SURF2 \ - ( \ - G_AC_DITHER | AA_EN | IM_RD | CVG_DST_CLAMP | ZMODE_OPA | \ - GBL_c2(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_1MA) \ - ) -#define G_RM_ZB_PCL_SURF \ - ( \ - G_AC_DITHER | Z_CMP | Z_UPD | CVG_DST_FULL | ZMODE_OPA | \ - GBL_c1(G_BL_CLR_IN, G_BL_0, G_BL_CLR_IN, G_BL_1) \ - ) -#define G_RM_ZB_PCL_SURF2 \ - ( \ - G_AC_DITHER | Z_CMP | Z_UPD | CVG_DST_FULL | ZMODE_OPA | \ - GBL_c2(G_BL_CLR_IN, G_BL_0, G_BL_CLR_IN, G_BL_1) \ - ) -#define G_RM_AA_ZB_PCL_SURF \ - ( \ - G_AC_DITHER | AA_EN | Z_CMP | Z_UPD | IM_RD | CVG_DST_CLAMP | \ - ZMODE_OPA | \ - GBL_c1(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_1MA) \ - ) -#define G_RM_AA_ZB_PCL_SURF2 \ - ( \ - G_AC_DITHER | AA_EN | Z_CMP | Z_UPD | IM_RD | CVG_DST_CLAMP | \ - ZMODE_OPA | \ - GBL_c2(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_1MA) \ - ) - -#define G_RM_AA_OPA_TERR \ - ( \ - AA_EN | IM_RD | CVG_DST_CLAMP | ZMODE_OPA | ALPHA_CVG_SEL | \ - GBL_c1(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_1MA) \ - ) -#define G_RM_AA_OPA_TERR2 \ - ( \ - AA_EN | IM_RD | CVG_DST_CLAMP | ZMODE_OPA | ALPHA_CVG_SEL | \ - GBL_c2(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_1MA) \ - ) -#define G_RM_AA_ZB_OPA_TERR \ - ( \ - AA_EN | Z_CMP | Z_UPD | IM_RD | CVG_DST_CLAMP | ZMODE_OPA | \ - ALPHA_CVG_SEL | \ - GBL_c1(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_1MA) \ - ) -#define G_RM_AA_ZB_OPA_TERR2 \ - ( \ - AA_EN | Z_CMP | Z_UPD | IM_RD | CVG_DST_CLAMP | ZMODE_OPA | \ - ALPHA_CVG_SEL | \ - GBL_c2(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_1MA) \ - ) - -#define G_RM_AA_TEX_TERR \ - ( \ - AA_EN | IM_RD | CVG_DST_CLAMP | ZMODE_OPA | CVG_X_ALPHA | \ - ALPHA_CVG_SEL | \ - GBL_c1(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_1MA) \ - ) -#define G_RM_AA_TEX_TERR2 \ - ( \ - AA_EN | IM_RD | CVG_DST_CLAMP | ZMODE_OPA | CVG_X_ALPHA | \ - ALPHA_CVG_SEL | \ - GBL_c2(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_1MA) \ - ) -#define G_RM_AA_ZB_TEX_TERR \ - ( \ - AA_EN | Z_CMP | Z_UPD | IM_RD | CVG_DST_CLAMP | ZMODE_OPA | \ - CVG_X_ALPHA | ALPHA_CVG_SEL | \ - GBL_c1(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_1MA) \ - ) -#define G_RM_AA_ZB_TEX_TERR2 \ - ( \ - AA_EN | Z_CMP | Z_UPD | IM_RD | CVG_DST_CLAMP | ZMODE_OPA | \ - CVG_X_ALPHA | ALPHA_CVG_SEL | \ - GBL_c2(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_1MA) \ - ) - -#define G_RM_AA_SUB_TERR \ - ( \ - AA_EN | IM_RD | CVG_DST_FULL | ZMODE_OPA | ALPHA_CVG_SEL | \ - GBL_c1(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_1MA) \ - ) -#define G_RM_AA_SUB_TERR2 \ - ( \ - AA_EN | IM_RD | CVG_DST_FULL | ZMODE_OPA | ALPHA_CVG_SEL | \ - GBL_c2(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_1MA) \ - ) -#define G_RM_AA_ZB_SUB_TERR \ - ( \ - AA_EN | Z_CMP | Z_UPD | IM_RD | CVG_DST_FULL | ZMODE_OPA | \ - ALPHA_CVG_SEL | \ - GBL_c1(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_1MA) \ - ) -#define G_RM_AA_ZB_SUB_TERR2 \ - ( \ - AA_EN | Z_CMP | Z_UPD | IM_RD | CVG_DST_FULL | ZMODE_OPA | \ - ALPHA_CVG_SEL | \ - GBL_c2(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_1MA) \ - ) - -#define G_RM_CLD_SURF \ - ( \ - IM_RD | CVG_DST_SAVE | ZMODE_OPA | FORCE_BL | \ - GBL_c1(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_1MA) \ - ) -#define G_RM_CLD_SURF2 \ - ( \ - IM_RD | CVG_DST_SAVE | ZMODE_OPA | FORCE_BL | \ - GBL_c2(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_1MA) \ - ) -#define G_RM_ZB_CLD_SURF \ - ( \ - Z_CMP | IM_RD | CVG_DST_SAVE | ZMODE_XLU | FORCE_BL | \ - GBL_c1(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_1MA) \ - ) -#define G_RM_ZB_CLD_SURF2 \ - ( \ - Z_CMP | IM_RD | CVG_DST_SAVE | ZMODE_XLU | FORCE_BL | \ - GBL_c2(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_1MA) \ - ) - -#define G_RM_ZB_OVL_SURF \ - ( \ - Z_CMP | IM_RD | CVG_DST_SAVE | ZMODE_DEC | FORCE_BL | \ - GBL_c1(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_1MA) \ - ) -#define G_RM_ZB_OVL_SURF2 \ - ( \ - Z_CMP | IM_RD | CVG_DST_SAVE | ZMODE_DEC | FORCE_BL | \ - GBL_c2(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_1MA) \ - ) - -#define G_RM_ADD \ - ( \ - IM_RD | CVG_DST_SAVE | ZMODE_OPA | FORCE_BL | \ - GBL_c1(G_BL_CLR_IN, G_BL_A_FOG, G_BL_CLR_MEM, G_BL_1) \ - ) -#define G_RM_ADD2 \ - ( \ - IM_RD | CVG_DST_SAVE | ZMODE_OPA | FORCE_BL | \ - GBL_c2(G_BL_CLR_IN, G_BL_A_FOG, G_BL_CLR_MEM, G_BL_1) \ - ) - -#define G_RM_FOG_SHADE_A \ - GBL_c1(G_BL_CLR_FOG, G_BL_A_SHADE, G_BL_CLR_IN, G_BL_1MA) - -#define G_RM_FOG_PRIM_A \ - GBL_c1(G_BL_CLR_FOG, G_BL_A_FOG, G_BL_CLR_IN, G_BL_1MA) - -#define G_RM_PASS \ - GBL_c1(G_BL_CLR_IN, G_BL_0, G_BL_CLR_IN, G_BL_1) - -#define G_RM_VISCVG \ - ( \ - IM_RD | FORCE_BL | \ - GBL_c1(G_BL_CLR_IN, G_BL_0, G_BL_CLR_BL, G_BL_A_MEM) \ - ) -#define G_RM_VISCVG2 \ - ( \ - IM_RD | FORCE_BL | \ - GBL_c2(G_BL_CLR_IN, G_BL_0, G_BL_CLR_BL, G_BL_A_MEM) \ - ) - -#define G_RM_OPA_CI \ - ( \ - CVG_DST_CLAMP | ZMODE_OPA | \ - GBL_c1(G_BL_CLR_IN, G_BL_0, G_BL_CLR_IN, G_BL_1) \ - ) -#define G_RM_OPA_CI2 \ - ( \ - CVG_DST_CLAMP | ZMODE_OPA | \ - GBL_c2(G_BL_CLR_IN, G_BL_0, G_BL_CLR_IN, G_BL_1) \ - ) - -#define G_RM_NOOP GBL_c1(0, 0, 0, 0) -#define G_RM_NOOP2 GBL_c2(0, 0, 0, 0) - -#define G_RM_SPRITE G_RM_OPA_SURF -#define G_RM_SPRITE2 G_RM_OPA_SURF2 -#define G_RM_RA_SPRITE \ - ( \ - AA_EN | CVG_DST_CLAMP | ZMODE_OPA | CVG_X_ALPHA | \ - ALPHA_CVG_SEL | \ - GBL_c1(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_1MA) \ - ) -#define G_RM_RA_SPRITE2 \ - ( \ - AA_EN | CVG_DST_CLAMP | ZMODE_OPA | CVG_X_ALPHA | \ - ALPHA_CVG_SEL | \ - GBL_c2(G_BL_CLR_IN, G_BL_A_IN, G_BL_CLR_MEM, G_BL_1MA) \ - ) -#define G_RM_AA_SPRITE G_RM_AA_TEX_TERR -#define G_RM_AA_SPRITE2 G_RM_AA_TEX_TERR2 -#define G_RM_XLU_SPRITE G_RM_XLU_SURF -#define G_RM_XLU_SPRITE2 G_RM_XLU_SURF2 -#define G_RM_AA_XLU_SPRITE G_RM_AA_XLU_SURF -#define G_RM_AA_XLU_SPRITE2 G_RM_AA_XLU_SURF2 - -#define G_OBJRM_NOTXCLAMP (gI_(0b1) << 0) -#define G_OBJRM_XLU (gI_(0b1) << 1) -#define G_OBJRM_ANTIALIAS (gI_(0b1) << 2) -#define G_OBJRM_BILERP (gI_(0b1) << 3) -#define G_OBJRM_SHRINKSIZE_1 (gI_(0b1) << 4) -#define G_OBJRM_SHRINKSIZE_2 (gI_(0b1) << 5) -#define G_OBJRM_WIDEN (gI_(0b1) << 6) - -/* othermode hi */ -#define G_MDSFT_ALPHADITHER 4 -#define G_MDSFT_RGBDITHER 6 -#define G_MDSFT_COMBKEY 8 -#define G_MDSFT_TEXTCONV 9 -#define G_MDSFT_TEXTFILT 12 -#define G_MDSFT_TEXTLUT 14 -#define G_MDSFT_TEXTLOD 16 -#define G_MDSFT_TEXTDETAIL 17 -#define G_MDSFT_TEXTPERSP 19 -#define G_MDSFT_CYCLETYPE 20 -#define G_MDSFT_PIPELINE 23 -#define G_MDSIZ_ALPHADITHER 2 -#define G_MDSIZ_RGBDITHER 2 -#define G_MDSIZ_COMBKEY 1 -#define G_MDSIZ_TEXTCONV 3 -#define G_MDSIZ_TEXTFILT 2 -#define G_MDSIZ_TEXTLUT 2 -#define G_MDSIZ_TEXTLOD 1 -#define G_MDSIZ_TEXTDETAIL 2 -#define G_MDSIZ_TEXTPERSP 1 -#define G_MDSIZ_CYCLETYPE 2 -#define G_MDSIZ_PIPELINE 1 - -#define G_AD_PATTERN (gI_(0b00) << G_MDSFT_ALPHADITHER) -#define G_AD_NOTPATTERN (gI_(0b01) << G_MDSFT_ALPHADITHER) -#define G_AD_NOISE (gI_(0b10) << G_MDSFT_ALPHADITHER) -#define G_AD_DISABLE (gI_(0b11) << G_MDSFT_ALPHADITHER) -#define G_CD_MAGICSQ (gI_(0b00) << G_MDSFT_RGBDITHER) -#define G_CD_BAYER (gI_(0b01) << G_MDSFT_RGBDITHER) -#define G_CD_NOISE (gI_(0b10) << G_MDSFT_RGBDITHER) -#define G_CD_DISABLE (gI_(0b11) << G_MDSFT_RGBDITHER) -#define G_CD_ENABLE (gI_(0b10) << G_MDSFT_RGBDITHER) -#define G_CK_NONE (gI_(0b0) << G_MDSFT_COMBKEY) -#define G_CK_KEY (gI_(0b1) << G_MDSFT_COMBKEY) -#define G_TC_CONV (gI_(0b000) << G_MDSFT_TEXTCONV) -#define G_TC_FILTCONV (gI_(0b101) << G_MDSFT_TEXTCONV) -#define G_TC_FILT (gI_(0b110) << G_MDSFT_TEXTCONV) -#define G_TF_POINT (gI_(0b00) << G_MDSFT_TEXTFILT) -#define G_TF_BILERP (gI_(0b10) << G_MDSFT_TEXTFILT) -#define G_TF_AVERAGE (gI_(0b11) << G_MDSFT_TEXTFILT) -#define G_TT_NONE (gI_(0b00) << G_MDSFT_TEXTLUT) -#define G_TT_RGBA16 (gI_(0b10) << G_MDSFT_TEXTLUT) -#define G_TT_IA16 (gI_(0b11) << G_MDSFT_TEXTLUT) -#define G_TL_TILE (gI_(0b0) << G_MDSFT_TEXTLOD) -#define G_TL_LOD (gI_(0b1) << G_MDSFT_TEXTLOD) -#define G_TD_CLAMP (gI_(0b00) << G_MDSFT_TEXTDETAIL) -#define G_TD_SHARPEN (gI_(0b01) << G_MDSFT_TEXTDETAIL) -#define G_TD_DETAIL (gI_(0b10) << G_MDSFT_TEXTDETAIL) -#define G_TP_NONE (gI_(0b0) << G_MDSFT_TEXTPERSP) -#define G_TP_PERSP (gI_(0b1) << G_MDSFT_TEXTPERSP) -#define G_CYC_1CYCLE (gI_(0b00) << G_MDSFT_CYCLETYPE) -#define G_CYC_2CYCLE (gI_(0b01) << G_MDSFT_CYCLETYPE) -#define G_CYC_COPY (gI_(0b10) << G_MDSFT_CYCLETYPE) -#define G_CYC_FILL (gI_(0b11) << G_MDSFT_CYCLETYPE) -#define G_PM_NPRIMITIVE (gI_(0b0) << G_MDSFT_PIPELINE) -#define G_PM_1PRIMITIVE (gI_(0b1) << G_MDSFT_PIPELINE) - -/* color conversion constants */ -#define G_CV_K0 (175) -#define G_CV_K1 (-43) -#define G_CV_K2 (-89) -#define G_CV_K3 (222) -#define G_CV_K4 (114) -#define G_CV_K5 (42) - -/* color combiner */ -#define G_CCMUX_COMBINED 0 -#define G_CCMUX_TEXEL0 1 -#define G_CCMUX_TEXEL1 2 -#define G_CCMUX_PRIMITIVE 3 -#define G_CCMUX_SHADE 4 -#define G_CCMUX_ENVIRONMENT 5 -#define G_CCMUX_1 6 -#define G_CCMUX_NOISE 7 -#define G_CCMUX_0 31 -#define G_CCMUX_CENTER 6 -#define G_CCMUX_K4 7 -#define G_CCMUX_SCALE 6 -#define G_CCMUX_COMBINED_ALPHA 7 -#define G_CCMUX_TEXEL0_ALPHA 8 -#define G_CCMUX_TEXEL1_ALPHA 9 -#define G_CCMUX_PRIMITIVE_ALPHA 10 -#define G_CCMUX_SHADE_ALPHA 11 -#define G_CCMUX_ENV_ALPHA 12 -#define G_CCMUX_LOD_FRACTION 13 -#define G_CCMUX_PRIM_LOD_FRAC 14 -#define G_CCMUX_K5 15 -#define G_ACMUX_COMBINED 0 -#define G_ACMUX_TEXEL0 1 -#define G_ACMUX_TEXEL1 2 -#define G_ACMUX_PRIMITIVE 3 -#define G_ACMUX_SHADE 4 -#define G_ACMUX_ENVIRONMENT 5 -#define G_ACMUX_1 6 -#define G_ACMUX_0 7 -#define G_ACMUX_LOD_FRACTION 0 -#define G_ACMUX_PRIM_LOD_FRAC 6 - -/* - * combine modes - * ( A - B ) * C + D -*/ -#define G_CC_MODULATEI \ - TEXEL0, 0, SHADE, 0, \ - 0, 0, 0, SHADE -#define G_CC_MODULATEIA \ - TEXEL0, 0, SHADE, 0, \ - TEXEL0, 0, SHADE, 0 -#define G_CC_MODULATEIDECALA \ - TEXEL0, 0, SHADE, 0, \ - 0, 0, 0, TEXEL0 -#define G_CC_MODULATERGB \ - G_CC_MODULATEI -#define G_CC_MODULATERGBA \ - G_CC_MODULATEIA -#define G_CC_MODULATERGBDECALA \ - G_CC_MODULATEIDECALA -#define G_CC_MODULATEI_PRIM \ - TEXEL0, 0, PRIMITIVE, 0, \ - 0, 0, 0, PRIMITIVE -#define G_CC_MODULATEIA_PRIM \ - TEXEL0, 0, PRIMITIVE, 0, \ - TEXEL0, 0, PRIMITIVE, 0 -#define G_CC_MODULATEIDECALA_PRIM \ - TEXEL0, 0, PRIMITIVE, 0, \ - 0, 0, 0, TEXEL0 -#define G_CC_MODULATERGB_PRIM \ - G_CC_MODULATEI_PRIM -#define G_CC_MODULATERGBA_PRIM \ - G_CC_MODULATEIA_PRIM -#define G_CC_MODULATERGBDECALA_PRIM \ - G_CC_MODULATEIDECALA_PRIM -#define G_CC_DECALRGB \ - 0, 0, 0, TEXEL0, \ - 0, 0, 0, SHADE -#define G_CC_DECALRGBA \ - 0, 0, 0, TEXEL0, \ - 0, 0, 0, TEXEL0 -#define G_CC_BLENDI \ - ENVIRONMENT, SHADE, TEXEL0, SHADE, \ - 0, 0, 0, SHADE -#define G_CC_BLENDIA \ - ENVIRONMENT, SHADE, TEXEL0, SHADE, \ - TEXEL0, 0, SHADE, 0 -#define G_CC_BLENDIDECALA \ - ENVIRONMENT, SHADE, TEXEL0, SHADE, \ - 0, 0, 0, TEXEL0 -#define G_CC_BLENDRGBA \ - TEXEL0, SHADE, TEXEL0_ALPHA, SHADE, \ - 0, 0, 0, SHADE -#define G_CC_BLENDRGBDECALA \ - TEXEL0, SHADE, TEXEL0_ALPHA, SHADE, \ - 0, 0, 0, TEXEL0 -#define G_CC_REFLECTRGB \ - ENVIRONMENT, 0, TEXEL0, SHADE, \ - 0, 0, 0, SHADE -#define G_CC_REFLECTRGBDECALA \ - ENVIRONMENT, 0, TEXEL0, SHADE, \ - 0, 0, 0, TEXEL0 -#define G_CC_HILITERGB \ - PRIMITIVE, SHADE, TEXEL0, SHADE, \ - 0, 0, 0, SHADE -#define G_CC_HILITERGBA \ - PRIMITIVE, SHADE, TEXEL0, SHADE, \ - PRIMITIVE, SHADE, TEXEL0, SHADE -#define G_CC_HILITERGBDECALA \ - PRIMITIVE, SHADE, TEXEL0, SHADE, \ - 0, 0, 0, TEXEL0 -#define G_CC_1CYUV2RGB \ - TEXEL0, K4, K5, TEXEL0, \ - 0, 0, 0, SHADE -#define G_CC_PRIMITIVE \ - 0, 0, 0, PRIMITIVE, \ - 0, 0, 0, PRIMITIVE -#define G_CC_SHADE \ - 0, 0, 0, SHADE, \ - 0, 0, 0, SHADE -#define G_CC_ADDRGB \ - 1, 0, TEXEL0, SHADE, \ - 0, 0, 0, SHADE -#define G_CC_ADDRGBDECALA \ - 1, 0, TEXEL0, SHADE, \ - 0, 0, 0, TEXEL0 -#define G_CC_SHADEDECALA \ - 0, 0, 0, SHADE, \ - 0, 0, 0, TEXEL0 -#define G_CC_BLENDPE \ - PRIMITIVE, ENVIRONMENT, TEXEL0, ENVIRONMENT, \ - TEXEL0, 0, SHADE, 0 -#define G_CC_BLENDPEDECALA \ - PRIMITIVE, ENVIRONMENT, TEXEL0, ENVIRONMENT, \ - 0, 0, 0, TEXEL0 -#define G_CC_TRILERP \ - TEXEL1, TEXEL0, LOD_FRACTION, TEXEL0, \ - TEXEL1, TEXEL0, LOD_FRACTION, TEXEL0 -#define G_CC_TEMPLERP \ - TEXEL1, TEXEL0, PRIM_LOD_FRAC, TEXEL0, \ - TEXEL1, TEXEL0, PRIM_LOD_FRAC, TEXEL0 -#define G_CC_INTERFERENCE \ - TEXEL0, 0, TEXEL1, 0, \ - TEXEL0, 0, TEXEL1, 0 -#define _G_CC_BLENDPE \ - ENVIRONMENT, PRIMITIVE, TEXEL0, PRIMITIVE, \ - TEXEL0, 0, SHADE, 0 -#define _G_CC_BLENDPEDECALA \ - ENVIRONMENT, PRIMITIVE, TEXEL0, PRIMITIVE, \ - 0, 0, 0, TEXEL0 -#define _G_CC_SPARSEST \ - PRIMITIVE, TEXEL0, LOD_FRACTION, TEXEL0, \ - PRIMITIVE, TEXEL0, LOD_FRACTION, TEXEL0 -#define _G_CC_TWOCOLORTEX \ - PRIMITIVE, SHADE, TEXEL0, SHADE, \ - 0, 0, 0, SHADE -#define G_CC_MODULATEI2 \ - COMBINED, 0, SHADE, 0, \ - 0, 0, 0, SHADE -#define G_CC_MODULATEIA2 \ - COMBINED, 0, SHADE, 0, \ - COMBINED, 0, SHADE, 0 -#define G_CC_MODULATERGB2 \ - G_CC_MODULATEI2 -#define G_CC_MODULATERGBA2 \ - G_CC_MODULATEIA2 -#define G_CC_MODULATEI_PRIM2 \ - COMBINED, 0, PRIMITIVE, 0, \ - 0, 0, 0, PRIMITIVE -#define G_CC_MODULATEIA_PRIM2 \ - COMBINED, 0, PRIMITIVE, 0, \ - COMBINED, 0, PRIMITIVE, 0 -#define G_CC_MODULATERGB_PRIM2 \ - G_CC_MODULATEI_PRIM2 -#define G_CC_MODULATERGBA_PRIM2 \ - G_CC_MODULATEIA_PRIM2 -#define G_CC_DECALRGB2 \ - 0, 0, 0, COMBINED, \ - 0, 0, 0, SHADE -#define G_CC_BLENDI2 \ - ENVIRONMENT, SHADE, COMBINED, SHADE, \ - 0, 0, 0, SHADE -#define G_CC_BLENDIA2 \ - ENVIRONMENT, SHADE, COMBINED, SHADE, \ - COMBINED, 0, SHADE, 0 -#define G_CC_HILITERGB2 \ - ENVIRONMENT, COMBINED, TEXEL0, COMBINED, \ - 0, 0, 0, SHADE -#define G_CC_HILITERGBA2 \ - ENVIRONMENT, COMBINED, TEXEL0, COMBINED, \ - ENVIRONMENT, COMBINED, TEXEL0, COMBINED -#define G_CC_HILITERGBDECALA2 \ - ENVIRONMENT, COMBINED, TEXEL0, COMBINED, \ - 0, 0, 0, TEXEL0 -#define G_CC_HILITERGBPASSA2 \ - ENVIRONMENT, COMBINED, TEXEL0, COMBINED, \ - 0, 0, 0, COMBINED -#define G_CC_CHROMA_KEY2 \ - TEXEL0, CENTER, SCALE, 0, \ - 0, 0, 0, 0 -#define G_CC_YUV2RGB \ - TEXEL1, K4, K5, TEXEL1, \ - 0, 0, 0, 0 -#define G_CC_PASS2 \ - 0, 0, 0, COMBINED, \ - 0, 0, 0, COMBINED -#define G_CC_LERP(a0, b0, c0, d0, Aa0, Ab0, Ac0, Ad0, \ - a1, b1, c1, d1, Aa1, Ab1, Ac1, Ad1) \ - ( \ - gFL_(G_CCMUX_##a0, 4, 52) | \ - gFL_(G_CCMUX_##c0, 5, 47) | \ - gFL_(G_ACMUX_##Aa0, 3, 44) | \ - gFL_(G_ACMUX_##Ac0, 3, 41) | \ - gFL_(G_CCMUX_##a1, 4, 37) | \ - gFL_(G_CCMUX_##c1, 5, 32) | \ - gFL_(G_CCMUX_##b0, 4, 28) | \ - gFL_(G_CCMUX_##b1, 4, 24) | \ - gFL_(G_ACMUX_##Aa1, 3, 21) | \ - gFL_(G_ACMUX_##Ac1, 3, 18) | \ - gFL_(G_CCMUX_##d0, 3, 15) | \ - gFL_(G_ACMUX_##Ab0, 3, 12) | \ - gFL_(G_ACMUX_##Ad0, 3, 9) | \ - gFL_(G_CCMUX_##d1, 3, 6) | \ - gFL_(G_ACMUX_##Ab1, 3, 3) | \ - gFL_(G_ACMUX_##Ad1, 3, 0) \ - ) -#define G_CC_MODE(mode1, mode2) G_CC_LERP(mode1, mode2) - -/* scissor modes */ -#define G_SC_NON_INTERLACE gI_(0b00) -#define G_SC_EVEN_INTERLACE gI_(0b10) -#define G_SC_ODD_INTERLACE gI_(0b11) - -/* display list branch flags */ -#define G_DL_PUSH gI_(0b0) -#define G_DL_NOPUSH gI_(0b1) - -/* conditional branching flags (f3dex and f3dex2) */ -#if defined(F3DEX_GBI) || defined(F3DEX_GBI_2) -# define G_BZ_PERSP 0 -# define G_BZ_ORTHO 1 -#endif - -/* matrix params */ -#define G_MTX_MUL (gI_(0b0) << 1) -#define G_MTX_LOAD (gI_(0b1) << 1) - -/* matrix params for fast3d and f3dex */ -#if defined(F3D_GBI) || defined(F3DEX_GBI) -# define G_MTX_MODELVIEW (gI_(0b0) << 0) -# define G_MTX_PROJECTION (gI_(0b1) << 0) -# define G_MTX_NOPUSH (gI_(0b0) << 2) -# define G_MTX_PUSH (gI_(0b1) << 2) -#endif - -/* matrix params for f3dex2 */ -#if defined(F3DEX_GBI_2) -# define G_MTX_NOPUSH (gI_(0b0) << 0) -# define G_MTX_PUSH (gI_(0b1) << 0) -# define G_MTX_MODELVIEW (gI_(0b0) << 2) -# define G_MTX_PROJECTION (gI_(0b1) << 2) -#endif - -/* moveword indices */ -#define G_MW_MATRIX 0 -#define G_MW_NUMLIGHT 2 -#define G_MW_CLIP 4 -#define G_MW_SEGMENT 6 -#define G_MW_FOG 8 -#define G_MW_GENSTAT 8 -#define G_MW_LIGHTCOL 10 -#define G_MW_PERSPNORM 14 - -/* moveword indices for fast3d and f3dex */ -#if defined(F3D_GBI) || defined(F3DEX_GBI) -# define G_MW_POINTS 12 -#endif - -/* moveword indices for f3dex2 */ -#if defined(F3DEX_GBI_2) -# define G_MW_FORCEMTX 12 -#endif - -/* moveword offsets */ -#define G_MWO_NUMLIGHT gI_(0x00) -#define G_MWO_CLIP_RNX gI_(0x04) -#define G_MWO_CLIP_RNY gI_(0x0C) -#define G_MWO_CLIP_RPX gI_(0x14) -#define G_MWO_CLIP_RPY gI_(0x1C) -#define G_MWO_SEGMENT_0 gI_(0x00) -#define G_MWO_SEGMENT_1 gI_(0x04) -#define G_MWO_SEGMENT_2 gI_(0x08) -#define G_MWO_SEGMENT_3 gI_(0x0C) -#define G_MWO_SEGMENT_4 gI_(0x10) -#define G_MWO_SEGMENT_5 gI_(0x14) -#define G_MWO_SEGMENT_6 gI_(0x18) -#define G_MWO_SEGMENT_7 gI_(0x1C) -#define G_MWO_SEGMENT_8 gI_(0x20) -#define G_MWO_SEGMENT_9 gI_(0x24) -#define G_MWO_SEGMENT_A gI_(0x28) -#define G_MWO_SEGMENT_B gI_(0x2C) -#define G_MWO_SEGMENT_C gI_(0x30) -#define G_MWO_SEGMENT_D gI_(0x34) -#define G_MWO_SEGMENT_E gI_(0x38) -#define G_MWO_SEGMENT_F gI_(0x3C) -#define G_MWO_FOG gI_(0x00) -#define G_MWO_aLIGHT_1 gI_(0x00) -#define G_MWO_bLIGHT_1 gI_(0x04) -#define G_MWO_MATRIX_XX_XY_I gI_(0x00) -#define G_MWO_MATRIX_XZ_XW_I gI_(0x04) -#define G_MWO_MATRIX_YX_YY_I gI_(0x08) -#define G_MWO_MATRIX_YZ_YW_I gI_(0x0C) -#define G_MWO_MATRIX_ZX_ZY_I gI_(0x10) -#define G_MWO_MATRIX_ZZ_ZW_I gI_(0x14) -#define G_MWO_MATRIX_WX_WY_I gI_(0x18) -#define G_MWO_MATRIX_WZ_WW_I gI_(0x1C) -#define G_MWO_MATRIX_XX_XY_F gI_(0x20) -#define G_MWO_MATRIX_XZ_XW_F gI_(0x24) -#define G_MWO_MATRIX_YX_YY_F gI_(0x28) -#define G_MWO_MATRIX_YZ_YW_F gI_(0x2C) -#define G_MWO_MATRIX_ZX_ZY_F gI_(0x30) -#define G_MWO_MATRIX_ZZ_ZW_F gI_(0x34) -#define G_MWO_MATRIX_WX_WY_F gI_(0x38) -#define G_MWO_MATRIX_WZ_WW_F gI_(0x3C) -#define G_MWO_POINT_RGBA gI_(0x10) -#define G_MWO_POINT_ST gI_(0x14) -#define G_MWO_POINT_XYSCREEN gI_(0x18) -#define G_MWO_POINT_ZSCREEN gI_(0x1C) - -/* moveword offsets for fast3d and f3dex */ -#if defined(F3D_GBI) || defined(F3DEX_GBI) -# define G_MWO_aLIGHT_2 gI_(0x20) -# define G_MWO_bLIGHT_2 gI_(0x24) -# define G_MWO_aLIGHT_3 gI_(0x40) -# define G_MWO_bLIGHT_3 gI_(0x44) -# define G_MWO_aLIGHT_4 gI_(0x60) -# define G_MWO_bLIGHT_4 gI_(0x64) -# define G_MWO_aLIGHT_5 gI_(0x80) -# define G_MWO_bLIGHT_5 gI_(0x84) -# define G_MWO_aLIGHT_6 gI_(0xA0) -# define G_MWO_bLIGHT_6 gI_(0xA4) -# define G_MWO_aLIGHT_7 gI_(0xC0) -# define G_MWO_bLIGHT_7 gI_(0xC4) -# define G_MWO_aLIGHT_8 gI_(0xE0) -# define G_MWO_bLIGHT_8 gI_(0xE4) -#endif - -/* moveword offsets for f3dex2 */ -#if defined(F3DEX_GBI_2) -# define G_MWO_aLIGHT_2 gI_(0x18) -# define G_MWO_bLIGHT_2 gI_(0x1C) -# define G_MWO_aLIGHT_3 gI_(0x30) -# define G_MWO_bLIGHT_3 gI_(0x34) -# define G_MWO_aLIGHT_4 gI_(0x48) -# define G_MWO_bLIGHT_4 gI_(0x4C) -# define G_MWO_aLIGHT_5 gI_(0x60) -# define G_MWO_bLIGHT_5 gI_(0x64) -# define G_MWO_aLIGHT_6 gI_(0x78) -# define G_MWO_bLIGHT_6 gI_(0x7C) -# define G_MWO_aLIGHT_7 gI_(0x90) -# define G_MWO_bLIGHT_7 gI_(0x94) -# define G_MWO_aLIGHT_8 gI_(0xA8) -# define G_MWO_bLIGHT_8 gI_(0xAC) -#endif - -/* movemem params for fast3d and f3dex */ -#if defined(F3D_GBI) || defined(F3DEX_GBI) -# define G_MV_VIEWPORT 128 -# define G_MV_LOOKATY 130 -# define G_MV_LOOKATX 132 -# define G_MV_L0 134 -# define G_MV_L1 136 -# define G_MV_L2 138 -# define G_MV_L3 140 -# define G_MV_L4 142 -# define G_MV_L5 144 -# define G_MV_L6 146 -# define G_MV_L7 148 -# define G_MV_TXTATT 150 -# define G_MV_MATRIX_2 152 -# define G_MV_MATRIX_3 154 -# define G_MV_MATRIX_4 156 -# define G_MV_MATRIX_1 158 -#endif - -/* movemem params for f3dex2 */ -#if defined(F3DEX_GBI_2) -# define G_MV_MMTX 2 -# define G_MV_PMTX 6 -# define G_MV_VIEWPORT 8 -# define G_MV_LIGHT 10 -# define G_MV_POINT 12 -# define G_MV_MATRIX 14 -# define G_MVO_LOOKATX gI_(0 * 0x18) -# define G_MVO_LOOKATY gI_(1 * 0x18) -# define G_MVO_L0 gI_(2 * 0x18) -# define G_MVO_L1 gI_(3 * 0x18) -# define G_MVO_L2 gI_(4 * 0x18) -# define G_MVO_L3 gI_(5 * 0x18) -# define G_MVO_L4 gI_(6 * 0x18) -# define G_MVO_L5 gI_(7 * 0x18) -# define G_MVO_L6 gI_(8 * 0x18) -# define G_MVO_L7 gI_(9 * 0x18) -#endif - -/* frustum ratios */ -#define FRUSTRATIO_1 gI_(1) -#define FRUSTRATIO_2 gI_(2) -#define FRUSTRATIO_3 gI_(3) -#define FRUSTRATIO_4 gI_(4) -#define FRUSTRATIO_5 gI_(5) -#define FRUSTRATIO_6 gI_(6) - -/* light params */ -#define NUMLIGHTS_0 1 -#define NUMLIGHTS_1 1 -#define NUMLIGHTS_2 2 -#define NUMLIGHTS_3 3 -#define NUMLIGHTS_4 4 -#define NUMLIGHTS_5 5 -#define NUMLIGHTS_6 6 -#define NUMLIGHTS_7 7 -#define LIGHT_1 1 -#define LIGHT_2 2 -#define LIGHT_3 3 -#define LIGHT_4 4 -#define LIGHT_5 5 -#define LIGHT_6 6 -#define LIGHT_7 7 -#define LIGHT_8 8 - -/* light params for fast3d and f3dex */ -#if defined(F3D_GBI) || defined(F3DEX_GBI) -# define NUML(n) (((n) + 1) * 32 + 0x80000000) -#endif - -/* light params for f3dex2 */ -#if defined(F3DEX_GBI_2) -# define NUML(n) ((n) * 0x18) -#endif - -/* background load types */ -#define G_BGLT_LOADBLOCK gI_(0x0033) -#define G_BGLT_LOADTILE gI_(0xFFF4) - -/* background flags */ -#define G_BG_FLAG_FLIPS (gI_(0b1) << 0) -#define G_BG_FLAG_FLIPT (gI_(0b1) << 1) - -/* object load types */ -#define G_OBJLT_TXTRBLOCK gI_(0x00001033) -#define G_OBJLT_TXTRTILE gI_(0x00FC1034) -#define G_OBJLT_TLUT gI_(0x00000030) - -/* object flags */ -#define G_OBJ_FLAG_FLIPS (gI_(0b1) << 0) -#define G_OBJ_FLAG_FLIPT (gI_(0b1) << 4) - -/* color macros */ -#define G_MAXZ 0x03FF -#define G_MAXFBZ 0x3FFF -#define GPACK_RGBA5551(r, g, b, a) \ - ( \ - gF_(r, 5, 11) | \ - gF_(g, 5, 6) | \ - gF_(b, 5, 1) | \ - gF_(a, 1, 0) \ - ) -#define GPACK_RGBA8888(r, g, b, a) \ - ( \ - gF_(r, 8, 24) | \ - gF_(g, 8, 16) | \ - gF_(b, 8, 8) | \ - gF_(a, 8, 0) \ - ) -#define GPACK_RGB24A8(rgb, a) (gF_(rgb, 24, 8) | gF_(a, 8, 0)) -#define GPACK_ZDZ(z, dz) (gF_(z, 14, 2) | gF_(dz, 2, 0)) - -/* structure definition macros */ -#define gdSPDefMtx(xx, xy, xz, xw, \ - yx, yy, yz, yw, \ - zx, zy, zz, zw, \ - wx, wy, wz, ww) \ - ( \ - (Mtx) \ - { \ - .i = \ - { \ - (qs1616(xx) >> 16) & 0xFFFF, \ - (qs1616(xy) >> 16) & 0xFFFF, \ - (qs1616(xz) >> 16) & 0xFFFF, \ - (qs1616(xw) >> 16) & 0xFFFF, \ - (qs1616(yx) >> 16) & 0xFFFF, \ - (qs1616(yy) >> 16) & 0xFFFF, \ - (qs1616(yz) >> 16) & 0xFFFF, \ - (qs1616(yw) >> 16) & 0xFFFF, \ - (qs1616(zx) >> 16) & 0xFFFF, \ - (qs1616(zy) >> 16) & 0xFFFF, \ - (qs1616(zz) >> 16) & 0xFFFF, \ - (qs1616(zw) >> 16) & 0xFFFF, \ - (qs1616(wx) >> 16) & 0xFFFF, \ - (qs1616(wy) >> 16) & 0xFFFF, \ - (qs1616(wz) >> 16) & 0xFFFF, \ - (qs1616(ww) >> 16) & 0xFFFF, \ - }, \ - .f = \ - { \ - qs1616(xx) & 0xFFFF, \ - qs1616(xy) & 0xFFFF, \ - qs1616(xz) & 0xFFFF, \ - qs1616(xw) & 0xFFFF, \ - qs1616(yx) & 0xFFFF, \ - qs1616(yy) & 0xFFFF, \ - qs1616(yz) & 0xFFFF, \ - qs1616(yw) & 0xFFFF, \ - qs1616(zx) & 0xFFFF, \ - qs1616(zy) & 0xFFFF, \ - qs1616(zz) & 0xFFFF, \ - qs1616(zw) & 0xFFFF, \ - qs1616(wx) & 0xFFFF, \ - qs1616(wy) & 0xFFFF, \ - qs1616(wz) & 0xFFFF, \ - qs1616(ww) & 0xFFFF, \ - } \ - } \ - ) -#define gdSPDefLookAt(rx, ry, rz, ux, uy, uz) \ - ( \ - (LookAt) \ - { \ - .l[0].l = \ - { \ - .col = {0, 0, 0}, \ - .colc = {0, 0, 0}, \ - .dir = {rx, ry, rz}, \ - }, \ - .l[1].l = \ - { \ - .col = {0, 0x80, 0}, \ - .colc = {0, 0x80, 0}, \ - .dir = {ux, uy, uz}, \ - }, \ - } \ - ) -#define gdSPDefLights0(ar, ag, ab) \ - ( \ - (Lights0) \ - { \ - .a.l = \ - { \ - .col = {ar, ag, ab}, \ - .colc = {ar, ag, ab}, \ - }, \ - .l[0].l = \ - { \ - } \ - } \ - ) -#define gdSPDefLights1(ar, ag, ab, \ - r1, g1, b1, x1, y1, z1) \ - ( \ - (Lights1) \ - { \ - .a.l = \ - { \ - .col = {ar, ag, ab}, \ - .colc = {ar, ag, ab}, \ - }, \ - .l[0].l = \ - { \ - .col = {r1, g1, b1}, \ - .colc = {r1, g1, b1}, \ - .dir = {x1, y1, z1}, \ - } \ - } \ - ) -#define gdSPDefLights2(ar, ag, ab, \ - r1, g1, b1, x1, y1, z1, \ - r2, g2, b2, x2, y2, z2) \ - ( \ - (Lights2) \ - { \ - .a.l = \ - { \ - .col = {ar, ag, ab}, \ - .colc = {ar, ag, ab}, \ - }, \ - .l[0].l = \ - { \ - .col = {r1, g1, b1}, \ - .colc = {r1, g1, b1}, \ - .dir = {x1, y1, z1}, \ - } \ - .l[1].l = \ - { \ - .col = {r2, g2, b2}, \ - .colc = {r2, g2, b2}, \ - .dir = {x2, y2, z2}, \ - } \ - } \ - ) -#define gdSPDefLights3(ar, ag, ab, \ - r1, g1, b1, x1, y1, z1, \ - r2, g2, b2, x2, y2, z2, \ - r3, g3, b3, x3, y3, z3) \ - ( \ - (Lights3) \ - { \ - .a.l = \ - { \ - .col = {ar, ag, ab}, \ - .colc = {ar, ag, ab}, \ - }, \ - .l[0].l = \ - { \ - .col = {r1, g1, b1}, \ - .colc = {r1, g1, b1}, \ - .dir = {x1, y1, z1}, \ - } \ - .l[1].l = \ - { \ - .col = {r2, g2, b2}, \ - .colc = {r2, g2, b2}, \ - .dir = {x2, y2, z2}, \ - } \ - .l[2].l = \ - { \ - .col = {r3, g3, b3}, \ - .colc = {r3, g3, b3}, \ - .dir = {x3, y3, z3}, \ - } \ - } \ - ) -#define gdSPDefLights4(ar, ag, ab, \ - r1, g1, b1, x1, y1, z1, \ - r2, g2, b2, x2, y2, z2, \ - r3, g3, b3, x3, y3, z3, \ - r4, g4, b4, x4, y4, z4) \ - ( \ - (Lights4) \ - { \ - .a.l = \ - { \ - .col = {ar, ag, ab}, \ - .colc = {ar, ag, ab}, \ - }, \ - .l[0].l = \ - { \ - .col = {r1, g1, b1}, \ - .colc = {r1, g1, b1}, \ - .dir = {x1, y1, z1}, \ - } \ - .l[1].l = \ - { \ - .col = {r2, g2, b2}, \ - .colc = {r2, g2, b2}, \ - .dir = {x2, y2, z2}, \ - } \ - .l[2].l = \ - { \ - .col = {r3, g3, b3}, \ - .colc = {r3, g3, b3}, \ - .dir = {x3, y3, z3}, \ - } \ - .l[3].l = \ - { \ - .col = {r4, g4, b4}, \ - .colc = {r4, g4, b4}, \ - .dir = {x4, y4, z4}, \ - } \ - } \ - ) -#define gdSPDefLights5(ar, ag, ab, \ - r1, g1, b1, x1, y1, z1, \ - r2, g2, b2, x2, y2, z2, \ - r3, g3, b3, x3, y3, z3, \ - r4, g4, b4, x4, y4, z4, \ - r5, g5, b5, x5, y5, z5) \ - ( \ - (Lights5) \ - { \ - .a.l = \ - { \ - .col = {ar, ag, ab}, \ - .colc = {ar, ag, ab}, \ - }, \ - .l[0].l = \ - { \ - .col = {r1, g1, b1}, \ - .colc = {r1, g1, b1}, \ - .dir = {x1, y1, z1}, \ - } \ - .l[1].l = \ - { \ - .col = {r2, g2, b2}, \ - .colc = {r2, g2, b2}, \ - .dir = {x2, y2, z2}, \ - } \ - .l[2].l = \ - { \ - .col = {r3, g3, b3}, \ - .colc = {r3, g3, b3}, \ - .dir = {x3, y3, z3}, \ - } \ - .l[3].l = \ - { \ - .col = {r4, g4, b4}, \ - .colc = {r4, g4, b4}, \ - .dir = {x4, y4, z4}, \ - } \ - .l[4].l = \ - { \ - .col = {r5, g5, b5}, \ - .colc = {r5, g5, b5}, \ - .dir = {x5, y5, z5}, \ - } \ - } \ - ) -#define gdSPDefLights6(ar, ag, ab, \ - r1, g1, b1, x1, y1, z1, \ - r2, g2, b2, x2, y2, z2, \ - r3, g3, b3, x3, y3, z3, \ - r4, g4, b4, x4, y4, z4, \ - r5, g5, b5, x5, y5, z5, \ - r6, g6, b6, x6, y6, z6)\ - ( \ - (Lights6) \ - { \ - .a.l = \ - { \ - .col = {ar, ag, ab}, \ - .colc = {ar, ag, ab}, \ - }, \ - .l[0].l = \ - { \ - .col = {r1, g1, b1}, \ - .colc = {r1, g1, b1}, \ - .dir = {x1, y1, z1}, \ - } \ - .l[1].l = \ - { \ - .col = {r2, g2, b2}, \ - .colc = {r2, g2, b2}, \ - .dir = {x2, y2, z2}, \ - } \ - .l[2].l = \ - { \ - .col = {r3, g3, b3}, \ - .colc = {r3, g3, b3}, \ - .dir = {x3, y3, z3}, \ - } \ - .l[3].l = \ - { \ - .col = {r4, g4, b4}, \ - .colc = {r4, g4, b4}, \ - .dir = {x4, y4, z4}, \ - } \ - .l[4].l = \ - { \ - .col = {r5, g5, b5}, \ - .colc = {r5, g5, b5}, \ - .dir = {x5, y5, z5}, \ - } \ - .l[5].l = \ - { \ - .col = {r6, g6, b6}, \ - .colc = {r6, g6, b6}, \ - .dir = {x6, y6, z6}, \ - } \ - } \ - ) -#define gdSPDefLights7(ar, ag, ab, \ - r1, g1, b1, x1, y1, z1, \ - r2, g2, b2, x2, y2, z2, \ - r3, g3, b3, x3, y3, z3, \ - r4, g4, b4, x4, y4, z4, \ - r5, g5, b5, x5, y5, z5, \ - r6, g6, b6, x6, y6, z6, \ - r7, g7, b7, x7, y7, z7) \ - ( \ - (Lights7) \ - { \ - .a.l = \ - { \ - .col = {ar, ag, ab}, \ - .colc = {ar, ag, ab}, \ - }, \ - .l[0].l = \ - { \ - .col = {r1, g1, b1}, \ - .colc = {r1, g1, b1}, \ - .dir = {x1, y1, z1}, \ - } \ - .l[1].l = \ - { \ - .col = {r2, g2, b2}, \ - .colc = {r2, g2, b2}, \ - .dir = {x2, y2, z2}, \ - } \ - .l[2].l = \ - { \ - .col = {r3, g3, b3}, \ - .colc = {r3, g3, b3}, \ - .dir = {x3, y3, z3}, \ - } \ - .l[3].l = \ - { \ - .col = {r4, g4, b4}, \ - .colc = {r4, g4, b4}, \ - .dir = {x4, y4, z4}, \ - } \ - .l[4].l = \ - { \ - .col = {r5, g5, b5}, \ - .colc = {r5, g5, b5}, \ - .dir = {x5, y5, z5}, \ - } \ - .l[5].l = \ - { \ - .col = {r6, g6, b6}, \ - .colc = {r6, g6, b6}, \ - .dir = {x6, y6, z6}, \ - } \ - .l[6].l = \ - { \ - .col = {r7, g7, b7}, \ - .colc = {r7, g7, b7}, \ - .dir = {x7, y7, z7}, \ - } \ - } \ - ) -#define gdSPDefVtx(x, y, z, s, t) \ - ( \ - (Vtx) \ - { \ - .v = \ - { \ - .ob = {x, y, z}, \ - .tc = {qs105(s), qs105(t)}, \ - } \ - } \ - ) -#define gdSPDefVtxC(x, y, z, s, t, cr, cg, cb, ca) \ - ( \ - (Vtx) \ - { \ - .v = \ - { \ - .ob = {x, y, z}, \ - .tc = {qs105(s), qs105(t)}, \ - .cn = {cr, cg, cb, ca}, \ - } \ - } \ - ) -#define gdSPDefVtxN(x, y, z, s, t, nx, ny, nz, ca) \ - ( \ - (Vtx) \ - { \ - .n = \ - { \ - .ob = {x, y, z}, \ - .tc = {qs105(s), qs105(t)}, \ - .n = {nx, ny, nz}, \ - .a = ca \ - } \ - } \ - ) - -/* instruction macros */ - -#define gsDPFillRectangle(ulx, uly, lrx, lry) \ - gO_( \ - G_FILLRECT, \ - gF_(lrx, 10, 14) | \ - gF_(lry, 10, 2), \ - gF_(ulx, 10, 14) | \ - gF_(uly, 10, 2)) - -#define gsDPScisFillRectangle(ulx, uly, lrx, lry) \ - gsDPFillRectangle(gScC_(ulx), gScC_(uly), gScC_(lrx), gScC_(lry)) - -#define gsDPFullSync() \ - gO_(G_RDPFULLSYNC, 0, 0) - -#define gsDPLoadSync() \ - gO_(G_RDPLOADSYNC, 0, 0) - -#define gsDPTileSync() \ - gO_(G_RDPTILESYNC, 0, 0) - -#define gsDPPipeSync() \ - gO_(G_RDPPIPESYNC, 0, 0) - -#define gsDPLoadTLUT_pal16(pal, dram) \ - gsDPLoadTLUT(16, 256 + (gI_(pal) & 0xF) * 16, dram) - -#define gsDPLoadTLUT_pal256(dram) \ - gsDPLoadTLUT(256, 256, dram) - -#define gLTB_(timg, fmt, siz, width, height, pal, \ - cms, cmt, masks, maskt, shifts, shiftt, \ - dxt, tmem, rt, line) \ - gsDPSetTextureImage(fmt, G_SIZ_LDSIZ(siz), 1, timg), \ - gsDPSetTile( \ - fmt, G_SIZ_LDSIZ(siz), 0, tmem, G_TX_LOADTILE, 0, \ - cmt, maskt, shiftt, \ - cms, masks, shifts), \ - gsDPLoadSync(), \ - gsDPLoadBlock( \ - G_TX_LOADTILE, 0, 0, \ - G_LTB_LRS(width, height, siz), \ - dxt), \ - gsDPPipeSync(), \ - gsDPSetTile( \ - fmt, siz, line, tmem, rt, pal, \ - cmt, maskt, shiftt, \ - cms, masks, shifts), \ - gsDPSetTileSize(rt, 0, 0, qu102((width) - 1), qu102((height) - 1)) - -#define gsDPLoadTextureBlock(timg, fmt, siz, width, height, pal, \ - cms, cmt, masks, maskt, shifts, shiftt) \ - gLTB_( \ - timg, fmt, siz, width, height, pal, \ - cms, cmt, masks, maskt, shifts, shiftt, \ - G_DXT(siz, width), 0x0, G_TX_RENDERTILE, \ - ((width) * G_SIZ_LDBITS(siz) + 63) / 64) - -#define gsDPLoadTextureBlockS(timg, fmt, siz, width, height, pal, \ - cms, cmt, masks, maskt, shifts, shiftt) \ - gLTB_( \ - timg, fmt, siz, width, height, pal, \ - cms, cmt, masks, maskt, shifts, shiftt, \ - 0, 0x0, G_TX_RENDERTILE, \ - ((width) * G_SIZ_LDBITS(siz) + 63) / 64) - -#define gsDPLoadTextureBlock_4b(timg, fmt, width, height, pal, \ - cms, cmt, masks, maskt, shifts, shiftt) \ - gLTB_( \ - timg, fmt, G_IM_SIZ_4b, width, height, pal, \ - cms, cmt, masks, maskt, shifts, shiftt, \ - G_DXT(G_IM_SIZ_4b, width), 0x0, G_TX_RENDERTILE, \ - ((width) * 4 + 63) / 64) - -#define gsDPLoadTextureBlock_4bS(timg, fmt, width, height, pal, \ - cms, cmt, masks, maskt, shifts, shiftt) \ - gLTB_( \ - timg, fmt, G_IM_SIZ_4b, width, height, pal, \ - cms, cmt, masks, maskt, shifts, shiftt, \ - 0, 0x0, G_TX_RENDERTILE, \ - ((width) * 4 + 63) / 64) - -#define gsDPLoadTextureBlockYuv(timg, fmt, siz, width, height, pal, \ - cms, cmt, masks, maskt, shifts, shiftt) \ - gLTB_( \ - timg, fmt, siz, width, height, pal, \ - cms, cmt, masks, maskt, shifts, shiftt, \ - G_DXT(siz, width), 0x0, G_TX_RENDERTILE, \ - ((width) + 7) / 8) - -#define gsDPLoadTextureBlockYuvS(timg, fmt, siz, width, height, pal, \ - cms, cmt, masks, maskt, shifts, shiftt) \ - gLTB_( \ - timg, fmt, siz, width, height, pal, \ - cms, cmt, masks, maskt, shifts, shiftt, \ - 0, 0x0, G_TX_RENDERTILE, \ - ((width) + 7) / 8) - -#define _gsDPLoadTextureBlock(timg, tmem, fmt, siz, width, height, pal, \ - cms, cmt, masks, maskt, shifts, shiftt) \ - gLTB_( \ - timg, fmt, siz, width, height, pal, \ - cms, cmt, masks, maskt, shifts, shiftt, \ - G_DXT(siz, width), tmem, G_TX_RENDERTILE, \ - ((width) * G_SIZ_LDBITS(siz) + 63) / 64) - -#define _gsDPLoadTextureBlockS(timg, tmem, fmt, siz, width, height, pal, \ - cms, cmt, masks, maskt, shifts, shiftt) \ - gLTB_( \ - timg, fmt, siz, width, height, pal, \ - cms, cmt, masks, maskt, shifts, shiftt, \ - 0, tmem, G_TX_RENDERTILE, \ - ((width) * G_SIZ_LDBITS(siz) + 63) / 64) - -#define _gsDPLoadTextureBlock_4b(timg, tmem, fmt, width, height, pal, \ - cms, cmt, masks, maskt, shifts, shiftt) \ - gLTB_( \ - timg, fmt, G_IM_SIZ_4b, width, height, pal, \ - cms, cmt, masks, maskt, shifts, shiftt, \ - G_DXT(G_IM_SIZ_4b, width), tmem, G_TX_RENDERTILE, \ - ((width) * 4 + 63) / 64) - -#define _gsDPLoadTextureBlock_4bS(timg, tmem, fmt, width, height, pal, \ - cms, cmt, masks, maskt, shifts, shiftt) \ - gLTB_( \ - timg, fmt, G_IM_SIZ_4b, width, height, pal, \ - cms, cmt, masks, maskt, shifts, shiftt, \ - 0, tmem, G_TX_RENDERTILE, \ - ((width) * 4 + 63) / 64) - -#define _gsDPLoadTextureBlockYuv(timg, tmem, fmt, siz, width, height, pal, \ - cms, cmt, masks, maskt, shifts, shiftt) \ - gLTB_( \ - timg, fmt, siz, width, height, pal, \ - cms, cmt, masks, maskt, shifts, shiftt, \ - G_DXT(siz, width), tmem, G_TX_RENDERTILE, \ - ((width) + 7) / 8) - -#define _gsDPLoadTextureBlockYuvS(timg, tmem, fmt, siz, width, height, pal, \ - cms, cmt, masks, maskt, shifts, shiftt) \ - gLTB_( \ - timg, fmt, siz, width, height, pal, \ - cms, cmt, masks, maskt, shifts, shiftt, \ - 0, tmem, G_TX_RENDERTILE, \ - ((width) + 7) / 8) - -#define gsDPLoadMultiBlock(timg, tmem, rt, fmt, siz, width, height, pal, \ - cms, cmt, masks, maskt, shifts, shiftt) \ - gLTB_( \ - timg, fmt, siz, width, height, pal, \ - cms, cmt, masks, maskt, shifts, shiftt, \ - G_DXT(siz, width), tmem, rt, \ - ((width) * G_SIZ_LDBITS(siz) + 63) / 64) - -#define gsDPLoadMultiBlockS(timg, tmem, rt, fmt, siz, width, height, pal, \ - cms, cmt, masks, maskt, shifts, shiftt) \ - gLTB_( \ - timg, fmt, siz, width, height, pal, \ - cms, cmt, masks, maskt, shifts, shiftt, \ - 0, tmem, rt, \ - ((width) * G_SIZ_LDBITS(siz) + 63) / 64) - -#define gsDPLoadMultiBlock_4b(timg, tmem, rt, fmt, width, height, pal, \ - cms, cmt, masks, maskt, shifts, shiftt) \ - gLTB_( \ - timg, fmt, G_IM_SIZ_4b, width, height, pal, \ - cms, cmt, masks, maskt, shifts, shiftt, \ - G_DXT(G_IM_SIZ_4b, width), tmem, rt, \ - ((width) * 4 + 63) / 64) - -#define gsDPLoadMultiBlock_4bS(timg, tmem, rt, fmt, width, height, pal, \ - cms, cmt, masks, maskt, shifts, shiftt) \ - gLTB_( \ - timg, fmt, G_IM_SIZ_4b, width, height, pal, \ - cms, cmt, masks, maskt, shifts, shiftt, \ - 0, tmem, rt, \ - ((width) * 4 + 63) / 64) - -#define gsDPLoadMultiBlockYuv(timg, tmem, rt, fmt, siz, width, height, pal, \ - cms, cmt, masks, maskt, shifts, shiftt) \ - gLTB_( \ - timg, fmt, siz, width, height, pal, \ - cms, cmt, masks, maskt, shifts, shiftt, \ - G_DXT(siz, width), tmem, rt, \ - ((width) + 7) / 8) - -#define gsDPLoadMultiBlockYuvS(timg, tmem, rt, fmt, siz, width, height, pal, \ - cms, cmt, masks, maskt, shifts, shiftt) \ - gLTB_( \ - timg, fmt, siz, width, height, pal, \ - cms, cmt, masks, maskt, shifts, shiftt, \ - 0, tmem, rt, \ - ((width) + 7) / 8) - -#define gLTT_(timg, fmt, siz, width, height, uls, ult, lrs, lrt, pal, \ - cms, cmt, masks, maskt, shifts, shiftt, \ - tmem, rt, line) \ - gsDPSetTextureImage(fmt, siz, width, timg), \ - gsDPSetTile( \ - fmt, siz, line, tmem, \ - G_TX_LOADTILE, 0, \ - cmt, maskt, shiftt, \ - cms, masks, shifts), \ - gsDPLoadSync(), \ - gsDPLoadTile( \ - G_TX_LOADTILE, \ - qu102(uls), qu102(ult), \ - qu102(lrs), qu102(lrt)), \ - gsDPPipeSync(), \ - gsDPSetTile( \ - fmt, siz, line, \ - tmem, rt, pal, \ - cmt, maskt, shiftt, \ - cms, masks, shifts), \ - gsDPSetTileSize( \ - rt, \ - qu102(uls), qu102(ult), \ - qu102(lrs), qu102(lrt)) - -#define gLTT4_(timg, fmt, width, height, uls, ult, lrs, lrt, pal, \ - cms, cmt, masks, maskt, shifts, shiftt, \ - tmem, rt) \ - gsDPSetTextureImage(fmt, G_IM_SIZ_8b, (width) / 2, timg), \ - gsDPSetTile( \ - fmt, G_IM_SIZ_8b, \ - (((lrs) - (uls) + 1) / 2 + 7) / 8, \ - tmem, G_TX_LOADTILE, 0, \ - cmt, maskt, shiftt, \ - cms, masks, shifts), \ - gsDPLoadSync(), \ - gsDPLoadTile( \ - G_TX_LOADTILE, \ - qu102(uls) / 2, qu102(ult), \ - qu102(lrs) / 2, qu102(lrt)), \ - gsDPPipeSync(), \ - gsDPSetTile( \ - fmt, G_IM_SIZ_4b, \ - (((lrs) - (uls) + 1) / 2 + 7) / 8, \ - tmem, rt, pal, \ - cmt, maskt, shiftt, \ - cms, masks, shifts), \ - gsDPSetTileSize( \ - rt, \ - qu102(uls), qu102(ult), \ - qu102(lrs), qu102(lrt)) - -#define gsDPLoadTextureTile(timg, fmt, siz, width, height, \ - uls, ult, lrs, lrt, pal, \ - cms, cmt, masks, maskt, shifts, shiftt) \ - gLTT_( \ - timg, fmt, siz, width, height, \ - uls, ult, lrs, lrt, pal, \ - cms, cmt, masks, maskt, shifts, shiftt, \ - 0x0, G_TX_RENDERTILE, \ - (((lrs) - (uls) + 1) * G_SIZ_LDBITS(siz) + 63) / 64) - -#define gsDPLoadTextureTile_4b(timg, fmt, width, height, \ - uls, ult, lrs, lrt, pal, \ - cms, cmt, masks, maskt, shifts, shiftt) \ - gLTT4_( \ - timg, fmt, width, height, \ - uls, ult, lrs, lrt, pal, \ - cms, cmt, masks, maskt, shifts, shiftt, \ - 0x0, G_TX_RENDERTILE) - -#define gsDPLoadTextureTileYuv(timg, fmt, siz, width, height, \ - uls, ult, lrs, lrt, pal, \ - cms, cmt, masks, maskt, shifts, shiftt) \ - gLTT_( \ - timg, fmt, siz, width, height, \ - uls, ult, lrs, lrt, pal, \ - cms, cmt, masks, maskt, shifts, shiftt, \ - 0x0, G_TX_RENDERTILE, \ - (((lrs) - (uls) + 1) + 7) / 8) - -#define _gsDPLoadTextureTile(timg, tmem, fmt, siz, width, height, \ - uls, ult, lrs, lrt, pal, \ - cms, cmt, masks, maskt, shifts, shiftt) \ - gLTT_( \ - timg, fmt, siz, width, height, \ - uls, ult, lrs, lrt, pal, \ - cms, cmt, masks, maskt, shifts, shiftt, \ - tmem, G_TX_RENDERTILE, \ - (((lrs) - (uls) + 1) * G_SIZ_LDBITS(siz) + 63) / 64) - -#define _gsDPLoadTextureTile_4b(timg, tmem, fmt, width, height, \ - uls, ult, lrs, lrt, pal, \ - cms, cmt, masks, maskt, shifts, shiftt) \ - gLTT4_( \ - timg, fmt, width, height, \ - uls, ult, lrs, lrt, pal, \ - cms, cmt, masks, maskt, shifts, shiftt, \ - tmem, G_TX_RENDERTILE) - -#define _gsDPLoadTextureTileYuv(timg, tmem, fmt, siz, width, height, \ - uls, ult, lrs, lrt, pal, cms, cmt, \ - masks, maskt, shifts, shiftt) \ - gLTT_( \ - timg, fmt, siz, width, height, \ - uls, ult, lrs, lrt, pal, \ - cms, cmt, masks, maskt, shifts, shiftt, \ - tmem, G_TX_RENDERTILE, \ - (((lrs) - (uls) + 1) + 7) / 8) - -#define gsDPLoadMultiTile(timg, tmem, rt, fmt, siz, width, height, \ - uls, ult, lrs, lrt, pal, \ - cms, cmt, masks, maskt, shifts, shiftt) \ - gLTT_( \ - timg, fmt, siz, width, height, \ - uls, ult, lrs, lrt, pal, \ - cms, cmt, masks, maskt, shifts, shiftt, \ - tmem, rt, \ - (((lrs) - (uls) + 1) * G_SIZ_LDBITS(siz) + 63) / 64) - -#define gsDPLoadMultiTile_4b(timg, tmem, rt, fmt, width, height, \ - uls, ult, lrs, lrt, pal, \ - cms, cmt, masks, maskt, shifts, shiftt) \ - gLTT4_( \ - timg, fmt, width, height, \ - uls, ult, lrs, lrt, pal, \ - cms, cmt, masks, maskt, shifts, shiftt, \ - tmem, rt) - -#define gsDPLoadMultiTileYuv(timg, tmem, rt, fmt, siz, width, height, \ - uls, ult, lrs, lrt, pal, \ - cms, cmt, masks, maskt, shifts, shiftt) \ - gLTT_( \ - timg, fmt, siz, width, height, \ - uls, ult, lrs, lrt, pal, \ - cms, cmt, masks, maskt, shifts, shiftt, \ - tmem, rt, \ - (((lrs) - (uls) + 1) + 7) / 8) - -#define gsDPLoadBlock(tile, uls, ult, lrs, dxt) \ - gO_( \ - G_LOADBLOCK, \ - gF_(uls, 12, 12) | \ - gF_(ult, 12, 0), \ - gF_(tile, 3, 24) | \ - gF_(G_LDBLK_TXL(lrs), 12, 12) | \ - gF_(dxt, 12, 0)) - -#define gsDPNoOp() \ - gsDPNoOpTag(0) - -#define gsDPNoOpTag(tag) \ - gO_(G_NOOP, 0, tag) - -#define gsDPPipelineMode(mode) \ - gsSPSetOtherModeHi(G_MDSFT_PIPELINE, G_MDSIZ_PIPELINE, mode) - -#define gsDPSetBlendColor(r, g, b, a) \ - gO_( \ - G_SETBLENDCOLOR, \ - 0, \ - gF_(r, 8, 24) | \ - gF_(g, 8, 16) | \ - gF_(b, 8, 8) | \ - gF_(a, 8, 0)) - -#define gsDPSetEnvColor(r, g, b, a) \ - gO_( \ - G_SETENVCOLOR, \ - 0, \ - gF_(r, 8, 24) | \ - gF_(g, 8, 16) | \ - gF_(b, 8, 8) | \ - gF_(a, 8, 0)) - -#define gsDPSetFillColor(c) \ - gO_(G_SETFILLCOLOR, 0, c) - -#define gsDPSetFogColor(r, g, b, a) \ - gO_( \ - G_SETFOGCOLOR, 0, \ - gF_(r, 8, 24) | \ - gF_(g, 8, 16) | \ - gF_(b, 8, 8) | \ - gF_(a, 8, 0)) - -#define gsDPSetPrimColor(m, l, r, g, b, a) \ - gO_( \ - G_SETPRIMCOLOR, \ - gF_(m, 8, 8) | \ - gF_(l, 8, 0), \ - gF_(r, 8, 24) | \ - gF_(g, 8, 16) | \ - gF_(b, 8, 8) | \ - gF_(a, 8, 0)) - -#define gsDPSetColorImage(fmt, siz, width, img) \ - gO_( \ - G_SETCIMG, \ - gF_(fmt, 3, 21) | \ - gF_(siz, 2, 19) | \ - gF_((width) - 1, 12, 0), \ - img) - -#define gsDPSetDepthImage(img) \ - gO_(G_SETZIMG, 0, img) - -#define gsDPSetTextureImage(fmt, siz, width, img) \ - gO_( \ - G_SETTIMG, \ - gF_(fmt, 3, 21) | \ - gF_(siz, 2, 19) | \ - gF_((width) - 1, 12, 0), \ - img) - -#define gsDPSetHilite1Tile(tile, hilite, width, height) \ - gsDPSetTileSize( \ - tile, \ - ((Hilite *)(hilite))->h.x1 & 0xFFF, \ - ((Hilite *)(hilite))->h.y1 & 0xFFF, \ - (((width) - 1) * 4 + ((Hilite *)(hilite))->h.x1) & 0xFFF, \ - (((height) - 1) * 4 + ((Hilite *)(hilite))->h.y1) & 0xFFF) - -#define gsDPSetHilite2Tile(tile, hilite, width, height) \ - gsDPSetTileSize( \ - tile, \ - ((Hilite *)(hilite))->h.x2 & 0xFFF, \ - ((Hilite *)(hilite))->h.y2 & 0xFFF, \ - (((width) - 1) * 4 + ((Hilite *)(hilite))->h.x2) & 0xFFF, \ - (((height) - 1) * 4 + ((Hilite *)(hilite))->h.y2) & 0xFFF) - -#define gsDPSetAlphaCompare(mode) \ - gsSPSetOtherModeLo(G_MDSFT_ALPHACOMPARE, G_MDSIZ_ALPHACOMPARE, mode) - -#define gsDPSetAlphaDither(type) \ - gsSPSetOtherModeHi(G_MDSFT_ALPHADITHER, G_MDSIZ_ALPHADITHER, type) - -#define gsDPSetColorDither(type) \ - gsSPSetOtherModeHi(G_MDSFT_RGBDITHER, G_MDSIZ_RGBDITHER, type) - -#define gsDPSetCombineMode(mode1, mode2) \ - gsDPSetCombineLERP(mode1, mode2) - -#define gsDPSetCombineLERP(a0, b0, c0, d0, Aa0, Ab0, Ac0, Ad0, \ - a1, b1, c1, d1, Aa1, Ab1, Ac1, Ad1) \ - gO_( \ - G_SETCOMBINE, \ - gF_(G_CCMUX_##a0, 4, 20) | \ - gF_(G_CCMUX_##c0, 5, 15) | \ - gF_(G_ACMUX_##Aa0, 3, 12) | \ - gF_(G_ACMUX_##Ac0, 3, 9) | \ - gF_(G_CCMUX_##a1, 4, 5) | \ - gF_(G_CCMUX_##c1, 5, 0), \ - gF_(G_CCMUX_##b0, 4, 28) | \ - gF_(G_CCMUX_##b1, 4, 24) | \ - gF_(G_ACMUX_##Aa1, 3, 21) | \ - gF_(G_ACMUX_##Ac1, 3, 18) | \ - gF_(G_CCMUX_##d0, 3, 15) | \ - gF_(G_ACMUX_##Ab0, 3, 12) | \ - gF_(G_ACMUX_##Ad0, 3, 9) | \ - gF_(G_CCMUX_##d1, 3, 6) | \ - gF_(G_ACMUX_##Ab1, 3, 3) | \ - gF_(G_ACMUX_##Ad1, 3, 0)) - -#define gsDPSetConvert(k0, k1, k2, k3, k4, k5) \ - gO_( \ - G_SETCONVERT, \ - gF_(k0, 9, 13) | \ - gF_(k1, 9, 4) | \ - gF_(gI_(k2) >> 5, 4, 0), \ - gF_(k2, 5, 27) | \ - gF_(k3, 9, 18) | \ - gF_(k4, 9, 9) | \ - gF_(k5, 9, 0)) - -#define gsDPSetTextureConvert(type) \ - gsSPSetOtherModeHi(G_MDSFT_TEXTCONV, G_MDSIZ_TEXTCONV, type) - -#define gsDPSetCycleType(type) \ - gsSPSetOtherModeHi(G_MDSFT_CYCLETYPE, G_MDSIZ_CYCLETYPE, type) - -#define gsDPSetDepthSource(source) \ - gsSPSetOtherModeLo(G_MDSFT_ZSRCSEL, G_MDSIZ_ZSRCSEL, source) - -#define gsDPSetCombineKey(type) \ - gsSPSetOtherModeHi(G_MDSFT_COMBKEY, G_MDSIZ_COMBKEY, type) - -#define gsDPSetKeyGB(cG, sG, wG, cB, sB, wB) \ - gO_( \ - G_SETKEYGB, \ - gF_(wG, 12, 12) | \ - gF_(wB, 12, 0), \ - gF_(cG, 8, 24) | \ - gF_(sG, 8, 16) | \ - gF_(cB, 8, 8) | \ - gF_(sB, 8, 0)) - -#define gsDPSetKeyR(cR, sR, wR) \ - gO_( \ - G_SETKEYR, 0, \ - gF_(wR, 12, 16) | \ - gF_(cR, 8, 8) | \ - gF_(sR, 8, 0)) - -#define gsDPSetPrimDepth(z, dz) \ - gO_( \ - G_SETPRIMDEPTH, \ - 0, \ - gF_(z, 16, 16) | \ - gF_(dz, 16, 0)) - -#define gsDPSetRenderMode(mode1, mode2) \ - gsSPSetOtherModeLo( \ - G_MDSFT_RENDERMODE, \ - G_MDSIZ_RENDERMODE, \ - gI_(mode1) | \ - gI_(mode2)) - -#define gsDPSetScissor(mode, ulx, uly, lrx, lry) \ - gsDPSetScissorFrac( \ - mode, \ - qu102(gI_(ulx)), \ - qu102(gI_(uly)), \ - qu102(gI_(lrx)), \ - qu102(gI_(lry))) - -#define gsDPSetScissorFrac(mode, ulx, uly, lrx, lry) \ - gO_( \ - G_SETSCISSOR, \ - gF_(ulx, 12, 12) | \ - gF_(uly, 12, 0), \ - gF_(mode, 2, 24) | \ - gF_(lrx, 12, 12) | \ - gF_(lry, 12, 0)) - -#define gsDPSetTextureDetail(type) \ - gsSPSetOtherModeHi(G_MDSFT_TEXTDETAIL, G_MDSIZ_TEXTDETAIL, type) - -#define gsDPSetTextureFilter(mode) \ - gsSPSetOtherModeHi(G_MDSFT_TEXTFILT, G_MDSIZ_TEXTFILT, mode) - -#define gsDPSetTextureLOD(mode) \ - gsSPSetOtherModeHi(G_MDSFT_TEXTLOD, G_MDSIZ_TEXTLOD, mode) - -#define gsDPSetTextureLUT(mode) \ - gsSPSetOtherModeHi(G_MDSFT_TEXTLUT, G_MDSIZ_TEXTLUT, mode) - -#define gsDPSetTexturePersp(enable) \ - gsSPSetOtherModeHi(G_MDSFT_TEXTPERSP, G_MDSIZ_TEXTPERSP, enable) - -#define gsDPSetTile(fmt, siz, line, tmem, tile, palette, \ - cmt, maskt, shiftt, cms, masks, shifts) \ - gO_( \ - G_SETTILE, \ - gF_(fmt, 3, 21) | \ - gF_(siz, 2, 19) | \ - gF_(line, 9, 9) | \ - gF_(tmem, 9, 0), \ - gF_(tile, 3, 24) | \ - gF_(palette, 4, 20) | \ - gF_(cmt, 2, 18) | \ - gF_(maskt, 4, 14) | \ - gF_(shiftt, 4, 10) | \ - gF_(cms, 2, 8) | \ - gF_(masks, 4, 4) | \ - gF_(shifts, 4, 0)) - -#define gsDPSetTileSize(tile, uls, ult, lrs, lrt) \ - gO_( \ - G_SETTILESIZE, \ - gF_(uls, 12, 12) | \ - gF_(ult, 12, 0), \ - gF_(tile, 3, 24) | \ - gF_(lrs, 12, 12) | \ - gF_(lrt, 12, 0)) - -#define gsSPBranchList(dl) \ - gsDisplayList(dl, 1) - -#define gsSPClipRatio(r) \ - gsMoveWd(G_MW_CLIP, G_MWO_CLIP_RNX, (uint16_t)(r)), \ - gsMoveWd(G_MW_CLIP, G_MWO_CLIP_RNY, (uint16_t)(r)), \ - gsMoveWd(G_MW_CLIP, G_MWO_CLIP_RPX, (uint16_t)-(r)), \ - gsMoveWd(G_MW_CLIP, G_MWO_CLIP_RPY, (uint16_t)-(r)) - -#define gsSPDisplayList(dl) \ - gsDisplayList(dl, 0) - -#define gsSPEndDisplayList() \ - gO_(G_ENDDL, 0, 0) - -#define gsSPFogFactor(fm, fo) \ - gsMoveWd( \ - G_MW_FOG, \ - G_MWO_FOG, \ - gF_(fm, 16, 16) | \ - gF_(fo, 16, 0)) - -#define gsSPFogPosition(min, max) \ - gsSPFogFactor( \ - (500 * 0x100) / ((max) - (min)), \ - (500 - (min)) * 0x100 / ((max) - (min))) - -#define gsSPLine3D(v0, v1, flag) \ - gsSPLineW3D(v0, v1, 0, flag) - -#define gsSPLookAt(l) \ - gsSPLookAtX(l), \ - gsSPLookAtY(gI_(l) + 0x10) - -#define gsSPSegment(seg, base) \ - gsMoveWd(G_MW_SEGMENT, (seg) * 4, base) - -#define gsSPSetLights0(lites) \ - gsSPNumLights(NUMLIGHTS_0), \ - gsSPLight(&(lites).l[0], 1), \ - gsSPLight(&(lites).a, 2) - -#define gsSPSetLights1(lites) \ - gsSPNumLights(NUMLIGHTS_1), \ - gsSPLight(&(lites).l[0], 1), \ - gsSPLight(&(lites).a, 2) - -#define gsSPSetLights2(lites) \ - gsSPNumLights(NUMLIGHTS_2), \ - gsSPLight(&(lites).l[0], 1), \ - gsSPLight(&(lites).l[1], 2), \ - gsSPLight(&(lites).a, 3) - -#define gsSPSetLights3(lites) \ - gsSPNumLights(NUMLIGHTS_3), \ - gsSPLight(&(lites).l[0], 1), \ - gsSPLight(&(lites).l[1], 2), \ - gsSPLight(&(lites).l[2], 3), \ - gsSPLight(&(lites).a, 4) - -#define gsSPSetLights4(lites) \ - gsSPNumLights(NUMLIGHTS_4), \ - gsSPLight(&(lites).l[0], 1), \ - gsSPLight(&(lites).l[1], 2), \ - gsSPLight(&(lites).l[2], 3), \ - gsSPLight(&(lites).l[3], 4), \ - gsSPLight(&(lites).a, 5) - -#define gsSPSetLights5(lites) \ - gsSPNumLights(NUMLIGHTS_5), \ - gsSPLight(&(lites).l[0], 1), \ - gsSPLight(&(lites).l[1], 2), \ - gsSPLight(&(lites).l[2], 3), \ - gsSPLight(&(lites).l[3], 4), \ - gsSPLight(&(lites).l[4], 5), \ - gsSPLight(&(lites).a, 6) - -#define gsSPSetLights6(lites) \ - gsSPNumLights(NUMLIGHTS_6), \ - gsSPLight(&(lites).l[0], 1), \ - gsSPLight(&(lites).l[1], 2), \ - gsSPLight(&(lites).l[2], 3), \ - gsSPLight(&(lites).l[3], 4), \ - gsSPLight(&(lites).l[4], 5), \ - gsSPLight(&(lites).l[5], 6), \ - gsSPLight(&(lites).a, 7) - -#define gsSPSetLights7(lites) \ - gsSPNumLights(NUMLIGHTS_7), \ - gsSPLight(&(lites).l[0], 1), \ - gsSPLight(&(lites).l[1], 2), \ - gsSPLight(&(lites).l[2], 3), \ - gsSPLight(&(lites).l[3], 4), \ - gsSPLight(&(lites).l[4], 5), \ - gsSPLight(&(lites).l[5], 6), \ - gsSPLight(&(lites).l[6], 7), \ - gsSPLight(&(lites).a, 8) - -#define gsSPSetStatus(sid, val) \ - gsMoveWd(G_MW_GENSTAT, sid, val) - -#define gsSPNumLights(n) \ - gsMoveWd(G_MW_NUMLIGHT, G_MWO_NUMLIGHT, NUML(n)) - -#define gsSPLightColor(Lightnum, packedcolor) \ - gsMoveWd(G_MW_LIGHTCOL, G_MWO_a##Lightnum, packedcolor), \ - gsMoveWd(G_MW_LIGHTCOL, G_MWO_b##Lightnum, packedcolor) - -#define gsSPTextureRectangle(ulx, uly, lrx, lry, tile, s, t, dsdx, dtdy) \ - gsTexRect(ulx, uly, lrx, lry, tile), \ - gsDPHalf1(gF_(s, 16, 16) | gF_(t, 16, 0)), \ - gsDPHalf2(gF_(dsdx, 16, 16) | gF_(dtdy, 16, 0)) - -#define gsSPScisTextureRectangle(ulx, uly, lrx, lry, tile, s, t, dsdx, dtdy) \ - gsTexRect(gScC_(ulx), gScC_(uly), gScC_(lrx), gScC_(lry), tile), \ - gsDPHalf1( \ - gF_(gScD_(s, ulx, dsdx), 16, 16) | \ - gF_(gScD_(t, uly, dtdy), 16, 0)), \ - gsDPHalf2(gF_(dsdx, 16, 16) | gF_(dtdy, 16, 0)) - -#define gsSPTextureRectangleFlip(ulx, uly, lrx, lry, tile, s, t, dsdx, dtdy) \ - gsTexRectFlip(ulx, uly, lrx, lry, tile), \ - gsDPHalf1(gF_(s, 16, 16) | gF_(t, 16, 0)), \ - gsDPHalf2(gF_(dsdx, 16, 16) | gF_(dtdy, 16, 0)) - -#define gsSPScisTextureRectangleFlip( \ - ulx, uly, lrx, lry, tile, s, t, dsdx, dtdy) \ - gsTexRectFlip(gScC_(ulx), gScC_(uly), gScC_(lrx), gScC_(lry), tile), \ - gsDPHalf1( \ - gF_(gScD_(s, ulx, dsdx), 16, 16) | \ - gF_(gScD_(t, uly, dtdy), 16, 0)), \ - gsDPHalf2(gF_(dsdx, 16, 16) | gF_(dtdy, 16, 0)) - -#define gsSPBgRectCopy(bg) \ - gO_(G_BG_COPY, 0, bg) - -#define gsSPBgRect1Cyc(bg) \ - gO_(G_BG_1CYC, 0, bg) - -#define gsSPObjRectangle(sp) \ - gO_(G_OBJ_RECTANGLE, 0, sp) - -#define gsSPObjRectangleR(sp) \ - gO_(G_OBJ_RECTANGLE_R, 0, sp) - -#define gsSPObjSprite(sp) \ - gO_(G_OBJ_SPRITE, 0, sp) - -#define gsSPObjMatrix(mtx) \ - gO_( \ - G_OBJ_MOVEMEM, \ - gF_(sizeof(uObjMtx) - 1, 8, 16), \ - mtx) - -#define gsSPObjSubMatrix(mtx) \ - gO_( \ - G_OBJ_MOVEMEM, \ - gF_(sizeof(uObjSubMtx) - 1, 8, 16) | \ - gF_(2, 16, 0), \ - mtx) - -#define gsSPObjRenderMode(mode) \ - gO_(G_OBJ_RENDERMODE, 0, mode) - -#define gsSPObjLoadTxtr(tx) \ - gO_(G_OBJ_LOADTXTR, 23, tx) - -#define gsSPObjLoadTxRect(txsp) \ - gO_(G_OBJ_LDTX_RECT, 47, txsp) - -#define gsSPObjLoadTxRectR(txsp) \ - gO_(G_OBJ_LDTX_RECT_R, 47, txsp) - -#define gsSPObjLoadTxSprite(txsp) \ - gO_(G_OBJ_LDTX_SPRITE, 47, txsp) - -#define gsSPSelectDL(ldl, sid, flag, mask) \ - gO_( \ - G_RDPHALF_0, \ - gF_(sid, 8, 16) | \ - gF_(ldl, 16, 0), \ - flag), \ - gO_( \ - G_SELECT_DL, \ - gF_(0x00, 8, 16) | \ - gF_(gI_(ldl) >> 16, 16, 0), \ - mask) - -#define gsSPSelectBranchDL(bdl, sid, flag, mask) \ - gO_( \ - G_RDPHALF_0, \ - gF_(sid, 8, 16) | \ - gF_(bdl, 16, 0), \ - flag), \ - gO_( \ - G_SELECT_DL, \ - gF_(0x01, 8, 16) | \ - gF_(gI_(bdl) >> 16, 16, 0), \ - mask) - -/* unlisted instructions */ - -#define gsDPLoadTLUTCmd(tile, count) \ - gO_( \ - G_LOADTLUT, \ - 0, \ - gF_(tile, 3, 24) | \ - gF_(count, 10, 14)) - -#define gsDPLoadTLUT(count, tmem, dram) \ - gsDPSetTextureImage(G_IM_FMT_RGBA, G_IM_SIZ_16b, 1, dram), \ - gsDPTileSync(), \ - gsDPSetTile(0, 0, 0, tmem, G_TX_LOADTILE, 0, 0, 0, 0, 0, 0, 0), \ - gsDPLoadSync(), \ - gsDPLoadTLUTCmd(G_TX_LOADTILE, (count) - 1), \ - gsDPPipeSync() - -#define gsDisplayList(dl, branch) \ - gO_(G_DL, gF_(branch, 8, 16), dl) - -#define gsDPLoadTile(tile, uls, ult, lrs, lrt) \ - gO_( \ - G_LOADTILE, \ - gF_(uls, 12, 12) | \ - gF_(ult, 12, 0), \ - gF_(tile, 3, 24) | \ - gF_(lrs, 12, 12) | \ - gF_(lrt, 12, 0)) - -#define gsDPSetCombine(c) \ - gO_( \ - G_SETCOMBINE, \ - (gL_(c) >> 32) & 0xFFFFFFFF, \ - (gL_(c) >> 0) & 0xFFFFFFFF) - -#define gsSPSetOtherModeLo(shift, length, data) \ - gsSPSetOtherMode(G_SETOTHERMODE_L, shift, length, data) - -#define gsSPSetOtherModeHi(shift, length, data) \ - gsSPSetOtherMode(G_SETOTHERMODE_H, shift, length, data) - -#define gsDPSetOtherMode(mode0, mode1) \ - gO_(G_RDPSETOTHERMODE, gF_(mode0, 24, 0), mode1) - -#define gsTexRect(ulx, uly, lrx, lry, tile) \ - gO_( \ - G_TEXRECT, \ - gF_(lrx, 12, 12) | \ - gF_(lry, 12, 0), \ - gF_(tile, 3, 24) | \ - gF_(ulx, 12, 12) | \ - gF_(uly, 12, 0)) - -#define gsTexRectFlip(ulx, uly, lrx, lry, tile) \ - gO_( \ - G_TEXRECTFLIP, \ - gF_(lrx, 12, 12) | \ - gF_(lry, 12, 0), \ - gF_(tile, 3, 24) | \ - gF_(ulx, 12, 12) | \ - gF_(uly, 12, 0)) - -#define gsSPNoOp() \ - gO_(G_SPNOOP, 0, 0) - -#define gsDPHalf1(wordhi) \ - gO_(G_RDPHALF_1, 0, wordhi) - -#define gsDPHalf2(wordlo) \ - gO_(G_RDPHALF_2, 0, wordlo) - -#define gsDPWord(wordhi, wordlo) \ - gsDPHalf1(wordhi), \ - gsDPHalf2(wordlo) - -/* instruction macros for fast3d */ - -#if defined(F3D_GBI) - -# define gsSP1Triangle(v0, v1, v2, flag) \ - gO_( \ - G_TRI1, \ - 0, \ - gF_(flag, 8, 24) | \ - gF_(gI_(v0) * 10, 8, 16) | \ - gF_(gI_(v1) * 10, 8, 8) | \ - gF_(gI_(v2) * 10, 8, 0)) - -# define gsSPCullDisplayList(v0, vn) \ - gO_( \ - G_CULLDL, \ - (gI_(v0) & 0xF) * 40, \ - gI_((vn) + 1) & 0xF) * 40) - -# define gsSPLineW3D(v0, v1, wd, flag) \ - gO_( \ - G_LINE3D, \ - 0, \ - gF_(flag, 8, 24) | \ - gF_(gI_(v0) * 10, 8, 16) | \ - gF_(gI_(v1) * 10, 8, 8) | \ - gF_(wd, 8, 0)) - -# define gsSPVertex(v, n, v0) \ - gO_( \ - G_VTX, \ - gF_((n) - 1, 4, 20) | \ - gF_(v0, 4, 16) | \ - gF_(sizeof(Vtx) * (n), 16, 0), \ - v) - -#endif - -/* instruction macros for fast3d and beta f3dex */ -#if defined(F3D_GBI) || (defined(F3D_BETA) && defined(F3DEX_GBI)) - -# define gsSPModifyVertex(vtx, where, val) \ - gsMoveWd(G_MW_POINTS, (vtx) * 40 + (where), val) - -#endif - -/* instruction macros for fast3d and f3dex */ - -#if defined(F3D_GBI) || defined(F3DEX_GBI) - -# define gsSPForceMatrix(mptr) \ - gsMoveMem(16, G_MV_MATRIX_1, (char *)(mptr)), \ - gsMoveMem(16, G_MV_MATRIX_2, (char *)(mptr) + 16), \ - gsMoveMem(16, G_MV_MATRIX_3, (char *)(mptr) + 32), \ - gsMoveMem(16, G_MV_MATRIX_4, (char *)(mptr) + 48) - -# define gsSPSetGeometryMode(mode) \ - gO_(G_SETGEOMETRYMODE, 0, gI_(mode)) - -# define gsSPClearGeometryMode(mode) \ - gO_(G_CLEARGEOMETRYMODE, 0, gI_(mode)) - -# define gsSPLoadGeometryMode(mode) \ - gsSPClearGeometryMode(~gI_(0)), \ - gsSPSetGeometryMode(mode) - -# define gsSPInsertMatrix(where, num) \ - gsMoveWd(G_MW_MATRIX, where, num) - -# define gsSPLookAtX(l) \ - gsMoveMem(sizeof(Light), G_MV_LOOKATX, l) - -# define gsSPLookAtY(l) \ - gsMoveMem(sizeof(Light), G_MV_LOOKATY, l) - -# define gsSPMatrix(matrix, param) \ - gO_( \ - G_MTX, \ - gF_(param, 8, 16) | \ - gF_(sizeof(Mtx), 16, 0), \ - matrix) - -# define gsSPPopMatrix(param) \ - gO_(G_POPMTX, 0, param) - -# define gsSPLight(l, n) \ - gsMoveMem(sizeof(Light), G_MV_L0 + ((n) - 1) * 2, l) - -# define gsSPTexture(sc, tc, level, tile, on) \ - gO_( \ - G_TEXTURE, \ - gF_(level, 3, 11) | \ - gF_(tile, 3, 8) | \ - gF_(on, 8, 0), \ - gF_(sc, 16, 16) | \ - gF_(tc, 16, 0)) - -# define gsSPViewport(v) \ - gsMoveMem(sizeof(Vp), G_MV_VIEWPORT, v) - -# define gsSPSetOtherMode(opc, shift, length, data) \ - gO_( \ - opc, \ - gF_(shift, 8, 8) | \ - gF_(length, 8, 0), \ - data) - -# define gsMoveWd(index, offset, data) \ - gO_( \ - G_MOVEWORD, \ - gF_(offset, 16, 8) | \ - gF_(index, 8, 0), \ - data) - -# define gsMoveMem(size, index, address) \ - gO_( \ - G_MOVEMEM, \ - gF_(index, 8, 16) | \ - gF_(size, 16, 0), \ - address) - -#endif - -/* instruction macros for f3dex */ - -#if defined(F3DEX_GBI) - -# define gsSP1Triangle(v0, v1, v2, flag) \ - gO_( \ - G_TRI1, \ - 0, \ - gF_(gV3_(v0, v1, v2, flag) * 2, 8, 16) | \ - gF_(gV3_(v1, v2, v0, flag) * 2, 8, 8) | \ - gF_(gV3_(v2, v0, v1, flag) * 2, 8, 0)) - -# define gsSP1Quadrangle(v0, v1, v2, v3, flag) \ - gO_( \ - G_TRI2, \ - gF_(gV4_(v0, v1, v2, v3, flag) * 2, 8, 16) | \ - gF_(gV4_(v1, v2, v3, v0, flag) * 2, 8, 8) | \ - gF_(gV4_(v2, v3, v0, v1, flag) * 2, 8, 0), \ - gF_(gV4_(v0, v1, v2, v3, flag) * 2, 8, 16) | \ - gF_(gV4_(v2, v3, v0, v1, flag) * 2, 8, 8) | \ - gF_(gV4_(v3, v0, v1, v2, flag) * 2, 8, 0)) - -# define gsSPLineW3D(v0, v1, wd, flag) \ - gO_( \ - G_LINE3D, \ - 0, \ - gF_(gV2_(v0, v1, flag) * 2, 8, 16) | \ - gF_(gV2_(v1, v0, flag) * 2, 8, 8) | \ - gF_(wd, 8, 0)) - -# define gsSPVertex(v, n, v0) \ - gO_( \ - G_VTX, \ - gF_((v0) * 2, 8, 16) | \ - gF_(n, 6, 10) | \ - gF_(sizeof(Vtx) * (n) - 1, 10, 0), \ - v) - -#endif - -/* instruction macros for f3dex and f3dex2 */ - -#if defined(F3DEX_GBI) || defined(F3DEX_GBI_2) - -# define gsSP2Triangles(v00, v01, v02, flag0, v10, v11, v12, flag1) \ - gO_( \ - G_TRI2, \ - gF_(gV3_(v00, v01, v02, flag0) * 2, 8, 16) | \ - gF_(gV3_(v01, v02, v00, flag0) * 2, 8, 8) | \ - gF_(gV3_(v02, v00, v01, flag0) * 2, 8, 0), \ - gF_(gV3_(v10, v11, v12, flag1) * 2, 8, 16) | \ - gF_(gV3_(v11, v12, v10, flag1) * 2, 8, 8) | \ - gF_(gV3_(v12, v10, v11, flag1) * 2, 8, 0)) - -# define gsSPBranchLessZ(branchdl, vtx, zval, near, far, flag) \ - gsSPBranchLessZrg(branchdl, vtx, zval, near, far, flag, 0, G_MAXZ) - -# define gsSPBranchLessZrg(branchdl, vtx, zval, near, far, flag, zmin, zmax) \ - gsSPBranchLessZraw(branchdl, vtx, \ - G_DEPTOZSrg(zval, near, far, flag, zmin, zmax)) - -# define gsSPBranchLessZraw(branchdl, vtx, zval) \ - gsDPHalf1(branchdl), \ - gsBranchZ(vtx, zval) - -# define gsSPCullDisplayList(v0, vn) \ - gO_( \ - G_CULLDL, \ - gF_((v0) * 2, 16, 0), \ - gF_((vn) * 2, 16, 0)) - -# define gsSPLoadUcode(uc_start, uc_dstart) \ - gsSPLoadUcodeEx(uc_start, uc_dstart, 0x800) - -# define gsSPLoadUcodeL(ucode) \ - gsSPLoadUcode( \ - gI_(&ucode##TextStart) & 0x1FFFFFFF, \ - gI_(&ucode##DataStart) & 0x1FFFFFFF) - -# if !(defined(F3D_BETA) && defined(F3DEX_GBI)) -# define gsSPModifyVertex(vtx, where, val) \ - gO_( \ - G_MODIFYVTX, \ - gF_(where, 8, 16) | \ - gF_((vtx) * 2, 16, 0), \ - val) -# endif - -# define gsBranchZ(vtx, zval) \ - gO_( \ - G_BRANCH_Z, \ - gF_((vtx) * 5, 12, 12) | \ - gF_((vtx) * 2, 12, 0), \ - zval) - -# define gsLoadUcode(uc_start, uc_dsize) \ - gO_( \ - G_LOAD_UCODE, \ - gF_((uc_dsize) - 1, 16, 0), \ - uc_start) - -# define gsSPLoadUcodeEx(uc_start, uc_dstart, uc_dsize) \ - gsDPHalf1(uc_dstart), \ - gsLoadUcode(uc_start, uc_dsize) - -#endif - -/* instruction macros for f3dex2 */ - -#if defined(F3DEX_GBI_2) - -# define gsSP1Triangle(v0, v1, v2, flag) \ - gO_( \ - G_TRI1, \ - gF_(gV3_(v0, v1, v2, flag) * 2, 8, 16) | \ - gF_(gV3_(v1, v2, v0, flag) * 2, 8, 8) | \ - gF_(gV3_(v2, v0, v1, flag) * 2, 8, 0), \ - 0) - -# define gsSP1Quadrangle(v0, v1, v2, v3, flag) \ - gO_( \ - G_QUAD, \ - gF_(gV4_(v0, v1, v2, v3, flag) * 2, 8, 16) | \ - gF_(gV4_(v1, v2, v3, v0, flag) * 2, 8, 8) | \ - gF_(gV4_(v2, v3, v0, v1, flag) * 2, 8, 0), \ - gF_(gV4_(v0, v1, v2, v3, flag) * 2, 8, 16) | \ - gF_(gV4_(v2, v3, v0, v1, flag) * 2, 8, 8) | \ - gF_(gV4_(v3, v0, v1, v2, flag) * 2, 8, 0)) - -# define gsSPForceMatrix(mptr) \ - gsMoveMem(sizeof(Mtx), G_MV_MATRIX, 0, mptr), \ - gsMoveWd(G_MW_FORCEMTX, 0, 0x10000) - -# define gsSPSetGeometryMode(mode) \ - gsSPGeometryMode(0, mode) - -# define gsSPClearGeometryMode(mode) \ - gsSPGeometryMode(mode, 0) - -# define gsSPLoadGeometryMode(mode) \ - gsSPGeometryMode(~gI_(0), mode) - -# define gsSPLineW3D(v0, v1, wd, flag) \ - gO_( \ - G_LINE3D, \ - gF_(gV2_(v0, v1, flag) * 2, 8, 16) | \ - gF_(gV2_(v1, v0, flag) * 2, 8, 8) | \ - gF_(wd, 8, 0), \ - 0) - -# define gsSPLookAtX(l) \ - gsMoveMem(sizeof(Light), G_MV_LIGHT, G_MVO_LOOKATX, l) - -# define gsSPLookAtY(l) \ - gsMoveMem(sizeof(Light), G_MV_LIGHT, G_MVO_LOOKATY, l) - -# define gsSPMatrix(matrix, param) \ - gO_( \ - G_MTX, \ - gF_((sizeof(Mtx) - 1) / 8, 5, 19) | \ - gF_(gI_(param) ^ G_MTX_PUSH, 8, 0), \ - matrix) - -# define gsSPPopMatrix(param) \ - gsSPPopMatrixN(param, 1) - -# define gsSPPopMatrixN(param, n) \ - gO_( \ - G_POPMTX, \ - gF_((sizeof(Mtx) - 1) / 8, 5, 19) | \ - gF_(2, 8, 0), \ - sizeof(Mtx) * (n)) - -# define gsSPLight(l, n) \ - gsMoveMem(sizeof(Light), G_MV_LIGHT, ((n) + 1) * 0x18, l) - -# define gsSPTexture(sc, tc, level, tile, on) \ - gO_( \ - G_TEXTURE, \ - gF_(level, 3, 11) | \ - gF_(tile, 3, 8) | \ - gF_(on, 7, 1), \ - gF_(sc, 16, 16) | \ - gF_(tc, 16, 0)) - -# define gsSPVertex(v, n, v0) \ - gO_( \ - G_VTX, \ - gF_(n, 8, 12) | \ - gF_((v0) + (n), 7, 1), \ - v) - -# define gsSPViewport(v) \ - gsMoveMem(sizeof(Vp), G_MV_VIEWPORT, 0, v) - -# define gsSPGeometryMode(clearbits, setbits) \ - gO_( \ - G_GEOMETRYMODE, \ - gF_(~gI_(clearbits), 24, 0), \ - setbits) - -# define gsSPSetOtherMode(opc, shift, length, data) \ - gO_( \ - opc, \ - gF_(32 - (shift) - (length), 8, 8) | \ - gF_((length) - 1, 8, 0), \ - data) - -# define gsMoveWd(index, offset, data) \ - gO_( \ - G_MOVEWORD, \ - gF_(index, 8, 16) | \ - gF_(offset, 16, 0), \ - data) - -# define gsMoveMem(size, index, offset, address) \ - gO_( \ - G_MOVEMEM, \ - gF_((size - 1) / 8, 5, 19) | \ - gF_((offset) / 8, 8, 8) | \ - gF_(index, 8, 0), \ - address) - -# define gsSPDma_io(flag, dmem, dram, size) \ - gO_( \ - G_DMA_IO, \ - gF_(flag, 1, 23) | \ - gF_((dmem) / 8, 10, 13) | \ - gF_((size) - 1, 12, 0), \ - dram) - -# define gsSPDmaRead(dmem, dram, size) \ - gsSPDma_io(0, dmem, dram, size) - -# define gsSPDmaWrite(dmem, dram, size) \ - gsSPDma_io(1, dmem, dram, size) - -# define gsSpecial3(hi, lo) \ - gO_(G_SPECIAL_3, hi, lo) - -# define gsSpecial2(hi, lo) \ - gO_(G_SPECIAL_2, hi, lo) - -# define gsSpecial1(hi, lo) \ - gO_(G_SPECIAL_1, hi, lo) - -#endif - -/* instruction macros for beta fast3d and f3dex */ - -#if defined(F3D_BETA) && (defined(F3D_GBI) || defined(F3DEX_GBI)) - -# define gsSPPerspNormalize(scale) \ - gO_(G_PERSPNORM, 0, scale) - -#else - -# define gsSPPerspNormalize(scale) \ - gsMoveWd(G_MW_PERSPNORM, 0, scale) - -#endif - -/* dynamic instruction macros */ - -#define gDisplayListPut(gdl, ...) \ - ({ \ - Gfx Gd_[] = {__VA_ARGS__}; \ - for(size_t Gi_ = 0; Gi_ < sizeof(Gd_) / sizeof(Gfx); Gi_++) \ - { \ - *(Gfx *)(gdl) = Gd_[Gi_]; \ - } \ - (void)0; \ - }) -#define gDisplayListAppend(pgdl, ...) \ - ({ \ - Gfx Gd_[] = {__VA_ARGS__}; \ - for(size_t Gi_ = 0; Gi_ < sizeof(Gd_) / sizeof(Gfx); Gi_++) \ - { \ - *(*(Gfx **)(pgdl))++ = Gd_[Gi_]; \ - } \ - (void)0; \ - }) -#define gDisplayListData(pgdl, d) \ - ({ \ - Gfx **Gp_ = (void *)(pgdl); \ - struct \ - { \ - __typeof__(d) v; \ - } *Gd_, *Gs_; \ - *Gp_ -= (sizeof(*Gd_) + sizeof(Gfx) - 1) / sizeof(Gfx); \ - Gd_ = (void *)*Gp_; \ - Gs_ = (void *)&(d); \ - *Gd_ = *Gs_; \ - &Gd_->v; \ - }) -#define gDisplayListAlloc(pgdl, s) \ - ({ \ - Gfx **Gp_ = (void *)(pgdl); \ - *Gp_ -= ((s) + sizeof(Gfx) - 1) / sizeof(Gfx); \ - (void *)*Gp_; \ - }) - -#define gDPFillRectangle(gdl, ...) \ - gD_(gdl, gsDPFillRectangle, __VA_ARGS__) -#define gDPScisFillRectangle(gdl, ...) \ - gD_(gdl, gsDPScisFillRectangle, __VA_ARGS__) -#define gDPFullSync(gdl) \ - gDisplayListPut(gdl, gsDPFullSync()) -#define gDPLoadSync(gdl) \ - gDisplayListPut(gdl, gsDPLoadSync()) -#define gDPTileSync(gdl) \ - gDisplayListPut(gdl, gsDPTileSync()) -#define gDPPipeSync(gdl) \ - gDisplayListPut(gdl, gsDPPipeSync()) -#define gDPLoadTLUT_pal16(gdl, ...) \ - gD_(gdl, gsDPLoadTLUT_pal16, __VA_ARGS__) -#define gDPLoadTLUT_pal256(gdl, ...) \ - gD_(gdl, gsDPLoadTLUT_pal256, __VA_ARGS__) -#define gDPLoadTextureBlock(gdl, ...) \ - gD_(gdl, gsDPLoadTextureBlock, __VA_ARGS__) -#define gDPLoadTextureBlockS(gdl, ...) \ - gD_(gdl, gsDPLoadTextureBlockS, __VA_ARGS__) -#define gDPLoadTextureBlock_4b(gdl, ...) \ - gD_(gdl, gsDPLoadTextureBlock_4b, __VA_ARGS__) -#define gDPLoadTextureBlock_4bS(gdl, ...) \ - gD_(gdl, gsDPLoadTextureBlock_4bS, __VA_ARGS__) -#define gDPLoadTextureBlockYuv(gdl, ...) \ - gD_(gdl, gsDPLoadTextureBlockYuv, __VA_ARGS__) -#define gDPLoadTextureBlockYuvS(gdl, ...) \ - gD_(gdl, gsDPLoadTextureBlockYuvS, __VA_ARGS__) -#define _gDPLoadTextureBlock(gdl, ...) \ - gD_(gdl, _gsDPLoadTextureBlock, __VA_ARGS__) -#define _gDPLoadTextureBlockS(gdl, ...) \ - gD_(gdl, _gsDPLoadTextureBlockS, __VA_ARGS__) -#define _gDPLoadTextureBlock_4b(gdl, ...) \ - gD_(gdl, _gsDPLoadTextureBlock_4b, __VA_ARGS__) -#define _gDPLoadTextureBlock_4bS(gdl, ...) \ - gD_(gdl, _gsDPLoadTextureBlock_4bS, __VA_ARGS__) -#define _gDPLoadTextureBlockYuv(gdl, ...) \ - gD_(gdl, _gsDPLoadTextureBlockYuv, __VA_ARGS__) -#define _gDPLoadTextureBlockYuvS(gdl, ...) \ - gD_(gdl, _gsDPLoadTextureBlockYuvS, __VA_ARGS__) -#define gDPLoadMultiBlock(gdl, ...) \ - gD_(gdl, gsDPLoadMultiBlock, __VA_ARGS__) -#define gDPLoadMultiBlockS(gdl, ...) \ - gD_(gdl, gsDPLoadMultiBlockS, __VA_ARGS__) -#define gDPLoadMultiBlock_4b(gdl, ...) \ - gD_(gdl, gsDPLoadMultiBlock_4b, __VA_ARGS__) -#define gDPLoadMultiBlock_4bS(gdl, ...) \ - gD_(gdl, gsDPLoadMultiBlock_4bS, __VA_ARGS__) -#define gDPLoadMultiBlockYuv(gdl, ...) \ - gD_(gdl, gsDPLoadMultiBlockYuv, __VA_ARGS__) -#define gDPLoadMultiBlockYuvS(gdl, ...) \ - gD_(gdl, gsDPLoadMultiBlockYuvS, __VA_ARGS__) -#define gDPLoadTextureTile(gdl, ...) \ - gD_(gdl, gsDPLoadTextureTile, __VA_ARGS__) -#define gDPLoadTextureTile_4b(gdl, ...) \ - gD_(gdl, gsDPLoadTextureTile_4b, __VA_ARGS__) -#define gDPLoadTextureTileYuv(gdl, ...) \ - gD_(gdl, gsDPLoadTextureTileYuv, __VA_ARGS__) -#define _gDPLoadTextureTile(gdl, ...) \ - gD_(gdl, _gsDPLoadTextureTile, __VA_ARGS__) -#define _gDPLoadTextureTile_4b(gdl, ...) \ - gD_(gdl, _gsDPLoadTextureTile_4b, __VA_ARGS__) -#define _gDPLoadTextureTileYuv(gdl, ...) \ - gD_(gdl, _gsDPLoadTextureTileYuv, __VA_ARGS__) -#define gDPLoadMultiTile(gdl, ...) \ - gD_(gdl, gsDPLoadMultiTile, __VA_ARGS__) -#define gDPLoadMultiTile_4b(gdl, ...) \ - gD_(gdl, gsDPLoadMultiTile_4b, __VA_ARGS__) -#define gDPLoadMultiTileYuv(gdl, ...) \ - gD_(gdl, gsDPLoadMultiTileYuv, __VA_ARGS__) -#define gDPLoadBlock(gdl, ...) \ - gD_(gdl, gsDPLoadBlock, __VA_ARGS__) -#define gDPNoOp(gdl) \ - gDisplayListPut(gdl, gsDPNoOp()) -#define gDPNoOpTag(gdl, ...) \ - gD_(gdl, gsDPNoOpTag, __VA_ARGS__) -#define gDPPipelineMode(gdl, ...) \ - gD_(gdl, gsDPPipelineMode, __VA_ARGS__) -#define gDPSetBlendColor(gdl, ...) \ - gD_(gdl, gsDPSetBlendColor, __VA_ARGS__) -#define gDPSetEnvColor(gdl, ...) \ - gD_(gdl, gsDPSetEnvColor, __VA_ARGS__) -#define gDPSetFillColor(gdl, ...) \ - gD_(gdl, gsDPSetFillColor, __VA_ARGS__) -#define gDPSetFogColor(gdl, ...) \ - gD_(gdl, gsDPSetFogColor, __VA_ARGS__) -#define gDPSetPrimColor(gdl, ...) \ - gD_(gdl, gsDPSetPrimColor, __VA_ARGS__) -#define gDPSetColorImage(gdl, ...) \ - gD_(gdl, gsDPSetColorImage, __VA_ARGS__) -#define gDPSetDepthImage(gdl, ...) \ - gD_(gdl, gsDPSetDepthImage, __VA_ARGS__) -#define gDPSetTextureImage(gdl, ...) \ - gD_(gdl, gsDPSetTextureImage, __VA_ARGS__) -#define gDPSetHilite1Tile(gdl, ...) \ - gD_(gdl, gsDPSetHilite1Tile, __VA_ARGS__) -#define gDPSetHilite2Tile(gdl, ...) \ - gD_(gdl, gsDPSetHilite2Tile, __VA_ARGS__) -#define gDPSetAlphaCompare(gdl, ...) \ - gD_(gdl, gsDPSetAlphaCompare, __VA_ARGS__) -#define gDPSetAlphaDither(gdl, ...) \ - gD_(gdl, gsDPSetAlphaDither, __VA_ARGS__) -#define gDPSetColorDither(gdl, ...) \ - gD_(gdl, gsDPSetColorDither, __VA_ARGS__) -#define gDPSetCombineMode(gdl, ...) \ - gD_(gdl, gsDPSetCombineLERP, __VA_ARGS__) -#define gDPSetCombineLERP(gdl, ...) \ - gD_(gdl, gsDPSetCombineLERP, __VA_ARGS__) -#define gDPSetConvert(gdl, ...) \ - gD_(gdl, gsDPSetConvert, __VA_ARGS__) -#define gDPSetTextureConvert(gdl, ...) \ - gD_(gdl, gsDPSetTextureConvert, __VA_ARGS__) -#define gDPSetCycleType(gdl, ...) \ - gD_(gdl, gsDPSetCycleType, __VA_ARGS__) -#define gDPSetDepthSource(gdl, ...) \ - gD_(gdl, gsDPSetDepthSource, __VA_ARGS__) -#define gDPSetCombineKey(gdl, ...) \ - gD_(gdl, gsDPSetCombineKey, __VA_ARGS__) -#define gDPSetKeyGB(gdl, ...) \ - gD_(gdl, gsDPSetKeyGB, __VA_ARGS__) -#define gDPSetKeyR(gdl, ...) \ - gD_(gdl, gsDPSetKeyR, __VA_ARGS__) -#define gDPSetPrimDepth(gdl, ...) \ - gD_(gdl, gsDPSetPrimDepth, __VA_ARGS__) -#define gDPSetRenderMode(gdl, ...) \ - gD_(gdl, gsDPSetRenderMode, __VA_ARGS__) -#define gDPSetScissor(gdl, ...) \ - gD_(gdl, gsDPSetScissor, __VA_ARGS__) -#define gDPSetScissorFrac(gdl, ...) \ - gD_(gdl, gsDPSetScissorFrac, __VA_ARGS__) -#define gDPSetTextureDetail(gdl, ...) \ - gD_(gdl, gsDPSetTextureDetail, __VA_ARGS__) -#define gDPSetTextureFilter(gdl, ...) \ - gD_(gdl, gsDPSetTextureFilter, __VA_ARGS__) -#define gDPSetTextureLOD(gdl, ...) \ - gD_(gdl, gsDPSetTextureLOD, __VA_ARGS__) -#define gDPSetTextureLUT(gdl, ...) \ - gD_(gdl, gsDPSetTextureLUT, __VA_ARGS__) -#define gDPSetTexturePersp(gdl, ...) \ - gD_(gdl, gsDPSetTexturePersp, __VA_ARGS__) -#define gDPSetTile(gdl, ...) \ - gD_(gdl, gsDPSetTile, __VA_ARGS__) -#define gDPSetTileSize(gdl, ...) \ - gD_(gdl, gsDPSetTileSize, __VA_ARGS__) -#define gSP1Triangle(gdl, ...) \ - gD_(gdl, gsSP1Triangle, __VA_ARGS__) -#if defined(F3DEX_GBI) || defined(F3DEX_GBI_2) -# define gSP2Triangles(gdl, ...) \ - gD_(gdl, gsSP2Triangles, __VA_ARGS__) -# define gSP1Quadrangle(gdl, ...) \ - gD_(gdl, gsSP1Quadrangle, __VA_ARGS__) -# define gSPBranchLessZ(gdl, ...) \ - gD_(gdl, gsSPBranchLessZ, __VA_ARGS__) -# define gSPBranchLessZrg(gdl, ...) \ - gD_(gdl, gsSPBranchLessZrg, __VA_ARGS__) -# define gSPBranchLessZraw(gdl, ...) \ - gD_(gdl, gsSPBranchLessZraw, __VA_ARGS__) -#endif -#define gSPBranchList(gdl, ...) \ - gD_(gdl, gsSPBranchList, __VA_ARGS__) -#define gSPClipRatio(gdl, ...) \ - gD_(gdl, gsSPClipRatio, __VA_ARGS__) -#define gSPCullDisplayList(gdl, ...) \ - gD_(gdl, gsSPCullDisplayList, __VA_ARGS__) -#define gSPDisplayList(gdl, ...) \ - gD_(gdl, gsSPDisplayList, __VA_ARGS__) -#define gSPEndDisplayList(gdl) \ - gDisplayListPut(gdl, gsSPEndDisplayList()) -#define gSPFogFactor(gdl, ...) \ - gD_(gdl, gsSPFogFactor, __VA_ARGS__) -#define gSPFogPosition(gdl, ...) \ - gD_(gdl, gsSPFogPosition, __VA_ARGS__) -#define gSPForceMatrix(gdl, ...) \ - gD_(gdl, gsSPForceMatrix, __VA_ARGS__) -#define gSPSetGeometryMode(gdl, ...) \ - gD_(gdl, gsSPSetGeometryMode, __VA_ARGS__) -#define gSPClearGeometryMode(gdl, ...) \ - gD_(gdl, gsSPClearGeometryMode, __VA_ARGS__) -#define gSPLoadGeometryMode(gdl, ...) \ - gD_(gdl, gsSPLoadGeometryMode, __VA_ARGS__) -#if defined(F3D_GBI) || defined(F3DEX_GBI) -# define gSPInsertMatrix(gdl, ...) \ - gD_(gdl, gsSPInsertMatrix, __VA_ARGS__) -#endif -#define gSPLine3D(gdl, ...) \ - gD_(gdl, gsSPLine3D, __VA_ARGS__) -#define gSPLineW3D(gdl, ...) \ - gD_(gdl, gsSPLineW3D, __VA_ARGS__) -#define gSPLoadUcode(gdl, ...) \ - gD_(gdl, gsSPLoadUcode, __VA_ARGS__) -#define gSPLoadUcodeL(gdl, ...) \ - gD_(gdl, gsSPLoadUcodeL, __VA_ARGS__) -#define gSPLookAtX(gdl, ...) \ - gD_(gdl, gsSPLookAtX, __VA_ARGS__) -#define gSPLookAtY(gdl, ...) \ - gD_(gdl, gsSPLookAtY, __VA_ARGS__) -#define gSPLookAt(gdl, ...) \ - gD_(gdl, gsSPLookAt, __VA_ARGS__) -#define gSPMatrix(gdl, ...) \ - gD_(gdl, gsSPMatrix, __VA_ARGS__) -#define gSPModifyVertex(gdl, ...) \ - gD_(gdl, gsSPModifyVertex, __VA_ARGS__) -#define gSPPerspNormalize(gdl, ...) \ - gD_(gdl, gsSPPerspNormalize, __VA_ARGS__) -#define gSPPopMatrix(gdl, ...) \ - gD_(gdl, gsSPPopMatrix, __VA_ARGS__) -#if defined(F3DEX_GBI_2) -# define gSPPopMatrixN(gdl, ...) \ - gD_(gdl, gsSPPopMatrixN, __VA_ARGS__) -#endif -#define gSPSegment(gdl, ...) \ - gD_(gdl, gsSPSegment, __VA_ARGS__) -#define gSPSetLights0(gdl, ...) \ - gD_(gdl, gsSPSetLights0, __VA_ARGS__) -#define gSPSetLights1(gdl, ...) \ - gD_(gdl, gsSPSetLights1, __VA_ARGS__) -#define gSPSetLights2(gdl, ...) \ - gD_(gdl, gsSPSetLights2, __VA_ARGS__) -#define gSPSetLights3(gdl, ...) \ - gD_(gdl, gsSPSetLights3, __VA_ARGS__) -#define gSPSetLights4(gdl, ...) \ - gD_(gdl, gsSPSetLights4, __VA_ARGS__) -#define gSPSetLights5(gdl, ...) \ - gD_(gdl, gsSPSetLights5, __VA_ARGS__) -#define gSPSetLights6(gdl, ...) \ - gD_(gdl, gsSPSetLights6, __VA_ARGS__) -#define gSPSetLights7(gdl, ...) \ - gD_(gdl, gsSPSetLights7, __VA_ARGS__) -#define gSPSetStatus(gdl, ...) \ - gD_(gdl, gsSPSetStatus, __VA_ARGS__) -#define gSPNumLights(gdl, ...) \ - gD_(gdl, gsSPNumLights, __VA_ARGS__) -#define gSPLight(gdl, ...) \ - gD_(gdl, gsSPLight, __VA_ARGS__) -#define gSPLightColor(gdl, ...) \ - gD_(gdl, gsSPLightColor, __VA_ARGS__) -#define gSPTexture(gdl, ...) \ - gD_(gdl, gsSPTexture, __VA_ARGS__) -#define gSPTextureRectangle(gdl, ...) \ - gD_(gdl, gsSPTextureRectangle, __VA_ARGS__) -#define gSPScisTextureRectangle(gdl, ...) \ - gD_(gdl, gsSPScisTextureRectangle, __VA_ARGS__) -#define gSPTextureRectangleFlip(gdl, ...) \ - gD_(gdl, gsSPTextureRectangleFlip, __VA_ARGS__) -#define gSPScisTextureRectangleFlip(gdl, ...) \ - gD_(gdl, gsSPScisTextureRectangleFlip, __VA_ARGS__) -#define gSPVertex(gdl, ...) \ - gD_(gdl, gsSPVertex, __VA_ARGS__) -#define gSPViewport(gdl, ...) \ - gD_(gdl, gsSPViewport, __VA_ARGS__) -#define gSPBgRectCopy(gdl, ...) \ - gD_(gdl, gsSPBgRectCopy, __VA_ARGS__) -#define gSPBgRect1Cyc(gdl, ...) \ - gD_(gdl, gsSPBgRect1Cyc, __VA_ARGS__) -#define gSPObjRectangle(gdl, ...) \ - gD_(gdl, gsSPObjRectangle, __VA_ARGS__) -#define gSPObjRectangleR(gdl, ...) \ - gD_(gdl, gsSPObjRectangleR, __VA_ARGS__) -#define gSPObjSprite(gdl, ...) \ - gD_(gdl, gsSPObjSprite, __VA_ARGS__) -#define gSPObjMatrix(gdl, ...) \ - gD_(gdl, gsSPObjMatrix, __VA_ARGS__) -#define gSPObjSubMatrix(gdl, ...) \ - gD_(gdl, gsSPObjSubMatrix, __VA_ARGS__) -#define gSPObjRenderMode(gdl, ...) \ - gD_(gdl, gsSPObjRenderMode, __VA_ARGS__) -#define gSPObjLoadTxtr(gdl, ...) \ - gD_(gdl, gsSPObjLoadTxtr, __VA_ARGS__) -#define gSPObjLoadTxRect(gdl, ...) \ - gD_(gdl, gsSPObjLoadTxRect, __VA_ARGS__) -#define gSPObjLoadTxRectR(gdl, ...) \ - gD_(gdl, gsSPObjLoadTxRectR, __VA_ARGS__) -#define gSPObjLoadTxSprite(gdl, ...) \ - gD_(gdl, gsSPObjLoadTxSprite, __VA_ARGS__) -#define gSPSelectDL(gdl, ...) \ - gD_(gdl, gsSPSelectDL, __VA_ARGS__) -#define gSPSelectBranchDL(gdl, ...) \ - gD_(gdl, gsSPSelectBranchDL, __VA_ARGS__) -#define gDPLoadTLUTCmd(gdl, ...) \ - gD_(gdl, gsDPLoadTLUTCmd, __VA_ARGS__) -#define gDPLoadTLUT(gdl, ...) \ - gD_(gdl, gsDPLoadTLUT, __VA_ARGS__) -#if defined(F3DEX_GBI) || defined(F3DEX_GBI_2) -# define gBranchZ(gdl, ...) \ - gD_(gdl, gsBranchZ, __VA_ARGS__) -#endif -#define gDisplayList(gdl, ...) \ - gD_(gdl, gsDisplayList, __VA_ARGS__) -#define gDPHalf1(gdl, ...) \ - gD_(gdl, gsDPHalf1, __VA_ARGS__) -#define gDPHalf2(gdl, ...) \ - gD_(gdl, gsDPHalf2, __VA_ARGS__) -#define gDPLoadTile(gdl, ...) \ - gD_(gdl, gsDPLoadTile, __VA_ARGS__) -#define gDPSetCombine(gdl, ...) \ - gD_(gdl, gsDPSetCombine, __VA_ARGS__) -#if defined(F3DEX_GBI_2) -# define gSPGeometryMode(gdl, ...) \ - gD_(gdl, gsSPGeometryMode, __VA_ARGS__) -#endif -#define gSPSetOtherMode(gdl, ...) \ - gD_(gdl, gsSPSetOtherMode, __VA_ARGS__) -#define gSPSetOtherModeLo(gdl, ...) \ - gD_(gdl, gsSPSetOtherModeLo, __VA_ARGS__) -#define gSPSetOtherModeHi(gdl, ...) \ - gD_(gdl, gsSPSetOtherModeHi, __VA_ARGS__) -#define gDPSetOtherMode(gdl, ...) \ - gD_(gdl, gsDPSetOtherMode, __VA_ARGS__) -#define gMoveWd(gdl, ...) \ - gD_(gdl, gsMoveWd, __VA_ARGS__) -#define gMoveMem(gdl, ...) \ - gD_(gdl, gsMoveMem, __VA_ARGS__) -#if defined(F3DEX_GBI_2) -# define gSPDma_io(gdl, ...) \ - gD_(gdl, gsSPDma_io, __VA_ARGS__) -# define gSPDmaRead(gdl, ...) \ - gD_(gdl, gsSPDmaRead, __VA_ARGS__) -# define gSPDmaWrite(gdl, ...) \ - gD_(gdl, gsSPDmaWrite, __VA_ARGS__) -#endif -#if defined(F3DEX_GBI) || defined(F3DEX_GBI_2) -# define gLoadUcode(gdl, ...) \ - gD_(gdl, gsLoadUcode, __VA_ARGS__) -# define gSPLoadUcodeEx(gdl, ...) \ - gD_(gdl, gsSPLoadUcodeEx, __VA_ARGS__) -#endif -#define gTexRect(gdl, ...) \ - gD_(gdl, gsTexRect, __VA_ARGS__) -#define gTexRectFlip(gdl, ...) \ - gD_(gdl, gsTexRectFlip, __VA_ARGS__) -#define gSPNoOp(gdl) \ - gDisplayListPut(gdl, gsSPNoOp()) -#define gDPWord(gdl, ...) \ - gD_(gdl, gsDPWord, __VA_ARGS__) -#if defined(F3DEX_GBI_2) -# define gSpecial3(gdl, ...) \ - gD_(gdl, gsSpecial3, __VA_ARGS__) -# define gSpecial2(gdl, ...) \ - gD_(gdl, gsSpecial2, __VA_ARGS__) -# define gSpecial1(gdl, ...) \ - gD_(gdl, gsSpecial1, __VA_ARGS__) -#endif - -/* data types and structures */ -typedef uint8_t qu08_t; -typedef uint16_t qu016_t; -typedef int16_t qs48_t; -typedef int16_t qs510_t; -typedef uint16_t qu510_t; -typedef int16_t qs102_t; -typedef uint16_t qu102_t; -typedef int16_t qs105_t; -typedef uint16_t qu105_t; -typedef int16_t qs132_t; -typedef int16_t qs142_t; -typedef int32_t qs1516_t; -typedef int32_t qs1616_t; -typedef int32_t qs205_t; - -typedef uint16_t g_bglt_t; -typedef uint8_t g_ifmt_t; -typedef uint8_t g_isiz_t; -typedef uint16_t g_bgf_t; -typedef uint8_t g_objf_t; -typedef uint32_t g_objlt_t; - -typedef struct -{ - _Alignas(8) - uint32_t hi; - uint32_t lo; -} Gfx; - -typedef struct -{ - int32_t x1; - int32_t y1; - int32_t x2; - int32_t y2; -} Hilite_t; - -typedef union -{ - _Alignas(8) - Hilite_t h; -} Hilite; - -typedef int32_t Mtx_t[4][4]; - -typedef union -{ - _Alignas(8) - Mtx_t m; - int32_t l[16]; - struct - { - int16_t i[16]; - uint16_t f[16]; - }; -} Mtx; - -typedef struct -{ - uint8_t col[3]; - char pad1; - uint8_t colc[3]; - char pad2; - int8_t dir[3]; - char pad3; -} Light_t; - -typedef union -{ - _Alignas(8) - Light_t l; -} Light; - -typedef struct -{ - Light l[2]; -} LookAt; - -typedef struct -{ - uint8_t col[3]; - char pad1; - uint8_t colc[3]; - char pad2; -} Ambient_t; - -typedef union -{ - _Alignas(8) - Ambient_t l; -} Ambient; - -typedef struct -{ - Ambient a; - Light l[1]; -} Lights0, Lights1; - -typedef struct -{ - Ambient a; - Light l[2]; -} Lights2; - -typedef struct -{ - Ambient a; - Light l[3]; -} Lights3; - -typedef struct -{ - Ambient a; - Light l[4]; -} Lights4; - -typedef struct -{ - Ambient a; - Light l[5]; -} Lights5; - -typedef struct -{ - Ambient a; - Light l[6]; -} Lights6; - -typedef struct -{ - Ambient a; - Light l[7]; -} Lightsn, Lights7; - -typedef struct -{ - int16_t ob[3]; - uint16_t flag; - qs105_t tc[2]; - uint8_t cn[4]; -} Vtx_t; - -typedef struct -{ - int16_t ob[3]; - uint16_t flag; - qs105_t tc[2]; - int8_t n[3]; - uint8_t a; -} Vtx_tn; - -typedef union -{ - _Alignas(8) - Vtx_t v; - Vtx_tn n; -} Vtx; - -typedef struct -{ - qs142_t vscale[4]; - qs142_t vtrans[4]; -} Vp_t; - -typedef union -{ - _Alignas(8) - Vp_t vp; -} Vp; - -typedef struct -{ - qs1516_t A; - qs1516_t B; - qs1516_t C; - qs1516_t D; - qs102_t X; - qs102_t Y; - qu510_t BaseScaleX; - qu510_t BaseScaleY; -} uObjMtx_t; - -typedef union -{ - _Alignas(8) - uObjMtx_t m; -} uObjMtx; - -typedef struct -{ - qs102_t X; - qs102_t Y; - qu510_t BaseScaleX; - qu510_t BaseScaleY; -} uObjSubMtx_t; - -typedef union -{ - _Alignas(8) - uObjSubMtx_t m; -} uObjSubMtx; - -typedef struct -{ - qu105_t imageX; - qu102_t imageW; - qs102_t frameX; - qu102_t frameW; - qu105_t imageY; - qu102_t imageH; - qs102_t frameY; - qu102_t frameH; - uint64_t * imagePtr; - g_bglt_t imageLoad; - g_ifmt_t imageFmt; - g_isiz_t imageSiz; - uint16_t imagePal; - g_bgf_t imageFlip; - uint16_t tmemW; - qs132_t tmemH; - uint16_t tmemLoadSH; - uint16_t tmemLoadTH; - uint16_t tmemSizeW; - uint16_t tmemSize; -} uObjBg_t; - -typedef struct -{ - qu105_t imageX; - qu102_t imageW; - qs102_t frameX; - qu102_t frameW; - qu105_t imageY; - qu102_t imageH; - qs102_t frameY; - qu102_t frameH; - uint64_t * imagePtr; - g_bglt_t imageLoad; - g_ifmt_t imageFmt; - g_isiz_t imageSiz; - uint16_t imagePal; - g_bgf_t imageFlip; - qu510_t scaleW; - qu510_t scaleH; - qs205_t imageYorig; - char padding[4]; -} uObjScaleBg_t; - -typedef union -{ - _Alignas(8) - uObjBg_t b; - uObjScaleBg_t s; -} uObjBg; - -typedef struct -{ - qs102_t objX; - qu510_t scaleW; - qu105_t imageW; - uint16_t paddingX; - qs102_t objY; - qu510_t scaleH; - qu105_t imageH; - uint16_t paddingY; - uint16_t imageStride; - uint16_t imageAdrs; - g_ifmt_t imageFmt; - g_isiz_t imageSiz; - uint16_t imagePal; - g_objf_t imageFlags; -} uObjSprite_t; - -typedef union -{ - _Alignas(8) - uObjSprite_t s; -} uObjSprite; - -typedef struct -{ - g_objlt_t type; - uint64_t * image; - uint16_t tmem; - uint16_t tsize; - uint16_t tline; - uint16_t sid; - uint32_t flag; - uint32_t mask; -} uObjTxtrBlock_t; - -typedef struct -{ - g_objlt_t type; - uint64_t * image; - uint16_t tmem; - uint16_t twidth; - uint16_t theight; - uint16_t sid; - uint32_t flag; - uint32_t mask; -} uObjTxtrTile_t; - -typedef struct -{ - g_objlt_t type; - uint64_t * image; - uint16_t phead; - uint16_t pnum; - uint16_t zero; - uint16_t sid; - uint32_t flag; - uint32_t mask; -} uObjTxtrTLUT_t; - -typedef union -{ - _Alignas(8) - uObjTxtrBlock_t block; - uObjTxtrTile_t tile; - uObjTxtrTLUT_t tlut; -} uObjTxtr; - -typedef struct -{ - uObjTxtr txtr; - uObjSprite sprite; -} uObjTxSprite; - -/* rectangle scissoring macros */ -#define gScC_(c) ((c) < 0 ? 0 : (c)) -#define gScD_(t, c, d) \ - ( \ - (c) < 0 ? \ - ( \ - (d) < 0 ? \ - (t) + (c) * (d) / 0x80 : \ - (t) - (c) * (d) / 0x80 \ - ) : \ - (t) \ - ) - -/* texture loading helper macros */ -#define G_SIZ_LDSIZ(siz) ((siz) < G_IM_SIZ_16b ? G_IM_SIZ_16b : (siz)) -#define G_SIZ_BITS(siz) (4 << gI_(siz)) -#define G_SIZ_LDBITS(siz) ((siz) < G_IM_SIZ_16b ? G_SIZ_BITS(siz) : 16) -#define G_DXT(siz, width) \ - ( \ - (width) * G_SIZ_BITS(siz) > 64 ? \ - ((1 << 11) + (width) * G_SIZ_BITS(siz) / 64 - 1) / \ - ((width) * G_SIZ_BITS(siz) / 64) : \ - (1 << 11) \ - ) -#define G_LTB_LRS(width, height, siz) \ - ( \ - (((width) * (height) + 1) * G_SIZ_BITS(siz) - 1) / \ - G_SIZ_BITS(G_SIZ_LDSIZ(siz)) - 1 \ - ) -#define G_LDBLK_TXL(txl) \ - ( \ - (txl) > G_TX_LDBLK_MAX_TXL ? \ - G_TX_LDBLK_MAX_TXL : \ - (txl) \ - ) - -/* depth value macros */ -#define gZp_(zval, near, far) \ - ( \ - (1.f - (float)(near) / (float)(zval)) / \ - (1.f - (float)(near) / (float)(far)) \ - ) -#define gZo_(zval, near, far) \ - ( \ - ((float)(zval) - (float)(near)) / \ - ((float)(far) - (float)(near)) \ - ) -#define gZf_(zval, near, far, flag) \ - qs1616 \ - ( \ - (flag) == G_BZ_PERSP ? \ - gZp_(zval, near, far) : \ - gZo_(zval, near, far) \ - ) -#define G_DEPTOZSrg(zval, near, far, flag, zmin, zmax) \ - ( \ - gZf_(zval, near, far, flag) * \ - ((int32_t)((zmax) - (zmin)) & ~(int32_t)1) + \ - qs1616(zmin) \ - ) -#define G_DEPTOZS(zval, near, far, flag) \ - G_DEPTOZSrg(zval, near, far, flag, 0, G_MAXZ) - -/* vertex ordering macros */ -#define gV2_(v0, v1, flag) \ - ( \ - (flag) == 0 ? gI_(v0) : \ - gI_(v1) \ - ) -#define gV3_(v0, v1, v2, flag) \ - ( \ - (flag) == 0 ? gI_(v0) : \ - (flag) == 1 ? gI_(v1) : \ - gI_(v2) \ - ) -#define gV4_(v0, v1, v2, v3, flag) \ - ( \ - (flag) == 0 ? gI_(v0) : \ - (flag) == 1 ? gI_(v1) : \ - (flag) == 2 ? gI_(v2) : \ - gI_(v3) \ - ) - -/* sprite texture parameter macros */ -#define GS_PIX2TMEM(pix, siz) ((pix) * G_SIZ_BITS(siz) / 64) -#define GS_TB_TSIZE(pix, siz) (GS_PIX2TMEM(pix, siz) - 1) -#define GS_TB_TLINE(pix, siz) (((1 << 11) - 1) / GS_PIX2TMEM(pix, siz) + 1) -#define GS_TT_TWIDTH(pix, siz) (GS_PIX2TMEM(pix, siz) * 4 - 1) -#define GS_TT_THEIGHT(pix, siz) ((pix) * 4 - 1) -#define GS_PAL_HEAD(head) ((head) + 256) -#define GS_PAL_NUM(num) ((num) - 1) - -/* fixed-point conversion macros */ -#define qu08(n) ((qu08_t)((n) * 0x100)) -#define qu016(n) ((qu016_t)((n) * 0x10000)) -#define qs48(n) ((qs48_t)((n) * 0x0100)) -#define qs510(n) ((qs510_t)((n) * 0x0400)) -#define qu510(n) ((qu510_t)((n) * 0x0400)) -#define qs102(n) ((qs102_t)((n) * 0x0004)) -#define qu102(n) ((qu102_t)((n) * 0x0004)) -#define qs105(n) ((qs105_t)((n) * 0x0020)) -#define qu105(n) ((qu105_t)((n) * 0x0020)) -#define qs132(n) ((qs132_t)((n) * 0x0004)) -#define qs142(n) ((qs142_t)((n) * 0x0004)) -#define qs1516(n) ((qs1516_t)((n) * 0x00010000)) -#define qs1616(n) ((qs1616_t)((n) * 0x00010000)) -#define qs205(n) ((qs205_t)((n) * 0x00000020)) - -/* private helper macros */ -#define gI_(i) ((uint32_t)(i)) -#define gL_(l) ((uint64_t)(l)) -#define gF_(i, n, s) ((gI_(i) & ((gI_(1) << (n)) - 1)) << (s)) -#define gFL_(l, n, s) ((gL_(l) & ((gL_(1) << (n)) - 1)) << (s)) -#define gO_(opc, hi, lo) ((Gfx){gF_(opc, 8, 24) | gI_(hi), gI_(lo)}) -#define gD_(gdl, m, ...) gDisplayListPut(gdl, m(__VA_ARGS__)) - -#endif diff --git a/tools/ZAPD/lib/libgfxd/gfxd.c b/tools/ZAPD/lib/libgfxd/gfxd.c deleted file mode 100644 index 76d7ded8a7..0000000000 --- a/tools/ZAPD/lib/libgfxd/gfxd.c +++ /dev/null @@ -1,863 +0,0 @@ -#include -#include -#include -#include -#include -#ifdef _WIN32 -# include -# define read _read -# define write _write -#else -# include -#endif -#include "gbi.h" -#include "gfxd.h" -#include "priv.h" - -static TLOCAL struct gfxd_state state; - -static int buffer_input_fn(void *buf, int count) -{ - if (count > config.input_buf_size) - count = config.input_buf_size; - memcpy(buf, config.input_buf, count); - config.input_buf += count; - config.input_buf_size -= count; - return count; -} - -static int buffer_output_fn(const char *buf, int count) -{ - if (count > config.output_buf_size) - count = config.output_buf_size; - memcpy(config.output_buf, buf, count); - config.output_buf += count; - config.output_buf_size -= count; - return count; -} - -static int fd_input_fn(void *buf, int count) -{ - return read(config.input_fd, buf, count); -} - -static int fd_output_fn(const char *buf, int count) -{ - return write(config.output_fd, buf, count); -} - -static void swap_words(Gfx *gfx) -{ - uint8_t b[8]; - uint8_t *pw = (void *) gfx; - uint8_t *pb = b; - - int endian = config.endian; - int wordsize = config.wordsize; - - for (int i = 0; i < 8 / wordsize; i++) - { - if (endian == gfxd_endian_host) - { - switch (wordsize) - { - case 1: - { - uint8_t w = *(uint8_t *) pw; - *pb++ = w >> 0; - break; - } - case 2: - { - uint16_t w = *(uint16_t *) pw; - *pb++ = w >> 8; - *pb++ = w >> 0; - break; - } - case 4: - { - uint32_t w = *(uint32_t *) pw; - *pb++ = w >> 24; - *pb++ = w >> 16; - *pb++ = w >> 8; - *pb++ = w >> 0; - break; - } - case 8: - { - uint64_t w = *(uint64_t *) pw; - *pb++ = w >> 56; - *pb++ = w >> 48; - *pb++ = w >> 40; - *pb++ = w >> 32; - *pb++ = w >> 24; - *pb++ = w >> 16; - *pb++ = w >> 8; - *pb++ = w >> 0; - break; - } - } - } - else - { - for (int j = 0; j < wordsize; j++) - { - if (endian == gfxd_endian_little) - *pb++ = pw[wordsize - 1 - j]; - else - *pb++ = pw[j]; - } - } - pw += wordsize; - } - - gfx->hi = ((uint32_t) b[0] << 24) - | ((uint32_t) b[1] << 16) - | ((uint32_t) b[2] << 8) - | ((uint32_t) b[3] << 0); - gfx->lo = ((uint32_t) b[4] << 24) - | ((uint32_t) b[5] << 16) - | ((uint32_t) b[6] << 8) - | ((uint32_t) b[7] << 0); -} - -static void get_more_input(void) -{ - if (state.end_input != 0) - return; - - char *recv_buf = (void *) &state.gfx[0]; - - while (state.n_gfx < sizeof(state.gfx) / sizeof(state.gfx[0])) - { - int n_read = sizeof(state.gfx) - state.n_byte; - n_read = config.input_fn(&recv_buf[state.n_byte], n_read); - if (n_read == 0) - return; - state.n_byte += n_read; - - while (state.n_gfx < state.n_byte / sizeof(Gfx)) - { - Gfx gfx = state.gfx[state.n_gfx]; - gfxd_macro_t *m = &state.macro[state.n_gfx]; - - swap_words(&gfx); - - int ret = config.ucode->disas_fn(m, gfx.hi, gfx.lo); - if (ret != 0 && config.stop_on_invalid != 0) - { - state.end_input = 1; - state.ret = ret; - return; - } - - state.n_gfx++; - } - } -} - -static int32_t typed_arg_i(int type, int idx) -{ - const gfxd_value_t *v = gfxd_value_by_type(type, idx); - if (v != NULL) - return v->i; - else - return -1; -} - -static uint32_t typed_arg_u(int type, int idx) -{ - const gfxd_value_t *v = gfxd_value_by_type(type, idx); - if (v != NULL) - return v->u; - else - return 0; -} - - -TLOCAL struct gfxd_config config = -{ - .ucode = NULL, - .endian = gfxd_endian_big, - .wordsize = 4, - .arg = NULL, - - .stop_on_invalid = 1, - .stop_on_end = 1, - .emit_dec_color = 0, - .emit_q_macro = 0, - .emit_ext_macro = 0, - - .input_buf = NULL, - .input_buf_size = 0, - .input_fn = &buffer_input_fn, - - .output_buf = NULL, - .output_buf_size = 0, - .output_fn = &buffer_output_fn, - - .macro_fn = &gfxd_macro_dflt, - .arg_fn = &gfxd_arg_dflt, - - .tlut_fn = NULL, - .timg_fn = NULL, - .cimg_fn = NULL, - .zimg_fn = NULL, - .dl_fn = NULL, - .mtx_fn = NULL, - .lookat_fn = NULL, - .light_fn = NULL, - .seg_fn = NULL, - .vtx_fn = NULL, - .vp_fn = NULL, - .uctext_fn = NULL, - .ucdata_fn = NULL, - .dram_fn = NULL, -}; - -void gfxd_input_buffer(const void *buf, int size) -{ - config.input_buf = buf; - config.input_buf_size = size; - config.input_fn = &buffer_input_fn; -} - -void gfxd_output_buffer(char *buf, int size) -{ - config.output_buf = buf; - config.output_buf_size = size; - config.output_fn = &buffer_output_fn; -} - -void gfxd_input_fd(int fd) -{ - config.input_fd = fd; - config.input_fn = &fd_input_fn; -} - -void gfxd_output_fd(int fd) -{ - config.output_fd = fd; - config.output_fn = &fd_output_fn; -} - -void gfxd_input_callback(gfxd_input_fn_t *fn) -{ - if (fn != NULL) - config.input_fn = fn; - else - gfxd_input_buffer(NULL, 0); -} - -void gfxd_output_callback(gfxd_output_fn_t *fn) -{ - if (fn != NULL) - config.output_fn = fn; - else - gfxd_output_buffer(NULL, 0); -} - -void gfxd_macro_fn(gfxd_macro_fn_t *fn) -{ - if (fn != NULL) - config.macro_fn = fn; - else - config.macro_fn = gfxd_macro_dflt; -} - -void gfxd_arg_fn(gfxd_arg_fn_t *fn) -{ - if (fn != NULL) - config.arg_fn = fn; - else - config.arg_fn = gfxd_arg_dflt; -} - -int gfxd_write(const void *buf, int count) -{ - return config.output_fn(buf, count); -} - -int gfxd_puts(const char *str) -{ - return gfxd_write(str, strlen(str)); -} - -int gfxd_printf(const char *fmt, ...) -{ - char s[256]; - - va_list arg; - va_start(arg, fmt); - int n = vsnprintf(s, sizeof(s), fmt, arg); - va_end(arg); - - if (n > sizeof(s) - 1) - n = sizeof(s) - 1; - - return gfxd_write(s, n); -} - -int gfxd_print_value(int type, const gfxd_value_t *value) -{ - return config.ucode->arg_tbl[type].fn(value); -} - -int gfxd_macro_dflt(void) -{ - gfxd_macro_t *m = &state.macro[0]; - const gfxd_macro_type_t *t = &config.ucode->macro_tbl[m->id]; - - const char *name = gfxd_macro_name(); - if (name == NULL) - { - if (config.arg != NULL) - { - gfxd_puts(config.arg); - gfxd_puts(" = "); - } - - gfxd_puts("(Gfx){"); - } - else - { - gfxd_puts(name); - gfxd_puts("("); - - if (config.arg != NULL) - { - gfxd_puts(config.arg); - if (t->n_arg != 0) - gfxd_puts(", "); - } - } - - for (int i = 0; i < t->n_arg; i++) - { - if (i != 0) - gfxd_puts(", "); - - config.arg_fn(i); - } - - if (name == NULL) - gfxd_puts("}"); - else - gfxd_puts(")"); - - return 0; -} - -int gfxd_arg_callbacks(int arg_num) -{ - int id = gfxd_macro_id(); - - switch (gfxd_arg_type(arg_num)) - { - case gfxd_Tlut: - { - if (config.tlut_fn != NULL) - { - int32_t num; - if (id == gfxd_DPLoadTLUT_pal16) - num = 16; - else if (id == gfxd_DPLoadTLUT_pal256) - num = 256; - else - num = typed_arg_i(gfxd_Num, 0); - return config.tlut_fn( - typed_arg_u(gfxd_Tlut, 0), - typed_arg_i(gfxd_Pal, 0), - num); - } - break; - } - case gfxd_Timg: - { - if (config.timg_fn != NULL) - { - int32_t siz = typed_arg_i(gfxd_Siz, 0); - if (siz == -1) - siz = G_IM_SIZ_4b; - return config.timg_fn( - typed_arg_u(gfxd_Timg, 0), - typed_arg_i(gfxd_Fmt, 0), - siz, - typed_arg_i(gfxd_Dim, 0), - typed_arg_i(gfxd_Dim, 1), - typed_arg_i(gfxd_Pal, 0)); - } - break; - } - case gfxd_Cimg: - { - if (config.cimg_fn != NULL) - { - return config.cimg_fn( - typed_arg_u(gfxd_Cimg, 0), - typed_arg_i(gfxd_Fmt, 0), - typed_arg_i(gfxd_Siz, 0), - typed_arg_i(gfxd_Dim, 0)); - } - break; - } - case gfxd_Zimg: - { - if (config.zimg_fn != NULL) - { - return config.zimg_fn( - typed_arg_u(gfxd_Zimg, 0)); - } - break; - } - case gfxd_Dl: - { - if (config.dl_fn != NULL) - { - return config.dl_fn( - typed_arg_u(gfxd_Dl, 0)); - } - break; - } - case gfxd_Mtxptr: - { - if (config.mtx_fn != NULL) - { - return config.mtx_fn( - typed_arg_u(gfxd_Mtxptr, 0)); - } - break; - } - case gfxd_Lookatptr: - { - if (config.lookat_fn != NULL) - { - int32_t num; - if (id == gfxd_SPLookAt) - num = 2; - else - num = 1; - return config.lookat_fn( - typed_arg_u(gfxd_Lookatptr, 0), - num); - } - break; - } - case gfxd_Lightptr: - { - if (config.light_fn != NULL) - { - int32_t num; - if (id == gfxd_SPSetLights1) - num = 1; - else if (id == gfxd_SPSetLights2) - num = 2; - else if (id == gfxd_SPSetLights3) - num = 3; - else if (id == gfxd_SPSetLights4) - num = 4; - else if (id == gfxd_SPSetLights5) - num = 5; - else if (id == gfxd_SPSetLights6) - num = 6; - else if (id == gfxd_SPSetLights7) - num = 7; - else - num = 1; - return config.light_fn( - typed_arg_u(gfxd_Lightptr, 0), - num); - } - break; - - } - case gfxd_Segptr: - { - if (config.seg_fn != NULL) - { - return config.seg_fn( - typed_arg_u(gfxd_Segptr, 0), - typed_arg_i(gfxd_Seg, 0)); - } - break; - } - case gfxd_Vtxptr: - { - if (config.vtx_fn != NULL) - { - return config.vtx_fn( - typed_arg_u(gfxd_Vtxptr, 0), - typed_arg_i(gfxd_Num, 0)); - } - break; - } - case gfxd_Vpptr: - { - if (config.vp_fn != NULL) - { - return config.vp_fn( - typed_arg_u(gfxd_Vpptr, 0)); - } - break; - } - case gfxd_Uctext: - { - if (config.uctext_fn != NULL) - { - return config.uctext_fn( - typed_arg_u(gfxd_Uctext, 0), - 0x1000); - } - break; - } - case gfxd_Ucdata: - { - if (config.ucdata_fn != NULL) - { - uint32_t size; - if (id == gfxd_SPLoadUcodeEx) - size = typed_arg_u(gfxd_Size, 0); - else - size = 0x800; - return config.ucdata_fn( - typed_arg_u(gfxd_Ucdata, 0), - size); - } - break; - } - case gfxd_Dram: - { - if (config.dram_fn != NULL) - { - return config.dram_fn( - typed_arg_u(gfxd_Dram, 0), - typed_arg_u(gfxd_Size, 0)); - } - break; - } - } - - return 0; -} - -void gfxd_arg_dflt(int arg_num) -{ - if (gfxd_arg_callbacks(arg_num) == 0) - { - gfxd_arg_t *a = &state.macro[0].arg[arg_num]; - - gfxd_print_value(a->type, &a->value); - } -} - -void gfxd_tlut_callback(gfxd_tlut_fn_t *fn) -{ - config.tlut_fn = fn; -} - -void gfxd_timg_callback(gfxd_timg_fn_t *fn) -{ - config.timg_fn = fn; -} - -void gfxd_cimg_callback(gfxd_cimg_fn_t *fn) -{ - config.cimg_fn = fn; -} - -void gfxd_zimg_callback(gfxd_zimg_fn_t *fn) -{ - config.zimg_fn = fn; -} - -void gfxd_dl_callback(gfxd_dl_fn_t *fn) -{ - config.dl_fn = fn; -} - -void gfxd_mtx_callback(gfxd_mtx_fn_t *fn) -{ - config.mtx_fn = fn; -} - -void gfxd_lookat_callback(gfxd_lookat_fn_t *fn) -{ - config.lookat_fn = fn; -} - -void gfxd_light_callback(gfxd_light_fn_t *fn) -{ - config.light_fn = fn; -} - -void gfxd_seg_callback(gfxd_seg_fn_t *fn) -{ - config.seg_fn = fn; -} - -void gfxd_vtx_callback(gfxd_vtx_fn_t *fn) -{ - config.vtx_fn = fn; -} - -void gfxd_vp_callback(gfxd_vp_fn_t *fn) -{ - config.vp_fn = fn; -} - -void gfxd_uctext_callback(gfxd_uctext_fn_t *fn) -{ - config.uctext_fn = fn; -} - -void gfxd_ucdata_callback(gfxd_ucdata_fn_t *fn) -{ - config.ucdata_fn = fn; -} - -void gfxd_dram_callback(gfxd_dram_fn_t *fn) -{ - config.dram_fn = fn; -} - -void gfxd_target(gfxd_ucode_t ucode) -{ - config.ucode = ucode; -} - -void gfxd_endian(int endian, int wordsize) -{ - config.endian = endian; - config.wordsize = wordsize; -} - -void gfxd_dynamic(const char *arg) -{ - config.arg = arg; -} - -void gfxd_enable(int cap) -{ - switch (cap) - { - case gfxd_stop_on_invalid: - config.stop_on_invalid = 1; - break; - - case gfxd_stop_on_end: - config.stop_on_end = 1; - break; - - case gfxd_emit_dec_color: - config.emit_dec_color = 1; - break; - - case gfxd_emit_q_macro: - config.emit_q_macro = 1; - break; - - case gfxd_emit_ext_macro: - config.emit_ext_macro = 1; - break; - } -} - -void gfxd_disable(int cap) -{ - switch (cap) - { - case gfxd_stop_on_invalid: - config.stop_on_invalid = 0; - return; - - case gfxd_stop_on_end: - config.stop_on_end = 0; - return; - - case gfxd_emit_dec_color: - config.emit_dec_color = 0; - break; - - case gfxd_emit_q_macro: - config.emit_q_macro = 0; - break; - - case gfxd_emit_ext_macro: - config.emit_ext_macro = 0; - break; - } -} - -void gfxd_udata_set(void *ptr) -{ - config.udata = ptr; -} - -void *gfxd_udata_get(void) -{ - return config.udata; -} - -int gfxd_execute(void) -{ - state.macro_offset = 0; - state.n_byte = 0; - state.n_gfx = 0; - state.end_input = 0; - state.ret = 0; - - for (;;) - { - get_more_input(); - if (state.n_gfx == 0) - break; - - gfxd_macro_t *m = &state.macro[0]; - config.ucode->combine_fn(m, state.n_gfx); - - const gfxd_macro_type_t *t = &config.ucode->macro_tbl[m->id]; - if (t->ext != 0 && config.emit_ext_macro == 0) - { - Gfx gfx = state.gfx[0]; - swap_words(&gfx); - - t = &config.ucode->macro_tbl[gfxd_Invalid]; - t->disas_fn(m, gfx.hi, gfx.lo); - } - - int ret = config.macro_fn(); - if (ret != 0) - { - state.ret = ret; - break; - } - - if (config.stop_on_end != 0 - && (m->id == gfxd_SPBranchList - || m->id == gfxd_SPEndDisplayList)) - { - break; - } - - int n_pop = config.ucode->macro_tbl[m->id].n_gfx; - int n_rem = state.n_gfx - n_pop; - { - int n_byte = n_rem * sizeof(gfxd_macro_t); - memmove(&state.macro[0], &state.macro[n_pop], n_byte); - state.n_gfx = n_rem; - } - { - int n_byte = n_rem * sizeof(Gfx); - memmove(&state.gfx[0], &state.gfx[n_pop], n_byte); - state.n_byte = n_byte; - } - state.macro_offset += n_pop * sizeof(Gfx); - } - - return state.ret; -} - -int gfxd_macro_offset(void) -{ - return state.macro_offset; -} - -int gfxd_macro_packets(void) -{ - return config.ucode->macro_tbl[state.macro[0].id].n_gfx; -} - -const void *gfxd_macro_data(void) -{ - return state.gfx; -} - -int gfxd_macro_id(void) -{ - return state.macro[0].id; -} - -const char *gfxd_macro_name(void) -{ - int id = state.macro[0].id; - const gfxd_macro_type_t *t = &config.ucode->macro_tbl[id]; - - if (t->prefix == NULL && t->suffix == NULL) - { - return NULL; - } - else - { - static TLOCAL char buf[32]; - - char *p = buf; - if (t->prefix != NULL) - { - const char *s = t->prefix; - while (*s != '\0') - *p++ = *s++; - } - *p++ = 'g'; - if (config.arg == NULL) - *p++ = 's'; - if (t->suffix != NULL) - { - const char *s = t->suffix; - while (*s != '\0') - *p++ = *s++; - } - *p++ = '\0'; - - return buf; - } -} - -int gfxd_arg_count(void) -{ - return config.ucode->macro_tbl[state.macro[0].id].n_arg; -} - -int gfxd_arg_type(int arg_num) -{ - return state.macro[0].arg[arg_num].type; -} - -const char *gfxd_arg_name(int arg_num) -{ - return state.macro[0].arg[arg_num].name; -} - -int gfxd_arg_fmt(int arg_num) -{ - return config.ucode->arg_tbl[state.macro[0].arg[arg_num].type].fmt; -} - -const gfxd_value_t *gfxd_arg_value(int arg_num) -{ - return &state.macro[0].arg[arg_num].value; -} - -const gfxd_value_t *gfxd_value_by_type(int type, int idx) -{ - gfxd_macro_t *m = &state.macro[0]; - const gfxd_macro_type_t *t = &config.ucode->macro_tbl[m->id]; - - for (int i = 0; i < t->n_arg; i++) - { - gfxd_arg_t *a = &m->arg[i]; - if (a->type == type) - { - if (idx == 0) - return &a->value; - else - idx--; - } - } - - return NULL; -} - -int gfxd_arg_valid(int arg_num) -{ - return state.macro[0].arg[arg_num].bad == 0; -} diff --git a/tools/ZAPD/lib/libgfxd/gfxd.h b/tools/ZAPD/lib/libgfxd/gfxd.h deleted file mode 100644 index 268bbfa10f..0000000000 --- a/tools/ZAPD/lib/libgfxd/gfxd.h +++ /dev/null @@ -1,387 +0,0 @@ -#ifndef GFXD_H -#define GFXD_H -#include - -#ifdef __cplusplus -extern "C" -{ -#endif - -enum -{ - gfxd_Word, /* generic word */ - gfxd_Opcode, /* command opcode (G_*) */ - gfxd_Coordi, /* integer coordinate */ - gfxd_Coordq, /* fractional (q10.2) coordinate */ - gfxd_Pal, /* palette index */ - gfxd_Tlut, /* tlut pointer */ - gfxd_Timg, /* texture image pointer */ - gfxd_Tmem, /* tmem address */ - gfxd_Tile, /* tile index */ - gfxd_Fmt, /* texture format */ - gfxd_Siz, /* texture pixel size */ - gfxd_Dim, /* integer dimension (width / height) */ - gfxd_Cm, /* clamp and mirror flags */ - gfxd_Tm, /* tile mask */ - gfxd_Ts, /* tile shift */ - gfxd_Dxt, /* texture dxt */ - gfxd_Tag, /* generic tag */ - gfxd_Pm, /* pipeline mode */ - gfxd_Colorpart, /* color component */ - gfxd_Color, /* color */ - gfxd_Lodfrac, /* lod fraction (q0.8) */ - gfxd_Cimg, /* color image pointer */ - gfxd_Zimg, /* depth image pointer */ - gfxd_Ac, /* alpha compare mode */ - gfxd_Ad, /* alpha dither mode */ - gfxd_Cd, /* color dither mode */ - gfxd_Ccpre, /* color combiner preset index */ - gfxd_Ccmuxa, /* color mux operand (a) */ - gfxd_Ccmuxb, /* color mux operand (b) */ - gfxd_Ccmuxc, /* color mux operand (c) */ - gfxd_Ccmuxd, /* color mux operand (d) */ - gfxd_Acmuxabd, /* alpha mux operand (a, b, or d) */ - gfxd_Acmuxc, /* alpha mux operand (c) */ - gfxd_Cv, /* color convert operand */ - gfxd_Tc, /* texture convert mode */ - gfxd_Cyc, /* cycle type */ - gfxd_Zs, /* depth source mode */ - gfxd_Ck, /* combine key mode */ - gfxd_Keyscale, /* combine key scale */ - gfxd_Keywidth, /* combine key width */ - gfxd_Zi, /* integer depth */ - gfxd_Rm1, /* cycle 1 render mode */ - gfxd_Rm2, /* cycle 2 render mode */ - gfxd_Sc, /* scissor mode */ - gfxd_Td, /* texture detail mode */ - gfxd_Tf, /* texture filter mode */ - gfxd_Tl, /* texture LOD mode */ - gfxd_Tt, /* textuure LUT mode */ - gfxd_Tp, /* texture perspective mode */ - gfxd_Line, /* texture line size */ - gfxd_Vtx, /* vertex index */ - gfxd_Vtxflag, /* vertex flag */ - gfxd_Dl, /* display list pointer */ - gfxd_Zraw, /* raw depth value (q16.16) */ - gfxd_Dlflag, /* display list flag */ - gfxd_Cr, /* clip ratio */ - gfxd_Num, /* element count */ - gfxd_Fogz, /* fog factor */ - gfxd_Fogp, /* fog position (0 - 1000) */ - gfxd_Mtxptr, /* matrix pointer */ - gfxd_Gm, /* geometry mode */ - gfxd_Mwo_matrix, /* matrix moveword offset */ - gfxd_Linewd, /* line width (1.5 + q7.1) */ - gfxd_Uctext, /* microcode text pointer */ - gfxd_Ucdata, /* microcode data pointer */ - gfxd_Size, /* data size */ - gfxd_Lookatptr, /* lookat pointer */ - gfxd_Mtxparam, /* matrix param */ - gfxd_Mtxstack, /* matrix param (stack select only) */ - gfxd_Mwo_point, /* vertex moveword offset */ - gfxd_Wscale, /* w-component scale (perspnorm) */ - gfxd_Seg, /* segment number */ - gfxd_Segptr, /* segment pointer */ - gfxd_Lightsn, /* dereferenced Lighstn pointer */ - gfxd_Numlights, /* light count (NUMLIGHTS_*) */ - gfxd_Lightnum, /* light number (LIGHT_*) */ - gfxd_Lightptr, /* light pointer */ - gfxd_Tcscale, /* texture coordinate scale */ - gfxd_Switch, /* on-off value */ - gfxd_St, /* vertex coordinate (q10.5) */ - gfxd_Stdelta, /* vertex coordinate delta (q5.10) */ - gfxd_Vtxptr, /* vertex pointer */ - gfxd_Vpptr, /* viewport pointer */ - gfxd_Dram, /* generic dram address */ - gfxd_Sftlo, /* othermode lo shift */ - gfxd_Othermodelo, /* othermode lo value */ - gfxd_Sfthi, /* othermode hi shift */ - gfxd_Othermodehi, /* othermode hi value */ - gfxd_Mw, /* moveword index */ - gfxd_Mwo, /* moveword offset */ - gfxd_Mwo_clip, /* clip ratio moveword offset */ - gfxd_Mwo_lightcol, /* light color moveword offset */ - gfxd_Mv, /* movemem index */ - gfxd_Mvo, /* movemem offset */ - gfxd_Dmem, /* dmem address */ - gfxd_Dmaflag, /* dma io flag */ -}; - -enum -{ - gfxd_Invalid, - gfxd_DPFillRectangle, - gfxd_DPFullSync, - gfxd_DPLoadSync, - gfxd_DPTileSync, - gfxd_DPPipeSync, - gfxd_DPLoadTLUT_pal16, - gfxd_DPLoadTLUT_pal256, - gfxd_DPLoadMultiBlockYuvS, - gfxd_DPLoadMultiBlockYuv, - gfxd_DPLoadMultiBlock_4bS, - gfxd_DPLoadMultiBlock_4b, - gfxd_DPLoadMultiBlockS, - gfxd_DPLoadMultiBlock, - gfxd__DPLoadTextureBlockYuvS, - gfxd__DPLoadTextureBlockYuv, - gfxd__DPLoadTextureBlock_4bS, - gfxd__DPLoadTextureBlock_4b, - gfxd__DPLoadTextureBlockS, - gfxd__DPLoadTextureBlock, - gfxd_DPLoadTextureBlockYuvS, - gfxd_DPLoadTextureBlockYuv, - gfxd_DPLoadTextureBlock_4bS, - gfxd_DPLoadTextureBlock_4b, - gfxd_DPLoadTextureBlockS, - gfxd_DPLoadTextureBlock, - gfxd_DPLoadMultiTileYuv, - gfxd_DPLoadMultiTile_4b, - gfxd_DPLoadMultiTile, - gfxd__DPLoadTextureTileYuv, - gfxd__DPLoadTextureTile_4b, - gfxd__DPLoadTextureTile, - gfxd_DPLoadTextureTileYuv, - gfxd_DPLoadTextureTile_4b, - gfxd_DPLoadTextureTile, - gfxd_DPLoadBlock, - gfxd_DPNoOp, - gfxd_DPNoOpTag, - gfxd_DPPipelineMode, - gfxd_DPSetBlendColor, - gfxd_DPSetEnvColor, - gfxd_DPSetFillColor, - gfxd_DPSetFogColor, - gfxd_DPSetPrimColor, - gfxd_DPSetColorImage, - gfxd_DPSetDepthImage, - gfxd_DPSetTextureImage, - gfxd_DPSetAlphaCompare, - gfxd_DPSetAlphaDither, - gfxd_DPSetColorDither, - gfxd_DPSetCombineMode, - gfxd_DPSetCombineLERP, - gfxd_DPSetConvert, - gfxd_DPSetTextureConvert, - gfxd_DPSetCycleType, - gfxd_DPSetDepthSource, - gfxd_DPSetCombineKey, - gfxd_DPSetKeyGB, - gfxd_DPSetKeyR, - gfxd_DPSetPrimDepth, - gfxd_DPSetRenderMode, - gfxd_DPSetScissor, - gfxd_DPSetScissorFrac, - gfxd_DPSetTextureDetail, - gfxd_DPSetTextureFilter, - gfxd_DPSetTextureLOD, - gfxd_DPSetTextureLUT, - gfxd_DPSetTexturePersp, - gfxd_DPSetTile, - gfxd_DPSetTileSize, - gfxd_SP1Triangle, - gfxd_SP2Triangles, - gfxd_SP1Quadrangle, - gfxd_SPBranchLessZraw, - gfxd_SPBranchList, - gfxd_SPClipRatio, - gfxd_SPCullDisplayList, - gfxd_SPDisplayList, - gfxd_SPEndDisplayList, - gfxd_SPFogFactor, - gfxd_SPFogPosition, - gfxd_SPForceMatrix, - gfxd_SPSetGeometryMode, - gfxd_SPClearGeometryMode, - gfxd_SPLoadGeometryMode, - gfxd_SPInsertMatrix, - gfxd_SPLine3D, - gfxd_SPLineW3D, - gfxd_SPLoadUcode, - gfxd_SPLookAtX, - gfxd_SPLookAtY, - gfxd_SPLookAt, - gfxd_SPMatrix, - gfxd_SPModifyVertex, - gfxd_SPPerspNormalize, - gfxd_SPPopMatrix, - gfxd_SPPopMatrixN, - gfxd_SPSegment, - gfxd_SPSetLights1, - gfxd_SPSetLights2, - gfxd_SPSetLights3, - gfxd_SPSetLights4, - gfxd_SPSetLights5, - gfxd_SPSetLights6, - gfxd_SPSetLights7, - gfxd_SPNumLights, - gfxd_SPLight, - gfxd_SPLightColor, - gfxd_SPTexture, - gfxd_SPTextureRectangle, - gfxd_SPTextureRectangleFlip, - gfxd_SPVertex, - gfxd_SPViewport, - gfxd_DPLoadTLUTCmd, - gfxd_DPLoadTLUT, - gfxd_BranchZ, - gfxd_DisplayList, - gfxd_DPHalf1, - gfxd_DPHalf2, - gfxd_DPWord, - gfxd_DPLoadTile, - gfxd_SPGeometryMode, - gfxd_SPSetOtherMode, - gfxd_SPSetOtherModeLo, - gfxd_SPSetOtherModeHi, - gfxd_DPSetOtherMode, - gfxd_MoveWd, - gfxd_MoveMem, - gfxd_SPDma_io, - gfxd_SPDmaRead, - gfxd_SPDmaWrite, - gfxd_LoadUcode, - gfxd_SPLoadUcodeEx, - gfxd_TexRect, - gfxd_TexRectFlip, - gfxd_SPNoOp, - gfxd_Special3, - gfxd_Special2, - gfxd_Special1, -}; - -enum -{ - gfxd_stop_on_invalid, - gfxd_stop_on_end, - gfxd_emit_dec_color, - gfxd_emit_q_macro, - gfxd_emit_ext_macro, -}; - -enum -{ - gfxd_endian_big, - gfxd_endian_little, - gfxd_endian_host, -}; - -enum -{ - gfxd_argfmt_i, - gfxd_argfmt_u, - gfxd_argfmt_f, -}; - -typedef union -{ - int32_t i; - uint32_t u; - float f; -} gfxd_value_t; - -typedef const struct gfxd_ucode *gfxd_ucode_t; - -typedef int gfxd_input_fn_t(void *buf, int count); -void gfxd_input_buffer(const void *buf, int size); -void gfxd_input_fd(int fd); -void gfxd_input_callback(gfxd_input_fn_t *fn); - -typedef int gfxd_output_fn_t(const char *buf, int count); -void gfxd_output_buffer(char *buf, int size); -void gfxd_output_fd(int fd); -void gfxd_output_callback(gfxd_output_fn_t *fn); - -typedef int gfxd_macro_fn_t(void); -void gfxd_macro_fn(gfxd_macro_fn_t *fn); -gfxd_macro_fn_t gfxd_macro_dflt; - -typedef void gfxd_arg_fn_t(int arg_num); -void gfxd_arg_fn(gfxd_arg_fn_t *fn); -gfxd_arg_fn_t gfxd_arg_dflt; - -typedef int gfxd_tlut_fn_t(uint32_t tlut, int32_t idx, int32_t count); -void gfxd_tlut_callback(gfxd_tlut_fn_t *fn); - -typedef int gfxd_timg_fn_t(uint32_t timg, int32_t fmt, int32_t siz, - int32_t width, int32_t height, int32_t pal); -void gfxd_timg_callback(gfxd_timg_fn_t *fn); - -typedef int gfxd_cimg_fn_t(uint32_t cimg, int32_t fmt, int32_t siz, - int32_t width); -void gfxd_cimg_callback(gfxd_cimg_fn_t *fn); - -typedef int gfxd_zimg_fn_t(uint32_t zimg); -void gfxd_zimg_callback(gfxd_zimg_fn_t *fn); - -typedef int gfxd_dl_fn_t(uint32_t dl); -void gfxd_dl_callback(gfxd_dl_fn_t *fn); - -typedef int gfxd_mtx_fn_t(uint32_t mtx); -void gfxd_mtx_callback(gfxd_mtx_fn_t *fn); - -typedef int gfxd_lookat_fn_t(uint32_t lookat, int32_t count); -void gfxd_lookat_callback(gfxd_lookat_fn_t *fn); - -typedef int gfxd_light_fn_t(uint32_t light, int32_t count); -void gfxd_light_callback(gfxd_light_fn_t *fn); - -typedef int gfxd_seg_fn_t(uint32_t seg, int32_t num); -void gfxd_seg_callback(gfxd_seg_fn_t *fn); - -typedef int gfxd_vtx_fn_t(uint32_t vtx, int32_t num); -void gfxd_vtx_callback(gfxd_vtx_fn_t *fn); - -typedef int gfxd_vp_fn_t(uint32_t vp); -void gfxd_vp_callback(gfxd_vp_fn_t *fn); - -typedef int gfxd_uctext_fn_t(uint32_t text, uint32_t size); -void gfxd_uctext_callback(gfxd_uctext_fn_t *fn); - -typedef int gfxd_ucdata_fn_t(uint32_t data, uint32_t size); -void gfxd_ucdata_callback(gfxd_ucdata_fn_t *fn); - -typedef int gfxd_dram_fn_t(uint32_t dram, uint32_t size); -void gfxd_dram_callback(gfxd_dram_fn_t *fn); - -int gfxd_write(const void *buf, int count); -int gfxd_puts(const char *str); -int gfxd_printf(const char *fmt, ...); -int gfxd_print_value(int type, const gfxd_value_t *value); - -void gfxd_target(gfxd_ucode_t ucode); -void gfxd_endian(int endian, int wordsize); -void gfxd_dynamic(const char *arg); -void gfxd_enable(int cap); -void gfxd_disable(int cap); -void gfxd_udata_set(void *ptr); -void *gfxd_udata_get(void); - -int gfxd_execute(void); - -int gfxd_macro_offset(void); -int gfxd_macro_packets(void); -const void *gfxd_macro_data(void); -int gfxd_macro_id(void); -const char *gfxd_macro_name(void); - -int gfxd_arg_count(void); -int gfxd_arg_type(int arg_num); -const char *gfxd_arg_name(int arg_num); -int gfxd_arg_fmt(int arg_num); -const gfxd_value_t *gfxd_arg_value(int arg_num); -const gfxd_value_t *gfxd_value_by_type(int type, int idx); -int gfxd_arg_valid(int arg_num); -int gfxd_arg_callbacks(int arg_num); - -extern const gfxd_ucode_t gfxd_f3d; -extern const gfxd_ucode_t gfxd_f3db; -extern const gfxd_ucode_t gfxd_f3dex; -extern const gfxd_ucode_t gfxd_f3dexb; -extern const gfxd_ucode_t gfxd_f3dex2; - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/tools/ZAPD/lib/libgfxd/priv.h b/tools/ZAPD/lib/libgfxd/priv.h deleted file mode 100644 index 37cb66b683..0000000000 --- a/tools/ZAPD/lib/libgfxd/priv.h +++ /dev/null @@ -1,123 +0,0 @@ -#ifndef GFXD_PRIV_H -#define GFXD_PRIV_H -#include "gfxd.h" - -#ifdef CONFIG_MT -# ifdef _MSC_VER -# define TLOCAL __declspec(thread) -# else -# define TLOCAL _Thread_local -# endif -#else -# define TLOCAL -#endif - -#define UCFUNC static inline - -#define config gfxd_config__ - -typedef int gfxd_argfn_t(const gfxd_value_t *v); - -typedef struct -{ - int fmt; - gfxd_argfn_t * fn; -} gfxd_arg_type_t; - -typedef struct -{ - int type; - const char * name; - gfxd_value_t value; - int bad; -} gfxd_arg_t; - -typedef struct -{ - int id; - gfxd_arg_t arg[18]; -} gfxd_macro_t; - -typedef int gfxd_disas_fn_t(gfxd_macro_t *macro, uint32_t hi, uint32_t lo); -typedef int gfxd_combine_fn_t(gfxd_macro_t *macro, int n_macro); - -typedef struct -{ - const char * prefix; - const char * suffix; - int opcode; - int n_arg; - int n_gfx; - gfxd_disas_fn_t * disas_fn; - gfxd_combine_fn_t * combine_fn; - int alias; - int ext; -} gfxd_macro_type_t; - -struct gfxd_ucode -{ - gfxd_disas_fn_t * disas_fn; - gfxd_combine_fn_t * combine_fn; - const gfxd_arg_type_t * arg_tbl; - const gfxd_macro_type_t * macro_tbl; -}; - -struct gfxd_state -{ - int macro_offset; - - Gfx gfx[9]; - int n_byte; - int n_gfx; - gfxd_macro_t macro[9]; - - int end_input; - int ret; -}; - -struct gfxd_config -{ - gfxd_ucode_t ucode; - int endian; - int wordsize; - const char * arg; - void * udata; - - int stop_on_invalid; - int stop_on_end; - int emit_dec_color; - int emit_q_macro; - int emit_ext_macro; - - const char * input_buf; - int input_buf_size; - int input_fd; - gfxd_input_fn_t * input_fn; - - char * output_buf; - int output_buf_size; - int output_fd; - gfxd_output_fn_t * output_fn; - - gfxd_macro_fn_t * macro_fn; - gfxd_arg_fn_t * arg_fn; - - gfxd_tlut_fn_t * tlut_fn; - gfxd_timg_fn_t * timg_fn; - gfxd_cimg_fn_t * cimg_fn; - gfxd_zimg_fn_t * zimg_fn; - gfxd_dl_fn_t * dl_fn; - gfxd_mtx_fn_t * mtx_fn; - gfxd_lookat_fn_t * lookat_fn; - gfxd_light_fn_t * light_fn; - gfxd_seg_fn_t * seg_fn; - gfxd_vtx_fn_t * vtx_fn; - gfxd_vp_fn_t * vp_fn; - gfxd_uctext_fn_t * uctext_fn; - gfxd_ucdata_fn_t * ucdata_fn; - gfxd_dram_fn_t * dram_fn; -}; - -extern TLOCAL struct gfxd_config gfxd_config__; - -#endif diff --git a/tools/ZAPD/lib/libgfxd/uc.c b/tools/ZAPD/lib/libgfxd/uc.c deleted file mode 100644 index 7efb091052..0000000000 --- a/tools/ZAPD/lib/libgfxd/uc.c +++ /dev/null @@ -1,54 +0,0 @@ -#include -#include -#include -#include "gbi.h" -#include "gfxd.h" -#include "priv.h" - -#include "uc_argfn.c" -#include "uc_argtbl.c" -#include "uc_macrofn.c" -#include "uc_macrotbl.c" - -UCFUNC int disas(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - int opcode = (hi >> 24) & 0xFF; - - for (int i = 0; i < sizeof(macro_tbl) / sizeof(macro_tbl[0]); i++) - { - const gfxd_macro_type_t *t = ¯o_tbl[i]; - if (t->disas_fn != NULL && t->opcode == opcode) - return t->disas_fn(m, hi, lo); - } - - return d_Invalid(m, hi, lo); -} - -UCFUNC int combine(gfxd_macro_t *m, int num) -{ - int opcode = macro_tbl[m->id].opcode; - - for (int i = 0; i < sizeof(macro_tbl) / sizeof(macro_tbl[0]); i++) - { - const gfxd_macro_type_t *t = ¯o_tbl[i]; - if (t->combine_fn != NULL - && t->opcode == opcode - && (t->ext == 0 || config.emit_ext_macro != 0)) - { - if (t->combine_fn(m, num) == 0) - return 0; - } - } - - return -1; -} - -static const struct gfxd_ucode uc = -{ - .disas_fn = disas, - .combine_fn = combine, - .arg_tbl = arg_tbl, - .macro_tbl = macro_tbl, -}; - -const gfxd_ucode_t uc_name = &uc; diff --git a/tools/ZAPD/lib/libgfxd/uc_argfn.c b/tools/ZAPD/lib/libgfxd/uc_argfn.c deleted file mode 100644 index f65feb60f7..0000000000 --- a/tools/ZAPD/lib/libgfxd/uc_argfn.c +++ /dev/null @@ -1,1814 +0,0 @@ -#define MDMASK(md) ((((uint32_t)1 << G_MDSIZ_##md) - 1) << G_MDSFT_##md) -#define MDMASK_RM_C1 ((uint32_t)0xCCCC0000) -#define MDMASK_RM_C2 ((uint32_t)0x33330000) -#define MDMASK_RM_LO ((uint32_t)0x0000FFF8) - -UCFUNC int argfn_i(const gfxd_value_t *v) -{ - return gfxd_printf("%" PRIi32, v->i); -} - -UCFUNC int argfn_u(const gfxd_value_t *v) -{ - return gfxd_printf("%" PRIu32, v->u); -} - -UCFUNC int argfn_x8(const gfxd_value_t *v) -{ - return gfxd_printf("0x%02" PRIX32, v->u); -} - -UCFUNC int argfn_x16(const gfxd_value_t *v) -{ - return gfxd_printf("0x%04" PRIX32, v->u); -} - -UCFUNC int argfn_x32(const gfxd_value_t *v) -{ - return gfxd_printf("0x%08" PRIX32, v->u); -} - -UCFUNC int argfn_color(const gfxd_value_t *v) -{ - if (config.emit_dec_color) - return gfxd_printf("%" PRIu32, v->u); - else - return gfxd_printf("0x%02" PRIX32, v->u); -} - -UCFUNC int argfn_qu08(const gfxd_value_t *v) -{ - if (v->u == 0) - return gfxd_puts("0"); - else if (config.emit_q_macro) - return gfxd_printf("qu08(%.16g)", v->u / 256.f); - else - return gfxd_printf("0x%02" PRIX32, v->u); -} - -UCFUNC int argfn_qu016(const gfxd_value_t *v) -{ - if (v->u == 0) - return gfxd_puts("0"); - else if (config.emit_q_macro) - return gfxd_printf("qu016(%.16g)", v->u / 65536.f); - else - return gfxd_printf("0x%04" PRIX32, v->u); -} - -UCFUNC int argfn_qs48(const gfxd_value_t *v) -{ - if (v->i == 0) - return gfxd_puts("0"); - else if (config.emit_q_macro) - return gfxd_printf("qs48(%.16g)", v->i / 256.f); - else - { - if (v->i < 0) - return gfxd_printf("-0x%04" PRIX32, (uint32_t)-v->i); - else - return gfxd_printf("0x%04" PRIX32, (uint32_t)v->i); - } -} - -UCFUNC int argfn_qs510(const gfxd_value_t *v) -{ - if (v->i == 0) - return gfxd_puts("0"); - else if (config.emit_q_macro) - return gfxd_printf("qs510(%.16g)", v->i / 1024.f); - else - { - if (v->i < 0) - return gfxd_printf("-0x%04" PRIX32, (uint32_t)-v->i); - else - return gfxd_printf("0x%04" PRIX32, (uint32_t)v->i); - } -} - -UCFUNC int argfn_qu102(const gfxd_value_t *v) -{ - if (v->u == 0) - return gfxd_puts("0"); - else if (config.emit_q_macro) - return gfxd_printf("qu102(%.16g)", v->u / 4.f); - else - return gfxd_printf("0x%04" PRIX32, v->u); -} - -UCFUNC int argfn_qs105(const gfxd_value_t *v) -{ - if (v->i == 0) - return gfxd_puts("0"); - else if (config.emit_q_macro) - return gfxd_printf("qs105(%.16g)", v->i / 32.f); - else - { - if (v->i < 0) - return gfxd_printf("-0x%04" PRIX32, (uint32_t)-v->i); - else - return gfxd_printf("0x%04" PRIX32, (uint32_t)v->i); - } -} - -UCFUNC int argfn_qs1616(const gfxd_value_t *v) -{ - if (v->i == 0) - return gfxd_puts("0"); - else if (config.emit_q_macro) - return gfxd_printf("qs1616(%.16g)", v->i / 65536.f); - else - { - if (v->i < 0) - return gfxd_printf("-0x%08" PRIX32, (uint32_t)-v->i); - else - return gfxd_printf("0x%08" PRIX32, (uint32_t)v->i); - } -} - -UCFUNC int argfn_opc(const gfxd_value_t *v) -{ - switch (v->i) - { - case G_SPNOOP: - return gfxd_puts("G_SPNOOP"); - case G_MTX: - return gfxd_puts("G_MTX"); - case G_MOVEMEM: - return gfxd_puts("G_MOVEMEM"); - case G_VTX: - return gfxd_puts("G_VTX"); - case G_DL: - return gfxd_puts("G_DL"); - case G_RDPHALF_2: - return gfxd_puts("G_RDPHALF_2"); - case G_RDPHALF_1: - return gfxd_puts("G_RDPHALF_1"); -#if defined(F3D_BETA) && (defined(F3D_GBI) || defined(F3DEX_GBI)) - case G_PERSPNORM: - return gfxd_puts("G_PERSPNORM"); -#endif - case G_LINE3D: - return gfxd_puts("G_LINE3D"); -#if defined(F3D_GBI) || defined(F3DEX_GBI) - case G_CLEARGEOMETRYMODE: - return gfxd_puts("G_CLEARGEOMETRYMODE"); - case G_SETGEOMETRYMODE: - return gfxd_puts("G_SETGEOMETRYMODE"); -#endif - case G_ENDDL: - return gfxd_puts("G_ENDDL"); - case G_SETOTHERMODE_L: - return gfxd_puts("G_SETOTHERMODE_L"); - case G_SETOTHERMODE_H: - return gfxd_puts("G_SETOTHERMODE_H"); - case G_TEXTURE: - return gfxd_puts("G_TEXTURE"); - case G_MOVEWORD: - return gfxd_puts("G_MOVEWORD"); - case G_POPMTX: - return gfxd_puts("G_POPMTX"); - case G_CULLDL: - return gfxd_puts("G_CULLDL"); - case G_TRI1: - return gfxd_puts("G_TRI1"); - case G_NOOP: - return gfxd_puts("G_NOOP"); -#if defined(F3DEX_GBI) || defined(F3DEX_GBI_2) - case G_LOAD_UCODE: - return gfxd_puts("G_LOAD_UCODE"); - case G_BRANCH_Z: - return gfxd_puts("G_BRANCH_Z"); - case G_TRI2: - return gfxd_puts("G_TRI2"); -# if !(defined(F3D_BETA) && defined(F3DEX_GBI)) - case G_MODIFYVTX: - return gfxd_puts("G_MODIFYVTX"); -# endif -#endif -#if defined(F3DEX_GBI_2) - case G_QUAD: - return gfxd_puts("G_QUAD"); - case G_SPECIAL_3: - return gfxd_puts("G_SPECIAL_3"); - case G_SPECIAL_2: - return gfxd_puts("G_SPECIAL_2"); - case G_SPECIAL_1: - return gfxd_puts("G_SPECIAL_1"); - case G_DMA_IO: - return gfxd_puts("G_DMA_IO"); - case G_GEOMETRYMODE: - return gfxd_puts("G_GEOMETRYMODE"); -#endif - case G_TEXRECT: - return gfxd_puts("G_TEXRECT"); - case G_TEXRECTFLIP: - return gfxd_puts("G_TEXRECTFLIP"); - case G_RDPLOADSYNC: - return gfxd_puts("G_RDPLOADSYNC"); - case G_RDPPIPESYNC: - return gfxd_puts("G_RDPPIPESYNC"); - case G_RDPTILESYNC: - return gfxd_puts("G_RDPTILESYNC"); - case G_RDPFULLSYNC: - return gfxd_puts("G_RDPFULLSYNC"); - case G_SETKEYGB: - return gfxd_puts("G_SETKEYGB"); - case G_SETKEYR: - return gfxd_puts("G_SETKEYR"); - case G_SETCONVERT: - return gfxd_puts("G_SETCONVERT"); - case G_SETSCISSOR: - return gfxd_puts("G_SETSCISSOR"); - case G_SETPRIMDEPTH: - return gfxd_puts("G_SETPRIMDEPTH"); - case G_RDPSETOTHERMODE: - return gfxd_puts("G_RDPSETOTHERMODE"); - case G_LOADTLUT: - return gfxd_puts("G_LOADTLUT"); - case G_SETTILESIZE: - return gfxd_puts("G_SETTILESIZE"); - case G_LOADBLOCK: - return gfxd_puts("G_LOADBLOCK"); - case G_LOADTILE: - return gfxd_puts("G_LOADTILE"); - case G_SETTILE: - return gfxd_puts("G_SETTILE"); - case G_FILLRECT: - return gfxd_puts("G_FILLRECT"); - case G_SETFILLCOLOR: - return gfxd_puts("G_SETFILLCOLOR"); - case G_SETFOGCOLOR: - return gfxd_puts("G_SETFOGCOLOR"); - case G_SETBLENDCOLOR: - return gfxd_puts("G_SETBLENDCOLOR"); - case G_SETPRIMCOLOR: - return gfxd_puts("G_SETPRIMCOLOR"); - case G_SETENVCOLOR: - return gfxd_puts("G_SETENVCOLOR"); - case G_SETCOMBINE: - return gfxd_puts("G_SETCOMBINE"); - case G_SETTIMG: - return gfxd_puts("G_SETTIMG"); - case G_SETZIMG: - return gfxd_puts("G_SETZIMG"); - case G_SETCIMG: - return gfxd_puts("G_SETCIMG"); - default: - return gfxd_printf("0x%02" PRIX32, (uint32_t)v->i); - } -} - -UCFUNC int argfn_fmt(const gfxd_value_t *v) -{ - switch (v->i) - { - case G_IM_FMT_RGBA: - return gfxd_puts("G_IM_FMT_RGBA"); - case G_IM_FMT_YUV: - return gfxd_puts("G_IM_FMT_YUV"); - case G_IM_FMT_CI: - return gfxd_puts("G_IM_FMT_CI"); - case G_IM_FMT_IA: - return gfxd_puts("G_IM_FMT_IA"); - case G_IM_FMT_I: - return gfxd_puts("G_IM_FMT_I"); - default: - return gfxd_printf("%" PRIi32, v->i); - } -} - -UCFUNC int argfn_siz(const gfxd_value_t *v) -{ - switch (v->i) - { - case G_IM_SIZ_4b: - return gfxd_puts("G_IM_SIZ_4b"); - case G_IM_SIZ_8b: - return gfxd_puts("G_IM_SIZ_8b"); - case G_IM_SIZ_16b: - return gfxd_puts("G_IM_SIZ_16b"); - case G_IM_SIZ_32b: - return gfxd_puts("G_IM_SIZ_32b"); - default: - return gfxd_printf("%" PRIi32, v->i); - } -} - -UCFUNC int argfn_cm(const gfxd_value_t *v) -{ - int n = 0; - if (v->u & G_TX_MIRROR) - n += gfxd_puts("G_TX_MIRROR"); - else - n += gfxd_puts("G_TX_NOMIRROR"); - if (v->u & G_TX_CLAMP) - n += gfxd_puts(" | G_TX_CLAMP"); - else - n += gfxd_puts(" | G_TX_WRAP"); - return n; -} - -UCFUNC int argfn_tm(const gfxd_value_t *v) -{ - if (v->i == 0) - return gfxd_puts("G_TX_NOMASK"); - else - return gfxd_printf("%" PRIi32, v->i); -} - -UCFUNC int argfn_ts(const gfxd_value_t *v) -{ - if (v->i == 0) - return gfxd_puts("G_TX_NOLOD"); - else - return gfxd_printf("%" PRIi32, v->i); -} - -UCFUNC int argfn_switch(const gfxd_value_t *v) -{ - switch (v->i) - { - case G_ON: - return gfxd_puts("G_ON"); - case G_OFF: - return gfxd_puts("G_OFF"); - default: - return gfxd_printf("%" PRIi32, v->i); - } -} - -UCFUNC int argfn_tile(const gfxd_value_t *v) -{ - if (v->i == G_TX_LOADTILE) - return gfxd_puts("G_TX_LOADTILE"); - else if (v->i == G_TX_RENDERTILE) - return gfxd_puts("G_TX_RENDERTILE"); - else - return gfxd_printf("%" PRIi32, v->i); -} - -UCFUNC int argfn_gm(const gfxd_value_t *v) -{ - int n = 0; - uint32_t arg = v->u; - if (arg & G_ZBUFFER) - n += gfxd_puts("G_ZBUFFER"); - if (arg & G_TEXTURE_ENABLE) - { - if (n > 0) - n += gfxd_puts(" | "); - n += gfxd_puts("G_TEXTURE_ENABLE"); - } - if (arg & G_SHADE) - { - if (n > 0) - n += gfxd_puts(" | "); - n += gfxd_puts("G_SHADE"); - } - if ((arg & G_CULL_BOTH) == G_CULL_BOTH) - { - if (n > 0) - n += gfxd_puts(" | "); - n += gfxd_puts("G_CULL_BOTH"); - } - else - { - if (arg & G_CULL_FRONT) - { - if (n > 0) - n += gfxd_puts(" | "); - n += gfxd_puts("G_CULL_FRONT"); - } - if (arg & G_CULL_BACK) - { - if (n > 0) - n += gfxd_puts(" | "); - n += gfxd_puts("G_CULL_BACK"); - } - } - if (arg & G_FOG) - { - if (n > 0) - n += gfxd_puts(" | "); - n += gfxd_puts("G_FOG"); - } - if (arg & G_LIGHTING) - { - if (n > 0) - n += gfxd_puts(" | "); - n += gfxd_puts("G_LIGHTING"); - } - if (arg & G_TEXTURE_GEN) - { - if (n > 0) - n += gfxd_puts(" | "); - n += gfxd_puts("G_TEXTURE_GEN"); - } - if (arg & G_TEXTURE_GEN_LINEAR) - { - if (n > 0) - n += gfxd_puts(" | "); - n += gfxd_puts("G_TEXTURE_GEN_LINEAR"); - } - if (arg & G_LOD) - { - if (n > 0) - n += gfxd_puts(" | "); - n += gfxd_puts("G_LOD"); - } - if (arg & G_SHADING_SMOOTH) - { - if (n > 0) - n += gfxd_puts(" | "); - n += gfxd_puts("G_SHADING_SMOOTH"); - } - if (arg & G_CLIPPING) - { - if (n > 0) - n += gfxd_puts(" | "); - n += gfxd_puts("G_CLIPPING"); - } - arg = arg & ~(G_ZBUFFER | G_TEXTURE_ENABLE | G_SHADE | G_CULL_BOTH | - G_FOG | G_LIGHTING | G_TEXTURE_GEN | - G_TEXTURE_GEN_LINEAR | G_LOD | G_SHADING_SMOOTH | - G_CLIPPING); - if (arg) - { - if (n > 0) - n += gfxd_puts(" | "); - n += gfxd_printf("0x%08" PRIX32, arg); - } - return n; -} - -UCFUNC int argfn_sftlo(const gfxd_value_t *v) -{ - switch (v->i) - { - case G_MDSFT_ALPHACOMPARE: - return gfxd_puts("G_MDSFT_ALPHACOMPARE"); - case G_MDSFT_ZSRCSEL: - return gfxd_puts("G_MDSFT_ZSRCSEL"); - case G_MDSFT_RENDERMODE: - return gfxd_puts("G_MDSFT_RENDERMODE"); - case G_MDSFT_BLENDER: - return gfxd_puts("G_MDSFT_BLENDER"); - default: - return gfxd_printf("%" PRIi32, v->i); - } -} - -UCFUNC int rm_mode_str(uint32_t arg) -{ - int n = 0; - if (arg & AA_EN) - n += gfxd_puts("AA_EN"); - if (arg & Z_CMP) - { - if (n > 0) - n += gfxd_puts(" | "); - n += gfxd_puts("Z_CMP"); - } - if (arg & Z_UPD) - { - if (n > 0) - n += gfxd_puts(" | "); - n += gfxd_puts("Z_UPD"); - } - if (arg & IM_RD) - { - if (n > 0) - n += gfxd_puts(" | "); - n += gfxd_puts("IM_RD"); - } - if (arg & CLR_ON_CVG) - { - if (n > 0) - n += gfxd_puts(" | "); - n += gfxd_puts("CLR_ON_CVG"); - } - if (n > 0) - n += gfxd_puts(" | "); - int cvg = arg & 0x00000300; - switch (cvg) - { - case CVG_DST_CLAMP: - n += gfxd_puts("CVG_DST_CLAMP"); - break; - case CVG_DST_WRAP: - n += gfxd_puts("CVG_DST_WRAP"); - break; - case CVG_DST_FULL: - n += gfxd_puts("CVG_DST_FULL"); - break; - case CVG_DST_SAVE: - n += gfxd_puts("CVG_DST_SAVE"); - break; - } - int zmode = arg & 0x00000C00; - switch (zmode) - { - case ZMODE_OPA: - n += gfxd_puts(" | ZMODE_OPA"); - break; - case ZMODE_INTER: - n += gfxd_puts(" | ZMODE_INTER"); - break; - case ZMODE_XLU: - n += gfxd_puts(" | ZMODE_XLU"); - break; - case ZMODE_DEC: - n += gfxd_puts(" | ZMODE_DEC"); - break; - } - if (arg & CVG_X_ALPHA) - n += gfxd_puts(" | CVG_X_ALPHA"); - if (arg & ALPHA_CVG_SEL) - n += gfxd_puts(" | ALPHA_CVG_SEL"); - if (arg & FORCE_BL) - n += gfxd_puts(" | FORCE_BL"); - return n; -} - -UCFUNC int rm_cbl_str(uint32_t arg, int c) -{ - int n = 0; - if (c == 2) - arg <<= 2; - int bp = (arg >> 30) & 0b11; - switch (bp) - { - case G_BL_CLR_IN: - n += gfxd_printf("GBL_c%i(G_BL_CLR_IN", c); - break; - case G_BL_CLR_MEM: - n += gfxd_printf("GBL_c%i(G_BL_CLR_MEM", c); - break; - case G_BL_CLR_BL: - n += gfxd_printf("GBL_c%i(G_BL_CLR_BL", c); - break; - case G_BL_CLR_FOG: - n += gfxd_printf("GBL_c%i(G_BL_CLR_FOG", c); - break; - } - int ba = (arg >> 26) & 0b11; - switch (ba) - { - case G_BL_A_IN: - n += gfxd_puts(", G_BL_A_IN"); - break; - case G_BL_A_FOG: - n += gfxd_puts(", G_BL_A_FOG"); - break; - case G_BL_A_SHADE: - n += gfxd_puts(", G_BL_A_SHADE"); - break; - case G_BL_0: - n += gfxd_puts(", G_BL_0"); - break; - } - int bm = (arg >> 22) & 0b11; - switch (bm) - { - case G_BL_CLR_IN: - n += gfxd_puts(", G_BL_CLR_IN"); - break; - case G_BL_CLR_MEM: - n += gfxd_puts(", G_BL_CLR_MEM"); - break; - case G_BL_CLR_BL: - n += gfxd_puts(", G_BL_CLR_BL"); - break; - case G_BL_CLR_FOG: - n += gfxd_puts(", G_BL_CLR_FOG"); - break; - } - int bb = (arg >> 18) & 0b11; - switch (bb) - { - case G_BL_1MA: - n += gfxd_puts(", G_BL_1MA)"); - break; - case G_BL_A_MEM: - n += gfxd_puts(", G_BL_A_MEM)"); - break; - case G_BL_1: - n += gfxd_puts(", G_BL_1)"); - break; - case G_BL_0: - n += gfxd_puts(", G_BL_0)"); - break; - } - return n; -} - -struct rm_preset -{ - uint32_t rm; - const char * name; -}; - -static const struct rm_preset rm_presets[] = -{ - {G_RM_OPA_SURF, "G_RM_OPA_SURF"}, - {G_RM_OPA_SURF2, "G_RM_OPA_SURF2"}, - {G_RM_AA_OPA_SURF, "G_RM_AA_OPA_SURF"}, - {G_RM_AA_OPA_SURF2, "G_RM_AA_OPA_SURF2"}, - {G_RM_RA_OPA_SURF, "G_RM_RA_OPA_SURF"}, - {G_RM_RA_OPA_SURF2, "G_RM_RA_OPA_SURF2"}, - {G_RM_ZB_OPA_SURF, "G_RM_ZB_OPA_SURF"}, - {G_RM_ZB_OPA_SURF2, "G_RM_ZB_OPA_SURF2"}, - {G_RM_AA_ZB_OPA_SURF, "G_RM_AA_ZB_OPA_SURF"}, - {G_RM_AA_ZB_OPA_SURF2, "G_RM_AA_ZB_OPA_SURF2"}, - {G_RM_RA_ZB_OPA_SURF, "G_RM_RA_ZB_OPA_SURF"}, - {G_RM_RA_ZB_OPA_SURF2, "G_RM_RA_ZB_OPA_SURF2"}, - {G_RM_XLU_SURF, "G_RM_XLU_SURF"}, - {G_RM_XLU_SURF2, "G_RM_XLU_SURF2"}, - {G_RM_AA_XLU_SURF, "G_RM_AA_XLU_SURF"}, - {G_RM_AA_XLU_SURF2, "G_RM_AA_XLU_SURF2"}, - {G_RM_ZB_XLU_SURF, "G_RM_ZB_XLU_SURF"}, - {G_RM_ZB_XLU_SURF2, "G_RM_ZB_XLU_SURF2"}, - {G_RM_AA_ZB_XLU_SURF, "G_RM_AA_ZB_XLU_SURF"}, - {G_RM_AA_ZB_XLU_SURF2, "G_RM_AA_ZB_XLU_SURF2"}, - {G_RM_ZB_OPA_DECAL, "G_RM_ZB_OPA_DECAL"}, - {G_RM_ZB_OPA_DECAL2, "G_RM_ZB_OPA_DECAL2"}, - {G_RM_AA_ZB_OPA_DECAL, "G_RM_AA_ZB_OPA_DECAL"}, - {G_RM_AA_ZB_OPA_DECAL2, "G_RM_AA_ZB_OPA_DECAL2"}, - {G_RM_RA_ZB_OPA_DECAL, "G_RM_RA_ZB_OPA_DECAL"}, - {G_RM_RA_ZB_OPA_DECAL2, "G_RM_RA_ZB_OPA_DECAL2"}, - {G_RM_ZB_XLU_DECAL, "G_RM_ZB_XLU_DECAL"}, - {G_RM_ZB_XLU_DECAL2, "G_RM_ZB_XLU_DECAL2"}, - {G_RM_AA_ZB_XLU_DECAL, "G_RM_AA_ZB_XLU_DECAL"}, - {G_RM_AA_ZB_XLU_DECAL2, "G_RM_AA_ZB_XLU_DECAL2"}, - {G_RM_AA_ZB_OPA_INTER, "G_RM_AA_ZB_OPA_INTER"}, - {G_RM_AA_ZB_OPA_INTER2, "G_RM_AA_ZB_OPA_INTER2"}, - {G_RM_RA_ZB_OPA_INTER, "G_RM_RA_ZB_OPA_INTER"}, - {G_RM_RA_ZB_OPA_INTER2, "G_RM_RA_ZB_OPA_INTER2"}, - {G_RM_AA_ZB_XLU_INTER, "G_RM_AA_ZB_XLU_INTER"}, - {G_RM_AA_ZB_XLU_INTER2, "G_RM_AA_ZB_XLU_INTER2"}, - {G_RM_AA_XLU_LINE, "G_RM_AA_XLU_LINE"}, - {G_RM_AA_XLU_LINE2, "G_RM_AA_XLU_LINE2"}, - {G_RM_AA_ZB_XLU_LINE, "G_RM_AA_ZB_XLU_LINE"}, - {G_RM_AA_ZB_XLU_LINE2, "G_RM_AA_ZB_XLU_LINE2"}, - {G_RM_AA_DEC_LINE, "G_RM_AA_DEC_LINE"}, - {G_RM_AA_DEC_LINE2, "G_RM_AA_DEC_LINE2"}, - {G_RM_AA_ZB_DEC_LINE, "G_RM_AA_ZB_DEC_LINE"}, - {G_RM_AA_ZB_DEC_LINE2, "G_RM_AA_ZB_DEC_LINE2"}, - {G_RM_TEX_EDGE, "G_RM_TEX_EDGE"}, - {G_RM_TEX_EDGE2, "G_RM_TEX_EDGE2"}, - {G_RM_AA_TEX_EDGE, "G_RM_AA_TEX_EDGE"}, - {G_RM_AA_TEX_EDGE2, "G_RM_AA_TEX_EDGE2"}, - {G_RM_AA_ZB_TEX_EDGE, "G_RM_AA_ZB_TEX_EDGE"}, - {G_RM_AA_ZB_TEX_EDGE2, "G_RM_AA_ZB_TEX_EDGE2"}, - {G_RM_AA_ZB_TEX_INTER, "G_RM_AA_ZB_TEX_INTER"}, - {G_RM_AA_ZB_TEX_INTER2, "G_RM_AA_ZB_TEX_INTER2"}, - {G_RM_AA_SUB_SURF, "G_RM_AA_SUB_SURF"}, - {G_RM_AA_SUB_SURF2, "G_RM_AA_SUB_SURF2"}, - {G_RM_AA_ZB_SUB_SURF, "G_RM_AA_ZB_SUB_SURF"}, - {G_RM_AA_ZB_SUB_SURF2, "G_RM_AA_ZB_SUB_SURF2"}, - {G_RM_PCL_SURF, "G_RM_PCL_SURF"}, - {G_RM_PCL_SURF2, "G_RM_PCL_SURF2"}, - {G_RM_AA_PCL_SURF, "G_RM_AA_PCL_SURF"}, - {G_RM_AA_PCL_SURF2, "G_RM_AA_PCL_SURF2"}, - {G_RM_ZB_PCL_SURF, "G_RM_ZB_PCL_SURF"}, - {G_RM_ZB_PCL_SURF2, "G_RM_ZB_PCL_SURF2"}, - {G_RM_AA_ZB_PCL_SURF, "G_RM_AA_ZB_PCL_SURF"}, - {G_RM_AA_ZB_PCL_SURF2, "G_RM_AA_ZB_PCL_SURF2"}, - {G_RM_AA_OPA_TERR, "G_RM_AA_OPA_TERR"}, - {G_RM_AA_OPA_TERR2, "G_RM_AA_OPA_TERR2"}, - {G_RM_AA_ZB_OPA_TERR, "G_RM_AA_ZB_OPA_TERR"}, - {G_RM_AA_ZB_OPA_TERR2, "G_RM_AA_ZB_OPA_TERR2"}, - {G_RM_AA_TEX_TERR, "G_RM_AA_TEX_TERR"}, - {G_RM_AA_TEX_TERR2, "G_RM_AA_TEX_TERR2"}, - {G_RM_AA_ZB_TEX_TERR, "G_RM_AA_ZB_TEX_TERR"}, - {G_RM_AA_ZB_TEX_TERR2, "G_RM_AA_ZB_TEX_TERR2"}, - {G_RM_AA_SUB_TERR, "G_RM_AA_SUB_TERR"}, - {G_RM_AA_SUB_TERR2, "G_RM_AA_SUB_TERR2"}, - {G_RM_AA_ZB_SUB_TERR, "G_RM_AA_ZB_SUB_TERR"}, - {G_RM_AA_ZB_SUB_TERR2, "G_RM_AA_ZB_SUB_TERR2"}, - {G_RM_CLD_SURF, "G_RM_CLD_SURF"}, - {G_RM_CLD_SURF2, "G_RM_CLD_SURF2"}, - {G_RM_ZB_CLD_SURF, "G_RM_ZB_CLD_SURF"}, - {G_RM_ZB_CLD_SURF2, "G_RM_ZB_CLD_SURF2"}, - {G_RM_ZB_OVL_SURF, "G_RM_ZB_OVL_SURF"}, - {G_RM_ZB_OVL_SURF2, "G_RM_ZB_OVL_SURF2"}, - {G_RM_ADD, "G_RM_ADD"}, - {G_RM_ADD2, "G_RM_ADD2"}, - {G_RM_VISCVG, "G_RM_VISCVG"}, - {G_RM_VISCVG2, "G_RM_VISCVG2"}, - {G_RM_OPA_CI, "G_RM_OPA_CI"}, - {G_RM_OPA_CI2, "G_RM_OPA_CI2"}, - {G_RM_RA_SPRITE, "G_RM_RA_SPRITE"}, - {G_RM_RA_SPRITE2, "G_RM_RA_SPRITE2"}, -}; - -static const struct rm_preset bl1_presets[] = -{ - {G_RM_FOG_SHADE_A, "G_RM_FOG_SHADE_A"}, - {G_RM_FOG_PRIM_A, "G_RM_FOG_PRIM_A"}, - {G_RM_PASS, "G_RM_PASS"}, - {G_RM_NOOP, "G_RM_NOOP"}, -}; - -static const struct rm_preset bl2_presets[] = -{ - {G_RM_NOOP2, "G_RM_NOOP2"}, -}; - -UCFUNC int othermodelo_str(uint32_t arg, uint32_t which) -{ - int n = 0; - uint32_t rm_c1_mask = MDMASK_RM_C1; - uint32_t rm_c2_mask = MDMASK_RM_C2; - uint32_t rm_mode_lo = MDMASK_RM_LO; - uint32_t rm_mask = rm_c1_mask | rm_c2_mask | rm_mode_lo; - const struct rm_preset *pre_c1 = NULL; - const struct rm_preset *pre_c2 = NULL; - int n_rm_presets = sizeof(rm_presets) / sizeof(*rm_presets); - for (int i = 0; i < n_rm_presets; i++) - { - const struct rm_preset *pre = &rm_presets[i]; - uint32_t pre_extra = pre->rm & ~rm_mask; - uint32_t rm_c1 = arg & (rm_c1_mask | rm_mode_lo | pre_extra); - if (!pre_c1 && rm_c1 == pre->rm) - pre_c1 = pre; - uint32_t rm_c2 = arg & (rm_c2_mask | rm_mode_lo | pre_extra); - if (!pre_c2 && rm_c2 == pre->rm) - pre_c2 = pre; - } - if (!pre_c1 || !pre_c2 || pre_c1 + 1 != pre_c2) - { - int n_bl1_presets = sizeof(bl1_presets) / sizeof(*bl1_presets); - for (int i = 0; i < n_bl1_presets; i++) - { - const struct rm_preset *pre = &bl1_presets[i]; - uint32_t pre_extra = pre->rm & ~rm_mask; - uint32_t rm_c1 = arg & (rm_c1_mask | pre_extra); - if (rm_c1 == pre->rm) - { - pre_c1 = pre; - break; - } - } - int n_bl2_presets = sizeof(bl2_presets) / sizeof(*bl2_presets); - for (int i = 0; i < n_bl2_presets; i++) - { - const struct rm_preset *pre = &bl2_presets[i]; - uint32_t pre_extra = pre->rm & ~rm_mask; - uint32_t rm_c2 = arg & (rm_c2_mask | pre_extra); - if (rm_c2 == pre->rm) - { - pre_c2 = pre; - break; - } - } - } - uint32_t pre_rm = 0; - if (pre_c1) - pre_rm |= pre_c1->rm; - if (pre_c2) - pre_rm |= pre_c2->rm; - uint32_t ac_mask = MDMASK(ALPHACOMPARE); - if (((arg & ~pre_rm) | which) & ac_mask) - { - uint32_t ac = arg & ac_mask; - switch (ac) - { - case G_AC_NONE: - n += gfxd_puts("G_AC_NONE"); - break; - case G_AC_THRESHOLD: - n += gfxd_puts("G_AC_THRESHOLD"); - break; - case G_AC_DITHER: - n += gfxd_puts("G_AC_DITHER"); - break; - default: - n += gfxd_printf("0x%08" PRIX32, ac); - break; - } - } - uint32_t zs_mask = MDMASK(ZSRCSEL); - if (((arg & ~pre_rm) | which) & zs_mask) - { - if (n > 0) - n += gfxd_puts(" | "); - uint32_t zs = arg & zs_mask; - switch (zs) - { - case G_ZS_PIXEL: - n += gfxd_puts("G_ZS_PIXEL"); - break; - case G_ZS_PRIM: - n += gfxd_puts("G_ZS_PRIM"); - break; - default: - n += gfxd_printf("0x%08" PRIX32, zs); - break; - } - } - uint32_t rm = arg & (rm_mask | pre_rm); - if (((arg & ~pre_rm) | which) & rm_mode_lo) - { - if (n > 0) - n += gfxd_puts(" | "); - n += rm_mode_str(rm); - } - int c = 0; - if (which & rm_c1_mask) - c |= 1; - if (which & rm_c2_mask) - c |= 2; - if (c & 1 || (c == 0 && arg & rm_c1_mask)) - { - if (n > 0) - n += gfxd_puts(" | "); - if (pre_c1) - n += gfxd_printf("%s", pre_c1->name); - else - n += rm_cbl_str(rm, 1); - } - if (c & 2 || (c == 0 && arg & rm_c2_mask)) - { - if (n > 0) - n += gfxd_puts(" | "); - if (pre_c2) - n += gfxd_printf("%s", pre_c2->name); - else - n += rm_cbl_str(rm, 2); - } - uint32_t unk_mask = ~(rm_mask | ac_mask | zs_mask); - if (arg & unk_mask) - { - if (n > 0) - n += gfxd_puts(" | "); - uint32_t unk = arg & unk_mask; - n += gfxd_printf("0x%08" PRIX32, unk); - } - return n; -} - -UCFUNC int argfn_ac(const gfxd_value_t *v) -{ - return othermodelo_str(v->u, MDMASK(ALPHACOMPARE)); -} - -UCFUNC int argfn_zs(const gfxd_value_t *v) -{ - return othermodelo_str(v->u, MDMASK(ZSRCSEL)); -} - -UCFUNC int argfn_rm1(const gfxd_value_t *v) -{ - return othermodelo_str(v->u, MDMASK_RM_C1); -} - -UCFUNC int argfn_rm2(const gfxd_value_t *v) -{ - return othermodelo_str(v->u, MDMASK_RM_C2); -} - -UCFUNC int argfn_othermodelo(const gfxd_value_t *v) -{ - uint32_t mask = MDMASK(ALPHACOMPARE) | MDMASK(ZSRCSEL) | MDMASK_RM_C1 | - MDMASK_RM_C2; - return othermodelo_str(v->u, mask); -} - -UCFUNC int argfn_sfthi(const gfxd_value_t *v) -{ - switch (v->i) - { - case G_MDSFT_ALPHADITHER: - return gfxd_puts("G_MDSFT_ALPHADITHER"); - case G_MDSFT_RGBDITHER: - return gfxd_puts("G_MDSFT_RGBDITHER"); - case G_MDSFT_COMBKEY: - return gfxd_puts("G_MDSFT_COMBKEY"); - case G_MDSFT_TEXTCONV: - return gfxd_puts("G_MDSFT_TEXTCONV"); - case G_MDSFT_TEXTFILT: - return gfxd_puts("G_MDSFT_TEXTFILT"); - case G_MDSFT_TEXTLUT: - return gfxd_puts("G_MDSFT_TEXTLUT"); - case G_MDSFT_TEXTLOD: - return gfxd_puts("G_MDSFT_TEXTLOD"); - case G_MDSFT_TEXTDETAIL: - return gfxd_puts("G_MDSFT_TEXTDETAIL"); - case G_MDSFT_TEXTPERSP: - return gfxd_puts("G_MDSFT_TEXTPERSP"); - case G_MDSFT_CYCLETYPE: - return gfxd_puts("G_MDSFT_CYCLETYPE"); - case G_MDSFT_PIPELINE: - return gfxd_puts("G_MDSFT_PIPELINE"); - default: - return gfxd_printf("%" PRIi32, v->i); - } -} - -UCFUNC int othermodehi_str(uint32_t arg, uint32_t which) -{ - int n = 0; - uint32_t ad_mask = MDMASK(ALPHADITHER); - if ((arg | which) & ad_mask) - { - uint32_t ad = arg & ad_mask; - switch (ad) - { - case G_AD_PATTERN: - n += gfxd_puts("G_AD_PATTERN"); - break; - case G_AD_NOTPATTERN: - n += gfxd_puts("G_AD_NOTPATTERN"); - break; - case G_AD_NOISE: - n += gfxd_puts("G_AD_NOISE"); - break; - case G_AD_DISABLE: - n += gfxd_puts("G_AD_DISABLE"); - break; - default: - n += gfxd_printf("0x%08" PRIX32, ad); - break; - } - } - uint32_t cd_mask = MDMASK(RGBDITHER); - if ((arg | which) & cd_mask) - { - if (n > 0) - n += gfxd_puts(" | "); - uint32_t cd = arg & cd_mask; - switch (cd) - { - case G_CD_MAGICSQ: - n += gfxd_puts("G_CD_MAGICSQ"); - break; - case G_CD_BAYER: - n += gfxd_puts("G_CD_BAYER"); - break; - case G_CD_NOISE: - n += gfxd_puts("G_CD_NOISE"); - break; - case G_CD_DISABLE: - n += gfxd_puts("G_CD_DISABLE"); - break; - default: - n += gfxd_printf("0x%08" PRIX32, cd); - break; - } - } - uint32_t ck_mask = MDMASK(COMBKEY); - if ((arg | which) & ck_mask) - { - if (n > 0) - n += gfxd_puts(" | "); - uint32_t ck = arg & ck_mask; - switch (ck) - { - case G_CK_NONE: - n += gfxd_puts("G_CK_NONE"); - break; - case G_CK_KEY: - n += gfxd_puts("G_CK_KEY"); - break; - default: - n += gfxd_printf("0x%08" PRIX32, ck); - break; - } - } - uint32_t tc_mask = MDMASK(TEXTCONV); - if ((arg | which) & tc_mask) - { - if (n > 0) - n += gfxd_puts(" | "); - uint32_t tc = arg & tc_mask; - switch (tc) - { - case G_TC_CONV: - n += gfxd_puts("G_TC_CONV"); - break; - case G_TC_FILTCONV: - n += gfxd_puts("G_TC_FILTCONV"); - break; - case G_TC_FILT: - n += gfxd_puts("G_TC_FILT"); - break; - default: - n += gfxd_printf("0x%08" PRIX32, tc); - break; - } - } - uint32_t tf_mask = MDMASK(TEXTFILT); - if ((arg | which) & tf_mask) - { - if (n > 0) - n += gfxd_puts(" | "); - uint32_t tf = arg & tf_mask; - switch (tf) - { - case G_TF_POINT: - n += gfxd_puts("G_TF_POINT"); - break; - case G_TF_BILERP: - n += gfxd_puts("G_TF_BILERP"); - break; - case G_TF_AVERAGE: - n += gfxd_puts("G_TF_AVERAGE"); - break; - default: - n += gfxd_printf("0x%08" PRIX32, tf); - break; - } - } - uint32_t tt_mask = MDMASK(TEXTLUT); - if ((arg | which) & tt_mask) - { - if (n > 0) - n += gfxd_puts(" | "); - uint32_t tt = arg & tt_mask; - switch (tt) - { - case G_TT_NONE: - n += gfxd_puts("G_TT_NONE"); - break; - case G_TT_RGBA16: - n += gfxd_puts("G_TT_RGBA16"); - break; - case G_TT_IA16: - n += gfxd_puts("G_TT_IA16"); - break; - default: - n += gfxd_printf("0x%08" PRIX32, tt); - break; - } - } - uint32_t tl_mask = MDMASK(TEXTLOD); - if ((arg | which) & tl_mask) - { - if (n > 0) - n += gfxd_puts(" | "); - uint32_t tl = arg & tl_mask; - switch (tl) - { - case G_TL_TILE: - n += gfxd_puts("G_TL_TILE"); - break; - case G_TL_LOD: - n += gfxd_puts("G_TL_LOD"); - break; - default: - n += gfxd_printf("0x%08" PRIX32, tl); - break; - } - } - uint32_t td_mask = MDMASK(TEXTDETAIL); - if ((arg | which) & td_mask) - { - if (n > 0) - n += gfxd_puts(" | "); - uint32_t td = arg & td_mask; - switch (td) - { - case G_TD_CLAMP: - n += gfxd_puts("G_TD_CLAMP"); - break; - case G_TD_SHARPEN: - n += gfxd_puts("G_TD_SHARPEN"); - break; - case G_TD_DETAIL: - n += gfxd_puts("G_TD_DETAIL"); - break; - default: - n += gfxd_printf("0x%08" PRIX32, td); - break; - } - } - uint32_t tp_mask = MDMASK(TEXTPERSP); - if ((arg | which) & tp_mask) - { - if (n > 0) - n += gfxd_puts(" | "); - uint32_t tp = arg & tp_mask; - switch (tp) - { - case G_TP_NONE: - n += gfxd_puts("G_TP_NONE"); - break; - case G_TP_PERSP: - n += gfxd_puts("G_TP_PERSP"); - break; - default: - n += gfxd_printf("0x%08" PRIX32, tp); - break; - } - } - uint32_t cyc_mask = MDMASK(CYCLETYPE); - if ((arg | which) & cyc_mask) - { - if (n > 0) - n += gfxd_puts(" | "); - uint32_t cyc = arg & cyc_mask; - switch (cyc) - { - case G_CYC_1CYCLE: - n += gfxd_puts("G_CYC_1CYCLE"); - break; - case G_CYC_2CYCLE: - n += gfxd_puts("G_CYC_2CYCLE"); - break; - case G_CYC_COPY: - n += gfxd_puts("G_CYC_COPY"); - break; - case G_CYC_FILL: - n += gfxd_puts("G_CYC_FILL"); - break; - default: - n += gfxd_printf("0x%08" PRIX32, cyc); - break; - } - } - uint32_t pm_mask = MDMASK(PIPELINE); - if ((arg | which) & pm_mask) - { - if (n > 0) - n += gfxd_puts(" | "); - uint32_t pm = arg & pm_mask; - switch (pm) - { - case G_PM_NPRIMITIVE: - n += gfxd_puts("G_PM_NPRIMITIVE"); - break; - case G_PM_1PRIMITIVE: - n += gfxd_puts("G_PM_1PRIMITIVE"); - break; - default: - n += gfxd_printf("0x%08" PRIX32, pm); - break; - } - } - uint32_t unk_mask = ~(ad_mask | cd_mask | ck_mask | tc_mask | tf_mask | - tt_mask | tl_mask | td_mask | tp_mask | - cyc_mask | pm_mask); - if (arg & unk_mask) - { - if (n > 0) - n += gfxd_puts(" | "); - uint32_t unk = arg & unk_mask; - n += gfxd_printf("0x%08" PRIX32, unk); - } - return n; -} - -UCFUNC int argfn_ad(const gfxd_value_t *v) -{ - return othermodehi_str(v->u, MDMASK(ALPHADITHER)); -} - -UCFUNC int argfn_cd(const gfxd_value_t *v) -{ - return othermodehi_str(v->u, MDMASK(RGBDITHER)); -} - -UCFUNC int argfn_ck(const gfxd_value_t *v) -{ - return othermodehi_str(v->u, MDMASK(COMBKEY)); -} - -UCFUNC int argfn_tc(const gfxd_value_t *v) -{ - return othermodehi_str(v->u, MDMASK(TEXTCONV)); -} - -UCFUNC int argfn_tf(const gfxd_value_t *v) -{ - return othermodehi_str(v->u, MDMASK(TEXTFILT)); -} - -UCFUNC int argfn_tt(const gfxd_value_t *v) -{ - return othermodehi_str(v->u, MDMASK(TEXTLUT)); -} - -UCFUNC int argfn_tl(const gfxd_value_t *v) -{ - return othermodehi_str(v->u, MDMASK(TEXTLOD)); -} - -UCFUNC int argfn_td(const gfxd_value_t *v) -{ - return othermodehi_str(v->u, MDMASK(TEXTDETAIL)); -} - -UCFUNC int argfn_tp(const gfxd_value_t *v) -{ - return othermodehi_str(v->u, MDMASK(TEXTPERSP)); -} - -UCFUNC int argfn_cyc(const gfxd_value_t *v) -{ - return othermodehi_str(v->u, MDMASK(CYCLETYPE)); -} - -UCFUNC int argfn_pm(const gfxd_value_t *v) -{ - return othermodehi_str(v->u, MDMASK(PIPELINE)); -} - -UCFUNC int argfn_othermodehi(const gfxd_value_t *v) -{ - uint32_t mask = MDMASK(ALPHADITHER) | - MDMASK(RGBDITHER) | - MDMASK(COMBKEY) | - MDMASK(TEXTCONV) | - MDMASK(TEXTFILT) | - MDMASK(TEXTLUT) | - MDMASK(TEXTLOD) | - MDMASK(TEXTDETAIL) | - MDMASK(TEXTPERSP) | - MDMASK(CYCLETYPE) | - MDMASK(PIPELINE); - return othermodehi_str(v->u, mask); -} - -UCFUNC int argfn_cv(const gfxd_value_t *v) -{ - switch (v->i) - { - case G_CV_K0: - return gfxd_puts("G_CV_K0"); - case G_CV_K1: - return gfxd_puts("G_CV_K1"); - case G_CV_K2: - return gfxd_puts("G_CV_K2"); - case G_CV_K3: - return gfxd_puts("G_CV_K3"); - case G_CV_K4: - return gfxd_puts("G_CV_K4"); - case G_CV_K5: - return gfxd_puts("G_CV_K5"); - default: - return gfxd_printf("%" PRIi32, v->i); - } -} - -UCFUNC int argfn_ccmuxa(const gfxd_value_t *v) -{ - switch (v->i) - { - case G_CCMUX_COMBINED: - return gfxd_puts("COMBINED"); - case G_CCMUX_TEXEL0: - return gfxd_puts("TEXEL0"); - case G_CCMUX_TEXEL1: - return gfxd_puts("TEXEL1"); - case G_CCMUX_PRIMITIVE: - return gfxd_puts("PRIMITIVE"); - case G_CCMUX_SHADE: - return gfxd_puts("SHADE"); - case G_CCMUX_ENVIRONMENT: - return gfxd_puts("ENVIRONMENT"); - case G_CCMUX_1: - return gfxd_puts("1"); - case G_CCMUX_NOISE: - return gfxd_puts("NOISE"); - default: - return gfxd_puts("0"); - } -} - -UCFUNC int argfn_ccmuxb(const gfxd_value_t *v) -{ - switch (v->i) - { - case G_CCMUX_COMBINED: - return gfxd_puts("COMBINED"); - case G_CCMUX_TEXEL0: - return gfxd_puts("TEXEL0"); - case G_CCMUX_TEXEL1: - return gfxd_puts("TEXEL1"); - case G_CCMUX_PRIMITIVE: - return gfxd_puts("PRIMITIVE"); - case G_CCMUX_SHADE: - return gfxd_puts("SHADE"); - case G_CCMUX_ENVIRONMENT: - return gfxd_puts("ENVIRONMENT"); - case G_CCMUX_CENTER: - return gfxd_puts("CENTER"); - case G_CCMUX_K4: - return gfxd_puts("K4"); - default: - return gfxd_puts("0"); - } -} - -UCFUNC int argfn_ccmuxc(const gfxd_value_t *v) -{ - switch (v->i) - { - case G_CCMUX_COMBINED: - return gfxd_puts("COMBINED"); - case G_CCMUX_TEXEL0: - return gfxd_puts("TEXEL0"); - case G_CCMUX_TEXEL1: - return gfxd_puts("TEXEL1"); - case G_CCMUX_PRIMITIVE: - return gfxd_puts("PRIMITIVE"); - case G_CCMUX_SHADE: - return gfxd_puts("SHADE"); - case G_CCMUX_ENVIRONMENT: - return gfxd_puts("ENVIRONMENT"); - case G_CCMUX_SCALE: - return gfxd_puts("SCALE"); - case G_CCMUX_COMBINED_ALPHA: - return gfxd_puts("COMBINED_ALPHA"); - case G_CCMUX_TEXEL0_ALPHA: - return gfxd_puts("TEXEL0_ALPHA"); - case G_CCMUX_TEXEL1_ALPHA: - return gfxd_puts("TEXEL1_ALPHA"); - case G_CCMUX_PRIMITIVE_ALPHA: - return gfxd_puts("PRIMITIVE_ALPHA"); - case G_CCMUX_SHADE_ALPHA: - return gfxd_puts("SHADE_ALPHA"); - case G_CCMUX_ENV_ALPHA: - return gfxd_puts("ENV_ALPHA"); - case G_CCMUX_LOD_FRACTION: - return gfxd_puts("LOD_FRACTION"); - case G_CCMUX_PRIM_LOD_FRAC: - return gfxd_puts("PRIM_LOD_FRAC"); - case G_CCMUX_K5: - return gfxd_puts("K5"); - default: - return gfxd_puts("0"); - } -} - -UCFUNC int argfn_ccmuxd(const gfxd_value_t *v) -{ - switch (v->i) - { - case G_CCMUX_COMBINED: - return gfxd_puts("COMBINED"); - case G_CCMUX_TEXEL0: - return gfxd_puts("TEXEL0"); - case G_CCMUX_TEXEL1: - return gfxd_puts("TEXEL1"); - case G_CCMUX_PRIMITIVE: - return gfxd_puts("PRIMITIVE"); - case G_CCMUX_SHADE: - return gfxd_puts("SHADE"); - case G_CCMUX_ENVIRONMENT: - return gfxd_puts("ENVIRONMENT"); - case G_CCMUX_1: - return gfxd_puts("1"); - default: - return gfxd_puts("0"); - } -} - -UCFUNC int argfn_acmuxabd(const gfxd_value_t *v) -{ - switch (v->i) - { - case G_ACMUX_COMBINED: - return gfxd_puts("COMBINED"); - case G_ACMUX_TEXEL0: - return gfxd_puts("TEXEL0"); - case G_ACMUX_TEXEL1: - return gfxd_puts("TEXEL1"); - case G_ACMUX_PRIMITIVE: - return gfxd_puts("PRIMITIVE"); - case G_ACMUX_SHADE: - return gfxd_puts("SHADE"); - case G_ACMUX_ENVIRONMENT: - return gfxd_puts("ENVIRONMENT"); - case G_ACMUX_1: - return gfxd_puts("1"); - default: - return gfxd_puts("0"); - } -} - -UCFUNC int argfn_acmuxc(const gfxd_value_t *v) -{ - switch (v->i) - { - case G_ACMUX_LOD_FRACTION: - return gfxd_puts("LOD_FRACTION"); - case G_ACMUX_TEXEL0: - return gfxd_puts("TEXEL0"); - case G_ACMUX_TEXEL1: - return gfxd_puts("TEXEL1"); - case G_ACMUX_PRIMITIVE: - return gfxd_puts("PRIMITIVE"); - case G_ACMUX_SHADE: - return gfxd_puts("SHADE"); - case G_ACMUX_ENVIRONMENT: - return gfxd_puts("ENVIRONMENT"); - case G_ACMUX_PRIM_LOD_FRAC: - return gfxd_puts("PRIM_LOD_FRAC"); - default: - return gfxd_puts("0"); - } -} - -struct cc_mode -{ - int a; - int b; - int c; - int d; - int Aa; - int Ab; - int Ac; - int Ad; -}; - -struct cc_preset -{ - struct cc_mode mode; - const char * name; -}; - -#define CC_(a,b,c,d,Aa,Ab,Ac,Ad) \ - { \ - G_CCMUX_##a, G_CCMUX_##b, \ - G_CCMUX_##c, G_CCMUX_##d, \ - G_ACMUX_##Aa, G_ACMUX_##Ab, \ - G_ACMUX_##Ac, G_ACMUX_##Ad \ - } -#define CC(m) CC_(m) -static const struct cc_preset cc_presets[] = -{ - {CC(G_CC_MODULATEI), "G_CC_MODULATEI"}, - {CC(G_CC_MODULATEIA), "G_CC_MODULATEIA"}, - {CC(G_CC_MODULATEIDECALA), "G_CC_MODULATEIDECALA"}, - {CC(G_CC_MODULATERGB), "G_CC_MODULATERGB"}, - {CC(G_CC_MODULATERGBA), "G_CC_MODULATERGBA"}, - {CC(G_CC_MODULATERGBDECALA), "G_CC_MODULATERGBDECALA"}, - {CC(G_CC_MODULATEI_PRIM), "G_CC_MODULATEI_PRIM"}, - {CC(G_CC_MODULATEIA_PRIM), "G_CC_MODULATEIA_PRIM"}, - {CC(G_CC_MODULATEIDECALA_PRIM), "G_CC_MODULATEIDECALA_PRIM"}, - {CC(G_CC_MODULATERGB_PRIM), "G_CC_MODULATERGB_PRIM"}, - {CC(G_CC_MODULATERGBA_PRIM), "G_CC_MODULATERGBA_PRIM"}, - {CC(G_CC_MODULATERGBDECALA_PRIM), "G_CC_MODULATERGBDECALA_PRIM"}, - {CC(G_CC_DECALRGB), "G_CC_DECALRGB"}, - {CC(G_CC_DECALRGBA), "G_CC_DECALRGBA"}, - {CC(G_CC_BLENDI), "G_CC_BLENDI"}, - {CC(G_CC_BLENDIA), "G_CC_BLENDIA"}, - {CC(G_CC_BLENDIDECALA), "G_CC_BLENDIDECALA"}, - {CC(G_CC_BLENDRGBA), "G_CC_BLENDRGBA"}, - {CC(G_CC_BLENDRGBDECALA), "G_CC_BLENDRGBDECALA"}, - {CC(G_CC_REFLECTRGB), "G_CC_REFLECTRGB"}, - {CC(G_CC_REFLECTRGBDECALA), "G_CC_REFLECTRGBDECALA"}, - {CC(G_CC_HILITERGB), "G_CC_HILITERGB"}, - {CC(G_CC_HILITERGBA), "G_CC_HILITERGBA"}, - {CC(G_CC_HILITERGBDECALA), "G_CC_HILITERGBDECALA"}, - {CC(G_CC_1CYUV2RGB), "G_CC_1CYUV2RGB"}, - {CC(G_CC_PRIMITIVE), "G_CC_PRIMITIVE"}, - {CC(G_CC_SHADE), "G_CC_SHADE"}, - {CC(G_CC_ADDRGB), "G_CC_ADDRGB"}, - {CC(G_CC_ADDRGBDECALA), "G_CC_ADDRGBDECALA"}, - {CC(G_CC_SHADEDECALA), "G_CC_SHADEDECALA"}, - {CC(G_CC_BLENDPE), "G_CC_BLENDPE"}, - {CC(G_CC_BLENDPEDECALA), "G_CC_BLENDPEDECALA"}, - {CC(G_CC_TRILERP), "G_CC_TRILERP"}, - {CC(G_CC_TEMPLERP), "G_CC_TEMPLERP"}, - {CC(G_CC_INTERFERENCE), "G_CC_INTERFERENCE"}, - {CC(_G_CC_BLENDPE), "_G_CC_BLENDPE"}, - {CC(_G_CC_BLENDPEDECALA), "_G_CC_BLENDPEDECALA"}, - {CC(_G_CC_SPARSEST), "_G_CC_SPARSEST"}, - {CC(_G_CC_TWOCOLORTEX), "_G_CC_TWOCOLORTEX"}, - {CC(G_CC_MODULATEI2), "G_CC_MODULATEI2"}, - {CC(G_CC_MODULATEIA2), "G_CC_MODULATEIA2"}, - {CC(G_CC_MODULATERGB2), "G_CC_MODULATERGB2"}, - {CC(G_CC_MODULATERGBA2), "G_CC_MODULATERGBA2"}, - {CC(G_CC_MODULATEI_PRIM2), "G_CC_MODULATEI_PRIM2"}, - {CC(G_CC_MODULATEIA_PRIM2), "G_CC_MODULATEIA_PRIM2"}, - {CC(G_CC_MODULATERGB_PRIM2), "G_CC_MODULATERGB_PRIM2"}, - {CC(G_CC_MODULATERGBA_PRIM2), "G_CC_MODULATERGBA_PRIM2"}, - {CC(G_CC_DECALRGB2), "G_CC_DECALRGB2"}, - {CC(G_CC_BLENDI2), "G_CC_BLENDI2"}, - {CC(G_CC_BLENDIA2), "G_CC_BLENDIA2"}, - {CC(G_CC_HILITERGB2), "G_CC_HILITERGB2"}, - {CC(G_CC_HILITERGBA2), "G_CC_HILITERGBA2"}, - {CC(G_CC_HILITERGBDECALA2), "G_CC_HILITERGBDECALA2"}, - {CC(G_CC_HILITERGBPASSA2), "G_CC_HILITERGBPASSA2"}, - {CC(G_CC_CHROMA_KEY2), "G_CC_CHROMA_KEY2"}, - {CC(G_CC_YUV2RGB), "G_CC_YUV2RGB"}, - {CC(G_CC_PASS2), "G_CC_PASS2"}, -}; -#undef CC_ -#undef CC - -UCFUNC int argfn_ccpre(const gfxd_value_t *v) -{ - return gfxd_printf("%s", cc_presets[v->i].name); -} - -UCFUNC int argfn_sc(const gfxd_value_t *v) -{ - switch (v->i) - { - case G_SC_NON_INTERLACE: - return gfxd_puts("G_SC_NON_INTERLACE"); - case G_SC_EVEN_INTERLACE: - return gfxd_puts("G_SC_EVEN_INTERLACE"); - case G_SC_ODD_INTERLACE: - return gfxd_puts("G_SC_ODD_INTERLACE"); - default: - return gfxd_printf("%" PRIi32, v->i); - } -} - -#if defined(F3DEX_GBI) || defined(F3DEX_GBI_2) -UCFUNC int argfn_bz(const gfxd_value_t *v) -{ - switch (v->i) - { - case G_BZ_PERSP: - return gfxd_puts("G_BZ_PERSP"); - default: - return gfxd_puts("G_BZ_ORTHO"); - } -} -#endif - -UCFUNC int argfn_dlf(const gfxd_value_t *v) -{ - switch (v->i) - { - case G_DL_PUSH: - return gfxd_puts("G_DL_PUSH"); - case G_DL_NOPUSH: - return gfxd_puts("G_DL_NOPUSH"); - default: - return gfxd_printf("%" PRIi32, v->i);; - } -} - -UCFUNC int argfn_mp(const gfxd_value_t *v) -{ - int n = 0; - if (v->u & G_MTX_PUSH) - n += gfxd_puts("G_MTX_PUSH"); - else - n += gfxd_puts("G_MTX_NOPUSH"); - if (v->u & G_MTX_LOAD) - n += gfxd_puts(" | G_MTX_LOAD"); - else - n += gfxd_puts(" | G_MTX_MUL"); - if (v->u & G_MTX_PROJECTION) - n += gfxd_puts(" | G_MTX_PROJECTION"); - else - n += gfxd_puts(" | G_MTX_MODELVIEW"); - for (int i = 3; i < 8; i++) - if (v->u & (1 << i)) - n += gfxd_printf(" | 0x%02x", 1 << i); - return n; -} - -UCFUNC int argfn_ms(const gfxd_value_t *v) -{ - switch (v->i) - { - case G_MTX_MODELVIEW: - return gfxd_puts("G_MTX_MODELVIEW"); - case G_MTX_PROJECTION: - return gfxd_puts("G_MTX_PROJECTION"); - default: - return gfxd_printf("%" PRIi32, v->i); - } -} - -UCFUNC int argfn_mw(const gfxd_value_t *v) -{ - switch (v->i) - { - case G_MW_MATRIX: - return gfxd_puts("G_MW_MATRIX"); - case G_MW_NUMLIGHT: - return gfxd_puts("G_MW_NUMLIGHT"); - case G_MW_CLIP: - return gfxd_puts("G_MW_CLIP"); - case G_MW_SEGMENT: - return gfxd_puts("G_MW_SEGMENT"); - case G_MW_FOG: - return gfxd_puts("G_MW_FOG"); - case G_MW_LIGHTCOL: - return gfxd_puts("G_MW_LIGHTCOL"); - case G_MW_PERSPNORM: - return gfxd_puts("G_MW_PERSPNORM"); -#if defined(F3D_GBI) || defined(F3DEX_GBI) - case G_MW_POINTS: - return gfxd_puts("G_MW_POINTS"); -#endif -#if defined(F3DEX_GBI_2) - case G_MW_FORCEMTX: - return gfxd_puts("G_MW_FORCEMTX"); -#endif - default: - return gfxd_printf("%" PRIi32, v->i); - } -} - -UCFUNC int argfn_mwo_clip(const gfxd_value_t *v) -{ - switch (v->u) - { - case G_MWO_CLIP_RNX: - return gfxd_puts("G_MWO_CLIP_RNX"); - case G_MWO_CLIP_RNY: - return gfxd_puts("G_MWO_CLIP_RNY"); - case G_MWO_CLIP_RPX: - return gfxd_puts("G_MWO_CLIP_RPX"); - case G_MWO_CLIP_RPY: - return gfxd_puts("G_MWO_CLIP_RPY"); - default: - return gfxd_printf("0x%04" PRIX32, v->u); - } -} - -UCFUNC int argfn_mwo_lightcol(const gfxd_value_t *v) -{ - switch (v->u) - { - case G_MWO_aLIGHT_1: - return gfxd_puts("G_MWO_aLIGHT_1"); - case G_MWO_bLIGHT_1: - return gfxd_puts("G_MWO_bLIGHT_1"); - case G_MWO_aLIGHT_2: - return gfxd_puts("G_MWO_aLIGHT_2"); - case G_MWO_bLIGHT_2: - return gfxd_puts("G_MWO_bLIGHT_2"); - case G_MWO_aLIGHT_3: - return gfxd_puts("G_MWO_aLIGHT_3"); - case G_MWO_bLIGHT_3: - return gfxd_puts("G_MWO_bLIGHT_3"); - case G_MWO_aLIGHT_4: - return gfxd_puts("G_MWO_aLIGHT_4"); - case G_MWO_bLIGHT_4: - return gfxd_puts("G_MWO_bLIGHT_4"); - case G_MWO_aLIGHT_5: - return gfxd_puts("G_MWO_aLIGHT_5"); - case G_MWO_bLIGHT_5: - return gfxd_puts("G_MWO_bLIGHT_5"); - case G_MWO_aLIGHT_6: - return gfxd_puts("G_MWO_aLIGHT_6"); - case G_MWO_bLIGHT_6: - return gfxd_puts("G_MWO_bLIGHT_6"); - case G_MWO_aLIGHT_7: - return gfxd_puts("G_MWO_aLIGHT_7"); - case G_MWO_bLIGHT_7: - return gfxd_puts("G_MWO_bLIGHT_7"); - case G_MWO_aLIGHT_8: - return gfxd_puts("G_MWO_aLIGHT_8"); - case G_MWO_bLIGHT_8: - return gfxd_puts("G_MWO_bLIGHT_8"); - default: - return gfxd_printf("0x%04" PRIX32, v->u); - } -} - -UCFUNC int argfn_lightnum(const gfxd_value_t *v) -{ - return gfxd_printf("LIGHT_%" PRIi32, v->i); -} - -UCFUNC int argfn_lightsn(const gfxd_value_t *v) -{ - return gfxd_printf("*(Lightsn *)0x%08" PRIX32, v->u); -} - -UCFUNC int argfn_mwo_matrix(const gfxd_value_t *v) -{ - switch (v->u) - { - case G_MWO_MATRIX_XX_XY_I: - return gfxd_puts("G_MWO_MATRIX_XX_XY_I"); - case G_MWO_MATRIX_XZ_XW_I: - return gfxd_puts("G_MWO_MATRIX_XZ_XW_I"); - case G_MWO_MATRIX_YX_YY_I: - return gfxd_puts("G_MWO_MATRIX_YX_YY_I"); - case G_MWO_MATRIX_YZ_YW_I: - return gfxd_puts("G_MWO_MATRIX_YZ_YW_I"); - case G_MWO_MATRIX_ZX_ZY_I: - return gfxd_puts("G_MWO_MATRIX_ZX_ZY_I"); - case G_MWO_MATRIX_ZZ_ZW_I: - return gfxd_puts("G_MWO_MATRIX_ZZ_ZW_I"); - case G_MWO_MATRIX_WX_WY_I: - return gfxd_puts("G_MWO_MATRIX_WX_WY_I"); - case G_MWO_MATRIX_WZ_WW_I: - return gfxd_puts("G_MWO_MATRIX_WZ_WW_I"); - case G_MWO_MATRIX_XX_XY_F: - return gfxd_puts("G_MWO_MATRIX_XX_XY_F"); - case G_MWO_MATRIX_XZ_XW_F: - return gfxd_puts("G_MWO_MATRIX_XZ_XW_F"); - case G_MWO_MATRIX_YX_YY_F: - return gfxd_puts("G_MWO_MATRIX_YX_YY_F"); - case G_MWO_MATRIX_YZ_YW_F: - return gfxd_puts("G_MWO_MATRIX_YZ_YW_F"); - case G_MWO_MATRIX_ZX_ZY_F: - return gfxd_puts("G_MWO_MATRIX_ZX_ZY_F"); - case G_MWO_MATRIX_ZZ_ZW_F: - return gfxd_puts("G_MWO_MATRIX_ZZ_ZW_F"); - case G_MWO_MATRIX_WX_WY_F: - return gfxd_puts("G_MWO_MATRIX_WX_WY_F"); - case G_MWO_MATRIX_WZ_WW_F: - return gfxd_puts("G_MWO_MATRIX_WZ_WW_F"); - default: - return gfxd_printf("0x%04" PRIX32, v->u); - } -} - -UCFUNC int argfn_mwo_point(const gfxd_value_t *v) -{ - switch (v->u) - { - case G_MWO_POINT_RGBA: - return gfxd_puts("G_MWO_POINT_RGBA"); - case G_MWO_POINT_ST: - return gfxd_puts("G_MWO_POINT_ST"); - case G_MWO_POINT_XYSCREEN: - return gfxd_puts("G_MWO_POINT_XYSCREEN"); - case G_MWO_POINT_ZSCREEN: - return gfxd_puts("G_MWO_POINT_ZSCREEN"); - default: - return gfxd_printf("0x%04" PRIX32, v->u); - } -} - -UCFUNC int argfn_mv(const gfxd_value_t *v) -{ - switch (v->i) - { - case G_MV_VIEWPORT: - return gfxd_puts("G_MV_VIEWPORT"); -#if defined(F3D_GBI) || defined(F3DEX_GBI) - case G_MV_LOOKATY: - return gfxd_puts("G_MV_LOOKATY"); - case G_MV_LOOKATX: - return gfxd_puts("G_MV_LOOKATX"); - case G_MV_L0: - return gfxd_puts("G_MV_L0"); - case G_MV_L1: - return gfxd_puts("G_MV_L1"); - case G_MV_L2: - return gfxd_puts("G_MV_L2"); - case G_MV_L3: - return gfxd_puts("G_MV_L3"); - case G_MV_L4: - return gfxd_puts("G_MV_L4"); - case G_MV_L5: - return gfxd_puts("G_MV_L5"); - case G_MV_L6: - return gfxd_puts("G_MV_L6"); - case G_MV_L7: - return gfxd_puts("G_MV_L7"); - case G_MV_TXTATT: - return gfxd_puts("G_MV_TXTATT"); - case G_MV_MATRIX_2: - return gfxd_puts("G_MV_MATRIX_2"); - case G_MV_MATRIX_3: - return gfxd_puts("G_MV_MATRIX_3"); - case G_MV_MATRIX_4: - return gfxd_puts("G_MV_MATRIX_4"); - case G_MV_MATRIX_1: - return gfxd_puts("G_MV_MATRIX_1"); -#elif defined(F3DEX_GBI_2) - case G_MV_MMTX: - return gfxd_puts("G_MV_MMTX"); - case G_MV_PMTX: - return gfxd_puts("G_MV_PMTX"); - case G_MV_LIGHT: - return gfxd_puts("G_MV_LIGHT"); - case G_MV_POINT: - return gfxd_puts("G_MV_POINT"); - case G_MV_MATRIX: - return gfxd_puts("G_MV_MATRIX"); -#endif - default: - return gfxd_printf("%" PRIi32, v->i); - } -} - -UCFUNC int argfn_cr(const gfxd_value_t *v) -{ - switch (v->u) - { - case FRUSTRATIO_1: - return gfxd_puts("FRUSTRATIO_1"); - case FRUSTRATIO_2: - return gfxd_puts("FRUSTRATIO_2"); - case FRUSTRATIO_3: - return gfxd_puts("FRUSTRATIO_3"); - case FRUSTRATIO_4: - return gfxd_puts("FRUSTRATIO_4"); - case FRUSTRATIO_5: - return gfxd_puts("FRUSTRATIO_5"); - case FRUSTRATIO_6: - return gfxd_puts("FRUSTRATIO_6"); - default: - return gfxd_printf("%" PRIu32, v->u); - } -} diff --git a/tools/ZAPD/lib/libgfxd/uc_argtbl.c b/tools/ZAPD/lib/libgfxd/uc_argtbl.c deleted file mode 100644 index 22a0b65009..0000000000 --- a/tools/ZAPD/lib/libgfxd/uc_argtbl.c +++ /dev/null @@ -1,485 +0,0 @@ -static const gfxd_arg_type_t arg_tbl[] = -{ - [gfxd_Word] = - { - .fmt = gfxd_argfmt_u, - .fn = argfn_x32, - }, - [gfxd_Opcode] = - { - .fmt = gfxd_argfmt_i, - .fn = argfn_opc, - }, - [gfxd_Coordi] = - { - .fmt = gfxd_argfmt_u, - .fn = argfn_u, - }, - [gfxd_Coordq] = - { - .fmt = gfxd_argfmt_u, - .fn = argfn_qu102, - }, - [gfxd_Pal] = - { - .fmt = gfxd_argfmt_i, - .fn = argfn_i, - }, - [gfxd_Tlut] = - { - .fmt = gfxd_argfmt_u, - .fn = argfn_x32, - }, - [gfxd_Timg] = - { - .fmt = gfxd_argfmt_u, - .fn = argfn_x32, - }, - [gfxd_Tmem] = - { - .fmt = gfxd_argfmt_u, - .fn = argfn_x16, - }, - [gfxd_Tile] = - { - .fmt = gfxd_argfmt_i, - .fn = argfn_tile, - }, - [gfxd_Fmt] = - { - .fmt = gfxd_argfmt_i, - .fn = argfn_fmt, - }, - [gfxd_Siz] = - { - .fmt = gfxd_argfmt_i, - .fn = argfn_siz, - }, - [gfxd_Dim] = - { - .fmt = gfxd_argfmt_i, - .fn = argfn_i, - }, - [gfxd_Cm] = - { - .fmt = gfxd_argfmt_u, - .fn = argfn_cm, - }, - [gfxd_Tm] = - { - .fmt = gfxd_argfmt_i, - .fn = argfn_tm, - }, - [gfxd_Ts] = - { - .fmt = gfxd_argfmt_i, - .fn = argfn_ts, - }, - [gfxd_Dxt] = - { - .fmt = gfxd_argfmt_u, - .fn = argfn_u, - }, - [gfxd_Tag] = - { - .fmt = gfxd_argfmt_u, - .fn = argfn_x32, - }, - [gfxd_Pm] = - { - .fmt = gfxd_argfmt_u, - .fn = argfn_pm, - }, - [gfxd_Colorpart] = - { - .fmt = gfxd_argfmt_u, - .fn = argfn_color, - }, - [gfxd_Color] = - { - .fmt = gfxd_argfmt_u, - .fn = argfn_x32, - }, - [gfxd_Lodfrac] = - { - .fmt = gfxd_argfmt_u, - .fn = argfn_qu08, - }, - [gfxd_Cimg] = - { - .fmt = gfxd_argfmt_u, - .fn = argfn_x32, - }, - [gfxd_Zimg] = - { - .fmt = gfxd_argfmt_u, - .fn = argfn_x32, - }, - [gfxd_Ac] = - { - .fmt = gfxd_argfmt_u, - .fn = argfn_ac, - }, - [gfxd_Ad] = - { - .fmt = gfxd_argfmt_u, - .fn = argfn_ad, - }, - [gfxd_Cd] = - { - .fmt = gfxd_argfmt_u, - .fn = argfn_cd, - }, - [gfxd_Ccpre] = - { - .fmt = gfxd_argfmt_u, - .fn = argfn_ccpre, - }, - [gfxd_Ccmuxa] = - { - .fmt = gfxd_argfmt_i, - .fn = argfn_ccmuxa, - }, - [gfxd_Ccmuxb] = - { - .fmt = gfxd_argfmt_i, - .fn = argfn_ccmuxb, - }, - [gfxd_Ccmuxc] = - { - .fmt = gfxd_argfmt_i, - .fn = argfn_ccmuxc, - }, - [gfxd_Ccmuxd] = - { - .fmt = gfxd_argfmt_i, - .fn = argfn_ccmuxd, - }, - [gfxd_Acmuxabd] = - { - .fmt = gfxd_argfmt_i, - .fn = argfn_acmuxabd, - }, - [gfxd_Acmuxc] = - { - .fmt = gfxd_argfmt_i, - .fn = argfn_acmuxc, - }, - [gfxd_Cv] = - { - .fmt = gfxd_argfmt_i, - .fn = argfn_cv, - }, - [gfxd_Tc] = - { - .fmt = gfxd_argfmt_u, - .fn = argfn_tc, - }, - [gfxd_Cyc] = - { - .fmt = gfxd_argfmt_u, - .fn = argfn_cyc, - }, - [gfxd_Zs] = - { - .fmt = gfxd_argfmt_u, - .fn = argfn_zs, - }, - [gfxd_Ck] = - { - .fmt = gfxd_argfmt_u, - .fn = argfn_ck, - }, - [gfxd_Keyscale] = - { - .fmt = gfxd_argfmt_u, - .fn = argfn_color, - }, - [gfxd_Keywidth] = - { - .fmt = gfxd_argfmt_i, - .fn = argfn_qs48, - }, - [gfxd_Zi] = - { - .fmt = gfxd_argfmt_i, - .fn = argfn_i, - }, - [gfxd_Rm1] = - { - .fmt = gfxd_argfmt_u, - .fn = argfn_rm1, - }, - [gfxd_Rm2] = - { - .fmt = gfxd_argfmt_u, - .fn = argfn_rm2, - }, - [gfxd_Sc] = - { - .fmt = gfxd_argfmt_i, - .fn = argfn_sc, - }, - [gfxd_Td] = - { - .fmt = gfxd_argfmt_u, - .fn = argfn_td, - }, - [gfxd_Tf] = - { - .fmt = gfxd_argfmt_u, - .fn = argfn_tf, - }, - [gfxd_Tl] = - { - .fmt = gfxd_argfmt_u, - .fn = argfn_tl, - }, - [gfxd_Tt] = - { - .fmt = gfxd_argfmt_u, - .fn = argfn_tt, - }, - [gfxd_Tp] = - { - .fmt = gfxd_argfmt_u, - .fn = argfn_tp, - }, - [gfxd_Line] = - { - .fmt = gfxd_argfmt_i, - .fn = argfn_i, - }, - [gfxd_Vtx] = - { - .fmt = gfxd_argfmt_i, - .fn = argfn_i, - }, - [gfxd_Vtxflag] = - { - .fmt = gfxd_argfmt_i, - .fn = argfn_i, - }, - [gfxd_Dl] = - { - .fmt = gfxd_argfmt_u, - .fn = argfn_x32, - }, -#if defined(F3DEX_GBI) || defined(F3DEX_GBI_2) - [gfxd_Zraw] = - { - .fmt = gfxd_argfmt_i, - .fn = argfn_qs1616, - }, -#endif - [gfxd_Dlflag] = - { - .fmt = gfxd_argfmt_i, - .fn = argfn_dlf, - }, - [gfxd_Cr] = - { - .fmt = gfxd_argfmt_u, - .fn = argfn_cr, - }, - [gfxd_Num] = - { - .fmt = gfxd_argfmt_i, - .fn = argfn_i, - }, - [gfxd_Fogz] = - { - .fmt = gfxd_argfmt_i, - .fn = argfn_i, - }, - [gfxd_Fogp] = - { - .fmt = gfxd_argfmt_i, - .fn = argfn_i, - }, - [gfxd_Mtxptr] = - { - .fmt = gfxd_argfmt_u, - .fn = argfn_x32, - }, - [gfxd_Gm] = - { - .fmt = gfxd_argfmt_u, - .fn = argfn_gm, - }, - [gfxd_Mwo_matrix] = - { - .fmt = gfxd_argfmt_u, - .fn = argfn_mwo_matrix, - }, - [gfxd_Linewd] = - { - .fmt = gfxd_argfmt_i, - .fn = argfn_i, - }, - [gfxd_Uctext] = - { - .fmt = gfxd_argfmt_u, - .fn = argfn_x32, - }, - [gfxd_Ucdata] = - { - .fmt = gfxd_argfmt_u, - .fn = argfn_x32, - }, - [gfxd_Size] = - { - .fmt = gfxd_argfmt_u, - .fn = argfn_x16, - }, - [gfxd_Lookatptr] = - { - .fmt = gfxd_argfmt_u, - .fn = argfn_x32, - }, - [gfxd_Mtxparam] = - { - .fmt = gfxd_argfmt_i, - .fn = argfn_mp, - }, - [gfxd_Mtxstack] = - { - .fmt = gfxd_argfmt_i, - .fn = argfn_ms, - }, - [gfxd_Mwo_point] = - { - .fmt = gfxd_argfmt_u, - .fn = argfn_mwo_point, - }, - [gfxd_Wscale] = - { - .fmt = gfxd_argfmt_u, - .fn = argfn_qu016, - }, - [gfxd_Seg] = - { - .fmt = gfxd_argfmt_u, - .fn = argfn_x8, - }, - [gfxd_Segptr] = - { - .fmt = gfxd_argfmt_u, - .fn = argfn_x32, - }, - [gfxd_Lightsn] = - { - .fmt = gfxd_argfmt_u, - .fn = argfn_lightsn, - }, - [gfxd_Numlights] = - { - .fmt = gfxd_argfmt_i, - .fn = argfn_i, - }, - [gfxd_Lightnum] = - { - .fmt = gfxd_argfmt_i, - .fn = argfn_lightnum, - }, - [gfxd_Lightptr] = - { - .fmt = gfxd_argfmt_u, - .fn = argfn_x32, - }, - [gfxd_Tcscale] = - { - .fmt = gfxd_argfmt_u, - .fn = argfn_qu016, - }, - [gfxd_Switch] = - { - .fmt = gfxd_argfmt_i, - .fn = argfn_switch, - }, - [gfxd_St] = - { - .fmt = gfxd_argfmt_i, - .fn = argfn_qs105, - }, - [gfxd_Stdelta] = - { - .fmt = gfxd_argfmt_i, - .fn = argfn_qs510, - }, - [gfxd_Vtxptr] = - { - .fmt = gfxd_argfmt_u, - .fn = argfn_x32, - }, - [gfxd_Vpptr] = - { - .fmt = gfxd_argfmt_u, - .fn = argfn_x32, - }, - [gfxd_Dram] = - { - .fmt = gfxd_argfmt_u, - .fn = argfn_x32, - }, - [gfxd_Sftlo] = - { - .fmt = gfxd_argfmt_i, - .fn = argfn_sftlo, - }, - [gfxd_Othermodelo] = - { - .fmt = gfxd_argfmt_u, - .fn = argfn_othermodelo, - }, - [gfxd_Sfthi] = - { - .fmt = gfxd_argfmt_i, - .fn = argfn_sfthi, - }, - [gfxd_Othermodehi] = - { - .fmt = gfxd_argfmt_u, - .fn = argfn_othermodehi, - }, - [gfxd_Mw] = - { - .fmt = gfxd_argfmt_i, - .fn = argfn_mw, - }, - [gfxd_Mwo] = - { - .fmt = gfxd_argfmt_u, - .fn = argfn_x16, - }, - [gfxd_Mwo_clip] = - { - .fmt = gfxd_argfmt_u, - .fn = argfn_mwo_clip, - }, - [gfxd_Mwo_lightcol] = - { - .fmt = gfxd_argfmt_u, - .fn = argfn_mwo_lightcol, - }, - [gfxd_Mv] = - { - .fmt = gfxd_argfmt_i, - .fn = argfn_mv, - }, - [gfxd_Mvo] = - { - .fmt = gfxd_argfmt_u, - .fn = argfn_x16, - }, - [gfxd_Dmem] = - { - .fmt = gfxd_argfmt_u, - .fn = argfn_x16, - }, - [gfxd_Dmaflag] = - { - .fmt = gfxd_argfmt_i, - .fn = argfn_i, - }, -}; diff --git a/tools/ZAPD/lib/libgfxd/uc_f3d.c b/tools/ZAPD/lib/libgfxd/uc_f3d.c deleted file mode 100644 index 9465515108..0000000000 --- a/tools/ZAPD/lib/libgfxd/uc_f3d.c +++ /dev/null @@ -1,4 +0,0 @@ -#define uc_name gfxd_f3d -#define F3D_GBI - -#include "uc.c" diff --git a/tools/ZAPD/lib/libgfxd/uc_f3db.c b/tools/ZAPD/lib/libgfxd/uc_f3db.c deleted file mode 100644 index cd4990412d..0000000000 --- a/tools/ZAPD/lib/libgfxd/uc_f3db.c +++ /dev/null @@ -1,5 +0,0 @@ -#define uc_name gfxd_f3db -#define F3D_GBI -#define F3D_BETA - -#include "uc.c" diff --git a/tools/ZAPD/lib/libgfxd/uc_f3dex.c b/tools/ZAPD/lib/libgfxd/uc_f3dex.c deleted file mode 100644 index 2ec70d8aba..0000000000 --- a/tools/ZAPD/lib/libgfxd/uc_f3dex.c +++ /dev/null @@ -1,4 +0,0 @@ -#define uc_name gfxd_f3dex -#define F3DEX_GBI - -#include "uc.c" diff --git a/tools/ZAPD/lib/libgfxd/uc_f3dex2.c b/tools/ZAPD/lib/libgfxd/uc_f3dex2.c deleted file mode 100644 index 9a19c99038..0000000000 --- a/tools/ZAPD/lib/libgfxd/uc_f3dex2.c +++ /dev/null @@ -1,4 +0,0 @@ -#define uc_name gfxd_f3dex2 -#define F3DEX_GBI_2 - -#include "uc.c" diff --git a/tools/ZAPD/lib/libgfxd/uc_f3dexb.c b/tools/ZAPD/lib/libgfxd/uc_f3dexb.c deleted file mode 100644 index 2b5c30a4a6..0000000000 --- a/tools/ZAPD/lib/libgfxd/uc_f3dexb.c +++ /dev/null @@ -1,5 +0,0 @@ -#define uc_name gfxd_f3dexb -#define F3DEX_GBI -#define F3D_BETA - -#include "uc.c" diff --git a/tools/ZAPD/lib/libgfxd/uc_macrofn.c b/tools/ZAPD/lib/libgfxd/uc_macrofn.c deleted file mode 100644 index 46d4b4ee8c..0000000000 --- a/tools/ZAPD/lib/libgfxd/uc_macrofn.c +++ /dev/null @@ -1,2507 +0,0 @@ -static inline uint32_t getfield(uint32_t w, int n, int s) -{ - return (w >> s) & (((uint32_t)1 << n) - 1); -} - -static inline int32_t argvi(gfxd_macro_t *m, int idx) -{ - return m->arg[idx].value.i; -} - -static inline uint32_t argvu(gfxd_macro_t *m, int idx) -{ - return m->arg[idx].value.u; -} - -static inline float argvf(gfxd_macro_t *m, int idx) -{ - return m->arg[idx].value.f; -} - -static inline void argi(gfxd_macro_t *m, int idx, const char *name, - int32_t value, int type) -{ - m->arg[idx].type = type; - m->arg[idx].name = name; - m->arg[idx].value.i = value; - m->arg[idx].bad = 0; -} - -static inline void argu(gfxd_macro_t *m, int idx, const char *name, - uint32_t value, int type) -{ - m->arg[idx].type = type; - m->arg[idx].name = name; - m->arg[idx].value.u = value; - m->arg[idx].bad = 0; -} - -static inline void argf(gfxd_macro_t *m, int idx, const char *name, - float value, int type) -{ - m->arg[idx].type = type; - m->arg[idx].name = name; - m->arg[idx].value.f = value; - m->arg[idx].bad = 0; -} - -static inline void badarg(gfxd_macro_t *m, int idx) -{ - m->arg[idx].bad = 1; -} - -UCFUNC int32_t sx(uint32_t n, int bits) -{ - int32_t smin = (int32_t)1 << (bits - 1); - int32_t smax = (int32_t)1 << bits; - int32_t i = n; - if (i < smin) - return i; - else - return i - smax; -} - -UCFUNC int d_Invalid(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_Invalid; - argu(m, 0, "hi", hi, gfxd_Word); - argu(m, 1, "lo", lo, gfxd_Word); - return -1; -} - -UCFUNC int d_DPFillRectangle(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_DPFillRectangle; - argu(m, 0, "ulx", getfield(lo, 10, 14), gfxd_Coordi); - argu(m, 1, "uly", getfield(lo, 10, 2), gfxd_Coordi); - argu(m, 2, "lrx", getfield(hi, 10, 14), gfxd_Coordi); - argu(m, 3, "lry", getfield(hi, 10, 2), gfxd_Coordi); - return 0; -} - -UCFUNC int d_DPFullSync(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_DPFullSync; - return 0; -} - -UCFUNC int d_DPLoadSync(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_DPLoadSync; - return 0; -} - -UCFUNC int d_DPTileSync(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_DPTileSync; - return 0; -} - -UCFUNC int d_DPPipeSync(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_DPPipeSync; - return 0; -} - -UCFUNC int c_DPLoadTLUT_pal16(gfxd_macro_t *m, int n_macro) -{ - if (n_macro < 6) - return -1; - if (m[0].id != gfxd_DPSetTextureImage - || argvi(&m[0], 0) != G_IM_FMT_RGBA - || argvi(&m[0], 1) != G_IM_SIZ_16b - || argvi(&m[0], 2) != 1) - { - return -1; - } - uint32_t dram = argvu(&m[0], 3); - if (m[1].id != gfxd_DPTileSync) - return -1; - if (m[2].id != gfxd_DPSetTile - || argvi(&m[2], 0) != 0 - || argvi(&m[2], 1) != 0 - || argvi(&m[2], 2) != 0 - || argvu(&m[2], 3) < 0x100 - || argvu(&m[2], 3) % 0x10 != 0 - || argvi(&m[2], 4) != G_TX_LOADTILE - || argvi(&m[2], 5) != 0 - || argvu(&m[2], 6) != 0 - || argvi(&m[2], 7) != 0 - || argvi(&m[2], 8) != 0 - || argvu(&m[2], 9) != 0 - || argvi(&m[2], 10) != 0 - || argvi(&m[2], 11) != 0) - { - return -1; - } - int pal = (argvu(&m[2], 3) - 0x100) / 0x10; - if (m[3].id != gfxd_DPLoadSync) - return -1; - if (m[4].id != gfxd_DPLoadTLUTCmd - || argvi(&m[4], 0) != G_TX_LOADTILE - || argvi(&m[4], 1) != 15) - { - return -1; - } - if (m[5].id != gfxd_DPPipeSync) - return -1; - m->id = gfxd_DPLoadTLUT_pal16; - argi(m, 0, "pal", pal, gfxd_Pal); - argu(m, 1, "dram", dram, gfxd_Tlut); - return 0; -} - -UCFUNC int c_DPLoadTLUT_pal256(gfxd_macro_t *m, int n_macro) -{ - if (n_macro < 6) - return -1; - if (m[0].id != gfxd_DPSetTextureImage - || argvi(&m[0], 0) != G_IM_FMT_RGBA - || argvi(&m[0], 1) != G_IM_SIZ_16b - || argvi(&m[0], 2) != 1) - { - return -1; - } - uint32_t dram = argvu(&m[0], 3); - if (m[1].id != gfxd_DPTileSync) - return -1; - if (m[2].id != gfxd_DPSetTile - || argvi(&m[2], 0) != 0 - || argvi(&m[2], 1) != 0 - || argvi(&m[2], 2) != 0 - || argvu(&m[2], 3) != 0x100 - || argvi(&m[2], 4) != G_TX_LOADTILE - || argvi(&m[2], 5) != 0 - || argvu(&m[2], 6) != 0 - || argvi(&m[2], 7) != 0 - || argvi(&m[2], 8) != 0 - || argvu(&m[2], 9) != 0 - || argvi(&m[2], 10) != 0 - || argvi(&m[2], 11) != 0) - { - return -1; - } - if (m[3].id != gfxd_DPLoadSync) - return -1; - if (m[4].id != gfxd_DPLoadTLUTCmd - || argvi(&m[4], 0) != G_TX_LOADTILE - || argvi(&m[4], 1) != 255) - { - return -1; - } - if (m[5].id != gfxd_DPPipeSync) - return -1; - m->id = gfxd_DPLoadTLUT_pal256; - argu(m, 0, "dram", dram, gfxd_Tlut); - return 0; -} - -UCFUNC int c_ltb(gfxd_macro_t *m, int n_macro, int id, int mdxt, int mtmem, - int mrt, int myuv, int m4b) -{ - if (n_macro < 7) - return -1; - if (m[0].id != gfxd_DPSetTextureImage || argvi(&m[0], 2) != 1) - return -1; - g_ifmt_t fmt = argvi(&m[0], 0); - g_isiz_t ldsiz = argvi(&m[0], 1); - uint32_t timg = argvu(&m[0], 3); - if (myuv && fmt != G_IM_FMT_YUV) - return -1; - if (m[1].id != gfxd_DPSetTile - || argvi(&m[1], 0) != fmt - || argvi(&m[1], 1) != ldsiz - || argvi(&m[1], 2) != 0 - || argvi(&m[1], 4) != G_TX_LOADTILE - || argvi(&m[1], 5) != 0) - { - return -1; - } - uint32_t tmem = argvu(&m[1], 3); - unsigned cms = argvu(&m[1], 9); - unsigned cmt = argvu(&m[1], 6); - int masks = argvi(&m[1], 10); - int maskt = argvi(&m[1], 7); - int shifts = argvi(&m[1], 11); - int shiftt = argvi(&m[1], 8); - if (m[2].id != gfxd_DPLoadSync) - return -1; - if (m[3].id != gfxd_DPLoadBlock - || argvi(&m[3], 0) != G_TX_LOADTILE - || argvu(&m[3], 1) != 0 - || argvu(&m[3], 2) != 0) - { - return -1; - } - qu102_t ldlrs = argvu(&m[3], 3); - unsigned lddxt = argvu(&m[3], 4); - if (m[4].id != gfxd_DPPipeSync) - return -1; - if (m[5].id != gfxd_DPSetTile - || argvi(&m[5], 0) != fmt - || G_SIZ_LDSIZ(argvi(&m[5], 1)) != ldsiz - || argvu(&m[5], 3) != tmem - || argvu(&m[5], 6) != cmt - || argvi(&m[5], 7) != maskt - || argvi(&m[5], 8) != shiftt - || argvu(&m[5], 9) != cms - || argvi(&m[5], 10) != masks - || argvi(&m[5], 11) != shifts) - { - return -1; - } - int siz = argvi(&m[5], 1); - int rdline = argvi(&m[5], 2); - int rt = argvi(&m[5], 4); - int pal = argvi(&m[5], 5); - if (m4b && siz != G_IM_SIZ_4b) - return -1; - if (!(mrt && rt != G_TX_RENDERTILE && tmem == 0) - && (tmem != 0) != mtmem) - { - return -1; - } - if ((rt != G_TX_RENDERTILE) != mrt) - return -1; - if (m[6].id != gfxd_DPSetTileSize - || argvi(&m[6], 0) != rt - || argvu(&m[6], 1) != 0 - || argvu(&m[6], 2) != 0 - || (argvu(&m[6], 3) & 3) - || (argvu(&m[6], 4) & 3)) - { - return -1; - } - int width = (argvu(&m[6], 3) >> 2) + 1; - int height = (argvu(&m[6], 4) >> 2) + 1; - unsigned lrs = G_LDBLK_TXL(G_LTB_LRS(width, height, siz)); - unsigned dxt = 0; - if (!mdxt) - dxt = G_DXT(siz, width); - int line; - if (myuv) - line = (width + 7) / 8; - else - line = (width * G_SIZ_LDBITS(siz) + 63) / 64; - if (ldlrs != lrs || lddxt != dxt || rdline != line) - return -1; - m->id = id; - int i = 0; - argu(m, i++, "timg", timg, gfxd_Timg); - if (mtmem) - argu(m, i++, "tmem", tmem, gfxd_Tmem); - if (mrt) - argi(m, i++, "rtile", rt, gfxd_Tile); - argi(m, i++, "fmt", fmt, gfxd_Fmt); - if (!m4b) - argi(m, i++, "siz", siz, gfxd_Siz); - argi(m, i++, "width", width, gfxd_Dim); - argi(m, i++, "height", height, gfxd_Dim); - argi(m, i++, "pal", pal, gfxd_Pal); - argu(m, i++, "cms", cms, gfxd_Cm); - argu(m, i++, "cmt", cmt, gfxd_Cm); - argi(m, i++, "masks", masks, gfxd_Tm); - argi(m, i++, "maskt", maskt, gfxd_Tm); - argi(m, i++, "shifts", shifts, gfxd_Ts); - argi(m, i++, "shiftt", shiftt, gfxd_Ts); - return 0; -} - -UCFUNC int c_DPLoadMultiBlockYuvS(gfxd_macro_t *m, int n_macro) -{ - return c_ltb(m, n_macro, gfxd_DPLoadMultiBlockYuvS, 1, 1, 1, 1, 0); -} - -UCFUNC int c_DPLoadMultiBlockYuv(gfxd_macro_t *m, int n_macro) -{ - return c_ltb(m, n_macro, gfxd_DPLoadMultiBlockYuv, 0, 1, 1, 1, 0); -} - -UCFUNC int c_DPLoadMultiBlock_4bS(gfxd_macro_t *m, int n_macro) -{ - return c_ltb(m, n_macro, gfxd_DPLoadMultiBlock_4bS, 1, 1, 1, 0, 1); -} - -UCFUNC int c_DPLoadMultiBlock_4b(gfxd_macro_t *m, int n_macro) -{ - return c_ltb(m, n_macro, gfxd_DPLoadMultiBlock_4b, 0, 1, 1, 0, 1); -} - -UCFUNC int c_DPLoadMultiBlockS(gfxd_macro_t *m, int n_macro) -{ - return c_ltb(m, n_macro, gfxd_DPLoadMultiBlockS, 1, 1, 1, 0, 0); -} - -UCFUNC int c_DPLoadMultiBlock(gfxd_macro_t *m, int n_macro) -{ - return c_ltb(m, n_macro, gfxd_DPLoadMultiBlock, 0, 1, 1, 0, 0); -} - -UCFUNC int c__DPLoadTextureBlockYuvS(gfxd_macro_t *m, int n_macro) -{ - return c_ltb(m, n_macro, gfxd__DPLoadTextureBlockYuvS, 1, 1, 0, 1, 0); -} - -UCFUNC int c__DPLoadTextureBlockYuv(gfxd_macro_t *m, int n_macro) -{ - return c_ltb(m, n_macro, gfxd__DPLoadTextureBlockYuv, 0, 1, 0, 1, 0); -} - -UCFUNC int c__DPLoadTextureBlock_4bS(gfxd_macro_t *m, int n_macro) -{ - return c_ltb(m, n_macro, gfxd__DPLoadTextureBlock_4bS, 1, 1, 0, 0, 1); -} - -UCFUNC int c__DPLoadTextureBlock_4b(gfxd_macro_t *m, int n_macro) -{ - return c_ltb(m, n_macro, gfxd__DPLoadTextureBlock_4b, 0, 1, 0, 0, 1); -} - -UCFUNC int c__DPLoadTextureBlockS(gfxd_macro_t *m, int n_macro) -{ - return c_ltb(m, n_macro, gfxd__DPLoadTextureBlockS, 1, 1, 0, 0, 0); -} - -UCFUNC int c__DPLoadTextureBlock(gfxd_macro_t *m, int n_macro) -{ - return c_ltb(m, n_macro, gfxd__DPLoadTextureBlock, 0, 1, 0, 0, 0); -} - -UCFUNC int c_DPLoadTextureBlockYuvS(gfxd_macro_t *m, int n_macro) -{ - return c_ltb(m, n_macro, gfxd_DPLoadTextureBlockYuvS, 1, 0, 0, 1, 0); -} - -UCFUNC int c_DPLoadTextureBlockYuv(gfxd_macro_t *m, int n_macro) -{ - return c_ltb(m, n_macro, gfxd_DPLoadTextureBlockYuv, 0, 0, 0, 1, 0); -} - -UCFUNC int c_DPLoadTextureBlock_4bS(gfxd_macro_t *m, int n_macro) -{ - return c_ltb(m, n_macro, gfxd_DPLoadTextureBlock_4bS, 1, 0, 0, 0, 1); -} - -UCFUNC int c_DPLoadTextureBlock_4b(gfxd_macro_t *m, int n_macro) -{ - return c_ltb(m, n_macro, gfxd_DPLoadTextureBlock_4b, 0, 0, 0, 0, 1); -} - -UCFUNC int c_DPLoadTextureBlockS(gfxd_macro_t *m, int n_macro) -{ - return c_ltb(m, n_macro, gfxd_DPLoadTextureBlockS, 1, 0, 0, 0, 0); -} - -UCFUNC int c_DPLoadTextureBlock(gfxd_macro_t *m, int n_macro) -{ - return c_ltb(m, n_macro, gfxd_DPLoadTextureBlock, 0, 0, 0, 0, 0); -} - -UCFUNC int c_ltt(gfxd_macro_t *m, int n_macro, int id, int mtmem, int mrt, - int myuv, int m4b) -{ - if (n_macro < 7) - return -1; - if (m[0].id != gfxd_DPSetTextureImage) - return -1; - g_ifmt_t fmt = argvi(&m[0], 0); - g_isiz_t ldsiz = argvi(&m[0], 1); - int width = argvi(&m[0], 2); - if (m4b) - { - if (ldsiz != G_IM_SIZ_8b) - return -1; - width *= 2; - } - uint32_t timg = argvu(&m[0], 3); - if (myuv && fmt != G_IM_FMT_YUV) - return -1; - if (m[1].id != gfxd_DPSetTile - || argvi(&m[1], 0) != fmt - || argvi(&m[1], 1) != ldsiz - || argvi(&m[1], 4) != G_TX_LOADTILE - || argvi(&m[1], 5) != 0) - { - return -1; - } - int ldline = argvi(&m[1], 2); - uint32_t tmem = argvu(&m[1], 3); - unsigned cms = argvu(&m[1], 9); - unsigned cmt = argvu(&m[1], 6); - int masks = argvi(&m[1], 10); - int maskt = argvi(&m[1], 7); - int shifts = argvi(&m[1], 11); - int shiftt = argvi(&m[1], 8); - if (m[2].id != gfxd_DPLoadSync) - return -1; - if (m[3].id != gfxd_DPLoadTile - || argvi(&m[3], 0) != G_TX_LOADTILE - || (argvu(&m[3], 1) & 1) - || (argvu(&m[3], 2) & 3) - || (argvu(&m[3], 3) & 1) - || (argvu(&m[3], 4) & 3)) - { - return -1; - } - qu102_t lduls = argvu(&m[3], 1); - qu102_t ldult = argvu(&m[3], 2); - qu102_t ldlrs = argvu(&m[3], 3); - qu102_t ldlrt = argvu(&m[3], 4); - if (m[4].id != gfxd_DPPipeSync) - return -1; - if (m[5].id != gfxd_DPSetTile - || argvi(&m[5], 0) != fmt - || argvi(&m[5], 2) != ldline - || argvu(&m[5], 3) != tmem - || argvu(&m[5], 6) != cmt - || argvi(&m[5], 7) != maskt - || argvi(&m[5], 8) != shiftt - || argvu(&m[5], 9) != cms - || argvi(&m[5], 10) != masks - || argvi(&m[5], 11) != shifts) - { - return -1; - } - int siz = argvi(&m[5], 1); - int rt = argvi(&m[5], 4); - int pal = argvi(&m[5], 5); - if (m4b) - { - if (siz != G_IM_SIZ_4b) - return -1; - } - else if (siz != ldsiz) - return -1; - if (!(mrt && rt != G_TX_RENDERTILE && tmem == 0) - && (tmem != 0) != mtmem) - { - return -1; - } - if ((rt != G_TX_RENDERTILE) != mrt) - return -1; - if (m[6].id != gfxd_DPSetTileSize - || argvi(&m[6], 0) != rt - || (argvu(&m[6], 1) & 3) - || (argvu(&m[6], 2) & 3) - || (argvu(&m[6], 3) & 3) - || (argvu(&m[6], 4) & 3)) - { - return -1; - } - unsigned uls = argvu(&m[6], 1) >> 2; - unsigned ult = argvu(&m[6], 2) >> 2; - unsigned lrs = argvu(&m[6], 3) >> 2; - unsigned lrt = argvu(&m[6], 4) >> 2; - int line; - if (myuv) - line = ((lrs - uls + 1) + 7) / 8; - else if (m4b) - line = ((lrs - uls + 1) / 2 + 7) / 8; - else - line = ((lrs - uls + 1) * G_SIZ_LDBITS(siz) + 63) / 64; - if (m4b) - { - if (lduls != qu102(uls) / 2 || ldlrs != qu102(lrs) / 2) - return -1; - } - else if (lduls != qu102(uls) || ldlrs != qu102(lrs)) - return -1; - if (ldult != qu102(ult) || ldlrt != qu102(lrt) || ldline != line) - return -1; - m->id = id; - int i = 0; - argu(m, i++, "timg", timg, gfxd_Timg); - if (mtmem) - argu(m, i++, "tmem", tmem, gfxd_Tmem); - if (mrt) - argi(m, i++, "rtile", rt, gfxd_Tile); - argi(m, i++, "fmt", fmt, gfxd_Fmt); - if (!m4b) - argi(m, i++, "siz", siz, gfxd_Siz); - argi(m, i++, "width", width, gfxd_Dim); - argi(m, i++, "height", 0, gfxd_Dim); - argu(m, i++, "uls", uls, gfxd_Coordi); - argu(m, i++, "ult", ult, gfxd_Coordi); - argu(m, i++, "lrs", lrs, gfxd_Coordi); - argu(m, i++, "lrt", lrt, gfxd_Coordi); - argi(m, i++, "pal", pal, gfxd_Pal); - argu(m, i++, "cms", cms, gfxd_Cm); - argu(m, i++, "cmt", cmt, gfxd_Cm); - argi(m, i++, "masks", masks, gfxd_Tm); - argi(m, i++, "maskt", maskt, gfxd_Tm); - argi(m, i++, "shifts", shifts, gfxd_Ts); - argi(m, i++, "shiftt", shiftt, gfxd_Ts); - return 0; -} - -UCFUNC int c_DPLoadMultiTileYuv(gfxd_macro_t *m, int n_macro) -{ - return c_ltt(m, n_macro, gfxd_DPLoadMultiTileYuv, 1, 1, 1, 0); -} - -UCFUNC int c_DPLoadMultiTile_4b(gfxd_macro_t *m, int n_macro) -{ - return c_ltt(m, n_macro, gfxd_DPLoadMultiTile_4b, 1, 1, 0, 1); -} - -UCFUNC int c_DPLoadMultiTile(gfxd_macro_t *m, int n_macro) -{ - return c_ltt(m, n_macro, gfxd_DPLoadMultiTile, 1, 1, 0, 0); -} - -UCFUNC int c__DPLoadTextureTileYuv(gfxd_macro_t *m, int n_macro) -{ - return c_ltt(m, n_macro, gfxd__DPLoadTextureTileYuv, 1, 0, 1, 0); -} - -UCFUNC int c__DPLoadTextureTile_4b(gfxd_macro_t *m, int n_macro) -{ - return c_ltt(m, n_macro, gfxd__DPLoadTextureTile_4b, 1, 0, 0, 1); -} - -UCFUNC int c__DPLoadTextureTile(gfxd_macro_t *m, int n_macro) -{ - return c_ltt(m, n_macro, gfxd__DPLoadTextureTile, 1, 0, 0, 0); -} - -UCFUNC int c_DPLoadTextureTileYuv(gfxd_macro_t *m, int n_macro) -{ - return c_ltt(m, n_macro, gfxd_DPLoadTextureTileYuv, 0, 0, 1, 0); -} - -UCFUNC int c_DPLoadTextureTile_4b(gfxd_macro_t *m, int n_macro) -{ - return c_ltt(m, n_macro, gfxd_DPLoadTextureTile_4b, 0, 0, 0, 1); -} - -UCFUNC int c_DPLoadTextureTile(gfxd_macro_t *m, int n_macro) -{ - return c_ltt(m, n_macro, gfxd_DPLoadTextureTile, 0, 0, 0, 0); -} - -UCFUNC int d_DPLoadBlock(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_DPLoadBlock; - argi(m, 0, "tile", getfield(lo, 3, 24), gfxd_Tile); - argu(m, 1, "uls", getfield(hi, 12, 12), gfxd_Coordi); - argu(m, 2, "ult", getfield(hi, 12, 0), gfxd_Coordi); - argu(m, 3, "lrs", getfield(lo, 12, 12), gfxd_Coordi); - argu(m, 4, "dxt", getfield(lo, 12, 0), gfxd_Dxt); - if (argvu(m, 3) > G_TX_LDBLK_MAX_TXL) { - badarg(m, 3); - return -1; - } - else { - return 0; - } -} - -UCFUNC int d_DPNoOp(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_DPNoOp; - return 0; -} - -UCFUNC int d_DPNoOpTag(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - if (lo == 0) - return d_DPNoOp(m, hi, lo); - else - { - m->id = gfxd_DPNoOpTag; - argu(m, 0, "tag", lo, gfxd_Tag); - return 0; - } -} - -UCFUNC int d_DPPipelineMode(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_DPPipelineMode; - argu(m, 0, "mode", lo, gfxd_Pm); - return 0; -} - -UCFUNC int d_DPSetBlendColor(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_DPSetBlendColor; - argu(m, 0, "r", getfield(lo, 8, 24), gfxd_Colorpart); - argu(m, 1, "g", getfield(lo, 8, 16), gfxd_Colorpart); - argu(m, 2, "b", getfield(lo, 8, 8), gfxd_Colorpart); - argu(m, 3, "a", getfield(lo, 8, 0), gfxd_Colorpart); - return 0; -} - -UCFUNC int d_DPSetEnvColor(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_DPSetEnvColor; - argu(m, 0, "r", getfield(lo, 8, 24), gfxd_Colorpart); - argu(m, 1, "g", getfield(lo, 8, 16), gfxd_Colorpart); - argu(m, 2, "b", getfield(lo, 8, 8), gfxd_Colorpart); - argu(m, 3, "a", getfield(lo, 8, 0), gfxd_Colorpart); - return 0; -} - -UCFUNC int d_DPSetFillColor(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_DPSetFillColor; - argu(m, 0, "c", lo, gfxd_Color); - return 0; -} - -UCFUNC int d_DPSetFogColor(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_DPSetFogColor; - argu(m, 0, "r", getfield(lo, 8, 24), gfxd_Colorpart); - argu(m, 1, "g", getfield(lo, 8, 16), gfxd_Colorpart); - argu(m, 2, "b", getfield(lo, 8, 8), gfxd_Colorpart); - argu(m, 3, "a", getfield(lo, 8, 0), gfxd_Colorpart); - return 0; -} - -UCFUNC int d_DPSetPrimColor(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_DPSetPrimColor; - argu(m, 0, "m", getfield(hi, 8, 8), gfxd_Lodfrac); - argu(m, 1, "l", getfield(hi, 8, 0), gfxd_Lodfrac); - argu(m, 2, "r", getfield(lo, 8, 24), gfxd_Colorpart); - argu(m, 3, "g", getfield(lo, 8, 16), gfxd_Colorpart); - argu(m, 4, "b", getfield(lo, 8, 8), gfxd_Colorpart); - argu(m, 5, "a", getfield(lo, 8, 0), gfxd_Colorpart); - return 0; -} - -UCFUNC int d_DPSetColorImage(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_DPSetColorImage; - argi(m, 0, "fmt", getfield(hi, 3, 21), gfxd_Fmt); - argi(m, 1, "siz", getfield(hi, 2, 19), gfxd_Siz); - argi(m, 2, "width", getfield(hi, 12, 0) + 1, gfxd_Dim); - argu(m, 3, "cimg", lo, gfxd_Cimg); - return 0; -} - -UCFUNC int d_DPSetDepthImage(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_DPSetDepthImage; - argu(m, 0, "zimg", lo, gfxd_Zimg); - return 0; -} - -UCFUNC int d_DPSetTextureImage(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_DPSetTextureImage; - argi(m, 0, "fmt", getfield(hi, 3, 21), gfxd_Fmt); - argi(m, 1, "siz", getfield(hi, 2, 19), gfxd_Siz); - argi(m, 2, "width", getfield(hi, 12, 0) + 1, gfxd_Dim); - argu(m, 3, "timg", lo, gfxd_Timg); - return 0; -} - -UCFUNC int d_DPSetAlphaCompare(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_DPSetAlphaCompare; - argu(m, 0, "mode", lo, gfxd_Ac); - return 0; -} - -UCFUNC int d_DPSetAlphaDither(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_DPSetAlphaDither; - argu(m, 0, "mode", lo, gfxd_Ad); - return 0; -} - -UCFUNC int d_DPSetColorDither(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_DPSetColorDither; - argu(m, 0, "mode", lo, gfxd_Cd); - return 0; -} - -UCFUNC void cc_unpack(struct cc_mode *m0, struct cc_mode *m1, uint32_t hi, - uint32_t lo) -{ - m0->a = getfield(hi, 4, 20); - m0->b = getfield(lo, 4, 28); - m0->c = getfield(hi, 5, 15); - m0->d = getfield(lo, 3, 15); - m0->Aa = getfield(hi, 3, 12); - m0->Ab = getfield(lo, 3, 12); - m0->Ac = getfield(hi, 3, 9); - m0->Ad = getfield(lo, 3, 9); - m1->a = getfield(hi, 4, 5); - m1->b = getfield(lo, 4, 24); - m1->c = getfield(hi, 5, 0); - m1->d = getfield(lo, 3, 6); - m1->Aa = getfield(lo, 3, 21); - m1->Ab = getfield(lo, 3, 3); - m1->Ac = getfield(lo, 3, 18); - m1->Ad = getfield(lo, 3, 0); -} - -UCFUNC int cc_lookup(const struct cc_mode *m) -{ - struct cc_mode m_norm = *m; - if (m_norm.a > 0x7) m_norm.a = G_CCMUX_0; - if (m_norm.b > 0x7) m_norm.b = G_CCMUX_0; - if (m_norm.c > 0xF) m_norm.c = G_CCMUX_0; - if (m_norm.d > 0x6) m_norm.d = G_CCMUX_0; - m = &m_norm; - int n_presets = sizeof(cc_presets) / sizeof(*cc_presets); - for (int i = 0; i < n_presets; i++) - { - const struct cc_mode *p = &cc_presets[i].mode; - if (m->a == p->a - && m->b == p->b - && m->c == p->c - && m->d == p->d - && m->Aa == p->Aa - && m->Ab == p->Ab - && m->Ac == p->Ac - && m->Ad == p->Ad) - { - return i; - } - } - return -1; -} - -UCFUNC int d_DPSetCombineMode(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_DPSetCombineMode; - struct cc_mode m0; - struct cc_mode m1; - cc_unpack(&m0, &m1, hi, lo); - int p0 = cc_lookup(&m0); - int p1 = cc_lookup(&m1); - argi(m, 0, "mode1", p0, gfxd_Ccpre); - argi(m, 1, "mode2", p1, gfxd_Ccpre); - int ret = 0; - if (p0 == -1) - { - badarg(m, 0); - ret = -1; - } - if (p1 == -1) - { - badarg(m, 1); - ret = -1; - } - return ret; -} - -UCFUNC int d_DPSetCombineLERP(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - struct cc_mode m0; - struct cc_mode m1; - cc_unpack(&m0, &m1, hi, lo); - int p0 = cc_lookup(&m0); - int p1 = cc_lookup(&m1); - if (p0 != -1 && p1 != -1) - return d_DPSetCombineMode(m, hi, lo); - else - { - m->id = gfxd_DPSetCombineLERP; - argi(m, 0, "a0", m0.a, gfxd_Ccmuxa); - argi(m, 1, "b0", m0.b, gfxd_Ccmuxb); - argi(m, 2, "c0", m0.c, gfxd_Ccmuxc); - argi(m, 3, "d0", m0.d, gfxd_Ccmuxd); - argi(m, 4, "Aa0", m0.Aa, gfxd_Acmuxabd); - argi(m, 5, "Ab0", m0.Ab, gfxd_Acmuxabd); - argi(m, 6, "Ac0", m0.Ac, gfxd_Acmuxc); - argi(m, 7, "Ad0", m0.Ad, gfxd_Acmuxabd); - argi(m, 8, "a1", m1.a, gfxd_Ccmuxa); - argi(m, 9, "b1", m1.b, gfxd_Ccmuxb); - argi(m, 10, "c1", m1.c, gfxd_Ccmuxc); - argi(m, 11, "d1", m1.d, gfxd_Ccmuxd); - argi(m, 12, "Aa1", m1.Aa, gfxd_Acmuxabd); - argi(m, 13, "Ab1", m1.Ab, gfxd_Acmuxabd); - argi(m, 14, "Ac1", m1.Ac, gfxd_Acmuxc); - argi(m, 15, "Ad1", m1.Ad, gfxd_Acmuxabd); - return 0; - } -} - -UCFUNC int d_DPSetConvert(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_DPSetConvert; - argi(m, 0, "k0", sx(getfield(hi, 9, 13), 9), gfxd_Cv); - argi(m, 1, "k1", sx(getfield(hi, 9, 4), 9), gfxd_Cv); - argi(m, 2, "k2", sx((getfield(hi, 4, 0) << 5) | getfield(lo, 5, 27), 9), - gfxd_Cv); - argi(m, 3, "k3", sx(getfield(lo, 9, 18), 9), gfxd_Cv); - argi(m, 4, "k4", sx(getfield(lo, 9, 9), 9), gfxd_Cv); - argi(m, 5, "k5", sx(getfield(lo, 9, 0), 9), gfxd_Cv); - return 0; -} - -UCFUNC int d_DPSetTextureConvert(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_DPSetTextureConvert; - argu(m, 0, "mode", lo, gfxd_Tc); - return 0; -} - -UCFUNC int d_DPSetCycleType(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_DPSetCycleType; - argu(m, 0, "mode", lo, gfxd_Cyc); - return 0; -} - -UCFUNC int d_DPSetDepthSource(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_DPSetDepthSource; - argu(m, 0, "mode", lo, gfxd_Zs); - return 0; -} - -UCFUNC int d_DPSetCombineKey(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_DPSetCombineKey; - argu(m, 0, "mode", lo, gfxd_Ck); - return 0; -} - -UCFUNC int d_DPSetKeyGB(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_DPSetKeyGB; - argu(m, 0, "cG", getfield(lo, 8, 24), gfxd_Color); - argu(m, 1, "sG", getfield(lo, 8, 16), gfxd_Keyscale); - argi(m, 2, "wG", sx(getfield(hi, 12, 12), 12), gfxd_Keywidth); - argu(m, 3, "cB", getfield(lo, 8, 8), gfxd_Color); - argu(m, 4, "sB", getfield(lo, 8, 0), gfxd_Keyscale); - argi(m, 5, "wB", sx(getfield(hi, 12, 0), 12), gfxd_Keywidth); - return 0; -} - -UCFUNC int d_DPSetKeyR(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_DPSetKeyR; - argu(m, 0, "cR", getfield(lo, 8, 8), gfxd_Color); - argu(m, 1, "sR", getfield(lo, 8, 0), gfxd_Keyscale); - argi(m, 2, "wR", sx(getfield(lo, 12, 16), 12), gfxd_Keywidth); - return 0; -} - -UCFUNC int d_DPSetPrimDepth(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_DPSetPrimDepth; - argi(m, 0, "z", sx(getfield(lo, 16, 16), 16), gfxd_Zi); - argi(m, 1, "dz", sx(getfield(lo, 16, 0), 16), gfxd_Zi); - return 0; -} - -UCFUNC int d_DPSetRenderMode(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_DPSetRenderMode; - argu(m, 0, "mode1", lo, gfxd_Rm1); - argu(m, 1, "mode2", lo, gfxd_Rm2); - return 0; -} - -UCFUNC int d_DPSetScissor(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_DPSetScissor; - argi(m, 0, "mode", getfield(lo, 2, 24), gfxd_Sc); - argu(m, 1, "ulx", getfield(hi, 10, 14), gfxd_Coordi); - argu(m, 2, "uly", getfield(hi, 10, 2), gfxd_Coordi); - argu(m, 3, "lrx", getfield(lo, 10, 14), gfxd_Coordi); - argu(m, 4, "lry", getfield(lo, 10, 2), gfxd_Coordi); - return 0; -} - -UCFUNC int d_DPSetScissorFrac(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - qu102_t ulx = getfield(hi, 12, 12); - qu102_t uly = getfield(hi, 12, 0); - qu102_t lrx = getfield(lo, 12, 12); - qu102_t lry = getfield(lo, 12, 0); - if ((ulx & 3) || (uly & 3) || (lrx & 3) || (lry & 3)) - { - m->id = gfxd_DPSetScissorFrac; - argi(m, 0, "mode", getfield(lo, 2, 24), gfxd_Sc); - argu(m, 1, "ulx", ulx, gfxd_Coordq); - argu(m, 2, "uly", uly, gfxd_Coordq); - argu(m, 3, "lrx", lrx, gfxd_Coordq); - argu(m, 4, "lry", lry, gfxd_Coordq); - return 0; - } - else - return d_DPSetScissor(m, hi, lo); -} - -UCFUNC int d_DPSetTextureDetail(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_DPSetTextureDetail; - argu(m, 0, "mode", lo, gfxd_Td); - return 0; -} - -UCFUNC int d_DPSetTextureFilter(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_DPSetTextureFilter; - argu(m, 0, "mode", lo, gfxd_Tf); - return 0; -} - -UCFUNC int d_DPSetTextureLOD(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_DPSetTextureLOD; - argu(m, 0, "mode", lo, gfxd_Tl); - return 0; -} - -UCFUNC int d_DPSetTextureLUT(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_DPSetTextureLUT; - argu(m, 0, "mode", lo, gfxd_Tt); - return 0; -} - -UCFUNC int d_DPSetTexturePersp(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_DPSetTexturePersp; - argu(m, 0, "mode", lo, gfxd_Tp); - return 0; -} - -UCFUNC int d_DPSetTile(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_DPSetTile; - argi(m, 0, "fmt", getfield(hi, 3, 21), gfxd_Fmt); - argi(m, 1, "siz", getfield(hi, 2, 19), gfxd_Siz); - argi(m, 2, "line", getfield(hi, 9, 9), gfxd_Line); - argu(m, 3, "tmem", getfield(hi, 9, 0), gfxd_Tmem); - argi(m, 4, "tile", getfield(lo, 3, 24), gfxd_Tile); - argi(m, 5, "pal", getfield(lo, 4, 20), gfxd_Pal); - argu(m, 6, "cmt", getfield(lo, 2, 18), gfxd_Cm); - argi(m, 7, "maskt", getfield(lo, 4, 14), gfxd_Tm); - argi(m, 8, "shiftt", getfield(lo, 4, 10), gfxd_Ts); - argu(m, 9, "cms", getfield(lo, 2, 8), gfxd_Cm); - argi(m, 10, "masks", getfield(lo, 4, 4), gfxd_Tm); - argi(m, 11, "shifts", getfield(lo, 4, 0), gfxd_Ts); - return 0; -} - -UCFUNC int d_DPSetTileSize(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_DPSetTileSize; - argi(m, 0, "tile", getfield(lo, 3, 24), gfxd_Tile); - argu(m, 1, "uls", getfield(hi, 12, 12), gfxd_Coordq); - argu(m, 2, "ult", getfield(hi, 12, 0), gfxd_Coordq); - argu(m, 3, "lrs", getfield(lo, 12, 12), gfxd_Coordq); - argu(m, 4, "lrt", getfield(lo, 12, 0), gfxd_Coordq); - return 0; -} - -#if defined(F3D_GBI) -UCFUNC int d_SP1Triangle(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_SP1Triangle; - int n0 = getfield(lo, 8, 16); - int n1 = getfield(lo, 8, 8); - int n2 = getfield(lo, 8, 0); - argi(m, 0, "v0", n0 / 10, gfxd_Vtx); - argi(m, 1, "v1", n1 / 10, gfxd_Vtx); - argi(m, 2, "v2", n2 / 10, gfxd_Vtx); - argi(m, 3, "flag", getfield(lo, 8, 24), gfxd_Vtxflag); - int ret = 0; - if (n0 % 10 != 0) - { - badarg(m, 0); - ret = -1; - } - if (n1 % 10 != 0) - { - badarg(m, 1); - ret = -1; - } - if (n2 % 10 != 0) - { - badarg(m, 2); - ret = -1; - } - return ret; -} -#elif defined(F3DEX_GBI) -UCFUNC int d_SP1Triangle(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_SP1Triangle; - int n0 = getfield(lo, 8, 16); - int n1 = getfield(lo, 8, 8); - int n2 = getfield(lo, 8, 0); - argi(m, 0, "v0", n0 / 2, gfxd_Vtx); - argi(m, 1, "v1", n1 / 2, gfxd_Vtx); - argi(m, 2, "v2", n2 / 2, gfxd_Vtx); - argi(m, 3, "flag", 0, gfxd_Vtxflag); - int ret = 0; - if (n0 % 2 != 0) - { - badarg(m, 0); - ret = -1; - } - if (n1 % 2 != 0) - { - badarg(m, 1); - ret = -1; - } - if (n2 % 2 != 0) - { - badarg(m, 2); - ret = -1; - } - return ret; -} -#elif defined(F3DEX_GBI_2) -UCFUNC int d_SP1Triangle(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_SP1Triangle; - int n0 = getfield(hi, 8, 16); - int n1 = getfield(hi, 8, 8); - int n2 = getfield(hi, 8, 0); - argi(m, 0, "v0", n0 / 2, gfxd_Vtx); - argi(m, 1, "v1", n1 / 2, gfxd_Vtx); - argi(m, 2, "v2", n2 / 2, gfxd_Vtx); - argi(m, 3, "flag", 0, gfxd_Vtxflag); - int ret = 0; - if (n0 % 2 != 0) - { - badarg(m, 0); - ret = -1; - } - if (n1 % 2 != 0) - { - badarg(m, 1); - ret = -1; - } - if (n2 % 2 != 0) - { - badarg(m, 2); - ret = -1; - } - return ret; -} -#endif - -#if defined(F3DEX_GBI) || defined(F3DEX_GBI_2) -UCFUNC int d_SP1Quadrangle(gfxd_macro_t *m, uint32_t hi, uint32_t lo); -UCFUNC int d_SP2Triangles(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - int n00 = getfield(hi, 8, 16); - int n01 = getfield(hi, 8, 8); - int n02 = getfield(hi, 8, 0); - int n10 = getfield(lo, 8, 16); - int n11 = getfield(lo, 8, 8); - int n12 = getfield(lo, 8, 0); -#if defined(F3DEX_GBI) - if (n00 == n10 && n02 == n11) - return d_SP1Quadrangle(m, hi, lo); -#endif - m->id = gfxd_SP2Triangles; - argi(m, 0, "v00", n00 / 2, gfxd_Vtx); - argi(m, 1, "v01", n01 / 2, gfxd_Vtx); - argi(m, 2, "v02", n02 / 2, gfxd_Vtx); - argi(m, 3, "flag0", 0, gfxd_Vtxflag); - argi(m, 4, "v10", n10 / 2, gfxd_Vtx); - argi(m, 5, "v11", n11 / 2, gfxd_Vtx); - argi(m, 6, "v12", n12 / 2, gfxd_Vtx); - argi(m, 7, "flag1", 0, gfxd_Vtxflag); - int ret = 0; - if (n00 % 2 != 0) - { - badarg(m, 0); - ret = -1; - } - if (n01 % 2 != 0) - { - badarg(m, 1); - ret = -1; - } - if (n02 % 2 != 0) - { - badarg(m, 2); - ret = -1; - } - if (n10 % 2 != 0) - { - badarg(m, 4); - ret = -1; - } - if (n11 % 2 != 0) - { - badarg(m, 5); - ret = -1; - } - if (n12 % 2 != 0) - { - badarg(m, 6); - ret = -1; - } - return ret; -} - -UCFUNC int d_SP1Quadrangle(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_SP1Quadrangle; - int n00 = getfield(hi, 8, 16); - int n01 = getfield(hi, 8, 8); - int n02 = getfield(hi, 8, 0); - int n10 = getfield(lo, 8, 16); - int n11 = getfield(lo, 8, 8); - int n12 = getfield(lo, 8, 0); - int v00 = n00 / 2; - int v01 = n01 / 2; - int v02 = n02 / 2; - int v10 = n10 / 2; - int v11 = n11 / 2; - int v12 = n12 / 2; - argi(m, 0, "v0", v00, gfxd_Vtx); - argi(m, 1, "v1", v01, gfxd_Vtx); - argi(m, 2, "v2", v11, gfxd_Vtx); - argi(m, 3, "v3", v12, gfxd_Vtx); - argi(m, 4, "flag", 0, gfxd_Vtxflag); - int ret = 0; - if (v00 != v10 || n00 % 2 != 0 || n10 % 2 != 0) - { - badarg(m, 0); - ret = -1; - } - if (n01 % 2 != 0) - { - badarg(m, 1); - ret = -1; - } - if (v02 != v11 || n02 % 2 != 0 || n11 % 2 != 0) - { - badarg(m, 2); - ret = -1; - } - if (n12 % 2 != 0) - { - badarg(m, 3); - ret = -1; - } - return ret; -} - -UCFUNC int c_SPBranchLessZraw(gfxd_macro_t *m, int n_macro) -{ - if (n_macro < 2) - return -1; - if (m[0].id != gfxd_DPHalf1) - return -1; - uint32_t branchdl = argvu(&m[0], 0); - if (m[1].id != gfxd_BranchZ) - return -1; - int32_t vtx = argvi(&m[1], 0); - int32_t zval = argvi(&m[1], 1); - m->id = gfxd_SPBranchLessZraw; - argu(m, 0, "dl", branchdl, gfxd_Dl); - argi(m, 1, "vtx", vtx, gfxd_Vtx); - argi(m, 2, "zval", zval, gfxd_Zraw); - return 0; -} -#endif - -UCFUNC int d_SPBranchList(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_SPBranchList; - argu(m, 0, "dl", lo, gfxd_Dl); - return 0; -} - -UCFUNC int c_SPClipRatio(gfxd_macro_t *m, int n_macro) -{ - if (n_macro < 4) - return -1; - if (m[0].id != gfxd_MoveWd - || argvi(&m[0], 0) != G_MW_CLIP - || argvu(&m[0], 1) != G_MWO_CLIP_RNX) - { - return -1; - } - uint32_t r = argvu(&m[0], 2); - if (m[1].id != gfxd_MoveWd - || argvi(&m[1], 0) != G_MW_CLIP - || argvu(&m[1], 1) != G_MWO_CLIP_RNY - || argvu(&m[1], 2) != r) - { - return -1; - } - if (m[2].id != gfxd_MoveWd - || argvi(&m[2], 0) != G_MW_CLIP - || argvu(&m[2], 1) != G_MWO_CLIP_RPX - || ((uint32_t)1 << 16) - argvu(&m[2], 2) != r) - { - return -1; - } - if (m[3].id != gfxd_MoveWd - || argvi(&m[3], 0) != G_MW_CLIP - || argvu(&m[3], 1) != G_MWO_CLIP_RPY - || ((uint32_t)1 << 16) - argvu(&m[3], 2) != r) - { - return -1; - } - m->id = gfxd_SPClipRatio; - argi(m, 0, "r", r, gfxd_Cr); - return 0; -} - -#if defined(F3D_GBI) -UCFUNC int d_SPCullDisplayList(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_SPCullDisplayList; - int n0 = getfield(hi, 24, 0); - int nn = getfield(lo, 16, 0); - argi(m, 0, "v0", n0 / 40, gfxd_Vtx); - argi(m, 1, "vn", nn / 40 - 1, gfxd_Num); - int ret = 0; - if (n0 % 40 != 0) - { - badarg(m, 0); - ret = -1; - } - if (nn % 40 != 0) - { - badarg(m, 1); - ret = -1; - } - return ret; -} -#elif defined(F3DEX_GBI) || defined(F3DEX_GBI_2) -UCFUNC int d_SPCullDisplayList(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_SPCullDisplayList; - int n0 = getfield(hi, 16, 0); - int nn = getfield(lo, 16, 0); - argi(m, 0, "v0", n0 / 2, gfxd_Vtx); - argi(m, 1, "vn", nn / 2, gfxd_Num); - int ret = 0; - if (n0 % 2 != 0) - { - badarg(m, 0); - ret = -1; - } - if (nn % 2 != 0) - { - badarg(m, 1); - ret = -1; - } - return ret; -} -#endif - -UCFUNC int d_SPDisplayList(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_SPDisplayList; - argu(m, 0, "dl", lo, gfxd_Dl); - return 0; -} - -UCFUNC int d_SPEndDisplayList(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_SPEndDisplayList; - return 0; -} - -UCFUNC int d_SPFogFactor(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_SPFogFactor; - argi(m, 0, "fm", sx(getfield(lo, 16, 16), 16), gfxd_Fogz); - argi(m, 1, "fo", sx(getfield(lo, 16, 0), 16), gfxd_Fogz); - return 0; -} - -UCFUNC int d_SPFogPosition(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - int x = sx(getfield(lo, 16, 16), 16); - int y = sx(getfield(lo, 16, 0), 16); - if (x == 0) - return d_SPFogFactor(m, hi, lo); - else - { - int d = 128000 / x; - int yd = y * d; - if (yd > 0) - yd += 255; - else if (yd < 0) - yd -= 255; - int min = 500 - yd / 256; - int max = d + min; - - if (min >= 0 && min <= 1000 && max >= 0 && max <= 1000) - { - m->id = gfxd_SPFogPosition; - argi(m, 0, "min", min, gfxd_Fogp); - argi(m, 1, "max", max, gfxd_Fogp); - return 0; - } - else - return d_SPFogFactor(m, hi, lo); - } -} - -#if defined(F3D_GBI) || defined(F3DEX_GBI) -UCFUNC int c_SPForceMatrix(gfxd_macro_t *m, int n_macro) -{ - if (n_macro < 4) - return -1; - for (int i = 0; i < 4; i++) - if (m[i].id != gfxd_MoveMem - || argvu(&m[i], 0) != 16 - || argvu(&m[i], 2) != argvu(&m[0], 2) + i * 16) - { - return -1; - } - if (argvi(&m[0], 1) != G_MV_MATRIX_1 - || argvi(&m[1], 1) != G_MV_MATRIX_2 - || argvi(&m[2], 1) != G_MV_MATRIX_3 - || argvi(&m[3], 1) != G_MV_MATRIX_4) - { - return -1; - } - uint32_t mptr = argvu(&m[0], 2); - m->id = gfxd_SPForceMatrix; - argu(m, 0, "mptr", mptr, gfxd_Mtxptr); - return 0; -} -#elif defined(F3DEX_GBI_2) -UCFUNC int c_SPForceMatrix(gfxd_macro_t *m, int n_macro) -{ - if (n_macro < 2) - return -1; - if (m[0].id != gfxd_MoveMem - || argvu(&m[0], 0) != sizeof(Mtx) - || argvi(&m[0], 1) != G_MV_MATRIX - || argvu(&m[0], 2) != 0) - { - return -1; - } - uint32_t mptr = argvu(&m[0], 3); - if (m[1].id != gfxd_MoveWd - || argvi(&m[1], 0) != G_MW_FORCEMTX - || argvu(&m[1], 1) != 0 - || argvu(&m[1], 2) != 0x10000) - { - return -1; - } - m->id = gfxd_SPForceMatrix; - argu(m, 0, "mptr", mptr, gfxd_Mtxptr); - return 0; -} -#endif - -UCFUNC int d_SPSetGeometryMode(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_SPSetGeometryMode; - argu(m, 0, "mode", lo, gfxd_Gm); - return 0; -} - -UCFUNC int d_SPClearGeometryMode(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_SPClearGeometryMode; -#if defined(F3D_GBI) || defined(F3DEX_GBI) - argu(m, 0, "mode", lo, gfxd_Gm); -#elif defined(F3DEX_GBI_2) - argu(m, 0, "mode", getfield(~hi, 24, 0), gfxd_Gm); -#endif - return 0; -} - -#if defined(F3D_GBI) || defined(F3DEX_GBI) -UCFUNC int c_SPLoadGeometryMode(gfxd_macro_t *m, int n_macro) -{ - if (n_macro < 2) - return -1; - if (m[0].id != gfxd_SPClearGeometryMode - || argvu(&m[0], 0) != 0xFFFFFFFF - || m[1].id != gfxd_SPSetGeometryMode) - { - return -1; - } - uint32_t mode = argvu(&m[1], 0); - m->id = gfxd_SPLoadGeometryMode; - argu(m, 0, "mode", mode, gfxd_Gm); - return 0; -} -#elif defined(F3DEX_GBI_2) -UCFUNC int d_SPLoadGeometryMode(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_SPLoadGeometryMode; - argu(m, 0, "mode", lo, gfxd_Gm); - return 0; -} -#endif - -#if defined(F3D_GBI) || defined(F3DEX_GBI) -UCFUNC int d_SPInsertMatrix(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_SPInsertMatrix; - argu(m, 0, "where", getfield(hi, 16, 8), gfxd_Mwo_matrix); - argu(m, 1, "val", lo, gfxd_Word); - return 0; -} -#endif - -#if defined(F3D_GBI) -UCFUNC int d_SPLine3D(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_SPLine3D; - int n0 = getfield(lo, 8, 16); - int n1 = getfield(lo, 8, 8); - argi(m, 0, "v0", n0 / 10, gfxd_Vtx); - argi(m, 1, "v1", n1 / 10, gfxd_Vtx); - argi(m, 2, "flag", getfield(lo, 8, 24), gfxd_Vtxflag); - int ret = 0; - if (n0 % 10 != 0) - { - badarg(m, 0); - ret = -1; - } - if (n1 % 10 != 0) - { - badarg(m, 1); - ret = -1; - } - return ret; -} -#elif defined(F3DEX_GBI) -UCFUNC int d_SPLine3D(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_SPLine3D; - int n0 = getfield(lo, 8, 16); - int n1 = getfield(lo, 8, 8); - argi(m, 0, "v0", n0 / 2, gfxd_Vtx); - argi(m, 1, "v1", n1 / 2, gfxd_Vtx); - argi(m, 2, "flag", 0, gfxd_Vtxflag); - int ret = 0; - if (n0 % 2 != 0) - { - badarg(m, 0); - ret = -1; - } - if (n1 % 2 != 0) - { - badarg(m, 1); - ret = -1; - } - return ret; -} -#elif defined(F3DEX_GBI_2) -UCFUNC int d_SPLine3D(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_SPLine3D; - int n0 = getfield(hi, 8, 16); - int n1 = getfield(hi, 8, 8); - argi(m, 0, "v0", n0 / 2, gfxd_Vtx); - argi(m, 1, "v1", n1 / 2, gfxd_Vtx); - argi(m, 2, "flag", 0, gfxd_Vtxflag); - int ret = 0; - if (n0 % 2 != 0) - { - badarg(m, 0); - ret = -1; - } - if (n1 % 2 != 0) - { - badarg(m, 1); - ret = -1; - } - return ret; -} -#endif - -#if defined(F3D_GBI) -UCFUNC int d_SPLineW3D(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - int wd = getfield(lo, 8, 0); - if (wd == 0) - return d_SPLine3D(m, hi, lo); - else - { - m->id = gfxd_SPLineW3D; - int n0 = getfield(lo, 8, 16); - int n1 = getfield(lo, 8, 8); - argi(m, 0, "v0", n0 / 10, gfxd_Vtx); - argi(m, 1, "v1", n1 / 10, gfxd_Vtx); - argi(m, 2, "wd", wd, gfxd_Linewd); - argi(m, 3, "flag", getfield(lo, 8, 24), gfxd_Vtxflag); - int ret = 0; - if (n0 % 10 != 0) - { - badarg(m, 0); - ret = -1; - } - if (n1 % 10 != 0) - { - badarg(m, 1); - ret = -1; - } - return ret; - } -} -#elif defined(F3DEX_GBI) || defined(F3DEX_GBI_2) -UCFUNC int d_SPLineW3D(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - int wd = getfield(hi, 8, 0); - if (wd == 0) - return d_SPLine3D(m, hi, lo); - else - { - m->id = gfxd_SPLineW3D; - int n0 = getfield(hi, 8, 16); - int n1 = getfield(hi, 8, 8); - argi(m, 0, "v0", n0 / 2, gfxd_Vtx); - argi(m, 1, "v1", n1 / 2, gfxd_Vtx); - argi(m, 2, "wd", wd, gfxd_Linewd); - argi(m, 3, "flag", 0, gfxd_Vtxflag); - int ret = 0; - if (n0 % 2 != 0) - { - badarg(m, 0); - ret = -1; - } - if (n1 % 2 != 0) - { - badarg(m, 1); - ret = -1; - } - return ret; - } -} -#endif - -#if defined(F3DEX_GBI) || defined(F3DEX_GBI_2) -UCFUNC int c_SPLoadUcode(gfxd_macro_t *m, int n_macro) -{ - if (n_macro < 2) - return -1; - if (m[0].id != gfxd_DPHalf1) - return -1; - uint32_t uc_dstart = argvu(&m[0], 0); - if (m[1].id != gfxd_LoadUcode) - return -1; - uint32_t uc_start = argvu(&m[1], 0); - uint32_t uc_dsize = argvu(&m[1], 1); - if (uc_dsize != 0x800) - return -1; - m->id = gfxd_SPLoadUcode; - argu(m, 0, "uc_start", uc_start, gfxd_Uctext); - argu(m, 1, "uc_dstart", uc_dstart, gfxd_Ucdata); - return 0; -} -#endif - -UCFUNC int d_SPLookAtX(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_SPLookAtX; - argu(m, 0, "l", lo, gfxd_Lookatptr); - return 0; -} - -UCFUNC int d_SPLookAtY(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_SPLookAtY; - argu(m, 0, "l", lo, gfxd_Lookatptr); - return 0; -} - -UCFUNC int c_SPLookAt(gfxd_macro_t *m, int n_macro) -{ - if (n_macro < 2) - return -1; - if (m[0].id != gfxd_SPLookAtX) - return -1; - uint32_t l = argvu(&m[0], 0); - if (m[1].id != gfxd_SPLookAtY || argvu(&m[1], 0) != l + 0x10) - return -1; - m->id = gfxd_SPLookAt; - argu(m, 0, "l", l, gfxd_Lookatptr); - return 0; -} - -#if defined(F3D_GBI) || defined(F3DEX_GBI) -UCFUNC int d_SPMatrix(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_SPMatrix; - int x = getfield(hi, 16, 0); - argu(m, 0, "matrix", lo, gfxd_Mtxptr); - argi(m, 1, "param", getfield(hi, 8, 16), gfxd_Mtxparam); - if (x != sizeof(Mtx)) - return -1; - else - return 0; -} -#elif defined(F3DEX_GBI_2) -UCFUNC int d_SPMatrix(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_SPMatrix; - int x = getfield(hi, 5, 19); - argu(m, 0, "matrix", lo, gfxd_Mtxptr); - argi(m, 1, "param", getfield(hi, 8, 0) ^ G_MTX_PUSH, gfxd_Mtxparam); - if (x != (sizeof(Mtx) - 1) / 8) - return -1; - else - return 0; -} -#endif - -#if defined(F3D_GBI) || (defined(F3D_BETA) && defined(F3DEX_GBI)) -UCFUNC int d_SPModifyVertex(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_SPModifyVertex; - int offset = getfield(hi, 16, 8); - argi(m, 0, "vtx", offset / 40, gfxd_Vtx); - argu(m, 1, "where", offset % 40, gfxd_Mwo_point); - argu(m, 2, "val", lo, gfxd_Word); - return 0; -} -#elif defined(F3DEX_GBI) || defined(F3DEX_GBI_2) -UCFUNC int d_SPModifyVertex(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_SPModifyVertex; - int vtx = getfield(hi, 16, 0); - argi(m, 0, "vtx", vtx / 2, gfxd_Vtx); - argu(m, 1, "where", getfield(hi, 8, 16), gfxd_Mwo_point); - argu(m, 2, "val", lo, gfxd_Word); - int ret = 0; - if (vtx % 2 != 0) - { - badarg(m, 0); - ret = -1; - } - return ret; -} -#endif - -UCFUNC int d_SPPerspNormalize(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_SPPerspNormalize; - argu(m, 0, "scale", getfield(lo, 16, 0), gfxd_Wscale); - return 0; -} - -UCFUNC int d_SPPopMatrix(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_SPPopMatrix; -#if defined(F3D_GBI) || defined(F3DEX_GBI) - argi(m, 0, "param", lo, gfxd_Mtxstack); -#elif defined(F3DEX_GBI_2) - argi(m, 0, "param", G_MTX_MODELVIEW, gfxd_Mtxstack); -#endif - return 0; -} - -#if defined(F3DEX_GBI_2) -UCFUNC int d_SPPopMatrixN(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - int len = (getfield(hi, 5, 19) + 1) * 8; - int ofs = getfield(hi, 8, 8) * 8; - int idx = getfield(hi, 8, 0); - int n = lo / sizeof(Mtx); - if (lo % sizeof(Mtx) == 0 - && len == sizeof(Mtx) - && ofs == 0 - && idx == 2 - && n == 1) - { - return d_SPPopMatrix(m, hi, lo); - } - m->id = gfxd_SPPopMatrixN; - argi(m, 0, "param", G_MTX_MODELVIEW, gfxd_Mtxstack); - argi(m, 1, "num", n, gfxd_Num); - int ret = 0; - if (lo % sizeof(Mtx) != 0) - { - badarg(m, 1); - ret = -1; - } - if (len != sizeof(Mtx) || ofs != 0 || idx != 2) - ret = -1; - return ret; -} -#endif - -UCFUNC int d_SPSegment(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_SPSegment; -#if defined(F3D_GBI) || defined(F3DEX_GBI) - int offset = getfield(hi, 16, 8); -#elif defined(F3DEX_GBI_2) - int offset = getfield(hi, 16, 0); -#endif - argu(m, 0, "seg", offset / 4, gfxd_Seg); - argu(m, 1, "base", lo, gfxd_Segptr); - int ret = 0; - if (offset % 4 != 0) - { - badarg(m, 0); - ret = -1; - } - return ret; -} - -UCFUNC int c_SPSetLightsN(gfxd_macro_t *m, int n_macro, int id, int numlights) -{ - if (n_macro < 2 + numlights) - return -1; - if (m[0].id != gfxd_SPNumLights || argvi(&m[0], 0) != numlights) - return -1; - int a = 1 + numlights; - if (m[a].id != gfxd_SPLight || argvi(&m[a], 1) != a) - return -1; - uint32_t l = argvu(&m[a], 0); - for (int i = 1; i <= numlights; i++) - { - int offset = sizeof(Ambient) + sizeof(Light) * (i - 1); - if (m[i].id != gfxd_SPLight - || argvu(&m[i], 0) != l + offset - || argvi(&m[i], 1) != i) - { - return -1; - } - } - m->id = id; - argu(m, 0, "l", l, gfxd_Lightsn); - return 0; -} - -UCFUNC int c_SPSetLights1(gfxd_macro_t *m, int n_macro) -{ - return c_SPSetLightsN(m, n_macro, gfxd_SPSetLights1, NUMLIGHTS_1); -} - -UCFUNC int c_SPSetLights2(gfxd_macro_t *m, int n_macro) -{ - return c_SPSetLightsN(m, n_macro, gfxd_SPSetLights2, NUMLIGHTS_2); -} - -UCFUNC int c_SPSetLights3(gfxd_macro_t *m, int n_macro) -{ - return c_SPSetLightsN(m, n_macro, gfxd_SPSetLights3, NUMLIGHTS_3); -} - -UCFUNC int c_SPSetLights4(gfxd_macro_t *m, int n_macro) -{ - return c_SPSetLightsN(m, n_macro, gfxd_SPSetLights4, NUMLIGHTS_4); -} - -UCFUNC int c_SPSetLights5(gfxd_macro_t *m, int n_macro) -{ - return c_SPSetLightsN(m, n_macro, gfxd_SPSetLights5, NUMLIGHTS_5); -} - -UCFUNC int c_SPSetLights6(gfxd_macro_t *m, int n_macro) -{ - return c_SPSetLightsN(m, n_macro, gfxd_SPSetLights6, NUMLIGHTS_6); -} - -UCFUNC int c_SPSetLights7(gfxd_macro_t *m, int n_macro) -{ - return c_SPSetLightsN(m, n_macro, gfxd_SPSetLights7, NUMLIGHTS_7); -} - -#if defined(F3D_GBI) || defined(F3DEX_GBI) -UCFUNC int d_SPNumLights(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_SPNumLights; - argi(m, 0, "n", (lo - 0x80000000) / 32 - 1, gfxd_Numlights); - int ret = 0; - if (lo < 0x80000040 || lo % 32 != 0) - { - badarg(m, 0); - ret = -1; - } - return ret; -} -#elif defined(F3DEX_GBI_2) -UCFUNC int d_SPNumLights(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_SPNumLights; - argi(m, 0, "n", lo / 24, gfxd_Numlights); - int ret = 0; - if (lo < 24 || lo % 24 != 0) - { - badarg(m, 0); - ret = -1; - } - return ret; -} -#endif - -#if defined(F3D_GBI) || defined(F3DEX_GBI) -UCFUNC int d_SPLight(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - int n = (getfield(hi, 8, 16) - G_MV_L0) / 2 + 1; - m->id = gfxd_SPLight; - argu(m, 0, "l", lo, gfxd_Lightptr); - argi(m, 1, "n", n, gfxd_Num); - return 0; -} -#elif defined(F3DEX_GBI_2) -UCFUNC int d_SPLight(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - int n = (getfield(hi, 8, 8) * 8 / 24) - 1; - m->id = gfxd_SPLight; - argu(m, 0, "l", lo, gfxd_Lightptr); - argi(m, 1, "n", n, gfxd_Num); - return 0; -} -#endif - -UCFUNC int c_SPLightColor(gfxd_macro_t *m, int n_macro) -{ - if (n_macro < 2) - return -1; - if (m[0].id != gfxd_MoveWd - || argvi(&m[0], 0) != G_MW_LIGHTCOL - || argvu(&m[0], 1) % 0x18 != 0 - || argvu(&m[0], 1) > G_MWO_aLIGHT_8) - { - return -1; - } - uint32_t offset = argvu(&m[0], 1); - uint32_t packedcolor = argvu(&m[0], 2); - if (m[1].id != gfxd_MoveWd - || argvi(&m[1], 0) != G_MW_LIGHTCOL - || argvu(&m[1], 1) != offset + 4 - || argvu(&m[1], 2) != packedcolor) - { - return -1; - } - m->id = gfxd_SPLightColor; - argi(m, 0, "n", offset / 0x18 + 1, gfxd_Lightnum); - argu(m, 1, "c", packedcolor, gfxd_Color); - return 0; -} - -UCFUNC int d_SPTexture(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_SPTexture; - argu(m, 0, "sc", getfield(lo, 16, 16), gfxd_Tcscale); - argu(m, 1, "tc", getfield(lo, 16, 0), gfxd_Tcscale); - argi(m, 2, "level", getfield(hi, 3, 11), gfxd_Num); - argi(m, 3, "tile", getfield(hi, 3, 8), gfxd_Tile); -#if defined(F3D_GBI) || defined(F3DEX_GBI) - argi(m, 4, "on", getfield(hi, 8, 0), gfxd_Switch); -#elif defined(F3DEX_GBI_2) - argi(m, 4, "on", getfield(hi, 7, 1), gfxd_Switch); -#endif - return 0; -} - -UCFUNC int c_SPTextureRectangle(gfxd_macro_t *m, int n_macro) -{ - if (n_macro < 3) - return -1; - if (m[0].id != gfxd_TexRect) - return -1; - qu102_t ulx = argvu(&m[0], 0); - qu102_t uly = argvu(&m[0], 1); - qu102_t lrx = argvu(&m[0], 2); - qu102_t lry = argvu(&m[0], 3); - int tile = argvi(&m[0], 4); - if (m[1].id != gfxd_DPHalf1) - return -1; - qs105_t s = sx(getfield(argvu(&m[1], 0), 16, 16), 16); - qs105_t t = sx(getfield(argvu(&m[1], 0), 16, 0), 16); - if (m[2].id != gfxd_DPHalf2) - return -1; - qs510_t dsdx = sx(getfield(argvu(&m[2], 0), 16, 16), 16); - qs510_t dtdy = sx(getfield(argvu(&m[2], 0), 16, 0), 16); - m->id = gfxd_SPTextureRectangle; - argu(m, 0, "ulx", ulx, gfxd_Coordq); - argu(m, 1, "uly", uly, gfxd_Coordq); - argu(m, 2, "lrx", lrx, gfxd_Coordq); - argu(m, 3, "lry", lry, gfxd_Coordq); - argi(m, 4, "tile", tile, gfxd_Tile); - argi(m, 5, "s", s, gfxd_St); - argi(m, 6, "t", t, gfxd_St); - argi(m, 7, "dsdx", dsdx, gfxd_Stdelta); - argi(m, 8, "dtdy", dtdy, gfxd_Stdelta); - return 0; -} - -UCFUNC int c_SPTextureRectangleFlip(gfxd_macro_t *m, int n_macro) -{ - if (n_macro < 3) - return -1; - if (m[0].id != gfxd_TexRectFlip) - return -1; - qu102_t ulx = argvu(&m[0], 0); - qu102_t uly = argvu(&m[0], 1); - qu102_t lrx = argvu(&m[0], 2); - qu102_t lry = argvu(&m[0], 3); - int tile = argvi(&m[0], 4); - if (m[1].id != gfxd_DPHalf1) - return -1; - qs105_t s = sx(getfield(argvu(&m[1], 0), 16, 16), 16); - qs105_t t = sx(getfield(argvu(&m[1], 0), 16, 0), 16); - if (m[2].id != gfxd_DPHalf2) - return -1; - qs510_t dsdx = sx(getfield(argvu(&m[2], 0), 16, 16), 16); - qs510_t dtdy = sx(getfield(argvu(&m[2], 0), 16, 0), 16); - m->id = gfxd_SPTextureRectangleFlip; - argu(m, 0, "ulx", ulx, gfxd_Coordq); - argu(m, 1, "uly", uly, gfxd_Coordq); - argu(m, 2, "lrx", lrx, gfxd_Coordq); - argu(m, 3, "lry", lry, gfxd_Coordq); - argi(m, 4, "tile", tile, gfxd_Tile); - argi(m, 5, "s", s, gfxd_St); - argi(m, 6, "t", t, gfxd_St); - argi(m, 7, "dsdx", dsdx, gfxd_Stdelta); - argi(m, 8, "dtdy", dtdy, gfxd_Stdelta); - return 0; -} - -#if defined(F3D_GBI) -UCFUNC int d_SPVertex(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_SPVertex; - int n = getfield(hi, 4, 20) + 1; - int v0 = getfield(hi, 4, 16); - int size = getfield(hi, 16, 0); - argu(m, 0, "v", lo, gfxd_Vtxptr); - argi(m, 1, "n", n, gfxd_Num); - argi(m, 2, "v0", v0, gfxd_Vtx); - int ret = 0; - if (size != sizeof(Vtx) * n) - { - badarg(m, 1); - ret = -1; - } - return ret; -} -#elif defined(F3DEX_GBI) -UCFUNC int d_SPVertex(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_SPVertex; - int n = getfield(hi, 6, 10); - int v0 = getfield(hi, 8, 16); - int size = getfield(hi, 10, 0); - argu(m, 0, "v", lo, gfxd_Vtxptr); - argi(m, 1, "n", n, gfxd_Num); - argi(m, 2, "v0", v0 / 2, gfxd_Vtx); - int ret = 0; - if (size != sizeof(Vtx) * n - 1) - { - badarg(m, 1); - ret = -1; - } - if (v0 % 2 != 0) - { - badarg(m, 2); - ret = -1; - } - return ret; -} -#elif defined(F3DEX_GBI_2) -UCFUNC int d_SPVertex(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_SPVertex; - int n = getfield(hi, 8, 12); - int v0 = getfield(hi, 7, 1) - n; - argu(m, 0, "v", lo, gfxd_Vtxptr); - argi(m, 1, "n", n, gfxd_Num); - argi(m, 2, "v0", v0, gfxd_Vtx); - return 0; -} -#endif - -UCFUNC int d_SPViewport(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_SPViewport; - argu(m, 0, "v", lo, gfxd_Vpptr); - return 0; -} - -UCFUNC int d_DPLoadTLUTCmd(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_DPLoadTLUTCmd; - argi(m, 0, "tile", getfield(lo, 3, 24), gfxd_Tile); - argi(m, 1, "count", getfield(lo, 10, 14), gfxd_Num); - return 0; -} - -UCFUNC int c_DPLoadTLUT(gfxd_macro_t *m, int n_macro) -{ - if (n_macro < 6) - return -1; - if (m[0].id != gfxd_DPSetTextureImage - || argvi(&m[0], 0) != G_IM_FMT_RGBA - || argvi(&m[0], 1) != G_IM_SIZ_16b - || argvi(&m[0], 2) != 1) - { - return -1; - } - uint32_t dram = argvu(&m[0], 3); - if (m[1].id != gfxd_DPTileSync) - return -1; - if (m[2].id != gfxd_DPSetTile - || argvi(&m[2], 0) != 0 - || argvi(&m[2], 1) != 0 - || argvi(&m[2], 2) != 0 - || argvi(&m[2], 4) != G_TX_LOADTILE - || argvi(&m[2], 5) != 0 - || argvu(&m[2], 6) != 0 - || argvi(&m[2], 7) != 0 - || argvi(&m[2], 8) != 0 - || argvu(&m[2], 9) != 0 - || argvi(&m[2], 10) != 0 - || argvi(&m[2], 11) != 0) - { - return -1; - } - uint32_t tmem = argvu(&m[2], 3); - if (m[3].id != gfxd_DPLoadSync) - return -1; - if (m[4].id != gfxd_DPLoadTLUTCmd || argvi(&m[4], 0) != G_TX_LOADTILE) - return -1; - int count = argvi(&m[4], 1) + 1; - if (m[5].id != gfxd_DPPipeSync) - return -1; - m->id = gfxd_DPLoadTLUT; - argi(m, 0, "count", count, gfxd_Num); - argu(m, 1, "tmem", tmem, gfxd_Tmem); - argu(m, 2, "dram", dram, gfxd_Tlut); - return 0; -} - -#if defined(F3DEX_GBI) || defined(F3DEX_GBI_2) -UCFUNC int d_BranchZ(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_BranchZ; - int na = getfield(hi, 12, 12); - int nb = getfield(hi, 12, 0); - int32_t zval; - if (lo > 0x7FFFFFFF) - zval = INT32_MIN + (int32_t)(lo & 0x7FFFFFFF); - else - zval = lo; - argi(m, 0, "vtx", nb / 2, gfxd_Vtx); - argi(m, 1, "zval", zval, gfxd_Zraw); - int ret = 0; - if (nb % 2 != 0 || na / 5 != nb / 2 || na % 5 != 0) - { - badarg(m, 0); - ret = -1; - } - return ret; -} -#endif - -UCFUNC int d_DisplayList(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - int flag = getfield(hi, 8, 16); - if (flag == 0) - return d_SPDisplayList(m, hi, lo); - else if (flag == 1) - return d_SPBranchList(m, hi, lo); - else - { - m->id = gfxd_DisplayList; - argu(m, 0, "dl", lo, gfxd_Dl); - argi(m, 1, "flag", flag, gfxd_Dlflag); - return 0; - } -} - -UCFUNC int d_DPHalf1(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_DPHalf1; - argu(m, 0, "hi", lo, gfxd_Word); - return 0; -} - -UCFUNC int d_DPHalf2(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_DPHalf2; - argu(m, 0, "lo", lo, gfxd_Word); - return 0; -} - -UCFUNC int c_DPWord(gfxd_macro_t *m, int n_macro) -{ - if (n_macro < 2) - return -1; - if (m[0].id != gfxd_DPHalf1 || m[1].id != gfxd_DPHalf2) - return -1; - uint32_t wordhi = argvu(&m[0], 0); - uint32_t wordlo = argvu(&m[1], 0); - m->id = gfxd_DPWord; - argu(m, 0, "wordhi", wordhi, gfxd_Word); - argu(m, 1, "wordlo", wordlo, gfxd_Word); - return 0; -} - -UCFUNC int d_DPLoadTile(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_DPLoadTile; - argi(m, 0, "tile", getfield(lo, 3, 24), gfxd_Tile); - argu(m, 1, "uls", getfield(hi, 12, 12), gfxd_Coordq); - argu(m, 2, "ult", getfield(hi, 12, 0), gfxd_Coordq); - argu(m, 3, "lrs", getfield(lo, 12, 12), gfxd_Coordq); - argu(m, 4, "lrt", getfield(lo, 12, 0), gfxd_Coordq); - return 0; -} - -#if defined(F3DEX_GBI_2) -UCFUNC int d_SPGeometryMode(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - uint32_t clearbits = getfield(~hi, 24, 0); - uint32_t setbits = lo; - if (clearbits == 0 && setbits != 0) - return d_SPSetGeometryMode(m, hi, lo); - else if (clearbits != 0 && setbits == 0) - return d_SPClearGeometryMode(m, hi, lo); - else if (clearbits == 0x00FFFFFF) - return d_SPLoadGeometryMode(m, hi, lo); - else - { - m->id = gfxd_SPGeometryMode; - argu(m, 0, "c", clearbits, gfxd_Gm); - argu(m, 1, "s", setbits, gfxd_Gm); - return 0; - } -} -#endif - -UCFUNC int d_SPSetOtherMode(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_SPSetOtherMode; - int opc = getfield(hi, 8, 24); -#if defined(F3D_GBI) || defined(F3DEX_GBI) - int length = getfield(hi, 8, 0); - int shift = getfield(hi, 8, 8); -#elif defined(F3DEX_GBI_2) - int length = getfield(hi, 8, 0) + 1; - int shift = 32 - (getfield(hi, 8, 8) + length); -#endif - argi(m, 0, "opc", opc, gfxd_Opcode); - argi(m, 1, "sft", shift, gfxd_Sftlo); - argi(m, 2, "len", length, gfxd_Num); - if (opc == G_SETOTHERMODE_H) - argu(m, 3, "mode", lo, gfxd_Othermodehi); - else if (opc == G_SETOTHERMODE_L) - argu(m, 3, "mode", lo, gfxd_Othermodelo); - else - argu(m, 3, "mode", lo, gfxd_Word); - return 0; -} - -UCFUNC int d_SPSetOtherModeLo(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ -#if defined(F3D_GBI) || defined(F3DEX_GBI) - int length = getfield(hi, 8, 0); - int shift = getfield(hi, 8, 8); -#elif defined(F3DEX_GBI_2) - int length = getfield(hi, 8, 0) + 1; - int shift = 32 - (getfield(hi, 8, 8) + length); -#endif - if (shift == G_MDSFT_ALPHACOMPARE && length == G_MDSIZ_ALPHACOMPARE) - return d_DPSetAlphaCompare(m, hi, lo); - else if (shift == G_MDSFT_ZSRCSEL && length == G_MDSIZ_ZSRCSEL) - return d_DPSetDepthSource(m, hi, lo); - else if (shift == G_MDSFT_RENDERMODE && length == G_MDSIZ_RENDERMODE) - return d_DPSetRenderMode(m, hi, lo); - else if (config.emit_ext_macro) - { - m->id = gfxd_SPSetOtherModeLo; - argi(m, 0, "sft", shift, gfxd_Sftlo); - argi(m, 1, "len", length, gfxd_Num); - argu(m, 2, "mode", lo, gfxd_Othermodelo); - return 0; - } - else - return d_SPSetOtherMode(m, hi, lo); -} - -UCFUNC int d_SPSetOtherModeHi(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ -#if defined(F3D_GBI) || defined(F3DEX_GBI) - int length = getfield(hi, 8, 0); - int shift = getfield(hi, 8, 8); -#elif defined(F3DEX_GBI_2) - int length = getfield(hi, 8, 0) + 1; - int shift = 32 - (getfield(hi, 8, 8) + length); -#endif - if (shift == G_MDSFT_ALPHADITHER && length == G_MDSIZ_ALPHADITHER) - return d_DPSetAlphaDither(m, hi, lo); - else if (shift == G_MDSFT_RGBDITHER && length == G_MDSIZ_RGBDITHER) - return d_DPSetColorDither(m, hi, lo); - else if (shift == G_MDSFT_COMBKEY && length == G_MDSIZ_COMBKEY) - return d_DPSetCombineKey(m, hi, lo); - else if (shift == G_MDSFT_TEXTCONV && length == G_MDSIZ_TEXTCONV) - return d_DPSetTextureConvert(m, hi, lo); - else if (shift == G_MDSFT_TEXTFILT && length == G_MDSIZ_TEXTFILT) - return d_DPSetTextureFilter(m, hi, lo); - else if (shift == G_MDSFT_TEXTLUT && length == G_MDSIZ_TEXTLUT) - return d_DPSetTextureLUT(m, hi, lo); - else if (shift == G_MDSFT_TEXTLOD && length == G_MDSIZ_TEXTLOD) - return d_DPSetTextureLOD(m, hi, lo); - else if (shift == G_MDSFT_TEXTDETAIL && length == G_MDSIZ_TEXTDETAIL) - return d_DPSetTextureDetail(m, hi, lo); - else if (shift == G_MDSFT_TEXTPERSP && length == G_MDSIZ_TEXTPERSP) - return d_DPSetTexturePersp(m, hi, lo); - else if (shift == G_MDSFT_CYCLETYPE && length == G_MDSIZ_CYCLETYPE) - return d_DPSetCycleType(m, hi, lo); - else if (shift == G_MDSFT_PIPELINE && length == G_MDSIZ_PIPELINE) - return d_DPPipelineMode(m, hi, lo); - else if (config.emit_ext_macro) - { - m->id = gfxd_SPSetOtherModeHi; - argi(m, 0, "sft", shift, gfxd_Sfthi); - argi(m, 1, "len", length, gfxd_Num); - argu(m, 2, "mode", lo, gfxd_Othermodehi); - return 0; - } - else - return d_SPSetOtherMode(m, hi, lo); -} - -UCFUNC int d_DPSetOtherMode(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_DPSetOtherMode; - argu(m, 0, "hi", getfield(hi, 24, 0), gfxd_Othermodehi); - argu(m, 1, "lo", lo, gfxd_Othermodelo); - return 0; -} - -UCFUNC int d_MoveWd(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ -#if defined(F3D_GBI) || defined(F3DEX_GBI) - int index = getfield(hi, 8, 0); - int offset = getfield(hi, 16, 8); -#elif defined(F3DEX_GBI_2) - int index = getfield(hi, 8, 16); - int offset = getfield(hi, 16, 0); -#endif - if (index == G_MW_FOG && offset == G_MWO_FOG) - return d_SPFogPosition(m, hi, lo); -#if !(defined(F3D_BETA) && (defined(F3D_GBI) || defined(F3DEX_GBI))) - else if (index == G_MW_PERSPNORM && offset == 0) - return d_SPPerspNormalize(m, hi, lo); -#endif - else if (index == G_MW_SEGMENT) - return d_SPSegment(m, hi, lo); - else if (index == G_MW_NUMLIGHT && offset == G_MWO_NUMLIGHT) - return d_SPNumLights(m, hi, lo); -#if defined(F3D_GBI) || (defined(F3D_BETA) && defined(F3DEX_GBI)) - else if (index == G_MW_POINTS) - return d_SPModifyVertex(m, hi, lo); -#endif -#if defined(F3D_GBI) || defined(F3DEX_GBI) - else if (index == G_MW_MATRIX) - return d_SPInsertMatrix(m, hi, lo); -#endif - else - { - m->id = gfxd_MoveWd; - argi(m, 0, "index", index, gfxd_Mw); - if (index == G_MW_MATRIX) - argu(m, 1, "offset", offset, gfxd_Mwo_matrix); - else if (index == G_MW_CLIP) - argu(m, 1, "offset", offset, gfxd_Mwo_clip); - else if (index == G_MW_LIGHTCOL) - argu(m, 1, "offset", offset, gfxd_Mwo_lightcol); - else - argu(m, 1, "offset", offset, gfxd_Mwo); - argu(m, 2, "value", lo, gfxd_Word); - } - return 0; -} - -#if defined(F3D_GBI) || defined(F3DEX_GBI) -UCFUNC int d_MoveMem(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - int size = getfield(hi, 16, 0); - int index = getfield(hi, 8, 16); - if (size == sizeof(Light) - && index >= G_MV_L0 - && index <= G_MV_L7 - && index % 2 == 0) - { - return d_SPLight(m, hi, lo); - } - else if (size == sizeof(Light) && index == G_MV_LOOKATX) - return d_SPLookAtX(m, hi, lo); - else if (size == sizeof(Light) && index == G_MV_LOOKATY) - return d_SPLookAtY(m, hi, lo); - else if (size == sizeof(Vp) && index == G_MV_VIEWPORT) - return d_SPViewport(m, hi, lo); - else - { - m->id = gfxd_MoveMem; - argu(m, 0, "size", size, gfxd_Size); - argi(m, 1, "index", index, gfxd_Mv); - argu(m, 2, "dram", lo, gfxd_Dram); - return 0; - } -} -#elif defined(F3DEX_GBI_2) -UCFUNC int d_MoveMem(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - int size = (getfield(hi, 5, 19) + 1) * 8; - int index = getfield(hi, 8, 0); - int offset = getfield(hi, 8, 8) * 8; - if (size == sizeof(Light) - && index == G_MV_LIGHT - && offset >= G_MVO_L0 - && offset <= G_MVO_L7 - && offset % 0x18 == 0) - { - return d_SPLight(m, hi, lo); - } - else if (size == sizeof(Light) - && index == G_MV_LIGHT - && offset == G_MVO_LOOKATX) - { - return d_SPLookAtX(m, hi, lo); - } - else if (size == sizeof(Light) - && index == G_MV_LIGHT - && offset == G_MVO_LOOKATY) - { - return d_SPLookAtY(m, hi, lo); - } - else if (size == sizeof(Vp) - && index == G_MV_VIEWPORT - && offset == 0) - { - return d_SPViewport(m, hi, lo); - } - else - { - m->id = gfxd_MoveMem; - argu(m, 0, "size", size, gfxd_Size); - argi(m, 1, "index", index, gfxd_Mv); - argu(m, 2, "offset", offset, gfxd_Size); - argu(m, 3, "dram", lo, gfxd_Dram); - return 0; - } -} -#endif - -#if defined(F3DEX_GBI_2) -UCFUNC int d_SPDmaRead(gfxd_macro_t *m, uint32_t hi, uint32_t lo); -UCFUNC int d_SPDmaWrite(gfxd_macro_t *m, uint32_t hi, uint32_t lo); -UCFUNC int d_SPDma_io(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - int flag = getfield(hi, 1, 23); - if (flag == 0) - return d_SPDmaRead(m, hi, lo); - else if (flag == 1) - return d_SPDmaWrite(m, hi, lo); - else - { - m->id = gfxd_SPDma_io; - argi(m, 0, "flag", flag, gfxd_Dmaflag); - argu(m, 1, "dmem", getfield(hi, 10, 13) * 8, gfxd_Dmem); - argu(m, 2, "dram", lo, gfxd_Dram); - argu(m, 3, "size", getfield(hi, 12, 10) + 1, gfxd_Size); - return 0; - } -} - -UCFUNC int d_SPDmaRead(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_SPDmaRead; - argu(m, 0, "dmem", getfield(hi, 10, 13) * 8, gfxd_Dmem); - argu(m, 1, "dram", lo, gfxd_Dram); - argu(m, 2, "size", getfield(hi, 12, 10) + 1, gfxd_Size); - return 0; -} - -UCFUNC int d_SPDmaWrite(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_SPDmaWrite; - argu(m, 0, "dmem", getfield(hi, 10, 13) * 8, gfxd_Dmem); - argu(m, 1, "dram", lo, gfxd_Dram); - argu(m, 2, "size", getfield(hi, 12, 10) + 1, gfxd_Size); - return 0; -} -#endif - -#if defined(F3DEX_GBI) || defined(F3DEX_GBI_2) -UCFUNC int d_LoadUcode(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_LoadUcode; - argu(m, 0, "uc_start", lo, gfxd_Uctext); - argu(m, 1, "uc_dsize", getfield(hi, 16, 0) + 1, gfxd_Size); - return 0; -} - -UCFUNC int c_SPLoadUcodeEx(gfxd_macro_t *m, int n_macro) -{ - if (n_macro < 2) - return -1; - if (m[0].id != gfxd_DPHalf1) - return -1; - uint32_t uc_dstart = argvu(&m[0], 0); - if (m[1].id != gfxd_LoadUcode) - return -1; - uint32_t uc_start = argvu(&m[1], 0); - uint32_t uc_dsize = argvu(&m[1], 1); - m->id = gfxd_SPLoadUcodeEx; - argu(m, 0, "uc_start", uc_start, gfxd_Uctext); - argu(m, 1, "uc_dstart", uc_dstart, gfxd_Ucdata); - argu(m, 2, "uc_dsize", uc_dsize, gfxd_Size); - return 0; -} -#endif - -UCFUNC int d_TexRect(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_TexRect; - argu(m, 0, "ulx", getfield(lo, 12, 12), gfxd_Coordq); - argu(m, 1, "uly", getfield(lo, 12, 0), gfxd_Coordq); - argu(m, 2, "lrx", getfield(hi, 12, 12), gfxd_Coordq); - argu(m, 3, "lry", getfield(hi, 12, 0), gfxd_Coordq); - argi(m, 4, "tile", getfield(lo, 3, 24), gfxd_Tile); - return 0; -} - -UCFUNC int d_TexRectFlip(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_TexRectFlip; - argu(m, 0, "ulx", getfield(lo, 12, 12), gfxd_Coordq); - argu(m, 1, "uly", getfield(lo, 12, 0), gfxd_Coordq); - argu(m, 2, "lrx", getfield(hi, 12, 12), gfxd_Coordq); - argu(m, 3, "lry", getfield(hi, 12, 0), gfxd_Coordq); - argi(m, 4, "tile", getfield(lo, 3, 24), gfxd_Tile); - return 0; -} - -UCFUNC int d_SPNoOp(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_SPNoOp; - return 0; -} - -#if defined(F3DEX_GBI_2) -UCFUNC int d_Special3(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_Special3; - argu(m, 0, "hi", getfield(hi, 24, 0), gfxd_Word); - argu(m, 1, "lo", lo, gfxd_Word); - return 0; -} - -UCFUNC int d_Special2(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_Special2; - argu(m, 0, "hi", getfield(hi, 24, 0), gfxd_Word); - argu(m, 1, "lo", lo, gfxd_Word); - return 0; -} - -UCFUNC int d_Special1(gfxd_macro_t *m, uint32_t hi, uint32_t lo) -{ - m->id = gfxd_Special1; - argu(m, 0, "hi", getfield(hi, 24, 0), gfxd_Word); - argu(m, 1, "lo", lo, gfxd_Word); - return 0; -} -#endif diff --git a/tools/ZAPD/lib/libgfxd/uc_macrotbl.c b/tools/ZAPD/lib/libgfxd/uc_macrotbl.c deleted file mode 100644 index a8939cede0..0000000000 --- a/tools/ZAPD/lib/libgfxd/uc_macrotbl.c +++ /dev/null @@ -1,1397 +0,0 @@ -static const gfxd_macro_type_t macro_tbl[] = -{ - [gfxd_Invalid] = - { - .prefix = NULL, - .suffix = NULL, - .opcode = -1, - .n_gfx = 1, - .n_arg = 2, - .disas_fn = d_Invalid, - }, - [gfxd_DPFillRectangle] = - { - .prefix = NULL, - .suffix = "DPFillRectangle", - .opcode = G_FILLRECT, - .n_gfx = 1, - .n_arg = 4, - .disas_fn = d_DPFillRectangle, - }, - [gfxd_DPFullSync] = - { - .prefix = NULL, - .suffix = "DPFullSync", - .opcode = G_RDPFULLSYNC, - .n_gfx = 1, - .n_arg = 0, - .disas_fn = d_DPFullSync, - }, - [gfxd_DPLoadSync] = - { - .prefix = NULL, - .suffix = "DPLoadSync", - .opcode = G_RDPLOADSYNC, - .n_gfx = 1, - .n_arg = 0, - .disas_fn = d_DPLoadSync, - }, - [gfxd_DPTileSync] = - { - .prefix = NULL, - .suffix = "DPTileSync", - .opcode = G_RDPTILESYNC, - .n_gfx = 1, - .n_arg = 0, - .disas_fn = d_DPTileSync, - }, - [gfxd_DPPipeSync] = - { - .prefix = NULL, - .suffix = "DPPipeSync", - .opcode = G_RDPPIPESYNC, - .n_gfx = 1, - .n_arg = 0, - .disas_fn = d_DPPipeSync, - }, - [gfxd_DPLoadTLUT_pal16] = - { - .prefix = NULL, - .suffix = "DPLoadTLUT_pal16", - .opcode = G_SETTIMG, - .n_gfx = 6, - .n_arg = 2, - .combine_fn = c_DPLoadTLUT_pal16, - }, - [gfxd_DPLoadTLUT_pal256] = - { - .prefix = NULL, - .suffix = "DPLoadTLUT_pal256", - .opcode = G_SETTIMG, - .n_gfx = 6, - .n_arg = 1, - .combine_fn = c_DPLoadTLUT_pal256, - }, - [gfxd_DPLoadMultiBlockYuvS] = - { - .prefix = NULL, - .suffix = "DPLoadMultiBlockYuvS", - .opcode = G_SETTIMG, - .n_gfx = 7, - .n_arg = 14, - .combine_fn = c_DPLoadMultiBlockYuvS, - .ext = 1, - }, - [gfxd_DPLoadMultiBlockYuv] = - { - .prefix = NULL, - .suffix = "DPLoadMultiBlockYuv", - .opcode = G_SETTIMG, - .n_gfx = 7, - .n_arg = 14, - .combine_fn = c_DPLoadMultiBlockYuv, - .ext = 1, - }, - [gfxd_DPLoadMultiBlock_4bS] = - { - .prefix = NULL, - .suffix = "DPLoadMultiBlock_4bS", - .opcode = G_SETTIMG, - .n_gfx = 7, - .n_arg = 13, - .combine_fn = c_DPLoadMultiBlock_4bS, - }, - [gfxd_DPLoadMultiBlock_4b] = - { - .prefix = NULL, - .suffix = "DPLoadMultiBlock_4b", - .opcode = G_SETTIMG, - .n_gfx = 7, - .n_arg = 13, - .combine_fn = c_DPLoadMultiBlock_4b, - }, - [gfxd_DPLoadMultiBlockS] = - { - .prefix = NULL, - .suffix = "DPLoadMultiBlockS", - .opcode = G_SETTIMG, - .n_gfx = 7, - .n_arg = 14, - .combine_fn = c_DPLoadMultiBlockS, - }, - [gfxd_DPLoadMultiBlock] = - { - .prefix = NULL, - .suffix = "DPLoadMultiBlock", - .opcode = G_SETTIMG, - .n_gfx = 7, - .n_arg = 14, - .combine_fn = c_DPLoadMultiBlock, - }, - [gfxd__DPLoadTextureBlockYuvS] = - { - .prefix = "_", - .suffix = "DPLoadTextureBlockYuvS", - .opcode = G_SETTIMG, - .n_gfx = 7, - .n_arg = 13, - .combine_fn = c__DPLoadTextureBlockYuvS, - .ext = 1, - }, - [gfxd__DPLoadTextureBlockYuv] = - { - .prefix = "_", - .suffix = "DPLoadTextureBlockYuv", - .opcode = G_SETTIMG, - .n_gfx = 7, - .n_arg = 13, - .combine_fn = c__DPLoadTextureBlockYuv, - .ext = 1, - }, - [gfxd__DPLoadTextureBlock_4bS] = - { - .prefix = "_", - .suffix = "DPLoadTextureBlock_4bS", - .opcode = G_SETTIMG, - .n_gfx = 7, - .n_arg = 12, - .combine_fn = c__DPLoadTextureBlock_4bS, - .ext = 1, - }, - [gfxd__DPLoadTextureBlock_4b] = - { - .prefix = "_", - .suffix = "DPLoadTextureBlock_4b", - .opcode = G_SETTIMG, - .n_gfx = 7, - .n_arg = 12, - .combine_fn = c__DPLoadTextureBlock_4b, - }, - [gfxd__DPLoadTextureBlockS] = - { - .prefix = "_", - .suffix = "DPLoadTextureBlockS", - .opcode = G_SETTIMG, - .n_gfx = 7, - .n_arg = 13, - .combine_fn = c__DPLoadTextureBlockS, - .ext = 1, - }, - [gfxd__DPLoadTextureBlock] = - { - .prefix = "_", - .suffix = "DPLoadTextureBlock", - .opcode = G_SETTIMG, - .n_gfx = 7, - .n_arg = 13, - .combine_fn = c__DPLoadTextureBlock, - }, - [gfxd_DPLoadTextureBlockYuvS] = - { - .prefix = NULL, - .suffix = "DPLoadTextureBlockYuvS", - .opcode = G_SETTIMG, - .n_gfx = 7, - .n_arg = 12, - .combine_fn = c_DPLoadTextureBlockYuvS, - .ext = 1, - }, - [gfxd_DPLoadTextureBlockYuv] = - { - .prefix = NULL, - .suffix = "DPLoadTextureBlockYuv", - .opcode = G_SETTIMG, - .n_gfx = 7, - .n_arg = 12, - .combine_fn = c_DPLoadTextureBlockYuv, - .ext = 1, - }, - [gfxd_DPLoadTextureBlock_4bS] = - { - .prefix = NULL, - .suffix = "DPLoadTextureBlock_4bS", - .opcode = G_SETTIMG, - .n_gfx = 7, - .n_arg = 11, - .combine_fn = c_DPLoadTextureBlock_4bS, - }, - [gfxd_DPLoadTextureBlock_4b] = - { - .prefix = NULL, - .suffix = "DPLoadTextureBlock_4b", - .opcode = G_SETTIMG, - .n_gfx = 7, - .n_arg = 11, - .combine_fn = c_DPLoadTextureBlock_4b, - }, - [gfxd_DPLoadTextureBlockS] = - { - .prefix = NULL, - .suffix = "DPLoadTextureBlockS", - .opcode = G_SETTIMG, - .n_gfx = 7, - .n_arg = 12, - .combine_fn = c_DPLoadTextureBlockS, - }, - [gfxd_DPLoadTextureBlock] = - { - .prefix = NULL, - .suffix = "DPLoadTextureBlock", - .opcode = G_SETTIMG, - .n_gfx = 7, - .n_arg = 12, - .combine_fn = c_DPLoadTextureBlock, - }, - [gfxd_DPLoadMultiTileYuv] = - { - .prefix = NULL, - .suffix = "DPLoadMultiTileYuv", - .opcode = G_SETTIMG, - .n_gfx = 7, - .n_arg = 18, - .combine_fn = c_DPLoadMultiTileYuv, - .ext = 1, - }, - [gfxd_DPLoadMultiTile_4b] = - { - .prefix = NULL, - .suffix = "DPLoadMultiTile_4b", - .opcode = G_SETTIMG, - .n_gfx = 7, - .n_arg = 17, - .combine_fn = c_DPLoadMultiTile_4b, - }, - [gfxd_DPLoadMultiTile] = - { - .prefix = NULL, - .suffix = "DPLoadMultiTile", - .opcode = G_SETTIMG, - .n_gfx = 7, - .n_arg = 18, - .combine_fn = c_DPLoadMultiTile, - }, - [gfxd__DPLoadTextureTileYuv] = - { - .prefix = "_", - .suffix = "DPLoadTextureTileYuv", - .opcode = G_SETTIMG, - .n_gfx = 7, - .n_arg = 17, - .combine_fn = c__DPLoadTextureTileYuv, - .ext = 1, - }, - [gfxd__DPLoadTextureTile_4b] = - { - .prefix = "_", - .suffix = "DPLoadTextureTile_4b", - .opcode = G_SETTIMG, - .n_gfx = 7, - .n_arg = 16, - .combine_fn = c__DPLoadTextureTile_4b, - .ext = 1, - }, - [gfxd__DPLoadTextureTile] = - { - .prefix = "_", - .suffix = "DPLoadTextureTile", - .opcode = G_SETTIMG, - .n_gfx = 7, - .n_arg = 17, - .combine_fn = c__DPLoadTextureTile, - .ext = 1, - }, - [gfxd_DPLoadTextureTileYuv] = - { - .prefix = NULL, - .suffix = "DPLoadTextureTileYuv", - .opcode = G_SETTIMG, - .n_gfx = 7, - .n_arg = 16, - .combine_fn = c_DPLoadTextureTileYuv, - .ext = 1, - }, - [gfxd_DPLoadTextureTile_4b] = - { - .prefix = NULL, - .suffix = "DPLoadTextureTile_4b", - .opcode = G_SETTIMG, - .n_gfx = 7, - .n_arg = 15, - .combine_fn = c_DPLoadTextureTile_4b, - }, - [gfxd_DPLoadTextureTile] = - { - .prefix = NULL, - .suffix = "DPLoadTextureTile", - .opcode = G_SETTIMG, - .n_gfx = 7, - .n_arg = 16, - .combine_fn = c_DPLoadTextureTile, - }, - [gfxd_DPLoadBlock] = - { - .prefix = NULL, - .suffix = "DPLoadBlock", - .opcode = G_LOADBLOCK, - .n_gfx = 1, - .n_arg = 5, - .disas_fn = d_DPLoadBlock, - }, - [gfxd_DPNoOp] = - { - .prefix = NULL, - .suffix = "DPNoOp", - .opcode = G_NOOP, - .n_gfx = 1, - .n_arg = 0, - .alias = gfxd_DPNoOpTag, - }, - [gfxd_DPNoOpTag] = - { - .prefix = NULL, - .suffix = "DPNoOpTag", - .opcode = G_NOOP, - .n_gfx = 1, - .n_arg = 1, - .disas_fn = d_DPNoOpTag, - }, - [gfxd_DPPipelineMode] = - { - .prefix = NULL, - .suffix = "DPPipelineMode", - .opcode = G_SETOTHERMODE_H, - .n_gfx = 1, - .n_arg = 1, - .alias = gfxd_SPSetOtherModeHi, - }, - [gfxd_DPSetBlendColor] = - { - .prefix = NULL, - .suffix = "DPSetBlendColor", - .opcode = G_SETBLENDCOLOR, - .n_gfx = 1, - .n_arg = 4, - .disas_fn = d_DPSetBlendColor, - }, - [gfxd_DPSetEnvColor] = - { - .prefix = NULL, - .suffix = "DPSetEnvColor", - .opcode = G_SETENVCOLOR, - .n_gfx = 1, - .n_arg = 4, - .disas_fn = d_DPSetEnvColor, - }, - [gfxd_DPSetFillColor] = - { - .prefix = NULL, - .suffix = "DPSetFillColor", - .opcode = G_SETFILLCOLOR, - .n_gfx = 1, - .n_arg = 1, - .disas_fn = d_DPSetFillColor, - }, - [gfxd_DPSetFogColor] = - { - .prefix = NULL, - .suffix = "DPSetFogColor", - .opcode = G_SETFOGCOLOR, - .n_gfx = 1, - .n_arg = 4, - .disas_fn = d_DPSetFogColor, - }, - [gfxd_DPSetPrimColor] = - { - .prefix = NULL, - .suffix = "DPSetPrimColor", - .opcode = G_SETPRIMCOLOR, - .n_gfx = 1, - .n_arg = 6, - .disas_fn = d_DPSetPrimColor, - }, - [gfxd_DPSetColorImage] = - { - .prefix = NULL, - .suffix = "DPSetColorImage", - .opcode = G_SETCIMG, - .n_gfx = 1, - .n_arg = 4, - .disas_fn = d_DPSetColorImage, - }, - [gfxd_DPSetDepthImage] = - { - .prefix = NULL, - .suffix = "DPSetDepthImage", - .opcode = G_SETZIMG, - .n_gfx = 1, - .n_arg = 1, - .disas_fn = d_DPSetDepthImage, - }, - [gfxd_DPSetTextureImage] = - { - .prefix = NULL, - .suffix = "DPSetTextureImage", - .opcode = G_SETTIMG, - .n_gfx = 1, - .n_arg = 4, - .disas_fn = d_DPSetTextureImage, - }, - [gfxd_DPSetAlphaCompare] = - { - .prefix = NULL, - .suffix = "DPSetAlphaCompare", - .opcode = G_SETOTHERMODE_L, - .n_gfx = 1, - .n_arg = 1, - .alias = gfxd_SPSetOtherModeLo, - }, - [gfxd_DPSetAlphaDither] = - { - .prefix = NULL, - .suffix = "DPSetAlphaDither", - .opcode = G_SETOTHERMODE_H, - .n_gfx = 1, - .n_arg = 1, - .alias = gfxd_SPSetOtherModeHi, - }, - [gfxd_DPSetColorDither] = - { - .prefix = NULL, - .suffix = "DPSetColorDither", - .opcode = G_SETOTHERMODE_H, - .n_gfx = 1, - .n_arg = 1, - .alias = gfxd_SPSetOtherModeHi, - }, - [gfxd_DPSetCombineMode] = - { - .prefix = NULL, - .suffix = "DPSetCombineMode", - .opcode = G_SETCOMBINE, - .n_gfx = 1, - .n_arg = 2, - .alias = gfxd_DPSetCombineLERP, - }, - [gfxd_DPSetCombineLERP] = - { - .prefix = NULL, - .suffix = "DPSetCombineLERP", - .opcode = G_SETCOMBINE, - .n_gfx = 1, - .n_arg = 16, - .disas_fn = d_DPSetCombineLERP, - }, - [gfxd_DPSetConvert] = - { - .prefix = NULL, - .suffix = "DPSetConvert", - .opcode = G_SETCONVERT, - .n_gfx = 1, - .n_arg = 6, - .disas_fn = d_DPSetConvert, - }, - [gfxd_DPSetTextureConvert] = - { - .prefix = NULL, - .suffix = "DPSetTextureConvert", - .opcode = G_SETOTHERMODE_H, - .n_gfx = 1, - .n_arg = 1, - .alias = gfxd_SPSetOtherModeHi, - }, - [gfxd_DPSetCycleType] = - { - .prefix = NULL, - .suffix = "DPSetCycleType", - .opcode = G_SETOTHERMODE_H, - .n_gfx = 1, - .n_arg = 1, - .alias = gfxd_SPSetOtherModeHi, - }, - [gfxd_DPSetDepthSource] = - { - .prefix = NULL, - .suffix = "DPSetDepthSource", - .opcode = G_SETOTHERMODE_L, - .n_gfx = 1, - .n_arg = 1, - .alias = gfxd_SPSetOtherModeLo, - }, - [gfxd_DPSetCombineKey] = - { - .prefix = NULL, - .suffix = "DPSetCombineKey", - .opcode = G_SETOTHERMODE_H, - .n_gfx = 1, - .n_arg = 1, - .alias = gfxd_SPSetOtherModeHi, - }, - [gfxd_DPSetKeyGB] = - { - .prefix = NULL, - .suffix = "DPSetKeyGB", - .opcode = G_SETKEYGB, - .n_gfx = 1, - .n_arg = 6, - .disas_fn = d_DPSetKeyGB, - }, - [gfxd_DPSetKeyR] = - { - .prefix = NULL, - .suffix = "DPSetKeyR", - .opcode = G_SETKEYR, - .n_gfx = 1, - .n_arg = 3, - .disas_fn = d_DPSetKeyR, - }, - [gfxd_DPSetPrimDepth] = - { - .prefix = NULL, - .suffix = "DPSetPrimDepth", - .opcode = G_SETPRIMDEPTH, - .n_gfx = 1, - .n_arg = 2, - .disas_fn = d_DPSetPrimDepth, - }, - [gfxd_DPSetRenderMode] = - { - .prefix = NULL, - .suffix = "DPSetRenderMode", - .opcode = G_SETOTHERMODE_L, - .n_gfx = 1, - .n_arg = 2, - .alias = gfxd_SPSetOtherModeLo, - }, - [gfxd_DPSetScissor] = - { - .prefix = NULL, - .suffix = "DPSetScissor", - .opcode = G_SETSCISSOR, - .n_gfx = 1, - .n_arg = 5, - .alias = gfxd_DPSetScissorFrac, - }, - [gfxd_DPSetScissorFrac] = - { - .prefix = NULL, - .suffix = "DPSetScissorFrac", - .opcode = G_SETSCISSOR, - .n_gfx = 1, - .n_arg = 5, - .disas_fn = d_DPSetScissorFrac, - }, - [gfxd_DPSetTextureDetail] = - { - .prefix = NULL, - .suffix = "DPSetTextureDetail", - .opcode = G_SETOTHERMODE_H, - .n_gfx = 1, - .n_arg = 1, - .alias = gfxd_SPSetOtherModeHi, - }, - [gfxd_DPSetTextureFilter] = - { - .prefix = NULL, - .suffix = "DPSetTextureFilter", - .opcode = G_SETOTHERMODE_H, - .n_gfx = 1, - .n_arg = 1, - .alias = gfxd_SPSetOtherModeHi, - }, - [gfxd_DPSetTextureLOD] = - { - .prefix = NULL, - .suffix = "DPSetTextureLOD", - .opcode = G_SETOTHERMODE_H, - .n_gfx = 1, - .n_arg = 1, - .alias = gfxd_SPSetOtherModeHi, - }, - [gfxd_DPSetTextureLUT] = - { - .prefix = NULL, - .suffix = "DPSetTextureLUT", - .opcode = G_SETOTHERMODE_H, - .n_gfx = 1, - .n_arg = 1, - .alias = gfxd_SPSetOtherModeHi, - }, - [gfxd_DPSetTexturePersp] = - { - .prefix = NULL, - .suffix = "DPSetTexturePersp", - .opcode = G_SETOTHERMODE_H, - .n_gfx = 1, - .n_arg = 1, - .alias = gfxd_SPSetOtherModeHi, - }, - [gfxd_DPSetTile] = - { - .prefix = NULL, - .suffix = "DPSetTile", - .opcode = G_SETTILE, - .n_gfx = 1, - .n_arg = 12, - .disas_fn = d_DPSetTile, - }, - [gfxd_DPSetTileSize] = - { - .prefix = NULL, - .suffix = "DPSetTileSize", - .opcode = G_SETTILESIZE, - .n_gfx = 1, - .n_arg = 5, - .disas_fn = d_DPSetTileSize, - }, - [gfxd_SP1Triangle] = - { - .prefix = NULL, - .suffix = "SP1Triangle", - .opcode = G_TRI1, - .n_gfx = 1, - .n_arg = 4, - .disas_fn = d_SP1Triangle, - }, -#if defined(F3DEX_GBI) || defined(F3DEX_GBI_2) - [gfxd_SP2Triangles] = - { - .prefix = NULL, - .suffix = "SP2Triangles", - .opcode = G_TRI2, - .n_gfx = 1, - .n_arg = 8, - .disas_fn = d_SP2Triangles, - }, -#endif -#if defined(F3DEX_GBI) - [gfxd_SP1Quadrangle] = - { - .prefix = NULL, - .suffix = "SP1Quadrangle", - .opcode = G_TRI2, - .n_gfx = 1, - .n_arg = 5, - .alias = gfxd_SP2Triangles, - }, -#elif defined(F3DEX_GBI_2) - [gfxd_SP1Quadrangle] = - { - .prefix = NULL, - .suffix = "SP1Quadrangle", - .opcode = G_QUAD, - .n_gfx = 1, - .n_arg = 5, - .disas_fn = d_SP1Quadrangle, - }, -#endif -#if defined(F3DEX_GBI) || defined(F3DEX_GBI_2) - [gfxd_SPBranchLessZraw] = - { - .prefix = NULL, - .suffix = "SPBranchLessZraw", - .opcode = G_RDPHALF_1, - .n_gfx = 2, - .n_arg = 3, - .combine_fn = c_SPBranchLessZraw, - }, -#endif - [gfxd_SPBranchList] = - { - .prefix = NULL, - .suffix = "SPBranchList", - .opcode = G_DL, - .n_gfx = 1, - .n_arg = 1, - .alias = gfxd_DisplayList, - }, - [gfxd_SPClipRatio] = - { - .prefix = NULL, - .suffix = "SPClipRatio", - .opcode = G_MOVEWORD, - .n_gfx = 4, - .n_arg = 1, - .combine_fn = c_SPClipRatio, - }, - [gfxd_SPCullDisplayList] = - { - .prefix = NULL, - .suffix = "SPCullDisplayList", - .opcode = G_CULLDL, - .n_gfx = 1, - .n_arg = 2, - .disas_fn = d_SPCullDisplayList, - }, - [gfxd_SPDisplayList] = - { - .prefix = NULL, - .suffix = "SPDisplayList", - .opcode = G_DL, - .n_gfx = 1, - .n_arg = 1, - .alias = gfxd_DisplayList, - }, - [gfxd_SPEndDisplayList] = - { - .prefix = NULL, - .suffix = "SPEndDisplayList", - .opcode = G_ENDDL, - .n_gfx = 1, - .n_arg = 0, - .disas_fn = d_SPEndDisplayList, - }, - [gfxd_SPFogFactor] = - { - .prefix = NULL, - .suffix = "SPFogFactor", - .opcode = G_MOVEWORD, - .n_gfx = 1, - .n_arg = 2, - .alias = gfxd_SPFogPosition, - }, - [gfxd_SPFogPosition] = - { - .prefix = NULL, - .suffix = "SPFogPosition", - .opcode = G_MOVEWORD, - .n_gfx = 1, - .n_arg = 2, - .alias = gfxd_MoveWd, - }, -#if defined(F3D_GBI) || defined(F3DEX_GBI) - [gfxd_SPForceMatrix] = - { - .prefix = NULL, - .suffix = "SPForceMatrix", - .opcode = G_MOVEMEM, - .n_gfx = 4, - .n_arg = 1, - .combine_fn = c_SPForceMatrix, - }, - [gfxd_SPSetGeometryMode] = - { - .prefix = NULL, - .suffix = "SPSetGeometryMode", - .opcode = G_SETGEOMETRYMODE, - .n_gfx = 1, - .n_arg = 1, - .disas_fn = d_SPSetGeometryMode, - }, - [gfxd_SPClearGeometryMode] = - { - .prefix = NULL, - .suffix = "SPClearGeometryMode", - .opcode = G_CLEARGEOMETRYMODE, - .n_gfx = 1, - .n_arg = 1, - .disas_fn = d_SPClearGeometryMode, - }, - [gfxd_SPLoadGeometryMode] = - { - .prefix = NULL, - .suffix = "SPLoadGeometryMode", - .opcode = G_CLEARGEOMETRYMODE, - .n_gfx = 2, - .n_arg = 1, - .combine_fn = c_SPLoadGeometryMode, - }, -#elif defined(F3DEX_GBI_2) - [gfxd_SPForceMatrix] = - { - .prefix = NULL, - .suffix = "SPForceMatrix", - .opcode = G_MOVEMEM, - .n_gfx = 2, - .n_arg = 1, - .combine_fn = c_SPForceMatrix, - }, - [gfxd_SPSetGeometryMode] = - { - .prefix = NULL, - .suffix = "SPSetGeometryMode", - .opcode = G_GEOMETRYMODE, - .n_gfx = 1, - .n_arg = 1, - .alias = gfxd_SPGeometryMode, - }, - [gfxd_SPClearGeometryMode] = - { - .prefix = NULL, - .suffix = "SPClearGeometryMode", - .opcode = G_GEOMETRYMODE, - .n_gfx = 1, - .n_arg = 1, - .alias = gfxd_SPGeometryMode, - }, - [gfxd_SPLoadGeometryMode] = - { - .prefix = NULL, - .suffix = "SPLoadGeometryMode", - .opcode = G_GEOMETRYMODE, - .n_gfx = 1, - .n_arg = 1, - .alias = gfxd_SPGeometryMode, - }, -#endif -#if defined(F3D_GBI) || defined(F3DEX_GBI) - [gfxd_SPInsertMatrix] = - { - .prefix = NULL, - .suffix = "SPInsertMatrix", - .opcode = G_MOVEWORD, - .n_gfx = 1, - .n_arg = 2, - .alias = gfxd_MoveWd, - }, -#endif - [gfxd_SPLine3D] = - { - .prefix = NULL, - .suffix = "SPLine3D", - .opcode = G_LINE3D, - .n_gfx = 1, - .n_arg = 3, - .alias = gfxd_SPLineW3D, - }, - [gfxd_SPLineW3D] = - { - .prefix = NULL, - .suffix = "SPLineW3D", - .opcode = G_LINE3D, - .n_gfx = 1, - .n_arg = 4, - .disas_fn = d_SPLineW3D, - }, -#if defined(F3DEX_GBI) || defined(F3DEX_GBI_2) - [gfxd_SPLoadUcode] = - { - .prefix = NULL, - .suffix = "SPLoadUcode", - .opcode = G_RDPHALF_1, - .n_gfx = 2, - .n_arg = 2, - .combine_fn = c_SPLoadUcode, - }, -#endif - [gfxd_SPLookAtX] = - { - .prefix = NULL, - .suffix = "SPLookAtX", - .opcode = G_MOVEMEM, - .n_gfx = 1, - .n_arg = 1, - .alias = gfxd_MoveMem, - }, - [gfxd_SPLookAtY] = - { - .prefix = NULL, - .suffix = "SPLookAtY", - .opcode = G_MOVEMEM, - .n_gfx = 1, - .n_arg = 1, - .alias = gfxd_MoveMem, - }, - [gfxd_SPLookAt] = - { - .prefix = NULL, - .suffix = "SPLookAt", - .opcode = G_MOVEMEM, - .n_gfx = 2, - .n_arg = 1, - .combine_fn = c_SPLookAt, - }, - [gfxd_SPMatrix] = - { - .prefix = NULL, - .suffix = "SPMatrix", - .opcode = G_MTX, - .n_gfx = 1, - .n_arg = 2, - .disas_fn = d_SPMatrix, - }, -#if defined(F3D_GBI) || (defined(F3D_BETA) && defined(F3DEX_GBI)) - [gfxd_SPModifyVertex] = - { - .prefix = NULL, - .suffix = "SPModifyVertex", - .opcode = G_MOVEWORD, - .n_gfx = 1, - .n_arg = 3, - .alias = gfxd_MoveWd, - }, -#elif defined(F3DEX_GBI) || defined(F3DEX_GBI_2) - [gfxd_SPModifyVertex] = - { - .prefix = NULL, - .suffix = "SPModifyVertex", - .opcode = G_MODIFYVTX, - .n_gfx = 1, - .n_arg = 3, - .disas_fn = d_SPModifyVertex, - }, -#endif -#if defined(F3D_BETA) && (defined(F3D_GBI) || defined(F3DEX_GBI)) - [gfxd_SPPerspNormalize] = - { - .prefix = NULL, - .suffix = "SPPerspNormalize", - .opcode = G_PERSPNORM, - .n_gfx = 1, - .n_arg = 1, - .disas_fn = d_SPPerspNormalize, - }, -#else - [gfxd_SPPerspNormalize] = - { - .prefix = NULL, - .suffix = "SPPerspNormalize", - .opcode = G_MOVEWORD, - .n_gfx = 1, - .n_arg = 1, - .alias = gfxd_MoveWd, - }, -#endif -#if defined(F3D_GBI) || defined(F3DEX_GBI) - [gfxd_SPPopMatrix] = - { - .prefix = NULL, - .suffix = "SPPopMatrix", - .opcode = G_POPMTX, - .n_gfx = 1, - .n_arg = 1, - .disas_fn = d_SPPopMatrix, - }, -#elif defined(F3DEX_GBI_2) - [gfxd_SPPopMatrix] = - { - .prefix = NULL, - .suffix = "SPPopMatrix", - .opcode = G_POPMTX, - .n_gfx = 1, - .n_arg = 1, - .alias = gfxd_SPPopMatrixN, - }, - [gfxd_SPPopMatrixN] = - { - .prefix = NULL, - .suffix = "SPPopMatrixN", - .opcode = G_POPMTX, - .n_gfx = 1, - .n_arg = 2, - .disas_fn = d_SPPopMatrixN, - }, -#endif - [gfxd_SPSegment] = - { - .prefix = NULL, - .suffix = "SPSegment", - .opcode = G_MOVEWORD, - .n_gfx = 1, - .n_arg = 2, - .alias = gfxd_MoveWd, - }, - [gfxd_SPSetLights1] = - { - .prefix = NULL, - .suffix = "SPSetLights1", - .opcode = G_MOVEWORD, - .n_gfx = 3, - .n_arg = 1, - .combine_fn = c_SPSetLights1, - }, - [gfxd_SPSetLights2] = - { - .prefix = NULL, - .suffix = "SPSetLights2", - .opcode = G_MOVEWORD, - .n_gfx = 4, - .n_arg = 1, - .combine_fn = c_SPSetLights2, - }, - [gfxd_SPSetLights3] = - { - .prefix = NULL, - .suffix = "SPSetLights3", - .opcode = G_MOVEWORD, - .n_gfx = 5, - .n_arg = 1, - .combine_fn = c_SPSetLights3, - }, - [gfxd_SPSetLights4] = - { - .prefix = NULL, - .suffix = "SPSetLights4", - .opcode = G_MOVEWORD, - .n_gfx = 6, - .n_arg = 1, - .combine_fn = c_SPSetLights4, - }, - [gfxd_SPSetLights5] = - { - .prefix = NULL, - .suffix = "SPSetLights5", - .opcode = G_MOVEWORD, - .n_gfx = 7, - .n_arg = 1, - .combine_fn = c_SPSetLights5, - }, - [gfxd_SPSetLights6] = - { - .prefix = NULL, - .suffix = "SPSetLights6", - .opcode = G_MOVEWORD, - .n_gfx = 8, - .n_arg = 1, - .combine_fn = c_SPSetLights6, - }, - [gfxd_SPSetLights7] = - { - .prefix = NULL, - .suffix = "SPSetLights7", - .opcode = G_MOVEWORD, - .n_gfx = 9, - .n_arg = 1, - .combine_fn = c_SPSetLights7, - }, - [gfxd_SPNumLights] = - { - .prefix = NULL, - .suffix = "SPNumLights", - .opcode = G_MOVEWORD, - .n_gfx = 1, - .n_arg = 1, - .alias = gfxd_MoveWd, - }, - [gfxd_SPLight] = - { - .prefix = NULL, - .suffix = "SPLight", - .opcode = G_MOVEMEM, - .n_gfx = 1, - .n_arg = 2, - .alias = gfxd_MoveMem, - }, - [gfxd_SPLightColor] = - { - .prefix = NULL, - .suffix = "SPLightColor", - .opcode = G_MOVEWORD, - .n_gfx = 2, - .n_arg = 2, - .combine_fn = c_SPLightColor, - }, - [gfxd_SPTexture] = - { - .prefix = NULL, - .suffix = "SPTexture", - .opcode = G_TEXTURE, - .n_gfx = 1, - .n_arg = 5, - .disas_fn = d_SPTexture, - }, - [gfxd_SPTextureRectangle] = - { - .prefix = NULL, - .suffix = "SPTextureRectangle", - .opcode = G_TEXRECT, - .n_gfx = 3, - .n_arg = 9, - .combine_fn = c_SPTextureRectangle, - }, - [gfxd_SPTextureRectangleFlip] = - { - .prefix = NULL, - .suffix = "SPTextureRectangleFlip", - .opcode = G_TEXRECTFLIP, - .n_gfx = 3, - .n_arg = 9, - .combine_fn = c_SPTextureRectangleFlip, - }, - [gfxd_SPVertex] = - { - .prefix = NULL, - .suffix = "SPVertex", - .opcode = G_VTX, - .n_gfx = 1, - .n_arg = 3, - .disas_fn = d_SPVertex, - }, - [gfxd_SPViewport] = - { - .prefix = NULL, - .suffix = "SPViewport", - .opcode = G_MOVEMEM, - .n_gfx = 1, - .n_arg = 1, - .alias = gfxd_MoveMem, - }, - [gfxd_DPLoadTLUTCmd] = - { - .prefix = NULL, - .suffix = "DPLoadTLUTCmd", - .opcode = G_LOADTLUT, - .n_gfx = 1, - .n_arg = 2, - .disas_fn = d_DPLoadTLUTCmd, - }, - [gfxd_DPLoadTLUT] = - { - .prefix = NULL, - .suffix = "DPLoadTLUT", - .opcode = G_SETTIMG, - .n_gfx = 6, - .n_arg = 3, - .combine_fn = c_DPLoadTLUT, - }, -#if defined(F3DEX_GBI) || defined(F3DEX_GBI_2) - [gfxd_BranchZ] = - { - .prefix = NULL, - .suffix = "BranchZ", - .opcode = G_BRANCH_Z, - .n_gfx = 1, - .n_arg = 2, - .disas_fn = d_BranchZ, - .ext = 1, - }, -#endif - [gfxd_DisplayList] = - { - .prefix = NULL, - .suffix = "DisplayList", - .opcode = G_DL, - .n_gfx = 1, - .n_arg = 2, - .disas_fn = d_DisplayList, - .ext = 1, - }, - [gfxd_DPHalf1] = - { - .prefix = NULL, - .suffix = "DPHalf1", - .opcode = G_RDPHALF_1, - .n_gfx = 1, - .n_arg = 1, - .disas_fn = d_DPHalf1, - .ext = 1, - }, - [gfxd_DPHalf2] = - { - .prefix = NULL, - .suffix = "DPHalf2", - .opcode = G_RDPHALF_2, - .n_gfx = 1, - .n_arg = 1, - .disas_fn = d_DPHalf2, - .ext = 1, - }, - [gfxd_DPWord] = - { - .prefix = NULL, - .suffix = "DPWord", - .opcode = G_RDPHALF_1, - .n_gfx = 2, - .n_arg = 2, - .combine_fn = c_DPWord, - }, - [gfxd_DPLoadTile] = - { - .prefix = NULL, - .suffix = "DPLoadTile", - .opcode = G_LOADTILE, - .n_gfx = 1, - .n_arg = 5, - .disas_fn = d_DPLoadTile, - }, -#if defined(F3DEX_GBI_2) - [gfxd_SPGeometryMode] = - { - .prefix = NULL, - .suffix = "SPGeometryMode", - .opcode = G_GEOMETRYMODE, - .n_gfx = 1, - .n_arg = 2, - .disas_fn = d_SPGeometryMode, - }, -#endif - [gfxd_SPSetOtherMode] = - { - .prefix = NULL, - .suffix = "SPSetOtherMode", - .opcode = -1, - .n_gfx = 1, - .n_arg = 4, - .disas_fn = d_SPSetOtherMode, - }, - [gfxd_SPSetOtherModeLo] = - { - .prefix = NULL, - .suffix = "SPSetOtherModeLo", - .opcode = G_SETOTHERMODE_L, - .n_gfx = 1, - .n_arg = 3, - .disas_fn = d_SPSetOtherModeLo, - .ext = 1, - }, - [gfxd_SPSetOtherModeHi] = - { - .prefix = NULL, - .suffix = "SPSetOtherModeHi", - .opcode = G_SETOTHERMODE_H, - .n_gfx = 1, - .n_arg = 3, - .disas_fn = d_SPSetOtherModeHi, - .ext = 1, - }, - [gfxd_DPSetOtherMode] = - { - .prefix = NULL, - .suffix = "DPSetOtherMode", - .opcode = G_RDPSETOTHERMODE, - .n_gfx = 1, - .n_arg = 2, - .disas_fn = d_DPSetOtherMode, - }, - [gfxd_MoveWd] = - { - .prefix = NULL, - .suffix = "MoveWd", - .opcode = G_MOVEWORD, - .n_gfx = 1, - .n_arg = 3, - .disas_fn = d_MoveWd, - }, -#if defined(F3D_GBI) || defined(F3DEX_GBI) - [gfxd_MoveMem] = - { - .prefix = NULL, - .suffix = "MoveMem", - .opcode = G_MOVEMEM, - .n_gfx = 1, - .n_arg = 3, - .disas_fn = d_MoveMem, - .ext = 1, - }, -#elif defined(F3DEX_GBI_2) - [gfxd_MoveMem] = - { - .prefix = NULL, - .suffix = "MoveMem", - .opcode = G_MOVEMEM, - .n_gfx = 1, - .n_arg = 4, - .disas_fn = d_MoveMem, - .ext = 1, - }, -#endif -#if defined(F3DEX_GBI_2) - [gfxd_SPDma_io] = - { - .prefix = NULL, - .suffix = "SPDma_io", - .opcode = G_DMA_IO, - .n_gfx = 1, - .n_arg = 4, - .disas_fn = d_SPDma_io, - }, - [gfxd_SPDmaRead] = - { - .prefix = NULL, - .suffix = "SPDmaRead", - .opcode = G_DMA_IO, - .n_gfx = 1, - .n_arg = 3, - .alias = gfxd_SPDma_io, - }, - [gfxd_SPDmaWrite] = - { - .prefix = NULL, - .suffix = "SPDmaWrite", - .opcode = G_DMA_IO, - .n_gfx = 1, - .n_arg = 3, - .alias = gfxd_SPDma_io, - }, -#endif -#if defined(F3DEX_GBI) || defined(F3DEX_GBI_2) - [gfxd_LoadUcode] = - { - .prefix = NULL, - .suffix = "LoadUcode", - .opcode = G_LOAD_UCODE, - .n_gfx = 1, - .n_arg = 2, - .disas_fn = d_LoadUcode, - }, - [gfxd_SPLoadUcodeEx] = - { - .prefix = NULL, - .suffix = "SPLoadUcodeEx", - .opcode = G_RDPHALF_1, - .n_gfx = 2, - .n_arg = 3, - .combine_fn = c_SPLoadUcodeEx, - }, -#endif - [gfxd_TexRect] = - { - .prefix = NULL, - .suffix = "TexRect", - .opcode = G_TEXRECT, - .n_gfx = 1, - .n_arg = 5, - .disas_fn = d_TexRect, - .ext = 1, - }, - [gfxd_TexRectFlip] = - { - .prefix = NULL, - .suffix = "TexRectFlip", - .opcode = G_TEXRECTFLIP, - .n_gfx = 1, - .n_arg = 5, - .disas_fn = d_TexRectFlip, - .ext = 1, - }, - [gfxd_SPNoOp] = - { - .prefix = NULL, - .suffix = "SPNoOp", - .opcode = G_SPNOOP, - .n_gfx = 1, - .n_arg = 0, - .disas_fn = d_SPNoOp, - }, -#if defined(F3DEX_GBI_2) - [gfxd_Special3] = - { - .prefix = NULL, - .suffix = "Special3", - .opcode = G_SPECIAL_3, - .n_gfx = 1, - .n_arg = 2, - .disas_fn = d_Special3, - .ext = 1, - }, - [gfxd_Special2] = - { - .prefix = NULL, - .suffix = "Special2", - .opcode = G_SPECIAL_2, - .n_gfx = 1, - .n_arg = 2, - .disas_fn = d_Special2, - .ext = 1, - }, - [gfxd_Special1] = - { - .prefix = NULL, - .suffix = "Special1", - .opcode = G_SPECIAL_1, - .n_gfx = 1, - .n_arg = 2, - .disas_fn = d_Special1, - .ext = 1, - }, -#endif -}; diff --git a/tools/ZAPD/lib/tinyxml2/tinyxml2.cpp b/tools/ZAPD/lib/tinyxml2/tinyxml2.cpp deleted file mode 100644 index 23a3a6ce47..0000000000 --- a/tools/ZAPD/lib/tinyxml2/tinyxml2.cpp +++ /dev/null @@ -1,2837 +0,0 @@ -/* -Original code by Lee Thomason (www.grinninglizard.com) - -This software is provided 'as-is', without any express or implied -warranty. In no event will the authors be held liable for any -damages arising from the use of this software. - -Permission is granted to anyone to use this software for any -purpose, including commercial applications, and to alter it and -redistribute it freely, subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must -not claim that you wrote the original software. If you use this -software in a product, an acknowledgment in the product documentation -would be appreciated but is not required. - -2. Altered source versions must be plainly marked as such, and -must not be misrepresented as being the original software. - -3. This notice may not be removed or altered from any source -distribution. -*/ - -#include "tinyxml2.h" - -#include // yes, this one new style header, is in the Android SDK. -#if defined(ANDROID_NDK) || defined(__BORLANDC__) || defined(__QNXNTO__) -# include -# include -#else -# include -# include -#endif - -#if defined(_MSC_VER) && (_MSC_VER >= 1400 ) && (!defined WINCE) - // Microsoft Visual Studio, version 2005 and higher. Not WinCE. - /*int _snprintf_s( - char *buffer, - size_t sizeOfBuffer, - size_t count, - const char *format [, - argument] ... - );*/ - static inline int TIXML_SNPRINTF( char* buffer, size_t size, const char* format, ... ) - { - va_list va; - va_start( va, format ); - int result = vsnprintf_s( buffer, size, _TRUNCATE, format, va ); - va_end( va ); - return result; - } - - static inline int TIXML_VSNPRINTF( char* buffer, size_t size, const char* format, va_list va ) - { - int result = vsnprintf_s( buffer, size, _TRUNCATE, format, va ); - return result; - } - - #define TIXML_VSCPRINTF _vscprintf - #define TIXML_SSCANF sscanf_s -#elif defined _MSC_VER - // Microsoft Visual Studio 2003 and earlier or WinCE - #define TIXML_SNPRINTF _snprintf - #define TIXML_VSNPRINTF _vsnprintf - #define TIXML_SSCANF sscanf - #if (_MSC_VER < 1400 ) && (!defined WINCE) - // Microsoft Visual Studio 2003 and not WinCE. - #define TIXML_VSCPRINTF _vscprintf // VS2003's C runtime has this, but VC6 C runtime or WinCE SDK doesn't have. - #else - // Microsoft Visual Studio 2003 and earlier or WinCE. - static inline int TIXML_VSCPRINTF( const char* format, va_list va ) - { - int len = 512; - for (;;) { - len = len*2; - char* str = new char[len](); - const int required = _vsnprintf(str, len, format, va); - delete[] str; - if ( required != -1 ) { - TIXMLASSERT( required >= 0 ); - len = required; - break; - } - } - TIXMLASSERT( len >= 0 ); - return len; - } - #endif -#else - // GCC version 3 and higher - //#warning( "Using sn* functions." ) - #define TIXML_SNPRINTF snprintf - #define TIXML_VSNPRINTF vsnprintf - static inline int TIXML_VSCPRINTF( const char* format, va_list va ) - { - int len = vsnprintf( 0, 0, format, va ); - TIXMLASSERT( len >= 0 ); - return len; - } - #define TIXML_SSCANF sscanf -#endif - - -static const char LINE_FEED = (char)0x0a; // all line endings are normalized to LF -static const char LF = LINE_FEED; -static const char CARRIAGE_RETURN = (char)0x0d; // CR gets filtered out -static const char CR = CARRIAGE_RETURN; -static const char SINGLE_QUOTE = '\''; -static const char DOUBLE_QUOTE = '\"'; - -// Bunch of unicode info at: -// http://www.unicode.org/faq/utf_bom.html -// ef bb bf (Microsoft "lead bytes") - designates UTF-8 - -static const unsigned char TIXML_UTF_LEAD_0 = 0xefU; -static const unsigned char TIXML_UTF_LEAD_1 = 0xbbU; -static const unsigned char TIXML_UTF_LEAD_2 = 0xbfU; - -namespace tinyxml2 -{ - -struct Entity { - const char* pattern; - int length; - char value; -}; - -static const int NUM_ENTITIES = 5; -static const Entity entities[NUM_ENTITIES] = { - { "quot", 4, DOUBLE_QUOTE }, - { "amp", 3, '&' }, - { "apos", 4, SINGLE_QUOTE }, - { "lt", 2, '<' }, - { "gt", 2, '>' } -}; - - -StrPair::~StrPair() -{ - Reset(); -} - - -void StrPair::TransferTo( StrPair* other ) -{ - if ( this == other ) { - return; - } - // This in effect implements the assignment operator by "moving" - // ownership (as in auto_ptr). - - TIXMLASSERT( other != 0 ); - TIXMLASSERT( other->_flags == 0 ); - TIXMLASSERT( other->_start == 0 ); - TIXMLASSERT( other->_end == 0 ); - - other->Reset(); - - other->_flags = _flags; - other->_start = _start; - other->_end = _end; - - _flags = 0; - _start = 0; - _end = 0; -} - - -void StrPair::Reset() -{ - if ( _flags & NEEDS_DELETE ) { - delete [] _start; - } - _flags = 0; - _start = 0; - _end = 0; -} - - -void StrPair::SetStr( const char* str, int flags ) -{ - TIXMLASSERT( str ); - Reset(); - size_t len = strlen( str ); - TIXMLASSERT( _start == 0 ); - _start = new char[ len+1 ]; - memcpy( _start, str, len+1 ); - _end = _start + len; - _flags = flags | NEEDS_DELETE; -} - - -char* StrPair::ParseText( char* p, const char* endTag, int strFlags, int* curLineNumPtr ) -{ - TIXMLASSERT( p ); - TIXMLASSERT( endTag && *endTag ); - TIXMLASSERT(curLineNumPtr); - - char* start = p; - char endChar = *endTag; - size_t length = strlen( endTag ); - - // Inner loop of text parsing. - while ( *p ) { - if ( *p == endChar && strncmp( p, endTag, length ) == 0 ) { - Set( start, p, strFlags ); - return p + length; - } else if (*p == '\n') { - ++(*curLineNumPtr); - } - ++p; - TIXMLASSERT( p ); - } - return 0; -} - - -char* StrPair::ParseName( char* p ) -{ - if ( !p || !(*p) ) { - return 0; - } - if ( !XMLUtil::IsNameStartChar( *p ) ) { - return 0; - } - - char* const start = p; - ++p; - while ( *p && XMLUtil::IsNameChar( *p ) ) { - ++p; - } - - Set( start, p, 0 ); - return p; -} - - -void StrPair::CollapseWhitespace() -{ - // Adjusting _start would cause undefined behavior on delete[] - TIXMLASSERT( ( _flags & NEEDS_DELETE ) == 0 ); - // Trim leading space. - _start = XMLUtil::SkipWhiteSpace( _start, 0 ); - - if ( *_start ) { - const char* p = _start; // the read pointer - char* q = _start; // the write pointer - - while( *p ) { - if ( XMLUtil::IsWhiteSpace( *p )) { - p = XMLUtil::SkipWhiteSpace( p, 0 ); - if ( *p == 0 ) { - break; // don't write to q; this trims the trailing space. - } - *q = ' '; - ++q; - } - *q = *p; - ++q; - ++p; - } - *q = 0; - } -} - - -const char* StrPair::GetStr() -{ - TIXMLASSERT( _start ); - TIXMLASSERT( _end ); - if ( _flags & NEEDS_FLUSH ) { - *_end = 0; - _flags ^= NEEDS_FLUSH; - - if ( _flags ) { - const char* p = _start; // the read pointer - char* q = _start; // the write pointer - - while( p < _end ) { - if ( (_flags & NEEDS_NEWLINE_NORMALIZATION) && *p == CR ) { - // CR-LF pair becomes LF - // CR alone becomes LF - // LF-CR becomes LF - if ( *(p+1) == LF ) { - p += 2; - } - else { - ++p; - } - *q = LF; - ++q; - } - else if ( (_flags & NEEDS_NEWLINE_NORMALIZATION) && *p == LF ) { - if ( *(p+1) == CR ) { - p += 2; - } - else { - ++p; - } - *q = LF; - ++q; - } - else if ( (_flags & NEEDS_ENTITY_PROCESSING) && *p == '&' ) { - // Entities handled by tinyXML2: - // - special entities in the entity table [in/out] - // - numeric character reference [in] - // 中 or 中 - - if ( *(p+1) == '#' ) { - const int buflen = 10; - char buf[buflen] = { 0 }; - int len = 0; - char* adjusted = const_cast( XMLUtil::GetCharacterRef( p, buf, &len ) ); - if ( adjusted == 0 ) { - *q = *p; - ++p; - ++q; - } - else { - TIXMLASSERT( 0 <= len && len <= buflen ); - TIXMLASSERT( q + len <= adjusted ); - p = adjusted; - memcpy( q, buf, len ); - q += len; - } - } - else { - bool entityFound = false; - for( int i = 0; i < NUM_ENTITIES; ++i ) { - const Entity& entity = entities[i]; - if ( strncmp( p + 1, entity.pattern, entity.length ) == 0 - && *( p + entity.length + 1 ) == ';' ) { - // Found an entity - convert. - *q = entity.value; - ++q; - p += entity.length + 2; - entityFound = true; - break; - } - } - if ( !entityFound ) { - // fixme: treat as error? - ++p; - ++q; - } - } - } - else { - *q = *p; - ++p; - ++q; - } - } - *q = 0; - } - // The loop below has plenty going on, and this - // is a less useful mode. Break it out. - if ( _flags & NEEDS_WHITESPACE_COLLAPSING ) { - CollapseWhitespace(); - } - _flags = (_flags & NEEDS_DELETE); - } - TIXMLASSERT( _start ); - return _start; -} - - - - -// --------- XMLUtil ----------- // - -const char* XMLUtil::writeBoolTrue = "true"; -const char* XMLUtil::writeBoolFalse = "false"; - -void XMLUtil::SetBoolSerialization(const char* writeTrue, const char* writeFalse) -{ - static const char* defTrue = "true"; - static const char* defFalse = "false"; - - writeBoolTrue = (writeTrue) ? writeTrue : defTrue; - writeBoolFalse = (writeFalse) ? writeFalse : defFalse; -} - - -const char* XMLUtil::ReadBOM( const char* p, bool* bom ) -{ - TIXMLASSERT( p ); - TIXMLASSERT( bom ); - *bom = false; - const unsigned char* pu = reinterpret_cast(p); - // Check for BOM: - if ( *(pu+0) == TIXML_UTF_LEAD_0 - && *(pu+1) == TIXML_UTF_LEAD_1 - && *(pu+2) == TIXML_UTF_LEAD_2 ) { - *bom = true; - p += 3; - } - TIXMLASSERT( p ); - return p; -} - - -void XMLUtil::ConvertUTF32ToUTF8( unsigned long input, char* output, int* length ) -{ - const unsigned long BYTE_MASK = 0xBF; - const unsigned long BYTE_MARK = 0x80; - const unsigned long FIRST_BYTE_MARK[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC }; - - if (input < 0x80) { - *length = 1; - } - else if ( input < 0x800 ) { - *length = 2; - } - else if ( input < 0x10000 ) { - *length = 3; - } - else if ( input < 0x200000 ) { - *length = 4; - } - else { - *length = 0; // This code won't convert this correctly anyway. - return; - } - - output += *length; - - // Scary scary fall throughs are annotated with carefully designed comments - // to suppress compiler warnings such as -Wimplicit-fallthrough in gcc - switch (*length) { - case 4: - --output; - *output = (char)((input | BYTE_MARK) & BYTE_MASK); - input >>= 6; - //fall through - case 3: - --output; - *output = (char)((input | BYTE_MARK) & BYTE_MASK); - input >>= 6; - //fall through - case 2: - --output; - *output = (char)((input | BYTE_MARK) & BYTE_MASK); - input >>= 6; - //fall through - case 1: - --output; - *output = (char)(input | FIRST_BYTE_MARK[*length]); - break; - default: - TIXMLASSERT( false ); - } -} - - -const char* XMLUtil::GetCharacterRef( const char* p, char* value, int* length ) -{ - // Presume an entity, and pull it out. - *length = 0; - - if ( *(p+1) == '#' && *(p+2) ) { - unsigned long ucs = 0; - TIXMLASSERT( sizeof( ucs ) >= 4 ); - ptrdiff_t delta = 0; - unsigned mult = 1; - static const char SEMICOLON = ';'; - - if ( *(p+2) == 'x' ) { - // Hexadecimal. - const char* q = p+3; - if ( !(*q) ) { - return 0; - } - - q = strchr( q, SEMICOLON ); - - if ( !q ) { - return 0; - } - TIXMLASSERT( *q == SEMICOLON ); - - delta = q-p; - --q; - - while ( *q != 'x' ) { - unsigned int digit = 0; - - if ( *q >= '0' && *q <= '9' ) { - digit = *q - '0'; - } - else if ( *q >= 'a' && *q <= 'f' ) { - digit = *q - 'a' + 10; - } - else if ( *q >= 'A' && *q <= 'F' ) { - digit = *q - 'A' + 10; - } - else { - return 0; - } - TIXMLASSERT( digit < 16 ); - TIXMLASSERT( digit == 0 || mult <= UINT_MAX / digit ); - const unsigned int digitScaled = mult * digit; - TIXMLASSERT( ucs <= ULONG_MAX - digitScaled ); - ucs += digitScaled; - TIXMLASSERT( mult <= UINT_MAX / 16 ); - mult *= 16; - --q; - } - } - else { - // Decimal. - const char* q = p+2; - if ( !(*q) ) { - return 0; - } - - q = strchr( q, SEMICOLON ); - - if ( !q ) { - return 0; - } - TIXMLASSERT( *q == SEMICOLON ); - - delta = q-p; - --q; - - while ( *q != '#' ) { - if ( *q >= '0' && *q <= '9' ) { - const unsigned int digit = *q - '0'; - TIXMLASSERT( digit < 10 ); - TIXMLASSERT( digit == 0 || mult <= UINT_MAX / digit ); - const unsigned int digitScaled = mult * digit; - TIXMLASSERT( ucs <= ULONG_MAX - digitScaled ); - ucs += digitScaled; - } - else { - return 0; - } - TIXMLASSERT( mult <= UINT_MAX / 10 ); - mult *= 10; - --q; - } - } - // convert the UCS to UTF-8 - ConvertUTF32ToUTF8( ucs, value, length ); - return p + delta + 1; - } - return p+1; -} - - -void XMLUtil::ToStr( int v, char* buffer, int bufferSize ) -{ - TIXML_SNPRINTF( buffer, bufferSize, "%d", v ); -} - - -void XMLUtil::ToStr( unsigned v, char* buffer, int bufferSize ) -{ - TIXML_SNPRINTF( buffer, bufferSize, "%u", v ); -} - - -void XMLUtil::ToStr( bool v, char* buffer, int bufferSize ) -{ - TIXML_SNPRINTF( buffer, bufferSize, "%s", v ? writeBoolTrue : writeBoolFalse); -} - -/* - ToStr() of a number is a very tricky topic. - https://github.com/leethomason/tinyxml2/issues/106 -*/ -void XMLUtil::ToStr( float v, char* buffer, int bufferSize ) -{ - TIXML_SNPRINTF( buffer, bufferSize, "%.8g", v ); -} - - -void XMLUtil::ToStr( double v, char* buffer, int bufferSize ) -{ - TIXML_SNPRINTF( buffer, bufferSize, "%.17g", v ); -} - - -void XMLUtil::ToStr(int64_t v, char* buffer, int bufferSize) -{ - // horrible syntax trick to make the compiler happy about %lld - TIXML_SNPRINTF(buffer, bufferSize, "%lld", (long long)v); -} - - -bool XMLUtil::ToInt( const char* str, int* value ) -{ - if ( TIXML_SSCANF( str, "%d", value ) == 1 ) { - return true; - } - return false; -} - -bool XMLUtil::ToUnsigned( const char* str, unsigned *value ) -{ - if ( TIXML_SSCANF( str, "%u", value ) == 1 ) { - return true; - } - return false; -} - -bool XMLUtil::ToBool( const char* str, bool* value ) -{ - int ival = 0; - if ( ToInt( str, &ival )) { - *value = (ival==0) ? false : true; - return true; - } - if ( StringEqual( str, "true" ) ) { - *value = true; - return true; - } - else if ( StringEqual( str, "false" ) ) { - *value = false; - return true; - } - return false; -} - - -bool XMLUtil::ToFloat( const char* str, float* value ) -{ - if ( TIXML_SSCANF( str, "%f", value ) == 1 ) { - return true; - } - return false; -} - - -bool XMLUtil::ToDouble( const char* str, double* value ) -{ - if ( TIXML_SSCANF( str, "%lf", value ) == 1 ) { - return true; - } - return false; -} - - -bool XMLUtil::ToInt64(const char* str, int64_t* value) -{ - long long v = 0; // horrible syntax trick to make the compiler happy about %lld - if (TIXML_SSCANF(str, "%lld", &v) == 1) { - *value = (int64_t)v; - return true; - } - return false; -} - - -char* XMLDocument::Identify( char* p, XMLNode** node ) -{ - TIXMLASSERT( node ); - TIXMLASSERT( p ); - char* const start = p; - int const startLine = _parseCurLineNum; - p = XMLUtil::SkipWhiteSpace( p, &_parseCurLineNum ); - if( !*p ) { - *node = 0; - TIXMLASSERT( p ); - return p; - } - - // These strings define the matching patterns: - static const char* xmlHeader = { "( _commentPool ); - returnNode->_parseLineNum = _parseCurLineNum; - p += xmlHeaderLen; - } - else if ( XMLUtil::StringEqual( p, commentHeader, commentHeaderLen ) ) { - returnNode = CreateUnlinkedNode( _commentPool ); - returnNode->_parseLineNum = _parseCurLineNum; - p += commentHeaderLen; - } - else if ( XMLUtil::StringEqual( p, cdataHeader, cdataHeaderLen ) ) { - XMLText* text = CreateUnlinkedNode( _textPool ); - returnNode = text; - returnNode->_parseLineNum = _parseCurLineNum; - p += cdataHeaderLen; - text->SetCData( true ); - } - else if ( XMLUtil::StringEqual( p, dtdHeader, dtdHeaderLen ) ) { - returnNode = CreateUnlinkedNode( _commentPool ); - returnNode->_parseLineNum = _parseCurLineNum; - p += dtdHeaderLen; - } - else if ( XMLUtil::StringEqual( p, elementHeader, elementHeaderLen ) ) { - returnNode = CreateUnlinkedNode( _elementPool ); - returnNode->_parseLineNum = _parseCurLineNum; - p += elementHeaderLen; - } - else { - returnNode = CreateUnlinkedNode( _textPool ); - returnNode->_parseLineNum = _parseCurLineNum; // Report line of first non-whitespace character - p = start; // Back it up, all the text counts. - _parseCurLineNum = startLine; - } - - TIXMLASSERT( returnNode ); - TIXMLASSERT( p ); - *node = returnNode; - return p; -} - - -bool XMLDocument::Accept( XMLVisitor* visitor ) const -{ - TIXMLASSERT( visitor ); - if ( visitor->VisitEnter( *this ) ) { - for ( const XMLNode* node=FirstChild(); node; node=node->NextSibling() ) { - if ( !node->Accept( visitor ) ) { - break; - } - } - } - return visitor->VisitExit( *this ); -} - - -// --------- XMLNode ----------- // - -XMLNode::XMLNode( XMLDocument* doc ) : - _document( doc ), - _parent( 0 ), - _value(), - _parseLineNum( 0 ), - _firstChild( 0 ), _lastChild( 0 ), - _prev( 0 ), _next( 0 ), - _userData( 0 ), - _memPool( 0 ) -{ -} - - -XMLNode::~XMLNode() -{ - DeleteChildren(); - if ( _parent ) { - _parent->Unlink( this ); - } -} - -const char* XMLNode::Value() const -{ - // Edge case: XMLDocuments don't have a Value. Return null. - if ( this->ToDocument() ) - return 0; - return _value.GetStr(); -} - -void XMLNode::SetValue( const char* str, bool staticMem ) -{ - if ( staticMem ) { - _value.SetInternedStr( str ); - } - else { - _value.SetStr( str ); - } -} - -XMLNode* XMLNode::DeepClone(XMLDocument* target) const -{ - XMLNode* clone = this->ShallowClone(target); - if (!clone) return 0; - - for (const XMLNode* child = this->FirstChild(); child; child = child->NextSibling()) { - XMLNode* childClone = child->DeepClone(target); - TIXMLASSERT(childClone); - clone->InsertEndChild(childClone); - } - return clone; -} - -void XMLNode::DeleteChildren() -{ - while( _firstChild ) { - TIXMLASSERT( _lastChild ); - DeleteChild( _firstChild ); - } - _firstChild = _lastChild = 0; -} - - -void XMLNode::Unlink( XMLNode* child ) -{ - TIXMLASSERT( child ); - TIXMLASSERT( child->_document == _document ); - TIXMLASSERT( child->_parent == this ); - if ( child == _firstChild ) { - _firstChild = _firstChild->_next; - } - if ( child == _lastChild ) { - _lastChild = _lastChild->_prev; - } - - if ( child->_prev ) { - child->_prev->_next = child->_next; - } - if ( child->_next ) { - child->_next->_prev = child->_prev; - } - child->_next = 0; - child->_prev = 0; - child->_parent = 0; -} - - -void XMLNode::DeleteChild( XMLNode* node ) -{ - TIXMLASSERT( node ); - TIXMLASSERT( node->_document == _document ); - TIXMLASSERT( node->_parent == this ); - Unlink( node ); - TIXMLASSERT(node->_prev == 0); - TIXMLASSERT(node->_next == 0); - TIXMLASSERT(node->_parent == 0); - DeleteNode( node ); -} - - -XMLNode* XMLNode::InsertEndChild( XMLNode* addThis ) -{ - TIXMLASSERT( addThis ); - if ( addThis->_document != _document ) { - TIXMLASSERT( false ); - return 0; - } - InsertChildPreamble( addThis ); - - if ( _lastChild ) { - TIXMLASSERT( _firstChild ); - TIXMLASSERT( _lastChild->_next == 0 ); - _lastChild->_next = addThis; - addThis->_prev = _lastChild; - _lastChild = addThis; - - addThis->_next = 0; - } - else { - TIXMLASSERT( _firstChild == 0 ); - _firstChild = _lastChild = addThis; - - addThis->_prev = 0; - addThis->_next = 0; - } - addThis->_parent = this; - return addThis; -} - - -XMLNode* XMLNode::InsertFirstChild( XMLNode* addThis ) -{ - TIXMLASSERT( addThis ); - if ( addThis->_document != _document ) { - TIXMLASSERT( false ); - return 0; - } - InsertChildPreamble( addThis ); - - if ( _firstChild ) { - TIXMLASSERT( _lastChild ); - TIXMLASSERT( _firstChild->_prev == 0 ); - - _firstChild->_prev = addThis; - addThis->_next = _firstChild; - _firstChild = addThis; - - addThis->_prev = 0; - } - else { - TIXMLASSERT( _lastChild == 0 ); - _firstChild = _lastChild = addThis; - - addThis->_prev = 0; - addThis->_next = 0; - } - addThis->_parent = this; - return addThis; -} - - -XMLNode* XMLNode::InsertAfterChild( XMLNode* afterThis, XMLNode* addThis ) -{ - TIXMLASSERT( addThis ); - if ( addThis->_document != _document ) { - TIXMLASSERT( false ); - return 0; - } - - TIXMLASSERT( afterThis ); - - if ( afterThis->_parent != this ) { - TIXMLASSERT( false ); - return 0; - } - if ( afterThis == addThis ) { - // Current state: BeforeThis -> AddThis -> OneAfterAddThis - // Now AddThis must disappear from it's location and then - // reappear between BeforeThis and OneAfterAddThis. - // So just leave it where it is. - return addThis; - } - - if ( afterThis->_next == 0 ) { - // The last node or the only node. - return InsertEndChild( addThis ); - } - InsertChildPreamble( addThis ); - addThis->_prev = afterThis; - addThis->_next = afterThis->_next; - afterThis->_next->_prev = addThis; - afterThis->_next = addThis; - addThis->_parent = this; - return addThis; -} - - - - -const XMLElement* XMLNode::FirstChildElement( const char* name ) const -{ - for( const XMLNode* node = _firstChild; node; node = node->_next ) { - const XMLElement* element = node->ToElementWithName( name ); - if ( element ) { - return element; - } - } - return 0; -} - - -const XMLElement* XMLNode::LastChildElement( const char* name ) const -{ - for( const XMLNode* node = _lastChild; node; node = node->_prev ) { - const XMLElement* element = node->ToElementWithName( name ); - if ( element ) { - return element; - } - } - return 0; -} - - -const XMLElement* XMLNode::NextSiblingElement( const char* name ) const -{ - for( const XMLNode* node = _next; node; node = node->_next ) { - const XMLElement* element = node->ToElementWithName( name ); - if ( element ) { - return element; - } - } - return 0; -} - - -const XMLElement* XMLNode::PreviousSiblingElement( const char* name ) const -{ - for( const XMLNode* node = _prev; node; node = node->_prev ) { - const XMLElement* element = node->ToElementWithName( name ); - if ( element ) { - return element; - } - } - return 0; -} - - -char* XMLNode::ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr ) -{ - // This is a recursive method, but thinking about it "at the current level" - // it is a pretty simple flat list: - // - // - // - // With a special case: - // - // - // - // - // Where the closing element (/foo) *must* be the next thing after the opening - // element, and the names must match. BUT the tricky bit is that the closing - // element will be read by the child. - // - // 'endTag' is the end tag for this node, it is returned by a call to a child. - // 'parentEnd' is the end tag for the parent, which is filled in and returned. - - XMLDocument::DepthTracker tracker(_document); - if (_document->Error()) - return 0; - - while( p && *p ) { - XMLNode* node = 0; - - p = _document->Identify( p, &node ); - TIXMLASSERT( p ); - if ( node == 0 ) { - break; - } - - int initialLineNum = node->_parseLineNum; - - StrPair endTag; - p = node->ParseDeep( p, &endTag, curLineNumPtr ); - if ( !p ) { - DeleteNode( node ); - if ( !_document->Error() ) { - _document->SetError( XML_ERROR_PARSING, initialLineNum, 0); - } - break; - } - - XMLDeclaration* decl = node->ToDeclaration(); - if ( decl ) { - // Declarations are only allowed at document level - // - // Multiple declarations are allowed but all declarations - // must occur before anything else. - // - // Optimized due to a security test case. If the first node is - // a declaration, and the last node is a declaration, then only - // declarations have so far been addded. - bool wellLocated = false; - - if (ToDocument()) { - if (FirstChild()) { - wellLocated = - FirstChild() && - FirstChild()->ToDeclaration() && - LastChild() && - LastChild()->ToDeclaration(); - } - else { - wellLocated = true; - } - } - if ( !wellLocated ) { - _document->SetError( XML_ERROR_PARSING_DECLARATION, initialLineNum, "XMLDeclaration value=%s", decl->Value()); - DeleteNode( node ); - break; - } - } - - XMLElement* ele = node->ToElement(); - if ( ele ) { - // We read the end tag. Return it to the parent. - if ( ele->ClosingType() == XMLElement::CLOSING ) { - if ( parentEndTag ) { - ele->_value.TransferTo( parentEndTag ); - } - node->_memPool->SetTracked(); // created and then immediately deleted. - DeleteNode( node ); - return p; - } - - // Handle an end tag returned to this level. - // And handle a bunch of annoying errors. - bool mismatch = false; - if ( endTag.Empty() ) { - if ( ele->ClosingType() == XMLElement::OPEN ) { - mismatch = true; - } - } - else { - if ( ele->ClosingType() != XMLElement::OPEN ) { - mismatch = true; - } - else if ( !XMLUtil::StringEqual( endTag.GetStr(), ele->Name() ) ) { - mismatch = true; - } - } - if ( mismatch ) { - _document->SetError( XML_ERROR_MISMATCHED_ELEMENT, initialLineNum, "XMLElement name=%s", ele->Name()); - DeleteNode( node ); - break; - } - } - InsertEndChild( node ); - } - return 0; -} - -/*static*/ void XMLNode::DeleteNode( XMLNode* node ) -{ - if ( node == 0 ) { - return; - } - TIXMLASSERT(node->_document); - if (!node->ToDocument()) { - node->_document->MarkInUse(node); - } - - MemPool* pool = node->_memPool; - node->~XMLNode(); - pool->Free( node ); -} - -void XMLNode::InsertChildPreamble( XMLNode* insertThis ) const -{ - TIXMLASSERT( insertThis ); - TIXMLASSERT( insertThis->_document == _document ); - - if (insertThis->_parent) { - insertThis->_parent->Unlink( insertThis ); - } - else { - insertThis->_document->MarkInUse(insertThis); - insertThis->_memPool->SetTracked(); - } -} - -const XMLElement* XMLNode::ToElementWithName( const char* name ) const -{ - const XMLElement* element = this->ToElement(); - if ( element == 0 ) { - return 0; - } - if ( name == 0 ) { - return element; - } - if ( XMLUtil::StringEqual( element->Name(), name ) ) { - return element; - } - return 0; -} - -// --------- XMLText ---------- // -char* XMLText::ParseDeep( char* p, StrPair*, int* curLineNumPtr ) -{ - if ( this->CData() ) { - p = _value.ParseText( p, "]]>", StrPair::NEEDS_NEWLINE_NORMALIZATION, curLineNumPtr ); - if ( !p ) { - _document->SetError( XML_ERROR_PARSING_CDATA, _parseLineNum, 0 ); - } - return p; - } - else { - int flags = _document->ProcessEntities() ? StrPair::TEXT_ELEMENT : StrPair::TEXT_ELEMENT_LEAVE_ENTITIES; - if ( _document->WhitespaceMode() == COLLAPSE_WHITESPACE ) { - flags |= StrPair::NEEDS_WHITESPACE_COLLAPSING; - } - - p = _value.ParseText( p, "<", flags, curLineNumPtr ); - if ( p && *p ) { - return p-1; - } - if ( !p ) { - _document->SetError( XML_ERROR_PARSING_TEXT, _parseLineNum, 0 ); - } - } - return 0; -} - - -XMLNode* XMLText::ShallowClone( XMLDocument* doc ) const -{ - if ( !doc ) { - doc = _document; - } - XMLText* text = doc->NewText( Value() ); // fixme: this will always allocate memory. Intern? - text->SetCData( this->CData() ); - return text; -} - - -bool XMLText::ShallowEqual( const XMLNode* compare ) const -{ - TIXMLASSERT( compare ); - const XMLText* text = compare->ToText(); - return ( text && XMLUtil::StringEqual( text->Value(), Value() ) ); -} - - -bool XMLText::Accept( XMLVisitor* visitor ) const -{ - TIXMLASSERT( visitor ); - return visitor->Visit( *this ); -} - - -// --------- XMLComment ---------- // - -XMLComment::XMLComment( XMLDocument* doc ) : XMLNode( doc ) -{ -} - - -XMLComment::~XMLComment() -{ -} - - -char* XMLComment::ParseDeep( char* p, StrPair*, int* curLineNumPtr ) -{ - // Comment parses as text. - p = _value.ParseText( p, "-->", StrPair::COMMENT, curLineNumPtr ); - if ( p == 0 ) { - _document->SetError( XML_ERROR_PARSING_COMMENT, _parseLineNum, 0 ); - } - return p; -} - - -XMLNode* XMLComment::ShallowClone( XMLDocument* doc ) const -{ - if ( !doc ) { - doc = _document; - } - XMLComment* comment = doc->NewComment( Value() ); // fixme: this will always allocate memory. Intern? - return comment; -} - - -bool XMLComment::ShallowEqual( const XMLNode* compare ) const -{ - TIXMLASSERT( compare ); - const XMLComment* comment = compare->ToComment(); - return ( comment && XMLUtil::StringEqual( comment->Value(), Value() )); -} - - -bool XMLComment::Accept( XMLVisitor* visitor ) const -{ - TIXMLASSERT( visitor ); - return visitor->Visit( *this ); -} - - -// --------- XMLDeclaration ---------- // - -XMLDeclaration::XMLDeclaration( XMLDocument* doc ) : XMLNode( doc ) -{ -} - - -XMLDeclaration::~XMLDeclaration() -{ - //printf( "~XMLDeclaration\n" ); -} - - -char* XMLDeclaration::ParseDeep( char* p, StrPair*, int* curLineNumPtr ) -{ - // Declaration parses as text. - p = _value.ParseText( p, "?>", StrPair::NEEDS_NEWLINE_NORMALIZATION, curLineNumPtr ); - if ( p == 0 ) { - _document->SetError( XML_ERROR_PARSING_DECLARATION, _parseLineNum, 0 ); - } - return p; -} - - -XMLNode* XMLDeclaration::ShallowClone( XMLDocument* doc ) const -{ - if ( !doc ) { - doc = _document; - } - XMLDeclaration* dec = doc->NewDeclaration( Value() ); // fixme: this will always allocate memory. Intern? - return dec; -} - - -bool XMLDeclaration::ShallowEqual( const XMLNode* compare ) const -{ - TIXMLASSERT( compare ); - const XMLDeclaration* declaration = compare->ToDeclaration(); - return ( declaration && XMLUtil::StringEqual( declaration->Value(), Value() )); -} - - - -bool XMLDeclaration::Accept( XMLVisitor* visitor ) const -{ - TIXMLASSERT( visitor ); - return visitor->Visit( *this ); -} - -// --------- XMLUnknown ---------- // - -XMLUnknown::XMLUnknown( XMLDocument* doc ) : XMLNode( doc ) -{ -} - - -XMLUnknown::~XMLUnknown() -{ -} - - -char* XMLUnknown::ParseDeep( char* p, StrPair*, int* curLineNumPtr ) -{ - // Unknown parses as text. - p = _value.ParseText( p, ">", StrPair::NEEDS_NEWLINE_NORMALIZATION, curLineNumPtr ); - if ( !p ) { - _document->SetError( XML_ERROR_PARSING_UNKNOWN, _parseLineNum, 0 ); - } - return p; -} - - -XMLNode* XMLUnknown::ShallowClone( XMLDocument* doc ) const -{ - if ( !doc ) { - doc = _document; - } - XMLUnknown* text = doc->NewUnknown( Value() ); // fixme: this will always allocate memory. Intern? - return text; -} - - -bool XMLUnknown::ShallowEqual( const XMLNode* compare ) const -{ - TIXMLASSERT( compare ); - const XMLUnknown* unknown = compare->ToUnknown(); - return ( unknown && XMLUtil::StringEqual( unknown->Value(), Value() )); -} - - -bool XMLUnknown::Accept( XMLVisitor* visitor ) const -{ - TIXMLASSERT( visitor ); - return visitor->Visit( *this ); -} - -// --------- XMLAttribute ---------- // - -const char* XMLAttribute::Name() const -{ - return _name.GetStr(); -} - -const char* XMLAttribute::Value() const -{ - return _value.GetStr(); -} - -char* XMLAttribute::ParseDeep( char* p, bool processEntities, int* curLineNumPtr ) -{ - // Parse using the name rules: bug fix, was using ParseText before - p = _name.ParseName( p ); - if ( !p || !*p ) { - return 0; - } - - // Skip white space before = - p = XMLUtil::SkipWhiteSpace( p, curLineNumPtr ); - if ( *p != '=' ) { - return 0; - } - - ++p; // move up to opening quote - p = XMLUtil::SkipWhiteSpace( p, curLineNumPtr ); - if ( *p != '\"' && *p != '\'' ) { - return 0; - } - - char endTag[2] = { *p, 0 }; - ++p; // move past opening quote - - p = _value.ParseText( p, endTag, processEntities ? StrPair::ATTRIBUTE_VALUE : StrPair::ATTRIBUTE_VALUE_LEAVE_ENTITIES, curLineNumPtr ); - return p; -} - - -void XMLAttribute::SetName( const char* n ) -{ - _name.SetStr( n ); -} - - -XMLError XMLAttribute::QueryIntValue( int* value ) const -{ - if ( XMLUtil::ToInt( Value(), value )) { - return XML_SUCCESS; - } - return XML_WRONG_ATTRIBUTE_TYPE; -} - - -XMLError XMLAttribute::QueryUnsignedValue( unsigned int* value ) const -{ - if ( XMLUtil::ToUnsigned( Value(), value )) { - return XML_SUCCESS; - } - return XML_WRONG_ATTRIBUTE_TYPE; -} - - -XMLError XMLAttribute::QueryInt64Value(int64_t* value) const -{ - if (XMLUtil::ToInt64(Value(), value)) { - return XML_SUCCESS; - } - return XML_WRONG_ATTRIBUTE_TYPE; -} - - -XMLError XMLAttribute::QueryBoolValue( bool* value ) const -{ - if ( XMLUtil::ToBool( Value(), value )) { - return XML_SUCCESS; - } - return XML_WRONG_ATTRIBUTE_TYPE; -} - - -XMLError XMLAttribute::QueryFloatValue( float* value ) const -{ - if ( XMLUtil::ToFloat( Value(), value )) { - return XML_SUCCESS; - } - return XML_WRONG_ATTRIBUTE_TYPE; -} - - -XMLError XMLAttribute::QueryDoubleValue( double* value ) const -{ - if ( XMLUtil::ToDouble( Value(), value )) { - return XML_SUCCESS; - } - return XML_WRONG_ATTRIBUTE_TYPE; -} - - -void XMLAttribute::SetAttribute( const char* v ) -{ - _value.SetStr( v ); -} - - -void XMLAttribute::SetAttribute( int v ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( v, buf, BUF_SIZE ); - _value.SetStr( buf ); -} - - -void XMLAttribute::SetAttribute( unsigned v ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( v, buf, BUF_SIZE ); - _value.SetStr( buf ); -} - - -void XMLAttribute::SetAttribute(int64_t v) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr(v, buf, BUF_SIZE); - _value.SetStr(buf); -} - - - -void XMLAttribute::SetAttribute( bool v ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( v, buf, BUF_SIZE ); - _value.SetStr( buf ); -} - -void XMLAttribute::SetAttribute( double v ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( v, buf, BUF_SIZE ); - _value.SetStr( buf ); -} - -void XMLAttribute::SetAttribute( float v ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( v, buf, BUF_SIZE ); - _value.SetStr( buf ); -} - - -// --------- XMLElement ---------- // -XMLElement::XMLElement( XMLDocument* doc ) : XMLNode( doc ), - _closingType( OPEN ), - _rootAttribute( 0 ) -{ -} - - -XMLElement::~XMLElement() -{ - while( _rootAttribute ) { - XMLAttribute* next = _rootAttribute->_next; - DeleteAttribute( _rootAttribute ); - _rootAttribute = next; - } -} - - -const XMLAttribute* XMLElement::FindAttribute( const char* name ) const -{ - for( XMLAttribute* a = _rootAttribute; a; a = a->_next ) { - if ( XMLUtil::StringEqual( a->Name(), name ) ) { - return a; - } - } - return 0; -} - - -const char* XMLElement::Attribute( const char* name, const char* value ) const -{ - const XMLAttribute* a = FindAttribute( name ); - if ( !a ) { - return 0; - } - if ( !value || XMLUtil::StringEqual( a->Value(), value )) { - return a->Value(); - } - return 0; -} - -int XMLElement::IntAttribute(const char* name, int defaultValue) const -{ - int i = defaultValue; - QueryIntAttribute(name, &i); - return i; -} - -unsigned XMLElement::UnsignedAttribute(const char* name, unsigned defaultValue) const -{ - unsigned i = defaultValue; - QueryUnsignedAttribute(name, &i); - return i; -} - -int64_t XMLElement::Int64Attribute(const char* name, int64_t defaultValue) const -{ - int64_t i = defaultValue; - QueryInt64Attribute(name, &i); - return i; -} - -bool XMLElement::BoolAttribute(const char* name, bool defaultValue) const -{ - bool b = defaultValue; - QueryBoolAttribute(name, &b); - return b; -} - -double XMLElement::DoubleAttribute(const char* name, double defaultValue) const -{ - double d = defaultValue; - QueryDoubleAttribute(name, &d); - return d; -} - -float XMLElement::FloatAttribute(const char* name, float defaultValue) const -{ - float f = defaultValue; - QueryFloatAttribute(name, &f); - return f; -} - -const char* XMLElement::GetText() const -{ - if ( FirstChild() && FirstChild()->ToText() ) { - return FirstChild()->Value(); - } - return 0; -} - - -void XMLElement::SetText( const char* inText ) -{ - if ( FirstChild() && FirstChild()->ToText() ) - FirstChild()->SetValue( inText ); - else { - XMLText* theText = GetDocument()->NewText( inText ); - InsertFirstChild( theText ); - } -} - - -void XMLElement::SetText( int v ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( v, buf, BUF_SIZE ); - SetText( buf ); -} - - -void XMLElement::SetText( unsigned v ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( v, buf, BUF_SIZE ); - SetText( buf ); -} - - -void XMLElement::SetText(int64_t v) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr(v, buf, BUF_SIZE); - SetText(buf); -} - - -void XMLElement::SetText( bool v ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( v, buf, BUF_SIZE ); - SetText( buf ); -} - - -void XMLElement::SetText( float v ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( v, buf, BUF_SIZE ); - SetText( buf ); -} - - -void XMLElement::SetText( double v ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( v, buf, BUF_SIZE ); - SetText( buf ); -} - - -XMLError XMLElement::QueryIntText( int* ival ) const -{ - if ( FirstChild() && FirstChild()->ToText() ) { - const char* t = FirstChild()->Value(); - if ( XMLUtil::ToInt( t, ival ) ) { - return XML_SUCCESS; - } - return XML_CAN_NOT_CONVERT_TEXT; - } - return XML_NO_TEXT_NODE; -} - - -XMLError XMLElement::QueryUnsignedText( unsigned* uval ) const -{ - if ( FirstChild() && FirstChild()->ToText() ) { - const char* t = FirstChild()->Value(); - if ( XMLUtil::ToUnsigned( t, uval ) ) { - return XML_SUCCESS; - } - return XML_CAN_NOT_CONVERT_TEXT; - } - return XML_NO_TEXT_NODE; -} - - -XMLError XMLElement::QueryInt64Text(int64_t* ival) const -{ - if (FirstChild() && FirstChild()->ToText()) { - const char* t = FirstChild()->Value(); - if (XMLUtil::ToInt64(t, ival)) { - return XML_SUCCESS; - } - return XML_CAN_NOT_CONVERT_TEXT; - } - return XML_NO_TEXT_NODE; -} - - -XMLError XMLElement::QueryBoolText( bool* bval ) const -{ - if ( FirstChild() && FirstChild()->ToText() ) { - const char* t = FirstChild()->Value(); - if ( XMLUtil::ToBool( t, bval ) ) { - return XML_SUCCESS; - } - return XML_CAN_NOT_CONVERT_TEXT; - } - return XML_NO_TEXT_NODE; -} - - -XMLError XMLElement::QueryDoubleText( double* dval ) const -{ - if ( FirstChild() && FirstChild()->ToText() ) { - const char* t = FirstChild()->Value(); - if ( XMLUtil::ToDouble( t, dval ) ) { - return XML_SUCCESS; - } - return XML_CAN_NOT_CONVERT_TEXT; - } - return XML_NO_TEXT_NODE; -} - - -XMLError XMLElement::QueryFloatText( float* fval ) const -{ - if ( FirstChild() && FirstChild()->ToText() ) { - const char* t = FirstChild()->Value(); - if ( XMLUtil::ToFloat( t, fval ) ) { - return XML_SUCCESS; - } - return XML_CAN_NOT_CONVERT_TEXT; - } - return XML_NO_TEXT_NODE; -} - -int XMLElement::IntText(int defaultValue) const -{ - int i = defaultValue; - QueryIntText(&i); - return i; -} - -unsigned XMLElement::UnsignedText(unsigned defaultValue) const -{ - unsigned i = defaultValue; - QueryUnsignedText(&i); - return i; -} - -int64_t XMLElement::Int64Text(int64_t defaultValue) const -{ - int64_t i = defaultValue; - QueryInt64Text(&i); - return i; -} - -bool XMLElement::BoolText(bool defaultValue) const -{ - bool b = defaultValue; - QueryBoolText(&b); - return b; -} - -double XMLElement::DoubleText(double defaultValue) const -{ - double d = defaultValue; - QueryDoubleText(&d); - return d; -} - -float XMLElement::FloatText(float defaultValue) const -{ - float f = defaultValue; - QueryFloatText(&f); - return f; -} - - -XMLAttribute* XMLElement::FindOrCreateAttribute( const char* name ) -{ - XMLAttribute* last = 0; - XMLAttribute* attrib = 0; - for( attrib = _rootAttribute; - attrib; - last = attrib, attrib = attrib->_next ) { - if ( XMLUtil::StringEqual( attrib->Name(), name ) ) { - break; - } - } - if ( !attrib ) { - attrib = CreateAttribute(); - TIXMLASSERT( attrib ); - if ( last ) { - TIXMLASSERT( last->_next == 0 ); - last->_next = attrib; - } - else { - TIXMLASSERT( _rootAttribute == 0 ); - _rootAttribute = attrib; - } - attrib->SetName( name ); - } - return attrib; -} - - -void XMLElement::DeleteAttribute( const char* name ) -{ - XMLAttribute* prev = 0; - for( XMLAttribute* a=_rootAttribute; a; a=a->_next ) { - if ( XMLUtil::StringEqual( name, a->Name() ) ) { - if ( prev ) { - prev->_next = a->_next; - } - else { - _rootAttribute = a->_next; - } - DeleteAttribute( a ); - break; - } - prev = a; - } -} - - -char* XMLElement::ParseAttributes( char* p, int* curLineNumPtr ) -{ - XMLAttribute* prevAttribute = 0; - - // Read the attributes. - while( p ) { - p = XMLUtil::SkipWhiteSpace( p, curLineNumPtr ); - if ( !(*p) ) { - _document->SetError( XML_ERROR_PARSING_ELEMENT, _parseLineNum, "XMLElement name=%s", Name() ); - return 0; - } - - // attribute. - if (XMLUtil::IsNameStartChar( *p ) ) { - XMLAttribute* attrib = CreateAttribute(); - TIXMLASSERT( attrib ); - attrib->_parseLineNum = _document->_parseCurLineNum; - - int attrLineNum = attrib->_parseLineNum; - - p = attrib->ParseDeep( p, _document->ProcessEntities(), curLineNumPtr ); - if ( !p || Attribute( attrib->Name() ) ) { - DeleteAttribute( attrib ); - _document->SetError( XML_ERROR_PARSING_ATTRIBUTE, attrLineNum, "XMLElement name=%s", Name() ); - return 0; - } - // There is a minor bug here: if the attribute in the source xml - // document is duplicated, it will not be detected and the - // attribute will be doubly added. However, tracking the 'prevAttribute' - // avoids re-scanning the attribute list. Preferring performance for - // now, may reconsider in the future. - if ( prevAttribute ) { - TIXMLASSERT( prevAttribute->_next == 0 ); - prevAttribute->_next = attrib; - } - else { - TIXMLASSERT( _rootAttribute == 0 ); - _rootAttribute = attrib; - } - prevAttribute = attrib; - } - // end of the tag - else if ( *p == '>' ) { - ++p; - break; - } - // end of the tag - else if ( *p == '/' && *(p+1) == '>' ) { - _closingType = CLOSED; - return p+2; // done; sealed element. - } - else { - _document->SetError( XML_ERROR_PARSING_ELEMENT, _parseLineNum, 0 ); - return 0; - } - } - return p; -} - -void XMLElement::DeleteAttribute( XMLAttribute* attribute ) -{ - if ( attribute == 0 ) { - return; - } - MemPool* pool = attribute->_memPool; - attribute->~XMLAttribute(); - pool->Free( attribute ); -} - -XMLAttribute* XMLElement::CreateAttribute() -{ - TIXMLASSERT( sizeof( XMLAttribute ) == _document->_attributePool.ItemSize() ); - XMLAttribute* attrib = new (_document->_attributePool.Alloc() ) XMLAttribute(); - TIXMLASSERT( attrib ); - attrib->_memPool = &_document->_attributePool; - attrib->_memPool->SetTracked(); - return attrib; -} - -// -// -// foobar -// -char* XMLElement::ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr ) -{ - // Read the element name. - p = XMLUtil::SkipWhiteSpace( p, curLineNumPtr ); - - // The closing element is the form. It is - // parsed just like a regular element then deleted from - // the DOM. - if ( *p == '/' ) { - _closingType = CLOSING; - ++p; - } - - p = _value.ParseName( p ); - if ( _value.Empty() ) { - return 0; - } - - p = ParseAttributes( p, curLineNumPtr ); - if ( !p || !*p || _closingType != OPEN ) { - return p; - } - - p = XMLNode::ParseDeep( p, parentEndTag, curLineNumPtr ); - return p; -} - - - -XMLNode* XMLElement::ShallowClone( XMLDocument* doc ) const -{ - if ( !doc ) { - doc = _document; - } - XMLElement* element = doc->NewElement( Value() ); // fixme: this will always allocate memory. Intern? - for( const XMLAttribute* a=FirstAttribute(); a; a=a->Next() ) { - element->SetAttribute( a->Name(), a->Value() ); // fixme: this will always allocate memory. Intern? - } - return element; -} - - -bool XMLElement::ShallowEqual( const XMLNode* compare ) const -{ - TIXMLASSERT( compare ); - const XMLElement* other = compare->ToElement(); - if ( other && XMLUtil::StringEqual( other->Name(), Name() )) { - - const XMLAttribute* a=FirstAttribute(); - const XMLAttribute* b=other->FirstAttribute(); - - while ( a && b ) { - if ( !XMLUtil::StringEqual( a->Value(), b->Value() ) ) { - return false; - } - a = a->Next(); - b = b->Next(); - } - if ( a || b ) { - // different count - return false; - } - return true; - } - return false; -} - - -bool XMLElement::Accept( XMLVisitor* visitor ) const -{ - TIXMLASSERT( visitor ); - if ( visitor->VisitEnter( *this, _rootAttribute ) ) { - for ( const XMLNode* node=FirstChild(); node; node=node->NextSibling() ) { - if ( !node->Accept( visitor ) ) { - break; - } - } - } - return visitor->VisitExit( *this ); -} - - -// --------- XMLDocument ----------- // - -// Warning: List must match 'enum XMLError' -const char* XMLDocument::_errorNames[XML_ERROR_COUNT] = { - "XML_SUCCESS", - "XML_NO_ATTRIBUTE", - "XML_WRONG_ATTRIBUTE_TYPE", - "XML_ERROR_FILE_NOT_FOUND", - "XML_ERROR_FILE_COULD_NOT_BE_OPENED", - "XML_ERROR_FILE_READ_ERROR", - "XML_ERROR_PARSING_ELEMENT", - "XML_ERROR_PARSING_ATTRIBUTE", - "XML_ERROR_PARSING_TEXT", - "XML_ERROR_PARSING_CDATA", - "XML_ERROR_PARSING_COMMENT", - "XML_ERROR_PARSING_DECLARATION", - "XML_ERROR_PARSING_UNKNOWN", - "XML_ERROR_EMPTY_DOCUMENT", - "XML_ERROR_MISMATCHED_ELEMENT", - "XML_ERROR_PARSING", - "XML_CAN_NOT_CONVERT_TEXT", - "XML_NO_TEXT_NODE", - "XML_ELEMENT_DEPTH_EXCEEDED" -}; - - -XMLDocument::XMLDocument( bool processEntities, Whitespace whitespaceMode ) : - XMLNode( 0 ), - _writeBOM( false ), - _processEntities( processEntities ), - _errorID(XML_SUCCESS), - _whitespaceMode( whitespaceMode ), - _errorStr(), - _errorLineNum( 0 ), - _charBuffer( 0 ), - _parseCurLineNum( 0 ), - _parsingDepth(0), - _unlinked(), - _elementPool(), - _attributePool(), - _textPool(), - _commentPool() -{ - // avoid VC++ C4355 warning about 'this' in initializer list (C4355 is off by default in VS2012+) - _document = this; -} - - -XMLDocument::~XMLDocument() -{ - Clear(); -} - - -void XMLDocument::MarkInUse(XMLNode* node) -{ - TIXMLASSERT(node); - TIXMLASSERT(node->_parent == 0); - - for (int i = 0; i < _unlinked.Size(); ++i) { - if (node == _unlinked[i]) { - _unlinked.SwapRemove(i); - break; - } - } -} - -void XMLDocument::Clear() -{ - DeleteChildren(); - while( _unlinked.Size()) { - DeleteNode(_unlinked[0]); // Will remove from _unlinked as part of delete. - } - -#ifdef TINYXML2_DEBUG - const bool hadError = Error(); -#endif - ClearError(); - - delete [] _charBuffer; - _charBuffer = 0; - _parsingDepth = 0; - -#if 0 - _textPool.Trace( "text" ); - _elementPool.Trace( "element" ); - _commentPool.Trace( "comment" ); - _attributePool.Trace( "attribute" ); -#endif - -#ifdef TINYXML2_DEBUG - if ( !hadError ) { - TIXMLASSERT( _elementPool.CurrentAllocs() == _elementPool.Untracked() ); - TIXMLASSERT( _attributePool.CurrentAllocs() == _attributePool.Untracked() ); - TIXMLASSERT( _textPool.CurrentAllocs() == _textPool.Untracked() ); - TIXMLASSERT( _commentPool.CurrentAllocs() == _commentPool.Untracked() ); - } -#endif -} - - -void XMLDocument::DeepCopy(XMLDocument* target) const -{ - TIXMLASSERT(target); - if (target == this) { - return; // technically success - a no-op. - } - - target->Clear(); - for (const XMLNode* node = this->FirstChild(); node; node = node->NextSibling()) { - target->InsertEndChild(node->DeepClone(target)); - } -} - -XMLElement* XMLDocument::NewElement( const char* name ) -{ - XMLElement* ele = CreateUnlinkedNode( _elementPool ); - ele->SetName( name ); - return ele; -} - - -XMLComment* XMLDocument::NewComment( const char* str ) -{ - XMLComment* comment = CreateUnlinkedNode( _commentPool ); - comment->SetValue( str ); - return comment; -} - - -XMLText* XMLDocument::NewText( const char* str ) -{ - XMLText* text = CreateUnlinkedNode( _textPool ); - text->SetValue( str ); - return text; -} - - -XMLDeclaration* XMLDocument::NewDeclaration( const char* str ) -{ - XMLDeclaration* dec = CreateUnlinkedNode( _commentPool ); - dec->SetValue( str ? str : "xml version=\"1.0\" encoding=\"UTF-8\"" ); - return dec; -} - - -XMLUnknown* XMLDocument::NewUnknown( const char* str ) -{ - XMLUnknown* unk = CreateUnlinkedNode( _commentPool ); - unk->SetValue( str ); - return unk; -} - -static FILE* callfopen( const char* filepath, const char* mode ) -{ - TIXMLASSERT( filepath ); - TIXMLASSERT( mode ); -#if defined(_MSC_VER) && (_MSC_VER >= 1400 ) && (!defined WINCE) - FILE* fp = 0; - errno_t err = fopen_s( &fp, filepath, mode ); - if ( err ) { - return 0; - } -#else - FILE* fp = fopen( filepath, mode ); -#endif - return fp; -} - -void XMLDocument::DeleteNode( XMLNode* node ) { - TIXMLASSERT( node ); - TIXMLASSERT(node->_document == this ); - if (node->_parent) { - node->_parent->DeleteChild( node ); - } - else { - // Isn't in the tree. - // Use the parent delete. - // Also, we need to mark it tracked: we 'know' - // it was never used. - node->_memPool->SetTracked(); - // Call the static XMLNode version: - XMLNode::DeleteNode(node); - } -} - - -XMLError XMLDocument::LoadFile( const char* filename ) -{ - if ( !filename ) { - TIXMLASSERT( false ); - SetError( XML_ERROR_FILE_COULD_NOT_BE_OPENED, 0, "filename=" ); - return _errorID; - } - - Clear(); - FILE* fp = callfopen( filename, "rb" ); - if ( !fp ) { - SetError( XML_ERROR_FILE_NOT_FOUND, 0, "filename=%s", filename ); - return _errorID; - } - LoadFile( fp ); - fclose( fp ); - return _errorID; -} - -// This is likely overengineered template art to have a check that unsigned long value incremented -// by one still fits into size_t. If size_t type is larger than unsigned long type -// (x86_64-w64-mingw32 target) then the check is redundant and gcc and clang emit -// -Wtype-limits warning. This piece makes the compiler select code with a check when a check -// is useful and code with no check when a check is redundant depending on how size_t and unsigned long -// types sizes relate to each other. -template -= sizeof(size_t))> -struct LongFitsIntoSizeTMinusOne { - static bool Fits( unsigned long value ) - { - return value < (size_t)-1; - } -}; - -template <> -struct LongFitsIntoSizeTMinusOne { - static bool Fits( unsigned long ) - { - return true; - } -}; - -XMLError XMLDocument::LoadFile( FILE* fp ) -{ - Clear(); - - fseek( fp, 0, SEEK_SET ); - if ( fgetc( fp ) == EOF && ferror( fp ) != 0 ) { - SetError( XML_ERROR_FILE_READ_ERROR, 0, 0 ); - return _errorID; - } - - fseek( fp, 0, SEEK_END ); - const long filelength = ftell( fp ); - fseek( fp, 0, SEEK_SET ); - if ( filelength == -1L ) { - SetError( XML_ERROR_FILE_READ_ERROR, 0, 0 ); - return _errorID; - } - TIXMLASSERT( filelength >= 0 ); - - if ( !LongFitsIntoSizeTMinusOne<>::Fits( filelength ) ) { - // Cannot handle files which won't fit in buffer together with null terminator - SetError( XML_ERROR_FILE_READ_ERROR, 0, 0 ); - return _errorID; - } - - if ( filelength == 0 ) { - SetError( XML_ERROR_EMPTY_DOCUMENT, 0, 0 ); - return _errorID; - } - - const size_t size = filelength; - TIXMLASSERT( _charBuffer == 0 ); - _charBuffer = new char[size+1]; - size_t read = fread( _charBuffer, 1, size, fp ); - if ( read != size ) { - SetError( XML_ERROR_FILE_READ_ERROR, 0, 0 ); - return _errorID; - } - - _charBuffer[size] = 0; - - Parse(); - return _errorID; -} - - -XMLError XMLDocument::SaveFile( const char* filename, bool compact ) -{ - if ( !filename ) { - TIXMLASSERT( false ); - SetError( XML_ERROR_FILE_COULD_NOT_BE_OPENED, 0, "filename=" ); - return _errorID; - } - - FILE* fp = callfopen( filename, "w" ); - if ( !fp ) { - SetError( XML_ERROR_FILE_COULD_NOT_BE_OPENED, 0, "filename=%s", filename ); - return _errorID; - } - SaveFile(fp, compact); - fclose( fp ); - return _errorID; -} - - -XMLError XMLDocument::SaveFile( FILE* fp, bool compact ) -{ - // Clear any error from the last save, otherwise it will get reported - // for *this* call. - ClearError(); - XMLPrinter stream( fp, compact ); - Print( &stream ); - return _errorID; -} - - -XMLError XMLDocument::Parse( const char* p, size_t len ) -{ - Clear(); - - if ( len == 0 || !p || !*p ) { - SetError( XML_ERROR_EMPTY_DOCUMENT, 0, 0 ); - return _errorID; - } - if ( len == (size_t)(-1) ) { - len = strlen( p ); - } - TIXMLASSERT( _charBuffer == 0 ); - _charBuffer = new char[ len+1 ]; - memcpy( _charBuffer, p, len ); - _charBuffer[len] = 0; - - Parse(); - if ( Error() ) { - // clean up now essentially dangling memory. - // and the parse fail can put objects in the - // pools that are dead and inaccessible. - DeleteChildren(); - _elementPool.Clear(); - _attributePool.Clear(); - _textPool.Clear(); - _commentPool.Clear(); - } - return _errorID; -} - - -void XMLDocument::Print( XMLPrinter* streamer ) const -{ - if ( streamer ) { - Accept( streamer ); - } - else { - XMLPrinter stdoutStreamer( stdout ); - Accept( &stdoutStreamer ); - } -} - - -void XMLDocument::SetError( XMLError error, int lineNum, const char* format, ... ) -{ - TIXMLASSERT( error >= 0 && error < XML_ERROR_COUNT ); - _errorID = error; - _errorLineNum = lineNum; - _errorStr.Reset(); - - size_t BUFFER_SIZE = 1000; - char* buffer = new char[BUFFER_SIZE]; - - TIXMLASSERT(sizeof(error) <= sizeof(int)); - TIXML_SNPRINTF(buffer, BUFFER_SIZE, "Error=%s ErrorID=%d (0x%x) Line number=%d", ErrorIDToName(error), int(error), int(error), lineNum); - - if (format) { - size_t len = strlen(buffer); - TIXML_SNPRINTF(buffer + len, BUFFER_SIZE - len, ": "); - len = strlen(buffer); - - va_list va; - va_start(va, format); - TIXML_VSNPRINTF(buffer + len, BUFFER_SIZE - len, format, va); - va_end(va); - } - _errorStr.SetStr(buffer); - delete[] buffer; -} - - -/*static*/ const char* XMLDocument::ErrorIDToName(XMLError errorID) -{ - TIXMLASSERT( errorID >= 0 && errorID < XML_ERROR_COUNT ); - const char* errorName = _errorNames[errorID]; - TIXMLASSERT( errorName && errorName[0] ); - return errorName; -} - -const char* XMLDocument::ErrorStr() const -{ - return _errorStr.Empty() ? "" : _errorStr.GetStr(); -} - - -void XMLDocument::PrintError() const -{ - printf("%s\n", ErrorStr()); -} - -const char* XMLDocument::ErrorName() const -{ - return ErrorIDToName(_errorID); -} - -void XMLDocument::Parse() -{ - TIXMLASSERT( NoChildren() ); // Clear() must have been called previously - TIXMLASSERT( _charBuffer ); - _parseCurLineNum = 1; - _parseLineNum = 1; - char* p = _charBuffer; - p = XMLUtil::SkipWhiteSpace( p, &_parseCurLineNum ); - p = const_cast( XMLUtil::ReadBOM( p, &_writeBOM ) ); - if ( !*p ) { - SetError( XML_ERROR_EMPTY_DOCUMENT, 0, 0 ); - return; - } - ParseDeep(p, 0, &_parseCurLineNum ); -} - -void XMLDocument::PushDepth() -{ - _parsingDepth++; - if (_parsingDepth == TINYXML2_MAX_ELEMENT_DEPTH) { - SetError(XML_ELEMENT_DEPTH_EXCEEDED, _parseCurLineNum, "Element nesting is too deep." ); - } -} - -void XMLDocument::PopDepth() -{ - TIXMLASSERT(_parsingDepth > 0); - --_parsingDepth; -} - -XMLPrinter::XMLPrinter( FILE* file, bool compact, int depth ) : - _elementJustOpened( false ), - _stack(), - _firstElement( true ), - _fp( file ), - _depth( depth ), - _textDepth( -1 ), - _processEntities( true ), - _compactMode( compact ), - _buffer() -{ - for( int i=0; i'] = true; // not required, but consistency is nice - _buffer.Push( 0 ); -} - - -void XMLPrinter::Print( const char* format, ... ) -{ - va_list va; - va_start( va, format ); - - if ( _fp ) { - vfprintf( _fp, format, va ); - } - else { - const int len = TIXML_VSCPRINTF( format, va ); - // Close out and re-start the va-args - va_end( va ); - TIXMLASSERT( len >= 0 ); - va_start( va, format ); - TIXMLASSERT( _buffer.Size() > 0 && _buffer[_buffer.Size() - 1] == 0 ); - char* p = _buffer.PushArr( len ) - 1; // back up over the null terminator. - TIXML_VSNPRINTF( p, len+1, format, va ); - } - va_end( va ); -} - - -void XMLPrinter::Write( const char* data, size_t size ) -{ - if ( _fp ) { - fwrite ( data , sizeof(char), size, _fp); - } - else { - char* p = _buffer.PushArr( static_cast(size) ) - 1; // back up over the null terminator. - memcpy( p, data, size ); - p[size] = 0; - } -} - - -void XMLPrinter::Putc( char ch ) -{ - if ( _fp ) { - fputc ( ch, _fp); - } - else { - char* p = _buffer.PushArr( sizeof(char) ) - 1; // back up over the null terminator. - p[0] = ch; - p[1] = 0; - } -} - - -void XMLPrinter::PrintSpace( int depth ) -{ - for( int i=0; i 0 && *q < ENTITY_RANGE ) { - // Check for entities. If one is found, flush - // the stream up until the entity, write the - // entity, and keep looking. - if ( flag[(unsigned char)(*q)] ) { - while ( p < q ) { - const size_t delta = q - p; - const int toPrint = ( INT_MAX < delta ) ? INT_MAX : (int)delta; - Write( p, toPrint ); - p += toPrint; - } - bool entityPatternPrinted = false; - for( int i=0; i( bom ) ); - } - if ( writeDec ) { - PushDeclaration( "xml version=\"1.0\"" ); - } -} - - -void XMLPrinter::OpenElement( const char* name, bool compactMode ) -{ - SealElementIfJustOpened(); - _stack.Push( name ); - - if ( _textDepth < 0 && !_firstElement && !compactMode ) { - Putc( '\n' ); - } - if ( !compactMode ) { - PrintSpace( _depth ); - } - - Write ( "<" ); - Write ( name ); - - _elementJustOpened = true; - _firstElement = false; - ++_depth; -} - - -void XMLPrinter::PushAttribute( const char* name, const char* value ) -{ - TIXMLASSERT( _elementJustOpened ); - Putc ( ' ' ); - Write( name ); - Write( "=\"" ); - PrintString( value, false ); - Putc ( '\"' ); -} - - -void XMLPrinter::PushAttribute( const char* name, int v ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( v, buf, BUF_SIZE ); - PushAttribute( name, buf ); -} - - -void XMLPrinter::PushAttribute( const char* name, unsigned v ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( v, buf, BUF_SIZE ); - PushAttribute( name, buf ); -} - - -void XMLPrinter::PushAttribute(const char* name, int64_t v) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr(v, buf, BUF_SIZE); - PushAttribute(name, buf); -} - - -void XMLPrinter::PushAttribute( const char* name, bool v ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( v, buf, BUF_SIZE ); - PushAttribute( name, buf ); -} - - -void XMLPrinter::PushAttribute( const char* name, double v ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( v, buf, BUF_SIZE ); - PushAttribute( name, buf ); -} - - -void XMLPrinter::CloseElement( bool compactMode ) -{ - --_depth; - const char* name = _stack.Pop(); - - if ( _elementJustOpened ) { - Write( "/>" ); - } - else { - if ( _textDepth < 0 && !compactMode) { - Putc( '\n' ); - PrintSpace( _depth ); - } - Write ( "" ); - } - - if ( _textDepth == _depth ) { - _textDepth = -1; - } - if ( _depth == 0 && !compactMode) { - Putc( '\n' ); - } - _elementJustOpened = false; -} - - -void XMLPrinter::SealElementIfJustOpened() -{ - if ( !_elementJustOpened ) { - return; - } - _elementJustOpened = false; - Putc( '>' ); -} - - -void XMLPrinter::PushText( const char* text, bool cdata ) -{ - _textDepth = _depth-1; - - SealElementIfJustOpened(); - if ( cdata ) { - Write( "" ); - } - else { - PrintString( text, true ); - } -} - -void XMLPrinter::PushText( int64_t value ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( value, buf, BUF_SIZE ); - PushText( buf, false ); -} - -void XMLPrinter::PushText( int value ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( value, buf, BUF_SIZE ); - PushText( buf, false ); -} - - -void XMLPrinter::PushText( unsigned value ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( value, buf, BUF_SIZE ); - PushText( buf, false ); -} - - -void XMLPrinter::PushText( bool value ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( value, buf, BUF_SIZE ); - PushText( buf, false ); -} - - -void XMLPrinter::PushText( float value ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( value, buf, BUF_SIZE ); - PushText( buf, false ); -} - - -void XMLPrinter::PushText( double value ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( value, buf, BUF_SIZE ); - PushText( buf, false ); -} - - -void XMLPrinter::PushComment( const char* comment ) -{ - SealElementIfJustOpened(); - if ( _textDepth < 0 && !_firstElement && !_compactMode) { - Putc( '\n' ); - PrintSpace( _depth ); - } - _firstElement = false; - - Write( "" ); -} - - -void XMLPrinter::PushDeclaration( const char* value ) -{ - SealElementIfJustOpened(); - if ( _textDepth < 0 && !_firstElement && !_compactMode) { - Putc( '\n' ); - PrintSpace( _depth ); - } - _firstElement = false; - - Write( "" ); -} - - -void XMLPrinter::PushUnknown( const char* value ) -{ - SealElementIfJustOpened(); - if ( _textDepth < 0 && !_firstElement && !_compactMode) { - Putc( '\n' ); - PrintSpace( _depth ); - } - _firstElement = false; - - Write( "' ); -} - - -bool XMLPrinter::VisitEnter( const XMLDocument& doc ) -{ - _processEntities = doc.ProcessEntities(); - if ( doc.HasBOM() ) { - PushHeader( true, false ); - } - return true; -} - - -bool XMLPrinter::VisitEnter( const XMLElement& element, const XMLAttribute* attribute ) -{ - const XMLElement* parentElem = 0; - if ( element.Parent() ) { - parentElem = element.Parent()->ToElement(); - } - const bool compactMode = parentElem ? CompactMode( *parentElem ) : _compactMode; - OpenElement( element.Name(), compactMode ); - while ( attribute ) { - PushAttribute( attribute->Name(), attribute->Value() ); - attribute = attribute->Next(); - } - return true; -} - - -bool XMLPrinter::VisitExit( const XMLElement& element ) -{ - CloseElement( CompactMode(element) ); - return true; -} - - -bool XMLPrinter::Visit( const XMLText& text ) -{ - PushText( text.Value(), text.CData() ); - return true; -} - - -bool XMLPrinter::Visit( const XMLComment& comment ) -{ - PushComment( comment.Value() ); - return true; -} - -bool XMLPrinter::Visit( const XMLDeclaration& declaration ) -{ - PushDeclaration( declaration.Value() ); - return true; -} - - -bool XMLPrinter::Visit( const XMLUnknown& unknown ) -{ - PushUnknown( unknown.Value() ); - return true; -} - -} // namespace tinyxml2 diff --git a/tools/ZAPD/lib/tinyxml2/tinyxml2.h b/tools/ZAPD/lib/tinyxml2/tinyxml2.h deleted file mode 100644 index 7cd3127363..0000000000 --- a/tools/ZAPD/lib/tinyxml2/tinyxml2.h +++ /dev/null @@ -1,2309 +0,0 @@ -/* -Original code by Lee Thomason (www.grinninglizard.com) - -This software is provided 'as-is', without any express or implied -warranty. In no event will the authors be held liable for any -damages arising from the use of this software. - -Permission is granted to anyone to use this software for any -purpose, including commercial applications, and to alter it and -redistribute it freely, subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must -not claim that you wrote the original software. If you use this -software in a product, an acknowledgment in the product documentation -would be appreciated but is not required. - -2. Altered source versions must be plainly marked as such, and -must not be misrepresented as being the original software. - -3. This notice may not be removed or altered from any source -distribution. -*/ - -#ifndef TINYXML2_INCLUDED -#define TINYXML2_INCLUDED - -#if defined(ANDROID_NDK) || defined(__BORLANDC__) || defined(__QNXNTO__) -# include -# include -# include -# include -# include -# if defined(__PS3__) -# include -# endif -#else -# include -# include -# include -# include -# include -#endif -#include - -/* - TODO: intern strings instead of allocation. -*/ -/* - gcc: - g++ -Wall -DTINYXML2_DEBUG tinyxml2.cpp xmltest.cpp -o gccxmltest.exe - - Formatting, Artistic Style: - AStyle.exe --style=1tbs --indent-switches --break-closing-brackets --indent-preprocessor tinyxml2.cpp tinyxml2.h -*/ - -#if defined( _DEBUG ) || defined (__DEBUG__) -# ifndef TINYXML2_DEBUG -# define TINYXML2_DEBUG -# endif -#endif - -#ifdef _MSC_VER -# pragma warning(push) -# pragma warning(disable: 4251) -#endif - -#ifdef _WIN32 -# ifdef TINYXML2_EXPORT -# define TINYXML2_LIB __declspec(dllexport) -# elif defined(TINYXML2_IMPORT) -# define TINYXML2_LIB __declspec(dllimport) -# else -# define TINYXML2_LIB -# endif -#elif __GNUC__ >= 4 -# define TINYXML2_LIB __attribute__((visibility("default"))) -#else -# define TINYXML2_LIB -#endif - - -#if defined(TINYXML2_DEBUG) -# if defined(_MSC_VER) -# // "(void)0," is for suppressing C4127 warning in "assert(false)", "assert(true)" and the like -# define TIXMLASSERT( x ) if ( !((void)0,(x))) { __debugbreak(); } -# elif defined (ANDROID_NDK) -# include -# define TIXMLASSERT( x ) if ( !(x)) { __android_log_assert( "assert", "grinliz", "ASSERT in '%s' at %d.", __FILE__, __LINE__ ); } -# else -# include -# define TIXMLASSERT assert -# endif -#else -# define TIXMLASSERT( x ) {} -#endif - - -/* Versioning, past 1.0.14: - http://semver.org/ -*/ -static const int TIXML2_MAJOR_VERSION = 7; -static const int TIXML2_MINOR_VERSION = 0; -static const int TIXML2_PATCH_VERSION = 1; - -#define TINYXML2_MAJOR_VERSION 7 -#define TINYXML2_MINOR_VERSION 0 -#define TINYXML2_PATCH_VERSION 1 - -// A fixed element depth limit is problematic. There needs to be a -// limit to avoid a stack overflow. However, that limit varies per -// system, and the capacity of the stack. On the other hand, it's a trivial -// attack that can result from ill, malicious, or even correctly formed XML, -// so there needs to be a limit in place. -static const int TINYXML2_MAX_ELEMENT_DEPTH = 100; - -namespace tinyxml2 -{ -class XMLDocument; -class XMLElement; -class XMLAttribute; -class XMLComment; -class XMLText; -class XMLDeclaration; -class XMLUnknown; -class XMLPrinter; - -/* - A class that wraps strings. Normally stores the start and end - pointers into the XML file itself, and will apply normalization - and entity translation if actually read. Can also store (and memory - manage) a traditional char[] - - Isn't clear why TINYXML2_LIB is needed; but seems to fix #719 -*/ -class TINYXML2_LIB StrPair -{ -public: - enum { - NEEDS_ENTITY_PROCESSING = 0x01, - NEEDS_NEWLINE_NORMALIZATION = 0x02, - NEEDS_WHITESPACE_COLLAPSING = 0x04, - - TEXT_ELEMENT = NEEDS_ENTITY_PROCESSING | NEEDS_NEWLINE_NORMALIZATION, - TEXT_ELEMENT_LEAVE_ENTITIES = NEEDS_NEWLINE_NORMALIZATION, - ATTRIBUTE_NAME = 0, - ATTRIBUTE_VALUE = NEEDS_ENTITY_PROCESSING | NEEDS_NEWLINE_NORMALIZATION, - ATTRIBUTE_VALUE_LEAVE_ENTITIES = NEEDS_NEWLINE_NORMALIZATION, - COMMENT = NEEDS_NEWLINE_NORMALIZATION - }; - - StrPair() : _flags( 0 ), _start( 0 ), _end( 0 ) {} - ~StrPair(); - - void Set( char* start, char* end, int flags ) { - TIXMLASSERT( start ); - TIXMLASSERT( end ); - Reset(); - _start = start; - _end = end; - _flags = flags | NEEDS_FLUSH; - } - - const char* GetStr(); - - bool Empty() const { - return _start == _end; - } - - void SetInternedStr( const char* str ) { - Reset(); - _start = const_cast(str); - } - - void SetStr( const char* str, int flags=0 ); - - char* ParseText( char* in, const char* endTag, int strFlags, int* curLineNumPtr ); - char* ParseName( char* in ); - - void TransferTo( StrPair* other ); - void Reset(); - -private: - void CollapseWhitespace(); - - enum { - NEEDS_FLUSH = 0x100, - NEEDS_DELETE = 0x200 - }; - - int _flags; - char* _start; - char* _end; - - StrPair( const StrPair& other ); // not supported - void operator=( const StrPair& other ); // not supported, use TransferTo() -}; - - -/* - A dynamic array of Plain Old Data. Doesn't support constructors, etc. - Has a small initial memory pool, so that low or no usage will not - cause a call to new/delete -*/ -template -class DynArray -{ -public: - DynArray() : - _mem( _pool ), - _allocated( INITIAL_SIZE ), - _size( 0 ) - { - } - - ~DynArray() { - if ( _mem != _pool ) { - delete [] _mem; - } - } - - void Clear() { - _size = 0; - } - - void Push( T t ) { - TIXMLASSERT( _size < INT_MAX ); - EnsureCapacity( _size+1 ); - _mem[_size] = t; - ++_size; - } - - T* PushArr( int count ) { - TIXMLASSERT( count >= 0 ); - TIXMLASSERT( _size <= INT_MAX - count ); - EnsureCapacity( _size+count ); - T* ret = &_mem[_size]; - _size += count; - return ret; - } - - T Pop() { - TIXMLASSERT( _size > 0 ); - --_size; - return _mem[_size]; - } - - void PopArr( int count ) { - TIXMLASSERT( _size >= count ); - _size -= count; - } - - bool Empty() const { - return _size == 0; - } - - T& operator[](int i) { - TIXMLASSERT( i>= 0 && i < _size ); - return _mem[i]; - } - - const T& operator[](int i) const { - TIXMLASSERT( i>= 0 && i < _size ); - return _mem[i]; - } - - const T& PeekTop() const { - TIXMLASSERT( _size > 0 ); - return _mem[ _size - 1]; - } - - int Size() const { - TIXMLASSERT( _size >= 0 ); - return _size; - } - - int Capacity() const { - TIXMLASSERT( _allocated >= INITIAL_SIZE ); - return _allocated; - } - - void SwapRemove(int i) { - TIXMLASSERT(i >= 0 && i < _size); - TIXMLASSERT(_size > 0); - _mem[i] = _mem[_size - 1]; - --_size; - } - - const T* Mem() const { - TIXMLASSERT( _mem ); - return _mem; - } - - T* Mem() { - TIXMLASSERT( _mem ); - return _mem; - } - -private: - DynArray( const DynArray& ); // not supported - void operator=( const DynArray& ); // not supported - - void EnsureCapacity( int cap ) { - TIXMLASSERT( cap > 0 ); - if ( cap > _allocated ) { - TIXMLASSERT( cap <= INT_MAX / 2 ); - int newAllocated = cap * 2; - T* newMem = new T[newAllocated]; - TIXMLASSERT( newAllocated >= _size ); - memcpy( newMem, _mem, sizeof(T)*_size ); // warning: not using constructors, only works for PODs - if ( _mem != _pool ) { - delete [] _mem; - } - _mem = newMem; - _allocated = newAllocated; - } - } - - T* _mem; - T _pool[INITIAL_SIZE]; - int _allocated; // objects allocated - int _size; // number objects in use -}; - - -/* - Parent virtual class of a pool for fast allocation - and deallocation of objects. -*/ -class MemPool -{ -public: - MemPool() {} - virtual ~MemPool() {} - - virtual int ItemSize() const = 0; - virtual void* Alloc() = 0; - virtual void Free( void* ) = 0; - virtual void SetTracked() = 0; -}; - - -/* - Template child class to create pools of the correct type. -*/ -template< int ITEM_SIZE > -class MemPoolT : public MemPool -{ -public: - MemPoolT() : _blockPtrs(), _root(0), _currentAllocs(0), _nAllocs(0), _maxAllocs(0), _nUntracked(0) {} - ~MemPoolT() { - MemPoolT< ITEM_SIZE >::Clear(); - } - - void Clear() { - // Delete the blocks. - while( !_blockPtrs.Empty()) { - Block* lastBlock = _blockPtrs.Pop(); - delete lastBlock; - } - _root = 0; - _currentAllocs = 0; - _nAllocs = 0; - _maxAllocs = 0; - _nUntracked = 0; - } - - virtual int ItemSize() const { - return ITEM_SIZE; - } - int CurrentAllocs() const { - return _currentAllocs; - } - - virtual void* Alloc() { - if ( !_root ) { - // Need a new block. - Block* block = new Block(); - _blockPtrs.Push( block ); - - Item* blockItems = block->items; - for( int i = 0; i < ITEMS_PER_BLOCK - 1; ++i ) { - blockItems[i].next = &(blockItems[i + 1]); - } - blockItems[ITEMS_PER_BLOCK - 1].next = 0; - _root = blockItems; - } - Item* const result = _root; - TIXMLASSERT( result != 0 ); - _root = _root->next; - - ++_currentAllocs; - if ( _currentAllocs > _maxAllocs ) { - _maxAllocs = _currentAllocs; - } - ++_nAllocs; - ++_nUntracked; - return result; - } - - virtual void Free( void* mem ) { - if ( !mem ) { - return; - } - --_currentAllocs; - Item* item = static_cast( mem ); -#ifdef TINYXML2_DEBUG - memset( item, 0xfe, sizeof( *item ) ); -#endif - item->next = _root; - _root = item; - } - void Trace( const char* name ) { - printf( "Mempool %s watermark=%d [%dk] current=%d size=%d nAlloc=%d blocks=%d\n", - name, _maxAllocs, _maxAllocs * ITEM_SIZE / 1024, _currentAllocs, - ITEM_SIZE, _nAllocs, _blockPtrs.Size() ); - } - - void SetTracked() { - --_nUntracked; - } - - int Untracked() const { - return _nUntracked; - } - - // This number is perf sensitive. 4k seems like a good tradeoff on my machine. - // The test file is large, 170k. - // Release: VS2010 gcc(no opt) - // 1k: 4000 - // 2k: 4000 - // 4k: 3900 21000 - // 16k: 5200 - // 32k: 4300 - // 64k: 4000 21000 - // Declared public because some compilers do not accept to use ITEMS_PER_BLOCK - // in private part if ITEMS_PER_BLOCK is private - enum { ITEMS_PER_BLOCK = (4 * 1024) / ITEM_SIZE }; - -private: - MemPoolT( const MemPoolT& ); // not supported - void operator=( const MemPoolT& ); // not supported - - union Item { - Item* next; - char itemData[ITEM_SIZE]; - }; - struct Block { - Item items[ITEMS_PER_BLOCK]; - }; - DynArray< Block*, 10 > _blockPtrs; - Item* _root; - - int _currentAllocs; - int _nAllocs; - int _maxAllocs; - int _nUntracked; -}; - - - -/** - Implements the interface to the "Visitor pattern" (see the Accept() method.) - If you call the Accept() method, it requires being passed a XMLVisitor - class to handle callbacks. For nodes that contain other nodes (Document, Element) - you will get called with a VisitEnter/VisitExit pair. Nodes that are always leafs - are simply called with Visit(). - - If you return 'true' from a Visit method, recursive parsing will continue. If you return - false, no children of this node or its siblings will be visited. - - All flavors of Visit methods have a default implementation that returns 'true' (continue - visiting). You need to only override methods that are interesting to you. - - Generally Accept() is called on the XMLDocument, although all nodes support visiting. - - You should never change the document from a callback. - - @sa XMLNode::Accept() -*/ -class TINYXML2_LIB XMLVisitor -{ -public: - virtual ~XMLVisitor() {} - - /// Visit a document. - virtual bool VisitEnter( const XMLDocument& /*doc*/ ) { - return true; - } - /// Visit a document. - virtual bool VisitExit( const XMLDocument& /*doc*/ ) { - return true; - } - - /// Visit an element. - virtual bool VisitEnter( const XMLElement& /*element*/, const XMLAttribute* /*firstAttribute*/ ) { - return true; - } - /// Visit an element. - virtual bool VisitExit( const XMLElement& /*element*/ ) { - return true; - } - - /// Visit a declaration. - virtual bool Visit( const XMLDeclaration& /*declaration*/ ) { - return true; - } - /// Visit a text node. - virtual bool Visit( const XMLText& /*text*/ ) { - return true; - } - /// Visit a comment node. - virtual bool Visit( const XMLComment& /*comment*/ ) { - return true; - } - /// Visit an unknown node. - virtual bool Visit( const XMLUnknown& /*unknown*/ ) { - return true; - } -}; - -// WARNING: must match XMLDocument::_errorNames[] -enum XMLError { - XML_SUCCESS = 0, - XML_NO_ATTRIBUTE, - XML_WRONG_ATTRIBUTE_TYPE, - XML_ERROR_FILE_NOT_FOUND, - XML_ERROR_FILE_COULD_NOT_BE_OPENED, - XML_ERROR_FILE_READ_ERROR, - XML_ERROR_PARSING_ELEMENT, - XML_ERROR_PARSING_ATTRIBUTE, - XML_ERROR_PARSING_TEXT, - XML_ERROR_PARSING_CDATA, - XML_ERROR_PARSING_COMMENT, - XML_ERROR_PARSING_DECLARATION, - XML_ERROR_PARSING_UNKNOWN, - XML_ERROR_EMPTY_DOCUMENT, - XML_ERROR_MISMATCHED_ELEMENT, - XML_ERROR_PARSING, - XML_CAN_NOT_CONVERT_TEXT, - XML_NO_TEXT_NODE, - XML_ELEMENT_DEPTH_EXCEEDED, - - XML_ERROR_COUNT -}; - - -/* - Utility functionality. -*/ -class TINYXML2_LIB XMLUtil -{ -public: - static const char* SkipWhiteSpace( const char* p, int* curLineNumPtr ) { - TIXMLASSERT( p ); - - while( IsWhiteSpace(*p) ) { - if (curLineNumPtr && *p == '\n') { - ++(*curLineNumPtr); - } - ++p; - } - TIXMLASSERT( p ); - return p; - } - static char* SkipWhiteSpace( char* p, int* curLineNumPtr ) { - return const_cast( SkipWhiteSpace( const_cast(p), curLineNumPtr ) ); - } - - // Anything in the high order range of UTF-8 is assumed to not be whitespace. This isn't - // correct, but simple, and usually works. - static bool IsWhiteSpace( char p ) { - return !IsUTF8Continuation(p) && isspace( static_cast(p) ); - } - - inline static bool IsNameStartChar( unsigned char ch ) { - if ( ch >= 128 ) { - // This is a heuristic guess in attempt to not implement Unicode-aware isalpha() - return true; - } - if ( isalpha( ch ) ) { - return true; - } - return ch == ':' || ch == '_'; - } - - inline static bool IsNameChar( unsigned char ch ) { - return IsNameStartChar( ch ) - || isdigit( ch ) - || ch == '.' - || ch == '-'; - } - - inline static bool StringEqual( const char* p, const char* q, int nChar=INT_MAX ) { - if ( p == q ) { - return true; - } - TIXMLASSERT( p ); - TIXMLASSERT( q ); - TIXMLASSERT( nChar >= 0 ); - return strncmp( p, q, nChar ) == 0; - } - - inline static bool IsUTF8Continuation( char p ) { - return ( p & 0x80 ) != 0; - } - - static const char* ReadBOM( const char* p, bool* hasBOM ); - // p is the starting location, - // the UTF-8 value of the entity will be placed in value, and length filled in. - static const char* GetCharacterRef( const char* p, char* value, int* length ); - static void ConvertUTF32ToUTF8( unsigned long input, char* output, int* length ); - - // converts primitive types to strings - static void ToStr( int v, char* buffer, int bufferSize ); - static void ToStr( unsigned v, char* buffer, int bufferSize ); - static void ToStr( bool v, char* buffer, int bufferSize ); - static void ToStr( float v, char* buffer, int bufferSize ); - static void ToStr( double v, char* buffer, int bufferSize ); - static void ToStr(int64_t v, char* buffer, int bufferSize); - - // converts strings to primitive types - static bool ToInt( const char* str, int* value ); - static bool ToUnsigned( const char* str, unsigned* value ); - static bool ToBool( const char* str, bool* value ); - static bool ToFloat( const char* str, float* value ); - static bool ToDouble( const char* str, double* value ); - static bool ToInt64(const char* str, int64_t* value); - - // Changes what is serialized for a boolean value. - // Default to "true" and "false". Shouldn't be changed - // unless you have a special testing or compatibility need. - // Be careful: static, global, & not thread safe. - // Be sure to set static const memory as parameters. - static void SetBoolSerialization(const char* writeTrue, const char* writeFalse); - -private: - static const char* writeBoolTrue; - static const char* writeBoolFalse; -}; - - -/** XMLNode is a base class for every object that is in the - XML Document Object Model (DOM), except XMLAttributes. - Nodes have siblings, a parent, and children which can - be navigated. A node is always in a XMLDocument. - The type of a XMLNode can be queried, and it can - be cast to its more defined type. - - A XMLDocument allocates memory for all its Nodes. - When the XMLDocument gets deleted, all its Nodes - will also be deleted. - - @verbatim - A Document can contain: Element (container or leaf) - Comment (leaf) - Unknown (leaf) - Declaration( leaf ) - - An Element can contain: Element (container or leaf) - Text (leaf) - Attributes (not on tree) - Comment (leaf) - Unknown (leaf) - - @endverbatim -*/ -class TINYXML2_LIB XMLNode -{ - friend class XMLDocument; - friend class XMLElement; -public: - - /// Get the XMLDocument that owns this XMLNode. - const XMLDocument* GetDocument() const { - TIXMLASSERT( _document ); - return _document; - } - /// Get the XMLDocument that owns this XMLNode. - XMLDocument* GetDocument() { - TIXMLASSERT( _document ); - return _document; - } - - /// Safely cast to an Element, or null. - virtual XMLElement* ToElement() { - return 0; - } - /// Safely cast to Text, or null. - virtual XMLText* ToText() { - return 0; - } - /// Safely cast to a Comment, or null. - virtual XMLComment* ToComment() { - return 0; - } - /// Safely cast to a Document, or null. - virtual XMLDocument* ToDocument() { - return 0; - } - /// Safely cast to a Declaration, or null. - virtual XMLDeclaration* ToDeclaration() { - return 0; - } - /// Safely cast to an Unknown, or null. - virtual XMLUnknown* ToUnknown() { - return 0; - } - - virtual const XMLElement* ToElement() const { - return 0; - } - virtual const XMLText* ToText() const { - return 0; - } - virtual const XMLComment* ToComment() const { - return 0; - } - virtual const XMLDocument* ToDocument() const { - return 0; - } - virtual const XMLDeclaration* ToDeclaration() const { - return 0; - } - virtual const XMLUnknown* ToUnknown() const { - return 0; - } - - /** The meaning of 'value' changes for the specific type. - @verbatim - Document: empty (NULL is returned, not an empty string) - Element: name of the element - Comment: the comment text - Unknown: the tag contents - Text: the text string - @endverbatim - */ - const char* Value() const; - - /** Set the Value of an XML node. - @sa Value() - */ - void SetValue( const char* val, bool staticMem=false ); - - /// Gets the line number the node is in, if the document was parsed from a file. - int GetLineNum() const { return _parseLineNum; } - - /// Get the parent of this node on the DOM. - const XMLNode* Parent() const { - return _parent; - } - - XMLNode* Parent() { - return _parent; - } - - /// Returns true if this node has no children. - bool NoChildren() const { - return !_firstChild; - } - - /// Get the first child node, or null if none exists. - const XMLNode* FirstChild() const { - return _firstChild; - } - - XMLNode* FirstChild() { - return _firstChild; - } - - /** Get the first child element, or optionally the first child - element with the specified name. - */ - const XMLElement* FirstChildElement( const char* name = 0 ) const; - - XMLElement* FirstChildElement( const char* name = 0 ) { - return const_cast(const_cast(this)->FirstChildElement( name )); - } - - /// Get the last child node, or null if none exists. - const XMLNode* LastChild() const { - return _lastChild; - } - - XMLNode* LastChild() { - return _lastChild; - } - - /** Get the last child element or optionally the last child - element with the specified name. - */ - const XMLElement* LastChildElement( const char* name = 0 ) const; - - XMLElement* LastChildElement( const char* name = 0 ) { - return const_cast(const_cast(this)->LastChildElement(name) ); - } - - /// Get the previous (left) sibling node of this node. - const XMLNode* PreviousSibling() const { - return _prev; - } - - XMLNode* PreviousSibling() { - return _prev; - } - - /// Get the previous (left) sibling element of this node, with an optionally supplied name. - const XMLElement* PreviousSiblingElement( const char* name = 0 ) const ; - - XMLElement* PreviousSiblingElement( const char* name = 0 ) { - return const_cast(const_cast(this)->PreviousSiblingElement( name ) ); - } - - /// Get the next (right) sibling node of this node. - const XMLNode* NextSibling() const { - return _next; - } - - XMLNode* NextSibling() { - return _next; - } - - /// Get the next (right) sibling element of this node, with an optionally supplied name. - const XMLElement* NextSiblingElement( const char* name = 0 ) const; - - XMLElement* NextSiblingElement( const char* name = 0 ) { - return const_cast(const_cast(this)->NextSiblingElement( name ) ); - } - - /** - Add a child node as the last (right) child. - If the child node is already part of the document, - it is moved from its old location to the new location. - Returns the addThis argument or 0 if the node does not - belong to the same document. - */ - XMLNode* InsertEndChild( XMLNode* addThis ); - - XMLNode* LinkEndChild( XMLNode* addThis ) { - return InsertEndChild( addThis ); - } - /** - Add a child node as the first (left) child. - If the child node is already part of the document, - it is moved from its old location to the new location. - Returns the addThis argument or 0 if the node does not - belong to the same document. - */ - XMLNode* InsertFirstChild( XMLNode* addThis ); - /** - Add a node after the specified child node. - If the child node is already part of the document, - it is moved from its old location to the new location. - Returns the addThis argument or 0 if the afterThis node - is not a child of this node, or if the node does not - belong to the same document. - */ - XMLNode* InsertAfterChild( XMLNode* afterThis, XMLNode* addThis ); - - /** - Delete all the children of this node. - */ - void DeleteChildren(); - - /** - Delete a child of this node. - */ - void DeleteChild( XMLNode* node ); - - /** - Make a copy of this node, but not its children. - You may pass in a Document pointer that will be - the owner of the new Node. If the 'document' is - null, then the node returned will be allocated - from the current Document. (this->GetDocument()) - - Note: if called on a XMLDocument, this will return null. - */ - virtual XMLNode* ShallowClone( XMLDocument* document ) const = 0; - - /** - Make a copy of this node and all its children. - - If the 'target' is null, then the nodes will - be allocated in the current document. If 'target' - is specified, the memory will be allocated is the - specified XMLDocument. - - NOTE: This is probably not the correct tool to - copy a document, since XMLDocuments can have multiple - top level XMLNodes. You probably want to use - XMLDocument::DeepCopy() - */ - XMLNode* DeepClone( XMLDocument* target ) const; - - /** - Test if 2 nodes are the same, but don't test children. - The 2 nodes do not need to be in the same Document. - - Note: if called on a XMLDocument, this will return false. - */ - virtual bool ShallowEqual( const XMLNode* compare ) const = 0; - - /** Accept a hierarchical visit of the nodes in the TinyXML-2 DOM. Every node in the - XML tree will be conditionally visited and the host will be called back - via the XMLVisitor interface. - - This is essentially a SAX interface for TinyXML-2. (Note however it doesn't re-parse - the XML for the callbacks, so the performance of TinyXML-2 is unchanged by using this - interface versus any other.) - - The interface has been based on ideas from: - - - http://www.saxproject.org/ - - http://c2.com/cgi/wiki?HierarchicalVisitorPattern - - Which are both good references for "visiting". - - An example of using Accept(): - @verbatim - XMLPrinter printer; - tinyxmlDoc.Accept( &printer ); - const char* xmlcstr = printer.CStr(); - @endverbatim - */ - virtual bool Accept( XMLVisitor* visitor ) const = 0; - - /** - Set user data into the XMLNode. TinyXML-2 in - no way processes or interprets user data. - It is initially 0. - */ - void SetUserData(void* userData) { _userData = userData; } - - /** - Get user data set into the XMLNode. TinyXML-2 in - no way processes or interprets user data. - It is initially 0. - */ - void* GetUserData() const { return _userData; } - -protected: - explicit XMLNode( XMLDocument* ); - virtual ~XMLNode(); - - virtual char* ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr); - - XMLDocument* _document; - XMLNode* _parent; - mutable StrPair _value; - int _parseLineNum; - - XMLNode* _firstChild; - XMLNode* _lastChild; - - XMLNode* _prev; - XMLNode* _next; - - void* _userData; - -private: - MemPool* _memPool; - void Unlink( XMLNode* child ); - static void DeleteNode( XMLNode* node ); - void InsertChildPreamble( XMLNode* insertThis ) const; - const XMLElement* ToElementWithName( const char* name ) const; - - XMLNode( const XMLNode& ); // not supported - XMLNode& operator=( const XMLNode& ); // not supported -}; - - -/** XML text. - - Note that a text node can have child element nodes, for example: - @verbatim - This is bold - @endverbatim - - A text node can have 2 ways to output the next. "normal" output - and CDATA. It will default to the mode it was parsed from the XML file and - you generally want to leave it alone, but you can change the output mode with - SetCData() and query it with CData(). -*/ -class TINYXML2_LIB XMLText : public XMLNode -{ - friend class XMLDocument; -public: - virtual bool Accept( XMLVisitor* visitor ) const; - - virtual XMLText* ToText() { - return this; - } - virtual const XMLText* ToText() const { - return this; - } - - /// Declare whether this should be CDATA or standard text. - void SetCData( bool isCData ) { - _isCData = isCData; - } - /// Returns true if this is a CDATA text element. - bool CData() const { - return _isCData; - } - - virtual XMLNode* ShallowClone( XMLDocument* document ) const; - virtual bool ShallowEqual( const XMLNode* compare ) const; - -protected: - explicit XMLText( XMLDocument* doc ) : XMLNode( doc ), _isCData( false ) {} - virtual ~XMLText() {} - - char* ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr ); - -private: - bool _isCData; - - XMLText( const XMLText& ); // not supported - XMLText& operator=( const XMLText& ); // not supported -}; - - -/** An XML Comment. */ -class TINYXML2_LIB XMLComment : public XMLNode -{ - friend class XMLDocument; -public: - virtual XMLComment* ToComment() { - return this; - } - virtual const XMLComment* ToComment() const { - return this; - } - - virtual bool Accept( XMLVisitor* visitor ) const; - - virtual XMLNode* ShallowClone( XMLDocument* document ) const; - virtual bool ShallowEqual( const XMLNode* compare ) const; - -protected: - explicit XMLComment( XMLDocument* doc ); - virtual ~XMLComment(); - - char* ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr); - -private: - XMLComment( const XMLComment& ); // not supported - XMLComment& operator=( const XMLComment& ); // not supported -}; - - -/** In correct XML the declaration is the first entry in the file. - @verbatim - - @endverbatim - - TinyXML-2 will happily read or write files without a declaration, - however. - - The text of the declaration isn't interpreted. It is parsed - and written as a string. -*/ -class TINYXML2_LIB XMLDeclaration : public XMLNode -{ - friend class XMLDocument; -public: - virtual XMLDeclaration* ToDeclaration() { - return this; - } - virtual const XMLDeclaration* ToDeclaration() const { - return this; - } - - virtual bool Accept( XMLVisitor* visitor ) const; - - virtual XMLNode* ShallowClone( XMLDocument* document ) const; - virtual bool ShallowEqual( const XMLNode* compare ) const; - -protected: - explicit XMLDeclaration( XMLDocument* doc ); - virtual ~XMLDeclaration(); - - char* ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr ); - -private: - XMLDeclaration( const XMLDeclaration& ); // not supported - XMLDeclaration& operator=( const XMLDeclaration& ); // not supported -}; - - -/** Any tag that TinyXML-2 doesn't recognize is saved as an - unknown. It is a tag of text, but should not be modified. - It will be written back to the XML, unchanged, when the file - is saved. - - DTD tags get thrown into XMLUnknowns. -*/ -class TINYXML2_LIB XMLUnknown : public XMLNode -{ - friend class XMLDocument; -public: - virtual XMLUnknown* ToUnknown() { - return this; - } - virtual const XMLUnknown* ToUnknown() const { - return this; - } - - virtual bool Accept( XMLVisitor* visitor ) const; - - virtual XMLNode* ShallowClone( XMLDocument* document ) const; - virtual bool ShallowEqual( const XMLNode* compare ) const; - -protected: - explicit XMLUnknown( XMLDocument* doc ); - virtual ~XMLUnknown(); - - char* ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr ); - -private: - XMLUnknown( const XMLUnknown& ); // not supported - XMLUnknown& operator=( const XMLUnknown& ); // not supported -}; - - - -/** An attribute is a name-value pair. Elements have an arbitrary - number of attributes, each with a unique name. - - @note The attributes are not XMLNodes. You may only query the - Next() attribute in a list. -*/ -class TINYXML2_LIB XMLAttribute -{ - friend class XMLElement; -public: - /// The name of the attribute. - const char* Name() const; - - /// The value of the attribute. - const char* Value() const; - - /// Gets the line number the attribute is in, if the document was parsed from a file. - int GetLineNum() const { return _parseLineNum; } - - /// The next attribute in the list. - const XMLAttribute* Next() const { - return _next; - } - - /** IntValue interprets the attribute as an integer, and returns the value. - If the value isn't an integer, 0 will be returned. There is no error checking; - use QueryIntValue() if you need error checking. - */ - int IntValue() const { - int i = 0; - QueryIntValue(&i); - return i; - } - - int64_t Int64Value() const { - int64_t i = 0; - QueryInt64Value(&i); - return i; - } - - /// Query as an unsigned integer. See IntValue() - unsigned UnsignedValue() const { - unsigned i=0; - QueryUnsignedValue( &i ); - return i; - } - /// Query as a boolean. See IntValue() - bool BoolValue() const { - bool b=false; - QueryBoolValue( &b ); - return b; - } - /// Query as a double. See IntValue() - double DoubleValue() const { - double d=0; - QueryDoubleValue( &d ); - return d; - } - /// Query as a float. See IntValue() - float FloatValue() const { - float f=0; - QueryFloatValue( &f ); - return f; - } - - /** QueryIntValue interprets the attribute as an integer, and returns the value - in the provided parameter. The function will return XML_SUCCESS on success, - and XML_WRONG_ATTRIBUTE_TYPE if the conversion is not successful. - */ - XMLError QueryIntValue( int* value ) const; - /// See QueryIntValue - XMLError QueryUnsignedValue( unsigned int* value ) const; - /// See QueryIntValue - XMLError QueryInt64Value(int64_t* value) const; - /// See QueryIntValue - XMLError QueryBoolValue( bool* value ) const; - /// See QueryIntValue - XMLError QueryDoubleValue( double* value ) const; - /// See QueryIntValue - XMLError QueryFloatValue( float* value ) const; - - /// Set the attribute to a string value. - void SetAttribute( const char* value ); - /// Set the attribute to value. - void SetAttribute( int value ); - /// Set the attribute to value. - void SetAttribute( unsigned value ); - /// Set the attribute to value. - void SetAttribute(int64_t value); - /// Set the attribute to value. - void SetAttribute( bool value ); - /// Set the attribute to value. - void SetAttribute( double value ); - /// Set the attribute to value. - void SetAttribute( float value ); - -private: - enum { BUF_SIZE = 200 }; - - XMLAttribute() : _name(), _value(),_parseLineNum( 0 ), _next( 0 ), _memPool( 0 ) {} - virtual ~XMLAttribute() {} - - XMLAttribute( const XMLAttribute& ); // not supported - void operator=( const XMLAttribute& ); // not supported - void SetName( const char* name ); - - char* ParseDeep( char* p, bool processEntities, int* curLineNumPtr ); - - mutable StrPair _name; - mutable StrPair _value; - int _parseLineNum; - XMLAttribute* _next; - MemPool* _memPool; -}; - - -/** The element is a container class. It has a value, the element name, - and can contain other elements, text, comments, and unknowns. - Elements also contain an arbitrary number of attributes. -*/ -class TINYXML2_LIB XMLElement : public XMLNode -{ - friend class XMLDocument; -public: - /// Get the name of an element (which is the Value() of the node.) - const char* Name() const { - return Value(); - } - /// Set the name of the element. - void SetName( const char* str, bool staticMem=false ) { - SetValue( str, staticMem ); - } - - virtual XMLElement* ToElement() { - return this; - } - virtual const XMLElement* ToElement() const { - return this; - } - virtual bool Accept( XMLVisitor* visitor ) const; - - /** Given an attribute name, Attribute() returns the value - for the attribute of that name, or null if none - exists. For example: - - @verbatim - const char* value = ele->Attribute( "foo" ); - @endverbatim - - The 'value' parameter is normally null. However, if specified, - the attribute will only be returned if the 'name' and 'value' - match. This allow you to write code: - - @verbatim - if ( ele->Attribute( "foo", "bar" ) ) callFooIsBar(); - @endverbatim - - rather than: - @verbatim - if ( ele->Attribute( "foo" ) ) { - if ( strcmp( ele->Attribute( "foo" ), "bar" ) == 0 ) callFooIsBar(); - } - @endverbatim - */ - const char* Attribute( const char* name, const char* value=0 ) const; - - /** Given an attribute name, IntAttribute() returns the value - of the attribute interpreted as an integer. The default - value will be returned if the attribute isn't present, - or if there is an error. (For a method with error - checking, see QueryIntAttribute()). - */ - int IntAttribute(const char* name, int defaultValue = 0) const; - /// See IntAttribute() - unsigned UnsignedAttribute(const char* name, unsigned defaultValue = 0) const; - /// See IntAttribute() - int64_t Int64Attribute(const char* name, int64_t defaultValue = 0) const; - /// See IntAttribute() - bool BoolAttribute(const char* name, bool defaultValue = false) const; - /// See IntAttribute() - double DoubleAttribute(const char* name, double defaultValue = 0) const; - /// See IntAttribute() - float FloatAttribute(const char* name, float defaultValue = 0) const; - - /** Given an attribute name, QueryIntAttribute() returns - XML_SUCCESS, XML_WRONG_ATTRIBUTE_TYPE if the conversion - can't be performed, or XML_NO_ATTRIBUTE if the attribute - doesn't exist. If successful, the result of the conversion - will be written to 'value'. If not successful, nothing will - be written to 'value'. This allows you to provide default - value: - - @verbatim - int value = 10; - QueryIntAttribute( "foo", &value ); // if "foo" isn't found, value will still be 10 - @endverbatim - */ - XMLError QueryIntAttribute( const char* name, int* value ) const { - const XMLAttribute* a = FindAttribute( name ); - if ( !a ) { - return XML_NO_ATTRIBUTE; - } - return a->QueryIntValue( value ); - } - - /// See QueryIntAttribute() - XMLError QueryUnsignedAttribute( const char* name, unsigned int* value ) const { - const XMLAttribute* a = FindAttribute( name ); - if ( !a ) { - return XML_NO_ATTRIBUTE; - } - return a->QueryUnsignedValue( value ); - } - - /// See QueryIntAttribute() - XMLError QueryInt64Attribute(const char* name, int64_t* value) const { - const XMLAttribute* a = FindAttribute(name); - if (!a) { - return XML_NO_ATTRIBUTE; - } - return a->QueryInt64Value(value); - } - - /// See QueryIntAttribute() - XMLError QueryBoolAttribute( const char* name, bool* value ) const { - const XMLAttribute* a = FindAttribute( name ); - if ( !a ) { - return XML_NO_ATTRIBUTE; - } - return a->QueryBoolValue( value ); - } - /// See QueryIntAttribute() - XMLError QueryDoubleAttribute( const char* name, double* value ) const { - const XMLAttribute* a = FindAttribute( name ); - if ( !a ) { - return XML_NO_ATTRIBUTE; - } - return a->QueryDoubleValue( value ); - } - /// See QueryIntAttribute() - XMLError QueryFloatAttribute( const char* name, float* value ) const { - const XMLAttribute* a = FindAttribute( name ); - if ( !a ) { - return XML_NO_ATTRIBUTE; - } - return a->QueryFloatValue( value ); - } - - /// See QueryIntAttribute() - XMLError QueryStringAttribute(const char* name, const char** value) const { - const XMLAttribute* a = FindAttribute(name); - if (!a) { - return XML_NO_ATTRIBUTE; - } - *value = a->Value(); - return XML_SUCCESS; - } - - - - /** Given an attribute name, QueryAttribute() returns - XML_SUCCESS, XML_WRONG_ATTRIBUTE_TYPE if the conversion - can't be performed, or XML_NO_ATTRIBUTE if the attribute - doesn't exist. It is overloaded for the primitive types, - and is a generally more convenient replacement of - QueryIntAttribute() and related functions. - - If successful, the result of the conversion - will be written to 'value'. If not successful, nothing will - be written to 'value'. This allows you to provide default - value: - - @verbatim - int value = 10; - QueryAttribute( "foo", &value ); // if "foo" isn't found, value will still be 10 - @endverbatim - */ - XMLError QueryAttribute( const char* name, int* value ) const { - return QueryIntAttribute( name, value ); - } - - XMLError QueryAttribute( const char* name, unsigned int* value ) const { - return QueryUnsignedAttribute( name, value ); - } - - XMLError QueryAttribute(const char* name, int64_t* value) const { - return QueryInt64Attribute(name, value); - } - - XMLError QueryAttribute( const char* name, bool* value ) const { - return QueryBoolAttribute( name, value ); - } - - XMLError QueryAttribute( const char* name, double* value ) const { - return QueryDoubleAttribute( name, value ); - } - - XMLError QueryAttribute( const char* name, float* value ) const { - return QueryFloatAttribute( name, value ); - } - - /// Sets the named attribute to value. - void SetAttribute( const char* name, const char* value ) { - XMLAttribute* a = FindOrCreateAttribute( name ); - a->SetAttribute( value ); - } - /// Sets the named attribute to value. - void SetAttribute( const char* name, int value ) { - XMLAttribute* a = FindOrCreateAttribute( name ); - a->SetAttribute( value ); - } - /// Sets the named attribute to value. - void SetAttribute( const char* name, unsigned value ) { - XMLAttribute* a = FindOrCreateAttribute( name ); - a->SetAttribute( value ); - } - - /// Sets the named attribute to value. - void SetAttribute(const char* name, int64_t value) { - XMLAttribute* a = FindOrCreateAttribute(name); - a->SetAttribute(value); - } - - /// Sets the named attribute to value. - void SetAttribute( const char* name, bool value ) { - XMLAttribute* a = FindOrCreateAttribute( name ); - a->SetAttribute( value ); - } - /// Sets the named attribute to value. - void SetAttribute( const char* name, double value ) { - XMLAttribute* a = FindOrCreateAttribute( name ); - a->SetAttribute( value ); - } - /// Sets the named attribute to value. - void SetAttribute( const char* name, float value ) { - XMLAttribute* a = FindOrCreateAttribute( name ); - a->SetAttribute( value ); - } - - /** - Delete an attribute. - */ - void DeleteAttribute( const char* name ); - - /// Return the first attribute in the list. - const XMLAttribute* FirstAttribute() const { - return _rootAttribute; - } - /// Query a specific attribute in the list. - const XMLAttribute* FindAttribute( const char* name ) const; - - /** Convenience function for easy access to the text inside an element. Although easy - and concise, GetText() is limited compared to getting the XMLText child - and accessing it directly. - - If the first child of 'this' is a XMLText, the GetText() - returns the character string of the Text node, else null is returned. - - This is a convenient method for getting the text of simple contained text: - @verbatim - This is text - const char* str = fooElement->GetText(); - @endverbatim - - 'str' will be a pointer to "This is text". - - Note that this function can be misleading. If the element foo was created from - this XML: - @verbatim - This is text - @endverbatim - - then the value of str would be null. The first child node isn't a text node, it is - another element. From this XML: - @verbatim - This is text - @endverbatim - GetText() will return "This is ". - */ - const char* GetText() const; - - /** Convenience function for easy access to the text inside an element. Although easy - and concise, SetText() is limited compared to creating an XMLText child - and mutating it directly. - - If the first child of 'this' is a XMLText, SetText() sets its value to - the given string, otherwise it will create a first child that is an XMLText. - - This is a convenient method for setting the text of simple contained text: - @verbatim - This is text - fooElement->SetText( "Hullaballoo!" ); - Hullaballoo! - @endverbatim - - Note that this function can be misleading. If the element foo was created from - this XML: - @verbatim - This is text - @endverbatim - - then it will not change "This is text", but rather prefix it with a text element: - @verbatim - Hullaballoo!This is text - @endverbatim - - For this XML: - @verbatim - - @endverbatim - SetText() will generate - @verbatim - Hullaballoo! - @endverbatim - */ - void SetText( const char* inText ); - /// Convenience method for setting text inside an element. See SetText() for important limitations. - void SetText( int value ); - /// Convenience method for setting text inside an element. See SetText() for important limitations. - void SetText( unsigned value ); - /// Convenience method for setting text inside an element. See SetText() for important limitations. - void SetText(int64_t value); - /// Convenience method for setting text inside an element. See SetText() for important limitations. - void SetText( bool value ); - /// Convenience method for setting text inside an element. See SetText() for important limitations. - void SetText( double value ); - /// Convenience method for setting text inside an element. See SetText() for important limitations. - void SetText( float value ); - - /** - Convenience method to query the value of a child text node. This is probably best - shown by example. Given you have a document is this form: - @verbatim - - 1 - 1.4 - - @endverbatim - - The QueryIntText() and similar functions provide a safe and easier way to get to the - "value" of x and y. - - @verbatim - int x = 0; - float y = 0; // types of x and y are contrived for example - const XMLElement* xElement = pointElement->FirstChildElement( "x" ); - const XMLElement* yElement = pointElement->FirstChildElement( "y" ); - xElement->QueryIntText( &x ); - yElement->QueryFloatText( &y ); - @endverbatim - - @returns XML_SUCCESS (0) on success, XML_CAN_NOT_CONVERT_TEXT if the text cannot be converted - to the requested type, and XML_NO_TEXT_NODE if there is no child text to query. - - */ - XMLError QueryIntText( int* ival ) const; - /// See QueryIntText() - XMLError QueryUnsignedText( unsigned* uval ) const; - /// See QueryIntText() - XMLError QueryInt64Text(int64_t* uval) const; - /// See QueryIntText() - XMLError QueryBoolText( bool* bval ) const; - /// See QueryIntText() - XMLError QueryDoubleText( double* dval ) const; - /// See QueryIntText() - XMLError QueryFloatText( float* fval ) const; - - int IntText(int defaultValue = 0) const; - - /// See QueryIntText() - unsigned UnsignedText(unsigned defaultValue = 0) const; - /// See QueryIntText() - int64_t Int64Text(int64_t defaultValue = 0) const; - /// See QueryIntText() - bool BoolText(bool defaultValue = false) const; - /// See QueryIntText() - double DoubleText(double defaultValue = 0) const; - /// See QueryIntText() - float FloatText(float defaultValue = 0) const; - - // internal: - enum ElementClosingType { - OPEN, // - CLOSED, // - CLOSING // - }; - ElementClosingType ClosingType() const { - return _closingType; - } - virtual XMLNode* ShallowClone( XMLDocument* document ) const; - virtual bool ShallowEqual( const XMLNode* compare ) const; - -protected: - char* ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr ); - -private: - XMLElement( XMLDocument* doc ); - virtual ~XMLElement(); - XMLElement( const XMLElement& ); // not supported - void operator=( const XMLElement& ); // not supported - - XMLAttribute* FindOrCreateAttribute( const char* name ); - char* ParseAttributes( char* p, int* curLineNumPtr ); - static void DeleteAttribute( XMLAttribute* attribute ); - XMLAttribute* CreateAttribute(); - - enum { BUF_SIZE = 200 }; - ElementClosingType _closingType; - // The attribute list is ordered; there is no 'lastAttribute' - // because the list needs to be scanned for dupes before adding - // a new attribute. - XMLAttribute* _rootAttribute; -}; - - -enum Whitespace { - PRESERVE_WHITESPACE, - COLLAPSE_WHITESPACE -}; - - -/** A Document binds together all the functionality. - It can be saved, loaded, and printed to the screen. - All Nodes are connected and allocated to a Document. - If the Document is deleted, all its Nodes are also deleted. -*/ -class TINYXML2_LIB XMLDocument : public XMLNode -{ - friend class XMLElement; - // Gives access to SetError and Push/PopDepth, but over-access for everything else. - // Wishing C++ had "internal" scope. - friend class XMLNode; - friend class XMLText; - friend class XMLComment; - friend class XMLDeclaration; - friend class XMLUnknown; -public: - /// constructor - XMLDocument( bool processEntities = true, Whitespace whitespaceMode = PRESERVE_WHITESPACE ); - ~XMLDocument(); - - virtual XMLDocument* ToDocument() { - TIXMLASSERT( this == _document ); - return this; - } - virtual const XMLDocument* ToDocument() const { - TIXMLASSERT( this == _document ); - return this; - } - - /** - Parse an XML file from a character string. - Returns XML_SUCCESS (0) on success, or - an errorID. - - You may optionally pass in the 'nBytes', which is - the number of bytes which will be parsed. If not - specified, TinyXML-2 will assume 'xml' points to a - null terminated string. - */ - XMLError Parse( const char* xml, size_t nBytes=(size_t)(-1) ); - - /** - Load an XML file from disk. - Returns XML_SUCCESS (0) on success, or - an errorID. - */ - XMLError LoadFile( const char* filename ); - - /** - Load an XML file from disk. You are responsible - for providing and closing the FILE*. - - NOTE: The file should be opened as binary ("rb") - not text in order for TinyXML-2 to correctly - do newline normalization. - - Returns XML_SUCCESS (0) on success, or - an errorID. - */ - XMLError LoadFile( FILE* ); - - /** - Save the XML file to disk. - Returns XML_SUCCESS (0) on success, or - an errorID. - */ - XMLError SaveFile( const char* filename, bool compact = false ); - - /** - Save the XML file to disk. You are responsible - for providing and closing the FILE*. - - Returns XML_SUCCESS (0) on success, or - an errorID. - */ - XMLError SaveFile( FILE* fp, bool compact = false ); - - bool ProcessEntities() const { - return _processEntities; - } - Whitespace WhitespaceMode() const { - return _whitespaceMode; - } - - /** - Returns true if this document has a leading Byte Order Mark of UTF8. - */ - bool HasBOM() const { - return _writeBOM; - } - /** Sets whether to write the BOM when writing the file. - */ - void SetBOM( bool useBOM ) { - _writeBOM = useBOM; - } - - /** Return the root element of DOM. Equivalent to FirstChildElement(). - To get the first node, use FirstChild(). - */ - XMLElement* RootElement() { - return FirstChildElement(); - } - const XMLElement* RootElement() const { - return FirstChildElement(); - } - - /** Print the Document. If the Printer is not provided, it will - print to stdout. If you provide Printer, this can print to a file: - @verbatim - XMLPrinter printer( fp ); - doc.Print( &printer ); - @endverbatim - - Or you can use a printer to print to memory: - @verbatim - XMLPrinter printer; - doc.Print( &printer ); - // printer.CStr() has a const char* to the XML - @endverbatim - */ - void Print( XMLPrinter* streamer=0 ) const; - virtual bool Accept( XMLVisitor* visitor ) const; - - /** - Create a new Element associated with - this Document. The memory for the Element - is managed by the Document. - */ - XMLElement* NewElement( const char* name ); - /** - Create a new Comment associated with - this Document. The memory for the Comment - is managed by the Document. - */ - XMLComment* NewComment( const char* comment ); - /** - Create a new Text associated with - this Document. The memory for the Text - is managed by the Document. - */ - XMLText* NewText( const char* text ); - /** - Create a new Declaration associated with - this Document. The memory for the object - is managed by the Document. - - If the 'text' param is null, the standard - declaration is used.: - @verbatim - - @endverbatim - */ - XMLDeclaration* NewDeclaration( const char* text=0 ); - /** - Create a new Unknown associated with - this Document. The memory for the object - is managed by the Document. - */ - XMLUnknown* NewUnknown( const char* text ); - - /** - Delete a node associated with this document. - It will be unlinked from the DOM. - */ - void DeleteNode( XMLNode* node ); - - void ClearError() { - SetError(XML_SUCCESS, 0, 0); - } - - /// Return true if there was an error parsing the document. - bool Error() const { - return _errorID != XML_SUCCESS; - } - /// Return the errorID. - XMLError ErrorID() const { - return _errorID; - } - const char* ErrorName() const; - static const char* ErrorIDToName(XMLError errorID); - - /** Returns a "long form" error description. A hopefully helpful - diagnostic with location, line number, and/or additional info. - */ - const char* ErrorStr() const; - - /// A (trivial) utility function that prints the ErrorStr() to stdout. - void PrintError() const; - - /// Return the line where the error occurred, or zero if unknown. - int ErrorLineNum() const - { - return _errorLineNum; - } - - /// Clear the document, resetting it to the initial state. - void Clear(); - - /** - Copies this document to a target document. - The target will be completely cleared before the copy. - If you want to copy a sub-tree, see XMLNode::DeepClone(). - - NOTE: that the 'target' must be non-null. - */ - void DeepCopy(XMLDocument* target) const; - - // internal - char* Identify( char* p, XMLNode** node ); - - // internal - void MarkInUse(XMLNode*); - - virtual XMLNode* ShallowClone( XMLDocument* /*document*/ ) const { - return 0; - } - virtual bool ShallowEqual( const XMLNode* /*compare*/ ) const { - return false; - } - -private: - XMLDocument( const XMLDocument& ); // not supported - void operator=( const XMLDocument& ); // not supported - - bool _writeBOM; - bool _processEntities; - XMLError _errorID; - Whitespace _whitespaceMode; - mutable StrPair _errorStr; - int _errorLineNum; - char* _charBuffer; - int _parseCurLineNum; - int _parsingDepth; - // Memory tracking does add some overhead. - // However, the code assumes that you don't - // have a bunch of unlinked nodes around. - // Therefore it takes less memory to track - // in the document vs. a linked list in the XMLNode, - // and the performance is the same. - DynArray _unlinked; - - MemPoolT< sizeof(XMLElement) > _elementPool; - MemPoolT< sizeof(XMLAttribute) > _attributePool; - MemPoolT< sizeof(XMLText) > _textPool; - MemPoolT< sizeof(XMLComment) > _commentPool; - - static const char* _errorNames[XML_ERROR_COUNT]; - - void Parse(); - - void SetError( XMLError error, int lineNum, const char* format, ... ); - - // Something of an obvious security hole, once it was discovered. - // Either an ill-formed XML or an excessively deep one can overflow - // the stack. Track stack depth, and error out if needed. - class DepthTracker { - public: - explicit DepthTracker(XMLDocument * document) { - this->_document = document; - document->PushDepth(); - } - ~DepthTracker() { - _document->PopDepth(); - } - private: - XMLDocument * _document; - }; - void PushDepth(); - void PopDepth(); - - template - NodeType* CreateUnlinkedNode( MemPoolT& pool ); -}; - -template -inline NodeType* XMLDocument::CreateUnlinkedNode( MemPoolT& pool ) -{ - TIXMLASSERT( sizeof( NodeType ) == PoolElementSize ); - TIXMLASSERT( sizeof( NodeType ) == pool.ItemSize() ); - NodeType* returnNode = new (pool.Alloc()) NodeType( this ); - TIXMLASSERT( returnNode ); - returnNode->_memPool = &pool; - - _unlinked.Push(returnNode); - return returnNode; -} - -/** - A XMLHandle is a class that wraps a node pointer with null checks; this is - an incredibly useful thing. Note that XMLHandle is not part of the TinyXML-2 - DOM structure. It is a separate utility class. - - Take an example: - @verbatim - - - - - - - @endverbatim - - Assuming you want the value of "attributeB" in the 2nd "Child" element, it's very - easy to write a *lot* of code that looks like: - - @verbatim - XMLElement* root = document.FirstChildElement( "Document" ); - if ( root ) - { - XMLElement* element = root->FirstChildElement( "Element" ); - if ( element ) - { - XMLElement* child = element->FirstChildElement( "Child" ); - if ( child ) - { - XMLElement* child2 = child->NextSiblingElement( "Child" ); - if ( child2 ) - { - // Finally do something useful. - @endverbatim - - And that doesn't even cover "else" cases. XMLHandle addresses the verbosity - of such code. A XMLHandle checks for null pointers so it is perfectly safe - and correct to use: - - @verbatim - XMLHandle docHandle( &document ); - XMLElement* child2 = docHandle.FirstChildElement( "Document" ).FirstChildElement( "Element" ).FirstChildElement().NextSiblingElement(); - if ( child2 ) - { - // do something useful - @endverbatim - - Which is MUCH more concise and useful. - - It is also safe to copy handles - internally they are nothing more than node pointers. - @verbatim - XMLHandle handleCopy = handle; - @endverbatim - - See also XMLConstHandle, which is the same as XMLHandle, but operates on const objects. -*/ -class TINYXML2_LIB XMLHandle -{ -public: - /// Create a handle from any node (at any depth of the tree.) This can be a null pointer. - explicit XMLHandle( XMLNode* node ) : _node( node ) { - } - /// Create a handle from a node. - explicit XMLHandle( XMLNode& node ) : _node( &node ) { - } - /// Copy constructor - XMLHandle( const XMLHandle& ref ) : _node( ref._node ) { - } - /// Assignment - XMLHandle& operator=( const XMLHandle& ref ) { - _node = ref._node; - return *this; - } - - /// Get the first child of this handle. - XMLHandle FirstChild() { - return XMLHandle( _node ? _node->FirstChild() : 0 ); - } - /// Get the first child element of this handle. - XMLHandle FirstChildElement( const char* name = 0 ) { - return XMLHandle( _node ? _node->FirstChildElement( name ) : 0 ); - } - /// Get the last child of this handle. - XMLHandle LastChild() { - return XMLHandle( _node ? _node->LastChild() : 0 ); - } - /// Get the last child element of this handle. - XMLHandle LastChildElement( const char* name = 0 ) { - return XMLHandle( _node ? _node->LastChildElement( name ) : 0 ); - } - /// Get the previous sibling of this handle. - XMLHandle PreviousSibling() { - return XMLHandle( _node ? _node->PreviousSibling() : 0 ); - } - /// Get the previous sibling element of this handle. - XMLHandle PreviousSiblingElement( const char* name = 0 ) { - return XMLHandle( _node ? _node->PreviousSiblingElement( name ) : 0 ); - } - /// Get the next sibling of this handle. - XMLHandle NextSibling() { - return XMLHandle( _node ? _node->NextSibling() : 0 ); - } - /// Get the next sibling element of this handle. - XMLHandle NextSiblingElement( const char* name = 0 ) { - return XMLHandle( _node ? _node->NextSiblingElement( name ) : 0 ); - } - - /// Safe cast to XMLNode. This can return null. - XMLNode* ToNode() { - return _node; - } - /// Safe cast to XMLElement. This can return null. - XMLElement* ToElement() { - return ( _node ? _node->ToElement() : 0 ); - } - /// Safe cast to XMLText. This can return null. - XMLText* ToText() { - return ( _node ? _node->ToText() : 0 ); - } - /// Safe cast to XMLUnknown. This can return null. - XMLUnknown* ToUnknown() { - return ( _node ? _node->ToUnknown() : 0 ); - } - /// Safe cast to XMLDeclaration. This can return null. - XMLDeclaration* ToDeclaration() { - return ( _node ? _node->ToDeclaration() : 0 ); - } - -private: - XMLNode* _node; -}; - - -/** - A variant of the XMLHandle class for working with const XMLNodes and Documents. It is the - same in all regards, except for the 'const' qualifiers. See XMLHandle for API. -*/ -class TINYXML2_LIB XMLConstHandle -{ -public: - explicit XMLConstHandle( const XMLNode* node ) : _node( node ) { - } - explicit XMLConstHandle( const XMLNode& node ) : _node( &node ) { - } - XMLConstHandle( const XMLConstHandle& ref ) : _node( ref._node ) { - } - - XMLConstHandle& operator=( const XMLConstHandle& ref ) { - _node = ref._node; - return *this; - } - - const XMLConstHandle FirstChild() const { - return XMLConstHandle( _node ? _node->FirstChild() : 0 ); - } - const XMLConstHandle FirstChildElement( const char* name = 0 ) const { - return XMLConstHandle( _node ? _node->FirstChildElement( name ) : 0 ); - } - const XMLConstHandle LastChild() const { - return XMLConstHandle( _node ? _node->LastChild() : 0 ); - } - const XMLConstHandle LastChildElement( const char* name = 0 ) const { - return XMLConstHandle( _node ? _node->LastChildElement( name ) : 0 ); - } - const XMLConstHandle PreviousSibling() const { - return XMLConstHandle( _node ? _node->PreviousSibling() : 0 ); - } - const XMLConstHandle PreviousSiblingElement( const char* name = 0 ) const { - return XMLConstHandle( _node ? _node->PreviousSiblingElement( name ) : 0 ); - } - const XMLConstHandle NextSibling() const { - return XMLConstHandle( _node ? _node->NextSibling() : 0 ); - } - const XMLConstHandle NextSiblingElement( const char* name = 0 ) const { - return XMLConstHandle( _node ? _node->NextSiblingElement( name ) : 0 ); - } - - - const XMLNode* ToNode() const { - return _node; - } - const XMLElement* ToElement() const { - return ( _node ? _node->ToElement() : 0 ); - } - const XMLText* ToText() const { - return ( _node ? _node->ToText() : 0 ); - } - const XMLUnknown* ToUnknown() const { - return ( _node ? _node->ToUnknown() : 0 ); - } - const XMLDeclaration* ToDeclaration() const { - return ( _node ? _node->ToDeclaration() : 0 ); - } - -private: - const XMLNode* _node; -}; - - -/** - Printing functionality. The XMLPrinter gives you more - options than the XMLDocument::Print() method. - - It can: - -# Print to memory. - -# Print to a file you provide. - -# Print XML without a XMLDocument. - - Print to Memory - - @verbatim - XMLPrinter printer; - doc.Print( &printer ); - SomeFunction( printer.CStr() ); - @endverbatim - - Print to a File - - You provide the file pointer. - @verbatim - XMLPrinter printer( fp ); - doc.Print( &printer ); - @endverbatim - - Print without a XMLDocument - - When loading, an XML parser is very useful. However, sometimes - when saving, it just gets in the way. The code is often set up - for streaming, and constructing the DOM is just overhead. - - The Printer supports the streaming case. The following code - prints out a trivially simple XML file without ever creating - an XML document. - - @verbatim - XMLPrinter printer( fp ); - printer.OpenElement( "foo" ); - printer.PushAttribute( "foo", "bar" ); - printer.CloseElement(); - @endverbatim -*/ -class TINYXML2_LIB XMLPrinter : public XMLVisitor -{ -public: - /** Construct the printer. If the FILE* is specified, - this will print to the FILE. Else it will print - to memory, and the result is available in CStr(). - If 'compact' is set to true, then output is created - with only required whitespace and newlines. - */ - XMLPrinter( FILE* file=0, bool compact = false, int depth = 0 ); - virtual ~XMLPrinter() {} - - /** If streaming, write the BOM and declaration. */ - void PushHeader( bool writeBOM, bool writeDeclaration ); - /** If streaming, start writing an element. - The element must be closed with CloseElement() - */ - void OpenElement( const char* name, bool compactMode=false ); - /// If streaming, add an attribute to an open element. - void PushAttribute( const char* name, const char* value ); - void PushAttribute( const char* name, int value ); - void PushAttribute( const char* name, unsigned value ); - void PushAttribute(const char* name, int64_t value); - void PushAttribute( const char* name, bool value ); - void PushAttribute( const char* name, double value ); - /// If streaming, close the Element. - virtual void CloseElement( bool compactMode=false ); - - /// Add a text node. - void PushText( const char* text, bool cdata=false ); - /// Add a text node from an integer. - void PushText( int value ); - /// Add a text node from an unsigned. - void PushText( unsigned value ); - /// Add a text node from an unsigned. - void PushText(int64_t value); - /// Add a text node from a bool. - void PushText( bool value ); - /// Add a text node from a float. - void PushText( float value ); - /// Add a text node from a double. - void PushText( double value ); - - /// Add a comment - void PushComment( const char* comment ); - - void PushDeclaration( const char* value ); - void PushUnknown( const char* value ); - - virtual bool VisitEnter( const XMLDocument& /*doc*/ ); - virtual bool VisitExit( const XMLDocument& /*doc*/ ) { - return true; - } - - virtual bool VisitEnter( const XMLElement& element, const XMLAttribute* attribute ); - virtual bool VisitExit( const XMLElement& element ); - - virtual bool Visit( const XMLText& text ); - virtual bool Visit( const XMLComment& comment ); - virtual bool Visit( const XMLDeclaration& declaration ); - virtual bool Visit( const XMLUnknown& unknown ); - - /** - If in print to memory mode, return a pointer to - the XML file in memory. - */ - const char* CStr() const { - return _buffer.Mem(); - } - /** - If in print to memory mode, return the size - of the XML file in memory. (Note the size returned - includes the terminating null.) - */ - int CStrSize() const { - return _buffer.Size(); - } - /** - If in print to memory mode, reset the buffer to the - beginning. - */ - void ClearBuffer() { - _buffer.Clear(); - _buffer.Push(0); - _firstElement = true; - } - -protected: - virtual bool CompactMode( const XMLElement& ) { return _compactMode; } - - /** Prints out the space before an element. You may override to change - the space and tabs used. A PrintSpace() override should call Print(). - */ - virtual void PrintSpace( int depth ); - void Print( const char* format, ... ); - void Write( const char* data, size_t size ); - inline void Write( const char* data ) { Write( data, strlen( data ) ); } - void Putc( char ch ); - - void SealElementIfJustOpened(); - bool _elementJustOpened; - DynArray< const char*, 10 > _stack; - -private: - void PrintString( const char*, bool restrictedEntitySet ); // prints out, after detecting entities. - - bool _firstElement; - FILE* _fp; - int _depth; - int _textDepth; - bool _processEntities; - bool _compactMode; - - enum { - ENTITY_RANGE = 64, - BUF_SIZE = 200 - }; - bool _entityFlag[ENTITY_RANGE]; - bool _restrictedEntityFlag[ENTITY_RANGE]; - - DynArray< char, 20 > _buffer; - - // Prohibit cloning, intentionally not implemented - XMLPrinter( const XMLPrinter& ); - XMLPrinter& operator=( const XMLPrinter& ); -}; - - -} // tinyxml2 - -#if defined(_MSC_VER) -# pragma warning(pop) -#endif - -#endif // TINYXML2_INCLUDED diff --git a/tools/ZAPDConfigs/ActorList.txt b/tools/ZAPDConfigs/ActorList.txt deleted file mode 100644 index a0395eb277..0000000000 --- a/tools/ZAPDConfigs/ActorList.txt +++ /dev/null @@ -1,472 +0,0 @@ -ACTOR_PLAYER -ACTOR_UNSET_1 -ACTOR_EN_TEST -ACTOR_UNSET_3 -ACTOR_EN_GIRLA -ACTOR_UNSET_5 -ACTOR_UNSET_6 -ACTOR_EN_PART -ACTOR_EN_LIGHT -ACTOR_EN_DOOR -ACTOR_EN_BOX -ACTOR_BG_DY_YOSEIZO -ACTOR_BG_HIDAN_FIREWALL -ACTOR_EN_POH -ACTOR_EN_OKUTA -ACTOR_BG_YDAN_SP -ACTOR_EN_BOM -ACTOR_EN_WALLMAS -ACTOR_EN_DODONGO -ACTOR_EN_FIREFLY -ACTOR_EN_HORSE -ACTOR_EN_ITEM00 -ACTOR_EN_ARROW -ACTOR_UNSET_17 -ACTOR_EN_ELF -ACTOR_EN_NIW -ACTOR_UNSET_1A -ACTOR_EN_TITE -ACTOR_EN_REEBA -ACTOR_EN_PEEHAT -ACTOR_EN_BUTTE -ACTOR_UNSET_1F -ACTOR_EN_INSECT -ACTOR_EN_FISH -ACTOR_UNSET_22 -ACTOR_EN_HOLL -ACTOR_EN_SCENE_CHANGE -ACTOR_EN_ZF -ACTOR_EN_HATA -ACTOR_BOSS_DODONGO -ACTOR_BOSS_GOMA -ACTOR_EN_ZL1 -ACTOR_EN_VIEWER -ACTOR_EN_GOMA -ACTOR_BG_PUSHBOX -ACTOR_EN_BUBBLE -ACTOR_DOOR_SHUTTER -ACTOR_EN_DODOJR -ACTOR_EN_BDFIRE -ACTOR_UNSET_31 -ACTOR_EN_BOOM -ACTOR_EN_TORCH2 -ACTOR_EN_BILI -ACTOR_EN_TP -ACTOR_UNSET_36 -ACTOR_EN_ST -ACTOR_EN_BW -ACTOR_EN_A_OBJ -ACTOR_EN_EIYER -ACTOR_EN_RIVER_SOUND -ACTOR_EN_HORSE_NORMAL -ACTOR_EN_OSSAN -ACTOR_BG_TREEMOUTH -ACTOR_BG_DODOAGO -ACTOR_BG_HIDAN_DALM -ACTOR_BG_HIDAN_HROCK -ACTOR_EN_HORSE_GANON -ACTOR_BG_HIDAN_ROCK -ACTOR_BG_HIDAN_RSEKIZOU -ACTOR_BG_HIDAN_SEKIZOU -ACTOR_BG_HIDAN_SIMA -ACTOR_BG_HIDAN_SYOKU -ACTOR_EN_XC -ACTOR_BG_HIDAN_CURTAIN -ACTOR_BG_SPOT00_HANEBASI -ACTOR_EN_MB -ACTOR_EN_BOMBF -ACTOR_EN_ZL2 -ACTOR_BG_HIDAN_FSLIFT -ACTOR_EN_OE2 -ACTOR_BG_YDAN_HASI -ACTOR_BG_YDAN_MARUTA -ACTOR_BOSS_GANONDROF -ACTOR_UNSET_53 -ACTOR_EN_AM -ACTOR_EN_DEKUBABA -ACTOR_EN_M_FIRE1 -ACTOR_EN_M_THUNDER -ACTOR_BG_DDAN_JD -ACTOR_BG_BREAKWALL -ACTOR_EN_JJ -ACTOR_EN_HORSE_ZELDA -ACTOR_BG_DDAN_KD -ACTOR_DOOR_WARP1 -ACTOR_OBJ_SYOKUDAI -ACTOR_ITEM_B_HEART -ACTOR_EN_DEKUNUTS -ACTOR_BG_MENKURI_KAITEN -ACTOR_BG_MENKURI_EYE -ACTOR_EN_VALI -ACTOR_BG_MIZU_MOVEBG -ACTOR_BG_MIZU_WATER -ACTOR_ARMS_HOOK -ACTOR_EN_FHG -ACTOR_BG_MORI_HINERI -ACTOR_EN_BB -ACTOR_BG_TOKI_HIKARI -ACTOR_EN_YUKABYUN -ACTOR_BG_TOKI_SWD -ACTOR_EN_FHG_FIRE -ACTOR_BG_MJIN -ACTOR_BG_HIDAN_KOUSI -ACTOR_DOOR_TOKI -ACTOR_BG_HIDAN_HAMSTEP -ACTOR_EN_BIRD -ACTOR_UNSET_73 -ACTOR_UNSET_74 -ACTOR_UNSET_75 -ACTOR_UNSET_76 -ACTOR_EN_WOOD02 -ACTOR_UNSET_78 -ACTOR_UNSET_79 -ACTOR_UNSET_7A -ACTOR_UNSET_7B -ACTOR_EN_LIGHTBOX -ACTOR_EN_PU_BOX -ACTOR_UNSET_7E -ACTOR_UNSET_7F -ACTOR_EN_TRAP -ACTOR_EN_AROW_TRAP -ACTOR_EN_VASE -ACTOR_UNSET_83 -ACTOR_EN_TA -ACTOR_EN_TK -ACTOR_BG_MORI_BIGST -ACTOR_BG_MORI_ELEVATOR -ACTOR_BG_MORI_KAITENKABE -ACTOR_BG_MORI_RAKKATENJO -ACTOR_EN_VM -ACTOR_DEMO_EFFECT -ACTOR_DEMO_KANKYO -ACTOR_BG_HIDAN_FWBIG -ACTOR_EN_FLOORMAS -ACTOR_EN_HEISHI1 -ACTOR_EN_RD -ACTOR_EN_PO_SISTERS -ACTOR_BG_HEAVY_BLOCK -ACTOR_BG_PO_EVENT -ACTOR_OBJ_MURE -ACTOR_EN_SW -ACTOR_BOSS_FD -ACTOR_OBJECT_KANKYO -ACTOR_EN_DU -ACTOR_EN_FD -ACTOR_EN_HORSE_LINK_CHILD -ACTOR_DOOR_ANA -ACTOR_BG_SPOT02_OBJECTS -ACTOR_BG_HAKA -ACTOR_MAGIC_WIND -ACTOR_MAGIC_FIRE -ACTOR_UNSET_A0 -ACTOR_EN_RU1 -ACTOR_BOSS_FD2 -ACTOR_EN_FD_FIRE -ACTOR_EN_DH -ACTOR_EN_DHA -ACTOR_EN_RL -ACTOR_EN_ENCOUNT1 -ACTOR_DEMO_DU -ACTOR_DEMO_IM -ACTOR_DEMO_TRE_LGT -ACTOR_EN_FW -ACTOR_BG_VB_SIMA -ACTOR_EN_VB_BALL -ACTOR_BG_HAKA_MEGANE -ACTOR_BG_HAKA_MEGANEBG -ACTOR_BG_HAKA_SHIP -ACTOR_BG_HAKA_SGAMI -ACTOR_UNSET_B2 -ACTOR_EN_HEISHI2 -ACTOR_EN_ENCOUNT2 -ACTOR_EN_FIRE_ROCK -ACTOR_EN_BROB -ACTOR_MIR_RAY -ACTOR_BG_SPOT09_OBJ -ACTOR_BG_SPOT18_OBJ -ACTOR_BOSS_VA -ACTOR_BG_HAKA_TUBO -ACTOR_BG_HAKA_TRAP -ACTOR_BG_HAKA_HUTA -ACTOR_BG_HAKA_ZOU -ACTOR_BG_SPOT17_FUNEN -ACTOR_EN_SYATEKI_ITM -ACTOR_EN_SYATEKI_MAN -ACTOR_EN_TANA -ACTOR_EN_NB -ACTOR_BOSS_MO -ACTOR_EN_SB -ACTOR_EN_BIGOKUTA -ACTOR_EN_KAREBABA -ACTOR_BG_BDAN_OBJECTS -ACTOR_DEMO_SA -ACTOR_DEMO_GO -ACTOR_EN_IN -ACTOR_EN_TR -ACTOR_BG_SPOT16_BOMBSTONE -ACTOR_UNSET_CE -ACTOR_BG_HIDAN_KOWARERUKABE -ACTOR_BG_BOMBWALL -ACTOR_BG_SPOT08_ICEBLOCK -ACTOR_EN_RU2 -ACTOR_OBJ_DEKUJR -ACTOR_BG_MIZU_UZU -ACTOR_BG_SPOT06_OBJECTS -ACTOR_BG_ICE_OBJECTS -ACTOR_BG_HAKA_WATER -ACTOR_UNSET_D8 -ACTOR_EN_MA2 -ACTOR_EN_BOM_CHU -ACTOR_EN_HORSE_GAME_CHECK -ACTOR_BOSS_TW -ACTOR_EN_RR -ACTOR_EN_BA -ACTOR_EN_BX -ACTOR_EN_ANUBICE -ACTOR_EN_ANUBICE_FIRE -ACTOR_BG_MORI_HASHIGO -ACTOR_BG_MORI_HASHIRA4 -ACTOR_BG_MORI_IDOMIZU -ACTOR_BG_SPOT16_DOUGHNUT -ACTOR_BG_BDAN_SWITCH -ACTOR_EN_MA1 -ACTOR_BOSS_GANON -ACTOR_BOSS_SST -ACTOR_UNSET_EA -ACTOR_UNSET_EB -ACTOR_EN_NY -ACTOR_EN_FR -ACTOR_ITEM_SHIELD -ACTOR_BG_ICE_SHELTER -ACTOR_EN_ICE_HONO -ACTOR_ITEM_OCARINA -ACTOR_UNSET_F2 -ACTOR_UNSET_F3 -ACTOR_MAGIC_DARK -ACTOR_DEMO_6K -ACTOR_EN_ANUBICE_TAG -ACTOR_BG_HAKA_GATE -ACTOR_BG_SPOT15_SAKU -ACTOR_BG_JYA_GOROIWA -ACTOR_BG_JYA_ZURERUKABE -ACTOR_UNSET_FB -ACTOR_BG_JYA_COBRA -ACTOR_BG_JYA_KANAAMI -ACTOR_FISHING -ACTOR_OBJ_OSHIHIKI -ACTOR_BG_GATE_SHUTTER -ACTOR_EFF_DUST -ACTOR_BG_SPOT01_FUSYA -ACTOR_BG_SPOT01_IDOHASHIRA -ACTOR_BG_SPOT01_IDOMIZU -ACTOR_BG_PO_SYOKUDAI -ACTOR_BG_GANON_OTYUKA -ACTOR_BG_SPOT15_RRBOX -ACTOR_BG_UMAJUMP -ACTOR_UNSET_109 -ACTOR_ARROW_FIRE -ACTOR_ARROW_ICE -ACTOR_ARROW_LIGHT -ACTOR_UNSET_10D -ACTOR_UNSET_10E -ACTOR_ITEM_ETCETERA -ACTOR_OBJ_KIBAKO -ACTOR_OBJ_TSUBO -ACTOR_EN_WONDER_ITEM -ACTOR_EN_IK -ACTOR_DEMO_IK -ACTOR_EN_SKJ -ACTOR_EN_SKJNEEDLE -ACTOR_EN_G_SWITCH -ACTOR_DEMO_EXT -ACTOR_DEMO_SHD -ACTOR_EN_DNS -ACTOR_ELF_MSG -ACTOR_EN_HONOTRAP -ACTOR_EN_TUBO_TRAP -ACTOR_OBJ_ICE_POLY -ACTOR_BG_SPOT03_TAKI -ACTOR_BG_SPOT07_TAKI -ACTOR_EN_FZ -ACTOR_EN_PO_RELAY -ACTOR_BG_RELAY_OBJECTS -ACTOR_EN_DIVING_GAME -ACTOR_EN_KUSA -ACTOR_OBJ_BEAN -ACTOR_OBJ_BOMBIWA -ACTOR_UNSET_128 -ACTOR_UNSET_129 -ACTOR_OBJ_SWITCH -ACTOR_OBJ_ELEVATOR -ACTOR_OBJ_LIFT -ACTOR_OBJ_HSBLOCK -ACTOR_EN_OKARINA_TAG -ACTOR_EN_YABUSAME_MARK -ACTOR_EN_GOROIWA -ACTOR_EN_EX_RUPPY -ACTOR_EN_TORYO -ACTOR_EN_DAIKU -ACTOR_UNSET_134 -ACTOR_EN_NWC -ACTOR_EN_BLKOBJ -ACTOR_ITEM_INBOX -ACTOR_EN_GE1 -ACTOR_OBJ_BLOCKSTOP -ACTOR_EN_SDA -ACTOR_EN_CLEAR_TAG -ACTOR_EN_NIW_LADY -ACTOR_EN_GM -ACTOR_EN_MS -ACTOR_EN_HS -ACTOR_BG_INGATE -ACTOR_EN_KANBAN -ACTOR_EN_HEISHI3 -ACTOR_EN_SYATEKI_NIW -ACTOR_EN_ATTACK_NIW -ACTOR_BG_SPOT01_IDOSOKO -ACTOR_EN_SA -ACTOR_EN_WONDER_TALK -ACTOR_BG_GJYO_BRIDGE -ACTOR_EN_DS -ACTOR_EN_MK -ACTOR_EN_BOM_BOWL_MAN -ACTOR_EN_BOM_BOWL_PIT -ACTOR_EN_OWL -ACTOR_EN_ISHI -ACTOR_OBJ_HANA -ACTOR_OBJ_LIGHTSWITCH -ACTOR_OBJ_MURE2 -ACTOR_EN_GO -ACTOR_EN_FU -ACTOR_UNSET_154 -ACTOR_EN_CHANGER -ACTOR_BG_JYA_MEGAMI -ACTOR_BG_JYA_LIFT -ACTOR_BG_JYA_BIGMIRROR -ACTOR_BG_JYA_BOMBCHUIWA -ACTOR_BG_JYA_AMISHUTTER -ACTOR_BG_JYA_BOMBIWA -ACTOR_BG_SPOT18_BASKET -ACTOR_UNSET_15D -ACTOR_EN_GANON_ORGAN -ACTOR_EN_SIOFUKI -ACTOR_EN_STREAM -ACTOR_UNSET_161 -ACTOR_EN_MM -ACTOR_EN_KO -ACTOR_EN_KZ -ACTOR_EN_WEATHER_TAG -ACTOR_BG_SST_FLOOR -ACTOR_EN_ANI -ACTOR_EN_EX_ITEM -ACTOR_BG_JYA_IRONOBJ -ACTOR_EN_JS -ACTOR_EN_JSJUTAN -ACTOR_EN_CS -ACTOR_EN_MD -ACTOR_EN_HY -ACTOR_EN_GANON_MANT -ACTOR_EN_OKARINA_EFFECT -ACTOR_EN_MAG -ACTOR_DOOR_GERUDO -ACTOR_ELF_MSG2 -ACTOR_DEMO_GT -ACTOR_EN_PO_FIELD -ACTOR_EFC_ERUPC -ACTOR_BG_ZG -ACTOR_EN_HEISHI4 -ACTOR_EN_ZL3 -ACTOR_BOSS_GANON2 -ACTOR_EN_KAKASI -ACTOR_EN_TAKARA_MAN -ACTOR_OBJ_MAKEOSHIHIKI -ACTOR_OCEFF_SPOT -ACTOR_END_TITLE -ACTOR_UNSET_180 -ACTOR_EN_TORCH -ACTOR_DEMO_EC -ACTOR_SHOT_SUN -ACTOR_EN_DY_EXTRA -ACTOR_EN_WONDER_TALK2 -ACTOR_EN_GE2 -ACTOR_OBJ_ROOMTIMER -ACTOR_EN_SSH -ACTOR_EN_STH -ACTOR_OCEFF_WIPE -ACTOR_OCEFF_STORM -ACTOR_EN_WEIYER -ACTOR_BG_SPOT05_SOKO -ACTOR_BG_JYA_1FLIFT -ACTOR_BG_JYA_HAHENIRON -ACTOR_BG_SPOT12_GATE -ACTOR_BG_SPOT12_SAKU -ACTOR_EN_HINTNUTS -ACTOR_EN_NUTSBALL -ACTOR_BG_SPOT00_BREAK -ACTOR_EN_SHOPNUTS -ACTOR_EN_IT -ACTOR_EN_GELDB -ACTOR_OCEFF_WIPE2 -ACTOR_OCEFF_WIPE3 -ACTOR_EN_NIW_GIRL -ACTOR_EN_DOG -ACTOR_EN_SI -ACTOR_BG_SPOT01_OBJECTS2 -ACTOR_OBJ_COMB -ACTOR_BG_SPOT11_BAKUDANKABE -ACTOR_OBJ_KIBAKO2 -ACTOR_EN_DNT_DEMO -ACTOR_EN_DNT_JIJI -ACTOR_EN_DNT_NOMAL -ACTOR_EN_GUEST -ACTOR_BG_BOM_GUARD -ACTOR_EN_HS2 -ACTOR_DEMO_KEKKAI -ACTOR_BG_SPOT08_BAKUDANKABE -ACTOR_BG_SPOT17_BAKUDANKABE -ACTOR_UNSET_1AA -ACTOR_OBJ_MURE3 -ACTOR_EN_TG -ACTOR_EN_MU -ACTOR_EN_GO2 -ACTOR_EN_WF -ACTOR_EN_SKB -ACTOR_DEMO_GJ -ACTOR_DEMO_GEFF -ACTOR_BG_GND_FIREMEIRO -ACTOR_BG_GND_DARKMEIRO -ACTOR_BG_GND_SOULMEIRO -ACTOR_BG_GND_NISEKABE -ACTOR_BG_GND_ICEBLOCK -ACTOR_EN_GB -ACTOR_EN_GS -ACTOR_BG_MIZU_BWALL -ACTOR_BG_MIZU_SHUTTER -ACTOR_EN_DAIKU_KAKARIKO -ACTOR_BG_BOWL_WALL -ACTOR_EN_WALL_TUBO -ACTOR_EN_PO_DESERT -ACTOR_EN_CROW -ACTOR_DOOR_KILLER -ACTOR_BG_SPOT11_OASIS -ACTOR_BG_SPOT18_FUTA -ACTOR_BG_SPOT18_SHUTTER -ACTOR_EN_MA3 -ACTOR_EN_COW -ACTOR_BG_ICE_TURARA -ACTOR_BG_ICE_SHUTTER -ACTOR_EN_KAKASI2 -ACTOR_EN_KAKASI3 -ACTOR_OCEFF_WIPE4 -ACTOR_EN_EG -ACTOR_BG_MENKURI_NISEKABE -ACTOR_EN_ZO -ACTOR_OBJ_MAKEKINSUTA -ACTOR_EN_GE3 -ACTOR_OBJ_TIMEBLOCK -ACTOR_OBJ_HAMISHI -ACTOR_EN_ZL4 -ACTOR_EN_MM2 -ACTOR_BG_JYA_BLOCK -ACTOR_OBJ_WARP2BLOCK -ACTOR_ID_MAX \ No newline at end of file diff --git a/tools/ZAPDConfigs/EntranceList.txt b/tools/ZAPDConfigs/EntranceList.txt deleted file mode 100644 index 5ff4617df1..0000000000 --- a/tools/ZAPDConfigs/EntranceList.txt +++ /dev/null @@ -1,1556 +0,0 @@ -ENTR_DEKU_TREE_0 -ENTR_DEKU_TREE_0_1 -ENTR_DEKU_TREE_0_2 -ENTR_DEKU_TREE_0_3 -ENTR_DODONGOS_CAVERN_0 -ENTR_DODONGOS_CAVERN_0_1 -ENTR_DODONGOS_CAVERN_0_2 -ENTR_DODONGOS_CAVERN_0_3 -ENTR_GERUDO_TRAINING_GROUND_0 -ENTR_GERUDO_TRAINING_GROUND_0_1 -ENTR_GERUDO_TRAINING_GROUND_0_2 -ENTR_GERUDO_TRAINING_GROUND_0_3 -ENTR_FOREST_TEMPLE_BOSS_0 -ENTR_FOREST_TEMPLE_BOSS_0_1 -ENTR_FOREST_TEMPLE_BOSS_0_2 -ENTR_FOREST_TEMPLE_BOSS_0_3 -ENTR_WATER_TEMPLE_0 -ENTR_WATER_TEMPLE_0_1 -ENTR_WATER_TEMPLE_0_2 -ENTR_WATER_TEMPLE_0_3 -ENTR_UNUSED_6E -ENTR_UNUSED_6E_1 -ENTR_UNUSED_6E_2 -ENTR_UNUSED_6E_3 -ENTR_SASATEST_0 -ENTR_SASATEST_0_1 -ENTR_SASATEST_0_2 -ENTR_SASATEST_0_3 -ENTR_SYOTES_0 -ENTR_SYOTES_0_1 -ENTR_SYOTES_0_2 -ENTR_SYOTES_0_3 -ENTR_SYOTES2_0 -ENTR_SYOTES2_0_1 -ENTR_SYOTES2_0_2 -ENTR_SYOTES2_0_3 -ENTR_TESTROOM_0 -ENTR_TESTROOM_0_1 -ENTR_TESTROOM_0_2 -ENTR_TESTROOM_0_3 -ENTR_JABU_JABU_0 -ENTR_JABU_JABU_0_1 -ENTR_JABU_JABU_0_2 -ENTR_JABU_JABU_0_3 -ENTR_JABU_JABU_0_4 -ENTR_ROYAL_FAMILYS_TOMB_0 -ENTR_ROYAL_FAMILYS_TOMB_0_1 -ENTR_ROYAL_FAMILYS_TOMB_0_2 -ENTR_ROYAL_FAMILYS_TOMB_0_3 -ENTR_ROYAL_FAMILYS_TOMB_0_4 -ENTR_ROYAL_FAMILYS_TOMB_0_5 -ENTR_MARKET_ENTRANCE_DAY_0 -ENTR_MARKET_ENTRANCE_NIGHT_0_1 -ENTR_MARKET_ENTRANCE_RUINS_0_2 -ENTR_MARKET_ENTRANCE_RUINS_0_3 -ENTR_SHADOW_TEMPLE_0 -ENTR_SHADOW_TEMPLE_0_1 -ENTR_SHADOW_TEMPLE_0_2 -ENTR_SHADOW_TEMPLE_0_3 -ENTR_SHOOTING_GALLERY_0 -ENTR_SHOOTING_GALLERY_0_1 -ENTR_SHOOTING_GALLERY_0_2 -ENTR_SHOOTING_GALLERY_0_3 -ENTR_GROTTOS_0 -ENTR_GROTTOS_0_1 -ENTR_GROTTOS_0_2 -ENTR_GROTTOS_0_3 -ENTR_LAKESIDE_LABORATORY_0 -ENTR_LAKESIDE_LABORATORY_0_1 -ENTR_LAKESIDE_LABORATORY_0_2 -ENTR_LAKESIDE_LABORATORY_0_3 -ENTR_SUTARU_0 -ENTR_SUTARU_0_1 -ENTR_SUTARU_0_2 -ENTR_SUTARU_0_3 -ENTR_GRAVE_WITH_FAIRYS_FOUNTAIN_0 -ENTR_GRAVE_WITH_FAIRYS_FOUNTAIN_0_1 -ENTR_GRAVE_WITH_FAIRYS_FOUNTAIN_0_2 -ENTR_GRAVE_WITH_FAIRYS_FOUNTAIN_0_3 -ENTR_LON_LON_BUILDINGS_0 -ENTR_LON_LON_BUILDINGS_0_1 -ENTR_LON_LON_BUILDINGS_0_2 -ENTR_LON_LON_BUILDINGS_0_3 -ENTR_TEMPLE_OF_TIME_0 -ENTR_TEMPLE_OF_TIME_0_1 -ENTR_TEMPLE_OF_TIME_0_2 -ENTR_TEMPLE_OF_TIME_0_3 -ENTR_TEMPLE_OF_TIME_0_4 -ENTR_TEMPLE_OF_TIME_0_5 -ENTR_TEMPLE_OF_TIME_0_6 -ENTR_TEMPLE_OF_TIME_0_7 -ENTR_TEMPLE_OF_TIME_0_8 -ENTR_TEMPLE_OF_TIME_0_9 -ENTR_TEMPLE_OF_TIME_0_10 -ENTR_TEMPLE_OF_TIME_0_11 -ENTR_TEMPLE_OF_TIME_0_12 -ENTR_TEMPLE_OF_TIME_0_13 -ENTR_TEMPLE_OF_TIME_0_14 -ENTR_TEMPLE_OF_TIME_0_15 -ENTR_TREASURE_BOX_SHOP_0 -ENTR_TREASURE_BOX_SHOP_0_1 -ENTR_TREASURE_BOX_SHOP_0_2 -ENTR_TREASURE_BOX_SHOP_0_3 -ENTR_BACK_ALLEY_DAY_3 -ENTR_BACK_ALLEY_NIGHT_3_1 -ENTR_BACK_ALLEY_DAY_3_2 -ENTR_BACK_ALLEY_NIGHT_3_3 -ENTR_CHAMBER_OF_THE_SAGES_0 -ENTR_CHAMBER_OF_THE_SAGES_0_1 -ENTR_CHAMBER_OF_THE_SAGES_0_2 -ENTR_CHAMBER_OF_THE_SAGES_0_3 -ENTR_CHAMBER_OF_THE_SAGES_0_4 -ENTR_CHAMBER_OF_THE_SAGES_0_5 -ENTR_CHAMBER_OF_THE_SAGES_0_6 -ENTR_POTION_SHOP_GRANNY_0 -ENTR_POTION_SHOP_GRANNY_0_1 -ENTR_POTION_SHOP_GRANNY_0_2 -ENTR_POTION_SHOP_GRANNY_0_3 -ENTR_HAIRAL_NIWA2_0 -ENTR_HAIRAL_NIWA2_0_1 -ENTR_HAIRAL_NIWA2_0_2 -ENTR_HAIRAL_NIWA2_0_3 -ENTR_CASTLE_COURTYARD_GUARDS_DAY_0 -ENTR_CASTLE_COURTYARD_GUARDS_NIGHT_0_1 -ENTR_CASTLE_COURTYARD_GUARDS_DAY_0_2 -ENTR_CASTLE_COURTYARD_GUARDS_NIGHT_0_3 -ENTR_MARKET_GUARD_HOUSE_0 -ENTR_MARKET_GUARD_HOUSE_0_1 -ENTR_MARKET_GUARD_HOUSE_0_2 -ENTR_MARKET_GUARD_HOUSE_0_3 -ENTR_SPIRIT_TEMPLE_0 -ENTR_SPIRIT_TEMPLE_0_1 -ENTR_SPIRIT_TEMPLE_0_2 -ENTR_SPIRIT_TEMPLE_0_3 -ENTR_SPIRIT_TEMPLE_0_4 -ENTR_SPIRIT_TEMPLE_0_5 -ENTR_ICE_CAVERN_0 -ENTR_ICE_CAVERN_0_1 -ENTR_ICE_CAVERN_0_2 -ENTR_ICE_CAVERN_0_3 -ENTR_ICE_CAVERN_0_4 -ENTR_SPIRIT_TEMPLE_BOSS_0 -ENTR_SPIRIT_TEMPLE_BOSS_0_1 -ENTR_SPIRIT_TEMPLE_BOSS_0_2 -ENTR_SPIRIT_TEMPLE_BOSS_0_3 -ENTR_SPIRIT_TEMPLE_BOSS_0_4 -ENTR_SPIRIT_TEMPLE_BOSS_0_5 -ENTR_SPIRIT_TEMPLE_BOSS_0_6 -ENTR_TEST01_0 -ENTR_TEST01_0_1 -ENTR_TEST01_0_2 -ENTR_TEST01_0_3 -ENTR_BOTTOM_OF_THE_WELL_0 -ENTR_BOTTOM_OF_THE_WELL_0_1 -ENTR_BOTTOM_OF_THE_WELL_0_2 -ENTR_BOTTOM_OF_THE_WELL_0_3 -ENTR_TWINS_HOUSE_0 -ENTR_TWINS_HOUSE_0_1 -ENTR_TWINS_HOUSE_0_2 -ENTR_TWINS_HOUSE_0_3 -ENTR_CUTSCENE_MAP_0 -ENTR_CUTSCENE_MAP_0_1 -ENTR_CUTSCENE_MAP_0_2 -ENTR_CUTSCENE_MAP_0_3 -ENTR_CUTSCENE_MAP_0_4 -ENTR_CUTSCENE_MAP_0_5 -ENTR_CUTSCENE_MAP_0_6 -ENTR_CUTSCENE_MAP_0_7 -ENTR_CUTSCENE_MAP_0_8 -ENTR_CUTSCENE_MAP_0_9 -ENTR_CUTSCENE_MAP_0_10 -ENTR_CUTSCENE_MAP_0_11 -ENTR_CUTSCENE_MAP_0_12 -ENTR_BACK_ALLEY_DAY_0 -ENTR_BACK_ALLEY_NIGHT_0_1 -ENTR_BACK_ALLEY_DAY_0_2 -ENTR_BACK_ALLEY_NIGHT_0_3 -ENTR_MARKET_DAY_0 -ENTR_MARKET_NIGHT_0_1 -ENTR_MARKET_RUINS_0_2 -ENTR_MARKET_RUINS_0_3 -ENTR_MARKET_DAY_0_4 -ENTR_DEPTH_TEST_0 -ENTR_BAZAAR_0 -ENTR_BAZAAR_0_1 -ENTR_BAZAAR_0_2 -ENTR_BAZAAR_0_3 -ENTR_LINKS_HOUSE_0 -ENTR_LINKS_HOUSE_0_1 -ENTR_LINKS_HOUSE_0_2 -ENTR_LINKS_HOUSE_0_3 -ENTR_LINKS_HOUSE_0_4 -ENTR_LINKS_HOUSE_0_5 -ENTR_KOKIRI_SHOP_0 -ENTR_KOKIRI_SHOP_0_1 -ENTR_KOKIRI_SHOP_0_2 -ENTR_KOKIRI_SHOP_0_3 -ENTR_DODONGOS_CAVERN_1 -ENTR_DODONGOS_CAVERN_1_1 -ENTR_DODONGOS_CAVERN_1_2 -ENTR_DODONGOS_CAVERN_1_3 -ENTR_KNOW_IT_ALL_BROS_HOUSE_0 -ENTR_KNOW_IT_ALL_BROS_HOUSE_0_1 -ENTR_KNOW_IT_ALL_BROS_HOUSE_0_2 -ENTR_KNOW_IT_ALL_BROS_HOUSE_0_3 -ENTR_HYRULE_FIELD_0 -ENTR_HYRULE_FIELD_0_1 -ENTR_HYRULE_FIELD_0_2 -ENTR_HYRULE_FIELD_0_3 -ENTR_HYRULE_FIELD_0_4 -ENTR_HYRULE_FIELD_0_5 -ENTR_HYRULE_FIELD_0_6 -ENTR_HYRULE_FIELD_0_7 -ENTR_HYRULE_FIELD_0_8 -ENTR_HYRULE_FIELD_0_9 -ENTR_HYRULE_FIELD_0_10 -ENTR_HYRULE_FIELD_0_11 -ENTR_HYRULE_FIELD_0_12 -ENTR_HYRULE_FIELD_0_13 -ENTR_KAKARIKO_VILLAGE_0 -ENTR_KAKARIKO_VILLAGE_0_1 -ENTR_KAKARIKO_VILLAGE_0_2 -ENTR_KAKARIKO_VILLAGE_0_3 -ENTR_KAKARIKO_VILLAGE_0_4 -ENTR_KAKARIKO_VILLAGE_0_5 -ENTR_KAKARIKO_VILLAGE_0_6 -ENTR_KAKARIKO_VILLAGE_0_7 -ENTR_KAKARIKO_VILLAGE_0_8 -ENTR_GRAVEYARD_0 -ENTR_GRAVEYARD_0_1 -ENTR_GRAVEYARD_0_2 -ENTR_GRAVEYARD_0_3 -ENTR_GRAVEYARD_0_4 -ENTR_GRAVEYARD_0_5 -ENTR_ZORAS_RIVER_0 -ENTR_ZORAS_RIVER_0_1 -ENTR_ZORAS_RIVER_0_2 -ENTR_ZORAS_RIVER_0_3 -ENTR_KOKIRI_FOREST_0 -ENTR_KOKIRI_FOREST_0_1 -ENTR_KOKIRI_FOREST_0_2 -ENTR_KOKIRI_FOREST_0_3 -ENTR_KOKIRI_FOREST_0_4 -ENTR_KOKIRI_FOREST_0_5 -ENTR_KOKIRI_FOREST_0_6 -ENTR_KOKIRI_FOREST_0_7 -ENTR_KOKIRI_FOREST_0_8 -ENTR_KOKIRI_FOREST_0_9 -ENTR_KOKIRI_FOREST_0_10 -ENTR_KOKIRI_FOREST_0_11 -ENTR_KOKIRI_FOREST_0_12 -ENTR_KOKIRI_FOREST_0_13 -ENTR_SACRED_FOREST_MEADOW_0 -ENTR_SACRED_FOREST_MEADOW_0_1 -ENTR_SACRED_FOREST_MEADOW_0_2 -ENTR_SACRED_FOREST_MEADOW_0_3 -ENTR_SACRED_FOREST_MEADOW_0_4 -ENTR_SACRED_FOREST_MEADOW_0_5 -ENTR_LAKE_HYLIA_0 -ENTR_LAKE_HYLIA_0_1 -ENTR_LAKE_HYLIA_0_2 -ENTR_LAKE_HYLIA_0_3 -ENTR_LAKE_HYLIA_0_4 -ENTR_LAKE_HYLIA_0_5 -ENTR_ZORAS_DOMAIN_0 -ENTR_ZORAS_DOMAIN_0_1 -ENTR_ZORAS_DOMAIN_0_2 -ENTR_ZORAS_DOMAIN_0_3 -ENTR_ZORAS_DOMAIN_0_4 -ENTR_ZORAS_DOMAIN_0_5 -ENTR_ZORAS_FOUNTAIN_0 -ENTR_ZORAS_FOUNTAIN_0_1 -ENTR_ZORAS_FOUNTAIN_0_2 -ENTR_ZORAS_FOUNTAIN_0_3 -ENTR_ZORAS_FOUNTAIN_0_4 -ENTR_ZORAS_FOUNTAIN_0_5 -ENTR_ZORAS_FOUNTAIN_0_6 -ENTR_ZORAS_FOUNTAIN_0_7 -ENTR_ZORAS_FOUNTAIN_0_8 -ENTR_GERUDO_VALLEY_0 -ENTR_GERUDO_VALLEY_0_1 -ENTR_GERUDO_VALLEY_0_2 -ENTR_GERUDO_VALLEY_0_3 -ENTR_GERUDO_VALLEY_0_4 -ENTR_GERUDO_VALLEY_0_5 -ENTR_GERUDO_VALLEY_0_6 -ENTR_LOST_WOODS_0 -ENTR_LOST_WOODS_0_1 -ENTR_LOST_WOODS_0_2 -ENTR_LOST_WOODS_0_3 -ENTR_LOST_WOODS_0_4 -ENTR_DESERT_COLOSSUS_0 -ENTR_DESERT_COLOSSUS_0_1 -ENTR_DESERT_COLOSSUS_0_2 -ENTR_DESERT_COLOSSUS_0_3 -ENTR_DESERT_COLOSSUS_0_4 -ENTR_DESERT_COLOSSUS_0_5 -ENTR_GERUDOS_FORTRESS_0 -ENTR_GERUDOS_FORTRESS_0_1 -ENTR_GERUDOS_FORTRESS_0_2 -ENTR_GERUDOS_FORTRESS_0_3 -ENTR_GERUDOS_FORTRESS_0_4 -ENTR_GERUDOS_FORTRESS_0_5 -ENTR_GERUDOS_FORTRESS_0_6 -ENTR_HAUNTED_WASTELAND_0 -ENTR_HAUNTED_WASTELAND_0_1 -ENTR_HAUNTED_WASTELAND_0_2 -ENTR_HAUNTED_WASTELAND_0_3 -ENTR_GANONS_TOWER_COLLAPSE_INTERIOR_1 -ENTR_GANONS_TOWER_COLLAPSE_INTERIOR_1_1 -ENTR_GANONS_TOWER_COLLAPSE_INTERIOR_1_2 -ENTR_GANONS_TOWER_COLLAPSE_INTERIOR_1_3 -ENTR_HYRULE_CASTLE_0 -ENTR_HYRULE_CASTLE_0_1 -ENTR_OUTSIDE_GANONS_CASTLE_0_2 -ENTR_OUTSIDE_GANONS_CASTLE_0_3 -ENTR_OUTSIDE_GANONS_CASTLE_0_4 -ENTR_DEATH_MOUNTAIN_TRAIL_0 -ENTR_DEATH_MOUNTAIN_TRAIL_0_1 -ENTR_DEATH_MOUNTAIN_TRAIL_0_2 -ENTR_DEATH_MOUNTAIN_TRAIL_0_3 -ENTR_DEATH_MOUNTAIN_TRAIL_0_4 -ENTR_DEATH_MOUNTAIN_TRAIL_0_5 -ENTR_DEATH_MOUNTAIN_TRAIL_0_6 -ENTR_DEATH_MOUNTAIN_TRAIL_0_7 -ENTR_DEATH_MOUNTAIN_TRAIL_0_8 -ENTR_DEATH_MOUNTAIN_TRAIL_0_9 -ENTR_DEATH_MOUNTAIN_CRATER_0 -ENTR_DEATH_MOUNTAIN_CRATER_0_1 -ENTR_DEATH_MOUNTAIN_CRATER_0_2 -ENTR_DEATH_MOUNTAIN_CRATER_0_3 -ENTR_DEATH_MOUNTAIN_CRATER_0_4 -ENTR_DEATH_MOUNTAIN_CRATER_0_5 -ENTR_GORON_CITY_0 -ENTR_GORON_CITY_0_1 -ENTR_GORON_CITY_0_2 -ENTR_GORON_CITY_0_3 -ENTR_GORON_CITY_0_4 -ENTR_GORON_CITY_0_5 -ENTR_ZORAS_DOMAIN_3 -ENTR_ZORAS_DOMAIN_3_1 -ENTR_ZORAS_DOMAIN_3_2 -ENTR_ZORAS_DOMAIN_3_3 -ENTR_LON_LON_RANCH_0 -ENTR_LON_LON_RANCH_0_1 -ENTR_LON_LON_RANCH_0_2 -ENTR_LON_LON_RANCH_0_3 -ENTR_LON_LON_RANCH_0_4 -ENTR_LON_LON_RANCH_0_5 -ENTR_LON_LON_RANCH_0_6 -ENTR_LON_LON_RANCH_0_7 -ENTR_LON_LON_RANCH_0_8 -ENTR_LON_LON_RANCH_0_9 -ENTR_LON_LON_RANCH_0_10 -ENTR_LON_LON_RANCH_0_11 -ENTR_LON_LON_RANCH_0_12 -ENTR_LON_LON_RANCH_0_13 -ENTR_FIRE_TEMPLE_0 -ENTR_FIRE_TEMPLE_0_1 -ENTR_FIRE_TEMPLE_0_2 -ENTR_FIRE_TEMPLE_0_3 -ENTR_FOREST_TEMPLE_0 -ENTR_FOREST_TEMPLE_0_1 -ENTR_FOREST_TEMPLE_0_2 -ENTR_FOREST_TEMPLE_0_3 -ENTR_SHOOTING_GALLERY_1 -ENTR_SHOOTING_GALLERY_1_1 -ENTR_SHOOTING_GALLERY_1_2 -ENTR_SHOOTING_GALLERY_1_3 -ENTR_TEMPLE_OF_TIME_EXTERIOR_DAY_0 -ENTR_TEMPLE_OF_TIME_EXTERIOR_NIGHT_0_1 -ENTR_TEMPLE_OF_TIME_EXTERIOR_RUINS_0_2 -ENTR_TEMPLE_OF_TIME_EXTERIOR_RUINS_0_3 -ENTR_FIRE_TEMPLE_1 -ENTR_FIRE_TEMPLE_1_1 -ENTR_FIRE_TEMPLE_1_2 -ENTR_FIRE_TEMPLE_1_3 -ENTR_GANONS_TOWER_COLLAPSE_INTERIOR_0 -ENTR_GANONS_TOWER_COLLAPSE_INTERIOR_0_1 -ENTR_GANONS_TOWER_COLLAPSE_INTERIOR_0_2 -ENTR_GANONS_TOWER_COLLAPSE_INTERIOR_0_3 -ENTR_HYRULE_FIELD_1 -ENTR_HYRULE_FIELD_1_1 -ENTR_HYRULE_FIELD_1_2 -ENTR_HYRULE_FIELD_1_3 -ENTR_HYRULE_FIELD_2 -ENTR_HYRULE_FIELD_2_1 -ENTR_HYRULE_FIELD_2_2 -ENTR_HYRULE_FIELD_2_3 -ENTR_HYRULE_FIELD_3 -ENTR_HYRULE_FIELD_3_1 -ENTR_HYRULE_FIELD_3_2 -ENTR_HYRULE_FIELD_3_3 -ENTR_HYRULE_FIELD_4 -ENTR_HYRULE_FIELD_4_1 -ENTR_HYRULE_FIELD_4_2 -ENTR_HYRULE_FIELD_4_3 -ENTR_HYRULE_FIELD_5 -ENTR_HYRULE_FIELD_5_1 -ENTR_HYRULE_FIELD_5_2 -ENTR_HYRULE_FIELD_5_3 -ENTR_KAKARIKO_VILLAGE_1 -ENTR_KAKARIKO_VILLAGE_1_1 -ENTR_KAKARIKO_VILLAGE_1_2 -ENTR_KAKARIKO_VILLAGE_1_3 -ENTR_KAKARIKO_VILLAGE_2 -ENTR_KAKARIKO_VILLAGE_2_1 -ENTR_KAKARIKO_VILLAGE_2_2 -ENTR_KAKARIKO_VILLAGE_2_3 -ENTR_ZORAS_RIVER_1 -ENTR_ZORAS_RIVER_1_1 -ENTR_ZORAS_RIVER_1_2 -ENTR_ZORAS_RIVER_1_3 -ENTR_ZORAS_RIVER_2 -ENTR_ZORAS_RIVER_2_1 -ENTR_ZORAS_RIVER_2_2 -ENTR_ZORAS_RIVER_2_3 -ENTR_ZORAS_DOMAIN_1 -ENTR_ZORAS_DOMAIN_1_1 -ENTR_ZORAS_DOMAIN_1_2 -ENTR_ZORAS_DOMAIN_1_3 -ENTR_GERUDO_VALLEY_1 -ENTR_GERUDO_VALLEY_1_1 -ENTR_GERUDO_VALLEY_1_2 -ENTR_GERUDO_VALLEY_1_3 -ENTR_LOST_WOODS_1 -ENTR_LOST_WOODS_1_1 -ENTR_LOST_WOODS_1_2 -ENTR_LOST_WOODS_1_3 -ENTR_LOST_WOODS_2 -ENTR_LOST_WOODS_2_1 -ENTR_LOST_WOODS_2_2 -ENTR_LOST_WOODS_2_3 -ENTR_LOST_WOODS_3 -ENTR_LOST_WOODS_3_1 -ENTR_LOST_WOODS_3_2 -ENTR_LOST_WOODS_3_3 -ENTR_GANONS_TOWER_COLLAPSE_INTERIOR_2 -ENTR_GANONS_TOWER_COLLAPSE_INTERIOR_2_1 -ENTR_GANONS_TOWER_COLLAPSE_INTERIOR_2_2 -ENTR_GANONS_TOWER_COLLAPSE_INTERIOR_2_3 -ENTR_DEATH_MOUNTAIN_TRAIL_1 -ENTR_DEATH_MOUNTAIN_TRAIL_1_1 -ENTR_DEATH_MOUNTAIN_TRAIL_1_2 -ENTR_DEATH_MOUNTAIN_TRAIL_1_3 -ENTR_DEATH_MOUNTAIN_TRAIL_2 -ENTR_DEATH_MOUNTAIN_TRAIL_2_1 -ENTR_DEATH_MOUNTAIN_TRAIL_2_2 -ENTR_DEATH_MOUNTAIN_TRAIL_2_3 -ENTR_GORON_CITY_1 -ENTR_GORON_CITY_1_1 -ENTR_GORON_CITY_1_2 -ENTR_GORON_CITY_1_3 -ENTR_LAKESIDE_LABORATORY_1 -ENTR_LAKESIDE_LABORATORY_1_1 -ENTR_LAKESIDE_LABORATORY_1_2 -ENTR_LAKESIDE_LABORATORY_1_3 -ENTR_GANONS_TOWER_COLLAPSE_EXTERIOR_5 -ENTR_GANONS_TOWER_COLLAPSE_EXTERIOR_5_1 -ENTR_GANONS_TOWER_COLLAPSE_EXTERIOR_5_2 -ENTR_GANONS_TOWER_COLLAPSE_EXTERIOR_5_3 -ENTR_MARKET_DAY_8 -ENTR_MARKET_NIGHT_8_1 -ENTR_MARKET_RUINS_8_2 -ENTR_MARKET_RUINS_8_3 -ENTR_MARKET_DAY_9 -ENTR_MARKET_NIGHT_9_1 -ENTR_MARKET_RUINS_9_2 -ENTR_MARKET_RUINS_9_3 -ENTR_MARKET_DAY_10 -ENTR_MARKET_NIGHT_10_1 -ENTR_MARKET_RUINS_10_2 -ENTR_MARKET_RUINS_10_3 -ENTR_ZORAS_RIVER_3 -ENTR_ZORAS_RIVER_3_1 -ENTR_ZORAS_RIVER_3_2 -ENTR_ZORAS_RIVER_3_3 -ENTR_ZORAS_RIVER_4 -ENTR_ZORAS_RIVER_4_1 -ENTR_ZORAS_RIVER_4_2 -ENTR_ZORAS_RIVER_4_3 -ENTR_DESERT_COLOSSUS_1 -ENTR_DESERT_COLOSSUS_1_1 -ENTR_DESERT_COLOSSUS_1_2 -ENTR_DESERT_COLOSSUS_1_3 -ENTR_DESERT_COLOSSUS_2 -ENTR_DESERT_COLOSSUS_2_1 -ENTR_DESERT_COLOSSUS_2_2 -ENTR_DESERT_COLOSSUS_2_3 -ENTR_DESERT_COLOSSUS_3 -ENTR_DESERT_COLOSSUS_3_1 -ENTR_DESERT_COLOSSUS_3_2 -ENTR_DESERT_COLOSSUS_3_3 -ENTR_DESERT_COLOSSUS_4 -ENTR_DESERT_COLOSSUS_4_1 -ENTR_DESERT_COLOSSUS_4_2 -ENTR_DESERT_COLOSSUS_4_3 -ENTR_DESERT_COLOSSUS_5 -ENTR_DESERT_COLOSSUS_5_1 -ENTR_DESERT_COLOSSUS_5_2 -ENTR_DESERT_COLOSSUS_5_3 -ENTR_DESERT_COLOSSUS_6 -ENTR_DESERT_COLOSSUS_6_1 -ENTR_DESERT_COLOSSUS_6_2 -ENTR_DESERT_COLOSSUS_6_3 -ENTR_HYRULE_FIELD_6 -ENTR_HYRULE_FIELD_6_1 -ENTR_HYRULE_FIELD_6_2 -ENTR_HYRULE_FIELD_6_3 -ENTR_HYRULE_FIELD_7 -ENTR_HYRULE_FIELD_7_1 -ENTR_HYRULE_FIELD_7_2 -ENTR_HYRULE_FIELD_7_3 -ENTR_KAKARIKO_VILLAGE_3 -ENTR_KAKARIKO_VILLAGE_3_1 -ENTR_KAKARIKO_VILLAGE_3_2 -ENTR_KAKARIKO_VILLAGE_3_3 -ENTR_GRAVEYARD_1 -ENTR_GRAVEYARD_1_1 -ENTR_GRAVEYARD_1_2 -ENTR_GRAVEYARD_1_3 -ENTR_KOKIRI_FOREST_1 -ENTR_KOKIRI_FOREST_1_1 -ENTR_KOKIRI_FOREST_1_2 -ENTR_KOKIRI_FOREST_1_3 -ENTR_KOKIRI_FOREST_2 -ENTR_KOKIRI_FOREST_2_1 -ENTR_KOKIRI_FOREST_2_2 -ENTR_KOKIRI_FOREST_2_3 -ENTR_KOKIRI_FOREST_3 -ENTR_KOKIRI_FOREST_3_1 -ENTR_KOKIRI_FOREST_3_2 -ENTR_KOKIRI_FOREST_3_3 -ENTR_SACRED_FOREST_MEADOW_1 -ENTR_SACRED_FOREST_MEADOW_1_1 -ENTR_SACRED_FOREST_MEADOW_1_2 -ENTR_SACRED_FOREST_MEADOW_1_3 -ENTR_LAKE_HYLIA_1 -ENTR_LAKE_HYLIA_1_1 -ENTR_LAKE_HYLIA_1_2 -ENTR_LAKE_HYLIA_1_3 -ENTR_LAKE_HYLIA_2 -ENTR_LAKE_HYLIA_2_1 -ENTR_LAKE_HYLIA_2_2 -ENTR_LAKE_HYLIA_2_3 -ENTR_ZORAS_FOUNTAIN_1 -ENTR_ZORAS_FOUNTAIN_1_1 -ENTR_ZORAS_FOUNTAIN_1_2 -ENTR_ZORAS_FOUNTAIN_1_3 -ENTR_ZORAS_FOUNTAIN_2 -ENTR_ZORAS_FOUNTAIN_2_1 -ENTR_ZORAS_FOUNTAIN_2_2 -ENTR_ZORAS_FOUNTAIN_2_3 -ENTR_GERUDO_VALLEY_2 -ENTR_GERUDO_VALLEY_2_1 -ENTR_GERUDO_VALLEY_2_2 -ENTR_GERUDO_VALLEY_2_3 -ENTR_GERUDO_VALLEY_3 -ENTR_GERUDO_VALLEY_3_1 -ENTR_GERUDO_VALLEY_3_2 -ENTR_GERUDO_VALLEY_3_3 -ENTR_GERUDOS_FORTRESS_1 -ENTR_GERUDOS_FORTRESS_1_1 -ENTR_GERUDOS_FORTRESS_1_2 -ENTR_GERUDOS_FORTRESS_1_3 -ENTR_GERUDOS_FORTRESS_2 -ENTR_GERUDOS_FORTRESS_2_1 -ENTR_GERUDOS_FORTRESS_2_2 -ENTR_GERUDOS_FORTRESS_2_3 -ENTR_GERUDOS_FORTRESS_3 -ENTR_GERUDOS_FORTRESS_3_1 -ENTR_GERUDOS_FORTRESS_3_2 -ENTR_GERUDOS_FORTRESS_3_3 -ENTR_HYRULE_CASTLE_1 -ENTR_HYRULE_CASTLE_1_1 -ENTR_OUTSIDE_GANONS_CASTLE_1_2 -ENTR_OUTSIDE_GANONS_CASTLE_1_3 -ENTR_HYRULE_CASTLE_1_4 -ENTR_DEATH_MOUNTAIN_TRAIL_3 -ENTR_DEATH_MOUNTAIN_TRAIL_3_1 -ENTR_DEATH_MOUNTAIN_TRAIL_3_2 -ENTR_DEATH_MOUNTAIN_TRAIL_3_3 -ENTR_DEATH_MOUNTAIN_CRATER_1 -ENTR_DEATH_MOUNTAIN_CRATER_1_1 -ENTR_DEATH_MOUNTAIN_CRATER_1_2 -ENTR_DEATH_MOUNTAIN_CRATER_1_3 -ENTR_DEATH_MOUNTAIN_CRATER_2 -ENTR_DEATH_MOUNTAIN_CRATER_2_1 -ENTR_DEATH_MOUNTAIN_CRATER_2_2 -ENTR_DEATH_MOUNTAIN_CRATER_2_3 -ENTR_FOREST_TEMPLE_1 -ENTR_FOREST_TEMPLE_1_1 -ENTR_FOREST_TEMPLE_1_2 -ENTR_FOREST_TEMPLE_1_3 -ENTR_DEKU_TREE_1 -ENTR_DEKU_TREE_1_1 -ENTR_DEKU_TREE_1_2 -ENTR_DEKU_TREE_1_3 -ENTR_GANONS_TOWER_COLLAPSE_INTERIOR_3 -ENTR_GANONS_TOWER_COLLAPSE_INTERIOR_3_1 -ENTR_GANONS_TOWER_COLLAPSE_INTERIOR_3_2 -ENTR_GANONS_TOWER_COLLAPSE_INTERIOR_3_3 -ENTR_MARKET_DAY_1 -ENTR_MARKET_NIGHT_1_1 -ENTR_MARKET_RUINS_1_2 -ENTR_MARKET_RUINS_1_3 -ENTR_MARKET_DAY_2 -ENTR_MARKET_NIGHT_2_1 -ENTR_MARKET_RUINS_2_2 -ENTR_MARKET_RUINS_2_3 -ENTR_MARKET_DAY_3 -ENTR_MARKET_NIGHT_3_1 -ENTR_MARKET_RUINS_3_2 -ENTR_MARKET_RUINS_3_3 -ENTR_KOKIRI_FOREST_4 -ENTR_KOKIRI_FOREST_4_1 -ENTR_KOKIRI_FOREST_4_2 -ENTR_KOKIRI_FOREST_4_3 -ENTR_KOKIRI_FOREST_5 -ENTR_KOKIRI_FOREST_5_1 -ENTR_KOKIRI_FOREST_5_2 -ENTR_KOKIRI_FOREST_5_3 -ENTR_MARKET_ENTRANCE_DAY_2 -ENTR_MARKET_ENTRANCE_NIGHT_2_1 -ENTR_MARKET_ENTRANCE_RUINS_2_2 -ENTR_MARKET_ENTRANCE_RUINS_2_3 -ENTR_LINKS_HOUSE_1 -ENTR_LINKS_HOUSE_1_1 -ENTR_LINKS_HOUSE_1_2 -ENTR_LINKS_HOUSE_1_3 -ENTR_MARKET_ENTRANCE_DAY_1 -ENTR_MARKET_ENTRANCE_NIGHT_1_1 -ENTR_MARKET_ENTRANCE_RUINS_1_2 -ENTR_MARKET_ENTRANCE_RUINS_1_3 -ENTR_HYRULE_FIELD_8 -ENTR_HYRULE_FIELD_8_1 -ENTR_HYRULE_FIELD_8_2 -ENTR_HYRULE_FIELD_8_3 -ENTR_HYRULE_FIELD_9 -ENTR_HYRULE_FIELD_9_1 -ENTR_HYRULE_FIELD_9_2 -ENTR_HYRULE_FIELD_9_3 -ENTR_HYRULE_FIELD_10 -ENTR_HYRULE_FIELD_10_1 -ENTR_HYRULE_FIELD_10_2 -ENTR_HYRULE_FIELD_10_3 -ENTR_KOKIRI_FOREST_6 -ENTR_KOKIRI_FOREST_6_1 -ENTR_KOKIRI_FOREST_6_2 -ENTR_KOKIRI_FOREST_6_3 -ENTR_HYRULE_FIELD_11 -ENTR_HYRULE_FIELD_11_1 -ENTR_HYRULE_FIELD_11_2 -ENTR_HYRULE_FIELD_11_3 -ENTR_HYRULE_FIELD_12 -ENTR_HYRULE_FIELD_12_1 -ENTR_HYRULE_FIELD_12_2 -ENTR_HYRULE_FIELD_12_3 -ENTR_HYRULE_FIELD_13 -ENTR_HYRULE_FIELD_13_1 -ENTR_HYRULE_FIELD_13_2 -ENTR_HYRULE_FIELD_13_3 -ENTR_CASTLE_COURTYARD_GUARDS_DAY_1 -ENTR_CASTLE_COURTYARD_GUARDS_NIGHT_1_1 -ENTR_CASTLE_COURTYARD_GUARDS_DAY_1_2 -ENTR_CASTLE_COURTYARD_GUARDS_NIGHT_1_3 -ENTR_BACK_ALLEY_DAY_1 -ENTR_BACK_ALLEY_NIGHT_1_1 -ENTR_BACK_ALLEY_DAY_1_2 -ENTR_BACK_ALLEY_NIGHT_1_3 -ENTR_MARKET_DAY_4 -ENTR_MARKET_NIGHT_4_1 -ENTR_MARKET_RUINS_4_2 -ENTR_MARKET_RUINS_4_3 -ENTR_MARKET_DAY_5 -ENTR_MARKET_NIGHT_5_1 -ENTR_MARKET_RUINS_5_2 -ENTR_MARKET_RUINS_5_3 -ENTR_KAKARIKO_VILLAGE_4 -ENTR_KAKARIKO_VILLAGE_4_1 -ENTR_KAKARIKO_VILLAGE_4_2 -ENTR_KAKARIKO_VILLAGE_4_3 -ENTR_GERUDOS_FORTRESS_4 -ENTR_GERUDOS_FORTRESS_4_1 -ENTR_GERUDOS_FORTRESS_4_2 -ENTR_GERUDOS_FORTRESS_4_3 -ENTR_LON_LON_RANCH_1 -ENTR_LON_LON_RANCH_1_1 -ENTR_LON_LON_RANCH_1_2 -ENTR_LON_LON_RANCH_1_3 -ENTR_SHADOW_TEMPLE_1 -ENTR_SHADOW_TEMPLE_1_1 -ENTR_SHADOW_TEMPLE_1_2 -ENTR_SHADOW_TEMPLE_1_3 -ENTR_SHADOW_TEMPLE_2 -ENTR_SHADOW_TEMPLE_2_1 -ENTR_SHADOW_TEMPLE_2_2 -ENTR_SHADOW_TEMPLE_2_3 -ENTR_GERUDOS_FORTRESS_5 -ENTR_GERUDOS_FORTRESS_5_1 -ENTR_GERUDOS_FORTRESS_5_2 -ENTR_GERUDOS_FORTRESS_5_3 -ENTR_GERUDOS_FORTRESS_6 -ENTR_GERUDOS_FORTRESS_6_1 -ENTR_GERUDOS_FORTRESS_6_2 -ENTR_GERUDOS_FORTRESS_6_3 -ENTR_GERUDOS_FORTRESS_7 -ENTR_GERUDOS_FORTRESS_7_1 -ENTR_GERUDOS_FORTRESS_7_2 -ENTR_GERUDOS_FORTRESS_7_3 -ENTR_GERUDOS_FORTRESS_8 -ENTR_GERUDOS_FORTRESS_8_1 -ENTR_GERUDOS_FORTRESS_8_2 -ENTR_GERUDOS_FORTRESS_8_3 -ENTR_TEMPLE_OF_TIME_2 -ENTR_TEMPLE_OF_TIME_2_1 -ENTR_TEMPLE_OF_TIME_2_2 -ENTR_TEMPLE_OF_TIME_2_3 -ENTR_CHAMBER_OF_THE_SAGES_1 -ENTR_CHAMBER_OF_THE_SAGES_1_1 -ENTR_CHAMBER_OF_THE_SAGES_1_2 -ENTR_CHAMBER_OF_THE_SAGES_1_3 -ENTR_GERUDOS_FORTRESS_9 -ENTR_GERUDOS_FORTRESS_9_1 -ENTR_GERUDOS_FORTRESS_9_2 -ENTR_GERUDOS_FORTRESS_9_3 -ENTR_GERUDOS_FORTRESS_10 -ENTR_GERUDOS_FORTRESS_10_1 -ENTR_GERUDOS_FORTRESS_10_2 -ENTR_GERUDOS_FORTRESS_10_3 -ENTR_GERUDOS_FORTRESS_11 -ENTR_GERUDOS_FORTRESS_11_1 -ENTR_GERUDOS_FORTRESS_11_2 -ENTR_GERUDOS_FORTRESS_11_3 -ENTR_GERUDOS_FORTRESS_12 -ENTR_GERUDOS_FORTRESS_12_1 -ENTR_GERUDOS_FORTRESS_12_2 -ENTR_GERUDOS_FORTRESS_12_3 -ENTR_LON_LON_RANCH_2 -ENTR_LON_LON_RANCH_2_1 -ENTR_LON_LON_RANCH_2_2 -ENTR_LON_LON_RANCH_2_3 -ENTR_LON_LON_RANCH_3 -ENTR_LON_LON_RANCH_3_1 -ENTR_LON_LON_RANCH_3_2 -ENTR_LON_LON_RANCH_3_3 -ENTR_TEST_SHOOTING_GALLERY_0 -ENTR_TEST_SHOOTING_GALLERY_0_1 -ENTR_TEST_SHOOTING_GALLERY_0_2 -ENTR_TEST_SHOOTING_GALLERY_0_3 -ENTR_TEST_SACRED_FOREST_MEADOW_0_4 -ENTR_TEST_CUTSCENE_MAP_0_5 -ENTR_TEST_SHOOTING_GALLERY_0_6 -ENTR_TEST_SHOOTING_GALLERY_0_7 -ENTR_TEST_SHOOTING_GALLERY_0_8 -ENTR_TEST_SHOOTING_GALLERY_0_9 -ENTR_TEST_SHOOTING_GALLERY_0_10 -ENTR_SPIRIT_TEMPLE_1 -ENTR_SPIRIT_TEMPLE_1_1 -ENTR_SPIRIT_TEMPLE_1_2 -ENTR_SPIRIT_TEMPLE_1_3 -ENTR_STABLE_0 -ENTR_STABLE_0_1 -ENTR_STABLE_0_2 -ENTR_STABLE_0_3 -ENTR_KAKARIKO_CENTER_GUEST_HOUSE_0 -ENTR_KAKARIKO_CENTER_GUEST_HOUSE_0_1 -ENTR_KAKARIKO_CENTER_GUEST_HOUSE_0_2 -ENTR_KAKARIKO_CENTER_GUEST_HOUSE_0_3 -ENTR_JABU_JABU_BOSS_0 -ENTR_JABU_JABU_BOSS_0_1 -ENTR_JABU_JABU_BOSS_0_2 -ENTR_JABU_JABU_BOSS_0_3 -ENTR_FIRE_TEMPLE_BOSS_0 -ENTR_FIRE_TEMPLE_BOSS_0_1 -ENTR_FIRE_TEMPLE_BOSS_0_2 -ENTR_FIRE_TEMPLE_BOSS_0_3 -ENTR_LAKE_HYLIA_6 -ENTR_LAKE_HYLIA_6_1 -ENTR_LAKE_HYLIA_6_2 -ENTR_LAKE_HYLIA_6_3 -ENTR_GRAVEKEEPERS_HUT_0 -ENTR_GRAVEKEEPERS_HUT_0_1 -ENTR_GRAVEKEEPERS_HUT_0_2 -ENTR_GRAVEKEEPERS_HUT_0_3 -ENTR_HYRULE_FIELD_14 -ENTR_HYRULE_FIELD_14_1 -ENTR_HYRULE_FIELD_14_2 -ENTR_HYRULE_FIELD_14_3 -ENTR_GREAT_FAIRYS_FOUNTAIN_MAGIC_0 -ENTR_GREAT_FAIRYS_FOUNTAIN_MAGIC_0_1 -ENTR_GREAT_FAIRYS_FOUNTAIN_MAGIC_0_2 -ENTR_GREAT_FAIRYS_FOUNTAIN_MAGIC_0_3 -ENTR_GREAT_FAIRYS_FOUNTAIN_MAGIC_0_4 -ENTR_GREAT_FAIRYS_FOUNTAIN_MAGIC_0_5 -ENTR_GREAT_FAIRYS_FOUNTAIN_MAGIC_0_6 -ENTR_REDEAD_GRAVE_0 -ENTR_REDEAD_GRAVE_0_1 -ENTR_REDEAD_GRAVE_0_2 -ENTR_REDEAD_GRAVE_0_3 -ENTR_TEMPLE_OF_TIME_3 -ENTR_TEMPLE_OF_TIME_3_1 -ENTR_TEMPLE_OF_TIME_3_2 -ENTR_TEMPLE_OF_TIME_3_3 -ENTR_TEMPLE_OF_TIME_4 -ENTR_TEMPLE_OF_TIME_4_1 -ENTR_TEMPLE_OF_TIME_4_2 -ENTR_TEMPLE_OF_TIME_4_3 -ENTR_ZORAS_DOMAIN_4 -ENTR_ZORAS_DOMAIN_4_1 -ENTR_ZORAS_DOMAIN_4_2 -ENTR_ZORAS_DOMAIN_4_3 -ENTR_GANONS_TOWER_COLLAPSE_EXTERIOR_2 -ENTR_GANONS_TOWER_COLLAPSE_EXTERIOR_2_1 -ENTR_GANONS_TOWER_COLLAPSE_EXTERIOR_2_2 -ENTR_GANONS_TOWER_COLLAPSE_EXTERIOR_2_3 -ENTR_GANONS_TOWER_COLLAPSE_EXTERIOR_3 -ENTR_GANONS_TOWER_COLLAPSE_EXTERIOR_3_1 -ENTR_GANONS_TOWER_COLLAPSE_EXTERIOR_3_2 -ENTR_GANONS_TOWER_COLLAPSE_EXTERIOR_3_3 -ENTR_GANONS_TOWER_COLLAPSE_EXTERIOR_4 -ENTR_GANONS_TOWER_COLLAPSE_EXTERIOR_4_1 -ENTR_GANONS_TOWER_COLLAPSE_EXTERIOR_4_2 -ENTR_GANONS_TOWER_COLLAPSE_EXTERIOR_4_3 -ENTR_KOKIRI_FOREST_7 -ENTR_KOKIRI_FOREST_7_1 -ENTR_KOKIRI_FOREST_7_2 -ENTR_KOKIRI_FOREST_7_3 -ENTR_KOKIRI_FOREST_8 -ENTR_KOKIRI_FOREST_8_1 -ENTR_KOKIRI_FOREST_8_2 -ENTR_KOKIRI_FOREST_8_3 -ENTR_HYRULE_CASTLE_2 -ENTR_HYRULE_CASTLE_2_1 -ENTR_OUTSIDE_GANONS_CASTLE_2_2 -ENTR_OUTSIDE_GANONS_CASTLE_2_3 -ENTR_HYRULE_CASTLE_2_4 -ENTR_KAKARIKO_VILLAGE_5 -ENTR_KAKARIKO_VILLAGE_5_1 -ENTR_KAKARIKO_VILLAGE_5_2 -ENTR_KAKARIKO_VILLAGE_5_3 -ENTR_KAKARIKO_VILLAGE_6 -ENTR_KAKARIKO_VILLAGE_6_1 -ENTR_KAKARIKO_VILLAGE_6_2 -ENTR_KAKARIKO_VILLAGE_6_3 -ENTR_KAKARIKO_VILLAGE_7 -ENTR_KAKARIKO_VILLAGE_7_1 -ENTR_KAKARIKO_VILLAGE_7_2 -ENTR_KAKARIKO_VILLAGE_7_3 -ENTR_KAKARIKO_VILLAGE_8 -ENTR_KAKARIKO_VILLAGE_8_1 -ENTR_KAKARIKO_VILLAGE_8_2 -ENTR_KAKARIKO_VILLAGE_8_3 -ENTR_GRAVEYARD_2 -ENTR_GRAVEYARD_2_1 -ENTR_GRAVEYARD_2_2 -ENTR_GRAVEYARD_2_3 -ENTR_GRAVEYARD_3 -ENTR_GRAVEYARD_3_1 -ENTR_GRAVEYARD_3_2 -ENTR_GRAVEYARD_3_3 -ENTR_GRAVEYARD_4 -ENTR_GRAVEYARD_4_1 -ENTR_GRAVEYARD_4_2 -ENTR_GRAVEYARD_4_3 -ENTR_GRAVEYARD_5 -ENTR_GRAVEYARD_5_1 -ENTR_GRAVEYARD_5_2 -ENTR_GRAVEYARD_5_3 -ENTR_HAUNTED_WASTELAND_1 -ENTR_HAUNTED_WASTELAND_1_1 -ENTR_HAUNTED_WASTELAND_1_2 -ENTR_HAUNTED_WASTELAND_1_3 -ENTR_HAUNTED_WASTELAND_2 -ENTR_HAUNTED_WASTELAND_2_1 -ENTR_HAUNTED_WASTELAND_2_2 -ENTR_HAUNTED_WASTELAND_2_3 -ENTR_FAIRYS_FOUNTAIN_0 -ENTR_FAIRYS_FOUNTAIN_0_1 -ENTR_FAIRYS_FOUNTAIN_0_2 -ENTR_FAIRYS_FOUNTAIN_0_3 -ENTR_GREAT_FAIRYS_FOUNTAIN_SPELLS_0 -ENTR_GREAT_FAIRYS_FOUNTAIN_SPELLS_0_1 -ENTR_GREAT_FAIRYS_FOUNTAIN_SPELLS_0_2 -ENTR_GREAT_FAIRYS_FOUNTAIN_SPELLS_0_3 -ENTR_GREAT_FAIRYS_FOUNTAIN_SPELLS_0_4 -ENTR_GREAT_FAIRYS_FOUNTAIN_SPELLS_0_5 -ENTR_GREAT_FAIRYS_FOUNTAIN_SPELLS_0_6 -ENTR_LON_LON_RANCH_4 -ENTR_LON_LON_RANCH_4_1 -ENTR_LON_LON_RANCH_4_2 -ENTR_LON_LON_RANCH_4_3 -ENTR_GORON_SHOP_0 -ENTR_GORON_SHOP_0_1 -ENTR_GORON_SHOP_0_2 -ENTR_GORON_SHOP_0_3 -ENTR_ZORA_SHOP_0 -ENTR_ZORA_SHOP_0_1 -ENTR_ZORA_SHOP_0_2 -ENTR_ZORA_SHOP_0_3 -ENTR_POTION_SHOP_KAKARIKO_0 -ENTR_POTION_SHOP_KAKARIKO_0_1 -ENTR_POTION_SHOP_KAKARIKO_0_2 -ENTR_POTION_SHOP_KAKARIKO_0_3 -ENTR_POTION_SHOP_MARKET_0 -ENTR_POTION_SHOP_MARKET_0_1 -ENTR_POTION_SHOP_MARKET_0_2 -ENTR_POTION_SHOP_MARKET_0_3 -ENTR_BACK_ALLEY_DAY_4 -ENTR_BACK_ALLEY_NIGHT_4_1 -ENTR_BACK_ALLEY_DAY_4_2 -ENTR_BACK_ALLEY_NIGHT_4_3 -ENTR_BOMBCHU_SHOP_0 -ENTR_BOMBCHU_SHOP_0_1 -ENTR_BOMBCHU_SHOP_0_2 -ENTR_BOMBCHU_SHOP_0_3 -ENTR_ZORAS_FOUNTAIN_5 -ENTR_ZORAS_FOUNTAIN_5_1 -ENTR_ZORAS_FOUNTAIN_5_2 -ENTR_ZORAS_FOUNTAIN_5_3 -ENTR_DOG_LADY_HOUSE_0 -ENTR_DOG_LADY_HOUSE_0_1 -ENTR_DOG_LADY_HOUSE_0_2 -ENTR_DOG_LADY_HOUSE_0_3 -ENTR_IMPAS_HOUSE_0 -ENTR_IMPAS_HOUSE_0_1 -ENTR_IMPAS_HOUSE_0_2 -ENTR_IMPAS_HOUSE_0_3 -ENTR_CARPENTERS_TENT_0 -ENTR_CARPENTERS_TENT_0_1 -ENTR_CARPENTERS_TENT_0_2 -ENTR_CARPENTERS_TENT_0_3 -ENTR_GERUDOS_FORTRESS_13 -ENTR_GERUDOS_FORTRESS_13_1 -ENTR_GERUDOS_FORTRESS_13_2 -ENTR_GERUDOS_FORTRESS_13_3 -ENTR_GERUDOS_FORTRESS_14 -ENTR_GERUDOS_FORTRESS_14_1 -ENTR_GERUDOS_FORTRESS_14_2 -ENTR_GERUDOS_FORTRESS_14_3 -ENTR_GERUDOS_FORTRESS_15 -ENTR_GERUDOS_FORTRESS_15_1 -ENTR_GERUDOS_FORTRESS_15_2 -ENTR_GERUDOS_FORTRESS_15_3 -ENTR_GERUDOS_FORTRESS_16 -ENTR_GERUDOS_FORTRESS_16_1 -ENTR_GERUDOS_FORTRESS_16_2 -ENTR_GERUDOS_FORTRESS_16_3 -ENTR_GERUDOS_FORTRESS_17 -ENTR_GERUDOS_FORTRESS_17_1 -ENTR_GERUDOS_FORTRESS_17_2 -ENTR_GERUDOS_FORTRESS_17_3 -ENTR_MARKET_DAY_6 -ENTR_MARKET_NIGHT_6_1 -ENTR_MARKET_RUINS_6_2 -ENTR_MARKET_RUINS_6_3 -ENTR_MARKET_DAY_7 -ENTR_MARKET_NIGHT_7_1 -ENTR_MARKET_RUINS_7_2 -ENTR_MARKET_RUINS_7_3 -ENTR_BACK_ALLEY_DAY_2 -ENTR_BACK_ALLEY_NIGHT_2_1 -ENTR_BACK_ALLEY_DAY_2_2 -ENTR_BACK_ALLEY_NIGHT_2_3 -ENTR_ZORAS_DOMAIN_2 -ENTR_ZORAS_DOMAIN_2_1 -ENTR_ZORAS_DOMAIN_2_2 -ENTR_ZORAS_DOMAIN_2_3 -ENTR_LAKE_HYLIA_3 -ENTR_LAKE_HYLIA_3_1 -ENTR_LAKE_HYLIA_3_2 -ENTR_LAKE_HYLIA_3_3 -ENTR_LAKE_HYLIA_4 -ENTR_LAKE_HYLIA_4_1 -ENTR_LAKE_HYLIA_4_2 -ENTR_LAKE_HYLIA_4_3 -ENTR_GERUDO_VALLEY_4 -ENTR_GERUDO_VALLEY_4_1 -ENTR_GERUDO_VALLEY_4_2 -ENTR_GERUDO_VALLEY_4_3 -ENTR_ZORAS_FOUNTAIN_3 -ENTR_ZORAS_FOUNTAIN_3_1 -ENTR_ZORAS_FOUNTAIN_3_2 -ENTR_ZORAS_FOUNTAIN_3_3 -ENTR_ZORAS_FOUNTAIN_4 -ENTR_ZORAS_FOUNTAIN_4_1 -ENTR_ZORAS_FOUNTAIN_4_2 -ENTR_ZORAS_FOUNTAIN_4_3 -ENTR_GANONS_TOWER_COLLAPSE_INTERIOR_4 -ENTR_GANONS_TOWER_COLLAPSE_INTERIOR_4_1 -ENTR_GANONS_TOWER_COLLAPSE_INTERIOR_4_2 -ENTR_GANONS_TOWER_COLLAPSE_INTERIOR_4_3 -ENTR_GANONS_TOWER_COLLAPSE_INTERIOR_5 -ENTR_GANONS_TOWER_COLLAPSE_INTERIOR_5_1 -ENTR_GANONS_TOWER_COLLAPSE_INTERIOR_5_2 -ENTR_GANONS_TOWER_COLLAPSE_INTERIOR_5_3 -ENTR_GANONS_TOWER_COLLAPSE_INTERIOR_6 -ENTR_GANONS_TOWER_COLLAPSE_INTERIOR_6_1 -ENTR_GANONS_TOWER_COLLAPSE_INTERIOR_6_2 -ENTR_GANONS_TOWER_COLLAPSE_INTERIOR_6_3 -ENTR_POTION_SHOP_KAKARIKO_1 -ENTR_POTION_SHOP_KAKARIKO_1_1 -ENTR_POTION_SHOP_KAKARIKO_1_2 -ENTR_POTION_SHOP_KAKARIKO_1_3 -ENTR_POTION_SHOP_KAKARIKO_2 -ENTR_POTION_SHOP_KAKARIKO_2_1 -ENTR_POTION_SHOP_KAKARIKO_2_2 -ENTR_POTION_SHOP_KAKARIKO_2_3 -ENTR_SPIRIT_TEMPLE_2 -ENTR_SPIRIT_TEMPLE_2_1 -ENTR_SPIRIT_TEMPLE_2_2 -ENTR_SPIRIT_TEMPLE_2_3 -ENTR_SPIRIT_TEMPLE_3 -ENTR_SPIRIT_TEMPLE_3_1 -ENTR_SPIRIT_TEMPLE_3_2 -ENTR_SPIRIT_TEMPLE_3_3 -ENTR_SPIRIT_TEMPLE_4 -ENTR_SPIRIT_TEMPLE_4_1 -ENTR_SPIRIT_TEMPLE_4_2 -ENTR_SPIRIT_TEMPLE_4_3 -ENTR_GORON_CITY_2 -ENTR_GORON_CITY_2_1 -ENTR_GORON_CITY_2_2 -ENTR_GORON_CITY_2_3 -ENTR_CASTLE_COURTYARD_ZELDA_0 -ENTR_CASTLE_COURTYARD_ZELDA_0_1 -ENTR_CASTLE_COURTYARD_ZELDA_0_2 -ENTR_CASTLE_COURTYARD_ZELDA_0_3 -ENTR_CASTLE_COURTYARD_ZELDA_0_4 -ENTR_CASTLE_COURTYARD_ZELDA_0_5 -ENTR_CASTLE_COURTYARD_ZELDA_0_6 -ENTR_JABU_JABU_1 -ENTR_JABU_JABU_1_1 -ENTR_JABU_JABU_1_2 -ENTR_JABU_JABU_1_3 -ENTR_DODONGOS_CAVERN_BOSS_0 -ENTR_DODONGOS_CAVERN_BOSS_0_1 -ENTR_DODONGOS_CAVERN_BOSS_0_2 -ENTR_DODONGOS_CAVERN_BOSS_0_3 -ENTR_DEKU_TREE_BOSS_0 -ENTR_DEKU_TREE_BOSS_0_1 -ENTR_DEKU_TREE_BOSS_0_2 -ENTR_DEKU_TREE_BOSS_0_3 -ENTR_SHADOW_TEMPLE_BOSS_0 -ENTR_SHADOW_TEMPLE_BOSS_0_1 -ENTR_SHADOW_TEMPLE_BOSS_0_2 -ENTR_SHADOW_TEMPLE_BOSS_0_3 -ENTR_WATER_TEMPLE_BOSS_0 -ENTR_WATER_TEMPLE_BOSS_0_1 -ENTR_WATER_TEMPLE_BOSS_0_2 -ENTR_WATER_TEMPLE_BOSS_0_3 -ENTR_GANONS_TOWER_0 -ENTR_GANONS_TOWER_0_1 -ENTR_GANONS_TOWER_0_2 -ENTR_GANONS_TOWER_0_3 -ENTR_GANONDORF_BOSS_0 -ENTR_GANONDORF_BOSS_0_1 -ENTR_GANONDORF_BOSS_0_2 -ENTR_GANONDORF_BOSS_0_3 -ENTR_WATER_TEMPLE_1 -ENTR_WATER_TEMPLE_1_1 -ENTR_WATER_TEMPLE_1_2 -ENTR_WATER_TEMPLE_1_3 -ENTR_GANONS_TOWER_1 -ENTR_GANONS_TOWER_1_1 -ENTR_GANONS_TOWER_1_2 -ENTR_GANONS_TOWER_1_3 -ENTR_GANONS_TOWER_2 -ENTR_GANONS_TOWER_2_1 -ENTR_GANONS_TOWER_2_2 -ENTR_GANONS_TOWER_2_3 -ENTR_LON_LON_RANCH_5 -ENTR_LON_LON_RANCH_5_1 -ENTR_LON_LON_RANCH_5_2 -ENTR_LON_LON_RANCH_5_3 -ENTR_MIDOS_HOUSE_0 -ENTR_MIDOS_HOUSE_0_1 -ENTR_MIDOS_HOUSE_0_2 -ENTR_MIDOS_HOUSE_0_3 -ENTR_SARIAS_HOUSE_0 -ENTR_SARIAS_HOUSE_0_1 -ENTR_SARIAS_HOUSE_0_2 -ENTR_SARIAS_HOUSE_0_3 -ENTR_BACK_ALLEY_HOUSE_0 -ENTR_BACK_ALLEY_HOUSE_0_1 -ENTR_BACK_ALLEY_HOUSE_0_2 -ENTR_BACK_ALLEY_HOUSE_0_3 -ENTR_GANONS_TOWER_COLLAPSE_EXTERIOR_0 -ENTR_GANONS_TOWER_COLLAPSE_EXTERIOR_0_1 -ENTR_GANONS_TOWER_COLLAPSE_EXTERIOR_0_2 -ENTR_GANONS_TOWER_COLLAPSE_EXTERIOR_0_3 -ENTR_KOKIRI_FOREST_9 -ENTR_KOKIRI_FOREST_9_1 -ENTR_KOKIRI_FOREST_9_2 -ENTR_KOKIRI_FOREST_9_3 -ENTR_KOKIRI_FOREST_10 -ENTR_KOKIRI_FOREST_10_1 -ENTR_KOKIRI_FOREST_10_2 -ENTR_KOKIRI_FOREST_10_3 -ENTR_KAKARIKO_VILLAGE_9 -ENTR_KAKARIKO_VILLAGE_9_1 -ENTR_KAKARIKO_VILLAGE_9_2 -ENTR_KAKARIKO_VILLAGE_9_3 -ENTR_WINDMILL_AND_DAMPES_GRAVE_0 -ENTR_WINDMILL_AND_DAMPES_GRAVE_0_1 -ENTR_WINDMILL_AND_DAMPES_GRAVE_0_2 -ENTR_WINDMILL_AND_DAMPES_GRAVE_0_3 -ENTR_WINDMILL_AND_DAMPES_GRAVE_1 -ENTR_WINDMILL_AND_DAMPES_GRAVE_1_1 -ENTR_WINDMILL_AND_DAMPES_GRAVE_1_2 -ENTR_WINDMILL_AND_DAMPES_GRAVE_1_3 -ENTR_KOKIRI_FOREST_11 -ENTR_KOKIRI_FOREST_11_1 -ENTR_KOKIRI_FOREST_11_2 -ENTR_KOKIRI_FOREST_11_3 -ENTR_DEATH_MOUNTAIN_TRAIL_4 -ENTR_DEATH_MOUNTAIN_TRAIL_4_1 -ENTR_DEATH_MOUNTAIN_TRAIL_4_2 -ENTR_DEATH_MOUNTAIN_TRAIL_4_3 -ENTR_FISHING_POND_0 -ENTR_FISHING_POND_0_1 -ENTR_FISHING_POND_0_2 -ENTR_FISHING_POND_0_3 -ENTR_KAKARIKO_VILLAGE_10 -ENTR_KAKARIKO_VILLAGE_10_1 -ENTR_KAKARIKO_VILLAGE_10_2 -ENTR_KAKARIKO_VILLAGE_10_3 -ENTR_INSIDE_GANONS_CASTLE_0 -ENTR_INSIDE_GANONS_CASTLE_0_1 -ENTR_INSIDE_GANONS_CASTLE_0_2 -ENTR_INSIDE_GANONS_CASTLE_0_3 -ENTR_INSIDE_GANONS_CASTLE_0_4 -ENTR_INSIDE_GANONS_CASTLE_0_5 -ENTR_INSIDE_GANONS_CASTLE_0_6 -ENTR_INSIDE_GANONS_CASTLE_0_7 -ENTR_INSIDE_GANONS_CASTLE_0_8 -ENTR_INSIDE_GANONS_CASTLE_0_9 -ENTR_INSIDE_GANONS_CASTLE_0_10 -ENTR_TEMPLE_OF_TIME_EXTERIOR_DAY_1 -ENTR_TEMPLE_OF_TIME_EXTERIOR_NIGHT_1_1 -ENTR_TEMPLE_OF_TIME_EXTERIOR_RUINS_1_2 -ENTR_TEMPLE_OF_TIME_EXTERIOR_RUINS_1_3 -ENTR_HYRULE_FIELD_15 -ENTR_HYRULE_FIELD_15_1 -ENTR_HYRULE_FIELD_15_2 -ENTR_HYRULE_FIELD_15_3 -ENTR_DEATH_MOUNTAIN_TRAIL_5 -ENTR_DEATH_MOUNTAIN_TRAIL_5_1 -ENTR_DEATH_MOUNTAIN_TRAIL_5_2 -ENTR_DEATH_MOUNTAIN_TRAIL_5_3 -ENTR_HYRULE_CASTLE_4 -ENTR_HYRULE_CASTLE_4_1 -ENTR_OUTSIDE_GANONS_CASTLE_4_2 -ENTR_OUTSIDE_GANONS_CASTLE_4_3 -ENTR_DEATH_MOUNTAIN_CRATER_3 -ENTR_DEATH_MOUNTAIN_CRATER_3_1 -ENTR_DEATH_MOUNTAIN_CRATER_3_2 -ENTR_DEATH_MOUNTAIN_CRATER_3_3 -ENTR_THIEVES_HIDEOUT_0 -ENTR_THIEVES_HIDEOUT_0_1 -ENTR_THIEVES_HIDEOUT_0_2 -ENTR_THIEVES_HIDEOUT_0_3 -ENTR_THIEVES_HIDEOUT_1 -ENTR_THIEVES_HIDEOUT_1_1 -ENTR_THIEVES_HIDEOUT_1_2 -ENTR_THIEVES_HIDEOUT_1_3 -ENTR_THIEVES_HIDEOUT_2 -ENTR_THIEVES_HIDEOUT_2_1 -ENTR_THIEVES_HIDEOUT_2_2 -ENTR_THIEVES_HIDEOUT_2_3 -ENTR_THIEVES_HIDEOUT_3 -ENTR_THIEVES_HIDEOUT_3_1 -ENTR_THIEVES_HIDEOUT_3_2 -ENTR_THIEVES_HIDEOUT_3_3 -ENTR_THIEVES_HIDEOUT_4 -ENTR_THIEVES_HIDEOUT_4_1 -ENTR_THIEVES_HIDEOUT_4_2 -ENTR_THIEVES_HIDEOUT_4_3 -ENTR_THIEVES_HIDEOUT_5 -ENTR_THIEVES_HIDEOUT_5_1 -ENTR_THIEVES_HIDEOUT_5_2 -ENTR_THIEVES_HIDEOUT_5_3 -ENTR_THIEVES_HIDEOUT_6 -ENTR_THIEVES_HIDEOUT_6_1 -ENTR_THIEVES_HIDEOUT_6_2 -ENTR_THIEVES_HIDEOUT_6_3 -ENTR_THIEVES_HIDEOUT_7 -ENTR_THIEVES_HIDEOUT_7_1 -ENTR_THIEVES_HIDEOUT_7_2 -ENTR_THIEVES_HIDEOUT_7_3 -ENTR_THIEVES_HIDEOUT_8 -ENTR_THIEVES_HIDEOUT_8_1 -ENTR_THIEVES_HIDEOUT_8_2 -ENTR_THIEVES_HIDEOUT_8_3 -ENTR_THIEVES_HIDEOUT_9 -ENTR_THIEVES_HIDEOUT_9_1 -ENTR_THIEVES_HIDEOUT_9_2 -ENTR_THIEVES_HIDEOUT_9_3 -ENTR_THIEVES_HIDEOUT_10 -ENTR_THIEVES_HIDEOUT_10_1 -ENTR_THIEVES_HIDEOUT_10_2 -ENTR_THIEVES_HIDEOUT_10_3 -ENTR_THIEVES_HIDEOUT_11 -ENTR_THIEVES_HIDEOUT_11_1 -ENTR_THIEVES_HIDEOUT_11_2 -ENTR_THIEVES_HIDEOUT_11_3 -ENTR_GANONS_TOWER_COLLAPSE_INTERIOR_7 -ENTR_GANONS_TOWER_COLLAPSE_INTERIOR_7_1 -ENTR_GANONS_TOWER_COLLAPSE_INTERIOR_7_2 -ENTR_GANONS_TOWER_COLLAPSE_INTERIOR_7_3 -ENTR_GANONS_TOWER_COLLAPSE_EXTERIOR_1 -ENTR_GANONS_TOWER_COLLAPSE_EXTERIOR_1_1 -ENTR_GANONS_TOWER_COLLAPSE_EXTERIOR_1_2 -ENTR_GANONS_TOWER_COLLAPSE_EXTERIOR_1_3 -ENTR_GREAT_FAIRYS_FOUNTAIN_MAGIC_1 -ENTR_GREAT_FAIRYS_FOUNTAIN_MAGIC_1_1 -ENTR_GREAT_FAIRYS_FOUNTAIN_MAGIC_1_2 -ENTR_GREAT_FAIRYS_FOUNTAIN_MAGIC_1_3 -ENTR_GREAT_FAIRYS_FOUNTAIN_MAGIC_2 -ENTR_GREAT_FAIRYS_FOUNTAIN_MAGIC_2_1 -ENTR_GREAT_FAIRYS_FOUNTAIN_MAGIC_2_2 -ENTR_GREAT_FAIRYS_FOUNTAIN_MAGIC_2_3 -ENTR_LOST_WOODS_4 -ENTR_LOST_WOODS_4_1 -ENTR_LOST_WOODS_4_2 -ENTR_LOST_WOODS_4_3 -ENTR_LON_LON_RANCH_6 -ENTR_LON_LON_RANCH_6_1 -ENTR_LON_LON_RANCH_6_2 -ENTR_LON_LON_RANCH_6_3 -ENTR_LON_LON_RANCH_7 -ENTR_LON_LON_RANCH_7_1 -ENTR_LON_LON_RANCH_7_2 -ENTR_LON_LON_RANCH_7_3 -ENTR_LOST_WOODS_5 -ENTR_LOST_WOODS_5_1 -ENTR_LOST_WOODS_5_2 -ENTR_LOST_WOODS_5_3 -ENTR_LOST_WOODS_6 -ENTR_LOST_WOODS_6_1 -ENTR_LOST_WOODS_6_2 -ENTR_LOST_WOODS_6_3 -ENTR_LOST_WOODS_7 -ENTR_LOST_WOODS_7_1 -ENTR_LOST_WOODS_7_2 -ENTR_LOST_WOODS_7_3 -ENTR_LOST_WOODS_8 -ENTR_LOST_WOODS_8_1 -ENTR_LOST_WOODS_8_2 -ENTR_LOST_WOODS_8_3 -ENTR_GORON_CITY_3 -ENTR_GORON_CITY_3_1 -ENTR_GORON_CITY_3_2 -ENTR_GORON_CITY_3_3 -ENTR_LAKE_HYLIA_5 -ENTR_LAKE_HYLIA_5_1 -ENTR_LAKE_HYLIA_5_2 -ENTR_LAKE_HYLIA_5_3 -ENTR_SHADOW_TEMPLE_3 -ENTR_SHADOW_TEMPLE_3_1 -ENTR_SHADOW_TEMPLE_3_2 -ENTR_SHADOW_TEMPLE_3_3 -ENTR_KAKARIKO_VILLAGE_11 -ENTR_KAKARIKO_VILLAGE_11_1 -ENTR_KAKARIKO_VILLAGE_11_2 -ENTR_KAKARIKO_VILLAGE_11_3 -ENTR_GREAT_FAIRYS_FOUNTAIN_MAGIC_3 -ENTR_GREAT_FAIRYS_FOUNTAIN_MAGIC_3_1 -ENTR_GREAT_FAIRYS_FOUNTAIN_MAGIC_3_2 -ENTR_GREAT_FAIRYS_FOUNTAIN_MAGIC_3_3 -ENTR_DEATH_MOUNTAIN_CRATER_4 -ENTR_DEATH_MOUNTAIN_CRATER_4_1 -ENTR_DEATH_MOUNTAIN_CRATER_4_2 -ENTR_DEATH_MOUNTAIN_CRATER_4_3 -ENTR_HYRULE_CASTLE_3 -ENTR_HYRULE_CASTLE_3_1 -ENTR_OUTSIDE_GANONS_CASTLE_3_2 -ENTR_OUTSIDE_GANONS_CASTLE_3_3 -ENTR_HYRULE_CASTLE_3_4 -ENTR_KAKARIKO_VILLAGE_12 -ENTR_KAKARIKO_VILLAGE_12_1 -ENTR_KAKARIKO_VILLAGE_12_2 -ENTR_KAKARIKO_VILLAGE_12_3 -ENTR_WINDMILL_AND_DAMPES_GRAVE_2 -ENTR_WINDMILL_AND_DAMPES_GRAVE_2_1 -ENTR_WINDMILL_AND_DAMPES_GRAVE_2_2 -ENTR_WINDMILL_AND_DAMPES_GRAVE_2_3 -ENTR_BOMBCHU_BOWLING_ALLEY_0 -ENTR_BOMBCHU_BOWLING_ALLEY_0_1 -ENTR_BOMBCHU_BOWLING_ALLEY_0_2 -ENTR_BOMBCHU_BOWLING_ALLEY_0_3 -ENTR_GRAVEYARD_6 -ENTR_GRAVEYARD_6_1 -ENTR_GRAVEYARD_6_2 -ENTR_GRAVEYARD_6_3 -ENTR_HYRULE_FIELD_16 -ENTR_HYRULE_FIELD_16_1 -ENTR_HYRULE_FIELD_16_2 -ENTR_HYRULE_FIELD_16_3 -ENTR_KAKARIKO_VILLAGE_13 -ENTR_KAKARIKO_VILLAGE_13_1 -ENTR_KAKARIKO_VILLAGE_13_2 -ENTR_KAKARIKO_VILLAGE_13_3 -ENTR_GANON_BOSS_0 -ENTR_GANON_BOSS_0_1 -ENTR_GANON_BOSS_0_2 -ENTR_GANON_BOSS_0_3 -ENTR_GANON_BOSS_0_4 -ENTR_GANONS_TOWER_COLLAPSE_EXTERIOR_6 -ENTR_GANONS_TOWER_COLLAPSE_EXTERIOR_6_1 -ENTR_GANONS_TOWER_COLLAPSE_EXTERIOR_6_2 -ENTR_GANONS_TOWER_COLLAPSE_EXTERIOR_6_3 -ENTR_BESITU_0 -ENTR_BESITU_0_1 -ENTR_BESITU_0_2 -ENTR_BESITU_0_3 -ENTR_GANONS_TOWER_COLLAPSE_EXTERIOR_7 -ENTR_GANONS_TOWER_COLLAPSE_EXTERIOR_7_1 -ENTR_GANONS_TOWER_COLLAPSE_EXTERIOR_7_2 -ENTR_GANONS_TOWER_COLLAPSE_EXTERIOR_7_3 -ENTR_BOMBCHU_SHOP_1 -ENTR_BOMBCHU_SHOP_1_1 -ENTR_BOMBCHU_SHOP_1_2 -ENTR_BOMBCHU_SHOP_1_3 -ENTR_BAZAAR_1 -ENTR_BAZAAR_1_1 -ENTR_BAZAAR_1_2 -ENTR_BAZAAR_1_3 -ENTR_HAPPY_MASK_SHOP_0 -ENTR_HAPPY_MASK_SHOP_0_1 -ENTR_HAPPY_MASK_SHOP_0_2 -ENTR_HAPPY_MASK_SHOP_0_3 -ENTR_INSIDE_GANONS_CASTLE_1 -ENTR_INSIDE_GANONS_CASTLE_1_1 -ENTR_INSIDE_GANONS_CASTLE_1_2 -ENTR_INSIDE_GANONS_CASTLE_1_3 -ENTR_INSIDE_GANONS_CASTLE_2 -ENTR_INSIDE_GANONS_CASTLE_2_1 -ENTR_INSIDE_GANONS_CASTLE_2_2 -ENTR_INSIDE_GANONS_CASTLE_2_3 -ENTR_INSIDE_GANONS_CASTLE_3 -ENTR_INSIDE_GANONS_CASTLE_3_1 -ENTR_INSIDE_GANONS_CASTLE_3_2 -ENTR_INSIDE_GANONS_CASTLE_3_3 -ENTR_INSIDE_GANONS_CASTLE_4 -ENTR_INSIDE_GANONS_CASTLE_4_1 -ENTR_INSIDE_GANONS_CASTLE_4_2 -ENTR_INSIDE_GANONS_CASTLE_4_3 -ENTR_INSIDE_GANONS_CASTLE_5 -ENTR_INSIDE_GANONS_CASTLE_5_1 -ENTR_INSIDE_GANONS_CASTLE_5_2 -ENTR_INSIDE_GANONS_CASTLE_5_3 -ENTR_INSIDE_GANONS_CASTLE_6 -ENTR_INSIDE_GANONS_CASTLE_6_1 -ENTR_INSIDE_GANONS_CASTLE_6_2 -ENTR_INSIDE_GANONS_CASTLE_6_3 -ENTR_INSIDE_GANONS_CASTLE_7 -ENTR_INSIDE_GANONS_CASTLE_7_1 -ENTR_INSIDE_GANONS_CASTLE_7_2 -ENTR_INSIDE_GANONS_CASTLE_7_3 -ENTR_HOUSE_OF_SKULLTULA_0 -ENTR_HOUSE_OF_SKULLTULA_0_1 -ENTR_HOUSE_OF_SKULLTULA_0_2 -ENTR_HOUSE_OF_SKULLTULA_0_3 -ENTR_KAKARIKO_VILLAGE_14 -ENTR_KAKARIKO_VILLAGE_14_1 -ENTR_KAKARIKO_VILLAGE_14_2 -ENTR_KAKARIKO_VILLAGE_14_3 -ENTR_LON_LON_RANCH_8 -ENTR_LON_LON_RANCH_8_1 -ENTR_LON_LON_RANCH_8_2 -ENTR_LON_LON_RANCH_8_3 -ENTR_LON_LON_RANCH_9 -ENTR_LON_LON_RANCH_9_1 -ENTR_LON_LON_RANCH_9_2 -ENTR_LON_LON_RANCH_9_3 -ENTR_LAKE_HYLIA_7 -ENTR_LAKE_HYLIA_7_1 -ENTR_LAKE_HYLIA_7_2 -ENTR_LAKE_HYLIA_7_3 -ENTR_DEATH_MOUNTAIN_CRATER_5 -ENTR_DEATH_MOUNTAIN_CRATER_5_1 -ENTR_DEATH_MOUNTAIN_CRATER_5_2 -ENTR_DEATH_MOUNTAIN_CRATER_5_3 -ENTR_GRAVEYARD_7 -ENTR_GRAVEYARD_7_1 -ENTR_GRAVEYARD_7_2 -ENTR_GRAVEYARD_7_3 -ENTR_INSIDE_GANONS_CASTLE_COLLAPSE_0 -ENTR_INSIDE_GANONS_CASTLE_COLLAPSE_0_1 -ENTR_INSIDE_GANONS_CASTLE_COLLAPSE_0_2 -ENTR_INSIDE_GANONS_CASTLE_COLLAPSE_0_3 -ENTR_THIEVES_HIDEOUT_12 -ENTR_THIEVES_HIDEOUT_12_1 -ENTR_THIEVES_HIDEOUT_12_2 -ENTR_THIEVES_HIDEOUT_12_3 -ENTR_ROYAL_FAMILYS_TOMB_1 -ENTR_ROYAL_FAMILYS_TOMB_1_1 -ENTR_ROYAL_FAMILYS_TOMB_1_2 -ENTR_ROYAL_FAMILYS_TOMB_1_3 -ENTR_GREAT_FAIRYS_FOUNTAIN_SPELLS_1 -ENTR_GREAT_FAIRYS_FOUNTAIN_SPELLS_1_1 -ENTR_GREAT_FAIRYS_FOUNTAIN_SPELLS_1_2 -ENTR_GREAT_FAIRYS_FOUNTAIN_SPELLS_1_3 -ENTR_DESERT_COLOSSUS_7 -ENTR_DESERT_COLOSSUS_7_1 -ENTR_DESERT_COLOSSUS_7_2 -ENTR_DESERT_COLOSSUS_7_3 -ENTR_GRAVEYARD_8 -ENTR_GRAVEYARD_8_1 -ENTR_GRAVEYARD_8_2 -ENTR_GRAVEYARD_8_3 -ENTR_FOREST_TEMPLE_2 -ENTR_FOREST_TEMPLE_2_1 -ENTR_FOREST_TEMPLE_2_2 -ENTR_FOREST_TEMPLE_2_3 -ENTR_GREAT_FAIRYS_FOUNTAIN_SPELLS_2 -ENTR_GREAT_FAIRYS_FOUNTAIN_SPELLS_2_1 -ENTR_GREAT_FAIRYS_FOUNTAIN_SPELLS_2_2 -ENTR_GREAT_FAIRYS_FOUNTAIN_SPELLS_2_3 -ENTR_TEMPLE_OF_TIME_5 -ENTR_TEMPLE_OF_TIME_5_1 -ENTR_TEMPLE_OF_TIME_5_2 -ENTR_TEMPLE_OF_TIME_5_3 -ENTR_TEMPLE_OF_TIME_6 -ENTR_TEMPLE_OF_TIME_6_1 -ENTR_TEMPLE_OF_TIME_6_2 -ENTR_TEMPLE_OF_TIME_6_3 -ENTR_HYRULE_FIELD_17 -ENTR_HYRULE_FIELD_17_1 -ENTR_HYRULE_FIELD_17_2 -ENTR_HYRULE_FIELD_17_3 -ENTR_GROTTOS_1 -ENTR_GROTTOS_1_1 -ENTR_GROTTOS_1_2 -ENTR_GROTTOS_1_3 -ENTR_GROTTOS_2 -ENTR_GROTTOS_2_1 -ENTR_GROTTOS_2_2 -ENTR_GROTTOS_2_3 -ENTR_GROTTOS_3 -ENTR_GROTTOS_3_1 -ENTR_GROTTOS_3_2 -ENTR_GROTTOS_3_3 -ENTR_GROTTOS_4 -ENTR_GROTTOS_4_1 -ENTR_GROTTOS_4_2 -ENTR_GROTTOS_4_3 -ENTR_GROTTOS_5 -ENTR_GROTTOS_5_1 -ENTR_GROTTOS_5_2 -ENTR_GROTTOS_5_3 -ENTR_GROTTOS_6 -ENTR_GROTTOS_6_1 -ENTR_GROTTOS_6_2 -ENTR_GROTTOS_6_3 -ENTR_GROTTOS_7 -ENTR_GROTTOS_7_1 -ENTR_GROTTOS_7_2 -ENTR_GROTTOS_7_3 -ENTR_GROTTOS_8 -ENTR_GROTTOS_8_1 -ENTR_GROTTOS_8_2 -ENTR_GROTTOS_8_3 -ENTR_GROTTOS_9 -ENTR_GROTTOS_9_1 -ENTR_GROTTOS_9_2 -ENTR_GROTTOS_9_3 -ENTR_GROTTOS_10 -ENTR_GROTTOS_10_1 -ENTR_GROTTOS_10_2 -ENTR_GROTTOS_10_3 -ENTR_GROTTOS_11 -ENTR_GROTTOS_11_1 -ENTR_GROTTOS_11_2 -ENTR_GROTTOS_11_3 -ENTR_GROTTOS_12 -ENTR_GROTTOS_12_1 -ENTR_GROTTOS_12_2 -ENTR_GROTTOS_12_3 -ENTR_IMPAS_HOUSE_1 -ENTR_IMPAS_HOUSE_1_1 -ENTR_IMPAS_HOUSE_1_2 -ENTR_IMPAS_HOUSE_1_3 -ENTR_BOTTOM_OF_THE_WELL_1 -ENTR_BOTTOM_OF_THE_WELL_1_1 -ENTR_BOTTOM_OF_THE_WELL_1_2 -ENTR_BOTTOM_OF_THE_WELL_1_3 -ENTR_LON_LON_BUILDINGS_1 -ENTR_LON_LON_BUILDINGS_1_1 -ENTR_LON_LON_BUILDINGS_1_2 -ENTR_LON_LON_BUILDINGS_1_3 -ENTR_LON_LON_RANCH_10 -ENTR_LON_LON_RANCH_10_1 -ENTR_LON_LON_RANCH_10_2 -ENTR_LON_LON_RANCH_10_3 -ENTR_ICE_CAVERN_1 -ENTR_ICE_CAVERN_1_1 -ENTR_ICE_CAVERN_1_2 -ENTR_ICE_CAVERN_1_3 -ENTR_KAKARIKO_VILLAGE_15 -ENTR_KAKARIKO_VILLAGE_15_1 -ENTR_KAKARIKO_VILLAGE_15_2 -ENTR_KAKARIKO_VILLAGE_15_3 -ENTR_LOST_WOODS_9 -ENTR_LOST_WOODS_9_1 -ENTR_LOST_WOODS_9_2 -ENTR_LOST_WOODS_9_3 -ENTR_LON_LON_BUILDINGS_2 -ENTR_LON_LON_BUILDINGS_2_1 -ENTR_LON_LON_BUILDINGS_2_2 -ENTR_LON_LON_BUILDINGS_2_3 -ENTR_KOKIRI_FOREST_12 -ENTR_KOKIRI_FOREST_12_1 -ENTR_KOKIRI_FOREST_12_2 -ENTR_KOKIRI_FOREST_12_3 -ENTR_SPIRIT_TEMPLE_BOSS_2 -ENTR_SPIRIT_TEMPLE_BOSS_2_1 -ENTR_SPIRIT_TEMPLE_BOSS_2_2 -ENTR_SPIRIT_TEMPLE_BOSS_2_3 -ENTR_CASTLE_COURTYARD_ZELDA_1 -ENTR_CASTLE_COURTYARD_ZELDA_1_1 -ENTR_CASTLE_COURTYARD_ZELDA_1_2 -ENTR_CASTLE_COURTYARD_ZELDA_1_3 -ENTR_TEMPLE_OF_TIME_7 -ENTR_TEMPLE_OF_TIME_7_1 -ENTR_TEMPLE_OF_TIME_7_2 -ENTR_TEMPLE_OF_TIME_7_3 -ENTR_GERUDOS_FORTRESS_18 -ENTR_GERUDOS_FORTRESS_18_1 -ENTR_GERUDOS_FORTRESS_18_2 -ENTR_GERUDOS_FORTRESS_18_3 -ENTR_GROTTOS_13 -ENTR_GROTTOS_13_1 -ENTR_GROTTOS_13_2 -ENTR_GROTTOS_13_3 -ENTR_SACRED_FOREST_MEADOW_2 -ENTR_SACRED_FOREST_MEADOW_2_1 -ENTR_SACRED_FOREST_MEADOW_2_2 -ENTR_SACRED_FOREST_MEADOW_2_3 -ENTR_LAKE_HYLIA_8 -ENTR_LAKE_HYLIA_8_1 -ENTR_LAKE_HYLIA_8_2 -ENTR_LAKE_HYLIA_8_3 -ENTR_SACRED_FOREST_MEADOW_3 -ENTR_SACRED_FOREST_MEADOW_3_1 -ENTR_SACRED_FOREST_MEADOW_3_2 -ENTR_SACRED_FOREST_MEADOW_3_3 -ENTR_LAKE_HYLIA_9 -ENTR_LAKE_HYLIA_9_1 -ENTR_LAKE_HYLIA_9_2 -ENTR_LAKE_HYLIA_9_3 -ENTR_DESERT_COLOSSUS_8 -ENTR_DESERT_COLOSSUS_8_1 -ENTR_DESERT_COLOSSUS_8_2 -ENTR_DESERT_COLOSSUS_8_3 diff --git a/tools/ZAPDConfigs/EnumData.xml b/tools/ZAPDConfigs/EnumData.xml deleted file mode 100644 index bbe0b2d07a..0000000000 --- a/tools/ZAPDConfigs/EnumData.xml +++ /dev/null @@ -1,599 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tools/ZAPDConfigs/ObjectList.txt b/tools/ZAPDConfigs/ObjectList.txt deleted file mode 100644 index 1ecc3441bb..0000000000 --- a/tools/ZAPDConfigs/ObjectList.txt +++ /dev/null @@ -1,402 +0,0 @@ -OBJECT_INVALID -OBJECT_GAMEPLAY_KEEP -OBJECT_GAMEPLAY_FIELD_KEEP -OBJECT_GAMEPLAY_DANGEON_KEEP -OBJECT_UNSET_4 -OBJECT_UNSET_5 -OBJECT_HUMAN -OBJECT_OKUTA -OBJECT_CROW -OBJECT_POH -OBJECT_DY_OBJ -OBJECT_WALLMASTER -OBJECT_DODONGO -OBJECT_FIREFLY -OBJECT_BOX -OBJECT_FIRE -OBJECT_UNSET_10 -OBJECT_UNSET_11 -OBJECT_BUBBLE -OBJECT_NIW -OBJECT_LINK_BOY -OBJECT_LINK_CHILD -OBJECT_TITE -OBJECT_REEBA -OBJECT_PEEHAT -OBJECT_KINGDODONGO -OBJECT_HORSE -OBJECT_ZF -OBJECT_GOMA -OBJECT_ZL1 -OBJECT_GOL -OBJECT_DODOJR -OBJECT_TORCH2 -OBJECT_BL -OBJECT_TP -OBJECT_OA1 -OBJECT_ST -OBJECT_BW -OBJECT_EI -OBJECT_HORSE_NORMAL -OBJECT_OB1 -OBJECT_O_ANIME -OBJECT_SPOT04_OBJECTS -OBJECT_DDAN_OBJECTS -OBJECT_HIDAN_OBJECTS -OBJECT_HORSE_GANON -OBJECT_OA2 -OBJECT_SPOT00_OBJECTS -OBJECT_MB -OBJECT_BOMBF -OBJECT_SK2 -OBJECT_OE1 -OBJECT_OE_ANIME -OBJECT_OE2 -OBJECT_YDAN_OBJECTS -OBJECT_GND -OBJECT_AM -OBJECT_DEKUBABA -OBJECT_UNSET_3A -OBJECT_OA3 -OBJECT_OA4 -OBJECT_OA5 -OBJECT_OA6 -OBJECT_OA7 -OBJECT_JJ -OBJECT_OA8 -OBJECT_OA9 -OBJECT_OB2 -OBJECT_OB3 -OBJECT_OB4 -OBJECT_HORSE_ZELDA -OBJECT_OPENING_DEMO1 -OBJECT_WARP1 -OBJECT_B_HEART -OBJECT_DEKUNUTS -OBJECT_OE3 -OBJECT_OE4 -OBJECT_MENKURI_OBJECTS -OBJECT_OE5 -OBJECT_OE6 -OBJECT_OE7 -OBJECT_OE8 -OBJECT_OE9 -OBJECT_OE10 -OBJECT_OE11 -OBJECT_OE12 -OBJECT_VALI -OBJECT_OA10 -OBJECT_OA11 -OBJECT_MIZU_OBJECTS -OBJECT_FHG -OBJECT_OSSAN -OBJECT_MORI_HINERI1 -OBJECT_BB -OBJECT_TOKI_OBJECTS -OBJECT_YUKABYUN -OBJECT_ZL2 -OBJECT_MJIN -OBJECT_MJIN_FLASH -OBJECT_MJIN_DARK -OBJECT_MJIN_FLAME -OBJECT_MJIN_ICE -OBJECT_MJIN_SOUL -OBJECT_MJIN_WIND -OBJECT_MJIN_OKA -OBJECT_HAKA_OBJECTS -OBJECT_SPOT06_OBJECTS -OBJECT_ICE_OBJECTS -OBJECT_RELAY_OBJECTS -OBJECT_PO_FIELD -OBJECT_PO_COMPOSER -OBJECT_MORI_HINERI1A -OBJECT_MORI_HINERI2 -OBJECT_MORI_HINERI2A -OBJECT_MORI_OBJECTS -OBJECT_MORI_TEX -OBJECT_SPOT08_OBJ -OBJECT_WARP2 -OBJECT_HATA -OBJECT_BIRD -OBJECT_UNSET_78 -OBJECT_UNSET_79 -OBJECT_UNSET_7A -OBJECT_UNSET_7B -OBJECT_WOOD02 -OBJECT_UNSET_7D -OBJECT_UNSET_7E -OBJECT_UNSET_7F -OBJECT_UNSET_80 -OBJECT_LIGHTBOX -OBJECT_PU_BOX -OBJECT_UNSET_83 -OBJECT_UNSET_84 -OBJECT_TRAP -OBJECT_VASE -OBJECT_IM -OBJECT_TA -OBJECT_TK -OBJECT_XC -OBJECT_VM -OBJECT_BV -OBJECT_HAKACH_OBJECTS -OBJECT_EFC_CRYSTAL_LIGHT -OBJECT_EFC_FIRE_BALL -OBJECT_EFC_FLASH -OBJECT_EFC_LGT_SHOWER -OBJECT_EFC_STAR_FIELD -OBJECT_GOD_LGT -OBJECT_LIGHT_RING -OBJECT_TRIFORCE_SPOT -OBJECT_BDAN_OBJECTS -OBJECT_SD -OBJECT_RD -OBJECT_PO_SISTERS -OBJECT_HEAVY_OBJECT -OBJECT_GNDD -OBJECT_FD -OBJECT_DU -OBJECT_FW -OBJECT_MEDAL -OBJECT_HORSE_LINK_CHILD -OBJECT_SPOT02_OBJECTS -OBJECT_HAKA -OBJECT_RU1 -OBJECT_SYOKUDAI -OBJECT_FD2 -OBJECT_DH -OBJECT_RL -OBJECT_EFC_TW -OBJECT_DEMO_TRE_LGT -OBJECT_GI_KEY -OBJECT_MIR_RAY -OBJECT_BROB -OBJECT_GI_JEWEL -OBJECT_SPOT09_OBJ -OBJECT_SPOT18_OBJ -OBJECT_BDOOR -OBJECT_SPOT17_OBJ -OBJECT_SHOP_DUNGEN -OBJECT_NB -OBJECT_MO -OBJECT_SB -OBJECT_GI_MELODY -OBJECT_GI_HEART -OBJECT_GI_COMPASS -OBJECT_GI_BOSSKEY -OBJECT_GI_MEDAL -OBJECT_GI_NUTS -OBJECT_SA -OBJECT_GI_HEARTS -OBJECT_GI_ARROWCASE -OBJECT_GI_BOMBPOUCH -OBJECT_IN -OBJECT_TR -OBJECT_SPOT16_OBJ -OBJECT_OE1S -OBJECT_OE4S -OBJECT_OS_ANIME -OBJECT_GI_BOTTLE -OBJECT_GI_STICK -OBJECT_GI_MAP -OBJECT_OF1D_MAP -OBJECT_RU2 -OBJECT_GI_SHIELD_1 -OBJECT_DEKUJR -OBJECT_GI_MAGICPOT -OBJECT_GI_BOMB_1 -OBJECT_OF1S -OBJECT_MA2 -OBJECT_GI_PURSE -OBJECT_HNI -OBJECT_TW -OBJECT_RR -OBJECT_BXA -OBJECT_ANUBICE -OBJECT_GI_GERUDO -OBJECT_GI_ARROW -OBJECT_GI_BOMB_2 -OBJECT_GI_EGG -OBJECT_GI_SCALE -OBJECT_GI_SHIELD_2 -OBJECT_GI_HOOKSHOT -OBJECT_GI_OCARINA -OBJECT_GI_MILK -OBJECT_MA1 -OBJECT_GANON -OBJECT_SST -OBJECT_NY_UNUSED -OBJECT_UNSET_E4 -OBJECT_NY -OBJECT_FR -OBJECT_GI_PACHINKO -OBJECT_GI_BOOMERANG -OBJECT_GI_BOW -OBJECT_GI_GLASSES -OBJECT_GI_LIQUID -OBJECT_ANI -OBJECT_DEMO_6K -OBJECT_GI_SHIELD_3 -OBJECT_GI_LETTER -OBJECT_SPOT15_OBJ -OBJECT_JYA_OBJ -OBJECT_GI_CLOTHES -OBJECT_GI_BEAN -OBJECT_GI_FISH -OBJECT_GI_SAW -OBJECT_GI_HAMMER -OBJECT_GI_GRASS -OBJECT_GI_LONGSWORD -OBJECT_SPOT01_OBJECTS -OBJECT_MD_UNUSED -OBJECT_MD -OBJECT_KM1 -OBJECT_KW1 -OBJECT_ZO -OBJECT_KZ -OBJECT_UMAJUMP -OBJECT_MASTERKOKIRI -OBJECT_MASTERKOKIRIHEAD -OBJECT_MASTERGOLON -OBJECT_MASTERZOORA -OBJECT_AOB -OBJECT_IK -OBJECT_AHG -OBJECT_CNE -OBJECT_GI_NIWATORI -OBJECT_SKJ -OBJECT_GI_BOTTLE_LETTER -OBJECT_BJI -OBJECT_BBA -OBJECT_GI_OCARINA_0 -OBJECT_DS -OBJECT_ANE -OBJECT_BOJ -OBJECT_SPOT03_OBJECT -OBJECT_SPOT07_OBJECT -OBJECT_FZ -OBJECT_BOB -OBJECT_GE1 -OBJECT_YABUSAME_POINT -OBJECT_GI_BOOTS_2 -OBJECT_GI_SEED -OBJECT_GND_MAGIC -OBJECT_D_ELEVATOR -OBJECT_D_HSBLOCK -OBJECT_D_LIFT -OBJECT_MAMENOKI -OBJECT_GOROIWA -OBJECT_UNSET_120 -OBJECT_TORYO -OBJECT_DAIKU -OBJECT_UNSET_123 -OBJECT_NWC -OBJECT_BLKOBJ -OBJECT_GM -OBJECT_MS -OBJECT_HS -OBJECT_INGATE -OBJECT_LIGHTSWITCH -OBJECT_KUSA -OBJECT_TSUBO -OBJECT_GI_GLOVES -OBJECT_GI_COIN -OBJECT_KANBAN -OBJECT_GJYO_OBJECTS -OBJECT_OWL -OBJECT_MK -OBJECT_FU -OBJECT_GI_KI_TAN_MASK -OBJECT_GI_REDEAD_MASK -OBJECT_GI_SKJ_MASK -OBJECT_GI_RABIT_MASK -OBJECT_GI_TRUTH_MASK -OBJECT_GANON_OBJECTS -OBJECT_SIOFUKI -OBJECT_STREAM -OBJECT_MM -OBJECT_FA -OBJECT_OS -OBJECT_GI_EYE_LOTION -OBJECT_GI_POWDER -OBJECT_GI_MUSHROOM -OBJECT_GI_TICKETSTONE -OBJECT_GI_BROKENSWORD -OBJECT_JS -OBJECT_CS -OBJECT_GI_PRESCRIPTION -OBJECT_GI_BRACELET -OBJECT_GI_SOLDOUT -OBJECT_GI_FROG -OBJECT_MAG -OBJECT_DOOR_GERUDO -OBJECT_GT -OBJECT_EFC_ERUPC -OBJECT_ZL2_ANIME1 -OBJECT_ZL2_ANIME2 -OBJECT_GI_GOLONMASK -OBJECT_GI_ZORAMASK -OBJECT_GI_GERUDOMASK -OBJECT_GANON2 -OBJECT_KA -OBJECT_TS -OBJECT_ZG -OBJECT_GI_HOVERBOOTS -OBJECT_GI_M_ARROW -OBJECT_DS2 -OBJECT_EC -OBJECT_FISH -OBJECT_GI_SUTARU -OBJECT_GI_GODDESS -OBJECT_SSH -OBJECT_BIGOKUTA -OBJECT_BG -OBJECT_SPOT05_OBJECTS -OBJECT_SPOT12_OBJ -OBJECT_BOMBIWA -OBJECT_HINTNUTS -OBJECT_RS -OBJECT_SPOT00_BREAK -OBJECT_GLA -OBJECT_SHOPNUTS -OBJECT_GELDB -OBJECT_GR -OBJECT_DOG -OBJECT_JYA_IRON -OBJECT_JYA_DOOR -OBJECT_UNSET_16E -OBJECT_SPOT11_OBJ -OBJECT_KIBAKO2 -OBJECT_DNS -OBJECT_DNK -OBJECT_GI_FIRE -OBJECT_GI_INSECT -OBJECT_GI_BUTTERFLY -OBJECT_GI_GHOST -OBJECT_GI_SOUL -OBJECT_BOWL -OBJECT_DEMO_KEKKAI -OBJECT_EFC_DOUGHNUT -OBJECT_GI_DEKUPOUCH -OBJECT_GANON_ANIME1 -OBJECT_GANON_ANIME2 -OBJECT_GANON_ANIME3 -OBJECT_GI_RUPY -OBJECT_SPOT01_MATOYA -OBJECT_SPOT01_MATOYAB -OBJECT_MU -OBJECT_WF -OBJECT_SKB -OBJECT_GJ -OBJECT_GEFF -OBJECT_HAKA_DOOR -OBJECT_GS -OBJECT_PS -OBJECT_BWALL -OBJECT_COW -OBJECT_COB -OBJECT_GI_SWORD_1 -OBJECT_DOOR_KILLER -OBJECT_OUKE_HAKA -OBJECT_TIMEBLOCK -OBJECT_ZL4 \ No newline at end of file diff --git a/tools/ZAPDConfigs/SpecialEntranceList.txt b/tools/ZAPDConfigs/SpecialEntranceList.txt deleted file mode 100644 index fdd12773de..0000000000 --- a/tools/ZAPDConfigs/SpecialEntranceList.txt +++ /dev/null @@ -1,7 +0,0 @@ -ENTR_RETURN_GREAT_FAIRYS_FOUNTAIN_SPELLS -ENTR_RETURN_SHOOTING_GALLERY -ENTR_RETURN_2 -ENTR_RETURN_BAZAAR -ENTR_RETURN_4 -ENTR_RETURN_GREAT_FAIRYS_FOUNTAIN_MAGIC -ENTR_RETURN_GROTTO diff --git a/tools/ZAPDConfigs/gc-eu-mq-dbg/Config.xml b/tools/ZAPDConfigs/gc-eu-mq-dbg/Config.xml deleted file mode 100644 index 0b6ea61ff5..0000000000 --- a/tools/ZAPDConfigs/gc-eu-mq-dbg/Config.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - diff --git a/tools/ZAPDConfigs/gc-eu-mq-dbg/SymbolMap.txt b/tools/ZAPDConfigs/gc-eu-mq-dbg/SymbolMap.txt deleted file mode 100644 index 54d92b15e1..0000000000 --- a/tools/ZAPDConfigs/gc-eu-mq-dbg/SymbolMap.txt +++ /dev/null @@ -1,2 +0,0 @@ -8012DB20 gIdentityMtx -80A8E610 sShadowTex diff --git a/tools/ZAPDConfigs/gc-eu-mq/Config.xml b/tools/ZAPDConfigs/gc-eu-mq/Config.xml deleted file mode 100644 index 0b6ea61ff5..0000000000 --- a/tools/ZAPDConfigs/gc-eu-mq/Config.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - diff --git a/tools/ZAPDConfigs/gc-eu-mq/SymbolMap.txt b/tools/ZAPDConfigs/gc-eu-mq/SymbolMap.txt deleted file mode 100644 index 7e1132fc21..0000000000 --- a/tools/ZAPDConfigs/gc-eu-mq/SymbolMap.txt +++ /dev/null @@ -1,2 +0,0 @@ -800FBC00 gIdentityMtx -80A72FA0 sShadowTex diff --git a/tools/ZAPDConfigs/gc-eu/Config.xml b/tools/ZAPDConfigs/gc-eu/Config.xml deleted file mode 100644 index 0b6ea61ff5..0000000000 --- a/tools/ZAPDConfigs/gc-eu/Config.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - diff --git a/tools/ZAPDConfigs/gc-eu/SymbolMap.txt b/tools/ZAPDConfigs/gc-eu/SymbolMap.txt deleted file mode 100644 index 99b8cf8c05..0000000000 --- a/tools/ZAPDConfigs/gc-eu/SymbolMap.txt +++ /dev/null @@ -1,2 +0,0 @@ -800FBC20 gIdentityMtx -80A73020 sShadowTex diff --git a/tools/ZAPDConfigs/gc-jp-ce/Config.xml b/tools/ZAPDConfigs/gc-jp-ce/Config.xml deleted file mode 100644 index b2f4e3e4d3..0000000000 --- a/tools/ZAPDConfigs/gc-jp-ce/Config.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - diff --git a/tools/ZAPDConfigs/gc-jp-ce/SymbolMap.txt b/tools/ZAPDConfigs/gc-jp-ce/SymbolMap.txt deleted file mode 100644 index 038e0ca7b4..0000000000 --- a/tools/ZAPDConfigs/gc-jp-ce/SymbolMap.txt +++ /dev/null @@ -1,2 +0,0 @@ -800FE2A0 gIdentityMtx -80A74120 sShadowTex diff --git a/tools/ZAPDConfigs/gc-jp-mq/Config.xml b/tools/ZAPDConfigs/gc-jp-mq/Config.xml deleted file mode 100644 index b2f4e3e4d3..0000000000 --- a/tools/ZAPDConfigs/gc-jp-mq/Config.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - diff --git a/tools/ZAPDConfigs/gc-jp-mq/SymbolMap.txt b/tools/ZAPDConfigs/gc-jp-mq/SymbolMap.txt deleted file mode 100644 index 5f5a09bdce..0000000000 --- a/tools/ZAPDConfigs/gc-jp-mq/SymbolMap.txt +++ /dev/null @@ -1,2 +0,0 @@ -800FE2A0 gIdentityMtx -80A740D0 sShadowTex diff --git a/tools/ZAPDConfigs/gc-jp/Config.xml b/tools/ZAPDConfigs/gc-jp/Config.xml deleted file mode 100644 index b2f4e3e4d3..0000000000 --- a/tools/ZAPDConfigs/gc-jp/Config.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - diff --git a/tools/ZAPDConfigs/gc-jp/SymbolMap.txt b/tools/ZAPDConfigs/gc-jp/SymbolMap.txt deleted file mode 100644 index 86349adc0f..0000000000 --- a/tools/ZAPDConfigs/gc-jp/SymbolMap.txt +++ /dev/null @@ -1,2 +0,0 @@ -800FE2C0 gIdentityMtx -80A74150 sShadowTex diff --git a/tools/ZAPDConfigs/gc-us-mq/Config.xml b/tools/ZAPDConfigs/gc-us-mq/Config.xml deleted file mode 100644 index b2f4e3e4d3..0000000000 --- a/tools/ZAPDConfigs/gc-us-mq/Config.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - diff --git a/tools/ZAPDConfigs/gc-us-mq/SymbolMap.txt b/tools/ZAPDConfigs/gc-us-mq/SymbolMap.txt deleted file mode 100644 index 252ade1105..0000000000 --- a/tools/ZAPDConfigs/gc-us-mq/SymbolMap.txt +++ /dev/null @@ -1,2 +0,0 @@ -800FE280 gIdentityMtx -80A740B0 sShadowTex diff --git a/tools/ZAPDConfigs/gc-us/Config.xml b/tools/ZAPDConfigs/gc-us/Config.xml deleted file mode 100644 index b2f4e3e4d3..0000000000 --- a/tools/ZAPDConfigs/gc-us/Config.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - diff --git a/tools/ZAPDConfigs/gc-us/SymbolMap.txt b/tools/ZAPDConfigs/gc-us/SymbolMap.txt deleted file mode 100644 index 79433d6691..0000000000 --- a/tools/ZAPDConfigs/gc-us/SymbolMap.txt +++ /dev/null @@ -1,2 +0,0 @@ -800FE2A0 gIdentityMtx -80A74130 sShadowTex diff --git a/tools/ZAPDConfigs/ique-cn/Config.xml b/tools/ZAPDConfigs/ique-cn/Config.xml deleted file mode 100644 index b2f4e3e4d3..0000000000 --- a/tools/ZAPDConfigs/ique-cn/Config.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - diff --git a/tools/ZAPDConfigs/ique-cn/SymbolMap.txt b/tools/ZAPDConfigs/ique-cn/SymbolMap.txt deleted file mode 100644 index 37a1f9a672..0000000000 --- a/tools/ZAPDConfigs/ique-cn/SymbolMap.txt +++ /dev/null @@ -1,2 +0,0 @@ -80106980 gIdentityMtx -80AE0B10 sShadowTex diff --git a/tools/ZAPDConfigs/ntsc-1.0/Config.xml b/tools/ZAPDConfigs/ntsc-1.0/Config.xml deleted file mode 100644 index b2f4e3e4d3..0000000000 --- a/tools/ZAPDConfigs/ntsc-1.0/Config.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - diff --git a/tools/ZAPDConfigs/ntsc-1.0/SymbolMap.txt b/tools/ZAPDConfigs/ntsc-1.0/SymbolMap.txt deleted file mode 100644 index 0d0ae8d436..0000000000 --- a/tools/ZAPDConfigs/ntsc-1.0/SymbolMap.txt +++ /dev/null @@ -1,2 +0,0 @@ -800FEDB0 gIdentityMtx -80AE0AE0 sShadowTex diff --git a/tools/ZAPDConfigs/ntsc-1.1/Config.xml b/tools/ZAPDConfigs/ntsc-1.1/Config.xml deleted file mode 100644 index b2f4e3e4d3..0000000000 --- a/tools/ZAPDConfigs/ntsc-1.1/Config.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - diff --git a/tools/ZAPDConfigs/ntsc-1.1/SymbolMap.txt b/tools/ZAPDConfigs/ntsc-1.1/SymbolMap.txt deleted file mode 100644 index d494cd2bfe..0000000000 --- a/tools/ZAPDConfigs/ntsc-1.1/SymbolMap.txt +++ /dev/null @@ -1,2 +0,0 @@ -800FEF70 gIdentityMtx -80AE0C80 sShadowTex diff --git a/tools/ZAPDConfigs/ntsc-1.2/Config.xml b/tools/ZAPDConfigs/ntsc-1.2/Config.xml deleted file mode 100644 index b2f4e3e4d3..0000000000 --- a/tools/ZAPDConfigs/ntsc-1.2/Config.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - diff --git a/tools/ZAPDConfigs/ntsc-1.2/SymbolMap.txt b/tools/ZAPDConfigs/ntsc-1.2/SymbolMap.txt deleted file mode 100644 index 5f7af0dc80..0000000000 --- a/tools/ZAPDConfigs/ntsc-1.2/SymbolMap.txt +++ /dev/null @@ -1,2 +0,0 @@ -800FF3F0 gIdentityMtx -80AE0FE0 sShadowTex diff --git a/tools/ZAPDConfigs/pal-1.0/Config.xml b/tools/ZAPDConfigs/pal-1.0/Config.xml deleted file mode 100644 index 0b6ea61ff5..0000000000 --- a/tools/ZAPDConfigs/pal-1.0/Config.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - diff --git a/tools/ZAPDConfigs/pal-1.0/SymbolMap.txt b/tools/ZAPDConfigs/pal-1.0/SymbolMap.txt deleted file mode 100644 index 5ebd4ad9ab..0000000000 --- a/tools/ZAPDConfigs/pal-1.0/SymbolMap.txt +++ /dev/null @@ -1,2 +0,0 @@ -800FCD00 gIdentityMtx -80AE19F0 sShadowTex diff --git a/tools/ZAPDConfigs/pal-1.1/Config.xml b/tools/ZAPDConfigs/pal-1.1/Config.xml deleted file mode 100644 index 0b6ea61ff5..0000000000 --- a/tools/ZAPDConfigs/pal-1.1/Config.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - diff --git a/tools/ZAPDConfigs/pal-1.1/SymbolMap.txt b/tools/ZAPDConfigs/pal-1.1/SymbolMap.txt deleted file mode 100644 index d41f225318..0000000000 --- a/tools/ZAPDConfigs/pal-1.1/SymbolMap.txt +++ /dev/null @@ -1,2 +0,0 @@ -800FCD40 gIdentityMtx -80AE1B80 sShadowTex diff --git a/tools/assets/Makefile b/tools/assets/Makefile index d445d38794..324e19d571 100644 --- a/tools/assets/Makefile +++ b/tools/assets/Makefile @@ -1,8 +1,11 @@ all: +# must build n64texconv before build_from_png $(MAKE) -C n64texconv + $(MAKE) -C build_from_png clean: $(MAKE) -C n64texconv clean + $(MAKE) -C build_from_png clean distclean: clean $(MAKE) -C n64texconv distclean diff --git a/tools/assets/build_from_png/.gitignore b/tools/assets/build_from_png/.gitignore new file mode 100644 index 0000000000..e0d6a78806 --- /dev/null +++ b/tools/assets/build_from_png/.gitignore @@ -0,0 +1 @@ +build_from_png diff --git a/tools/assets/build_from_png/Makefile b/tools/assets/build_from_png/Makefile new file mode 100644 index 0000000000..4a74a0d6e8 --- /dev/null +++ b/tools/assets/build_from_png/Makefile @@ -0,0 +1,17 @@ +CFLAGS := -Wall -Werror -O3 + +ifeq ($(shell $(CC) --version | grep clang),) + OMPFLAGS := -fopenmp +else + OMPFLAGS := +endif + +default: build_from_png + +clean: + $(RM) build_from_png + +.PHONY: default clean + +build_from_png: build_from_png.c ../n64texconv/libn64texconv.a + $(CC) $(CFLAGS) -o $@ $^ $(OMPFLAGS) -lz -lm diff --git a/tools/assets/build_from_png/build_from_png.c b/tools/assets/build_from_png/build_from_png.c new file mode 100644 index 0000000000..4ce790d04c --- /dev/null +++ b/tools/assets/build_from_png/build_from_png.c @@ -0,0 +1,554 @@ +// SPDX-FileCopyrightText: © 2024 ZeldaRET +// SPDX-License-Identifier: MIT + +// Note: this is statically linked with GPL binaries, making the binary GPL-licensed + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../n64texconv/src/libn64texconv/n64texconv.h" + +#define NUM_FORMATS 9 +static const struct fmt_info { + const char* name; + int fmt; + int siz; +} fmt_map[NUM_FORMATS] = { + // clang-format off + { "i4", G_IM_FMT_I, G_IM_SIZ_4b, }, + { "i8", G_IM_FMT_I, G_IM_SIZ_8b, }, + { "ci4", G_IM_FMT_CI, G_IM_SIZ_4b, }, + { "ci8", G_IM_FMT_CI, G_IM_SIZ_8b, }, + { "ia4", G_IM_FMT_IA, G_IM_SIZ_4b, }, + { "ia8", G_IM_FMT_IA, G_IM_SIZ_8b, }, + { "ia16", G_IM_FMT_IA, G_IM_SIZ_16b, }, + { "rgba16", G_IM_FMT_RGBA, G_IM_SIZ_16b, }, + { "rgba32", G_IM_FMT_RGBA, G_IM_SIZ_32b, }, + // clang-format on +}; + +#define strequ(s1, s2) (strcmp(s1, s2) == 0) +#define strstartswith(s, prefix) (strncmp(s, prefix, strlen(prefix)) == 0) +static bool strendswith(const char* s, const char* suffix) { + size_t len_s = strlen(s); + size_t len_suffix = strlen(suffix); + return (len_s >= len_suffix) && (strncmp(s + len_s - len_suffix, suffix, len_suffix) == 0); +} + +static bool parse_png_p(char* png_p_buf, const struct fmt_info** fmtp, int* elem_sizep, char** tlut_namep, + int* tlut_elem_sizep, bool print_err) { + // The last 4 (or less) suffixes, without the '.' + const int max_n_suffixes = 4; + char* png_p_suffixes[max_n_suffixes]; + int n_suffixes_found = 0; + size_t i = strlen(png_p_buf); + while (i != 0) { + i--; + if (png_p_buf[i] == '.') { + png_p_suffixes[n_suffixes_found] = &png_p_buf[i + 1]; + n_suffixes_found++; + if (n_suffixes_found >= max_n_suffixes) { + break; + } + png_p_buf[i] = '\0'; + } + } + + if (n_suffixes_found == 0 || !strequ(png_p_suffixes[0], "png")) { + if (print_err) { + fprintf(stderr, "png path doesn't end with .png\n"); + } + return false; + } + int i_suffix = 1; + int i_suffix_elemtype = -1; + int i_suffix_tlut = -1; + int i_suffix_fmt = -1; + if (i_suffix < n_suffixes_found && + (strequ(png_p_suffixes[i_suffix], "u32") || strequ(png_p_suffixes[i_suffix], "u64"))) { + i_suffix_elemtype = i_suffix; + i_suffix++; + } + if (i_suffix < n_suffixes_found && strstartswith(png_p_suffixes[i_suffix], "tlut_")) { + i_suffix_tlut = i_suffix; + i_suffix++; + } + if (i_suffix >= n_suffixes_found) { + if (print_err) { + fprintf(stderr, "png path is missing a .format suffix\n"); + } + return false; + } + i_suffix_fmt = i_suffix; + + if (i_suffix_elemtype < 0) { + if (print_err) { + fprintf(stderr, "png path is missing a .u32 or .u64 suffix\n"); + } + return false; + } else { + if (strequ(png_p_suffixes[i_suffix_elemtype], "u64")) { + *elem_sizep = 8; + } else if (strequ(png_p_suffixes[i_suffix_elemtype], "u32")) { + *elem_sizep = 4; + } else { + // unreachable + assert(false); + } + } + + const struct fmt_info* fmt = NULL; + + for (size_t i = 0; i < NUM_FORMATS; i++) { + if (strequ(fmt_map[i].name, png_p_suffixes[i_suffix_fmt])) { + fmt = &fmt_map[i]; + break; + } + } + + if (fmt == NULL) { + if (print_err) { + fprintf(stderr, "png path is missing a .format suffix\n"); + } + return false; + } + + if (fmt->fmt == G_IM_FMT_CI && i_suffix_tlut >= 0) { + if (strendswith(png_p_suffixes[i_suffix_tlut], "_u64")) { + *tlut_elem_sizep = 8; + } else if (strendswith(png_p_suffixes[i_suffix_tlut], "_u32")) { + *tlut_elem_sizep = 4; + } else { + if (print_err) { + fprintf(stderr, "png path with ci format has a .tlut_ suffix without a _u32 or _u64 suffix\n"); + } + return false; + } + // extract "ABC" from the "tlut_ABC_uXX" suffix + if (strlen(png_p_suffixes[i_suffix_tlut]) <= strlen("tlut__uXX")) { + if (print_err) { + fprintf(stderr, "png path with ci format has a bad .tlut_ suffix\n"); + } + return false; + } + png_p_suffixes[i_suffix_tlut][strlen(png_p_suffixes[i_suffix_tlut]) - strlen("_uXX")] = '\0'; + *tlut_namep = strdup(png_p_suffixes[i_suffix_tlut] + strlen("tlut_")); + } + + *fmtp = fmt; + + return true; +} + +static void free_dir_list(char** dir_list) { + for (size_t i = 0; dir_list[i] != NULL; i++) { + free(dir_list[i]); + } + free(dir_list); +} + +/** + * Returns a NULL-terminated array of filenames in `dir_p`, + * or NULL if an error happens. + */ +static char** new_dir_list(const char* dir_p) { + DIR* dir = opendir(dir_p); + if (dir == NULL) { + perror("opendir"); + return NULL; + } + + size_t len_dir_list = 0; + size_t maxlen_dir_list = 16; + char** dir_list = malloc(sizeof(char* [maxlen_dir_list])); + + while (true) { + errno = 0; + struct dirent* dirent = readdir(dir); + if (dirent == NULL) { + if (errno != 0) { + perror("readdir"); + assert(len_dir_list < maxlen_dir_list); + dir_list[len_dir_list] = NULL; + free_dir_list(dir_list); + return NULL; + } + break; + } + assert(len_dir_list < maxlen_dir_list); + dir_list[len_dir_list] = strdup(dirent->d_name); + len_dir_list++; + + if (len_dir_list >= maxlen_dir_list) { + maxlen_dir_list *= 2; + dir_list = realloc(dir_list, sizeof(char* [maxlen_dir_list])); + } + } + + assert(len_dir_list < maxlen_dir_list); + dir_list[len_dir_list] = NULL; + + if (closedir(dir) != 0) { + perror("closedir"); + free_dir_list(dir_list); + return NULL; + } + return dir_list; +} + +static char* make_inc_c_p(const char* png_p, const char* out_dir_p) { + char* png_p_buf = strdup(png_p); + char* png_stem = basename(png_p_buf); + assert(strendswith(png_stem, ".png")); // checked by parse_png_p + png_stem[strlen(png_stem) - strlen(".png")] = '\0'; // cut off .png suffix + char* inc_c_p = malloc(strlen(out_dir_p) + strlen("/") + strlen(png_stem) + strlen(".inc.c") + 1); + sprintf(inc_c_p, "%s/%s.inc.c", out_dir_p, png_stem); + free(png_p_buf); + return inc_c_p; +} + +static bool handle_non_ci(const char* png_p, const struct fmt_info* fmt, int elem_size, const char* out_dir_p) { + char* inc_c_p = make_inc_c_p(png_p, out_dir_p); + + struct n64_image* img = n64texconv_image_from_png(png_p, fmt->fmt, fmt->siz, G_IM_FMT_RGBA); + bool success = n64texconv_image_to_c_file(inc_c_p, img, false, false, elem_size) == 0; + n64texconv_image_free(img); + free(inc_c_p); + return success; +} + +static bool handle_ci_single(const char* png_p, const struct fmt_info* fmt, int elem_size, const char* out_dir_p) { + const int tlut_elem_size = 8; + char* inc_c_p = make_inc_c_p(png_p, out_dir_p); + + char* png_p_buf = strdup(png_p); + char* png_stem = basename(png_p_buf); + // parse_png_p ensured these suffixes + assert(strlen(png_stem) >= strlen(".ciX.uXX.png")); + png_stem[strlen(png_stem) - strlen(".ciX.uXX.png")] = '\0'; + char* pal_inc_c_p = + malloc(strlen(out_dir_p) + strlen("/") + strlen(png_stem) + strlen(".tlut.rgba16.u64.inc.c") + 1); + sprintf(pal_inc_c_p, "%s/%s.tlut.rgba16.u64.inc.c", out_dir_p, png_stem); + free(png_p_buf); + + struct n64_image* img = n64texconv_image_from_png(png_p, fmt->fmt, fmt->siz, G_IM_FMT_RGBA); + bool success = n64texconv_image_to_c_file(inc_c_p, img, false, false, elem_size) == 0; + if (!success) { + fprintf(stderr, "Could not write image to %s\n", inc_c_p); + } + if (success) { + success = n64texconv_palette_to_c_file(pal_inc_c_p, img->pal, true, tlut_elem_size) == 0; + if (!success) { + fprintf(stderr, "Could not write palette to %s\n", pal_inc_c_p); + } + } + n64texconv_palette_free(img->pal); + n64texconv_image_free(img); + free(inc_c_p); + free(pal_inc_c_p); + return success; +} + +static bool handle_ci_shared_tlut(const char* png_p, const struct fmt_info* fmt, const char* out_dir_p, char** in_dirs, + int num_in_dirs, char* tlut_name, int tlut_elem_size) { + const size_t len_out_dir_p = strlen(out_dir_p); + + size_t len_pngs_with_tlut = 0; + size_t maxlen_pngs_with_tlut = 16; + struct other_png_info { + char* png_p; + char* name; // pointer into png_p; don't free + int elem_size; + struct n64_image* img; + }* pngs_with_tlut = malloc(sizeof(struct other_png_info[maxlen_pngs_with_tlut])); + + for (int j = 0; j < num_in_dirs; j++) { + const char* in_dir_p = in_dirs[j]; + const size_t len_in_dir_p = strlen(in_dir_p); + + char** in_dir_list = new_dir_list(in_dir_p); + if (in_dir_list == NULL) { + fprintf(stderr, "Couldn't list files in %s\n", in_dir_p); + return false; + } + + for (size_t i = 0; in_dir_list[i] != NULL; i++) { + char* direntry_name_buf = strdup(in_dir_list[i]); + const struct fmt_info* direntry_fmt; + int direntry_elem_size; + char* direntry_tlut_name = NULL; + int direntry_tlut_elem_size = -1; + if (parse_png_p(direntry_name_buf, &direntry_fmt, &direntry_elem_size, &direntry_tlut_name, + &direntry_tlut_elem_size, false)) { + if (direntry_fmt->fmt == G_IM_FMT_CI && direntry_tlut_name != NULL) { + if (strequ(tlut_name, direntry_tlut_name)) { + // TODO change asserts to errors and fail + assert(direntry_fmt == fmt); + assert(direntry_tlut_elem_size == tlut_elem_size); + + bool png_name_already_found = false; + for (size_t k = 0; k < len_pngs_with_tlut; k++) { + if (strequ(pngs_with_tlut[k].name, in_dir_list[i])) { + png_name_already_found = true; + break; + } + } + + if (!png_name_already_found) { + if (len_pngs_with_tlut == maxlen_pngs_with_tlut) { + maxlen_pngs_with_tlut *= 2; + pngs_with_tlut = + realloc(pngs_with_tlut, sizeof(struct other_png_info[maxlen_pngs_with_tlut])); + } + assert(len_pngs_with_tlut < maxlen_pngs_with_tlut); + char* other_png_p = malloc(len_in_dir_p + strlen("/") + strlen(in_dir_list[i]) + 1); + sprintf(other_png_p, "%s/%s", in_dir_p, in_dir_list[i]); + pngs_with_tlut[len_pngs_with_tlut].png_p = other_png_p; + pngs_with_tlut[len_pngs_with_tlut].name = other_png_p + len_in_dir_p + strlen("/"); + pngs_with_tlut[len_pngs_with_tlut].elem_size = direntry_elem_size; + pngs_with_tlut[len_pngs_with_tlut].img = NULL; + len_pngs_with_tlut++; + } + } + } + } + free(direntry_name_buf); + } + assert(len_pngs_with_tlut <= maxlen_pngs_with_tlut); + + free_dir_list(in_dir_list); + } + + struct n64_image* ref_img = n64texconv_image_from_png(png_p, G_IM_FMT_CI, fmt->siz, G_IM_FMT_RGBA); + bool all_other_pngs_match_ref_img_pal = true; + + bool success = true; + + for (size_t i = 0; i < len_pngs_with_tlut; i++) { + struct n64_image* other_img = + n64texconv_image_from_png(pngs_with_tlut[i].png_p, G_IM_FMT_CI, fmt->siz, G_IM_FMT_RGBA); + pngs_with_tlut[i].img = other_img; + if (other_img == NULL) { + fprintf(stderr, "Could not read png %s\n", pngs_with_tlut[i].png_p); + success = false; + break; + } + if (all_other_pngs_match_ref_img_pal) { + bool pal_matches_ref = + other_img->pal->count == ref_img->pal->count && + memcmp(other_img->pal->texels, ref_img->pal->texels, sizeof(struct color[ref_img->pal->count])) == 0; + if (!pal_matches_ref) { + all_other_pngs_match_ref_img_pal = false; + } + } + } + + if (success) { + for (size_t i = 0; i < len_pngs_with_tlut; i++) { + assert(pngs_with_tlut[i].img != NULL); +#ifdef VERBOSE + fprintf(stderr, "%s %s\n", pngs_with_tlut[i].name, pngs_with_tlut[i].png_p); +#endif + } + + char* pal_inc_c_p = + malloc(len_out_dir_p + strlen("/") + strlen(tlut_name) + strlen(".tlut.rgba16.uXX.inc.c") + 1); + assert(tlut_elem_size == 8 || tlut_elem_size == 4); + sprintf(pal_inc_c_p, "%s/%s.tlut.rgba16.%s.inc.c", out_dir_p, tlut_name, tlut_elem_size == 8 ? "u64" : "u32"); + + if (all_other_pngs_match_ref_img_pal) { + // write matching palette, and matching color indices for all pngs +#ifdef VERBOSE + fprintf(stderr, "Matching data detected!\n"); +#endif + + // pass pad_to_8b=true to account for the case where this is in fact not matching data + // (the png was silently palettized by n64texconv) + // Note: this forces all palette sizes to be 8-aligned, even u32-element-typed ones + int ret = n64texconv_palette_to_c_file(pal_inc_c_p, ref_img->pal, true, tlut_elem_size); + success = ret == 0; + if (!success) { + fprintf(stderr, "Could not write palette to %s (%d)\n", pal_inc_c_p, ret); + } + + if (success) { + for (size_t i = 0; i < len_pngs_with_tlut; i++) { + char* inc_c_p = make_inc_c_p(pngs_with_tlut[i].png_p, out_dir_p); + + success = n64texconv_image_to_c_file(inc_c_p, pngs_with_tlut[i].img, false, false, + pngs_with_tlut[i].elem_size) == 0; + if (!success) { + fprintf(stderr, "Could not write image to %s\n", inc_c_p); + } + free(inc_c_p); + if (!success) { + break; + } + } + } + } else { + // co-palettize all pngs +#ifdef VERBOSE + fprintf(stderr, "Non-matching data detected!\n"); +#endif + const bool copaletize_write_out_pngs = true; + + const size_t num_images = len_pngs_with_tlut; + uint8_t* out_indices[num_images]; + struct color* texels[num_images]; + size_t widths[num_images]; + size_t heights[num_images]; + for (size_t i = 0; i < len_pngs_with_tlut; i++) { + assert(pngs_with_tlut[i].img != NULL); + out_indices[i] = malloc(pngs_with_tlut[i].img->width * pngs_with_tlut[i].img->height); + texels[i] = pngs_with_tlut[i].img->texels; + widths[i] = pngs_with_tlut[i].img->width; + heights[i] = pngs_with_tlut[i].img->height; + } + const unsigned int max_colors = fmt->siz == G_IM_SIZ_8b ? 256 : 16; + struct color out_pal[max_colors]; + size_t out_pal_count; + const float dither_level = 0.5f; + + success = n64texconv_quantize_shared(out_indices, out_pal, &out_pal_count, texels, widths, heights, + num_images, max_colors, dither_level) == 0; + if (!success) { + fprintf(stderr, "Could not co-palettize images\n"); + } + + struct n64_palette pal = { out_pal, G_IM_FMT_RGBA, out_pal_count }; + if (success) { + int ret = n64texconv_palette_to_c_file(pal_inc_c_p, &pal, true, tlut_elem_size); + success = ret == 0; + if (!success) { + fprintf(stderr, "Could not write generated palette to %s (%d)\n", pal_inc_c_p, ret); + } + } + if (success) { + if (copaletize_write_out_pngs) { + char* pal_out_png_p = strdup(pal_inc_c_p); + assert(strendswith(pal_inc_c_p, ".inc.c")); + pal_out_png_p[strlen(pal_out_png_p) - strlen(".inc.c")] = '\0'; + strcat(pal_out_png_p, ".png"); + success = n64texconv_palette_to_png(pal_out_png_p, &pal) == 0; + if (!success) { + fprintf(stderr, "Could not write generated palette to png %s\n", pal_out_png_p); + } + free(pal_out_png_p); + } + } + if (success) { + for (size_t i = 0; i < len_pngs_with_tlut; i++) { + char* other_png_p_buf = strdup(pngs_with_tlut[i].png_p); + char* other_png_stem = basename(other_png_p_buf); + assert(strendswith(other_png_stem, ".png")); // checked by parse_png_p + other_png_stem[strlen(other_png_stem) - strlen(".png")] = '\0'; // cut off .png suffix + char* inc_c_p = malloc(len_out_dir_p + strlen("/") + strlen(other_png_stem) + strlen(".inc.c") + 1); + sprintf(inc_c_p, "%s/%s.inc.c", out_dir_p, other_png_stem); + free(other_png_p_buf); + + struct n64_image img = { + pngs_with_tlut[i].img->width, + pngs_with_tlut[i].img->height, + G_IM_FMT_CI, + fmt->siz, + &pal, + pngs_with_tlut[i].img->texels, + out_indices[i], + }; + + success = n64texconv_image_to_c_file(inc_c_p, &img, false, false, pngs_with_tlut[i].elem_size) == 0; + if (!success) { + fprintf(stderr, "Could not write palettized image to %s\n", inc_c_p); + break; + } + + if (copaletize_write_out_pngs) { + char* out_png_p = strdup(inc_c_p); + assert(strendswith(inc_c_p, ".inc.c")); + out_png_p[strlen(out_png_p) - strlen(".inc.c")] = '\0'; + strcat(out_png_p, ".png"); + success = n64texconv_image_to_png(out_png_p, &img, false) == 0; + if (!success) { + fprintf(stderr, "Could not write palettized image to png %s\n", out_png_p); + } + free(out_png_p); + if (!success) { + break; + } + } + } + } + + for (size_t i = 0; i < num_images; i++) { + free(out_indices[i]); + } + } + + free(pal_inc_c_p); + } + + n64texconv_image_free(ref_img); + + for (size_t i = 0; i < len_pngs_with_tlut; i++) { + free(pngs_with_tlut[i].png_p); + if (pngs_with_tlut[i].img != NULL) { + n64texconv_palette_free(pngs_with_tlut[i].img->pal); + n64texconv_image_free(pngs_with_tlut[i].img); + } + } + free(pngs_with_tlut); + + return success; +} + +int main(int argc, char** argv) { + if (argc < 3) { + usage: + fprintf(stderr, "Usage: build_from_png path/to/file.png path/to/out/folder/ [path/to/input/folder1/ ...]\n"); + fprintf(stderr, "The png file should be named like:\n"); + fprintf(stderr, " - texName.format..png (non-ci formats or ci formats with a non-shared tlut)\n"); + fprintf(stderr, " - texName.ci<4|8>.tlut_tlutName_..png (ci formats with a shared tlut)\n"); + return EXIT_FAILURE; + } + const char* png_p = argv[1]; + const char* out_dir_p = argv[2]; + char** in_dirs = argv + 3; + const int num_in_dirs = argc - 3; + + const struct fmt_info* fmt; + int elem_size; + char* tlut_name = NULL; + int tlut_elem_size = -1; + + { + char* png_p_buf = strdup(png_p); + bool success = parse_png_p(png_p_buf, &fmt, &elem_size, &tlut_name, &tlut_elem_size, true); + free(png_p_buf); + if (!success) { + goto usage; + } + } + + bool success; + + if (fmt->fmt != G_IM_FMT_CI) { + success = handle_non_ci(png_p, fmt, elem_size, out_dir_p); + } else { + if (tlut_name == NULL) { + success = handle_ci_single(png_p, fmt, elem_size, out_dir_p); + } else { + success = handle_ci_shared_tlut(png_p, fmt, out_dir_p, in_dirs, num_in_dirs, tlut_name, tlut_elem_size); + free(tlut_name); + } + } + + return success ? EXIT_SUCCESS : EXIT_FAILURE; +} diff --git a/tools/assets/conf.py b/tools/assets/conf.py new file mode 100644 index 0000000000..f31582a988 --- /dev/null +++ b/tools/assets/conf.py @@ -0,0 +1,2 @@ +WRITE_HINTS = True +I_D_OMEGALUL = True # IDO specific things that may be otherwise different diff --git a/tools/assets/descriptor/README.md b/tools/assets/descriptor/README.md new file mode 100644 index 0000000000..6336e0d417 --- /dev/null +++ b/tools/assets/descriptor/README.md @@ -0,0 +1 @@ +This package serves as an abstraction layer wrapping assets xml files. diff --git a/tools/assets/descriptor/__main__.py b/tools/assets/descriptor/__main__.py new file mode 100644 index 0000000000..0d3f4e6dc3 --- /dev/null +++ b/tools/assets/descriptor/__main__.py @@ -0,0 +1,32 @@ +# SPDX-FileCopyrightText: © 2025 ZeldaRET +# SPDX-License-Identifier: CC0-1.0 + +from pprint import pprint as vanilla_pprint + +try: + from rich.pretty import pprint +except ImportError: + pprint = vanilla_pprint + +from tools import version_config + +from . import base + + +def main(): + vc = version_config.load_version_config("gc-eu-mq-dbg") + + pools = base.get_resources_desc(vc) + + try: + for pool in pools: + if any(coll.out_path.name == "gameplay_keep" for coll in pool.collections): + vanilla_pprint(pool) + else: + pprint(pool) + input("Press enter for next pool") + except KeyboardInterrupt: + print() + + +main() diff --git a/tools/assets/descriptor/base.py b/tools/assets/descriptor/base.py new file mode 100644 index 0000000000..a0833ec093 --- /dev/null +++ b/tools/assets/descriptor/base.py @@ -0,0 +1,318 @@ +# SPDX-FileCopyrightText: © 2025 ZeldaRET +# SPDX-License-Identifier: CC0-1.0 + +import abc +import dataclasses +from functools import cache +from pathlib import Path +from typing import Callable, Optional +from xml.etree import ElementTree + +from tools import version_config + + +class BackingMemory(abc.ABC): + pass + + +@dataclasses.dataclass +class BaseromFileBackingMemory(BackingMemory): + name: str + range: Optional[tuple[int, int]] + """If set, consider file_data[range[0]:range[1]] instead of the full file""" + + +@dataclasses.dataclass +class NoBackingMemory(BackingMemory): + pass + + +# eq=False so this uses id-based equality and hashing +# Subclasses must also be made to use id-based equality and hashing +@dataclasses.dataclass(eq=False) +class ResourceDesc(abc.ABC): + """A resource is a data unit. + For example, a symbol's data such as a DList or a texture.""" + + symbol_name: str + offset: int + """How many bytes into the backing memory the resource is located at""" + collection: "ResourcesDescCollection" = dataclasses.field(repr=False) + origin: object + """opaque object with data about where this resource comes from (for debugging)""" + + hack_modes: set[str] = dataclasses.field(init=False, default_factory=set) + + +class StartAddress(abc.ABC): + pass + + +@dataclasses.dataclass +class VRAMStartAddress(StartAddress): + vram: int + + +@dataclasses.dataclass +class SegmentStartAddress(StartAddress): + segment: int + + +@dataclasses.dataclass(eq=False) +class ResourcesDescCollection: + """A collection is a list of resources backed by the same memory.""" + + out_path: Path + backing_memory: BackingMemory + start_address: Optional[StartAddress] + resources: list[ResourceDesc] + last_modified_time: float + depends: list["ResourcesDescCollection"] + + +@dataclasses.dataclass(eq=False) +class ResourcesDescCollectionsPool: + """A pool contains a minimal set of interconnected collections. + For example, gkeep and all files using gkeep, + or more simply a single collection with no connection.""" + + collections: list[ResourcesDescCollection] + + +ResourceHandlerPass2Callback = Callable[[ResourcesDescCollectionsPool], None] + + +@dataclasses.dataclass +class ResourceHandlerNeedsPass2Exception(Exception): + resource: ResourceDesc + pass2_callback: ResourceHandlerPass2Callback + + +# eq=False so this uses id-based equality and hashing +@dataclasses.dataclass(eq=False) +class AssetConfigPiece: + ac: version_config.AssetConfig + last_modified_time: float = None + etree: ElementTree.ElementTree = None + depends: list["AssetConfigPiece"] = dataclasses.field(default_factory=list) + """The AssetConfigPiece s this instance depends on""" + collections: list[ResourcesDescCollection] = dataclasses.field(default_factory=list) + + +def get_resources_desc(vc: version_config.VersionConfig): + # Wrap AssetConfig objects in AssetConfigPiece for hashability and to collect data + acps = [AssetConfigPiece(ac) for ac in vc.assets] + + # Parse xmls + for acp in acps: + acp.last_modified_time = acp.ac.xml_path.stat().st_mtime + try: + with acp.ac.xml_path.open(encoding="UTF-8") as f: + etree = ElementTree.parse(f) + acp.etree = etree + except Exception as e: + raise Exception(f"Error when parsing XML for {acp}") from e + + # Resolve pools + acp_by_name = {acp.ac.name: acp for acp in acps} + pools = {acp: {acp} for acp in acps} + for acp in acps: + try: + rootelem = acp.etree.getroot() + assert rootelem.tag == "Root", rootelem.tag + for fileelem in rootelem: + assert fileelem.tag in {"ExternalFile", "File"}, fileelem.tag + if fileelem.tag == "ExternalFile": + externalfile_name = str( + Path(fileelem.attrib["OutPath"]).relative_to("assets") + ) + assert externalfile_name in acp_by_name, externalfile_name + externalfile_acp = acp_by_name[externalfile_name] + acp.depends.append(externalfile_acp) + acp_pool = pools[acp] + externalfile_acp_pool = pools[externalfile_acp] + merged_pool = acp_pool | externalfile_acp_pool + for merged_pool_acp in merged_pool: + pools[merged_pool_acp] = merged_pool + except Exception as e: + raise Exception(f"Error while resolving pools with {acp}") from e + + # List unique pools + pools_unique: list[set[AssetConfigPiece]] = [] + while pools: + pool = next(iter(pools.values())) + pools_unique.append(pool) + for acp in pool: + del pools[acp] + + # Build resources for all pools + pools: list[ResourcesDescCollectionsPool] = [] + for pool in pools_unique: + try: + all_needs_pass2_exceptions: list[ResourceHandlerNeedsPass2Exception] = [] + rescolls: list[ResourcesDescCollection] = [] + + # Pass 1: create Resource objects + for acp in pool: + try: + rootelem = acp.etree.getroot() + for fileelem in rootelem: + if fileelem.tag == "File": + rc, needs_pass2_exceptions = ( + _get_resources_fileelem_to_resourcescollection_pass1( + vc, pool, acp, fileelem + ) + ) + acp.collections.append(rc) + rescolls.append(rc) + all_needs_pass2_exceptions.extend(needs_pass2_exceptions) + except Exception as e: + raise Exception(f"Error with {acp}") from e + + rcpool = ResourcesDescCollectionsPool(rescolls) + + # + for acp in pool: + for acp_coll in acp.collections: + acp_coll.depends.extend( + (_coll for _coll in acp.collections if _coll != acp_coll) + ) + for acp_dep in acp.depends: + acp_coll.depends.extend(acp_dep.collections) + + # Pass 2: execute callbacks + for needs_pass2_exc in all_needs_pass2_exceptions: + try: + needs_pass2_exc.pass2_callback(rcpool) + except Exception as e: + raise Exception( + f"Error with pass 2 callback for {needs_pass2_exc.resource}" + ) from e + + pools.append(rcpool) + + except Exception as e: + raise Exception(f"Error with pool {pool}") from e + + return pools + + +def _get_resources_fileelem_to_resourcescollection_pass1( + vc: version_config.VersionConfig, + pool: list[AssetConfigPiece], + acp: AssetConfigPiece, + fileelem: ElementTree.Element, +): + # Determine backing_memory + if acp.ac.start_offset is None: + assert acp.ac.end_offset is None + baserom_file_range = None + else: + assert acp.ac.end_offset is not None + baserom_file_range = (acp.ac.start_offset, acp.ac.end_offset) + backing_memory = BaseromFileBackingMemory( + name=fileelem.attrib["Name"], + range=baserom_file_range, + ) + + # Determine start_address + if any( + acp.ac.name.startswith(_prefix) for _prefix in ("code/", "n64dd/", "overlays/") + ): + # File start address is vram + assert "Segment" not in fileelem.attrib + assert acp.ac.start_offset is not None and acp.ac.end_offset is not None, ( + "Unsupported combination: " + f"start/end offset not in config for vram asset {acp.ac.name}" + ) + if acp.ac.name.startswith("overlays/"): + overlay_name = acp.ac.name.split("/")[1] + start_address = VRAMStartAddress( + vc.dmadata_segments[overlay_name].vram + acp.ac.start_offset + ) + else: + file_name = acp.ac.name.split("/")[0] # "code" or "n64dd" + start_address = VRAMStartAddress( + vc.dmadata_segments[file_name].vram + acp.ac.start_offset + ) + elif "Segment" in fileelem.attrib: + # File start address is a segmented address + assert acp.ac.start_offset is None and acp.ac.end_offset is None, ( + "Unsupported combination: " + "start/end offset in config and file starts at a segmented address" + ) + start_address = SegmentStartAddress(int(fileelem.attrib["Segment"])) + else: + # File does not have a start address + start_address = None + + # resources + resources: list[ResourceDesc] = [] + collection = ResourcesDescCollection( + Path(acp.ac.name), + backing_memory, + start_address, + resources, + acp.last_modified_time, + [], + ) + needs_pass2_exceptions: list[ResourceHandlerNeedsPass2Exception] = [] + for reselem in fileelem: + try: + symbol_name = reselem.attrib["Name"] + offset = int(reselem.attrib["Offset"], 16) + res_handler = _get_resource_handler(reselem.tag) + try: + res = res_handler(symbol_name, offset, collection, reselem) + except ResourceHandlerNeedsPass2Exception as needs_pass2_exc: + res = needs_pass2_exc.resource + needs_pass2_exceptions.append(needs_pass2_exc) + assert isinstance(res, ResourceDesc) + resources.append(res) + except Exception as e: + raise Exception( + "Error with resource element:\n" + + ElementTree.tostring(reselem, encoding="unicode") + ) from e + + return collection, needs_pass2_exceptions + + +ResourceHandler = Callable[ + [str, int, ResourcesDescCollection, ElementTree.Element], + ResourceDesc, +] + + +@cache +def _get_resource_handler(tag: str) -> ResourceHandler: + from . import n64resources + from . import z64resources + + resource_handlers = { + "DList": n64resources.handler_DList, + "Blob": n64resources.handler_Blob, + "Mtx": n64resources.handler_Mtx, + "Array": n64resources.handler_Array, + "Texture": n64resources.handler_Texture, + "Collision": z64resources.handler_Collision, + "Animation": z64resources.handler_Animation, + "PlayerAnimation": z64resources.handler_PlayerAnimation, + "LegacyAnimation": z64resources.handler_LegacyAnimation, + "Cutscene": z64resources.handler_Cutscene, + "Scene": z64resources.handler_Scene, + "Room": z64resources.handler_Room, + "PlayerAnimationData": z64resources.handler_PlayerAnimationData, + "Path": z64resources.handler_PathList, + "Skeleton": z64resources.handler_Skeleton, + "Limb": z64resources.handler_Limb, + "CurveAnimation": z64resources.handler_CurveAnimation, + "LimbTable": z64resources.handler_LimbTable, + } + + rh = resource_handlers.get(tag) + + if rh is None: + raise Exception(f"Unknown resource tag {tag}") + else: + return rh diff --git a/tools/assets/descriptor/n64resources.py b/tools/assets/descriptor/n64resources.py new file mode 100644 index 0000000000..53030c6630 --- /dev/null +++ b/tools/assets/descriptor/n64resources.py @@ -0,0 +1,239 @@ +# SPDX-FileCopyrightText: © 2025 ZeldaRET +# SPDX-License-Identifier: CC0-1.0 + +import dataclasses +import enum +from xml.etree.ElementTree import Element + +from ..n64 import G_IM_FMT, G_IM_SIZ + +from .base import ( + ResourceDesc, + ResourcesDescCollection, + ResourcesDescCollectionsPool, + ResourceHandlerNeedsPass2Exception, + BaseromFileBackingMemory, +) +from . import xml_errors + +# TODO remove +STATIC_ATTRIB = {"Static"} + + +class GfxMicroCode(enum.Enum): + F3DEX = enum.auto() + F3DEX2 = enum.auto() + + +@dataclasses.dataclass(eq=False) +class DListResourceDesc(ResourceDesc): + ucode: GfxMicroCode + raw_pointers: set[int] = dataclasses.field(default_factory=set) + """Pointers in the dlist that are fine to keep raw ("in hex") instead of using symbols""" + + +def handler_DList(symbol_name, offset, collection, reselem: Element): + xml_errors.check_attrib( + reselem, {"Name", "Offset"}, {"Ucode", "RawPointers"} | STATIC_ATTRIB + ) + if "Ucode" in reselem.attrib: + ucode = GfxMicroCode[reselem.attrib["Ucode"].upper()] + else: + ucode = GfxMicroCode.F3DEX2 + res = DListResourceDesc(symbol_name, offset, collection, reselem, ucode) + raw_pointers_str = reselem.attrib.get("RawPointers") + if raw_pointers_str: + for rp_str in raw_pointers_str.split(","): + res.raw_pointers.add(int(rp_str, 16)) + return res + + +@dataclasses.dataclass(eq=False) +class BlobResourceDesc(ResourceDesc): + size: int + + +def handler_Blob(symbol_name, offset, collection, reselem: Element): + xml_errors.check_attrib(reselem, {"Name", "Offset", "Size"}, STATIC_ATTRIB) + size = int(reselem.attrib["Size"], 16) + return BlobResourceDesc(symbol_name, offset, collection, reselem, size) + + +@dataclasses.dataclass(eq=False) +class MtxResourceDesc(ResourceDesc): + pass + + +def handler_Mtx(symbol_name, offset, collection, reselem: Element): + xml_errors.check_attrib(reselem, {"Name", "Offset"}, STATIC_ATTRIB) + return MtxResourceDesc(symbol_name, offset, collection, reselem) + + +@dataclasses.dataclass(eq=False) +class S16ArrayResourceDesc(ResourceDesc): + count: int + + +@dataclasses.dataclass(eq=False) +class Vec3sArrayResourceDesc(ResourceDesc): + count: int + + +@dataclasses.dataclass(eq=False) +class VtxArrayResourceDesc(ResourceDesc): + count: int + + +def handler_Array(symbol_name, offset, collection, reselem: Element): + xml_errors.check_attrib(reselem, {"Name", "Offset", "Count"}, STATIC_ATTRIB) + count = int(reselem.attrib["Count"]) + assert len(reselem) == 1, "Expected exactly one child of Array node" + array_elem = reselem[0] + if array_elem.tag == "Vtx": + array_resource_type = VtxArrayResourceDesc + elif ( + array_elem.tag == "Vector" + and array_elem.attrib["Type"] == "s16" + and int(array_elem.attrib["Dimensions"]) == 3 + ): + array_resource_type = Vec3sArrayResourceDesc + elif array_elem.tag == "Scalar" and array_elem.attrib["Type"] == "s16": + array_resource_type = S16ArrayResourceDesc + else: + raise NotImplementedError(f"Array of {array_elem.tag}") + return array_resource_type(symbol_name, offset, collection, reselem, count) + + +class TextureFormat(enum.Enum): + RGBA16 = (G_IM_FMT.RGBA, G_IM_SIZ._16b) + RGBA32 = (G_IM_FMT.RGBA, G_IM_SIZ._32b) + CI4 = (G_IM_FMT.CI, G_IM_SIZ._4b) + CI8 = (G_IM_FMT.CI, G_IM_SIZ._8b) + I4 = (G_IM_FMT.I, G_IM_SIZ._4b) + I8 = (G_IM_FMT.I, G_IM_SIZ._8b) + IA4 = (G_IM_FMT.IA, G_IM_SIZ._4b) + IA8 = (G_IM_FMT.IA, G_IM_SIZ._8b) + IA16 = (G_IM_FMT.IA, G_IM_SIZ._16b) + + def __init__(self, fmt: G_IM_FMT, siz: G_IM_SIZ): + self.fmt = fmt + self.siz = siz + + +@dataclasses.dataclass(eq=False) +class TextureResourceDesc(ResourceDesc): + format: TextureFormat + width: int + height: int + + +@dataclasses.dataclass(eq=False) +class CITextureResourceDesc(TextureResourceDesc): + tlut: TextureResourceDesc + + +def handler_Texture( + symbol_name, offset, collection: ResourcesDescCollection, reselem: Element +): + xml_errors.check_attrib( + reselem, + {"Name", "Offset", "Format", "Width", "Height"}, + # TODO remove OutName, SplitTlut + { + "OutName", + "SplitTlut", + "TlutOffset", + "ExternalTlut", + "ExternalTlutOffset", + "HackMode", + } + | STATIC_ATTRIB, + ) + format = TextureFormat[reselem.attrib["Format"].upper()] + width = int(reselem.attrib["Width"]) + height = int(reselem.attrib["Height"]) + if format.fmt == G_IM_FMT.CI: + res = CITextureResourceDesc( + symbol_name, offset, collection, reselem, format, width, height, None + ) + + if reselem.attrib.get("SplitTlut") == "true": + res.hack_modes.add("hackmode_split_tlut") + + assert ( + "TlutOffset" in reselem.attrib or "ExternalTlutOffset" in reselem.attrib + ), f"CI texture {symbol_name} is missing a tlut offset" + + if "TlutOffset" in reselem.attrib: + xml_errors.check_attrib( + reselem, + {"Name", "Offset", "Format", "Width", "Height", "TlutOffset"}, + # TODO remove OutName, SplitTlut + {"OutName", "SplitTlut", "HackMode"} | STATIC_ATTRIB, + ) + tlut_offset = int(reselem.attrib["TlutOffset"], 16) + + def pass2_callback(pool: ResourcesDescCollectionsPool): + matching_tlut_resources = [ + res for res in collection.resources if res.offset == tlut_offset + ] + assert len(matching_tlut_resources) == 1, ( + f"Found {len(matching_tlut_resources)} resources at TlutOffset " + f"0x{tlut_offset:X} instead of exactly one" + ) + assert isinstance( + matching_tlut_resources[0], TextureResourceDesc + ), matching_tlut_resources[0] + res.tlut = matching_tlut_resources[0] + + else: + xml_errors.check_attrib( + reselem, + { + "Name", + "Offset", + "Format", + "Width", + "Height", + "ExternalTlut", + "ExternalTlutOffset", + }, + # TODO remove OutName, SplitTlut + {"OutName", "SplitTlut", "HackMode"} | STATIC_ATTRIB, + ) + external_tlut_file = reselem.attrib["ExternalTlut"] + external_tlut_offset = int(reselem.attrib["ExternalTlutOffset"], 16) + + def pass2_callback(pool: ResourcesDescCollectionsPool): + matching_collections = [ + coll + for coll in pool.collections + if isinstance(coll.backing_memory, BaseromFileBackingMemory) + and coll.backing_memory.name == external_tlut_file + ] + assert len(matching_collections) == 1 + matching_tlut_resources = [ + res + for res in matching_collections[0].resources + if res.offset == external_tlut_offset + ] + assert len(matching_tlut_resources) == 1, matching_tlut_resources + assert isinstance( + matching_tlut_resources[0], TextureResourceDesc + ), matching_tlut_resources[0] + res.tlut = matching_tlut_resources[0] + + raise ResourceHandlerNeedsPass2Exception(res, pass2_callback) + else: + xml_errors.check_attrib( + reselem, + {"Name", "Offset", "Format", "Width", "Height"}, + # TODO remove OutName + {"OutName", "HackMode"} | STATIC_ATTRIB, + ) + res = TextureResourceDesc( + symbol_name, offset, collection, reselem, format, width, height + ) + if reselem.attrib.get("HackMode") == "ignore_orphaned_tlut": + res.hack_modes.add("hackmode_ignore_orphaned_tlut") + return res diff --git a/tools/assets/descriptor/spec.md b/tools/assets/descriptor/spec.md new file mode 100644 index 0000000000..c038a13f82 --- /dev/null +++ b/tools/assets/descriptor/spec.md @@ -0,0 +1,291 @@ +This document describes the expected structure of xml files describing assets. + +# Top elements + +## `Root` + +```xml + + ... + +``` + +This is the root element in the file, containing exclusively `` and `` elements as direct children. + +## `File` + +```xml + + ... + +``` + +A `` contains resources elements as children. + +- Required attributes: `Name` +- Optional attributes: `Segment` + +`Name` is the name of the baserom file from which the data is to be extracted. + +`Segment` (decimal) is the segment number for the file. + +## `ExternalFile` + +```xml + +``` + +Declare the ``s in the xml may reference symbols from an external file. + +The external file is located by matching its name against the list of assets in the version's `config.yml`. + +For example, `baseroms/gc-eu/config.yml` contains + +```yml +assets: +- name: objects/gameplay_keep + xml_path: assets/xml/objects/gameplay_keep_pal.xml +``` + +then `` refers to that gameplay_keep entry, which uses the `gameplay_keep_pal.xml` xml file when extracting assets for version gc-eu. + + +# Resource elements + +Resource elements describe resources. Resources are pieces of data corresponding to a symbol each. + +Two attributes are required on all resource elements: `Name` and `Offset`. + +- `Name` is the name of the symbol associated to the resource. +- `Offset` is the location in bytes from the start of the file data. + +## `Blob` + +```xml + +``` + +Unstructured binary data. + +- Required attributes: `Size` + +`Size` is the size of the binary blob in bytes. + +## `DList` + +```xml + +``` + +A display list. + +- Optional attributes: `Ucode`, `RawPointers` + +`Ucode` (defaults to `f3dex2`) picks the graphics microcode for which to disassemble the dlist. It may be `f3dex` or `f3dex2`. + +`RawPointers` (defaults to an empty value) is a comma-separated list of values the display list uses as raw pointers ("hex" instead of a symbol). The purpose of this attribute is to silence extraction warnings. + +## `Mtx` + +```xml + +``` + +A fixed-point matrix. + +## `Texture` + +```xml + + + +``` + +A texture, an image in one of the native N64 formats. + +- Required attributes for all formats: `Format`, `Width`, `Height` +- Required attributes for CI formats (`ci4`, `ci8`): `TlutOffset`, or `ExternalTlut` and `ExternalTlutOffset` + +`Format` is the format of the texture, one of `rgba32`, `rgba16`, `i4`, `i8`, `ia4`, `ia8`, `ia16`, `ci4` or `ci8`. + +`Width` and `Height` specify the dimensions of the texture. + +For CI formats, the TLUT (Texture Look Up Table, or palette) must be specified with either `TlutOffset` if the TLUT is in the same file as the texture, or both of `ExternalTlut` and `ExternalTlutOffset` if the TLUT is in a different file. `ExternalTlut` is the name of the baserom file where the TLUT is. In both cases, the TLUT must also be declared as a resource. + +## `Array` + +```xml + + + + + + + + + +``` + +An array of vertices, vectors or scalars. The child element determines the array's element type. + +- Required attributes: `Count` + +`Count` is the length of the array. + +The child element may be one of `` (for `Vtx[]`), `` (for `Vec3s[]`) or `` (for `s16[]`). + +## `Scene` + +```xml + +``` + +Scene commands. + +## `Room` + +```xml + +``` + +Room commands. + +## `Collision` + +```xml + +``` + +Collision header. + +## `Cutscene` + +```xml + +``` + +Cutscene script. + +## `Path` + +```xml + +``` + +Path list. + +- Required attributes: `NumPaths` + +`NumPaths` is the length of the path list. + +## `Skeleton` + +```xml + +``` + +Skeleton header. + +- Required attributes: `Type`, `LimbType` +- Optional attributes: `LimbNone`, `LimbMax`, `EnumName` + +`Type` is the type of the skeleton, one of `Normal`, `Flex` or `Curve`. + +`LimbType` is the type of limb used in the skeleton, one of `Standard`, `LOD`, `Skin`, `Curve` or `Legacy`. + +Not all skeleton types are compatible with all limb types: + +`LimbType` | Compatible skeleton `Type` +-----------|--------------------------- +`Standard` | `Normal`, `Flex` +`LOD` | `Normal`, `Flex` +`Skin` | `Normal` +`Curve` | `Curve` +`Legacy` | none + +`LimbNone`, `LimbMax`, `EnumName` can be set to override the corresponding names in the generated limb enum: + +```c +typedef enum NameLimb { + NAME_LIMB_NONE, + ... + NAME_LIMB_MAX +} NameLimb; +``` + +## `LimbTable` + +```xml + +``` + +Limb table. + +- Required attributes: `LimbType`, `Count` + +`LimbType` is one of `Standard`, `LOD`, `Skin`, `Curve` or `Legacy`. + +`Count` is the amount of limbs. + +## `Limb` + +```xml + +``` + +Limb of a skeleton. + +- Required attributes: `LimbType` +- Optional attributes: `EnumName` + +`LimbType` is one of `Standard`, `LOD`, `Skin`, `Curve` or `Legacy`. + +`EnumName` can be set to override the limb name in the generated limb enum. + +## `Animation` + +```xml + +``` + +Animation header. + +## `CurveAnimation` + +```xml + +``` + +Curve animation header. + +- Required attributes: `SkelOffset` + +`SkelOffset` is the offset of the skeleton which uses this animation. The skeleton must also be declared as a resource. + +## `LegacyAnimation` + +```xml + +``` + +Legacy animation header. + +## `PlayerAnimation` + +```xml + +``` + +Player animation header. + +## `PlayerAnimationData` + +```xml + +``` + +Player animation data. + +- Required attributes: `FrameCount` + +`FrameCount` is the amount of frames in the animation. diff --git a/tools/assets/descriptor/xml_errors.py b/tools/assets/descriptor/xml_errors.py new file mode 100644 index 0000000000..7d7f6e0197 --- /dev/null +++ b/tools/assets/descriptor/xml_errors.py @@ -0,0 +1,31 @@ +# SPDX-FileCopyrightText: © 2025 ZeldaRET +# SPDX-License-Identifier: CC0-1.0 + +from xml.etree import ElementTree + + +class XMLDescError(Exception): + pass + + +def check_attrib( + elem: ElementTree.Element, + required: set[str], + optional: set[str] = set(), +): + required_and_missing = required - elem.attrib.keys() + if required_and_missing: + raise XMLDescError( + "Missing attributes on " + + ElementTree.tostring(elem, encoding="unicode") + + ": " + + ", ".join(required_and_missing) + ) + unknown = elem.attrib.keys() - required - optional + if unknown: + raise XMLDescError( + "Unknown attributes on " + + ElementTree.tostring(elem, encoding="unicode") + + ": " + + ", ".join(unknown) + ) diff --git a/tools/assets/descriptor/z64resources.py b/tools/assets/descriptor/z64resources.py new file mode 100644 index 0000000000..fba264151f --- /dev/null +++ b/tools/assets/descriptor/z64resources.py @@ -0,0 +1,218 @@ +# SPDX-FileCopyrightText: © 2025 ZeldaRET +# SPDX-License-Identifier: CC0-1.0 + +import dataclasses +import enum +from typing import Optional +from xml.etree.ElementTree import Element + +from .base import ( + ResourceDesc, + ResourcesDescCollection, + ResourceHandlerNeedsPass2Exception, +) +from . import xml_errors + + +@dataclasses.dataclass(eq=False) +class CollisionResourceDesc(ResourceDesc): + pass + + +def handler_Collision(symbol_name, offset, collection, reselem: Element): + xml_errors.check_attrib(reselem, {"Name", "Offset"}) + return CollisionResourceDesc(symbol_name, offset, collection, reselem) + + +@dataclasses.dataclass(eq=False) +class AnimationResourceDesc(ResourceDesc): + pass + + +def handler_Animation(symbol_name, offset, collection, reselem: Element): + xml_errors.check_attrib(reselem, {"Name", "Offset"}) + return AnimationResourceDesc(symbol_name, offset, collection, reselem) + + +@dataclasses.dataclass(eq=False) +class PlayerAnimationResourceDesc(ResourceDesc): + pass + + +def handler_PlayerAnimation(symbol_name, offset, collection, reselem: Element): + xml_errors.check_attrib(reselem, {"Name", "Offset"}) + return PlayerAnimationResourceDesc(symbol_name, offset, collection, reselem) + + +@dataclasses.dataclass(eq=False) +class LegacyAnimationResourceDesc(ResourceDesc): + pass + + +def handler_LegacyAnimation(symbol_name, offset, collection, reselem: Element): + xml_errors.check_attrib(reselem, {"Name", "Offset"}) + return LegacyAnimationResourceDesc(symbol_name, offset, collection, reselem) + + +@dataclasses.dataclass(eq=False) +class CutsceneResourceDesc(ResourceDesc): + pass + + +def handler_Cutscene(symbol_name, offset, collection, reselem: Element): + xml_errors.check_attrib(reselem, {"Name", "Offset"}) + return CutsceneResourceDesc(symbol_name, offset, collection, reselem) + + +@dataclasses.dataclass(eq=False) +class SceneResourceDesc(ResourceDesc): + pass + + +def handler_Scene(symbol_name, offset, collection, reselem: Element): + xml_errors.check_attrib(reselem, {"Name", "Offset"}) + return SceneResourceDesc(symbol_name, offset, collection, reselem) + + +@dataclasses.dataclass(eq=False) +class RoomResourceDesc(ResourceDesc): + pass + + +def handler_Room(symbol_name, offset, collection, reselem: Element): + xml_errors.check_attrib(reselem, {"Name", "Offset"}, {"HackMode"}) + res = RoomResourceDesc(symbol_name, offset, collection, reselem) + if reselem.attrib.get("HackMode") == "syotes_room": + res.hack_modes.add("hackmode_syotes_room") + return res + + +@dataclasses.dataclass(eq=False) +class PlayerAnimationDataResourceDesc(ResourceDesc): + frame_count: int + + +def handler_PlayerAnimationData(symbol_name, offset, collection, reselem: Element): + xml_errors.check_attrib(reselem, {"Name", "Offset", "FrameCount"}) + frame_count = int(reselem.attrib["FrameCount"]) + return PlayerAnimationDataResourceDesc( + symbol_name, offset, collection, reselem, frame_count + ) + + +@dataclasses.dataclass(eq=False) +class PathListResourceDesc(ResourceDesc): + num_paths: int + + +def handler_PathList(symbol_name, offset, collection, reselem: Element): + xml_errors.check_attrib(reselem, {"Name", "Offset", "NumPaths"}) + num_paths = int(reselem.attrib["NumPaths"]) + return PathListResourceDesc(symbol_name, offset, collection, reselem, num_paths) + + +class SkeletonType(enum.Enum): + NORMAL = enum.auto() + FLEX = enum.auto() + CURVE = enum.auto() + + +class LimbType(enum.Enum): + STANDARD = enum.auto() + LOD = enum.auto() + SKIN = enum.auto() + CURVE = enum.auto() + LEGACY = enum.auto() + + +@dataclasses.dataclass(eq=False) +class SkeletonResourceDesc(ResourceDesc): + type: SkeletonType + limb_type: LimbType + limb_enum_name: Optional[str] + limb_enum_none_member_name: Optional[str] + limb_enum_max_member_name: Optional[str] + + +def handler_Skeleton(symbol_name, offset, collection, reselem: Element): + xml_errors.check_attrib( + reselem, + {"Name", "Offset", "Type", "LimbType"}, + {"EnumName", "LimbNone", "LimbMax"}, + ) + skel_type = SkeletonType[reselem.attrib["Type"].upper()] + limb_type = LimbType[reselem.attrib["LimbType"].upper()] + return SkeletonResourceDesc( + symbol_name, + offset, + collection, + reselem, + skel_type, + limb_type, + reselem.attrib.get("EnumName"), + reselem.attrib.get("LimbNone"), + reselem.attrib.get("LimbMax"), + ) + + +@dataclasses.dataclass(eq=False) +class LimbResourceDesc(ResourceDesc): + limb_type: LimbType + limb_enum_member_name: Optional[str] + + +def handler_Limb(symbol_name, offset, collection, reselem: Element): + xml_errors.check_attrib(reselem, {"Name", "Offset", "LimbType"}, {"EnumName"}) + limb_type = LimbType[reselem.attrib["LimbType"].upper()] + return LimbResourceDesc( + symbol_name, + offset, + collection, + reselem, + limb_type, + reselem.attrib.get("EnumName"), + ) + + +@dataclasses.dataclass(eq=False) +class LimbTableResourceDesc(ResourceDesc): + limb_type: LimbType + count: int + + +def handler_LimbTable(symbol_name, offset, collection, reselem: Element): + xml_errors.check_attrib(reselem, {"Name", "Offset", "LimbType", "Count"}) + limb_type = LimbType[reselem.attrib["LimbType"].upper()] + count = int(reselem.attrib["Count"]) + return LimbTableResourceDesc( + symbol_name, offset, collection, reselem, limb_type, count + ) + + +@dataclasses.dataclass(eq=False) +class CurveAnimationResourceDesc(ResourceDesc): + skeleton: SkeletonResourceDesc + + +def handler_CurveAnimation( + symbol_name, offset, collection: ResourcesDescCollection, reselem: Element +): + xml_errors.check_attrib(reselem, {"Name", "Offset", "SkelOffset"}) + res = CurveAnimationResourceDesc(symbol_name, offset, collection, reselem, None) + + skel_offset = int(reselem.attrib["SkelOffset"], 16) + + def pass2_callback(pool): + matching_tlut_resources = [ + res for res in collection.resources if res.offset == skel_offset + ] + assert len(matching_tlut_resources) == 1, ( + f"Found {len(matching_tlut_resources)} resources at SkelOffset " + f"0x{skel_offset:X} instead of exactly one" + ) + assert isinstance( + matching_tlut_resources[0], SkeletonResourceDesc + ), matching_tlut_resources[0] + res.skeleton = matching_tlut_resources[0] + + raise ResourceHandlerNeedsPass2Exception(res, pass2_callback) diff --git a/tools/assets/extract/__main__.py b/tools/assets/extract/__main__.py new file mode 100644 index 0000000000..62676350b5 --- /dev/null +++ b/tools/assets/extract/__main__.py @@ -0,0 +1,13 @@ +# SPDX-FileCopyrightText: © 2025 ZeldaRET +# SPDX-License-Identifier: CC0-1.0 + +from . import extract_xml_z64 + +if __name__ == "__main__": + profile = False + if profile: + import cProfile + + cProfile.run("extract_xml_z64.main()", "cprofile_extract_assets.txt") + else: + extract_xml_z64.main() diff --git a/tools/assets/extract/extase/__init__.py b/tools/assets/extract/extase/__init__.py new file mode 100644 index 0000000000..a40c9765c2 --- /dev/null +++ b/tools/assets/extract/extase/__init__.py @@ -0,0 +1,1110 @@ +# SPDX-FileCopyrightText: © 2025 ZeldaRET +# SPDX-License-Identifier: CC0-1.0 + +from pathlib import Path +import abc +from dataclasses import dataclass +import enum +import reprlib + +import io +from typing import TYPE_CHECKING, Sequence, Optional, Union, Any, Iterable + +from pprint import pprint + +if TYPE_CHECKING: + from .memorymap import MemoryContext + + +# 0: nothing, 1: in progress & waiting, 2: all +VERBOSE_FILE_TRY_PARSE_DATA = 0 +VERBOSE_REPORT_RESBUF = False + +# +# file +# + +# sentinel value +RESOURCE_PARSE_SUCCESS = object() + + +class ResourceParseException(Exception): + pass + + +class ResourceParseWaiting(ResourceParseException): + """Resource has nothing to do and can't be parsed yet, try again later. + + For example, another resource may need to be parsed first. + + If all resources fail to parse in this way, it means parsing has come to a deadlock. + """ + + def __init__(self, *args, waiting_for: list[Any]): + """ + waiting_for should be a non-empty list of things the resource is currently waiting for. + (one item per meaningful thing that is waited for) + It is only meant for informational purpose (such as debugging). + It may contain more than the strict minimum the resource needs to make some progress, + and less than everything the resource needs to be fully parsed. + """ + assert waiting_for + super().__init__(*args, waiting_for) + self.waiting_for = waiting_for + + +class ResourceParseInProgress(ResourceParseException): + """Resource can't be parsed yet, try again later. + But there was progress (as opposed to ResourceParseWaiting indicating no progress). + + "Progress" includes: + - other resources were reported + - information was passed to or made available to other resources + - data was partially parsed + """ + + def __init__(self, *args, new_progress_done: list[Any], waiting_for: list[Any]): + """ + new_progress_done, waiting_for: see ResourceParseWaiting.__init__ + """ + assert new_progress_done and waiting_for + super().__init__(*args, new_progress_done, waiting_for) + self.new_progress_done = new_progress_done + self.waiting_for = waiting_for + + +class ResourceParseImpossible(ResourceParseException): + """Resource cannot be parsed, neither now nor later. + + For example, there is unexpected data or values that cannot be handled properly. + """ + + pass + + +class GetResourceAtResult(enum.Enum): + DEFINITIVE = enum.auto() + PERHAPS = enum.auto() + NONE_YET = enum.auto() + + +@dataclass +class ResourceBufferMarker: + name: str + file_start: int + file_end: int + users: set["Resource"] + + +@dataclass +class ResourcesOverlapError(Exception): + overlaps: list[tuple["Resource", "Resource"]] + + +class File: + """A file is a collection of resources + + It typically corresponds to a rom file (segment) but doesn't have to + It doesn't even need to correspond to the entirety of one or more .c files, + it can be only a fraction + + It can also correspond to how some memory is laid out, + for example what a segment "contains" in the context of a file or resource. + """ + + def __init__( + self, + name: str, + *, + data: Optional[memoryview] = None, + size: Optional[int] = None, + alignment: int = 8, + ): + self.name = name + if data is None != size is None: + raise Exception( + "Exactly one of either data or size must be provided", data, size + ) + if data is not None: + self.data = data + self.size = len(data) + else: + assert size is not None + self.data = None + self.size = size + self.alignment = alignment + self._resources: list[Resource] = [] + self._is_resources_sorted = True + self.referenced_files: set[File] = set() + self.resource_buffer_markers_by_resource_type: dict[ + type[Resource], list[ResourceBufferMarker] + ] = dict() + + def add_resource(self, resource: "Resource"): + assert resource is not None + assert resource not in self._resources + self._resources.append(resource) + self._is_resources_sorted = False + + def extend_resources(self, resources: Sequence["Resource"]): + self._resources.extend(resources) + self._is_resources_sorted = False + + def sort_resources(self): + self._resources.sort(key=lambda resource: resource.range_start) + self._is_resources_sorted = True + + def get_resource_at(self, offset: int): + if __debug__: + # FIXME when resources overlap during parse, nothing catches that + # (and nothing can really catch it because of the unk-size resources) + # probably implement this check properly by finding all resources at the offset below, + # hopefully there is at most one and do normal operation, + # or if there are >=2 then error (or best_effort: pick the furthest resource?) + self.sort_resources() + self.check_overlapping_resources() + assert offset < self.size + + # Resources may use a defined range with both start and end defined, + # or a range that only has its start defined. + + # While looking for a resource with a defined range the request offset + # belongs to, also keep track of the last resource that starts at or before + # offset (note: that resource may or may not have an end range defined). + last_resource_before_offset: Union[Resource, None] = None + + for resource in self._resources: + + if resource.range_start <= offset: + if ( + last_resource_before_offset is None + or last_resource_before_offset.range_start < resource.range_start + ): + last_resource_before_offset = resource + + if resource.range_end is not None: + # If the requested offset falls within a defined range, return that + # resource with GetResourceAtResult.DEFINITIVE . + if resource.range_start <= offset < resource.range_end: + return GetResourceAtResult.DEFINITIVE, resource + + # If the loop exits normally, without returning a defined range resource, + # check if the last resource starting at or before the requested offset + # (if any) has an undefined range. + if ( + last_resource_before_offset is not None + and last_resource_before_offset.range_end is None + ): + if last_resource_before_offset.range_start == offset: + # Resources are always more than 0 bytes in size, so if the resource + # starts exactly at the requested offset, then it is guaranteed to + # cover (at least) that offset. + return GetResourceAtResult.DEFINITIVE, last_resource_before_offset + else: + # Return it with GetResourceAtResult.PERHAPS , as it may extend up to + # and beyond the requested offset (or not). + return GetResourceAtResult.PERHAPS, last_resource_before_offset + else: + # No (potential) resource at that offset (currently). + return GetResourceAtResult.NONE_YET, None + + def get_overlapping_resources(self): + if not self._is_resources_sorted: + raise Exception("sort resources first") + + overlaps: list[tuple[Resource, Resource]] = [] + + for i in range(1, len(self._resources)): + resource_a = self._resources[i - 1] + + if resource_a.range_end is not None: + for j in range(i, len(self._resources)): + resource_b = self._resources[j] + + # This should hold true, as resources are sorted + assert resource_a.range_start <= resource_b.range_start + + if resource_a.range_end > resource_b.range_start: + overlaps.append((resource_a, resource_b)) + else: + break + else: + for j in range(i, len(self._resources)): + resource_b = self._resources[j] + + assert resource_a.range_start <= resource_b.range_start + + if resource_a.range_start == resource_b.range_start: + overlaps.append((resource_a, resource_b)) + else: + break + + return overlaps + + def check_overlapping_resources(self): + try: + overlaps = self.get_overlapping_resources() + if overlaps: + raise ResourcesOverlapError(overlaps) + except: + print(self.str_report()) + raise + + def get_non_parsed_resources(self): + return [resource for resource in self._resources if not resource.is_data_parsed] + + def check_non_parsed_resources(self): + try: + resources_data_not_parsed = self.get_non_parsed_resources() + if resources_data_not_parsed: + print(len(resources_data_not_parsed), "resource(s) not parsed:") + for resource in resources_data_not_parsed: + print(resource) + if hasattr(resource, "last_parse_waiting_e"): + print( + " last_parse_waiting_e =", + repr(resource.last_parse_waiting_e), + ) + else: + print("??? no last_parse_waiting_e ???") + print("then why has", resource.name, "not been parsed?") + BEST_EFFORT = False # TODO move + if BEST_EFFORT: + print("BEST_EFFORT: removing non-parsed resources") + for resource in resources_data_not_parsed: + self._resources.remove(resource) + self.add_resource( + BinaryBlobResource( + self, + resource.range_start, + ( + resource.range_end + if resource.range_end is not None + else ( + resource.range_start + + 4 # TODO 4 if I_D_OMEGALUL else 1 + ) + ), + f"{resource.name}_bin_placeholder", + ) + ) + return + raise Exception( + "resources not parsed", + len(resources_data_not_parsed), + [(r.name, r.__class__) for r in resources_data_not_parsed], + resources_data_not_parsed, + ) + except: + print(self.str_report()) + raise + + def try_parse_resources_data(self, file_memory_context: "MemoryContext"): + """Returns true if any progress was made between the method being called and the method returning.""" + any_progress = False + + while True: + any_data_parsed = False + + # Parsing resources may add more, copy the list + # to avoid concurrent modification while iterating + resources_copy = self._resources.copy() + + for resource in resources_copy: + if resource.is_data_parsed: + pass + else: + resource.last_parse_waiting_e = None + resource_memory_context = file_memory_context # TODO + try: + ret_try_parse_data = resource.try_parse_data( + resource_memory_context + ) + except ResourceParseInProgress as e: + any_progress = True + if VERBOSE_FILE_TRY_PARSE_DATA >= 1: + pprint( + ( + "(in progress) Defering parsing", + resource, + "progress:", + e.new_progress_done, + "waiting:", + e.waiting_for, + ) + ) + except ResourceParseWaiting as e: + if VERBOSE_FILE_TRY_PARSE_DATA >= 1: + pprint( + ( + "(waiting) Defering parsing", + resource, + "waiting:", + e.waiting_for, + ) + ) + resource.last_parse_waiting_e = e + except ( + ResourceParseException + ) as e: # TODO ResourceParseImpossible ? + # TODO replace resource with binblob or something idk + print("Error while attempting to parse data", resource) + raise + except: + # TODO replace resource with binblob or something idk + print("Error while attempting to parse data", resource) + raise + else: + # Catch try_parse_data mistakenly returning successfully + # (instead of raising) by enforcing having it return a sentinel value + assert ret_try_parse_data is RESOURCE_PARSE_SUCCESS, ( + "Resources should return RESOURCE_PARSE_SUCCESS when parsing is successful, " + "or raise ResourceParseInProgress/ResourceParseWaiting if parsing is unsuccessful", + resource, + resource.try_parse_data, + ) + + # resource parsed successfully + if VERBOSE_FILE_TRY_PARSE_DATA >= 2: + pprint(("(success) Done parsing", resource)) + any_progress = True + assert resource.range_end is not None, ( + resource, + resource.__class__, + ) + resource.is_data_parsed = True + any_data_parsed = True + + any_resource_added = len(self._resources) != len(resources_copy) + keep_looping = any_data_parsed or any_resource_added + if not keep_looping: + break + + return any_progress + + def mark_resource_buffer( + self, + reporter: "Resource", + resource_type: type["Resource"], + name: str, + file_start: int, + file_end: int, + ): + # Ignore markers falling within existing resources + result, resource = self.get_resource_at(file_start) + if result == GetResourceAtResult.DEFINITIVE: + if resource.range_start <= file_start < file_end <= resource.range_end: + assert isinstance(resource, resource_type) + resource.reporters.add(reporter) + return + + # Check for intersection with existing resources + for resource in self._resources: + # TODO and when resource.range_end is None ? + if resource.range_end is not None and ( + resource.range_start <= file_start < resource.range_end + or resource.range_start < file_end <= resource.range_end + ): + raise Exception( + f"Resource buffer {name=} of {resource_type=}" + f" to be marked at {file_start:#X}-{file_end:#X}" + f" intersects with existing {resource=}" + ) + + resource_buffer_markers = ( + self.resource_buffer_markers_by_resource_type.setdefault(resource_type, []) + ) + resource_buffer_markers.append( + ResourceBufferMarker(name, file_start, file_end, {reporter}) + ) + + resource_buffer_markers.sort(key=lambda rbm: rbm.file_start) + + def do_fuse(i_start, i_end): + assert i_start < i_end + if i_start + 1 == i_end: + return False + fused = resource_buffer_markers[i_start:i_end] + users = set() + for rbm in fused: + users.update(rbm.users) + resource_buffer_markers[i_start:i_end] = [ + ResourceBufferMarker( + fused[0].name.removesuffix("_fused_") + "_fused_", # TODO + fused[0].file_start, + fused[-1].file_end, + users, + ) + ] + return True + + def fuse_more(): + stride_first_i = None + for i, rbm in enumerate(resource_buffer_markers): + if stride_first_i is None: + stride_first_i = i + else: + assert i > 0 + prev = resource_buffer_markers[i - 1] + if prev.file_end < rbm.file_start: + # disjointed + if do_fuse(stride_first_i, i): + return True + stride_first_i = i + if stride_first_i is not None: + return do_fuse(stride_first_i, len(resource_buffer_markers)) + else: + return False + + while fuse_more(): + pass + + def commit_resource_buffers(self): + # TODO rework resource buffers handling + # this won't play well with manually defined vtx arrays + # probably can't merge the vbuf refs so quick + for ( + resource_type, + resource_buffer_markers, + ) in self.resource_buffer_markers_by_resource_type.items(): + if VERBOSE_REPORT_RESBUF: + print(resource_type, resource_buffer_markers) + for rbm in resource_buffer_markers: + result, resource = self.get_resource_at(rbm.file_start) + assert ( + result != GetResourceAtResult.PERHAPS + ), "commit_resource_buffers should be called at a point where all resources have a definitive range" + if result == GetResourceAtResult.NONE_YET: + resource = resource_type( + self, rbm.file_start, rbm.file_end, rbm.name + ) + resource.reporters.update(rbm.users) + self.add_resource(resource) + else: + assert result == GetResourceAtResult.DEFINITIVE + assert ( + resource.range_start + <= rbm.file_start + < rbm.file_end + <= resource.range_end + ), ( + "marked resource buffer overlaps with existing resource but also extends out of that resource", + hex(rbm.file_start), + hex(rbm.file_end), + rbm, + resource, + ) + + # TODO ? not really reporters but at least users, figure out reporters/users + resource.reporters.update(rbm.users) + self.resource_buffer_markers_by_resource_type = dict() + + def add_unaccounted_resources(self, *, I_D_OMEGALUL: bool): + assert self._is_resources_sorted + assert self.data is not None + + unaccounted_resources: list[Resource] = [] + + def add_unaccounted(range_start, range_end): + if I_D_OMEGALUL: + # IDO aligns every declaration to 4, so declaring zeros + # that is actually padding for that purpose throws off matching. + # This block strips such zeros from the unaccounted range. + + # Compute the amount of bytes from range_start to the + # next multiple of 4. + pad_bytes = (4 - range_start % 4) % 4 + if pad_bytes != 0: + pad_range_end = range_start + pad_bytes + assert pad_range_end <= range_end + pad_data = self.data[range_start:pad_range_end] + if set(pad_data) != {0}: + raise Exception( + "Expected pad bytes to be 0", + hex(range_start), + hex(pad_range_end), + set(pad_data), + bytes(pad_data), + ) + pad_resource = ZeroPaddingResource( + self, + range_start, + pad_range_end, + f"{self.name}_zero_padding_{range_start:06X}", + include_in_source=False, + ) + unaccounted_resources.append(pad_resource) + range_start += pad_bytes + if range_start == range_end: + # It turns out the whole unaccounted range is + # zero padding, so do nothing else + return + assert range_start < range_end + unaccounted_data = self.data[range_start:range_end] + if set(unaccounted_data) == {0}: + unaccounted_resource = ZeroPaddingResource( + self, + range_start, + range_end, + f"{self.name}_zeros_{range_start:06X}", + ) + else: + unaccounted_resource = BinaryBlobResource( + self, + range_start, + range_end, + f"{self.name}_unaccounted_{range_start:06X}", + ) + unaccounted_resources.append(unaccounted_resource) + + if self._resources: + # Add unaccounted if needed at the start of the file + resource_first = self._resources[0] + if resource_first.range_start > 0: + add_unaccounted( + 0, + resource_first.range_start, + ) + + # Add unaccounted if needed at the end of the file + resource_last = self._resources[-1] + if resource_last.range_end < len(self.data): + add_unaccounted( + resource_last.range_end, + len(self.data), + ) + else: + # Add unaccounted for the whole file + add_unaccounted(0, len(self.data)) + + for i in range(1, len(self._resources)): + resource_a = self._resources[i - 1] + resource_b = self._resources[i] + assert resource_a.range_end <= resource_b.range_start + + # Add unaccounted if needed between two successive resources + if resource_a.range_end < resource_b.range_start: + try: + add_unaccounted( + resource_a.range_end, + resource_b.range_start, + ) + except: + print( + "Could not add an unaccounted resource between the two resources:" + ) + print(resource_a) + print(resource_b) + raise + + self.extend_resources(unaccounted_resources) + + def set_resources_paths(self, extracted_path, build_path, out_path): + for resource in self._resources: + resource.set_paths(extracted_path, build_path, out_path) + + def write_resources_extracted(self, file_memory_context: "MemoryContext"): + for resource in self._resources: + assert resource.is_data_parsed, resource + resource_memory_context = file_memory_context # TODO + try: + resource.extract_to_path.parent.mkdir(parents=True, exist_ok=True) + resource.write_extracted(resource_memory_context) + except: + print("Couldn't write extracted resource", resource) + raise + + # These two are set by calling set_source_path + source_c_path: Path + source_h_path: Path + + def set_source_path(self, source_path: Path): + file_name = self.name + + # May catch random problems but not a hard requirement otherwise + assert file_name and all( + (c in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_0123456789") + for c in file_name + ), file_name + + self.source_file_name = file_name + self.source_c_path = source_path / f"{file_name}.c" + self.source_h_path = source_path / f"{file_name}.h" + + def write_source(self): + assert hasattr( + self, "source_c_path" + ), "set_source_path must be called before write_source" + assert hasattr(self, "source_h_path") + self.source_c_path.parent.mkdir(parents=True, exist_ok=True) + self.source_h_path.parent.mkdir(parents=True, exist_ok=True) + with self.source_c_path.open("w") as c: + with self.source_h_path.open("w") as h: + + # Paths to files to be included + file_include_paths_complete: list[Path] = [] + file_include_paths_complete.append(self.source_h_path) + for referenced_file in self.referenced_files: + assert isinstance(referenced_file, File), referenced_file + assert hasattr(referenced_file, "source_c_path"), ( + "set_source_path must be called on all files before any write_source call", + referenced_file, + ) + assert hasattr(referenced_file, "source_h_path") + file_include_paths_complete.append(referenced_file.source_h_path) + + # Same as file_include_paths_complete, + # but paths that can be are made relative to the source C. + file_include_paths: list[Path] = [] + for path_complete in file_include_paths_complete: + try: + path = path_complete.relative_to(self.source_c_path.parent) + except ValueError: + # Included path is not relative to this file's source C folder. + # Just use the complete path. + path = path_complete + file_include_paths.append(path) + + included_headers_in_c = set() + included_headers_in_h = set() + + for resource in self._resources: + incls = resource.get_c_includes() + assert not isinstance(incls, str) + included_headers_in_c.update(incls) + + incls = resource.get_h_includes() + assert not isinstance(incls, str) + included_headers_in_h.update(incls) + + for file_include_path in file_include_paths: + c.write(f'#include "{file_include_path}"\n') + c.write("\n") + c.writelines( + f'#include "{_h}"\n' for _h in sorted(included_headers_in_c) + ) + c.write("\n") + + INCLUDE_GUARD = self.source_file_name.upper() + "_H" + + h.writelines( + ( + f"#ifndef {INCLUDE_GUARD}\n", + f"#define {INCLUDE_GUARD}\n", + "\n", + ) + ) + h.writelines( + f'#include "{_h}"\n' for _h in sorted(included_headers_in_h) + ) + h.write("\n") + + if not self._is_resources_sorted: + self.sort_resources() + for resource in self._resources: + + if resource.write_c_definition(c): + c.write("\n") + + resource.write_c_declaration(h) + + h.writelines( + ( + "\n", + "#endif\n", + ) + ) + + def str_report(self): + return "\n".join( + f"0x{resource.range_start:06X}-" + + ( + f"0x{resource.range_end:06X}" + if resource.range_end is not None + else "..." + ) + + f" {resource.name}" + for resource in self._resources + ) + + @reprlib.recursive_repr() + def __repr__(self): + return ( + self.__class__.__qualname__ + + f"({self.name!r}, data is None={self.data is None}, size={self.size}, {self._resources!r})" + ) + + def __rich_repr__(self): + yield "name", self.name + yield "data is None", self.data is None + yield "size", self.size + yield "resources", self._resources + + __rich_repr__.angular = True + + +# +# resources +# + + +class Resource(abc.ABC): + """A resource is a blob of data inside a file. + + (at least for now,) one resource = one symbol + + Examples: + - a struct-defined piece of data, such as a SkeletonHeader + - an array of data, such as a display list Gfx[], or a texture u64[] + """ + + braces_in_source = True + + def __init_subclass__(cls, /, can_size_be_unknown=False, **kwargs): + super().__init_subclass__(**kwargs) + cls.can_size_be_unknown = can_size_be_unknown + + def __init__( + self, + file: File, + range_start: int, + range_end: Optional[int], + name: str, + ): + assert ( + 0 <= range_start < file.size + ), f"{range_start=:#08X} out of range [0,{file.size=:#08X})" + if range_end is None: + assert self.can_size_be_unknown + else: + assert ( + range_start < range_end <= file.size + ), f"{range_end=:#08X} out of range [{range_start=:#08X},{file.size=:#08X})" + + self.file = file + + self.range_start = range_start + """Offset in the file data this resource starts at (inclusive) + + Example: + range_start = 1 and range_end = 3 + means the resource is two bytes, the second and third bytes in the file + """ + + self.range_end = range_end + """Offset in the file data this resource end at (exclusive) + + May be None if the resource size isn't known yet + (only if can_size_be_unknown is True, see __init_subclass__) + Must be set at the latest before try_parse_data returns normally (without raising) + + See range_start + """ + + self.name = name + """Name of this resource, for logging/reporting. + + This member is NOT to be used as a C identifier, symbol name or file name. + + See also: + - symbol_name + - get_filename_stem + """ + + self.symbol_name = name + """Name of the symbol to use to reference this resource""" + + self.is_data_parsed = False + """Will be set to true when the resource is successfully parsed + (after a successful try_parse_data call) + """ + + self.reporters: set[Resource] = set() + """Collection of all the resources having reported this resource + TODO figure out what to do with this, for now thinking debugging""" + + @abc.abstractmethod + def try_parse_data(self, memory_context: "MemoryContext"): + """Parse this resource's data bytes + + This can typically result in finding more resources, + for example from pointer types. + + If data can't be parsed yet, ResourceParseInProgress or ResourceParseWaiting should be raised. + Then this will be called again later. + + Raising other ResourceParseException s abandons parsing this resource. + Other exceptions raised are not caught. + + Note this can both add found resources to the file, + and wait before further parsing its own data (by raising ResourceParseInProgress). + + If data is successfully parsed, the method should return normally + and RESOURCE_PARSE_SUCCESS should be returned. + Then this will not be called again. + """ + ... + + @abc.abstractmethod + def get_c_reference(self, resource_offset: int) -> str: + """Get a C expression for referencing data in this resource (as a pointer) + + The offset `resource_offset` is relative to the resource: + 0 means the start of the resource data, + and NOT the start of the file the resource is in. + + Should raise `ValueError` if the `resource_offset` isn't meaningful. + + Examples: + - `StructData data`, `get_c_reference(0)` -> `&data` + - `u8 array[]`, `get_c_reference(0)` -> `&array[0]` + - `u8 array[]`, `get_c_reference(6)` -> `&array[6]` + - `u16 array[]`, `get_c_reference(6)` -> `&array[3]` + - `u16 array[]`, `get_c_reference(1)` -> raises `ValueError` + - `u64 texture[]`, `get_c_reference(0)` -> `texture` + """ + ... + + def get_c_expression_length(self, resource_offset: int): + """Get a C expression for referencing the length of data in this resource + + The offset `resource_offset` is relative to the resource, as in get_c_reference. + + Should raise `ValueError` if the `resource_offset` isn't meaningful. + + Examples: + - `StructData data`, `get_c_expression_length(0)` -> raises `ValueError` + - `u8 array[]`, `get_c_reference(0)` -> `ARRAY_COUNT(array)` + - `u8 array[]`, `get_c_reference(1)` -> raises `ValueError` + """ + # Override in children classes if needed + raise ValueError( + "This resource has no data with a length that can be referenced", + self.__class__, + self, + ) + + needs_build = False + """Whether this resource needs processing by the build system. + + If False, it is extracted directly as .inc.c and included as is. + + See set_paths + """ + + extracted_path_suffix = ".inc.c" + """The file extension for constructing the path to extract this resource to. + + See set_paths + """ + + def get_filename_stem(self): + """Stem (name without suffix) for the file to write this resource to + + See set_paths + """ + return self.name + + # These two are set by calling set_paths + extract_to_path: Path + inc_c_path: Path + + def set_paths(self, extracted_path: Path, build_path: Path, out_path: Path): + """Compute and set `self.extract_to_path` and `self.inc_c_path` + + Examples with + extracted_path: `extracted/VERSION/` + build_path: `build/VERSION/` + out_path: `assets/.../` + + Binary: extracted_path_suffix = ".bin" + with get_filename_stem() = "blob" + extract_to_path: `extracted/VERSION/assets/.../blob.bin` + inc_c_path: `assets/.../blob.inc.c` + + C: extracted_path_suffix = ".inc.c" + with get_filename_stem() = "data" + extract_to_path: `extracted/VERSION/assets/.../data.inc.c` + inc_c_path: `assets/.../data.inc.c` + + rgba16 image: extracted_path_suffix = ".png" + with get_filename_stem() = "img.rgba16" + extract_to_path: `extracted/VERSION/assets/.../img.rgba16.png` + inc_c_path: `assets/.../img.rgba16.inc.c` + """ + + filename_stem = self.get_filename_stem() + + extract_to_path = ( + extracted_path / out_path / (filename_stem + self.extracted_path_suffix) + ) + + if not self.needs_build: + assert self.extracted_path_suffix == ".inc.c" + inc_c_path = out_path / (filename_stem + ".inc.c") + + self.extract_to_path = extract_to_path + self.inc_c_path = inc_c_path + + def get_c_includes(self) -> Iterable[str]: + return () + + def get_h_includes(self) -> Iterable[str]: + return () + + @abc.abstractmethod + def write_extracted(self, memory_context: "MemoryContext") -> None: + """Write the extracted resource data to self.extract_to_path""" + ... + + @abc.abstractmethod + def get_c_declaration_base(self) -> str: + """Get the base source for declaring this resource's symbol in C. + + For example: + - "u8 blob[]", `return f"u8 {self.symbol_name}[]"` + - "DataStruct data", `return f"DataStruct {self.symbol_name}"` + """ + ... + + def write_c_definition(self, c: io.TextIOBase) -> bool: + """ + Returns True if something was written + """ + + if hasattr(self, "HACK_IS_STATIC_ON"): + c.write("static ") + c.write(self.get_c_declaration_base()) + if self.braces_in_source: + c.write(" = {\n") + else: + c.write(" =\n") + + c.write(f'#include "{self.inc_c_path}"\n') + if self.braces_in_source: + c.write("};\n") + else: + c.write(";\n") + + return True + + def write_c_declaration(self, h: io.TextIOBase) -> None: + + if hasattr(self, "HACK_IS_STATIC_ON"): + h.write("static ") + else: + h.write("extern ") + h.write(self.get_c_declaration_base()) + h.write(";\n") + + @reprlib.recursive_repr() + def __repr__(self): + return ( + self.__class__.__qualname__ + + "(" + + ", ".join( + ( + repr(self.name), + ( + f"0x{self.range_start:08X}-" + + ( + f"0x{self.range_end:08X}" + if self.range_end is not None + else "..." + ) + ), + f"file.name={self.file.name!r}", + ) + ) + + ")" + ) + + def __rich_repr__(self): + yield self.name + yield ( + f"0x{self.range_start:08X}-" + + (f"0x{self.range_end:08X}" if self.range_end is not None else "...") + ) + yield "file.name", self.file.name + + __rich_repr__.angular = True + + +class ZeroPaddingResource(Resource): + def __init__( + self, + file: File, + range_start: int, + range_end: int, + name: str, + *, + include_in_source=True, + ): + # TODO move to try_parse_data ? + assert set(file.data[range_start:range_end]) == {0} + super().__init__(file, range_start, range_end, name) + self.include_in_source = include_in_source + + def try_parse_data(self, memory_context): + # Nothing specific to do + return RESOURCE_PARSE_SUCCESS + + def get_c_reference(self, resource_offset): + raise ValueError("Referencing zero padding should not happen") + + def get_c_includes(self): + return ("ultra64.h",) + + def write_extracted(self, memory_context): + # No need to extract zeros + pass + + def get_c_declaration_base(self): + length_bytes = self.range_end - self.range_start + assert length_bytes > 0 + return f"u8 {self.symbol_name}[{length_bytes}]" + + def write_c_definition(self, c: io.TextIOBase): + if self.include_in_source: + c.write(self.get_c_declaration_base()) + c.write(" = { 0 };\n") + return True + else: + return False + + def write_c_declaration(self, h: io.TextIOBase): + # No need to declare zeros + pass + + +class BinaryBlobResource(Resource): + needs_build = True + extracted_path_suffix = ".bin" + + def try_parse_data(self, memory_context): + # Nothing specific to do + return RESOURCE_PARSE_SUCCESS + + def get_c_reference(self, resource_offset): + return f"&{self.symbol_name}[{resource_offset}]" + + def get_filename_stem(self): + return super().get_filename_stem() + ".u8" + + def get_h_includes(self): + return ("ultra64.h",) + + def write_extracted(self, memory_context): + data = self.file.data[self.range_start : self.range_end] + assert len(data) == self.range_end - self.range_start + self.extract_to_path.write_bytes(data) + + def get_c_declaration_base(self): + return f"u8 {self.symbol_name}[]" + + def get_c_expression_length(self, resource_offset: int): + raise Exception( + "A binary blob resource could support returning a C expression for its length, " + "but it would be error-prone due to the 'anything goes' nature of binary blobs. " + "Make a dedicated resource instead" + ) diff --git a/tools/assets/extract/extase/cdata_resources.py b/tools/assets/extract/extase/cdata_resources.py new file mode 100644 index 0000000000..467d39897a --- /dev/null +++ b/tools/assets/extract/extase/cdata_resources.py @@ -0,0 +1,499 @@ +# SPDX-FileCopyrightText: © 2025 ZeldaRET +# SPDX-License-Identifier: CC0-1.0 + +import abc +import dataclasses +import io +from typing import TYPE_CHECKING, Callable, Any, Sequence, Union + +if TYPE_CHECKING: + from .memorymap import MemoryContext + +from . import ( + RESOURCE_PARSE_SUCCESS, + Resource, + File, + ResourceParseWaiting, +) + +from .repr_c_struct import ( + CData, + CData_Value, + CData_Struct, + CData_Array, +) + + +@dataclasses.dataclass +class CDataExtWriteContext: + f: io.TextIOBase + line_prefix: str + inhibit_top_braces: bool + + +class CDataExt(CData, abc.ABC): + + report_f = None + write_f = None + + def set_report( + self, report_f: Callable[["CDataResource", "MemoryContext", Any], None] + ): + self.report_f = report_f + return self + + def set_write( + self, + write_f: Callable[ + ["CDataResource", "MemoryContext", Any, CDataExtWriteContext], + bool, + ], + ): + """ + write_f should return True if it wrote anything + """ + self.write_f = write_f + return self + + def freeze(self): + self.set_report = None + self.set_write = None + return self + + @abc.abstractmethod + def write_default( + self, + resource: "CDataResource", + memory_context: "MemoryContext", + v: Any, + f: io.TextIOBase, + line_prefix: str, + *, + inhibit_top_braces: bool, + ) -> bool: ... + + def report( + self, + resource: "CDataResource", + memory_context: "MemoryContext", + v: Any, + ): + if self.report_f: + try: + self.report_f(resource, memory_context, v) + except: + print("Error reporting data", self, self.report_f, resource, v) + raise + + def write( + self, + resource: "CDataResource", + memory_context: "MemoryContext", + v: Any, + f: io.TextIOBase, + line_prefix: str, + *, + inhibit_top_braces: bool, + ) -> bool: + """ + Returns True if something has been written + (typically, False will be returned if this data is struct padding) + """ + if self.write_f: + ret = self.write_f( + resource, + memory_context, + v, + CDataExtWriteContext(f, line_prefix, inhibit_top_braces), + ) + # This assert is meant to ensure the function returns a value at all, + # since it's easy to forget to return a value (typically True) + assert isinstance(ret, bool), ("must return a bool", self.write_f) + else: + ret = self.write_default( + resource, + memory_context, + v, + f, + line_prefix, + inhibit_top_braces=inhibit_top_braces, + ) + assert isinstance(ret, bool), self + return ret + + +class CDataExt_Value(CData_Value, CDataExt): + is_padding = False + + def padding(self): + self.is_padding = True + return self + + def freeze(self): + self.padding = None + return super().freeze() + + def set_write_str_v(self, str_v: Callable[[Any], str]): + """Utility wrapper for set_write, writes the value as stringified by str_v.""" + + def write_f( + resource: "CDataResource", + memory_context: "MemoryContext", + v: Any, + wctx: CDataExtWriteContext, + ): + wctx.f.write(wctx.line_prefix) + wctx.f.write(str_v(v)) + return True + + self.set_write(write_f) + return self + + def report(self, resource, memory_context, v): + super().report(resource, memory_context, v) + if self.is_padding: + if v != 0: + raise Exception("non-0 padding") + + def write_default( + self, resource, memory_context, v, f, line_prefix, *, inhibit_top_braces + ): + assert ( + not inhibit_top_braces + ), "CDataExt_Value can't inhibit top braces, it doesn't have any" + if not self.is_padding: + f.write(line_prefix) + f.write(str(v)) + return True + else: + return False + + +CDataExt_Value.s8 = CDataExt_Value("b").freeze() +CDataExt_Value.u8 = CDataExt_Value("B").freeze() +CDataExt_Value.s16 = CDataExt_Value("h").freeze() +CDataExt_Value.u16 = CDataExt_Value("H").freeze() +CDataExt_Value.s32 = CDataExt_Value("i").freeze() +CDataExt_Value.u32 = CDataExt_Value("I").freeze() +CDataExt_Value.f32 = CDataExt_Value("f").freeze() +CDataExt_Value.f64 = CDataExt_Value("d").freeze() +CDataExt_Value.pointer = CDataExt_Value("I").freeze() + +CDataExt_Value.pad8 = CDataExt_Value("b").padding().freeze() +CDataExt_Value.pad16 = CDataExt_Value("h").padding().freeze() +CDataExt_Value.pad32 = CDataExt_Value("i").padding().freeze() + + +INDENT = " " * 4 + + +class CDataExt_Array(CData_Array, CDataExt): + def __init__(self, element_cdata_ext: CDataExt, length: int): + super().__init__(element_cdata_ext, length) + self.element_cdata_ext = element_cdata_ext + + def report(self, resource, memory_context, v): + assert isinstance(v, list) + super().report(resource, memory_context, v) + for elem in v: + self.element_cdata_ext.report(resource, memory_context, elem) + + def write_default( + self, resource, memory_context, v, f, line_prefix, *, inhibit_top_braces + ): + assert isinstance(v, list) + if not inhibit_top_braces: + f.write(line_prefix) + f.write("{\n") + for i, elem in enumerate(v): + ret = self.element_cdata_ext.write( + resource, + memory_context, + elem, + f, + line_prefix + INDENT, + inhibit_top_braces=False, + ) + assert ret + f.write(f", // {i}\n") + if not inhibit_top_braces: + f.write(line_prefix) + f.write("}") + return True + + +class CDataExt_Struct(CData_Struct, CDataExt): + def __init__(self, members: Sequence[tuple[str, CDataExt]]): + super().__init__(members) + self.members_ext = members + + def report(self, resource, memory_context, v): + assert isinstance(v, dict) + super().report(resource, memory_context, v) + for member_name, member_cdata_ext in self.members_ext: + member_cdata_ext.report(resource, memory_context, v[member_name]) + + def write_default( + self, resource, memory_context, v, f, line_prefix, *, inhibit_top_braces + ): + assert isinstance(v, dict) + if not inhibit_top_braces: + f.write(line_prefix) + f.write("{\n") + for member_name, member_cdata_ext in self.members_ext: + if member_cdata_ext.write( + resource, + memory_context, + v[member_name], + f, + line_prefix + INDENT, + inhibit_top_braces=False, + ): + f.write(f", // {member_name}\n") + if not inhibit_top_braces: + f.write(line_prefix) + f.write("}") + return True + + +class CDataResource(Resource): + + # Set by child classes + cdata_ext: CDataExt + + # Resource implementation + + def __init__(self, file: File, range_start: int, name: str): + if not self.can_size_be_unknown: + assert hasattr(self, "cdata_ext"), self.__class__ + assert self.cdata_ext is not None + range_end = range_start + self.cdata_ext.size + else: + if hasattr(self, "cdata_ext") and self.cdata_ext is not None: + range_end = range_start + self.cdata_ext.size + else: + range_end = None + super().__init__(file, range_start, range_end, name) + self._is_cdata_processed = False + + def try_parse_data(self, memory_context: "MemoryContext"): + if self.can_size_be_unknown: + assert hasattr(self, "cdata_ext") and self.cdata_ext is not None, ( + "Subclasses with can_size_be_unknown=True should redefine try_parse_data" + " and call the superclass definition (CDataResource.try_parse_data)" + " only once cdata_ext has been set", + self.__class__, + ) + assert ( + self.range_end is not None + ), "Subclasses with can_size_be_unknown=True should also set range_end once the size is known" + assert hasattr(self, "cdata_ext") + assert self.cdata_ext is not None + + # In case the subclass does more involved processing, the self.is_data_parsed + # bool wouldn't necessarily reflect the state of the cdata. + # Use own bool self._is_cdata_processed to remember if cdata has been unpacked and + # reported already. + if not self._is_cdata_processed: + self.cdata_unpacked = self.cdata_ext.unpack_from( + self.file.data, self.range_start + ) + + self.cdata_ext.report(self, memory_context, self.cdata_unpacked) + + self._is_cdata_processed = True + + return RESOURCE_PARSE_SUCCESS + + def write_extracted(self, memory_context): + with self.extract_to_path.open("w") as f: + self.cdata_ext.write( + self, + memory_context, + self.cdata_unpacked, + f, + "", + inhibit_top_braces=self.braces_in_source, + ) + f.write("\n") + + +class CDataArrayResource(CDataResource): + """Helper for variable-length array resources. + + The length is unknown at object creation, and must be set eventually + with set_length (for example by another resource). + + The length being set then allows this resource to be parsed. + + For static-length array resources, just use CDataResource. + """ + + def __init_subclass__(cls, /, **kwargs): + super().__init_subclass__(can_size_be_unknown=True, **kwargs) + + elem_cdata_ext: CDataExt + + def __init__(self, file: File, range_start: int, name: str): + super().__init__(file, range_start, name) + self._length: Union[None, int] = None + + def set_length(self, length: int): + if self._length is not None: + if self._length != length: + raise Exception( + "length already set and is different", self._length, length + ) + assert length > 0 + self._length = length + + def try_parse_data(self, memory_context: "MemoryContext"): + if self._length is None: + raise ResourceParseWaiting(waiting_for=["self._length"]) + assert isinstance(self.elem_cdata_ext, CDataExt), (self.__class__, self) + self.cdata_ext = CDataExt_Array(self.elem_cdata_ext, self._length) + self.range_end = self.range_start + self.cdata_ext.size + return super().try_parse_data(memory_context) + + def get_c_reference(self, resource_offset: int): + if resource_offset == 0: + return self.symbol_name + else: + raise ValueError + + def get_c_expression_length(self, resource_offset: int): + if resource_offset == 0: + return f"ARRAY_COUNT({self.symbol_name})" + else: + raise ValueError + + +class CDataArrayNamedLengthResource(CDataArrayResource): + """CDataArrayResource and with a macro (define) for its length. + + This is useful for arrays that have a length that should be referenced somewhere, + but cannot due to the order the definitions are in. + + This writes a macro to the .h for the length, along the symbol declaration, + to be used in the declaration base (! by the subclass, in get_c_declaration_base) + """ + + def __init__(self, file: File, range_start: int, name: str): + super().__init__(file, range_start, name) + self.length_name = f"LENGTH_{self.symbol_name}" + + def write_c_declaration(self, h: io.TextIOBase): + h.write(f"#define {self.length_name} {self._length}\n") + super().write_c_declaration(h) + + +cdata_ext_Vec3s = CDataExt_Struct( + ( + ("x", CDataExt_Value.s16), + ("y", CDataExt_Value.s16), + ("z", CDataExt_Value.s16), + ) +) + + +class Vec3sArrayResource(CDataResource): + + elem_cdata_ext = cdata_ext_Vec3s + + def __init__(self, file: File, range_start: int, name: str, length: int): + assert length > 0 + self.cdata_ext = CDataExt_Array(self.elem_cdata_ext, length) + super().__init__(file, range_start, name) + + def get_c_declaration_base(self): + return f"Vec3s {self.symbol_name}[]" + + def get_c_reference(self, resource_offset: int): + if resource_offset == 0: + return self.symbol_name + else: + raise ValueError() + + def get_c_expression_length(self, resource_offset: int): + if resource_offset == 0: + return f"ARRAY_COUNT({self.symbol_name})" + else: + raise ValueError() + + def get_h_includes(self): + return ("z64math.h",) + + +class S16ArrayResource(CDataResource): + + elem_cdata_ext = CDataExt_Value.s16 + + def __init__(self, file: File, range_start: int, name: str, length: int): + assert length > 0 + self.cdata_ext = CDataExt_Array(self.elem_cdata_ext, length) + super().__init__(file, range_start, name) + + def get_c_declaration_base(self): + if hasattr(self, "HACK_IS_STATIC_ON"): + return f"s16 {self.symbol_name}[{self.cdata_ext.size // self.elem_cdata_ext.size}]" + return f"s16 {self.symbol_name}[]" + + def get_c_reference(self, resource_offset: int): + if resource_offset == 0: + return self.symbol_name + else: + raise ValueError() + + def get_c_expression_length(self, resource_offset: int): + if resource_offset == 0: + return f"ARRAY_COUNT({self.symbol_name})" + else: + raise ValueError() + + def get_h_includes(self): + return ("ultra64.h",) + + +cdata_ext_Vec3f = CDataExt_Struct( + ( + ("x", CDataExt_Value.f32), + ("y", CDataExt_Value.f32), + ("z", CDataExt_Value.f32), + ) +) + + +def fmt_hex_s(v: int, nibbles: int = 0): + """Format v to 0x-prefixed uppercase hexadecimal, using (at least) the specified amount of nibbles. + + Meant for signed values (_s suffix), + adds a space in place of where the - sign would be for positive values. + + Note compared to this, + - f"{v:#X}" would produce an uppercase 0X (1 -> 0X1) + - f"0x{v:X}" doesn't work with negative values (-1 -> 0x-1) + """ + v_str = f"{v:0{nibbles}X}" + if v < 0: + v_str = v_str.removeprefix("-") + return f"-0x{v_str}" + else: + return f" 0x{v_str}" + + +def fmt_hex_u(v: int, nibbles: int = 0): + """Format v to 0x-prefixed uppercase hexadecimal, using (at least) the specified amount of nibbles. + + Meant for unsigned values (_u suffix), + but won't fail for negative values. + + See: fmt_hex_s + """ + v_str = f"{v:0{nibbles}X}" + if v < 0: + # Also handle v being negative just in case, + # it will only mean the output isn't aligned as expected + v_str = v_str.removeprefix("-") + return f"-0x{v_str}" + else: + return f"0x{v_str}" diff --git a/tools/assets/extract/extase/memorymap.py b/tools/assets/extract/extase/memorymap.py new file mode 100644 index 0000000000..0064357bfe --- /dev/null +++ b/tools/assets/extract/extase/memorymap.py @@ -0,0 +1,428 @@ +# SPDX-FileCopyrightText: © 2025 ZeldaRET +# SPDX-License-Identifier: CC0-1.0 + +import abc +from dataclasses import dataclass + +from typing import Callable, TypeVar, Generic + +try: + from rich.pretty import pprint as rich_pprint +except ImportError: + rich_pprint = print + +from . import Resource, File, GetResourceAtResult + + +# when failing to resolve an address, +# (try to) keep going by creating "fake" files/resources +# or defaulting to poor choices (e.g. raw addresses) +BEST_EFFORT = True +if BEST_EFFORT: + VERBOSE_BEST_EFFORT = 1 + VERBOSE_BEST_EFFORT_LVL1_IGNORED_SEGS = { + 1, # billboard matrix segment + 8, # often used for eye/mouth textures, or various dlist callbacks. same for 9-0xC + 9, + 0xA, + 0xB, + 0xC, + 0xD, # matrix buffer for skeletons dlists + } + + +# RangeMap + +RangeMapValueT = TypeVar("RangeMapValueT") + + +class RangeMap(Generic[RangeMapValueT]): + def __init__(self): + self.values_by_range: dict[tuple[int, int], RangeMapValueT] = dict() + + def set(self, range_start: int, range_end: int, value: RangeMapValueT): + assert range_start < range_end + current_values_in_range = self.get_all_in_range(range_start, range_end) + if current_values_in_range: + raise Exception( + "Range already used (at least partially)", + hex(range_start), + hex(range_end), + current_values_in_range, + ) + self.values_by_range[(range_start, range_end)] = value + + def get_all_by_predicate(self, predicate: Callable[[int, int], bool]): + """Return all values associated to a range for which the predicate returns True""" + values: dict[tuple[int, int], RangeMapValueT] = dict() + for (range_start, range_end), value in self.values_by_range.items(): + if predicate(range_start, range_end): + values[(range_start, range_end)] = value + return values + + def get_all_in_range(self, range_start: int, range_end: int): + """Return all values associated to a range intersecting with the given range""" + assert range_start < range_end + + def check_intersect(value_range_start, value_range_end): + assert value_range_start < value_range_end + if range_end <= value_range_start: + return False + if value_range_end <= range_start: + return False + return True + + return self.get_all_by_predicate(check_intersect) + + def get(self, offset) -> RangeMapValueT: + """Return the value associated to the range the given offset is in, + if any, or raise IndexError""" + + def check_belong(value_range_start, value_range_end): + assert value_range_start < value_range_end + return value_range_start <= offset < value_range_end + + values = self.get_all_by_predicate(check_belong) + assert len(values) <= 1, values + if values: + return next(iter(values.values())) + else: + raise IndexError(offset) + + def copy(self): + """Returns a shallow copy""" + other = RangeMap() + other.values_by_range = self.values_by_range.copy() + return other + + +class NoResourceError(Exception): + """There is no resource at the requested address""" + + pass + + +class UnexpectedResourceTypeError(Exception): + """There is a resource at the requested address, but of the wrong type""" + + pass + + +class UnmappedAddressError(Exception): + """Indicates an address could not be resolved because nothing was found for the address.""" + + pass + + +AttributeValueT = TypeVar("AttributeValueT") + + +@dataclass(frozen=True) +class Attribute(Generic[AttributeValueT]): + name: str # Uniquely identifies the attribute + value_type: type[AttributeValueT] + + def __eq__(self, other): + if isinstance(other, Attribute): + return self.name == other.name + else: + return False + + def __hash__(self): + return hash(self.name) + + +class Attributes: + c_reference = Attribute("c_reference", str) + c_expression_length = Attribute("c_expression_length", str) + + +ResourceT = TypeVar("ResourceT", bound="Resource") + + +class AddressResolveResult: + def __init__(self, original_address: int, file: File, file_offset: int): + self.original_address = original_address + """Original address that was resolved to this result (for debugging purposes)""" + + self.file = file + self.file_offset = file_offset + + def get_resource(self, resource_type: type[ResourceT]) -> ResourceT: + result, resource = self.file.get_resource_at(self.file_offset) + if result != GetResourceAtResult.DEFINITIVE: + raise NoResourceError("No definitive resource", result) + assert resource is not None + if resource.range_start != self.file_offset: + raise NoResourceError( + "No resource at (exactly) the requested address", resource + ) + if not isinstance(resource, resource_type): + raise UnexpectedResourceTypeError(resource, resource_type) + return resource + + def get_attribute(self, attribute: Attribute[AttributeValueT]) -> AttributeValueT: + result, resource = self.file.get_resource_at(self.file_offset) + + if result != GetResourceAtResult.DEFINITIVE: + raise Exception("No definitive resource", result) + assert resource is not None + + resource_offset = self.file_offset - resource.range_start + + if attribute == Attributes.c_reference: + value = resource.get_c_reference(resource_offset) + elif attribute == Attributes.c_expression_length: + value = resource.get_c_expression_length(resource_offset) + else: + raise NotImplementedError(attribute) + + if not isinstance(value, attribute.value_type): + raise Exception( + "Resource gave an attribute value of unexpected type", + resource, + attribute, + value, + type(value), + ) + + return value + + def __repr__(self): + return ( + "AddressResolveResult(" + f"original_address=0x{self.original_address:08X}, " + f"file_name={self.file.name!r}, " + f"file_offset=0x{self.file_offset:X})" + ) + + +class AddressResolver(abc.ABC): + @abc.abstractmethod + def resolve( + self, original_address: int, address_offset: int + ) -> AddressResolveResult: ... + + +class MemoryMap: + def __init__(self): + self.direct = RangeMap[AddressResolver]() + self.segments: dict[int, RangeMap[AddressResolver]] = { + segment_num: RangeMap[AddressResolver]() for segment_num in range(1, 16) + } + + def copy(self): + """Returns a copy that is independently mutable + + (only the mappings are copied, the underlying AddressResolver s are the same) + """ + other = MemoryMap() + other.direct = self.direct.copy() + other.segments = { + segment_num: segment_range_map.copy() + for segment_num, segment_range_map in self.segments.items() + } + return other + + +def get_segment_num(address: int): + return (address & 0x0F00_0000) >> 24 + + +@dataclass +class FileDirectAddressResolver(AddressResolver): + direct_file_offset_start: int + target_file: File + + def resolve(self, original_address, address_offset): + file_offset = address_offset - self.direct_file_offset_start + return AddressResolveResult(original_address, self.target_file, file_offset) + + +@dataclass +class FileSegmentAddressResolver(AddressResolver): + target_file: File + + def resolve(self, original_address, address_offset): + file_offset = address_offset + return AddressResolveResult(original_address, self.target_file, file_offset) + + +class MemoryContext: + """ + handles segmented addresses, pointers, external symbols (eg gMtxClear) + + maps offsets to data + """ + + def __init__(self, dmadata_table_rom_file_name_by_vrom): + self.memory_map = MemoryMap() + self.dmadata_table_rom_file_name_by_vrom = dmadata_table_rom_file_name_by_vrom + + def copy(self): + other = MemoryContext(self.dmadata_table_rom_file_name_by_vrom) + other.memory_map = self.memory_map.copy() + return other + + def get_dmadata_table_rom_file_name_from_vrom(self, vromStart, vromEnd): + return self.dmadata_table_rom_file_name_by_vrom[(vromStart, vromEnd)] + + def _direct_address_to_offset(self, address: int): + segment_num = get_segment_num(address) + if segment_num != 0: + raise ValueError("Address is segmented, not direct", hex(address)) + # The 0xF000_0000 bits are ignored. Not 100% correct but simplest + offset = address & 0x00FF_FFFF + return offset + + def set_direct_file(self, address: int, target_file: File): + direct_file_offset_start = self._direct_address_to_offset(address) + direct_file_offset_end = direct_file_offset_start + target_file.size + + self.memory_map.direct.set( + direct_file_offset_start, + direct_file_offset_end, + FileDirectAddressResolver(direct_file_offset_start, target_file), + ) + + def set_segment_file(self, segment_num: int, target_file: File): + if not (1 <= segment_num < 16): + raise ValueError( + "Segment number must be between 1 and 15 (inclusive)", segment_num + ) + + self.memory_map.segments[segment_num].set( + 0, 0x0100_0000, FileSegmentAddressResolver(target_file) + ) + + def resolve_direct(self, address: int): + offset = self._direct_address_to_offset(address) + try: + address_resolver = self.memory_map.direct.get(offset) + except IndexError as e: + raise UnmappedAddressError( + "direct address is not mapped", f"0x{address:08X}" + ) from e + return address_resolver.resolve(address, offset) + + def resolve_segmented(self, address: int): + segment_num = get_segment_num(address) + if segment_num == 0: + return self.resolve_direct(address) + else: + assert address & 0xF000_0000 == 0 + offset = address & 0x00FF_FFFF + try: + address_resolver = self.memory_map.segments[segment_num].get(offset) + except IndexError as e: + raise UnmappedAddressError( + "segment address is not mapped", f"0x{address:08X}" + ) from e + return address_resolver.resolve(address, offset) + + def report_resource_at_segmented( + self, + reporter: Resource, + address: int, + resource_type: type[ResourceT], + new_resource_pointed_to: Callable[[File, int], ResourceT], + ) -> ResourceT: + try: + resolve_result = self.resolve_segmented(address) + except UnmappedAddressError as e: + if BEST_EFFORT: + fake_file = File(f"besteffort_fakefile_{address:08X}", size=0x0100_0000) + fake_resource = new_resource_pointed_to(fake_file, 0) + fake_resource.reporters.add(reporter) + fake_file.add_resource(fake_resource) + if VERBOSE_BEST_EFFORT >= 2 or ( + VERBOSE_BEST_EFFORT >= 1 + and (address >> 24) not in VERBOSE_BEST_EFFORT_LVL1_IGNORED_SEGS + ): + print("BEST_EFFORT: ignored error e=") + rich_pprint(e) + print(" on resource report by reporter=") + rich_pprint(reporter) + print(f" at {address=:#08X}") + print(" and created fake_file=") + rich_pprint(fake_file), + print(" and fake_resource=") + rich_pprint(fake_resource) + fake_file.FAKE_FOR_BEST_EFFORT = True + fake_resource.FAKE_FOR_BEST_EFFORT = True + return fake_resource + raise + try: + resource = resolve_result.get_resource(resource_type) + except NoResourceError: + resource = None + except UnexpectedResourceTypeError: + print("Could not resolve segment address for reporting", resolve_result) + raise + else: + assert resource is not None + if resource is None: + resource = new_resource_pointed_to( + resolve_result.file, + resolve_result.file_offset, + ) + resolve_result.file.add_resource(resource) + resource.reporters.add(reporter) + return resource + + def mark_resource_buffer_at_segmented( + self, + reporter: Resource, + resource_type: type[Resource], + name: str, + address_start: int, + address_end: int, + ): + # Note: this function assumes the whole address_start-address_end range resolves the same way. + # It not being the case would be very weird, but it's not checked here + try: + resolve_result = self.resolve_segmented(address_start) + except UnmappedAddressError as e: + if BEST_EFFORT: + if VERBOSE_BEST_EFFORT >= 2 or ( + VERBOSE_BEST_EFFORT >= 1 + and (address_start >> 24) + not in VERBOSE_BEST_EFFORT_LVL1_IGNORED_SEGS + ): + print("BEST_EFFORT: ignored error e=") + rich_pprint(e) + print(" and skipping marking resource buffer for reporter=") + rich_pprint(reporter) + print( + f" {resource_type=} {address_start=:#08X} {address_end=:#08X}" + ) + return + raise + file_start = resolve_result.file_offset + file_end = file_start + address_end - address_start + resolve_result.file.mark_resource_buffer( + reporter, resource_type, name, file_start, file_end + ) + + def get_attribute_at_segmented( + self, address: int, attribute: Attribute[AttributeValueT] + ): + return self.resolve_segmented(address).get_attribute(attribute) + + def get_c_reference_at_segmented(self, address: int): + try: + return self.get_attribute_at_segmented(address, Attributes.c_reference) + except UnmappedAddressError as e: + if BEST_EFFORT: + if VERBOSE_BEST_EFFORT >= 2 or ( + VERBOSE_BEST_EFFORT >= 1 + and (address >> 24) not in VERBOSE_BEST_EFFORT_LVL1_IGNORED_SEGS + ): + print("BEST_EFFORT: ignored error e="), + rich_pprint(e) + print(f" and returning raw address=0x{address:08X}") + return f"0x{address:08X}" + raise + + def get_c_expression_length_at_segmented(self, address: int): + return self.get_attribute_at_segmented(address, Attributes.c_expression_length) diff --git a/tools/assets/extract/extase/repr_c_struct.py b/tools/assets/extract/extase/repr_c_struct.py new file mode 100644 index 0000000000..3548ede370 --- /dev/null +++ b/tools/assets/extract/extase/repr_c_struct.py @@ -0,0 +1,223 @@ +# SPDX-FileCopyrightText: © 2025 ZeldaRET +# SPDX-License-Identifier: CC0-1.0 + +import struct +import abc +from typing import Sequence, Any + + +# NOTE: this system does NOT handle struct alignment/padding automatically, it should be made explicit + +# this system voluntarily does not handle variable length arrays. which is not a valid "type" in C anyway (?) +# having variable-sized data is too messy to handle, because it needs a size at some point anyway +# This choice allows the root CData ABC to have a size as a guaranteed attribute + + +# BOSA = "Byte Order, Size, and Alignment" for the struct module +# Big Endian +STRUCT_BOSA_CHAR = ">" + + +class CData(abc.ABC): + @abc.abstractmethod + def __init__(self, size: int): + self.size = size + + # Unpack + + @abc.abstractmethod + def unpack_from(self, data: memoryview, offset: int = 0) -> Any: ... + + +class CData_Value(CData): + def __init__(self, format_char: str): + assert format_char in set("bBhHiIfd") + self.unpack_struct = struct.Struct(STRUCT_BOSA_CHAR + format_char) + super().__init__(self.unpack_struct.size) + + def unpack_from(self, data: memoryview, offset: int = 0): + return self.unpack_struct.unpack_from(data, offset)[0] + + +CData_Value.s8 = CData_Value("b") +CData_Value.u8 = CData_Value("B") +CData_Value.s16 = CData_Value("h") +CData_Value.u16 = CData_Value("H") +CData_Value.s32 = CData_Value("i") +CData_Value.u32 = CData_Value("I") +CData_Value.f32 = CData_Value("f") +CData_Value.f64 = CData_Value("d") +CData_Value.pointer = CData_Value("I") + + +class CData_Array(CData): + def __init__(self, element_cdata: CData, length: int): + assert length > 0 + self.element_cdata = element_cdata + self.length = length + super().__init__(element_cdata.size * length) + + def unpack_from(self, data: memoryview, offset: int = 0): + array_unpacked = [] + + for i in range(self.length): + unpacked = self.element_cdata.unpack_from(data, offset) + array_unpacked.append(unpacked) + offset += self.element_cdata.size + + assert len(array_unpacked) == self.length + + return array_unpacked + + +class CData_Struct(CData): + def __init__(self, members: Sequence[tuple[str, CData]]): + # assert all members have different names + assert len(members) == len( + set(member_name for member_name, member_cdata in members) + ), members + + self.members = members + super().__init__( + sum(member_cdata.size for member_name, member_cdata in members) + ) + + if __debug__: + # Check alignment + + # This may mess up with CData instances other than CData_Value, Array and Struct + def get_required_alignment(cdata: CData): + if isinstance(cdata, CData_Struct): + return max( + get_required_alignment(cdata_member_cdata) + for cdata_member_name, cdata_member_cdata in cdata.members + ) + elif isinstance(cdata, CData_Array): + return get_required_alignment(cdata.element_cdata) + else: + # Assume the alignment requirement corresponds to the size + # (e.g. this is correct for CData_Value) + return cdata.size + + # Check alignment of the members of the struct + offset = 0 + for member_name, member_cdata in members: + alignment = get_required_alignment(member_cdata) + assert offset % alignment == 0, (member_name, offset, alignment) + offset += member_cdata.size + + # Check alignment of the struct size + alignment = get_required_alignment(self) + assert self.size % alignment == 0, (self.size, alignment) + + def unpack_from(self, data: memoryview, offset: int = 0): + struct_unpacked = dict() + + for member_name, member_cdata in self.members: + member_unpacked = member_cdata.unpack_from(data, offset) + struct_unpacked[member_name] = member_unpacked + offset += member_cdata.size + + return struct_unpacked + + +def try_stuff(): + """ + struct { + s8 fun; + // u8 pad; + s16 games; + } array[] = { { 1, 2 }, { 3, 4 } }; + + + u8 varLenArray[] = { 1, 2, 3 }; + + struct { + u8* ptr; + u16 len; + struct { + s32 secret1; + u32 secret2; + } mySubStruct; + } data = { varLenArray, 3, { 421, 0x01020304 } }; + """ + + array_bytes = bytes( + [ + 1, + 0, + *(0, 2), + 3, + 0, + *(0, 4), + ] + ) + varLenArray_bytes = bytes([1, 2, 3]) + data_bytes = bytes( + [ + *(0x12, 0x34, 0x56, 0x78), + *(0, 3), + 0, + 0, + *(0, 0, 421 >> 8, 421 & 0xFF), + *(1, 2, 3, 4), + ] + ) + + arrayElem_CData_Struct = CData_Struct( + ( + ("fun", CData_Value.s8), + ("pad1", CData_Value.s8), + ("games", CData_Value.s16), + ) + ) + array_CData_Array = CData_Array(arrayElem_CData_Struct, 2) + + print(array_CData_Array.unpack_from(array_bytes)) + + mySubStruct_CData_Struct = CData_Struct( + ( + ("secret1", CData_Value.s32), + ("secret2", CData_Value.u32), + ) + ) + + data_CData_Struct = CData_Struct( + ( + ("ptr", CData_Value.pointer), + ("len", CData_Value.u16), + ("pad_6", CData_Value.s16), + ("mySubStruct", mySubStruct_CData_Struct), + ) + ) + + data_unpacked = data_CData_Struct.unpack_from(data_bytes) + print(data_unpacked) + + varLenArray_CData_Array = CData_Array(CData_Value.u8, data_unpacked["len"]) + + print(varLenArray_CData_Array.unpack_from(varLenArray_bytes)) + + data_integratedSubStruct_CData_Struct = CData_Struct( + ( + ("ptr", CData_Value.pointer), + ("len", CData_Value.u16), + ("pad_6", CData_Value.s16), + ( + "mySubStruct", + CData_Struct( + ( + ("secret1", CData_Value.s32), + ("secret2", CData_Value.u32), + ) + ), + ), + ) + ) + + data_unpacked = data_integratedSubStruct_CData_Struct.unpack_from(data_bytes) + print(data_unpacked) + + +if __name__ == "__main__": + try_stuff() diff --git a/tools/assets/extract/extase_oot64/animation_resources.py b/tools/assets/extract/extase_oot64/animation_resources.py new file mode 100644 index 0000000000..ec7e4bbac3 --- /dev/null +++ b/tools/assets/extract/extase_oot64/animation_resources.py @@ -0,0 +1,205 @@ +# SPDX-FileCopyrightText: © 2025 ZeldaRET +# SPDX-License-Identifier: CC0-1.0 + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ..extase.memorymap import MemoryContext + +from ..extase import ( + RESOURCE_PARSE_SUCCESS, + ResourceParseWaiting, + File, +) +from ..extase.cdata_resources import ( + CDataResource, + CDataExt_Value, + CDataExt_Struct, + CDataExt_Array, + CDataExtWriteContext, +) + + +class AnimationFrameDataResource(CDataResource, can_size_be_unknown=True): + def write_binang(resource, memory_context, v, wctx: CDataExtWriteContext): + wctx.f.write(wctx.line_prefix) + wctx.f.write(f" 0x{v:04X}" if v >= 0 else "-0x" + f"{v:04X}".removeprefix("-")) + return True + + elem_cdata_ext = CDataExt_Value("h").set_write(write_binang) + + def __init__(self, file: File, range_start: int, name: str): + super().__init__(file, range_start, name) + self.length = None + + def try_parse_data(self, memory_context): + if self.length is not None: + self.cdata_ext = CDataExt_Array(self.elem_cdata_ext, self.length) + self.range_end = self.range_start + self.cdata_ext.size + return super().try_parse_data(memory_context) + else: + raise ResourceParseWaiting(waiting_for=["self.length"]) + + def get_c_declaration_base(self): + return f"s16 {self.symbol_name}[]" + + def get_c_reference(self, resource_offset: int): + if resource_offset == 0: + return self.symbol_name + else: + raise ValueError() + + def get_h_includes(self): + return ("ultra64.h",) + + +class AnimationJointIndicesResource(CDataResource, can_size_be_unknown=True): + elem_cdata_ext = CDataExt_Struct( + ( + ("x", CDataExt_Value.u16), + ("y", CDataExt_Value.u16), + ("z", CDataExt_Value.u16), + ) + ) + + def __init__(self, file: File, range_start: int, name: str): + super().__init__(file, range_start, name) + self.length = None + + def try_parse_data(self, memory_context): + if self.length is not None: + self.cdata_ext = CDataExt_Array(self.elem_cdata_ext, self.length) + self.range_end = self.range_start + self.cdata_ext.size + return super().try_parse_data(memory_context) + else: + raise ResourceParseWaiting(waiting_for=["self.length"]) + + def get_c_declaration_base(self): + return f"JointIndex {self.symbol_name}[]" + + def get_c_reference(self, resource_offset: int): + if resource_offset == 0: + return self.symbol_name + else: + raise ValueError() + + def get_h_includes(self): + return ("z64animation.h",) + + +class AnimationResource(CDataResource): + def write_frameData( + resource, memory_context: "MemoryContext", v, wctx: CDataExtWriteContext + ): + assert isinstance(v, int) + address = v + wctx.f.write(wctx.line_prefix) + wctx.f.write(memory_context.get_c_reference_at_segmented(address)) + return True + + def write_jointIndices( + resource, memory_context: "MemoryContext", v, wctx: CDataExtWriteContext + ): + assert isinstance(v, int) + address = v + wctx.f.write(wctx.line_prefix) + wctx.f.write(memory_context.get_c_reference_at_segmented(address)) + return True + + cdata_ext = CDataExt_Struct( + ( + ( + "common", + CDataExt_Struct((("frameCount", CDataExt_Value.s16),)), + ), + ("pad2", CDataExt_Value.pad16), + ( + "frameData", + CDataExt_Value("I").set_write(write_frameData), + ), + ( + "jointIndices", + CDataExt_Value("I").set_write(write_jointIndices), + ), + ("staticIndexMax", CDataExt_Value.u16), + ("padE", CDataExt_Value.pad16), + ) + ) + + def try_parse_data(self, memory_context): + super().try_parse_data(memory_context) + + frameData_address = self.cdata_unpacked["frameData"] + assert isinstance(frameData_address, int) + resource_frameData = memory_context.report_resource_at_segmented( + self, + frameData_address, + AnimationFrameDataResource, + lambda file, offset: AnimationFrameDataResource( + file, + offset, + f"{self.name}_{frameData_address:08X}_FrameData", + ), + ) + + jointIndices_address = self.cdata_unpacked["jointIndices"] + assert isinstance(jointIndices_address, int) + resource_jointIndices = memory_context.report_resource_at_segmented( + self, + jointIndices_address, + AnimationJointIndicesResource, + lambda file, offset: AnimationJointIndicesResource( + file, + offset, + f"{self.name}_{jointIndices_address:08X}_JointIndices", + ), + ) + + # The length of the frameData and jointIndices arrays is + # for now assumed to fill the space to the animation, + # at the very least before subtracting the offsets check that + # the offsets belong to the same file + # TODO better idea for computing this data's size + + if not (resource_frameData.file == resource_jointIndices.file == self.file): + raise NotImplementedError( + "Expected frameData and jointIndices to be in the same file as the animation", + self.cdata_unpacked, + resource_frameData.file, + resource_jointIndices.file, + self.file, + ) + + if ( + resource_frameData.range_start + < resource_jointIndices.range_start + < self.range_start + ): + resource_frameData.length = ( + resource_jointIndices.range_start - resource_frameData.range_start + ) // AnimationFrameDataResource.elem_cdata_ext.size + resource_jointIndices.length = ( + self.range_start - resource_jointIndices.range_start + ) // AnimationJointIndicesResource.elem_cdata_ext.size + else: + raise NotImplementedError( + "Expected offsets of frameData, jointIndices, animation to be in order", + self.cdata_unpacked, + hex(resource_frameData.range_start), + hex(resource_jointIndices.range_start), + hex(self.range_start), + ) + + return RESOURCE_PARSE_SUCCESS + + def get_c_reference(self, resource_offset: int): + if resource_offset == 0: + return f"&{self.symbol_name}" + else: + raise ValueError() + + def get_c_declaration_base(self): + return f"AnimationHeader {self.symbol_name}" + + def get_h_includes(self): + return ("z64animation.h",) diff --git a/tools/assets/extract/extase_oot64/collision_resources.py b/tools/assets/extract/extase_oot64/collision_resources.py new file mode 100644 index 0000000000..1c8558676e --- /dev/null +++ b/tools/assets/extract/extase_oot64/collision_resources.py @@ -0,0 +1,766 @@ +# SPDX-FileCopyrightText: © 2025 ZeldaRET +# SPDX-License-Identifier: CC0-1.0 + +from typing import TYPE_CHECKING, Optional + +if TYPE_CHECKING: + from ..extase.memorymap import MemoryContext + +from ..extase import ( + File, + RESOURCE_PARSE_SUCCESS, + ResourceParseInProgress, + ResourceParseWaiting, +) +from ..extase.cdata_resources import ( + CDataResource, + CDataExt_Struct, + CDataExt_Array, + CDataExt_Value, + CDataExtWriteContext, + cdata_ext_Vec3s, + INDENT, +) + +from .. import oot64_data + +# TODO would be better for array resources to be of unknown size at instanciation +# and have their size set later, like LimbsArrayResource, +# which allows declaring them with offsets in xmls and have the data parsing +# fill in the length for both cases of it instantiating the array, +# and it being instantiated much earlier from the xml + + +class CollisionVtxListResource(CDataResource): + cdata_ext_elem = cdata_ext_Vec3s + + def __init__(self, file: File, range_start: int, name: str, length: int): + self.cdata_ext = CDataExt_Array(self.cdata_ext_elem, length) + super().__init__(file, range_start, name) + + def get_c_declaration_base(self): + if hasattr(self, "HACK_IS_STATIC_ON"): + return f"Vec3s {self.symbol_name}[{self.cdata_ext.length}]" + return f"Vec3s {self.symbol_name}[]" + + def get_c_reference(self, resource_offset: int): + if resource_offset == 0: + return self.symbol_name + else: + raise ValueError() + + def get_c_expression_length(self, resource_offset: int): + if resource_offset == 0: + return f"ARRAY_COUNT({self.symbol_name})" + else: + raise ValueError() + + def get_h_includes(self): + return ("z64math.h",) + + +class CollisionPolyListResource(CDataResource): + def write_vtxData( + resource: "CollisionPolyListResource", + memory_context: "MemoryContext", + v, + wctx: CDataExtWriteContext, + ): + assert isinstance(v, list) + assert len(v) == 3 + vtxData = v + f = wctx.f + f.write(wctx.line_prefix) + f.write("{\n") + for i in range(3): + vI = vtxData[i] + vtxId = vI & 0x1FFF + flags = (vI & 0xE000) >> 13 + flags_str_list = [] + if i == 0: + if flags & 1: + flags &= ~1 + flags_str_list.append("1") + if flags & 2: + flags &= ~2 + flags_str_list.append("2") + if flags & 4: + flags &= ~4 + flags_str_list.append("4") + elif i == 1: + if flags & 1: + flags &= ~1 + flags_str_list.append("1") + if flags != 0: + flags_str_list.append(f"0x{flags:X}") + if flags_str_list: + flags_str = " | ".join(flags_str_list) + else: + flags_str = "0" + f.write(wctx.line_prefix) + f.write(INDENT) + f.write(f"{vtxId} | (({flags_str}) << 13), // {i}\n") + f.write(wctx.line_prefix) + f.write("}") + return True + + def write_normal_component( + resource: "CollisionPolyListResource", + memory_context: "MemoryContext", + v, + wctx: CDataExtWriteContext, + ): + assert isinstance(v, int) + nf = v / 0x7FFF + wctx.f.write(wctx.line_prefix) + wctx.f.write(f"COLPOLY_SNORMAL({nf})") + + return True + + normal_component = CDataExt_Value("h").set_write(write_normal_component) + cdata_ext_elem = CDataExt_Struct( + ( + ("type", CDataExt_Value.u16), + ("vtxData", CDataExt_Array(CDataExt_Value.u16, 3).set_write(write_vtxData)), + ( + "normal", + CDataExt_Struct( + ( + ("x", normal_component), + ("y", normal_component), + ("z", normal_component), + ) + ), + ), + ("dist", CDataExt_Value.s16), + ) + ) + + def __init__(self, file: File, range_start: int, name: str, length: int): + self.cdata_ext = CDataExt_Array(self.cdata_ext_elem, length) + super().__init__(file, range_start, name) + + def try_parse_data(self, memory_context): + super().try_parse_data(memory_context) + self.max_surface_type_index = max(elem["type"] for elem in self.cdata_unpacked) + assert isinstance(self.max_surface_type_index, int) + return RESOURCE_PARSE_SUCCESS + + def get_c_declaration_base(self): + if hasattr(self, "HACK_IS_STATIC_ON"): + return f"CollisionPoly {self.symbol_name}[{self.cdata_ext.length}]" + return f"CollisionPoly {self.symbol_name}[]" + + def get_c_reference(self, resource_offset: int): + if resource_offset == 0: + return self.symbol_name + else: + raise ValueError() + + def get_c_expression_length(self, resource_offset: int): + if resource_offset == 0: + return f"ARRAY_COUNT({self.symbol_name})" + else: + raise ValueError() + + def get_h_includes(self): + return ("z64bgcheck.h",) + + +class CollisionSurfaceTypeListResource(CDataResource): + def write_data( + resource: "CollisionSurfaceTypeListResource", + memory_context: "MemoryContext", + v, + wctx: CDataExtWriteContext, + ): + assert isinstance(v, list) + assert len(v) == 2 + f = wctx.f + + f.write(wctx.line_prefix) + f.write("{\n") + + for i_data, bitfield_info in ( + ( + 0, + ( + (0x000000FF, 0, "bgCamIndex"), + (0x00001F00, 8, "exitIndex"), + (0x0003E000, 13, "floorType"), + (0x001C0000, 18, "unk18"), + (0x03E00000, 21, "wallType"), + (0x3C000000, 26, "floorProperty"), + (0x40000000, 30, "isSoft"), + (0x80000000, 31, "isHorseBlocked"), + ), + ), + ( + 1, + ( + (0x0000000F, 0, "material"), + (0x00000030, 4, "floorEffect"), + (0x000007C0, 6, "lightSetting"), + (0x0001F800, 11, "echo"), + (0x00020000, 17, "canHookshot"), + (0x001C0000, 18, "conveyorSpeed"), + (0x07E00000, 21, "conveyorDirection"), + (0x08000000, 27, "unk27"), + ), + ), + ): + + data_val = v[i_data] + + f.write(wctx.line_prefix) + f.write(INDENT) + f.write("(\n") + + has_prev = False + for mask, shift, name in bitfield_info: + val = (data_val & mask) >> shift + + f.write(wctx.line_prefix) + f.write(INDENT * 2) + if has_prev: + f.write("| ") + else: + f.write(" ") + + f.write(f"(({val} << {shift:2}) & 0x{mask:08X}) // {name}\n") + + has_prev = True + + f.write(wctx.line_prefix) + f.write(INDENT) + f.write(f"), // {i_data}\n") + + f.write(wctx.line_prefix) + f.write("}") + + return True + + cdata_ext_elem = CDataExt_Struct( + (("data", CDataExt_Array(CDataExt_Value.u32, 2).set_write(write_data)),) + ) + + def __init__(self, file: File, range_start: int, name: str, length: int): + self.cdata_ext = CDataExt_Array(self.cdata_ext_elem, length) + super().__init__(file, range_start, name) + + def try_parse_data(self, memory_context): + super().try_parse_data(memory_context) + self.max_bgCamIndex = max( + elem["data"][0] & 0xFF for elem in self.cdata_unpacked + ) + self.max_exitIndex = max( + (elem["data"][0] & 0x00001F00) >> 8 for elem in self.cdata_unpacked + ) + return RESOURCE_PARSE_SUCCESS + + def get_c_declaration_base(self): + if hasattr(self, "HACK_IS_STATIC_ON"): + return f"SurfaceType {self.symbol_name}[{self.cdata_ext.length}]" + return f"SurfaceType {self.symbol_name}[]" + + def get_c_reference(self, resource_offset: int): + if resource_offset == 0: + return self.symbol_name + else: + raise ValueError() + + def get_h_includes(self): + return ("z64bgcheck.h",) + + +class BgCamFuncDataResource(CDataResource): + element_cdata_ext = cdata_ext_Vec3s + + def __init__(self, file: File, range_start: int, range_end: int, name: str): + count = (range_end - range_start) // self.element_cdata_ext.size + self.cdata_ext = CDataExt_Array(self.element_cdata_ext, count) + super().__init__(file, range_start, name) + + def get_c_declaration_base(self): + if hasattr(self, "HACK_IS_STATIC_ON"): + return f"Vec3s {self.symbol_name}[{self.cdata_ext.length}]" + return f"Vec3s {self.symbol_name}[]" + + def get_c_reference(self, resource_offset: int): + if resource_offset % self.element_cdata_ext.size != 0: + raise ValueError( + "unaligned offset into Vec3s array (BgCamFuncData)", + hex(resource_offset), + self.element_cdata_ext.size, + ) + index = resource_offset // self.element_cdata_ext.size + return f"&{self.symbol_name}[{index}]" + + def get_h_includes(self): + return ("z64math.h",) + + +class CollisionBgCamListResource(CDataResource): + def write_bgCamFuncData( + resource: "CollisionSurfaceTypeListResource", + memory_context: "MemoryContext", + v, + wctx: CDataExtWriteContext, + ): + assert isinstance(v, int) + address = v + wctx.f.write(wctx.line_prefix) + if address != 0: + wctx.f.write(memory_context.get_c_reference_at_segmented(address)) + else: + wctx.f.write("NULL") + return True + + cdata_ext_elem = CDataExt_Struct( + ( + ( + "setting", + CDataExt_Value("H").set_write_str_v( + lambda v: oot64_data.get_camera_setting_type_name(v) + ), + ), + ("count", CDataExt_Value.s16), + ( + "bgCamFuncData", + CDataExt_Value("I").set_write(write_bgCamFuncData), + ), # Vec3s* + ) + ) + + def __init__(self, file: File, range_start: int, name: str, length: int): + self.cdata_ext = CDataExt_Array(self.cdata_ext_elem, length) + super().__init__(file, range_start, name) + + def try_parse_data(self, memory_context): + super().try_parse_data(memory_context) + # Note: operating directly on the segmented addresses here, + # so assuming from the start all bgCamFuncData use the same segment + bgCamFuncData_buffer_start = None + bgCamFuncData_buffer_end = None + for bgCamInfo in self.cdata_unpacked: + count = bgCamInfo["count"] + assert isinstance(count, int) + bgCamFuncData = bgCamInfo["bgCamFuncData"] + assert isinstance(bgCamFuncData, int) + + if bgCamFuncData == 0: + continue + + if bgCamFuncData_buffer_start is None: + bgCamFuncData_buffer_start = bgCamFuncData + bgCamFuncData_buffer_end = ( + bgCamFuncData + count * BgCamFuncDataResource.element_cdata_ext.size + ) + continue + + assert bgCamFuncData_buffer_start is not None + assert bgCamFuncData_buffer_end is not None + if bgCamFuncData != bgCamFuncData_buffer_end: + raise NotImplementedError( + "bgCamFuncData buffer not used in the same order as its elements" + ) + bgCamFuncData_buffer_end += ( + count * BgCamFuncDataResource.element_cdata_ext.size + ) + if bgCamFuncData_buffer_start is not None: + assert bgCamFuncData_buffer_end is not None + memory_context.report_resource_at_segmented( + self, + bgCamFuncData_buffer_start, + BgCamFuncDataResource, + lambda file, offset: BgCamFuncDataResource( + file, + offset, + offset + bgCamFuncData_buffer_end - bgCamFuncData_buffer_start, + f"{self.name}_{bgCamFuncData_buffer_start:08X}_BgCamFuncData", + ), + ) + return RESOURCE_PARSE_SUCCESS + + def get_c_declaration_base(self): + if hasattr(self, "HACK_IS_STATIC_ON"): + return f"BgCamInfo {self.symbol_name}[{self.cdata_ext.length}]" + return f"BgCamInfo {self.symbol_name}[]" + + def get_c_reference(self, resource_offset: int): + if resource_offset == 0: + return self.symbol_name + else: + raise ValueError() + + def get_c_includes(self): + return ("z64camera.h",) + + def get_h_includes(self): + return ("z64bgcheck.h",) + + +class CollisionWaterBoxesResource(CDataResource): + elem_cdata_ext = CDataExt_Struct( + ( + ("xMin", CDataExt_Value.s16), + ("ySurface", CDataExt_Value.s16), + ("zMin", CDataExt_Value.s16), + ("xLength", CDataExt_Value.s16), + ("zLength", CDataExt_Value.s16), + ("pad12", CDataExt_Value.pad16), + ("properties", CDataExt_Value.u32), # TODO formatting + ) + ) + + def __init__(self, file: File, range_start: int, name: str, length: int): + self.cdata_ext = CDataExt_Array(self.elem_cdata_ext, length) + super().__init__(file, range_start, name) + + def get_c_declaration_base(self): + return f"WaterBox {self.symbol_name}[]" + + def get_c_reference(self, resource_offset: int): + if resource_offset == 0: + return self.symbol_name + else: + raise ValueError + + def get_c_expression_length(self, resource_offset: int): + if resource_offset == 0: + return f"ARRAY_COUNT({self.symbol_name})" + else: + raise ValueError + + def get_h_includes(self): + return ("z64bgcheck.h",) + + +def transfer_HACK_IS_STATIC_ON(source, dest): + if hasattr(source, "HACK_IS_STATIC_ON"): + dest.HACK_IS_STATIC_ON = source.HACK_IS_STATIC_ON + return dest + + +class CollisionResource(CDataResource): + def write_numVertices( + resource: "CollisionResource", + memory_context: "MemoryContext", + v, + wctx: CDataExtWriteContext, + ): + wctx.f.write(wctx.line_prefix) + wctx.f.write( + memory_context.get_c_expression_length_at_segmented( + resource.cdata_unpacked["vtxList"] + ) + ) + return True + + def report_vtxList( + resource: "CollisionResource", memory_context: "MemoryContext", v + ): + assert isinstance(v, int) + address = v + memory_context.report_resource_at_segmented( + resource, + address, + CollisionVtxListResource, + lambda file, offset: transfer_HACK_IS_STATIC_ON( + resource, + CollisionVtxListResource( + file, + offset, + f"{resource.name}_{address:08X}_VtxList", + resource.cdata_unpacked["numVertices"], + ), + ), + ) + + def write_vtxList( + resource: "CollisionResource", + memory_context: "MemoryContext", + v, + wctx: CDataExtWriteContext, + ): + assert isinstance(v, int) + wctx.f.write(wctx.line_prefix) + wctx.f.write(memory_context.get_c_reference_at_segmented(v)) + return True + + def write_numPolygons( + resource: "CollisionResource", + memory_context: "MemoryContext", + v, + wctx: CDataExtWriteContext, + ): + wctx.f.write(wctx.line_prefix) + wctx.f.write( + memory_context.get_c_expression_length_at_segmented( + resource.cdata_unpacked["polyList"] + ) + ) + return True + + def report_polyList( + resource: "CollisionResource", memory_context: "MemoryContext", v + ): + assert isinstance(v, int) + address = v + resource.resource_polyList = memory_context.report_resource_at_segmented( + resource, + address, + CollisionPolyListResource, + lambda file, offset: transfer_HACK_IS_STATIC_ON( + resource, + CollisionPolyListResource( + file, + offset, + f"{resource.name}_{address:08X}_PolyList", + resource.cdata_unpacked["numPolygons"], + ), + ), + ) + + def write_polyList( + resource: "CollisionResource", + memory_context: "MemoryContext", + v, + wctx: CDataExtWriteContext, + ): + assert isinstance(v, int) + address = v + wctx.f.write(wctx.line_prefix) + wctx.f.write(memory_context.get_c_reference_at_segmented(address)) + return True + + def write_numWaterBoxes( + resource: "CollisionResource", + memory_context: "MemoryContext", + v, + wctx: CDataExtWriteContext, + ): + wctx.f.write(wctx.line_prefix) + length = resource.cdata_unpacked["numWaterBoxes"] + if length != 0: + wctx.f.write( + memory_context.get_c_expression_length_at_segmented( + resource.cdata_unpacked["waterBoxes"] + ) + ) + else: + wctx.f.write("0") + return True + + def report_waterBoxes( + resource: "CollisionResource", memory_context: "MemoryContext", v + ): + assert isinstance(v, int) + address = v + length = resource.cdata_unpacked["numWaterBoxes"] + if length != 0: + assert address != 0, address # should not be NULL + memory_context.report_resource_at_segmented( + resource, + address, + CollisionWaterBoxesResource, + lambda file, offset: transfer_HACK_IS_STATIC_ON( + resource, + CollisionWaterBoxesResource( + file, + offset, + f"{resource.name}_{address:08X}_WaterBoxes", + length, + ), + ), + ) + + def write_surfaceTypeList( + resource: "CollisionResource", + memory_context: "MemoryContext", + v, + wctx: CDataExtWriteContext, + ): + assert isinstance(v, int) + wctx.f.write(wctx.line_prefix) + wctx.f.write(memory_context.get_c_reference_at_segmented(v)) + return True + + def write_bgCamList( + resource: "CollisionResource", + memory_context: "MemoryContext", + v, + wctx: CDataExtWriteContext, + ): + assert isinstance(v, int) + wctx.f.write(wctx.line_prefix) + wctx.f.write(memory_context.get_c_reference_at_segmented(v)) + return True + + def write_waterBoxes( + resource: "CollisionResource", + memory_context: "MemoryContext", + v, + wctx: CDataExtWriteContext, + ): + assert isinstance(v, int) + length = resource.cdata_unpacked["numWaterBoxes"] + f = wctx.f + f.write(wctx.line_prefix) + if length != 0: + f.write(memory_context.get_c_reference_at_segmented(v)) + else: + if v == 0: + f.write("NULL") + else: + f.write(f"0x{v:08X}") + return True + + cdata_ext = CDataExt_Struct( + ( + ("minBounds", cdata_ext_Vec3s), + ("maxBounds", cdata_ext_Vec3s), + ("numVertices", CDataExt_Value("H").set_write(write_numVertices)), + ("pad14", CDataExt_Value.pad16), + ( + "vtxList", + CDataExt_Value("I").set_report(report_vtxList).set_write(write_vtxList), + ), # Vec3s* + ("numPolygons", CDataExt_Value("H").set_write(write_numPolygons)), + ("pad22", CDataExt_Value.pad16), + ( + "polyList", + CDataExt_Value("I") + .set_report(report_polyList) + .set_write(write_polyList), + ), # CollisionPoly* + ( + "surfaceTypeList", + CDataExt_Value("I").set_write(write_surfaceTypeList), + ), # SurfaceType* + ("bgCamList", CDataExt_Value("I").set_write(write_bgCamList)), # BgCamInfo* + ("numWaterBoxes", CDataExt_Value("H").set_write(write_numWaterBoxes)), + ("pad38", CDataExt_Value.pad16), + ( + "waterBoxes", + CDataExt_Value("I") + .set_report(report_waterBoxes) + .set_write(write_waterBoxes), + ), # WaterBox* + ) + ) + + def __init__(self, file: File, range_start: int, name: str): + super().__init__(file, range_start, name) + + self.length_exitList: Optional[int] = None + + self.resource_polyList: Optional[CollisionPolyListResource] = None + self.resource_surfaceTypeList: Optional[CollisionSurfaceTypeListResource] = None + self.resource_bgCamList: Optional[CollisionBgCamListResource] = None + + def try_parse_data(self, memory_context): + super().try_parse_data(memory_context) + + assert self.resource_polyList is not None + + new_progress_done = [] + waiting_for = [] + + # If the CollisionPolyListResource is parsed + if self.resource_polyList.is_data_parsed: + # report surfaceTypeList based on its length guessed from polyList data + length_surfaceTypeList = self.resource_polyList.max_surface_type_index + 1 + surfaceTypeList_address = self.cdata_unpacked["surfaceTypeList"] + assert isinstance(surfaceTypeList_address, int) + self.resource_surfaceTypeList = memory_context.report_resource_at_segmented( + self, + surfaceTypeList_address, + CollisionSurfaceTypeListResource, + lambda file, offset: transfer_HACK_IS_STATIC_ON( + self, + CollisionSurfaceTypeListResource( + file, + offset, + f"{self.name}_{surfaceTypeList_address:08X}_SurfaceTypes", + length_surfaceTypeList, # TODO change CollisionSurfaceTypeListResource to a CDataArrayResource (same with more resources) + ), + ), + ) + + new_progress_done.append("reported CollisionSurfaceTypeListResource") + else: + waiting_for.append( + ( + "waiting for CollisionPolyListResource" + " to be parsed to report CollisionSurfaceTypeListResource", + self.resource_polyList, + ) + ) + + if self.resource_surfaceTypeList is not None: + # If the CollisionSurfaceTypeListResource is parsed + if self.resource_surfaceTypeList.is_data_parsed: + # report bgCamList based on its length guessed from surfaceTypeList data + length_bgCamList = self.resource_surfaceTypeList.max_bgCamIndex + 1 + bgCamList_address = self.cdata_unpacked["bgCamList"] + assert isinstance(bgCamList_address, int) + self.resource_bgCamList = memory_context.report_resource_at_segmented( + self, + bgCamList_address, + CollisionBgCamListResource, + lambda file, offset: transfer_HACK_IS_STATIC_ON( + self, + CollisionBgCamListResource( + file, + offset, + f"{self.name}_{bgCamList_address:08X}_BgCamList", + length_bgCamList, + ), + ), + ) + + # exitIndex is 1-indexed, so e.g. if the max is 1 the list is of length 1. + self.length_exitList = self.resource_surfaceTypeList.max_exitIndex + + new_progress_done.append("reported CollisionBgCamListResource") + else: + waiting_for.append( + ( + "waiting for CollisionSurfaceTypeListResource" + " to be parsed to report CollisionBgCamListResource", + self.resource_surfaceTypeList, + ) + ) + else: + waiting_for.append("self.resource_surfaceTypeList") + + if waiting_for: + if new_progress_done: + raise ResourceParseInProgress( + new_progress_done=new_progress_done, waiting_for=waiting_for + ) + else: + raise ResourceParseWaiting(waiting_for=waiting_for) + + assert ( + self.resource_surfaceTypeList is not None + and self.resource_bgCamList is not None + and self.length_exitList is not None + ) + return RESOURCE_PARSE_SUCCESS + + def get_c_declaration_base(self): + return f"CollisionHeader {self.symbol_name}" + + def get_c_reference(self, resource_offset: int): + if resource_offset == 0: + return f"&{self.symbol_name}" + else: + raise ValueError() + + def get_c_includes(self): + return ("array_count.h",) + + def get_h_includes(self): + return ("z64bgcheck.h",) diff --git a/tools/assets/extract/extase_oot64/dlist_resources.py b/tools/assets/extract/extase_oot64/dlist_resources.py new file mode 100644 index 0000000000..d883f1907b --- /dev/null +++ b/tools/assets/extract/extase_oot64/dlist_resources.py @@ -0,0 +1,1528 @@ +# SPDX-FileCopyrightText: © 2025 ZeldaRET +# SPDX-License-Identifier: CC0-1.0 + +import enum +import io +from pathlib import Path +import reprlib + +from typing import TYPE_CHECKING, Union, Optional, Callable + +try: + from rich.pretty import pprint as rich_pprint +except ImportError: + rich_pprint = print + +import pygfxd + +if TYPE_CHECKING: + from ..extase.memorymap import MemoryContext +from ..extase.memorymap import UnmappedAddressError, UnexpectedResourceTypeError + +from ..extase import ( + RESOURCE_PARSE_SUCCESS, + ResourceParseWaiting, + Resource, + File, +) +from ..extase.cdata_resources import ( + CDataResource, + CDataExt_Array, + CDataExt_Struct, + CDataExt_Value, + CDataExtWriteContext, + INDENT, + fmt_hex_s, + fmt_hex_u, +) + + +BEST_EFFORT = True + +VERBOSE_ColorIndexedTexturesManager = False +VERBOSE_BEST_EFFORT_TLUT_NO_REAL_USER = True + + +class MtxResource(CDataResource): + braces_in_source = False + + def write_mtx(resource, memory_context, v, wctx: CDataExtWriteContext): + assert isinstance(v, dict) + assert v.keys() == {"intPart", "fracPart"} + intPart = v["intPart"] + fracPart = v["fracPart"] + + f = wctx.f + f.write(wctx.line_prefix) + f.write("gdSPDefMtx(\n") + + for i in range(4): + if i != 0: + f.write(",\n") + f.write(wctx.line_prefix + INDENT) + + for j in range(4): + # #define IPART(x) (((s32)((x) * 0x10000) >> 16) & 0xFFFF) + xi = intPart[j][i] + # #define FPART(x) ((s32)((x) * 0x10000) & 0xFFFF) + xf = fracPart[j][i] + # Reconstruct the `(s32)((x) * 0x10000)` but as a u32 + # (u32 since intPart and fracPart are u16 arrays) + # This works since `(s32)((x) * 0x10000)` in the IPART and FPART + # macros could be switched to `(u32)(s32)((x) * 0x10000)` without issue + u32_x_s15_16 = (xi << 16) | xf + # Cast to s32 (`(s32)(u32)(s32)((x) * 0x10000)` == `(s32)((x) * 0x10000)`) + s32_x_s15_16 = ( + u32_x_s15_16 + if u32_x_s15_16 < 0x8000_0000 + else u32_x_s15_16 - 0x1_0000_0000 + ) + x = s32_x_s15_16 / 0x10000 + + if j != 0: + f.write(", ") + f.write(f"{x}f") + f.write("\n") + + f.write(wctx.line_prefix) + f.write(")") + + return True + + cdata_ext = CDataExt_Struct( + ( + ("intPart", CDataExt_Array(CDataExt_Array(CDataExt_Value.u16, 4), 4)), + ("fracPart", CDataExt_Array(CDataExt_Array(CDataExt_Value.u16, 4), 4)), + ) + ).set_write(write_mtx) + + def get_c_declaration_base(self): + return f"Mtx {self.symbol_name}" + + def get_c_reference(self, resource_offset: int): + if resource_offset == 0: + return f"&{self.symbol_name}" + else: + raise ValueError + + def get_h_includes(self): + return ("ultra64.h",) + + +class VtxArrayResource(CDataResource): + def write_elem(resource, memory_context, v, wctx: CDataExtWriteContext): + assert isinstance(v, dict) + wctx.f.write(wctx.line_prefix) + wctx.f.write( + f"VTX({v['x']:6}, {v['y']:6}, {v['z']:6}, " + f"{fmt_hex_s(v['s']):>7}, {fmt_hex_s(v['t']):>7}, " + f"{fmt_hex_u(v['crnx'], 2)}, {fmt_hex_u(v['cgny'], 2)}, {fmt_hex_u(v['cbnz'], 2)}, {fmt_hex_u(v['a'], 2)})" + ) + return True + + element_cdata_ext = CDataExt_Struct( + ( + ("x", CDataExt_Value.s16), + ("y", CDataExt_Value.s16), + ("z", CDataExt_Value.s16), + ( + "pad6", + CDataExt_Value.pad16, + ), # Not technically padding but unused and expected to always be 0 + ("s", CDataExt_Value.s16), + ("t", CDataExt_Value.s16), + ("crnx", CDataExt_Value.u8), + ("cgny", CDataExt_Value.u8), + ("cbnz", CDataExt_Value.u8), + ("a", CDataExt_Value.u8), + ) + ).set_write(write_elem) + + def __init__(self, file: File, range_start: int, range_end: int, name: str): + num = (range_end - range_start) // self.element_cdata_ext.size + self.cdata_ext = CDataExt_Array(self.element_cdata_ext, num) + super().__init__(file, range_start, name) + + def get_c_declaration_base(self): + if hasattr(self, "HACK_IS_STATIC_ON"): + return f"Vtx {self.symbol_name}[{self.cdata_ext.length}]" + return f"Vtx {self.symbol_name}[]" + + def get_c_reference(self, resource_offset: int): + if resource_offset % self.element_cdata_ext.size != 0: + raise ValueError( + "unaligned offset into vtx array", + hex(resource_offset), + self.element_cdata_ext.size, + ) + index = resource_offset // self.element_cdata_ext.size + return f"&{self.symbol_name}[{index}]" + + def get_c_includes(self): + return ("gfx.h",) + + def get_h_includes(self): + return ("ultra64.h",) + + +from ...n64 import G_IM_FMT, G_IM_SIZ, G_TT, G_MDSFT_TEXTLUT +from ... import n64texconv + +G_IM_FMT_n64texconv_by_n64 = { + G_IM_FMT.RGBA: n64texconv.G_IM_FMT_RGBA, + G_IM_FMT.YUV: n64texconv.G_IM_FMT_YUV, + G_IM_FMT.CI: n64texconv.G_IM_FMT_CI, + G_IM_FMT.IA: n64texconv.G_IM_FMT_IA, + G_IM_FMT.I: n64texconv.G_IM_FMT_I, +} +G_IM_SIZ_n64texconv_by_n64 = { + G_IM_SIZ._4b: n64texconv.G_IM_SIZ_4b, + G_IM_SIZ._8b: n64texconv.G_IM_SIZ_8b, + G_IM_SIZ._16b: n64texconv.G_IM_SIZ_16b, + G_IM_SIZ._32b: n64texconv.G_IM_SIZ_32b, +} + + +def write_n64_image_to_png( + path: Path, width: int, height: int, fmt: G_IM_FMT, siz: G_IM_SIZ, data: memoryview +): + n64texconv.N64Image.from_bin( + data, + width, + height, + G_IM_FMT_n64texconv_by_n64[fmt], + G_IM_SIZ_n64texconv_by_n64[siz], + ).to_png(str(path), False) + + +def write_n64_image_to_png_color_indexed( + path: Path, + width: int, + height: int, + fmt: G_IM_FMT, + siz: G_IM_SIZ, + data: memoryview, + tlut_data: memoryview, + tlut_count: int, + tlut_fmt: G_IM_FMT, +): + assert tlut_count * 2 == len(tlut_data) + n64texconv.N64Image.from_bin( + data, + width, + height, + G_IM_FMT_n64texconv_by_n64[fmt], + G_IM_SIZ_n64texconv_by_n64[siz], + n64texconv.N64Palette.from_bin(tlut_data, G_IM_FMT_n64texconv_by_n64[tlut_fmt]), + ).to_png(str(path), False) + + +class TextureResource(Resource): + needs_build = True + extracted_path_suffix = ".png" + + def __init__( + self, + file: File, + range_start: int, + name: str, + fmt: G_IM_FMT, + siz: G_IM_SIZ, + width: int, + height: int, + ): + size_bits = siz.bpp * width * height + assert size_bits % 8 == 0, size_bits + size_bytes = size_bits // 8 + range_end = range_start + size_bytes + + super().__init__(file, range_start, range_end, name) + + self.fmt = fmt + self.siz = siz + self.width = width + self.height = height + + # For handling color-indexed textures: + self.resource_tlut: Optional[TextureResource] = None + """For CI textures, the TLUT used""" + self.resources_ci_list: list[TextureResource] = [] + """For TLUT "textures", the CI textures using it""" + + if size_bytes % 8 == 0 and (file.alignment + range_start) % 8 == 0: + self.alignment = 8 + elif size_bytes % 4 == 0 and (file.alignment + range_start) % 4 == 0: + self.alignment = 4 + else: + raise NotImplementedError( + "unimplemented: unaligned texture size/offset", + hex(size_bytes), + hex(range_start), + ) + + alignment_bits = self.alignment * 8 + self.elem_type = f"u{alignment_bits}" + assert self.elem_type in {"u64", "u32"} + + self.width_name = f"{self.symbol_name}_WIDTH" + self.height_name = f"{self.symbol_name}_HEIGHT" + + def get_c_declaration_base(self): + if hasattr(self, "HACK_IS_STATIC_ON"): + if self.is_tlut(): + raise NotImplementedError + return f"{self.elem_type} {self.symbol_name}[{self.height_name}*{self.width_name}*{self.siz.bpp}/8/sizeof({self.elem_type})]" + return f"{self.elem_type} {self.symbol_name}[]" + + def get_c_reference(self, resource_offset: int): + if resource_offset == 0: + return self.symbol_name + else: + raise ValueError(self, hex(resource_offset)) + + def resources_ci_list_append(self, resource_ci: "TextureResource"): + if resource_ci not in self.resources_ci_list: + self.resources_ci_list.append(resource_ci) + + HACK_NO_CHECK_TLUT_BOUNDS = self.name in { + # this TLUT should be 184 colors instead of 136 as defined in the xml, + # but then it would overlap with gZelda2_6TLUT. + "gZelda2_5TLUT", + # the skybox TLUTs are used "weirdly" (TODO understand) + "gSunriseSkyboxTLUT", + "gSunsetSkyboxTLUT", + "gDayOvercastSkyboxTLUT", + "gNightOvercastSkyboxTLUT", + "gHoly1SkyboxTLUT", + } + + if __debug__ and not HACK_NO_CHECK_TLUT_BOUNDS: + # if not a TLUTResource, but only a TextureResource, + # this TLUT is xml-defined (using ) + if self.__class__ == TextureResource: + # check the CI texture doesn't index OOB into this tlut + + if resource_ci.file.data is None: + # TODO see similar in TLUTResource.resources_ci_list_append + return + + # Copypasted from TLUTResource.resources_ci_list_append + + resource_ci_data = resource_ci.file.data[ + resource_ci.range_start : resource_ci.range_end + ] + + assert resource_ci.siz in {G_IM_SIZ._4b, G_IM_SIZ._8b} + + if resource_ci.siz == G_IM_SIZ._4b: + v_max = max(max((b >> 4) & 0xF, b & 0xF) for b in resource_ci_data) + assert v_max < 16 + + if resource_ci.siz == G_IM_SIZ._8b: + v_max = max(resource_ci_data) + assert v_max < 256 + + new_min_count = v_max + 1 + + # end Copypasted + + cur_count = self.width * self.height + + assert cur_count >= new_min_count, ( + "TLUT resource", + self, + "is defined as having", + cur_count, + "colors, but there is an image using it as having at least", + new_min_count, + "colors:", + resource_ci, + ) + + def set_tlut(self, resource_tlut: "TextureResource"): + assert self.fmt == G_IM_FMT.CI, (self, resource_tlut) + if self.resource_tlut is not None: + HACK_NO_FAIL_MULTIPLE_TLUTS = self.name in { + "gZelda2Tex_003A08", + } + if self.resource_tlut != resource_tlut and not HACK_NO_FAIL_MULTIPLE_TLUTS: + # Technically not impossible so NotImplementedError + raise NotImplementedError( + "Color-indexed texture using two different TLUTs", + self, + resource_tlut, + ) + return + + # Assert resource_tlut is rgba16. + # Note it could be ia16, but that's not implemented + assert ( + resource_tlut.fmt == G_IM_FMT.RGBA and resource_tlut.siz == G_IM_SIZ._16b + ), resource_tlut + + self.resource_tlut = resource_tlut + assert self not in resource_tlut.resources_ci_list + resource_tlut.resources_ci_list_append(self) + + def try_parse_data(self, memory_context): + if self.fmt != G_IM_FMT.CI: + # Nothing to do + return RESOURCE_PARSE_SUCCESS + else: + if self.resource_tlut is None: + raise ResourceParseWaiting(waiting_for=["self.resource_tlut"]) + return RESOURCE_PARSE_SUCCESS + + def is_tlut(self): + """The result is only meaningful after all resources have been parsed + + (otherwise, for example, the dlists referencing this resource + as a tlut may not have been parsed and this would be considered + a regular texture) + """ + return len(self.resources_ci_list) != 0 + + def is_shared_tlut(self): + # Same caveat as is_tlut + return len(self.resources_ci_list) >= 2 + + def tlut_can_omit_tlut_info_from_users(self): + assert self.is_tlut() + return len(self.resources_ci_list) == 1 and self.alignment == 8 + + def tlut_get_count(self): + assert self.is_tlut() + return self.width * self.height + + def get_filename_stem(self): + format_name = f"{self.fmt.name.lower()}{self.siz.bpp}" + if self.fmt == G_IM_FMT.CI: + assert self.resource_tlut is not None + tlut_info = f"tlut_{self.resource_tlut.name}_{self.resource_tlut.elem_type}" + if not self.resource_tlut.tlut_can_omit_tlut_info_from_users(): + return f"{self.name}.{format_name}.{tlut_info}.{self.elem_type}" + else: + return f"{self.name}.{format_name}.{self.elem_type}" + elif self.is_tlut(): + if not self.tlut_can_omit_tlut_info_from_users(): + return f"{self.name}.tlut.{format_name}.{self.elem_type}" + else: + return f"{self.resources_ci_list[0].name}.tlut.{format_name}.{self.elem_type}" + else: + return f"{self.name}.{format_name}.{self.elem_type}" + + def write_extracted(self, memory_context): + if self.is_tlut(): + # TLUTs are extracted as part of the color-indexed textures using them + + def is_all_resources_fake(): + return all( + hasattr(res, "FAKE_FOR_BEST_EFFORT") + for res in self.resources_ci_list + ) + + if BEST_EFFORT: + if is_all_resources_fake(): + assert self.fmt == G_IM_FMT.RGBA + + if VERBOSE_BEST_EFFORT_TLUT_NO_REAL_USER and not getattr( + self, "HACK_ignore_orphaned_tlut", False + ): + print( + "BEST_EFFORT", + "no real (non-fake for best effort) ci resource uses this tlut", + ) + rich_pprint(self) + print( + " extracting the tlut as its own png", + self.extract_to_path.resolve().as_uri(), + "instead of relying on it being generated", + "\n (note while the result may build and match the tlut probably is", + "the wrong size since there was no ci image to take/guess its length from)", + ) + + # Extract the tlut as png instead of relying on + # it being generated from pngs using it, since + # there are no such pngs. + # (Copypaste of the general case (non-tlut) below): + data = self.file.data[self.range_start : self.range_end] + assert len(data) == self.range_end - self.range_start + write_n64_image_to_png( + self.extract_to_path, + self.width, + self.height, + self.fmt, + self.siz, + data, + ) + else: + # assert this TLUT is used by at least one real resource, + # otherwise it won't be generated by anything + assert not is_all_resources_fake() + return + + data = self.file.data[self.range_start : self.range_end] + assert len(data) == self.range_end - self.range_start + if self.fmt == G_IM_FMT.CI: + tlut_data = self.resource_tlut.file.data[ + self.resource_tlut.range_start : self.resource_tlut.range_end + ] + tlut_count = self.resource_tlut.tlut_get_count() + tlut_fmt = self.resource_tlut.fmt + write_n64_image_to_png_color_indexed( + self.extract_to_path, + self.width, + self.height, + self.fmt, + self.siz, + data, + tlut_data, + tlut_count, + tlut_fmt, + ) + else: + write_n64_image_to_png( + self.extract_to_path, self.width, self.height, self.fmt, self.siz, data + ) + + def write_c_declaration(self, h: io.TextIOBase): + if self.is_tlut(): + # TODO + h.writelines( + (f"//#define {self.symbol_name}_TLUT_COUNT {self.tlut_get_count()}\n",) + ) + else: + h.writelines( + ( + f"#define {self.width_name} {self.width}\n", + f"#define {self.height_name} {self.height}\n", + ) + ) + super().write_c_declaration(h) + + def get_h_includes(self): + return ("ultra64.h",) + + @reprlib.recursive_repr() + def __repr__(self): + return super().__repr__().removesuffix(")") + ( + f", fmt={self.fmt}, siz={self.siz}" + f", width={self.width}, height={self.height}" + f", elem_type={self.elem_type}" + f", resource_tlut={self.resource_tlut}, resources_ci_list={self.resources_ci_list}" + ")" + ) + + def __rich_repr__(self): + yield from super().__rich_repr__() + yield "fmt", self.fmt + yield "siz", self.siz + yield "width", self.width + yield "height", self.height + yield "elem_type", self.elem_type + yield "resource_tlut", self.resource_tlut + yield "resources_ci_list", self.resources_ci_list + + __rich_repr__.angular = True + + +class TLUTResource(TextureResource, can_size_be_unknown=True): + """ + Note this resource is only used for discovered TLUTs, not tluts from xmls + (TODO maybe change the xmls eventually) + Discovered TLUTs are different because their size is unknown + """ + + def __init__(self, file: File, range_start: int, name: str, fmt: G_IM_FMT): + assert fmt in {G_IM_FMT.RGBA, G_IM_FMT.IA} + + # just to make TextureResource.__init__ happy + # Note these values are picked so u64 elem_type is possible + fake_width = 4 + fake_height = 1 + + super().__init__( + file, range_start, name, fmt, G_IM_SIZ._16b, fake_width, fake_height + ) + + def tlut_get_count(self): + if self.range_end is None: + raise Exception("cannot tlut_get_count, unknown count yet") + return super().tlut_get_count() + + def resources_ci_list_append(self, resource_ci: "TextureResource"): + super().resources_ci_list_append(resource_ci) + + if resource_ci.file.data is None: + # Can't expand length, the user CI texture has no data attached + # TODO handle better? but idk + # maybe just a warning + return + + resource_ci_data = resource_ci.file.data[ + resource_ci.range_start : resource_ci.range_end + ] + + assert resource_ci.siz in {G_IM_SIZ._4b, G_IM_SIZ._8b} + + if resource_ci.siz == G_IM_SIZ._4b: + v_max = max(max((b >> 4) & 0xF, b & 0xF) for b in resource_ci_data) + assert v_max < 16 + + if resource_ci.siz == G_IM_SIZ._8b: + v_max = max(resource_ci_data) + assert v_max < 256 + + new_min_count = v_max + 1 + + assert self.height == 1 + if new_min_count > self.width: + # round width up to a multiple of 4, for elem_type=u64 + self.width = (new_min_count + 3) // 4 * 4 + + assert self.width <= 256 + + # TODO HACK this is hacky because not explicitly permitted, + # once set self.range_end is assumed to be fixed + # but surely it'll be fine (copium) + # In practice nothing should reference inside a tlut, + # so the resource has all the time to expand. + # A better implementation would be to give a "final warning" kind of signal + # to the resource on try_parse_data (add optional tryhard_parse_data ?) + assert self.siz == G_IM_SIZ._16b + self.range_end = self.range_start + self.width * self.height * 2 + + +def gfxdis( + *, + input_buffer: Union[bytes, memoryview], + output_callback: Optional[ + Callable[[bytes], None] # deviates a bit from gfxd, no count arg/return + ] = None, + enable_caps: set[pygfxd.GfxdCap] = { + pygfxd.GfxdCap.stop_on_end, + pygfxd.GfxdCap.emit_dec_color, + }, + target: pygfxd.gfx_ucode_t = pygfxd.gfxd_f3dex2, + vtx_callback: Optional[Callable[[int, int], int]] = None, + timg_callback: Optional[Callable[[int, int, int, int, int, int], int]] = None, + tlut_callback: Optional[Callable[[int, int, int], int]] = None, + mtx_callback: Optional[Callable[[int], int]] = None, + dl_callback: Optional[Callable[[int], int]] = None, + macro_fn: Optional[Callable[[], int]] = None, + arg_fn: Optional[Callable[[int], None]] = None, +): + for cap in ( + pygfxd.GfxdCap.stop_on_invalid, + pygfxd.GfxdCap.stop_on_end, + pygfxd.GfxdCap.emit_dec_color, + pygfxd.GfxdCap.emit_q_macro, + pygfxd.GfxdCap.emit_ext_macro, + ): + if cap in enable_caps: + pygfxd.gfxd_enable(cap) + else: + pygfxd.gfxd_disable(cap) + + pygfxd.gfxd_target(target) + + pygfxd.gfxd_input_buffer(bytes(input_buffer)) + + uncaught_exc_infos = [] + + # output_callback + + if output_callback: + + def output_callback_wrapper(buf, count): + try: + output_callback(buf) + except: + import sys + + exc_info = sys.exc_info() + uncaught_exc_infos.append(exc_info) + return count + + else: + + def output_callback_wrapper(buf, count): + return count + + pygfxd.gfxd_output_callback(output_callback_wrapper) + + # vtx_callback + + if vtx_callback: + + def vtx_callback_wrapper(vtx, num): + try: + ret = vtx_callback(vtx, num) + except: + import sys + + exc_info = sys.exc_info() + uncaught_exc_infos.append(exc_info) + + ret = 0 + return ret + + else: + + def vtx_callback_wrapper(vtx, num): + return 0 + + pygfxd.gfxd_vtx_callback(vtx_callback_wrapper) + + # timg_callback + + if timg_callback: + + def timg_callback_wrapper(timg, fmt, siz, width, height, pal): + try: + ret = timg_callback(timg, fmt, siz, width, height, pal) + assert isinstance(ret, int) + except: + import sys + + exc_info = sys.exc_info() + uncaught_exc_infos.append(exc_info) + + ret = 0 + return ret + + else: + + def timg_callback_wrapper(timg, fmt, siz, width, height, pal): + return 0 + + pygfxd.gfxd_timg_callback(timg_callback_wrapper) + + # tlut_callback + + if tlut_callback: + + def tlut_callback_wrapper(tlut, idx, count): + try: + ret = tlut_callback(tlut, idx, count) + except: + import sys + + exc_info = sys.exc_info() + uncaught_exc_infos.append(exc_info) + + ret = 0 + return ret + + else: + + def tlut_callback_wrapper(tlut, idx, count): + return 0 + + pygfxd.gfxd_tlut_callback(tlut_callback_wrapper) + + # mtx_callback + + if mtx_callback: + + def mtx_callback_wrapper(mtx): + try: + ret = mtx_callback(mtx) + except: + import sys + + exc_info = sys.exc_info() + uncaught_exc_infos.append(exc_info) + + ret = 0 + return ret + + else: + + def mtx_callback_wrapper(mtx): + return 0 + + pygfxd.gfxd_mtx_callback(mtx_callback_wrapper) + + # dl_callback + + if dl_callback: + + def dl_callback_wrapper(dl): + try: + ret = dl_callback(dl) + except: + import sys + + exc_info = sys.exc_info() + uncaught_exc_infos.append(exc_info) + + ret = 0 + return ret + + else: + + def dl_callback_wrapper(dl): + return 0 + + pygfxd.gfxd_dl_callback(dl_callback_wrapper) + + # macro_fn + + if macro_fn: + + def macro_fn_wrapper(): + try: + ret = macro_fn() + except: + import sys + + exc_info = sys.exc_info() + uncaught_exc_infos.append(exc_info) + + ret = 0 + + # TODO consider: + if uncaught_exc_infos: + pygfxd.gfxd_input_buffer( + b"" + ) # interrupt current execution TODO check if this is safe and if it works + ret = 1 + + return ret + + else: + + def macro_fn_wrapper(): + ret = pygfxd.gfxd_macro_dflt() + + # TODO consider: + if uncaught_exc_infos: + pygfxd.gfxd_input_buffer(b"") # TODO see same line above + ret = 1 + + return ret + + pygfxd.gfxd_macro_fn(macro_fn_wrapper) + + # arg_fn + + if arg_fn: + + def arg_fn_wrapper(arg_num): + try: + arg_fn(arg_num) + except: + import sys + + exc_info = sys.exc_info() + uncaught_exc_infos.append(exc_info) + + pygfxd.gfxd_arg_fn(arg_fn_wrapper) + else: + pygfxd.gfxd_arg_fn(None) + + # Execute + + pygfxd.gfxd_execute() + + # The offset is in bytes and indicates the last command, + # so add 8 (sizeof(Gfx)) + size = pygfxd.gfxd_macro_offset() + 8 + + if uncaught_exc_infos: + import traceback + + msg = "There were uncaught python errors in callbacks during gfxd execution." + + print() + print(msg) + print("vvv See below for a list of the traces of the uncaught errors:") + + for exc_info in uncaught_exc_infos: + import sys + + print() + traceback.print_exception(*exc_info, file=sys.stdout) + + print() + print(msg) + print("^^^ See above for a list of the traces of the uncaught errors.") + + raise Exception( + msg, + "See the standard output for a list of the traces of the uncaught errors.", + uncaught_exc_infos, + ) + + return size + + +class StringWrapper: + def __init__( + self, + data: Union[str, bytes], + max_line_length, + writer: Callable[[Union[str, bytes]], None], + ): + self.max_line_length = max_line_length + self.pending_data = data + self.writer = writer + self.newline_char = "\n" if isinstance(data, str) else b"\n" + self.space_char = " " if isinstance(data, str) else b" " + + def append(self, data: Union[str, bytes]): + self.pending_data += data + self.proc() + + def proc(self, flush=False): + while len(self.pending_data) > self.max_line_length or ( + flush and self.pending_data + ): + i = self.pending_data.find(self.newline_char, 0, self.max_line_length) + if i >= 0: + i += 1 + self.writer(self.pending_data[:i]) + self.pending_data = self.pending_data[i:] + continue + + i = self.pending_data.rfind(self.space_char, 1, self.max_line_length) + if i < 0: + i = self.pending_data.find(self.space_char, 1) + if i < 0: + if flush: + i = len(self.pending_data) + else: + # Avoid adding a line return in the middle of a word + return + self.writer(self.pending_data[:i]) + self.pending_data = self.pending_data[i:] + if not flush or self.pending_data: + self.writer(self.newline_char) + + def flush(self): + self.proc(flush=True) + + +class Ucode(enum.Enum): + f3dex = pygfxd.gfxd_f3dex + f3dex2 = pygfxd.gfxd_f3dex2 + + def __init__(self, gfxd_ucode: pygfxd.gfx_ucode_t): + self.gfxd_ucode = gfxd_ucode + + +# TODO probably need to split TLUTResource from TextureResource +# to achieve cleaner code, +# tluts behave very differently + + +# TODO maybe refactor this once it works tm +class ColorIndexedTexturesManager: + from dataclasses import dataclass + + @dataclass + class Tex: + timg: int + fmt: G_IM_FMT + siz: G_IM_SIZ + width: int + height: int + pal: int + + @dataclass + class Tlut: + tlut: int + idx: int + count: int + + @dataclass + class CIState: + tlut_mode: G_TT + tluts_count: int + tluts: dict[int, "ColorIndexedTexturesManager.Tlut"] + texs: list["ColorIndexedTexturesManager.Tex"] + + def __init__(self, *, HACK_late_SetTextureLUT=False): + self.cur_tlut_mode: G_TT = None + + self.cur_tluts_count: int = None + self.cur_tluts: dict[int, ColorIndexedTexturesManager.Tlut] = dict() + self.cur_texs: list[ColorIndexedTexturesManager.Tex] = [] + + self.ci_states: list[ColorIndexedTexturesManager.CIState] = [] + + # Rarely, + # gsDPSetTextureLUT comes after gsDPLoadTextureBlock and gsDPLoadTLUT, + # instead of before + self.HACK_late_SetTextureLUT = HACK_late_SetTextureLUT + + def ci_timg(self, timg, fmt: G_IM_FMT, siz: G_IM_SIZ, width, height, pal): + if VERBOSE_ColorIndexedTexturesManager: + print( + "ColorIndexedTexturesManager.ci_timg", + hex(timg), + fmt, + siz, + width, + height, + pal, + ) + assert fmt == G_IM_FMT.CI + if not self.HACK_late_SetTextureLUT: + assert self.cur_tlut_mode != G_TT.NONE + + self.cur_texs.append( + ColorIndexedTexturesManager.Tex(timg, fmt, siz, width, height, pal) + ) + + def tlut(self, tlut, idx, count): + if VERBOSE_ColorIndexedTexturesManager: + print("ColorIndexedTexturesManager.tlut", hex(tlut), idx, count) + if idx == -1: + # HACK idx==-1 may be a libgfxd bug? + assert count == 256 + idx = 0 + if not self.HACK_late_SetTextureLUT: + assert self.cur_tlut_mode != G_TT.NONE + if self.cur_tluts_count != count: + self.cur_tluts.clear() # TODO ? idk. (at worst it will cause errors) + self.cur_tluts_count = count + self.cur_tluts[idx] = ColorIndexedTexturesManager.Tlut(tlut, idx, count) + + def tlut_mode(self, tt: G_TT): + if VERBOSE_ColorIndexedTexturesManager: + print("ColorIndexedTexturesManager.tlut_mode", tt) + if self.cur_tlut_mode != tt: + if not self.HACK_late_SetTextureLUT: + self.cur_tluts.clear() # TODO ? idk. (at worst it will cause errors) + self.cur_tlut_mode = tt + + def commit_state(self): + if self.cur_tlut_mode == G_TT.NONE: + return + if not self.cur_texs: + return + assert self.cur_tluts + assert self.cur_tluts_count is not None + if self.cur_tlut_mode is None: + if BEST_EFFORT: + # Some dlists (eg gMegamiPiece2DL) inherit G_TT_RGBA16 + # since ia16 is uncommon if not unused, just default to that + self.cur_tlut_mode = G_TT.RGBA16 + assert self.cur_tlut_mode is not None + cur_state = ColorIndexedTexturesManager.CIState( + self.cur_tlut_mode, + self.cur_tluts_count, + self.cur_tluts.copy(), + self.cur_texs, + ) + self.cur_texs = [] + self.ci_states.append(cur_state) + if VERBOSE_ColorIndexedTexturesManager: + print( + "ColorIndexedTexturesManager.commit_state", + "cur_state =", + cur_state, + ) + + def report_states(self, reporter: Resource, memory_context: "MemoryContext"): + if VERBOSE_ColorIndexedTexturesManager: + print("ColorIndexedTexturesManager.report_states") + for ci_state in self.ci_states: + if VERBOSE_ColorIndexedTexturesManager: + print(" ci_state =", ci_state) + assert ci_state.tlut_mode != G_TT.NONE + for tex in ci_state.texs: + if VERBOSE_ColorIndexedTexturesManager: + print(" tex =", tex) + assert tex.fmt == G_IM_FMT.CI + + # HACK + if ( + reporter.file.name + in { + "jyasinzou_room_5", + "jyasinzou_room_25", + } + and ci_state.tluts_count == 256 + and tex.siz == G_IM_SIZ._4b + ): + # For some reason jyasinzou_room_5DL_008EC0 has this: + """ + gsDPLoadTextureBlock_4b(jyasinzou_sceneTex_019320, G_IM_FMT_CI, 64, 64, 0, G_TX_NOMIRROR | G_TX_WRAP, G_TX_NOMIRROR + | G_TX_WRAP, 6, 6, G_TX_NOLOD, G_TX_NOLOD), + gsDPLoadTLUT_pal16(0, jyasinzou_sceneTLUT_018000), + gsDPLoadTextureBlock(jyasinzou_room_5Tex_00DFC8, G_IM_FMT_CI, G_IM_SIZ_8b, 64, 32, 0, G_TX_NOMIRROR | G_TX_WRAP, + G_TX_NOMIRROR | G_TX_WRAP, 6, 5, G_TX_NOLOD, G_TX_NOLOD), + gsDPLoadTLUT_pal256(jyasinzou_sceneTLUT_017DE0), + """ + # (where the first texture & tlut loads are useless, overriden by the latter two) + + # -> Ignore the first texture (in `tex` at this point) + + # similar thing in jyasinzou_room_25DL_005050 + + # (note the condition to restrict this to the above cases is very broad, + # just checking reporter.file.name, so this may happen more in those files + # and not have been caught and documented here) + + continue + + # Not a proper hard requirement but if this fails + # something is probably wrong, look at details then + assert ( + ci_state.tluts_count + == { + G_IM_SIZ._4b: 16, + G_IM_SIZ._8b: 256, + }[tex.siz] + ), (reporter, ci_state, tex) + + if ci_state.tluts_count > 16: + assert ci_state.tluts.keys() == {0}, ci_state.tluts + + resource = memory_context.report_resource_at_segmented( + reporter, + tex.timg, + TextureResource, + lambda file, offset: TextureResource( + file, + offset, + f"{reporter.name}_{offset:08X}_CITex", + tex.fmt, + tex.siz, + tex.width, + tex.height, + ), + ) + + tlut = ci_state.tluts[tex.pal] + assert tlut.idx == tex.pal + assert tlut.count == ci_state.tluts_count + + resource_tlut = memory_context.report_resource_at_segmented( + reporter, + tlut.tlut, + # TLUTs declared in xmls use so are TextureResource, + # so we can only expects a TextureResource + # (TLUTResource is a subclass of TextureResource) + TextureResource, + lambda file, offset: TLUTResource( + file, + offset, + f"{reporter.name}_{offset:08X}_TLUT", + { + G_TT.RGBA16: G_IM_FMT.RGBA, + G_TT.IA16: G_IM_FMT.IA, + }[ci_state.tlut_mode], + ), + ) + + resource.set_tlut(resource_tlut) + + +class DListResource(Resource, can_size_be_unknown=True): + def __init__( + self, + file: File, + range_start: int, + name: str, + *, + target_ucode: Ucode = Ucode.f3dex2, + ): + super().__init__(file, range_start, None, name) + self.target_ucode = target_ucode + self.ignored_raw_pointers: set[int] = set() + + def try_parse_data(self, memory_context): + offset = self.range_start + + if VERBOSE2: + print(self.name, hex(offset)) + + def vtx_cb(vtx, num): + if vtx in self.ignored_raw_pointers: + return 0 + + # TODO be smarter about buffer merging + # (don't merge buffers from two different DLs, if they can be split cleanly) + # if that even happens + memory_context.mark_resource_buffer_at_segmented( + self, + VtxArrayResource, + f"{self.name}_{vtx:08X}_Vtx", + vtx, + vtx + num * VtxArrayResource.element_cdata_ext.size, + ) + return 0 + + ci_tex_manager = ColorIndexedTexturesManager( + # TODO + HACK_late_SetTextureLUT=(self.name in {"gEponaHeadLimb_0600AC20_DL"}) + ) + + def timg_cb(timg, fmt, siz, width, height, pal): + if timg in self.ignored_raw_pointers: + return 0 + + g_fmt = G_IM_FMT.by_i[fmt] + g_siz = G_IM_SIZ.by_i[siz] + + if g_fmt == G_IM_FMT.CI: + ci_tex_manager.ci_timg(timg, g_fmt, g_siz, width, height, pal) + else: + memory_context.report_resource_at_segmented( + self, + timg, + TextureResource, + lambda file, offset: TextureResource( + file, + offset, + f"{self.name}_{offset:08X}_Tex", + g_fmt, + g_siz, + width, + height, + ), + ) + return 0 + + def tlut_cb(tlut, idx, count): + if tlut in self.ignored_raw_pointers: + return 0 + + ci_tex_manager.tlut(tlut, idx, count) + return 0 + + def mtx_cb(mtx): + if mtx in self.ignored_raw_pointers: + return 0 + + memory_context.report_resource_at_segmented( + self, + mtx, + MtxResource, + lambda file, offset: MtxResource( + file, offset, f"{self.name}_{mtx:08X}_Mtx" + ), + ) + return 0 + + def dl_cb(dl): + if dl in self.ignored_raw_pointers: + return 0 + + memory_context.report_resource_at_segmented( + self, + dl, + DListResource, + lambda file, offset: DListResource( + file, + offset, + f"{self.name}_{dl:08X}_DL", + target_ucode=self.target_ucode, + ), + ) + return 0 + + def macro_fn(): + tt = pygfxd.gfxd_value_by_type(pygfxd.GfxdArgType.Tt, 0) + if tt is not None: + tt = tt[1] + else: + othermodehi = pygfxd.gfxd_value_by_type( + pygfxd.GfxdArgType.Othermodehi, 0 + ) + if othermodehi is not None: + othermodehi = othermodehi[1] + tt = othermodehi & (0b11 << G_MDSFT_TEXTLUT) + else: + tt = None + if tt is not None: + g_tt = G_TT.by_i[tt] + ci_tex_manager.tlut_mode(g_tt) + + macro_id = pygfxd.gfxd_macro_id() + if macro_id in { + pygfxd.GfxdMacroId.SP1Triangle, + pygfxd.GfxdMacroId.SP2Triangles, + }: + ci_tex_manager.commit_state() + + return pygfxd.gfxd_macro_dflt() + + size = gfxdis( + input_buffer=self.file.data[self.range_start :], + target=self.target_ucode.gfxd_ucode, + vtx_callback=vtx_cb, + timg_callback=timg_cb, + tlut_callback=tlut_cb, + mtx_callback=mtx_cb, + dl_callback=dl_cb, + macro_fn=macro_fn, + ) + + # Also commit state at the end of the display list. + # This handles "material" dlists that only load a texture, + # without drawing geometry. + ci_tex_manager.commit_state() + + ci_tex_manager.report_states(self, memory_context) + + self.range_end = self.range_start + size + + if VERBOSE2: + print(self.name, hex(offset), hex(self.range_end)) + + return RESOURCE_PARSE_SUCCESS + + def get_c_declaration_base(self): + if hasattr(self, "HACK_IS_STATIC_ON"): + length = (self.range_end - self.range_start) // 8 + return f"Gfx {self.symbol_name}[{length}]" + return f"Gfx {self.symbol_name}[]" + + def get_c_reference(self, resource_offset: int): + if resource_offset == 0: + return self.symbol_name + else: + raise ValueError() + + def write_extracted(self, memory_context): + def macro_fn(): + pygfxd.gfxd_puts(INDENT) + ret = pygfxd.gfxd_macro_dflt() + pygfxd.gfxd_puts(",\n") + return ret + + def arg_fn_handle_Dim(arg_num: int): + timg = pygfxd.gfxd_value_by_type(pygfxd.GfxdArgType.Timg, 0) + if timg is None: + return False + _, timg_segmented, _ = timg + dim_args_i = [] + for arg_i in range(pygfxd.gfxd_arg_count()): + if pygfxd.gfxd_arg_type(arg_i) == pygfxd.GfxdArgType.Dim: + dim_args_i.append(arg_i) + assert arg_num in dim_args_i + assert len(dim_args_i) <= 2 + if len(dim_args_i) != 2: + return False + width_arg_i, height_arg_i = dim_args_i + try: + timg_resolved = memory_context.resolve_segmented(timg_segmented) + except UnmappedAddressError: + # TODO store failed resolutions somewhere, for later printing + # (in general, it would be nice to fail less and *firmly* warn more instead, + # even if it means having compilation fail on purpose (#error)) + return False + try: + resolved_resource = timg_resolved.get_resource(TextureResource) + except UnexpectedResourceTypeError: + # TODO investigate. eg spot18 uses 0x0800_0000 as both a DL and Tex ? + return False + + assert isinstance(resolved_resource, TextureResource), ( + hex(timg_segmented), + resolved_resource, + resolved_resource.__class__, + ) + width_arg_value = pygfxd.gfxd_arg_value(width_arg_i)[1] + height_arg_value = pygfxd.gfxd_arg_value(height_arg_i)[1] + if (resolved_resource.width, resolved_resource.height) == ( + width_arg_value, + height_arg_value, + ): + if arg_num == width_arg_i: + if resolved_resource.width_name: + pygfxd.gfxd_puts(resolved_resource.width_name) + return True + else: + assert arg_num == height_arg_i + if resolved_resource.height_name: + pygfxd.gfxd_puts(resolved_resource.height_name) + return True + else: + HACK_no_warn_bad_dims_DLs = { + "sPresentedByNintendoDL", # uses gsDPLoadTextureTile, in which height is unused, so disassembled as 0 by gfxdis + "gMantUnusedMaterialDL", # DList bug + "gSunDL", # DList loads bigger chunks than the individual texture pieces (overlaps) + } + HACK_no_warn_bad_dims_Texs = { + "gPoeComposerFlatHeadDL_000060E0_Tex", # used as both rgba16 16x16 and rgba16 8x8 + "gDekuStickTex", # used as both i8 8x8 and i8 16x16 + "gHilite1Tex", # used as both rgba16 16x16 and rgba16 32x32 + "gHilite2Tex", # used as both rgba16 16x16 and rgba16 32x32 + "gUnknownCircle4Tex", # used as both i8 16x16 and rgba16 32x32 + "gLinkChildLowerBootTex", # used as both ci8 32x32 and ci8 16x16 + "gDecorativeFlameMaskTex", # used as both i4 32x128 and i4 32x64 + } + if ( + arg_num == width_arg_i + and self.name not in HACK_no_warn_bad_dims_DLs + and resolved_resource.name not in HACK_no_warn_bad_dims_Texs + ): + print( + "Unexpected texture dimensions used: in dlist =", + self, + "texture =", + resolved_resource, + "texture resource has WxH =", + (resolved_resource.width, resolved_resource.height), + "but dlist uses WxH =", + (width_arg_value, height_arg_value), + ) + pygfxd.gfxd_puts( + " /* ! Unexpected texture dimensions !" + f" DL={width_arg_value}x{height_arg_value}" + f" vs Tex={resolved_resource.width}x{resolved_resource.height} */ " + ) + return False + + arg_fn_handlers = { + pygfxd.GfxdArgType.Dim: arg_fn_handle_Dim, + } + + def arg_fn(arg_num: int): + arg_type = pygfxd.gfxd_arg_type(arg_num) + arg_handler = arg_fn_handlers.get(arg_type) + + if arg_handler is not None: + inhibit_default = arg_handler(arg_num) + else: + inhibit_default = False + + if not inhibit_default: + pygfxd.gfxd_arg_dflt(arg_num) + + def vtx_cb(vtx, num): + if vtx in self.ignored_raw_pointers: + return 0 + + pygfxd.gfxd_puts(memory_context.get_c_reference_at_segmented(vtx)) + return 1 + + def timg_cb(timg, fmt, siz, width, height, pal): + if timg in self.ignored_raw_pointers: + return 0 + + try: + timg_c_ref = memory_context.get_c_reference_at_segmented(timg) + # except NoSegmentBaseError: # TODO + # timg_c_ref = None + except ValueError: + if BEST_EFFORT: + # (turns out I needed this because of a mistake in a xml so it can be useful) + import traceback + + print("vvv /* BAD TIMG REF */ vvv") + traceback.print_exc() + pygfxd.gfxd_puts("/* BAD TIMG REF */") + return 0 + else: + raise + if timg_c_ref: + pygfxd.gfxd_puts(timg_c_ref) + return 1 + return 0 + + def tlut_cb(tlut, idx, count): + if tlut in self.ignored_raw_pointers: + return 0 + + tlut_c_ref = memory_context.get_c_reference_at_segmented(tlut) + pygfxd.gfxd_puts(tlut_c_ref) + return 1 + + def mtx_cb(mtx): + if mtx in self.ignored_raw_pointers: + return 0 + + mtx_c_ref = memory_context.get_c_reference_at_segmented(mtx) + pygfxd.gfxd_puts(mtx_c_ref) + return 1 + + def dl_cb(dl): + if dl in self.ignored_raw_pointers: + return 0 + + dl_c_ref = memory_context.get_c_reference_at_segmented(dl) + pygfxd.gfxd_puts(dl_c_ref) + return 1 + + with self.extract_to_path.open("wb") as f: + if not self.braces_in_source: + f.write(b"{\n") + + out_string_wrapper = StringWrapper(b"", 120, f.write) + + def output_cb(buf: bytes): + out_string_wrapper.append(buf) + + gfxdis( + input_buffer=self.file.data[self.range_start : self.range_end], + output_callback=output_cb, + enable_caps={pygfxd.GfxdCap.emit_dec_color}, + target=self.target_ucode.gfxd_ucode, + vtx_callback=vtx_cb, + timg_callback=timg_cb, + tlut_callback=tlut_cb, + mtx_callback=mtx_cb, + dl_callback=dl_cb, + macro_fn=macro_fn, + arg_fn=arg_fn, + ) + + out_string_wrapper.flush() + + if not self.braces_in_source: + f.write(b"}\n") + + def get_c_includes(self): + return ( + # TODO these are not always needed: + "sys_matrix.h", # for gIdentityMtx + ) + + def get_h_includes(self): + return ("ultra64.h",) + + +def report_gfx_segmented(resource: Resource, memory_context: "MemoryContext", v): + assert isinstance(v, int) + address = v + if address != 0: + memory_context.report_resource_at_segmented( + resource, + address, + DListResource, + lambda file, offset: DListResource( + file, + offset, + f"{resource.name}_{address:08X}_DL", + ), + ) + + +def write_gfx_segmented( + resource: Resource, + memory_context: "MemoryContext", + v, + wctx: CDataExtWriteContext, +): + assert isinstance(v, int) + address = v + wctx.f.write(wctx.line_prefix) + if address == 0: + wctx.f.write("NULL") + else: + wctx.f.write(memory_context.get_c_reference_at_segmented(address)) + return True + + +cdata_ext_gfx_segmented = ( + CDataExt_Value("I").set_report(report_gfx_segmented).set_write(write_gfx_segmented) +) + +VERBOSE2 = False diff --git a/tools/assets/extract/extase_oot64/misc_resources.py b/tools/assets/extract/extase_oot64/misc_resources.py new file mode 100644 index 0000000000..6f5f3a8265 --- /dev/null +++ b/tools/assets/extract/extase_oot64/misc_resources.py @@ -0,0 +1,63 @@ +# SPDX-FileCopyrightText: © 2025 ZeldaRET +# SPDX-License-Identifier: CC0-1.0 + +import struct + +from ..extase import ( + RESOURCE_PARSE_SUCCESS, + File, + Resource, +) + +from tools import csdis + + +class CutsceneResource(Resource, can_size_be_unknown=True): + + def __init__(self, file: File, range_start: int, name: str): + super().__init__(file, range_start, None, name) + + def try_parse_data(self, memory_context): + assert self.range_start % 4 == 0 + data = self.file.data[self.range_start :] + num_bytes = len(data) + if num_bytes % 4 != 0: + data = data[: -(num_bytes % 4)] + data_words = [unpacked[0] for unpacked in struct.iter_unpack(">I", data)] + size_words, cs_source = csdis.disassemble_cutscene(data_words) + self.range_end = self.range_start + 4 * size_words + self.cs_source = cs_source + return RESOURCE_PARSE_SUCCESS + + def get_c_reference(self, resource_offset: int): + if resource_offset == 0: + return self.symbol_name + else: + raise ValueError + + extracted_path_suffix = ".inc.c" + + def get_filename_stem(self): + return f"{self.name}.csdata" + + def write_extracted(self, memory_context): + with self.extract_to_path.open("w") as f: + if not self.braces_in_source: + f.write("{\n") + f.write(self.cs_source) + if not self.braces_in_source: + f.write("}\n") + + def get_c_declaration_base(self): + return f"CutsceneData {self.symbol_name}[]" + + def get_c_includes(self): + return ( + "z64cutscene_commands.h", + # TODO these are not always needed: + "z64ocarina.h", # for OCARINA_ACTION_* + "z64player.h", # for PLAYER_CUEID_* + ) + + def get_h_includes(self): + return ("z64cutscene.h",) diff --git a/tools/assets/extract/extase_oot64/playeranim_resources.py b/tools/assets/extract/extase_oot64/playeranim_resources.py new file mode 100644 index 0000000000..b002f91ff9 --- /dev/null +++ b/tools/assets/extract/extase_oot64/playeranim_resources.py @@ -0,0 +1,102 @@ +# SPDX-FileCopyrightText: © 2025 ZeldaRET +# SPDX-License-Identifier: CC0-1.0 + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ..extase import MemoryContext + +from ..extase.cdata_resources import ( + CDataResource, + CDataArrayResource, + CDataExt_Struct, + CDataExt_Value, + CDataExtWriteContext, + fmt_hex_s, +) + + +class PlayerAnimationDataResource(CDataArrayResource): + elem_cdata_ext = CDataExt_Value("h").set_write_str_v(lambda v: fmt_hex_s(v)) + + def __init__(self, file, range_start, name): + super().__init__(file, range_start, name) + self.frame_count_name = f"FRAMECOUNT_{self.symbol_name}" + + def set_frame_count(self, frame_count: int): + self.set_length(frame_count * (22 * 3 + 1)) + self.frame_count = frame_count + + def write_c_declaration(self, h): + h.write(f"#define {self.frame_count_name} {self.frame_count}\n") + super().write_c_declaration(h) + + def get_c_declaration_base(self): + return f"s16 {self.symbol_name}[{self.frame_count_name} * (PLAYER_LIMB_MAX * 3 + 1)]" + + def get_h_includes(self): + return ("ultra64.h", "z64player.h") + + +class PlayerAnimationResource(CDataResource): + + def report(resource, memory_context: "MemoryContext", v): + assert isinstance(v, dict) + segment = v["segment"] + assert isinstance(segment, int) + player_animation_data_res = memory_context.report_resource_at_segmented( + resource, + segment, + PlayerAnimationDataResource, + lambda file, offset: PlayerAnimationDataResource( + file, offset, f"{resource.name}_{segment:08X}_PlayerAnimData" + ), + ) + player_animation_data_res.set_frame_count(v["common"]["frameCount"]) + + def write_frameCount( + resource, memory_context: "MemoryContext", v, wctx: CDataExtWriteContext + ): + address = resource.cdata_unpacked["segment"] + assert isinstance(address, int) + wctx.f.write(wctx.line_prefix) + wctx.f.write( + memory_context.resolve_segmented(address) + .get_resource(PlayerAnimationDataResource) + .frame_count_name + ) + return True + + def write_segment( + resource, memory_context: "MemoryContext", v, wctx: CDataExtWriteContext + ): + assert isinstance(v, int) + address = v + wctx.f.write(wctx.line_prefix) + wctx.f.write(memory_context.get_c_reference_at_segmented(address)) + return True + + cdata_ext = CDataExt_Struct( + ( + ( + "common", + CDataExt_Struct( + (("frameCount", CDataExt_Value("h").set_write(write_frameCount)),) + ), + ), + ("pad2", CDataExt_Value.pad16), + ("segment", CDataExt_Value("I").set_write(write_segment)), + ) + ).set_report(report) + + def get_c_reference(self, resource_offset: int): + if resource_offset == 0: + return f"&{self.symbol_name}" + else: + raise ValueError() + + def get_c_declaration_base(self): + return f"LinkAnimationHeader {self.symbol_name}" + + def get_h_includes(self): + return ("z64animation.h",) diff --git a/tools/assets/extract/extase_oot64/room_shape_resources.py b/tools/assets/extract/extase_oot64/room_shape_resources.py new file mode 100644 index 0000000000..740adbf72d --- /dev/null +++ b/tools/assets/extract/extase_oot64/room_shape_resources.py @@ -0,0 +1,557 @@ +# SPDX-FileCopyrightText: © 2025 ZeldaRET +# SPDX-License-Identifier: CC0-1.0 + +import enum +from typing import TYPE_CHECKING + +from .. import oot64_data + +if TYPE_CHECKING: + from ..extase.memorymap import MemoryContext + + +from ..extase import ( + Resource, + File, + RESOURCE_PARSE_SUCCESS, +) +from ..extase.cdata_resources import ( + CDataResource, + CDataArrayNamedLengthResource, + CDataExt_Struct, + CDataExt_Value, + CDataExtWriteContext, + cdata_ext_Vec3s, +) + +from . import dlist_resources + + +class RoomShapeType(enum.Enum): + ROOM_SHAPE_TYPE_NORMAL = 0 + ROOM_SHAPE_TYPE_IMAGE = enum.auto() + ROOM_SHAPE_TYPE_CULLABLE = enum.auto() + + +class RoomShapeImageAmountType(enum.Enum): + ROOM_SHAPE_IMAGE_AMOUNT_SINGLE = 1 + ROOM_SHAPE_IMAGE_AMOUNT_MULTI = enum.auto() + + +def report_room_shape_at_segmented( + reporter: Resource, memory_context: "MemoryContext", address: int, name_base: str +): + def new_resource_pointed_to(file: File, offset: int): + resource_type = get_room_shape_resource_type(file, offset) + name_suffix = resource_type.__name__.removesuffix("Resource") + return resource_type( + file, + offset, + f"{name_base}_{address:08X}_{name_suffix}", + ) + + memory_context.report_resource_at_segmented( + reporter, address, Resource, new_resource_pointed_to + ) + + +def get_room_shape_resource_type(file: File, offset: int): + room_shape_type_int = file.data[offset] + room_shape_type = RoomShapeType(room_shape_type_int) + + resource_type = None + + if room_shape_type == RoomShapeType.ROOM_SHAPE_TYPE_NORMAL: + resource_type = RoomShapeNormalResource + + if room_shape_type == RoomShapeType.ROOM_SHAPE_TYPE_IMAGE: + room_shape_image_amount_type_int = file.data[offset + 1] + room_shape_image_amount_type = RoomShapeImageAmountType( + room_shape_image_amount_type_int + ) + if ( + room_shape_image_amount_type + == RoomShapeImageAmountType.ROOM_SHAPE_IMAGE_AMOUNT_SINGLE + ): + resource_type = RoomShapeImageSingleResource + if ( + room_shape_image_amount_type + == RoomShapeImageAmountType.ROOM_SHAPE_IMAGE_AMOUNT_MULTI + ): + resource_type = RoomShapeImageMultiResource + + if room_shape_type == RoomShapeType.ROOM_SHAPE_TYPE_CULLABLE: + resource_type = RoomShapeCullableResource + + assert resource_type is not None + + return resource_type + + +cdata_ext_RoomShapeBase = CDataExt_Struct( + ( + ( + "type", + CDataExt_Value("B").set_write_str_v(oot64_data.get_room_shape_type_name), + ), + ) +) + +cdata_ext_RoomShapeDListsEntry = CDataExt_Struct( + ( + ("opa", dlist_resources.cdata_ext_gfx_segmented), + ("xlu", dlist_resources.cdata_ext_gfx_segmented), + ) +) + + +# TODO check if this even needs a named length +class RoomShapeNormalEntryArrayResource(CDataArrayNamedLengthResource): + elem_cdata_ext = cdata_ext_RoomShapeDListsEntry + + def get_c_declaration_base(self): + return f"RoomShapeDListsEntry {self.symbol_name}[{self.length_name}]" + + def get_h_includes(self): + return ("z64room.h",) + + +class RoomShapeNormalResource(CDataResource): + def write_numEntries( + resource, memory_context: "MemoryContext", v, wctx: CDataExtWriteContext + ): + address = resource.cdata_unpacked["entries"] + assert isinstance(address, int) + wctx.f.write(wctx.line_prefix) + wctx.f.write(memory_context.get_c_expression_length_at_segmented(address)) + return True + + def report_entries(resource, memory_context: "MemoryContext", v): + assert isinstance(v, int) + address = v + entries_resource = memory_context.report_resource_at_segmented( + resource, + address, + RoomShapeNormalEntryArrayResource, + lambda file, offset: RoomShapeNormalEntryArrayResource( + file, offset, f"{resource.name}_{address:08X}_DListsEntries" + ), + ) + assert isinstance(entries_resource, RoomShapeNormalEntryArrayResource) + numEntries = resource.cdata_unpacked["numEntries"] + assert isinstance(numEntries, int) + entries_resource.set_length(numEntries) + + def write_entries( + resource, memory_context: "MemoryContext", v, wctx: CDataExtWriteContext + ): + assert isinstance(v, int) + address = v + wctx.f.write(wctx.line_prefix) + wctx.f.write(memory_context.get_c_reference_at_segmented(address)) + return True + + def write_entriesEnd( + resource, memory_context: "MemoryContext", v, wctx: CDataExtWriteContext + ): + address = resource.cdata_unpacked["entries"] + assert isinstance(address, int) + wctx.f.write(wctx.line_prefix) + wctx.f.write(memory_context.get_c_reference_at_segmented(address)) + wctx.f.write(" + ") + wctx.f.write(memory_context.get_c_expression_length_at_segmented(address)) + return True + + cdata_ext = CDataExt_Struct( + ( + ("base", cdata_ext_RoomShapeBase), + ("numEntries", CDataExt_Value("B").set_write(write_numEntries)), + ("pad2", CDataExt_Value.pad16), + ( + "entries", + CDataExt_Value("I").set_report(report_entries).set_write(write_entries), + ), + ( + "entriesEnd", + CDataExt_Value("I").set_write(write_entriesEnd), + ), + ) + ) + + def get_c_declaration_base(self): + return f"RoomShapeNormal {self.symbol_name}" + + def get_c_reference(self, resource_offset: int): + if resource_offset == 0: + return f"&{self.symbol_name}" + else: + raise ValueError + + def get_c_includes(self): + return ("array_count.h",) + + def get_h_includes(self): + return ("z64room.h",) + + +class RoomShapeDListsEntryResource(CDataResource): + cdata_ext = cdata_ext_RoomShapeDListsEntry + + def get_c_declaration_base(self): + return f"RoomShapeDListsEntry {self.symbol_name}" + + def get_c_reference(self, resource_offset): + if resource_offset == 0: + return f"&{self.symbol_name}" + else: + raise ValueError + + def get_h_includes(self): + return ("z64room.h",) + + +def report_RoomShapeImageBase_entry(resource, memory_context: "MemoryContext", v): + assert isinstance(v, int) + address = v + memory_context.report_resource_at_segmented( + resource, + address, + RoomShapeDListsEntryResource, + lambda file, offset: RoomShapeDListsEntryResource( + file, offset, f"{resource.name}_{address:08X}_RoomShapeDListsEntry" + ), + ) + + +def write_RoomShapeImageBase_entry( + resource, memory_context: "MemoryContext", v, wctx: CDataExtWriteContext +): + assert isinstance(v, int) + address = v + wctx.f.write(wctx.line_prefix) + wctx.f.write(memory_context.get_c_reference_at_segmented(address)) + return True + + +cdata_ext_RoomShapeImageBase = CDataExt_Struct( + ( + ("base", cdata_ext_RoomShapeBase), + ( + "amountType", + CDataExt_Value("B").set_write_str_v( + oot64_data.get_room_shape_image_amount_type_name + ), + ), + ("pad2", CDataExt_Value.pad16), + ( + "entry", + ( + CDataExt_Value("I") + .set_report(report_RoomShapeImageBase_entry) + .set_write(write_RoomShapeImageBase_entry) + ), + ), # RoomShapeDListsEntry* + ) +) + + +class JFIFResource(Resource): + def __init__(self, file, range_start, name): + super().__init__(file, range_start, range_start + 320 * 240 * 2, name) + + def try_parse_data(self, memory_context): + return RESOURCE_PARSE_SUCCESS + + needs_build = True + extracted_path_suffix = "" + + def get_filename_stem(self): + return f"{self.name}.u64.jpg" + + def write_extracted(self, memory_context): + # TODO trim zeros at the end of the data + self.extract_to_path.write_bytes( + self.file.data[self.range_start : self.range_end] + ) + + def get_c_declaration_base(self): + return f"u64 {self.symbol_name}[SCREEN_WIDTH * SCREEN_HEIGHT * G_IM_SIZ_16b_BYTES / sizeof(u64)]" + + def get_c_reference(self, resource_offset: int): + if resource_offset == 0: + return f"&{self.symbol_name}" + else: + raise ValueError + + def get_h_includes(self): + return ( + "ultra64.h", + "gfx.h", # for SCREEN_WIDTH, SCREEN_HEIGHT + ) + + +class RoomShapeImageSingleResource(CDataResource): + def report_source(resource, memory_context: "MemoryContext", v): + assert isinstance(v, int) + address = v + memory_context.report_resource_at_segmented( + resource, + address, + JFIFResource, + lambda file, offset: JFIFResource( + file, + offset, + f"{resource.name}_{address:08X}_JFIF", + ), + ) + + def write_source( + resource, memory_context: "MemoryContext", v, wctx: CDataExtWriteContext + ): + assert isinstance(v, int) + address = v + wctx.f.write(wctx.line_prefix) + wctx.f.write(memory_context.get_c_reference_at_segmented(address)) + return True + + cdata_ext = CDataExt_Struct( + ( + ("base", cdata_ext_RoomShapeImageBase), + ( + "source", + CDataExt_Value("I").set_report(report_source).set_write(write_source), + ), + ("unk_0C", CDataExt_Value.u32), + ("tlut", CDataExt_Value.pointer), # TODO + ("width", CDataExt_Value.u16), + ("height", CDataExt_Value.u16), + ("fmt", CDataExt_Value.u8), # TODO + ("siz", CDataExt_Value.u8), # TODO + ("tlutMode", CDataExt_Value.u16), + ("tlutCount", CDataExt_Value.u16), + ("pad1E", CDataExt_Value.pad16), + ) + ) + + def get_c_declaration_base(self): + return f"RoomShapeImageSingle {self.symbol_name}" + + def get_c_reference(self, resource_offset: int): + if resource_offset == 0: + return f"&{self.symbol_name}" + else: + raise ValueError + + def get_h_includes(self): + return ("z64room.h",) + + +class RoomShapeImageMultiBgEntryArrayResource(CDataArrayNamedLengthResource): + def report_source(resource, memory_context: "MemoryContext", v): + assert isinstance(v, int) + address = v + memory_context.report_resource_at_segmented( + resource, + address, + JFIFResource, + lambda file, offset: JFIFResource( + file, + offset, + f"{resource.name}_{address:08X}_JFIF", + ), + ) + + def write_source( + resource, memory_context: "MemoryContext", v, wctx: CDataExtWriteContext + ): + assert isinstance(v, int) + address = v + wctx.f.write(wctx.line_prefix) + wctx.f.write(memory_context.get_c_reference_at_segmented(address)) + return True + + elem_cdata_ext = CDataExt_Struct( + ( + ("unk_00", CDataExt_Value.u16), + ("bgCamIndex", CDataExt_Value.u8), + ("pad3", CDataExt_Value.pad8), + ( + "source", + CDataExt_Value("I").set_report(report_source).set_write(write_source), + ), + ("unk_0C", CDataExt_Value.u32), + ("tlut", CDataExt_Value.pointer), # TODO + ("width", CDataExt_Value.u16), + ("height", CDataExt_Value.u16), + ("fmt", CDataExt_Value.u8), # TODO + ("siz", CDataExt_Value.u8), # TODO + ("tlutMode", CDataExt_Value.u16), + ("tlutCount", CDataExt_Value.u16), + ("pad1A", CDataExt_Value.pad16), + ) + ) + + def get_c_declaration_base(self): + return f"RoomShapeImageMultiBgEntry {self.name}[{self.length_name}]" + + def get_h_includes(self): + return ("z64room.h",) + + +class RoomShapeImageMultiResource(CDataResource): + def write_numBackgrounds( + resource, memory_context: "MemoryContext", v, wctx: CDataExtWriteContext + ): + address = resource.cdata_unpacked["backgrounds"] + assert isinstance(address, int) + backgrounds_resource = memory_context.resolve_segmented(address).get_resource( + RoomShapeImageMultiBgEntryArrayResource + ) + wctx.f.write(wctx.line_prefix) + wctx.f.write(backgrounds_resource.length_name) + return True + + def report_backgrounds(resource, memory_context: "MemoryContext", v): + assert isinstance(v, int) + address = v + backgrounds_resource = memory_context.report_resource_at_segmented( + resource, + address, + RoomShapeImageMultiBgEntryArrayResource, + lambda file, offset: RoomShapeImageMultiBgEntryArrayResource( + file, + offset, + f"{resource.name}_{address:08X}_RoomShapeImageMultiBgEntries", + ), + ) + backgrounds_resource.set_length(resource.cdata_unpacked["numBackgrounds"]) + + def write_backgrounds( + resource, memory_context: "MemoryContext", v, wctx: CDataExtWriteContext + ): + assert isinstance(v, int) + address = v + wctx.f.write(wctx.line_prefix) + wctx.f.write(memory_context.get_c_reference_at_segmented(address)) + return True + + cdata_ext = CDataExt_Struct( + ( + ("base", cdata_ext_RoomShapeImageBase), + ("numBackgrounds", CDataExt_Value("B").set_write(write_numBackgrounds)), + ("pad9", CDataExt_Value.pad8), + ("padA", CDataExt_Value.pad16), + ( + "backgrounds", + ( + CDataExt_Value("I") + .set_report(report_backgrounds) + .set_write(write_backgrounds) + ), + ), # RoomShapeImageMultiBgEntry* + ) + ) + + def get_c_declaration_base(self): + return f"RoomShapeImageMulti {self.symbol_name}" + + def get_c_reference(self, resource_offset: int): + if resource_offset == 0: + return f"&{self.symbol_name}" + else: + raise ValueError + + def get_h_includes(self): + return ("z64room.h",) + + +class RoomShapeCullableEntryArrayResource(CDataArrayNamedLengthResource): + elem_cdata_ext = CDataExt_Struct( + ( + ("boundsSphereCenter", cdata_ext_Vec3s), + ("boundsSphereRadius", CDataExt_Value.s16), + ("opa", dlist_resources.cdata_ext_gfx_segmented), + ("xlu", dlist_resources.cdata_ext_gfx_segmented), + ) + ) + + def get_c_declaration_base(self): + return f"RoomShapeCullableEntry {self.symbol_name}[{self.length_name}]" + + def get_h_includes(self): + return ("z64room.h",) + + +class RoomShapeCullableResource(CDataResource): + def write_numEntries( + resource, memory_context: "MemoryContext", v, wctx: CDataExtWriteContext + ): + address = resource.cdata_unpacked["entries"] + assert isinstance(address, int) + wctx.f.write(wctx.line_prefix) + wctx.f.write(memory_context.get_c_expression_length_at_segmented(address)) + return True + + def report_entries(resource, memory_context: "MemoryContext", v): + assert isinstance(v, int) + address = v + entries_resource = memory_context.report_resource_at_segmented( + resource, + address, + RoomShapeCullableEntryArrayResource, + lambda file, offset: RoomShapeCullableEntryArrayResource( + file, offset, f"{resource.name}_{address:08X}_CullableEntries" + ), + ) + assert isinstance(entries_resource, RoomShapeCullableEntryArrayResource) + numEntries = resource.cdata_unpacked["numEntries"] + assert isinstance(numEntries, int) + entries_resource.set_length(numEntries) + + def write_entries( + resource, memory_context: "MemoryContext", v, wctx: CDataExtWriteContext + ): + assert isinstance(v, int) + address = v + wctx.f.write(wctx.line_prefix) + wctx.f.write(memory_context.get_c_reference_at_segmented(address)) + return True + + def write_entriesEnd( + resource, memory_context: "MemoryContext", v, wctx: CDataExtWriteContext + ): + address = resource.cdata_unpacked["entries"] + assert isinstance(address, int) + wctx.f.write(wctx.line_prefix) + wctx.f.write(memory_context.get_c_reference_at_segmented(address)) + wctx.f.write(" + ") + wctx.f.write(memory_context.get_c_expression_length_at_segmented(address)) + return True + + cdata_ext = CDataExt_Struct( + ( + ("base", cdata_ext_RoomShapeBase), + ("numEntries", CDataExt_Value("B").set_write(write_numEntries)), + ("pad2", CDataExt_Value.pad16), + ( + "entries", + CDataExt_Value("I").set_report(report_entries).set_write(write_entries), + ), + ( + "entriesEnd", + CDataExt_Value("I").set_write(write_entriesEnd), + ), + ) + ) + + def get_c_declaration_base(self): + return f"RoomShapeCullable {self.symbol_name}" + + def get_c_reference(self, resource_offset: int): + if resource_offset == 0: + return f"&{self.symbol_name}" + else: + raise ValueError + + def get_h_includes(self): + return ("z64room.h",) diff --git a/tools/assets/extract/extase_oot64/scene_commands_resource.py b/tools/assets/extract/extase_oot64/scene_commands_resource.py new file mode 100644 index 0000000000..a02e6417b9 --- /dev/null +++ b/tools/assets/extract/extase_oot64/scene_commands_resource.py @@ -0,0 +1,715 @@ +# SPDX-FileCopyrightText: © 2025 ZeldaRET +# SPDX-License-Identifier: CC0-1.0 + +import enum +import struct +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ..extase.memorymap import MemoryContext + +from ..extase import ( + File, + Resource, + RESOURCE_PARSE_SUCCESS, + ResourceParseInProgress, + ResourceParseWaiting, +) +from ..extase.cdata_resources import ( + CDataArrayResource, + CDataExt_Value, + CDataExtWriteContext, +) + +from .. import oot64_data + +from . import scene_rooms_resources +from . import collision_resources +from . import room_shape_resources +from . import misc_resources + + +def _SHIFTR(v: int, s: int, w: int): + assert isinstance(v, int) + assert isinstance(s, int) + assert isinstance(w, int) + assert v >= 0 + assert s >= 0 + assert w >= 1 + return (v >> s) & ((1 << w) - 1) + + +VERBOSE_NOT_FULLY_PARSED_SCENECMD = False + + +class SceneCmdId(enum.Enum): + # keep the SCENE_CMD_ID_ prefix for grepability + SCENE_CMD_ID_SPAWN_LIST = 0 + SCENE_CMD_ID_ACTOR_LIST = enum.auto() + SCENE_CMD_ID_UNUSED_2 = enum.auto() + SCENE_CMD_ID_COLLISION_HEADER = enum.auto() + SCENE_CMD_ID_ROOM_LIST = enum.auto() + SCENE_CMD_ID_WIND_SETTINGS = enum.auto() + SCENE_CMD_ID_ENTRANCE_LIST = enum.auto() + SCENE_CMD_ID_SPECIAL_FILES = enum.auto() + SCENE_CMD_ID_ROOM_BEHAVIOR = enum.auto() + SCENE_CMD_ID_UNDEFINED_9 = enum.auto() + SCENE_CMD_ID_ROOM_SHAPE = enum.auto() + SCENE_CMD_ID_OBJECT_LIST = enum.auto() + SCENE_CMD_ID_LIGHT_LIST = enum.auto() + SCENE_CMD_ID_PATH_LIST = enum.auto() + SCENE_CMD_ID_TRANSITION_ACTOR_LIST = enum.auto() + SCENE_CMD_ID_LIGHT_SETTINGS_LIST = enum.auto() + SCENE_CMD_ID_TIME_SETTINGS = enum.auto() + SCENE_CMD_ID_SKYBOX_SETTINGS = enum.auto() + SCENE_CMD_ID_SKYBOX_DISABLES = enum.auto() + SCENE_CMD_ID_EXIT_LIST = enum.auto() + SCENE_CMD_ID_END = enum.auto() + SCENE_CMD_ID_SOUND_SETTINGS = enum.auto() + SCENE_CMD_ID_ECHO_SETTINGS = enum.auto() + SCENE_CMD_ID_CUTSCENE_DATA = enum.auto() + SCENE_CMD_ID_ALTERNATE_HEADER_LIST = enum.auto() + SCENE_CMD_ID_MISC_SETTINGS = enum.auto() + + +scene_cmd_macro_name_by_cmd_id = { + SceneCmdId.SCENE_CMD_ID_SPAWN_LIST: "SCENE_CMD_SPAWN_LIST", + SceneCmdId.SCENE_CMD_ID_ACTOR_LIST: "SCENE_CMD_ACTOR_LIST", + SceneCmdId.SCENE_CMD_ID_UNUSED_2: "SCENE_CMD_UNUSED_02", + SceneCmdId.SCENE_CMD_ID_COLLISION_HEADER: "SCENE_CMD_COL_HEADER", + SceneCmdId.SCENE_CMD_ID_ROOM_LIST: "SCENE_CMD_ROOM_LIST", + SceneCmdId.SCENE_CMD_ID_WIND_SETTINGS: "SCENE_CMD_WIND_SETTINGS", + SceneCmdId.SCENE_CMD_ID_ENTRANCE_LIST: "SCENE_CMD_ENTRANCE_LIST", + SceneCmdId.SCENE_CMD_ID_SPECIAL_FILES: "SCENE_CMD_SPECIAL_FILES", + SceneCmdId.SCENE_CMD_ID_ROOM_BEHAVIOR: "SCENE_CMD_ROOM_BEHAVIOR", + SceneCmdId.SCENE_CMD_ID_UNDEFINED_9: "SCENE_CMD_UNK_09", + SceneCmdId.SCENE_CMD_ID_ROOM_SHAPE: "SCENE_CMD_ROOM_SHAPE", + SceneCmdId.SCENE_CMD_ID_OBJECT_LIST: "SCENE_CMD_OBJECT_LIST", + SceneCmdId.SCENE_CMD_ID_LIGHT_LIST: "SCENE_CMD_LIGHT_LIST", + SceneCmdId.SCENE_CMD_ID_PATH_LIST: "SCENE_CMD_PATH_LIST", + SceneCmdId.SCENE_CMD_ID_TRANSITION_ACTOR_LIST: "SCENE_CMD_TRANSITION_ACTOR_LIST", + SceneCmdId.SCENE_CMD_ID_LIGHT_SETTINGS_LIST: "SCENE_CMD_ENV_LIGHT_SETTINGS", + SceneCmdId.SCENE_CMD_ID_TIME_SETTINGS: "SCENE_CMD_TIME_SETTINGS", + SceneCmdId.SCENE_CMD_ID_SKYBOX_SETTINGS: "SCENE_CMD_SKYBOX_SETTINGS", + SceneCmdId.SCENE_CMD_ID_SKYBOX_DISABLES: "SCENE_CMD_SKYBOX_DISABLES", + SceneCmdId.SCENE_CMD_ID_EXIT_LIST: "SCENE_CMD_EXIT_LIST", + SceneCmdId.SCENE_CMD_ID_END: "SCENE_CMD_END", + SceneCmdId.SCENE_CMD_ID_SOUND_SETTINGS: "SCENE_CMD_SOUND_SETTINGS", + SceneCmdId.SCENE_CMD_ID_ECHO_SETTINGS: "SCENE_CMD_ECHO_SETTINGS", + SceneCmdId.SCENE_CMD_ID_CUTSCENE_DATA: "SCENE_CMD_CUTSCENE_DATA", + SceneCmdId.SCENE_CMD_ID_ALTERNATE_HEADER_LIST: "SCENE_CMD_ALTERNATE_HEADER_LIST", + SceneCmdId.SCENE_CMD_ID_MISC_SETTINGS: "SCENE_CMD_MISC_SETTINGS", +} + + +class SceneCommandsResource(Resource, can_size_be_unknown=True): + def __init__(self, file: File, range_start: int, name: str): + super().__init__(file, range_start, None, name) + self.parsed_commands: set[SceneCmdId] = set() + self.player_entry_list_length = None + self.room_list_length = None + self.exit_list_length = None + + def try_parse_data(self, memory_context: "MemoryContext"): + data = self.file.data[self.range_start :] + + new_progress_done = [] + waiting_for = [] + + offset = 0 + cmd_id = None + end_offset = None + + found_commands: set[SceneCmdId] = set() + + while offset + 8 <= len(data): + (cmd_id_int, data1, pad2, data2_I) = struct.unpack_from( + ">BBHI", data, offset + ) + (_, data2_H0, data2_H1) = struct.unpack_from(">IHH", data, offset) + (_, data2_B0, data2_B1, data2_B2, data2_B3) = struct.unpack_from( + ">IBBBB", data, offset + ) + + offset += 8 + cmd_id = SceneCmdId(cmd_id_int) + assert pad2 == 0 + + found_commands.add(cmd_id) + + if cmd_id == SceneCmdId.SCENE_CMD_ID_END: + assert data1 == 0 + assert data2_I == 0 + end_offset = offset + self.parsed_commands.add(cmd_id) + break + + if cmd_id in self.parsed_commands: + continue + + if cmd_id == SceneCmdId.SCENE_CMD_ID_ACTOR_LIST: + resource = memory_context.report_resource_at_segmented( + self, + data2_I, + scene_rooms_resources.ActorEntryListResource, + lambda file, offset: scene_rooms_resources.ActorEntryListResource( + file, offset, f"{self.name}_{data2_I:08X}_ActorEntryList" + ), + ) + resource.set_length(data1) + self.parsed_commands.add(cmd_id) + new_progress_done.append(("reported ActorEntryListResource", cmd_id)) + + if cmd_id == SceneCmdId.SCENE_CMD_ID_OBJECT_LIST: + resource = memory_context.report_resource_at_segmented( + self, + data2_I, + scene_rooms_resources.ObjectListResource, + lambda file, offset: scene_rooms_resources.ObjectListResource( + file, offset, f"{self.name}_{data2_I:08X}_ObjectList" + ), + ) + resource.set_length(data1) + self.parsed_commands.add(cmd_id) + new_progress_done.append(("reported ObjectListResource", cmd_id)) + + if cmd_id == SceneCmdId.SCENE_CMD_ID_ROOM_SHAPE: + room_shape_resources.report_room_shape_at_segmented( + self, memory_context, data2_I, self.name + ) + self.parsed_commands.add(cmd_id) + new_progress_done.append(("reported room shape resource", cmd_id)) + + if cmd_id == SceneCmdId.SCENE_CMD_ID_ROOM_LIST: + self.room_list_length = data1 + resource = memory_context.report_resource_at_segmented( + self, + data2_I, + scene_rooms_resources.RoomListResource, + lambda file, offset: scene_rooms_resources.RoomListResource( + file, offset, f"{self.name}_{data2_I:08X}_RoomList" + ), + ) + resource.set_length(data1) + self.parsed_commands.add(cmd_id) + new_progress_done.append(("reported RoomListResource", cmd_id)) + + if cmd_id == SceneCmdId.SCENE_CMD_ID_COLLISION_HEADER: + assert data1 == 0 + resource = memory_context.report_resource_at_segmented( + self, + data2_I, + collision_resources.CollisionResource, + lambda file, offset: collision_resources.CollisionResource( + file, offset, f"{self.name}_{data2_I:08X}_Col" + ), + ) + new_progress_done.append(("reported CollisionResource", cmd_id)) + if resource.is_data_parsed: + self.exit_list_length = resource.length_exitList + self.parsed_commands.add(cmd_id) + new_progress_done.append( + ("set self.exit_list_length from CollisionResource", cmd_id) + ) + else: + waiting_for.append( + ( + "CollisionResource to be parsed to set self.exit_list_length", + cmd_id, + resource, + ) + ) + + if cmd_id == SceneCmdId.SCENE_CMD_ID_ENTRANCE_LIST: + assert data1 == 0 + resource = memory_context.report_resource_at_segmented( + self, + data2_I, + scene_rooms_resources.SpawnListResource, + lambda file, offset: scene_rooms_resources.SpawnListResource( + file, offset, f"{self.name}_{data2_I:08X}_SpawnList" + ), + ) + new_progress_done.append(("reported SpawnListResource", cmd_id)) + if ( + self.player_entry_list_length is not None + and self.room_list_length is not None + ): + resource.player_entry_list_length = self.player_entry_list_length + resource.room_list_length = self.room_list_length + self.parsed_commands.add(cmd_id) + new_progress_done.append( + ("passed lengths to SpawnListResource", cmd_id) + ) + else: + waiting_for.append( + ( + "self.player_entry_list_length and self.room_list_length" + " to pass to SpawnListResource", + cmd_id, + ) + ) + + if cmd_id == SceneCmdId.SCENE_CMD_ID_SPAWN_LIST: + self.player_entry_list_length = data1 + resource = memory_context.report_resource_at_segmented( + self, + data2_I, + scene_rooms_resources.ActorEntryListResource, + lambda file, offset: scene_rooms_resources.ActorEntryListResource( + file, offset, f"{self.name}_{data2_I:08X}_PlayerEntryList" + ), + ) + resource.set_length(data1) + self.parsed_commands.add(cmd_id) + new_progress_done.append(("reported ActorEntryListResource", cmd_id)) + + if cmd_id == SceneCmdId.SCENE_CMD_ID_EXIT_LIST: + # TODO length from collision + assert data1 == 0 + resource = memory_context.report_resource_at_segmented( + self, + data2_I, + scene_rooms_resources.ExitListResource, + lambda file, offset: scene_rooms_resources.ExitListResource( + file, offset, f"{self.name}_{data2_I:08X}_ExitList" + ), + ) + new_progress_done.append(("reported ExitListResource", cmd_id)) + if self.exit_list_length is not None: + # TODO this doesnt work very well, eg need to trim to avoid overlaps + length = self.exit_list_length + # blindly align length to 2 (could/should check for zeros) + length = max(2, (length + 1) // 2 * 2) + # trim based on overlaps + while True: + _, other_resource = resource.file.get_resource_at( + resource.range_start + + length * resource.elem_cdata_ext.size + - 1 + ) + if other_resource is resource: + break + length -= 2 + assert length > 0 + resource.set_length(length) + self.parsed_commands.add(cmd_id) + new_progress_done.append( + ("passed length to ExitListResource", cmd_id, resource) + ) + else: + waiting_for.append( + ( + "self.exit_list_length to (guess a length to) pass to ExitListResource", + cmd_id, + ) + ) + + if cmd_id == SceneCmdId.SCENE_CMD_ID_LIGHT_SETTINGS_LIST: + resource = memory_context.report_resource_at_segmented( + self, + data2_I, + scene_rooms_resources.EnvLightSettingsListResource, + lambda file, offset: scene_rooms_resources.EnvLightSettingsListResource( + file, offset, f"{self.name}_{data2_I:08X}_EnvLightSettingsList" + ), + ) + resource.set_length(data1) + self.parsed_commands.add(cmd_id) + new_progress_done.append( + ("reported EnvLightSettingsListResource", cmd_id) + ) + + if cmd_id == SceneCmdId.SCENE_CMD_ID_TRANSITION_ACTOR_LIST: + resource = memory_context.report_resource_at_segmented( + self, + data2_I, + scene_rooms_resources.TransitionActorEntryListResource, + lambda file, offset: scene_rooms_resources.TransitionActorEntryListResource( + file, + offset, + f"{self.name}_{data2_I:08X}_TransitionActorEntryList", + ), + ) + resource.set_length(data1) + self.parsed_commands.add(cmd_id) + new_progress_done.append( + ("reported TransitionActorEntryListResource", cmd_id) + ) + + if cmd_id == SceneCmdId.SCENE_CMD_ID_PATH_LIST: + # TODO guess length, no other way I think + assert data1 == 0 + memory_context.report_resource_at_segmented( + self, + data2_I, + scene_rooms_resources.PathListResource, + lambda file, offset: scene_rooms_resources.PathListResource( + file, offset, f"{self.name}_{data2_I:08X}_PathList" + ), + ) + self.parsed_commands.add(cmd_id) + new_progress_done.append(("reported PathListResource", cmd_id)) + + if cmd_id == SceneCmdId.SCENE_CMD_ID_ALTERNATE_HEADER_LIST: + # TODO guess length, no other way I think + assert data1 == 0 + memory_context.report_resource_at_segmented( + self, + data2_I, + AltHeadersResource, + lambda file, offset: AltHeadersResource( + file, offset, f"{self.name}_{data2_I:08X}_AltHeaders" + ), + ) + self.parsed_commands.add(cmd_id) + new_progress_done.append(("reported AltHeadersResource", cmd_id)) + + if cmd_id == SceneCmdId.SCENE_CMD_ID_CUTSCENE_DATA: + assert data1 == 0 + memory_context.report_resource_at_segmented( + self, + data2_I, + misc_resources.CutsceneResource, + lambda file, offset: misc_resources.CutsceneResource( + file, offset, f"{self.name}_{data2_I:08X}_Cs" + ), + ) + self.parsed_commands.add(cmd_id) + new_progress_done.append(("reported CutsceneResource", cmd_id)) + + if cmd_id != SceneCmdId.SCENE_CMD_ID_END: + raise Exception("reached end of data without encountering end marker") + assert end_offset is not None + + # TODO hack until I have a clearer view of stuff once all cmds are loosely implemented + found_commands.discard(SceneCmdId.SCENE_CMD_ID_SOUND_SETTINGS) + found_commands.discard(SceneCmdId.SCENE_CMD_ID_MISC_SETTINGS) + found_commands.discard(SceneCmdId.SCENE_CMD_ID_SPECIAL_FILES) + found_commands.discard(SceneCmdId.SCENE_CMD_ID_SKYBOX_SETTINGS) + found_commands.discard(SceneCmdId.SCENE_CMD_ID_TIME_SETTINGS) + found_commands.discard(SceneCmdId.SCENE_CMD_ID_ROOM_BEHAVIOR) + found_commands.discard(SceneCmdId.SCENE_CMD_ID_ECHO_SETTINGS) + found_commands.discard(SceneCmdId.SCENE_CMD_ID_SKYBOX_DISABLES) + found_commands.discard(SceneCmdId.SCENE_CMD_ID_UNDEFINED_9) + found_commands.discard(SceneCmdId.SCENE_CMD_ID_WIND_SETTINGS) + + self.range_end = self.range_start + end_offset + assert self.parsed_commands.issubset(found_commands) + + if found_commands - self.parsed_commands: + if VERBOSE_NOT_FULLY_PARSED_SCENECMD: + print( + "NOT FULLY PARSED:", + self, + "Found commands:", + found_commands, + "Parsed commands:", + self.parsed_commands, + "FOUND BUT NOT PARSED:", + found_commands - self.parsed_commands, + ) + + if waiting_for: + if new_progress_done: + raise ResourceParseInProgress( + new_progress_done=new_progress_done, waiting_for=waiting_for + ) + else: + raise ResourceParseWaiting(waiting_for=waiting_for) + + assert self.parsed_commands == found_commands + return RESOURCE_PARSE_SUCCESS + + def get_c_declaration_base(self): + return f"SceneCmd {self.symbol_name}[]" + + def write_extracted(self, memory_context): + data = self.file.data[self.range_start : self.range_end] + with self.extract_to_path.open("w") as f: + if not self.braces_in_source: + f.write("{\n") + for offset in range(0, len(data), 8): + (cmd_id_int, data1, pad2, data2_I) = struct.unpack_from( + ">BBHI", data, offset + ) + (_, data2_H0, data2_H1) = struct.unpack_from(">IHH", data, offset) + (_, data2_B0, data2_B1, data2_B2, data2_B3) = struct.unpack_from( + ">IBBBB", data, offset + ) + cmd_id = SceneCmdId(cmd_id_int) + f.write(" " * 4) + f.write(scene_cmd_macro_name_by_cmd_id[cmd_id]) + f.write("(") + if cmd_id == SceneCmdId.SCENE_CMD_ID_SPAWN_LIST: + address = data2_I + f.write( + memory_context.get_c_expression_length_at_segmented(address) + ) + f.write(", ") + f.write(memory_context.get_c_reference_at_segmented(address)) + if cmd_id == SceneCmdId.SCENE_CMD_ID_ACTOR_LIST: + address = data2_I + f.write( + memory_context.get_c_expression_length_at_segmented(address) + ) + f.write(", ") + f.write(memory_context.get_c_reference_at_segmented(address)) + if cmd_id == SceneCmdId.SCENE_CMD_ID_UNUSED_2: + raise NotImplementedError(cmd_id) + if cmd_id == SceneCmdId.SCENE_CMD_ID_COLLISION_HEADER: + assert data1 == 0 + address = data2_I + f.write(memory_context.get_c_reference_at_segmented(address)) + if cmd_id == SceneCmdId.SCENE_CMD_ID_ROOM_LIST: + address = data2_I + f.write( + memory_context.get_c_expression_length_at_segmented(address) + ) + f.write(", ") + f.write(memory_context.get_c_reference_at_segmented(address)) + if cmd_id == SceneCmdId.SCENE_CMD_ID_WIND_SETTINGS: + assert data1 == 0 + # TODO cast x,y,z to s8 + xDir = data2_B0 + yDir = data2_B1 + zDir = data2_B2 + strength = data2_B3 + f.write(f"{xDir}, {yDir}, {zDir}, {strength}") + if cmd_id == SceneCmdId.SCENE_CMD_ID_ENTRANCE_LIST: + assert data1 == 0 + address = data2_I + f.write(memory_context.get_c_reference_at_segmented(address)) + if cmd_id == SceneCmdId.SCENE_CMD_ID_SPECIAL_FILES: + naviQuestHintFileId = data1 + keepObjectId = data2_I + f.write(f"{naviQuestHintFileId}, {keepObjectId}") + if cmd_id == SceneCmdId.SCENE_CMD_ID_ROOM_BEHAVIOR: + gpFlags1 = data1 + gpFlags2 = data2_I + behaviorType1 = gpFlags1 + behaviorType2 = _SHIFTR(gpFlags2, 0, 8) + lensMode = _SHIFTR(gpFlags2, 8, 1) + disableWarpSongs = _SHIFTR(gpFlags2, 10, 1) + behaviorType1_name = oot64_data.get_room_behavior_type1_name( + behaviorType1 + ) + behaviorType2_name = oot64_data.get_room_behavior_type2_name( + behaviorType2 + ) + lensMode_name = oot64_data.get_lens_mode_name(lensMode) + disableWarpSongs_name = ( + "true /* no warp songs */" + if disableWarpSongs + else "false /* warp songs enabled */" + ) + f.write( + f"{behaviorType1_name}, {behaviorType2_name}, {lensMode_name}, {disableWarpSongs_name}" + ) + if cmd_id == SceneCmdId.SCENE_CMD_ID_UNDEFINED_9: + assert data1 == 0 + assert data2_I == 0 + if cmd_id == SceneCmdId.SCENE_CMD_ID_ROOM_SHAPE: + assert data1 == 0 # TODO these asserts should be done on parse? + address = data2_I + f.write(memory_context.get_c_reference_at_segmented(address)) + if cmd_id == SceneCmdId.SCENE_CMD_ID_OBJECT_LIST: + address = data2_I + f.write( + memory_context.get_c_expression_length_at_segmented(address) + ) + f.write(", ") + f.write(memory_context.get_c_reference_at_segmented(address)) + if cmd_id == SceneCmdId.SCENE_CMD_ID_LIGHT_LIST: + raise NotImplementedError(cmd_id) + if cmd_id == SceneCmdId.SCENE_CMD_ID_PATH_LIST: + assert data1 == 0 + address = data2_I + f.write(memory_context.get_c_reference_at_segmented(address)) + if cmd_id == SceneCmdId.SCENE_CMD_ID_TRANSITION_ACTOR_LIST: + address = data2_I + f.write( + memory_context.get_c_expression_length_at_segmented(address) + ) + f.write(", ") + f.write(memory_context.get_c_reference_at_segmented(address)) + if cmd_id == SceneCmdId.SCENE_CMD_ID_LIGHT_SETTINGS_LIST: + address = data2_I + f.write( + memory_context.get_c_expression_length_at_segmented(address) + ) + f.write(", ") + f.write(memory_context.get_c_reference_at_segmented(address)) + if cmd_id == SceneCmdId.SCENE_CMD_ID_TIME_SETTINGS: + assert data1 == 0 + hour = data2_B0 + min_ = data2_B1 + timeSpeed = data2_B2 + assert data2_B3 == 0 + + hour_str = "0xFF" if hour == 0xFF else str(hour) + min_str = "0xFF" if min_ == 0xFF else str(min_) + timeSpeed_str = "0xFF" if timeSpeed == 0xFF else str(timeSpeed) + + if hour == 0xFF or min_ == 0xFF: + f.write("/* don't set time */ ") + f.write(f"{hour_str}, {min_str}, {timeSpeed_str}") + if timeSpeed == 0xFF or timeSpeed == 0: + f.write(" /* time doesn't move */") + if cmd_id == SceneCmdId.SCENE_CMD_ID_SKYBOX_SETTINGS: + assert data1 == 0 + skyboxId = data2_B0 + skyboxConfig = data2_B1 + envLightMode = data2_B2 + assert data2_B3 == 0 + f.write( + f"{oot64_data.get_skybox_id(skyboxId)}, " + f"{skyboxConfig}, " + f"{oot64_data.get_light_mode(envLightMode)}" + ) + if cmd_id == SceneCmdId.SCENE_CMD_ID_SKYBOX_DISABLES: + assert data1 == 0 + skyboxDisabled = data2_B0 + sunMoonDisabled = data2_B1 + assert data2_B2 == data2_B3 == 0 + skyboxDisabled_name = ( + "true /* no skybox */" + if skyboxDisabled + else "false /* skybox enabled */" + ) + sunMoonDisabled_name = ( + "true /* no sun/moon */" + if sunMoonDisabled + else "false /* sun/moon enabled */" + ) + f.write(f"{skyboxDisabled_name}, {sunMoonDisabled_name}") + if cmd_id == SceneCmdId.SCENE_CMD_ID_EXIT_LIST: + assert data1 == 0 + address = data2_I + f.write(memory_context.get_c_reference_at_segmented(address)) + if cmd_id == SceneCmdId.SCENE_CMD_ID_END: + assert data1 == 0 + assert data2_I == 0 + if cmd_id == SceneCmdId.SCENE_CMD_ID_SOUND_SETTINGS: + specId = data1 + assert data2_B0 == 0 + assert data2_B1 == 0 + natureAmbienceId = data2_B2 + seqId = data2_B3 + natureAmbienceId_name = oot64_data.get_nature_ambience_id_name( + natureAmbienceId + ) + seqId_name = oot64_data.get_sequence_id_name(seqId) + f.write(f"{specId}, {natureAmbienceId_name}, {seqId_name}") + if cmd_id == SceneCmdId.SCENE_CMD_ID_ECHO_SETTINGS: + assert data1 == 0 + assert data2_B0 == data2_B1 == data2_B2 == 0 + echo = data2_B3 + f.write(f"{echo}") + if cmd_id == SceneCmdId.SCENE_CMD_ID_CUTSCENE_DATA: + assert data1 == 0 + address = data2_I + f.write(memory_context.get_c_reference_at_segmented(address)) + if cmd_id == SceneCmdId.SCENE_CMD_ID_ALTERNATE_HEADER_LIST: + assert data1 == 0 + address = data2_I + f.write(memory_context.get_c_reference_at_segmented(address)) + if cmd_id == SceneCmdId.SCENE_CMD_ID_MISC_SETTINGS: + sceneCamType = data1 + worldMapLocation = data2_I + sceneCamType_name = oot64_data.get_scene_cam_type_name(sceneCamType) + f.write(f"{sceneCamType_name}, {worldMapLocation}") + + f.write("),\n") + + if not self.braces_in_source: + f.write("}\n") + + def get_c_reference(self, resource_offset: int): + if resource_offset == 0: + return self.symbol_name + else: + raise ValueError + + def get_c_includes(self): + return ( + "array_count.h", + # TODO these are not always needed: + "sequence.h", # for NATURE_ID_* and NA_BGM_* + "z64skybox.h", # for SKYBOX_* + ) + + def get_h_includes(self): + return ("z64scene.h",) + + +class AltHeadersResource(CDataArrayResource): + def report_elem(resource, memory_context: "MemoryContext", v): + assert isinstance(v, int) + address = v + if address != 0: + memory_context.report_resource_at_segmented( + resource, + address, + SceneCommandsResource, + lambda file, offset: SceneCommandsResource( + file, offset, f"{resource.name}_{address:08X}_Cmds" + ), + ) + + def write_elem( + resource, memory_context: "MemoryContext", v, wctx: CDataExtWriteContext + ): + assert isinstance(v, int) + address = v + wctx.f.write(wctx.line_prefix) + if address == 0: + wctx.f.write("NULL") + else: + wctx.f.write(memory_context.get_c_reference_at_segmented(address)) + return True + + elem_cdata_ext = ( + CDataExt_Value("I").set_report(report_elem).set_write(write_elem) + ) # SceneCmd* + + def try_parse_data(self, memory_context): + length = 0 + for i, (v,) in enumerate( + struct.iter_unpack(">I", self.file.data[self.range_start :]) + ): + if v == 0: + if i < 3: + length = i + 1 + continue + else: + break + + try: + resolve_result = memory_context.resolve_segmented(v) + except: + break + data_may_be_scenecmds = False + for j in range( + resolve_result.file_offset, len(resolve_result.file.data), 8 + ): + cmd_id_int = resolve_result.file.data[j] + try: + cmd_id = SceneCmdId(cmd_id_int) + except ValueError: + break + if cmd_id == SceneCmdId.SCENE_CMD_ID_END: + data_may_be_scenecmds = True + break + if not data_may_be_scenecmds: + break + length = i + 1 + assert length > 0 + self.set_length(length) + return super().try_parse_data(memory_context) + + def get_c_declaration_base(self): + return f"SceneCmd* {self.symbol_name}[]" + + def get_h_includes(self): + return ("z64scene.h",) diff --git a/tools/assets/extract/extase_oot64/scene_rooms_resources.py b/tools/assets/extract/extase_oot64/scene_rooms_resources.py new file mode 100644 index 0000000000..aabab9b79e --- /dev/null +++ b/tools/assets/extract/extase_oot64/scene_rooms_resources.py @@ -0,0 +1,433 @@ +# SPDX-FileCopyrightText: © 2025 ZeldaRET +# SPDX-License-Identifier: CC0-1.0 + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ..extase.memorymap import MemoryContext + +from ..extase import ( + ResourceParseWaiting, +) + +from ..extase.cdata_resources import ( + CDataArrayResource, + CDataArrayNamedLengthResource, + CDataExt_Struct, + CDataExt_Array, + CDataExt_Value, + CDataExtWriteContext, + cdata_ext_Vec3s, + INDENT, + Vec3sArrayResource, + fmt_hex_s, +) + +from .. import oot64_data + + +VERBOSE_SPAWN_LIST_LENGTH_GUESSING = False + + +class ActorEntryListResource(CDataArrayNamedLengthResource): + def write_elem(resource, memory_context, v, wctx: CDataExtWriteContext): + assert isinstance(v, dict) + f = wctx.f + f.write(wctx.line_prefix) + f.write("{\n") + + f.write(wctx.line_prefix + INDENT) + f.write(oot64_data.get_actor_id_name(v["id"])) + f.write(",\n") + + f.write(wctx.line_prefix + INDENT) + f.write("{ ") + f.write(", ".join(f"{p:6}" for p in (v["pos"][axis] for axis in "xyz"))) + f.write(" }, // pos\n") + + f.write(wctx.line_prefix + INDENT) + f.write("{ ") + f.write(", ".join(fmt_hex_s(r, 4) for r in (v["rot"][axis] for axis in "xyz"))) + f.write(" }, // rot\n") + + f.write(wctx.line_prefix + INDENT) + params = v["params"] + f.write(fmt_hex_s(params, 4)) + if params < 0: + params_u16 = params + 0x1_0000 + f.write(f" /* 0x{params_u16:04X} */") + f.write(", // params\n") + + f.write(wctx.line_prefix) + f.write("}") + + return True + + elem_cdata_ext = CDataExt_Struct( + ( + ("id", CDataExt_Value.s16), + ("pos", cdata_ext_Vec3s), + ("rot", cdata_ext_Vec3s), + ("params", CDataExt_Value.s16), + ) + ).set_write(write_elem) + + def get_c_declaration_base(self): + return f"ActorEntry {self.symbol_name}[{self.length_name}]" + + def get_c_includes(self): + return ("z64actor.h",) + + def get_h_includes(self): + return ("z64scene.h",) + + +class ObjectListResource(CDataArrayNamedLengthResource): + elem_cdata_ext = CDataExt_Value("h").set_write_str_v( + lambda v: oot64_data.get_object_id_name(v) + ) + + def get_c_declaration_base(self): + return f"s16 {self.symbol_name}[{self.length_name}]" + + def get_c_includes(self): + return ("z64object.h",) + + def get_h_includes(self): + return ("ultra64.h",) + + +def write_RomFile( + resource, memory_context: "MemoryContext", v, wctx: CDataExtWriteContext +): + assert isinstance(v, dict) + vromStart = v["vromStart"] + vromEnd = v["vromEnd"] + rom_file_name = memory_context.get_dmadata_table_rom_file_name_from_vrom( + vromStart, vromEnd + ) + wctx.f.write(wctx.line_prefix) + wctx.f.write(f"ROM_FILE({rom_file_name})") + return True + + +cdata_ext_RomFile = CDataExt_Struct( + ( + ("vromStart", CDataExt_Value.u32), + ("vromEnd", CDataExt_Value.u32), + ) +).set_write(write_RomFile) + + +class RoomListResource(CDataArrayNamedLengthResource): + elem_cdata_ext = cdata_ext_RomFile + + def get_c_declaration_base(self): + return f"RomFile {self.symbol_name}[{self.length_name}]" + + def get_c_includes(self): + # TODO use DECLARE_ROM_SEGMENT to declare rooms rom files + return ("segment_symbols.h",) + + def get_h_includes(self): + return ("romfile.h",) + + +class SpawnListResource(CDataArrayResource): + elem_cdata_ext = CDataExt_Struct( + ( + ("playerEntryIndex", CDataExt_Value.u8), + ("room", CDataExt_Value.u8), + ) + ) + + # (eventually) set by SceneCommandsResource + player_entry_list_length = None + room_list_length = None + + def try_parse_data(self, memory_context): + if self.player_entry_list_length is None or self.room_list_length is None: + raise ResourceParseWaiting( + waiting_for=[ + msg + for is_waiting, msg in ( + ( + self.player_entry_list_length is None, + "self.player_entry_list_length", + ), + ( + self.room_list_length is None, + "self.room_list_length", + ), + ) + if is_waiting + ] + ) + + # File.name comes from the Name attribute on a element, + # which is also used to make the path to the baserom file to read from. + # So File.name is the name of the baserom file. + # This may change in the future though ¯\_(ツ)_/¯ + rom_file_name = self.file.name + # This way we can get the scene ID of the file + scene_id = oot64_data.get_scene_id_from_rom_file_name(rom_file_name) + scene_id_name = oot64_data.get_scene_id_name(scene_id) + # Get all the spawns used by all entrances using the scene + entrance_ids = oot64_data.get_entrance_ids_from_scene_id_name(scene_id_name) + all_used_spawns = set() + for entrance_id in entrance_ids: + entrance_spawn = oot64_data.get_entrance_spawn(entrance_id) + all_used_spawns.add(entrance_spawn) + num_spawns = max(all_used_spawns) + 1 + + # Handle the cases where the entrance table references spawn outside the spawn list, + # by checking if the indices in the last spawn in the list make sense. + # This is required for a few scenes in practice, otherwise the spawn list and exit list overlap. + while True: + last_spawn_unpacked = self.elem_cdata_ext.unpack_from( + self.file.data, + self.range_start + (num_spawns - 1) * self.elem_cdata_ext.size, + ) + if ( + last_spawn_unpacked["playerEntryIndex"] < self.player_entry_list_length + and last_spawn_unpacked["room"] < self.room_list_length + ): + break + if VERBOSE_SPAWN_LIST_LENGTH_GUESSING: + print( + self, + "Removing one spawn because the last spawn of the list has bad indices", + last_spawn_unpacked, + num_spawns, + "->", + num_spawns - 1, + ) + num_spawns -= 1 + assert num_spawns > 0 + + # Handle the case where there may be an unused spawn, in the place of + # what would otherwise be padding. + if oot64_data.I_D_OMEGALUL: + assert self.elem_cdata_ext.size == 2 + if num_spawns % 2 == 1: + data_to_next_4align = self.file.data[ + self.range_start + num_spawns * 2 : + ][:2] + if data_to_next_4align != b"\x00\x00": + if VERBOSE_SPAWN_LIST_LENGTH_GUESSING: + print( + self, + "Adding one spawn because the next supposedly-padding" + " two bytes are not padding (not zero)", + bytes(data_to_next_4align), + num_spawns, + "->", + num_spawns + 1, + ) + num_spawns += 1 + + # Trim the list to avoid overlaps + # TODO this may be linked to headers for cutscene layers not having the spawns the entrance table expects + # for example spot00 hyrule field seems to always have a single 0,0 spawn for cutscene layers? + # (so the above approach using the entrance table does not generalize to cutscene layers) + # so it may be relevant to have the layer type when parsing the spawn list + # Alternatively, somehow trim the variable-length resources when overlapping + while True: + range_end = self.range_start + num_spawns * self.elem_cdata_ext.size + result, resource = self.file.get_resource_at(range_end - 1) + if resource is self: + break + if VERBOSE_SPAWN_LIST_LENGTH_GUESSING: + print( + self, + "Removing one spawn because the last spawn of the list overlaps with another resource", + resource, + num_spawns, + "->", + num_spawns - 1, + ) + num_spawns -= 1 + assert num_spawns > 0 + + self.set_length(num_spawns) + return super().try_parse_data(memory_context) + + def get_c_declaration_base(self): + return f"Spawn {self.symbol_name}[]" + + def get_h_includes(self): + return ("z64scene.h",) + + +class ExitListResource(CDataArrayResource): + elem_cdata_ext = CDataExt_Value("h").set_write_str_v( + lambda v: oot64_data.get_entrance_id_name(v) + ) + + # length set by SceneCommandsResource.try_parse_data + + def get_c_declaration_base(self): + return f"s16 {self.symbol_name}[]" + + def get_h_includes(self): + return ("ultra64.h",) + + +class EnvLightSettingsListResource(CDataArrayNamedLengthResource): + # TODO formatting + elem_cdata_ext = CDataExt_Struct( + ( + ("ambientColor", CDataExt_Array(CDataExt_Value.u8, 3)), + ("light1Dir", CDataExt_Array(CDataExt_Value.s8, 3)), + ("light1Color", CDataExt_Array(CDataExt_Value.u8, 3)), + ("light2Dir", CDataExt_Array(CDataExt_Value.s8, 3)), + ("light2Color", CDataExt_Array(CDataExt_Value.u8, 3)), + ("fogColor", CDataExt_Array(CDataExt_Value.u8, 3)), + ("blendRateAndFogNear", CDataExt_Value.s16), + ("zFar", CDataExt_Value.s16), + ) + ) + + def get_c_declaration_base(self): + return f"EnvLightSettings {self.symbol_name}[{self.length_name}]" + + def get_h_includes(self): + return ("z64environment.h",) + + +class TransitionActorEntryListResource(CDataArrayNamedLengthResource): + def write_elem(resource, memory_context, v, wctx: CDataExtWriteContext): + assert isinstance(v, dict) + f = wctx.f + f.write(wctx.line_prefix) + f.write("{\n") + + f.write(wctx.line_prefix + INDENT) + f.write("{\n") + f.write(wctx.line_prefix + 2 * INDENT) + f.write("// { room, bgCamIndex }\n") + for side_i in range(2): + side = v["sides"][side_i] + room = side["room"] + bgCamIndex = side["bgCamIndex"] + f.write(wctx.line_prefix + 2 * INDENT) + f.write("{ ") + f.write(f"{room}, {bgCamIndex}") + f.write(" },\n") + f.write(wctx.line_prefix + INDENT) + f.write("}, // sides\n") + + f.write(wctx.line_prefix + INDENT) + f.write(oot64_data.get_actor_id_name(v["id"])) + f.write(",\n") + + f.write(wctx.line_prefix + INDENT) + f.write("{ ") + f.write(", ".join(f"{p:6}" for p in (v["pos"][axis] for axis in "xyz"))) + f.write(" }, // pos\n") + + f.write(wctx.line_prefix + INDENT) + f.write(fmt_hex_s(v["rotY"], 4)) + f.write(", // rotY\n") + + f.write(wctx.line_prefix + INDENT) + params = v["params"] + f.write(fmt_hex_s(params, 4)) + if params < 0: + params_u16 = params + 0x1_0000 + f.write(f" /* 0x{params_u16:04X} */") + f.write(", // params\n") + + f.write(wctx.line_prefix) + f.write("}") + + return True + + elem_cdata_ext = CDataExt_Struct( + ( + ( + "sides", + CDataExt_Array( + CDataExt_Struct( + ( + ("room", CDataExt_Value.s8), + ("bgCamIndex", CDataExt_Value.s8), + ) + ), + 2, + ), + ), + ("id", CDataExt_Value.s16), + ("pos", cdata_ext_Vec3s), + ("rotY", CDataExt_Value.s16), + ("params", CDataExt_Value.s16), + ) + ).set_write(write_elem) + + def get_c_declaration_base(self): + return f"TransitionActorEntry {self.symbol_name}[{self.length_name}]" + + def get_c_includes(self): + return ("z64actor.h",) + + def get_h_includes(self): + return ("z64scene.h",) + + +class PathListResource(CDataArrayResource): + def report_elem(resource, memory_context: "MemoryContext", v): + assert isinstance(v, dict) + count = v["count"] + assert isinstance(count, int) + points = v["points"] + assert isinstance(points, int) + memory_context.report_resource_at_segmented( + resource, + points, + Vec3sArrayResource, + lambda file, offset: Vec3sArrayResource( + file, offset, f"{resource.name}_{points:08X}_Points", count + ), + ) + + def write_elem( + resource, memory_context: "MemoryContext", v, wctx: CDataExtWriteContext + ): + assert isinstance(v, dict) + count = v["count"] + assert isinstance(count, int) + points = v["points"] + assert isinstance(points, int) + f = wctx.f + f.write(wctx.line_prefix) + f.write("{ ") + f.write(memory_context.get_c_expression_length_at_segmented(points)) + f.write(", ") + f.write(memory_context.get_c_reference_at_segmented(points)) + f.write(" }") + return True + + elem_cdata_ext = ( + CDataExt_Struct( + ( + ("count", CDataExt_Value.u8), + ("pad1", CDataExt_Value.pad8), + ("pad2", CDataExt_Value.pad16), + ("points", CDataExt_Value("I")), # Vec3s* + ) + ) + .set_report(report_elem) + .set_write(write_elem) + ) + + def try_parse_data(self, memory_context): + if self._length is None: + # TODO guess + self.set_length(1) + return super().try_parse_data(memory_context) + + def get_c_declaration_base(self): + return f"Path {self.symbol_name}[]" + + def get_h_includes(self): + return ("z64path.h",) diff --git a/tools/assets/extract/extase_oot64/skelanime_legacy_resources.py b/tools/assets/extract/extase_oot64/skelanime_legacy_resources.py new file mode 100644 index 0000000000..056e49762b --- /dev/null +++ b/tools/assets/extract/extase_oot64/skelanime_legacy_resources.py @@ -0,0 +1,218 @@ +# SPDX-FileCopyrightText: © 2025 ZeldaRET +# SPDX-License-Identifier: CC0-1.0 + +from typing import TYPE_CHECKING + +from ..extase import RESOURCE_PARSE_SUCCESS + +if TYPE_CHECKING: + from ..extase.memorymap import MemoryContext + +from ..extase.cdata_resources import ( + CDataResource, + CDataArrayResource, + CDataExt_Struct, + CDataExtWriteContext, + cdata_ext_Vec3f, + cdata_ext_Vec3s, + CDataExt_Value, +) + +from . import animation_resources +from . import dlist_resources +from . import skeleton_resources + + +class LegacyLimbResource(CDataResource): + + def report_limb(resource, memory_context: "MemoryContext", v): + assert isinstance(v, int) + address = v + if address != 0: + memory_context.report_resource_at_segmented( + resource, + address, + LegacyLimbResource, + lambda file, offset: LegacyLimbResource( + file, + offset, + f"{resource.name}_{address:08X}_LegacyLimb", + ), + ) + + def write_limb( + resource, memory_context: "MemoryContext", v, wctx: CDataExtWriteContext + ): + assert isinstance(v, int) + address = v + wctx.f.write(wctx.line_prefix) + if address == 0: + wctx.f.write("NULL") + else: + wctx.f.write(memory_context.get_c_reference_at_segmented(address)) + return True + + cdata_ext = CDataExt_Struct( + ( + ("dList", dlist_resources.cdata_ext_gfx_segmented), + ("trans", cdata_ext_Vec3f), + ("rot", cdata_ext_Vec3s), + ("pad16", CDataExt_Value.pad16), + ( + "sibling", + CDataExt_Value("I").set_report(report_limb).set_write(write_limb), + ), # LegacyLimb* + ( + "child", + CDataExt_Value("I").set_report(report_limb).set_write(write_limb), + ), # LegacyLimb* + ) + ) + + def get_c_declaration_base(self): + return f"LegacyLimb {self.symbol_name}" + + def get_c_reference(self, resource_offset: int): + if resource_offset == 0: + return f"&{self.symbol_name}" + else: + raise ValueError() + + def get_h_includes(self): + return ("z64animation_legacy.h",) + + +class LegacyJointKeyArrayResource(CDataArrayResource): + elem_cdata_ext = CDataExt_Struct( + ( + ("xMax", CDataExt_Value.s16), + ("x", CDataExt_Value.s16), + ("yMax", CDataExt_Value.s16), + ("y", CDataExt_Value.s16), + ("zMax", CDataExt_Value.s16), + ("z", CDataExt_Value.s16), + ) + ) + + def get_c_declaration_base(self): + return f"LegacyJointKey {self.symbol_name}[]" + + def get_c_reference(self, resource_offset: int): + if resource_offset == 0: + return f"{self.symbol_name}" + else: + raise ValueError() + + def get_h_includes(self): + return ("z64animation_legacy.h",) + + +class LegacyAnimationResource(CDataResource): + + def write_frameData( + resource, memory_context: "MemoryContext", v, wctx: CDataExtWriteContext + ): + assert isinstance(v, int) + address = v + wctx.f.write(wctx.line_prefix) + wctx.f.write(memory_context.get_c_reference_at_segmented(address)) + return True + + def write_jointKey( + resource, memory_context: "MemoryContext", v, wctx: CDataExtWriteContext + ): + assert isinstance(v, int) + address = v + wctx.f.write(wctx.line_prefix) + wctx.f.write(memory_context.get_c_reference_at_segmented(address)) + return True + + cdata_ext = CDataExt_Struct( + ( + ("frameCount", CDataExt_Value.s16), + ("limbCount", CDataExt_Value.s16), + ("frameData", CDataExt_Value("I").set_write(write_frameData)), # s16* + ( + "jointKey", + CDataExt_Value("I").set_write(write_jointKey), + ), # LegacyJointKey* + ) + ) + + def try_parse_data(self, memory_context): + super().try_parse_data(memory_context) + + address_frameData = self.cdata_unpacked["frameData"] + assert isinstance(address_frameData, int) + resource_frameData = memory_context.report_resource_at_segmented( + self, + address_frameData, + animation_resources.AnimationFrameDataResource, + lambda file, offset: animation_resources.AnimationFrameDataResource( + file, + offset, + f"{self.name}_{address_frameData:08X}_FrameData", + ), + ) + + address_jointKey = self.cdata_unpacked["jointKey"] + assert isinstance(address_jointKey, int) + resource_jointKey = memory_context.report_resource_at_segmented( + self, + address_jointKey, + LegacyJointKeyArrayResource, + lambda file, offset: LegacyJointKeyArrayResource( + file, + offset, + f"{self.name}_{address_jointKey:08X}_JointKeys", + ), + ) + resource_jointKey.set_length(self.cdata_unpacked["limbCount"] + 1) + + # The length of the frameData array is + # for now assumed to fill the space to the jointKey data, + # at the very least before subtracting the offsets check that + # the offsets belong to the same file + # TODO better idea for computing this data's size + + if not (resource_frameData.file == resource_jointKey.file): + raise NotImplementedError( + "Expected frameData and jointIndices to be in the same file", + self.cdata_unpacked, + resource_frameData.file, + resource_jointKey.file, + ) + + if resource_frameData.range_start < resource_jointKey.range_start: + resource_frameData.length = ( + resource_jointKey.range_start - resource_frameData.range_start + ) // animation_resources.AnimationFrameDataResource.elem_cdata_ext.size + else: + raise NotImplementedError( + "Expected offsets of frameData, jointKey to be in order", + self.cdata_unpacked, + hex(resource_frameData.range_start), + hex(resource_jointKey.range_start), + ) + + return RESOURCE_PARSE_SUCCESS + + def get_c_declaration_base(self): + return f"LegacyAnimationHeader {self.symbol_name}" + + def get_c_reference(self, resource_offset: int): + if resource_offset == 0: + return f"&{self.symbol_name}" + else: + raise ValueError() + + def get_h_includes(self): + return ("z64animation_legacy.h",) + + +class LegacyLimbsArrayResource(skeleton_resources.LimbsArrayResourceABC): + limb_type = LegacyLimbResource + c_limb_type = "LegacyLimb" + + def get_h_includes(self): + return ("z64animation_legacy.h",) diff --git a/tools/assets/extract/extase_oot64/skelcurve_resources.py b/tools/assets/extract/extase_oot64/skelcurve_resources.py new file mode 100644 index 0000000000..4b140c2568 --- /dev/null +++ b/tools/assets/extract/extase_oot64/skelcurve_resources.py @@ -0,0 +1,378 @@ +# SPDX-FileCopyrightText: © 2025 ZeldaRET +# SPDX-License-Identifier: CC0-1.0 + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ..extase.memorymap import MemoryContext + +from ..extase import ( + File, + RESOURCE_PARSE_SUCCESS, + ResourceParseWaiting, +) +from ..extase.cdata_resources import ( + CDataResource, + CDataExt_Struct, + CDataExt_Value, + CDataExt_Array, + CDataExtWriteContext, +) + +from . import dlist_resources + + +class KnotCountsArrayResource(CDataResource, can_size_be_unknown=True): + elem_cdata_ext = CDataExt_Value.u8 + + def __init__(self, file: File, range_start: int, name: str): + super().__init__(file, range_start, name) + self.length = None + + def try_parse_data(self, memory_context: "MemoryContext"): + if self.length is not None: + self.cdata_ext = CDataExt_Array(self.elem_cdata_ext, self.length) + self.range_end = self.range_start + self.cdata_ext.size + return super().try_parse_data(memory_context) + else: + raise ResourceParseWaiting(waiting_for=["self.length"]) + + def get_c_declaration_base(self): + return f"u8 {self.symbol_name}[]" + + def get_c_reference(self, resource_offset: int): + if resource_offset == 0: + return self.symbol_name + else: + raise ValueError() + + def get_h_includes(self): + return ("ultra64.h",) + + +class CurveInterpKnotArrayResource(CDataResource, can_size_be_unknown=True): + elem_cdata_ext = CDataExt_Struct( + ( + ("flags", CDataExt_Value.u16), + ("abscissa", CDataExt_Value.s16), + ("leftGradient", CDataExt_Value.s16), + ("rightGradient", CDataExt_Value.s16), + ("ordinate", CDataExt_Value.f32), + ) + ) + + def __init__(self, file: File, range_start: int, name: str): + super().__init__(file, range_start, name) + self.length = None + + def try_parse_data(self, memory_context: "MemoryContext"): + if self.length is not None: + self.cdata_ext = CDataExt_Array(self.elem_cdata_ext, self.length) + self.range_end = self.range_start + self.cdata_ext.size + return super().try_parse_data(memory_context) + else: + raise ResourceParseWaiting(waiting_for=["self.length"]) + + def get_c_declaration_base(self): + return f"CurveInterpKnot {self.symbol_name}[]" + + def get_c_reference(self, resource_offset: int): + if resource_offset == 0: + return self.symbol_name + else: + raise ValueError() + + def get_h_includes(self): + return ("z64curve.h",) + + +class ConstantDataArrayResource(CDataResource, can_size_be_unknown=True): + elem_cdata_ext = CDataExt_Value.s16 + + def __init__(self, file: File, range_start: int, name: str): + super().__init__(file, range_start, name) + self.length = None + + def try_parse_data(self, memory_context: "MemoryContext"): + if self.length is not None: + self.cdata_ext = CDataExt_Array(self.elem_cdata_ext, self.length) + self.range_end = self.range_start + self.cdata_ext.size + return super().try_parse_data(memory_context) + else: + raise ResourceParseWaiting(waiting_for=["self.length"]) + + def get_c_declaration_base(self): + return f"s16 {self.symbol_name}[]" + + def get_c_reference(self, resource_offset: int): + if resource_offset == 0: + return self.symbol_name + else: + raise ValueError() + + def get_h_includes(self): + return ("ultra64.h",) + + +class CurveAnimationHeaderResource(CDataResource): + def report_knotCounts(resource, memory_context: "MemoryContext", v): + assert isinstance(v, int) + address = v + memory_context.report_resource_at_segmented( + resource, + address, + KnotCountsArrayResource, + lambda file, offset: KnotCountsArrayResource( + file, offset, f"{resource.name}_{address:08X}_KnotCounts" + ), + ) + + def write_knotCounts( + resource, memory_context: "MemoryContext", v, wctx: CDataExtWriteContext + ): + assert isinstance(v, int) + address = v + wctx.f.write(wctx.line_prefix) + wctx.f.write(memory_context.get_c_reference_at_segmented(address)) + return True + + def report_interpolationData(resource, memory_context: "MemoryContext", v): + assert isinstance(v, int) + address = v + memory_context.report_resource_at_segmented( + resource, + address, + CurveInterpKnotArrayResource, + lambda file, offset: CurveInterpKnotArrayResource( + file, offset, f"{resource.name}_{address:08X}_InterpolationData" + ), + ) + + def write_interpolationData( + resource, memory_context: "MemoryContext", v, wctx: CDataExtWriteContext + ): + assert isinstance(v, int) + address = v + wctx.f.write(wctx.line_prefix) + wctx.f.write(memory_context.get_c_reference_at_segmented(address)) + return True + + def report_constantData(resource, memory_context: "MemoryContext", v): + assert isinstance(v, int) + address = v + memory_context.report_resource_at_segmented( + resource, + address, + ConstantDataArrayResource, + lambda file, offset: ConstantDataArrayResource( + file, offset, f"{resource.name}_{address:08X}_ConstantData" + ), + ) + + def write_constantData( + resource, memory_context: "MemoryContext", v, wctx: CDataExtWriteContext + ): + assert isinstance(v, int) + address = v + wctx.f.write(wctx.line_prefix) + wctx.f.write(memory_context.get_c_reference_at_segmented(address)) + return True + + cdata_ext = CDataExt_Struct( + ( + ( + "knotCounts", + CDataExt_Value("I") + .set_report(report_knotCounts) + .set_write(write_knotCounts), + ), # u8* + ( + "interpolationData", + CDataExt_Value("I") + .set_report(report_interpolationData) + .set_write(write_interpolationData), + ), # CurveInterpKnot* + ( + "constantData", + CDataExt_Value("I") + .set_report(report_constantData) + .set_write(write_constantData), + ), # s16* + ("unk_0C", CDataExt_Value.s16), + ("frameCount", CDataExt_Value.s16), + ) + ) + + def try_parse_data(self, memory_context): + super().try_parse_data(memory_context) + knotCounts = self.cdata_unpacked["knotCounts"] + interpolationData = self.cdata_unpacked["interpolationData"] + constantData = self.cdata_unpacked["constantData"] + resource_knotCounts = memory_context.resolve_segmented(knotCounts).get_resource( + KnotCountsArrayResource + ) + resource_interpolationData = memory_context.resolve_segmented( + interpolationData + ).get_resource(CurveInterpKnotArrayResource) + resource_constantData = memory_context.resolve_segmented( + constantData + ).get_resource(ConstantDataArrayResource) + if ( + resource_knotCounts.file + == resource_interpolationData.file + == resource_constantData.file + == self.file + ): + knotCounts_offset = resource_knotCounts.range_start + constantData_offset = resource_constantData.range_start + interpolationData_offset = resource_interpolationData.range_start + animHeader_offset = self.range_start + assert ( + knotCounts_offset + < constantData_offset + < interpolationData_offset + < animHeader_offset + ) + resource_knotCounts.length = ( + constantData_offset - knotCounts_offset + ) // resource_knotCounts.elem_cdata_ext.size + resource_constantData.length = ( + interpolationData_offset - constantData_offset + ) // resource_constantData.elem_cdata_ext.size + resource_interpolationData.length = ( + animHeader_offset - interpolationData_offset + ) // resource_interpolationData.elem_cdata_ext.size + + return RESOURCE_PARSE_SUCCESS + else: + raise NotImplementedError + + def get_c_declaration_base(self): + return f"CurveAnimationHeader {self.symbol_name}" + + def get_c_reference(self, resource_offset: int): + raise ValueError() + + def get_h_includes(self): + return ("z64curve.h",) + + +class SkelCurveLimbResource(CDataResource): + cdata_ext = CDataExt_Struct( + ( + ("child", CDataExt_Value.u8), + ("sibling", CDataExt_Value.u8), + ("pad2", CDataExt_Value.pad16), + ( + "dList", + CDataExt_Array( + dlist_resources.cdata_ext_gfx_segmented, # Gfx* + 2, + ), + ), + ) + ) + + def get_c_declaration_base(self): + return f"SkelCurveLimb {self.symbol_name}" + + def get_c_reference(self, resource_offset: int): + if resource_offset == 0: + return f"&{self.symbol_name}" + else: + raise ValueError() + + def get_h_includes(self): + return ("z64curve.h",) + + +class SkelCurveLimbArrayResource(CDataResource): + def report_limb_element(resource, memory_context: "MemoryContext", v): + assert isinstance(v, int) + address = v + memory_context.report_resource_at_segmented( + resource, + address, + SkelCurveLimbResource, + lambda file, offset: SkelCurveLimbResource( + file, offset, f"{resource.name}_{address:08X}" + ), + ) + + def write_limb_element( + resource, memory_context: "MemoryContext", v, wctx: CDataExtWriteContext + ): + assert isinstance(v, int) + address = v + wctx.f.write(wctx.line_prefix) + wctx.f.write(memory_context.get_c_reference_at_segmented(address)) + return True + + elem_cdata_ext = ( + CDataExt_Value("I") + .set_report(report_limb_element) + .set_write(write_limb_element) + ) + + def __init__(self, file: File, range_start: int, name: str, length: int): + self.cdata_ext = CDataExt_Array(self.elem_cdata_ext, length) + super().__init__(file, range_start, name) + + def get_c_declaration_base(self): + return f"SkelCurveLimb* {self.symbol_name}[]" + + def get_c_reference(self, resource_offset: int): + if resource_offset == 0: + return self.symbol_name + else: + raise ValueError() + + def get_h_includes(self): + return ("z64curve.h",) + + +class CurveSkeletonHeaderResource(CDataResource): + def report_limbs(resource, memory_context: "MemoryContext", v): + assert isinstance(v, int) + address = v + memory_context.report_resource_at_segmented( + resource, + address, + SkelCurveLimbArrayResource, + lambda file, offset: SkelCurveLimbArrayResource( + file, + offset, + f"{resource.name}_Limbs_", + resource.cdata_unpacked["limbCount"], + ), + ) + + def write_limbs( + resource, memory_context: "MemoryContext", v, wctx: CDataExtWriteContext + ): + assert isinstance(v, int) + address = v + wctx.f.write(wctx.line_prefix) + wctx.f.write(memory_context.get_c_reference_at_segmented(address)) + return True + + cdata_ext = CDataExt_Struct( + ( + ( + "limbs", + CDataExt_Value("I").set_report(report_limbs).set_write(write_limbs), + ), # SkelCurveLimb** + ("limbCount", CDataExt_Value.u8), + ("pad5", CDataExt_Value.pad8), + ("pad6", CDataExt_Value.pad16), + ) + ) + + def get_c_declaration_base(self): + return f"CurveSkeletonHeader {self.symbol_name}" + + def get_c_reference(self, resource_offset: int): + raise ValueError() + + def get_h_includes(self): + return ("z64curve.h",) diff --git a/tools/assets/extract/extase_oot64/skeleton_resources.py b/tools/assets/extract/extase_oot64/skeleton_resources.py new file mode 100644 index 0000000000..a3459d1172 --- /dev/null +++ b/tools/assets/extract/extase_oot64/skeleton_resources.py @@ -0,0 +1,356 @@ +# SPDX-FileCopyrightText: © 2025 ZeldaRET +# SPDX-License-Identifier: CC0-1.0 + +import abc +from typing import TYPE_CHECKING + +from ..extase import ( + RESOURCE_PARSE_SUCCESS, + ResourceParseInProgress, + ResourceParseWaiting, +) + +if TYPE_CHECKING: + from ..extase.memorymap import MemoryContext + +from ..extase.cdata_resources import ( + CDataResource, + CDataArrayResource, + CDataExt_Value, + CDataExt_Struct, + CDataExt_Array, + CDataExtWriteContext, + cdata_ext_Vec3s, +) + +from . import dlist_resources + + +class StandardLimbResource(CDataResource): + def write_limb_index( + resource, memory_context: "MemoryContext", v, wctx: CDataExtWriteContext + ): + assert isinstance(v, int) + f = wctx.f + f.write(wctx.line_prefix) + if resource.skeleton_resource is None: + f.write(f"{v}") + else: + f.write(f"/* {v} */ ") + if v == 0xFF: + f.write("LIMB_DONE") + else: + f.write( + resource.skeleton_resource.limbs_array_resource.limbs[ + v + ].enum_member_name + ) + f.write(" - 1") + return True + + cdata_ext = CDataExt_Struct( + ( + ("jointPos", cdata_ext_Vec3s), + ("child", CDataExt_Value("B").set_write(write_limb_index)), + ("sibling", CDataExt_Value("B").set_write(write_limb_index)), + ("dList", dlist_resources.cdata_ext_gfx_segmented), + ) + ) + + def __init__(self, file, range_start, name): + super().__init__(file, range_start, name) + self.enum_member_name = f"LIMB_{file.name.upper()}_{range_start:06X}" + self.skeleton_resource: "SkeletonResourceBaseABC | None" = None + + def set_enum_member_name(self, enum_member_name: str): + self.enum_member_name = enum_member_name + + def get_c_declaration_base(self): + return f"StandardLimb {self.symbol_name}" + + def get_c_reference(self, resource_offset: int): + if resource_offset == 0: + return f"&{self.symbol_name}" + else: + raise ValueError() + + def get_h_includes(self): + return ("z64animation.h",) + + +class LODLimbResource(CDataResource): + cdata_ext = CDataExt_Struct( + ( + ("jointPos", cdata_ext_Vec3s), + ( + "child", + CDataExt_Value("B").set_write(StandardLimbResource.write_limb_index), + ), + ( + "sibling", + CDataExt_Value("B").set_write(StandardLimbResource.write_limb_index), + ), + ("dLists", CDataExt_Array(dlist_resources.cdata_ext_gfx_segmented, 2)), + ) + ) + + def __init__(self, file, range_start, name): + super().__init__(file, range_start, name) + self.enum_member_name = f"LIMB_{file.name.upper()}_{range_start:06X}" + + def set_enum_member_name(self, enum_member_name: str): + self.enum_member_name = enum_member_name + + def get_c_declaration_base(self): + return f"LodLimb {self.symbol_name}" + + def get_c_reference(self, resource_offset: int): + if resource_offset == 0: + return f"&{self.symbol_name}" + else: + raise ValueError() + + def get_h_includes(self): + return ("z64animation.h",) + + +class LimbsArrayResourceABC(CDataArrayResource): + limb_type: type[CDataResource] + c_limb_type: str + + def write_limb_element( + resource, memory_context: "MemoryContext", v, wctx: CDataExtWriteContext + ): + assert isinstance(v, int) + address = v + wctx.f.write(wctx.line_prefix) + wctx.f.write(memory_context.get_c_reference_at_segmented(address)) + return True + + elem_cdata_ext = CDataExt_Value("I").set_write(write_limb_element) + + def __init__(self, file, range_start, name): + super().__init__(file, range_start, name) + self.limbs = None + + def try_parse_data(self, memory_context): + ret = super().try_parse_data(memory_context) + assert ret == RESOURCE_PARSE_SUCCESS + self.limbs: list[self.limb_type] = [] + for address in self.cdata_unpacked: + limb = memory_context.report_resource_at_segmented( + self, + address, + self.limb_type, + lambda file, offset: self.limb_type( + file, + offset, + f"{self.name}_{address:08X}_{self.c_limb_type}", + ), + ) + self.limbs.append(limb) + return RESOURCE_PARSE_SUCCESS + + def get_c_declaration_base(self): + return f"void* {self.symbol_name}[]" + + +class StandardLimbsArrayResource(LimbsArrayResourceABC): + limb_type = StandardLimbResource + c_limb_type = "StandardLimb" + + +class LODLimbsArrayResource(LimbsArrayResourceABC): + limb_type = LODLimbResource + c_limb_type = "LodLimb" + + +class SkeletonResourceBaseABC(CDataResource): + limbs_array_type: type[LimbsArrayResourceABC] + + def __init__(self, file, range_start, name): + super().__init__(file, range_start, name) + self.enum_name = f"{self.symbol_name}Limb" + self.enum_member_name_none = f"LIMB_{file.name.upper()}_{range_start:06X}_NONE" + self.enum_member_name_max = f"LIMB_{file.name.upper()}_{range_start:06X}_MAX" + self.limbs_array_resource = None + + def set_enum_name(self, enum_name: str): + self.enum_name = enum_name + + def set_enum_member_name_none(self, enum_member_name_none: str): + self.enum_member_name_none = enum_member_name_none + + def set_enum_member_name_max(self, enum_member_name_max: str): + self.enum_member_name_max = enum_member_name_max + + def try_parse_data(self, memory_context): + if self.limbs_array_resource is None: + ret = super().try_parse_data(memory_context) + assert ret == RESOURCE_PARSE_SUCCESS + data = self.get_skeleton_header_cdata_unpacked() + segment_resolve_result = memory_context.resolve_segmented(data["segment"]) + self.limbs_array_resource = segment_resolve_result.get_resource( + self.limbs_array_type + ) + if self.limbs_array_resource.limbs is None: + raise ResourceParseInProgress( + new_progress_done=["reported limbs array"], + waiting_for=["self.limbs_array_resource.limbs"], + ) + else: + if self.limbs_array_resource.limbs is None: + raise ResourceParseWaiting( + waiting_for=["self.limbs_array_resource.limbs"], + ) + for limb in self.limbs_array_resource.limbs: + limb.skeleton_resource = self + return RESOURCE_PARSE_SUCCESS + + def write_c_declaration(self, h): + h.write(f"typedef enum {self.enum_name} {{\n") + limb_enum_members = ( + self.enum_member_name_none, + *(limb.enum_member_name for limb in self.limbs_array_resource.limbs), + self.enum_member_name_max, + ) + h.write( + ",\n".join( + f" /* {i:2} */ {enum_member}" + for i, enum_member in enumerate(limb_enum_members) + ) + + "\n" + ) + h.write(f"}} {self.enum_name};\n") + super().write_c_declaration(h) + return True + + @abc.abstractmethod + def get_skeleton_header_cdata_unpacked(self) -> dict: ... + + +class SkeletonResourceABC(SkeletonResourceBaseABC): + + def report_segment(resource, memory_context: "MemoryContext", v): + assert isinstance(v, int) + address = v + resource_limbs = memory_context.report_resource_at_segmented( + resource, + address, + resource.limbs_array_type, + lambda file, offset: resource.limbs_array_type( + file, + offset, + f"{resource.name}_{address:08X}_Limbs", + ), + ) + resource_limbs.set_length( + resource.get_skeleton_header_cdata_unpacked()["limbCount"] + ) + + def write_segment( + resource, memory_context: "MemoryContext", v, wctx: CDataExtWriteContext + ): + assert isinstance(v, int) + address = v + wctx.f.write(wctx.line_prefix) + wctx.f.write(memory_context.get_c_reference_at_segmented(address)) + return True + + def write_limbCount( + resource, memory_context: "MemoryContext", v, wctx: CDataExtWriteContext + ): + wctx.f.write(wctx.line_prefix) + wctx.f.write( + memory_context.get_c_expression_length_at_segmented( + resource.get_skeleton_header_cdata_unpacked()["segment"] + ) + ) + return True + + cdata_ext = CDataExt_Struct( + ( + ( + "segment", + CDataExt_Value("I").set_report(report_segment).set_write(write_segment), + ), + ( + "limbCount", + CDataExt_Value("B").set_write(write_limbCount), + ), + ("pad5", CDataExt_Value.pad8), + ("pad6", CDataExt_Value.pad16), + ) + ) + + def get_skeleton_header_cdata_unpacked(self): + return self.cdata_unpacked + + def get_c_reference(self, resource_offset: int): + if resource_offset == 0: + return f"&{self.symbol_name}" + else: + raise ValueError() + + def get_c_declaration_base(self): + return f"SkeletonHeader {self.symbol_name}" + + def get_c_includes(self): + return ("array_count.h",) + + def get_h_includes(self): + return ("z64animation.h",) + + +class SkeletonNormalResource(SkeletonResourceABC): + limbs_array_type = StandardLimbsArrayResource + + +class SkeletonNormalLODResource(SkeletonResourceABC): + limbs_array_type = LODLimbsArrayResource + + +class SkeletonFlexResourceABC(SkeletonResourceBaseABC): + skeleton_type: type[SkeletonResourceABC] + + # For SkeletonResourceABC.report_segment + @property + def limbs_array_type(self): + return self.skeleton_type.limbs_array_type + + def __init__(self, file, range_start, name): + self.cdata_ext = CDataExt_Struct( + ( + ("sh", self.skeleton_type.cdata_ext), + ("dListCount", CDataExt_Value.u8), + ("pad9", CDataExt_Value.pad8), + ("pad10", CDataExt_Value.pad16), + ) + ) + super().__init__(file, range_start, name) + + def get_skeleton_header_cdata_unpacked(self): + return self.cdata_unpacked["sh"] + + def get_c_reference(self, resource_offset: int): + if resource_offset == 0: + return f"&{self.symbol_name}" + else: + raise ValueError() + + def get_c_declaration_base(self): + return f"FlexSkeletonHeader {self.symbol_name}" + + def get_c_includes(self): + return ("array_count.h",) + + def get_h_includes(self): + return ("z64animation.h",) + + +class SkeletonFlexResource(SkeletonFlexResourceABC): + skeleton_type = SkeletonNormalResource + + +class SkeletonFlexLODResource(SkeletonFlexResourceABC): + skeleton_type = SkeletonNormalLODResource diff --git a/tools/assets/extract/extase_oot64/skeleton_skin_resources.py b/tools/assets/extract/extase_oot64/skeleton_skin_resources.py new file mode 100644 index 0000000000..b1ad1e5b3a --- /dev/null +++ b/tools/assets/extract/extase_oot64/skeleton_skin_resources.py @@ -0,0 +1,279 @@ +# SPDX-FileCopyrightText: © 2025 ZeldaRET +# SPDX-License-Identifier: CC0-1.0 + +from typing import TYPE_CHECKING + +from ..oot64_data.misc_ids import SKIN_LIMB_TYPES + +if TYPE_CHECKING: + from ..extase.memorymap import MemoryContext + +from ..extase.cdata_resources import ( + CDataResource, + CDataArrayResource, + CDataExt_Value, + CDataExt_Struct, + CDataExtWriteContext, + cdata_ext_Vec3s, +) + +from . import dlist_resources +from . import skeleton_resources + + +class SkinVertexArrayResource(CDataArrayResource): + elem_cdata_ext = CDataExt_Struct( + ( + ("index", CDataExt_Value.u16), + ("s", CDataExt_Value.s16), + ("t", CDataExt_Value.s16), + ("normX", CDataExt_Value.s8), + ("normY", CDataExt_Value.s8), + ("normZ", CDataExt_Value.s8), + ("alpha", CDataExt_Value.u8), + ) + ) + + def get_c_declaration_base(self): + return f"SkinVertex {self.symbol_name}[]" + + def get_h_includes(self): + return ("z64skin.h",) + + +class SkinTransformationArrayResource(CDataArrayResource): + elem_cdata_ext = CDataExt_Struct( + ( + ("limbIndex", CDataExt_Value.u8), + ("pad1", CDataExt_Value.pad8), + ("x", CDataExt_Value.s16), + ("y", CDataExt_Value.s16), + ("z", CDataExt_Value.s16), + ("scale", CDataExt_Value.u8), + ("pad9", CDataExt_Value.pad8), + ) + ) + + def get_c_declaration_base(self): + return f"SkinTransformation {self.symbol_name}[]" + + def get_h_includes(self): + return ("z64skin.h",) + + +class SkinLimbModifArrayResource(CDataArrayResource): + def report_elem(resource, memory_context: "MemoryContext", v): + assert isinstance(v, dict) + + address = v["skinVertices"] + assert isinstance(address, int) + skin_vertices_res = memory_context.report_resource_at_segmented( + resource, + address, + SkinVertexArrayResource, + lambda file, offset: SkinVertexArrayResource( + file, + offset, + f"{resource.name}_{offset:08X}_SkinVertices", + ), + ) + skin_vertices_res.set_length(v["vtxCount"]) + + address = v["limbTransformations"] + assert isinstance(address, int) + skin_vertices_res = memory_context.report_resource_at_segmented( + resource, + address, + SkinTransformationArrayResource, + lambda file, offset: SkinTransformationArrayResource( + file, + offset, + f"{resource.name}_{offset:08X}_SkinTransforms", + ), + ) + skin_vertices_res.set_length(v["transformCount"]) + + def write_skinVertices( + resource, memory_context: "MemoryContext", v, wctx: CDataExtWriteContext + ): + assert isinstance(v, int) + address = v + wctx.f.write(wctx.line_prefix) + wctx.f.write(memory_context.get_c_reference_at_segmented(address)) + return True + + def write_limbTransformations( + resource, memory_context: "MemoryContext", v, wctx: CDataExtWriteContext + ): + assert isinstance(v, int) + address = v + wctx.f.write(wctx.line_prefix) + wctx.f.write(memory_context.get_c_reference_at_segmented(address)) + return True + + elem_cdata_ext = CDataExt_Struct( + ( + ("vtxCount", CDataExt_Value.u16), + ("transformCount", CDataExt_Value.u16), + ("unk_4", CDataExt_Value.u16), + ("pad6", CDataExt_Value.pad16), + ( + "skinVertices", + (CDataExt_Value("I").set_write(write_skinVertices)), + ), # SkinVertex* + ( + "limbTransformations", + (CDataExt_Value("I").set_write(write_limbTransformations)), + ), # SkinTransformation* + ) + ).set_report(report_elem) + + def get_c_declaration_base(self): + return f"SkinLimbModif {self.symbol_name}[]" + + def get_h_includes(self): + return ("z64skin.h",) + + +class SkinAnimatedLimbDataResource(CDataResource): + def report_limbModifications(resource, memory_context: "MemoryContext", v): + assert isinstance(v, int) + address = v + skin_vertices_res = memory_context.report_resource_at_segmented( + resource, + address, + SkinLimbModifArrayResource, + lambda file, offset: SkinLimbModifArrayResource( + file, + offset, + f"{resource.name}_{offset:08X}_SkinLimbModifs", + ), + ) + skin_vertices_res.set_length(resource.cdata_unpacked["limbModifCount"]) + + def write_limbModifications( + resource, memory_context: "MemoryContext", v, wctx: CDataExtWriteContext + ): + assert isinstance(v, int) + address = v + wctx.f.write(wctx.line_prefix) + wctx.f.write(memory_context.get_c_reference_at_segmented(address)) + return True + + cdata_ext = CDataExt_Struct( + ( + ("totalVtxCount", CDataExt_Value.u16), + ("limbModifCount", CDataExt_Value.u16), + ( + "limbModifications", + ( + CDataExt_Value("I") + .set_report(report_limbModifications) + .set_write(write_limbModifications) + ), + ), # SkinLimbModif* + ("dlist", dlist_resources.cdata_ext_gfx_segmented), + ) + ) + + def get_c_declaration_base(self): + return f"SkinAnimatedLimbData {self.symbol_name}" + + def get_c_reference(self, resource_offset: int): + if resource_offset == 0: + return f"&{self.symbol_name}" + else: + raise ValueError() + + def get_h_includes(self): + return ("z64skin.h",) + + +class SkinLimbResource(CDataResource): + def report_segment(resource, memory_context: "MemoryContext", v): + assert isinstance(v, int) + address = v + segmentType = resource.cdata_unpacked["segmentType"] + if segmentType == 4: # SKIN_LIMB_TYPE_ANIMATED + # segment is SkinAnimatedLimbData* + assert address != 0 + memory_context.report_resource_at_segmented( + resource, + address, + SkinAnimatedLimbDataResource, + lambda file, offset: SkinAnimatedLimbDataResource( + file, offset, f"{resource.name}_{address:08X}_SkinAnimatedLimbData" + ), + ) + elif segmentType == 11: # SKIN_LIMB_TYPE_NORMAL + # segment is Gfx* + assert address != 0 + dlist_resources.report_gfx_segmented(resource, memory_context, address) + + def write_segment( + resource, memory_context: "MemoryContext", v, wctx: CDataExtWriteContext + ): + assert isinstance(v, int) + address = v + wctx.f.write(wctx.line_prefix) + if address == 0: + wctx.f.write("NULL") + else: + wctx.f.write(memory_context.get_c_reference_at_segmented(address)) + return True + + cdata_ext = CDataExt_Struct( + ( + ("jointPos", cdata_ext_Vec3s), + ( + "child", + CDataExt_Value("B").set_write( + skeleton_resources.StandardLimbResource.write_limb_index + ), + ), + ( + "sibling", + CDataExt_Value("B").set_write( + skeleton_resources.StandardLimbResource.write_limb_index + ), + ), + ( + "segmentType", + CDataExt_Value("i").set_write_str_v( + lambda v: SKIN_LIMB_TYPES.get(v, f"{v}") + ), + ), + ( + "segment", + CDataExt_Value("I").set_report(report_segment).set_write(write_segment), + ), + ) + ) + + def __init__(self, file, range_start, name): + super().__init__(file, range_start, name) + self.enum_member_name = f"LIMB_{file.name.upper()}_{range_start:06X}" + + def set_enum_member_name(self, enum_member_name: str): + self.enum_member_name = enum_member_name + + def get_c_declaration_base(self): + return f"SkinLimb {self.symbol_name}" + + def get_c_reference(self, resource_offset: int): + if resource_offset == 0: + return f"&{self.symbol_name}" + else: + raise ValueError() + + def get_h_includes(self): + return ("z64skin.h",) + + +class SkinLimbsArrayResource(skeleton_resources.LimbsArrayResourceABC): + limb_type = SkinLimbResource + c_limb_type = "SkinLimb" + + +class SkeletonSkinResource(skeleton_resources.SkeletonResourceABC): + limbs_array_type = SkinLimbsArrayResource diff --git a/tools/assets/extract/extract_xml_z64.py b/tools/assets/extract/extract_xml_z64.py new file mode 100644 index 0000000000..7177082fdf --- /dev/null +++ b/tools/assets/extract/extract_xml_z64.py @@ -0,0 +1,511 @@ +# SPDX-FileCopyrightText: © 2025 ZeldaRET +# SPDX-License-Identifier: CC0-1.0 + +import dataclasses +from pathlib import Path + +from ..descriptor.base import ( + BaseromFileBackingMemory, + get_resources_desc, + ResourceDesc, + ResourcesDescCollection, + ResourcesDescCollectionsPool, + SegmentStartAddress, + VRAMStartAddress, +) + +from .extase import File, Resource +from .extase.memorymap import MemoryContext + +from . import z64_resource_handlers + +try: + import rich + import rich.console + import rich.pretty +except ImportError: + USE_RICH = False +else: + USE_RICH = True + +# +# main +# + +VERBOSE1 = False +VERBOSE2 = False +VERBOSE3 = False + +# "options" +RM_SOURCE = True +WRITE_SOURCE = True +RM_EXTRACT = True +WRITE_EXTRACT = True +from ..conf import WRITE_HINTS, I_D_OMEGALUL + + +@dataclasses.dataclass +class ExtractionContext: + oot_version: str + version_memctx_base: MemoryContext + baserom_path: Path + build_path: Path + extracted_path: Path + + def get_baserom_file_data(self, baserom_file_name: str): + return memoryview((self.baserom_path / baserom_file_name).read_bytes()) + + +def create_file_resources(rescoll: ResourcesDescCollection, file: File): + """Collect resources described by the collection into the file object. + + Does not do any processing of the data itself: no parsing, no discovering more resources. + """ + + file_resources_by_desc: dict[ResourceDesc, Resource] = dict() + + list_ResourceNeedsPostProcessWithPoolResourcesException: list[ + z64_resource_handlers.ResourceNeedsPostProcessWithPoolResourcesException + ] = [] + + for resource_desc in rescoll.resources: + + try: + resource = z64_resource_handlers.get_resource_from_desc(file, resource_desc) + except ( + z64_resource_handlers.ResourceNeedsPostProcessWithPoolResourcesException + ) as e: + resource = e.resource + list_ResourceNeedsPostProcessWithPoolResourcesException.append(e) + except Exception as e: + raise Exception( + "Error while creating resource from description:", resource_desc + ) from e + + # TODO nice hack right here. + # probably instead rework the "c declaration" system into a more opaque object + # not that this is really a required long term feature as it's only relevant + # for writing the source files (main .c/.h), not extracting + if file.name.startswith("ovl_") and file.name != "ovl_file_choose": + resource.HACK_IS_STATIC_ON = ... + + file.add_resource(resource) + + file_resources_by_desc[resource_desc] = resource + + if VERBOSE1: + print(file) + print(file.name, file._resources) + + # Check if described resources overlap + file.sort_resources() + file.check_overlapping_resources() + + return ( + file_resources_by_desc, + list_ResourceNeedsPostProcessWithPoolResourcesException, + ) + + +def process_pool( + extraction_ctx: ExtractionContext, pool_desc: ResourcesDescCollectionsPool +): + if VERBOSE1: + print("> process_pool") + colls_str = " + ".join(set(map(str, (_c.out_path for _c in pool_desc.collections)))) + if USE_RICH: + rich.print(f"[b]{colls_str}[/b]") + else: + print(colls_str) + + file_by_rescoll: dict[ResourcesDescCollection, File] = dict() + + # 1) Create File and Resource objects + + pool_resources_by_desc: dict[ResourceDesc, Resource] = dict() + list_all_ResourceNeedsPostProcessWithPoolResourcesException: list[ + z64_resource_handlers.ResourceNeedsPostProcessWithPoolResourcesException + ] = [] + for rescoll in pool_desc.collections: + if not isinstance(rescoll.backing_memory, BaseromFileBackingMemory): + raise NotImplementedError(rescoll.backing_memory) + data = extraction_ctx.get_baserom_file_data(rescoll.backing_memory.name) + if rescoll.backing_memory.range is not None: + range_start, range_end = rescoll.backing_memory.range + data = data[range_start:range_end] + + if isinstance(rescoll.start_address, VRAMStartAddress): + if rescoll.start_address.vram % 8 == 0: + alignment = 8 + elif rescoll.start_address.vram % 4 == 0: + alignment = 4 + else: + raise NotImplementedError( + f"alignment for {rescoll.start_address.vram=:#08X}" + ) + elif ( + isinstance(rescoll.start_address, SegmentStartAddress) + or rescoll.start_address is None + ): + alignment = 8 + else: + raise NotImplementedError(rescoll.start_address) + # TODO File.name + file = File(rescoll.backing_memory.name, data=data, alignment=alignment) + file_by_rescoll[rescoll] = file + + ( + file_resources_by_desc, + list_ResourceNeedsPostProcessWithPoolResourcesException, + ) = create_file_resources(rescoll, file) + pool_resources_by_desc |= file_resources_by_desc + list_all_ResourceNeedsPostProcessWithPoolResourcesException.extend( + list_ResourceNeedsPostProcessWithPoolResourcesException + ) + + for e in list_all_ResourceNeedsPostProcessWithPoolResourcesException: + e.callback(pool_resources_by_desc) + + # 2) Build a MemoryContext for each File + + memctx_base = extraction_ctx.version_memctx_base.copy() + memctx_by_file: dict[File, MemoryContext] = dict() + + for rescoll, file in file_by_rescoll.items(): + if VERBOSE2: + print("Building MemoryContext for", file.name) + files_by_segment: dict[int, list[File]] = dict() + file_memctx = memctx_base.copy() + + for rescoll_dep in (rescoll, *rescoll.depends): + file_dep = file_by_rescoll[rescoll_dep] + + if rescoll_dep.start_address is None: + pass + elif isinstance(rescoll_dep.start_address, SegmentStartAddress): + files_by_segment.setdefault( + rescoll_dep.start_address.segment, [] + ).append(file_dep) + elif isinstance(rescoll_dep.start_address, VRAMStartAddress): + file_memctx.set_direct_file(rescoll_dep.start_address.vram, file_dep) + if file_dep != file: + file.referenced_files.add(file_dep) + else: + raise NotImplementedError(rescoll_dep.start_address) + + disputed_segments = [] + + for segment, files in files_by_segment.items(): + if len(files) == 1: + file_memctx.set_segment_file(segment, files[0]) + if files[0] != file: + file.referenced_files.add(files[0]) + if VERBOSE2: + print("segment", segment, "set to", files[0].name) + else: + disputed_segments.append(segment) + + if VERBOSE2: + print(f"{disputed_segments=}") + + if ( + isinstance(rescoll.start_address, SegmentStartAddress) + and rescoll.start_address.segment in disputed_segments + ): + if VERBOSE2: + print( + "disputed segment", + rescoll.start_address.segment, + "set to own file for file's memctx", + file.name, + ) + file_memctx.set_segment_file(rescoll.start_address.segment, file) + memctx_by_file[file] = file_memctx + + # 3) parse: iteratively discover and parse data + # (discover = add resources, parse = make friendlier than binary) + + def parse_all_files(): + while True: + any_progress = False + for file, file_memctx in memctx_by_file.items(): + if VERBOSE3: + print(file.name, ".try_parse_resources_data()") + if file.try_parse_resources_data(file_memctx): + any_progress = True + if not any_progress: + break + + for file in memctx_by_file.keys(): + file.check_non_parsed_resources() + + if VERBOSE3: + print("parse_all_files() ...") + parse_all_files() + + for file in memctx_by_file.keys(): + file.commit_resource_buffers() + + if VERBOSE3: + print("parse new resources (resource buffers) ...") + parse_all_files() # parse new resources (resource buffers) + + for file in memctx_by_file.keys(): + file.sort_resources() + file.check_overlapping_resources() + + # 4) add dummy (binary) resources for the unaccounted gaps + + if VERBOSE3: + print("unaccounted...") + + for file in memctx_by_file.keys(): + file.add_unaccounted_resources(I_D_OMEGALUL=I_D_OMEGALUL) + + parse_all_files() # FIXME this is to set is_data_parsed=True on binary blob unaccounteds, handle better + + for file in memctx_by_file.keys(): + file.sort_resources() + assert not file.get_overlapping_resources() + + # At this point all files are completely mapped with resources + + # 5) + + for rescoll, file in file_by_rescoll.items(): + file.set_source_path( + extraction_ctx.extracted_path / "assets" / rescoll.out_path + ) + + file.set_resources_paths( + extraction_ctx.extracted_path, + extraction_ctx.build_path, + Path("assets") / rescoll.out_path, + ) + + for file, file_memctx in memctx_by_file.items(): + # write to extracted/ + if WRITE_EXTRACT: + file.write_resources_extracted(file_memctx) + + # "source" refers to the main .c and .h `#include`ing all the extracted resources + if WRITE_SOURCE: + file.write_source() + + +def process_pool_wrapped(extraction_ctx, pd): + try: + process_pool(extraction_ctx, pd) + except Exception as e: + import traceback + import sys + + # Some exceptions can't be pickled for passing back to the main process + # so print them now as well as reraising + traceback.print_exc(file=sys.stdout) + raise Exception( + "ERROR with pool_desc collections:", + [str(rescoll.out_path) for rescoll in pd.collections], + ) from e + + +# Make interrupting jobs with ^C less jank +# https://stackoverflow.com/questions/72967793/keyboardinterrupt-with-python-multiprocessing-pool +def set_sigint_ignored(): + import signal + + signal.signal(signal.SIGINT, signal.SIG_IGN) + + +def main(): + import argparse + import json + import re + import time + + from tools import version_config + from tools import dmadata + + parser = argparse.ArgumentParser() + parser.add_argument( + "baserom_segments_dir", + type=Path, + help="Directory of uncompressed ROM segments", + ) + parser.add_argument( + "output_dir", + type=Path, + help="Output directory to place files in", + ) + parser.add_argument("-v", dest="oot_version", default="gc-eu-mq-dbg") + parser.add_argument("-j", dest="jobs", nargs="?", default=False, type=int) + parser.add_argument("-f", dest="force", action="store_true") + parser.add_argument("-s", dest="single", default=None) + parser.add_argument("-r", dest="single_is_regex", default=None, action="store_true") + args = parser.parse_args() + + vc = version_config.load_version_config(args.oot_version) + + dma_entries = dmadata.read_dmadata( + memoryview((args.baserom_segments_dir / "dmadata").read_bytes()), 0 + ) + dmadata_table_rom_file_name_by_vrom = dict() + for dma_entry, name in zip(dma_entries, vc.dmadata_segments.keys(), strict=True): + dmadata_table_rom_file_name_by_vrom[ + (dma_entry.vrom_start, dma_entry.vrom_end) + ] = name + + pools_desc = get_resources_desc(vc) + + last_extracts_json_p = args.output_dir / "last_extracts.json" + try: + with last_extracts_json_p.open("r") as f: + last_extracts = json.load(f) + except (OSError, json.decoder.JSONDecodeError): + last_extracts = dict() + + def is_pool_desc_modified(pool_desc: ResourcesDescCollectionsPool): + modified = False + for rdc in pool_desc.collections: + if isinstance(rdc.backing_memory, BaseromFileBackingMemory): + if rdc.last_modified_time > last_extracts.get( + f"{rdc.out_path} {rdc.backing_memory.name}", 0 + ): + modified = True + return modified + + def set_pool_desc_modified(pool_desc: ResourcesDescCollectionsPool): + for rdc in pool_desc.collections: + if isinstance(rdc.backing_memory, BaseromFileBackingMemory): + last_extracts[f"{rdc.out_path} {rdc.backing_memory.name}"] = ( + rdc.last_modified_time + ) + + version_memctx_base = MemoryContext(dmadata_table_rom_file_name_by_vrom) + + from .extase_oot64.dlist_resources import MtxResource, TextureResource + from ..n64 import G_IM_FMT, G_IM_SIZ + + file_gIdentityMtx = File("sys_matrix__gIdentityMtx", size=0x40) + file_gIdentityMtx.add_resource(MtxResource(file_gIdentityMtx, 0, "gIdentityMtx")) + version_memctx_base.set_direct_file(vc.variables["gIdentityMtx"], file_gIdentityMtx) + + file_sShadowTex = File("z_en_jsjutan__sShadowTex", size=0x800) + file_sShadowTex.add_resource( + TextureResource( + file_sShadowTex, 0, "sShadowTex", G_IM_FMT.I, G_IM_SIZ._8b, 32, 64 + ) + ) + version_memctx_base.set_direct_file(vc.variables["sShadowTex"], file_sShadowTex) + + extraction_ctx = ExtractionContext( + args.oot_version, + version_memctx_base, + args.baserom_segments_dir, + Path("build") / args.oot_version, + args.output_dir, + ) + + z64_resource_handlers.register_resource_handlers() + + try: + if args.single is not None: + any_match = False + any_pool_processed = False + for pool_desc in pools_desc: + pool_matches = False + for coll in pool_desc.collections: + if isinstance(coll.backing_memory, BaseromFileBackingMemory): + if args.single_is_regex: + if re.fullmatch(args.single, coll.backing_memory.name): + pool_matches = True + else: + if coll.backing_memory.name == args.single: + pool_matches = True + if pool_matches: + any_match = True + if args.force or is_pool_desc_modified(pool_desc): + process_pool(extraction_ctx, pool_desc) + set_pool_desc_modified(pool_desc) + any_pool_processed = True + if any_pool_processed: + print("Done!") + elif not any_match: + print("Not found:", args.single) + else: + print("Nothing to do") + elif args.jobs is False: # everything on one process + any_pool_processed = False + for pool_desc in pools_desc: + if args.force or is_pool_desc_modified(pool_desc): + process_pool(extraction_ctx, pool_desc) + set_pool_desc_modified(pool_desc) + any_pool_processed = True + if any_pool_processed: + print("All done!") + else: + print("Nothing to do") + else: # multiprocessing + import multiprocessing + + if args.force: + pools_desc_to_extract = pools_desc + else: + pools_desc_modified = [ + pool_desc + for pool_desc in pools_desc + if is_pool_desc_modified(pool_desc) + ] + pools_desc_to_extract = pools_desc_modified + + if pools_desc_to_extract: + with multiprocessing.get_context("fork").Pool( + processes=args.jobs, initializer=set_sigint_ignored + ) as pool: + jobs = [ + ( + pd, + pool.apply_async( + process_pool_wrapped, (extraction_ctx, pd) + ), + ) + for pd in pools_desc_to_extract + ] + while jobs: + any_finished = False + still_waiting_for_jobs = [] + for pd, ar in jobs: + try: + ar.get(0) + except multiprocessing.TimeoutError: + still_waiting_for_jobs.append((pd, ar)) + else: + any_finished = True + set_pool_desc_modified(pd) + jobs = still_waiting_for_jobs + if not any_finished: + time.sleep(0.001) + print("All done!") + else: + print("Nothing to do") + except Exception as e: + import traceback + import sys + + if USE_RICH: + rich.console.Console().print_exception() + # TODO implement more __rich_repr__ + if e.__class__ in (Exception, AssertionError, NotImplementedError): + print("rich.pretty.pprint(e.args):") + rich.pretty.pprint(e.args, indent_guides=False) + else: + print("rich.pretty.pprint(e):") + rich.pretty.pprint(e, indent_guides=False) + else: + traceback.print_exc(file=sys.stdout) + print("Install rich for prettier output (`pip install rich`)") + + sys.exit(1) + finally: + with last_extracts_json_p.open("w") as f: + json.dump(last_extracts, f) diff --git a/tools/assets/extract/oot64_data/Makefile b/tools/assets/extract/oot64_data/Makefile new file mode 100644 index 0000000000..b36b6542f3 --- /dev/null +++ b/tools/assets/extract/oot64_data/Makefile @@ -0,0 +1,56 @@ +# SPDX-FileCopyrightText: © 2025 ZeldaRET +# SPDX-License-Identifier: CC0-1.0 + +ROOT := ../../../../ + +DATA_FILES := actor_ids.py object_ids.py entrance_table_mini.py scene_table_mini.py + +default: + @echo 'Run `make all` or with the appropriate target to (re)build data files' + +all: $(DATA_FILES) + +distclean: + $(RM) $(DATA_FILES) + +.PHONY: default all distclean + +actor_ids.py: $(ROOT)/include/tables/actor_table.h + echo '# This file was generated from $<' > $@ + echo >> $@ + echo 'DATA = (' >> $@ + cpp -P \ + -D'DEFINE_ACTOR(_0,enumValue,_2,_3)=#enumValue,' \ + -D'DEFINE_ACTOR_UNSET(enumValue)=#enumValue,' \ + -D'DEFINE_ACTOR_INTERNAL=DEFINE_ACTOR' \ + $< >> $@ + echo ')' >> $@ + +object_ids.py: $(ROOT)/include/tables/object_table.h + echo '# This file was generated from $<' > $@ + echo >> $@ + echo 'DATA = (' >> $@ + cpp -P \ + -D'DEFINE_OBJECT(_0,enumValue)=#enumValue,' \ + -D'DEFINE_OBJECT_UNSET(enumValue)=#enumValue,' \ + -D'DEFINE_OBJECT_NULL(_0,enumValue)=#enumValue,' \ + $< >> $@ + echo ')' >> $@ + +entrance_table_mini.py: $(ROOT)/include/tables/entrance_table.h + echo '# This file was generated from $<' > $@ + echo >> $@ + echo 'DATA = (' >> $@ + cpp -P \ + -D'DEFINE_ENTRANCE(enumValue, sceneId, spawn, _3, _4, _5, _6)=(#enumValue, #sceneId, spawn),' \ + $< >> $@ + echo ')' >> $@ + +scene_table_mini.py: $(ROOT)/include/tables/scene_table.h + echo '# This file was generated from $<' > $@ + echo >> $@ + echo 'DATA = (' >> $@ + cpp -P \ + -D'DEFINE_SCENE(name, _1, enumValue, _3, _4, _5)=(#name, #enumValue),' \ + $< >> $@ + echo ')' >> $@ diff --git a/tools/assets/extract/oot64_data/__init__.py b/tools/assets/extract/oot64_data/__init__.py new file mode 100644 index 0000000000..7e90913ed9 --- /dev/null +++ b/tools/assets/extract/oot64_data/__init__.py @@ -0,0 +1,128 @@ +# SPDX-FileCopyrightText: © 2025 ZeldaRET +# SPDX-License-Identifier: CC0-1.0 + +from typing import Sequence + + +I_D_OMEGALUL = True + + +from . import actor_ids + + +def get_actor_id_name(actor_id: int) -> str: + return actor_ids.DATA[actor_id] + + +from . import object_ids + + +def get_object_id_name(object_id: int) -> str: + return object_ids.DATA[object_id] + + +from . import entrance_table_mini +from . import entrance_ids_special + + +def get_entrance_id_name(entrance_id: int) -> str: + if entrance_id in entrance_ids_special.DATA: + return entrance_ids_special.DATA[entrance_id] + return entrance_table_mini.DATA[entrance_id][0] + + +def get_entrance_scene_id_name(entrance_id: int) -> str: + return entrance_table_mini.DATA[entrance_id][1] + + +def get_entrance_spawn(entrance_id: int) -> int: + return entrance_table_mini.DATA[entrance_id][2] + + +entrance_ids_by_scene_id_name: dict[str, list[int]] = dict() +for ( + entrance_id, + ( + entrance_id_name, + entrance_scene_id_name, + entrance_spawn, + ), +) in enumerate(entrance_table_mini.DATA): + entrance_ids_by_scene_id_name.setdefault(entrance_scene_id_name, []).append( + entrance_id + ) + + +def get_entrance_ids_from_scene_id_name(scene_id_name: str) -> Sequence[int]: + return entrance_ids_by_scene_id_name[scene_id_name] + + +from . import scene_table_mini + + +def get_scene_rom_file_name(scene_id: int) -> str: + return scene_table_mini.DATA[scene_id][0] + + +def get_scene_id_name(scene_id: int) -> str: + return scene_table_mini.DATA[scene_id][1] + + +scene_id_by_rom_file_name = { + rom_file_name: scene_id + for scene_id, (rom_file_name, scene_id_name) in enumerate(scene_table_mini.DATA) +} + + +def get_scene_id_from_rom_file_name(rom_file_name: str) -> int: + return scene_id_by_rom_file_name[rom_file_name] + + +from . import audio_ids + + +def get_sequence_id_name(sequence_id: int) -> str: + return audio_ids.SEQ_IDS[sequence_id] + + +def get_nature_ambience_id_name(nature_ambience_id: int) -> str: + return audio_ids.NATURE_AMBIENCE_IDS[nature_ambience_id] + + +from . import misc_ids + + +def get_scene_cam_type_name(scene_cam_type: int) -> str: + return misc_ids.SCENE_CAM_TYPES[scene_cam_type] + + +def get_room_behavior_type1_name(behavior_type1: int) -> str: + return misc_ids.ROOM_BEHAVIOR_TYPE1_NAMES[behavior_type1] + + +def get_room_behavior_type2_name(behavior_type2: int) -> str: + return misc_ids.ROOM_BEHAVIOR_TYPE2_NAMES[behavior_type2] + + +def get_lens_mode_name(lens_mode: int) -> str: + return misc_ids.LENS_MODES[lens_mode] + + +def get_camera_setting_type_name(camera_setting_type: int) -> str: + return misc_ids.CAMERA_SETTING_TYPES[camera_setting_type] + + +def get_room_shape_type_name(room_shape_type: int) -> str: + return misc_ids.ROOM_SHAPE_TYPE[room_shape_type] + + +def get_room_shape_image_amount_type_name(room_shape_image_amount_type: int) -> str: + return misc_ids.ROOM_SHAPE_IMAGE_AMOUNT_TYPE[room_shape_image_amount_type] + + +def get_skybox_id(skybox_id: int) -> str: + return misc_ids.SKYBOX_IDS[skybox_id] + + +def get_light_mode(light_mode: int) -> str: + return misc_ids.LIGHT_MODES[light_mode] diff --git a/tools/assets/extract/oot64_data/actor_ids.py b/tools/assets/extract/oot64_data/actor_ids.py new file mode 100644 index 0000000000..3654a9d2a2 --- /dev/null +++ b/tools/assets/extract/oot64_data/actor_ids.py @@ -0,0 +1,475 @@ +# This file was generated from ../../../..//include/tables/actor_table.h + +DATA = ( + "ACTOR_PLAYER", + "ACTOR_UNSET_1", + "ACTOR_EN_TEST", + "ACTOR_UNSET_3", + "ACTOR_EN_GIRLA", + "ACTOR_UNSET_5", + "ACTOR_UNSET_6", + "ACTOR_EN_PART", + "ACTOR_EN_LIGHT", + "ACTOR_EN_DOOR", + "ACTOR_EN_BOX", + "ACTOR_BG_DY_YOSEIZO", + "ACTOR_BG_HIDAN_FIREWALL", + "ACTOR_EN_POH", + "ACTOR_EN_OKUTA", + "ACTOR_BG_YDAN_SP", + "ACTOR_EN_BOM", + "ACTOR_EN_WALLMAS", + "ACTOR_EN_DODONGO", + "ACTOR_EN_FIREFLY", + "ACTOR_EN_HORSE", + "ACTOR_EN_ITEM00", + "ACTOR_EN_ARROW", + "ACTOR_UNSET_17", + "ACTOR_EN_ELF", + "ACTOR_EN_NIW", + "ACTOR_UNSET_1A", + "ACTOR_EN_TITE", + "ACTOR_EN_REEBA", + "ACTOR_EN_PEEHAT", + "ACTOR_EN_BUTTE", + "ACTOR_UNSET_1F", + "ACTOR_EN_INSECT", + "ACTOR_EN_FISH", + "ACTOR_UNSET_22", + "ACTOR_EN_HOLL", + "ACTOR_EN_SCENE_CHANGE", + "ACTOR_EN_ZF", + "ACTOR_EN_HATA", + "ACTOR_BOSS_DODONGO", + "ACTOR_BOSS_GOMA", + "ACTOR_EN_ZL1", + "ACTOR_EN_VIEWER", + "ACTOR_EN_GOMA", + "ACTOR_BG_PUSHBOX", + "ACTOR_EN_BUBBLE", + "ACTOR_DOOR_SHUTTER", + "ACTOR_EN_DODOJR", + "ACTOR_EN_BDFIRE", + "ACTOR_UNSET_31", + "ACTOR_EN_BOOM", + "ACTOR_EN_TORCH2", + "ACTOR_EN_BILI", + "ACTOR_EN_TP", + "ACTOR_UNSET_36", + "ACTOR_EN_ST", + "ACTOR_EN_BW", + "ACTOR_EN_A_OBJ", + "ACTOR_EN_EIYER", + "ACTOR_EN_RIVER_SOUND", + "ACTOR_EN_HORSE_NORMAL", + "ACTOR_EN_OSSAN", + "ACTOR_BG_TREEMOUTH", + "ACTOR_BG_DODOAGO", + "ACTOR_BG_HIDAN_DALM", + "ACTOR_BG_HIDAN_HROCK", + "ACTOR_EN_HORSE_GANON", + "ACTOR_BG_HIDAN_ROCK", + "ACTOR_BG_HIDAN_RSEKIZOU", + "ACTOR_BG_HIDAN_SEKIZOU", + "ACTOR_BG_HIDAN_SIMA", + "ACTOR_BG_HIDAN_SYOKU", + "ACTOR_EN_XC", + "ACTOR_BG_HIDAN_CURTAIN", + "ACTOR_BG_SPOT00_HANEBASI", + "ACTOR_EN_MB", + "ACTOR_EN_BOMBF", + "ACTOR_EN_ZL2", + "ACTOR_BG_HIDAN_FSLIFT", + "ACTOR_EN_OE2", + "ACTOR_BG_YDAN_HASI", + "ACTOR_BG_YDAN_MARUTA", + "ACTOR_BOSS_GANONDROF", + "ACTOR_UNSET_53", + "ACTOR_EN_AM", + "ACTOR_EN_DEKUBABA", + "ACTOR_EN_M_FIRE1", + "ACTOR_EN_M_THUNDER", + "ACTOR_BG_DDAN_JD", + "ACTOR_BG_BREAKWALL", + "ACTOR_EN_JJ", + "ACTOR_EN_HORSE_ZELDA", + "ACTOR_BG_DDAN_KD", + "ACTOR_DOOR_WARP1", + "ACTOR_OBJ_SYOKUDAI", + "ACTOR_ITEM_B_HEART", + "ACTOR_EN_DEKUNUTS", + "ACTOR_BG_MENKURI_KAITEN", + "ACTOR_BG_MENKURI_EYE", + "ACTOR_EN_VALI", + "ACTOR_BG_MIZU_MOVEBG", + "ACTOR_BG_MIZU_WATER", + "ACTOR_ARMS_HOOK", + "ACTOR_EN_FHG", + "ACTOR_BG_MORI_HINERI", + "ACTOR_EN_BB", + "ACTOR_BG_TOKI_HIKARI", + "ACTOR_EN_YUKABYUN", + "ACTOR_BG_TOKI_SWD", + "ACTOR_EN_FHG_FIRE", + "ACTOR_BG_MJIN", + "ACTOR_BG_HIDAN_KOUSI", + "ACTOR_DOOR_TOKI", + "ACTOR_BG_HIDAN_HAMSTEP", + "ACTOR_EN_BIRD", + "ACTOR_UNSET_73", + "ACTOR_UNSET_74", + "ACTOR_UNSET_75", + "ACTOR_UNSET_76", + "ACTOR_EN_WOOD02", + "ACTOR_UNSET_78", + "ACTOR_UNSET_79", + "ACTOR_UNSET_7A", + "ACTOR_UNSET_7B", + "ACTOR_EN_LIGHTBOX", + "ACTOR_EN_PU_BOX", + "ACTOR_UNSET_7E", + "ACTOR_UNSET_7F", + "ACTOR_EN_TRAP", + "ACTOR_EN_AROW_TRAP", + "ACTOR_EN_VASE", + "ACTOR_UNSET_83", + "ACTOR_EN_TA", + "ACTOR_EN_TK", + "ACTOR_BG_MORI_BIGST", + "ACTOR_BG_MORI_ELEVATOR", + "ACTOR_BG_MORI_KAITENKABE", + "ACTOR_BG_MORI_RAKKATENJO", + "ACTOR_EN_VM", + "ACTOR_DEMO_EFFECT", + "ACTOR_DEMO_KANKYO", + "ACTOR_BG_HIDAN_FWBIG", + "ACTOR_EN_FLOORMAS", + "ACTOR_EN_HEISHI1", + "ACTOR_EN_RD", + "ACTOR_EN_PO_SISTERS", + "ACTOR_BG_HEAVY_BLOCK", + "ACTOR_BG_PO_EVENT", + "ACTOR_OBJ_MURE", + "ACTOR_EN_SW", + "ACTOR_BOSS_FD", + "ACTOR_OBJECT_KANKYO", + "ACTOR_EN_DU", + "ACTOR_EN_FD", + "ACTOR_EN_HORSE_LINK_CHILD", + "ACTOR_DOOR_ANA", + "ACTOR_BG_SPOT02_OBJECTS", + "ACTOR_BG_HAKA", + "ACTOR_MAGIC_WIND", + "ACTOR_MAGIC_FIRE", + "ACTOR_UNSET_A0", + "ACTOR_EN_RU1", + "ACTOR_BOSS_FD2", + "ACTOR_EN_FD_FIRE", + "ACTOR_EN_DH", + "ACTOR_EN_DHA", + "ACTOR_EN_RL", + "ACTOR_EN_ENCOUNT1", + "ACTOR_DEMO_DU", + "ACTOR_DEMO_IM", + "ACTOR_DEMO_TRE_LGT", + "ACTOR_EN_FW", + "ACTOR_BG_VB_SIMA", + "ACTOR_EN_VB_BALL", + "ACTOR_BG_HAKA_MEGANE", + "ACTOR_BG_HAKA_MEGANEBG", + "ACTOR_BG_HAKA_SHIP", + "ACTOR_BG_HAKA_SGAMI", + "ACTOR_UNSET_B2", + "ACTOR_EN_HEISHI2", + "ACTOR_EN_ENCOUNT2", + "ACTOR_EN_FIRE_ROCK", + "ACTOR_EN_BROB", + "ACTOR_MIR_RAY", + "ACTOR_BG_SPOT09_OBJ", + "ACTOR_BG_SPOT18_OBJ", + "ACTOR_BOSS_VA", + "ACTOR_BG_HAKA_TUBO", + "ACTOR_BG_HAKA_TRAP", + "ACTOR_BG_HAKA_HUTA", + "ACTOR_BG_HAKA_ZOU", + "ACTOR_BG_SPOT17_FUNEN", + "ACTOR_EN_SYATEKI_ITM", + "ACTOR_EN_SYATEKI_MAN", + "ACTOR_EN_TANA", + "ACTOR_EN_NB", + "ACTOR_BOSS_MO", + "ACTOR_EN_SB", + "ACTOR_EN_BIGOKUTA", + "ACTOR_EN_KAREBABA", + "ACTOR_BG_BDAN_OBJECTS", + "ACTOR_DEMO_SA", + "ACTOR_DEMO_GO", + "ACTOR_EN_IN", + "ACTOR_EN_TR", + "ACTOR_BG_SPOT16_BOMBSTONE", + "ACTOR_UNSET_CE", + "ACTOR_BG_HIDAN_KOWARERUKABE", + "ACTOR_BG_BOMBWALL", + "ACTOR_BG_SPOT08_ICEBLOCK", + "ACTOR_EN_RU2", + "ACTOR_OBJ_DEKUJR", + "ACTOR_BG_MIZU_UZU", + "ACTOR_BG_SPOT06_OBJECTS", + "ACTOR_BG_ICE_OBJECTS", + "ACTOR_BG_HAKA_WATER", + "ACTOR_UNSET_D8", + "ACTOR_EN_MA2", + "ACTOR_EN_BOM_CHU", + "ACTOR_EN_HORSE_GAME_CHECK", + "ACTOR_BOSS_TW", + "ACTOR_EN_RR", + "ACTOR_EN_BA", + "ACTOR_EN_BX", + "ACTOR_EN_ANUBICE", + "ACTOR_EN_ANUBICE_FIRE", + "ACTOR_BG_MORI_HASHIGO", + "ACTOR_BG_MORI_HASHIRA4", + "ACTOR_BG_MORI_IDOMIZU", + "ACTOR_BG_SPOT16_DOUGHNUT", + "ACTOR_BG_BDAN_SWITCH", + "ACTOR_EN_MA1", + "ACTOR_BOSS_GANON", + "ACTOR_BOSS_SST", + "ACTOR_UNSET_EA", + "ACTOR_UNSET_EB", + "ACTOR_EN_NY", + "ACTOR_EN_FR", + "ACTOR_ITEM_SHIELD", + "ACTOR_BG_ICE_SHELTER", + "ACTOR_EN_ICE_HONO", + "ACTOR_ITEM_OCARINA", + "ACTOR_UNSET_F2", + "ACTOR_UNSET_F3", + "ACTOR_MAGIC_DARK", + "ACTOR_DEMO_6K", + "ACTOR_EN_ANUBICE_TAG", + "ACTOR_BG_HAKA_GATE", + "ACTOR_BG_SPOT15_SAKU", + "ACTOR_BG_JYA_GOROIWA", + "ACTOR_BG_JYA_ZURERUKABE", + "ACTOR_UNSET_FB", + "ACTOR_BG_JYA_COBRA", + "ACTOR_BG_JYA_KANAAMI", + "ACTOR_FISHING", + "ACTOR_OBJ_OSHIHIKI", + "ACTOR_BG_GATE_SHUTTER", + "ACTOR_EFF_DUST", + "ACTOR_BG_SPOT01_FUSYA", + "ACTOR_BG_SPOT01_IDOHASHIRA", + "ACTOR_BG_SPOT01_IDOMIZU", + "ACTOR_BG_PO_SYOKUDAI", + "ACTOR_BG_GANON_OTYUKA", + "ACTOR_BG_SPOT15_RRBOX", + "ACTOR_BG_UMAJUMP", + "ACTOR_UNSET_109", + "ACTOR_ARROW_FIRE", + "ACTOR_ARROW_ICE", + "ACTOR_ARROW_LIGHT", + "ACTOR_UNSET_10D", + "ACTOR_UNSET_10E", + "ACTOR_ITEM_ETCETERA", + "ACTOR_OBJ_KIBAKO", + "ACTOR_OBJ_TSUBO", + "ACTOR_EN_WONDER_ITEM", + "ACTOR_EN_IK", + "ACTOR_DEMO_IK", + "ACTOR_EN_SKJ", + "ACTOR_EN_SKJNEEDLE", + "ACTOR_EN_G_SWITCH", + "ACTOR_DEMO_EXT", + "ACTOR_DEMO_SHD", + "ACTOR_EN_DNS", + "ACTOR_ELF_MSG", + "ACTOR_EN_HONOTRAP", + "ACTOR_EN_TUBO_TRAP", + "ACTOR_OBJ_ICE_POLY", + "ACTOR_BG_SPOT03_TAKI", + "ACTOR_BG_SPOT07_TAKI", + "ACTOR_EN_FZ", + "ACTOR_EN_PO_RELAY", + "ACTOR_BG_RELAY_OBJECTS", + "ACTOR_EN_DIVING_GAME", + "ACTOR_EN_KUSA", + "ACTOR_OBJ_BEAN", + "ACTOR_OBJ_BOMBIWA", + "ACTOR_UNSET_128", + "ACTOR_UNSET_129", + "ACTOR_OBJ_SWITCH", + "ACTOR_OBJ_ELEVATOR", + "ACTOR_OBJ_LIFT", + "ACTOR_OBJ_HSBLOCK", + "ACTOR_EN_OKARINA_TAG", + "ACTOR_EN_YABUSAME_MARK", + "ACTOR_EN_GOROIWA", + "ACTOR_EN_EX_RUPPY", + "ACTOR_EN_TORYO", + "ACTOR_EN_DAIKU", + "ACTOR_UNSET_134", + "ACTOR_EN_NWC", + "ACTOR_EN_BLKOBJ", + "ACTOR_ITEM_INBOX", + "ACTOR_EN_GE1", + "ACTOR_OBJ_BLOCKSTOP", + "ACTOR_EN_SDA", + "ACTOR_EN_CLEAR_TAG", + "ACTOR_EN_NIW_LADY", + "ACTOR_EN_GM", + "ACTOR_EN_MS", + "ACTOR_EN_HS", + "ACTOR_BG_INGATE", + "ACTOR_EN_KANBAN", + "ACTOR_EN_HEISHI3", + "ACTOR_EN_SYATEKI_NIW", + "ACTOR_EN_ATTACK_NIW", + "ACTOR_BG_SPOT01_IDOSOKO", + "ACTOR_EN_SA", + "ACTOR_EN_WONDER_TALK", + "ACTOR_BG_GJYO_BRIDGE", + "ACTOR_EN_DS", + "ACTOR_EN_MK", + "ACTOR_EN_BOM_BOWL_MAN", + "ACTOR_EN_BOM_BOWL_PIT", + "ACTOR_EN_OWL", + "ACTOR_EN_ISHI", + "ACTOR_OBJ_HANA", + "ACTOR_OBJ_LIGHTSWITCH", + "ACTOR_OBJ_MURE2", + "ACTOR_EN_GO", + "ACTOR_EN_FU", + "ACTOR_UNSET_154", + "ACTOR_EN_CHANGER", + "ACTOR_BG_JYA_MEGAMI", + "ACTOR_BG_JYA_LIFT", + "ACTOR_BG_JYA_BIGMIRROR", + "ACTOR_BG_JYA_BOMBCHUIWA", + "ACTOR_BG_JYA_AMISHUTTER", + "ACTOR_BG_JYA_BOMBIWA", + "ACTOR_BG_SPOT18_BASKET", + "ACTOR_UNSET_15D", + "ACTOR_EN_GANON_ORGAN", + "ACTOR_EN_SIOFUKI", + "ACTOR_EN_STREAM", + "ACTOR_UNSET_161", + "ACTOR_EN_MM", + "ACTOR_EN_KO", + "ACTOR_EN_KZ", + "ACTOR_EN_WEATHER_TAG", + "ACTOR_BG_SST_FLOOR", + "ACTOR_EN_ANI", + "ACTOR_EN_EX_ITEM", + "ACTOR_BG_JYA_IRONOBJ", + "ACTOR_EN_JS", + "ACTOR_EN_JSJUTAN", + "ACTOR_EN_CS", + "ACTOR_EN_MD", + "ACTOR_EN_HY", + "ACTOR_EN_GANON_MANT", + "ACTOR_EN_OKARINA_EFFECT", + "ACTOR_EN_MAG", + "ACTOR_DOOR_GERUDO", + "ACTOR_ELF_MSG2", + "ACTOR_DEMO_GT", + "ACTOR_EN_PO_FIELD", + "ACTOR_EFC_ERUPC", + "ACTOR_BG_ZG", + "ACTOR_EN_HEISHI4", + "ACTOR_EN_ZL3", + "ACTOR_BOSS_GANON2", + "ACTOR_EN_KAKASI", + "ACTOR_EN_TAKARA_MAN", + "ACTOR_OBJ_MAKEOSHIHIKI", + "ACTOR_OCEFF_SPOT", + "ACTOR_END_TITLE", + "ACTOR_UNSET_180", + "ACTOR_EN_TORCH", + "ACTOR_DEMO_EC", + "ACTOR_SHOT_SUN", + "ACTOR_EN_DY_EXTRA", + "ACTOR_EN_WONDER_TALK2", + "ACTOR_EN_GE2", + "ACTOR_OBJ_ROOMTIMER", + "ACTOR_EN_SSH", + "ACTOR_EN_STH", + "ACTOR_OCEFF_WIPE", + "ACTOR_OCEFF_STORM", + "ACTOR_EN_WEIYER", + "ACTOR_BG_SPOT05_SOKO", + "ACTOR_BG_JYA_1FLIFT", + "ACTOR_BG_JYA_HAHENIRON", + "ACTOR_BG_SPOT12_GATE", + "ACTOR_BG_SPOT12_SAKU", + "ACTOR_EN_HINTNUTS", + "ACTOR_EN_NUTSBALL", + "ACTOR_BG_SPOT00_BREAK", + "ACTOR_EN_SHOPNUTS", + "ACTOR_EN_IT", + "ACTOR_EN_GELDB", + "ACTOR_OCEFF_WIPE2", + "ACTOR_OCEFF_WIPE3", + "ACTOR_EN_NIW_GIRL", + "ACTOR_EN_DOG", + "ACTOR_EN_SI", + "ACTOR_BG_SPOT01_OBJECTS2", + "ACTOR_OBJ_COMB", + "ACTOR_BG_SPOT11_BAKUDANKABE", + "ACTOR_OBJ_KIBAKO2", + "ACTOR_EN_DNT_DEMO", + "ACTOR_EN_DNT_JIJI", + "ACTOR_EN_DNT_NOMAL", + "ACTOR_EN_GUEST", + "ACTOR_BG_BOM_GUARD", + "ACTOR_EN_HS2", + "ACTOR_DEMO_KEKKAI", + "ACTOR_BG_SPOT08_BAKUDANKABE", + "ACTOR_BG_SPOT17_BAKUDANKABE", + "ACTOR_UNSET_1AA", + "ACTOR_OBJ_MURE3", + "ACTOR_EN_TG", + "ACTOR_EN_MU", + "ACTOR_EN_GO2", + "ACTOR_EN_WF", + "ACTOR_EN_SKB", + "ACTOR_DEMO_GJ", + "ACTOR_DEMO_GEFF", + "ACTOR_BG_GND_FIREMEIRO", + "ACTOR_BG_GND_DARKMEIRO", + "ACTOR_BG_GND_SOULMEIRO", + "ACTOR_BG_GND_NISEKABE", + "ACTOR_BG_GND_ICEBLOCK", + "ACTOR_EN_GB", + "ACTOR_EN_GS", + "ACTOR_BG_MIZU_BWALL", + "ACTOR_BG_MIZU_SHUTTER", + "ACTOR_EN_DAIKU_KAKARIKO", + "ACTOR_BG_BOWL_WALL", + "ACTOR_EN_WALL_TUBO", + "ACTOR_EN_PO_DESERT", + "ACTOR_EN_CROW", + "ACTOR_DOOR_KILLER", + "ACTOR_BG_SPOT11_OASIS", + "ACTOR_BG_SPOT18_FUTA", + "ACTOR_BG_SPOT18_SHUTTER", + "ACTOR_EN_MA3", + "ACTOR_EN_COW", + "ACTOR_BG_ICE_TURARA", + "ACTOR_BG_ICE_SHUTTER", + "ACTOR_EN_KAKASI2", + "ACTOR_EN_KAKASI3", + "ACTOR_OCEFF_WIPE4", + "ACTOR_EN_EG", + "ACTOR_BG_MENKURI_NISEKABE", + "ACTOR_EN_ZO", + "ACTOR_OBJ_MAKEKINSUTA", + "ACTOR_EN_GE3", + "ACTOR_OBJ_TIMEBLOCK", + "ACTOR_OBJ_HAMISHI", + "ACTOR_EN_ZL4", + "ACTOR_EN_MM2", + "ACTOR_BG_JYA_BLOCK", + "ACTOR_OBJ_WARP2BLOCK", +) diff --git a/tools/assets/extract/oot64_data/audio_ids.py b/tools/assets/extract/oot64_data/audio_ids.py new file mode 100644 index 0000000000..8bcf2b60b8 --- /dev/null +++ b/tools/assets/extract/oot64_data/audio_ids.py @@ -0,0 +1,141 @@ +# This file was made manually + +SEQ_IDS = { + 0x00: "NA_BGM_GENERAL_SFX", + 0x01: "NA_BGM_NATURE_AMBIENCE", + 0x02: "NA_BGM_FIELD_LOGIC", + 0x03: "NA_BGM_FIELD_INIT", + 0x04: "NA_BGM_FIELD_DEFAULT_1", + 0x05: "NA_BGM_FIELD_DEFAULT_2", + 0x06: "NA_BGM_FIELD_DEFAULT_3", + 0x07: "NA_BGM_FIELD_DEFAULT_4", + 0x08: "NA_BGM_FIELD_DEFAULT_5", + 0x09: "NA_BGM_FIELD_DEFAULT_6", + 0x0A: "NA_BGM_FIELD_DEFAULT_7", + 0x0B: "NA_BGM_FIELD_DEFAULT_8", + 0x0C: "NA_BGM_FIELD_DEFAULT_9", + 0x0D: "NA_BGM_FIELD_DEFAULT_A", + 0x0E: "NA_BGM_FIELD_DEFAULT_B", + 0x0F: "NA_BGM_FIELD_ENEMY_INIT", + 0x10: "NA_BGM_FIELD_ENEMY_1", + 0x11: "NA_BGM_FIELD_ENEMY_2", + 0x12: "NA_BGM_FIELD_ENEMY_3", + 0x13: "NA_BGM_FIELD_ENEMY_4", + 0x14: "NA_BGM_FIELD_STILL_1", + 0x15: "NA_BGM_FIELD_STILL_2", + 0x16: "NA_BGM_FIELD_STILL_3", + 0x17: "NA_BGM_FIELD_STILL_4", + 0x18: "NA_BGM_DUNGEON", + 0x19: "NA_BGM_KAKARIKO_ADULT", + 0x1A: "NA_BGM_ENEMY", + 0x1B: "NA_BGM_BOSS", + 0x1C: "NA_BGM_INSIDE_DEKU_TREE", + 0x1D: "NA_BGM_MARKET", + 0x1E: "NA_BGM_TITLE", + 0x1F: "NA_BGM_LINK_HOUSE", + 0x20: "NA_BGM_GAME_OVER", + 0x21: "NA_BGM_BOSS_CLEAR", + 0x22: "NA_BGM_ITEM_GET", + 0x23: "NA_BGM_OPENING_GANON", + 0x24: "NA_BGM_HEART_GET", + 0x25: "NA_BGM_OCA_LIGHT", + 0x26: "NA_BGM_JABU_JABU", + 0x27: "NA_BGM_KAKARIKO_KID", + 0x28: "NA_BGM_GREAT_FAIRY", + 0x29: "NA_BGM_ZELDA_THEME", + 0x2A: "NA_BGM_FIRE_TEMPLE", + 0x2B: "NA_BGM_OPEN_TRE_BOX", + 0x2C: "NA_BGM_FOREST_TEMPLE", + 0x2D: "NA_BGM_COURTYARD", + 0x2E: "NA_BGM_GANON_TOWER", + 0x2F: "NA_BGM_LONLON", + 0x30: "NA_BGM_GORON_CITY", + 0x31: "NA_BGM_FIELD_MORNING", + 0x32: "NA_BGM_SPIRITUAL_STONE", + 0x33: "NA_BGM_OCA_BOLERO", + 0x34: "NA_BGM_OCA_MINUET", + 0x35: "NA_BGM_OCA_SERENADE", + 0x36: "NA_BGM_OCA_REQUIEM", + 0x37: "NA_BGM_OCA_NOCTURNE", + 0x38: "NA_BGM_MINI_BOSS", + 0x39: "NA_BGM_SMALL_ITEM_GET", + 0x3A: "NA_BGM_TEMPLE_OF_TIME", + 0x3B: "NA_BGM_EVENT_CLEAR", + 0x3C: "NA_BGM_KOKIRI", + 0x3D: "NA_BGM_OCA_FAIRY_GET", + 0x3E: "NA_BGM_SARIA_THEME", + 0x3F: "NA_BGM_SPIRIT_TEMPLE", + 0x40: "NA_BGM_HORSE", + 0x41: "NA_BGM_HORSE_GOAL", + 0x42: "NA_BGM_INGO", + 0x43: "NA_BGM_MEDALLION_GET", + 0x44: "NA_BGM_OCA_SARIA", + 0x45: "NA_BGM_OCA_EPONA", + 0x46: "NA_BGM_OCA_ZELDA", + 0x47: "NA_BGM_OCA_SUNS", + 0x48: "NA_BGM_OCA_TIME", + 0x49: "NA_BGM_OCA_STORM", + 0x4A: "NA_BGM_NAVI_OPENING", + 0x4B: "NA_BGM_DEKU_TREE_CS", + 0x4C: "NA_BGM_WINDMILL", + 0x4D: "NA_BGM_HYRULE_CS", + 0x4E: "NA_BGM_MINI_GAME", + 0x4F: "NA_BGM_SHEIK", + 0x50: "NA_BGM_ZORA_DOMAIN", + 0x51: "NA_BGM_APPEAR", + 0x52: "NA_BGM_ADULT_LINK", + 0x53: "NA_BGM_MASTER_SWORD", + 0x54: "NA_BGM_INTRO_GANON", + 0x55: "NA_BGM_SHOP", + 0x56: "NA_BGM_CHAMBER_OF_SAGES", + 0x57: "NA_BGM_FILE_SELECT", + 0x58: "NA_BGM_ICE_CAVERN", + 0x59: "NA_BGM_DOOR_OF_TIME", + 0x5A: "NA_BGM_OWL", + 0x5B: "NA_BGM_SHADOW_TEMPLE", + 0x5C: "NA_BGM_WATER_TEMPLE", + 0x5D: "NA_BGM_BRIDGE_TO_GANONS", + 0x5E: "NA_BGM_OCARINA_OF_TIME", + 0x5F: "NA_BGM_GERUDO_VALLEY", + 0x60: "NA_BGM_POTION_SHOP", + 0x61: "NA_BGM_KOTAKE_KOUME", + 0x62: "NA_BGM_ESCAPE", + 0x63: "NA_BGM_UNDERGROUND", + 0x64: "NA_BGM_GANONDORF_BOSS", + 0x65: "NA_BGM_GANON_BOSS", + 0x66: "NA_BGM_END_DEMO", + 0x67: "NA_BGM_STAFF_1", + 0x68: "NA_BGM_STAFF_2", + 0x69: "NA_BGM_STAFF_3", + 0x6A: "NA_BGM_STAFF_4", + 0x6B: "NA_BGM_FIRE_BOSS", + 0x6C: "NA_BGM_TIMED_MINI_GAME", + 0x6D: "NA_BGM_CUTSCENE_EFFECTS", + 0x7F: "NA_BGM_NO_MUSIC", + 0x80: "NA_BGM_NATURE_SFX_RAIN", + 0xFFFF: "NA_BGM_DISABLED", +} + +NATURE_AMBIENCE_IDS = { + 0x00: "NATURE_ID_GENERAL_NIGHT", + 0x01: "NATURE_ID_MARKET_ENTRANCE", + 0x02: "NATURE_ID_KAKARIKO_REGION", + 0x03: "NATURE_ID_MARKET_RUINS", + 0x04: "NATURE_ID_KOKIRI_REGION", + 0x05: "NATURE_ID_MARKET_NIGHT", + 0x06: "NATURE_ID_06", + 0x07: "NATURE_ID_GANONS_LAIR", + 0x08: "NATURE_ID_08", + 0x09: "NATURE_ID_09", + 0x0A: "NATURE_ID_WASTELAND", + 0x0B: "NATURE_ID_COLOSSUS", + 0x0C: "NATURE_ID_DEATH_MOUNTAIN_TRAIL", + 0x0D: "NATURE_ID_0D", + 0x0E: "NATURE_ID_0E", + 0x0F: "NATURE_ID_0F", + 0x10: "NATURE_ID_10", + 0x11: "NATURE_ID_11", + 0x12: "NATURE_ID_12", + 0x13: "NATURE_ID_NONE", + 0xFF: "NATURE_ID_DISABLED", +} diff --git a/tools/assets/extract/oot64_data/entrance_ids_special.py b/tools/assets/extract/oot64_data/entrance_ids_special.py new file mode 100644 index 0000000000..48a798f253 --- /dev/null +++ b/tools/assets/extract/oot64_data/entrance_ids_special.py @@ -0,0 +1,11 @@ +# This file was made manually + +DATA = { + 0x7FF9: "ENTR_RETURN_GREAT_FAIRYS_FOUNTAIN_SPELLS", + 0x7FFA: "ENTR_RETURN_SHOOTING_GALLERY", + 0x7FFB: "ENTR_RETURN_2", + 0x7FFC: "ENTR_RETURN_BAZAAR", + 0x7FFD: "ENTR_RETURN_4", + 0x7FFE: "ENTR_RETURN_GREAT_FAIRYS_FOUNTAIN_MAGIC", + 0x7FFF: "ENTR_RETURN_GROTTO", +} diff --git a/tools/assets/extract/oot64_data/entrance_table_mini.py b/tools/assets/extract/oot64_data/entrance_table_mini.py new file mode 100644 index 0000000000..9b23c6135c --- /dev/null +++ b/tools/assets/extract/oot64_data/entrance_table_mini.py @@ -0,0 +1,1560 @@ +# This file was generated from ../../../..//include/tables/entrance_table.h + +DATA = ( + ("ENTR_DEKU_TREE_0", "SCENE_DEKU_TREE", 0), + ("ENTR_DEKU_TREE_0_1", "SCENE_DEKU_TREE", 0), + ("ENTR_DEKU_TREE_0_2", "SCENE_DEKU_TREE", 0), + ("ENTR_DEKU_TREE_0_3", "SCENE_DEKU_TREE", 0), + ("ENTR_DODONGOS_CAVERN_0", "SCENE_DODONGOS_CAVERN", 0), + ("ENTR_DODONGOS_CAVERN_0_1", "SCENE_DODONGOS_CAVERN", 0), + ("ENTR_DODONGOS_CAVERN_0_2", "SCENE_DODONGOS_CAVERN", 0), + ("ENTR_DODONGOS_CAVERN_0_3", "SCENE_DODONGOS_CAVERN", 0), + ("ENTR_GERUDO_TRAINING_GROUND_0", "SCENE_GERUDO_TRAINING_GROUND", 0), + ("ENTR_GERUDO_TRAINING_GROUND_0_1", "SCENE_GERUDO_TRAINING_GROUND", 0), + ("ENTR_GERUDO_TRAINING_GROUND_0_2", "SCENE_GERUDO_TRAINING_GROUND", 0), + ("ENTR_GERUDO_TRAINING_GROUND_0_3", "SCENE_GERUDO_TRAINING_GROUND", 0), + ("ENTR_FOREST_TEMPLE_BOSS_0", "SCENE_FOREST_TEMPLE_BOSS", 0), + ("ENTR_FOREST_TEMPLE_BOSS_0_1", "SCENE_FOREST_TEMPLE_BOSS", 0), + ("ENTR_FOREST_TEMPLE_BOSS_0_2", "SCENE_FOREST_TEMPLE_BOSS", 0), + ("ENTR_FOREST_TEMPLE_BOSS_0_3", "SCENE_FOREST_TEMPLE_BOSS", 0), + ("ENTR_WATER_TEMPLE_0", "SCENE_WATER_TEMPLE", 0), + ("ENTR_WATER_TEMPLE_0_1", "SCENE_WATER_TEMPLE", 0), + ("ENTR_WATER_TEMPLE_0_2", "SCENE_WATER_TEMPLE", 0), + ("ENTR_WATER_TEMPLE_0_3", "SCENE_WATER_TEMPLE", 0), + ("ENTR_UNUSED_6E", "SCENE_UNUSED_6E", 0), + ("ENTR_UNUSED_6E_1", "SCENE_UNUSED_6E", 0), + ("ENTR_UNUSED_6E_2", "SCENE_UNUSED_6E", 0), + ("ENTR_UNUSED_6E_3", "SCENE_UNUSED_6E", 0), + ("ENTR_SASATEST_0", "SCENE_SASATEST", 0), + ("ENTR_SASATEST_0_1", "SCENE_SASATEST", 0), + ("ENTR_SASATEST_0_2", "SCENE_SASATEST", 0), + ("ENTR_SASATEST_0_3", "SCENE_SASATEST", 0), + ("ENTR_SYOTES_0", "SCENE_SYOTES", 0), + ("ENTR_SYOTES_0_1", "SCENE_SYOTES", 0), + ("ENTR_SYOTES_0_2", "SCENE_SYOTES", 0), + ("ENTR_SYOTES_0_3", "SCENE_SYOTES", 0), + ("ENTR_SYOTES2_0", "SCENE_SYOTES2", 0), + ("ENTR_SYOTES2_0_1", "SCENE_SYOTES2", 0), + ("ENTR_SYOTES2_0_2", "SCENE_SYOTES2", 0), + ("ENTR_SYOTES2_0_3", "SCENE_SYOTES2", 0), + ("ENTR_TESTROOM_0", "SCENE_TESTROOM", 0), + ("ENTR_TESTROOM_0_1", "SCENE_TESTROOM", 0), + ("ENTR_TESTROOM_0_2", "SCENE_TESTROOM", 0), + ("ENTR_TESTROOM_0_3", "SCENE_TESTROOM", 0), + ("ENTR_JABU_JABU_0", "SCENE_JABU_JABU", 0), + ("ENTR_JABU_JABU_0_1", "SCENE_JABU_JABU", 0), + ("ENTR_JABU_JABU_0_2", "SCENE_JABU_JABU", 0), + ("ENTR_JABU_JABU_0_3", "SCENE_JABU_JABU", 0), + ("ENTR_JABU_JABU_0_4", "SCENE_JABU_JABU", 0), + ("ENTR_ROYAL_FAMILYS_TOMB_0", "SCENE_ROYAL_FAMILYS_TOMB", 0), + ("ENTR_ROYAL_FAMILYS_TOMB_0_1", "SCENE_ROYAL_FAMILYS_TOMB", 0), + ("ENTR_ROYAL_FAMILYS_TOMB_0_2", "SCENE_ROYAL_FAMILYS_TOMB", 0), + ("ENTR_ROYAL_FAMILYS_TOMB_0_3", "SCENE_ROYAL_FAMILYS_TOMB", 0), + ("ENTR_ROYAL_FAMILYS_TOMB_0_4", "SCENE_ROYAL_FAMILYS_TOMB", 0), + ("ENTR_ROYAL_FAMILYS_TOMB_0_5", "SCENE_ROYAL_FAMILYS_TOMB", 0), + ("ENTR_MARKET_ENTRANCE_DAY_0", "SCENE_MARKET_ENTRANCE_DAY", 0), + ("ENTR_MARKET_ENTRANCE_NIGHT_0_1", "SCENE_MARKET_ENTRANCE_NIGHT", 0), + ("ENTR_MARKET_ENTRANCE_RUINS_0_2", "SCENE_MARKET_ENTRANCE_RUINS", 0), + ("ENTR_MARKET_ENTRANCE_RUINS_0_3", "SCENE_MARKET_ENTRANCE_RUINS", 0), + ("ENTR_SHADOW_TEMPLE_0", "SCENE_SHADOW_TEMPLE", 0), + ("ENTR_SHADOW_TEMPLE_0_1", "SCENE_SHADOW_TEMPLE", 0), + ("ENTR_SHADOW_TEMPLE_0_2", "SCENE_SHADOW_TEMPLE", 0), + ("ENTR_SHADOW_TEMPLE_0_3", "SCENE_SHADOW_TEMPLE", 0), + ("ENTR_SHOOTING_GALLERY_0", "SCENE_SHOOTING_GALLERY", 0), + ("ENTR_SHOOTING_GALLERY_0_1", "SCENE_SHOOTING_GALLERY", 0), + ("ENTR_SHOOTING_GALLERY_0_2", "SCENE_SHOOTING_GALLERY", 0), + ("ENTR_SHOOTING_GALLERY_0_3", "SCENE_SHOOTING_GALLERY", 0), + ("ENTR_GROTTOS_0", "SCENE_GROTTOS", 0), + ("ENTR_GROTTOS_0_1", "SCENE_GROTTOS", 0), + ("ENTR_GROTTOS_0_2", "SCENE_GROTTOS", 0), + ("ENTR_GROTTOS_0_3", "SCENE_GROTTOS", 0), + ("ENTR_LAKESIDE_LABORATORY_0", "SCENE_LAKESIDE_LABORATORY", 0), + ("ENTR_LAKESIDE_LABORATORY_0_1", "SCENE_LAKESIDE_LABORATORY", 0), + ("ENTR_LAKESIDE_LABORATORY_0_2", "SCENE_LAKESIDE_LABORATORY", 0), + ("ENTR_LAKESIDE_LABORATORY_0_3", "SCENE_LAKESIDE_LABORATORY", 0), + ("ENTR_SUTARU_0", "SCENE_SUTARU", 0), + ("ENTR_SUTARU_0_1", "SCENE_SUTARU", 0), + ("ENTR_SUTARU_0_2", "SCENE_SUTARU", 0), + ("ENTR_SUTARU_0_3", "SCENE_SUTARU", 0), + ("ENTR_GRAVE_WITH_FAIRYS_FOUNTAIN_0", "SCENE_GRAVE_WITH_FAIRYS_FOUNTAIN", 0), + ("ENTR_GRAVE_WITH_FAIRYS_FOUNTAIN_0_1", "SCENE_GRAVE_WITH_FAIRYS_FOUNTAIN", 0), + ("ENTR_GRAVE_WITH_FAIRYS_FOUNTAIN_0_2", "SCENE_GRAVE_WITH_FAIRYS_FOUNTAIN", 0), + ("ENTR_GRAVE_WITH_FAIRYS_FOUNTAIN_0_3", "SCENE_GRAVE_WITH_FAIRYS_FOUNTAIN", 0), + ("ENTR_LON_LON_BUILDINGS_0", "SCENE_LON_LON_BUILDINGS", 0), + ("ENTR_LON_LON_BUILDINGS_0_1", "SCENE_LON_LON_BUILDINGS", 0), + ("ENTR_LON_LON_BUILDINGS_0_2", "SCENE_LON_LON_BUILDINGS", 0), + ("ENTR_LON_LON_BUILDINGS_0_3", "SCENE_LON_LON_BUILDINGS", 0), + ("ENTR_TEMPLE_OF_TIME_0", "SCENE_TEMPLE_OF_TIME", 0), + ("ENTR_TEMPLE_OF_TIME_0_1", "SCENE_TEMPLE_OF_TIME", 0), + ("ENTR_TEMPLE_OF_TIME_0_2", "SCENE_TEMPLE_OF_TIME", 0), + ("ENTR_TEMPLE_OF_TIME_0_3", "SCENE_TEMPLE_OF_TIME", 0), + ("ENTR_TEMPLE_OF_TIME_0_4", "SCENE_TEMPLE_OF_TIME", 0), + ("ENTR_TEMPLE_OF_TIME_0_5", "SCENE_TEMPLE_OF_TIME", 0), + ("ENTR_TEMPLE_OF_TIME_0_6", "SCENE_TEMPLE_OF_TIME", 0), + ("ENTR_TEMPLE_OF_TIME_0_7", "SCENE_TEMPLE_OF_TIME", 0), + ("ENTR_TEMPLE_OF_TIME_0_8", "SCENE_TEMPLE_OF_TIME", 0), + ("ENTR_TEMPLE_OF_TIME_0_9", "SCENE_TEMPLE_OF_TIME", 0), + ("ENTR_TEMPLE_OF_TIME_0_10", "SCENE_TEMPLE_OF_TIME", 0), + ("ENTR_TEMPLE_OF_TIME_0_11", "SCENE_TEMPLE_OF_TIME", 0), + ("ENTR_TEMPLE_OF_TIME_0_12", "SCENE_TEMPLE_OF_TIME", 0), + ("ENTR_TEMPLE_OF_TIME_0_13", "SCENE_TEMPLE_OF_TIME", 0), + ("ENTR_TEMPLE_OF_TIME_0_14", "SCENE_TEMPLE_OF_TIME", 0), + ("ENTR_TEMPLE_OF_TIME_0_15", "SCENE_TEMPLE_OF_TIME", 0), + ("ENTR_TREASURE_BOX_SHOP_0", "SCENE_TREASURE_BOX_SHOP", 0), + ("ENTR_TREASURE_BOX_SHOP_0_1", "SCENE_TREASURE_BOX_SHOP", 0), + ("ENTR_TREASURE_BOX_SHOP_0_2", "SCENE_TREASURE_BOX_SHOP", 0), + ("ENTR_TREASURE_BOX_SHOP_0_3", "SCENE_TREASURE_BOX_SHOP", 0), + ("ENTR_BACK_ALLEY_DAY_3", "SCENE_BACK_ALLEY_DAY", 3), + ("ENTR_BACK_ALLEY_NIGHT_3_1", "SCENE_BACK_ALLEY_NIGHT", 3), + ("ENTR_BACK_ALLEY_DAY_3_2", "SCENE_BACK_ALLEY_DAY", 3), + ("ENTR_BACK_ALLEY_NIGHT_3_3", "SCENE_BACK_ALLEY_NIGHT", 3), + ("ENTR_CHAMBER_OF_THE_SAGES_0", "SCENE_CHAMBER_OF_THE_SAGES", 0), + ("ENTR_CHAMBER_OF_THE_SAGES_0_1", "SCENE_CHAMBER_OF_THE_SAGES", 0), + ("ENTR_CHAMBER_OF_THE_SAGES_0_2", "SCENE_CHAMBER_OF_THE_SAGES", 0), + ("ENTR_CHAMBER_OF_THE_SAGES_0_3", "SCENE_CHAMBER_OF_THE_SAGES", 0), + ("ENTR_CHAMBER_OF_THE_SAGES_0_4", "SCENE_CHAMBER_OF_THE_SAGES", 0), + ("ENTR_CHAMBER_OF_THE_SAGES_0_5", "SCENE_CHAMBER_OF_THE_SAGES", 0), + ("ENTR_CHAMBER_OF_THE_SAGES_0_6", "SCENE_CHAMBER_OF_THE_SAGES", 0), + ("ENTR_POTION_SHOP_GRANNY_0", "SCENE_POTION_SHOP_GRANNY", 0), + ("ENTR_POTION_SHOP_GRANNY_0_1", "SCENE_POTION_SHOP_GRANNY", 0), + ("ENTR_POTION_SHOP_GRANNY_0_2", "SCENE_POTION_SHOP_GRANNY", 0), + ("ENTR_POTION_SHOP_GRANNY_0_3", "SCENE_POTION_SHOP_GRANNY", 0), + ("ENTR_HAIRAL_NIWA2_0", "SCENE_HAIRAL_NIWA2", 0), + ("ENTR_HAIRAL_NIWA2_0_1", "SCENE_HAIRAL_NIWA2", 0), + ("ENTR_HAIRAL_NIWA2_0_2", "SCENE_HAIRAL_NIWA2", 0), + ("ENTR_HAIRAL_NIWA2_0_3", "SCENE_HAIRAL_NIWA2", 0), + ("ENTR_CASTLE_COURTYARD_GUARDS_DAY_0", "SCENE_CASTLE_COURTYARD_GUARDS_DAY", 0), + ("ENTR_CASTLE_COURTYARD_GUARDS_NIGHT_0_1", "SCENE_CASTLE_COURTYARD_GUARDS_NIGHT", 0), + ("ENTR_CASTLE_COURTYARD_GUARDS_DAY_0_2", "SCENE_CASTLE_COURTYARD_GUARDS_DAY", 0), + ("ENTR_CASTLE_COURTYARD_GUARDS_NIGHT_0_3", "SCENE_CASTLE_COURTYARD_GUARDS_NIGHT", 0), + ("ENTR_MARKET_GUARD_HOUSE_0", "SCENE_MARKET_GUARD_HOUSE", 0), + ("ENTR_MARKET_GUARD_HOUSE_0_1", "SCENE_MARKET_GUARD_HOUSE", 0), + ("ENTR_MARKET_GUARD_HOUSE_0_2", "SCENE_MARKET_GUARD_HOUSE", 0), + ("ENTR_MARKET_GUARD_HOUSE_0_3", "SCENE_MARKET_GUARD_HOUSE", 0), + ("ENTR_SPIRIT_TEMPLE_0", "SCENE_SPIRIT_TEMPLE", 0), + ("ENTR_SPIRIT_TEMPLE_0_1", "SCENE_SPIRIT_TEMPLE", 0), + ("ENTR_SPIRIT_TEMPLE_0_2", "SCENE_SPIRIT_TEMPLE", 0), + ("ENTR_SPIRIT_TEMPLE_0_3", "SCENE_SPIRIT_TEMPLE", 0), + ("ENTR_SPIRIT_TEMPLE_0_4", "SCENE_SPIRIT_TEMPLE", 0), + ("ENTR_SPIRIT_TEMPLE_0_5", "SCENE_SPIRIT_TEMPLE", 0), + ("ENTR_ICE_CAVERN_0", "SCENE_ICE_CAVERN", 0), + ("ENTR_ICE_CAVERN_0_1", "SCENE_ICE_CAVERN", 0), + ("ENTR_ICE_CAVERN_0_2", "SCENE_ICE_CAVERN", 0), + ("ENTR_ICE_CAVERN_0_3", "SCENE_ICE_CAVERN", 0), + ("ENTR_ICE_CAVERN_0_4", "SCENE_ICE_CAVERN", 0), + ("ENTR_SPIRIT_TEMPLE_BOSS_0", "SCENE_SPIRIT_TEMPLE_BOSS", 0), + ("ENTR_SPIRIT_TEMPLE_BOSS_0_1", "SCENE_SPIRIT_TEMPLE_BOSS", 0), + ("ENTR_SPIRIT_TEMPLE_BOSS_0_2", "SCENE_SPIRIT_TEMPLE_BOSS", 0), + ("ENTR_SPIRIT_TEMPLE_BOSS_0_3", "SCENE_SPIRIT_TEMPLE_BOSS", 0), + ("ENTR_SPIRIT_TEMPLE_BOSS_0_4", "SCENE_SPIRIT_TEMPLE_BOSS", 0), + ("ENTR_SPIRIT_TEMPLE_BOSS_0_5", "SCENE_SPIRIT_TEMPLE_BOSS", 0), + ("ENTR_SPIRIT_TEMPLE_BOSS_0_6", "SCENE_SPIRIT_TEMPLE_BOSS", 0), + ("ENTR_TEST01_0", "SCENE_TEST01", 0), + ("ENTR_TEST01_0_1", "SCENE_TEST01", 0), + ("ENTR_TEST01_0_2", "SCENE_TEST01", 0), + ("ENTR_TEST01_0_3", "SCENE_TEST01", 0), + ("ENTR_BOTTOM_OF_THE_WELL_0", "SCENE_BOTTOM_OF_THE_WELL", 0), + ("ENTR_BOTTOM_OF_THE_WELL_0_1", "SCENE_BOTTOM_OF_THE_WELL", 0), + ("ENTR_BOTTOM_OF_THE_WELL_0_2", "SCENE_BOTTOM_OF_THE_WELL", 0), + ("ENTR_BOTTOM_OF_THE_WELL_0_3", "SCENE_BOTTOM_OF_THE_WELL", 0), + ("ENTR_TWINS_HOUSE_0", "SCENE_TWINS_HOUSE", 0), + ("ENTR_TWINS_HOUSE_0_1", "SCENE_TWINS_HOUSE", 0), + ("ENTR_TWINS_HOUSE_0_2", "SCENE_TWINS_HOUSE", 0), + ("ENTR_TWINS_HOUSE_0_3", "SCENE_TWINS_HOUSE", 0), + ("ENTR_CUTSCENE_MAP_0", "SCENE_CUTSCENE_MAP", 0), + ("ENTR_CUTSCENE_MAP_0_1", "SCENE_CUTSCENE_MAP", 0), + ("ENTR_CUTSCENE_MAP_0_2", "SCENE_CUTSCENE_MAP", 0), + ("ENTR_CUTSCENE_MAP_0_3", "SCENE_CUTSCENE_MAP", 0), + ("ENTR_CUTSCENE_MAP_0_4", "SCENE_CUTSCENE_MAP", 0), + ("ENTR_CUTSCENE_MAP_0_5", "SCENE_CUTSCENE_MAP", 0), + ("ENTR_CUTSCENE_MAP_0_6", "SCENE_CUTSCENE_MAP", 0), + ("ENTR_CUTSCENE_MAP_0_7", "SCENE_CUTSCENE_MAP", 0), + ("ENTR_CUTSCENE_MAP_0_8", "SCENE_CUTSCENE_MAP", 0), + ("ENTR_CUTSCENE_MAP_0_9", "SCENE_CUTSCENE_MAP", 0), + ("ENTR_CUTSCENE_MAP_0_10", "SCENE_CUTSCENE_MAP", 0), + ("ENTR_CUTSCENE_MAP_0_11", "SCENE_CUTSCENE_MAP", 0), + ("ENTR_CUTSCENE_MAP_0_12", "SCENE_CUTSCENE_MAP", 0), + ("ENTR_BACK_ALLEY_DAY_0", "SCENE_BACK_ALLEY_DAY", 0), + ("ENTR_BACK_ALLEY_NIGHT_0_1", "SCENE_BACK_ALLEY_NIGHT", 0), + ("ENTR_BACK_ALLEY_DAY_0_2", "SCENE_BACK_ALLEY_DAY", 0), + ("ENTR_BACK_ALLEY_NIGHT_0_3", "SCENE_BACK_ALLEY_NIGHT", 0), + ("ENTR_MARKET_DAY_0", "SCENE_MARKET_DAY", 0), + ("ENTR_MARKET_NIGHT_0_1", "SCENE_MARKET_NIGHT", 0), + ("ENTR_MARKET_RUINS_0_2", "SCENE_MARKET_RUINS", 0), + ("ENTR_MARKET_RUINS_0_3", "SCENE_MARKET_RUINS", 0), + ("ENTR_MARKET_DAY_0_4", "SCENE_MARKET_DAY", 0), + ("ENTR_DEPTH_TEST_0", "SCENE_DEPTH_TEST", 0), + ("ENTR_BAZAAR_0", "SCENE_BAZAAR", 0), + ("ENTR_BAZAAR_0_1", "SCENE_BAZAAR", 0), + ("ENTR_BAZAAR_0_2", "SCENE_BAZAAR", 0), + ("ENTR_BAZAAR_0_3", "SCENE_BAZAAR", 0), + ("ENTR_LINKS_HOUSE_0", "SCENE_LINKS_HOUSE", 0), + ("ENTR_LINKS_HOUSE_0_1", "SCENE_LINKS_HOUSE", 0), + ("ENTR_LINKS_HOUSE_0_2", "SCENE_LINKS_HOUSE", 0), + ("ENTR_LINKS_HOUSE_0_3", "SCENE_LINKS_HOUSE", 0), + ("ENTR_LINKS_HOUSE_0_4", "SCENE_LINKS_HOUSE", 0), + ("ENTR_LINKS_HOUSE_0_5", "SCENE_LINKS_HOUSE", 0), + ("ENTR_KOKIRI_SHOP_0", "SCENE_KOKIRI_SHOP", 0), + ("ENTR_KOKIRI_SHOP_0_1", "SCENE_KOKIRI_SHOP", 0), + ("ENTR_KOKIRI_SHOP_0_2", "SCENE_KOKIRI_SHOP", 0), + ("ENTR_KOKIRI_SHOP_0_3", "SCENE_KOKIRI_SHOP", 0), + ("ENTR_DODONGOS_CAVERN_1", "SCENE_DODONGOS_CAVERN", 1), + ("ENTR_DODONGOS_CAVERN_1_1", "SCENE_DODONGOS_CAVERN", 1), + ("ENTR_DODONGOS_CAVERN_1_2", "SCENE_DODONGOS_CAVERN", 1), + ("ENTR_DODONGOS_CAVERN_1_3", "SCENE_DODONGOS_CAVERN", 1), + ("ENTR_KNOW_IT_ALL_BROS_HOUSE_0", "SCENE_KNOW_IT_ALL_BROS_HOUSE", 0), + ("ENTR_KNOW_IT_ALL_BROS_HOUSE_0_1", "SCENE_KNOW_IT_ALL_BROS_HOUSE", 0), + ("ENTR_KNOW_IT_ALL_BROS_HOUSE_0_2", "SCENE_KNOW_IT_ALL_BROS_HOUSE", 0), + ("ENTR_KNOW_IT_ALL_BROS_HOUSE_0_3", "SCENE_KNOW_IT_ALL_BROS_HOUSE", 0), + ("ENTR_HYRULE_FIELD_0", "SCENE_HYRULE_FIELD", 0), + ("ENTR_HYRULE_FIELD_0_1", "SCENE_HYRULE_FIELD", 0), + ("ENTR_HYRULE_FIELD_0_2", "SCENE_HYRULE_FIELD", 0), + ("ENTR_HYRULE_FIELD_0_3", "SCENE_HYRULE_FIELD", 0), + ("ENTR_HYRULE_FIELD_0_4", "SCENE_HYRULE_FIELD", 0), + ("ENTR_HYRULE_FIELD_0_5", "SCENE_HYRULE_FIELD", 0), + ("ENTR_HYRULE_FIELD_0_6", "SCENE_HYRULE_FIELD", 0), + ("ENTR_HYRULE_FIELD_0_7", "SCENE_HYRULE_FIELD", 0), + ("ENTR_HYRULE_FIELD_0_8", "SCENE_HYRULE_FIELD", 0), + ("ENTR_HYRULE_FIELD_0_9", "SCENE_HYRULE_FIELD", 0), + ("ENTR_HYRULE_FIELD_0_10", "SCENE_HYRULE_FIELD", 0), + ("ENTR_HYRULE_FIELD_0_11", "SCENE_HYRULE_FIELD", 0), + ("ENTR_HYRULE_FIELD_0_12", "SCENE_HYRULE_FIELD", 0), + ("ENTR_HYRULE_FIELD_0_13", "SCENE_HYRULE_FIELD", 0), + ("ENTR_KAKARIKO_VILLAGE_0", "SCENE_KAKARIKO_VILLAGE", 0), + ("ENTR_KAKARIKO_VILLAGE_0_1", "SCENE_KAKARIKO_VILLAGE", 0), + ("ENTR_KAKARIKO_VILLAGE_0_2", "SCENE_KAKARIKO_VILLAGE", 0), + ("ENTR_KAKARIKO_VILLAGE_0_3", "SCENE_KAKARIKO_VILLAGE", 0), + ("ENTR_KAKARIKO_VILLAGE_0_4", "SCENE_KAKARIKO_VILLAGE", 0), + ("ENTR_KAKARIKO_VILLAGE_0_5", "SCENE_KAKARIKO_VILLAGE", 0), + ("ENTR_KAKARIKO_VILLAGE_0_6", "SCENE_KAKARIKO_VILLAGE", 0), + ("ENTR_KAKARIKO_VILLAGE_0_7", "SCENE_KAKARIKO_VILLAGE", 0), + ("ENTR_KAKARIKO_VILLAGE_0_8", "SCENE_KAKARIKO_VILLAGE", 0), + ("ENTR_GRAVEYARD_0", "SCENE_GRAVEYARD", 0), + ("ENTR_GRAVEYARD_0_1", "SCENE_GRAVEYARD", 0), + ("ENTR_GRAVEYARD_0_2", "SCENE_GRAVEYARD", 0), + ("ENTR_GRAVEYARD_0_3", "SCENE_GRAVEYARD", 0), + ("ENTR_GRAVEYARD_0_4", "SCENE_GRAVEYARD", 0), + ("ENTR_GRAVEYARD_0_5", "SCENE_GRAVEYARD", 0), + ("ENTR_ZORAS_RIVER_0", "SCENE_ZORAS_RIVER", 0), + ("ENTR_ZORAS_RIVER_0_1", "SCENE_ZORAS_RIVER", 0), + ("ENTR_ZORAS_RIVER_0_2", "SCENE_ZORAS_RIVER", 0), + ("ENTR_ZORAS_RIVER_0_3", "SCENE_ZORAS_RIVER", 0), + ("ENTR_KOKIRI_FOREST_0", "SCENE_KOKIRI_FOREST", 0), + ("ENTR_KOKIRI_FOREST_0_1", "SCENE_KOKIRI_FOREST", 0), + ("ENTR_KOKIRI_FOREST_0_2", "SCENE_KOKIRI_FOREST", 0), + ("ENTR_KOKIRI_FOREST_0_3", "SCENE_KOKIRI_FOREST", 0), + ("ENTR_KOKIRI_FOREST_0_4", "SCENE_KOKIRI_FOREST", 0), + ("ENTR_KOKIRI_FOREST_0_5", "SCENE_KOKIRI_FOREST", 0), + ("ENTR_KOKIRI_FOREST_0_6", "SCENE_KOKIRI_FOREST", 0), + ("ENTR_KOKIRI_FOREST_0_7", "SCENE_KOKIRI_FOREST", 0), + ("ENTR_KOKIRI_FOREST_0_8", "SCENE_KOKIRI_FOREST", 0), + ("ENTR_KOKIRI_FOREST_0_9", "SCENE_KOKIRI_FOREST", 0), + ("ENTR_KOKIRI_FOREST_0_10", "SCENE_KOKIRI_FOREST", 0), + ("ENTR_KOKIRI_FOREST_0_11", "SCENE_KOKIRI_FOREST", 0), + ("ENTR_KOKIRI_FOREST_0_12", "SCENE_KOKIRI_FOREST", 0), + ("ENTR_KOKIRI_FOREST_0_13", "SCENE_KOKIRI_FOREST", 0), + ("ENTR_SACRED_FOREST_MEADOW_0", "SCENE_SACRED_FOREST_MEADOW", 0), + ("ENTR_SACRED_FOREST_MEADOW_0_1", "SCENE_SACRED_FOREST_MEADOW", 0), + ("ENTR_SACRED_FOREST_MEADOW_0_2", "SCENE_SACRED_FOREST_MEADOW", 0), + ("ENTR_SACRED_FOREST_MEADOW_0_3", "SCENE_SACRED_FOREST_MEADOW", 0), + ("ENTR_SACRED_FOREST_MEADOW_0_4", "SCENE_SACRED_FOREST_MEADOW", 0), + ("ENTR_SACRED_FOREST_MEADOW_0_5", "SCENE_SACRED_FOREST_MEADOW", 0), + ("ENTR_LAKE_HYLIA_0", "SCENE_LAKE_HYLIA", 0), + ("ENTR_LAKE_HYLIA_0_1", "SCENE_LAKE_HYLIA", 0), + ("ENTR_LAKE_HYLIA_0_2", "SCENE_LAKE_HYLIA", 0), + ("ENTR_LAKE_HYLIA_0_3", "SCENE_LAKE_HYLIA", 0), + ("ENTR_LAKE_HYLIA_0_4", "SCENE_LAKE_HYLIA", 0), + ("ENTR_LAKE_HYLIA_0_5", "SCENE_LAKE_HYLIA", 0), + ("ENTR_ZORAS_DOMAIN_0", "SCENE_ZORAS_DOMAIN", 0), + ("ENTR_ZORAS_DOMAIN_0_1", "SCENE_ZORAS_DOMAIN", 0), + ("ENTR_ZORAS_DOMAIN_0_2", "SCENE_ZORAS_DOMAIN", 0), + ("ENTR_ZORAS_DOMAIN_0_3", "SCENE_ZORAS_DOMAIN", 0), + ("ENTR_ZORAS_DOMAIN_0_4", "SCENE_ZORAS_DOMAIN", 0), + ("ENTR_ZORAS_DOMAIN_0_5", "SCENE_ZORAS_DOMAIN", 0), + ("ENTR_ZORAS_FOUNTAIN_0", "SCENE_ZORAS_FOUNTAIN", 0), + ("ENTR_ZORAS_FOUNTAIN_0_1", "SCENE_ZORAS_FOUNTAIN", 0), + ("ENTR_ZORAS_FOUNTAIN_0_2", "SCENE_ZORAS_FOUNTAIN", 0), + ("ENTR_ZORAS_FOUNTAIN_0_3", "SCENE_ZORAS_FOUNTAIN", 0), + ("ENTR_ZORAS_FOUNTAIN_0_4", "SCENE_ZORAS_FOUNTAIN", 0), + ("ENTR_ZORAS_FOUNTAIN_0_5", "SCENE_ZORAS_FOUNTAIN", 0), + ("ENTR_ZORAS_FOUNTAIN_0_6", "SCENE_ZORAS_FOUNTAIN", 0), + ("ENTR_ZORAS_FOUNTAIN_0_7", "SCENE_ZORAS_FOUNTAIN", 0), + ("ENTR_ZORAS_FOUNTAIN_0_8", "SCENE_ZORAS_FOUNTAIN", 0), + ("ENTR_GERUDO_VALLEY_0", "SCENE_GERUDO_VALLEY", 0), + ("ENTR_GERUDO_VALLEY_0_1", "SCENE_GERUDO_VALLEY", 0), + ("ENTR_GERUDO_VALLEY_0_2", "SCENE_GERUDO_VALLEY", 0), + ("ENTR_GERUDO_VALLEY_0_3", "SCENE_GERUDO_VALLEY", 0), + ("ENTR_GERUDO_VALLEY_0_4", "SCENE_GERUDO_VALLEY", 0), + ("ENTR_GERUDO_VALLEY_0_5", "SCENE_GERUDO_VALLEY", 0), + ("ENTR_GERUDO_VALLEY_0_6", "SCENE_GERUDO_VALLEY", 0), + ("ENTR_LOST_WOODS_0", "SCENE_LOST_WOODS", 0), + ("ENTR_LOST_WOODS_0_1", "SCENE_LOST_WOODS", 0), + ("ENTR_LOST_WOODS_0_2", "SCENE_LOST_WOODS", 0), + ("ENTR_LOST_WOODS_0_3", "SCENE_LOST_WOODS", 0), + ("ENTR_LOST_WOODS_0_4", "SCENE_LOST_WOODS", 0), + ("ENTR_DESERT_COLOSSUS_0", "SCENE_DESERT_COLOSSUS", 0), + ("ENTR_DESERT_COLOSSUS_0_1", "SCENE_DESERT_COLOSSUS", 0), + ("ENTR_DESERT_COLOSSUS_0_2", "SCENE_DESERT_COLOSSUS", 0), + ("ENTR_DESERT_COLOSSUS_0_3", "SCENE_DESERT_COLOSSUS", 0), + ("ENTR_DESERT_COLOSSUS_0_4", "SCENE_DESERT_COLOSSUS", 0), + ("ENTR_DESERT_COLOSSUS_0_5", "SCENE_DESERT_COLOSSUS", 0), + ("ENTR_GERUDOS_FORTRESS_0", "SCENE_GERUDOS_FORTRESS", 0), + ("ENTR_GERUDOS_FORTRESS_0_1", "SCENE_GERUDOS_FORTRESS", 0), + ("ENTR_GERUDOS_FORTRESS_0_2", "SCENE_GERUDOS_FORTRESS", 0), + ("ENTR_GERUDOS_FORTRESS_0_3", "SCENE_GERUDOS_FORTRESS", 0), + ("ENTR_GERUDOS_FORTRESS_0_4", "SCENE_GERUDOS_FORTRESS", 0), + ("ENTR_GERUDOS_FORTRESS_0_5", "SCENE_GERUDOS_FORTRESS", 0), + ("ENTR_GERUDOS_FORTRESS_0_6", "SCENE_GERUDOS_FORTRESS", 0), + ("ENTR_HAUNTED_WASTELAND_0", "SCENE_HAUNTED_WASTELAND", 0), + ("ENTR_HAUNTED_WASTELAND_0_1", "SCENE_HAUNTED_WASTELAND", 0), + ("ENTR_HAUNTED_WASTELAND_0_2", "SCENE_HAUNTED_WASTELAND", 0), + ("ENTR_HAUNTED_WASTELAND_0_3", "SCENE_HAUNTED_WASTELAND", 0), + ("ENTR_GANONS_TOWER_COLLAPSE_INTERIOR_1", "SCENE_GANONS_TOWER_COLLAPSE_INTERIOR", 1), + ("ENTR_GANONS_TOWER_COLLAPSE_INTERIOR_1_1", "SCENE_GANONS_TOWER_COLLAPSE_INTERIOR", 1), + ("ENTR_GANONS_TOWER_COLLAPSE_INTERIOR_1_2", "SCENE_GANONS_TOWER_COLLAPSE_INTERIOR", 1), + ("ENTR_GANONS_TOWER_COLLAPSE_INTERIOR_1_3", "SCENE_GANONS_TOWER_COLLAPSE_INTERIOR", 1), + ("ENTR_HYRULE_CASTLE_0", "SCENE_HYRULE_CASTLE", 0), + ("ENTR_HYRULE_CASTLE_0_1", "SCENE_HYRULE_CASTLE", 0), + ("ENTR_OUTSIDE_GANONS_CASTLE_0_2", "SCENE_OUTSIDE_GANONS_CASTLE", 0), + ("ENTR_OUTSIDE_GANONS_CASTLE_0_3", "SCENE_OUTSIDE_GANONS_CASTLE", 0), + ("ENTR_OUTSIDE_GANONS_CASTLE_0_4", "SCENE_OUTSIDE_GANONS_CASTLE", 0), + ("ENTR_DEATH_MOUNTAIN_TRAIL_0", "SCENE_DEATH_MOUNTAIN_TRAIL", 0), + ("ENTR_DEATH_MOUNTAIN_TRAIL_0_1", "SCENE_DEATH_MOUNTAIN_TRAIL", 0), + ("ENTR_DEATH_MOUNTAIN_TRAIL_0_2", "SCENE_DEATH_MOUNTAIN_TRAIL", 0), + ("ENTR_DEATH_MOUNTAIN_TRAIL_0_3", "SCENE_DEATH_MOUNTAIN_TRAIL", 0), + ("ENTR_DEATH_MOUNTAIN_TRAIL_0_4", "SCENE_DEATH_MOUNTAIN_TRAIL", 0), + ("ENTR_DEATH_MOUNTAIN_TRAIL_0_5", "SCENE_DEATH_MOUNTAIN_TRAIL", 0), + ("ENTR_DEATH_MOUNTAIN_TRAIL_0_6", "SCENE_DEATH_MOUNTAIN_TRAIL", 0), + ("ENTR_DEATH_MOUNTAIN_TRAIL_0_7", "SCENE_DEATH_MOUNTAIN_TRAIL", 0), + ("ENTR_DEATH_MOUNTAIN_TRAIL_0_8", "SCENE_DEATH_MOUNTAIN_TRAIL", 0), + ("ENTR_DEATH_MOUNTAIN_TRAIL_0_9", "SCENE_DEATH_MOUNTAIN_TRAIL", 0), + ("ENTR_DEATH_MOUNTAIN_CRATER_0", "SCENE_DEATH_MOUNTAIN_CRATER", 0), + ("ENTR_DEATH_MOUNTAIN_CRATER_0_1", "SCENE_DEATH_MOUNTAIN_CRATER", 0), + ("ENTR_DEATH_MOUNTAIN_CRATER_0_2", "SCENE_DEATH_MOUNTAIN_CRATER", 0), + ("ENTR_DEATH_MOUNTAIN_CRATER_0_3", "SCENE_DEATH_MOUNTAIN_CRATER", 0), + ("ENTR_DEATH_MOUNTAIN_CRATER_0_4", "SCENE_DEATH_MOUNTAIN_CRATER", 0), + ("ENTR_DEATH_MOUNTAIN_CRATER_0_5", "SCENE_DEATH_MOUNTAIN_CRATER", 0), + ("ENTR_GORON_CITY_0", "SCENE_GORON_CITY", 0), + ("ENTR_GORON_CITY_0_1", "SCENE_GORON_CITY", 0), + ("ENTR_GORON_CITY_0_2", "SCENE_GORON_CITY", 0), + ("ENTR_GORON_CITY_0_3", "SCENE_GORON_CITY", 0), + ("ENTR_GORON_CITY_0_4", "SCENE_GORON_CITY", 0), + ("ENTR_GORON_CITY_0_5", "SCENE_GORON_CITY", 0), + ("ENTR_ZORAS_DOMAIN_3", "SCENE_ZORAS_DOMAIN", 3), + ("ENTR_ZORAS_DOMAIN_3_1", "SCENE_ZORAS_DOMAIN", 3), + ("ENTR_ZORAS_DOMAIN_3_2", "SCENE_ZORAS_DOMAIN", 3), + ("ENTR_ZORAS_DOMAIN_3_3", "SCENE_ZORAS_DOMAIN", 3), + ("ENTR_LON_LON_RANCH_0", "SCENE_LON_LON_RANCH", 0), + ("ENTR_LON_LON_RANCH_0_1", "SCENE_LON_LON_RANCH", 0), + ("ENTR_LON_LON_RANCH_0_2", "SCENE_LON_LON_RANCH", 0), + ("ENTR_LON_LON_RANCH_0_3", "SCENE_LON_LON_RANCH", 0), + ("ENTR_LON_LON_RANCH_0_4", "SCENE_LON_LON_RANCH", 0), + ("ENTR_LON_LON_RANCH_0_5", "SCENE_LON_LON_RANCH", 0), + ("ENTR_LON_LON_RANCH_0_6", "SCENE_LON_LON_RANCH", 0), + ("ENTR_LON_LON_RANCH_0_7", "SCENE_LON_LON_RANCH", 0), + ("ENTR_LON_LON_RANCH_0_8", "SCENE_LON_LON_RANCH", 0), + ("ENTR_LON_LON_RANCH_0_9", "SCENE_LON_LON_RANCH", 0), + ("ENTR_LON_LON_RANCH_0_10", "SCENE_LON_LON_RANCH", 0), + ("ENTR_LON_LON_RANCH_0_11", "SCENE_LON_LON_RANCH", 0), + ("ENTR_LON_LON_RANCH_0_12", "SCENE_LON_LON_RANCH", 0), + ("ENTR_LON_LON_RANCH_0_13", "SCENE_LON_LON_RANCH", 0), + ("ENTR_FIRE_TEMPLE_0", "SCENE_FIRE_TEMPLE", 0), + ("ENTR_FIRE_TEMPLE_0_1", "SCENE_FIRE_TEMPLE", 0), + ("ENTR_FIRE_TEMPLE_0_2", "SCENE_FIRE_TEMPLE", 0), + ("ENTR_FIRE_TEMPLE_0_3", "SCENE_FIRE_TEMPLE", 0), + ("ENTR_FOREST_TEMPLE_0", "SCENE_FOREST_TEMPLE", 0), + ("ENTR_FOREST_TEMPLE_0_1", "SCENE_FOREST_TEMPLE", 0), + ("ENTR_FOREST_TEMPLE_0_2", "SCENE_FOREST_TEMPLE", 0), + ("ENTR_FOREST_TEMPLE_0_3", "SCENE_FOREST_TEMPLE", 0), + ("ENTR_SHOOTING_GALLERY_1", "SCENE_SHOOTING_GALLERY", 1), + ("ENTR_SHOOTING_GALLERY_1_1", "SCENE_SHOOTING_GALLERY", 1), + ("ENTR_SHOOTING_GALLERY_1_2", "SCENE_SHOOTING_GALLERY", 1), + ("ENTR_SHOOTING_GALLERY_1_3", "SCENE_SHOOTING_GALLERY", 1), + ("ENTR_TEMPLE_OF_TIME_EXTERIOR_DAY_0", "SCENE_TEMPLE_OF_TIME_EXTERIOR_DAY", 0), + ("ENTR_TEMPLE_OF_TIME_EXTERIOR_NIGHT_0_1", "SCENE_TEMPLE_OF_TIME_EXTERIOR_NIGHT", 0), + ("ENTR_TEMPLE_OF_TIME_EXTERIOR_RUINS_0_2", "SCENE_TEMPLE_OF_TIME_EXTERIOR_RUINS", 0), + ("ENTR_TEMPLE_OF_TIME_EXTERIOR_RUINS_0_3", "SCENE_TEMPLE_OF_TIME_EXTERIOR_RUINS", 0), + ("ENTR_FIRE_TEMPLE_1", "SCENE_FIRE_TEMPLE", 1), + ("ENTR_FIRE_TEMPLE_1_1", "SCENE_FIRE_TEMPLE", 1), + ("ENTR_FIRE_TEMPLE_1_2", "SCENE_FIRE_TEMPLE", 1), + ("ENTR_FIRE_TEMPLE_1_3", "SCENE_FIRE_TEMPLE", 1), + ("ENTR_GANONS_TOWER_COLLAPSE_INTERIOR_0", "SCENE_GANONS_TOWER_COLLAPSE_INTERIOR", 0), + ("ENTR_GANONS_TOWER_COLLAPSE_INTERIOR_0_1", "SCENE_GANONS_TOWER_COLLAPSE_INTERIOR", 0), + ("ENTR_GANONS_TOWER_COLLAPSE_INTERIOR_0_2", "SCENE_GANONS_TOWER_COLLAPSE_INTERIOR", 0), + ("ENTR_GANONS_TOWER_COLLAPSE_INTERIOR_0_3", "SCENE_GANONS_TOWER_COLLAPSE_INTERIOR", 0), + ("ENTR_HYRULE_FIELD_1", "SCENE_HYRULE_FIELD", 1), + ("ENTR_HYRULE_FIELD_1_1", "SCENE_HYRULE_FIELD", 1), + ("ENTR_HYRULE_FIELD_1_2", "SCENE_HYRULE_FIELD", 1), + ("ENTR_HYRULE_FIELD_1_3", "SCENE_HYRULE_FIELD", 1), + ("ENTR_HYRULE_FIELD_2", "SCENE_HYRULE_FIELD", 2), + ("ENTR_HYRULE_FIELD_2_1", "SCENE_HYRULE_FIELD", 2), + ("ENTR_HYRULE_FIELD_2_2", "SCENE_HYRULE_FIELD", 2), + ("ENTR_HYRULE_FIELD_2_3", "SCENE_HYRULE_FIELD", 2), + ("ENTR_HYRULE_FIELD_3", "SCENE_HYRULE_FIELD", 3), + ("ENTR_HYRULE_FIELD_3_1", "SCENE_HYRULE_FIELD", 3), + ("ENTR_HYRULE_FIELD_3_2", "SCENE_HYRULE_FIELD", 3), + ("ENTR_HYRULE_FIELD_3_3", "SCENE_HYRULE_FIELD", 3), + ("ENTR_HYRULE_FIELD_4", "SCENE_HYRULE_FIELD", 4), + ("ENTR_HYRULE_FIELD_4_1", "SCENE_HYRULE_FIELD", 4), + ("ENTR_HYRULE_FIELD_4_2", "SCENE_HYRULE_FIELD", 4), + ("ENTR_HYRULE_FIELD_4_3", "SCENE_HYRULE_FIELD", 4), + ("ENTR_HYRULE_FIELD_5", "SCENE_HYRULE_FIELD", 5), + ("ENTR_HYRULE_FIELD_5_1", "SCENE_HYRULE_FIELD", 5), + ("ENTR_HYRULE_FIELD_5_2", "SCENE_HYRULE_FIELD", 5), + ("ENTR_HYRULE_FIELD_5_3", "SCENE_HYRULE_FIELD", 5), + ("ENTR_KAKARIKO_VILLAGE_1", "SCENE_KAKARIKO_VILLAGE", 1), + ("ENTR_KAKARIKO_VILLAGE_1_1", "SCENE_KAKARIKO_VILLAGE", 1), + ("ENTR_KAKARIKO_VILLAGE_1_2", "SCENE_KAKARIKO_VILLAGE", 1), + ("ENTR_KAKARIKO_VILLAGE_1_3", "SCENE_KAKARIKO_VILLAGE", 1), + ("ENTR_KAKARIKO_VILLAGE_2", "SCENE_KAKARIKO_VILLAGE", 2), + ("ENTR_KAKARIKO_VILLAGE_2_1", "SCENE_KAKARIKO_VILLAGE", 2), + ("ENTR_KAKARIKO_VILLAGE_2_2", "SCENE_KAKARIKO_VILLAGE", 2), + ("ENTR_KAKARIKO_VILLAGE_2_3", "SCENE_KAKARIKO_VILLAGE", 2), + ("ENTR_ZORAS_RIVER_1", "SCENE_ZORAS_RIVER", 1), + ("ENTR_ZORAS_RIVER_1_1", "SCENE_ZORAS_RIVER", 1), + ("ENTR_ZORAS_RIVER_1_2", "SCENE_ZORAS_RIVER", 1), + ("ENTR_ZORAS_RIVER_1_3", "SCENE_ZORAS_RIVER", 1), + ("ENTR_ZORAS_RIVER_2", "SCENE_ZORAS_RIVER", 2), + ("ENTR_ZORAS_RIVER_2_1", "SCENE_ZORAS_RIVER", 2), + ("ENTR_ZORAS_RIVER_2_2", "SCENE_ZORAS_RIVER", 2), + ("ENTR_ZORAS_RIVER_2_3", "SCENE_ZORAS_RIVER", 2), + ("ENTR_ZORAS_DOMAIN_1", "SCENE_ZORAS_DOMAIN", 1), + ("ENTR_ZORAS_DOMAIN_1_1", "SCENE_ZORAS_DOMAIN", 1), + ("ENTR_ZORAS_DOMAIN_1_2", "SCENE_ZORAS_DOMAIN", 1), + ("ENTR_ZORAS_DOMAIN_1_3", "SCENE_ZORAS_DOMAIN", 1), + ("ENTR_GERUDO_VALLEY_1", "SCENE_GERUDO_VALLEY", 1), + ("ENTR_GERUDO_VALLEY_1_1", "SCENE_GERUDO_VALLEY", 1), + ("ENTR_GERUDO_VALLEY_1_2", "SCENE_GERUDO_VALLEY", 1), + ("ENTR_GERUDO_VALLEY_1_3", "SCENE_GERUDO_VALLEY", 1), + ("ENTR_LOST_WOODS_1", "SCENE_LOST_WOODS", 1), + ("ENTR_LOST_WOODS_1_1", "SCENE_LOST_WOODS", 1), + ("ENTR_LOST_WOODS_1_2", "SCENE_LOST_WOODS", 1), + ("ENTR_LOST_WOODS_1_3", "SCENE_LOST_WOODS", 1), + ("ENTR_LOST_WOODS_2", "SCENE_LOST_WOODS", 2), + ("ENTR_LOST_WOODS_2_1", "SCENE_LOST_WOODS", 2), + ("ENTR_LOST_WOODS_2_2", "SCENE_LOST_WOODS", 2), + ("ENTR_LOST_WOODS_2_3", "SCENE_LOST_WOODS", 2), + ("ENTR_LOST_WOODS_3", "SCENE_LOST_WOODS", 3), + ("ENTR_LOST_WOODS_3_1", "SCENE_LOST_WOODS", 3), + ("ENTR_LOST_WOODS_3_2", "SCENE_LOST_WOODS", 3), + ("ENTR_LOST_WOODS_3_3", "SCENE_LOST_WOODS", 3), + ("ENTR_GANONS_TOWER_COLLAPSE_INTERIOR_2", "SCENE_GANONS_TOWER_COLLAPSE_INTERIOR", 2), + ("ENTR_GANONS_TOWER_COLLAPSE_INTERIOR_2_1", "SCENE_GANONS_TOWER_COLLAPSE_INTERIOR", 2), + ("ENTR_GANONS_TOWER_COLLAPSE_INTERIOR_2_2", "SCENE_GANONS_TOWER_COLLAPSE_INTERIOR", 2), + ("ENTR_GANONS_TOWER_COLLAPSE_INTERIOR_2_3", "SCENE_GANONS_TOWER_COLLAPSE_INTERIOR", 2), + ("ENTR_DEATH_MOUNTAIN_TRAIL_1", "SCENE_DEATH_MOUNTAIN_TRAIL", 1), + ("ENTR_DEATH_MOUNTAIN_TRAIL_1_1", "SCENE_DEATH_MOUNTAIN_TRAIL", 1), + ("ENTR_DEATH_MOUNTAIN_TRAIL_1_2", "SCENE_DEATH_MOUNTAIN_TRAIL", 1), + ("ENTR_DEATH_MOUNTAIN_TRAIL_1_3", "SCENE_DEATH_MOUNTAIN_TRAIL", 1), + ("ENTR_DEATH_MOUNTAIN_TRAIL_2", "SCENE_DEATH_MOUNTAIN_TRAIL", 2), + ("ENTR_DEATH_MOUNTAIN_TRAIL_2_1", "SCENE_DEATH_MOUNTAIN_TRAIL", 2), + ("ENTR_DEATH_MOUNTAIN_TRAIL_2_2", "SCENE_DEATH_MOUNTAIN_TRAIL", 2), + ("ENTR_DEATH_MOUNTAIN_TRAIL_2_3", "SCENE_DEATH_MOUNTAIN_TRAIL", 2), + ("ENTR_GORON_CITY_1", "SCENE_GORON_CITY", 1), + ("ENTR_GORON_CITY_1_1", "SCENE_GORON_CITY", 1), + ("ENTR_GORON_CITY_1_2", "SCENE_GORON_CITY", 1), + ("ENTR_GORON_CITY_1_3", "SCENE_GORON_CITY", 1), + ("ENTR_LAKESIDE_LABORATORY_1", "SCENE_LAKESIDE_LABORATORY", 1), + ("ENTR_LAKESIDE_LABORATORY_1_1", "SCENE_LAKESIDE_LABORATORY", 1), + ("ENTR_LAKESIDE_LABORATORY_1_2", "SCENE_LAKESIDE_LABORATORY", 1), + ("ENTR_LAKESIDE_LABORATORY_1_3", "SCENE_LAKESIDE_LABORATORY", 1), + ("ENTR_GANONS_TOWER_COLLAPSE_EXTERIOR_5", "SCENE_GANONS_TOWER_COLLAPSE_EXTERIOR", 5), + ("ENTR_GANONS_TOWER_COLLAPSE_EXTERIOR_5_1", "SCENE_GANONS_TOWER_COLLAPSE_EXTERIOR", 5), + ("ENTR_GANONS_TOWER_COLLAPSE_EXTERIOR_5_2", "SCENE_GANONS_TOWER_COLLAPSE_EXTERIOR", 5), + ("ENTR_GANONS_TOWER_COLLAPSE_EXTERIOR_5_3", "SCENE_GANONS_TOWER_COLLAPSE_EXTERIOR", 5), + ("ENTR_MARKET_DAY_8", "SCENE_MARKET_DAY", 8), + ("ENTR_MARKET_NIGHT_8_1", "SCENE_MARKET_NIGHT", 8), + ("ENTR_MARKET_RUINS_8_2", "SCENE_MARKET_RUINS", 8), + ("ENTR_MARKET_RUINS_8_3", "SCENE_MARKET_RUINS", 8), + ("ENTR_MARKET_DAY_9", "SCENE_MARKET_DAY", 9), + ("ENTR_MARKET_NIGHT_9_1", "SCENE_MARKET_NIGHT", 9), + ("ENTR_MARKET_RUINS_9_2", "SCENE_MARKET_RUINS", 9), + ("ENTR_MARKET_RUINS_9_3", "SCENE_MARKET_RUINS", 9), + ("ENTR_MARKET_DAY_10", "SCENE_MARKET_DAY", 10), + ("ENTR_MARKET_NIGHT_10_1", "SCENE_MARKET_NIGHT", 10), + ("ENTR_MARKET_RUINS_10_2", "SCENE_MARKET_RUINS", 10), + ("ENTR_MARKET_RUINS_10_3", "SCENE_MARKET_RUINS", 10), + ("ENTR_ZORAS_RIVER_3", "SCENE_ZORAS_RIVER", 3), + ("ENTR_ZORAS_RIVER_3_1", "SCENE_ZORAS_RIVER", 3), + ("ENTR_ZORAS_RIVER_3_2", "SCENE_ZORAS_RIVER", 3), + ("ENTR_ZORAS_RIVER_3_3", "SCENE_ZORAS_RIVER", 3), + ("ENTR_ZORAS_RIVER_4", "SCENE_ZORAS_RIVER", 4), + ("ENTR_ZORAS_RIVER_4_1", "SCENE_ZORAS_RIVER", 4), + ("ENTR_ZORAS_RIVER_4_2", "SCENE_ZORAS_RIVER", 4), + ("ENTR_ZORAS_RIVER_4_3", "SCENE_ZORAS_RIVER", 4), + ("ENTR_DESERT_COLOSSUS_1", "SCENE_DESERT_COLOSSUS", 1), + ("ENTR_DESERT_COLOSSUS_1_1", "SCENE_DESERT_COLOSSUS", 1), + ("ENTR_DESERT_COLOSSUS_1_2", "SCENE_DESERT_COLOSSUS", 1), + ("ENTR_DESERT_COLOSSUS_1_3", "SCENE_DESERT_COLOSSUS", 1), + ("ENTR_DESERT_COLOSSUS_2", "SCENE_DESERT_COLOSSUS", 2), + ("ENTR_DESERT_COLOSSUS_2_1", "SCENE_DESERT_COLOSSUS", 2), + ("ENTR_DESERT_COLOSSUS_2_2", "SCENE_DESERT_COLOSSUS", 2), + ("ENTR_DESERT_COLOSSUS_2_3", "SCENE_DESERT_COLOSSUS", 2), + ("ENTR_DESERT_COLOSSUS_3", "SCENE_DESERT_COLOSSUS", 3), + ("ENTR_DESERT_COLOSSUS_3_1", "SCENE_DESERT_COLOSSUS", 3), + ("ENTR_DESERT_COLOSSUS_3_2", "SCENE_DESERT_COLOSSUS", 3), + ("ENTR_DESERT_COLOSSUS_3_3", "SCENE_DESERT_COLOSSUS", 3), + ("ENTR_DESERT_COLOSSUS_4", "SCENE_DESERT_COLOSSUS", 4), + ("ENTR_DESERT_COLOSSUS_4_1", "SCENE_DESERT_COLOSSUS", 4), + ("ENTR_DESERT_COLOSSUS_4_2", "SCENE_DESERT_COLOSSUS", 4), + ("ENTR_DESERT_COLOSSUS_4_3", "SCENE_DESERT_COLOSSUS", 4), + ("ENTR_DESERT_COLOSSUS_5", "SCENE_DESERT_COLOSSUS", 5), + ("ENTR_DESERT_COLOSSUS_5_1", "SCENE_DESERT_COLOSSUS", 5), + ("ENTR_DESERT_COLOSSUS_5_2", "SCENE_DESERT_COLOSSUS", 5), + ("ENTR_DESERT_COLOSSUS_5_3", "SCENE_DESERT_COLOSSUS", 5), + ("ENTR_DESERT_COLOSSUS_6", "SCENE_DESERT_COLOSSUS", 6), + ("ENTR_DESERT_COLOSSUS_6_1", "SCENE_DESERT_COLOSSUS", 6), + ("ENTR_DESERT_COLOSSUS_6_2", "SCENE_DESERT_COLOSSUS", 6), + ("ENTR_DESERT_COLOSSUS_6_3", "SCENE_DESERT_COLOSSUS", 6), + ("ENTR_HYRULE_FIELD_6", "SCENE_HYRULE_FIELD", 6), + ("ENTR_HYRULE_FIELD_6_1", "SCENE_HYRULE_FIELD", 6), + ("ENTR_HYRULE_FIELD_6_2", "SCENE_HYRULE_FIELD", 6), + ("ENTR_HYRULE_FIELD_6_3", "SCENE_HYRULE_FIELD", 6), + ("ENTR_HYRULE_FIELD_7", "SCENE_HYRULE_FIELD", 7), + ("ENTR_HYRULE_FIELD_7_1", "SCENE_HYRULE_FIELD", 7), + ("ENTR_HYRULE_FIELD_7_2", "SCENE_HYRULE_FIELD", 7), + ("ENTR_HYRULE_FIELD_7_3", "SCENE_HYRULE_FIELD", 7), + ("ENTR_KAKARIKO_VILLAGE_3", "SCENE_KAKARIKO_VILLAGE", 3), + ("ENTR_KAKARIKO_VILLAGE_3_1", "SCENE_KAKARIKO_VILLAGE", 3), + ("ENTR_KAKARIKO_VILLAGE_3_2", "SCENE_KAKARIKO_VILLAGE", 3), + ("ENTR_KAKARIKO_VILLAGE_3_3", "SCENE_KAKARIKO_VILLAGE", 3), + ("ENTR_GRAVEYARD_1", "SCENE_GRAVEYARD", 1), + ("ENTR_GRAVEYARD_1_1", "SCENE_GRAVEYARD", 1), + ("ENTR_GRAVEYARD_1_2", "SCENE_GRAVEYARD", 1), + ("ENTR_GRAVEYARD_1_3", "SCENE_GRAVEYARD", 1), + ("ENTR_KOKIRI_FOREST_1", "SCENE_KOKIRI_FOREST", 1), + ("ENTR_KOKIRI_FOREST_1_1", "SCENE_KOKIRI_FOREST", 1), + ("ENTR_KOKIRI_FOREST_1_2", "SCENE_KOKIRI_FOREST", 1), + ("ENTR_KOKIRI_FOREST_1_3", "SCENE_KOKIRI_FOREST", 1), + ("ENTR_KOKIRI_FOREST_2", "SCENE_KOKIRI_FOREST", 2), + ("ENTR_KOKIRI_FOREST_2_1", "SCENE_KOKIRI_FOREST", 2), + ("ENTR_KOKIRI_FOREST_2_2", "SCENE_KOKIRI_FOREST", 2), + ("ENTR_KOKIRI_FOREST_2_3", "SCENE_KOKIRI_FOREST", 2), + ("ENTR_KOKIRI_FOREST_3", "SCENE_KOKIRI_FOREST", 3), + ("ENTR_KOKIRI_FOREST_3_1", "SCENE_KOKIRI_FOREST", 3), + ("ENTR_KOKIRI_FOREST_3_2", "SCENE_KOKIRI_FOREST", 3), + ("ENTR_KOKIRI_FOREST_3_3", "SCENE_KOKIRI_FOREST", 3), + ("ENTR_SACRED_FOREST_MEADOW_1", "SCENE_SACRED_FOREST_MEADOW", 1), + ("ENTR_SACRED_FOREST_MEADOW_1_1", "SCENE_SACRED_FOREST_MEADOW", 1), + ("ENTR_SACRED_FOREST_MEADOW_1_2", "SCENE_SACRED_FOREST_MEADOW", 1), + ("ENTR_SACRED_FOREST_MEADOW_1_3", "SCENE_SACRED_FOREST_MEADOW", 1), + ("ENTR_LAKE_HYLIA_1", "SCENE_LAKE_HYLIA", 1), + ("ENTR_LAKE_HYLIA_1_1", "SCENE_LAKE_HYLIA", 1), + ("ENTR_LAKE_HYLIA_1_2", "SCENE_LAKE_HYLIA", 1), + ("ENTR_LAKE_HYLIA_1_3", "SCENE_LAKE_HYLIA", 1), + ("ENTR_LAKE_HYLIA_2", "SCENE_LAKE_HYLIA", 2), + ("ENTR_LAKE_HYLIA_2_1", "SCENE_LAKE_HYLIA", 2), + ("ENTR_LAKE_HYLIA_2_2", "SCENE_LAKE_HYLIA", 2), + ("ENTR_LAKE_HYLIA_2_3", "SCENE_LAKE_HYLIA", 2), + ("ENTR_ZORAS_FOUNTAIN_1", "SCENE_ZORAS_FOUNTAIN", 1), + ("ENTR_ZORAS_FOUNTAIN_1_1", "SCENE_ZORAS_FOUNTAIN", 1), + ("ENTR_ZORAS_FOUNTAIN_1_2", "SCENE_ZORAS_FOUNTAIN", 1), + ("ENTR_ZORAS_FOUNTAIN_1_3", "SCENE_ZORAS_FOUNTAIN", 1), + ("ENTR_ZORAS_FOUNTAIN_2", "SCENE_ZORAS_FOUNTAIN", 2), + ("ENTR_ZORAS_FOUNTAIN_2_1", "SCENE_ZORAS_FOUNTAIN", 2), + ("ENTR_ZORAS_FOUNTAIN_2_2", "SCENE_ZORAS_FOUNTAIN", 2), + ("ENTR_ZORAS_FOUNTAIN_2_3", "SCENE_ZORAS_FOUNTAIN", 2), + ("ENTR_GERUDO_VALLEY_2", "SCENE_GERUDO_VALLEY", 2), + ("ENTR_GERUDO_VALLEY_2_1", "SCENE_GERUDO_VALLEY", 2), + ("ENTR_GERUDO_VALLEY_2_2", "SCENE_GERUDO_VALLEY", 2), + ("ENTR_GERUDO_VALLEY_2_3", "SCENE_GERUDO_VALLEY", 2), + ("ENTR_GERUDO_VALLEY_3", "SCENE_GERUDO_VALLEY", 3), + ("ENTR_GERUDO_VALLEY_3_1", "SCENE_GERUDO_VALLEY", 3), + ("ENTR_GERUDO_VALLEY_3_2", "SCENE_GERUDO_VALLEY", 3), + ("ENTR_GERUDO_VALLEY_3_3", "SCENE_GERUDO_VALLEY", 3), + ("ENTR_GERUDOS_FORTRESS_1", "SCENE_GERUDOS_FORTRESS", 1), + ("ENTR_GERUDOS_FORTRESS_1_1", "SCENE_GERUDOS_FORTRESS", 1), + ("ENTR_GERUDOS_FORTRESS_1_2", "SCENE_GERUDOS_FORTRESS", 1), + ("ENTR_GERUDOS_FORTRESS_1_3", "SCENE_GERUDOS_FORTRESS", 1), + ("ENTR_GERUDOS_FORTRESS_2", "SCENE_GERUDOS_FORTRESS", 2), + ("ENTR_GERUDOS_FORTRESS_2_1", "SCENE_GERUDOS_FORTRESS", 2), + ("ENTR_GERUDOS_FORTRESS_2_2", "SCENE_GERUDOS_FORTRESS", 2), + ("ENTR_GERUDOS_FORTRESS_2_3", "SCENE_GERUDOS_FORTRESS", 2), + ("ENTR_GERUDOS_FORTRESS_3", "SCENE_GERUDOS_FORTRESS", 3), + ("ENTR_GERUDOS_FORTRESS_3_1", "SCENE_GERUDOS_FORTRESS", 3), + ("ENTR_GERUDOS_FORTRESS_3_2", "SCENE_GERUDOS_FORTRESS", 3), + ("ENTR_GERUDOS_FORTRESS_3_3", "SCENE_GERUDOS_FORTRESS", 3), + ("ENTR_HYRULE_CASTLE_1", "SCENE_HYRULE_CASTLE", 1), + ("ENTR_HYRULE_CASTLE_1_1", "SCENE_HYRULE_CASTLE", 1), + ("ENTR_OUTSIDE_GANONS_CASTLE_1_2", "SCENE_OUTSIDE_GANONS_CASTLE", 1), + ("ENTR_OUTSIDE_GANONS_CASTLE_1_3", "SCENE_OUTSIDE_GANONS_CASTLE", 1), + ("ENTR_HYRULE_CASTLE_1_4", "SCENE_HYRULE_CASTLE", 1), + ("ENTR_DEATH_MOUNTAIN_TRAIL_3", "SCENE_DEATH_MOUNTAIN_TRAIL", 3), + ("ENTR_DEATH_MOUNTAIN_TRAIL_3_1", "SCENE_DEATH_MOUNTAIN_TRAIL", 3), + ("ENTR_DEATH_MOUNTAIN_TRAIL_3_2", "SCENE_DEATH_MOUNTAIN_TRAIL", 3), + ("ENTR_DEATH_MOUNTAIN_TRAIL_3_3", "SCENE_DEATH_MOUNTAIN_TRAIL", 3), + ("ENTR_DEATH_MOUNTAIN_CRATER_1", "SCENE_DEATH_MOUNTAIN_CRATER", 1), + ("ENTR_DEATH_MOUNTAIN_CRATER_1_1", "SCENE_DEATH_MOUNTAIN_CRATER", 1), + ("ENTR_DEATH_MOUNTAIN_CRATER_1_2", "SCENE_DEATH_MOUNTAIN_CRATER", 1), + ("ENTR_DEATH_MOUNTAIN_CRATER_1_3", "SCENE_DEATH_MOUNTAIN_CRATER", 1), + ("ENTR_DEATH_MOUNTAIN_CRATER_2", "SCENE_DEATH_MOUNTAIN_CRATER", 2), + ("ENTR_DEATH_MOUNTAIN_CRATER_2_1", "SCENE_DEATH_MOUNTAIN_CRATER", 2), + ("ENTR_DEATH_MOUNTAIN_CRATER_2_2", "SCENE_DEATH_MOUNTAIN_CRATER", 2), + ("ENTR_DEATH_MOUNTAIN_CRATER_2_3", "SCENE_DEATH_MOUNTAIN_CRATER", 2), + ("ENTR_FOREST_TEMPLE_1", "SCENE_FOREST_TEMPLE", 1), + ("ENTR_FOREST_TEMPLE_1_1", "SCENE_FOREST_TEMPLE", 1), + ("ENTR_FOREST_TEMPLE_1_2", "SCENE_FOREST_TEMPLE", 1), + ("ENTR_FOREST_TEMPLE_1_3", "SCENE_FOREST_TEMPLE", 1), + ("ENTR_DEKU_TREE_1", "SCENE_DEKU_TREE", 1), + ("ENTR_DEKU_TREE_1_1", "SCENE_DEKU_TREE", 1), + ("ENTR_DEKU_TREE_1_2", "SCENE_DEKU_TREE", 1), + ("ENTR_DEKU_TREE_1_3", "SCENE_DEKU_TREE", 1), + ("ENTR_GANONS_TOWER_COLLAPSE_INTERIOR_3", "SCENE_GANONS_TOWER_COLLAPSE_INTERIOR", 3), + ("ENTR_GANONS_TOWER_COLLAPSE_INTERIOR_3_1", "SCENE_GANONS_TOWER_COLLAPSE_INTERIOR", 3), + ("ENTR_GANONS_TOWER_COLLAPSE_INTERIOR_3_2", "SCENE_GANONS_TOWER_COLLAPSE_INTERIOR", 3), + ("ENTR_GANONS_TOWER_COLLAPSE_INTERIOR_3_3", "SCENE_GANONS_TOWER_COLLAPSE_INTERIOR", 3), + ("ENTR_MARKET_DAY_1", "SCENE_MARKET_DAY", 1), + ("ENTR_MARKET_NIGHT_1_1", "SCENE_MARKET_NIGHT", 1), + ("ENTR_MARKET_RUINS_1_2", "SCENE_MARKET_RUINS", 1), + ("ENTR_MARKET_RUINS_1_3", "SCENE_MARKET_RUINS", 1), + ("ENTR_MARKET_DAY_2", "SCENE_MARKET_DAY", 2), + ("ENTR_MARKET_NIGHT_2_1", "SCENE_MARKET_NIGHT", 2), + ("ENTR_MARKET_RUINS_2_2", "SCENE_MARKET_RUINS", 2), + ("ENTR_MARKET_RUINS_2_3", "SCENE_MARKET_RUINS", 2), + ("ENTR_MARKET_DAY_3", "SCENE_MARKET_DAY", 3), + ("ENTR_MARKET_NIGHT_3_1", "SCENE_MARKET_NIGHT", 3), + ("ENTR_MARKET_RUINS_3_2", "SCENE_MARKET_RUINS", 3), + ("ENTR_MARKET_RUINS_3_3", "SCENE_MARKET_RUINS", 3), + ("ENTR_KOKIRI_FOREST_4", "SCENE_KOKIRI_FOREST", 4), + ("ENTR_KOKIRI_FOREST_4_1", "SCENE_KOKIRI_FOREST", 4), + ("ENTR_KOKIRI_FOREST_4_2", "SCENE_KOKIRI_FOREST", 4), + ("ENTR_KOKIRI_FOREST_4_3", "SCENE_KOKIRI_FOREST", 4), + ("ENTR_KOKIRI_FOREST_5", "SCENE_KOKIRI_FOREST", 5), + ("ENTR_KOKIRI_FOREST_5_1", "SCENE_KOKIRI_FOREST", 5), + ("ENTR_KOKIRI_FOREST_5_2", "SCENE_KOKIRI_FOREST", 5), + ("ENTR_KOKIRI_FOREST_5_3", "SCENE_KOKIRI_FOREST", 5), + ("ENTR_MARKET_ENTRANCE_DAY_2", "SCENE_MARKET_ENTRANCE_DAY", 2), + ("ENTR_MARKET_ENTRANCE_NIGHT_2_1", "SCENE_MARKET_ENTRANCE_NIGHT", 2), + ("ENTR_MARKET_ENTRANCE_RUINS_2_2", "SCENE_MARKET_ENTRANCE_RUINS", 2), + ("ENTR_MARKET_ENTRANCE_RUINS_2_3", "SCENE_MARKET_ENTRANCE_RUINS", 2), + ("ENTR_LINKS_HOUSE_1", "SCENE_LINKS_HOUSE", 1), + ("ENTR_LINKS_HOUSE_1_1", "SCENE_LINKS_HOUSE", 1), + ("ENTR_LINKS_HOUSE_1_2", "SCENE_LINKS_HOUSE", 1), + ("ENTR_LINKS_HOUSE_1_3", "SCENE_LINKS_HOUSE", 1), + ("ENTR_MARKET_ENTRANCE_DAY_1", "SCENE_MARKET_ENTRANCE_DAY", 1), + ("ENTR_MARKET_ENTRANCE_NIGHT_1_1", "SCENE_MARKET_ENTRANCE_NIGHT", 1), + ("ENTR_MARKET_ENTRANCE_RUINS_1_2", "SCENE_MARKET_ENTRANCE_RUINS", 1), + ("ENTR_MARKET_ENTRANCE_RUINS_1_3", "SCENE_MARKET_ENTRANCE_RUINS", 1), + ("ENTR_HYRULE_FIELD_8", "SCENE_HYRULE_FIELD", 8), + ("ENTR_HYRULE_FIELD_8_1", "SCENE_HYRULE_FIELD", 8), + ("ENTR_HYRULE_FIELD_8_2", "SCENE_HYRULE_FIELD", 8), + ("ENTR_HYRULE_FIELD_8_3", "SCENE_HYRULE_FIELD", 8), + ("ENTR_HYRULE_FIELD_9", "SCENE_HYRULE_FIELD", 9), + ("ENTR_HYRULE_FIELD_9_1", "SCENE_HYRULE_FIELD", 9), + ("ENTR_HYRULE_FIELD_9_2", "SCENE_HYRULE_FIELD", 9), + ("ENTR_HYRULE_FIELD_9_3", "SCENE_HYRULE_FIELD", 9), + ("ENTR_HYRULE_FIELD_10", "SCENE_HYRULE_FIELD", 10), + ("ENTR_HYRULE_FIELD_10_1", "SCENE_HYRULE_FIELD", 10), + ("ENTR_HYRULE_FIELD_10_2", "SCENE_HYRULE_FIELD", 10), + ("ENTR_HYRULE_FIELD_10_3", "SCENE_HYRULE_FIELD", 10), + ("ENTR_KOKIRI_FOREST_6", "SCENE_KOKIRI_FOREST", 6), + ("ENTR_KOKIRI_FOREST_6_1", "SCENE_KOKIRI_FOREST", 6), + ("ENTR_KOKIRI_FOREST_6_2", "SCENE_KOKIRI_FOREST", 6), + ("ENTR_KOKIRI_FOREST_6_3", "SCENE_KOKIRI_FOREST", 6), + ("ENTR_HYRULE_FIELD_11", "SCENE_HYRULE_FIELD", 11), + ("ENTR_HYRULE_FIELD_11_1", "SCENE_HYRULE_FIELD", 11), + ("ENTR_HYRULE_FIELD_11_2", "SCENE_HYRULE_FIELD", 11), + ("ENTR_HYRULE_FIELD_11_3", "SCENE_HYRULE_FIELD", 11), + ("ENTR_HYRULE_FIELD_12", "SCENE_HYRULE_FIELD", 12), + ("ENTR_HYRULE_FIELD_12_1", "SCENE_HYRULE_FIELD", 12), + ("ENTR_HYRULE_FIELD_12_2", "SCENE_HYRULE_FIELD", 12), + ("ENTR_HYRULE_FIELD_12_3", "SCENE_HYRULE_FIELD", 12), + ("ENTR_HYRULE_FIELD_13", "SCENE_HYRULE_FIELD", 13), + ("ENTR_HYRULE_FIELD_13_1", "SCENE_HYRULE_FIELD", 13), + ("ENTR_HYRULE_FIELD_13_2", "SCENE_HYRULE_FIELD", 13), + ("ENTR_HYRULE_FIELD_13_3", "SCENE_HYRULE_FIELD", 13), + ("ENTR_CASTLE_COURTYARD_GUARDS_DAY_1", "SCENE_CASTLE_COURTYARD_GUARDS_DAY", 1), + ("ENTR_CASTLE_COURTYARD_GUARDS_NIGHT_1_1", "SCENE_CASTLE_COURTYARD_GUARDS_NIGHT", 1), + ("ENTR_CASTLE_COURTYARD_GUARDS_DAY_1_2", "SCENE_CASTLE_COURTYARD_GUARDS_DAY", 1), + ("ENTR_CASTLE_COURTYARD_GUARDS_NIGHT_1_3", "SCENE_CASTLE_COURTYARD_GUARDS_NIGHT", 1), + ("ENTR_BACK_ALLEY_DAY_1", "SCENE_BACK_ALLEY_DAY", 1), + ("ENTR_BACK_ALLEY_NIGHT_1_1", "SCENE_BACK_ALLEY_NIGHT", 1), + ("ENTR_BACK_ALLEY_DAY_1_2", "SCENE_BACK_ALLEY_DAY", 1), + ("ENTR_BACK_ALLEY_NIGHT_1_3", "SCENE_BACK_ALLEY_NIGHT", 1), + ("ENTR_MARKET_DAY_4", "SCENE_MARKET_DAY", 4), + ("ENTR_MARKET_NIGHT_4_1", "SCENE_MARKET_NIGHT", 4), + ("ENTR_MARKET_RUINS_4_2", "SCENE_MARKET_RUINS", 4), + ("ENTR_MARKET_RUINS_4_3", "SCENE_MARKET_RUINS", 4), + ("ENTR_MARKET_DAY_5", "SCENE_MARKET_DAY", 5), + ("ENTR_MARKET_NIGHT_5_1", "SCENE_MARKET_NIGHT", 5), + ("ENTR_MARKET_RUINS_5_2", "SCENE_MARKET_RUINS", 5), + ("ENTR_MARKET_RUINS_5_3", "SCENE_MARKET_RUINS", 5), + ("ENTR_KAKARIKO_VILLAGE_4", "SCENE_KAKARIKO_VILLAGE", 4), + ("ENTR_KAKARIKO_VILLAGE_4_1", "SCENE_KAKARIKO_VILLAGE", 4), + ("ENTR_KAKARIKO_VILLAGE_4_2", "SCENE_KAKARIKO_VILLAGE", 4), + ("ENTR_KAKARIKO_VILLAGE_4_3", "SCENE_KAKARIKO_VILLAGE", 4), + ("ENTR_GERUDOS_FORTRESS_4", "SCENE_GERUDOS_FORTRESS", 4), + ("ENTR_GERUDOS_FORTRESS_4_1", "SCENE_GERUDOS_FORTRESS", 4), + ("ENTR_GERUDOS_FORTRESS_4_2", "SCENE_GERUDOS_FORTRESS", 4), + ("ENTR_GERUDOS_FORTRESS_4_3", "SCENE_GERUDOS_FORTRESS", 4), + ("ENTR_LON_LON_RANCH_1", "SCENE_LON_LON_RANCH", 1), + ("ENTR_LON_LON_RANCH_1_1", "SCENE_LON_LON_RANCH", 1), + ("ENTR_LON_LON_RANCH_1_2", "SCENE_LON_LON_RANCH", 1), + ("ENTR_LON_LON_RANCH_1_3", "SCENE_LON_LON_RANCH", 1), + ("ENTR_SHADOW_TEMPLE_1", "SCENE_SHADOW_TEMPLE", 1), + ("ENTR_SHADOW_TEMPLE_1_1", "SCENE_SHADOW_TEMPLE", 1), + ("ENTR_SHADOW_TEMPLE_1_2", "SCENE_SHADOW_TEMPLE", 1), + ("ENTR_SHADOW_TEMPLE_1_3", "SCENE_SHADOW_TEMPLE", 1), + ("ENTR_SHADOW_TEMPLE_2", "SCENE_SHADOW_TEMPLE", 2), + ("ENTR_SHADOW_TEMPLE_2_1", "SCENE_SHADOW_TEMPLE", 2), + ("ENTR_SHADOW_TEMPLE_2_2", "SCENE_SHADOW_TEMPLE", 2), + ("ENTR_SHADOW_TEMPLE_2_3", "SCENE_SHADOW_TEMPLE", 2), + ("ENTR_GERUDOS_FORTRESS_5", "SCENE_GERUDOS_FORTRESS", 5), + ("ENTR_GERUDOS_FORTRESS_5_1", "SCENE_GERUDOS_FORTRESS", 5), + ("ENTR_GERUDOS_FORTRESS_5_2", "SCENE_GERUDOS_FORTRESS", 5), + ("ENTR_GERUDOS_FORTRESS_5_3", "SCENE_GERUDOS_FORTRESS", 5), + ("ENTR_GERUDOS_FORTRESS_6", "SCENE_GERUDOS_FORTRESS", 6), + ("ENTR_GERUDOS_FORTRESS_6_1", "SCENE_GERUDOS_FORTRESS", 6), + ("ENTR_GERUDOS_FORTRESS_6_2", "SCENE_GERUDOS_FORTRESS", 6), + ("ENTR_GERUDOS_FORTRESS_6_3", "SCENE_GERUDOS_FORTRESS", 6), + ("ENTR_GERUDOS_FORTRESS_7", "SCENE_GERUDOS_FORTRESS", 7), + ("ENTR_GERUDOS_FORTRESS_7_1", "SCENE_GERUDOS_FORTRESS", 7), + ("ENTR_GERUDOS_FORTRESS_7_2", "SCENE_GERUDOS_FORTRESS", 7), + ("ENTR_GERUDOS_FORTRESS_7_3", "SCENE_GERUDOS_FORTRESS", 7), + ("ENTR_GERUDOS_FORTRESS_8", "SCENE_GERUDOS_FORTRESS", 8), + ("ENTR_GERUDOS_FORTRESS_8_1", "SCENE_GERUDOS_FORTRESS", 8), + ("ENTR_GERUDOS_FORTRESS_8_2", "SCENE_GERUDOS_FORTRESS", 8), + ("ENTR_GERUDOS_FORTRESS_8_3", "SCENE_GERUDOS_FORTRESS", 8), + ("ENTR_TEMPLE_OF_TIME_2", "SCENE_TEMPLE_OF_TIME", 2), + ("ENTR_TEMPLE_OF_TIME_2_1", "SCENE_TEMPLE_OF_TIME", 2), + ("ENTR_TEMPLE_OF_TIME_2_2", "SCENE_TEMPLE_OF_TIME", 2), + ("ENTR_TEMPLE_OF_TIME_2_3", "SCENE_TEMPLE_OF_TIME", 2), + ("ENTR_CHAMBER_OF_THE_SAGES_1", "SCENE_CHAMBER_OF_THE_SAGES", 1), + ("ENTR_CHAMBER_OF_THE_SAGES_1_1", "SCENE_CHAMBER_OF_THE_SAGES", 1), + ("ENTR_CHAMBER_OF_THE_SAGES_1_2", "SCENE_CHAMBER_OF_THE_SAGES", 1), + ("ENTR_CHAMBER_OF_THE_SAGES_1_3", "SCENE_CHAMBER_OF_THE_SAGES", 1), + ("ENTR_GERUDOS_FORTRESS_9", "SCENE_GERUDOS_FORTRESS", 9), + ("ENTR_GERUDOS_FORTRESS_9_1", "SCENE_GERUDOS_FORTRESS", 9), + ("ENTR_GERUDOS_FORTRESS_9_2", "SCENE_GERUDOS_FORTRESS", 9), + ("ENTR_GERUDOS_FORTRESS_9_3", "SCENE_GERUDOS_FORTRESS", 9), + ("ENTR_GERUDOS_FORTRESS_10", "SCENE_GERUDOS_FORTRESS", 10), + ("ENTR_GERUDOS_FORTRESS_10_1", "SCENE_GERUDOS_FORTRESS", 10), + ("ENTR_GERUDOS_FORTRESS_10_2", "SCENE_GERUDOS_FORTRESS", 10), + ("ENTR_GERUDOS_FORTRESS_10_3", "SCENE_GERUDOS_FORTRESS", 10), + ("ENTR_GERUDOS_FORTRESS_11", "SCENE_GERUDOS_FORTRESS", 11), + ("ENTR_GERUDOS_FORTRESS_11_1", "SCENE_GERUDOS_FORTRESS", 11), + ("ENTR_GERUDOS_FORTRESS_11_2", "SCENE_GERUDOS_FORTRESS", 11), + ("ENTR_GERUDOS_FORTRESS_11_3", "SCENE_GERUDOS_FORTRESS", 11), + ("ENTR_GERUDOS_FORTRESS_12", "SCENE_GERUDOS_FORTRESS", 12), + ("ENTR_GERUDOS_FORTRESS_12_1", "SCENE_GERUDOS_FORTRESS", 12), + ("ENTR_GERUDOS_FORTRESS_12_2", "SCENE_GERUDOS_FORTRESS", 12), + ("ENTR_GERUDOS_FORTRESS_12_3", "SCENE_GERUDOS_FORTRESS", 12), + ("ENTR_LON_LON_RANCH_2", "SCENE_LON_LON_RANCH", 2), + ("ENTR_LON_LON_RANCH_2_1", "SCENE_LON_LON_RANCH", 2), + ("ENTR_LON_LON_RANCH_2_2", "SCENE_LON_LON_RANCH", 2), + ("ENTR_LON_LON_RANCH_2_3", "SCENE_LON_LON_RANCH", 2), + ("ENTR_LON_LON_RANCH_3", "SCENE_LON_LON_RANCH", 3), + ("ENTR_LON_LON_RANCH_3_1", "SCENE_LON_LON_RANCH", 3), + ("ENTR_LON_LON_RANCH_3_2", "SCENE_LON_LON_RANCH", 3), + ("ENTR_LON_LON_RANCH_3_3", "SCENE_LON_LON_RANCH", 3), + ("ENTR_TEST_SHOOTING_GALLERY_0", "SCENE_SHOOTING_GALLERY", 0), + ("ENTR_TEST_SHOOTING_GALLERY_0_1", "SCENE_SHOOTING_GALLERY", 0), + ("ENTR_TEST_SHOOTING_GALLERY_0_2", "SCENE_SHOOTING_GALLERY", 0), + ("ENTR_TEST_SHOOTING_GALLERY_0_3", "SCENE_SHOOTING_GALLERY", 0), + ("ENTR_TEST_SACRED_FOREST_MEADOW_0_4", "SCENE_SACRED_FOREST_MEADOW", 0), + ("ENTR_TEST_CUTSCENE_MAP_0_5", "SCENE_CUTSCENE_MAP", 0), + ("ENTR_TEST_SHOOTING_GALLERY_0_6", "SCENE_SHOOTING_GALLERY", 0), + ("ENTR_TEST_SHOOTING_GALLERY_0_7", "SCENE_SHOOTING_GALLERY", 0), + ("ENTR_TEST_SHOOTING_GALLERY_0_8", "SCENE_SHOOTING_GALLERY", 0), + ("ENTR_TEST_SHOOTING_GALLERY_0_9", "SCENE_SHOOTING_GALLERY", 0), + ("ENTR_TEST_SHOOTING_GALLERY_0_10", "SCENE_SHOOTING_GALLERY", 0), + ("ENTR_SPIRIT_TEMPLE_1", "SCENE_SPIRIT_TEMPLE", 1), + ("ENTR_SPIRIT_TEMPLE_1_1", "SCENE_SPIRIT_TEMPLE", 1), + ("ENTR_SPIRIT_TEMPLE_1_2", "SCENE_SPIRIT_TEMPLE", 1), + ("ENTR_SPIRIT_TEMPLE_1_3", "SCENE_SPIRIT_TEMPLE", 1), + ("ENTR_STABLE_0", "SCENE_STABLE", 0), + ("ENTR_STABLE_0_1", "SCENE_STABLE", 0), + ("ENTR_STABLE_0_2", "SCENE_STABLE", 0), + ("ENTR_STABLE_0_3", "SCENE_STABLE", 0), + ("ENTR_KAKARIKO_CENTER_GUEST_HOUSE_0", "SCENE_KAKARIKO_CENTER_GUEST_HOUSE", 0), + ("ENTR_KAKARIKO_CENTER_GUEST_HOUSE_0_1", "SCENE_KAKARIKO_CENTER_GUEST_HOUSE", 0), + ("ENTR_KAKARIKO_CENTER_GUEST_HOUSE_0_2", "SCENE_KAKARIKO_CENTER_GUEST_HOUSE", 0), + ("ENTR_KAKARIKO_CENTER_GUEST_HOUSE_0_3", "SCENE_KAKARIKO_CENTER_GUEST_HOUSE", 0), + ("ENTR_JABU_JABU_BOSS_0", "SCENE_JABU_JABU_BOSS", 0), + ("ENTR_JABU_JABU_BOSS_0_1", "SCENE_JABU_JABU_BOSS", 0), + ("ENTR_JABU_JABU_BOSS_0_2", "SCENE_JABU_JABU_BOSS", 0), + ("ENTR_JABU_JABU_BOSS_0_3", "SCENE_JABU_JABU_BOSS", 0), + ("ENTR_FIRE_TEMPLE_BOSS_0", "SCENE_FIRE_TEMPLE_BOSS", 0), + ("ENTR_FIRE_TEMPLE_BOSS_0_1", "SCENE_FIRE_TEMPLE_BOSS", 0), + ("ENTR_FIRE_TEMPLE_BOSS_0_2", "SCENE_FIRE_TEMPLE_BOSS", 0), + ("ENTR_FIRE_TEMPLE_BOSS_0_3", "SCENE_FIRE_TEMPLE_BOSS", 0), + ("ENTR_LAKE_HYLIA_6", "SCENE_LAKE_HYLIA", 6), + ("ENTR_LAKE_HYLIA_6_1", "SCENE_LAKE_HYLIA", 6), + ("ENTR_LAKE_HYLIA_6_2", "SCENE_LAKE_HYLIA", 6), + ("ENTR_LAKE_HYLIA_6_3", "SCENE_LAKE_HYLIA", 6), + ("ENTR_GRAVEKEEPERS_HUT_0", "SCENE_GRAVEKEEPERS_HUT", 0), + ("ENTR_GRAVEKEEPERS_HUT_0_1", "SCENE_GRAVEKEEPERS_HUT", 0), + ("ENTR_GRAVEKEEPERS_HUT_0_2", "SCENE_GRAVEKEEPERS_HUT", 0), + ("ENTR_GRAVEKEEPERS_HUT_0_3", "SCENE_GRAVEKEEPERS_HUT", 0), + ("ENTR_HYRULE_FIELD_14", "SCENE_HYRULE_FIELD", 14), + ("ENTR_HYRULE_FIELD_14_1", "SCENE_HYRULE_FIELD", 14), + ("ENTR_HYRULE_FIELD_14_2", "SCENE_HYRULE_FIELD", 14), + ("ENTR_HYRULE_FIELD_14_3", "SCENE_HYRULE_FIELD", 14), + ("ENTR_GREAT_FAIRYS_FOUNTAIN_MAGIC_0", "SCENE_GREAT_FAIRYS_FOUNTAIN_MAGIC", 0), + ("ENTR_GREAT_FAIRYS_FOUNTAIN_MAGIC_0_1", "SCENE_GREAT_FAIRYS_FOUNTAIN_MAGIC", 0), + ("ENTR_GREAT_FAIRYS_FOUNTAIN_MAGIC_0_2", "SCENE_GREAT_FAIRYS_FOUNTAIN_MAGIC", 0), + ("ENTR_GREAT_FAIRYS_FOUNTAIN_MAGIC_0_3", "SCENE_GREAT_FAIRYS_FOUNTAIN_MAGIC", 0), + ("ENTR_GREAT_FAIRYS_FOUNTAIN_MAGIC_0_4", "SCENE_GREAT_FAIRYS_FOUNTAIN_MAGIC", 0), + ("ENTR_GREAT_FAIRYS_FOUNTAIN_MAGIC_0_5", "SCENE_GREAT_FAIRYS_FOUNTAIN_MAGIC", 0), + ("ENTR_GREAT_FAIRYS_FOUNTAIN_MAGIC_0_6", "SCENE_GREAT_FAIRYS_FOUNTAIN_MAGIC", 0), + ("ENTR_REDEAD_GRAVE_0", "SCENE_REDEAD_GRAVE", 0), + ("ENTR_REDEAD_GRAVE_0_1", "SCENE_REDEAD_GRAVE", 0), + ("ENTR_REDEAD_GRAVE_0_2", "SCENE_REDEAD_GRAVE", 0), + ("ENTR_REDEAD_GRAVE_0_3", "SCENE_REDEAD_GRAVE", 0), + ("ENTR_TEMPLE_OF_TIME_3", "SCENE_TEMPLE_OF_TIME", 3), + ("ENTR_TEMPLE_OF_TIME_3_1", "SCENE_TEMPLE_OF_TIME", 3), + ("ENTR_TEMPLE_OF_TIME_3_2", "SCENE_TEMPLE_OF_TIME", 3), + ("ENTR_TEMPLE_OF_TIME_3_3", "SCENE_TEMPLE_OF_TIME", 3), + ("ENTR_TEMPLE_OF_TIME_4", "SCENE_TEMPLE_OF_TIME", 4), + ("ENTR_TEMPLE_OF_TIME_4_1", "SCENE_TEMPLE_OF_TIME", 4), + ("ENTR_TEMPLE_OF_TIME_4_2", "SCENE_TEMPLE_OF_TIME", 4), + ("ENTR_TEMPLE_OF_TIME_4_3", "SCENE_TEMPLE_OF_TIME", 4), + ("ENTR_ZORAS_DOMAIN_4", "SCENE_ZORAS_DOMAIN", 4), + ("ENTR_ZORAS_DOMAIN_4_1", "SCENE_ZORAS_DOMAIN", 4), + ("ENTR_ZORAS_DOMAIN_4_2", "SCENE_ZORAS_DOMAIN", 4), + ("ENTR_ZORAS_DOMAIN_4_3", "SCENE_ZORAS_DOMAIN", 4), + ("ENTR_GANONS_TOWER_COLLAPSE_EXTERIOR_2", "SCENE_GANONS_TOWER_COLLAPSE_EXTERIOR", 2), + ("ENTR_GANONS_TOWER_COLLAPSE_EXTERIOR_2_1", "SCENE_GANONS_TOWER_COLLAPSE_EXTERIOR", 2), + ("ENTR_GANONS_TOWER_COLLAPSE_EXTERIOR_2_2", "SCENE_GANONS_TOWER_COLLAPSE_EXTERIOR", 2), + ("ENTR_GANONS_TOWER_COLLAPSE_EXTERIOR_2_3", "SCENE_GANONS_TOWER_COLLAPSE_EXTERIOR", 2), + ("ENTR_GANONS_TOWER_COLLAPSE_EXTERIOR_3", "SCENE_GANONS_TOWER_COLLAPSE_EXTERIOR", 3), + ("ENTR_GANONS_TOWER_COLLAPSE_EXTERIOR_3_1", "SCENE_GANONS_TOWER_COLLAPSE_EXTERIOR", 3), + ("ENTR_GANONS_TOWER_COLLAPSE_EXTERIOR_3_2", "SCENE_GANONS_TOWER_COLLAPSE_EXTERIOR", 3), + ("ENTR_GANONS_TOWER_COLLAPSE_EXTERIOR_3_3", "SCENE_GANONS_TOWER_COLLAPSE_EXTERIOR", 3), + ("ENTR_GANONS_TOWER_COLLAPSE_EXTERIOR_4", "SCENE_GANONS_TOWER_COLLAPSE_EXTERIOR", 4), + ("ENTR_GANONS_TOWER_COLLAPSE_EXTERIOR_4_1", "SCENE_GANONS_TOWER_COLLAPSE_EXTERIOR", 4), + ("ENTR_GANONS_TOWER_COLLAPSE_EXTERIOR_4_2", "SCENE_GANONS_TOWER_COLLAPSE_EXTERIOR", 4), + ("ENTR_GANONS_TOWER_COLLAPSE_EXTERIOR_4_3", "SCENE_GANONS_TOWER_COLLAPSE_EXTERIOR", 4), + ("ENTR_KOKIRI_FOREST_7", "SCENE_KOKIRI_FOREST", 7), + ("ENTR_KOKIRI_FOREST_7_1", "SCENE_KOKIRI_FOREST", 7), + ("ENTR_KOKIRI_FOREST_7_2", "SCENE_KOKIRI_FOREST", 7), + ("ENTR_KOKIRI_FOREST_7_3", "SCENE_KOKIRI_FOREST", 7), + ("ENTR_KOKIRI_FOREST_8", "SCENE_KOKIRI_FOREST", 8), + ("ENTR_KOKIRI_FOREST_8_1", "SCENE_KOKIRI_FOREST", 8), + ("ENTR_KOKIRI_FOREST_8_2", "SCENE_KOKIRI_FOREST", 8), + ("ENTR_KOKIRI_FOREST_8_3", "SCENE_KOKIRI_FOREST", 8), + ("ENTR_HYRULE_CASTLE_2", "SCENE_HYRULE_CASTLE", 2), + ("ENTR_HYRULE_CASTLE_2_1", "SCENE_HYRULE_CASTLE", 2), + ("ENTR_OUTSIDE_GANONS_CASTLE_2_2", "SCENE_OUTSIDE_GANONS_CASTLE", 2), + ("ENTR_OUTSIDE_GANONS_CASTLE_2_3", "SCENE_OUTSIDE_GANONS_CASTLE", 2), + ("ENTR_HYRULE_CASTLE_2_4", "SCENE_HYRULE_CASTLE", 2), + ("ENTR_KAKARIKO_VILLAGE_5", "SCENE_KAKARIKO_VILLAGE", 5), + ("ENTR_KAKARIKO_VILLAGE_5_1", "SCENE_KAKARIKO_VILLAGE", 5), + ("ENTR_KAKARIKO_VILLAGE_5_2", "SCENE_KAKARIKO_VILLAGE", 5), + ("ENTR_KAKARIKO_VILLAGE_5_3", "SCENE_KAKARIKO_VILLAGE", 5), + ("ENTR_KAKARIKO_VILLAGE_6", "SCENE_KAKARIKO_VILLAGE", 6), + ("ENTR_KAKARIKO_VILLAGE_6_1", "SCENE_KAKARIKO_VILLAGE", 6), + ("ENTR_KAKARIKO_VILLAGE_6_2", "SCENE_KAKARIKO_VILLAGE", 6), + ("ENTR_KAKARIKO_VILLAGE_6_3", "SCENE_KAKARIKO_VILLAGE", 6), + ("ENTR_KAKARIKO_VILLAGE_7", "SCENE_KAKARIKO_VILLAGE", 7), + ("ENTR_KAKARIKO_VILLAGE_7_1", "SCENE_KAKARIKO_VILLAGE", 7), + ("ENTR_KAKARIKO_VILLAGE_7_2", "SCENE_KAKARIKO_VILLAGE", 7), + ("ENTR_KAKARIKO_VILLAGE_7_3", "SCENE_KAKARIKO_VILLAGE", 7), + ("ENTR_KAKARIKO_VILLAGE_8", "SCENE_KAKARIKO_VILLAGE", 8), + ("ENTR_KAKARIKO_VILLAGE_8_1", "SCENE_KAKARIKO_VILLAGE", 8), + ("ENTR_KAKARIKO_VILLAGE_8_2", "SCENE_KAKARIKO_VILLAGE", 8), + ("ENTR_KAKARIKO_VILLAGE_8_3", "SCENE_KAKARIKO_VILLAGE", 8), + ("ENTR_GRAVEYARD_2", "SCENE_GRAVEYARD", 2), + ("ENTR_GRAVEYARD_2_1", "SCENE_GRAVEYARD", 2), + ("ENTR_GRAVEYARD_2_2", "SCENE_GRAVEYARD", 2), + ("ENTR_GRAVEYARD_2_3", "SCENE_GRAVEYARD", 2), + ("ENTR_GRAVEYARD_3", "SCENE_GRAVEYARD", 3), + ("ENTR_GRAVEYARD_3_1", "SCENE_GRAVEYARD", 3), + ("ENTR_GRAVEYARD_3_2", "SCENE_GRAVEYARD", 3), + ("ENTR_GRAVEYARD_3_3", "SCENE_GRAVEYARD", 3), + ("ENTR_GRAVEYARD_4", "SCENE_GRAVEYARD", 4), + ("ENTR_GRAVEYARD_4_1", "SCENE_GRAVEYARD", 4), + ("ENTR_GRAVEYARD_4_2", "SCENE_GRAVEYARD", 4), + ("ENTR_GRAVEYARD_4_3", "SCENE_GRAVEYARD", 4), + ("ENTR_GRAVEYARD_5", "SCENE_GRAVEYARD", 5), + ("ENTR_GRAVEYARD_5_1", "SCENE_GRAVEYARD", 5), + ("ENTR_GRAVEYARD_5_2", "SCENE_GRAVEYARD", 5), + ("ENTR_GRAVEYARD_5_3", "SCENE_GRAVEYARD", 5), + ("ENTR_HAUNTED_WASTELAND_1", "SCENE_HAUNTED_WASTELAND", 1), + ("ENTR_HAUNTED_WASTELAND_1_1", "SCENE_HAUNTED_WASTELAND", 1), + ("ENTR_HAUNTED_WASTELAND_1_2", "SCENE_HAUNTED_WASTELAND", 1), + ("ENTR_HAUNTED_WASTELAND_1_3", "SCENE_HAUNTED_WASTELAND", 1), + ("ENTR_HAUNTED_WASTELAND_2", "SCENE_HAUNTED_WASTELAND", 2), + ("ENTR_HAUNTED_WASTELAND_2_1", "SCENE_HAUNTED_WASTELAND", 2), + ("ENTR_HAUNTED_WASTELAND_2_2", "SCENE_HAUNTED_WASTELAND", 2), + ("ENTR_HAUNTED_WASTELAND_2_3", "SCENE_HAUNTED_WASTELAND", 2), + ("ENTR_FAIRYS_FOUNTAIN_0", "SCENE_FAIRYS_FOUNTAIN", 0), + ("ENTR_FAIRYS_FOUNTAIN_0_1", "SCENE_FAIRYS_FOUNTAIN", 0), + ("ENTR_FAIRYS_FOUNTAIN_0_2", "SCENE_FAIRYS_FOUNTAIN", 0), + ("ENTR_FAIRYS_FOUNTAIN_0_3", "SCENE_FAIRYS_FOUNTAIN", 0), + ("ENTR_GREAT_FAIRYS_FOUNTAIN_SPELLS_0", "SCENE_GREAT_FAIRYS_FOUNTAIN_SPELLS", 0), + ("ENTR_GREAT_FAIRYS_FOUNTAIN_SPELLS_0_1", "SCENE_GREAT_FAIRYS_FOUNTAIN_SPELLS", 0), + ("ENTR_GREAT_FAIRYS_FOUNTAIN_SPELLS_0_2", "SCENE_GREAT_FAIRYS_FOUNTAIN_SPELLS", 0), + ("ENTR_GREAT_FAIRYS_FOUNTAIN_SPELLS_0_3", "SCENE_GREAT_FAIRYS_FOUNTAIN_SPELLS", 0), + ("ENTR_GREAT_FAIRYS_FOUNTAIN_SPELLS_0_4", "SCENE_GREAT_FAIRYS_FOUNTAIN_SPELLS", 0), + ("ENTR_GREAT_FAIRYS_FOUNTAIN_SPELLS_0_5", "SCENE_GREAT_FAIRYS_FOUNTAIN_SPELLS", 0), + ("ENTR_GREAT_FAIRYS_FOUNTAIN_SPELLS_0_6", "SCENE_GREAT_FAIRYS_FOUNTAIN_SPELLS", 0), + ("ENTR_LON_LON_RANCH_4", "SCENE_LON_LON_RANCH", 4), + ("ENTR_LON_LON_RANCH_4_1", "SCENE_LON_LON_RANCH", 4), + ("ENTR_LON_LON_RANCH_4_2", "SCENE_LON_LON_RANCH", 4), + ("ENTR_LON_LON_RANCH_4_3", "SCENE_LON_LON_RANCH", 4), + ("ENTR_GORON_SHOP_0", "SCENE_GORON_SHOP", 0), + ("ENTR_GORON_SHOP_0_1", "SCENE_GORON_SHOP", 0), + ("ENTR_GORON_SHOP_0_2", "SCENE_GORON_SHOP", 0), + ("ENTR_GORON_SHOP_0_3", "SCENE_GORON_SHOP", 0), + ("ENTR_ZORA_SHOP_0", "SCENE_ZORA_SHOP", 0), + ("ENTR_ZORA_SHOP_0_1", "SCENE_ZORA_SHOP", 0), + ("ENTR_ZORA_SHOP_0_2", "SCENE_ZORA_SHOP", 0), + ("ENTR_ZORA_SHOP_0_3", "SCENE_ZORA_SHOP", 0), + ("ENTR_POTION_SHOP_KAKARIKO_0", "SCENE_POTION_SHOP_KAKARIKO", 0), + ("ENTR_POTION_SHOP_KAKARIKO_0_1", "SCENE_POTION_SHOP_KAKARIKO", 0), + ("ENTR_POTION_SHOP_KAKARIKO_0_2", "SCENE_POTION_SHOP_KAKARIKO", 0), + ("ENTR_POTION_SHOP_KAKARIKO_0_3", "SCENE_POTION_SHOP_KAKARIKO", 0), + ("ENTR_POTION_SHOP_MARKET_0", "SCENE_POTION_SHOP_MARKET", 0), + ("ENTR_POTION_SHOP_MARKET_0_1", "SCENE_POTION_SHOP_MARKET", 0), + ("ENTR_POTION_SHOP_MARKET_0_2", "SCENE_POTION_SHOP_MARKET", 0), + ("ENTR_POTION_SHOP_MARKET_0_3", "SCENE_POTION_SHOP_MARKET", 0), + ("ENTR_BACK_ALLEY_DAY_4", "SCENE_BACK_ALLEY_DAY", 4), + ("ENTR_BACK_ALLEY_NIGHT_4_1", "SCENE_BACK_ALLEY_NIGHT", 4), + ("ENTR_BACK_ALLEY_DAY_4_2", "SCENE_BACK_ALLEY_DAY", 4), + ("ENTR_BACK_ALLEY_NIGHT_4_3", "SCENE_BACK_ALLEY_NIGHT", 4), + ("ENTR_BOMBCHU_SHOP_0", "SCENE_BOMBCHU_SHOP", 0), + ("ENTR_BOMBCHU_SHOP_0_1", "SCENE_BOMBCHU_SHOP", 0), + ("ENTR_BOMBCHU_SHOP_0_2", "SCENE_BOMBCHU_SHOP", 0), + ("ENTR_BOMBCHU_SHOP_0_3", "SCENE_BOMBCHU_SHOP", 0), + ("ENTR_ZORAS_FOUNTAIN_5", "SCENE_ZORAS_FOUNTAIN", 5), + ("ENTR_ZORAS_FOUNTAIN_5_1", "SCENE_ZORAS_FOUNTAIN", 5), + ("ENTR_ZORAS_FOUNTAIN_5_2", "SCENE_ZORAS_FOUNTAIN", 5), + ("ENTR_ZORAS_FOUNTAIN_5_3", "SCENE_ZORAS_FOUNTAIN", 5), + ("ENTR_DOG_LADY_HOUSE_0", "SCENE_DOG_LADY_HOUSE", 0), + ("ENTR_DOG_LADY_HOUSE_0_1", "SCENE_DOG_LADY_HOUSE", 0), + ("ENTR_DOG_LADY_HOUSE_0_2", "SCENE_DOG_LADY_HOUSE", 0), + ("ENTR_DOG_LADY_HOUSE_0_3", "SCENE_DOG_LADY_HOUSE", 0), + ("ENTR_IMPAS_HOUSE_0", "SCENE_IMPAS_HOUSE", 0), + ("ENTR_IMPAS_HOUSE_0_1", "SCENE_IMPAS_HOUSE", 0), + ("ENTR_IMPAS_HOUSE_0_2", "SCENE_IMPAS_HOUSE", 0), + ("ENTR_IMPAS_HOUSE_0_3", "SCENE_IMPAS_HOUSE", 0), + ("ENTR_CARPENTERS_TENT_0", "SCENE_CARPENTERS_TENT", 0), + ("ENTR_CARPENTERS_TENT_0_1", "SCENE_CARPENTERS_TENT", 0), + ("ENTR_CARPENTERS_TENT_0_2", "SCENE_CARPENTERS_TENT", 0), + ("ENTR_CARPENTERS_TENT_0_3", "SCENE_CARPENTERS_TENT", 0), + ("ENTR_GERUDOS_FORTRESS_13", "SCENE_GERUDOS_FORTRESS", 13), + ("ENTR_GERUDOS_FORTRESS_13_1", "SCENE_GERUDOS_FORTRESS", 13), + ("ENTR_GERUDOS_FORTRESS_13_2", "SCENE_GERUDOS_FORTRESS", 13), + ("ENTR_GERUDOS_FORTRESS_13_3", "SCENE_GERUDOS_FORTRESS", 13), + ("ENTR_GERUDOS_FORTRESS_14", "SCENE_GERUDOS_FORTRESS", 14), + ("ENTR_GERUDOS_FORTRESS_14_1", "SCENE_GERUDOS_FORTRESS", 14), + ("ENTR_GERUDOS_FORTRESS_14_2", "SCENE_GERUDOS_FORTRESS", 14), + ("ENTR_GERUDOS_FORTRESS_14_3", "SCENE_GERUDOS_FORTRESS", 14), + ("ENTR_GERUDOS_FORTRESS_15", "SCENE_GERUDOS_FORTRESS", 15), + ("ENTR_GERUDOS_FORTRESS_15_1", "SCENE_GERUDOS_FORTRESS", 15), + ("ENTR_GERUDOS_FORTRESS_15_2", "SCENE_GERUDOS_FORTRESS", 15), + ("ENTR_GERUDOS_FORTRESS_15_3", "SCENE_GERUDOS_FORTRESS", 15), + ("ENTR_GERUDOS_FORTRESS_16", "SCENE_GERUDOS_FORTRESS", 16), + ("ENTR_GERUDOS_FORTRESS_16_1", "SCENE_GERUDOS_FORTRESS", 16), + ("ENTR_GERUDOS_FORTRESS_16_2", "SCENE_GERUDOS_FORTRESS", 16), + ("ENTR_GERUDOS_FORTRESS_16_3", "SCENE_GERUDOS_FORTRESS", 16), + ("ENTR_GERUDOS_FORTRESS_17", "SCENE_GERUDOS_FORTRESS", 17), + ("ENTR_GERUDOS_FORTRESS_17_1", "SCENE_GERUDOS_FORTRESS", 17), + ("ENTR_GERUDOS_FORTRESS_17_2", "SCENE_GERUDOS_FORTRESS", 17), + ("ENTR_GERUDOS_FORTRESS_17_3", "SCENE_GERUDOS_FORTRESS", 17), + ("ENTR_MARKET_DAY_6", "SCENE_MARKET_DAY", 6), + ("ENTR_MARKET_NIGHT_6_1", "SCENE_MARKET_NIGHT", 6), + ("ENTR_MARKET_RUINS_6_2", "SCENE_MARKET_RUINS", 6), + ("ENTR_MARKET_RUINS_6_3", "SCENE_MARKET_RUINS", 6), + ("ENTR_MARKET_DAY_7", "SCENE_MARKET_DAY", 7), + ("ENTR_MARKET_NIGHT_7_1", "SCENE_MARKET_NIGHT", 7), + ("ENTR_MARKET_RUINS_7_2", "SCENE_MARKET_RUINS", 7), + ("ENTR_MARKET_RUINS_7_3", "SCENE_MARKET_RUINS", 7), + ("ENTR_BACK_ALLEY_DAY_2", "SCENE_BACK_ALLEY_DAY", 2), + ("ENTR_BACK_ALLEY_NIGHT_2_1", "SCENE_BACK_ALLEY_NIGHT", 2), + ("ENTR_BACK_ALLEY_DAY_2_2", "SCENE_BACK_ALLEY_DAY", 2), + ("ENTR_BACK_ALLEY_NIGHT_2_3", "SCENE_BACK_ALLEY_NIGHT", 2), + ("ENTR_ZORAS_DOMAIN_2", "SCENE_ZORAS_DOMAIN", 2), + ("ENTR_ZORAS_DOMAIN_2_1", "SCENE_ZORAS_DOMAIN", 2), + ("ENTR_ZORAS_DOMAIN_2_2", "SCENE_ZORAS_DOMAIN", 2), + ("ENTR_ZORAS_DOMAIN_2_3", "SCENE_ZORAS_DOMAIN", 2), + ("ENTR_LAKE_HYLIA_3", "SCENE_LAKE_HYLIA", 3), + ("ENTR_LAKE_HYLIA_3_1", "SCENE_LAKE_HYLIA", 3), + ("ENTR_LAKE_HYLIA_3_2", "SCENE_LAKE_HYLIA", 3), + ("ENTR_LAKE_HYLIA_3_3", "SCENE_LAKE_HYLIA", 3), + ("ENTR_LAKE_HYLIA_4", "SCENE_LAKE_HYLIA", 4), + ("ENTR_LAKE_HYLIA_4_1", "SCENE_LAKE_HYLIA", 4), + ("ENTR_LAKE_HYLIA_4_2", "SCENE_LAKE_HYLIA", 4), + ("ENTR_LAKE_HYLIA_4_3", "SCENE_LAKE_HYLIA", 4), + ("ENTR_GERUDO_VALLEY_4", "SCENE_GERUDO_VALLEY", 4), + ("ENTR_GERUDO_VALLEY_4_1", "SCENE_GERUDO_VALLEY", 4), + ("ENTR_GERUDO_VALLEY_4_2", "SCENE_GERUDO_VALLEY", 4), + ("ENTR_GERUDO_VALLEY_4_3", "SCENE_GERUDO_VALLEY", 4), + ("ENTR_ZORAS_FOUNTAIN_3", "SCENE_ZORAS_FOUNTAIN", 3), + ("ENTR_ZORAS_FOUNTAIN_3_1", "SCENE_ZORAS_FOUNTAIN", 3), + ("ENTR_ZORAS_FOUNTAIN_3_2", "SCENE_ZORAS_FOUNTAIN", 3), + ("ENTR_ZORAS_FOUNTAIN_3_3", "SCENE_ZORAS_FOUNTAIN", 3), + ("ENTR_ZORAS_FOUNTAIN_4", "SCENE_ZORAS_FOUNTAIN", 4), + ("ENTR_ZORAS_FOUNTAIN_4_1", "SCENE_ZORAS_FOUNTAIN", 4), + ("ENTR_ZORAS_FOUNTAIN_4_2", "SCENE_ZORAS_FOUNTAIN", 4), + ("ENTR_ZORAS_FOUNTAIN_4_3", "SCENE_ZORAS_FOUNTAIN", 4), + ("ENTR_GANONS_TOWER_COLLAPSE_INTERIOR_4", "SCENE_GANONS_TOWER_COLLAPSE_INTERIOR", 4), + ("ENTR_GANONS_TOWER_COLLAPSE_INTERIOR_4_1", "SCENE_GANONS_TOWER_COLLAPSE_INTERIOR", 4), + ("ENTR_GANONS_TOWER_COLLAPSE_INTERIOR_4_2", "SCENE_GANONS_TOWER_COLLAPSE_INTERIOR", 4), + ("ENTR_GANONS_TOWER_COLLAPSE_INTERIOR_4_3", "SCENE_GANONS_TOWER_COLLAPSE_INTERIOR", 4), + ("ENTR_GANONS_TOWER_COLLAPSE_INTERIOR_5", "SCENE_GANONS_TOWER_COLLAPSE_INTERIOR", 5), + ("ENTR_GANONS_TOWER_COLLAPSE_INTERIOR_5_1", "SCENE_GANONS_TOWER_COLLAPSE_INTERIOR", 5), + ("ENTR_GANONS_TOWER_COLLAPSE_INTERIOR_5_2", "SCENE_GANONS_TOWER_COLLAPSE_INTERIOR", 5), + ("ENTR_GANONS_TOWER_COLLAPSE_INTERIOR_5_3", "SCENE_GANONS_TOWER_COLLAPSE_INTERIOR", 5), + ("ENTR_GANONS_TOWER_COLLAPSE_INTERIOR_6", "SCENE_GANONS_TOWER_COLLAPSE_INTERIOR", 6), + ("ENTR_GANONS_TOWER_COLLAPSE_INTERIOR_6_1", "SCENE_GANONS_TOWER_COLLAPSE_INTERIOR", 6), + ("ENTR_GANONS_TOWER_COLLAPSE_INTERIOR_6_2", "SCENE_GANONS_TOWER_COLLAPSE_INTERIOR", 6), + ("ENTR_GANONS_TOWER_COLLAPSE_INTERIOR_6_3", "SCENE_GANONS_TOWER_COLLAPSE_INTERIOR", 6), + ("ENTR_POTION_SHOP_KAKARIKO_1", "SCENE_POTION_SHOP_KAKARIKO", 1), + ("ENTR_POTION_SHOP_KAKARIKO_1_1", "SCENE_POTION_SHOP_KAKARIKO", 1), + ("ENTR_POTION_SHOP_KAKARIKO_1_2", "SCENE_POTION_SHOP_KAKARIKO", 1), + ("ENTR_POTION_SHOP_KAKARIKO_1_3", "SCENE_POTION_SHOP_KAKARIKO", 1), + ("ENTR_POTION_SHOP_KAKARIKO_2", "SCENE_POTION_SHOP_KAKARIKO", 2), + ("ENTR_POTION_SHOP_KAKARIKO_2_1", "SCENE_POTION_SHOP_KAKARIKO", 2), + ("ENTR_POTION_SHOP_KAKARIKO_2_2", "SCENE_POTION_SHOP_KAKARIKO", 2), + ("ENTR_POTION_SHOP_KAKARIKO_2_3", "SCENE_POTION_SHOP_KAKARIKO", 2), + ("ENTR_SPIRIT_TEMPLE_2", "SCENE_SPIRIT_TEMPLE", 2), + ("ENTR_SPIRIT_TEMPLE_2_1", "SCENE_SPIRIT_TEMPLE", 2), + ("ENTR_SPIRIT_TEMPLE_2_2", "SCENE_SPIRIT_TEMPLE", 2), + ("ENTR_SPIRIT_TEMPLE_2_3", "SCENE_SPIRIT_TEMPLE", 2), + ("ENTR_SPIRIT_TEMPLE_3", "SCENE_SPIRIT_TEMPLE", 3), + ("ENTR_SPIRIT_TEMPLE_3_1", "SCENE_SPIRIT_TEMPLE", 3), + ("ENTR_SPIRIT_TEMPLE_3_2", "SCENE_SPIRIT_TEMPLE", 3), + ("ENTR_SPIRIT_TEMPLE_3_3", "SCENE_SPIRIT_TEMPLE", 3), + ("ENTR_SPIRIT_TEMPLE_4", "SCENE_SPIRIT_TEMPLE", 4), + ("ENTR_SPIRIT_TEMPLE_4_1", "SCENE_SPIRIT_TEMPLE", 4), + ("ENTR_SPIRIT_TEMPLE_4_2", "SCENE_SPIRIT_TEMPLE", 4), + ("ENTR_SPIRIT_TEMPLE_4_3", "SCENE_SPIRIT_TEMPLE", 4), + ("ENTR_GORON_CITY_2", "SCENE_GORON_CITY", 2), + ("ENTR_GORON_CITY_2_1", "SCENE_GORON_CITY", 2), + ("ENTR_GORON_CITY_2_2", "SCENE_GORON_CITY", 2), + ("ENTR_GORON_CITY_2_3", "SCENE_GORON_CITY", 2), + ("ENTR_CASTLE_COURTYARD_ZELDA_0", "SCENE_CASTLE_COURTYARD_ZELDA", 0), + ("ENTR_CASTLE_COURTYARD_ZELDA_0_1", "SCENE_CASTLE_COURTYARD_ZELDA", 0), + ("ENTR_CASTLE_COURTYARD_ZELDA_0_2", "SCENE_CASTLE_COURTYARD_ZELDA", 0), + ("ENTR_CASTLE_COURTYARD_ZELDA_0_3", "SCENE_CASTLE_COURTYARD_ZELDA", 0), + ("ENTR_CASTLE_COURTYARD_ZELDA_0_4", "SCENE_CASTLE_COURTYARD_ZELDA", 0), + ("ENTR_CASTLE_COURTYARD_ZELDA_0_5", "SCENE_CASTLE_COURTYARD_ZELDA", 0), + ("ENTR_CASTLE_COURTYARD_ZELDA_0_6", "SCENE_CASTLE_COURTYARD_ZELDA", 0), + ("ENTR_JABU_JABU_1", "SCENE_JABU_JABU", 1), + ("ENTR_JABU_JABU_1_1", "SCENE_JABU_JABU", 1), + ("ENTR_JABU_JABU_1_2", "SCENE_JABU_JABU", 1), + ("ENTR_JABU_JABU_1_3", "SCENE_JABU_JABU", 1), + ("ENTR_DODONGOS_CAVERN_BOSS_0", "SCENE_DODONGOS_CAVERN_BOSS", 0), + ("ENTR_DODONGOS_CAVERN_BOSS_0_1", "SCENE_DODONGOS_CAVERN_BOSS", 0), + ("ENTR_DODONGOS_CAVERN_BOSS_0_2", "SCENE_DODONGOS_CAVERN_BOSS", 0), + ("ENTR_DODONGOS_CAVERN_BOSS_0_3", "SCENE_DODONGOS_CAVERN_BOSS", 0), + ("ENTR_DEKU_TREE_BOSS_0", "SCENE_DEKU_TREE_BOSS", 0), + ("ENTR_DEKU_TREE_BOSS_0_1", "SCENE_DEKU_TREE_BOSS", 0), + ("ENTR_DEKU_TREE_BOSS_0_2", "SCENE_DEKU_TREE_BOSS", 0), + ("ENTR_DEKU_TREE_BOSS_0_3", "SCENE_DEKU_TREE_BOSS", 0), + ("ENTR_SHADOW_TEMPLE_BOSS_0", "SCENE_SHADOW_TEMPLE_BOSS", 0), + ("ENTR_SHADOW_TEMPLE_BOSS_0_1", "SCENE_SHADOW_TEMPLE_BOSS", 0), + ("ENTR_SHADOW_TEMPLE_BOSS_0_2", "SCENE_SHADOW_TEMPLE_BOSS", 0), + ("ENTR_SHADOW_TEMPLE_BOSS_0_3", "SCENE_SHADOW_TEMPLE_BOSS", 0), + ("ENTR_WATER_TEMPLE_BOSS_0", "SCENE_WATER_TEMPLE_BOSS", 0), + ("ENTR_WATER_TEMPLE_BOSS_0_1", "SCENE_WATER_TEMPLE_BOSS", 0), + ("ENTR_WATER_TEMPLE_BOSS_0_2", "SCENE_WATER_TEMPLE_BOSS", 0), + ("ENTR_WATER_TEMPLE_BOSS_0_3", "SCENE_WATER_TEMPLE_BOSS", 0), + ("ENTR_GANONS_TOWER_0", "SCENE_GANONS_TOWER", 0), + ("ENTR_GANONS_TOWER_0_1", "SCENE_GANONS_TOWER", 0), + ("ENTR_GANONS_TOWER_0_2", "SCENE_GANONS_TOWER", 0), + ("ENTR_GANONS_TOWER_0_3", "SCENE_GANONS_TOWER", 0), + ("ENTR_GANONDORF_BOSS_0", "SCENE_GANONDORF_BOSS", 0), + ("ENTR_GANONDORF_BOSS_0_1", "SCENE_GANONDORF_BOSS", 0), + ("ENTR_GANONDORF_BOSS_0_2", "SCENE_GANONDORF_BOSS", 0), + ("ENTR_GANONDORF_BOSS_0_3", "SCENE_GANONDORF_BOSS", 0), + ("ENTR_WATER_TEMPLE_1", "SCENE_WATER_TEMPLE", 1), + ("ENTR_WATER_TEMPLE_1_1", "SCENE_WATER_TEMPLE", 1), + ("ENTR_WATER_TEMPLE_1_2", "SCENE_WATER_TEMPLE", 1), + ("ENTR_WATER_TEMPLE_1_3", "SCENE_WATER_TEMPLE", 1), + ("ENTR_GANONS_TOWER_1", "SCENE_GANONS_TOWER", 1), + ("ENTR_GANONS_TOWER_1_1", "SCENE_GANONS_TOWER", 1), + ("ENTR_GANONS_TOWER_1_2", "SCENE_GANONS_TOWER", 1), + ("ENTR_GANONS_TOWER_1_3", "SCENE_GANONS_TOWER", 1), + ("ENTR_GANONS_TOWER_2", "SCENE_GANONS_TOWER", 2), + ("ENTR_GANONS_TOWER_2_1", "SCENE_GANONS_TOWER", 2), + ("ENTR_GANONS_TOWER_2_2", "SCENE_GANONS_TOWER", 2), + ("ENTR_GANONS_TOWER_2_3", "SCENE_GANONS_TOWER", 2), + ("ENTR_LON_LON_RANCH_5", "SCENE_LON_LON_RANCH", 5), + ("ENTR_LON_LON_RANCH_5_1", "SCENE_LON_LON_RANCH", 5), + ("ENTR_LON_LON_RANCH_5_2", "SCENE_LON_LON_RANCH", 5), + ("ENTR_LON_LON_RANCH_5_3", "SCENE_LON_LON_RANCH", 5), + ("ENTR_MIDOS_HOUSE_0", "SCENE_MIDOS_HOUSE", 0), + ("ENTR_MIDOS_HOUSE_0_1", "SCENE_MIDOS_HOUSE", 0), + ("ENTR_MIDOS_HOUSE_0_2", "SCENE_MIDOS_HOUSE", 0), + ("ENTR_MIDOS_HOUSE_0_3", "SCENE_MIDOS_HOUSE", 0), + ("ENTR_SARIAS_HOUSE_0", "SCENE_SARIAS_HOUSE", 0), + ("ENTR_SARIAS_HOUSE_0_1", "SCENE_SARIAS_HOUSE", 0), + ("ENTR_SARIAS_HOUSE_0_2", "SCENE_SARIAS_HOUSE", 0), + ("ENTR_SARIAS_HOUSE_0_3", "SCENE_SARIAS_HOUSE", 0), + ("ENTR_BACK_ALLEY_HOUSE_0", "SCENE_BACK_ALLEY_HOUSE", 0), + ("ENTR_BACK_ALLEY_HOUSE_0_1", "SCENE_BACK_ALLEY_HOUSE", 0), + ("ENTR_BACK_ALLEY_HOUSE_0_2", "SCENE_BACK_ALLEY_HOUSE", 0), + ("ENTR_BACK_ALLEY_HOUSE_0_3", "SCENE_BACK_ALLEY_HOUSE", 0), + ("ENTR_GANONS_TOWER_COLLAPSE_EXTERIOR_0", "SCENE_GANONS_TOWER_COLLAPSE_EXTERIOR", 0), + ("ENTR_GANONS_TOWER_COLLAPSE_EXTERIOR_0_1", "SCENE_GANONS_TOWER_COLLAPSE_EXTERIOR", 0), + ("ENTR_GANONS_TOWER_COLLAPSE_EXTERIOR_0_2", "SCENE_GANONS_TOWER_COLLAPSE_EXTERIOR", 0), + ("ENTR_GANONS_TOWER_COLLAPSE_EXTERIOR_0_3", "SCENE_GANONS_TOWER_COLLAPSE_EXTERIOR", 0), + ("ENTR_KOKIRI_FOREST_9", "SCENE_KOKIRI_FOREST", 9), + ("ENTR_KOKIRI_FOREST_9_1", "SCENE_KOKIRI_FOREST", 9), + ("ENTR_KOKIRI_FOREST_9_2", "SCENE_KOKIRI_FOREST", 9), + ("ENTR_KOKIRI_FOREST_9_3", "SCENE_KOKIRI_FOREST", 9), + ("ENTR_KOKIRI_FOREST_10", "SCENE_KOKIRI_FOREST", 10), + ("ENTR_KOKIRI_FOREST_10_1", "SCENE_KOKIRI_FOREST", 10), + ("ENTR_KOKIRI_FOREST_10_2", "SCENE_KOKIRI_FOREST", 10), + ("ENTR_KOKIRI_FOREST_10_3", "SCENE_KOKIRI_FOREST", 10), + ("ENTR_KAKARIKO_VILLAGE_9", "SCENE_KAKARIKO_VILLAGE", 9), + ("ENTR_KAKARIKO_VILLAGE_9_1", "SCENE_KAKARIKO_VILLAGE", 9), + ("ENTR_KAKARIKO_VILLAGE_9_2", "SCENE_KAKARIKO_VILLAGE", 9), + ("ENTR_KAKARIKO_VILLAGE_9_3", "SCENE_KAKARIKO_VILLAGE", 9), + ("ENTR_WINDMILL_AND_DAMPES_GRAVE_0", "SCENE_WINDMILL_AND_DAMPES_GRAVE", 0), + ("ENTR_WINDMILL_AND_DAMPES_GRAVE_0_1", "SCENE_WINDMILL_AND_DAMPES_GRAVE", 0), + ("ENTR_WINDMILL_AND_DAMPES_GRAVE_0_2", "SCENE_WINDMILL_AND_DAMPES_GRAVE", 0), + ("ENTR_WINDMILL_AND_DAMPES_GRAVE_0_3", "SCENE_WINDMILL_AND_DAMPES_GRAVE", 0), + ("ENTR_WINDMILL_AND_DAMPES_GRAVE_1", "SCENE_WINDMILL_AND_DAMPES_GRAVE", 1), + ("ENTR_WINDMILL_AND_DAMPES_GRAVE_1_1", "SCENE_WINDMILL_AND_DAMPES_GRAVE", 1), + ("ENTR_WINDMILL_AND_DAMPES_GRAVE_1_2", "SCENE_WINDMILL_AND_DAMPES_GRAVE", 1), + ("ENTR_WINDMILL_AND_DAMPES_GRAVE_1_3", "SCENE_WINDMILL_AND_DAMPES_GRAVE", 1), + ("ENTR_KOKIRI_FOREST_11", "SCENE_KOKIRI_FOREST", 11), + ("ENTR_KOKIRI_FOREST_11_1", "SCENE_KOKIRI_FOREST", 11), + ("ENTR_KOKIRI_FOREST_11_2", "SCENE_KOKIRI_FOREST", 11), + ("ENTR_KOKIRI_FOREST_11_3", "SCENE_KOKIRI_FOREST", 11), + ("ENTR_DEATH_MOUNTAIN_TRAIL_4", "SCENE_DEATH_MOUNTAIN_TRAIL", 4), + ("ENTR_DEATH_MOUNTAIN_TRAIL_4_1", "SCENE_DEATH_MOUNTAIN_TRAIL", 4), + ("ENTR_DEATH_MOUNTAIN_TRAIL_4_2", "SCENE_DEATH_MOUNTAIN_TRAIL", 4), + ("ENTR_DEATH_MOUNTAIN_TRAIL_4_3", "SCENE_DEATH_MOUNTAIN_TRAIL", 4), + ("ENTR_FISHING_POND_0", "SCENE_FISHING_POND", 0), + ("ENTR_FISHING_POND_0_1", "SCENE_FISHING_POND", 0), + ("ENTR_FISHING_POND_0_2", "SCENE_FISHING_POND", 0), + ("ENTR_FISHING_POND_0_3", "SCENE_FISHING_POND", 0), + ("ENTR_KAKARIKO_VILLAGE_10", "SCENE_KAKARIKO_VILLAGE", 10), + ("ENTR_KAKARIKO_VILLAGE_10_1", "SCENE_KAKARIKO_VILLAGE", 10), + ("ENTR_KAKARIKO_VILLAGE_10_2", "SCENE_KAKARIKO_VILLAGE", 10), + ("ENTR_KAKARIKO_VILLAGE_10_3", "SCENE_KAKARIKO_VILLAGE", 10), + ("ENTR_INSIDE_GANONS_CASTLE_0", "SCENE_INSIDE_GANONS_CASTLE", 0), + ("ENTR_INSIDE_GANONS_CASTLE_0_1", "SCENE_INSIDE_GANONS_CASTLE", 0), + ("ENTR_INSIDE_GANONS_CASTLE_0_2", "SCENE_INSIDE_GANONS_CASTLE", 0), + ("ENTR_INSIDE_GANONS_CASTLE_0_3", "SCENE_INSIDE_GANONS_CASTLE", 0), + ("ENTR_INSIDE_GANONS_CASTLE_0_4", "SCENE_INSIDE_GANONS_CASTLE", 0), + ("ENTR_INSIDE_GANONS_CASTLE_0_5", "SCENE_INSIDE_GANONS_CASTLE", 0), + ("ENTR_INSIDE_GANONS_CASTLE_0_6", "SCENE_INSIDE_GANONS_CASTLE", 0), + ("ENTR_INSIDE_GANONS_CASTLE_0_7", "SCENE_INSIDE_GANONS_CASTLE", 0), + ("ENTR_INSIDE_GANONS_CASTLE_0_8", "SCENE_INSIDE_GANONS_CASTLE", 0), + ("ENTR_INSIDE_GANONS_CASTLE_0_9", "SCENE_INSIDE_GANONS_CASTLE", 0), + ("ENTR_INSIDE_GANONS_CASTLE_0_10", "SCENE_INSIDE_GANONS_CASTLE", 0), + ("ENTR_TEMPLE_OF_TIME_EXTERIOR_DAY_1", "SCENE_TEMPLE_OF_TIME_EXTERIOR_DAY", 1), + ("ENTR_TEMPLE_OF_TIME_EXTERIOR_NIGHT_1_1", "SCENE_TEMPLE_OF_TIME_EXTERIOR_NIGHT", 1), + ("ENTR_TEMPLE_OF_TIME_EXTERIOR_RUINS_1_2", "SCENE_TEMPLE_OF_TIME_EXTERIOR_RUINS", 1), + ("ENTR_TEMPLE_OF_TIME_EXTERIOR_RUINS_1_3", "SCENE_TEMPLE_OF_TIME_EXTERIOR_RUINS", 1), + ("ENTR_HYRULE_FIELD_15", "SCENE_HYRULE_FIELD", 15), + ("ENTR_HYRULE_FIELD_15_1", "SCENE_HYRULE_FIELD", 15), + ("ENTR_HYRULE_FIELD_15_2", "SCENE_HYRULE_FIELD", 15), + ("ENTR_HYRULE_FIELD_15_3", "SCENE_HYRULE_FIELD", 15), + ("ENTR_DEATH_MOUNTAIN_TRAIL_5", "SCENE_DEATH_MOUNTAIN_TRAIL", 5), + ("ENTR_DEATH_MOUNTAIN_TRAIL_5_1", "SCENE_DEATH_MOUNTAIN_TRAIL", 5), + ("ENTR_DEATH_MOUNTAIN_TRAIL_5_2", "SCENE_DEATH_MOUNTAIN_TRAIL", 5), + ("ENTR_DEATH_MOUNTAIN_TRAIL_5_3", "SCENE_DEATH_MOUNTAIN_TRAIL", 5), + ("ENTR_HYRULE_CASTLE_4", "SCENE_HYRULE_CASTLE", 4), + ("ENTR_HYRULE_CASTLE_4_1", "SCENE_HYRULE_CASTLE", 4), + ("ENTR_OUTSIDE_GANONS_CASTLE_4_2", "SCENE_OUTSIDE_GANONS_CASTLE", 4), + ("ENTR_OUTSIDE_GANONS_CASTLE_4_3", "SCENE_OUTSIDE_GANONS_CASTLE", 4), + ("ENTR_DEATH_MOUNTAIN_CRATER_3", "SCENE_DEATH_MOUNTAIN_CRATER", 3), + ("ENTR_DEATH_MOUNTAIN_CRATER_3_1", "SCENE_DEATH_MOUNTAIN_CRATER", 3), + ("ENTR_DEATH_MOUNTAIN_CRATER_3_2", "SCENE_DEATH_MOUNTAIN_CRATER", 3), + ("ENTR_DEATH_MOUNTAIN_CRATER_3_3", "SCENE_DEATH_MOUNTAIN_CRATER", 3), + ("ENTR_THIEVES_HIDEOUT_0", "SCENE_THIEVES_HIDEOUT", 0), + ("ENTR_THIEVES_HIDEOUT_0_1", "SCENE_THIEVES_HIDEOUT", 0), + ("ENTR_THIEVES_HIDEOUT_0_2", "SCENE_THIEVES_HIDEOUT", 0), + ("ENTR_THIEVES_HIDEOUT_0_3", "SCENE_THIEVES_HIDEOUT", 0), + ("ENTR_THIEVES_HIDEOUT_1", "SCENE_THIEVES_HIDEOUT", 1), + ("ENTR_THIEVES_HIDEOUT_1_1", "SCENE_THIEVES_HIDEOUT", 1), + ("ENTR_THIEVES_HIDEOUT_1_2", "SCENE_THIEVES_HIDEOUT", 1), + ("ENTR_THIEVES_HIDEOUT_1_3", "SCENE_THIEVES_HIDEOUT", 1), + ("ENTR_THIEVES_HIDEOUT_2", "SCENE_THIEVES_HIDEOUT", 2), + ("ENTR_THIEVES_HIDEOUT_2_1", "SCENE_THIEVES_HIDEOUT", 2), + ("ENTR_THIEVES_HIDEOUT_2_2", "SCENE_THIEVES_HIDEOUT", 2), + ("ENTR_THIEVES_HIDEOUT_2_3", "SCENE_THIEVES_HIDEOUT", 2), + ("ENTR_THIEVES_HIDEOUT_3", "SCENE_THIEVES_HIDEOUT", 3), + ("ENTR_THIEVES_HIDEOUT_3_1", "SCENE_THIEVES_HIDEOUT", 3), + ("ENTR_THIEVES_HIDEOUT_3_2", "SCENE_THIEVES_HIDEOUT", 3), + ("ENTR_THIEVES_HIDEOUT_3_3", "SCENE_THIEVES_HIDEOUT", 3), + ("ENTR_THIEVES_HIDEOUT_4", "SCENE_THIEVES_HIDEOUT", 4), + ("ENTR_THIEVES_HIDEOUT_4_1", "SCENE_THIEVES_HIDEOUT", 4), + ("ENTR_THIEVES_HIDEOUT_4_2", "SCENE_THIEVES_HIDEOUT", 4), + ("ENTR_THIEVES_HIDEOUT_4_3", "SCENE_THIEVES_HIDEOUT", 4), + ("ENTR_THIEVES_HIDEOUT_5", "SCENE_THIEVES_HIDEOUT", 5), + ("ENTR_THIEVES_HIDEOUT_5_1", "SCENE_THIEVES_HIDEOUT", 5), + ("ENTR_THIEVES_HIDEOUT_5_2", "SCENE_THIEVES_HIDEOUT", 5), + ("ENTR_THIEVES_HIDEOUT_5_3", "SCENE_THIEVES_HIDEOUT", 5), + ("ENTR_THIEVES_HIDEOUT_6", "SCENE_THIEVES_HIDEOUT", 6), + ("ENTR_THIEVES_HIDEOUT_6_1", "SCENE_THIEVES_HIDEOUT", 6), + ("ENTR_THIEVES_HIDEOUT_6_2", "SCENE_THIEVES_HIDEOUT", 6), + ("ENTR_THIEVES_HIDEOUT_6_3", "SCENE_THIEVES_HIDEOUT", 6), + ("ENTR_THIEVES_HIDEOUT_7", "SCENE_THIEVES_HIDEOUT", 7), + ("ENTR_THIEVES_HIDEOUT_7_1", "SCENE_THIEVES_HIDEOUT", 7), + ("ENTR_THIEVES_HIDEOUT_7_2", "SCENE_THIEVES_HIDEOUT", 7), + ("ENTR_THIEVES_HIDEOUT_7_3", "SCENE_THIEVES_HIDEOUT", 7), + ("ENTR_THIEVES_HIDEOUT_8", "SCENE_THIEVES_HIDEOUT", 8), + ("ENTR_THIEVES_HIDEOUT_8_1", "SCENE_THIEVES_HIDEOUT", 8), + ("ENTR_THIEVES_HIDEOUT_8_2", "SCENE_THIEVES_HIDEOUT", 8), + ("ENTR_THIEVES_HIDEOUT_8_3", "SCENE_THIEVES_HIDEOUT", 8), + ("ENTR_THIEVES_HIDEOUT_9", "SCENE_THIEVES_HIDEOUT", 9), + ("ENTR_THIEVES_HIDEOUT_9_1", "SCENE_THIEVES_HIDEOUT", 9), + ("ENTR_THIEVES_HIDEOUT_9_2", "SCENE_THIEVES_HIDEOUT", 9), + ("ENTR_THIEVES_HIDEOUT_9_3", "SCENE_THIEVES_HIDEOUT", 9), + ("ENTR_THIEVES_HIDEOUT_10", "SCENE_THIEVES_HIDEOUT", 10), + ("ENTR_THIEVES_HIDEOUT_10_1", "SCENE_THIEVES_HIDEOUT", 10), + ("ENTR_THIEVES_HIDEOUT_10_2", "SCENE_THIEVES_HIDEOUT", 10), + ("ENTR_THIEVES_HIDEOUT_10_3", "SCENE_THIEVES_HIDEOUT", 10), + ("ENTR_THIEVES_HIDEOUT_11", "SCENE_THIEVES_HIDEOUT", 11), + ("ENTR_THIEVES_HIDEOUT_11_1", "SCENE_THIEVES_HIDEOUT", 11), + ("ENTR_THIEVES_HIDEOUT_11_2", "SCENE_THIEVES_HIDEOUT", 11), + ("ENTR_THIEVES_HIDEOUT_11_3", "SCENE_THIEVES_HIDEOUT", 11), + ("ENTR_GANONS_TOWER_COLLAPSE_INTERIOR_7", "SCENE_GANONS_TOWER_COLLAPSE_INTERIOR", 7), + ("ENTR_GANONS_TOWER_COLLAPSE_INTERIOR_7_1", "SCENE_GANONS_TOWER_COLLAPSE_INTERIOR", 7), + ("ENTR_GANONS_TOWER_COLLAPSE_INTERIOR_7_2", "SCENE_GANONS_TOWER_COLLAPSE_INTERIOR", 7), + ("ENTR_GANONS_TOWER_COLLAPSE_INTERIOR_7_3", "SCENE_GANONS_TOWER_COLLAPSE_INTERIOR", 7), + ("ENTR_GANONS_TOWER_COLLAPSE_EXTERIOR_1", "SCENE_GANONS_TOWER_COLLAPSE_EXTERIOR", 1), + ("ENTR_GANONS_TOWER_COLLAPSE_EXTERIOR_1_1", "SCENE_GANONS_TOWER_COLLAPSE_EXTERIOR", 1), + ("ENTR_GANONS_TOWER_COLLAPSE_EXTERIOR_1_2", "SCENE_GANONS_TOWER_COLLAPSE_EXTERIOR", 1), + ("ENTR_GANONS_TOWER_COLLAPSE_EXTERIOR_1_3", "SCENE_GANONS_TOWER_COLLAPSE_EXTERIOR", 1), + ("ENTR_GREAT_FAIRYS_FOUNTAIN_MAGIC_1", "SCENE_GREAT_FAIRYS_FOUNTAIN_MAGIC", 1), + ("ENTR_GREAT_FAIRYS_FOUNTAIN_MAGIC_1_1", "SCENE_GREAT_FAIRYS_FOUNTAIN_MAGIC", 1), + ("ENTR_GREAT_FAIRYS_FOUNTAIN_MAGIC_1_2", "SCENE_GREAT_FAIRYS_FOUNTAIN_MAGIC", 1), + ("ENTR_GREAT_FAIRYS_FOUNTAIN_MAGIC_1_3", "SCENE_GREAT_FAIRYS_FOUNTAIN_MAGIC", 1), + ("ENTR_GREAT_FAIRYS_FOUNTAIN_MAGIC_2", "SCENE_GREAT_FAIRYS_FOUNTAIN_MAGIC", 2), + ("ENTR_GREAT_FAIRYS_FOUNTAIN_MAGIC_2_1", "SCENE_GREAT_FAIRYS_FOUNTAIN_MAGIC", 2), + ("ENTR_GREAT_FAIRYS_FOUNTAIN_MAGIC_2_2", "SCENE_GREAT_FAIRYS_FOUNTAIN_MAGIC", 2), + ("ENTR_GREAT_FAIRYS_FOUNTAIN_MAGIC_2_3", "SCENE_GREAT_FAIRYS_FOUNTAIN_MAGIC", 2), + ("ENTR_LOST_WOODS_4", "SCENE_LOST_WOODS", 4), + ("ENTR_LOST_WOODS_4_1", "SCENE_LOST_WOODS", 4), + ("ENTR_LOST_WOODS_4_2", "SCENE_LOST_WOODS", 4), + ("ENTR_LOST_WOODS_4_3", "SCENE_LOST_WOODS", 4), + ("ENTR_LON_LON_RANCH_6", "SCENE_LON_LON_RANCH", 6), + ("ENTR_LON_LON_RANCH_6_1", "SCENE_LON_LON_RANCH", 6), + ("ENTR_LON_LON_RANCH_6_2", "SCENE_LON_LON_RANCH", 6), + ("ENTR_LON_LON_RANCH_6_3", "SCENE_LON_LON_RANCH", 6), + ("ENTR_LON_LON_RANCH_7", "SCENE_LON_LON_RANCH", 7), + ("ENTR_LON_LON_RANCH_7_1", "SCENE_LON_LON_RANCH", 7), + ("ENTR_LON_LON_RANCH_7_2", "SCENE_LON_LON_RANCH", 7), + ("ENTR_LON_LON_RANCH_7_3", "SCENE_LON_LON_RANCH", 7), + ("ENTR_LOST_WOODS_5", "SCENE_LOST_WOODS", 5), + ("ENTR_LOST_WOODS_5_1", "SCENE_LOST_WOODS", 5), + ("ENTR_LOST_WOODS_5_2", "SCENE_LOST_WOODS", 5), + ("ENTR_LOST_WOODS_5_3", "SCENE_LOST_WOODS", 5), + ("ENTR_LOST_WOODS_6", "SCENE_LOST_WOODS", 6), + ("ENTR_LOST_WOODS_6_1", "SCENE_LOST_WOODS", 6), + ("ENTR_LOST_WOODS_6_2", "SCENE_LOST_WOODS", 6), + ("ENTR_LOST_WOODS_6_3", "SCENE_LOST_WOODS", 6), + ("ENTR_LOST_WOODS_7", "SCENE_LOST_WOODS", 7), + ("ENTR_LOST_WOODS_7_1", "SCENE_LOST_WOODS", 7), + ("ENTR_LOST_WOODS_7_2", "SCENE_LOST_WOODS", 7), + ("ENTR_LOST_WOODS_7_3", "SCENE_LOST_WOODS", 7), + ("ENTR_LOST_WOODS_8", "SCENE_LOST_WOODS", 8), + ("ENTR_LOST_WOODS_8_1", "SCENE_LOST_WOODS", 8), + ("ENTR_LOST_WOODS_8_2", "SCENE_LOST_WOODS", 8), + ("ENTR_LOST_WOODS_8_3", "SCENE_LOST_WOODS", 8), + ("ENTR_GORON_CITY_3", "SCENE_GORON_CITY", 3), + ("ENTR_GORON_CITY_3_1", "SCENE_GORON_CITY", 3), + ("ENTR_GORON_CITY_3_2", "SCENE_GORON_CITY", 3), + ("ENTR_GORON_CITY_3_3", "SCENE_GORON_CITY", 3), + ("ENTR_LAKE_HYLIA_5", "SCENE_LAKE_HYLIA", 5), + ("ENTR_LAKE_HYLIA_5_1", "SCENE_LAKE_HYLIA", 5), + ("ENTR_LAKE_HYLIA_5_2", "SCENE_LAKE_HYLIA", 5), + ("ENTR_LAKE_HYLIA_5_3", "SCENE_LAKE_HYLIA", 5), + ("ENTR_SHADOW_TEMPLE_3", "SCENE_SHADOW_TEMPLE", 3), + ("ENTR_SHADOW_TEMPLE_3_1", "SCENE_SHADOW_TEMPLE", 3), + ("ENTR_SHADOW_TEMPLE_3_2", "SCENE_SHADOW_TEMPLE", 3), + ("ENTR_SHADOW_TEMPLE_3_3", "SCENE_SHADOW_TEMPLE", 3), + ("ENTR_KAKARIKO_VILLAGE_11", "SCENE_KAKARIKO_VILLAGE", 11), + ("ENTR_KAKARIKO_VILLAGE_11_1", "SCENE_KAKARIKO_VILLAGE", 11), + ("ENTR_KAKARIKO_VILLAGE_11_2", "SCENE_KAKARIKO_VILLAGE", 11), + ("ENTR_KAKARIKO_VILLAGE_11_3", "SCENE_KAKARIKO_VILLAGE", 11), + ("ENTR_GREAT_FAIRYS_FOUNTAIN_MAGIC_3", "SCENE_GREAT_FAIRYS_FOUNTAIN_MAGIC", 3), + ("ENTR_GREAT_FAIRYS_FOUNTAIN_MAGIC_3_1", "SCENE_GREAT_FAIRYS_FOUNTAIN_MAGIC", 3), + ("ENTR_GREAT_FAIRYS_FOUNTAIN_MAGIC_3_2", "SCENE_GREAT_FAIRYS_FOUNTAIN_MAGIC", 3), + ("ENTR_GREAT_FAIRYS_FOUNTAIN_MAGIC_3_3", "SCENE_GREAT_FAIRYS_FOUNTAIN_MAGIC", 3), + ("ENTR_DEATH_MOUNTAIN_CRATER_4", "SCENE_DEATH_MOUNTAIN_CRATER", 4), + ("ENTR_DEATH_MOUNTAIN_CRATER_4_1", "SCENE_DEATH_MOUNTAIN_CRATER", 4), + ("ENTR_DEATH_MOUNTAIN_CRATER_4_2", "SCENE_DEATH_MOUNTAIN_CRATER", 4), + ("ENTR_DEATH_MOUNTAIN_CRATER_4_3", "SCENE_DEATH_MOUNTAIN_CRATER", 4), + ("ENTR_HYRULE_CASTLE_3", "SCENE_HYRULE_CASTLE", 3), + ("ENTR_HYRULE_CASTLE_3_1", "SCENE_HYRULE_CASTLE", 3), + ("ENTR_OUTSIDE_GANONS_CASTLE_3_2", "SCENE_OUTSIDE_GANONS_CASTLE", 3), + ("ENTR_OUTSIDE_GANONS_CASTLE_3_3", "SCENE_OUTSIDE_GANONS_CASTLE", 3), + ("ENTR_HYRULE_CASTLE_3_4", "SCENE_HYRULE_CASTLE", 3), + ("ENTR_KAKARIKO_VILLAGE_12", "SCENE_KAKARIKO_VILLAGE", 12), + ("ENTR_KAKARIKO_VILLAGE_12_1", "SCENE_KAKARIKO_VILLAGE", 12), + ("ENTR_KAKARIKO_VILLAGE_12_2", "SCENE_KAKARIKO_VILLAGE", 12), + ("ENTR_KAKARIKO_VILLAGE_12_3", "SCENE_KAKARIKO_VILLAGE", 12), + ("ENTR_WINDMILL_AND_DAMPES_GRAVE_2", "SCENE_WINDMILL_AND_DAMPES_GRAVE", 2), + ("ENTR_WINDMILL_AND_DAMPES_GRAVE_2_1", "SCENE_WINDMILL_AND_DAMPES_GRAVE", 2), + ("ENTR_WINDMILL_AND_DAMPES_GRAVE_2_2", "SCENE_WINDMILL_AND_DAMPES_GRAVE", 2), + ("ENTR_WINDMILL_AND_DAMPES_GRAVE_2_3", "SCENE_WINDMILL_AND_DAMPES_GRAVE", 2), + ("ENTR_BOMBCHU_BOWLING_ALLEY_0", "SCENE_BOMBCHU_BOWLING_ALLEY", 0), + ("ENTR_BOMBCHU_BOWLING_ALLEY_0_1", "SCENE_BOMBCHU_BOWLING_ALLEY", 0), + ("ENTR_BOMBCHU_BOWLING_ALLEY_0_2", "SCENE_BOMBCHU_BOWLING_ALLEY", 0), + ("ENTR_BOMBCHU_BOWLING_ALLEY_0_3", "SCENE_BOMBCHU_BOWLING_ALLEY", 0), + ("ENTR_GRAVEYARD_6", "SCENE_GRAVEYARD", 6), + ("ENTR_GRAVEYARD_6_1", "SCENE_GRAVEYARD", 6), + ("ENTR_GRAVEYARD_6_2", "SCENE_GRAVEYARD", 6), + ("ENTR_GRAVEYARD_6_3", "SCENE_GRAVEYARD", 6), + ("ENTR_HYRULE_FIELD_16", "SCENE_HYRULE_FIELD", 16), + ("ENTR_HYRULE_FIELD_16_1", "SCENE_HYRULE_FIELD", 16), + ("ENTR_HYRULE_FIELD_16_2", "SCENE_HYRULE_FIELD", 16), + ("ENTR_HYRULE_FIELD_16_3", "SCENE_HYRULE_FIELD", 16), + ("ENTR_KAKARIKO_VILLAGE_13", "SCENE_KAKARIKO_VILLAGE", 13), + ("ENTR_KAKARIKO_VILLAGE_13_1", "SCENE_KAKARIKO_VILLAGE", 13), + ("ENTR_KAKARIKO_VILLAGE_13_2", "SCENE_KAKARIKO_VILLAGE", 13), + ("ENTR_KAKARIKO_VILLAGE_13_3", "SCENE_KAKARIKO_VILLAGE", 13), + ("ENTR_GANON_BOSS_0", "SCENE_GANON_BOSS", 0), + ("ENTR_GANON_BOSS_0_1", "SCENE_GANON_BOSS", 0), + ("ENTR_GANON_BOSS_0_2", "SCENE_GANON_BOSS", 0), + ("ENTR_GANON_BOSS_0_3", "SCENE_GANON_BOSS", 0), + ("ENTR_GANON_BOSS_0_4", "SCENE_GANON_BOSS", 0), + ("ENTR_GANONS_TOWER_COLLAPSE_EXTERIOR_6", "SCENE_GANONS_TOWER_COLLAPSE_EXTERIOR", 6), + ("ENTR_GANONS_TOWER_COLLAPSE_EXTERIOR_6_1", "SCENE_GANONS_TOWER_COLLAPSE_EXTERIOR", 6), + ("ENTR_GANONS_TOWER_COLLAPSE_EXTERIOR_6_2", "SCENE_GANONS_TOWER_COLLAPSE_EXTERIOR", 6), + ("ENTR_GANONS_TOWER_COLLAPSE_EXTERIOR_6_3", "SCENE_GANONS_TOWER_COLLAPSE_EXTERIOR", 6), + ("ENTR_BESITU_0", "SCENE_BESITU", 0), + ("ENTR_BESITU_0_1", "SCENE_BESITU", 0), + ("ENTR_BESITU_0_2", "SCENE_BESITU", 0), + ("ENTR_BESITU_0_3", "SCENE_BESITU", 0), + ("ENTR_GANONS_TOWER_COLLAPSE_EXTERIOR_7", "SCENE_GANONS_TOWER_COLLAPSE_EXTERIOR", 7), + ("ENTR_GANONS_TOWER_COLLAPSE_EXTERIOR_7_1", "SCENE_GANONS_TOWER_COLLAPSE_EXTERIOR", 7), + ("ENTR_GANONS_TOWER_COLLAPSE_EXTERIOR_7_2", "SCENE_GANONS_TOWER_COLLAPSE_EXTERIOR", 7), + ("ENTR_GANONS_TOWER_COLLAPSE_EXTERIOR_7_3", "SCENE_GANONS_TOWER_COLLAPSE_EXTERIOR", 7), + ("ENTR_BOMBCHU_SHOP_1", "SCENE_BOMBCHU_SHOP", 1), + ("ENTR_BOMBCHU_SHOP_1_1", "SCENE_BOMBCHU_SHOP", 1), + ("ENTR_BOMBCHU_SHOP_1_2", "SCENE_BOMBCHU_SHOP", 1), + ("ENTR_BOMBCHU_SHOP_1_3", "SCENE_BOMBCHU_SHOP", 1), + ("ENTR_BAZAAR_1", "SCENE_BAZAAR", 1), + ("ENTR_BAZAAR_1_1", "SCENE_BAZAAR", 1), + ("ENTR_BAZAAR_1_2", "SCENE_BAZAAR", 1), + ("ENTR_BAZAAR_1_3", "SCENE_BAZAAR", 1), + ("ENTR_HAPPY_MASK_SHOP_0", "SCENE_HAPPY_MASK_SHOP", 0), + ("ENTR_HAPPY_MASK_SHOP_0_1", "SCENE_HAPPY_MASK_SHOP", 0), + ("ENTR_HAPPY_MASK_SHOP_0_2", "SCENE_HAPPY_MASK_SHOP", 0), + ("ENTR_HAPPY_MASK_SHOP_0_3", "SCENE_HAPPY_MASK_SHOP", 0), + ("ENTR_INSIDE_GANONS_CASTLE_1", "SCENE_INSIDE_GANONS_CASTLE", 1), + ("ENTR_INSIDE_GANONS_CASTLE_1_1", "SCENE_INSIDE_GANONS_CASTLE", 1), + ("ENTR_INSIDE_GANONS_CASTLE_1_2", "SCENE_INSIDE_GANONS_CASTLE", 1), + ("ENTR_INSIDE_GANONS_CASTLE_1_3", "SCENE_INSIDE_GANONS_CASTLE", 1), + ("ENTR_INSIDE_GANONS_CASTLE_2", "SCENE_INSIDE_GANONS_CASTLE", 2), + ("ENTR_INSIDE_GANONS_CASTLE_2_1", "SCENE_INSIDE_GANONS_CASTLE", 2), + ("ENTR_INSIDE_GANONS_CASTLE_2_2", "SCENE_INSIDE_GANONS_CASTLE", 2), + ("ENTR_INSIDE_GANONS_CASTLE_2_3", "SCENE_INSIDE_GANONS_CASTLE", 2), + ("ENTR_INSIDE_GANONS_CASTLE_3", "SCENE_INSIDE_GANONS_CASTLE", 3), + ("ENTR_INSIDE_GANONS_CASTLE_3_1", "SCENE_INSIDE_GANONS_CASTLE", 3), + ("ENTR_INSIDE_GANONS_CASTLE_3_2", "SCENE_INSIDE_GANONS_CASTLE", 3), + ("ENTR_INSIDE_GANONS_CASTLE_3_3", "SCENE_INSIDE_GANONS_CASTLE", 3), + ("ENTR_INSIDE_GANONS_CASTLE_4", "SCENE_INSIDE_GANONS_CASTLE", 4), + ("ENTR_INSIDE_GANONS_CASTLE_4_1", "SCENE_INSIDE_GANONS_CASTLE", 4), + ("ENTR_INSIDE_GANONS_CASTLE_4_2", "SCENE_INSIDE_GANONS_CASTLE", 4), + ("ENTR_INSIDE_GANONS_CASTLE_4_3", "SCENE_INSIDE_GANONS_CASTLE", 4), + ("ENTR_INSIDE_GANONS_CASTLE_5", "SCENE_INSIDE_GANONS_CASTLE", 5), + ("ENTR_INSIDE_GANONS_CASTLE_5_1", "SCENE_INSIDE_GANONS_CASTLE", 5), + ("ENTR_INSIDE_GANONS_CASTLE_5_2", "SCENE_INSIDE_GANONS_CASTLE", 5), + ("ENTR_INSIDE_GANONS_CASTLE_5_3", "SCENE_INSIDE_GANONS_CASTLE", 5), + ("ENTR_INSIDE_GANONS_CASTLE_6", "SCENE_INSIDE_GANONS_CASTLE", 6), + ("ENTR_INSIDE_GANONS_CASTLE_6_1", "SCENE_INSIDE_GANONS_CASTLE", 6), + ("ENTR_INSIDE_GANONS_CASTLE_6_2", "SCENE_INSIDE_GANONS_CASTLE", 6), + ("ENTR_INSIDE_GANONS_CASTLE_6_3", "SCENE_INSIDE_GANONS_CASTLE", 6), + ("ENTR_INSIDE_GANONS_CASTLE_7", "SCENE_INSIDE_GANONS_CASTLE", 7), + ("ENTR_INSIDE_GANONS_CASTLE_7_1", "SCENE_INSIDE_GANONS_CASTLE", 7), + ("ENTR_INSIDE_GANONS_CASTLE_7_2", "SCENE_INSIDE_GANONS_CASTLE", 7), + ("ENTR_INSIDE_GANONS_CASTLE_7_3", "SCENE_INSIDE_GANONS_CASTLE", 7), + ("ENTR_HOUSE_OF_SKULLTULA_0", "SCENE_HOUSE_OF_SKULLTULA", 0), + ("ENTR_HOUSE_OF_SKULLTULA_0_1", "SCENE_HOUSE_OF_SKULLTULA", 0), + ("ENTR_HOUSE_OF_SKULLTULA_0_2", "SCENE_HOUSE_OF_SKULLTULA", 0), + ("ENTR_HOUSE_OF_SKULLTULA_0_3", "SCENE_HOUSE_OF_SKULLTULA", 0), + ("ENTR_KAKARIKO_VILLAGE_14", "SCENE_KAKARIKO_VILLAGE", 14), + ("ENTR_KAKARIKO_VILLAGE_14_1", "SCENE_KAKARIKO_VILLAGE", 14), + ("ENTR_KAKARIKO_VILLAGE_14_2", "SCENE_KAKARIKO_VILLAGE", 14), + ("ENTR_KAKARIKO_VILLAGE_14_3", "SCENE_KAKARIKO_VILLAGE", 14), + ("ENTR_LON_LON_RANCH_8", "SCENE_LON_LON_RANCH", 8), + ("ENTR_LON_LON_RANCH_8_1", "SCENE_LON_LON_RANCH", 8), + ("ENTR_LON_LON_RANCH_8_2", "SCENE_LON_LON_RANCH", 8), + ("ENTR_LON_LON_RANCH_8_3", "SCENE_LON_LON_RANCH", 8), + ("ENTR_LON_LON_RANCH_9", "SCENE_LON_LON_RANCH", 9), + ("ENTR_LON_LON_RANCH_9_1", "SCENE_LON_LON_RANCH", 9), + ("ENTR_LON_LON_RANCH_9_2", "SCENE_LON_LON_RANCH", 9), + ("ENTR_LON_LON_RANCH_9_3", "SCENE_LON_LON_RANCH", 9), + ("ENTR_LAKE_HYLIA_7", "SCENE_LAKE_HYLIA", 7), + ("ENTR_LAKE_HYLIA_7_1", "SCENE_LAKE_HYLIA", 7), + ("ENTR_LAKE_HYLIA_7_2", "SCENE_LAKE_HYLIA", 7), + ("ENTR_LAKE_HYLIA_7_3", "SCENE_LAKE_HYLIA", 7), + ("ENTR_DEATH_MOUNTAIN_CRATER_5", "SCENE_DEATH_MOUNTAIN_CRATER", 5), + ("ENTR_DEATH_MOUNTAIN_CRATER_5_1", "SCENE_DEATH_MOUNTAIN_CRATER", 5), + ("ENTR_DEATH_MOUNTAIN_CRATER_5_2", "SCENE_DEATH_MOUNTAIN_CRATER", 5), + ("ENTR_DEATH_MOUNTAIN_CRATER_5_3", "SCENE_DEATH_MOUNTAIN_CRATER", 5), + ("ENTR_GRAVEYARD_7", "SCENE_GRAVEYARD", 7), + ("ENTR_GRAVEYARD_7_1", "SCENE_GRAVEYARD", 7), + ("ENTR_GRAVEYARD_7_2", "SCENE_GRAVEYARD", 7), + ("ENTR_GRAVEYARD_7_3", "SCENE_GRAVEYARD", 7), + ("ENTR_INSIDE_GANONS_CASTLE_COLLAPSE_0", "SCENE_INSIDE_GANONS_CASTLE_COLLAPSE", 0), + ("ENTR_INSIDE_GANONS_CASTLE_COLLAPSE_0_1", "SCENE_INSIDE_GANONS_CASTLE_COLLAPSE", 0), + ("ENTR_INSIDE_GANONS_CASTLE_COLLAPSE_0_2", "SCENE_INSIDE_GANONS_CASTLE_COLLAPSE", 0), + ("ENTR_INSIDE_GANONS_CASTLE_COLLAPSE_0_3", "SCENE_INSIDE_GANONS_CASTLE_COLLAPSE", 0), + ("ENTR_THIEVES_HIDEOUT_12", "SCENE_THIEVES_HIDEOUT", 12), + ("ENTR_THIEVES_HIDEOUT_12_1", "SCENE_THIEVES_HIDEOUT", 12), + ("ENTR_THIEVES_HIDEOUT_12_2", "SCENE_THIEVES_HIDEOUT", 12), + ("ENTR_THIEVES_HIDEOUT_12_3", "SCENE_THIEVES_HIDEOUT", 12), + ("ENTR_ROYAL_FAMILYS_TOMB_1", "SCENE_ROYAL_FAMILYS_TOMB", 1), + ("ENTR_ROYAL_FAMILYS_TOMB_1_1", "SCENE_ROYAL_FAMILYS_TOMB", 1), + ("ENTR_ROYAL_FAMILYS_TOMB_1_2", "SCENE_ROYAL_FAMILYS_TOMB", 1), + ("ENTR_ROYAL_FAMILYS_TOMB_1_3", "SCENE_ROYAL_FAMILYS_TOMB", 1), + ("ENTR_GREAT_FAIRYS_FOUNTAIN_SPELLS_1", "SCENE_GREAT_FAIRYS_FOUNTAIN_SPELLS", 1), + ("ENTR_GREAT_FAIRYS_FOUNTAIN_SPELLS_1_1", "SCENE_GREAT_FAIRYS_FOUNTAIN_SPELLS", 1), + ("ENTR_GREAT_FAIRYS_FOUNTAIN_SPELLS_1_2", "SCENE_GREAT_FAIRYS_FOUNTAIN_SPELLS", 1), + ("ENTR_GREAT_FAIRYS_FOUNTAIN_SPELLS_1_3", "SCENE_GREAT_FAIRYS_FOUNTAIN_SPELLS", 1), + ("ENTR_DESERT_COLOSSUS_7", "SCENE_DESERT_COLOSSUS", 7), + ("ENTR_DESERT_COLOSSUS_7_1", "SCENE_DESERT_COLOSSUS", 7), + ("ENTR_DESERT_COLOSSUS_7_2", "SCENE_DESERT_COLOSSUS", 7), + ("ENTR_DESERT_COLOSSUS_7_3", "SCENE_DESERT_COLOSSUS", 7), + ("ENTR_GRAVEYARD_8", "SCENE_GRAVEYARD", 8), + ("ENTR_GRAVEYARD_8_1", "SCENE_GRAVEYARD", 8), + ("ENTR_GRAVEYARD_8_2", "SCENE_GRAVEYARD", 8), + ("ENTR_GRAVEYARD_8_3", "SCENE_GRAVEYARD", 8), + ("ENTR_FOREST_TEMPLE_2", "SCENE_FOREST_TEMPLE", 2), + ("ENTR_FOREST_TEMPLE_2_1", "SCENE_FOREST_TEMPLE", 2), + ("ENTR_FOREST_TEMPLE_2_2", "SCENE_FOREST_TEMPLE", 2), + ("ENTR_FOREST_TEMPLE_2_3", "SCENE_FOREST_TEMPLE", 2), + ("ENTR_GREAT_FAIRYS_FOUNTAIN_SPELLS_2", "SCENE_GREAT_FAIRYS_FOUNTAIN_SPELLS", 2), + ("ENTR_GREAT_FAIRYS_FOUNTAIN_SPELLS_2_1", "SCENE_GREAT_FAIRYS_FOUNTAIN_SPELLS", 2), + ("ENTR_GREAT_FAIRYS_FOUNTAIN_SPELLS_2_2", "SCENE_GREAT_FAIRYS_FOUNTAIN_SPELLS", 2), + ("ENTR_GREAT_FAIRYS_FOUNTAIN_SPELLS_2_3", "SCENE_GREAT_FAIRYS_FOUNTAIN_SPELLS", 2), + ("ENTR_TEMPLE_OF_TIME_5", "SCENE_TEMPLE_OF_TIME", 5), + ("ENTR_TEMPLE_OF_TIME_5_1", "SCENE_TEMPLE_OF_TIME", 5), + ("ENTR_TEMPLE_OF_TIME_5_2", "SCENE_TEMPLE_OF_TIME", 5), + ("ENTR_TEMPLE_OF_TIME_5_3", "SCENE_TEMPLE_OF_TIME", 5), + ("ENTR_TEMPLE_OF_TIME_6", "SCENE_TEMPLE_OF_TIME", 6), + ("ENTR_TEMPLE_OF_TIME_6_1", "SCENE_TEMPLE_OF_TIME", 6), + ("ENTR_TEMPLE_OF_TIME_6_2", "SCENE_TEMPLE_OF_TIME", 6), + ("ENTR_TEMPLE_OF_TIME_6_3", "SCENE_TEMPLE_OF_TIME", 6), + ("ENTR_HYRULE_FIELD_17", "SCENE_HYRULE_FIELD", 17), + ("ENTR_HYRULE_FIELD_17_1", "SCENE_HYRULE_FIELD", 17), + ("ENTR_HYRULE_FIELD_17_2", "SCENE_HYRULE_FIELD", 17), + ("ENTR_HYRULE_FIELD_17_3", "SCENE_HYRULE_FIELD", 17), + ("ENTR_GROTTOS_1", "SCENE_GROTTOS", 1), + ("ENTR_GROTTOS_1_1", "SCENE_GROTTOS", 1), + ("ENTR_GROTTOS_1_2", "SCENE_GROTTOS", 1), + ("ENTR_GROTTOS_1_3", "SCENE_GROTTOS", 1), + ("ENTR_GROTTOS_2", "SCENE_GROTTOS", 2), + ("ENTR_GROTTOS_2_1", "SCENE_GROTTOS", 2), + ("ENTR_GROTTOS_2_2", "SCENE_GROTTOS", 2), + ("ENTR_GROTTOS_2_3", "SCENE_GROTTOS", 2), + ("ENTR_GROTTOS_3", "SCENE_GROTTOS", 3), + ("ENTR_GROTTOS_3_1", "SCENE_GROTTOS", 3), + ("ENTR_GROTTOS_3_2", "SCENE_GROTTOS", 3), + ("ENTR_GROTTOS_3_3", "SCENE_GROTTOS", 3), + ("ENTR_GROTTOS_4", "SCENE_GROTTOS", 4), + ("ENTR_GROTTOS_4_1", "SCENE_GROTTOS", 4), + ("ENTR_GROTTOS_4_2", "SCENE_GROTTOS", 4), + ("ENTR_GROTTOS_4_3", "SCENE_GROTTOS", 4), + ("ENTR_GROTTOS_5", "SCENE_GROTTOS", 5), + ("ENTR_GROTTOS_5_1", "SCENE_GROTTOS", 5), + ("ENTR_GROTTOS_5_2", "SCENE_GROTTOS", 5), + ("ENTR_GROTTOS_5_3", "SCENE_GROTTOS", 5), + ("ENTR_GROTTOS_6", "SCENE_GROTTOS", 6), + ("ENTR_GROTTOS_6_1", "SCENE_GROTTOS", 6), + ("ENTR_GROTTOS_6_2", "SCENE_GROTTOS", 6), + ("ENTR_GROTTOS_6_3", "SCENE_GROTTOS", 6), + ("ENTR_GROTTOS_7", "SCENE_GROTTOS", 7), + ("ENTR_GROTTOS_7_1", "SCENE_GROTTOS", 7), + ("ENTR_GROTTOS_7_2", "SCENE_GROTTOS", 7), + ("ENTR_GROTTOS_7_3", "SCENE_GROTTOS", 7), + ("ENTR_GROTTOS_8", "SCENE_GROTTOS", 8), + ("ENTR_GROTTOS_8_1", "SCENE_GROTTOS", 8), + ("ENTR_GROTTOS_8_2", "SCENE_GROTTOS", 8), + ("ENTR_GROTTOS_8_3", "SCENE_GROTTOS", 8), + ("ENTR_GROTTOS_9", "SCENE_GROTTOS", 9), + ("ENTR_GROTTOS_9_1", "SCENE_GROTTOS", 9), + ("ENTR_GROTTOS_9_2", "SCENE_GROTTOS", 9), + ("ENTR_GROTTOS_9_3", "SCENE_GROTTOS", 9), + ("ENTR_GROTTOS_10", "SCENE_GROTTOS", 10), + ("ENTR_GROTTOS_10_1", "SCENE_GROTTOS", 10), + ("ENTR_GROTTOS_10_2", "SCENE_GROTTOS", 10), + ("ENTR_GROTTOS_10_3", "SCENE_GROTTOS", 10), + ("ENTR_GROTTOS_11", "SCENE_GROTTOS", 11), + ("ENTR_GROTTOS_11_1", "SCENE_GROTTOS", 11), + ("ENTR_GROTTOS_11_2", "SCENE_GROTTOS", 11), + ("ENTR_GROTTOS_11_3", "SCENE_GROTTOS", 11), + ("ENTR_GROTTOS_12", "SCENE_GROTTOS", 12), + ("ENTR_GROTTOS_12_1", "SCENE_GROTTOS", 12), + ("ENTR_GROTTOS_12_2", "SCENE_GROTTOS", 12), + ("ENTR_GROTTOS_12_3", "SCENE_GROTTOS", 12), + ("ENTR_IMPAS_HOUSE_1", "SCENE_IMPAS_HOUSE", 1), + ("ENTR_IMPAS_HOUSE_1_1", "SCENE_IMPAS_HOUSE", 1), + ("ENTR_IMPAS_HOUSE_1_2", "SCENE_IMPAS_HOUSE", 1), + ("ENTR_IMPAS_HOUSE_1_3", "SCENE_IMPAS_HOUSE", 1), + ("ENTR_BOTTOM_OF_THE_WELL_1", "SCENE_BOTTOM_OF_THE_WELL", 1), + ("ENTR_BOTTOM_OF_THE_WELL_1_1", "SCENE_BOTTOM_OF_THE_WELL", 1), + ("ENTR_BOTTOM_OF_THE_WELL_1_2", "SCENE_BOTTOM_OF_THE_WELL", 1), + ("ENTR_BOTTOM_OF_THE_WELL_1_3", "SCENE_BOTTOM_OF_THE_WELL", 1), + ("ENTR_LON_LON_BUILDINGS_1", "SCENE_LON_LON_BUILDINGS", 1), + ("ENTR_LON_LON_BUILDINGS_1_1", "SCENE_LON_LON_BUILDINGS", 1), + ("ENTR_LON_LON_BUILDINGS_1_2", "SCENE_LON_LON_BUILDINGS", 1), + ("ENTR_LON_LON_BUILDINGS_1_3", "SCENE_LON_LON_BUILDINGS", 1), + ("ENTR_LON_LON_RANCH_10", "SCENE_LON_LON_RANCH", 10), + ("ENTR_LON_LON_RANCH_10_1", "SCENE_LON_LON_RANCH", 10), + ("ENTR_LON_LON_RANCH_10_2", "SCENE_LON_LON_RANCH", 10), + ("ENTR_LON_LON_RANCH_10_3", "SCENE_LON_LON_RANCH", 10), + ("ENTR_ICE_CAVERN_1", "SCENE_ICE_CAVERN", 1), + ("ENTR_ICE_CAVERN_1_1", "SCENE_ICE_CAVERN", 1), + ("ENTR_ICE_CAVERN_1_2", "SCENE_ICE_CAVERN", 1), + ("ENTR_ICE_CAVERN_1_3", "SCENE_ICE_CAVERN", 1), + ("ENTR_KAKARIKO_VILLAGE_15", "SCENE_KAKARIKO_VILLAGE", 15), + ("ENTR_KAKARIKO_VILLAGE_15_1", "SCENE_KAKARIKO_VILLAGE", 15), + ("ENTR_KAKARIKO_VILLAGE_15_2", "SCENE_KAKARIKO_VILLAGE", 15), + ("ENTR_KAKARIKO_VILLAGE_15_3", "SCENE_KAKARIKO_VILLAGE", 15), + ("ENTR_LOST_WOODS_9", "SCENE_LOST_WOODS", 9), + ("ENTR_LOST_WOODS_9_1", "SCENE_LOST_WOODS", 9), + ("ENTR_LOST_WOODS_9_2", "SCENE_LOST_WOODS", 9), + ("ENTR_LOST_WOODS_9_3", "SCENE_LOST_WOODS", 9), + ("ENTR_LON_LON_BUILDINGS_2", "SCENE_LON_LON_BUILDINGS", 2), + ("ENTR_LON_LON_BUILDINGS_2_1", "SCENE_LON_LON_BUILDINGS", 2), + ("ENTR_LON_LON_BUILDINGS_2_2", "SCENE_LON_LON_BUILDINGS", 2), + ("ENTR_LON_LON_BUILDINGS_2_3", "SCENE_LON_LON_BUILDINGS", 2), + ("ENTR_KOKIRI_FOREST_12", "SCENE_KOKIRI_FOREST", 12), + ("ENTR_KOKIRI_FOREST_12_1", "SCENE_KOKIRI_FOREST", 12), + ("ENTR_KOKIRI_FOREST_12_2", "SCENE_KOKIRI_FOREST", 12), + ("ENTR_KOKIRI_FOREST_12_3", "SCENE_KOKIRI_FOREST", 12), + ("ENTR_SPIRIT_TEMPLE_BOSS_2", "SCENE_SPIRIT_TEMPLE_BOSS", 2), + ("ENTR_SPIRIT_TEMPLE_BOSS_2_1", "SCENE_SPIRIT_TEMPLE_BOSS", 2), + ("ENTR_SPIRIT_TEMPLE_BOSS_2_2", "SCENE_SPIRIT_TEMPLE_BOSS", 2), + ("ENTR_SPIRIT_TEMPLE_BOSS_2_3", "SCENE_SPIRIT_TEMPLE_BOSS", 2), + ("ENTR_CASTLE_COURTYARD_ZELDA_1", "SCENE_CASTLE_COURTYARD_ZELDA", 1), + ("ENTR_CASTLE_COURTYARD_ZELDA_1_1", "SCENE_CASTLE_COURTYARD_ZELDA", 1), + ("ENTR_CASTLE_COURTYARD_ZELDA_1_2", "SCENE_CASTLE_COURTYARD_ZELDA", 1), + ("ENTR_CASTLE_COURTYARD_ZELDA_1_3", "SCENE_CASTLE_COURTYARD_ZELDA", 1), + ("ENTR_TEMPLE_OF_TIME_7", "SCENE_TEMPLE_OF_TIME", 7), + ("ENTR_TEMPLE_OF_TIME_7_1", "SCENE_TEMPLE_OF_TIME", 7), + ("ENTR_TEMPLE_OF_TIME_7_2", "SCENE_TEMPLE_OF_TIME", 7), + ("ENTR_TEMPLE_OF_TIME_7_3", "SCENE_TEMPLE_OF_TIME", 7), + ("ENTR_GERUDOS_FORTRESS_18", "SCENE_GERUDOS_FORTRESS", 18), + ("ENTR_GERUDOS_FORTRESS_18_1", "SCENE_GERUDOS_FORTRESS", 18), + ("ENTR_GERUDOS_FORTRESS_18_2", "SCENE_GERUDOS_FORTRESS", 18), + ("ENTR_GERUDOS_FORTRESS_18_3", "SCENE_GERUDOS_FORTRESS", 18), + ("ENTR_GROTTOS_13", "SCENE_GROTTOS", 13), + ("ENTR_GROTTOS_13_1", "SCENE_GROTTOS", 13), + ("ENTR_GROTTOS_13_2", "SCENE_GROTTOS", 13), + ("ENTR_GROTTOS_13_3", "SCENE_GROTTOS", 13), + ("ENTR_SACRED_FOREST_MEADOW_2", "SCENE_SACRED_FOREST_MEADOW", 2), + ("ENTR_SACRED_FOREST_MEADOW_2_1", "SCENE_SACRED_FOREST_MEADOW", 2), + ("ENTR_SACRED_FOREST_MEADOW_2_2", "SCENE_SACRED_FOREST_MEADOW", 2), + ("ENTR_SACRED_FOREST_MEADOW_2_3", "SCENE_SACRED_FOREST_MEADOW", 2), + ("ENTR_LAKE_HYLIA_8", "SCENE_LAKE_HYLIA", 8), + ("ENTR_LAKE_HYLIA_8_1", "SCENE_LAKE_HYLIA", 8), + ("ENTR_LAKE_HYLIA_8_2", "SCENE_LAKE_HYLIA", 8), + ("ENTR_LAKE_HYLIA_8_3", "SCENE_LAKE_HYLIA", 8), + ("ENTR_SACRED_FOREST_MEADOW_3", "SCENE_SACRED_FOREST_MEADOW", 3), + ("ENTR_SACRED_FOREST_MEADOW_3_1", "SCENE_SACRED_FOREST_MEADOW", 3), + ("ENTR_SACRED_FOREST_MEADOW_3_2", "SCENE_SACRED_FOREST_MEADOW", 3), + ("ENTR_SACRED_FOREST_MEADOW_3_3", "SCENE_SACRED_FOREST_MEADOW", 3), + ("ENTR_LAKE_HYLIA_9", "SCENE_LAKE_HYLIA", 9), + ("ENTR_LAKE_HYLIA_9_1", "SCENE_LAKE_HYLIA", 9), + ("ENTR_LAKE_HYLIA_9_2", "SCENE_LAKE_HYLIA", 9), + ("ENTR_LAKE_HYLIA_9_3", "SCENE_LAKE_HYLIA", 9), + ("ENTR_DESERT_COLOSSUS_8", "SCENE_DESERT_COLOSSUS", 8), + ("ENTR_DESERT_COLOSSUS_8_1", "SCENE_DESERT_COLOSSUS", 8), + ("ENTR_DESERT_COLOSSUS_8_2", "SCENE_DESERT_COLOSSUS", 8), + ("ENTR_DESERT_COLOSSUS_8_3", "SCENE_DESERT_COLOSSUS", 8), +) diff --git a/tools/assets/extract/oot64_data/misc_ids.py b/tools/assets/extract/oot64_data/misc_ids.py new file mode 100644 index 0000000000..86d15f5501 --- /dev/null +++ b/tools/assets/extract/oot64_data/misc_ids.py @@ -0,0 +1,155 @@ +# This file was made manually + +SCENE_CAM_TYPES = { + 0: "SCENE_CAM_TYPE_DEFAULT", + 0x10: "SCENE_CAM_TYPE_FIXED_SHOP_VIEWPOINT", + 0x20: "SCENE_CAM_TYPE_FIXED_TOGGLE_VIEWPOINT", + 0x30: "SCENE_CAM_TYPE_FIXED", + 0x40: "SCENE_CAM_TYPE_FIXED_MARKET", + 0x50: "SCENE_CAM_TYPE_SHOOTING_GALLERY", +} + +ROOM_BEHAVIOR_TYPE1_NAMES = { + 0: "ROOM_TYPE_NORMAL", + 1: "ROOM_TYPE_DUNGEON", + 2: "ROOM_TYPE_INDOORS", + 3: "ROOM_TYPE_3", + 4: "ROOM_TYPE_4", + 5: "ROOM_TYPE_BOSS", +} + +ROOM_BEHAVIOR_TYPE2_NAMES = { + 0: "ROOM_ENV_DEFAULT", + 1: "ROOM_ENV_COLD", + 2: "ROOM_ENV_WARM", + 3: "ROOM_ENV_HOT", + 4: "ROOM_ENV_UNK_STRETCH_1", + 5: "ROOM_ENV_UNK_STRETCH_2", + 6: "ROOM_ENV_UNK_STRETCH_3", +} + +LENS_MODES = { + 0: "LENS_MODE_SHOW_ACTORS", + 1: "LENS_MODE_HIDE_ACTORS", +} + +CAMERA_SETTING_TYPES = { + 0x00: "CAM_SET_NONE", + 0x01: "CAM_SET_NORMAL0", + 0x02: "CAM_SET_NORMAL1", + 0x03: "CAM_SET_DUNGEON0", + 0x04: "CAM_SET_DUNGEON1", + 0x05: "CAM_SET_NORMAL3", + 0x06: "CAM_SET_HORSE", + 0x07: "CAM_SET_BOSS_GOHMA", + 0x08: "CAM_SET_BOSS_DODONGO", + 0x09: "CAM_SET_BOSS_BARINADE", + 0x0A: "CAM_SET_BOSS_PHANTOM_GANON", + 0x0B: "CAM_SET_BOSS_VOLVAGIA", + 0x0C: "CAM_SET_BOSS_BONGO", + 0x0D: "CAM_SET_BOSS_MORPHA", + 0x0E: "CAM_SET_BOSS_TWINROVA_PLATFORM", + 0x0F: "CAM_SET_BOSS_TWINROVA_FLOOR", + 0x10: "CAM_SET_BOSS_GANONDORF", + 0x11: "CAM_SET_BOSS_GANON", + 0x12: "CAM_SET_TOWER_CLIMB", + 0x13: "CAM_SET_TOWER_UNUSED", + 0x14: "CAM_SET_MARKET_BALCONY", + 0x15: "CAM_SET_CHU_BOWLING", + 0x16: "CAM_SET_PIVOT_CRAWLSPACE", + 0x17: "CAM_SET_PIVOT_SHOP_BROWSING", + 0x18: "CAM_SET_PIVOT_IN_FRONT", + 0x19: "CAM_SET_PREREND_FIXED", + 0x1A: "CAM_SET_PREREND_PIVOT", + 0x1B: "CAM_SET_PREREND_SIDE_SCROLL", + 0x1C: "CAM_SET_DOOR0", + 0x1D: "CAM_SET_DOORC", + 0x1E: "CAM_SET_CRAWLSPACE", + 0x1F: "CAM_SET_START0", + 0x20: "CAM_SET_START1", + 0x21: "CAM_SET_FREE0", + 0x22: "CAM_SET_FREE2", + 0x23: "CAM_SET_PIVOT_CORNER", + 0x24: "CAM_SET_PIVOT_WATER_SURFACE", + 0x25: "CAM_SET_CS_0", + 0x26: "CAM_SET_CS_TWISTED_HALLWAY", + 0x27: "CAM_SET_FOREST_BIRDS_EYE", + 0x28: "CAM_SET_SLOW_CHEST_CS", + 0x29: "CAM_SET_ITEM_UNUSED", + 0x2A: "CAM_SET_CS_3", + 0x2B: "CAM_SET_CS_ATTENTION", + 0x2C: "CAM_SET_BEAN_GENERIC", + 0x2D: "CAM_SET_BEAN_LOST_WOODS", + 0x2E: "CAM_SET_SCENE_UNUSED", + 0x2F: "CAM_SET_SCENE_TRANSITION", + 0x30: "CAM_SET_ELEVATOR_PLATFORM", + 0x31: "CAM_SET_FIRE_STAIRCASE", + 0x32: "CAM_SET_FOREST_UNUSED", + 0x33: "CAM_SET_FOREST_DEFEAT_POE", + 0x34: "CAM_SET_BIG_OCTO", + 0x35: "CAM_SET_MEADOW_BIRDS_EYE", + 0x36: "CAM_SET_MEADOW_UNUSED", + 0x37: "CAM_SET_FIRE_BIRDS_EYE", + 0x38: "CAM_SET_TURN_AROUND", + 0x39: "CAM_SET_PIVOT_VERTICAL", + 0x3A: "CAM_SET_NORMAL2", + 0x3B: "CAM_SET_FISHING", + 0x3C: "CAM_SET_CS_C", + 0x3D: "CAM_SET_JABU_TENTACLE", + 0x3E: "CAM_SET_DUNGEON2", + 0x3F: "CAM_SET_DIRECTED_YAW", + 0x40: "CAM_SET_PIVOT_FROM_SIDE", + 0x41: "CAM_SET_NORMAL4", +} + +SKIN_LIMB_TYPES = { + 4: "SKIN_LIMB_TYPE_ANIMATED", + 11: "SKIN_LIMB_TYPE_NORMAL", +} + +ROOM_SHAPE_TYPE = { + 0: "ROOM_SHAPE_TYPE_NORMAL", + 1: "ROOM_SHAPE_TYPE_IMAGE", + 2: "ROOM_SHAPE_TYPE_CULLABLE", +} + +ROOM_SHAPE_IMAGE_AMOUNT_TYPE = { + 1: "ROOM_SHAPE_IMAGE_AMOUNT_SINGLE", + 2: "ROOM_SHAPE_IMAGE_AMOUNT_MULTI", +} + +SKYBOX_IDS = { + 0x00: "SKYBOX_NONE", + 0x01: "SKYBOX_NORMAL_SKY", + 0x02: "SKYBOX_BAZAAR", + 0x03: "SKYBOX_OVERCAST_SUNSET", + 0x04: "SKYBOX_MARKET_ADULT", + 0x05: "SKYBOX_CUTSCENE_MAP", + 0x07: "SKYBOX_HOUSE_LINK", + 0x09: "SKYBOX_MARKET_CHILD_DAY", + 0x0A: "SKYBOX_MARKET_CHILD_NIGHT", + 0x0B: "SKYBOX_HAPPY_MASK_SHOP", + 0x0C: "SKYBOX_HOUSE_KNOW_IT_ALL_BROTHERS", + 0x0E: "SKYBOX_HOUSE_OF_TWINS", + 0x0F: "SKYBOX_STABLES", + 0x10: "SKYBOX_HOUSE_KAKARIKO", + 0x11: "SKYBOX_KOKIRI_SHOP", + 0x13: "SKYBOX_GORON_SHOP", + 0x14: "SKYBOX_ZORA_SHOP", + 0x16: "SKYBOX_POTION_SHOP_KAKARIKO", + 0x17: "SKYBOX_POTION_SHOP_MARKET", + 0x18: "SKYBOX_BOMBCHU_SHOP", + 0x1A: "SKYBOX_HOUSE_RICHARD", + 0x1B: "SKYBOX_HOUSE_IMPA", + 0x1C: "SKYBOX_TENT", + 0x1D: "SKYBOX_UNSET_1D", + 0x20: "SKYBOX_HOUSE_MIDO", + 0x21: "SKYBOX_HOUSE_SARIA", + 0x22: "SKYBOX_HOUSE_ALLEY", + 0x27: "SKYBOX_UNSET_27", +} + +LIGHT_MODES = { + 0: "LIGHT_MODE_TIME", + 1: "LIGHT_MODE_SETTINGS", +} diff --git a/tools/assets/extract/oot64_data/object_ids.py b/tools/assets/extract/oot64_data/object_ids.py new file mode 100644 index 0000000000..2db79aa5c1 --- /dev/null +++ b/tools/assets/extract/oot64_data/object_ids.py @@ -0,0 +1,406 @@ +# This file was generated from ../../../..//include/tables/object_table.h + +DATA = ( + "OBJECT_INVALID", + "OBJECT_GAMEPLAY_KEEP", + "OBJECT_GAMEPLAY_FIELD_KEEP", + "OBJECT_GAMEPLAY_DANGEON_KEEP", + "OBJECT_UNSET_4", + "OBJECT_UNSET_5", + "OBJECT_HUMAN", + "OBJECT_OKUTA", + "OBJECT_CROW", + "OBJECT_POH", + "OBJECT_DY_OBJ", + "OBJECT_WALLMASTER", + "OBJECT_DODONGO", + "OBJECT_FIREFLY", + "OBJECT_BOX", + "OBJECT_FIRE", + "OBJECT_UNSET_10", + "OBJECT_UNSET_11", + "OBJECT_BUBBLE", + "OBJECT_NIW", + "OBJECT_LINK_BOY", + "OBJECT_LINK_CHILD", + "OBJECT_TITE", + "OBJECT_REEBA", + "OBJECT_PEEHAT", + "OBJECT_KINGDODONGO", + "OBJECT_HORSE", + "OBJECT_ZF", + "OBJECT_GOMA", + "OBJECT_ZL1", + "OBJECT_GOL", + "OBJECT_DODOJR", + "OBJECT_TORCH2", + "OBJECT_BL", + "OBJECT_TP", + "OBJECT_OA1", + "OBJECT_ST", + "OBJECT_BW", + "OBJECT_EI", + "OBJECT_HORSE_NORMAL", + "OBJECT_OB1", + "OBJECT_O_ANIME", + "OBJECT_SPOT04_OBJECTS", + "OBJECT_DDAN_OBJECTS", + "OBJECT_HIDAN_OBJECTS", + "OBJECT_HORSE_GANON", + "OBJECT_OA2", + "OBJECT_SPOT00_OBJECTS", + "OBJECT_MB", + "OBJECT_BOMBF", + "OBJECT_SK2", + "OBJECT_OE1", + "OBJECT_OE_ANIME", + "OBJECT_OE2", + "OBJECT_YDAN_OBJECTS", + "OBJECT_GND", + "OBJECT_AM", + "OBJECT_DEKUBABA", + "OBJECT_UNSET_3A", + "OBJECT_OA3", + "OBJECT_OA4", + "OBJECT_OA5", + "OBJECT_OA6", + "OBJECT_OA7", + "OBJECT_JJ", + "OBJECT_OA8", + "OBJECT_OA9", + "OBJECT_OB2", + "OBJECT_OB3", + "OBJECT_OB4", + "OBJECT_HORSE_ZELDA", + "OBJECT_OPENING_DEMO1", + "OBJECT_WARP1", + "OBJECT_B_HEART", + "OBJECT_DEKUNUTS", + "OBJECT_OE3", + "OBJECT_OE4", + "OBJECT_MENKURI_OBJECTS", + "OBJECT_OE5", + "OBJECT_OE6", + "OBJECT_OE7", + "OBJECT_OE8", + "OBJECT_OE9", + "OBJECT_OE10", + "OBJECT_OE11", + "OBJECT_OE12", + "OBJECT_VALI", + "OBJECT_OA10", + "OBJECT_OA11", + "OBJECT_MIZU_OBJECTS", + "OBJECT_FHG", + "OBJECT_OSSAN", + "OBJECT_MORI_HINERI1", + "OBJECT_BB", + "OBJECT_TOKI_OBJECTS", + "OBJECT_YUKABYUN", + "OBJECT_ZL2", + "OBJECT_MJIN", + "OBJECT_MJIN_FLASH", + "OBJECT_MJIN_DARK", + "OBJECT_MJIN_FLAME", + "OBJECT_MJIN_ICE", + "OBJECT_MJIN_SOUL", + "OBJECT_MJIN_WIND", + "OBJECT_MJIN_OKA", + "OBJECT_HAKA_OBJECTS", + "OBJECT_SPOT06_OBJECTS", + "OBJECT_ICE_OBJECTS", + "OBJECT_RELAY_OBJECTS", + "OBJECT_PO_FIELD", + "OBJECT_PO_COMPOSER", + "OBJECT_MORI_HINERI1A", + "OBJECT_MORI_HINERI2", + "OBJECT_MORI_HINERI2A", + "OBJECT_MORI_OBJECTS", + "OBJECT_MORI_TEX", + "OBJECT_SPOT08_OBJ", + "OBJECT_WARP2", + "OBJECT_HATA", + "OBJECT_BIRD", + "OBJECT_UNSET_78", + "OBJECT_UNSET_79", + "OBJECT_UNSET_7A", + "OBJECT_UNSET_7B", + "OBJECT_WOOD02", + "OBJECT_UNSET_7D", + "OBJECT_UNSET_7E", + "OBJECT_UNSET_7F", + "OBJECT_UNSET_80", + "OBJECT_LIGHTBOX", + "OBJECT_PU_BOX", + "OBJECT_UNSET_83", + "OBJECT_UNSET_84", + "OBJECT_TRAP", + "OBJECT_VASE", + "OBJECT_IM", + "OBJECT_TA", + "OBJECT_TK", + "OBJECT_XC", + "OBJECT_VM", + "OBJECT_BV", + "OBJECT_HAKACH_OBJECTS", + "OBJECT_EFC_CRYSTAL_LIGHT", + "OBJECT_EFC_FIRE_BALL", + "OBJECT_EFC_FLASH", + "OBJECT_EFC_LGT_SHOWER", + "OBJECT_EFC_STAR_FIELD", + "OBJECT_GOD_LGT", + "OBJECT_LIGHT_RING", + "OBJECT_TRIFORCE_SPOT", + "OBJECT_BDAN_OBJECTS", + "OBJECT_SD", + "OBJECT_RD", + "OBJECT_PO_SISTERS", + "OBJECT_HEAVY_OBJECT", + "OBJECT_GNDD", + "OBJECT_FD", + "OBJECT_DU", + "OBJECT_FW", + "OBJECT_MEDAL", + "OBJECT_HORSE_LINK_CHILD", + "OBJECT_SPOT02_OBJECTS", + "OBJECT_HAKA", + "OBJECT_RU1", + "OBJECT_SYOKUDAI", + "OBJECT_FD2", + "OBJECT_DH", + "OBJECT_RL", + "OBJECT_EFC_TW", + "OBJECT_DEMO_TRE_LGT", + "OBJECT_GI_KEY", + "OBJECT_MIR_RAY", + "OBJECT_BROB", + "OBJECT_GI_JEWEL", + "OBJECT_SPOT09_OBJ", + "OBJECT_SPOT18_OBJ", + "OBJECT_BDOOR", + "OBJECT_SPOT17_OBJ", + "OBJECT_SHOP_DUNGEN", + "OBJECT_NB", + "OBJECT_MO", + "OBJECT_SB", + "OBJECT_GI_MELODY", + "OBJECT_GI_HEART", + "OBJECT_GI_COMPASS", + "OBJECT_GI_BOSSKEY", + "OBJECT_GI_MEDAL", + "OBJECT_GI_NUTS", + "OBJECT_SA", + "OBJECT_GI_HEARTS", + "OBJECT_GI_ARROWCASE", + "OBJECT_GI_BOMBPOUCH", + "OBJECT_IN", + "OBJECT_TR", + "OBJECT_SPOT16_OBJ", + "OBJECT_OE1S", + "OBJECT_OE4S", + "OBJECT_OS_ANIME", + "OBJECT_GI_BOTTLE", + "OBJECT_GI_STICK", + "OBJECT_GI_MAP", + "OBJECT_OF1D_MAP", + "OBJECT_RU2", + "OBJECT_GI_SHIELD_1", + "OBJECT_DEKUJR", + "OBJECT_GI_MAGICPOT", + "OBJECT_GI_BOMB_1", + "OBJECT_OF1S", + "OBJECT_MA2", + "OBJECT_GI_PURSE", + "OBJECT_HNI", + "OBJECT_TW", + "OBJECT_RR", + "OBJECT_BXA", + "OBJECT_ANUBICE", + "OBJECT_GI_GERUDO", + "OBJECT_GI_ARROW", + "OBJECT_GI_BOMB_2", + "OBJECT_GI_EGG", + "OBJECT_GI_SCALE", + "OBJECT_GI_SHIELD_2", + "OBJECT_GI_HOOKSHOT", + "OBJECT_GI_OCARINA", + "OBJECT_GI_MILK", + "OBJECT_MA1", + "OBJECT_GANON", + "OBJECT_SST", + "OBJECT_NY_UNUSED", + "OBJECT_UNSET_E4", + "OBJECT_NY", + "OBJECT_FR", + "OBJECT_GI_PACHINKO", + "OBJECT_GI_BOOMERANG", + "OBJECT_GI_BOW", + "OBJECT_GI_GLASSES", + "OBJECT_GI_LIQUID", + "OBJECT_ANI", + "OBJECT_DEMO_6K", + "OBJECT_GI_SHIELD_3", + "OBJECT_GI_LETTER", + "OBJECT_SPOT15_OBJ", + "OBJECT_JYA_OBJ", + "OBJECT_GI_CLOTHES", + "OBJECT_GI_BEAN", + "OBJECT_GI_FISH", + "OBJECT_GI_SAW", + "OBJECT_GI_HAMMER", + "OBJECT_GI_GRASS", + "OBJECT_GI_LONGSWORD", + "OBJECT_SPOT01_OBJECTS", + "OBJECT_MD_UNUSED", + "OBJECT_MD", + "OBJECT_KM1", + "OBJECT_KW1", + "OBJECT_ZO", + "OBJECT_KZ", + "OBJECT_UMAJUMP", + "OBJECT_MASTERKOKIRI", + "OBJECT_MASTERKOKIRIHEAD", + "OBJECT_MASTERGOLON", + "OBJECT_MASTERZOORA", + "OBJECT_AOB", + "OBJECT_IK", + "OBJECT_AHG", + "OBJECT_CNE", + "OBJECT_GI_NIWATORI", + "OBJECT_SKJ", + "OBJECT_GI_BOTTLE_LETTER", + "OBJECT_BJI", + "OBJECT_BBA", + "OBJECT_GI_OCARINA_0", + "OBJECT_DS", + "OBJECT_ANE", + "OBJECT_BOJ", + "OBJECT_SPOT03_OBJECT", + "OBJECT_SPOT07_OBJECT", + "OBJECT_FZ", + "OBJECT_BOB", + "OBJECT_GE1", + "OBJECT_YABUSAME_POINT", + "OBJECT_GI_BOOTS_2", + "OBJECT_GI_SEED", + "OBJECT_GND_MAGIC", + "OBJECT_D_ELEVATOR", + "OBJECT_D_HSBLOCK", + "OBJECT_D_LIFT", + "OBJECT_MAMENOKI", + "OBJECT_GOROIWA", + "OBJECT_UNSET_120", + "OBJECT_TORYO", + "OBJECT_DAIKU", + "OBJECT_UNSET_123", + "OBJECT_NWC", + "OBJECT_BLKOBJ", + "OBJECT_GM", + "OBJECT_MS", + "OBJECT_HS", + "OBJECT_INGATE", + "OBJECT_LIGHTSWITCH", + "OBJECT_KUSA", + "OBJECT_TSUBO", + "OBJECT_GI_GLOVES", + "OBJECT_GI_COIN", + "OBJECT_KANBAN", + "OBJECT_GJYO_OBJECTS", + "OBJECT_OWL", + "OBJECT_MK", + "OBJECT_FU", + "OBJECT_GI_KI_TAN_MASK", + "OBJECT_GI_REDEAD_MASK", + "OBJECT_GI_SKJ_MASK", + "OBJECT_GI_RABIT_MASK", + "OBJECT_GI_TRUTH_MASK", + "OBJECT_GANON_OBJECTS", + "OBJECT_SIOFUKI", + "OBJECT_STREAM", + "OBJECT_MM", + "OBJECT_FA", + "OBJECT_OS", + "OBJECT_GI_EYE_LOTION", + "OBJECT_GI_POWDER", + "OBJECT_GI_MUSHROOM", + "OBJECT_GI_TICKETSTONE", + "OBJECT_GI_BROKENSWORD", + "OBJECT_JS", + "OBJECT_CS", + "OBJECT_GI_PRESCRIPTION", + "OBJECT_GI_BRACELET", + "OBJECT_GI_SOLDOUT", + "OBJECT_GI_FROG", + "OBJECT_MAG", + "OBJECT_DOOR_GERUDO", + "OBJECT_GT", + "OBJECT_EFC_ERUPC", + "OBJECT_ZL2_ANIME1", + "OBJECT_ZL2_ANIME2", + "OBJECT_GI_GOLONMASK", + "OBJECT_GI_ZORAMASK", + "OBJECT_GI_GERUDOMASK", + "OBJECT_GANON2", + "OBJECT_KA", + "OBJECT_TS", + "OBJECT_ZG", + "OBJECT_GI_HOVERBOOTS", + "OBJECT_GI_M_ARROW", + "OBJECT_DS2", + "OBJECT_EC", + "OBJECT_FISH", + "OBJECT_GI_SUTARU", + "OBJECT_GI_GODDESS", + "OBJECT_SSH", + "OBJECT_BIGOKUTA", + "OBJECT_BG", + "OBJECT_SPOT05_OBJECTS", + "OBJECT_SPOT12_OBJ", + "OBJECT_BOMBIWA", + "OBJECT_HINTNUTS", + "OBJECT_RS", + "OBJECT_SPOT00_BREAK", + "OBJECT_GLA", + "OBJECT_SHOPNUTS", + "OBJECT_GELDB", + "OBJECT_GR", + "OBJECT_DOG", + "OBJECT_JYA_IRON", + "OBJECT_JYA_DOOR", + "OBJECT_UNSET_16E", + "OBJECT_SPOT11_OBJ", + "OBJECT_KIBAKO2", + "OBJECT_DNS", + "OBJECT_DNK", + "OBJECT_GI_FIRE", + "OBJECT_GI_INSECT", + "OBJECT_GI_BUTTERFLY", + "OBJECT_GI_GHOST", + "OBJECT_GI_SOUL", + "OBJECT_BOWL", + "OBJECT_DEMO_KEKKAI", + "OBJECT_EFC_DOUGHNUT", + "OBJECT_GI_DEKUPOUCH", + "OBJECT_GANON_ANIME1", + "OBJECT_GANON_ANIME2", + "OBJECT_GANON_ANIME3", + "OBJECT_GI_RUPY", + "OBJECT_SPOT01_MATOYA", + "OBJECT_SPOT01_MATOYAB", + "OBJECT_MU", + "OBJECT_WF", + "OBJECT_SKB", + "OBJECT_GJ", + "OBJECT_GEFF", + "OBJECT_HAKA_DOOR", + "OBJECT_GS", + "OBJECT_PS", + "OBJECT_BWALL", + "OBJECT_COW", + "OBJECT_COB", + "OBJECT_GI_SWORD_1", + "OBJECT_DOOR_KILLER", + "OBJECT_OUKE_HAKA", + "OBJECT_TIMEBLOCK", + "OBJECT_ZL4", +) diff --git a/tools/assets/extract/oot64_data/scene_table_mini.py b/tools/assets/extract/oot64_data/scene_table_mini.py new file mode 100644 index 0000000000..682ee8fd38 --- /dev/null +++ b/tools/assets/extract/oot64_data/scene_table_mini.py @@ -0,0 +1,114 @@ +# This file was generated from ../../../..//include/tables/scene_table.h + +DATA = ( + ("ydan_scene", "SCENE_DEKU_TREE"), + ("ddan_scene", "SCENE_DODONGOS_CAVERN"), + ("bdan_scene", "SCENE_JABU_JABU"), + ("Bmori1_scene", "SCENE_FOREST_TEMPLE"), + ("HIDAN_scene", "SCENE_FIRE_TEMPLE"), + ("MIZUsin_scene", "SCENE_WATER_TEMPLE"), + ("jyasinzou_scene", "SCENE_SPIRIT_TEMPLE"), + ("HAKAdan_scene", "SCENE_SHADOW_TEMPLE"), + ("HAKAdanCH_scene", "SCENE_BOTTOM_OF_THE_WELL"), + ("ice_doukutu_scene", "SCENE_ICE_CAVERN"), + ("ganon_scene", "SCENE_GANONS_TOWER"), + ("men_scene", "SCENE_GERUDO_TRAINING_GROUND"), + ("gerudoway_scene", "SCENE_THIEVES_HIDEOUT"), + ("ganontika_scene", "SCENE_INSIDE_GANONS_CASTLE"), + ("ganon_sonogo_scene", "SCENE_GANONS_TOWER_COLLAPSE_INTERIOR"), + ("ganontikasonogo_scene", "SCENE_INSIDE_GANONS_CASTLE_COLLAPSE"), + ("takaraya_scene", "SCENE_TREASURE_BOX_SHOP"), + ("ydan_boss_scene", "SCENE_DEKU_TREE_BOSS"), + ("ddan_boss_scene", "SCENE_DODONGOS_CAVERN_BOSS"), + ("bdan_boss_scene", "SCENE_JABU_JABU_BOSS"), + ("moribossroom_scene", "SCENE_FOREST_TEMPLE_BOSS"), + ("FIRE_bs_scene", "SCENE_FIRE_TEMPLE_BOSS"), + ("MIZUsin_bs_scene", "SCENE_WATER_TEMPLE_BOSS"), + ("jyasinboss_scene", "SCENE_SPIRIT_TEMPLE_BOSS"), + ("HAKAdan_bs_scene", "SCENE_SHADOW_TEMPLE_BOSS"), + ("ganon_boss_scene", "SCENE_GANONDORF_BOSS"), + ("ganon_final_scene", "SCENE_GANONS_TOWER_COLLAPSE_EXTERIOR"), + ("entra_scene", "SCENE_MARKET_ENTRANCE_DAY"), + ("entra_n_scene", "SCENE_MARKET_ENTRANCE_NIGHT"), + ("enrui_scene", "SCENE_MARKET_ENTRANCE_RUINS"), + ("market_alley_scene", "SCENE_BACK_ALLEY_DAY"), + ("market_alley_n_scene", "SCENE_BACK_ALLEY_NIGHT"), + ("market_day_scene", "SCENE_MARKET_DAY"), + ("market_night_scene", "SCENE_MARKET_NIGHT"), + ("market_ruins_scene", "SCENE_MARKET_RUINS"), + ("shrine_scene", "SCENE_TEMPLE_OF_TIME_EXTERIOR_DAY"), + ("shrine_n_scene", "SCENE_TEMPLE_OF_TIME_EXTERIOR_NIGHT"), + ("shrine_r_scene", "SCENE_TEMPLE_OF_TIME_EXTERIOR_RUINS"), + ("kokiri_home_scene", "SCENE_KNOW_IT_ALL_BROS_HOUSE"), + ("kokiri_home3_scene", "SCENE_TWINS_HOUSE"), + ("kokiri_home4_scene", "SCENE_MIDOS_HOUSE"), + ("kokiri_home5_scene", "SCENE_SARIAS_HOUSE"), + ("kakariko_scene", "SCENE_KAKARIKO_CENTER_GUEST_HOUSE"), + ("kakariko3_scene", "SCENE_BACK_ALLEY_HOUSE"), + ("shop1_scene", "SCENE_BAZAAR"), + ("kokiri_shop_scene", "SCENE_KOKIRI_SHOP"), + ("golon_scene", "SCENE_GORON_SHOP"), + ("zoora_scene", "SCENE_ZORA_SHOP"), + ("drag_scene", "SCENE_POTION_SHOP_KAKARIKO"), + ("alley_shop_scene", "SCENE_POTION_SHOP_MARKET"), + ("night_shop_scene", "SCENE_BOMBCHU_SHOP"), + ("face_shop_scene", "SCENE_HAPPY_MASK_SHOP"), + ("link_home_scene", "SCENE_LINKS_HOUSE"), + ("impa_scene", "SCENE_DOG_LADY_HOUSE"), + ("malon_stable_scene", "SCENE_STABLE"), + ("labo_scene", "SCENE_IMPAS_HOUSE"), + ("hylia_labo_scene", "SCENE_LAKESIDE_LABORATORY"), + ("tent_scene", "SCENE_CARPENTERS_TENT"), + ("hut_scene", "SCENE_GRAVEKEEPERS_HUT"), + ("daiyousei_izumi_scene", "SCENE_GREAT_FAIRYS_FOUNTAIN_MAGIC"), + ("yousei_izumi_tate_scene", "SCENE_FAIRYS_FOUNTAIN"), + ("yousei_izumi_yoko_scene", "SCENE_GREAT_FAIRYS_FOUNTAIN_SPELLS"), + ("kakusiana_scene", "SCENE_GROTTOS"), + ("hakaana_scene", "SCENE_REDEAD_GRAVE"), + ("hakaana2_scene", "SCENE_GRAVE_WITH_FAIRYS_FOUNTAIN"), + ("hakaana_ouke_scene", "SCENE_ROYAL_FAMILYS_TOMB"), + ("syatekijyou_scene", "SCENE_SHOOTING_GALLERY"), + ("tokinoma_scene", "SCENE_TEMPLE_OF_TIME"), + ("kenjyanoma_scene", "SCENE_CHAMBER_OF_THE_SAGES"), + ("hairal_niwa_scene", "SCENE_CASTLE_COURTYARD_GUARDS_DAY"), + ("hairal_niwa_n_scene", "SCENE_CASTLE_COURTYARD_GUARDS_NIGHT"), + ("hiral_demo_scene", "SCENE_CUTSCENE_MAP"), + ("hakasitarelay_scene", "SCENE_WINDMILL_AND_DAMPES_GRAVE"), + ("turibori_scene", "SCENE_FISHING_POND"), + ("nakaniwa_scene", "SCENE_CASTLE_COURTYARD_ZELDA"), + ("bowling_scene", "SCENE_BOMBCHU_BOWLING_ALLEY"), + ("souko_scene", "SCENE_LON_LON_BUILDINGS"), + ("miharigoya_scene", "SCENE_MARKET_GUARD_HOUSE"), + ("mahouya_scene", "SCENE_POTION_SHOP_GRANNY"), + ("ganon_demo_scene", "SCENE_GANON_BOSS"), + ("kinsuta_scene", "SCENE_HOUSE_OF_SKULLTULA"), + ("spot00_scene", "SCENE_HYRULE_FIELD"), + ("spot01_scene", "SCENE_KAKARIKO_VILLAGE"), + ("spot02_scene", "SCENE_GRAVEYARD"), + ("spot03_scene", "SCENE_ZORAS_RIVER"), + ("spot04_scene", "SCENE_KOKIRI_FOREST"), + ("spot05_scene", "SCENE_SACRED_FOREST_MEADOW"), + ("spot06_scene", "SCENE_LAKE_HYLIA"), + ("spot07_scene", "SCENE_ZORAS_DOMAIN"), + ("spot08_scene", "SCENE_ZORAS_FOUNTAIN"), + ("spot09_scene", "SCENE_GERUDO_VALLEY"), + ("spot10_scene", "SCENE_LOST_WOODS"), + ("spot11_scene", "SCENE_DESERT_COLOSSUS"), + ("spot12_scene", "SCENE_GERUDOS_FORTRESS"), + ("spot13_scene", "SCENE_HAUNTED_WASTELAND"), + ("spot15_scene", "SCENE_HYRULE_CASTLE"), + ("spot16_scene", "SCENE_DEATH_MOUNTAIN_TRAIL"), + ("spot17_scene", "SCENE_DEATH_MOUNTAIN_CRATER"), + ("spot18_scene", "SCENE_GORON_CITY"), + ("spot20_scene", "SCENE_LON_LON_RANCH"), + ("ganon_tou_scene", "SCENE_OUTSIDE_GANONS_CASTLE"), + ("test01_scene", "SCENE_TEST01"), + ("besitu_scene", "SCENE_BESITU"), + ("depth_test_scene", "SCENE_DEPTH_TEST"), + ("syotes_scene", "SCENE_SYOTES"), + ("syotes2_scene", "SCENE_SYOTES2"), + ("sutaru_scene", "SCENE_SUTARU"), + ("hairal_niwa2_scene", "SCENE_HAIRAL_NIWA2"), + ("sasatest_scene", "SCENE_SASATEST"), + ("testroom_scene", "SCENE_TESTROOM"), +) diff --git a/tools/assets/extract/z64_resource_handlers.py b/tools/assets/extract/z64_resource_handlers.py new file mode 100644 index 0000000000..a3ae3c77ac --- /dev/null +++ b/tools/assets/extract/z64_resource_handlers.py @@ -0,0 +1,469 @@ +# SPDX-FileCopyrightText: © 2025 ZeldaRET +# SPDX-License-Identifier: CC0-1.0 + +from typing import Callable + +from ..descriptor.base import ResourceDesc +from ..descriptor import n64resources +from ..descriptor import z64resources + +from .extase import ( + File, + Resource, + BinaryBlobResource, +) +from .extase.cdata_resources import Vec3sArrayResource, S16ArrayResource + +from .extase_oot64 import ( + skeleton_resources, + skeleton_skin_resources, + animation_resources, + collision_resources, + dlist_resources, + playeranim_resources, + skelcurve_resources, + misc_resources, + scene_rooms_resources, + scene_commands_resource, + skelanime_legacy_resources, + room_shape_resources, +) + + +# +# resource handlers +# + + +class ResourceHandlerException(Exception): ... + + +class ResourceNeedsPostProcessWithPoolResourcesException(ResourceHandlerException): + def __init__( + self, + *args, + resource: Resource, + callback: Callable[[dict[ResourceDesc, Resource]], None], + ): + super().__init__(*args) + self.resource = resource + self.callback = callback + + def __repr__(self) -> str: + return ( + super().__repr__().removesuffix(")") + + f", resource={self.resource!r}" + + f", callback={self.callback!r})" + ) + + +ResourceHandler = Callable[[File, ResourceDesc], Resource] + + +def register_resource_handlers(): + + def skeleton_resource_handler( + file: File, + resource_desc: z64resources.SkeletonResourceDesc, + ): + offset = resource_desc.offset + if resource_desc.limb_type == z64resources.LimbType.STANDARD: + if resource_desc.type == z64resources.SkeletonType.NORMAL: + res = skeleton_resources.SkeletonNormalResource( + file, + offset, + resource_desc.symbol_name, + ) + elif resource_desc.type == z64resources.SkeletonType.FLEX: + res = skeleton_resources.SkeletonFlexResource( + file, + offset, + resource_desc.symbol_name, + ) + else: + raise NotImplementedError( + "unimplemented SkeletonType", + resource_desc.type, + ) + elif resource_desc.limb_type == z64resources.LimbType.LOD: + if resource_desc.type == z64resources.SkeletonType.NORMAL: + res = skeleton_resources.SkeletonNormalLODResource( + file, offset, resource_desc.symbol_name + ) + elif resource_desc.type == z64resources.SkeletonType.FLEX: + res = skeleton_resources.SkeletonFlexLODResource( + file, offset, resource_desc.symbol_name + ) + else: + raise NotImplementedError( + "LimbType=LOD", + "unimplemented SkeletonType", + resource_desc.type, + ) + elif resource_desc.limb_type == z64resources.LimbType.SKIN: + assert resource_desc.type == z64resources.SkeletonType.NORMAL + res = skeleton_skin_resources.SkeletonSkinResource( + file, offset, resource_desc.symbol_name + ) + elif resource_desc.limb_type == z64resources.LimbType.CURVE: + assert resource_desc.type == z64resources.SkeletonType.CURVE + res = skelcurve_resources.CurveSkeletonHeaderResource( + file, offset, resource_desc.symbol_name + ) + else: + raise NotImplementedError( + "unimplemented Skeleton LimbType", + resource_desc.limb_type, + ) + # TODO check is this works for SkeletonSkinResource + # TODO implement for CurveSkeletonHeaderResource + if resource_desc.limb_enum_name is not None: + res.set_enum_name(resource_desc.limb_enum_name) + if resource_desc.limb_enum_none_member_name is not None: + res.set_enum_member_name_none(resource_desc.limb_enum_none_member_name) + if resource_desc.limb_enum_max_member_name is not None: + res.set_enum_member_name_max(resource_desc.limb_enum_max_member_name) + return res + + def limb_resource_handler( + file: File, + resource_desc: z64resources.LimbResourceDesc, + ): + offset = resource_desc.offset + if resource_desc.limb_type == z64resources.LimbType.STANDARD: + res = skeleton_resources.StandardLimbResource( + file, + offset, + resource_desc.symbol_name, + ) + elif resource_desc.limb_type == z64resources.LimbType.SKIN: + res = skeleton_skin_resources.SkinLimbResource( + file, offset, resource_desc.symbol_name + ) + elif resource_desc.limb_type == z64resources.LimbType.LOD: + res = skeleton_resources.LODLimbResource( + file, offset, resource_desc.symbol_name + ) + elif resource_desc.limb_type == z64resources.LimbType.LEGACY: + return skelanime_legacy_resources.LegacyLimbResource( + file, offset, resource_desc.symbol_name + ) + elif resource_desc.limb_type == z64resources.LimbType.CURVE: + res = skelcurve_resources.SkelCurveLimbResource( + file, offset, resource_desc.symbol_name + ) + else: + raise NotImplementedError( + "unimplemented LimbType", + resource_desc.limb_type, + ) + # TODO check this works for SkinLimbResource + # TODO implement for SkelCurveLimbResource + if resource_desc.limb_enum_member_name is not None: + res.set_enum_member_name(resource_desc.limb_enum_member_name) + return res + + def limb_table_handler( + file: File, + resource_desc: z64resources.LimbTableResourceDesc, + ): + if resource_desc.limb_type == z64resources.LimbType.STANDARD: + resource = skeleton_resources.StandardLimbsArrayResource( + file, resource_desc.offset, resource_desc.symbol_name + ) + resource.set_length(resource_desc.count) + return resource + elif resource_desc.limb_type == z64resources.LimbType.SKIN: + resource = skeleton_skin_resources.SkinLimbsArrayResource( + file, resource_desc.offset, resource_desc.symbol_name + ) + resource.set_length(resource_desc.count) + return resource + elif resource_desc.limb_type == z64resources.LimbType.LOD: + resource = skeleton_resources.LODLimbsArrayResource( + file, resource_desc.offset, resource_desc.symbol_name + ) + resource.set_length(resource_desc.count) + return resource + elif resource_desc.limb_type == z64resources.LimbType.LEGACY: + resource = skelanime_legacy_resources.LegacyLimbsArrayResource( + file, + resource_desc.offset, + resource_desc.symbol_name, + ) + resource.set_length(resource_desc.count) + return resource + else: + raise NotImplementedError("LimbTable of limb type", resource_desc.limb_type) + + def animation_resource_handler( + file: File, + resource_desc: z64resources.AnimationResourceDesc, + ): + return animation_resources.AnimationResource( + file, + resource_desc.offset, + resource_desc.symbol_name, + ) + + def collision_resource_handler( + file: File, + resource_desc: z64resources.CollisionResourceDesc, + ): + return collision_resources.CollisionResource( + file, + resource_desc.offset, + resource_desc.symbol_name, + ) + + def dlist_resource_handler( + file: File, + resource_desc: n64resources.DListResourceDesc, + ): + res = dlist_resources.DListResource( + file, + resource_desc.offset, + resource_desc.symbol_name, + target_ucode={ + n64resources.GfxMicroCode.F3DEX: dlist_resources.Ucode.f3dex, + n64resources.GfxMicroCode.F3DEX2: dlist_resources.Ucode.f3dex2, + }[resource_desc.ucode], + ) + res.ignored_raw_pointers |= resource_desc.raw_pointers + return res + + def texture_resource_handler( + file: File, resource_desc: n64resources.TextureResourceDesc + ): + res = dlist_resources.TextureResource( + file, + resource_desc.offset, + resource_desc.symbol_name, + resource_desc.format.fmt, + resource_desc.format.siz, + resource_desc.width, + resource_desc.height, + ) + if "hackmode_ignore_orphaned_tlut" in resource_desc.hack_modes: + res.HACK_ignore_orphaned_tlut = True + return res + + def ci_texture_resource_handler( + file: File, resource_desc: n64resources.CITextureResourceDesc + ): + if "hackmode_split_tlut" in resource_desc.hack_modes: + # TODO implement SplitTlut="true" + return BinaryBlobResource( + file, + resource_desc.offset, + resource_desc.offset + + ( + resource_desc.format.siz.bpp + * resource_desc.width + * resource_desc.height + // 8 + ), + resource_desc.symbol_name, + ) + + resource = dlist_resources.TextureResource( + file, + resource_desc.offset, + resource_desc.symbol_name, + resource_desc.format.fmt, + resource_desc.format.siz, + resource_desc.width, + resource_desc.height, + ) + + def callback_set_tlut(pool_resources_by_desc): + resource_tlut_desc = resource_desc.tlut + resource_tlut = pool_resources_by_desc[resource_tlut_desc] + resource.set_tlut(resource_tlut) + + raise ResourceNeedsPostProcessWithPoolResourcesException( + resource=resource, callback=callback_set_tlut + ) + + def PlayerAnimationData_handler( + file: File, + resource_desc: z64resources.PlayerAnimationDataResourceDesc, + ): + res = playeranim_resources.PlayerAnimationDataResource( + file, + resource_desc.offset, + resource_desc.symbol_name, + ) + res.set_frame_count(resource_desc.frame_count) + return res + + def PlayerAnimation_handler( + file: File, + resource_desc: z64resources.PlayerAnimationResourceDesc, + ): + return playeranim_resources.PlayerAnimationResource( + file, + resource_desc.offset, + resource_desc.symbol_name, + ) + + def vec3s_array_resource_handler( + file: File, + resource_desc: n64resources.Vec3sArrayResourceDesc, + ): + return Vec3sArrayResource( + file, + resource_desc.offset, + resource_desc.symbol_name, + resource_desc.count, + ) + + def s16_array_resource_handler( + file: File, + resource_desc: n64resources.S16ArrayResourceDesc, + ): + return S16ArrayResource( + file, + resource_desc.offset, + resource_desc.symbol_name, + resource_desc.count, + ) + + def vtx_array_resource_handler( + file: File, + resource_desc: n64resources.VtxArrayResourceDesc, + ): + return dlist_resources.VtxArrayResource( + file, + resource_desc.offset, + ( + resource_desc.offset + + ( + resource_desc.count + * dlist_resources.VtxArrayResource.element_cdata_ext.size + ) + ), + resource_desc.symbol_name, + ) + + def binary_blob_resource_handler( + file: File, + resource_desc: n64resources.BlobResourceDesc, + ): + return BinaryBlobResource( + file, + resource_desc.offset, + resource_desc.offset + resource_desc.size, + resource_desc.symbol_name, + ) + + def CurveAnimation_handler( + file: File, + resource_desc: z64resources.CurveAnimationResourceDesc, + ): + # TODO use resource_desc.skeleton + return skelcurve_resources.CurveAnimationHeaderResource( + file, resource_desc.offset, resource_desc.symbol_name + ) + + def Mtx_handler( + file: File, + resource_desc: n64resources.MtxResourceDesc, + ): + return dlist_resources.MtxResource( + file, resource_desc.offset, resource_desc.symbol_name + ) + + def cutscene_resource_handler( + file: File, + resource_desc: z64resources.CutsceneResourceDesc, + ): + return misc_resources.CutsceneResource( + file, resource_desc.offset, resource_desc.symbol_name + ) + + def scene_resource_handler( + file: File, + resource_desc: z64resources.SceneResourceDesc, + ): + return scene_commands_resource.SceneCommandsResource( + file, resource_desc.offset, resource_desc.symbol_name + ) + + def room_resource_handler( + file: File, + resource_desc: z64resources.RoomResourceDesc, + ): + if "hackmode_syotes_room" in resource_desc.hack_modes: + return room_shape_resources.RoomShapeNormalResource( + file, + resource_desc.offset, + resource_desc.symbol_name, + ) + return scene_commands_resource.SceneCommandsResource( + file, resource_desc.offset, resource_desc.symbol_name + ) + + def path_list_resource_handler( + file: File, + resource_desc: z64resources.PathListResourceDesc, + ): + resource = scene_rooms_resources.PathListResource( + file, resource_desc.offset, resource_desc.symbol_name + ) + resource.set_length(resource_desc.num_paths) + return resource + + def legacy_animation_handler( + file: File, + resource_desc: z64resources.LegacyAnimationResourceDesc, + ): + return skelanime_legacy_resources.LegacyAnimationResource( + file, resource_desc.offset, resource_desc.symbol_name + ) + + RESOURCE_HANDLERS.update( + { + z64resources.SkeletonResourceDesc: skeleton_resource_handler, + z64resources.LimbResourceDesc: limb_resource_handler, + z64resources.AnimationResourceDesc: animation_resource_handler, + z64resources.CollisionResourceDesc: collision_resource_handler, + n64resources.DListResourceDesc: dlist_resource_handler, + n64resources.TextureResourceDesc: texture_resource_handler, + n64resources.CITextureResourceDesc: ci_texture_resource_handler, + z64resources.PlayerAnimationDataResourceDesc: PlayerAnimationData_handler, + n64resources.Vec3sArrayResourceDesc: vec3s_array_resource_handler, + n64resources.S16ArrayResourceDesc: s16_array_resource_handler, + n64resources.VtxArrayResourceDesc: vtx_array_resource_handler, + z64resources.PlayerAnimationResourceDesc: PlayerAnimation_handler, + n64resources.BlobResourceDesc: binary_blob_resource_handler, + n64resources.MtxResourceDesc: Mtx_handler, + z64resources.LegacyAnimationResourceDesc: legacy_animation_handler, + z64resources.LimbTableResourceDesc: limb_table_handler, + z64resources.CurveAnimationResourceDesc: CurveAnimation_handler, + z64resources.SceneResourceDesc: scene_resource_handler, + z64resources.RoomResourceDesc: room_resource_handler, + z64resources.PathListResourceDesc: path_list_resource_handler, + z64resources.CutsceneResourceDesc: cutscene_resource_handler, + } + ) + + +RESOURCE_HANDLERS: dict[str, ResourceHandler] = {} + + +def get_resource_from_desc( + file: File, + resource_desc: ResourceDesc, +) -> Resource: + resource_handler = RESOURCE_HANDLERS.get(type(resource_desc)) + + if resource_handler is None: + raise Exception("Unknown resource descriptor type", resource_desc) + + try: + resource = resource_handler(file, resource_desc) + except ResourceHandlerException: + raise + + return resource diff --git a/tools/assets/n64.py b/tools/assets/n64.py new file mode 100644 index 0000000000..e3ebf70528 --- /dev/null +++ b/tools/assets/n64.py @@ -0,0 +1,53 @@ +# SPDX-FileCopyrightText: © 2025 ZeldaRET +# SPDX-License-Identifier: CC0-1.0 + +import enum + + +class G_IM_FMT(enum.Enum): + RGBA = 0 + YUV = 1 + CI = 2 + IA = 3 + I = 4 + + def __init__(self, i: int): + self.i = i + + by_i: dict[int, "G_IM_FMT"] + + +G_IM_FMT.by_i = {fmt.i: fmt for fmt in G_IM_FMT} + + +class G_IM_SIZ(enum.Enum): + _4b = (0, 4) + _8b = (1, 8) + _16b = (2, 16) + _32b = (3, 32) + + def __init__(self, i: int, bpp: int): + self.i = i + self.bpp = bpp + + by_i: dict[int, "G_IM_SIZ"] + + +G_IM_SIZ.by_i = {siz.i: siz for siz in G_IM_SIZ} + + +G_MDSFT_TEXTLUT = 14 + + +class G_TT(enum.Enum): + NONE = 0b00 << G_MDSFT_TEXTLUT + RGBA16 = 0b10 << G_MDSFT_TEXTLUT + IA16 = 0b11 << G_MDSFT_TEXTLUT + + def __init__(self, i: int): + self.i = i + + by_i: dict[int, "G_TT"] + + +G_TT.by_i = {tt.i: tt for tt in G_TT} diff --git a/tools/assets/n64texconv/__init__.py b/tools/assets/n64texconv/__init__.py index 9e4ea1c510..3952b19c8e 100644 --- a/tools/assets/n64texconv/__init__.py +++ b/tools/assets/n64texconv/__init__.py @@ -354,9 +354,9 @@ class N64Image(Structure): return deref(ln64texconv.n64texconv_image_new(width, height, fmt, siz, pal)) def __del__(self): - ln64texconv.n64texconv_image_free(byref(self)) # Also free the palette if the reference count drops to 0 _object_refcount.rm_ref(self.pal, ln64texconv.n64texconv_palette_free) + ln64texconv.n64texconv_image_free(byref(self)) def copy(self) -> Optional["N64Image"]: _object_refcount.add_ref(self.pal) diff --git a/tools/assets/n64texconv/src/libn64texconv/n64texconv.c b/tools/assets/n64texconv/src/libn64texconv/n64texconv.c index 06caf36f60..61d7fbb8eb 100644 --- a/tools/assets/n64texconv/src/libn64texconv/n64texconv.c +++ b/tools/assets/n64texconv/src/libn64texconv/n64texconv.c @@ -119,7 +119,7 @@ n64texconv_quantize(uint8_t *out_indices, struct color *out_pal, size_t *out_pal * out_indices, out_pal, out_pal_count, texels, widths, heights are all arrays of size num_images * texels[i] and out_indices[i] are arrays of size widths[i] * heights[i] */ -UNUSED static int +int n64texconv_quantize_shared(uint8_t **out_indices, struct color *out_pal, size_t *out_pal_count, struct color **texels, size_t *widths, size_t *heights, size_t num_images, unsigned int max_colors, float dither_level) @@ -880,13 +880,10 @@ n64texconv_image_from_png(const char *path, int fmt, int siz, int pal_fmt) if (plte.n_entries == 0) goto error_post_create_img; - // TODO ZAPD always writes 256-color palettes which breaks this, enable it when we can -#if 0 // Palette must have sufficiently few colors for the target format. If there are too // many, requantize to the maximum amount for the target format. if (plte.n_entries > max_colors) goto requantize; -#endif pal = n64texconv_palette_new(plte.n_entries, pal_fmt); if (pal == NULL) @@ -922,9 +919,9 @@ n64texconv_image_from_png(const char *path, int fmt, int siz, int pal_fmt) assert(rv == 0); } else { // Input is not an indexed png, quantize and generate palette -#if 0 + requantize: // Input is an indexed png but has too many colors, requantize with new palette -#endif + rv = spng_decode_image(ctx, (void *)img->texels, nbytes, SPNG_FMT_RGBA8, 0); assert(rv == 0); diff --git a/tools/assets/n64texconv/src/libn64texconv/n64texconv.h b/tools/assets/n64texconv/src/libn64texconv/n64texconv.h index 1c2dd98fcc..0c6476e3aa 100644 --- a/tools/assets/n64texconv/src/libn64texconv/n64texconv.h +++ b/tools/assets/n64texconv/src/libn64texconv/n64texconv.h @@ -119,4 +119,9 @@ n64texconv_image_to_c_file(const char *out_path, struct n64_image *img, bool pad const char * n64texconv_png_extension(struct n64_image *img); +int +n64texconv_quantize_shared(uint8_t **out_indices, struct color *out_pal, size_t *out_pal_count, struct color **texels, + size_t *widths, size_t *heights, size_t num_images, unsigned int max_colors, + float dither_level); + #endif diff --git a/tools/extract_assets.py b/tools/extract_assets.py deleted file mode 100755 index 09519cb1ea..0000000000 --- a/tools/extract_assets.py +++ /dev/null @@ -1,208 +0,0 @@ -#!/usr/bin/env python3 - -import argparse -import json -import os -import signal -import time -import multiprocessing -from pathlib import Path - -import version_config - - -def SignalHandler(sig, frame): - print(f'Signal {sig} received. Aborting...') - mainAbort.set() - # Don't exit immediately to update the extracted assets file. - -def ExtractFile(assetConfig: version_config.AssetConfig, outputPath: Path, outputSourcePath: Path): - name = assetConfig.name - xmlPath = assetConfig.xml_path - version = globalVersionConfig.version - if globalAbort.is_set(): - # Don't extract if another file wasn't extracted properly. - return - - zapdPath = Path("tools") / "ZAPD" / "ZAPD.out" - configPath = Path("tools") / "ZAPDConfigs" / version / "Config.xml" - - outputPath.mkdir(parents=True, exist_ok=True) - outputSourcePath.mkdir(parents=True, exist_ok=True) - - execStr = f"{zapdPath} e -eh -i {xmlPath} -b {globalBaseromSegmentsDir} -o {outputPath} -osf {outputSourcePath} -gsf 1 -rconf {configPath} --cs-float both {ZAPDArgs}" - - if name.startswith("code/") or name.startswith("n64dd/") or name.startswith("overlays/"): - assert assetConfig.start_offset is not None - assert assetConfig.end_offset is not None - - execStr += f" --start-offset 0x{assetConfig.start_offset:X}" - execStr += f" --end-offset 0x{assetConfig.end_offset:X}" - - if name.startswith("overlays/"): - overlayName = name.split("/")[1] - baseAddress = globalVersionConfig.dmadata_segments[overlayName].vram + assetConfig.start_offset - - execStr += f" --base-address 0x{baseAddress:X}" - execStr += " --static" - - if globalUnaccounted: - execStr += " -Wunaccounted" - - print(execStr) - exitValue = os.system(execStr) - if exitValue != 0: - globalAbort.set() - print("\n") - print(f"Error when extracting from file {xmlPath}", file=os.sys.stderr) - print("Aborting...", file=os.sys.stderr) - print("\n") - -def ExtractFunc(assetConfig: version_config.AssetConfig): - objectName = assetConfig.name - xml_path = assetConfig.xml_path - xml_path_str = str(xml_path) - - outPath = globalOutputDir / objectName - outSourcePath = outPath - - if xml_path_str in globalExtractedAssetsTracker: - timestamp = globalExtractedAssetsTracker[xml_path_str]["timestamp"] - modificationTime = int(os.path.getmtime(xml_path)) - if modificationTime < timestamp: - # XML has not been modified since last extraction. - return - - currentTimeStamp = int(time.time()) - - ExtractFile(assetConfig, outPath, outSourcePath) - - if not globalAbort.is_set(): - # Only update timestamp on successful extractions - if xml_path_str not in globalExtractedAssetsTracker: - globalExtractedAssetsTracker[xml_path_str] = globalManager.dict() - globalExtractedAssetsTracker[xml_path_str]["timestamp"] = currentTimeStamp - -def initializeWorker(versionConfig: version_config.VersionConfig, abort, unaccounted: bool, extractedAssetsTracker: dict, manager, baseromSegmentsDir: Path, outputDir: Path): - global globalVersionConfig - global globalAbort - global globalUnaccounted - global globalExtractedAssetsTracker - global globalManager - global globalBaseromSegmentsDir - global globalOutputDir - globalVersionConfig = versionConfig - globalAbort = abort - globalUnaccounted = unaccounted - globalExtractedAssetsTracker = extractedAssetsTracker - globalManager = manager - globalBaseromSegmentsDir = baseromSegmentsDir - globalOutputDir = outputDir - -def processZAPDArgs(argsZ): - badZAPDArg = False - for z in argsZ: - if z[0] == '-': - print(f'error: argument "{z}" starts with "-", which is not supported.', file=os.sys.stderr) - badZAPDArg = True - - if badZAPDArg: - exit(1) - - ZAPDArgs = " ".join(f"-{z}" for z in argsZ) - print("Using extra ZAPD arguments: " + ZAPDArgs) - return ZAPDArgs - -def main(): - parser = argparse.ArgumentParser(description="baserom asset extractor") - parser.add_argument( - "baserom_segments_dir", - type=Path, - help="Directory of uncompressed ROM segments", - ) - parser.add_argument( - "output_dir", - type=Path, - help="Output directory to place files in", - ) - parser.add_argument("-v", "--version", dest="oot_version", help="OOT game version", default="gc-eu-mq-dbg") - parser.add_argument("-s", "--single", help="Extract a single asset by name, e.g. objects/gameplay_keep") - parser.add_argument("-f", "--force", help="Force the extraction of every xml instead of checking the touched ones (overwriting current files).", action="store_true") - parser.add_argument("-j", "--jobs", help="Number of cpu cores to extract with.") - parser.add_argument("-u", "--unaccounted", help="Enables ZAPD unaccounted detector warning system.", action="store_true") - parser.add_argument("-Z", help="Pass the argument on to ZAPD, e.g. `-ZWunaccounted` to warn about unaccounted blocks in XMLs. Each argument should be passed separately, *without* the leading dash.", metavar="ZAPD_ARG", action="append") - args = parser.parse_args() - - baseromSegmentsDir: Path = args.baserom_segments_dir - version: str = args.oot_version - outputDir: Path = args.output_dir - - args.output_dir.mkdir(parents=True, exist_ok=True) - - versionConfig = version_config.load_version_config(version) - - global ZAPDArgs - ZAPDArgs = processZAPDArgs(args.Z) if args.Z else "" - - global mainAbort - mainAbort = multiprocessing.Event() - manager = multiprocessing.Manager() - signal.signal(signal.SIGINT, SignalHandler) - - extraction_times_p = outputDir / "assets_extraction_times.json" - extractedAssetsTracker = manager.dict() - if extraction_times_p.exists() and not args.force: - with extraction_times_p.open(encoding='utf-8') as f: - extractedAssetsTracker.update(json.load(f, object_hook=manager.dict)) - - singleAssetName = args.single - if singleAssetName is not None: - assetConfig = None - for asset in versionConfig.assets: - if asset.name == singleAssetName: - assetConfig = asset - break - else: - print(f"Error. Asset {singleAssetName} not found in config.", file=os.sys.stderr) - exit(1) - - initializeWorker(versionConfig, mainAbort, args.unaccounted, extractedAssetsTracker, manager, baseromSegmentsDir, outputDir) - # Always extract if -s is used. - xml_path_str = str(assetConfig.xml_path) - if xml_path_str in extractedAssetsTracker: - del extractedAssetsTracker[xml_path_str] - ExtractFunc(assetConfig) - else: - class CannotMultiprocessError(Exception): - pass - - try: - numCores = int(args.jobs or 0) - if numCores <= 0: - numCores = 1 - print("Extracting assets with " + str(numCores) + " CPU core" + ("s" if numCores > 1 else "") + ".") - try: - mp_context = multiprocessing.get_context("fork") - except ValueError as e: - raise CannotMultiprocessError() from e - with mp_context.Pool(numCores, initializer=initializeWorker, initargs=(versionConfig, mainAbort, args.unaccounted, extractedAssetsTracker, manager, baseromSegmentsDir, outputDir)) as p: - p.map(ExtractFunc, versionConfig.assets) - except (multiprocessing.ProcessError, TypeError, CannotMultiprocessError): - print("Warning: Multiprocessing exception occurred.", file=os.sys.stderr) - print("Disabling mutliprocessing.", file=os.sys.stderr) - - initializeWorker(versionConfig, mainAbort, args.unaccounted, extractedAssetsTracker, manager, baseromSegmentsDir, outputDir) - for assetConfig in versionConfig.assets: - ExtractFunc(assetConfig) - - with extraction_times_p.open('w', encoding='utf-8') as f: - serializableDict = dict() - for xml, data in extractedAssetsTracker.items(): - serializableDict[xml] = dict(data) - json.dump(dict(serializableDict), f, ensure_ascii=False, indent=4) - - if mainAbort.is_set(): - exit(1) - -if __name__ == "__main__": - main() diff --git a/tools/extract_assets.sh b/tools/extract_assets.sh new file mode 100755 index 0000000000..bda2b587da --- /dev/null +++ b/tools/extract_assets.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash + +# SPDX-FileCopyrightText: © 2024 ZeldaRET +# SPDX-License-Identifier: CC0-1.0 + +if [ $# -eq 0 ] +then + echo "Usage: $0 [args...]" + exit 1 +fi + +v=$1 +.venv/bin/python3 -m tools.assets.extract extracted/$v/baserom extracted/$v -v $v "${@:2}"