ToolPaint.py 211 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162
  1. # ##########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # File Modified: Marius Adrian Stanciu (c) #
  4. # Date: 3/10/2019 #
  5. # MIT Licence #
  6. # ##########################################################
  7. from PyQt5 import QtWidgets, QtGui, QtCore
  8. from PyQt5.QtCore import Qt
  9. from FlatCAMTool import FlatCAMTool
  10. from copy import deepcopy
  11. # from ObjectCollection import *
  12. from flatcamParsers.ParseGerber import Gerber
  13. from FlatCAMObj import FlatCAMGerber, FlatCAMGeometry
  14. from camlib import Geometry, FlatCAMRTreeStorage
  15. from flatcamGUI.GUIElements import FCTable, FCDoubleSpinner, FCCheckBox, FCInputDialog, RadioSet, FCButton, FCComboBox
  16. import FlatCAMApp
  17. from shapely.geometry import base, Polygon, MultiPolygon, LinearRing, Point, MultiLineString
  18. from shapely.ops import cascaded_union, unary_union, linemerge
  19. import numpy as np
  20. import math
  21. from numpy import Inf
  22. import traceback
  23. import logging
  24. import gettext
  25. import FlatCAMTranslation as fcTranslate
  26. import builtins
  27. fcTranslate.apply_language('strings')
  28. if '_' not in builtins.__dict__:
  29. _ = gettext.gettext
  30. log = logging.getLogger('base')
  31. class ToolPaint(FlatCAMTool, Gerber):
  32. toolName = _("Paint Tool")
  33. def __init__(self, app):
  34. self.app = app
  35. self.decimals = self.app.decimals
  36. FlatCAMTool.__init__(self, app)
  37. Geometry.__init__(self, geo_steps_per_circle=self.app.defaults["geometry_circle_steps"])
  38. # ## Title
  39. title_label = QtWidgets.QLabel("%s" % self.toolName)
  40. title_label.setStyleSheet("""
  41. QLabel
  42. {
  43. font-size: 16px;
  44. font-weight: bold;
  45. }
  46. """)
  47. self.layout.addWidget(title_label)
  48. self.tools_frame = QtWidgets.QFrame()
  49. self.tools_frame.setContentsMargins(0, 0, 0, 0)
  50. self.layout.addWidget(self.tools_frame)
  51. self.tools_box = QtWidgets.QVBoxLayout()
  52. self.tools_box.setContentsMargins(0, 0, 0, 0)
  53. self.tools_frame.setLayout(self.tools_box)
  54. # ## Form Layout
  55. grid0 = QtWidgets.QGridLayout()
  56. grid0.setColumnStretch(0, 0)
  57. grid0.setColumnStretch(1, 1)
  58. self.tools_box.addLayout(grid0)
  59. # ################################################
  60. # ##### Type of object to be painted #############
  61. # ################################################
  62. self.type_obj_combo_label = QtWidgets.QLabel('%s:' % _("Obj Type"))
  63. self.type_obj_combo_label.setToolTip(
  64. _("Specify the type of object to be painted.\n"
  65. "It can be of type: Gerber or Geometry.\n"
  66. "What is selected here will dictate the kind\n"
  67. "of objects that will populate the 'Object' combobox.")
  68. )
  69. self.type_obj_combo_label.setMinimumWidth(60)
  70. self.type_obj_combo = RadioSet([{'label': "Geometry", 'value': 'geometry'},
  71. {'label': "Gerber", 'value': 'gerber'}])
  72. grid0.addWidget(self.type_obj_combo_label, 1, 0)
  73. grid0.addWidget(self.type_obj_combo, 1, 1)
  74. # ################################################
  75. # ##### The object to be painted #################
  76. # ################################################
  77. self.obj_combo = FCComboBox()
  78. self.obj_combo.setModel(self.app.collection)
  79. self.obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  80. self.obj_combo.set_last = True
  81. self.object_label = QtWidgets.QLabel('%s:' % _("Object"))
  82. self.object_label.setToolTip(_("Object to be painted."))
  83. grid0.addWidget(self.object_label, 2, 0)
  84. grid0.addWidget(self.obj_combo, 2, 1)
  85. separator_line = QtWidgets.QFrame()
  86. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  87. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  88. grid0.addWidget(separator_line, 5, 0, 1, 2)
  89. # ### Tools ## ##
  90. self.tools_table_label = QtWidgets.QLabel('<b>%s</b>' % _('Tools Table'))
  91. self.tools_table_label.setToolTip(
  92. _("Tools pool from which the algorithm\n"
  93. "will pick the ones used for painting.")
  94. )
  95. self.tools_table = FCTable()
  96. grid0.addWidget(self.tools_table_label, 6, 0, 1, 2)
  97. grid0.addWidget(self.tools_table, 7, 0, 1, 2)
  98. self.tools_table.setColumnCount(4)
  99. self.tools_table.setHorizontalHeaderLabels(['#', _('Diameter'), _('TT'), ''])
  100. self.tools_table.setColumnHidden(3, True)
  101. # self.tools_table.setSortingEnabled(False)
  102. # self.tools_table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
  103. self.tools_table.horizontalHeaderItem(0).setToolTip(
  104. _("This is the Tool Number.\n"
  105. "Painting will start with the tool with the biggest diameter,\n"
  106. "continuing until there are no more tools.\n"
  107. "Only tools that create painting geometry will still be present\n"
  108. "in the resulting geometry. This is because with some tools\n"
  109. "this function will not be able to create painting geometry.")
  110. )
  111. self.tools_table.horizontalHeaderItem(1).setToolTip(
  112. _("Tool Diameter. It's value (in current FlatCAM units) \n"
  113. "is the cut width into the material."))
  114. self.tools_table.horizontalHeaderItem(2).setToolTip(
  115. _("The Tool Type (TT) can be:<BR>"
  116. "- <B>Circular</B> with 1 ... 4 teeth -> it is informative only. Being circular, <BR>"
  117. "the cut width in material is exactly the tool diameter.<BR>"
  118. "- <B>Ball</B> -> informative only and make reference to the Ball type endmill.<BR>"
  119. "- <B>V-Shape</B> -> it will disable de Z-Cut parameter in the resulting geometry UI form "
  120. "and enable two additional UI form fields in the resulting geometry: V-Tip Dia and "
  121. "V-Tip Angle. Adjusting those two values will adjust the Z-Cut parameter such "
  122. "as the cut width into material will be equal with the value in the Tool Diameter "
  123. "column of this table.<BR>"
  124. "Choosing the <B>V-Shape</B> Tool Type automatically will select the Operation Type "
  125. "in the resulting geometry as Isolation."))
  126. self.order_label = QtWidgets.QLabel('<b>%s:</b>' % _('Tool order'))
  127. self.order_label.setToolTip(_("This set the way that the tools in the tools table are used.\n"
  128. "'No' --> means that the used order is the one in the tool table\n"
  129. "'Forward' --> means that the tools will be ordered from small to big\n"
  130. "'Reverse' --> menas that the tools will ordered from big to small\n\n"
  131. "WARNING: using rest machining will automatically set the order\n"
  132. "in reverse and disable this control."))
  133. self.order_radio = RadioSet([{'label': _('No'), 'value': 'no'},
  134. {'label': _('Forward'), 'value': 'fwd'},
  135. {'label': _('Reverse'), 'value': 'rev'}])
  136. self.order_radio.setToolTip(_("This set the way that the tools in the tools table are used.\n"
  137. "'No' --> means that the used order is the one in the tool table\n"
  138. "'Forward' --> means that the tools will be ordered from small to big\n"
  139. "'Reverse' --> menas that the tools will ordered from big to small\n\n"
  140. "WARNING: using rest machining will automatically set the order\n"
  141. "in reverse and disable this control."))
  142. grid0.addWidget(self.order_label, 9, 0)
  143. grid0.addWidget(self.order_radio, 9, 1)
  144. separator_line = QtWidgets.QFrame()
  145. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  146. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  147. grid0.addWidget(separator_line, 10, 0, 1, 2)
  148. self.grid3 = QtWidgets.QGridLayout()
  149. self.tools_box.addLayout(self.grid3)
  150. self.grid3.setColumnStretch(0, 0)
  151. self.grid3.setColumnStretch(1, 1)
  152. # ##############################################################################
  153. # ###################### ADD A NEW TOOL ########################################
  154. # ##############################################################################
  155. self.tool_sel_label = QtWidgets.QLabel('<b>%s</b>' % _("New Tool"))
  156. self.grid3.addWidget(self.tool_sel_label, 1, 0, 1, 2)
  157. # Tool Type Radio Button
  158. self.tool_type_label = QtWidgets.QLabel('%s:' % _('Tool Type'))
  159. self.tool_type_label.setToolTip(
  160. _("Default tool type:\n"
  161. "- 'V-shape'\n"
  162. "- Circular")
  163. )
  164. self.tool_type_radio = RadioSet([{'label': _('V-shape'), 'value': 'V'},
  165. {'label': _('Circular'), 'value': 'C1'}])
  166. self.tool_type_radio.setToolTip(
  167. _("Default tool type:\n"
  168. "- 'V-shape'\n"
  169. "- Circular")
  170. )
  171. self.tool_type_radio.setObjectName('p_tool_type')
  172. self.grid3.addWidget(self.tool_type_label, 2, 0)
  173. self.grid3.addWidget(self.tool_type_radio, 2, 1)
  174. # Tip Dia
  175. self.tipdialabel = QtWidgets.QLabel('%s:' % _('V-Tip Dia'))
  176. self.tipdialabel.setToolTip(
  177. _("The tip diameter for V-Shape Tool"))
  178. self.tipdia_entry = FCDoubleSpinner(callback=self.confirmation_message)
  179. self.tipdia_entry.set_precision(self.decimals)
  180. self.tipdia_entry.set_range(0.0000, 9999.9999)
  181. self.tipdia_entry.setSingleStep(0.1)
  182. self.tipdia_entry.setObjectName('p_vtip_dia')
  183. self.grid3.addWidget(self.tipdialabel, 3, 0)
  184. self.grid3.addWidget(self.tipdia_entry, 3, 1)
  185. # Tip Angle
  186. self.tipanglelabel = QtWidgets.QLabel('%s:' % _('V-Tip Angle'))
  187. self.tipanglelabel.setToolTip(
  188. _("The tip angle for V-Shape Tool.\n"
  189. "In degree."))
  190. self.tipangle_entry = FCDoubleSpinner(callback=self.confirmation_message)
  191. self.tipangle_entry.set_precision(self.decimals)
  192. self.tipangle_entry.set_range(0.0000, 180.0000)
  193. self.tipangle_entry.setSingleStep(5)
  194. self.tipangle_entry.setObjectName('p_vtip_angle')
  195. self.grid3.addWidget(self.tipanglelabel, 4, 0)
  196. self.grid3.addWidget(self.tipangle_entry, 4, 1)
  197. # Cut Z entry
  198. cutzlabel = QtWidgets.QLabel('%s:' % _('Cut Z'))
  199. cutzlabel.setToolTip(
  200. _("Depth of cut into material. Negative value.\n"
  201. "In FlatCAM units.")
  202. )
  203. self.cutz_entry = FCDoubleSpinner(callback=self.confirmation_message)
  204. self.cutz_entry.set_precision(self.decimals)
  205. self.cutz_entry.set_range(-99999.9999, 0.0000)
  206. self.cutz_entry.setObjectName('p_cutz')
  207. self.cutz_entry.setToolTip(
  208. _("Depth of cut into material. Negative value.\n"
  209. "In FlatCAM units.")
  210. )
  211. self.grid3.addWidget(cutzlabel, 5, 0)
  212. self.grid3.addWidget(self.cutz_entry, 5, 1)
  213. # ### Tool Diameter ####
  214. self.addtool_entry_lbl = QtWidgets.QLabel('<b>%s:</b>' % _('Tool Dia'))
  215. self.addtool_entry_lbl.setToolTip(
  216. _("Diameter for the new tool to add in the Tool Table.\n"
  217. "If the tool is V-shape type then this value is automatically\n"
  218. "calculated from the other parameters.")
  219. )
  220. self.addtool_entry = FCDoubleSpinner(callback=self.confirmation_message)
  221. self.addtool_entry.set_precision(self.decimals)
  222. self.addtool_entry.set_range(0.000, 9999.9999)
  223. self.addtool_entry.setObjectName('p_tool_dia')
  224. self.grid3.addWidget(self.addtool_entry_lbl, 6, 0)
  225. self.grid3.addWidget(self.addtool_entry, 6, 1)
  226. hlay = QtWidgets.QHBoxLayout()
  227. self.addtool_btn = QtWidgets.QPushButton(_('Add'))
  228. self.addtool_btn.setToolTip(
  229. _("Add a new tool to the Tool Table\n"
  230. "with the diameter specified above.")
  231. )
  232. self.addtool_from_db_btn = QtWidgets.QPushButton(_('Add from DB'))
  233. self.addtool_from_db_btn.setToolTip(
  234. _("Add a new tool to the Tool Table\n"
  235. "from the Tool DataBase.")
  236. )
  237. hlay.addWidget(self.addtool_btn)
  238. hlay.addWidget(self.addtool_from_db_btn)
  239. self.grid3.addLayout(hlay, 7, 0, 1, 2)
  240. separator_line = QtWidgets.QFrame()
  241. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  242. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  243. self.grid3.addWidget(separator_line, 8, 0, 1, 2)
  244. self.deltool_btn = QtWidgets.QPushButton(_('Delete'))
  245. self.deltool_btn.setToolTip(
  246. _("Delete a selection of tools in the Tool Table\n"
  247. "by first selecting a row(s) in the Tool Table.")
  248. )
  249. self.grid3.addWidget(self.deltool_btn, 9, 0, 1, 2)
  250. self.grid3.addWidget(QtWidgets.QLabel(''), 10, 0, 1, 2)
  251. separator_line = QtWidgets.QFrame()
  252. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  253. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  254. self.grid3.addWidget(separator_line, 11, 0, 1, 2)
  255. self.tool_data_label = QtWidgets.QLabel(
  256. "<b>%s: <font color='#0000FF'>%s %d</font></b>" % (_('Parameters for'), _("Tool"), int(1)))
  257. self.tool_data_label.setToolTip(
  258. _(
  259. "The data used for creating GCode.\n"
  260. "Each tool store it's own set of such data."
  261. )
  262. )
  263. self.grid3.addWidget(self.tool_data_label, 12, 0, 1, 2)
  264. grid4 = QtWidgets.QGridLayout()
  265. grid4.setColumnStretch(0, 0)
  266. grid4.setColumnStretch(1, 1)
  267. self.tools_box.addLayout(grid4)
  268. # Overlap
  269. ovlabel = QtWidgets.QLabel('%s:' % _('Overlap'))
  270. ovlabel.setToolTip(
  271. _("How much (percentage) of the tool width to overlap each tool pass.\n"
  272. "Adjust the value starting with lower values\n"
  273. "and increasing it if areas that should be painted are still \n"
  274. "not painted.\n"
  275. "Lower values = faster processing, faster execution on CNC.\n"
  276. "Higher values = slow processing and slow execution on CNC\n"
  277. "due of too many paths.")
  278. )
  279. self.paintoverlap_entry = FCDoubleSpinner(callback=self.confirmation_message, suffix='%')
  280. self.paintoverlap_entry.set_precision(3)
  281. self.paintoverlap_entry.setWrapping(True)
  282. self.paintoverlap_entry.setRange(0.0000, 99.9999)
  283. self.paintoverlap_entry.setSingleStep(0.1)
  284. self.paintoverlap_entry.setObjectName('p_overlap')
  285. grid4.addWidget(ovlabel, 1, 0)
  286. grid4.addWidget(self.paintoverlap_entry, 1, 1)
  287. # Margin
  288. marginlabel = QtWidgets.QLabel('%s:' % _('Margin'))
  289. marginlabel.setToolTip(
  290. _("Distance by which to avoid\n"
  291. "the edges of the polygon to\n"
  292. "be painted.")
  293. )
  294. self.paintmargin_entry = FCDoubleSpinner(callback=self.confirmation_message)
  295. self.paintmargin_entry.set_precision(self.decimals)
  296. self.paintmargin_entry.set_range(-9999.9999, 9999.9999)
  297. self.paintmargin_entry.setObjectName('p_margin')
  298. grid4.addWidget(marginlabel, 2, 0)
  299. grid4.addWidget(self.paintmargin_entry, 2, 1)
  300. # Method
  301. methodlabel = QtWidgets.QLabel('%s:' % _('Method'))
  302. methodlabel.setToolTip(
  303. _("Algorithm for painting:\n"
  304. "- Standard: Fixed step inwards.\n"
  305. "- Seed-based: Outwards from seed.\n"
  306. "- Line-based: Parallel lines.\n"
  307. "- Laser-lines: Active only for Gerber objects.\n"
  308. "Will create lines that follow the traces.\n"
  309. "- Combo: In case of failure a new method will be picked from the above\n"
  310. "in the order specified.")
  311. )
  312. # self.paintmethod_combo = RadioSet([
  313. # {"label": _("Standard"), "value": "standard"},
  314. # {"label": _("Seed-based"), "value": _("Seed")},
  315. # {"label": _("Straight lines"), "value": _("Lines")},
  316. # {"label": _("Laser lines"), "value": _("Laser_lines")},
  317. # {"label": _("Combo"), "value": _("Combo")}
  318. # ], orientation='vertical', stretch=False)
  319. # for choice in self.paintmethod_combo.choices:
  320. # if choice['value'] == _("Laser_lines"):
  321. # choice["radio"].setEnabled(False)
  322. self.paintmethod_combo = FCComboBox()
  323. self.paintmethod_combo.addItems(
  324. [_("Standard"), _("Seed"), _("Lines"), _("Laser_lines"), _("Combo")]
  325. )
  326. idx = self.paintmethod_combo.findText(_("Laser_lines"))
  327. self.paintmethod_combo.model().item(idx).setEnabled(False)
  328. self.paintmethod_combo.setObjectName('p_method')
  329. grid4.addWidget(methodlabel, 7, 0)
  330. grid4.addWidget(self.paintmethod_combo, 7, 1)
  331. # Connect lines
  332. self.pathconnect_cb = FCCheckBox('%s' % _("Connect"))
  333. self.pathconnect_cb.setObjectName('p_connect')
  334. self.pathconnect_cb.setToolTip(
  335. _("Draw lines between resulting\n"
  336. "segments to minimize tool lifts.")
  337. )
  338. self.paintcontour_cb = FCCheckBox('%s' % _("Contour"))
  339. self.paintcontour_cb.setObjectName('p_contour')
  340. self.paintcontour_cb.setToolTip(
  341. _("Cut around the perimeter of the polygon\n"
  342. "to trim rough edges.")
  343. )
  344. grid4.addWidget(self.pathconnect_cb, 10, 0)
  345. grid4.addWidget(self.paintcontour_cb, 10, 1)
  346. separator_line = QtWidgets.QFrame()
  347. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  348. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  349. grid4.addWidget(separator_line, 11, 0, 1, 2)
  350. self.apply_param_to_all = FCButton(_("Apply parameters to all tools"))
  351. self.apply_param_to_all.setToolTip(
  352. _("The parameters in the current form will be applied\n"
  353. "on all the tools from the Tool Table.")
  354. )
  355. grid4.addWidget(self.apply_param_to_all, 12, 0, 1, 2)
  356. separator_line = QtWidgets.QFrame()
  357. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  358. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  359. grid4.addWidget(separator_line, 13, 0, 1, 2)
  360. # General Parameters
  361. self.gen_param_label = QtWidgets.QLabel('<b>%s</b>' % _("Common Parameters"))
  362. self.gen_param_label.setToolTip(
  363. _("Parameters that are common for all tools.")
  364. )
  365. grid4.addWidget(self.gen_param_label, 15, 0, 1, 2)
  366. self.rest_cb = FCCheckBox('%s' % _("Rest Machining"))
  367. self.rest_cb.setObjectName('p_rest_machining')
  368. self.rest_cb.setToolTip(
  369. _("If checked, use 'rest machining'.\n"
  370. "Basically it will clear copper outside PCB features,\n"
  371. "using the biggest tool and continue with the next tools,\n"
  372. "from bigger to smaller, to clear areas of copper that\n"
  373. "could not be cleared by previous tool, until there is\n"
  374. "no more copper to clear or there are no more tools.\n\n"
  375. "If not checked, use the standard algorithm.")
  376. )
  377. grid4.addWidget(self.rest_cb, 16, 0, 1, 2)
  378. # Polygon selection
  379. selectlabel = QtWidgets.QLabel('%s:' % _('Selection'))
  380. selectlabel.setToolTip(
  381. _("Selection of area to be processed.\n"
  382. "- 'Polygon Selection' - left mouse click to add/remove polygons to be processed.\n"
  383. "- 'Area Selection' - left mouse click to start selection of the area to be processed.\n"
  384. "Keeping a modifier key pressed (CTRL or SHIFT) will allow to add multiple areas.\n"
  385. "- 'All Polygons' - the process will start after click.\n"
  386. "- 'Reference Object' - will process the area specified by another object.")
  387. )
  388. # grid3 = QtWidgets.QGridLayout()
  389. # self.selectmethod_combo = RadioSet([
  390. # {"label": _("Polygon Selection"), "value": "single"},
  391. # {"label": _("Area Selection"), "value": "area"},
  392. # {"label": _("All Polygons"), "value": "all"},
  393. # {"label": _("Reference Object"), "value": "ref"}
  394. # ], orientation='vertical', stretch=False)
  395. # self.selectmethod_combo.setObjectName('p_selection')
  396. # self.selectmethod_combo.setToolTip(
  397. # _("How to select Polygons to be painted.\n"
  398. # "- 'Polygon Selection' - left mouse click to add/remove polygons to be painted.\n"
  399. # "- 'Area Selection' - left mouse click to start selection of the area to be painted.\n"
  400. # "Keeping a modifier key pressed (CTRL or SHIFT) will allow to add multiple areas.\n"
  401. # "- 'All Polygons' - the Paint will start after click.\n"
  402. # "- 'Reference Object' - will do non copper clearing within the area\n"
  403. # "specified by another object.")
  404. # )
  405. self.selectmethod_combo = FCComboBox()
  406. self.selectmethod_combo.addItems(
  407. [_("Polygon Selection"), _("Area Selection"), _("All Polygons"), _("Reference Object")]
  408. )
  409. self.selectmethod_combo.setObjectName('p_selection')
  410. grid4.addWidget(selectlabel, 18, 0)
  411. grid4.addWidget(self.selectmethod_combo, 18, 1)
  412. form1 = QtWidgets.QFormLayout()
  413. grid4.addLayout(form1, 20, 0, 1, 2)
  414. self.box_combo_type_label = QtWidgets.QLabel('%s:' % _("Ref. Type"))
  415. self.box_combo_type_label.setToolTip(
  416. _("The type of FlatCAM object to be used as paint reference.\n"
  417. "It can be Gerber, Excellon or Geometry.")
  418. )
  419. self.box_combo_type = FCComboBox()
  420. self.box_combo_type.addItem(_("Reference Gerber"))
  421. self.box_combo_type.addItem(_("Reference Excellon"))
  422. self.box_combo_type.addItem(_("Reference Geometry"))
  423. form1.addRow(self.box_combo_type_label, self.box_combo_type)
  424. self.box_combo_label = QtWidgets.QLabel('%s:' % _("Ref. Object"))
  425. self.box_combo_label.setToolTip(
  426. _("The FlatCAM object to be used as non copper clearing reference.")
  427. )
  428. self.box_combo = FCComboBox()
  429. self.box_combo.setModel(self.app.collection)
  430. self.box_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  431. self.box_combo.set_last = True
  432. form1.addRow(self.box_combo_label, self.box_combo)
  433. self.box_combo.hide()
  434. self.box_combo_label.hide()
  435. self.box_combo_type.hide()
  436. self.box_combo_type_label.hide()
  437. # GO Button
  438. self.generate_paint_button = QtWidgets.QPushButton(_('Generate Geometry'))
  439. self.generate_paint_button.setToolTip(
  440. _("- 'Area Selection' - left mouse click to start selection of the area to be painted.\n"
  441. "Keeping a modifier key pressed (CTRL or SHIFT) will allow to add multiple areas.\n"
  442. "- 'All Polygons' - the Paint will start after click.\n"
  443. "- 'Reference Object' - will do non copper clearing within the area\n"
  444. "specified by another object.")
  445. )
  446. self.generate_paint_button.setStyleSheet("""
  447. QPushButton
  448. {
  449. font-weight: bold;
  450. }
  451. """)
  452. self.tools_box.addWidget(self.generate_paint_button)
  453. self.tools_box.addStretch()
  454. # ## Reset Tool
  455. self.reset_button = QtWidgets.QPushButton(_("Reset Tool"))
  456. self.reset_button.setToolTip(
  457. _("Will reset the tool parameters.")
  458. )
  459. self.reset_button.setStyleSheet("""
  460. QPushButton
  461. {
  462. font-weight: bold;
  463. }
  464. """)
  465. self.tools_box.addWidget(self.reset_button)
  466. # #################################### FINSIHED GUI ###########################
  467. # #############################################################################
  468. # #############################################################################
  469. # ########################## VARIABLES ########################################
  470. # #############################################################################
  471. self.obj_name = ""
  472. self.paint_obj = None
  473. self.bound_obj_name = ""
  474. self.bound_obj = None
  475. self.tooldia_list = []
  476. self.tooldia = None
  477. self.sel_rect = None
  478. self.o_name = None
  479. self.overlap = None
  480. self.connect = None
  481. self.contour = None
  482. self.select_method = None
  483. self.units = ''
  484. self.paint_tools = {}
  485. self.tooluid = 0
  486. self.first_click = False
  487. self.cursor_pos = None
  488. self.mouse_is_dragging = False
  489. self.mm = None
  490. self.mp = None
  491. self.mr = None
  492. self.sel_rect = []
  493. # store here if the grid snapping is active
  494. self.grid_status_memory = False
  495. # dict to store the polygons selected for painting; key is the shape added to be plotted and value is the poly
  496. self.poly_dict = {}
  497. # store here the default data for Geometry Data
  498. self.default_data = {}
  499. self.tool_type_item_options = ["C1", "C2", "C3", "C4", "B", "V"]
  500. self.form_fields = {
  501. "paintoverlap": self.paintoverlap_entry,
  502. "paintmargin": self.paintmargin_entry,
  503. "paintmethod": self.paintmethod_combo,
  504. "pathconnect": self.pathconnect_cb,
  505. "paintcontour": self.paintcontour_cb,
  506. }
  507. self.name2option = {
  508. 'p_overlap': "paintoverlap",
  509. 'p_margin': "paintmargin",
  510. 'p_method': "paintmethod",
  511. 'p_connect': "pathconnect",
  512. 'p_contour': "paintcontour",
  513. }
  514. self.old_tool_dia = None
  515. # #############################################################################
  516. # ################################# Signals ###################################
  517. # #############################################################################
  518. self.addtool_btn.clicked.connect(self.on_tool_add)
  519. self.addtool_entry.returnPressed.connect(self.on_tool_add)
  520. self.deltool_btn.clicked.connect(self.on_tool_delete)
  521. self.tipdia_entry.returnPressed.connect(self.on_calculate_tooldia)
  522. self.tipangle_entry.returnPressed.connect(self.on_calculate_tooldia)
  523. self.cutz_entry.returnPressed.connect(self.on_calculate_tooldia)
  524. # self.copytool_btn.clicked.connect(lambda: self.on_tool_copy())
  525. # self.tools_table.itemChanged.connect(self.on_tool_edit)
  526. self.tools_table.clicked.connect(self.on_row_selection_change)
  527. self.generate_paint_button.clicked.connect(self.on_paint_button_click)
  528. self.selectmethod_combo.currentIndexChanged.connect(self.on_selection)
  529. self.order_radio.activated_custom[str].connect(self.on_order_changed)
  530. self.rest_cb.stateChanged.connect(self.on_rest_machining_check)
  531. self.box_combo_type.currentIndexChanged.connect(self.on_combo_box_type)
  532. self.type_obj_combo.activated_custom.connect(self.on_type_obj_changed)
  533. self.apply_param_to_all.clicked.connect(self.on_apply_param_to_all_clicked)
  534. self.reset_button.clicked.connect(self.set_tool_ui)
  535. # #############################################################################
  536. # ###################### Setup CONTEXT MENU ###################################
  537. # #############################################################################
  538. self.tools_table.setupContextMenu()
  539. self.tools_table.addContextMenu(
  540. _("Add"), self.on_add_tool_by_key, icon=QtGui.QIcon(self.app.resource_location + "/plus16.png")
  541. )
  542. self.tools_table.addContextMenu(
  543. _("Add from DB"), self.on_add_tool_by_key, icon=QtGui.QIcon(self.app.resource_location + "/plus16.png")
  544. )
  545. self.tools_table.addContextMenu(
  546. _("Delete"), lambda:
  547. self.on_tool_delete(rows_to_delete=None, all_tools=None),
  548. icon=QtGui.QIcon(self.app.resource_location + "/delete32.png")
  549. )
  550. def on_type_obj_changed(self, val):
  551. obj_type = 0 if val == 'gerber' else 2
  552. self.obj_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  553. self.obj_combo.setCurrentIndex(0)
  554. idx = self.paintmethod_combo.findText(_("Laser_lines"))
  555. if self.type_obj_combo.get_value().lower() == 'gerber':
  556. self.paintmethod_combo.model().item(idx).setEnabled(True)
  557. else:
  558. self.paintmethod_combo.model().item(idx).setEnabled(False)
  559. if self.paintmethod_combo.get_value() == _("Laser_lines"):
  560. self.paintmethod_combo.set_value(_("Lines"))
  561. def install(self, icon=None, separator=None, **kwargs):
  562. FlatCAMTool.install(self, icon, separator, shortcut='ALT+P', **kwargs)
  563. def run(self, toggle=True):
  564. self.app.report_usage("ToolPaint()")
  565. log.debug("ToolPaint().run() was launched ...")
  566. if toggle:
  567. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  568. if self.app.ui.splitter.sizes()[0] == 0:
  569. self.app.ui.splitter.setSizes([1, 1])
  570. else:
  571. try:
  572. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  573. # if tab is populated with the tool but it does not have the focus, focus on it
  574. if not self.app.ui.notebook.currentWidget() is self.app.ui.tool_tab:
  575. # focus on Tool Tab
  576. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  577. else:
  578. self.app.ui.splitter.setSizes([0, 1])
  579. except AttributeError:
  580. pass
  581. else:
  582. if self.app.ui.splitter.sizes()[0] == 0:
  583. self.app.ui.splitter.setSizes([1, 1])
  584. FlatCAMTool.run(self)
  585. self.set_tool_ui()
  586. self.app.ui.notebook.setTabText(2, _("Paint Tool"))
  587. def on_row_selection_change(self):
  588. self.blockSignals(True)
  589. sel_rows = [it.row() for it in self.tools_table.selectedItems()]
  590. # sel_rows = sorted(set(index.row() for index in self.tools_table.selectedIndexes()))
  591. if not sel_rows:
  592. sel_rows = [0]
  593. for current_row in sel_rows:
  594. # populate the form with the data from the tool associated with the row parameter
  595. try:
  596. item = self.tools_table.item(current_row, 3)
  597. if item is None:
  598. return 'fail'
  599. tooluid = int(item.text())
  600. except Exception as e:
  601. log.debug("Tool missing. Add a tool in the Tool Table. %s" % str(e))
  602. return
  603. # update the QLabel that shows for which Tool we have the parameters in the UI form
  604. if len(sel_rows) == 1:
  605. cr = self.tools_table.item(current_row, 0).text()
  606. self.tool_data_label.setText(
  607. "<b>%s: <font color='#0000FF'>%s %s</font></b>" % (_('Parameters for'), _("Tool"), cr)
  608. )
  609. try:
  610. # set the form with data from the newly selected tool
  611. for tooluid_key, tooluid_value in list(self.paint_tools.items()):
  612. if int(tooluid_key) == tooluid:
  613. for key, value in tooluid_value.items():
  614. if key == 'data':
  615. form_value_storage = tooluid_value[key]
  616. self.storage_to_form(form_value_storage)
  617. except Exception as e:
  618. log.debug("ToolPaint ---> update_ui() " + str(e))
  619. else:
  620. self.tool_data_label.setText(
  621. "<b>%s: <font color='#0000FF'>%s</font></b>" % (_('Parameters for'), _("Multiple Tools"))
  622. )
  623. self.blockSignals(False)
  624. def storage_to_form(self, dict_storage):
  625. for form_key in self.form_fields:
  626. for storage_key in dict_storage:
  627. if form_key == storage_key:
  628. try:
  629. self.form_fields[form_key].set_value(dict_storage[form_key])
  630. except Exception:
  631. pass
  632. def form_to_storage(self):
  633. if self.tools_table.rowCount() == 0:
  634. # there is no tool in tool table so we can't save the GUI elements values to storage
  635. return
  636. self.blockSignals(True)
  637. widget_changed = self.sender()
  638. wdg_objname = widget_changed.objectName()
  639. option_changed = self.name2option[wdg_objname]
  640. # row = self.tools_table.currentRow()
  641. rows = sorted(set(index.row() for index in self.tools_table.selectedIndexes()))
  642. for row in rows:
  643. if row < 0:
  644. row = 0
  645. tooluid_item = int(self.tools_table.item(row, 3).text())
  646. for tooluid_key, tooluid_val in self.paint_tools.items():
  647. if int(tooluid_key) == tooluid_item:
  648. new_option_value = self.form_fields[option_changed].get_value()
  649. if option_changed in tooluid_val:
  650. tooluid_val[option_changed] = new_option_value
  651. if option_changed in tooluid_val['data']:
  652. tooluid_val['data'][option_changed] = new_option_value
  653. self.blockSignals(False)
  654. def on_apply_param_to_all_clicked(self):
  655. if self.tools_table.rowCount() == 0:
  656. # there is no tool in tool table so we can't save the GUI elements values to storage
  657. log.debug("NonCopperClear.on_apply_param_to_all_clicked() --> no tool in Tools Table, aborting.")
  658. return
  659. self.blockSignals(True)
  660. row = self.tools_table.currentRow()
  661. if row < 0:
  662. row = 0
  663. tooluid_item = int(self.tools_table.item(row, 3).text())
  664. temp_tool_data = {}
  665. for tooluid_key, tooluid_val in self.paint_tools.items():
  666. if int(tooluid_key) == tooluid_item:
  667. # this will hold the 'data' key of the self.tools[tool] dictionary that corresponds to
  668. # the current row in the tool table
  669. temp_tool_data = tooluid_val['data']
  670. break
  671. for tooluid_key, tooluid_val in self.paint_tools.items():
  672. tooluid_val['data'] = deepcopy(temp_tool_data)
  673. self.app.inform.emit('[success] %s' % _("Current Tool parameters were applied to all tools."))
  674. self.blockSignals(False)
  675. def on_add_tool_by_key(self):
  676. tool_add_popup = FCInputDialog(title='%s...' % _("New Tool"),
  677. text='%s:' % _('Enter a Tool Diameter'),
  678. min=0.0000, max=99.9999, decimals=4)
  679. tool_add_popup.setWindowIcon(QtGui.QIcon(self.app.resource_location + '/letter_t_32.png'))
  680. val, ok = tool_add_popup.get_value()
  681. if ok:
  682. if float(val) == 0:
  683. self.app.inform.emit('[WARNING_NOTCL] %s' %
  684. _("Please enter a tool diameter with non-zero value, in Float format."))
  685. return
  686. self.on_tool_add(dia=float(val))
  687. else:
  688. self.app.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  689. def on_tooltable_cellwidget_change(self):
  690. cw = self.sender()
  691. cw_index = self.tools_table.indexAt(cw.pos())
  692. cw_row = cw_index.row()
  693. cw_col = cw_index.column()
  694. current_uid = int(self.tools_table.item(cw_row, 3).text())
  695. # if the sender is in the column with index 2 then we update the tool_type key
  696. if cw_col == 2:
  697. tt = cw.currentText()
  698. typ = 'Iso' if tt == 'V' else "Rough"
  699. self.paint_tools[current_uid].update({
  700. 'type': typ,
  701. 'tool_type': tt,
  702. })
  703. def on_tool_type(self, val):
  704. if val == 'V':
  705. self.addtool_entry_lbl.setDisabled(True)
  706. self.addtool_entry.setDisabled(True)
  707. self.tipdialabel.show()
  708. self.tipdia_entry.show()
  709. self.tipanglelabel.show()
  710. self.tipangle_entry.show()
  711. self.on_calculate_tooldia()
  712. else:
  713. self.addtool_entry_lbl.setDisabled(False)
  714. self.addtool_entry.setDisabled(False)
  715. self.tipdialabel.hide()
  716. self.tipdia_entry.hide()
  717. self.tipanglelabel.hide()
  718. self.tipangle_entry.hide()
  719. self.addtool_entry.set_value(self.old_tool_dia)
  720. def on_calculate_tooldia(self):
  721. if self.tool_type_radio.get_value() == 'V':
  722. tip_dia = float(self.tipdia_entry.get_value())
  723. tip_angle = float(self.tipangle_entry.get_value()) / 2.0
  724. cut_z = float(self.cutz_entry.get_value())
  725. cut_z = -cut_z if cut_z < 0 else cut_z
  726. # calculated tool diameter so the cut_z parameter is obeyed
  727. tool_dia = tip_dia + (2 * cut_z * math.tan(math.radians(tip_angle)))
  728. # update the default_data so it is used in the ncc_tools dict
  729. self.default_data.update({
  730. "vtipdia": tip_dia,
  731. "vtipangle": (tip_angle * 2),
  732. })
  733. self.addtool_entry.set_value(tool_dia)
  734. return tool_dia
  735. else:
  736. return float(self.addtool_entry.get_value())
  737. def on_selection(self):
  738. if self.selectmethod_combo.get_value() == _("Reference Object"):
  739. self.box_combo.show()
  740. self.box_combo_label.show()
  741. self.box_combo_type.show()
  742. self.box_combo_type_label.show()
  743. else:
  744. self.box_combo.hide()
  745. self.box_combo_label.hide()
  746. self.box_combo_type.hide()
  747. self.box_combo_type_label.hide()
  748. if self.selectmethod_combo.get_value() == _("Polygon Selection"):
  749. # disable rest-machining for single polygon painting
  750. self.rest_cb.set_value(False)
  751. self.rest_cb.setDisabled(True)
  752. if self.selectmethod_combo.get_value() == _("Area Selection"):
  753. # disable rest-machining for single polygon painting
  754. self.rest_cb.set_value(False)
  755. self.rest_cb.setDisabled(True)
  756. else:
  757. self.rest_cb.setDisabled(False)
  758. self.addtool_entry.setDisabled(False)
  759. self.addtool_btn.setDisabled(False)
  760. self.deltool_btn.setDisabled(False)
  761. self.tools_table.setContextMenuPolicy(Qt.ActionsContextMenu)
  762. def on_order_changed(self, order):
  763. if order != 'no':
  764. self.build_ui()
  765. def on_rest_machining_check(self, state):
  766. if state:
  767. self.order_radio.set_value('rev')
  768. self.order_label.setDisabled(True)
  769. self.order_radio.setDisabled(True)
  770. else:
  771. self.order_label.setDisabled(False)
  772. self.order_radio.setDisabled(False)
  773. def set_tool_ui(self):
  774. self.tools_frame.show()
  775. self.reset_fields()
  776. self.old_tool_dia = self.app.defaults["tools_paintnewdia"]
  777. # updated units
  778. self.units = self.app.defaults['units'].upper()
  779. # set the working variables to a known state
  780. self.paint_tools.clear()
  781. self.tooluid = 0
  782. self.default_data.clear()
  783. self.default_data.update({
  784. "name": '_paint',
  785. "plot": self.app.defaults["geometry_plot"],
  786. "cutz": float(self.cutz_entry.get_value()),
  787. "vtipdia": float(self.tipdia_entry.get_value()),
  788. "vtipangle": float(self.tipangle_entry.get_value()),
  789. "travelz": float(self.app.defaults["geometry_travelz"]),
  790. "feedrate": float(self.app.defaults["geometry_feedrate"]),
  791. "feedrate_z": float(self.app.defaults["geometry_feedrate_z"]),
  792. "feedrate_rapid": float(self.app.defaults["geometry_feedrate_rapid"]),
  793. "dwell": self.app.defaults["geometry_dwell"],
  794. "dwelltime": float(self.app.defaults["geometry_dwelltime"]),
  795. "multidepth": self.app.defaults["geometry_multidepth"],
  796. "ppname_g": self.app.defaults["geometry_ppname_g"],
  797. "depthperpass": float(self.app.defaults["geometry_depthperpass"]),
  798. "extracut": self.app.defaults["geometry_extracut"],
  799. "extracut_length": self.app.defaults["geometry_extracut_length"],
  800. "toolchange": self.app.defaults["geometry_toolchange"],
  801. "toolchangez": float(self.app.defaults["geometry_toolchangez"]),
  802. "endz": float(self.app.defaults["geometry_endz"]),
  803. "endxy": self.app.defaults["geometry_endxy"],
  804. "spindlespeed": self.app.defaults["geometry_spindlespeed"],
  805. "toolchangexy": self.app.defaults["geometry_toolchangexy"],
  806. "startz": self.app.defaults["geometry_startz"],
  807. "tooldia": self.app.defaults["tools_painttooldia"],
  808. "paintmargin": self.app.defaults["tools_paintmargin"],
  809. "paintmethod": self.app.defaults["tools_paintmethod"],
  810. "selectmethod": self.app.defaults["tools_selectmethod"],
  811. "pathconnect": self.app.defaults["tools_pathconnect"],
  812. "paintcontour": self.app.defaults["tools_paintcontour"],
  813. "paintoverlap": self.app.defaults["tools_paintoverlap"],
  814. "paintrest": self.app.defaults["tools_paintrest"],
  815. })
  816. # ## Init the GUI interface
  817. self.order_radio.set_value(self.app.defaults["tools_paintorder"])
  818. self.paintmargin_entry.set_value(self.app.defaults["tools_paintmargin"])
  819. self.paintmethod_combo.set_value(self.app.defaults["tools_paintmethod"])
  820. self.selectmethod_combo.set_value(self.app.defaults["tools_selectmethod"])
  821. self.pathconnect_cb.set_value(self.app.defaults["tools_pathconnect"])
  822. self.paintcontour_cb.set_value(self.app.defaults["tools_paintcontour"])
  823. self.paintoverlap_entry.set_value(self.app.defaults["tools_paintoverlap"])
  824. self.cutz_entry.set_value(self.app.defaults["tools_paintcutz"])
  825. self.tool_type_radio.set_value(self.app.defaults["tools_painttool_type"])
  826. self.tipdia_entry.set_value(self.app.defaults["tools_painttipdia"])
  827. self.tipangle_entry.set_value(self.app.defaults["tools_painttipangle"])
  828. self.addtool_entry.set_value(self.app.defaults["tools_paintnewdia"])
  829. self.rest_cb.set_value(self.app.defaults["tools_paintrest"])
  830. self.on_tool_type(val=self.tool_type_radio.get_value())
  831. # make the default object type, "Geometry"
  832. self.type_obj_combo.set_value("geometry")
  833. try:
  834. diameters = [float(self.app.defaults["tools_painttooldia"])]
  835. except (ValueError, TypeError):
  836. diameters = [eval(x) for x in self.app.defaults["tools_painttooldia"].split(",") if x != '']
  837. if not diameters:
  838. log.error("At least one tool diameter needed. Verify in Edit -> Preferences -> TOOLS -> NCC Tools.")
  839. self.build_ui()
  840. # if the Paint Method is "Single" disable the tool table context menu
  841. if self.default_data["selectmethod"] == "single":
  842. self.tools_table.setContextMenuPolicy(Qt.NoContextMenu)
  843. return
  844. # call on self.on_tool_add() counts as an call to self.build_ui()
  845. # through this, we add a initial row / tool in the tool_table
  846. for dia in diameters:
  847. self.on_tool_add(dia, muted=True)
  848. # if the Paint Method is "Single" disable the tool table context menu
  849. if self.default_data["selectmethod"] == "single":
  850. self.tools_table.setContextMenuPolicy(Qt.NoContextMenu)
  851. def build_ui(self):
  852. self.ui_disconnect()
  853. # updated units
  854. self.units = self.app.defaults['units'].upper()
  855. sorted_tools = []
  856. for k, v in self.paint_tools.items():
  857. sorted_tools.append(float('%.*f' % (self.decimals, float(v['tooldia']))))
  858. order = self.order_radio.get_value()
  859. if order == 'fwd':
  860. sorted_tools.sort(reverse=False)
  861. elif order == 'rev':
  862. sorted_tools.sort(reverse=True)
  863. else:
  864. pass
  865. n = len(sorted_tools)
  866. self.tools_table.setRowCount(n)
  867. tool_id = 0
  868. for tool_sorted in sorted_tools:
  869. for tooluid_key, tooluid_value in self.paint_tools.items():
  870. if float('%.*f' % (self.decimals, tooluid_value['tooldia'])) == tool_sorted:
  871. tool_id += 1
  872. id_item = QtWidgets.QTableWidgetItem('%d' % int(tool_id))
  873. id_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  874. row_no = tool_id - 1
  875. self.tools_table.setItem(row_no, 0, id_item) # Tool name/id
  876. # Make sure that the drill diameter when in MM is with no more than 2 decimals
  877. # There are no drill bits in MM with more than 2 decimals diameter
  878. # For INCH the decimals should be no more than 4. There are no drills under 10mils
  879. dia = QtWidgets.QTableWidgetItem('%.*f' % (self.decimals, tooluid_value['tooldia']))
  880. dia.setFlags(QtCore.Qt.ItemIsEnabled)
  881. tool_type_item = FCComboBox()
  882. for item in self.tool_type_item_options:
  883. tool_type_item.addItem(item)
  884. # tool_type_item.setStyleSheet('background-color: rgb(255,255,255)')
  885. idx = tool_type_item.findText(tooluid_value['tool_type'])
  886. tool_type_item.setCurrentIndex(idx)
  887. tool_uid_item = QtWidgets.QTableWidgetItem(str(int(tooluid_key)))
  888. self.tools_table.setItem(row_no, 1, dia) # Diameter
  889. self.tools_table.setCellWidget(row_no, 2, tool_type_item)
  890. # ## REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY # ##
  891. self.tools_table.setItem(row_no, 3, tool_uid_item) # Tool unique ID
  892. # make the diameter column editable
  893. for row in range(tool_id):
  894. self.tools_table.item(row, 1).setFlags(
  895. QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  896. # all the tools are selected by default
  897. self.tools_table.selectColumn(0)
  898. #
  899. self.tools_table.resizeColumnsToContents()
  900. self.tools_table.resizeRowsToContents()
  901. vertical_header = self.tools_table.verticalHeader()
  902. vertical_header.hide()
  903. self.tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  904. horizontal_header = self.tools_table.horizontalHeader()
  905. horizontal_header.setMinimumSectionSize(10)
  906. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  907. horizontal_header.resizeSection(0, 20)
  908. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  909. # self.tools_table.setSortingEnabled(True)
  910. # sort by tool diameter
  911. # self.tools_table.sortItems(1)
  912. self.tools_table.setMinimumHeight(self.tools_table.getHeight())
  913. self.tools_table.setMaximumHeight(self.tools_table.getHeight())
  914. self.ui_connect()
  915. def on_combo_box_type(self):
  916. obj_type = self.box_combo_type.currentIndex()
  917. self.box_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  918. self.box_combo.setCurrentIndex(0)
  919. def on_tool_add(self, dia=None, muted=None):
  920. self.blockSignals(True)
  921. if dia:
  922. tool_dia = dia
  923. else:
  924. tool_dia = self.on_calculate_tooldia()
  925. if tool_dia is None:
  926. self.build_ui()
  927. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Please enter a tool diameter to add, in Float format."))
  928. return
  929. # construct a list of all 'tooluid' in the self.tools
  930. tool_uid_list = []
  931. for tooluid_key in self.paint_tools:
  932. tool_uid_item = int(tooluid_key)
  933. tool_uid_list.append(tool_uid_item)
  934. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  935. if not tool_uid_list:
  936. max_uid = 0
  937. else:
  938. max_uid = max(tool_uid_list)
  939. self.tooluid = int(max_uid + 1)
  940. tool_dias = []
  941. for k, v in self.paint_tools.items():
  942. for tool_v in v.keys():
  943. if tool_v == 'tooldia':
  944. tool_dias.append(float('%.*f' % (self.decimals, v[tool_v])))
  945. if float('%.*f' % (self.decimals, tool_dia)) in tool_dias:
  946. if muted is None:
  947. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Adding tool cancelled. Tool already in Tool Table."))
  948. self.tools_table.itemChanged.connect(self.on_tool_edit)
  949. return
  950. else:
  951. if muted is None:
  952. self.app.inform.emit('[success] %s' % _("New tool added to Tool Table."))
  953. self.paint_tools.update({
  954. int(self.tooluid): {
  955. 'tooldia': float('%.*f' % (self.decimals, tool_dia)),
  956. 'offset': 'Path',
  957. 'offset_value': 0.0,
  958. 'type': 'Iso',
  959. 'tool_type': self.tool_type_radio.get_value(),
  960. 'data': dict(self.default_data),
  961. 'solid_geometry': []
  962. }
  963. })
  964. self.blockSignals(False)
  965. self.build_ui()
  966. def on_tool_edit(self):
  967. self.blockSignals(True)
  968. old_tool_dia = ''
  969. tool_dias = []
  970. for k, v in self.paint_tools.items():
  971. for tool_v in v.keys():
  972. if tool_v == 'tooldia':
  973. tool_dias.append(float('%.*f' % (self.decimals, v[tool_v])))
  974. for row in range(self.tools_table.rowCount()):
  975. try:
  976. new_tool_dia = float(self.tools_table.item(row, 1).text())
  977. except ValueError:
  978. # try to convert comma to decimal point. if it's still not working error message and return
  979. try:
  980. new_tool_dia = float(self.tools_table.item(row, 1).text().replace(',', '.'))
  981. except ValueError:
  982. self.app.inform.emit('[ERROR_NOTCL] %s' %
  983. _("Wrong value format entered, use a number."))
  984. return
  985. tooluid = int(self.tools_table.item(row, 3).text())
  986. # identify the tool that was edited and get it's tooluid
  987. if new_tool_dia not in tool_dias:
  988. self.paint_tools[tooluid]['tooldia'] = new_tool_dia
  989. self.app.inform.emit('[success] %s' %
  990. _("Tool from Tool Table was edited."))
  991. self.build_ui()
  992. return
  993. else:
  994. # identify the old tool_dia and restore the text in tool table
  995. for k, v in self.paint_tools.items():
  996. if k == tooluid:
  997. old_tool_dia = v['tooldia']
  998. break
  999. restore_dia_item = self.tools_table.item(row, 1)
  1000. restore_dia_item.setText(str(old_tool_dia))
  1001. self.app.inform.emit('[WARNING_NOTCL] %s' %
  1002. _("Edit cancelled. New diameter value is already in the Tool Table."))
  1003. self.blockSignals(False)
  1004. self.build_ui()
  1005. # def on_tool_copy(self, all=None):
  1006. # try:
  1007. # self.tools_table.itemChanged.disconnect()
  1008. # except:
  1009. # pass
  1010. #
  1011. # # find the tool_uid maximum value in the self.tools
  1012. # uid_list = []
  1013. # for key in self.paint_tools:
  1014. # uid_list.append(int(key))
  1015. # try:
  1016. # max_uid = max(uid_list, key=int)
  1017. # except ValueError:
  1018. # max_uid = 0
  1019. #
  1020. # if all is None:
  1021. # if self.tools_table.selectedItems():
  1022. # for current_row in self.tools_table.selectedItems():
  1023. # # sometime the header get selected and it has row number -1
  1024. # # we don't want to do anything with the header :)
  1025. # if current_row.row() < 0:
  1026. # continue
  1027. # try:
  1028. # tooluid_copy = int(self.tools_table.item(current_row.row(), 3).text())
  1029. # max_uid += 1
  1030. # self.paint_tools[int(max_uid)] = dict(self.paint_tools[tooluid_copy])
  1031. # for td in self.paint_tools:
  1032. # print("COPIED", self.paint_tools[td])
  1033. # self.build_ui()
  1034. # except AttributeError:
  1035. # self.app.inform.emit("[WARNING_NOTCL] Failed. Select a tool to copy.")
  1036. # self.build_ui()
  1037. # return
  1038. # except Exception as e:
  1039. # log.debug("on_tool_copy() --> " + str(e))
  1040. # # deselect the table
  1041. # # self.ui.geo_tools_table.clearSelection()
  1042. # else:
  1043. # self.app.inform.emit("[WARNING_NOTCL] Failed. Select a tool to copy.")
  1044. # self.build_ui()
  1045. # return
  1046. # else:
  1047. # # we copy all tools in geo_tools_table
  1048. # try:
  1049. # temp_tools = dict(self.paint_tools)
  1050. # max_uid += 1
  1051. # for tooluid in temp_tools:
  1052. # self.paint_tools[int(max_uid)] = dict(temp_tools[tooluid])
  1053. # temp_tools.clear()
  1054. # self.build_ui()
  1055. # except Exception as e:
  1056. # log.debug("on_tool_copy() --> " + str(e))
  1057. #
  1058. # self.app.inform.emit("[success] Tool was copied in the Tool Table.")
  1059. def on_tool_delete(self, rows_to_delete=None, all_tools=None):
  1060. self.blockSignals(True)
  1061. deleted_tools_list = []
  1062. if all_tools:
  1063. self.paint_tools.clear()
  1064. self.blockSignals(False)
  1065. self.build_ui()
  1066. return
  1067. if rows_to_delete:
  1068. try:
  1069. for row in rows_to_delete:
  1070. tooluid_del = int(self.tools_table.item(row, 3).text())
  1071. deleted_tools_list.append(tooluid_del)
  1072. except TypeError:
  1073. deleted_tools_list.append(rows_to_delete)
  1074. for t in deleted_tools_list:
  1075. self.paint_tools.pop(t, None)
  1076. self.blockSignals(False)
  1077. self.build_ui()
  1078. return
  1079. try:
  1080. if self.tools_table.selectedItems():
  1081. for row_sel in self.tools_table.selectedItems():
  1082. row = row_sel.row()
  1083. if row < 0:
  1084. continue
  1085. tooluid_del = int(self.tools_table.item(row, 3).text())
  1086. deleted_tools_list.append(tooluid_del)
  1087. for t in deleted_tools_list:
  1088. self.paint_tools.pop(t, None)
  1089. except AttributeError:
  1090. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Delete failed. Select a tool to delete."))
  1091. self.blockSignals(False)
  1092. return
  1093. except Exception as e:
  1094. log.debug(str(e))
  1095. self.app.inform.emit('[success] %s' % _("Tool(s) deleted from Tool Table."))
  1096. self.blockSignals(False)
  1097. self.build_ui()
  1098. def on_paint_button_click(self):
  1099. # init values for the next usage
  1100. self.reset_usage()
  1101. self.app.report_usage("on_paint_button_click")
  1102. # self.app.call_source = 'paint'
  1103. # #####################################################
  1104. # ######### Reading Parameters ########################
  1105. # #####################################################
  1106. self.app.inform.emit(_("Paint Tool. Reading parameters."))
  1107. self.overlap = float(self.paintoverlap_entry.get_value()) / 100.0
  1108. self.connect = self.pathconnect_cb.get_value()
  1109. self.contour = self.paintcontour_cb.get_value()
  1110. self.select_method = self.selectmethod_combo.get_value()
  1111. self.obj_name = self.obj_combo.currentText()
  1112. # Get source object.
  1113. try:
  1114. self.paint_obj = self.app.collection.get_by_name(str(self.obj_name))
  1115. except Exception as e:
  1116. log.debug("ToolPaint.on_paint_button_click() --> %s" % str(e))
  1117. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object: %s"), self.obj_name))
  1118. return
  1119. if self.paint_obj is None:
  1120. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Object not found"), self.paint_obj))
  1121. return
  1122. # test if the Geometry Object is multigeo and return Fail if True because
  1123. # for now Paint don't work on MultiGeo
  1124. if self.paint_obj.multigeo is True:
  1125. self.app.inform.emit('[ERROR_NOTCL] %s...' % _("Can't do Paint on MultiGeo geometries"))
  1126. return 'Fail'
  1127. self.o_name = '%s_mt_paint' % self.obj_name
  1128. # use the selected tools in the tool table; get diameters
  1129. self.tooldia_list = []
  1130. if self.tools_table.selectedItems():
  1131. for x in self.tools_table.selectedItems():
  1132. try:
  1133. self.tooldia = float(self.tools_table.item(x.row(), 1).text())
  1134. except ValueError:
  1135. # try to convert comma to decimal point. if it's still not working error message and return
  1136. try:
  1137. self.tooldia = float(self.tools_table.item(x.row(), 1).text().replace(',', '.'))
  1138. except ValueError:
  1139. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Wrong value format entered, use a number."))
  1140. continue
  1141. self.tooldia_list.append(self.tooldia)
  1142. else:
  1143. self.app.inform.emit('[ERROR_NOTCL] %s' % _("No selected tools in Tool Table."))
  1144. return
  1145. if self.select_method == _("All Polygons"):
  1146. self.paint_poly_all(self.paint_obj,
  1147. tooldia=self.tooldia_list,
  1148. outname=self.o_name,
  1149. overlap=self.overlap,
  1150. connect=self.connect,
  1151. contour=self.contour)
  1152. elif self.select_method == _("Polygon Selection"):
  1153. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Click on a polygon to paint it."))
  1154. # disengage the grid snapping since it may be hard to click on polygons with grid snapping on
  1155. if self.app.ui.grid_snap_btn.isChecked():
  1156. self.grid_status_memory = True
  1157. self.app.ui.grid_snap_btn.trigger()
  1158. else:
  1159. self.grid_status_memory = False
  1160. self.mr = self.app.plotcanvas.graph_event_connect('mouse_release', self.on_single_poly_mouse_release)
  1161. if self.app.is_legacy is False:
  1162. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  1163. self.app.plotcanvas.graph_event_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  1164. else:
  1165. self.app.plotcanvas.graph_event_disconnect(self.app.mr)
  1166. self.app.plotcanvas.graph_event_disconnect(self.app.mp)
  1167. elif self.select_method == _("Area Selection"):
  1168. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Click the start point of the paint area."))
  1169. if self.app.is_legacy is False:
  1170. self.app.plotcanvas.graph_event_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  1171. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  1172. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  1173. else:
  1174. self.app.plotcanvas.graph_event_disconnect(self.app.mp)
  1175. self.app.plotcanvas.graph_event_disconnect(self.app.mm)
  1176. self.app.plotcanvas.graph_event_disconnect(self.app.mr)
  1177. self.mr = self.app.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_release)
  1178. self.mm = self.app.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move)
  1179. elif self.select_method == _("Reference Object"):
  1180. self.bound_obj_name = self.box_combo.currentText()
  1181. # Get source object.
  1182. try:
  1183. self.bound_obj = self.app.collection.get_by_name(self.bound_obj_name)
  1184. except Exception:
  1185. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), self.obj_name))
  1186. return "Could not retrieve object: %s" % self.obj_name
  1187. self.paint_poly_ref(obj=self.paint_obj,
  1188. sel_obj=self.bound_obj,
  1189. tooldia=self.tooldia_list,
  1190. overlap=self.overlap,
  1191. outname=self.o_name,
  1192. connect=self.connect,
  1193. contour=self.contour)
  1194. # To be called after clicking on the plot.
  1195. def on_single_poly_mouse_release(self, event):
  1196. if self.app.is_legacy is False:
  1197. event_pos = event.pos
  1198. right_button = 2
  1199. event_is_dragging = self.app.event_is_dragging
  1200. else:
  1201. event_pos = (event.xdata, event.ydata)
  1202. right_button = 3
  1203. event_is_dragging = self.app.ui.popMenu.mouse_is_panning
  1204. try:
  1205. x = float(event_pos[0])
  1206. y = float(event_pos[1])
  1207. except TypeError:
  1208. return
  1209. event_pos = (x, y)
  1210. curr_pos = self.app.plotcanvas.translate_coords(event_pos)
  1211. # do paint single only for left mouse clicks
  1212. if event.button == 1:
  1213. clicked_poly = self.find_polygon(point=(curr_pos[0], curr_pos[1]), geoset=self.paint_obj.solid_geometry)
  1214. if clicked_poly:
  1215. if clicked_poly not in self.poly_dict.values():
  1216. shape_id = self.app.tool_shapes.add(tolerance=self.paint_obj.drawing_tolerance,
  1217. layer=0,
  1218. shape=clicked_poly,
  1219. color=self.app.defaults['global_sel_draw_color'] + 'AF',
  1220. face_color=self.app.defaults['global_sel_draw_color'] + 'AF',
  1221. visible=True)
  1222. self.poly_dict[shape_id] = clicked_poly
  1223. self.app.inform.emit(
  1224. '%s: %d. %s' % (_("Added polygon"),
  1225. int(len(self.poly_dict)),
  1226. _("Click to add next polygon or right click to start painting."))
  1227. )
  1228. else:
  1229. try:
  1230. for k, v in list(self.poly_dict.items()):
  1231. if v == clicked_poly:
  1232. self.app.tool_shapes.remove(k)
  1233. self.poly_dict.pop(k)
  1234. break
  1235. except TypeError:
  1236. return
  1237. self.app.inform.emit(
  1238. '%s. %s' % (_("Removed polygon"),
  1239. _("Click to add/remove next polygon or right click to start painting."))
  1240. )
  1241. self.app.tool_shapes.redraw()
  1242. else:
  1243. self.app.inform.emit(_("No polygon detected under click position."))
  1244. elif event.button == right_button and event_is_dragging is False:
  1245. # restore the Grid snapping if it was active before
  1246. if self.grid_status_memory is True:
  1247. self.app.ui.grid_snap_btn.trigger()
  1248. if self.app.is_legacy is False:
  1249. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_single_poly_mouse_release)
  1250. else:
  1251. self.app.plotcanvas.graph_event_disconnect(self.mr)
  1252. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press',
  1253. self.app.on_mouse_click_over_plot)
  1254. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  1255. self.app.on_mouse_click_release_over_plot)
  1256. self.app.tool_shapes.clear(update=True)
  1257. if self.poly_dict:
  1258. poly_list = deepcopy(list(self.poly_dict.values()))
  1259. self.paint_poly(self.paint_obj,
  1260. inside_pt=(curr_pos[0], curr_pos[1]),
  1261. poly_list=poly_list,
  1262. tooldia=self.tooldia_list,
  1263. overlap=self.overlap,
  1264. connect=self.connect,
  1265. contour=self.contour)
  1266. self.poly_dict.clear()
  1267. else:
  1268. self.app.inform.emit('[ERROR_NOTCL] %s' % _("List of single polygons is empty. Aborting."))
  1269. # To be called after clicking on the plot.
  1270. def on_mouse_release(self, event):
  1271. if self.app.is_legacy is False:
  1272. event_pos = event.pos
  1273. event_is_dragging = event.is_dragging
  1274. right_button = 2
  1275. else:
  1276. event_pos = (event.xdata, event.ydata)
  1277. event_is_dragging = self.app.plotcanvas.is_dragging
  1278. right_button = 3
  1279. try:
  1280. x = float(event_pos[0])
  1281. y = float(event_pos[1])
  1282. except TypeError:
  1283. return
  1284. event_pos = (x, y)
  1285. # do paint single only for left mouse clicks
  1286. if event.button == 1:
  1287. if not self.first_click:
  1288. self.first_click = True
  1289. self.app.inform.emit('[WARNING_NOTCL] %s' %
  1290. _("Click the end point of the paint area."))
  1291. self.cursor_pos = self.app.plotcanvas.translate_coords(event_pos)
  1292. if self.app.grid_status():
  1293. self.cursor_pos = self.app.geo_editor.snap(self.cursor_pos[0], self.cursor_pos[1])
  1294. else:
  1295. self.app.inform.emit(_("Zone added. Click to start adding next zone or right click to finish."))
  1296. self.app.delete_selection_shape()
  1297. curr_pos = self.app.plotcanvas.translate_coords(event_pos)
  1298. if self.app.grid_status():
  1299. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  1300. x0, y0 = self.cursor_pos[0], self.cursor_pos[1]
  1301. x1, y1 = curr_pos[0], curr_pos[1]
  1302. pt1 = (x0, y0)
  1303. pt2 = (x1, y0)
  1304. pt3 = (x1, y1)
  1305. pt4 = (x0, y1)
  1306. new_rectangle = Polygon([pt1, pt2, pt3, pt4])
  1307. self.sel_rect.append(new_rectangle)
  1308. # add a temporary shape on canvas
  1309. self.draw_tool_selection_shape(old_coords=(x0, y0), coords=(x1, y1))
  1310. self.first_click = False
  1311. return
  1312. elif event.button == right_button and self.mouse_is_dragging is False:
  1313. self.first_click = False
  1314. self.delete_tool_selection_shape()
  1315. if self.app.is_legacy is False:
  1316. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_release)
  1317. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move)
  1318. else:
  1319. self.app.plotcanvas.graph_event_disconnect(self.mr)
  1320. self.app.plotcanvas.graph_event_disconnect(self.mm)
  1321. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press',
  1322. self.app.on_mouse_click_over_plot)
  1323. self.app.mm = self.app.plotcanvas.graph_event_connect('mouse_move',
  1324. self.app.on_mouse_move_over_plot)
  1325. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  1326. self.app.on_mouse_click_release_over_plot)
  1327. if len(self.sel_rect) == 0:
  1328. return
  1329. self.sel_rect = cascaded_union(self.sel_rect)
  1330. self.paint_poly_area(obj=self.paint_obj,
  1331. tooldia=self.tooldia_list,
  1332. sel_obj=self.sel_rect,
  1333. outname=self.o_name,
  1334. overlap=self.overlap,
  1335. connect=self.connect,
  1336. contour=self.contour)
  1337. # called on mouse move
  1338. def on_mouse_move(self, event):
  1339. if self.app.is_legacy is False:
  1340. event_pos = event.pos
  1341. event_is_dragging = event.is_dragging
  1342. right_button = 2
  1343. else:
  1344. event_pos = (event.xdata, event.ydata)
  1345. event_is_dragging = self.app.plotcanvas.is_dragging
  1346. right_button = 3
  1347. try:
  1348. x = float(event_pos[0])
  1349. y = float(event_pos[1])
  1350. except TypeError:
  1351. return
  1352. curr_pos = self.app.plotcanvas.translate_coords((x, y))
  1353. # detect mouse dragging motion
  1354. if event_is_dragging == 1:
  1355. self.mouse_is_dragging = True
  1356. else:
  1357. self.mouse_is_dragging = False
  1358. # update the cursor position
  1359. if self.app.grid_status():
  1360. # Update cursor
  1361. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  1362. self.app.app_cursor.set_data(np.asarray([(curr_pos[0], curr_pos[1])]),
  1363. symbol='++', edge_color=self.app.cursor_color_3D,
  1364. edge_width=self.app.defaults["global_cursor_width"],
  1365. size=self.app.defaults["global_cursor_size"])
  1366. # update the positions on status bar
  1367. self.app.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  1368. "<b>Y</b>: %.4f" % (curr_pos[0], curr_pos[1]))
  1369. if self.cursor_pos is None:
  1370. self.cursor_pos = (0, 0)
  1371. dx = curr_pos[0] - float(self.cursor_pos[0])
  1372. dy = curr_pos[1] - float(self.cursor_pos[1])
  1373. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  1374. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  1375. # draw the utility geometry
  1376. if self.first_click:
  1377. self.app.delete_selection_shape()
  1378. self.app.draw_moving_selection_shape(old_coords=(self.cursor_pos[0], self.cursor_pos[1]),
  1379. coords=(curr_pos[0], curr_pos[1]))
  1380. def paint_poly(self, obj, inside_pt=None, poly_list=None, tooldia=None, overlap=None, order=None,
  1381. margin=None, method=None, outname=None, connect=None, contour=None, tools_storage=None,
  1382. plot=True, run_threaded=True):
  1383. """
  1384. Paints a polygon selected by clicking on its interior or by having a point coordinates given
  1385. Note:
  1386. * The margin is taken directly from the form.
  1387. :param run_threaded:
  1388. :param plot:
  1389. :param poly_list:
  1390. :param obj: painted object
  1391. :param inside_pt: [x, y]
  1392. :param tooldia: Diameter of the painting tool
  1393. :param overlap: Overlap of the tool between passes.
  1394. :param order: if the tools are ordered and how
  1395. :param margin: a border around painting area
  1396. :param outname: Name of the resulting Geometry Object.
  1397. :param connect: Connect lines to avoid tool lifts.
  1398. :param contour: Paint around the edges.
  1399. :param method: choice out of _("Seed"), 'normal', 'lines'
  1400. :param tools_storage: whether to use the current tools_storage self.paints_tools or a different one.
  1401. Usage of the different one is related to when this function is called from a TcL command.
  1402. :return: None
  1403. """
  1404. if isinstance(obj, FlatCAMGerber):
  1405. if self.app.defaults["gerber_buffering"] == 'no':
  1406. self.app.inform.emit('%s %s %s' %
  1407. (_("Paint Tool."), _("Normal painting polygon task started."),
  1408. _("Buffering geometry...")))
  1409. else:
  1410. self.app.inform.emit('%s %s' % (_("Paint Tool."), _("Normal painting polygon task started.")))
  1411. else:
  1412. self.app.inform.emit('%s %s' % (_("Paint Tool."), _("Normal painting polygon task started.")))
  1413. if isinstance(obj, FlatCAMGerber):
  1414. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1415. if isinstance(obj.solid_geometry, list):
  1416. obj.solid_geometry = MultiPolygon(obj.solid_geometry).buffer(0)
  1417. else:
  1418. obj.solid_geometry = obj.solid_geometry.buffer(0)
  1419. polygon_list = None
  1420. if inside_pt and poly_list is None:
  1421. polygon_list = [self.find_polygon(point=inside_pt, geoset=obj.solid_geometry)]
  1422. elif (inside_pt is None and poly_list) or (inside_pt and poly_list):
  1423. polygon_list = poly_list
  1424. # No polygon?
  1425. if polygon_list is None:
  1426. self.app.log.warning('No polygon found.')
  1427. self.app.inform.emit('[WARNING] %s' % _('No polygon found.'))
  1428. return
  1429. paint_method = method if method is not None else self.paintmethod_combo.get_value()
  1430. paint_margin = float(self.paintmargin_entry.get_value()) if margin is None else margin
  1431. # determine if to use the progressive plotting
  1432. prog_plot = True if self.app.defaults["tools_paint_plotting"] == 'progressive' else False
  1433. name = outname if outname is not None else self.obj_name + "_paint"
  1434. over = overlap if overlap is not None else float(self.app.defaults["tools_paintoverlap"]) / 100.0
  1435. conn = connect if connect is not None else self.app.defaults["tools_pathconnect"]
  1436. cont = contour if contour is not None else self.app.defaults["tools_paintcontour"]
  1437. order = order if order is not None else self.order_radio.get_value()
  1438. tools_storage = self.paint_tools if tools_storage is None else tools_storage
  1439. sorted_tools = []
  1440. if tooldia is not None:
  1441. try:
  1442. sorted_tools = [float(eval(dia)) for dia in tooldia.split(",") if dia != '']
  1443. except AttributeError:
  1444. if not isinstance(tooldia, list):
  1445. sorted_tools = [float(tooldia)]
  1446. else:
  1447. sorted_tools = tooldia
  1448. else:
  1449. for row in range(self.tools_table.rowCount()):
  1450. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  1451. # sort the tools if we have an order selected in the UI
  1452. if order == 'fwd':
  1453. sorted_tools.sort(reverse=False)
  1454. elif order == 'rev':
  1455. sorted_tools.sort(reverse=True)
  1456. proc = self.app.proc_container.new(_("Painting polygon..."))
  1457. # Initializes the new geometry object
  1458. def gen_paintarea(geo_obj, app_obj):
  1459. geo_obj.solid_geometry = []
  1460. def paint_p(polyg, tooldiameter):
  1461. cpoly = None
  1462. try:
  1463. if paint_method == _("Standard"):
  1464. # Type(cp) == FlatCAMRTreeStorage | None
  1465. cpoly = self.clear_polygon(polyg,
  1466. tooldia=tooldiameter,
  1467. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1468. overlap=over,
  1469. contour=cont,
  1470. connect=conn,
  1471. prog_plot=prog_plot)
  1472. elif paint_method == _("Seed"):
  1473. # Type(cp) == FlatCAMRTreeStorage | None
  1474. cpoly = self.clear_polygon2(polyg,
  1475. tooldia=tooldiameter,
  1476. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1477. overlap=over,
  1478. contour=cont,
  1479. connect=conn,
  1480. prog_plot=prog_plot)
  1481. elif paint_method == _("Lines"):
  1482. # Type(cp) == FlatCAMRTreeStorage | None
  1483. cpoly = self.clear_polygon3(polyg,
  1484. tooldia=tooldiameter,
  1485. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1486. overlap=over,
  1487. contour=cont,
  1488. connect=conn,
  1489. prog_plot=prog_plot)
  1490. elif paint_method == _("Laser_lines"):
  1491. # line = None
  1492. # aperture_size = None
  1493. # the key is the aperture type and the val is a list of geo elements
  1494. flash_el_dict = {}
  1495. # the key is the aperture size, the val is a list of geo elements
  1496. traces_el_dict = {}
  1497. # find the flashes and the lines that are in the selected polygon and store them separately
  1498. for apid, apval in obj.apertures.items():
  1499. for geo_el in apval['geometry']:
  1500. if apval["size"] == 0.0:
  1501. if apval["size"] in traces_el_dict:
  1502. traces_el_dict[apval["size"]].append(geo_el)
  1503. else:
  1504. traces_el_dict[apval["size"]] = [geo_el]
  1505. if 'follow' in geo_el and geo_el['follow'].within(polyg):
  1506. if isinstance(geo_el['follow'], Point):
  1507. if apval["type"] == 'C':
  1508. if 'C' in flash_el_dict:
  1509. flash_el_dict['C'].append(geo_el)
  1510. else:
  1511. flash_el_dict['C'] = [geo_el]
  1512. elif apval["type"] == 'O':
  1513. if 'O' in flash_el_dict:
  1514. flash_el_dict['O'].append(geo_el)
  1515. else:
  1516. flash_el_dict['O'] = [geo_el]
  1517. elif apval["type"] == 'R':
  1518. if 'R' in flash_el_dict:
  1519. flash_el_dict['R'].append(geo_el)
  1520. else:
  1521. flash_el_dict['R'] = [geo_el]
  1522. else:
  1523. aperture_size = apval['size']
  1524. if aperture_size in traces_el_dict:
  1525. traces_el_dict[aperture_size].append(geo_el)
  1526. else:
  1527. traces_el_dict[aperture_size] = [geo_el]
  1528. cpoly = FlatCAMRTreeStorage()
  1529. pads_lines_list = []
  1530. # process the flashes found in the selected polygon with the 'lines' method for rectangular
  1531. # flashes and with _("Seed") for oblong and circular flashes
  1532. # and pads (flahes) need the contour therefore I override the GUI settings with always True
  1533. for ap_type in flash_el_dict:
  1534. for elem in flash_el_dict[ap_type]:
  1535. if 'solid' in elem:
  1536. if ap_type == 'C':
  1537. f_o = self.clear_polygon2(elem['solid'],
  1538. tooldia=tooldiameter,
  1539. steps_per_circle=self.app.defaults[
  1540. "geometry_circle_steps"],
  1541. overlap=over,
  1542. contour=True,
  1543. connect=conn,
  1544. prog_plot=prog_plot)
  1545. pads_lines_list += [p for p in f_o.get_objects() if p]
  1546. elif ap_type == 'O':
  1547. f_o = self.clear_polygon2(elem['solid'],
  1548. tooldia=tooldiameter,
  1549. steps_per_circle=self.app.defaults[
  1550. "geometry_circle_steps"],
  1551. overlap=over,
  1552. contour=True,
  1553. connect=conn,
  1554. prog_plot=prog_plot)
  1555. pads_lines_list += [p for p in f_o.get_objects() if p]
  1556. elif ap_type == 'R':
  1557. f_o = self.clear_polygon3(elem['solid'],
  1558. tooldia=tooldiameter,
  1559. steps_per_circle=self.app.defaults[
  1560. "geometry_circle_steps"],
  1561. overlap=over,
  1562. contour=True,
  1563. connect=conn,
  1564. prog_plot=prog_plot)
  1565. pads_lines_list += [p for p in f_o.get_objects() if p]
  1566. # add the lines from pads to the storage
  1567. try:
  1568. for lin in pads_lines_list:
  1569. if lin:
  1570. cpoly.insert(lin)
  1571. except TypeError:
  1572. cpoly.insert(pads_lines_list)
  1573. copper_lines_list = []
  1574. # process the traces found in the selected polygon using the 'laser_lines' method,
  1575. # method which will follow the 'follow' line therefore use the longer path possible for the
  1576. # laser, therefore the acceleration will play a smaller factor
  1577. for aperture_size in traces_el_dict:
  1578. for elem in traces_el_dict[aperture_size]:
  1579. line = elem['follow']
  1580. if line:
  1581. t_o = self.fill_with_lines(line, aperture_size,
  1582. tooldia=tooldiameter,
  1583. steps_per_circle=self.app.defaults[
  1584. "geometry_circle_steps"],
  1585. overlap=over,
  1586. contour=cont,
  1587. connect=conn,
  1588. prog_plot=prog_plot)
  1589. copper_lines_list += [p for p in t_o.get_objects() if p]
  1590. # add the lines from copper features to storage but first try to make as few lines as possible
  1591. # by trying to fuse them
  1592. lines_union = linemerge(unary_union(copper_lines_list))
  1593. try:
  1594. for lin in lines_union:
  1595. if lin:
  1596. cpoly.insert(lin)
  1597. except TypeError:
  1598. cpoly.insert(lines_union)
  1599. # # determine the Gerber follow line
  1600. # for apid, apval in obj.apertures.items():
  1601. # for geo_el in apval['geometry']:
  1602. # if 'solid' in geo_el:
  1603. # if Point(inside_pt).within(geo_el['solid']):
  1604. # if not isinstance(geo_el['follow'], Point):
  1605. # line = geo_el['follow']
  1606. #
  1607. # if apval['type'] == 'C':
  1608. # aperture_size = apval['size']
  1609. # else:
  1610. # if apval['width'] > apval['height']:
  1611. # aperture_size = apval['height']
  1612. # else:
  1613. # aperture_size = apval['width']
  1614. #
  1615. # if line:
  1616. # cpoly = self.fill_with_lines(line, aperture_size,
  1617. # tooldia=tooldiameter,
  1618. # steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1619. # overlap=over,
  1620. # contour=cont,
  1621. # connect=conn,
  1622. # prog_plot=prog_plot)
  1623. elif paint_method == _("Combo"):
  1624. self.app.inform.emit(_("Painting polygon with method: lines."))
  1625. cpoly = self.clear_polygon3(polyg,
  1626. tooldia=tooldiameter,
  1627. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1628. overlap=over,
  1629. contour=cont,
  1630. connect=conn,
  1631. prog_plot=prog_plot)
  1632. if cpoly and cpoly.objects:
  1633. pass
  1634. else:
  1635. self.app.inform.emit(_("Failed. Painting polygon with method: seed."))
  1636. cpoly = self.clear_polygon2(polyg,
  1637. tooldia=tooldiameter,
  1638. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1639. overlap=over,
  1640. contour=cont,
  1641. connect=conn,
  1642. prog_plot=prog_plot)
  1643. if cpoly and cpoly.objects:
  1644. pass
  1645. else:
  1646. self.app.inform.emit(_("Failed. Painting polygon with method: standard."))
  1647. cpoly = self.clear_polygon(polyg,
  1648. tooldia=tooldiameter,
  1649. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1650. overlap=over,
  1651. contour=cont,
  1652. connect=conn,
  1653. prog_plot=prog_plot)
  1654. except FlatCAMApp.GracefulException:
  1655. return "fail"
  1656. except Exception as ee:
  1657. log.debug("ToolPaint.paint_poly().gen_paintarea().paint_p() --> %s" % str(ee))
  1658. if cpoly and cpoly.objects:
  1659. geo_obj.solid_geometry += list(cpoly.get_objects())
  1660. return cpoly
  1661. else:
  1662. app_obj.inform.emit('[ERROR_NOTCL] %s' % _('Geometry could not be painted completely'))
  1663. return None
  1664. current_uid = int(1)
  1665. tool_dia = None
  1666. for tool_dia in sorted_tools:
  1667. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  1668. for k, v in tools_storage.items():
  1669. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals, tool_dia)):
  1670. current_uid = int(k)
  1671. break
  1672. try:
  1673. poly_buf = [pol.buffer(-paint_margin) for pol in polygon_list]
  1674. cp = []
  1675. try:
  1676. for pp in poly_buf:
  1677. cp.append(paint_p(pp, tooldiameter=tool_dia))
  1678. except TypeError:
  1679. cp = paint_p(poly_buf, tooldiameter=tool_dia)
  1680. total_geometry = []
  1681. if cp:
  1682. try:
  1683. for x in cp:
  1684. total_geometry += list(x.get_objects())
  1685. except TypeError:
  1686. total_geometry = list(cp.get_objects())
  1687. except FlatCAMApp.GracefulException:
  1688. return "fail"
  1689. except Exception as e:
  1690. log.debug("Could not Paint the polygons. %s" % str(e))
  1691. app_obj.inform.emit('[ERROR] %s\n%s' %
  1692. (_("Could not do Paint. Try a different combination of parameters. "
  1693. "Or a different strategy of paint"),
  1694. str(e)
  1695. )
  1696. )
  1697. return "fail"
  1698. # add the solid_geometry to the current too in self.paint_tools (tools_storage)
  1699. # dictionary and then reset the temporary list that stored that solid_geometry
  1700. tools_storage[current_uid]['solid_geometry'] = deepcopy(total_geometry)
  1701. tools_storage[current_uid]['data']['name'] = name
  1702. # clean the progressive plotted shapes if it was used
  1703. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1704. self.temp_shapes.clear(update=True)
  1705. # delete tools with empty geometry
  1706. # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  1707. for uid in list(tools_storage.keys()):
  1708. # if the solid_geometry (type=list) is empty
  1709. if not tools_storage[uid]['solid_geometry']:
  1710. tools_storage.pop(uid, None)
  1711. geo_obj.options["cnctooldia"] = str(tool_dia)
  1712. # this will turn on the FlatCAMCNCJob plot for multiple tools
  1713. geo_obj.multigeo = True
  1714. geo_obj.multitool = True
  1715. geo_obj.tools.clear()
  1716. geo_obj.tools = dict(tools_storage)
  1717. geo_obj.solid_geometry = cascaded_union(tools_storage[current_uid]['solid_geometry'])
  1718. try:
  1719. if isinstance(geo_obj.solid_geometry, list):
  1720. a, b, c, d = MultiPolygon(geo_obj.solid_geometry).bounds
  1721. else:
  1722. a, b, c, d = geo_obj.solid_geometry.bounds
  1723. geo_obj.options['xmin'] = a
  1724. geo_obj.options['ymin'] = b
  1725. geo_obj.options['xmax'] = c
  1726. geo_obj.options['ymax'] = d
  1727. except Exception as e:
  1728. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  1729. return
  1730. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1731. has_solid_geo = 0
  1732. for tooluid in geo_obj.tools:
  1733. if geo_obj.tools[tooluid]['solid_geometry']:
  1734. has_solid_geo += 1
  1735. if has_solid_geo == 0:
  1736. self.app.inform.emit('[ERROR] %s' %
  1737. _("There is no Painting Geometry in the file.\n"
  1738. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1739. "Change the painting parameters and try again."))
  1740. return
  1741. total_geometry[:] = []
  1742. self.app.inform.emit('[success] %s' % _("Paint Single Done."))
  1743. # Experimental...
  1744. # print("Indexing...", end=' ')
  1745. # geo_obj.make_index()
  1746. # if errors == 0:
  1747. # print("[success] Paint single polygon Done")
  1748. # self.app.inform.emit("[success] Paint single polygon Done")
  1749. # else:
  1750. # print("[WARNING] Paint single polygon done with errors")
  1751. # self.app.inform.emit("[WARNING] Paint single polygon done with errors. "
  1752. # "%d area(s) could not be painted.\n"
  1753. # "Use different paint parameters or edit the paint geometry and correct"
  1754. # "the issue."
  1755. # % errors)
  1756. def job_thread(app_obj):
  1757. try:
  1758. app_obj.new_object("geometry", name, gen_paintarea, plot=plot)
  1759. except FlatCAMApp.GracefulException:
  1760. proc.done()
  1761. return
  1762. except Exception as e:
  1763. proc.done()
  1764. self.app.inform.emit('[ERROR_NOTCL] %s --> %s' %
  1765. ('PaintTool.paint_poly()',
  1766. str(e)))
  1767. return
  1768. proc.done()
  1769. # focus on Selected Tab
  1770. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1771. self.app.inform.emit(_("Polygon Paint started ..."))
  1772. # Promise object with the new name
  1773. self.app.collection.promise(name)
  1774. if run_threaded:
  1775. # Background
  1776. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1777. else:
  1778. job_thread(app_obj=self.app)
  1779. def paint_poly_all(self, obj, tooldia=None, overlap=None, order=None, margin=None, method=None, outname=None,
  1780. connect=None, contour=None, tools_storage=None, plot=True, run_threaded=True):
  1781. """
  1782. Paints all polygons in this object.
  1783. :param run_threaded:
  1784. :param plot:
  1785. :param obj: painted object
  1786. :param tooldia: a tuple or single element made out of diameters of the tools to be used
  1787. :param overlap: value by which the paths will overlap
  1788. :param order: if the tools are ordered and how
  1789. :param margin: a border around painting area
  1790. :param outname: name of the resulting object
  1791. :param connect: Connect lines to avoid tool lifts.
  1792. :param contour: Paint around the edges.
  1793. :param method: choice out of _("Seed"), 'normal', 'lines'
  1794. :param tools_storage: whether to use the current tools_storage self.paints_tools or a different one.
  1795. Usage of the different one is related to when this function is called from a TcL command.
  1796. :return:
  1797. """
  1798. paint_method = method if method is not None else self.paintmethod_combo.get_value()
  1799. if margin is not None:
  1800. paint_margin = margin
  1801. else:
  1802. paint_margin = float(self.paintmargin_entry.get_value())
  1803. # determine if to use the progressive plotting
  1804. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1805. prog_plot = True
  1806. else:
  1807. prog_plot = False
  1808. proc = self.app.proc_container.new(_("Painting polygons..."))
  1809. name = outname if outname is not None else self.obj_name + "_paint"
  1810. over = overlap if overlap is not None else float(self.app.defaults["tools_paintoverlap"]) / 100.0
  1811. conn = connect if connect is not None else self.app.defaults["tools_pathconnect"]
  1812. cont = contour if contour is not None else self.app.defaults["tools_paintcontour"]
  1813. order = order if order is not None else self.order_radio.get_value()
  1814. sorted_tools = []
  1815. if tooldia is not None:
  1816. try:
  1817. sorted_tools = [float(eval(dia)) for dia in tooldia.split(",") if dia != '']
  1818. except AttributeError:
  1819. if not isinstance(tooldia, list):
  1820. sorted_tools = [float(tooldia)]
  1821. else:
  1822. sorted_tools = tooldia
  1823. else:
  1824. for row in range(self.tools_table.rowCount()):
  1825. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  1826. if tools_storage is not None:
  1827. tools_storage = tools_storage
  1828. else:
  1829. tools_storage = self.paint_tools
  1830. # This is a recursive generator of individual Polygons.
  1831. # Note: Double check correct implementation. Might exit
  1832. # early if it finds something that is not a Polygon?
  1833. # def recurse(geo):
  1834. # try:
  1835. # for subg in geo:
  1836. # for subsubg in recurse(subg):
  1837. # yield subsubg
  1838. # except TypeError:
  1839. # if isinstance(geo, Polygon):
  1840. # yield geo
  1841. #
  1842. # raise StopIteration
  1843. def recurse(geometry, reset=True):
  1844. """
  1845. Creates a list of non-iterable linear geometry objects.
  1846. Results are placed in self.flat_geometry
  1847. :param geometry: Shapely type or list or list of list of such.
  1848. :param reset: Clears the contents of self.flat_geometry.
  1849. """
  1850. if self.app.abort_flag:
  1851. # graceful abort requested by the user
  1852. raise FlatCAMApp.GracefulException
  1853. if geometry is None:
  1854. return
  1855. if reset:
  1856. self.flat_geometry = []
  1857. # ## If iterable, expand recursively.
  1858. try:
  1859. for geo in geometry:
  1860. if geo is not None:
  1861. recurse(geometry=geo, reset=False)
  1862. # ## Not iterable, do the actual indexing and add.
  1863. except TypeError:
  1864. if isinstance(geometry, LinearRing):
  1865. g = Polygon(geometry)
  1866. self.flat_geometry.append(g)
  1867. else:
  1868. self.flat_geometry.append(geometry)
  1869. return self.flat_geometry
  1870. # Initializes the new geometry object
  1871. def gen_paintarea(geo_obj, app_obj):
  1872. # assert isinstance(geo_obj, FlatCAMGeometry), \
  1873. # "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1874. log.debug("Paint Tool. Normal painting all task started.")
  1875. if isinstance(obj, FlatCAMGerber):
  1876. if app_obj.defaults["gerber_buffering"] == 'no':
  1877. app_obj.inform.emit('%s %s' %
  1878. (_("Paint Tool. Normal painting all task started."),
  1879. _("Buffering geometry...")))
  1880. else:
  1881. app_obj.inform.emit(_("Paint Tool. Normal painting all task started."))
  1882. else:
  1883. app_obj.inform.emit(_("Paint Tool. Normal painting all task started."))
  1884. tool_dia = None
  1885. if order == 'fwd':
  1886. sorted_tools.sort(reverse=False)
  1887. elif order == 'rev':
  1888. sorted_tools.sort(reverse=True)
  1889. else:
  1890. pass
  1891. if isinstance(obj, FlatCAMGerber):
  1892. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1893. if isinstance(obj.solid_geometry, list):
  1894. obj.solid_geometry = MultiPolygon(obj.solid_geometry).buffer(0)
  1895. else:
  1896. obj.solid_geometry = obj.solid_geometry.buffer(0)
  1897. try:
  1898. a, b, c, d = obj.bounds()
  1899. geo_obj.options['xmin'] = a
  1900. geo_obj.options['ymin'] = b
  1901. geo_obj.options['xmax'] = c
  1902. geo_obj.options['ymax'] = d
  1903. except Exception as e:
  1904. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  1905. return
  1906. total_geometry = []
  1907. current_uid = int(1)
  1908. geo_obj.solid_geometry = []
  1909. for tool_dia in sorted_tools:
  1910. log.debug("Starting geometry processing for tool: %s" % str(tool_dia))
  1911. app_obj.inform.emit(
  1912. '[success] %s %s%s %s' % (_('Painting with tool diameter = '),
  1913. str(tool_dia),
  1914. self.units.lower(),
  1915. _('started'))
  1916. )
  1917. app_obj.proc_container.update_view_text(' %d%%' % 0)
  1918. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  1919. for k, v in tools_storage.items():
  1920. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals, tool_dia)):
  1921. current_uid = int(k)
  1922. break
  1923. painted_area = recurse(obj.solid_geometry)
  1924. # variables to display the percentage of work done
  1925. geo_len = len(painted_area)
  1926. old_disp_number = 0
  1927. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  1928. pol_nr = 0
  1929. for geo in painted_area:
  1930. # provide the app with a way to process the GUI events when in a blocking loop
  1931. QtWidgets.QApplication.processEvents()
  1932. if self.app.abort_flag:
  1933. # graceful abort requested by the user
  1934. raise FlatCAMApp.GracefulException
  1935. # try to clean the Polygon but it may result into a MultiPolygon
  1936. geo = geo.buffer(0)
  1937. poly_buf = geo.buffer(-paint_margin)
  1938. if geo is not None and geo.is_valid:
  1939. poly_processed = []
  1940. try:
  1941. for pol in poly_buf:
  1942. if pol is not None and isinstance(pol, Polygon):
  1943. cp = None
  1944. if paint_method == _("Standard"):
  1945. cp = self.clear_polygon(pol,
  1946. tooldia=tool_dia,
  1947. steps_per_circle=self.app.defaults[
  1948. "geometry_circle_steps"],
  1949. overlap=over,
  1950. contour=cont,
  1951. connect=conn,
  1952. prog_plot=prog_plot)
  1953. elif paint_method == _("Seed"):
  1954. cp = self.clear_polygon2(pol,
  1955. tooldia=tool_dia,
  1956. steps_per_circle=self.app.defaults[
  1957. "geometry_circle_steps"],
  1958. overlap=over,
  1959. contour=cont,
  1960. connect=conn,
  1961. prog_plot=prog_plot)
  1962. elif paint_method == _("Lines"):
  1963. cp = self.clear_polygon3(pol,
  1964. tooldia=tool_dia,
  1965. steps_per_circle=self.app.defaults[
  1966. "geometry_circle_steps"],
  1967. overlap=over,
  1968. contour=cont,
  1969. connect=conn,
  1970. prog_plot=prog_plot)
  1971. elif paint_method == _("Laser_lines"):
  1972. # line = None
  1973. # aperture_size = None
  1974. # the key is the aperture type and the val is a list of geo elements
  1975. flash_el_dict = {}
  1976. # the key is the aperture size, the val is a list of geo elements
  1977. traces_el_dict = {}
  1978. # find the flashes and the lines that are in the selected polygon and store
  1979. # them separately
  1980. for apid, apval in obj.apertures.items():
  1981. for geo_el in apval['geometry']:
  1982. if apval["size"] == 0.0:
  1983. if apval["size"] in traces_el_dict:
  1984. traces_el_dict[apval["size"]].append(geo_el)
  1985. else:
  1986. traces_el_dict[apval["size"]] = [geo_el]
  1987. if 'follow' in geo_el and geo_el['follow'].within(pol):
  1988. if isinstance(geo_el['follow'], Point):
  1989. if apval["type"] == 'C':
  1990. if 'C' in flash_el_dict:
  1991. flash_el_dict['C'].append(geo_el)
  1992. else:
  1993. flash_el_dict['C'] = [geo_el]
  1994. elif apval["type"] == 'O':
  1995. if 'O' in flash_el_dict:
  1996. flash_el_dict['O'].append(geo_el)
  1997. else:
  1998. flash_el_dict['O'] = [geo_el]
  1999. elif apval["type"] == 'R':
  2000. if 'R' in flash_el_dict:
  2001. flash_el_dict['R'].append(geo_el)
  2002. else:
  2003. flash_el_dict['R'] = [geo_el]
  2004. else:
  2005. aperture_size = apval['size']
  2006. if aperture_size in traces_el_dict:
  2007. traces_el_dict[aperture_size].append(geo_el)
  2008. else:
  2009. traces_el_dict[aperture_size] = [geo_el]
  2010. cp = FlatCAMRTreeStorage()
  2011. pads_lines_list = []
  2012. # process the flashes found in the selected polygon with the 'lines' method
  2013. # for rectangular flashes and with _("Seed") for oblong and circular flashes
  2014. # and pads (flahes) need the contour therefore I override the GUI settings
  2015. # with always True
  2016. for ap_type in flash_el_dict:
  2017. for elem in flash_el_dict[ap_type]:
  2018. if 'solid' in elem:
  2019. if ap_type == 'C':
  2020. f_o = self.clear_polygon2(elem['solid'],
  2021. tooldia=tool_dia,
  2022. steps_per_circle=self.app.defaults[
  2023. "geometry_circle_steps"],
  2024. overlap=over,
  2025. contour=True,
  2026. connect=conn,
  2027. prog_plot=prog_plot)
  2028. pads_lines_list += [p for p in f_o.get_objects() if p]
  2029. elif ap_type == 'O':
  2030. f_o = self.clear_polygon2(elem['solid'],
  2031. tooldia=tool_dia,
  2032. steps_per_circle=self.app.defaults[
  2033. "geometry_circle_steps"],
  2034. overlap=over,
  2035. contour=True,
  2036. connect=conn,
  2037. prog_plot=prog_plot)
  2038. pads_lines_list += [p for p in f_o.get_objects() if p]
  2039. elif ap_type == 'R':
  2040. f_o = self.clear_polygon3(elem['solid'],
  2041. tooldia=tool_dia,
  2042. steps_per_circle=self.app.defaults[
  2043. "geometry_circle_steps"],
  2044. overlap=over,
  2045. contour=True,
  2046. connect=conn,
  2047. prog_plot=prog_plot)
  2048. pads_lines_list += [p for p in f_o.get_objects() if p]
  2049. # add the lines from pads to the storage
  2050. try:
  2051. for lin in pads_lines_list:
  2052. if lin:
  2053. cp.insert(lin)
  2054. except TypeError:
  2055. cp.insert(pads_lines_list)
  2056. copper_lines_list = []
  2057. # process the traces found in the selected polygon using the 'laser_lines'
  2058. # method, method which will follow the 'follow' line therefore use the longer
  2059. # path possible for the laser, therefore the acceleration will play
  2060. # a smaller factor
  2061. for aperture_size in traces_el_dict:
  2062. for elem in traces_el_dict[aperture_size]:
  2063. line = elem['follow']
  2064. if line:
  2065. t_o = self.fill_with_lines(line, aperture_size,
  2066. tooldia=tool_dia,
  2067. steps_per_circle=self.app.defaults[
  2068. "geometry_circle_steps"],
  2069. overlap=over,
  2070. contour=cont,
  2071. connect=conn,
  2072. prog_plot=prog_plot)
  2073. copper_lines_list += [p for p in t_o.get_objects() if p]
  2074. # add the lines from copper features to storage but first try to make as few
  2075. # lines as possible
  2076. # by trying to fuse them
  2077. lines_union = linemerge(unary_union(copper_lines_list))
  2078. try:
  2079. for lin in lines_union:
  2080. if lin:
  2081. cp.insert(lin)
  2082. except TypeError:
  2083. cp.insert(lines_union)
  2084. elif paint_method == _("Combo"):
  2085. self.app.inform.emit(_("Painting polygons with method: lines."))
  2086. cp = self.clear_polygon3(pol,
  2087. tooldia=tool_dia,
  2088. steps_per_circle=self.app.defaults[
  2089. "geometry_circle_steps"],
  2090. overlap=over,
  2091. contour=cont,
  2092. connect=conn,
  2093. prog_plot=prog_plot)
  2094. if cp and cp.objects:
  2095. pass
  2096. else:
  2097. self.app.inform.emit(_("Failed. Painting polygons with method: seed."))
  2098. cp = self.clear_polygon2(pol,
  2099. tooldia=tool_dia,
  2100. steps_per_circle=self.app.defaults[
  2101. "geometry_circle_steps"],
  2102. overlap=over,
  2103. contour=cont,
  2104. connect=conn,
  2105. prog_plot=prog_plot)
  2106. if cp and cp.objects:
  2107. pass
  2108. else:
  2109. self.app.inform.emit(
  2110. _("Failed. Painting polygons with method: standard."))
  2111. cp = self.clear_polygon(pol,
  2112. tooldia=tool_dia,
  2113. steps_per_circle=self.app.defaults[
  2114. "geometry_circle_steps"],
  2115. overlap=over,
  2116. contour=cont,
  2117. connect=conn,
  2118. prog_plot=prog_plot)
  2119. if cp and cp.objects:
  2120. total_geometry += list(cp.get_objects())
  2121. poly_processed.append(True)
  2122. else:
  2123. poly_processed.append(False)
  2124. log.warning("Polygon in MultiPolygon can not be cleared.")
  2125. else:
  2126. log.warning("Geo in Iterable can not be cleared because it is not Polygon. "
  2127. "It is: %s" % str(type(pol)))
  2128. except TypeError:
  2129. if isinstance(poly_buf, Polygon):
  2130. cp = None
  2131. if paint_method == _("Standard"):
  2132. cp = self.clear_polygon(poly_buf,
  2133. tooldia=tool_dia,
  2134. steps_per_circle=self.app.defaults[
  2135. "geometry_circle_steps"],
  2136. overlap=over,
  2137. contour=cont,
  2138. connect=conn,
  2139. prog_plot=prog_plot)
  2140. elif paint_method == _("Seed"):
  2141. cp = self.clear_polygon2(poly_buf,
  2142. tooldia=tool_dia,
  2143. steps_per_circle=self.app.defaults[
  2144. "geometry_circle_steps"],
  2145. overlap=over,
  2146. contour=cont,
  2147. connect=conn,
  2148. prog_plot=prog_plot)
  2149. elif paint_method == _("Lines"):
  2150. cp = self.clear_polygon3(poly_buf,
  2151. tooldia=tool_dia,
  2152. steps_per_circle=self.app.defaults[
  2153. "geometry_circle_steps"],
  2154. overlap=over,
  2155. contour=cont,
  2156. connect=conn,
  2157. prog_plot=prog_plot)
  2158. elif paint_method == _("Laser_lines"):
  2159. # line = None
  2160. # aperture_size = None
  2161. # the key is the aperture type and the val is a list of geo elements
  2162. flash_el_dict = {}
  2163. # the key is the aperture size, the val is a list of geo elements
  2164. traces_el_dict = {}
  2165. # find the flashes and the lines that are in the selected polygon and store
  2166. # them separately
  2167. for apid, apval in obj.apertures.items():
  2168. for geo_el in apval['geometry']:
  2169. if apval["size"] == 0.0:
  2170. if apval["size"] in traces_el_dict:
  2171. traces_el_dict[apval["size"]].append(geo_el)
  2172. else:
  2173. traces_el_dict[apval["size"]] = [geo_el]
  2174. if 'follow' in geo_el and geo_el['follow'].within(poly_buf):
  2175. if isinstance(geo_el['follow'], Point):
  2176. if apval["type"] == 'C':
  2177. if 'C' in flash_el_dict:
  2178. flash_el_dict['C'].append(geo_el)
  2179. else:
  2180. flash_el_dict['C'] = [geo_el]
  2181. elif apval["type"] == 'O':
  2182. if 'O' in flash_el_dict:
  2183. flash_el_dict['O'].append(geo_el)
  2184. else:
  2185. flash_el_dict['O'] = [geo_el]
  2186. elif apval["type"] == 'R':
  2187. if 'R' in flash_el_dict:
  2188. flash_el_dict['R'].append(geo_el)
  2189. else:
  2190. flash_el_dict['R'] = [geo_el]
  2191. else:
  2192. aperture_size = apval['size']
  2193. if aperture_size in traces_el_dict:
  2194. traces_el_dict[aperture_size].append(geo_el)
  2195. else:
  2196. traces_el_dict[aperture_size] = [geo_el]
  2197. cp = FlatCAMRTreeStorage()
  2198. pads_lines_list = []
  2199. # process the flashes found in the selected polygon with the 'lines' method
  2200. # for rectangular flashes and with _("Seed") for oblong and circular flashes
  2201. # and pads (flahes) need the contour therefore I override the GUI settings
  2202. # with always True
  2203. for ap_type in flash_el_dict:
  2204. for elem in flash_el_dict[ap_type]:
  2205. if 'solid' in elem:
  2206. if ap_type == 'C':
  2207. f_o = self.clear_polygon2(elem['solid'],
  2208. tooldia=tool_dia,
  2209. steps_per_circle=self.app.defaults[
  2210. "geometry_circle_steps"],
  2211. overlap=over,
  2212. contour=True,
  2213. connect=conn,
  2214. prog_plot=prog_plot)
  2215. pads_lines_list += [p for p in f_o.get_objects() if p]
  2216. elif ap_type == 'O':
  2217. f_o = self.clear_polygon2(elem['solid'],
  2218. tooldia=tool_dia,
  2219. steps_per_circle=self.app.defaults[
  2220. "geometry_circle_steps"],
  2221. overlap=over,
  2222. contour=True,
  2223. connect=conn,
  2224. prog_plot=prog_plot)
  2225. pads_lines_list += [p for p in f_o.get_objects() if p]
  2226. elif ap_type == 'R':
  2227. f_o = self.clear_polygon3(elem['solid'],
  2228. tooldia=tool_dia,
  2229. steps_per_circle=self.app.defaults[
  2230. "geometry_circle_steps"],
  2231. overlap=over,
  2232. contour=True,
  2233. connect=conn,
  2234. prog_plot=prog_plot)
  2235. pads_lines_list += [p for p in f_o.get_objects() if p]
  2236. # add the lines from pads to the storage
  2237. try:
  2238. for lin in pads_lines_list:
  2239. if lin:
  2240. cp.insert(lin)
  2241. except TypeError:
  2242. cp.insert(pads_lines_list)
  2243. copper_lines_list = []
  2244. # process the traces found in the selected polygon using the 'laser_lines'
  2245. # method, method which will follow the 'follow' line therefore use the longer
  2246. # path possible for the laser, therefore the acceleration will play
  2247. # a smaller factor
  2248. for aperture_size in traces_el_dict:
  2249. for elem in traces_el_dict[aperture_size]:
  2250. line = elem['follow']
  2251. if line:
  2252. t_o = self.fill_with_lines(line, aperture_size,
  2253. tooldia=tool_dia,
  2254. steps_per_circle=self.app.defaults[
  2255. "geometry_circle_steps"],
  2256. overlap=over,
  2257. contour=cont,
  2258. connect=conn,
  2259. prog_plot=prog_plot)
  2260. copper_lines_list += [p for p in t_o.get_objects() if p]
  2261. # add the lines from copper features to storage but first try to make as few
  2262. # lines as possible
  2263. # by trying to fuse them
  2264. lines_union = linemerge(unary_union(copper_lines_list))
  2265. try:
  2266. for lin in lines_union:
  2267. if lin:
  2268. cp.insert(lin)
  2269. except TypeError:
  2270. cp.insert(lines_union)
  2271. elif paint_method == _("Combo"):
  2272. self.app.inform.emit(_("Painting polygons with method: lines."))
  2273. cp = self.clear_polygon3(poly_buf,
  2274. tooldia=tool_dia,
  2275. steps_per_circle=self.app.defaults[
  2276. "geometry_circle_steps"],
  2277. overlap=over,
  2278. contour=cont,
  2279. connect=conn,
  2280. prog_plot=prog_plot)
  2281. if cp and cp.objects:
  2282. pass
  2283. else:
  2284. self.app.inform.emit(_("Failed. Painting polygons with method: seed."))
  2285. cp = self.clear_polygon2(poly_buf,
  2286. tooldia=tool_dia,
  2287. steps_per_circle=self.app.defaults[
  2288. "geometry_circle_steps"],
  2289. overlap=over,
  2290. contour=cont,
  2291. connect=conn,
  2292. prog_plot=prog_plot)
  2293. if cp and cp.objects:
  2294. pass
  2295. else:
  2296. self.app.inform.emit(_("Failed. Painting polygons with method: standard."))
  2297. cp = self.clear_polygon(poly_buf,
  2298. tooldia=tool_dia,
  2299. steps_per_circle=self.app.defaults[
  2300. "geometry_circle_steps"],
  2301. overlap=over,
  2302. contour=cont,
  2303. connect=conn,
  2304. prog_plot=prog_plot)
  2305. if cp:
  2306. total_geometry += list(cp.get_objects())
  2307. poly_processed.append(True)
  2308. else:
  2309. poly_processed.append(False)
  2310. log.warning("Polygon can not be cleared.")
  2311. else:
  2312. log.warning("Geo can not be cleared because it is: %s" % str(type(poly_buf)))
  2313. p_cleared = poly_processed.count(True)
  2314. p_not_cleared = poly_processed.count(False)
  2315. if p_not_cleared:
  2316. app_obj.poly_not_cleared = True
  2317. if p_cleared == 0:
  2318. continue
  2319. # try:
  2320. # # Polygons are the only really paintable geometries,
  2321. # # lines in theory have no area to be painted
  2322. # if not isinstance(geo, Polygon):
  2323. # continue
  2324. # poly_buf = geo.buffer(-paint_margin)
  2325. #
  2326. # if paint_method == _("Seed"):
  2327. # # Type(cp) == FlatCAMRTreeStorage | None
  2328. # cp = self.clear_polygon2(poly_buf,
  2329. # tooldia=tool_dia,
  2330. # steps_per_circle=self.app.defaults["geometry_circle_steps"],
  2331. # overlap=over,
  2332. # contour=cont,
  2333. # connect=conn,
  2334. # prog_plot=prog_plot)
  2335. #
  2336. # elif paint_method == _("Lines"):
  2337. # # Type(cp) == FlatCAMRTreeStorage | None
  2338. # cp = self.clear_polygon3(poly_buf,
  2339. # tooldia=tool_dia,
  2340. # steps_per_circle=self.app.defaults["geometry_circle_steps"],
  2341. # overlap=over,
  2342. # contour=cont,
  2343. # connect=conn,
  2344. # prog_plot=prog_plot)
  2345. #
  2346. # else:
  2347. # # Type(cp) == FlatCAMRTreeStorage | None
  2348. # cp = self.clear_polygon(poly_buf,
  2349. # tooldia=tool_dia,
  2350. # steps_per_circle=self.app.defaults["geometry_circle_steps"],
  2351. # overlap=over,
  2352. # contour=cont,
  2353. # connect=conn,
  2354. # prog_plot=prog_plot)
  2355. #
  2356. # if cp is not None:
  2357. # total_geometry += list(cp.get_objects())
  2358. # except FlatCAMApp.GracefulException:
  2359. # return "fail"
  2360. # except Exception as e:
  2361. # log.debug("Could not Paint the polygons. %s" % str(e))
  2362. # self.app.inform.emit('[ERROR] %s\n%s' %
  2363. # (_("Could not do Paint All. Try a different combination of parameters. "
  2364. # "Or a different Method of paint"),
  2365. # str(e)))
  2366. # return "fail"
  2367. pol_nr += 1
  2368. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  2369. # log.debug("Polygons cleared: %d" % pol_nr)
  2370. if old_disp_number < disp_number <= 100:
  2371. app_obj.proc_container.update_view_text(' %d%%' % disp_number)
  2372. old_disp_number = disp_number
  2373. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  2374. # add the solid_geometry to the current too in self.paint_tools (tools_storage)
  2375. # dictionary and then reset the temporary list that stored that solid_geometry
  2376. tools_storage[current_uid]['solid_geometry'] = deepcopy(total_geometry)
  2377. tools_storage[current_uid]['data']['name'] = name
  2378. total_geometry[:] = []
  2379. # clean the progressive plotted shapes if it was used
  2380. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  2381. self.temp_shapes.clear(update=True)
  2382. # # delete tools with empty geometry
  2383. # keys_to_delete = []
  2384. # # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  2385. # for uid in tools_storage:
  2386. # # if the solid_geometry (type=list) is empty
  2387. # if not tools_storage[uid]['solid_geometry']:
  2388. # keys_to_delete.append(uid)
  2389. #
  2390. # # actual delete of keys from the tools_storage dict
  2391. # for k in keys_to_delete:
  2392. # tools_storage.pop(k, None)
  2393. # delete tools with empty geometry
  2394. # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  2395. for uid in list(tools_storage.keys()):
  2396. # if the solid_geometry (type=list) is empty
  2397. if not tools_storage[uid]['solid_geometry']:
  2398. tools_storage.pop(uid, None)
  2399. geo_obj.options["cnctooldia"] = str(tool_dia)
  2400. # this turn on the FlatCAMCNCJob plot for multiple tools
  2401. geo_obj.multigeo = True
  2402. geo_obj.multitool = True
  2403. geo_obj.tools.clear()
  2404. geo_obj.tools = dict(tools_storage)
  2405. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  2406. has_solid_geo = 0
  2407. for tooluid in geo_obj.tools:
  2408. if geo_obj.tools[tooluid]['solid_geometry']:
  2409. has_solid_geo += 1
  2410. if has_solid_geo == 0:
  2411. self.app.inform.emit('[ERROR] %s' %
  2412. _("There is no Painting Geometry in the file.\n"
  2413. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  2414. "Change the painting parameters and try again."))
  2415. return
  2416. # Experimental...
  2417. # print("Indexing...", end=' ')
  2418. # geo_obj.make_index()
  2419. self.app.inform.emit('[success] %s' % _("Paint All Done."))
  2420. # Initializes the new geometry object
  2421. def gen_paintarea_rest_machining(geo_obj, app_obj):
  2422. assert isinstance(geo_obj, FlatCAMGeometry), \
  2423. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  2424. log.debug("Paint Tool. Rest machining painting all task started.")
  2425. if isinstance(obj, FlatCAMGerber):
  2426. if app_obj.defaults["gerber_buffering"] == 'no':
  2427. app_obj.inform.emit('%s %s %s' %
  2428. (_("Paint Tool."), _("Rest machining painting all task started."),
  2429. _("Buffering geometry...")))
  2430. else:
  2431. app_obj.inform.emit('%s %s' %
  2432. (_("Paint Tool."), _("Rest machining painting all task started.")))
  2433. else:
  2434. app_obj.inform.emit('%s %s' %
  2435. (_("Paint Tool."), _("Rest machining painting all task started.")))
  2436. tool_dia = None
  2437. sorted_tools.sort(reverse=True)
  2438. cleared_geo = []
  2439. current_uid = int(1)
  2440. geo_obj.solid_geometry = []
  2441. if isinstance(obj, FlatCAMGerber):
  2442. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  2443. if isinstance(obj.solid_geometry, list):
  2444. obj.solid_geometry = MultiPolygon(obj.solid_geometry).buffer(0)
  2445. else:
  2446. obj.solid_geometry = obj.solid_geometry.buffer(0)
  2447. try:
  2448. a, b, c, d = obj.bounds()
  2449. geo_obj.options['xmin'] = a
  2450. geo_obj.options['ymin'] = b
  2451. geo_obj.options['xmax'] = c
  2452. geo_obj.options['ymax'] = d
  2453. except Exception as e:
  2454. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  2455. return
  2456. for tool_dia in sorted_tools:
  2457. log.debug("Starting geometry processing for tool: %s" % str(tool_dia))
  2458. app_obj.inform.emit(
  2459. '[success] %s %s%s %s' % (_('Painting with tool diameter = '),
  2460. str(tool_dia),
  2461. self.units.lower(),
  2462. _('started'))
  2463. )
  2464. app_obj.proc_container.update_view_text(' %d%%' % 0)
  2465. painted_area = recurse(obj.solid_geometry)
  2466. # variables to display the percentage of work done
  2467. geo_len = int(len(painted_area) / 100)
  2468. old_disp_number = 0
  2469. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  2470. pol_nr = 0
  2471. for geo in painted_area:
  2472. try:
  2473. geo = Polygon(geo) if not isinstance(geo, Polygon) else geo
  2474. poly_buf = geo.buffer(-paint_margin)
  2475. cp = None
  2476. if paint_method == _("Standard"):
  2477. # Type(cp) == FlatCAMRTreeStorage | None
  2478. cp = self.clear_polygon(poly_buf, tooldia=tool_dia,
  2479. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  2480. overlap=over, contour=cont, connect=conn,
  2481. prog_plot=prog_plot)
  2482. elif paint_method == _("Seed"):
  2483. # Type(cp) == FlatCAMRTreeStorage | None
  2484. cp = self.clear_polygon2(poly_buf, tooldia=tool_dia,
  2485. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  2486. overlap=over, contour=cont, connect=conn,
  2487. prog_plot=prog_plot)
  2488. elif paint_method == _("Lines"):
  2489. # Type(cp) == FlatCAMRTreeStorage | None
  2490. cp = self.clear_polygon3(poly_buf, tooldia=tool_dia,
  2491. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  2492. overlap=over, contour=cont, connect=conn,
  2493. prog_plot=prog_plot)
  2494. elif paint_method == _("Laser_lines"):
  2495. # line = None
  2496. # aperture_size = None
  2497. # the key is the aperture type and the val is a list of geo elements
  2498. flash_el_dict = {}
  2499. # the key is the aperture size, the val is a list of geo elements
  2500. traces_el_dict = {}
  2501. # find the flashes and the lines that are in the selected polygon and store
  2502. # them separately
  2503. for apid, apval in obj.apertures.items():
  2504. for geo_el in apval['geometry']:
  2505. if apval["size"] == 0.0:
  2506. if apval["size"] in traces_el_dict:
  2507. traces_el_dict[apval["size"]].append(geo_el)
  2508. else:
  2509. traces_el_dict[apval["size"]] = [geo_el]
  2510. if 'follow' in geo_el and geo_el['follow'].within(poly_buf):
  2511. if isinstance(geo_el['follow'], Point):
  2512. if apval["type"] == 'C':
  2513. if 'C' in flash_el_dict:
  2514. flash_el_dict['C'].append(geo_el)
  2515. else:
  2516. flash_el_dict['C'] = [geo_el]
  2517. elif apval["type"] == 'O':
  2518. if 'O' in flash_el_dict:
  2519. flash_el_dict['O'].append(geo_el)
  2520. else:
  2521. flash_el_dict['O'] = [geo_el]
  2522. elif apval["type"] == 'R':
  2523. if 'R' in flash_el_dict:
  2524. flash_el_dict['R'].append(geo_el)
  2525. else:
  2526. flash_el_dict['R'] = [geo_el]
  2527. else:
  2528. aperture_size = apval['size']
  2529. if aperture_size in traces_el_dict:
  2530. traces_el_dict[aperture_size].append(geo_el)
  2531. else:
  2532. traces_el_dict[aperture_size] = [geo_el]
  2533. cp = FlatCAMRTreeStorage()
  2534. pads_lines_list = []
  2535. # process the flashes found in the selected polygon with the 'lines' method
  2536. # for rectangular flashes and with _("Seed") for oblong and circular flashes
  2537. # and pads (flahes) need the contour therefore I override the GUI settings
  2538. # with always True
  2539. for ap_type in flash_el_dict:
  2540. for elem in flash_el_dict[ap_type]:
  2541. if 'solid' in elem:
  2542. if ap_type == 'C':
  2543. f_o = self.clear_polygon2(elem['solid'],
  2544. tooldia=tool_dia,
  2545. steps_per_circle=self.app.defaults[
  2546. "geometry_circle_steps"],
  2547. overlap=over,
  2548. contour=True,
  2549. connect=conn,
  2550. prog_plot=prog_plot)
  2551. pads_lines_list += [p for p in f_o.get_objects() if p]
  2552. elif ap_type == 'O':
  2553. f_o = self.clear_polygon2(elem['solid'],
  2554. tooldia=tool_dia,
  2555. steps_per_circle=self.app.defaults[
  2556. "geometry_circle_steps"],
  2557. overlap=over,
  2558. contour=True,
  2559. connect=conn,
  2560. prog_plot=prog_plot)
  2561. pads_lines_list += [p for p in f_o.get_objects() if p]
  2562. elif ap_type == 'R':
  2563. f_o = self.clear_polygon3(elem['solid'],
  2564. tooldia=tool_dia,
  2565. steps_per_circle=self.app.defaults[
  2566. "geometry_circle_steps"],
  2567. overlap=over,
  2568. contour=True,
  2569. connect=conn,
  2570. prog_plot=prog_plot)
  2571. pads_lines_list += [p for p in f_o.get_objects() if p]
  2572. # add the lines from pads to the storage
  2573. try:
  2574. for lin in pads_lines_list:
  2575. if lin:
  2576. cp.insert(lin)
  2577. except TypeError:
  2578. cp.insert(pads_lines_list)
  2579. copper_lines_list = []
  2580. # process the traces found in the selected polygon using the 'laser_lines'
  2581. # method, method which will follow the 'follow' line therefore use the longer
  2582. # path possible for the laser, therefore the acceleration will play
  2583. # a smaller factor
  2584. for aperture_size in traces_el_dict:
  2585. for elem in traces_el_dict[aperture_size]:
  2586. line = elem['follow']
  2587. if line:
  2588. t_o = self.fill_with_lines(line, aperture_size,
  2589. tooldia=tool_dia,
  2590. steps_per_circle=self.app.defaults[
  2591. "geometry_circle_steps"],
  2592. overlap=over,
  2593. contour=cont,
  2594. connect=conn,
  2595. prog_plot=prog_plot)
  2596. copper_lines_list += [p for p in t_o.get_objects() if p]
  2597. # add the lines from copper features to storage but first try to make as few
  2598. # lines as possible
  2599. # by trying to fuse them
  2600. lines_union = linemerge(unary_union(copper_lines_list))
  2601. try:
  2602. for lin in lines_union:
  2603. if lin:
  2604. cp.insert(lin)
  2605. except TypeError:
  2606. cp.insert(lines_union)
  2607. elif paint_method == _("Combo"):
  2608. self.app.inform.emit(_("Painting polygons with method: lines."))
  2609. cp = self.clear_polygon3(poly_buf,
  2610. tooldia=tool_dia,
  2611. steps_per_circle=self.app.defaults[
  2612. "geometry_circle_steps"],
  2613. overlap=over,
  2614. contour=cont,
  2615. connect=conn,
  2616. prog_plot=prog_plot)
  2617. if cp and cp.objects:
  2618. pass
  2619. else:
  2620. self.app.inform.emit(_("Failed. Painting polygons with method: seed."))
  2621. cp = self.clear_polygon2(poly_buf,
  2622. tooldia=tool_dia,
  2623. steps_per_circle=self.app.defaults[
  2624. "geometry_circle_steps"],
  2625. overlap=over,
  2626. contour=cont,
  2627. connect=conn,
  2628. prog_plot=prog_plot)
  2629. if cp and cp.objects:
  2630. pass
  2631. else:
  2632. self.app.inform.emit(_("Failed. Painting polygons with method: standard."))
  2633. cp = self.clear_polygon(poly_buf,
  2634. tooldia=tool_dia,
  2635. steps_per_circle=self.app.defaults[
  2636. "geometry_circle_steps"],
  2637. overlap=over,
  2638. contour=cont,
  2639. connect=conn,
  2640. prog_plot=prog_plot)
  2641. if cp is not None:
  2642. cleared_geo += list(cp.get_objects())
  2643. except FlatCAMApp.GracefulException:
  2644. return "fail"
  2645. except Exception as e:
  2646. log.debug("Could not Paint the polygons. %s" % str(e))
  2647. self.app.inform.emit('[ERROR] %s\n%s' %
  2648. (_("Could not do Paint All. Try a different combination of parameters. "
  2649. "Or a different Method of paint"),
  2650. str(e)))
  2651. return "fail"
  2652. pol_nr += 1
  2653. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  2654. # log.debug("Polygons cleared: %d" % pol_nr)
  2655. if old_disp_number < disp_number <= 100:
  2656. app_obj.proc_container.update_view_text(' %d%%' % disp_number)
  2657. old_disp_number = disp_number
  2658. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  2659. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  2660. for k, v in tools_storage.items():
  2661. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals, tool_dia)):
  2662. current_uid = int(k)
  2663. break
  2664. # add the solid_geometry to the current too in self.paint_tools (or tools_storage) dictionary and
  2665. # then reset the temporary list that stored that solid_geometry
  2666. tools_storage[current_uid]['solid_geometry'] = deepcopy(cleared_geo)
  2667. tools_storage[current_uid]['data']['name'] = name
  2668. cleared_geo[:] = []
  2669. geo_obj.options["cnctooldia"] = str(tool_dia)
  2670. # this turn on the FlatCAMCNCJob plot for multiple tools
  2671. geo_obj.multigeo = True
  2672. geo_obj.multitool = True
  2673. geo_obj.tools.clear()
  2674. geo_obj.tools = dict(tools_storage)
  2675. # clean the progressive plotted shapes if it was used
  2676. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  2677. self.temp_shapes.clear(update=True)
  2678. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  2679. has_solid_geo = 0
  2680. for tooluid in geo_obj.tools:
  2681. if geo_obj.tools[tooluid]['solid_geometry']:
  2682. has_solid_geo += 1
  2683. if has_solid_geo == 0:
  2684. self.app.inform.emit('[ERROR_NOTCL] %s' %
  2685. _("There is no Painting Geometry in the file.\n"
  2686. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  2687. "Change the painting parameters and try again."))
  2688. return
  2689. # Experimental...
  2690. # print("Indexing...", end=' ')
  2691. # geo_obj.make_index()
  2692. self.app.inform.emit('[success] %s' % _("Paint All with Rest-Machining done."))
  2693. def job_thread(app_obj):
  2694. try:
  2695. if self.rest_cb.isChecked():
  2696. app_obj.new_object("geometry", name, gen_paintarea_rest_machining, plot=plot)
  2697. else:
  2698. app_obj.new_object("geometry", name, gen_paintarea, plot=plot)
  2699. except FlatCAMApp.GracefulException:
  2700. proc.done()
  2701. return
  2702. except Exception:
  2703. proc.done()
  2704. traceback.print_stack()
  2705. return
  2706. proc.done()
  2707. # focus on Selected Tab
  2708. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  2709. self.app.inform.emit(_("Polygon Paint started ..."))
  2710. # Promise object with the new name
  2711. self.app.collection.promise(name)
  2712. if run_threaded:
  2713. # Background
  2714. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  2715. else:
  2716. job_thread(app_obj=self.app)
  2717. def paint_poly_area(self, obj, sel_obj,
  2718. tooldia=None,
  2719. overlap=None,
  2720. order=None,
  2721. margin=None,
  2722. method=None,
  2723. outname=None,
  2724. connect=None,
  2725. contour=None,
  2726. tools_storage=None,
  2727. plot=True,
  2728. run_threaded=True):
  2729. """
  2730. Paints all polygons in this object that are within the sel_obj object
  2731. :param run_threaded:
  2732. :param plot:
  2733. :param obj: painted object
  2734. :param sel_obj: paint only what is inside this object bounds
  2735. :param tooldia: a tuple or single element made out of diameters of the tools to be used
  2736. :param overlap: value by which the paths will overlap
  2737. :param order: if the tools are ordered and how
  2738. :param margin: a border around painting area
  2739. :param outname: name of the resulting object
  2740. :param connect: Connect lines to avoid tool lifts.
  2741. :param contour: Paint around the edges.
  2742. :param method: choice out of _("Seed"), 'normal', 'lines'
  2743. :param tools_storage: whether to use the current tools_storage self.paints_tools or a different one.
  2744. Usage of the different one is related to when this function is called from a TcL command.
  2745. :return:
  2746. """
  2747. paint_method = method if method is not None else self.paintmethod_combo.get_value()
  2748. if margin is not None:
  2749. paint_margin = margin
  2750. else:
  2751. try:
  2752. paint_margin = float(self.paintmargin_entry.get_value())
  2753. except ValueError:
  2754. # try to convert comma to decimal point. if it's still not working error message and return
  2755. try:
  2756. paint_margin = float(self.paintmargin_entry.get_value().replace(',', '.'))
  2757. except ValueError:
  2758. self.app.inform.emit('[ERROR_NOTCL] %s' %
  2759. _("Wrong value format entered, use a number."))
  2760. return
  2761. # determine if to use the progressive plotting
  2762. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  2763. prog_plot = True
  2764. else:
  2765. prog_plot = False
  2766. proc = self.app.proc_container.new(_("Painting polygons..."))
  2767. name = outname if outname is not None else self.obj_name + "_paint"
  2768. over = overlap if overlap is not None else float(self.app.defaults["tools_paintoverlap"]) / 100.0
  2769. conn = connect if connect is not None else self.app.defaults["tools_pathconnect"]
  2770. cont = contour if contour is not None else self.app.defaults["tools_paintcontour"]
  2771. order = order if order is not None else self.order_radio.get_value()
  2772. sorted_tools = []
  2773. if tooldia is not None:
  2774. try:
  2775. sorted_tools = [float(eval(dia)) for dia in tooldia.split(",") if dia != '']
  2776. except AttributeError:
  2777. if not isinstance(tooldia, list):
  2778. sorted_tools = [float(tooldia)]
  2779. else:
  2780. sorted_tools = tooldia
  2781. else:
  2782. for row in range(self.tools_table.rowCount()):
  2783. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  2784. if tools_storage is not None:
  2785. tools_storage = tools_storage
  2786. else:
  2787. tools_storage = self.paint_tools
  2788. def recurse(geometry, reset=True):
  2789. """
  2790. Creates a list of non-iterable linear geometry objects.
  2791. Results are placed in self.flat_geometry
  2792. :param geometry: Shapely type or list or list of list of such.
  2793. :param reset: Clears the contents of self.flat_geometry.
  2794. """
  2795. if self.app.abort_flag:
  2796. # graceful abort requested by the user
  2797. raise FlatCAMApp.GracefulException
  2798. if geometry is None:
  2799. return
  2800. if reset:
  2801. self.flat_geometry = []
  2802. # ## If iterable, expand recursively.
  2803. try:
  2804. for geo in geometry:
  2805. if geo is not None:
  2806. recurse(geometry=geo, reset=False)
  2807. # ## Not iterable, do the actual indexing and add.
  2808. except TypeError:
  2809. if isinstance(geometry, LinearRing):
  2810. g = Polygon(geometry)
  2811. self.flat_geometry.append(g)
  2812. else:
  2813. self.flat_geometry.append(geometry)
  2814. return self.flat_geometry
  2815. # Initializes the new geometry object
  2816. def gen_paintarea(geo_obj, app_obj):
  2817. # assert isinstance(geo_obj, FlatCAMGeometry), \
  2818. # "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  2819. log.debug("Paint Tool. Normal painting area task started.")
  2820. if isinstance(obj, FlatCAMGerber):
  2821. if app_obj.defaults["gerber_buffering"] == 'no':
  2822. app_obj.inform.emit('%s %s %s' %
  2823. (_("Paint Tool."),
  2824. _("Normal painting area task started."),
  2825. _("Buffering geometry...")))
  2826. else:
  2827. app_obj.inform.emit('%s %s' %
  2828. (_("Paint Tool."), _("Normal painting area task started.")))
  2829. else:
  2830. app_obj.inform.emit('%s %s' %
  2831. (_("Paint Tool."), _("Normal painting area task started.")))
  2832. tool_dia = None
  2833. if order == 'fwd':
  2834. sorted_tools.sort(reverse=False)
  2835. elif order == 'rev':
  2836. sorted_tools.sort(reverse=True)
  2837. else:
  2838. pass
  2839. # this is were heavy lifting is done and creating the geometry to be painted
  2840. target_geo = MultiPolygon(obj.solid_geometry)
  2841. if isinstance(obj, FlatCAMGerber):
  2842. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  2843. if isinstance(target_geo, list):
  2844. target_geo = MultiPolygon(target_geo).buffer(0)
  2845. else:
  2846. target_geo = target_geo.buffer(0)
  2847. geo_to_paint = target_geo.intersection(sel_obj)
  2848. painted_area = recurse(geo_to_paint)
  2849. try:
  2850. a, b, c, d = self.paint_bounds(geo_to_paint)
  2851. geo_obj.options['xmin'] = a
  2852. geo_obj.options['ymin'] = b
  2853. geo_obj.options['xmax'] = c
  2854. geo_obj.options['ymax'] = d
  2855. except Exception as e:
  2856. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  2857. return
  2858. total_geometry = []
  2859. current_uid = int(1)
  2860. geo_obj.solid_geometry = []
  2861. for tool_dia in sorted_tools:
  2862. log.debug("Starting geometry processing for tool: %s" % str(tool_dia))
  2863. app_obj.inform.emit(
  2864. '[success] %s %s%s %s' % (_('Painting with tool diameter = '),
  2865. str(tool_dia),
  2866. self.units.lower(),
  2867. _('started'))
  2868. )
  2869. app_obj.proc_container.update_view_text(' %d%%' % 0)
  2870. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  2871. for k, v in tools_storage.items():
  2872. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals, tool_dia)):
  2873. current_uid = int(k)
  2874. break
  2875. # variables to display the percentage of work done
  2876. geo_len = len(painted_area)
  2877. old_disp_number = 0
  2878. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  2879. pol_nr = 0
  2880. for geo in painted_area:
  2881. try:
  2882. # Polygons are the only really paintable geometries, lines in theory have no area to be painted
  2883. if not isinstance(geo, Polygon):
  2884. continue
  2885. poly_buf = geo.buffer(-paint_margin)
  2886. cp = None
  2887. if paint_method == _("Seed"):
  2888. # Type(cp) == FlatCAMRTreeStorage | None
  2889. cp = self.clear_polygon2(poly_buf,
  2890. tooldia=tool_dia,
  2891. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  2892. overlap=over,
  2893. contour=cont,
  2894. connect=conn,
  2895. prog_plot=prog_plot)
  2896. elif paint_method == _("Lines"):
  2897. # Type(cp) == FlatCAMRTreeStorage | None
  2898. cp = self.clear_polygon3(poly_buf,
  2899. tooldia=tool_dia,
  2900. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  2901. overlap=over,
  2902. contour=cont,
  2903. connect=conn,
  2904. prog_plot=prog_plot)
  2905. elif paint_method == _("Standard"):
  2906. # Type(cp) == FlatCAMRTreeStorage | None
  2907. cp = self.clear_polygon(poly_buf,
  2908. tooldia=tool_dia,
  2909. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  2910. overlap=over,
  2911. contour=cont,
  2912. connect=conn,
  2913. prog_plot=prog_plot)
  2914. elif paint_method == _("Laser_lines"):
  2915. # line = None
  2916. # aperture_size = None
  2917. # the key is the aperture type and the val is a list of geo elements
  2918. flash_el_dict = {}
  2919. # the key is the aperture size, the val is a list of geo elements
  2920. traces_el_dict = {}
  2921. # find the flashes and the lines that are in the selected polygon and store
  2922. # them separately
  2923. for apid, apval in obj.apertures.items():
  2924. for geo_el in apval['geometry']:
  2925. if apval["size"] == 0.0:
  2926. if apval["size"] in traces_el_dict:
  2927. traces_el_dict[apval["size"]].append(geo_el)
  2928. else:
  2929. traces_el_dict[apval["size"]] = [geo_el]
  2930. if 'follow' in geo_el and geo_el['follow'].within(poly_buf):
  2931. if isinstance(geo_el['follow'], Point):
  2932. if apval["type"] == 'C':
  2933. if 'C' in flash_el_dict:
  2934. flash_el_dict['C'].append(geo_el)
  2935. else:
  2936. flash_el_dict['C'] = [geo_el]
  2937. elif apval["type"] == 'O':
  2938. if 'O' in flash_el_dict:
  2939. flash_el_dict['O'].append(geo_el)
  2940. else:
  2941. flash_el_dict['O'] = [geo_el]
  2942. elif apval["type"] == 'R':
  2943. if 'R' in flash_el_dict:
  2944. flash_el_dict['R'].append(geo_el)
  2945. else:
  2946. flash_el_dict['R'] = [geo_el]
  2947. else:
  2948. aperture_size = apval['size']
  2949. if aperture_size in traces_el_dict:
  2950. traces_el_dict[aperture_size].append(geo_el)
  2951. else:
  2952. traces_el_dict[aperture_size] = [geo_el]
  2953. cp = FlatCAMRTreeStorage()
  2954. pads_lines_list = []
  2955. # process the flashes found in the selected polygon with the 'lines' method
  2956. # for rectangular flashes and with _("Seed") for oblong and circular flashes
  2957. # and pads (flahes) need the contour therefore I override the GUI settings
  2958. # with always True
  2959. for ap_type in flash_el_dict:
  2960. for elem in flash_el_dict[ap_type]:
  2961. if 'solid' in elem:
  2962. if ap_type == 'C':
  2963. f_o = self.clear_polygon2(elem['solid'],
  2964. tooldia=tool_dia,
  2965. steps_per_circle=self.app.defaults[
  2966. "geometry_circle_steps"],
  2967. overlap=over,
  2968. contour=True,
  2969. connect=conn,
  2970. prog_plot=prog_plot)
  2971. pads_lines_list += [p for p in f_o.get_objects() if p]
  2972. elif ap_type == 'O':
  2973. f_o = self.clear_polygon2(elem['solid'],
  2974. tooldia=tool_dia,
  2975. steps_per_circle=self.app.defaults[
  2976. "geometry_circle_steps"],
  2977. overlap=over,
  2978. contour=True,
  2979. connect=conn,
  2980. prog_plot=prog_plot)
  2981. pads_lines_list += [p for p in f_o.get_objects() if p]
  2982. elif ap_type == 'R':
  2983. f_o = self.clear_polygon3(elem['solid'],
  2984. tooldia=tool_dia,
  2985. steps_per_circle=self.app.defaults[
  2986. "geometry_circle_steps"],
  2987. overlap=over,
  2988. contour=True,
  2989. connect=conn,
  2990. prog_plot=prog_plot)
  2991. pads_lines_list += [p for p in f_o.get_objects() if p]
  2992. # add the lines from pads to the storage
  2993. try:
  2994. for lin in pads_lines_list:
  2995. if lin:
  2996. cp.insert(lin)
  2997. except TypeError:
  2998. cp.insert(pads_lines_list)
  2999. copper_lines_list = []
  3000. # process the traces found in the selected polygon using the 'laser_lines'
  3001. # method, method which will follow the 'follow' line therefore use the longer
  3002. # path possible for the laser, therefore the acceleration will play
  3003. # a smaller factor
  3004. for aperture_size in traces_el_dict:
  3005. for elem in traces_el_dict[aperture_size]:
  3006. line = elem['follow']
  3007. if line:
  3008. t_o = self.fill_with_lines(line, aperture_size,
  3009. tooldia=tool_dia,
  3010. steps_per_circle=self.app.defaults[
  3011. "geometry_circle_steps"],
  3012. overlap=over,
  3013. contour=cont,
  3014. connect=conn,
  3015. prog_plot=prog_plot)
  3016. copper_lines_list += [p for p in t_o.get_objects() if p]
  3017. # add the lines from copper features to storage but first try to make as few
  3018. # lines as possible
  3019. # by trying to fuse them
  3020. lines_union = linemerge(unary_union(copper_lines_list))
  3021. try:
  3022. for lin in lines_union:
  3023. if lin:
  3024. cp.insert(lin)
  3025. except TypeError:
  3026. cp.insert(lines_union)
  3027. elif paint_method == _("Combo"):
  3028. self.app.inform.emit(_("Painting polygons with method: lines."))
  3029. cp = self.clear_polygon3(poly_buf,
  3030. tooldia=tool_dia,
  3031. steps_per_circle=self.app.defaults[
  3032. "geometry_circle_steps"],
  3033. overlap=over,
  3034. contour=cont,
  3035. connect=conn,
  3036. prog_plot=prog_plot)
  3037. if cp and cp.objects:
  3038. pass
  3039. else:
  3040. self.app.inform.emit(_("Failed. Painting polygons with method: seed."))
  3041. cp = self.clear_polygon2(poly_buf,
  3042. tooldia=tool_dia,
  3043. steps_per_circle=self.app.defaults[
  3044. "geometry_circle_steps"],
  3045. overlap=over,
  3046. contour=cont,
  3047. connect=conn,
  3048. prog_plot=prog_plot)
  3049. if cp and cp.objects:
  3050. pass
  3051. else:
  3052. self.app.inform.emit(_("Failed. Painting polygons with method: standard."))
  3053. cp = self.clear_polygon(poly_buf,
  3054. tooldia=tool_dia,
  3055. steps_per_circle=self.app.defaults[
  3056. "geometry_circle_steps"],
  3057. overlap=over,
  3058. contour=cont,
  3059. connect=conn,
  3060. prog_plot=prog_plot)
  3061. if cp and cp.objects:
  3062. total_geometry += list(cp.get_objects())
  3063. except FlatCAMApp.GracefulException:
  3064. return "fail"
  3065. except Exception as e:
  3066. log.debug("Could not Paint the polygons. %s" % str(e))
  3067. self.app.inform.emit('[ERROR] %s\n%s' %
  3068. (_("Could not do Paint All. Try a different combination of parameters. "
  3069. "Or a different Method of paint"), str(e)))
  3070. return
  3071. pol_nr += 1
  3072. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  3073. # log.debug("Polygons cleared: %d" % pol_nr)
  3074. if old_disp_number < disp_number <= 100:
  3075. app_obj.proc_container.update_view_text(' %d%%' % disp_number)
  3076. old_disp_number = disp_number
  3077. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  3078. # add the solid_geometry to the current too in self.paint_tools (tools_storage)
  3079. # dictionary and then reset the temporary list that stored that solid_geometry
  3080. tools_storage[current_uid]['solid_geometry'] = deepcopy(total_geometry)
  3081. tools_storage[current_uid]['data']['name'] = name
  3082. total_geometry[:] = []
  3083. # clean the progressive plotted shapes if it was used
  3084. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  3085. self.temp_shapes.clear(update=True)
  3086. # delete tools with empty geometry
  3087. keys_to_delete = []
  3088. # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  3089. for uid in tools_storage:
  3090. # if the solid_geometry (type=list) is empty
  3091. if not tools_storage[uid]['solid_geometry']:
  3092. keys_to_delete.append(uid)
  3093. # actual delete of keys from the tools_storage dict
  3094. for k in keys_to_delete:
  3095. tools_storage.pop(k, None)
  3096. geo_obj.options["cnctooldia"] = str(tool_dia)
  3097. # this turn on the FlatCAMCNCJob plot for multiple tools
  3098. geo_obj.multigeo = True
  3099. geo_obj.multitool = True
  3100. geo_obj.tools.clear()
  3101. geo_obj.tools = dict(tools_storage)
  3102. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  3103. has_solid_geo = 0
  3104. for tooluid in geo_obj.tools:
  3105. if geo_obj.tools[tooluid]['solid_geometry']:
  3106. has_solid_geo += 1
  3107. if has_solid_geo == 0:
  3108. self.app.inform.emit('[ERROR] %s' %
  3109. _("There is no Painting Geometry in the file.\n"
  3110. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  3111. "Change the painting parameters and try again."))
  3112. return
  3113. # Experimental...
  3114. # print("Indexing...", end=' ')
  3115. # geo_obj.make_index()
  3116. self.app.inform.emit('[success] %s' % _("Paint Area Done."))
  3117. # Initializes the new geometry object
  3118. def gen_paintarea_rest_machining(geo_obj, app_obj):
  3119. assert isinstance(geo_obj, FlatCAMGeometry), \
  3120. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  3121. log.debug("Paint Tool. Rest machining painting area task started.")
  3122. if isinstance(obj, FlatCAMGerber):
  3123. if app_obj.defaults["gerber_buffering"] == 'no':
  3124. app_obj.inform.emit('%s %s %s' %
  3125. (_("Paint Tool."),
  3126. _("Rest machining painting area task started."),
  3127. _("Buffering geometry...")))
  3128. else:
  3129. app_obj.inform.emit(_("Paint Tool. Rest machining painting area task started."))
  3130. else:
  3131. app_obj.inform.emit('%s %s' %
  3132. (_("Paint Tool."), _("Rest machining painting area task started.")))
  3133. tool_dia = None
  3134. sorted_tools.sort(reverse=True)
  3135. cleared_geo = []
  3136. current_uid = int(1)
  3137. geo_obj.solid_geometry = []
  3138. # this is were heavy lifting is done and creating the geometry to be painted
  3139. target_geo = obj.solid_geometry
  3140. if isinstance(obj, FlatCAMGerber):
  3141. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  3142. if isinstance(target_geo, list):
  3143. target_geo = MultiPolygon(target_geo).buffer(0)
  3144. else:
  3145. target_geo = target_geo.buffer(0)
  3146. geo_to_paint = target_geo.intersection(sel_obj)
  3147. painted_area = recurse(geo_to_paint)
  3148. try:
  3149. a, b, c, d = obj.bounds()
  3150. geo_obj.options['xmin'] = a
  3151. geo_obj.options['ymin'] = b
  3152. geo_obj.options['xmax'] = c
  3153. geo_obj.options['ymax'] = d
  3154. except Exception as e:
  3155. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  3156. return
  3157. for tool_dia in sorted_tools:
  3158. log.debug("Starting geometry processing for tool: %s" % str(tool_dia))
  3159. app_obj.inform.emit(
  3160. '[success] %s %s%s %s' % (_('Painting with tool diameter = '),
  3161. str(tool_dia),
  3162. self.units.lower(),
  3163. _('started'))
  3164. )
  3165. app_obj.proc_container.update_view_text(' %d%%' % 0)
  3166. # variables to display the percentage of work done
  3167. geo_len = len(painted_area)
  3168. old_disp_number = 0
  3169. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  3170. pol_nr = 0
  3171. for geo in painted_area:
  3172. try:
  3173. geo = Polygon(geo) if not isinstance(geo, Polygon) else geo
  3174. poly_buf = geo.buffer(-paint_margin)
  3175. cp = None
  3176. if paint_method == _("Standard"):
  3177. # Type(cp) == FlatCAMRTreeStorage | None
  3178. cp = self.clear_polygon(poly_buf, tooldia=tool_dia,
  3179. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  3180. overlap=over, contour=cont, connect=conn,
  3181. prog_plot=prog_plot)
  3182. elif paint_method == _("Seed"):
  3183. # Type(cp) == FlatCAMRTreeStorage | None
  3184. cp = self.clear_polygon2(poly_buf, tooldia=tool_dia,
  3185. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  3186. overlap=over, contour=cont, connect=conn,
  3187. prog_plot=prog_plot)
  3188. elif paint_method == _("Lines"):
  3189. # Type(cp) == FlatCAMRTreeStorage | None
  3190. cp = self.clear_polygon3(poly_buf, tooldia=tool_dia,
  3191. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  3192. overlap=over, contour=cont, connect=conn,
  3193. prog_plot=prog_plot)
  3194. elif paint_method == _("Laser_lines"):
  3195. # line = None
  3196. # aperture_size = None
  3197. # the key is the aperture type and the val is a list of geo elements
  3198. flash_el_dict = {}
  3199. # the key is the aperture size, the val is a list of geo elements
  3200. copper_el_dict = {}
  3201. # find the flashes and the lines that are in the selected polygon and store
  3202. # them separately
  3203. for apid, apval in obj.apertures.items():
  3204. for geo_el in apval['geometry']:
  3205. if apval["size"] == 0.0:
  3206. if apval["size"] in copper_el_dict:
  3207. copper_el_dict[apval["size"]].append(geo_el)
  3208. else:
  3209. copper_el_dict[apval["size"]] = [geo_el]
  3210. if 'follow' in geo_el and geo_el['follow'].within(poly_buf):
  3211. if isinstance(geo_el['follow'], Point):
  3212. if apval["type"] == 'C':
  3213. if 'C' in flash_el_dict:
  3214. flash_el_dict['C'].append(geo_el)
  3215. else:
  3216. flash_el_dict['C'] = [geo_el]
  3217. elif apval["type"] == 'O':
  3218. if 'O' in flash_el_dict:
  3219. flash_el_dict['O'].append(geo_el)
  3220. else:
  3221. flash_el_dict['O'] = [geo_el]
  3222. elif apval["type"] == 'R':
  3223. if 'R' in flash_el_dict:
  3224. flash_el_dict['R'].append(geo_el)
  3225. else:
  3226. flash_el_dict['R'] = [geo_el]
  3227. else:
  3228. aperture_size = apval['size']
  3229. if aperture_size in copper_el_dict:
  3230. copper_el_dict[aperture_size].append(geo_el)
  3231. else:
  3232. copper_el_dict[aperture_size] = [geo_el]
  3233. cp = FlatCAMRTreeStorage()
  3234. pads_lines_list = []
  3235. # process the flashes found in the selected polygon with the 'lines' method
  3236. # for rectangular flashes and with _("Seed") for oblong and circular flashes
  3237. # and pads (flahes) need the contour therefore I override the GUI settings
  3238. # with always True
  3239. for ap_type in flash_el_dict:
  3240. for elem in flash_el_dict[ap_type]:
  3241. if 'solid' in elem:
  3242. if ap_type == 'C':
  3243. f_o = self.clear_polygon2(elem['solid'],
  3244. tooldia=tool_dia,
  3245. steps_per_circle=self.app.defaults[
  3246. "geometry_circle_steps"],
  3247. overlap=over,
  3248. contour=True,
  3249. connect=conn,
  3250. prog_plot=prog_plot)
  3251. pads_lines_list += [p for p in f_o.get_objects() if p]
  3252. elif ap_type == 'O':
  3253. f_o = self.clear_polygon2(elem['solid'],
  3254. tooldia=tool_dia,
  3255. steps_per_circle=self.app.defaults[
  3256. "geometry_circle_steps"],
  3257. overlap=over,
  3258. contour=True,
  3259. connect=conn,
  3260. prog_plot=prog_plot)
  3261. pads_lines_list += [p for p in f_o.get_objects() if p]
  3262. elif ap_type == 'R':
  3263. f_o = self.clear_polygon3(elem['solid'],
  3264. tooldia=tool_dia,
  3265. steps_per_circle=self.app.defaults[
  3266. "geometry_circle_steps"],
  3267. overlap=over,
  3268. contour=True,
  3269. connect=conn,
  3270. prog_plot=prog_plot)
  3271. pads_lines_list += [p for p in f_o.get_objects() if p]
  3272. # add the lines from pads to the storage
  3273. try:
  3274. for lin in pads_lines_list:
  3275. if lin:
  3276. cp.insert(lin)
  3277. except TypeError:
  3278. cp.insert(pads_lines_list)
  3279. copper_lines_list = []
  3280. # process the traces found in the selected polygon using the 'laser_lines'
  3281. # method, method which will follow the 'follow' line therefore use the longer
  3282. # path possible for the laser, therefore the acceleration will play
  3283. # a smaller factor
  3284. for aperture_size in copper_el_dict:
  3285. for elem in copper_el_dict[aperture_size]:
  3286. line = elem['follow']
  3287. if line:
  3288. t_o = self.fill_with_lines(line, aperture_size,
  3289. tooldia=tool_dia,
  3290. steps_per_circle=self.app.defaults[
  3291. "geometry_circle_steps"],
  3292. overlap=over,
  3293. contour=cont,
  3294. connect=conn,
  3295. prog_plot=prog_plot)
  3296. copper_lines_list += [p for p in t_o.get_objects() if p]
  3297. # add the lines from copper features to storage but first try to make as few
  3298. # lines as possible
  3299. # by trying to fuse them
  3300. lines_union = linemerge(unary_union(copper_lines_list))
  3301. try:
  3302. for lin in lines_union:
  3303. if lin:
  3304. cp.insert(lin)
  3305. except TypeError:
  3306. cp.insert(lines_union)
  3307. elif paint_method == _("Combo"):
  3308. self.app.inform.emit(_("Painting polygons with method: lines."))
  3309. cp = self.clear_polygon3(poly_buf,
  3310. tooldia=tool_dia,
  3311. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  3312. overlap=over,
  3313. contour=cont,
  3314. connect=conn,
  3315. prog_plot=prog_plot)
  3316. if cp and cp.objects:
  3317. pass
  3318. else:
  3319. self.app.inform.emit(_("Failed. Painting polygons with method: seed."))
  3320. cp = self.clear_polygon2(poly_buf,
  3321. tooldia=tool_dia,
  3322. steps_per_circle=self.app.defaults[
  3323. "geometry_circle_steps"],
  3324. overlap=over,
  3325. contour=cont,
  3326. connect=conn,
  3327. prog_plot=prog_plot)
  3328. if cp and cp.objects:
  3329. pass
  3330. else:
  3331. self.app.inform.emit(_("Failed. Painting polygons with method: standard."))
  3332. cp = self.clear_polygon(poly_buf,
  3333. tooldia=tool_dia,
  3334. steps_per_circle=self.app.defaults[
  3335. "geometry_circle_steps"],
  3336. overlap=over,
  3337. contour=cont,
  3338. connect=conn,
  3339. prog_plot=prog_plot)
  3340. if cp and cp.objects:
  3341. cleared_geo += list(cp.get_objects())
  3342. except FlatCAMApp.GracefulException:
  3343. return "fail"
  3344. except Exception as e:
  3345. log.debug("Could not Paint the polygons. %s" % str(e))
  3346. self.app.inform.emit('[ERROR] %s\n%s' %
  3347. (_("Could not do Paint All. Try a different combination of parameters. "
  3348. "Or a different Method of paint"), str(e)))
  3349. return
  3350. pol_nr += 1
  3351. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  3352. # log.debug("Polygons cleared: %d" % pol_nr)
  3353. if old_disp_number < disp_number <= 100:
  3354. app_obj.proc_container.update_view_text(' %d%%' % disp_number)
  3355. old_disp_number = disp_number
  3356. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  3357. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  3358. for k, v in tools_storage.items():
  3359. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals, tool_dia)):
  3360. current_uid = int(k)
  3361. break
  3362. # add the solid_geometry to the current too in self.paint_tools (or tools_storage) dictionary and
  3363. # then reset the temporary list that stored that solid_geometry
  3364. tools_storage[current_uid]['solid_geometry'] = deepcopy(cleared_geo)
  3365. tools_storage[current_uid]['data']['name'] = name
  3366. cleared_geo[:] = []
  3367. geo_obj.options["cnctooldia"] = str(tool_dia)
  3368. # this turn on the FlatCAMCNCJob plot for multiple tools
  3369. geo_obj.multigeo = True
  3370. geo_obj.multitool = True
  3371. geo_obj.tools.clear()
  3372. geo_obj.tools = dict(self.paint_tools)
  3373. # clean the progressive plotted shapes if it was used
  3374. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  3375. self.temp_shapes.clear(update=True)
  3376. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  3377. has_solid_geo = 0
  3378. for tooluid in geo_obj.tools:
  3379. if geo_obj.tools[tooluid]['solid_geometry']:
  3380. has_solid_geo += 1
  3381. if has_solid_geo == 0:
  3382. self.app.inform.emit('[ERROR_NOTCL] %s' %
  3383. _("There is no Painting Geometry in the file.\n"
  3384. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  3385. "Change the painting parameters and try again."))
  3386. return
  3387. # Experimental...
  3388. # print("Indexing...", end=' ')
  3389. # geo_obj.make_index()
  3390. self.app.inform.emit('[success] %s' % _("Paint All with Rest-Machining done."))
  3391. def job_thread(app_obj):
  3392. try:
  3393. if self.rest_cb.isChecked():
  3394. app_obj.new_object("geometry", name, gen_paintarea_rest_machining, plot=plot)
  3395. else:
  3396. app_obj.new_object("geometry", name, gen_paintarea, plot=plot)
  3397. except FlatCAMApp.GracefulException:
  3398. proc.done()
  3399. return
  3400. except Exception:
  3401. proc.done()
  3402. traceback.print_stack()
  3403. return
  3404. proc.done()
  3405. # focus on Selected Tab
  3406. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  3407. self.app.inform.emit(_("Polygon Paint started ..."))
  3408. # Promise object with the new name
  3409. self.app.collection.promise(name)
  3410. if run_threaded:
  3411. # Background
  3412. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  3413. else:
  3414. job_thread(app_obj=self.app)
  3415. def paint_poly_ref(self, obj, sel_obj,
  3416. tooldia=None,
  3417. overlap=None,
  3418. order=None,
  3419. margin=None,
  3420. method=None,
  3421. outname=None,
  3422. connect=None,
  3423. contour=None,
  3424. tools_storage=None,
  3425. plot=True,
  3426. run_threaded=True):
  3427. """
  3428. Paints all polygons in this object that are within the sel_obj object
  3429. :param run_threaded:
  3430. :param plot:
  3431. :param obj: painted object
  3432. :param sel_obj: paint only what is inside this object bounds
  3433. :param tooldia: a tuple or single element made out of diameters of the tools to be used
  3434. :param overlap: value by which the paths will overlap
  3435. :param order: if the tools are ordered and how
  3436. :param margin: a border around painting area
  3437. :param outname: name of the resulting object
  3438. :param connect: Connect lines to avoid tool lifts.
  3439. :param contour: Paint around the edges.
  3440. :param method: choice out of _("Seed"), 'normal', 'lines'
  3441. :param tools_storage: whether to use the current tools_storage self.paints_tools or a different one.
  3442. Usage of the different one is related to when this function is called from a TcL command.
  3443. :return:
  3444. """
  3445. geo = sel_obj.solid_geometry
  3446. try:
  3447. if isinstance(geo, MultiPolygon):
  3448. env_obj = geo.convex_hull
  3449. elif (isinstance(geo, MultiPolygon) and len(geo) == 1) or \
  3450. (isinstance(geo, list) and len(geo) == 1) and isinstance(geo[0], Polygon):
  3451. env_obj = cascaded_union(self.bound_obj.solid_geometry)
  3452. else:
  3453. env_obj = cascaded_union(self.bound_obj.solid_geometry)
  3454. env_obj = env_obj.convex_hull
  3455. sel_rect = env_obj.buffer(distance=0.0000001, join_style=base.JOIN_STYLE.mitre)
  3456. except Exception as e:
  3457. log.debug("ToolPaint.on_paint_button_click() --> %s" % str(e))
  3458. self.app.inform.emit('[ERROR_NOTCL] %s' % _("No object available."))
  3459. return
  3460. self.paint_poly_area(obj=obj,
  3461. sel_obj=sel_rect,
  3462. tooldia=tooldia,
  3463. overlap=overlap,
  3464. order=order,
  3465. margin=margin,
  3466. method=method,
  3467. outname=outname,
  3468. connect=connect,
  3469. contour=contour,
  3470. tools_storage=tools_storage,
  3471. plot=plot,
  3472. run_threaded=run_threaded)
  3473. def ui_connect(self):
  3474. self.tools_table.itemChanged.connect(self.on_tool_edit)
  3475. # rows selected
  3476. self.tools_table.clicked.connect(self.on_row_selection_change)
  3477. self.tools_table.horizontalHeader().sectionClicked.connect(self.on_row_selection_change)
  3478. for row in range(self.tools_table.rowCount()):
  3479. try:
  3480. self.tools_table.cellWidget(row, 2).currentIndexChanged.connect(self.on_tooltable_cellwidget_change)
  3481. except AttributeError:
  3482. pass
  3483. try:
  3484. self.tools_table.cellWidget(row, 4).currentIndexChanged.connect(self.on_tooltable_cellwidget_change)
  3485. except AttributeError:
  3486. pass
  3487. self.tool_type_radio.activated_custom.connect(self.on_tool_type)
  3488. # first disconnect
  3489. for opt in self.form_fields:
  3490. current_widget = self.form_fields[opt]
  3491. if isinstance(current_widget, FCCheckBox):
  3492. try:
  3493. current_widget.stateChanged.disconnect()
  3494. except (TypeError, ValueError):
  3495. pass
  3496. if isinstance(current_widget, RadioSet):
  3497. try:
  3498. current_widget.activated_custom.disconnect()
  3499. except (TypeError, ValueError):
  3500. pass
  3501. elif isinstance(current_widget, FCDoubleSpinner):
  3502. try:
  3503. current_widget.returnPressed.disconnect()
  3504. except (TypeError, ValueError):
  3505. pass
  3506. # then reconnect
  3507. for opt in self.form_fields:
  3508. current_widget = self.form_fields[opt]
  3509. if isinstance(current_widget, FCCheckBox):
  3510. current_widget.stateChanged.connect(self.form_to_storage)
  3511. if isinstance(current_widget, RadioSet):
  3512. current_widget.activated_custom.connect(self.form_to_storage)
  3513. elif isinstance(current_widget, FCDoubleSpinner):
  3514. current_widget.returnPressed.connect(self.form_to_storage)
  3515. elif isinstance(current_widget, FCComboBox):
  3516. current_widget.currentIndexChanged.connect(self.form_to_storage)
  3517. self.rest_cb.stateChanged.connect(self.on_rest_machining_check)
  3518. self.order_radio.activated_custom[str].connect(self.on_order_changed)
  3519. def ui_disconnect(self):
  3520. try:
  3521. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  3522. self.tools_table.itemChanged.disconnect()
  3523. except (TypeError, AttributeError):
  3524. pass
  3525. # rows selected
  3526. try:
  3527. self.tools_table.clicked.disconnect(self.on_row_selection_change)
  3528. except (TypeError, AttributeError):
  3529. pass
  3530. try:
  3531. self.tools_table.horizontalHeader().sectionClicked.disconnect(self.on_row_selection_change)
  3532. except (TypeError, AttributeError):
  3533. pass
  3534. try:
  3535. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  3536. self.tool_type_radio.activated_custom.disconnect()
  3537. except (TypeError, AttributeError):
  3538. pass
  3539. for row in range(self.tools_table.rowCount()):
  3540. for col in [2, 4]:
  3541. try:
  3542. self.ui.geo_tools_table.cellWidget(row, col).currentIndexChanged.disconnect()
  3543. except (TypeError, AttributeError):
  3544. pass
  3545. for opt in self.form_fields:
  3546. current_widget = self.form_fields[opt]
  3547. if isinstance(current_widget, FCCheckBox):
  3548. try:
  3549. current_widget.stateChanged.disconnect(self.form_to_storage)
  3550. except (TypeError, ValueError):
  3551. pass
  3552. if isinstance(current_widget, RadioSet):
  3553. try:
  3554. current_widget.activated_custom.disconnect(self.form_to_storage)
  3555. except (TypeError, ValueError):
  3556. pass
  3557. elif isinstance(current_widget, FCDoubleSpinner):
  3558. try:
  3559. current_widget.returnPressed.disconnect(self.form_to_storage)
  3560. except (TypeError, ValueError):
  3561. pass
  3562. elif isinstance(current_widget, FCComboBox):
  3563. try:
  3564. current_widget.currentIndexChanged.connect(self.form_to_storage)
  3565. except (TypeError, ValueError):
  3566. pass
  3567. def reset_usage(self):
  3568. self.obj_name = ""
  3569. self.paint_obj = None
  3570. self.bound_obj = None
  3571. self.first_click = False
  3572. self.cursor_pos = None
  3573. self.mouse_is_dragging = False
  3574. self.sel_rect = []
  3575. @staticmethod
  3576. def paint_bounds(geometry):
  3577. def bounds_rec(o):
  3578. if type(o) is list:
  3579. minx = Inf
  3580. miny = Inf
  3581. maxx = -Inf
  3582. maxy = -Inf
  3583. for k in o:
  3584. try:
  3585. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  3586. except Exception as e:
  3587. log.debug("ToolPaint.bounds() --> %s" % str(e))
  3588. return
  3589. minx = min(minx, minx_)
  3590. miny = min(miny, miny_)
  3591. maxx = max(maxx, maxx_)
  3592. maxy = max(maxy, maxy_)
  3593. return minx, miny, maxx, maxy
  3594. else:
  3595. # it's a Shapely object, return it's bounds
  3596. return o.bounds
  3597. return bounds_rec(geometry)
  3598. def reset_fields(self):
  3599. self.obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))