DistributedObjectAI.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570
  1. """DistributedObjectAI module: contains the DistributedObjectAI class"""
  2. from direct.directnotify.DirectNotifyGlobal import directNotify
  3. from direct.distributed.DistributedObjectBase import DistributedObjectBase
  4. from direct.showbase.MessengerGlobal import messenger
  5. from direct.showbase import PythonUtil
  6. from panda3d.core import *
  7. from panda3d.direct import *
  8. #from PyDatagram import PyDatagram
  9. #from PyDatagramIterator import PyDatagramIterator
  10. class DistributedObjectAI(DistributedObjectBase):
  11. notify = directNotify.newCategory("DistributedObjectAI")
  12. QuietZone = 1
  13. def __init__(self, air):
  14. if not hasattr(self, 'DistributedObjectAI_initialized'):
  15. self.DistributedObjectAI_initialized = 1
  16. DistributedObjectBase.__init__(self, air)
  17. self.accountName=''
  18. # Record the repository
  19. self.air = air
  20. # Record our distributed class
  21. className = self.__class__.__name__
  22. self.dclass = self.air.dclassesByName[className]
  23. # init doId pre-allocated flag
  24. self.__preallocDoId = 0
  25. # used to track zone changes across the quiet zone
  26. # NOTE: the quiet zone is defined in OTP, but we need it
  27. # here.
  28. self.lastNonQuietZone = None
  29. self._DOAI_requestedDelete = False
  30. # These are used to implement beginBarrier().
  31. self.__nextBarrierContext = 0
  32. self.__barriers = {}
  33. self.__generated = False
  34. # reference count for multiple inheritance
  35. self.__generates = 0
  36. self._zoneData = None
  37. # Uncomment if you want to debug DO leaks
  38. #def __del__(self):
  39. # """
  40. # For debugging purposes, this just prints out what got deleted
  41. # """
  42. # print ("Destructing: " + self.__class__.__name__)
  43. if __debug__:
  44. def status(self, indent=0):
  45. """
  46. print out doId(parentId, zoneId) className
  47. and conditionally show generated or deleted
  48. """
  49. spaces = ' ' * (indent + 2)
  50. try:
  51. print("%s%s:" % (' ' * indent, self.__class__.__name__))
  52. flags = []
  53. if self.__generated:
  54. flags.append("generated")
  55. if self.air is None:
  56. flags.append("deleted")
  57. flagStr = ""
  58. if len(flags) > 0:
  59. flagStr = " (%s)" % (" ".join(flags))
  60. print("%sfrom DistributedObject doId:%s, parent:%s, zone:%s%s" % (
  61. spaces, self.doId, self.parentId, self.zoneId, flagStr))
  62. except Exception as e:
  63. print("%serror printing status %s" % (spaces, e))
  64. def getDeleteEvent(self):
  65. # this is sent just before we get deleted
  66. if hasattr(self, 'doId'):
  67. return 'distObjDelete-%s' % self.doId
  68. return None
  69. def sendDeleteEvent(self):
  70. # this is called just before we get deleted
  71. delEvent = self.getDeleteEvent()
  72. if delEvent:
  73. messenger.send(delEvent)
  74. def getCacheable(self):
  75. """ This method exists only to mirror the similar method on
  76. DistributedObject. AI objects aren't cacheable. """
  77. return False
  78. def deleteOrDelay(self):
  79. """ This method exists only to mirror the similar method on
  80. DistributedObject. AI objects don't have delayDelete, they
  81. just get deleted immediately. """
  82. self.delete()
  83. def getDelayDeleteCount(self):
  84. return 0
  85. def delete(self):
  86. """
  87. Inheritors should redefine this to take appropriate action on delete
  88. Note that this may be called multiple times if a class inherits
  89. from DistributedObjectAI more than once.
  90. """
  91. self.__generates -= 1
  92. if self.__generates < 0:
  93. self.notify.debug('DistributedObjectAI: delete() called more times than generate()')
  94. if self.__generates == 0:
  95. # prevent this code from executing multiple times
  96. if self.air is not None:
  97. # self.doId may not exist. The __dict__ syntax works around that.
  98. assert self.notify.debug('delete(): %s' % (self.__dict__.get("doId")))
  99. #if not self._DOAI_requestedDelete:
  100. # # this logs every delete that was not requested by us.
  101. # # TODO: this currently prints warnings for deletes of objects
  102. # # that we did not create. We need to add a 'locally created'
  103. # # flag to every object to filter these out.
  104. #
  105. # DistributedObjectAI.notify.warning(
  106. # 'delete() called but requestDelete never called for %s: %s'
  107. # % (self.__dict__.get('doId'), self.__class__.__name__))
  108. #
  109. # # print a stack trace so we can detect whether this is the
  110. # # result of a network msg.
  111. # # this is slow.
  112. # from direct.showbase.PythonUtil import StackTrace
  113. # DistributedObjectAI.notify.warning(
  114. # 'stack trace: %s' % StackTrace())
  115. self._DOAI_requestedDelete = False
  116. self.releaseZoneData()
  117. # Clean up all the pending barriers.
  118. for barrier in self.__barriers.values():
  119. barrier.cleanup()
  120. self.__barriers = {}
  121. # DCR: I've re-enabled this block of code so that Toontown's
  122. # AI won't leak channels.
  123. # Let me know if it causes trouble.
  124. ### Asad: As per Roger's suggestion, turn off the following
  125. ### block until a solution is thought out of how to prevent
  126. ### this delete message or to handle this message better
  127. # TODO: do we still need this check?
  128. if not getattr(self, "doNotDeallocateChannel", False):
  129. if self.air:
  130. self.air.deallocateChannel(self.doId)
  131. self.air = None
  132. self.parentId = None
  133. self.zoneId = None
  134. self.__generated = False
  135. def isDeleted(self):
  136. """
  137. Returns true if the object has been deleted,
  138. or if it is brand new and hasnt yet been generated.
  139. """
  140. return self.air is None
  141. def isGenerated(self):
  142. """
  143. Returns true if the object has been generated
  144. """
  145. return self.__generated
  146. def getDoId(self):
  147. """
  148. Return the distributed object id
  149. """
  150. return self.doId
  151. def preAllocateDoId(self):
  152. """
  153. objects that need to have a doId before they are generated
  154. can call this to pre-allocate a doId for the object
  155. """
  156. assert not self.__preallocDoId
  157. self.doId = self.air.allocateChannel()
  158. self.__preallocDoId = 1
  159. def announceGenerate(self):
  160. """
  161. Called after the object has been generated and all
  162. of its required fields filled in. Overwrite when needed.
  163. """
  164. def b_setLocation(self, parentId, zoneId):
  165. self.d_setLocation(parentId, zoneId)
  166. self.setLocation(parentId, zoneId)
  167. def d_setLocation(self, parentId, zoneId):
  168. self.air.sendSetLocation(self, parentId, zoneId)
  169. def setLocation(self, parentId, zoneId):
  170. # Prevent Duplicate SetLocations for being Called
  171. if self.parentId == parentId and self.zoneId == zoneId:
  172. return
  173. oldParentId = self.parentId
  174. oldZoneId = self.zoneId
  175. self.air.storeObjectLocation(self, parentId, zoneId)
  176. if oldParentId != parentId or oldZoneId != zoneId:
  177. self.releaseZoneData()
  178. messenger.send(self.getZoneChangeEvent(), [zoneId, oldZoneId])
  179. # if we are not going into the quiet zone, send a 'logical' zone
  180. # change message
  181. if zoneId != DistributedObjectAI.QuietZone:
  182. lastLogicalZone = oldZoneId
  183. if oldZoneId == DistributedObjectAI.QuietZone:
  184. lastLogicalZone = self.lastNonQuietZone
  185. self.handleLogicalZoneChange(zoneId, lastLogicalZone)
  186. self.lastNonQuietZone = zoneId
  187. def getLocation(self):
  188. try:
  189. if self.parentId <= 0 and self.zoneId <= 0:
  190. return None
  191. # This is a -1 stuffed into a uint32
  192. if self.parentId == 0xffffffff and self.zoneId == 0xffffffff:
  193. return None
  194. return (self.parentId, self.zoneId)
  195. except AttributeError:
  196. return None
  197. def postGenerateMessage(self):
  198. self.__generated = True
  199. messenger.send(self.uniqueName("generate"), [self])
  200. def updateRequiredFields(self, dclass, di):
  201. dclass.receiveUpdateBroadcastRequired(self, di)
  202. self.announceGenerate()
  203. self.postGenerateMessage()
  204. def updateAllRequiredFields(self, dclass, di):
  205. dclass.receiveUpdateAllRequired(self, di)
  206. self.announceGenerate()
  207. self.postGenerateMessage()
  208. def updateRequiredOtherFields(self, dclass, di):
  209. dclass.receiveUpdateBroadcastRequired(self, di)
  210. # Announce generate after updating all the required fields,
  211. # but before we update the non-required fields.
  212. self.announceGenerate()
  213. self.postGenerateMessage()
  214. dclass.receiveUpdateOther(self, di)
  215. def updateAllRequiredOtherFields(self, dclass, di):
  216. dclass.receiveUpdateAllRequired(self, di)
  217. # Announce generate after updating all the required fields,
  218. # but before we update the non-required fields.
  219. self.announceGenerate()
  220. self.postGenerateMessage()
  221. dclass.receiveUpdateOther(self, di)
  222. def startMessageBundle(self, name):
  223. self.air.startMessageBundle(name)
  224. def sendMessageBundle(self):
  225. self.air.sendMessageBundle(self.doId)
  226. def getZoneChangeEvent(self):
  227. # this event is generated whenever this object changes zones.
  228. # arguments are newZoneId, oldZoneId
  229. # includes the quiet zone.
  230. return DistributedObjectAI.staticGetZoneChangeEvent(self.doId)
  231. def getLogicalZoneChangeEvent(self):
  232. # this event is generated whenever this object changes to a
  233. # non-quiet-zone zone.
  234. # arguments are newZoneId, oldZoneId
  235. # does not include the quiet zone.
  236. return DistributedObjectAI.staticGetLogicalZoneChangeEvent(self.doId)
  237. @staticmethod
  238. def staticGetZoneChangeEvent(doId):
  239. return 'DOChangeZone-%s' % doId
  240. @staticmethod
  241. def staticGetLogicalZoneChangeEvent(doId):
  242. return 'DOLogicalChangeZone-%s' % doId
  243. def handleLogicalZoneChange(self, newZoneId, oldZoneId):
  244. """this function gets called as if we never go through the
  245. quiet zone. Note that it is called once you reach the newZone,
  246. and not at the time that you leave the oldZone."""
  247. messenger.send(self.getLogicalZoneChangeEvent(),
  248. [newZoneId, oldZoneId])
  249. def getZoneData(self):
  250. # Call this to get an AIZoneData object for the current zone.
  251. # This class will hold onto it as self._zoneData
  252. # setLocation destroys self._zoneData if we move away to
  253. # a different zone
  254. if self._zoneData is None:
  255. from otp.ai.AIZoneData import AIZoneData
  256. self._zoneData = AIZoneData(self.air, self.parentId, self.zoneId)
  257. return self._zoneData
  258. def releaseZoneData(self):
  259. # You can call this to release any AIZoneData object that we might be
  260. # holding onto. If we're the last one for the current zone, the data
  261. # will be destroyed (render, collision traverser, etc.)
  262. # Note that the AIZoneData object that we're holding will be destroyed
  263. # automatically when we move away or are destroyed.
  264. if self._zoneData is not None:
  265. self._zoneData.destroy()
  266. self._zoneData = None
  267. def getRender(self):
  268. # note that this will return a different node if we change zones
  269. #return self.air.getRender(self.zoneId)
  270. return self.getZoneData().getRender()
  271. def getNonCollidableParent(self):
  272. return self.getZoneData().getNonCollidableParent()
  273. def getParentMgr(self):
  274. #return self.air.getParentMgr(self.zoneId)
  275. return self.getZoneData().getParentMgr()
  276. def getCollTrav(self, *args, **kArgs):
  277. return self.getZoneData().getCollTrav(*args, **kArgs)
  278. def sendUpdate(self, fieldName, args = []):
  279. assert self.notify.debugStateCall(self)
  280. if self.air:
  281. self.air.sendUpdate(self, fieldName, args)
  282. def GetPuppetConnectionChannel(self, doId):
  283. return doId + (1001 << 32)
  284. def GetAccountConnectionChannel(self, doId):
  285. return doId + (1003 << 32)
  286. def GetAccountIDFromChannelCode(self, channel):
  287. return channel >> 32
  288. def GetAvatarIDFromChannelCode(self, channel):
  289. return channel & 0xffffffff
  290. def sendUpdateToAvatarId(self, avId, fieldName, args):
  291. assert self.notify.debugStateCall(self)
  292. channelId = self.GetPuppetConnectionChannel(avId)
  293. self.sendUpdateToChannel(channelId, fieldName, args)
  294. def sendUpdateToAccountId(self, accountId, fieldName, args):
  295. assert self.notify.debugStateCall(self)
  296. channelId = self.GetAccountConnectionChannel(accountId)
  297. self.sendUpdateToChannel(channelId, fieldName, args)
  298. def sendUpdateToChannel(self, channelId, fieldName, args):
  299. assert self.notify.debugStateCall(self)
  300. if self.air:
  301. self.air.sendUpdateToChannel(self, channelId, fieldName, args)
  302. def generateWithRequired(self, zoneId, optionalFields=[]):
  303. assert self.notify.debugStateCall(self)
  304. # have we already allocated a doId?
  305. if self.__preallocDoId:
  306. self.__preallocDoId = 0
  307. return self.generateWithRequiredAndId(
  308. self.doId, zoneId, optionalFields)
  309. # The repository is the one that really does the work
  310. parentId = self.air.districtId
  311. self.air.generateWithRequired(self, parentId, zoneId, optionalFields)
  312. self.generate()
  313. self.announceGenerate()
  314. self.postGenerateMessage()
  315. # this is a special generate used for estates, or anything else that
  316. # needs to have a hard coded doId as assigned by the server
  317. def generateWithRequiredAndId(self, doId, parentId, zoneId, optionalFields=[]):
  318. assert self.notify.debugStateCall(self)
  319. # have we already allocated a doId?
  320. if self.__preallocDoId:
  321. assert doId == self.doId
  322. self.__preallocDoId = 0
  323. # The repository is the one that really does the work
  324. self.air.generateWithRequiredAndId(self, doId, parentId, zoneId, optionalFields)
  325. self.generate()
  326. self.announceGenerate()
  327. self.postGenerateMessage()
  328. def generateOtpObject(self, parentId, zoneId, optionalFields=[], doId=None):
  329. assert self.notify.debugStateCall(self)
  330. # have we already allocated a doId?
  331. if self.__preallocDoId:
  332. assert doId is None or doId == self.doId
  333. doId=self.doId
  334. self.__preallocDoId = 0
  335. # Assign it an id
  336. if doId is None:
  337. self.doId = self.air.allocateChannel()
  338. else:
  339. self.doId = doId
  340. # Put the new DO in the dictionaries
  341. self.air.addDOToTables(self, location=(parentId, zoneId))
  342. # Send a generate message
  343. self.sendGenerateWithRequired(self.air, parentId, zoneId, optionalFields)
  344. self.generate()
  345. self.announceGenerate()
  346. self.postGenerateMessage()
  347. def generate(self):
  348. """
  349. Inheritors should put functions that require self.zoneId or
  350. other networked info in this function.
  351. """
  352. assert self.notify.debugStateCall(self)
  353. self.__generates += 1
  354. def generateInit(self, repository=None):
  355. """
  356. First generate (not from cache).
  357. """
  358. assert self.notify.debugStateCall(self)
  359. def generateTargetChannel(self, repository):
  360. """
  361. Who to send this to for generate messages
  362. """
  363. if hasattr(self, "dbObject"):
  364. return self.doId
  365. return repository.serverId
  366. def sendGenerateWithRequired(self, repository, parentId, zoneId, optionalFields=[]):
  367. assert self.notify.debugStateCall(self)
  368. dg = self.dclass.aiFormatGenerate(
  369. self, self.doId, parentId, zoneId,
  370. #repository.serverId,
  371. self.generateTargetChannel(repository),
  372. repository.ourChannel,
  373. optionalFields)
  374. repository.send(dg)
  375. def initFromServerResponse(self, valDict):
  376. assert self.notify.debugStateCall(self)
  377. # This is a special method used for estates, etc., which get
  378. # their fields set from the database indirectly by way of the
  379. # AI. The input parameter is a dictionary of field names to
  380. # datagrams that describes the initial field values from the
  381. # database.
  382. dclass = self.dclass
  383. for key, value in valDict.items():
  384. # Update the field
  385. dclass.directUpdate(self, key, value)
  386. def requestDelete(self):
  387. assert self.notify.debugStateCall(self)
  388. if not self.air:
  389. doId = "none"
  390. if hasattr(self, "doId"):
  391. doId = self.doId
  392. self.notify.warning(
  393. "Tried to delete a %s (doId %s) that is already deleted" %
  394. (self.__class__, doId))
  395. return
  396. self.air.requestDelete(self)
  397. self._DOAI_requestedDelete = True
  398. def taskName(self, taskString):
  399. return "%s-%s" % (taskString, self.doId)
  400. def uniqueName(self, idString):
  401. return "%s-%s" % (idString, self.doId)
  402. def validate(self, avId, bool, msg):
  403. if not bool:
  404. self.air.writeServerEvent('suspicious', avId, msg)
  405. self.notify.warning('validate error: avId: %s -- %s' % (avId, msg))
  406. return bool
  407. def beginBarrier(self, name, avIds, timeout, callback):
  408. # Begins waiting for a set of avatars. When all avatars in
  409. # the list have reported back in or the callback has expired,
  410. # calls the indicated callback with the list of avatars that
  411. # made it through. There may be multiple barriers waiting
  412. # simultaneously on different lists of avatars, although they
  413. # should have different names.
  414. from otp.ai import Barrier
  415. context = self.__nextBarrierContext
  416. # We assume the context number is passed as a uint16.
  417. self.__nextBarrierContext = (self.__nextBarrierContext + 1) & 0xffff
  418. assert self.notify.debug('beginBarrier(%s, %s, %s, %s)' % (context, name, avIds, timeout))
  419. if avIds:
  420. barrier = Barrier.Barrier(
  421. name, self.uniqueName(name), avIds, timeout,
  422. doneFunc = PythonUtil.Functor(
  423. self.__barrierCallback, context, callback))
  424. self.__barriers[context] = barrier
  425. # Send the context number to each involved client.
  426. self.sendUpdate("setBarrierData", [self.getBarrierData()])
  427. else:
  428. # No avatars; just call the callback immediately.
  429. callback(avIds)
  430. return context
  431. def getBarrierData(self):
  432. # Returns the barrier data formatted for sending to the
  433. # clients. This lists all of the current outstanding barriers
  434. # and the avIds waiting for them.
  435. data = []
  436. for context, barrier in self.__barriers.items():
  437. avatars = barrier.pendingAvatars
  438. if avatars:
  439. data.append((context, barrier.name, avatars))
  440. return data
  441. def ignoreBarrier(self, context):
  442. # Aborts a previously-set barrier. The context is the return
  443. # value from the previous call to beginBarrier().
  444. barrier = self.__barriers.get(context)
  445. if barrier:
  446. barrier.cleanup()
  447. del self.__barriers[context]
  448. def setBarrierReady(self, context):
  449. # Generated by the clients to check in after a beginBarrier()
  450. # call.
  451. avId = self.air.getAvatarIdFromSender()
  452. assert self.notify.debug('setBarrierReady(%s, %s)' % (context, avId))
  453. barrier = self.__barriers.get(context)
  454. if barrier is None:
  455. # This may be None if a client was slow and missed an
  456. # earlier timeout. Too bad.
  457. return
  458. barrier.clear(avId)
  459. def __barrierCallback(self, context, callback, avIds):
  460. assert self.notify.debug('barrierCallback(%s, %s)' % (context, avIds))
  461. # The callback that is generated when a barrier is completed.
  462. barrier = self.__barriers.get(context)
  463. if barrier:
  464. barrier.cleanup()
  465. del self.__barriers[context]
  466. callback(avIds)
  467. else:
  468. self.notify.warning("Unexpected completion from barrier %s" % (context))
  469. def isGridParent(self):
  470. # If this distributed object is a DistributedGrid return 1. 0 by default
  471. return 0
  472. def execCommand(self, string, mwMgrId, avId, zoneId):
  473. pass
  474. def _retrieveCachedData(self):
  475. """ This is a no-op on the AI. """
  476. def setAI(self, aiChannel):
  477. self.air.setAI(self.doId, aiChannel)