Need help merging

strategyonly

C2C Supreme Commander
Joined
Mar 13, 2006
Messages
20,994
Location
MN
I need help understanding why this is happening?? Need someone to figure out how to fix, pls.

I found out I have a problem with my CvEventInterface

Spoiler :
Code:
import CvCustomEventManager
import CvUtil
import CvEventManager
import CvModEvents
from CvPythonExtensions import *

ModEventManager = CvModEvents.CvModEvents()
customEventManager = CvCustomEventManager.CvCustomEventManager()
normalEventManager = CvEventManager.CvEventManager()

def getEventManager():
	[B]return customEventManager[/B]
	return ModEventManager
	return eventManager

If i leave it as above the GreatPersonMod works, but another part does not (Subdue Animals)

And if i change it to:

Spoiler :
Code:
import CvCustomEventManager
import CvUtil
import CvEventManager
import CvModEvents
from CvPythonExtensions import *

ModEventManager = CvModEvents.CvModEvents()
customEventManager = CvCustomEventManager.CvCustomEventManager()
normalEventManager = CvEventManager.CvEventManager()

def getEventManager():
        [B]return ModEventManager[/B]
	return customEventManager
	return eventManager

The GP doesnt work, but the Subdue Animals does work.

Is there anyway someone could combine these to get them to work correctly??:rolleyes:


If you still dont have the SA here it is:

http://wwwnew.filefront.com/9344910/Subdue_Animals.zip
 
You must create and use exactly one event manager object; you are creating three. In Python, the first return statement reached exits the function with the object(s) being returned.

getEventManager() must return the one event manager to be used by the rest of Civ4. When you have this

Code:
def getEventManager():
	return customEventManager
	return ModEventManager
	return eventManager

customEventManager (which is a CvCustomEventManager object) is used. ModEventManager is ignored, and the line with the undefined variable eventManager is never reached, so it doesn't have a chance to cause an exception.

My guess without looking at the code is that you need to hook CvModEvents into CvCustomEventManager. You absolutely need to remove the extraneous event managers from CvEventsInterface:

Code:
import CvCustomEventManager
import CvUtil
[s]import CvEventManager[/s]
[s]import CvModEvents[/s]
from CvPythonExtensions import *

[s]ModEventManager = CvModEvents.CvModEvents()[/s]
customEventManager = CvCustomEventManager.CvCustomEventManager()
[s]normalEventManager = CvEventManager.CvEventManager()[/s]

def getEventManager():
	return customEventManager
	[s]return ModEventManager[/s]
	[s]return eventManager[/s]

Next open CvCustomEventManager.py and add two lines. Look for this line and add the bold line after it:

Code:
import CvGreatPersonEventManager
[B]import CvModEvents[/B]

Similarly, add this other bold line:

Code:
CvGreatPersonEventManager.CvGreatPersonEventManager(self)
[B]CvModEvents.CvModEvents(self)[/B]

You might be looking for CvGreatPersonEvents or CvGreatPerson; I am not sure. But that's what those lines will look like.
 
Well, if CvCustomEventManager is importing CvGreatPersonEventManager, it must be initializing it as well. Look to the end of the first __init__ function.
 
Well, if CvCustomEventManager is importing CvGreatPersonEventManager, it must be initializing it as well. Look to the end of the first __init__ function.

Great Person works, like his, but the Subdue Animals doesnt.
 
Did you add both bolded lines I had above? You said you couldn't find where to add the second one.
 
Did you add both bolded lines I had above? You said you couldn't find where to add the second one.

Correct, i cant find that. CvGreatPersonEventManager.CvGreatPersonEventManager(self)


Here's what i have:

Code:
class CvGreatPersonModEventManager:

	def __init__(self, eventManager):

		GreatPerson(eventManager)

class AbstractGreatPerson(object):

	def __init__(self, eventManager, *args, **kwargs):
		super(AbstractGreatPerson, self).__init__(*args, **kwargs)
 
OK heres:

CvEventInterface:
Code:
import CvCustomEventManager
import CvUtil
from CvPythonExtensions import *

customEventManager = CvCustomEventManager.CvCustomEventManager()

def getEventManager():
	return customEventManager


heres CvCustomEventManager
Code:
import BarbarianCiv
import CvEventManager
import CvConfigParser
import Popup as PyPopup
# --------- GreatPersonMod BTS -------------
import CvGreatPersonModEventManager
import CvModEvents

class CvCustomEventManager(CvEventManager.CvEventManager, object):

and the GP one is above??
 
Right, you import CvModEvents just fine, show me the code for the __init__ function. It should be immediately after the last code you posted.
 
Right, you import CvModEvents just fine, show me the code for the __init__ function. It should be immediately after the last code you posted.

Heres the whole thing: CvCustomEventManager:

Spoiler :
Code:
# $Source: /usr/local/cvsroot/Civ4lerts/src/main/python/CvCustomEventManager.py,v $


# --------- BarbarianCiv mod -------------
import BarbarianCiv
import CvEventManager
import CvConfigParser
import Popup as PyPopup
# --------- GreatPersonMod BTS -------------
import CvGreatPersonModEventManager
import CvModEvents


class CvCustomEventManager(CvEventManager.CvEventManager, object):

    """Extends the standard event manager by adding support for multiple
    handlers for each event.
    
    Methods exist for both adding and removing event handlers.  A set method 
    also exists to override the default handlers.  Clients should not depend 
    on event handlers being called in a particular order.
    
    This approach works best with mods that have implemented the design
    pattern suggested on Apolyton by dsplaisted.
    
    http://apolyton.net/forums/showthread.php?threadid=142916
    
    The example given in the 8th post in the thread would be handled by adding
    the following lines to the CvCustomEventManager constructor.  The RealFort,
    TechConquest, and CulturalDecay classes can remain unmodified.
    
        self.addEventHandler("unitMove", rf.onUnitMove)
        self.addEventHandler("improvementBuilt", rf.onImprovementBuilt)
        self.addEventHandler("techAcquired", rf.onTechAcquired)
        self.addEventHandler("cityAcquired", tc.onCityAcquired)
        self.addEventHandler("EndGameTurn", cd.onEndGameTurn)
        
    Note that the naming conventions for the event type strings vary from event
    to event.  Some use initial capitalization, some do not; some eliminate the
    "on..." prefix used in the event handler function name, some do not.  Look
    at the unmodified CvEventManager.py source code to determine the correct
    name for a particular event.
    
    Take care with event handlers that also extend CvEventManager.  Since
    this event manager handles invocation of the base class handler function,
    additional handlers should not also call the base class function themselves.

    """

    def __init__(self, *args, **kwargs):
        super(CvCustomEventManager, self).__init__(*args, **kwargs)
        # map the initial EventHandlerMap values into the new data structure
        for eventType, eventHandler in self.EventHandlerMap.iteritems():
            self.setEventHandler(eventType, eventHandler)
        # --> INSERT EVENT HANDLER INITIALIZATION HERE <--

        # --------- GreatPersonMod BTS ------------------
	CvGreatPersonModEventManager.CvGreatPersonModEventManager(self)
        # --------- BarbarianCiv mod -------------
        config = CvConfigParser.CvConfigParser("Next War Advanced.ini")
         

        if( not config.getboolean("CONFIG", "FoundConfig", False) ) :
            try :
                popup = PyPopup.PyPopup( )       
                bodStr = "WARNING:  BarbarianCiv.ini not found!  Using default settings."
                bodStr += "  Check mod installation directory, should be: (civ install directory)\Mods\Next War Advanced\."
                popup.setBodyString( bodStr )
                popup.launch()
            except :
                print "WARNING:  BarbarianCiv.ini not found!  Using default settings."
        
        if( config.getboolean("BarbarianCiv", "Enable", True) ) :
            BarbarianCiv.BarbarianCiv(self, config)

    def addEventHandler(self, eventType, eventHandler):
        """Adds a handler for the given event type.
        
        A list of supported event types can be found in the initialization 
        of EventHandlerMap in the CvEventManager class.
        
        Throws LookupError if the eventType is not valid.

        """
        if eventType not in self.EventHandlerMap:
            raise LookupError(eventType)
        if( not eventHandler in self.EventHandlerMap[eventType] ) :
            self.EventHandlerMap[eventType].append(eventHandler)

    def removeEventHandler(self, eventType, eventHandler):
        """Removes a handler for the given event type.
        
        A list of supported event types can be found in the initialization 
        of EventHandlerMap in the CvEventManager class.  It is an error if 
        the given handler is not found in the list of installed handlers.
        
        Throws LookupError if the eventType is not valid.

        """
        if eventType not in self.EventHandlerMap:
            raise LookupError(eventType)
        self.EventHandlerMap[eventType].remove(eventHandler)
    
    def setEventHandler(self, eventType, eventHandler):
        """Removes all previously installed event handlers for the given 
        event type and installs a new handler.
        
        A list of supported event types can be found in the initialization 
        of EventHandlerMap in the CvEventManager class.  This method is 
        primarily useful for overriding, rather than extending, the default 
        event handler functionality.
        
        Throws LookupError if the eventType is not valid.

        """
        if eventType not in self.EventHandlerMap:
            raise LookupError(eventType)
        self.EventHandlerMap[eventType] = [eventHandler]
    
    def setPopupHandler(self, eventType, popupHandler):
        """Removes all previously installed popup handlers for the given 
        event type and installs a new handler.
        
        The eventType should be an integer.  It must be unique with respect
        to the integers assigned to built in events.  The popupHandler should
        be a list made up of (name, beginFunction, applyFunction).  The name
        is used in debugging output.  The begin and apply functions are invoked
        by beginEvent and applyEvent, respectively, to manage a popup dialog
        in response to the event.

        """
        self.Events[eventType] = popupHandler

    def handleEvent(self, argsList):
        """Handles events by calling all installed handlers."""
        self.origArgsList = argsList
        flagsIndex = len(argsList) - 6
        self.bDbg, self.bMultiPlayer, self.bAlt, self.bCtrl, self.bShift, self.bAllowCheats = argsList[flagsIndex:]
        eventType = argsList[0]
        return {
            "kbdEvent": self._handleConsumableEvent,
            "mouseEvent": self._handleConsumableEvent,
            "OnSave": self._handleOnSaveEvent,
            "OnLoad": self._handleOnLoadEvent
        }.get(eventType, self._handleDefaultEvent)(eventType, argsList[1:])

    def _handleDefaultEvent(self, eventType, argsList):
        if self.EventHandlerMap.has_key(eventType):
            for eventHandler in self.EventHandlerMap[eventType]:
                # the last 6 arguments are for internal use by handleEvent
                eventHandler(argsList[:len(argsList) - 6])

    def _handleConsumableEvent(self, eventType, argsList):
        """Handles events that can be consumed by the handlers, such as
        keyboard or mouse events.
        
        If a handler returns non-zero, processing is terminated, and no 
        subsequent handlers are invoked.

        """
        if self.EventHandlerMap.has_key(eventType):
            for eventHandler in self.EventHandlerMap[eventType]:
                # the last 6 arguments are for internal use by handleEvent
                result = eventHandler(argsList[:len(argsList) - 6])
                if (result > 0):
                    return result
        return 0

    # TODO: this probably needs to be more complex
    def _handleOnSaveEvent(self, eventType, argsList):
        """Handles OnSave events by concatenating the results obtained
        from each handler to form an overall consolidated save string.

        """
        result = ""
        if self.EventHandlerMap.has_key(eventType):
            for eventHandler in self.EventHandlerMap[eventType]:
                # the last 6 arguments are for internal use by handleEvent
                result = result + eventHandler(argsList[:len(argsList) - 6])
        return result

    # TODO: this probably needs to be more complex
    def _handleOnLoadEvent(self, eventType, argsList):
        """Handles OnLoad events."""
        return self._handleDefaultEvent(eventType, argsList)


Heres the CvGreatPersonModEventManager:


Spoiler :
Code:
# GreatPersonMod BTS
# CvGreatPersonModEventManager
# 

from CvPythonExtensions import *

import CvUtil
import CvEventManager
import sys
import PyHelpers
import CvGreatPersonScreen
import RandomNameUtils
import CvConfigParser
# Change the value to enable or disable the features from the Great Person Mod.
# Default value is true
g_bGreatPersonModFeaturesEnabled = true

gc = CyGlobalContext()

PyPlayer = PyHelpers.PyPlayer

g_iCount = 0     # autoincrement global used as the primary key for dictionary
g_dict = dict()  # holds information transferred from here to CvGreatPersonScreen.py

class CvGreatPersonModEventManager:

	def __init__(self, eventManager):

		GreatPerson(eventManager)

class AbstractGreatPerson(object):

	def __init__(self, eventManager, *args, **kwargs):
		super(AbstractGreatPerson, self).__init__(*args, **kwargs)

class GreatPerson(AbstractGreatPerson):

	def __init__(self, eventManager, *args, **kwargs):
		super(GreatPerson, self).__init__(eventManager, *args, **kwargs)

		eventManager.addEventHandler("greatPersonBorn", self.onGreatPersonBorn)

		self.eventMgr = eventManager

		# Begin Test Code
		""" # Uncomment this block to enable test code
		eventManager.addEventHandler("kbdEvent", self.onKbdEvent)

	# Test (ok cheat...) code to make sure that we can go through the vanilla great person
	# names and test the random names.
	## Changed event from just clicking mouse to hitting ALT-SHIFT-G. Test code not multiplayer compatible.
	## def onMouseEvent(self, argsList):
	def onKbdEvent(self, argsList):
		eventType,key,mx,my,px,py = argsList

		if(not g_bGreatPersonModFeaturesEnabled):
			return

		if ( eventType == self.eventMgr.EventKeyDown ):
			theKey=int(key)
			
			# Check if ALT + Shift + G was hit
			if (theKey == int(InputTypes.KB_G) and self.eventMgr.bAlt and self.eventMgr.bShift):	
				gc.getActivePlayer().getCapitalCity().createGreatPeople(gc.getInfoTypeForString("UNIT_GENERAL"), False, False)
				return 1
			
			# Check if CTRL + Shift + G was hit
			if (theKey == int(InputTypes.KB_G) and self.eventMgr.bCtrl and self.eventMgr.bShift):	
				gc.getActivePlayer().getCapitalCity().createGreatPeople(gc.getInfoTypeForString("UNIT_GREAT_SPY"), False, False)
				return 1
		return 0
		"""
		# End Test Code


	def onGreatPersonBorn(self, argsList):
		'Great Person Born'

		if(not g_bGreatPersonModFeaturesEnabled):
			return
		
		pUnit, iPlayer, pCity = argsList
		player = gc.getPlayer(iPlayer)
        
		# Check if we should even show the popup:
		if pUnit.isNone() or pCity.isNone():
			return
		
		#CvUtil.pyPrint("Great Person Born: Name:<%s> Player:<%s> City:<%s>"%(pUnit.getNameNoDesc(), player.getName(), pCity.getName()))
		    
		#If Person doesn't have unique name, give him a random one
		if(len(pUnit.getNameNoDesc()) == 0):
			iCivilizationType = player.getCivilizationType()
			pUnit.setName(RandomNameUtils.getRandomCivilizationName(iCivilizationType))

		#Show fancy lil popup if a human got the great person:
		if player.isHuman():
		
			global g_dict
			global g_iCount
			
			g_dict[g_iCount] = (pUnit, iPlayer, pCity)
			
			#CvUtil.pyPrint("Great Person Born 2: Name:<%s> iPlayer:<%d> City:<%s>"%(g_dict[g_iCount][0].getNameNoDesc(), g_dict[g_iCount][1], g_dict[g_iCount][2].getName()))
			
			popupInfo = CyPopupInfo()
			popupInfo.setButtonPopupType(ButtonPopupTypes.BUTTONPOPUP_PYTHON_SCREEN)
			popupInfo.setData1(g_iCount)
			g_iCount += 1
			popupInfo.setText(u"showGreatPersonScreen")
			popupInfo.addPopup(iPlayer)

Then CvEventInterface:


Spoiler :
Code:
# Sid Meier's Civilization 4
# Copyright Firaxis Games 2005
#
# CvEventInterface.py
#
# These functions are App Entry Points from C++
# WARNING: These function names should not be changed
# WARNING: These functions can not be placed into a class
#
# No other modules should import this


import CvCustomEventManager
import CvUtil
from CvPythonExtensions import *

customEventManager = CvCustomEventManager.CvCustomEventManager()

def getEventManager():
	return customEventManager
		
		
def onEvent(argsList):
    """Called when a game event happens - return 1 if the event was consumed."""
    return getEventManager().handleEvent(argsList)

def applyEvent(argsList):
    context, playerID, netUserData, popupReturn = argsList
    return getEventManager().applyEvent(argsList)

def beginEvent(context, argsList = -1):
    return getEventManager().beginEvent(context, argsList)
 
Didn't you see this under __init__() in CvCustomEventManager?

Code:
# --------- GreatPersonMod BTS ------------------
CvGreatPersonModEventManager.CvGreatPersonModEventManager(self)
# --------- BarbarianCiv mod -------------

Add this bold line I posted here:

Code:
# --------- GreatPersonMod BTS ------------------
CvGreatPersonModEventManager.CvGreatPersonModEventManager(self)
[B]CvModEvents.CvModEvents(self)[/B]
# --------- BarbarianCiv mod -------------
 
Didn't you see this under __init__() in CvCustomEventManager?

Code:
# --------- GreatPersonMod BTS ------------------
CvGreatPersonModEventManager.CvGreatPersonModEventManager(self)
# --------- BarbarianCiv mod -------------

Add this bold line I posted here:

Code:
# --------- GreatPersonMod BTS ------------------
CvGreatPersonModEventManager.CvGreatPersonModEventManager(self)
[B]CvModEvents.CvModEvents(self)[/B]
# --------- BarbarianCiv mod -------------

Yeah i saw that, but i get this error now???

Traceback (most recent call last):
ERR: Call function onEvent failed. Can't find module CvEventInterface
File "<string>", line 1, in ?
ERR: Call function onEvent failed. Can't find module CvEventInterface
ERR: Call function onEvent failed. Can't find module CvEventInterface
File "<string>", line 52, in load_module
ERR: Call function onEvent failed. Can't find module CvEventInterface
ERR: Call function onEvent failed. Can't find module CvEventInterface
File "CvEventInterface", line 17, in ?
ERR: Call function onEvent failed. Can't find module CvEventInterface
ERR: Call function onEvent failed. Can't find module CvEventInterface
File "CvCustomEventManager", line 79, in __init__
ERR: Call function onEvent failed. Can't find module CvEventInterface
ERR: Call function onEvent failed. Can't find module CvEventInterface
TypeError
ERR: Call function onEvent failed. Can't find module CvEventInterface
ERR: Call function onEvent failed. Can't find module CvEventInterface
:
ERR: Call function onEvent failed. Can't find module CvEventInterface
ERR: Call function onEvent failed. Can't find module CvEventInterface
__init__() takes exactly 1 argument (2 given)
ERR: Call function onEvent failed. Can't find module CvEventInterface
ERR: Call function onEvent failed. Can't find module CvEventInterface

ERR: Call function onEvent failed. Can't find module CvEventInterface
ERR: Call function onEvent failed. Can't find module CvEventInterface
Failed to load python module CvEventInterface.
ERR: Call function onEvent failed. Can't find module CvEventInterface
ERR: Call function onEvent failed. Can't find module CvEventInterface

Thats why i thought it was wrong????
 
Ah, you said you couldn't find that line anywhere in your Python. Please be more specific about what's happening in the future. It's very hard to help if we don't know the actual problem you're getting. :confused:

Try removing the "self" from that line. The error is saying that CvModEvents wants only 1 parameter (and the CvModEvents object becomes the "self" in its function.
 
Ah, you said you couldn't find that line anywhere in your Python. Please be more specific about what's happening in the future. It's very hard to help if we don't know the actual problem you're getting. :confused:

Try removing the "self" from that line. The error is saying that CvModEvents wants only 1 parameter (and the CvModEvents object becomes the "self" in its function.

Yeah, i didnt find it till your last message, then i just wrote the message i sent above, sometimes i just write stuff like: "Yeah i saw that" meaning i just saw that and the results are, sorry.:blush:

EDIT: Nope, didnt work, my Subdue Animals does NOT work.
 
Try this version of CvModEvents.py, and put the "self" back into the call to CvModEvents() in CvCustomEventManager as I originally posted it. The version you posted only works as a replacement for CvCustomEventManager--not with it.
 
Try this version of CvModEvents.py, and put the "self" back into the call to CvModEvents() in CvCustomEventManager as I originally posted it. The version you posted only works as a replacement for CvCustomEventManager--not with it.

OK tried it, it didnt give me the animal and had this error: Had to leave CvCustomEventManager cause it has two different mods going there for info????

Traceback (most recent call last):

File "CvEventInterface", line 25, in onEvent

File "CvCustomEventManager", line 162, in handleEvent

File "CvCustomEventManager", line 173, in _handleDefaultEvent

File "CvModEvents", line 44, in onCombatResult

NameError: global name 'PyInfo' is not defined
ERR: Python function onEvent failed, module CvEventInterface
 
Change this line up at the top

Code:
from PyHelpers import PyPlayer

to this

Code:
from PyHelpers import *
 
OK, the Subdue is working and the GP is working, now just let me play it for 10 hours and see what happens, and many many many many thx.

I have a different error about an event that never showed up before do you want me to make a different thread or use this one for it?? It has NOTHING to do in what YOU just did, ok.

Its an event from RoM mod.:mischief:

Also what would cause the second attachment to happen, to lose half of the air deployment strike area??
 
Is that Buccaneers event a creation of yours or one of the mods you merged, or is it from BTS itself? I've never gotten the event, but I don't play a whole lot.

I have no idea what would cause the second problem with the bombing range shading. That's really strange. If you select a different unit and then reselect the missile, does it fix it or still look wrong?
 
Top Bottom