Esempio n. 1
0
    def __init__(self, obj=None):
        self.obj = obj
        self.callback = None
        self.true_start_file = None
        self.frame = 0
        self.speaker = None

        if obj == None:
            logic.LibLoad(logic.expandPath("//core/misc/screen.blend"),
                          'Scene')
            obj = self.obj = logic.getCurrentScene().objects["__CORE__Screen"]
            obj.visible = False

        try:
            t = obj.meshes[0].materials[0].textures[0]
            if t == None: raise Exception
        except Exception:
            try:
                logic.LibLoad(logic.expandPath("//core/misc/screen.blend"),
                              'Mesh')
                obj.replaceMesh("__CORE__Screen")
            except Exception:
                utils.debug(
                    "Video not set, " + obj.name +
                    " object is not a screen. Make sure it has a texture to an image file. "
                )
                self.play = self.no_play
                self.replaceTexture = self.no_replaceTexture
Esempio n. 2
0
def unique_libload(file_path):
    '''Loads a unique instance of a blend.
    INPUTS:
        - file_path - path to the blend file
    OUTPUTS:
        - added_objects, the object that were added
    '''
    scene = logic.getCurrentScene()
    old_objects = scene.objects + scene.objectsInactive
    
    f = open(file_path, 'rb').read()
    identifier = file_path.split('.')[0] + "_lib" + str(.0)

    while identifier in logic.LibList():
        id = identifier.split('.')
        identifier = id[0] + '.' + str(int(id[1])+1)
    logic.LibLoad(identifier, 'Scene', f)
    
    all_obj = scene.objects + scene.objectsInactive
    
    added_objects = []
    
    for o in all_obj:
        if o not in old_objects:
            added_objects.append(o)


    return added_objects
Esempio n. 3
0
    def load_lib(file_path):

        if not (Loadmap.isFile(file_path) and Loadmap.isBlend(file_path)):
            print("no such file or is no blend file")
            print(file_path)
            return

        print("load lib %s" % Loadmap.makeLibName(file_path))
        try:
            f = open(file_path, 'rb')
            fb = f.read()
            identifier = Loadmap.makeLibName(file_path)
            print("libload %s " % identifier)
            logic.LibLoad(identifier,
                          'Scene',
                          fb,
                          load_actions=False,
                          verbose=True,
                          load_scripts=False,
                          async=False).onFinish = Loadmap.asyncLibLoad_cb
        finally:
            f.close()

        # set the physics of the loadad map to no colliiosn

    #    print(bpy.data.objects)
    #    for ob in bpy.context.scene.objects:
    #        if ob.type == 'MESH' and (ob.name.startswith("mapFrom")):
    #            ob.game.physics_type = 'NO_COLLISION'

        return identifier
Esempio n. 4
0
def load_external_models(name):

    ### Finds all the 'blend' files in the 'models' subdirectory
    files = [
        f for f in os.listdir(models_directory + '/' + name) if 'blend' in f
    ]
    debug_print("The files inside the folder {} are: ".format(name, files))

    ### Load each found file
    for f in files:
        model = models_directory + name + '/' + f  ### The file(s) in the "models" subfolder. "Name" is the name of the the subfolder. "f" is the filename of the blend file
        logic.LibLoad(model,
                      'Scene',
                      load_actions=False,
                      load_scripts=False,
                      async=False
                      )  ### Load it with LibLoad (async messes up the loading)
    def load_blender_file(self, file_name):
        """ Loads a blender file.
		@param file_name An absolute path to the file, or if a relative path such that
		the file will be looked for in the mission folder, in the user home resources folder,
		in the execution folder, or finally in the installation folder.
		@remarks Full scene will be loaded by default.
		"""
        # Locate the file
        file_path = self._locate_resource(file_name)
        if not file_path:
            return
        # Load it
        if file_path in g.LibList():
            return
        status = g.LibLoad(file_path,
                           'Scene',
                           load_actions=True,
                           verbose=True,
                           load_scripts=True)
Esempio n. 6
0
    def load_blender_file(self, file_name):
        # Locate the file
        file_path = self._locate_resource(file_name)
        if not file_path:
            print('Failure loading "{}":'.format(file_name))
            print('    File not found')
            return
        loaded = g.LibList()
        print(loaded)
        if file_path in loaded:
            return

        # Load it
        g.LibLoad(file_path,
                  'Scene',
                  load_actions=True,
                  verbose=True,
                  load_scripts=True)
        loaded = g.LibList()
        print(loaded)
Esempio n. 7
0
def START(cont):
    owner = cont.owner

    base.SC_HUD = owner.scene

    base.SC_HUD.post_draw.append(settings.SCREENSHOT)
    if settings.SCREENSHOT in base.SC_SCN.post_draw:
        base.SC_SCN.post_draw.remove(settings.SCREENSHOT)

    print("Loading HUD...")
    base.LEVEL["HUDData"] = {}

    libblend = base.DATA[
        "GAMEPATH"] + config.LIBRARY_PATH + "\\Game Assets HUD.blend"

    logic.LibLoad(libblend,
                  "Scene",
                  load_actions=True,
                  verbose=False,
                  load_scripts=True)

    logic.HUDCLASS = SceneManager()
Esempio n. 8
0
def loadIntoScene(filepath, mode, camera):
    """ Loads all objects/meshes/actions from another blend into the scene of the *camera*.

	Blends loaded with this method must have only 1 scene. They also need to have a Python controller conected with an always on module mode with the following string: ``main.libload``.
	This logic bricks are recomended to be used in an object that clearly is the main object of the scene or a camera if any. The name of the library is the filepath.

	:param string filepath: Relative path from the *data* folder where the blend file is placed.
	:param mode: The same mode that will be used on ``bge.logic.LibLoad()``, it's recomended to use "Scene".
	:type mode: "Scene","Mesh" or "Action"
	:param camera: The main camera of the scene (where logic bricks are used).
	:type camera: |KX_GameObject|

	.. note:: Trying to load multiple times the same file will throw an error. Instad use ObjectGenerator
	"""
    path = logic.expandPath("//../data/" + filepath)
    scene_to = camera.scene
    if scene_to == module.scene_gui:
        logic.LibLoad(path, mode, load_actions=True, load_scripts=False)
    elif scene_to == module.scene_game:
        module.libload_queue.append((path, mode))
        module._arecallbacks = True
    else:
        utils.debug("utils.loadIntoScene failed, the scene " + scene_to.name +
                    " is not running.")
Esempio n. 9
0
def GAME(cont):
	global CURRENT, PROFILE, DATA, WORLD, LEVEL, ACTIVE_LIBLOAD, GAME_STATE

	global SC_SCN, SC_RUN
	SC_SCN = cont.owner.scene
	SC_RUN = cont.owner

	scene = SC_SCN
	owner = SC_RUN

	spawn = owner.get("SPAWN", True)
	timer = owner.get("TIMER", None)
	black = owner.get("GFXBG", None)

	if spawn == False:
		#MAIN(cont)
		#GAME_STATE = "DONE"
		return "DONE"

	## SET SCENE ##
	if WORLD.get("NEWSCENE", None) != None and config.EMBEDDED_FIX == False:
		if WORLD["NEWSCENE"] != scene.name:
			if scene.replace(WORLD["NEWSCENE"]) == True:
				CURRENT["Level"] = None
				print(scene.name, WORLD["NEWSCENE"])
				GAME_STATE = "SCENE"
				return "SCENE"
			else:
				print("NOTICE: Scene '"+CURRENT["Scene"]+"' Not Found...")

	if GAME_STATE == "SCENE":
		settings.applyGraphics()

	CURRENT["Scene"] = scene.name

	## LEVEL DATA ##
	if WORLD.get("NEWLEVEL", None) != None:
		CURRENT["Level"] = WORLD["NEWLEVEL"]

	if CURRENT["Level"] == None and owner.get("MAP", None) != None:
		CURRENT["Level"] = owner["MAP"]+".blend"

	newmap = str(CURRENT["Level"])+scene.name

	WORLD["NEWLEVEL"] = CURRENT["Level"]
	WORLD["NEWSCENE"] = CURRENT["Scene"]

	if newmap not in PROFILE["LVLData"]:
		print("Initializing Level Data...", newmap)
		PROFILE["LVLData"][newmap] = settings.GenerateLevelData()

	LEVEL = PROFILE["LVLData"][newmap]

	## EARLY BAIL ##
	if config.EMBEDDED_FIX == True:
		owner["SPAWN"] = False
		GAME_STATE = "EMBEDDED"
		return "EMBEDDED"

	if black == None:
		owner["GFXBG"] = True
		GAME_STATE = "BLACK"
		return "BLACK"

	## LIBLOAD ##
	if owner.get("LIBLIST", None) == None:
		owner["LIBLIST"] = [COREBLENDS["ASSETS"]]
		for libblend in config.LIBRARIES:
			libblend = DATA["GAMEPATH"]+config.LIBRARY_PATH+"\\"+libblend+".blend"
			owner["LIBLIST"].append(libblend)
		GAME_STATE = "LIBLOAD"
		return "LIBLOAD"

	if ACTIVE_LIBLOAD != None:
		print(ACTIVE_LIBLOAD.libraryName, ACTIVE_LIBLOAD.progress)
		GAME_STATE = "LIBLOAD"
		return "LIBLOAD"

	if len(owner["LIBLIST"]) > 0:
		libblend = owner["LIBLIST"].pop(0)
		#if config.LIBLOAD_TYPE != "ASYNC":
		logic.LibLoad(libblend, "Scene", load_actions=True, verbose=False, load_scripts=True)
		print(libblend)
		#elif config.LIBLOAD_TYPE == "ASYNC":
		#	ACTIVE_LIBLOAD = logic.LibLoad(libblend, "Scene", load_actions=True, verbose=False, load_scripts=True, async=True)
		#	ACTIVE_LIBLOAD.onFinish = LIBCB

		GAME_STATE = "LIBLOAD"
		return "LIBLOAD"

	## HUD SCENE ##
	if timer == None:
		owner["TIMER"] = (config.UPBGE_FIX == False)*100

		owner.worldScale = [1,1,1]
		logic.addScene("HUD", 1)
		GAME_STATE = "HUD"
		return "HUD"

	elif timer <= 30:
		owner["TIMER"] += 1
		GAME_STATE = "TIMER"
		return "TIMER"

	## SPAWN ##
	if "CLIP" in owner:
		LEVEL["CLIP"] = owner["CLIP"]

	if spawn == True:
		LOAD(owner)
		SC_SCN.addObject("__gameloop__", owner, 0)
		owner["SPAWN"] = None
		GAME_STATE = "SPAWN"
		return "SPAWN"

	elif spawn == None:
		owner["SPAWN"] = False
		GAME_STATE = "DONE"
		return "DONE"

	GAME_STATE = "WAIT"
	return "WAIT"
Esempio n. 10
0
def load():
    logic.LibLoad("wall.blend","Scene")
    logic.LibNew('wall001','Mesh',['Monkey'])
Esempio n. 11
0
def importGeometry(meshFullPath,
                   mol=None,
                   molInfo=None,
                   template=None,
                   name="",
                   scale=None,
                   availableChains=None,
                   matrix=None,
                   largeRadius=False,
                   centerToScreen=True):
    '''Load mesh into the GE'''
    # get pdb id
    if template:
        pdbid = name
    else:
        pdbid = mol.name.lower()

    # open blend file to load in mesh data
    f = open(meshFullPath, 'rb')
    data = f.read()
    f.close()

    try:
        logic.LibLoad(pdbid, 'Mesh', data)
    except Exception as E:
        if "file already open" in str(E):
            print("Warning: Lib Mesh already loaded")
        else:
            # file not open, but other errors
            logic.logger.new("Error loading Mesh.", type="ERROR")
            return False

    cameraPivot = logic.controllerObject

    if scale:  # incoming is dimensions in nm
        scaling = scale
    else:
        scaling = [
            0.1, 0.1, 0.1
        ]  # assuming incoming model is in Ag (i.e. 1Blender Unit == 1 ang)

    objList = []
    if template:
        # get template obj, and use libLoad to replace the mesh of that object
        parentObj = "template" + str(
            logic.objCounter)  # because KX_Object.physicsProperty is messed up
        logic.objCounter += 1

        newObj = logic.scene.addObject(parentObj, cameraPivot, 0)

        # re-center
        np = [0, 0, 0]
        op = newObj.position
        newObj.position = [
            op[0] + np[0] * scaling[0], op[1] + np[1] * scaling[1],
            op[2] + np[2] * scaling[2]
        ]

        try:
            newObj.replaceMesh(template)
        except Exception as E:
            logging.error(E)
            newObj.endObject()
            logic.logger.new("%s not imported" % (pdbid), "ERROR")
        else:
            newObj.worldScale = scaling  # reset for more predictable behavior
            newObj.worldOrientation = [0.0, 0.0, 0.0
                                       ]  # reset for more predictable behavior
            newObj.reinstancePhysicsMesh()  # recalc physics
            newObj["name"] = name  # this, because KX_object.name is read-only

            # add pdb object and its data to module, datastore
            obj = logic.mvb.addObject(name,
                                      newObj,
                                      objType=1,
                                      molObj=name,
                                      scale=scale)
            obj.ribbonMesh = template
            obj.fineSurfaceMesh = template
            obj.surfaceMesh = template

            # apply default shader
            shader.initProtein(newObj, "default")

            logic.logger.new("Added to scene: " + str(name))
            objList.append(obj)
    else:
        # load real pdb surfaces
        parDir = os.path.dirname(meshFullPath)
        fp = open(os.path.join(parDir, "centers"), mode='rb')
        chainsCenter = pickle.load(fp)

        # make sure we have enough free object
        counter = 0
        for (key, visible) in availableChains.items():
            if visible:
                if matrix:
                    counter += len(matrix)
                else:
                    counter += 1
        if logic.objCounter + counter > maxObject:
            logic.logger.new(
                str(counter) + " is too many objects in scene", "ERROR")
            return False

        delayedError = []
        delayedOkay = []

        # prepare group name
        usedParentNames = [
            obj.parent for name, obj in logic.mvb.objects.items()
        ]
        parentName = datastoreUtils.incrementName(pdbid, usedParentNames)

        # loop through all chains
        for (key, visible) in availableChains.items():

            if visible:
                if matrix:
                    for i, transform in matrix.items():

                        # get template obj, and use libLoad to replace the mesh of that object
                        parentObj = "template" + str(
                            logic.objCounter
                        )  # this, because KX_Object.physicsProperty is messed up
                        logic.objCounter += 1

                        cmsMeshname = pdbid + '_' + key + '_cms'

                        newObj = logic.scene.addObject(parentObj, cameraPivot,
                                                       0)

                        # transform
                        mat = mathutils.Matrix()
                        mat[0] = transform[0]
                        mat[1] = transform[1]
                        mat[2] = transform[2]
                        loc = mat.to_translation()
                        rot = mat.to_euler()

                        op = loc
                        newObj.position = [
                            op[0] * scaling[0], op[1] * scaling[1],
                            op[2] * scaling[2]
                        ]
                        newObj.worldOrientation = rot

                        failed = False

                        try:
                            newObj.replaceMesh(cmsMeshname)
                        except Exception as E:
                            logging.warning(E)
                            failed = True

                        if failed:
                            newObj.endObject()
                            delayedError.append("%s:%s not imported" %
                                                (pdbid, key))
                        else:
                            newObj.worldScale = scaling  # reset for more predictable behavior
                            newObj.reinstancePhysicsMesh()  # recalc physics

                            chain = None
                            for c in mol.chains:
                                if key == c.name:
                                    chain = c
                            if not chain:
                                logging.warning(
                                    "Matching chain PDB data cannot be found")

                            # add pdb object and its data to module, datastore
                            name = pdbid + '_' + key
                            name = datastoreUtils.incrementName(
                                name, logic.mvb.objects)

                            obj = logic.mvb.addObject(name,
                                                      newObj,
                                                      objType=0,
                                                      molObj=mol,
                                                      chainObj=chain,
                                                      molInfo=molInfo,
                                                      parent=parentName)
                            obj.SESLargeRadius = largeRadius
                            obj.ribbonMesh = cmsMeshname
                            obj.fineSurfaceMesh = cmsMeshname
                            obj.surfaceMesh = cmsMeshname

                            # apply default shader
                            shader.initProtein(newObj, "default")
                            delayedOkay.append("Added to scene: " + str(name))

                            obj.matrix = matrix

                else:
                    # get template obj, and use libLoad to replace the mesh of that object
                    parentObj = "template" + str(
                        logic.objCounter
                    )  # this, because KX_Object.physicsProperty is messed up
                    logic.objCounter += 1

                    msmsMeshname = pdbid + '_' + key + '_msms'
                    cmsMeshname = pdbid + '_' + key + '_cms'
                    ribbonMeshname = pdbid + '_' + key + '_bb'

                    newObj = logic.scene.addObject(parentObj, cameraPivot, 0)

                    # re-center
                    np = chainsCenter[key]
                    op = newObj.position

                    if centerToScreen:
                        newObj.position = [
                            op[0] + np[0] * scaling[0],
                            op[1] + np[1] * scaling[1],
                            op[2] + np[2] * scaling[2]
                        ]
                    else:
                        newObj.position = [
                            np[0] * scaling[0], np[1] * scaling[1],
                            np[2] * scaling[2]
                        ]

                    failed = False

                    try:
                        newObj.replaceMesh(msmsMeshname)
                    except Exception as E:
                        logging.warning(E)
                        failed = True

                    if failed:
                        try:
                            newObj.replaceMesh(cmsMeshname)
                            failed = False
                        except Exception as E:
                            logging.warning(E)
                            failed = True

                    if failed:
                        try:
                            newObj.replaceMesh(ribbonMeshname)
                            failed = False
                        except Exception as E:
                            logging.warning(E)
                            failed = True

                    if failed:
                        newObj.endObject()
                        delayedError.append("%s:%s not imported" %
                                            (pdbid, key))
                    else:
                        newObj.worldScale = scaling  # reset for more predictable behavior
                        newObj.worldOrientation = [
                            0.0, 0.0, 0.0
                        ]  # reset for more predictable behavior
                        newObj.reinstancePhysicsMesh()  # recalc physics

                        chain = None
                        for c in mol.chains:
                            if key == c.name:
                                chain = c
                        if not chain:
                            logging.warning(
                                "Matching chain PDB data cannot be found")

                        # add pdb object and its data to module, datastore
                        name = pdbid + '_' + key
                        name = datastoreUtils.incrementName(
                            name, logic.mvb.objects)

                        obj = logic.mvb.addObject(name,
                                                  newObj,
                                                  objType=0,
                                                  molObj=mol,
                                                  chainObj=chain,
                                                  molInfo=molInfo,
                                                  parent=parentName)
                        obj.SESLargeRadius = largeRadius
                        obj.ribbonMesh = ribbonMeshname
                        obj.fineSurfaceMesh = msmsMeshname
                        obj.surfaceMesh = cmsMeshname

                        # apply default shader
                        shader.initProtein(newObj, "default")
                        delayedOkay.append("Added to scene: " + str(name))

                        objList.append(obj)

        for msg in delayedOkay:
            logic.logger.new(msg)

        for error in delayedError:
            logic.logger.new(error, "ERROR")

        if delayedError:
            logic.pluggable.loader.loadPDBError.notify()
        else:
            # no error:
            logic.pluggable.loader.loadPDB.notify()

            # mark cache as good
            parDir = os.path.dirname(meshFullPath)
            filePath = os.path.join(parDir, 'validCache')
            open(filePath, 'a').close()

    logic.gui.showFullUI()
    logic.mvb.slides[logic.mvb.activeSlide].capture()

    return objList