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