-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrobot_3d_visualizer.py
More file actions
2404 lines (1996 loc) · 83.6 KB
/
robot_3d_visualizer.py
File metadata and controls
2404 lines (1996 loc) · 83.6 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
"""
3D Robot Arm Visualizer for ThorRR Robot
Displays robot skeleton and end effector trajectory in interactive 3D view
PYQTGRAPH VERSION: Uses OpenGL for smooth interactive controls and better performance
Realistic visualization using geometric primitives to approximate ThorRR robot geometry.
"""
import numpy as np
import pyqtgraph as pg
import pyqtgraph.opengl as gl
from PyQt5 import QtCore, QtWidgets, QtGui
import logging
import threading
from pathlib import Path
import json
import paths
import forward_kinematics as fk
logger = logging.getLogger(__name__)
# Try to import numpy-stl for STL loading
try:
from stl import mesh as stl_mesh
STL_AVAILABLE = True
except ImportError:
STL_AVAILABLE = False
logger.warning("numpy-stl not installed. STL visualization disabled. "
"Install with: pip install numpy-stl")
# =============================================================================
# STL Mesh Loading for Realistic Robot Visualisation
# =============================================================================
# STL file mapping: joint index -> filename
STL_FILES = {
'base': 'Thor - base.stl',
'art1': 'Thor - Art1.stl',
'art2': 'Thor - Art2.stl',
'art3': 'Thor - Art3.stl',
'art4': 'Thor - Art4.stl',
'art5': 'Thor - Art5.stl',
'gripper': 'Thor - Gripper.stl',
}
# Cache for loaded STL meshes
_stl_cache = {}
def get_stl_directory():
"""Get the STL files directory path"""
return paths.get_bundle_dir() / 'STLs'
def load_stl_mesh(name):
"""
Load an STL file and convert to PyQtGraph mesh format.
Args:
name: Key from STL_FILES dict ('base', 'art1', etc.)
Returns:
Tuple (vertices, faces) or None if loading fails.
vertices: Nx3 numpy array of vertex positions
faces: Mx3 numpy array of face indices
"""
global _stl_cache
if not STL_AVAILABLE:
return None
if name in _stl_cache:
return _stl_cache[name]
if name not in STL_FILES:
logger.warning(f"Unknown STL name: {name}")
return None
stl_path = get_stl_directory() / STL_FILES[name]
if not stl_path.exists():
logger.warning(f"STL file not found: {stl_path}")
return None
try:
# Load STL using numpy-stl
mesh_data = stl_mesh.Mesh.from_file(str(stl_path))
# Extract vertices - STL stores 3 vertices per face
# mesh_data.vectors has shape (n_faces, 3, 3) - 3 vertices per face, 3 coords per vertex
n_faces = len(mesh_data.vectors)
# Flatten to get all vertices (with duplicates)
all_vertices = mesh_data.vectors.reshape(-1, 3)
# Create unique vertices and face indices
# For efficiency with large meshes, we deduplicate vertices
unique_vertices, inverse_indices = np.unique(
all_vertices, axis=0, return_inverse=True
)
# Reshape inverse indices to get face indices
faces = inverse_indices.reshape(n_faces, 3)
# Convert to float32 for OpenGL
vertices = unique_vertices.astype(np.float32)
faces = faces.astype(np.uint32)
logger.info(f"Loaded STL '{name}': {len(vertices)} vertices, {len(faces)} faces")
# Cache the result
_stl_cache[name] = (vertices, faces)
return vertices, faces
except Exception as e:
logger.error(f"Error loading STL '{name}': {e}")
return None
def load_all_stl_meshes():
"""Pre-load all STL meshes into cache"""
if not STL_AVAILABLE:
logger.warning("STL loading not available")
return False
success = True
for name in STL_FILES.keys():
result = load_stl_mesh(name)
if result is None:
success = False
return success
def get_stl_calibration():
"""
Load STL calibration offsets from config file.
Returns:
Dict mapping STL name to calibration dict with:
- offset: [x, y, z] translation offset in mm
- rotation: [rx, ry, rz] rotation in degrees (applied as Euler XYZ)
- scale: float scale factor (default 1.0)
"""
config_path = get_stl_directory() / 'stl_calibration.json'
# Default calibration (identity - no offset)
default_calibration = {
'base': {'offset': [0, 0, 0], 'rotation': [0, 0, 0], 'scale': 1.0},
'art1': {'offset': [0, 0, 0], 'rotation': [0, 0, 0], 'scale': 1.0},
'art2': {'offset': [0, 0, 0], 'rotation': [0, 0, 0], 'scale': 1.0},
'art3': {'offset': [0, 0, 0], 'rotation': [0, 0, 0], 'scale': 1.0},
'art4': {'offset': [0, 0, 0], 'rotation': [0, 0, 0], 'scale': 1.0},
'art5': {'offset': [0, 0, 0], 'rotation': [0, 0, 0], 'scale': 1.0},
'gripper': {'offset': [0, 0, 0], 'rotation': [0, 0, 0], 'scale': 1.0},
}
if config_path.exists():
try:
with open(config_path, 'r') as f:
loaded = json.load(f)
# Merge with defaults
for key in default_calibration:
if key in loaded:
default_calibration[key].update(loaded[key])
logger.info("Loaded STL calibration from config")
except Exception as e:
logger.warning(f"Error loading STL calibration: {e}")
return default_calibration
def euler_to_rotation_matrix(rx, ry, rz):
"""
Create rotation matrix from Euler angles (XYZ order, degrees).
Args:
rx, ry, rz: Rotation angles in degrees
Returns:
3x3 rotation matrix
"""
rx, ry, rz = np.radians([rx, ry, rz])
cx, sx = np.cos(rx), np.sin(rx)
cy, sy = np.cos(ry), np.sin(ry)
cz, sz = np.cos(rz), np.sin(rz)
# Rotation matrices
Rx = np.array([[1, 0, 0], [0, cx, -sx], [0, sx, cx]])
Ry = np.array([[cy, 0, sy], [0, 1, 0], [-sy, 0, cy]])
Rz = np.array([[cz, -sz, 0], [sz, cz, 0], [0, 0, 1]])
# Combined rotation (XYZ order)
return Rz @ Ry @ Rx
def transform_stl_vertices(vertices, transform_4x4, calibration=None):
"""
Apply transformation to STL vertices.
Args:
vertices: Nx3 array of vertex positions
transform_4x4: 4x4 homogeneous transformation matrix (from FK)
calibration: Optional dict with 'offset', 'rotation', 'scale'
Returns:
Transformed Nx3 vertex array
"""
verts = vertices.copy()
# Apply calibration first (in original STL local frame)
if calibration:
# Scale first
scale = calibration.get('scale', 1.0)
verts = verts * scale
# Offset in original STL coordinates (before rotation)
offset = calibration.get('offset', [0, 0, 0])
verts = verts + np.array(offset)
# Then rotate to align with robot frame
rot = calibration.get('rotation', [0, 0, 0])
if any(r != 0 for r in rot):
R_local = euler_to_rotation_matrix(*rot)
verts = verts @ R_local.T
# Apply FK transformation
R = transform_4x4[:3, :3]
t = transform_4x4[:3, 3]
verts = verts @ R.T + t
return verts.astype(np.float32)
# =============================================================================
# Mesh Generation Helpers for Realistic Robot Visualisation
# =============================================================================
def create_cylinder_mesh(radius, height, segments=16):
"""
Create a cylinder mesh centered at origin, extending along Z-axis.
Args:
radius: Cylinder radius
height: Cylinder height (extends from -height/2 to +height/2 on Z)
segments: Number of segments around circumference
Returns:
verts: Nx3 array of vertices
faces: Mx3 array of face indices
"""
theta = np.linspace(0, 2*np.pi, segments, endpoint=False)
# Bottom and top circle vertices
bottom_verts = np.zeros((segments, 3))
bottom_verts[:, 0] = radius * np.cos(theta)
bottom_verts[:, 1] = radius * np.sin(theta)
bottom_verts[:, 2] = -height / 2
top_verts = np.zeros((segments, 3))
top_verts[:, 0] = radius * np.cos(theta)
top_verts[:, 1] = radius * np.sin(theta)
top_verts[:, 2] = height / 2
# Centre points for caps
bottom_center = np.array([[0, 0, -height/2]])
top_center = np.array([[0, 0, height/2]])
# Combine vertices: bottom ring, top ring, bottom centre, top centre
verts = np.vstack([bottom_verts, top_verts, bottom_center, top_center])
faces = []
bottom_center_idx = 2 * segments
top_center_idx = 2 * segments + 1
for i in range(segments):
next_i = (i + 1) % segments
# Side faces (two triangles per quad)
# Bottom-left, bottom-right, top-right
faces.append([i, next_i, segments + next_i])
# Bottom-left, top-right, top-left
faces.append([i, segments + next_i, segments + i])
# Bottom cap
faces.append([bottom_center_idx, next_i, i])
# Top cap
faces.append([top_center_idx, segments + i, segments + next_i])
return np.array(verts, dtype=np.float32), np.array(faces, dtype=np.uint32)
def create_box_mesh(width, depth, height):
"""
Create a box mesh centered at origin.
Args:
width: Size along X-axis
depth: Size along Y-axis
height: Size along Z-axis
Returns:
verts: 8x3 array of vertices
faces: 12x3 array of face indices (triangles)
"""
w, d, h = width/2, depth/2, height/2
verts = np.array([
[-w, -d, -h], # 0: bottom-back-left
[ w, -d, -h], # 1: bottom-back-right
[ w, d, -h], # 2: bottom-front-right
[-w, d, -h], # 3: bottom-front-left
[-w, -d, h], # 4: top-back-left
[ w, -d, h], # 5: top-back-right
[ w, d, h], # 6: top-front-right
[-w, d, h], # 7: top-front-left
], dtype=np.float32)
faces = np.array([
# Bottom
[0, 2, 1], [0, 3, 2],
# Top
[4, 5, 6], [4, 6, 7],
# Front
[3, 7, 6], [3, 6, 2],
# Back
[0, 1, 5], [0, 5, 4],
# Left
[0, 4, 7], [0, 7, 3],
# Right
[1, 2, 6], [1, 6, 5],
], dtype=np.uint32)
return verts, faces
def create_dome_mesh(radius, segments=16, rings=8):
"""
Create a hemisphere/dome mesh (top half of sphere).
Args:
radius: Dome radius
segments: Number of segments around circumference
rings: Number of rings from base to top
Returns:
verts: Nx3 array of vertices
faces: Mx3 array of face indices
"""
verts = []
# Generate vertices ring by ring from bottom to top
for i in range(rings + 1):
phi = (np.pi / 2) * (i / rings) # 0 to pi/2
z = radius * np.sin(phi)
ring_radius = radius * np.cos(phi)
for j in range(segments):
theta = 2 * np.pi * j / segments
x = ring_radius * np.cos(theta)
y = ring_radius * np.sin(theta)
verts.append([x, y, z])
verts = np.array(verts, dtype=np.float32)
faces = []
for i in range(rings):
for j in range(segments):
next_j = (j + 1) % segments
# Current ring indices
curr = i * segments + j
curr_next = i * segments + next_j
# Next ring indices
upper = (i + 1) * segments + j
upper_next = (i + 1) * segments + next_j
# Two triangles per quad (except at the pole)
if i < rings - 1:
faces.append([curr, curr_next, upper_next])
faces.append([curr, upper_next, upper])
else:
# At the top, triangles converge
faces.append([curr, curr_next, upper])
return verts, np.array(faces, dtype=np.uint32)
def transform_mesh(verts, position, rotation_matrix=None):
"""
Transform mesh vertices by rotation and translation.
Args:
verts: Nx3 array of vertices
position: [x, y, z] translation
rotation_matrix: 3x3 rotation matrix (optional)
Returns:
Transformed vertices
"""
transformed = verts.copy()
if rotation_matrix is not None:
transformed = transformed @ rotation_matrix.T
transformed += np.array(position)
return transformed
def rotation_matrix_from_vectors(vec1, vec2):
"""
Create rotation matrix that rotates vec1 to vec2.
Args:
vec1: Source vector (will be normalized)
vec2: Target vector (will be normalized)
Returns:
3x3 rotation matrix
"""
a = np.array(vec1, dtype=np.float64)
b = np.array(vec2, dtype=np.float64)
a_norm = np.linalg.norm(a)
b_norm = np.linalg.norm(b)
if a_norm < 1e-10 or b_norm < 1e-10:
return np.eye(3)
a = a / a_norm
b = b / b_norm
# Check if vectors are parallel
dot = np.dot(a, b)
if dot > 0.9999:
return np.eye(3)
if dot < -0.9999:
# 180 degree rotation - find perpendicular axis
perp = np.array([1, 0, 0]) if abs(a[0]) < 0.9 else np.array([0, 1, 0])
perp = perp - np.dot(perp, a) * a
perp = perp / np.linalg.norm(perp)
return 2 * np.outer(perp, perp) - np.eye(3)
# Rodrigues' rotation formula
v = np.cross(a, b)
s = np.linalg.norm(v)
c = dot
vx = np.array([
[0, -v[2], v[1]],
[v[2], 0, -v[0]],
[-v[1], v[0], 0]
])
R = np.eye(3) + vx + vx @ vx * ((1 - c) / (s * s + 1e-10))
return R
class Robot3DCanvas(gl.GLViewWidget):
"""
PyQtGraph OpenGL canvas for visualizing robot arm and trajectory
Provides smooth mouse controls and better visual clarity
"""
def __init__(self, parent=None, width=800, height=700, dpi=100):
"""
Initialize 3D robot visualization canvas with OpenGL rendering
Args:
parent: Parent Qt widget
width: Widget width (if < 100, treated as inches and multiplied by dpi; otherwise pixels)
height: Widget height (if < 100, treated as inches and multiplied by dpi; otherwise pixels)
dpi: Dots per inch for converting inches to pixels (default: 100)
"""
super().__init__(parent)
self.setParent(parent)
# Convert inches to pixels if needed (for matplotlib API compatibility)
# If width/height < 100, assume it's in inches (like matplotlib figsize)
if width < 100:
width_px = int(width * dpi)
else:
width_px = int(width)
if height < 100:
height_px = int(height * dpi)
else:
height_px = int(height)
# Set widget size
self.resize(width_px, height_px)
# Visualisation state
self.current_joint_positions = None
self.trajectory_points = []
self.trajectory_timestamps = []
# Display options
self.show_robot = True
self.show_trajectory = True
self.show_base_frame = True
self.show_workspace = False
self.show_grid = True
self.show_labels = False
self.auto_rotate = False
self.rotation_angle = 45 # Current azimuth for auto-rotate
self.show_joint_frames = False
self._joint_frame_items = [] # GL items for joint coordinate frames
# STL visualisation options
self.use_stl = STL_AVAILABLE # Use STL meshes if available
self.stl_loaded = False
self.stl_calibration = get_stl_calibration()
# Colour schemes (RGBA format for PyQtGraph)
# ThorRR robot colours - orange body with contrasting accents
self.colors_active = {
'body': (1.0, 0.55, 0.2, 1.0), # ThorRR orange
'body_dark': (0.95, 0.48, 0.12, 1.0), # Darker orange
'joint': (0.47, 0.47, 0.47, 1.0), # Medium grey for joint rings
'accent': (0.38, 0.38, 0.38, 1.0), # Dark grey accents
'tcp': (1.0, 0.25, 0.25, 1.0), # Red TCP
'gripper': (0.57, 0.57, 0.57, 1.0), # Medium grey gripper
# Legacy keys for compatibility
'link': (1.0, 0.55, 0.2, 1.0),
'base': (0.42, 0.42, 0.42, 1.0)
}
self.colors_inactive = {
'body': (0.85, 0.55, 0.35, 0.8), # Muted orange
'body_dark': (0.78, 0.48, 0.28, 0.8),
'joint': (0.5, 0.5, 0.5, 0.7),
'accent': (0.4, 0.4, 0.4, 0.7),
'tcp': (0.75, 0.45, 0.45, 0.7),
'gripper': (0.6, 0.6, 0.6, 0.7),
# Legacy keys
'link': (0.85, 0.55, 0.35, 0.8),
'base': (0.45, 0.45, 0.45, 0.7)
}
# PERFORMANCE OPTIMIZATION: Dirty flag pattern
self._is_dirty = True # Needs redraw
self._last_joint_angles = None # Cache last angles to detect changes
self._last_trajectory_length = 0 # Cache trajectory length
self._last_options = None # Cache last display options to detect changes
self._render_lock = threading.Lock() # Thread-safe rendering
self._pending_update = False # Debounce rapid updates
# FK calculation cache (avoid redundant calculations)
self._fk_cache = {}
self._fk_cache_lock = threading.Lock()
# PERFORMANCE OPTIMIZATION: Cache workspace envelope (only changes with DH params)
self._workspace_envelope_cache = None
# PERFORMANCE OPTIMIZATION: Persistent mesh items (reuse instead of recreate)
self._persistent_mesh_items = {} # name -> GLMeshItem
self._persistent_meshes_initialized = False
self._grid_initialized = False
self._tcp_mesh_item = None # Separate TCP indicator
self._base_frame_initialized = False # Base frame is static
# Base-in-world transform (from coordinate_frames.json base frame)
self._base_world_transform = np.eye(4)
# Active tool offset relative to TCP flange (e.g. gripper Z length)
self._tool_offset = np.eye(4)
# Force reload DH parameters at startup to ensure latest values
fk.reload_dh_parameters()
logger.info("DH parameters loaded at visualizer startup")
# Graphics items (will be created/updated as needed)
self.robot_arm_item = None
self.robot_joints_item = None
self.tcp_item = None
self.base_item = None
self.trajectory_item = None
self.sequence_preview_item = None # Separate GL item for sequence preview path
self._sequence_preview_points = None # Cached dense TCP points from sequence
self.grid_item = None
self.grid_label_items = [] # Coordinate labels on grid
self.base_frame_items = []
self.tcp_frame_items = []
self.tool_tip_items = [] # GL items for tool tip frame visualization
self.workspace_item = None
self._workspace_mesh_item = None # Cached accurate workspace mesh
self.tool_direction_item = None
self.base_front_item = None
self.robot_mesh_items = [] # List of 3D mesh items for realistic robot
# Setup initial view
self.setup_3d_view()
# Pre-load STL meshes if available
if self.use_stl:
self.stl_loaded = load_all_stl_meshes()
if self.stl_loaded:
logger.info("STL meshes loaded successfully")
else:
logger.warning("Some STL meshes failed to load, falling back to primitives")
self.use_stl = False
# Show home position immediately
self.show_home_position()
logger.info("3D robot canvas initialised with PyQtGraph OpenGL rendering")
def setup_3d_view(self):
"""Setup 3D view with camera position, grid, and axes"""
# Get workspace envelope for setting limits
workspace = fk.compute_workspace_envelope()
max_reach = workspace['radius']
z_max = workspace['z_max']
# Set camera distance to see whole workspace
# PyQtGraph uses distance from centre
distance = max_reach * 2.5
# Set camera centre point above the base (not at origin)
# This shifts the view focus up so the robot isn't centred vertically
center_z = z_max * 0.35 # Focus at ~35% of max height
self.camera_center = pg.Vector(0, 0, center_z)
# Set camera position (isometric view)
# elevation=30°, azimuth=45°, centered above base
self.setCameraPosition(distance=distance, elevation=30, azimuth=45)
self.opts['center'] = self.camera_center
# Add grid at Z=0 (base plane)
if self.show_grid:
if self.grid_item:
self.removeItem(self.grid_item)
# Clear old grid labels
for item in self.grid_label_items:
if item is not None:
try:
self.removeItem(item)
except Exception:
pass
self.grid_label_items = []
# Create grid - snap size to multiple of 2*spacing so lines pass through origin
grid_spacing = 50
grid_size_raw = max_reach * 2.5
grid_size = int(np.ceil(grid_size_raw / (grid_spacing * 2)) * (grid_spacing * 2))
self.grid_item = gl.GLGridItem()
self.grid_item.setSize(grid_size, grid_size)
self.grid_item.setSpacing(grid_spacing, grid_spacing)
self.grid_item.setColor(pg.mkColor(50, 50, 50, 200)) # Dark grey grid
self.addItem(self.grid_item)
# Thick axis lines along X=0, Y=0 spanning the full grid
grid_half = grid_size / 2
axis_line_width = 3
axis_line_alpha = 0.6
# X-axis line (along X at Y=0, Z=0)
x_axis_line = gl.GLLinePlotItem(
pos=np.array([[-grid_half, 0, 0], [grid_half, 0, 0]]),
color=(0.8, 0.0, 0.0, axis_line_alpha),
width=axis_line_width,
antialias=True
)
self.addItem(x_axis_line)
self.grid_label_items.append(x_axis_line)
# Y-axis line (along Y at X=0, Z=0)
y_axis_line = gl.GLLinePlotItem(
pos=np.array([[0, -grid_half, 0], [0, grid_half, 0]]),
color=(0.0, 0.6, 0.0, axis_line_alpha),
width=axis_line_width,
antialias=True
)
self.addItem(y_axis_line)
self.grid_label_items.append(y_axis_line)
# Add coordinate labels along axes at round multiples of label_spacing
label_spacing = 100 # Label every 100mm
max_label = (int(grid_size / 2) // label_spacing) * label_spacing
# X-axis labels (along positive and negative X)
for x in range(-max_label, max_label + 1, label_spacing):
if x == 0:
continue # Skip origin
text_item = gl.GLTextItem(
pos=np.array([x, -30, 0]),
text=f'{x}',
color=pg.mkColor(0, 0, 0, 255),
font=QtGui.QFont('Arial', 8)
)
self.addItem(text_item)
self.grid_label_items.append(text_item)
# Y-axis labels (along positive and negative Y)
for y in range(-max_label, max_label + 1, label_spacing):
if y == 0:
continue # Skip origin
text_item = gl.GLTextItem(
pos=np.array([-30, y, 0]),
text=f'{y}',
color=pg.mkColor(0, 0, 0, 255),
font=QtGui.QFont('Arial', 8)
)
self.addItem(text_item)
self.grid_label_items.append(text_item)
# Origin label
origin_label = gl.GLTextItem(
pos=np.array([-40, -40, 0]),
text='0',
color=pg.mkColor(0, 0, 0, 255),
font=QtGui.QFont('Arial', 8)
)
self.addItem(origin_label)
self.grid_label_items.append(origin_label)
# Axis labels
x_label = gl.GLTextItem(
pos=np.array([max_label + 20, 0, 0]),
text='X+',
color=pg.mkColor(200, 0, 0, 255),
font=QtGui.QFont('Arial', 10, QtGui.QFont.Bold)
)
self.addItem(x_label)
self.grid_label_items.append(x_label)
y_label = gl.GLTextItem(
pos=np.array([0, max_label + 20, 0]),
text='Y+',
color=pg.mkColor(0, 150, 0, 255),
font=QtGui.QFont('Arial', 10, QtGui.QFont.Bold)
)
self.addItem(y_label)
self.grid_label_items.append(y_label)
# Set background colour to white
self.setBackgroundColor('w')
def set_base_world_transform(self, transform: np.ndarray):
"""Set the base-in-world transform for rendering the robot at its
mounted position/orientation. Invalidates cached base frame visuals."""
self._base_world_transform = np.array(transform, dtype=np.float64)
self._base_frame_initialized = False # Force redraw of base frame axes
self._last_joint_angles = None # Force next periodic update to redraw
def set_tool_offset(self, transform: np.ndarray):
"""Set the active tool offset (relative to TCP flange).
The TCP indicator and frame axes will be drawn at the tool tip."""
self._tool_offset = np.array(transform, dtype=np.float64)
self._last_joint_angles = None # Force next periodic update to redraw
def show_home_position(self):
"""Display robot at home position (all joints at 0)"""
# Force reload DH parameters to ensure latest values are used
fk.reload_dh_parameters()
# Invalidate all caches since DH parameters may have changed
self.invalidate_workspace_cache()
with self._fk_cache_lock:
self._fk_cache.clear()
logger.info("DH parameters reloaded and caches cleared")
# Use persistent grid
if self.show_grid:
self._ensure_grid_initialized()
# Show robot at home position (all joints at 0)
home_angles = (0, 0, 0, 0, 0, 0)
home_positions = fk.compute_all_joint_positions(*home_angles)
self.current_joint_positions = home_positions
# DEBUG: Log computed positions
logger.info(f"Home positions computed:")
for i, pos in enumerate(home_positions):
logger.info(f" [{i}]: X={pos[0]:.1f}, Y={pos[1]:.1f}, Z={pos[2]:.1f}")
# Draw robot using fast path if STL available
if self.use_stl and self.stl_loaded:
self._initialize_persistent_meshes()
self._ensure_meshes_in_scene()
self._update_robot_transforms(home_angles)
else:
self.draw_robot_arm(home_positions, active=False, joint_angles=home_angles)
# Draw base coordinate frame (XYZ axes at origin)
self.draw_base_frame(length=100)
# Draw TCP frame at home position
self.draw_tcp_frame(0, 0, 0, 0, 0, 0, length=50)
def preview_dh_parameters(self, dh_params):
"""
Preview robot with custom DH parameters (for live editing).
Args:
dh_params: List of dicts with DH parameters for each link
"""
# Apply DH parameters to FK module temporarily
fk.apply_dh_parameters(dh_params)
# Invalidate all caches since parameters changed
self.invalidate_workspace_cache()
with self._fk_cache_lock:
self._fk_cache.clear()
# Remove old persistent meshes and force re-creation with new DH transforms
self._remove_meshes_from_scene()
self._persistent_meshes_initialized = False
self._base_frame_initialized = False
# Re-initialize and update with home position using new DH parameters
home_angles = (0, 0, 0, 0, 0, 0)
if self.use_stl and self.stl_loaded:
self._initialize_persistent_meshes()
self._ensure_meshes_in_scene()
self._update_robot_transforms(home_angles)
self.draw_tcp_frame(*home_angles, length=50)
else:
home_positions = fk.compute_all_joint_positions(*home_angles)
self.current_joint_positions = home_positions
self._draw_robot_primitives(home_positions, active=False)
if self.show_base_frame:
self.draw_base_frame()
logger.debug("DH parameters preview updated")
def update_robot(self, joint_angles):
"""
Update robot visualization directly from joint angles (no position history needed).
Args:
joint_angles: List/tuple of 6 joint angles [q1, q2, q3, q4, q5, q6] in degrees
"""
angles = tuple(joint_angles[:6])
if self.show_robot and self.use_stl and self.stl_loaded:
self._initialize_persistent_meshes()
self._ensure_meshes_in_scene()
self._update_robot_transforms(angles)
self.draw_tcp_frame(*angles, length=50)
elif self.show_robot:
current_positions = self._compute_fk_cached(*angles)
self.current_joint_positions = current_positions
self._draw_robot_primitives(current_positions, active=True)
if self.show_joint_frames:
self.draw_joint_frames(*angles)
else:
self._clear_joint_frames()
if self.show_workspace:
self.draw_workspace_limits()
elif self._workspace_mesh_item is not None and self._workspace_mesh_item in self.items:
try:
self.removeItem(self._workspace_mesh_item)
except Exception:
pass
def clear_all_items(self):
"""Remove all graphics items from the view"""
# Clear all items (including grid)
items_to_remove = [
self.robot_arm_item,
self.robot_joints_item,
self.tcp_item,
self.base_item,
self.trajectory_item,
self.sequence_preview_item,
self.tool_direction_item,
self.base_front_item,
self.workspace_item,
self._workspace_mesh_item,
self.grid_item
]
for item in items_to_remove:
if item is not None:
self.removeItem(item)
# Clear robot mesh items (3D body parts)
for item in self.robot_mesh_items:
if item is not None:
try:
self.removeItem(item)
except Exception:
pass
self.robot_mesh_items = []
# Clear grid label items
for item in self.grid_label_items:
if item is not None:
try:
self.removeItem(item)
except Exception:
pass
self.grid_label_items = []
# Clear base frame items
for item in self.base_frame_items:
if item is not None:
self.removeItem(item)
self.base_frame_items = []
# Clear TCP frame items
for item in self.tcp_frame_items:
if item is not None:
self.removeItem(item)
self.tcp_frame_items = []
# Clear tool tip items
for item in self.tool_tip_items:
if item is not None:
try:
self.removeItem(item)
except Exception:
pass
self.tool_tip_items = []
# Reset references
self.robot_arm_item = None
self.robot_joints_item = None
self.tcp_item = None
self.base_item = None
self.trajectory_item = None
self.sequence_preview_item = None
self._sequence_preview_points = None
self.tool_direction_item = None
self.base_front_item = None
self.workspace_item = None
self._workspace_mesh_item = None
self.grid_item = None
def draw_robot_arm(self, joint_positions, active=True, joint_angles=None):
"""
Draw ThorRR robot arm - dispatches to STL or primitive rendering.
Args:
joint_positions: List of 7 tuples [(x,y,z), ...] for joints
active: If True, use active colors; if False, use inactive (gray)
joint_angles: Optional tuple (q1,q2,q3,q4,q5,q6) for STL rendering
"""
if joint_positions is None or len(joint_positions) < 7:
return
# Try STL rendering if available
if self.use_stl and self.stl_loaded and joint_angles is not None:
self._draw_robot_stl(joint_angles, active)
return
# Fall back to primitive rendering
self._draw_robot_primitives(joint_positions, active)
def _draw_robot_stl(self, joint_angles, active=True):
"""
Draw ThorRR robot using actual STL mesh files.
Args:
joint_angles: Tuple (q1, q2, q3, q4, q5, q6) in degrees
active: If True, use active colors; if False, use inactive (gray)
"""
q1, q2, q3, q4, q5, q6 = joint_angles
B = self._base_world_transform
# Get cumulative transforms for each joint (in base frame), then apply base-in-world
raw_transforms = fk.compute_all_joint_transforms(q1, q2, q3, q4, q5, q6)
transforms = [B @ T for T in raw_transforms]
# Clear existing mesh items
for item in self.robot_mesh_items:
if item is not None:
try:
self.removeItem(item)
except Exception:
pass
self.robot_mesh_items = []
# Select colour scheme
colors = self.colors_active if active else self.colors_inactive
# STL to transform mapping:
# base -> transforms[0] (identity - fixed at origin)
# art1 -> transforms[1] (after J1)
# art2 -> transforms[2] (after J1+J2)
# art3 -> transforms[3] (after J1+J2+J3)
# art4 -> transforms[4] (after J1+J2+J3+J4)
# art5 -> transforms[5] (after J1+J2+J3+J4+J5)
# gripper -> transforms[6] (after all joints - TCP frame)
stl_mapping = [
('base', 0, colors['accent']),
('art1', 1, colors['body']),
('art2', 2, colors['body']),