コード例 #1
0
ファイル: mubin.py プロジェクト: NiceneNerd/BCML
    def diff_objs() -> Hash:
        base_hashes = [int(obj["HashId"]) for obj in base_map["Objs"]]
        mod_hashes = [int(obj["HashId"]) for obj in mod_map["Objs"]]

        diffs = Hash()
        diffs["add"] = Array([
            obj for obj in mod_map["Objs"]
            if int(obj["HashId"]) not in base_hashes
        ])
        diffs["mod"] = Hash({
            str(obj["HashId"]): obj
            for obj in mod_map["Objs"] if int(obj["HashId"]) in base_hashes
            and obj != base_map["Objs"][base_hashes.index(int(obj["HashId"]))]
        })
        diffs["del"] = Array([
            oead.U32(h) for h in
            {hash_id
             for hash_id in base_hashes if hash_id not in mod_hashes}
        ])

        if new_hashes:
            hash_map: Dict[int, int] = {}
            for obj in diffs["add"]:
                new_hash = crc32(oead.byml.to_text(obj).encode("utf8"))
                hash_map[obj["HashId"].v] = new_hash
                obj["HashId"] = oead.U32(new_hash)
            for obj in [*diffs["add"], *[v for k, v in diffs["mod"].items()]]:
                if "LinksToObj" in obj:
                    for link in obj["LinksToObj"]:
                        if link["DestUnitHashId"].v in hash_map:
                            link["DestUnitHashId"] = oead.U32(
                                hash_map[link["DestUnitHashId"].v])
        return diffs
コード例 #2
0
ファイル: actorinfo.py プロジェクト: krenyy/botw_tools
def actorinfo_duplicate(args: argparse.Namespace) -> None:
    actorinfo = read_actorinfo(args)

    entry_hash_from = crc32(args.entry_name_from.encode())

    if convert_hash(entry_hash_from) not in actorinfo["Hashes"]:
        raise SystemExit(
            f"'{args.entry_name_from}' doesn't exist in this file")

    entry_index_from = list(actorinfo["Hashes"]).index(
        oead.U32(entry_hash_from) if entry_hash_from > 0x80000000 else oead.
        S32(entry_hash_from))

    entry = duplicate_entry(actorinfo["Actors"][entry_index_from])
    entry["name"] = args.entry_name_to

    entry_hash_to = crc32(args.entry_name_to.encode())

    if convert_hash(entry_hash_to) in actorinfo["Hashes"]:
        raise SystemExit(f"'{args.entry_name_to}' already exists")

    entry_index_to = bisect.bisect([int(x) for x in actorinfo["Hashes"]],
                                   entry_hash_to)
    actorinfo["Hashes"].insert(entry_index_to, convert_hash(entry_hash_to))
    actorinfo["Actors"].insert(entry_index_to, entry)

    write_stdout(f"{args.entry_name_from} -> {args.entry_name_to}".encode(
        "utf-8")) if args.actorinfo and args.actorinfo.name != "-" else None
    write_actorinfo(args, actorinfo)
    return
コード例 #3
0
ファイル: actorinfo.py プロジェクト: krenyy/botw_tools
def actorinfo_edit(args: argparse.Namespace) -> None:
    actorinfo = read_actorinfo(args)

    entry_hash = crc32(args.entry_name.encode())

    if convert_hash(entry_hash) not in actorinfo["Hashes"]:
        raise SystemExit(f"'{args.entry_name}' doesn't exist in this file")

    entry_index = list(actorinfo["Hashes"]).index(
        oead.U32(entry_hash) if entry_hash > 0x80000000 else oead.
        S32(entry_hash))

    entry = actorinfo["Actors"][entry_index]

    try:
        value_before = entry[args.key]
    except KeyError:
        value_before = None
    entry[args.key] = args.value
    value_after = entry[args.key]

    write_stdout(
        f"{args.entry_name}['{args.key}']: '{value_before}' -> '{value_after}'"
        .encode("utf-8"
                )) if args.actorinfo and args.actorinfo.name != "-" else None
    write_actorinfo(args, actorinfo)
    return
コード例 #4
0
ファイル: actorinfo.py プロジェクト: krenyy/botw_tools
def actorinfo_remove(args: argparse.Namespace) -> None:
    actorinfo = read_actorinfo(args)

    entry_hash = crc32(args.entry_name.encode())

    if convert_hash(entry_hash) not in actorinfo["Hashes"]:
        raise SystemExit(f"'{args.entry_name}' doesn't exist in this file")

    entry_index = list(actorinfo["Hashes"]).index(
        oead.U32(entry_hash) if entry_hash > 0x80000000 else oead.
        S32(entry_hash))

    if not args.key:
        actorinfo["Hashes"].pop(entry_index)
        actorinfo["Actors"].pop(entry_index)
        msg = f"{args.entry_name} removed".encode("utf-8")
    else:
        try:
            del actorinfo["Actors"][entry_index][args.key]
        except KeyError:
            raise SystemExit(
                f"Key '{args.key}' doesn't exist in '{args.entry_name}'")
        msg = f"{args.entry_name}['{args.key}'] removed".encode("utf-8")

    write_stdout(
        msg) if args.actorinfo and args.actorinfo.name != "-" else None
    write_actorinfo(args, actorinfo)
    return
コード例 #5
0
ファイル: mubin.py プロジェクト: StoneyMoonCat/BCML
    def diff_objs() -> Hash:
        base_hashes = [int(obj["HashId"]) for obj in base_map["Objs"]]
        base_links = (set() if link_del else {
            int(link["DestUnitHashId"])
            for obj in base_map["Objs"]
            for link in obj.get("LinksToObj", Array()) if "LinksToObj" in obj
        })
        mod_hashes = [int(obj["HashId"]) for obj in mod_map["Objs"]]

        diffs = Hash()
        diffs["add"] = Array([
            obj for obj in mod_map["Objs"]
            if int(obj["HashId"]) not in base_hashes
        ])
        diffs["mod"] = Hash({
            str(obj["HashId"]): obj
            for obj in mod_map["Objs"] if int(obj["HashId"]) in base_hashes
            and obj != base_map["Objs"][base_hashes.index(int(obj["HashId"]))]
        })
        diffs["del"] = Array([
            oead.U32(h) for h in {
                hash_id
                for hash_id in base_hashes
                if hash_id not in {*mod_hashes, *base_links}
            }
        ] if not no_del else set())
        return diffs
コード例 #6
0
ファイル: actors.py プロジェクト: arkhamsaiyan/BCML
    def perform_merge(self):
        actor_path = (util.get_master_modpack_dir() / util.get_content_path() /
                      "Actor" / "ActorInfo.product.sbyml")
        print("Loading modded actor info...")
        modded_actors = self.consolidate_diffs(self.get_all_diffs())
        if not modded_actors:
            print("No actor info merging necessary.")
            if actor_path.exists():
                actor_path.unlink()
            return

        print("Loading unmodded actor info...")
        actorinfo = get_stock_actorinfo()
        stock_actors = {
            crc32(actor["name"].encode("utf8")): actor
            for actor in actorinfo["Actors"]
        }

        print("Merging changes...")
        new_hashes = set()
        for actor_hash, actor_info in modded_actors.items():
            if isinstance(actor_hash, str):
                actor_hash = int(actor_hash)
            if actor_hash in stock_actors:
                util.dict_merge(stock_actors[actor_hash],
                                actor_info,
                                overwrite_lists=True)
            else:
                actorinfo["Actors"].append(actor_info)
                new_hashes.add(actor_hash)

        print("Sorting new actor info...")
        actorinfo["Hashes"] = oead.byml.Array([
            oead.S32(x) if x < 2147483648 else oead.U32(x)
            for x in sorted(new_hashes | set(stock_actors.keys()))
        ])
        try:
            actorinfo["Actors"] = sorted(
                actorinfo["Actors"],
                key=lambda x: crc32(x["name"].encode("utf-8")))
        except KeyError as err:
            if str(err) == "":
                raise RuntimeError(
                    "Your actor info mods could not be merged. "
                    "This usually indicates a corrupt game dump.") from err
            else:
                raise

        print("Saving new actor info...")
        actor_path.parent.mkdir(parents=True, exist_ok=True)
        actor_path.write_bytes(
            util.compress(
                oead.byml.to_binary(actorinfo,
                                    big_endian=util.get_settings("wiiu"))))
        print("Actor info merged successfully")
コード例 #7
0
def get_actorlink_tags(
        data: oead.aamp.ParameterIO) -> Union[oead.byml.Hash, None]:
    d: Union[oead.byml.Hash, None] = None
    if "Tags" in data.objects:
        d = oead.byml.Hash()
        for _, val in data.objects["Tags"].params.items():
            taghash = zlib.crc32(val.v.encode("utf-8"))
            tagval = oead.U32(taghash) if taghash > 2147483647 else oead.S32(
                taghash)
            taghex = f"tag{padhex(hex(taghash))[2:]}"
            d[taghex] = tagval
    return d
コード例 #8
0
def _build_actorinfo(params: BuildParams):
    actors = []
    for actor_file in (params.out / params.content / "Actor" / "ActorInfo").glob(
        "*.info"
    ):
        actors.append(oead.byml.from_binary(actor_file.read_bytes()))
        actor_file.unlink()
    hashes = oead.byml.Array(
        [
            oead.S32(crc) if crc < 2147483648 else oead.U32(crc)
            for crc in sorted({crc32(a["name"].encode("utf8")) for a in actors})
        ]
    )
    actors.sort(key=lambda actor: crc32(actor["name"].encode("utf8")))
    actor_info = oead.byml.Hash({"Actors": oead.byml.Array(actors), "Hashes": hashes})
    info_path = params.out / params.content / "Actor" / "ActorInfo.product.sbyml"
    info_path.parent.mkdir(exist_ok=True, parents=True)
    info_path.write_bytes(
        compress(oead.byml.to_binary(actor_info, big_endian=params.be))
    )
コード例 #9
0
ファイル: mubin.py プロジェクト: VelouriasMoon/BCML
    def diff_objs() -> Hash:
        base_hashes = [int(obj["HashId"]) for obj in base_map["Objs"]]
        mod_hashes = [int(obj["HashId"]) for obj in mod_map["Objs"]]

        diffs = Hash()
        diffs["add"] = Array([
            obj for obj in mod_map["Objs"]
            if int(obj["HashId"]) not in base_hashes
        ])
        diffs["mod"] = Hash({
            str(obj["HashId"]): obj
            for obj in mod_map["Objs"] if int(obj["HashId"]) in base_hashes
            and obj != base_map["Objs"][base_hashes.index(int(obj["HashId"]))]
        })
        diffs["del"] = Array([
            oead.U32(h) for h in
            {hash_id
             for hash_id in base_hashes if hash_id not in mod_hashes}
        ])
        return diffs
コード例 #10
0
ファイル: builder.py プロジェクト: biD3V/Hyrule-Builder
def _build_actorinfo(params: BuildParams):
    actors = []
    for actor_file in (params.mod / params.content / 'Actor' /
                       'ActorInfo').glob('*.info.yml'):
        actors.append(
            oead.byml.from_text(actor_file.read_text(encoding='utf-8')))
    hashes = oead.byml.Array([
        oead.S32(crc) if crc < 2147483648 else oead.U32(crc)
        for crc in sorted({crc32(a['name'].encode('utf8'))
                           for a in actors})
    ])
    actors.sort(key=lambda actor: crc32(actor['name'].encode('utf8')))
    actor_info = oead.byml.Hash({
        'Actors': oead.byml.Array(actors),
        'Hashes': hashes
    })
    info_path = params.out / params.content / 'Actor' / 'ActorInfo.product.sbyml'
    info_path.parent.mkdir(exist_ok=True, parents=True)
    info_path.write_bytes(
        compress(oead.byml.to_binary(actor_info, big_endian=params.be)))
コード例 #11
0
ファイル: mubin.py プロジェクト: arkhamsaiyan/BCML
def get_map_diff(map_unit: Map,
                 tmp_dir: Path,
                 no_del: bool = False,
                 link_del: bool = False) -> Hash:
    mod_map = get_modded_map(map_unit, tmp_dir)
    stock_map = True
    for obj in mod_map["Objs"]:
        str_obj = oead.byml.to_text(obj)
        if "IsHardModeActor" in str_obj or "AoC_HardMode_Enabled" in str_obj:
            stock_map = False
            break
    base_map = get_stock_map(map_unit, force_vanilla=stock_map)

    base_hashes = [int(obj["HashId"]) for obj in base_map["Objs"]]
    base_links = (set() if link_del else {
        int(link["DestUnitHashId"])
        for obj in base_map["Objs"] for link in obj.get("LinksToObj", Array())
        if "LinksToObj" in obj
    })
    mod_hashes = [int(obj["HashId"]) for obj in mod_map["Objs"]]

    diffs = Hash()
    diffs["add"] = Array({
        obj
        for obj in mod_map["Objs"] if int(obj["HashId"]) not in base_hashes
    })
    diffs["mod"] = Hash({
        str(obj["HashId"]): obj
        for obj in mod_map["Objs"] if int(obj["HashId"]) in base_hashes
        and obj != base_map["Objs"][base_hashes.index(int(obj["HashId"]))]
    })
    diffs["del"] = Array({
        oead.U32(hash_id)
        for hash_id in base_hashes
        if hash_id not in {*mod_hashes, *base_links}
    } if not no_del else set())
    del mod_map
    del base_map
    del base_links
    del mod_hashes
    return "_".join(map_unit), oead.byml.to_text(diffs)
コード例 #12
0
ファイル: mubin.py プロジェクト: VelouriasMoon/BCML
    def diff_rails() -> Hash:
        base_hashes = [int(rail["HashId"]) for rail in base_map["Rails"]]
        mod_hashes = [int(rail["HashId"]) for rail in mod_map["Rails"]]

        diffs = Hash()
        diffs["add"] = Array([
            rail for rail in mod_map["Rails"]
            if int(rail["HashId"]) not in base_hashes
        ])
        diffs["mod"] = Hash({
            str(rail["HashId"]): rail
            for rail in mod_map["Rails"]
            if int(rail["HashId"]) in base_hashes and
            rail != base_map["Rails"][base_hashes.index(int(rail["HashId"]))]
        })
        diffs["del"] = Array([
            oead.U32(h) for h in
            {hash_id
             for hash_id in base_hashes if hash_id not in mod_hashes}
        ])
        return diffs
コード例 #13
0
ファイル: actorinfo.py プロジェクト: krenyy/botw_tools
def actorinfo_get(args: argparse.Namespace) -> None:
    actorinfo = read_actorinfo(args)
    entry_hash = crc32(args.entry_name.encode())

    if convert_hash(entry_hash) not in actorinfo["Hashes"]:
        raise SystemExit(f"'{args.entry_name}' doesn't exist in this file")

    entry_index = list(actorinfo["Hashes"]).index(
        oead.U32(entry_hash) if entry_hash > 0x80000000 else oead.
        S32(entry_hash))

    entry = actorinfo["Actors"][entry_index]

    try:
        write_stdout(
            oead.byml.to_text(entry[args.key] if args.key else entry).encode(
                "utf-8"))
        return
    except KeyError:
        raise SystemExit(
            f"Key '{args.key}' doesn't exist in '{args.entry_name}'")
コード例 #14
0
def removeActor(fileToOpen, fileName, fileExt, actorToDel, nameHash, args):
    keysToRem = []
    endian = args.endian
    fileDict = {}
    entryDict = {}
    iterate = 0
    objList = []
    deleted = False
    if (args.subStr == True):
        startWith = True
    else:
        startWith = False
#    print(fileExt)
    if fileExt == '.sblwp' or fileExt == '.blwp':
        fileToOpen = pathlib.Path(fileToOpen)
        decodedData = blwp.prod.decoder(fileToOpen)
        for key in decodedData.keys():
            if startWith == True:
                if str(key).lower().startswith(
                        str(actorToDel).lower()) == True:
                    keysToRem.append(key)
                else:
                    continue
            elif startWith == False:
                if str(key).lower() == str(actorToDel).lower():
                    keysToRem.append(key)
                else:
                    continue
            else:
                print('error')
                continue
        for key in keysToRem:
            decodedData.pop(key)
        if (args.noCompression):
            extList = []
            fileExt = fileExt.lstrip('.s')
            fileExt = ('.') + fileExt
            fileWrite = open(fileName + fileExt, 'wb')
            fileWrite.write(blwp.prod.encoder(decodedData))
            return

        else:
            fileWrite = open(fileName + fileExt, 'wb')
            fileWrite.write(oead.yaz0.compress(blwp.prod.encoder(decodedData)))
            print("Compressing file.")
        fileWrite.close()
        print('Done!')
        return
    elif fileExt == '.smubin' or fileExt == '.mubin':
        fileToOpen = open(fileToOpen, 'rb').read()
        uncompressedFile = util.checkCompression(fileToOpen)
        extractByml = oead.byml.from_binary(uncompressedFile)
        for key in extractByml.keys():
            fileDict.update({key: extractByml.get(key)})
        array = fileDict.get('Objs')

        if (int(nameHash) == 0 or str(nameHash).lower() == 'hash'):
            actorToDel = int(actorToDel)
            actorToDel = oead.U32(value=actorToDel)
        elif (int(nameHash) == 1 or str(nameHash).lower() == 'name'):
            actorToDel = str(actorToDel)
        if (array != None):
            for entry in array:
                exactItem = array[iterate]
                entryDict.update(exactItem)
                iterate += 1

                for key in entryDict.keys():
                    if (startWith == True):
                        if (str(entryDict.get(key)).lower().startswith(
                                str(actorToDel).lower()) == True):
                            deleted = True
                    elif (startWith == False):
                        if (str(entryDict.get(key)).lower() == str(
                                actorToDel).lower()):
                            deleted = True
                    else:
                        deleted = False

                if (deleted != True):
                    objList.append(oead.byml.Hash(entryDict))
                elif (deleted == True):
                    entryDict.clear()
                    deleted = False
                    continue
                entryDict.clear()
                deleted = False

            fileDict.update({'Objs': objList})
            if (args.noCompression):
                extList = []
                fileExt = fileExt.lstrip('.s')
                fileExt = ('.') + fileExt
                fileWrite = open(fileName + fileExt, 'wb')
                fileWrite.write(
                    oead.byml.to_binary(fileDict, big_endian=bool(endian)))
                return

            else:
                fileWrite = open(fileName + fileExt, 'wb')
                fileWrite.write(
                    oead.yaz0.compress(
                        oead.byml.to_binary(fileDict,
                                            big_endian=bool(endian))))
                print("Compressing file.")
            fileWrite.close()
            print('Done!')
            return
        else:
            print('could not find "Objs" parameter in the map file.')
            return
コード例 #15
0
ファイル: mubin.py プロジェクト: NiceneNerd/BCML
 def consolidate_diffs(self, diffs: list):
     a_diffs = Hash()
     for mod_diff in diffs:
         for file, diff in mod_diff.items():
             # a_map = Map(*file.split("_"))
             if file not in a_diffs:
                 a_diffs[file] = Array()
             a_diffs[file].append(diff)
     c_diffs = Hash()
     for file, mods in a_diffs.items():
         c_diffs[file] = Hash({
             "Objs":
             Hash({
                 "add":
                 Array(),
                 "mod":
                 Hash(),
                 "del":
                 Array([
                     oead.U32(h) for h in set([
                         hash_id.v for hashes in [
                             mod["Objs"]["del"] for mod in mods
                             if "Objs" in mod and "del" in mod["Objs"]
                         ] for hash_id in hashes
                     ])
                 ]),
             }),
             "Rails":
             Hash({
                 "add":
                 Array(),
                 "mod":
                 Hash(),
                 "del":
                 Array([
                     oead.U32(h) for h in set([
                         hash_id.v for hashes in [
                             mod["Rails"]["del"] for mod in mods
                             if "Rails" in mod and "del" in mod["Rails"]
                         ] for hash_id in hashes
                     ])
                 ]),
             }),
         })
         for mod in [m for m in mods if "Objs" in m and "mod" in m["Objs"]]:
             for hash_id, actor in mod["Objs"]["mod"].items():
                 c_diffs[file]["Objs"]["mod"][hash_id] = actor
         for mod in [
                 m for m in mods if "Rails" in m and "mod" in m["Rails"]
         ]:
             for hash_id, actor in mod["Rails"]["mod"].items():
                 c_diffs[file]["Rails"]["mod"][hash_id] = actor
         add_obj_hashes = []
         add_rail_hashes = []
         for mod in reversed(mods):
             if "add" in mod["Objs"]:
                 for actor in mod["Objs"]["add"]:
                     if actor["HashId"] not in add_obj_hashes:
                         add_obj_hashes.append(actor["HashId"])
                         c_diffs[file]["Objs"]["add"].append(actor)
             if "add" in mod["Rails"]:
                 for actor in mod["Rails"]["add"]:
                     if actor["HashId"] not in add_rail_hashes:
                         add_rail_hashes.append(actor["HashId"])
                         c_diffs[file]["Rails"]["add"].append(actor)
     return c_diffs
コード例 #16
0
ファイル: actor.py プロジェクト: NiceneNerd/botw_actor_tool
    def save(self, root_dir: str, be: bool) -> None:
        if self._resident:
            titlebg_path = Path(f"{root_dir}/Pack/TitleBG.pack")
            actor_dir = f"Actor/Pack/{self._pack.get_name()}.sbactorpack"
            if not titlebg_path.exists():
                titlebg_path.parent.mkdir(parents=True, exist_ok=True)
                shutil.copy(util.find_file(Path("Pack/TitleBG.pack")),
                            titlebg_path)
            yaz0_bytes = oead.yaz0.compress(self._pack.get_bytes(be))
            util.inject_bytes_into_sarc(titlebg_path, actor_dir, yaz0_bytes)
        else:
            actor_path = Path(
                f"{root_dir}/Actor/Pack/{self._pack.get_name()}.sbactorpack")
            yaz0_bytes = oead.yaz0.compress(self._pack.get_bytes(be))
            if not actor_path.exists():
                actor_path.parent.mkdir(parents=True, exist_ok=True)
                actor_path.touch()
            actor_path.write_bytes(yaz0_bytes)

        hash = crc32(self._pack.get_name().encode("utf-8"))
        info = self.get_info()

        if self._has_far:
            actor_path = Path(
                f"{root_dir}/Actor/Pack/{self._far_pack.get_name()}.sbactorpack"
            )
            yaz0_bytes = oead.yaz0.compress(self._far_pack.get_bytes(be))
            if not actor_path.exists():
                actor_path.touch()
            actor_path.write_bytes(yaz0_bytes)

            far_hash = crc32(self._far_pack.get_name().encode("utf-8"))
            far_info = self.get_far_info()

        actorinfo_path = Path(f"{root_dir}/Actor/ActorInfo.product.sbyml")
        actorinfo_load_path = actorinfo_path
        if not actorinfo_load_path.exists():
            actorinfo_load_path.touch()
            actorinfo_load_path = Path(
                util.find_file(Path("Actor/ActorInfo.product.sbyml")))
        actorinfo = oead.byml.from_binary(
            oead.yaz0.decompress(actorinfo_load_path.read_bytes()))

        hashes = [int(h) for h in actorinfo["Hashes"]]
        try:
            hash_index = hashes.index(hash)
        except ValueError:
            hashes.append(hash)
            hashes.sort()
            hash_index = hashes.index(hash)
            actorinfo["Actors"].insert(hash_index, oead.byml.Hash())
        if self._has_far:
            try:
                far_hash_index = hashes.index(far_hash)
            except ValueError:
                hashes.append(far_hash)
                hashes.sort()
                far_hash_index = hashes.index(far_hash)
                actorinfo["Actors"].insert(far_hash_index, oead.byml.Hash())
        actorinfo["Hashes"] = oead.byml.Array(
            [oead.U32(h) if h > 2147483647 else oead.S32(h) for h in hashes])

        actorinfo["Actors"][hash_index] = info
        if self._has_far:
            actorinfo["Actors"][far_hash_index] = far_info

        actorinfo_path.write_bytes(
            oead.yaz0.compress(oead.byml.to_binary(actorinfo, be)))

        self._texts.write(root_dir, be)

        bootup_path = Path(f"{root_dir}/Pack/Bootup.pack")
        if not bootup_path.exists():
            bootup_path.parent.mkdir(parents=True, exist_ok=True)
            shutil.copy(util.find_file(Path("Pack/Bootup.pack")), bootup_path)

        gamedata_sarc = util.get_gamedata_sarc(bootup_path)
        for bgdata_name, bgdata_hash in map(util.unpack_oead_file,
                                            gamedata_sarc.get_files()):
            self._flags.add_flags_from_Hash(bgdata_name, bgdata_hash, False)

        files_to_write: list = []
        files_to_write.append("GameData/gamedata.ssarc")
        files_to_write.append("GameData/savedataformat.ssarc")
        orig_files = util.get_last_two_savedata_files(bootup_path)
        datas_to_write: list = []
        datas_to_write.append(
            oead.yaz0.compress(util.make_new_gamedata(self._flags, be)))
        datas_to_write.append(
            oead.yaz0.compress(
                util.make_new_savedata(self._flags, be, orig_files)))
        util.inject_files_into_bootup(bootup_path, files_to_write,
                                      datas_to_write)
コード例 #17
0
ファイル: actorinfo.py プロジェクト: krenyy/botw_tools
def convert_hash(x: int) -> Union[oead.S32, oead.U32]:
    return oead.U32(x) if x > 0x80000000 else oead.S32(x)
コード例 #18
0
def create_hash(x):
    result = zlib.crc32(bytes(x.encode()))
    if result < 2147483647:
        return oead.S32(result)
    else:
        return oead.U32(result)
コード例 #19
0
def replaceActor(fileToOpen, fileName, fileExt, nameHash, convFrom, convTo,
                 args):
    endian = args.endian
    try:
        paramDB = util.loadActorDatabase()
    except:
        return
    if (args.subStr == True):
        startWith = True
    else:
        startWith = False
    fileDict = {}
    paramDict = {}
    entryDict = {}
    iterate = 0
    objList = []
    fileToOpen = open(fileToOpen, 'rb').read()
    uncompressedFile = util.checkCompression(fileToOpen)
    extractByml = oead.byml.from_binary(uncompressedFile)
    for key in extractByml.keys():
        fileDict.update({key: extractByml.get(key)})
    array = list(fileDict.get('Objs'))

    if (int(nameHash) == 0 or str(nameHash).lower() == 'hash'):
        convFrom = oead.U32(value=int(convFrom))
    elif (int(nameHash) == 1 or str(nameHash).lower() == 'name'):
        convFrom = str(convFrom)

    if (convTo in paramDB.keys()):
        for entry in array:
            exactItem = dict(entry)
            #            print(dict(entry))
            entryDict.update(exactItem)
            iterate += 1

            for key in entryDict.keys():
                if (startWith == True):
                    if (str(entryDict.get(key)).lower().startswith(
                            str(convFrom).lower()) == True):
                        entryDict.update({'UnitConfigName': convTo})
                        #                        print('using startswith')
                        #                        print(dict(entryDict.get('!Parameters')))
                        if (paramDB.get(convTo) is not None):
                            paramDBGet = util.dictParamsToByml(
                                paramDB.get(convTo))
                            paramDict.update((paramDBGet))
                            #                            print(paramDict)
                            #                           print(paramDBGet)
                            entryDict.update({"!Parameters": dict(paramDict)})
#                            print(oead.byml.Hash(paramDict))
#                            print(entryDict)
#                            print(paramDict)
#                            entryDict.update({"!Parameters": paramDict})
#                            print(util.dictParamsToByml(paramDB.get(convTo)))
                        else:
                            try:
                                entryDict.pop(str("!Parameters"))
                            except:
                                continue
                        break
                    else:
                        continue

                elif (startWith == False):
                    if (str(entryDict.get(key)).lower() == str(
                            convFrom).lower()):
                        entryDict.update({'UnitConfigName': convTo})
                        #                        print(dict(entryDict.get('!Parameters')))
                        if (paramDB.get(convTo) is not None):
                            paramDBGet = util.dictParamsToByml(
                                paramDB.get(convTo))
                            paramDict.update((paramDBGet))
                            #                            print(paramDict)
                            #                           print(paramDBGet)
                            entryDict.update({"!Parameters": dict(paramDict)})
#                            print(oead.byml.Hash(paramDict))
#                            print(entryDict)
#                            print(paramDict)
#                            entryDict.update({"!Parameters": paramDict})
#                            print(util.dictParamsToByml(paramDB.get(convTo)))
                        else:
                            try:
                                entryDict.pop(str("!Parameters"))
                            except:
                                continue
                        break
                    else:
                        continue
                else:
                    print('How did you end up here?')
                    return
#            try:
#                print(dict(dict(entryDict).get('!Parameters')))
#            except:
#                print('woops')
            objList.append(dict(entryDict))
            entryDict.clear()
            paramDict.clear()
#        print(objList)
#        print(objList)
        fileDict.update({'Objs': oead.byml.Array(objList)})
        fileDict = (fileDict)
        if (args.noCompression):
            extList = []
            fileExt = fileExt.lstrip('.s')
            fileExt = ('.') + fileExt
            fileWrite = open(fileName + fileExt, 'wb')
            fileWrite.write(
                oead.byml.to_binary(fileDict, big_endian=bool(endian)))

        else:
            fileWrite = open(fileName + fileExt, 'wb')
            fileWrite.write(
                oead.yaz0.compress(
                    oead.byml.to_binary(fileDict, big_endian=bool(endian))))
            print("Compressing file.")

        fileWrite.close()
        print('Done!')
    else:
        print(
            f'Error: Could not find the value {convTo} in the database. Check your spelling and/or capitalization or try regenerating the database.'
        )
コード例 #20
0
def yml_to_sbyml(a):
    bigendian: bool = a.bigendian
    startpath = Path.cwd() / Path("CookData.yml")
    cookdata = oead.byml.from_text(startpath.read_text())

    for recipe in cookdata["Recipes"]:
        if "Actors" in recipe:
            for combo in recipe["Actors"]:
                idx = 0
                for idx in range(len(combo)):
                    try:
                        combo[idx] = oead.U32(
                            ctypes.c_uint32(zlib.crc32(
                                combo[idx].encode())).value)
                    except AttributeError:
                        continue
        if "Tags" in recipe:
            for taglist in recipe["Tags"]:
                idx = 0
                for idx in range(len(taglist)):
                    try:
                        taglist[idx] = oead.U32(
                            ctypes.c_uint32(zlib.crc32(
                                taglist[idx].encode())).value)
                    except AttributeError:
                        continue
        try:
            recipe["Recipe"] = oead.U32(
                ctypes.c_uint32(zlib.crc32(recipe["Recipe"].encode())).value)
        except AttributeError:
            continue

    for recipe in cookdata["SingleRecipes"]:
        if "Actors" in recipe:
            idx = 0
            for idx in range(len(recipe["Actors"])):
                try:
                    recipe["Actors"][idx] = oead.U32(
                        ctypes.c_uint32(
                            zlib.crc32(recipe["Actors"][idx].encode())).value)
                except AttributeError:
                    continue
        if "Tags" in recipe:
            idx = 0
            for idx in range(len(recipe["Tags"])):
                try:
                    recipe["Tags"][idx] = oead.U32(
                        ctypes.c_uint32(
                            zlib.crc32(recipe["Tags"][idx].encode())).value)
                except AttributeError:
                    continue
        try:
            recipe["Recipe"] = oead.U32(
                ctypes.c_uint32(zlib.crc32(recipe["Recipe"].encode())).value)
        except AttributeError:
            continue

    endpath = Path.cwd() / Path("CookData.sbyml")

    if not endpath.exists():
        endpath.touch()

    endpath.write_bytes(
        oead.yaz0.compress(oead.byml.to_binary(cookdata, bigendian)))