ToolPanelize.py 23 KB

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