Esempio n. 1
0
    def __init__(self, *args, **kwds):
        '''
        '''
        self.points = []
        self.name = "street part"
        self.author = "Rage Tracks Team"
        self.mirrored = True

        self.texcoords = []

        for arg in args:
            if type(arg) == Vec2:
                self.points.append(arg)

        if "name" in list(kwds.keys()):
            self.name = str(kwds["name"])

        if "author" in list(kwds.keys()):
            self.author = str(kwds["author"])

        if "mirrored" in list(kwds.keys()):
            self.mirrored = bool(kwds["mirrored"])

        # if the points should be mirrored, we'll do it
        if self.mirrored:
            self.mirrorPoints()
        self._notify = DirectNotify().newCategory("TrackGen3D")
        self._notify.info("New StreetData-Object created: %s" % (self))
Esempio n. 2
0
class Settings(object):
    '''
    This class represents a joystick and holds the pygame data
    '''
    def __init__(self):
        '''
        this class is able to load and save the application's settings
        '''
        self._notify = DirectNotify().newCategory("Settings")
        self._notify.info("New Settings-Object created: %s" % (self))
        self.width = 800
        self.height = 600
        self.antialias = False

        self.fullscreen = False
        self._input_settings = {"keyboard": {}, "joysticks": {}}

    # ---------------------------------------------------------

    def saveSettings(self, filename):
        '''
        '''
        config = ConfigObj()
        config.filename = filename

        config["application"] = {}
        #config["application"]["resolution"] = "%dx%d"%(self.width, self.height)
        config["application"]["resolution"] = [
            str(self.width), str(self.height)
        ]
        config["application"]["fullscreen"] = str(int(self.fullscreen))
        config["application"]["antialias"] = str(int(self.antialias))

        config["joysticks"] = {}
        config["keyboard"] = {}
        config.write()

    # ---------------------------------------------------------

    def loadSettings(self, filename):
        '''
        '''
        config = ConfigObj(filename)
        #
        self.width = int(config["application"]["resolution"][0])
        self.height = int(config["application"]["resolution"][1])
        self.fullscreen = bool(int(config["application"]["fullscreen"]))
        self.antialias = bool(int(config["application"]["antialias"]))

        self._input_settings = {
            "joysticks": config["joysticks"],
            "keyboard": config["keyboard"]
        }

    # ---------------------------------------------------------

    def getInputSettings(self):
        '''
        '''
        return self._input_settings
    def __init__(self, camera, parent):
        """Arguments:
        camera -- Camera to be used
        parent -- Aeroplane which the camera should follow
        """

        self.notifier = DirectNotify().newCategory("azure-camera")
        self.camera = camera
        self.parent = parent
        # This gets replaced by a NodePath with all available cameras as
        # children and plane node as parent in createCamNodes()
        self.cameras = None

        #if parent.__class__.__name__ is not "Aeroplane":
        if not isinstance(self.parent, Aeroplane):
            raise ParamError, "Parent must be an Aeroplane instance, " + \
                              "but is %s" % type(self.parent)

        FSM.__init__(self, "PlaneCamera: %s" % self.parent.name)
        DirectObject.__init__(self)

        self.cameras = self.parent.node.find("cameras")
        if self.cameras.isEmpty():
            self.createCamNodes()
        self.updateCamArray()

        self.sideview_direction = 0

        # Set up the default camera
        self.setView("ThirdPerson")
Esempio n. 4
0
    def __init__(self, parent, newGame, device, devices):
        self._parent = parent
        self._notify = DirectNotify().newCategory("Menu")
        self._notify.info("New Menu-Object created: %s" %(self))
        self.device = device #The keybord
        self.devices = devices #For Wii
        
        time.sleep(1)               #Bad Hack to make sure that the Key isn't pressed.
        self.device.boost = False   #Bad Hack to make sure that the Key isn't .setColor(self.colorA)pressed.
        
        self.newGame = newGame
        self.track = []

        #Wiimotes
        self.wiimoteX = []
                
        #Font
        self.font = DynamicTextFont(FONT)
        self.font.setRenderMode(TextFont.RMSolid)
        
        self.CONF_PATH = "user/config.ini"
        self._conf = settings.Settings()
        self._conf.loadSettings(self.CONF_PATH)
        
        taskMgr.add(self.input, 'input')
Esempio n. 5
0
 def __init__(self):
     #create a new notify category
     self._notify = DirectNotify().newCategory("CamMovement")
     self._notify.info("Put some informational text here.")
     self._notify.debug("Put some informational text here.")
     self._notify.warning("Put some informational text here.")
     self._notify.error(
         "Put some informational text here.")  #raise an exeption
Esempio n. 6
0
class Logger:
    """
    Prints messages to the consol and/or file and or gui element
    """
    def __init__(self, gui=None, out_file=None):
        self.notify = DirectNotify().newCategory('a4p')
        self.gui = gui
        self.out_file = None
        if out_file:
            self.out_file = open(path + out_file, 'a')
            self.out_file.write('---<Opening file on: ' + str(datetime.now()) +
                                ' >---\n')

        self.debug('Logger is now logging')
        self.debug('Logger gui is ' + str(gui))
        self.debug('Logger out_file is ' + str(out_file))

    def error(self, msg):
        if self.gui:
            self.gui.showMsg('Error: ' + msg)
        if self.out_file:
            self.out_file.write('Error:' + msg + '\n')
        self.notify.warning('Error: ' + msg)

    def warning(self, msg):
        self.notify.warning(msg)
        if self.gui:
            self.gui.showMsg('Warning: ' + msg)
        if self.out_file:
            self.out_file.write('Warning: ' + msg + '\n')

    def info(self, msg):
        self.notify.info(msg)
        if self.gui:
            self.gui.showMsg(msg)
        if self.out_file:
            self.out_file.write(msg)

    def debug(self, msg):
        self.notify.debug(msg)
        if self.gui:
            self.gui.showMsg('Debug: ' + msg)
        if self.out_file:
            self.out_file.write('Debug: ' + msg + '\n')

    def exception(self, msg):
        if self.gui:
            self.gui.showMsg('Exception: ' + msg)
        if self.out_file:
            self.out_file.write('Exception: ' + msg + '\n')
        self.notify.error(msg)

    def closeLogFile(self):
        if self.out_file:
            self.out_file.write('---<Closing file on: ' + str(datetime.now()) +
                                ' >---\n')
            self.out_file.close()
        self.out_file = None
Esempio n. 7
0
def setup(name='Server Name'):
    log = DirectNotify().newCategory("Allegiance-Server-" + name)
    log.debug("Loading space drive")
    spacedrive.init(run_server=True,
                    run_client=False,
                    log_level='debug',
                    window_title='Allegiance 2')
    log.info("Setting up server network")
    spacedrive.init_server_net(NetworkSystem, port=47624)
Esempio n. 8
0
class PlayerCam(object):
    '''
    '''
    def __init__(self, camera):
        '''
        '''
        self._notify = DirectNotify().newCategory("PlayerCam")
        self._notify.info("New PlayerCam-Object created: %s" % (self))
        self._position = Vec3(0, -20, 5)
        self._camera = camera
        self._vehicle_direction = Vec3(0, 0,
                                       0)  # the direction the object is moving
        self._nodepath = None
        self._distance = 0.7
        self._cam_node = NodePath()
        self._vehicle = None

        # filters = CommonFilters(base.win, self._camera)
        # filters.setBloom(blend=(0,1,0,0) ,desat=10, intensity=1, size='medium')

    # ---------------------------------------------------------
    def followVehicle(self, direction, vehicle=None):
        '''
        Let the camera follow the node path.
        '''
        if vehicle is not None:
            self._nodepath = vehicle.model
        else:
            self._nodepath = None
        self._vehicle = vehicle
        self._vehicle_direction = direction

    # ---------------------------------------------------------
    def updateCam(self):
        '''
        Needs to get executed every frame that gets displayed on the screen
        '''
        if self._nodepath is not None:
            x, y, z = self._nodepath.getX(), self._nodepath.getY(
            ), self._nodepath.getZ()
            self._camera.setPos(
                (self._nodepath.getQuat().xform(Vec3(0, -10, 6)) +
                 self._nodepath.getPos() - (self._vehicle_direction * 0.05)))
            self._camera.lookAt(x, y, z)
            self._camera.setR(self._nodepath.getR())
        else:
            pass

    # ---------------------------------------------------------

    def getCamera(self):
        return self._camera

    def setCamera(self, value):
        self._camera = value

    camera = property(fget=getCamera, fset=setCamera)
Esempio n. 9
0
class JoystickDevice(object):
    '''
    This class represents a joystick and holds the pygame data
    '''
    def __init__(self, joystick):
        '''
        @param joystick: the pygame joystick object
        '''
        self._notify = DirectNotify().newCategory("Input")
        self._notify.info("New Joystick-Object created: %s" % (self))
        # the pygame joysick object
        self.joystick = joystick
        self.joystick.init()
        #print self.joystick.get_name()

        # initialize the buttons axes, and cooliehats
        self.buttons = []
        self.axes = []
        self.hats = []

        for i in range(self.joystick.get_numaxes()):
            self.axes.append(0.0)

        for i in range(self.joystick.get_numbuttons()):
            self.buttons.append(False)

        for i in range(self.joystick.get_numhats()):
            self.hats.append((0, 0))

    # ---------------------------------------------------------

    def getAxisCount(self):
        '''
        '''
        return len(self.axes)

    # ---------------------------------------------------------

    def getHatCount(self):
        '''
        '''
        return len(self.hats)

    # ---------------------------------------------------------

    def getButtonCount(self):
        '''
        '''
        return len(self.buttons)

    # ---------------------------------------------------------

    def getName(self):
        '''
        '''
        return self.joystick.get_name()
Esempio n. 10
0
File: main.py Progetto: wezu/a4p
class Logger:
    """
    Prints messages to the consol and/or file and or gui element
    """
    def __init__(self, gui=None, out_file=None):
        self.notify = DirectNotify().newCategory('a4p')
        self.gui=gui
        self.out_file=None
        if out_file:
            self.out_file=open(path+out_file,'a')
            self.out_file.write('---<Opening file on: '+str(datetime.now())+' >---\n')

        self.debug('Logger is now logging')
        self.debug('Logger gui is '+str(gui))
        self.debug('Logger out_file is '+str(out_file))

    def error(self, msg):
        if self.gui:
            self.gui.showMsg('Error: '+msg)
        if self.out_file:
            self.out_file.write('Error:'+msg+'\n')
        self.notify.warning('Error: '+msg)

    def warning(self, msg):
        self.notify.warning(msg)
        if self.gui:
            self.gui.showMsg('Warning: '+msg)
        if self.out_file:
            self.out_file.write('Warning: '+msg+'\n')

    def info(self, msg):
        self.notify.info(msg)
        if self.gui:
            self.gui.showMsg(msg)
        if self.out_file:
            self.out_file.write(msg)

    def debug(self, msg):
        self.notify.debug(msg)
        if self.gui:
            self.gui.showMsg('Debug: '+msg)
        if self.out_file:
            self.out_file.write('Debug: '+msg+'\n')

    def exception(self, msg):
        if self.gui:
            self.gui.showMsg('Exception: '+msg)
        if self.out_file:
            self.out_file.write('Exception: '+msg+'\n')
        self.notify.error(msg)

    def closeLogFile(self):
        if self.out_file:
            self.out_file.write('---<Closing file on: '+str(datetime.now())+' >---\n')
            self.out_file.close()
        self.out_file=None
Esempio n. 11
0
 def land(self):
     if (self.__z == 0):
         notify = DirectNotify().newCategory("")
         notify.warning("The drone has already landed")
         exit()
     self.__commandCheck()
     seq = self.droneActor.posInterval(self.__z / 5,
                                       Point3(self.__x, self.__y, 0))
     self.__z = 0
     self.__overallSequence.append(seq)
Esempio n. 12
0
 def takeoff(self):
     if (self.__z != 0):
         notify = DirectNotify().newCategory("")
         notify.warning("The drone has already taken off")
         exit()
     self.__commandCheck()
     seq = self.droneActor.posInterval(
         2, Point3(self.__x, self.__y, self.__z + 10))
     self.__z = self.__z + 10
     self.__overallSequence.append(seq)
Esempio n. 13
0
    def __init__(self):
        '''
        '''
        self._notify = DirectNotify().newCategory("Input")
        self._notify.info("New Keyboard-Object created: %s" % (self))
        base.buttonThrowers[0].node().setButtonUpEvent("button-up")
        base.buttonThrowers[0].node().setButtonDownEvent("button")
        base.accept("button-up", self.setKey, [False])
        base.accept("button", self.setKey, [True])

        self.keys = {}
Esempio n. 14
0
    def __init__(self, gui=None, out_file=None):
        self.notify = DirectNotify().newCategory('a4p')
        self.gui = gui
        self.out_file = None
        if out_file:
            self.out_file = open(path + out_file, 'a')
            self.out_file.write('---<Opening file on: ' + str(datetime.now()) +
                                ' >---\n')

        self.debug('Logger is now logging')
        self.debug('Logger gui is ' + str(gui))
        self.debug('Logger out_file is ' + str(out_file))
Esempio n. 15
0
    def __init__(self):
        '''
        this class is able to load and save the application's settings
        '''
        self._notify = DirectNotify().newCategory("Settings")
        self._notify.info("New Settings-Object created: %s" % (self))
        self.width = 800
        self.height = 600
        self.antialias = False

        self.fullscreen = False
        self._input_settings = {"keyboard": {}, "joysticks": {}}
Esempio n. 16
0
File: engine.py Progetto: etodd/a3p
class Logger:
	def __init__(self):
		self.notify = DirectNotify().newCategory("core")
	def error(self, msg):
		self.notify.warning(msg)
	def warning(self, msg):
		self.notify.warning(msg)
	def info(self, msg):
		self.notify.info(msg)
	def debug(self, msg):
		self.notify.debug(msg)
	def exception(self, msg):
		self.notify.error(msg)
Esempio n. 17
0
 def cw(self, amount):
     self.__commandCheck()
     if (amount > 3600 or amount < 1):
         #print("Error Line ",self.__get_linenumber,": Please enter amount between 1 and 3600 ")
         notify = DirectNotify().newCategory("MyCategory")
         notify.warning(
             "Error: For 'cw' please enter amount between 1 and 3600 ")
         exit()
     seq = self.droneActor.hprInterval(amount / 45, Vec3(amount, 0, 0))
     self.__heading = self.__heading + amount
     while (self.__heading > 360):
         self.__heading = self.__heading - 360
     self.__overallSequence.append(seq)
Esempio n. 18
0
 def __init__(self, camera):
     '''
     '''
     self._notify = DirectNotify().newCategory("PlayerCam")
     self._notify.info("New PlayerCam-Object created: %s" % (self))
     self._position = Vec3(0, -20, 5)
     self._camera = camera
     self._vehicle_direction = Vec3(0, 0,
                                    0)  # the direction the object is moving
     self._nodepath = None
     self._distance = 0.7
     self._cam_node = NodePath()
     self._vehicle = None
Esempio n. 19
0
    def __init__(self):
        ShowBase.__init__(self)

        # Load the environment model.
        self.scene = self.loader.loadModel("models/environment")
        # Reparent the model to render.
        self.scene.reparentTo(self.render)
        # Apply scale and position transforms on the model.
        self.scene.setScale(0.25, 0.25, 0.25)
        self.scene.setPos(-8, 42, 0)

        self.accept('a', self.printRepeat)

        self.py3notify = DirectNotify().newCategory("Python3_main")
Esempio n. 20
0
    def __init__(self, res, x, y, z=200, player_count=1, street_data=""):
        '''
        '''
        self._notify = DirectNotify().newCategory("TrackGen3D")
        self._notify.info("New Track3D-Object created: %s" % (self))
        # street_data = (Vec2(4.0,4.0), Vec2(10.0,10.0), Vec2(10.0,0.0), Vec2(4.0,0.0), Vec2(0.0,-1.0))
        # street_data = StreetData(Vec2(15.0,1.0), Vec2(15.0,-5.0), Vec2(0.0,-5.0), mirrored=True) #, Vec2(15.0,0.0)
        self.street_data = StreetData()

        # self.street_data.readFile("data/road/road01.xml")
        # self.street_data.readFile("data/road/tube.xml")
        if street_data == "":
            datas = ["road01", "tube"]
            street_data = datas[random.randint(0, len(datas) - 1)]
        self.street_data.readFile("data/road/" + street_data + ".xml")

        self.streetTextrange = 0.0
        self.track = Track(x, y, z)
        self.track.generateTestTrack(player_count)
        # self.track.generateTrack(player_count)

        self.track_points = self.track.getInterpolatedPoints(res)
        self.varthickness = []  # Generate the Vector for thickness of the road

        self.generateNormals()
        # for i in range(len(self.track_points)-1):
        # if i == 0:
        # self.varthickness.append(self.calcTheVector(self.track_points[i],self.track_points[i],self.track_points[i+1])) #First
        # continue
        # self.varthickness.append(self.calcTheVector(self.track_points[i-1],self.track_points[i],self.track_points[i+1]))
        # self.varthickness.append(self.calcTheVector(self.track_points[len(self.track_points)-2],self.track_points[len(self.track_points)-1],self.track_points[len(self.track_points)-1])) #Last
        ##
        # Normalizing the Vector
        # for i in self.varthickness:
        # i.normalize()
        ##
        # print self.varthickness[-1]
        # print self.varthickness[0]
        # print self.varthickness[1]
        # print self.varthickness[2]

        # Spin the last 100 Points a litte bit to Vec3(-1,0,0)
        for i in range(-100, 1):
            # print self.varthickness[i] * (-i / 100), self.varthickness[i] , ((i* -1) / 100.0), i
            # print ((i* -1) / 100.0), self.varthickness[i], self.varthickness[i] * ((i* -1) / 100.0)
            self.varthickness[i] = self.varthickness[i] * (((i + 1) * -1) / 100.0) + Vec3(-1, 0, 0)
            self.normals[i] = self.normals[i] * (((i + 1) * -1) / 100.0) + Vec3(0, 0, 1)

            self.varthickness[i].normalize()
            self.normals[i].normalize()
Esempio n. 21
0
 def up(self, distance):
     self.__commandCheck()
     if (distance > 500 or distance < 20):
         #print("Error Line ",self.__get_linenumber,": Please enter amount between 1 and 3600 ")
         notify = DirectNotify().newCategory("")
         notify.warning(
             "Error: For 'up' please enter amount between 20 and 500 ")
         exit()
     distance = distance / 10
     newz = self.__z + distance
     seq = self.droneActor.posInterval(distance / 5,
                                       Point3(self.__x, self.__y, newz))
     self.__z = newz
     self.__overallSequence.append(seq)
Esempio n. 22
0
    def __init__(self, cam_count=0):
        '''
        @param cam_count: (int) number of cameras which should be added
        '''
        self._notify = DirectNotify().newCategory("SplitScreen")
        self._notify.info("New SplitScreen-Object created: %s" % (self))
        self.regions = []  # the regions the screen is separated into
        self.cameras = []  # the cameras (empty ones are None)
        self.filters = []  # the shader filters applied to each camera
        self.cameraPosPre = []  # the position of the cameras before change
        self.steps = 1
        self.shaders_on = False

        if cam_count > 0:  # add cameras, if needed
            self.addCameras(cam_count)
Esempio n. 23
0
def setup():
    log = DirectNotify().newCategory("Allegiance-Client")
    log.debug("Loading space drive")
    spacedrive.init(run_server=False,
                    run_client=True,
                    log_level='debug',
                    window_title='Allegiance 2')
    log.info('Setting up graphics')
    #spacedrive.init_graphics(debug_mouse=False)
    log.info("Setting up client gui")
    spacedrive.init_gui()
    spacedrive.base.wireframe = False
    spacedrive.base.accept("f3", toggleSceneWireframe)
    spacedrive.gui_system.setup_screen(MainMenu())
    log.info("Setting up client network")
    spacedrive.init_server_net(NetworkSystem)
Esempio n. 24
0
    def __init__(self, size_x, size_y, max_height=2300):
        '''
        the constructor creates an empty track
        @param size_x: (int) maximum x-coordinates
        @param size_y: (int) maximum y-coordinates
        @param max_height: (int) maximum z-coordinates
        '''
        # self.setSize(size_x, size_y, max_height)
        # self.setSize(8000, 8000, 1000)
        self.setSize(1600, 1600, 800)
        self.points = []
        self.curve = None
        self._notify = DirectNotify().newCategory("TrackGen")
        self._notify.info("New Track-Object created: %s" % (self))

        self.prefabs = glob.glob("data/road/parts/*.xml")
class DistributedMinigameStation(DistributedGroupStation,
                                 MinigameStation.MinigameStation,
                                 DistributedObject):
    notify = DirectNotify().newCategory("DistributedMinigameStation")

    def __init__(self, cr):
        try:
            self.DistributedMinigameStation_initialized
            return
        except:
            self.DistributedMinigameStation_initialized = 1
        MinigameStation.MinigameStation.__init__(self)
        DistributedObject.__init__(self, cr)
        return

    def setStation(self, game):
        self.generateStation(game)

    def headOff(self, zone, laffMeter):
        if self.camIval:
            self.camIval.finish()
            self.camIval = None
        self.deleteStationAbortGui()
        requestStatus = {
            'zoneId': zone,
            'hoodId': self.cr.playGame.hood.hoodId,
            'where': 'minigame',
            'avId': base.localAvatar.doId,
            'loader': 'minigame',
            'shardId': None,
            'wantLaffMeter': laffMeter
        }
        self.cr.playGame.getPlace().fsm.request('teleportOut', [requestStatus])
        Sequence(Wait(3.0), Func(self.d_leaving)).start()
Esempio n. 26
0
    def __init__(self, parent):
        """Arguments:
        parent -- Aeroplane which the camera should follow
        """

        # Used for debugging. Verbosity is set in config file.
        # Usually this is called self.notify, but in this case it would
        # override FSM's own.
        self.notifier = DirectNotify().newCategory("azure-camera")
        self.parent = parent
        # Replaced by a NodePath with all available cameras as children and
        # plane node as parent.
        self.__cameras = None

        #if parent.__class__.__name__ is not "Aeroplane":
        if not isinstance(self.parent, Aeroplane):
            raise ParamError, "Parent must be an Aeroplane instance, but is %s" % type(self.parent)

        FSM.__init__(self, "PlaneCamera: %s" % self.parent.name)

        try:
            self.camera = base.camera
        except:
            raise BaseMissing

        self.__cameras = self.parent.node.find("cameras")
        if self.__cameras.isEmpty():
            self.createCamNodes()
        self.updateCamArray()

        self.sideview_direction = 0

        # Set up the default camera
        self.setCameraMode("ThirdPerson")
Esempio n. 27
0
 def __init__(self, number, ode_world, ode_space, device=None, camera=None):
     '''
     '''
     self._notify = DirectNotify().newCategory("Player")
     self._notify.info("New Player-Object created: %s" % (self))
     self._ode_world = ode_world
     self._ode_space = ode_space
     self._number = number
     self._camera = camera
     self._vehicle = vehicle.Vehicle(self._ode_world, self._ode_space)  # the properties of the vehicle
     self._device = device  # The input device
     # self._osd_health = OnscreenText(text = "100", pos = ((self._number*0.2)-1,0.9))
     self._position = 0
     self._pre_position = 0
     self._rank = 0
     self._lap = 1
     self._time = 0
Esempio n. 28
0
 def forward(self, distance):
     self.__commandCheck()
     if (distance > 500 or distance < 20):
         #print("Error Line ",self.__get_linenumber,": Please enter amount between 1 and 3600 ")
         notify = DirectNotify().newCategory("")
         notify.warning(
             "Error: For 'forwards' please enter amount between 20 and 500 "
         )
         exit()
     distance = distance / 10
     newx = (distance * math.cos(self.__heading)) + self.__x
     newy = (distance * math.sin(self.__heading)) + self.__y
     seq = self.droneActor.posInterval(distance / 5,
                                       Point3(newx, newy, self.__z))
     self.__x = newx
     self.__y = newy
     self.__overallSequence.append(seq)
Esempio n. 29
0
 def __init__(self, parent):
     
     self._notify = DirectNotify().newCategory("Menu")
     self._notify.info("New Menu-Object created: %s" %(self))
     
     #Font
     self.font = DynamicTextFont(FONT)
     self.font.setRenderMode(TextFont.RMSolid)
     
     self.KEY_DELAY = 0.15
     self.player_buttonpressed = []
     
     self._parent = parent
     self._players = parent.players
     self._devices = parent.devices
     
     taskMgr.add(self.fetchAnyKey, "fetchAnyKey")
Esempio n. 30
0
    def __init__(self, ode_world, ode_space, name="standard"):
        '''
        '''
        self._notify = DirectNotify().newCategory("Vehicle")
        self._notify.info("New Vehicle-Object created: %s" % (self))
        self._ode_world = ode_world
        self._ode_space = ode_space
        self._model = None
        self._physics_model = None
        self._physics_mass = None
        self._collision_model = None
        self._speed = 0.0  # the actual speed of the vehicle (forward direction)
        self._direction = Vec3(0, 0, 0)  # the direction the car is heading
        self._boost_direction = Vec3(0, 0, 0)
        self._boost_strength = 10.0  # the boost propertys of the vehicle
        self._control_strength = 1.5  # impact on the steering behaviour
        self._grip_strength = 0.5  # impact on the steering behaviour
        self._track_grip = 0.8  # impact on the steering behaviour
        self._energy = 100.0
        self._armor = 100.0
        self._max_energy = 100.0
        self._max_armor = 100.0
        self._weight = 10.0
        self._description = "The best vehicle ever"
        self._name = "The flying egg"
        self._brake_strength = 10.0
        self._hit_ground = True
        self._model_loading = False
        self._blowout = []
        self._blowout_on = False
        self._streetnormal = Vec3(0, 0, 1)

        # set up the propertys of the vehicle that schould be loaded
        # the methods get called because the data is immutable and
        # wouldnt get updated when calling the objects directly
        # the last entry is the function to convert the string
        self._tags = [["name", self.setName, str],
                      ["description", self.setDescription, str],
                      ["control_strength", self.setControlStrength, float],
                      ["grip_strength", self.setGripStrength, float],
                      ["track_grip", self.setTrackGrip, float],
                      ["max_energy", self.setMaxEnergy, float],
                      ["max_armor", self.setMaxArmor, float],
                      ["weight", self.setWeight, float],
                      ["brake_strength", self.setBrakeStrength, float],
                      ["boost_strength", self.setBoostStrength, float]]
Esempio n. 31
0
class Logger:
    def __init__(self):
        self.notify = DirectNotify().newCategory("core")

    def error(self, msg):
        self.notify.warning(msg)

    def warning(self, msg):
        self.notify.warning(msg)

    def info(self, msg):
        self.notify.info(msg)

    def debug(self, msg):
        self.notify.debug(msg)

    def exception(self, msg):
        self.notify.error(msg)
Esempio n. 32
0
 def disconnect(self):
     if (self.__connection != None):
         __tello = None
         __commanding = False
         __connection = None
         notify = DirectNotify().newCategory("")
         notify.warning("Disonnected!")
     else:
         notify = DirectNotify().newCategory("")
         notify.warning("You are not connected to a drone yet")
         exit()
Esempio n. 33
0
def setup():
    log = DirectNotify().newCategory("Allegiance-Client")
    log.debug("Loading space drive")
    spacedrive.init(run_server=False,
                    run_client=True,
                    log_level='debug',
                    window_title='Allegiance 2')
    log.info('Setting up graphics')
    #spacedrive.init_graphics(debug_mouse=False)
    log.info("Setting up client gui")
    spacedrive.init_gui()
    spacedrive.base.wireframe = False
    spacedrive.base.accept("f3", toggleSceneWireframe)
    spacedrive.gui_system.setup_screen(MainMenu())
    log.info("Setting up client network")
    spacedrive.init_server_net(NetworkSystem)
Esempio n. 34
0
File: main.py Progetto: wezu/a4p
    def __init__(self, gui=None, out_file=None):
        self.notify = DirectNotify().newCategory('a4p')
        self.gui=gui
        self.out_file=None
        if out_file:
            self.out_file=open(path+out_file,'a')
            self.out_file.write('---<Opening file on: '+str(datetime.now())+' >---\n')

        self.debug('Logger is now logging')
        self.debug('Logger gui is '+str(gui))
        self.debug('Logger out_file is '+str(out_file))
Esempio n. 35
0
    def __init__(self, device, settings):
        '''
        '''
        self._notify = DirectNotify().newCategory("Input")
        self._notify.info("New Input-Object created: %s" % (self))
        self.device = device
        self.directions = [0, 0]  # x and y movement
        self.boost = False  # Button for boosting
        self.use_item = False  # Button for using items
        self.escape = False

        # if this is a Joystick, look if there are Settings for Joysticks with this name
        if type(self.device) == joystickdevice.JoystickDevice:
            if self.device.getName() in settings["joysticks"]:
                self.settings = settings["joysticks"][self.device.getName()]
            else:
                self.settings = {}
                self._setStandardSettings()

        # Keyboard settings are always available
        elif type(self.device) == keyboarddevice.KeyboardDevice:
            #self.settings = settings["keyboard"]
            self.settings = {}
            self.settings["boost"] = "space"
            self.settings["use_item"] = "lalt"
            self.settings["up"] = "arrow_up"
            self.settings["down"] = "arrow_down"
            self.settings["left"] = "arrow_left"
            self.settings["right"] = "arrow_right"
            self.settings["escape"] = "escape"

            self.device.keys[self.settings["up"]] = False
            self.device.keys[self.settings["down"]] = False
            self.device.keys[self.settings["left"]] = False
            self.device.keys[self.settings["right"]] = False
            self.device.keys[self.settings["boost"]] = False
            self.device.keys[self.settings["use_item"]] = False
            self.device.keys[self.settings["escape"]] = False

        elif type(self.device) == wiidevice.WiiDevice:
            pass  #Think isn't necessary by Wiimotes
Esempio n. 36
0
    def __init__(self):
        BBGlobalVars.initialise(self, render)  # set render as current coordinate system (NOT CURRENTLY USED)
        #super(DirectObject, self).__init__() # I'd like to do this init
        self.notify = DirectNotify()
        self.notify.newCategory('bareBonesErr')
        self.bareBonesNP = render.attachNewNode('bareBonesNode')
        self.levitorNP = self.bareBonesNP.attachNewNode('levitorNode')
        self.levitor = Levitor(self.bareBonesNP, self.levitorNP)
        self.bbDummyNP = None  # should always be None, save for during file ops


        self.twoDGui = TwoDeeGui()
Esempio n. 37
0
class KeyboardDevice(object):
    '''
    This class holds data about the keyboard
    '''
    def __init__(self):
        '''
        '''
        self._notify = DirectNotify().newCategory("Input")
        self._notify.info("New Keyboard-Object created: %s" % (self))
        base.buttonThrowers[0].node().setButtonUpEvent("button-up")
        base.buttonThrowers[0].node().setButtonDownEvent("button")
        base.accept("button-up", self.setKey, [False])
        base.accept("button", self.setKey, [True])

        self.keys = {}

    # ---------------------------------------------------------

    def setKey(self, value, key):
        '''
        '''
        self.keys[key] = value
Esempio n. 38
0
class BareBones(object):
    def __init__(self):
        BBGlobalVars.initialise(self, render)  # set render as current coordinate system (NOT CURRENTLY USED)
        #super(DirectObject, self).__init__() # I'd like to do this init
        self.notify = DirectNotify()
        self.notify.newCategory('bareBonesErr')
        self.bareBonesNP = render.attachNewNode('bareBonesNode')
        self.levitorNP = self.bareBonesNP.attachNewNode('levitorNode')
        self.levitor = Levitor(self.bareBonesNP, self.levitorNP)
        self.bbDummyNP = None  # should always be None, save for during file ops


        self.twoDGui = TwoDeeGui()


    def prepareForSave(self):
        self.bbDummyNP = NodePath(PandaNode("bbDummyNP"))
        self.bareBonesNP.reparentTo(self.bbDummyNP)


    def recoverFromSave(self):
        self.bareBonesNP.reparentTo(render)
        self.bbDummyNP.removeNode()
        self.bbDummyNP = None


    def prepareForLoad(self):
        self.prepareForSave()


    def recoverFromLoad(self):
        assert(render is not None)
        global BBGlobalVars
        BBGlobalVars.initialise(self, render)  # set render as current coord sys
        self.levitor.grabber.grabModelNP.hide()  # HACK REMOVE this line barebones shouldn't know about grabber
        self.recoverFromSave()
        # for i in range(0, len(BBGlobalVars.recoverFromPickleLst)):
        #     BBGlobalVars.recoverFromPickleLst[i].recoverFromPickle()
Esempio n. 39
0
import yaml

from .import celestial_components as cel_comp
from .import render_components as render_comps
from .import surface_mesh
from .import universals
from .utils import blackbody

from .renderpipeline.rpcore import PointLight as DirectionalLight
#TODO: Switch to the sun direction manager or as tobias for info
#TODO: Reenable scattering
#from .renderpipeline import Scattering

from direct.directnotify.DirectNotify import DirectNotify

log = DirectNotify().newCategory("SpaceDrive-OrbitSystem")
log.setSeverity(3)

is2d = False


class OrbitSystem(sandbox.EntitySystem):
    """Positions and moves celestial bodies in orbit."""
    def add_parent_pos(self, displacement, child_component):
        parent_node_path = child_component.node_path.get_parent()
        parent_entity = parent_node_path.get_python_tag('entity')
        if parent_entity:
            parent_component = parent_entity.get_component(cel_comp.CelestialComponent)
            if parent_component:
                displacement += self.add_parent_pos(displacement, parent_component)
                displacement += parent_component.true_pos
Esempio n. 40
0
File: main.py Progetto: croxis/itf
run_menu = False
if not run_server and not run_client:
    run_menu = True

if run_client:
    # We must import this before panda due to talmoc issues in linux
    from cefpython3 import cefpython

from direct.directnotify.DirectNotify import DirectNotify
from panda3d.core import loadPrcFileData, Shader
import spacedrive

from networking import server_net, client_net

loadPrcFileData("", "notify-level-ITF debug")
log = DirectNotify().newCategory("ITF")


# After initial setup we can now start sandbox
log.debug("Loading space drive")
spacedrive.init(run_server=run_server,
                run_client=(run_client or run_menu),
                log_level='debug',
                window_title='Into The Fire')

import solarSystem


def main_menu():
    """Main menu management."""
    import sandbox
Esempio n. 41
0
    def initialize(self):
        """Reset everything except LevitorNP and selected, also called inside __init__"""
        self.notify = DirectNotify().newCategory('grabberErr')
        self.currPlaneColNorm = Vec3(0.0)
        self.isCameraControlOn = False
        self.isDragging = False
        self.isMultiselect = False
        self.grabScaleFactor = .075
        self.currTransformDir = Point3(0.0)
        self.interFrameMousePosition = Point3(0.0)
        self.init3DemVal = Point3(0.0)
        # initCommVal holds the value before a command operation has taken place
        self.initialCommandTrgVal = None
        # To load the grabber model, this climbs up the absolute path to /barebones/ to gain access to the model folder
        self.grabModelNP = loader.loadModel(Filename.fromOsSpecific(
                                            ntpath.split( ntpath.split(inspect.stack()[0][1])[0] )[0])
                                            + '/EditorModels/widget')
        self.grabModelNP.setPos(0.0, 0.0, 0.0)
        self.grabModelNP.setBin("fixed", 40)
        self.grabModelNP.setDepthTest(False)
        self.grabModelNP.setDepthWrite(False)
        self.transformOpEnum = Enum('rot, scale, trans')
        self.currTransformOperation = None
        # TODO For readability, use this enum in the nested if/else as was the original intent.
        self.grabInd = Enum('xRot, yRot, zRot, xScaler, yScaler, zScaler, xTrans, yTrans, zTrans, xyTrans, xzTrans, zyTrans, grabCore')
        grbrNodLst = [self.grabModelNP.find("**/XRotator;+h-s-i"),       # 0
                       self.grabModelNP.find("**/YRotator;+h-s-i"),      # 1
                       self.grabModelNP.find("**/ZRotator;+h-s-i"),      # 2 end rotate
                       self.grabModelNP.find("**/XScaler;+h-s-i"),       # 3
                       self.grabModelNP.find("**/YScaler;+h-s-i"),       # 4
                       self.grabModelNP.find("**/ZScaler;+h-s-i"),       # 5 end scale
                       self.grabModelNP.find("**/XTranslator;+h-s-i"),   # 6
                       self.grabModelNP.find("**/YTranslator;+h-s-i"),   # 7
                       self.grabModelNP.find("**/ZTranslator;+h-s-i"),   # 8 end translate / end single dir operations
                       self.grabModelNP.find("**/XYTranslator;+h-s-i"),  # 9
                       self.grabModelNP.find("**/XZTranslator;+h-s-i"),  # 10
                       self.grabModelNP.find("**/ZYTranslator;+h-s-i"),  # 11 end bi-directional operations
                       self.grabModelNP.find("**/WidgetCore;+h-s-i")]    # 12
        #Mat4.yToZUpMat()  # change coordinate to z up
        grbrNodLst[12].getParent().setHprScale(0, 0, 0, 1, 1, -1)
        self.grabModelNP.setPythonTag('grabberRoot', grbrNodLst)
        self.grabModelNP.reparentTo(BBGlobalVars.bareBonesObj.levitorNP)
        self.grabModelNP.hide()
        #self.grabIntoBitMask = COLLISIONMASKS
        self.grabModelNP.setCollideMask(COLLISIONMASKS['default'])
        self.grabModelNP.setPythonTag('grabber', self)

        ##############################################################################
        # This whole section is the basics for setting up mouse selection
        # --The mouse events are added in the events section (next)

        # Create the collision node for the picker ray to add traverser as a 'from' collider
        self.grabberColNode = CollisionNode('grabberMouseRay')
        # Set the collision bitmask
        # TODO: define collision bitmask (let user define thiers? likely not)
        self.defaultBitMask = GeomNode.getDefaultCollideMask()
        self.grabberColNode.setFromCollideMask(self.defaultBitMask)
        self.grabberRayColNP = camera.attachNewNode(self.grabberColNode)
        # Create the grabberRay and add it to the picker CollisionNode
        self.grabberRay = CollisionRay(0.0, 0.0, 0.0,
                                       0.0, 1.0, 0.0)
        self.grabberRayNP = self.grabberColNode.addSolid(self.grabberRay)
        # create a collision queue for the traverser
        self.colHandlerQueue = CollisionHandlerQueue()
        # Create collision traverser
        self.colTraverser = CollisionTraverser('grabberTraverser')
        # Set the collision traverser's 'fromObj' and handler
        # e.g. trav.addCollider( fromObj, handler )
        self.colTraverser.addCollider(self.grabberRayColNP, self.colHandlerQueue)


        ############################################################
        # setup event handling with the messenger
        # URGENT remove all of this messenger code throughout Grabber, especially the camera control
        # disable the mouse when the ~ is pressed (w/o shift)
        self.disableCamera()                            # disable camera control by the mouse
        messenger.accept('`', self, self.enableCamera)  # enable camera control when the ~ key is pressed w/o shift
        messenger.accept('`-up', self, self.disableCamera)  # disable camera control when the ~ key is released

        # handle mouse selection/deselection & manipulating the scene
        messenger.accept('mouse1', self, self.handleM1, persistent=1)  # deselect in event handler

        taskMgr.add(self.scaleGrabber, 'scaleGrabber')
Esempio n. 42
0
class Grabber(object):
    def __init__( self, levitNP):
        """ A widget to position, rotate, and scale Panda 3D Models and Actors
            * handleM1 decides what to do with a mouse1 click
            -- object selection by calling handleSelection when the grabModel is inactive (hidden)
            -- object manipulation by calling handleManipulationSetup (sets the stage for and launches the dragTask)

            isHidden() when nothing is selected
            isDragging means not running collision checks for selection setup and LMB is pressed

            call handleM1 from another class to push control up
            in the program hierarchy (remove inner class calls)
        """
        # TODO remove selection functionality from grabber and put it in a selector class
        self.levitorNP = levitNP  # TODO remove this and use barebonesNP
        self.selected = None
        self.initialize()

    def initialize(self):
        """Reset everything except LevitorNP and selected, also called inside __init__"""
        self.notify = DirectNotify().newCategory('grabberErr')
        self.currPlaneColNorm = Vec3(0.0)
        self.isCameraControlOn = False
        self.isDragging = False
        self.isMultiselect = False
        self.grabScaleFactor = .075
        self.currTransformDir = Point3(0.0)
        self.interFrameMousePosition = Point3(0.0)
        self.init3DemVal = Point3(0.0)
        # initCommVal holds the value before a command operation has taken place
        self.initialCommandTrgVal = None
        # To load the grabber model, this climbs up the absolute path to /barebones/ to gain access to the model folder
        self.grabModelNP = loader.loadModel(Filename.fromOsSpecific(
                                            ntpath.split( ntpath.split(inspect.stack()[0][1])[0] )[0])
                                            + '/EditorModels/widget')
        self.grabModelNP.setPos(0.0, 0.0, 0.0)
        self.grabModelNP.setBin("fixed", 40)
        self.grabModelNP.setDepthTest(False)
        self.grabModelNP.setDepthWrite(False)
        self.transformOpEnum = Enum('rot, scale, trans')
        self.currTransformOperation = None
        # TODO For readability, use this enum in the nested if/else as was the original intent.
        self.grabInd = Enum('xRot, yRot, zRot, xScaler, yScaler, zScaler, xTrans, yTrans, zTrans, xyTrans, xzTrans, zyTrans, grabCore')
        grbrNodLst = [self.grabModelNP.find("**/XRotator;+h-s-i"),       # 0
                       self.grabModelNP.find("**/YRotator;+h-s-i"),      # 1
                       self.grabModelNP.find("**/ZRotator;+h-s-i"),      # 2 end rotate
                       self.grabModelNP.find("**/XScaler;+h-s-i"),       # 3
                       self.grabModelNP.find("**/YScaler;+h-s-i"),       # 4
                       self.grabModelNP.find("**/ZScaler;+h-s-i"),       # 5 end scale
                       self.grabModelNP.find("**/XTranslator;+h-s-i"),   # 6
                       self.grabModelNP.find("**/YTranslator;+h-s-i"),   # 7
                       self.grabModelNP.find("**/ZTranslator;+h-s-i"),   # 8 end translate / end single dir operations
                       self.grabModelNP.find("**/XYTranslator;+h-s-i"),  # 9
                       self.grabModelNP.find("**/XZTranslator;+h-s-i"),  # 10
                       self.grabModelNP.find("**/ZYTranslator;+h-s-i"),  # 11 end bi-directional operations
                       self.grabModelNP.find("**/WidgetCore;+h-s-i")]    # 12
        #Mat4.yToZUpMat()  # change coordinate to z up
        grbrNodLst[12].getParent().setHprScale(0, 0, 0, 1, 1, -1)
        self.grabModelNP.setPythonTag('grabberRoot', grbrNodLst)
        self.grabModelNP.reparentTo(BBGlobalVars.bareBonesObj.levitorNP)
        self.grabModelNP.hide()
        #self.grabIntoBitMask = COLLISIONMASKS
        self.grabModelNP.setCollideMask(COLLISIONMASKS['default'])
        self.grabModelNP.setPythonTag('grabber', self)

        ##############################################################################
        # This whole section is the basics for setting up mouse selection
        # --The mouse events are added in the events section (next)

        # Create the collision node for the picker ray to add traverser as a 'from' collider
        self.grabberColNode = CollisionNode('grabberMouseRay')
        # Set the collision bitmask
        # TODO: define collision bitmask (let user define thiers? likely not)
        self.defaultBitMask = GeomNode.getDefaultCollideMask()
        self.grabberColNode.setFromCollideMask(self.defaultBitMask)
        self.grabberRayColNP = camera.attachNewNode(self.grabberColNode)
        # Create the grabberRay and add it to the picker CollisionNode
        self.grabberRay = CollisionRay(0.0, 0.0, 0.0,
                                       0.0, 1.0, 0.0)
        self.grabberRayNP = self.grabberColNode.addSolid(self.grabberRay)
        # create a collision queue for the traverser
        self.colHandlerQueue = CollisionHandlerQueue()
        # Create collision traverser
        self.colTraverser = CollisionTraverser('grabberTraverser')
        # Set the collision traverser's 'fromObj' and handler
        # e.g. trav.addCollider( fromObj, handler )
        self.colTraverser.addCollider(self.grabberRayColNP, self.colHandlerQueue)


        ############################################################
        # setup event handling with the messenger
        # URGENT remove all of this messenger code throughout Grabber, especially the camera control
        # disable the mouse when the ~ is pressed (w/o shift)
        self.disableCamera()                            # disable camera control by the mouse
        messenger.accept('`', self, self.enableCamera)  # enable camera control when the ~ key is pressed w/o shift
        messenger.accept('`-up', self, self.disableCamera)  # disable camera control when the ~ key is released

        # handle mouse selection/deselection & manipulating the scene
        messenger.accept('mouse1', self, self.handleM1, persistent=1)  # deselect in event handler

        taskMgr.add(self.scaleGrabber, 'scaleGrabber')
        # ////////////////////////////////////////////////////////////////////
        # comment out: good for debug info
        #taskMgr.add(self.watchMouseColl, name='grabberDebug')
        #this is only good for seeing types and hierarchy
        #self.grabModelNP.ls()
        #render.ls()
        # self.frames = 0  #remove
        # self.axis = loader.loadModel("zup-axis")
        # self.axis.reparentTo(self.grabModelNP)
        # self.axis.setScale(.15)
        # self.axis.setPos(0.0)
        # self.grabModelNP.append( 'newAttrib', self)
        # setattr( self.grabModelNP, 'newAttrib', self)


    def prepareForPickle(self):
        self.colTraverser = None     # Traversers are not picklable
        self.defaultBitMask = None   # BitMasks "..."
        # self.grabIntoBitMask = None  # "..."
        self.colHandlerQueue = None  # CollisonHandlerQueue "..."
        self.grabModelNP.removeNode()
        self.grabModelNP = None
        taskMgr.remove('scaleGrabber')


    def recoverFromPickle(self):
        self.initialize()
        if self.selected is not None:
            self.grabModelNP.setPos(render, self.selected.getPos(render))
            self.grabModelNP.show()
        print "grabber sel ", self.selected, " isHidden() ", self.grabModelNP.isHidden(), '\n'
        taskMgr.add(self.scaleGrabber, 'scaleGrabber')

    #### May use to gain control over pickling.
    # def __repr__(self): # for pickling purposes
    #     if self.colTraverser:
    #         self.colTraverser = None
    #
    #     dictrepr = dict.__repr__(self.__dict__)
    #     dictrepr = '%r(%r)' % (type(self).__name__, dictrepr)
    #     print dictrepr  # REMOVE
    #     return dictrepr


    def watchMouseColl(self, task):
        """ This exists for debugging purposes to perpetually watch mouse collisions.
        """
        # TODO make this highlight objects under the mouse for predictable object selection/grabber operations
        self.colTraverser.showCollisions(render)
        if base.mouseWatcherNode.hasMouse() and False == self.isCameraControlOn:
            # This gives the screen coordinates of the mouse.
            mPos = base.mouseWatcherNode.getMouse()
            # This makes the ray's origin the camera and makes the ray point
            # to the screen coordinates of the mouse.
            self.grabberRay.setFromLens(base.camNode, mPos.getX(), mPos.getY())
            # traverses the graph for collisions
            self.colTraverser.traverse(render)
        return task.cont


    def scaleGrabber(self, task):
        if self.grabModelNP.isHidden():
            return task.cont
        coreLst = self.grabModelNP.getPythonTag('grabberRoot')
        camPos = self.grabModelNP.getRelativePoint(self.grabModelNP, camera.getPos())

        if camPos.z >= 0:        # 1-4
            if camPos.x > 0.0 <= camPos.y:    # quad 1
                coreLst[12].getParent().setScale( 1, 1, -1)

            elif camPos.x < 0.0 <= camPos.y:  # quad 2
                coreLst[12].getParent().setScale( -1, 1, -1)

            elif camPos.x < 0.0 >= camPos.y:  # quad 3
                coreLst[12].getParent().setScale( -1, -1, -1)

            elif camPos.x > 0.0 >= camPos.y:  # quad 4
                coreLst[12].getParent().setScale( 1, -1, -1)

            else:
                self.notify.warning("if-else default, scaleGrabber cam.z > 0")

        else:      # 5-8
            if camPos.x > 0.0 <= camPos.y:    # quad 5
                coreLst[12].getParent().setScale( 1, 1, 1)

            elif camPos.x < 0.0 <= camPos.y:  # quad 6
                coreLst[12].getParent().setScale( -1, 1, 1)

            elif camPos.x < 0.0 >= camPos.y:  # quad 7
                coreLst[12].getParent().setScale( -1, -1, 1)

            elif camPos.x > 0.0 >= camPos.y:  # quad 8
                coreLst[12].getParent().setScale( 1, -1, 1)

            else:
                self.notify.warning("if-else default, scaleGrabber cam.z z < 0")


        distToCam = (camera.getPos() - render.getRelativePoint(BBGlobalVars.currCoordSysNP, self.grabModelNP.getPos())).length()
        self.grabModelNP.setScale(self.grabScaleFactor * distToCam,
                                  self.grabScaleFactor * distToCam,
                                  self.grabScaleFactor * distToCam)
        # keep the position identical to the selection
        # for when outside objects like undo/redo move selected
        self.grabModelNP.setPos(render, self.selected.getPos(render))
        return task.cont

    # TODO find a way to move camera control to a proper camera handler, perhaps move these to a global
    def enableCamera(self):
        self.isCameraControlOn = True
        PanditorEnableMouseFunc()

    def disableCamera(self):
        self.isCameraControlOn = False
        PanditorDisableMouseFunc()


    def handleM3(self):
        """Deselect the selected object."""
        if not self.grabModelNP.isHidden() and not self.isCameraControlOn:
            # if the grab model is in the scene and the camera is not in control
            if base.mouseWatcherNode.hasMouse() and not self.isDragging:
                # we're ignoring accidental mouse3 clicks while dragging here with not isDragging
                self.selected = None              # empty the selected, will be turned back on once something's selected
                messenger.ignore('mouse3', self)  # turn the deselect event off
                self.grabModelNP.hide()           # hide the grab model and set it back to render's pos
                self.grabModelNP.setPos(0.0)


    def handleM1Up(self):
        """Stop dragging the selected object."""
        taskMgr.remove('mouse1Dragging')
        self.isDragging = False
        self.currTransformOperation = None  # NOTE other references have been added, but no other object references them
        # record the mouse1 operation
        BBGlobalVars.undoHandler.record(self.selected, CommandUndo([self.initialCommandTrgVal],
                                                                    self.selected.setMat, self.selected.getMat(render)))
        messenger.ignore('mouse1-up', self)


    def handleM1(self):
        """Decides how to handle a mouse1 click."""
        if self.isCameraControlOn:
            return

        if base.mouseWatcherNode.hasMouse():
            # give the grabber first chance
            if self.grabModelNP.isHidden():
                # no collisions w/ grabber or nothing selected
                # handle selection with scene objects
                self.handleSelection()

            elif not self.isDragging:
                # The grabber is in place but not dragging. Get ready to drag.
                self.handleManipulationSetup()  # it'll call self.handleSelection() if no collision w/ grabber
                # TODO (if warranted) make self.handleManipulationSetup() return false if no col w/ grabber, call selection here instead


    def handleManipulationSetup(self):
        """Sets up all the attributes needed for the mouse dragging task."""
        # This makes the ray's origin the camera and makes the ray point
        # to the screen coordinates of the mouse.
        if self.isDragging:
            return
        camVec = self.grabModelNP.getRelativeVector(self.grabModelNP, camera.getPos())
        mPos = base.mouseWatcherNode.getMouse()
        self.grabberRay.setFromLens(base.camNode, mPos.getX(), mPos.getY())
        self.colTraverser.traverse(self.grabModelNP)  # look for collisions on the grabber

        if not self.isCameraControlOn and self.colHandlerQueue.getNumEntries() > 0 and not self.grabModelNP.isHidden():
            # see if collided with the grabber if not handle re or multi selection
            self.colHandlerQueue.sortEntries()
            grabberObj = self.colHandlerQueue.getEntry(0).getIntoNodePath()
            grabberLst = self.grabModelNP.getPythonTag('grabberRoot')  # see __init__

            # the index gives the operations rot < 3 scale < 6 trans < 9 trans2D < 12
            # mod index gives axis 0 == x, 1 == y, 2 == z
            ind = -1
            for i in range(0, 13):
                if grabberObj == grabberLst[i]:
                    ind = i
                    grabberObj = grabberLst[i]
            # ensure we are not picking ourselves, ahem, the grabber
            assert(not self.grabModelNP.isAncestorOf(self.selected))
            mPos3D = Point3(0.0)
            xVec = Vec3(1, 0, 0)
            yVec = Vec3(0, 1, 0)
            zVec = Vec3(0, 0, 1)
            # TODO: ??? break this up into translate rotate and scale function to make it readable
            if -1 < ind < 3:             # rotate
                if ind % 3 == 0:    # x
                    self.initializeManipVars(Point3(1.0, 0.0, 0.0), self.transformOpEnum.rot,
                                             Point3(mPos.getX(), mPos.getY(), 0.0))
                elif ind % 3 == 1:  # y
                    self.initializeManipVars(Point3(0.0, 1.0, 0.0), self.transformOpEnum.rot,
                                             Point3(mPos.getX(), mPos.getY(), 0.0))
                else:               # z
                    self.initializeManipVars(Point3(0.0, 0.0, 1.0), self.transformOpEnum.rot,
                                             Point3(mPos.getX(), mPos.getY(), 0.0))

            elif ind < 6:                 # scale
                if ind % 3 == 0:    # x
                    self.initializeManipVars(Point3(1.0, 0.0, 0.0), self.transformOpEnum.scale,
                                             Point3(mPos.getX(), mPos.getY(), 0.0))
                elif ind % 3 == 1:  # y
                    # self.currTransformDir = Point3( 0.0, 1.0, 0.0)
                    self.initializeManipVars(Point3(0.0, 1.0, 0.0), self.transformOpEnum.scale,
                                             Point3(mPos.getX(), mPos.getY(), 0.0))
                else:               # z
                    # self.currTransformDir = Point3( 0.0, 0.0, 1.0)
                    self.initializeManipVars(Point3(0.0, 0.0, 1.0), self.transformOpEnum.scale,
                                             Point3(mPos.getX(), mPos.getY(), 0.0))

            elif ind < 9:                 # translate
                if ind % 3 == 0:    # x
                    # if the camera's too flat to the collision plane bad things happen
                    if camVec.angleDeg( zVec) < 89.0 and self.getMousePlaneIntersect(mPos3D, zVec):
                        self.initializeManipVars(Point3(1.0, 0.0, 0.0), self.transformOpEnum.trans, mPos3D, zVec)

                    elif self.getMousePlaneIntersect(mPos3D, yVec):
                        self.initializeManipVars(Point3(1.0, 0.0, 0.0), self.transformOpEnum.trans, mPos3D, yVec)

                elif ind % 3 == 1:  # y
                    if camVec.angleDeg( zVec) < 89.0 and self.getMousePlaneIntersect(mPos3D, zVec):
                        self.initializeManipVars(Point3(0.0, 1.0, 0.0), self.transformOpEnum.trans, mPos3D, zVec)

                    elif self.getMousePlaneIntersect(mPos3D, xVec):
                        self.initializeManipVars(Point3(0.0, 1.0, 0.0), self.transformOpEnum.trans, mPos3D, xVec)

                else:               # z
                    if camVec.angleDeg( yVec) < 89.0 and self.getMousePlaneIntersect(mPos3D, yVec):
                        self.initializeManipVars(Point3(0.0, 0.0, 1.0), self.transformOpEnum.trans, mPos3D, yVec)

                    elif self.getMousePlaneIntersect(mPos3D, xVec):
                        self.initializeManipVars(Point3(0.0, 0.0, 1.0), self.transformOpEnum.trans, mPos3D, xVec)

            elif ind < 12:            # translate 2D
                if ind % 3 == 0:    # xy
                    if self.getMousePlaneIntersect(mPos3D, zVec):
                        self.initializeManipVars(Point3(1.0, 1.0, 0.0), self.transformOpEnum.trans, mPos3D, zVec)

                elif ind % 3 == 1:  # xz
                    if self.getMousePlaneIntersect(mPos3D, yVec):
                        self.initializeManipVars(Point3(1.0, 0.0, 1.0), self.transformOpEnum.trans, mPos3D, yVec)
                else:               # zy
                    if self.getMousePlaneIntersect(mPos3D, xVec):
                        self.initializeManipVars(Point3(0.0, 1.0, 1.0), self.transformOpEnum.trans, mPos3D, xVec)

            elif ind == 12:  # scale in three directions
                self.initializeManipVars(Point3(1.0, 1.0, 1.0), self.transformOpEnum.scale,
                                         Point3(mPos.getX(), mPos.getY(), 0.0))

            else:
                self.notify.warning("Grabber Err: no grabber collision when col entries > 0 AND grabber not hidden")

            # Save initial value for save/undo.
            # The end result of the operation is sent to the undo handler on mouse up event.
            if self.selected:
                self.initialCommandTrgVal = self.selected.getMat(render)
        else:
            # no collisions w/ grabber or nothing selected
            # handle reselection or multi-selection (not yet implemented) with other scene obj
            self.handleSelection()


    def handleSelection(self):
        if self.isDragging:
            return

        # First check that the mouse is not outside the screen.
        if base.mouseWatcherNode.hasMouse() and False == self.isCameraControlOn:

            self.grabberColNode.setFromCollideMask(self.defaultBitMask)
            # This gives the screen coordinates of the mouse.
            mPos = base.mouseWatcherNode.getMouse()

            # This makes the ray's origin the camera and makes the ray point
            # to the screen coordinates of the mouse.
            self.colHandlerQueue.clearEntries()
            self.grabberRay.setFromLens(base.camNode, mPos.getX(), mPos.getY())
            self.colTraverser.traverse(render)  # look for collisions

            if self.colHandlerQueue.getNumEntries() > 0:
                self.colHandlerQueue.sortEntries()
                grabbedObj = self.colHandlerQueue.getEntry(0).getIntoNodePath()
                if not grabbedObj.findNetTag('pickable').isEmpty():
                    grabbedObj = grabbedObj.findNetTag('pickable')
                    self.selected = grabbedObj
                    self.grabModelNP.setPos(render,
                                            grabbedObj.getPos(render).x,
                                            grabbedObj.getPos(render).y,
                                            grabbedObj.getPos(render).z)
                    self.grabModelNP.show()
                    messenger.accept('mouse3', self, self.handleM3)

    def handleDragging(self, task):
        """ Does the actual work of manipulating objects,
            once the needed attributes have been setup by handleManipulationSetup().
        """

        if not self.isDragging:
            return task.done
        mPos3D = Point3(0.0)
        #
        # This section handles the actual translating rotating or scale after it's been set up in mouse1SetupManip...()
        # ONLY one operation is preformed per frame
        if self.currTransformOperation == self.transformOpEnum.trans:
            # 1st translation, rotation's section is at next elif
            if self.getMousePlaneIntersect(mPos3D, self.currPlaneColNorm):

                # get the difference between the last mouse and this frames mouse
                selectedNewPos = mPos3D - self.interFrameMousePosition
                # store this frames mouse
                self.interFrameMousePosition = mPos3D
                # add the difference to the selected object's pos
                self.selected.setPos(render, self.selected.getPos(render).x + self.currTransformDir.x * selectedNewPos.x,
                                             self.selected.getPos(render).y + self.currTransformDir.y * selectedNewPos.y,
                                             self.selected.getPos(render).z + self.currTransformDir.z * selectedNewPos.z)

                self.grabModelNP.setPos(render, self.selected.getPos(render))

        elif self.currTransformOperation == self.transformOpEnum.rot:
            # 2nd rotation, followed finally by scaling
            # if operating on the z-axis, use the y (vertical screen coordinates otherwise use x (horizontal)
            mPos = base.mouseWatcherNode.getMouse()
            #rotMag = 0.0
            if self.currTransformDir == Vec3( 0.0, 0.0, 1.0):
                rotMag = (mPos.x - self.interFrameMousePosition.x) * 1000
            else:
                rotMag = (self.interFrameMousePosition.y - mPos.y) * 1000

            initPos = self.selected.getPos()
            initPar = self.selected.getParent()
            self.selected.wrtReparentTo(render)
            self.selected.setMat(self.selected.getMat() * Mat4.rotateMat(rotMag, self.currTransformDir))
            self.selected.wrtReparentTo(initPar)
            self.selected.setPos(initPos)

            self.interFrameMousePosition = Point3(mPos.x, mPos.y, 0.0)

        elif self.currTransformOperation == self.transformOpEnum.scale:
            # 3rd and final is scaling
            mPos = base.mouseWatcherNode.getMouse()
            # TODO: make dragging away from the object larger and to the object smaller (not simply left right up down)
            # td The problem with this MAY come if negative, mirrored, scaling is implemented.

            # if operating on the z-axis, use the y (vertical screen coordinates otherwise use x (horizontal)
            if self.currTransformDir == Point3( 0.0, 0.0, 1.0):
                sclMag = (mPos.y - self.interFrameMousePosition.y) * 5.5
            elif self.currTransformDir == Point3( 0.0, 1.0, 0.0):
                sclMag = (mPos.x - self.interFrameMousePosition.x) * 5.5
            else:
                sclMag = (self.interFrameMousePosition.x - mPos.x) * 5.5

            # This is the line that prevents scaling past the origin. Flipping the faces doesn't seem to work.
            if -0.0001 < sclMag < 0.0001:
                sclMag = 0.000001

            # create a dummy node to parent to and position such that applying scale to it will scale selected properly
            dummy = self.levitorNP.attachNewNode('dummy')
            initScl = dummy.getScale()
            # Don't forget the parent. Selected needs put back in place
            initPar = self.selected.getParent()
            initPos = self.selected.getPos()
            self.selected.wrtReparentTo(dummy)

            dummy.setScale(initScl.x + sclMag * self.currTransformDir.x,
                           initScl.y + sclMag * self.currTransformDir.y,
                           initScl.z + sclMag * self.currTransformDir.z)

            # reset selected's parent then destroy dummy
            self.selected.wrtReparentTo(initPar)
            self.selected.setPos(initPos)
            dummy.removeNode()
            dummy = None

            self.interFrameMousePosition = Point3( mPos.x, mPos.y, 0.0)
        else:
            self.notify.error("Err: Dragging with invalid curTransformOperation enum in handleDragging")

        return task.cont  # ended by handleM1Up(), the mouse1-up event handler


    def initializeManipVars(self, transformDir, transformOp, mPos3D, planeNormVec=None):
        self.currTransformDir = transformDir
        self.currPlaneColNorm = planeNormVec  # set the norm for the collision plane to be used in mouse1Dragging
        self.interFrameMousePosition = mPos3D
        self.currTransformOperation = transformOp
        self.isDragging = True
        taskMgr.add(self.handleDragging, 'mouse1Dragging')
        messenger.accept('mouse1-up', self, self.handleM1Up)


    def getMousePlaneIntersect(self, mPos3Dref, normVec):
        mPos = base.mouseWatcherNode.getMouse()
        plane = Plane(normVec, self.grabModelNP.getPos())
        nearPoint = Point3()
        farPoint = Point3()
        base.camLens.extrude(mPos, nearPoint, farPoint)
        if plane.intersectsLine(mPos3Dref,
            render.getRelativePoint(camera, nearPoint),
            render.getRelativePoint(camera, farPoint)):
            return True
        return False



    def destroy(self):
        raise NotImplementedError('Make sure messenger etc are cleared of refs and the model node is deleted')
        self.grabModelNP.clearPythonTag('grabberRoot')
        self.grabModelNP.clearPythonTag('grabber')
        self.grabModelNP = None
        messenger.ignoreAll(self)
from panda3d.core import ConfigVariableString
from direct.directnotify.DirectNotify import DirectNotify

language = ConfigVariableString('language', 'English')
language = language.getValue()

notify = DirectNotify().newCategory("OTPLocalizer")

def getLanguage():
    return language

_languageModule = 'otp.otpbase.OTPLocalizer' + language

try:
    exec 'from ' + _languageModule + ' import *'
    print ":OTPLocalizer: Running in language: %s" % language
except:
    notify.warning("Error, Language %s not found!" % language)
    notify.warning("Setting language to default (English)")
    from otp.otpbase.OTPLocalizerEnglish import *
    

Esempio n. 44
0
 def __init__(self):
     self.notify = DirectNotify().newCategory("core")
Esempio n. 45
0
class PlaneCamera(FSM, DirectObject):
    """Give this class a plane as argument and it will create
    some nodes around it which you can parent the camera to (if there are no
    such nodes yet). Keep in mind, that it only uses base.camera the whole
    time - no other cams are involved.

    Usage:
    plane_camera = PlaneCamera(aeroplane)
    plane_camera.setView("ThirdPerson")
    plane_camera.setView("Next")
    """
    def __init__(self, parent):
        """Arguments:
        parent -- Aeroplane which the camera should follow
        """

        # Used for debugging. Verbosity is set in config file.
        # Usually this is called self.notify, but in this case it would
        # override FSM's own.
        self.notifier = DirectNotify().newCategory("azure-camera")
        self.parent = parent
        # Replaced by a NodePath with all available cameras as children and
        # plane node as parent.
        self.cameras = None

        #if parent.__class__.__name__ is not "Aeroplane":
        if not isinstance(self.parent, Aeroplane):
            raise ParamError, "Parent must be an Aeroplane instance, " + \
                              "but is %s" % type(self.parent)

        FSM.__init__(self, "PlaneCamera: %s" % self.parent.name)
        DirectObject.__init__(self)

        try:
            self.camera = base.camera
        except:
            raise BaseMissing

        self.cameras = self.parent.node.find("cameras")
        if self.cameras.isEmpty():
            self.createCamNodes()
        self.updateCamArray()

        self.sideview_direction = 0

        # Set up the default camera
        self.setView("ThirdPerson")

    def createCamNodes(self):
        """Creates a few empty nodes around a plane which the camera might be
        parented to. It looks if there are cameras inside the model file and
        uses those if possible. Where everything named "camera CamType" is
        considered a camera. At least ThirdPerson, FirstPerson and Cockpit
        should be defined inside the egg file, otherwise some guessed defaults
        are taken.
        """

        # Look for cameras inside the model (loaded egg file)
        self.cameras = NodePath("cameras")
        found_cams = self.parent.node.findAllMatches("**/camera ?*")
        found_cams.removeDuplicatePaths()
        found_cams.reparentTo(self.cameras)

        if not found_cams.isEmpty():
            self.notifier.info("Cameras found under model:\n%s"
                               % found_cams)
        else:
            self.notifier.info("No cameras found under model.")

        # FirstPerson camera is a must-have. Set up a guessed one if none
        # defined yet.
        if self.cameras.find("camera FirstPerson").isEmpty():
            assert self.notifier.debug("No first person camera found in %s. "
                                  "Guessing best position." % self.parent.name)
            first_person = NodePath("camera FirstPerson")
            # TODO: Guess best position based on bounding box.
            first_person.setY(5)
            first_person.reparentTo(cameras)

        # ThirdPerson camera is a must-have. Set up a guessed one if none
        # defined yet.
        if self.cameras.find("camera ThirdPerson").isEmpty():
            assert self.notifier.debug("No third person camera found in %s. "
                                  "Guessing best position." % self.parent.name)
            third_person = NodePath("camera ThirdPerson")
            # TODO: Guess best position based on bounding box.
            third_person.setPos(0, -30, 5)
            #third_person.setP(-80)
            third_person.reparentTo(cameras)

        # Cockpit needs to be accurate. Don't try to guess it.
        if self.cameras.find("camera Cockpit").isEmpty():
            assert self.notifier.debug("No cockpit camera found in "
                                       "%s. Cockpit camera disabled."
                                       % self.parent.name)
        self.sideview_cam = NodePath("camera Sideview")
        self.sideview_cam.reparentTo(render)

        # Store the cams at parent node..
        # You can edit the camera nodes from outside as well.
        # If you attach new camera nodes, though, you'll have to call this
        # function again.
        self.cameras.reparentTo(self.parent.node)

    def updateCamArray(self, cameramodes=None):
        """Set the cameras which next and previous will switch to. Expects a
        list or tuple. Defaults to all available cameras."""
        a = []
        if not cameramodes:
            for c in self.cameras.getChildren():
                if c.getName().startswith("camera "):
                    a.append(c.getName().strip("camera "))
            self.setStateArray(a)
        else:
            self.setStateArray(cameramodes)

    def getView(self):
        """Returns the current view mode."""
        return self.getCurrentOrNextState()

    def setView(self, mode, *args):
        """Convenience function."""
        return self.request(mode, args)

    def defaultEnter(self, *args):
        """Executed by the FSM every time an undefined state is entered.
        Note: this function is called AFTER the responsible filter."""

        assert self.notifier.debug("Changing state from %s to %s with args: %s."
                                   % (self.oldState, self.newState, args))
        request = self.newState

        target_cam = self.cameras.find("camera " + request)
        if not target_cam.isEmpty():
            try:
                self.camera.reparentTo(target_cam)
                self.camera.setPosHpr(0, 0, 0, 0, 0, 0)
            except:
                self.notifier.warning(
                        "Ok, now this really shouldn't happen! Filter said the "
                        "camera is there and enter can't find it...")



    def defaultFilter(self, request, args):
        """Executed by the FSM every time an undefined state is requested."""
        assert self.notifier.debug("Requested %s with args: %s"
                                   % (request, args))

        self.camera.setPosHpr(0, 0, 0, 0, 0, 0)

        # Always available.
        if request == "Off":   # implemented in FSM.py
            return (request,) + args
        if request == "Next":  # implemented in FSM.py
            return self.requestNext(args)
        if request == "Prev":  # implemented in FSM.py
            return self.requestPrev(args)
        if request == "Detached":
            return (request,) + args
        if request == "Sideview":
            return (request,) + args
        
        # Depending on airplane.
        if not self.cameras.find("camera " + request).isEmpty():
            # TODO(Nemesis13, 26.10.09): add some nice camera transition
            return (request,) + args
        assert self.notifier.info("Sorry, no %s camera found." % request)
        return None


    def enterOff(self, *args):
        """Clean up everything by reparenting the camera to the airplane."""
        self.camera.reparentTo(self.parent.node)
        self.camera.setPosHpr(0, 0, 0, 0, 0, 0)

    def enterSideview(self, *args):
        self.sideview_direction += 90
        self.camera.reparentTo(self.sideview_cam)
        self.camera.setY(-30)
        self.sideview_cam.setH(self.sideview_direction)
        self.addTask(self.updateSideview, "sideview camera", taskChain="world")

    def exitSideview(self, *args):
        self.removeTask("sideview camera")

    def updateSideview(self, task):
        self.sideview_cam.setPos(self.parent.node.getPos())
        return Task.cont

    def enterDetached(self, *args):
        """Lets the camera view the plane from far away."""
        self.camera.reparentTo(render)
        self.camera.setPosHpr(0, 0, 10, 0, 0, 0)
        self.addTask(self.updateDetachedCam, "detached camera",
                     taskChain="world")

    def exitDetached(self, *args):
        self.removeTask("detached camera")

    def updateDetachedCam(self, task):
        """Updates camera position and rotation for Detached camera."""
        try:
            self.camera.lookAt(self.parent.node)
        except:
            self.notifier.warning("Error on detached cam task. Exit.")
            return Task.done
        return Task.cont

    def enterThirdPerson(self, *args):
        """Lets the camera view the plane from far away."""
        self._hist = []
        self.camera.reparentTo(self.cameras.find("camera ThirdPerson"))
        self.addTask(self.updateThirdPersonCam, "third person camera",
                     taskChain="world")
        #print "entering third person"

    def exitThirdPerson(self, *args):
        self.removeTask("third person camera")
        del self._hist
        #print "third person exited"

    def updateThirdPersonCam(self, task):
        """Updates camera position and rotation for ThirdPerson camera."""
        #speed = self.parent.speed()
        #plane = self.parent.node
        #self._hist.insert(0, [task.time, camera.getPos(plane)])
        #while len(self._hist) > 50:
        #    self._hist.pop()
        #
        #for snapshot in self._hist:
        #    if snapshot[0] > task.time:
        #        break
        #time_delta = snapshot[0] - task.time
        #self.camera.setPos(plane, snapshot[1])

        #print snapshot
        #self.camera.setPos(render, snapshot[1])
        #self.camera.lookAt(plane, (0, 20+1*speed, 0))

        #self.camera.setY(5+0.1*speed)
        #self.camera.setZ(5-0.1*speed)

        return Task.cont

    def destroy(self):
        self.removeAllTasks()
        self.demand("Off")
Esempio n. 46
0
def get_logs(task):
    '''Yanks Panda3D's log pipe and pumps it to logOutput'''
    #if line_stream.hasNewline():
    while line_stream.isTextAvailable():
        logOutput.contents.append(urwid.Text(line_stream.getLine()))
        logOutput.set_focus(len(logOutput) - 1)
    return task.cont


if __name__ == '__main__':
    from direct.showbase.ShowBase import ShowBase
    from math import pi, sin, cos
    from direct.task import Task

    log = DirectNotify().newCategory("SandBox")
    log.info("Sweet")

    def spinCameraTask(task):
        angleDegrees = task.time * 6.0
        angleRadians = angleDegrees * (pi / 180.0)
        app.camera.setPos(20 * sin(angleRadians), -20.0 * cos(angleRadians), 3)
        app.camera.setHpr(angleDegrees, 0, 0)
        return Task.cont

    class MyApp(ShowBase):
        def __init__(self):
            ShowBase.__init__(self)
            self.environ = self.loader.loadModel("models/environment")
            self.environ.reparentTo(self.render)
            self.environ.setScale(0.25, 0.25, 0.25)