to the workers of the world
[carveJwlIkooP6JGAAIwe30JlM.git] / blender_export.py
1 import bpy, math, gpu, os
2 import cProfile
3 from ctypes import *
4 from mathutils import *
5 from gpu_extras.batch import batch_for_shader
6
7 bl_info = {
8 "name":"Skaterift .mdl exporter",
9 "author": "Harry Godden (hgn)",
10 "version": (0,2),
11 "blender":(3,1,0),
12 "location":"Export",
13 "description":"",
14 "warning":"",
15 "wiki_url":"",
16 "category":"Import/Export",
17 }
18
19 class mdl_vert(Structure): # 48 bytes. Quite large. Could compress
20 #{ # the normals and uvs to i16s. Not an
21 _pack_ = 1 # real issue, yet.
22 _fields_ = [("co",c_float*3),
23 ("norm",c_float*3),
24 ("uv",c_float*2),
25 ("colour",c_uint8*4),
26 ("weights",c_uint16*4),
27 ("groups",c_uint8*4)]
28 #}
29
30 class mdl_transform(Structure):
31 #{
32 _fields_ = [("co",c_float*3),
33 ( "s",c_float*3),
34 ( "q",c_float*4)]
35 #}
36
37 class mdl_submesh(Structure):
38 #{
39 _fields_ = [("indice_start",c_uint32),
40 ("indice_count",c_uint32),
41 ("vertex_start",c_uint32),
42 ("vertex_count",c_uint32),
43 ("bbx",(c_float*3)*2),
44 ("material_id",c_uint32)] # index into the material array
45 #}
46
47 class mdl_material(Structure):
48 #{
49 _fields_ = [("pstr_name",c_uint32),
50 ("shader",c_uint32),
51 ("flags",c_uint32),
52 ("surface_prop",c_uint32),
53 ("colour",c_float*4),
54 ("colour1",c_float*4),
55 ("tex_diffuse",c_uint32),
56 ("tex_none0",c_uint32),
57 ("tex_none1",c_uint32)]
58 #}
59
60 class mdl_bone(Structure):
61 #{
62 _fields_ = [("co",c_float*3),("end",c_float*3),
63 ("parent",c_uint32),
64 ("collider",c_uint32),
65 ("ik_target",c_uint32),
66 ("ik_pole",c_uint32),
67 ("flags",c_uint32),
68 ("pstr_name",c_uint32),
69 ("hitbox",(c_float*3)*2),
70 ("conevx",c_float*3),("conevy",c_float*3),("coneva",c_float*3),
71 ("conet",c_float)]
72 #}
73
74 class mdl_armature(Structure):
75 #{
76 _fields_ = [("transform",mdl_transform),
77 ("bone_start",c_uint32),
78 ("bone_count",c_uint32),
79 ("anim_start",c_uint32),
80 ("anim_count",c_uint32)]
81 #}
82
83 class mdl_animation(Structure):
84 #{
85 _fields_ = [("pstr_name",c_uint32),
86 ("length",c_uint32),
87 ("rate",c_float),
88 ("keyframe_start",c_uint32)]
89 #}
90
91 class mdl_mesh(Structure):
92 #{
93 _fields_ = [("transform",mdl_transform),
94 ("submesh_start",c_uint32),
95 ("submesh_count",c_uint32),
96 ("pstr_name",c_uint32),
97 ("flags",c_uint32),
98 ("armature_id",c_uint32)]
99 #}
100
101 class mdl_file(Structure):
102 #{
103 _fields_ = [("path",c_uint32),
104 ("pack_offset",c_uint32),
105 ("pack_size",c_uint32)]
106 #}
107
108 class mdl_texture(Structure):
109 #{
110 _fields_ = [("file",mdl_file),
111 ("type",c_uint32)]
112 #}
113
114 class mdl_array(Structure):
115 #{
116 _fields_ = [("file_offset",c_uint32),
117 ("item_count",c_uint32),
118 ("item_size",c_uint32),
119 ("name",c_byte*16)]
120 #}
121
122 class mdl_header(Structure):
123 #{
124 _fields_ = [("version",c_uint32),
125 ("arrays",mdl_array)]
126 #}
127
128 class ent_spawn(Structure):
129 #{
130 _fields_ = [("transform",mdl_transform),
131 ("pstr_name",c_uint32)]
132 #}
133
134 class ent_light(Structure):
135 #{
136 _fields_ = [("transform",mdl_transform),
137 ("daytime",c_uint32),
138 ("type",c_uint32),
139 ("colour",c_float*4),
140 ("angle",c_float),
141 ("range",c_float),
142 ("inverse_world",(c_float*3)*4), # Runtime
143 ("angle_sin_cos",(c_float*2))] # Runtime
144 #}
145
146 class version_refcount_union(Union):
147 #{
148 _fields_ = [("timing_version",c_uint32),
149 ("ref_count",c_uint8)]
150 #}
151
152 class ent_gate(Structure):
153 #{
154 _fields_ = [("type",c_uint32),
155 ("target", c_uint32),
156 ("dimensions", c_float*3),
157 ("co", (c_float*3)*2),
158 ("q", (c_float*4)*2),
159 ("to_world",(c_float*3)*4),
160 ("transport",(c_float*3)*4),
161 ("_anonymous_union",version_refcount_union),
162 ("timing_time",c_double),
163 ("routes",c_uint16*4)]
164 #}
165
166 class ent_route_node(Structure):
167 #{
168 _fields_ = [("co",c_float*3),
169 ("ref_count",c_uint8),
170 ("ref_total",c_uint8)]
171 #}
172
173 class ent_path_index(Structure):
174 #{
175 _fields_ = [("index",c_uint16)]
176 #}
177
178 class ent_checkpoint(Structure):
179 #{
180 _fields_ = [("gate_index",c_uint16),
181 ("path_start",c_uint16),
182 ("path_count",c_uint16)]
183 #}
184
185 class ent_route(Structure):
186 #{
187 _fields_ = [("transform",mdl_transform),
188 ("pstr_name",c_uint32),
189 ("checkpoints_start",c_uint16),
190 ("checkpoints_count",c_uint16),
191 ("colour",c_float*4),
192 ("active",c_uint32), #runtime
193 ("factive",c_float),
194 ("board_transform",(c_float*3)*4),
195 ("sm",mdl_submesh),
196 ("latest_pass",c_double)]
197 #}
198
199 def obj_ent_type( obj ):
200 #{
201 if obj.type == 'ARMATURE': return 'mdl_armature'
202 elif obj.type == 'LIGHT': return 'ent_light'
203 else: return obj.SR_data.ent_type
204 #}
205
206 def sr_filter_ent_type( obj, ent_type ):
207 #{
208 if obj == bpy.context.active_object: return False
209
210 for c0 in obj.users_collection:#{
211 for c1 in bpy.context.active_object.users_collection:#{
212 if c0 == c1:#{
213 return ent_type == obj_ent_type( obj )
214 #}
215 #}
216 #}
217
218 return False
219 #}
220
221 def compile_obj_transform( obj, transform ):
222 #{
223 co = obj.matrix_world @ Vector((0,0,0))
224 q = obj.matrix_local.to_quaternion()
225 s = obj.scale
226
227 # Setup transform
228 #
229 transform.co[0] = co[0]
230 transform.co[1] = co[2]
231 transform.co[2] = -co[1]
232 transform.q[0] = q[1]
233 transform.q[1] = q[3]
234 transform.q[2] = -q[2]
235 transform.q[3] = q[0]
236 transform.s[0] = s[0]
237 transform.s[1] = s[2]
238 transform.s[2] = s[1]
239 #}
240
241 def int_align_to( v, align ):
242 #{
243 while(v%align)!=0: v += 1
244 return v
245 #}
246
247 def bytearray_align_to( buffer, align, w=b'\xaa' ):
248 #{
249 while (len(buffer) % align) != 0: buffer.extend(w)
250 return buffer
251 #}
252
253 def bytearray_print_hex( s, w=16 ):
254 #{
255 for r in range((len(s)+(w-1))//w):#{
256 i0=(r+0)*w
257 i1=min((r+1)*w,len(s))
258 print( F'{r*w:06x}| \x1B[31m', end='')
259 print( F"{' '.join('{:02x}'.format(x) for x in s[i0:i1]):<48}",end='' )
260 print( "\x1B[0m", end='')
261 print( ''.join(chr(x) if (x>=33 and x<=126) else '.' for x in s[i0:i1] ) )
262 #}
263 #}
264
265 def sr_compile_string( s ):
266 #{
267 if s in sr_compile.string_cache: return sr_compile.string_cache[s]
268
269 index = len( sr_compile.string_data )
270 sr_compile.string_cache[s] = index
271 sr_compile.string_data.extend( s.encode('utf-8') )
272 sr_compile.string_data.extend( b'\0' )
273
274 bytearray_align_to( sr_compile.string_data, 4 )
275 return index
276 #}
277
278 def material_tex_image(v):
279 #{
280 return {
281 "Image Texture":
282 {
283 "image": F"{v}"
284 }
285 }
286 #}
287
288 cxr_graph_mapping = \
289 {
290 # Default shader setup
291 "Principled BSDF":
292 {
293 "Base Color":
294 {
295 "Image Texture":
296 {
297 "image": "tex_diffuse"
298 },
299 "Mix":
300 {
301 "A": material_tex_image("tex_diffuse"),
302 "B": material_tex_image("tex_decal")
303 },
304 },
305 "Normal":
306 {
307 "Normal Map":
308 {
309 "Color": material_tex_image("tex_normal")
310 }
311 }
312 }
313 }
314
315 # https://harrygodden.com/git/?p=convexer.git;a=blob;f=__init__.py;#l1164
316 #
317 def material_info(mat):
318 #{
319 info = {}
320
321 # Using the cxr_graph_mapping as a reference, go through the shader
322 # graph and gather all $props from it.
323 #
324 def _graph_read( node_def, node=None, depth=0 ):#{
325 nonlocal mat
326 nonlocal info
327
328 # Find rootnodes
329 #
330 if node == None:#{
331 _graph_read.extracted = []
332
333 for node_idname in node_def:#{
334 for n in mat.node_tree.nodes:#{
335 if n.name == node_idname:#{
336 node_def = node_def[node_idname]
337 node = n
338 break
339 #}
340 #}
341 #}
342 #}
343
344 for link in node_def:#{
345 link_def = node_def[link]
346
347 if isinstance( link_def, dict ):#{
348 node_link = None
349 for x in node.inputs:#{
350 if isinstance( x, bpy.types.NodeSocketColor ):#{
351 if link == x.name:#{
352 node_link = x
353 break
354 #}
355 #}
356 #}
357
358 if node_link and node_link.is_linked:#{
359 # look for definitions for the connected node type
360 #
361 from_node = node_link.links[0].from_node
362
363 node_name = from_node.name.split('.')[0]
364 if node_name in link_def:#{
365 from_node_def = link_def[ node_name ]
366
367 _graph_read( from_node_def, from_node, depth+1 )
368 #}
369
370 # No definition! :(
371 # TODO: Make a warning for this?
372 #}
373 else:#{
374 if "default" in link_def:#{
375 prop = link_def['default']
376 info[prop] = node_link.default_value
377 #}
378 #}
379 #}
380 else:#{
381 prop = link_def
382 info[prop] = getattr( node, link )
383 #}
384 #}
385 #}
386
387 _graph_read( cxr_graph_mapping )
388 return info
389 #}
390
391 def sr_pack_file( file, path, data ):
392 #{
393 file.path = sr_compile_string( path )
394 file.pack_offset = len( sr_compile.pack_data )
395 file.pack_size = len( data )
396
397 sr_compile.pack_data.extend( data )
398 bytearray_align_to( sr_compile.pack_data, 16 )
399 #}
400
401 def sr_compile_texture( img ):
402 #{
403 if img == None:
404 return 0
405
406 name = os.path.splitext( img.name )[0]
407
408 if name in sr_compile.texture_cache:
409 return sr_compile.texture_cache[name]
410
411 texture_index = (len(sr_compile.texture_data)//sizeof(mdl_texture)) +1
412
413 tex = mdl_texture()
414 tex.type = 0
415
416 if sr_compile.pack_textures:#{
417 filedata = qoi_encode( img )
418 sr_pack_file( tex.file, name, filedata )
419 #}
420
421 sr_compile.texture_cache[name] = texture_index
422 sr_compile.texture_data.extend( bytearray(tex) )
423 return texture_index
424 #}
425
426 def sr_compile_material( mat ):
427 #{
428 if mat == None:
429 return 0
430 if mat.name in sr_compile.material_cache:
431 return sr_compile.material_cache[mat.name]
432
433 index = (len(sr_compile.material_data)//sizeof(mdl_material))+1
434 sr_compile.material_cache[mat.name] = index
435
436 m = mdl_material()
437 m.pstr_name = sr_compile_string( mat.name )
438
439 flags = 0x00
440 if mat.SR_data.collision:#{
441 flags |= 0x2
442 if mat.SR_data.skate_surface: flags |= 0x1
443 if mat.SR_data.grind_surface: flags |= (0x8|0x1)
444 #}
445
446 if mat.SR_data.grow_grass: flags |= 0x4
447 m.flags = flags
448
449 m.surface_prop = int(mat.SR_data.surface_prop)
450
451 if mat.SR_data.shader == 'standard': m.shader = 0
452 if mat.SR_data.shader == 'standard_cutout': m.shader = 1
453 if mat.SR_data.shader == 'terrain_blend':#{
454 m.shader = 2
455
456 m.colour[0] = pow( mat.SR_data.sand_colour[0], 1.0/2.2 )
457 m.colour[1] = pow( mat.SR_data.sand_colour[1], 1.0/2.2 )
458 m.colour[2] = pow( mat.SR_data.sand_colour[2], 1.0/2.2 )
459 m.colour[3] = 1.0
460
461 m.colour1[0] = mat.SR_data.blend_offset[0]
462 m.colour1[1] = mat.SR_data.blend_offset[1]
463 #}
464
465 if mat.SR_data.shader == 'vertex_blend':#{
466 m.shader = 3
467
468 m.colour1[0] = mat.SR_data.blend_offset[0]
469 m.colour1[1] = mat.SR_data.blend_offset[1]
470 #}
471
472 if mat.SR_data.shader == 'water':#{
473 m.shader = 4
474
475 m.colour[0] = pow( mat.SR_data.shore_colour[0], 1.0/2.2 )
476 m.colour[1] = pow( mat.SR_data.shore_colour[1], 1.0/2.2 )
477 m.colour[2] = pow( mat.SR_data.shore_colour[2], 1.0/2.2 )
478 m.colour[3] = 1.0
479 m.colour1[0] = pow( mat.SR_data.ocean_colour[0], 1.0/2.2 )
480 m.colour1[1] = pow( mat.SR_data.ocean_colour[1], 1.0/2.2 )
481 m.colour1[2] = pow( mat.SR_data.ocean_colour[2], 1.0/2.2 )
482 m.colour1[3] = 1.0
483 #}
484
485 inf = material_info( mat )
486
487 if mat.SR_data.shader == 'standard' or \
488 mat.SR_data.shader == 'standard_cutout' or \
489 mat.SR_data.shader == 'terrain_blend' or \
490 mat.SR_data.shader == 'vertex_blend':
491 #{
492 if 'tex_diffuse' in inf:
493 m.tex_diffuse = sr_compile_texture(inf['tex_diffuse'])
494 #}
495
496 sr_compile.material_data.extend( bytearray(m) )
497 return index
498 #}
499
500 def sr_armature_bones( armature ):
501 #{
502 def _recurse_bone( b ):
503 #{
504 yield b
505 for c in b.children: yield from _recurse_bone( c )
506 #}
507
508 for b in armature.data.bones:
509 if not b.parent:
510 yield from _recurse_bone( b )
511 #}
512
513 def sr_compile_mesh( obj ):
514 #{
515 node=mdl_mesh()
516 compile_obj_transform(obj, node.transform)
517 node.pstr_name = sr_compile_string(obj.name)
518 node.flags = 0
519
520 can_use_cache = True
521 armature = None
522
523 for mod in obj.modifiers:#{
524 if mod.type == 'DATA_TRANSFER' or mod.type == 'SHRINKWRAP' or \
525 mod.type == 'BOOLEAN' or mod.type == 'CURVE' or \
526 mod.type == 'ARRAY':
527 #{
528 can_use_cache = False
529 #}
530
531 if mod.type == 'ARMATURE': #{
532 node.flags = 1
533 armature = mod.object
534 rig_weight_groups = \
535 ['0 [ROOT]']+[_.name for _ in sr_armature_bones(mod.object)]
536 node.armature_id = sr_compile.entity_ids[armature.name]
537
538 POSE_OR_REST_CACHE = armature.data.pose_position
539 armature.data.pose_position = 'REST'
540 #}
541 #}
542
543 # Check the cache first
544 #
545 if can_use_cache and (obj.data.name in sr_compile.mesh_cache):#{
546 ref = sr_compile.mesh_cache[obj.data.name]
547 node.submesh_start = ref[0]
548 node.submesh_count = ref[1]
549 sr_compile.mesh_data.extend(bytearray(node))
550 return
551 #}
552
553 # Compile a whole new mesh
554 #
555 node.submesh_start = len(sr_compile.submesh_data)//sizeof(mdl_submesh)
556 node.submesh_count = 0
557
558 dgraph = bpy.context.evaluated_depsgraph_get()
559 data = obj.evaluated_get(dgraph).data
560 data.calc_loop_triangles()
561 data.calc_normals_split()
562
563 # Mesh is split into submeshes based on their material
564 #
565 mat_list = data.materials if len(data.materials) > 0 else [None]
566 for material_id, mat in enumerate(mat_list): #{
567 mref = {}
568
569 sm = mdl_submesh()
570 sm.indice_start = len(sr_compile.indice_data)//sizeof(c_uint32)
571 sm.vertex_start = len(sr_compile.vertex_data)//sizeof(mdl_vert)
572 sm.vertex_count = 0
573 sm.indice_count = 0
574 sm.material_id = sr_compile_material( mat )
575
576 INF=99999999.99999999
577 for i in range(3):#{
578 sm.bbx[0][i] = INF
579 sm.bbx[1][i] = -INF
580 #}
581
582 # Keep a reference to very very very similar vertices
583 # i have no idea how to speed it up.
584 #
585 vertex_reference = {}
586
587 # Write the vertex / indice data
588 #
589 for tri_index, tri in enumerate(data.loop_triangles):#{
590 if tri.material_index != material_id:
591 continue
592
593 for j in range(3):#{
594 vert = data.vertices[tri.vertices[j]]
595 li = tri.loops[j]
596 vi = data.loops[li].vertex_index
597
598 # Gather vertex information
599 #
600 co = vert.co
601 norm = data.loops[li].normal
602 uv = (0,0)
603 colour = (255,255,255,255)
604 groups = [0,0,0,0]
605 weights = [0,0,0,0]
606
607 # Uvs
608 #
609 if data.uv_layers:
610 uv = data.uv_layers.active.data[li].uv
611
612 # Vertex Colours
613 #
614 if data.vertex_colors:#{
615 colour = data.vertex_colors.active.data[li].color
616 colour = (int(colour[0]*255.0),\
617 int(colour[1]*255.0),\
618 int(colour[2]*255.0),\
619 int(colour[3]*255.0))
620 #}
621
622 # Weight groups: truncates to the 3 with the most influence. The
623 # fourth bone ID is never used by the shader so it
624 # is always 0
625 #
626 if armature:#{
627 src_groups = [_ for _ in data.vertices[vi].groups \
628 if obj.vertex_groups[_.group].name in \
629 rig_weight_groups ]
630
631 weight_groups = sorted( src_groups, key = \
632 lambda a: a.weight, reverse=True )
633 tot = 0.0
634 for ml in range(3):#{
635 if len(weight_groups) > ml:#{
636 g = weight_groups[ml]
637 name = obj.vertex_groups[g.group].name
638 weight = g.weight
639 weights[ml] = weight
640 groups[ml] = rig_weight_groups.index(name)
641 tot += weight
642 #}
643 #}
644
645 if len(weight_groups) > 0:#{
646 inv_norm = (1.0/tot) * 65535.0
647 for ml in range(3):#{
648 weights[ml] = int( weights[ml] * inv_norm )
649 weights[ml] = min( weights[ml], 65535 )
650 weights[ml] = max( weights[ml], 0 )
651 #}
652 #}
653 #}
654 else:#{
655 li1 = tri.loops[(j+1)%3]
656 vi1 = data.loops[li1].vertex_index
657 e0 = data.edges[ data.loops[li].edge_index ]
658
659 if e0.use_freestyle_mark and \
660 ((e0.vertices[0] == vi and e0.vertices[1] == vi1) or \
661 (e0.vertices[0] == vi1 and e0.vertices[1] == vi)):
662 #{
663 weights[0] = 1
664 #}
665 #}
666
667 TOLERENCE = float(10**4)
668 key = (int(co[0]*TOLERENCE+0.5),
669 int(co[1]*TOLERENCE+0.5),
670 int(co[2]*TOLERENCE+0.5),
671 int(norm[0]*TOLERENCE+0.5),
672 int(norm[1]*TOLERENCE+0.5),
673 int(norm[2]*TOLERENCE+0.5),
674 int(uv[0]*TOLERENCE+0.5),
675 int(uv[1]*TOLERENCE+0.5),
676 colour[0], # these guys are already quantized
677 colour[1], # .
678 colour[2], # .
679 colour[3], # .
680 weights[0], # v
681 weights[1],
682 weights[2],
683 weights[3],
684 groups[0],
685 groups[1],
686 groups[2],
687 groups[3])
688
689 if key in vertex_reference:
690 index = vertex_reference[key]
691 else:#{
692 index = bytearray(c_uint32(sm.vertex_count))
693 sm.vertex_count+=1
694
695 vertex_reference[key] = index
696 v = mdl_vert()
697 v.co[0] = co[0]
698 v.co[1] = co[2]
699 v.co[2] = -co[1]
700 v.norm[0] = norm[0]
701 v.norm[1] = norm[2]
702 v.norm[2] = -norm[1]
703 v.uv[0] = uv[0]
704 v.uv[1] = uv[1]
705 v.colour[0] = colour[0]
706 v.colour[1] = colour[1]
707 v.colour[2] = colour[2]
708 v.colour[3] = colour[3]
709 v.weights[0] = weights[0]
710 v.weights[1] = weights[1]
711 v.weights[2] = weights[2]
712 v.weights[3] = weights[3]
713 v.groups[0] = groups[0]
714 v.groups[1] = groups[1]
715 v.groups[2] = groups[2]
716 v.groups[3] = groups[3]
717
718 for i in range(3):#{
719 sm.bbx[0][i] = min( sm.bbx[0][i], v.co[i] )
720 sm.bbx[1][i] = max( sm.bbx[1][i], v.co[i] )
721 #}
722
723 sr_compile.vertex_data.extend(bytearray(v))
724 #}
725
726 sm.indice_count += 1
727 sr_compile.indice_data.extend( index )
728 #}
729 #}
730
731 # Make sure bounding box isn't -inf -> inf if no vertices
732 #
733 if sm.vertex_count == 0:
734 for j in range(2):
735 for i in range(3):
736 sm.bbx[j][i] = 0
737
738 # Add submesh to encoder
739 #
740 sr_compile.submesh_data.extend( bytearray(sm) )
741 node.submesh_count += 1
742 #}
743
744 if armature:#{
745 armature.data.pose_position = POSE_OR_REST_CACHE
746 #}
747
748 # Save a reference to this node since we want to reuse the submesh indices
749 # later.
750 sr_compile.mesh_cache[obj.data.name]=(node.submesh_start,node.submesh_count)
751 sr_compile.mesh_data.extend(bytearray(node))
752 #}
753
754 def sr_compile_armature( obj ):
755 #{
756 node = mdl_armature()
757 node.bone_start = len(sr_compile.bone_data)//sizeof(mdl_bone)
758 node.bone_count = 0
759 node.anim_start = len(sr_compile.anim_data)//sizeof(mdl_animation)
760 node.anim_count = 0
761
762 bones = [_ for _ in sr_armature_bones(obj)]
763 bones_names = [None]+[_.name for _ in bones]
764
765 for b in bones:#{
766 bone = mdl_bone()
767 if b.use_deform: bone.flags = 0x1
768 if b.parent: bone.parent = bones_names.index(b.parent.name)
769
770 bone.collider = int(b.SR_data.collider)
771
772 if bone.collider>0:#{
773 bone.hitbox[0][0] = b.SR_data.collider_min[0]
774 bone.hitbox[0][1] = b.SR_data.collider_min[2]
775 bone.hitbox[0][2] = -b.SR_data.collider_max[1]
776 bone.hitbox[1][0] = b.SR_data.collider_max[0]
777 bone.hitbox[1][1] = b.SR_data.collider_max[2]
778 bone.hitbox[1][2] = -b.SR_data.collider_min[1]
779 #}
780
781 if b.SR_data.cone_constraint:#{
782 bone.flags |= 0x4
783 bone.conevx[0] = b.SR_data.conevx[0]
784 bone.conevx[1] = b.SR_data.conevx[2]
785 bone.conevx[2] = -b.SR_data.conevx[1]
786 bone.conevy[0] = b.SR_data.conevy[0]
787 bone.conevy[1] = b.SR_data.conevy[2]
788 bone.conevy[2] = -b.SR_data.conevy[1]
789 bone.coneva[0] = b.SR_data.coneva[0]
790 bone.coneva[1] = b.SR_data.coneva[2]
791 bone.coneva[2] = -b.SR_data.coneva[1]
792 bone.conet = b.SR_data.conet
793 #}
794
795 bone.co[0] = b.head_local[0]
796 bone.co[1] = b.head_local[2]
797 bone.co[2] = -b.head_local[1]
798 bone.end[0] = b.tail_local[0] - bone.co[0]
799 bone.end[1] = b.tail_local[2] - bone.co[1]
800 bone.end[2] = -b.tail_local[1] - bone.co[2]
801 bone.pstr_name = sr_compile_string( b.name )
802
803 for c in obj.pose.bones[b.name].constraints:#{
804 if c.type == 'IK':#{
805 bone.flags |= 0x2
806 bone.ik_target = bones_names.index(c.subtarget)
807 bone.ik_pole = bones_names.index(c.pole_subtarget)
808 #}
809 #}
810
811 node.bone_count += 1
812 sr_compile.bone_data.extend(bytearray(bone))
813 #}
814
815 # Compile anims
816 #
817 if obj.animation_data and sr_compile.pack_animations: #{
818 # So we can restore later
819 #
820 previous_frame = bpy.context.scene.frame_current
821 previous_action = obj.animation_data.action
822 POSE_OR_REST_CACHE = obj.data.pose_position
823 obj.data.pose_position = 'POSE'
824
825 for NLALayer in obj.animation_data.nla_tracks:#{
826 for NLAStrip in NLALayer.strips:#{
827 # set active
828 #
829 for a in bpy.data.actions:#{
830 if a.name == NLAStrip.name:#{
831 obj.animation_data.action = a
832 break
833 #}
834 #}
835
836 # Clip to NLA settings
837 #
838 anim_start = int(NLAStrip.action_frame_start)
839 anim_end = int(NLAStrip.action_frame_end)
840
841 # Export strips
842 #
843 anim = mdl_animation()
844 anim.pstr_name = sr_compile_string( NLAStrip.action.name )
845 anim.rate = 30.0
846 anim.keyframe_start = len(sr_compile.keyframe_data)//\
847 sizeof(mdl_transform)
848 anim.length = anim_end-anim_start
849
850 i = 0
851 # Export the keyframes
852 for frame in range(anim_start,anim_end):#{
853 bpy.context.scene.frame_set(frame)
854
855 for rb in bones:#{
856 pb = obj.pose.bones[rb.name]
857
858 # relative bone matrix
859 if rb.parent is not None:#{
860 offset_mtx = rb.parent.matrix_local
861 offset_mtx = offset_mtx.inverted_safe() @ \
862 rb.matrix_local
863
864 inv_parent = pb.parent.matrix @ offset_mtx
865 inv_parent.invert_safe()
866 fpm = inv_parent @ pb.matrix
867 #}
868 else:#{
869 bone_mtx = rb.matrix.to_4x4()
870 local_inv = rb.matrix_local.inverted_safe()
871 fpm = bone_mtx @ local_inv @ pb.matrix
872 #}
873
874 loc, rot, sca = fpm.decompose()
875
876 # rotation
877 lc_m = pb.matrix_channel.to_3x3()
878 if pb.parent is not None:#{
879 smtx = pb.parent.matrix_channel.to_3x3()
880 lc_m = smtx.inverted() @ lc_m
881 #}
882 rq = lc_m.to_quaternion()
883
884 kf = mdl_transform()
885 kf.co[0] = loc[0]
886 kf.co[1] = loc[2]
887 kf.co[2] = -loc[1]
888 kf.q[0] = rq[1]
889 kf.q[1] = rq[3]
890 kf.q[2] = -rq[2]
891 kf.q[3] = rq[0]
892 kf.s[0] = sca[0]
893 kf.s[1] = sca[1]
894 kf.s[2] = sca[2]
895 sr_compile.keyframe_data.extend(bytearray(kf))
896
897 i+=1
898 #}
899 #}
900
901 # Add to animation buffer
902 #
903 sr_compile.anim_data.extend(bytearray(anim))
904 node.anim_count += 1
905
906 # Report progress
907 #
908 print( F"[SR] | anim( {NLAStrip.action.name} )" )
909 #}
910 #}
911
912 # Restore context to how it was before
913 #
914 bpy.context.scene.frame_set( previous_frame )
915 obj.animation_data.action = previous_action
916 obj.data.pose_position = POSE_OR_REST_CACHE
917 #}
918
919 sr_compile.armature_data.extend(bytearray(node))
920 #}
921
922 def sr_ent_push( struct ):
923 #{
924 clase = type(struct).__name__
925
926 if clase not in sr_compile.entity_data:#{
927 sr_compile.entity_data[ clase ] = bytearray()
928 sr_compile.entity_info[ clase ] = { 'size': sizeof(struct) }
929 #}
930
931 index = len(sr_compile.entity_data[ clase ])//sizeof(struct)
932 sr_compile.entity_data[ clase ].extend( bytearray(struct) )
933 return index
934 #}
935
936 def sr_array_title( arr, name, count, size, offset ):
937 #{
938 for i in range(len(name)):#{
939 arr.name[i] = ord(name[i])
940 #}
941 arr.file_offset = offset
942 arr.item_count = count
943 arr.item_size = size
944 #}
945
946 def sr_compile( collection ):
947 #{
948 print( F"[SR] compiler begin ({collection.name}.mdl)" )
949
950 #settings
951 sr_compile.pack_textures = collection.SR_data.pack_textures
952 sr_compile.pack_animations = collection.SR_data.animations
953
954 # caches
955 sr_compile.string_cache = {}
956 sr_compile.mesh_cache = {}
957 sr_compile.material_cache = {}
958 sr_compile.texture_cache = {}
959
960 # compiled data
961 sr_compile.mesh_data = bytearray()
962 sr_compile.submesh_data = bytearray()
963 sr_compile.vertex_data = bytearray()
964 sr_compile.indice_data = bytearray()
965 sr_compile.bone_data = bytearray()
966 sr_compile.material_data = bytearray()
967 sr_compile.armature_data = bytearray()
968 sr_compile.anim_data = bytearray()
969 sr_compile.keyframe_data = bytearray()
970 sr_compile.texture_data = bytearray()
971
972 # just bytes not structures
973 sr_compile.string_data = bytearray()
974 sr_compile.pack_data = bytearray()
975
976 # variable
977 sr_compile.entity_data = {}
978 sr_compile.entity_info = {}
979
980 print( F"[SR] assign entity ID's" )
981 sr_compile.entities = {}
982 sr_compile.entity_ids = {}
983
984 mesh_count = 0
985 for obj in collection.all_objects: #{
986 if obj.type == 'MESH': mesh_count += 1
987
988 ent_type = obj_ent_type( obj )
989 if ent_type == 'none': continue
990
991 if ent_type not in sr_compile.entities: sr_compile.entities[ent_type] = []
992 sr_compile.entity_ids[obj.name] = len( sr_compile.entities[ent_type] )
993 sr_compile.entities[ent_type] += [obj]
994 #}
995
996 print( F"[SR] Compiling geometry" )
997 i=0
998 for obj in collection.all_objects:#{
999 if obj.type == 'MESH':#{
1000 i+=1
1001 print( F'[SR] {i: 3}/{mesh_count} {obj.name:<40}', end='\r' )
1002 sr_compile_mesh( obj )
1003 #}
1004 #}
1005
1006 checkpoint_count = 0
1007 pathindice_count = 0
1008
1009 for ent_type, arr in sr_compile.entities.items():#{
1010 print(F"[SR] Compiling {len(arr)} {ent_type}{'s' if len(arr)>1 else ''}")
1011
1012 for i in range(len(arr)):#{
1013 obj = arr[i]
1014
1015 print( F"[SR] {i+1: 3}/{len(arr)} {obj.name:<40} ",end='\r' )
1016
1017 if ent_type == 'mdl_armature': sr_compile_armature(obj)
1018 elif ent_type == 'ent_light': #{
1019 light = ent_light()
1020 compile_obj_transform( obj, light.transform )
1021 light.daytime = obj.data.SR_data.daytime
1022 if obj.data.type == 'POINT':#{
1023 light.type = 0
1024 #}
1025 elif obj.data.type == 'SPOT':#{
1026 light.type = 1
1027 light.angle = obj.data.spot_size*0.5
1028 #}
1029 light.range = obj.data.cutoff_distance
1030 light.colour[0] = obj.data.color[0]
1031 light.colour[1] = obj.data.color[1]
1032 light.colour[2] = obj.data.color[2]
1033 light.colour[3] = obj.data.energy
1034 sr_ent_push( light )
1035 #}
1036 elif ent_type == 'ent_gate': #{
1037 gate = ent_gate()
1038 gate.type = 0
1039 obj_data = obj.SR_data.ent_gate[0]
1040 mesh_data = obj.data.SR_data.ent_gate[0]
1041 if obj_data.target:#{
1042 gate.target = sr_compile.entity_ids[obj_data.target.name]
1043 gate.type = 1
1044 #}
1045 gate.dimensions[0] = mesh_data.dimensions[0]
1046 gate.dimensions[1] = mesh_data.dimensions[1]
1047 gate.dimensions[2] = mesh_data.dimensions[2]
1048
1049 q = [obj.matrix_local.to_quaternion(), (0,0,0,1)]
1050 co = [obj.matrix_world @ Vector((0,0,0)), (0,0,0)]
1051
1052 if obj_data.target:#{
1053 q[1] = obj_data.target.matrix_local.to_quaternion()
1054 co[1]= obj_data.target.matrix_world @ Vector((0,0,0))
1055 #}
1056
1057 # Setup transform
1058 #
1059 for x in range(2):#{
1060 gate.co[x][0] = co[x][0]
1061 gate.co[x][1] = co[x][2]
1062 gate.co[x][2] = -co[x][1]
1063 gate.q[x][0] = q[x][1]
1064 gate.q[x][1] = q[x][3]
1065 gate.q[x][2] = -q[x][2]
1066 gate.q[x][3] = q[x][0]
1067 #}
1068
1069 sr_ent_push( gate )
1070 #}
1071 elif ent_type == 'ent_spawn': #{
1072 spawn = ent_spawn()
1073 compile_obj_transform( obj, spawn.transform )
1074 obj_data = obj.SR_data.ent_spawn[0]
1075 spawn.pstr_name = sr_compile_string( obj_data.name )
1076 sr_ent_push( spawn )
1077 #}
1078 elif ent_type == 'ent_route': #{
1079 obj_data = obj.SR_data.ent_route[0]
1080 route = ent_route()
1081 route.pstr_name = sr_compile_string( obj_data.alias ) #TODO
1082 route.checkpoints_start = checkpoint_count
1083 route.checkpoints_count = 0
1084
1085 for ci in range(3):
1086 route.colour[ci] = obj_data.colour[ci]
1087 route.colour[3] = 1.0
1088
1089 compile_obj_transform( obj, route.transform )
1090
1091 checkpoints = obj_data.gates
1092 route_nodes = []
1093
1094 for uc in obj.users_collection[0].objects:#{
1095 uc_type = obj_ent_type( uc )
1096 if uc_type == 'ent_gate' or uc_type == 'ent_route_node':
1097 route_nodes += [uc]
1098 #}
1099 graph = node_graph( route_nodes )
1100
1101 for i in range(len(checkpoints)):#{
1102 gi = checkpoints[i].target
1103 gj = checkpoints[(i+1)%len(checkpoints)].target
1104 gate = gi
1105
1106 if gi:#{
1107 dest = gi.SR_data.ent_gate[0].target
1108 gi = dest
1109 #}
1110
1111 if gi==gj: continue # error?
1112 if not gi or not gj: continue
1113
1114 checkpoint = ent_checkpoint()
1115 checkpoint.gate_index = sr_compile.entity_ids[gate.name]
1116 checkpoint.path_start = pathindice_count
1117 checkpoint.path_count = 0
1118
1119 path = dijkstra( graph, gj.name, gi.name )
1120 if path:#{
1121 for pi in range(1,len(path)-1):#{
1122 pathindice = ent_path_index()
1123 pathindice.index = sr_compile.entity_ids[path[pi]]
1124 sr_ent_push( pathindice )
1125
1126 checkpoint.path_count += 1
1127 pathindice_count += 1
1128 #}
1129 #}
1130
1131 sr_ent_push( checkpoint )
1132 route.checkpoints_count += 1
1133 checkpoint_count += 1
1134 #}
1135
1136 sr_ent_push( route )
1137 #}
1138 elif ent_type == 'ent_route_node':#{
1139 rn = ent_route_node()
1140 rn.co[0] = obj.location[0]
1141 rn.co[1] = obj.location[2]
1142 rn.co[2] = -obj.location[1]
1143 sr_ent_push( rn )
1144 #}
1145 #}
1146 #}
1147
1148 print( F"[SR] Writing file" )
1149
1150 file_array_instructions = {}
1151 file_offset = 0
1152
1153 def _write_array( name, item_size, data ):#{
1154 nonlocal file_array_instructions, file_offset
1155
1156 count = len(data)//item_size
1157 file_array_instructions[name] = {'count':count, 'size':item_size,\
1158 'data':data, 'offset': file_offset}
1159 file_offset += len(data)
1160 file_offset = int_align_to( file_offset, 8 )
1161 #}
1162
1163 _write_array( 'strings', 1, sr_compile.string_data )
1164 _write_array( 'mdl_mesh', sizeof(mdl_mesh), sr_compile.mesh_data )
1165 _write_array( 'mdl_submesh', sizeof(mdl_submesh), sr_compile.submesh_data )
1166 _write_array( 'mdl_material', sizeof(mdl_material), sr_compile.material_data)
1167 _write_array( 'mdl_texture', sizeof(mdl_texture), sr_compile.texture_data)
1168 _write_array( 'mdl_armature', sizeof(mdl_armature), sr_compile.armature_data)
1169 _write_array( 'mdl_bone', sizeof(mdl_bone), sr_compile.bone_data )
1170
1171 for name, buffer in sr_compile.entity_data.items():#{
1172 _write_array( name, sr_compile.entity_info[name]['size'], buffer )
1173 #}
1174
1175 _write_array( 'mdl_animation', sizeof(mdl_animation), sr_compile.anim_data)
1176 _write_array( 'mdl_keyframe', sizeof(mdl_transform),sr_compile.keyframe_data)
1177 _write_array( 'mdl_vert', sizeof(mdl_vert), sr_compile.vertex_data )
1178 _write_array( 'mdl_indice', sizeof(c_uint32), sr_compile.indice_data )
1179 _write_array( 'pack', 1, sr_compile.pack_data )
1180
1181 header_size = int_align_to( sizeof(mdl_header), 8 )
1182 index_size = int_align_to( sizeof(mdl_array)*len(file_array_instructions),8 )
1183
1184 folder = bpy.path.abspath(bpy.context.scene.SR_data.export_dir)
1185 path = F"{folder}{collection.name}.mdl"
1186 print( path )
1187
1188 fp = open( path, "wb" )
1189 header = mdl_header()
1190 header.version = 40
1191 sr_array_title( header.arrays, \
1192 'index', len(file_array_instructions), \
1193 sizeof(mdl_array), header_size )
1194
1195 fp.write( bytearray_align_to( bytearray(header), 8 ) )
1196
1197 print( F'[SR] {"name":>16}| count | offset' )
1198 index = bytearray()
1199 for name,info in file_array_instructions.items():#{
1200 arr = mdl_array()
1201 offset = info['offset'] + header_size + index_size
1202 sr_array_title( arr, name, info['count'], info['size'], offset )
1203 index.extend( bytearray(arr) )
1204
1205 print( F'[SR] {name:>16}| {info["count"]: 8} '+\
1206 F' 0x{info["offset"]:02x}' )
1207 #}
1208 fp.write( bytearray_align_to( index, 8 ) )
1209 #bytearray_print_hex( index )
1210
1211 for name,info in file_array_instructions.items():#{
1212 fp.write( bytearray_align_to( info['data'], 8 ) )
1213 #}
1214
1215 fp.close()
1216
1217 print( '[SR] done' )
1218 #}
1219
1220 class SR_SCENE_SETTINGS(bpy.types.PropertyGroup):
1221 #{
1222 use_hidden: bpy.props.BoolProperty( name="use hidden", default=False )
1223 export_dir: bpy.props.StringProperty( name="Export Dir", subtype='DIR_PATH' )
1224 gizmos: bpy.props.BoolProperty( name="Draw Gizmos", default=True )
1225
1226 panel: bpy.props.EnumProperty(
1227 name='Panel',
1228 description='',
1229 items=[
1230 ('EXPORT', 'Export', '', 'MOD_BUILD',0),
1231 ('ENTITY', 'Entity', '', 'MONKEY',1),
1232 ('SETTINGS', 'Settings', 'Settings', 'PREFERENCES',2),
1233 ],
1234 )
1235 #}
1236
1237 class SR_COLLECTION_SETTINGS(bpy.types.PropertyGroup):
1238 #{
1239 pack_textures: bpy.props.BoolProperty( name="Pack Textures", default=False )
1240 animations: bpy.props.BoolProperty( name="Export animation", default=True)
1241 #}
1242
1243 def sr_get_mirror_bone( bones ):
1244 #{
1245 side = bones.active.name[-1:]
1246 other_name = bones.active.name[:-1]
1247 if side == 'L': other_name += 'R'
1248 elif side == 'R': other_name += 'L'
1249 else: return None
1250
1251 for b in bones:#{
1252 if b.name == other_name:
1253 return b
1254 #}
1255
1256 return None
1257 #}
1258
1259 class SR_MIRROR_BONE_X(bpy.types.Operator):
1260 #{
1261 bl_idname="skaterift.mirror_bone"
1262 bl_label="Mirror bone attributes - SkateRift"
1263
1264 def execute(_,context):
1265 #{
1266 active_object = context.active_object
1267 bones = active_object.data.bones
1268 a = bones.active
1269 b = sr_get_mirror_bone( bones )
1270
1271 if not b: return {'FINISHED'}
1272
1273 b.SR_data.collider = a.SR_data.collider
1274
1275 def _v3copyflipy( a, b ):#{
1276 b[0] = a[0]
1277 b[1] = -a[1]
1278 b[2] = a[2]
1279 #}
1280
1281 _v3copyflipy( a.SR_data.collider_min, b.SR_data.collider_min )
1282 _v3copyflipy( a.SR_data.collider_max, b.SR_data.collider_max )
1283 b.SR_data.collider_min[1] = -a.SR_data.collider_max[1]
1284 b.SR_data.collider_max[1] = -a.SR_data.collider_min[1]
1285
1286 b.SR_data.cone_constraint = a.SR_data.cone_constraint
1287
1288 _v3copyflipy( a.SR_data.conevx, b.SR_data.conevy )
1289 _v3copyflipy( a.SR_data.conevy, b.SR_data.conevx )
1290 _v3copyflipy( a.SR_data.coneva, b.SR_data.coneva )
1291
1292 b.SR_data.conet = a.SR_data.conet
1293
1294 # redraw
1295 ob = bpy.context.scene.objects[0]
1296 ob.hide_render = ob.hide_render
1297 return {'FINISHED'}
1298 #}
1299 #}
1300
1301 class SR_COMPILE(bpy.types.Operator):
1302 #{
1303 bl_idname="skaterift.compile_all"
1304 bl_label="Compile All"
1305
1306 def execute(_,context):
1307 #{
1308 view_layer = bpy.context.view_layer
1309 for col in view_layer.layer_collection.children["export"].children:
1310 if not col.hide_viewport or bpy.context.scene.SR_data.use_hidden:
1311 sr_compile( bpy.data.collections[col.name] )
1312
1313 return {'FINISHED'}
1314 #}
1315 #}
1316
1317 class SR_COMPILE_THIS(bpy.types.Operator):
1318 #{
1319 bl_idname="skaterift.compile_this"
1320 bl_label="Compile This collection"
1321
1322 def execute(_,context):
1323 #{
1324 col = bpy.context.collection
1325 sr_compile( col )
1326
1327 return {'FINISHED'}
1328 #}
1329 #}
1330
1331 class SR_INTERFACE(bpy.types.Panel):
1332 #{
1333 bl_idname = "VIEW3D_PT_skate_rift"
1334 bl_label = "Skate Rift"
1335 bl_space_type = 'VIEW_3D'
1336 bl_region_type = 'UI'
1337 bl_category = "Skate Rift"
1338
1339 def draw(_, context):
1340 #{
1341 # Compiler section
1342
1343 row = _.layout.row()
1344 row.scale_y = 1.75
1345 row.prop( context.scene.SR_data, 'panel', expand=True )
1346
1347 if context.scene.SR_data.panel == 'SETTINGS': #{
1348 _.layout.prop( context.scene.SR_data, 'gizmos' )
1349 #}
1350 elif context.scene.SR_data.panel == 'EXPORT': #{
1351 _.layout.prop( context.scene.SR_data, "export_dir" )
1352 col = bpy.context.collection
1353
1354 found_in_export = False
1355 export_count = 0
1356 view_layer = bpy.context.view_layer
1357 for c1 in view_layer.layer_collection.children["export"].children: #{
1358 if not c1.hide_viewport or bpy.context.scene.SR_data.use_hidden:
1359 export_count += 1
1360
1361 if c1.name == col.name: #{
1362 found_in_export = True
1363 #}
1364 #}
1365
1366 box = _.layout.box()
1367 row = box.row()
1368 row.alignment = 'CENTER'
1369 row.scale_y = 1.5
1370
1371 if found_in_export: #{
1372 row.label( text=col.name + ".mdl" )
1373 box.prop( col.SR_data, "pack_textures" )
1374 box.prop( col.SR_data, "animations" )
1375 box.operator( "skaterift.compile_this" )
1376 #}
1377 else: #{
1378 row.enabled=False
1379 row.label( text=col.name )
1380
1381 row = box.row()
1382 row.enabled=False
1383 row.alignment = 'CENTER'
1384 row.scale_y = 1.5
1385 row.label( text="This collection is not in the export group" )
1386 #}
1387
1388 box = _.layout.box()
1389 row = box.row()
1390
1391 split = row.split( factor=0.3, align=True )
1392 split.prop( context.scene.SR_data, "use_hidden", text="hidden" )
1393
1394 row1 = split.row()
1395 if export_count == 0:
1396 row1.enabled=False
1397 row1.operator( "skaterift.compile_all", \
1398 text=F"Compile all ({export_count} collections)" )
1399 #}
1400 elif context.scene.SR_data.panel == 'ENTITY': #{
1401 active_object = context.active_object
1402 if not active_object: return
1403
1404 box = _.layout.box()
1405 row = box.row()
1406 row.alignment = 'CENTER'
1407 row.label( text=active_object.name )
1408 row.scale_y = 1.5
1409
1410 def _draw_prop_collection( data ): #{
1411 nonlocal box
1412 row = box.row()
1413 row.alignment = 'CENTER'
1414 row.enabled = False
1415 row.scale_y = 1.5
1416 row.label( text=F'{data[0]}' )
1417
1418 if hasattr(type(data[0]),'sr_inspector'):#{
1419 type(data[0]).sr_inspector( box, data )
1420 #}
1421 else:#{
1422 for a in data[0].__annotations__:
1423 box.prop( data[0], a )
1424 #}
1425 #}
1426
1427 if active_object.type == 'ARMATURE': #{
1428 if active_object.mode == 'POSE': #{
1429 bones = active_object.data.bones
1430 mb = sr_get_mirror_bone( bones )
1431 if mb:#{
1432 box.operator( "skaterift.mirror_bone", \
1433 text=F'Mirror attributes to {mb.name}' )
1434 #}
1435
1436 _draw_prop_collection( [bones.active.SR_data ] )
1437 #}
1438 else: #{
1439 row = box.row()
1440 row.alignment='CENTER'
1441 row.scale_y=2.0
1442 row.enabled=False
1443 row.label( text="Enter pose mode to modify bone properties" )
1444 #}
1445 #}
1446 elif active_object.type == 'LIGHT': #{
1447 _draw_prop_collection( [active_object.data.SR_data] )
1448 #}
1449 elif active_object.type == 'EMPTY' or active_object.type == 'MESH': #{
1450 box.prop( active_object.SR_data, "ent_type" )
1451 ent_type = active_object.SR_data.ent_type
1452
1453 col = getattr( active_object.SR_data, ent_type, None )
1454 if col != None and len(col)!=0: _draw_prop_collection( col )
1455
1456 if active_object.type == 'MESH':#{
1457 col = getattr( active_object.data.SR_data, ent_type, None )
1458 if col != None and len(col)!=0: _draw_prop_collection( col )
1459 #}
1460 #}
1461 #}
1462 #}
1463 #}
1464
1465 class SR_MATERIAL_PANEL(bpy.types.Panel):
1466 #{
1467 bl_label="Skate Rift material"
1468 bl_idname="MATERIAL_PT_sr_material"
1469 bl_space_type='PROPERTIES'
1470 bl_region_type='WINDOW'
1471 bl_context="material"
1472
1473 def draw(_,context):
1474 #{
1475 active_object = bpy.context.active_object
1476 if active_object == None: return
1477 active_mat = active_object.active_material
1478 if active_mat == None: return
1479
1480 info = material_info( active_mat )
1481
1482 if 'tex_diffuse' in info:#{
1483 _.layout.label( icon='INFO', \
1484 text=F"{info['tex_diffuse'].name} will be compiled" )
1485 #}
1486
1487 _.layout.prop( active_mat.SR_data, "shader" )
1488 _.layout.prop( active_mat.SR_data, "surface_prop" )
1489 _.layout.prop( active_mat.SR_data, "collision" )
1490
1491 if active_mat.SR_data.collision:#{
1492 _.layout.prop( active_mat.SR_data, "skate_surface" )
1493 _.layout.prop( active_mat.SR_data, "grind_surface" )
1494 _.layout.prop( active_mat.SR_data, "grow_grass" )
1495 #}
1496
1497 if active_mat.SR_data.shader == "terrain_blend":#{
1498 box = _.layout.box()
1499 box.prop( active_mat.SR_data, "blend_offset" )
1500 box.prop( active_mat.SR_data, "sand_colour" )
1501 #}
1502 elif active_mat.SR_data.shader == "vertex_blend":#{
1503 box = _.layout.box()
1504 box.label( icon='INFO', text="Uses vertex colours, the R channel" )
1505 box.prop( active_mat.SR_data, "blend_offset" )
1506 #}
1507 elif active_mat.SR_data.shader == "water":#{
1508 box = _.layout.box()
1509 box.label( icon='INFO', text="Depth scale of 16 meters" )
1510 box.prop( active_mat.SR_data, "shore_colour" )
1511 box.prop( active_mat.SR_data, "ocean_colour" )
1512 #}
1513 #}
1514 #}
1515
1516 def sr_get_type_enum( scene, context ):
1517 #{
1518 items = [('none','None',"")]
1519 mesh_entities=['ent_gate']
1520 point_entities=['ent_spawn','ent_route_node','ent_route']
1521
1522 for e in point_entities: items += [(e,e,'')]
1523
1524 if context.scene.SR_data.panel == 'ENTITY': #{
1525 if context.active_object.type == 'MESH': #{
1526 for e in mesh_entities: items += [(e,e,'')]
1527 #}
1528 #}
1529 else: #{
1530 for e in mesh_entities: items += [(e,e,'')]
1531 #}
1532
1533 return items
1534 #}
1535
1536 def sr_on_type_change( _, context ):
1537 #{
1538 obj = context.active_object
1539 ent_type = obj.SR_data.ent_type
1540 if ent_type == 'none': return
1541 if obj.type == 'MESH':#{
1542 col = getattr( obj.data.SR_data, ent_type, None )
1543 if col != None and len(col)==0: col.add()
1544 #}
1545
1546 col = getattr( obj.SR_data, ent_type, None )
1547 if col != None and len(col)==0: col.add()
1548 #}
1549
1550 class SR_OBJECT_ENT_SPAWN(bpy.types.PropertyGroup):
1551 #{
1552 alias: bpy.props.StringProperty( name='alias' )
1553 #}
1554
1555 class SR_OBJECT_ENT_GATE(bpy.types.PropertyGroup):
1556 #{
1557 target: bpy.props.PointerProperty( \
1558 type=bpy.types.Object, name="destination", \
1559 poll=lambda self,obj: sr_filter_ent_type(obj,'ent_gate'))
1560 #}
1561
1562 class SR_MESH_ENT_GATE(bpy.types.PropertyGroup):
1563 #{
1564 dimensions: bpy.props.FloatVectorProperty(name="dimensions",size=3)
1565 #}
1566
1567 class SR_OBJECT_ENT_ROUTE_ENTRY(bpy.types.PropertyGroup):
1568 #{
1569 target: bpy.props.PointerProperty( \
1570 type=bpy.types.Object, name='target', \
1571 poll=lambda self,obj: sr_filter_ent_type(obj,'ent_gate'))
1572 #}
1573
1574 class SR_UL_ROUTE_NODE_LIST(bpy.types.UIList):
1575 #{
1576 bl_idname = 'SR_UL_ROUTE_NODE_LIST'
1577
1578 def draw_item(_,context,layout,data,item,icon,active_data,active_propname):
1579 #{
1580 layout.prop( item, 'target', text='', emboss=False )
1581 #}
1582 #}
1583
1584 class SR_OT_ROUTE_LIST_NEW_ITEM(bpy.types.Operator):
1585 #{
1586 bl_idname = "skaterift.new_entry"
1587 bl_label = "Add gate"
1588
1589 def execute(self, context):#{
1590 active_object = context.active_object
1591 active_object.SR_data.ent_route[0].gates.add()
1592 return{'FINISHED'}
1593 #}
1594 #}
1595
1596 class SR_OT_ROUTE_LIST_DEL_ITEM(bpy.types.Operator):
1597 #{
1598 bl_idname = "skaterift.del_entry"
1599 bl_label = "Remove gate"
1600
1601 @classmethod
1602 def poll(cls, context):#{
1603 active_object = context.active_object
1604 if obj_ent_type == 'ent_gate':#{
1605 return active_object.SR_data.ent_route[0].gates
1606 #}
1607 else: return False
1608 #}
1609
1610 def execute(self, context):#{
1611 active_object = context.active_object
1612 lista = active_object.SR_data.ent_route[0].gates
1613 index = active_object.SR_data.ent_route[0].gates_index
1614 lista.remove(index)
1615 active_object.SR_data.ent_route[0].gates_index = \
1616 min(max(0, index-1), len(lista) - 1)
1617 return{'FINISHED'}
1618 #}
1619 #}
1620
1621 class SR_OBJECT_ENT_ROUTE(bpy.types.PropertyGroup):
1622 #{
1623 gates: bpy.props.CollectionProperty(type=SR_OBJECT_ENT_ROUTE_ENTRY)
1624 gates_index: bpy.props.IntProperty()
1625
1626 colour: bpy.props.FloatVectorProperty( \
1627 name="Colour",\
1628 subtype='COLOR',\
1629 min=0.0,max=1.0,\
1630 default=Vector((0.79,0.63,0.48)),\
1631 description="Route colour"\
1632 )
1633
1634 alias: bpy.props.StringProperty(\
1635 name="Alias",\
1636 default="Untitled Course")
1637
1638 @staticmethod
1639 def sr_inspector( layout, data ):
1640 #{
1641 layout.prop( data[0], 'alias' )
1642 layout.prop( data[0], 'colour' )
1643
1644 layout.label( text='Checkpoints' )
1645 layout.template_list('SR_UL_ROUTE_NODE_LIST', 'Checkpoints', \
1646 data[0], 'gates', data[0], 'gates_index', rows=5)
1647
1648 row = layout.row()
1649 row.operator( 'skaterift.new_entry', text='Add' )
1650 row.operator( 'skaterift.del_entry', text='Remove' )
1651 #}
1652 #}
1653
1654 class SR_OBJECT_PROPERTIES(bpy.types.PropertyGroup):
1655 #{
1656 ent_gate: bpy.props.CollectionProperty(type=SR_OBJECT_ENT_GATE)
1657 ent_spawn: bpy.props.CollectionProperty(type=SR_OBJECT_ENT_SPAWN)
1658 ent_route: bpy.props.CollectionProperty(type=SR_OBJECT_ENT_ROUTE)
1659
1660 ent_type: bpy.props.EnumProperty(
1661 name="Type",
1662 items=[('none', 'None', '', 0),
1663 ('ent_gate','Gate','', 1),
1664 ('ent_spawn','Spawn','', 2),
1665 ('ent_route_node', 'Route Node', '', 3 ),
1666 ('ent_route', 'Route', '', 4)],
1667 update=sr_on_type_change
1668 )
1669 #}
1670
1671 class SR_MESH_PROPERTIES(bpy.types.PropertyGroup):
1672 #{
1673 ent_gate: bpy.props.CollectionProperty(type=SR_MESH_ENT_GATE)
1674 #}
1675
1676 class SR_LIGHT_PROPERTIES(bpy.types.PropertyGroup):
1677 #{
1678 daytime: bpy.props.BoolProperty( name='Daytime' )
1679 #}
1680
1681 class SR_BONE_PROPERTIES(bpy.types.PropertyGroup):
1682 #{
1683 collider: bpy.props.EnumProperty( name='Collider Type',
1684 items=[('0','none',''),
1685 ('1','box',''),
1686 ('2','capsule','')])
1687
1688 collider_min: bpy.props.FloatVectorProperty( name='Collider Min', size=3 )
1689 collider_max: bpy.props.FloatVectorProperty( name='Collider Max', size=3 )
1690
1691 cone_constraint: bpy.props.BoolProperty( name='Cone constraint' )
1692
1693 conevx: bpy.props.FloatVectorProperty( name='vx' )
1694 conevy: bpy.props.FloatVectorProperty( name='vy' )
1695 coneva: bpy.props.FloatVectorProperty( name='va' )
1696 conet: bpy.props.FloatProperty( name='t' )
1697
1698 @staticmethod
1699 def sr_inspector( layout, data ):
1700 #{
1701 data = data[0]
1702 box = layout.box()
1703 box.prop( data, 'collider' )
1704
1705 if int(data.collider)>0:#{
1706 row = box.row()
1707 row.prop( data, 'collider_min' )
1708 row = box.row()
1709 row.prop( data, 'collider_max' )
1710 #}
1711
1712 box = layout.box()
1713 box.prop( data, 'cone_constraint' )
1714 if data.cone_constraint:#{
1715 row = box.row()
1716 row.prop( data, 'conevx' )
1717 row = box.row()
1718 row.prop( data, 'conevy' )
1719 row = box.row()
1720 row.prop( data, 'coneva' )
1721 box.prop( data, 'conet' )
1722 #}
1723 #}
1724 #}
1725
1726 class SR_MATERIAL_PROPERTIES(bpy.types.PropertyGroup):
1727 #{
1728 shader: bpy.props.EnumProperty(
1729 name="Format",
1730 items = [
1731 ('standard',"standard",''),
1732 ('standard_cutout', "standard_cutout", ''),
1733 ('terrain_blend', "terrain_blend", ''),
1734 ('vertex_blend', "vertex_blend", ''),
1735 ('water',"water",'')
1736 ])
1737
1738 surface_prop: bpy.props.EnumProperty(
1739 name="Surface Property",
1740 items = [
1741 ('0','concrete',''),
1742 ('1','wood',''),
1743 ('2','grass',''),
1744 ('3','tiles',''),
1745 ('4','metal','')
1746 ])
1747
1748 collision: bpy.props.BoolProperty( \
1749 name="Collisions Enabled",\
1750 default=True,\
1751 description = "Can the player collide with this material"\
1752 )
1753 skate_surface: bpy.props.BoolProperty( \
1754 name="Skate Surface", \
1755 default=True,\
1756 description = "Should the game try to target this surface?" \
1757 )
1758 grind_surface: bpy.props.BoolProperty( \
1759 name="Grind Surface", \
1760 default=False,\
1761 description = "Grind face?" \
1762 )
1763 grow_grass: bpy.props.BoolProperty( \
1764 name="Grow Grass", \
1765 default=False,\
1766 description = "Spawn grass sprites on this surface?" \
1767 )
1768 blend_offset: bpy.props.FloatVectorProperty( \
1769 name="Blend Offset", \
1770 size=2, \
1771 default=Vector((0.5,0.0)),\
1772 description="When surface is more than 45 degrees, add this vector " +\
1773 "to the UVs" \
1774 )
1775 sand_colour: bpy.props.FloatVectorProperty( \
1776 name="Sand Colour",\
1777 subtype='COLOR',\
1778 min=0.0,max=1.0,\
1779 default=Vector((0.79,0.63,0.48)),\
1780 description="Blend to this colour near the 0 coordinate on UP axis"\
1781 )
1782 shore_colour: bpy.props.FloatVectorProperty( \
1783 name="Shore Colour",\
1784 subtype='COLOR',\
1785 min=0.0,max=1.0,\
1786 default=Vector((0.03,0.32,0.61)),\
1787 description="Water colour at the shoreline"\
1788 )
1789 ocean_colour: bpy.props.FloatVectorProperty( \
1790 name="Ocean Colour",\
1791 subtype='COLOR',\
1792 min=0.0,max=1.0,\
1793 default=Vector((0.0,0.006,0.03)),\
1794 description="Water colour in the deep bits"\
1795 )
1796 #}
1797
1798 # ---------------------------------------------------------------------------- #
1799 # #
1800 # GUI section #
1801 # #
1802 # ---------------------------------------------------------------------------- #
1803
1804 cv_view_draw_handler = None
1805 cv_view_shader = gpu.shader.from_builtin('3D_SMOOTH_COLOR')
1806 cv_view_verts = []
1807 cv_view_colours = []
1808 cv_view_course_i = 0
1809
1810 # Draw axis alligned sphere at position with radius
1811 #
1812 def cv_draw_sphere( pos, radius, colour ):
1813 #{
1814 global cv_view_verts, cv_view_colours
1815
1816 ly = pos + Vector((0,0,radius))
1817 lx = pos + Vector((0,radius,0))
1818 lz = pos + Vector((0,0,radius))
1819
1820 pi = 3.14159265358979323846264
1821
1822 for i in range(16):
1823 #{
1824 t = ((i+1.0) * 1.0/16.0) * pi * 2.0
1825 s = math.sin(t)
1826 c = math.cos(t)
1827
1828 py = pos + Vector((s*radius,0.0,c*radius))
1829 px = pos + Vector((s*radius,c*radius,0.0))
1830 pz = pos + Vector((0.0,s*radius,c*radius))
1831
1832 cv_view_verts += [ px, lx ]
1833 cv_view_verts += [ py, ly ]
1834 cv_view_verts += [ pz, lz ]
1835
1836 cv_view_colours += [ colour, colour, colour, colour, colour, colour ]
1837
1838 ly = py
1839 lx = px
1840 lz = pz
1841 #}
1842 cv_draw_lines()
1843 #}
1844
1845 # Draw axis alligned sphere at position with radius
1846 #
1847 def cv_draw_halfsphere( pos, tx, ty, tz, radius, colour ):
1848 #{
1849 global cv_view_verts, cv_view_colours
1850
1851 ly = pos + tz*radius
1852 lx = pos + ty*radius
1853 lz = pos + tz*radius
1854
1855 pi = 3.14159265358979323846264
1856
1857 for i in range(16):
1858 #{
1859 t = ((i+1.0) * 1.0/16.0) * pi
1860 s = math.sin(t)
1861 c = math.cos(t)
1862
1863 s1 = math.sin(t*2.0)
1864 c1 = math.cos(t*2.0)
1865
1866 py = pos + s*tx*radius + c *tz*radius
1867 px = pos + s*tx*radius + c *ty*radius
1868 pz = pos + s1*ty*radius + c1*tz*radius
1869
1870 cv_view_verts += [ px, lx ]
1871 cv_view_verts += [ py, ly ]
1872 cv_view_verts += [ pz, lz ]
1873
1874 cv_view_colours += [ colour, colour, colour, colour, colour, colour ]
1875
1876 ly = py
1877 lx = px
1878 lz = pz
1879 #}
1880 cv_draw_lines()
1881 #}
1882
1883 # Draw transformed -1 -> 1 cube
1884 #
1885 def cv_draw_ucube( transform, colour, s=Vector((1,1,1)), o=Vector((0,0,0)) ):
1886 #{
1887 global cv_view_verts, cv_view_colours
1888
1889 a = o + -1.0 * s
1890 b = o + 1.0 * s
1891
1892 vs = [None]*8
1893 vs[0] = transform @ Vector((a[0], a[1], a[2]))
1894 vs[1] = transform @ Vector((a[0], b[1], a[2]))
1895 vs[2] = transform @ Vector((b[0], b[1], a[2]))
1896 vs[3] = transform @ Vector((b[0], a[1], a[2]))
1897 vs[4] = transform @ Vector((a[0], a[1], b[2]))
1898 vs[5] = transform @ Vector((a[0], b[1], b[2]))
1899 vs[6] = transform @ Vector((b[0], b[1], b[2]))
1900 vs[7] = transform @ Vector((b[0], a[1], b[2]))
1901
1902 indices = [(0,1),(1,2),(2,3),(3,0),(4,5),(5,6),(6,7),(7,4),\
1903 (0,4),(1,5),(2,6),(3,7)]
1904
1905 for l in indices:
1906 #{
1907 v0 = vs[l[0]]
1908 v1 = vs[l[1]]
1909 cv_view_verts += [(v0[0],v0[1],v0[2])]
1910 cv_view_verts += [(v1[0],v1[1],v1[2])]
1911 cv_view_colours += [colour, colour]
1912 #}
1913 cv_draw_lines()
1914 #}
1915
1916 # Draw line with colour
1917 #
1918 def cv_draw_line( p0, p1, colour ):
1919 #{
1920 global cv_view_verts, cv_view_colours
1921
1922 cv_view_verts += [p0,p1]
1923 cv_view_colours += [colour, colour]
1924 cv_draw_lines()
1925 #}
1926
1927 # Draw line with colour(s)
1928 #
1929 def cv_draw_line2( p0, p1, c0, c1 ):
1930 #{
1931 global cv_view_verts, cv_view_colours
1932
1933 cv_view_verts += [p0,p1]
1934 cv_view_colours += [c0,c1]
1935 cv_draw_lines()
1936 #}
1937
1938 #
1939 #
1940 def cv_tangent_basis( n, tx, ty ):
1941 #{
1942 if abs( n[0] ) >= 0.57735027:
1943 #{
1944 tx[0] = n[1]
1945 tx[1] = -n[0]
1946 tx[2] = 0.0
1947 #}
1948 else:
1949 #{
1950 tx[0] = 0.0
1951 tx[1] = n[2]
1952 tx[2] = -n[1]
1953 #}
1954
1955 tx.normalize()
1956 _ty = n.cross( tx )
1957
1958 ty[0] = _ty[0]
1959 ty[1] = _ty[1]
1960 ty[2] = _ty[2]
1961 #}
1962
1963 # Draw coloured arrow
1964 #
1965 def cv_draw_arrow( p0, p1, c0, size=0.15 ):
1966 #{
1967 global cv_view_verts, cv_view_colours
1968
1969 n = p1-p0
1970 midpt = p0 + n*0.5
1971 n.normalize()
1972
1973 tx = Vector((1,0,0))
1974 ty = Vector((1,0,0))
1975 cv_tangent_basis( n, tx, ty )
1976
1977 cv_view_verts += [p0,p1, midpt+(tx-n)*size,midpt, midpt+(-tx-n)*size,midpt ]
1978 cv_view_colours += [c0,c0,c0,c0,c0,c0]
1979 cv_draw_lines()
1980 #}
1981
1982 def cv_draw_line_dotted( p0, p1, c0, dots=10 ):
1983 #{
1984 global cv_view_verts, cv_view_colours
1985
1986 for i in range(dots):#{
1987 t0 = i/dots
1988 t1 = (i+0.25)/dots
1989
1990 p2 = p0*(1.0-t0)+p1*t0
1991 p3 = p0*(1.0-t1)+p1*t1
1992
1993 cv_view_verts += [p2,p3]
1994 cv_view_colours += [c0,c0]
1995 #}
1996 cv_draw_lines()
1997 #}
1998
1999 # Drawhandles of a bezier control point
2000 #
2001 def cv_draw_bhandle( obj, direction, colour ):
2002 #{
2003 global cv_view_verts, cv_view_colours
2004
2005 p0 = obj.location
2006 h0 = obj.matrix_world @ Vector((0,direction,0))
2007
2008 cv_view_verts += [p0]
2009 cv_view_verts += [h0]
2010 cv_view_colours += [colour,colour]
2011 cv_draw_lines()
2012 #}
2013
2014 # Draw a bezier curve (at fixed resolution 10)
2015 #
2016 def cv_draw_bezier( p0,h0,p1,h1,c0,c1 ):
2017 #{
2018 global cv_view_verts, cv_view_colours
2019
2020 last = p0
2021 for i in range(10):
2022 #{
2023 t = (i+1)/10
2024 a0 = 1-t
2025
2026 tt = t*t
2027 ttt = tt*t
2028 p=ttt*p1+(3*tt-3*ttt)*h1+(3*ttt-6*tt+3*t)*h0+(3*tt-ttt-3*t+1)*p0
2029
2030 cv_view_verts += [(last[0],last[1],last[2])]
2031 cv_view_verts += [(p[0],p[1],p[2])]
2032 cv_view_colours += [c0*a0+c1*(1-a0),c0*a0+c1*(1-a0)]
2033
2034 last = p
2035 #}
2036 cv_draw_lines()
2037 #}
2038
2039 # I think this one extends the handles of the bezier otwards......
2040 #
2041 def cv_draw_sbpath( o0,o1,c0,c1,s0,s1 ):
2042 #{
2043 global cv_view_course_i
2044
2045 offs = ((cv_view_course_i % 2)*2-1) * cv_view_course_i * 0.02
2046
2047 p0 = o0.matrix_world @ Vector((offs, 0,0))
2048 h0 = o0.matrix_world @ Vector((offs, s0,0))
2049 p1 = o1.matrix_world @ Vector((offs, 0,0))
2050 h1 = o1.matrix_world @ Vector((offs,-s1,0))
2051
2052 cv_draw_bezier( p0,h0,p1,h1,c0,c1 )
2053 cv_draw_lines()
2054 #}
2055
2056 # Flush the lines buffers. This is called often because god help you if you want
2057 # to do fixed, fast buffers in this catastrophic programming language.
2058 #
2059 def cv_draw_lines():
2060 #{
2061 global cv_view_shader, cv_view_verts, cv_view_colours
2062
2063 if len(cv_view_verts) < 2:
2064 return
2065
2066 lines = batch_for_shader(\
2067 cv_view_shader, 'LINES', \
2068 { "pos":cv_view_verts, "color":cv_view_colours })
2069
2070 lines.draw( cv_view_shader )
2071
2072 cv_view_verts = []
2073 cv_view_colours = []
2074 #}
2075
2076 # I dont remember what this does exactly
2077 #
2078 def cv_draw_bpath( o0,o1,c0,c1 ):
2079 #{
2080 cv_draw_sbpath( o0,o1,c0,c1,1.0,1.0 )
2081 #}
2082
2083 # Semi circle to show the limit. and some lines
2084 #
2085 def draw_limit( obj, center, major, minor, amin, amax, colour ):
2086 #{
2087 global cv_view_verts, cv_view_colours
2088 f = 0.05
2089 ay = major*f
2090 ax = minor*f
2091
2092 for x in range(16):#{
2093 t0 = x/16
2094 t1 = (x+1)/16
2095 a0 = amin*(1.0-t0)+amax*t0
2096 a1 = amin*(1.0-t1)+amax*t1
2097
2098 p0 = center + major*f*math.cos(a0) + minor*f*math.sin(a0)
2099 p1 = center + major*f*math.cos(a1) + minor*f*math.sin(a1)
2100
2101 p0=obj.matrix_world @ p0
2102 p1=obj.matrix_world @ p1
2103 cv_view_verts += [p0,p1]
2104 cv_view_colours += [colour,colour]
2105
2106 if x == 0:#{
2107 cv_view_verts += [p0,center]
2108 cv_view_colours += [colour,colour]
2109 #}
2110 if x == 15:#{
2111 cv_view_verts += [p1,center]
2112 cv_view_colours += [colour,colour]
2113 #}
2114 #}
2115
2116 cv_view_verts += [center+major*1.2*f,center+major*f*0.8]
2117 cv_view_colours += [colour,colour]
2118
2119 cv_draw_lines()
2120 #}
2121
2122 # Cone and twist limit
2123 #
2124 def draw_cone_twist( center, vx, vy, va ):
2125 #{
2126 global cv_view_verts, cv_view_colours
2127 axis = vy.cross( vx )
2128 axis.normalize()
2129
2130 size = 0.12
2131
2132 cv_view_verts += [center, center+va*size]
2133 cv_view_colours += [ (1,1,1,1), (1,1,1,1) ]
2134
2135 for x in range(32):#{
2136 t0 = (x/32) * math.tau
2137 t1 = ((x+1)/32) * math.tau
2138
2139 c0 = math.cos(t0)
2140 s0 = math.sin(t0)
2141 c1 = math.cos(t1)
2142 s1 = math.sin(t1)
2143
2144 p0 = center + (axis + vx*c0 + vy*s0).normalized() * size
2145 p1 = center + (axis + vx*c1 + vy*s1).normalized() * size
2146
2147 col0 = ( abs(c0), abs(s0), 0.0, 1.0 )
2148 col1 = ( abs(c1), abs(s1), 0.0, 1.0 )
2149
2150 cv_view_verts += [center, p0, p0, p1]
2151 cv_view_colours += [ (0,0,0,0), col0, col0, col1 ]
2152 #}
2153
2154 cv_draw_lines()
2155 #}
2156
2157 # Draws constraints and stuff for the skeleton. This isnt documented and wont be
2158 #
2159 def draw_skeleton_helpers( obj ):
2160 #{
2161 global cv_view_verts, cv_view_colours
2162
2163 if obj.data.pose_position != 'REST':#{
2164 return
2165 #}
2166
2167 for bone in obj.data.bones:#{
2168 c = bone.head_local
2169 a = Vector((bone.SR_data.collider_min[0],
2170 bone.SR_data.collider_min[1],
2171 bone.SR_data.collider_min[2]))
2172 b = Vector((bone.SR_data.collider_max[0],
2173 bone.SR_data.collider_max[1],
2174 bone.SR_data.collider_max[2]))
2175
2176 if bone.SR_data.collider == '1':#{
2177 vs = [None]*8
2178 vs[0]=obj.matrix_world@Vector((c[0]+a[0],c[1]+a[1],c[2]+a[2]))
2179 vs[1]=obj.matrix_world@Vector((c[0]+a[0],c[1]+b[1],c[2]+a[2]))
2180 vs[2]=obj.matrix_world@Vector((c[0]+b[0],c[1]+b[1],c[2]+a[2]))
2181 vs[3]=obj.matrix_world@Vector((c[0]+b[0],c[1]+a[1],c[2]+a[2]))
2182 vs[4]=obj.matrix_world@Vector((c[0]+a[0],c[1]+a[1],c[2]+b[2]))
2183 vs[5]=obj.matrix_world@Vector((c[0]+a[0],c[1]+b[1],c[2]+b[2]))
2184 vs[6]=obj.matrix_world@Vector((c[0]+b[0],c[1]+b[1],c[2]+b[2]))
2185 vs[7]=obj.matrix_world@Vector((c[0]+b[0],c[1]+a[1],c[2]+b[2]))
2186
2187 indices = [(0,1),(1,2),(2,3),(3,0),(4,5),(5,6),(6,7),(7,4),\
2188 (0,4),(1,5),(2,6),(3,7)]
2189
2190 for l in indices:#{
2191 v0 = vs[l[0]]
2192 v1 = vs[l[1]]
2193
2194 cv_view_verts += [(v0[0],v0[1],v0[2])]
2195 cv_view_verts += [(v1[0],v1[1],v1[2])]
2196 cv_view_colours += [(0.5,0.5,0.5,0.5),(0.5,0.5,0.5,0.5)]
2197 #}
2198 #}
2199 elif bone.SR_data.collider == '2':#{
2200 v0 = b-a
2201 major_axis = 0
2202 largest = -1.0
2203
2204 for i in range(3):#{
2205 if abs(v0[i]) > largest:#{
2206 largest = abs(v0[i])
2207 major_axis = i
2208 #}
2209 #}
2210
2211 v1 = Vector((0,0,0))
2212 v1[major_axis] = 1.0
2213
2214 tx = Vector((0,0,0))
2215 ty = Vector((0,0,0))
2216
2217 cv_tangent_basis( v1, tx, ty )
2218 r = (abs(tx.dot( v0 )) + abs(ty.dot( v0 ))) * 0.25
2219 l = v0[ major_axis ] - r*2
2220
2221 p0 = obj.matrix_world@Vector( c + (a+b)*0.5 + v1*l*-0.5 )
2222 p1 = obj.matrix_world@Vector( c + (a+b)*0.5 + v1*l* 0.5 )
2223
2224 colour = [0.2,0.2,0.2,1.0]
2225 colour[major_axis] = 0.5
2226
2227 cv_draw_halfsphere( p0, -v1, ty, tx, r, colour )
2228 cv_draw_halfsphere( p1, v1, ty, tx, r, colour )
2229 cv_draw_line( p0+tx* r, p1+tx* r, colour )
2230 cv_draw_line( p0+tx*-r, p1+tx*-r, colour )
2231 cv_draw_line( p0+ty* r, p1+ty* r, colour )
2232 cv_draw_line( p0+ty*-r, p1+ty*-r, colour )
2233 #}
2234 else:#{
2235 continue
2236 #}
2237
2238 center = obj.matrix_world @ c
2239 if bone.SR_data.cone_constraint:#{
2240 vx = Vector([bone.SR_data.conevx[_] for _ in range(3)])
2241 vy = Vector([bone.SR_data.conevy[_] for _ in range(3)])
2242 va = Vector([bone.SR_data.coneva[_] for _ in range(3)])
2243 draw_cone_twist( center, vx, vy, va )
2244 #}
2245 #}
2246 #}
2247
2248 def cv_ent_gate( obj ):
2249 #{
2250 global cv_view_verts, cv_view_colours
2251
2252 if obj.type != 'MESH': return
2253
2254 mesh_data = obj.data.SR_data.ent_gate[0]
2255 data = obj.SR_data.ent_gate[0]
2256 dims = mesh_data.dimensions
2257
2258 vs = [None]*9
2259 c = Vector((0,0,dims[2]))
2260
2261 vs[0] = obj.matrix_world @ Vector((-dims[0],0.0,-dims[1]+dims[2]))
2262 vs[1] = obj.matrix_world @ Vector((-dims[0],0.0, dims[1]+dims[2]))
2263 vs[2] = obj.matrix_world @ Vector(( dims[0],0.0, dims[1]+dims[2]))
2264 vs[3] = obj.matrix_world @ Vector(( dims[0],0.0,-dims[1]+dims[2]))
2265 vs[4] = obj.matrix_world @ (c+Vector((-1,0,-2)))
2266 vs[5] = obj.matrix_world @ (c+Vector((-1,0, 2)))
2267 vs[6] = obj.matrix_world @ (c+Vector(( 1,0, 2)))
2268 vs[7] = obj.matrix_world @ (c+Vector((-1,0, 0)))
2269 vs[8] = obj.matrix_world @ (c+Vector(( 1,0, 0)))
2270
2271 indices = [(0,1),(1,2),(2,3),(3,0),(4,5),(5,6),(7,8)]
2272
2273 for l in indices:#{
2274 v0 = vs[l[0]]
2275 v1 = vs[l[1]]
2276 cv_view_verts += [(v0[0],v0[1],v0[2])]
2277 cv_view_verts += [(v1[0],v1[1],v1[2])]
2278 cv_view_colours += [(1,1,0,1),(1,1,0,1)]
2279 #}
2280
2281 sw = (0.4,0.4,0.4,0.2)
2282 if data.target != None:
2283 cv_draw_arrow( obj.location, data.target.location, sw )
2284 #}
2285
2286 def dijkstra( graph, start_node, target_node ):
2287 #{
2288 unvisited = [_ for _ in graph]
2289 shortest_path = {}
2290 previous_nodes = {}
2291
2292 for n in unvisited:
2293 shortest_path[n] = 9999999.999999
2294 shortest_path[start_node] = 0
2295
2296 while unvisited:#{
2297 current_min_node = None
2298 for n in unvisited:#{
2299 if current_min_node == None:
2300 current_min_node = n
2301 elif shortest_path[n] < shortest_path[current_min_node]:
2302 current_min_node = n
2303 #}
2304
2305 for branch in graph[current_min_node]:#{
2306 tentative_value = shortest_path[current_min_node]
2307 tentative_value += graph[current_min_node][branch]
2308 if tentative_value < shortest_path[branch]:#{
2309 shortest_path[branch] = tentative_value
2310 previous_nodes[branch] = current_min_node
2311 #}
2312 #}
2313
2314 unvisited.remove(current_min_node)
2315 #}
2316
2317 path = []
2318 node = target_node
2319 while node != start_node:#{
2320 path.append(node)
2321
2322 if node not in previous_nodes: return None
2323 node = previous_nodes[node]
2324 #}
2325
2326 # Add the start node manually
2327 path.append(start_node)
2328 return path
2329 #}
2330
2331 def node_graph( route_nodes ):
2332 #{
2333 graph = {}
2334 for n in route_nodes:
2335 graph[n.name] = {}
2336
2337 for i in range(len(route_nodes)-1):#{
2338 for j in range(i+1, len(route_nodes)):#{
2339 ni = route_nodes[i]
2340 nj = route_nodes[j]
2341
2342 v0 = ni.location - nj.location
2343
2344 gate = None
2345
2346 if ni.SR_data.ent_type == 'ent_gate':
2347 gate = ni
2348
2349 if nj.SR_data.ent_type == 'ent_gate':#{
2350 if gate: continue
2351 gate = nj
2352 #}
2353
2354 if gate:#{
2355 v1 = gate.matrix_world.to_3x3() @ Vector((0,-1,0))
2356 if gate.SR_data.ent_gate[0].target:
2357 if v1.dot(v0) > 0.0: continue
2358 else:
2359 if v1.dot(v0) < 0.0: continue
2360 #}
2361
2362 dist = v0.magnitude
2363
2364 if dist > 25.0: continue
2365 graph[route_nodes[i].name][route_nodes[j].name] = dist
2366 graph[route_nodes[j].name][route_nodes[i].name] = dist
2367 #}
2368 #}
2369
2370 return graph
2371 #}
2372
2373 def cv_draw_route( route, route_nodes ):
2374 #{
2375 pole = Vector((0.2,0.2,10))
2376 hat = Vector((1,8,0.2))
2377 cc = route.SR_data.ent_route[0].colour
2378
2379 cv_draw_ucube(route.matrix_world,cc,Vector((0.5,-7.5,6)),\
2380 Vector((0,-6.5,5.5)))
2381 cv_draw_ucube(route.matrix_world,cc,pole, Vector(( 0.5, 0.5,0)) )
2382 cv_draw_ucube(route.matrix_world,cc,pole, Vector(( 0.5,-13.5,0)) )
2383 cv_draw_ucube(route.matrix_world,cc,hat, Vector((-0.5,-6.5, 12)) )
2384 cv_draw_ucube(route.matrix_world,cc,hat, Vector((-0.5,-6.5,-1)) )
2385
2386 checkpoints = route.SR_data.ent_route[0].gates
2387 graph = node_graph( route_nodes )
2388
2389 for i in range(len(checkpoints)):#{
2390 gi = checkpoints[i].target
2391 gj = checkpoints[(i+1)%len(checkpoints)].target
2392
2393 if gi:#{
2394 dest = gi.SR_data.ent_gate[0].target
2395 if dest:
2396 cv_draw_line_dotted( gi.location, dest.location, cc )
2397 gi = dest
2398 #}
2399
2400 if gi==gj: continue # error?
2401 if not gi or not gj: continue
2402
2403 path = dijkstra( graph, gj.name, gi.name )
2404
2405 if path:#{
2406 for sj in range(len(path)-1):#{
2407 o0 = bpy.data.objects[ path[sj] ]
2408 o1 = bpy.data.objects[ path[sj+1] ]
2409 cv_draw_arrow(o0.location,o1.location,cc,1.5)
2410 #}
2411 #}
2412 else:#{
2413 cv_draw_line_dotted( gi.location, gj.location, cc )
2414 #}
2415 #}
2416 #}
2417
2418 def cv_draw():
2419 #{
2420 global cv_view_shader
2421 global cv_view_verts
2422 global cv_view_colours
2423 global cv_view_course_i
2424
2425 cv_view_course_i = 0
2426 cv_view_verts = []
2427 cv_view_colours = []
2428
2429 cv_view_shader.bind()
2430 gpu.state.depth_mask_set(False)
2431 gpu.state.line_width_set(2.0)
2432 gpu.state.face_culling_set('BACK')
2433 gpu.state.depth_test_set('LESS')
2434 gpu.state.blend_set('NONE')
2435
2436 route_nodes = []
2437 routes = []
2438
2439 for obj in bpy.context.collection.objects:#{
2440 if obj.type == 'ARMATURE':#{
2441 if obj.data.pose_position == 'REST':
2442 draw_skeleton_helpers( obj )
2443 #}
2444 else:#{
2445 ent_type = obj_ent_type( obj )
2446
2447 if ent_type == 'ent_gate':#{
2448 cv_ent_gate( obj )
2449 route_nodes += [obj]
2450 #}
2451 elif ent_type == 'ent_route_node':
2452 route_nodes += [obj]
2453 elif ent_type == 'ent_route':
2454 routes += [obj]
2455 #}
2456 #}
2457
2458 #cv_draw_route_map( route_nodes )
2459 for route in routes:#{
2460 cv_draw_route( route, route_nodes )
2461 #}
2462
2463 cv_draw_lines()
2464 return
2465 #}
2466
2467 classes = [ SR_INTERFACE, SR_MATERIAL_PANEL,\
2468 SR_COLLECTION_SETTINGS, SR_SCENE_SETTINGS, \
2469 SR_COMPILE, SR_COMPILE_THIS, SR_MIRROR_BONE_X,\
2470 \
2471 SR_OBJECT_ENT_GATE, SR_MESH_ENT_GATE, SR_OBJECT_ENT_SPAWN, \
2472 SR_OBJECT_ENT_ROUTE_ENTRY, SR_UL_ROUTE_NODE_LIST, \
2473 SR_OBJECT_ENT_ROUTE, SR_OT_ROUTE_LIST_NEW_ITEM,
2474 SR_OT_ROUTE_LIST_DEL_ITEM,\
2475 \
2476 SR_OBJECT_PROPERTIES, SR_LIGHT_PROPERTIES, SR_BONE_PROPERTIES,
2477 SR_MESH_PROPERTIES, SR_MATERIAL_PROPERTIES \
2478 ]
2479
2480 def register():
2481 #{
2482 for c in classes:
2483 bpy.utils.register_class(c)
2484
2485 bpy.types.Scene.SR_data = \
2486 bpy.props.PointerProperty(type=SR_SCENE_SETTINGS)
2487 bpy.types.Collection.SR_data = \
2488 bpy.props.PointerProperty(type=SR_COLLECTION_SETTINGS)
2489
2490 bpy.types.Object.SR_data = \
2491 bpy.props.PointerProperty(type=SR_OBJECT_PROPERTIES)
2492 bpy.types.Light.SR_data = \
2493 bpy.props.PointerProperty(type=SR_LIGHT_PROPERTIES)
2494 bpy.types.Bone.SR_data = \
2495 bpy.props.PointerProperty(type=SR_BONE_PROPERTIES)
2496 bpy.types.Mesh.SR_data = \
2497 bpy.props.PointerProperty(type=SR_MESH_PROPERTIES)
2498 bpy.types.Material.SR_data = \
2499 bpy.props.PointerProperty(type=SR_MATERIAL_PROPERTIES)
2500
2501 global cv_view_draw_handler
2502 cv_view_draw_handler = bpy.types.SpaceView3D.draw_handler_add(\
2503 cv_draw,(),'WINDOW','POST_VIEW')
2504 #}
2505
2506 def unregister():
2507 #{
2508 for c in classes:
2509 bpy.utils.unregister_class(c)
2510
2511 global cv_view_draw_handler
2512 bpy.types.SpaceView3D.draw_handler_remove(cv_view_draw_handler,'WINDOW')
2513 #}
2514
2515 # ---------------------------------------------------------------------------- #
2516 # #
2517 # QOI encoder #
2518 # #
2519 # ---------------------------------------------------------------------------- #
2520 # #
2521 # Transliteration of: #
2522 # https://github.com/phoboslab/qoi/blob/master/qoi.h #
2523 # #
2524 # Copyright (c) 2021, Dominic Szablewski - https://phoboslab.org #
2525 # SPDX-License-Identifier: MIT #
2526 # QOI - The "Quite OK Image" format for fast, lossless image compression #
2527 # #
2528 # ---------------------------------------------------------------------------- #
2529
2530 class qoi_rgba_t(Structure):
2531 #{
2532 _pack_ = 1
2533 _fields_ = [("r",c_uint8),
2534 ("g",c_uint8),
2535 ("b",c_uint8),
2536 ("a",c_uint8)]
2537 #}
2538
2539 QOI_OP_INDEX = 0x00 # 00xxxxxx
2540 QOI_OP_DIFF = 0x40 # 01xxxxxx
2541 QOI_OP_LUMA = 0x80 # 10xxxxxx
2542 QOI_OP_RUN = 0xc0 # 11xxxxxx
2543 QOI_OP_RGB = 0xfe # 11111110
2544 QOI_OP_RGBA = 0xff # 11111111
2545
2546 QOI_MASK_2 = 0xc0 # 11000000
2547
2548 def qoi_colour_hash( c ):
2549 #{
2550 return c.r*3 + c.g*5 + c.b*7 + c.a*11
2551 #}
2552
2553 def qoi_eq( a, b ):
2554 #{
2555 return (a.r==b.r) and (a.g==b.g) and (a.b==b.b) and (a.a==b.a)
2556 #}
2557
2558 def qoi_32bit( v ):
2559 #{
2560 return bytearray([ (0xff000000 & v) >> 24, \
2561 (0x00ff0000 & v) >> 16, \
2562 (0x0000ff00 & v) >> 8, \
2563 (0x000000ff & v) ])
2564 #}
2565
2566 def qoi_encode( img ):
2567 #{
2568 data = bytearray()
2569
2570 print(F"{' ':<30}",end='\r')
2571 print(F"[QOI] Encoding {img.name}.qoi[{img.size[0]},{img.size[1]}]",end='\r')
2572
2573 index = [ qoi_rgba_t() for _ in range(64) ]
2574
2575 # Header
2576 #
2577 data.extend( bytearray(c_uint32(0x66696f71)) )
2578 data.extend( qoi_32bit( img.size[0] ) )
2579 data.extend( qoi_32bit( img.size[1] ) )
2580 data.extend( bytearray(c_uint8(4)) )
2581 data.extend( bytearray(c_uint8(0)) )
2582
2583 run = 0
2584 px_prev = qoi_rgba_t()
2585 px_prev.r = c_uint8(0)
2586 px_prev.g = c_uint8(0)
2587 px_prev.b = c_uint8(0)
2588 px_prev.a = c_uint8(255)
2589
2590 px = qoi_rgba_t()
2591 px.r = c_uint8(0)
2592 px.g = c_uint8(0)
2593 px.b = c_uint8(0)
2594 px.a = c_uint8(255)
2595
2596 px_len = img.size[0] * img.size[1]
2597 paxels = [ int(min(max(_,0),1)*255) for _ in img.pixels ]
2598
2599 for px_pos in range( px_len ): #{
2600 idx = px_pos * img.channels
2601 nc = img.channels-1
2602
2603 px.r = paxels[idx+min(0,nc)]
2604 px.g = paxels[idx+min(1,nc)]
2605 px.b = paxels[idx+min(2,nc)]
2606 px.a = paxels[idx+min(3,nc)]
2607
2608 if qoi_eq( px, px_prev ): #{
2609 run += 1
2610
2611 if (run == 62) or (px_pos == px_len-1): #{
2612 data.extend( bytearray( c_uint8(QOI_OP_RUN | (run-1))) )
2613 run = 0
2614 #}
2615 #}
2616 else: #{
2617 if run > 0: #{
2618 data.extend( bytearray( c_uint8(QOI_OP_RUN | (run-1))) )
2619 run = 0
2620 #}
2621
2622 index_pos = qoi_colour_hash(px) % 64
2623
2624 if qoi_eq( index[index_pos], px ): #{
2625 data.extend( bytearray( c_uint8(QOI_OP_INDEX | index_pos)) )
2626 #}
2627 else: #{
2628 index[ index_pos ].r = px.r
2629 index[ index_pos ].g = px.g
2630 index[ index_pos ].b = px.b
2631 index[ index_pos ].a = px.a
2632
2633 if px.a == px_prev.a: #{
2634 vr = int(px.r) - int(px_prev.r)
2635 vg = int(px.g) - int(px_prev.g)
2636 vb = int(px.b) - int(px_prev.b)
2637
2638 vg_r = vr - vg
2639 vg_b = vb - vg
2640
2641 if (vr > -3) and (vr < 2) and\
2642 (vg > -3) and (vg < 2) and\
2643 (vb > -3) and (vb < 2):
2644 #{
2645 op = QOI_OP_DIFF | (vr+2) << 4 | (vg+2) << 2 | (vb+2)
2646 data.extend( bytearray( c_uint8(op) ))
2647 #}
2648 elif (vg_r > -9) and (vg_r < 8) and\
2649 (vg > -33) and (vg < 32 ) and\
2650 (vg_b > -9) and (vg_b < 8):
2651 #{
2652 op = QOI_OP_LUMA | (vg+32)
2653 delta = (vg_r+8) << 4 | (vg_b + 8)
2654 data.extend( bytearray( c_uint8(op) ) )
2655 data.extend( bytearray( c_uint8(delta) ))
2656 #}
2657 else: #{
2658 data.extend( bytearray( c_uint8(QOI_OP_RGB) ) )
2659 data.extend( bytearray( c_uint8(px.r) ))
2660 data.extend( bytearray( c_uint8(px.g) ))
2661 data.extend( bytearray( c_uint8(px.b) ))
2662 #}
2663 #}
2664 else: #{
2665 data.extend( bytearray( c_uint8(QOI_OP_RGBA) ) )
2666 data.extend( bytearray( c_uint8(px.r) ))
2667 data.extend( bytearray( c_uint8(px.g) ))
2668 data.extend( bytearray( c_uint8(px.b) ))
2669 data.extend( bytearray( c_uint8(px.a) ))
2670 #}
2671 #}
2672 #}
2673
2674 px_prev.r = px.r
2675 px_prev.g = px.g
2676 px_prev.b = px.b
2677 px_prev.a = px.a
2678 #}
2679
2680 # Padding
2681 for i in range(7):
2682 data.extend( bytearray( c_uint8(0) ))
2683 data.extend( bytearray( c_uint8(1) ))
2684 bytearray_align_to( data, 16, b'\x00' )
2685
2686 return data
2687 #}