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