-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDTM Pro New.py
More file actions
6118 lines (5354 loc) · 288 KB
/
DTM Pro New.py
File metadata and controls
6118 lines (5354 loc) · 288 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
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
# -*- coding: utf-8 -*-
# DTM Pro 2025 Final (Integraded Edition)
# 包含 实验二、三、四、五、七、八 的功能整合
import sys
import os
import re
import copy
import math # 导入数学库,用于新功能
import numpy as np
import pandas as pd
from datetime import datetime
from scipy.spatial import Delaunay
from matplotlib.tri import LinearTriInterpolator, Triangulation
from docx import Document
from docx.shared import Inches, Pt, Cm, RGBColor
from docx.enum.text import WD_ALIGN_PARAGRAPH
import requests
import io
import rasterio
from rasterio.transform import from_origin
import rasterstats
from PyQt5.QtWidgets import (
QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QGridLayout,
QPushButton, QLabel, QFileDialog, QMessageBox, QSplitter, QGroupBox, QComboBox,
QDialog, QLineEdit, QScrollArea, QSizePolicy, QTextEdit,
QInputDialog # --- NEW --- 导入 QInputDialog
)
from PyQt5.QtCore import Qt, QObject, QThread, pyqtSignal, pyqtSlot, QPointF, QRectF, QSize,QTimer
from PyQt5.QtGui import (
QDoubleValidator, QPainter, QPen, QColor, QBrush, QFont, QPolygonF, QPixmap, QGuiApplication, QIcon
)
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import matplotlib # For colormap access
import geopandas as gpd # --- 新增:GIS 矢量数据处理 ---
# 应用元信息
APP_NAME = "DTM Pro — Terrain Analysis Suite (Integrated)"
APP_NAME_CN = "地形大师 (集成版)"
APP_VERSION = "1.2.1" # 更新版本号(修正土方量输入 & cmap 警告)
# -------------------- 全局样式 --------------------
plt.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei', 'Arial']
plt.rcParams['axes.unicode_minus'] = False
plt.style.use('dark_background')
MODERN_STYLESHEET = """
QWidget {
background-color: #2E2E2E;
color: #F0F0F0;
font-family: 'Segoe UI', 'SimHei';
font-size: 10pt;
}
QPushButton {
background-color: #555555;
color: #FFFFFF;
border: 1px solid #666666;
border-radius: 4px;
padding: 6px 10px;
}
QPushButton:hover { background-color: #6a6a6a; }
QPushButton:pressed { background-color: #4CAF50; }
QGroupBox {
font-weight: bold;
border: 1px solid #4A4A4A;
border-radius: 6px;
margin-top: 16px;
}
QGroupBox::title {
subcontrol-origin: margin;
subcontrol-position: top center;
padding: 3px 8px;
margin-top: 4px;
background-color: transparent;
}
QSplitter::handle { background-color: #4A4A4A; }
QSplitter::handle:hover { background-color: #6a6a6a; }
QScrollArea { border: none; }
QLineEdit {
background-color: #3C3C3C;
border: 1px solid #555;
border-radius: 3px;
padding: 4px;
}
QTextEdit {
background-color: #252525;
border: 1px solid #555;
border-radius: 3px;
color: #E0E0E0;
}
QComboBox {
background-color: #3C3C3C;
border: 1px solid #555;
border-radius: 3px;
padding: 4px;
}
QLabel {
background-color: transparent;
}
"""
CAD_CLASSIC_STYLESHEET = """
QMainWindow, QWidget {
background-color: #D2D2D2;
color: #111111;
font-family: '%s', 'Microsoft YaHei', 'SimHei', 'Segoe UI';
font-size: 10pt;
}
QGroupBox {
font-weight: bold;
border: 1px solid #8A8A8A;
border-radius: 2px;
margin-top: 16px;
}
QGroupBox::title {
subcontrol-origin: margin;
subcontrol-position: top left;
padding: 2px 6px;
margin-top: 4px;
background-color: #D2D2D2;
}
QPushButton {
background-color: #E6E6E6;
color: #111111;
border: 1px solid #8A8A8A;
border-radius: 2px;
padding: 6px 10px;
}
QPushButton:hover { background-color: #F2F2F2; }
QPushButton:pressed { background-color: #CFCFCF; }
QLineEdit, QComboBox, QTextEdit {
background-color: #F7F7F7;
color: #111111;
border: 1px solid #8A8A8A;
border-radius: 2px;
padding: 4px;
}
QSplitter::handle { background-color: #9A9A9A; height: 3px; }
QSplitter::handle:hover { background-color: #B0B0B0; }
QLabel { background-color: transparent; color: #111111; }
QScrollArea { border: none; }
QToolTip {
background-color: #F7F7F7;
color: #111111;
border: 1px solid #8A8A8A;
}
"""
CAD_2024_STYLESHEET = """
QMainWindow, QWidget {
background-color: #1E1F22;
color: #E6E6E6;
font-family: '%s', 'Microsoft YaHei', 'SimHei', 'Segoe UI';
font-size: 10pt;
}
QGroupBox {
font-weight: bold;
border: 1px solid #3B3D40;
border-radius: 2px;
margin-top: 16px;
}
QGroupBox::title {
subcontrol-origin: margin;
subcontrol-position: top left;
padding: 2px 6px;
margin-top: 4px;
background-color: #1E1F22;
color: #E6E6E6;
}
QPushButton {
background-color: #2B2D31;
color: #E6E6E6;
border: 1px solid #3B3D40;
border-radius: 2px;
padding: 6px 10px;
}
QPushButton:hover { background-color: #3A3D43; }
QPushButton:pressed { background-color: #1F2328; }
QLineEdit, QComboBox, QTextEdit {
background-color: #2B2D31;
color: #E6E6E6;
border: 1px solid #3B3D40;
border-radius: 2px;
padding: 4px;
}
QSplitter::handle { background-color: #3D4045; height: 3px; }
QSplitter::handle:hover { background-color: #4A4E55; }
QLabel { background-color: transparent; color: #E6E6E6; }
QScrollArea { border: none; }
QToolTip {
background-color: #2B2D31;
color: #E6E6E6;
border: 1px solid #3B3D40;
}
"""
def build_cad_stylesheet(theme_name, font_family):
font_name = font_family.strip() if font_family else "Microsoft YaHei"
if theme_name == 'cad_classic':
return CAD_CLASSIC_STYLESHEET % font_name
return CAD_2024_STYLESHEET % font_name
# -------------------- 自定义工具栏(中文友好) --------------------
class ChineseNavigationToolbar(NavigationToolbar2QT):
toolitems = [
('Home', 'Reset original view', 'home', 'home'),
('Back', 'Go back', 'back', 'back'),
('Forward', 'Go forward', 'forward', 'forward'),
(None, None, None, None),
('Pan', 'Pan/Zoom', 'move', 'pan'),
('Zoom', 'Zoom to rect', 'zoom_to_rect', 'zoom'),
(None, None, None, None),
('Subplots', 'Configure subplots', 'subplots', 'configure_subplots'),
('Save', 'Save figure', 'filesave', 'save_figure'),
]
def _init_toolbar(self):
self.actions = {}
from PyQt5.QtWidgets import QSizePolicy
for text, tooltip_text, image_file, callback in self.toolitems:
if text is None:
self.addSeparator()
continue
icon = self.get_icon(image_file)
a = self.addAction(icon, text, getattr(self, callback))
self.actions[callback] = a
if text in ['Pan', 'Zoom']:
a.setCheckable(True)
a.setToolTip(tooltip_text)
self.addSeparator()
self.locLabel = QLabel("", self)
self.locLabel.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
self.locLabel.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
self.addWidget(self.locLabel)
# -------------------- Matplotlib 画布 --------------------
class MplCanvas(FigureCanvas):
def __init__(self, parent=None, is_3d=False):
fig = Figure() # 移除 facecolor='#2E2E2E'
self.figure = fig
self.is_3d = is_3d
self.colorbar_axes = None
if is_3d:
self.axes = fig.add_subplot(111, projection='3d') # 移除 facecolor
self.axes.azim = -70
self.axes.elev = 35
self.default_azim = self.axes.azim
self.default_elev = self.axes.elev
self.cbar_position_rect = [0.80, 0.25, 0.03, 0.50]
fig.subplots_adjust(left=0.0, right=0.75, bottom=0.0, top=1.0)
else:
self.axes = fig.add_subplot(111) # 移除 facecolor
fig.tight_layout(pad=3.0)
# 默认设置为深色主题
self.set_theme('dark')
super().__init__(fig)
def set_theme(self, theme_name):
"""为画布设置深色或玻璃主题。"""
if theme_name == 'glass':
fig_color = 'none' # 透明
ax_color = 'none' # 透明
tick_color = 'white' # 刻度设为白色
elif theme_name == 'light':
fig_color = '#EDEDED'
ax_color = '#F7F7F7'
tick_color = '#1A1A1A'
else: # 默认 'dark'
fig_color = '#2E2E2E'
ax_color = '#2E2E2E'
tick_color = 'white'
try:
self.figure.set_facecolor(fig_color)
self.axes.set_facecolor(ax_color)
# 更新刻度和标签颜色
self.axes.tick_params(colors=tick_color, labelcolor=tick_color)
for spine in self.axes.spines.values():
if theme_name == 'glass':
spine.set_color(tick_color)
elif theme_name == 'light':
spine.set_color('#888888')
else:
spine.set_color('#888888') # 深色主题用中性边框
# 3D 画布有 Z 轴
if self.is_3d:
try:
self.axes.w_xaxis.line.set_color(tick_color)
self.axes.w_yaxis.line.set_color(tick_color)
self.axes.w_zaxis.line.set_color(tick_color)
except:
pass
# 更新已有的色条(如果存在)
if self.colorbar_axes and hasattr(self.colorbar_axes, 'ax'):
cbar = self.colorbar_axes.ax.figure.colorbar
if cbar:
cbar.ax.yaxis.set_tick_params(color=tick_color, labelcolor=tick_color)
cbar.ax.spines['right'].set_color(tick_color)
cbar.ax.spines['left'].set_color(tick_color)
cbar.ax.spines['top'].set_color(tick_color)
cbar.ax.spines['bottom'].set_color(tick_color)
self.draw_idle()
except Exception as e:
print(f"Error setting canvas theme: {e}")
def wheelEvent(self, event):
"""把 Qt 的 wheel 事件转成程序期望的 scroll_event 调用,优先调用父窗口的 on_scroll。"""
try:
delta = 0
try:
ad = event.angleDelta()
delta = ad.y() if hasattr(ad, 'y') else int(ad)
except Exception:
try:
delta = event.delta()
except Exception:
delta = 0
class _FakeEvent:
pass
fe = _FakeEvent()
fe.inaxes = getattr(self, 'axes', None)
fe.guiEvent = event
fe.step = 1 if delta > 0 else -1
# Let parent handle it if possible
parent = self.parent()
if parent is not None and hasattr(parent, 'on_scroll'):
try:
parent.on_scroll(fe)
event.accept()
return
except Exception:
pass
except Exception:
pass
# fallback to default
super().wheelEvent(event)
class _ViewshedWorker(QObject):
"""
在后台线程中计算视域分析
"""
finished = pyqtSignal(object) # (visibility_grid)
progress = pyqtSignal(int)
error = pyqtSignal(str)
def __init__(self, obs_pos, grid_x, grid_y, grid_z, spacing, parent=None):
super().__init__(parent)
self.obs_x, self.obs_y, self.obs_z = obs_pos
self.grid_x = grid_x
self.grid_y = grid_y
self.grid_z = grid_z
self.spacing = max(spacing, 1e-6) # 避免除零
self._cancel = False
def cancel(self):
self._cancel = True
@pyqtSlot()
def run(self):
try:
ny, nx = self.grid_z.shape
visibility_grid = np.zeros((ny, nx), dtype=bool)
# 找到观察者在格网中的索引
obs_ix = np.clip(np.round((self.obs_x - self.grid_x[0]) / self.spacing), 0, nx - 1).astype(int)
obs_iy = np.clip(np.round((self.obs_y - self.grid_y[0]) / self.spacing), 0, ny - 1).astype(int)
# 遍历所有目标单元格
for iy in range(ny):
if self._cancel:
self.error.emit('cancelled')
return
for ix in range(nx):
if ix == obs_ix and iy == obs_iy:
visibility_grid[iy, ix] = True # 观察点自身总是可见的
continue
target_x = self.grid_x[ix]
target_y = self.grid_y[iy]
target_z = self.grid_z[iy, ix]
if np.isnan(target_z):
visibility_grid[iy, ix] = False
continue
# 检查视线
is_visible = self.check_line_of_sight(target_x, target_y, target_z)
visibility_grid[iy, ix] = is_visible
# 更新进度
pct = int(100 * (iy + 1) / ny)
self.progress.emit(pct)
self.finished.emit(visibility_grid)
except Exception as e:
self.error.emit(str(e))
def check_line_of_sight(self, target_x, target_y, target_z):
"""
检查从 (obs_pos) 到 (target_pos) 的视线是否被地形阻挡
"""
# 1. 计算视线向量
dx = target_x - self.obs_x
dy = target_y - self.obs_y
dz = target_z - self.obs_z
# 2. 确定采样步数 (基于最长的 X 或 Y 轴格网距离)
num_steps = int(max(abs(dx), abs(dy)) / self.spacing) + 2
# 3. 沿 2D 视线生成采样点 (不包括起点和终点)
t = np.linspace(0, 1, num_steps)[1:-1] # 截取中间点
if t.size == 0:
return True # 两个点是相邻的,没有中间点
x_line = self.obs_x + dx * t
y_line = self.obs_y + dy * t
# 4. 计算这些点上的“视线高度”
z_line_of_sight = self.obs_z + dz * t
# 5. 计算这些点下方的“地形高度”
# 将采样点的真实坐标转换为格网索引
x_indices = np.clip(np.round((x_line - self.grid_x[0]) / self.spacing), 0, len(self.grid_x) - 1).astype(int)
y_indices = np.clip(np.round((y_line - self.grid_y[0]) / self.spacing), 0, len(self.grid_y) - 1).astype(int)
# 从格网中提取地形高度
terrain_z_under_line = self.grid_z[y_indices, x_indices]
# 6. 检查遮挡
# 检查是否有任何地形高度 (terrain_z) 高于视线高度 (z_line_of_sight)
# 增加一个小的容差 (e.g., 0.1m) 以避免浮点错误
obstruction = terrain_z_under_line > (z_line_of_sight + 0.1)
if np.any(obstruction):
return False # 被遮挡
else:
return True # 可见
# -------------------- 断面对话框 --------------------
class ProfileDialog(QDialog):
def __init__(self, distances, elevations, parent=None):
super().__init__(parent)
self.setWindowTitle("断面分析结果")
self.setGeometry(200, 200, 800, 520)
layout = QVBoxLayout(self)
self.canvas = MplCanvas(self)
layout.addWidget(self.canvas)
self.plot(distances, elevations)
def plot(self, distances, elevations):
self.canvas.axes.clear()
self.canvas.axes.plot(distances, elevations, color='#00AEEF')
self.canvas.axes.fill_between(distances, elevations, elevations.min(), color='#00AEEF', alpha=0.3)
self.canvas.axes.set_title("地形断面图", color='white')
self.canvas.axes.set_xlabel("距离 (m)", color='white')
self.canvas.axes.set_ylabel("高程 (m)", color='white')
self.canvas.axes.grid(True, linestyle='--', alpha=0.5)
self.canvas.draw()
class ProjectNameDialog(QDialog):
@staticmethod
def get_project_name(parent=None):
dlg = QDialog(parent)
dlg.setWindowTitle("设置项目名称")
layout = QVBoxLayout(dlg)
le = QLineEdit()
le.setPlaceholderText("在此输入项目名称")
btns = QHBoxLayout()
ok = QPushButton("确定"); cancel = QPushButton("取消")
btns.addWidget(ok); btns.addWidget(cancel)
layout.addWidget(QLabel("项目名称:")); layout.addWidget(le); layout.addLayout(btns)
def do_ok():
dlg.accept()
def do_cancel():
dlg.reject()
ok.clicked.connect(do_ok); cancel.clicked.connect(do_cancel)
if dlg.exec_() == QDialog.Accepted:
return le.text().strip()
return None
class APISettingsDialog(QDialog):
@staticmethod
def get_settings(parent=None):
dlg = QDialog(parent)
dlg.setWindowTitle("设置")
layout = QVBoxLayout(dlg)
api_group = QGroupBox("API 设置")
api_layout = QVBoxLayout(api_group)
le_url = QLineEdit(os.environ.get('AI_API_URL', ''))
le_key = QLineEdit(os.environ.get('DEEP_AI_API_KEY', ''))
le_model = QLineEdit(os.environ.get('AI_MODEL_NAME', ''))
api_layout.addWidget(QLabel('API URL:')); api_layout.addWidget(le_url)
api_layout.addWidget(QLabel('API Key:')); api_layout.addWidget(le_key)
api_layout.addWidget(QLabel('模型名称:')); api_layout.addWidget(le_model)
ui_group = QGroupBox("UI 设置")
ui_layout = QGridLayout(ui_group)
theme_combo = QComboBox()
theme_combo.addItems(["CAD 经典 (浅色)", "CAD 2024 (深色)"])
current_theme = os.environ.get('CAD_UI_THEME', 'cad_2024')
theme_combo.setCurrentIndex(0 if current_theme == 'cad_classic' else 1)
le_font = QLineEdit(os.environ.get('CAD_UI_FONT', ''))
le_font.setPlaceholderText("例如:Microsoft YaHei / SimSun / Consolas")
ui_layout.addWidget(QLabel("CAD 主题:"), 0, 0)
ui_layout.addWidget(theme_combo, 0, 1)
ui_layout.addWidget(QLabel("字体偏好:"), 1, 0)
ui_layout.addWidget(le_font, 1, 1)
layout.addWidget(api_group)
layout.addWidget(ui_group)
btns = QHBoxLayout(); ok = QPushButton('确定'); cancel = QPushButton('取消')
btns.addWidget(ok); btns.addWidget(cancel); layout.addLayout(btns)
def do_ok(): dlg.accept()
def do_cancel(): dlg.reject()
ok.clicked.connect(do_ok); cancel.clicked.connect(do_cancel)
if dlg.exec_() == QDialog.Accepted:
theme_value = 'cad_classic' if theme_combo.currentIndex() == 0 else 'cad_2024'
return {
'url': le_url.text().strip(),
'key': le_key.text().strip(),
'model': le_model.text().strip(),
'ui_theme': theme_value,
'ui_font': le_font.text().strip()
}
return None
class ColumnMappingDialog(QDialog):
@staticmethod
def get_mapping(columns, parent=None):
dlg = QDialog(parent)
dlg.setWindowTitle('列映射')
layout = QVBoxLayout(dlg)
layout.addWidget(QLabel('请选择 X, Y, Z 列对应'))
combo_x = QComboBox(); combo_y = QComboBox(); combo_z = QComboBox()
combo_x.addItems(columns); combo_y.addItems(columns); combo_z.addItems(columns)
layout.addWidget(QLabel('X 列:')); layout.addWidget(combo_x)
layout.addWidget(QLabel('Y 列:')); layout.addWidget(combo_y)
layout.addWidget(QLabel('Z 列:')); layout.addWidget(combo_z)
btns = QHBoxLayout(); ok = QPushButton('确定'); cancel = QPushButton('取消')
btns.addWidget(ok); btns.addWidget(cancel); layout.addLayout(btns)
ok.clicked.connect(dlg.accept); cancel.clicked.connect(dlg.reject)
if dlg.exec_() == QDialog.Accepted:
return (combo_x.currentText(), combo_y.currentText(), combo_z.currentText())
return None
def closeEvent(self, event):
try:
self.canvas.figure.clf()
plt.close(self.canvas.figure)
except:
pass
super().closeEvent(event)
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
# 设置窗体标题为应用名与版本
try:
self.setWindowTitle(f"{APP_NAME} {APP_VERSION} — {APP_NAME_CN}")
except:
pass
# 数据与状态
self.file_path = None
self.raw_data = None
self.data = None
self.triangulation = None
self.interpolator = None
self.grid_x = None
self.grid_y = None
self.grid_z = None
self.slope_data = None
self.aspect_data = None
self.surface_area = 0.0
self.planar_area = 0.0
self.profile_points = []
self.is_profiling = False
self.data_compare = None
self.triangulation_compare = None
self.interpolator_compare = None
self.vector_layers = []
self.is_querying = False
self.is_adding_point = False
self.is_deleting_point = False
self.show_data_points = False
# 多段断面相关
self.multi_profiles = [] # list of segments, each is list of (x,y)
self.multi_profile_mode = False # whether multi-profile drawing mode is active
self._current_profile_segment = [] # points for current segment being drawn
# last single-profile line (for display persistence)
self.last_profile_line = None # ((x1,x2),(y1,y2])
self.stats_slope_min = 0.0
self.stats_slope_max = 0.0
self.stats_slope_avg = 0.0
self.grid_spacing = 1.0
self.current_3d_mode = "TIN_Mesh"
self.current_analysis_mode = "TIN_Contour"
# 2D 画布中键平移状态
self._canvas2d_pan = {'active': False, 'xpix0': None, 'ypix0': None, 'orig_xlim': None, 'orig_ylim': None}
# 新增:项目名称(由用户在导出前设置)
self.project_name = None
self.last_volume_results = None
# --- 新增:视域分析 (Viewshed) ---
self.is_setting_viewshed = False
self.viewshed_obs_height = 1.8 # 默认观察高度 (m)
self.viewshed_data = None # 存储 (bool) 可视性格网
self.viewshed_observer_pos = None # 存储 (x, y) 观察点
# --- 结束新增 ---
# --- 新增:通视分析 (Line-of-Sight) ---
self.is_checking_los = False # 是否处于通视分析模式
self.los_points = [] # 存储点击的 [p1, p2]
self.last_los_result = None # 存储 (p1, p2, is_visible)
self.los_obs_height = 1.8 # 观察点高度
self.los_tgt_height = 1.8 # 目标点高度
# --- 新增:主题和背景管理 ---
self.current_theme = 'dark' # 'dark' 或 'glass'
self.ui_theme = os.environ.get('CAD_UI_THEME', 'cad_2024')
self.ui_font = os.environ.get('CAD_UI_FONT', '')
self.background_files = []
self.current_background_index = 0
self._load_background_file_list() # 启动时加载文件列表
# 定义新的玻璃样式表 (CSS)
self.GLASS_STYLESHEET = """
/* 主窗口 - 应用背景图 */
QMainWindow {
border-image: url(%s);
background-origin: content;
}
/* 所有透明背景的 QWidget */
QWidget, QScrollArea {
background-color: transparent;
color: #F0F0F0;
font-family: 'Segoe UI', 'SimHei';
font-size: 10pt;
}
/* 半透明卡片样式 */
QGroupBox, QScrollArea > QWidget { /* QScrollArea > QWidget 针对顶部工具栏 */
background-color: rgba(30, 30, 40, 0.7); /* 液态玻璃深色底 */
border: 1px solid rgba(255, 255, 255, 0.3);
border-radius: 10px;
margin-top: 16px;
backdrop-filter: blur(10px);
}
QGroupBox::title {
subcontrol-origin: margin;
subcontrol-position: top center;
padding: 3px 8px;
margin-top: 4px;
background-color: transparent;
color: white;
}
/* 半透明控件 */
QPushButton {
background-color: rgba(85, 85, 85, 0.8);
color: #FFFFFF;
border: 1px solid rgba(255, 255, 255, 0.4);
border-radius: 4px;
padding: 6px 10px;
}
QPushButton:hover { background-color: rgba(100, 100, 100, 0.9); }
QPushButton:pressed { background-color: rgba(76, 175, 80, 0.9); }
QLineEdit, QComboBox, QTextEdit {
background-color: rgba(60, 60, 60, 0.7);
border: 1px solid rgba(255, 255, 255, 0.4);
border-radius: 3px;
padding: 4px;
color: #E0E0E0;
}
/* 分割线 */
QSplitter::handle {
background-color: rgba(74, 74, 74, 0.5);
height: 4px; /* 使其更像一条线 */
}
QSplitter::handle:hover { background-color: rgba(100, 100, 100, 0.8); }
/* 标签 */
QLabel {
background-color: transparent;
color: #F0F0F0;
}
"""
self.initUI()
self.apply_ui_preferences(persist=False)
self.update_ui_state(enabled=False)
# ...existing code...
def initUI(self):
main_widget = QWidget()
self.setCentralWidget(main_widget)
main_layout = QVBoxLayout(main_widget)
main_layout.setContentsMargins(0, 0, 0, 0)
# 顶部控制面板(横向滚动 + 自动高度)
control_widget = self.create_control_panel_content()
scroll_area = QScrollArea()
scroll_area.setWidget(control_widget)
scroll_area.setWidgetResizable(True)
scroll_area.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
scroll_area.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded)
scroll_area.setFrameShape(QScrollArea.NoFrame)
try:
# 计算 control_widget 的推荐高度
required_height = control_widget.sizeHint().height()
# 增加一点缓冲区,防止意外截断
required_height += 55
scroll_area.setFixedHeight(required_height)
except Exception as e:
print(f"Warning: Could not set fixed height for scroll area: {e}")
# Fallback: 如果计算失败,恢复之前的策略
scroll_area.setSizeAdjustPolicy(QScrollArea.AdjustToContents)
scroll_area.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
main_layout.addWidget(scroll_area)
# 下部:2D / 3D 可拖拽
plots_splitter = QSplitter(Qt.Horizontal)
main_layout.addWidget(plots_splitter, stretch=1)
# 2D 区域(方案三)
plot_2d_widget = QWidget()
plot_2d_layout = QVBoxLayout(plot_2d_widget)
plot_2d_layout.setContentsMargins(5, 5, 5, 5)
plot_2d_layout.setSpacing(6)
label_2d = QLabel("2D 模型区域")
self.label_2d = label_2d
self._apply_section_label_style(label_2d)
plot_2d_layout.addWidget(label_2d)
self.canvas_2d = MplCanvas(self)
plot_2d_layout.addWidget(self.canvas_2d, stretch=1)
self.btn_popout_2d = QPushButton("2D 独立查看器")
plot_2d_layout.addWidget(self.btn_popout_2d)
plot_2d_layout.setStretch(0, 0)
plot_2d_layout.setStretch(1, 1)
plot_2d_layout.setStretch(2, 0)
plots_splitter.addWidget(plot_2d_widget)
# 3D 区域(方案三)
plot_3d_widget = QWidget()
plot_3d_layout = QVBoxLayout(plot_3d_widget)
plot_3d_layout.setContentsMargins(5, 5, 5, 5)
plot_3d_layout.setSpacing(6)
label_3d = QLabel("3D 模型区域")
self.label_3d = label_3d
self._apply_section_label_style(label_3d)
plot_3d_layout.addWidget(label_3d)
# --- MODIFICATION START: Overlay Reset Button ---
# 1. Create a container widget that will hold both the canvas and the button
canvas_3d_container = QWidget()
# 2. Use a layout that allows placing widgets on top of each other, like QGridLayout
container_layout = QGridLayout(canvas_3d_container)
container_layout.setContentsMargins(0, 0, 0, 0)
# 3. Add the canvas to the layout, occupying the entire cell (0,0)
self.canvas_3d = MplCanvas(self, is_3d=True)
container_layout.addWidget(self.canvas_3d, 0, 0)
# 4. Create the reset button (moved from create_control_panel_content)
self.btn_reset_view = QPushButton("复位")
# --- MODIFICATION: Set button size as requested by user ---
self.btn_reset_view.setFixedSize(80, 50) # Give it a specific size
self.btn_reset_view.setStyleSheet("margin: 4px;") # Add a small margin from the corner
# 5. Add the button to the same cell (0,0), but align it to the top-right corner
container_layout.addWidget(self.btn_reset_view, 0, 0, Qt.AlignTop | Qt.AlignRight)
# 6. Add the container to the main 3D layout instead of the canvas directly
plot_3d_layout.addWidget(canvas_3d_container, stretch=1)
# --- MODIFICATION END ---
self.btn_popout_3d = QPushButton("3D 独立查看器")
plot_3d_layout.addWidget(self.btn_popout_3d)
plot_3d_layout.setStretch(0, 0)
plot_3d_layout.setStretch(1, 1)
plot_3d_layout.setStretch(2, 0)
plots_splitter.addWidget(plot_3d_widget)
plots_splitter.setSizes([900, 900])
self.showMaximized()
# 连接信号
self.connect_signals()
self._apply_cad_icons()
def create_control_panel_content(self):
panel = QWidget()
layout = QHBoxLayout(panel)
layout.setSpacing(20) # 调整回稍小的间距
layout.setContentsMargins(12, 10, 12, 10)
layout.setAlignment(Qt.AlignTop)
# -------------------- 1. 文件操作 --------------------
file_group = QGroupBox("文件操作")
file_layout = QVBoxLayout()
self.btn_load = QPushButton("加载数据文件") # Simplified text
self.btn_clear = QPushButton("清除显示")
self.btn_process_rtk = QPushButton("RTK 转换加载") # Simplified text
self.btn_load_compare = QPushButton("加载对比 DTM") # Simplified text
self.btn_load_vector = QPushButton("加载矢量图层") # Simplified text
self.lbl_file = QLabel("未加载文件")
# Icons will be applied with CAD style after all buttons are created.
file_layout.addWidget(self.btn_load)
file_layout.addWidget(self.btn_clear)
file_layout.addWidget(self.btn_process_rtk)
file_layout.addWidget(self.btn_load_compare)
file_layout.addWidget(self.btn_load_vector)
file_layout.addWidget(self.lbl_file)
file_group.setLayout(file_layout)
# -------------------- 2. 数据控制 --------------------
data_control_group = QGroupBox("数据控制")
data_control_layout = QVBoxLayout()
# Z 过滤
z_filter_group = QGroupBox("Z 过滤")
z_filter_layout = QGridLayout()
self.line_min_z = QLineEdit(); self.line_max_z = QLineEdit()
validator = QDoubleValidator(); self.line_min_z.setValidator(validator); self.line_max_z.setValidator(validator)
self.btn_apply_z_filter = QPushButton("应用过滤"); self.btn_reset_z_filter = QPushButton("重置")
z_filter_layout.addWidget(QLabel("Min Z:"), 0, 0); z_filter_layout.addWidget(self.line_min_z, 0, 1)
z_filter_layout.addWidget(QLabel("Max Z:"), 1, 0); z_filter_layout.addWidget(self.line_max_z, 1, 1)
z_filter_btn_h = QHBoxLayout(); z_filter_btn_h.addWidget(self.btn_reset_z_filter); z_filter_btn_h.addWidget(self.btn_apply_z_filter)
z_filter_layout.addLayout(z_filter_btn_h, 2, 0, 1, 2)
z_filter_group.setLayout(z_filter_layout)
data_control_layout.addWidget(z_filter_group)
# 数据编辑
self.btn_add_point = QPushButton("添加数据点"); self.btn_add_point.setCheckable(True)
self.btn_delete_point = QPushButton("删除数据点"); self.btn_delete_point.setCheckable(True)
data_control_layout.addWidget(self.btn_add_point)
data_control_layout.addWidget(self.btn_delete_point)
data_control_group.setLayout(data_control_layout)
# -------------------- 3. 渲染设置 --------------------
display_group = QGroupBox("模型渲染设置")
display_layout = QVBoxLayout()
self.combo_3d_mode = QComboBox(); self.combo_3d_mode.addItems(["TIN Mesh (原始网格)", "Smoothed Grid (平滑曲面)"])
self.combo_colormap = QComboBox(); self.colormaps = ['terrain', 'plasma', 'inferno', 'magma', 'viridis', 'coolwarm', 'hsv']; self.combo_colormap.addItems(self.colormaps)
grid_h = QHBoxLayout(); self.line_grid_spacing = QLineEdit("1.0"); self.line_grid_spacing.setValidator(QDoubleValidator(0.1, 1000.0, 2))
grid_h.addWidget(QLabel("格网间距(m):")); grid_h.addWidget(self.line_grid_spacing)
display_layout.addWidget(QLabel("3D 渲染:")); display_layout.addWidget(self.combo_3d_mode)
display_layout.addWidget(QLabel("配色方案:")); display_layout.addWidget(self.combo_colormap)
display_layout.addLayout(grid_h)
self.btn_toggle_points = QPushButton("显示数据点"); self.btn_toggle_points.setCheckable(True); self.btn_toggle_points.setChecked(self.show_data_points)
display_layout.addWidget(self.btn_toggle_points)
display_group.setLayout(display_layout)
# -------------------- 4. 分析设置 (简化) --------------------
analysis_group = QGroupBox("分析设置") # 标题简化
analysis_layout = QVBoxLayout()
# 2D 模式选择
analysis_layout.addWidget(QLabel("2D 显示模式:"))
self.combo_2d_mode = QComboBox()
self.combo_2d_mode.addItems(["等高线图 (Contour)", "坡度图 (Slope)", "坡向图 (Aspect)",
"差值图 (Difference Map)", "视域分析 (Viewshed)"])
analysis_layout.addWidget(self.combo_2d_mode)
# 等高线设置
contour_group = QGroupBox("等高线设置")
cont_layout = QGridLayout()
self.line_major_interval = QLineEdit("5.0"); self.line_minor_interval = QLineEdit("1.0"); self.line_base_elevation = QLineEdit("0.0")
validator_cont = QDoubleValidator(0.01, 10000.0, 2); validator_base = QDoubleValidator(-10000.0, 10000.0, 2)
self.line_major_interval.setValidator(validator_cont); self.line_minor_interval.setValidator(validator_cont); self.line_base_elevation.setValidator(validator_base)
cont_layout.addWidget(QLabel("主线:"), 0, 0); cont_layout.addWidget(self.line_major_interval, 0, 1)
cont_layout.addWidget(QLabel("次线:"), 1, 0); cont_layout.addWidget(self.line_minor_interval, 1, 1)
cont_layout.addWidget(QLabel("基准高程:"), 2, 0); cont_layout.addWidget(self.line_base_elevation, 2, 1)
contour_group.setLayout(cont_layout)
analysis_layout.addWidget(contour_group)
# --- 定量分析和土方量按钮已移出 ---
analysis_group.setLayout(analysis_layout)
# -------------------- 5. 定量分析 (恢复独立) --------------------
terrain_stats_group = QGroupBox("地形定量分析")
terrain_stats_layout = QVBoxLayout()
self.lbl_area_planar = QLabel("平面面积:-- m²")
self.lbl_area_surface = QLabel("表面面积:-- m²")
self.lbl_z_range = QLabel("高程范围:-- ~ -- m")
self.lbl_slope_range = QLabel("坡度范围:--° ~ --°")
self.lbl_slope_avg = QLabel("平均坡度:--°")
for lbl in [self.lbl_area_planar, self.lbl_area_surface, self.lbl_z_range, self.lbl_slope_range, self.lbl_slope_avg]:
lbl.setStyleSheet("color: #DDDDDD; font-size: 10.5pt; padding: 2px;")
terrain_stats_layout.addWidget(lbl)
self.btn_update_stats = QPushButton("刷新定量分析")
self.btn_update_stats.setToolTip("根据当前数据重新计算地形指标")
terrain_stats_layout.addWidget(self.btn_update_stats)
self.btn_calc_volume = QPushButton("土方量计算")
self.btn_calc_volume.setToolTip("基于当前格网与基准面或对比DTM计算挖填方")
terrain_stats_layout.addWidget(self.btn_calc_volume)
terrain_stats_group.setLayout(terrain_stats_layout)
# -------------------- 6. 交互工具 --------------------
interactive_group = QGroupBox("交互工具")
interactive_layout = QVBoxLayout()
self.btn_profile = QPushButton("启用断面分析"); self.btn_multi_profile = QPushButton("多段断面模式")
self.btn_run_viewshed = QPushButton("运行视域分析"); self.btn_run_viewshed.setCheckable(True)
self.btn_check_los = QPushButton("两点通视分析"); self.btn_check_los.setCheckable(True)
self.btn_query_tool = QPushButton("属性查询"); self.btn_query_tool.setCheckable(True)
interactive_layout.addWidget(self.btn_profile); interactive_layout.addWidget(self.btn_multi_profile)
interactive_layout.addWidget(self.btn_run_viewshed); interactive_layout.addWidget(self.btn_check_los)
interactive_layout.addWidget(self.btn_query_tool)
interactive_group.setLayout(interactive_layout)
# -------------------- 7. 测量与GIS工具 --------------------
tools_group = QGroupBox("测量与GIS工具")
tools_layout = QVBoxLayout()
self.btn_tool_coord = QPushButton("坐标转换"); self.btn_tool_distance = QPushButton("距离计算")
self.btn_tool_intersect = QPushButton("前方交会"); self.btn_tool_mapnum = QPushButton("地形图编号")
self.btn_tool_leveling = QPushButton("水准闭合差")
tools_layout.addWidget(self.btn_tool_coord); tools_layout.addWidget(self.btn_tool_distance)
tools_layout.addWidget(self.btn_tool_intersect); tools_layout.addWidget(self.btn_tool_mapnum)
tools_layout.addWidget(self.btn_tool_leveling)
self.btn_zonal_stats = QPushButton("分区统计 (Zonal Stats)")
tools_layout.addWidget(self.btn_zonal_stats)
tools_group.setLayout(tools_layout)
# -------------------- 8. 导出与设置 --------------------
export_settings_group = QGroupBox("导出与设置")
export_settings_layout = QGridLayout()
self.btn_export_2d = QPushButton("导出 2D 图像"); self.btn_export_3d = QPushButton("导出 3D 图像")
self.btn_export_grid = QPushButton("导出 DGM 格网"); self.btn_export_report = QPushButton("导出报告 (.docx)")
self.btn_export_profiles = QPushButton("导出断面汇总")
self.btn_set_api = QPushButton("设置 (API/界面)"); self.btn_set_project = QPushButton("项目名称")
self.btn_toggle_theme = QPushButton("切换主题 (Glass)")
# 布局
export_settings_layout.addWidget(self.btn_export_2d, 0, 0); export_settings_layout.addWidget(self.btn_set_api, 0, 1)
export_settings_layout.addWidget(self.btn_export_3d, 1, 0); export_settings_layout.addWidget(self.btn_set_project, 1, 1)
export_settings_layout.addWidget(self.btn_export_grid, 2, 0); export_settings_layout.addWidget(self.btn_toggle_theme, 2, 1)
export_settings_layout.addWidget(self.btn_export_profiles, 3, 0)
export_settings_layout.addWidget(self.btn_export_report, 4, 0)
self.btn_export_modified_data = QPushButton("导出修改后数据 (.csv)")
export_settings_layout.addWidget(self.btn_export_modified_data, 5, 0)
export_settings_group.setLayout(export_settings_layout)
# -------------------- 添加所有 GroupBox 到主布局 --------------------
groups_list = [
file_group,
data_control_group,
display_group,
analysis_group, # 简化后的分析设置
terrain_stats_group, # 恢复的定量分析
interactive_group,
tools_group,
export_settings_group
]
min_width = 220 # 统一最小宽度
for g in groups_list:
g.setMinimumWidth(min_width)
layout.addWidget(g)
layout.addStretch()
# 根据新的组数和间距调整面板最小宽度
panel_min_width = sum(min_width for g in groups_list) + \
(len(groups_list) - 1) * layout.spacing() + \
layout.contentsMargins().left() + layout.contentsMargins().right()
panel.setMinimumWidth(panel_min_width)
return panel
def connect_signals(self):
# 文件与过滤
self.btn_load.clicked.connect(self.load_data)
self.btn_clear.clicked.connect(self.clear_display)
self.btn_apply_z_filter.clicked.connect(self.apply_z_filter)
self.btn_reset_z_filter.clicked.connect(self.reset_z_filter)
# 显示与分析
self.combo_3d_mode.currentTextChanged.connect(self.on_3d_mode_changed)
self.combo_2d_mode.currentTextChanged.connect(self.on_2d_mode_changed)
self.combo_colormap.currentTextChanged.connect(self.on_colormap_changed)