File size: 10,863 Bytes
e237055
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
from __future__ import annotations

import os
import tempfile
import zipfile
from codecs import encode
from pathlib import Path
from textwrap import wrap

import numpy as np
from PIL import Image


def _setpress(pressure: float) -> str:
    pressure_str = str(int(pressure * 10)).zfill(4)
    command_bytes = bytes("08PS  " + pressure_str, "utf-8")
    hex_command = encode(command_bytes, "hex").decode("utf-8")
    format_command = "\\x" + "\\x".join(
        hex_command[i : i + 2] for i in range(0, len(hex_command), 2)
    )

    hex_pairs = wrap(hex_command, 2)
    decimal_sum = sum(int(pair, 16) for pair in hex_pairs)
    checksum_bin = bin(decimal_sum % 256)[2:].zfill(8)
    inverted = int("".join("1" if c == "0" else "0" for c in checksum_bin), 2) + 1
    checksum_hex = hex(inverted)[2:].upper()
    format_checksum = "\\x" + "\\x".join(
        checksum_hex[i : i + 2] for i in range(0, len(checksum_hex), 2)
    )

    return "b'" + "\\x05\\x02" + format_command + format_checksum + "\\x03" + "'"


def _togglepress() -> str:
    return "b'\\x05\\x02\\x30\\x34\\x44\\x49\\x20\\x20\\x43\\x46\\x03'"


def _setpress_cmd(port: str, pressure: float, start: bool) -> str:
    insert = "{preset}" if start else ""
    return f"\n\r{insert}{port}.write({_setpress(pressure)})"


def _toggle_cmd(port: str, start: bool) -> str:
    insert = "{preset}" if start else ""
    return f"\n\r{insert}{port}.write({_togglepress()})"


def _valve_cmd(valve: int, command: int) -> str:
    return f"\n{{aux_command}}WAGO_ValveCommands({valve}, {command})\n"


def _gcode_layer(
    path_img: np.ndarray,
    color_img: np.ndarray,
    output_list: list[dict],
    pixel_size: float,
    direction: int,
    layer_number: int,
) -> int:
    mask = path_img > 0
    first_nonblack = np.where(mask.any(axis=1), mask.argmax(axis=1), -1)
    last_nonblack = np.where(
        mask.any(axis=1),
        mask.shape[1] - 1 - np.fliplr(mask).argmax(axis=1),
        -1,
    )

    stored_gcode: list[dict] = []
    nonblank_rows = np.where(first_nonblack != -1)[0]

    for idx, i in enumerate(nonblank_rows):
        f_idx, l_idx = int(first_nonblack[i]), int(last_nonblack[i])
        if f_idx == -1:
            continue

        if direction < 0:
            rng = range(f_idx, l_idx + 1)
        else:
            rng = range(l_idx, f_idx - 1, -1)
        direction *= -1

        prev_color = None
        color_len = 0
        buffer = direction
        stored_gcode.append({"X": buffer * pixel_size, "Y": 0, "Color": 0})

        for j in rng:
            this_color = int(color_img[i, j])
            if prev_color is None:
                prev_color = this_color
                color_len = 1
            elif this_color == prev_color:
                color_len += 1
            else:
                stored_gcode.append(
                    {
                        "X": direction * color_len * pixel_size,
                        "Y": 0,
                        "Color": prev_color,
                    }
                )
                color_len = 1
                prev_color = this_color

        if color_len > 0:
            stored_gcode.append(
                {
                    "X": direction * color_len * pixel_size,
                    "Y": 0,
                    "Color": prev_color,
                }
            )

        stored_gcode.append({"X": buffer * pixel_size, "Y": 0, "Color": 0})

        curr_x = l_idx if direction > 0 else f_idx
        curr_x += buffer

        if idx + 1 < len(nonblank_rows):
            next_i = int(nonblank_rows[idx + 1])
            y_travel_dist = next_i - int(i)
            nf, nl = int(first_nonblack[next_i]), int(last_nonblack[next_i])
            if nf == -1:
                continue
            next_start = nf if direction < 0 else nl
            travel_x = (next_start + buffer) - curr_x
            y_dir = -1 if layer_number % 2 == 1 else 1
            stored_gcode.append(
                {
                    "X": travel_x * pixel_size,
                    "Y": y_travel_dist * pixel_size * y_dir,
                    "Color": 0,
                }
            )

    output_list.extend(stored_gcode)
    return direction


def _sort_key(filename: str) -> int:
    digits = "".join(filter(str.isdigit, filename))
    return int(digits) if digits else 2**31


def _extract_zip_tiffs(zip_path: Path, dest: Path) -> list[Path]:
    with zipfile.ZipFile(zip_path) as archive:
        archive.extractall(dest)

    tiffs: list[Path] = []
    for root, _, files in os.walk(dest):
        for name in files:
            if name.lower().endswith((".tif", ".tiff")):
                tiffs.append(Path(root) / name)
    tiffs.sort(key=lambda p: _sort_key(p.name))
    return tiffs


def _load_grayscale(path: Path, invert: bool) -> np.ndarray:
    with Image.open(path) as image:
        array = np.array(image.convert("L"), dtype=np.uint8)
    if invert:
        array = 255 - array
    return array


def generate_snake_path_gcode(
    zip_path: str | Path,
    shape_name: str,
    pressure: float,
    valve: int,
    port: int,
    fil_width: float = 0.8,
    invert: bool = True,
    increase_pressure_per_layer: float = 0.1,
) -> Path:
    zip_path = Path(zip_path)
    if not zip_path.exists():
        raise FileNotFoundError(f"ZIP file not found: {zip_path}")

    work_dir = Path(tempfile.mkdtemp(prefix="tiff_gcode_"))
    extract_dir = work_dir / "tiffs"
    extract_dir.mkdir(parents=True, exist_ok=True)
    tiff_files = _extract_zip_tiffs(zip_path, extract_dir)
    if not tiff_files:
        raise ValueError("No TIFF files found in the ZIP archive.")

    ref_list: list[np.ndarray] = []
    img_list: list[np.ndarray] = []
    for i, path in enumerate(tiff_files):
        img = _load_grayscale(path, invert=invert)
        ref_list.append(img.copy())
        if (i + 1) % 2 == 0:
            img = np.flipud(img)
        img_list.append(img)

    off_color = 0
    com_port = f"serialPort{port}"
    color_dict: dict[int, int] = {0: 100, 255: valve}

    setpress_lines = [_setpress_cmd(com_port, pressure, start=True)]
    pressure_on_lines = [_toggle_cmd(com_port, start=True)]
    pressure_off_lines = [_toggle_cmd(com_port, start=False)]

    gcode_list: list[dict] = []
    dist_sign_long = 1
    current_offsets_x: list[int] = []
    use_flip_y = False
    direction = -1

    for layers in range(len(img_list)):
        current_image = img_list[layers]
        current_image_ref = ref_list[layers]
        last_image_ref = ref_list[layers - 1] if layers > 0 else None
        y_ref = current_image_ref.shape[0]

        def find_first_valid_y(row: np.ndarray | None, flip: bool = False) -> int | None:
            if row is None:
                return None
            row_data = np.flip(row) if flip else row
            for j, pixel in enumerate(row_data):
                if np.any(pixel) != off_color:
                    return y_ref - 1 - j if flip else j
            return None

        last_x = last_y = None
        if current_offsets_x:
            use_flip_x = layers % 2 == 1
            last_x = current_offsets_x[-1] if use_flip_x else current_offsets_x[0]
            last_row = (
                last_image_ref[last_x] if last_image_ref is not None else None
            )
            last_y = find_first_valid_y(last_row, flip=use_flip_y)
            current_offsets_x.clear()

        current_offsets_x = [
            i for i, row in enumerate(current_image_ref) if np.any(row) != off_color
        ]

        first_x = first_y = None
        if current_offsets_x:
            use_flip_x = layers % 2 == 1
            first_x = current_offsets_x[-1] if use_flip_x else current_offsets_x[0]
            first_row = current_image_ref[first_x]
            first_y = find_first_valid_y(first_row, flip=use_flip_y)

        if None in (last_x, last_y, first_x, first_y):
            shift_x = shift_y = 0
        else:
            shift_x = (first_x - last_x) * fil_width
            shift_y = (first_y - last_y) * fil_width * dist_sign_long
            if use_flip_y:
                shift_y = -shift_y

        if len(current_offsets_x) % 2 == 1:
            use_flip_y = not use_flip_y

        if layers > 0:
            gcode_list.append(
                {"X": shift_y, "Y": shift_x, "Z": fil_width, "Color": 0}
            )

        for row in current_image_ref:
            if all(p == off_color for p in row):
                dist_sign_long = -dist_sign_long
            dist_sign_long = -dist_sign_long

        ref_for_path = current_image_ref.copy()
        if (layers + 1) % 2 == 0:
            ref_for_path = np.flipud(ref_for_path)

        if layers == 0:
            direction = -1
        direction = _gcode_layer(
            ref_for_path,
            current_image,
            gcode_list,
            fil_width,
            direction,
            layers,
        )

    gcode_path = work_dir / f"{shape_name}_SnakePath_gcode.txt"
    pressure_cur = float(pressure)

    with open(gcode_path, "w") as f:
        f.write("G91\n")
        for color in color_dict:
            f.write(_valve_cmd(color_dict[color], 0))
        for line in setpress_lines:
            f.write(f"{line}\n")
        for line in pressure_on_lines:
            f.write(f"{line}\n")

        pressure_next: str | None = None
        for i, move in enumerate(gcode_list):
            prev_color = gcode_list[i - 1]["Color"] if i > 0 else 0
            cur_color = move["Color"]
            if prev_color != cur_color:
                if cur_color == off_color:
                    f.write(_valve_cmd(color_dict[prev_color], 0))
                else:
                    if prev_color == off_color:
                        f.write(_valve_cmd(color_dict[cur_color], 1))
                    else:
                        f.write(_valve_cmd(color_dict[cur_color], 1))
                        f.write(_valve_cmd(color_dict[prev_color], 0))

            move_type = "G0" if cur_color != off_color else "G1"
            if "Z" in move:
                line = (
                    f"{move_type} X{move['X']} Y{move['Y']} Z{fil_width} "
                    f"; Color {move['Color']}"
                )
                pressure_cur += increase_pressure_per_layer
                pressure_next = _setpress_cmd(com_port, pressure_cur, start=False)
            else:
                line = (
                    f"{move_type} X{move['X']} Y{move['Y']} ; Color {move['Color']}"
                )
                pressure_next = None

            f.write(f"{line}\n")
            if pressure_next is not None:
                f.write(f"{pressure_next}\n")
                pressure_next = None

        for color in color_dict:
            f.write(_valve_cmd(color_dict[color], 0))
        for line in pressure_off_lines:
            f.write(f"{line}\n")

    return gcode_path