def __init__(self, actor, label, sz, offset, rot): print(actor) self.width = sz[0] self.height = sz[1] #print("before attach",actor.get_actor_components()) mesh = actor.get_actor_component_by_type(SkeletalMeshComponent) # we need three parts, SceneCaptureActor, ATextureReader, RenderTargetTextures self.rendertarget = TextureRenderTarget2D() self.rendertarget.set_property("SizeX", self.width) self.rendertarget.set_property("SizeY", self.height) xform = FTransform() xform.translation = FVector(offset[0], offset[1], offset[2]) xform.rotation = FRotator(rot[0], rot[1], rot[2]) ue.log("vcam xlate {} rot {}".format(xform.translation, xform.rotation)) self.scene_capture = actor.get_actor_component_by_type( SceneCaptureComponent2D) self.scene_capture.set_relative_location(offset[0], offset[1], offset[2]) self.scene_capture.set_relative_rotation(rot[0], rot[1], rot[2]) self.scene_capture.set_property("TextureTarget", self.rendertarget) # add reader last self.reader = actor.add_actor_component( ue.find_class('ATextureReader'), label + "_rendertarget") self.reader.set_property('RenderTarget', self.rendertarget) self.reader.SetWidthHeight(sz[0], sz[1])
def build_skeleton(self, pkg_name, obj_name): pkg = ue.get_or_create_package('{0}_Skeleton'.format(pkg_name)) skel = Skeleton('{0}_Skeleton'.format(obj_name), pkg) # add a root bone from which all of the others will descend # (this trick will avoid generating an invalid skeleton [and a crash], as in UE4 only one root can exist) skel.skeleton_add_bone('root', -1, FTransform()) # iterate bones in the json file, note that we move from opengl axis to UE4 # (y on top, x right, z forward right-handed) to (y right, x forward left-handed, z on top) for bone in self.model['bones']: # assume no rotation quat = FQuat() # give priority to quaternions # remember to negate x and y axis, as we invert z on position if 'rotq' in bone: quat = FQuat(bone['rotq'][2], bone['rotq'][0] * -1, bone['rotq'][1] * -1, bone['rotq'][3]) elif 'rot' in bone: quat = FRotator(bone['rot'][2], bone['rot'][0] - 180, bone['rot'][1] - 180).quaternion() pos = FVector(bone['pos'][2] * -1, bone['pos'][0], bone['pos'][1]) * self.scale # always set parent+1 as we added the root bone before skel.skeleton_add_bone(bone['name'], bone['parent'] + 1, FTransform(pos, quat)) skel.save_package() return skel
def AddSequencerSectionTransformKeysByIniFile(SequencerSection, SectionFileName, FileLoc): Config = configparser.ConfigParser() Config.read(FileLoc) for option in Config.options(SectionFileName): frame = float(option)/float(frameRateNumerator) #FrameRate list = Config.get(SectionFileName, option) list = list.split(',') transform = FTransform(FVector(float(list[0]), float(list[1]), float(list[2])), FRotator(float(list[3]), float(list[4]), float(list[5]))) SequencerSection.sequencer_section_add_key(frame,transform)
def build_animation(self, pkg_name, obj_name): factory = AnimSequenceFactory() factory.TargetSkeleton = self.skeleton new_anim = factory.factory_create_new('{0}_Animation'.format(pkg_name)) new_anim.NumFrames = self.model['animation']['length'] * \ self.model['animation']['fps'] new_anim.SequenceLength = self.model['animation']['length'] # each bone maps to a track in UE4 animations for bone_index, track in enumerate(self.model['animation']['hierarchy']): # retrieve the bone/track name from the index (remember to add 1 as we have the additional root bone) bone_name = self.skeleton.skeleton_get_bone_name(bone_index + 1) positions = [] rotations = [] scales = [] for key in track['keys']: t = key['time'] if 'pos' in key: positions.append( (t, FVector(key['pos'][2] * -1, key['pos'][0], key['pos'][1]) * 100)) if 'rotq' in key: rotations.append((t, FQuat( key['rotq'][2], key['rotq'][0] * -1, key['rotq'][1] * -1, key['rotq'][3]))) elif 'rot' in key: # is it a quaternion ? if len(key['rot']) == 4: rotations.append( (t, FQuat(key['rot'][2], key['rot'][0] * -1, key['rot'][1] * -1, key['rot'][3]))) else: rotations.append( (t, FRotator(key['rot'][2], key['rot'][0] - 180, key['rot'][1] - 180).quaternion())) pos_keys = [] rot_keys = [] # generate the right number of frames for t in numpy.arange(0, self.model['animation']['length'], 1.0 / self.model['animation']['fps']): pos_keys.append(self.interpolate_vector(positions, t)) rot_keys.append(self.interpolate_quaternion( rotations, t).get_normalized()) track_data = FRawAnimSequenceTrack() track_data.pos_keys = pos_keys track_data.rot_keys = rot_keys new_anim.add_new_raw_track(bone_name, track_data) # if we have curves, just add them to the animation if self.curves: new_anim.RawCurveData = RawCurveTracks(FloatCurves=self.curves) new_anim.save_package() return new_anim
def loadAndSpawnObjects(self): ue.log("+++++++++++++++++++") ue.log("loadAndSpawnObjects") ue.log("checking for " + self.datapath) if os.path.exists(self.datapath): with codecs.open(self.datapath, "r", "utf-8") as f: data = json.loads(f.read()) ue.log(data) for obj in data: objclass = ue.find_class(obj["type"]) #ue.log(str(type(objclass))+str(objclass)+"="+obj["json"]) objinst = self.uobject.actor_spawn(objclass, FVector(0, 0, 0), FRotator(0, 0, 0)) jsonstr = obj["json"] self.objects.append(objinst) objinst.call_function("loadjson", jsonstr) ue.log("------------------")
import unreal_engine as ue from unreal_engine.classes import Actor, Character from unreal_engine import FVector, FRotator #use ue.exec('WorldActor.py') world = ue.get_editor_world() actor000 = world.actor_spawn(Actor, FVector(0, 0, 0), FRotator(0, 0, 0)) character000 = world.actor_spawn(Character, FVector(100, 100, 100), FRotator(0, 0, 0)) # select an actor unreal_engine.editor_select_actor(actor000) ''' # get access to the editor world editor = unreal_engine.get_editor_world() # get the list of selected actors selected_actors = unreal_engine.editor_get_selected_actors() # deselect actors unreal_engine.editor_deselect_actors() # import an asset new_asset = unreal_engine.import_asset(filename, package[, factory_class]) # get a factory class factory = ue.find_class('TextureFactory')
def CreateTask_SK_Armature(): ################[ Import Armature as SkeletalMesh type ]################ print( '================[ New import task : Armature as SkeletalMesh type ]================' ) FilePath = os.path.join( r'D:\Repos\Piroots2\Other Files\ExportedFbx\SkeletalMesh\Armature\SK_Armature.fbx' ) AdditionalParameterLoc = os.path.join( r'D:\Repos\Piroots2\Other Files\ExportedFbx\SkeletalMesh\Armature\SK_Armature_AdditionalParameter.ini' ) AssetImportPath = (os.path.join(unrealImportLocation, r'').replace('\\', '/')).rstrip('/') task = PyFbxFactory() task.ImportUI.MeshTypeToImport = EFBXImportType.FBXIT_SkeletalMesh task.ImportUI.bImportMaterials = True task.ImportUI.bImportTextures = False task.ImportUI.bImportAnimations = False task.ImportUI.bCreatePhysicsAsset = True task.ImportUI.bImportAnimations = False task.ImportUI.bImportMesh = True task.ImportUI.bCreatePhysicsAsset = True task.ImportUI.TextureImportData.MaterialSearchLocation = EMaterialSearchLocation.Local task.ImportUI.SkeletalMeshImportData.bImportMorphTargets = True print('================[ import asset : Armature ]================') try: asset = task.factory_import_object(FilePath, AssetImportPath) except: asset = None if asset == None: ImportFailList.append( 'Asset "Armature" not found for after inport') return print( '========================= Imports of Armature completed ! Post treatment started... =========================' ) skeleton = asset.skeleton current_sockets = skeleton.Sockets new_sockets = [] sockets_to_add = GetOptionByIniFile(AdditionalParameterLoc, 'Sockets', True) for socket in sockets_to_add: #Create socket new_socket = SkeletalMeshSocket('', skeleton) new_socket.SocketName = socket[0] print(socket[0]) new_socket.BoneName = socket[1] l = socket[2] r = socket[3] s = socket[4] new_socket.RelativeLocation = FVector(l[0], l[1], l[2]) new_socket.RelativeRotation = FRotator(r[0], r[1], r[2]) new_socket.RelativeScale = FVector(s[0], s[1], s[2]) new_sockets.append(new_socket) skeleton.Sockets = new_sockets lods_to_add = GetOptionByIniFile(AdditionalParameterLoc, 'LevelOfDetail') for x, lod in enumerate(lods_to_add): pass print( '========================= Post treatment of Armature completed ! =========================' ) asset.save_package() asset.post_edit_change() ImportedList.append([asset, 'SkeletalMesh'])
def test_rotation(self): new_actor = self.world.actor_spawn(Character, FVector(), FRotator(0, 0, 90)) yaw = new_actor.get_actor_rotation().yaw self.assertTrue(math.fabs(90 - yaw) < 0.1)
from unreal_engine import FVector, FRotator from unreal_engine.classes import StaticMeshActor, StaticMesh import json, os, glob, math geo_folder = geo_directory + "\\" + geo_map + "\\" geo_mtl_file = geo_directory + "\\" + geo_map + "\\" + geo_map + ".mtl" xmodels_directory = geo_directory + r"\xmodels" xmodels_json = geo_directory + "\\" + geo_map + "\\" + geo_map + "_xmodels.json" with open(xmodels_json, 'r') as file: entities = json.load(file) cube_placeholder = ue.load_object(StaticMesh, '/Engine/BasicShapes/Cube.Cube') props_cube = ue.get_editor_world().actor_spawn(StaticMeshActor, FVector(0, 0, 0), FRotator(0, 0, 0)) props_cube.StaticMeshComponent.StaticMesh = cube_placeholder props_cube.set_actor_label('props') mesh_number = 0 last_mesh = '' for actor in entities: if 'Name' in actor: if actor['Name'].endswith("."): actor['Name'] = actor['Name'][:actor['Name'].rfind(".")] #Set all the coordinates, scale and rotations.
def test_roll_pitch_yaw(self): rotator0 = FRotator(10, 20, 30) self.assertEqual( rotator0.roll, 10) self.assertEqual( rotator0.pitch, 20) self.assertEqual( rotator0.yaw, 30)
# import the animation anim_factory = PyFbxFactory() anim_factory.ImportUI.Skeleton = mesh.Skeleton anim_factory.ImportUI.bImportMesh = False anim_factory.ImportUI.bImportMaterials = False anim_factory.ImportUI.bImportTextures = False anim_factory.ImportUI.AnimSequenceImportData.ImportUniformScale = 0.1; animation = anim_factory.factory_import_object(os.path.join(kaiju_source, kaiju_animation), kaiju_destination) new_blueprint = ue.create_blueprint(Character, kaiju_destination + '/Kaiju_BP') new_blueprint.GeneratedClass.get_cdo().Mesh.SkeletalMesh = mesh new_blueprint.GeneratedClass.get_cdo().Mesh.RelativeLocation = FVector(0, 0, -140) new_blueprint.GeneratedClass.get_cdo().Mesh.RelativeRotation = FRotator(0, 0, -90) new_blueprint.GeneratedClass.get_cdo().CapsuleComponent.CapsuleHalfHeight = 150 new_blueprint.GeneratedClass.get_cdo().CapsuleComponent.CapsuleRadius = 50 new_blueprint.GeneratedClass.get_cdo().Mesh.OverrideMaterials = [None, mat] new_blueprint.GeneratedClass.get_cdo().Mesh.AnimationMode = EAnimationMode.AnimationSingleNode new_blueprint.GeneratedClass.get_cdo().Mesh.AnimationData = SingleAnimationPlayData(AnimToPlay=animation) # move forward tick = new_blueprint.UberGraphPages[0].graph_add_node_event(Actor, 'ReceiveTick') add_movement_input = new_blueprint.UberGraphPages[0].graph_add_node_call_function(Character.AddMovementInput) add_movement_input.node_find_pin('WorldDirection').default_value = '1,0,0' tick.node_find_pin('then').make_link_to(add_movement_input.node_find_pin('execute')) ue.compile_blueprint(new_blueprint)
import unreal_engine as ue from unreal_engine.classes import Actor, Character from unreal_engine import FVector, FRotator world = ue.get_editor_world() actor000 = world.actor_spawn(Actor, FVector(0, 0, 0), FRotator(0, 0, 0)) character000 = world.actor_spawn(Character, FVector(100, 100, 100), FRotator(0, 0, 0))
def begin_play(self): ue.log('Begin Play on class') print(tf.__version__) # set input player = GameplayStatics.GetPlayerController(self.uobject) self.uobject.EnableInput(player) self.uobject.bind_key('C', ue.IE_PRESSED, self.you_pressed_C) self.uobject.bind_key('M', ue.IE_PRESSED, self.you_pressed_M) self.bSimulation = True self.auto_move_mode = True # Load mesh as proceduralmesh self.Procedural_mesh = self.uobject.add_actor_root_component(ProceduralMesh.CustomProceduralMeshComponent, 'ProceduralMesh') self.Procedural_mesh.import_renderable(simdata_path) # spawn a new PyActor self.sphere_actor = self.uobject.actor_spawn(ue.find_class('PyActor'), FVector(0, 0, 0),FRotator(0, 0, 0)) # add a sphere component as the root one self.sphere_component = self.sphere_actor.add_actor_root_component(ProceduralMesh.CustomProceduralMeshComponent, 'SphereMesh') # set the mesh as the Sphere asset self.sphere_component.import_renderable(simdatacollision_path) self.scale_factor = 200 scale = self.scale_factor self.uobject.set_actor_scale(FVector(scale,scale,scale)) self.uobject.set_actor_rotation(FRotator(-90, 0, 0)) self.uobject.set_actor_location(FVector(0, 0, 0)) self.sphere_actor.set_actor_scale(FVector(scale,scale,scale)) self.sphere_actor.set_actor_rotation(FRotator(-90, 0, 0)) self.sphere_actor.set_actor_location(FVector(0, 0, 0)) # Load model self.model = keras.models.load_model(model_path) self.model.summary() # Load paras self.z = np.load(z_path) self.w = np.load(w_path) self.alpha = np.load(alpha_path) self.beta = np.load(beta_path) self.x_transform_mat = np.load(x_transform_path) self.x_mean = np.load(x_mean_path) self.y_transform_mat = np.load(y_transform_path) self.y_mean = np.load(y_mean_path) self.z_init_last_2 = self.z[0, :] self.z_init_last_1 = self.z[1, :] self.sphere_location_last = self.sphere_actor.get_actor_location() # select t=2, make sure t >= 2 # input data for model [/zt;zt-1;wt] self.t = 0+2 # for auto move self.z_last_2_auto = self.z[self.t-2, :] self.z_last_1_auto = self.z[self.t-1, :] self.tick_frequency = 100 self.elapsed_time = 0.0
def direction_at(self, distance): tmp = self.component.GetDirectionAtDistanceAlongSpline(distance) return FRotator(0, 0, math.atan2(tmp.y, tmp.x) * 57.2957)