def loadEnvir(self):
     terrain = GeoMipTerrain("terreno")
     terrain.setHeightfield("terreno/preto.png")
     terrain.setColorMap("terreno/tile_far.jpg")
     terrain.getRoot().setScale(5, 5, 50)
     terrain.getRoot().reparentTo(render)
     terrain.generate()
Example #2
0
 def play(self, ai, difficult=False):
     self.easyAI.destroy()
     self.hardAI.destroy()
     self.ai = None
     self.cTrav = CollisionTraverser()
     self.coll = CollisionHandlerEvent()
     self.coll.addInPattern("%fn-into-%in")
     self.clock = ClockObject()
     terrain = GeoMipTerrain("worldTerrain")
     terrain.setHeightfield("heightMap.png")
     terrain.setColorMap("colormap.png")
     terrain.setBruteforce(True)
     root = terrain.getRoot()
     root.reparentTo(self.render)
     root.setSz(1)
     terrain.generate()
     self.player = Character("models/panda-model", 0.05, (300, 300, 0),
                             self.render, {"walk": "models/panda-walk4"},
                             self, self.path, 200, "player")
     self.addControls()
     self.loadUI()
     self.startTasks()
     self.accept("proj-into-player", self.player.changeLife, [-1])
     self.others = dict()
     self.roundOv = False
     self.taskMgr.add(self.update, "Update")
     self.gameOver = False
     if ai:
         self.aiBattle(difficult)
    def __init__(self, data_source):
        ShowBase.__init__(self)
        if not os.path.isfile('world.bam'):
            terrain = GeoMipTerrain("worldTerrain")
            terrain.setHeightfield(
                os.path.join(RESOURCE_DIR, "uk_height_map_25.png"))
            terrain.setColorMap(
                os.path.join(RESOURCE_DIR, "uk_flopped_rotated_25.png"))
            terrain.setBruteforce(True)
            root = terrain.getRoot()
            root.reparentTo(render)
            root.setSz(10)
            terrain.generate()
            root.writeBamFile('world.bam')
        else:
            world = loader.loadModel("world.bam")
            world.reparentTo(render)

        self.toasters = {}
        self.toasters_by_zone = {}
        for vm in data_source.get_vms():
            height = len(self.toasters_by_zone.get(vm.zonename, []))
            self.toasters[vm.name] = Toaster(vm.zonename, height,
                                             vm.state == "Running")
            self.toasters_by_zone.setdefault(vm.zonename,
                                             []).append(self.toasters[vm.name])

        # In Panda3D you have to cancel the default mouse control to set the camera explicitly
        # Falsify the following 3 lines to allow it back again:
        if True:
            self.disableMouse()
            self.camera.setPos(350, -100, 100)
            self.camera.setHpr(0, -25, 0)
Example #4
0
    def __init__(self):
        fn = Filename.fromOsSpecific(self.filepath)
        self.terrain = GeoMipTerrain("mySimpleTerrain")
        self.terrain.setHeightfield("Entities/Maps/heightmap.png")
        self.terrain.getRoot().setSz(40)
        #terrain.setBruteforce(True)
        self.terrain.getRoot().reparentTo(render)

        # Set terrain properties
        self.terrain.setBlockSize(16)
        self.terrain.setNear(500)
        self.terrain.setFar(100)
        self.terrain.setFocalPoint(base.camera)

        # Store the root NodePath for convenience
        root = self.terrain.getRoot()
        root.reparentTo(render)

        # some tinkering
        """
        # tell renderer to repeat texture when reading over the edge.
        texGrass.setWrapU(Texture.WM_repeat)
        texGrass.setWrapV(Texture.WM_repeat)
        # apply mipmapping: tell renderer how to handle multiple texture pixels being rendered t a single screen pixel (makes textures 30% larger in GPU mem.)
        texGrass.setMinfilter(SamplerState.FT_linear_mipmap_linear)
        """
        self.terrain.generate()
        """
        new attempt to include blend mapping:
        """
        # determine terrain size
        self.heightmap = self.terrain.heightfield()
        if self.heightmap.getXSize() > self.heightmap.getYSize():
            self.size = self.heightmap.getXSize() - 1
        else:
            self.size = self.heightmap.getYSize() - 1
        self.xsize = self.heightmap.getXSize() - 1
        self.ysize = self.heightmap.getYSize() - 1

        # Set multi texture
        # Source http://www.panda3d.org/phpbb2/viewtopic.php?t=4536
        self.generateSurfaceTextures()

        # load a blend texture from file:
        self.blendTexture = loader.loadTexture("Entities/Maps/blendMap.png")

        self.blendTS = TextureStage('blend')
        self.blendTS.setSort(0)
        self.blendTS.setPriority(1)
        # apply textures to the terrain and connect custom shader for blend mapping:
        self.setSurfaceTextures()

        # Add a task to keep updating the terrain (for changing terrain, or synamic resolution)
        def updateTask(task):
            self.terrain.update()
            return task.cont

        taskMgr.add(updateTask, "update")
Example #5
0
    def __init__(self, *args, **kwargs):
        super(environment, self).__init__()

        self.sky = loader.loadModel(
            'models/environmentModels/sceneModels/sky/skydome2.egg')

        self.modelList = []

        self.terrain = GeoMipTerrain('terrain')
Example #6
0
 def __init__(self):
     ShowBase.__init__(self)
     terrain = GeoMipTerrain("worldTerrain")
     terrain.setHeightfield("height-map.png")
     terrain.setColorMap("texture-map.png")
     terrain.setBruteforce(True)
     root = terrain.getRoot()
     root.reparentTo(render)
     root.setSz(60)
     terrain.generate()
Example #7
0
 def __init__(self):
     ShowBase.__init__(self)  # initialise
     terrain = GeoMipTerrain("worldTerrain")  # create a terrain
     terrain.setHeightfield("mapheight.png")  # set the height map
     terrain.setColorMap("maptex.png")  # set the colour map
     terrain.setBruteforce(True)  # level of detail
     root = terrain.getRoot()  # capture root
     root.reparentTo(render)  # render from root
     root.setSz(60)  # maximum height
     terrain.generate()  # generate
Example #8
0
 def __init__(self):
     ShowBase.__init__(self)  # initialise
     terrain = GeoMipTerrain("worldTerrain")  # create a terrain
     terrain.setHeightfield("gwadaHeightSmall.png")  # set the height map
     terrain.setColorMap("gwadaTextureSmall.jpg")  # set the colour map
     #terrain.setBruteforce(True)                    # level of detail
     root = terrain.getRoot()  # capture root
     root.reparentTo(render)  # render from root
     root.setSz(60)  # maximum height
     terrain.generate()  # generate
     root.writeBamFile('world.bam')  # create 3D model
Example #9
0
    def __init__(self):
        assert engine_initialized(
        ), "You should initialize engine before adding camera to vehicle"
        config = get_global_config()["vehicle_config"]["depth_camera"]
        self.BUFFER_W, self.BUFFER_H = config[0], config[1]
        self.VIEW_GROUND = config[2]
        super(DepthCamera, self).__init__()
        cam = self.get_cam()
        lens = self.get_lens()

        cam.lookAt(0, 2.4, 1.3)
        lens.setFov(60)
        lens.setAspectRatio(2.0)
        if get_engine(
        ).mode == RENDER_MODE_NONE or not AssetLoader.initialized():
            return
        # add shader for it
        if get_global_config()["headless_machine_render"]:
            vert_path = AssetLoader.file_path("shaders",
                                              "depth_cam_gles.vert.glsl")
            frag_path = AssetLoader.file_path("shaders",
                                              "depth_cam_gles.frag.glsl")
        else:
            from pgdrive.utils import is_mac
            if is_mac():
                vert_path = AssetLoader.file_path("shaders",
                                                  "depth_cam_mac.vert.glsl")
                frag_path = AssetLoader.file_path("shaders",
                                                  "depth_cam_mac.frag.glsl")
            else:
                vert_path = AssetLoader.file_path("shaders",
                                                  "depth_cam.vert.glsl")
                frag_path = AssetLoader.file_path("shaders",
                                                  "depth_cam.frag.glsl")
        custom_shader = Shader.load(Shader.SL_GLSL,
                                    vertex=vert_path,
                                    fragment=frag_path)
        cam.node().setInitialState(
            RenderState.make(ShaderAttrib.make(custom_shader, 1)))

        if self.VIEW_GROUND:
            self.GROUND = GeoMipTerrain("mySimpleTerrain")

            self.GROUND.setHeightfield(
                AssetLoader.file_path("textures", "height_map.png"))
            # terrain.setBruteforce(True)
            # # Since the terrain is a texture, shader will not calculate the depth information, we add a moving terrain
            # # model to enable the depth information of terrain
            self.GROUND_MODEL = self.GROUND.getRoot()
            self.GROUND_MODEL.setPos(-128, 0, self.GROUND_HEIGHT)
            self.GROUND_MODEL.hide(CamMask.AllOn)
            self.GROUND_MODEL.show(CamMask.DepthCam)
            self.GROUND.generate()
Example #10
0
    def __init__(self):
        ShowBase.__init__(self)
        terrain = GeoMipTerrain("worldTerrain")
        terrain.setHeightfield("models/issue1terrain.png")
        terrain.setColorMap("models/issue2terrain.png")
        terrain.setBruteforce(True)  # level of detail
        root = terrain.getRoot()
        root.reparentTo(render)
        root.setSz(60)  # maximum height
        terrain.generate()

        root.writeBamFile("models/world.bam")
Example #11
0
 def __init__(self):
     ShowBase.__init__(self)  # initialise
     terrain = GeoMipTerrain("worldTerrain")  # create a terrain
     terrain.setHeightfield(height)  # set the height map
     terrain.setColorMap(texture)  # set the colour map
     terrain.setBruteforce(True)  # level of detail
     root = terrain.getRoot()  # capture root
     root.reparentTo(render)  # render from root
     root.setSz(2)  # maximum height
     terrain.generate()  # generate
     root.writeBamFile('models/world' + worldNameSuffix +
                       ".bam")  # create 3D model
Example #12
0
    def __init__(self, _heightField):

    	texture = loader.loadTexture("ground_tex.png")
        self.zScale = 45

        self.terrain = GeoMipTerrain("BasicTerrain")
        self.terrain.setHeightfield(_heightField)

        # Dynamic settings?
        self.terrain.setBlockSize(16)
        self.terrain.setNear(20)
        self.terrain.setFar(100)
        self.terrain.setFocalPoint(base.camera)

        # Settings
        self.terrain.getRoot().setSz(self.zScale)
        self.terrain.getRoot().setTexture(texture)
        self.terrain.getRoot().reparentTo(render)
        self.terrain.generate()

        self.terrainSize = (self.terrain.heightfield().getReadXSize(), self.terrain.heightfield().getReadYSize())
        print "Terrain Size:", self.terrainSize
        taskMgr.add(self.terrainTask, "TerrainTask")

        self.skydome = loader.loadModel("Skydome")
        self.skydome.setDepthTest(False)
        self.skydome.setAttrib(CullBinAttrib.make("skydomeBin", 1000))
        self.skydome.reparentTo(camera)
        self.skydome.setScale(2)
        self.skydome.setPos(0, 0, -0.5)
        self.skydome.setCollideMask(BitMask32.allOff())
        taskMgr.add(self.skydomeTask, "paperplanet_skydome")

        # Add some fancy fog
        self.fog = Fog("Fog Name")
        self.fog.setColor(0.4,0.2,0.3)
        self.fog.setExpDensity(0.015)
        render.setFog(self.fog)

        # Some Test light
        dlight = DirectionalLight("dlight")
        dlight.setColor(VBase4(0.8, 0.8, 0.5, 1))
        dlnp = render.attachNewNode(dlight)
        dlnp.setHpr(0, -60, 0)
        render.setLight(dlnp)


        # Add basic blacksmith hut
        tmp = loader.loadModel("blacksmith_hut")
        tmp.reparentTo(render)
        tmp.setPos(164.054, 340.92, 11.3384)
Example #13
0
def loadTerrain(name, widthScale = 0.5, heightScale = 10.0):
    """load terrain stuff"""

    global app, terrain, terrainRootNetPos
        
    steerMgr = OSSteerManager.get_global_ptr()

    terrain = GeoMipTerrain("terrain")
    heightField = PNMImage(Filename(dataDir + "/heightfield.png"))
    terrain.set_heightfield(heightField)
    # sizing
    environmentWidthX = (heightField.get_x_size() - 1) * widthScale
    environmentWidthY = (heightField.get_y_size() - 1) * widthScale
    environmentWidth = (environmentWidthX + environmentWidthY) / 2.0
    terrain.get_root().set_sx(widthScale)
    terrain.get_root().set_sy(widthScale)
    terrain.get_root().set_sz(heightScale)
    # set other terrain's properties
    blockSize, minimumLevel = (64, 0)
    nearPercent, farPercent = (0.1, 0.7)
    terrainLODmin = min(minimumLevel, terrain.get_max_level())
    flattenMode = GeoMipTerrain.AFM_off
    terrain.set_block_size(blockSize)
    terrain.set_near(nearPercent * environmentWidth)
    terrain.set_far(farPercent * environmentWidth)
    terrain.set_min_level(terrainLODmin)
    terrain.set_auto_flatten(flattenMode)
    # terrain texturing
    textureStage0 = TextureStage("TextureStage0")
    textureImage = TexturePool.load_texture(Filename("terrain.png"))
    terrain.get_root().set_tex_scale(textureStage0, 1.0, 1.0)
    terrain.get_root().set_texture(textureStage0, textureImage, 1)
    # reparent this Terrain node path to the object node path
    terrain.get_root().reparent_to(steerMgr.get_reference_node_path())
    terrain.get_root().set_collide_mask(mask)
    terrain.get_root().set_name(name)
    # brute force generation
    bruteForce = True
    terrain.set_bruteforce(bruteForce)
    # Generate the terrain
    terrain.generate()
    # check if terrain needs update or not
    if not bruteForce:
        # save the net pos of terrain root
        terrainRootNetPos = terrain.get_root().get_net_transform().get_pos()
        # Add a task to keep updating the terrain
        app.taskMgr.add(terrainUpdate, "terrainUpdate", appendTask=True)
    #
    return terrain.get_root()
Example #14
0
 def initTerrain(self):
     self.terrain = GeoMipTerrain("worldTerrain")  # create a self.terrain
     self.terrain.setHeightfield(
         parameters["modelHeightMap"])  # set the height map
     if parameters[
             "loadNullModels"]:  #if null, then create uniform back and sky
         self.terrain.setColorMap(
             parameters["modelTextureMapNull"])  # set the colour map
     else:
         self.terrain.setColorMap(
             parameters["modelTextureMap"])  # set the colour map
     self.terrain.setBruteforce(True)  # level of detail
     self.root = self.terrain.getRoot()  # capture root
     self.root.reparentTo(self.render)  # render from root
     self.root.setSz(0.2)  # maximum height
     self.terrain.generate()  # generate
Example #15
0
    def __init__(self):
        ShowBase.__init__(self)
        self.terrain = GeoMipTerrain("terrain")
        #doesn't use search path
        self.terrain.setHeightfield("../textures/height.png")
        self.terrain.setColorMap("../textures/grass.png")
        self.terrain.getRoot().setSz(35)
        #self.terrain.setBlockSize(16)
        #self.terrain.setNear(35)
        #self.terrain.setFar(75)
        self.terrain.getRoot().reparentTo(render)
        self.terrain.generate()

        z = self.terrain.getElevation(256, 256) * 40
        self.cam.setPos(256, 256, z)

        self.terrain.setFocalPoint(self.cam)
        self.taskMgr.add(self.updateTerrain, "update terrain")
Example #16
0
    def __create_terrain(self):
        terrain = GeoMipTerrain("Terrain")
        terrain.setHeightfield(self.__texture_path(self.__scene.get("scene", "heightmap")))
        terrain.getRoot().reparentTo(self.render)
        terrain.generate()
        terrain.getRoot().setSx(1000.0 / 512)
        terrain.getRoot().setSy(1000.0 / 512)
        terrain.getRoot().setSz(74)
        terrain.getRoot().setPos(-500, -500, 0)

        black = self.loader.loadTexture(self.__texture_path(self.__scene.get("terrain", "black")))
        black.setMinfilter(Texture.FTLinearMipmapNearest)
        ts = TextureStage("stage-first")
        ts.setSort(0)
        ts.setMode(TextureStage.MReplace)
        ts.setSavedResult(True)
        terrain.getRoot().setTexture(ts, black)
        terrain.getRoot().setTexScale(ts, 250, 250)

        white = self.loader.loadTexture(self.__texture_path(self.__scene.get("terrain", "white")))
        white.setMinfilter(Texture.FTLinearMipmapNearest)
        ts = TextureStage("stage-second")
        ts.setSort(1)
        ts.setMode(TextureStage.MReplace)
        terrain.getRoot().setTexture(ts, white)
        terrain.getRoot().setTexScale(ts, 250, 250)

        stencil = self.loader.loadTexture(self.__texture_path(self.__scene.get("scene", "stencil")))
        ts = TextureStage("stage-stencil")
        ts.setSort(2)
        ts.setCombineRgb(TextureStage.CMInterpolate,
                         TextureStage.CSPrevious, TextureStage.COSrcColor,
                         TextureStage.CSLastSavedResult, TextureStage.COSrcColor,
                         TextureStage.CSTexture, TextureStage.COSrcColor)

        terrain.getRoot().setTexture(ts, stencil)

        ts = TextureStage("stage-vertexcolour")
        ts.setSort(3)
        ts.setCombineRgb(TextureStage.CMModulate, TextureStage.CSPrevious, TextureStage.COSrcColor,
                         TextureStage.CSPrimaryColor, TextureStage.COSrcColor)

        terrain.getRoot().setTexture(ts, "final")
 def createTile(self, x, y):
     # Set up the GeoMipTerrain
     terrain = GeoMipTerrain("terrain")
     terrain.setHeightfield("./height-map.png")
     # Set terrain properties
     terrain.setBlockSize(32)
     terrain.setNear(40)
     terrain.setFar(100)
     terrain.setFocalPoint(self.showBase.camera)
     #terrain.setAutoFlatten(GeoMipTerrain.AFMStrong)
     terrain.getRoot().setScale(1, 1, 1)
     terrain.getRoot().setPos(x * 128 - 64, y * 128 - 64, 0)
     terrain.getRoot().setTexture(TextureStage.getDefault(), self.showBase.loader.loadTexture("./grass-texture.png"))
     terrain.getRoot().setTexScale(TextureStage.getDefault(), 50)
     # Store the root NodePath for convenience
     root = terrain.getRoot()
     root.reparentTo(self.showBase.render)
     root.setSz(100)
     # Generate it.
     terrain.generate()
     return terrain
Example #18
0
    def __init__(self):
        ShowBase.__init__(self)  # initialise
        self.terrain = GeoMipTerrain("worldTerrain")  # create a terrain
        self.terrain.setHeightfield(
            "heightmapper-1567436259173.png")  # set the height map
        self.terrain.setColorMap(
            "TexturesCom_Moss0138_2_L.jpg")  # set the colour map
        self.terrain.setBruteforce(True)  # level of detail
        root = self.terrain.getRoot()  # capture root
        root.reparentTo(self.render)  # render from root
        root.setSz(80)  # maximum height
        self.terrain.generate()  # generate
        self.sphere = self.loader.loadModel("skysphere-1.egg")

        self.sphere.setScale(700)
        self.sphere.setPos(500, 500, 0)

        self.tex = self.loader.loadTexture("TexturesCom_Skies0282_L.jpg")
        self.sphere.setTexture(self.tex)

        self.sphere.reparentTo(self.render)
        self.setupLight()
    def create(self):
        self.test_texture = base.loader.loadTexture(self.settings["texture"])

        self.terrain = GeoMipTerrain(self.settings["name"])
        self.terrain.setHeightfield(self.settings["heightmap"])

        # Set terrain properties
        self.terrain.setBruteforce(False)
        self.terrain.setBlockSize(32)
        self.terrain.setNear(40)
        self.terrain.setFar(100)
        #self.terrain.setMinLevel(16)
        self.terrain.setFocalPoint(base.camera)
        self.terrain.setBorderStitching(True)

        self.terrain.getRoot().setSz(300)
        self.terrain.getRoot().setSx(Globals.TERRAIN_MULT)
        self.terrain.getRoot().setSy(Globals.TERRAIN_MULT)
        self.terrain.getRoot().setPos((self.settings["x"]*512)*Globals.TERRAIN_MULT, \
                  (self.settings["y"]*512)*Globals.TERRAIN_MULT, 0)
        self.terrain.getRoot().setTexture(self.test_texture)
        self.terrain.generate()
Example #20
0
    def __init__(self, length: int, width: int, view_ground: bool,
                 chassis_np: NodePath, pg_world: PGWorld):
        """
        :param length: Control resolution of this sensor
        :param width: Control resolution of this sensor
        :param view_ground: Lane line will be invisible when set to True
        :param chassis_np: The vehicle chassis to place this sensor
        :param pg_world: PG-World
        """
        self.view_ground = view_ground
        self.BUFFER_W = length
        self.BUFFER_H = width
        super(DepthCamera, self).__init__(self.BUFFER_W,
                                          self.BUFFER_H,
                                          Vec3(0.0, 0.8, 1.5),
                                          self.BKG_COLOR,
                                          pg_world=pg_world,
                                          parent_node=chassis_np)
        self.add_to_display(pg_world, self.default_region)
        self.cam.lookAt(0, 2.4, 1.3)
        self.lens.setFov(60)
        self.lens.setAspectRatio(2.0)

        # add shader for it
        if pg_world.world_config["headless_image"]:
            vert_path = AssetLoader.file_path("shaders",
                                              "depth_cam_gles.vert.glsl")
            frag_path = AssetLoader.file_path("shaders",
                                              "depth_cam_gles.frag.glsl")
        else:
            if is_mac():
                vert_path = AssetLoader.file_path("shaders",
                                                  "depth_cam_mac.vert.glsl")
                frag_path = AssetLoader.file_path("shaders",
                                                  "depth_cam_mac.frag.glsl")
            else:
                vert_path = AssetLoader.file_path("shaders",
                                                  "depth_cam.vert.glsl")
                frag_path = AssetLoader.file_path("shaders",
                                                  "depth_cam.frag.glsl")
        custom_shader = Shader.load(Shader.SL_GLSL,
                                    vertex=vert_path,
                                    fragment=frag_path)
        self.cam.node().setInitialState(
            RenderState.make(ShaderAttrib.make(custom_shader, 1)))

        if self.view_ground:
            self.ground = GeoMipTerrain("mySimpleTerrain")

            self.ground.setHeightfield(
                AssetLoader.file_path("textures", "height_map.png"))
            # terrain.setBruteforce(True)
            # # Since the terrain is a texture, shader will not calculate the depth information, we add a moving terrain
            # # model to enable the depth information of terrain
            self.ground_model = self.ground.getRoot()
            self.ground_model.reparentTo(chassis_np)
            self.ground_model.setPos(-128, 0, self.GROUND)
            self.ground_model.hide(BitMask32.allOn())
            self.ground_model.show(CamMask.DepthCam)
            self.ground.generate()
            pg_world.taskMgr.add(self.renew_pos_of_ground_mode,
                                 self.TASK_NAME,
                                 extraArgs=[chassis_np],
                                 appendTask=True)
Example #21
0
    def __init__(self):

        ShowBase.__init__(self)

        self.disableMouse()

        self.cam_away = 20
        self.cam_elevation = 5
        self.rot_rate = .5

        self.cam_dist = (self.cam_away**2 + self.cam_elevation**2)**.5

        #######
        self.environ = GeoMipTerrain("terrain")
        self.environ.setHeightfield("../terrain/first.png")
        self.environ.setColorMap("../terrain/first-c.png")
        self.environ.generate()
        self.environ.getRoot().setScale(1, 1, 100)
        self.environ.getRoot().setPos(0, 0, 0)
        self.environ.getRoot().reparentTo(render)
        self.environ.getRoot().setName("terrain")
        self.environ.getRoot().setCollideMask(BitMask32.bit(0))
        #######

        self.pandaActor = Actor("models/panda", {"walk": "models/panda-walk"})
        self.pandaActor.setScale(.5, .5, .5)
        self.pandaActor.setHpr(180, 0, 0)
        self.pandaActor.setPos(50, 50, 50)
        self.pandaActor.reparentTo(render)
        self.pandaActor.setPythonTag("moving", False)
        self.avatarYawRot = 0
        self.avatarPitchRot = 0

        #self.teapot = loader.loadModel("models/teapot")
        #self.teapot.setScale(1, 1, 1)
        #self.teapot.setPos(60, 60, 50)
        #self.teapot.reparentTo(render)

        self.cam.setHpr(0, 0, 0)

        self.taskMgr.add(self.updateTerrain, "update terrain", priority=35)

        self.keys = {"w": 0, "s": 0, "a": 0, "d": 0}

        self.accept("w", self.setKey, ["w", 1])
        self.accept("w-up", self.setKey, ["w", 0])
        self.accept("s", self.setKey, ["s", 1])
        self.accept("s-up", self.setKey, ["s", 0])
        self.accept("a", self.setKey, ["a", 1])
        self.accept("a-up", self.setKey, ["a", 0])
        self.accept("d", self.setKey, ["d", 1])
        self.accept("d-up", self.setKey, ["d", 0])
        self.accept("wheel_up", self.zoomCamera, [-1])
        self.accept("wheel_down", self.zoomCamera, [1])

        self.accept('window-event', self.handleWindowEvent)

        props = WindowProperties()
        props.setCursorHidden(True)
        base.win.requestProperties(props)

        self.last_mouse_x = self.win.getPointer(0).getX()
        #self.last_mouse_y = self.win.getPointer(0).getY()

        self.cTrav = CollisionTraverser()

        self.pandaGroundRay = CollisionRay(0, 0, 0, 0, 0, 1)
        self.pandaGroundRayNode = CollisionNode('pandaGroundRay')
        self.pandaGroundRayNode.addSolid(self.pandaGroundRay)
        self.pandaGroundRayNode.setFromCollideMask(BitMask32.bit(0))
        self.pandaGroundRayNode.setIntoCollideMask(BitMask32.allOff())
        self.pandaGroundRayNodepath = self.pandaActor.attachNewNode(
            self.pandaGroundRayNode)
        self.pandaGroundRayNodepath.show()
        self.pandaGroundCollisionHandler = CollisionHandlerFloor()
        self.pandaGroundCollisionHandler.addCollider(
            self.pandaGroundRayNodepath, self.pandaActor)
        self.cTrav.addCollider(self.pandaGroundRayNodepath,
                               self.pandaGroundCollisionHandler)
Example #22
0
    def load_map(self, map):
        """Load a map."""
        #Unload the current map first
        self.unload_map()

        #Locate the XML file for the map
        Logger.info("Loading map '{}'...".format(map))
        map_file = os.path.join(map, os.path.basename(map) + ".xml")

        if not os.path.exists(map_file):
            Logger.error("Failed to load map file '{}'.".format(map_file))
            return False

        #Load the map XML file
        xml = etree.parse(map_file)
        root = xml.getroot()

        for child in root:
            #Terrain?
            if child.tag == "terrain":
                #Validate terrain
                if not ("size" in child.attrib and "spawnpos" in child.attrib
                        and "heightmap" in child.attrib):
                    Logger.error(
                        "Terrain section must define 'size', 'spawnpos', and 'heightmap'."
                    )
                    return False

                #Load terrain
                self.size = parse_vec(child.attrib["size"], 3)
                self.spawnpos = parse_vec(child.attrib["spawnpos"], 2)
                heightmap = os.path.join(map, child.attrib["heightmap"])

                self.terrain = GeoMipTerrain("Terrain")
                self.terrain.set_block_size(64)
                self.terrain.set_bruteforce(True)

                if not self.terrain.set_heightfield(heightmap):
                    Logger.error("Failed to load heightmap for terrain.")
                    self.terrain = None
                    return False

                self.terrain_np = self.terrain.get_root()
                self.terrain_np.set_scale(self.size[0] / 512,
                                          self.size[1] / 512, self.size[2])
                tex = loader.load_texture(
                    "./data/textures/terrain/grass_tex2.png")
                self.terrain_np.set_texture(tex)
                self.terrain_np.set_tex_scale(TextureStage.get_default(),
                                              self.size[0] / 512,
                                              self.size[1] / 512)
                tex.set_wrap_u(Texture.WM_repeat)
                tex.set_wrap_v(Texture.WM_repeat)
                self.terrain_np.reparent_to(render)
                self.terrain.generate()

                base.camera.set_pos(self.size[0] / 2, self.size[1] / 2,
                                    self.size[2])

            #Portal?
            elif child.tag == "portal":
                #Validate portal
                if not ("pos" in child.attrib and "destmap" in child.attrib):
                    Logger.warning("Portal must define 'pos' and 'destmap'.")
                    continue

                #Load portal
                pos = parse_vec(child.attrib["pos"], 3)
                radius = parse_float(
                    child.attrib["radius"]) if "radius" in child.attrib else 1
                destmap = child.attrib["destmap"]
                self.add_portal(pos, radius, destmap)

            #Gate?
            elif child.tag == "gate":
                #Validate gate
                if not ("pos" in child.attrib and "destmap" in child.attrib
                        and "destvec" in child.attrib):
                    Logger.warning(
                        "Gate must define 'pos', 'destmap', and 'destvec'.")
                    continue

                #Load gate
                pos = parse_vec(child.attrib["pos"], 3)
                destmap = child.attrib["destmap"]
                destvec = parse_vec(child.attrib["destvec"], 3)
                material = child.attrib[
                    "material"] if "material" in child.attrib else ""
                self.add_gate(pos, destmap, destvec, material)

            #Object?
            elif child.tag == "object":
                #Validate object
                if not ("mesh" in child.attrib and "pos" in child.attrib):
                    Logger.warning("Object must define 'mesh' and 'pos'.")
                    continue

                #Load object
                mesh = child.attrib["mesh"]
                pos = parse_vec(child.attrib["pos"], 3)
                rot = parse_vec(child.attrib["rot"],
                                3) if "rot" in child.attrib else [0, 0, 0]
                scale = parse_vec(child.attrib["scale"],
                                  3) if "scale" in child.attrib else [1, 1, 1]
                material = child.attrib[
                    "material"] if "material" in child.attrib else ""
                sound = child.attrib["sound"] if "sound" in child.attrib else ""
                self.add_object(mesh, pos, rot, scale, material, sound)

            #Object Group?
            elif child.tag == "objectgroup":
                #Validate object group
                if not ("mesh" in child.attrib):
                    Logger.warning("Object group must define 'mesh'.")
                    continue

                #Load object group
                mesh = child.attrib["mesh"]
                material = child.attrib[
                    "material"] if "material" in child.attrib else ""
                self.load_object_group(child, mesh, material)

            #Unknown?
            else:
                Logger.warning(
                    "Unknown tag '{}' encountered in map '{}'.".format(
                        child.tag, map))

        #Map loaded
        Logger.info("Map '{}' loaded.".format(map))
        return True
Example #23
0
import sys
from panda3d.core import GeoMipTerrain
from pandac.PandaModules import TextureStage, Texture
import direct.directbase.DirectStart

if True:

    heightfieldIndex = 2

    #zScale = sys.argv[1]
    zScale = 60

    #heightfieldFile = sys.argv[heightfieldIndex]
    heightfieldFile = "a.png"

    terrain = GeoMipTerrain("hey")

    terrain.setHeightfield("terrain.png")
    terrain.setColorMap("terrain_texture.png")
    #terrain.setColorMap("colourmap.jpg")
    #terrain.setBlockSize(512)
    #terrain.setBruteforce(True)

    terrain.generate()

    root = terrain.getRoot()
    root.setSz(60)

    #textures1 = ["default_c.png", "maps/default_d.png", "maps/default_l.png",
    #			"textures/bigRockFace.png", "textures/hardDirt.png", "textures/grayRock.png", "textures/shortGrass.png"]
Example #24
0
    def setup_environment(self):
        # encapsulate some stuff

        # set up ambient lighting
        self.alight = AmbientLight('alight')
        self.alight.setColor(VBase4(0.1, 0.1, 0.1, 1))
        self.alnp = self.render.attachNewNode(self.alight)
        self.render.setLight(self.alnp)

        # set up a point light
        self.plight = PointLight('plight')
        self.plight.setColor(VBase4(0.8, 0.8, 0.8, 1))
        self.plnp = self.render.attachNewNode(self.plight)
        self.plnp.setPos(0, 0, 100)
        self.render.setLight(self.plnp)

        # set up terrain model
        self.terr_material = Material()
        self.terr_material.setShininess(1.0)
        self.terr_material.setAmbient(VBase4(0, 0, 0, 0))
        self.terr_material.setDiffuse(VBase4(1, 1, 1, 1))
        self.terr_material.setEmission(VBase4(0, 0, 0, 0))
        self.terr_material.setSpecular(VBase4(0, 0, 0, 0))

        # general scaling
        self.trrHorzSc = 4.0
        self.trrVertSc = 4.0  # was 4.0

        # Create sky
        #terrctr = self.trrHorzSc*65.0
        #self.setup_skybox(terrctr,800.0,2.0,0.3)

        self.skysphere = self.loader.loadModel("sky-forest/SkySphere.bam")
        self.skysphere.setBin('background', 1)
        self.skysphere.setDepthWrite(0)
        self.skysphere.reparentTo(self.render)

        # Load some textures
        self.grsTxtSc = 5
        self.numTreeTexts = 7

        # ground texture
        self.txtGrass = self.loader.loadTexture('tex/ground005.png')
        self.txtGrass.setWrapU(Texture.WM_mirror)
        self.txtGrass.setWrapV(Texture.WM_mirror)
        self.txtGrass.setMagfilter(Texture.FTLinear)
        self.txtGrass.setMinfilter(Texture.FTLinearMipmapLinear)

        # set up terrain texture stages
        self.TS1 = TextureStage('terrtext')
        self.TS1.setSort(0)
        self.TS1.setMode(TextureStage.MReplace)

        # Set up the GeoMipTerrain
        self.terrain = GeoMipTerrain("myDynamicTerrain")
        img = PNMImage(Filename('tex/bowl_height_map.png'))
        self.terrain.setHeightfield(img)
        self.terrain.setBruteforce(0)
        self.terrain.setAutoFlatten(GeoMipTerrain.AFMMedium)

        # Set terrain properties
        self.terrain.setBlockSize(32)
        self.terrain.setNear(50)
        self.terrain.setFar(500)
        self.terrain.setFocalPoint(self.camera)

        # Store the root NodePath for convenience
        self.root = self.terrain.getRoot()
        self.root.clearTexture()
        self.root.setTwoSided(0)
        self.root.setCollideMask(BitMask32.bit(0))
        self.root.setSz(self.trrVertSc)
        self.root.setSx(self.trrHorzSc)
        self.root.setSy(self.trrHorzSc)
        self.root.setMaterial(self.terr_material)
        self.root.setTexture(self.TS1, self.txtGrass)
        self.root.setTexScale(self.TS1, self.grsTxtSc, self.grsTxtSc)
        offset = 0.5 * img.getXSize() * self.trrHorzSc - 0.5
        self.root.setPos(-offset, -offset, 0)

        self.terrain.generate()
        self.root.reparentTo(self.render)

        # load tree billboards
        self.txtTreeBillBoards = []
        for a in range(self.numTreeTexts):
            fstr = 'trees/tree' + '%03d' % (a + 991)
            self.txtTreeBillBoards.append( \
                self.loader.loadTexture(fstr + '-color.png', fstr + '-opacity.png'))
            self.txtTreeBillBoards[a].setMinfilter(
                Texture.FTLinearMipmapLinear)

        #self.placePlantOnTerrain('trees',300,0,20,20,self.trrHorzSc,self.trrVertSc, \
        #    self.numTreeTexts,self.txtTreeBillBoards,'scene-def/trees.txt')
        self.setup_house()
        self.setup_vehicle()

        self.taskMgr.add(self.skysphereTask, "SkySphere Task")
    def setupHeightmap(self, name):

        # Automatically generate a heightmap mesh from a monochrome image.
        self.hmHeight = 120
        hmPath = "../maps/map" + name + "/map" + name + "-h.png"
        imPath = "../maps/map" + name + "/map" + name + "-i.png"
        smPath = "../maps/map" + name + "/map" + name + "-s.png"
        scmPath = "../maps/map" + name + "/map" + name + "-sc.png"
        print(hmPath)
        print(imPath)
        print(smPath)
        print(scmPath)
        hmImg = PNMImage(Filename(hmPath))
        hmShape = BulletHeightfieldShape(hmImg, self.hmHeight, ZUp)
        hmNode = BulletRigidBodyNode('Terrain')
        hmNode.addShape(hmShape)
        hmNode.setMass(0)
        self.hmNP = render.attachNewNode(hmNode)
        self.worldBullet.attachRigidBody(hmNode)
        self.hmOffset = hmImg.getXSize() / 2.0 - 0.5
        self.hmTerrain = GeoMipTerrain('gmTerrain')
        self.hmTerrain.setHeightfield(hmImg)

        # Optimizations and fixes
        self.hmTerrain.setBruteforce(
            True)  # I don't think this is actually needed.
        self.hmTerrain.setMinLevel(3)  # THIS is what triangulates the terrain.
        self.hmTerrain.setBlockSize(
            128)  # This does a pretty good job of raising FPS.
        # Level-of-detail (not yet working)
        # self.hmTerrain.setNear(40)
        # self.hmTerrain.setFar(200)

        self.hmTerrain.generate()

        self.hmTerrainNP = self.hmTerrain.getRoot()
        self.hmTerrainNP.setSz(self.hmHeight)
        self.hmTerrainNP.setPos(-self.hmOffset, -self.hmOffset,
                                -self.hmHeight / 2.0)
        self.hmTerrainNP.flattenStrong(
        )  # This only reduces the number of nodes; nothing to do with polys.
        self.hmTerrainNP.analyze()

        # Here begins the scenery mapping
        treeModel = loader.loadModel("../res/models/tree_1.egg")
        rockModel = loader.loadModel("../res/models/rock_1.egg")
        rock2Model = loader.loadModel("../res/models/rock_2.egg")
        rock3Model = loader.loadModel("../res/models/rock_3.egg")
        # caveModel = loader.loadModel("../res/models/cave_new.egg")
        # planeFrontModel = loader.loadModel("../res/models/plane_front.egg")
        # planeWingModel = loader.loadModel("../res/models/plane_wing.egg")
        texpk = loader.loadTexture(scmPath).peek()

        # GameObject nodepath for flattening
        self.objNP = render.attachNewNode("gameObjects")
        self.treeNP = self.objNP.attachNewNode("goTrees")
        self.rockNP = self.objNP.attachNewNode("goRocks")
        self.rock2NP = self.objNP.attachNewNode("goRocks2")
        self.rock3NP = self.objNP.attachNewNode("goRocks3")
        # self.caveNP = self.objNP.attachNewNode("goCave")
        # self.planeFrontNP = self.objNP.attachNewNode("goPlaneFront")
        # self.planeWingNP = self.objNP.attachNewNode("goPlaneWing")

        for i in range(0, texpk.getXSize()):
            for j in range(0, texpk.getYSize()):
                color = VBase4(0, 0, 0, 0)
                texpk.lookup(color,
                             float(i) / texpk.getXSize(),
                             float(j) / texpk.getYSize())
                if (int(color.getX() * 255.0) == 255.0):
                    newTree = self.treeNP.attachNewNode("treeNode")
                    treeModel.instanceTo(newTree)
                    newTree.setPos(
                        i - texpk.getXSize() / 2, j - texpk.getYSize() / 2,
                        self.hmTerrain.get_elevation(i, j) * self.hmHeight -
                        self.hmHeight / 2)
                    # newTree.setScale(randint(0,4))
                    newTree.setScale(2)

                if (int(color.getX() * 255.0) == 128):
                    newRock = self.rockNP.attachNewNode("newRock")
                    newRock.setPos(
                        i - texpk.getXSize() / 2, j - texpk.getYSize() / 2,
                        self.hmTerrain.get_elevation(i, j) * self.hmHeight -
                        self.hmHeight / 2)
                    rockModel.instanceTo(newRock)

                if (int(color.getX() * 255.0) == 77):
                    newRock2 = self.rock2NP.attachNewNode("newRock2")
                    newRock2.setPos(
                        i - texpk.getXSize() / 2, j - texpk.getYSize() / 2,
                        self.hmTerrain.get_elevation(i, j) * self.hmHeight -
                        self.hmHeight / 2)
                    rock2Model.instanceTo(newRock2)

                if (int(color.getX() * 255.0) == 102):
                    newRock3 = self.rock3NP.attachNewNode("newRock3")
                    newRock3.setPos(
                        i - texpk.getXSize() / 2, j - texpk.getYSize() / 2,
                        self.hmTerrain.get_elevation(i, j) * self.hmHeight -
                        self.hmHeight / 2)
                    rock3Model.instanceTo(newRock3)

                # if(int(color.getX() * 255.0) == 64):
                # newCave = self.caveNP.attachNewNode("newCave")
                # newCave.setPos(i - texpk.getXSize() / 2, j - texpk.getYSize() / 2, self.hmTerrain.get_elevation(i, j) * self.hmHeight - self.hmHeight / 2)
                # newCave.setScale(5)
                # newCave.setP(180)
                # caveModel.instanceTo(newCave)

                # if(int(color.getX() * 255.0) == 191):
                # newPlaneFront = self.planeFrontNP.attachNewNode("newPlaneFront")
                # newPlaneFront.setPos(i - texpk.getXSize() / 2, j - texpk.getYSize() / 2, self.hmTerrain.get_elevation(i, j) * self.hmHeight - self.hmHeight / 2)
                # newPlaneFront.setScale(6)
                # planeFrontModel.instanceTo(newPlaneFront)

                # if(int(color.getX() * 255.0) == 179):
                # newPlaneWing = self.planeWingNP.attachNewNode("newPlaneWing")
                # newPlaneWing.setPos(i - texpk.getXSize() / 2, j - texpk.getYSize() / 2, self.hmTerrain.get_elevation(i, j) * self.hmHeight - self.hmHeight / 2)
                # newPlaneWing.setScale(6)
                # newPlaneWing.setH(250)
                # newPlaneWing.setR(180)
                # newPlaneWing.setP(135)
                # planeWingModel.instanceTo(newPlaneWing)

        self.snowflakes = []

        for i in xrange(0, self.snowflakeCount):
            print("Call " + str(i))
            sf = SMCollect(self.worldBullet, self.worldObj,
                           self.snowflakePositions[i])
            self.snowflakes.append(sf)

        # render.flattenStrong()
        self.hmTerrainNP.reparentTo(render)

        # Here begins the attribute mapping
        ts = TextureStage("stage-alpha")
        ts.setSort(0)
        ts.setPriority(1)
        ts.setMode(TextureStage.MReplace)
        ts.setSavedResult(True)
        self.hmTerrainNP.setTexture(ts, loader.loadTexture(imPath, smPath))

        ts = TextureStage("stage-stone")
        ts.setSort(1)
        ts.setPriority(1)
        ts.setMode(TextureStage.MReplace)
        self.hmTerrainNP.setTexture(
            ts, loader.loadTexture("../res/textures/stone_tex.png"))
        self.hmTerrainNP.setTexScale(ts, 32, 32)

        ts = TextureStage("stage-ice")
        ts.setSort(2)
        ts.setPriority(1)
        ts.setCombineRgb(TextureStage.CMInterpolate, TextureStage.CSTexture,
                         TextureStage.COSrcColor, TextureStage.CSPrevious,
                         TextureStage.COSrcColor,
                         TextureStage.CSLastSavedResult,
                         TextureStage.COSrcColor)
        self.hmTerrainNP.setTexture(
            ts, loader.loadTexture("../res/textures/ice_tex.png"))
        self.hmTerrainNP.setTexScale(ts, 32, 32)

        ts = TextureStage("stage-snow")
        ts.setSort(3)
        ts.setPriority(0)
        ts.setCombineRgb(TextureStage.CMInterpolate, TextureStage.CSTexture,
                         TextureStage.COSrcColor, TextureStage.CSPrevious,
                         TextureStage.COSrcColor,
                         TextureStage.CSLastSavedResult,
                         TextureStage.COSrcAlpha)
        self.hmTerrainNP.setTexture(
            ts, loader.loadTexture("../res/textures/snow_tex_1.png"))
        self.hmTerrainNP.setTexScale(ts, 32, 32)

        # print(self.snowflakes)

        return hmNode
Example #26
0
    def generate(self):
        '''(Re)generate the entire terrain erasing any current changes'''
        factor = self.blockSize * self.chunkSize
        #print "Factor:", factor
        for terrain in self.terrains:
            terrain.getRoot().removeNode()
        self.terrains = []
        # Breaking master heightmap into subimages
        heightmaps = []
        self.xchunks = (self.heightfield.getXSize() - 1) / factor
        self.ychunks = (self.heightfield.getYSize() - 1) / factor
        #print "X,Y chunks:", self.xchunks, self.ychunks
        n = 0
        for y in range(0, self.ychunks):
            for x in range(0, self.xchunks):
                heightmap = PNMImage(factor + 1, factor + 1)
                heightmap.copySubImage(self.heightfield,
                                       0,
                                       0,
                                       xfrom=x * factor,
                                       yfrom=y * factor)
                heightmaps.append(heightmap)
                n += 1

        # Generate GeoMipTerrains
        n = 0
        y = self.ychunks - 1
        x = 0
        for heightmap in heightmaps:
            terrain = GeoMipTerrain(str(n))
            terrain.setHeightfield(heightmap)
            terrain.setBruteforce(self.bruteForce)
            terrain.setBlockSize(self.blockSize)
            terrain.generate()
            self.terrains.append(terrain)
            root = terrain.getRoot()
            root.reparentTo(self.root)
            root.setPos(n % self.xchunks * factor, (y) * factor, 0)

            # In order to texture span properly we need to reiterate through every vertex
            # and redefine the uv coordinates based on our size, not the subGeoMipTerrain's
            root = terrain.getRoot()
            children = root.getChildren()
            for child in children:
                geomNode = child.node()
                for i in range(geomNode.getNumGeoms()):
                    geom = geomNode.modifyGeom(i)
                    vdata = geom.modifyVertexData()
                    texcoord = GeomVertexWriter(vdata, 'texcoord')
                    vertex = GeomVertexReader(vdata, 'vertex')
                    while not vertex.isAtEnd():
                        v = vertex.getData3f()
                        t = texcoord.setData2f(
                            (v[0] + self.blockSize / 2 + self.blockSize * x) /
                            (self.xsize - 1),
                            (v[1] + self.blockSize / 2 + self.blockSize * y) /
                            (self.ysize - 1))
            x += 1
            if x >= self.xchunks:
                x = 0
                y -= 1
            n += 1
Example #27
0
    def setup(self):
        self.worldNP = render.attachNewNode('World')

        # World
        self.debugNP = self.worldNP.attachNewNode(BulletDebugNode('Debug'))
        self.debugNP.show()
        self.debugNP.node().showNormals(True)

        self.world = BulletWorld()
        self.world.setGravity(Vec3(0, 0, -9.81))
        self.world.setDebugNode(self.debugNP.node())

        # Box (dynamic)
        shape = BulletBoxShape(Vec3(0.5, 0.5, 0.5))

        np = self.worldNP.attachNewNode(BulletRigidBodyNode('Box'))
        np.node().setMass(1.0)
        np.node().addShape(shape)
        np.setPos(0, 0, 4)
        np.setCollideMask(BitMask32.allOn())

        self.world.attachRigidBody(np.node())

        self.boxNP = np  # For applying force & torque

        visualNP = loader.loadModel('models/box.egg')
        visualNP.clearModelNodes()
        visualNP.reparentTo(self.boxNP)

        # Heightfield (static)
        height = 8.0

        img = PNMImage(Filename('models/elevation.png'))
        shape = BulletHeightfieldShape(img, height, ZUp)
        shape.setUseDiamondSubdivision(True)

        np = self.worldNP.attachNewNode(BulletRigidBodyNode('Heightfield'))
        np.node().addShape(shape)
        np.setPos(0, 0, 0)
        np.setCollideMask(BitMask32.allOn())

        self.world.attachRigidBody(np.node())

        self.hf = np.node()  # To enable/disable debug visualisation

        self.terrain = GeoMipTerrain('terrain')
        self.terrain.setHeightfield(img)

        self.terrain.setBlockSize(32)
        self.terrain.setNear(50)
        self.terrain.setFar(100)
        self.terrain.setFocalPoint(base.camera)

        rootNP = self.terrain.getRoot()
        rootNP.reparentTo(render)
        rootNP.setSz(8.0)

        offset = img.getXSize() / 2.0 - 0.5
        rootNP.setPos(-offset, -offset, -height / 2.0)

        self.terrain.generate()
Example #28
0
    def setup(self):
        self.worldNP = render.attachNewNode('World')

        # World
        self.world = BulletWorld()
        self.world.setGravity(Vec3(0, 0, -9.81))

        #height map
        # Filename:
        # small ->  'Maps/HeightMapSmall.png'
        # big   ->  'Maps/HeightMapBig.png'
        img = PNMImage(Filename('Maps/HeightMapSmall.png'))
        shape = BulletHeightfieldShape(img, self.height, ZUp)
        shape.setUseDiamondSubdivision(True)

        np = self.worldNP.attachNewNode(BulletRigidBodyNode('Heightfield'))
        np.node().addShape(shape)
        np.setPos(0, 0, 0)
        np.setCollideMask(BitMask32.allOn())
        self.world.attachRigidBody(np.node())

        #adding Texture
        #setColorMap:
        #small ->   'Maps/TextureMapSmall.jpg'
        #big   ->   'Maps/TextureMapBig.jpg'
        self.terrain = GeoMipTerrain('terrain')
        self.terrain.setHeightfield(img)
        self.terrain.setColorMap('Maps/TextureMapSmall.jpg')
        self.terrain.setBruteforce(True)  # level of detail

        self.terrain.setBlockSize(32)
        self.terrain.setNear(50)
        self.terrain.setFar(100)
        self.terrain.setFocalPoint(base.camera)

        rootNP = self.terrain.getRoot()
        rootNP.reparentTo(render)
        rootNP.setSz(self.height)

        offset = img.getXSize() / 2.0 - 0.5
        rootNP.setPos(-offset, -offset, -self.height / 2.0)

        self.makeMapBorders(offset)
        self.terrain.generate()

        # creating vehicles
        #controlled vehicles
        self.controlVehicles = []
        self.controlVehicles.append(
            Vehicle(0, 00, 40, "B", self.worldNP, self.world))

        #vehicles goint to a specific point
        #self.squareVeh = Vehicle(0, 50, 40, "G", self.worldNP, self.world)
        #thread.start_new_thread(self.goSquare, (self.squareVeh, 100))

        #vehicles following user
        #self.followVehicles = []
        #self.followVehicles.append(Vehicle(-offset+10, -offset+10, 40, "R", self.worldNP, self.world))
        #self.followVehicles.append(Vehicle(offset-10, offset-10, 60, "R", self.worldNP, self.world))
        #for veh in self.followVehicles:
        #    thread.start_new_thread(follow, (veh, self.controlVehicles[0]))

        #vehicles for hill climbing
        self.hillVehicles = []
        self.hillVehicles.append(
            Vehicle(-offset + 10, -offset + 10, 40, "R", self.worldNP,
                    self.world))
        self.hillVehicles.append(
            Vehicle(offset - 10, offset - 10, 60, "R", self.worldNP,
                    self.world))
        for veh in self.hillVehicles:
            thread.start_new_thread(blindClimb, (veh, ))
Example #29
0
 def makeBlock(self,drawResourcesFactories,x,y,x1,y1,tileCenter,collision):
     drawResourcesFactory=drawResourcesFactories[self.LOD]
     tile=drawResourcesFactory.getTile()
     resources=drawResourcesFactory.getDrawResources(self.dataIndex[self.LOD])
     
     # Set up the GeoMipTerrain
     terrain = GeoMipTerrain("TerrainTile")
     heightTex=tile.bakedTile.renderMaps[self.specialMaps["height"]].tex
     heightTexSize=heightTex.getXSize()
     pnmImage=PNMImage()
     #heightTex.makeRamImage() # Makes it run without having ran image in advance, but it all ends up flat.
     
     heightTex.store(pnmImage)
     terrain.setHeightfield(pnmImage)
     
     
     # Set terrain properties
     terrain.setBruteforce(True)
     # Store the root NodePath for convenience
     root = terrain.getRoot()
     
     root.setPos(tile.bakedTile.x-tileCenter.getX(),tile.bakedTile.y-tileCenter.getY(),0)
     
     for t in self.texList:
         texScale=1.0/(t[1])
         root.setTexture(t[0],t[2])
         root.setShaderInput('tex2D_'+t[3],t[2])
         root.setTexScale(t[0],texScale*tile.tileScale)
         root.setTexOffset(t[0],(tile.getX() % t[1])*texScale,(tile.getY() % t[1])*texScale)
     
     for t in self.mapTexStages:
         tex=tile.bakedTile.renderMaps[t].tex
         
         root.setTexture(self.mapTexStages[t],tex)
         
         # Here we apply a transform to the textures so centers of the edge pixels fall on the edges of the tile
         # Normally the edges of the edge pixels would fall on the edges of the tiles.
         # The benifits of this should be visible, though they have not been varified sucessfully yet.
         # In fact, these transforms appear to not do anything.
         # This is troubling, but the problem they are supposed to fix is currently invisible as well.
         #size=tex.getXSize()
         #margin=bakery.texMargin(size)
         #tile.setTexOffset(t,-margin,-margin)
         #tile.setTexScale(t,float(size+margin*2)/size)
         
     root.setShaderInput("offset",tile.bakedTile.x,tile.bakedTile.y,0.0,0.0)
     root.setShaderInput("scale",tile.bakedTile.scale)
     
     xyScale=float(tile.tileScale)/(heightTexSize-1)
     root.setScale(xyScale,xyScale,self.heightScale)
     if self.shader: root.setShader(self.shader)
     # Generate it.
     terrain.generate()
     
     
     #root.flattenLight()
     if collision:
         col=collisionUtil.rebuildGeomNodesToColPolys(root,collision)
         col.setCollideMask(collisionUtil.groundMask)
         col.reparentTo(collision)
     
     return root