def _loadObjects(self):
		# get fifedit objects
		self.model = self._engine.getModel()
		self.all_action_sets = ActionSetLoader.get_sets()

		TileSetLoader.load()
		ActionSetLoader.load()
		self.animationloader = SQLiteAnimationLoader()

		self._loadGroundTiles()
		self._loadBuildings()
	def loadResource(self, location):
		"""
		@param location: String with the location. See below for details:
		Location format: <animation_id>:<command>:<params> (e.g.: "123:shift:left-16, bottom-8)
		Available commands:
		- shift:
		Shift the image using the params left, right, center, middle for x shifting and
		y-shifting with the params: top, bottom, center, middle.
		A param looks like this: "param_x(+/-)value, param_y(+/-)value" (e.g.: left-16, bottom+8)
		- cut:
		#TODO: complete documentation
		"""
		commands = location.split(':')
		ident = commands.pop(0)
		actionset, action, rotation = ident.split('-')
		commands = zip(commands[0::2], commands[1::2])

		ani = fife.Animation.createAnimation()

		frame_start, frame_end = 0.0, 0.0
		for file in sorted(ActionSetLoader.get_action_sets()[actionset][action][int(rotation)].iterkeys()):
			frame_end = ActionSetLoader.get_action_sets()[actionset][action][int(rotation)][file]
			img = horizons.main.fife.imagemanager.load(file)
			for command, arg in commands:
				if command == 'shift':
					x, y = arg.split(',')
					if x.startswith('left'):
						x = int(x[4:]) + int(img.getWidth() / 2)
					elif x.startswith('right'):
						x = int(x[5:]) - int(img.getWidth() / 2)
					elif x.startswith(('center', 'middle')):
						x = int(x[6:])
					else:
						x = int(x)

					if y.startswith('top'):
						y = int(y[3:]) + int(img.getHeight() / 2)
					elif y.startswith('bottom'):
						y = int(y[6:]) - int(img.getHeight() / 2)
					elif y.startswith(('center', 'middle')):
						y = int(y[6:])
					else:
						y = int(y)

					img.setXShift(x)
					img.setYShift(y)

			ani.addFrame(img, max(1, int((float(frame_end) - frame_start)*1000)))
			frame_start = float(frame_end)
		ani.setActionFrame(0)
		return ani
Exemple #3
0
	def _loadObject(cls):
		"""Loads building from the db.
		"""
		cls.log.debug("Loading building %s", cls.id)
		try:
			cls._real_object = horizons.main.fife.engine.getModel().createObject(str(cls.id), 'building')
		except RuntimeError:
			cls.log.debug("Already loaded building %s", cls.id)
			cls._real_object = horizons.main.fife.engine.getModel().getObject(str(cls.id), 'building')
			return
		all_action_sets = ActionSetLoader.get_sets()

		# NOTE: the code below is basically duplicated in UHObjectLoader._loadBuilding in the editor

		# cls.action_sets looks like this: {tier1: {set1: None, set2: preview2, ..}, ..}
		for action_set_list in cls.action_sets.itervalues():
			for action_set_id in action_set_list.iterkeys(): # set1, set2, ...
				for action_id in all_action_sets[action_set_id].iterkeys(): # idle, move, ...
					action = cls._real_object.createAction(action_id+"_"+str(action_set_id))
					fife.ActionVisual.create(action)
					for rotation in all_action_sets[action_set_id][action_id].iterkeys():
						if rotation == 45:
							command = 'left-32,bottom+' + str(cls.size[0] * 16)
						elif rotation == 135:
							command = 'left-' + str(cls.size[1] * 32) + ',bottom+16'
						elif rotation == 225:
							command = 'left-' + str((cls.size[0] + cls.size[1] - 1) * 32) + ',bottom+' + str(cls.size[1] * 16)
						elif rotation == 315:
							command = 'left-' + str(cls.size[0] * 32) + ',bottom+' + str((cls.size[0] + cls.size[1] - 1) * 16)
						else:
							assert False, "Bad rotation for action_set %(id)s: %(rotation)s for action: %(action_id)s" % \
								   { 'id':action_set_id, 'rotation': rotation, 'action_id': action_id }
						anim = horizons.main.fife.animationloader.loadResource(str(action_set_id)+"+"+str(action_id)+"+"+str(rotation) + ':shift:' + command)
						action.get2dGfxVisual().addAnimation(int(rotation), anim)
						action.setDuration(anim.getDuration())
Exemple #4
0
    def _loadObject(cls, db):
        """Loads the object with all animations.
		"""
        cls.log.debug('Loading unit %s', cls.id)
        try:
            cls._object = horizons.main.fife.engine.getModel().createObject(
                str(cls.id), 'unit')
        except RuntimeError:
            cls.log.debug('Already loaded unit %s', cls.id)
            cls._object = horizons.main.fife.engine.getModel().getObject(
                str(cls.id), 'unit')
            return
        cls._object.setPather(
            horizons.main.fife.engine.getModel().getPather('RoutePather'))
        cls._object.setBlocking(False)
        cls._object.setStatic(False)
        action_sets = ActionSetLoader.get_action_sets()
        for (action_set_id, ) in db(
                "SELECT action_set_id FROM data.action_set WHERE object_id=?",
                cls.id):
            for action_id in action_sets[action_set_id].iterkeys():
                action = cls._object.createAction(action_id + "_" +
                                                  str(action_set_id))
                fife.ActionVisual.create(action)
                for rotation in action_sets[action_set_id][action_id].iterkeys(
                ):
                    anim_id = horizons.main.fife.animationpool.addResourceFromFile( \
                     str(action_set_id)+"-"+str(action_id)+"-"+ \
                     str(rotation) + ':shift:center+0,bottom+8')
                    action.get2dGfxVisual().addAnimation(
                        int(rotation), anim_id)
                    action.setDuration(
                        horizons.main.fife.animationpool.getAnimation(
                            anim_id).getDuration())
Exemple #5
0
    def _loadObject(cls):
        """Loads the object with all animations.
		"""
        cls.log.debug("Loading unit %s", cls.id)
        try:
            cls._real_object = horizons.main.fife.engine.getModel().createObject(str(cls.id), "unit")
        except RuntimeError:
            cls.log.debug("Already loaded unit %s", cls.id)
            cls._real_object = horizons.main.fife.engine.getModel().getObject(str(cls.id), "unit")
            return
        cls._real_object.setPather(horizons.main.fife.engine.getModel().getPather("RoutePather"))
        cls._real_object.setBlocking(False)
        cls._real_object.setStatic(False)
        all_action_sets = ActionSetLoader.get_sets()
        # create load callbacks to be called when the actions are needed
        # { action_set : { action_id : [ load0, load1, ..., loadn ]}}
        # (loadi are load functions of objects, there can be many per as_id and action)
        # cls.action_sets looks like this: {tier1: {set1: None, set2: preview2, ..}, ..}
        for set_dict in cls.action_sets.itervalues():
            for action_set in set_dict:  # set1, set2, ...
                if not action_set in cls._action_load_callbacks:
                    cls._action_load_callbacks[action_set] = {}
                for action_id in all_action_sets[action_set]:  # idle, move, ...
                    if not action_id in cls._action_load_callbacks[action_set]:
                        cls._action_load_callbacks[action_set][action_id] = []
                    cls._action_load_callbacks[action_set][action_id].append(
                        Callback(cls._do_load, all_action_sets, action_set, action_id)
                    )
 def __init__(self, instance):
     super(SignalFireOverviewTab, self).__init__(widget="overview_signalfire.xml", instance=instance)
     action_set = ActionSetLoader.get_action_sets()[self.instance._action_set_id]
     action_gfx = action_set.items()[0][1]
     image = action_gfx[45].keys()[0]
     self.widget.findChild(name="building_image").image = image
     self.tooltip = _("Overview")
 def draw_gui(self):
     if not hasattr(self, "action_set"):
         level = (
             self.session.world.player.settler_level
             if not hasattr(self._class, "default_level_on_build")
             else self._class.default_level_on_build
         )
         self.action_set = self._class.get_random_action_set(level)
     action_set, preview_action_set = self.action_set
     action_sets = ActionSetLoader.get_sets()
     if preview_action_set in action_sets:
         action_set = preview_action_set
     if "idle" in action_sets[action_set]:
         action = "idle"
     elif "idle_full" in action_sets[action_set]:
         action = "idle_full"
     else:  # If no idle animation found, use the first you find
         action = action_sets[action_set].keys()[0]
     image = sorted(
         action_sets[action_set][action][
             (self.rotation + int(self.session.view.cam.getRotation()) - 45) % 360
         ].keys()
     )[0]
     building_icon = self.gui.findChild(name="building")
     building_icon.image = image
     # TODO: Remove hardcoded 70
     building_icon.position = (
         self.gui.size[0] / 2 - building_icon.size[0] / 2,
         self.gui.size[1] / 2 - building_icon.size[1] / 2 - 70,
     )
     self.gui.adaptLayout()
 def draw_gui(self):
     if not hasattr(self, "action_set"):
         level = self.session.world.player.settler_level if \
               not hasattr(self._class, "default_level_on_build") else \
               self._class.default_level_on_build
         self.action_set = self.session.db.get_random_action_set(
             self._class.id, level)
     action_set, preview_action_set = self.action_set
     action_sets = ActionSetLoader.get_action_sets()
     if preview_action_set in action_sets:
         action_set = preview_action_set
     if 'idle' in action_sets[action_set]:
         action = 'idle'
     elif 'idle_full' in action_sets[action_set]:
         action = 'idle_full'
     else:  # If no idle animation found, use the first you find
         action = action_sets[action_set].keys()[0]
     image = sorted(action_sets[action_set][action][
         (self.rotation + int(self.session.view.cam.getRotation()) - 45) %
         360].keys())[0]
     building_icon = self.gui.findChild(name='building')
     building_icon.image = image
     # TODO: Remove hardcoded 70
     building_icon.position = (self.gui.size[0] / 2 -
                               building_icon.size[0] / 2,
                               self.gui.size[1] / 2 -
                               building_icon.size[1] / 2 - 70)
     self.gui.adaptLayout()
	def draw_gui(self):
		if not hasattr(self, "action_set"):
			level = self.session.world.player.settler_level if \
				not hasattr(self._class, "default_level_on_build") else \
				self._class.default_level_on_build
			self.action_set = self._class.get_random_action_set(level=level, include_preview=True)
		action_set, preview_action_set = self.action_set
		action_sets = ActionSetLoader.get_sets()
		if preview_action_set in action_sets:
			action_set = preview_action_set
		if 'idle' in action_sets[action_set]:
			action = 'idle'
		elif 'idle_full' in action_sets[action_set]:
			action = 'idle_full'
		else: # If no idle animation found, use the first you find
			action = action_sets[action_set].keys()[0]
		rotation = (self.rotation+int(self.session.view.cam.getRotation())-45)%360
		image = sorted(action_sets[action_set][action][rotation].keys())[0]
		if GFX.USE_ATLASES:
			# Make sure the preview is loaded
			horizons.main.fife.animationloader.load_image(image, action_set, action, rotation)
		building_icon = self.gui.findChild(name='building')
		building_icon.image = image
		# TODO: Remove hardcoded 70
		building_icon.position = (self.__class__.gui.size[0]/2 - building_icon.size[0]/2, self.__class__.gui.size[1]/2 - building_icon.size[1]/2 - 70)
		self.__class__.gui.adaptLayout()
Exemple #10
0
	def _loadObject(cls):
		"""Loads building from the db.
		"""
		cls.log.debug("Loading building %s", cls.id)
		try:
			cls._real_object = horizons.main.fife.engine.getModel().createObject(str(cls.id), 'building')
		except RuntimeError:
			cls.log.debug("Already loaded building %s", cls.id)
			cls._real_object = horizons.main.fife.engine.getModel().getObject(str(cls.id), 'building')
			return
		action_sets = cls.action_sets.iterkeys()
		all_action_sets = ActionSetLoader.get_sets()
		for action_set_id in action_sets:
			for action_id in all_action_sets[action_set_id].iterkeys():
				action = cls._real_object.createAction(action_id+"_"+str(action_set_id))
				fife.ActionVisual.create(action)
				for rotation in all_action_sets[action_set_id][action_id].iterkeys():
					#print "rotation:", rotation
					if rotation == 45:
						command = 'left-32,bottom+' + str(cls.size[0] * 16)
					elif rotation == 135:
						command = 'left-' + str(cls.size[1] * 32) + ',bottom+16'
					elif rotation == 225:
						command = 'left-' + str((cls.size[0] + cls.size[1] - 1) * 32) + ',bottom+' + str(cls.size[1] * 16)
					elif rotation == 315:
						command = 'left-' + str(cls.size[0] * 32) + ',bottom+' + str((cls.size[0] + cls.size[1] - 1) * 16)
					else:
						assert False, "Bad rotation for action_set %(id)s: %(rotation)s for action: %(action_id)s" % \
							   { 'id':action_set_id, 'rotation': rotation, 'action_id': action_id }
					anim = horizons.main.fife.animationloader.loadResource(str(action_set_id)+"+"+str(action_id)+"+"+str(rotation) + ':shift:' + command)
					action.get2dGfxVisual().addAnimation(int(rotation), anim)
					action.setDuration(anim.getDuration())
	def on_settler_level_change(self, message):
		assert isinstance(message, SettlerUpdate)
		setup_tax_slider(self.widget.child_finder('tax_slider'), self.widget.child_finder('tax_val_label'),
		                  self.instance.settlement, message.level)
		self.widget.child_finder('tax_val_label').text = unicode(self.instance.settlement.tax_settings[self.instance.level])
		imgs = ActionSetLoader.get_sets()[self.instance._action_set_id].items()[0][1]
		self.widget.findChild(name="building_image").image = imgs[45].keys()[0]
 def __init__(self, instance):
     super(SignalFireOverviewTab,
           self).__init__(widget='overview_signalfire.xml',
                          instance=instance)
     action_set = ActionSetLoader.get_action_sets()[
         self.instance._action_set_id]
     action_gfx = action_set.items()[0][1]
     image = action_gfx[45].keys()[0]
     self.widget.findChild(name="building_image").image = image
     self.tooltip = _("Overview")
	def __init__(self, instance):
		super(SignalFireOverviewTab, self).__init__(
			widget = 'tab_widget/tab_overview_signalfire.xml',
			instance = instance
		)
		action_set = ActionSetLoader.get_action_sets()[self.instance._action_set_id]
		action_gfx = action_set.items()[0][1]
		image = action_gfx[45].keys()[0]
		self.widget.findChild(name="building_image").image = image
		self.widget.findChild(name='name').stylize("headline")
		self.tooltip = u"Overview"
	def  __init__(self, instance):
		super(SettlerOverviewTab, self).__init__(
			widget = 'tab_widget/tab_overview_settler.xml',
			instance = instance
		)
		self.tooltip = u"Settler Overview"
		_setup_tax_slider(self.widget.child_finder('tax_slider'), self.instance.settlement)

		action_set = ActionSetLoader.get_action_sets()[self.instance._action_set_id]
		action_gfx = action_set.items()[0][1]
		image = action_gfx[45].keys()[0]
		self.widget.findChild(name="building_image").image = image
	def  __init__(self, instance):
		super(SettlerOverviewTab, self).__init__(
			widget = 'overview_settler.xml',
			instance = instance
		)
		self.tooltip = _("Settler overview")
		_setup_tax_slider(self.widget.child_finder('tax_slider'), self.instance.settlement)

		action_set = ActionSetLoader.get_action_sets()[self.instance._action_set_id]
		action_gfx = action_set.items()[0][1]
		image = action_gfx[45].keys()[0]
		self.widget.findChild(name="building_image").image = image
	def  __init__(self, instance):
		super(SettlerOverviewTab, self).__init__(
			widget = 'overview_settler.xml',
			instance = instance
		)
		self.tooltip = _("Settler overview")
		self.widget.findChild(name="headline").text = unicode(self.instance.settlement.name)
		_setup_tax_slider(self.widget.child_finder('tax_slider'), self.widget.child_finder('tax_val_label'), self.instance.settlement)

		self.widget.child_finder('tax_val_label').text = unicode(self.instance.settlement.tax_setting)
		action_set = ActionSetLoader.get_action_sets()[self.instance._action_set_id]
		action_gfx = action_set.items()[0][1]
		image = action_gfx[45].keys()[0]
		self.widget.findChild(name="building_image").image = image
    def _loadObject(cls, db):
        """Loads building from the db.
		"""
        cls.log.debug("Loading building %s", cls.id)
        try:
            cls._object = horizons.main.fife.engine.getModel().createObject(
                str(cls.id), 'building')
        except RuntimeError:
            cls.log.debug("Already loaded building %s", cls.id)
            cls._object = horizons.main.fife.engine.getModel().getObject(
                str(cls.id), 'building')
            return
        action_sets = db(
            "SELECT action_set_id FROM data.action_set WHERE object_id=?",
            cls.id)
        all_action_sets = ActionSetLoader.get_action_sets()
        for (action_set_id, ) in action_sets:
            for action_id in all_action_sets[action_set_id].iterkeys():
                action = cls._object.createAction(action_id + "_" +
                                                  str(action_set_id))
                fife.ActionVisual.create(action)
                for rotation in all_action_sets[action_set_id][
                        action_id].iterkeys():
                    #print "rotation:", rotation
                    if rotation == 45:
                        command = 'left-32,bottom+' + str(cls.size[0] * 16)
                    elif rotation == 135:
                        command = 'left-' + str(
                            cls.size[1] * 32) + ',bottom+16'
                    elif rotation == 225:
                        command = 'left-' + str(
                            (cls.size[0] + cls.size[1] - 1) *
                            32) + ',bottom+' + str(cls.size[1] * 16)
                    elif rotation == 315:
                        command = 'left-' + str(
                            cls.size[0] * 32) + ',bottom+' + str(
                                (cls.size[0] + cls.size[1] - 1) * 16)
                    else:
                        assert False, "Bad rotation for action_set %(id)s: %(rotation)s for action: %(action_id)s" % \
                            { 'id':action_set_id, 'rotation': rotation, 'action_id': action_id }
                    anim_id = horizons.main.fife.animationpool.addResourceFromFile(
                        str(action_set_id) + "-" + str(action_id) + "-" +
                        str(rotation) + ':shift:' + command)
                    action.get2dGfxVisual().addAnimation(
                        int(rotation), anim_id)
                    action.setDuration(
                        horizons.main.fife.animationpool.getAnimation(
                            anim_id).getDuration())
	def  __init__(self, instance):
		super(SettlerOverviewTab, self).__init__(
			widget = 'overview_settler.xml',
			instance = instance
		)
		self.instance.session.message_bus.subscribe_locally(SettlerUpdate, self.instance, self.on_settler_level_change)
		self.tooltip = _("Settler overview")
		self.widget.findChild(name="headline").text = unicode(self.instance.settlement.get_component(NamedComponent).name)
		_setup_tax_slider(self.widget.child_finder('tax_slider'), self.widget.child_finder('tax_val_label'),
		                  self.instance.settlement, self.instance.level)

		self.widget.child_finder('tax_val_label').text = unicode(self.instance.settlement.tax_settings[self.instance.level])
		action_set = ActionSetLoader.get_sets()[self.instance._action_set_id]
		action_gfx = action_set.items()[0][1]
		image = action_gfx[45].keys()[0]
		self.widget.findChild(name="building_image").image = image
	def _loadObject(cls):
		"""Loads building from the db.
		"""
		cls.log.debug("Loading building %s", cls.id)
		try:
			cls._real_object = horizons.main.fife.engine.getModel().createObject(str(cls.id), 'building')
		except RuntimeError:
			cls.log.debug("Already loaded building %s", cls.id)
			cls._real_object = horizons.main.fife.engine.getModel().getObject(str(cls.id), 'building')
			return
		all_action_sets = ActionSetLoader.get_sets()

		# cls.action_sets looks like this: {tier1: {set1: None, set2: preview2, ..}, ..}
		for action_set_list in cls.action_sets.itervalues():
			for action_set in action_set_list: # set1, set2, ...
				for action_id in all_action_sets[action_set]: # idle, move, ...
					cls._do_load(all_action_sets, action_set, action_id)
	def  __init__(self, instance):
		super(SettlerOverviewTab, self).__init__(
			widget = 'overview_settler.xml',
			instance = instance
		)
		self.helptext = _("Settler overview")
		name = self.instance.settlement.get_component(NamedComponent).name
		self.widget.findChild(name="headline").text = name
		setup_tax_slider(self.widget.child_finder('tax_slider'),
		                 self.widget.child_finder('tax_val_label'),
		                 self.instance.settlement,
		                 self.instance.level)

		taxes = self.instance.settlement.tax_settings[self.instance.level]
		self.widget.child_finder('tax_val_label').text = unicode(taxes)
		action_set = ActionSetLoader.get_sets()[self.instance._action_set_id]
		action_gfx = action_set.items()[0][1]
		image = action_gfx[45].keys()[0]
		self.widget.findChild(name="building_image").image = image
    def _loadObject(cls, db):
        """Loads building from the db.
		"""
        cls.log.debug("Loading building %s", cls.id)
        try:
            cls._object = horizons.main.fife.engine.getModel().createObject(str(cls.id), "building")
        except RuntimeError:
            cls.log.debug("Already loaded building %s", cls.id)
            cls._object = horizons.main.fife.engine.getModel().getObject(str(cls.id), "building")
            return
        action_sets = db("SELECT action_set_id FROM data.action_set WHERE object_id=?", cls.id)
        all_action_sets = ActionSetLoader.get_action_sets()
        for (action_set_id,) in action_sets:
            for action_id in all_action_sets[action_set_id].iterkeys():
                action = cls._object.createAction(action_id + "_" + str(action_set_id))
                fife.ActionVisual.create(action)
                for rotation in all_action_sets[action_set_id][action_id].iterkeys():
                    # print "rotation:", rotation
                    if rotation == 45:
                        command = "left-32,bottom+" + str(cls.size[0] * 16)
                    elif rotation == 135:
                        command = "left-" + str(cls.size[1] * 32) + ",bottom+16"
                    elif rotation == 225:
                        command = (
                            "left-" + str((cls.size[0] + cls.size[1] - 1) * 32) + ",bottom+" + str(cls.size[1] * 16)
                        )
                    elif rotation == 315:
                        command = (
                            "left-" + str(cls.size[0] * 32) + ",bottom+" + str((cls.size[0] + cls.size[1] - 1) * 16)
                        )
                    else:
                        assert False, "Bad rotation for action_set %(id)s: %(rotation)s for action: %(action_id)s" % {
                            "id": action_set_id,
                            "rotation": rotation,
                            "action_id": action_id,
                        }
                    anim_id = horizons.main.fife.animationpool.addResourceFromFile(
                        str(action_set_id) + "-" + str(action_id) + "-" + str(rotation) + ":shift:" + command
                    )
                    action.get2dGfxVisual().addAnimation(int(rotation), anim_id)
                    action.setDuration(horizons.main.fife.animationpool.getAnimation(anim_id).getDuration())
	def _loadObject(cls):
		"""Loads the object with all animations.
		"""
		cls.log.debug('Loading unit %s', cls.id)
		try:
			cls._real_object = horizons.main.fife.engine.getModel().createObject(str(cls.id), 'unit')
		except RuntimeError:
			cls.log.debug('Already loaded unit %s', cls.id)
			cls._real_object = horizons.main.fife.engine.getModel().getObject(str(cls.id), 'unit')
			return
		cls._real_object.setPather(horizons.main.fife.engine.getModel().getPather('RoutePather'))
		cls._real_object.setBlocking(False)
		cls._real_object.setStatic(False)
		action_sets = ActionSetLoader.get_sets()
		# create load callbacks to be called when the actions are needed

		def do_load(action_set_id, action_id):
			action = cls._real_object.createAction(action_id+"_"+str(action_set_id))
			fife.ActionVisual.create(action)
			for rotation in action_sets[action_set_id][action_id].iterkeys():
				anim = horizons.main.fife.animationloader.loadResource( \
					str(action_set_id)+"+"+str(action_id)+"+"+ \
					str(rotation) + ':shift:center+0,bottom+8')
				action.get2dGfxVisual().addAnimation(int(rotation), anim)
				action.setDuration(anim.getDuration())

		#{ action_set : { action_id : [ load0, load1, ..., loadn ]}}
		# (loadi are load functions of objects, there can be many per as_id and action)
		# cls.action_sets looks like this: {tier1: {set1: None, set2: preview2, ..}, ..}
		for set_dict in cls.action_sets.itervalues():
			for action_set in set_dict.iterkeys(): # set1, set2, ...
				if not action_set in cls._action_load_callbacks:
					cls._action_load_callbacks[action_set] = {}
				for action_id in action_sets[action_set].iterkeys(): # idle, move, ...
					if not action_id in cls._action_load_callbacks[action_set]:
						cls._action_load_callbacks[action_set][action_id] = []
					cls._action_load_callbacks[action_set][action_id].append(
					  Callback(do_load, action_set, action_id))
	def _loadObject(cls, db):
		"""Loads the object with all animations.
		"""
		cls.log.debug('Loading unit %s', cls.id)
		try:
			cls._object = horizons.main.fife.engine.getModel().createObject(str(cls.id), 'unit')
		except RuntimeError:
			cls.log.debug('Already loaded unit %s', cls.id)
			cls._object = horizons.main.fife.engine.getModel().getObject(str(cls.id), 'unit')
			return
		cls._object.setPather(horizons.main.fife.engine.getModel().getPather('RoutePather'))
		cls._object.setBlocking(False)
		cls._object.setStatic(False)
		action_sets = ActionSetLoader.get_action_sets()
		for (action_set_id,) in db("SELECT action_set_id FROM action_set WHERE object_id=?", cls.id):
			for action_id in action_sets[action_set_id].iterkeys():
				action = cls._object.createAction(action_id+"_"+str(action_set_id))
				fife.ActionVisual.create(action)
				for rotation in action_sets[action_set_id][action_id].iterkeys():
					anim = horizons.main.fife.animationloader.loadResource( \
						str(action_set_id)+"-"+str(action_id)+"-"+ \
						str(rotation) + ':shift:center+0,bottom+8')
					action.get2dGfxVisual().addAnimation(int(rotation), anim)
					action.setDuration(anim.getDuration())
	def has_action(self, action):
		"""Checks if this unit has a certain action.
		@param anim: animation id as string"""
		return (action in ActionSetLoader.get_action_sets()[self._action_set_id])
Exemple #25
0
	def getInstance(cls, session, x, y, action='idle', level=0, rotation=45, action_set_id=None):
		"""Get a Fife instance
		@param x, y: The coordinates
		@param action: The action, defaults to 'idle'
		@param level: object level. Relevant for choosing an action set
		@param rotation: rotation of the object. Any of [ 45 + 90*i for i in xrange(0, 4) ]
		@param action_set_id: can be set if the action set is already known. If set, level isn't considered.
		"""
		assert isinstance(x, int)
		assert isinstance(y, int)
		#rotation = cls.check_build_rotation(session, rotation, x, y)
		# TODO: replace this with new buildable api
		# IDEA: save rotation in savegame
		facing_loc = fife.Location(session.view.layers[cls.layer])
		instance_coords = list((x, y, 0))
		layer_coords = list((x, y, 0))

		# NOTE:
		# nobody acctually knows how the code below works.
		# it's for adapting the facing location and instance coords in
		# different rotations, and works with all quadratic buildings (tested up to 4x4)
		# for the first unquadratic building (2x4), a hack fix was put into it.
		# the plan for fixing this code in general is to wait until there are more
		# unquadratic buildings, and figure out a pattern of the placement error,
		# then fix that generally.

		if rotation == 45:
			layer_coords[0] = x+cls.size[0]+3

			if cls.size[0] == 2 and cls.size[1] == 4:
				# HACK: fix for 4x2 buildings
				instance_coords[0] -= 1
				instance_coords[1] += 1

		elif rotation == 135:
			instance_coords[1] = y + cls.size[1] - 1
			layer_coords[1] = y-cls.size[1]-3

			if cls.size[0] == 2 and cls.size[1] == 4:
				# HACK: fix for 4x2 buildings
				instance_coords[0] += 1
				instance_coords[1] -= 1

		elif rotation == 225:
			instance_coords = list(( x + cls.size[0] - 1, y + cls.size[1] - 1, 0))
			layer_coords[0] = x-cls.size[0]-3

			if cls.size[0] == 2 and cls.size[1] == 4:
				# HACK: fix for 4x2 buildings
				instance_coords[0] += 1
				instance_coords[1] -= 1

		elif rotation == 315:
			instance_coords[0] = x + cls.size[0] - 1
			layer_coords[1] = y+cls.size[1]+3

			if cls.size[0] == 2 and cls.size[1] == 4:
				# HACK: fix for 4x2 buildings
				instance_coords[0] += 1
				instance_coords[1] -= 1

		else:
			return None
		instance = session.view.layers[cls.layer].createInstance(cls._object, \
											                                       fife.ModelCoordinate(*instance_coords))
		facing_loc.setLayerCoordinates(fife.ModelCoordinate(*layer_coords))

		if action_set_id is None:
			action_set_id = session.db.get_random_action_set(cls.id, level=level)[0]
		fife.InstanceVisual.create(instance)

		action_sets = ActionSetLoader.get_action_sets()
		if not action in action_sets[action_set_id]:
			if 'idle' in action_sets[action_set_id]:
				action='idle'
			elif 'idle_full' in action_sets[action_set_id]:
				action='idle_full'
			else:
				# set first action
				action = action_sets[action_set_id].keys()[0]

		instance.act(action+"_"+str(action_set_id), facing_loc, True)
		return instance
    def loadResource(self, location):
        """
		@param location: String with the location. See below for details:
		Location format: <animation_id>:<command>:<params> (e.g.: "123:shift:left-16, bottom-8)
		Available commands:
		- shift:
		Shift the image using the params left, right, center, middle for x shifting and
		y-shifting with the params: top, bottom, center, middle.
		A param looks like this: "param_x(+/-)value, param_y(+/-)value" (e.g.: left-16, bottom+8)
		- cut:
		#TODO: complete documentation
		"""
        commands = location.getFilename().split(":")
        id = commands.pop(0)
        actionset, action, rotation = id.split("-")
        commands = zip(commands[0::2], commands[1::2])

        ani = fife.Animation()
        frame_start, frame_end = 0.0, 0.0
        for file in sorted(ActionSetLoader.get_action_sets()[actionset][action][int(rotation)].iterkeys()):
            frame_end = ActionSetLoader.get_action_sets()[actionset][action][int(rotation)][file]
            idx = horizons.main.fife.imagepool.addResourceFromFile(file)
            img = horizons.main.fife.imagepool.getImage(idx)
            for command, arg in commands:
                if command == "shift":
                    x, y = arg.split(",")
                    if x.startswith("left"):
                        x = int(x[4:]) + int(img.getWidth() / 2)
                    elif x.startswith("right"):
                        x = int(x[5:]) - int(img.getWidth() / 2)
                    elif x.startswith(("center", "middle")):
                        x = int(x[6:])
                    else:
                        x = int(x)

                    if y.startswith("top"):
                        y = int(y[3:]) + int(img.getHeight() / 2)
                    elif y.startswith("bottom"):
                        y = int(y[6:]) - int(img.getHeight() / 2)
                    elif y.startswith(("center", "middle")):
                        y = int(y[6:])
                    else:
                        y = int(y)

                    img.setXShift(x)
                    img.setYShift(y)
                elif command == "cut":
                    loc = fife.ImageLocation("asdf")
                    loc.setParentSource(img)
                    x, y, w, h = arg.split(",")

                    if x.startswith("left"):
                        x = int(x[4:])
                    elif x.startswith("right"):
                        x = int(x[5:]) + img.getWidth()
                    elif x.startswith(("center", "middle")):
                        x = int(x[6:]) + int(img.getWidth() / 2)
                    else:
                        x = int(x)

                    if y.startswith("top"):
                        y = int(y[3:])
                    elif y.startswith("bottom"):
                        y = int(y[6:]) - img.getHeight()
                    elif y.startswith(("center", "middle")):
                        y = int(y[6:]) + int(img.getHeight() / 2)
                    else:
                        y = int(y)

                    if w.startswith("left"):
                        w = int(w[4:]) - x
                    elif w.startswith("right"):
                        w = int(w[5:]) + img.getWidth() - x
                    elif w.startswith(("center", "middle")):
                        w = int(w[6:]) + int(img.getWidth() / 2) - x
                    else:
                        w = int(w)

                    if h.startswith("top"):
                        h = int(h[3:]) - y
                    elif h.startswith("bottom"):
                        h = int(h[6:]) + img.getHeight() - y
                    elif h.startswith(("center", "middle")):
                        h = int(h[6:]) + int(img.getHeight() / 2) - y
                    else:
                        h = int(h)

                    loc.setXShift(x)
                    loc.setYShift(y)
                    loc.setWidth(w)
                    loc.setHeight(h)

                    idx = horizons.main.fife.imagepool.addResourceFromLocation(loc)
                    # img = horizons.main.fife.imagepool.getImage(idx)
            ani.addFrame(
                fife.ResourcePtr(horizons.main.fife.imagepool, idx),
                max(1, int((float(frame_end) - frame_start) * 1000)),
            )
            frame_start = float(frame_end)
        ani.setActionFrame(0)
        ani.thisown = 0
        return ani
	def loadResource(self, location):
		"""
		@param location: String with the location. See below for details:
		Location format: <animation_id>:<command>:<params> (e.g.: "123:shift:left-16, bottom-8)
		Available commands:
		- shift:
		Shift the image using the params left, right, center, middle for x shifting and
		y-shifting with the params: top, bottom, center, middle.
		A param looks like this: "param_x(+/-)value, param_y(+/-)value" (e.g.: left-16, bottom+8)
		- cut:
		#TODO: complete documentation
		"""
		commands = location.split(':')
		id = commands.pop(0)
		actionset, action, rotation = id.split('-')
		commands = zip(commands[0::2], commands[1::2])

		ani = fife.Animation.createAnimation()

		frame_start, frame_end = 0.0, 0.0
		for file in sorted(ActionSetLoader.get_action_sets()[actionset][action][int(rotation)].iterkeys()):
			entry = ActionSetLoader.get_action_sets()[actionset][action][int(rotation)][file]
			# we don't need to load images at this point to query for its parameters
			# such as width and height because we can get those from json file
			xpos, ypos, width, height = entry[2:]

			if horizons.main.fife.imagemanager.exists(file):
				img = horizons.main.fife.imagemanager.get(file)
			else:
				img = horizons.main.fife.imagemanager.create(file)
				region = fife.Rect(xpos, ypos, width, height)
				img.useSharedImage(self.atlaslib[entry[1]], region)

			for command, arg in commands:
				if command == 'shift':
					x, y = arg.split(',')
					if x.startswith('left'):
						x = int(x[4:]) + int(width / 2)
					elif x.startswith('right'):
						x = int(x[5:]) - int(width / 2)
					elif x.startswith(('center', 'middle')):
						x = int(x[6:])
					else:
						x = int(x)

					if y.startswith('top'):
						y = int(y[3:]) + int(height / 2)
					elif y.startswith('bottom'):
						y = int(y[6:]) - int(height / 2)
					elif y.startswith(('center', 'middle')):
						y = int(y[6:])
					else:
						y = int(y)

					img.setXShift(x)
					img.setYShift(y)

			frame_end = entry[0]
			ani.addFrame(img, max(1, int((float(frame_end) - frame_start)*1000)))
			frame_start = float(frame_end)
		ani.setActionFrame(0)
		return ani
    def getInstance(cls,
                    session,
                    x,
                    y,
                    action='idle',
                    level=0,
                    rotation=45,
                    action_set_id=None):
        """Get a Fife instance
		@param x, y: The coordinates
		@param action: The action, defaults to 'idle'
		@param level: object level. Relevant for choosing an action set
		@param rotation: rotation of the object. Any of [ 45 + 90*i for i in xrange(0, 4) ]
		@param action_set_id: can be set if the action set is already known. If set, level isn't considered.
		"""
        assert isinstance(x, int)
        assert isinstance(y, int)
        #rotation = cls.check_build_rotation(session, rotation, x, y)
        # TODO: replace this with new buildable api
        # IDEA: save rotation in savegame
        facing_loc = fife.Location(session.view.layers[cls.layer])
        instance_coords = list((x, y, 0))
        layer_coords = list((x, y, 0))

        # NOTE:
        # nobody acctually knows how the code below works.
        # it's for adapting the facing location and instance coords in
        # different rotations, and works with all quadratic buildings (tested up to 4x4)
        # for the first unquadratic building (2x4), a hack fix was put into it.
        # the plan for fixing this code in general is to wait until there are more
        # unquadratic buildings, and figure out a pattern of the placement error,
        # then fix that generally.

        if rotation == 45:
            layer_coords[0] = x + cls.size[0] + 3

            if cls.size[0] == 2 and cls.size[1] == 4:
                # HACK: fix for 4x2 buildings
                instance_coords[0] -= 1
                instance_coords[1] += 1

        elif rotation == 135:
            instance_coords[1] = y + cls.size[1] - 1
            layer_coords[1] = y - cls.size[1] - 3

            if cls.size[0] == 2 and cls.size[1] == 4:
                # HACK: fix for 4x2 buildings
                instance_coords[0] += 1
                instance_coords[1] -= 1

        elif rotation == 225:
            instance_coords = list(
                (x + cls.size[0] - 1, y + cls.size[1] - 1, 0))
            layer_coords[0] = x - cls.size[0] - 3

            if cls.size[0] == 2 and cls.size[1] == 4:
                # HACK: fix for 4x2 buildings
                instance_coords[0] += 1
                instance_coords[1] -= 1

        elif rotation == 315:
            instance_coords[0] = x + cls.size[0] - 1
            layer_coords[1] = y + cls.size[1] + 3

            if cls.size[0] == 2 and cls.size[1] == 4:
                # HACK: fix for 4x2 buildings
                instance_coords[0] += 1
                instance_coords[1] -= 1

        else:
            return None
        instance = session.view.layers[cls.layer].createInstance(cls._object, \
                                                        fife.ModelCoordinate(*instance_coords))
        facing_loc.setLayerCoordinates(fife.ModelCoordinate(*layer_coords))

        if action_set_id is None:
            action_set_id = session.db.get_random_action_set(cls.id,
                                                             level=level)[0]
        fife.InstanceVisual.create(instance)

        action_sets = ActionSetLoader.get_action_sets()
        if not action in action_sets[action_set_id]:
            if 'idle' in action_sets[action_set_id]:
                action = 'idle'
            elif 'idle_full' in action_sets[action_set_id]:
                action = 'idle_full'
            else:
                # set first action
                action = action_sets[action_set_id].keys()[0]

        instance.act(action + "_" + str(action_set_id), facing_loc, True)
        return instance
Exemple #29
0
    def loadResource(self, location):
        """
		@param location: String with the location. See below for details:
		Location format: <animation_id>:<command>:<params> (e.g.: "123:shift:left-16, bottom-8)
		Available commands:
		- shift:
		Shift the image using the params left, right, center, middle for x shifting and
		y-shifting with the params: top, bottom, center, middle.
		A param looks like this: "param_x(+/-)value, param_y(+/-)value" (e.g.: left-16, bottom+8)
		- cut:
		#TODO: complete documentation
		"""
        commands = location.getFilename().split(':')
        id = commands.pop(0)
        actionset, action, rotation = id.split('-')
        commands = zip(commands[0::2], commands[1::2])

        ani = fife.Animation()
        frame_start, frame_end = 0.0, 0.0
        for file in sorted(ActionSetLoader.get_action_sets()[actionset][action]
                           [int(rotation)].iterkeys()):
            frame_end = ActionSetLoader.get_action_sets()[actionset][action][
                int(rotation)][file]
            idx = horizons.main.fife.imagepool.addResourceFromFile(file)
            img = horizons.main.fife.imagepool.getImage(idx)
            for command, arg in commands:
                if command == 'shift':
                    x, y = arg.split(',')
                    if x.startswith('left'):
                        x = int(x[4:]) + int(img.getWidth() / 2)
                    elif x.startswith('right'):
                        x = int(x[5:]) - int(img.getWidth() / 2)
                    elif x.startswith(('center', 'middle')):
                        x = int(x[6:])
                    else:
                        x = int(x)

                    if y.startswith('top'):
                        y = int(y[3:]) + int(img.getHeight() / 2)
                    elif y.startswith('bottom'):
                        y = int(y[6:]) - int(img.getHeight() / 2)
                    elif y.startswith(('center', 'middle')):
                        y = int(y[6:])
                    else:
                        y = int(y)

                    img.setXShift(x)
                    img.setYShift(y)
                elif command == 'cut':
                    loc = fife.ImageLocation('asdf')
                    loc.setParentSource(img)
                    x, y, w, h = arg.split(',')

                    if x.startswith('left'):
                        x = int(x[4:])
                    elif x.startswith('right'):
                        x = int(x[5:]) + img.getWidth()
                    elif x.startswith(('center', 'middle')):
                        x = int(x[6:]) + int(img.getWidth() / 2)
                    else:
                        x = int(x)

                    if y.startswith('top'):
                        y = int(y[3:])
                    elif y.startswith('bottom'):
                        y = int(y[6:]) - img.getHeight()
                    elif y.startswith(('center', 'middle')):
                        y = int(y[6:]) + int(img.getHeight() / 2)
                    else:
                        y = int(y)

                    if w.startswith('left'):
                        w = int(w[4:]) - x
                    elif w.startswith('right'):
                        w = int(w[5:]) + img.getWidth() - x
                    elif w.startswith(('center', 'middle')):
                        w = int(w[6:]) + int(img.getWidth() / 2) - x
                    else:
                        w = int(w)

                    if h.startswith('top'):
                        h = int(h[3:]) - y
                    elif h.startswith('bottom'):
                        h = int(h[6:]) + img.getHeight() - y
                    elif h.startswith(('center', 'middle')):
                        h = int(h[6:]) + int(img.getHeight() / 2) - y
                    else:
                        h = int(h)

                    loc.setXShift(x)
                    loc.setYShift(y)
                    loc.setWidth(w)
                    loc.setHeight(h)

                    idx = horizons.main.fife.imagepool.addResourceFromLocation(
                        loc)
                    #img = horizons.main.fife.imagepool.getImage(idx)
            ani.addFrame(fife.ResourcePtr(horizons.main.fife.imagepool, idx),
                         max(1, int((float(frame_end) - frame_start) * 1000)))
            frame_start = float(frame_end)
        ani.setActionFrame(0)
        ani.thisown = 0
        return ani
not_found = 0
deleted = []

for source in mapping:
	if not os.path.exists(source):
		deleted.append(source)

if deleted:
	deleted.sort()
	print "Unused atlas entry:"
	for v in deleted:
		print "  {0} (in {1})".format(v, mapping[v].source)
	print ""

# Modify a bit how all_action_sets looks like
all_action_sets = ActionSetLoader.get_sets()
for tileset_id in all_action_sets:
	for action_id in all_action_sets[tileset_id]:
		for rotation in sorted(all_action_sets[tileset_id][action_id]):
			for file in sorted(all_action_sets[tileset_id][action_id][rotation]):
				# File name is only there for image manager to have unique names, it really doesn't matter
				# if its '/' or '\\' or even ':', we just need to pick one
				file_new = file.replace('\\', '/')

				try:
					entry = mapping[file_new]
				except KeyError:
					print "Warning: {0} not found".format(file)
					not_found = not_found + 1
					continue
    def has_action(self, action):
        """Checks if this unit has a certain action.
		@param anim: animation id as string"""
        return (action
                in ActionSetLoader.get_action_sets()[self._action_set_id])