Esempio n. 1
0
    def __init__(self, cx, cz, world, data=None, create=False):
        """
        :param cx, cz int, int Coordinates of the chunk
        :param data List of 3 strings. (83200 bytes of terrain data, tile-entity data, entity data)
        :param world PocketLeveldbWorld, instance of the world the chunk belongs too
        """
        self.chunkPosition = (cx, cz)
        self.world = world

        if create:
            self.Blocks = numpy.zeros(32768, 'uint16')
            self.Data = numpy.zeros(16384, 'uint8')
            self.SkyLight = numpy.zeros(16384, 'uint8')
            self.BlockLight = numpy.zeros(16384, 'uint8')
            self.DirtyColumns = numpy.zeros(256, 'uint8')
            self.GrassColors = numpy.zeros(1024, 'uint8')

            self.TileEntities = nbt.TAG_List()
            self.Entities = nbt.TAG_List()

        else:
            terrain = numpy.fromstring(data[0], dtype='uint8')
            if data[1] is not None:
                TileEntities = loadNBTCompoundList(data[1])
                self.TileEntities = nbt.TAG_List(TileEntities,
                                                 list_type=nbt.TAG_COMPOUND)

            if data[2] is not None:
                Entities = loadNBTCompoundList(data[2])
                # PE saves entities with their int ID instead of string name. We swap them to make it work in mcedit.
                # Whenever we save an entity, we need to make sure to swap back.
                invertEntities = {
                    v: k
                    for k, v in entity.PocketEntity.entityList.items()
                }
                for ent in Entities:
                    # Get the string id, or a build one
                    v = ent["id"].value
                    id = invertEntities.get(v, "Entity %s" % v)
                    # Add the built one to the entities
                    if id not in entity.PocketEntity.entityList.keys():
                        logger.warning("Found unknown entity '%s'" % v)
                        entity.PocketEntity.entityList[id] = v
                    ent["id"] = nbt.TAG_String(id)
                self.Entities = nbt.TAG_List(Entities,
                                             list_type=nbt.TAG_COMPOUND)

            self.Blocks, terrain = terrain[:32768], terrain[32768:]
            self.Data, terrain = terrain[:16384], terrain[16384:]
            self.SkyLight, terrain = terrain[:16384], terrain[16384:]
            self.BlockLight, terrain = terrain[:16384], terrain[16384:]
            self.DirtyColumns, terrain = terrain[:256], terrain[256:]

            # Unused at the moment. Might need a special editor? Maybe hooked up to biomes?
            self.GrassColors = terrain[:1024]

        self._unpackChunkData()
        self.shapeChunkData()
Esempio n. 2
0
    def TileEntities(self):
        chestTag = nbt.TAG_Compound()
        chestTag["id"] = nbt.TAG_String("Chest")
        chestTag["Items"] = nbt.TAG_List(self.root_tag["Inventory"])
        chestTag["x"] = nbt.TAG_Int(0)
        chestTag["y"] = nbt.TAG_Int(0)
        chestTag["z"] = nbt.TAG_Int(0)

        return nbt.TAG_List([chestTag], name="TileEntities")
Esempio n. 3
0
    def TileEntities(self):
        chestTag = nbt.TAG_Compound()
        chest_id = "Chest"
        split_ver = self.gameVersion.split('.')
        if int(split_ver[0]) >= 1 and int(split[1]) >= 11:
            chest_id = "minecraft:chest"
        chestTag["id"] = nbt.TAG_String(chest_id)
        chestTag["Items"] = nbt.TAG_List(self.root_tag["Inventory"])
        chestTag["x"] = nbt.TAG_Int(0)
        chestTag["y"] = nbt.TAG_Int(0)
        chestTag["z"] = nbt.TAG_Int(0)

        return nbt.TAG_List([chestTag], name="TileEntities")
Esempio n. 4
0
    def _getFakeChunkEntities(self, cx, cz):
        """distribute entities into sublists based on fake chunk position
        _fakeEntities keys are (cx, cz) and values are (Entities, TileEntities, TileTicks)"""
        if self._fakeEntities is None:
            self._fakeEntities = defaultdict(lambda: (nbt.TAG_List(), nbt.TAG_List(), nbt.TAG_List()))
            for i, e in enumerate((self.Entities, self.TileEntities, self.TileTicks)):
                for ent in e:
                    x, y, z = [Entity, TileEntity, TileTick][i].pos(ent)
                    ecx, ecz = map(lambda x: (int(floor(x)) >> 4), (x, z))

                    self._fakeEntities[ecx, ecz][i].append(ent)

        return self._fakeEntities[cx, cz]
Esempio n. 5
0
 def save(self, level):
     objectiveList = nbt.TAG_List()
     teamList = nbt.TAG_List()
     for objective in level.scoreboard.Objectives:
         objectiveList.append(objective.getTAGStructure())
     for team in level.scoreboard.Teams:
         teamList.append(team.getTAGStructure())
     level.scoreboard.root_tag["data"]["Objectives"] = objectiveList
     level.scoreboard.root_tag["data"]["Teams"] = teamList
     print "Saving Scoreboard...."
     #with open(level.worldFolder.getFolderPath("data")+"/scoreboard.dat", 'w') as datFile:
     level.scoreboard.root_tag.save(
         level.worldFolder.getFolderPath("data") + "/scoreboard.dat")
Esempio n. 6
0
class INVEditChest(MCSchematic):
    Width = 1
    Height = 1
    Length = 1
    Data = array([[[0]]], 'uint8')
    Entities = nbt.TAG_List()
    Materials = alphaMaterials

    @classmethod
    def _isTagLevel(cls, root_tag):
        return "Inventory" in root_tag

    def __init__(self, root_tag, filename):

        self.Blocks = array([[[alphaMaterials.Chest.ID]]], 'uint8')

        if filename:
            self.filename = filename
            if None is root_tag:
                try:
                    root_tag = nbt.load(filename)
                except IOError, e:
                    log.info(u"Failed to load file {0}".format(e))
                    raise
        else:
Esempio n. 7
0
  def __init__(self, cmd="", hover="", block="I", d="u", cond=False, redstone=False, time=0, first=False):
    name = "minecraft:" + self.nameMap[block]
    dv = self.dMap[d]
    if cond:
      dv += 8
    nbtData = nbt.TAG_Compound("", [])
    nbtData.add(nbt.TAG_Byte("auto", int(not redstone)))
    nbtData.add(nbt.TAG_String("Command", cmd))
    nbtData.add(nbt.TAG_String("CustomName", hover))
    nbtData.add(nbt.TAG_Byte("powered", int(block == "R" and not redstone)))
    if time == 0 and not first:
      nbtData.add(nbt.TAG_Int("Version", 8))
    else:
      nbtData.add(nbt.TAG_Int("Version", 9))
      nbtData.add(nbt.TAG_Byte("ExecuteOnFirstTick", int(first)))
      nbtData.add(nbt.TAG_Int("TickDelay", time))

    nbtData.add(nbt.TAG_Byte("conditionMet", 0))
    nbtData.add(nbt.TAG_String("id", "CommandBlock"))
    nbtData.add(nbt.TAG_Byte("isMovable", 1))
    nbtData.add(nbt.TAG_Int("LPCommandMode", 0)) # Not sure what these LPModes do. This works.
    nbtData.add(nbt.TAG_Byte("LPConditionalMode", 0))
    nbtData.add(nbt.TAG_Byte("LPRedstoneMode", 0))
    nbtData.add(nbt.TAG_Long("LastExecution", 0))
    nbtData.add(nbt.TAG_String("LastOutput", ""))
    nbtData.add(nbt.TAG_List("LastOutputParams", []))
    nbtData.add(nbt.TAG_Int("SuccessCount", 0))
    nbtData.add(nbt.TAG_Byte("TrackOutput", 1))
    super().__init__(name, dv, nbtData)
Esempio n. 8
0
    def copyWithOffset(cls, entity, copyOffset, regenerateUUID=False):
        eTag = deepcopy(entity)

        # Need to check the content of the copy to regenerate the possible sub entities UUIDs.
        # A simple fix for the 1.9+ minecarts is proposed.

        positionTags = map(lambda p, co: nbt.TAG_Double(p.value + co),
                           eTag["Pos"], copyOffset)
        eTag["Pos"] = nbt.TAG_List(positionTags)

        # Also match the 'minecraft:XXX' names
        #         if eTag["id"].value in ("Painting", "ItemFrame", u'minecraft:painting', u'minecraft:item_frame'):
        #             print "#" * 40
        #             print eTag
        #             eTag["TileX"].value += copyOffset[0]
        #             eTag["TileY"].value += copyOffset[1]
        #             eTag["TileZ"].value += copyOffset[2]

        # Trying more agnostic way
        if eTag.get('TileX') and eTag.get('TileY') and eTag.get('TileZ'):
            eTag["TileX"].value += copyOffset[0]
            eTag["TileY"].value += copyOffset[1]
            eTag["TileZ"].value += copyOffset[2]

        if "Riding" in eTag:
            eTag["Riding"] = Entity.copyWithOffset(eTag["Riding"], copyOffset)

        # # Fix for 1.9+ minecarts
        if "Passengers" in eTag:
            passengers = nbt.TAG_List()
            for passenger in eTag["Passengers"]:
                passengers.append(
                    Entity.copyWithOffset(passenger, copyOffset,
                                          regenerateUUID))
            eTag["Passengers"] = passengers
        # #

        if regenerateUUID:
            # Courtesy of SethBling
            eTag["UUIDMost"] = nbt.TAG_Long((random.getrandbits(47) << 16)
                                            | (1 << 12)
                                            | random.getrandbits(12))
            eTag["UUIDLeast"] = nbt.TAG_Long(-(
                (7 << 60) | random.getrandbits(60)))
        return eTag
Esempio n. 9
0
 def setPlayerOrientation(self, yp, player="Player"):
     """
     Gets the players orientation.
     :param player: string of the name of the player. "Player" for SSP player, player_<client-id> for SMP player.
     :param yp: int tuple (yaw, pitch)
     :return: None
     """
     self.getPlayerTag(player)["Rotation"] = nbt.TAG_List(
         [nbt.TAG_Float(p) for p in yp])
Esempio n. 10
0
class INVEditChest(MCSchematic):
    Width = 1
    Height = 1
    Length = 1
    Data = array([[[0]]], 'uint8')
    Entities = nbt.TAG_List()
    Materials = alphaMaterials

    @classmethod
    def _isTagLevel(cls, root_tag):
        return "Inventory" in root_tag

    def __init__(self, root_tag, filename):

        self.Blocks = array([[[alphaMaterials.Chest.ID]]], 'uint8')

        if filename:
            self.filename = filename
            if None is root_tag:
                try:
                    root_tag = nbt.load(filename)
                except IOError as e:
                    log.info(u"Failed to load file {0}".format(e))
                    raise
        else:
            assert root_tag, "Must have either root_tag or filename"
            self.filename = None

        for item in list(root_tag["Inventory"]):
            slot = item["Slot"].value
            if slot < 9 or slot >= 36:
                root_tag["Inventory"].remove(item)
            else:
                item[
                    "Slot"].value -= 9  # adjust for different chest slot indexes

        self.root_tag = root_tag

    @property
    def TileEntities(self):
        chestTag = nbt.TAG_Compound()
        chest_id = "Chest"
        if self.gamePlatform == "Java":
            split_ver = self.gameVersionNumber.split('.')
        else:
            split_ver = self.gamePlatform.split('.')
        if int(split_ver[0]) >= 1 and int(split_ver[1]) >= 11:
            chest_id = "minecraft:chest"
        chestTag["id"] = nbt.TAG_String(chest_id)
        chestTag["Items"] = nbt.TAG_List(self.root_tag["Inventory"])
        chestTag["x"] = nbt.TAG_Int(0)
        chestTag["y"] = nbt.TAG_Int(0)
        chestTag["z"] = nbt.TAG_Int(0)

        return nbt.TAG_List([chestTag], name="TileEntities")
Esempio n. 11
0
 def toNBT(self):
     root = nbt.TAG_Compound()
     root['BlockStates'] = nbt.TAG_Long_Array(self.__old_blockstates)
     root['Y'] = nbt.TAG_Byte(self._y)
     root['BlockLight'] = nbt.TAG_Byte_Array(self._block_light)
     root['SkyLight'] = nbt.TAG_Byte_Array(self._sky_light)
     palette = nbt.TAG_List()
     for block in self.palette:
         palette.append(block.toNBT())
     root['Palette'] = self._palette
     return root
Esempio n. 12
0
    def copyWithOffset(cls, entity, copyOffset):
        eTag = deepcopy(entity)

        positionTags = map(lambda p, co: nbt.TAG_Double(p.value + co),
                           eTag["Pos"], copyOffset)
        eTag["Pos"] = nbt.TAG_List(positionTags)

        if eTag["id"].value in ("Painting", "ItemFrame"):
            eTag["TileX"].value += copyOffset[0]
            eTag["TileY"].value += copyOffset[1]
            eTag["TileZ"].value += copyOffset[2]

        return eTag
Esempio n. 13
0
    def save(self):
        root = self._nbt

        root['Level']['Biomes'] = nbt.TAG_Byte_Array(self._biomes)
        root['Level']['HeightMap'] = nbt.TAG_Int_Array(
            self._height_map.ravel())

        tile_entities = nbt.TAG_List()
        for te in self._tile_entities:
            tile_entities.append(te)
        root['Level']['TileEntities'] = tile_entities

        entities = nbt.TAG_List()
        for e in self._entities:
            entities.append(e)
        root['Level']['Entities'] = entities

        sections = nbt.TAG_List()
        for section in self._sections.itervalues():
            sections.append(section.toNBT())
        root['Level']['Sections'] = sections

        self.region.saveChunk(self.cx, self.cz, root.save(compressed=False))
Esempio n. 14
0
    def testCreate(self):
        "Create an indev level."

        "The root of an NBT file is always a TAG_Compound."
        level = nbt.TAG_Compound(name="MinecraftLevel")

        "Subtags of a TAG_Compound are automatically named when you use the [] operator."
        level["About"] = nbt.TAG_Compound()
        level["About"]["Author"] = nbt.TAG_String("codewarrior")

        level["Environment"] = nbt.TAG_Compound()
        level["Environment"]["SkyBrightness"] = nbt.TAG_Byte(16)
        level["Environment"]["SurroundingWaterHeight"] = nbt.TAG_Short(32)

        "You can also create and name a tag before adding it to the compound."
        spawn = nbt.TAG_List(
            (nbt.TAG_Short(100), nbt.TAG_Short(45), nbt.TAG_Short(55)))
        spawn.name = "Spawn"

        mapTag = nbt.TAG_Compound()
        mapTag.add(spawn)
        mapTag.name = "Map"
        level.add(mapTag)

        "I think it looks more familiar with [] syntax."

        l, w, h = 128, 128, 128
        mapTag["Height"] = nbt.TAG_Short(h)  # y dimension
        mapTag["Length"] = nbt.TAG_Short(l)  # z dimension
        mapTag["Width"] = nbt.TAG_Short(w)  # x dimension

        "Byte arrays are stored as numpy.uint8 arrays. "

        mapTag["Blocks"] = nbt.TAG_Byte_Array()
        mapTag["Blocks"].value = numpy.zeros(
            l * w * h, dtype=numpy.uint8)  # create lots of air!

        "The blocks array is indexed (y,z,x) for indev levels, so reshape the blocks"
        mapTag["Blocks"].value.shape = (h, l, w)

        "Replace the bottom layer of the indev level with wood"
        mapTag["Blocks"].value[0, :, :] = 5

        "This is a great way to learn the power of numpy array slicing and indexing."

        mapTag["Data"] = nbt.TAG_Byte_Array()
        mapTag["Data"].value = numpy.zeros(l * w * h, dtype=numpy.uint8)

        return level
Esempio n. 15
0
 def getTAGStructure(self):
     tag = nbt.TAG_Compound()
     tag["Name"] = nbt.TAG_String(self.name)
     tag["DisplayName"] = nbt.TAG_String(self.displayName)
     tag["Prefix"] = nbt.TAG_String(self.prefix)
     tag["Suffix"] = nbt.TAG_String(self.suffix)
     if self.color != None:
         tag["TeamColor"] = nbt.TAG_String(self.color)
     tag["NameTagVisibility"] = nbt.TAG_String(self.nametags)
     tag["DeathMessageVisibility"] = nbt.TAG_String(self.deathMessage)
     tag["AllowFriendlyFire"] = nbt.TAG_Byte(self.friendlyFire)
     tag["SeeFriendlyInvisibles"] = nbt.TAG_Byte(self.friendlyInvisibles)
     players = nbt.TAG_List()
     for member in self.teamMembers:
         players.append(nbt.TAG_String(member))
     tag["Players"] = players
     return tag
Esempio n. 16
0
    def chestWithItemID(cls, itemID, count=64, damage=0):
        """ Creates a chest with a stack of 'itemID' in each slot.
        Optionally specify the count of items in each stack. Pass a negative
        value for damage to create unnaturally sturdy tools. """
        root_tag = nbt.TAG_Compound()
        invTag = nbt.TAG_List()
        root_tag["Inventory"] = invTag
        for slot in range(9, 36):
            itemTag = nbt.TAG_Compound()
            itemTag["Slot"] = nbt.TAG_Byte(slot)
            itemTag["Count"] = nbt.TAG_Byte(count)
            itemTag["id"] = nbt.TAG_Short(itemID)
            itemTag["Damage"] = nbt.TAG_Short(damage)
            invTag.append(itemTag)

        chest = INVEditChest(root_tag, "")

        return chest
Esempio n. 17
0
    def copyWithOffset(cls, entity, copyOffset, regenerateUUID=False):
        eTag = deepcopy(entity)

        positionTags = map(lambda p, co: nbt.TAG_Double(p.value + co), eTag["Pos"], copyOffset)
        eTag["Pos"] = nbt.TAG_List(positionTags)

        if eTag["id"].value in ("Painting", "ItemFrame"):
            eTag["TileX"].value += copyOffset[0]
            eTag["TileY"].value += copyOffset[1]
            eTag["TileZ"].value += copyOffset[2]

        if "Riding" in eTag:
            eTag["Riding"] = Entity.copyWithOffset(eTag["Riding"], copyOffset)

        if regenerateUUID:
            # Courtesy of SethBling
            eTag["UUIDMost"] = nbt.TAG_Long((random.getrandbits(47) << 16) | (1 << 12) | random.getrandbits(12))
            eTag["UUIDLeast"] = nbt.TAG_Long(-((7 << 60) | random.getrandbits(60)))
        return eTag
Esempio n. 18
0
    def testModify(self):
        level = self.testCreate()

        # Most of the value types work as expected. Here, we replace the entire tag with a TAG_String
        level["About"]["Author"] = nbt.TAG_String("YARRR~!")

        # Because the tag type usually doesn't change,
        # we can replace the string tag's value instead of replacing the entire tag.
        level["About"]["Author"].value = "Stew Pickles"

        # Remove members of a TAG_Compound using del, similar to a python dict.
        del (level["About"])

        # Replace all of the wood blocks with gold using a boolean index array
        blocks = level["Map"]["Blocks"].value
        blocks[blocks == 5] = 41

        level["Entities"][0] = nbt.TAG_Compound([
            nbt.TAG_String("Creeper", "id"),
            nbt.TAG_List([nbt.TAG_Double(d) for d in (1, 1, 1)], "Pos")
        ])
Esempio n. 19
0
    def toSchematic(self):
        schem = MCSchematic(shape=self.Size, mats=self._mat)
        for (x, y, z), value in ndenumerate(self._blocks):
            b_id, b_data = value
            schem.Blocks[x, z, y] = b_id
            schem.Data[x, z, y] = b_data

        for (x, y, z), value in ndenumerate(self._tile_entities):
            if not value:
                continue
            tag = value
            tag["x"] = nbt.TAG_Int(x)
            tag["y"] = nbt.TAG_Int(y)
            tag["z"] = nbt.TAG_Int(z)
            schem.addTileEntity(tag)

        entity_list = nbt.TAG_List()
        for e in self._entities:
            entity_list.append(e)
        schem.root_tag["Entities"] = entity_list

        return schem
Esempio n. 20
0
 def _getFakeChunkEntities(self, cx, cz):
     """Returns Entities, TileEntities"""
     return nbt.TAG_List(), nbt.TAG_List()
Esempio n. 21
0
 def setpos(cls, tag, pos):
     tag["Pos"] = nbt.TAG_List([nbt.TAG_Double(p) for p in pos])
Esempio n. 22
0
    def __init__(self, shape=None, root_tag=None, filename=None, mats='Alpha'):
        """ shape is (x,y,z) for a new level's shape.  if none, takes
        root_tag as a TAG_Compound for an existing schematic file.  if
        none, tries to read the tag from filename.  if none, results
        are undefined. materials can be a MCMaterials instance, or one of
        "Classic", "Alpha", "Pocket" to indicate allowable blocks. The default
        is Alpha.

        block coordinate order in the file is y,z,x to use the same code as classic/indev levels.
        in hindsight, this was a completely arbitrary decision.

        the Entities and TileEntities are nbt.TAG_List objects containing TAG_Compounds.
        this makes it easy to copy entities without knowing about their insides.

        rotateLeft swaps the axes of the different arrays.  because of this, the Width, Height, and Length
        reflect the current dimensions of the schematic rather than the ones specified in the NBT structure.
        I'm not sure what happens when I try to re-save a rotated schematic.
        """

        if filename:
            self.filename = filename
            if None is root_tag and os.path.exists(filename):
                root_tag = nbt.load(filename)
        else:
            self.filename = None

        if mats in namedMaterials:
            self.materials = namedMaterials[mats]
        else:
            assert (isinstance(mats, MCMaterials))
            self.materials = mats

        if root_tag:
            self.root_tag = root_tag
            if "Materials" in root_tag:
                self.materials = namedMaterials[self.Materials]
            else:
                root_tag["Materials"] = nbt.TAG_String(self.materials.name)

            w = self.root_tag["Width"].value
            l = self.root_tag["Length"].value
            h = self.root_tag["Height"].value

            self._Blocks = self.root_tag["Blocks"].value.astype('uint16').reshape(h, l, w)  # _Blocks is y, z, x
            del self.root_tag["Blocks"]
            if "AddBlocks" in self.root_tag:
                # Use WorldEdit's "AddBlocks" array to load and store the 4 high bits of a block ID.
                # Unlike Minecraft's NibbleArrays, this array stores the first block's bits in the
                # 4 high bits of the first byte.

                size = (h * l * w)

                # If odd, add one to the size to make sure the adjacent slices line up.
                add = zeros(size + (size & 1), 'uint16')

                # Fill the even bytes with data
                add[::2] = self.root_tag["AddBlocks"].value

                # Copy the low 4 bits to the odd bytes
                add[1::2] = add[::2] & 0xf

                # Shift the even bytes down
                add[::2] >>= 4

                # Shift every byte up before merging it with Blocks
                add <<= 8
                self._Blocks |= add[:size].reshape(h, l, w)
                del self.root_tag["AddBlocks"]

            self.root_tag["Data"].value = self.root_tag["Data"].value.reshape(h, l, w)

            if "Biomes" in self.root_tag:
                self.root_tag["Biomes"].value.shape = (l, w)

        else:
            assert shape is not None
            root_tag = nbt.TAG_Compound(name="Schematic")
            root_tag["Height"] = nbt.TAG_Short(shape[1])
            root_tag["Length"] = nbt.TAG_Short(shape[2])
            root_tag["Width"] = nbt.TAG_Short(shape[0])

            root_tag["Entities"] = nbt.TAG_List()
            root_tag["TileEntities"] = nbt.TAG_List()
            root_tag["Materials"] = nbt.TAG_String(self.materials.name)

            self._Blocks = zeros((shape[1], shape[2], shape[0]), 'uint16')
            root_tag["Data"] = nbt.TAG_Byte_Array(zeros((shape[1], shape[2], shape[0]), uint8))

            root_tag["Biomes"] = nbt.TAG_Byte_Array(zeros((shape[2], shape[0]), uint8))

            self.root_tag = root_tag

        self.root_tag["Data"].value &= 0xF  # discard high bits
Esempio n. 23
0
 def setPlayerPosition(self, pos, player="Ignored"):
     for x in self.root_tag["Entities"]:
         if x["id"].value == "LocalPlayer":
             x["Pos"] = nbt.TAG_List([nbt.TAG_Float(p) for p in pos])
Esempio n. 24
0
    def saveToFile(self, filename=None):
        if filename is None:
            filename = self.filename
        if filename is None:
            log.warn(u"Attempted to save an unnamed file in place")
            return  # you fool!

        self.Data <<= 4
        self.Data |= (self.BlockLight & 0xf)

        self.Blocks = swapaxes(self.Blocks, 0, 2)
        self.Data = swapaxes(self.Data, 0, 2)

        mapTag = nbt.TAG_Compound()
        mapTag["Width"] = nbt.TAG_Short(self.Width)
        mapTag["Height"] = nbt.TAG_Short(self.Height)
        mapTag["Length"] = nbt.TAG_Short(self.Length)
        mapTag["Blocks"] = nbt.TAG_Byte_Array(self.Blocks)
        mapTag["Data"] = nbt.TAG_Byte_Array(self.Data)

        self.Blocks = swapaxes(self.Blocks, 0, 2)
        self.Data = swapaxes(self.Data, 0, 2)

        mapTag[Spawn] = nbt.TAG_List([nbt.TAG_Short(i) for i in self.Spawn])

        self.root_tag["Map"] = mapTag

        self.Entities.append(self.LocalPlayer)
        # fix up Entities imported from Alpha worlds

        def numbersToFloats(ent):
            for attr in "Motion", "Pos":
                if attr in ent:
                    ent[attr] = nbt.TAG_List([nbt.TAG_Double(t.value) for t in ent[attr]])

        for ent in self.Entities:
            numbersToFloats(ent)

        # fix up TileEntities imported from Alpha worlds.
        for ent in self.TileEntities:
            if "Pos" not in ent and all(c in ent for c in 'xyz'):
                ent["Pos"] = nbt.TAG_Int(self.encodePos(ent['x'].value, ent['y'].value, ent['z'].value))
        # output_file = gzip.open(self.filename, "wb", compresslevel=1)
        try:
            os.rename(filename, filename + ".old")
        except Exception:
            pass

        try:
            self.root_tag.save(filename)
        except:
            os.rename(filename + ".old", filename)

        try:
            os.remove(filename + ".old")
        except Exception:
            pass

        self.Entities.remove(self.LocalPlayer)

        self.BlockLight = self.Data & 0xf

        self.Data >>= 4
Esempio n. 25
0
 def numbersToFloats(ent):
     for attr in "Motion", "Pos":
         if attr in ent:
             ent[attr] = nbt.TAG_List([nbt.TAG_Double(t.value) for t in ent[attr]])
Esempio n. 26
0
    def __init__(self, root_tag=None, filename=""):
        self.Width = 0
        self.Height = 0
        self.Length = 0
        self.Blocks = array([], "uint8")
        self.Data = array([], "uint8")
        self.Spawn = (0, 0, 0)
        self.filename = filename

        if root_tag:

            self.root_tag = root_tag
            mapTag = root_tag["Map"]
            self.Width = mapTag["Width"].value
            self.Length = mapTag["Length"].value
            self.Height = mapTag["Height"].value

            mapTag["Blocks"].value.shape = (self.Height, self.Length, self.Width)

            self.Blocks = swapaxes(mapTag["Blocks"].value, 0, 2)

            mapTag["Data"].value.shape = (self.Height, self.Length, self.Width)

            self.Data = swapaxes(mapTag["Data"].value, 0, 2)

            self.BlockLight = self.Data & 0xf

            self.Data >>= 4

            self.Spawn = [mapTag[Spawn][i].value for i in range(3)]

            if "Entities" not in root_tag:
                root_tag["Entities"] = nbt.TAG_List()
            self.Entities = root_tag["Entities"]

            # xxx fixup Motion and Pos to match infdev format
            def numbersToDoubles(ent):
                for attr in "Motion", "Pos":
                    if attr in ent:
                        ent[attr] = nbt.TAG_List([nbt.TAG_Double(t.value) for t in ent[attr]])

            for ent in self.Entities:
                numbersToDoubles(ent)

            if "TileEntities" not in root_tag:
                root_tag["TileEntities"] = nbt.TAG_List()
            self.TileEntities = root_tag["TileEntities"]
            # xxx fixup TileEntities positions to match infdev format
            for te in self.TileEntities:
                pos = te["Pos"].value

                (x, y, z) = self.decodePos(pos)

                TileEntity.setpos(te, (x, y, z))

            localPlayerList = [tag for tag in root_tag["Entities"] if tag['id'].value == 'LocalPlayer']
            if len(localPlayerList) == 0:  # omen doesn't make a player entity
                playerTag = nbt.TAG_Compound()
                playerTag['id'] = nbt.TAG_String('LocalPlayer')
                playerTag['Pos'] = nbt.TAG_List([nbt.TAG_Float(0.), nbt.TAG_Float(64.), nbt.TAG_Float(0.)])
                playerTag['Rotation'] = nbt.TAG_List([nbt.TAG_Float(0.), nbt.TAG_Float(45.)])
                self.LocalPlayer = playerTag

            else:
                self.LocalPlayer = localPlayerList[0]

        else:
            log.info(u"Creating new Indev levels is not yet implemented.!")
            raise ValueError("Can't do that yet")
Esempio n. 27
0
 def setPlayerOrientation(self, yp, player="Ignored"):
     self.LocalPlayer["Rotation"] = nbt.TAG_List([nbt.TAG_Float(p) for p in yp])
Esempio n. 28
0
 def setPlayerPosition(self, pos, player="Ignored"):
     self.LocalPlayer["Pos"] = nbt.TAG_List([nbt.TAG_Float(p) for p in pos])
Esempio n. 29
0
    def __init__(self, root_tag=None, filename=""):
        self.Width = 0
        self.Height = 0
        self.Length = 0
        self.Blocks = array([], uint8)
        self.Data = array([], uint8)
        self.Spawn = (0, 0, 0)
        self.filename = filename

        if root_tag:

            self.root_tag = root_tag
            mapTag = root_tag[Map]
            self.Width = mapTag[Width].value
            self.Length = mapTag[Length].value
            self.Height = mapTag[Height].value

            mapTag[Blocks].value.shape = (self.Height, self.Length, self.Width)

            self.Blocks = swapaxes(mapTag[Blocks].value, 0, 2)

            mapTag[Data].value.shape = (self.Height, self.Length, self.Width)

            self.Data = swapaxes(mapTag[Data].value, 0, 2)

            self.BlockLight = self.Data & 0xf

            self.Data >>= 4

            self.Spawn = [mapTag[Spawn][i].value for i in range(3)]

            if not Entities in root_tag:
                root_tag[Entities] = nbt.TAG_List()
            self.Entities = root_tag[Entities]

            # xxx fixup Motion and Pos to match infdev format
            def numbersToDoubles(ent):
                for attr in "Motion", "Pos":
                    if attr in ent:
                        ent[attr] = nbt.TAG_List(
                            [nbt.TAG_Double(t.value) for t in ent[attr]])

            for ent in self.Entities:
                numbersToDoubles(ent)

            if not TileEntities in root_tag:
                root_tag[TileEntities] = nbt.TAG_List()
            self.TileEntities = root_tag[TileEntities]
            # xxx fixup TileEntities positions to match infdev format
            for te in self.TileEntities:
                pos = te["Pos"].value

                (x, y, z) = self.decodePos(pos)

                TileEntity.setpos(te, (x, y, z))

            if len(
                    filter(lambda x: x['id'].value == 'LocalPlayer',
                           root_tag[Entities])
            ) == 0:  # omen doesn't make a player entity
                p = nbt.TAG_Compound()
                p['id'] = nbt.TAG_String('LocalPlayer')
                p['Pos'] = nbt.TAG_List(
                    [nbt.TAG_Float(0.),
                     nbt.TAG_Float(64.),
                     nbt.TAG_Float(0.)])
                p['Rotation'] = nbt.TAG_List(
                    [nbt.TAG_Float(0.), nbt.TAG_Float(45.)])

                root_tag[Entities].append(p)
                # self.saveInPlace()

        else:
            info(u"Creating new Indev levels is not yet implemented.!")
            raise ValueError("Can't do that yet")
Esempio n. 30
0
 def setPlayerOrientation(self, yp, player="Ignored"):
     for x in self.root_tag["Entities"]:
         if x["id"].value == "LocalPlayer":
             x["Rotation"] = nbt.TAG_List([nbt.TAG_Float(p) for p in yp])