yum-slop/TaSTT
Free self-hosted STT for VRChat.
git clone https://git.yummers.dev/yum-slop/TaSTT
3db7723
v0.20.0
1#!/usr/bin/env python3 2 3from functools import partial 4 5import argparse 6import copy 7import enum 8import math 9import os 10import pickle 11import random 12import sys 13import typing 14# python3 -m pip install pyyaml 15# License: MIT. 16import yaml 17 18import multiprocessing as mp 19 20WRITE_DEFAULTS_ANIM_TEMPLATE = """ 21%YAML 1.1 22%TAG !u! tag:unity3d.com,2011: 23--- !u!74 &7400000 24AnimationClip: 25m_ObjectHideFlags: 0 26m_CorrespondingSourceObject: {fileID: 0} 27m_PrefabInstance: {fileID: 0} 28m_PrefabAsset: {fileID: 0} 29m_Name: TaSTT_Reset_Animations 30serializedVersion: 6 31m_Legacy: 0 32m_Compressed: 0 33m_UseHighQualityCurve: 1 34m_RotationCurves: [] 35m_CompressedRotationCurves: [] 36m_EulerCurves: [] 37m_PositionCurves: [] 38m_ScaleCurves: [] 39m_FloatCurves: 40- curve: 41serializedVersion: 2 42m_Curve: 43- serializedVersion: 3 44time: 0 45value: 0 46inSlope: 0 47outSlope: 0 48tangentMode: 136 49weightedMode: 0 50inWeight: 0 51outWeight: 0 52m_PreInfinity: 2 53m_PostInfinity: 2 54m_RotationOrder: 4 55attribute: REPLACEME_ATTRIBUTE 56path: REPLACEME_PATH 57classID: 137 58script: {fileID: 0} 59m_PPtrCurves: [] 60m_SampleRate: 60 61m_WrapMode: 0 62m_Bounds: 63m_Center: {x: 0, y: 0, z: 0} 64m_Extent: {x: 0, y: 0, z: 0} 65m_ClipBindingConstant: 66genericBindings: 67- serializedVersion: 2 68path: 2794480623 69attribute: 2284639795 70script: {fileID: 0} 71typeID: 137 72customType: 22 73isPPtrCurve: 0 74pptrCurveMapping: [] 75m_AnimationClipSettings: 76serializedVersion: 2 77m_AdditiveReferencePoseClip: {fileID: 0} 78m_AdditiveReferencePoseTime: 0 79m_StartTime: 0 80m_StopTime: 0 81m_OrientationOffsetY: 0 82m_Level: 0 83m_CycleOffset: 0 84m_HasAdditiveReferencePose: 0 85m_LoopTime: 1 86m_LoopBlend: 0 87m_LoopBlendOrientation: 0 88m_LoopBlendPositionY: 0 89m_LoopBlendPositionXZ: 0 90m_KeepOriginalOrientation: 0 91m_KeepOriginalPositionY: 1 92m_KeepOriginalPositionXZ: 0 93m_HeightFromFeet: 0 94m_Mirror: 0 95m_EditorCurves: 96- curve: 97serializedVersion: 2 98m_Curve: 99- serializedVersion: 3 100time: 0 101value: 0 102inSlope: 0 103outSlope: 0 104tangentMode: 136 105weightedMode: 0 106inWeight: 0 107outWeight: 0 108m_PreInfinity: 2 109m_PostInfinity: 2 110m_RotationOrder: 4 111attribute: REPLACEME_ATTRIBUTE 112path: REPLACEME_PATH 113classID: 137 114script: {fileID: 0} 115m_EulerEditorCurves: [] 116m_HasGenericRootTransform: 0 117m_HasMotionFloatCurves: 0 118m_Events: [] 119""" [ 1 : ][ : - 1 ] 120 121METADATA_TEMPLATE = """ 122fileFormatVersion: 2 123guid: REPLACEME_GUID 124NativeFormatImporter: 125externalObjects: {} 126mainObjectFileID: 7400000 127userData: 128assetBundleName: 129assetBundleVariant: 130""" [ 1 : ][ : - 1 ] 131 132ANIMATION_STATE_TEMPLATE = """ 133--- !u!1102 &110200000 134AnimatorState: 135serializedVersion: 6 136m_ObjectHideFlags: 1 137m_CorrespondingSourceObject: {fileID: 0} 138m_PrefabInstance: {fileID: 0} 139m_PrefabAsset: {fileID: 0} 140m_Name: REPLACEME_ANIMATION_NAME 141m_Speed: 1 142m_CycleOffset: 0 143m_Transitions: [] 144m_StateMachineBehaviours: [] 145m_Position: {x: 50, y: 50, z: 0} 146m_IKOnFeet: 0 147m_WriteDefaultValues: 0 148m_Mirror: 0 149m_SpeedParameterActive: 0 150m_MirrorParameterActive: 0 151m_CycleOffsetParameterActive: 0 152m_TimeParameterActive: 0 153m_Motion: {} 154m_Tag: 155m_SpeedParameter: 156m_MirrorParameter: 157m_CycleOffsetParameter: 158m_TimeParameter: 159""" [ 1 : ][ : - 1 ] 160 161TRANSITION_TEMPLATE = """ 162--- !u!1101 &110100000 163AnimatorStateTransition: 164m_ObjectHideFlags: 1 165m_CorrespondingSourceObject: {fileID: 0} 166m_PrefabInstance: {fileID: 0} 167m_PrefabAsset: {fileID: 0} 168m_Name: 169m_Conditions: [] 170m_DstStateMachine: {fileID: 0} 171m_DstState: {fileID: 0} 172m_Solo: 0 173m_Mute: 0 174m_IsExit: 0 175serializedVersion: 3 176m_TransitionDuration: 0 177m_TransitionOffset: 0 178m_ExitTime: 0.0 179m_HasExitTime: 0 180m_HasFixedDuration: 1 181m_InterruptionSource: 2 182m_OrderedInterruption: 1 183m_CanTransitionToSelf: 1 184""" [ 1 : ][ : - 1 ] 185 186BLEND_TREE_TEMPLATE = """ 187--- !u!206 &1071664566462684110 188BlendTree: 189m_ObjectHideFlags: 1 190m_CorrespondingSourceObject: {fileID: 0} 191m_PrefabInstance: {fileID: 0} 192m_PrefabAsset: {fileID: 0} 193m_Name: REPLACEME_BLEND_TREE_NAME 194m_Childs: 195- serializedVersion: 2 196m_Motion: {fileID: 7400000, guid: REPLACEME_GUID_LO, type: 2} 197m_Threshold: -1 198m_Position: {x: 0, y: 0} 199m_TimeScale: 1 200m_CycleOffset: 0 201m_DirectBlendParameter: REPLACEME_BLEND_PARAMETER 202m_Mirror: 0 203- serializedVersion: 2 204m_Motion: {fileID: 7400000, guid: REPLACEME_GUID_HI, type: 2} 205m_Threshold: 1 206m_Position: {x: 0, y: 0} 207m_TimeScale: 1 208m_CycleOffset: 0 209m_DirectBlendParameter: REPLACEME_BLEND_PARAMETER 210m_Mirror: 0 211m_BlendParameter: REPLACEME_BLEND_PARAMETER 212m_BlendParameterY: REPLACEME_BLEND_PARAMETER 213m_MinThreshold: -1 214m_MaxThreshold: 1 215m_UseAutomaticThresholds: 0 216m_NormalizedBlendValues: 0 217m_BlendType: 0 218""" [ 1 : ][ : - 1 ] 219 220class Metadata : 221def __init__ ( self ) : 222self . guid = "%032x" % random . randrange ( 16 ** 32 ) 223 224def load ( self , path ) : 225if not path . endswith ( ".meta" ) : 226path = path + ".meta" 227 228self . guid = None 229with open ( path , "r" , encoding = "utf-8" ) as f : 230for line in f : 231if line . startswith ( "guid" ) : 232self . guid = line . split ()[ 1 ] 233 234def loadOrCreate ( self , path , guid_map ) : 235if not path . endswith ( ".meta" ) : 236path = path + ".meta" 237 238if os . path . exists ( path ) : 239self . load ( path ) 240return 241 242self . persist ( path , guid_map ) 243 244def persist ( self , path , guid_map ) : 245with open ( path , "w" , encoding = "utf-8" ) as f : 246f . write ( str ( self )) 247 248guid_map [ self . guid ] = path 249guid_map [ path ] = self . guid 250 251def __str__ ( self ) : 252return METADATA_TEMPLATE . replace ( "REPLACEME_GUID" , self . guid ) 253 254class Node : 255def __init__ ( self ) : 256# Optional. In Unity, this is the fileID of an object. Not all YAML 257# mappings have an anchor. 258self . anchor = None 259 260# Pointer to the Node containing this one. 261self . parent = None 262 263class Sequence ( Node ) : 264def __init__ ( self ) : 265super () . __init__ () 266self . sequence = [] 267 268def copy ( self ) : 269new = Sequence () 270new . anchor = self . anchor 271new . parent = self . parent 272 273for v in self . sequence : 274if hasattr ( v , "copy" ) : 275new . sequence . append ( v . copy ()) 276new . sequence [ - 1 ] . parent = new 277else : 278new . sequence . append ( v ) 279 280return new 281 282def prettyPrint ( self , first_indent = None , leading_newline = None ) : 283depth = 0 284p = self . parent 285while p != None : 286depth += 1 287p = p . parent 288indent = " " * depth 289 290lines = [] 291first = True 292for item in self . sequence : 293cur_indent = indent 294if first : 295if first_indent != None : 296cur_indent = first_indent 297first = False 298if hasattr ( item , "prettyPrint" ) : 299lines . append ( "{}- {}" . format ( cur_indent , item . prettyPrint ( first_indent = "" , leading_newline = False ))) 300else : 301lines . append ( "{}- {}" . format ( cur_indent , item )) 302 303if len ( lines ) == 0 : 304return "[]" 305 306return " \n " + ' \n ' . join ( lines ) 307 308def __str__ ( self ) : 309return self . prettyPrint () 310 311def addChildMapping ( self , anchor = None , add_to_head = False ) : 312child = Mapping () 313child . anchor = anchor 314child . parent = self 315child . sequence = [] 316 317if add_to_head : 318self . sequence = [ child ] + self . sequence 319else : 320self . sequence . append ( child ) 321 322return child 323 324def addChildSequence ( self , anchor = None ) : 325child = Sequence () 326child . anchor = anchor 327child . parent = self 328child . sequence = [] 329 330self . sequence . append ( child ) 331 332return child 333 334def forEach ( self , cb ) : 335for k in self . sequence : 336cb ( k ) 337 338class Mapping ( Node ) : 339def __init__ ( self ) : 340super () . __init__ () 341self . mapping = {} 342 343def copy ( self ) : 344new = Mapping () 345new . anchor = self . anchor 346new . parent = self . parent 347 348for k , v in self . mapping . items () : 349if hasattr ( v , "copy" ) : 350new . mapping [ k ] = v . copy () 351new . mapping [ k ] . parent = new 352else : 353new . mapping [ k ] = v 354 355return new 356 357def prettyPrint ( self , first_indent = None , leading_newline = True ) : 358depth = 0 359p = self . parent 360while p != None : 361depth += 1 362p = p . parent 363indent = " " * depth 364 365lines = [] 366first = True 367for k , v in self . mapping . items () : 368cur_indent = indent 369if first : 370if first_indent != None : 371cur_indent = first_indent 372first = False 373lines . append ( "{}{}: {}" . format ( cur_indent , k , v )) 374 375result = ' \n ' . join ( lines ) 376 377# Inline 1-item mappings, matching Unity behavior. 378if len ( self . mapping . keys ()) == 1 and len ( result . split ( " \n " )) == 1 : 379if first_indent == None : 380return self . prettyPrint ( first_indent = "" ) 381return "{" + lines [ 0 ] + "}" 382 383# Empty mappings are represented by '{}'. If we don't do this, Unity 384# will assume that they are Sequences and get very sad. 385if len ( self . mapping . keys ()) == 0 : 386return "{}" 387 388if leading_newline : 389result = " \n " + result 390 391return result 392 393def __str__ ( self ) : 394return self . prettyPrint () 395 396def addChildMapping ( self , key , anchor = None ) : 397child = Mapping () 398child . anchor = anchor 399child . parent = self 400child . mapping = {} 401 402self . mapping [ key ] = child 403 404return child 405 406def addChildSequence ( self , key , anchor = None ) : 407child = Sequence () 408child . anchor = anchor 409child . parent = self 410child . mapping = {} 411 412self . mapping [ key ] = child 413 414return child 415 416def forEach ( self , cb ) : 417for k , v in self . mapping . items () : 418cb ( v ) 419 420class UnityDocument ( Mapping ) : 421def __init__ ( self ) : 422super () . __init__ () 423self . class_id = None 424 425def __str__ ( self ) : 426return super () . __str__ () 427 428def copy ( self ) : 429result = super () . copy () 430result . class_id = self . class_id 431return result 432 433# Class representing a Unity AnimatorController. Implements manipulations, like 434# merging and reanchoring. 435class UnityAnimator () : 436def __init__ ( self ) : 437self . nodes = [] 438self . id_to_node = {} 439self . next_id = 1000 * 1000 440 441def __str__ ( self ) : 442return unityYamlToString ( self . nodes ) 443 444def addNodes ( self , nodes ) : 445for node in nodes : 446self . nodes . append ( node ) 447anchor = node . anchor 448if anchor == None : 449anchor = self . allocateId () 450if anchor in self . id_to_node : 451raise Exception ( "Duplicate anchor: {}, node 1: {}, node 2: {}" . format ( anchor , str ( node ) , str ( self . id_to_node [ anchor ]))) 452self . id_to_node [ anchor ] = node 453 454if int ( anchor ) > self . next_id : 455self . next_id = int ( anchor ) + 1 456# I don't know why but this fixes a bug in the `fixWriteDefaults` 457# codepath: two documents wind up with the same anchor. 458self . next_id += 1 459 460def allocateId ( self ) -> int : 461result = self . next_id 462self . next_id += 1 463return result 464 465# Checks if `old_id` is in `self.id_mapping`, and if so, returns the 466# already-generated ID. Otherwise this allocates a new ID and 467# records it in `self.id_mapping`. 468def mapId ( self , old_id : str ) -> int : 469new_id = None 470if old_id in self . id_mapping . keys () : 471new_id = self . id_mapping [ old_id ] 472else : 473new_id = self . allocateId () 474self . id_mapping [ old_id ] = new_id 475return new_id 476 477# Recursively iterate every mapping under `node` and assign new IDs to 478# every identifier. Mappings are recorded in `self.id_mapping`. 479def mergeIterator ( self , node ) : 480if hasattr ( node , "mapping" ) : 481# Don't relabel anything that's defined in an external file. 482# TODO(yum) do this. 483if 'fileID' in node . mapping and not 'guid' in node . mapping : 484if node . mapping [ 'fileID' ] != '0' : 485old_id = node . mapping [ 'fileID' ] 486new_id = self . mapId ( old_id ) 487node . mapping [ 'fileID' ] = str ( new_id ) 488if hasattr ( node , "forEach" ) : 489node . forEach ( self . mergeIterator ) 490 491# Delete any key-value pairs where the value == the value. 492def scrubReferencesByValue ( self , node , values : typing . Set [ str ]) : 493if hasattr ( node , "mapping" ) : 494node . mapping = { k : v for k , v in node . mapping . items () if v not in values } 495if hasattr ( node , "forEach" ) : 496node . forEach ( partial ( self . scrubReferencesByValue , values = values )) 497 498def peekNodeOfClass ( self , classId ) : 499for node in self . nodes : 500if node . class_id == classId : 501return node 502return None 503 504def popNodeOfClass ( self , classId ) : 505result = None 506for node in self . nodes : 507if node . class_id == classId : 508result = node 509self . nodes . remove ( result ) 510break 511if result : 512del self . id_to_node [ result . anchor ] 513return result 514 515def pushNode ( self , node ) : 516self . nodes . append ( node ) 517self . id_to_node [ node . anchor ] = node 518 519# Merges two animator controllers and returns the result. Any identifiers 520# in the animators are reassigned in a new namespace. The mappings from old 521# identifiers to new identifiers are recorded in `self.id_mapping0` and 522# `self.id_mapping1`. 523def mergeAnimatorControllers ( self , ctrl0 , ctrl1 ) : 524ctrl0 = copy . deepcopy ( ctrl0 ) 525ctrl1 = copy . deepcopy ( ctrl1 ) 526 527self . id_mapping0 = {} 528self . id_mapping1 = {} 529 530p0 = ctrl0 . mapping [ 'AnimatorController' ] . mapping [ 'm_AnimatorParameters' ] 531p1 = ctrl1 . mapping [ 'AnimatorController' ] . mapping [ 'm_AnimatorParameters' ] 532 533a0 = ctrl0 . mapping [ 'AnimatorController' ] . mapping [ 'm_AnimatorLayers' ] 534a1 = ctrl1 . mapping [ 'AnimatorController' ] . mapping [ 'm_AnimatorLayers' ] 535 536self . id_mapping = self . id_mapping0 537p0 . forEach ( self . mergeIterator ) 538a0 . forEach ( self . mergeIterator ) 539 540# Hack to prevent ctrl1 from getting a new ID for the animator. 541# TODO(yum) delete this? 542#del self.class_to_next_id['91'] 543 544self . id_mapping = self . id_mapping1 545p1 . forEach ( self . mergeIterator ) 546a1 . forEach ( self . mergeIterator ) 547 548p0 . sequence += p1 . sequence 549a0 . sequence += a1 . sequence 550 551for elm in p0 . sequence : 552elm . mapping [ 'm_Controller' ] . mapping [ 'fileID' ] = ctrl0 . anchor 553for elm in a0 . sequence : 554elm . mapping [ 'm_Controller' ] . mapping [ 'fileID' ] = ctrl0 . anchor 555 556return ctrl0 557 558def merge ( self , other ) : 559ctrl0 = self . popNodeOfClass ( '91' ) 560ctrl1 = other . popNodeOfClass ( '91' ) 561# Merge animators and populate `self.id_mapping0` and 562# `self.id_mapping1. 563merged_anim = self . mergeAnimatorControllers ( ctrl0 , ctrl1 ) 564 565# Mapping from class ID (string) to new class ID (int) 566self . id_mapping = self . id_mapping0 567for node in self . nodes : 568new_id = self . mapId ( node . anchor ) 569node . anchor = str ( new_id ) 570node . forEach ( self . mergeIterator ) 571 572self . id_mapping = self . id_mapping1 573for node in other . nodes : 574new_id = self . mapId ( node . anchor ) 575node . anchor = str ( new_id ) 576node . forEach ( self . mergeIterator ) 577 578nodes = self . nodes 579self . nodes = [] 580self . id_to_node = {} 581self . pushNode ( merged_anim ) 582self . addNodes ( nodes ) 583self . addNodes ( other . nodes ) 584 585# TODO(yum) support overwriting duplicates 586def addParameter ( self , param_name , param_type ) : 587unity_type = None 588if param_type == float : 589unity_type = '1' 590elif param_type == int : 591unity_type = '3' 592elif param_type == bool : 593unity_type = '4' 594 595anim = self . peekNodeOfClass ( '91' ) 596params = anim . mapping [ 'AnimatorController' ] . mapping [ 'm_AnimatorParameters' ] 597 598for p in params . sequence : 599if p . mapping [ 'm_Name' ] == param_name : 600return 601 602param = params . addChildMapping () 603param . mapping [ 'm_Name' ] = param_name 604param . mapping [ 'm_Type' ] = unity_type 605param . mapping [ 'm_DefaultFloat' ] = '0' 606param . mapping [ 'm_DefaultInt' ] = '0' 607param . mapping [ 'm_DefaultBool' ] = '0' 608ctrl = param . addChildMapping ( 'm_Controller' ) 609ctrl . mapping [ 'fileID' ] = anim . anchor 610 611def addLayer ( self , layer_name , add_to_head = False , weight : float = 1.0 ) -> UnityDocument : 612# Add layer to controller 613anim = self . peekNodeOfClass ( '91' ) 614layers = anim . mapping [ 'AnimatorController' ] . mapping [ 'm_AnimatorLayers' ] 615layer = layers . addChildMapping ( add_to_head = add_to_head ) 616layer . mapping [ 'serializedVersion' ] = '5' 617layer . mapping [ 'm_Name' ] = layer_name 618new_id = self . allocateId () 619layer . addChildMapping ( 'm_StateMachine' ) . mapping [ 'fileID' ] = str ( new_id ) 620layer . addChildMapping ( 'm_Mask' ) . mapping [ 'fileID' ] = '0' 621layer . addChildSequence ( 'm_Motions' ) 622layer . addChildSequence ( 'm_Behaviours' ) 623layer . mapping [ 'm_BlendingMode' ] = '0' 624layer . mapping [ 'm_SyncedLayerIndex' ] = '-1' 625layer . mapping [ 'm_DefaultWeight' ] = str ( weight ) 626layer . mapping [ 'm_IKPass' ] = '0' 627layer . mapping [ 'm_SyncedLayerAffectsTiming' ] = '0' 628layer . addChildMapping ( 'm_Controller' ) . mapping [ 'fileID' ] = anim . anchor 629 630# Create layer object 631layer = UnityDocument () 632layer . class_id = "1107" 633layer . anchor = str ( new_id ) 634mach = layer . addChildMapping ( 'AnimatorStateMachine' ) 635 636mach . mapping [ 'serializedVersion' ] = '6' 637 638mach . mapping [ 'm_ObjectHideFlags' ] = '1' 639mach . addChildMapping ( 'm_CorrespondingSourceObject' ) . mapping [ 'fileID' ] = '0' 640mach . addChildMapping ( 'm_PrefabInstance' ) . mapping [ 'fileID' ] = '0' 641mach . addChildMapping ( 'm_PrefabAsset' ) . mapping [ 'fileID' ] = '0' 642mach . mapping [ 'm_Name' ] = layer_name 643mach . addChildSequence ( 'm_ChildStates' ) 644mach . addChildSequence ( 'm_ChildStateMachines' ) 645mach . addChildSequence ( 'm_AnyStateTransitions' ) 646mach . addChildSequence ( 'm_EntryTransitions' ) 647mach . addChildMapping ( 'm_StateMachineTransitions' ) 648mach . addChildSequence ( 'm_StateMachineBehaviours' ) 649pos = mach . addChildMapping ( 'm_AnyStatePosition' ) 650pos . mapping [ 'x' ] = '50' 651pos . mapping [ 'y' ] = '20' 652pos . mapping [ 'z' ] = '0' 653pos = mach . addChildMapping ( 'm_EntryPosition' ) 654pos . mapping [ 'x' ] = '50' 655pos . mapping [ 'y' ] = '120' 656pos . mapping [ 'z' ] = '0' 657pos = mach . addChildMapping ( 'm_ExitPosition' ) 658pos . mapping [ 'x' ] = '800' 659pos . mapping [ 'y' ] = '120' 660pos . mapping [ 'z' ] = '0' 661pos = mach . addChildMapping ( 'm_ParentStateMachinePosition' ) 662pos . mapping [ 'x' ] = '800' 663pos . mapping [ 'y' ] = '20' 664pos . mapping [ 'z' ] = '0' 665mach . addChildMapping ( 'm_DefaultState' ) 666 667self . nodes . append ( layer ) 668return layer 669 670def addAnimatorState ( self , layer , state_name , is_default_state = False , 671dx = 0 , dy = 0 ) -> UnityDocument : 672# Create animation state 673parser = UnityParser () 674parser . parse ( ANIMATION_STATE_TEMPLATE ) 675new_anim = UnityAnimator () 676new_anim . addNodes ( parser . nodes ) 677node = new_anim . nodes [ 0 ] 678 679new_id = self . allocateId () 680node . class_id = "1102" 681node . anchor = str ( new_id ) 682state = node . mapping [ 'AnimatorState' ] 683state . mapping [ 'm_Name' ] = state_name 684#state.mapping['m_Motion'].mapping['guid'] = anim_guid 685self . nodes . append ( node ) 686 687# Add state to layer 688child_state = layer . mapping [ 'AnimatorStateMachine' ] . mapping [ 'm_ChildStates' ] . addChildMapping () 689child_state . mapping [ 'serializedVersion' ] = '1' 690child_state . addChildMapping ( 'm_State' ) . mapping [ 'fileID' ] = str ( new_id ) 691state_pos = child_state . addChildMapping ( 'm_Position' ) 692state_pos . mapping [ 'x' ] = str ( 280 + dx ) 693state_pos . mapping [ 'y' ] = str ( 80 + dy ) 694state_pos . mapping [ 'z' ] = '0' 695 696if is_default_state : 697layer . mapping [ 'AnimatorStateMachine' ] . mapping [ 'm_DefaultState' ] . mapping [ 'fileID' ] = str ( new_id ) 698 699return node 700 701def setAnimatorStateAnimation ( self , anim_state , anim_guid ) : 702anim_state . mapping [ 'AnimatorState' ] . mapping [ 'm_Motion' ] . mapping [ 'guid' ] = anim_guid 703anim_state . mapping [ 'AnimatorState' ] . mapping [ 'm_Motion' ] . mapping [ 'fileID' ] = '7400000' 704anim_state . mapping [ 'AnimatorState' ] . mapping [ 'm_Motion' ] . mapping [ 'type' ] = '2' 705 706# Adds a blend tree which uses the parameter named `param_name` to blend 707# between anim_lo and anim_hi. Also creates the corresponding animation 708# state. 709def addAnimatorBlendTree ( self , layer , state_name , param_name , 710anim_guid_lo , anim_guid_hi , dx = 0 , dy = 0 , 711lo_threshold = - 1.0 , hi_threshold = 1.0 , 712is_default_state = False ) -> UnityDocument : 713# Create the blend tree. 714parser = UnityParser () 715parser . parse ( BLEND_TREE_TEMPLATE ) 716new_anim = UnityAnimator () 717new_anim . addNodes ( parser . nodes ) 718node = new_anim . nodes [ 0 ] 719 720new_id = self . allocateId () 721node . class_id = "206" 722node . anchor = str ( new_id ) 723tree = node . mapping [ 'BlendTree' ] 724tree . mapping [ 'm_Name' ] = state_name 725# Low animation 726tree . mapping [ 'm_Childs' ] . sequence [ 0 ] . mapping [ 'm_Motion' ] . mapping [ 'guid' ] = anim_guid_lo 727tree . mapping [ 'm_Childs' ] . sequence [ 0 ] . mapping [ 'm_DirectBlendParameter' ] = param_name 728tree . mapping [ 'm_Childs' ] . sequence [ 0 ] . mapping [ 'm_Threshold' ] = str ( lo_threshold ) 729# High animation 730tree . mapping [ 'm_Childs' ] . sequence [ 1 ] . mapping [ 'm_Motion' ] . mapping [ 'guid' ] = anim_guid_hi 731tree . mapping [ 'm_Childs' ] . sequence [ 1 ] . mapping [ 'm_DirectBlendParameter' ] = param_name 732tree . mapping [ 'm_Childs' ] . sequence [ 1 ] . mapping [ 'm_Threshold' ] = str ( hi_threshold ) 733 734tree . mapping [ 'm_BlendParameter' ] = param_name 735tree . mapping [ 'm_BlendParameterY' ] = param_name 736 737self . nodes . append ( node ) 738 739# Create the corresponding animation state. 740anim_state = self . addAnimatorState ( layer , state_name , is_default_state , dx = dx , dy = 741dy ) 742anim_state . mapping [ 'AnimatorState' ] . mapping [ 'm_Motion' ] . mapping [ 'fileID' ] = node . anchor 743 744return anim_state 745 746def addTransition ( self , dst_state , dur_s = 0.0 ) : 747# Create animation state 748parser = UnityParser () 749parser . parse ( TRANSITION_TEMPLATE ) 750new_transition = UnityAnimator () 751new_transition . addNodes ( parser . nodes ) 752node = new_transition . nodes [ 0 ] 753 754new_id = self . allocateId () 755node . class_id = "1101" 756node . anchor = str ( new_id ) 757state = node . mapping [ 'AnimatorStateTransition' ] 758state . mapping [ 'm_DstState' ] . mapping [ 'fileID' ] = copy . copy ( dst_state . anchor ) 759state . mapping [ 'm_TransitionDuration' ] = dur_s 760self . nodes . append ( node ) 761 762return node 763 764def fixWriteDefaults ( self , guid_map , generated_anim_path ) : 765# TODO(yum) we should have an Animation class which encapsulates all 766# this stuff. 767parser = UnityParser () 768parser . parse ( WRITE_DEFAULTS_ANIM_TEMPLATE ) 769new_anim = UnityAnimator () 770new_anim . addNodes ( parser . nodes ) 771 772new_clip = new_anim . peekNodeOfClass ( '74' ) . mapping [ 'AnimationClip' ] 773curve_template = new_clip . mapping [ 'm_FloatCurves' ] . sequence [ 0 ] 774new_clip . mapping [ 'm_FloatCurves' ] . sequence = [] 775new_clip . mapping [ 'm_EditorCurves' ] . sequence = [] 776 777# Keep track of the (attribute, path) tuples we've already set to avoid 778# animating the same thing twice. 779attributes_set = set () 780 781animator_state_id = '1102' 782for node in self . nodes : 783if node . class_id != animator_state_id : 784continue 785 786# Looking at an animator state. 787if node . mapping [ 'AnimatorState' ] . mapping [ 'm_WriteDefaultValues' ] != '1' : 788continue 789 790# Disable write defaults. 791node . mapping [ 'AnimatorState' ] . mapping [ 'm_WriteDefaultValues' ] = '0' 792 793# Looking at an animator state with write defaults. 794motion = node . mapping [ 'AnimatorState' ] . mapping [ 'm_Motion' ] 795# Some animations have write defaults but don't trigger an 796# animation. No idea what that's about. For now, just ignore. 797if not 'guid' in motion . mapping : 798continue 799guid = motion . mapping [ 'guid' ] 800 801# Again, not really sure what's going on here, just ignore and 802# revisit if we hit problems. 803if not guid in guid_map . keys () : 804continue 805 806# OK, we found an animation with write defaults, and we know where 807# the animation lives. Crack it open and see what it's writing. 808animation_path = guid_map [ guid ] 809( "Animation has write defaults: {}" . format ( animation_path ) , file = sys . stderr ) 810parser = UnityParser () 811parser . parseFile ( animation_path ) 812anim = UnityAnimator () 813anim . addNodes ( parser . nodes ) 814 815clip = anim . peekNodeOfClass ( '74' ) 816 817for curve in clip . mapping [ 'AnimationClip' ] . mapping [ 'm_FloatCurves' ] . sequence : 818attr = curve . mapping [ 'attribute' ] 819path = curve . mapping [ 'path' ] 820if ( attr , path ) in attributes_set : 821continue 822#print("Fix attr/path {}/{}".format(attr, path), file=sys.stderr) 823attributes_set . add (( attr , path )) 824 825new_curve = curve_template . copy () 826new_curve . mapping [ 'attribute' ] = attr 827new_curve . mapping [ 'path' ] = path 828 829new_clip . mapping [ 'm_FloatCurves' ] . sequence . append ( new_curve ) 830new_clip . mapping [ 'm_EditorCurves' ] . sequence . append ( new_curve ) 831 832#print("len float curves: {}".format(len(new_clip.mapping['m_FloatCurves'].sequence)), file=sys.stderr) 833 834def generateOffAnimationForGuid ( self , guid_map , generated_anim_dir , guid ) : 835# Looking at an animation. 836if not guid in guid_map . keys () : 837return 838 839animation_path = guid_map [ guid ] 840( "Checking animation at {}" . format ( animation_path ) , file = sys . stderr ) 841parser = UnityParser () 842parser . parseFile ( animation_path ) 843anim = UnityAnimator () 844anim . addNodes ( parser . nodes ) 845 846clip = anim . peekNodeOfClass ( '74' ) 847 848has_nonzero = False 849curve_members = [ "m_FloatCurves" , "m_EditorCurves" ] 850for memb in curve_members : 851for curve in clip . mapping [ 'AnimationClip' ] . mapping [ memb ] . sequence : 852attr = curve . mapping [ 'attribute' ] 853path = curve . mapping [ 'path' ] 854 855for m_curve in curve . mapping [ 'curve' ] . mapping [ 'm_Curve' ] . sequence : 856if m_curve . mapping [ 'value' ] != '0' : 857has_nonzero = True 858m_curve . mapping [ 'value' ] = '0' 859 860if not has_nonzero : 861( "Animation does not set anything nonzero" ) 862return 863 864( "Animation sets things nonzero, fixing" ) 865 866new_anim_path = "OFF_{}" . format ( os . path . basename ( animation_path )) 867new_anim_path = "{}/{}" . format ( generated_anim_dir , new_anim_path ) 868 869with open ( new_anim_path , "w" , encoding = "utf-8" ) as f : 870f . write ( str ( anim )) 871 872meta = Metadata () 873with open ( new_anim_path + ".meta" , "w" , encoding = "utf-8" ) as f : 874f . write ( str ( meta )) 875 876def generateOffAnimationsAnimStates ( self , guid_map , generated_anim_dir ) : 877animator_state_id = '1102' 878for node in self . nodes : 879if node . class_id != animator_state_id : 880continue 881 882# Looking at an animation state. 883motion = node . mapping [ 'AnimatorState' ] . mapping [ 'm_Motion' ] 884if not 'guid' in motion . mapping : 885continue 886guid = motion . mapping [ 'guid' ] 887self . generateOffAnimationForGuid ( guid_map , generated_anim_dir , guid ) 888 889 890def generateOffAnimationsBlendTrees ( self , guid_map , generated_anim_dir ) : 891animator_state_id = '206' 892for node in self . nodes : 893if node . class_id != animator_state_id : 894continue 895 896# Looking at an animation state. 897for child in node . mapping [ 'BlendTree' ] . mapping [ 'm_Childs' ] . sequence : 898motion = child . mapping [ 'm_Motion' ] 899 900if not 'guid' in motion . mapping : 901continue 902guid = motion . mapping [ 'guid' ] 903self . generateOffAnimationForGuid ( guid_map , generated_anim_dir , guid ) 904 905def generateOffAnimations ( self , guid_map , generated_anim_dir ) : 906self . generateOffAnimationsAnimStates ( guid_map , generated_anim_dir ) 907self . generateOffAnimationsBlendTrees ( guid_map , generated_anim_dir ) 908 909def addTransitionBooleanCondition ( self , from_state , trans , param , branch ) : 910# Populate the transition's condition logic. 911cond = trans . mapping [ 'AnimatorStateTransition' ] . mapping [ 'm_Conditions' ] . addChildMapping () 912if branch : 913cond . mapping [ 'm_ConditionMode' ] = '1' 914else : 915cond . mapping [ 'm_ConditionMode' ] = '2' 916cond . mapping [ 'm_ConditionEvent' ] = param 917cond . mapping [ 'm_EventThreshold' ] = '0' 918# Register the transition with the `from_state`. 919if from_state : 920from_state_trans = from_state . mapping [ 'AnimatorState' ] . mapping [ 'm_Transitions' ] . addChildMapping () 921from_state_trans . mapping [ 'fileID' ] = copy . copy ( trans . anchor ) 922 923def addTransitionIntegerEqualityCondition ( self , from_state , trans , param , param_val ) : 924# Populate the transition's condition logic. 925cond = trans . mapping [ 'AnimatorStateTransition' ] . mapping [ 'm_Conditions' ] . addChildMapping () 926cond . mapping [ 'm_ConditionMode' ] = '6' 927cond . mapping [ 'm_ConditionEvent' ] = param 928# Curiously, the typo ("treshold" only has 1 'h') is needed for this to 929# work, but not for boolean conditions to work. 930cond . mapping [ 'm_EventTreshold' ] = str ( param_val ) 931# Register the transition with the `from_state`. 932if from_state : 933from_state_trans = from_state . mapping [ 'AnimatorState' ] . mapping [ 'm_Transitions' ] . addChildMapping () 934from_state_trans . mapping [ 'fileID' ] = trans . anchor 935 936def addTransitionIntegerGreaterCondition ( self , from_state , trans , param , param_val ) : 937# Populate the transition's condition logic. 938cond = trans . mapping [ 'AnimatorStateTransition' ] . mapping [ 'm_Conditions' ] . addChildMapping () 939cond . mapping [ 'm_ConditionMode' ] = '3' 940cond . mapping [ 'm_ConditionEvent' ] = param 941cond . mapping [ 'm_EventThreshold' ] = str ( param_val ) 942# Register the transition with the `from_state`. 943if from_state : 944from_state_trans = from_state . mapping [ 'AnimatorState' ] . mapping [ 'm_Transitions' ] . addChildMapping () 945from_state_trans . mapping [ 'fileID' ] = trans . anchor 946 947# TODO(yum) this should be factored out into generate_fx.py 948def addTasttToggle ( self , off_anim_path , on_anim_path , toggle_param , 949guid_map ) : 950self . addParameter ( toggle_param , bool ) 951 952off_anim_meta = Metadata () 953off_anim_meta . loadOrCreate ( off_anim_path , guid_map ) 954 955on_anim_meta = Metadata () 956on_anim_meta . loadOrCreate ( on_anim_path , guid_map ) 957 958layer = self . addLayer ( 'TaSTT_Toggle' ) 959off_anim = self . addAnimatorState ( layer , 'TaSTT_Toggle_Off' , is_default_state = True ) 960self . setAnimatorStateAnimation ( off_anim , off_anim_meta . guid ) 961on_anim = self . addAnimatorState ( layer , 'TaSTT_Toggle_On' ) 962self . setAnimatorStateAnimation ( on_anim , on_anim_meta . guid ) 963 964# TODO(yum) make a Transition class with methods for adding boolean 965# conditions 966off_to_on = self . addTransition ( on_anim ) 967self . addTransitionBooleanCondition ( off_anim , off_to_on , toggle_param , True ) 968 969on_to_off = self . addTransition ( off_anim ) 970self . addTransitionBooleanCondition ( on_anim , on_to_off , toggle_param , False ) 971 972def setNoopAnimations ( self , guid_map , noop_anim_path ) : 973noop_anim_meta = Metadata () 974noop_anim_meta . loadOrCreate ( noop_anim_path , guid_map ) 975 976for node in self . nodes : 977if node . class_id != "1102" : 978continue 979motion = node . mapping [ 'AnimatorState' ] . mapping [ 'm_Motion' ] 980replace = False 981 982name = node . mapping [ 'AnimatorState' ] . mapping [ 'm_Name' ] 983anchor = node . anchor 984 985# As of 8 May 2023, idle states look like this: 986# m_Motion: {fileID: 7400000, guid: e5881c5b0c09be854b0fd6fd8144333f, type: 2} 987# Before that, they looked like this: 988# m_Motion: {fileID: 0} 989# The first predicate looks for the new pattern. 990# The second predicate looks for the second pattern. 991if "fileID" in motion . mapping . keys () and \ 992"guid" in motion . mapping . keys () and \ 993not motion . mapping [ "guid" ] in guid_map : 994motion . mapping [ "fileID" ] = "7400000" 995( f"Set noop animation to guid { noop_anim_meta . guid } in state { node . anchor } " ) 996motion . mapping [ "guid" ] = noop_anim_meta . guid 997motion . mapping [ "type" ] = "2" 998elif not ( "fileID" in motion . mapping . keys () and 999motion . mapping [ "fileID" ] != "0" ) and not ( "guid" in 1000motion . mapping . keys () and motion . mapping [ "guid" ] in 1001guid_map ) : 1002motion . mapping [ "fileID" ] = "7400000" 1003( f"Set noop animation to guid { noop_anim_meta . guid } in state { node . anchor } " ) 1004motion . mapping [ "guid" ] = noop_anim_meta . guid 1005motion . mapping [ "type" ] = "2" 1006else : 1007#print(f"Skipping state {anchor} / {name}") 1008pass 1009 1010def unityYamlToString ( nodes ) : 1011lines = [] 1012preamble = """ 1013%YAML 1.1 1014%TAG !u! tag:unity3d.com,2011: 1015""" [ 1 : ][ : - 1 ] 1016if len ( nodes ) > 1 or ( len ( nodes ) == 1 and nodes [ 0 ] . anchor ) : 1017lines . append ( preamble ) 1018for doc in nodes : 1019if len ( nodes ) > 1 or ( len ( nodes ) == 1 and nodes [ 0 ] . anchor ) : 1020lines . append ( "--- !u!" + doc . class_id + " &" + doc . anchor ) 1021lines . append ( str ( doc )) 1022result = ' \n ' . join ( lines ) 1023 1024for i in range ( 0 , 10 ) : 1025result = result . replace ( " \n\n " , " \n " ) 1026 1027return result 1028 1029class UnityParser : 1030STREAM_START = 100 1031STREAM_END = 199 1032 1033DOCUMENT_START = 200 1034DOCUMENT_END = 299 1035 1036MAPPING_START = 300 1037MAPPING_KEY = 301 1038 1039SEQUENCE_VALUE = 400 1040 1041def __init__ ( self ) : 1042self . state = self . STREAM_START 1043self . cur_scalar = None 1044self . cur_node = None 1045 1046# Simple list of parsed documents. Populated by parse(). 1047self . nodes = [] 1048self . prev_states = [] 1049 1050def __str__ ( self ) : 1051return unityYamlToString ( self . nodes ) 1052 1053def pushState ( self , state ) : 1054self . prev_states . append ( self . state ) 1055self . state = state 1056#print("state {} ({})".format(self.state, len(self.prev_states))) 1057 1058def popState ( self ) : 1059self . state = self . prev_states [ - 1 ] 1060self . prev_states = self . prev_states [ 0 : len ( self . prev_states ) - 1 ] 1061#print("state {} ({})".format(self.state, len(self.prev_states))) 1062return self . state 1063 1064def cleanYaml ( self , yaml_str ) : 1065lines = [] 1066first_document = True 1067got_document = False 1068for line in yaml_str . split ( " \n " ) : 1069# Add end-of-document indicators. 1070if line . startswith ( "---" ) : 1071got_document = True 1072if not first_document : 1073lines . append ( "... \n " ) 1074first_document = False 1075 1076# Remove class ID tag from each block. 1077if line . startswith ( "---" ) : 1078parts = line . split () 1079lines . append ( parts [ 0 ] + " " + parts [ 2 ] + " \n " ) 1080continue 1081lines . append ( line ) 1082 1083if got_document : 1084lines . append ( "... \n " ) 1085return ' \n ' . join ( lines ) 1086 1087def getClassIds ( self , yaml_str ) : 1088anchor_to_class_id = {} 1089for line in yaml_str . split ( " \n " ) : 1090if not line . startswith ( "---" ) : 1091continue 1092 1093parts = line . split () 1094class_id = parts [ 1 ][ 3 : ] 1095anchor = parts [ 2 ][ 1 : ] 1096anchor_to_class_id [ anchor ] = class_id 1097 1098return anchor_to_class_id 1099 1100def parseFile ( self , yaml_file ) : 1101yaml_str = "" 1102with open ( yaml_file , "r" , encoding = "utf-8" ) as f : 1103yaml_str = f . read () 1104return self . parse ( yaml_str ) 1105 1106def parse ( self , yaml_str ) : 1107anchor_to_class_id = self . getClassIds ( yaml_str ) 1108yaml_str = self . cleanYaml ( yaml_str ) 1109 1110for event in yaml . parse ( yaml_str ) : 1111if isinstance ( event , yaml . StreamStartEvent ) : 1112if len ( self . prev_states ) > 0 : 1113raise Exception ( "Multiple StreamStartEvents received" ) 1114self . pushState ( self . STREAM_START ) 1115 1116elif isinstance ( event , yaml . StreamEndEvent ) : 1117if self . state != self . STREAM_START : 1118raise Exception ( "Document end received after state {}" . format ( self . state )) 1119self . popState () 1120if len ( self . prev_states ) > 0 : 1121raise Exception ( "Extra states at stream end" ) 1122 1123elif isinstance ( event , yaml . DocumentStartEvent ) : 1124if self . state != self . STREAM_START and self . state != self . DOCUMENT_END : 1125raise Exception ( "Document start received after state {}" . format ( self . state )) 1126self . pushState ( self . DOCUMENT_START ) 1127 1128elif isinstance ( event , yaml . DocumentEndEvent ) : 1129if self . state != self . DOCUMENT_START : 1130raise Exception ( "Document end received after state {}" . format ( self . state )) 1131self . popState () 1132self . nodes . append ( self . cur_node ) 1133self . cur_node = None 1134 1135elif isinstance ( event , yaml . MappingStartEvent ) : 1136if self . cur_node == None : 1137self . cur_node = UnityDocument () 1138self . cur_node . anchor = event . anchor 1139if event . anchor : 1140self . cur_node . class_id = anchor_to_class_id [ event . anchor ] 1141else : 1142self . cur_node = self . cur_node . addChildMapping ( self . cur_scalar ) 1143self . pushState ( self . MAPPING_START ) 1144 1145elif isinstance ( event , yaml . MappingEndEvent ) : 1146if self . state != self . MAPPING_START : 1147raise Exception ( "Mapping end received after state {}" . format ( self . state )) 1148self . popState () 1149if self . state == self . MAPPING_KEY : 1150self . popState () 1151if self . cur_node . parent != None : 1152self . cur_node = self . cur_node . parent 1153 1154elif isinstance ( event , yaml . SequenceStartEvent ) : 1155self . cur_node = self . cur_node . addChildSequence ( self . cur_scalar ) 1156self . pushState ( self . SEQUENCE_VALUE ) 1157 1158elif isinstance ( event , yaml . SequenceEndEvent ) : 1159if self . state != self . SEQUENCE_VALUE : 1160raise Exception ( "Sequence end received after state {}" . format ( self . state )) 1161self . popState () 1162if self . state == self . MAPPING_KEY : 1163self . popState () 1164self . cur_node = self . cur_node . parent 1165 1166elif isinstance ( event , yaml . ScalarEvent ) : 1167if self . state == self . MAPPING_START : 1168self . cur_scalar = event . value 1169self . pushState ( self . MAPPING_KEY ) 1170elif self . state == self . MAPPING_KEY : 1171self . cur_node . mapping [ self . cur_scalar ] = event . value 1172self . popState () 1173elif self . state == self . SEQUENCE_VALUE : 1174self . cur_node . sequence . append ( event . value ) 1175else : 1176raise Exception ( "Scalar event received after state {}" . format ( self . state )) 1177else : 1178raise Exception ( "Unhandled event {}" . format ( event )) 1179continue 1180 1181class MulticoreUnityParser : 1182def parseFile ( self , yaml_file ) : 1183yaml_str = "" 1184with open ( yaml_file , "r" , encoding = "utf-8" ) as f : 1185yaml_str = f . read () 1186return self . parse ( yaml_str ) 1187 1188def parse ( self , yaml_str ) : 1189lines = [] 1190documents = [] 1191first = True 1192n_lines = 0 1193for line in yaml_str . split ( " \n " ) : 1194n_lines += 1 1195if line . startswith ( "---" ) : 1196if not first : 1197documents . append ( " \n " . join ( lines )) 1198lines = [] 1199first = False 1200lines . append ( line ) 1201if len ( lines ) > 0 : 1202documents . append ( " \n " . join ( lines )) 1203lines = [] 1204( "Got {} documents out of {} lines" . format ( len ( documents ) , n_lines ) , file = sys . stderr ) 1205 1206# Divide the work evenly among the # of CPUs we have available. 1207n_threads = os . cpu_count () 1208window_size = int ( math . ceil ( len ( documents ) / n_threads )) 1209merge_window = [] 1210merged_documents = [] 1211for i in range ( 0 , len ( documents )) : 1212if i > 0 and i % window_size == 0 : 1213merged_documents . append ( " \n " . join ( merge_window )) 1214merge_window = [] 1215merge_window . append ( documents [ i ]) 1216if len ( merge_window ) > 0 : 1217merged_documents . append ( " \n " . join ( merge_window )) 1218merge_window = [] 1219documents = merged_documents 1220 1221mgr = mp . Manager () 1222 1223( "Spawning {} threads" . format ( len ( documents )) , file = sys . stderr ) 1224threads = [] 1225for document in documents : 1226res = mgr . dict () 1227thread = mp . Process ( target = self . parseOneSerial , args = ( document , res , )) 1228threads . append (( thread , res )) 1229thread . start () 1230 1231( "Joining threads" , file = sys . stderr ) 1232nodes = [] 1233for thread , res in threads : 1234thread . join () 1235nodes += res [ 'nodes' ] 1236 1237( "Creating animator" , file = sys . stderr ) 1238result = UnityAnimator () 1239result . addNodes ( nodes ) 1240 1241return result 1242 1243def parseOneSerial ( self , document , res ) : 1244parser = UnityParser () 1245parser . parse ( document ) 1246res [ 'nodes' ] = parser . nodes 1247 1248def parseFile ( self , yaml_file ) : 1249yaml_str = "" 1250with open ( yaml_file , "r" , encoding = "utf-8" ) as f : 1251yaml_str = f . read () 1252return self . parse ( yaml_str ) 1253 1254def getGuidMap ( d ) : 1255result = {} 1256for f in os . scandir ( d ) : 1257path = f . path 1258if f . is_dir () : 1259result . update ( getGuidMap ( path )) 1260if not f . is_file () : 1261continue 1262suffix = ".meta" 1263if path . endswith ( suffix ) : 1264with open ( path , "r" , encoding = "utf-8" ) as f : 1265for line in f : 1266if line . startswith ( "guid" ) : 1267guid = line . split ()[ 1 ] 1268result [ guid ] = path [ : - len ( suffix )] 1269return result 1270 1271if __name__ == "__main__" : 1272os . chdir ( os . path . dirname ( os . path . abspath ( __file__ ))) 1273 1274parser = argparse . ArgumentParser () 1275parser . add_argument ( "cmd" , type = str , help = "One of merge, guid_map, fix_write_defaults" ) 1276parser . add_argument ( "--fx0" , type = str , help = "The first animator to merge" ) 1277parser . add_argument ( "--fx1" , type = str , help = "The second animator to merge" ) 1278parser . add_argument ( "--fx_dest" , type = str , help = "The path at which to " + 1279"save the generated/merged animator" ) 1280parser . add_argument ( "--project_root" , type = str , help = "The path to the " + 1281"Unity project Assets folder" ) 1282parser . add_argument ( "--save_to" , type = str , help = "The path to save the " + 1283"result of the computation" ) 1284parser . add_argument ( "--guid_map" , type = str , help = "Path to guid.map, " + 1285"generated by a previous call to `guid_map`" ) 1286parser . add_argument ( "--guid_map_append" , type = bool , help = "If set, " + 1287"append to GUID map instead of overwriting." ) 1288parser . add_argument ( "--gen_anim_dir" , type = str , help = "The folder under which generated animations are stored" ) 1289args = parser . parse_args () 1290 1291if args . cmd == "merge" : 1292if not args . fx0 or not args . fx1 or not args . fx_dest : 1293( "--fx0, --fx1, and --fx_dest required" , file = sys . stderr ) 1294parser . print_help () 1295parser . exit ( 1 ) 1296 1297( "Parsing {}" . format ( args . fx0 ) , file = sys . stderr ) 1298parser0 = MulticoreUnityParser () 1299anim0 = parser0 . parseFile ( args . fx0 ) 1300 1301arg1 = "TaSTT_fx.controller" 1302( "Parsing {}" . format ( args . fx1 ) , file = sys . stderr ) 1303parser1 = MulticoreUnityParser () 1304anim1 = parser1 . parseFile ( args . fx1 ) 1305 1306( "Merging animators" , file = sys . stderr ) 1307anim0 . merge ( anim1 ) 1308 1309( "Serializing to {}" . format ( args . fx_dest ) , file = sys . stderr ) 1310with open ( args . fx_dest , "w" , encoding = "utf-8" ) as f : 1311f . write ( unityYamlToString ( anim0 . nodes )) 1312 1313elif args . cmd == "guid_map" : 1314if not args . project_root or not args . save_to : 1315( "--project_root and --save_to required" ) 1316parser . print_help () 1317parser . exit ( 1 ) 1318 1319( "Looking up GUIDs under {}" . format ( args . project_root ) , 1320file = sys . stderr ) 1321guid_map = getGuidMap ( args . project_root ) 1322 1323save_to_dir = os . path . dirname ( args . save_to ) 1324os . makedirs ( save_to_dir , exist_ok = True ) 1325 1326if args . guid_map_append : 1327tmp_map = {} 1328with open ( args . save_to , "rb" ) as f : 1329tmp_map = pickle . load ( f ) 1330# combine guid_map and tmp_map 1331guid_map = { ** guid_map , ** tmp_map } 1332( "Saving to {}" . format ( args . save_to ) , file = sys . stderr ) 1333with open ( args . save_to , 'wb' ) as f : 1334pickle . dump ( guid_map , f ) 1335elif args . cmd == "fix_write_defaults" : 1336if not args . fx0 or not args . guid_map : 1337( "--fx0 and --guid_map required" ) 1338parser . print_help () 1339parser . exit ( 1 ) 1340 1341guid_map = {} 1342with open ( args . guid_map , 'rb' ) as f : 1343guid_map = pickle . load ( f ) 1344 1345( "Parsing {}" . format ( args . fx0 ) , file = sys . stderr ) 1346parser0 = MulticoreUnityParser () 1347anim = parser0 . parseFile ( args . fx0 ) 1348 1349( "Fixing write defaults" , file = sys . stderr ) 1350anim_dir = "generated/animations/" 1351os . makedirs ( anim_dir , exist_ok = True ) 1352anim . fixWriteDefaults ( guid_map , anim_dir + "TaSTT_Reset_Animation.anim" ) 1353( str ( anim )) 1354 1355elif args . cmd == "gen_off_anims" : 1356if not args . fx0 or not args . guid_map : 1357( "--fx0 and --guid_map required" ) 1358parser . print_help () 1359parser . exit ( 1 ) 1360 1361guid_map = {} 1362with open ( args . guid_map , 'rb' ) as f : 1363guid_map = pickle . load ( f ) 1364 1365( "Parsing {}" . format ( args . fx0 ) , file = sys . stderr ) 1366parser0 = MulticoreUnityParser () 1367anim = parser0 . parseFile ( args . fx0 ) 1368 1369( "Generating off animations" , file = sys . stderr ) 1370anim_dir = "generated/animations/" 1371os . makedirs ( anim_dir , exist_ok = True ) 1372anim . generateOffAnimations ( guid_map , "generated/animations" ) 1373 1374elif args . cmd == "add_toggle" : 1375if not args . fx0 or not args . fx_dest or not args . gen_anim_dir or not args . guid_map : 1376( "--fx0, --fx_dest, --gen_anim_dir and --guid_map required" ) 1377parser . print_help () 1378parser . exit ( 1 ) 1379 1380guid_map = {} 1381with open ( args . guid_map , 'rb' ) as f : 1382guid_map = pickle . load ( f ) 1383 1384( "Parsing {}" . format ( args . fx0 ) , file = sys . stderr ) 1385parser0 = MulticoreUnityParser () 1386anim = parser0 . parseFile ( args . fx0 ) 1387 1388( "Adding toggle" , file = sys . stderr ) 1389anim . addTasttToggle ( args . gen_anim_dir + "/TaSTT_Toggle_Off.anim" , 1390args . gen_anim_dir + "/TaSTT_Toggle_On.anim" , "TaSTT_Toggle" , 1391guid_map ) 1392 1393( "Serializing to {}" . format ( args . fx_dest ) , file = sys . stderr ) 1394with open ( args . fx_dest , "w" , encoding = "utf-8" ) as f : 1395f . write ( str ( anim )) 1396 1397with open ( args . guid_map , 'wb' ) as f : 1398pickle . dump ( guid_map , f ) 1399 1400elif args . cmd == "fast_parse_test" : 1401if not args . fx0 : 1402( "--fx0 required" ) 1403parser . print_help () 1404parser . exit ( 1 ) 1405 1406( "Parsing {}" . format ( args . fx0 ) , file = sys . stderr ) 1407parser0 = MulticoreUnityParser () 1408anim = parser0 . parseFile ( args . fx0 ) 1409( str ( anim )) 1410 1411elif args . cmd == "set_noop_anim" : 1412if not args . fx0 or not args . fx_dest or not args . gen_anim_dir or not args . guid_map : 1413( "--fx0, --fx_dest, --gen_anim_dir and --guid_map required" ) 1414parser . print_help () 1415parser . exit ( 1 ) 1416 1417guid_map = {} 1418with open ( args . guid_map , 'rb' ) as f : 1419guid_map = pickle . load ( f ) 1420 1421( "Parsing {}" . format ( args . fx0 ) , file = sys . stderr ) 1422parser = MulticoreUnityParser () 1423anim = parser . parseFile ( args . fx0 ) 1424 1425anim . setNoopAnimations ( guid_map , args . gen_anim_dir + "/TaSTT_Do_Nothing.anim" ) 1426 1427with open ( args . fx_dest , "w" , encoding = "utf-8" ) as f : 1428f . write ( str ( anim )) 1429 1430else : 1431( "Unrecognized command: {}" . format ( args . cmd )) 1432