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