Example #1
0
def _over_event_loop(own, status):
	global _hold, _selok
	global selected
	list = module.widget_dict
	
	if status == 3:
		try:
			list[own]._mouseOut()
			if cam.pointInsideFrustum(pos): list[own].mouseOut()
		except: pass
		_selok = False
		if _hold == False: selected = None
		
	if status == 2:
		try: list[own].mouseOver()
		except: pass
	
	if status == 1:
		if _hold == False or selected==own:
			try:
				if own in list:
					list[own]._mouseIn()
					if module.window.cursorInsideFrustum(): list[own].mouseIn()
			except: utils.debug("_over_event_loop: Forgot to disable collisions?")
			selected = own
			_selok = True
Example #2
0
def _over_event_loop(own, status):
    global _hold, _selok
    global selected
    list = module.widget_dict

    if status == 3:
        try:
            list[own]._mouseOut()
            if cam.pointInsideFrustum(pos): list[own].mouseOut()
        except:
            pass
        _selok = False
        if _hold == False: selected = None

    if status == 2:
        try:
            list[own].mouseOver()
        except:
            pass

    if status == 1:
        if _hold == False or selected == own:
            try:
                if own in list:
                    list[own]._mouseIn()
                    if module.window.cursorInsideFrustum(): list[own].mouseIn()
            except:
                utils.debug("_over_event_loop: Forgot to disable collisions?")
            selected = own
            _selok = True
Example #3
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
Example #4
0
def replaceBlenderText(obj):
	font = obj.get("Font")
	if not font:
		#utils.debug("Impossible to replace text object " + obj.name + ". Doesn't have a Font property.")
		return
	
	sx, sy, sz = [int(n*100) for n in obj.localScale]
	if sx != sy or sy != sz:
		utils.debug("Impossible to replace text object " + obj.name + ". Size is not uniform.")
		return
	
	align = obj.get("Align", 0)
	align = ["Left", "Center", "Right"].index(align)
	
	wp = obj.worldPosition
	#position = [wp.x+float(0.006*sx), wp.y+(0.002*sx), wp.z]
	label = FLabel(font, obj["Text"], sx/3.1, align, wp)
	xyz = obj.worldOrientation.to_euler()
	label.rotation = xyz
	if align == ALIGN_RIGHT: label.rotation.y = 3.14
	
	label.visible = obj.visible
	
	module.labels[obj.name] = label
	obj.endObject()
Example #5
0
def replaceBlenderText(obj):
    font = obj.get("Font")
    if not font:
        #utils.debug("Impossible to replace text object " + obj.name + ". Doesn't have a Font property.")
        return

    sx, sy, sz = [int(n * 100) for n in obj.localScale]
    if sx != sy or sy != sz:
        utils.debug("Impossible to replace text object " + obj.name +
                    ". Size is not uniform.")
        return

    align = obj.get("Align", 0)
    align = ["Left", "Center", "Right"].index(align)

    wp = obj.worldPosition
    #position = [wp.x+float(0.006*sx), wp.y+(0.002*sx), wp.z]
    label = FLabel(font, obj["Text"], sx / 3.1, align, wp)
    xyz = obj.worldOrientation.to_euler()
    label.rotation = xyz
    if align == ALIGN_RIGHT: label.rotation.y = 3.14

    label.visible = obj.visible

    module.labels[obj.name] = label
    obj.endObject()
Example #6
0
    def play(self, filepath=None, loop=False, volume=None, pitch=1, callback=None, transition=(3, 2, 3)):
        """ Method to play an audio file.
		
		If an audio file is being played while calling this, it will be replaced by a new one. During the transation a *fadeOut->FadeIn* effect will occur.
		
		:param string filepath: Relative path (from the data folder) of the audio file to use.
		:param bool loop: If true the audio will be played in loop.
		:param float volume: The volume of the audio file relative to the master device. (Default = 1.0)
		:param float pitch: The pitch.
		:param function callback: Function to call once the playback ends.
		:param tuple transition: The times for the fade effect during transations. In order: Duration of the fadeout, time for the fadein to start, duration of the fadein. In sconds.
		"""

        if self.waiting == True:  # Replace sound that will be played.
            self.filepath = filepath
            return

        if self.playing == True:  # FadeOut this sound and fadeIn the new one.
            x, y, z = transition

            dummy = self.moveInstance()
            dummy.fadeOut(x, stop=True)

            if filepath:
                self.filepath = filepath
            self.waiting = True

            sequencer.Wait(y, lambda: self._transition_callback(z))
            self.callback = callback
            return

        self.callback = callback
        if not filepath:
            filepath = self.filepath
        else:
            self.filepath = filepath
        path = logic.expandPath("//../data/" + filepath)
        factory = aud.Factory(path)

        try:
            self.factory = factory
            self.handle = device.play(self.factory)  # It sends a callback that will play the music on a new theread.
            self.handle.pitch = pitch
            if volume == None:
                self.volume = self._volume
            else:
                self.volume = volume
            if loop:
                self.handle.loop_count = -1
        except:
            if os.path.isfile(path) == False:
                utils.debug("Audio File, Not Found: " + path)
            else:
                raise RuntimeException("AudioFile Load Error: " + path)

        self.playing = True
        module.low_frequency_callbacks.append(self.update)
        return self
Example #7
0
def loop():
    global _state, _last_time, _last_time2

    #Game initialization
    if _state == 0:
        _state = 1
        logic.setMaxLogicFrame(1)
        module.scene_gui_behavior.scene = module.scene_gui
        for o in module.scene_gui.objects:
            module.scene_gui_behavior.objects[o.name] = o
        module.scene_gui_behavior.init()
        for b in module.scene_gui_behavior.behaviors:
            b.init()
        media.device.volume = float(utils.loadGameProperty("volume"))
        module._arecallbacks = False
        if utils.checkVersion() == False:
            utils.debug(
                "Atention! BGE version is outdated, please install last Blender release."
            )

    if module._arecallbacks == True: return

    #GUI Behavior
    if module.scene_gui_behavior.paused == False:
        module.scene_gui_behavior.update()
    for b in module.scene_gui_behavior.behaviors:
        if b.paused == False: b.update()

    #Key events
    listen_list = [
        x for x in module.listen_input_list
        if x._immuse_keyboard == True and x.scene == module.scene_gui
    ]
    for x in module.listen_input_list:
        x._immuse_keyboard = x.use_keyboard
    event._key_event_loop(listen_list)
    event.first_time_in_frame = True
    event.last_keyevents = event.last_butstillthisframe_keyevents

    #Frequency callbacks
    for v in module.video_playback_list:
        v.updateVideo()

    done = time.time()
    if (done - _last_time) >= module.LOW_FREQUENCY_TICK:
        dtime = done - _last_time
        _last_time = done
        for call in module.low_frequency_callbacks:
            call(dtime)

    if (done - _last_time2) >= module.HEIGHT_FREQUENCY_TICK:
        dtime = done - _last_time2
        _last_time2 = done
        for call in module.height_frequency_callbacks:
            call(dtime)
Example #8
0
	def __init__(self, sprite, over = None):
		super().__init__(sprite)
		if type(over) is str:
			self.over = self.scene.objectsInactive[over]
			if not self.over:
				try:
					acov = self.scene.objects[over]
					if acov: utils.debug("Interface error (" + self.__class__.__name__ + "): Object '" + acov.name + " must be in an inactive layer.")
				except: pass
		else: self.over = over
		self.objt = None
Example #9
0
	def play(self, filepath=None, loop=False, volume = None, pitch = 1, callback = None, transition = (3, 2, 3)):
		""" Method to play an audio file.
		
		If an audio file is being played while calling this, it will be replaced by a new one. During the transation a *fadeOut->FadeIn* effect will occur.
		
		:param string filepath: Relative path (from the data folder) of the audio file to use.
		:param bool loop: If true the audio will be played in loop.
		:param float volume: The volume of the audio file relative to the master device. (Default = 1.0)
		:param float pitch: The pitch.
		:param function callback: Function to call once the playback ends.
		:param tuple transition: The times for the fade effect during transations. In order: Duration of the fadeout, time for the fadein to start, duration of the fadein. In sconds.
		"""
		
		if self.waiting == True: #Replace sound that will be played.
			self.filepath = filepath
			return
			
		if self.playing == True: #FadeOut this sound and fadeIn the new one.
			x, y, z = transition
			
			dummy = self.moveInstance()
			dummy.fadeOut(x, stop=True)

			if filepath: self.filepath = filepath
			self.waiting = True
			
			sequencer.Wait(y, lambda: self._transition_callback(z))
			self.callback = callback
			return
		
		self.callback = callback
		if not filepath: filepath = self.filepath
		else: self.filepath = filepath
		path = logic.expandPath("//../data/" + filepath)
		factory = aud.Factory(path)
		
		try:
			self.factory = factory
			self.handle = device.play(self.factory) #It sends a callback that will play the music on a new theread.
			self.handle.pitch = pitch
			if volume == None: self.volume = self._volume
			else: self.volume = volume
			if loop: self.handle.loop_count = -1
		except:
			if os.path.isfile(path) == False: utils.debug("Audio File, Not Found: " + path)
			else: raise RuntimeException("AudioFile Load Error: " + path)
		
		self.playing = True
		module.low_frequency_callbacks.append(self.update)
		return self
Example #10
0
 def next(self):
     """ Plays a song, or replaces the current song. """
     current_song = self.audiofile.filepath
     path = self.getRandomFileTrack()
     try:
         self.audiofile.play(self.directory + path,
                             transition=self.transition)
     except IndexError:
         utils.debug("No music found in directory " + self.directory)
     except RuntimeError as e:
         utils.debug(e)
         self.ignore.append(path)
         self.audiofile.filepath = current_song
         self.next()
Example #11
0
 def __init__(self, sprite, over=None):
     super().__init__(sprite)
     if type(over) is str:
         self.over = self.scene.objectsInactive[over]
         if not self.over:
             try:
                 acov = self.scene.objects[over]
                 if acov:
                     utils.debug("Interface error (" +
                                 self.__class__.__name__ + "): Object '" +
                                 acov.name +
                                 " must be in an inactive layer.")
             except:
                 pass
     else:
         self.over = over
     self.objt = None
Example #12
0
def loop():
	global _state, _last_time, _last_time2

	#Game initialization
	if _state == 0:
		_state = 1
		logic.setMaxLogicFrame(1)
		module.scene_gui_behavior.scene = module.scene_gui
		for o in module.scene_gui.objects: module.scene_gui_behavior.objects[o.name] = o
		module.scene_gui_behavior.init()
		for b in module.scene_gui_behavior.behaviors: b.init()
		media.device.volume = float(utils.loadGameProperty("volume"))
		module._arecallbacks = False
		if utils.checkVersion() == False: utils.debug("Atention! BGE version is outdated, please install last Blender release.")

	if module._arecallbacks == True: return

	#GUI Behavior
	if module.scene_gui_behavior.paused == False: module.scene_gui_behavior.update()
	for b in module.scene_gui_behavior.behaviors:
		if b.paused == False: b.update()

	#Key events
	listen_list = [x for x in module.listen_input_list if x._immuse_keyboard == True and x.scene == module.scene_gui]
	for x in module.listen_input_list: x._immuse_keyboard = x.use_keyboard
	event._key_event_loop(listen_list)
	event.first_time_in_frame = True
	event.last_keyevents = event.last_butstillthisframe_keyevents

	#Frequency callbacks
	for v in module.video_playback_list: v.updateVideo()

	done = time.time()
	if (done - _last_time) >= module.LOW_FREQUENCY_TICK:
		dtime = done - _last_time
		_last_time = done
		for call in module.low_frequency_callbacks:
			call(dtime)

	if (done - _last_time2) >= module.HEIGHT_FREQUENCY_TICK:
		dtime = done - _last_time2
		_last_time2 = done
		for call in module.height_frequency_callbacks:
			call(dtime)
Example #13
0
    def __init__(self,
                 font,
                 text,
                 size=16,
                 align=ALIGN_LEFT,
                 position=[0, 0, 0]):
        self.scene = module.scene_gui
        font_name = "Font." + font
        self._font = self.scene.objectsInactive[font_name]

        self.obj = self.scene.addObject(self._font, self.scene.active_camera)
        self.obj.worldPosition = position

        if font_name not in FLabel._loaded_fonts_right.keys():
            mesh = logic.LibNew('Font' + str(FLabel._font_id), 'Mesh',
                                [font_name])[0]
            v_array = mesh.getVertexArrayLength(0)
            if v_array != 4:
                utils.debug("Font object not valid, skipping!")
                return

            v0 = mesh.getVertex(0, 0)
            v1 = mesh.getVertex(0, 1)
            v2 = mesh.getVertex(0, 2)
            v3 = mesh.getVertex(0, 3)
            _swap_UV_2(v0, v1)
            _swap_UV_2(v2, v3)

            FLabel._loaded_fonts_right[font] = mesh
            FLabel._loaded_fonts_left[font] = self.obj.meshes[0]
            FLabel._font_id += 1

        self._location = super().ProxyPosition()
        self._scale = super().ProxyScale()
        self._rotation = super().ProxyRotation()
        self._color = super().ProxyColor()
        self.transformable = [self.obj]
        self._align = None
        self._text = text
        self.ob2 = None  #Second object to use on ALIGN_CENTER

        self.size = size
        self.align = align  #It also does set text the first time.
Example #14
0
def secondary_loop():
    global _last_traceback, _fatal_error

    #It takes 0.6ms when with the editor. (Without tile replacing)
    try:
        if _fatal_error: return

        #Set scene
        if module.change_scene_frame == True:
            if module.change_scene_dynamic == True:
                dynamic.loadScene(None, None)
            else:
                utils.setScene(None)
            return

        else:
            if module.scene_behavior.paused == False:
                module.scene_behavior.update()
                module.scene_behavior.baseUpdate()
            if not module.scene_behavior: return  #When removing the scene
            for b in module.scene_behavior.behaviors:
                if b.paused == False: b.update()
                if not module.scene_behavior: return  #When removing the scene
    except:
        if not module.scene_behavior: return
        module.scene_behavior.paused = True
        s = traceback.format_exc()
        if s != _last_traceback:
            utils.debug("Error during runtime. Scene behavior suspended!")
            print(s)
            _fatal_error = True
        _last_traceback = s

    #It takes about 0.3ms (As much as the main loop)
    listen_list = [
        x for x in module.listen_input_list
        if x._immuse_keyboard == True and x.scene == module.scene_game
    ]
    for x in module.listen_input_list:
        x._immuse_keyboard = x.use_keyboard
    event._key_event_loop(listen_list)
    module.window.secondary_update()
Example #15
0
	def rotation(self, xyz):
		if len(xyz) != 3: utils.debug("Rotation assignment failed on " + self.obj.name + " object. xyz size != 3.")
		if isinstance(xyz, (list, tuple)) or len(xyz) == 3:
			xyz = Euler(xyz, 'XYZ')
		srt = self.obj.localOrientation.copy()
		xyz = xyz.to_matrix()
			
		for obj in self.transformable:
			if obj.__class__.__name__ == "KX_GameObject":
				if obj == self.obj: obj.localOrientation = xyz
				else:
					srr = obj.worldOrientation.copy()
					srr.rotate(xyz)
					srr = srr.to_euler()
					obj.localOrientation = srr
			else:
				srr = obj.rotation.copy()
				srr.rotate(xyz)
				obj.localOrientation = srr
				obj.rotation = srr
		self._rotation = self.ProxyRotation()
Example #16
0
def _click_event_loop(status):
	global _hold, _selok
	global selected
	list = module.widget_dict
	
	if status == 1 and selected: _hold = True
	if status == 2:
		if selected in list: list[selected].mousePressed()
	
	if status != 3: return
	
	if selected and _selok == True and _hold == True:
		try:
			if selected in list and list[selected]._active == True:
				list[selected]._mouseClick()
				if module.window.cursorInsideFrustum(): list[selected].mouseClick()
		except:
			#utils.debug("_click_event_loop: Forgot to disable collisions?")
			utils.debug(traceback.format_exc())
		
	_hold = False
Example #17
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.")
Example #18
0
def _click_event_loop(status):
    global _hold, _selok
    global selected
    list = module.widget_dict

    if status == 1 and selected: _hold = True
    if status == 2:
        if selected in list: list[selected].mousePressed()

    if status != 3: return

    if selected and _selok == True and _hold == True:
        try:
            if selected in list and list[selected]._active == True:
                list[selected]._mouseClick()
                if module.window.cursorInsideFrustum():
                    list[selected].mouseClick()
        except:
            #utils.debug("_click_event_loop: Forgot to disable collisions?")
            utils.debug(traceback.format_exc())

    _hold = False
Example #19
0
    def rotation(self, xyz):
        if len(xyz) != 3:
            utils.debug("Rotation assignment failed on " + self.obj.name +
                        " object. xyz size != 3.")
        if isinstance(xyz, (list, tuple)) or len(xyz) == 3:
            xyz = Euler(xyz, 'XYZ')
        srt = self.obj.localOrientation.copy()
        xyz = xyz.to_matrix()

        for obj in self.transformable:
            if obj.__class__.__name__ == "KX_GameObject":
                if obj == self.obj: obj.localOrientation = xyz
                else:
                    srr = obj.worldOrientation.copy()
                    srr.rotate(xyz)
                    srr = srr.to_euler()
                    obj.localOrientation = srr
            else:
                srr = obj.rotation.copy()
                srr.rotate(xyz)
                obj.localOrientation = srr
                obj.rotation = srr
        self._rotation = self.ProxyRotation()
Example #20
0
	def __init__(self, font, text, size = 16, align = ALIGN_LEFT, position = [0,0,0]):
		self.scene = module.scene_gui
		font_name = "Font." + font
		self._font = self.scene.objectsInactive[font_name]
		
		self.obj = self.scene.addObject(self._font, self.scene.active_camera)
		self.obj.worldPosition = position
			
		if font_name not in FLabel._loaded_fonts_right.keys():
			mesh = logic.LibNew('Font'+str(FLabel._font_id), 'Mesh', [font_name])[0]
			v_array = mesh.getVertexArrayLength(0)
			if v_array != 4:
				utils.debug("Font object not valid, skipping!")
				return
			
			v0 = mesh.getVertex(0,0)
			v1 = mesh.getVertex(0,1)
			v2 = mesh.getVertex(0,2)
			v3 = mesh.getVertex(0,3)
			_swap_UV_2(v0,v1)
			_swap_UV_2(v2,v3)
			
			FLabel._loaded_fonts_right[font] = mesh
			FLabel._loaded_fonts_left[font] = self.obj.meshes[0]
			FLabel._font_id += 1
		
		self._location = super().ProxyPosition()
		self._scale = super().ProxyScale()
		self._rotation = super().ProxyRotation()
		self._color = super().ProxyColor()
		self.transformable = [self.obj]
		self._align = None
		self._text = text
		self.ob2 = None #Second object to use on ALIGN_CENTER
		
		self.size = size
		self.align = align #It also does set text the first time.
Example #21
0
def secondary_loop():
	global _last_traceback, _fatal_error

	#It takes 0.6ms when with the editor. (Without tile replacing)
	try:
		if _fatal_error: return
		
		#Set scene
		if module.change_scene_frame == True:
			if module.change_scene_dynamic == True: dynamic.loadScene(None, None)
			else: utils.setScene(None)
			return
		
		else:
			if module.scene_behavior.paused == False:
				module.scene_behavior.update()
				module.scene_behavior.baseUpdate()
			if not module.scene_behavior: return #When removing the scene
			for b in module.scene_behavior.behaviors:
				if b.paused == False: b.update()
				if not module.scene_behavior: return #When removing the scene
	except:
		if not module.scene_behavior: return
		module.scene_behavior.paused = True
		s = traceback.format_exc()
		if s != _last_traceback:
			utils.debug("Error during runtime. Scene behavior suspended!")
			print(s)
			_fatal_error = True
		_last_traceback = s

	#It takes about 0.3ms (As much as the main loop)
	listen_list = [x for x in module.listen_input_list if x._immuse_keyboard == True and x.scene == module.scene_game]
	for x in module.listen_input_list: x._immuse_keyboard = x.use_keyboard
	event._key_event_loop(listen_list)
	module.window.secondary_update()
Example #22
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.")
Example #23
0
 def _add(self, linename, item, offset):
     target_tick = self.tick + offset
     line = self.lines[linename]
     self.pad(line, target_tick)
     line[target_tick].append(item)
     debug("_add:", linename, target_tick, item)
Example #24
0
	def next(self):
		""" Plays a song, or replaces the current song. """
		try:
			self.audiofile.play(self.directory + self.getRandomFileTrack(), transition = self.transition)
		except IndexError: utils.debug("No music found in directory " + self.directory)
Example #25
0
 def next(self):
     """ Plays a song, or replaces the current song. """
     try:
         self.audiofile.play(self.directory + self.getRandomFileTrack(), transition=self.transition)
     except IndexError:
         utils.debug("No music found in directory " + self.directory)