DistributedObjectAI.py 20 KB

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