Exemplo n.º 1
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
Exemplo n.º 2
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
Exemplo n.º 3
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
Exemplo n.º 4
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)
Exemplo n.º 5
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 = urllib.request.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