-
Notifications
You must be signed in to change notification settings - Fork 3
/
ImagePrinter.ts
156 lines (132 loc) · 4.02 KB
/
ImagePrinter.ts
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
import { Frame, GIF, Image } from "https://deno.land/x/imagescript/mod.ts";
import { extname, join } from "https://deno.land/std@0.123.0/path/mod.ts";
import { sprintf } from "https://deno.land/std@0.125.0/fmt/printf.ts";
import { EOL } from "https://deno.land/std@0.125.0/fs/mod.ts";
import { materials } from "../store/_materials.ts";
import BlockEntry from "./BlockEntry.ts";
import { DIR_BP } from "../store/_config.ts";
import { hex2rgb } from "../_utils.ts";
import type { IMaterial, RGB } from "../../typings/types.ts";
const MAX_PRINT_SIZE = 3 * 16;
const MASK_COLOR = [
Image.rgbaToColor(255, 255, 255, 0),
Image.rgbaToColor(0, 0, 0, 0),
]; // Image.rgbToColor(...hex2rgb("#ff00ff"));
const FUNCTIONS_NAMESPACE = "printer";
const DIR_FUNCTIONS = join(DIR_BP, "functions", FUNCTIONS_NAMESPACE);
type Axis = "x" | "y" | "z";
function colorDistance(color1: RGB, color2: RGB) {
return Math.sqrt(
Math.pow(color1[0] - color2[0], 2) + Math.pow(color1[1] - color2[1], 2) +
Math.pow(color1[2] - color2[2], 2),
);
}
export function getNearestColor(
color: RGB,
palette: BlockEntry[],
): BlockEntry {
// https://gist.github.com/Ademking/560d541e87043bfff0eb8470d3ef4894?permalink_comment_id=3720151#gistcomment-3720151
return palette.reduce(
(prev: [number, BlockEntry], curr: BlockEntry): [number, BlockEntry] => {
const distance = colorDistance(color, hex2rgb(curr.hexColor()));
return (distance < prev[0]) ? [distance, curr] : prev;
},
[Number.POSITIVE_INFINITY, palette[0]],
)[1];
}
function writeFill(
x: number,
y: number,
z: number,
fillWith = "air",
flipAxis?: Axis,
): string {
const position = sprintf(
"~%d ~%d ~%d",
...(flipAxis === "x"
? [z, y, x]
: flipAxis === "y"
? [x, z, y]
: [x, y, z]),
);
return `fill ${position} ${position} ${fillWith} 0 keep`;
}
async function printDecoded(
name: string,
idx: number,
img: Image | Frame,
palette: BlockEntry[],
offset: number[],
) {
const axises = ["x", "y", "z"] as const;
// TODO: Add 10000 line limit
return await Promise.all(
materials.flatMap(async ({ label }: IMaterial) => {
const materialPalette = palette.filter(({ material }: BlockEntry) =>
label === material.label
);
return await Promise.all(axises.map(async (axis) => {
const func: string[] = [];
for (const [x, y, c] of img.iterateWithColors()) {
const nearest = MASK_COLOR.includes(c)
? "air"
: getNearestColor(<RGB> Image.colorToRGB(c), materialPalette)
.behaviorId;
func.push(
writeFill(
x + offset[0],
Math.abs((y + offset[1]) - img.height), // Starts print row at top
offset[2],
nearest,
<Axis> axis,
),
);
}
// FIXME: Use sprintf
const filename = `${name + (idx ? `_${idx}` : "")}_${
label || ""
}_${axis}`;
await Deno.writeTextFile(
join(
DIR_FUNCTIONS,
`${filename}.mcfunction`,
),
func.join(EOL.CRLF),
);
return filename;
}));
}),
);
}
export async function pixelPrinter(
name: string,
imageUrl: URL,
palette: BlockEntry[],
chunks = 2,
) {
const res = await fetch(imageUrl.href);
const data = new Uint8Array(await res.arrayBuffer());
const frames = (extname(imageUrl.href) !== ".gif")
? [await Image.decode(data)]
: (await GIF.decode(data, false));
const size = Math.min(MAX_PRINT_SIZE, chunks * 16);
let fnNames: Array<string | undefined> = [];
let idx = 0;
for await (const frame of frames) {
if (frame.width > size) {
frame.resize(size, Image.RESIZE_AUTO, Image.RESIZE_NEAREST_NEIGHBOR);
}
// Align frames end-to-end
//const offsets = [(idx * frame.width) + 1, 0, idx + 1];
// Align frames as stack
const offsets = [0, 0, idx];
await printDecoded(
name,
idx,
frame,
palette,
offsets,
);
idx++;
}
}