@@ -10,6 +10,7 @@ def __init__(self, start_node, end_node, label=""):
1010 self .label = label # New attribute
1111
1212 def draw (self , screen , offset_x = 0 , offset_y = 0 , zoom = 1.0 ):
13+ # Use local variables to avoid repeated calculations and excessive allocations
1314 start_pos = (
1415 int ((self .start_node .get_output_pos ()[0 ] - offset_x ) * zoom ),
1516 int ((self .start_node .get_output_pos ()[1 ] - offset_y ) * zoom )
@@ -22,28 +23,33 @@ def draw(self, screen, offset_x=0, offset_y=0, zoom=1.0):
2223 thickness = max (1 , int (2 * zoom ))
2324 color = GREEN if self .marked else WHITE
2425
25- # Draw label in a rectangle if present
2626 label_rect = None
2727 label_box_halfwidth = 0
2828 label_box_halfheight = 0
2929 label_center = None
30+
31+ # --- Optimization: Only create font ONCE per draw call, not per label ---
32+ # Use a static font cache for each font size
33+ if not hasattr (self , "_font_cache" ):
34+ self ._font_cache = {}
35+
3036 if self .label :
31- # Font size decreases with zoom, but not too fast (clamped)
3237 min_font_size = 10
3338 max_font_size = 28
3439 font_size = int (18 * max (0.7 , min (1.0 , zoom )))
3540 font_size = max (min_font_size , min (max_font_size , font_size ))
36- font = pygame .font .Font (None , font_size )
41+ # Use cached font object
42+ if font_size not in self ._font_cache :
43+ self ._font_cache [font_size ] = pygame .font .Font (None , font_size )
44+ font = self ._font_cache [font_size ]
3745 label_surf = font .render (self .label , True , color )
38- # Padding is reduced for less box size at low zoom
3946 max_pad = 12
4047 pad_scale = max (0.5 , min (1.0 , zoom ))
4148 label_padding_x = int (max_pad * pad_scale )
4249 label_padding_y = int (3 * pad_scale )
4350 rect_width = label_surf .get_width () + 2 * label_padding_x
4451 rect_height = label_surf .get_height () + 2 * label_padding_y
4552
46- # Midpoint of the line
4753 mid_x = (start_pos [0 ] + end_pos [0 ]) // 2
4854 mid_y = (start_pos [1 ] + end_pos [1 ]) // 2
4955
@@ -54,13 +60,10 @@ def draw(self, screen, offset_x=0, offset_y=0, zoom=1.0):
5460 label_box_halfwidth = rect_width // 2
5561 label_box_halfheight = rect_height // 2
5662
57- # Draw filled rectangle (background) directly on the screen to cover the line
5863 bg_color = (32 , 32 , 32 )
5964 pygame .draw .rect (screen , bg_color , label_rect , border_radius = 6 )
60- # Draw border (always thin, regardless of zoom)
6165 border_width = 1
6266 pygame .draw .rect (screen , color , label_rect , width = border_width , border_radius = 6 )
63- # Blit label text centered
6467 label_text_rect = label_surf .get_rect (center = label_rect .center )
6568 screen .blit (label_surf , label_text_rect )
6669
0 commit comments