DistributedObjectAI.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. """DistributedObjectAI module: contains the DistributedObjectAI class"""
  2. from direct.directnotify.DirectNotifyGlobal import *
  3. from direct.showbase import PythonUtil
  4. from direct.showbase import DirectObject
  5. from pandac.PandaModules import *
  6. from PyDatagram import PyDatagram
  7. from PyDatagramIterator import PyDatagramIterator
  8. class DistributedObjectAI(DirectObject.DirectObject):
  9. notify = directNotify.newCategory("DistributedObjectAI")
  10. QuietZone = 1
  11. def __init__(self, air):
  12. try:
  13. self.DistributedObjectAI_initialized
  14. except:
  15. self.DistributedObjectAI_initialized = 1
  16. self.accountName=''
  17. # Record the repository
  18. self.air = air
  19. # Record our parentId and zoneId
  20. self.__location = None
  21. # Record our distributed class
  22. className = self.__class__.__name__
  23. self.dclass = self.air.dclassesByName[className]
  24. # init doId pre-allocated flag
  25. self.__preallocDoId = 0
  26. # used to track zone changes across the quiet zone
  27. # NOTE: the quiet zone is defined in OTP, but we need it
  28. # here.
  29. self.lastNonQuietZone = None
  30. self._DOAI_requestedDelete = False
  31. # These are used to implement beginBarrier().
  32. self.__nextBarrierContext = 0
  33. self.__barriers = {}
  34. # Uncomment if you want to debug DO leaks
  35. #def __del__(self):
  36. # """
  37. # For debugging purposes, this just prints out what got deleted
  38. # """
  39. # print ("Destructing: " + self.__class__.__name__)
  40. def getDeleteEvent(self):
  41. # this is sent just before we get deleted
  42. if hasattr(self, 'doId'):
  43. return 'distObjDelete-%s' % self.doId
  44. return None
  45. def sendDeleteEvent(self):
  46. # this is called just before we get deleted
  47. delEvent = self.getDeleteEvent()
  48. if delEvent:
  49. messenger.send(delEvent)
  50. def delete(self):
  51. """
  52. Inheritors should redefine this to take appropriate action on delete
  53. Note that this may be called multiple times if a class inherits
  54. from DistributedObjectAI more than once.
  55. """
  56. # prevent this code from executing multiple times
  57. if self.air is not None:
  58. # self.doId may not exist. The __dict__ syntax works around that.
  59. assert(self.notify.debug('delete(): %s' % (self.__dict__.get("doId"))))
  60. if not self._DOAI_requestedDelete:
  61. # this logs every delete that was not requested by us.
  62. # TODO: this currently prints warnings for deletes of objects
  63. # that we did not create. We need to add a 'locally created'
  64. # flag to every object to filter these out.
  65. """
  66. DistributedObjectAI.notify.warning(
  67. 'delete() called but requestDelete never called for %s: %s'
  68. % (self.__dict__.get('doId'), self.__class__.__name__))
  69. """
  70. """
  71. # print a stack trace so we can detect whether this is the
  72. # result of a network msg.
  73. # this is slow.
  74. from direct.showbase.PythonUtil import StackTrace
  75. DistributedObjectAI.notify.warning(
  76. 'stack trace: %s' % StackTrace())
  77. """
  78. self._DOAI_requestedDelete = False
  79. # Clean up all the pending barriers.
  80. for barrier in self.__barriers.values():
  81. barrier.cleanup()
  82. self.__barriers = {}
  83. if not hasattr(self, "doNotDeallocateChannel"):
  84. if self.air:
  85. self.air.deallocateChannel(self.doId)
  86. self.air = None
  87. if hasattr(self, 'parentId'):
  88. del self.parentId
  89. del self.zoneId
  90. def isDeleted(self):
  91. """
  92. Returns true if the object has been deleted,
  93. or if it is brand new and hasn't yet been generated.
  94. """
  95. return self.air == None
  96. def isGenerated(self):
  97. """
  98. Returns true if the object has been generated
  99. """
  100. return hasattr(self, 'zoneId')
  101. def getDoId(self):
  102. """
  103. Return the distributed object id
  104. """
  105. return self.doId
  106. def preAllocateDoId(self):
  107. """
  108. objects that need to have a doId before they are generated
  109. can call this to pre-allocate a doId for the object
  110. """
  111. assert not self.__preallocDoId
  112. self.doId = self.air.allocateChannel()
  113. self.__preallocDoId = 1
  114. def announceGenerate(self):
  115. """
  116. Called after the object has been generated and all
  117. of its required fields filled in. Overwrite when needed.
  118. """
  119. pass
  120. if wantOtpServer:
  121. def addInterest(self, zoneId, note="", event=None):
  122. self.air.addInterest(self.getDoId(), zoneId, note, event)
  123. def b_setLocation(self, parentId, zoneId):
  124. self.d_setLocation(parentId, zoneId)
  125. self.setLocation(parentId, zoneId)
  126. def d_setLocation(self, parentId, zoneId):
  127. self.air.sendSetLocation(self, parentId, zoneId)
  128. def setLocation(self, parentId, zoneId):
  129. oldParentId = self.parentId
  130. oldZoneId = self.zoneId
  131. if ((oldParentId != parentId) or
  132. (oldZoneId != zoneId)):
  133. self.zoneId = zoneId
  134. self.parentId = parentId
  135. self.air.changeDOZoneInTables(self, parentId, zoneId, oldParentId, oldZoneId)
  136. messenger.send(self.getZoneChangeEvent(), [zoneId, oldZoneId])
  137. # if we are not going into the quiet zone, send a 'logical' zone
  138. # change message
  139. if zoneId != DistributedObjectAI.QuietZone:
  140. lastLogicalZone = oldZoneId
  141. if oldZoneId == DistributedObjectAI.QuietZone:
  142. lastLogicalZone = self.lastNonQuietZone
  143. self.handleLogicalZoneChange(zoneId, lastLogicalZone)
  144. self.lastNonQuietZone = zoneId
  145. #self.air.storeObjectLocation(self.doId, parentId, zoneId)
  146. self.__location = (parentId, zoneId)
  147. def getLocation(self):
  148. return self.__location
  149. else:
  150. # NON OTP
  151. def handleZoneChange(self, newZoneId, oldZoneId):
  152. self.zoneId = newZoneId
  153. self.air.changeDOZoneInTables(self, newZoneId, oldZoneId)
  154. messenger.send(self.getZoneChangeEvent(), [newZoneId, oldZoneId])
  155. # if we are not going into the quiet zone, send a 'logical' zone change
  156. # message
  157. if newZoneId != DistributedObjectAI.QuietZone:
  158. lastLogicalZone = oldZoneId
  159. if oldZoneId == DistributedObjectAI.QuietZone:
  160. lastLogicalZone = self.lastNonQuietZone
  161. self.handleLogicalZoneChange(newZoneId, lastLogicalZone)
  162. self.lastNonQuietZone = newZoneId
  163. def updateRequiredFields(self, dclass, di):
  164. dclass.receiveUpdateBroadcastRequired(self, di)
  165. self.announceGenerate()
  166. def updateAllRequiredFields(self, dclass, di):
  167. dclass.receiveUpdateAllRequired(self, di)
  168. self.announceGenerate()
  169. def updateRequiredOtherFields(self, dclass, di):
  170. dclass.receiveUpdateBroadcastRequired(self, di)
  171. # Announce generate after updating all the required fields,
  172. # but before we update the non-required fields.
  173. self.announceGenerate()
  174. dclass.receiveUpdateOther(self, di)
  175. def updateAllRequiredOtherFields(self, dclass, di):
  176. dclass.receiveUpdateAllRequired(self, di)
  177. # Announce generate after updating all the required fields,
  178. # but before we update the non-required fields.
  179. self.announceGenerate()
  180. dclass.receiveUpdateOther(self, di)
  181. def sendSetZone(self, zoneId):
  182. self.air.sendSetZone(self, zoneId)
  183. def getZoneChangeEvent(self):
  184. # this event is generated whenever this object changes zones.
  185. # arguments are newZoneId, oldZoneId
  186. # includes the quiet zone.
  187. return 'DOChangeZone-%s' % self.doId
  188. def getLogicalZoneChangeEvent(self):
  189. # this event is generated whenever this object changes to a
  190. # non-quiet-zone zone.
  191. # arguments are newZoneId, oldZoneId
  192. # does not include the quiet zone.
  193. return 'DOLogicalChangeZone-%s' % self.doId
  194. def handleLogicalZoneChange(self, newZoneId, oldZoneId):
  195. """this function gets called as if we never go through the
  196. quiet zone. Note that it is called once you reach the newZone,
  197. and not at the time that you leave the oldZone."""
  198. messenger.send(self.getLogicalZoneChangeEvent(),
  199. [newZoneId, oldZoneId])
  200. def getRender(self):
  201. # note that this will return a different node if we change zones
  202. return self.air.getRender(self.zoneId)
  203. def getParentMgr(self):
  204. return self.air.getParentMgr(self.zoneId)
  205. def getCollTrav(self):
  206. return self.air.getCollTrav(self.zoneId)
  207. def sendUpdate(self, fieldName, args = []):
  208. assert self.notify.debugStateCall(self)
  209. if self.air:
  210. self.air.sendUpdate(self, fieldName, args)
  211. if wantOtpServer:
  212. def GetPuppetConnectionChannel(self, doId):
  213. return doId + (1L << 32);
  214. def GetAccountIDFromChannelCode(self, channel):
  215. return channel >> 32
  216. def GetAvatarIDFromChannelCode(self, channel):
  217. return channel & 0xffffffffL
  218. def sendUpdateToAvatarId(self, avId, fieldName, args):
  219. assert self.notify.debugStateCall(self)
  220. channelId = self.GetPuppetConnectionChannel(avId)
  221. self.sendUpdateToChannel(channelId, fieldName, args)
  222. else:
  223. def sendUpdateToAvatarId(self, avId, fieldName, args):
  224. assert self.notify.debugStateCall(self)
  225. channelId = avId + 1
  226. self.sendUpdateToChannel(channelId, fieldName, args)
  227. def sendUpdateToChannel(self, channelId, fieldName, args):
  228. assert self.notify.debugStateCall(self)
  229. if self.air:
  230. self.air.sendUpdateToChannel(self, channelId, fieldName, args)
  231. def generateWithRequired(self, zoneId, optionalFields=[]):
  232. assert self.notify.debugStateCall(self)
  233. # have we already allocated a doId?
  234. if self.__preallocDoId:
  235. self.__preallocDoId = 0
  236. return self.generateWithRequiredAndId(
  237. self.doId, zoneId, optionalFields)
  238. # The repository is the one that really does the work
  239. self.air.generateWithRequired(self, zoneId, optionalFields)
  240. if wantOtpServer:
  241. #HACK:
  242. if not hasattr(self, 'parentId'):
  243. parentId = self.air.districtId
  244. self.parentId = parentId
  245. self.zoneId = zoneId
  246. self.generate()
  247. # this is a special generate used for estates, or anything else that
  248. # needs to have a hard coded doId as assigned by the server
  249. def generateWithRequiredAndId(self, doId, zoneId, optionalFields=[]):
  250. assert self.notify.debugStateCall(self)
  251. # have we already allocated a doId?
  252. if self.__preallocDoId:
  253. assert doId == self.__preallocDoId
  254. self.__preallocDoId = 0
  255. # The repository is the one that really does the work
  256. self.air.generateWithRequiredAndId(self, doId, zoneId, optionalFields)
  257. if wantOtpServer:
  258. #HACK:
  259. if not hasattr(self, 'parentId'):
  260. parentId = self.air.districtId
  261. self.parentId = parentId
  262. self.zoneId = zoneId
  263. self.generate()
  264. if wantOtpServer:
  265. def generateOtpObject(self, parentId, zoneId, optionalFields=[], doId=None):
  266. assert self.notify.debugStateCall(self)
  267. # have we already allocated a doId?
  268. if self.__preallocDoId:
  269. assert doId is None or doId == self.__preallocDoId
  270. doId=self.__preallocDoId
  271. self.__preallocDoId = 0
  272. self.air.sendGenerateOtpObject(
  273. self, parentId, zoneId, optionalFields, doId=doId)
  274. assert not hasattr(self, 'parentId')
  275. self.parentId = parentId
  276. self.zoneId = zoneId
  277. self.__location = (parentId, zoneId)
  278. self.generate()
  279. def generate(self):
  280. """
  281. Inheritors should put functions that require self.zoneId or
  282. other networked info in this function.
  283. """
  284. assert self.notify.debugStateCall(self)
  285. if wantOtpServer:
  286. def generateInit(self, repository=None):
  287. """
  288. First generate (not from cache).
  289. """
  290. assert self.notify.debugStateCall(self)
  291. def generateTargetChannel(self, repository):
  292. """
  293. Who to send this to for generate messages
  294. """
  295. if hasattr(self, "dbObject"):
  296. return self.doId
  297. return repository.serverId
  298. def sendGenerateWithRequired(self, repository, parentId, zoneId, optionalFields=[]):
  299. assert self.notify.debugStateCall(self)
  300. if not wantOtpServer:
  301. parentId = 0
  302. # Make the dclass do the hard work
  303. if not wantOtpServer:
  304. dg = self.dclass.aiFormatGenerate(
  305. self, self.doId, 0, zoneId,
  306. repository.districtId,
  307. repository.ourChannel,
  308. optionalFields)
  309. else:
  310. dg = self.dclass.aiFormatGenerate(
  311. self, self.doId, parentId, zoneId,
  312. #repository.serverId,
  313. self.generateTargetChannel(repository),
  314. repository.ourChannel,
  315. optionalFields)
  316. repository.send(dg)
  317. def initFromServerResponse(self, valDict):
  318. assert self.notify.debugStateCall(self)
  319. # This is a special method used for estates, etc., which get
  320. # their fields set from the database indirectly by way of the
  321. # AI. The input parameter is a dictionary of field names to
  322. # datagrams that describes the initial field values from the
  323. # database.
  324. dclass = self.dclass
  325. for key, value in valDict.items():
  326. # Update the field
  327. dclass.directUpdate(self, key, value)
  328. def requestDelete(self):
  329. assert self.notify.debugStateCall(self)
  330. if not self.air:
  331. doId = "none"
  332. if hasattr(self, "doId"):
  333. doId = self.doId
  334. self.notify.warning("Tried to delete a %s (doId %s) that is already deleted" % (self.__class__, doId))
  335. return
  336. self.air.requestDelete(self)
  337. self._DOAI_requestedDelete = True
  338. def taskName(self, taskString):
  339. return (taskString + "-" + str(self.getDoId()))
  340. def uniqueName(self, idString):
  341. return (idString + "-" + str(self.getDoId()))
  342. def validate(self, avId, bool, msg):
  343. if not bool:
  344. self.air.writeServerEvent('suspicious', avId, msg)
  345. self.notify.warning('validate error: avId: %s -- %s' % (avId, msg))
  346. return bool
  347. def beginBarrier(self, name, avIds, timeout, callback):
  348. # Begins waiting for a set of avatars. When all avatars in
  349. # the list have reported back in or the callback has expired,
  350. # calls the indicated callback with the list of toons that
  351. # made it through. There may be multiple barriers waiting
  352. # simultaneously on different lists of avatars, although they
  353. # should have different names.
  354. from toontown.ai import ToonBarrier
  355. context = self.__nextBarrierContext
  356. # We assume the context number is passed as a uint16.
  357. self.__nextBarrierContext = (self.__nextBarrierContext + 1) & 0xffff
  358. assert(self.notify.debug('beginBarrier(%s, %s, %s, %s)' % (context, name, avIds, timeout)))
  359. if avIds:
  360. barrier = ToonBarrier.ToonBarrier(
  361. name, self.uniqueName(name), avIds, timeout,
  362. doneFunc = PythonUtil.Functor(self.__barrierCallback, context, callback))
  363. self.__barriers[context] = barrier
  364. # Send the context number to each involved client.
  365. self.sendUpdate("setBarrierData", [self.__getBarrierData()])
  366. else:
  367. # No avatars; just call the callback immediately.
  368. callback(avIds)
  369. return context
  370. def __getBarrierData(self):
  371. # Returns the barrier data formatted for sending to the
  372. # clients. This lists all of the current outstanding barriers
  373. # and the avIds waiting for them.
  374. data = []
  375. for context, barrier in self.__barriers.items():
  376. toons = barrier.pendingToons
  377. if toons:
  378. data.append((context, barrier.name, toons))
  379. return data
  380. def ignoreBarrier(self, context):
  381. # Aborts a previously-set barrier. The context is the return
  382. # value from the previous call to beginBarrier().
  383. barrier = self.__barriers.get(context)
  384. if barrier:
  385. barrier.cleanup()
  386. del self.__barriers[context]
  387. def setBarrierReady(self, context):
  388. # Generated by the clients to check in after a beginBarrier()
  389. # call.
  390. avId = self.air.GetAvatarIDFromSender()
  391. assert(self.notify.debug('setBarrierReady(%s, %s)' % (context, avId)))
  392. barrier = self.__barriers.get(context)
  393. if barrier == None:
  394. # This may be None if a client was slow and missed an
  395. # earlier timeout. Too bad.
  396. return
  397. barrier.clear(avId)
  398. def __barrierCallback(self, context, callback, avIds):
  399. assert(self.notify.debug('barrierCallback(%s, %s)' % (context, avIds)))
  400. # The callback that is generated when a barrier is completed.
  401. barrier = self.__barriers.get(context)
  402. if barrier:
  403. barrier.cleanup()
  404. del self.__barriers[context]
  405. callback(avIds)
  406. else:
  407. self.notify.warning("Unexpected completion from barrier %s" % (context))
  408. def isGridParent(self):
  409. # If this distributed object is a DistributedGrid return 1. 0 by default
  410. return 0