DistributedObjectUD.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  1. """DistributedObjectUD module: contains the DistributedObjectUD 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 DistributedObjectUD(DistributedObjectBase):
  9. notify = directNotify.newCategory("DistributedObjectUD")
  10. QuietZone = 1
  11. def __init__(self, air):
  12. try:
  13. self.DistributedObjectUD_initialized
  14. except:
  15. self.DistributedObjectUD_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._DOUD_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:" % (' ' * indent, self.__class__.__name__)
  50. print ("%sfrom "
  51. "DistributedObject doId:%s, parent:%s, zone:%s" %
  52. (spaces, self.doId, self.parentId, self.zoneId)),
  53. flags = []
  54. if self.__generated:
  55. flags.append("generated")
  56. if self.air == None:
  57. flags.append("deleted")
  58. if len(flags):
  59. print "(%s)" % (" ".join(flags),),
  60. print
  61. except Exception, e: print "%serror printing status" % (spaces,), e
  62. def getDeleteEvent(self):
  63. # this is sent just before we get deleted
  64. if hasattr(self, 'doId'):
  65. return 'distObjDelete-%s' % self.doId
  66. return None
  67. def sendDeleteEvent(self):
  68. # this is called just before we get deleted
  69. delEvent = self.getDeleteEvent()
  70. if delEvent:
  71. messenger.send(delEvent)
  72. def delete(self):
  73. """
  74. Inheritors should redefine this to take appropriate action on delete
  75. Note that this may be called multiple times if a class inherits
  76. from DistributedObjectUD more than once.
  77. """
  78. # prevent this code from executing multiple times
  79. if self.air is not None:
  80. # self.doId may not exist. The __dict__ syntax works around that.
  81. assert self.notify.debug('delete(): %s' % (self.__dict__.get("doId")))
  82. if not self._DOUD_requestedDelete:
  83. # this logs every delete that was not requested by us.
  84. # TODO: this currently prints warnings for deletes of objects
  85. # that we did not create. We need to add a 'locally created'
  86. # flag to every object to filter these out.
  87. """
  88. DistributedObjectUD.notify.warning(
  89. 'delete() called but requestDelete never called for %s: %s'
  90. % (self.__dict__.get('doId'), self.__class__.__name__))
  91. """
  92. """
  93. # print a stack trace so we can detect whether this is the
  94. # result of a network msg.
  95. # this is slow.
  96. from direct.showbase.PythonUtil import StackTrace
  97. DistributedObjectUD.notify.warning(
  98. 'stack trace: %s' % StackTrace())
  99. """
  100. self._DOUD_requestedDelete = False
  101. # Clean up all the pending barriers.
  102. for barrier in self.__barriers.values():
  103. barrier.cleanup()
  104. self.__barriers = {}
  105. # Asad: As per Roger's suggestion, turn off the following block until a solution is
  106. # Thought out of how to prevent this delete message or to handle this message better
  107. ## if not hasattr(self, "doNotDeallocateChannel"):
  108. ## if self.air:
  109. ## self.air.deallocateChannel(self.doId)
  110. ## self.air = None
  111. if hasattr(self, 'parentId'):
  112. del self.parentId
  113. if hasattr(self, 'zoneId'):
  114. del self.zoneId
  115. self.__generated = False
  116. def isDeleted(self):
  117. """
  118. Returns true if the object has been deleted,
  119. or if it is brand new and hasnt yet been generated.
  120. """
  121. return self.air == None
  122. def isGenerated(self):
  123. """
  124. Returns true if the object has been generated
  125. """
  126. return self.__generated
  127. def getDoId(self):
  128. """
  129. Return the distributed object id
  130. """
  131. return self.doId
  132. def preAllocateDoId(self):
  133. """
  134. objects that need to have a doId before they are generated
  135. can call this to pre-allocate a doId for the object
  136. """
  137. assert not self.__preallocDoId
  138. self.doId = self.air.allocateChannel()
  139. self.__preallocDoId = 1
  140. def announceGenerate(self):
  141. """
  142. Called after the object has been generated and all
  143. of its required fields filled in. Overwrite when needed.
  144. """
  145. self.__generated = True
  146. def postGenerateMessage(self):
  147. messenger.send(self.uniqueName("generate"), [self])
  148. def addInterest(self, zoneId, note="", event=None):
  149. self.air.addInterest(self.getDoId(), zoneId, note, event)
  150. def b_setLocation(self, parentId, zoneId):
  151. self.d_setLocation(parentId, zoneId)
  152. self.setLocation(parentId, zoneId)
  153. def d_setLocation(self, parentId, zoneId):
  154. self.air.sendSetLocation(self, parentId, zoneId)
  155. def setLocation(self, parentId, zoneId):
  156. self.air.storeObjectLocation(self, parentId, zoneId)
  157. def getLocation(self):
  158. try:
  159. if self.parentId <= 0 and self.zoneId <= 0:
  160. return None
  161. # This is a -1 stuffed into a uint32
  162. if self.parentId == 0xffffffff and self.zoneId == 0xffffffff:
  163. return None
  164. return (self.parentId, self.zoneId)
  165. except AttributeError:
  166. return None
  167. def updateRequiredFields(self, dclass, di):
  168. dclass.receiveUpdateBroadcastRequired(self, di)
  169. self.announceGenerate()
  170. self.postGenerateMessage()
  171. def updateAllRequiredFields(self, dclass, di):
  172. dclass.receiveUpdateAllRequired(self, di)
  173. self.announceGenerate()
  174. self.postGenerateMessage()
  175. def updateRequiredOtherFields(self, dclass, di):
  176. dclass.receiveUpdateBroadcastRequired(self, di)
  177. # Announce generate after updating all the required fields,
  178. # but before we update the non-required fields.
  179. self.announceGenerate()
  180. self.postGenerateMessage()
  181. dclass.receiveUpdateOther(self, di)
  182. def updateAllRequiredOtherFields(self, dclass, di):
  183. dclass.receiveUpdateAllRequired(self, di)
  184. # Announce generate after updating all the required fields,
  185. # but before we update the non-required fields.
  186. self.announceGenerate()
  187. self.postGenerateMessage()
  188. dclass.receiveUpdateOther(self, di)
  189. def sendSetZone(self, zoneId):
  190. self.air.sendSetZone(self, zoneId)
  191. def getZoneChangeEvent(self):
  192. # this event is generated whenever this object changes zones.
  193. # arguments are newZoneId, oldZoneId
  194. # includes the quiet zone.
  195. return 'DOChangeZone-%s' % self.doId
  196. def getLogicalZoneChangeEvent(self):
  197. # this event is generated whenever this object changes to a
  198. # non-quiet-zone zone.
  199. # arguments are newZoneId, oldZoneId
  200. # does not include the quiet zone.
  201. return 'DOLogicalChangeZone-%s' % self.doId
  202. def handleLogicalZoneChange(self, newZoneId, oldZoneId):
  203. """this function gets called as if we never go through the
  204. quiet zone. Note that it is called once you reach the newZone,
  205. and not at the time that you leave the oldZone."""
  206. messenger.send(self.getLogicalZoneChangeEvent(),
  207. [newZoneId, oldZoneId])
  208. def getRender(self):
  209. # note that this will return a different node if we change zones
  210. return self.air.getRender(self.zoneId)
  211. def getNonCollidableParent(self):
  212. return self.air.getNonCollidableParent(self.zoneId)
  213. def getParentMgr(self):
  214. return self.air.getParentMgr(self.zoneId)
  215. def getCollTrav(self):
  216. return self.air.getCollTrav(self.zoneId)
  217. def sendUpdate(self, fieldName, args = []):
  218. assert self.notify.debugStateCall(self)
  219. if self.air:
  220. self.air.sendUpdate(self, fieldName, args)
  221. def GetPuppetConnectionChannel(self, doId):
  222. return doId + (1L << 32)
  223. def GetAccountConnectionChannel(self, doId):
  224. return doId + (3L << 32)
  225. def GetAccountIDFromChannelCode(self, channel):
  226. return channel >> 32
  227. def GetAvatarIDFromChannelCode(self, channel):
  228. return channel & 0xffffffffL
  229. def sendUpdateToAvatarId(self, avId, fieldName, args):
  230. assert self.notify.debugStateCall(self)
  231. channelId = self.GetPuppetConnectionChannel(avId)
  232. self.sendUpdateToChannel(channelId, fieldName, args)
  233. def sendUpdateToAccountId(self, accountId, fieldName, args):
  234. assert self.notify.debugStateCall(self)
  235. channelId = self.GetAccountConnectionChannel(accountId)
  236. self.sendUpdateToChannel(channelId, fieldName, args)
  237. def sendUpdateToChannel(self, channelId, fieldName, args):
  238. assert self.notify.debugStateCall(self)
  239. if self.air:
  240. self.air.sendUpdateToChannel(self, channelId, fieldName, args)
  241. def generateWithRequired(self, zoneId, optionalFields=[]):
  242. assert self.notify.debugStateCall(self)
  243. # have we already allocated a doId?
  244. if self.__preallocDoId:
  245. self.__preallocDoId = 0
  246. return self.generateWithRequiredAndId(self.doId, zoneId,
  247. optionalFields)
  248. # The repository is the one that really does the work
  249. parentId = self.air.districtId
  250. self.parentId = parentId
  251. self.zoneId = zoneId
  252. self.air.generateWithRequired(self, parentId, zoneId, optionalFields)
  253. self.generate()
  254. # this is a special generate used for estates, or anything else that
  255. # needs to have a hard coded doId as assigned by the server
  256. def generateWithRequiredAndId(self, doId, parentId, zoneId, optionalFields=[]):
  257. assert self.notify.debugStateCall(self)
  258. # have we already allocated a doId?
  259. if self.__preallocDoId:
  260. assert doId == self.__preallocDoId
  261. self.__preallocDoId = 0
  262. # The repository is the one that really does the work
  263. self.air.generateWithRequiredAndId(self, doId, parentId, zoneId, optionalFields)
  264. ## self.parentId = parentId
  265. ## self.zoneId = zoneId
  266. self.generate()
  267. self.announceGenerate()
  268. self.postGenerateMessage()
  269. def generateOtpObject(self, parentId, zoneId, optionalFields=[], doId=None):
  270. assert self.notify.debugStateCall(self)
  271. # have we already allocated a doId?
  272. if self.__preallocDoId:
  273. assert doId is None or doId == self.__preallocDoId
  274. doId = self.__preallocDoId
  275. self.__preallocDoId = 0
  276. # Assign it an id
  277. if doId is None:
  278. self.doId = self.air.allocateChannel()
  279. else:
  280. self.doId = doId
  281. # Put the new DO in the dictionaries
  282. self.air.addDOToTables(self, location = (parentId, zoneId))
  283. # Send a generate message
  284. self.sendGenerateWithRequired(self.air, parentId, zoneId, optionalFields)
  285. ## assert not hasattr(self, 'parentId') or self.parentId is None
  286. ## self.parentId = parentId
  287. ## self.zoneId = zoneId
  288. self.generate()
  289. def generate(self):
  290. """
  291. Inheritors should put functions that require self.zoneId or
  292. other networked info in this function.
  293. """
  294. assert self.notify.debugStateCall(self)
  295. self.air.storeObjectLocation(self, self.parentId, self.zoneId)
  296. def generateInit(self, repository=None):
  297. """
  298. First generate (not from cache).
  299. """
  300. assert self.notify.debugStateCall(self)
  301. def generateTargetChannel(self, repository):
  302. """
  303. Who to send this to for generate messages
  304. """
  305. if hasattr(self, "dbObject"):
  306. return self.doId
  307. return repository.serverId
  308. def sendGenerateWithRequired(self, repository, parentId, zoneId, optionalFields=[]):
  309. assert self.notify.debugStateCall(self)
  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. # UD. 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._DOUD_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 otp.ai import Barrier
  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 = Barrier.Barrier(
  361. name, self.uniqueName(name), avIds, timeout,
  362. doneFunc = PythonUtil.Functor(
  363. self.__barrierCallback, context, callback))
  364. self.__barriers[context] = barrier
  365. # Send the context number to each involved client.
  366. self.sendUpdate("setBarrierData", [self.__getBarrierData()])
  367. else:
  368. # No avatars; just call the callback immediately.
  369. callback(avIds)
  370. return context
  371. def __getBarrierData(self):
  372. # Returns the barrier data formatted for sending to the
  373. # clients. This lists all of the current outstanding barriers
  374. # and the avIds waiting for them.
  375. data = []
  376. for context, barrier in self.__barriers.items():
  377. toons = barrier.pendingToons
  378. if toons:
  379. data.append((context, barrier.name, toons))
  380. return data
  381. def ignoreBarrier(self, context):
  382. # Aborts a previously-set barrier. The context is the return
  383. # value from the previous call to beginBarrier().
  384. barrier = self.__barriers.get(context)
  385. if barrier:
  386. barrier.cleanup()
  387. del self.__barriers[context]
  388. def setBarrierReady(self, context):
  389. # Generated by the clients to check in after a beginBarrier()
  390. # call.
  391. avId = self.air.getAvatarIdFromSender()
  392. assert self.notify.debug('setBarrierReady(%s, %s)' % (context, avId))
  393. barrier = self.__barriers.get(context)
  394. if barrier == None:
  395. # This may be None if a client was slow and missed an
  396. # earlier timeout. Too bad.
  397. return
  398. barrier.clear(avId)
  399. def __barrierCallback(self, context, callback, avIds):
  400. assert self.notify.debug('barrierCallback(%s, %s)' % (context, avIds))
  401. # The callback that is generated when a barrier is completed.
  402. barrier = self.__barriers.get(context)
  403. if barrier:
  404. barrier.cleanup()
  405. del self.__barriers[context]
  406. callback(avIds)
  407. else:
  408. self.notify.warning("Unexpected completion from barrier %s" % (context))
  409. def isGridParent(self):
  410. # If this distributed object is a DistributedGrid return 1. 0 by default
  411. return 0