chpod
02-08-2008 10:15:14
I got your initial code working with RC2. Basically you are doing ray casting, but you did not set any up action to perform afterwards.
Could you please be more precise on your question, I did not get what the issue is here.
In case anyone is interested, the modified source code for RC2:
test_ray.py
import ogre.renderer.OGRE as ogre
import ogre.io.OIS as OIS
import ogre.gui.CEGUI as CEGUI
#import psyco
try:
import psyco
psyco.full()
except ImportError:
pass
class Character(object):
def __init__(self):
pass
def update(self, elapsedTime, input):
pass
def getMainNode(self):
return self.mainNode
def getSightNode(self):
return self.sightNode
def getThirdPersonNode(self):
return self.thirdPersonNode
def _getDerivedPosition(self):
return self.charNode._getDerivedPosition()
class OgreCharacter(Character):
def __init__(self, name, sceneManager):
self.name = name
self.sceneManager = sceneManager
## create mainNode to attach sightNode and Camera Node for third person view
self.mainNode = self.sceneManager.getRootSceneNode().createChildSceneNode(self.name)
## sightNode is what the 3rd person camera looks at and cameraNode is what the camera is attached to
self.sightNode = self.mainNode.createChildSceneNode(self.name + "_sight", (0, 0, 100 ))
self.thirdPersonNode = self.mainNode.createChildSceneNode(self.name + "_camera", (0, 200, -500))
## create robot/entity, attach to its own node and rotate to face the right direction
self.entity = self.sceneManager.createEntity(self.name, 'robot.mesh')
self.charNode = self.mainNode.createChildSceneNode(self.name + "_char")
self.charNode.attachObject(self.entity)
self.charNode.yaw(ogre.Degree(-90))
## scale to appropriate size for terrain
#self.mainNode.setScale(0.1,0.1,0.1)
## Place in terrain
self.mainNode.translate(435,8,910)
def setAnimationState(self, state, elapsedTime):
if state == "Die":
self.animationState = self.entity.getAnimationState(state)
self.animationState.setEnabled(True)
self.animationState.addTime(elapsedTime)
if state == 0:
self.animationState = self.entity.getAnimationState('Idle')
self.animationState.setEnabled(False)
else:
self.animationState = self.entity.getAnimationState(state)
self.animationState.setLoop(True)
self.animationState.setEnabled(True)
self.animationState.addTime(elapsedTime)
def setVisible(self, visible):
self.mainNode.setVisible(visible)
def __del__(self):
"Clear variables, this should not actually be needed."
del self.camera
del self.sceneManager
del self.frameListener
if self.world:
del self.world
del self.root
del self.renderWindow
class ExtendedCamera():
def __init__(self, name, sceneManager, camera = None):
self.name = name
self.sceneManager = sceneManager
self.cameraNode = self.sceneManager.getRootSceneNode().createChildSceneNode(self.name)
self.targetNode = self.sceneManager.getRootSceneNode().createChildSceneNode(self.name + "_target")
self.cameraNode.setAutoTracking(True, self.targetNode)
self.cameraNode.setFixedYawAxis(True)
self.camera = camera
self.camera.setPosition(0,0,20)
self.ownCamera = False
self.cameraNode.attachObject(self.camera)
self.tightness = 0.1
def getCameraPosition(self):
return self.cameraNode.getPosition()
def instantUpdate(self, cameraPosition, targetPosition):
self.cameraNode.setPosition(cameraPosition)
self.targetNode.setPosition(targetPosition)
def update(self, elapsedTime, cameraPosition, targetPosition):
# "cameraPosition: ",cameraPosition
displacement = (cameraPosition - self.cameraNode._getDerivedPosition()) * self.tightness
self.cameraNode.translate(displacement)
displacement = (targetPosition - self.targetNode.getPosition()) * self.tightness
self.targetNode.translate(displacement)
def __del__(self):
self.cameraNode.detachAllObjects()
if self.ownCamera:
del self.camera
self.sceneManager.destroySceneNode(self.name)
self.sceneManager.destroySceneNode(self.name + "_target")
##-------------------------------------------------------------------------------------------------------
class EventListener(ogre.FrameListener, ogre.WindowEventListener, OIS.MouseListener, OIS.KeyListener):
"""
This class handles all our ogre and OIS events, mouse/keyboard
depending on how you initialize this class. All events are handled
using callbacks (buffered).
"""
mouse = None
keyboard = None
def __init__(self, renderWindow, camera, sceneManager, app, viewport, bufferedMouse, bufferedKeys):
# Initialize the various listener classes we are a subclass from
ogre.FrameListener.__init__(self)
ogre.WindowEventListener.__init__(self)
OIS.MouseListener.__init__(self)
OIS.KeyListener.__init__(self)
self.char = 0
self.exCamera = 0
self.mode = 0
self.lastYPos = 0
self.yPos = 0
self.app = app
self.camera = camera
self.idleState = 1
self.sceneManager = sceneManager
self.renderWindow = renderWindow
self.viewPort = viewport
self.walkingSpeed = 100
self.walkingSpeedUphill = 200
# waypoint variables
self.direction = ogre.Vector3.ZERO
self.distance = 0.0
self.waypoint = 0
self.robotCount = 1
# Create the inputManager using the supplied renderWindow
windowHnd = self.renderWindow.getCustomAttributeInt("WINDOW")
self.inputManager = OIS.createPythonInputSystem([("WINDOW",str(windowHnd))])
# Attempt to get the mouse/keyboard input objects,
# and use this same class for handling the callback functions.
# These functions are defined later on.
try:
if bufferedMouse:
self.mouse = self.inputManager.createInputObjectMouse(OIS.OISMouse, bufferedMouse)
self.mouse.setEventCallback(self)
if bufferedKeys:
self.Keyboard = self.inputManager.createInputObjectKeyboard(OIS.OISKeyboard, bufferedKeys)
self.Keyboard.setEventCallback(self)
except Exception, e: # Unable to obtain mouse/keyboard/joy input
raise e
# Set this to True when we get an event to exit the application
self.quitApplication = False
# Listen for any events directed to the window manager's close button
ogre.WindowEventUtilities.addWindowEventListener(self.renderWindow, self)
self.raySceneQueryMouse = self.sceneManager.createRayQuery(ogre.Ray())
def setCharacter(self, character):
self.char = character
self.raySceneQuery = self.app.sceneManager.createRayQuery(ogre.Ray(self.char._getDerivedPosition(), ogre.Vector3.NEGATIVE_UNIT_Y))
def setExtendedCamera(self, cam):
self.exCamera = cam
def __del__ (self ):
# Clean up OIS
print "QUITING"
self.delInputObjects()
OIS.InputManager.destroyInputSystem(self.inputManager)
self.inputManager = None
ogre.WindowEventUtilities.removeWindowEventListener(self.renderWindow, self)
self.windowClosed(self.renderWindow)
def delInputObjects(self):
# Clean up the initialized input objects
if self.keyboard:
self.inputManager.destroyInputObjectKeyboard(self.keyboard)
if self.mouse:
self.inputManager.destroyInputObjectMouse(self.mouse)
def frameStarted(self, evt):
"""
Called before a frame is displayed, handles events
(also those via callback functions, as you need to call capture()
on the input objects)
Returning False here exits the application (render loop stops)
"""
# Capture any buffered events and call any required callback functions
if self.Keyboard:
self.Keyboard.capture()
if self.mouse:
self.mouse.capture()
self.mainNode = self.char.getMainNode()
## create ray for character to determine height from terrain
charRay = ogre.Ray()
charRay.setOrigin (self.char._getDerivedPosition() + ogre.Vector3(0.0, 10.0, 0.0))
charRay.setDirection (ogre.Vector3.NEGATIVE_UNIT_Y)
self.raySceneQuery.Ray = charRay
## get results from ray interaction loop through and determine height
for queryResult in self.raySceneQuery.execute():
if queryResult.worldFragment is not None:
pos = self.camera.getPosition()
self.yPos = pos.y - queryResult.distance + 11.0
break
## Immitate physics adjusting for uphill downhill and flat
## Makes it seem a little more realistic
if self.lastYPos < self.yPos:
self.walkingSpeed = self.walkingSpeedUphill
else:
self.walkingSpeed = self.walkingSpeed
if self.waypoint != 0:
# Set walking animation
self.char.setAnimationState('Walk', evt.timeSinceLastFrame)
self.destination = self.waypoint
self.direction = self.destination - self.mainNode.getPosition()
self.distance = self.direction.normalise()
src = self.mainNode.Orientation * (-ogre.Vector3.UNIT_X)
## set rotation amount then add 90 degrees for adjustment
self.turn = src.getRotationTo(self.direction).getYaw(True) + ogre.Radian(-1.5708)
self.mainNode.yaw((self.turn) * evt.timeSinceLastFrame)
## begin walking slightly before entity is actually turned
if ogre.Radian(-0.6) < self.turn > ogre.Radian(-0.5) :
move = self.walkingSpeed * 0.8 * evt.timeSinceLastFrame
self.distance -= move
if self.distance < .4:
self.mainNode.setPosition(self.destination)
self.waypoint = 0
else:
self.mainNode.translate((self.direction * move *(1,0,1)) +(0, self.yPos, 0))
if self.char:
## ---- begin unbuffered key events ----------
## Change Animation : change animation for any movement pressed
## wanted this seperate from moving so more animations could be added
if self.Keyboard.isKeyDown(OIS.KC_W) or self.Keyboard.isKeyDown(OIS.KC_D) or self.Keyboard.isKeyDown(OIS.KC_A) or self.Keyboard.isKeyDown(OIS.KC_S) :
self.char.setAnimationState('Walk', evt.timeSinceLastFrame)
if self.Keyboard.isKeyDown(OIS.KC_1):
self.char.setAnimationState('Idle', evt.timeSinceLastFrame)
if self.Keyboard.isKeyDown(OIS.KC_2):
self.char.setAnimationState('Walk', evt.timeSinceLastFrame)
if self.Keyboard.isKeyDown(OIS.KC_3):
self.char.setAnimationState('Die', evt.timeSinceLastFrame)
if self.Keyboard.isKeyDown(OIS.KC_4):
self.char.setAnimationState('Shoot', evt.timeSinceLastFrame)
if self.Keyboard.isKeyDown(OIS.KC_5):
self.char.setAnimationState('Slump', evt.timeSinceLastFrame)
if self.Keyboard.isKeyDown(OIS.KC_H):
self.waypointActive = 1
if self.Keyboard.isKeyDown(OIS.KC_0):
# toggle idle state
if not self.idleState:
self.idleState = 1
else:
self.idleState = 0
else:
if self.idleState:
self.char.setAnimationState('Idle', evt.timeSinceLastFrame)
## waypoint sequence
## Have each keydown in a seperate if block so more then one can be pressed at a time
if self.Keyboard.isKeyDown(OIS.KC_Q):
#prints location of character
print "Location of character: ",self.mainNode._getDerivedPosition()
if self.Keyboard.isKeyDown(OIS.KC_E):
self.mainNode.translate(self.mainNode.getOrientation() * (0, 1, 0 * evt.timeSinceLastFrame))
if self.Keyboard.isKeyDown(OIS.KC_W):
self.mainNode.translate(self.mainNode.getOrientation() * (0, self.yPos, self.walkingSpeed * evt.timeSinceLastFrame))
if self.Keyboard.isKeyDown(OIS.KC_S):
self.mainNode.translate(self.mainNode.getOrientation()* (0, self.yPos, -1 * self.walkingSpeed * evt.timeSinceLastFrame))
if self.Keyboard.isKeyDown(OIS.KC_A):
self.mainNode.yaw(ogre.Radian(2 * evt.timeSinceLastFrame))
if self.Keyboard.isKeyDown(OIS.KC_D):
self.mainNode.yaw(ogre.Radian(-2 * evt.timeSinceLastFrame))
lastYpos = self.yPos
if self.exCamera:
if self.mode == 0:
self.exCamera.update( evt.timeSinceLastFrame,
self.char.getThirdPersonNode()._getDerivedPosition() + self.yPos,
self.char.getSightNode()._getDerivedPosition() + self.yPos,)
elif self.mode == 1:
self.exCamera.update(evt.timeSinceLastFrame,
(0, 200, 0),
self.char.getSightNode()._getDerivedPosition() + self.yPos)
elif self.mode == 2:
self.exCamera.update(evt.timeSinceLastFrame,
self.char._getDerivedPosition() + self.yPos +3,
self.char.getSightNode()._getDerivedPosition() + self.yPos +3)
if self.Keyboard.isKeyDown(OIS.KC_F1):
self.mode = 0
if self.char:
self.char.setVisible(True)
if self.exCamera:
if self.char:
self.exCamera.instantUpdate(self.char.getThirdPersonNode()._getDerivedPosition(),
self.char.getSightNode() \
._getDerivedPosition())
self.exCamera.tightness = 0.01
if self.Keyboard.isKeyDown(OIS.KC_F2):
self.mode = 1
if self.char:
self.char.setVisible(True)
if self.exCamera:
if self.char:
self.exCamera.instantUpdate((0, 200, 0),
self.char.getSightNode() \
._getDerivedPosition())
self.exCamera.tightness = 0.01
if self.Keyboard.isKeyDown(OIS.KC_F3):
self.mode = 2
if self.char:
self.char.setVisible(False)
if self.exCamera:
if self.char:
self.exCamera.instantUpdate(self.char._getDerivedPosition(),
self.char.getSightNode() \
._getDerivedPosition())
self.exCamera.tightness = 1.0
# Neatly close our FrameListener if our renderWindow has been shut down
if(self.renderWindow.isClosed()) or self.Keyboard.isKeyDown(OIS.KC_ESCAPE):
return False
return not self.quitApplication
### Window Event Listener callbacks ###
def windowResized(self, renderWindow):
pass
def windowClosed(self, renderWindow):
# Only close for window that created OIS
if(renderWindow == self.renderWindow):
del self
### Mouse Listener callbacks ###
def mouseMoved(self, evt):
# Pass the location of the mouse pointer over to CEGUI
CEGUI.System.getSingleton().injectMouseMove(evt.get_state().X.rel, evt.get_state().Y.rel)
return True
def mousePressed(self, evt, id):
# Handle any CEGUI mouseButton events
CEGUI.System.getSingleton().injectMouseButtonDown(self.convertButton(id))
if id == OIS.MB_Left:
self.leftMouseDown = True
# Setup the ray scene query, use CEGUI's mouse position
mousePos = CEGUI.MouseCursor.getSingleton().getPosition()
mouseRay = self.camera.getCameraToViewportRay(mousePos.d_x / float(evt.get_state().width),
mousePos.d_y / float(evt.get_state().height))
self.raySceneQueryMouse.setRay(mouseRay)
# Execute query
result = self.raySceneQueryMouse.execute()
if len(result) > 0:
item = result[0]
if item.worldFragment:
#self.mainNode.translate(ogre.Vector3(item.worldFragment.singleIntersection) + ogre.Vector3(0,100,0))
#print ogre.Vector3(item.worldFragment.singleIntersection)
#self.waypoint = ogre.Vector3(item.worldFragment.singleIntersection)
#ogre.Vector3(416.57,17.1509,944.229)
name = "Robot" + str(self.robotCount)
ent = self.sceneManager.createEntity(name, "robot.mesh")
self.robotCount += 1
self.currentObject = self.sceneManager.getRootSceneNode().createChildSceneNode(name + "Node", item.worldFragment.singleIntersection)
print "INTERSECTION: ",item.worldFragment.singleIntersection
print "MAINNODE: ",self.mainNode._getDerivedPosition()
self.currentObject.attachObject(ent)
#self.currentObject.setScale(0.1, 0.1, 0.1)
self.leftMouseDown = True
return True
def mouseReleased(self, evt, id):
# Handle any CEGUI mouseButton events
CEGUI.System.getSingleton().injectMouseButtonUp(self.convertButton(id))
return True
def convertButton(self,oisID):
if oisID == OIS.MB_Left:
return CEGUI.LeftButton
elif oisID == OIS.MB_Right:
return CEGUI.RightButton
elif oisID == OIS.MB_Middle:
return CEGUI.MiddleButton
else:
return CEGUI.LeftButton
### Key Listener callbacks ###
def keyPressed(self, evt):
# Quit the application if we hit the escape button
if evt.key == OIS.KC_ESCAPE:
self.quitApplication = True
## if evt.key == OIS.KC_1:
## print "hello"
return True
def keyReleased(self, evt):
return True
class Application(object):
app_title = "MyApplication"
def go(self):
# See Basic Tutorial 6 for details
self.createRoot()
self.defineResources()
self.setupRenderSystem()
self.createRenderWindow()
self.initializeResourceGroups()
self.setupScene()
self.createFrameListener()
self.setupCEGUI()
self.startRenderLoop()
#self.cleanUp()
def createRoot(self):
self.root = ogre.Root()
def defineResources(self):
# Read the resources.cfg file and add all resource locations in it
cf = ogre.ConfigFile()
cf.load("resources.cfg")
seci = cf.getSectionIterator()
while seci.hasMoreElements():
secName = seci.peekNextKey()
settings = seci.getNext()
for item in settings:
typeName = item.key
archName = item.value
ogre.ResourceGroupManager.getSingleton().addResourceLocation(archName, typeName, secName)
def setupRenderSystem(self):
# Show the config dialog if we don't yet have an ogre.cfg file
if not self.root.restoreConfig() and not self.root.showConfigDialog():
raise Exception("User canceled config dialog! (setupRenderSystem)")
def createRenderWindow(self):
self.root.initialise(True, self.app_title)
def initializeResourceGroups(self):
ogre.TextureManager.getSingleton().setDefaultNumMipmaps(5)
ogre.ResourceGroupManager.getSingleton().initialiseAllResourceGroups()
def setupScene(self):
self.renderWindow = self.root.getAutoCreatedWindow()
self.sceneManager = self.root.createSceneManager(ogre.ST_EXTERIOR_CLOSE, "Default SceneManager")
self.camera = self.sceneManager.createCamera('PlayerCam')
self.camera.NearClipDistance = 5
self.viewPort = self.root.getAutoCreatedWindow().addViewport(self.camera)
self.sceneManager.setAmbientLight((0.2, 0.2, 0.2))
light = self.sceneManager.createLight("MainLight")
light.setType(ogre.Light.LT_DIRECTIONAL)
light.setDirection(-0.5, -0.5, 0)
self.sceneManager.setWorldGeometry("terrain.cfg")
self.camera.setPosition(ogre.Vector3(0, 0, 0))
self.camera.lookAt(ogre.Vector3(0, 0, 0))
## Setup the fog.
## fadeColour = (0.9, 0.9, 0.9)
## self.renderWindow.getViewport (0).backgroundColour = fadeColour
## self.sceneManager.setFog (ogre.FOG_LINEAR, fadeColour, 0.02, 50, 500)
## Setup a sky plane.
plane = ogre.Plane ((0, -1, 0), -10)
self.sceneManager.setSkyPlane (True, plane, "Examples/CloudySky", 100, 45, True, 0.8, 150, 150)
self.ogreChar = OgreCharacter("Robot001", self.sceneManager)
self.exCamera = ExtendedCamera("ExtendedCamera", self.sceneManager,
self.camera)
def createFrameListener(self):
self.eventListener = EventListener(self.renderWindow, self.camera, self.sceneManager, self, self.viewPort, True, True)
self.eventListener.setCharacter(self.ogreChar)
self.eventListener.setExtendedCamera(self.exCamera)
self.root.addFrameListener(self.eventListener)
def setupCEGUI(self):
sceneManager = self.sceneManager
# CEGUI
self.renderer = CEGUI.OgreCEGUIRenderer(self.renderWindow, ogre.RENDER_QUEUE_OVERLAY, False, 3000, sceneManager)
self.system = CEGUI.System(self.renderer)
CEGUI.SchemeManager.getSingleton().loadScheme("TaharezLookSkin.scheme")
self.system.setDefaultMouseCursor("TaharezLook", "MouseArrow")
self.system.setDefaultFont("BlueHighway-12")
# self.mainSheet = CEGUI.WindowManager.getSingleton().loadWindowLayout("facial.layout",0)
self.mainSheet = CEGUI.WindowManager.getSingleton().loadWindowLayout("myapplication.layout",0)
self.system.setGUISheet(self.mainSheet)
def startRenderLoop(self):
self.root.startRendering()
def cleanUp(self):
# Clean up CEGUI
print "CLEANING"
#del self.renderer
del self.system
# Clean up Ogre
#del self.exitListener
del self.root
if __name__ == '__main__':
try:
ta = Application()
ta.go()
except ogre.OgreException, e:
print "EXCEPTION: ",e
And the needed myapplication.layout:
<?xml version="1.0" ?>
<GUILayout>
<Window Type="DefaultGUISheet" Name="Cgcroot">
<Window Type="DefaultGUISheet" Name="CgcGui">
<Property Name="UnifiedSize" Value="{{4.10,0},{0.1,0}}" />
<Window Type="TaharezLook/TabControl" Name="CgcGui/TabCtrl">
<Property Name="UnifiedPosition" Value="{{0.0,0},{0.0,0}}" />
<Property Name="UnifiedSize" Value="{{0.5,0},{1.0,0}}" />
<Window Type="DefaultGUISheet" Name="CgcGui/TabCtrl/Page1">
<Property Name="Text" Value="File" />
<Window Type="TaharezLook/Button" Name="CgcGui/TabCtrl/Page1/QuitButton">
<Property Name="UnifiedPosition" Value="{{0.1,0},{0.3,0}}" />
<Property Name="UnifiedSize" Value="{{0.2,0},{0.5,0}}" />
<Property Name="Text" Value="Quit" />
</Window>
<Window Type="TaharezLook/Button" Name="CgcGui/TabCtrl/Page1/LoginButton">
<Property Name="UnifiedPosition" Value="{{0.3,0},{0.3,0}}" />
<Property Name="UnifiedSize" Value="{{0.2,0},{0.5,0}}" />
<Property Name="Text" Value="Login" />
</Window>
<Window Type="TaharezLook/Button" Name="CgcGui/TabCtrl/Page1/LobbyButton">
<Property Name="UnifiedPosition" Value="{{0.5,0},{0.3,0}}" />
<Property Name="UnifiedSize" Value="{{0.2,0},{0.5,0}}" />
<Property Name="Text" Value="Lobby" />
</Window>
<Window Type="TaharezLook/Button" Name="CgcGui/TabCtrl/Page1/RouletteButton">
<Property Name="UnifiedPosition" Value="{{0.7,0},{0.3,0}}" />
<Property Name="UnifiedSize" Value="{{0.2,0},{0.5,0}}" />
<Property Name="Text" Value="Roulette" />
</Window>
</Window>
</Window>
</Window>
</Window>
</GUILayout>