"""
HVAC Sheet Metal Duct Transition Generator
Generates rectangular-to-rectangular duct transitions with offsets,
computes 3D geometry, flattens panels, and exports to DXF with seam allowances.
"""
import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import numpy as np
import ezdxf
from ezdxf import colors
from dataclasses import dataclass
from typing import List, Tuple
import math
import os
@dataclass
class RectDuct:
"""Rectangular duct dimensions"""
width: float # inches
height: float # inches
@dataclass
class Offset:
"""Offset in X and Y directions"""
x: float # inches
y: float # inches
@dataclass
class Transition:
"""Transition parameters"""
start_duct: RectDuct
end_duct: RectDuct
length: float # inches (along centerline)
offset: Offset
class Point3D:
"""3D Point"""
def __init__(self, x: float, y: float, z: float):
self.x = x
self.y = y
self.z = z
def to_tuple(self):
return (self.x, self.y, self.z)
def distance_to(self, other):
return math.sqrt((self.x - other.x)**2 +
(self.y - other.y)**2 +
(self.z - other.z)**2)
class Panel:
"""Represents a panel with 3D corners and flattened 2D shape"""
def __init__(self, name: str, corners_3d: List[Point3D]):
self.name = name
self.corners_3d = corners_3d
self.corners_2d = []
self.seam_allowance_2d = []
self.tabs_2d = []
class TransitionGenerator:
"""Generates transition geometry and flattened panels"""
def __init__(self, transition: Transition):
self.transition = transition
self.panels = []
def generate(self):
"""Generate all panels for the transition"""
# Define 8 corners of the transition (4 at start, 4 at end)
start_corners = self._get_rectangle_corners(
self.transition.start_duct, z=0, offset_x=0, offset_y=0
)
end_corners = self._get_rectangle_corners(
self.transition.end_duct,
z=self.transition.length,
offset_x=self.transition.offset.x,
offset_y=self.transition.offset.y
)
# Create 4 panels (top, bottom, left, right)
# Bottom panel
bottom_panel = Panel("Bottom", [
start_corners[0], # front-left
start_corners[1], # front-right
end_corners[1], # front-right (end)
end_corners[0] # front-left (end)
])
# Top panel
top_panel = Panel("Top", [
start_corners[3], # back-left
end_corners[3], # back-left (end)
end_corners[2], # back-right (end)
start_corners[2] # back-right
])
# Left panel
left_panel = Panel("Left", [
start_corners[0], # front-left
end_corners[0], # front-left (end)
end_corners[3], # back-left (end)
start_corners[3] # back-left
])
# Right panel
right_panel = Panel("Right", [
start_corners[1], # front-right
start_corners[2], # back-right
end_corners[2], # back-right (end)
end_corners[1] # front-right (end)
])
self.panels = [bottom_panel, top_panel, left_panel, right_panel]
# Flatten each panel
for panel in self.panels:
self._flatten_panel(panel)
self._add_seam_allowances(panel)
self._add_connection_tabs(panel)
def _get_rectangle_corners(self, duct: RectDuct, z: float,
offset_x: float, offset_y: float) -> List[Point3D]:
"""Get 4 corners of a rectangle at given z-position with offset"""
hw = duct.width / 2.0
hh = duct.height / 2.0
return [
Point3D(-hw + offset_x, -hh + offset_y, z), # front-left
Point3D(hw + offset_x, -hh + offset_y, z), # front-right
Point3D(hw + offset_x, hh + offset_y, z), # back-right
Point3D(-hw + offset_x, hh + offset_y, z) # back-left
]
def _flatten_panel(self, panel: Panel):
"""Flatten a 3D panel to 2D using triangulation method"""
corners = panel.corners_3d
if len(corners) != 4:
raise ValueError("Panel must have exactly 4 corners")
# Use first point as origin
p0 = corners[0]
panel.corners_2d.append((0, 0))
# Second point along X-axis
d01 = p0.distance_to(corners[1])
panel.corners_2d.append((d01, 0))
# Third point using triangulation
d02 = p0.distance_to(corners[2])
d12 = corners[1].distance_to(corners[2])
# Law of cosines to find angle
cos_angle = (d01**2 + d02**2 - d12**2) / (2 * d01 * d02)
cos_angle = max(-1, min(1, cos_angle)) # Clamp to valid range
angle = math.acos(cos_angle)
x2 = d02 * math.cos(angle)
y2 = d02 * math.sin(angle)
panel.corners_2d.append((x2, y2))
# Fourth point using triangulation from first and third points
d03 = p0.distance_to(corners[3])
d23 = corners[2].distance_to(corners[3])
# Use point 0 and point 2 to triangulate point 3
cos_angle_03 = (d02**2 + d03**2 - d23**2) / (2 * d02 * d03)
cos_angle_03 = max(-1, min(1, cos_angle_03))
angle_03 = math.acos(cos_angle_03)
# Angle from X-axis to point 2
angle_02 = angle
# Angle from X-axis to point 3
angle_final = angle_02 + angle_03
x3 = d03 * math.cos(angle_final)
y3 = d03 * math.sin(angle_final)
panel.corners_2d.append((x3, y3))
def _add_seam_allowances(self, panel: Panel):
"""Add 1-inch Pittsburgh seam allowances to appropriate edges"""
seam_allowance = 1.0 # inches
# Add seam allowance to edges 1 and 3 (vertical edges)
# For simplicity, we'll add to the right and left edges
corners = panel.corners_2d
# Right edge seam (between point 1 and 2)
p1 = np.array(corners[1])
p2 = np.array(corners[2])
edge_vec = p2 - p1
edge_length = np.linalg.norm(edge_vec)
edge_unit = edge_vec / edge_length if edge_length > 0 else np.array([0, 1])
# Perpendicular vector (outward)
perp = np.array([edge_unit[1], -edge_unit[0]])
# Create seam allowance rectangle
s1 = p1 + perp * seam_allowance
s2 = p2 + perp * seam_allowance
panel.seam_allowance_2d.append({
'edge': 'right',
'points': [tuple(p1), tuple(p2), tuple(s2), tuple(s1)]
})
# Left edge seam (between point 0 and 3)
p0 = np.array(corners[0])
p3 = np.array(corners[3])
edge_vec = p3 - p0
edge_length = np.linalg.norm(edge_vec)
edge_unit = edge_vec / edge_length if edge_length > 0 else np.array([0, 1])
# Perpendicular vector (outward, opposite direction)
perp = np.array([-edge_unit[1], edge_unit[0]])
s0 = p0 + perp * seam_allowance
s3 = p3 + perp * seam_allowance
panel.seam_allowance_2d.append({
'edge': 'left',
'points': [tuple(p0), tuple(p3), tuple(s3), tuple(s0)]
})
def _add_connection_tabs(self, panel: Panel):
"""Add 0.5-inch drive connection tabs to top and bottom edges"""
tab_depth = 0.5 # inches
tab_width = 2.0 # inches
tab_spacing = 6.0 # inches
corners = panel.corners_2d
# Bottom edge (between point 0 and 1)
self._add_tabs_to_edge(panel, corners[0], corners[1],
tab_depth, tab_width, tab_spacing, 'bottom')
# Top edge (between point 3 and 2)
self._add_tabs_to_edge(panel, corners[3], corners[2],
tab_depth, tab_width, tab_spacing, 'top')
def _add_tabs_to_edge(self, panel: Panel, p1: Tuple[float, float],
p2: Tuple[float, float], depth: float,
width: float, spacing: float, edge_name: str):
"""Add tabs along an edge"""
p1 = np.array(p1)
p2 = np.array(p2)
edge_vec = p2 - p1
edge_length = np.linalg.norm(edge_vec)
edge_unit = edge_vec / edge_length if edge_length > 0 else np.array([1, 0])
# Perpendicular vector (outward)
perp = np.array([-edge_unit[1], edge_unit[0]])
# Calculate number of tabs
num_tabs = max(2, int(edge_length / spacing))
actual_spacing = edge_length / num_tabs
tabs = []
for i in range(num_tabs):
# Tab center position along edge
t = (i + 0.5) / num_tabs
center = p1 + edge_vec * t
# Tab corners
half_width = width / 2.0
tab_p1 = center - edge_unit * half_width
tab_p2 = center + edge_unit * half_width
tab_p3 = tab_p2 + perp * depth
tab_p4 = tab_p1 + perp * depth
tabs.append({
'center': tuple(center),
'points': [tuple(tab_p1), tuple(tab_p2),
tuple(tab_p3), tuple(tab_p4)]
})
panel.tabs_2d.append({
'edge': edge_name,
'tabs': tabs
})
class DXFExporter:
"""Export panels to DXF format"""
def __init__(self, panels: List[Panel], output_dir: str, base_name: str):
self.panels = panels
self.output_dir = output_dir
self.base_name = base_name
def export(self):
"""Export all panels to DXF files"""
for i, panel in enumerate(self.panels):
filename = os.path.join(
self.output_dir,
f"{self.base_name}_{panel.name}.dxf"
)
self._export_panel(panel, filename)
def _export_panel(self, panel: Panel, filename: str):
"""Export a single panel to DXF"""
doc = ezdxf.new('R2010')
msp = doc.modelspace()
# Create layers
doc.layers.new('CUT', dxfattribs={'color': colors.RED})
doc.layers.new('SCORE', dxfattribs={'color': colors.BLUE})
doc.layers.new('FOLD', dxfattribs={'color': colors.GREEN})
# Draw main panel outline (CUT layer)
corners = panel.corners_2d + [panel.corners_2d[0]] # Close the polygon
for i in range(len(corners) - 1):
msp.add_line(corners[i], corners[i+1],
dxfattribs={'layer': 'CUT'})
# Draw seam allowances
for seam in panel.seam_allowance_2d:
points = seam['points'] + [seam['points'][0]]
for i in range(len(points) - 1):
msp.add_line(points[i], points[i+1],
dxfattribs={'layer': 'CUT'})
# Add fold line at the base of seam
msp.add_line(seam['points'][0], seam['points'][1],
dxfattribs={'layer': 'FOLD'})
# Draw tabs
for tab_group in panel.tabs_2d:
for tab in tab_group['tabs']:
points = tab['points'] + [tab['points'][0]]
for i in range(len(points) - 1):
msp.add_line(points[i], points[i+1],
dxfattribs={'layer': 'CUT'})
# Add fold line at base of tab
msp.add_line(tab['points'][0], tab['points'][1],
dxfattribs={'layer': 'FOLD'})
# Add text label
center_x = sum(p[0] for p in panel.corners_2d) / 4
center_y = sum(p[1] for p in panel.corners_2d) / 4
msp.add_text(
panel.name,
dxfattribs={
'layer': 'CUT',
'height': 1.0
}
).set_pos((center_x, center_y), align='MIDDLE_CENTER')
# Save DXF
doc.saveas(filename)
class TransitionGUI:
"""GUI for inputting transition parameters"""
def __init__(self, root):
self.root = root
self.root.title("HVAC Duct Transition Generator")
self.root.geometry("500x600")
self._create_widgets()