forked from EmGi96/TrailPrint3D
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
8809 lines (6883 loc) · 315 KB
/
Copy pathutils.py
File metadata and controls
8809 lines (6883 loc) · 315 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
# Copyright (C) 2026 EmGi
# You are free to modify it under the terms of the GNU General Public License as published by the Free Software Foundation.
# You are free to use any models Generated by this Addon Commercially
import bpy # type: ignore
import webbrowser
from collections import deque
import xml.etree.ElementTree as ET
import math
import requests # type: ignore
import time
from datetime import date
from datetime import datetime
import bmesh # type: ignore
from mathutils import Vector, bvhtree, Euler
import os
import sys
import json
import platform
import zlib
import struct
import csv
import random
import hashlib
import zipfile
import io
import addon_utils
from .export import export_to_STL, export_selected_to_STL, export_selected_to_3mf, customThumbnail, get_selection_center, is_3mf_extension_installed, install_3mf_extension
try:
from .utils_pe import textIcon
except ImportError:
def textIcon(*_):
return None
from bpy.app.translations import pgettext as _
from . import progress as _progress
from . import addon_preferences
from . import bl_info
from . import panels
from . import constants as const
def open_website(self, context, url="https://patreon.com/EmGi3D?utm_source=Blender"):
print(url)
webbrowser.open(url)
def save_myproperties_to_csv(filename):
"""
Save all writable properties of a MyProperties instance to a CSV file.
Each row is: property_name , value
"""
folder = const.preset_dir
os.makedirs(folder, exist_ok=True)
filepath = os.path.join(folder, filename + ".csv")
props = bpy.context.scene.tp3d
print(filepath)
with open(filepath, "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow(["property", "value"]) # header
for p in props.bl_rna.properties:
name = p.identifier
if name == "rna_type" or p.is_readonly:
continue
try:
value = getattr(props, name)
except:
continue
# Convert lists/tuples to string
if isinstance(value, (list, tuple)):
value = ",".join(map(str, value))
writer.writerow([name, value])
def appendCollection():
addon_dir = os.path.dirname(__file__)
filepath = os.path.join(addon_dir, "assets", bpy.context.scene.tp3d.specialBlendFile)
collection_name = bpy.context.scene.tp3d.specialCollectionName
#If the collection already exists, delete it and its contents
collection = bpy.data.collections.get(collection_name)
if collection:
bpy.context.scene.collection.children.unlink(collection)
bpy.data.collections.remove(collection)
print(f"Collection to Import: {collection_name}")
with bpy.data.libraries.load(filepath, link=False) as (data_from, data_to):
if collection_name in data_from.collections:
data_to.collections.append(collection_name)
else:
print(f"Collection '{collection_name}' not found.")
return
col = bpy.data.collections.get(collection_name)
if col:
bpy.context.scene.collection.children.link(col)
scene_col = bpy.context.scene.collection
objs = list(col.objects)
roots = [o for o in objs if not o.parent]
if roots:
roots[0].location = bpy.context.scene.cursor.location
return_obj = None
for obj in objs:
scene_col.objects.link(obj)
col.objects.unlink(obj)
#eg jigzaw or slider puzzles
if "BLANK" in obj.name or "Blank" in obj.name:
bpy.ops.object.select_all(action='DESELECT')
obj.select_set(True)
bpy.context.view_layer.objects.active = obj
parts = collection_name.split("_")
for part in parts[1:]: # everything after a "_"
num = part.split("mm")[0] # take what's before "mm"
if "mm" in part and num.replace(".", "", 1).isdigit():
bpy.context.scene.tp3d.objSize = int(num)
break
return_obj = obj
if "objSize" in obj.keys():
scaleFactor = 1/100 * bpy.context.scene.tp3d.objSize
obj.scale = (scaleFactor, scaleFactor, scaleFactor)
scene_col.children.unlink(col)
bpy.data.collections.remove(col)
return return_obj
else:
return None
def get_external_collections(path):
if not os.path.exists(path):
return []
with bpy.data.libraries.load(path, link=True) as (data_from, _):
return list(data_from.collections)
def loadCollections(self, context):
addon_dir = os.path.dirname(__file__)
path = os.path.join(addon_dir, "assets", bpy.context.scene.tp3d.specialBlendFile)
names = get_external_collections(path)
const.specialCollection = [(name, name, "") for name in names]
first_name = names[0]
if first_name in [item.identifier for item in bpy.context.scene.tp3d.bl_rna.properties["specialCollectionName"].enum_items]:
bpy.context.scene.tp3d.specialCollectionName = first_name
bpy.context.scene.tp3d.specialCollectionName = first_name
print(f"First name: {first_name}")
def load_myproperties_from_csv(filename):
"""
Load all properties from a CSV file and overwrite the values in MyProperties.
"""
folder = const.preset_dir
filepath = os.path.join(folder, filename + ".csv")
if not os.path.isfile(filepath):
print("Preset file not found:", filepath)
return
props = bpy.context.scene.tp3d
with open(filepath, "r", encoding="utf-8") as f:
reader = csv.reader(f)
next(reader) # skip header
for row in reader:
if len(row) < 2:
continue
name, value = row[0], row[1]
if not hasattr(props, name):
continue # skip unknown properties
current = getattr(props, name)
try:
# Convert back to correct type
if isinstance(current, bool):
value = value.lower() == "true"
elif isinstance(current, int):
value = int(value)
elif isinstance(current, float):
value = float(value)
elif isinstance(current, (list, tuple)):
# Split list stored as comma-separated string
value = [float(v) for v in value.split(",")]
# strings stay strings
except:
# Failed conversion → keep original
continue
try:
setattr(props, name, value)
except:
pass
def delete_preset_file(preset_name):
"""
Deletes a preset .csv file from the Blender CONFIG/presets folder.
preset_name = name WITHOUT extension
"""
folder = const.preset_dir
filepath = os.path.join(folder, preset_name + ".csv")
if not os.path.isfile(filepath):
print("File not found:", filepath)
return False
try:
os.remove(filepath)
print("Deleted:", filepath)
return True
except Exception as e:
print("Error deleting file:", e)
return False
def list_files_callback(self, context):
folder = const.preset_dir
items = []
if os.path.isdir(folder):
for fname in os.listdir(folder):
if os.path.isfile(os.path.join(folder, fname)):
name_no_ext = os.path.splitext(fname)[0]
items.append((name_no_ext, name_no_ext, ""))
# Show placeholder if empty
if not items:
items.append(("none", "-- No files found --", ""))
return items
def load_counter():
if os.path.exists(const.counter_file):
try:
with open(const.counter_file, "r") as f:
data = json.load(f)
return data.get("count_openTopodata", 0), data.get("date_openTopoData", ""), data.get("count_openElevation",0), data.get("date_openElevation","")
except:
return 0, "", 0, ""
return 0, "", 0, ""
# Function to save the counter data
def save_counter(count_openTopodata, date_openTopoData, count_openElevation, date_openElevation):
with open(const.counter_file, "w") as f:
json.dump({"count_openTopodata": count_openTopodata, "date_openTopoData": date_openTopoData, "count_openElevation": count_openElevation, "date_openElevation": date_openElevation}, f)
# Function to update the request counter
def update_request_counter():
api = bpy.context.scene.tp3d.api
today = date.today().isoformat() # ✅ This correctly gets today's date
today_date = date.today().isoformat() # Get today's date in iso format
today_month = date.today().month # Get current month as an integer (1-12)
count_openTopodata, date_openTopoData, count_openElevation, date_openElevation = load_counter()
# Reset counter if the date has changed
if date_openTopoData != today_date:
count_openTopodata = 0
if date_openElevation != today_month:
count_openElevation = 0
if api == "OPENTOPODATA":
count_openTopodata += 1
elif api == "OPEN-ELEVATION":
count_openElevation += 1
save_counter(count_openTopodata, today_date, count_openElevation,today_month)
return count_openTopodata, count_openElevation # Return the updated count
def send_api_request(addition = ""):
dataset = bpy.context.scene.tp3d.dataset
api = bpy.context.scene.tp3d.api
request_count = update_request_counter()
now = datetime.now()
if api == "OPENTOPODATA":
print(f"{now.hour:02d}:{now.minute:02d} | Fetching: {addition} | API Usage: {request_count} | {dataset}")
elif api == "OPEN-ELEVATION":
print(f"{now.hour:02d}:{now.minute:02d} | Fetching: {addition} | API Usage: {request_count}")
elif api == "TERRAIN-TILES":
print(f"{now.hour:02d}:{now.minute:02d} | Fetching API")
#--------------------------------------------------------------------------------------------------------------------
#DISPLAY GENERATION----------------------------------------------------------------------------------------------------------
#--------------------------------------------------------------------------------------------------------------------
def _parse_points(points, point_type):
segcoords = []
lowestElevation = float("inf")
for pt in points:
lat = float(pt.get("lat"))
lon = float(pt.get("lon"))
ele = None
time = None
for c in pt:
tag = c.tag.split("}")[-1]
if tag == "ele":
ele = c
elif tag == "time":
time = c
elevation = float(ele.text) if ele is not None else 0.0
try:
timestamp = (
datetime.fromisoformat(time.text.replace("Z", "+00:00"))
if time is not None else None
)
except Exception:
timestamp = None
segcoords.append((lat, lon, elevation, timestamp))
lowestElevation = min(lowestElevation, elevation)
bpy.context.scene.tp3d["o_verticesPath"] = f"{point_type} Path vertices: {len(segcoords)}"
return segcoords
def read_gpx(filepath):
"""
Universal GPX reader.
Supports:
- GPX 1.1 / 1.0
- trk / trkseg / trkpt
- rte / rtept
- files without namespaces
"""
tree = ET.parse(filepath)
root = tree.getroot()
segmentlist = []
# --------------------------------------------------
# Namespace handling (GPX 1.1 / 1.0 / none)
# --------------------------------------------------
def strip_ns(tag):
return tag.split("}")[-1]
def findall_any(elem, names):
return [e for e in elem.iter() if strip_ns(e.tag) in names]
def find_child(elem, names):
for c in elem:
if strip_ns(c.tag) in names:
return c
return None
# --------------------------------------------------
# Track segments
# --------------------------------------------------
trksegs = findall_any(root, ["trkseg"])
if trksegs:
for seg in trksegs:
points = [p for p in seg if strip_ns(p.tag) == "trkpt"]
if points:
segmentlist.append(
_parse_points(points, "TRKPT")
)
# --------------------------------------------------
# Routes (fallback or additional if no segments found)
# --------------------------------------------------
routes = findall_any(root, ["rte"])
for rte in routes:
points = [p for p in rte if strip_ns(p.tag) == "rtept"]
if points:
segmentlist.append(
_parse_points(points, "RTEPT")
)
# --------------------------------------------------
# Edge case: GPX with direct trkpt/rtept (rare but real)
# --------------------------------------------------
if not segmentlist:
points = findall_any(root, ["trkpt", "rtept"])
if points:
segmentlist.append(
_parse_points(points, "POINT")
)
return segmentlist
def read_igc(filepath):
"""Reads an IGC file and extracts the coordinates, elevation, and timestamps."""
segmentlist = []
coordinates = []
lowestElevation = 10000
with open(filepath, 'r') as file:
for line in file:
# IGC B records contain position data
if line.startswith('B'):
try:
# Extract time (HHMMSS)
time_str = line[1:7]
hours = int(time_str[0:2])
minutes = int(time_str[2:4])
seconds = int(time_str[4:6])
# Extract latitude (DDMMmmmN/S)
lat_str = line[7:15]
lat_deg = int(lat_str[0:2])
lat_min = int(lat_str[2:4])
lat_min_frac = int(lat_str[4:7]) / 1000.0
lat = lat_deg + (lat_min + lat_min_frac) / 60.0
if lat_str[7] == 'S':
lat = -lat
# Extract longitude (DDDMMmmmE/W)
lon_str = line[15:24]
lon_deg = int(lon_str[0:3])
lon_min = int(lon_str[3:5])
lon_min_frac = int(lon_str[5:8]) / 1000.0
lon = lon_deg + (lon_min + lon_min_frac) / 60.0
if lon_str[8] == 'W':
lon = -lon
# Extract pressure altitude (in meters)
pressure_alt = int(line[25:30])
# Extract GPS altitude (in meters)
gps_alt = int(line[30:35])
# Create timestamp (using current date since IGC files don't store date in B records)
now = datetime.now()
timestamp = datetime(now.year, now.month, now.day, hours, minutes, seconds)
# Use GPS altitude for elevation
elevation = gps_alt
coordinates.append((lat, lon, elevation, timestamp))
if elevation < lowestElevation:
lowestElevation = elevation
except (ValueError, IndexError) as e:
print(f"Error parsing IGC line: {line.strip()}")
continue
bpy.context.scene.tp3d["o_verticesPath"] = "Path vertices: " + str(len(coordinates))
segmentlist.append(coordinates)
return segmentlist
def read_gpx_directory(directory_path):
"""Reads all GPX files in a directory and extracts coordinates, elevation, and timestamps."""
# Define GPX namespace
ns = {'default': 'http://www.topografix.com/GPX/1/1'}
# List to store all coordinates from all GPX files, grouped by file.
# Structure: [[seg1, seg2, ...], [seg1, ...], ...] — one inner list per file,
# each inner list contains that file's track segments.
coordinatesByFile = []
lowestElevation = 10000 # High initial value
# Iterate over all files in the directory
for filename in os.listdir(directory_path):
if filename.lower().endswith(".gpx") or filename.lower().endswith(".igc"):
filepath = os.path.join(directory_path, filename)
file_extension = os.path.splitext(filepath)[1].lower()
if file_extension == '.gpx':
tree = ET.parse(filepath)
root = tree.getroot()
version = root.get("version")
print(f"File Name: {filename}, File Version: {version}")
co = read_gpx(filepath)
elif file_extension == '.igc':
co = read_igc(filepath)
# Keep all segments from this file together as a group
if co:
coordinatesByFile.append(co)
for coseg in co:
lowest = min(coseg, key=lambda x: x[2])
lowest_In_coords = lowest[2]
if lowest_In_coords < lowestElevation:
lowestElevation = lowest_In_coords
print(f"new Lowest Elevation: {lowestElevation}")
# Flatten for vertex count reporting
coordinatesSeparate = [seg for file_segs in coordinatesByFile for seg in file_segs]
coordinates = [pt for seg in coordinatesSeparate for pt in seg]
# Store the number of points in the Blender scene property
bpy.context.scene.tp3d["o_verticesPath"] = f"Path vertices: {len(coordinates)}"
print(f"Total GPX files processed: {len(coordinatesByFile)}")
return coordinatesByFile
def read_gpx_file():
gpx_file_path = bpy.context.scene.tp3d.get('file_path', None)
coords = []
file_extension = os.path.splitext(gpx_file_path)[1].lower()
if file_extension == '.gpx':
tree = ET.parse(gpx_file_path)
root = tree.getroot()
version = root.get("version")
ns = {'default': root.tag.split('}')[0].strip('{')}
GPXsections = len(root.findall(".//default:trkseg", ns))
print(f"GPX Sections found in GPX File: {GPXsections}")
coords = read_gpx(gpx_file_path)
elif file_extension == '.igc':
coords= read_igc(gpx_file_path)
else:
show_message_box("Unsupported file format. Please use .gpx or .igc files.")
return
return coords
# Load cache from disk
def load_elevation_cache():
"""Load the elevation cache from disk"""
if os.path.exists(const.elevation_cache_file):
try:
with open(const.elevation_cache_file, "r") as f:
const._elevation_cache = json.load(f)
except Exception as e:
print(f"Error loading elevation cache: {str(e)}")
const._elevation_cache = {}
else:
const._elevation_cache = {}
# Save cache to disk
def save_elevation_cache():
"""Save the elevation cache from Opentopodata or OpenElevation to disk"""
cacheSize = bpy.context.scene.tp3d.ccacheSize
# Limit cache size to prevent excessive file sizes
#print(f"Currently cached: {len(_elevation_cache)}")
if len(const._elevation_cache) > cacheSize:
# Keep only the most recent entries
keys = list(const._elevation_cache.keys())
for key in keys[:-cacheSize]:
del const._elevation_cache[key]
try:
with open(const.elevation_cache_file, "w") as f:
json.dump(const._elevation_cache, f)
except Exception as e:
print(f"Error saving elevation cache: {str(e)}")
def get_cached_elevation(lat, lon, api_type="opentopodata"):
"""Get elevation from cache if available"""
key = f"{lat:.5f}_{lon:.5f}_{api_type}"
return const._elevation_cache.get(key)
def cache_elevation(lat, lon, elevation, api_type="opentopodata"):
"""Cache elevation data"""
key = f"{lat:.5f}_{lon:.5f}_{api_type}"
const._elevation_cache[key] = elevation
def _setup_material(name, color):
if name not in bpy.data.materials:
mat = bpy.data.materials.new(name=name)
else:
mat = bpy.data.materials[name]
mat.use_nodes = True
nodes = mat.node_tree.nodes
links = mat.node_tree.links
bsdf = next((n for n in nodes if n.type == 'BSDF_PRINCIPLED'), None)
if not bsdf:
bsdf = nodes.new(type="ShaderNodeBsdfPrincipled")
bsdf.location = (0, 0)
output = next((n for n in nodes if n.type == 'OUTPUT_MATERIAL'), None)
if not output:
output = nodes.new(type="ShaderNodeOutputMaterial")
output.location = (300, 0)
if not bsdf.outputs["BSDF"].is_linked:
links.new(bsdf.outputs["BSDF"], output.inputs["Surface"])
bsdf.inputs["Base Color"].default_value = color
def setupColors():
_setup_material("BASE", (0.05, 0.7, 0.05, 1.0))
_setup_material("FOREST", (0.05, 0.25, 0.05, 1.0))
_setup_material("MOUNTAIN", (0.5, 0.5, 0.5, 1.0))
_setup_material("WATER", (0.0, 0.0, 0.8, 1.0))
_setup_material("TRAIL", (1.0, 0.0, 0.0, 1.0))
_setup_material("YELLOW", (1.0, 1.0, 0.0, 1.0))
_setup_material("CITY", (0.7, 0.7, 0.1, 1.0))
_setup_material("GREENSPACE",(0.16, 1.0, 0.16, 1.0))
_setup_material("GLACIER", (0.8, 0.9, 0.8, 1.0))
_setup_material("BLACK", (0.0, 0.0, 0.0, 1.0))
_setup_material("WHITE", (1.0, 1.0, 1.0, 1.0))
_setup_material("BUILDINGS", (0.4, 0.4, 0.4, 1.0))
_setup_material("FARMLAND", (0.3, 0.5, 0.1, 1.0))
def calculate_scale(mapSize, coordinates, gen_type):
scalemode = bpy.context.scene.tp3d.scalemode
pathScale = bpy.context.scene.tp3d.pathScale
print(f"Scalemode: {scalemode}")
print(f"Gen_type: {gen_type}")
#for lat, lon, ele in coordinates:
min_lat = min(point[0] for point in coordinates)
max_lat = max(point[0] for point in coordinates)
min_lon = min(point[1] for point in coordinates)
max_lon = max(point[1] for point in coordinates)
R = const.R
#x1 = R * math.radians(min_lon)
#x1 = R * math.radians(min_lon) * math.cos(math.radians(min_lat))
#y1 = R * math.log(math.tan(math.pi / 4 + math.radians(min_lat) / 2))
#x2 = R * math.radians(max_lon)
#x2 = R * math.radians(max_lon) * math.cos(math.radians(max_lat))
#y2 = R * math.log(math.tan(math.pi / 4 + math.radians(max_lat) / 2))
#width = abs(x2 - x1)
#height = abs(y2 - y1)
#distance = math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
x1, y1, e = convert_to_neutral_coordinates(min_lat, min_lon, 0,0)
x2, y2, e = convert_to_neutral_coordinates(max_lat, max_lon, 0,0)
if scalemode == "FACTOR" and gen_type != 2:
width = abs(x2 - x1)
height = abs(y2 - y1)
distance = math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
else:
width = haversine(min_lat, min_lon, min_lat, max_lon) * 1
height = haversine(min_lat, min_lon, max_lat,min_lon) * 1
distance = haversine(min_lat,min_lon,max_lat,max_lon)*1
#COMMENTED OUT
#CALCULATES THE ACCURATE SCALE BUT MULTIPLE PATHS TO EACH OTHER WONT ALIGN CORRECTLY WITH IT AS THE "mf"
#IS DIFFRENT FOR EACH LATITUDE AND THEREFORE HAS A DIFFRENT "COORDINATE SYSTEM"
if scalemode == "SCALE":
mx1 = x1 = R * math.radians(min_lon) * math.cos(math.radians(min_lat))
mx2 = x2 = R * math.radians(max_lon) * math.cos(math.radians(max_lat))
mwidth = abs(mx1 - mx2)
mf = 1/width * mwidth
mf = 1
if scalemode == "COORDINATES" or scalemode == "SCALE":
distance = 0
maxer = max(width,height, distance)
scale = 1
if scalemode == "COORDINATES" or gen_type == 2 or gen_type == 3:
print("scalemode1")
scale = mapSize / maxer
elif scalemode == "FACTOR":
print("scalemode2")
scale = (mapSize * pathScale) / maxer
elif scalemode == "SCALE":
print("scalemode3")
scale = pathScale * mf
print(f"Scale: {scale}")
return scale
def convert_to_blender_coordinates(lat, lon, elevation,timestamp):
scaleHor = bpy.context.scene.tp3d.sScaleHor
autoScale = bpy.context.scene.tp3d.sAutoScale
scaleElevation = bpy.context.scene.tp3d.scaleElevation
R = const.R
x = R * math.radians(lon) * scaleHor
y = R * math.log(math.tan(math.pi / 4 + math.radians(lat) / 2)) * scaleHor
z = elevation / 1000 * scaleElevation * autoScale
return (x, y, z)
def convert_to_neutral_coordinates(lat, lon, elevation,timestamp):
autoScale = bpy.context.scene.tp3d.sAutoScale
scaleElevation = bpy.context.scene.tp3d.scaleElevation
R = const.R
x = R * math.radians(lon)
y = R * math.log(math.tan(math.pi / 4 + math.radians(lat) / 2))
z = elevation / 1000 * scaleElevation * autoScale
return (x, y, z)
# Convert offsets to latitude/longitude
def convert_to_geo(x,y):
"""Converts Blender x/y offsets to latitude/longitude."""
scaleHor = bpy.context.scene.tp3d.sScaleHor
R = const.R
longitude = math.degrees((x) / (R * scaleHor) )
latitude = math.degrees(2 * math.atan(math.exp((y) / (R * scaleHor) )) - math.pi / 2)
return latitude, longitude
def create_curve_from_coordinates(coordinates):
"""
Create a curve in Blender based on a list of (x, y, z) coordinates.
"""
pathThickness = bpy.context.scene.tp3d.pathThickness
name = bpy.context.scene.tp3d.modelname
# Create a new curve object
curve_data = bpy.data.curves.new('GPX_Curve', type='CURVE')
curve_data.dimensions = '3D'
polyline = curve_data.splines.new('POLY')
polyline.points.add(count=len(coordinates) - 1)
# Populate the curve with points
for i, coord in enumerate(coordinates):
polyline.points[i].co = (coord[0], coord[1], coord[2], 1) # (x, y, z, w)
# Create an object with this curve
curve_object = bpy.data.objects.new('GPX_Curve_Object', curve_data)
bpy.context.collection.objects.link(curve_object)
curve_object.data.bevel_depth = pathThickness/2 # Set the thickness of the curve
curve_object.data.bevel_resolution = 4 # Set the resolution for smoothness
mod = curve_object.modifiers.new(name="Remesh",type="REMESH")
mod.mode = "VOXEL"
mod.voxel_size = 0.05 * pathThickness * 10/2
mod.adaptivity = 0.0
curve_object.data.use_fill_caps = True
curve_object.data.name = name + "_Trail"
curve_object.name = name + "_Trail"
curve_object.select_set(True)
bpy.context.view_layer.objects.active = curve_object
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.curve.select_all(action='SELECT')
#bpy.ops.curve.smooth()
bpy.ops.object.mode_set(mode='OBJECT')
return curve_object
def simplify_curve(points_with_extra, min_distance=0.1000):
"""
Removes points that are too close to any previously accepted point.
Keeps the full (x, y, z, time) format.
"""
if not points_with_extra:
return []
simplified = [points_with_extra[0]]
last_xyz = Vector(points_with_extra[0][:3])
skipped = 0
for pt in points_with_extra[1:]:
current_xyz = Vector(pt[:3])
if (current_xyz - last_xyz).length >= min_distance:
simplified.append(pt)
last_xyz = current_xyz
else:
skipped += 1
pass
print(f"Smooth curve: Removed {skipped} vertices")
return simplified
def create_hexagon(size, num_subdivisions = 1, name = "Hexagon"):
"""Creates a hexagon at (0,0,0), subdivides it, and rotates it by 90 degrees."""
verts = []
faces = []
for i in range(6):
angle = math.radians(60 * i)
x = size * math.cos(angle)
y = size * math.sin(angle)
verts.append((x, y, 0))
verts.append((0, 0, 0)) # Center vertex
faces = [[i, (i + 1) % 6, 6] for i in range(6)]
mesh = bpy.data.meshes.new("Hexagon")
obj = bpy.data.objects.new("Hexagon", mesh)
bpy.context.collection.objects.link(obj)
mesh.from_pydata(verts, [], faces)
mesh.update()
bpy.context.view_layer.objects.active = obj
bpy.ops.object.mode_set(mode='EDIT')
#bpy.ops.mesh.subdivide(number_cuts=num_subdivisions)
for _ in range(num_subdivisions):
bpy.ops.mesh.subdivide(number_cuts=1) # 1 cut per loop for even refinement
bpy.ops.object.mode_set(mode='OBJECT')
obj.name = name
obj.data.name = name
return obj
def create_rectangle(width, height, num_subdivisions = 1, name="Rectangle"):
"""Creates a rectangle and adds loop cuts to ensure cells are as square as possible."""
cuts = 1 + 2**(num_subdivisions+1)
# 1. Create the basic plane mesh
verts = [
(-width / 2, -height / 2, 0),
(width / 2, -height / 2, 0),
(width / 2, height / 2, 0),
(-width / 2, height / 2, 0)
]
faces = [[0, 1, 2, 3]]
mesh = bpy.data.meshes.new(name)
obj = bpy.data.objects.new(name, mesh)
bpy.context.collection.objects.link(obj)
mesh.from_pydata(verts, [], faces)
mesh.update()
# 2. Calculate cuts needed to keep cells square
# Number of cuts = (Total Length / Cell Size) - 1
# We use max(0, ...) to ensure we don't pass negative numbers
target_cell_size = width/cuts
cuts_y = max(0, int(round(height / target_cell_size)) - 1)
# 3. Apply the cuts
bpy.context.view_layer.objects.active = obj
bpy.ops.object.mode_set(mode='EDIT')
# Subdivide the edges differently for X and Y
# We use the 'subdivide' operator but specify which edges to cut
# by using the 'number_cuts' property twice on specific axes
bm = bmesh.from_edit_mesh(mesh)
# Subdivide horizontal edges (cuts along Width)
horizontal_edges = [e for e in bm.edges if e.verts[0].co.y == e.verts[1].co.y]
if num_subdivisions > 0:
bmesh.ops.subdivide_edges(bm, edges=horizontal_edges, cuts=cuts, use_grid_fill=True)
bm.verts.ensure_lookup_table()
bm.edges.ensure_lookup_table()
bm.faces.ensure_lookup_table()
vertical_edges = [e for e in bm.edges if abs(e.verts[0].co.x - e.verts[1].co.x) < 0.001]
if cuts_y > 0:
bmesh.ops.subdivide_edges(bm, edges=vertical_edges, cuts=cuts_y, use_grid_fill=True)
bmesh.update_edit_mesh(mesh)
bpy.ops.object.mode_set(mode='OBJECT')
return obj
def create_heart(size, num_subdivisions = 1, name = "Heart"):
"""Creates a full heart-shaped mesh in Blender and applies a Remesh modifier."""
verts = []
faces = []
# Heart parametric equations (full heart)
steps = 200
for i in range(steps + 1):
t = i / steps * (2 * math.pi)
x = size * (16 * math.sin(t) ** 3) / 16
y = size * (13 * math.cos(t) - 5 * math.cos(2 * t) - 2 * math.cos(3 * t) - math.cos(4 * t)) / 16
verts.append((x, y, 0))
# Add the center vertex for triangulation
verts.append((0, -size / 2, 0))
center_index = len(verts) - 1
# Create faces
for i in range(steps):
faces.append([i, (i + 1) % steps, center_index])
# Create the mesh
mesh = bpy.data.meshes.new(name)
obj = bpy.data.objects.new(name, mesh)
bpy.context.collection.objects.link(obj)
# Set the mesh data
mesh.from_pydata(verts, [], faces)
mesh.update()
bpy.context.view_layer.objects.active = obj
# Enter Edit mode
bpy.ops.object.mode_set(mode='EDIT')
# Extrude the surface
bpy.ops.mesh.extrude_region_move(TRANSFORM_OT_translate={
'value': (0, 0, 2)
})
bpy.ops.object.mode_set(mode='OBJECT')
# Add Remesh modifier
remesh = obj.modifiers.new(name="Remesh", type='REMESH')
remesh.mode = 'SHARP'
remesh.octree_depth = num_subdivisions + 1
remesh.scale = 0.9
remesh.sharpness = 1.0
if "Remesh" in obj.modifiers:
bpy.ops.object.modifier_apply(modifier="Remesh")
bpy.ops.object.mode_set(mode='EDIT')
# Get the mesh data
mesh = obj.data
bm = bmesh.new()
bm.from_mesh(mesh)
# Find the top coplanar faces
bm.faces.ensure_lookup_table()
top_faces = [f for f in bm.faces if f.normal == Vector((0, 0, 1))]
top_normals = {tuple(f.normal) for f in top_faces}
# Delete faces that are not coplanar with the top surfaces
faces_to_delete = [f for f in bm.faces if tuple(f.normal) not in top_normals]
bmesh.ops.delete(bm, geom=faces_to_delete, context='FACES')
bpy.ops.object.mode_set(mode='OBJECT')
# Update the mesh
bm.to_mesh(mesh)
mesh.update()
bm.free()
# Back to Object mode
bpy.ops.object.mode_set(mode='OBJECT')
return obj
def create_circle(radius, num_subdivisions = 1, name = "Circle", num_segments=64):