forked from Marginal/OverlayEditor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
clutter.py
2505 lines (2274 loc) · 114 KB
/
clutter.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Derived classes expected to have following members:
# __init__
# __str__
# clone -> make a new copy, minus layout
# copy -> make a new copy, minus layout, moved offset
# position -> returns (x,z) position relative to centre of enclosing tile
# load -> read definition
# location -> returns (average) lat/lon
# locationstr -> returns info suitable for display in status bar
# inside -> whether inside a lat,lon bounding box
# layout -> fit to terrain, allocate into VBO(s)
# clearlayout -> clear above
# flush -> clear dynamic VBO allocation (but retain layout) - note doesn't clear instance VBO allocation since def may be shared
# move -> move and layout
# movenode -> move - no layout
# updatenode -> move node - no layout
# updatehandle -> move node bezier control - no layout
# pick_dynamic -> pick geometry in dynamic VBO, including child geometry
# pick_nodes -> pick nodes of selected polygon
# draw_nodes -> draw highlighted
# bucket_dynamic -> callback to enumerate drawing data in dynamic VBO, *not* including children which get separate callbacks
# Clutter (except for DrapedImage) not in the current tile retain their layout, but not their VBO allocation.
import gc
from collections import defaultdict
from math import atan2, ceil, cos, degrees, floor, hypot, modf, pi, radians, sin, tan
import numpy
from numpy import array, array_equal, concatenate, dot, empty, nonzero, float32, float64
from os.path import join
from sys import maxint
if __debug__:
import time
from traceback import print_exc
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.extensions import alternate
from OpenGL.GL.ARB.occlusion_query import *
glBeginQuery = alternate(glBeginQuery, glBeginQueryARB)
glEndQuery = alternate(glEndQuery, glEndQueryARB)
from clutterdef import ClutterDef, ObjectDef, AutoGenPointDef, PolygonDef, DrapedDef, ExcludeDef, FacadeDef, ForestDef, LineDef, StringDef, NetworkDef, ObjectFallback, AutoGenFallback, DrapedFallback, FacadeFallback, ForestFallback, LineFallback, StringFallback, NetworkFallback, SkipDefs, COL_UNPAINTED, COL_POLYGON, COL_FOREST, COL_EXCLUDE, COL_NONSIMPLE, COL_SELECTED, COL_SELBEZ, COL_SELBEZHANDLE, COL_SELNODE
from elevation import BBox, onedeg, maxres, minres, minhdg, resolution, round2res, ElevationMeshBase
from nodes import Node, BezierNode, ParamNode, BezierParamNode, NetworkNode
from palette import PaletteEntry
from prefs import Prefs, prefs
twopi=pi*2
piby2=pi/2
class Clutter:
def __init__(self, name, lat=None, lon=None):
self.name=name.decode() # virtual name ASCII only - may raise UnicodeError
self.definition=None
self.lat=lat # For centreing etc
self.lon=lon
self.vertexcache = None # link to global cache for allocating resources
self.dynamic_data=None # Data for inclusion in VBO
self.base=None # Offset when allocated in VBO
self.parent = None # parent if this is a child
self.placements=[] # child object placements
self.bbox = None # bounding box (x,z)
@staticmethod
def position(tile, lat, lon):
# returns (x,z) position relative to centre of enclosing tile
# z is positive south
return ((lon-tile[1]-0.5)*onedeg*cos(radians(lat)),
(0.5-(lat-tile[0]))*onedeg)
@staticmethod
def latlondisp(dms, lat, lon):
if dms:
sgnlat = lat>=0 and 'N' or 'S'
abslat=abs(lat)
mmlat=(abslat-int(abslat)) * 60.0
sslat=(mmlat-int(mmlat)) * 60.0
sgnlon = lon>=0 and 'E' or 'W'
abslon=abs(lon)
mmlon=(abslon-int(abslon)) * 60.0
sslon=(mmlon-int(mmlon)) * 60.0
return u'Lat: %s%02d\u00B0%02d\u2032%07.4f\u2033 Lon: %s%03d\u00B0%02d\u2032%07.4f\u2033' % (sgnlat, abslat, mmlat, sslat, sgnlon, abslon, mmlon, sslon)
else:
return "Lat: %.7f Lon: %.7f" % (lat, lon)
@staticmethod
def distancedisp(imp, dist):
if imp:
(i,f) = modf(dist * (1/0.3048))
return u'%d\u2032%d\u2033' % (f, round(i*12,0))
else:
return '%.2fm' % dist
class Object(Clutter):
origin=array([0,0,0],float32)
@staticmethod
def factory(name, lat, lon, hdg):
"creates and initialises appropriate Object subclass based on file extension"
if name.lower()[-4:]==AutoGenPointDef.AGP:
return AutoGenPoint(name, lat, lon, hdg)
else:
return Object(name, lat, lon, hdg)
def __init__(self, name, lat, lon, hdg, parent=None):
Clutter.__init__(self, name, lat, lon)
self.parent = parent
self.hdg=hdg
self.y=0
self.transform=None
self.matrix=None
def __str__(self):
return '<Object "%s" %12.7f %11.7f %d %s>' % (
self.name, self.lat, self.lon, self.hdg, self.y)
def clone(self):
return self.__class__(self.name, self.lat, self.lon, self.hdg)
def copy(self, dlat, dlon):
copy = self.clone()
copy.lat -= dlat
copy.lon -= dlon
return copy
def load(self, lookup, defs, vertexcache, usefallback=False, definition=None):
self.vertexcache = vertexcache
if definition:
self.definition = definition # for child objects that may not be in global namespace lookup
return True
try:
if self.name.startswith('*'): # this application's resource
filename=join('Resources', self.name[1:])
else:
filename=lookup[self.name].file
if filename in defs:
self.definition=defs[filename]
else:
gc.disable() # work round http://bugs.python.org/issue4074 on Python<2.7
defs[filename]=self.definition=ObjectDef(filename, vertexcache, lookup, defs)
gc.enable()
return True
except:
# virtual name not found or can't load physical file
gc.enable()
if __debug__:
print_exc()
if usefallback:
if self.name in lookup:
filename=lookup[self.name].file
else:
filename=self.name
lookup[self.name]=PaletteEntry(self.name)
if filename in defs:
self.definition=defs[filename]
else:
defs[filename]=self.definition=ObjectFallback(filename, vertexcache, lookup, defs)
return False
def location(self):
return [self.lat, self.lon]
def locationstr(self, dms, imp, node=None):
if self.y:
return u'%s Hdg: %.1f\u00B0 Elv: %s' % (self.latlondisp(dms, self.lat, self.lon), self.hdg, self.distancedisp(imp, self.y))
else:
return u'%s Hdg: %.1f\u00B0' % (self.latlondisp(dms, self.lat, self.lon), self.hdg)
def inside(self, bbox):
return bbox.inside(self.lon, self.lat)
def pick_dynamic(self, glstate, lookup):
assert self.islaidout() and (self.dynamic_data is None or self.base is not None), self
# assume for speed that children are all Objects and and don't have dynamic data that extends outside the footprint
if __debug__:
for p in self.placements: assert p.__class__ is Object, p
if self.dynamic_data is None:
return False
elif glstate.occlusion_query:
glBeginQuery(glstate.occlusion_query, glstate.queries[len(lookup)])
glDrawArrays(GL_TRIANGLES, self.base, len(self.dynamic_data)/6)
# no need to draw point at origin in case no fragments generated, since pick_instanced handles this for Objects
glEndQuery(glstate.occlusion_query)
else:
glLoadName(len(lookup))
glDrawArrays(GL_TRIANGLES, self.base, len(self.dynamic_data)/6)
lookup.append(self)
return True
def draw_nodes(self, glstate, selectednode):
pass
def bucket_dynamic(self, base, buckets):
self.base = base
buckets.add(self.definition.layer, self.definition.texture_draped, base, len(self.dynamic_data)/6)
if __debug__: # draw outline for debug
for i in range(base, base+len(self.dynamic_data)/6, 3):
buckets.add(ClutterDef.OUTLINELAYER, None, i, 3)
return self.dynamic_data
def clearlayout(self):
self.transform=None
self.matrix=None
self.dynamic_data=None # Can be removed from dynamic VBO
self.flush()
for p in self.placements:
p.clearlayout()
# number of children is fixed, so no need to delete and re-create them
def islaidout(self):
return self.transform is not None
def flush(self):
self.vertexcache.allocate_dynamic(self, False)
self.definition.instances.discard(self)
self.definition.transform_valid=False
for p in self.placements:
p.flush()
def layout(self, tile, x=None, y=None, z=None, hdg=None, meshtris=None, recalc=True):
self.definition.instances.add(self)
self.definition.transform_valid=False
if self.islaidout() and not recalc:
# just ensure allocated
self.definition.allocate(self.vertexcache)
if self.dynamic_data is not None: self.vertexcache.allocate_dynamic(self, True)
for p in self.placements:
p.layout(tile, recalc=False)
return
elev = self.vertexcache.getElevationMesh(tile)
if not (x and z):
x,z=self.position(tile, self.lat, self.lon)
if meshtris is None: # if meshtris are passed in then assume bbox has already been calculated
self.bbox = BBox(x, x, z, z)
meshtris = elev.getbox(self.bbox)
if y is not None:
self.y=y
else:
self.y = elev.height(x,z,meshtris)
if hdg is not None:
self.hdg=hdg
h = radians(self.hdg)
s = sin(h)
c = cos(h)
self.transform = array([x,self.y,z,h],float32)
self.matrix = array([c,0.0,s,0.0, 0.0,1.0,0.0,0.0, -s,0.0,c,0.0, x,self.y,z,1.0],float32)
self.definition.allocate(self.vertexcache) # ensure allocated
for p in self.placements:
p.layout(tile, meshtris=meshtris)
# draped & poly_os
if not self.definition.draped: return
coshdg=cos(h)
sinhdg=sin(h)
if self.definition.poly or elev.flat: # poly_os
self.dynamic_data=array([[x+v[0]*coshdg-v[2]*sinhdg,self.y+v[1],z+v[0]*sinhdg+v[2]*coshdg,v[3],v[4],0] for v in self.definition.draped], float32).flatten()
self.vertexcache.allocate_dynamic(self, True)
else: # draped
tris=[]
for v in self.definition.draped:
vx=x+v[0]*coshdg-v[2]*sinhdg
vz=z+v[0]*sinhdg+v[2]*coshdg
vy = elev.height(vx, vz, meshtris)
tris.append([vx,vy,vz,v[3],v[4],0])
tris = elev.drapetris(tris, meshtris)
if tris:
self.dynamic_data = concatenate(tris)
self.vertexcache.allocate_dynamic(self, True)
else:
self.dynamic_data = None
self.vertexcache.allocate_dynamic(self, False)
def move(self, dlat, dlon, dhdg, dparam, loc, tile):
self.lat=max(tile[0], min(tile[0]+maxres, self.lat+dlat))
self.lon=max(tile[1], min(tile[1]+maxres, self.lon+dlon))
if dhdg:
h=atan2(self.lon-loc[1], self.lat-loc[0])+radians(dhdg)
l=hypot(self.lon-loc[1], self.lat-loc[0])
self.lat=max(tile[0], min(tile[0]+maxres, round2res(loc[0]+cos(h)*l)))
self.lon=max(tile[1], min(tile[1]+maxres, round2res(loc[1]+sin(h)*l)))
self.hdg=(self.hdg+dhdg)%360
self.layout(tile)
def write(self, idx, south, west):
# DSFTool rounds down, so round up here first
return 'OBJECT\t%d\t%14.9f %14.9f %5.1f\n' % (idx, min(west+1, self.lon+minres/4), min(south+1, self.lat+minres/4), round(self.hdg,1)+minhdg/4)
class AutoGenPoint(Object):
def load(self, lookup, defs, vertexcache, usefallback=False, definition=None):
self.vertexcache = vertexcache
try:
filename=lookup[self.name].file
if filename in defs:
self.definition=defs[filename]
else:
defs[filename]=self.definition=AutoGenPointDef(filename, vertexcache, lookup, defs)
except:
# virtual name not found or can't load physical file
if __debug__:
print_exc()
if usefallback:
if self.name in lookup:
filename=lookup[self.name].file
else:
filename=self.name
lookup[self.name]=PaletteEntry(self.name)
if filename in defs:
self.definition=defs[filename]
else:
defs[filename]=self.definition=AutoGenFallback(filename, vertexcache, lookup, defs)
return False
# load children
self.placements=[] # might not be empty if e.g. we're re-loading after Undo
for child in self.definition.children:
(childname, definition, xdelta, zdelta, hdelta)=child
assert definition.filename in defs # Child Def should have been created when AutoGenPointDef was loaded
placement = Object(childname, self.lat, self.lon, self.hdg, parent=self)
placement.load(None, None, vertexcache, definition=definition)
self.placements.append(placement)
return True
if __debug__:
def layoutp(self, tile, recalc=True):
try:
from cProfile import runctx
runctx('self.layout2(tile, recalc)', globals(), locals(), 'profile.dmp')
except:
print_exc()
def layout(self, tile, recalc=True):
if self.islaidout() and not recalc:
# just ensure allocated
Object.layout(self, tile, recalc=False)
return
# We're likely to be doing a lot of height testing and draping, so pre-compute relevant mesh
# triangles on the assumption that all children are contained in .agp's "floorplan"
x,z=self.position(tile, self.lat, self.lon)
self.bbox = BBox(x, x, z, z)
h=radians(self.hdg)
coshdg=cos(h)
sinhdg=sin(h)
for v in self.definition.draped:
self.bbox.include(x+v[0]*coshdg-v[2]*sinhdg, z+v[0]*sinhdg+v[2]*coshdg)
elev = self.vertexcache.getElevationMesh(tile)
mymeshtris = elev.getbox(self.bbox)
Object.layout(self, tile, x, None, z, self.hdg, mymeshtris)
assert len(self.placements)==len(self.definition.children), "%s %s %s %s" % (self, len(self.placements), self.definition, len(self.definition.children))
for i in range(len(self.placements)):
(childname, definition, xdelta, zdelta, hdelta)=self.definition.children[i]
childx=x+xdelta*coshdg-zdelta*sinhdg
childz=z+xdelta*sinhdg+zdelta*coshdg
self.placements[i].layout(tile, childx, None, childz, self.hdg+hdelta, mymeshtris)
class Polygon(Clutter):
BEZPTS = 8 # X-Plane stops at or before 8?
NETBEZPTS = 4 # X-Plane seems lazier about networks
@staticmethod
def factory(name, param, nodes, lon=None, size=None, hdg=None):
"creates and initialises appropriate Polygon subclass based on file extension"
if lon==None:
nodes = [[Node(coords) for coords in winding] for winding in nodes]
if name.startswith(PolygonDef.EXCLUDE):
return Exclude(name, param, nodes, lon, size, hdg)
ext=name.lower()[-4:]
if ext==PolygonDef.DRAPED:
return Draped(name, param, nodes, lon, size, hdg)
elif ext==PolygonDef.FACADE:
return Facade(name, param, nodes, lon, size, hdg)
elif ext==PolygonDef.FOREST:
return Forest(name, param, nodes, lon, size, hdg)
elif ext==PolygonDef.LINE:
return Line(name, param, nodes, lon, size, hdg)
elif ext==PolygonDef.STRING:
return String(name, param, nodes, lon, size, hdg)
elif ext==PolygonDef.BEACH:
return Beach(name, param, nodes, lon, size, hdg)
elif ext==NetworkDef.NETWORK:
return Network(name, param, nodes, lon, size, hdg)
elif ext==ObjectDef.OBJECT:
raise IOError # not a polygon
elif ext in SkipDefs:
raise IOError # what's this doing here?
else: # unknown polygon type
return Polygon(name, param, nodes, lon, size, hdg)
def __init__(self, name, param, nodes, lon=None, size=None, hdg=None):
if param==None: param=0
if lon==None:
Clutter.__init__(self, name)
assert isinstance(nodes[0][0], Node)
self.nodes = nodes
else:
lat=nodes
Clutter.__init__(self, name, lat, lon)
h=radians(hdg)
self.nodes=[[]]
size=0.000007071*size
for i in [h+5*pi/4, h+3*pi/4, h+pi/4, h+7*pi/4]:
self.nodes[0].append(Node([max(floor(lon), min(floor(lon)+1, round2res(self.lon+sin(i)*size))),
max(floor(lat), min(floor(lat)+1, round2res(self.lat+cos(i)*size)))]))
self.param=param
self.nonsimple=False # True iff non-simple and the polygon type cares about it (i.e. not Facades)
self.singlewinding = True # most polygon types don't support additional windings
self.fixednodes = False # most polygon types support additional nodes
self.canbezier = False # support for bezier control points
self.isbezier = False # nodes are derived from BezierNode, not just Node
self.closed=True # Open or closed
self.col=COL_POLYGON # Outline colour
self.points=[] # list of windings in world space (x,y,z), including points generated by bezier curves
self.bbox = None # bounding box for above
def __str__(self):
return '<"%s" %d %s>' % (self.name,self.param,self.points)
def clone(self):
return self.__class__(self.name, self.param, [[p.clone() for p in w] for w in self.nodes])
def copy(self, dlat, dlon):
copy = self.clone()
# move manually to avoid rounding etc and complications while not loaded
for w in copy.nodes:
for node in w:
node.move(-dlat, -dlon, None)
return copy
def load(self, lookup, defs, vertexcache, usefallback=True):
self.vertexcache = vertexcache
if self.name in lookup:
filename=lookup[self.name].file
else:
filename=None
self.definition=PolygonDef(filename, vertexcache, lookup, defs)
return True
def location(self):
if self.lat==None:
self.lon = sum([node.lon for node in self.nodes[0]]) / len(self.nodes[0])
self.lat = sum([node.lat for node in self.nodes[0]]) / len(self.nodes[0])
return [self.lat, self.lon]
# horizontal distance to adjacent node(s)
def distancestr(self, imp, node):
(i,j) = node
pt = self.nodes[i][j].loc
n = len(self.nodes[i])
if j==0 and not self.closed:
nxt = self.nodes[i][j+1].loc
return u'\u2022%s' % self.distancedisp(imp, hypot(pt[0]-nxt[0], pt[2]-nxt[2]))
elif j==n-1 and not self.closed:
prv = self.nodes[i][j-1].loc
return u'\u2022%s' % self.distancedisp(imp, hypot(pt[0]-prv[0], pt[2]-prv[2]))
else:
prv = self.nodes[i][(j-1)%n].loc
nxt = self.nodes[i][(j+1)%n].loc
return u'%s\u2022%s' % (self.distancedisp(imp, hypot(pt[0]-prv[0], pt[2]-prv[2])), self.distancedisp(imp, hypot(pt[0]-nxt[0], pt[2]-nxt[2])))
def locationstr(self, dms, imp, node=None, extranodeinfo=None):
if node:
(i,j)=node
hole=['', 'Hole '][i and 1]
extra = extranodeinfo and ' '+extranodeinfo or ''
if self.nodes[i][j].loc[1]:
return '%s Elv: %s %sNode %d%s %s' % (self.latlondisp(dms, self.nodes[i][j].lat, self.nodes[i][j].lon), self.distancedisp(imp, self.nodes[i][j].loc[1]), hole, j, extra, self.distancestr(imp, node))
else:
return '%s %sNode %d%s %s' % (self.latlondisp(dms, self.nodes[i][j].lat, self.nodes[i][j].lon), hole, j, extra, self.distancestr(imp, node))
else:
return u'%s Param\u2195 %-3d (%d nodes)' % (self.latlondisp(dms, self.lat, self.lon), self.param, len(self.nodes[0]))
def inside(self, bbox):
for w in self.nodes:
for node in w:
if bbox.inside(node.lon, node.lat):
return True
return False
def pick_dynamic(self, glstate, lookup):
assert self.islaidout() and self.base is not None, self
# assume for speed that children are all Objects and so don't have dynamic data
if __debug__:
for p in self.placements: assert p.__class__ is Object, p
base=self.base
if glstate.occlusion_query:
glBeginQuery(glstate.occlusion_query, glstate.queries[len(lookup)])
for winding in self.points:
glDrawArrays(GL_LINE_STRIP, base, len(winding))
base+=len(winding)
glEndQuery(glstate.occlusion_query)
else:
glLoadName(len(lookup))
for winding in self.points:
glDrawArrays(GL_LINE_STRIP, base, len(winding))
base+=len(winding)
lookup.append(self)
return True
def draw_nodes(self, glstate, selectednode):
# Just do it in immediate mode
# bezier control handles
if self.canbezier:
glstate.set_color(COL_SELBEZ)
glBegin(GL_LINES)
for winding in self.nodes:
for node in winding:
if node.bezier:
glVertex3f(*node.bezloc)
glVertex3f(*node.loc)
glVertex3f(*node.loc)
glVertex3f(*node.bz2loc)
glEnd()
glstate.set_color(COL_SELECTED)
for winding in self.points:
glBegin(GL_LINE_STRIP)
for p in winding:
glVertex3f(*p)
glEnd()
# draw selected on top
if selectednode:
(i,j) = selectednode
node = self.nodes[i][j]
if self.canbezier and node.bezier:
glstate.set_color(COL_SELBEZHANDLE)
glBegin(GL_LINES)
glVertex3f(*node.bezloc)
glVertex3f(*node.loc)
glVertex3f(*node.loc)
glVertex3f(*node.bz2loc)
glEnd()
glstate.set_color(COL_SELNODE)
# Points
if glstate.pointshader: # have to do point smoothing with a shader if we're using shaders
glUseProgram(glstate.pointshader)
else:
glEnable(GL_POINT_SMOOTH)
# bezier control handles
if self.canbezier:
glstate.set_color(COL_SELBEZ)
glBegin(GL_POINTS)
for winding in self.nodes:
for node in winding:
if node.bezier:
glVertex3f(*node.bezloc)
glVertex3f(*node.bz2loc)
glEnd()
glstate.set_color(COL_SELECTED)
glBegin(GL_POINTS)
for winding in self.nodes:
for node in winding:
glVertex3f(*node.loc)
glEnd()
# draw selected on top
if selectednode:
(i,j) = selectednode
node = self.nodes[i][j]
glstate.set_color(COL_SELNODE)
glBegin(GL_POINTS)
glVertex3f(*node.loc)
if self.canbezier and node.bezier:
glVertex3f(*node.bezloc)
glVertex3f(*node.bz2loc)
glEnd()
if glstate.pointshader:
glUseProgram(glstate.colorshader)
else:
glDisable(GL_POINT_SMOOTH) # Make selection etc slightly easier on the GPU
def bucket_dynamic(self, base, buckets):
# allocate for drawing, assuming outlines
self.base = base
for winding in self.points:
buckets.add(ClutterDef.OUTLINELAYER, None, base, len(winding))
base += len(winding)
return self.dynamic_data
def clearlayout(self):
self.points=[]
self.dynamic_data=None # Can be removed from VBO
self.flush()
for p in self.placements:
p.clearlayout()
self.placements=[]
def islaidout(self):
return self.dynamic_data is not None
def flush(self):
self.vertexcache.allocate_dynamic(self, False)
for p in self.placements:
p.flush()
def layout_nodes(self, tile, selectednode):
self.lat=self.lon=0
self.points=[]
self.bbox = BBox()
self.nonsimple=False
fittomesh=self.definition.fittomesh
elev = self.vertexcache.getElevationMesh(tile)
if not fittomesh:
# elevation determined by mid-point of nodes 0 and 1
if len(self.nodes[0])>1:
self.lon=(self.nodes[0][0].lon+self.nodes[0][1].lon)/2
self.lat=(self.nodes[0][0].lat+self.nodes[0][1].lat)/2
else: # shouldn't happen
self.lon=self.nodes[0][0].lon
self.lat=self.nodes[0][0].lat
(x,z)=self.position(tile, self.lat, self.lon)
y = elev.height(x,z)
else:
self.lon = sum([node.lon for node in self.nodes[0]]) / len(self.nodes[0])
self.lat = sum([node.lat for node in self.nodes[0]]) / len(self.nodes[0])
i = 0
while i < len(self.nodes):
nodes=self.nodes[i]
n=len(nodes)
a=0
for j in range(n):
node = nodes[j]
(x,z) = self.position(tile, node.lat, node.lon)
if fittomesh:
y = elev.height(x,z)
node.setloc(x,y,z)
if node.bezier:
(x,z) = self.position(tile, node.lat+node.bezlat, node.lon+node.bezlon)
node.setbezloc(x,y,z)
(x,z) = self.position(tile, node.lat+node.bz2lat, node.lon+node.bz2lon)
node.setbz2loc(x,y,z)
a += node.lon * nodes[(j+1)%n].lat - nodes[(j+1)%n].lon * node.lat
if self.closed and ((i==0 and a<0) or (i and a>0)):
# Outer should be CCW, inner CW
nodes.reverse()
if selectednode and selectednode[0]==i: selectednode=(i,n-1-selectednode[1])
if self.isbezier:
for node in nodes: node.swapbez()
continue # re-do layout with updated beziers
points=[]
bezpts = Polygon.BEZPTS
for j in range(n):
node = nodes[j]
nxt = nodes[(j+1)%n]
node.pointidx = len(points) # which point corresponds to this node
points.append(node.loc)
if self.canbezier and (self.closed or j!=n-1) and (node.bezier or nxt.bezier): # only do beziers from last point if closed
if fittomesh:
if isinstance(self, Network): # limit number of bezier points for speed
size = hypot(nxt.loc[0] - node.loc[0], nxt.loc[2] - node.loc[2])
bezpts = min(Polygon.NETBEZPTS, max(2, int(1.414 * size / self.definition.width)))
for u in range(1,bezpts):
if node.bezier and nxt.bezier:
(bx,by,bz) = self.bez4([node.loc, node.bezloc, nxt.bz2loc, nxt.loc], float(u)/bezpts)
elif node.bezier:
(bx,by,bz) = self.bez3([node.loc, node.bezloc, nxt.loc], float(u)/bezpts)
else:
(bx,by,bz) = self.bez3([node.loc, nxt.bz2loc, nxt.loc], float(u)/bezpts)
points.append((bx, elev.height(bx,bz), bz))
else:
if node.bezier and nxt.bezier:
points.extend([self.bez4([node.loc, node.bezloc, nxt.bz2loc, nxt.loc], float(u)/bezpts) for u in range(1,bezpts)])
elif node.bezier:
points.extend([self.bez3([node.loc, node.bezloc, nxt.loc], float(u)/bezpts) for u in range(1,bezpts)])
else:
points.extend([self.bez3([node.loc, nxt.bz2loc, nxt.loc], float(u)/bezpts) for u in range(1,bezpts)])
if self.closed: points.append(points[0]) # repeat first if closed
self.points.append(points)
i += 1
for (x,y,z) in self.points[0]:
self.bbox.include(x,z)
return selectednode
def layout(self, tile, selectednode=None, recalc=True):
if self.islaidout() and not recalc:
# just ensure allocated
self.vertexcache.allocate_dynamic(self, True)
for p in self.placements:
p.layout(tile, recalc=False)
return selectednode
selectednode=self.layout_nodes(tile, selectednode)
col=self.nonsimple and COL_NONSIMPLE or self.col
self.dynamic_data=concatenate([array(p+col,float32) for w in self.points for p in w])
self.vertexcache.allocate_dynamic(self, True)
for p in self.placements:
p.layout(tile)
return selectednode
def addnode(self, tile, selectednode, lat, lon, clockwise=False):
if self.fixednodes: return False
(i,j)=selectednode
n=len(self.nodes[i])
if n>=255: return False # node count is encoded as uint8 in DSF
if (not self.closed) and (j==0 or j==n-1):
# Special handling for ends of open lines and facades - add new node at cursor
if j:
newnode=nextnode=j+1
else:
newnode=nextnode=0
self.nodes[i].insert(newnode, self.nodes[0][0].__class__([lon, lat]))
else:
if (i and clockwise) or (not i and not clockwise):
newnode=j+1
nextnode=(j+1)%n
else:
newnode=j
nextnode=(j-1)%n
self.nodes[i].insert(newnode, self.nodes[0][0].__class__([round2res((self.nodes[i][j].lon + self.nodes[i][nextnode].lon)/2),
round2res((self.nodes[i][j].lat + self.nodes[i][nextnode].lat)/2)]))
return self.layout(tile, (i,newnode))
def delnode(self, tile, selectednode, clockwise=False):
if self.fixednodes: return False
(i,j)=selectednode
if len(self.nodes[i])<=(self.closed and 3 or 2): # Open lines and facades can have just two nodes
return self.delwinding(tile, selectednode)
self.nodes[i].pop(j)
if (i and clockwise) or (not i and not clockwise):
selectednode=(i,(j-1)%len(self.nodes[i]))
else:
selectednode=(i,j%len(self.nodes[i]))
self.layout(tile, selectednode)
return selectednode
def addwinding(self, tile, size, hdg):
if self.singlewinding: return False
minrad=0.000007071*size
for j in self.nodes[0]:
minrad=min(minrad, abs(self.lon-j.lon), abs(self.lat-j.lat))
i=len(self.nodes)
h=radians(hdg)
self.nodes.append([])
for j in [h+5*pi/4, h+7*pi/4, h+pi/4, h+3*pi/4]:
self.nodes[i].append(self.nodes[0][0].__class__([round2res(self.lon+sin(j)*minrad), round2res(self.lat+cos(j)*minrad)]))
return self.layout(tile, (i,0))
def delwinding(self, tile, selectednode):
(i,j)=selectednode
if not i: return False # don't delete outer winding
self.nodes.pop(i)
return self.layout(tile, (i-1,0))
def togglebezier(self, tile, selectednode):
# Add or delete bezier control points
(i,j) = selectednode
node = self.nodes[i][j]
n = len(self.nodes[i])
if not self.canbezier:
return False
elif node.bezier:
node.bezier = False # retain bezier co-ordinates in case user changes their mind
node.split = False # but unsplit
node.bz2lon = -node.bezlon
node.bz2lat = -node.bezlat
elif self.isbezier and (node.bezlat or node.bezlon):
node.bezier = True # use retained co-ordinates
else:
if not self.isbezier:
self.nodes = [[BezierNode(p) for p in w] for w in self.nodes] # trashes layout
self.isbezier = True
node = self.nodes[i][j]
node.bezier = True
if not self.closed and j==0:
(node.bezlon, node.bezlat) = ((self.nodes[i][j+1].lon - node.lon) / 2, (self.nodes[i][j+1].lat - node.lat) / 2)
(node.bz2lon, node.bz2lat) = (-node.bezlon, -node.bezlat)
elif not self.closed and j==n-1:
(node.bz2lon, node.bz2lat) = ((self.nodes[i][j-1].lon - node.lon) / 2, (self.nodes[i][j-1].lat - node.lat) / 2)
(node.bezlon, node.bezlat) = (-node.bz2lon, -node.bz2lat)
else:
(node.bezlon, node.bezlat) = ((self.nodes[i][(j+1)%n].lon - self.nodes[i][(j-1)%n].lon) / 4, (self.nodes[i][(j+1)%n].lat - self.nodes[i][(j-1)%n].lat) / 4)
(node.bz2lon, node.bz2lat) = (-node.bezlon, -node.bezlat)
return self.layout(tile, selectednode, True)
def move(self, dlat, dlon, dhdg, dparam, loc, tile):
if dlat or dlon:
for i in range(len(self.nodes)):
for j in range(len(self.nodes[i])):
self.movenode((i,j), dlat, dlon, 0, tile)
if dhdg:
for w in self.nodes:
for p in w:
p.rotate(dhdg, loc, tile)
if dparam:
self.param+=dparam
if self.param<0: self.param=0
elif self.param>65535: self.param=65535 # uint16
# do layout if changed
if dlat or dlon or dhdg or dparam:
self.layout(tile)
def movenode(self, node, dlat, dlon, darg, tile, defer=True):
# Most polygons don't have co-ordinate arguments other than lat/lon & beziers, so darg ignored here.
if not self.canbezier:
# Trash additional co-ordinates of unknown types, and of types (e.g. v8 Facades) that don't meaningfully support them
self.nodes = [[Node(p) for p in w] for w in self.nodes] # trashes layout
self.isbezier = False
(i,j)=node
self.nodes[i][j].move(dlat, dlon, tile)
if defer:
return node
else:
return self.layout(tile, node)
def updatenode(self, node, lat, lon, tile):
# update node height but defer full layout. Assumes lat,lon is valid
(i,j) = node
p = self.nodes[i][j]
p.lon = lon
p.lat = lat
(x,z) = self.position(tile, lat, lon)
if not self.canbezier:
# Trash additional co-ordinates of unknown types, and of types (e.g. v8 Facades) that don't meaningfully support them
if self.isbezier:
p.setloc(x, None, z)
self.nodes = [[Node(p) for p in w] for w in self.nodes] # trashes layout
self.isbezier = False
return self.layout(tile, node)
else:
for w in self.nodes:
for p in w:
p.rest = []
if self.definition.fittomesh:
p.setloc(x, self.vertexcache.getElevationMesh(tile).height(x,z), z)
else:
p.setloc(x, None, z) # assumes elevation already correct
if p.bezier:
(x,z) = self.position(tile, p.lat+p.bezlat, p.lon+p.bezlon)
p.setbezloc(x, None, z)
(x,z) = self.position(tile, p.lat+p.bz2lat, p.lon+p.bz2lon)
p.setbz2loc(x, None, z)
return node
def updatehandle(self, node, handle, split, lat, lon, tile):
# Defer full layout
assert handle in [1,2], handle
assert self.isbezier and self.canbezier # shouldn't be able to manipulate control handles on types we think shouldn't have them
(i,j) = node
p = self.nodes[i][j]
assert p.bezier
(x,z) = self.position(tile, lat, lon)
if self.closed or (j>0 and j<len(self.nodes[i])-1):
if split: p.split = True
else:
p.split = False # meaningless to split first or last node of open poly
if handle==1:
(p.bezlon, p.bezlat) = (lon - p.lon, lat - p.lat)
p.setbezloc(x, None, z)
if not p.split:
(p.bz2lon, p.bz2lat) = (-p.bezlon, -p.bezlat)
(x,z) = self.position(tile, p.lat + p.bz2lat, p.lon + p.bz2lon)
p.setbz2loc(x, None, z)
else:
(p.bz2lon, p.bz2lat) = (lon - p.lon, lat - p.lat)
p.setbz2loc(x, None, z)
if not p.split:
(p.bezlon, p.bezlat) = (-p.bz2lon, -p.bz2lat)
(x,z) = self.position(tile, p.lat + p.bezlat, p.lon + p.bezlon)
p.setbezloc(x, None, z)
return node
def pick_nodes(self, projection, withhandles):
# prefer inner windings over outer, and handles over node
if withhandles and self.isbezier:
for i in range(len(self.nodes)-1, -1, -1):
nodes = self.nodes[i]
points = empty((len(nodes) * 3, 4))
points[:,:3] = array([node.bezier and node.bz2loc or node.loc for node in nodes] + [node.bezier and node.bezloc or node.loc for node in nodes] + [node.loc for node in nodes])
points[:,3] = 1 # make homogenous
projected = numpy.abs(dot(points, projection)[:,:2]) # |x|,|y| in NDC space
inview = numpy.nonzero(numpy.all(projected <= 1, axis=1))[0]
if len(inview):
j = inview[0] % len(nodes)
return ((i,j), nodes[j].bezier and (2 - inview[0]/len(nodes)) or 0)
else:
for i in range(len(self.nodes)-1, -1, -1):
nodes = self.nodes[i]
points = empty((len(nodes), 4))
points[:,:3] = array([node.loc for node in nodes])
points[:,3] = 1 # make homogenous
projected = numpy.abs(dot(points, projection)[:,:2]) # |x|,|y| in NDC space
inview = numpy.nonzero(numpy.all(projected <= 1, axis=1))[0]
if len(inview):
return ((i,inview[0]), 0)
return None
def write(self, idx, south, west):
# DSFTool rounds down, so round up here first
s = 'BEGIN_POLYGON\t%d\t%d %d\n' % (idx, self.param, self.nodes[0][0].coordcount())
for w in self.nodes:
s += 'BEGIN_WINDING\n'
for p in w:
s += p.write(south,west)
s += 'END_WINDING\n'
s += 'END_POLYGON\n'
return s
def bez3(self, p, mu):
# http://paulbourke.net/geometry/bezier/
mum1 = 1-mu
mu2 = mu*mu
mum12= mum1*mum1
return (p[0][0]*mum12 + 2*p[1][0]*mum1*mu + p[2][0]*mu2, p[0][1], p[0][2]*mum12 + 2*p[1][2]*mum1*mu + p[2][2]*mu2)
def bez4(self, p, mu):
# http://paulbourke.net/geometry/bezier/
mum1 = 1-mu
mu3 = mu*mu*mu
mum13= mum1*mum1*mum1
return (p[0][0]*mum13 + 3*p[1][0]*mu*mum1*mum1 + 3*p[2][0]*mu*mu*mum1 + p[3][0]*mu3, p[0][1], p[0][2]*mum13 + 3*p[1][2]*mu*mum1*mum1 + 3*p[2][2]*mu*mu*mum1 + p[3][2]*mu3)
class Beach(Polygon):
# Editing would zap extra vertex parameters that we don't understand,
# so make a dummy type to prevent selection and therefore editing
def __init__(self, name, param, nodes, lon=None, size=None, hdg=None):
Polygon.__init__(self, name, param, nodes, lon, size, hdg)
def load(self, lookup, defs, vertexcache, usefallback=True):
Polygon.load(self, lookup, defs, vertexcache, usefallback=True)
self.definition.layer=ClutterDef.BEACHESLAYER
def pick_dynamic(self, glstate, lookup):
return False # Don't draw so can't be picked
class Draped(Polygon):
def tessvertex(vertex, data):
data.append(vertex)
def tessedge(flag):
pass # dummy
tess=gluNewTess()
gluTessNormal(tess, 0, -1, 0)
gluTessProperty(tess, GLU_TESS_WINDING_RULE, GLU_TESS_WINDING_NEGATIVE)
gluTessCallback(tess, GLU_TESS_VERTEX_DATA, tessvertex)
gluTessCallback(tess, GLU_TESS_EDGE_FLAG, tessedge) # no strips
def __init__(self, name, param, nodes, lon=None, size=None, hdg=None):
Polygon.__init__(self, name, param, nodes, lon, size, hdg)
if self.param == 65535:
self.fixednodes = True # we don't support new nodes in orthos
self.canbezier = False
if len(self.nodes[0][0].rest)==6: # Has bezier coords but DSFTool can't write them, so demote
for w in self.nodes:
for p in w:
p.rest = p.rest[4:6]
else:
self.singlewinding = False # Can have holes if not an orthophoto
self.canbezier = True # can have curves if not an orthophoto
if len(self.nodes[0][0].rest)==2: # Has bezier coords - promote
self.nodes = BezierNode.fromNodes(self.nodes)
self.isbezier = True
elif isinstance(self.nodes[0][0], BezierNode):
self.isbezier = True # already promoted
def load(self, lookup, defs, vertexcache, usefallback=False):
self.vertexcache = vertexcache
try:
filename=lookup[self.name].file
if filename in defs:
self.definition=defs[filename]
else:
defs[filename]=self.definition=DrapedDef(filename, vertexcache, lookup, defs)
return True
except:
if __debug__:
print_exc()
if usefallback:
if self.name in lookup:
filename=lookup[self.name].file
else:
filename=self.name
lookup[self.name]=PaletteEntry(self.name)