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