def currentTemplateChanged(self, index=None):
    cbox = self.ui.comboBox_Template
    templateType = cbox.itemData(cbox.currentIndex(), Qt.UserRole)
    if templateType == self.templateType:
      return

    # hide items unsupported by template
    tree = self.ui.treeWidget
    for i, id in enumerate(ObjectTreeItem.topItemIds):
      hidden = (templateType == "sphere" and id != ObjectTreeItem.ITEM_CONTROLS)
      tree.topLevelItem(i).setHidden(hidden)

    # set current tree item
    if templateType == "sphere":
      tree.setCurrentItem(tree.topLevelItem(ObjectTreeItem.topItemIndex(ObjectTreeItem.ITEM_CONTROLS)))
    elif self.lastTreeItemData is None or not self.setCurrentTreeItemByData(self.lastTreeItemData):   # restore selection
      tree.setCurrentItem(tree.topLevelItem(ObjectTreeItem.topItemIndex(ObjectTreeItem.ITEM_DEM)))   # default selection for plain is DEM

    # display messages
    self.clearMessageBar()
    if templateType != "sphere":
      # show message if crs unit is degrees
      mapSettings = self.iface.mapCanvas().mapSettings() if QGis.QGIS_VERSION_INT >= 20300 else self.iface.mapCanvas().mapRenderer()
      if mapSettings.destinationCrs().mapUnits() in [QGis.Degrees]:
        self.showMessageBar("The unit of current CRS is degrees, so terrain may not appear well.", QgsMessageBar.WARNING)

    self.templateType = templateType
  def initObjectTree(self):
    tree = self.ui.treeWidget
    tree.clear()

    # add vector and raster layers into tree widget
    topItems = {}
    for id, name in zip(ObjectTreeItem.topItemIds, ObjectTreeItem.topItemNames):
      item = QTreeWidgetItem(tree, [name])
      item.setData(0, Qt.UserRole, id)
      topItems[id] = item

    optDEMChecked = False
    for layer in self.iface.legendInterface().layers():
      parentId = ObjectTreeItem.parentIdByLayer(layer)
      if parentId is None:
        continue

      item = QTreeWidgetItem(topItems[parentId], [layer.name()])
      isVisible = self._settings.get(parentId, {}).get(layer.id(), {}).get("visible", False)   #self.iface.legendInterface().isLayerVisible(layer)
      check_state = Qt.Checked if isVisible else Qt.Unchecked
      item.setData(0, Qt.CheckStateRole, check_state)
      item.setData(0, Qt.UserRole, layer.id())
      if parentId == ObjectTreeItem.ITEM_OPTDEM and isVisible:
        optDEMChecked = True

    for id, item in topItems.iteritems():
      if id != ObjectTreeItem.ITEM_OPTDEM or optDEMChecked:
        tree.expandItem(item)

    # disable additional DEM item which is selected as main DEM
    layerId = self._settings.get(ObjectTreeItem.ITEM_DEM, {}).get("comboBox_DEMLayer")
    if layerId:
      self.primaryDEMChanged(layerId)
 def primaryDEMChanged(self, layerId):
   tree = self.ui.treeWidget
   parent = tree.topLevelItem(ObjectTreeItem.topItemIndex(ObjectTreeItem.ITEM_OPTDEM))
   tree.blockSignals(True)
   for i in range(parent.childCount()):
     item = parent.child(i)
     isPrimary = item.data(0, Qt.UserRole) == layerId
     item.setDisabled(isPrimary)
   tree.blockSignals(False)
 def primaryDEMChanged(self, layerId):
     tree = self.ui.treeWidget
     parent = tree.topLevelItem(
         ObjectTreeItem.topItemIndex(ObjectTreeItem.ITEM_OPTDEM))
     tree.blockSignals(True)
     for i in range(parent.childCount()):
         item = parent.child(i)
         isPrimary = item.data(0, Qt.UserRole) == layerId
         item.setDisabled(isPrimary)
     tree.blockSignals(False)
    def currentTemplateChanged(self, index=None):
        cbox = self.ui.comboBox_Template
        templateType = cbox.itemData(cbox.currentIndex(), Qt.UserRole)
        if templateType == self.templateType:
            return

        # hide items unsupported by template
        tree = self.ui.treeWidget
        for i, id in enumerate(ObjectTreeItem.topItemIds):
            hidden = (templateType == "sphere"
                      and id != ObjectTreeItem.ITEM_CONTROLS)
            tree.topLevelItem(i).setHidden(hidden)

        # set current tree item
        if templateType == "sphere":
            tree.setCurrentItem(
                tree.topLevelItem(
                    ObjectTreeItem.topItemIndex(ObjectTreeItem.ITEM_CONTROLS)))
        elif self.lastTreeItemData is None or not self.setCurrentTreeItemByData(
                self.lastTreeItemData):  # restore selection
            tree.setCurrentItem(
                tree.topLevelItem(
                    ObjectTreeItem.topItemIndex(ObjectTreeItem.ITEM_DEM))
            )  # default selection for plain is DEM

        # display messages
        self.clearMessageBar()
        if templateType != "sphere":
            # show message if crs unit is degrees
            mapSettings = self.iface.mapCanvas().mapSettings(
            ) if QGis.QGIS_VERSION_INT >= 20300 else self.iface.mapCanvas(
            ).mapRenderer()
            if mapSettings.destinationCrs().mapUnits() in [QGis.Degrees]:
                self.showMessageBar(
                    "The unit of current CRS is degrees, so terrain may not appear well.",
                    QgsMessageBar.WARNING)

        self.templateType = templateType
    def initObjectTree(self):
        tree = self.ui.treeWidget
        tree.clear()

        # add vector and raster layers into tree widget
        topItems = {}
        for id, name in zip(ObjectTreeItem.topItemIds,
                            ObjectTreeItem.topItemNames):
            item = QTreeWidgetItem(tree, [name])
            item.setData(0, Qt.UserRole, id)
            topItems[id] = item

        optDEMChecked = False
        for layer in self.iface.legendInterface().layers():
            parentId = ObjectTreeItem.parentIdByLayer(layer)
            if parentId is None:
                continue

            item = QTreeWidgetItem(topItems[parentId], [layer.name()])
            isVisible = self._settings.get(parentId, {}).get(
                layer.id(), {}).get(
                    "visible",
                    False)  #self.iface.legendInterface().isLayerVisible(layer)
            check_state = Qt.Checked if isVisible else Qt.Unchecked
            item.setData(0, Qt.CheckStateRole, check_state)
            item.setData(0, Qt.UserRole, layer.id())
            if parentId == ObjectTreeItem.ITEM_OPTDEM and isVisible:
                optDEMChecked = True

        for id, item in topItems.iteritems():
            if id != ObjectTreeItem.ITEM_OPTDEM or optDEMChecked:
                tree.expandItem(item)

        # disable additional DEM item which is selected as main DEM
        layerId = self._settings.get(ObjectTreeItem.ITEM_DEM,
                                     {}).get("comboBox_DEMLayer")
        if layerId:
            self.primaryDEMChanged(layerId)
def writeVectors(writer, legendInterface=None, progress=None):
    settings = writer.settings
    baseExtent = settings.baseExtent
    progress = progress or dummyProgress
    renderer = QgsMapRenderer()

    layers = []
    if legendInterface is None:
        for parentId in [
                ObjectTreeItem.ITEM_POINT, ObjectTreeItem.ITEM_LINE,
                ObjectTreeItem.ITEM_POLYGON
        ]:
            for layerId, properties in settings.get(parentId, {}).iteritems():
                if properties.get("visible", False):
                    layers.append([layerId, properties])
    else:
        # use vector layer order in legendInterface
        for layer in legendInterface.layers():
            if layer.type() != QgsMapLayer.VectorLayer:
                continue

            parentId = ObjectTreeItem.parentIdByLayer(layer)
            properties = settings.get(parentId, {}).get(layer.id(), {})
            if properties.get("visible", False):
                layers.append([layer.id(), properties])

    finishedLayers = 0
    for layerId, properties in layers:
        mapLayer = QgsMapLayerRegistry.instance().mapLayer(layerId)
        if mapLayer is None:
            continue

        prop = VectorPropertyReader(writer.objectTypeManager, mapLayer,
                                    properties)
        obj_mod = writer.objectTypeManager.module(prop.mod_index)
        if obj_mod is None:
            logMessage("Module not found")
            continue

        # prepare triangle mesh
        geom_type = mapLayer.geometryType()
        if geom_type == QGis.Polygon and prop.type_index == 1 and prop.isHeightRelativeToDEM(
        ):  # Overlay
            progress(None, "Initializing triangle mesh for overlay polygons")
            writer.triangleMesh()

        progress(
            30 + 30 * finishedLayers / len(layers),
            u"Writing vector layer ({0} of {1}): {2}".format(
                finishedLayers + 1, len(layers), mapLayer.name()))

        # write layer object
        layer = VectorLayer(writer, mapLayer, prop, obj_mod)
        writer.writeLayer(layer.layerObject(), layer.fieldNames)

        # initialize symbol rendering
        mapLayer.rendererV2().startRender(
            renderer.rendererContext(),
            mapLayer.pendingFields()
            if QGis.QGIS_VERSION_INT >= 20300 else mapLayer)

        # features to export
        request = QgsFeatureRequest()
        clipGeom = None
        if properties.get("radioButton_IntersectingFeatures", False):
            request.setFilterRect(
                layer.transform.transformBoundingBox(
                    baseExtent.boundingBox(),
                    QgsCoordinateTransform.ReverseTransform))
            if properties.get("checkBox_Clip"):
                extent = baseExtent.clone().scale(
                    0.999999
                )  # clip with slightly smaller extent than map canvas extent
                clipGeom = extent.geometry()

        for feat in layer.features(request, clipGeom):
            # write geometry
            obj_mod.write(writer, layer,
                          feat)  # writer.writeFeature(layer, feat, obj_mod)

            # stack attributes in writer
            if layer.writeAttrs:
                writer.addAttributes(feat.attributes())

        # write attributes
        if layer.writeAttrs:
            writer.writeAttributes()

        # write materials
        writer.writeMaterials(layer.materialManager)

        mapLayer.rendererV2().stopRender(renderer.rendererContext())
        finishedLayers += 1
Exemple #8
0
def writeVectors(writer, legendInterface=None, progress=None):
  settings = writer.settings
  baseExtent = settings.baseExtent
  progress = progress or dummyProgress
  renderer = QgsMapRenderer()

  layers = []
  if legendInterface is None:
    for parentId in [ObjectTreeItem.ITEM_POINT, ObjectTreeItem.ITEM_LINE, ObjectTreeItem.ITEM_POLYGON]:
      for layerId, properties in settings.get(parentId, {}).iteritems():
        if properties.get("visible", False):
          layers.append([layerId, properties])
  else:
    # use vector layer order in legendInterface
    for layer in legendInterface.layers():
      if layer.type() != QgsMapLayer.VectorLayer:
        continue

      parentId = ObjectTreeItem.parentIdByLayer(layer)
      properties = settings.get(parentId, {}).get(layer.id(), {})
      if properties.get("visible", False):
        layers.append([layer.id(), properties])

  finishedLayers = 0
  for layerId, properties in layers:
    mapLayer = QgsMapLayerRegistry.instance().mapLayer(layerId)
    if mapLayer is None:
      continue

    prop = VectorPropertyReader(writer.objectTypeManager, mapLayer, properties)
    obj_mod = writer.objectTypeManager.module(prop.mod_index)
    if obj_mod is None:
      logMessage("Module not found")
      continue

    # prepare triangle mesh
    geom_type = mapLayer.geometryType()
    if geom_type == QGis.Polygon and prop.type_index == 1 and prop.isHeightRelativeToDEM():   # Overlay
      progress(None, "Initializing triangle mesh for overlay polygons")
      writer.triangleMesh()

    progress(30 + 30 * finishedLayers / len(layers), u"Writing vector layer ({0} of {1}): {2}".format(finishedLayers + 1, len(layers), mapLayer.name()))

    # write layer object
    layer = VectorLayer(writer, mapLayer, prop, obj_mod)
    writer.writeLayer(layer.layerObject(), layer.fieldNames)

    # initialize symbol rendering
    mapLayer.rendererV2().startRender(renderer.rendererContext(), mapLayer.pendingFields() if QGis.QGIS_VERSION_INT >= 20300 else mapLayer)

    # features to export
    request = QgsFeatureRequest()
    clipGeom = None
    if properties.get("radioButton_IntersectingFeatures", False):
      request.setFilterRect(layer.transform.transformBoundingBox(baseExtent.boundingBox(), QgsCoordinateTransform.ReverseTransform))
      if properties.get("checkBox_Clip"):
        extent = baseExtent.clone().scale(0.999999)   # clip with slightly smaller extent than map canvas extent
        clipGeom = extent.geometry()

    for feat in layer.features(request, clipGeom):
      # write geometry
      obj_mod.write(writer, layer, feat)   # writer.writeFeature(layer, feat, obj_mod)

      # stack attributes in writer
      if layer.writeAttrs:
        writer.addAttributes(feat.attributes())

    # write attributes
    if layer.writeAttrs:
      writer.writeAttributes()

    # write materials
    writer.writeMaterials(layer.materialManager)

    mapLayer.rendererV2().stopRender(renderer.rendererContext())
    finishedLayers += 1