meerk40t 0.9.2000__py2.py3-none-any.whl → 0.9.3001__py2.py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (187) hide show
  1. meerk40t/balormk/balor_params.py +1 -43
  2. meerk40t/balormk/controller.py +1 -41
  3. meerk40t/balormk/device.py +16 -22
  4. meerk40t/balormk/driver.py +4 -4
  5. meerk40t/balormk/gui/balorconfig.py +2 -2
  6. meerk40t/balormk/gui/balorcontroller.py +13 -5
  7. meerk40t/balormk/gui/baloroperationproperties.py +0 -46
  8. meerk40t/balormk/gui/gui.py +17 -17
  9. meerk40t/camera/gui/camerapanel.py +18 -11
  10. meerk40t/core/cutcode/rastercut.py +3 -1
  11. meerk40t/core/cutplan.py +145 -14
  12. meerk40t/core/elements/clipboard.py +18 -9
  13. meerk40t/core/elements/element_treeops.py +320 -180
  14. meerk40t/core/elements/element_types.py +7 -2
  15. meerk40t/core/elements/elements.py +53 -27
  16. meerk40t/core/elements/geometry.py +8 -0
  17. meerk40t/core/elements/offset_clpr.py +129 -4
  18. meerk40t/core/elements/offset_mk.py +3 -1
  19. meerk40t/core/elements/shapes.py +28 -25
  20. meerk40t/core/laserjob.py +7 -0
  21. meerk40t/core/node/bootstrap.py +4 -0
  22. meerk40t/core/node/effect_hatch.py +85 -96
  23. meerk40t/core/node/effect_wobble.py +309 -0
  24. meerk40t/core/node/elem_image.py +49 -19
  25. meerk40t/core/node/elem_line.py +60 -0
  26. meerk40t/core/node/elem_rect.py +5 -3
  27. meerk40t/core/node/image_processed.py +766 -0
  28. meerk40t/core/node/image_raster.py +113 -0
  29. meerk40t/core/node/node.py +120 -1
  30. meerk40t/core/node/op_cut.py +2 -8
  31. meerk40t/core/node/op_dots.py +0 -8
  32. meerk40t/core/node/op_engrave.py +2 -18
  33. meerk40t/core/node/op_image.py +22 -35
  34. meerk40t/core/node/op_raster.py +0 -9
  35. meerk40t/core/planner.py +32 -2
  36. meerk40t/core/svg_io.py +699 -461
  37. meerk40t/core/treeop.py +191 -0
  38. meerk40t/core/undos.py +15 -1
  39. meerk40t/core/units.py +14 -4
  40. meerk40t/device/dummydevice.py +3 -2
  41. meerk40t/device/gui/defaultactions.py +43 -55
  42. meerk40t/device/gui/formatterpanel.py +58 -49
  43. meerk40t/device/gui/warningpanel.py +12 -12
  44. meerk40t/device/mixins.py +13 -0
  45. meerk40t/dxf/dxf_io.py +9 -5
  46. meerk40t/extra/ezd.py +28 -26
  47. meerk40t/extra/imageactions.py +300 -308
  48. meerk40t/extra/lbrn.py +19 -2
  49. meerk40t/fill/fills.py +6 -6
  50. meerk40t/fill/patternfill.py +1061 -1061
  51. meerk40t/fill/patterns.py +2 -6
  52. meerk40t/grbl/controller.py +168 -52
  53. meerk40t/grbl/device.py +23 -18
  54. meerk40t/grbl/driver.py +39 -0
  55. meerk40t/grbl/emulator.py +79 -19
  56. meerk40t/grbl/gcodejob.py +10 -0
  57. meerk40t/grbl/gui/grblconfiguration.py +2 -2
  58. meerk40t/grbl/gui/grblcontroller.py +24 -8
  59. meerk40t/grbl/gui/grblhardwareconfig.py +153 -0
  60. meerk40t/grbl/gui/gui.py +17 -14
  61. meerk40t/grbl/mock_connection.py +15 -34
  62. meerk40t/grbl/plugin.py +0 -4
  63. meerk40t/grbl/serial_connection.py +2 -1
  64. meerk40t/gui/about.py +8 -5
  65. meerk40t/gui/alignment.py +10 -6
  66. meerk40t/gui/basicops.py +27 -17
  67. meerk40t/gui/bufferview.py +2 -2
  68. meerk40t/gui/choicepropertypanel.py +101 -13
  69. meerk40t/gui/consolepanel.py +12 -9
  70. meerk40t/gui/devicepanel.py +38 -25
  71. meerk40t/gui/executejob.py +6 -4
  72. meerk40t/gui/help_assets/help_assets.py +13 -10
  73. meerk40t/gui/hersheymanager.py +8 -6
  74. meerk40t/gui/icons.py +1951 -3065
  75. meerk40t/gui/imagesplitter.py +14 -7
  76. meerk40t/gui/keymap.py +3 -3
  77. meerk40t/gui/laserpanel.py +151 -84
  78. meerk40t/gui/laserrender.py +61 -70
  79. meerk40t/gui/lasertoolpanel.py +8 -7
  80. meerk40t/gui/materialtest.py +3 -3
  81. meerk40t/gui/mkdebug.py +254 -1
  82. meerk40t/gui/navigationpanels.py +321 -180
  83. meerk40t/gui/notes.py +3 -3
  84. meerk40t/gui/opassignment.py +12 -12
  85. meerk40t/gui/operation_info.py +13 -13
  86. meerk40t/gui/plugin.py +5 -0
  87. meerk40t/gui/position.py +20 -18
  88. meerk40t/gui/preferences.py +21 -6
  89. meerk40t/gui/propertypanels/attributes.py +70 -22
  90. meerk40t/gui/propertypanels/blobproperty.py +2 -2
  91. meerk40t/gui/propertypanels/consoleproperty.py +2 -2
  92. meerk40t/gui/propertypanels/groupproperties.py +3 -3
  93. meerk40t/gui/propertypanels/hatchproperty.py +11 -18
  94. meerk40t/gui/propertypanels/imageproperty.py +4 -3
  95. meerk40t/gui/propertypanels/opbranchproperties.py +1 -1
  96. meerk40t/gui/propertypanels/pathproperty.py +2 -2
  97. meerk40t/gui/propertypanels/pointproperty.py +2 -2
  98. meerk40t/gui/propertypanels/propertywindow.py +4 -4
  99. meerk40t/gui/propertypanels/textproperty.py +3 -3
  100. meerk40t/gui/propertypanels/wobbleproperty.py +204 -0
  101. meerk40t/gui/ribbon.py +367 -259
  102. meerk40t/gui/scene/scene.py +31 -5
  103. meerk40t/gui/scenewidgets/elementswidget.py +12 -4
  104. meerk40t/gui/scenewidgets/gridwidget.py +2 -2
  105. meerk40t/gui/scenewidgets/laserpathwidget.py +7 -2
  106. meerk40t/gui/scenewidgets/machineoriginwidget.py +6 -2
  107. meerk40t/gui/scenewidgets/relocatewidget.py +1 -1
  108. meerk40t/gui/scenewidgets/reticlewidget.py +9 -0
  109. meerk40t/gui/scenewidgets/selectionwidget.py +12 -7
  110. meerk40t/gui/simpleui.py +95 -8
  111. meerk40t/gui/simulation.py +44 -36
  112. meerk40t/gui/spoolerpanel.py +124 -26
  113. meerk40t/gui/statusbarwidgets/defaultoperations.py +18 -6
  114. meerk40t/gui/statusbarwidgets/infowidget.py +2 -2
  115. meerk40t/gui/statusbarwidgets/opassignwidget.py +12 -12
  116. meerk40t/gui/statusbarwidgets/shapepropwidget.py +45 -18
  117. meerk40t/gui/statusbarwidgets/statusbar.py +11 -4
  118. meerk40t/gui/themes.py +78 -0
  119. meerk40t/gui/toolwidgets/toolcircle.py +2 -1
  120. meerk40t/gui/toolwidgets/toolellipse.py +2 -1
  121. meerk40t/gui/toolwidgets/toolimagecut.py +132 -0
  122. meerk40t/gui/toolwidgets/toolline.py +144 -0
  123. meerk40t/gui/toolwidgets/toolnodeedit.py +72 -145
  124. meerk40t/gui/toolwidgets/toolpoint.py +1 -1
  125. meerk40t/gui/toolwidgets/toolpolygon.py +8 -55
  126. meerk40t/gui/toolwidgets/toolrect.py +2 -1
  127. meerk40t/gui/usbconnect.py +2 -2
  128. meerk40t/gui/utilitywidgets/cyclocycloidwidget.py +2 -2
  129. meerk40t/gui/utilitywidgets/harmonograph.py +7 -7
  130. meerk40t/gui/utilitywidgets/scalewidget.py +1 -1
  131. meerk40t/gui/wordlisteditor.py +33 -18
  132. meerk40t/gui/wxmeerk40t.py +166 -66
  133. meerk40t/gui/wxmmain.py +236 -157
  134. meerk40t/gui/wxmribbon.py +49 -25
  135. meerk40t/gui/wxmscene.py +49 -38
  136. meerk40t/gui/wxmtree.py +216 -85
  137. meerk40t/gui/wxutils.py +62 -4
  138. meerk40t/image/imagetools.py +443 -15
  139. meerk40t/internal_plugins.py +2 -10
  140. meerk40t/kernel/kernel.py +12 -4
  141. meerk40t/lihuiyu/controller.py +7 -7
  142. meerk40t/lihuiyu/device.py +3 -1
  143. meerk40t/lihuiyu/driver.py +3 -0
  144. meerk40t/lihuiyu/gui/gui.py +8 -8
  145. meerk40t/lihuiyu/gui/lhyaccelgui.py +2 -2
  146. meerk40t/lihuiyu/gui/lhycontrollergui.py +73 -27
  147. meerk40t/lihuiyu/gui/lhydrivergui.py +2 -2
  148. meerk40t/lihuiyu/gui/tcpcontroller.py +22 -9
  149. meerk40t/main.py +6 -1
  150. meerk40t/moshi/controller.py +5 -5
  151. meerk40t/moshi/device.py +5 -2
  152. meerk40t/moshi/driver.py +4 -0
  153. meerk40t/moshi/gui/gui.py +8 -8
  154. meerk40t/moshi/gui/moshicontrollergui.py +24 -8
  155. meerk40t/moshi/gui/moshidrivergui.py +2 -2
  156. meerk40t/newly/controller.py +2 -0
  157. meerk40t/newly/device.py +9 -2
  158. meerk40t/newly/driver.py +4 -0
  159. meerk40t/newly/gui/gui.py +16 -17
  160. meerk40t/newly/gui/newlyconfig.py +2 -2
  161. meerk40t/newly/gui/newlycontroller.py +13 -5
  162. meerk40t/rotary/gui/gui.py +2 -2
  163. meerk40t/rotary/gui/rotarysettings.py +2 -2
  164. meerk40t/ruida/device.py +3 -0
  165. meerk40t/ruida/driver.py +4 -0
  166. meerk40t/ruida/gui/gui.py +6 -6
  167. meerk40t/ruida/gui/ruidaconfig.py +2 -2
  168. meerk40t/ruida/gui/ruidacontroller.py +13 -5
  169. meerk40t/svgelements.py +9 -9
  170. meerk40t/tools/geomstr.py +849 -153
  171. meerk40t/tools/kerftest.py +8 -4
  172. meerk40t/tools/livinghinges.py +15 -8
  173. {meerk40t-0.9.2000.dist-info → meerk40t-0.9.3001.dist-info}/METADATA +21 -16
  174. {meerk40t-0.9.2000.dist-info → meerk40t-0.9.3001.dist-info}/RECORD +185 -177
  175. {meerk40t-0.9.2000.dist-info → meerk40t-0.9.3001.dist-info}/entry_points.txt +0 -1
  176. test/test_core_elements.py +8 -24
  177. test/test_file_svg.py +88 -0
  178. test/test_fill.py +9 -9
  179. test/test_geomstr.py +258 -8
  180. test/test_kernel.py +4 -0
  181. test/test_tools_rasterplotter.py +29 -0
  182. meerk40t/extra/embroider.py +0 -56
  183. meerk40t/extra/pathoptimize.py +0 -249
  184. {meerk40t-0.9.2000.dist-info → meerk40t-0.9.3001.dist-info}/LICENSE +0 -0
  185. {meerk40t-0.9.2000.dist-info → meerk40t-0.9.3001.dist-info}/WHEEL +0 -0
  186. {meerk40t-0.9.2000.dist-info → meerk40t-0.9.3001.dist-info}/top_level.txt +0 -0
  187. {meerk40t-0.9.2000.dist-info → meerk40t-0.9.3001.dist-info}/zip-safe +0 -0
@@ -0,0 +1,766 @@
1
+ import threading
2
+ from copy import copy
3
+ from math import ceil, floor
4
+
5
+ from meerk40t.core.node.node import Node
6
+ from meerk40t.core.units import UNITS_PER_INCH
7
+ from meerk40t.image.imagetools import RasterScripts
8
+ from meerk40t.svgelements import Matrix, Path, Polygon
9
+
10
+
11
+ class ImageProcessedNode(Node):
12
+ """
13
+ ImageProcessedNode is the bootstrapped node type for the 'image processed' type.
14
+
15
+ This node type accepts an image_node as an operand. And calculates a processed node. Unprocessed nodes cannot
16
+ rotate and will not resample. This node will allow rotation, resampling, and processing scripts.
17
+ """
18
+
19
+ def __init__(self, **kwargs):
20
+ self.node = None
21
+ self.matrix = None
22
+ self.overscan = None
23
+ self.direction = None
24
+ self.dpi = 500
25
+ self.operations = list()
26
+ self.invert = None
27
+ self.dither = True
28
+ self.dither_type = "Floyd-Steinberg"
29
+ self.red = 1.0
30
+ self.green = 1.0
31
+ self.blue = 1.0
32
+ self.lightness = 1.0
33
+ self.view_invert = False
34
+ self.prevent_crop = False
35
+
36
+ super().__init__(type="elem image", **kwargs)
37
+ # kwargs can actually reset quite a lot of the properties to none
38
+ # so we need to revert these changes...
39
+ if self.red is None:
40
+ self.red = 1.0
41
+ if self.green is None:
42
+ self.green = 1.0
43
+ if self.blue is None:
44
+ self.blue = 1.0
45
+ if self.lightness is None:
46
+ self.lightness = 1.0
47
+ if self.operations is None:
48
+ self.operations = list()
49
+ if self.dither_type is None:
50
+ self.dither_type = "Floyd-Steinberg"
51
+
52
+ self.__formatter = "{element_type} {id} {width}x{height}"
53
+ if self.matrix is None:
54
+ self.matrix = Matrix()
55
+ if hasattr(self, "href"):
56
+ # TODO: Move all of this to svgio loading.
57
+ try:
58
+ from PIL import Image as PILImage
59
+
60
+ if not isinstance(self.href, str):
61
+ # Error caused by href being int value
62
+ raise ImportError
63
+
64
+ self.image = PILImage.open(self.href)
65
+ if hasattr(self, "x"):
66
+ self.matrix.post_translate_x(self.x)
67
+ if hasattr(self, "y"):
68
+ self.matrix.post_translate_x(self.y)
69
+ real_width, real_height = self.image.size
70
+ declared_width, declared_height = real_width, real_height
71
+ if hasattr(self, "width"):
72
+ declared_width = self.width
73
+ if hasattr(self, "height"):
74
+ declared_height = self.height
75
+ try:
76
+ sx = declared_width / real_width
77
+ sy = declared_height / real_height
78
+ self.matrix.post_scale(sx, sy)
79
+ except ZeroDivisionError:
80
+ pass
81
+ delattr(self, "href")
82
+ delattr(self, "x")
83
+ delattr(self, "y")
84
+ delattr(self, "height")
85
+ delattr(self, "width")
86
+ except ImportError:
87
+ self.image = None
88
+
89
+ # Step_x/y is the step factor of the image, the reciprocal of the DPI.
90
+ self.step_x = None
91
+ self.step_y = None
92
+
93
+ self._needs_update = False
94
+ self._update_thread = None
95
+ self._update_lock = threading.Lock()
96
+ self._processed_image = None
97
+ self._processed_matrix = None
98
+ self._process_image_failed = False
99
+ self.message = None
100
+ if self.operations or self.dither or self.prevent_crop:
101
+ step = UNITS_PER_INCH / self.dpi
102
+ step_x = step
103
+ step_y = step
104
+ self.process_image(step_x, step_y, not self.prevent_crop)
105
+
106
+ def __copy__(self):
107
+ nd = self.node_dict
108
+ nd["matrix"] = copy(self.matrix)
109
+ nd["operations"] = copy(self.operations)
110
+ return ImageProcessedNode(**nd)
111
+
112
+ def __repr__(self):
113
+ return f"{self.__class__.__name__}('{self.type}', {str(self.image)}, {str(self._parent)})"
114
+
115
+ def as_image(self):
116
+ if self._processed_image is None and (
117
+ (self.operations is not None and len(self.operations) > 0) or self.dither
118
+ ):
119
+ step = UNITS_PER_INCH / self.dpi
120
+ step_x = step
121
+ step_y = step
122
+ self.process_image(step_x, step_y, not self.prevent_crop)
123
+ return self._processed_image, self.bbox()
124
+
125
+ @property
126
+ def active_matrix(self):
127
+ if self._processed_matrix is None:
128
+ return self.matrix
129
+ return self._processed_matrix * self.matrix
130
+
131
+ def preprocess(self, context, matrix, plan):
132
+ """
133
+ Preprocess step during the cut planning stages.
134
+
135
+ We require a context to calculate the correct step values relative to the device
136
+ """
137
+ self.step_x, self.step_y = context.device.view.dpi_to_steps(self.dpi)
138
+ self.matrix *= matrix
139
+ self.set_dirty_bounds()
140
+ self.process_image(self.step_x, self.step_y, not self.prevent_crop)
141
+
142
+ def bbox(self, transformed=True, with_stroke=False):
143
+ image_width, image_height = self.active_image.size
144
+ matrix = self.active_matrix
145
+ x0, y0 = matrix.point_in_matrix_space((0, 0))
146
+ x1, y1 = matrix.point_in_matrix_space((image_width, image_height))
147
+ x2, y2 = matrix.point_in_matrix_space((0, image_height))
148
+ x3, y3 = matrix.point_in_matrix_space((image_width, 0))
149
+ return (
150
+ min(x0, x1, x2, x3),
151
+ min(y0, y1, y2, y3),
152
+ max(x0, x1, x2, x3),
153
+ max(y0, y1, y2, y3),
154
+ )
155
+
156
+ def default_map(self, default_map=None):
157
+ default_map = super().default_map(default_map=default_map)
158
+ default_map.update(self.__dict__)
159
+ image = self.active_image
160
+ default_map["width"] = image.width
161
+ default_map["height"] = image.height
162
+ default_map["element_type"] = "Image"
163
+ return default_map
164
+
165
+ def drop(self, drag_node, modify=True):
166
+ # Dragging element into element.
167
+ if drag_node.type.startswith("elem"):
168
+ if modify:
169
+ self.insert_sibling(drag_node)
170
+ return True
171
+ elif drag_node.type.startswith("op"):
172
+ # If we drag an operation to this node,
173
+ # then we will reverse the game
174
+ return drag_node.drop(self, modify=modify)
175
+ return False
176
+
177
+ def revalidate_points(self):
178
+ bounds = self.bounds
179
+ if bounds is None:
180
+ return
181
+ if len(self._points) < 9:
182
+ self._points.extend([None] * (9 - len(self._points)))
183
+ self._points[0] = [bounds[0], bounds[1], "bounds top_left"]
184
+ self._points[1] = [bounds[2], bounds[1], "bounds top_right"]
185
+ self._points[2] = [bounds[0], bounds[3], "bounds bottom_left"]
186
+ self._points[3] = [bounds[2], bounds[3], "bounds bottom_right"]
187
+ cx = (bounds[0] + bounds[2]) / 2
188
+ cy = (bounds[1] + bounds[3]) / 2
189
+ self._points[4] = [cx, cy, "bounds center_center"]
190
+ self._points[5] = [cx, bounds[1], "bounds top_center"]
191
+ self._points[6] = [cx, bounds[3], "bounds bottom_center"]
192
+ self._points[7] = [bounds[0], cy, "bounds center_left"]
193
+ self._points[8] = [bounds[2], cy, "bounds center_right"]
194
+
195
+ def update_point(self, index, point):
196
+ return False
197
+
198
+ def add_point(self, point, index=None):
199
+ return False
200
+
201
+ def update(self, context):
202
+ """
203
+ Update kicks off the image processing thread, which performs RasterWizard script operations on the image node.
204
+
205
+ The text should be displayed in the scene by the renderer. And any additional changes will be processed
206
+ until the new processed image is completed.
207
+
208
+ @param context:
209
+ @return:
210
+ """
211
+ self._needs_update = True
212
+ if context is not None:
213
+ self.message = "Processing..."
214
+ context.signal("refresh_scene", "Scene")
215
+ if self._update_thread is None:
216
+
217
+ def clear(result):
218
+ self._needs_update = False
219
+ self._update_thread = None
220
+ if context is not None:
221
+ if self._process_image_failed:
222
+ self.message = "Process image could not exist in memory."
223
+ else:
224
+ self.message = None
225
+ context.signal("refresh_scene", "Scene")
226
+ context.signal("image_updated", self)
227
+
228
+ self._processed_image = None
229
+ # self.processed_matrix = None
230
+ if context is None:
231
+ # Direct execution
232
+ self._needs_update = False
233
+ # Calculate scene step_x, step_y values
234
+ step = UNITS_PER_INCH / self.dpi
235
+ step_x = step
236
+ step_y = step
237
+ self.process_image(step_x, step_y, not self.prevent_crop)
238
+ # Unset cache.
239
+ self._cache = None
240
+ else:
241
+ self._update_thread = context.threaded(
242
+ self._process_image_thread, result=clear, daemon=True
243
+ )
244
+
245
+ def _process_image_thread(self):
246
+ """
247
+ The function deletes the caches and processes the image until it no longer needs updating.
248
+
249
+ @return:
250
+ """
251
+ while self._needs_update:
252
+ self._needs_update = False
253
+ # Calculate scene step_x, step_y values
254
+ step = UNITS_PER_INCH / self.dpi
255
+ step_x = step
256
+ step_y = step
257
+ self.process_image(step_x, step_y, not self.prevent_crop)
258
+ # Unset cache.
259
+ self._cache = None
260
+
261
+ def process_image(self, step_x=None, step_y=None, crop=True):
262
+ """
263
+ SVG matrices are defined as follows.
264
+ [a c e]
265
+ [b d f]
266
+
267
+ Pil requires a, c, e, b, d, f accordingly.
268
+
269
+ As of 0.7.2 this converts the image to "L" as part of the process.
270
+
271
+ There is a small amount of slop at the edge of converted images sometimes, so it's essential
272
+ to mark the image as inverted if black should be treated as empty pixels. The scaled down image
273
+ cannot lose the edge pixels since they could be important, but also dim may not be a multiple
274
+ of step level which requires an introduced empty edge pixel to be added.
275
+ """
276
+
277
+ from PIL import Image
278
+
279
+ if step_x is None:
280
+ step_x = self.step_x
281
+ if step_y is None:
282
+ step_y = self.step_y
283
+ try:
284
+ actualized_matrix, image = self._process_image(step_x, step_y, crop=crop)
285
+ self._processed_matrix = actualized_matrix * ~self.matrix
286
+ self._processed_image = image
287
+ self._process_image_failed = False
288
+ bb = self.bbox()
289
+ self._bounds = bb
290
+ self._paint_bounds = bb
291
+ except (MemoryError, Image.DecompressionBombError, ValueError):
292
+ # Memory error if creating requires too much memory.
293
+ # DecompressionBomb if over 272 megapixels.
294
+ # ValueError if bounds are NaN.
295
+ self._process_image_failed = True
296
+ self.updated()
297
+
298
+ @property
299
+ def opaque_image(self):
300
+ from PIL import Image
301
+
302
+ img = self.image
303
+ if img is not None:
304
+ if img.mode == "RGBA":
305
+ r, g, b, a = img.split()
306
+ background = Image.new("RGB", img.size, "white")
307
+ background.paste(img, mask=a)
308
+ img = background
309
+ return img
310
+
311
+ def _convert_image_to_grayscale(self, image):
312
+ # Convert image to L type.
313
+ if image.mode != "L":
314
+ # Precalculate RGB for L conversion.
315
+ # if self.red is None:
316
+ # self.red = 1
317
+ if self.red is None or self.green is None or self.blue is None:
318
+ r = 1
319
+ g = 1
320
+ b = 1
321
+ else:
322
+ r = self.red * 0.299
323
+ g = self.green * 0.587
324
+ b = self.blue * 0.114
325
+ v = self.lightness
326
+ c = r + g + b
327
+ try:
328
+ c /= v
329
+ r = r / c
330
+ g = g / c
331
+ b = b / c
332
+ except ZeroDivisionError:
333
+ pass
334
+ image = image.convert("RGB")
335
+ image = image.convert("L", matrix=(r, g, b, 1.0))
336
+ return image
337
+
338
+ def _get_transparent_mask(self, image):
339
+ """
340
+ Create Transparency Mask.
341
+ @param image:
342
+ @return:
343
+ """
344
+ if image is None:
345
+ return None
346
+ if "transparency" in image.info:
347
+ image = image.convert("RGBA")
348
+ try:
349
+ return image.getchannel("A").point(lambda e: 255 - e)
350
+ except ValueError:
351
+ return None
352
+
353
+ def _apply_mask(self, image, mask, reject_color=None):
354
+ """
355
+ Fill in original image with reject pixels.
356
+
357
+ @param image: Image to be masked off.
358
+ @param mask: Mask to apply to image
359
+ @param reject_color: Optional specified reject color override. Reject is usually "white" or black if inverted.
360
+ @return: image with mask pixels filled in with reject pixels
361
+ """
362
+ if not mask:
363
+ return image
364
+ if reject_color is None:
365
+ reject_color = "black" if self.invert else "white"
366
+ from PIL import Image
367
+
368
+ background = image.copy()
369
+ reject = Image.new("L", image.size, reject_color)
370
+ background.paste(reject, mask=mask)
371
+ return background
372
+
373
+ def _get_crop_box(self, image):
374
+ """
375
+ Get the bbox cutting off the reject edges. The reject edges depend on the image's invert setting.
376
+ @param image: Image to get crop box for.
377
+ @return:
378
+ """
379
+ try:
380
+ if self.invert:
381
+ return image.getbbox()
382
+ else:
383
+ return image.point(lambda e: 255 - e).getbbox()
384
+ except ValueError:
385
+ return None
386
+
387
+ def _process_script(self, image):
388
+ """
389
+ Process actual raster script operations. Any required grayscale, inversion, and masking will already have
390
+ occurred. If there were reject pixels before they will be masked off after this process.
391
+
392
+ @param image: image to process with self.operation script.
393
+
394
+ @return: processed image
395
+ """
396
+ from PIL import ImageEnhance, ImageFilter, ImageOps
397
+
398
+ overall_left = 0
399
+ overall_top = 0
400
+ overall_right, overall_bottom = image.size
401
+ for op in self.operations:
402
+ name = op["name"]
403
+ if name == "resample":
404
+ # This is just a reminder, that while this may still appear in the scripts it is intentionally
405
+ # ignored (or needs to be revised with the upcoming appearance of passthrough) as it is not
406
+ # serving the purpose of the past
407
+ continue
408
+ if name == "crop":
409
+ try:
410
+ if op["enable"] and op["bounds"] is not None:
411
+ crop = op["bounds"]
412
+ left = int(crop[0])
413
+ upper = int(crop[1])
414
+ right = int(crop[2])
415
+ lower = int(crop[3])
416
+ w, h = image.size
417
+ overall_left += left
418
+ overall_top += upper
419
+ overall_right -= w - right
420
+ overall_bottom -= h - lower
421
+ image = image.crop((left, upper, right, lower))
422
+ except KeyError:
423
+ pass
424
+ elif name == "edge_enhance":
425
+ try:
426
+ if op["enable"]:
427
+ if image.mode == "P":
428
+ image = image.convert("L")
429
+ image = image.filter(filter=ImageFilter.EDGE_ENHANCE)
430
+ except KeyError:
431
+ pass
432
+ elif name == "auto_contrast":
433
+ try:
434
+ if op["enable"]:
435
+ if image.mode not in ("RGB", "L"):
436
+ # Auto-contrast raises NotImplementedError if P
437
+ # Auto-contrast raises OSError if not RGB, L.
438
+ image = image.convert("L")
439
+ image = ImageOps.autocontrast(image, cutoff=op["cutoff"])
440
+ except KeyError:
441
+ pass
442
+ elif name == "tone":
443
+ try:
444
+ if op["enable"] and op["values"] is not None:
445
+ if image.mode == "L":
446
+ image = image.convert("P")
447
+ tone_values = op["values"]
448
+ if op["type"] == "spline":
449
+ spline = ImageProcessedNode.spline(tone_values)
450
+ else:
451
+ tone_values = [q for q in tone_values if q is not None]
452
+ spline = ImageProcessedNode.line(tone_values)
453
+ if len(spline) < 256:
454
+ spline.extend([255] * (256 - len(spline)))
455
+ if len(spline) > 256:
456
+ spline = spline[:256]
457
+ image = image.point(spline)
458
+ if image.mode != "L":
459
+ image = image.convert("L")
460
+ except KeyError:
461
+ pass
462
+ elif name == "contrast":
463
+ try:
464
+ if op["enable"]:
465
+ if op["contrast"] is not None and op["brightness"] is not None:
466
+ contrast = ImageEnhance.Contrast(image)
467
+ c = (op["contrast"] + 128.0) / 128.0
468
+ image = contrast.enhance(c)
469
+
470
+ brightness = ImageEnhance.Brightness(image)
471
+ b = (op["brightness"] + 128.0) / 128.0
472
+ image = brightness.enhance(b)
473
+ except KeyError:
474
+ pass
475
+ elif name == "gamma":
476
+ try:
477
+ if op["enable"] and op["factor"] is not None:
478
+ if image.mode == "L":
479
+ gamma_factor = float(op["factor"])
480
+
481
+ def crimp(px):
482
+ px = int(round(px))
483
+ if px < 0:
484
+ return 0
485
+ if px > 255:
486
+ return 255
487
+ return px
488
+
489
+ if gamma_factor == 0:
490
+ gamma_lut = [0] * 256
491
+ else:
492
+ gamma_lut = [
493
+ crimp(pow(i / 255, (1.0 / gamma_factor)) * 255)
494
+ for i in range(256)
495
+ ]
496
+ image = image.point(gamma_lut)
497
+ if image.mode != "L":
498
+ image = image.convert("L")
499
+ except KeyError:
500
+ pass
501
+ elif name == "unsharp_mask":
502
+ try:
503
+ if (
504
+ op["enable"]
505
+ and op["percent"] is not None
506
+ and op["radius"] is not None
507
+ and op["threshold"] is not None
508
+ ):
509
+ unsharp = ImageFilter.UnsharpMask(
510
+ radius=op["radius"],
511
+ percent=op["percent"],
512
+ threshold=op["threshold"],
513
+ )
514
+ image = image.filter(unsharp)
515
+ except (KeyError, ValueError): # Value error if wrong type of image.
516
+ pass
517
+ elif name == "halftone":
518
+ try:
519
+ if op["enable"]:
520
+ image = RasterScripts.halftone(
521
+ image,
522
+ sample=op["sample"],
523
+ angle=op["angle"],
524
+ oversample=op["oversample"],
525
+ black=op["black"],
526
+ )
527
+ except KeyError:
528
+ pass
529
+ elif name == "dither":
530
+ # Set dither
531
+ try:
532
+ if op["enable"] and op["type"] is not None:
533
+ self.dither_type = op["type"]
534
+ self.dither = True
535
+ else:
536
+ # Takes precedence
537
+ self.dither = False
538
+ # image = self._apply_dither(image)
539
+ except KeyError:
540
+ pass
541
+ else:
542
+ # print(f"Unknown operation in raster-script: {name}")
543
+ continue
544
+ return image, (overall_left, overall_top, overall_right, overall_bottom)
545
+
546
+ def _apply_dither(self, image):
547
+ """
548
+ Dither image to 1 bit. Floyd-Steinberg is performed by Pillow, other dithers require custom code.
549
+
550
+ @param image: grayscale image to dither.
551
+ @return: 1 bit dithered image
552
+ """
553
+ from meerk40t.image.imagetools import dither
554
+
555
+ if self.dither and self.dither_type is not None:
556
+ if self.dither_type != "Floyd-Steinberg":
557
+ image = dither(image, self.dither_type)
558
+ image = image.convert("1")
559
+ return image
560
+
561
+ def _process_image(self, step_x, step_y, crop=True):
562
+ """
563
+ This core code replaces the older actualize and rasterwizard functionalities. It should convert the image to
564
+ a post-processed form with resulting post-process matrix.
565
+
566
+ @param crop: Should the unneeded edges be cropped as part of this process. The need for the edge is determined
567
+ by the color and the state of the self.invert attribute.
568
+ @return:
569
+ """
570
+ from PIL import Image, ImageOps
571
+
572
+ image = self.image
573
+
574
+ transparent_mask = self._get_transparent_mask(image)
575
+
576
+ image = self._convert_image_to_grayscale(self.opaque_image)
577
+
578
+ image = self._apply_mask(image, transparent_mask)
579
+
580
+ # Calculate image box.
581
+ box = None
582
+ if crop:
583
+ box = self._get_crop_box(image)
584
+ if box is None:
585
+ # If box is entirely white, bbox caused value error, or crop not set.
586
+ box = (0, 0, image.width, image.height)
587
+
588
+ transform_matrix = copy(self.matrix) # Prevent Knock-on effect.
589
+
590
+ # Find the boundary points of the rotated box edges.
591
+ boundary_points = [
592
+ transform_matrix.point_in_matrix_space([box[0], box[1]]), # Top-left
593
+ transform_matrix.point_in_matrix_space([box[2], box[1]]), # Top-right
594
+ transform_matrix.point_in_matrix_space([box[0], box[3]]), # Bottom-left
595
+ transform_matrix.point_in_matrix_space([box[2], box[3]]), # Bottom-right
596
+ ]
597
+ xs = [e[0] for e in boundary_points]
598
+ ys = [e[1] for e in boundary_points]
599
+
600
+ # bbox here is expanded matrix size of box.
601
+ step_scale_x = 1 / float(step_x)
602
+ step_scale_y = 1 / float(step_y)
603
+
604
+ bbox = min(xs), min(ys), max(xs), max(ys)
605
+
606
+ image_width = ceil(bbox[2] * step_scale_x) - floor(bbox[0] * step_scale_x)
607
+ image_height = ceil(bbox[3] * step_scale_y) - floor(bbox[1] * step_scale_y)
608
+ tx = bbox[0]
609
+ ty = bbox[1]
610
+ transform_matrix.post_translate(-tx, -ty)
611
+ transform_matrix.post_scale(step_scale_x, step_scale_y)
612
+ if step_y < 0:
613
+ # If step_y is negative, translate
614
+ transform_matrix.post_translate(0, image_height)
615
+ if step_x < 0:
616
+ # If step_x is negative, translate
617
+ transform_matrix.post_translate(image_width, 0)
618
+
619
+ try:
620
+ transform_matrix.inverse()
621
+ except ZeroDivisionError:
622
+ # malformed matrix, scale=0 or something.
623
+ transform_matrix.reset()
624
+
625
+ # Perform image transform if needed.
626
+ if (
627
+ self.matrix.a != step_x
628
+ or self.matrix.b != 0.0
629
+ or self.matrix.c != 0.0
630
+ or self.matrix.d != step_y
631
+ ):
632
+ if image_height <= 0:
633
+ image_height = 1
634
+ if image_width <= 0:
635
+ image_width = 1
636
+ image = image.transform(
637
+ (image_width, image_height),
638
+ Image.AFFINE,
639
+ (
640
+ transform_matrix.a,
641
+ transform_matrix.c,
642
+ transform_matrix.e,
643
+ transform_matrix.b,
644
+ transform_matrix.d,
645
+ transform_matrix.f,
646
+ ),
647
+ resample=Image.BICUBIC,
648
+ fillcolor="black" if self.invert else "white",
649
+ )
650
+ actualized_matrix = Matrix()
651
+
652
+ # If crop applies, apply crop.
653
+ if crop:
654
+ box = self._get_crop_box(image)
655
+ if box is not None:
656
+ width = box[2] - box[0]
657
+ height = box[3] - box[1]
658
+ if width != image.width or height != image.height:
659
+ image = image.crop(box)
660
+ actualized_matrix.post_translate(box[0], box[1])
661
+
662
+ if step_y < 0:
663
+ # if step_y is negative, translate.
664
+ actualized_matrix.post_translate(0, -image_height)
665
+ if step_x < 0:
666
+ # if step_x is negative, translate.
667
+ actualized_matrix.post_translate(-image_width, 0)
668
+
669
+ actualized_matrix.post_scale(step_x, step_y)
670
+ actualized_matrix.post_translate(tx, ty)
671
+
672
+ # Invert black to white if needed.
673
+ if self.invert:
674
+ image = ImageOps.invert(image)
675
+
676
+ # Find rejection mask of white pixels. (already inverted)
677
+ reject_mask = image.point(lambda e: 0 if e == 255 else 255)
678
+
679
+ image, newbounds = self._process_script(image)
680
+ # This may have again changed the size of the image (op crop)
681
+ # so we need to adjust the reject mask...
682
+ reject_mask = reject_mask.crop(newbounds)
683
+
684
+ background = Image.new("L", image.size, "white")
685
+ background.paste(image, mask=reject_mask)
686
+ image = background
687
+
688
+ image = self._apply_dither(image)
689
+ return actualized_matrix, image
690
+
691
+ @staticmethod
692
+ def line(p):
693
+ N = len(p) - 1
694
+ try:
695
+ m = [(p[i + 1][1] - p[i][1]) / (p[i + 1][0] - p[i][0]) for i in range(0, N)]
696
+ except ZeroDivisionError:
697
+ m = [1] * N
698
+ # b = y - mx
699
+ b = [p[i][1] - (m[i] * p[i][0]) for i in range(0, N)]
700
+ r = list()
701
+ for i in range(0, p[0][0]):
702
+ r.append(0)
703
+ for i in range(len(p) - 1):
704
+ x0 = p[i][0]
705
+ x1 = p[i + 1][0]
706
+ range_list = [int(round((m[i] * x) + b[i])) for x in range(x0, x1)]
707
+ r.extend(range_list)
708
+ for i in range(p[-1][0], 256):
709
+ r.append(255)
710
+ r.append(round(int(p[-1][1])))
711
+ return r
712
+
713
+ @staticmethod
714
+ def spline(p):
715
+ """
716
+ Spline interpreter.
717
+
718
+ Returns all integer locations between different spline interpolation values
719
+ @param p: points to be quad spline interpolated.
720
+ @return: integer y values for given spline points.
721
+ """
722
+ try:
723
+ N = len(p) - 1
724
+ w = [(p[i + 1][0] - p[i][0]) for i in range(0, N)]
725
+ h = [(p[i + 1][1] - p[i][1]) / w[i] for i in range(0, N)]
726
+ ftt = (
727
+ [0]
728
+ + [3 * (h[i + 1] - h[i]) / (w[i + 1] + w[i]) for i in range(0, N - 1)]
729
+ + [0]
730
+ )
731
+ A = [(ftt[i + 1] - ftt[i]) / (6 * w[i]) for i in range(0, N)]
732
+ B = [ftt[i] / 2 for i in range(0, N)]
733
+ C = [h[i] - w[i] * (ftt[i + 1] + 2 * ftt[i]) / 6 for i in range(0, N)]
734
+ D = [p[i][1] for i in range(0, N)]
735
+ except ZeroDivisionError:
736
+ return list(range(256))
737
+ r = list()
738
+ for i in range(0, p[0][0]):
739
+ r.append(0)
740
+ for i in range(len(p) - 1):
741
+ a = p[i][0]
742
+ b = p[i + 1][0]
743
+ r.extend(
744
+ int(
745
+ round(
746
+ A[i] * (x - a) ** 3
747
+ + B[i] * (x - a) ** 2
748
+ + C[i] * (x - a)
749
+ + D[i]
750
+ )
751
+ )
752
+ for x in range(a, b)
753
+ )
754
+ for i in range(p[-1][0], 256):
755
+ r.append(255)
756
+ r.append(round(int(p[-1][1])))
757
+ return r
758
+
759
+ def as_path(self):
760
+ image_width, image_height = self.active_image.size
761
+ matrix = self.active_matrix
762
+ x0, y0 = matrix.point_in_matrix_space((0, 0))
763
+ x1, y1 = matrix.point_in_matrix_space((0, image_height))
764
+ x2, y2 = matrix.point_in_matrix_space((image_width, image_height))
765
+ x3, y3 = matrix.point_in_matrix_space((image_width, 0))
766
+ return abs(Path(Polygon((x0, y0), (x1, y1), (x2, y2), (x3, y3), (x0, y0))))