示例#1
0
def import_csv(fn,orig,datatext=None):
	# lat lon
	yy=orig.split(',')
	origin=(float(yy[0]),float(yy[1]))

	data=[]
	if len(datatext) <> 0:
		lines=datatext.split('\n')
		for l in lines:
			pp=re.split("( )+",l)
			print pp
			print len(pp)
			if len(pp)==1:
				continue
			if len(pp)<3:
				raise Exception("Syntax error in 'direct Data input'")
			data.append([str(pp[0]),str(pp[2])])
		print(data)
	else:
		with open(fn, 'rb') as csvfile:
			reader = csv.reader(csvfile, delimiter=';')
			for row in reader:
				print ', '.join(row)
				data.append(row)

	print data

	tm=TransverseMercator()
	tm.lat=origin[0]
	tm.lon=origin[1]
	center=tm.fromGeographic(tm.lat,tm.lon)

	points=[]
	for p in data:
		lat,lon = p[0],p[1]
		ll=tm.fromGeographic(float(lat),float(lon))
		points.append( FreeCAD.Vector(ll[0]-center[0],ll[1]-center[1],0.0))

	import Draft
	points.append(points[0])
	Draft.makeWire(points)

	po=App.ActiveDocument.ActiveObject
	po.ViewObject.LineColor=(1.0,0.0,0.0)
	po.MakeFace = False

	App.activeDocument().recompute()
	Gui.SendMsgToActiveView("ViewFit")
示例#2
0
def import_csv(fn, orig, datatext=None):
    # lat lon
    yy = orig.split(',')
    origin = (float(yy[0]), float(yy[1]))

    data = []
    if len(datatext) <> 0:
        lines = datatext.split('\n')
        for l in lines:
            pp = re.split("( )+", l)
            print pp
            print len(pp)
            if len(pp) == 1:
                continue
            if len(pp) < 3:
                raise Exception("Syntax error in 'direct Data input'")
            data.append([str(pp[0]), str(pp[2])])
        print(data)
    else:
        with open(fn, 'rb') as csvfile:
            reader = csv.reader(csvfile, delimiter=';')
            for row in reader:
                print ', '.join(row)
                data.append(row)

    print data

    tm = TransverseMercator()
    tm.lat = origin[0]
    tm.lon = origin[1]
    center = tm.fromGeographic(tm.lat, tm.lon)

    points = []
    for p in data:
        lat, lon = p[0], p[1]
        ll = tm.fromGeographic(float(lat), float(lon))
        points.append(FreeCAD.Vector(ll[0] - center[0], ll[1] - center[1],
                                     0.0))

    import Draft
    points.append(points[0])
    Draft.makeWire(points)

    po = App.ActiveDocument.ActiveObject
    po.ViewObject.LineColor = (1.0, 0.0, 0.0)
    po.MakeFace = False

    App.activeDocument().recompute()
    Gui.SendMsgToActiveView("ViewFit")
示例#3
0
    import urllib.request
else:
    import urllib2

import json, time
import pivy
from pivy import coin

import geodat.transversmercator
from geodat.transversmercator import TransverseMercator
import inventortools

from geodat.say import *

#\cond
tm = TransverseMercator()
#\endcond

## get the height of point
# @param b latitude
# @param l longitude
'''
f='https://maps.googleapis.com/maps/api/elevation/json?locations=50.3377879,11.2104096'
response = urllib2.urlopen(f)
'''


def getheight(b, l):
    source = "https://maps.googleapis.com/maps/api/elevation/json?locations=" + str(
        b) + ',' + str(l)
    say(source)
示例#4
0
def import_gpx(filename, orig, hi):
    '''import a gpx trackfile'''

    global sd
    # content=trackstring

    #	fn='/home/microelly2/FCB/b202_gmx_tracks/im_haus.gpx'
    #	filename='/home/microelly2/FCB/b202_gmx_tracks/neufang.gpx'

    f = open(filename, "r")
    c1 = f.read()
    import re
    content = re.sub('^\<\?[^\>]+\?\>', '', c1)
    print(content)

    tm = TransverseMercator()

    # outdoor inn ...
    tm.lat, tm.lon = 50.3736049, 11.191643

    if orig != 'auto':
        yy = orig.split(',')
        origin = (float(yy[0]), float(yy[1]))
        tm.lat = origin[0]
        tm.lon = origin[1]
#	center=tm.fromGeographic(tm.lat,tm.lon)

    sd = parse(content)
    if debug: print(json.dumps(sd, indent=4))

    points = []
    points2 = []
    points0 = []
    px = []
    py = []
    pz = []
    pt = []

    startx = None
    starty = None
    starth = None
    FreeCAD.sd = sd
    seg = sd['gpx']['trk']['trkseg']
    try:
        seg['trkpt']
        ss = seg
        seg = [ss]
    except:
        pass
    lats = []
    lons = []

    for s in seg:
        trkpts = s['trkpt']
        for n in trkpts:
            lats.append(float(n['@lat']))
            lons.append(float(n['@lon']))

    print(min(lats), max(lats))
    print(min(lons), max(lons))
    print((max(lats) + min(lats)) / 2, (max(lons) + min(lons)) / 2)
    print((max(lats) - min(lats)) / 2, (max(lons) - min(lons)) / 2)

    if orig == 'auto':
        tm.lat, tm.lon = (max(lats) + min(lats)) / 2, (max(lons) +
                                                       min(lons)) / 2
        print("origin:")
        print(tm.lat, tm.lon)
        print("----------")

    for s in seg:
        trkpts = s['trkpt']

        n = trkpts[0]

        center = tm.fromGeographic(tm.lat, tm.lon)

        #		print(trkpts)
        #		for p in  trkpts:
        #			print(p)

        # map all points to xy-plane
        for n in trkpts:
            #			print(n['@lat'],n['@lon'])
            lats.append(float(n['@lat']))
            lons.append(float(n['@lon']))
            ll = tm.fromGeographic(float(n['@lat']), float(n['@lon']))
            h = n['ele']
            #			print(h)
            tim = n['time']
            t2 = re.sub('^.*T', '', tim)
            t3 = re.sub('Z', '', t2)
            t4 = t3.split(':')
            timx = int(t4[0]) * 3600 + int(t4[1]) * 60 + int(t4[2])
            pt.append(timx)
            if starth == None:
                starth = float(h)
                starth = 0

            points.append(
                FreeCAD.Vector(ll[0] - center[0], ll[1] - center[1],
                               1000 * (float(h) - starth)))
            points.append(
                FreeCAD.Vector(ll[0] - center[0], ll[1] - center[1], 0))
            points.append(
                FreeCAD.Vector(ll[0] - center[0], ll[1] - center[1],
                               1000 * (float(h) - starth)))
            points2.append(
                FreeCAD.Vector(ll[0] - center[0], ll[1] - center[1],
                               1000 * (float(h) - starth) + 20000))
            points0.append(
                FreeCAD.Vector(ll[0] - center[0], ll[1] - center[1], 0))
            px.append(ll[0] - center[0])
            py.append(ll[1] - center[1])
            pz.append(1000 * (float(h) - starth))


#			print(ll)

    if 1:
        import Draft
        if 0:  #close path
            points.append(points[0])

        Draft.makeWire(points0)

        Draft.makeWire(points)

        po = App.ActiveDocument.ActiveObject
        po.ViewObject.LineColor = (1.0, .0, 0.0)
        po.MakeFace = False

        po.Placement.Base.z = float(hi) * 1000
        po.Label = "My Track"

        Draft.makeWire(points2)

        po2 = App.ActiveDocument.ActiveObject
        po2.ViewObject.LineColor = (.0, .0, 1.0)
        po2.ViewObject.PointSize = 5
        po2.ViewObject.PointColor = (.0, 1.0, 1.0)

        po2.Placement.Base.z = float(hi) * 1000
        po2.Label = "Track + 20m"

        App.activeDocument().recompute()
        Gui.SendMsgToActiveView("ViewFit")
        # break

    #------------------------------------------------
    # data for postprocessing
    return

    try:
        import numpyNode
        import mathplotlibNode

        t = mathplotlibNode.createMPL()
        t.Label = "My Track raw Data"

        # hier werte bereitstellen
        t.countSources = 4
        t.source1Values = px
        t.source2Values = py
        t.source3Values = pz
        t.source4Values = pt

        t.source1Data = "px"
        t.source2Data = "py"
        t.source3Data = "pz"
        t.source4Data = "pt"

        t.useOut1 = True
        t.useOut2 = True
        t.useOut3 = True
        t.useOut4 = True

        # werte umrechnen
        t2 = numpyNode.createNP()
        t2.Label = "My Track data processed"
        t2.sourceObject = t
        t2.expression1 = "in1/np.max(np.abs(in1))"
        t2.label1 = "x relative"

        t2.expression2 = "in2/np.max(np.abs(in2))"
        t2.label2 = "y relative"

        t2.expression3 = "in3/np.max(np.abs(in3))"
        t2.label3 = "z relative"

        t2.expression4 = "-1+2*(in4-np.min(in4))/(np.max(in4)-np.min(in4))"
        t2.label4 = "time relative"

        # werte grafisch darstellen
        t3 = mathplotlibNode.createMPL()
        t3.Label = "My Track Data visualization"
        t3.record = False
        t3.useNumpy = True
        t3.sourceNumpy = t2

        t3.useOut1 = True
        t3.useOut2 = True
        t3.useOut3 = True
        t3.useOut4 = True

        t4 = numpyNode.createNP()
        t4.Label = "My Track Data xy"
        t4.sourceObject = t

        t4.expression2 = "in2"
        t4.label2 = "path xy"

        t4.expressionTime = "in1"

        t5 = mathplotlibNode.createMPL()
        t5.Label = "My Track Data xy Map"
        t5.record = False
        t5.useNumpy = True
        t5.sourceNumpy = t4

        t5.useOut2 = True
        FreeCAD.ActiveDocument.recompute()
    except:
        sayexc()

    return (str(tm.lat) + ',' + str(tm.lon))
    return px, py
示例#5
0
def getAST(b=50.26,l=11.39):

	bs=np.floor(b)
	ls=np.floor(l)

	# the ast dataset
	ff="N%02dE%03d" % (int(bs),int(ls))
	fn=FreeCAD.ConfigGet("UserAppData") +'/geodat/AST/ASTGTM2_' + ff +'_dem.tif'
	print fn

	'''
	fn='/home/microelly2/FCB/b217_heightmaps/tandemx_daten/Chile-Chuquicatmata.tif'
	b=-22.3054705
	l=-68.9259643
	bs=np.floor(b)
	ls=np.floor(l)
	print fn
	'''


	dataset = gdal.Open(fn, GA_ReadOnly) 
	if dataset == None:
		msg="\nProblem cannot open " + fn + "\n"
		FreeCAD.Console.PrintError(msg)
		errorDialog(msg)
		return

	cols=dataset.RasterXSize
	rows=dataset.RasterYSize

	geotransform = dataset.GetGeoTransform()
	originX = geotransform[0]
	originY = geotransform[3]
	pixelWidth = geotransform[1]
	pixelHeight = geotransform[5]

	band = dataset.GetRasterBand(1)
	data = band.ReadAsArray(0, 0, cols, rows)

	#data.shape -> 3601 x 3601 secs
	# erfurt 51,11
	#data[0,0]
	# zeitz  51,12
	#data[3600,0]
	# windischletten(zapfendorf) 50,11
	#data[0,3600]
	# troestau fichtelgebirge 50,12
	#data[3600,3600]

	px=int(round((bs+1-b)*3600))
	py=int(round((l-ls)*3600))


	pts=[]
	d=70

	print "----------------------------",d

	d1=20
	d2=50
	d1=d
	d2=d


	tm=TransverseMercator()
	tm.lat=b
	tm.lon=l
	center=tm.fromGeographic(tm.lat,tm.lon)

	z0= data[px,py] # relative height to origin px,py

	for x in range(px-d1,px+d1):
		for y in range(py-d2,py+d2):
			ll=tm.fromGeographic(bs+1-1.0/3600*x,ls+1.0/3600*y)
			pt=FreeCAD.Vector(ll[0]-center[0],ll[1]-center[1], 1000.0* (data[x,y]-z0))
			pts.append(pt)

	# display the point cloud
	p=Points.Points(pts)
	Points.show(p)

	return pts
示例#6
0
def runfile(fn, xw, xe, ys, yn, ox=0, oy=0):
    f = 100000000

    tm = TransverseMercator()
    tm.lat = 0.5 * (yn + ys)
    tm.lon = 0.5 * (xw + xe)

    center = tm.fromGeographic(tm.lat, tm.lon)

    xw *= f
    xe *= f
    ys *= f
    yn *= f
    ox *= f
    oy *= f
    pts = []
    poss = {}
    nds = []
    elev = -1

    c = 0

    #Gui.ActiveDocument.ActiveView.setAnimationEnabled(False)

    pb = createProgressBar(label="create Elevations " + os.path.basename(fn))

    # file = open('/home/microelly2/Downloads/Lat50Lon11Lat51Lon12.osm', 'r')
    file = open(fn)
    #	pb.pb.setValue(10)

    for line in file.readlines():

        c += 1
        # if c == 100000: break
        pb.pb.setValue((c / 100) % 100)

        #	print("!", line)
        #if c % 10 == 0:
        #	Gui.updateGui()
        #	Gui.SendMsgToActiveView("ViewFit")

        m = re.match(r'.*<node id="([^"]+)" lat="([^"]+)" lon="([^"]+)".*',
                     line)
        if m:
            y = float(m.group(2)) * f
            x = float(m.group(3)) * f
            id = m.group(1)
            poss[id] = (x, y)
            continue

        m = re.match(r'.*<nd ref="([^"]+)".*', line)
        if m:
            nds.append(m.group(1))
            continue

        m = re.match(r'.*<tag k="ele" v="([^"]+)".*', line)
        if m:
            elev = float(m.group(1))
            continue

        m = re.match(r'.*/way.*', line)
        if m:
            print("erzeuge pfad")
            for nd in nds:
                x = poss[nd][0]
                y = poss[nd][1]
                if xw < x and x < xe and ys < y and y < yn:
                    ll = tm.fromGeographic(y / f, x / f)
                    pts.append(
                        FreeCAD.Vector(ll[0] - center[0], ll[1] - center[1],
                                       elev * 1000))

#			if len(pts)>2:
#				d=Draft.makeWire(pts)
#			if len(pts)==1:
#				d=Draft.makePoint(pts[0])

            c += 1
            print(c, elev, len(pts))

            poss = {}
            elev = 0
            nds = []
            continue

    pb.hide()
    return pts
示例#7
0
def import_osm2(b,l,bk,progressbar,status,elevation):

	dialog=False
	debug=False

	if progressbar:
			progressbar.setValue(0)

	if status:
		status.setText("get data from openstreetmap.org ...")
		FreeCADGui.updateGui()
	content=''

	bk=0.5*bk
	dn=FreeCAD.ConfigGet("UserAppData") + "/geodat/"
	fn=dn+str(b)+'-'+str(l)+'-'+str(bk)
	import os
	if not os.path.isdir(dn):
		print "create " + dn
		os.makedirs(dn)

	try:
		f=open(fn,"r")
		content=f.read()
#		print content
	except:
		lk=bk # 
		b1=b-bk/1113*10
		l1=l-lk/713*10
		b2=b+bk/1113*10
		l2=l+lk/713*10
		source='http://api.openstreetmap.org/api/0.6/map?bbox='+str(l1)+','+str(b1)+','+str(l2)+','+str(b2)
		print source
		try:
			response = urllib2.urlopen(source)
			first=True
			content=''
			f=open(fn,"w")
			l=0
			z=0
			ct=0
			for line in response:
				if status:
					if z>5000:
						status.setText("read data ..." + str(l)) 
						z=0
					FreeCADGui.updateGui()
					l+=1
					z+=1
				if first:
					first=False
				else:
					content += line
					f.write(line)
			f.close()
			if status:
				status.setText("FILE CLOSED ..." + str(l))
				FreeCADGui.updateGui()
			response.close()
		except:
			print "Fehler beim Lesen"
		if status:
			status.setText("got data from openstreetmap.org ...")
			FreeCADGui.updateGui()
		print "Beeenden - im zweiten versuch daten auswerten"
		return

	if elevation:
		baseheight=getheight(b,l)
	else:
		baseheight=0 

	print "-------Data---------"
	print content
	print "--------------------"

	if status:
		status.setText("parse data ...")
		FreeCADGui.updateGui()

	sd=parse(content)
	if debug: print(json.dumps(sd, indent=4))

	if status:
		status.setText("transform data ...")
		FreeCADGui.updateGui()

	bounds=sd['osm']['bounds']
	nodes=sd['osm']['node']
	ways=sd['osm']['way']
	relations=sd['osm']['relation']


	# center of the scene
	bounds=sd['osm']['bounds']
	minlat=float(bounds['@minlat'])
	minlon=float(bounds['@minlon'])
	maxlat=float(bounds['@maxlat'])
	maxlon=float(bounds['@maxlon'])

	tm=TransverseMercator()
	tm.lat=0.5*(minlat+maxlat)
	tm.lon=0.5*(minlon+maxlon)

	center=tm.fromGeographic(tm.lat,tm.lon)
	corner=tm.fromGeographic(minlat,minlon)
	size=[center[0]-corner[0],center[1]-corner[1]]

	# map all points to xy-plane
	points={}
	nodesbyid={}
	for n in nodes:
		nodesbyid[n['@id']]=n
		ll=tm.fromGeographic(float(n['@lat']),float(n['@lon']))
		points[str(n['@id'])]=FreeCAD.Vector(ll[0]-center[0],ll[1]-center[1],0.0)

	# hack to catch deutsche umlaute
	def beaustring(string):
		res=''
		for tk in zz:
			try:
				res += str(tk)
			except:
				
				if ord(tk)==223:
					res += 'ß'
				elif ord(tk)==246:
					res += 'ö'
				elif ord(tk)==196:
					res += 'Ä'
				elif ord(tk)==228:
					res += 'ä'
				elif ord(tk)==242:
					res += 'ü'
				else:
					print ["error sign",tk,ord(tk),string]
					res +="#"
		return res

	if status:
		status.setText("create visualizations  ...")
		FreeCADGui.updateGui()

	App.newDocument("OSM Map")
	say("Datei erzeugt")
	area=App.ActiveDocument.addObject("Part::Plane","area")
	obj = FreeCAD.ActiveDocument.ActiveObject
	say("grundflaeche erzeugt")
	try:
		viewprovider = obj.ViewObject
		root=viewprovider.RootNode
		myLight = coin.SoDirectionalLight()
		myLight.color.setValue(coin.SbColor(0,1,0))
		root.insertChild(myLight, 0)
		say("beleuchtung auf grundobjekt eingeschaltet")
	except:
		sayexc("Beleuchtung 272")

	cam='''#Inventor V2.1 ascii
	OrthographicCamera {
	  viewportMapping ADJUST_CAMERA
	  orientation 0 0 -1.0001  0.001
	  nearDistance 0
	  farDistance 10000000000
	  aspectRatio 100
	  focalDistance 1
	'''
	x=0
	y=0
	height=1000000
	height=200*bk*10000/0.6
	cam += '\nposition ' +str(x) + ' ' + str(y) + ' 999\n '
	cam += '\nheight ' + str(height) + '\n}\n\n'
	FreeCADGui.activeDocument().activeView().setCamera(cam)
	FreeCADGui.activeDocument().activeView().viewAxonometric()
	say("Kamera gesetzt")
	
	area.Length=size[0]*2
	area.Width=size[1]*2
	area.Placement=FreeCAD.Placement(FreeCAD.Vector(-size[0],-size[1],0.00),FreeCAD.Rotation(0.00,0.00,0.00,1.00))
	say("Area skaliert")
	wn=-1
	coways=len(ways)
	starttime=time.time()
	refresh=1000
	for w in ways:
#		print w
		wid=w['@id']
#		print wid
		
		building=False
		landuse=False
		highway=False
		wn += 1

		# nur teile testen 
		#if wn <2000: continue

		nowtime=time.time()
		if wn<>0: print "way ---- # " + str(wn) + "/" + str(coways) + " time per house: " +  str(round((nowtime-starttime)/wn,2))
		if progressbar:
			progressbar.setValue(int(0+100.0*wn/coways))

		if debug: print "w=", w
		if debug: print "tags ..."
		st=""
		nr=""
		h=0
		try:
			w['tag']
		except:
			print "no tags found."
			continue

		for t in w['tag']:
			if t.__class__.__name__ == 'OrderedDict':
				try:
					if debug: print t

					if str(t['@k'])=='building':
						building=True
						st='building'

					if str(t['@k'])=='landuse':
						landuse=True
						st=w['tag']['@k']
						nr=w['tag']['@v']

					if str(t['@k'])=='highway':
						highway=True
						st=t['@k']

					if str(t['@k'])=='name':
						zz=t['@v']
						nr=beaustring(zz)
					if str(t['@k'])=='ref':
						zz=t['@v']
						nr=beaustring(zz)+" /"

					if str(t['@k'])=='addr:street':
						zz=w['tag'][1]['@v']
						st=beaustring(zz)
					if str(t['@k'])=='addr:housenumber':
						nr=str(t['@v'])

					if str(t['@k'])=='building:levels':
						if h==0:
							h=int(str(t['@v']))*1000*3
					if str(t['@k'])=='building:height':
						h=int(str(t['@v']))*1000

				except:
					print "unexpected error ################################################################"

			else:
				if debug: print [w['tag']['@k'],w['tag']['@v']]
				if str(w['tag']['@k'])=='building':
					building=True
					st='building'
				if str(w['tag']['@k'])=='building:levels':
					if h==0:
						h=int(str(w['tag']['@v']))*1000*3
				if str(w['tag']['@k'])=='building:height':
					h=int(str(w['tag']['@v']))*1000

				if str(w['tag']['@k'])=='landuse':
					landuse=True
					st=w['tag']['@k']
					nr=w['tag']['@v']
				if str(w['tag']['@k'])=='highway':
					highway=True
					st=w['tag']['@k']
					nr=w['tag']['@v']

			name=str(st) + " " + str(nr)
			if name==' ':
				name='landuse xyz'
			if debug: print "name ",name

		#generate pointlist of the way
		polis=[]
		height=None
		
		llpoints=[]
		for n in w['nd']:
			m=nodesbyid[n['@ref']]
			llpoints.append([n['@ref'],m['@lat'],m['@lon']])
		if elevation:
			heights=get_heights(llpoints)

		for n in w['nd']:
			p=points[str(n['@ref'])]
			if building and elevation:
				if not height:
					try:
						height=heights[m['@lat']+' '+m['@lon']]*1000 - baseheight
					except:
						print "---no height avaiable for " + m['@lat']+' '+m['@lon']
						height=0
				p.z=height
			polis.append(p)

		#create 2D map
		pp=Part.makePolygon(polis)
		Part.show(pp)
		z=App.ActiveDocument.ActiveObject
		z.Label="w_"+wid

		if name==' ':
			g=App.ActiveDocument.addObject("Part::Extrusion",name)
			g.Base = z
			g.ViewObject.ShapeColor = (1.00,1.00,0.00)
			g.Dir = (0,0,10)
			g.Solid=True
			g.Label='way ex '

		if building:
			g=App.ActiveDocument.addObject("Part::Extrusion",name)
			g.Base = z
			g.ViewObject.ShapeColor = (1.00,1.00,1.00)

			if h==0:
				h=10000
			g.Dir = (0,0,h)
			g.Solid=True
			g.Label=name

			obj = FreeCAD.ActiveDocument.ActiveObject
			inventortools.setcolors2(obj)

		if landuse:
			g=App.ActiveDocument.addObject("Part::Extrusion",name)
			g.Base = z
			if nr == 'residential':
				g.ViewObject.ShapeColor = (1.00,.60,.60)
			elif nr == 'meadow':
				g.ViewObject.ShapeColor = (0.00,1.00,0.00)
			elif nr == 'farmland':
				g.ViewObject.ShapeColor = (.80,.80,.00)
			elif nr == 'forest':
				g.ViewObject.ShapeColor = (1.0,.40,.40)
			g.Dir = (0,0,0.1)
			g.Label=name
			g.Solid=True

		if highway:
			g=App.ActiveDocument.addObject("Part::Extrusion","highway")
			g.Base = z
			g.ViewObject.LineColor = (0.00,.00,1.00)
			g.ViewObject.LineWidth = 10
			g.Dir = (0,0,0.2)
			g.Label=name
		refresh += 1
		if os.path.exists("/tmp/stop"):
			
			print("notbremse gezogen")
			FreeCAD.w=w
			raise Exception("Notbremse Manager main loop")

		if refresh >3:
			FreeCADGui.updateGui()
			# FreeCADGui.SendMsgToActiveView("ViewFit")
			refresh=0


	FreeCAD.activeDocument().recompute()
	FreeCADGui.updateGui()
	FreeCAD.activeDocument().recompute()

	if status:
		status.setText("import finished.")
	if progressbar:
			progressbar.setValue(100)

	organize()

	endtime=time.time()
	print "running time ", int(endtime-starttime),  " count ways ", coways
示例#8
0
def import_osm2(b,l,bk,progressbar,status,elevation):

	dialog=False
	debug=False

	if progressbar:
			progressbar.setValue(0)

	if status:
		status.setText("get data from openstreetmap.org ...")
		FreeCADGui.updateGui()
	content=''

	bk=0.5*bk
	dn=FreeCAD.ConfigGet("UserAppData") + "/geodat/"
	fn=dn+str(b)+'-'+str(l)+'-'+str(bk)
	import os
	if not os.path.isdir(dn):
		print "create " + dn
		os.makedirs(dn)

	try:
		print "I try to read data from cache file ..."
		print fn
		f=open(fn,"r")
		content=f.read()
		print "successful read"
#		print content
	except:
		print "no cache file, so I connect to  openstreetmap.org..."
		lk=bk #
		b1=b-bk/1113*10
		l1=l-lk/713*10
		b2=b+bk/1113*10
		l2=l+lk/713*10
		source='http://api.openstreetmap.org/api/0.6/map?bbox='+str(l1)+','+str(b1)+','+str(l2)+','+str(b2)
		print source
		try:
			response = urllib2.urlopen(source)
			first=True
			content=''
			f=open(fn,"w")
			l=0
			z=0
			ct=0
			for line in response:
				if status:
					if z>5000:
						status.setText("read data ..." + str(l))
						z=0
					FreeCADGui.updateGui()
					l+=1
					z+=1
				if first:
					first=False
				else:
					content += line
					f.write(line)
			f.close()
			if status:
				status.setText("FILE CLOSED ..." + str(l))
				FreeCADGui.updateGui()
			response.close()
		except:
			print "Fehler beim Lesen"
		if status:
			status.setText("got data from openstreetmap.org ...")
			FreeCADGui.updateGui()
		print "Beeenden - im zweiten versuch daten auswerten"
		return False

	if elevation:
		baseheight=getHeight(b,l)
	else:
		baseheight=0

	if debug:
		print "-------Data---------"
		print content
		print "--------------------"

	if status:
		status.setText("parse data ...")
		FreeCADGui.updateGui()

	try:
		sd=parse(content)
	except:
		sayexc("Problem parsing data - abort")
		status.setText("Problem parsing data - aborted, for details see Report view")
		return



	if debug: print(json.dumps(sd, indent=4))

	if status:
		status.setText("transform data ...")
		FreeCADGui.updateGui()

	bounds=sd['osm']['bounds']
	nodes=sd['osm']['node']
	ways=sd['osm']['way']
	try:
		relations=sd['osm']['relation']
	except:
		relations=[]


	# center of the scene
	bounds=sd['osm']['bounds']
	minlat=float(bounds['@minlat'])
	minlon=float(bounds['@minlon'])
	maxlat=float(bounds['@maxlat'])
	maxlon=float(bounds['@maxlon'])

	tm=TransverseMercator()
	tm.lat=0.5*(minlat+maxlat)
	tm.lon=0.5*(minlon+maxlon)

	center=tm.fromGeographic(tm.lat,tm.lon)
	corner=tm.fromGeographic(minlat,minlon)
	size=[center[0]-corner[0],center[1]-corner[1]]

	# map all points to xy-plane
	points={}
	nodesbyid={}
	for n in nodes:
		nodesbyid[n['@id']]=n
		ll=tm.fromGeographic(float(n['@lat']),float(n['@lon']))
		points[str(n['@id'])]=FreeCAD.Vector(ll[0]-center[0],ll[1]-center[1],0.0)

	# hack to catch deutsche umlaute
	def beaustring(string):
		res=''
		for tk in zz:
			try:
				res += str(tk)
			except:

				if ord(tk)==223:
					res += 'ß'
				elif ord(tk)==246:
					res += 'ö'
				elif ord(tk)==196:
					res += 'Ä'
				elif ord(tk)==228:
					res += 'ä'
				elif ord(tk)==242:
					res += 'ü'
				else:
					print ["error sign",tk,ord(tk),string]
					res +="#"
		return res

	if status:
		status.setText("create visualizations  ...")
		FreeCADGui.updateGui()

	App.newDocument("OSM Map")
	say("Datei erzeugt")
	area=App.ActiveDocument.addObject("Part::Plane","area")
	obj = FreeCAD.ActiveDocument.ActiveObject
	say("grundflaeche erzeugt")
	try:
		viewprovider = obj.ViewObject
		root=viewprovider.RootNode
		myLight = coin.SoDirectionalLight()
		myLight.color.setValue(coin.SbColor(0,1,0))
		root.insertChild(myLight, 0)
		say("beleuchtung auf grundobjekt eingeschaltet")
	except:
		sayexc("Beleuchtung 272")

	cam='''#Inventor V2.1 ascii
	OrthographicCamera {
	  viewportMapping ADJUST_CAMERA
	  orientation 0 0 -1.0001  0.001
	  nearDistance 0
	  farDistance 10000000000
	  aspectRatio 100
	  focalDistance 1
	'''
	x=0
	y=0
	height=1000000
	height=200*bk*10000/0.6
	cam += '\nposition ' +str(x) + ' ' + str(y) + ' 999\n '
	cam += '\nheight ' + str(height) + '\n}\n\n'
	FreeCADGui.activeDocument().activeView().setCamera(cam)
	FreeCADGui.activeDocument().activeView().viewAxonometric()
	say("Kamera gesetzt")

	area.Length=size[0]*2
	area.Width=size[1]*2
	area.Placement=FreeCAD.Placement(FreeCAD.Vector(-size[0],-size[1],0.00),FreeCAD.Rotation(0.00,0.00,0.00,1.00))
	say("Area skaliert")
	wn=-1
	coways=len(ways)
	starttime=time.time()
	refresh=1000
	for w in ways:
#		print w
		wid=w['@id']
#		print wid

		building=False
		landuse=False
		highway=False
		wn += 1

		# nur teile testen
		#if wn <2000: continue

		nowtime=time.time()
		if wn<>0 and (nowtime-starttime)/wn > 0.5: print "way ---- # " + str(wn) + "/" + str(coways) + " time per house: " +  str(round((nowtime-starttime)/wn,2))
		if progressbar:
			progressbar.setValue(int(0+100.0*wn/coways))

		if debug: print "w=", w
		if debug: print "tags ..."
		st=""
		nr=""
		h=0
		try:
			w['tag']
		except:
			print "no tags found."
			continue

		for t in w['tag']:
			if t.__class__.__name__ == 'OrderedDict':
				try:
					if debug: print t

					if str(t['@k'])=='building':
						building=True
						st='building'

					if str(t['@k'])=='landuse':
						landuse=True
						st=w['tag']['@k']
						nr=w['tag']['@v']

					if str(t['@k'])=='highway':
						highway=True
						st=t['@k']

					if str(t['@k'])=='name':
						zz=t['@v']
						nr=beaustring(zz)
					if str(t['@k'])=='ref':
						zz=t['@v']
						nr=beaustring(zz)+" /"

					if str(t['@k'])=='addr:street':
						zz=w['tag'][1]['@v']
						st=beaustring(zz)
					if str(t['@k'])=='addr:housenumber':
						nr=str(t['@v'])

					if str(t['@k'])=='building:levels':
						if h==0:
							h=int(str(t['@v']))*1000*3
					if str(t['@k'])=='building:height':
						h=int(str(t['@v']))*1000

				except:
					print "unexpected error ################################################################"

			else:
				if debug: print [w['tag']['@k'],w['tag']['@v']]
				if str(w['tag']['@k'])=='building':
					building=True
					st='building'
				if str(w['tag']['@k'])=='building:levels':
					if h==0:
						h=int(str(w['tag']['@v']))*1000*3
				if str(w['tag']['@k'])=='building:height':
					h=int(str(w['tag']['@v']))*1000

				if str(w['tag']['@k'])=='landuse':
					landuse=True
					st=w['tag']['@k']
					nr=w['tag']['@v']
				if str(w['tag']['@k'])=='highway':
					highway=True
					st=w['tag']['@k']
					nr=w['tag']['@v']

			name=str(st) + " " + str(nr)
			if name==' ':
				name='landuse xyz'
			if debug: print "name ",name

		#generate pointlist of the way
		polis=[]
		height=None

		llpoints=[]
		for n in w['nd']:
			m=nodesbyid[n['@ref']]
			llpoints.append([n['@ref'],m['@lat'],m['@lon']])
		if elevation:
			print "get heights for " + str(len(llpoints))
			heights=getHeights(llpoints)

		for n in w['nd']:
			p=points[str(n['@ref'])]
			if building and elevation:
				if not height:
					try:
						height=heights[m['@lat']+' '+m['@lon']]*1000 - baseheight
					except:
						print "---no height avaiable for " + m['@lat']+' '+m['@lon']
						height=0
				p.z=height
			polis.append(p)

		#create 2D map
		pp=Part.makePolygon(polis)
		Part.show(pp)
		z=App.ActiveDocument.ActiveObject
		z.Label="w_"+wid

		if name==' ':
			g=App.ActiveDocument.addObject("Part::Extrusion",name)
			g.Base = z
			g.ViewObject.ShapeColor = (1.00,1.00,0.00)
			g.Dir = (0,0,10)
			g.Solid=True
			g.Label='way ex '

		if building:
			g=App.ActiveDocument.addObject("Part::Extrusion",name)
			g.Base = z
			g.ViewObject.ShapeColor = (1.00,1.00,1.00)

			if h==0:
				h=10000
			g.Dir = (0,0,h)
			g.Solid=True
			g.Label=name

			obj = FreeCAD.ActiveDocument.ActiveObject
			inventortools.setcolors2(obj)

		if landuse:
			g=App.ActiveDocument.addObject("Part::Extrusion",name)
			g.Base = z
			if nr == 'residential':
				g.ViewObject.ShapeColor = (1.00,.60,.60)
			elif nr == 'meadow':
				g.ViewObject.ShapeColor = (0.00,1.00,0.00)
			elif nr == 'farmland':
				g.ViewObject.ShapeColor = (.80,.80,.00)
			elif nr == 'forest':
				g.ViewObject.ShapeColor = (1.0,.40,.40)
			g.Dir = (0,0,0.1)
			g.Label=name
			g.Solid=True

		if highway:
			g=App.ActiveDocument.addObject("Part::Extrusion","highway")
			g.Base = z
			g.ViewObject.LineColor = (0.00,.00,1.00)
			g.ViewObject.LineWidth = 10
			g.Dir = (0,0,0.2)
			g.Label=name
		refresh += 1
		if os.path.exists("/tmp/stop"):

			print("notbremse gezogen")
			FreeCAD.w=w
			raise Exception("Notbremse Manager main loop")

		if refresh >3:
			FreeCADGui.updateGui()
			# FreeCADGui.SendMsgToActiveView("ViewFit")
			refresh=0


	FreeCAD.activeDocument().recompute()
	FreeCADGui.updateGui()
	FreeCAD.activeDocument().recompute()

	if status:
		status.setText("import finished.")
	if progressbar:
			progressbar.setValue(100)

	organize()

	endtime=time.time()
	print "running time ", int(endtime-starttime),  " count ways ", coways
	return True
示例#9
0
def runfile(fn, xw,xe,ys,yn,ox=0,oy=0):
	f= 100000000

	tm=TransverseMercator()
	tm.lat=0.5*(yn+ys)
	tm.lon=0.5*(xw+xe)

	center=tm.fromGeographic(tm.lat,tm.lon)


	xw *= f
	xe *= f
	ys *= f
	yn *= f
	ox *= f
	oy *= f
	pts=[]
	poss={}
	nds=[]
	elev=-1

	c=0


	#Gui.ActiveDocument.ActiveView.setAnimationEnabled(False)


	pb=createProgressBar(label="create Elevations " + os.path.basename(fn) )

	# file = open('/home/microelly2/Downloads/Lat50Lon11Lat51Lon12.osm', 'r')
	file =open(fn)
#	pb.pb.setValue(10)

	for line in file.readlines():

		c += 1
		# if c == 100000: break
		pb.pb.setValue((c/100)%100)
		
		
	#	print "!", line
		#if c % 10 == 0:
		#	Gui.updateGui()
		#	Gui.SendMsgToActiveView("ViewFit")
		

		m = re.match(r'.*<node id="([^"]+)" lat="([^"]+)" lon="([^"]+)".*', line)
		if m:
			y=float(m.group(2))*f
			x=float(m.group(3))*f
			id=m.group(1)
			poss[id]=(x,y)
			continue

		m = re.match(r'.*<nd ref="([^"]+)".*', line)
		if m:
			nds.append(m.group(1))
			continue

		m = re.match(r'.*<tag k="ele" v="([^"]+)".*', line)
		if m:
			elev=float(m.group(1))
			continue

		m = re.match(r'.*/way.*', line)
		if m:
			print "erzeuge pfad"
			for nd in nds:
				x=poss[nd][0]
				y=poss[nd][1]
				if xw<x and x<xe and ys<y and y<yn:
					ll=tm.fromGeographic(y/f,x/f)
					pts.append(FreeCAD.Vector(ll[0]-center[0],ll[1]-center[1],elev*1000))

#			if len(pts)>2:
#				d=Draft.makeWire(pts)
#			if len(pts)==1:
#				d=Draft.makePoint(pts[0])

			c +=1 
			print (c,elev, len(pts)) 

			poss={}
			elev=0
			nds=[]
			continue

	pb.hide()
	return pts
示例#10
0
def import_osm2(b, l, bk, progressbar, status, elevation):

	dialog = False

	if progressbar:
		progressbar.setValue(0)

	if status:
		status.setText("get data from openstreetmap.org ...")
		FreeCADGui.updateGui()

	content = ''

	bk = 0.5*bk
	dn = FreeCAD.ConfigGet("UserAppData") + "geodat3/"
	fn = dn+str(b)+'-'+str(l)+'-'+str(bk)
	import os

	if not os.path.isdir(dn):
		os.makedirs(dn)

	try:
		say("I try to read data from cache file ... ")
		say(fn)
		f = open(fn, "r")
		content = f.read()

	except:
		sayW("no cache file, so I connect to  openstreetmap.org...")
		lk = bk
		b1 = b-bk/1113*10
		l1 = l-lk/713*10
		b2 = b+bk/1113*10
		l2 = l+lk/713*10
		source = 'http://api.openstreetmap.org/api/0.6/map?bbox='+str(l1)+','+str(b1)+','+str(l2)+','+str(b2)
		say(source)

		import requests
		response = requests.get(source)
		data = response.text
		lines = response.text.split('\n')
		FreeCAD.t = response

		f = open(fn, "w")
#		f.write(response.text)
		if response.status_code == 200:
			with open(fn, 'wb') as f:
				for chunk in response.iter_content(1024):
					f.write(chunk)
		f.close()

	if elevation:
		baseheight = getHeight(b, l)

	else:
		baseheight = 0

	if debug:
		say("-------Data---------")
		say(content)

	if status:
		status.setText("parse data ...")
		FreeCADGui.updateGui()

	say("------------------------------")
	say(fn)

	say(fn)
	tree = my_xmlparser.getData(fn)

	if debug:
		say(json.dumps(sd, indent=4))

	if status:
		status.setText("transform data ...")
		FreeCADGui.updateGui()

	relations = tree.getiterator('relation')
	nodes = tree.getiterator('node')
	ways = tree.getiterator('way')
	bounds = tree.getiterator('bounds')[0]

	# center of the scene
	minlat = float(bounds.params['minlat'])
	minlon = float(bounds.params['minlon'])
	maxlat = float(bounds.params['maxlat'])
	maxlon = float(bounds.params['maxlon'])

	tm = TransverseMercator()
	tm.lat = 0.5*(minlat+maxlat)
	tm.lon = 0.5*(minlon+maxlon)

	center = tm.fromGeographic(tm.lat, tm.lon)
	corner = tm.fromGeographic(minlat, minlon)
	size = [center[0]-corner[0], center[1]-corner[1]]

	# map all points to xy-plane
	points = {}
	nodesbyid = {}

	for n in nodes:
		nodesbyid[n.params['id']] = n
		ll = tm.fromGeographic(float(n.params['lat']), float(n.params['lon']))
		points[str(n.params['id'])] = FreeCAD.Vector(ll[0]-center[0], ll[1]-center[1], 0.0)

	if status:
		status.setText("create visualizations  ...")
		FreeCADGui.updateGui()

	App.newDocument("OSM Map")
	say("Datei erzeugt")
	area = App.ActiveDocument.addObject("Part::Plane", "area")
	obj = FreeCAD.ActiveDocument.ActiveObject
	say("grundflaeche erzeugt")

	try:
		viewprovider = obj.ViewObject
		root = viewprovider.RootNode
		myLight = coin.SoDirectionalLight()
		myLight.color.setValue(coin.SbColor(0, 1, 0))
		root.insertChild(myLight, 0)
		say("beleuchtung auf grundobjekt eingeschaltet")

	except:
		sayexc("Beleuchtung 272")

	cam = '''#Inventor V2.1 ascii
	OrthographicCamera {
	  viewportMapping ADJUST_CAMERA
	  orientation 0 0 -1.0001  0.001
	  nearDistance 0
	  farDistance 10000000000
	  aspectRatio 100
	  focalDistance 1
	'''
	x = 0
	y = 0
	height = 200*bk*10000/0.6
	cam += '\nposition ' + str(x) + ' ' + str(y) + ' 999\n '
	cam += '\nheight ' + str(height) + '\n}\n\n'
	FreeCADGui.activeDocument().activeView().setCamera(cam)
	FreeCADGui.activeDocument().activeView().viewAxonometric()
	say("Kamera gesetzt")

	area.Length = size[0]*2
	area.Width = size[1]*2
	area.Placement = FreeCAD.Placement(FreeCAD.Vector(-size[0], -size[1], 0.00), FreeCAD.Rotation(0.00, 0.00, 0.00, 1.00))
	say("Area skaliert")
	wn = -1
	coways = len(ways)
	starttime = time.time()
	refresh = 1000

	for w in ways:
		wid = w.params['id']
		building = False
		landuse = False
		highway = False
		wn += 1

		nowtime = time.time()

		if wn != 0 and (nowtime-starttime)/wn > 0.5:
			say(("way ---- # " + str(wn) + "/" + str(coways) + " time per house: " + str(round((nowtime-starttime)/wn, 2))))

		if progressbar:
			progressbar.setValue(int(0+100.0*wn/coways))

		st = ""
		st2 = ""
		nr = ""
		h = 0
		ci = ""

		for t in w.getiterator('tag'):
			try:
				if str(t.params['k']) == 'building':
					building = True

					if st == '':
						st = 'building'

				if str(t.params['k']) == 'landuse':
					landuse = True
					st = t.params['k']
					nr = t.params['v']

				if str(t.params['k']) == 'highway':
					highway = True
					st = t.params['k']

				if str(t.params['k']) == 'addr:city':
					ci = t.params['v']

				if str(t.params['k']) == 'name':
					nr = t.params['v']

				if str(t.params['k']) == 'ref':
					nr = t.params['v']+" /"

				if str(t.params['k']) == 'addr:street':
					st2 = " "+t.params['v']

				if str(t.params['k']) == 'addr:housenumber':
					nr = str(t.params['v'])

				if str(t.params['k']) == 'building:levels':
					if h == 0:
						h = int(str(t.params['v']))*1000*3

				if str(t.params['k']) == 'building:height':
					h = int(str(t.params['v']))*1000

			except:
				sayErr("unexpected error ######################################################")

		name = str(st) + st2 + " " + str(nr)

		if name == ' ':
			name = 'landuse xyz'

		if debug:
			say(("name ", name))

		# Generate pointlist of the way
		polis = []
		height = None
		llpoints = []

		for n in w.getiterator('nd'):
			m = nodesbyid[n.params['ref']]
			llpoints.append([n.params['ref'], m.params['lat'], m.params['lon']])

		if elevation:
			say("get heights for " + str(len(llpoints)))
			heights = getHeights(llpoints)

		for n in w.getiterator('nd'):
			p = points[str(n.params['ref'])]

			if building and elevation:
				if not height:
					try:
						height = heights[m.params['lat']+' '+m.params['lon']]*1000 - baseheight

					except:
						sayErr("---no height avaiable for " + m.params['lat']+' '+m.params['lon'])
						height = 0

				p.z = height

			polis.append(p)

		# Create 2D map
		pp = Part.makePolygon(polis)
		Part.show(pp)
		z = App.ActiveDocument.ActiveObject
		z.Label = "w_"+wid

		if name == ' ':
			g = App.ActiveDocument.addObject("Part::Extrusion", name)
			g.Base = z
			g.ViewObject.ShapeColor = (1.00, 1.00, 0.00)
			g.Dir = (0, 0, 10)
			g.Solid = True
			g.Label = 'way ex '

		if building:
			g = App.ActiveDocument.addObject("Part::Extrusion", name)
			g.Base = z
			g.ViewObject.ShapeColor = (1.00, 1.00, 1.00)

			if h == 0:
				h = 10000
			g.Dir = (0, 0, h)
			g.Solid = True
			g.Label = name

			obj = FreeCAD.ActiveDocument.ActiveObject
			inventortools.setcolors2(obj)

		if landuse:
			g = App.ActiveDocument.addObject("Part::Extrusion", name)
			g.Base = z

			if nr == 'residential':
				g.ViewObject.ShapeColor = (1.00, 0.60, 0.60)

			elif nr == 'meadow':
				g.ViewObject.ShapeColor = (0.00, 1.00, 0.00)

			elif nr == 'farmland':
				g.ViewObject.ShapeColor = (0.80, 0.80, 0.00)

			elif nr == 'forest':
				g.ViewObject.ShapeColor = (1.0, 0.40, 0.40)

			g.Dir = (0, 0, 0.1)
			g.Label = name
			g.Solid = True

		if highway:
			g = App.ActiveDocument.addObject("Part::Extrusion", "highway")
			g.Base = z
			g.ViewObject.LineColor = (0.00, 0.00, 1.00)
			g.ViewObject.LineWidth = 10
			g.Dir = (0, 0, 0.2)
			g.Label = name
		refresh += 1

		if os.path.exists("/tmp/stop"):
			sayErr("notbremse gezogen")
			FreeCAD.w = w
			raise Exception("Notbremse Manager main loop")

		if refresh > 3:
			FreeCADGui.updateGui()
			refresh = 0

	FreeCADGui.updateGui()
	FreeCAD.activeDocument().recompute()

	if status:
		status.setText("import finished.")

	if progressbar:
		progressbar.setValue(100)

	organize()

	endtime = time.time()
	say(("running time ", int(endtime-starttime),  " count ways ", coways))

	return True
示例#11
0
def getAST(b=50.26, l=11.39):

    bs = np.floor(b)
    ls = np.floor(l)

    # the ast dataset
    ff = "N%02dE%03d" % (int(bs), int(ls))
    fn = FreeCAD.ConfigGet("UserAppData") + "/geodat/AST/ASTGTM2_" + ff + "_dem.tif"
    # print fn

    """
	fn='/home/microelly2/FCB/b217_heightmaps/tandemx_daten/Chile-Chuquicatmata.tif'
	b=-22.3054705
	l=-68.9259643
	bs=np.floor(b)
	ls=np.floor(l)
	print fn
	"""

    dataset = gdal.Open(fn, GA_ReadOnly)
    if dataset == None:
        msg = "\nProblem cannot open " + fn + "\n"
        FreeCAD.Console.PrintError(msg)
        errorDialog(msg)
        return

    cols = dataset.RasterXSize
    rows = dataset.RasterYSize

    geotransform = dataset.GetGeoTransform()
    originX = geotransform[0]
    originY = geotransform[3]
    pixelWidth = geotransform[1]
    pixelHeight = geotransform[5]

    band = dataset.GetRasterBand(1)
    data = band.ReadAsArray(0, 0, cols, rows)

    # data.shape -> 3601 x 3601 secs
    # erfurt 51,11
    # data[0,0]
    # zeitz  51,12
    # data[3600,0]
    # windischletten(zapfendorf) 50,11
    # data[0,3600]
    # troestau fichtelgebirge 50,12
    # data[3600,3600]

    px = int(round((bs + 1 - b) * 3600))
    py = int(round((l - ls) * 3600))

    pts = []
    d = 50

    tm = TransverseMercator()
    tm.lat = b
    tm.lon = l
    center = tm.fromGeographic(tm.lat, tm.lon)

    z0 = data[px, py]  # relative height to origin px,py

    for x in range(px - d, px + d):
        for y in range(py - d, py + d):
            ll = tm.fromGeographic(bs + 1 - 1.0 / 3600 * x, ls + 1.0 / 3600 * y)
            pt = FreeCAD.Vector(ll[0] - center[0], ll[1] - center[1], 1000.0 * (data[x, y] - z0))
            pts.append(pt)

            # display the point cloud
    p = Points.Points(pts)
    Points.show(p)

    return pts
示例#12
0
def import_osm2(b, l, bk, progressbar, status, elevation):

    dialog = False
    debug = False

    if progressbar:
        progressbar.setValue(0)

    if status:
        status.setText("get data from openstreetmap.org ...")
        FreeCADGui.updateGui()
    content = ''

    bk = 0.5 * bk
    dn = FreeCAD.ConfigGet("UserAppData") + "/geodat3/"
    fn = dn + str(b) + '-' + str(l) + '-' + str(bk)
    import os
    if not os.path.isdir(dn):
        os.makedirs(dn)

    try:
        say("I try to read data from cache file ... ")
        say(fn)
        f = open(fn, "r")
        content = f.read()
    #	say(content)
    #	raise Exception("to debug:force load from internet")
    except:
        sayW("no cache file, so I connect to  openstreetmap.org...")
        lk = bk  #
        b1 = b - bk / 1113 * 10
        l1 = l - lk / 713 * 10
        b2 = b + bk / 1113 * 10
        l2 = l + lk / 713 * 10
        source = 'http://api.openstreetmap.org/api/0.6/map?bbox=' + str(
            l1) + ',' + str(b1) + ',' + str(l2) + ',' + str(b2)
        say(source)

        import requests
        response = requests.get(source)
        data = response.text
        lines = response.text.split('\n')
        FreeCAD.t = response

        f = open(fn, "w")
        #		f.write(response.text)
        if response.status_code == 200:
            with open(fn, 'wb') as f:
                for chunk in response.iter_content(1024):
                    f.write(chunk)
        f.close()
        #		print("huhu");return

        if 0:
            try:
                say("read--")
                response = urllib.request.urlopen(source)
                #import ssl
                #ssl._create_default_https_context = ssl._create_unverified_context
                #response = urllib.request.urlopen(source)

                #			import requests
                #			response = requests.get(source)

                say(response)
                say("2huu")
                first = True
                content = ''
                f = open(fn, "w")
                l = 0
                z = 0
                ct = 0

                say("2wkkw")
                #say(response.text)
                #		lines=response.text.split('\n')
                #		say(len(lines))
                say("ll")
                # for line in lines:
                for line in response:
                    print("Y", line)
                    if status:
                        if z > 5000:
                            status.setText("read data ..." + str(l))
                            z = 0
                        FreeCADGui.updateGui()
                        l += 1
                        z += 1
                    if first:
                        first = False
                    else:
                        content += line
                        f.write(line)
                f.close()
                if status:
                    status.setText("FILE CLOSED ..." + str(l))
                    FreeCADGui.updateGui()
                response.close()
            except:
                sayErr("Fehler beim Lesen")

            if status:
                status.setText("got data from openstreetmap.org ...")
                FreeCADGui.updateGui()
            sayW("Beeenden - im zweiten versuch daten auswerten")

            return False

    if elevation:
        baseheight = getHeight(b, l)
    else:
        baseheight = 0

    if debug:
        say("-------Data---------")
        say(content)

    if status:
        status.setText("parse data ...")
        FreeCADGui.updateGui()

    say("------------------------------")
    say(fn)

    #	fn='/home/thomas/.FreeCAD//geodat3/50.340722-11.232647-0.015'
    say(fn)

    tree = geodat.my_xmlparser.getData(fn)

    #	for element in tree.getiterator('node'):
    #		say(element.params)

    #	say("ways")
    #	for element in tree.getiterator('way'):
    #		say(element.params)
    #	say("relations")
    #	for element in tree.getiterator('relation'):
    #		say(element.params)

    if 0:
        try:
            sd = parse(content)
        except:
            sayexc("Problem parsing data - abort")
            status.setText(
                "Problem parsing data - aborted, for details see Report view")
            return

    if debug: say(json.dumps(sd, indent=4))

    if status:
        status.setText("transform data ...")
        FreeCADGui.updateGui()

    relations = tree.getiterator('relation')
    nodes = tree.getiterator('node')
    ways = tree.getiterator('way')
    bounds = tree.getiterator('bounds')[0]

    # center of the scene
    minlat = float(bounds.params['minlat'])
    minlon = float(bounds.params['minlon'])
    maxlat = float(bounds.params['maxlat'])
    maxlon = float(bounds.params['maxlon'])

    tm = TransverseMercator()
    tm.lat = 0.5 * (minlat + maxlat)
    tm.lon = 0.5 * (minlon + maxlon)

    center = tm.fromGeographic(tm.lat, tm.lon)
    corner = tm.fromGeographic(minlat, minlon)
    size = [center[0] - corner[0], center[1] - corner[1]]

    # map all points to xy-plane
    points = {}
    nodesbyid = {}
    for n in nodes:
        nodesbyid[n.params['id']] = n
        ll = tm.fromGeographic(float(n.params['lat']), float(n.params['lon']))
        points[str(n.params['id'])] = FreeCAD.Vector(ll[0] - center[0],
                                                     ll[1] - center[1], 0.0)


#	say(points)
#	say("abbruch3 -hier daten uebernehmen !!");return

# hack to catch deutsche umlaute

    def beaustring(string):
        res = ''
        for tk in zz:
            try:
                res += str(tk)
            except:

                if ord(tk) == 223:
                    res += 'ß'
                elif ord(tk) == 246:
                    res += 'ö'
                elif ord(tk) == 196:
                    res += 'Ä'
                elif ord(tk) == 228:
                    res += 'ä'
                elif ord(tk) == 242:
                    res += 'ü'
                else:
                    sayErr(["error sign", tk, ord(tk), string])
                    res += "#"
        return res

    if status:
        status.setText("create visualizations  ...")
        FreeCADGui.updateGui()

    App.newDocument("OSM Map")
    say("Datei erzeugt")
    area = App.ActiveDocument.addObject("Part::Plane", "area")
    obj = FreeCAD.ActiveDocument.ActiveObject
    say("grundflaeche erzeugt")
    try:
        viewprovider = obj.ViewObject
        root = viewprovider.RootNode
        myLight = coin.SoDirectionalLight()
        myLight.color.setValue(coin.SbColor(0, 1, 0))
        root.insertChild(myLight, 0)
        say("beleuchtung auf grundobjekt eingeschaltet")
    except:
        sayexc("Beleuchtung 272")

    cam = '''#Inventor V2.1 ascii
	OrthographicCamera {
	  viewportMapping ADJUST_CAMERA
	  orientation 0 0 -1.0001  0.001
	  nearDistance 0
	  farDistance 10000000000
	  aspectRatio 100
	  focalDistance 1
	'''
    x = 0
    y = 0
    height = 1000000
    height = 200 * bk * 10000 / 0.6
    cam += '\nposition ' + str(x) + ' ' + str(y) + ' 999\n '
    cam += '\nheight ' + str(height) + '\n}\n\n'
    FreeCADGui.activeDocument().activeView().setCamera(cam)
    FreeCADGui.activeDocument().activeView().viewAxonometric()
    say("Kamera gesetzt")

    area.Length = size[0] * 2
    area.Width = size[1] * 2
    area.Placement = FreeCAD.Placement(
        FreeCAD.Vector(-size[0], -size[1], 0.00),
        FreeCAD.Rotation(0.00, 0.00, 0.00, 1.00))
    say("Area skaliert")
    wn = -1
    coways = len(ways)
    starttime = time.time()
    refresh = 1000
    for w in ways:
        wid = w.params['id']

        #		say(w.params)
        #		say("way content")
        #		for c in w.content:
        #			say(c)

        building = False
        landuse = False
        highway = False
        wn += 1

        # nur teile testen
        #if wn <2000: continue

        nowtime = time.time()
        if wn != 0 and (nowtime - starttime) / wn > 0.5:
            say(("way ---- # " + str(wn) + "/" + str(coways) +
                 " time per house: " + str(round(
                     (nowtime - starttime) / wn, 2))))
        if progressbar:
            progressbar.setValue(int(0 + 100.0 * wn / coways))

        st = ""
        st2 = ""
        nr = ""
        h = 0
        ci = ""

        for t in w.getiterator('tag'):
            try:
                if debug: say(t)
                #						say(t.params['k'])
                #						say(t.params['v'])

                if str(t.params['k']) == 'building':
                    building = True
                    if st == '':
                        st = 'building'

                if str(t.params['k']) == 'landuse':
                    landuse = True
                    st = t.params['k']
                    nr = t.params['v']

                if str(t.params['k']) == 'highway':
                    highway = True
                    st = t.params['k']

                if str(t.params['k']) == 'addr:city':
                    ci = t.params['v']

                if str(t.params['k']) == 'name':
                    zz = t.params['v']
                    nr = beaustring(zz)
                if str(t.params['k']) == 'ref':
                    zz = t.params['v']
                    nr = beaustring(zz) + " /"

                if str(t.params['k']) == 'addr:street':
                    zz = t.params['v']
                    st2 = " " + beaustring(zz)
                if str(t.params['k']) == 'addr:housenumber':
                    nr = str(t.params['v'])

                if str(t.params['k']) == 'building:levels':
                    if h == 0:
                        h = int(str(t.params['v'])) * 1000 * 3
                if str(t.params['k']) == 'building:height':
                    h = int(str(t.params['v'])) * 1000

            except:
                sayErr(
                    "unexpected error ######################################################"
                )

        name = str(st) + " " + str(nr)
        name = str(st) + st2 + " " + str(nr)
        if name == ' ':
            name = 'landuse xyz'
        if debug: say(("name ", name))
        #say(name,zz,nr,ci)

        #generate pointlist of the way
        polis = []
        height = None

        llpoints = []
        #		say("get nodes",w)
        for n in w.getiterator('nd'):
            #			say(n.params)
            m = nodesbyid[n.params['ref']]
            llpoints.append(
                [n.params['ref'], m.params['lat'], m.params['lon']])
        if elevation:
            say("get heights for " + str(len(llpoints)))
            heights = getHeights(llpoints)

        for n in w.getiterator('nd'):
            p = points[str(n.params['ref'])]
            if building and elevation:
                if not height:
                    try:
                        height = heights[m.params['lat'] + ' ' +
                                         m.params['lon']] * 1000 - baseheight
                    except:
                        sayErr("---no height avaiable for " + m.params['lat'] +
                               ' ' + m.params['lon'])
                        height = 0
                p.z = height
            polis.append(p)

        #create 2D map
        pp = Part.makePolygon(polis)
        Part.show(pp)
        z = App.ActiveDocument.ActiveObject
        z.Label = "w_" + wid

        if name == ' ':
            g = App.ActiveDocument.addObject("Part::Extrusion", name)
            g.Base = z
            g.ViewObject.ShapeColor = (1.00, 1.00, 0.00)
            g.Dir = (0, 0, 10)
            g.Solid = True
            g.Label = 'way ex '

        if building:
            g = App.ActiveDocument.addObject("Part::Extrusion", name)
            g.Base = z
            g.ViewObject.ShapeColor = (1.00, 1.00, 1.00)

            if h == 0:
                h = 10000
            g.Dir = (0, 0, h)
            g.Solid = True
            g.Label = name

            obj = FreeCAD.ActiveDocument.ActiveObject
            inventortools.setcolors2(obj)

        if landuse:
            g = App.ActiveDocument.addObject("Part::Extrusion", name)
            g.Base = z
            if nr == 'residential':
                g.ViewObject.ShapeColor = (1.00, .60, .60)
            elif nr == 'meadow':
                g.ViewObject.ShapeColor = (0.00, 1.00, 0.00)
            elif nr == 'farmland':
                g.ViewObject.ShapeColor = (.80, .80, .00)
            elif nr == 'forest':
                g.ViewObject.ShapeColor = (1.0, .40, .40)
            g.Dir = (0, 0, 0.1)
            g.Label = name
            g.Solid = True

        if highway:
            g = App.ActiveDocument.addObject("Part::Extrusion", "highway")
            g.Base = z
            g.ViewObject.LineColor = (0.00, .00, 1.00)
            g.ViewObject.LineWidth = 10
            g.Dir = (0, 0, 0.2)
            g.Label = name
        refresh += 1
        if os.path.exists("/tmp/stop"):

            sayErr("notbremse gezogen")
            FreeCAD.w = w
            raise Exception("Notbremse Manager main loop")

        if refresh > 3:
            FreeCADGui.updateGui()
            # FreeCADGui.SendMsgToActiveView("ViewFit")
            refresh = 0

    FreeCAD.activeDocument().recompute()
    FreeCADGui.updateGui()
    FreeCAD.activeDocument().recompute()

    if status:
        status.setText("import finished.")
    if progressbar:
        progressbar.setValue(100)

    organize()

    endtime = time.time()
    say(("running time ", int(endtime - starttime), " count ways ", coways))
    return True
示例#13
0
def import_gpx(filename, orig, hi):
    '''import a gpx trackfile'''

    global sd
    f = open(filename, "r")
    c1 = f.read()
    content = re.sub('^\<\?[^\>]+\?\>', '', c1)
    print(content)

    tm = TransverseMercator()

    # outdoor inn ...
    tm.lat, tm.lon = 50.3736049, 11.191643

    if orig != 'auto':
        yy = orig.split(',')
        origin = (float(yy[0]), float(yy[1]))
        tm.lat = origin[0]
        tm.lon = origin[1]

    sd = parse(content)

    if debug:
        print(json.dumps(sd, indent=4))

    points = []
    points2 = []
    points0 = []
    px = []
    py = []
    pz = []
    pt = []

    startx = None
    starty = None
    starth = None
    FreeCAD.sd = sd
    seg = sd['gpx']['trk']['trkseg']

    try:
        seg['trkpt']
        ss = seg
        seg = [ss]

    except:
        pass

    lats = []
    lons = []

    for s in seg:
        trkpts = s['trkpt']

        for n in trkpts:
            lats.append(float(n['@lat']))
            lons.append(float(n['@lon']))

    print(min(lats), max(lats))
    print(min(lons), max(lons))
    print((max(lats) + min(lats)) / 2, (max(lons) + min(lons)) / 2)
    print((max(lats) - min(lats)) / 2, (max(lons) - min(lons)) / 2)

    if orig == 'auto':
        tm.lat, tm.lon = (max(lats) + min(lats)) / 2, (max(lons) +
                                                       min(lons)) / 2
        print("origin:")
        print(tm.lat, tm.lon)
        print("----------")

    for s in seg:
        trkpts = s['trkpt']
        n = trkpts[0]
        center = tm.fromGeographic(tm.lat, tm.lon)

        # map all points to xy-plane
        for n in trkpts:
            lats.append(float(n['@lat']))
            lons.append(float(n['@lon']))
            ll = tm.fromGeographic(float(n['@lat']), float(n['@lon']))
            h = n['ele']
            tim = n['time']
            t2 = re.sub('^.*T', '', tim)
            t3 = re.sub('Z', '', t2)
            t4 = t3.split(':')
            timx = int(t4[0]) * 3600 + int(t4[1]) * 60 + int(t4[2])
            pt.append(timx)

            if starth == None:
                starth = float(h)
                starth = 0

            points.append(
                FreeCAD.Vector(ll[0] - center[0], ll[1] - center[1],
                               1000 * (float(h) - starth)))
            points.append(
                FreeCAD.Vector(ll[0] - center[0], ll[1] - center[1], 0))
            points.append(
                FreeCAD.Vector(ll[0] - center[0], ll[1] - center[1],
                               1000 * (float(h) - starth)))
            points2.append(
                FreeCAD.Vector(ll[0] - center[0], ll[1] - center[1],
                               1000 * (float(h) - starth) + 20000))
            points0.append(
                FreeCAD.Vector(ll[0] - center[0], ll[1] - center[1], 0))
            px.append(ll[0] - center[0])
            py.append(ll[1] - center[1])
            pz.append(1000 * (float(h) - starth))

    Draft.makeWire(points0)

    Draft.makeWire(points)

    po = App.ActiveDocument.ActiveObject
    po.ViewObject.LineColor = (1.0, 0.0, 0.0)
    po.MakeFace = False

    po.Placement.Base.z = float(hi) * 1000
    po.Label = "My Track"

    Draft.makeWire(points2)

    po2 = App.ActiveDocument.ActiveObject
    po2.ViewObject.LineColor = (0.0, 0.0, 1.0)
    po2.ViewObject.PointSize = 5
    po2.ViewObject.PointColor = (0.0, 1.0, 1.0)

    po2.Placement.Base.z = float(hi) * 1000
    po2.Label = "Track + 20m"

    App.activeDocument().recompute()
    Gui.SendMsgToActiveView("ViewFit")

    return str(tm.lat) + ',' + str(tm.lon)
示例#14
0
def import_gpx(filename,orig,hi):
	global sd
	# content=trackstring
	
#	fn='/home/microelly2/FCB/b202_gmx_tracks/im_haus.gpx'
#	filename='/home/microelly2/FCB/b202_gmx_tracks/neufang.gpx'
	
	
	f=open(filename,"r")
	c1=f.read()
	import re
	content = re.sub('^\<\?[^\>]+\?\>', '', c1)
#	print content


	tm=TransverseMercator()

	# outdoor inn ...
	tm.lat,tm.lon = 50.3736049,11.191643
	
	if orig<>'auto':
		yy=orig.split(',')
		origin=(float(yy[0]),float(yy[1]))
		tm.lat=origin[0]
		tm.lon=origin[1]
#	center=tm.fromGeographic(tm.lat,tm.lon)
	
	sd=parse(content)
	if debug: print(json.dumps(sd, indent=4))
	
	points=[]
	points2=[]
	points0=[]
	px=[]
	py=[]
	pz=[]
	pt=[]
	
	startx=None
	starty=None
	starth=None
	FreeCAD.sd=sd
	seg=sd['gpx']['trk']['trkseg']
	try:
		seg['trkpt']
		ss=seg
		seg=[ss]
	except:
		pass
	lats=[]
	lons=[]

	for s in seg:
		trkpts=s['trkpt']
		for n in trkpts:
			lats.append(float(n['@lat']))
			lons.append(float(n['@lon']))

	print (min(lats),max(lats))
	print (min(lons),max(lons))
	print ((max(lats)+min(lats))/2,(max(lons)+min(lons))/2)
	print ((max(lats)-min(lats))/2,(max(lons)-min(lons))/2)

	if orig == 'auto':
		tm.lat, tm.lon = (max(lats)+min(lats))/2,(max(lons)+min(lons))/2
		print "origin:"
		print(tm.lat,tm.lon)
		print ("----------")



	for s in seg:
		trkpts=s['trkpt']


		n=trkpts[0]

		center=tm.fromGeographic(tm.lat,tm.lon)

#		print trkpts
#		for p in  trkpts:
#			print p

		# map all points to xy-plane
		for n in trkpts:
#			print n['@lat'],n['@lon']
			lats.append(float(n['@lat']))
			lons.append(float(n['@lon']))
			ll=tm.fromGeographic(float(n['@lat']),float(n['@lon']))
			h=n['ele']
#			print h
			tim=n['time']
			t2=re.sub('^.*T', '', tim)
			t3=re.sub('Z', '', t2)
			t4=t3.split(':')
			timx=int(t4[0])*3600+int(t4[1])*60+int(t4[2])
			pt.append(timx)
			if starth == None:
				starth=float(h)
				starth=0

			points.append(FreeCAD.Vector(ll[0]-center[0],ll[1]-center[1],1000*(float(h)-starth)))
			points.append(FreeCAD.Vector(ll[0]-center[0],ll[1]-center[1],0))
			points.append(FreeCAD.Vector(ll[0]-center[0],ll[1]-center[1],1000*(float(h)-starth)))
			points2.append(FreeCAD.Vector(ll[0]-center[0],ll[1]-center[1],1000*(float(h)-starth)+20000))
			points0.append(FreeCAD.Vector(ll[0]-center[0],ll[1]-center[1],0))
			px.append(ll[0]-center[0])
			py.append(ll[1]-center[1])
			pz.append(1000*(float(h)-starth))
#			print ll


	if 1:
		import Draft
		if 0: #close path
			points.append(points[0])
		
		
		
		Draft.makeWire(points0)
		
		Draft.makeWire(points)

		po=App.ActiveDocument.ActiveObject
		po.ViewObject.LineColor=(1.0,.0,0.0)
		po.MakeFace = False

		po.Placement.Base.z= float(hi) *1000
		po.Label="My Track" 

		Draft.makeWire(points2)

		po2=App.ActiveDocument.ActiveObject
		po2.ViewObject.LineColor=(.0,.0,1.0)
		po2.ViewObject.PointSize=5
		po2.ViewObject.PointColor=(.0,1.0,1.0)
		
		po2.Placement.Base.z= float(hi)*1000
		po2.Label="Track + 20m"


		App.activeDocument().recompute()
		Gui.SendMsgToActiveView("ViewFit")
		# break

	#------------------------------------------------
	# data for postprocessing

	try:
		import numpyNode
		import mathplotlibNode

		t=mathplotlibNode.createMPL()
		t.Label="My Track raw Data"

		# hier werte bereitstellen
		t.countSources=4
		t.source1Values=px
		t.source2Values=py
		t.source3Values=pz
		t.source4Values=pt

		t.source1Data="px"
		t.source2Data="py"
		t.source3Data="pz"
		t.source4Data="pt"
		
		t.useOut1=True
		t.useOut2=True
		t.useOut3=True
		t.useOut4=True

		# werte umrechnen
		t2=numpyNode.createNP()
		t2.Label="My Track data processed"
		t2.sourceObject=t
		t2.expression1="in1/np.max(np.abs(in1))"
		t2.label1 = "x relative"

		t2.expression2="in2/np.max(np.abs(in2))"
		t2.label2 = "y relative"

		t2.expression3="in3/np.max(np.abs(in3))"
		t2.label3 = "z relative"

		t2.expression4="-1+2*(in4-np.min(in4))/(np.max(in4)-np.min(in4))"
		t2.label4 = "time relative"

		# werte grafisch darstellen
		t3=mathplotlibNode.createMPL()
		t3.Label="My Track Data visualization"
		t3.record=False
		t3.useNumpy=True
		t3.sourceNumpy=t2

		t3.useOut1=True
		t3.useOut2=True
		t3.useOut3=True
		t3.useOut4=True

		t4=numpyNode.createNP()
		t4.Label="My Track Data xy"
		t4.sourceObject=t

		t4.expression2="in2"
		t4.label2 = "path xy"
		
		t4.expressionTime="in1"

		t5=mathplotlibNode.createMPL()
		t5.Label="My Track Data xy Map"
		t5.record=False
		t5.useNumpy=True
		t5.sourceNumpy=t4

		t5.useOut2=True
		FreeCAD.ActiveDocument.recompute()
	except:
		sayexc()

	print "!",orig,"!"
	return (str(tm.lat)+','+str(tm.lon))
	return px,py