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