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