ToolPanelize.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  1. from FlatCAMTool import FlatCAMTool
  2. from copy import copy, deepcopy
  3. from ObjectCollection import *
  4. import time
  5. class Panelize(FlatCAMTool):
  6. toolName = "Panelize PCB"
  7. def __init__(self, app):
  8. super(Panelize, self).__init__(self)
  9. self.app = app
  10. ## Title
  11. title_label = QtWidgets.QLabel("<font size=4><b>%s</b></font>" % self.toolName)
  12. self.layout.addWidget(title_label)
  13. ## Form Layout
  14. form_layout = QtWidgets.QFormLayout()
  15. self.layout.addLayout(form_layout)
  16. ## Type of object to be panelized
  17. self.type_obj_combo = QtWidgets.QComboBox()
  18. self.type_obj_combo.addItem("Gerber")
  19. self.type_obj_combo.addItem("Excellon")
  20. self.type_obj_combo.addItem("Geometry")
  21. self.type_obj_combo.setItemIcon(0, QtGui.QIcon("share/flatcam_icon16.png"))
  22. self.type_obj_combo.setItemIcon(1, QtGui.QIcon("share/drill16.png"))
  23. self.type_obj_combo.setItemIcon(2, QtGui.QIcon("share/geometry16.png"))
  24. self.type_obj_combo_label = QtWidgets.QLabel("Object Type:")
  25. self.type_obj_combo_label.setToolTip(
  26. "Specify the type of object to be panelized\n"
  27. "It can be of type: Gerber, Excellon or Geometry.\n"
  28. "The selection here decide the type of objects that will be\n"
  29. "in the Object combobox."
  30. )
  31. form_layout.addRow(self.type_obj_combo_label, self.type_obj_combo)
  32. ## Object to be panelized
  33. self.object_combo = QtWidgets.QComboBox()
  34. self.object_combo.setModel(self.app.collection)
  35. self.object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  36. self.object_combo.setCurrentIndex(1)
  37. self.object_label = QtWidgets.QLabel("Object:")
  38. self.object_label.setToolTip(
  39. "Object to be panelized. This means that it will\n"
  40. "be duplicated in an array of rows and columns."
  41. )
  42. form_layout.addRow(self.object_label, self.object_combo)
  43. ## Type of Box Object to be used as an envelope for panelization
  44. self.type_box_combo = QtWidgets.QComboBox()
  45. self.type_box_combo.addItem("Gerber")
  46. self.type_box_combo.addItem("Excellon")
  47. self.type_box_combo.addItem("Geometry")
  48. # we get rid of item1 ("Excellon") as it is not suitable for use as a "box" for panelizing
  49. self.type_box_combo.view().setRowHidden(1, True)
  50. self.type_box_combo.setItemIcon(0, QtGui.QIcon("share/flatcam_icon16.png"))
  51. self.type_box_combo.setItemIcon(2, QtGui.QIcon("share/geometry16.png"))
  52. self.type_box_combo_label = QtWidgets.QLabel("Box Type:")
  53. self.type_box_combo_label.setToolTip(
  54. "Specify the type of object to be used as an container for\n"
  55. "panelization. It can be: Gerber or Geometry type.\n"
  56. "The selection here decide the type of objects that will be\n"
  57. "in the Box Object combobox."
  58. )
  59. form_layout.addRow(self.type_box_combo_label, self.type_box_combo)
  60. ## Box
  61. self.box_combo = QtWidgets.QComboBox()
  62. self.box_combo.setModel(self.app.collection)
  63. self.box_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  64. self.box_combo.setCurrentIndex(1)
  65. self.box_combo_label = QtWidgets.QLabel("Box Object:")
  66. self.box_combo_label.setToolTip(
  67. "The actual object that is used a container for the\n "
  68. "selected object that is to be panelized."
  69. )
  70. form_layout.addRow(self.box_combo_label, self.box_combo)
  71. ## Spacing Columns
  72. self.spacing_columns = FloatEntry()
  73. self.spacing_columns.set_value(0.0)
  74. self.spacing_columns_label = QtWidgets.QLabel("Spacing cols:")
  75. self.spacing_columns_label.setToolTip(
  76. "Spacing between columns of the desired panel.\n"
  77. "In current units."
  78. )
  79. form_layout.addRow(self.spacing_columns_label, self.spacing_columns)
  80. ## Spacing Rows
  81. self.spacing_rows = FloatEntry()
  82. self.spacing_rows.set_value(0.0)
  83. self.spacing_rows_label = QtWidgets.QLabel("Spacing rows:")
  84. self.spacing_rows_label.setToolTip(
  85. "Spacing between rows of the desired panel.\n"
  86. "In current units."
  87. )
  88. form_layout.addRow(self.spacing_rows_label, self.spacing_rows)
  89. ## Columns
  90. self.columns = IntEntry()
  91. self.columns.set_value(1)
  92. self.columns_label = QtWidgets.QLabel("Columns:")
  93. self.columns_label.setToolTip(
  94. "Number of columns of the desired panel"
  95. )
  96. form_layout.addRow(self.columns_label, self.columns)
  97. ## Rows
  98. self.rows = IntEntry()
  99. self.rows.set_value(1)
  100. self.rows_label = QtWidgets.QLabel("Rows:")
  101. self.rows_label.setToolTip(
  102. "Number of rows of the desired panel"
  103. )
  104. form_layout.addRow(self.rows_label, self.rows)
  105. ## Constrains
  106. self.constrain_cb = FCCheckBox("Constrain panel within:")
  107. self.constrain_cb.setToolTip(
  108. "Area define by DX and DY within to constrain the panel.\n"
  109. "DX and DY values are in current units.\n"
  110. "Regardless of how many columns and rows are desired,\n"
  111. "the final panel will have as many columns and rows as\n"
  112. "they fit completely within selected area."
  113. )
  114. form_layout.addRow(self.constrain_cb)
  115. self.x_width_entry = FloatEntry()
  116. self.x_width_entry.set_value(0.0)
  117. self.x_width_lbl = QtWidgets.QLabel("Width (DX):")
  118. self.x_width_lbl.setToolTip(
  119. "The width (DX) within which the panel must fit.\n"
  120. "In current units."
  121. )
  122. form_layout.addRow(self.x_width_lbl, self.x_width_entry)
  123. self.y_height_entry = FloatEntry()
  124. self.y_height_entry.set_value(0.0)
  125. self.y_height_lbl = QtWidgets.QLabel("Height (DY):")
  126. self.y_height_lbl.setToolTip(
  127. "The height (DY)within which the panel must fit.\n"
  128. "In current units."
  129. )
  130. form_layout.addRow(self.y_height_lbl, self.y_height_entry)
  131. self.constrain_sel = OptionalInputSection(
  132. self.constrain_cb, [self.x_width_lbl, self.x_width_entry, self.y_height_lbl, self.y_height_entry])
  133. ## Buttons
  134. hlay_2 = QtWidgets.QHBoxLayout()
  135. self.layout.addLayout(hlay_2)
  136. hlay_2.addStretch()
  137. self.panelize_object_button = QtWidgets.QPushButton("Panelize Object")
  138. self.panelize_object_button.setToolTip(
  139. "Panelize the specified object around the specified box.\n"
  140. "In other words it creates multiple copies of the source object,\n"
  141. "arranged in a 2D array of rows and columns."
  142. )
  143. hlay_2.addWidget(self.panelize_object_button)
  144. self.layout.addStretch()
  145. ## Signals
  146. self.panelize_object_button.clicked.connect(self.on_panelize)
  147. self.type_obj_combo.currentIndexChanged.connect(self.on_type_obj_index_changed)
  148. self.type_box_combo.currentIndexChanged.connect(self.on_type_box_index_changed)
  149. # list to hold the temporary objects
  150. self.objs = []
  151. # final name for the panel object
  152. self.outname = ""
  153. # flag to signal the constrain was activated
  154. self.constrain_flag = False
  155. def on_type_obj_index_changed(self):
  156. obj_type = self.type_obj_combo.currentIndex()
  157. self.object_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  158. self.object_combo.setCurrentIndex(0)
  159. def on_type_box_index_changed(self):
  160. obj_type = self.type_box_combo.currentIndex()
  161. self.box_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  162. self.box_combo.setCurrentIndex(0)
  163. def run(self):
  164. FlatCAMTool.run(self)
  165. self.app.ui.notebook.setTabText(2, "Panel. Tool")
  166. def install(self, icon=None, separator=None, **kwargs):
  167. FlatCAMTool.install(self, icon, separator, shortcut='ALT+Z', **kwargs)
  168. def on_panelize(self):
  169. name = self.object_combo.currentText()
  170. # Get source object.
  171. try:
  172. obj = self.app.collection.get_by_name(str(name))
  173. except:
  174. self.app.inform.emit("[error_notcl]Could not retrieve object: %s" % name)
  175. return "Could not retrieve object: %s" % name
  176. panel_obj = obj
  177. if panel_obj is None:
  178. self.app.inform.emit("[error_notcl]Object not found: %s" % panel_obj)
  179. return "Object not found: %s" % panel_obj
  180. boxname = self.box_combo.currentText()
  181. try:
  182. box = self.app.collection.get_by_name(boxname)
  183. except:
  184. self.app.inform.emit("[error_notcl]Could not retrieve object: %s" % boxname)
  185. return "Could not retrieve object: %s" % boxname
  186. if box is None:
  187. self.app.inform.emit("[warning]No object Box. Using instead %s" % panel_obj)
  188. box = panel_obj
  189. self.outname = name + '_panelized'
  190. spacing_columns = self.spacing_columns.get_value()
  191. spacing_columns = spacing_columns if spacing_columns is not None else 0
  192. spacing_rows = self.spacing_rows.get_value()
  193. spacing_rows = spacing_rows if spacing_rows is not None else 0
  194. rows = self.rows.get_value()
  195. rows = rows if rows is not None else 1
  196. columns = self.columns.get_value()
  197. columns = columns if columns is not None else 1
  198. constrain_dx = self.x_width_entry.get_value()
  199. constrain_dy = self.y_height_entry.get_value()
  200. if 0 in {columns, rows}:
  201. self.app.inform.emit("[error_notcl]Columns or Rows are zero value. Change them to a positive integer.")
  202. return "Columns or Rows are zero value. Change them to a positive integer."
  203. xmin, ymin, xmax, ymax = box.bounds()
  204. lenghtx = xmax - xmin + spacing_columns
  205. lenghty = ymax - ymin + spacing_rows
  206. # check if constrain within an area is desired
  207. if self.constrain_cb.isChecked():
  208. panel_lengthx = ((xmax - xmin) * columns) + (spacing_columns * (columns - 1))
  209. panel_lengthy = ((ymax - ymin) * rows) + (spacing_rows * (rows - 1))
  210. # adjust the number of columns and/or rows so the panel will fit within the panel constraint area
  211. if (panel_lengthx > constrain_dx) or (panel_lengthy > constrain_dy):
  212. self.constrain_flag = True
  213. while panel_lengthx > constrain_dx:
  214. columns -= 1
  215. panel_lengthx = ((xmax - xmin) * columns) + (spacing_columns * (columns - 1))
  216. while panel_lengthy > constrain_dy:
  217. rows -= 1
  218. panel_lengthy = ((ymax - ymin) * rows) + (spacing_rows * (rows - 1))
  219. # def clean_temp():
  220. # # deselect all to avoid delete selected object when run delete from shell
  221. # self.app.collection.set_all_inactive()
  222. #
  223. # for del_obj in self.objs:
  224. # self.app.collection.set_active(del_obj.options['name'])
  225. # self.app.on_delete()
  226. #
  227. # self.objs[:] = []
  228. # def panelize():
  229. # if panel_obj is not None:
  230. # self.app.inform.emit("Generating panel ... Please wait.")
  231. #
  232. # self.app.progress.emit(10)
  233. #
  234. # if isinstance(panel_obj, FlatCAMExcellon):
  235. # currenty = 0.0
  236. # self.app.progress.emit(0)
  237. #
  238. # def initialize_local_excellon(obj_init, app):
  239. # obj_init.tools = panel_obj.tools
  240. # # drills are offset, so they need to be deep copied
  241. # obj_init.drills = deepcopy(panel_obj.drills)
  242. # obj_init.offset([float(currentx), float(currenty)])
  243. # obj_init.create_geometry()
  244. # self.objs.append(obj_init)
  245. #
  246. # self.app.progress.emit(0)
  247. # for row in range(rows):
  248. # currentx = 0.0
  249. # for col in range(columns):
  250. # local_outname = self.outname + ".tmp." + str(col) + "." + str(row)
  251. # self.app.new_object("excellon", local_outname, initialize_local_excellon, plot=False,
  252. # autoselected=False)
  253. # currentx += lenghtx
  254. # currenty += lenghty
  255. # else:
  256. # currenty = 0
  257. # self.app.progress.emit(0)
  258. #
  259. # def initialize_local_geometry(obj_init, app):
  260. # obj_init.solid_geometry = panel_obj.solid_geometry
  261. # obj_init.offset([float(currentx), float(currenty)])
  262. # self.objs.append(obj_init)
  263. #
  264. # self.app.progress.emit(0)
  265. # for row in range(rows):
  266. # currentx = 0
  267. #
  268. # for col in range(columns):
  269. # local_outname = self.outname + ".tmp." + str(col) + "." + str(row)
  270. # self.app.new_object("geometry", local_outname, initialize_local_geometry, plot=False,
  271. # autoselected=False)
  272. # currentx += lenghtx
  273. # currenty += lenghty
  274. #
  275. # def job_init_geometry(obj_fin, app_obj):
  276. # FlatCAMGeometry.merge(self.objs, obj_fin)
  277. #
  278. # def job_init_excellon(obj_fin, app_obj):
  279. # # merge expects tools to exist in the target object
  280. # obj_fin.tools = panel_obj.tools.copy()
  281. # FlatCAMExcellon.merge(self.objs, obj_fin)
  282. #
  283. # if isinstance(panel_obj, FlatCAMExcellon):
  284. # self.app.progress.emit(50)
  285. # self.app.new_object("excellon", self.outname, job_init_excellon, plot=True, autoselected=True)
  286. # else:
  287. # self.app.progress.emit(50)
  288. # self.app.new_object("geometry", self.outname, job_init_geometry, plot=True, autoselected=True)
  289. #
  290. # else:
  291. # self.app.inform.emit("[error_notcl] Obj is None")
  292. # return "ERROR: Obj is None"
  293. # panelize()
  294. # clean_temp()
  295. def panelize_2():
  296. if panel_obj is not None:
  297. self.app.inform.emit("Generating panel ... Please wait.")
  298. self.app.progress.emit(0)
  299. def job_init_excellon(obj_fin, app_obj):
  300. currenty = 0.0
  301. self.app.progress.emit(10)
  302. obj_fin.tools = panel_obj.tools.copy()
  303. obj_fin.drills = []
  304. obj_fin.slots = []
  305. obj_fin.solid_geometry = []
  306. for option in panel_obj.options:
  307. if option is not 'name':
  308. try:
  309. obj_fin.options[option] = panel_obj.options[option]
  310. except:
  311. log.warning("Failed to copy option.", option)
  312. for row in range(rows):
  313. currentx = 0.0
  314. for col in range(columns):
  315. if panel_obj.drills:
  316. for tool_dict in panel_obj.drills:
  317. point_offseted = affinity.translate(tool_dict['point'], currentx, currenty)
  318. obj_fin.drills.append(
  319. {
  320. "point": point_offseted,
  321. "tool": tool_dict['tool']
  322. }
  323. )
  324. if panel_obj.slots:
  325. for tool_dict in panel_obj.slots:
  326. start_offseted = affinity.translate(tool_dict['start'], currentx, currenty)
  327. stop_offseted = affinity.translate(tool_dict['stop'], currentx, currenty)
  328. obj_fin.slots.append(
  329. {
  330. "start": start_offseted,
  331. "stop": stop_offseted,
  332. "tool": tool_dict['tool']
  333. }
  334. )
  335. currentx += lenghtx
  336. currenty += lenghty
  337. obj_fin.create_geometry()
  338. obj_fin.zeros = panel_obj.zeros
  339. obj_fin.units = panel_obj.units
  340. def job_init_geometry(obj_fin, app_obj):
  341. currentx = 0.0
  342. currenty = 0.0
  343. def translate_recursion(geom):
  344. if type(geom) == list:
  345. geoms = list()
  346. for local_geom in geom:
  347. geoms.append(translate_recursion(local_geom))
  348. return geoms
  349. else:
  350. return affinity.translate(geom, xoff=currentx, yoff=currenty)
  351. obj_fin.solid_geometry = []
  352. if isinstance(panel_obj, FlatCAMGeometry):
  353. obj_fin.multigeo = panel_obj.multigeo
  354. obj_fin.tools = deepcopy(panel_obj.tools)
  355. if panel_obj.multigeo is True:
  356. for tool in panel_obj.tools:
  357. obj_fin.tools[tool]['solid_geometry'][:] = []
  358. self.app.progress.emit(0)
  359. for row in range(rows):
  360. currentx = 0.0
  361. for col in range(columns):
  362. if isinstance(panel_obj, FlatCAMGeometry):
  363. if panel_obj.multigeo is True:
  364. for tool in panel_obj.tools:
  365. obj_fin.tools[tool]['solid_geometry'].append(translate_recursion(
  366. panel_obj.tools[tool]['solid_geometry'])
  367. )
  368. else:
  369. obj_fin.solid_geometry.append(
  370. translate_recursion(panel_obj.solid_geometry)
  371. )
  372. else:
  373. obj_fin.solid_geometry.append(
  374. translate_recursion(panel_obj.solid_geometry)
  375. )
  376. currentx += lenghtx
  377. currenty += lenghty
  378. if isinstance(panel_obj, FlatCAMExcellon):
  379. self.app.progress.emit(50)
  380. self.app.new_object("excellon", self.outname, job_init_excellon, plot=True, autoselected=True)
  381. else:
  382. self.app.progress.emit(50)
  383. self.app.new_object("geometry", self.outname, job_init_geometry, plot=True, autoselected=True)
  384. if self.constrain_flag is False:
  385. self.app.inform.emit("[success]Panel done...")
  386. else:
  387. self.constrain_flag = False
  388. self.app.inform.emit("[warning] Too big for the constrain area. Final panel has %s columns and %s rows" %
  389. (columns, rows))
  390. proc = self.app.proc_container.new("Generating panel ... Please wait.")
  391. def job_thread(app_obj):
  392. try:
  393. panelize_2()
  394. self.app.inform.emit("[success]Panel created successfully.")
  395. except Exception as e:
  396. proc.done()
  397. log.debug(str(e))
  398. return
  399. proc.done()
  400. self.app.collection.promise(self.outname)
  401. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  402. def reset_fields(self):
  403. self.object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  404. self.box_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))