Compare commits

...

2 Commits

Author SHA1 Message Date
KatKatKateryna fca3e00e79 Merge pull request #10 from specklesystems/kate/development
fixed z-dimension; multi-geometry types; receiving incomplete arcs; u…
2022-08-30 21:36:22 +01:00
KatKatKateryna 60c2875a38 fixed z-dimension; multi-geometry types; receiving incomplete arcs; updated Readmi 2022-08-31 04:35:49 +08:00
17 changed files with 182 additions and 314 deletions
View File
+4 -4
View File
@@ -1,5 +1,5 @@
# to build an installer: run cmd from this folder:
# "%PROGRAMFILES%\\ArcGIS\\Pro\\bin\\Python\\envs\\arcgispro-py3\\python.exe" C:\\Users\\Kateryna\\Documents\\00_Speckle\\GitHub\\speckle-arcgis\\setup.py sdist bdist_wheel
# "%PROGRAMFILES%\\ArcGIS\\Pro\\bin\\Python\\envs\\arcgispro-py3\\python.exe" C:\\Users\\username\\Documents\\00_Speckle\\GitHub\\speckle-arcgis\\setup.py sdist bdist_wheel
import os
from setuptools import setup
@@ -13,7 +13,7 @@ setup(name='speckle_toolbox',
version='0.1',
author='SpeckleSystems',
description=("Example for extending geoprocessing through Python modules"),
long_description=read('Readme.txt'),
long_description=read('Readme.md'),
python_requires='~=3.3',
packages=['speckle_toolbox'],
package_data={'speckle_toolbox':['esri/toolboxes/*',
@@ -26,6 +26,6 @@ setup(name='speckle_toolbox',
)
# then to install in ArcGIS:
# import sysconfig; import subprocess; x = sysconfig.get_paths()['data'] + r"\python.exe"; subprocess.run((x, '-m','pip', 'install', 'C:\\Users\\Kateryna\\Documents\\00_Speckle\\GitHub\\speckle-arcgis\\dist\\foo-0.1-py3-none-any.whl'), capture_output=True, text=True, shell=True, timeout=1000 )
# import sysconfig; import subprocess; x = sysconfig.get_paths()['data'] + r"\python.exe"; subprocess.run((x, '-m','pip', 'install', 'C:\\Users\\username\\Documents\\00_Speckle\\GitHub\\speckle-arcgis\\dist\\foo-0.1-py3-none-any.whl'), capture_output=True, text=True, shell=True, timeout=1000 )
# to uninstall:
# "C:\\Users\\Kateryna\\AppData\\Local\\ESRI\\conda\\envs\\arcgispro-py3-speckle\\python.exe" -m pip uninstall C:\\Users\\Kateryna\\Documents\\00_Speckle\\GitHub\\speckle-arcgis\\dist\\foo-0.1-py3-none-any.whl
# "C:\\Users\\username\\AppData\\Local\\ESRI\\conda\\envs\\arcgispro-py3-speckle\\python.exe" -m pip uninstall C:\\Users\\username\\Documents\\00_Speckle\\GitHub\\speckle-arcgis\\dist\\foo-0.1-py3-none-any.whl
@@ -16,7 +16,7 @@ import arcpy
def setup():
#print(plugin_dir)
pythonExec = get_python_path() # import numpy; import os; print(os.path.abspath(numpy.__file__))
print(pythonExec)
#print(pythonExec)
if pythonExec is None: # env is default, need to restart ArcGIS
return False
@@ -26,18 +26,18 @@ def get_python_path(): # create a full copy of default env
# import specklepy; import os; print(os.path.abspath(specklepy.__file__)) ##currentPythonExec = sysconfig.get_paths()['data'] + r"\python.exe"
pythonExec = os.environ["ProgramFiles"] + r'\ArcGIS\Pro\bin\Python\envs\arcgispro-py3\python.exe' #(r"%PROGRAMFILES%\ArcGIS\Pro\bin\Python\envs\arcgispro-py3\python.exe") #os.path.dirname(sys.executable) + "\\python.exe" # default python.exe
print(pythonExec)
#print(pythonExec)
if sys.platform == "win32":
env_new_name = "arcgispro-py3-speckle"
clone_env(pythonExec, env_new_name) # only if doesn't exist yet
#clone_env(pythonExec, env_new_name) # only if doesn't exist yet
activate_env(env_new_name)
return pythonExec
else: pass
def clone_env(pythonExec_old: str, env_new_name: str):
install_folder = os.getenv('APPDATA').replace("\\Roaming","") + r"\Local\ESRI\conda\envs" #r"%LOCALAPPDATA%\ESRI\conda\envs"
print("Clone default ArcGIS Pro conda env")
print(install_folder)
#print("Clone default ArcGIS Pro conda env")
#print(install_folder)
#if not os.path.exists(install_folder): os.makedirs(install_folder)
default_env = pythonExec_old.replace("Pro\\bin\\Python\\envs\\arcgispro-py3\\python.exe","Pro\\bin\\Python\\envs\\arcgispro-py3") # + "\\" + 'arcgispro-py3'
@@ -51,7 +51,7 @@ def clone_env(pythonExec_old: str, env_new_name: str):
def activate_env(env_new_name: str):
# using Popen, because process does not return result; subprocess.run will hang indefinitely
variable = subprocess.Popen((f'proswap {env_new_name}'),stdout = subprocess.PIPE,stderr = subprocess.PIPE,text = True,shell = True)
print(variable)
#print(variable)
# activate new env : https://support.esri.com/en/technical-article/000024206
setup()
@@ -7,7 +7,7 @@
from subprocess_call import subprocess_call
import os
pythonPath = 'C:\\ ...\\custom_environment_name\\python.exe"
pythonPath = "C:\\ ...\\custom_environment_name\\python.exe"
def installToolbox(newExec: str):
print("Installing Speckle Toolbox")
+5 -5
View File
@@ -15,21 +15,21 @@ def subprocess_call(*args, **kwargs):
startupinfo.wShowWindow = subprocess.SW_HIDE
kwargs['startupinfo'] = startupinfo
print("start")
print(*args)
#print(*args)
try:
# if manually: cmd.exe -> conda activate [env folder] -> pip install specklepy
result = subprocess.run(*args, capture_output=True, text=True, shell=True, timeout=1000)
print(result)
#print(result)
#result = subprocess.Popen( arg, shell=True, stdout=subprocess.PIPE) #, stderr=subprocess.STDOUT)
#retcode = subprocess.check_call(*args, **kwargs) # Creates infinite loop, known issue: https://github.com/python/cpython/issues/87512
except CalledProcessError as e:
print("ERROR: " + e.output)
#print("ERROR: " + e.output)
return False
except subprocess.TimeoutExpired as e:
print("Timeout Error: " + str(e.args[0])) # e.g. Defaulting to user installation because normal site-packages is not writeable
#print("Timeout Error: " + str(e.args[0])) # e.g. Defaulting to user installation because normal site-packages is not writeable
return False
except Exception as e:
print(str(e))
#print(str(e))
return False
except: print("unknown error")
print("end")
+2 -2
View File
@@ -12,7 +12,7 @@ def installToolbox(newExec: str):
return
def installDependencies(pythonExec: str):
print("Installing dependencies")
#print("Installing dependencies")
print(pythonExec)
try:
import pip
@@ -26,7 +26,7 @@ def installDependencies(pythonExec: str):
pkgVersion = "2.7.4"
pkgName = "specklepy"
try:
import specklepy # C:\Users\Kateryna\AppData\Roaming\Python\Python37\site-packages\specklepy\__init__.py
import specklepy # C:\Users\username\AppData\Roaming\Python\Python37\site-packages\specklepy\__init__.py
except Exception as e:
subprocess_call([ pythonExec, "-m", "pip", "install", f"{pkgName}=={pkgVersion}"])
+3 -3
View File
@@ -25,7 +25,7 @@ What is Speckle? Check our ![YouTube Video Views](https://img.shields.io/youtube
- **GraphQL API:** get what you need anywhere you want it
- **Webhooks:** the base for a automation and next-gen pipelines
- **Built for developers:** we are building Speckle with developers in mind and got tools for every stack
- **Built for the AEC industry:** Speckle connectors are plugins for the most common software used in the industry such as Revit, Rhino, Grasshopper, AutoCAD, Civil 3D, Excel, Unreal Engine, Unity, QGIS (you are here), Blender and more!
- **Built for the AEC industry:** Speckle connectors are plugins for the most common software used in the industry such as Revit, Rhino, Grasshopper, AutoCAD, Civil 3D, Excel, Unreal Engine, Unity, QGIS, ArcGIS (you are here), Blender and more!
### Try Speckle now!
@@ -44,7 +44,7 @@ Give Speckle a try in no time by:
## Repo Structure
This repo contains the QGIS plugin for Speckle 2.0. It is written in `python` and uses our fantastic [Python SDK](https://github.com/specklesystems/speckle-py). The [Speckle Server](https://github.com/specklesystems/Server) is providing all the web-facing functionality and can be found [here](https://github.com/specklesystems/Server).
This repo contains the ArcGIS plugin for Speckle 2.0. It is written in `python` and uses our fantastic [Python SDK](https://github.com/specklesystems/speckle-py). The [Speckle Server](https://github.com/specklesystems/Server) is providing all the web-facing functionality and can be found [here](https://github.com/specklesystems/Server).
> **Try it out!!**
> Although we're still in early development stages, we encourage you to try out the latest stable release.
@@ -52,7 +52,7 @@ This repo contains the QGIS plugin for Speckle 2.0. It is written in `python` an
>
> **What can it do?**
>
> Currently, the plugin allows to send data from a single layer to a Speckle server using one of the accounts configured on your computer. It will extract all the features of that layer along side their properties and, when possible, geometry too.
> Currently, the plugin allows to receive the data from Speckle and send data from a AcrGIS Pro layers to a Speckle server using one of the accounts configured on your computer. It will extract all the features of that layer along side their properties.
> The following geometry types are supported for now:
>
> - Point
@@ -18,8 +18,8 @@ def convertToSpeckle(feature, layer, geomType, featureType) -> Union[Base, Seque
geomMultiType = geom.isMultipart
hasCurves = feature.hasCurves
print(featureType) # e.g. Simple
print(geomType) # e.g. Polygon
#print(featureType) # e.g. Simple
#print(geomType) # e.g. Polygon
#geomSingleType = (featureType=="Simple") # Simple,SimpleJunction,SimpleJunction,ComplexEdge,Annotation,CoverageAnnotation,Dimension,RasterCatalogItem
if geomType == "Point": #Polygon, Point, Polyline, Multipoint, MultiPatch
@@ -38,7 +38,7 @@ def convertToSpeckle(feature, layer, geomType, featureType) -> Union[Base, Seque
def convertToNative(base: Base, sr: arcpy.SpatialReference) -> Union[Any, None]:
"""Converts any given base object to QgsGeometry."""
#print("___Convert to Native___")
print("___Convert to Native SingleType___")
#print(base)
converted = None
conversions = [
@@ -62,46 +62,39 @@ def convertToNative(base: Base, sr: arcpy.SpatialReference) -> Union[Any, None]:
return converted
def multiPointToNative(items: List[Point], sr: arcpy.SpatialReference):
print("Create MultiPoint")
print("___Create MultiPoint")
all_pts = []
# example https://pro.arcgis.com/en/pro-app/2.8/arcpy/classes/multipoint.htm
for item in items:
pt = pointToCoord(item) # [x, y, z]
all_pts.append( arcpy.Point(pt[0], pt[1], pt[2]) )
print(all_pts)
#print(all_pts)
features = arcpy.Multipoint( arcpy.Array(all_pts) )
#if len(features)==0: features = None
return features
def multiPolylineToNative(items: List[Polyline], sr: arcpy.SpatialReference):
print("_______Drawing Multipolylines____")
print(items)
all_pts = []
# example https://community.esri.com/t5/python-questions/creating-a-multipolygon-polygon/td-p/392918
for item in items:
pts = []
for pt in item.as_points(): #[[x,y,z],[x,y,z],..]
pt = pointToCoord(pt)
pts.append(arcpy.Point(pt[0], pt[1], pt[2]) )
all_pts.append(arcpy.Array(pts))
poly = arcpy.Polygon(arcpy.Array(all_pts), sr)
#print(items)
poly = None
return poly
def multiPolygonToNative(items: List[Base], sr: arcpy.SpatialReference): #TODO fix multi features
print("_______Drawing Multipolygons____")
print(items)
#print(items)
for item in items: # will be 1 item
print(item)
#print(item)
pts = [pointToCoord(pt) for pt in item["boundary"].as_points()]
outer_arr = [arcpy.Point(*coords) for coords in pts]
outer_arr.append(outer_arr[0])
list_of_arrs = []
try:
for void in item["voids"]:
print(void)
#print(void)
pts = [pointToCoord(pt) for pt in void.as_points()]
print(pts)
#print(pts)
inner_arr = [arcpy.Point(*coords) for coords in pts]
inner_arr.append(inner_arr[0])
list_of_arrs.append(arcpy.Array(inner_arr))
@@ -109,23 +102,12 @@ def multiPolygonToNative(items: List[Base], sr: arcpy.SpatialReference): #TODO f
list_of_arrs.insert(0, arcpy.Array(outer_arr))
array = arcpy.Array(list_of_arrs)
polygon = arcpy.Polygon(array, sr)
polygon = arcpy.Polygon(array, sr, has_z=True)
r'''
all_pts = []
# example https://community.esri.com/t5/python-questions/creating-a-multipolygon-polygon/td-p/392918
for item in items:
pts = []
for pt in item["boundary"].as_points(): #[[x,y,z],[x,y,z],..]
pt = pointToCoord(pt)
pts.append(arcpy.Point(pt[0], pt[1], pt[2]) )
pts.append(pts[0])
all_pts.append(arcpy.Array(pts))
polygon = arcpy.Polygon(arcpy.Array(all_pts), sr)
'''
return polygon
def convertToNativeMulti(items: List[Base], sr: arcpy.SpatialReference):
print("___Convert to Native MultiType___")
first = items[0]
if isinstance(first, Point):
return multiPointToNative(items, sr)
@@ -47,10 +47,10 @@ def pointToSpeckle(pt, feature, layer):
def pointToNative(pt: Point, sr: arcpy.SpatialReference) -> arcpy.PointGeometry:
"""Converts a Speckle Point to QgsPoint"""
#print("___pointToNative__")
print("___pointToNative__")
#print(pt)
pt = scalePointToNative(pt, pt.units)
geom = arcpy.PointGeometry(arcpy.Point(pt.x, pt.y, pt.z), sr)
geom = arcpy.PointGeometry(arcpy.Point(pt.x, pt.y, pt.z), sr, has_z = True)
#print(geom)
return geom
@@ -68,18 +68,12 @@ def polygonToSpeckle(geom, feature, layer, multiType: bool):
if multiType is False:
print("single type")
for p in geom:
#print(p) # <geoprocessing array object object at 0x0000020F1D972C90>
for pt in p:
#print(pt) # 284394.58100903 5710688.11602606 NaN NaN <class 'arcpy.arcobjects.arcobjects.Point'>
#print(type(pt))
if pt != None: pointList.append(pt)
boundary = polylineFromVerticesToSpeckle(pointList, True, feature, layer)
else:
print("multi type")
for i, p in enumerate(geom):
#print(i)
#print(p) # <geoprocessing array object object at 0x00000296FFF11CF0>
#print(type(p)) # <class 'arcpy.arcobjects.arcobjects.Array'>
for pt in p:
#print(pt) # 284394.58100903 5710688.11602606 NaN NaN
if pt == None and boundary == None: # first break
@@ -96,15 +90,6 @@ def polygonToSpeckle(geom, feature, layer, multiType: bool):
void = polylineFromVerticesToSpeckle(pointList, True, feature, layer)
voids.append(void)
#print("boundary: ")
#print(boundary)
#try:
# for i in range(geom.numInteriorRings()):
# intRing = polylineFromVerticesToSpeckle(geom.interiorRing(i).vertices(), True, feature, layer)
# voids.append(intRing)
#except:
# pass
polygon.boundary = boundary
polygon.voids = voids
polygon.displayValue = [ boundary ] + voids
@@ -114,7 +99,7 @@ def polygonToSpeckle(geom, feature, layer, multiType: bool):
total_vertices = 0
polyBorder = boundary.as_points()
print(polyBorder)
#print(polyBorder)
if len(polyBorder)>2:
print("make meshes from polygons")
@@ -125,11 +110,11 @@ def polygonToSpeckle(geom, feature, layer, multiType: bool):
z = 0 if math.isnan(pt.z) else pt.z
vertices.extend([x, y, z])
total_vertices += 1
print(vertices)
#print(vertices)
ran = range(0, total_vertices)
faces = [total_vertices]
faces.extend([i for i in ran])
print(faces)
#print(faces)
# else: https://docs.panda3d.org/1.10/python/reference/panda3d.core.Triangulator
else:
trianglator = Triangulator()
@@ -162,24 +147,20 @@ def polygonToSpeckle(geom, feature, layer, multiType: bool):
trianglator.triangulate()
i = 0
#print(trianglator.getNumTriangles())
while i < trianglator.getNumTriangles():
tr = [trianglator.getTriangleV0(i),trianglator.getTriangleV1(i),trianglator.getTriangleV2(i)]
faces.extend([3, tr[0], tr[1], tr[2]])
i+=1
ran = range(0, total_vertices)
print(polygon)
#print(polygon)
col = (100<<16) + (100<<8) + 100 #featureColorfromNativeRenderer(feature, layer)
colors = [col for i in ran] # apply same color for all vertices
mesh = rasterToMesh(vertices, faces, colors)
polygon.displayValue = mesh
print("print resulted polygon")
print(polygon)
#print("print resulted polygon")
#print(polygon)
return polygon
#except:
# arcpy.AddWarning("Some polygons might be invalid")
# pass
def polygonToNative(poly: Base, sr: arcpy.SpatialReference) -> arcpy.Polygon:
"""Converts a Speckle Polygon base object to QgsPolygon.
@@ -193,15 +174,15 @@ def polygonToNative(poly: Base, sr: arcpy.SpatialReference) -> arcpy.Polygon:
list_of_arrs = []
try:
for void in poly["voids"]:
print(void)
#print(void)
pts = [pointToCoord(pt) for pt in void.as_points()]
print(pts)
#print(pts)
inner_arr = [arcpy.Point(*coords) for coords in pts]
inner_arr.append(inner_arr[0])
list_of_arrs.append(arcpy.Array(inner_arr))
except:pass
list_of_arrs.insert(0, outer_arr)
array = arcpy.Array(list_of_arrs)
polygon = arcpy.Polygon(array, sr)
polygon = arcpy.Polygon(array, sr, has_z=True)
return polygon
@@ -11,7 +11,7 @@ from speckle.converter.layers.utils import get_scale_factor
def circleToSpeckle(center, point, layer):
print("___Circle to Speckle____")
rad = math.sqrt(math.pow((center[0] - point[0]),2) + math.pow((center[1] - point[1]),2) )
print(rad)
#print(rad)
if len(center)>2: center_z = center[2]
else: center_z = 0
length = rad*2*math.pi
@@ -20,29 +20,21 @@ def circleToSpeckle(center, point, layer):
units = 3 #"m"
args = [0] + [rad] + domain + plane + [units]
print(args)
#print(args)
c = Circle().from_list(args)
#c.length = length
#c.domain = Interval.from_list([0, 1])
print(c)
#print(c)
return c
def polylineToSpeckle(geom, feature, layer, multiType: bool):
#try:
print("___Polyline to Speckle____")
polyline = None
pointList = []
print(geom.hasCurves)
#print(geom) # <geoprocessing describe geometry object object at 0x0000020F1D94AB10>
#print(multiType)
#print(geom.hasCurves)
if multiType is False:
for p in geom:
#print(p) # <geoprocessing array object object at 0x0000020F1D972C90>
for pt in p:
#print(pt) # 284394.58100903 5710688.11602606 NaN NaN
#print(type(pt)) #<class 'arcpy.arcobjects.arcobjects.Point'>
if pt != None: pointList.append(pt); print(pt.Z)
if pt != None: pointList.append(pt)#; print(pt.Z)
closed = False
if pointList[0] == pointList[len(pointList)-1]:
closed = True
@@ -54,13 +46,11 @@ def polylineToSpeckle(geom, feature, layer, multiType: bool):
def polylineFromVerticesToSpeckle(vertices, closed, feature, layer):
"""Converts a Polyline to Speckle"""
print("___PolyLINE to Speckle____")
print("___Polyline from vertices to Speckle____")
specklePts = []
for pt in vertices:
newPt = pointToSpeckle(pt, feature, layer)
specklePts.append(newPt)
#print(len(specklePts))
#print(specklePts)
# TODO: Replace with `from_points` function when fix is pushed.
polyline = Polyline(units = "m")
@@ -71,25 +61,20 @@ def polylineFromVerticesToSpeckle(vertices, closed, feature, layer):
if closed and i == len(specklePts) - 1:
continue
polyline.value.extend([point.x, point.y, point.z])
#print(polyline)
'''
col = featureColorfromNativeRenderer(feature, layer)
polyline['displayStyle'] = {}
polyline['displayStyle']['color'] = col
'''
return polyline
def polylineToNative(poly: Polyline, sr: arcpy.SpatialReference) -> arcpy.Polyline:
"""Converts a Speckle Polyline to QgsLineString"""
print("__ convert poly to native __")
#print(poly)
pts = [pointToCoord(pt) for pt in poly.as_points()]
if poly.closed is True:
pts.append( pointToCoord(poly.as_points()[0]) )
#print(pts)
polyline = arcpy.Polyline( arcpy.Array([arcpy.Point(*coords) for coords in pts]), sr )
#print(polyline)
pts_coord_list = [arcpy.Point(*coords) for coords in pts]
polyline = arcpy.Polyline( arcpy.Array(pts_coord_list), sr, has_z=True )
#print(polyline.JSON)
return polyline
@@ -97,8 +82,7 @@ def lineToNative(line: Line, sr: arcpy.SpatialReference) -> arcpy.Polyline:
"""Converts a Speckle Line to QgsLineString"""
print("___Line to Native___")
pts = [pointToCoord(pt) for pt in [line.start, line.end]]
print(pts)
line = arcpy.Polyline( arcpy.Array([arcpy.Point(*coords) for coords in pts]), sr )
line = arcpy.Polyline( arcpy.Array([arcpy.Point(*coords) for coords in pts]), sr , has_z=True)
return line
def curveToNative(poly: Curve, sr: arcpy.SpatialReference) -> arcpy.Polyline:
@@ -118,37 +102,24 @@ def circleToNative(poly: Circle, sr: arcpy.SpatialReference) -> arcpy.Polyline:
points = []
angle1 = math.pi/2
#try:
pointsNum = math.floor(math.pi*2) * 12
if pointsNum <4: pointsNum = 4
points.append(pointToCoord(poly.plane.origin))
#print(points)
#print(poly.units)
radScaled = poly.radius * get_scale_factor(poly.units)
points[0][1] += radScaled
#print(points)
#print(pointsNum)
for i in range(1, pointsNum + 1):
#print(pointsNum)
#print(i)
k = i/pointsNum # to reset values from 1/10 to 1
#print(k)
#print(poly.plane.normal.z)
angle = angle1 + k * math.pi*2 * poly.plane.normal.z
if poly.plane.normal.z == 0: normal = 1
else: normal = poly.plane.normal.z
angle = angle1 + k * math.pi*2 * normal
pt = Point( x = poly.plane.origin.x + radScaled * cos(angle), y = poly.plane.origin.y + radScaled * sin(angle), z = 0)
pt.units = "m"
#print(pt)
points.append(pointToCoord(pt))
points.append(points[0])
#print(points)
curve = arcpy.Polyline( arcpy.Array([arcpy.Point(*coords) for coords in points]), sr )
curve = arcpy.Polyline( arcpy.Array([arcpy.Point(*coords) for coords in points]), sr , has_z=True)
return curve
#except: return None
scaleFactor = get_scale_factor(poly.units)
circ = None #QgsCircle(pointToNative(poly.plane.origin), poly.radius * scaleFactor)
#circ = circ.toLineString() # QgsCircle is not supported to be added as a feature
return circ
def polycurveToNative(poly: Polycurve, sr: arcpy.SpatialReference) -> arcpy.Polyline:
points = []
@@ -157,7 +128,7 @@ def polycurveToNative(poly: Polycurve, sr: arcpy.SpatialReference) -> arcpy.Poly
try:
for segm in poly.segments: # Line, Polyline, Curve, Arc, Circle
print(segm)
#print(segm)
if isinstance(segm,Line): converted = lineToNative(segm, sr) # QgsLineString
elif isinstance(segm,Polyline): converted = polylineToNative(segm, sr) # QgsLineString
elif isinstance(segm,Curve): converted = curveToNative(segm, sr) # QgsLineString
@@ -165,52 +136,70 @@ def polycurveToNative(poly: Polycurve, sr: arcpy.SpatialReference) -> arcpy.Poly
elif isinstance(segm,Arc): converted = arcToNativePoints(segm, sr) # QgsLineString
else: # either return a part of the curve, of skip this segment and try next
arcpy.AddWarning(f"Part of the polycurve cannot be converted")
curve = arcpy.Polyline( arcpy.Array([arcpy.Point(*coords) for coords in points]) )
curve = arcpy.Polyline( arcpy.Array([arcpy.Point(*coords) for coords in points]), sr , has_z=True)
return curve
if converted is not None:
print(converted) # <geoprocessing describe geometry object object at 0x000002B2D3E338D0>
#print(converted) # <geoprocessing describe geometry object object at 0x000002B2D3E338D0>
for part in converted:
print(part) # <geoprocessing array object object at 0x000002B2D2E09530>
#print(part) # <geoprocessing array object object at 0x000002B2D2E09530>
for pt in part:
print(pt) # 64.4584221540162 5.5 NaN NaN
#print(pt) # 64.4584221540162 5.5 NaN NaN
if pt.Z != None: pt_z = pt.Z
else: pt_z = 0
print(pt_z)
print(len(points))
#print(pt_z)
#print(len(points))
if len(points)>0 and pt.X == points[len(points)-1][0] and pt.Y == points[len(points)-1][1] and pt_z == points[len(points)-1][2]: pass
else: points.append(pointToCoord(Point(x=pt.X, y = pt.Y, z = pt_z)))
print(points)
#print(points)
else:
arcpy.AddWarning(f"Part of the polycurve cannot be converted")
curve = arcpy.Polyline( arcpy.Array([arcpy.Point(*coords) for coords in points]) )
curve = arcpy.Polyline( arcpy.Array([arcpy.Point(*coords) for coords in points]), sr, has_z=True )
return curve
except: curve = None
print(curve)
#print(curve)
curve = arcpy.Polyline( arcpy.Array([arcpy.Point(*coords) for coords in points]), sr )
curve = arcpy.Polyline( arcpy.Array([arcpy.Point(*coords) for coords in points]), sr, has_z=True )
return curve
def arcToNativePoints(poly: Arc, sr: arcpy.SpatialReference):
print("__Arc to native__")
points = []
if poly.startPoint.x == poly.plane.origin.x: angle1 = math.pi/2
else: angle1 = atan( abs ((poly.startPoint.y - poly.plane.origin.y) / (poly.startPoint.x - poly.plane.origin.x) )) # between 0 and pi/2
#print(angle1)
if poly.plane.origin.x < poly.startPoint.x and poly.plane.origin.y > poly.startPoint.y: angle1 = 2*math.pi - angle1
if poly.plane.origin.x > poly.startPoint.x and poly.plane.origin.y > poly.startPoint.y: angle1 = math.pi + angle1
if poly.plane.origin.x > poly.startPoint.x and poly.plane.origin.y < poly.startPoint.y: angle1 = math.pi - angle1
print(angle1)
try:
pointsNum = math.floor( abs(poly.endAngle - poly.startAngle)) * 12
if pointsNum <4: pointsNum = 4
points.append(pointToCoord(poly.startPoint))
if poly.endPoint.x == poly.plane.origin.x: angle2 = math.pi/2
else: angle2 = atan( abs ((poly.endPoint.y - poly.plane.origin.y) / (poly.endPoint.x - poly.plane.origin.x) )) # between 0 and pi/2
#print(angle2)
if poly.plane.origin.x < poly.endPoint.x and poly.plane.origin.y > poly.endPoint.y: angle2 = 2*math.pi - angle2
if poly.plane.origin.x > poly.endPoint.x and poly.plane.origin.y > poly.endPoint.y: angle2 = math.pi + angle2
if poly.plane.origin.x > poly.endPoint.x and poly.plane.origin.y < poly.endPoint.y: angle2 = math.pi - angle2
print(angle2)
try: interval = math.floor(poly.endAngle - poly.startAngle)
except: interval = math.floor(angle2-angle1)
pointsNum = math.floor( abs(interval)) * 12
if pointsNum <4: pointsNum = 4
points.append(pointToCoord(poly.startPoint))
print(points)
print(interval)
print(pointsNum)
for i in range(1, pointsNum + 1):
k = i/pointsNum # to reset values from 1/10 to 1
if poly.plane.normal.z == 0: normal = 1
else: normal = poly.plane.normal.z
angle = angle1 + k * interval * normal
print(f"k: {str(i)} multiplied: {str(k*interval)} angle: {str(angle1 + k * interval)}")
#print(cos(angle))
pt = Point( x = poly.plane.origin.x + poly.radius * cos(angle), y = poly.plane.origin.y + poly.radius * sin(angle), z = 0)
pt.units = poly.startPoint.units
points.append(pointToCoord(pt))
#print(pointToCoord(pt))
points.append(pointToCoord(poly.endPoint))
curve = arcpy.Polyline( arcpy.Array([arcpy.Point(*coords) for coords in points]), sr, has_z=True )
return curve
for i in range(1, pointsNum + 1):
k = i/pointsNum # to reset values from 1/10 to 1
angle = angle1 + k * ( poly.endAngle - poly.startAngle) * poly.plane.normal.z
pt = Point( x = poly.plane.origin.x + poly.radius * cos(angle), y = poly.plane.origin.y + poly.radius * sin(angle), z = 0)
pt.units = poly.startPoint.units
points.append(pointToCoord(pt))
points.append(pointToCoord(poly.endPoint))
curve = arcpy.Polyline( arcpy.Array([arcpy.Point(*coords) for coords in points]), sr )
return curve
except: return None
@@ -51,8 +51,8 @@ def layerToSpeckle(layer: arcLayer, project: ArcGISProject) -> Layer: #now the i
projectCRS = project.activeMap.spatialReference
try: data = arcpy.Describe(layer.dataSource)
except OSError as e: arcpy.AddWarning(str(e.args[0])); return
print(projectCRS)
print(projectCRS.name)
#print(projectCRS)
#print(projectCRS.name)
crs = CRS(name = projectCRS.name, wkt = projectCRS.exportToString(), units = "m")
layer_geo_crs = None
@@ -69,11 +69,12 @@ def layerToSpeckle(layer: arcLayer, project: ArcGISProject) -> Layer: #now the i
try: # https://pro.arcgis.com/en/pro-app/2.8/arcpy/get-started/the-spatial-reference-object.htm
layerObjs = []
print(data.datasetType)
if data.datasetType == "FeatureClass": #FeatureClass, ?Table Properties, ?Datasets
# write feature attributes
fieldnames = [field.name for field in data.fields]
print(layer.longName) # e.g. 17b0b76d13_custom_crs_04dcfaa936\04dcfaa936_Vector_lineGeom
print(fieldnames) # e.g. ['OBJECTID', 'Shape', 'Shape_Length', 'Speckle_ID', 'number', 'area']
#print(layer.longName) # e.g. 17b0b76d13_custom_crs_04dcfaa936\04dcfaa936_Vector_lineGeom
#print(fieldnames) # e.g. ['OBJECTID', 'Shape', 'Shape_Length', 'Speckle_ID', 'number', 'area']
rows_shapes = arcpy.da.SearchCursor(layer.longName, "Shape@") # arcpy.da.SearchCursor(in_table, field_names, {where_clause}, {spatial_reference}, {explode_to_points}, {sql_clause})
#print(rows_shapes) # <da.SearchCursor object at 0x00000172565E6C10>
print("__ start iterating features")
@@ -81,20 +82,20 @@ def layerToSpeckle(layer: arcLayer, project: ArcGISProject) -> Layer: #now the i
for i, features in enumerate(rows_shapes):
print("____Feature # " + str(i+1))
if features[0] == None: continue
print(features[0].hasCurves)
#print(features[0].hasCurves)
if features[0].hasCurves: continue
rows_attributes = arcpy.da.SearchCursor(layer.longName, fieldnames)
row_attr = []
for k, attrs in enumerate(rows_attributes):
if i == k: row_attr = attrs; break
print(features) #(<Polygon object at 0x172592ae8c8[0x17258d2a600]>,)
print(features[0].pointCount)
print(features[0].partCount)
#print(features) #(<Polygon object at 0x172592ae8c8[0x17258d2a600]>,)
#print(features[0].pointCount)
#print(features[0].partCount)
if features[0]:
b = featureToSpeckle(fieldnames, row_attr, features[0], projectCRS, project, layer)
layerObjs.append(b)
print(layerObjs)
#print(layerObjs)
print("__ finish iterating features")
speckleLayer.features=layerObjs
@@ -153,7 +154,7 @@ def cadVectorLayerToNative(geomList, layerName: str, geomType: str, streamBranch
#CREATE A GROUP "received blabla" with sublayers
layerGroup = None
newGroupName = f'{streamBranch}'
print(newGroupName)
#print(newGroupName)
for l in active_map.listLayers():
if l.longName == newGroupName: layerGroup = l; break
@@ -165,35 +166,28 @@ def cadVectorLayerToNative(geomList, layerName: str, geomType: str, streamBranch
for l in project.activeMap.listLayers():
if l.longName.startswith(newGroupName + "\\"):
all_layer_names.append(l.longName)
print(all_layer_names)
#print(all_layer_names)
longName = streamBranch + "\\" + newName
if longName in all_layer_names:
for index, letter in enumerate('234567890abcdefghijklmnopqrstuvwxyz'):
print("trying options: ")
print((longName + "_" + letter))
if (longName + "_" + letter) not in all_layer_names: print("selected!"); newName += "_"+letter; layerExists +=1; break
if (longName + "_" + letter) not in all_layer_names: newName += "_"+letter; layerExists +=1; break
# particularly if the layer comes from ArcGIS
#geomType = layer.geomType # for ArcGIS: Polygon, Point, Polyline, Multipoint, MultiPatch
print(geomType)
if "polygon" in geomType.lower(): geomType = "Polygon"
if "line" in geomType.lower(): geomType = "Polyline"
if "multipoint" in geomType.lower(): geomType = "Multipoint"
elif "point" in geomType.lower(): geomType = "Point"
print(geomType)
#print(geomType)
print(newName)
#path = r"C:\Users\Kateryna\Documents\ArcGIS\Projects\MyProject-test\MyProject-test.gdb\\"
#print(newName)
#path = r"C:\Users\username\Documents\ArcGIS\Projects\MyProject-test\MyProject-test.gdb\\"
#https://community.esri.com/t5/arcgis-pro-questions/is-it-possible-to-create-a-new-group-layer-with/td-p/1068607
print("_________create feature class (cad)___________________________________")
# should be created inside the workspace to be a proper Feature class (not .shp) with Nullable Fields
class_name = ("f_class_" + newName)
#print(path)
#print(class_name)
#print(sr)
f_class = CreateFeatureclass(path, class_name, geomType, spatial_reference = sr)
f_class = CreateFeatureclass(path, class_name, geomType, has_z="ENABLED", spatial_reference = sr)
#print(f_class)
#print(geomList)
@@ -231,8 +225,8 @@ def cadVectorLayerToNative(geomList, layerName: str, geomType: str, streamBranch
new_feat = cadFeatureToNative(f, newFields, sr)
if new_feat != "" and new_feat != None:
fets.append(new_feat)
print("features created")
print(fets)
#print("features created")
#print(fets)
count = 0
rowValues = []
@@ -249,14 +243,14 @@ def cadVectorLayerToNative(geomList, layerName: str, geomType: str, streamBranch
row.append(value)
rowValues.append(row)
count += 1
print(heads)
#print(heads)
cur = arcpy.da.InsertCursor(str(f_class), tuple(heads) )
for row in rowValues:
#print(tuple(heads))
#print(tuple(row))
cur.insertRow(tuple(row))
del cur
print(f_class)
#print(f_class)
vl = MakeFeatureLayer(str(f_class), newName).getOutput(0)
#adding layers from code solved: https://gis.stackexchange.com/questions/344343/arcpy-makefeaturelayer-management-function-not-creating-feature-layer-in-arcgis
@@ -280,7 +274,7 @@ def vectorLayerToNative(layer: Layer, streamBranch: str, project: ArcGISProject)
#CREATE A GROUP "received blabla" with sublayers
layerGroup = None
newGroupName = f'{streamBranch}'
print(newGroupName)
#print(newGroupName)
for l in active_map.listLayers():
if l.longName == newGroupName: layerGroup = l; break
@@ -292,14 +286,12 @@ def vectorLayerToNative(layer: Layer, streamBranch: str, project: ArcGISProject)
for l in project.activeMap.listLayers():
if l.longName.startswith(newGroupName + "\\"):
all_layer_names.append(l.longName)
print(all_layer_names)
#print(all_layer_names)
longName = streamBranch + "\\" + newName
if longName in all_layer_names:
for index, letter in enumerate('234567890abcdefghijklmnopqrstuvwxyz'):
print("trying options: ")
print((longName + "_" + letter))
if (longName + "_" + letter) not in all_layer_names: print("selected!"); newName += "_"+letter; layerExists +=1; break
if (longName + "_" + letter) not in all_layer_names: newName += "_"+letter; layerExists +=1; break
# particularly if the layer comes from ArcGIS
geomType = layer.geomType # for ArcGIS: Polygon, Point, Polyline, Multipoint, MultiPatch
@@ -308,18 +300,18 @@ def vectorLayerToNative(layer: Layer, streamBranch: str, project: ArcGISProject)
if "line" in geomType.lower(): geomType = "Polyline"
if "multipoint" in geomType.lower(): geomType = "Multipoint"
elif "point" in geomType.lower(): geomType = "Point"
print(geomType)
#print(geomType)
print(newName)
#path = r"C:\Users\Kateryna\Documents\ArcGIS\Projects\MyProject-test\MyProject-test.gdb\\"
#print(newName)
#path = r"C:\Users\username\Documents\ArcGIS\Projects\MyProject-test\MyProject-test.gdb\\"
#https://community.esri.com/t5/arcgis-pro-questions/is-it-possible-to-create-a-new-group-layer-with/td-p/1068607
print(project.filePath.replace("aprx","gdb"))
print("_________create feature class___________________________________")
#print(project.filePath.replace("aprx","gdb"))
#print("_________create feature class___________________________________")
# should be created inside the workspace to be a proper Feature class (not .shp) with Nullable Fields
class_name = "f_class_" + newName
print(class_name)
try: f_class = CreateFeatureclass(path, class_name, geomType, spatial_reference = sr)
except arcgisscripting.ExecuteError: class_name+="_"; f_class = CreateFeatureclass(path, class_name, geomType, spatial_reference = sr)
#print(class_name)
try: f_class = CreateFeatureclass(path, class_name, geomType, has_z="ENABLED", spatial_reference = sr)
except arcgisscripting.ExecuteError: class_name+="_"; f_class = CreateFeatureclass(path, class_name, geomType, has_z="ENABLED", spatial_reference = sr)
# get and set Layer attribute fields
# example: https://resource.esriuk.com/blog/an-introductory-slice-of-arcpy-in-arcgis-pro/
@@ -349,33 +341,16 @@ def vectorLayerToNative(layer: Layer, streamBranch: str, project: ArcGISProject)
#print(matrix)
if len(matrix)>0: AddFields(str(f_class), matrix)
'''
# set the fields as nullable
for i, key in enumerate(all_keys):
#print(f_class)
for fc in arcpy.ListFeatureClasses():
#print(fc)
if fc == "class_" + newName:
for fl in arcpy.ListFields(fc):
# https://pro.arcgis.com/en/pro-app/2.8/tool-reference/data-management/alter-field-properties.htm
if fl.name == key:
#print("ADJUST FIELD:_________")
#print(fl.name)
#print(all_key_types[i])
#fl.isNullable = True
AlterField(f_class, key, key, key, all_key_types[i], "255", "NULLABLE", "FALSE")
break
'''
fets = []
for f in layer.features:
new_feat = featureToNative(f, newFields, sr)
new_feat = featureToNative(f, newFields, geomType, sr)
if new_feat != "" and new_feat!= None: fets.append(new_feat)
print(fets)
count = 0
rowValues = []
for feat in fets:
print(feat)
#print(feat)
try: feat['applicationId']
except: feat.update({'applicationId': count})
@@ -390,8 +365,8 @@ def vectorLayerToNative(layer: Layer, streamBranch: str, project: ArcGISProject)
count += 1
cur = arcpy.da.InsertCursor(str(f_class), tuple(heads) )
for row in rowValues:
#print(tuple(heads))
#print(tuple(row))
print(tuple(heads))
print(tuple(row))
cur.insertRow(tuple(row))
del cur
@@ -13,8 +13,8 @@ def featureToSpeckle(fieldnames, attr_list, f_shape, projectCRS: arcpy.SpatialRe
geomType = data.shapeType #Polygon, Point, Polyline, Multipoint, MultiPatch
featureType = data.featureType # Simple,SimpleJunction,SimpleJunction,ComplexEdge,Annotation,CoverageAnnotation,Dimension,RasterCatalogItem
print(layer_sr.name)
print(projectCRS.name)
#print(layer_sr.name)
#print(projectCRS.name)
#apply transformation if needed
if layer_sr.name != projectCRS.name:
@@ -70,8 +70,8 @@ def featureToSpeckle(fieldnames, attr_list, f_shape, projectCRS: arcpy.SpatialRe
print("Error converting geometry: " + str(error))
print(selectedLayer)
arcpy.AddError("Error converting geometry: " + str(error))
print(geomType)
print(featureType)
#print(geomType)
#print(featureType)
for i, name in enumerate(fieldnames):
corrected = name.replace("/", "_").replace(".", "-")
if corrected != "Shape" and corrected != "Shape@":
@@ -79,18 +79,19 @@ def featureToSpeckle(fieldnames, attr_list, f_shape, projectCRS: arcpy.SpatialRe
# save all attribute, duplicate one into applicationId
b[corrected] = attr_list[i]
if corrected == "FID" or corrected == "OID" or corrected == "OBJECTID": b["applicationId"] = str(attr_list[i])
print(b)
#print(b)
print("______end of __Feature to Speckle____________________")
return b
def featureToNative(feature: Base, fields: dict, sr: arcpy.SpatialReference):
print("Feature To Native____________")
def featureToNative(feature: Base, fields: dict, geomType: str, sr: arcpy.SpatialReference):
print("Feature To Native____________")
feat = {}
try: speckle_geom = feature["geometry"] # for created in QGIS / ArcGIS Layer type
except: speckle_geom = feature # for created in other software
print(speckle_geom)
if isinstance(speckle_geom, list):
arcGisGeom = convertToNativeMulti(speckle_geom, sr)
if len(speckle_geom)>1 or geomType == "Multipoint": arcGisGeom = convertToNativeMulti(speckle_geom, sr)
else: arcGisGeom = convertToNative(speckle_geom[0], sr)
else:
arcGisGeom = convertToNative(speckle_geom, sr)
@@ -99,15 +100,8 @@ def featureToNative(feature: Base, fields: dict, sr: arcpy.SpatialReference):
else:
return None
print(feat)
#try:
# if "id" not in fields.keys() and feature["applicationId"]: fields.update(QgsField("id", QVariant.String))
#except: pass
#feat.setFields(fields)
for key, variant in fields.items():
#if key.lower() == "objectid" or key.lower() == "fid": feat.update({key: str(feature["applicationId"]) })
#if key.lower() != "shape" and key.lower() != "shape@" and key != "arcGisGeomFromSpeckle":
#print(feature[key])
value = feature[key]
if variant == "TEXT": value = str(feature[key])
if variant == getVariantFromValue(value) and value != "NULL" and value != "None":
@@ -117,7 +111,6 @@ def featureToNative(feature: Base, fields: dict, sr: arcpy.SpatialReference):
if variant == "FLOAT": feat.update({key: None})
if variant == "LONG": feat.update({key: None})
if variant == "SHORT": feat.update({key: None})
#print(feat)
return feat
def cadFeatureToNative(feature: Base, fields: dict, sr: arcpy.SpatialReference):
@@ -125,22 +118,17 @@ def cadFeatureToNative(feature: Base, fields: dict, sr: arcpy.SpatialReference):
feat = {}
try: speckle_geom = feature["geometry"] # for created in QGIS Layer type
except: speckle_geom = feature # for created in other software
print(feature)
print(speckle_geom)
#print(feature)
#print(speckle_geom)
if isinstance(speckle_geom, list):
arcGisGeom = convertToNativeMulti(speckle_geom, sr)
if len(speckle_geom)>1: arcGisGeom = convertToNativeMulti(speckle_geom, sr)
else: arcGisGeom = convertToNative(speckle_geom[0], sr)
else:
arcGisGeom = convertToNative(speckle_geom, sr)
if arcGisGeom is not None:
feat.update({"arcGisGeomFromSpeckle": arcGisGeom})
else: return None
#print(feat)
#try:
# if "Speckle_ID" not in fields.names() and feature["id"]: fields.append(QgsField("Speckle_ID", QVariant.String))
#except: pass
#feat.setFields(fields)
for key, variant in fields.items():
value = feature[key]
if variant == "TEXT": value = str(feature[key])
@@ -151,25 +139,6 @@ def cadFeatureToNative(feature: Base, fields: dict, sr: arcpy.SpatialReference):
if variant == "FLOAT": feat.update({key: None})
if variant == "LONG": feat.update({key: None})
if variant == "SHORT": feat.update({key: None})
print(feat)
#print(feat)
return feat
for field in fields:
name = field.name()
variant = field.type()
if name == "Speckle_ID": feat[name] = str(feature["id"])
else:
value = feature[name]
if variant == QVariant.String: value = str(feature[name])
if isinstance(value, str) and variant == QVariant.Date: # 14
y,m,d = value.split("(")[1].split(")")[0].split(",")[:3]
value = QDate(int(y), int(m), int(d) )
elif isinstance(value, str) and variant == QVariant.DateTime:
y,m,d,t1,t2 = value.split("(")[1].split(")")[0].split(",")[:5]
value = QDateTime(int(y), int(m), int(d), int(t1), int(t2) )
if variant == getVariantFromValue(value) and value != "NULL" and value != "None":
feat[name] = value
@@ -38,7 +38,7 @@ def getLayerAttributes(features: List[Base]) -> dict:
except: pass
dynamicProps.sort()
print(dynamicProps)
#print(dynamicProps)
# add field names and variands
#variants = []
@@ -1,30 +0,0 @@
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<ArcGIS.Desktop xmlns="http://schemas.esri.com/DADF/Registry">
<QAT>esri_core_newProjectButton;esri_core_openProjectButton;esri_core_saveProjectButton;esri_core_undoSplitButton;esri_core_redoSplitButton;</QAT>
<QAT>esri_core_newProjectButton;esri_core_openProjectButton;esri_core_saveProjectButton;esri_core_undoSplitButton;esri_core_redoSplitButton;</QAT>
<modules>
<insertModule id="Custom_speckle">
<tabs>
<tab id="esriTab8b57edc2a9c81c3c" caption="Speckle" placeWith="esri_mapping_homeTab" insert="after">
<group refID="esriGroupdf926f3374d95768" />
</tab>
</tabs>
<groups>
<group id="esriGroupdf926f3374d95768" caption="">
<button refID="esri_geoprocessing_speckle_toolbox_SpeckleSender" size="large" />
</group>
</groups>
<controls>
<button id="esri_geoprocessing_speckle_toolbox_SpeckleSender" caption="Speckle" smallImage="C:\Users\Kateryna\Documents\00_Speckle\GitHub\speckle-arcgis\speckle\plugin_utils\speckle.png" largeImage="C:\Users\Kateryna\Documents\00_Speckle\GitHub\speckle-arcgis\speckle\plugin_utils\speckle.png" isCustomCommand="true" assembly="" className="esri_geoprocessing_module:Commands.ExecuteGPToolButton" extendedCaption="Speckle Toolbox">
<args>
<params toolPath="C:\Users\Kateryna\Documents\00_Speckle\GitHub\speckle-arcgis\Speckle.pyt\SpeckleSender" name="Speckle" xmlns="" />
</args>
<tooltip heading="Speckle">Allows you to send your layers to and receive from other software using Speckle server.</tooltip>
</button>
</controls>
</insertModule>
<updateModule refID="Custom_speckle">
<controls />
</updateModule>
</modules>
</ArcGIS.Desktop>
@@ -86,7 +86,7 @@ class uiInputs(object):
instances = []
def __init__(self):
print("start UI inputs________")
#print("start UI inputs________")
self.instances.append(self)
accounts = get_local_accounts()
account = None
@@ -95,10 +95,10 @@ class uiInputs(object):
#account.userInfo.name, account.serverInfo.url
self.speckle_client = SpeckleClient(account.serverInfo.url, account.serverInfo.url.startswith("https"))
self.speckle_client.authenticate_with_token(token=account.token)
print("ping")
print(self.speckle_client)
#print("ping")
#print(self.speckle_client)
self.streams = self.speckle_client.stream.search("")
print("ping")
#print("ping")
self.active_stream = None
self.active_branch = None
self.active_commit = None
@@ -110,7 +110,7 @@ class uiInputs(object):
#print(self.streams)
try: aprx = ArcGISProject('CURRENT')
except:
print(arcpy.env.workspace) # None
#print(arcpy.env.workspace) # None
#arcpy.env.workspace = ""
#proj_path = "\\".join(arcpy.env.workspace.split("\\")[:-1]) + "\\"
#aprx = ArcGISProject(proj_path)
@@ -127,7 +127,7 @@ class uiInputs(object):
class Speckle(object):
def __init__(self):
print("________________reset_______________")
#print("________________reset_______________")
self.label = "Speckle"
self.description = "Allows you to send and receive your layers " + \
"to/from other software using Speckle server."
@@ -142,7 +142,7 @@ class Speckle(object):
self.toolboxInputs = instance # take latest
except: pass
if self.toolboxInputs is None:
print("Instance is None")
#print("Instance is None")
self.toolboxInputs = uiInputs() #in case Toolbox class was not initialized
# TODO react on project changes
@@ -371,7 +371,7 @@ class Speckle(object):
# https://pro.arcgis.com/en/pro-app/latest/arcpy/get-started/what-is-arcpy-.htm
#Warning if any of the fields is invalid/empty
print("_______________________Run__________________________")
print(self.toolboxInputs.action)
#print(self.toolboxInputs.action)
if self.toolboxInputs.action == 1: self.onSend(parameters)
elif self.toolboxInputs.action == 0: self.onReceive(parameters)
@@ -419,7 +419,7 @@ class Speckle(object):
objId = operations.send(base=base_obj, transports=[transport])
except SpeckleException as error:
arcpy.AddError("Error sending data")
print("Error sending data")
#print("Error sending data")
return
except SpeckleWarning as warning:
arcpy.AddMessage("SpeckleWarning: " + str(warning.args[0]))
@@ -437,12 +437,12 @@ class Speckle(object):
source_application="ArcGIS",
)
arcpy.AddMessage("Successfully sent data to stream: " + streamId)
print("Successfully sent data to stream: " + streamId)
#print("Successfully sent data to stream: " + streamId)
#parameters[2].value = ""
except:
arcpy.AddError("Error creating commit")
print("sent")
#print("sent")
#self.updateParameters(parameters, True)
#self.refresh(parameters)
@@ -478,7 +478,7 @@ class Speckle(object):
return
try:
print(commit)
#print(commit)
objId = commit.referencedObject
commitDetailed = client.commit.get(streamId, commit.id)
app = commitDetailed.sourceApplication
@@ -497,23 +497,25 @@ class Speckle(object):
newGroupName = f'{streamBranch}'
groupExists = 0
#print(newGroupName)
for l in self.toolboxInputs.project.activeMap.listLayers():
#print(l.longName)
if l.longName.startswith(newGroupName + "\\"):
print(l.longName)
#print(l.longName)
self.toolboxInputs.project.activeMap.removeLayer(l)
groupExists+=1
elif l.longName == newGroupName:
groupExists+=1
if groupExists == 0:
# create empty group layer file
path = self.toolboxInputs.project.filePath.replace("aprx","gdb") #"\\".join(self.toolboxInputs.project.filePath.split("\\")[:-1]) + "\\speckle_layers\\"
#path = "\\".join(project.filePath.split("\\")[:-1]) + "\\speckle_layers\\" #arcpy.env.workspace + "\\" #
#if not os.path.exists(path): os.makedirs(path)
print(path)
#print(path)
f = open(path + "\\" + newGroupName + ".lyrx", "w")
content = createGroupLayer().replace("TestGroupLayer", newGroupName)
f.write(content)
f.close()
smth = arcpy.mp.LayerFile(path + "\\" + newGroupName + ".lyrx")
print(smth)
#print(smth)
layerGroup = self.toolboxInputs.project.activeMap.addLayer(smth)[0]
layerGroup.name = newGroupName
@@ -522,7 +524,7 @@ class Speckle(object):
def callback(base: Base) -> bool:
print("callback")
print(base)
#print(base)
if isinstance(base, Layer) or isinstance(base, RasterLayer):
layer = layerToNative(base, streamBranch, self.toolboxInputs.project)
if layer is not None: