TclCommandPanelize.py 12 KB

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