Beispiel #1
0
    def __init__(self, keys):
        self.modKeys = ModifierButtons()

        for key in keys:
            self.modKeys.addButton(key)
            self.accept(key.getName(), self.modKeys.buttonDown, [key])
            self.accept(key.getName() + '-up', self.modKeys.buttonUp, [key])
    def setup(self):
        """ Attaches the movement controller and inits the keybindings """

        # x
        self.showbase.accept("w", self._setMovement, [0, 1])
        self.showbase.accept("w-up", self._setMovement, [0, 0])
        self.showbase.accept("s", self._setMovement, [0, -1])
        self.showbase.accept("s-up", self._setMovement, [0, 0])

        # y
        self.showbase.accept("a", self._setMovement, [1, -1])
        self.showbase.accept("a-up", self._setMovement, [1, 0])
        self.showbase.accept("d", self._setMovement, [1, 1])
        self.showbase.accept("d-up", self._setMovement, [1, 0])

        # z
        self.showbase.accept("space", self._setMovement, [2, 1])
        self.showbase.accept("space-up", self._setMovement, [2, 0])
        self.showbase.accept("shift", self._setMovement, [2, -1])
        self.showbase.accept("shift-up", self._setMovement, [2, 0])

        # wireframe + debug + buffer viewer
        # self.showbase.accept("f3", self.showbase.toggleWireframe)
        self.showbase.accept("p", self._showDebugOutput)

        # mouse
        self.showbase.accept("mouse1", self._setMouseEnabled, [True])
        self.showbase.accept("mouse1-up", self._setMouseEnabled, [False])

        # arrow mouse navigation
        self.showbase.accept("arrow_up", self._setHprMovement, [1, 1])
        self.showbase.accept("arrow_up-up", self._setHprMovement, [1, 0])
        self.showbase.accept("arrow_down", self._setHprMovement, [1, -1])
        self.showbase.accept("arrow_down-up", self._setHprMovement, [1, 0])
        self.showbase.accept("arrow_left", self._setHprMovement, [0, 1])
        self.showbase.accept("arrow_left-up", self._setHprMovement, [0, 0])
        self.showbase.accept("arrow_right", self._setHprMovement, [0, -1])
        self.showbase.accept("arrow_right-up", self._setHprMovement, [0, 0])

        # increase / decrease speed
        self.showbase.accept("+", self._increaseSpeed)
        self.showbase.accept("-", self._decreaseSpeed)

        # disable modifier buttons to be able to move while pressing shift for
        # example
        self.showbase.mouseWatcherNode.setModifierButtons(ModifierButtons())
        self.showbase.buttonThrowers[0].node().setModifierButtons(
            ModifierButtons())

        # disable pandas builtin mouse control
        self.showbase.disableMouse()

        # add ourself as an update task
        self.showbase.addTask(self._update,
                              "updateMovementController",
                              priority=-19000)

        self.showbase.accept("1", PStatClient.connect)
        self.showbase.accept("3", self._resetToInitial)
 def enableAimKeys(self):
     self.leftPressed = 0
     self.rightPressed = 0
     base.mouseWatcherNode.setModifierButtons(ModifierButtons())
     base.buttonThrowers[0].node().setModifierButtons(ModifierButtons())
     self.accept(ROTATE_LEFT_KEY, self.__handleLeftKeyPressed)
     self.accept(ROTATE_RIGHT_KEY, self.__handleRightKeyPressed)
     self.accept(FORWARD_KEY, self.__handleUpKeyPressed)
     self.accept(BACKWARDS_KEY, self.__handleDownKeyPressed)
Beispiel #4
0
    def __init__(self):
        self.instructionText = addInstructions(0.95,
                                               '[ESC]: Leave Mouselook mode.')
        self.eventDispatcher = EventDispatcher()
        self.cameraMode = None
        self.clickPos = Vec2()
        self.lastMousePos = Vec2()
        self.focus = Vec3()
        self.mouseDown = False
        self.initialPos = Vec3()
        self.initialHpr = Vec3()
        self.initialMat = None

        # Disable the built-in mouse camera control (it sucks).
        base.disableMouse()
        self.setCameraMode(TRACKBALL)

        # Set the camera's initial position.
        base.camera.setPosHpr(0, 12, 30, 180, -70, 0)

        # Turn off events generated with modifier buttons, e.g. 'shift-a'
        # This is to keep keyboard control working after you alt-tab out
        # of the app.
        base.mouseWatcherNode.setModifierButtons(ModifierButtons())
        base.buttonThrowers[0].node().setModifierButtons(ModifierButtons())

        # This is a diagonal matrix that keeps track of movement key
        # state. The first three diagonal entries can be 1, 0, or -1.
        self.mouseLookTransMat = Mat4.scaleMat(Vec3(0.0, 0.0, 0.0))

        # Keep track of how many movement keys are currently pressed. This
        # lets us short-circuit past a lot of math when no keys are held.
        self.keysHeld = 0

        # Handle events for the movement keys.
        for key, value in key2MatArgs.items():
            self.accept(key, self._moveKeyHandler, value)

        self.accept('escape', self._escKeyHandler)
        self.accept('m', self._mKeyHandler)
        self.accept('mouse1', self._mouseDownHandler, [1])
        self.accept('mouse1-up', self._mouseUpHandler, [1])
        self.accept('mouse2', self._mouseDownHandler, [2])
        self.accept('mouse2-up', self._mouseUpHandler, [2])
        self.accept('wheel_up', self._mouseWheelHandler, [1])
        self.accept('wheel_down', self._mouseWheelHandler, [-1])

        self.modButtons = ModifierButtons()
        self.modButtons.addButton(KeyboardButton.control())
        self.accept('control', self.modButtons.buttonDown,
                    [KeyboardButton.control()])
        self.accept('control-up', self.modButtons.buttonUp,
                    [KeyboardButton.control()])

        self.accept(base.win.getWindowEvent(), self._windowHandler)
Beispiel #5
0
 def _gen_viewer(queue, max_points=17776, massage_que=None):
     base = ShowBase()
     base.setBackgroundColor(0, 0, 0)
     base.disableMouse()
     base.camera.setPos(0, -50, 20)
     base.camera.setHpr(0, -22, 0)
     base.mouseWatcherNode.set_modifier_buttons(ModifierButtons())
     base.buttonThrowers[0].node().set_modifier_buttons(ModifierButtons())
     base.setFrameRateMeter(True)
     pc_viewer = _PointCloudFrameViewer(point_cloud_size=max_points,
                                        queue=queue)
     base.run()
Beispiel #6
0
    def __init__(self):
        render.setAntialias(AntialiasAttrib.MAuto)

        # Enable physics - perhaps this should go someplace else, but it must
        # be done before the Vehicle is initialized.
        base.enableParticles()
        aei = AngularEulerIntegrator()
        base.physicsMgr.attachAngularIntegrator(aei)

        SelectionEngine.getDefault().enable()
        SelectionManager.getDefault().enable()

        # Make the environment and the vehicle model.
        makeEnvironment()
        self.vehicle = Vehicle(render)

        MissionElement.loadElementConfig('mission_elements.plist')

        #layoutName = AppPreferences.get('last_layout', 'defaultLayout.plist')
        if len(sys.argv) == 2:
            layoutName = sys.argv[1]
            print "Using command line argument %s for layout" % layoutName
        else:
            print "Using default layout file"
            print "Use ./sim2.py [layout file] to use a different layout"
            print "Or press Ctrl+O to open a new layout in the simulator"
            layoutName = 'defaultLayout.plist'

        self.layout = MissionLayout.loadLayout(layoutName)
        render.attachNewNode(self.layout)

        self.vehicle.setLayout(self.layout)  #Link the layout

        # Set up render buffer viewer, to aide debugging.
        self.accept("v", base.bufferViewer.toggleEnable)
        self.accept("V", base.bufferViewer.toggleEnable)
        base.bufferViewer.setPosition("llcorner")

        # Set up file saver
        self.accept('s', self._saveLayout)
        self.accept('o', self._openLayout)
        self.accept('f', self._setFreq)
        root = Tk()
        root.withdraw()
        self.modButtons = ModifierButtons()
        self.modButtons.addButton(KeyboardButton.control())
        self.accept('control', self.modButtons.buttonDown,
                    [KeyboardButton.control()])
        self.accept('control-up', self.modButtons.buttonUp,
                    [KeyboardButton.control()])
        # Add GUI Controls
        '''
Beispiel #7
0
class ButtonWatcher(DirectObject):
    def __init__(self, keys):
        self.modKeys = ModifierButtons()

        for key in keys:
            self.modKeys.addButton(key)
            self.accept(key.getName(), self.modKeys.buttonDown, [key])
            self.accept(key.getName() + '-up', self.modKeys.buttonUp, [key])

    def getKeys(self):
        return self.modKeys

    def destroy(self):
        self.ignoreAll()
class ButtonWatcher(DirectObject):
    def __init__(self, keys):
        self.modKeys = ModifierButtons()

        for key in keys:
            self.modKeys.addButton(key)
            self.accept(key.getName(), self.modKeys.buttonDown, [key])
            self.accept(key.getName()+'-up', self.modKeys.buttonUp, [key])

    def getKeys(self):
        return self.modKeys

    def destroy(self):
        self.ignoreAll()
Beispiel #9
0
 def __init__(self):
     self.__jumpPost = 0
     self.setPressHandlers(self.NULL_HANDLERS)
     self.setReleaseHandlers(self.NULL_HANDLERS)
     self.origMb = base.buttonThrowers[0].node().getModifierButtons()
     base.buttonThrowers[0].node().setModifierButtons(ModifierButtons())
     self.enable()
    def __init__(self, keys):
        self.modKeys = ModifierButtons()

        for key in keys:
            self.modKeys.addButton(key)
            self.accept(key.getName(), self.modKeys.buttonDown, [key])
            self.accept(key.getName()+'-up', self.modKeys.buttonUp, [key])
Beispiel #11
0
    def setup_bindings_for_sensors(self):
        modifiers = ModifierButtons()

        modifiers.addButton(KeyboardButton.lshift())
        modifiers.addButton(KeyboardButton.rshift())
        modifiers.addButton(KeyboardButton.lcontrol())
        modifiers.addButton(KeyboardButton.rcontrol())
        modifiers.addButton(KeyboardButton.lalt())
        modifiers.addButton(KeyboardButton.ralt())
        modifiers.addButton(KeyboardButton.meta())

        # For supporting "use_all_keys" and modifier keys
        button_node = base.buttonThrowers[0].node()
        button_node.setButtonDownEvent('buttonDown')
        button_node.setButtonUpEvent('buttonUp')
        button_node.setModifierButtons(modifiers)
def test_modifierbuttons_assign():
    # Tests assignment operator.
    btns1 = ModifierButtons()
    btns1.add_button("space")

    btns2 = ModifierButtons()
    btns2.assign(btns1)

    assert btns1 == btns2
    assert tuple(btns1.buttons) == tuple(btns2.buttons)
    def __init__(self):
        self.instructionText = addInstructions(0.95,
                '[ESC]: Leave Mouselook mode.')
        self.eventDispatcher = EventDispatcher()
        self.cameraMode = None
        self.clickPos = Vec2()
        self.lastMousePos = Vec2()
        self.focus = Vec3()
        self.mouseDown = False
        self.initialPos = Vec3()
        self.initialHpr = Vec3()
        self.initialMat = None

        # Disable the built-in mouse camera control (it sucks).
        base.disableMouse()
        self.setCameraMode(TRACKBALL)

        # Set the camera's initial position.
        base.camera.setPosHpr(0, 12, 30, 180, -70, 0)
        
        # Turn off events generated with modifier buttons, e.g. 'shift-a'
        # This is to keep keyboard control working after you alt-tab out
        # of the app.
        base.mouseWatcherNode.setModifierButtons(ModifierButtons())
        base.buttonThrowers[0].node().setModifierButtons(ModifierButtons())

        # This is a diagonal matrix that keeps track of movement key
        # state. The first three diagonal entries can be 1, 0, or -1.
        self.mouseLookTransMat = Mat4.scaleMat(Vec3(0.0, 0.0, 0.0))
        
        # Keep track of how many movement keys are currently pressed. This
        # lets us short-circuit past a lot of math when no keys are held.
        self.keysHeld = 0

        # Handle events for the movement keys.       
        for key, value in key2MatArgs.items():
            self.accept(key, self._moveKeyHandler, value)

        self.accept('escape', self._escKeyHandler)
        self.accept('m', self._mKeyHandler)
        self.accept('mouse1', self._mouseDownHandler, [1])
        self.accept('mouse1-up', self._mouseUpHandler, [1])
        self.accept('mouse2', self._mouseDownHandler, [2])
        self.accept('mouse2-up', self._mouseUpHandler, [2])
        self.accept('wheel_up', self._mouseWheelHandler, [1])
        self.accept('wheel_down', self._mouseWheelHandler, [-1])

        self.modButtons = ModifierButtons()
        self.modButtons.addButton(KeyboardButton.control())
        self.accept('control', self.modButtons.buttonDown,
                [KeyboardButton.control()])
        self.accept('control-up', self.modButtons.buttonUp,
                [KeyboardButton.control()])

        self.accept(base.win.getWindowEvent(), self._windowHandler)
Beispiel #14
0
    def __init__(self):
        render.setAntialias(AntialiasAttrib.MAuto)

        # Enable physics - perhaps this should go someplace else, but it must
        # be done before the Vehicle is initialized.
        base.enableParticles()
        aei = AngularEulerIntegrator()
        base.physicsMgr.attachAngularIntegrator(aei)

        SelectionEngine.getDefault().enable()
        SelectionManager.getDefault().enable()
        
        # Make the environment and the vehicle model.
        makeEnvironment()
        self.vehicle = Vehicle(render)

        MissionElement.loadElementConfig('mission_elements.plist')

        #layoutName = AppPreferences.get('last_layout', 'defaultLayout.plist')
        if len(sys.argv) == 2:
            layoutName = sys.argv[1]
            print "Using command line argument %s for layout" %layoutName
        else:
            print "Using default layout file"
            print "Use ./sim2.py [layout file] to use a different layout"
            print "Or press Ctrl+O to open a new layout in the simulator"
            layoutName = 'defaultLayout.plist'

        self.layout = MissionLayout.loadLayout(layoutName)
        render.attachNewNode(self.layout)

        self.vehicle.setLayout(self.layout) #Link the layout 

        # Set up render buffer viewer, to aide debugging.
        self.accept("v", base.bufferViewer.toggleEnable)
        self.accept("V", base.bufferViewer.toggleEnable)
        base.bufferViewer.setPosition("llcorner")
        
        # Set up file saver
        self.accept('s', self._saveLayout)
        self.accept('o', self._openLayout)
        self.accept('f', self._setFreq)
        root = Tk()
        root.withdraw()
        self.modButtons = ModifierButtons()
        self.modButtons.addButton(KeyboardButton.control())
        self.accept('control', self.modButtons.buttonDown,
                [KeyboardButton.control()])
        self.accept('control-up', self.modButtons.buttonUp,
                [KeyboardButton.control()])
        # Add GUI Controls
        '''
Beispiel #15
0
    def __init__(self, base):

        self.base = base
        self.key_map = {}
        self.keys = []

        accepted_keys = [
            'shift', 'control', 'mouse1', 'mouse2', 'mouse3', 'space',
            'wheel_up', 'wheel_down', 'g', 's', 'r', 'e', '/', 'x', 'y', 'z',
            '1', '2', '3', '5'
        ]
        base.mouseWatcherNode.set_modifier_buttons(ModifierButtons())
        base.buttonThrowers[0].node().set_modifier_buttons(ModifierButtons())

        index = 0
        for k in accepted_keys:
            self.key_map[k] = index
            self.keys.append(0)
            self.base.accept(k, self.setKeys, [index, 1])
            self.base.accept(k + '-up', self.setKeys, [index, 0])

            index += 1
Beispiel #16
0
    def __init__(self, playerNP):

        # Store player and reparent camera
        self.Player = playerNP
        # Attach camera to parent
        base.camera.reparentTo(self.Player)

        # Default variables
        self.movingForward = False
        self.movingLeft = False
        self.movingRight = False
        self.movingBack = False
        self.movingUp = False
        self.baseSpeed = 0.2  # basis for all relative speed calcs
        self.moveSpeed = self.baseSpeed
        self.mouseSensitivity = 0.2

        # Hide the cursor
        self.props = WindowProperties()
        self.props.setCursorHidden(True)
        base.win.requestProperties(self.props)
        self.handleWindowResize()  # Set center x/y to pull cursor to

        # Disable modifier keys like shift so I can use manually
        # and they don't throw a shift-x event instead
        base.buttonThrowers[0].node().setModifierButtons(ModifierButtons())
        # Disable default mouse/camera task
        base.disableMouse()
        base.accept("w", self.startMoveForward)
        base.accept("w-up", self.stopMoveForward)
        base.accept("a", self.startMoveLeft)
        base.accept("a-up", self.stopMoveLeft)
        base.accept("d", self.startMoveRight)
        base.accept("d-up", self.stopMoveRight)
        base.accept("s", self.startMoveBack)
        base.accept("s-up", self.stopMoveBack)
        base.accept("space", self.startMoveUp)
        base.accept("space-up", self.stopMoveUp)
        base.accept("shift", self.startMoveFast)
        base.accept("shift-up", self.stopMoveFast)
        base.accept("escape", sys.exit)
        base.accept("window-resize", self.handleWindowResize)

        # Player control task
        base.taskMgr.add(self.playerControlTask, "playerControlTask")
def test_modifierbuttons_state():
    btns = ModifierButtons()
    btns.add_button("alt")
    btns.add_button("shift")
    btns.add_button("control")
    assert not btns.is_any_down()

    # Not tracked
    btns.button_down("enter")
    assert not btns.is_any_down()

    # Tracked
    btns.button_down("shift")
    assert btns.is_any_down()
    assert not btns.is_down(0)
    assert btns.is_down(1)
    assert not btns.is_down(2)

    btns.button_up("shift")
    assert not btns.is_any_down()
    assert not btns.is_down(0)
    assert not btns.is_down(1)
    assert not btns.is_down(2)

    btns.button_down("alt")
    btns.button_down("shift")
    assert btns.is_any_down()
    assert btns.is_down(0)
    assert btns.is_down(1)
    assert not btns.is_down(2)

    btns.all_buttons_up()
    assert not btns.is_any_down()
    assert not btns.is_down(0)
    assert not btns.is_down(1)
    assert not btns.is_down(2)
Beispiel #18
0
def windowMaker(base, label):
    # find an open slot, if none, return false
    windict = dict()
    grid = None
    for i in range(grid_size[0]):
        for j in range(grid_size[1]):
            if occupied[i][j] == False:
                grid = (i, j)
                occupied[i][j] = True
                break
        else:
            continue
        break
    if not grid: return False
    windict['grid'] = grid
    position = grid_to_screen_pos(*grid)

    #open window
    newwin = base.openWindow(name=label)
    newwin.setWindowEvent(label + "-event")
    listener.accept(newwin.getWindowEvent(), windowEvent)
    windict['win'] = newwin

    #format window
    wp = WindowProperties()
    wp.setOrigin(*position)
    wp.setSize(*ws)
    newwin.requestProperties(wp)

    #make 3d-mousewatcher display region
    displayRegion = newwin.getDisplayRegion(0)
    displayRegion.setDimensions(.3, 1, 0, 1)
    mkNode = MouseAndKeyboard(newwin, 0, label + "_keyboard_mouse")
    mk = base.dataRoot.attachNewNode(mkNode)
    windict['mk'] = mk
    modis = ModifierButtons()
    modis.addButton(ButtonHandle('shift'))
    modis.addButton(ButtonHandle('control'))
    mwNode = MouseWatcher(label)
    mwNode.setModifierButtons(modis)
    mwNode.setDisplayRegion(displayRegion)
    mw = mk.attachNewNode(mwNode)
    windict['mw'] = mw
    bt = ButtonThrower(label + "_button_thrower")
    bt.setModifierButtons(modis)
    windict['bt'] = bt
    bt.setPrefix(label + "_")
    mw.attachNewNode(bt)
    #listen for default button events
    for button in buttons:
        listener.accept(bt.prefix + button, buttons[button])

    #format render display region
    render_dr = newwin.getDisplayRegion(1)
    windict['render_dr'] = render_dr
    render_dr.setDimensions(.3, 1, 0, 1)

    #create a display region for Gui Elements
    gui_dr = newwin.makeDisplayRegion(0, .3, .3, 1)
    # gui_dr.setSort(20)
    mwNodegui = MouseWatcher(label + "gui")
    mwNodegui.setDisplayRegion(gui_dr)
    mwgui = mk.attachNewNode(mwNodegui)

    #create a 2d render/aspect for gui
    rendergui = NodePath('render2d')
    rendergui.setDepthWrite(0)
    rendergui.setMaterialOff(1)
    rendergui.setTwoSided(1)
    #set up aspect2d
    aspectgui = rendergui.attachNewNode(PGTop('aspectgui'))
    aspectgui.node().setMouseWatcher(mwgui.node())
    #set up camera
    camNodegui = Camera("camNode2d")
    cameragui = rendergui.attachNewNode(camNodegui)
    cameragui.setPos(0, 0, 0)
    cameragui.setDepthTest(False)
    cameragui.setDepthWrite(False)
    lens = OrthographicLens()
    lens.setFilmSize(2, 2)
    lens.setNearFar(-1000, 1000)
    cameragui.node().setLens(lens)
    gui_dr.setCamera(cameragui)
    #make frame for gui
    frame = DirectFrame(frameSize=(-1, 1, -1, 1),
                        frameColor=(.5, .5, .5, 1),
                        relief='ridge')
    frame.reparentTo(aspectgui)
    frame.setTransparency(0)
    windict['gui_frame'] = frame

    #create Gui elements
    guibuttons = dict()
    # guibuttons['Create'] = label+"_mode_create"
    guibuttons['Preview'] = label + "_preview"
    # createButton(base, frame, .7, "Create", label+"_mode_create")
    createButton(base, frame, .7, "Preview", label + "_preview")
    windict['guibuttons'] = guibuttons

    #create a display region for math data preview
    preview_dr = newwin.makeDisplayRegion(0, .3, 0, .3)
    windict['preview_dr'] = preview_dr
    # preview_label = label+"_preview"
    # preview_mwNode = MouseWatcher(preview_label)
    # preview_mwNode.setDisplayRegion(preview_dr)
    # preview_mw = mk.attachNewNode(preview_mwNode)
    # preview_bt = ButtonThrower(preview_label+"_button_thrower")
    # preview_bt.setPrefix(preview_label+"_")
    # preview_mw.attachNewNode(preview_bt)
    # preview_dr.setSort(30)

    win_to_windict[newwin] = windict

    return windict
Beispiel #19
0
class World(DirectObject):
    instance = None

    def __init__(self):
        render.setAntialias(AntialiasAttrib.MAuto)

        # Enable physics - perhaps this should go someplace else, but it must
        # be done before the Vehicle is initialized.
        base.enableParticles()
        aei = AngularEulerIntegrator()
        base.physicsMgr.attachAngularIntegrator(aei)

        SelectionEngine.getDefault().enable()
        SelectionManager.getDefault().enable()

        # Make the environment and the vehicle model.
        makeEnvironment()
        self.vehicle = Vehicle(render)

        MissionElement.loadElementConfig('mission_elements.plist')

        #layoutName = AppPreferences.get('last_layout', 'defaultLayout.plist')
        if len(sys.argv) == 2:
            layoutName = sys.argv[1]
            print "Using command line argument %s for layout" % layoutName
        else:
            print "Using default layout file"
            print "Use ./sim2.py [layout file] to use a different layout"
            print "Or press Ctrl+O to open a new layout in the simulator"
            layoutName = 'defaultLayout.plist'

        self.layout = MissionLayout.loadLayout(layoutName)
        render.attachNewNode(self.layout)

        self.vehicle.setLayout(self.layout)  #Link the layout

        # Set up render buffer viewer, to aide debugging.
        self.accept("v", base.bufferViewer.toggleEnable)
        self.accept("V", base.bufferViewer.toggleEnable)
        base.bufferViewer.setPosition("llcorner")

        # Set up file saver
        self.accept('s', self._saveLayout)
        self.accept('o', self._openLayout)
        self.accept('f', self._setFreq)
        root = Tk()
        root.withdraw()
        self.modButtons = ModifierButtons()
        self.modButtons.addButton(KeyboardButton.control())
        self.accept('control', self.modButtons.buttonDown,
                    [KeyboardButton.control()])
        self.accept('control-up', self.modButtons.buttonUp,
                    [KeyboardButton.control()])
        # Add GUI Controls
        '''
        buttonReady = makeGeom('button_ready.png')
        b = DirectButton(geom = (buttonReady,
                                 makeGeom('button_click.png'),
                                 makeGeom('button_rollover.png'),
                                 buttonReady),
                          relief = None)
        b.reparentTo(pixel2d)
        b.hide()
        b.setPos(base.win.getXSize()/2, 0, -base.win.getYSize()/2)
        b.setScale(1, 1, 1)
        b.bind(DirectGuiGlobals.ACCEPT, eventHandler, ['accept'])
        b.bind(DirectGuiGlobals.ACCEPTFAILED, eventHandler, ['accept failed'])
        b.bind(DirectGuiGlobals.ADJUST, eventHandler, ['adjust'])
        b.bind(DirectGuiGlobals.B1CLICK, eventHandler, ['b1click'])
        b.bind(DirectGuiGlobals.B1PRESS, eventHandler, ['b1press'])
        b.bind(DirectGuiGlobals.B1RELEASE, eventHandler, ['b1release'])
        b.bind(DirectGuiGlobals.B2CLICK, eventHandler, ['b2click'])
        b.bind(DirectGuiGlobals.B2PRESS, eventHandler, ['b2press'])
        b.bind(DirectGuiGlobals.B2RELEASE, eventHandler, ['b2release'])
        b.bind(DirectGuiGlobals.B3CLICK, eventHandler, ['b3click'])
        b.bind(DirectGuiGlobals.B3PRESS, eventHandler, ['b3press'])
        b.bind(DirectGuiGlobals.B3RELEASE, eventHandler, ['b3release'])
        b.bind(DirectGuiGlobals.ENTER, eventHandler, ['enter'])
        b.bind(DirectGuiGlobals.EXIT, eventHandler, ['exit'])
        b.bind(DirectGuiGlobals.WITHIN, eventHandler, ['within'])
        b.bind(DirectGuiGlobals.WITHOUT, eventHandler, ['without'])
        b.bind(DirectGuiGlobals.CURSORMOVE, eventHandler, ['cursormove'])
        # b['frameSize'] = (3, 3, 3, 3)
        '''

    @classmethod
    def getInstance(cls):
        if cls.instance == None:
            cls.instance = World()
        return cls.instance

    def _saveLayout(self):
        if self.modButtons.isDown(KeyboardButton.control()):
            self.modButtons.buttonUp(KeyboardButton.control())
            self.modButtons.buttonUp(KeyboardButton.asciiKey('s'))
            filename = asksaveasfilename(filetypes=[('plist files',
                                                     '*.plist')])
            if filename:
                self.layout.save(filename)
                AppPreferences.set('last_layout', filename)

    def _setFreq(self):
        #TODO: Check pinger selected

        pinger = None
        for element in self.layout.elements:
            if element.getTypeName() == "Pinger" and element.isSelected():
                pinger = element
                break

        if pinger is None:
            return

        newfreq = askinteger("Set Pinger Frequency",
                             "Set this pinger to which frequency? (in Hz)",
                             initialvalue=pinger.pinger_frequency,
                             minvalue=10000,
                             maxvalue=50000)
        if newfreq is None:
            print "No frequency specified, aborting"
            return

        pinger.pinger_frequency = newfreq
        print "Frequency of pinger set to %d Hz" % newfreq

    def _openLayout(self):
        if self.modButtons.isDown(KeyboardButton.control()):
            self.modButtons.buttonUp(KeyboardButton.control())
            self.modButtons.buttonUp(KeyboardButton.asciiKey('o'))
            filename = askopenfilename(filetypes=[('plist files', '*.plist')])
            if filename:
                if self.layout:
                    NodePath(self.layout).detachNode()
                self.layout = MissionLayout.loadLayout(filename)
                render.attachNewNode(self.layout)
                AppPreferences.set('last_layout', filename)
class CameraController(DirectObject):
    instance = None

    def __init__(self):
        self.instructionText = addInstructions(0.95,
                '[ESC]: Leave Mouselook mode.')
        self.eventDispatcher = EventDispatcher()
        self.cameraMode = None
        self.clickPos = Vec2()
        self.lastMousePos = Vec2()
        self.focus = Vec3()
        self.mouseDown = False
        self.initialPos = Vec3()
        self.initialHpr = Vec3()
        self.initialMat = None

        # Disable the built-in mouse camera control (it sucks).
        base.disableMouse()
        self.setCameraMode(TRACKBALL)

        # Set the camera's initial position.
        base.camera.setPosHpr(0, 12, 30, 180, -70, 0)
        
        # Turn off events generated with modifier buttons, e.g. 'shift-a'
        # This is to keep keyboard control working after you alt-tab out
        # of the app.
        base.mouseWatcherNode.setModifierButtons(ModifierButtons())
        base.buttonThrowers[0].node().setModifierButtons(ModifierButtons())

        # This is a diagonal matrix that keeps track of movement key
        # state. The first three diagonal entries can be 1, 0, or -1.
        self.mouseLookTransMat = Mat4.scaleMat(Vec3(0.0, 0.0, 0.0))
        
        # Keep track of how many movement keys are currently pressed. This
        # lets us short-circuit past a lot of math when no keys are held.
        self.keysHeld = 0

        # Handle events for the movement keys.       
        for key, value in key2MatArgs.items():
            self.accept(key, self._moveKeyHandler, value)

        self.accept('escape', self._escKeyHandler)
        self.accept('m', self._mKeyHandler)
        self.accept('mouse1', self._mouseDownHandler, [1])
        self.accept('mouse1-up', self._mouseUpHandler, [1])
        self.accept('mouse2', self._mouseDownHandler, [2])
        self.accept('mouse2-up', self._mouseUpHandler, [2])
        self.accept('wheel_up', self._mouseWheelHandler, [1])
        self.accept('wheel_down', self._mouseWheelHandler, [-1])

        self.modButtons = ModifierButtons()
        self.modButtons.addButton(KeyboardButton.control())
        self.accept('control', self.modButtons.buttonDown,
                [KeyboardButton.control()])
        self.accept('control-up', self.modButtons.buttonUp,
                [KeyboardButton.control()])

        self.accept(base.win.getWindowEvent(), self._windowHandler)

    @classmethod
    def getInstance(cls):
        if cls.instance == None:
            cls.instance = cls()
        return cls.instance

    def setFocus(self, position):
        self.focus = position
        base.camera.lookAt(render, position)

    def addEventHandler(self, evtType, handler):
        self.eventDispatcher.addHandler(evtType, handler)

    def getCameraMode(self):
        return self.cameraMode

    def setCameraMode(self, mode):
        if mode == self.cameraMode:
            return

        winProps = WindowProperties()
        
        # Tear-down code for the current mode.
        if self.cameraMode == MOUSELOOK:
            winProps.setCursorHidden(False)
            self.removeTask(self.viewTask)
        elif self.cameraMode == TRACKBALL:
            self.removeTask(self.viewTask)

        # Set-up code for the new mode.
        if mode == MOUSELOOK:
            winProps.setCursorHidden(True)
            
            # Mouse accumulator. Whenever the mouse moves, it is reset to the
            # center of the window. The accumulator keeps track of the total
            # movement
            self.mouseAccX = 0
            self.mouseAccY = 0
            self.recenterMouse = True

            # Add a task that moves the camera based on mouse position.
            self.viewTask = taskMgr.add(self._mlViewTask, 'MLViewTask')
            self.lastFrameTime = 0  # Used to calculate dt in mlViewTask.
            self.instructionText.setText('[ESC]: Leave Mouselook Mode')
        
        elif mode == TRACKBALL:
            self.instructionText.setText('[m]: Enter Mouselook Mode')
            self.viewTask = taskMgr.add(self._trackballTask, 'TrackballTask')

        self.cameraMode = mode
        self.eventDispatcher.dispatchEvent(EVT_CAMERA_MODE, self)
        base.win.requestProperties(winProps)

    def _windowHandler(self, window):
        pos = aspect2d.find('a2dTopLeft').getPos()
        self.instructionText.setPos(pos.getX() + 0.05, pos.getZ() - 0.05)
        hasFocus = window.getProperties().getForeground()
        if not hasFocus:
            self.setCameraMode(TRACKBALL)

    def _escKeyHandler(self):
        self.setCameraMode(TRACKBALL)

    def _mKeyHandler(self):
        if self.cameraMode == MOUSELOOK:
            self.setCameraMode(TRACKBALL)
        else:
            self.setCameraMode(MOUSELOOK)

    def _mouseWheelHandler(self, arg):
        deltY = base.camera.getPos().length() * arg * 0.15
        transl = Mat4.translateMat(0, deltY, 0)
        base.camera.setMat(transl * base.camera.getMat())
        self.eventDispatcher.dispatchEvent(EVT_CAMERA_MOVE, base.camera)

    def _mouseDownHandler(self, button):
        if base.mouseWatcherNode.hasMouse():
            if button == 2 or self.modButtons.isDown(KeyboardButton.control()):
                self.clickPos = Vec2(base.mouseWatcherNode.getMouse())
                self.mouseDown = True
                offset = self.focus - base.camera.getPos()
                self.initialTranslation = offset.length()
                self.initialHpr = base.camera.getHpr()

    def _mouseUpHandler(self, button):
        self.mouseDown = False
            
    def _moveKeyHandler(self, *matArgs):
        self.mouseLookTransMat.setCell(*matArgs)
        
        # matArgs[2] is 0 for key release events.
        if (matArgs[2]):
            self.keysHeld += 1
        else:
            self.keysHeld -= 1

    def _trackballTask(self, task):
        if not self.mouseDown:
            return Task.cont

        if (base.mouseWatcherNode.hasMouse()):
            mpos = base.mouseWatcherNode.getMouse()
            if mpos == self.lastMousePos:
                return Task.cont

            mDelta = mpos - self.clickPos

            heading = -mDelta.x * 100 + self.initialHpr.x
            pitch = mDelta.y * 100 + self.initialHpr.y
            if pitch > 90:
                pitch = 90
            elif pitch < -90:
                pitch = -90
            trans1 = Mat4.translateMat(self.focus)
            rotx = Mat4.rotateMat(heading, Vec3(0, 0, 1))
            roty = Mat4.rotateMat(pitch, Vec3(1, 0, 0))
            trans2 = Mat4.translateMat(0, -self.initialTranslation, 0)
            rotation = trans2 * roty * rotx * trans1
            base.camera.setMat(rotation)
            self.eventDispatcher.dispatchEvent(EVT_CAMERA_MOVE, base.camera)
            
            self.lastMousePos = Vec2(mpos)
        return Task.cont

    def _mlViewTask(self, task):
        t = globalClock.getFrameTime()
        dt = t - self.lastFrameTime
        self.lastFrameTime = t
        if (self.keysHeld):
            # Update camera position based on keyboard controls.
            T = Mat4()
            T.invertAffineFrom(base.camera.getMat())
            cameraMoveMat = T*self.mouseLookTransMat
            xDir = cameraMoveMat.getCol3(0)
            yDir = cameraMoveMat.getCol3(1)
            zDir = cameraMoveMat.getCol3(2)
            currentPos = base.camera.getPos()
            nextPos = currentPos + (xDir + yDir + zDir)*(dt*8)
            base.camera.setPos(nextPos)
            self.eventDispatcher.dispatchEvent(EVT_CAMERA_MOVE, base.camera)

        if (base.mouseWatcherNode.hasMouse()):
            halfWidth = base.win.getProperties().getXSize()/2
            halfHeight = base.win.getProperties().getYSize()/2
            if self.recenterMouse:
                # Don't move the camera, but center the pointer. This is
                # useful when entering mouselook mode, to prevent the camera
                # from jumping to the pointer.
                heading, pitch = base.camera.getH(), base.camera.getP()
                self.mouseAccX = int(heading / ML_MULT)
                self.mouseAccY = int(pitch / ML_MULT)
                self.recenterMouse = False # Only do this once.
            else:
                mpos = base.mouseWatcherNode.getMouse()
                x, y = mpos.getX(), mpos.getY()
                
                # short-circuit if mouse hasn't moved or is outside the window.
                if x == 0 and y == 0 or x > 1.0 or y > 1.0:
                    return Task.cont
                # Convert x and y to pixels.
                self.mouseAccX -= int(round(x*halfWidth))
                self.mouseAccY += int(round(y*halfHeight))

                base.camera.setHpr(self.mouseAccX*ML_MULT,
                        self.mouseAccY*ML_MULT, 0.0)
            base.win.movePointer(0, halfWidth, halfHeight)
            
        return Task.cont
Beispiel #21
0
class World(DirectObject):
    instance = None

    def __init__(self):
        render.setAntialias(AntialiasAttrib.MAuto)

        # Enable physics - perhaps this should go someplace else, but it must
        # be done before the Vehicle is initialized.
        base.enableParticles()
        aei = AngularEulerIntegrator()
        base.physicsMgr.attachAngularIntegrator(aei)

        SelectionEngine.getDefault().enable()
        SelectionManager.getDefault().enable()
        
        # Make the environment and the vehicle model.
        makeEnvironment()
        self.vehicle = Vehicle(render)

        MissionElement.loadElementConfig('mission_elements.plist')

        #layoutName = AppPreferences.get('last_layout', 'defaultLayout.plist')
        if len(sys.argv) == 2:
            layoutName = sys.argv[1]
            print "Using command line argument %s for layout" %layoutName
        else:
            print "Using default layout file"
            print "Use ./sim2.py [layout file] to use a different layout"
            print "Or press Ctrl+O to open a new layout in the simulator"
            layoutName = 'defaultLayout.plist'

        self.layout = MissionLayout.loadLayout(layoutName)
        render.attachNewNode(self.layout)

        self.vehicle.setLayout(self.layout) #Link the layout 

        # Set up render buffer viewer, to aide debugging.
        self.accept("v", base.bufferViewer.toggleEnable)
        self.accept("V", base.bufferViewer.toggleEnable)
        base.bufferViewer.setPosition("llcorner")
        
        # Set up file saver
        self.accept('s', self._saveLayout)
        self.accept('o', self._openLayout)
        self.accept('f', self._setFreq)
        root = Tk()
        root.withdraw()
        self.modButtons = ModifierButtons()
        self.modButtons.addButton(KeyboardButton.control())
        self.accept('control', self.modButtons.buttonDown,
                [KeyboardButton.control()])
        self.accept('control-up', self.modButtons.buttonUp,
                [KeyboardButton.control()])
        # Add GUI Controls
        '''
        buttonReady = makeGeom('button_ready.png')
        b = DirectButton(geom = (buttonReady,
                                 makeGeom('button_click.png'),
                                 makeGeom('button_rollover.png'),
                                 buttonReady),
                          relief = None)
        b.reparentTo(pixel2d)
        b.hide()
        b.setPos(base.win.getXSize()/2, 0, -base.win.getYSize()/2)
        b.setScale(1, 1, 1)
        b.bind(DirectGuiGlobals.ACCEPT, eventHandler, ['accept'])
        b.bind(DirectGuiGlobals.ACCEPTFAILED, eventHandler, ['accept failed'])
        b.bind(DirectGuiGlobals.ADJUST, eventHandler, ['adjust'])
        b.bind(DirectGuiGlobals.B1CLICK, eventHandler, ['b1click'])
        b.bind(DirectGuiGlobals.B1PRESS, eventHandler, ['b1press'])
        b.bind(DirectGuiGlobals.B1RELEASE, eventHandler, ['b1release'])
        b.bind(DirectGuiGlobals.B2CLICK, eventHandler, ['b2click'])
        b.bind(DirectGuiGlobals.B2PRESS, eventHandler, ['b2press'])
        b.bind(DirectGuiGlobals.B2RELEASE, eventHandler, ['b2release'])
        b.bind(DirectGuiGlobals.B3CLICK, eventHandler, ['b3click'])
        b.bind(DirectGuiGlobals.B3PRESS, eventHandler, ['b3press'])
        b.bind(DirectGuiGlobals.B3RELEASE, eventHandler, ['b3release'])
        b.bind(DirectGuiGlobals.ENTER, eventHandler, ['enter'])
        b.bind(DirectGuiGlobals.EXIT, eventHandler, ['exit'])
        b.bind(DirectGuiGlobals.WITHIN, eventHandler, ['within'])
        b.bind(DirectGuiGlobals.WITHOUT, eventHandler, ['without'])
        b.bind(DirectGuiGlobals.CURSORMOVE, eventHandler, ['cursormove'])
        # b['frameSize'] = (3, 3, 3, 3)
        '''

    @classmethod
    def getInstance(cls):
        if cls.instance == None:
            cls.instance = World()
        return cls.instance

    def _saveLayout(self):
        if self.modButtons.isDown(KeyboardButton.control()):
            self.modButtons.buttonUp(KeyboardButton.control())
            self.modButtons.buttonUp(KeyboardButton.asciiKey('s'))
            filename = asksaveasfilename(filetypes=[('plist files', '*.plist')])
            if filename:
                self.layout.save(filename)
                AppPreferences.set('last_layout', filename)

    def _setFreq(self):
        #TODO: Check pinger selected

        pinger = None
        for element in self.layout.elements:
            if element.getTypeName() == "Pinger" and element.isSelected():
                pinger = element
                break

        if pinger is None:
            return

        newfreq = askinteger("Set Pinger Frequency", "Set this pinger to which frequency? (in Hz)", initialvalue=pinger.pinger_frequency, minvalue=10000, maxvalue=50000)
        if newfreq is None:
            print "No frequency specified, aborting"
            return

        pinger.pinger_frequency = newfreq
        print "Frequency of pinger set to %d Hz" % newfreq


    def _openLayout(self):
        if self.modButtons.isDown(KeyboardButton.control()):
            self.modButtons.buttonUp(KeyboardButton.control())
            self.modButtons.buttonUp(KeyboardButton.asciiKey('o'))
            filename = askopenfilename(filetypes=[('plist files', '*.plist')])
            if filename:
                if self.layout:
                    NodePath(self.layout).detachNode()
                self.layout = MissionLayout.loadLayout(filename)
                render.attachNewNode(self.layout)
                AppPreferences.set('last_layout', filename)
Beispiel #22
0
    def __init__(self, camera, r_init=2., enable_visual_aids=True):
        """ """
        CameraGear.__init__(self)

        base.disableMouse()

        self._orbit_center = None
        self.set_orbit_center(OrbiterOrtho.orbit_center_0, not_just_init=False)

        self.before_aspect_ratio_changed_at_init = True  # ?

        self.radius_init = r_init
        self.radius = r_init
        self.phi = OrbiterOrtho.phi_0
        self.theta = OrbiterOrtho.theta_0

        # self._previous_zoom_step_plane_coords = None
        # self.set_previous_zoom_step_plane_coords(0., 0.)

        # camera stuff
        self.camera = camera

        # # init the camera pos
        x, y, z = self.get_cam_coords(correct_for_camera_setting=True,
                                      fixed_phi=self.phi,
                                      fixed_theta=self.theta,
                                      fixed_r=self.radius)

        self.camera.setPos(
            x, y, z
        )  # TODO: is this really necessary in addition to the setViewMatrix ?

        # --- set the lens
        self.lens = OrthographicLens()
        self.lens.setNearFar(-500., 500.)
        self.camera.node().setLens(self.lens)

        # --- initial setting of the position
        self.update_camera_state(  # recalculate_film_size=True
        )

        self.set_view_matrix_after_updated_camera_pos()

        # --- event handling to reorient the camera
        from panda3d.core import ModifierButtons
        base.mouseWatcherNode.setModifierButtons(ModifierButtons())

        from direct.showbase.ShowBase import DirectObject

        # changing phi
        base.accept('wheel_down', self.handle_wheel_down)

        base.accept('wheel_up', self.handle_wheel_up)

        # changing theta
        base.accept('control-wheel_down', self.handle_control_wheel_down)

        base.accept('control-wheel_up', self.handle_control_wheel_up)

        # 'changing r' (although that's not what directly changes the 'zoom' in an ortho lens)
        base.accept('shift-wheel_up', self.handle_zoom_plus)

        base.accept('shift-wheel_down', self.handle_zoom_minus)

        # polling for zoom is better than events
        self.plus_button = KeyboardButton.ascii_key('+')
        self.minus_button = KeyboardButton.ascii_key('-')
        # taskMgr.add(self.poll_zoom_plus_minus, 'Zoom')

        # blender-like usage of 1, 3, 7 keys to align views with axes
        # base.accept('1', self.set_view_to_xz_plane)
        base.accept('3', self.set_view_to_yz_plane)
        base.accept('7', self.set_view_to_xy_plane)

        base.accept('1', self.set_view_to_xz_plane_and_reset_zoom)

        # base.accept('wheel_up', self.handle_wheel_up)

        # --- fix a point light to the side of the camera
        from panda3d.core import PointLight
        self.plight = PointLight('plight')
        self.pl_nodepath = engine.tq_graphics_basics.tq_render.attachNewNode_p3d(
            self.plight)
        self.set_pointlight_pos_spherical_coords()
        engine.tq_graphics_basics.tq_render.setLight(self.pl_nodepath)

        # -- set faint ambient white lighting
        from panda3d.core import AmbientLight
        self.alight = AmbientLight('alight')
        self.alnp = engine.tq_graphics_basics.tq_render.attachNewNode_p3d(
            self.alight)
        self.alight.setColor(Vec4(0.25, 0.25, 0.25, 1))
        engine.tq_graphics_basics.tq_render.setLight(self.alnp)

        self.visual_aids = OrbiterVisualAids(self)
        self.visual_aids.attach_to_render()

        if enable_visual_aids == True:
            self.visual_aids.on()
        else:
            self.visual_aids.off()

        # TODO: append a drag drop event manager here
        base.accept(
            'shift-mouse1',
            self.handle_shift_mouse1  # , extraArgs=[ob]
        )

        # p3d throws an aspectRatiochanged event after calling MyApp.run()
        # This variable controls which aspect ratio to take (initial aspect ratio (hard-coded or in configuration file)
        # or asking for it from the window manager)

        self.set_film_size_from_window_dimensions(
            called_from_orbiter_init=True)

        base.accept("aspectRatioChanged", self.run_window_resize_hooks)
        self.add_window_resize_hook(self.set_film_size_from_window_dimensions)
        self.add_window_resize_hook(self.scale_aspect2d_from_window_dimensions)
def test_modifierbuttons_empty():
    # Tests the initial state of a ModifierButtons object.
    btns = ModifierButtons()
    assert btns == ModifierButtons(btns)
    assert btns != ModifierButtons()
    assert btns.matches(ModifierButtons())
    assert not btns.is_down("alt")
    assert not btns.is_any_down()
    assert not btns.has_button("alt")
    assert btns.get_prefix() == ""
    assert btns.get_num_buttons() == 0
    assert len(btns.buttons) == 0
Beispiel #24
0
def resetModButtons(win=None):
    if win is not None and not win.getProperties().getForeground():
       return
    origMB=ModifierButtons(base.buttonThrowers[0].node().getModifierButtons())
    origMB.allButtonsUp()
    base.buttonThrowers[0].node().setModifierButtons(origMB)
def test_modifierbuttons_cow():
    # Tests the copy-on-write mechanism of the button list.
    btns1 = ModifierButtons()
    btns1.add_button("space")

    # Modifying original should not affect copy
    btns2 = ModifierButtons(btns1)
    assert tuple(btns2.buttons) == tuple(btns1.buttons)
    btns1.add_button("enter")
    assert tuple(btns1.buttons) == ("space", "enter")
    assert tuple(btns2.buttons) == ("space", )

    # Modifying copy should not affect original
    btns3 = ModifierButtons(btns2)
    assert tuple(btns3.buttons) == tuple(btns2.buttons)
    btns3.add_button("escape")
    assert tuple(btns2.buttons) == ("space", )
    assert tuple(btns3.buttons) == ("space", "escape")
Beispiel #26
0
    def initialize(self):
        self.lens = self.makeLens()
        self.camera = self.doc.render.attachNewNode(
            ModelNode("viewportCameraParent"))
        self.camNode = Camera("viewportCamera")
        self.camNode.setLens(self.lens)
        self.camNode.setCameraMask(self.getViewportMask())
        self.cam = self.camera.attachNewNode(self.camNode)

        winprops = WindowProperties.getDefault()
        winprops.setParentWindow(int(self.winId()))
        winprops.setForeground(False)
        winprops.setUndecorated(True)

        gsg = self.doc.gsg

        output = base.graphicsEngine.makeOutput(
            base.pipe, "viewportOutput", 0, FrameBufferProperties.getDefault(),
            winprops,
            (GraphicsPipe.BFFbPropsOptional | GraphicsPipe.BFRequireWindow),
            gsg)

        self.qtWindow = QtGui.QWindow.fromWinId(
            output.getWindowHandle().getIntHandle())
        self.qtWidget = QtWidgets.QWidget.createWindowContainer(
            self.qtWindow, self, QtCore.Qt.WindowDoesNotAcceptFocus
            | QtCore.Qt.WindowTransparentForInput
            | QtCore.Qt.WindowStaysOnBottomHint
            | QtCore.Qt.BypassWindowManagerHint | QtCore.Qt.SubWindow)  #,
        #(QtCore.Qt.FramelessWindowHint | QtCore.Qt.WindowDoesNotAcceptFocus
        #| QtCore.Qt.WindowTransparentForInput | QtCore.Qt.BypassWindowManagerHint
        #| QtCore.Qt.SubWindow | QtCore.Qt.WindowStaysOnBottomHint))
        self.qtWidget.setFocusPolicy(QtCore.Qt.NoFocus)

        self.inputDevice = output.getInputDevice(0)

        assert output is not None, "Unable to create viewport output!"

        dr = output.makeDisplayRegion()
        dr.disableClears()
        dr.setCamera(self.cam)
        self.displayRegion = dr

        output.disableClears()
        output.setClearColor(Viewport.ClearColor)
        output.setClearColorActive(True)
        output.setClearDepthActive(True)
        output.setActive(True)

        self.win = output

        # keep track of the mouse in this viewport
        mak = MouseAndKeyboard(self.win, 0, "mouse")
        mouse = base.dataRoot.attachNewNode(mak)
        self.mouseAndKeyboard = mouse
        self.mouseWatcher = MouseWatcher()
        self.mouseWatcher.setDisplayRegion(self.displayRegion)
        mw = mouse.attachNewNode(self.mouseWatcher)
        self.mouseWatcherNp = mw

        # listen for keyboard and mouse events in this viewport
        bt = ButtonThrower("kbEvents")
        bt.setButtonDownEvent("btndown")
        bt.setButtonUpEvent("btnup")
        mods = ModifierButtons()
        mods.addButton(KeyboardButton.shift())
        mods.addButton(KeyboardButton.control())
        mods.addButton(KeyboardButton.alt())
        mods.addButton(KeyboardButton.meta())
        bt.setModifierButtons(mods)
        self.buttonThrower = mouse.attachNewNode(bt)

        # collision objects for clicking on objects from this viewport
        self.clickRay = CollisionRay()
        self.clickNode = CollisionNode("viewportClickRay")
        self.clickNode.addSolid(self.clickRay)
        self.clickNp = NodePath(self.clickNode)
        self.clickQueue = CollisionHandlerQueue()

        self.setupRender2d()
        self.setupCamera2d()

        self.gizmo = ViewportGizmo(self)

        self.doc.viewportMgr.addViewport(self)

        self.makeGrid()
Beispiel #27
0
class CameraController(DirectObject):
    instance = None

    def __init__(self):
        self.instructionText = addInstructions(0.95,
                                               '[ESC]: Leave Mouselook mode.')
        self.eventDispatcher = EventDispatcher()
        self.cameraMode = None
        self.clickPos = Vec2()
        self.lastMousePos = Vec2()
        self.focus = Vec3()
        self.mouseDown = False
        self.initialPos = Vec3()
        self.initialHpr = Vec3()
        self.initialMat = None

        # Disable the built-in mouse camera control (it sucks).
        base.disableMouse()
        self.setCameraMode(TRACKBALL)

        # Set the camera's initial position.
        base.camera.setPosHpr(0, 12, 30, 180, -70, 0)

        # Turn off events generated with modifier buttons, e.g. 'shift-a'
        # This is to keep keyboard control working after you alt-tab out
        # of the app.
        base.mouseWatcherNode.setModifierButtons(ModifierButtons())
        base.buttonThrowers[0].node().setModifierButtons(ModifierButtons())

        # This is a diagonal matrix that keeps track of movement key
        # state. The first three diagonal entries can be 1, 0, or -1.
        self.mouseLookTransMat = Mat4.scaleMat(Vec3(0.0, 0.0, 0.0))

        # Keep track of how many movement keys are currently pressed. This
        # lets us short-circuit past a lot of math when no keys are held.
        self.keysHeld = 0

        # Handle events for the movement keys.
        for key, value in key2MatArgs.items():
            self.accept(key, self._moveKeyHandler, value)

        self.accept('escape', self._escKeyHandler)
        self.accept('m', self._mKeyHandler)
        self.accept('mouse1', self._mouseDownHandler, [1])
        self.accept('mouse1-up', self._mouseUpHandler, [1])
        self.accept('mouse2', self._mouseDownHandler, [2])
        self.accept('mouse2-up', self._mouseUpHandler, [2])
        self.accept('wheel_up', self._mouseWheelHandler, [1])
        self.accept('wheel_down', self._mouseWheelHandler, [-1])

        self.modButtons = ModifierButtons()
        self.modButtons.addButton(KeyboardButton.control())
        self.accept('control', self.modButtons.buttonDown,
                    [KeyboardButton.control()])
        self.accept('control-up', self.modButtons.buttonUp,
                    [KeyboardButton.control()])

        self.accept(base.win.getWindowEvent(), self._windowHandler)

    @classmethod
    def getInstance(cls):
        if cls.instance == None:
            cls.instance = cls()
        return cls.instance

    def setFocus(self, position):
        self.focus = position
        base.camera.lookAt(render, position)

    def addEventHandler(self, evtType, handler):
        self.eventDispatcher.addHandler(evtType, handler)

    def getCameraMode(self):
        return self.cameraMode

    def setCameraMode(self, mode):
        if mode == self.cameraMode:
            return

        winProps = WindowProperties()

        # Tear-down code for the current mode.
        if self.cameraMode == MOUSELOOK:
            winProps.setCursorHidden(False)
            self.removeTask(self.viewTask)
        elif self.cameraMode == TRACKBALL:
            self.removeTask(self.viewTask)

        # Set-up code for the new mode.
        if mode == MOUSELOOK:
            winProps.setCursorHidden(True)

            # Mouse accumulator. Whenever the mouse moves, it is reset to the
            # center of the window. The accumulator keeps track of the total
            # movement
            self.mouseAccX = 0
            self.mouseAccY = 0
            self.recenterMouse = True

            # Add a task that moves the camera based on mouse position.
            self.viewTask = taskMgr.add(self._mlViewTask, 'MLViewTask')
            self.lastFrameTime = 0  # Used to calculate dt in mlViewTask.
            self.instructionText.setText('[ESC]: Leave Mouselook Mode')

        elif mode == TRACKBALL:
            self.instructionText.setText('[m]: Enter Mouselook Mode')
            self.viewTask = taskMgr.add(self._trackballTask, 'TrackballTask')

        self.cameraMode = mode
        self.eventDispatcher.dispatchEvent(EVT_CAMERA_MODE, self)
        base.win.requestProperties(winProps)

    def _windowHandler(self, window):
        pos = aspect2d.find('a2dTopLeft').getPos()
        self.instructionText.setPos(pos.getX() + 0.05, pos.getZ() - 0.05)
        hasFocus = window.getProperties().getForeground()
        if not hasFocus:
            self.setCameraMode(TRACKBALL)

    def _escKeyHandler(self):
        self.setCameraMode(TRACKBALL)

    def _mKeyHandler(self):
        if self.cameraMode == MOUSELOOK:
            self.setCameraMode(TRACKBALL)
        else:
            self.setCameraMode(MOUSELOOK)

    def _mouseWheelHandler(self, arg):
        deltY = base.camera.getPos().length() * arg * 0.15
        transl = Mat4.translateMat(0, deltY, 0)
        base.camera.setMat(transl * base.camera.getMat())
        self.eventDispatcher.dispatchEvent(EVT_CAMERA_MOVE, base.camera)

    def _mouseDownHandler(self, button):
        if base.mouseWatcherNode.hasMouse():
            if button == 2 or self.modButtons.isDown(KeyboardButton.control()):
                self.clickPos = Vec2(base.mouseWatcherNode.getMouse())
                self.mouseDown = True
                offset = self.focus - base.camera.getPos()
                self.initialTranslation = offset.length()
                self.initialHpr = base.camera.getHpr()

    def _mouseUpHandler(self, button):
        self.mouseDown = False

    def _moveKeyHandler(self, *matArgs):
        self.mouseLookTransMat.setCell(*matArgs)

        # matArgs[2] is 0 for key release events.
        if (matArgs[2]):
            self.keysHeld += 1
        else:
            self.keysHeld -= 1

    def _trackballTask(self, task):
        if not self.mouseDown:
            return Task.cont

        if (base.mouseWatcherNode.hasMouse()):
            mpos = base.mouseWatcherNode.getMouse()
            if mpos == self.lastMousePos:
                return Task.cont

            mDelta = mpos - self.clickPos

            heading = -mDelta.x * 100 + self.initialHpr.x
            pitch = mDelta.y * 100 + self.initialHpr.y
            if pitch > 90:
                pitch = 90
            elif pitch < -90:
                pitch = -90
            trans1 = Mat4.translateMat(self.focus)
            rotx = Mat4.rotateMat(heading, Vec3(0, 0, 1))
            roty = Mat4.rotateMat(pitch, Vec3(1, 0, 0))
            trans2 = Mat4.translateMat(0, -self.initialTranslation, 0)
            rotation = trans2 * roty * rotx * trans1
            base.camera.setMat(rotation)
            self.eventDispatcher.dispatchEvent(EVT_CAMERA_MOVE, base.camera)

            self.lastMousePos = Vec2(mpos)
        return Task.cont

    def _mlViewTask(self, task):
        t = globalClock.getFrameTime()
        dt = t - self.lastFrameTime
        self.lastFrameTime = t
        if (self.keysHeld):
            # Update camera position based on keyboard controls.
            T = Mat4()
            T.invertAffineFrom(base.camera.getMat())
            cameraMoveMat = T * self.mouseLookTransMat
            xDir = cameraMoveMat.getCol3(0)
            yDir = cameraMoveMat.getCol3(1)
            zDir = cameraMoveMat.getCol3(2)
            currentPos = base.camera.getPos()
            nextPos = currentPos + (xDir + yDir + zDir) * (dt * 8)
            base.camera.setPos(nextPos)
            self.eventDispatcher.dispatchEvent(EVT_CAMERA_MOVE, base.camera)

        if (base.mouseWatcherNode.hasMouse()):
            halfWidth = base.win.getProperties().getXSize() / 2
            halfHeight = base.win.getProperties().getYSize() / 2
            if self.recenterMouse:
                # Don't move the camera, but center the pointer. This is
                # useful when entering mouselook mode, to prevent the camera
                # from jumping to the pointer.
                heading, pitch = base.camera.getH(), base.camera.getP()
                self.mouseAccX = int(heading / ML_MULT)
                self.mouseAccY = int(pitch / ML_MULT)
                self.recenterMouse = False  # Only do this once.
            else:
                mpos = base.mouseWatcherNode.getMouse()
                x, y = mpos.getX(), mpos.getY()

                # short-circuit if mouse hasn't moved or is outside the window.
                if x == 0 and y == 0 or x > 1.0 or y > 1.0:
                    return Task.cont
                # Convert x and y to pixels.
                self.mouseAccX -= int(round(x * halfWidth))
                self.mouseAccY += int(round(y * halfHeight))

                base.camera.setHpr(self.mouseAccX * ML_MULT,
                                   self.mouseAccY * ML_MULT, 0.0)
            base.win.movePointer(0, halfWidth, halfHeight)

        return Task.cont
Beispiel #28
0
    def setup(self):
        """ Attaches the movement controller and inits the keybindings """
        # x
        self.showbase.accept("raw-w", self.set_movement, [0, 1])
        self.showbase.accept("raw-w-up", self.set_movement, [0, 0])
        self.showbase.accept("raw-s", self.set_movement, [0, -1])
        self.showbase.accept("raw-s-up", self.set_movement, [0, 0])

        # y
        self.showbase.accept("raw-a", self.set_movement, [1, -1])
        self.showbase.accept("raw-a-up", self.set_movement, [1, 0])
        self.showbase.accept("raw-d", self.set_movement, [1, 1])
        self.showbase.accept("raw-d-up", self.set_movement, [1, 0])

        # z
        self.showbase.accept("space", self.set_movement, [2, 1])
        self.showbase.accept("space-up", self.set_movement, [2, 0])
        self.showbase.accept("shift", self.set_movement, [2, -1])
        self.showbase.accept("shift-up", self.set_movement, [2, 0])

        # wireframe + debug + buffer viewer
        self.showbase.accept("f3", self.showbase.toggle_wireframe)
        self.showbase.accept(
            "f11", lambda: self.showbase.win.save_screenshot("screenshot.png"))
        self.showbase.accept("j", self.print_position)

        # mouse
        self.showbase.accept("mouse1", self.set_mouse_enabled, [True])
        self.showbase.accept("mouse1-up", self.set_mouse_enabled, [False])

        # arrow mouse navigation
        self.showbase.accept("arrow_up", self.set_hpr_movement, [1, 1])
        self.showbase.accept("arrow_up-up", self.set_hpr_movement, [1, 0])
        self.showbase.accept("arrow_down", self.set_hpr_movement, [1, -1])
        self.showbase.accept("arrow_down-up", self.set_hpr_movement, [1, 0])
        self.showbase.accept("arrow_left", self.set_hpr_movement, [0, 1])
        self.showbase.accept("arrow_left-up", self.set_hpr_movement, [0, 0])
        self.showbase.accept("arrow_right", self.set_hpr_movement, [0, -1])
        self.showbase.accept("arrow_right-up", self.set_hpr_movement, [0, 0])

        # increase / decrease speed
        self.showbase.accept("+", self.increase_speed)
        self.showbase.accept("-", self.decrease_speed)

        # disable modifier buttons to be able to move while pressing shift for
        # example
        self.showbase.mouseWatcherNode.set_modifier_buttons(ModifierButtons())
        self.showbase.buttonThrowers[0].node().set_modifier_buttons(
            ModifierButtons())

        # disable pandas builtin mouse control
        self.showbase.disableMouse()

        # add ourself as an update task which gets executed very early before
        # the rendering
        self.update_task = self.showbase.addTask(self.update,
                                                 "RP_UpdateMovementController",
                                                 sort=-40)

        # Hotkeys to connect to pstats and reset the initial position
        self.showbase.accept("1", PStatClient.connect)
        self.showbase.accept("3", self.reset_to_initial)
Beispiel #29
0
    def __init__(self, p3d_camera, enable_visual_aids=True):
        """ """
        CameraGear.__init__(self)

        base.disableMouse()

        self._coords_3d_of_corner = None

        self.view_distance = Panner2d.view_distance_0

        # camera stuff
        self.p3d_camera = p3d_camera

        # init the camera pos
        self.x = Panner2d.x0
        self.p_previous_offset = Panner2d.p_previous_offset_0

        x, y, z = self.get_cam_coords(at_init=True)
        self.p3d_camera.setPos(x, y, z)

        self.lookat = self.get_lookat_vector(at_init=True)

        # --- hooks for camera movement
        self.p3d_camera_move_hooks = []  # store function objects

        self.p_previous_offset = np.array([0., 0.])

        self.set_corner_to_coords(Panner2d.r0, at_init=True)

        # --- set the lens
        self.lens = OrthographicLens()
        self.lens.setNearFar(Panner2d.near_0, Panner2d.far_0)
        self.p3d_camera.node().setLens(self.lens)

        # --- event handling to reorient the camera
        base.mouseWatcherNode.setModifierButtons(ModifierButtons())

        # changing zoom
        base.accept('control-wheel_down', self.handle_zoom_minus_with_mouse)
        base.accept('control-wheel_up', self.handle_zoom_plus_with_mouse)

        base.accept('control--', self.handle_zoom_minus_general)
        base.accept('control-+', self.handle_zoom_plus_general)
        base.accept('control---repeat', self.handle_zoom_minus_general)
        base.accept('control-+-repeat', self.handle_zoom_plus_general)

        # changing shift in horizontal direction
        base.accept('shift-wheel_up', self.handle_control_wheel_up)
        base.accept('shift-wheel_down', self.handle_control_wheel_down)

        # changing shift in vertical direction
        base.accept('wheel_up', self.handle_wheel_up)
        base.accept('wheel_down', self.handle_wheel_down)

        base.accept('shift-mouse1', self.handle_shift_mouse1)

        # -- window resize
        base.accept("aspectRatioChanged", self.run_window_resize_hooks)

        self.add_window_resize_hook(self.update_film_size_from_view_distance)
        self.add_window_resize_hook(self.scale_aspect2d_from_window_dimensions)