Example #1
0
def remove_lip_ctrlr():
    ops =  bpy.ops
    obj = bpy.context.object
    bone = obj.data.bones.active
    posebones = obj.pose.bones
    posebone = posebones[bone.name]
    customshapename = posebone.custom_shape.name
    bonename = posebone.name
    mode_set('EDIT')
    editbones = obj.data.edit_bones
    editbone = editbones[bone.name]
    editbone.select = True
    for chld in editbone.children:
        chld.select = True

    mode_set('POSE')
    mode_set('EDIT')
    bpy.ops.armature.delete()
    mode_set('OBJECT')
    select_all('DESELECT')
    lscoll = bpy.data.collections['LS.Widget']
    lscoll.hide_viewport = False
    active_object(customshapename)
    bpy.ops.object.delete()
    lscoll.hide_viewport = True
    purge_curves()
    if not armature_name:
        sorting_objects()
    bone_shapekey(figure_name[0], bonename)
    mode_set('OBJECT')
    ops.object.shape_key_remove(all=False)
    select_all('DESELECT')
    active_object(armature_name[0])
    mode_set('POSE')
Example #2
0
def arma_create_lipsync_shapekeys(shapekey_name):
    mode_set('OBJECT')
    select_all('DESELECT')
    active_object(figure_name[0])
    obj = bpy.context.object
    ops.object.transform_apply(location=True,
                                rotation=True, 
                                scale=True)
    global modif
    for mod in bpy.context.object.modifiers:
        if mod.type == 'ARMATURE':
            modif =  mod.name
            
    if bpy.app.version >= (2, 90, 0):
        ops.object.modifier_apply_as_shapekey(
        modifier=modif)
    else:
        ops.object.modifier_apply(apply_as='SHAPE',
        modifier=modif)
        
    keyname = obj.data.shape_keys.name
    key = bpy.data.shape_keys[keyname]
    keyblock = key.key_blocks[modif]
    keyblock.name = shapekey_name
            
    active_object(armature_name[0])
    ops.object.transform_apply(location=True,
                                rotation=True,
                                scale=True)
    ops.object.parent_set(type='ARMATURE_NAME')
    mode_set('POSE')
    ops.pose.user_transforms_clear()
Example #3
0
def show_policies():
    sql = "SELECT id, name, cloud_provider FROM trainer_cluster"
    rows = select_all(_BACKOFFICE_DB, sql=sql)
    results = []
    policy_data_sql = '''SELECT sim_model.name as model_name, 
                    policy.sim_config_id as sim_config_id,
                    policy_run.policy_id as policy_id, 
                    policy_run.id as policy_run_id, 
                    policy_run.time_start as time_start, 
                    policy_run.simulations as simulations, 
                    policy_run.duration as duration, 
                    policy_run.results as results
             FROM policy_run 
             INNER JOIN policy ON policy_run.policy_id = policy.id
             INNER JOIN sim_model ON policy.sim_model_id = sim_model.id'''
    deployed_sql = '''SELECT policy_id
                           FROM policy WHERE trainer_id = {}'''.format(P_MARKER)
    for trainer_row in rows:
        trainer_id, trainer_name, cloud_provider = trainer_row
        trainer_db = db_connect(_TRAINER_PATH(trainer_name, cloud_provider) + "/" + TRAINER_DB_NAME)
        trainer_data = select_all(trainer_db,sql=policy_data_sql)
        deployed_policies = [row[0] for row in select_all(_BACKOFFICE_DB, sql=deployed_sql, params=(trainer_id,))]
        df_data = [trainer_row+data[:-1]+(np.mean(json.loads(data[-1])), np.std(json.loads(data[-1])),
                                          data[2] in deployed_policies) for data in trainer_data]
        df_columns = ['trainer_id', 'trainer_name', 'cloud_provider', 'model_name', 'sim_config_id', 'policy_id',
                      'run_id', 'time_start', 'simulations', 'duration', 'mean', 'std', 'deployed']
        results.append(pd.DataFrame(data=df_data, columns=df_columns))
    return pd.concat(results)
Example #4
0
def apply_lipsync():
    mode_set('OBJECT')
    sorting_objects()
    obj = bpy.context.object
    select_all('DESELECT')
    if obj.type == 'MESH':
        apply_from_edit()
    else:
        apply_from_pose()
Example #5
0
def del_object(obj):
    select_all('DESELECT')
    active_object(obj)
    objs = bpy.data.objects
    if figure_name:
        objs[figure_name[0]].select_set(True)
    elif accessories:
        for a in accessories:
            objs[a].select_set(True)
    bpy.ops.object.delete()
    purge_scene()
Example #6
0
    def run_baselines(self,
                      sim_config: [int, list] = None,
                      simulations: int = 1):
        @ray.remote
        def base_run(base):
            return base.run()

        if sim_config is None:
            # Get all sim configs for the current model
            select_sim_sql = '''SELECT id, config FROM sim_config
                                WHERE sim_config.sim_model_id = {}'''.format(
                P_MARKER)
            rows = select_all(self.db,
                              sql=select_sim_sql,
                              params=(self._model_id, ))
            sim_configs = ((i, json.loads(config)) for i, config in rows)
        else:
            if isinstance(sim_config, int):
                sim_config = [sim_config]
            if isinstance(sim_config, list):
                # Get all policies for the list of sim_configs
                select_sim_sql = '''SELECT id, config FROM sim_config
                                    WHERE id IN ({})'''.format(
                    SQLParamList(len(sim_config)))
                rows = select_all(self.db,
                                  sql=select_sim_sql,
                                  params=tuple(sim_config))
                sim_configs = ((i, json.loads(config)) for i, config in rows)
            else:
                raise Exception("Invalid Sim Config {}".format(sim_config))

        for sim_config_id, sim_config in sim_configs:
            base = self._sim_baseline(sim_config=sim_config)
            print("# Baseline Simulation for Config {} started at {}!".format(
                sim_config_id, datetime.now()))
            time_start = datetime.now()
            result_list = ray.get(
                [base_run.remote(base) for _ in range(simulations)])
            # for i in range(simulations):
            #    future_result_list.append(base_run.remote())
            #    print("# Progress: {:2.1%} ".format((i + 1) / simulations), end="\r")

            policy_run_data = (sim_config_id, time_start, simulations,
                               (datetime.now() - time_start).total_seconds(),
                               json.dumps(result_list))
            self._add_baseline_run(policy_run_data)
            # print("# Progress: {:2.1%} ".format(1))
            print("# Baseline Simulation for Config {} ended at {}!".format(
                sim_config_id, datetime.now()))
Example #7
0
 def del_training_sessions(self, sessions: [int, list] = None):
     select_sessions_sql = '''SELECT id FROM training_session
                              WHERE sim_model_id = {}'''.format(P_MARKER)
     params = (self._model_id, )
     all_sessions = select_all(self.db,
                               sql=select_sessions_sql,
                               params=params)
     all_sessions = {t[0] for t in all_sessions}
     del_sessions = []
     if isinstance(sessions, int):
         assert sessions in all_sessions, "Invalid session id {}".format(
             sessions)
         del_sessions = (sessions, )
     if isinstance(sessions, list):
         assert set(sessions).issubset(
             all_sessions), "Invalid sessions list {}".format(sessions)
         del_sessions = tuple(sessions)
     if sessions is None:
         del_sessions = tuple(all_sessions)
     if len(del_sessions):
         cursor = self.db.cursor()
         sql = '''DELETE FROM training_iteration
                  WHERE training_session_id IN ({})'''.format(
             SQLParamList(len(del_sessions)))
         cursor.execute(sql, del_sessions)
         sql = '''DELETE FROM training_session
                  WHERE id IN ({})'''.format(SQLParamList(
             len(del_sessions)))
         cursor.execute(sql, del_sessions)
         self.db.commit()
Example #8
0
 def _get_sim_config(self, sim_config: dict):
     cursor = self.db.cursor()
     if sim_config is None:
         sim_config_id = self._get_sim_base_config()
     else:
         sql = '''SELECT id, config FROM sim_config 
                  WHERE sim_model_id = {}'''.format(P_MARKER)
         params = (self._model_id, )
         row_list = select_all(self.db, sql=sql, params=params)
         try:
             idx = [json.loads(config)
                    for _, config in row_list].index(sim_config)
             sim_config_id, _ = row_list[idx]
         except Exception:
             params = (self._model_id, "Config {}".format(len(row_list)),
                       self._get_baseline_avg(sim_config),
                       json.dumps(sim_config))
             cursor.execute(
                 '''INSERT INTO sim_config (sim_model_id,
                                                       name,
                                                       baseline_avg,
                                                       config) VALUES ({})'''
                 .format(SQLParamList(4)), params)
             sim_config_id = cursor.lastrowid
     self.db.commit()
     return sim_config_id
Example #9
0
def disable_GNSrig():
    mode_set('OBJECT')
    select_all('DESELECT')
    objs = bpy.data.objects
    rig_coll = objs['rig'].users_collection[0]
    widgt_coll = bpy.data.collections['Widgets']
    widgt_coll.objects.link(objs['GNSrig'])
    rig_coll.objects.unlink(objs['GNSrig'])
    for meshes in objs:
        if meshes.modifiers:
            for mod in meshes.modifiers:
                if (mod.type == "ARMATURE" 
                and mod.object.name == "GNSrig"):
                    mod.show_viewport = False
                    
    active_object('rig')
Example #10
0
def get_trainers_api(request):
    sql = '''SELECT id, name, cloud_provider, start, stop, config FROM trainer_cluster'''
    db = db_connect(BACKOFFICE_DB_NAME, check_same_thread=False)
    rows = select_all(db, sql)
    data = [(i, name, cloud_provider, start, stop, json.loads(config))
            for i, name, cloud_provider, start, stop, config in rows]
    return json.dumps(data)
Example #11
0
def get_policies_api(request):
    def _process(row, backend_list, backend_traffic):
        row[5] = json.loads(row[5])
        row[6] = json.loads(row[6])
        row += (None,None) if row[7] is None or row[7] not in backend_list.keys() \
                            else (backend_list[row[7]].num_replicas, backend_list[row[7]].max_concurrent_queries)
        row += (None, ) if row[7] is None else (backend_traffic.get(
            row[7], None), )
        return tuple(row)

    sql = '''SELECT policy.cluster_id as trainer_id,
                    trainer_cluster.name as trainer_name,
                    policy.policy_id as policy_id, 
                    policy.model_name as model_name,
                    policy.checkpoint as checkpoint,
                    policy.agent_config,
                    policy.sim_config,
                    policy.backend_name
             FROM policy INNER JOIN trainer_cluster ON policy.cluster_id = trainer_cluster.id'''
    db = db_connect(BACKOFFICE_DB_NAME, check_same_thread=False)
    rows = select_all(db, sql)
    backend = serve.connect()
    global BACKOFFICE_ENDPOINTS
    backend_traffic = {
        backend: endpoint
        for endpoint, props in backend.list_endpoints().items()
        if endpoint not in BACKOFFICE_ENDPOINTS.keys()
        for backend in props['traffic'].keys()
    }
    data = [
        _process(list(row), backend.list_backends(), backend_traffic)
        for row in rows
    ]
    return json.dumps(data)
Example #12
0
def enable_GNSrig():
    objs = bpy.data.objects
    rig_collection = objs['rig'].users_collection
    GNS_collection = objs['GNSrig'].users_collection
    rig_collection[0].objects.link(objs['GNSrig'])
    GNS_collection[0].objects.unlink(objs['GNSrig'])

    for meshes in objs:
        if meshes.modifiers:
            for mod in meshes.modifiers:
                if (mod.type == "ARMATURE" 
                and mod.object.name == "GNSrig"):
                    mod.show_viewport = True
                    
    mode_set('OBJECT')
    select_all('DESELECT')
    active_object('GNSrig')
    bpy.context.object.animation_data_create()
Example #13
0
def bone_shapekey(activeobj, bonename):
    select_all('DESELECT')
    active_object(activeobj)
    obj = bpy.context.object
    shape_keys = obj.data.shape_keys
    global key_blocks
    key_blocks = shape_keys.key_blocks
    key_blocks[bonename].driver_remove('value')
    # Get index of shape key in bpy.context
    kb_names.clear()
    kb.clear()
    mode_set('EDIT')
    for k in key_blocks:
        kb_names.append(k.name)
    global indx
    indx = deepcopy(kb_names.index(bonename))
    keyname = obj.data.shape_keys.name
    bpy.data.shape_keys[keyname].key_blocks[bonename].value = 1
    obj.active_shape_key_index = indx
Example #14
0
def update_custom_shape():
    if not figure_name:
        sorting_objects()
    obj = bpy.context.object
    bone = obj.data.bones.active
    bonename = bone.name
    customshape = obj.pose.bones[bonename].custom_shape
    customshapebody = customshape.data.body
    if customshapebody == bonename:
        return
    customshape.data.body = bonename
    mode_set('OBJECT')
    select_all('DESELECT')
    active_object(figure_name[0])
    obj = bpy.context.object
    shape_keys = obj.data.shape_keys
    key_blocks = shape_keys.key_blocks
    key_blocks[customshapebody].name = bonename
    select_all('DESELECT')
    active_object(armature_name[0])
    mode_set('POSE')
Example #15
0
def apply_from_edit():
    active_object(figure_name[0])
    obj = bpy.context.object
    obj.use_shape_key_edit_mode = False
    shape_keys = obj.data.shape_keys
    key_blocks = shape_keys.key_blocks
    kb_names.clear()
    kb.clear()
    for k in key_blocks:
        kb_names.append(k.name) 
        if k.name[:3] == '...':
            kb.append(k)
            
    kb[0].name = kb[0].name[3:]
    kb_name = kb[0].name
    driver = key_blocks[kb_name].driver_add('value')
    driverbone = [db.driverbonestore for db in 
                bpy.context.scene.archived]      
    shapekeys_drivers(driver, driverbone[0])
    select_all('DESELECT')
    active_object(armature_name[0])
    obj = bpy.context.object
    mode_set('POSE')
    select_all('SELECT')
    ops.pose.transforms_clear()
    select_all('DESELECT')
    obj.data.bones.active = obj.data.bones[kb_name]
    obj.data.bones.active.select = True
    bone_layers = range(32)
    for layer in bone_layers:
        obj.data.layers[layer] = False
        obj.data.layers[1] = True 

    obj.data.layers_protected[30] = False
Example #16
0
def configure_lipsync(mode):
    sorting_objects()
    obj = bpy.context.object
    bone = obj.data.bones.active
    for ch in bone.children:
        if ch.name[:10] == 'Arrow_bone':
            driverbone = ch.name
            
    stuff = bpy.context.scene.archived[0]
    stuff.driverbonestore = driverbone
    bonename = bone.name
    select_all('SELECT')
    ops.pose.user_transforms_clear()
    obj.data.layers_protected[30] = True
    select_all('DESELECT')
    mode_set('OBJECT')
    bone_shapekey(figure_name[0], bonename)
    obj = bpy.context.object
    obj.use_shape_key_edit_mode = True
    key_blocks[bonename].name = '...' + kb_names[indx]
    if mode == 'POSE':
        mode_set('OBJECT')
        select_all('DESELECT')
        active_object(armature_name[0])
        mode_set(mode)
    elif mode == 'SCULPT':
        mode_set(mode)
    else:
        return
Example #17
0
def apply_from_pose():
    active_object(figure_name[0])
    obj = bpy.context.object
    scene = bpy.context.scene
    maintool = scene.main_tool
    armaturename = maintool.armatures
    for mod in obj.modifiers:
        if (mod.type == 'ARMATURE' 
        and mod.object.name == armaturename):
            modifname =  deepcopy(mod.name)
            
    if bpy.app.version >= (2, 90, 0):
        ops.object.modifier_apply_as_shapekey(
        modifier=modifname)
    else:
        ops.object.modifier_apply(apply_as='SHAPE',
        modifier=modifname)
    keyname = obj.data.shape_keys.name
    key = bpy.data.shape_keys[keyname]
    existingshapekey = [sk for sk in key.key_blocks 
                    if sk.name[:3] == '...']
    newshapekey =  [sk for sk in key.key_blocks 
                    if sk.name == modifname]
    newshapekey[0].value = 1
    exshapekeyname = existingshapekey[0].name
    exshapekeyindx = obj.active_shape_key_index
    ops.object.shape_key_add(from_mix=True)
    mixshapekey = obj.active_shape_key
    shapekeylength = len(key.key_blocks)
    newshapekeyindx = shapekeylength - 2
    obj.active_shape_key_index = newshapekeyindx
    ops.object.shape_key_remove()
    obj.active_shape_key_index = exshapekeyindx
    ops.object.shape_key_remove()
    mixshapekey.name = exshapekeyname
    active_object(armature_name[0])
    ops.object.parent_set(type='ARMATURE_NAME')
    select_all('DESELECT')
    apply_from_edit()
Example #18
0
    def get_policy_run_data(self,
                            sim_config: int = None,
                            baseline: bool = True):

        if sim_config is None:
            sim_config = self._get_sim_base_config()
        else:
            sql = "SELECT id FROM sim_config WHERE id = {}".format(P_MARKER)
            row = select_record(self.db, sql=sql, params=(sim_config, ))
            assert row is not None, "Invalid Sim Config id {}".format(
                sim_config)
            sim_config, = row

        sql = '''SELECT policy_id, policy_run.id, time_start, results 
                 FROM policy_run
                 INNER JOIN policy ON policy_run.policy_id = policy.id
                 WHERE policy.sim_config_id = {}'''.format(P_MARKER)
        params = (sim_config, )
        policy_run = select_all(self.db, sql=sql, params=params)
        df = pd.DataFrame(
            [["ai_policy{}_run{}".format(policy_id, run_id), time, x]
             for policy_id, run_id, time, l in policy_run
             for x in json.loads(l)],
            columns=['policy', 'time', 'reward'])
        if baseline:
            sql = '''SELECT id, time_start, results 
                     FROM baseline_run
                     WHERE sim_config_id = {}'''.format(P_MARKER)
            params = (sim_config, )
            baseline_run = select_all(self.db, sql=sql, params=params)
            df2 = pd.DataFrame([["baseline_run{}".format(run_id), time, x]
                                for run_id, time, l in baseline_run
                                for x in json.loads(l)],
                               columns=['policy', 'time', 'reward'])
            df = df.append(df2)

        return df
Example #19
0
 def on_music_search_page_selectall(self, widget):
     """
     Select all
     """
     select_all(self.music_search_liststore, widget)    
Example #20
0
    def run_policies(self, policy: [int, list] = None, simulations: int = 1):

        select_policy_sql = '''SELECT id FROM policy
                                 WHERE sim_model_id = {}'''.format(P_MARKER)
        all_policies = select_all(self.db,
                                  sql=select_policy_sql,
                                  params=(self._model_id, ))
        all_policies = {t[0] for t in all_policies}

        if isinstance(policy, int):
            assert policy in all_policies, "Invalid session id {}".format(
                policy)
            policies = (policy, )
        elif isinstance(policy, list):
            assert set(policy).issubset(
                all_policies), "Invalid sessions list {}".format(policy)
            policies = tuple(policy)
        else:
            policies = tuple(all_policies)

        select_policy_sql = '''SELECT policy.id, checkpoint, agent_config, sim_config.config as s_config
                               FROM policy INNER JOIN sim_config ON policy.sim_config_id = sim_config.id
                               WHERE policy.id IN ({})'''.format(
            SQLParamList(len(policies)))
        policy_data = select_all(self.db,
                                 sql=select_policy_sql,
                                 params=policies)

        for policy_id, checkpoint, saved_agent_config, saved_sim_config in policy_data:

            print("# Running AI Policy {} started at {}!".format(
                policy_id, datetime.now()))

            agent_config = self._config.copy()
            agent_config.update(json.loads(saved_agent_config))

            sim_config = json.loads(saved_sim_config)

            agent = ppo.PPOTrainer(config=agent_config)
            agent.restore(checkpoint)

            time_start = datetime.now()
            # instantiate env class
            agent_config["env_config"]["sim_config"].update(sim_config)
            he = SimpyEnv(agent_config["env_config"])

            result_list = []
            for i in range(simulations):
                # run until episode ends
                episode_reward = 0
                done = False
                obs = he.reset()
                while not done:
                    action = agent.compute_action(obs)
                    obs, reward, done, info = he.step(action)
                    episode_reward += reward
                result_list.append(episode_reward)
                print("# Progress: {:2.1%} ".format((i + 1) / simulations),
                      end="\r")
            policy_run_data = (policy_id, time_start, simulations,
                               (datetime.now() - time_start).total_seconds(),
                               json.dumps(result_list))
            self._add_policy_run(policy_run_data)
            print("# Progress: {:2.1%} ".format(1))
            print("# Running AI Policy {} ended at {}!".format(
                policy_id, datetime.now()))
Example #21
0
def create_lipsync():
    objs = bpy.data.objects 
    genesis = [obj.name for obj in objs 
            if obj.name[:7] == 'Genesis']
    rig = [obj.name for obj in objs 
            if obj.name == 'rig']
    gnsarma = [obj.name for obj in objs 
            if obj.name == 'GNSrig']
    scene = bpy.context.scene
    tool = scene.main_tool
    automodify = tool.auto_modify
    if not tool.armatures:
        return [ERROR, except_msg[14]] 
    if not tool.meshes:
        return [ERROR, except_msg[15]] 
    if automodify:
        if not genesis:
            return [ERROR, except_msg[16]] 
        elif not rig:
            return [ERROR, except_msg[17]]
        elif not gnsarma:
            return [ERROR, except_msg[18]]

    empty_name_holders()
    sorting_objects()
    scene = bpy.context.scene
    scene.transform_orientation_slots[0].type = 'GLOBAL'
    # Creating mesh of Bar custom shape
    snap_cursor('CENTER')
    ops.mesh.primitive_circle_add(
                                vertices=16, 
                                radius=0.25, 
                                enter_editmode=True)
    select_all('SELECT')
    ops.mesh.duplicate_move()
    ops.transform.resize(value=(0.9, 0.9, 0.9))
    select_all('DESELECT')
    mode_set('OBJECT')
    obj = bpy.context.object
    obj.name = 'Bar'
    me = obj.data
    for v1 in range(5,12):
        for v2 in range(21,28):
            me.vertices[v1].select = True
            me.vertices[v2].select = True
    mode_set('EDIT')
    ops.mesh.delete(type='VERT')
    select_all('SELECT')
    ops.mesh.edge_face_add()
    # Creating mesh for Arrow Custom Shape#
    #######################################
    mode_set('OBJECT')
    ops.mesh.primitive_plane_add(size=0.5, enter_editmode=True)
    ops.transform.resize(value=(0.1, 0.03, 1))
    select_all('DESELECT')
    mode_set('OBJECT')
    obj = bpy.context.object
    obj.name = 'Arrow'
    me = obj.data
    vert = [0,2]
    for v in vert:
        me.vertices[v].select = True
    mode_set('EDIT')
    ops.transform.translate(value=(-0.1, 0, 0))
    ops.mesh.extrude_region_move()
    ops.transform.resize(value=(1, 3, 1))
    ops.mesh.extrude_region_move(TRANSFORM_OT_translate={
                                    "value":(-0.075, 0, 0)})
    ops.mesh.merge(type='CENTER')
    select_all('DESELECT')
    mode_set('OBJECT')
    
     # Creating lip sync controller bones
    ####################################
    active_object(armature_name[0])
    objs = bpy.data.objects
    # Getting hieght of figure and bone
    global figheight
    figheight = objs[figure_name[0]].dimensions[2]
    if figheight > 2:
        pass
    else:
         figheight = 2  
    stuff = bpy.context.scene.archived.add()
    stuff.figheightstore = figheight
    mode_set('EDIT')
    arm =  bpy.context.object
    edit_bones = arm.data.edit_bones
    tailheight = {}
    for bone in edit_bones:
        tailheight[bone.tail[2]] = bone.name
        highesttail = max(tailheight)
    
    bone_layers = range(32)
    for layer in bone_layers:
        arm.data.layers[layer] = True 
        
    select_all('DESELECT')
    arrow_bone = edit_bones.new('Arrow_bone')        
    arrow_bone.select = True
    arrow_bone.length = 0.5
    bpy.ops.armature.select_more()

    # Manipulating bone scale and orientation
    arrow_bone.head[2] = highesttail
    arrow_bone.tail[2] = highesttail+1
    arrow_bone.length = figheight/20
    for layer in bone_layers:
        if layer == 1:
            arrow_bone.layers[layer] = True
        else:
            arrow_bone.layers[layer] = False
    
    ops.armature.calculate_roll(type='GLOBAL_NEG_Y')
    ops.transform.translate(value=(0.15, 0, -0.3))
    
    # Adding Text to serve as custom shape
    mode_set('OBJECT')
    ops.object.text_add()
    obj = bpy.context.object
    if bpy.app.version >= (2, 90, 0):
        ops.transform.rotate(value=-1.5708, orient_axis='X')
    else:
        ops.transform.rotate(value=1.5708, orient_axis='X')
        
    ops.transform.resize(value=(0.04, 0.04, 0.04))
    obj.display.show_shadows = False
    obj.hide_render = True
    obj.data.body = 'A-H-J'
    obj.data.fill_mode = 'NONE'  
    obj.data.offset_x = figheight/4
    # Creating Text customshape duplicates
    active_object('Text')
    duplicate_selected_text('B-M-P')
    duplicate_selected_text('C-D-E')
    duplicate_selected_text('F-V')
    duplicate_selected_text('I-R')
    duplicate_selected_text('L-Th') 
    duplicate_selected_text('Q-U-W')
    duplicate_selected_text('O-Y')
    #Creating bar bone
    active_object(armature_name[0])
    arm =  bpy.context.object
    mode_set('EDIT')
    ops.armature.duplicate_move()
    edit_bones['Arrow_bone.001'].name = "Bar_bone"
    mode_set('POSE')
    arm.pose.bones["Bar_bone"].custom_shape = bpy.data.objects["Bar"]
    mode_set('EDIT')
    #Creating text bone
    ops.armature.duplicate_move()
    edit_bones['Bar_bone.001'].name = "Text_bone"
    textbone = edit_bones['Text_bone']
    textbone.length  = figheight/42
    mode_set('POSE')
    
    #adding custom shape to bone
    arm =  bpy.context.object
    global pose_bones
    pose_bones = arm.pose.bones
    pose_arrow_bone = pose_bones["Arrow_bone"]
    pose_arrow_bone.custom_shape = bpy.data.objects["Arrow"]
    
    # Creating bone groups and assigning
    arm =  bpy.context.object
    pose_bones = arm.pose.bones
    barbone = pose_bones["Bar_bone"]
    pose_text_bone = arm.pose.bones["Text_bone"]
    lipctrl = arm.pose.bone_groups.new(name='Lips_ctrl')
    lipctrl.name = "lip_sync"
    lipctrl.color_set = 'THEME02'
    pointer_ctrl = arm.pose.bone_groups.new(name='pointer_ctrl')
    pointer_ctrl.name = "pointer_ctrl"
    pointer_ctrl.color_set = 'THEME09'
    barbone.bone_group = arm.pose.bone_groups['lip_sync']
    pose_text_bone.bone_group = arm.pose.bone_groups['lip_sync']
    pose_arrow_bone.bone_group = arm.pose.bone_groups['pointer_ctrl']
    
    # Limiting constraints
    limit_rot = pose_arrow_bone.constraints.new(type='LIMIT_ROTATION')
    limit_rot.use_limit_x = True
    limit_rot.use_limit_y = True
    limit_rot.use_limit_z = True
    limit_rot.min_z = -3.14159
    limit_rot.use_transform_limit = True
    limit_rot.owner_space = 'LOCAL'
    transform = pose_arrow_bone.constraints.new(type='TRANSFORM')
    transform.target = bpy.data.objects[armature_name[0]]
    transform.subtarget = "Text_bone"
    transform.use_motion_extrapolate = True
    transform.map_from = 'SCALE'
    transform.from_max_z_scale = 1.5
    transform.map_to = 'ROTATION'
    transform.to_max_z_rot = -3.14159
    transform.target_space = 'LOCAL'
    transform.owner_space = 'LOCAL'
    arm.data.bones["Arrow_bone"].use_deform = False
    ##############################################
    limit_scale = pose_text_bone.constraints.new(type='LIMIT_SCALE')
    limit_scale.use_min_x = True
    limit_scale.use_max_x = True
    limit_scale.use_min_y = True
    limit_scale.use_max_y = True
    limit_scale.use_min_z = True
    limit_scale.use_max_z = True
    limit_scale.owner_space = 'LOCAL'
    limit_scale.use_transform_limit = True
    limit_scale.min_x = 1
    limit_scale.max_x = 1
    limit_scale.min_y = 1
    limit_scale.max_y = 1
    limit_scale.min_z = 1
    limit_scale.max_z = 1.5
    limit_rot2 = pose_text_bone.constraints.new(type='LIMIT_ROTATION')
    limit_rot2.use_limit_x = True
    limit_rot2.use_limit_y = True
    limit_rot2.use_limit_z = True
    limit_rot2.owner_space = 'LOCAL'
        
    # Duplicating control bones
    mode_set('EDIT')
    new_bones= ('Arrow_bone', 'Bar_bone')
    for bones in new_bones:
        edit_bones[bones].parent = edit_bones['Text_bone']
        edit_bones[bones].select = True
        edit_bones[bones].hide_select = True 
    mode_set('POSE')
    mode_set('EDIT')
    times = 7
    while times:
        times -= 1
        duplicate_move = ops.armature.duplicate_move
        duplicate_move(TRANSFORM_OT_translate={"value":(0, 0, figheight/40)})
    
    # Adding custom bone and constraints targets
    mode_set('POSE')
    trg_bone = 'Text_bone'
    trg_bone2 = 'Arrow_bone'
    trg_obj = 'Text'
    flt =  0
    for bones in  pose_bones:
        while trg_bone == bones.name:
            pose_bones[trg_bone].custom_shape = bpy.data.objects[trg_obj]
            pose_bones[trg_bone2].constraints["Transformation"].subtarget = trg_bone
            flt += 0.001
            sflt = str(flt)
            if len(sflt) < 6:
                ext = sflt[1:]
            else:
                ext = sflt[1:5]
            trg_bone = trg_bone[:9] + ext
            trg_bone2 = trg_bone2[:10] + ext
            trg_obj = trg_obj[:4] + ext
            
    #Renaming Text bones              
    mode_set('EDIT')   
    lipsyncname = ['O-Y', 'Q-U-W', 'L-Th', 'I-R', 
                'F-V', 'C-D-E', 'B-M-P', 'A-H-J']
    shpkeyname = deepcopy(lipsyncname)
    lsbonename = deepcopy(lipsyncname)
    lsbname = deepcopy(lipsyncname)
    
    tbone = 'Text_bone'
    flt =  0       
    while lipsyncname:
        bname = lipsyncname[-1]
        edit_bones[tbone].name = bname
        flt += 0.001
        sflt = str(flt)
        if len(sflt) < 6:
            ext = sflt[1:]
        else:
            ext = sflt[1:5]
        tbone = tbone[:9] + ext
        lipsyncname.pop()
        
    # Moving pose bones
    ################################################
    mode_set('OBJECT')
    select_all('DESELECT')
    active_object(armature_name[0])
    arm =  bpy.context.object
    mode_set('POSE')
    select_all('SELECT')
    ops.pose.user_transforms_clear()
    
    #Create shapekeys
    scene = bpy.context.scene
    tool = scene.main_tool
    automodify = tool.auto_modify
    if automodify == True:
        lipbonecoord = [oy, quw, lth, ir, fv, cde, bmp, ahj]
        ahj.update(upd)  
        ir.update(upd)
        while shpkeyname:
            skname = shpkeyname[-1]
            lbname = lipbonecoord[-1]
            lip_bone_positioning(lbname)
            arma_create_lipsync_shapekeys(skname)
            shpkeyname.pop()             
            lipbonecoord.pop()
    else:
        while shpkeyname:
            skname = shpkeyname[-1]
            create_lipsync_shapekeys(skname)
            shpkeyname.pop()                   
    mode_set('OBJECT')
    # Adding drivers
    #####################################
    active_object(figure_name[0])
    obj = bpy.context.object
    obj.show_only_shape_key = False
    obj.use_shape_key_edit_mode = False
    shape_keys = obj.data.shape_keys
    key_blocks = shape_keys.key_blocks
    trg_bone2 = 'Arrow_bone'
    flt =  0
                
    while lsbonename:
        bname = lsbonename[-1]
        driver = key_blocks[bname].driver_add('value')
        shapekeys_drivers(driver, trg_bone2)
        flt += 0.001
        sflt = str(flt)
        if len(sflt) < 6:
            ext = sflt[1:]
        else:
            ext = sflt[1:5]
        trg_bone2 = trg_bone2[:10] + ext
        lsbonename.pop()
    
    select_all('DESELECT')
    active_object(armature_name[0])
    obj = bpy.context.object
    mode_set('POSE')
    trgbone = "Bar_bone"
    trgbone2 = "Arrow_bone"
    flt =  0
    
    while lsbname:
        bname = lsbname[-1]
        bone = obj.pose.bones[trgbone]
        sdriver = bone.driver_add('custom_shape_scale')
        driver_scripted(sdriver, bname)
        
        bone = obj.pose.bones[trgbone2]
        sdriver = bone.driver_add('custom_shape_scale')
        driver_scripted(sdriver, bname)
        flt += 0.001
        sflt = str(flt)
        if len(sflt) < 6:
            ext = sflt[1:]
        else:
            ext = sflt[1:5]
        trgbone = trgbone[:8] + ext
        trgbone2 = trgbone2[:10] + ext
        lsbname.pop()
    
    mode_set('OBJECT')    
    select_all('DESELECT')
    coll = bpy.data.collections.new('LS.Widget')
    if bpy.context.scene.collection.children:
        bpy.data.collections[0].children.link(coll)
    else:
        bpy.context.scene.collection.children.link(coll)
    coll.hide_viewport = True
    objs = bpy.data.objects
    for obj in objs:
        if obj.name == 'Bar' or obj.name =='Arrow' or obj.name[:4] == 'Text':
            obj.select_set(True)
            coll.objects.link(obj)
            ext_coll = obj.users_collection[0]
            ext_coll.objects.unlink(obj)   
    active_object(armature_name[0])
    mode_set('POSE')
    select_all('DESELECT')
    for layer in bone_layers:
        arm.data.layers[layer] = False
        arm.data.layers[1] = True 
        arm.data.layers_protected[30] = False
    return[SUCCESS]
Example #22
0
def mixamo_copy():
    mode_set('OBJECT')
    empty_name_holders()
    sorting_armature()
    objs = bpy.data.objects
    b=[]
    for a in objs:
        if a.type == 'ARMATURE':
            if a.name[:8] == "Armature" or a.name[:7] == 'Genesis':
                b.append(a)
                
    Arma2 = [ob for ob in bpy.data.objects 
            if ob.name == 'GNSrig']
    if not Arma2:
        return [ERROR, except_msg[10]]
    Arma = [arm for arm in objs
        if arm.type == 'ARMATURE' 
        and (arm.name[:8] == 'Armature' 
        or arm.name[:7] == 'Genesis')]
    if not Arma:
        return [ERROR, except_msg[11]]
    
    try:
        posebones = Arma2[0].pose.bones
        const = posebones['hip'].constraints['Copy Transforms']
        if const:
            if  len(b) > 1:
                for bone in Arma2[0].pose.bones:
                    CT = [c for c in bone.constraints
                    if c.type == 'COPY_TRANSFORMS'
                    or c.type == 'COPY_ROTATION']
                    for c in CT:
                        bone.constraints.remove(c)
                                  
                for a in b:
                    if a.users_collection[0].name == "Widgets":
                        b.remove(a)
                        a.users_collection[0].objects.unlink(a)
                        purge_scene()
                        
            else:
                return [ERROR, except_msg[12]]
    except:
        pass
                
    for a in b:
        if a.users_collection[0].name == "Widgets":
            b.remove(a)
            a.users_collection[0].objects.unlink(a)
            purge_scene()
            
    if  len(b) > 1:
        b.clear()
        return [ERROR, except_msg[12]]
    else:
        empty_name_holders()
        sorting_armature()
        if Arma2[0].users_collection[0].hide_viewport == False:
            disable_GNSrig()
        rig_coll = objs['rig'].users_collection[0]
        GNS_coll = objs['GNSrig'].users_collection[0]
        if GNS_coll != rig_coll:
            GNS_coll.hide_viewport = False
        select_all('DESELECT')
        active_object('GNSrig')
        obj = bpy.context.object
        obj.data.display_type = 'STICK'    
        copy_mixam_transform()
        mode_set('OBJECT')
        obj.animation_data_clear()
        select_all('DESELECT')
        arma3 = armature_name[0]
        active_object(arma3)     
        obj = bpy.context.object
        armature_coll = obj.users_collection
        for chd in bpy.context.object.children:
            chd.select_set(True)
        obj.select_set(False)
        bpy.ops.object.delete()
        active_object(armature_name[0])
        widget_coll = bpy.data.collections['Widgets']
        widget_coll.objects.link(obj)
        armature_coll[0].objects.unlink(obj)
        select_all('DESELECT')
        adjust_framelength()
        enable_GNSrig()
        empty_name_holders()
        sorting_objects()
        active_object('GNSrig')
        if figure_name[0][:8] == 'Genesis8':
            if arma3[:8] == 'Armature':
                tilt_mixamo_bones(-0.4, 266, 76)
                tilt_mixamo_bones(0.05, 446, 446)
                tilt_mixamo_bones(-0.05, 486, 486)
            elif arma3[:8] == 'Genesis3':
                tilt_mixamo_bones(-0.4, 666, 416)
                tilt_mixamo_bones(-0.05, 196, 196)
                tilt_mixamo_bones(0.05, 26, 26)
            elif arma3[:8] == 'Genesis2':
                tilt_mixamo_bones(-0.4,  376, 586)
                tilt_mixamo_bones(-0.05, 116, 116)
                tilt_mixamo_bones(0.05, 26, 26)
        if GNS_coll != rig_coll:
            GNS_coll.hide_viewport = True
        return [SUCCESS]
Example #23
0
def add_lip_ctrlr():
    if not figure_name:
        sorting_objects()
    #Getting highest bone
    mode_set('EDIT')
    select_all('DESELECT')
    obj = bpy.context.object
    editbones = obj.data.edit_bones
    figheight = [fh.figheightstore 
    for fh in bpy.context.scene.archived]
    for bone in editbones:
        bonelength = str(bone.length)
        extratedheight = str(figheight[0]/42)
        if bonelength[:5] == extratedheight[:5]:
            tailheight = {}
            tailheight[bone.tail[2]] = bone.name
            highesttail = max(tailheight) 
            highestbone = tailheight[highesttail]
    
    # Selecting highest bones and making a copy     
    mode_set('POSE')
    posebones = obj.pose.bones
    obj.data.bones.active = obj.data.bones[highestbone]
    posebone = posebones[highestbone]
    customshape = posebone.custom_shape
    customshapename = customshape.name
    mode_set('EDIT')
    editbone = editbones[highestbone]
    editbone.select = True
    for chld in editbone.children:
        chld.select = True
    
    mode_set('POSE')
    mode_set('EDIT')
    duplicate_move = ops.armature.duplicate_move
    duplicate_move(TRANSFORM_OT_translate={
                "value":(0, 0, figheight[0]/40)})
                
    #getting child and adding scale drivers
    mode_set('POSE') 
    obj.data.bones.active.name = 'New'       
    newbone = obj.data.bones.active
    newbonename = newbone.name 
    for ch in newbone.children:
        bname = ch.name
        bone = obj.pose.bones[bname]
        try:
            bone.driver_remove('custom_shape_scale')
        except:
            pass
        sdriver = bone.driver_add('custom_shape_scale')
        driver_scripted(sdriver, newbonename)
        if ch.name[:10] == 'Arrow_bone':
            driverbone = ch.name
    
    # Duplicating custom shape and storing
    mode_set('OBJECT')
    select_all('DESELECT')
    lscoll = bpy.data.collections['LS.Widget']
    lscoll.hide_viewport = False
    active_object(customshapename)
    bpy.ops.object.duplicate_move()
    obj = bpy.context.object
    newcustomshape = obj
    obj.data.body = newbonename
    select_all('DESELECT')
    # Creating Shapekey 
    active_object(figure_name[0])
    create_lipsync_shapekeys(newbonename)
    
    # Adding drivers
    mode_set('OBJECT')   
    select_all('DESELECT')
    active_object(figure_name[0])
    obj = bpy.context.object
    obj.show_only_shape_key = False
    obj.use_shape_key_edit_mode = False
    shape_keys = obj.data.shape_keys
    key_blocks = shape_keys.key_blocks
    driver = key_blocks[newbonename].driver_add('value')   
    shapekeys_drivers(driver, driverbone)
    select_all('DESELECT')
    lscoll.hide_viewport = True
    # Returning to pose mode
    active_object(armature_name[0])
    mode_set('POSE')
    posebones[newbonename].custom_shape = newcustomshape
Example #24
0
 def on_music_page_selectall(self, widget):
     """
     Select all the music
     """
     select_all(self.music_page_liststore, widget)
Example #25
0
 def on_album_search_page_selectall(self, widget):
     """
     Select all
     """
     select_all(self.album_search_liststore, widget)