TclCommandPanelize.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. from tclCommands.TclCommand import TclCommand
  2. from FlatCAMObj import FlatCAMGeometry, FlatCAMExcellon
  3. import shapely.affinity as affinity
  4. import logging
  5. from copy import deepcopy
  6. import collections
  7. log = logging.getLogger('base')
  8. class TclCommandPanelize(TclCommand):
  9. """
  10. Tcl shell command to panelize an object.
  11. example:
  12. """
  13. # List of all command aliases, to be able use old names for backward compatibility (add_poly, add_polygon)
  14. aliases = ['panelize', 'pan', 'panel']
  15. description = '%s %s' % ("--", "Create a new object with an array of duplicates of the original geometry, "
  16. "arranged in a grid.")
  17. # Dictionary of types from Tcl command, needs to be ordered
  18. arg_names = collections.OrderedDict([
  19. ('name', str),
  20. ])
  21. # Dictionary of types from Tcl command, needs to be ordered , this is for options like -optionname value
  22. option_types = collections.OrderedDict([
  23. ('rows', int),
  24. ('columns', int),
  25. ('spacing_columns', float),
  26. ('spacing_rows', float),
  27. ('box', str),
  28. ('outname', str),
  29. ('run_threaded', str)
  30. ])
  31. # array of mandatory options for current Tcl command: required = {'name','outname'}
  32. required = ['name']
  33. # structured help for current command, args needs to be ordered
  34. help = {
  35. 'main': 'Create a new object with an array of duplicates of the original geometry, arranged in a grid.',
  36. 'args': collections.OrderedDict([
  37. ('name', 'Name of the object to panelize.'),
  38. ('box', 'Name of object which acts as box (cutout for example.)'
  39. 'for cutout boundary. Object from name is used if not specified.'),
  40. ('spacing_columns', 'Spacing between columns.'),
  41. ('spacing_rows', 'Spacing between rows.'),
  42. ('columns', 'Number of columns.'),
  43. ('rows', 'Number of rows;'),
  44. ('outname', 'Name of the new geometry object.'),
  45. ('run_threaded', 'False (0) = non-threaded execution or True (1) = threaded execution')
  46. ]),
  47. 'examples': [
  48. 'panelize obj_name',
  49. 'panel obj_name -rows 2 -columns 2 -spacing_columns 0.4 -spacing_rows 1.3 -box box_obj_name '
  50. '-outname panelized_name',
  51. 'panel obj_name -columns 2 -box box_obj_name -outname panelized_name',
  52. ]
  53. }
  54. def execute(self, args, unnamed_args):
  55. """
  56. :param args:
  57. :param unnamed_args:
  58. :return:
  59. """
  60. name = args['name']
  61. # Get source object.
  62. try:
  63. obj = self.app.collection.get_by_name(str(name))
  64. except Exception:
  65. return "Could not retrieve object: %s" % name
  66. if obj is None:
  67. return "Object not found: %s" % name
  68. if 'box' in args:
  69. boxname = args['box']
  70. try:
  71. box = self.app.collection.get_by_name(boxname)
  72. except Exception:
  73. return "Could not retrieve object: %s" % name
  74. else:
  75. box = obj
  76. if 'columns' in args:
  77. columns = int(args['columns'])
  78. else:
  79. columns = int(0)
  80. if 'rows' in args:
  81. rows = int(args['rows'])
  82. else:
  83. rows = int(0)
  84. if 'columns' not in args and 'rows' not in args:
  85. return "ERROR: Specify either -columns or -rows. The one not specified it will assumed to be 0"
  86. if 'outname' in args:
  87. outname = args['outname']
  88. else:
  89. outname = name + '_panelized'
  90. if 'run_threaded' in args:
  91. threaded = bool(eval(args['run_threaded']))
  92. else:
  93. threaded = False
  94. if 'spacing_columns' in args:
  95. spacing_columns = int(args['spacing_columns'])
  96. else:
  97. spacing_columns = 5
  98. if 'spacing_rows' in args:
  99. spacing_rows = int(args['spacing_rows'])
  100. else:
  101. spacing_rows = 5
  102. xmin, ymin, xmax, ymax = box.bounds()
  103. lenghtx = xmax - xmin + spacing_columns
  104. lenghty = ymax - ymin + spacing_rows
  105. # def panelize():
  106. # currenty = 0
  107. #
  108. # def initialize_local(obj_init, app):
  109. # obj_init.solid_geometry = obj.solid_geometry
  110. # obj_init.offset([float(currentx), float(currenty)])
  111. # objs.append(obj_init)
  112. #
  113. # def initialize_local_excellon(obj_init, app):
  114. # obj_init.tools = obj.tools
  115. # # drills are offset, so they need to be deep copied
  116. # obj_init.drills = deepcopy(obj.drills)
  117. # obj_init.offset([float(currentx), float(currenty)])
  118. # obj_init.create_geometry()
  119. # objs.append(obj_init)
  120. #
  121. # def initialize_geometry(obj_init, app):
  122. # FlatCAMGeometry.merge(objs, obj_init)
  123. #
  124. # def initialize_excellon(obj_init, app):
  125. # # merge expects tools to exist in the target object
  126. # obj_init.tools = obj.tools.copy()
  127. # FlatCAMExcellon.merge(objs, obj_init)
  128. #
  129. # objs = []
  130. # if obj is not None:
  131. #
  132. # for row in range(rows):
  133. # currentx = 0
  134. # for col in range(columns):
  135. # local_outname = outname + ".tmp." + str(col) + "." + str(row)
  136. # if isinstance(obj, FlatCAMExcellon):
  137. # self.app.new_object("excellon", local_outname, initialize_local_excellon, plot=False,
  138. # autoselected=False)
  139. # else:
  140. # self.app.new_object("geometry", local_outname, initialize_local, plot=False,
  141. # autoselected=False)
  142. #
  143. # currentx += lenghtx
  144. # currenty += lenghty
  145. #
  146. # if isinstance(obj, FlatCAMExcellon):
  147. # self.app.new_object("excellon", outname, initialize_excellon)
  148. # else:
  149. # self.app.new_object("geometry", outname, initialize_geometry)
  150. #
  151. # # deselect all to avoid delete selected object when run delete from shell
  152. # self.app.collection.set_all_inactive()
  153. # for delobj in objs:
  154. # self.app.collection.set_active(delobj.options['name'])
  155. # self.app.on_delete()
  156. # else:
  157. # return "fail"
  158. #
  159. # ret_value = panelize()
  160. # if ret_value == 'fail':
  161. # return 'fail'
  162. def panelize_2():
  163. if obj is not None:
  164. self.app.inform.emit("Generating panel ... Please wait.")
  165. def job_init_excellon(obj_fin, app_obj):
  166. currenty = 0.0
  167. obj_fin.tools = obj.tools.copy()
  168. obj_fin.drills = []
  169. obj_fin.slots = []
  170. obj_fin.solid_geometry = []
  171. for option in obj.options:
  172. if option != 'name':
  173. try:
  174. obj_fin.options[option] = obj.options[option]
  175. except Exception as e:
  176. log.warning("Failed to copy option: %s" % str(option))
  177. log.debug("TclCommandPanelize.execute().panelize2() --> %s" % str(e))
  178. for row in range(rows):
  179. currentx = 0.0
  180. for col in range(columns):
  181. if obj.drills:
  182. for tool_dict in obj.drills:
  183. point_offseted = affinity.translate(tool_dict['point'], currentx, currenty)
  184. obj_fin.drills.append(
  185. {
  186. "point": point_offseted,
  187. "tool": tool_dict['tool']
  188. }
  189. )
  190. if obj.slots:
  191. for tool_dict in obj.slots:
  192. start_offseted = affinity.translate(tool_dict['start'], currentx, currenty)
  193. stop_offseted = affinity.translate(tool_dict['stop'], currentx, currenty)
  194. obj_fin.slots.append(
  195. {
  196. "start": start_offseted,
  197. "stop": stop_offseted,
  198. "tool": tool_dict['tool']
  199. }
  200. )
  201. currentx += lenghtx
  202. currenty += lenghty
  203. obj_fin.create_geometry()
  204. obj_fin.zeros = obj.zeros
  205. obj_fin.units = obj.units
  206. def job_init_geometry(obj_fin, app_obj):
  207. currentx = 0.0
  208. currenty = 0.0
  209. def translate_recursion(geom):
  210. if type(geom) == list:
  211. geoms = []
  212. for local_geom in geom:
  213. geoms.append(translate_recursion(local_geom))
  214. return geoms
  215. else:
  216. return affinity.translate(geom, xoff=currentx, yoff=currenty)
  217. obj_fin.solid_geometry = []
  218. if isinstance(obj, FlatCAMGeometry):
  219. obj_fin.multigeo = obj.multigeo
  220. obj_fin.tools = deepcopy(obj.tools)
  221. if obj.multigeo is True:
  222. for tool in obj.tools:
  223. obj_fin.tools[tool]['solid_geometry'][:] = []
  224. for row in range(rows):
  225. currentx = 0.0
  226. for col in range(columns):
  227. if isinstance(obj, FlatCAMGeometry):
  228. if obj.multigeo is True:
  229. for tool in obj.tools:
  230. obj_fin.tools[tool]['solid_geometry'].append(translate_recursion(
  231. obj.tools[tool]['solid_geometry'])
  232. )
  233. else:
  234. obj_fin.solid_geometry.append(
  235. translate_recursion(obj.solid_geometry)
  236. )
  237. else:
  238. obj_fin.solid_geometry.append(
  239. translate_recursion(obj.solid_geometry)
  240. )
  241. currentx += lenghtx
  242. currenty += lenghty
  243. if isinstance(obj, FlatCAMExcellon):
  244. self.app.new_object("excellon", outname, job_init_excellon, plot=False, autoselected=True)
  245. else:
  246. self.app.new_object("geometry", outname, job_init_geometry, plot=False, autoselected=True)
  247. if threaded is True:
  248. proc = self.app.proc_container.new("Generating panel ... Please wait.")
  249. def job_thread(app_obj):
  250. try:
  251. panelize_2()
  252. self.app.inform.emit("[success] Panel created successfully.")
  253. except Exception as ee:
  254. proc.done()
  255. log.debug(str(ee))
  256. return
  257. proc.done()
  258. self.app.collection.promise(outname)
  259. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  260. else:
  261. panelize_2()
  262. self.app.inform.emit("[success] Panel created successfully.")