def __readObjectGroup(self): atts = self.xml.attributes() name = atts.value("name") x = Int(atts.value("x")) y = Int(atts.value("y")) width = Int(atts.value("width")) height = Int(atts.value("height")) objectGroup = ObjectGroup(name, x, y, width, height) readLayerAttributes(objectGroup, atts) color = atts.value("color") if color != '': objectGroup.setColor(color) if (atts.hasAttribute("draworder")): value = atts.value("draworder") drawOrder = drawOrderFromString(value) if (drawOrder == ObjectGroup.DrawOrder.UnknownOrder): #del objectGroup self.xml.raiseError(self.tr("Invalid draw order: %s" % value)) return None objectGroup.setDrawOrder(drawOrder) while (self.xml.readNextStartElement()): if (self.xml.name() == "object"): objectGroup.addObject(self.__readObject()) elif (self.xml.name() == "properties"): objectGroup.mergeProperties(self.__readProperties()) else: self.__readUnknownElement() return objectGroup
def __readObject(self): atts = self.xml.attributes() id = Int(atts.value("id")) name = atts.value("name") gid = Int(atts.value("gid")) x = Float(atts.value("x")) y = Float(atts.value("y")) width = Float(atts.value("width")) height = Float(atts.value("height")) type = atts.value("type") visibleRef = atts.value("visible") pos = QPointF(x, y) size = QSizeF(width, height) object = MapObject(name, type, pos, size) object.setId(id) try: rotation = Float(atts.value("rotation")) ok = True except: ok = False if (ok): object.setRotation(rotation) if (gid): object.setCell(self.__cellForGid(gid)) if (not object.cell().isEmpty()): tileSize = object.cell().tile.size() if (width == 0): object.setWidth(tileSize.width()) if (height == 0): object.setHeight(tileSize.height()) try: visible = int(visibleRef) ok = True except: ok = False if ok: object.setVisible(visible) while (self.xml.readNextStartElement()): if (self.xml.name() == "properties"): object.mergeProperties(self.__readProperties()) elif (self.xml.name() == "polygon"): object.setPolygon(self.__readPolygon()) object.setShape(MapObject.Polygon) elif (self.xml.name() == "polyline"): object.setPolygon(self.__readPolygon()) object.setShape(MapObject.Polyline) elif (self.xml.name() == "ellipse"): self.xml.skipCurrentElement() object.setShape(MapObject.Ellipse) else: self.__readUnknownElement() return object
def __readAnimationFrames(self): frames = QVector() while (self.xml.readNextStartElement()): if (self.xml.name() == "frame"): atts = self.xml.attributes() frame = Frame() frame.tileId = Int(atts.value("tileid")) frame.duration = Int(atts.value("duration")) frames.append(frame) self.xml.skipCurrentElement() else: self.__readUnknownElement() return frames
def __readImageLayer(self): atts = self.xml.attributes() name = atts.value("name") x = Int(atts.value("x")) y = Int(atts.value("y")) width = Int(atts.value("width")) height = Int(atts.value("height")) imageLayer = ImageLayer(name, x, y, width, height) readLayerAttributes(imageLayer, atts) while (self.xml.readNextStartElement()): if (self.xml.name() == "image"): self.__readImageLayerImage(imageLayer) elif (self.xml.name() == "properties"): imageLayer.mergeProperties(self.__readProperties()) else: self.__readUnknownElement() return imageLayer
def __readTileset(self): atts = self.xml.attributes() source = atts.value("source") firstGid = Int(atts.value("firstgid")) tileset = None if source == '': # Not an external tileset name = atts.value("name") tileWidth = Int(atts.value("tilewidth")) tileHeight = Int(atts.value("tileheight")) tileSpacing = Int(atts.value("spacing")) margin = Int(atts.value("margin")) if (tileWidth < 0 or tileHeight < 0 or (firstGid == 0 and not self.mReadingExternalTileset)): self.xml.raiseError( self.tr("Invalid tileset parameters for tileset '%s'" % name)) else: tileset = Tileset.create(name, tileWidth, tileHeight, tileSpacing, margin) while (self.xml.readNextStartElement()): if (self.xml.name() == "tile"): self.__readTilesetTile(tileset) elif (self.xml.name() == "tileoffset"): oa = self.xml.attributes() x = Int(oa.value("x")) y = Int(oa.value("y")) tileset.setTileOffset(QPoint(x, y)) self.xml.skipCurrentElement() elif (self.xml.name() == "properties"): tileset.mergeProperties(self.__readProperties()) elif (self.xml.name() == "image"): if (tileWidth == 0 or tileHeight == 0): self.xml.raiseError( self. tr("Invalid tileset parameters for tileset '%s'" % name)) tileset.clear() break else: self.__readTilesetImage(tileset) elif (self.xml.name() == "terraintypes"): self.__readTilesetTerrainTypes(tileset) else: self.__readUnknownElement() else: # External tileset absoluteSource = self.p.resolveReference(source, self.mPath) tileset, error = self.p.readExternalTileset(absoluteSource) if (not tileset): self.xml.raiseError( self.tr("Error while loading tileset '%s': %s" % (absoluteSource, error))) self.xml.skipCurrentElement() if (tileset and not self.mReadingExternalTileset): self.mGidMapper.insert(firstGid, tileset) return tileset
def __readLayerData(self, tileLayer): atts = self.xml.attributes() encoding = atts.value("encoding") compression = atts.value("compression") layerDataFormat = 0 if (encoding == ''): layerDataFormat = Map.LayerDataFormat.XML elif (encoding == "csv"): layerDataFormat = Map.LayerDataFormat.CSV elif (encoding == "base64"): if (compression == ''): layerDataFormat = Map.LayerDataFormat.Base64 elif (compression == "gzip"): layerDataFormat = Map.LayerDataFormat.Base64Gzip elif (compression == "zlib"): layerDataFormat = Map.LayerDataFormat.Base64Zlib else: self.xml.raiseError( self.tr("Compression method '%s' not supported" % compression)) return else: self.xml.raiseError(self.tr("Unknown encoding: %s" % encoding)) return self.mMap.setLayerDataFormat(layerDataFormat) x = 0 y = 0 while (self.xml.readNext() != QXmlStreamReader.Invalid): if (self.xml.isEndElement()): break elif (self.xml.isStartElement()): if (self.xml.name() == "tile"): if (y >= tileLayer.height()): self.xml.raiseError( self.tr("Too many <tile> elements")) continue atts = self.xml.attributes() gid = Int(atts.value("gid")) tileLayer.setCell(x, y, self.__cellForGid(gid)) x += 1 if (x >= tileLayer.width()): x = 0 y += 1 self.xml.skipCurrentElement() else: self.__readUnknownElement() elif (self.xml.isCharacters() and not self.xml.isWhitespace()): if (encoding == "base64"): self.__decodeBinaryLayerData(tileLayer, self.xml.text(), layerDataFormat) elif (encoding == "csv"): self.__decodeCSVLayerData(tileLayer, self.xml.text())
def __readTilesetTerrainTypes(self, tileset): while (self.xml.readNextStartElement()): if (self.xml.name() == "terrain"): atts = self.xml.attributes() name = atts.value("name") tile = Int(atts.value("tile")) terrain = tileset.addTerrain(name, tile) while (self.xml.readNextStartElement()): if (self.xml.name() == "properties"): terrain.mergeProperties(self.__readProperties()) else: self.__readUnknownElement() else: self.__readUnknownElement()
def setMapDocument(self, mapDoc): if (mapDoc == self.mMapDocument): return if (self.mMapDocument): self.mMapDocument.disconnect() self.mMapDocument = mapDoc if (self.mMapDocument): self.setModel(self.mMapDocument.mapObjectModel()) # 2 equal-sized columns, user can't adjust settings = preferences.Preferences.instance().settings() firstSectionSize = Int(settings.value(FIRST_SECTION_SIZE_KEY, 200)) self.header().resizeSection(0, firstSectionSize) else: self.setModel(None)
def __readTilesetImage(self, tileset): atts = self.xml.attributes() source = atts.value("source") trans = atts.value("trans") if len(trans) > 0: if (not trans.startswith('#')): trans = '#' + trans tileset.setTransparentColor(QColor(trans)) if len(source) > 0: source = self.p.resolveReference(source, self.mPath) # Set the width that the tileset had when the map was saved width = Int(atts.value("width")) self.mGidMapper.setTilesetWidth(tileset, width) if (not tileset.loadFromImage(self.__readImage(), source)): self.xml.raiseError( self.tr("Error loading tileset image:\n'%s'" % source))
def __readMap(self): atts = self.xml.attributes() mapWidth = Int(atts.value("width")) mapHeight = Int(atts.value("height")) tileWidth = Int(atts.value("tilewidth")) tileHeight = Int(atts.value("tileheight")) hexSideLength = Int(atts.value("hexsidelength")) orientationString = atts.value("orientation") orientation = orientationFromString(orientationString) if (orientation == Map.Orientation.Unknown): self.xml.raiseError( self.tr("Unsupported map orientation: \"%s\"" % orientationString)) staggerAxisString = atts.value("staggeraxis") staggerAxis = staggerAxisFromString(staggerAxisString) staggerIndexString = atts.value("staggerindex") staggerIndex = staggerIndexFromString(staggerIndexString) renderOrderString = atts.value("renderorder") renderOrder = renderOrderFromString(renderOrderString) nextObjectId = Int(atts.value("nextobjectid")) self.mMap = Map(orientation, mapWidth, mapHeight, tileWidth, tileHeight) self.mMap.setHexSideLength(hexSideLength) self.mMap.setStaggerAxis(staggerAxis) self.mMap.setStaggerIndex(staggerIndex) self.mMap.setRenderOrder(renderOrder) if (nextObjectId): self.mMap.setNextObjectId(nextObjectId) bgColorString = atts.value("backgroundcolor") if len(bgColorString) > 0: self.mMap.setBackgroundColor(QColor(bgColorString)) while (self.xml.readNextStartElement()): if (self.xml.name() == "properties"): self.mMap.mergeProperties(self.__readProperties()) elif (self.xml.name() == "tileset"): self.mMap.addTileset(self.__readTileset()) elif (self.xml.name() == "layer"): self.mMap.addLayer(self.__readLayer()) elif (self.xml.name() == "objectgroup"): self.mMap.addLayer(self.__readObjectGroup()) elif (self.xml.name() == "imagelayer"): self.mMap.addLayer(self.__readImageLayer()) else: self.__readUnknownElement() # Clean up in case of error if (self.xml.hasError()): self.mMap = None return self.mMap
def __toTileset(self, variant): variantMap = variant firstGid = variantMap.get("firstgid", 0) # Handle external tilesets sourceVariant = variantMap.get("source", '') if sourceVariant != '': source = resolvePath(self.mMapDir, sourceVariant) tileset, error = readTileset(source) if not tileset: self.mError = self.tr("Error while loading tileset '%s': %s" % (source, error)) else: self.mGidMapper.insert(firstGid, tileset) return tileset name = variantMap.get("name", '') tileWidth = variantMap.get("tilewidth", 0) tileHeight = variantMap.get("tileheight", 0) spacing = variantMap.get("spacing", 0) margin = variantMap.get("margin", 0) tileOffset = variantMap.get("tileoffset", {}) tileOffsetX = tileOffset.get("x", 0) tileOffsetY = tileOffset.get("y", 0) if (tileWidth <= 0 or tileHeight <= 0 or (firstGid == 0 and not self.mReadingExternalTileset)): self.mError = self.tr( "Invalid tileset parameters for tileset '%s'" % name) return None tileset = Tileset.create(name, tileWidth, tileHeight, spacing, margin) tileset.setTileOffset(QPoint(tileOffsetX, tileOffsetY)) trans = variantMap.get("transparentcolor", '') if (trans != '' and QColor.isValidColor(trans)): tileset.setTransparentColor(QColor(trans)) imageVariant = variantMap.get("image", '') if imageVariant != '': imagePath = resolvePath(self.mMapDir, imageVariant) if (not tileset.loadFromImage(imagePath)): self.mError = self.tr("Error loading tileset image:\n'%s'" % imagePath) return None tileset.setProperties( self.toProperties(variantMap.get("properties", {}))) # Read terrains terrainsVariantList = variantMap.get("terrains", []) for terrainMap in terrainsVariantList: tileset.addTerrain(terrainMap.get("name", ''), terrainMap.get("tile", 0)) # Read tile terrain and external image information tilesVariantMap = variantMap.get("tiles", {}) for it in tilesVariantMap.items(): ok = False tileIndex = Int(it[0]) if (tileIndex < 0): self.mError = self.tr("Tileset tile index negative:\n'%d'" % tileIndex) if (tileIndex >= tileset.tileCount()): # Extend the tileset to fit the tile if (tileIndex >= len(tilesVariantMap)): # If tiles are defined this way, there should be an entry # for each tile. # Limit the index to number of entries to prevent running out # of memory on malicious input.f self.mError = self.tr( "Tileset tile index too high:\n'%d'" % tileIndex) return None for i in range(tileset.tileCount(), tileIndex + 1): tileset.addTile(QPixmap()) tile = tileset.tileAt(tileIndex) if (tile): tileVar = it[1] terrains = tileVar.get("terrain", []) if len(terrains) == 4: for i in range(0, 4): terrainId, ok = Int2(terrains[i]) if (ok and terrainId >= 0 and terrainId < tileset.terrainCount()): tile.setCornerTerrainId(i, terrainId) probability, ok = Float2(tileVar.get("probability", 0.0)) if (ok): tile.setProbability(probability) imageVariant = tileVar.get("image", '') if imageVariant != '': imagePath = resolvePath(self.mMapDir, imageVariant) tileset.setTileImage(tileIndex, QPixmap(imagePath), imagePath) objectGroupVariant = tileVar.get("objectgroup", {}) if len(objectGroupVariant) > 0: tile.setObjectGroup(self.toObjectGroup(objectGroupVariant)) frameList = tileVar.get("animation", []) lenFrames = len(frameList) if lenFrames > 0: frames = QVector() for i in range(lenFrames): frames.append(Frame()) for i in range(lenFrames - 1, -1, -1): frameVariantMap = frameList[i] frame = frames[i] frame.tileId = frameVariantMap.get("tileid", 0) frame.duration = frameVariantMap.get("duration", 0) tile.setFrames(frames) # Read tile properties propertiesVariantMap = variantMap.get("tileproperties", {}) for it in propertiesVariantMap.items(): tileIndex = Int(it[0]) propertiesVar = it[1] if (tileIndex >= 0 and tileIndex < tileset.tileCount()): properties = self.toProperties(propertiesVar) tileset.tileAt(tileIndex).setProperties(properties) if not self.mReadingExternalTileset: self.mGidMapper.insert(firstGid, tileset) return tileset
def __readTilesetTile(self, tileset): atts = self.xml.attributes() id = Int(atts.value("id")) if (id < 0): self.xml.raiseError(self.tr("Invalid tile ID: %d" % id)) return hasImage = tileset.imageSource() != '' if (hasImage and id >= tileset.tileCount()): self.xml.raiseError( self.tr("Tile ID does not exist in tileset image: %d" % id)) return if (id > tileset.tileCount()): self.xml.raiseError( self.tr("Invalid (nonconsecutive) tile ID: %d" % id)) return # For tilesets without image source, consecutive tile IDs are allowed (for # tiles with individual images) if (id == tileset.tileCount()): tileset.addTile(QPixmap()) tile = tileset.tileAt(id) # Read tile quadrant terrain ids terrain = atts.value("terrain") if terrain != '': quadrants = terrain.split(",") if (len(quadrants) == 4): for i in range(4): if quadrants[i] == '': t = -1 else: t = Int(quadrants[i]) tile.setCornerTerrainId(i, t) # Read tile probability probability = atts.value("probability") if probability != '': tile.setProbability(Float(probability)) while (self.xml.readNextStartElement()): if (self.xml.name() == "properties"): tile.mergeProperties(self.__readProperties()) elif (self.xml.name() == "image"): source = self.xml.attributes().value("source") if source != '': source = self.p.resolveReference(source, self.mPath) tileset.setTileImage(id, QPixmap.fromImage(self.__readImage()), source) elif (self.xml.name() == "objectgroup"): tile.setObjectGroup(self.__readObjectGroup()) elif (self.xml.name() == "animation"): tile.setFrames(self.__readAnimationFrames()) else: self.__readUnknownElement() # Temporary code to support TMW-style animation frame properties if (not tile.isAnimated() and tile.hasProperty("animation-frame0")): frames = QVector() i = 0 while (i >= 0): frameName = "animation-frame" + str(i) delayName = "animation-delay" + str(i) if (tile.hasProperty(frameName) and tile.hasProperty(delayName)): frame = Frame() frame.tileId = tile.property(frameName) frame.duration = tile.property(delayName) * 10 frames.append(frame) else: break i += 1 tile.setFrames(frames)
def read(self, fileName): file = QFile(fileName) if (not file.open(QIODevice.ReadOnly)): self.mError = self.tr("Could not open file for reading.") return None # default to values of the original flare alpha game. map = Map(Map.Orientation.Isometric, 256, 256, 64, 32) stream = QTextStream(file) line = QString() sectionName = QString() newsection = False path = QFileInfo(file).absolutePath() base = 10 gidMapper = GidMapper() gid = 1 tilelayer = None objectgroup = None mapobject = None tilesetsSectionFound = False headerSectionFound = False tilelayerSectionFound = False # tile layer or objects while (not stream.atEnd()): line = stream.readLine() if line == '': continue startsWith = line[0] if (startsWith == '['): sectionName = line[1:line.index(']')] newsection = True continue if (sectionName == "header"): headerSectionFound = True #get map properties epos = line.index('=') if (epos != -1): key = line[:epos].strip() value = line[epos + 1:].strip() if (key == "width"): map.setWidth(Int(value)) elif (key == "height"): map.setHeight(Int(value)) elif (key == "tilewidth"): map.setTileWidth(Int(value)) elif (key == "tileheight"): map.setTileHeight(Int(value)) elif (key == "orientation"): map.setOrientation(orientationFromString(value)) else: map.setProperty(key, value) elif (sectionName == "tilesets"): tilesetsSectionFound = True epos = line.index('=') key = line[:epos].strip() value = line[epos + 1:].strip() if (key == "tileset"): _list = value.split(',') absoluteSource = _list[0] if (QDir.isRelativePath(absoluteSource)): absoluteSource = path + '/' + absoluteSource tilesetwidth = 0 tilesetheight = 0 if len(_list) > 2: tilesetwidth = Int(_list[1]) tilesetheight = Int(_list[2]) tileset = Tileset.create( QFileInfo(absoluteSource).fileName(), tilesetwidth, tilesetheight) ok = tileset.loadFromImage(absoluteSource) if not ok: self.mError = self.tr( "Error loading tileset %s, which expands to %s. Path not found!" % (_list[0], absoluteSource)) return None else: if len(_list) > 4: tileset.setTileOffset( QPoint(Int(_list[3]), Int(_list[4]))) gidMapper.insert(gid, tileset) if len(_list) > 5: gid += Int(_list[5]) else: gid += tileset.tileCount() map.addTileset(tileset) elif (sectionName == "layer"): if (not tilesetsSectionFound): self.mError = self.tr( "No tilesets section found before layer section.") return None tilelayerSectionFound = True epos = line.index('=') if (epos != -1): key = line[:epos].strip() value = line[epos + 1:].strip() if (key == "type"): tilelayer = TileLayer(value, 0, 0, map.width(), map.height()) map.addLayer(tilelayer) elif (key == "format"): if (value == "dec"): base = 10 elif (value == "hex"): base = 16 elif (key == "data"): for y in range(map.height()): line = stream.readLine() l = line.split(',') for x in range(min(map.width(), len(l))): ok = False tileid = int(l[x], base) c, ok = gidMapper.gidToCell(tileid) if (not ok): self.mError += self.tr( "Error mapping tile id %1.").arg( tileid) return None tilelayer.setCell(x, y, c) else: tilelayer.setProperty(key, value) else: if (newsection): if (map.indexOfLayer(sectionName) == -1): objectgroup = ObjectGroup(sectionName, 0, 0, map.width(), map.height()) map.addLayer(objectgroup) else: objectgroup = map.layerAt( map.indexOfLayer(sectionName)) mapobject = MapObject() objectgroup.addObject(mapobject) newsection = False if (not mapobject): continue if (startsWith == '#'): name = line[1].strip() mapobject.setName(name) epos = line.index('=') if (epos != -1): key = line[:epos].strip() value = line[epos + 1:].strip() if (key == "type"): mapobject.setType(value) elif (key == "location"): loc = value.split(',') x, y = 0.0, 0.0 w, h = 0, 0 if (map.orientation() == Map.Orthogonal): x = loc[0].toFloat() * map.tileWidth() y = loc[1].toFloat() * map.tileHeight() if len(loc) > 3: w = Int(loc[2]) * map.tileWidth() h = Int(loc[3]) * map.tileHeight() else: w = map.tileWidth() h = map.tileHeight() else: x = loc[0].toFloat() * map.tileHeight() y = loc[1].toFloat() * map.tileHeight() if len(loc) > 3: w = Int(loc[2]) * map.tileHeight() h = Int(loc[3]) * map.tileHeight() else: w = h = map.tileHeight() mapobject.setPosition(QPointF(x, y)) mapobject.setSize(w, h) else: mapobject.setProperty(key, value) if (not headerSectionFound or not tilesetsSectionFound or not tilelayerSectionFound): self.mError = self.tr( "This seems to be no valid flare map. " "A Flare map consists of at least a header " "section, a tileset section and one tile layer.") return None return map
def intValue(self, key, defaultValue): return Int(self.mSettings.value(key, defaultValue))