forked from Sprytile/Sprytile
-
Notifications
You must be signed in to change notification settings - Fork 5
/
sprytile_utils.py
2077 lines (1667 loc) · 71 KB
/
sprytile_utils.py
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 bpy
import bgl
import blf
import bmesh
import math
import sys
from bpy_extras import view3d_utils
from bpy_extras.io_utils import ImportHelper
from bpy.props import StringProperty
from bmesh.types import BMVert, BMEdge, BMFace
from mathutils import Matrix, Vector, Quaternion
from mathutils.geometry import intersect_line_plane, distance_point_to_plane
from mathutils.bvhtree import BVHTree
from bpy.path import abspath
from datetime import datetime
from os import path
import sprytile_modal
import sprytile_preview
import addon_updater_ops
def get_build_vertices(position, x_vector, y_vector, up_vector, right_vector):
"""Get the world position vertices for a new face, at the given position"""
x_dot = right_vector.dot(x_vector.normalized())
y_dot = up_vector.dot(y_vector.normalized())
x_positive = x_dot > 0
y_positive = y_dot > 0
# These are in world positions
vtx1 = position
vtx2 = position + y_vector
vtx3 = position + x_vector + y_vector
vtx4 = position + x_vector
# Quadrant II, IV
face_order = (vtx1, vtx2, vtx3, vtx4)
# Quadrant I, III
if x_positive == y_positive:
face_order = (vtx1, vtx4, vtx3, vtx2)
return face_order
def get_ortho2D_matrix(left, right, bottom, top):
rl = right - left
rl2 = right + left
tb = top - bottom
tb2 = top + bottom
return Matrix([(2.0 / rl, 0, 0, -(rl2 / rl)), (0, 2.0 / tb, 0, -(tb2 / tb)), (0, 0, -1, 0), (0, 0, 0, 1)])
def get_current_grid_vectors(scene, with_rotation=True):
"""Returns the current grid X/Y/Z vectors from scene data
:param scene: scene data
:param with_rotation: bool, rotate the grid vectors by sprytile_data
:return: up_vector, right_vector, normal_vector
"""
data_normal = scene.sprytile_data.paint_normal_vector
data_up_vector = scene.sprytile_data.paint_up_vector
normal_vector = Vector((data_normal[0], data_normal[1], data_normal[2]))
up_vector = Vector((data_up_vector[0], data_up_vector[1], data_up_vector[2]))
normal_vector.normalize()
up_vector.normalize()
right_vector = up_vector.cross(normal_vector)
if with_rotation:
rotation = Quaternion(-normal_vector, scene.sprytile_data.mesh_rotate)
up_vector = rotation @ up_vector
right_vector = rotation @ right_vector
return up_vector, right_vector, normal_vector
def grid_is_single_pixel(grid):
is_pixel = grid.grid[0] == 1 and grid.grid[1] == 1 and grid_no_spacing(grid)
return is_pixel
def grid_no_spacing(grid):
no_spacing = grid.padding[0] == 0 and grid.padding[0] == 0 and \
grid.margin[0] == 0 and grid.margin[1] == 0 and \
grid.margin[2] == 0 and grid.margin[3] == 0
return no_spacing
def get_grid_ids(context, grid, select_coords):
"""Convert an array of selection X/Y coordinates to grid ids"""
target_img = get_grid_texture(context.object, grid)
if target_img is None:
return None
row_size = math.ceil(target_img.size[0] / grid.grid[0])
grid_ids = []
for x, y in select_coords:
tile_id = (y * row_size) + x
grid_ids.append(tile_id)
return grid_ids
def get_grid_selection_coords(grid):
tile_sel = grid.tile_selection
selection_array = []
for y in range(tile_sel[3]):
for x in range(tile_sel[2]):
coord = (tile_sel[0] + x, tile_sel[1] + y)
selection_array.append(coord)
return selection_array
def get_grid_selection_ids(context, grid):
coords = get_grid_selection_coords(grid)
sel_size = (grid.tile_selection[2], grid.tile_selection[3])
grid_ids = get_grid_ids(context, grid, coords)
return coords, sel_size, grid_ids
def snap_vector_to_axis(vector, mirrored=False):
"""Snaps a vector to the closest world axis"""
norm_vector = vector.normalized()
x = Vector((1.0, 0.0, 0.0))
y = Vector((0.0, 1.0, 0.0))
z = Vector((0.0, 0.0, 1.0))
x_dot = 1 - abs(norm_vector.dot(x))
y_dot = 1 - abs(norm_vector.dot(y))
z_dot = 1 - abs(norm_vector.dot(z))
dot_array = [x_dot, y_dot, z_dot]
closest = min(dot_array)
if closest is dot_array[0]:
snapped_vector = x
elif closest is dot_array[1]:
snapped_vector = y
else:
snapped_vector = z
vector_dot = norm_vector.dot(snapped_vector)
if mirrored is False and vector_dot < 0:
snapped_vector *= -1
elif mirrored is True and vector_dot > 0:
snapped_vector *= -1
return snapped_vector
def get_grid_pos(position, grid_center, right_vector, up_vector, world_pixels, grid_x, grid_y, as_coord=False):
"""Snaps a world position to the given grid settings"""
position_vector = position - grid_center
pos_vector_normalized = position.normalized()
if not as_coord:
if right_vector.dot(pos_vector_normalized) < 0:
right_vector *= -1
if up_vector.dot(pos_vector_normalized) < 0:
up_vector *= -1
x_magnitude = position_vector.dot(right_vector)
y_magnitude = position_vector.dot(up_vector)
x_unit = grid_x / world_pixels
y_unit = grid_y / world_pixels
x_snap = math.floor(x_magnitude / x_unit)
y_snap = math.floor(y_magnitude / y_unit)
right_vector *= x_unit
up_vector *= y_unit
if as_coord:
return Vector((x_snap, y_snap)), right_vector, up_vector
grid_pos = grid_center + (right_vector * x_snap) + (up_vector * y_snap)
return grid_pos, right_vector, up_vector
def get_grid_right_up(right_vector, up_vector, world_pixels, grid_x, grid_y):
x_unit = grid_x / world_pixels
y_unit = grid_y / world_pixels
right_vector *= x_unit
up_vector *= y_unit
return right_vector, up_vector
def get_workplane_area(width, height):
offset_ids, offset_grid, coord_min, coord_max = get_grid_area(width, height)
return [coord_min[0] - 1, coord_min[1] - 1], coord_max
def get_grid_area(width, height, flip_x=False, flip_y=False):
"""
Get the grid and tile ID offset, for a given dimension
:param width:
:param height:
:param flip_x:
:param flip_y:
:return: offset_tile_ids, offset_grid
"""
offset_x = int(width/2)
offset_y = int(height/2)
if width % 2 == 0:
offset_x -= 1
if height % 2 == 0:
offset_y -= 1
offset_x *= -1
offset_y *= -1
offset_tile_ids = []
offset_grid = []
coords_min = [sys.maxsize, sys.maxsize]
coords_max = [-sys.maxsize, -sys.maxsize]
for y in range(height):
for x in range(width):
# Calculate tile offset
tile_offset = (width - 1 - x if flip_x else x,
height - 1 - y if flip_y else y)
offset_tile_ids.append(tile_offset)
# Calculate grid offset
grid_offset = (x + offset_x, y + offset_y)
coords_min[0] = min(grid_offset[0], coords_min[0])
coords_min[1] = min(grid_offset[1], coords_min[1])
coords_max[0] = max(grid_offset[0], coords_max[0])
coords_max[1] = max(grid_offset[1], coords_max[1])
offset_grid.append(grid_offset)
return offset_tile_ids, offset_grid, coords_min, coords_max
def raycast_grid(scene, context, up_vector, right_vector, plane_normal, ray_origin, ray_vector, as_coord=False):
"""
Raycast to a plane on the scene cursor, and return the grid snapped position
:param scene:
:param context:
:param up_vector:
:param right_vector:
:param plane_normal:
:param ray_origin:
:param ray_vector:
:param as_coord: If position should be returned as world position or grid coordinate
:return: grid_position, x_vector, y_vector, plane_pos
"""
plane_pos = intersect_line_plane(ray_origin, ray_origin + ray_vector, scene.cursor.location, plane_normal)
# Didn't hit the plane exit
if plane_pos is None:
return None, None, None, None
world_pixels = scene.sprytile_data.world_pixels
target_grid = get_grid(context, context.object.sprytile_gridid)
grid_x = target_grid.grid[0]
grid_y = target_grid.grid[1]
grid_position, x_vector, y_vector = get_grid_pos(
plane_pos, scene.cursor.location,
right_vector.copy(), up_vector.copy(),
world_pixels, grid_x, grid_y, as_coord
)
if x_vector.normalized().dot(right_vector) < 0:
x_vector *= -1
grid_position -= x_vector
if y_vector.normalized().dot(up_vector) < 0:
y_vector *= -1
grid_position -= y_vector
return grid_position, x_vector, y_vector, plane_pos
def get_grid_matrix(sprytile_grid):
"""Returns the transform matrix of a sprytile grid"""
offset_mtx = Matrix.Translation((sprytile_grid.offset[0], sprytile_grid.offset[1], 0))
rotate_mtx = Matrix.Rotation(sprytile_grid.rotate, 4, 'Z')
return offset_mtx @ rotate_mtx
def get_material_texture_node(mat):
"""
Returns the first image texture node applied to a material
:param mat: Material
:return: ShaderNodeImageTexImage or None
"""
if mat.node_tree is None:
return None
for node in mat.node_tree.nodes:
if node.bl_static_type == 'TEX_IMAGE':
return node
return None
def get_material_texture(mat):
"""
Returns the texture applied to a material
:param mat: Material
:return: Texture or None
"""
texture_img = get_material_texture_node(mat)
if texture_img:
return texture_img.image
else:
return None
def set_material_texture(mat, texture):
"""
Apply texture (if possible) to a material
:param mat: Material
:param mat: Texture image to apply
:return: True if successful
"""
texture_img = get_material_texture_node(mat)
if texture_img:
texture_img.image = texture
return True
else:
return False
def get_grid_material(sprytile_grid):
"""
Given the sprytile_grid, returns the corresponding material
:param sprytile_grid: the sprytile grid applied to the object
:return: Material or None
"""
mat_idx = bpy.data.materials.find(sprytile_grid.mat_id)
if mat_idx != -1 and bpy.data.materials[mat_idx] is not None:
return bpy.data.materials[mat_idx]
return None
def get_grid_texture(obj, sprytile_grid):
"""
Returns the texture applied to an object, given the sprytile_grid
:param obj: the Blender mesh object
:param sprytile_grid: the sprytile grid applied to the object
:return: Texture or None
"""
material = get_grid_material(sprytile_grid)
if material is None:
return None
return get_material_texture(material) or None
def has_material(obj, material):
"""
Checks if the given object has the given material
:param obj: the Blender mesh object
:param material: the material to search
:return: True or False
"""
for slot in obj.material_slots:
if slot.material == material:
return True
return False
def get_selected_grid(context):
"""
Returns the sprytile_grid currently selected
:param context: Blender tool context
:return: sprytile_grid or None
"""
obj = context.object
scene = context.scene
mat_list = scene.sprytile_mats
# The selected mesh object has the current sprytile_grid id
grid_id = obj.sprytile_gridid
return get_grid(context, grid_id)
def get_grid(context, grid_id):
"""
Returns the sprytile_grid with the given id
:param context: Blender tool context
:param grid_id: grid id
:return: sprytile_grid or None
"""
mat_list = context.scene.sprytile_mats
for mat_data in mat_list:
for grid in mat_data.grids:
if grid.id == grid_id:
return grid
return None
def get_highest_grid_id(context):
highest_id = -1
mat_list = context.scene.sprytile_mats
for mat_data in mat_list:
for grid in mat_data.grids:
highest_id = max(grid.id, highest_id)
return highest_id
def get_mat_data(context, mat_id):
mat_list = context.scene.sprytile_mats
for mat_data in mat_list:
if mat_data.mat_id == mat_id:
return mat_data
return None
def get_current_tool(context):
'''
Returns the active tool in edit mode
'''
cur_tool = context.workspace.tools.from_space_view3d_mode('EDIT_MESH', create=False).idname
return cur_tool
def get_paint_settings(sprytile_data):
'''
Returns the paint settings bitmask from a sprytile_data instance
:param sprytile_data: sprytile_data instance
:return: A bitmask representing the paint settings in the sprytile_data
'''
# Rotation and UV flip are always included
paint_settings = 0
# Flip x/y are toggles
paint_settings += (1 if sprytile_data.uv_flip_x else 0) << 9
paint_settings += (1 if sprytile_data.uv_flip_y else 0) << 8
# Rotation is encoded as 0-3 clockwise, bit shifted by 10
degree_rotation = round(math.degrees(sprytile_data.mesh_rotate), 0)
if degree_rotation < 0:
degree_rotation += 360
rot_val = 0
if degree_rotation <= 1:
rot_val = 0
elif degree_rotation <= 90:
rot_val = 3
elif degree_rotation <= 180:
rot_val = 2
elif degree_rotation <= 270:
rot_val = 1
paint_settings += rot_val << 10
if sprytile_data.paint_mode == 'MAKE_FACE':
paint_settings += 5 # Default center align
for x in range(4, 8): # All toggles on
paint_settings += 1 << x
if sprytile_data.paint_mode == 'PAINT':
if not "paint_align" in sprytile_data.keys():
sprytile_data["paint_align"] = 5
paint_settings += sprytile_data["paint_align"]
paint_settings += (1 if sprytile_data.paint_uv_snap else 0) << 7
paint_settings += (1 if sprytile_data.paint_edge_snap else 0) << 6
paint_settings += (1 if sprytile_data.paint_stretch_x else 0) << 5
paint_settings += (1 if sprytile_data.paint_stretch_y else 0) << 4
return paint_settings
def from_paint_settings(sprytile_data, paint_settings):
"""
Sets the paint settings of a sprytile_data using the paint settings bitmask
:param sprytile_data: sprytile_data instance to set
:param paint_settings: Painting settings bitmask
:return: None
"""
if paint_settings == 0:
return
align_value = paint_settings & 15 # First four bits
rot_value = (paint_settings & 3072) >> 10 # 11th and 12th bit, shifted back
rot_radian = 0
if rot_value == 1:
rot_radian = math.radians(270)
if rot_value == 2:
rot_radian = math.radians(180)
if rot_value == 3:
rot_radian = math.radians(90)
sprytile_data["paint_align"] = align_value
sprytile_data.mesh_rotate = rot_radian
sprytile_data.uv_flip_x = (paint_settings & 1 << 9) > 0
sprytile_data.uv_flip_y = (paint_settings & 1 << 8) > 0
sprytile_data.paint_uv_snap = (paint_settings & 1 << 7) > 0
sprytile_data.paint_edge_snap = (paint_settings & 1 << 6) > 0
sprytile_data.paint_stretch_x = (paint_settings & 1 << 5) > 0
sprytile_data.paint_stretch_y = (paint_settings & 1 << 4) > 0
def get_work_layer_data(sprytile_data):
"""
Returns the work layer bitmask from the given sprytile data
"""
# Bits 0-4 are reserved for storing layer numbers
# Bit 5 = Face is using decal mode
# Bit 6 = Face is using UV mode
# When face is using UV mode, there may be multiple
# UV layers, to find which layers it is using,
# Mask against bits 0-4
# This is only for 1 layer decals, figure out multi layer later
out_data = 0
if sprytile_data.work_layer != 'BASE':
out_data += (1 << 0)
if sprytile_data.work_layer_mode == 'MESH_DECAL':
out_data += (1 << 5)
else:
out_data += (1 << 6)
return out_data
def from_work_layer_data(sprytile_data, layer_data):
pass
def label_wrap(col, text, area="VIEW_3D", region_type="TOOL_PROPS", tab_str=" ", scale_y=0.55):
a_id = -1
r_id = -1
new_line = "\n"
tab = "\t"
tabbing = False
n_line = False
col.scale_y = scale_y
areas = bpy.context.screen.areas
for i, a in enumerate(areas):
if a.type == area:
a_id = i
reg = a.regions
for ir, r in enumerate(reg):
if r.type == region_type:
r_id = ir
if a_id < 0 or r_id < 0:
return
p_width = areas[a_id].regions[r_id].width
char_width = 7 # approximate width of each character
line_length = int(p_width / char_width)
last_space = line_length # current position of last space character in text
while last_space > 0:
split_point = line_length # where to split the text
if split_point > len(text):
split_point = len(text) - 1
cr = text.find(new_line, 0, len(text))
if (cr > 0) and (cr <= split_point):
n_line = True
last_space = cr # Position of new line symbol, if found
else:
tabp = text.find("\t", 0, split_point)
if tabp >= 0:
text = text.replace(tab, "", 1)
tabbing = True
n_line = False
last_space = text.rfind(" ", 0, split_point) # Position of last space character in text
if (last_space == -1) or len(text) <= line_length: # No more spaces found, or its the last line of text
last_space = len(text)
line = text[0:last_space]
if tabbing:
line = tab_str + line
col.label(text=line)
if n_line:
tabbing = False
text = text[last_space + 1:len(text)]
class UTIL_OP_SprytileAxisUpdate(bpy.types.Operator):
bl_idname = "sprytile.axis_update"
bl_label = "Update Sprytile Axis"
def execute(self, context):
return self.invoke(context, None)
def invoke(self, context, event):
# Given the normal mode, find the direction of paint_normal_vector, paint_up_vector
data = context.scene.sprytile_data
region = context.region
rv3d = context.region_data
# Get the view ray from center of screen
coord = Vector((int(region.width / 2), int(region.height / 2)))
view_vector = view3d_utils.region_2d_to_vector_3d(region, rv3d, coord)
# Get the up vector. The default scene view camera is pointed
# downward, with up on Y axis. Apply view rotation to get current up
view_up_vector = rv3d.view_rotation @ Vector((0.0, 1.0, 0.0))
view_vector = snap_vector_to_axis(view_vector, mirrored=True)
view_up_vector = snap_vector_to_axis(view_up_vector)
# implicit X
paint_normal = Vector((1.0, 0.0, 0.0))
if data.normal_mode == 'Y':
paint_normal = Vector((0.0, 1.0, 0.0))
elif data.normal_mode == 'Z':
paint_normal = Vector((0.0, 0.0, 1.0))
view_dot = paint_normal.dot(view_up_vector)
view_dot = abs(view_dot)
paint_up = view_up_vector
if view_dot > 0.9:
paint_up = view_vector
# print("View", view_vector, "View Up", view_up_vector)
# print("Axis update, view dot:", view_dot)
# print("mode", data.normal_mode, "paint normal", paint_normal, "paint up", paint_up)
data.paint_normal_vector = paint_normal
data.paint_up_vector = paint_up
return {'FINISHED'}
class UTIL_OP_SprytileGridAdd(bpy.types.Operator):
bl_idname = "sprytile.grid_add"
bl_label = "Add New Grid"
bl_description = "Add new tile grid"
def execute(self, context):
return self.invoke(context, None)
def invoke(self, context, event):
self.add_new_grid(context)
return {'FINISHED'}
@staticmethod
def add_new_grid(context):
mat_list = context.scene.sprytile_mats
target_mat = None
if len(mat_list) > 0:
target_mat = mat_list[0]
grid_id = context.object.sprytile_gridid
target_grid = get_grid(context, grid_id)
if target_grid is not None:
for mat in mat_list:
if mat.mat_id == target_grid.mat_id:
target_mat = mat
break
if target_mat is None:
return
grid_idx = -1
for idx, grid in enumerate(target_mat.grids):
if grid.id == grid_id:
grid_idx = idx
break
new_idx = len(target_mat.grids)
new_grid = target_mat.grids.add()
new_grid.mat_id = target_mat.mat_id
new_grid.id = get_highest_grid_id(context) + 1
if grid_idx > -1:
new_grid.grid = target_mat.grids[grid_idx].grid
target_mat.grids.move(new_idx, grid_idx + 1)
bpy.ops.sprytile.build_grid_list()
class UTIL_OP_SprytileGridRemove(bpy.types.Operator):
bl_idname = "sprytile.grid_remove"
bl_label = "Remove Grid"
bl_description = "Remove selected tile grid"
def execute(self, context):
return self.invoke(context, None)
def invoke(self, context, event):
self.delete_grid(context)
return {'FINISHED'}
@staticmethod
def delete_grid(context):
mat_list = context.scene.sprytile_mats
target_mat = None
if len(mat_list) > 0:
target_mat = mat_list[0]
grid_id = context.object.sprytile_gridid
target_grid = get_grid(context, grid_id)
if target_grid is not None:
for mat in mat_list:
if mat.mat_id == target_grid.mat_id:
target_mat = mat
break
if target_mat is None or len(target_mat.grids) <= 1:
return
grid_idx = -1
for idx, grid in enumerate(target_mat.grids):
if grid.id == grid_id:
grid_idx = idx
break
target_mat.grids.remove(grid_idx)
bpy.ops.sprytile.build_grid_list()
class UTIL_OP_SprytileGridCycle(bpy.types.Operator):
bl_idname = "sprytile.grid_cycle"
bl_label = "Cycle grid settings"
direction: bpy.props.IntProperty(default=1)
def execute(self, context):
return self.invoke(context, None)
def invoke(self, context, event):
self.cycle_grid(context)
return {'FINISHED'}
def cycle_grid(self, context):
obj = context.object
curr_grid = get_grid(context, obj.sprytile_gridid)
if curr_grid is None:
return
curr_mat = get_mat_data(context, curr_grid.mat_id)
if curr_mat is None:
return
idx = -1
for grid in curr_mat.grids:
idx += 1
if grid.id == curr_grid.id:
break
idx += self.direction
if idx < 0:
idx = len(curr_mat.grids)-1
if idx >= len(curr_mat.grids):
idx = 0
obj.sprytile_gridid = curr_mat.grids[idx].id
bpy.ops.sprytile.build_grid_list()
class UTIL_OP_SprytileStartTool(bpy.types.Operator):
bl_idname = "sprytile.start_tool"
bl_label = "Start Sprytile Paint"
mode: bpy.props.IntProperty(default=3)
def execute(self, context):
return self.invoke(context, None)
def invoke(self, context, event):
if self.mode is 0:
context.scene.sprytile_data.paint_mode = 'SET_NORMAL'
if self.mode is 1:
context.scene.sprytile_data.paint_mode = 'PAINT'
if self.mode is 2:
context.scene.sprytile_data.paint_mode = 'MAKE_FACE'
bpy.ops.sprytile.modal_tool('INVOKE_REGION_WIN')
return {'FINISHED'}
class UTIL_OP_SprytileGridMove(bpy.types.Operator):
bl_idname = "sprytile.grid_move"
bl_label = "Move Grid"
bl_description = "Move selected tile grid up or down"
direction : bpy.props.IntProperty(default=1)
def execute(self, context):
return self.invoke(context, None)
def invoke(self, context, event):
self.move_grid(context)
return {'FINISHED'}
def move_grid(self, context):
obj = context.object
curr_grid = get_grid(context, obj.sprytile_gridid)
if curr_grid is None:
return
curr_mat = get_mat_data(context, curr_grid.mat_id)
if curr_mat is None:
return
idx = -1
for grid in curr_mat.grids:
idx += 1
if grid.id == curr_grid.id:
break
old_idx = idx
idx = old_idx + self.direction
if idx < 0:
idx = len(curr_mat.grids)-1
if idx >= len(curr_mat.grids):
idx = 0
curr_mat.grids.move(old_idx, idx)
obj.sprytile_gridid = curr_mat.grids[idx].id
bpy.ops.sprytile.build_grid_list()
class UTIL_OP_SprytileNewMaterial(bpy.types.Operator):
bl_idname = "sprytile.add_new_material"
bl_label = "New Shadeless Material"
bl_description = "Create a new shadeless material"
@classmethod
def poll(cls, context):
return context.object is not None
def invoke(self, context, event):
obj = context.object
if obj.type != 'MESH':
return {'FINISHED'}
mat = bpy.data.materials.new(name="Material")
set_idx = len(obj.material_slots)
bpy.ops.object.material_slot_add()
obj.active_material_index = set_idx
obj.material_slots[set_idx].material = mat
bpy.ops.sprytile.material_setup('INVOKE_DEFAULT')
bpy.ops.sprytile.validate_grids('INVOKE_DEFAULT')
bpy.data.materials.update()
return {'FINISHED'}
class UTIL_OP_SprytileSetupMaterial(bpy.types.Operator):
bl_idname = "sprytile.material_setup"
bl_label = "Set Material to Shadeless"
bl_description = "Make current selected material shadeless, for pixel art texture purposes"
@classmethod
def poll(cls, context):
return context.object is not None
def execute(self, context):
return self.invoke(context, None)
def invoke(self, context, event):
obj = context.object
if obj.type != 'MESH' or len(obj.material_slots) == 0:
return {'FINISHED'}
mat = obj.material_slots[obj.active_material_index].material
# Make material equivalent to a shadeless transparent one in Blender 2.7
mat.use_nodes = True
mat.blend_method = 'CLIP'
# Get the material texture (if any) so we can keep it
mat_texture = get_material_texture(mat)
# Setup nodes
nodes = mat.node_tree.nodes
nodes.clear()
output_n = nodes.new(type = 'ShaderNodeOutputMaterial')
light_path_n = nodes.new(type = 'ShaderNodeLightPath')
transparent_n = nodes.new(type = 'ShaderNodeBsdfTransparent')
emission_n = nodes.new(type = 'ShaderNodeEmission')
mix_cam_ray_n = nodes.new(type = 'ShaderNodeMixShader')
mix_alpha_n = nodes.new(type = 'ShaderNodeMixShader')
texture_n = nodes.new(type = 'ShaderNodeTexImage')
# link
links = mat.node_tree.links
links.new(texture_n.outputs['Color'], emission_n.inputs['Color'])
links.new(texture_n.outputs['Alpha'], mix_alpha_n.inputs['Fac'])
links.new(transparent_n.outputs['BSDF'], mix_alpha_n.inputs[1])
links.new(transparent_n.outputs['BSDF'], mix_cam_ray_n.inputs[1])
links.new(emission_n.outputs['Emission'], mix_alpha_n.inputs[2])
links.new(mix_alpha_n.outputs['Shader'], mix_cam_ray_n.inputs[2])
links.new(light_path_n.outputs['Is Camera Ray'], mix_cam_ray_n.inputs['Fac'])
links.new(mix_cam_ray_n.outputs['Shader'], output_n.inputs['Surface'])
# reorder
output_n.location = (400, 0)
mix_cam_ray_n.location = (200, 0)
light_path_n.location = (0, 250)
mix_alpha_n.location = (0, -100)
transparent_n.location = (-200, -100)
emission_n.location = (-200, -200)
texture_n.location = (-500, 100)
if mat_texture:
texture_n.image = mat_texture
return {'FINISHED'}
class UTIL_OP_SprytileSetupViewport(bpy.types.Operator):
bl_idname = "sprytile.viewport_setup"
bl_label = "Setup Pixel Viewport"
bl_description = "Set optimal 3D viewport settings for pixel art"
def execute(self, context):
return self.invoke(context, None)
def invoke(self, context, event):
# Disable Eevee's TAA, which causes noticeable artefacts with pixel art
context.scene.eevee.taa_samples = 1
context.scene.eevee.use_taa_reprojection = False
# Set view transform to standard, for correct texture brightness
context.scene.view_settings.view_transform = 'Standard'
# Reflect changes
context.scene.update_tag()
for area in context.screen.areas:
area.tag_redraw()
return {'FINISHED'}
class UTIL_OP_SprytileLoadTileset(bpy.types.Operator, ImportHelper):
bl_idname = "sprytile.tileset_load"
bl_label = "Load Tileset"
bl_description = "Load a tileset into the current material"
# For some reason this full list doesn't really work,
# reordered the list to prioritize common file types
# filter_ext = "*" + ";*".join(bpy.path.extensions_image.sort())
filter_glob: bpy.props.StringProperty(
default="*.bmp;*.psd;*.hdr;*.rgba;*.jpg;*.png;*.tiff;*.tga;*.jpeg;*.jp2;*.rgb;*.dds;*.exr;*.psb;*.j2c;*.dpx;*.tif;*.tx;*.cin;*.pdd;*.sgi",
options={'HIDDEN'},
)
def execute(self, context):
if context.object.type != 'MESH':
return {'FINISHED'}
# Check object material count, if 0 create a new material before loading
if len(context.object.material_slots.items()) < 1:
bpy.ops.sprytile.add_new_material('INVOKE_DEFAULT')
UTIL_OP_SprytileLoadTileset.load_tileset_file(context, self.filepath)
return {'FINISHED'}
@staticmethod
def load_tileset_file(context, filepath):
obj = context.object
texture_name = filepath[filepath.rindex(path.sep) + 1:]
material_name = filepath[filepath.rindex(path.sep) + 1: filepath.rindex('.')]
bpy.ops.sprytile.material_setup()
target_mat = obj.material_slots[obj.active_material_index].material
target_mat.name = material_name
loaded_img = bpy.data.images.load(filepath)
set_material_texture(target_mat, loaded_img)
bpy.ops.sprytile.texture_setup('INVOKE_DEFAULT')
bpy.ops.sprytile.validate_grids('INVOKE_DEFAULT')
bpy.data.textures.update()
class UTIL_OP_SprytileNewTileset(bpy.types.Operator, ImportHelper):
bl_idname = "sprytile.tileset_new"
bl_label = "Add Tileset"
bl_description = "Create a new material and load another tileset"
# For some reason this full list doesn't really work,
# reordered the list to prioritize common file types
# filter_ext = "*" + ";*".join(bpy.path.extensions_image.sort())
filter_glob: bpy.props.StringProperty(
default="*.bmp;*.psd;*.hdr;*.rgba;*.jpg;*.png;*.tiff;*.tga;*.jpeg;*.jp2;*.rgb;*.dds;*.exr;*.psb;*.j2c;*.dpx;*.tif;*.tx;*.cin;*.pdd;*.sgi",
options={'HIDDEN'},
)
def execute(self, context):
if context.object.type != 'MESH':
return {'FINISHED'}
bpy.ops.sprytile.add_new_material('INVOKE_DEFAULT')
UTIL_OP_SprytileLoadTileset.load_tileset_file(context, self.filepath)
return {'FINISHED'}
class UTIL_OP_SprytileSetupTexture(bpy.types.Operator):
bl_idname = "sprytile.texture_setup"
bl_label = "Setup Pixel Texture"
bl_description = "Change texture settings for crunchy pixelart style"
def execute(self, context):
return self.invoke(context, None)
def invoke(self, context, event):
self.setup_tex(context)
return {'FINISHED'}