コード例 #1
0
ファイル: test_loader.py プロジェクト: loblao/libpandadna
    def test_loader_ai(self):
        store = DNAStorage()
        root = self.loader.loadDNAFileAI(store, Filename('test.pdna'))

        self.check_store(store)

        def check_name_class_and_children_count(comp, klass, name, num_children=1):
            self.assertEqual(comp.getName(), name)
            self.assertEqual(comp.__class__, klass)
            self.assertEqual(comp.getNumChildren(), num_children)

        check_name_class_and_children_count(root, DNAGroup, "root")

        test_group = root.at(0)
        check_name_class_and_children_count(test_group, DNAGroup, "test")

        test_visgroup = test_group.at(0)
        self.assertEqual(store.getDNAVisGroupAI(0), test_visgroup)
        check_name_class_and_children_count(test_visgroup, DNAVisGroup, "1000")

        test_subgroup = test_visgroup.at(0)
        check_name_class_and_children_count(test_subgroup, DNAGroup, "subgroup",
                                            num_children=2)

        test_prop = test_subgroup.at(0)
        check_name_class_and_children_count(test_prop, DNAProp, "prop_test",
                                            num_children=0)

        test_building = test_subgroup.at(1)
        check_name_class_and_children_count(test_building, DNALandmarkBuilding,
                                            "tb3:test_block", num_children=0)
コード例 #2
0
    def enter(self, requestStatus):
        CogHQExterior.CogHQExterior.enter(self, requestStatus)

        for train in self.trains:
            train.show()

        # Load the CogHQ DNA file:
        dnaStore = DNAStorage()
        dnaFileName = self.genDNAFileName(self.zoneId)
        loadDNAFileAI(dnaStore, dnaFileName)

        # Collect all of the vis group zone IDs:
        self.zoneVisDict = {}
        for i in range(dnaStore.getNumDNAVisGroupsAI()):
            groupFullName = dnaStore.getDNAVisGroupName(i)
            visGroup = dnaStore.getDNAVisGroupAI(i)
            visZoneId = int(base.cr.hoodMgr.extractGroupName(groupFullName))
            visZoneId = ZoneUtil.getTrueZoneId(visZoneId, self.zoneId)
            visibles = []
            for i in range(visGroup.getNumVisibles()):
                visibles.append(int(visGroup.getVisible(i)))
            visibles.append(ZoneUtil.getBranchZone(visZoneId))
            self.zoneVisDict[visZoneId] = visibles

        # Next, we want interest in all vis groups due to this being a Cog HQ:
        base.cr.sendSetZoneMsg(self.zoneId, list(self.zoneVisDict.values())[0])
コード例 #3
0
 def setupDNA(self):
     if self.dnaStore:
         return None
     self.dnaStore = DNAStorage()
     dnaFileName = self.genDNAFileName()
     loadDNAFileAI(self.dnaStore, dnaFileName)
     self.initDNAInfo()
コード例 #4
0
 def loadDnaStore(self):
     if not hasattr(self, 'dnaStore'):
         self.dnaStore = DNAStorage()
         files = ('phase_4/dna/storage.dna',
                  'phase_3.5/dna/storage_interior.dna')
         dnaBulk = DNABulkLoader(self.dnaStore, files)
         dnaBulk.loadDNAFiles()
         self.dnaStore.storeFont('humanist',
                                 ToontownGlobals.getInterfaceFont())
         self.dnaStore.storeFont('mickey', ToontownGlobals.getSignFont())
         self.dnaStore.storeFont('suit', ToontownGlobals.getSuitFont())
コード例 #5
0
    def __test_loader(self, filename, use_loader_class):
        store = DNAStorage()

        if use_loader_class:
            np = self.loader.loadDNAFile(store, filename)
            expected_repr = '''PandaNode dna
  PandaNode test
    PandaNode 1000
      PandaNode subgroup
        ModelNode prop_test T:(pos -12 5 7 hpr 180 15 0) S:(ColorScaleAttrib)
        PandaNode tb3:test_block [DNACode]
        PandaNode sb3:test_block'''

        else:
            np = NodePath(loadDNAFile(store, filename))
            expected_repr = '''PandaNode test
  PandaNode 1000
    PandaNode subgroup
      ModelNode prop_test T:(pos -12 5 7 hpr 180 15 0) S:(ColorScaleAttrib)
      PandaNode tb3:test_block [DNACode]
      PandaNode sb3:test_block'''

        self.check_store(store)

        ss = StringStream()
        np.ls(ss)

        self.assertEqual(ss.getData().strip(), expected_repr)
コード例 #6
0
    def test_load_invalid_file(self):
        store = DNAStorage()
        root = self.loader.loadDNAFile(store, Filename('invalid.pdna'))
        self.assertTrue(root.isEmpty())

        root = self.loader.loadDNAFileAI(store, Filename('invalid.pdna'))
        self.assertTrue(root is None)
コード例 #7
0
ファイル: test_storage.py プロジェクト: loblao/libpandadna
    def test_storage_catalog(self):
        store = DNAStorage()
        store.storeCatalogCode('root', 'code1')
        store.storeCatalogCode('root', 'code2')
        store.storeCatalogCode('root', 'code3')

        colors = ('red', 'green', 'blue', 'yellow', 'orange')
        for color in colors:
            store.storeCatalogCode('colors', color)

        self.assertEqual(store.getNumCatalogCodes('colors'), len(colors))

        for i, color in enumerate(colors):
            self.assertEqual(store.getCatalogCode('colors', i), color)

        # 'bad' root must have no codes
        self.assertEqual(store.getNumCatalogCodes('bad'), 0)
コード例 #8
0
    def test_texture(self):
        store = DNAStorage()
        texture1 = loader.loadTexture('files/texture1.png')
        texture2 = loader.loadTexture('files/texture2.png')

        store.storeTexture('texture1', texture1)
        store.storeTexture('texture2', texture2)
        self.assertEqual(store.findTexture('texture1'), texture1)
        self.assertEqual(store.findTexture('texture2'), texture2)
        self.assertEqual(store.findTexture('bad'), None)

        store.resetTextures()

        self.assertEqual(store.findTexture('texture1'), None)
        self.assertEqual(store.findTexture('texture2'), None)
コード例 #9
0
    def test_font(self):
        store = DNAStorage()
        font1 = loader.loadFont('files/arial.ttf')
        font2 = loader.loadFont('files/comic.ttf')

        store.storeFont('font1', font1)
        store.storeFont('font2', font2)
        self.assertEqual(store.findFont('font1'), font1)
        self.assertEqual(store.findFont('font2'), font2)
        self.assertEqual(store.findFont('bad'), None)

        store.resetFonts()

        self.assertEqual(store.findFont('font1'), None)
        self.assertEqual(store.findFont('font2'), None)
コード例 #10
0
    def enter(self, requestStatus):
        self.zoneId = requestStatus['zoneId']

        # Load the CogHQ DNA file:
        dnaStore = DNAStorage()
        dnaFileName = self.genDNAFileName(self.zoneId)

        if not dnaFileName.endswith('13200.dna'):

            loadDNAFileAI(dnaStore, dnaFileName)

            # Collect all of the vis group zone IDs:
            self.zoneVisDict = {}
            for i in range(dnaStore.getNumDNAVisGroupsAI()):
                groupFullName = dnaStore.getDNAVisGroupName(i)
                visGroup = dnaStore.getDNAVisGroupAI(i)
                visZoneId = int(base.cr.hoodMgr.extractGroupName(groupFullName))
                visZoneId = ZoneUtil.getTrueZoneId(visZoneId, self.zoneId)
                visibles = []
                for i in range(visGroup.getNumVisibles()):
                    visibles.append(int(visGroup.getVisible(i)))
                visibles.append(ZoneUtil.getBranchZone(visZoneId))
                self.zoneVisDict[visZoneId] = visibles

            # Next, we want interest in all vis groups due to this being a Cog HQ:
            base.cr.sendSetZoneMsg(self.zoneId, list(self.zoneVisDict.values())[0])

        BattlePlace.BattlePlace.enter(self)
        self.fsm.enterInitialState()
        base.playMusic(self.loader.music, looping=1, volume=0.8)
        self.loader.geom.reparentTo(render)
        self.nodeList = [self.loader.geom]
        self.loader.hood.startSky()
        self._telemLimiter = TLGatherAllAvs('FactoryExterior', RotationLimitToH)
        self.accept('doorDoneEvent', self.handleDoorDoneEvent)
        self.accept('DistributedDoor_doorTrigger', self.handleDoorTrigger)
        NametagGlobals.setWant2dNametags(True)
        self.tunnelOriginList = base.cr.hoodMgr.addLinkTunnelHooks(self, self.nodeList, self.zoneId)
        how = requestStatus['how']
        self.fsm.request(how, [requestStatus])
コード例 #11
0
    def test_loader_ai(self):
        store = DNAStorage()
        root = self.loader.loadDNAFileAI(store, Filename('test.pdna'))

        self.check_store(store)

        def check_name_class_and_children_count(comp,
                                                klass,
                                                name,
                                                num_children=1):
            self.assertEqual(comp.getName(), name)
            self.assertEqual(comp.__class__, klass)
            self.assertEqual(comp.getNumChildren(), num_children)

        check_name_class_and_children_count(root, DNAGroup, "root")

        test_group = root.at(0)
        check_name_class_and_children_count(test_group, DNAGroup, "test")

        test_visgroup = test_group.at(0)
        self.assertEqual(store.getDNAVisGroupAI(0), test_visgroup)
        check_name_class_and_children_count(test_visgroup, DNAVisGroup, "1000")

        test_subgroup = test_visgroup.at(0)
        check_name_class_and_children_count(test_subgroup,
                                            DNAGroup,
                                            "subgroup",
                                            num_children=2)

        test_prop = test_subgroup.at(0)
        check_name_class_and_children_count(test_prop,
                                            DNAProp,
                                            "prop_test",
                                            num_children=0)

        test_building = test_subgroup.at(1)
        check_name_class_and_children_count(test_building,
                                            DNALandmarkBuilding,
                                            "tb3:test_block",
                                            num_children=0)
コード例 #12
0
    def getDnaStore(self, zoneId):
        if zoneId in self.__dnaMap:
            return self.__dnaMap[zoneId]

        x = DNAStorage.DNAStorage()
        filename = self.genDNAFileName(zoneId)

        print 'Loading dna file', self.genDNAFileName(zoneId)
        self.loadDNAFileAI(x, filename)

        self.__dnaMap[zoneId] = x

        return x
コード例 #13
0
ファイル: test_storage.py プロジェクト: loblao/libpandadna
    def test_font(self):
        store = DNAStorage()
        font1 = loader.loadFont('files/arial.ttf')
        font2 = loader.loadFont('files/comic.ttf')

        store.storeFont('font1', font1)
        store.storeFont('font2', font2)
        self.assertEqual(store.findFont('font1'), font1)
        self.assertEqual(store.findFont('font2'), font2)
        self.assertEqual(store.findFont('bad'), None)

        store.resetFonts()

        self.assertEqual(store.findFont('font1'), None)
        self.assertEqual(store.findFont('font2'), None)
コード例 #14
0
ファイル: test_storage.py プロジェクト: loblao/libpandadna
    def test_texture(self):
        store = DNAStorage()
        texture1 = loader.loadTexture('files/texture1.png')
        texture2 = loader.loadTexture('files/texture2.png')

        store.storeTexture('texture1', texture1)
        store.storeTexture('texture2', texture2)
        self.assertEqual(store.findTexture('texture1'), texture1)
        self.assertEqual(store.findTexture('texture2'), texture2)
        self.assertEqual(store.findTexture('bad'), None)

        store.resetTextures()

        self.assertEqual(store.findTexture('texture1'), None)
        self.assertEqual(store.findTexture('texture2'), None)
コード例 #15
0
    def test_loader(self):
        store = DNAStorage()
        np = self.loader.loadDNAFile(store, Filename('test.pdna'))

        self.check_store(store)

        expected_repr = '''PandaNode dna
  PandaNode root
    PandaNode test
      PandaNode 1000
        PandaNode subgroup
          ModelNode prop_test T:(pos -12 5 7 hpr 180 15 0) S:(ColorScaleAttrib)
          PandaNode tb3:test_block [DNACode]
          PandaNode sb3:test_block'''
        ss = StringStream()
        np.ls(ss)
        self.assertEqual(ss.getData().strip(), expected_repr)
コード例 #16
0
    def __init__(self, air, zoneId, canonicalHoodId):
        self.air = air
        self.zoneId = zoneId
        self.canonicalHoodId = canonicalHoodId

        self.fishingPonds = []
        self.partyGates = []
        self.treasurePlanner = None
        self.buildingManagers = []
        self.suitPlanners = []

        for zoneId in self.getZoneTable():
            self.notify.info('Creating objects... ' +
                             self.getLocationName(zoneId))
            dnaFileName = self.air.lookupDNAFileName(zoneId)
            dnaStore = DNAStorage()
            dnaData = simbase.air.loadDNAFileAI(dnaStore, dnaFileName)
            self.air.dnaStoreMap[zoneId] = dnaStore
            self.air.dnaDataMap[zoneId] = dnaData
コード例 #17
0
    def initialize(self):
        # Get DNA file appropriate to this house...
        dnaFile = houseInteriors[self.houseIndex]

        # Load DNA...
        dnaStorage = DNAStorage()
        dnaData = loadDNAFileAI(dnaStorage, dnaFile)

        # Read it into furniture...
        furnitureReader = DNAFurnitureReaderAI(dnaData, [-11, 2, 0, 0, 0, 0])

        # Set furniture:
        self.furnitureManager.setItems(furnitureReader.getBlob())

        # Set default windows and wallpaper:
        del self.furnitureManager.windows[:]
        self.furnitureManager.windows.extend(defaultWindows)
        self.furnitureManager.applyWindows()
        del self.furnitureManager.wallpaper[:]
        self.furnitureManager.wallpaper.extend(defaultWallpaper)
        self.furnitureManager.applyWallpaper()

        # Save:
        self.furnitureManager.saveToHouse()
コード例 #18
0
 def loadDnaStoreTutorial(self):
     self.dnaStore = DNAStorage()
     files = ('phase_3.5/dna/storage_tutorial.dna',
              'phase_3.5/dna/storage_interior.dna')
     dnaBulk = DNABulkLoader(self.dnaStore, files)
     dnaBulk.loadDNAFiles()
コード例 #19
0
import sys
from panda3d.core import *

loadPrcFileData('', 'want-directtools #t')

import direct.directbase.DirectStart

sys.path.append('../../..')
getModelPath().appendDirectory('../..')

mode = "7100"
if len(sys.argv) > 1:
    mode = sys.argv[1]

from libpandadna import DNAStorage, DNALoader
s = DNAStorage.DNAStorage()
ld = DNALoader.DNALoader()


def load(x):
    return ld.loadDNAFile(s, x)


load('../../phase_4/dna/storage.pdna')
load('../../phase_5/dna/storage_town.pdna')
load('storage_FF.pdna')
load('storage_FF_%s.pdna' % ("sz" if mode == "sz" else "town"))
m = load('funny_farm_%s.pdna' % mode)
dnaEnviron = render.attachNewNode('dna_render')
m.reparentTo(dnaEnviron)
base.disableMouse()
コード例 #20
0
ファイル: test_storage.py プロジェクト: loblao/libpandadna
    def test_storage_visgroups(self):
        store = DNAStorage()
        vg = DNAVisGroup("my_vg")

        vg.addVisible("visible1")
        vg.addVisible("visible2")
        vg.addVisible("visible3")

        store.storeDNAVisGroup(vg)
        self.assertEqual(store.getNumDNAVisGroups(), 1)
        self.assertEqual(store.getNumDNAVisGroupsAI(), 1)
        self.assertEqual(store.getDNAVisGroupAI(0), vg)
        self.assertEqual(store.getDNAVisGroupName(0), vg.getName())

        num_visibles = store.getNumVisiblesInDNAVisGroup(0)
        self.assertEqual(num_visibles, 3)

        for i in xrange(num_visibles):
            self.assertEqual(store.getVisibleName(0, i), "visible%d" % (i + 1))

        vg.removeVisible("visible2")
        self.assertEqual(store.getNumVisiblesInDNAVisGroup(0), 2)
        self.assertEqual(store.getVisibleName(0, 0), "visible1")
        self.assertEqual(store.getVisibleName(0, 1), "visible3")

        store.resetDNAVisGroups()
        self.assertEqual(store.getNumDNAVisGroups(), 0)
        self.assertEqual(store.getNumDNAVisGroupsAI(), 0)
 def setUpClass(cls):
     cls.store = DNAStorage()
     cls.defaultColor = Vec4(1)
コード例 #22
0
ファイル: test_storage.py プロジェクト: loblao/libpandadna
    def test_suit_points(self):
        store = DNAStorage()

        point1 = DNASuitPoint(5, DNASuitPoint.STREET_POINT,
                              Point3(100, 20, 0.5))
        point2 = DNASuitPoint(10, DNASuitPoint.STREET_POINT,
                              Point3(100, 0, 0.5))
        point3 = DNASuitPoint(15, DNASuitPoint.FRONT_DOOR_POINT,
                              Point3(100, -20, 0.5), 10)

        store.storeSuitPoint(point1)
        store.storeSuitPoint(point2)
        store.storeSuitPoint(point3)

        self.assertEqual(store.getNumSuitPoints(), 3)
        self.assertEqual(store.getSuitPointAtIndex(0), point1)
        self.assertEqual(store.getSuitPointAtIndex(1), point2)
        self.assertEqual(store.getSuitPointAtIndex(2), point3)
        self.assertEqual(store.getSuitPointWithIndex(5), point1)
        self.assertEqual(store.getSuitPointWithIndex(10), point2)
        self.assertEqual(store.getSuitPointWithIndex(15), point3)

        # Test invalid index
        self.assertEqual(store.getSuitPointWithIndex(1000), None)

        # Test suit edges
        edges = ((5, 10, 2301), (10, 15, 2302), (15, 5, 2303))

        for edge in edges:
            store.storeSuitEdge(*edge)

        for edge in edges:
            dna_edge = store.getSuitEdge(edge[0], edge[1])
            self.assertTrue(dna_edge is not None)
            self.assertEqual(dna_edge.getStartPoint(), store.getSuitPointWithIndex(edge[0]))
            self.assertEqual(dna_edge.getEndPoint(), store.getSuitPointWithIndex(edge[1]))
            self.assertEqual(dna_edge.getZoneId(), edge[2])
            self.assertEqual(store.getSuitEdgeZone(edge[0], edge[1]), edge[2])

        adj_points = store.getAdjacentPoints(point1)
        self.assertEqual(adj_points.getNumPoints(), 1)
        self.assertEqual(adj_points.getPoint(0), point2)
        self.assertEqual(store.getSuitEdgeTravelTime(5, 10, 5), 4)
        self.assertEqual(store.getSuitEdgeTravelTime(10, 15, 5), 4)
        self.assertEqual(store.getSuitEdgeTravelTime(15, 5, 5), 8)

        # Test suit path
        path = store.getSuitPath(point1, point3, 1, 10)
        self.assertEqual(path.getNumPoints(), 3)
        self.assertEqual(path.getPoint(0), point1)
        self.assertEqual(path.getPoint(1), point2)
        self.assertEqual(path.getPoint(2), point3)

        # Test invalid values
        store.storeSuitEdge(1, 2, 2800)
        self.assertEqual(store.getSuitEdge(1, 2), None)
        self.assertEqual(store.getSuitEdge(145, 13442), None)
        self.assertEqual(store.getSuitEdgeTravelTime(1, 2, 5), 0)
        self.assertEqual(repr(store.getSuitEdgeTravelTime(10, 15, 0)), 'inf')  # Division by 0

        point4 = DNASuitPoint(400, DNASuitPoint.STREET_POINT, Point3(0, 0, 0))
        self.assertEqual(store.getSuitPath(point4, point2, 1, 10), None)

        # Reset
        store.resetSuitPoints()
        self.assertEqual(store.getSuitPointWithIndex(5), None)
        self.assertEqual(store.getSuitPointWithIndex(10), None)
        self.assertEqual(store.getSuitPointWithIndex(15), None)
        self.assertTrue(store.discoverContinuity())
コード例 #23
0
    def test_nodes(self):
        store = DNAStorage()
        store.storeNode('files/node.bam', 'dummy', 'node')
        store.storeHoodNode('files/hood_node.bam', 'dummy', 'hood_node')
        store.storePlaceNode('files/place_node.bam', 'dummy', 'place_node')

        self.assertTrue(store.findNode('bad').isEmpty())
        self.assertFalse(store.findNode('node').isEmpty())
        self.assertFalse(store.findNode('hood_node').isEmpty())
        self.assertFalse(store.findNode('place_node').isEmpty())

        store.resetNodes()
        self.assertTrue(store.findNode('node').isEmpty())

        store.resetHoodNodes()
        self.assertTrue(store.findNode('hood_node').isEmpty())

        store.resetPlaceNodes()
        self.assertTrue(store.findNode('place_node').isEmpty())
コード例 #24
0
    def test_storage_catalog(self):
        store = DNAStorage()
        store.storeCatalogCode('root', 'code1')
        store.storeCatalogCode('root', 'code2')
        store.storeCatalogCode('root', 'code3')

        colors = ('red', 'green', 'blue', 'yellow', 'orange')
        for color in colors:
            store.storeCatalogCode('colors', color)

        self.assertEqual(store.getNumCatalogCodes('colors'), len(colors))

        for i, color in enumerate(colors):
            self.assertEqual(store.getCatalogCode('colors', i), color)

        # 'bad' root must have no codes
        self.assertEqual(store.getNumCatalogCodes('bad'), 0)
コード例 #25
0
ファイル: test_storage.py プロジェクト: loblao/libpandadna
    def test_nodes(self):
        store = DNAStorage()
        store.storeNode('files/node.bam', 'dummy', 'node')
        store.storeHoodNode('files/hood_node.bam', 'dummy', 'hood_node')
        store.storePlaceNode('files/place_node.bam', 'dummy', 'place_node')

        self.assertTrue(store.findNode('bad').isEmpty())
        self.assertFalse(store.findNode('node').isEmpty())
        self.assertFalse(store.findNode('hood_node').isEmpty())
        self.assertFalse(store.findNode('place_node').isEmpty())

        store.resetNodes()
        self.assertTrue(store.findNode('node').isEmpty())

        store.resetHoodNodes()
        self.assertTrue(store.findNode('hood_node').isEmpty())

        store.resetPlaceNodes()
        self.assertTrue(store.findNode('place_node').isEmpty())
コード例 #26
0
ファイル: test_suit.py プロジェクト: nate97/libpandadna
 def setUpClass(cls):
     cls.store = DNAStorage()
コード例 #27
0
    def test_suit_points(self):
        store = DNAStorage()

        point1 = DNASuitPoint(5, DNASuitPoint.STREET_POINT,
                              Point3(100, 20, 0.5))
        point2 = DNASuitPoint(10, DNASuitPoint.STREET_POINT,
                              Point3(100, 0, 0.5))
        point3 = DNASuitPoint(15, DNASuitPoint.FRONT_DOOR_POINT,
                              Point3(100, -20, 0.5), 10)

        store.storeSuitPoint(point1)
        store.storeSuitPoint(point2)
        store.storeSuitPoint(point3)

        self.assertEqual(store.getNumSuitPoints(), 3)
        self.assertEqual(store.getSuitPointAtIndex(0), point1)
        self.assertEqual(store.getSuitPointAtIndex(1), point2)
        self.assertEqual(store.getSuitPointAtIndex(2), point3)
        self.assertEqual(store.getSuitPointWithIndex(5), point1)
        self.assertEqual(store.getSuitPointWithIndex(10), point2)
        self.assertEqual(store.getSuitPointWithIndex(15), point3)

        # Test invalid index
        self.assertEqual(store.getSuitPointWithIndex(1000), None)

        # Test suit edges
        edges = ((5, 10, 2301), (10, 15, 2302), (15, 5, 2303))

        for edge in edges:
            store.storeSuitEdge(*edge)

        for edge in edges:
            dna_edge = store.getSuitEdge(edge[0], edge[1])
            self.assertTrue(dna_edge is not None)
            self.assertEqual(dna_edge.getStartPoint(),
                             store.getSuitPointWithIndex(edge[0]))
            self.assertEqual(dna_edge.getEndPoint(),
                             store.getSuitPointWithIndex(edge[1]))
            self.assertEqual(dna_edge.getZoneId(), edge[2])
            self.assertEqual(store.getSuitEdgeZone(edge[0], edge[1]), edge[2])

        adj_points = store.getAdjacentPoints(point1)
        self.assertEqual(adj_points.getNumPoints(), 1)
        self.assertEqual(adj_points.getPoint(0), point2)
        self.assertEqual(store.getSuitEdgeTravelTime(5, 10, 5), 4)
        self.assertEqual(store.getSuitEdgeTravelTime(10, 15, 5), 4)
        self.assertEqual(store.getSuitEdgeTravelTime(15, 5, 5), 8)

        # Test suit path
        path = store.getSuitPath(point1, point3, 1, 10)
        self.assertEqual(path.getNumPoints(), 3)
        self.assertEqual(path.getPoint(0), point1)
        self.assertEqual(path.getPoint(1), point2)
        self.assertEqual(path.getPoint(2), point3)

        # Test invalid values
        store.storeSuitEdge(1, 2, 2800)
        self.assertEqual(store.getSuitEdge(1, 2), None)
        self.assertEqual(store.getSuitEdge(145, 13442), None)
        self.assertEqual(store.getSuitEdgeTravelTime(1, 2, 5), 0)
        self.assertEqual(repr(store.getSuitEdgeTravelTime(10, 15, 0)),
                         'inf')  # Division by 0

        point4 = DNASuitPoint(400, DNASuitPoint.STREET_POINT, Point3(0, 0, 0))
        self.assertEqual(store.getSuitPath(point4, point2, 1, 10), None)

        # Reset
        store.resetSuitPoints()
        self.assertEqual(store.getSuitPointWithIndex(5), None)
        self.assertEqual(store.getSuitPointWithIndex(10), None)
        self.assertEqual(store.getSuitPointWithIndex(15), None)
        self.assertTrue(store.discoverContinuity())
コード例 #28
0
    def test_storage_visgroups(self):
        store = DNAStorage()
        vg = DNAVisGroup("my_vg")

        vg.addVisible("visible1")
        vg.addVisible("visible2")
        vg.addVisible("visible3")

        store.storeDNAVisGroup(vg)
        self.assertEqual(store.getNumDNAVisGroups(), 1)
        self.assertEqual(store.getNumDNAVisGroupsAI(), 1)
        self.assertEqual(store.getDNAVisGroupAI(0), vg)
        self.assertEqual(store.getDNAVisGroupName(0), vg.getName())

        num_visibles = store.getNumVisiblesInDNAVisGroup(0)
        self.assertEqual(num_visibles, 3)

        for i in xrange(num_visibles):
            self.assertEqual(store.getVisibleName(0, i), "visible%d" % (i + 1))

        vg.removeVisible("visible2")
        self.assertEqual(store.getNumVisiblesInDNAVisGroup(0), 2)
        self.assertEqual(store.getVisibleName(0, 0), "visible1")
        self.assertEqual(store.getVisibleName(0, 1), "visible3")

        store.resetDNAVisGroups()
        self.assertEqual(store.getNumDNAVisGroups(), 0)
        self.assertEqual(store.getNumDNAVisGroupsAI(), 0)
コード例 #29
0
ファイル: test_storage.py プロジェクト: loblao/libpandadna
    def test_blocks(self):
        store = DNAStorage()
        block1 = (
                  4269,                   # block_number
                  "libpandadna",          # title
                  "",                     # article
                  "",                     # bldg_type
                  1337                    # zone_id
        )
        block2 = (
                  1337,                   # block_number
                  "Visual Studio 2010",   # title
                  "",                     # article
                  "",                     # bldg_type
                  4269                    # zone_id
        )
        block3 = (
                  1000,                   # block_number
                  "C++ reader",           # title
                  "",                     # article
                  "",                     # bldg_type
                  4269                    # zone_id
        )

        store.storeBlock(*block1)
        store.storeBlock(*block2)
        store.storeBlock(*block3)

        door1 = NodePath('block-1000')
        door1.setPos(5, 5, 10)
        door1.setH(180)
        store.storeBlockDoor(1000, door1)

        self.assertEqual(store.getNumBlockNumbers(), 3)

        # Test an invalid block number
        self.assertEqual(store.getZoneFromBlockNumber(100), 0)
        self.assertEqual(store.getZoneFromBlockNumber(1000), 4269)
        self.assertEqual(store.getZoneFromBlockNumber(1337), 4269)
        self.assertEqual(store.getZoneFromBlockNumber(4269), 1337)
        self.assertEqual(store.getTitleFromBlockNumber(1000), "C++ reader")
        self.assertEqual(store.getTitleFromBlockNumber(1337), "Visual Studio 2010")
        self.assertEqual(store.getTitleFromBlockNumber(4269), "libpandadna")
        self.assertEqual(store.getBlockNumberAt(0), 4269)
        self.assertEqual(store.getBlockNumberAt(1), 1337)
        self.assertEqual(store.getBlockNumberAt(2), 1000)
        self.assertEqual(store.getDoorPosHprFromBlockNumber(1000), door1)
        self.assertTrue(store.getDoorPosHprFromBlockNumber(1337).isEmpty())

        store.resetBlockNumbers()
        store.resetBlockZones()

        self.assertEqual(store.getTitleFromBlockNumber(1000), "")
        self.assertEqual(store.getTitleFromBlockNumber(1337), "")
        self.assertEqual(store.getTitleFromBlockNumber(4269), "")
コード例 #30
0
 def setup(self):
     self.dnaStore = base.cr.playGame.dnaStore
     self.randomGenerator = random.Random()
     self.randomGenerator.seed(self.zoneId)
     self.interior = loader.loadModel(
         'phase_3.5/models/modules/toon_interior_tutorial')
     self.interior.reparentTo(render)
     dnaStore = DNAStorage()
     node = loader.loadDNAFile(self.cr.playGame.hood.dnaStore,
                               'phase_3.5/dna/tutorial_street.dna')
     self.street = render.attachNewNode(node)
     self.street.flattenMedium()
     self.street.setPosHpr(-17, 42, -0.5, 180, 0, 0)
     self.street.find('**/tb2:toon_landmark_TT_A1_DNARoot').stash()
     self.street.find(
         '**/tb1:toon_landmark_hqTT_DNARoot/**/door_flat_0').stash()
     self.street.findAllMatches('**/+CollisionNode').stash()
     self.skyFile = 'phase_3.5/models/props/TT_sky'
     self.sky = loader.loadModel(self.skyFile)
     self.sky.setScale(0.8)
     self.sky.reparentTo(render)
     self.sky.setDepthTest(0)
     self.sky.setDepthWrite(0)
     self.sky.setBin('background', 100)
     self.sky.find('**/Sky').reparentTo(self.sky, -1)
     hoodId = ZoneUtil.getCanonicalHoodId(self.zoneId)
     self.colors = ToonInteriorColors.colors[hoodId]
     self.replaceRandomInModel(self.interior)
     doorModelName = 'door_double_round_ul'
     if doorModelName[-1:] == 'r':
         doorModelName = doorModelName[:-1] + 'l'
     else:
         doorModelName = doorModelName[:-1] + 'r'
     door = self.dnaStore.findNode(doorModelName)
     door_origin = render.find('**/door_origin;+s')
     doorNP = door.copyTo(door_origin)
     door_origin.setScale(0.8, 0.8, 0.8)
     door_origin.setPos(door_origin, 0, -0.025, 0)
     color = self.randomGenerator.choice(self.colors['TI_door'])
     DNADoor.setupDoor(doorNP, self.interior, door_origin, self.dnaStore,
                       str(self.block), color)
     doorFrame = doorNP.find('door_*_flat')
     doorFrame.wrtReparentTo(self.interior)
     doorFrame.setColor(color)
     del self.colors
     del self.dnaStore
     del self.randomGenerator
     self.interior.flattenMedium()
     npcOrigin = self.interior.find('**/npc_origin_' + repr(
         (self.cr.doId2do[self.npcId].posIndex)))
     if not npcOrigin.isEmpty():
         self.cr.doId2do[self.npcId].reparentTo(npcOrigin)
         self.cr.doId2do[self.npcId].clearMat()
     self.createSuit()
     base.localAvatar.setPosHpr(-2, 12, 0, -10, 0, 0)
     base.localAvatar.startPosHprBroadcast()
     base.localAvatar.b_setParent(ToontownGlobals.SPRender)
     self.cr.doId2do[self.npcId].setChatAbsolute(
         TTLocalizer.QuestScriptTutorialMickey_4, CFSpeech)
     place = base.cr.playGame.getPlace()
     if place and hasattr(place,
                          'fsm') and place.fsm.getCurrentState().getName():
         self.notify.info('Tutorial movie: Place ready.')
         self.playMovie()
     else:
         self.notify.info(
             'Tutorial movie: Waiting for place=%s, has fsm=%s' %
             (place, hasattr(place, 'fsm')))
         if hasattr(place, 'fsm'):
             self.notify.info('Tutorial movie: place state=%s' %
                              place.fsm.getCurrentState().getName())
         self.acceptOnce('enterTutorialInterior', self.playMovie)
コード例 #31
0
class SuitPlannerBase:
    notify = directNotify.newCategory('SuitPlannerBase')
    SuitHoodInfo = [[2100,               ##This is the Street name Sily Street
      5,                                 ##
      15,                                ##
      0,                                 ##
      5,                                 ##
      20,                                ##
      3,                                 ##
      (1,                                ##
       5,                                ##
       10,                               ##
       40,                               ##
       60,                               ##
       80),                              ##
      (20,                               ##This is the chance a Bossbot spawns
       20,                               ## Lawbot Spawn
       20,                               ##Cashbot
       20,                               ## Sellbot
       20),                              ## Secbot
      (1, 2, 3),                         ## These are the cog levels
      []],
     [2200,                              ##Loopy Lane
      3,
      10,
      0,
      5,
      15,
      3,
      (1,
       5,
       10,
       40,
       60,
       80),
      (10,
       60,
       10,
       10,
       10),
      (1, 2, 3),
      []],
     [2300,
      3,
      10,
      0,
      5,
      15,
      3,
      (1,
       5,
       10,
       40,
       60,
       80),
      (12,
       12,
       23,
       23,
       30),
      (1, 2, 3),
      []],
     [1100,
      1,
      5,
      0,
      99,
      100,
      4,
      (1,
       5,
       10,
       40,
       60,
       80),
      (80,
       10,
       0,
       0,
       10),
      (2, 3, 4),
      []],
     [1200,
      1,
      5,
      0,
      99,
      100,
      4,
      (1,
       5,
       10,
       40,
       60,
       80),
      (5,
       5,
       75,
       10,
       5),
      (3,
       4,
       5,
       6),
      []],
     [1300,
      1,
      5,
      0,
      99,
      100,
      4,
      (1,
       5,
       10,
       40,
       60,
       80),
      (30,
       30,
       12,
       12,
       16),
      (3,
       4,
       5,
       6),
      []],
     [3100,
      1,
      5,
      0,
      99,
      100,
      4,
      (1,
       5,
       10,
       40,
       60,
       80),
      (70,
       10,
       5,
       10,
       5),
      (5, 6, 7),
      []],
     [3200,
      1,
      5,
      0,
      99,
      100,
      4,
      (1,
       5,
       10,
       40,
       60,
       80),
      (10,
       20,
       20,
       25,
       25),
      (5, 6, 7, 8),
      []],
     [3300,
      1,
      5,
      0,
      99,
      100,
      4,
      (1,
       5,
       10,
       40,
       60,
       80),
      (5,
       80,
       5,
       5,
       5),
      (7, 8, 9),
      []],
     [4100,
      1,
      5,
      0,
      99,
      100,
      4,
      (1,
       5,
       10,
       40,
       60,
       80),
      (5,
       5,
       40,
       45,
       5),
      (2, 3, 4, 5),
      []],
     [4200,
      1,
      5,
      0,
      99,
      100,
      4,
      (1,
       5,
       10,
       40,
       60,
       80),
      (0,
       5,
       80,
       10,
       5),
      (3,
       4,
       5,
       6),
      []],
     [4300,
      1,
      5,
      0,
      99,
      100,
      4,
      (1,
       5,
       10,
       40,
       60,
       80),
      (35,
       35,
       10,
       10,
       10),
      (3,
       4,
       5,
       6),
      []],
     [5100,
      1,
      5,
      0,
      99,
      100,
      4,
      (1,
       5,
       10,
       40,
       60,
       80),
      (0,
       15,
       10,
       65,
       10),
      (2, 3, 4),
      []],
     [5200,
      1,
      5,
      0,
      99,
      100,
      4,
      (1,
       5,
       10,
       40,
       60,
       80),
      (7,
       45,
       0,
       13,
       35),
      (3,
       4,
       5,
       6),
      []],
     [5300,
      1,
      5,
      0,
      99,
      100,
      4,
      (1,
       5,
       10,
       40,
       60,
       80),
      (5,
       5,
       5,
       80,
       5),
      (3,
       4,
       5,
       6),
      []],
     [9100,
      1,
      5,
      0,
      99,
      100,
      4,
      (1,
       5,
       10,
       40,
       60,
       80),
      (20,
       20,
       20,
       20,
       20),
      (6,
       7,
       8,
       9),
      []],
     [9200,
      1,
      5,
      0,
      99,
      100,
      4,
      (1,
       5,
       10,
       40,
       60,
       80),
      (5,
       5,
       80,
       5,
       10),
      (6,
       7,
       8,
       9,
       10),
      []],
     [10000,
      3,
      15,
      0,
      5,
      15,
      3,
      (1,
       5,
       10,
       40,
       60,
       80),
      (100,
       0,
       0,
       0),
      (7, 8, 9, 10),
      []],
     [11000,
      3,
      15,
      0,
      0,
      0,
      4,
      (1,
       5,
       10,
       40,
       60,
       80),
      (0,
       0,
       0,
       100),
      (4, 5, 6),
      []],
     [11200,
      10,
      20,
      0,
      0,
      0,
      4,
      (1,
       5,
       10,
       40,
       60,
       80),
      (0,
       0,
       0,
       100),
      (4, 5, 6),
      []],
     [12000,
      10,
      20,
      0,
      0,
      0,
      4,
      (1,
       5,
       10,
       40,
       60,
       80),
      (0,
       0,
       100,
       0),
      (7, 8, 9),
      []],
     [13000,
      10,
      20,
      0,
      0,
      0,
      4,
      (1,
       5,
       10,
       40,
       60,
       80),
      (0,
       100,
       0,
       0),
      (8, 9, 10),
      []]]
    SUIT_HOOD_INFO_ZONE = 0
    SUIT_HOOD_INFO_MIN = 1
    SUIT_HOOD_INFO_MAX = 2
    SUIT_HOOD_INFO_BMIN = 3
    SUIT_HOOD_INFO_BMAX = 4
    SUIT_HOOD_INFO_BWEIGHT = 5
    SUIT_HOOD_INFO_SMAX = 6
    SUIT_HOOD_INFO_JCHANCE = 7
    SUIT_HOOD_INFO_TRACK = 8
    SUIT_HOOD_INFO_LVL = 9
    SUIT_HOOD_INFO_HEIGHTS = 10
    TOTAL_BWEIGHT = 0
    TOTAL_BWEIGHT_PER_TRACK = [0,
     0,
     0,
     0]
    TOTAL_BWEIGHT_PER_HEIGHT = [0,
     0,
     0,
     0,
     0]
    for currHoodInfo in SuitHoodInfo:
        weight = currHoodInfo[SUIT_HOOD_INFO_BWEIGHT]
        tracks = currHoodInfo[SUIT_HOOD_INFO_TRACK]
        levels = currHoodInfo[SUIT_HOOD_INFO_LVL]
        heights = [0,
         0,
         0,
         0,
         0]
        for level in levels:
            minFloors, maxFloors = SuitBuildingGlobals.SuitBuildingInfo[level - 1][0]
            for i in range(minFloors - 1, maxFloors):
                heights[i] += 1

        currHoodInfo[SUIT_HOOD_INFO_HEIGHTS] = heights
        TOTAL_BWEIGHT += weight
        TOTAL_BWEIGHT_PER_TRACK[0] += weight * tracks[0]
        TOTAL_BWEIGHT_PER_TRACK[1] += weight * tracks[1]
        TOTAL_BWEIGHT_PER_TRACK[2] += weight * tracks[2]
        TOTAL_BWEIGHT_PER_TRACK[3] += weight * tracks[3]
        TOTAL_BWEIGHT_PER_HEIGHT[0] += weight * heights[0]
        TOTAL_BWEIGHT_PER_HEIGHT[1] += weight * heights[1]
        TOTAL_BWEIGHT_PER_HEIGHT[2] += weight * heights[2]
        TOTAL_BWEIGHT_PER_HEIGHT[3] += weight * heights[3]
        TOTAL_BWEIGHT_PER_HEIGHT[4] += weight * heights[4]

    def __init__(self):
        self.suitWalkSpeed = ToontownGlobals.SuitWalkSpeed
        self.dnaStore = None
        self.pointIndexes = {}
        return

    def delete(self):
        del self.dnaStore

    def setupDNA(self):
        if self.dnaStore:
            return None
        self.dnaStore = DNAStorage()
        dnaFileName = self.genDNAFileName()
        loadDNAFileAI(self.dnaStore, dnaFileName)
        self.initDNAInfo()

    def genDNAFileName(self):
        zoneId = ZoneUtil.getCanonicalZoneId(self.getZoneId())
        hoodId = ZoneUtil.getCanonicalHoodId(zoneId)
        hood = ToontownGlobals.dnaMap[hoodId]
        phase = ToontownGlobals.streetPhaseMap[hoodId]
        if hoodId == zoneId:
            zoneId = 'sz'
        return 'phase_%s/dna/%s_%s.dna' % (phase, hood, zoneId)

    def getZoneId(self):
        return self.zoneId

    def setZoneId(self, zoneId):
        self.notify.debug('setting zone id for suit planner')
        self.zoneId = zoneId
        self.setupDNA()

    def extractGroupName(self, groupFullName):
        return groupFullName.split(':', 1)[0]

    def initDNAInfo(self):
        numGraphs = self.dnaStore.discoverContinuity()
        if numGraphs != 1:
            self.notify.info('zone %s has %s disconnected suit paths.' % (self.zoneId, numGraphs))
        self.battlePosDict = {}
        self.cellToGagBonusDict = {}
        for i in range(self.dnaStore.getNumDNAVisGroupsAI()):
            vg = self.dnaStore.getDNAVisGroupAI(i)
            zoneId = int(self.extractGroupName(vg.getName()))
            if vg.getNumBattleCells() == 1:
                self.battlePosDict[zoneId] = vg.getBattleCell(0).getPos()
            elif vg.getNumBattleCells() > 1:
                self.notify.warning('multiple battle cells for zone: %d' % zoneId)
                self.battlePosDict[zoneId] = vg.getBattleCell(0).getPos()
        self.dnaStore.resetDNAGroups()
        self.dnaStore.resetDNAVisGroups()
        self.dnaStore.resetDNAVisGroupsAI()
        self.streetPointList = []
        self.frontdoorPointList = []
        self.sidedoorPointList = []
        self.cogHQDoorPointList = []
        numPoints = self.dnaStore.getNumSuitPoints()
        for i in range(numPoints):
            point = self.dnaStore.getSuitPointAtIndex(i)
            if point.getPointType() == DNASuitPoint.FRONT_DOOR_POINT:
                self.frontdoorPointList.append(point)
            elif point.getPointType() == DNASuitPoint.SIDE_DOOR_POINT:
                self.sidedoorPointList.append(point)
            elif (point.getPointType() == DNASuitPoint.COGHQ_IN_POINT) or (point.getPointType() == DNASuitPoint.COGHQ_OUT_POINT):
                self.cogHQDoorPointList.append(point)
            else:
                self.streetPointList.append(point)
            self.pointIndexes[point.getIndex()] = point

    def performPathTest(self):
        if not self.notify.getDebug():
            return None
        startAndEnd = self.pickPath()
        if not startAndEnd:
            return None
        startPoint = startAndEnd[0]
        endPoint = startAndEnd[1]
        path = self.dnaStore.getSuitPath(startPoint, endPoint)
        numPathPoints = path.getNumPoints()
        for i in range(numPathPoints - 1):
            zone = self.dnaStore.getSuitEdgeZone(path.getPointIndex(i), path.getPointIndex(i + 1))
            travelTime = self.dnaStore.getSuitEdgeTravelTime(path.getPointIndex(i), path.getPointIndex(i + 1), self.suitWalkSpeed)
            self.notify.debug('edge from point ' + repr(i) + ' to point ' + repr((i + 1)) + ' is in zone: ' + repr(zone) + ' and will take ' + repr(travelTime) + ' seconds to walk.')

    def genPath(self, startPoint, endPoint, minPathLen, maxPathLen):
        return self.dnaStore.getSuitPath(startPoint, endPoint, minPathLen, maxPathLen)

    def getDnaStore(self):
        return self.dnaStore
コード例 #32
0
class PlayGame(StateData.StateData):
    notify = DirectNotifyGlobal.directNotify.newCategory('PlayGame')
    Hood2ClassDict = {
        ToontownGlobals.ToontownCentral: TTHood.TTHood,
        ToontownGlobals.DonaldsDock: DDHood.DDHood,
        ToontownGlobals.TheBrrrgh: BRHood.BRHood,
        ToontownGlobals.MinniesMelodyland: MMHood.MMHood,
        ToontownGlobals.DaisyGardens: DGHood.DGHood,
        ToontownGlobals.DonaldsDreamland: DLHood.DLHood,
        ToontownGlobals.GoofySpeedway: GSHood.GSHood,
        ToontownGlobals.OutdoorZone: OZHood.OZHood,
        ToontownGlobals.Tutorial: TutorialHood.TutorialHood,
        ToontownGlobals.MyEstate: EstateHood.EstateHood,
        ToontownGlobals.BossbotHQ: BossbotHQ.BossbotHQ,
        ToontownGlobals.SellbotHQ: SellbotHQ.SellbotHQ,
        ToontownGlobals.CashbotHQ: CashbotHQ.CashbotHQ,
        ToontownGlobals.LawbotHQ: LawbotHQ.LawbotHQ,
        ToontownGlobals.GolfZone: GZHood.GZHood,
        ToontownGlobals.PartyHood: PartyHood.PartyHood
    }
    Hood2StateDict = {
        ToontownGlobals.ToontownCentral: 'TTHood',
        ToontownGlobals.DonaldsDock: 'DDHood',
        ToontownGlobals.TheBrrrgh: 'BRHood',
        ToontownGlobals.MinniesMelodyland: 'MMHood',
        ToontownGlobals.DaisyGardens: 'DGHood',
        ToontownGlobals.DonaldsDreamland: 'DLHood',
        ToontownGlobals.GoofySpeedway: 'GSHood',
        ToontownGlobals.OutdoorZone: 'OZHood',
        ToontownGlobals.Tutorial: 'TutorialHood',
        ToontownGlobals.MyEstate: 'EstateHood',
        ToontownGlobals.BossbotHQ: 'BossbotHQ',
        ToontownGlobals.SellbotHQ: 'SellbotHQ',
        ToontownGlobals.CashbotHQ: 'CashbotHQ',
        ToontownGlobals.LawbotHQ: 'LawbotHQ',
        ToontownGlobals.GolfZone: 'GZHood',
        ToontownGlobals.PartyHood: 'PartyHood'
    }

    def __init__(self, parentFSM, doneEvent):
        StateData.StateData.__init__(self, doneEvent)
        self.place = None
        self.fsm = ClassicFSM.ClassicFSM('PlayGame', [
            State.State('start', self.enterStart, self.exitStart,
                        ['quietZone']),
            State.State('quietZone', self.enterQuietZone, self.exitQuietZone, [
                'TTHood', 'DDHood', 'BRHood', 'MMHood', 'DGHood', 'DLHood',
                'GSHood', 'OZHood', 'GZHood', 'SellbotHQ', 'CashbotHQ',
                'LawbotHQ', 'BossbotHQ', 'TutorialHood', 'EstateHood',
                'PartyHood'
            ]),
            State.State('TTHood', self.enterTTHood, self.exitTTHood,
                        ['quietZone']),
            State.State('DDHood', self.enterDDHood, self.exitDDHood,
                        ['quietZone']),
            State.State('BRHood', self.enterBRHood, self.exitBRHood,
                        ['quietZone']),
            State.State('MMHood', self.enterMMHood, self.exitMMHood,
                        ['quietZone']),
            State.State('DGHood', self.enterDGHood, self.exitDGHood,
                        ['quietZone']),
            State.State('DLHood', self.enterDLHood, self.exitDLHood,
                        ['quietZone']),
            State.State('GSHood', self.enterGSHood, self.exitGSHood,
                        ['quietZone']),
            State.State('OZHood', self.enterOZHood, self.exitOZHood,
                        ['quietZone']),
            State.State('GZHood', self.enterGZHood, self.exitGZHood,
                        ['quietZone']),
            State.State('BossbotHQ', self.enterBossbotHQ, self.exitBossbotHQ,
                        ['quietZone']),
            State.State('SellbotHQ', self.enterSellbotHQ, self.exitSellbotHQ,
                        ['quietZone']),
            State.State('CashbotHQ', self.enterCashbotHQ, self.exitCashbotHQ,
                        ['quietZone']),
            State.State('LawbotHQ', self.enterLawbotHQ, self.exitLawbotHQ,
                        ['quietZone']),
            State.State('TutorialHood', self.enterTutorialHood,
                        self.exitTutorialHood, ['quietZone']),
            State.State('EstateHood', self.enterEstateHood,
                        self.exitEstateHood, ['quietZone']),
            State.State('PartyHood', self.enterPartyHood, self.exitPartyHood,
                        ['quietZone'])
        ], 'start', 'start')
        self.fsm.enterInitialState()
        self.parentFSM = parentFSM
        self.parentFSM.getStateNamed('playGame').addChild(self.fsm)
        self.hoodDoneEvent = 'hoodDone'
        self.hood = None
        self.quietZoneDoneEvent = uniqueName('quietZoneDone')
        self.quietZoneStateData = None
        return

    def enter(self, hoodId, zoneId, avId):
        if hoodId == ToontownGlobals.Tutorial:
            loaderName = 'townLoader'
            whereName = 'toonInterior'
        elif hoodId == ToontownGlobals.MyEstate:
            self.getEstateZoneAndGoHome(avId, zoneId)
            return
        elif hoodId == ToontownGlobals.PartyHood:
            self.getPartyZoneAndGoToParty(avId, zoneId)
            return
        else:
            loaderName = ZoneUtil.getLoaderName(zoneId)
            whereName = ZoneUtil.getToonWhereName(zoneId)
        self.fsm.request('quietZone', [{
            'loader': loaderName,
            'where': whereName,
            'how': 'teleportIn',
            'hoodId': hoodId,
            'zoneId': zoneId,
            'shardId': None,
            'avId': avId
        }])
        return

    def exit(self):
        if base.placeBeforeObjects and self.quietZoneStateData:
            self.quietZoneStateData.exit()
            self.quietZoneStateData.unload()
            self.quietZoneStateData = None
        self.ignore(self.quietZoneDoneEvent)
        return

    def load(self):
        pass

    def loadDnaStoreTutorial(self):
        self.dnaStore = DNAStorage()
        files = ('phase_3.5/dna/storage_tutorial.dna',
                 'phase_3.5/dna/storage_interior.dna')
        dnaBulk = DNABulkLoader(self.dnaStore, files)
        dnaBulk.loadDNAFiles()

    def loadDnaStore(self):
        if not hasattr(self, 'dnaStore'):
            self.dnaStore = DNAStorage()
            files = ('phase_4/dna/storage.dna',
                     'phase_3.5/dna/storage_interior.dna')
            dnaBulk = DNABulkLoader(self.dnaStore, files)
            dnaBulk.loadDNAFiles()
            self.dnaStore.storeFont('humanist',
                                    ToontownGlobals.getInterfaceFont())
            self.dnaStore.storeFont('mickey', ToontownGlobals.getSignFont())
            self.dnaStore.storeFont('suit', ToontownGlobals.getSuitFont())

    def unloadDnaStore(self):
        if hasattr(self, 'dnaStore'):
            del self.dnaStore
            ModelPool.garbageCollect()
            TexturePool.garbageCollect()

    def unload(self):
        self.unloadDnaStore()
        if self.hood:
            self.notify.info('Aggressively cleaning up hood: %s' % self.hood)
            self.hood.exit()
            self.hood.unload()
            self.hood = None
        base.cr.cache.flush()

    def enterStart(self):
        pass

    def exitStart(self):
        pass

    def handleHoodDone(self):
        doneStatus = self.hood.getDoneStatus()
        shardId = doneStatus['shardId']
        if shardId != None:
            self.doneStatus = doneStatus
            messenger.send(self.doneEvent)
            base.transitions.fadeOut(0)
            return
        if doneStatus['where'] == 'party':
            self.getPartyZoneAndGoToParty(doneStatus['avId'],
                                          doneStatus['zoneId'])
            return
        how = doneStatus['how']
        if how in ['tunnelIn', 'teleportIn', 'doorIn', 'elevatorIn', 'walk']:
            self.fsm.request('quietZone', [doneStatus])
        else:
            self.notify.error('Exited hood with unexpected mode %s' % how)
        return

    def _destroyHood(self):
        self.unload()

    def enterQuietZone(self, requestStatus):
        self.acceptOnce(self.quietZoneDoneEvent, self.handleQuietZoneDone)
        self.quietZoneStateData = QuietZoneState.QuietZoneState(
            self.quietZoneDoneEvent)
        self._quietZoneLeftEvent = self.quietZoneStateData.getQuietZoneLeftEvent(
        )
        if base.placeBeforeObjects:
            self.acceptOnce(self._quietZoneLeftEvent, self.handleLeftQuietZone)
        self._enterWaitForSetZoneResponseMsg = self.quietZoneStateData.getEnterWaitForSetZoneResponseMsg(
        )
        self.acceptOnce(self._enterWaitForSetZoneResponseMsg,
                        self.handleWaitForSetZoneResponse)
        self.quietZoneStateData.load()
        self.quietZoneStateData.enter(requestStatus)

    def exitQuietZone(self):
        self.ignore(self._quietZoneLeftEvent)
        self.ignore(self._enterWaitForSetZoneResponseMsg)
        if not base.placeBeforeObjects:
            self.ignore(self.quietZoneDoneEvent)
            self.quietZoneStateData.exit()
            self.quietZoneStateData.unload()
            self.quietZoneStateData = None
        return

    def handleWaitForSetZoneResponse(self, requestStatus):
        hoodId = requestStatus['hoodId']
        canonicalHoodId = ZoneUtil.getCanonicalZoneId(hoodId)
        toHoodPhrase = ToontownGlobals.hoodNameMap[canonicalHoodId][0]
        hoodName = ToontownGlobals.hoodNameMap[canonicalHoodId][-1]
        zoneId = requestStatus['zoneId']
        requestStatus['loader'] = 'cogHQLoader' if ZoneUtil.isCogHQZone(
            hoodId) else requestStatus['loader']
        loaderName = requestStatus['loader']
        avId = requestStatus.get('avId', -1)
        ownerId = requestStatus.get('ownerId', avId)
        if base.config.GetBool('want-qa-regression', 0):
            self.notify.info('QA-REGRESSION: NEIGHBORHOODS: Visit %s' %
                             hoodName)
        count = ToontownGlobals.hoodCountMap[canonicalHoodId]
        if loaderName == 'safeZoneLoader':
            count += ToontownGlobals.safeZoneCountMap[canonicalHoodId]
        elif loaderName == 'townLoader':
            count += ToontownGlobals.townCountMap[canonicalHoodId]
        if not loader.inBulkBlock:
            if hoodId == ToontownGlobals.MyEstate:
                if avId == -1:
                    loader.beginBulkLoad('hood',
                                         TTLocalizer.HeadingToYourEstate,
                                         count, 1, TTLocalizer.TIP_ESTATE,
                                         zoneId)
                else:
                    owner = base.cr.identifyAvatar(ownerId)
                    if owner == None:
                        friend = base.cr.identifyAvatar(avId)
                        if friend != None:
                            avName = friend.getName()
                            loader.beginBulkLoad(
                                'hood', TTLocalizer.HeadingToFriend % avName,
                                count, 1, TTLocalizer.TIP_ESTATE, zoneId)
                        else:
                            self.notify.warning(
                                "we can't perform this teleport")
                            return
                    else:
                        avName = owner.getName()
                        loader.beginBulkLoad(
                            'hood', TTLocalizer.HeadingToEstate % avName,
                            count, 1, TTLocalizer.TIP_ESTATE, zoneId)
            elif ZoneUtil.isCogHQZone(zoneId):
                loader.beginBulkLoad(
                    'hood', TTLocalizer.HeadingToHood % {
                        'to': toHoodPhrase,
                        'hood': hoodName
                    }, count, 1, TTLocalizer.TIP_COGHQ, zoneId)
            elif ZoneUtil.isGoofySpeedwayZone(zoneId):
                loader.beginBulkLoad(
                    'hood', TTLocalizer.HeadingToHood % {
                        'to': toHoodPhrase,
                        'hood': hoodName
                    }, count, 1, TTLocalizer.TIP_KARTING, zoneId)
            else:
                loader.beginBulkLoad(
                    'hood', TTLocalizer.HeadingToHood % {
                        'to': toHoodPhrase,
                        'hood': hoodName
                    }, count, 1, TTLocalizer.TIP_GENERAL, zoneId)
        if hoodId == ToontownGlobals.Tutorial:
            self.loadDnaStoreTutorial()
        else:
            if not hasattr(self, 'dnaStore'):
                self.loadDnaStore()
        hoodClass = self.getHoodClassByNumber(canonicalHoodId)
        self.hood = hoodClass(self.fsm, self.hoodDoneEvent, self.dnaStore,
                              hoodId)
        self.hood.load()
        self.hood.loadLoader(requestStatus)
        if not base.placeBeforeObjects:
            loader.endBulkLoad('hood')
        return

    def handleLeftQuietZone(self):
        status = self.quietZoneStateData.getRequestStatus()
        hoodId = ZoneUtil.getCanonicalZoneId(status['hoodId'])
        hoodState = self.getHoodStateByNumber(hoodId)
        self.fsm.request(hoodState, [status])

    def handleQuietZoneDone(self):
        if base.placeBeforeObjects:
            self.quietZoneStateData.exit()
            self.quietZoneStateData.unload()
            self.quietZoneStateData = None
            loader.endBulkLoad('hood')
        else:
            self.handleLeftQuietZone()
        return

    def enterTTHood(self, requestStatus):
        self.accept(self.hoodDoneEvent, self.handleHoodDone)
        self.hood.enter(requestStatus)

    def exitTTHood(self):
        self._destroyHood()

    def enterDDHood(self, requestStatus):
        self.accept(self.hoodDoneEvent, self.handleHoodDone)
        self.hood.enter(requestStatus)

    def exitDDHood(self):
        self._destroyHood()

    def enterMMHood(self, requestStatus):
        self.accept(self.hoodDoneEvent, self.handleHoodDone)
        self.hood.enter(requestStatus)

    def exitMMHood(self):
        self._destroyHood()

    def enterBRHood(self, requestStatus):
        self.accept(self.hoodDoneEvent, self.handleHoodDone)
        self.hood.enter(requestStatus)

    def exitBRHood(self):
        self._destroyHood()

    def enterDGHood(self, requestStatus):
        self.accept(self.hoodDoneEvent, self.handleHoodDone)
        self.hood.enter(requestStatus)

    def exitDGHood(self):
        self._destroyHood()

    def enterDLHood(self, requestStatus):
        self.accept(self.hoodDoneEvent, self.handleHoodDone)
        self.hood.enter(requestStatus)

    def exitDLHood(self):
        self._destroyHood()

    def enterGSHood(self, requestStatus):
        self.accept(self.hoodDoneEvent, self.handleHoodDone)
        self.hood.enter(requestStatus)

    def exitGSHood(self):
        self._destroyHood()

    def enterOZHood(self, requestStatus):
        self.accept(self.hoodDoneEvent, self.handleHoodDone)
        self.hood.enter(requestStatus)

    def exitOZHood(self):
        self._destroyHood()

    def enterGZHood(self, requestStatus):
        self.accept(self.hoodDoneEvent, self.handleHoodDone)
        self.hood.enter(requestStatus)

    def exitGZHood(self):
        self._destroyHood()

    def enterSellbotHQ(self, requestStatus):
        self.accept(self.hoodDoneEvent, self.handleHoodDone)
        self.hood.enter(requestStatus)

    def exitSellbotHQ(self):
        self._destroyHood()

    def enterCashbotHQ(self, requestStatus):
        self.accept(self.hoodDoneEvent, self.handleHoodDone)
        self.hood.enter(requestStatus)

    def exitCashbotHQ(self):
        self._destroyHood()

    def enterLawbotHQ(self, requestStatus):
        self.accept(self.hoodDoneEvent, self.handleHoodDone)
        self.hood.enter(requestStatus)

    def exitLawbotHQ(self):
        self._destroyHood()

    def enterBossbotHQ(self, requestStatus):
        self.accept(self.hoodDoneEvent, self.handleHoodDone)
        self.hood.enter(requestStatus)

    def exitBossbotHQ(self):
        self._destroyHood()

    def enterTutorialHood(self, requestStatus):
        messenger.send('toonArrivedTutorial')
        self.accept(self.hoodDoneEvent, self.handleHoodDone)
        base.localAvatar.book.obscureButton(1)
        base.localAvatar.book.setSafeMode(1)
        base.localAvatar.laffMeter.obscure(1)
        base.localAvatar.chatMgr.obscure(1, 1, 1)
        base.localAvatar.obscureFriendsListButton(1)
        requestStatus['how'] = 'tutorial'
        if base.config.GetString('language', 'english') == 'japanese':
            musicVolume = base.config.GetFloat('tutorial-music-volume', 0.5)
            requestStatus['musicVolume'] = musicVolume
        self.hood.enter(requestStatus)

    def exitTutorialHood(self):
        self.unloadDnaStore()
        self._destroyHood()
        base.localAvatar.book.obscureButton(0)
        base.localAvatar.book.setSafeMode(0)
        base.localAvatar.laffMeter.obscure(0)
        base.localAvatar.chatMgr.obscure(0, 0, 0)
        base.localAvatar.obscureFriendsListButton(-1)

    def enterEstateHood(self, requestStatus):
        self.accept(self.hoodDoneEvent, self.handleHoodDone)
        self.hood.enter(requestStatus)

    def exitEstateHood(self):
        self._destroyHood()

    def getEstateZoneAndGoHome(self, avId, zoneId):
        self.doneStatus = {
            'avId': avId,
            'zoneId': zoneId,
            'hoodId': ToontownGlobals.MyEstate,
            'loader': 'safeZoneLoader',
            'how': 'teleportIn',
            'shardId': None
        }
        self.acceptOnce('setLocalEstateZone', self.goHome)
        if avId > 0:
            base.cr.estateMgr.getLocalEstateZone(avId)
        else:
            base.cr.estateMgr.getLocalEstateZone(base.localAvatar.getDoId())
        return

    def goHome(self, ownerId, zoneId):
        self.notify.debug('goHome ownerId = %s' % ownerId)
        if ownerId > 0 and ownerId != base.localAvatar.doId and not base.cr.isFriend(
                ownerId):
            self.doneStatus['failed'] = 1
            taskMgr.remove('goHomeFailed')
            taskMgr.add(self.goHomeFailed, 'goHomeFailed')
            return
        if ownerId == 0 and zoneId == 0:
            self.doneStatus['failed'] = 1
            self.goHomeFailed(None)
            return
        if self.doneStatus['zoneId'] != zoneId:
            self.doneStatus['where'] = 'house'
        else:
            self.doneStatus['where'] = 'estate'
        self.doneStatus['ownerId'] = ownerId
        self.fsm.request('quietZone', [self.doneStatus])
        return

    def goHomeFailed(self, task):
        self.notify.debug('goHomeFailed')
        failedToVisitAvId = self.doneStatus.get('avId')
        if failedToVisitAvId > 0:
            message = TTLocalizer.EstateTeleportFailedNotFriends % base.cr.identifyAvatar(
                failedToVisitAvId).getName()
        else:
            message = TTLocalizer.EstateTeleportFailed
        self.notify.debug('goHomeFailed, why =: %s' % message)
        self.ignore('setLocalEstateZone')
        zoneId = base.localAvatar.lastHood
        loaderName = ZoneUtil.getLoaderName(zoneId)
        whereName = ZoneUtil.getToonWhereName(zoneId)
        base.localAvatar.setSystemMessage(0, message)
        self.fsm.request('quietZone', [{
            'loader': loaderName,
            'where': whereName,
            'how': 'teleportIn',
            'hoodId': zoneId,
            'zoneId': zoneId,
            'shardId': None
        }])
        return Task.done

    def enterPartyHood(self, requestStatus):
        self.accept(self.hoodDoneEvent, self.handleHoodDone)
        requestStatus['where'] = 'party'
        self.hood.enter(requestStatus)

    def exitPartyHood(self):
        self._destroyHood()

    def getPartyZoneAndGoToParty(self, avId, zoneId):
        self.doneStatus = {
            'avId': avId,
            'zoneId': zoneId,
            'hoodId': ToontownGlobals.PartyHood,
            'loader': 'safeZoneLoader',
            'how': 'teleportIn',
            'shardId': None
        }
        if avId < 0:
            avId = base.localAvatar.getDoId()
        base.cr.partyManager.requestPartyZone(avId,
                                              zoneId,
                                              callback=self.goToParty)
        return

    def goToParty(self, ownerId, partyId, zoneId):
        if ownerId == 0 or partyId == 0 or zoneId == 0:
            self.doneStatus['where'] = 'playground'
        else:
            self.doneStatus['where'] = 'party'
        self.doneStatus['ownerId'] = ownerId
        self.doneStatus['partyId'] = partyId
        self.doneStatus['zoneId'] = zoneId
        self.fsm.request('quietZone', [self.doneStatus])

    def goToPartyFailed(self, reason):
        self.notify.debug('goToPartyFailed')
        failedToVisitAvId = self.doneStatus.get('avId')
        message = base.cr.partyManager.getGoToPartyFailedMessage(reason)
        self.notify.debug('goToPartyFailed, why =: %s' % message)
        self.ignore('gotLocalPartyZone')
        zoneId = base.localAvatar.lastHood
        loaderName = ZoneUtil.getLoaderName(zoneId)
        whereName = ZoneUtil.getToonWhereName(zoneId)
        base.localAvatar.setSystemMessage(0, message)
        self.fsm.request('quietZone', [{
            'loader': loaderName,
            'where': whereName,
            'how': 'teleportIn',
            'hoodId': zoneId,
            'zoneId': zoneId,
            'shardId': None
        }])
        return Task.done

    def getCatalogCodes(self, category):
        numCodes = self.dnaStore.getNumCatalogCodes(category)
        codes = []
        for i in range(numCodes):
            codes.append(self.dnaStore.getCatalogCode(category, i))

        return codes

    def getNodePathList(self, catalogGroup):
        result = []
        codes = self.getCatalogCodes(catalogGroup)
        for code in codes:
            np = self.dnaStore.findNode(code)
            result.append(np)

        return result

    def getNodePathDict(self, catalogGroup):
        result = {}
        codes = self.getCatalogCodes(catalogGroup)
        for code in codes:
            np = self.dnaStore.findNode(code)
            result[code] = np

        return result

    def getHoodClassByNumber(self, hoodNumber):
        return self.Hood2ClassDict[hoodNumber]

    def getHoodStateByNumber(self, hoodNumber):
        return self.Hood2StateDict[hoodNumber]

    def setPlace(self, place):
        self.place = place
        if self.place:
            messenger.send('playGameSetPlace')

    def getPlace(self):
        return self.place

    def getPlaceId(self):
        if self.hood:
            return self.hood.hoodId
        else:
            return None
        return None
コード例 #33
0
    def test_blocks(self):
        store = DNAStorage()
        block1 = (
            4269,  # block_number
            "libpandadna",  # title
            "",  # article
            "",  # bldg_type
            1337  # zone_id
        )
        block2 = (
            1337,  # block_number
            "Visual Studio 2010",  # title
            "",  # article
            "",  # bldg_type
            4269  # zone_id
        )
        block3 = (
            1000,  # block_number
            "C++ reader",  # title
            "",  # article
            "",  # bldg_type
            4269  # zone_id
        )

        store.storeBlock(*block1)
        store.storeBlock(*block2)
        store.storeBlock(*block3)

        door1 = NodePath('block-1000')
        door1.setPos(5, 5, 10)
        door1.setH(180)
        store.storeBlockDoor(1000, door1)

        self.assertEqual(store.getNumBlockNumbers(), 3)

        # Test an invalid block number
        self.assertEqual(store.getZoneFromBlockNumber(100), 0)
        self.assertEqual(store.getZoneFromBlockNumber(1000), 4269)
        self.assertEqual(store.getZoneFromBlockNumber(1337), 4269)
        self.assertEqual(store.getZoneFromBlockNumber(4269), 1337)
        self.assertEqual(store.getTitleFromBlockNumber(1000), "C++ reader")
        self.assertEqual(store.getTitleFromBlockNumber(1337),
                         "Visual Studio 2010")
        self.assertEqual(store.getTitleFromBlockNumber(4269), "libpandadna")
        self.assertEqual(store.getBlockNumberAt(0), 4269)
        self.assertEqual(store.getBlockNumberAt(1), 1337)
        self.assertEqual(store.getBlockNumberAt(2), 1000)
        self.assertEqual(store.getDoorPosHprFromBlockNumber(1000), door1)
        self.assertTrue(store.getDoorPosHprFromBlockNumber(1337).isEmpty())

        store.resetBlockNumbers()
        store.resetBlockZones()

        self.assertEqual(store.getTitleFromBlockNumber(1000), "")
        self.assertEqual(store.getTitleFromBlockNumber(1337), "")
        self.assertEqual(store.getTitleFromBlockNumber(4269), "")