-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdxf_manager.py
More file actions
845 lines (714 loc) · 37 KB
/
Copy pathdxf_manager.py
File metadata and controls
845 lines (714 loc) · 37 KB
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
"""Low-level DXF drawing manager.
Wraps ezdxf to provide the drawing primitives used by the plan generators
(beacons, parcels, contours, frames, title blocks, ...). All coordinates
passed to this class are in model units (metres); they are multiplied by
``scale`` so that the finished drawing is at the requested plan scale.
"""
import logging
import math
import os
import re
import tempfile
import uuid
import zipfile
from datetime import datetime
from typing import List, Optional, Tuple
import ezdxf
from ezdxf import bbox, colors
from ezdxf.addons import odafc
from ezdxf.addons.drawing import Frontend, RenderContext, config, layout, pymupdf
from ezdxf.enums import TextEntityAlignment
from ezdxf.fonts import fonts as ezfonts
from ezdxf.tools.text import MTextEditor
from upload import upload_file
logger = logging.getLogger(__name__)
# Metric-compatible substitutes used to *measure* text when the style's real
# font is not installed (e.g. in the Docker container). The DXF still names
# the original font; only the width/height estimates use the substitute.
MEASUREMENT_FONT_SUBSTITUTES = {
"times new roman": "LiberationSerif-Regular.ttf",
"arial": "LiberationSans-Regular.ttf",
"courier new": "LiberationMono-Regular.ttf",
}
# Paper sizes in mm (width, height) for portrait orientation.
PAPER_SIZES = {
"A0": (841, 1189),
"A1": (594, 841),
"A2": (420, 594),
"A3": (297, 420),
"A4": (210, 297),
"A5": (148, 210),
"LETTER": (216, 279),
"LEGAL": (216, 356),
}
def nice_round(value: float) -> float:
"""Round a positive value to the nearest 'nice' number (1, 2, 2.5, 5 x 10^k)."""
if value <= 0:
return 1.0
exp = math.floor(math.log10(value))
frac = value / 10 ** exp
nice = min((1.0, 2.0, 2.5, 5.0, 10.0), key=lambda n: abs(n - frac))
return nice * 10 ** exp
class SurveyDXFManager:
def __init__(self, plan_name: str = "Survey Plan", scale: float = 1.0, dxf_version: str = "R2000"):
self.plan_name = plan_name
self.scale = scale
self.dxf_version = dxf_version
self.doc = ezdxf.new(dxfversion=dxf_version)
self.msp = self.doc.modelspace()
self.setup_layers()
# Document units
self.doc.header["$INSUNITS"] = 6 # meters
self.doc.header["$LUNITS"] = 2 # decimal
self.doc.header["$LUPREC"] = 3 # 3 decimal places
self.doc.header["$AUNITS"] = 1 # degrees/minutes/seconds
self.doc.header["$AUPREC"] = 3 # 0d00'00"
self.doc.header["$ANGBASE"] = 90.0 # 0 degrees points North
# Absolute point display size; the default (0 = relative to viewport)
# is unsupported by the PDF renderer and triggers a log warning.
self.doc.header["$PDSIZE"] = 1.0
# ------------------------------------------------------------------
# Layer / style setup
# ------------------------------------------------------------------
def setup_layers(self):
self.doc.layers.add(name="LABELS", color=colors.BLACK)
self.doc.layers.add(name="FRAME", color=colors.BLACK)
self.doc.layers.add(name="TITLE_BLOCK", color=colors.BLACK)
self.doc.layers.add(name="FOOTER", color=colors.BLACK)
def setup_cadastral_layers(self):
self.doc.layers.add(name="BEACONS", color=colors.BLACK)
self.doc.layers.add(name="PARCELS", color=colors.RED)
def setup_topographic_layers(self):
self.doc.layers.add(name="BEACONS", color=colors.BLACK)
self.doc.layers.add(name="BOUNDARY", color=colors.RED)
self.doc.layers.add("CONTOUR_MAJOR", true_color=colors.rgb2int((127, 31, 0)),
linetype="Continuous", lineweight=35)
self.doc.layers.add("CONTOUR_MINOR", true_color=colors.rgb2int((127, 31, 0)),
linetype="Continuous", lineweight=18)
self.doc.layers.add("CONTOUR_LABELS", true_color=colors.rgb2int((127, 31, 0)))
self.doc.layers.add("TIN_MESH", color=colors.GRAY, linetype="Continuous", lineweight=9)
self.doc.layers.add("GRID_MESH", color=colors.LIGHT_GRAY, linetype="Dot", lineweight=9)
self.doc.layers.add("SPOT_HEIGHTS", true_color=colors.rgb2int((205, 105, 40)),
linetype="Continuous", lineweight=25)
def setup_layout_layers(self):
self.doc.layers.add(name="BEACONS", color=colors.BLACK)
self.doc.layers.add(name="BOUNDARY", color=colors.RED, linetype="CONTINUOUS", lineweight=50)
self.doc.layers.add(name="PARCELS", color=colors.GREEN, linetype="CONTINUOUS", lineweight=25)
self.doc.layers.add(name="ROADS", color=colors.BLACK, linetype="CONTINUOUS", lineweight=35)
self.doc.layers.add(name="ROADS_CL", color=colors.CYAN, linetype="DASHDOT", lineweight=18)
self.doc.layers.add(name="SETBACKS", color=colors.MAGENTA, linetype="DASHED", lineweight=18)
self.doc.layers.add(name="DIMENSIONS", color=colors.YELLOW, linetype="CONTINUOUS", lineweight=18)
self.doc.layers.add(name="TEXT", color=colors.BLACK, linetype="CONTINUOUS", lineweight=18)
self.doc.layers.add(name="GREEN_SPACE", color=colors.GREEN, linetype="CONTINUOUS", lineweight=25)
self.doc.layers.add(name="UTILITIES", color=colors.BLUE, linetype="DASHED", lineweight=18)
self.doc.layers.add(name="EASEMENTS", true_color=colors.rgb2int((255, 165, 0)),
linetype="DASHDOT", lineweight=18)
self.doc.layers.add(name="BUILDABLE", color=colors.GRAY, linetype="DASHDOT", lineweight=18)
def setup_route_layers(self):
self.doc.layers.add(name="GRID", color=colors.BLACK)
self.doc.layers.add(name="F-GRID", color=colors.YELLOW, linetype="DASHDOT")
self.doc.layers.add(name="TEXT", color=colors.BLUE)
self.doc.layers.add(name="PROFILE", color=colors.RED)
# plan view (horizontal alignment)
self.doc.layers.add(name="ALIGNMENT", color=colors.RED, linetype="DASHDOT", lineweight=35)
self.doc.layers.add(name="ROW", color=colors.BLACK, linetype="DASHED", lineweight=18)
self.doc.layers.add(name="STATIONS", color=colors.BLUE, lineweight=13)
def setup_font(self, font_name: str = "Times New Roman"):
self.doc.styles.add("SURVEY_TEXT", font=f"{font_name}.ttf")
def setup_beacon_style(self, type_: str = "box", size: float = 1.0):
size = size * self.scale
block = self.doc.blocks.new(name="BEACON_POINT")
radius = size * 0.2 # inner hatch radius
half = size / 2
if type_ == "circle":
block.add_circle((0, 0), radius=size * 0.5)
elif type_ == "box":
block.add_lwpolyline(
[(-half, -half), (half, -half), (half, half), (-half, half)],
close=True,
)
elif type_ == "none":
return
# Hatched inner circle shared by all visible styles
hatch = block.add_hatch(color=7)
path = hatch.paths.add_edge_path()
path.add_arc((0, 0), radius=radius, start_angle=0, end_angle=360)
def setup_topo_point_style(self, size: float = 1.0):
size = size * self.scale
block = self.doc.blocks.new(name="TOPO_POINT")
# cross with a colored point at the center
block.add_line((-size, -size), (size, size))
block.add_line((-size, size), (size, -size))
block.add_point((0, 0), dxfattribs={"true_color": colors.rgb2int((205, 105, 40))})
# ------------------------------------------------------------------
# Drawing primitives
# ------------------------------------------------------------------
def draw_beacon(self, x: float, y: float, z: float = 0,
text_height: float = 1.0, extent: float = 1000, label: Optional[str] = None):
"""Add a beacon point with an optional label offset from the point."""
x, y, z = x * self.scale, y * self.scale, z * self.scale
text_height = text_height * self.scale
self.msp.add_blockref("BEACON_POINT", (x, y, z), dxfattribs={"layer": "BEACONS"})
if label is not None:
offset = self.scale * extent * 0.01
self.msp.add_text(
label,
dxfattribs={"layer": "LABELS", "height": text_height, "style": "SURVEY_TEXT"},
).set_placement((x + offset, y + offset))
def add_parcel(self, points: List[Tuple[float, float]]):
points = [(x * self.scale, y * self.scale) for x, y, *_ in points]
self.msp.add_lwpolyline(points, close=True, dxfattribs={"layer": "PARCELS"})
def add_boundary(self, points: List[Tuple[float, float]]):
points = [(x * self.scale, y * self.scale) for x, y, *_ in points]
self.msp.add_lwpolyline(points, close=True, dxfattribs={"layer": "BOUNDARY"})
def add_buildable(self, points: List[Tuple[float, float]]):
points = [(x * self.scale, y * self.scale) for x, y, *_ in points]
self.msp.add_lwpolyline(points, close=True, dxfattribs={"layer": "BUILDABLE"})
def add_road_cl(self, points: List[Tuple[float, float]]):
points = [(x * self.scale, y * self.scale) for x, y, *_ in points]
self.msp.add_lwpolyline(points, dxfattribs={"layer": "ROADS_CL"})
def add_road(self, points: List[Tuple[float, float]]):
points = [(x * self.scale, y * self.scale) for x, y, *_ in points]
self.msp.add_lwpolyline(points, dxfattribs={"layer": "ROADS"})
def add_polyline(self, points: List[Tuple[float, float]], layer: str, close: bool = False):
"""Add a generic 2D polyline on the given layer."""
points = [(x * self.scale, y * self.scale) for x, y, *_ in points]
self.msp.add_lwpolyline(points, close=close, dxfattribs={"layer": layer})
def add_greenspace(self, points: List[Tuple[float, float]]):
points = [(x * self.scale, y * self.scale) for x, y, *_ in points]
self.msp.add_lwpolyline(points, close=True, dxfattribs={"layer": "GREEN_SPACE"})
hatch = self.msp.add_hatch(dxfattribs={"layer": "GREEN_SPACE"})
hatch.set_pattern_fill("ANSI31", scale=0.5)
hatch.paths.add_polyline_path(points, is_closed=True)
def add_label(self, text: str, x: float, y: float, angle: float = 0.0, height: float = 1.0,
alignment=TextEntityAlignment.MIDDLE_CENTER):
"""Add single-line text on the LABELS layer (centered by default)."""
x, y = x * self.scale, y * self.scale
height = height * self.scale
self.msp.add_text(
text,
dxfattribs={
"layer": "LABELS",
"height": height,
"style": "SURVEY_TEXT",
"rotation": angle,
},
).set_placement((x, y), align=alignment)
def add_mtext_label(self, text: str, x: float, y: float, angle: float = 0.0,
height: float = 1.0, layer: str = "LABELS"):
"""Add a single-line MText label centered at (x, y)."""
x, y = x * self.scale, y * self.scale
height = height * self.scale
mtext = self.msp.add_mtext(text, dxfattribs={
"layer": layer,
"style": "SURVEY_TEXT",
"char_height": height,
})
mtext.set_location(
(x, y),
rotation=angle,
attachment_point=ezdxf.enums.MTextEntityAlignment.MIDDLE_CENTER,
)
return mtext
def add_split_mtext_label(self, left: str, right: str, x: float, y: float,
angle: float = 0.0, height: float = 1.0, span: float = 0.0,
layer: str = "LABELS"):
"""Single MText label whose ``left`` and ``right`` parts are padded
apart with spaces so the whole label spans roughly ``span`` model
units, centered at (x, y)."""
font_file = "txt"
if "SURVEY_TEXT" in self.doc.styles:
font_file = self.doc.styles.get("SURVEY_TEXT").dxf.font or "txt"
font = self._measurement_font(font_file, height * self.scale)
text_width = font.text_width(left + right)
space_width = max(font.text_width("| |") - font.text_width("||"), 1e-9)
spaces = max(1, round((span * self.scale - text_width) / space_width))
return self.add_mtext_label(f"{left}{' ' * spaces}{right}", x, y,
angle=angle, height=height, layer=layer)
def add_text(self, text: str, x: float, y: float, height: float = 1.0,
rotation: float = 0.0, alignment=TextEntityAlignment.TOP_LEFT):
"""Add single-line text on the TEXT layer."""
x, y = x * self.scale, y * self.scale
height = height * self.scale
self.msp.add_text(
text,
dxfattribs={
"layer": "TEXT",
"height": height,
"style": "SURVEY_TEXT",
"rotation": rotation,
},
).set_placement((x, y), align=alignment)
# ------------------------------------------------------------------
# North arrow
# ------------------------------------------------------------------
def draw_north_arrow(self, x: float, y: float, height: float = 100.0, rotation: float = 0.0):
"""Draw the north arrow; ``rotation`` (CCW degrees) supports rotated
plan views where sheet-up is not true north."""
height = height * self.scale
x, y = x * self.scale, y * self.scale
if "NORTH_ARROW" not in self.doc.blocks:
block = self.doc.blocks.new(name="NORTH_ARROW")
arrow_size = height * 0.4
bulge = math.tan(math.radians(250) / 4) * -1
block.add_lwpolyline(
[(0, 0), (0, height), (-arrow_size / 2, height - arrow_size, bulge),
(-arrow_size / 2, height - (arrow_size * 2))],
format="xyb", dxfattribs={"color": 5},
)
block.add_text(
"U", dxfattribs={"height": height * 0.2, "color": 5, "style": "SURVEY_TEXT"},
).set_placement((-height * 0.3, height - (height * 0.2)),
align=TextEntityAlignment.MIDDLE_CENTER)
block.add_text(
"N", dxfattribs={"height": height * 0.2, "color": 5, "style": "SURVEY_TEXT"},
).set_placement((height * 0.2, height - (height * 0.2)),
align=TextEntityAlignment.MIDDLE_CENTER)
self.msp.add_blockref("NORTH_ARROW", (x, y), dxfattribs={"rotation": rotation})
def add_north_arrow_label(self, start: Tuple[float, float], stop: Tuple[float, float],
label: str = "", height: float = 100.0):
"""Draw a grid reference line with its label sitting just clear of it,
offset perpendicular to the line by a fraction of the text height."""
height = height * self.scale
x, y = start[0] * self.scale, start[1] * self.scale
stop_x, stop_y = stop[0] * self.scale, stop[1] * self.scale
self.msp.add_line((x, y), (stop_x, stop_y), dxfattribs={"color": 5})
if label:
angle = math.atan2(stop_y - y, stop_x - x)
ux, uy = math.cos(angle), math.sin(angle) # along the line
nx, ny = -uy, ux # perpendicular (left of direction)
placement = (
x + ux * (height * 0.5) + nx * (height * 0.35),
y + uy * (height * 0.5) + ny * (height * 0.35),
)
self.msp.add_text(
label,
dxfattribs={
"height": height,
"color": 5,
"style": "SURVEY_TEXT",
"rotation": math.degrees(angle),
},
).set_placement(placement, align=TextEntityAlignment.BOTTOM_LEFT)
def draw_north_arrow_cross(self, x: float, y: float, length: float = 100.0):
x, y = x * self.scale, y * self.scale
length = length * self.scale
half = length / 2
self.msp.add_line((x - half, y), (x + half, y), dxfattribs={"color": 5})
self.msp.add_line((x, y - half), (x, y + half), dxfattribs={"color": 5})
# ------------------------------------------------------------------
# Graphical scale & title block
# ------------------------------------------------------------------
def draw_graphical_scale(self, x: float, y: float, length: float = 1000.0):
"""Draw a scale bar around ``length`` model-metres long at (x, y).
The bar has 5 intervals; the interval is snapped to a 'nice' ground
distance so the tick labels reflect true distances on the plan.
"""
# Snap the interval to a nice ground distance and rebuild the length
interval_m = nice_round(length / 5)
length = interval_m * 5
X, Y = x * self.scale, y * self.scale
length = length * self.scale
height = length * 0.05 # bar height, 5% of length
interval = length / 5
block_name = f"GRAPHICAL_SCALE_{len(self.doc.blocks)}"
block = self.doc.blocks.new(name=block_name)
# outer rectangle and middle line
block.add_lwpolyline(
[(0, 0), (length, 0), (length, height), (0, height)],
close=True, dxfattribs={"color": 7},
)
block.add_line((0, height / 2), (length, height / 2), dxfattribs={"color": 7})
def label_for(i: int) -> str:
# Bar starts one interval before zero (the subdivided cell).
return f"{(i - 1) * interval_m:g}"
to_shade = "up"
for i in range(6):
tick_x = i * interval
block.add_line((tick_x, 0), (tick_x, height * 1.5), dxfattribs={"color": 7})
text = label_for(i)
alignment = TextEntityAlignment.TOP_CENTER
if i == 0:
text = f"Meters {interval_m:g}"
alignment = TextEntityAlignment.TOP_RIGHT
if i == 5:
text = f"{label_for(i)} Meters"
alignment = TextEntityAlignment.TOP_LEFT
block.add_text(
text,
dxfattribs={"height": height * 0.5, "color": 7, "style": "SURVEY_TEXT"},
).set_placement((tick_x, height * 2.3), align=alignment)
if i == 5:
continue
# Alternate shading of upper/lower halves; the first cell is
# subdivided into two half-interval cells.
sub_intervals = 2 if i == 0 else 1
sub_width = interval / sub_intervals
for j in range(sub_intervals):
sub_x = tick_x + j * sub_width
if to_shade == "up":
corners = [(sub_x, height / 2), (sub_x + sub_width, height / 2),
(sub_x + sub_width, height), (sub_x, height)]
to_shade = "down"
else:
corners = [(sub_x, 0), (sub_x + sub_width, 0),
(sub_x + sub_width, height / 2), (sub_x, height / 2)]
to_shade = "up"
hatch = block.add_hatch(color=7)
hatch.paths.add_polyline_path(corners)
return self.msp.add_blockref(block_name, (X, Y), dxfattribs={"layer": "TITLE_BLOCK"})
def draw_title_block(self, text: str, x: float, y: float, width: float,
title_height: float = 1.0, graphical_scale_length: float = 1000.0,
origin: str = "", area: str = ""):
x, y = x * self.scale, y * self.scale
title_height = title_height * self.scale
width = width * self.scale
graphical_scale_length = graphical_scale_length * self.scale
block = self.doc.blocks.new(name="TITLE_BLOCK")
title_mtext = block.add_mtext(
text=f"{MTextEditor.UNDERLINE_START}{text}{MTextEditor.UNDERLINE_STOP}",
dxfattribs={"style": "SURVEY_TEXT"},
)
title_mtext.dxf.attachment_point = ezdxf.enums.MTextEntityAlignment.TOP_CENTER
title_mtext.dxf.char_height = title_height
title_mtext.dxf.width = width
title_ref = self.msp.add_blockref("TITLE_BLOCK", (x, y), dxfattribs={"layer": "TITLE_BLOCK"})
title_box = bbox.extents(title_ref.virtual_entities())
title_min_y = title_box.extmin.y
title_min_x = title_box.extmin.x
title_max_x = title_box.extmax.x
# draw_graphical_scale snaps the bar to a nice round interval, so
# center using the length that will actually be drawn.
graphical_scale_length = nice_round((graphical_scale_length / self.scale) / 5) * 5 * self.scale
title_center_x = (title_min_x + title_max_x) / 2
graphical_x = title_center_x - (graphical_scale_length / 2)
# graphical scale below the title
graphical_ref = self.draw_graphical_scale(
graphical_x / self.scale,
(title_min_y - (graphical_scale_length * 0.05 * 3)) / self.scale,
graphical_scale_length / self.scale,
)
graphical_box = bbox.extents(graphical_ref.virtual_entities())
graphical_min_y = graphical_box.extmin.y
# area and origin lines below the graphical scale
lines = []
if area:
lines.append(rf"\C1;{area}")
if origin:
lines.append(rf"\C5;{origin}")
if not lines:
return
origin_mtext = self.msp.add_mtext(
text=f"{MTextEditor.UNDERLINE_START}{MTextEditor.NEW_LINE.join(lines)}{MTextEditor.UNDERLINE_STOP}",
dxfattribs={"style": "SURVEY_TEXT"},
)
origin_mtext.dxf.attachment_point = ezdxf.enums.MTextEntityAlignment.TOP_CENTER
origin_mtext.dxf.char_height = title_height
origin_mtext.dxf.width = width
origin_mtext.set_location((x, graphical_min_y - ((graphical_scale_length * 0.05) / 3)))
# ------------------------------------------------------------------
# Frames & footers
# ------------------------------------------------------------------
def draw_footer_box(self, text: str, min_x, min_y, max_x, max_y,
font_size: float = 1.0, top_inset: float = 0.0):
"""Draw a footer rectangle with MText content inside.
The text height is clamped so the estimated number of wrapped lines
always fits inside the box instead of overflowing across the frame.
``top_inset`` reserves space below the box's top edge (e.g. for the
plan number) before the footer text starts.
"""
font_size = font_size * self.scale
top_inset = top_inset * self.scale
min_x, min_y = min_x * self.scale, min_y * self.scale
max_x, max_y = max_x * self.scale, max_y * self.scale
box_width = max_x - min_x
box_height = max_y - min_y
self.msp.add_lwpolyline(
[(min_x, min_y), (max_x, min_y), (max_x, max_y), (min_x, max_y)],
close=True, dxfattribs={"layer": "FOOTER"},
)
if not text.strip():
return
# Estimate wrapped line count from the plain text and shrink the
# font until it fits (line spacing ~1.67x char height in MText).
segments = text.split(MTextEditor.NEW_LINE)
plain = [re.sub(r"\\f[^;]*;|\\[A-Za-z]|[{}]", "", seg) for seg in segments]
height = font_size
for _ in range(4):
capacity = max((box_width * 0.9) / (0.55 * height), 1.0)
lines = sum(max(1, math.ceil(len(seg) / capacity)) for seg in plain)
needed = lines * height * 1.67
allowed = max(box_height * 0.85 - top_inset, box_height * 0.1)
if needed <= allowed:
break
height *= allowed / needed
footer_mtext = self.msp.add_mtext(
text=text,
dxfattribs={"layer": "FOOTER", "style": "SURVEY_TEXT"},
)
footer_mtext.dxf.attachment_point = ezdxf.enums.MTextEntityAlignment.TOP_LEFT
footer_mtext.dxf.width = box_width * 0.9
footer_mtext.dxf.char_height = height
# top-left corner with some padding
footer_mtext.set_location(
(min_x + (0.05 * box_width), max_y - (0.1 * box_height) - top_inset)
)
def draw_frame(self, min_x, min_y, max_x, max_y):
"""Draw a rectangular frame given min and max coordinates."""
min_x, min_y = min_x * self.scale, min_y * self.scale
max_x, max_y = max_x * self.scale, max_y * self.scale
self.msp.add_lwpolyline(
[(min_x, min_y), (max_x, min_y), (max_x, max_y), (min_x, max_y)],
close=True, dxfattribs={"layer": "FRAME"},
)
def draw_table(self, x: float, y: float, rows: List[List[str]],
col_widths: List[float], row_height: float,
text_height: float = 1.0, layer: str = "TEXT"):
"""Draw a simple grid table with (x, y) as its top-left corner.
``rows`` is a list of rows; each row is a list of cell strings.
``col_widths`` and ``row_height`` are in model units.
"""
x, y = x * self.scale, y * self.scale
col_widths = [w * self.scale for w in col_widths]
row_height = row_height * self.scale
text_height = text_height * self.scale
table_width = sum(col_widths)
table_height = row_height * len(rows)
# outer border
self.msp.add_lwpolyline(
[(x, y), (x + table_width, y), (x + table_width, y - table_height), (x, y - table_height)],
close=True, dxfattribs={"layer": layer},
)
# horizontal lines
for i in range(1, len(rows)):
line_y = y - i * row_height
self.msp.add_line((x, line_y), (x + table_width, line_y), dxfattribs={"layer": layer})
# vertical lines
cx = x
for width in col_widths[:-1]:
cx += width
self.msp.add_line((cx, y), (cx, y - table_height), dxfattribs={"layer": layer})
# cell text (left-aligned, vertically centered)
padding = text_height * 0.4
for i, row in enumerate(rows):
cell_x = x
cell_y = y - (i + 0.5) * row_height
for j, cell in enumerate(row):
self.msp.add_text(
str(cell),
dxfattribs={
"layer": layer,
"height": text_height,
"style": "SURVEY_TEXT",
},
).set_placement((cell_x + padding, cell_y), align=TextEntityAlignment.MIDDLE_LEFT)
cell_x += col_widths[j]
# ------------------------------------------------------------------
# Topographic primitives
# ------------------------------------------------------------------
def draw_topo_point(self, x: float, y: float, z: float = 0,
label: Optional[str] = None, text_height: float = 1.0):
x, y, z = x * self.scale, y * self.scale, z * self.scale
text_height = text_height * self.scale
self.msp.add_blockref("TOPO_POINT", (x, y, z), dxfattribs={"layer": "SPOT_HEIGHTS"})
if label is not None:
offset = 0.25 * text_height
self.msp.add_text(
label,
dxfattribs={
"layer": "SPOT_HEIGHTS",
"height": text_height,
"style": "SURVEY_TEXT",
"color": 7,
},
).set_placement((x + offset, y + offset, z + offset))
def _scale3d(self, points: List[Tuple[float, float, float]]):
return [(x * self.scale, y * self.scale, z * self.scale) for x, y, z in points]
def add_tin_mesh(self, points: List[Tuple[float, float, float]]):
self.msp.add_polyline3d(self._scale3d(points), dxfattribs={"layer": "TIN_MESH"})
def add_grid_mesh(self, points: List[Tuple[float, float, float]]):
self.msp.add_polyline3d(self._scale3d(points), dxfattribs={"layer": "GRID_MESH"})
def add_grid_mesh_border(self, points: List[Tuple[float, float, float]]):
self.msp.add_polyline3d(
self._scale3d(points),
dxfattribs={"layer": "GRID_MESH", "lineweight": 25},
)
def add_grid_mesh_label(self, x: float, y: float, z: float, label: str,
text_height: float = 1.0, rotation: float = 0.0):
x, y, z = x * self.scale, y * self.scale, z * self.scale
text_height = text_height * self.scale
self.msp.add_text(label, dxfattribs={
"layer": "GRID_MESH",
"height": text_height,
"style": "SURVEY_TEXT",
"rotation": rotation,
}).set_placement((x, y, z))
def add_3d_contour(self, points: List[Tuple[float, float, float]], layer: str = "CONTOUR_MINOR"):
self.msp.add_polyline3d(self._scale3d(points), dxfattribs={"layer": layer})
def add_spline(self, points: List[Tuple[float, float, float]], layer: str = "CONTOUR_MINOR"):
self.msp.add_spline(self._scale3d(points), degree=3, dxfattribs={"layer": layer})
def add_contour_label(self, x: float, y: float, z: float, label: str, text_height: float = 1.0):
x, y, z = x * self.scale, y * self.scale, z * self.scale
text_height = text_height * self.scale
self.msp.add_text(label, dxfattribs={
"layer": "CONTOUR_LABELS",
"height": text_height,
}).set_placement((x, y, z), align=TextEntityAlignment.MIDDLE_CENTER)
# ------------------------------------------------------------------
# Route (longitudinal profile) primitives
# ------------------------------------------------------------------
def add_grid_line(self, x1: float, y1: float, x2: float, y2: float):
self.msp.add_line(
(x1 * self.scale, y1 * self.scale),
(x2 * self.scale, y2 * self.scale),
dxfattribs={"layer": "GRID"},
)
def add_f_grid_line(self, x1: float, y1: float, x2: float, y2: float):
self.msp.add_line(
(x1 * self.scale, y1 * self.scale),
(x2 * self.scale, y2 * self.scale),
dxfattribs={"layer": "F-GRID"},
)
def add_profile(self, points: List[Tuple[float, float]]):
points = [(x * self.scale, y * self.scale) for x, y in points]
self.msp.add_spline(points, dxfattribs={"layer": "PROFILE"})
# ------------------------------------------------------------------
# Layer visibility & output
# ------------------------------------------------------------------
def toggle_layer(self, layer: str, state: bool):
layer_entity = self.doc.layers.get(layer)
if state:
layer_entity.on()
else:
layer_entity.off()
def _measurement_font(self, font_name: str, cap_height: float):
"""Font used to estimate text extents, cached per (font, height).
Falls back to a metric-compatible substitute when the style's font is
not installed, so estimated widths stay close to what CAD software
with the real font will render.
"""
cache = getattr(self, "_font_cache", None)
if cache is None:
cache = self._font_cache = {}
key = (font_name, round(cap_height, 9))
font = cache.get(key)
if font is None:
name = font_name
face = ezfonts.font_manager.get_font_face(name)
stem = os.path.splitext(os.path.basename(font_name))[0].lower()
if face is not None and stem not in face.family.lower():
substitute = MEASUREMENT_FONT_SUBSTITUTES.get(stem)
if substitute is not None:
sub_face = ezfonts.font_manager.get_font_face(substitute)
if sub_face is not None and "liberation" in sub_face.family.lower():
name = substitute
font = cache[key] = ezfonts.make_font(name, cap_height)
return font
def fix_justified_text_insert_points(self):
"""Recompute the baseline-left insertion point of justified TEXT.
AutoCAD draws DWG TEXT glyphs starting at the insertion point
(group 10) and keeps the alignment point (group 11) as editing
metadata, while the ODA converter copies both points through
unchanged. ezdxf leaves the insertion point equal to the alignment
point (the DXF reference allows this because DXF readers must use
the alignment point), so every centered/right/top justified label
rendered as left/baseline justified once converted to DWG.
"""
spaces = [self.msp] + [block for block in self.doc.blocks]
for space in spaces:
for text in space.query("TEXT"):
halign = text.dxf.halign
valign = text.dxf.valign
if (halign == 0 and valign == 0) or halign in (3, 5):
# baseline-left already, or ALIGNED/FIT dual-point modes
continue
if not text.dxf.hasattr("align_point"):
continue
style_name = text.dxf.style
font_file = "txt"
if style_name in self.doc.styles:
font_file = self.doc.styles.get(style_name).dxf.font or "txt"
cap_height = text.dxf.height
font = self._measurement_font(font_file, cap_height)
width = font.text_width(text.dxf.text) * text.dxf.width
m = font.measurements
dx = 0.0
if halign in (1, 4): # center / middle
dx = -width / 2
elif halign == 2: # right
dx = -width
if halign == 4: # MIDDLE: centered on the full glyph extent
dy = (m.descender_height - m.cap_height) / 2
elif valign == 1: # bottom (descender line)
dy = m.descender_height
elif valign == 2: # middle of capitals
dy = -m.cap_height / 2
elif valign == 3: # top of capitals
dy = -m.cap_height
else: # baseline
dy = 0.0
rot = math.radians(text.dxf.rotation)
cos_r, sin_r = math.cos(rot), math.sin(rot)
align = text.dxf.align_point
text.dxf.insert = (
align.x + dx * cos_r - dy * sin_r,
align.y + dx * sin_r + dy * cos_r,
align.z,
)
def get_filename(self) -> str:
plan_name = self.plan_name.lower()
plan_name = re.sub(r"\s+", "_", plan_name)
plan_name = re.sub(r"[^a-z0-9._-]", "", plan_name)
plan_name = re.sub(r"_+", "_", plan_name)
return f"{plan_name}_{datetime.now().strftime('%Y%m%d_%H%M%S')}_{uuid.uuid4().hex[:6]}"
def save_dxf(self, filepath: Optional[str] = None):
if not filepath:
filepath = f"{self.get_filename()}.dxf"
self.fix_justified_text_insert_points()
self.doc.saveas(filepath)
def save_pdf(self, filepath: Optional[str] = None, paper_size: str = "A4", orientation: str = "portrait"):
width, height = PAPER_SIZES.get(paper_size.upper(), PAPER_SIZES["A4"])
if orientation.lower() == "landscape":
width, height = height, width
context = RenderContext(self.doc)
backend = pymupdf.PyMuPdfBackend()
cfg = config.Configuration(background_policy=config.BackgroundPolicy.WHITE)
frontend = Frontend(context, backend, config=cfg)
frontend.draw_layout(self.msp)
page = layout.Page(width, height, layout.Units.mm, margins=layout.Margins.all(20))
if not filepath:
filepath = f"{self.get_filename()}.pdf"
pdf_bytes = backend.get_pdf_bytes(page)
with open(filepath, "wb") as f:
f.write(pdf_bytes)
def save_dwg(self, dxf_filepath: str, filepath: Optional[str] = None):
"""Convert a saved DXF to DWG using the ODA File Converter."""
if not filepath:
filepath = f"{self.get_filename()}.dwg"
odafc.convert(dxf_filepath, filepath, version=self.dxf_version)
def save(self, paper_size: str = "A4", orientation: str = "portrait",
extra_files: Optional[dict] = None) -> str:
"""Export DXF + DWG + PDF, zip them, and upload the archive.
``extra_files`` maps file names to text content and is bundled into
the ZIP as well (e.g. setting-out coordinate CSVs).
Returns the public URL of the uploaded ZIP archive.
"""
with tempfile.TemporaryDirectory() as tmpdir:
filename = self.get_filename()
dxf_path = os.path.join(tmpdir, f"{filename}.dxf")
dwg_path = os.path.join(tmpdir, f"{filename}.dwg")
pdf_path = os.path.join(tmpdir, f"{filename}.pdf")
zip_path = os.path.join(tmpdir, f"{filename}.zip")
self.save_dxf(dxf_path)
self.save_dwg(dxf_path, dwg_path)
self.save_pdf(pdf_path, paper_size=paper_size, orientation=orientation)
with zipfile.ZipFile(zip_path, "w") as zipf:
zipf.write(dxf_path, os.path.basename(dxf_path))
zipf.write(dwg_path, os.path.basename(dwg_path))
zipf.write(pdf_path, os.path.basename(pdf_path))
for name, content in (extra_files or {}).items():
zipf.writestr(name, content)
url = upload_file(zip_path, folder="survey_plans", file_name=filename)
if url is None:
raise RuntimeError("Failed to upload generated plan archive")
return url