-
Notifications
You must be signed in to change notification settings - Fork 482
Expand file tree
/
Copy pathpainter.js
More file actions
3509 lines (3304 loc) · 113 KB
/
Copy pathpainter.js
File metadata and controls
3509 lines (3304 loc) · 113 KB
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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { PointerTarget } from "../interface/pointer_target";
import { clipboard, nativeImage } from "../native_apis";
import { Dynamic2DMap } from "../util/dynamic_2d_map";
StateMemory.init('brush_presets', 'array')
export const Painter = {
currentPixel: [-1, -1],
brushChanges: false,
current: {/*texture, image*/},
selection: {},
mirror_painting: false,
lock_alpha: false,
erase_mode: false,
edit(texture, callback, options) {
if (!options.no_undo && !options.no_undo_init) {
Undo.initEdit({textures: [texture], bitmap: true})
}
if (!texture.internal) texture.convertToInternal();
let edit_name = options.no_undo ? null : (options.edit_name || 'Edit texture');
let {canvas, ctx, offset} = texture.getActiveCanvas();
Painter.current.ctx = ctx;
if (!Painter.current.textures) Painter.current.textures = [];
Painter.current.textures.safePush(texture);
Painter.current.texture = texture;
Painter.current.offset = offset;
callback(canvas, Painter.current);
Blockbench.dispatchEvent('edit_texture', {texture, options, canvas, ctx, offset});
if (options.use_cache && options.no_update === true) {
return;
}
if (options.no_undo && options.use_cache) {
texture.updateLayerChanges();
let map = texture.getOwnMaterial().map;
map.needsUpdate = true;
UVEditor.vue.updateTextureCanvas();
} else {
texture.updateChangesAfterEdit();
if (!options.no_undo && !options.no_undo_finish) {
Undo.finishEdit(edit_name)
}
}
},
//alpha
setAlphaMatrix(texture, x, y, val) {
if (!Painter.current.alpha_matrix) Painter.current.alpha_matrix = {}
var mx = Painter.current.alpha_matrix;
if (!mx[texture.uuid]) mx[texture.uuid] = {};
if (!mx[texture.uuid][x]) mx[texture.uuid][x] = {};
if (mx[texture.uuid][x][y]) {
val = Math.max(val, mx[texture.uuid][x][y])
}
mx[texture.uuid][x][y] = val
},
getAlphaMatrix(texture, x, y) {
return Painter.current.alpha_matrix
&& Painter.current.alpha_matrix[texture.uuid]
&& Painter.current.alpha_matrix[texture.uuid][x]
&& Painter.current.alpha_matrix[texture.uuid][x][y];
},
// Preview Brush
getTextureToEdit(input_texture) {
if (BarItems.view_mode.value == 'material' && input_texture) {
if (input_texture.selected) return input_texture;
let texture_group = input_texture.getGroup();
if (texture_group) {
let textures = texture_group.getTextures();
if (textures.includes(Texture.selected)) {
return Texture.selected;
}
}
}
return input_texture;
},
startPaintToolCanvas(data, e) {
if (!data.intersects && Toolbox.selected.id == 'color_picker') {
let projections = {};
let references = ReferenceImage.active.filter(reference => {
let result = reference.projectMouseCursor(e.clientX, e.clientY);
if (result) {
projections[reference.uuid] = result;
return true;
}
});
if (references.length > 1) {
let z_indices = {background: 1, viewport: 2, blueprint: 0, float: 4};
references.sort((a, b) => z_indices[a.layer] - z_indices[b.layer]);
}
if (references.length) {
let projection = projections[references.last().uuid];
var ctx = Painter.getCanvas(references.last().img).getContext('2d');
let color = Painter.getPixelColor(ctx, projection[0], projection[1]);
if (settings.pick_color_opacity.value) {
let opacity = Math.floor(color.getAlpha()*256);
for (let id in BarItems) {
let tool = BarItems[id];
if (tool.tool_settings && tool.tool_settings.brush_opacity >= 0) {
tool.tool_settings.brush_opacity = opacity;
}
}
BarItems.slider_brush_opacity.update();
}
ColorPanel.set(color, e.button == 2);
}
}
if (!data.intersects || (data.element && data.element.locked)) return;
var texture = Painter.getTextureToEdit(data.element.faces[data.face].getTexture())
if (!texture || (texture.error && texture.error !== 2)) {
Blockbench.showQuickMessage('message.untextured')
return;
}
let [x, y] = Painter.getCanvasToolPixelCoords(data.intersects[0].uv, texture);
UVEditor.vue.texture = texture;
Painter.startPaintTool(texture, x, y, data.element.faces[data.face].uv, e, data)
addEventListeners(document, 'pointermove', Painter.movePaintToolCanvas, false );
addEventListeners(document, 'pointerup', Painter.stopPaintToolCanvas, false );
},
movePaintToolCanvas(event, data) {
convertTouchEvent(event);
if (!data) data = Canvas.raycast(event)
if (data && data.element && !data.element.locked && data.face) {
var texture = Painter.getTextureToEdit(data.element.faces[data.face].getTexture());
if (!texture) return;
if (texture.img.naturalWidth + texture.img.naturalHeight == 0) return;
let new_face;
let [x, y] = Painter.getCanvasToolPixelCoords(data.intersects[0].uv, texture);
let interval = Toolbox.selected.brush?.interval || 1;
let delta = [x - Painter.current.x, y - Painter.current.y];
let distance = Math.sqrt(Math.pow(delta[0], 2) + Math.pow(delta[1], 2));
if (distance < interval) {
return;
} else if (distance > interval && !(!Toolbox.selected.brush || Condition(Toolbox.selected.brush.floor_coordinates))) {
let rounded_distance = Math.floor(distance/interval)*interval;
x = Painter.current.x + (delta[0] / distance) * rounded_distance;
y = Painter.current.y + (delta[1] / distance) * rounded_distance;
}
if (
Painter.current.element !== data.element ||
(Painter.current.face !== data.face && !(data.element.faces[data.face] instanceof MeshFace && Painter.getMeshUVIsland(data.face, data.element.faces[data.face]).includes(Painter.current.face)))
) {
if (Toolbox.selected.id === 'draw_shape_tool' || Toolbox.selected.id === 'gradient_tool') {
return;
}
Painter.current.x = x
Painter.current.y = y
Painter.current.face = data.face
Painter.current.element = data.element
new_face = true
UVEditor.vue.texture = texture;
if (texture !== Painter.current.texture && Undo.current_save) {
Undo.current_save.addTextureOrLayer(texture)
}
} else {
let max_interval_dist = 6;
if (Painter.current.face != data.face && (delta[0]**2 + delta[1]**2) > max_interval_dist**2) {
new_face = true;
}
Painter.current.face = data.face;
}
Painter.movePaintTool(texture, x, y, event, new_face, data.element.faces[data.face].uv)
}
},
stopPaintToolCanvas() {
removeEventListeners(document, 'pointermove', Painter.movePaintToolCanvas, false );
removeEventListeners(document, 'pointerup', Painter.stopPaintToolCanvas, false );
Painter.stopPaintTool();
},
getMeshUVIsland(fkey, face) {
if (!Painter.current.uv_islands) Painter.current.uv_islands = {};
if (!Painter.current.uv_islands[fkey]) {
Painter.current.uv_islands[fkey] = face.getUVIsland(48);
}
return Painter.current.uv_islands[fkey];
},
// Paint Tool Main
startPaintTool(texture, x, y, uvTag, event, data) {
//Called directly by startPaintToolCanvas and startBrushUV
delete Painter.paint_stroke_canceled;
if (settings.paint_with_stylus_only.value && !(event.pointerType == 'pen' || event.touches?.[0]?.touchType == 'stylus')) {
Painter.paint_stroke_canceled = true;
return;
}
if (!PointerTarget.requestTarget(PointerTarget.types.paint)) {
Painter.paint_stroke_canceled = true;
if (Toolbox.selected != BarItems.copy_brush || !event.ctrlOrCmd) {
return;
}
}
if (Toolbox.selected.brush && Toolbox.selected.brush.onStrokeStart) {
let result = Toolbox.selected.brush.onStrokeStart({texture, x, y, uv: uvTag, event, raycast_data: data});
if (result == false) {
Painter.paint_stroke_canceled = true;
return;
}
}
if (Toolbox.selected.id === 'color_picker') {
Painter.colorPicker(texture, x, y, event);
Painter.paint_stroke_canceled = true;
return;
}
let undo_aspects = {selected_texture: true, bitmap: true};
if (texture.layers_enabled && texture.layers[0]) {
undo_aspects.layers = [texture.getActiveLayer()];
} else {
undo_aspects.textures = [texture];
}
Undo.initEdit(undo_aspects);
Painter.current.start_event = event;
Painter.brushChanges = false;
if (Toolbox.selected.id === 'draw_shape_tool' || Toolbox.selected.id === 'gradient_tool') {
Painter.current = {
element: data && data.element,
face: data && data.face,
x, y,
clear: document.createElement('canvas'),
face_matrices: {}
}
Painter.startPixel = [x, y];
let {canvas} = texture.getActiveCanvas();
Painter.current.clear.width = canvas.width;
Painter.current.clear.height = canvas.height;
Painter.current.clear.getContext('2d').drawImage(canvas, 0, 0);
} else {
Painter.current.face_matrices = {};
let is_line
if (data) {
is_line = (event.shiftKey || Pressing.overrides.shift)
&& Painter.current.element == data.element
&& (Painter.current.face == data.face ||
(data.element.faces[data.face] instanceof MeshFace && Painter.getMeshUVIsland(data.face, data.element.faces[data.face]).includes(Painter.current.face))
)
Painter.current.element = data.element;
Painter.current.face = data.face;
} else {
//uv editor
is_line = (event.shiftKey || Pressing.overrides.shift);
}
if (Toolbox.selected.brush?.line == false) is_line = false;
texture.edit(canvas => {
if (is_line) {
Painter.drawBrushLine(texture, x, y, event, false, uvTag);
} else {
Painter.current.x = Painter.current.y = 0
Painter.useBrushlike(texture, x, y, event, uvTag)
}
Painter.current.x = x;
Painter.current.y = y;
}, {no_undo: true, use_cache: true});
}
},
movePaintTool(texture, x, y, event, new_face, uv) {
// Called directly from movePaintToolCanvas and moveBrushUV
if (Painter.paint_stroke_canceled) return;
if (!PointerTarget.requestTarget(PointerTarget.types.paint)) return;
if (Toolbox.selected.brush && Toolbox.selected.brush.onStrokeMove) {
let result = Toolbox.selected.brush.onStrokeMove({texture, x, y, uv, event, raycast_data: data});
if (result == false) return;
}
if (Toolbox.selected.id === 'draw_shape_tool') {
Painter.useShapeTool(texture, x, y, event, uv)
} else if (Toolbox.selected.id === 'gradient_tool') {
Painter.useGradientTool(texture, x, y, event, uv)
} else {
texture.edit(canvas => {
let is_line = true;
if (new_face) is_line = false;
if (BarItems.image_tiled_view.value == true && (Math.abs(Painter.current.x - x) > texture.width/2 || Math.abs(Painter.current.y - y) > texture.display_height/2)) {
is_line = false;
}
if (is_line) {
Painter.drawBrushLine(texture, x, y, event, new_face, uv);
} else {
Painter.current.x = Painter.current.y = 0;
Painter.useBrushlike(texture, x, y, event, uv)
}
}, {no_undo: true, use_cache: true});
}
Painter.current.x = x;
Painter.current.y = y;
},
stopPaintTool() {
PointerTarget.endTarget();
if (Painter.paint_stroke_canceled) {
delete Painter.paint_stroke_canceled;
return;
}
let texture = Painter.current.texture;
if (Toolbox.selected.brush && Toolbox.selected.brush.onStrokeEnd) {
let result = Toolbox.selected.brush.onStrokeEnd({texture});
if (result == false) return;
}
if (Painter.brushChanges) {
Painter.current.textures.forEach(texture => {
texture.updateChangesAfterEdit();
})
Undo.finishEdit('Paint texture');
Painter.brushChanges = false;
}
if (Toolbox.selected.id == 'gradient_tool' || Toolbox.selected.id == 'draw_shape_tool') {
Blockbench.setStatusBarText();
}
preventContextMenu();
delete Painter.current.alpha_matrix;
delete Painter.editing_area;
delete Painter.current.cached_canvases;
delete Painter.current.last_pixel;
delete Painter.current.texture;
delete Painter.current.textures;
delete Painter.current.uv_rects;
delete Painter.current.uv_islands;
delete Painter.current.dynamic_brush_size;
delete Painter.current.face_matrices;
delete Painter.current.start_event;
Painter.currentPixel = [-1, -1];
},
// Tools
setupRectFromFace(uvTag, texture) {
if (!Painter.current.uv_rects) {
Painter.current.uv_rects = new Map();
}
let cached_rect = Painter.current.uv_rects.get(uvTag);
if (cached_rect) {
Painter.editing_area = cached_rect;
return cached_rect;
}
let rect;
let uvFactorX = texture.width / texture.getUVWidth();
let uvFactorY = texture.display_height / texture.getUVHeight();
if (uvTag) {
let anim_offset = texture.display_height * texture.currentFrame;
if (uvTag instanceof Array) {
rect = Painter.editing_area = [
uvTag[0] * uvFactorX,
uvTag[1] * uvFactorY + anim_offset,
uvTag[2] * uvFactorX,
uvTag[3] * uvFactorY + anim_offset
]
for (var t = 0; t < 2; t++) {
if (rect[t] > rect[t+2]) {
[rect[t], rect[t+2]] = [rect[t+2], rect[t]]
}
rect[t] = Math.floor(Math.roundTo(rect[t], 2))
rect[t+2] = Math.ceil(Math.roundTo(rect[t+2], 2))
}
} else {
let min_x = texture.getUVWidth(), min_y = texture.getUVHeight(), max_x = 0, max_y = 0;
for (let vkey in uvTag) {
min_x = Math.min(min_x, uvTag[vkey][0]); max_x = Math.max(max_x, uvTag[vkey][0]);
min_y = Math.min(min_y, uvTag[vkey][1]); max_y = Math.max(max_y, uvTag[vkey][1]);
}
let current_face = Mesh.selected[0] && Mesh.selected[0].faces[Painter.current.face];
if (current_face) {
let island = Painter.getMeshUVIsland(Painter.current.face, current_face);
island.forEach(fkey => {
let face = Mesh.selected[0].faces[fkey];
if (!face) return;
for (let vkey in face.uv) {
min_x = Math.min(min_x, face.uv[vkey][0]); max_x = Math.max(max_x, face.uv[vkey][0]);
min_y = Math.min(min_y, face.uv[vkey][1]); max_y = Math.max(max_y, face.uv[vkey][1]);
}
})
}
rect = Painter.editing_area = [
Math.floor(min_x * uvFactorX),
Math.floor(min_y * uvFactorY) + anim_offset,
Math.ceil(max_x * uvFactorX),
Math.ceil(max_y * uvFactorY) + anim_offset
]
}
} else {
rect = Painter.editing_area = [0, 0, texture.img.naturalWidth, texture.img.naturalHeight]
}
Painter.current.uv_rects.set(uvTag, rect);
return rect;
},
useBrushlike(texture, x, y, event, uvTag, no_update, is_opposite) {
if (Painter.currentPixel[0] === x && Painter.currentPixel[1] === y) return;
Painter.currentPixel = [x, y];
Painter.brushChanges = true;
if (!is_opposite) {
UVEditor.vue.last_brush_position.V2_set(x, y);
}
let uvFactorX = texture.width / texture.getUVWidth();
let uvFactorY = texture.display_height / texture.getUVHeight();
if (Painter.mirror_painting && !is_opposite) {
let targets = Painter.getMirrorPaintTargets(texture, x, y, uvTag);
if (targets.length) {
let old_element = Painter.current.element;
let old_face = Painter.current.face;
targets.forEach(target => {
Painter.current.element = target.element;
Painter.current.face = target.face;
Painter.useBrushlike(texture, target.x, target.y, event, target.uv_tag, true, true);
})
Painter.current.element = old_element;
Painter.current.face = old_face;
}
}
let ctx = Painter.current.ctx;
ctx.save()
ctx.beginPath();
let rect = Painter.editing_area || Painter.setupRectFromFace(uvTag, texture);
var [w, h] = [rect[2] - rect[0], rect[3] - rect[1]]
ctx.rect(rect[0], rect[1], w, h)
if (Toolbox.selected.id === 'fill_tool') {
Painter.useFilltool(texture, ctx, x, y, { rect, uvFactorX, uvFactorY, w, h })
} else {
Painter.useBrush(texture, ctx, x, y, event)
}
Painter.editing_area = undefined;
},
useBrush(texture, ctx, x, y, event) {
let use_2nd_color = Keybinds.extra.paint_secondary_color.keybind.isTriggered(Painter.current.start_event ?? event);
var color = tinycolor(ColorPanel.get(use_2nd_color)).toRgb();
var size = BarItems.slider_brush_size.get();
let softness = BarItems.slider_brush_softness.get()/100;
let max_opacity = BarItems.slider_brush_opacity.get()/255;
let b_opacity = max_opacity;
let tool = Toolbox.selected;
let matrix_id = Painter.current.element
? (Painter.current.element.uuid + Painter.current.face)
: Painter.current.face;
if (TextureLayer.selected) {
TextureLayer.selected.expandTo([x-size+1, y-size+1], [x+size, y+size]);
}
ctx.clip()
if (Painter.current.element instanceof Mesh) {
let face = Painter.current.element.faces[Painter.current.face];
if (face && face.vertices.length > 2 && !Painter.current.face_matrices[matrix_id]) {
Painter.current.face_matrices[matrix_id] = face.getOccupationMatrix(true, [0, 0]);
let island = Painter.getMeshUVIsland(Painter.current.face, face);
for (let fkey of island) {
let face = Painter.current.element.faces[fkey];
face.getOccupationMatrix(true, [0, 0], Painter.current.face_matrices[matrix_id]);
let matrix_id2 = Painter.current.element ? (Painter.current.element.uuid + fkey) : fkey;
Painter.current.face_matrices[matrix_id2] = Painter.current.face_matrices[matrix_id];
}
}
}
let pressure;
let angle;
if (event.touches && event.touches[0] && event.touches[0].touchType == 'stylus' && event.touches[0].force !== undefined) {
// Stylus
var touch = event.touches[0];
pressure = touch.force;
angle = touch.altitudeAngle;
} else if (event.pressure >= 0 && event.pressure <= 1 && (event.pressure < 1 || event.pointerType != 'touch') && event.pressure !== 0.5) {
pressure = event.pressure;
angle = event.altitudeAngle;
}
if (pressure !== undefined) {
if (settings.brush_opacity_modifier.value == 'pressure' && pressure !== undefined) {
b_opacity = Math.clamp(b_opacity * Math.clamp(pressure*1.25, 0, 1), 0, 100);
} else if (settings.brush_opacity_modifier.value == 'tilt' && angle !== undefined) {
var modifier = Math.clamp(0.5 / (angle + 0.3), 0, 1);
b_opacity = Math.clamp(b_opacity * modifier, 0, 100);
}
if (settings.brush_size_modifier.value == 'pressure' && pressure !== undefined) {
size = Math.clamp(pressure * size * 2, 1, 20);
} else if (settings.brush_size_modifier.value == 'tilt' && angle !== undefined) {
size *= Math.clamp(1.5 / (angle + 0.3), 1, 4);
}
Painter.current.dynamic_brush_size = size;
}
if (tool.brush.draw) {
tool.brush.draw({ctx, x, y, size, softness, texture, event});
} else {
let face_matrix = settings.paint_side_restrict.value && Painter.current.face_matrices[matrix_id];
let run_per_pixel = (pxcolor, local_opacity, px, py) => {
if (face_matrix) {
if (!face_matrix[px] || !face_matrix[px][py % texture.display_height]) {
return pxcolor;
}
}
return tool.brush.changePixel(px, py, pxcolor, local_opacity, {color, opacity: b_opacity, max_opacity, ctx, x, y, size, softness, texture, event});
}
let shape = BarItems.brush_shape.value;
if (shape == 'square') {
Painter.editSquare(ctx, x, y, size, softness * 1.8, run_per_pixel);
} else if (shape == 'circle') {
Painter.editCircle(ctx, x, y, size, softness * 1.8, run_per_pixel);
}
}
ctx.restore();
},
useFilltool(texture, ctx, x, y, area) {
let color = tinycolor(ColorPanel.get()).toRgb();
let b_opacity = BarItems.slider_brush_opacity.get()/255;
let fill_mode = BarItems.fill_mode.get()
let blend_mode = BarItems.blend_mode.value;
let {element, offset} = Painter.current;
let {rect, uvFactorX, uvFactorY, w, h} = area;
if (Painter.erase_mode && (fill_mode === 'element' || fill_mode === 'face')) {
ctx.globalAlpha = b_opacity;
ctx.fillStyle = 'white';
ctx.globalCompositeOperation = 'destination-out';
} else {
ctx.fillStyle = tinycolor(ColorPanel.get()).setAlpha(b_opacity).toRgbString();
ctx.globalCompositeOperation = Painter.getBlendModeCompositeOperation();
if (Painter.lock_alpha) {
ctx.globalCompositeOperation = 'source-atop';
}
}
function paintElement(element) {
if (element.getTypeBehavior('cube_faces')) {
texture.selection.maskCanvas(ctx, offset);
ctx.beginPath();
for (var fkey in element.faces) {
var face = element.faces[fkey]
if (fill_mode === 'face' && fkey !== Painter.current.face) continue;
if (Painter.getTextureToEdit(face.getTexture()) === texture) {
var face_rect = getRectangle(
face.uv[0] * uvFactorX,
face.uv[1] * uvFactorY,
face.uv[2] * uvFactorX,
face.uv[3] * uvFactorY
)
let animation_offset = texture.currentFrame * texture.display_height;
ctx.rect(
Math.floor(face_rect.ax),
Math.floor(face_rect.ay) + animation_offset,
Math.ceil(face_rect.bx) - Math.floor(face_rect.ax),
Math.ceil(face_rect.by) - Math.floor(face_rect.ay)
)
}
}
ctx.fill()
ctx.restore();
} else if (element instanceof Mesh) {
// Rasterize every target face into a coverage mask, then emit merged
// horizontal runs once. Emitting one rect per pixel (or per row per face)
// explodes into large numbers of canvas subpaths that ctx.fill chokes on
// even at small sizes. The mask dedups overlapping faces and the run merge
// keeps the canvas path proportional to the filled shape at every size.
let canvas_w = ctx.canvas.width, canvas_h = ctx.canvas.height;
let mask = new Uint8Array(canvas_w * canvas_h);
let changes = false;
let bounds_min_x = canvas_w, bounds_min_y = canvas_h, bounds_max_x = -1, bounds_max_y = -1;
let mark_run = (x_start, x_end, y) => {
if (y < 0 || y >= canvas_h) return;
let a = x_start < 0 ? 0 : x_start;
let b = x_end >= canvas_w ? canvas_w - 1 : x_end;
if (a > b) return;
mask.fill(1, y * canvas_w + a, y * canvas_w + b + 1);
changes = true;
if (a < bounds_min_x) bounds_min_x = a;
if (b > bounds_max_x) bounds_max_x = b;
if (y < bounds_min_y) bounds_min_y = y;
if (y > bounds_max_y) bounds_max_y = y;
};
for (var fkey in element.faces) {
var face = element.faces[fkey];
if (fill_mode === 'face' && fkey !== Painter.current.face) continue;
if (face.vertices.length <= 2 || Painter.getTextureToEdit(face.getTexture()) !== texture) continue;
// Face UV polygon in texture-space pixels (same factors as getOccupationMatrix).
let face_texture = face.getTexture();
let factor_x = face_texture ? (face_texture.width / face_texture.getUVWidth()) : 1;
let factor_y = face_texture ? (face_texture.display_height / face_texture.getUVHeight()) : 1;
let vertices = [];
for (let vkey of face.getSortedVertices()) {
let uv = face.uv[vkey];
if (!uv) { vertices = null; break; }
vertices.push([uv[0] * factor_x, uv[1] * factor_y]);
}
// Convex faces rasterize by scanline (one span per row); concave or
// degenerate faces fall back to the exact per-pixel occupation matrix.
if (vertices && Painter.scanlineConvexPolygon(vertices, mark_run)) continue;
let matrix = Painter.current.face_matrices[element.uuid + fkey] || face.getOccupationMatrix(true, [0, 0]);
Painter.current.face_matrices[element.uuid + fkey] = matrix;
for (let x in matrix) {
let px = parseInt(x), column = matrix[x];
for (let y in column) {
if (column[y]) mark_run(px, px, parseInt(y));
}
}
}
if (changes) {
// Emit one rect per contiguous horizontal run of the mask (respecting an
// active selection), then fill once. Path size is O(runs), not O(area).
let selection = texture.selection;
let check_selection = selection && selection.override === null;
ctx.beginPath();
for (let y = bounds_min_y; y <= bounds_max_y; y++) {
let row = y * canvas_w, run = -1;
for (let x = bounds_min_x; x <= bounds_max_x + 1; x++) {
let filled = x <= bounds_max_x && mask[row + x] && (!check_selection || selection.allow(x, y));
if (filled) {
if (run < 0) run = x;
} else if (run >= 0) {
ctx.rect(run, y, x - run, 1);
run = -1;
}
}
}
ctx.fill();
}
}
}
if ((element?.getTypeBehavior('cube_faces') || element instanceof Mesh || element instanceof SplineMesh) && (fill_mode === 'element' || fill_mode === 'face')) {
paintElement(element);
} else if (fill_mode === 'face' || fill_mode === 'element' || fill_mode === 'selection') {
texture.selection.maskCanvas(ctx, offset);
ctx.fill();
ctx.restore();
} else if (fill_mode === 'selected_elements') {
for (let element of Outliner.selected) {
paintElement(element);
}
} else {
// Perf note: this branch handles both the "Same Color" (global) and
// "Color Connected" (flood fill) modes. It used to build a nested
// object map (map[x][y]) via two separate full-canvas scanCanvas
// passes (each doing its own getImageData/putImageData), and the
// flood fill pushed duplicate, unvisited-checked neighbor coordinates
// as new arrays. On large textures (e.g. 1200x1200+) that caused
// multi-second freezes (see JannisX11/blockbench#3487). This does the
// same work with a single getImageData/putImageData round trip and
// flat typed arrays instead of per-pixel objects/array allocations.
let selection = texture.selection;
let image_data = ctx.getImageData(x - offset[0], y - offset[1], 1, 1);
let target_r = image_data.data[0];
let target_g = image_data.data[1];
let target_b = image_data.data[2];
let target_a = image_data.data[3];
// Mirror scanCanvas's offset/clamping logic so selected texture
// layers behave exactly the same as before.
let local_x = rect[0];
let local_y = rect[1];
let scan_x = rect[0];
let scan_y = rect[1];
if (Painter.current.texture && Painter.current.texture.selected_layer) {
local_x -= Painter.current.texture.selected_layer.offset[0];
local_y -= Painter.current.texture.selected_layer.offset[1];
}
if (local_x < 0) { scan_x -= local_x; local_x = 0; }
if (local_y < 0) { scan_y -= local_y; local_y = 0; }
let scan_w = Math.min(w, ctx.canvas.width - local_x);
let scan_h = Math.min(h, ctx.canvas.height - local_y);
if (scan_w > 0 && scan_h > 0) {
let arr = ctx.getImageData(local_x, local_y, scan_w, scan_h);
let data = arr.data;
let pixel_count = scan_w * scan_h;
let matches = new Uint8Array(pixel_count);
for (let row = 0; row < scan_h; row++) {
let py = scan_y + row;
let row_offset = row * scan_w;
for (let col = 0; col < scan_w; col++) {
let i = (row_offset + col) * 4;
if (data[i] === target_r && data[i+1] === target_g && data[i+2] === target_b && data[i+3] === target_a) {
let px = scan_x + col;
if (selection.allow(px, py)) matches[row_offset + col] = 1;
}
}
}
let fill_flags = matches;
if (fill_mode === 'color_connected') {
fill_flags = new Uint8Array(pixel_count);
let start_col = x - scan_x;
let start_row = y - scan_y;
if (start_col >= 0 && start_col < scan_w && start_row >= 0 && start_row < scan_h) {
let start_idx = start_row * scan_w + start_col;
if (matches[start_idx]) {
fill_flags[start_idx] = 1;
let stack = [start_idx];
while (stack.length) {
let idx = stack.pop();
let col = idx % scan_w;
if (col > 0 && matches[idx-1] && !fill_flags[idx-1]) { fill_flags[idx-1] = 1; stack.push(idx-1); }
if (col < scan_w-1 && matches[idx+1] && !fill_flags[idx+1]) { fill_flags[idx+1] = 1; stack.push(idx+1); }
if (idx-scan_w >= 0 && matches[idx-scan_w] && !fill_flags[idx-scan_w]) { fill_flags[idx-scan_w] = 1; stack.push(idx-scan_w); }
if (idx+scan_w < pixel_count && matches[idx+scan_w] && !fill_flags[idx+scan_w]) { fill_flags[idx+scan_w] = 1; stack.push(idx+scan_w); }
}
}
}
}
let changes = false;
for (let j = 0; j < pixel_count; j++) {
if (!fill_flags[j]) continue;
let i = j * 4;
var pxcolor = {
r: data[i],
g: data[i+1],
b: data[i+2],
a: data[i+3]/255
}
var result_color = pxcolor;
if (!Painter.erase_mode) {
if (blend_mode == 'default') {
result_color = Painter.combineColors(pxcolor, color, b_opacity);
} else {
result_color = Painter.blendColors(pxcolor, color, b_opacity, blend_mode);
}
} else if (!Painter.lock_alpha) {
if (b_opacity == 1) {
result_color.r = result_color.g = result_color.b = result_color.a = 0;
} else {
result_color.a = Math.clamp(result_color.a * (1-b_opacity), 0, 1);
}
}
data[i] = result_color.r;
data[i+1] = result_color.g;
data[i+2] = result_color.b;
if (!Painter.lock_alpha) data[i+3] = result_color.a*255;
changes = true;
}
if (changes) {
ctx.putImageData(arr, local_x, local_y);
}
}
}
ctx.globalAlpha = 1.0;
ctx.globalCompositeOperation = 'source-over'
},
getMirrorPaintTargets(texture, x, y, uvTag) {
function getTargetWithOptions(symmetry_axes, local) {
let mirror_element = local ? Painter.current.element : Painter.getMirrorElement(Painter.current.element, symmetry_axes);
let offset_pixel_brush = Condition(Toolbox.selected.brush?.floor_coordinates) ? 1 : 0;
let even_brush_size = BarItems.slider_brush_size.get()%2 == 0 && Toolbox.selected.brush?.offset_even_radius && Condition(Toolbox.selected.brush?.floor_coordinates);
if (Toolbox.selected.id == 'gradient_tool') even_brush_size = true;
if (mirror_element instanceof Cube) {
let uvFactorX = 1 / texture.getUVWidth() * texture.img.naturalWidth;
let uvFactorY = 1 / texture.getUVHeight() * texture.img.naturalHeight;
let fkey = Painter.current.face;
let side_face = (symmetry_axes[0] && (fkey === 'west' || fkey === 'east'))
|| (symmetry_axes[1] && (fkey === 'up' || fkey === 'down'))
|| (symmetry_axes[2] && (fkey === 'south' || fkey === 'north'));
if (side_face && local !== null) fkey = CubeFace.opposite[fkey];
let face = mirror_element.faces[fkey];
if (side_face &&
uvTag[1] === face.uv[1] && uvTag[3] === face.uv[3] &&
Math.min(uvTag[0], uvTag[2]) === Math.min(face.uv[0], face.uv[2]) &&
symmetry_axes.filter(v => v).length == 1
//same face
) return;
//calculate original point
var point_on_uv = [
x - Math.min(uvTag[0], uvTag[2]) * uvFactorX,
y - Math.min(uvTag[1], uvTag[3]) * uvFactorY,
]
//calculate new point
let mirror_x = symmetry_axes[0] != symmetry_axes[2];
if (local === null) mirror_x = !mirror_x;
if (fkey === 'up' || fkey === 'down') mirror_x = !!symmetry_axes[0];
if ((face.uv[0] > face.uv[0+2] == uvTag[0] > uvTag[0+2]) == mirror_x) {
point_on_uv[0] = Math.max(face.uv[0], face.uv[0+2]) * uvFactorX - point_on_uv[0] - offset_pixel_brush;
if (even_brush_size) point_on_uv[0] += 1
} else {
point_on_uv[0] = Math.min(face.uv[0], face.uv[0+2]) * uvFactorX + point_on_uv[0];
}
let mirror_y = symmetry_axes[2] && (fkey === 'up' || fkey === 'down');
if ((face.uv[1] > face.uv[1+2] == uvTag[1] > uvTag[1+2]) != mirror_y) {
point_on_uv[1] = Math.min(face.uv[1], face.uv[1+2]) * uvFactorY + point_on_uv[1];
} else {
point_on_uv[1] = Math.max(face.uv[1], face.uv[1+2]) * uvFactorY - point_on_uv[1] - offset_pixel_brush;
}
if (offset_pixel_brush == 1) {
point_on_uv[0] = Math.round(point_on_uv[0]);
point_on_uv[1] = Math.round(point_on_uv[1]);
}
return {
element: mirror_element,
x: point_on_uv[0],
y: point_on_uv[1],
uv_tag: face.uv,
face: fkey
}
} else if (mirror_element instanceof Mesh) {
let mesh = mirror_element;
let clicked_face = Painter.current.element.faces[Painter.current.face];
let normal = clicked_face.getNormal(true);
let center = clicked_face.getCenter();
let ep = 0.5;
let en = 0.1;
let face;
let match_fkey;
for (let fkey in mesh.faces) {
let normal2 = mesh.faces[fkey].getNormal(true);
let center2 = mesh.faces[fkey].getCenter();
if (local !== null) {
if (symmetry_axes[0]) {normal2[0] *= -1; center2[0] *= -1;}
if (symmetry_axes[1]) {normal2[1] *= -1; center2[1] *= -1;}
if (symmetry_axes[2]) {normal2[2] *= -1; center2[2] *= -1;}
}
if (
Math.epsilon(normal[0], normal2[0], en) && Math.epsilon(normal[1], normal2[1], en) && Math.epsilon(normal[2], normal2[2], en) &&
Math.epsilon(center[0], center2[0], ep) && Math.epsilon(center[1], center2[1], ep) && Math.epsilon(center[2], center2[2], ep)
) {
face = mesh.faces[fkey];
match_fkey = fkey;
}
}
if (!face) return;
let source_uv = [
(even_brush_size ? x : x + 0.5) * (texture.getUVWidth() / texture.width),
(even_brush_size ? y : y + 0.5) * (texture.getUVHeight() / texture.height)
];
let point_on_uv;
if (local === null) {
let vector = clicked_face.UVToLocal(source_uv);
if (symmetry_axes[0]) vector.x *= -1;
if (symmetry_axes[1]) vector.y *= -1;
if (symmetry_axes[2]) vector.z *= -1;
let world_coord = Painter.current.element.mesh.localToWorld(vector);
if (symmetry_axes[0]) world_coord.x *= -1;
if (symmetry_axes[1]) world_coord.y *= -1;
if (symmetry_axes[2]) world_coord.z *= -1;
mesh.mesh.worldToLocal(world_coord);
point_on_uv = face.localToUV(world_coord);
} else if (local) {
let vector = clicked_face.UVToLocal(source_uv);
if (symmetry_axes[0]) vector.x *= -1;
if (symmetry_axes[1]) vector.y *= -1;
if (symmetry_axes[2]) vector.z *= -1;
point_on_uv = face.localToUV(vector);
} else {
let world_coord = Painter.current.element.mesh.localToWorld(clicked_face.UVToLocal(source_uv));
if (symmetry_axes[0]) world_coord.x *= -1;
if (symmetry_axes[1]) world_coord.y *= -1;
if (symmetry_axes[2]) world_coord.z *= -1;
mesh.mesh.worldToLocal(world_coord);
point_on_uv = face.localToUV(world_coord);
}
point_on_uv[0] /= texture.getUVWidth() / texture.width;
point_on_uv[1] /= texture.getUVHeight() / texture.height;
if (Condition(Toolbox.selected.brush?.floor_coordinates)) {
if (even_brush_size) {
point_on_uv = point_on_uv.map(v => Math.round(v))
} else {
point_on_uv = point_on_uv.map(v => Math.floor(v))
}
}
if (offset_pixel_brush == 1) {
point_on_uv[0] = Math.round(point_on_uv[0]);
point_on_uv[1] = Math.round(point_on_uv[1]);
}
return {
element: mesh,
x: point_on_uv[0],
y: point_on_uv[1],
uv_tag: face.uv,
face: match_fkey
}
}
}
let targets = [];
if (uvTag && Painter.current.element) {
let mirror_vectors = [[
Painter.mirror_painting_options.axis.x?1:0,
0, //Painter.mirror_painting_options.axis.y?1:0,
Painter.mirror_painting_options.axis.z?1:0
]];
if (mirror_vectors[0].filter(v => v).length == 3) {
mirror_vectors = [
[1,0,0], [0,1,0], [0,0,1],
[1,1,0], [0,1,1], [1,0,1],
[1,1,1]
]
} else if (mirror_vectors[0].equals([1, 1, 0])) {
mirror_vectors = [[1,0,0], [0,1,0], [1,1,0]];
} else if (mirror_vectors[0].equals([0, 1, 1])) {
mirror_vectors = [[0,1,0], [0,0,1], [0,1,1]];
} else if (mirror_vectors[0].equals([1, 0, 1])) {
mirror_vectors = [[1,0,0], [0,0,1], [1,0,1]];
}
mirror_vectors.forEach((mirror_vector, i) => {
if (Painter.mirror_painting_options.global) {
targets.push(getTargetWithOptions(mirror_vector, false));
}
if (Painter.mirror_painting_options.local) {
targets.push(getTargetWithOptions(mirror_vector, true));
}
if (Painter.mirror_painting_options.global && Painter.mirror_painting_options.local) {
targets.push(getTargetWithOptions(mirror_vector, null));
}
})
}
// 2D
if (Painter.mirror_painting_options.texture && !Painter.current.element) {
let offset = 0;
if (!Toolbox.selected.brush || Condition(Toolbox.selected.brush.floor_coordinates)) {
offset = BarItems.slider_brush_size.get()%2 == 0 && Toolbox.selected.brush?.offset_even_radius ? 0 : 1;
}
let center = Painter.mirror_painting_options.texture_center;
if (!center || (!center[0] && !center[1])) {
center = [texture.width/2, texture.display_height/2];
}
if (Painter.mirror_painting_options.axis.x) {
targets.push({
x: center[0]*2 - x - offset,
y: y
});
}
if (Painter.mirror_painting_options.axis.z) {
targets.push({
x: x,
y: center[1]*2 - y - offset
});
}
if (Painter.mirror_painting_options.axis.x && Painter.mirror_painting_options.axis.z) {
targets.push({
x: center[0]*2 - x - offset,
y: center[1]*2 - y - offset
});
}
}
// Texture animation
if (Painter.mirror_painting_options.texture_frames && Format.animated_textures && texture && texture.frameCount > 1) {
let spatial_targets = targets.slice();
for (let frame = 0; frame < texture.frameCount; frame++) {
if (frame == texture.currentFrame) continue;
targets.push({
element: Painter.current.element,
x,
y: y + (frame - texture.currentFrame) * texture.display_height,
face: Painter.current.face
});
spatial_targets.forEach(spatial => {