Ejemplo n.º 1
0
    def GetIndicies(indexData):
        outbuff = []
        numTris = indexData.indexCount
        if numTris == 0 : return outbuff
        else : numTris /= 3

        ibuf = indexData.indexBuffer

        if ibuf.getType() == ogre.HardwareIndexBuffer.IT_32BIT:
            Use32Bit = True
        else:
            Use32Bit = False

        ogre_buffer = ibuf.lock(ogre.HardwareBuffer.HBL_READ_ONLY)
        address = ogre.castAsInt(ogre_buffer)

        for i in range(numTris):
            if Use32Bit:
                l = ogre.getUint32 (ogre.castAsVoidPtr (address), 3)
                address += ibuf.getIndexSize() * 3
            else:
                l = ogre.getUint16 (ogre.castAsVoidPtr (address), 3)
                address += ibuf.getIndexSize() * 3
            outbuff.append(tuple(l))
        ibuf.unlock()
        return outbuff
Ejemplo n.º 2
0
 def getIndices ( sm ) :
     outbuff = []
     
     numTris = sm.indexData.indexCount
     if numTris == 0 : return outbuff
     else : numTris /= 3
     
     ibuf = sm.indexData.indexBuffer
     
     if ibuf.getType() == ogre.HardwareIndexBuffer.IT_32BIT:
         Use32Bit = True
     else: Use32Bit = False
     
     buffer = ibuf.lock(ogre.HardwareBuffer.HBL_READ_ONLY)
     address = ogre.CastInt ( buffer )
         
     for i in range( numTris ):
         if Use32Bit:
             l = ogre.getUint32 ( ogre.CastVoidPtr ( address ), 3 )
             address += ibuf.getIndexSize() * 3 
         else:
             l = ogre.getUint16 ( ogre.CastVoidPtr ( address ), 3 )
             address += ibuf.getIndexSize() * 3
         outbuff.append(l[0])
         outbuff.append(l[1])
         outbuff.append(l[2])
     #mMaterials[index_offset++] = currentMaterialIndex;            
     return outbuff
 def _createScene(self): 
     sm = self.sceneManager
      
     ent1 = sm.createEntity("Robot","robot.mesh") 
     ud = UD( )
     ent1.setUserObject ( ud )
     
     nud = ent1.getUserObject()
     print nud
     print nud.id, nud.name
     print nud.getTypeName()
     print nud.getTypeID()   
     
     # now test Any
     list=[1,2,3,4]
     a=ogre.Any(list)
     b=a.getData()
     if len(b) != 2:
         print "ERROR", b
     if b[0] != 'p':
         print "ERROR", b
     if len(b[1]) != 4:
         print "ERROR", b
     print b
     list[1]=12
     print b[1]
     c=ogre.createAny(['us',123])
     d=c.getData()
     print d
     c=ogre.createAny(['l',123])
     d=c.getData()
     print d
     c=ogre.createAny(['ul',123])
     d=c.getData()
     print d
     c=ogre.createAny(['uc',5])
     d=c.getData()
     print d
     c=ogre.createAny(['p',list])
     #del list
     d=c.getData()
     print d
     
     a=ogre.Any( nud )
     print a
     b=a.getData()
     print b
     print b[1].id, b[1].name
     sys.exit()
Ejemplo n.º 4
0
 def _updateView(self):
     """Update object view
     """
     if self.needStateUpdate:
         self.needStateUpdate = False
         n = self.sceneNode.numAttachedObjects()
         mat_name = self._getMaterialName()
         for idx in xrange(n):
             object = self.sceneNode.getAttachedObject(idx)
             object.setMaterialName(mat_name)
         
     if self.needScaleUpdate:
         self.sceneNode.setScale(self.scale)
         self.needScaleUpdate = False
         
     if self.needModeUpdate:
         if render_engine.viewMode is render_engine.Mode_Perspective:
             self.sceneNode.setAutoTracking(True, render_engine._ogreCameraNode, ogre.Vector3(0, 0, 1))
         else:
             self.sceneNode.setAutoTracking(False)
             self.sceneNode.resetOrientation()
         self.needModeUpdate = False
         
     if self.needTextPositionUpdate:
         if self.text_obj:   self.text_obj.setPosition(self.position + self.scale * ogre.Vector3(0.125, -0.125, 0.125)) 
         self.needTextPositionUpdate = False
         
     objects.ObjectDepth._updateView(self)
Ejemplo n.º 5
0
 def __init__(self, sceneManager):
     ogre.FrameListener.__init__(self)
     self.entities = []
     self.warp_lock = True
     self.warped = 0
     self.sceneManager = sceneManager
     self.warptimer = ogre.Timer()
Ejemplo n.º 6
0
    def _onRootChanged(self, isRoot):
        """Root changed event
        """
        global prev_background
        global prev_back_visible
        BaseModeLogic._onRootChanged(self, isRoot)
        if isRoot:
            render_engine.setMode(render_engine.Mode_Perspective)
            self.prev_cam_pos = render_engine._ogreCameraNode.getPosition()
            self.prev_cam_dir = render_engine._ogreCameraNode.getOrientation()
            prev_background = render_engine._ogreViewport.getBackgroundColour()
            render_engine._ogreViewport.setBackgroundColour(
                ogre.ColourValue(0, 0, 0))
            #            space_panel.activate(self._getSheet().getChilds())
            prev_back_visible = render_engine.SceneManager.isBackVisible()
            if prev_back_visible:
                render_engine.SceneManager.hideBack()
        else:
            render_engine.setMode(render_engine.Mode_Isometric)
            render_engine._ogreCameraNode.setPosition(self.prev_cam_pos)
            render_engine._ogreCameraNode.setOrientation(self.prev_cam_dir)
            render_engine._ogreViewport.setBackgroundColour(prev_background)
            #            space_panel.deactivate()
            space_window.deactivate()

            if prev_back_visible:
                render_engine.SceneManager.showBack()
        self.is_root = isRoot
Ejemplo n.º 7
0
    def __init__(self, point1, point2, normal=None):
        BoundingObject.__init__(self, "linesegment")
        self.point1 = ogre.Vector3(point1[0], 0, point1[1])
        self.point2 = ogre.Vector3(point2[0], 0, point2[1])
        self.vector = ogre.Vector3(self.point2.x - self.point1.x, 0,
                                   self.point2.z - self.point1.z)
        if normal is not None:
            self.normal = ogre.Vector3(normal[0], 0, normal[1])
        #@todo: if normal == None, calculate it from p1, p2

        top = min((point1[1], point2[1])) - point1[1]
        right = max((point1[0], point2[0])) - point1[0]
        bottom = max((point1[1], point2[1])) - point1[1]
        left = min((point1[0], point2[0])) - point1[0]

        self.setup_AABB(top, right, bottom, left)
Ejemplo n.º 8
0
    def __init__(self, _logic):
        BaseEditMode.__init__(self, _logic, "Geometry edit")

        # last scroll position
        self.last_scroll_pos = None

        # grid align mode
        self.grid_align = True
        self.mouse_pos = (0, 0)
        self.objectInfoPanel = geom_controls.ObjectInfoPanel()

        # objects we works with
        self.highlighted_obj = None
        # current edit state
        self.state = GeometryEditMode.ES_None
        # current object we worked with
        self.active_object = None
        # candidate object to be processed with mouse
        self.candidate_object = None
        # line creation mode
        self.__pointSpirit = GeometryPoint()
        self.__pointSpirit.setState(Object.OS_Normal)
        self.__pointSpirit.setScale(ogre.Vector3(0.5, 0.5, 0.5))
        self.__lineSpirit = GeometryLineSection()
        self.__lineSpirit.setState(Object.OS_Normal)
        self.__lineSpirit.setEnd(self.__pointSpirit)
        self.__lineBegin = None
Ejemplo n.º 9
0
    def reloadResourses(self):
        if not self.ogreMgr.shouldInitResources:
            ogre.GpuProgramManager.getSingleton().removeAll()
            #ogre.CompositorManager.getSingleton().removeAll()
            ogre.TextureManager.getSingleton().removeAll()
            
            dict = []
            scripts = {}
            for value in self.resourceInformation.materialsOrigin:
                    ogre.MaterialManager.getSingleton().unload(value["name"])
                    ogre.MaterialManager.getSingleton().remove(value["name"])
            tempDic = {}
            for value in self.resourceInformation.materialsOrigin:
                tempDic[value["origin"]] = value
            
            for (key, value) in tempDic.iteritems():
                stream = ogre.ResourceGroupManager.getSingleton().openResource(key)
                if not ogre.MaterialManager.getSingleton().resourceExists(value["name"]) == True:
                    ogre.MaterialManager.getSingleton().parseScript(stream.getAsString(), value["group"])

            for value in self.resourceInformation.materialsOrigin:
                mat = ogre.MaterialPointer(ogre.MaterialManager.getSingleton().getByName(value["name"]))
                mat.compile(True)

            ogre.MeshManager.getSingleton().reloadAll()
Ejemplo n.º 10
0
    def tick(self, dtime):
        '''update vel from ds, dh
        '''
        if self.ent.ds > self.ent.speed:
            self.ent.speed += self.ent.acceleration
        elif self.ent.ds < self.ent.speed:
            self.ent.speed -= self.ent.acceleration

        if self.ent.speed < 0:
            self.ent.speed = 0
        if self.ent.speed > self.ent.maxSpeed:
            self.ent.speed = self.ent.maxSpeed

        if self.ent.dh > self.ent.yaw:
            self.ent.nyaw = self.ent.yaw + (self.ent.turningRate * dtime)
        elif self.ent.dh < self.ent.yaw:
            self.ent.nyaw = self.ent.yaw - (self.ent.turningRate * dtime)

        x = self.ent.speed * math.sin(math.pi - self.ent.nyaw)
        z = self.ent.speed * math.cos(math.pi - self.ent.nyaw)

        self.ent.vel.x = -x
        self.ent.vel.y = 0
        self.ent.vel.z = z

        if self.ent.isSelected:
            print str(self.ent.vel)

        self.ent.pos = self.ent.pos + (self.ent.vel * dtime)
        self.ent.deltaYaw = ogre.Radian(self.ent.nyaw - self.ent.yaw)
        self.ent.yaw = self.ent.nyaw
Ejemplo n.º 11
0
    def tick(self, dtime):
        self.keyboard.capture()
        self.mouse.capture()

        self.keyPressed(dtime)

        #self.camNode.yaw(ogre.Degree(-self.yawRot)
        self.camYawNode.yaw(ogre.Radian(self.yawRot))
        self.camPitchNode.pitch(ogre.Radian(self.pitchRot))

        # Translate the camera based on time.
        self.camYawNode.translate(self.camYawNode.orientation *
                                  self.transVector * dtime)

        self.handleCreateEnt(dtime)
        pass
Ejemplo n.º 12
0
def getPluginPath():
    """ Return the absolute path to a valid plugins.cfg file.
    look in the current directory for plugins.cfg followed by plugins.cfg.nt|linux|mac
    If not found look one directory up
    """ 
    
    paths = [os.path.join(os.getcwd(), 'plugins.cfg'),
             os.path.join(os.getcwd(), '..','plugins.cfg'),
             ]
    if os.sys.platform == 'darwin':
        paths.insert(1, os.path.join(os.getcwd(), 'plugins.cfg.mac'))
        paths.append(os.path.join(os.getcwd(), '..', 'plugins.cfg.mac'))
    else:
        paths.insert(1,os.path.join(os.getcwd(), 'plugins.cfg.'+os.name))
        paths.append(os.path.join(os.getcwd(), '..', 'plugins.cfg.'+os.name))
        
    for path in paths:
        if os.path.exists(path):
            return path

    sys.stderr.write("\n"
        "** Warning: Unable to locate a suitable plugins.cfg file.\n"
        "** Warning: Please check your ogre installation and copy a\n"
        "** Warning: working plugins.cfg file to the current directory.\n\n")
    raise ogre.Exception(0, "can't locate a suitable 'plugins' file", "")
Ejemplo n.º 13
0
    def __init__(self, id, engine, tankID='Null', pos=None, vel=MyVector(0, 0, 0), yaw=0):
        Entity.__init__(self, id, engine=engine, pos=pos, vel=vel, yaw=yaw)
        self.mesh = 'wallCube.mesh'
        self.material = "Examples/CannonBall"
        self.uiname = 'IWALL'
        self.eid = id
        self.yawOffset = 0
        self.acceleration = 0
        self.turningRate = 0
        self.maxSpeed = 0
        self.desiredSpeed = 0
        self.desiredHeading = 0
        self.speed = 0
        self.heading = 0
        self.engine = engine
        self.checkValue = 300
        self.tankID = tankID

        self.node = self.engine.gfxMgr.sceneManager.getRootSceneNode().createChildSceneNode(self.pos)
        self.ent = self.engine.gfxMgr.sceneManager.createEntity(self.eid, self.mesh)
        self.node.attachObject(self.ent)
        self.node.rotate(ogre.Vector3(0, 1, 0), ogre.Math.DegreesToRadians(yaw))

        self.light = self.engine.gfxMgr.sceneManager.createLight('light' + self.id)
        self.light.type = ogre.Light.LT_POINT
        self.node.attachObject(self.light)
Ejemplo n.º 14
0
    def _createScene(self):
        sceneManager = self.sceneManager
        camera = self.camera

        sceneManager.ambientLight = ogre.ColourValue(1.0, 1.0, 1.0)
#         sceneManager.setSkyDome(True, 'Examples/CloudySky', 5.0, 8.0)

        # create a main node to hang the effects off
        self.fountainNode = sceneManager.getRootSceneNode().createChildSceneNode()
        self.fountainNode.setPosition(ogre.Vector3(0, 0, -800))
        ## Setup Camera
        camera.setPosition(ogre.Vector3(0,0,300))
        camera.lookAt(ogre.Vector3(0,0,-300))
        
        
        mParticleSystemManager = PU.ParticleSystemManager.getSingletonPtr()
        self.names = ogre.stdVectorString()
        mParticleSystemManager.particleSystemTemplateNames(self.names)
	    
        for n in self.names:
            print "PU template:", n
            
        self.currentDemo=0   
        # create the particle system
        self.particleSystem2 = PU.ParticleSystemManager.getSingleton().createParticleSystem("mySystem", self.names[self.currentDemo], sceneManager)
        
        # attach it to the node
        self.fountainNode.attachObject(self.particleSystem2)
        
        # and don't forget to start it
        self.particleSystem2.start()
        name= self.particleSystem2.name
        self.ps = self.sceneManager.getMovableObject(name, PU.ParticleSystemFactory.PU_FACTORY_TYPE_NAME)
Ejemplo n.º 15
0
 def _createViewports(self):
     """Creates the Viewport."""
     try:    
         self.viewport = self.renderWindow.addViewport(self.camera.getRealCamera())
     except AttributeError:
         self.viewport = self.renderWindow.addViewport(self.camera)
     self.viewport.BackgroundColour = ogre.ColourValue(0,0,0)
Ejemplo n.º 16
0
    def _createPygameMixer(self):
        """Initialises the pyglet sound module"""
        try:
            import pyglet
            settings.sound_support = True
            import os.path
            if os.path.exists("sound.cfg"):
                config = ogre.ConfigFile()
                config.loadDirect("sound.cfg")
                music = config.getSetting("Music")
                if music == "Yes":
                    settings.music = True
                else:
                    settings.music = False

                sound = config.getSetting("Sound")
                if sound == "Yes":
                    settings.sound_effects = True
                else:
                    settings.sound_effects = False
        except ImportError:
            print "pyglet not found, sounds are disabled"
            settings.music = False
            settings.sound_effects = False
            settings.sound_support = False
Ejemplo n.º 17
0
    def run(self):
        import time
        import ogre.renderer.OGRE as ogre
        weu = ogre.WindowEventUtilities()  # Needed for linux/mac
        weu.messagePump()  # Needed for linux/mac

        self.oldTime = time.time()
        self.runTime = 0
        while (self.keepRunning):
            now = time.time()  # Change to time.clock() for windows
            dtime = now - self.oldTime
            self.oldTime = now

            self.entityMgr.tick(dtime)
            self.gfxMgr.tick(dtime)
            self.netMgr.tick(dtime)
            self.inputMgr.tick(dtime)
            self.selectionMgr.tick(dtime)
            self.controlMgr.tick(dtime)
            self.gameMgr.tick(dtime)

            self.runTime += dtime

            weu.messagePump()  # Needed for linux/mac
            time.sleep(0.001)

        print "381 Engine exiting..."
Ejemplo n.º 18
0
    def addPlanet(self, object, position, parent):
        pos = self.calculateRadialPosition(position, 300, 720, parent.planets,
                                           object.index)
        node = self.createObjectNode(pos, object.id, 'sphere_lod.mesh', 50)
        self.nodes[object.id] = node
        self.planets.append(node)
        entity_node = self.sceneManager.getSceneNode("Object%i_EntityNode" %
                                                     object.id)

        colour = None
        owner = object.Ownership[0][1]
        if owner != -1:
            random.seed(owner)
            r = random.random
            colour = ogre.ColourValue(r(), r(), r(), 1)

        icon = overlay.IconOverlay(entity_node, object,
                                   "Starmap/Icons/Planets", 15, 15, colour)
        self.icons[object.id] = icon

        random.seed(parent.id)
        for i in range(object.index):
            random.random()
        planet_type = random.choice(["Terran", "Ocean", "Arid"])

        entity = self.sceneManager.getEntity("Object%i" % object.id)
        entity.setMaterialName("Starmap/Planet/%s" % planet_type)

        return node
Ejemplo n.º 19
0
    def calculateFakeNormals(self):
        buf = self.vertexBuffers[self.currentBufNumber]
        pNormals = self.normVertexBuffer.lock(
            0, self.normVertexBuffer.getSizeInBytes(), ogre.HardwareBuffer.HBL_DISCARD
        )
        # storageclass1=ctypes.c_float * (self.normVertexBuffer.getSizeInBytes()*3)
        pNormalsAddress = (ctypes.c_float * (self.normVertexBuffer.getSizeInBytes() * 3)).from_address(
            ogre.castAsInt(pNormals)
        )

        for y in range(self.complexity):
            start = 3 * y * (self.complexity + 1)
            nrow = pNormalsAddress[start]
            row = buf[3 * y * (self.complexity + 1) + 1]
            rowup = buf[3 * (y - 1) * (self.complexity + 1) + 1]
            rowdown = buf[3 * (y + 1) * (self.complexity + 1) + 1]
            for x in range(self.complexity):
                xdiff = row + 3 * x + 3 - row + 3 * x - 3
                ydiff = rowup + 3 * x - rowdown + 3 * x - 3
                norm = ogre.Vector3(xdiff, 30, ydiff)
                norm.normalise()

                pNormalsAddress[start + 3 * x + 0] = norm.x
                pNormalsAddress[start + 3 * x + 1] = norm.y
                pNormalsAddress[start + 3 * x + 2] = norm.z

        # ogre.setUint16 ( pNormals, buf )
        self.normVertexBuffer.unlock()
Ejemplo n.º 20
0
    def _readFromScreenshotPictureToTexture(self):
        f = open(self.textureName, 'rb')
        data = f.read()
        f.close()

        stream = ogre.MemoryDataStream("%s" % str(self), len(data), False)
        stream.setData(data)
        img = ogre.Image()
        img.load(stream, ogre.Image.getFileExtFromMagic(stream))

        txtrMngr = ogre.TextureManager.getSingleton()
        screenshot = txtrMngr.loadImage(self.textureName, env.resource_group,
                                        img)
        self.texture.getBuffer().blit(screenshot.getBuffer())
        txtrMngr.remove(screenshot)
        screenshot.unload()
 def getScaledPosition(self, position):
     """Returns an array containing the position scaled accordingly"""
     return ogre.Vector3(
         (position[0] / self.map_scale) * self.distance_units,
         (position[1] / self.map_scale) * self.distance_units,
         (position[2] / self.map_scale) * self.distance_units,
     )
Ejemplo n.º 22
0
    def run(self):
        import time
        import ogre.renderer.OGRE as ogre
        weu = ogre.WindowEventUtilities()  # Needed for linux/mac
        weu.messagePump()  # Needed for linux/mac

        while (self.keepRunning):
            now = time.time()  # Change to time.clock() for windows
            dtime = now - self.oldTime
            self.oldTime = now

            self.entMgr.tick(dtime)
            self.gfxMgr.tick(dtime)
            self.netMgr.tick(dtime)
            self.inputMgr.tick(dtime)
            self.selectionMgr.tick(dtime)
            self.widgetMgr.tick(dtime)
            self.gameMgr.tick(dtime)

            self.runTime += dtime

            weu.messagePump()  # Needed for linux/mac
            time.sleep(0.001)

        self.releaseLevel()
Ejemplo n.º 23
0
    def _create(self, scene, shape_type, shape_props, mass, center_of_mass, 
                inertia, position, orientation):
        # Create Collision Object
        # TODO: Improve collision support
        col = None
        if shape_type == 'box':
            size = sim.OgreVector3(shape_props['size'])
            col = OgreNewt.Box(scene.world, size)
        elif shape_type == 'cylinder':
            col = OgreNewt.Cylinder(scene.world, shape_props['radius'], 
                                    shape_props['height'])
        elif shape_type == 'mesh':
            # Fix this by later (we shouldn't need a node!!!)
            name = 'TREE_HACK' + str(Body._tree_mesh_hack)
            Body._tree_mesh_hack += 1
            mesh_name = shape_props['mesh_name']
            scale = sim.OgreVector3(shape_props.get('mesh_scale',
                                                    Ogre.Vector3(1,1,1)))
            
            tree_ent = scene.scene_mgr.createEntity(name, mesh_name)

            # Need extra node, for scaling error
            temp_node = \
                scene.scene_mgr.getRootSceneNode().createChildSceneNode()
            temp_node.attachObject(tree_ent)
            temp_node.setVisible(False)
            temp_node.setScale(scale)
            
            col = OgreNewt.TreeCollision(scene.world, temp_node, True)
            # When this works remove and destory our node temporary node!!
        else:
            raise PhysicsError, '"%s" is not a valid shape type' % shape_type
        
        self._body = scene.world.create_body(self, col, mass, center_of_mass,
                                             inertia, position, orientation)
Ejemplo n.º 24
0
    def _setUp(self):
        """This sets up the ogre application

		Returns false if the user hits "cancel" in the dialog box.

		"""
        self._createLogger()
        self.root = ogre.Root("plugins.cfg", "ogre.cfg")
        settings.renderers = self.root.getAvailableRenderers()

        self._setUpResources()
        if not self._configure():
            return False

        self._chooseSceneManager()
        self._createCamera()
        self._createViewports()

        self._createPygameMixer()

        ogre.TextureManager.getSingleton().defaultNumMipmaps = 5

        self._createResourceListener()
        self._loadResources()

        self._createScene()
        self._createFrameListener()
        return True
Ejemplo n.º 25
0
    def lock (self, * args ) : # start, size, options):
        if len ( args ) != 1 and len (args ) != 3:
            print "ERROR IN ARG LIST", len (args), args
            raise ValueError 
            
        if len (args) == 3:    
            self.lock = self.buffer.lock(args[0], args[1], args[2] ) # this returns a void pointer
        else:
            self.lock = self.buffer.lock(args[0] ) # this returns a void pointer
        self.buffAddress = ogre.castAsInt ( self.lock ) # and we store it as an unsigned long so was can get to it 
        
        # and now we make a ctypes byte array that points to the index buffer
        if self.buffType == 1 : # index buffer so 'ints'
            if self.itemSize == 4:
                self.rawBuffer=(ctypes.c_uint32 * (self.numItems)).from_address(self.buffAddress)
            elif self.itemSize == 2:
#                if len(args) == 3:
#                    if args[2] == ogre.HardwareBuffer.HBL_READ_ONLY:
#                        self.ro = True
#                        temp= [0]*self.numItems
##                        self.rawBuffer=array.array('H')
#                        self.rawBuffer.fromlist(temp)
#                        self.buffer.readData(args[0], args[1], self.rawBuffer.buffer_info()[0] )
#                        return
                self.rawBuffer=(ctypes.c_ushort * (self.numItems)).from_address(self.buffAddress)
        else: # assume it's a vertex buffer with floats
            self.rawBuffer=(ctypes.c_float * (self.itemSize*self.numItems)).from_address(self.buffAddress)
    def __init__(self):
        og.MaterialManager.Listener.__init__(self)
      
        self.currentColor = og.ColourValue(0.0, 0.0, 0.0)
        self.currentColorAsVector3 = og.Vector3()

        self.lastEntity = ""
        self.lastTechnique = None
 

        if platform.system() == "Windows":
            self.lastTechnique = og.MaterialManager.getSingleton().load("PlainColor", og.ResourceGroupManager.DEFAULT_RESOURCE_GROUP_NAME).getTechnique(0)
        else:
            self.lastTechnique = og.MaterialManager.getSingleton().load("PlainColorGLSL", og.ResourceGroupManager.DEFAULT_RESOURCE_GROUP_NAME).getTechnique(0)
        
        self.colorDict = {}
Ejemplo n.º 27
0
 def _update(self, _timeSinceLastFrame):
     """Update mode
     """
     if self.navigation:
         if self._logic._getSheet().isRoot and render_engine.viewMode is render_engine.Mode_Perspective:
             # processing keyboard input
             if  render_engine._oisKeyboard.isKeyDown(ois.KC_A):
                 self.move.x = -self.moveScale    # Move camera left
     
             if  render_engine._oisKeyboard.isKeyDown(ois.KC_D):
                 self.move.x = self.moveScale    # Move camera RIGHT
     
             if  render_engine._oisKeyboard.isKeyDown(ois.KC_W):
                 self.move.z = -self.moveScale  # Move camera forward
     
             if  render_engine._oisKeyboard.isKeyDown(ois.KC_S):
                 self.move.z = self.moveScale    # Move camera backward
                 
             if  render_engine._oisKeyboard.isKeyDown(ois.KC_Q):
                 self.move.y = self.moveScale  # Move camera up
     
             if  render_engine._oisKeyboard.isKeyDown(ois.KC_E):
                 self.move.y = -self.moveScale    # Move camera down
         
             # updating camera position
             camera = render_engine._ogreCamera
             cameraNode = render_engine._ogreCameraNode
             cameraNode.translate(camera.getOrientation() * self.move)
             camera.yaw(self.rotX)
             camera.pitch(self.rotY)
             self.move = ogre.Vector3(0, 0, 0)
             self.rotX = 0
             self.rotY = 0
Ejemplo n.º 28
0
def create(ship_position=(0, 0, 0)):
    """Create a HexShip entity."""
    # Initialize OGRE graphical representation.
    ship_id = entitysystem.create_entity()
    logging.debug("HexShip id: " + str(ship_id) + "   pos: (" +
                  str(ship_position[0]) + ", " + str(ship_position[1]) + ", " +
                  str(ship_position[2]) + ")")

    ogre_entity = application.ogre_scene_manager.createEntity(
        'ogreEntity-' + str(ship_id), 'HexCell.mesh')
    ogre_node = application.ogre_root_node.createChildSceneNode('ogreNode-' +
                                                                str(ship_id))
    ogre_node.attachObject(ogre_entity)
    ogre_entity.setCastShadows(True)
    ogre_node.setScale(ogre.Vector3(1.0, 1.0, 1.0))
    entitysystem.add_component(ship_id, entitysystem.ComponentTypes.Graphics,
                               ogre_node)

    # Initialize physics.
    collision_object = OgreBulletUtils.CollisionObject(
        application.bullet_world)
    collision_object.setShape(
        OgreBulletUtils.MeshInfo.createCylinderShape(
            ogre_entity, OgreBulletUtils.BulletShapes.CYLINDERZ))
    collision_object.setTransform(
        bullet.btVector3(ship_position[0], ship_position[1], ship_position[2]))
    collision_object.setMass(1.0)
    collision_object.setInertia(bullet.btVector3(0.0, 0.0, 0.0))
    collision_object.setMotion(ogre_entity.getParentSceneNode())
    entitysystem.add_component(ship_id, entitysystem.ComponentTypes.Physics,
                               collision_object)
Ejemplo n.º 29
0
 def on_health_changed(self, player, value):
     p = player.health / player.max_health
     width = p * 120
     r, g, b = 1 - p, p, 0
     color = ogre.ColourValue(r, g, b, .5)
     self.bar_health.setDimensions(width, 20)
     self.bar_health.setColour(color)
Ejemplo n.º 30
0
 def createCamera(self):
     self.camera = self.sceneManager.createCamera("Camera")
     self.camera.nearClipDistance = 10
     yawNode = self.sceneManager.getRootSceneNode().createChildSceneNode("RTSCamNode", (0, 250, 1200))
     yawNode.yaw(ogre.Degree(0))
     yawNode.createChildSceneNode("RTSPitchNode").attachObject(self.camera)
     self.camera.lookAt = (0, 0, 0)
Ejemplo n.º 31
0
    def _spawnCube(self):
        # Now lets spawn an object
        obj = scene.SceneObject()
        position = self._robot._main_part._node.position
        robotOrient = self._robot._main_part._node.orientation

        # 30cm below robot
        offset = ogre.Vector3(0.4, 0.30 - (self._count * 0.2), 0)
        position = position + robotOrient * offset 
        
        cfg = {
            'name' : self._name + str(self._count),
            'position' : position,
            'Graphical' : {
                'mesh' : 'cylinder.mesh', 
                'scale' : [0.127, 0.0127, 0.0127],
                'material' : 'Simple/Yellow',
                'orientation' : robotOrient 
            },
            'Physical' : {
                'mass' : 0.005,
                'orientation' : robotOrient,
                'Shape' : {
                    'type' : 'cylinder',
                    'radius' : 0.0127,
                    'height' : 0.0127
                }
            }
        }
        obj.load((self._scene, None, cfg))
        self._scene._objects.append(obj)
	def __init__(self, parent, sceneManager):
		scene.Scene.__init__(self, parent, sceneManager)
		self.background_nodes = []
		self.sides = []
		self.bg_particle = None
		self.nodes = {}
		self.userobjects = {}
		self.listeners = {}
		self.initial_positions = []

		self.camera_focus_node = self.rootNode.createChildSceneNode("CameraFocus")
		self.camera_node = self.camera_focus_node.createChildSceneNode("CameraNode")
		self.camera_node.attachObject(self.camera)
		self.camera_target_node = self.camera_focus_node.createChildSceneNode("CameraTarget")
		self.camera_target_node.position = self.camera_node.position
		self.h_angle = 0
		self.v_angle = 0

		root = ogre.Root.getSingleton()
		self.mfl = MoveFrameListener()
		self.wfl = WarpFrameListener(self.sceneManager)
		root.addFrameListener(self.mfl)
		root.addFrameListener(self.wfl)

		self.zoomtimer = ogre.Timer()
		self.zoomstart = 0
		self.basezoom = 100

		#self.createBackground()
		self.hide()
Ejemplo n.º 33
0
    def _mouse_moved(self, arg):
        """
        If the shift key is down, swing the camera
        """

        if self.shift_key:
            ms = arg.get_state()
            # Rotate around our object
            self._camera_node.pitch(Ogre.Radian(ms.Y.rel * -0.5))
            self._camera_node.yaw(Ogre.Radian(ms.X.rel * -0.5),
                                  Ogre.Node.TS_WORLD)

            # Zoom in or out of our objective
            if ms.Z.rel < 0 or ms.Z.rel > 0:
                pos = self._camera.position
                self._camera.setPosition(pos + (pos * ms.Z.rel * 0.002))
Ejemplo n.º 34
0
def buoyancyCallback(colID, me, orient, pos, plane):
    """
    Here we need to create an Ogre::Plane object representing the surface of 
    the liquid.  In our case, we're just assuming a completely flat plane of 
    liquid, however you could use this function to retrieve the plane
    equation for an animated sea, etc.
    """
    plane1 = Ogre.Plane(Ogre.Vector3(0, 1, 0), Ogre.Vector3(0, 0, 0))

    # we need to copy the normals and 'd' to the plane we were passed...
    plane.normal = plane1.normal
    plane.d = plane1.d

    # pos = Ogre.Vector3(0,0,0)

    return True
Ejemplo n.º 35
0
    def _createCamera(self):  # creating the cameras

        #        Tkinter.Tk().withdraw()
        #        global file_path
        #        self.openOpt = options = {}
        #        options['initialdir'] = wDir+'\..\..\..\Configurations'
        #        options['title'] = 'Select experiment parameters'
        #
        #file_path = tkFileDialog.askopenfilename(**self.openOpt) # asking which experiment to load?
        # file_path = u'C:/LuigsNeumann_Treadmill/Configurations/20181001ReducedMazeSet.xlsx'
        # wb = load_workbook(file_path)
        # ws = wb.get_active_sheet()

        self.numMonitors = 3  #int(ws.cell('C46').value)
        self.resolution = [
            1024, 768
        ]  #map(int,re.findall(r'\d+',ws.cell('C47').value)) # 1024 x 768

        #This value represents the VERTICAL field-of-view.
        # The horizontal field of view is calculated from this depending on the dimensions of the viewport
        # (they will only be the same if the viewport is square).
        if self.numMonitors == 5:
            FOV = 34
        else:
            FOV = 73.74

        self.camera = self.sceneManager.createCamera('PlayerCam')
        self.camera.nearClipDistance = 1
        self.camera.setFOVy(ogre.Degree(FOV))
        camH = 4.9
        #        self.camera.pitch(ogre.Degree(22)) # to pitch the camera towards the sky
        self.camera.setPosition(ogre.Vector3(0, camH, 0))

        if self.numMonitors >= 3:
            self.cameraL = self.sceneManager.createCamera('CamL')
            self.cameraL.nearClipDistance = 1
            self.cameraL.setFOVy(ogre.Degree(FOV))
            self.cameraR = self.sceneManager.createCamera('CamR')
            self.cameraR.nearClipDistance = 1
            self.cameraR.setFOVy(ogre.Degree(FOV))
            self.cameraL.setPosition(ogre.Vector3(0, camH, 0))
            self.cameraR.setPosition(ogre.Vector3(0, camH, 0))

        if self.numMonitors == 5:
            self.cameraLL = self.sceneManager.createCamera('CamLL')
            self.cameraLL.nearClipDistance = 1
            self.cameraLL.setFOVy(ogre.Degree(FOV))
            self.cameraRR = self.sceneManager.createCamera('CamRR')
            self.cameraRR.nearClipDistance = 1
            self.cameraRR.setFOVy(ogre.Degree(FOV))

        self.renderWindow.resize(
            max(1, self.numMonitors) * self.resolution[0],
            self.resolution[1] + 30)  # window size and position
        #        self.renderWindow.reposition(-(max(1,self.numMonitors)-1)/2*self.resolution[0],-30)
        #        self.renderWindow.reposition(-3*self.resolution[0],-30)
        self.renderWindow.reposition(-3080, -30)
Ejemplo n.º 36
0
 def center(self, id=None):
     """Center on an object identified by object id, or center on map if id is None"""
     if id:
         node = self.nodes[id]
         pos = node.getPosition()
         cam_focus = self.sceneManager.getSceneNode("CameraFocus")
         cam_focus.position = ogre.Vector3(pos.x, pos.y, 0)
     else:
         map_width = self.map_upper_right[0] - self.map_lower_left[0]
         map_height = self.map_upper_right[1] - self.map_lower_left[1]
         cam_focus = self.sceneManager.getSceneNode("CameraFocus")
         cam_focus.resetOrientation()
         self.h_angle = 0
         self.v_angle = 0
         x = self.map_upper_right[0] - (map_width / 2)
         y = self.map_upper_right[1] - (map_height / 2)
         cam_focus.position = ogre.Vector3(x, y, 0)
Ejemplo n.º 37
0
    def GetVerticies(vertex_data, transform):
        outbuff = []

        # get the start of the element
        posElem = vertex_data.vertexDeclaration.findElementBySemantic(ogre.VertexElementSemantic.VES_POSITION)
        vbuf = vertex_data.vertexBufferBinding.getBuffer(posElem.getSource())

        # get the start of the actual buffer
        vertex = vbuf.lock(ogre.HardwareBuffer.HBL_READ_ONLY)

        # What we need is the actual address of the buffer,
        # so we have to check if there's an offset as well.
        # This is basically what baseVertexPointerToElement does.
        newaddress = posElem.getOffset() + ogre.castAsInt(vertex) # note the cast to int to get the address

        for i in range (vertex_data.vertexCount):
            points = ogre.getFloat(ogre.castAsVoidPtr(newaddress), 3) # note the getFloat and Cast back to a pointer :)

            #_transform
            vec = transform * ogre.Vector3(points[0], points[1], points[2])
            outbuff.append(tuple((vec.x, vec.y, vec.z)))
            newaddress += vbuf.getVertexSize()
        vbuf.unlock()
        return outbuff
Ejemplo n.º 38
0
    def _createScene(self):
        sceneManager = self.sceneManager
        camera = self.camera

        sceneManager.ambientLight = ogre.ColourValue(0.5, 0.5, 0.5)
        sceneManager.setSkyDome(True, 'Examples/CloudySky', 5.0, 8.0)

        self.fountainNode = sceneManager.getRootSceneNode().createChildSceneNode()
        
        psm = ogre.ParticleSystemManager.getSingleton()
        self.particleSystem2 = sceneManager.createParticleSystem("Smoke", "Examples/Smoke") #'fountain1', 'Examples/Smoke')
        node = self.fountainNode.createChildSceneNode()
        node.attachObject(self.particleSystem2)
        ogre.LogManager.getSingleton().logMessage( "INNER COUNT -- ANDY" )
        self.item = ogre.Any ( self.root )
        a1 = ogre.getAddress( self.item )
        print "Address:", a1
Ejemplo n.º 39
0
    def lock(self, *args):  # start, size, options):
        if len(args) != 1 and len(args) != 3:
            print "ERROR IN ARG LIST", len(args), args
            raise ValueError

        if len(args) == 3:
            self.lock = self.buffer.lock(args[0], args[1], args[2])  # this returns a void pointer
        else:
            self.lock = self.buffer.lock(args[0])  # this returns a void pointer
        self.buffAddress = ogre.castAsInt(self.lock)  # and we store it as an unsigned long so was can get to it

        # and now we make a ctypes byte array that points to the index buffer
        if self.buffType == 1:  # index buffer so 'ints'
            if self.itemSize == 4:
                self.rawBuffer = (ctypes.c_uint32 * (self.numItems)).from_address(self.buffAddress)
            elif self.itemSize == 2:
                self.rawBuffer = (ctypes.c_ushort * (self.numItems)).from_address(self.buffAddress)
        else:  # assume it's a vertex buffer with floats
            self.rawBuffer = (ctypes.c_float * (self.itemSize * self.numItems)).from_address(self.buffAddress)
Ejemplo n.º 40
0
    def getExtents ( mesh ) :
     
        vMin = ogre.Vector3(99999,99999,99999)
        vMax = ogre.Vector3(-99999,-99999,-99999)
        i = []
        for m in range(mesh.numSubMeshes):
            sm = mesh.getSubMesh(m)
            pmesh = sm.parent
            if pmesh and sm.useSharedVertices :
                vertex_data = pmesh.sharedVertexData
            else : vertex_data = sm.vertexData

            # get the start of the element
            posElem = vertex_data.vertexDeclaration.findElementBySemantic(ogre.VertexElementSemantic.VES_POSITION)
            vbuf = vertex_data.vertexBufferBinding.getBuffer(posElem.getSource())
            
            # get the start of the actual buffer
            vertex = vbuf.lock(ogre.HardwareBuffer.HBL_READ_ONLY)
            
            # what we need is the actual address of the buffer, so we have to check if there's an offset as well
            # the is basically what baseVertexPointerToElement does 
            newaddress = posElem.getOffset() + ogre.CastInt(vertex) # note the cast to int to get the address
                
            for i in range (vertex_data.vertexCount):
                points = ogre.getFloat( ogre.CastVoidPtr ( newaddress), 3 ) # note the getFloat and Cast back to a pointer :)
                print points
                if (points[0]<vMin.x):
                    vMin.x = points[0]
                if (points[1]<vMin.y):
                    vMin.y = points[1]
                if (points[2]<vMin.z):
                    vMin.z = points[2]
                if (points[0]>vMax.x):
                    vMax.x = points[0]
                if (points[1]>vMax.y):
                    vMax.y = points[1]
                if (points[2]>vMax.z):
                    vMax.z = points[2]
                    
                #outbuff.append(tuple(points))
                newaddress += vbuf.getVertexSize()
        return vMin, vMax
Ejemplo n.º 41
0
def prepareCircleMaterial():
    global CIRCLES_MATERIAL
    bmap = array.array('B')  # unsigned char -- int in python
    for x in range (256*256*4):
        bmap.append(127)
    
    for  b in range(16):
        x0 = b % 4  
        y0 = b >> 2  
        radius = 4.0 + 1.4 * b  
        for x in range(64):
            for y in range (64) :
                dist = math.sqrt((x-32)*(x-32)+(y-32)*(y-32))  ## 0..ca.45
                dist = math.fabs(dist-radius-2) / 2.0  
                dist = dist * 255.0 
                
                if (dist>255):
                    dist=255  
                colour = 255- int(dist)
                colour = int (float(15-b)/15.0 * colour )
                bmap[4*(256*(y+64*y0)+x+64*x0)+0]=colour  
                bmap[4*(256*(y+64*y0)+x+64*x0)+1]=colour 
                bmap[4*(256*(y+64*y0)+x+64*x0)+2]=colour 
                bmap[4*(256*(y+64*y0)+x+64*x0)+3]=colour 
                
    ### Need to  pass the address to MemoryDataStream
    ##  
    imgstream = Ogre.MemoryDataStream(pMem=Ogre.castAsVoidPtr(bmap.buffer_info()[0]),  size = 256 * 256 *4 )  
    Ogre.TextureManager.getSingleton().loadRawData(CIRCLES_MATERIAL,
        Ogre.ResourceGroupManager.DEFAULT_RESOURCE_GROUP_NAME,
        imgstream, 256, 256  , Ogre.PixelFormat.PF_A8R8G8B8 ) 
    material = Ogre.MaterialManager.getSingleton().create( CIRCLES_MATERIAL,
        Ogre.ResourceGroupManager.DEFAULT_RESOURCE_GROUP_NAME) 
    texLayer = material.getTechnique(0).getPass(0).createTextureUnitState( CIRCLES_MATERIAL ) 
    texLayer.setTextureAddressingMode( Ogre.TextureUnitState.TAM_CLAMP ) 
    material.setSceneBlending( Ogre.SceneBlendType.SBT_ADD ) 
    material.setDepthWriteEnabled( False )  
    material.load() 
Ejemplo n.º 42
0
def GetVerticies ( sm ) :
    outbuff = []
    pmesh = sm.parent
    if pmesh and sm.useSharedVertices :
        vertex_data = pmesh.sharedVertexData
    else : vertex_data = sm.vertexData

    # get the start of the element
    posElem = vertex_data.vertexDeclaration.findElementBySemantic(ogre.VertexElementSemantic.VES_POSITION)
    vbuf = vertex_data.vertexBufferBinding.getBuffer(posElem.getSource())
    
    # get the start of the actual buffer
    vertex = vbuf.lock(ogre.HardwareBuffer.HBL_READ_ONLY)
    
    # what we need is the actual address of the buffer, so we have to check if there's an offset as well
    # the is basically what baseVertexPointerToElement does 
    newaddress = posElem.getOffset() + ogre.CastInt(vertex) # note the cast to int to get the address
        
    for i in range (vertex_data.vertexCount):
        points = ogre.getFloat( ogre.CastVoidPtr ( newaddress), 3 ) # note the getFloat and Cast back to a pointer :)
        outbuff += points
        newaddress += vbuf.getVertexSize()
    return outbuff
Ejemplo n.º 43
0
    def updateOgreTexture(self):

        width    = self.texture.getWidth()
        height   = self.texture.getHeight()
        byteSize =  ogre.PixelUtil.getNumElemBytes(self.texture.getDesiredFormat())
        bufferSize =  width * height * byteSize

        ## sanity checks
        assert self.noiseImage.Width == width
        assert self.noiseImage.Height == height
        #assert (noiseImage.Width * noiseImage.Height * 4) == bufferSize

        # get and lock texture's pixel buffer
        pixelBuffer = self.texture.getBuffer()
        pointer = pixelBuffer.lock(0, bufferSize, ogre.HardwareBuffer.HBL_NORMAL)

        # python-ogre hack
        storageclass = ctypes.c_uint8 * ( bufferSize )
        cbuffer=storageclass.from_address(ogre.castAsInt(pointer))

        ## copy image buffer to texture
        k = 0
        for i in range(height):
            for j in range(width):
                c = self.noiseImage.GetSlabPtr(i,j)
                cbuffer[k]   = c.blue
                cbuffer[k+1] = c.green
                cbuffer[k+2] = c.red
                if byteSize>3:
                    cbuffer[k+3] = c.alpha
                    k+=4
                else: 
                    k+=3


        # Unlock the pixel buffer
        pixelBuffer.unlock() 
Ejemplo n.º 44
0
 def calculateNormals1(self):
     ## zero normals
     for i in range(self.numVertices*3) :
         self.vNormals[i]=  0
         
     ## first, calculate normals for faces, add them to proper vertices
     
     # use helper function
     vinds = buffer ( self.indexBuffer)
     vinds.lock (0, self.indexBuffer.getSizeInBytes(), ogre.HardwareBuffer.HBL_READ_ONLY)
     
     pNormals = self.normVertexBuffer.lock(
         0, self.normVertexBuffer.getSizeInBytes(), ogre.HardwareBuffer.HBL_DISCARD) 
     pNormalsAddress=(ctypes.c_float * (self.normVertexBuffer.getSizeInBytes()*3)).from_address(ogre.castAsInt(pNormals))
    
     # make life easier (and faster) by using a local variables
     buf = self.vertexBuffers[self.currentBufNumber]
     vNormals = self.vNormals
     
     ## AJM so here's a case where accessing a C++ object from python shows a performance hit !!
     ## in this case we look through and the original C++ code creates and access ovre.Vector3 objects
     ## multiple times on each pass.
     for count in range(self.numFaces) :
         p0 = vinds[3*count]  
         p1 = vinds[3*count+1]  
         p2 = vinds[3*count+2]  
         # this is slow
         # v0= ogre.Vector3 (self.vertexBuffers[buf][3*p0], self.vertexBuffers[buf][3*p0+1], self.vertexBuffers[buf][3*p0+2]) 
         # v1 = ogre.Vector3 (self.vertexBuffers[buf][3*p1], self.vertexBuffers[buf][3*p1+1], self.vertexBuffers[buf][3*p1+2]) 
         # v2 = ogre.Vector3 (self.vertexBuffers[buf][3*p2], self.vertexBuffers[buf][3*p2+1], self.vertexBuffers[buf][3*p2+2]) 
         
         # so use python arrays instead of Vector3's
         i0 = 3*p0
         i1 = 3*p1
         i2 = 3*p2
         v0 = [buf[i0], buf[i0+1], buf[i0+2]]
         v1 = [buf[i1], buf[i1+1], buf[i1+2]] 
         v2 = [buf[i2], buf[i2+1], buf[i2+2]] 
         
         # Do the vector subtraction by 'hand' instead of original
         # diff2 = v0 - v1  
         diff1  = [v2[0]-v1[0],v2[1]-v2[1],v2[2]-v2[2]]  
         diff2  = [v0[0]-v1[0],v0[1]-v2[1],v0[2]-v2[2]]  
         
         # and now we need to do a crossProduct by hand..
         # fn = ogre.Vector3(*diff1).crossProduct(ogre.Vector3(*diff2)) 
         fn = [diff1[1] * diff2[2] - diff1[2] * diff2[1],
             diff1[2] * diff2[0] - diff1[0] * diff2[2],
             diff1[0] * diff2[1] - diff1[1] * diff2[0]]
         # And of course now add the values into the normals
         # self.vNormals[p0] += fn  
         # self.vNormals[p1] += fn  
         # self.vNormals[p2] += fn  
         vNormals[i0] += fn[0] 
         vNormals[i0+1] += fn[1] 
         vNormals[i0+2] += fn[2] 
         vNormals[i1] += fn[0] 
         vNormals[i1+1] += fn[1] 
         vNormals[i1+2] += fn[2] 
         vNormals[i2] += fn[0] 
         vNormals[i2+1] += fn[1] 
         vNormals[i2+2] += fn[2] 
 
     ## now normalize vertex normals
     complexity = self.complexity
     for y in range(complexity) :
         for x in range(complexity) :
             numPoint = y*(complexity+1) + x  
             v = 3*numPoint
             n = ogre.Vector3(vNormals[v],vNormals[v+1],vNormals[v+2])  
             n.normalise()  
             v = 3*numPoint
             pNormalsAddress [v] = n.x
             pNormalsAddress [v+1] = n.y
             pNormalsAddress [v+2] = n.z
 
 
     self.indexBuffer.unlock() 
     self.normVertexBuffer.unlock() 
Ejemplo n.º 45
0
 def __init__ ( self, meshName, planeSize, complexity ):
     self.dirty = True # need to refo calcs
     self.meshName = meshName  
     self.complexity =  complexity  
     self.numFaces = 2 * complexity * complexity 
     self.numVertices = (complexity + 1) * (complexity + 1)  
     self.lastTimeStamp = 0  
     self.lastAnimationTimeStamp = 0 
     self.lastFrameTime = 0  
 
     ## initialize algorithm parameters
     self.PARAM_C = 0.3   ## ripple speed
     self.PARAM_D = 0.4   ## distance
     self.PARAM_U = 0.05   ## viscosity
     self.PARAM_T = 0.13   ## time
     self.useFakeNormals = False  
 
     ## allocate space for normal calculation
     self.vNormals=[]
     for x in range ( self.numVertices * 3 ):
         self.vNormals.append(0)
 
     ## create mesh and submesh
     self.mesh = ogre.MeshManager.getSingleton().createManual(meshName,
             ogre.ResourceGroupManager.DEFAULT_RESOURCE_GROUP_NAME) 
     self.subMesh = self.mesh.createSubMesh() 
     self.subMesh.useSharedVertices=False 
 
     ## Vertex buffers
     ##self.subMesh.vertexData = ogre.VertexData() 
     self.subMesh.vertexData = ogre.createVertexData() 
     self.subMesh.vertexData.vertexStart = 0 
     self.subMesh.vertexData.vertexCount = self.numVertices 
 
     vdecl = self.subMesh.vertexData.vertexDeclaration 
     vbind = self.subMesh.vertexData.vertexBufferBinding 
 
 
     vdecl.addElement(0, 0, ogre.VertexElementType.VET_FLOAT3, ogre.VertexElementSemantic.VES_POSITION) 
     vdecl.addElement(1, 0, ogre.VertexElementType.VET_FLOAT3, ogre.VertexElementSemantic.VES_NORMAL) 
     vdecl.addElement(2, 0, ogre.VertexElementType.VET_FLOAT2, ogre.VertexElementSemantic.VES_TEXTURE_COORDINATES) 
 
     ## Prepare buffer for positions - todo: first attempt, slow
     self.posVertexBuffer = \
          ogre.HardwareBufferManager.getSingleton().createVertexBuffer(
             3 * ctypes.sizeof(ctypes.c_float),
             self.numVertices,
             ogre.HardwareBuffer.HBU_DYNAMIC_WRITE_ONLY_DISCARDABLE) 
     vbind.setBinding(0, self.posVertexBuffer) 
 
     
     ## Prepare buffer for normals - write only
     self.normVertexBuffer = \
          ogre.HardwareBufferManager.getSingleton().createVertexBuffer(
             3*ctypes.sizeof(ctypes.c_float), 
             self.numVertices,
             ogre.HardwareBuffer.HBU_DYNAMIC_WRITE_ONLY_DISCARDABLE) 
     vbind.setBinding(1, self.normVertexBuffer) 
 
     ## Prepare texture coords buffer - static one
     ## todo: optimize to write directly into buffer
     texcoordsBufData=array.array('f')
     for x in range (self.numVertices*2):
         texcoordsBufData.append(0)
     
     for y in range (complexity) :
         for x in range(complexity) :
             texcoordsBufData[2*(y*(complexity+1)+x)+0] = float(x) / complexity  
             texcoordsBufData[2*(y*(complexity+1)+x)+1] = 1.0 - (float(y) / (complexity))  
 
 
     texcoordsVertexBuffer = \
          ogre.HardwareBufferManager.getSingleton().createVertexBuffer(
             2*ctypes.sizeof(ctypes.c_float),
             self.numVertices,
             ogre.HardwareBuffer.HBU_STATIC_WRITE_ONLY) 
     texcoordsVertexBuffer.writeData(0,
         texcoordsVertexBuffer.getSizeInBytes(),
         texcoordsBufData.buffer_info()[0],
         True)  ## true?
     vbind.setBinding(2, texcoordsVertexBuffer) 
 
     ## Prepare buffer for indices
     self.indexBuffer = \
         ogre.HardwareBufferManager.getSingleton().createIndexBuffer(
             ogre.HardwareIndexBuffer.IT_16BIT,
             3*self.numFaces,
             ogre.HardwareBuffer.HBU_STATIC, True) 
            
     # using a helper object to handle the ctypes implement
     # Create a buffer object and then lock it
     faceVertexIndices = buffer ( self.indexBuffer )
     faceVertexIndices.lock (0, self.numFaces*3*2, ogre.HardwareBuffer.HBL_DISCARD) 
     
     for y in range (complexity) :
         for  x in range (complexity ) :
             twoface = (y*complexity+x)*2*3 # index into buffer
             p0 = y*(complexity+1) + x  
             p1 = y*(complexity+1) + x + 1  
             p2 = (y+1)*(complexity+1) + x  
             p3 = (y+1)*(complexity+1) + x + 1 
             # write a series of bytes
             faceVertexIndices [ twoface + 0]= p2
             faceVertexIndices [ twoface + 1]= p1
             faceVertexIndices [ twoface + 2]= p0
             faceVertexIndices [ twoface + 3]= p2
             faceVertexIndices [ twoface + 4]= p3
             faceVertexIndices [ twoface + 5]= p1
             
     self.indexBuffer.unlock() 
     ## Set index buffer for self submesh
     self.subMesh.indexData.indexBuffer = self.indexBuffer 
     self.subMesh.indexData.indexStart = 0 
     self.subMesh.indexData.indexCount = 3*self.numFaces 
 
 #  prepare vertex positions
 #  note - we use 3 vertex buffers, since algorighm uses two last phases
 #  to calculate the next one
 
 # we need 2 floats, and are going through the loop three times 
     floatStorage = ctypes.c_float * (self.numVertices * 3 )
     #self.vertexBuffers = storageclass2 (1.1)
     #
     # Change here to use an 'array' for the buffers
     self.vertexBuffers = []
     for x in range (3):
         if USE_ARRAY:
             self.vertexBuffers.append( array.array('f') )
             for y in range (self.numVertices *3):
                 self.vertexBuffers[x].append(0)
         else:
             self.vertexBuffers.append( floatStorage(1.1) )
         
     
     ## Note that in the C++ code self.vertexBuffers is a float * array[3], whcih indexes into float*numverticies*3
     ## we have made a single array bige nough to cope
     #self.vertexIndexSize = self.numVertices*3
     
     for b in range(3) :
         for y in range(complexity) :
             for x in range (complexity) :
                 numPoint = y*(complexity+1) + x  
                 VertexPos = 3 * numPoint
                 self.vertexBuffers[b][VertexPos + 0] = float(x) / float(complexity) * float(planeSize)
                 self.vertexBuffers[b][VertexPos + 1] = 0
                 self.vertexBuffers[b][VertexPos + 2] = float(y) / float(complexity) * float(planeSize) 
                     
     meshBounds = ogre.AxisAlignedBox(0,0,0, planeSize,0, planeSize) 
     self.mesh._setBounds(meshBounds) 
 
     self.currentBufNumber = 0 
     if USE_ARRAY:
         self.posVertexBuffer.writeData(0,
             self.posVertexBuffer.getSizeInBytes(), ## size
             self.vertexBuffers[0].buffer_info()[0], 
             True)  ## discard?
     else:
         self.posVertexBuffer.writeData(0,
             self.posVertexBuffer.getSizeInBytes(), ## size
             ctypes.addressof(self.vertexBuffers[0]), 
             True)  ## discard?
     self.mesh.load() 
     self.mesh.touch() 
Ejemplo n.º 46
0
    def calculateNormals(self):
        # return  #AJM
        buf = self.currentBufNumber  # +1  #AJM
        ## zero normals

        for i in range(self.numVertices):
            self.vNormals[i] = ogre.Vector3().ZERO
        ## first, calculate normals for faces, add them to proper vertices

        # use helper function
        vinds = buffer(self.indexBuffer)
        vinds.lock(0, self.indexBuffer.getSizeInBytes(), ogre.HardwareBuffer.HBL_READ_ONLY)

        pNormals = self.normVertexBuffer.lock(
            0, self.normVertexBuffer.getSizeInBytes(), ogre.HardwareBuffer.HBL_DISCARD
        )
        # storageclass1=ctypes.c_float * (self.normVertexBuffer.getSizeInBytes()*3)
        pNormalsAddress = (ctypes.c_float * (self.normVertexBuffer.getSizeInBytes() * 3)).from_address(
            ogre.castAsInt(pNormals)
        )

        for i in range(self.numFaces):
            p0 = vinds[3 * i]
            p1 = vinds[3 * i + 1]
            p2 = vinds[3 * i + 2]
            # print p0, p1, p2
            v0 = ogre.Vector3(
                self.vertexBuffers[buf][3 * p0],
                self.vertexBuffers[buf][3 * p0 + 1],
                self.vertexBuffers[buf][3 * p0 + 2],
            )
            v1 = ogre.Vector3(
                self.vertexBuffers[buf][3 * p1],
                self.vertexBuffers[buf][3 * p1 + 1],
                self.vertexBuffers[buf][3 * p1 + 2],
            )
            v2 = ogre.Vector3(
                self.vertexBuffers[buf][3 * p2],
                self.vertexBuffers[buf][3 * p2 + 1],
                self.vertexBuffers[buf][3 * p2 + 2],
            )
            diff1 = v2 - v1
            diff2 = v0 - v1
            fn = diff1.crossProduct(diff2)
            self.vNormals[p0] += fn
            self.vNormals[p1] += fn
            self.vNormals[p2] += fn

        ## now normalize vertex normals
        for y in range(self.complexity):
            for x in range(self.complexity):
                numPoint = y * (self.complexity + 1) + x
                n = self.vNormals[numPoint]
                n.normalise()
                pNormalsAddress[3 * numPoint] = n.x
                pNormalsAddress[3 * numPoint + 1] = n.y
                pNormalsAddress[3 * numPoint + 2] = n.z
        #                normal[0]=n.x
        #                normal[1]=n.y
        #                normal[2]=n.z

        self.indexBuffer.unlock()
        self.normVertexBuffer.unlock()
Ejemplo n.º 47
0
    def calculateNormalsCython(self):
        
        # use helper function
        vinds = buffer ( self.indexBuffer)
        vinds.lock (0, self.indexBuffer.getSizeInBytes(), ogre.HardwareBuffer.HBL_READ_ONLY)
        
        pNormals = self.normVertexBuffer.lock(
            0, self.normVertexBuffer.getSizeInBytes(), ogre.HardwareBuffer.HBL_DISCARD) 
        pNormalsAddress=(ctypes.c_float * (self.normVertexBuffer.getSizeInBytes()*3)).from_address(ogre.castAsInt(pNormals))
       
        ## AJM so here's a case where accessing a C++ object from python shows a performance hit !!
        ## in this case we use an external cython module
        calcNormalsFast ( self.numFaces, vinds, self.vertexBuffers[self.currentBufNumber], self.vNormals, 
                            self.complexity, pNormalsAddress, self.numVertices)

        self.indexBuffer.unlock() 
        self.normVertexBuffer.unlock() 
Ejemplo n.º 48
0
    def _get_mesh_info(self, mesh):
        '''
        http://www.ogre3d.org/addonforums/viewtopic.php?f=3&t=11621
        '''

        added_shared = False

        current_offset = 0
        shared_offset = 0
        next_offset = 0
        index_offset = 0

        vertex_count = 0
        index_count = 0

        # Calculate how many vertices and indices we're going to need
        num_sub_meshes = mesh.getNumSubMeshes()
        for i in range(0, num_sub_meshes):
            submesh = mesh.getSubMesh(i)

            # We only need to add the shared vertices once
            if submesh.useSharedVertices:
                if not added_shared:
                    vertex_count += mesh.sharedVertexData.vertexCount
                    added_shared = True
            else:
                vertex_count += submesh.vertexData.vertexCount

            # Add the indices
            index_count += submesh.indexData.indexCount

        added_shared = False;

        # Run through the submeshes again, adding the data into the arrays
        for i in range(0, num_sub_meshes):
            submesh = mesh.getSubMesh(i)

            vertexData = None
            if submesh.useSharedVertices:
                vertexData =  mesh.sharedVertexData
            else:
                vertexData = submesh.vertexData

            if not submesh.useSharedVertices or\
                (submesh.useSharedVertices and not added_shared):

                if submesh.useSharedVertices:
                    added_shared = True
                    shared_offset = current_offset

                # retrieve index buffer for this submesh
                indexData = submesh.indexData
                ibuf = indexData.indexBuffer
                pointer = ibuf.lock(ogre.HardwareBuffer.HBL_READ_ONLY)
                index_buffer = None

                if bool(ibuf.getType() == ogre.HardwareIndexBuffer.IT_32BIT):
                    index_buffer = ogre.getUint32(pointer, index_count)
                else:
                    index_buffer = ogre.getUint16(pointer, index_count)
                ibuf.unlock()


                # retrieve vertex buffer for this submesh
                posElem = vertexData.vertexDeclaration\
                                .findElementBySemantic(ogre.VES_POSITION)
                vbuf = vertexData.vertexBufferBinding\
                                .getBuffer(posElem.getSource())
                pointer = vbuf.lock(ogre.HardwareBuffer.HBL_READ_ONLY)

                # There are 8 float entries for each vertex in the buffer
                # 3 for position, 3 for normal, 2 for texture coordinate.
                # We only need the position.
                vertex_buffer = ogre.getFloat(pointer, vertex_count * 8)
                vbuf.unlock()

        return [vertex_buffer, index_buffer]
Ejemplo n.º 49
0
    def createGrassMesh(self):
        global GRASS_MESH_NAME
        self.SetToNone = []
        ## Each grass section is 3 planes at 60 degrees to each other
        ## Normals point straight up to simulate correct lighting
        msh = ogre.MeshManager.getSingleton().createManual(GRASS_MESH_NAME, 
            ogre.ResourceGroupManager.DEFAULT_RESOURCE_GROUP_NAME) 
        self.msh = msh
        self.hw = ogre.HardwareBufferManager.getSingleton()
        sm = msh.createSubMesh() 
        
        sm.useSharedVertices = False 

           
        self.vertexdata = ogre.createVertexData() ## Create the VertexData Object
        
        ## NOTE the submesh will delete the vertexData when it is destroyed which is BAD -- ie we have C++ specifically
        ## deleting a Python object which makes everything confused..  The fix is to set the submesh vertexData to 
        ## 'None' before exiting -- see the __del__ function
        sm.vertexData = self.vertexdata     
        
        sm.vertexData.vertexStart = 0 
        sm.vertexData.vertexCount = 12 
        dcl = sm.vertexData.vertexDeclaration 
        offset = 0 
        dcl.addElement(0, offset, ogre.VertexElementType.VET_FLOAT3, ogre.VertexElementSemantic.VES_POSITION) 
        offset += ogre.VertexElement.getTypeSize(ogre.VertexElementType.VET_FLOAT3) 
        dcl.addElement(0, offset, ogre.VertexElementType.VET_FLOAT3, ogre.VertexElementSemantic.VES_NORMAL) 
        offset += ogre.VertexElement.getTypeSize(ogre.VertexElementType.VET_FLOAT3) 
        dcl.addElement(0, offset, ogre.VertexElementType.VET_FLOAT2, ogre.VertexElementSemantic.VES_TEXTURE_COORDINATES) 
        offset += ogre.VertexElement.getTypeSize(ogre.VertexElementType.VET_FLOAT2) 

        vbuf = ogre.HardwareBufferManager.getSingleton().createVertexBuffer(
                offset, 12, ogre.HardwareBuffer.HBU_STATIC_WRITE_ONLY) 

        #lock the buffer and get a pointer to the data      
        pointer = vbuf.lock(ogre.HardwareBuffer.HBL_DISCARD)
         
        baseVec = ogre.Vector3(GRASS_WIDTH/2, 0, 0) 
        vec = baseVec 
        rot = ogre.Quaternion () 
        rot.FromAngleAxis(ogre.Degree(d=60), ogre.Vector3().UNIT_Y) 
        
        # change from the C++ demo - we build a buffer and then write it in one go
        buffer=[]
        for i in range ( 3 ) :
            ## position
            buffer.append( -vec.x )
            buffer.append( GRASS_HEIGHT )
            buffer.append( -vec.z )
            ## normal
            buffer.append( 0 )
            buffer.append( 1 )
            buffer.append( 0 )
            ## uv
            buffer.append( 0 )
            buffer.append( 0 )
            
            ## position
            buffer.append( vec.x )
            buffer.append( GRASS_HEIGHT )
            buffer.append( vec.z )
            ## normal
            buffer.append( 0 )
            buffer.append( 1 )
            buffer.append( 0 )
            ## uv
            buffer.append( 1 )
            buffer.append( 0 )
            
            ## position
            buffer.append( -vec.x )
            buffer.append( 0 )
            buffer.append( -vec.z )
            ## normal
            buffer.append( 0 )
            buffer.append( 1 )
            buffer.append( 0 )
            ## uv
            buffer.append( 0 )
            buffer.append( 1 )
            
            ## position
            buffer.append( vec.x )
            buffer.append( 0 )
            buffer.append( vec.z )
            ## normal
            buffer.append( 0 )
            buffer.append( 1 )
            buffer.append( 0 )
            ## uv
            buffer.append( 1 )
            buffer.append( 1 )
            
            vec = rot * vec 
            
        ## Python-Ogre extension function to write a list of floats to a buffer
        ogre.setFloat( pointer, buffer )
        vbuf.unlock() 
              
        sm.vertexData.vertexBufferBinding.setBinding(0, vbuf) 
          
        sm.indexData.indexCount = 6*3 
        
        sm.indexData.indexBuffer = ogre.HardwareBufferManager.getSingleton().createIndexBuffer(
                ogre.HardwareIndexBuffer.IT_16BIT, sm.indexData.indexCount,
                ogre.HardwareBuffer.HBU_STATIC_WRITE_ONLY) 
        
        pointer = sm.indexData.indexBuffer.lock(ogre.HardwareBuffer.HBL_DISCARD)

        ## here is one way to do this using a Python-Ogre helper function        
# #         buff=[]
# #         for i in range ( 3 ):
# #             off = i*4 
# #             buff.append( 0 + off )
# #             buff.append( 3 + off ) 
# #             buff.append( 1 + off )
# #             
# #             buff.append( 0 + off )
# #             buff.append( 2 + off )
# #             buff.append( 3 + off )
# #             
# #         # another Python-Ogre helper function to write unsigned ints to a buffer
# #         ogre.setUint16( pointer, buff )   

        ## Here is a way to do it with ctypes....
        pVert= ( ctypes.c_uint16 * (sm.indexData.indexCount)).from_address ( ogre.castAsInt ( pointer ) ) 
        index = 0
        for i in range ( 3 ):
            off = i*4
            pVert[ index ] = 0 + off
            index +=1
            pVert[ index ] = 3 + off
            index +=1
            pVert[ index ] = 1 + off
            index +=1
            pVert[ index ] = 0 + off
            index +=1
            pVert[ index ] = 2 + off
            index +=1
            pVert[ index ] = 3 + off
            index +=1
        sm.indexData.indexBuffer.unlock() 
        
        
        sm.setMaterialName(GRASS_MATERIAL) 
        msh.load()
        ## we need to keep access to the submesh so we can set .vertexData to None at exit (see __del__ )
        self.sm = sm 
Ejemplo n.º 50
0
    def _createScene(self):

        self.sceneManager.ambientLight = ogre.ColourValue(0.5, 0.5, 0.5)
        ## Create a skydome
        ## self.sceneManager.setSkyDome(True, "Examples/CloudySky", 5, 8) 

        ## create terrain manager
        self.terrainMgr =  ET.TerrainManager(self.sceneManager)
        self.terrainMgr.setLODErrorMargin(2, self.camera.getViewport().getActualHeight())
        self.terrainMgr.setUseLODMorphing(True, 0.2, "morphFactor")

        ## create a fresh, mid-high terrain for editing
        # Note 
        try:
            heightMapValues = ogre.LodDistanceList() ## ET.stdVectorFloat()
        except:
            heightMapValues = ogre.stdVectorFloat()
         
        for i in xrange(129):
            for j in xrange(129):
                heightMapValues.append(float(0.50))
        self.terrainInfo = ET.TerrainInfo (129, 129, heightMapValues )

        ## save typing self
        terrainInfo  = self.terrainInfo 
        sceneManager = self.sceneManager
        terrainMgr   = self.terrainMgr

        ## set position and size of the terrain
        terrainInfo.setExtents(ogre.AxisAlignedBox(0, 0, 0, 1500, 300, 1500))
        ## now render it
        terrainMgr.createTerrain(terrainInfo)

        ## create the splatting manager
        self.splatMgr = ET.SplattingManager("ETSplatting", "ET", 128, 128, 3)
        ## specify number of splatting textures we need to handle
        self.splatMgr.setNumTextures(6)

        ## create a manual lightmap texture
        lightmapTex = ogre.TextureManager.getSingleton().createManual(
        "ETLightmap", "ET", ogre.TEX_TYPE_2D, 128, 128, 1, ogre.PF_BYTE_RGB)

        lightmap = ogre.Image()
        ET.createTerrainLightmap(terrainInfo, lightmap, 128, 128,\
                                 ogre.Vector3(1, -1, 1),\
                                 ogre.ColourValue().White,\
                                 ogre.ColourValue(0.3, 0.3, 0.3,1.0))
        lightmapTex.getBuffer(0, 0).blitFromMemory(lightmap.getPixelBox(0, 0))

        ##  load the terrain material and assign it
        material = ogre.MaterialManager.getSingleton().getByName("ETTerrainMaterial")
        self.terrainMgr.setMaterial(material)

        ## Set camera look point
        camNode = self.sceneManager.getRootSceneNode().createChildSceneNode("CamNode")
        camNode.setPosition( 40, 300, 580 )
        camNode.attachObject(self.camera)
        self.camera.pitch( ogre.Degree(-30) )
        self.camera.yaw( ogre.Degree(-45) )

        ## CEGUI setup
        self.GUIRenderer = CEGUI.OgreCEGUIRenderer(self.renderWindow, 
            ogre.RENDER_QUEUE_OVERLAY, False, 3000, self.sceneManager) 
        self.GUIsystem = CEGUI.System(self.GUIRenderer) 

        CEGUI.Logger.getSingleton().setLoggingLevel( CEGUI.Informative ) 
        CEGUI.SchemeManager.getSingleton().loadScheme("TaharezLookSkin.scheme") 
        CEGUI.MouseCursor.getSingleton().setImage("TaharezLook", "MouseArrow")
Ejemplo n.º 51
0
    def _prepareMesh(self):
        
        self.mesh = ogre.MeshManager.getSingleton().createManual(self.name,
            ogre.ResourceGroupManager.DEFAULT_RESOURCE_GROUP_NAME) 
        self.subMesh = self.mesh.createSubMesh()
        self.subMesh.useSharedVertices=False

        numVertices = 4

        if (WaterCircle._first) : # first Circle, create some static common data
            WaterCircle._first = False

            #static buffer for position and normals
            WaterCircle._posnormVertexBuffer =\
                ogre.HardwareBufferManager.getSingleton().createVertexBuffer(
                6*ctypes.sizeof(ctypes.c_float), #size of one vertex data
                4, # number of vertices
                ogre.HardwareBuffer.HBU_STATIC_WRITE_ONLY, # usage
                False) # no shadow buffer
                    
            posnormBufData = buffer ( WaterCircle._posnormVertexBuffer )
            posnormBufData.lock(ogre.HardwareBuffer.HBL_DISCARD)
            
            for i in range (numVertices):
                posnormBufData[6*i+0]=(float(i%2)-0.5)*WaterCircle.CIRCLE_SIZE; # pos X
                posnormBufData[6*i+1]=0; # pos Y
                posnormBufData[6*i+2]=(float(i/2)-0.5)*WaterCircle.CIRCLE_SIZE; # pos Z
                posnormBufData[6*i+3]=0 ; # normal X
                posnormBufData[6*i+4]=1 ; # normal Y
                posnormBufData[6*i+5]=0 ; # normal Z
                
            posnormBufData.unlock()

            #static buffers for 16 sets of texture coordinates
            for lvl in range ( 16 ):
                WaterCircle._texcoordsVertexBuffers.append(
                    ogre.HardwareBufferManager.getSingleton().createVertexBuffer(
                    2*ctypes.sizeof(ctypes.c_float), # size of one vertex data
                    numVertices, # number of vertices
                    ogre.HardwareBuffer.HBU_STATIC_WRITE_ONLY, # usage
                    False)) # no shadow buffer
                texcoordsBufData = buffer( WaterCircle._texcoordsVertexBuffers[lvl])
                texcoordsBufData.lock(ogre.HardwareBuffer.HBL_DISCARD)
                x0 = float(lvl % 4) * 0.25 
                y0 = float(lvl / 4) * 0.25
                y0 = 0.75-y0  # upside down
                for i in range (4):
                    texcoordsBufData[i*2 + 0]=x0 + 0.25 * float(i%2)
                    texcoordsBufData[i*2 + 1]=y0 + 0.25 * float(i/2)
                texcoordsBufData.unlock()

#			Index buffer for 2 faces
            faces = array.array('H',[2,1,0,2,3,1]) # unsigned short array
            WaterCircle._indexBuffer =\
				ogre.HardwareBufferManager.getSingleton().createIndexBuffer(
					ogre.HardwareIndexBuffer.IT_16BIT,
					6,
					ogre.HardwareBuffer.HBU_STATIC_WRITE_ONLY)
            WaterCircle._indexBuffer.writeData(0,
				WaterCircle._indexBuffer.getSizeInBytes(),
				faces.buffer_info()[0],
				True); # true?

#		Initialize vertex data
        self.subMesh.vertexData = ogre.createVertexData()
        self.subMesh.vertexData.vertexStart = 0
        self.subMesh.vertexData.vertexCount = 4
        #first, set vertex buffer bindings
        vbind = self.subMesh.vertexData.vertexBufferBinding 
        vbind.setBinding(0, WaterCircle._posnormVertexBuffer)
        vbind.setBinding(1, WaterCircle._texcoordsVertexBuffers[0])
        #now, set vertex buffer declaration
        vdecl = self.subMesh.vertexData.vertexDeclaration
        vdecl.addElement(0, 0, ogre.VertexElementType.VET_FLOAT3, ogre.VertexElementSemantic.VES_POSITION);
        vdecl.addElement(0, 3*ctypes.sizeof(ctypes.c_float), ogre.VertexElementType.VET_FLOAT3, ogre.VertexElementSemantic.VES_NORMAL);
        vdecl.addElement(1, 0, ogre.VertexElementType.VET_FLOAT2, ogre.VertexElementSemantic.VES_TEXTURE_COORDINATES);

        #		Initialize index data
        self.subMesh.indexData.indexBuffer = WaterCircle._indexBuffer
        self.subMesh.indexData.indexStart = 0
        self.subMesh.indexData.indexCount = 6

        #		set mesh bounds
        circleBounds = ogre.AxisAlignedBox (-WaterCircle.CIRCLE_SIZE/2.0, 0, -WaterCircle.CIRCLE_SIZE/2.0,
            WaterCircle.CIRCLE_SIZE/2.0, 0, WaterCircle.CIRCLE_SIZE/2.0)
        self.mesh._setBounds(circleBounds)
        self.mesh.load()
        self.mesh.touch()
Ejemplo n.º 52
0
    def addStaticPlane( self, bodyRestitution, bodyFriction):
        # Use a load of meshes to represent the floor
        i = 0 
        s = self.sceneManager.createStaticGeometry("StaticFloor") 
        s.setRegionDimensions(ogre.Vector3(160.0, 100.0, 160.0)) 
        # Set the region origin so the center is at 0 world
        s.setOrigin(ogre.Vector3.ZERO(0) 
        for (z in range (-80.0 , 80.0 , 20.0)):
            for ( x in range ( -80.0, 80.0 , 20.0) ):
                name = "Plane_" + str(i) 
                i + = 1

                entity = self.sceneManager.createEntity(name, "plane.mesh") 
                entity.setMaterialName("BulletPlane") 
                entity.setQueryFlags (ogre.STATIC_GEOMETRY_QUERY_MASK) 
                #entity.setUserObject(_plane) 
                entity.setCastShadows(false) 
                s.addEntity(entity, ogre.Vector3(x,0,z)) 
        s.build() 

        Shape = bulletC.StaticPlaneCollisionShape (ogre.Vector3(0,1,0), 0) 

        defaultPlaneBody = bulletC.RigidBody(
            "Plane" + str(self.mNumEntitiesInstanced), 
            self.world) 


        defaultPlaneBody.setStaticShape (Shape, bodyRestitution, bodyFriction) 

        self.mBodies.append(defaultPlaneBody) 
        self.mShapes.append(Shape) 

        self.mNumEntitiesInstanced + = 1 

        return defaultPlaneBody 

    def throwDynamicObject(self,  key)
    
    trowDist = 2.0
    if key == KC_B
        if ( self.checkIfEnoughPlaceToAddObject(trowDist)):
            vec =ogre.Vector3(self.camera.getDerivedPosition())
            body = self.addCube("cube", vec, Quaternion(0,0,0,1), 
                self.gCubeBodyBounds, self.gDynamicBodyRestitution, self.gDynamicBodyFriction, self.gDynamicBodyMass);

            body.setLinearVelocity(
                self.camera.getDerivedDirection().normalisedCopy() * mShootSpeed
    elif  key == KC_N: 
        if ( checkIfEnoughPlaceToAddObject(trowDist)):
            vec = ogre.vector3 (self.camera.getDerivedPosition());
            body = addSphere("sphere", vec, Quaternion(0,0,0,1), 
                gSphereBodyBounds, 
                gDynamicBodyRestitution, gDynamicBodyFriction, gDynamicBodyMass);

            body.setLinearVelocity(
                self.camera.getDerivedDirection().normalisedCopy() * mShootSpeed
    case KC_H: 
        if ( checkIfEnoughPlaceToAddObject(trowDist))
        {
            const Vector3 vec (self.camera.getDerivedPosition());
             body = addCylinder("cylinder", vec, Quaternion(0,0,0,1), 
                gCylinderBodyBounds, 
                gDynamicBodyRestitution, gDynamicBodyFriction, gDynamicBodyMass);

            body.setLinearVelocity(
                self.camera.getDerivedDirection().normalisedCopy() * mShootSpeed
                );
        }
        break;
    case KC_G : 
        if ( checkIfEnoughPlaceToAddObject(trowDist))
        {
            const Vector3 vec (self.camera.getDerivedPosition());
             body = addCone("cone", vec, Quaternion(0,0,0,1), 
                gConeBodyBounds, 
                gDynamicBodyRestitution, gDynamicBodyFriction, gDynamicBodyMass);

            body.setLinearVelocity(
                self.camera.getDerivedDirection().normalisedCopy() * mShootSpeed
                );
        }
        break;
    }
}
// -------------------------------------------------------------------------
void OgreBulletListener::dropDynamicObject(BULLET_KEY_CODE key)
{
    const float dropDist = 10.0f;
    switch(key)
    {
    case KC_J: 
        if ( checkIfEnoughPlaceToAddObject(dropDist))
        {
            const Vector3 vec (self.camera.getDerivedPosition());
             body = addCube("cube", 
                vec + self.camera.getDerivedDirection().normalisedCopy() * 10, 
                Quaternion(0,0,0,1), 
                gCubeBodyBounds, gDynamicBodyRestitution, gDynamicBodyFriction, gDynamicBodyMass);

        }
        break;
    case KC_K: 
        if ( checkIfEnoughPlaceToAddObject(dropDist))
        {
            const Vector3 vec (self.camera.getDerivedPosition());
             body = addSphere("sphere", 
                vec + self.camera.getDerivedDirection().normalisedCopy() * 10, 
                Quaternion(0,0,0,1), 
                gSphereBodyBounds, 
                gDynamicBodyRestitution, gDynamicBodyFriction, gDynamicBodyMass);

        }
        break;
    case KC_U : 
        if ( checkIfEnoughPlaceToAddObject(dropDist))
        {
            const Vector3 vec (self.camera.getDerivedPosition());
             body = addCylinder("Cylinder", vec, Quaternion(0,0,0,1), 
                gCylinderBodyBounds, 
                gDynamicBodyRestitution, gDynamicBodyFriction, gDynamicBodyMass);

        }
        break;
    case KC_I: 
        if ( checkIfEnoughPlaceToAddObject(dropDist))
        {
            const Vector3 vec (self.camera.getDerivedPosition());
             body = addCone("Cone", 
                vec + self.camera.getDerivedDirection().normalisedCopy() * 10, 
                Quaternion(0,0,0,1), 
                gConeBodyBounds, 
                gDynamicBodyRestitution, gDynamicBodyFriction, gDynamicBodyMass);
        }
        break;
    }
}