TclCommandPanelize.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  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,
  141. # plot=False,
  142. # autoselected=False)
  143. # else:
  144. # self.app.app_obj.new_object("geometry", local_outname, initialize_local, plot=False,
  145. # autoselected=False)
  146. #
  147. # currentx += lenghtx
  148. # currenty += lenghty
  149. #
  150. # if isinstance(obj, ExcellonObject):
  151. # self.app.app_obj.new_object("excellon", outname, initialize_excellon)
  152. # else:
  153. # self.app.app_obj.new_object("geometry", outname, initialize_geometry)
  154. #
  155. # # deselect all to avoid delete selected object when run delete from shell
  156. # self.app.collection.set_all_inactive()
  157. # for delobj in objs:
  158. # self.app.collection.set_active(delobj.options['name'])
  159. # self.app.on_delete()
  160. # else:
  161. # return "fail"
  162. #
  163. # ret_value = panelize()
  164. # if ret_value == 'fail':
  165. # return 'fail'
  166. def panelize_2():
  167. if obj is not None:
  168. self.app.inform.emit("Generating panel ... Please wait.")
  169. def job_init_excellon(obj_fin, app_obj):
  170. currenty = 0.0
  171. obj_fin.tools = obj.tools.copy()
  172. if 'drills' not in obj_fin.tools:
  173. obj_fin.tools['drills'] = []
  174. if 'slots' not in obj_fin.tools:
  175. obj_fin.tools['slots'] = []
  176. if 'solid_geometry' not in obj_fin.tools:
  177. obj_fin.tools['solid_geometry'] = []
  178. for option in obj.options:
  179. if option != 'name':
  180. try:
  181. obj_fin.options[option] = obj.options[option]
  182. except Exception as e:
  183. app_obj.log.warning("Failed to copy option: %s" % str(option))
  184. app_obj.log.debug("TclCommandPanelize.execute().panelize2() --> %s" % str(e))
  185. for row in range(rows):
  186. currentx = 0.0
  187. for col in range(columns):
  188. if 'drills' in obj.tools:
  189. for drill_pt in obj.tools['drills']:
  190. point_offseted = affinity.translate(drill_pt, currentx, currenty)
  191. obj_fin.tools['drills'].append(point_offseted)
  192. if 'slots' in obj.tools:
  193. for slot_tuple in obj.tools['slots']:
  194. start_offseted = affinity.translate(slot_tuple[0], currentx, currenty)
  195. stop_offseted = affinity.translate(slot_tuple[1], currentx, currenty)
  196. obj_fin.tools['slots'].append(
  197. (start_offseted, stop_offseted)
  198. )
  199. currentx += lenghtx
  200. currenty += lenghty
  201. obj_fin.create_geometry()
  202. obj_fin.zeros = obj.zeros
  203. obj_fin.units = obj.units
  204. def job_init_geometry(obj_fin, app_obj):
  205. currentx = 0.0
  206. currenty = 0.0
  207. def translate_recursion(geom):
  208. if type(geom) == list:
  209. geoms = []
  210. for local_geom in geom:
  211. geoms.append(translate_recursion(local_geom))
  212. return geoms
  213. else:
  214. return affinity.translate(geom, xoff=currentx, yoff=currenty)
  215. obj_fin.solid_geometry = []
  216. if obj.kind == 'geometry':
  217. obj_fin.multigeo = obj.multigeo
  218. obj_fin.tools = deepcopy(obj.tools)
  219. if obj.multigeo is True:
  220. for tool in obj.tools:
  221. obj_fin.tools[tool]['solid_geometry'][:] = []
  222. for row in range(rows):
  223. currentx = 0.0
  224. for col in range(columns):
  225. if obj.kind == 'geometry':
  226. if obj.multigeo is True:
  227. for tool in obj.tools:
  228. obj_fin.tools[tool]['solid_geometry'].append(translate_recursion(
  229. obj.tools[tool]['solid_geometry'])
  230. )
  231. else:
  232. obj_fin.solid_geometry.append(
  233. translate_recursion(obj.solid_geometry)
  234. )
  235. else:
  236. obj_fin.solid_geometry.append(
  237. translate_recursion(obj.solid_geometry)
  238. )
  239. currentx += lenghtx
  240. currenty += lenghty
  241. if obj.kind == 'excellon':
  242. self.app.app_obj.new_object("excellon", outname, job_init_excellon, plot=False, autoselected=True)
  243. else:
  244. self.app.app_obj.new_object("geometry", outname, job_init_geometry, plot=False, autoselected=True)
  245. if threaded is True:
  246. self.app.proc_container.new(_("Working ..."))
  247. def job_thread(app_obj):
  248. try:
  249. panelize_2()
  250. app_obj.inform.emit('[success]' % _("Done."))
  251. except Exception as ee:
  252. log.debug(str(ee))
  253. return
  254. self.app.collection.promise(outname)
  255. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  256. else:
  257. panelize_2()
  258. self.app.inform.emit('[success]' % _("Done."))