Loading files
This file is pinned to the selected release. Download the original to open it in your design tool.
10cd31badThis file is pinned to the selected release. Download the original to open it in your design tool.
# Copyright 2024 Tobias Senti
# Solderpad Hardware License, Version 0.51, see LICENSE for details.
# SPDX-License-Identifier: SHL-0.51
import argparse
import datetime
import json
import os
import subprocess
from kiutils.board import Board
from kiutils.footprint import Footprint as KiFootprint
from kiutils.items.common import Effects
from kiutils.items.common import Font
from kiutils.items.common import Net as KiNet
from kiutils.items.common import Position as KiPosition
from kiutils.items.brditems import LayerToken as BrdLayerToken
from kiutils.items.brditems import Segment as BrdSegment
from kiutils.items.brditems import Stackup
from kiutils.items.brditems import StackupLayer
from kiutils.items.brditems import PlotSettings
from kiutils.items.brditems import Via as BrdVia
from kiutils.items.gritems import GrRect
from kiutils.items.gritems import GrText
from kiutils.items.fpitems import FpRect
from kiutils.items.fpitems import FpText
from lef_def_parser import DefParser
from lef_def_parser.def_parser import *
stamp = 'Generated by https://github.com/TheMightyDuckOfDoom/liberty74 ' + subprocess.check_output(['git', 'describe', '--always']).strip().decode()
stamp += ' ' + datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S')
output_dir = './out/'
GEN_FOLLOWPIN_VIAS = False
# Parse arguments
parser = argparse.ArgumentParser(
prog='def2pcb',
description='Generates a .kicad_pcb file from .def'
)
parser.add_argument('def_files', type=str, help='.def files', nargs='+', default=[])
args = parser.parse_args()
# Filenames
def_file_path = args.def_files[0]
filename = os.path.splitext(os.path.basename(def_file_path))[0]
pcb_file_path = output_dir + filename + '.kicad_pcb'
# Parse DEF
print('Parsing ' + def_file_path + '...')
def_parser = DefParser(def_file_path)
def_parser.parse()
scale = float(def_parser.scale)
# Parse merge DEF files
merge_def_parsers = []
for merge_def_file in args.def_files[1:]:
print('Parsing ' + merge_def_file + '...')
merge_def_parsers.append(DefParser(merge_def_file))
merge_def_parsers[-1].parse()
# Merge DEF files
updated_components = []
merged_nets = []
merged_nets.extend(def_parser.nets)
if def_parser.components is not None:
for component in def_parser.components:
# Loop over all merge DEF files
found_match = False
for merge_def in merge_def_parsers:
# Check if the component macro matches the merge DEF file
if component.macro == merge_def.design_name:
found_match = True
print("Found matching macro " + component.macro + " for " + component.name)
merge_def_width = merge_def.diearea[1][0] - merge_def.diearea[0][0]
merge_def_height = merge_def.diearea[1][1] - merge_def.diearea[0][1]
# Add all component in the merge DEF file to the main DEF files components
if merge_def.components is not None:
for merge_component in merge_def.components:
# Copy component
new_component = Component(component.name + '_' + merge_component.name)
new_component.macro = merge_component.macro
new_component.location_type = merge_component.location_type
if(component.orient == 'N'):
# Same orientation
new_component.orient = merge_component.orient
new_component.location[0] = merge_component.location[0] + component.location[0]
new_component.location[1] = merge_component.location[1] + component.location[1]
else:
# Flip orientation
new_component.orient = 'S_TR' if merge_component.orient == 'N' else 'N_TR'
new_component.location[0] = merge_def_width - merge_component.location[0] + component.location[0]
new_component.location[1] = merge_def_height - merge_component.location[1] + component.location[1]
print("\tAdding Merge Component: " + new_component.name)
# Add component to updated components
updated_components.append(new_component)
# Add all nets inside the merge DEF file to the main DEF files nets
if merge_def.nets is not None:
for merge_net in merge_def.nets:
# Copy net
new_net = Net(merge_net.name)
new_net.name = component.name + '_' + merge_net.name
print("\tProcessing Merge Net: " + new_net.name)
# Check if macro internal net is connected to macro pin, update component name
is_connected_to_macro_pin = False
pin_name = ''
for comp_pin in merge_net.comp_pin:
if comp_pin[0] == 'PIN':
is_connected_to_macro_pin = True
pin_name = comp_pin[1]
else:
# Update component name
new_net.comp_pin.append([component.name + '_' + comp_pin[0], comp_pin[1]])
print("\t\tIs connected to macro pin: " + str(is_connected_to_macro_pin))
print("\t\tComponent pins: " + str(new_net.comp_pin))
for routed in merge_net.routed:
print("\t\tAdding Merge Routed:\n" + str(routed))
new_routed = Routed()
new_routed.layer = routed.layer
new_routed.points = []
# TODO: component pin and net propagation if macro internal net is connected with external net
for point in routed.points:
if component.orient == 'N':
new_routed.points.append([point[0] + component.location[0], point[1] + component.location[1]])
else:
new_routed.points.append([merge_def_width - point[0] + component.location[0], merge_def_height - point[1] + component.location[1]])
new_routed.end_via = routed.end_via
if routed.end_via_loc is not None:
if component.orient == 'N':
new_routed.end_via_loc = [routed.end_via_loc[0] + component.location[0], routed.end_via_loc[1] + component.location[1]]
else:
new_routed.end_via_loc = [merge_def_width - routed.end_via_loc[0] + component.location[0], merge_def_height - routed.end_via_loc[1] + component.location[1]]
print(str(new_routed))
new_net.routed.append(new_routed)
# If macro net is connected to macro pin, search for the connected net
if is_connected_to_macro_pin:
# Search for connected net to macro pin
found_net = None
for net in merged_nets:
for comp_pin in net.comp_pin:
if comp_pin[0] == component.name and comp_pin[1] == pin_name:
print("\t\tFound connected net: " + net.name)
found_net = net
break
if found_net is not None:
break
if found_net is not None:
# Add merged component pins
for comp_pin in new_net.comp_pin:
print("\t\tAdding Merge Component Pin: " + str(comp_pin))
found_net.comp_pin.append(comp_pin)
# Add routed to connected net
for routed in new_net.routed:
print("\t\tAdding Merge Routed to connected net: " + str(routed))
found_net.routed.append(routed)
else:
# Add net
merged_nets.append(new_net)
break
if not found_match:
# Add component to updated components
updated_components.append(component)
def_parser.components = updated_components
# Generate PCB
print('Generating ' + pcb_file_path + '...')
pcb = Board().create_new()
# General Information
pcb.version = 20221018
pcb.generator = 'def2pcb'
pcb.graphicItems.append(
GrText(
text = stamp,
layer = "F.SilkS",
position = KiPosition((def_parser.diearea[0][0] + def_parser.diearea[1][0]) / scale / 2, -5),
effects = Effects(
font = Font(
height = 2.0,
width = 2.0
)
)
)
)
# Layers
pcb.layers = []
tech_json = json.load(open('./config/technology.json'))
technology = tech_json['technology']
wire_width = technology['wire_width']
via_drill_size = technology['via_diameter']
via_size = via_drill_size + 2 * technology['via_annular_ring']
num_metal_layers = technology['metal_layers']
# Metal Layers
pcb_layer_dict = {}
pcb_copper_layers = []
for i in range(0, num_metal_layers):
layer_name = ''
ordinal = i
if i == 0:
layer_name = 'F'
elif i == num_metal_layers - 1:
layer_name = 'B'
ordinal = 31
else:
layer_name = 'In' + str(i)
layer_name += '.Cu'
pcb_copper_layers.append(layer_name)
metal_name = 'Metal' + str(i + 1)
pcb_layer_dict[metal_name] = layer_name
pcb.layers.append(
BrdLayerToken(
ordinal = ordinal,
name = layer_name,
type = 'signal',
userName = metal_name
)
)
# Manufacturing Layers
pcb.layers.append(BrdLayerToken(ordinal = 32, name = 'B.Adhes', type = 'user', userName = 'B.Adhesive'))
pcb.layers.append(BrdLayerToken(ordinal = 33, name = 'F.Adhes', type = 'user', userName = 'F.Adhesive'))
pcb.layers.append(BrdLayerToken(ordinal = 34, name = 'F.Paste', type = 'user'))
pcb.layers.append(BrdLayerToken(ordinal = 35, name = 'B.Paste', type = 'user'))
pcb.layers.append(BrdLayerToken(ordinal = 36, name = 'B.SilkS', type = 'user', userName = 'B.Silkscreen'))
pcb.layers.append(BrdLayerToken(ordinal = 37, name = 'F.SilkS', type = 'user', userName = 'F.Silkscreen'))
pcb.layers.append(BrdLayerToken(ordinal = 38, name = 'F.Mask', type = 'user'))
pcb.layers.append(BrdLayerToken(ordinal = 39, name = 'B.Mask', type = 'user'))
pcb.layers.append(BrdLayerToken(ordinal = 44, name = 'Edge.Cuts', type = 'user'))
pcb.layers.append(BrdLayerToken(ordinal = 45, name = 'Margin', type = 'user'))
pcb.layers.append(BrdLayerToken(ordinal = 46, name = 'B.CrtYd', type = 'user', userName = 'B.Courtyard'))
pcb.layers.append(BrdLayerToken(ordinal = 47, name = 'F.CrtYd', type = 'user', userName = 'F.Courtyard'))
pcb.layers.append(BrdLayerToken(ordinal = 48, name = 'F.Fab', type = 'user'))
pcb.layers.append(BrdLayerToken(ordinal = 49, name = 'B.Fab', type = 'user'))
# Stackup
stackup = Stackup()
stackup.layers.append(StackupLayer(name = 'F.SilkS', type = 'Top Silk Screen'))
stackup.layers.append(StackupLayer(name = 'F.Paste', type = 'Top Solder Paste'))
stackup.layers.append(StackupLayer(name = 'F.Mask', type = 'Top Solder Mask', thickness = 0.01))
pcb_stackup = tech_json['pcb_stackup']
for i in range(0, pcb_stackup['copper_layers']):
layer_name = ''
if i == 0:
layer_name = 'F'
elif i == num_metal_layers - 1:
layer_name = 'B'
else:
layer_name = 'In' + str(i)
layer_name += '.Cu'
# Add copper layer
stackup.layers.append(StackupLayer(name = layer_name, type = 'copper', thickness = pcb_stackup['copper_thickness'][i]))
# Add dielectric layer
if i < pcb_stackup['copper_layers']-1:
stackup.layers.append(
StackupLayer(
name = 'dielectric ' + str(i + 1),
material = pcb_stackup['dielectric_materials'][i],
type = pcb_stackup['dielectric_types'][i],
thickness = pcb_stackup['dielectric_thickness'][i],
epsilonR = pcb_stackup['dielectric_constants'][i],
lossTangent = pcb_stackup['dielectric_loss_tangents'][i]
)
)
stackup.layers.append(StackupLayer(name = 'B.Mask', type = 'Bottom Solder Mask', thickness = 0.01))
stackup.layers.append(StackupLayer(name = 'B.Paste', type = 'Bottom Solder Paste'))
stackup.layers.append(StackupLayer(name = 'B.SilkS', type = 'Bottom Silk Screen'))
pcb.setup.stackup = stackup
pcb.general.thickness = pcb_stackup['pcb_thickness']
# PCB Plot Settings
plot = PlotSettings()
plot.layerSelection = '0x00010fc_ffffffff'
plot.plotOnAllLayersSelection = '0x0'
plot.disableApertMacros = False
plot.useGerberExtensions = True
plot.useGerberAttributes = False
plot.useGerberAdvancedAttributes = False
plot.createGerberJobFile = False
plot.dashedLineDashRatio = 12.0
plot.dahsedLineGapRatio = 3.0
plot.svgPrecision = 4.0
plot.plotFrameRef = False
plot.viasOnMask = False
plot.mode = 1
plot.useAuxOrigin = False
plot.hpglPenNumber = 1
plot.hpglPenSpeed = 20
plot.hpglPenDiameter = 15.0
plot.dxfPolygonMode = True
plot.dxfImperialUnits = True
plot.dxfUsePcbnewFont = True
plot.psNegative = False
plot.psA4Output = False
plot.plotReference = True
plot.plotValue = False
plot.plotInvisibleText = False
plot.sketchPadsOnFab = False
plot.subtractMaskFromSilk = True
plot.outputFormat = 1
plot.mirror = False
plot.drillShape = 0
plot.scaleSelection = 1
plot.outputdirectory = 'plot/'
pcb.setup.plotSettings = plot
# PCB outline
outline = GrRect(
start = KiPosition(def_parser.diearea[0][0] / scale, -def_parser.diearea[0][1] / scale),
end = KiPosition(def_parser.diearea[1][0] / scale, -def_parser.diearea[1][1] / scale),
layer = 'Edge.Cuts',
width = 0.2,
fill = None,
tstamp = 'edge_cuts_pcb_outline',
locked = False,
)
pcb.traceItems.append(outline)
# Add special nets
print('Adding special nets...')
pcb_net_dict = {}
pcb_special_net_dict = {}
pcb.nets = []
if def_parser.specialnets is not None:
for idx, net in enumerate(def_parser.specialnets):
new_net = KiNet(number = idx + 1, name = net.name)
pcb_net_dict[net.name] = new_net
pcb_special_net_dict[net.name] = new_net
pcb.nets.append(new_net)
# Add nets
print('Adding nets...')
offset = 0 if def_parser.specialnets is None else pcb.nets[-1].number + 1
for idx, net in enumerate(merged_nets):
new_net = KiNet(number = idx + offset, name = net.name)
pcb_net_dict[net.name] = new_net
pcb.nets.append(new_net)
# Add components
print('Adding components...')
footprints_dir = './pdk/kicad/footprints/'
footprint_dict = {}
if def_parser.components is not None:
for comp in def_parser.components:
orient = comp.orient
origin_top_right = (orient == 'N_TR' or orient == 'S_TR')
if origin_top_right:
orient = orient[0]
footprint_path = footprints_dir + comp.macro + '_' + orient + '.kicad_mod'
if not os.path.exists(footprint_path):
print('Footprint ' + footprint_path + ' not found')
continue
fp = KiFootprint().from_file(footprints_dir + comp.macro + '_' + orient + '.kicad_mod')
for item in fp.graphicItems:
if isinstance(item, FpText) and item.type == 'reference':
item.text = comp.name
if origin_top_right:
fp_width = 0
fp_height = 0
for gi in fp.graphicItems:
if isinstance(gi, FpRect):
if gi.layer == 'F.CrtYd':
fp_width = max(fp_width, abs(gi.end.X - gi.start.X))
fp_height = max(fp_height, abs(gi.end.Y - gi.start.Y))
print("Component " + comp.name + " width: " + str(fp_width) + " height: " + str(fp_height))
print(comp.location[0] / scale, -comp.location[1] / scale)
fp.position = KiPosition(comp.location[0] / scale - fp_width, -comp.location[1] / scale + fp_height)
else:
fp.position = KiPosition(comp.location[0] / scale, -comp.location[1] / scale)
for pad in fp.pads:
if pad.pinFunction in pcb_special_net_dict:
pad.net = pcb_special_net_dict[pad.pinFunction]
footprint_dict[comp.name] = fp
pcb.footprints.append(fp)
def trimSegment(segment: BrdSegment):
if segment.start.X == segment.end.X:
if segment.start.Y > segment.end.Y:
segment.start.Y -= segment.width / 2
segment.end.Y += segment.width / 2
if segment.start.Y < segment.end.Y:
segment.start.Y += segment.width / 2
segment.end.Y -= segment.width / 2
if segment.start.Y == segment.end.Y:
if segment.start.X > segment.end.X:
segment.start.X -= segment.width / 2
segment.end.X += segment.width / 2
if segment.start.X < segment.end.X:
segment.start.X += segment.width / 2
segment.end.X -= segment.width / 2
return segment
def find_intercept(start1: KiPosition, end1: KiPosition, start2: KiPosition, end2: KiPosition):
# Check if orthogonal to each other
if start1.X == end1.X and start2.X == end2.X:
return None
if start1.Y == end1.Y and start2.Y == end2.Y:
return None
# One is horizontal and the other one is vertical
if start2.X == end2.X:
# Make start1-end1 vrtical
temp = start1
start1 = start2
start2 = temp
temp = end1
end1 = end2
end2 = temp
# start1-end1 is vertical
# start2-end2 is horizontal
# Make start always smaller
if start1.Y > end1.Y:
temp = start1.Y
start1.Y = end1.Y
end1.Y = temp
if start2.X > end2.X:
temp = start2.X
start2.X = end2.X
end2.X = temp
# Check if Y of horizontal line is within bounds of vertical line
if start2.Y < start1.Y or start2.Y > end1.Y:
return None
# Check if X of vertical line is within bounds of horizontal line
if start1.X < start2.X or start1.X > end2.X:
return None
# They have to intercept at Y of horizontal line and X of vertical line
return KiPosition(X = start1.X, Y = start2.Y)
# Add special nets routing
print('Adding power grid...')
if def_parser.specialnets is not None:
for net in def_parser.specialnets:
ring_shapes = list(filter(lambda x: x.shape_type == 'RING' and x.end_via == None, net.shapes))
for shape in net.shapes:
net_idx = next((x.number for x in pcb.nets if x.name == net.name), 0)
if shape.end_via == None:
start = KiPosition(shape.points[0][0] / scale, -shape.points[0][1] / scale)
end = KiPosition(shape.points[1][0] / scale, -shape.points[1][1] / scale)
# Generate Via at end of segment
if GEN_FOLLOWPIN_VIAS and shape.shape_type == 'FOLLOWPIN':
# Find intercept with rings
for ring in ring_shapes:
interception = find_intercept(start, end, KiPosition(ring.points[0][0] / scale, -ring.points[0][1] / scale), KiPosition(ring.points[1][0] / scale, -ring.points[1][1] / scale))
if interception == None:
continue
via = BrdVia(
type = None,
locked = False,
position = interception,
size = via_size,
drill = via_drill_size,
layers = pcb_copper_layers,
free = False,
net = net_idx,
tstamp = 'via_powergrid_interception_' + shape.layer
)
pcb.traceItems.append(via)
# Segment
segment = BrdSegment(
start = start,
end = end,
width = float(shape.width) / scale,
layer = pcb_layer_dict[shape.layer],
locked = False,
net = net_idx,
tstamp = 'seg_powergrid_' + shape.layer + '_' + str(shape.points[0][0]) + '_' + str(shape.points[0][1]) + '_' + str(shape.points[1][0]) + '_' + str(shape.points[1][1])
)
segment = trimSegment(segment)
pcb.traceItems.append(segment)
else:
# Via
via = BrdVia(
type = None,
locked = False,
position = KiPosition(shape.end_via_loc[0] / scale, -shape.end_via_loc[1] / scale),
size = via_size,
drill = via_drill_size,
layers = pcb_copper_layers,
free = False,
net = net_idx,
tstamp = 'via_powergrid_' + shape.shape_type.lower() + '_' + shape.layer + '_' + str(shape.end_via_loc[0]) + '_' + str(shape.end_via_loc[1])
)
pcb.traceItems.append(via)
# Add net routing
print('Adding net routing...')
for net in merged_nets:
# Connect components
for comp_pin in net.comp_pin:
comp_name = comp_pin[0]
if comp_name in footprint_dict:
fp_comp = footprint_dict[comp_name]
for pad in fp_comp.pads:
if pad.pinFunction == comp_pin[1]:
pad.net = pcb_net_dict[net.name]
else:
# Found PIN
continue
for route in net.routed:
if route.end_via == None:
# Segment
segment = BrdSegment(
start = KiPosition(route.points[0][0] / scale, -route.points[0][1] / scale),
end = KiPosition(route.points[1][0] / scale, -route.points[1][1] / scale),
width = wire_width,
layer = pcb_layer_dict[route.layer],
locked = False,
net = next((x.number for x in pcb.nets if x.name == net.name), 0),
tstamp = 'seg_' + route.layer + '_' + str(route.points[0][0]) + '_' + str(route.points[0][1]) + '_' + str(route.points[1][0]) + '_' + str(route.points[1][1])
)
pcb.traceItems.append(segment)
else:
# Via
via = BrdVia(
type = None,
locked = False,
position = KiPosition(route.end_via_loc[0] / scale, -route.end_via_loc[1] / scale),
size = via_size,
drill = via_drill_size,
layers = pcb_copper_layers,
free = False,
net = next((x.number for x in pcb.nets if x.name == net.name), 0),
tstamp = 'via_' + route.layer + '_' + str(route.end_via_loc[0]) + '_' + str(route.end_via_loc[1])
)
pcb.traceItems.append(via)
# Write generated PCB to file
pcb.to_file(pcb_file_path)
print('Done')