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