ClientRepository.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. """ClientRepository module: contains the ClientRepository class"""
  2. from .ClientRepositoryBase import ClientRepositoryBase
  3. from direct.directnotify import DirectNotifyGlobal
  4. from direct.showbase.MessengerGlobal import messenger
  5. from .MsgTypesCMU import (
  6. CLIENT_DISCONNECT_CMU,
  7. CLIENT_HEARTBEAT_CMU,
  8. CLIENT_OBJECT_UPDATE_FIELD_TARGETED_CMU,
  9. CLIENT_SET_INTEREST_CMU,
  10. OBJECT_DELETE_CMU,
  11. OBJECT_DISABLE_CMU,
  12. OBJECT_GENERATE_CMU,
  13. OBJECT_SET_ZONE_CMU,
  14. OBJECT_UPDATE_FIELD_CMU,
  15. REQUEST_GENERATES_CMU,
  16. SET_DOID_RANGE_CMU,
  17. )
  18. from .PyDatagram import PyDatagram
  19. from .PyDatagramIterator import PyDatagramIterator
  20. from panda3d.core import UniqueIdAllocator, Notify, ClockObject
  21. class ClientRepository(ClientRepositoryBase):
  22. """
  23. This is the open-source ClientRepository as provided by CMU. It
  24. communicates with the ServerRepository in this same directory.
  25. If you are looking for the VR Studio's implementation of the
  26. client repository, look to OTPClientRepository (elsewhere).
  27. """
  28. notify = DirectNotifyGlobal.directNotify.newCategory("ClientRepository")
  29. # This is required by DoCollectionManager, even though it's not
  30. # used by this implementation.
  31. GameGlobalsId = 0
  32. doNotDeallocateChannel = True
  33. def __init__(self, dcFileNames = None, dcSuffix = '', connectMethod = None,
  34. threadedNet = None):
  35. ClientRepositoryBase.__init__(self, dcFileNames = dcFileNames, dcSuffix = dcSuffix, connectMethod = connectMethod, threadedNet = threadedNet)
  36. self.setHandleDatagramsInternally(False)
  37. base.finalExitCallbacks.append(self.shutdown)
  38. # The doId allocator. The CMU LAN server may choose to
  39. # send us a block of doIds. If it chooses to do so, then we
  40. # may create objects, using those doIds.
  41. self.doIdAllocator = None
  42. self.doIdBase = 0
  43. self.doIdLast = 0
  44. # The doIdBase of the client message currently being
  45. # processed.
  46. self.currentSenderId = None
  47. # Explicitly-requested interest zones.
  48. self.interestZones = []
  49. def handleSetDoIdrange(self, di):
  50. self.doIdBase = di.getUint32()
  51. self.doIdLast = self.doIdBase + di.getUint32()
  52. self.doIdAllocator = UniqueIdAllocator(self.doIdBase, self.doIdLast - 1)
  53. self.ourChannel = self.doIdBase
  54. self.createReady()
  55. def createReady(self):
  56. # Now that we've got a doId range, we can safely generate new
  57. # distributed objects.
  58. messenger.send('createReady', taskChain = 'default')
  59. messenger.send(self.uniqueName('createReady'), taskChain = 'default')
  60. def handleRequestGenerates(self, di):
  61. # When new clients join the zone of an object, they need to hear
  62. # about it, so we send out all of our information about objects in
  63. # that particular zone.
  64. zone = di.getUint32()
  65. for obj in self.doId2do.values():
  66. if obj.zoneId == zone:
  67. if self.isLocalId(obj.doId):
  68. self.resendGenerate(obj)
  69. def resendGenerate(self, obj):
  70. """ Sends the generate message again for an already-generated
  71. object, presumably to inform any newly-arrived clients of this
  72. object's current state. """
  73. # get the list of "ram" fields that aren't
  74. # required. These are fields whose values should
  75. # persist even if they haven't been received
  76. # lately, so we have to re-broadcast these values
  77. # in case the new client hasn't heard their latest
  78. # values.
  79. extraFields = []
  80. for i in range(obj.dclass.getNumInheritedFields()):
  81. field = obj.dclass.getInheritedField(i)
  82. if field.hasKeyword('broadcast') and field.hasKeyword('ram') and not field.hasKeyword('required'):
  83. if field.asMolecularField():
  84. # It's a molecular field; this means
  85. # we have to pack the components.
  86. # Fortunately, we'll find those
  87. # separately through the iteration, so
  88. # we can ignore this field itself.
  89. continue
  90. extraFields.append(field.getName())
  91. datagram = self.formatGenerate(obj, extraFields)
  92. self.send(datagram)
  93. def handleGenerate(self, di):
  94. self.currentSenderId = di.getUint32()
  95. zoneId = di.getUint32()
  96. classId = di.getUint16()
  97. doId = di.getUint32()
  98. # Look up the dclass
  99. dclass = self.dclassesByNumber[classId]
  100. distObj = self.doId2do.get(doId)
  101. if distObj and distObj.dclass == dclass:
  102. # We've already got this object. Probably this is just a
  103. # repeat-generate, synthesized for the benefit of someone
  104. # else who just entered the zone. Accept the new updates,
  105. # but don't make a formal generate.
  106. assert self.notify.debug("performing generate-update for %s %s" % (dclass.getName(), doId))
  107. dclass.receiveUpdateBroadcastRequired(distObj, di)
  108. dclass.receiveUpdateOther(distObj, di)
  109. return
  110. assert self.notify.debug("performing generate for %s %s" % (dclass.getName(), doId))
  111. dclass.startGenerate()
  112. # Create a new distributed object, and put it in the dictionary
  113. distObj = self.generateWithRequiredOtherFields(dclass, doId, di, 0, zoneId)
  114. dclass.stopGenerate()
  115. def allocateDoId(self):
  116. """ Returns a newly-allocated doId. Call freeDoId() when the
  117. object has been deleted. """
  118. return self.doIdAllocator.allocate()
  119. def reserveDoId(self, doId):
  120. """ Removes the indicate doId from the available pool, as if
  121. it had been explicitly allocated. You may pass it to
  122. freeDoId() later if you wish. """
  123. self.doIdAllocator.initialReserveId(doId)
  124. return doId
  125. def freeDoId(self, doId):
  126. """ Returns a doId back into the free pool for re-use. """
  127. assert self.isLocalId(doId)
  128. self.doIdAllocator.free(doId)
  129. def storeObjectLocation(self, object, parentId, zoneId):
  130. # The CMU implementation doesn't use the DoCollectionManager
  131. # much.
  132. object.parentId = parentId
  133. object.zoneId = zoneId
  134. def createDistributedObject(self, className = None, distObj = None,
  135. zoneId = 0, optionalFields = None,
  136. doId = None, reserveDoId = False):
  137. """ To create a DistributedObject, you must pass in either the
  138. name of the object's class, or an already-created instance of
  139. the class (or both). If you pass in just a class name (to the
  140. className parameter), then a default instance of the object
  141. will be created, with whatever parameters the default
  142. constructor supplies. Alternatively, if you wish to create
  143. some initial values different from the default, you can create
  144. the instance yourself and supply it to the distObj parameter,
  145. then that instance will be used instead. (It should be a
  146. newly-created object, not one that has already been manifested
  147. on the network or previously passed through
  148. createDistributedObject.) In either case, the new
  149. DistributedObject is returned from this method.
  150. This method will issue the appropriate network commands to
  151. make this object appear on all of the other clients.
  152. You should supply an initial zoneId in which to manifest the
  153. object. The fields marked "required" or "ram" will be
  154. broadcast to all of the other clients; if you wish to
  155. broadcast additional field values at this time as well, pass a
  156. list of field names in the optionalFields parameters.
  157. Normally, doId is None, to mean allocate a new doId for the
  158. object. If you wish to use a particular doId, pass it in
  159. here. If you also pass reserveDoId = True, this doId will be
  160. reserved from the allocation pool using self.reserveDoId().
  161. You are responsible for ensuring this doId falls within the
  162. client's allowable doId range and has not already been
  163. assigned to another object. """
  164. if not className:
  165. if not distObj:
  166. self.notify.error("Must specify either a className or a distObj.")
  167. className = distObj.__class__.__name__
  168. if doId is None:
  169. doId = self.allocateDoId()
  170. elif reserveDoId:
  171. self.reserveDoId(doId)
  172. dclass = self.dclassesByName.get(className)
  173. if not dclass:
  174. self.notify.error("Unknown distributed class: %s" % (distObj.__class__))
  175. classDef = dclass.getClassDef()
  176. if classDef is None:
  177. self.notify.error("Could not create an undefined %s object." % (
  178. dclass.getName()))
  179. if not distObj:
  180. distObj = classDef(self)
  181. if not isinstance(distObj, classDef):
  182. self.notify.error("Object %s is not an instance of %s" % (distObj.__class__.__name__, classDef.__name__))
  183. distObj.dclass = dclass
  184. distObj.doId = doId
  185. self.doId2do[doId] = distObj
  186. distObj.generateInit()
  187. distObj._retrieveCachedData()
  188. distObj.generate()
  189. distObj.setLocation(0, zoneId)
  190. distObj.announceGenerate()
  191. datagram = self.formatGenerate(distObj, optionalFields)
  192. self.send(datagram)
  193. return distObj
  194. def formatGenerate(self, distObj, extraFields):
  195. """ Returns a datagram formatted for sending the generate message for the indicated object. """
  196. return distObj.dclass.clientFormatGenerateCMU(distObj, distObj.doId, distObj.zoneId, extraFields)
  197. def sendDeleteMsg(self, doId):
  198. datagram = PyDatagram()
  199. datagram.addUint16(OBJECT_DELETE_CMU)
  200. datagram.addUint32(doId)
  201. self.send(datagram)
  202. def sendDisconnect(self):
  203. if self.isConnected():
  204. # Tell the game server that we're going:
  205. datagram = PyDatagram()
  206. # Add message type
  207. datagram.addUint16(CLIENT_DISCONNECT_CMU)
  208. # Send the message
  209. self.send(datagram)
  210. self.notify.info("Sent disconnect message to server")
  211. self.disconnect()
  212. self.stopHeartbeat()
  213. def setInterestZones(self, interestZoneIds):
  214. """ Changes the set of zones that this particular client is
  215. interested in hearing about. """
  216. datagram = PyDatagram()
  217. # Add message type
  218. datagram.addUint16(CLIENT_SET_INTEREST_CMU)
  219. for zoneId in interestZoneIds:
  220. datagram.addUint32(zoneId)
  221. # send the message
  222. self.send(datagram)
  223. self.interestZones = interestZoneIds[:]
  224. def setObjectZone(self, distObj, zoneId):
  225. """ Moves the object into the indicated zone. """
  226. distObj.b_setLocation(0, zoneId)
  227. assert distObj.zoneId == zoneId
  228. # Tell all of the clients monitoring the new zone that we've
  229. # arrived.
  230. self.resendGenerate(distObj)
  231. def sendSetLocation(self, doId, parentId, zoneId):
  232. datagram = PyDatagram()
  233. datagram.addUint16(OBJECT_SET_ZONE_CMU)
  234. datagram.addUint32(doId)
  235. datagram.addUint32(zoneId)
  236. self.send(datagram)
  237. def sendHeartbeat(self):
  238. datagram = PyDatagram()
  239. # Add message type
  240. datagram.addUint16(CLIENT_HEARTBEAT_CMU)
  241. # Send it!
  242. self.send(datagram)
  243. self.lastHeartbeat = ClockObject.getGlobalClock().getRealTime()
  244. # This is important enough to consider flushing immediately
  245. # (particularly if we haven't run readerPollTask recently).
  246. self.considerFlush()
  247. def isLocalId(self, doId):
  248. """ Returns true if this doId is one that we're the owner of,
  249. false otherwise. """
  250. return doId >= self.doIdBase and doId < self.doIdLast
  251. def haveCreateAuthority(self):
  252. """ Returns true if this client has been assigned a range of
  253. doId's it may use to create objects, false otherwise. """
  254. return self.doIdLast > self.doIdBase
  255. def getAvatarIdFromSender(self):
  256. """ Returns the doIdBase of the client that originally sent
  257. the current update message. This is only defined when
  258. processing an update message or a generate message. """
  259. return self.currentSenderId
  260. def handleDatagram(self, di):
  261. if self.notify.getDebug():
  262. print("ClientRepository received datagram:")
  263. di.getDatagram().dumpHex(Notify.out())
  264. msgType = self.getMsgType()
  265. self.currentSenderId = None
  266. # These are the sort of messages we may expect from the public
  267. # Panda server.
  268. if msgType == SET_DOID_RANGE_CMU:
  269. self.handleSetDoIdrange(di)
  270. elif msgType == OBJECT_GENERATE_CMU:
  271. self.handleGenerate(di)
  272. elif msgType == OBJECT_UPDATE_FIELD_CMU:
  273. self.handleUpdateField(di)
  274. elif msgType == OBJECT_DISABLE_CMU:
  275. self.handleDisable(di)
  276. elif msgType == OBJECT_DELETE_CMU:
  277. self.handleDelete(di)
  278. elif msgType == REQUEST_GENERATES_CMU:
  279. self.handleRequestGenerates(di)
  280. else:
  281. self.handleMessageType(msgType, di)
  282. # If we're processing a lot of datagrams within one frame, we
  283. # may forget to send heartbeats. Keep them coming!
  284. self.considerHeartbeat()
  285. def handleMessageType(self, msgType, di):
  286. self.notify.error("unrecognized message type %s" % (msgType))
  287. def handleUpdateField(self, di):
  288. # The CMU update message starts with an additional field, not
  289. # present in the Disney update message: the doIdBase of the
  290. # original sender. Extract that and call up to the parent.
  291. self.currentSenderId = di.getUint32()
  292. ClientRepositoryBase.handleUpdateField(self, di)
  293. def handleDisable(self, di):
  294. # Receives a list of doIds.
  295. while di.getRemainingSize() > 0:
  296. doId = di.getUint32()
  297. # We should never get a disable message for our own object.
  298. assert not self.isLocalId(doId)
  299. self.disableDoId(doId)
  300. def handleDelete(self, di):
  301. # Receives a single doId.
  302. doId = di.getUint32()
  303. self.deleteObject(doId)
  304. def deleteObject(self, doId):
  305. """
  306. Removes the object from the client's view of the world. This
  307. should normally not be called directly except in the case of
  308. error recovery, since the server will normally be responsible
  309. for deleting and disabling objects as they go out of scope.
  310. After this is called, future updates by server on this object
  311. will be ignored (with a warning message). The object will
  312. become valid again the next time the server sends a generate
  313. message for this doId.
  314. This is not a distributed message and does not delete the
  315. object on the server or on any other client.
  316. """
  317. if doId in self.doId2do:
  318. # If it is in the dictionary, remove it.
  319. obj = self.doId2do[doId]
  320. # Remove it from the dictionary
  321. del self.doId2do[doId]
  322. # Disable, announce, and delete the object itself...
  323. # unless delayDelete is on...
  324. obj.deleteOrDelay()
  325. if self.isLocalId(doId):
  326. self.freeDoId(doId)
  327. elif self.cache.contains(doId):
  328. # If it is in the cache, remove it.
  329. self.cache.delete(doId)
  330. if self.isLocalId(doId):
  331. self.freeDoId(doId)
  332. else:
  333. # Otherwise, ignore it
  334. self.notify.warning(
  335. "Asked to delete non-existent DistObj " + str(doId))
  336. def stopTrackRequestDeletedDO(self, *args):
  337. # No-op. Not entirely sure what this does on the VR Studio side.
  338. pass
  339. def sendUpdate(self, distObj, fieldName, args):
  340. """ Sends a normal update for a single field. """
  341. dg = distObj.dclass.clientFormatUpdate(
  342. fieldName, distObj.doId, args)
  343. self.send(dg)
  344. def sendUpdateToChannel(self, distObj, channelId, fieldName, args):
  345. """ Sends a targeted update of a single field to a particular
  346. client. The top 32 bits of channelId is ignored; the lower 32
  347. bits should be the client Id of the recipient (i.e. the
  348. client's doIdbase). The field update will be sent to the
  349. indicated client only. The field must be marked clsend or
  350. p2p, and may not be marked broadcast. """
  351. datagram = distObj.dclass.clientFormatUpdate(
  352. fieldName, distObj.doId, args)
  353. dgi = PyDatagramIterator(datagram)
  354. # Reformat the packed datagram to change the message type and
  355. # add the target id.
  356. dgi.getUint16()
  357. dg = PyDatagram()
  358. dg.addUint16(CLIENT_OBJECT_UPDATE_FIELD_TARGETED_CMU)
  359. dg.addUint32(channelId & 0xffffffff)
  360. dg.appendData(dgi.getRemainingBytes())
  361. self.send(dg)