Exemplo n.º 1
0
	def __init__(self, *args, **kwargs):
		print("Hello from __init__")
		self.loader = Loader(self)
		panda = self.loader.loadModel("panda")
		# `render` here is a global variable injected from C++
		panda.reparentTo(render)
		panda.setPos(0, 50, 0)
Exemplo n.º 2
0
    def __init__(self):
        self.loadDefaultConfig()
        self.loadLocalConfig()

        if ConfigVariableBool("want-pstats", False):
            PStatClient.connect()

        # Set up some global objects
        self.globalClock = ClockObject.getGlobalClock()
        # We will manually manage the clock
        self.globalClock.setMode(ClockObject.MSlave)
        builtins.globalClock = self.globalClock

        self.vfs = VirtualFileSystem.getGlobalPtr()

        # For tasks that run every application frame
        self.taskMgr = TaskManagerGlobal.taskMgr
        builtins.taskMgr = self.taskMgr

        # For tasks that run every simulation tick
        self.simTaskMgr = Task.TaskManager()
        self.simTaskMgr.mgr = AsyncTaskManager("sim")
        builtins.simTaskmgr = self.simTaskMgr

        self.eventMgr = EventManagerGlobal.eventMgr
        builtins.eventMgr = self.eventMgr

        self.messenger = MessengerGlobal.messenger
        builtins.messenger = self.messenger

        self.loader = Loader(self)
        builtins.loader = self.loader

        builtins.base = self

        # What is the current frame number?
        self.frameCount = 0
        # Time at beginning of current frame
        self.frameTime = self.globalClock.getRealTime()
        # How long did the last frame take.
        self.deltaTime = 0

        #
        # Variables pertaining to simulation ticks.
        #

        self.prevRemainder = 0
        self.remainder = 0
        # What is the current overall simulation tick?
        self.tickCount = 0
        # How many ticks are we going to run this frame?
        self.totalTicksThisFrame = 0
        # How many ticks have we run so far this frame?
        self.currentTicksThisFrame = 0
        # What tick are we currently on this frame?
        self.currentFrameTick = 0
        # How many simulations ticks are we running per-second?
        self.ticksPerSec = 60
        self.intervalPerTick = 1.0 / self.ticksPerSec
Exemplo n.º 3
0
    def __init__(self):
        ShowBase.__init__(self)
        props = WindowProperties()
        props.setTitle("Big Bang")
        self.win.requestProperties(props)
        self.win.setClearColor((0, 0, 0, 1))
        self.disableMouse()
        self.locked = False
        lens = PerspectiveLens()
        lens.set_fov(70)
        lens.setNear(0.01)
        self.cam.node().setLens(lens)    
        render.setAntialias(AntialiasAttrib.MMultisample)
        b=OnscreenImage(parent=render2d, image="space.png")
        base.cam.node().getDisplayRegion(0).setSort(20)

        loader = Loader(self)
        bang = loader.loadModel("sphere.obj")
        bang.setScale((0.15, 0.15, 0.15))
        pos = (0, 4, 0)
        bang.setPos(pos)
        bang.reparentTo(render)
        sizeInterval1 = bang.scaleInterval(3,
        							 Point3(5, 5, 5),
        							 startScale=Point3(0.001, 0.001, 0.001))
        sizeInterval2 = bang.scaleInterval(0.1,
        							 Point3(0.001, 0.001, 0.001),
        							 startScale=Point3(5,5,5))
        sizeInterval3 = bang.scaleInterval(1,
        							 Point3(0.001, 0.001, 0.001),
        							 startScale=Point3(0.001, 0.001, 0.001))
        sizeInterval4 = bang.scaleInterval(0.1,
        							 Point3(0.1, 0.1, 1),
        							 startScale=Point3(0.1, 0.1, 0.1))
        sizeInterval5 = bang.scaleInterval(0.1,
        							 Point3(1, 0.1, 0.1),
        							 startScale=Point3(0.1, 0.1, 0.1))
        #posInterval1 = bang.posInterval(3,
        #							 Point3(0, 8, 0),
        #							 startPos=Point3(pos))
        #posInterval2 = bang.posInterval(0.1,
        #							 Point3(pos),
        #							 startPos=Point3(0, 8, 0))
        #posInterval3 = bang.posInterval(1,
        #							 Point3(pos),
        #							 startPos=Point3(pos))
        #posInterval4 = bang.posInterval(0.1,
        #							 Point3(pos),
        #							 startPos=Point3(pos))
        grow = Sequence(sizeInterval1, sizeInterval2, sizeInterval3, sizeInterval4, sizeInterval5,
        						  name="grow")
        grow.loop()
        #move = Sequence(posInterval1, posInterval2, posInterval3, posInterval4, posInterval4,
        #						  name="move")
        #move.loop()

        self.accept("e", self.lockMouse)
        # Add the spinCameraTask procedure to the task manager.
        self.taskMgr.add(self.cameraControl, "CameraControl")
Exemplo n.º 4
0
    def prepare(self, curr_cond, stim_period=''):
        self.curr_cond = curr_cond if stim_period == '' else curr_cond[
            stim_period]
        self.period = stim_period

        if not self.curr_cond:
            self.isrunning = False
        self.background_color = self.curr_cond['background_color']

        # set background color
        self.set_background_color(*self.curr_cond['background_color'])

        # Set Ambient Light
        self.ambientLight.setColor(self.curr_cond['ambient_color'])

        # Set Directional Light
        self.lights = dict()
        self.lightsNP = dict()
        for idx, light_idx in enumerate(iterable(self.curr_cond['light_idx'])):
            self.lights[idx] = core.DirectionalLight('directionalLight_%d' %
                                                     idx)
            self.lightsNP[idx] = self.render.attachNewNode(self.lights[idx])
            self.render.setLight(self.lightsNP[idx])
            self.lights[idx].setColor(tuple(
                self.curr_cond['light_color'][idx]))
            self.lightsNP[idx].setHpr(*self.curr_cond['light_dir'][idx])

        # Set Object tasks
        self.objects = dict()
        for idx, obj in enumerate(iterable(self.curr_cond['obj_id'])):
            self.objects[idx] = Agent(self, self.get_cond('obj_', idx))

        if 'movie_name' in self.curr_cond:
            self.movie = True
            loader = Loader(self)
            file_name = self.get_clip_info(self.curr_cond, 'file_name')
            self.mov_texture = loader.loadTexture(self.movie_path +
                                                  file_name[0])
            cm = CardMaker("card")
            tx_scale = self.mov_texture.getTexScale()
            cm.setFrame(-1, 1, -tx_scale[1] / tx_scale[0],
                        tx_scale[1] / tx_scale[0])
            self.movie_node = NodePath(cm.generate())
            self.movie_node.setTexture(self.mov_texture, 1)
            self.movie_node.setPos(0, 100, 0)
            self.movie_node.setTexScale(TextureStage.getDefault(),
                                        self.mov_texture.getTexScale())
            self.movie_node.setScale(48)
            self.movie_node.reparentTo(self.render)

        if not self.isrunning:
            self.timer.start()
            self.isrunning = True
Exemplo n.º 5
0
def draw_cicle(x, y, r, col=None, parent=None):
    base = app.get_show_base()
    loader = Loader(base)
    model = loader.loadModel("data/geom/circle.egg")

    col = draw_get_color(col, color_format="rgba")

    if parent is None:
        parent = builtins.pixel2d

    model.reparentTo(parent)

    model.setPos(x, 0, -y)
    model.setScale(r, 1, r)

    # model.setColorScale(1, 0, 0, 1)
    model.setColor(col)

    return model
Exemplo n.º 6
0
    def __init__(self, base):
        # Load texture
        tex = Loader(base).loadTexture((Path(path.realpath(__file__)).parent.parent.parent / "res/images/checkerboard.png").absolute())
        tex.setMagfilter(SamplerState.FT_nearest)
        tex.setMinfilter(SamplerState.FT_nearest)

        # Set up vertex data
        vdata = GeomVertexData("floor_data", GeomVertexFormat.get_v3t2(), Geom.UHStatic)
        vdata.setNumRows(6)
        vertex = GeomVertexWriter(vdata, "vertex")
        texcoord = GeomVertexWriter(vdata, "texcoord")

        vertex.addData3(-5, -5, 0)
        texcoord.addData3(0, 0, 0)
        vertex.addData3(-5, 5, 0)
        texcoord.addData3(0, 10, 0)
        vertex.addData3(5, 5, 0)
        texcoord.addData3(10, 10, 0)

        vertex.addData3(5, 5, 0)
        texcoord.addData3(10, 10, 0)
        vertex.addData3(5, -5, 0)
        texcoord.addData3(10, 0, 0)
        vertex.addData3(-5, -5, 0)
        texcoord.addData3(0, 0, 0)

        # Create primitive
        prim = GeomTriangles(Geom.UHStatic)
        prim.addVertices(0, 1, 2)
        prim.addVertices(3, 4, 5)
        geom = Geom(vdata)
        geom.add_primitive(prim)

        # Initialize geometry node
        GeomNode.__init__(self, "floor")
        attrib = TextureAttrib.make(tex)
        state = RenderState.make(attrib)
        self.addGeom(geom, state)
Exemplo n.º 7
0
#  GNU Lesser General Public License for more details.
#
#  You should have received a copy of the GNU Lesser General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>

# Panda3D modules.
from direct.showbase.Loader import Loader
from panda3d.core import SamplerState, Texture, TextureStage

# Global rendering options.
ANISOTROPIC_FILTERING = 4
MIPMAP = True
MIRROR = True

# Instanciate a Panda3D loader.
loader = Loader(None)


def load(path, anisotropic=None, mipmap=None, mirror=None):
    """Load a texture and apply some rendering properties.
    """
    if anisotropic is None: anisotropic = ANISOTROPIC_FILTERING
    if mipmap is None: mipmap = MIPMAP
    if mirror is None: mirror = MIRROR

    texture = loader.loadTexture(path)
    texture.setAnisotropicDegree(anisotropic)
    if mipmap:
        texture.setMagfilter(SamplerState.FT_linear_mipmap_linear)
        texture.setMinfilter(SamplerState.FT_linear_mipmap_linear)
    if mirror:
Exemplo n.º 8
0
 def load_font(font_path):
     font_folder_path = Path(
         path.realpath(__file__)).parent.parent.parent.parent / "res/fonts"
     font_loader = Loader(GUIFontLoader.base)
     return font_loader.loadFont(
         Filename(font_folder_path / font_path).cStr())
Exemplo n.º 9
0
    def gen_geom(self, mesh_json):
        # Create vertex format
        geom_array = GeomVertexArrayFormat()
        geom_array.add_column("vertex", 3, Geom.NTFloat32, Geom.CPoint)
        has_normals = False
        has_texcoords = False
        has_weights = False
        if "normals" in mesh_json:
            geom_array.add_column("normal", 3, Geom.NTFloat32, Geom.CNormal)
            has_normals = True
        if "texcoords" in mesh_json:
            geom_array.add_column("texcoord", 3, Geom.NTFloat32,
                                  Geom.CTexcoord)
            has_texcoords = True
        if "weights" in mesh_json:
            geom_array.add_column("joint", 4, Geom.NTUint8, Geom.CIndex)
            geom_array.add_column("weight", 4, Geom.NTFloat32, Geom.COther)
            has_weights = True
        geom_format = GeomVertexFormat()
        geom_format.add_array(geom_array)
        geom_format = GeomVertexFormat.register_format(geom_format)

        # Set up vertex data
        vdata = GeomVertexData(
            str(random.randint(0, 255)) + "_vdata", geom_format, Geom.UHStatic)
        vcount = len(mesh_json["vertices"]) // 3
        vdata.setNumRows(vcount)
        vertex = GeomVertexWriter(vdata, "vertex")

        for i in range(vcount):
            vertex.addData3(mesh_json["vertices"][3 * i],
                            mesh_json["vertices"][3 * i + 1],
                            mesh_json["vertices"][3 * i + 2])
        if has_normals:
            normal = GeomVertexWriter(vdata, "normal")
            for i in range(vcount):
                normal.addData3(mesh_json["normals"][3 * i],
                                mesh_json["normals"][3 * i + 1],
                                mesh_json["normals"][3 * i + 2])
        if has_texcoords:
            texcoord = GeomVertexWriter(vdata, "texcoord")
            for i in range(vcount):
                texcoord.addData2(mesh_json["texcoords"][2 * i],
                                  mesh_json["texcoords"][2 * i + 1])
        if has_weights:
            joint = GeomVertexWriter(vdata, "joint")
            weight = GeomVertexWriter(vdata, "weight")
            for i in range(vcount):
                joint_count = len(mesh_json["joints"][i])
                joint.addData4(
                    0 if joint_count < 1 else mesh_json["joints"][i][0],
                    0 if joint_count < 2 else mesh_json["joints"][i][1],
                    0 if joint_count < 3 else mesh_json["joints"][i][2],
                    0 if joint_count < 4 else mesh_json["joints"][i][3])
                weight.addData4(
                    0 if joint_count < 1 else mesh_json["weights"][i][0],
                    0 if joint_count < 2 else mesh_json["weights"][i][1],
                    0 if joint_count < 3 else mesh_json["weights"][i][2],
                    0 if joint_count < 4 else mesh_json["weights"][i][3])

        # Create primitive
        prim = GeomTriangles(Geom.UHStatic)
        for i in range(vcount // 3):
            prim.addVertices(3 * i, 3 * i + 1, 3 * i + 2)
        geom = Geom(vdata)
        geom.add_primitive(prim)

        # Load texture
        tex = None
        if "texture" in mesh_json:
            tex = Loader(EComponent.base).loadTexture(
                (Path("resources") / mesh_json["texture"]).absolute())
            tex.setMagfilter(SamplerState.FT_nearest)
            tex.setMinfilter(SamplerState.FT_nearest)

        # Create new geometry node
        geom_node = GeomNode(str(random.randint(0, 255)) + "_node")
        if tex is None:
            geom_node.addGeom(geom)
        else:
            attrib = TextureAttrib.make(tex)
            state = RenderState.make(attrib)
            geom_node.addGeom(geom, state)
        if EComponent.panda_root_node is not None:
            self.geom_path = EComponent.panda_root_node.attach_new_node(
                geom_node)
            self.geom_path.set_shader_input("object_id", self.object_id)

        # Set shader
        if has_weights and self.geom_path is not None:
            self.geom_path.setTag("shader type", "skinned")
            bone_mats = PTA_LMatrix4f()
            for _ in range(100):
                bone_mats.push_back(helper.np_mat4_to_panda(np.identity(4)))
            self.geom_path.set_shader_input(f"boneMats", bone_mats)

            # Disable culling
            self.geom_path.node().setBounds(OmniBoundingVolume())
            self.geom_path.node().setFinal(True)
Exemplo n.º 10
0
def loader():
    return Loader(base=None)
Exemplo n.º 11
0
    def __init__(
        self,
        agent_interfaces,
        traffic_sim,
        envision: EnvisionClient = None,
        visdom: VisdomClient = None,
        timestep_sec=0.1,
        reset_agents_only=False,
        zoo_workers=None,
        auth_key=None,
    ):
        '''
        try:
            super().__init__(self, windowType="offscreen")
        except Exception as e:
            # Known reasons for this failing:
            raise Exception(
                "Display is not found. Try running with different configurations of "
                "`export Display=` using `:0`, `:1`... If this does not work please consult "
                "the documentation."
            ) from e
        '''

        self.loader = Loader(self)
        gltf.patch_loader(self.loader)

        self._log = logging.getLogger(self.__class__.__name__)
        self.__configAspectRatio = ConfigVariableDouble('aspect-ratio',
                                                        0).getValue()
        self._is_setup = False
        self._scenario: Scenario = None
        self._envision: EnvisionClient = envision
        self._visdom: VisdomClient = visdom
        self._timestep_sec = timestep_sec
        self._traffic_sim = traffic_sim
        self._motion_planner_provider = MotionPlannerProvider()
        self._traffic_history_provider = TrafficHistoryProvider()
        self._providers = [
            self._traffic_sim,
            self._motion_planner_provider,
            self._traffic_history_provider,
        ]

        # We buffer provider state between steps to compensate for TRACI's timestep delay
        self._last_provider_state = None
        self._reset_agents_only = reset_agents_only  # a.k.a "teleportation"
        self._imitation_learning_mode = False

        self.finalExitCallbacks = []

        # Global clock always proceeds by a fixed dt on each tick
        from direct.task.TaskManagerGlobal import taskMgr
        self.taskMgr = taskMgr
        self.task_mgr = taskMgr
        self.taskMgr.clock.setMode(ClockObject.M_non_real_time)
        self.taskMgr.clock.setDt(timestep_sec)
        self._elapsed_sim_time = 0

        self.engine = GraphicsEngine.get_global_ptr()

        self.graphicsEngine = self.engine
        fb_prop = FrameBufferProperties()
        fb_prop.rgb_color = 1
        fb_prop.color_bits = 3 * 8
        fb_prop.back_buffers = 1
        self.pipe = GraphicsPipeSelection.get_global_ptr().make_default_pipe()

        flags = GraphicsPipe.BFFbPropsOptional
        flags = flags | GraphicsPipe.BFRefuseWindow
        self.win = self.engine.make_output(
            self.pipe,
            name="window",
            sort=0,
            fb_prop=fb_prop,
            win_prop=WindowProperties(size=(800, 600)),
            flags=flags)

        #self.setBackgroundColor(0, 0, 0, 1)
        #self.win.set_clear_color_active(True)
        #self.win.set_clear_clolor((0.5,0.5,0.5,1))

        self.frameRateMeter = None
        # Displayed framerate is misleading since we are not using a realtime clock
        self.setFrameRateMeter(False)

        self.render = NodePath("render")
        #self.cam = self.render.attach_new_node(Camera("camera"))
        #self.cam.node().set_lens(PerspectiveLens())
        self.camera = None
        self.camList = []
        self.mouse2cam = NodePath(Transform2SG('mouse2cam'))

        self.render.setAttrib(RescaleNormalAttrib.makeDefault())

        self.render.setTwoSided(0)
        self.backfaceCullingEnabled = 1
        self.textureEnabled = 1
        self.wireframeEnabled = 0

        # For macOS GUI. See our `BulletClient` docstring for details.
        # from .utils.bullet import BulletClient
        # self._bullet_client = BulletClient(pybullet.GUI)
        self._bullet_client = bc.BulletClient(pybullet.DIRECT)
        self._pybullet_action_spaces = {
            ActionSpaceType.Continuous,
            ActionSpaceType.Lane,
            ActionSpaceType.ActuatorDynamic,
            ActionSpaceType.LaneWithContinuousSpeed,
            ActionSpaceType.Trajectory,
            ActionSpaceType.MPC,
        }

        # Set up indices
        self._agent_manager = AgentManager(agent_interfaces, zoo_workers,
                                           auth_key)
        self._vehicle_index = VehicleIndex()

        # TODO: Should not be stored in SMARTS
        self._vehicle_collisions = defaultdict(
            list)  # list of `Collision` instances
        self._vehicle_states = []

        self._bubble_manager = None
        self._trap_manager: TrapManager = None

        # SceneGraph-related setup
        self._root_np = None
        self._vehicles_np = None
        self._road_network_np = None
        self._ground_bullet_id = None
Exemplo n.º 12
0
    def __init__(self):
        DirectObject.__init__(self)

        if ConfigVariableBool("want-pstats", False):
            PStatClient.connect()

        self.docTitle = ""
        self.viewportName = ""

        self.renderRequested = False

        ###################################################################
        # Minimal emulation of ShowBase glue code. Note we're not using
        # ShowBase because there's too much going on in there that assumes
        # too much (one camera, one lens, one aspect2d, lots of bloat).

        self.graphicsEngine = GraphicsEngine.getGlobalPtr()
        self.pipe = GraphicsPipeSelection.getGlobalPtr().makeDefaultPipe()
        if not self.pipe:
            self.notify.error("No graphics pipe is available!")
            return

        self.globalClock = ClockObject.getGlobalClock()
        # Since we have already started up a TaskManager, and probably
        # a number of tasks; and since the TaskManager had to use the
        # TrueClock to tell time until this moment, make sure the
        # globalClock object is exactly in sync with the TrueClock.
        trueClock = TrueClock.getGlobalPtr()
        self.globalClock.setRealTime(trueClock.getShortTime())
        self.globalClock.tick()
        builtins.globalClock = self.globalClock

        self.loader = Loader(self)
        self.graphicsEngine.setDefaultLoader(self.loader.loader)
        builtins.loader = self.loader

        self.taskMgr = taskMgr
        builtins.taskMgr = self.taskMgr

        self.dgTrav = DataGraphTraverser()

        self.dataRoot = NodePath("data")
        self.hidden = NodePath("hidden")

        self.aspect2d = NodePath("aspect2d")
        builtins.aspect2d = self.aspect2d

        # Messages that are sent regardless of the active document.
        self.messenger = messenger
        builtins.messenger = self.messenger

        self.eventMgr = eventMgr
        builtins.eventMgr = self.eventMgr
        self.eventMgr.restart()

        builtins.base = self
        builtins.hidden = self.hidden

        ###################################################################

        self.clickTrav = CollisionTraverser()

        # All open documents.
        self.documents = []
        # The focused document.
        self.document = None

        TextNode.setDefaultFont(loader.loadFont("models/fonts/consolas.ttf"))

        self.initialize()
Exemplo n.º 13
0
    def __init__(self):
        ShowBase.__init__(self)
        props = WindowProperties()
        props.setTitle("The Rat Cave")
        self.win.requestProperties(props)
        self.win.setClearColor((0.5, 0.5, 0.9, 1.0))
        self.disableMouse()
        self.locked = False
        lens = PerspectiveLens()
        lens.set_fov(70)
        self.cam.node().setLens(lens)
        self.position = [30, 30, 30]
        self.velocity = [0, 0, 0]
        self.setFrameRateMeter(True)
        self.myFog = Fog("Fog Name")
        self.myFog.setColor(0.5, 0.5, 0.9)
        self.myFog.setExpDensity(0.005)
        render.setFog(self.myFog)
        #cool bg
        #b=OnscreenImage(parent=render2d, image="space.png")
        #base.cam.node().getDisplayRegion(0).setSort(20)

        render.setAntialias(AntialiasAttrib.MMultisample)

        debugNode = BulletDebugNode('Debug')
        debugNode.showWireframe(True)
        debugNode.showConstraints(True)
        debugNode.showBoundingBoxes(False)
        debugNode.showNormals(False)
        debugNP = render.attachNewNode(debugNode)
        debugNP.show()

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

        loader = Loader(self)
        myShader = Shader.load(Shader.SL_GLSL,
                               vertex="vertshader.vert",
                               fragment="fragshader.frag")
        floorMesh = BulletTriangleMesh()

        texs = [
            loader.loadTexture("flatstone.png"),
            loader.loadTexture("flatstone2.png"),
            loader.loadTexture("flatgrass.png"),
            loader.loadTexture("flatgrass2.png"),
            loader.loadTexture("flatrock.png"),
            loader.loadTexture("flatrock2.png"),
            loader.loadTexture("flatsnow.png"),
            loader.loadTexture("flatsand.png"),
            loader.loadTexture("flatsand2.png")
        ]
        hmap = generator.generate(200, 200, 50, 0.01, 5)
        groundTypes = [[] for x in range(9)]
        for thing in hmap:
            groundTypes[thing[3]].append(thing[0:3])
        for i in range(len(groundTypes)):
            if len(groundTypes[i]) == 0:
                continue
            format = GeomVertexFormat.get_v3n3t2()
            format = GeomVertexFormat.registerFormat(format)
            vdata = GeomVertexData('name', format, Geom.UHStatic)
            vdata.setNumRows(3)
            vertex = GeomVertexWriter(vdata, 'vertex')
            normal = GeomVertexWriter(vdata, 'normal')
            texcoord = GeomVertexWriter(vdata, 'texcoord')
            prim = GeomTriangles(Geom.UHStatic)
            for grid in groundTypes[i]:
                v0 = (grid[0][0], grid[0][2], grid[0][1])
                vertex.addData3(v0)
                if grid[1][2] < 0:
                    normal.addData3(grid[1][0], grid[1][2], grid[1][1])
                else:
                    normal.addData3(-grid[1][0], -grid[1][2], -grid[1][1])
                texcoord.addData2(grid[2][0], grid[2][1])
                v1 = (grid[0][3], grid[0][5], grid[0][4])
                vertex.addData3(v1)
                if grid[1][5] < 0:
                    normal.addData3(grid[1][3], grid[1][5], grid[1][4])
                else:
                    normal.addData3(-grid[1][3], -grid[1][5], -grid[1][4])
                texcoord.addData2(grid[2][2], grid[2][3])
                v2 = (grid[0][6], grid[0][8], grid[0][7])
                vertex.addData3(v2)
                if grid[1][8] < 0:
                    normal.addData3(grid[1][6], grid[1][8], grid[1][7])
                else:
                    normal.addData3(-grid[1][6], -grid[1][8], -grid[1][7])
                texcoord.addData2(grid[2][4], grid[2][5])
                floorMesh.addTriangle(v0, v1, v2)
                prim.add_next_vertices(3)
            geom = Geom(vdata)
            geom.addPrimitive(prim)
            node = GeomNode('gnode')
            node.addGeom(geom)
            nodePath = render.attachNewNode(node)
            nodePath.setTexture(texs[i])
            nodePath.setShader(myShader)
        vdata2 = GeomVertexData('wata', format, Geom.UHStatic)
        vdata2.setNumRows(3)
        prim2 = GeomTriangles(Geom.UHStatic)
        vertex2 = GeomVertexWriter(vdata2, 'vertex')
        normal2 = GeomVertexWriter(vdata2, 'normal')
        texcoord2 = GeomVertexWriter(vdata2, 'texcoord')
        vertex2.addData3((0, 0, 0))
        vertex2.addData3((200, 0, 0))
        vertex2.addData3((0, 200, 0))
        normal2.addData3((0, 0, 1))
        normal2.addData3((0, 0, 1))
        normal2.addData3((0, 0, 1))
        texcoord2.addData2((0, 0))
        texcoord2.addData2((1, 0))
        texcoord2.addData2((0, 1))
        prim2.addNextVertices(3)
        vertex2.addData3((200, 200, 0))
        vertex2.addData3((0, 200, 0))
        vertex2.addData3((200, 0, 0))
        normal2.addData3((0, 0, 1))
        normal2.addData3((0, 0, 1))
        normal2.addData3((0, 0, 1))
        texcoord2.addData2((1, 1))
        texcoord2.addData2((0, 1))
        texcoord2.addData2((1, 0))
        prim2.addNextVertices(3)
        water = Geom(vdata2)
        water.addPrimitive(prim2)
        waterNode = GeomNode('water')
        waterNode.addGeom(water)
        waterNodePath = render.attachNewNode(waterNode)
        waterNodePath.setTransparency(True)
        waterNodePath.setTexture(loader.loadTexture("water.png"))
        floorMeshShape = BulletTriangleMeshShape(floorMesh, dynamic=False)
        fNode = BulletRigidBodyNode('floor')
        fNode.addShape(floorMeshShape)
        self.floorPhysNode = render.attachNewNode(fNode)
        self.world.attachRigidBody(fNode)
        for i in range(25):
            rat = loader.loadModel("deer.obj")
            rat.setScale((0.003, 0.003, 0.003))
            rat.setHpr((0, 90, 0))
            rat.setPos((0, 0, -0.8))
            rat.setTexture(texs[5])

            shape = BulletSphereShape(1)
            node = BulletRigidBodyNode('ratBox')
            #node.setAngularFactor((0,0,1))
            node.setMass(10.0)
            node.addShape(shape)
            node.setActive(False)
            #node.friction = 1
            np = render.attachNewNode(node)
            np.setPos((i % 5) * 2 + 40, int(i / 5) * 2 + 40, 50)
            self.world.attachRigidBody(node)
            rat.flattenLight()
            rat.reparentTo(np)
            #posInterval1 = rat.hprInterval(0.1,
            #							 Point3(10, 90, 0),
            #							 startHpr=Point3(-10, 90, 0))
            #posInterval2 = rat.hprInterval(0.1,
            #							 Point3(-10, 90, 0),
            #							 startHpr=Point3(10,90,0))
            #pandaPace = Sequence(posInterval1, posInterval2,
            #						  name="pandaPace" + str(i))
            #pandaPace.loop()
            self.ratto = np
        self.deer = loader.loadModel("rat.obj")
        self.deer.setScale((0.15, 0.15, 0.15))
        self.deer.setHpr((0, 90, 0))
        self.deer.setPos((0, 0, -2))
        self.deerShape = BulletBoxShape((3, 1, 3))
        self.deerNode = BulletRigidBodyNode('deerBox')
        self.deerNode.setAngularFactor((0, 0, 1))
        self.deerNode.setMass(10.0)
        self.deerNode.setFriction(1)
        self.deerNode.addShape(self.deerShape)
        self.deerNodePath = render.attachNewNode(self.deerNode)
        self.deerNodePath.setPos((30, 30, 130))
        self.world.attachRigidBody(self.deerNode)
        self.deer.reparentTo(self.deerNodePath)

        self.keyMap = {
            "w": False,
            "s": False,
            "a": False,
            "d": False,
            "space": False,
            "lshift": False,
            "p": False,
            "o": False
        }
        self.accept("w", self.setKey, ["w", True])
        self.accept("s", self.setKey, ["s", True])
        self.accept("a", self.setKey, ["a", True])
        self.accept("d", self.setKey, ["d", True])
        self.accept("space", self.setKey, ["space", True])
        self.accept("lshift", self.setKey, ["lshift", True])
        self.accept("e", self.lockMouse)
        self.accept("p", self.setKey, ["p", True])
        self.accept("o", self.setKey, ["o", True])

        self.accept("w-up", self.setKey, ["w", False])
        self.accept("s-up", self.setKey, ["s", False])
        self.accept("a-up", self.setKey, ["a", False])
        self.accept("d-up", self.setKey, ["d", False])
        self.accept("space-up", self.setKey, ["space", False])
        self.accept("lshift-up", self.setKey, ["lshift", False])
        self.accept("e-up", self.setKey, ["e", False])
        self.accept('escape', sys.exit)
        self.accept("p-up", self.setKey, ["p", False])
        self.accept("o-up", self.setKey, ["o", False])

        # Add the spinCameraTask procedure to the task manager.
        self.taskMgr.add(self.cameraControl, "CameraControl")

        self.camera.setPos(tuple(self.position))