예제 #1
0
    def reload(self):
        if self.__always_enable:
            self.__button['state'] = DGG.NORMAL
        else:
            self.__button['state'] = DGG.DISABLED
        datafile = game_settings[
            'save_folder'] + self.__fileName + game_settings['save_type']
        infofile = game_settings[
            'save_folder'] + self.__fileName + game_settings['save_infotype']
        if exists(datafile) and exists(infofile):
            infostream = open(
                game_settings['save_folder'] + self.__fileName +
                game_settings['save_infotype'], 'rb')
            info = pickle.load(infostream)
            infostream.close()
            temp = info.text.splitlines()
            if temp:
                text = temp[0]
            else:
                text = ''

            if len(text) > 15:
                text = text[0:13] + '...'
            self.__text.setText(self.__head + '\n' +
                                info.time.strftime('%Y-%m-%d %H:%M') + '\n' +
                                '  ' + text)
            self.__button['state'] = DGG.NORMAL
            self.__exists = True
        else:
            self.__text.setText(self.__head + '\n    NO DATA')
            self.__exists = False
예제 #2
0
def loadModel(file, collision=None, animation=None):
    model=None
    if animation:
        model=Actor(file, animation)                   
        #default anim
        if 'default' in animation:
            model.loop('default')
        elif 'idle' in animation:
            model.loop('idle')
        else: #some random anim
             model.loop(animation.items()[0])
    else:
        model=loader.loadModel(file)
    model.setPythonTag('model_file', file)
    #load shaders
    for geom in model.findAllMatches('**/+GeomNode'):
        if geom.hasTag('light'):
            model.setPythonTag('hasLight', True)
        if geom.hasTag('particle'):
            file='particle/'+geom.getTag('particle')
            if exists(file):
                with open(file) as f:  
                    values=json.load(f)
                p=createEffect(values)                
                model.setPythonTag('particle', p)    
                p.start(parent=model, renderParent=render) 
        if geom.hasTag('cg_shader'):            
            geom.setShader(loader.loadShader("shaders/"+geom.getTag('cg_shader')))
        elif geom.hasTag('glsl_shader'):  
            glsl_shader=geom.getTag('glsl_shader')  
            geom.setShader(Shader.load(Shader.SLGLSL, "shaders/{0}_v.glsl".format(glsl_shader),"shaders/{0}_f.glsl".format(glsl_shader)))
        else:
            #geom.setShader(loader.loadShader("shaders/default.cg"))
            geom.setShader(Shader.load(Shader.SLGLSL, "shaders/default_v.glsl","shaders/default_f.glsl"))
    #collisions        
    model.setCollideMask(BitMask32.allOff())
    if collision:
        coll=loader.loadModel(collision)
        coll.reparentTo(model)
        coll.find('**/collision').setCollideMask(BitMask32.bit(2))        
        coll.find('**/collision').setPythonTag('object', model)
        if animation:
            model.setPythonTag('actor_files', [file,animation,coll]) 
    else:
        try:
            model.find('**/collision').setCollideMask(BitMask32.bit(2))        
            model.find('**/collision').setPythonTag('object', model)        
        except:
            print "WARNING: Model {0} has no collision geometry!\nGenerating collision sphere...".format(file)
            bounds=model.getBounds()
            radi=bounds.getRadius()
            cent=bounds.getCenter()
            coll_sphere=model.attachNewNode(CollisionNode('collision'))
            coll_sphere.node().addSolid(CollisionSphere(cent[0],cent[1],cent[2], radi)) 
            coll_sphere.setCollideMask(BitMask32.bit(2))        
            coll_sphere.setPythonTag('object', model)
            #coll_sphere.show()
            if animation:
                model.setPythonTag('actor_files', [file,animation,None])
    return model
예제 #3
0
 def playSound(self, path, volume = 1):
     pathes = game_settings['sfxpathes']
     types = game_settings['soundtypes']
     for ft in ((folder,type) for folder in pathes for type in types):
         if exists(ft[0] + path + ft[1]):
             path = ft[0] + path + ft[1]
             break
     play(path,self.sfxMgr, volume = volume)
예제 #4
0
 def playSound(self, path, volume=1):
     pathes = game_settings['sfxpathes']
     types = game_settings['soundtypes']
     for ft in ((folder, type) for folder in pathes for type in types):
         if exists(ft[0] + path + ft[1]):
             path = ft[0] + path + ft[1]
             break
     play(path, self.sfxMgr, volume=volume)
예제 #5
0
 def _loadGlobalData(self):
     if not exists(game_settings['save_folder'] + 'global.dat'):
         return
     try:
         gdata = load_data(game_settings['save_folder'] + 'global.dat')
     except Exception as exp:
         safeprint(exp)
         return
     restoreGlobalData(gdata)
예제 #6
0
 def _loadReadText(self):
     if not exists(game_settings['save_folder'] + 'read.dat'):
         return
     try:
         read = load_data(game_settings['save_folder'] + 'read.dat')
     except Exception as exp:
         safeprint(exp)
         return
     restoreReadText(read)
예제 #7
0
 def loadModel(self, model):
     self.currentScale=1.0
     self.currentHPR=[0, 0, 0]
     self.currentZ=0.0
     self.isLocked=False
     if self.currentObject!=None:
         self.currentObject.removeNode()
     self.currentObject=loader.loadModel(model)
     self.currentObject.reparentTo(render)
     self.currentObject.setPythonTag('props', '')
     self.currentObject.setHpr(self.currentHPR[0],self.currentHPR[1],self.currentHPR[2])
     self.currentObject.setZ(self.currentZ)
     self.currentObject.setScale(self.currentScale) 
     for geom in self.currentObject.findAllMatches('**/+GeomNode'):
         if geom.hasTag('light'): 
             self.currentLight=self.lightManager.addLight(pos=self.currentObject.getPos(), color=(1.0, 1.0, 1.0), radius=10.0)
             self.currentObject.setPythonTag('hasLight', self.currentLight)
             self.currentHPR=[255.0, 255.0, 255.0]   
         if geom.hasTag('particle'):
             file='particle/'+geom.getTag('particle')
             if exists(file):
                 with open(file) as f:  
                     values=json.load(f)
                 p=createEffect(values)                
                 self.currentObject.setPythonTag('particle', p)    
                 p.start(parent=self.currentObject, renderParent=render)         
     if geom.hasTag('glsl_shader'): 
         glsl_shader=geom.getTag('glsl_shader')  
         self.currentObject.setShader(Shader.load(Shader.SLGLSL, "shaders/{0}_v.glsl".format(glsl_shader),"shaders/{0}_f.glsl".format(glsl_shader)))
     else:            
         self.currentObject.setShader(Shader.load(Shader.SLGLSL, "shaders/default_v.glsl","shaders/default_f.glsl"))
     
     if self.currentObject.find('**/navmesh_terrain'):            
         self.isLocked=True
         self.currentObject.find('**/navmesh_terrain').hide()
     if self.currentObject.find('**/navmesh_tile'):
         self.isLocked=True
         self.currentObject.find('**/navmesh_tile').hide()
     if self.currentObject.find('**/collision'):            
         self.currentObject.find('**/collision').hide()
     
     for tex_stage in self.currentObject.findAllTextureStages():            
         tex=self.currentObject.findTexture(tex_stage)
         if tex:
             file_name=tex.getFilename()
             tex_format=tex.getFormat()   
             #print tex_stage,  file_name, tex_format                
             newTex=loader.loadTexture(str(file_name)[:-3]+'dds')
             if tex_stage.getMode()==TextureStage.M_normal:
                 tex_stage.setMode(TextureStage.M_normal_gloss)
             if tex_stage.getMode()!=TextureStage.M_normal_gloss:
                 if tex_format==Texture.F_rgb:
                     tex_format=Texture.F_srgb
                 elif tex_format==Texture.F_rgba:
                     tex_format=Texture.F_srgb_alpha    
             newTex.setFormat(tex_format)
             self.currentObject.setTexture(tex_stage, newTex, 1)
예제 #8
0
 def _loadSettings(self):
     if not exists(game_settings['save_folder']+ 'config.dat'):
         return
     try:
         settings = load_data(game_settings['save_folder'] + 'config.dat')
     except Exception as error:
         safeprint(error)
         return    
     restoreSettings(settings)
예제 #9
0
 def _loadGlobalData(self):
     if not exists(game_settings['save_folder']+ 'global.dat'):
         return
     try:
         gdata = load_data(game_settings['save_folder']+ 'global.dat')
     except Exception as exp:
         safeprint(exp)
         return
     restoreGlobalData(gdata)
예제 #10
0
 def _loadReadText(self):
     if not exists(game_settings['save_folder']+ 'read.dat'):
         return
     try:
         read = load_data(game_settings['save_folder']+ 'read.dat')
     except Exception as exp:
         safeprint(exp)
         return
     restoreReadText(read)
예제 #11
0
 def _loadSettings(self):
     if not exists(game_settings['save_folder'] + 'config.dat'):
         return
     try:
         settings = load_data(game_settings['save_folder'] + 'config.dat')
     except Exception as error:
         safeprint(error)
         return
     restoreSettings(settings)
예제 #12
0
 def playBGM(self, path, fadein = 0, volume = 1, loop = True):
     if self._currentBGM:    #if there is a music playing then stop it
         self.stopBGM(fadein)
     RuntimeData.current_bgm = [path,fadein,volume,loop] #save for loading
     pathes = game_settings['musicpathes']
     types = game_settings['soundtypes']
     for ft in ((folder,type) for folder in pathes for type in types):
         if exists(ft[0] + path + ft[1]):
             path = ft[0] + path + ft[1]
             break
     loader.loadSound(self.bgmMgr,
                  path,
                  callback = self._setAndPlayBGM,extraArgs = [fadein, volume, loop]) 
예제 #13
0
 def playENV(self, path, fadein = 0, volume = 1, loop = True):
     if self._currentENV:
         self.stopENV(fadein)
     RuntimeData.current_env = [path,fadein,volume,loop]
     pathes = game_settings['envsoundpathes']
     types = game_settings['soundtypes']
     for ft in ((folder,type) for folder in pathes for type in types):
         if exists(ft[0] + path + ft[1]):
             path = ft[0] + path + ft[1]
             break
     loader.loadSound(self.envMgr,
                  path,
                  callback = self._setAndPlayENV,extraArgs = [fadein, volume, loop]) 
예제 #14
0
 def playENV(self, path, fadein=0, volume=1, loop=True):
     if self._currentENV:
         self.stopENV(fadein)
     RuntimeData.current_env = [path, fadein, volume, loop]
     pathes = game_settings['envsoundpathes']
     types = game_settings['soundtypes']
     for ft in ((folder, type) for folder in pathes for type in types):
         if exists(ft[0] + path + ft[1]):
             path = ft[0] + path + ft[1]
             break
     loader.loadSound(self.envMgr,
                      path,
                      callback=self._setAndPlayENV,
                      extraArgs=[fadein, volume, loop])
예제 #15
0
 def runScriptFile(self,fileName):
     #'''note that would ignore panda virtual pathes'''
     pathes = runtime_data.game_settings['pscriptpathes']
     types = runtime_data.game_settings['pscripttypes']
     for ft in ((folder,type) for folder in pathes for type in types):
         if exists(ft[0] + fileName + ft[1]):
             handle = open(ft[0] + fileName + ft[1])
             script = handle.read()
             handle.close()
             break
     if script:
         self.runScript(script)
     else:
         safeprint("file not find: "+ fileName) 
예제 #16
0
 def reload(self):
     if self.__always_enable:
         self.__button['state'] = DGG.NORMAL
     else: self.__button['state'] = DGG.DISABLED
     datafile = game_settings['save_folder']+ self.__fileName + game_settings['save_type']
     infofile = game_settings['save_folder']+ self.__fileName + game_settings['save_infotype']
     if exists(datafile) and exists(infofile):
         infostream = open(game_settings['save_folder']+ self.__fileName + game_settings['save_infotype'],'rb')
         info = pickle.load(infostream)
         infostream.close()
         temp = info.text.splitlines()
         if temp:
             text = temp[0]
         else: text = ''
         
         if len(text)>15:
             text = text[0:13] + '...'
         self.__text.setText(self.__head+'\n'+info.time.strftime('%Y-%m-%d %H:%M')+'\n'+'  '+text)
         self.__button['state'] = DGG.NORMAL
         self.__exists = True
     else: 
         self.__text.setText(self.__head + '\n    NO DATA')
         self.__exists = False
예제 #17
0
 def playBGM(self, path, fadein=0, volume=1, loop=True):
     if self._currentBGM:  #if there is a music playing then stop it
         self.stopBGM(fadein)
     RuntimeData.current_bgm = [path, fadein, volume,
                                loop]  #save for loading
     pathes = game_settings['musicpathes']
     types = game_settings['soundtypes']
     for ft in ((folder, type) for folder in pathes for type in types):
         if exists(ft[0] + path + ft[1]):
             path = ft[0] + path + ft[1]
             break
     loader.loadSound(self.bgmMgr,
                      path,
                      callback=self._setAndPlayBGM,
                      extraArgs=[fadein, volume, loop])
예제 #18
0
파일: main.py 프로젝트: wezu/p3d_launcher
 def __init__(self):
     #init ShowBase
     base = ShowBase.ShowBase()        
     #make the path a builtin
     builtins.path=path 
     
     if exists(path+'setup.json'):
         #the setup dict can be loaded from
         #-a json file
         #-a pickeled dict
         #-xml
         #-yaml
         #-any other file that can serialize a python dict
         #-or it could be here as a python dict
         #I used object_pairs_hook=OrderedDict to perserve the order of options
         with open(path+'setup.json') as f:  
             setup_data=json.load(f, object_pairs_hook=OrderedDict)
         #if some custom functions are needed you can add them here
         # and set the func value in the setup data e.g "func":"someCustomFunction(42)"
         functions={'someCustomFunction':self.someCustomFunction}        
         
         #launch the Launcher
         self.launcher=Launcher(self, setup_data, functions)
예제 #19
0
파일: main.py 프로젝트: wezu/p3d_launcher
    def __init__(self):
        #init ShowBase
        base = ShowBase.ShowBase()
        #make the path a builtin
        builtins.path = path

        if exists(path + 'setup.json'):
            #the setup dict can be loaded from
            #-a json file
            #-a pickeled dict
            #-xml
            #-yaml
            #-any other file that can serialize a python dict
            #-or it could be here as a python dict
            #I used object_pairs_hook=OrderedDict to perserve the order of options
            with open(path + 'setup.json') as f:
                setup_data = json.load(f, object_pairs_hook=OrderedDict)
            #if some custom functions are needed you can add them here
            # and set the func value in the setup data e.g "func":"someCustomFunction(42)"
            functions = {'someCustomFunction': self.someCustomFunction}

            #launch the Launcher
            self.launcher = Launcher(self, setup_data, functions)
예제 #20
0
    def loadModel(self, model):
        self.currentScale = 1.0
        self.currentHPR = [0, 0, 0]
        self.currentZ = 0.0
        self.isLocked = False
        if self.currentObject != None:
            self.currentObject.removeNode()
        self.currentObject = loader.loadModel(model)
        self.currentObject.reparentTo(render)
        self.currentObject.setPythonTag('props', '')
        self.currentObject.setHpr(self.currentHPR[0], self.currentHPR[1],
                                  self.currentHPR[2])
        self.currentObject.setZ(self.currentZ)
        self.currentObject.setScale(self.currentScale)
        for geom in self.currentObject.findAllMatches('**/+GeomNode'):
            if geom.hasTag('light'):
                self.currentLight = self.lightManager.addLight(
                    pos=self.currentObject.getPos(),
                    color=(1.0, 1.0, 1.0),
                    radius=10.0)
                self.currentObject.setPythonTag('hasLight', self.currentLight)
                self.currentHPR = [255.0, 255.0, 255.0]
            if geom.hasTag('particle'):
                file = 'particle/' + geom.getTag('particle')
                if exists(file):
                    with open(file) as f:
                        values = json.load(f)
                    p = createEffect(values)
                    self.currentObject.setPythonTag('particle', p)
                    p.start(parent=self.currentObject, renderParent=render)
        if geom.hasTag('glsl_shader'):
            glsl_shader = geom.getTag('glsl_shader')
            self.currentObject.setShader(
                Shader.load(Shader.SLGLSL,
                            "shaders/{0}_v.glsl".format(glsl_shader),
                            "shaders/{0}_f.glsl".format(glsl_shader)))
        else:
            self.currentObject.setShader(
                Shader.load(Shader.SLGLSL, "shaders/default_v.glsl",
                            "shaders/default_f.glsl"))

        if self.currentObject.find('**/navmesh_terrain'):
            self.isLocked = True
            self.currentObject.find('**/navmesh_terrain').hide()
        if self.currentObject.find('**/navmesh_tile'):
            self.isLocked = True
            self.currentObject.find('**/navmesh_tile').hide()
        if self.currentObject.find('**/collision'):
            self.currentObject.find('**/collision').hide()

        for tex_stage in self.currentObject.findAllTextureStages():
            tex = self.currentObject.findTexture(tex_stage)
            if tex:
                file_name = tex.getFilename()
                tex_format = tex.getFormat()
                #print tex_stage,  file_name, tex_format
                newTex = loader.loadTexture(str(file_name)[:-3] + 'dds')
                if tex_stage.getMode() == TextureStage.M_normal:
                    tex_stage.setMode(TextureStage.M_normal_gloss)
                if tex_stage.getMode() != TextureStage.M_normal_gloss:
                    if tex_format == Texture.F_rgb:
                        tex_format = Texture.F_srgb
                    elif tex_format == Texture.F_rgba:
                        tex_format = Texture.F_srgb_alpha
                newTex.setFormat(tex_format)
                self.currentObject.setTexture(tex_stage, newTex, 1)
예제 #21
0
    def _createItem(self, entry, ignore_fadein = False):
        '''Create an item(not including adding this to itemEntries)'''
        imagepathes = runtime_data.game_settings['imagepathes']
        imagetypes = runtime_data.game_settings['imagetypes']
        modelpathes = runtime_data.game_settings['modelpathes']
        modeltypes = runtime_data.game_settings['modeltypes']
        
        if self._sceneItems.has_key(entry.key):
            self._sceneItems[entry.key].removeNode()
            self._sceneItems.pop(entry.key)
        item = None
        if entry.category == SVIC.FG or entry.category == SVIC.BG or entry.category == SVIC.O2D:

            
            texture = None
            for ft in ((folder,type) for folder in imagepathes for type in imagetypes):
                if exists(ft[0] + entry.fileName + ft[1]):
                    texture = loader.loadTexture(ft[0] + entry.fileName + ft[1])
                    break
            
                
            '''Alternative
            item = loader.loadModel(r"models/plain.egg")
            item.setTexture(texture, 1)
            '''
            item = OnscreenImage(texture)
            
            item.setPos(entry.pos[0],entry.pos[1],entry.pos[2])
            item.setScale(entry.scale[0]*texture.getOrigFileXSize()/float(texture.getOrigFileYSize()),entry.scale[1],entry.scale[2])  #Always make its height fill the screen normally
            color = (entry.color[0],entry.color[1],entry.color[2],entry.color[3])
            if entry.fadein:
                lv = LerpColorInterval(item, entry.fadein, color, (color[0],color[1],color[2],0) ) 
                self._intervals.append(lv)
                lv.start()
            else: item.setColor(color)
            item.setName(entry.key)
            
            if entry.category == SVIC.FG:
                item.reparentTo(self.fgNodePath)
            elif entry.category == SVIC.BG:
                item.reparentTo(self.bgNodePath)
            elif entry.category == SVIC.O2D:
                item.reparentTo(self.vNodePath)
            
        elif entry.category == SVIC.AFG:
            item = None
            for ft in ((folder,type) for folder in imagepathes for type in modeltypes):
                if exists(ft[0] + entry.fileName + ft[1]):
                    item = loader.loadModel(ft[0] + entry.fileName + ft[1])
                    break
            if not item:  item = loader.loadModel(entry.fileName)
            item.setPos(entry.pos[0],entry.pos[1],entry.pos[2])
            item.setScale(entry.scale)  #For generated egg animation with "egg-texture-cards" is a 1x1 rectangle by default
            color = (entry.color[0],entry.color[1],entry.color[2],entry.color[3])
            if entry.fadein:
                lv = LerpColorInterval(item, entry.fadein, color, (color[0],color[1],color[2],0) ) 
                self._intervals.append(lv)
                lv.start()
            else: item.setColor(color)
            item.setTransparency(1)
            item.setName(entry.key)
            item.reparentTo(self.fgNodePath)
            #item.setBin("unsorted", 0)

            
        elif entry.category == SVIC.O3D:
            item = None
            for ft in ((folder,type) for folder in modelpathes for type in modeltypes):
                if exists(ft[0] + entry.fileName + ft[1]):
                    item = loader.loadModel(ft[0] + entry.fileName + ft[1])
                    break
            if not item:  item = loader.loadModel(entry.fileName)
            item.setPos(entry.pos[0],entry.pos[1],entry.pos[2])
            item.setScale(entry.scale)  #For generated egg animation with "egg-texture-cards" is a 1x1 rectangle by default
            color = (entry.color[0],entry.color[1],entry.color[2],entry.color[3])
            if entry.fadein:
                lv = LerpColorInterval(item, entry.fadein, color, (color[0],color[1],color[2],0) ) 
                self._intervals.append(lv)
                lv.start()
            else: item.setColor(color)
            item.setTransparency(1)
            item.setName(entry.key)
            item.reparentTo(self.vNodePath)
  
        if item:
            self._sceneItems[entry.key] = item
            if entry.quickitem:
                self._quickitems.append(entry.key) 
예제 #22
0
def loadScriptData(fileName):
    '''Load the sogal script file (.sogal) 
    returns a list of StoryCommands indicating different commands
    divided by empty lines and continuous rows of @ symbol
    读取sogal脚本,将不同的命令区分成很多StoryCommand但是不做解析,仅仅是简单地区分开命令行和文本行
    参见 game_entities.StoryCommand
    '''
    
    _lsdLock.acquire()
    
    fileloc = None
    for pt in ((path,type) for path in runtime_data.game_settings['sogalscrpathes'] for type in runtime_data.game_settings['sogalscrtypes']):
        if exists(pt[0]+fileName+pt[1]):
            fileloc = pt[0]+fileName+pt[1]
            break
    
    if not fileloc:
        safeprint('file not found: ' + fileName)
        _lsdLock.release()
        return
   
    fileHandle = open(fileloc)   #for 'from direct.stdpy.file import open', this 'open' is panda3d opereation and not the standard python operation
   
    global _current_index #I hate python below 3
    _current_index = 0 #current index of the command
    
    
    io_reader = StringIO(fileHandle.read())
    
    fileHandle.close()
    
    io_reader.seek(0)
    loaded_list = []
    global _current_command   #虽然global很讨厌……
    _current_command = None   #当前的命令文字
    global _current_text
    _current_text = None    #当前的文本
    controlAttribs_startswith = ['if ','while ','elif ','end ','mark ','mark:']
    controlAttribs_equal = ['else','end']
    
    def push_current():
        global _current_command   #如果是python3.0以上在这里用nonlocal就好了……
        global _current_text
        global _current_index
        '''将当前命令文本加入到loaded_list末尾'''
        if not _current_command and not _current_text:
            _current_command = None
            _current_text = None
            return
        else:
            loaded_list.append(StoryCommand(command = _current_command, text = _current_text,index= _current_index, fileLoc= fileloc))
            _current_index += 1 
            _current_command = None
            _current_text = None
            
            
    
    while True:
        temp_original = unicode(io_reader.readline().decode('utf-8'))
        if not temp_original:    #文件末
            push_current() 
            break;
        else:
            #textTemp = temp_original.strip('\n')
            notesplit = re.compile(ur'(?<!\\)#|^#',re.UNICODE) 
            #Convert the line to utf-8 and remove the note afterwards
            line_raw = notesplit.split(temp_original,1)[0]
            line = line_raw.strip()
            
            if not line:     #若是空行,则进行push操作
                push_current() 
                
            elif line.startswith('@'):
                if _current_command or _current_text:   
                    #如果在一个命令列前面已经有了内容,则前面已经是完整的一段,所以推入列表
                    push_current() 
                _current_command = line.lstrip('@')
                _stripedcc = _current_command.strip()
                
                #There should be no text in control parts so it it is an control part then push
                for attr in controlAttribs_startswith:
                    if _stripedcc.startswith(attr):
                        push_current()
                for attr in controlAttribs_equal:
                    if _stripedcc == attr:
                        push_current()
                
                
            else:    #于是就剩下是文本的情况
                if _current_text:
                    _current_text += '\n'
                else: _current_text = ''
                adding = line_raw.rstrip()
                if adding.startswith('__'):
                    _current_text += ' ' #用一个空格代替空行嗯
                else: _current_text += adding
            
    _lsdLock.release()
    return loaded_list
       

    
    

        
예제 #23
0
 def hasQuickData(self):
     return exists(game_settings['save_folder'] + 'quick_save' +
                   str(global_data['currentQuicksave']) +
                   game_settings['save_type'])
예제 #24
0
 def hasQuickData(self):
     return exists(game_settings['save_folder'] + 'quick_save' + str(global_data['currentQuicksave']) + game_settings['save_type'])
예제 #25
0
def LoadScene(file,
              quad_tree,
              actors,
              terrain,
              textures,
              current_textures,
              grass,
              grass_tex,
              current_grass_tex,
              flatten=False):
    json_data = None
    if not exists(file + '.json'):
        return None
    with open(file + '.json') as f:
        json_data = json.load(f)
    return_data = []
    for object in json_data:
        print ".",
        model = None
        if 'textures' in object:
            i = 0
            for tex in object['textures']:
                if tex in textures:
                    if current_textures:
                        id = textures.index(tex)
                        current_textures[i] = id
                    terrain.setTexture(
                        terrain.findTextureStage('tex{0}'.format(i + 1)),
                        loader.loadTexture(tex), 1)
                    #normal texture should have the same name but should be in '/normal/' directory
                    normal_tex = tex.replace('/diffuse/', '/normal/')
                    terrain.setTexture(
                        terrain.findTextureStage('tex{0}n'.format(i + 1)),
                        loader.loadTexture(normal_tex), 1)
                else:
                    print "WARNING: texture '{0}' not found!".format(tex)
                i += 1
            continue
        elif 'grass' in object:
            i = 0
            for tex in object['grass']:
                if tex in grass_tex:
                    if current_grass_tex:
                        id = grass_tex.index(tex)
                        current_grass_tex[i] = id
                        grs_tex = loader.loadTexture(tex)
                        grs_tex.setWrapU(Texture.WMClamp)
                        grs_tex.setWrapV(Texture.WMClamp)
                    grass.setTexture(
                        grass.findTextureStage('tex{0}'.format(i + 1)),
                        grs_tex, 1)
                else:
                    print "WARNING: grass texture '{0}' not found!".format(tex)
                i += 1
            continue
        elif 'model' in object:
            model = loadModel(object['model'])
        elif 'actor' in object:
            model = loadModel(object['actor'], object['actor_collision'],
                              object['actor_anims'])
            actors.append(model)
        else:
            return_data.append(object)
        if model:
            model.reparentTo(quad_tree[object['parent_index']])
            model.setPythonTag('props', object['props'])
            model.setHpr(render, object['rotation_h'], object['rotation_p'],
                         object['rotation_r'])
            model.setPos(render, object['position_x'], object['position_y'],
                         object['position_z'])
            if 'color_r' in object:
                model.setPythonTag(
                    'light_color',
                    [object['color_r'], object['color_g'], object['color_b']])
            model.setScale(object['scale'])

    if flatten:
        for node in quad_tree:
            flat = render.attachNewNode('flatten')
            for child in node.getChildren():
                if child.getPythonTag(
                        'props'
                ) == '':  #objects with SOME properties should be keept alone
                    child.clearPythonTag('model_file')
                    child.clearPythonTag('props')
                    child.clearModelNodes()
                    child.wrtReparentTo(flat)
            flat.flattenStrong()
            flat.wrtReparentTo(node)
    return return_data
예제 #26
0
def loadModel(file, collision=None, animation=None):
    model = None
    if animation:
        model = Actor(file, animation)
        #default anim
        if 'default' in animation:
            model.loop('default')
        elif 'idle' in animation:
            model.loop('idle')
        else:  #some random anim
            model.loop(animation.items()[0])
    else:
        model = loader.loadModel(file)
    model.setPythonTag('model_file', file)
    #load shaders
    for geom in model.findAllMatches('**/+GeomNode'):
        if geom.hasTag('light'):
            model.setPythonTag('hasLight', True)
        if geom.hasTag('particle'):
            file = 'particle/' + geom.getTag('particle')
            if exists(file):
                with open(file) as f:
                    values = json.load(f)
                p = createEffect(values)
                model.setPythonTag('particle', p)
                p.start(parent=model, renderParent=render)
        if geom.hasTag('cg_shader'):
            geom.setShader(
                loader.loadShader("shaders/" + geom.getTag('cg_shader')))
        elif geom.hasTag('glsl_shader'):
            glsl_shader = geom.getTag('glsl_shader')
            geom.setShader(
                Shader.load(Shader.SLGLSL,
                            "shaders/{0}_v.glsl".format(glsl_shader),
                            "shaders/{0}_f.glsl".format(glsl_shader)))
        else:
            #geom.setShader(loader.loadShader("shaders/default.cg"))
            geom.setShader(
                Shader.load(Shader.SLGLSL, "shaders/default_v.glsl",
                            "shaders/default_f.glsl"))
    #collisions
    model.setCollideMask(BitMask32.allOff())
    if collision:
        coll = loader.loadModel(collision)
        coll.reparentTo(model)
        coll.find('**/collision').setCollideMask(BitMask32.bit(2))
        coll.find('**/collision').setPythonTag('object', model)
        if animation:
            model.setPythonTag('actor_files', [file, animation, collision])
    else:
        try:
            model.find('**/collision').setCollideMask(BitMask32.bit(2))
            model.find('**/collision').setPythonTag('object', model)
        except:
            print "WARNING: Model {0} has no collision geometry!\nGenerating collision sphere...".format(
                file)
            bounds = model.getBounds()
            radi = bounds.getRadius()
            cent = bounds.getCenter()
            coll_sphere = model.attachNewNode(CollisionNode('collision'))
            coll_sphere.node().addSolid(
                CollisionSphere(cent[0], cent[1], cent[2], radi))
            coll_sphere.setCollideMask(BitMask32.bit(2))
            coll_sphere.setPythonTag('object', model)
            #coll_sphere.show()
            if animation:
                model.setPythonTag('actor_files', [file, animation, None])
    return model
예제 #27
0
def LoadScene(
    file, quad_tree, actors, terrain, textures, current_textures, grass, grass_tex, current_grass_tex, flatten=False
):
    json_data = None
    if not exists(file + ".json"):
        return None
    with open(file + ".json") as f:
        json_data = json.load(f)
    return_data = []
    for object in json_data:
        print ".",
        model = None
        if "textures" in object:
            i = 0
            for tex in object["textures"]:
                if tex in textures:
                    if current_textures:
                        id = textures.index(tex)
                        current_textures[i] = id
                    terrain.setTexture(terrain.findTextureStage("tex{0}".format(i + 1)), loader.loadTexture(tex), 1)
                    # normal texture should have the same name but should be in '/normal/' directory
                    normal_tex = tex.replace("/diffuse/", "/normal/")
                    terrain.setTexture(
                        terrain.findTextureStage("tex{0}n".format(i + 1)), loader.loadTexture(normal_tex), 1
                    )
                else:
                    print "WARNING: texture '{0}' not found!".format(tex)
                i += 1
            continue
        elif "grass" in object:
            i = 0
            for tex in object["grass"]:
                if tex in grass_tex:
                    if current_grass_tex:
                        id = grass_tex.index(tex)
                        current_grass_tex[i] = id
                        grs_tex = loader.loadTexture(tex)
                        grs_tex.setWrapU(Texture.WMClamp)
                        grs_tex.setWrapV(Texture.WMClamp)
                    grass.setTexture(grass.findTextureStage("tex{0}".format(i + 1)), grs_tex, 1)
                else:
                    print "WARNING: grass texture '{0}' not found!".format(tex)
                i += 1
            continue
        elif "model" in object:
            model = loadModel(object["model"])
        elif "actor" in object:
            model = loadModel(object["actor"], object["actor_collision"], object["actor_anims"])
            actors.append(model)
        else:
            return_data.append(object)
        if model:
            model.reparentTo(quad_tree[object["parent_index"]])
            model.setPythonTag("props", object["props"])
            model.setHpr(render, object["rotation_h"], object["rotation_p"], object["rotation_r"])
            model.setPos(render, object["position_x"], object["position_y"], object["position_z"])
            if "color_r" in object:
                model.setPythonTag("light_color", [object["color_r"], object["color_g"], object["color_b"]])
            model.setScale(object["scale"])

    if flatten:
        for node in quad_tree:
            flat = render.attachNewNode("flatten")
            for child in node.getChildren():
                if child.getPythonTag("props") == "":  # objects with SOME properties should be keept alone
                    child.clearPythonTag("model_file")
                    child.clearPythonTag("props")
                    child.clearModelNodes()
                    child.wrtReparentTo(flat)
            flat.flattenStrong()
            flat.wrtReparentTo(node)
    return return_data
예제 #28
0
def loadModel(file, collision=None, animation=None):
    model = None
    if animation:
        collision = file + '/collision'
        anims = {}
        dirList = listdir(file + '/animation')
        for fname in dirList:
            anims[fname[:-4]] = file + '/animation/' + fname
        #print anims
        model = Actor(file + '/model', anims)
        #default anim
        if 'default' in anims:
            model.loop('default')
        elif 'idle' in animation:
            model.loop('idle')
        else:  #some first, random anim
            model.loop(list(anims.items())[0])
    else:
        model = loader.loadModel(file)
    model.setPythonTag('model_file', file)
    #load shaders
    for geom in model.findAllMatches('**/+GeomNode'):
        if geom.hasTag('light'):
            model.setPythonTag('hasLight', True)
        if geom.hasTag('particle'):
            file = 'particle/' + geom.getTag('particle')
            if exists(file):
                with open(file) as f:
                    values = json.load(f)
                p = createEffect(values)
                model.setPythonTag('particle', p)
                p.start(parent=model, renderParent=render)
        if geom.hasTag('cg_shader'):
            geom.setShader(
                loader.loadShader("shaders/" + geom.getTag('cg_shader')))
        elif geom.hasTag('glsl_shader'):
            glsl_shader = geom.getTag('glsl_shader')
            model.setShader(
                Shader.load(Shader.SLGLSL,
                            "shaders/{0}_v.glsl".format(glsl_shader),
                            "shaders/{0}_f.glsl".format(glsl_shader)))
        else:
            #geom.setShader(loader.loadShader("shaders/default.cg"))
            model.setShader(
                Shader.load(Shader.SLGLSL, "shaders/default_v.glsl",
                            "shaders/default_f.glsl"), 1)
            print("default shader!")
    #collisions
    model.setCollideMask(BitMask32.allOff())
    if collision:
        coll = loader.loadModel(collision)
        coll.reparentTo(model)
        coll.find('**/collision').setCollideMask(BitMask32.bit(2))
        coll.find('**/collision').setPythonTag('object', model)
        if animation:
            model.setPythonTag('actor_files', [file, anims, coll])
    else:
        try:
            model.find('**/collision').setCollideMask(BitMask32.bit(2))
            model.find('**/collision').setPythonTag('object', model)
        except:
            print(
                "WARNING: Model {0} has no collision geometry!\nGenerating collision sphere..."
                .format(file))
            bounds = model.getBounds()
            radi = bounds.getRadius()
            cent = bounds.getCenter()
            coll_sphere = model.attachNewNode(CollisionNode('collision'))
            coll_sphere.node().addSolid(
                CollisionSphere(cent[0], cent[1], cent[2], radi))
            coll_sphere.setCollideMask(BitMask32.bit(2))
            coll_sphere.setPythonTag('object', model)
            #coll_sphere.show()
            if animation:
                model.setPythonTag('actor_files', [file, animation, None])
    if ConfigVariableBool('framebuffer-srgb', False).getValue():
        fixSrgbTextures(model)
    return model