Exemplo n.º 1
0
    def setOptionsFromGlobals(self):
        Tool.setOptionsFromGlobals(self)

        scene = getScene()
        self.options.full_screen = scene.getGlobal("fullscreen", self.options.full_screen)

        self.options.eye_distance = float(scene.getGlobal("eyedistance", self.options.eye_distance))

        # Check the stereo option and initialize the variable "stereo_mode"
        Sopt = scene.getGlobal("stereo", None)
        self.stereo_mode = self.translateKeyWordOpt(Sopt,
                                { None:0, "vsplit":1, "glstereo":2 },
                                "Unknown stereo mode: '%s'")

        # Check the polygon mode option
        Popt = scene.getGlobal("polygonmode", "fill")
        self.polygon_mode = self.translateKeyWordOpt(Popt,
                                { None:2, "point":0, "line":1, "fill":2 },
                                "Unknown polygon mode: '%s'")

        # Check the navigationmode option
        Nopt = scene.getGlobal("navigationmode", "maya")
        self.navigation_mode = self.translateKeyWordOpt(Nopt,
                            { None:1, "max":0, "maya":1, "softimage":2 },
                            "Unknown navigation mode: '%s'")
Exemplo n.º 2
0
    def run_gl(self):
        # Create a camera control component
        self._init_camera()
        CameraControl(cam=self._camera, mode=1)

        # Get options...
        width = self._config.getint('window', 'width')
        height = self._config.getint('window', 'height')

        # Open a window...
        pygame.display.set_caption("OpenGL viewer")
        flags = OPENGL | DOUBLEBUF
        self.gl_surface = pygame.display.set_mode((width,height), flags)

        # Try to get the native window handle
        # (this only works with pygame 1.6.2 and later)
        try:
            info = pygame.display.get_wm_info()
            hwnd = info["window"]
        except:
            hwnd = None

        # Event loop...
        self._running = True
        self._timer = getScene().timer()
        self._clock = pygame.time.Clock()
        self._cnt = 0
        self._timer.startClock()
        self._fps = self._config.getint('general', 'framerate')

        self.tk_root.after(50, self._loop_once, width, height)
        self._log.info(u"3d visualization running...")
Exemplo n.º 3
0
    def draw(self, cam, width, height):
        scene = getScene()
        renderer = self.gl_renderer

        # Set handedness
        renderer.left_handed = scene.handedness=="l"
        renderer.setViewport(0,0,width,height)

        renderer.draw_solid = True
        #renderer.draw_bboxes = self.options.bounding_box
        renderer.draw_coordsys = False
        #renderer.draw_orientation = self.draw_orientation
        renderer.smooth_model = True
        renderer.backface_culling = False
        #renderer.separate_specular_color = self.separate_specular_color
        #renderer.polygon_mode = self.polygon_mode  # 0=Point 1=Line 2=Fill
        #renderer.stereo_mode = self.stereo_mode
        renderer.clearcol = vec4(scene.getGlobal("background", vec4(0.5,0.5,0.6,0)))

        # Set projection matrix
        near, far = cam.getNearFar()
        P = cam.projection(width,height,near,far)
        renderer.setProjection(P)

        # Set view matrix
        renderer.setViewTransformation(cam.viewTransformation(), 0)

        # Draw scene
        root = scene.worldRoot()
        renderer.paint(root)
Exemplo n.º 4
0
def removeObject(obj, world):
    scene = getScene()
    try:
        scene.items.remove(obj)
    except:
        pass
    if world.body_dict.has_key(obj):
        body = world.body_dict.pop(obj)
        world.bodies.remove(body)
Exemplo n.º 5
0
    def saveScreenshot(self, srf):
        """Save the current window content.

        srf is the pygame Surface object.
        """
        name,ext = os.path.splitext(self.options.save)
        f = int(round(getScene().timer().frame))
        fname = "%s%04d%s"%(name, f, ext)
        print 'Saving "%s"...'%fname
        data = pygame.image.tostring(srf, "RGB")
        img = Image.fromstring("RGB", (srf.get_width(), srf.get_height()), data)
        img.save(fname)
Exemplo n.º 6
0
def drawBoxGL():
    #print "draw"
    #glutSolidCube(1)

    glColor3f(0,0,0)
    glLineWidth(2)
    glDisable(GL_LIGHTING)
    
    for b in getScene().walkWorld():
        if type(b.geom) == cgkit.boxgeom.BoxGeom:
            x,y,z = b.pos.x,b.pos.y,b.pos.z
            x,y,z = 0,0,0
            l,w,h = b.lx/2, b.ly/2, b.lz/2

            glPushMatrix()
            glMultMatrixd(b.worldtransform.toList())
            glBegin(GL_LINE_STRIP)
            glVertex3f(x-l,y-w,z-h)
            glVertex3f(x+l,y-w,z-h)
            glVertex3f(x+l,y+w,z-h)
            glVertex3f(x-l,y+w,z-h)
            glVertex3f(x-l,y-w,z-h)

            glVertex3f(x-l,y-w,z+h)
            glVertex3f(x+l,y-w,z+h)
            glVertex3f(x+l,y+w,z+h)
            glVertex3f(x-l,y+w,z+h)
            glVertex3f(x-l,y-w,z+h)
            glEnd()

            glBegin(GL_LINE_STRIP)
            glVertex3f(x-l,y-w,z-h)
            glVertex3f(x-l,y-w,z+h)
            glEnd()

            glBegin(GL_LINE_STRIP)
            glVertex3f(x-l,y+w,z-h)
            glVertex3f(x-l,y+w,z+h)
            glEnd()

            glBegin(GL_LINE_STRIP)
            glVertex3f(x+l,y+w,z-h)
            glVertex3f(x+l,y+w,z+h)
            glEnd()

            glBegin(GL_LINE_STRIP)
            glVertex3f(x+l,y-w,z-h)
            glVertex3f(x+l,y-w,z+h)
            glEnd()


            glPopMatrix()
Exemplo n.º 7
0
def remove(objs):
    objs = cmds.worldObjects(objs)
    
    for o in objs:
        for c in o.iterChilds():
            remove(c)
        for s in getScene().items:
            if type(s) == ODEDynamics:
                try: s.remove(o)
                except: pass
            if type(s) == cgkit._core.WorldObject:
                try: s.removeChild(o)
                except: pass
Exemplo n.º 8
0
def drawBoxGL():
    #print "draw"
    #glutSolidCube(1)

    glColor3f(0, 0, 0)
    glLineWidth(2)
    glDisable(GL_LIGHTING)

    for b in getScene().walkWorld():
        if type(b.geom) == cgkit.boxgeom.BoxGeom:
            x, y, z = b.pos.x, b.pos.y, b.pos.z
            x, y, z = 0, 0, 0
            l, w, h = b.lx / 2, b.ly / 2, b.lz / 2

            glPushMatrix()
            glMultMatrixd(b.worldtransform.toList())
            glBegin(GL_LINE_STRIP)
            glVertex3f(x - l, y - w, z - h)
            glVertex3f(x + l, y - w, z - h)
            glVertex3f(x + l, y + w, z - h)
            glVertex3f(x - l, y + w, z - h)
            glVertex3f(x - l, y - w, z - h)

            glVertex3f(x - l, y - w, z + h)
            glVertex3f(x + l, y - w, z + h)
            glVertex3f(x + l, y + w, z + h)
            glVertex3f(x - l, y + w, z + h)
            glVertex3f(x - l, y - w, z + h)
            glEnd()

            glBegin(GL_LINE_STRIP)
            glVertex3f(x - l, y - w, z - h)
            glVertex3f(x - l, y - w, z + h)
            glEnd()

            glBegin(GL_LINE_STRIP)
            glVertex3f(x - l, y + w, z - h)
            glVertex3f(x - l, y + w, z + h)
            glEnd()

            glBegin(GL_LINE_STRIP)
            glVertex3f(x + l, y + w, z - h)
            glVertex3f(x + l, y + w, z + h)
            glEnd()

            glBegin(GL_LINE_STRIP)
            glVertex3f(x + l, y - w, z - h)
            glVertex3f(x + l, y - w, z + h)
            glEnd()

            glPopMatrix()
Exemplo n.º 9
0
    def autoAdd(self):
        scene = getScene()
        # Add all rigid bodies first...
        for obj in scene.worldRoot().iterChilds():
            if obj not in self.body_dict:
                try:
                    obj = protocols.adapt(obj, IRigidBody)
                    self.add(obj)
                except NotImplementedError:
                    pass

        # Then add all joints...
        for obj in scene.worldRoot().iterChilds():
            if obj not in self.joints:
                if isinstance(obj, cgkit.odedynamics.ODEJointBase):
                    self.add(obj)
Exemplo n.º 10
0
    def autoAdd(self):
        scene = getScene()
        # Add all rigid bodies first...
        for obj in scene.worldRoot().iterChilds():
            if obj not in self.body_dict:
                try:
                    obj = protocols.adapt(obj, IRigidBody)
                    self.add(obj)
                except NotImplementedError:
                    pass

        # Then add all joints...
        for obj in scene.worldRoot().iterChilds():
            if obj not in self.joints:
                if isinstance(obj, cgkit.odedynamics.ODEJointBase):
                    self.add(obj)
Exemplo n.º 11
0
def remove(objs):
    objs = cmds.worldObjects(objs)

    for o in objs:
        for c in o.iterChilds():
            remove(c)
        for s in getScene().items:
            if type(s) == ODEDynamics:
                try:
                    s.remove(o)
                except:
                    pass
            if type(s) == cgkit._core.WorldObject:
                try:
                    s.removeChild(o)
                except:
                    pass
Exemplo n.º 12
0
    def draw(self, cam, width, height):
        scene = getScene()
        renderer = self.renderer

        # Set handedness
        renderer.left_handed = scene.handedness == "l"
        renderer.setViewport(0, 0, width, height)

        renderer.draw_solid = True
        renderer.draw_bboxes = self.options.bounding_box
        renderer.draw_coordsys = False
        renderer.draw_orientation = self.draw_orientation
        renderer.smooth_model = True
        renderer.backface_culling = False
        renderer.separate_specular_color = self.separate_specular_color
        renderer.polygon_mode = self.polygon_mode  # 0=Point 1=Line 2=Fill
        renderer.stereo_mode = self.stereo_mode
        renderer.clearcol = vec4(
            scene.getGlobal("background", vec4(0.5, 0.5, 0.6, 0)))

        V = cam.viewTransformation()
        V2 = None
        if renderer.stereo_mode != 0:
            d = getattr(cam, "eye_distance", self.options.eye_distance)
            T1 = mat4().translation(vec3(-d, 0, 0))
            T2 = mat4().translation(vec3(d, 0, 0))
            V2 = T2 * V
            V = T1 * V
            if renderer.stereo_mode == 1:
                width /= 2

        # Set projection matrix
        near, far = cam.getNearFar()
        P = cam.projection(width, height, near, far)
        renderer.setProjection(P)

        # Set view matrix
        renderer.setViewTransformation(V, 0)
        if V2 != None:
            renderer.setViewTransformation(V2, 1)

        # Draw scene
        root = scene.worldRoot()
        renderer.paint(root)
Exemplo n.º 13
0
 def _postContextReset(self):
     """This is called after a window resize which destroys the OpenGL context (using SDL/pygame).
      
     Using SDL, a window resize resets the OpenGL context, so all allocated
     resources get lost. Currently, this only destroys textures, so this
     method iterates over all objects and dirties the textures so that
     their image gets reloaded.
     """
     # Iterate over all objects in the scene...
     for obj in getScene().walkWorld():
         # Iterate over the materials of the current object...
         for matIdx in range(obj.getNumMaterials()):
             mat = obj.getMaterial(matIdx)
             if isinstance(mat, GLMaterial):
                 # Iterate over the textures of the current material...
                 for texIdx in range(mat.getNumTextures()):
                     tex = mat.getTexture(texIdx)
                     # Setting the name will mark the texture dirty and the image is reloaded
                     tex.imagename = tex.imagename
Exemplo n.º 14
0
    def _init_camera(self):
        scene = getScene()

        if self._config.has_option('scene', 'camera'):
            cname = self._config.get('scene', 'camera')
        else:
            cname = None
        
        # Search for a camera...
        cam = None
        for obj in scene.walkWorld():
            prots = obj.protocols()
            if ICamera in prots:
                if obj.name==cname or cname==None :
                    cam = obj
                    break

        if cname!=None and cam==None:
            raise ValueError, 'Camera "%s" not found.' % cname

        # No camera? Then create a default camera...
        if cam==None:
            self._log.info(u"No camera set, using a default camera.")
            bbmin, bbmax = scene.boundingBox().getBounds()
            dif = bbmax-bbmin
            b1 = scene.up.ortho()
            b2 = scene.up.cross(b1)
            pos = dif.length()*(0.5*b1+b2) + (bbmax.z+0.5*dif.z)*scene.up
            if abs(dif.z)<0.0001:
                pos += 0.8*dif.length()*scene.up
            cam = TargetCamera(pos = pos,
                               target = 0.5*(bbmin+bbmax)-0.2*(dif.z*scene.up),
                               fov = 50)
        else:
            self._log.info(u"Camera: %s" % cam.name)

        self._camera = cam
Exemplo n.º 15
0
    def action(self):

        CameraControl(cam=self.cam, mode=self.navigation_mode)

        print "mmmmhh3"

        scene = getScene()
        timer = scene.timer()
        worldroot = scene.worldRoot()
        myOgre = OgreCore()
        self.ogrecore = myOgre
        #myOgre.setAmbient(0,0,0)

        # tell ogre which shadow mode to use
        print "mmmmhh4"
        myOgre.setupShadowMode(self.shadowmode, 2048)
        #myOgre.setupShadowMode(0,512)

        myOgre.initialize(
            worldroot,
            self.options.width,
            self.options.height,
            self.options.full_screen,
            not self.options.no_shadow,
            self.use_opengl,
            r".\demosOgre\materials",
            #                         self.materialpath,
            self.options.stereo)

        # signature: cameraObject
        myOgre.setupData(self.cam, 0.1, 1000.0, self.cam.fov)

        # Set background color
        if scene.hasGlobal("background"):
            bg = scene.getGlobal("background")
            r = int(255 * bg[0])
            g = int(255 * bg[1])
            b = int(255 * bg[2])
            myOgre.changeBackgroundColor(r, g, b)

        eventmanager = eventManager()

        running = 1
        while (running):

            ####* #        SIMULATE

            timer.step()

            ####* #        RENDER ONE OGRE FRAME

            myOgre.renderTree()

            #####* #   **  GET EVENTS

            ########################
            #####* #   01  KEYDOWN ?

            kd = myOgre.pumpKeyDowns()
            i = 0
            while (i < len(kd)):
                # quit when ESC is pressed
                #print kd
                if (kd[i + 1] == 1):
                    #myOgre.rebuildOgreTree(worldroot)
                    running = 0
                code = self.keydict.get(kd[i + 1], kd[i + 1])
                mods = self.convertMods(kd[i + 2])
                eventmanager.event(KEY_PRESS, KeyEvent(kd[i], code, mods))
                i = i + 3

            #######################
            #####* #   1A  KEYUP ?

            kd = myOgre.pumpKeyUps()
            i = 0
            while (i < len(kd)):
                #print kd
                code = self.keydict.get(kd[i + 1], kd[i + 1])
                mods = self.convertMods(kd[i + 2])
                eventmanager.event(KEY_RELEASE, KeyEvent(kd[i], code, mods))
                i = i + 3

            ##########################
            #####* #   02  MOUSEMOVE ?

            mm = myOgre.pumpMotions()
            i = 0
            while (i < len(mm)):
                #print mm
                btns = 0
                b1, b2, b3 = mm[i + 4]
                if b1:
                    btns |= 0x1
                if b2:
                    btns |= 0x2
                if b3:
                    btns |= 0x4
                eventmanager.event(
                    MOUSE_MOVE,
                    MouseMoveEvent(mm[i] * self.options.width,
                                   mm[i + 1] * self.options.height,
                                   mm[i + 2] * self.options.width,
                                   mm[i + 3] * self.options.height, mm[i],
                                   mm[i + 1], mm[i + 2], mm[i + 3], btns))
                i = i + 5

            ############################
            #####* #   03  MOUSEBUTTON ?

            mb = myOgre.pumpMouseButtons()
            i = 0
            while (i < len(mb)):
                #print mb
                x = mb[i + 2] * self.options.width
                y = mb[i + 3] * self.options.height
                x0 = mb[i + 2]
                y0 = mb[i + 3]
                # relative coords mb[i+4], mb[i+5] not used yet
                if (mb[i + 1] == 0):  # MOUSE PRESSED
                    if (mb[i] == 16):  # LEFT_MOUSE
                        eventname = LEFT_DOWN
                        evt = MouseButtonEvent(1, x, y, x0, y0)
                    elif (mb[i] == 64):  # MIDDLE_MOUSE
                        eventname = MIDDLE_DOWN
                        evt = MouseButtonEvent(2, x, y, x0, y0)
                    elif (mb[i] == 32):  # RIGHT_MOUSE
                        eventname = RIGHT_DOWN
                        evt = MouseButtonEvent(3, x, y, x0, y0)
                    else:
                        eventname = MOUSE_BUTTON_DOWN
                        evt = MouseButtonEvent(mb[i], x, y, x0, y0)  # ?<---
                    eventmanager.event(eventname, evt)
                elif (mb[i + 1] == 1):  # MOUSE RELEASED
                    if (mb[i] == 16):  # LEFT_MOUSE
                        eventname = LEFT_UP
                        evt = MouseButtonEvent(1, x, y, x0, y0)
                    elif (mb[i] == 64):  # MIDDLE_MOUSE
                        eventname = MIDDLE_UP
                        evt = MouseButtonEvent(2, x, y, x0, y0)
                        myOgre.changeBackgroundColor(255, 0, 0)
                    elif (mb[i] == 32):  # RIGHT_MOUSE
                        eventname = RIGHT_UP
                        evt = MouseButtonEvent(3, x, y, x0, y0)
                    else:
                        eventname = MOUSE_BUTTON_DOWN
                        evt = MouseButtonEvent(mb[i], x, y, x0, y0)  # ?<---
                    eventmanager.event(eventname, evt)
                i = i + 6

            #####* #       BREMSE & CO

            myOgre.clock(int(self.options.fps))
Exemplo n.º 16
0
    def onStepFrame(self):
        """Callback for the StepFrame event.
        """
        if self.substeps == 0 or not self.enabled:
            return

        if self.randomness != 0:
            self._addRandomness()

        T0 = time.time()

        if self.show_contacts:
            cmds.drawClear()

        # Remove dead body manipulators...
        self.body_manips = filter(lambda x: x() is not None, self.body_manips)

        #~ collision_receivers_present = ODE_COLLISION in eventManager().scene_connections

        self.stepTime = 0

        # Sim loop...
        subdt = getScene().timer().timestep / self.substeps
        for i in range(self.substeps):
            self.numcontacts = 0

            # Apply body manipulators
            for bmref in self.body_manips:
                bm = bmref()
                if bm is not None:
                    bm._apply()

            # Detect collisions and create contact joints
            self.space.collide(None, self.nearCallback)
            #print "#Contacts:",self.numcontacts

            # Simulation step
            t0 = time.time()
            if self.use_quick_step or self.numcontacts > 100:
                #~ print "quickStep"
                self.world.quickStep(subdt)
            else:
                #~ print "step"
                self.world.step(subdt)
            t1 = time.time()
            self.stepTime = t1 - t0

            # Remove all contact joints
            self.contactgroup.empty()

        # Update the world objects
        for body in self.bodies:
            if body.odebody != None and body.odebody.isEnabled():
                body.updateObj()

        # Update geoms
        for body in self.bodies:
            try:
                body.obj.geom.radius = body.odegeoms[0].geom.radius
            except:
                pass
            try:
                body.obj.geom.length = body.odegeoms[0].geom.length
            except:
                pass
            try:
                body.obj.geom.lx, body.obj.geom.ly, body.obj.geom.lz = body.odegeoms[
                    0].geom.lengths
            except:
                pass

        # Reset body manipulators
        for bmref in self.body_manips:
            bm = bmref()
            if bm is not None:
                bm._reset()

        T1 = time.time()
        self.stepFrameTime = T1 - T0
Exemplo n.º 17
0
    def action(self):
        # Display the scene using pygame...
        scene = getScene()
        timer = scene.timer()

        # Create a camera control component
        CameraControl(cam=self.cam, mode=self.navigation_mode)

        # Get options...
        fps = timer.fps
        self.width = self.options.width  # (width, height) may be changed by a VIDEORESIZE event
        self.height = self.options.height

        # Open a window...
        pygame.display.set_caption("OpenGL viewer")
        if self.stereo_mode == 2:
            pygame.display.gl_set_attribute(pygame.GL_STEREO, 1)
        self.flags = OPENGL | DOUBLEBUF | RESIZABLE  # flags will also be used for handling VIDEORESIZE
        if self.options.full_screen:
            self.flags |= FULLSCREEN
        srf = pygame.display.set_mode((self.width, self.height), self.flags)

        # Output OpenGL infos...
        if self.options.verbose:
            print("OpenGL information:")
            print("  Vendor  :", glGetString(GL_VENDOR))
            print("  Renderer:", glGetString(GL_RENDERER))
            print("  Version :", glGetString(GL_VERSION))

        # Check if stereo output is active...
        if self.stereo_mode == 2:
            if pygame.display.gl_get_attribute(pygame.GL_STEREO) == 0:
                raise RuntimeError(
                    "Stereo buffers not supported by this hardware.")

        # Try to get the native window handle
        # (this only works with pygame 1.6.2 and later)
        try:
            info = pygame.display.get_wm_info()
            hwnd = info["window"]
        except:
            hwnd = None

        # Open SpaceMouse/SpaceBall device...
        if self.spacedevice != None:
            if hwnd == None:
                if sys.platform == "win32" and self.options.verbose:
                    print(
                        "SpaceMouse/SpaceBall support is not available with the installed version"
                    )
                    print("of pygame. Please upgrade to v1.6.2 or later.")
            else:
                try:
                    self.spacedevice.open("viewer.py", hwnd)
                    self.spacedevice.setUIMode(True)
                    if self.options.verbose:
                        typ, btns, degs, beep, firmware = self.spacedevice.getDeviceInfo(
                        )
                        print("3D input device:", firmware)
                        print("%s: %d buttons, %d degrees of freedom" %
                              (typ, btns, degs))
                    pygame.event.set_allowed(SYSWMEVENT)
                except RuntimeError as e:
                    print("SpaceDevice:", e)
                    print("SpaceMouse/SpaceBall support is disabled.")
                    self.spacedevice = None

        # Open Wintab context
        if self.wintabcontext != None:
            if hwnd == None:
                self.wintabcontext = None
                if sys.platform == "win32" and self.options.verbose:
                    print(
                        "Tablet support is not available with the installed version of pygame."
                    )
                    print("Please upgrade to v1.6.2 or later.")
            else:
                self.wintabcontext.open(hwnd, True)
                pygame.event.set_allowed(SYSWMEVENT)

        # Event loop...
        self.running = True
        active = True
        clk = pygame.time.Clock()
        cnt = 0
        timer.startClock()
        while self.running:
            # Display the scene
            self.draw(self.cam, self.width, self.height)
            pygame.display.flip()

            # Handle events
            events = pygame.event.get()
            self.handleEvents(events)

            if self.wintabcontext != None:
                self.handleWintabEvents()

            if self.time_end != None and timer.time > self.time_end + 1E-10:
                active = False

            if active:
                if self.options.save != None:
                    self.saveScreenshot(srf)

                # Step time
                timer.step()

            # Sync
            clk.tick(fps)
            cnt += 1
Exemplo n.º 18
0
    def action(self):

        CameraControl(cam=self.cam, mode=self.navigation_mode)
	
	print "mmmmhh3"

        scene = getScene()
        timer = scene.timer()
        worldroot = scene.worldRoot()
        myOgre = OgreCore()
        self.ogrecore = myOgre
        #myOgre.setAmbient(0,0,0)

	# tell ogre which shadow mode to use
	print "mmmmhh4"
	myOgre.setupShadowMode(self.shadowmode,2048)
	#myOgre.setupShadowMode(0,512)

        myOgre.initialize(worldroot,
                          self.options.width,
                          self.options.height,
                          self.options.full_screen,
                          not self.options.no_shadow,
                          self.use_opengl,
                          r".\demosOgre\materials",
#                         self.materialpath,
                          self.options.stereo)

        # signature: cameraObject
        myOgre.setupData(self.cam, 0.1, 1000.0, self.cam.fov)

        # Set background color
        if scene.hasGlobal("background"):
            bg = scene.getGlobal("background")
            r = int(255*bg[0])
            g = int(255*bg[1])
            b = int(255*bg[2])
            myOgre.changeBackgroundColor(r, g, b)

        eventmanager = eventManager()

        running = 1
        while (running):

            ####* #        SIMULATE   
            
            timer.step()

            ####* #        RENDER ONE OGRE FRAME

            myOgre.renderTree()

            #####* #   **  GET EVENTS  
   
            ########################
            #####* #   01  KEYDOWN ?  
  
            kd = myOgre.pumpKeyDowns()
            i = 0
            while ( i<len(kd) ):
                # quit when ESC is pressed
                #print kd
                if (kd[i+1] == 1):
                    #myOgre.rebuildOgreTree(worldroot)
                    running = 0
                code = self.keydict.get(kd[i+1], kd[i+1])
                mods = self.convertMods( kd[i+2] )
                eventmanager.event( KEY_PRESS, KeyEvent(kd[i], code, mods) )
                i = i+3

            #######################
            #####* #   1A  KEYUP ?  
  
            kd = myOgre.pumpKeyUps()
            i = 0
            while ( i<len(kd) ):
                #print kd
                code = self.keydict.get(kd[i+1], kd[i+1])
                mods = self.convertMods( kd[i+2] )
                eventmanager.event( KEY_RELEASE, KeyEvent(kd[i], code, mods) )
                i = i+3

            ##########################
            #####* #   02  MOUSEMOVE ? 

            mm = myOgre.pumpMotions()
            i = 0
            while ( i<len(mm) ):
                #print mm
                btns = 0
                b1,b2,b3 = mm[i+4]
                if b1:
                    btns |= 0x1
                if b2:
                    btns |= 0x2
                if b3:
                    btns |= 0x4 
                eventmanager.event(MOUSE_MOVE, MouseMoveEvent(mm[i]*self.options.width, mm[i+1]*self.options.height, mm[i+2]*self.options.width, mm[i+3]*self.options.height, mm[i], mm[i+1], mm[i+2], mm[i+3], btns) )	
                i = i+5	

            ############################
            #####* #   03  MOUSEBUTTON ? 

            mb = myOgre.pumpMouseButtons()
            i = 0
            while ( i<len(mb) ):
                #print mb
                x = mb[i+2]*self.options.width
                y = mb[i+3]*self.options.height
                x0 = mb[i+2]
                y0 = mb[i+3]
                # relative coords mb[i+4], mb[i+5] not used yet
                if ( mb[i+1] == 0 ): # MOUSE PRESSED
                    if ( mb[i] == 16 ): # LEFT_MOUSE
                        eventname = LEFT_DOWN
                        evt = MouseButtonEvent(1, x, y, x0, y0)
                    elif ( mb[i] == 64 ): # MIDDLE_MOUSE
                        eventname = MIDDLE_DOWN
                        evt = MouseButtonEvent(2, x, y, x0, y0)
                    elif ( mb[i] == 32 ): # RIGHT_MOUSE
                        eventname = RIGHT_DOWN
                        evt = MouseButtonEvent(3, x, y, x0, y0)
                    else: 
                        eventname = MOUSE_BUTTON_DOWN
                        evt = MouseButtonEvent(mb[i], x, y, x0, y0) # ?<---
                    eventmanager.event(eventname, evt)
                elif ( mb[i+1] == 1 ): # MOUSE RELEASED
                    if ( mb[i] == 16 ): # LEFT_MOUSE
                        eventname = LEFT_UP
                        evt = MouseButtonEvent(1, x, y, x0, y0)
                    elif ( mb[i] == 64 ): # MIDDLE_MOUSE
                        eventname = MIDDLE_UP
                        evt = MouseButtonEvent(2, x, y, x0, y0)
			myOgre.changeBackgroundColor(255, 0, 0)
                    elif ( mb[i] == 32 ): # RIGHT_MOUSE
                        eventname = RIGHT_UP
                        evt = MouseButtonEvent(3, x, y, x0, y0)
                    else: 
                        eventname = MOUSE_BUTTON_DOWN
                        evt = MouseButtonEvent(mb[i], x, y, x0, y0) # ?<---
                    eventmanager.event(eventname, evt)
                i = i+6

            #####* #       BREMSE & CO 

            myOgre.clock(int(self.options.fps))    
Exemplo n.º 19
0
    def action(self):
        # Create a camera control component
        CameraControl(cam=self.cam, mode=self.navigation_mode)

        print "NAV MODE:       ", self.navigation_mode
        
        scene = getScene()
        timer = scene.timer()
        worldroot = scene.worldRoot()
        myOsg = OsgCore()
        self.osgcore = myOsg
        myOsg.initStuff(worldroot)
        myOsg.setupCamera(worldroot, self.cam, 0.1, 1000.0, self.cam.fov, self.options.width, self.options.height)
        running = True
        #abc = 600
	
        while(running):
            eventmanager = eventManager()
            # testing the time limit
            #abc -= 1
            #if (abc == 0):
            #    running = False            
            timer.step()
            myOsg.renderFrame()

            # KEYDOWN EVENTS #
            ##################
            
            kd = myOsg.pumpKeyDowns()
            i = 0
            while(i<len(kd)):
		#print kd # format char / int / int
                # quit when ESC is pressed
                code = self.keydict.get(kd[i+1], kd[i+1])
                if (code == KEY_ALT_LEFT):
                    print "alt left pressed"
                try:
                    key = unicode(chr(kd[i+1]))
                except:
                    key = ""                
                mods = self.convertMods(kd[i+2])
                eventmanager.event( KEY_PRESS, KeyEvent(key, code, mods) )
                if (kd[i+1] == 27):
                    print "bye bye"
                    #running = False
                i = i+3

            # KEYUP EVENTS #
            ##################
            
            kd = myOsg.pumpKeyUps()
            i = 0
            while(i<len(kd)):
		#print kd # format char / int / int
                # quit when ESC is pressed
                code = self.keydict.get(kd[i+1], kd[i+1])
                if (code == KEY_ALT_LEFT):
                    print "alt left released"                
                try:
                    key = unicode(chr(kd[i+1]))
                except:
                    key = ""                
                mods = self.convertMods(kd[i+2])
                eventmanager.event( KEY_RELEASE, KeyEvent(key, code, mods) )
                if (kd[i+1] == 27):
                    print "bye bye"
                    #running = False
                i = i+3                

            # MOUSE MOTION EVENTS #
            #######################

            mb = myOsg.pumpMotions()
            i = 0
            if ( len(mb) > 5 ): 
                #print mb
                #print self.cam.transform
                #print self.cam.transform.toList()
                x = mb[i]
                y = mb[i+1]
                dx = mb[i+2]
                dy = mb[i+3]
                btns = 0
                b1 = mb[i+4]
                b2 = mb[i+5]
                b3 = mb[i+6]
                if b1:
                    btns |= 0x1
                    #print "left mouse!"
                if b2:
                    btns |= 0x2
                    #print "middle mouse!"
                if b3:
                    btns |= 0x4
                    #print "right mouse!"
                #print "Motion X Y (ABS): ",x*((float)(self.options.width)), y*((float)(self.options.height))
                #print "Motion X Y (REEEEEL): ",dx*((float)(self.options.width)), dy*((float)(self.options.height))
                evt = MouseMoveEvent(x*((float)(self.options.width)), y*((float)(self.options.height)), dx*((float)(self.options.width)), dy*((float)(self.options.height)), x, y, dx, dy, btns)
                #evt = MouseMoveEvent(10, 10, 3, 3, 0.1, 0.1, 0.1, 0.1, 0x2)
                #print evt
                #print "MOUSE MOVE"
                eventmanager.event(MOUSE_MOVE, evt)

            # MOUSE BUTTON EVENTS #
            #######################

            mb = myOsg.pumpMouseDowns()
            i = 0
            while ( i<len(mb) ):
                print "mousebuttonevent"
                x = mb[i+2]*self.options.width
                y = mb[i+3]*self.options.height
                #print "X and Y: ", x, y
                x0 = mb[i+2]
                y0 = mb[i+3]
                # relative coords mb[i+4], mb[i+5] not used yet
                if ( mb[i+1] == 0 ): # MOUSE PRESSED
                    #print "mouse pressed"
                    if ( mb[i] == 1 ): # LEFT_MOUSE
                        print "left mouse down"
                        eventname = LEFT_DOWN
                        evt = MouseButtonEvent(1, x, y, x0, y0)
                    elif ( mb[i] == 2 ): # MIDDLE_MOUSE
                        eventname = MIDDLE_DOWN
                        evt = MouseButtonEvent(2, x, y, x0, y0)
                    elif ( mb[i] == 4 ): # RIGHT_MOUSE
                        eventname = RIGHT_DOWN
                        evt = MouseButtonEvent(3, x, y, x0, y0)
                    else: 
                        eventname = MOUSE_BUTTON_DOWN
                        evt = MouseButtonEvent(mb[i], x, y, x0, y0) # ?<---
                    eventmanager.event(eventname, evt)
                elif ( mb[i+1] == 1 ): # MOUSE RELEASED
                    #print "mouse released"
                    if ( mb[i] == 1 ): # LEFT_MOUSE
                        eventname = LEFT_UP
                        print "leftup"
                        evt = MouseButtonEvent(1, x, y, x0, y0)
                    elif ( mb[i] == 2 ): # MIDDLE_MOUSE
                        eventname = MIDDLE_UP
                        print "middleup"
                        evt = MouseButtonEvent(2, x, y, x0, y0)
                    elif ( mb[i] == 4 ): # RIGHT_MOUSE
                        eventname = RIGHT_UP
                        print "rightup"
                        evt = MouseButtonEvent(3, x, y, x0, y0)
                    else: 
                        eventname = MOUSE_BUTTON_UP
                        print "up"
                        evt = MouseButtonEvent(mb[i], x, y, x0, y0) # ?<---
                    eventmanager.event(eventname, evt)
                i = i+7                
Exemplo n.º 20
0
    def __init__(self):
        Tool.__init__(self, defaultoptionvar="VIEWER_DEFAULT_OPTIONS")

        self.pygame_joysticks = []
        self.cgkit_joysticks = []

        self.spacedevice = None
        self.enable_spacedevice = False  # Disable SpaceMouse for now

        self.wintabcontext = None
        self.enable_wintab = True

        if sys.platform != "win32":
            self.enable_spacedevice = False
            self.enable_wintab = False

        # The window width (this is initially taken from the options)
        self.width = None
        # The window height (this is initially taken from the options)
        self.height = None
        # The pygame display flags
        self.flags = None

        scene = getScene()
        scene.setGlobal("stereo", self.options.stereo)
        scene.setGlobal("polygonmode", self.options.polygon_mode)
        scene.setGlobal("navigationmode", self.options.navigation_mode)

        self.separate_specular_color = False
        self.draw_orientation = True

        self.keydict = {
            8: KEY_BACK,
            9: KEY_TAB,
            13: KEY_RETURN,
            27: KEY_ESCAPE,
            32: KEY_SPACE,
            276: KEY_LEFT,
            273: KEY_UP,
            275: KEY_RIGHT,
            274: KEY_DOWN,
            301: KEY_CAPSLOCK,
            304: KEY_SHIFT_LEFT,
            303: KEY_SHIFT_RIGHT,
            306: KEY_CONTROL_LEFT,
            305: KEY_CONTROL_RIGHT,
            308: KEY_ALT_LEFT,
            307: KEY_ALT_RIGHT,
            310: KEY_WINDOWS_LEFT,
            309: KEY_WINDOWS_RIGHT,
            319: KEY_WINDOWS_MENU,
            317: KEY_PRINT,
            302: KEY_SCROLL,
            19: KEY_PAUSE,
            277: KEY_INSERT,
            127: KEY_DELETE,
            278: KEY_HOME,
            279: KEY_END,
            280: KEY_PRIOR,
            281: KEY_NEXT,
            282: KEY_F1,
            283: KEY_F2,
            284: KEY_F3,
            285: KEY_F4,
            286: KEY_F5,
            287: KEY_F6,
            288: KEY_F7,
            289: KEY_F8,
            290: KEY_F9,
            291: KEY_F10,
            292: KEY_F11,
            293: KEY_F12,
            300: KEY_NUMLOCK,
            256: KEY_NUMPAD0,
            257: KEY_NUMPAD1,
            258: KEY_NUMPAD2,
            259: KEY_NUMPAD3,
            260: KEY_NUMPAD4,
            261: KEY_NUMPAD5,
            262: KEY_NUMPAD6,
            263: KEY_NUMPAD7,
            264: KEY_NUMPAD8,
            265: KEY_NUMPAD9,
            266: KEY_NUMPAD_DECIMAL,
            267: KEY_NUMPAD_DIVIDE,
            268: KEY_NUMPAD_MULTIPLY,
            269: KEY_NUMPAD_SUBTRACT,
            270: KEY_NUMPAD_ADD,
            271: KEY_NUMPAD_ENTER
        }
Exemplo n.º 21
0
    def init(self):

        # Initialize pygame
        passed, failed = pygame.init()
        if failed > 0:
            print("Warning: %d pygame modules couldn't be initialized" %
                  failed)

        # Initialize joysticks...
        numjoy = pygame.joystick.get_count()
        if self.options.verbose:
            print(numjoy, "joysticks available")

        self.pygame_joysticks = []
        self.cgkit_joysticks = []
        for id in range(numjoy):
            j = pygame.joystick.Joystick(id)
            j.init()
            self.pygame_joysticks.append(j)
            # Create a cgkit joystick object...
            id = j.get_id()
            name = j.get_name()
            numaxes = j.get_numaxes()
            numballs = j.get_numballs()
            numhats = j.get_numhats()
            numbuttons = j.get_numbuttons()
            cgj = Joystick(id=id,
                           name=name,
                           numaxes=numaxes,
                           numhats=numhats,
                           numballs=numballs,
                           numbuttons=numbuttons)
            getScene().setJoystick(cgj)
            # Initialize the values
            #        for i in range(numaxes):
            #            cgj.setAxis(i, j.get_axis(i))
            self.cgkit_joysticks.append(cgj)
            if self.options.verbose:
                print("Joystick #%d (%s):" % (id, name))
                print("  %d axes, %d balls, %d buttons, %d hats" %
                      (numaxes, numballs, numbuttons, numhats))

        if self.options.disable_spacedevice:
            self.enable_spacedevice = True  # temporarily invert the meaning of -X
#            self.enable_spacedevice = False
        if self.options.disable_wintab:
            self.enable_wintab = False

        # Initialize SpaceMouse/SpaceBall
        if self.enable_spacedevice and cgkit.spacedevice.available():
            try:
                self.spacedevice = cgkit.spacedevice.SpaceDevice()
            except RuntimeError as e:
                print("3DxWare exception:", e)
        else:
            if self.options.verbose and self.enable_spacedevice:
                print(
                    "SpaceMouse/SpaceBall module (spacedevice) not available")

        # Initialize Wintab context
        if self.enable_wintab and cgkit.wintab.available():
            if self.options.verbose:
                info = cgkit.wintab.info(WTI_INTERFACE)
                print('Wintab identification: "%s"' % info["WINTABID"])
                info = cgkit.wintab.info(WTI_DEVICES)
                print("Initializing %s..." % info["NAME"])

            self.wintabcontext = cgkit.wintab.Context()
            ctx = self.wintabcontext
            ctx.name = os.path.basename(sys.argv[0])
            ctx.options = 0

            # Compute the pktdata attribute...
            ncursors = cgkit.wintab.info(WTI_INTERFACE)["NCURSORS"]
            pktdata = 0
            for i in range(ncursors):
                info = cgkit.wintab.info(WTI_CURSORS + i)
                pd = info["PKTDATA"]
                if pd != None:
                    pktdata |= pd
            ctx.pktdata = pktdata
        else:
            if self.options.verbose and self.enable_wintab:
                print("No Wintab driver available")

        # Create renderer
        self.renderer = GLRenderInstance()
Exemplo n.º 22
0
    def onStepFrame(self):
        """Callback for the StepFrame event.
        """
        if self.substeps==0 or not self.enabled:
            return
            
        if self.randomness != 0:
            self._addRandomness()

        T0 = time.time()
    
        if self.show_contacts:
            cmds.drawClear()

        # Remove dead body manipulators...
        self.body_manips = filter(lambda x: x() is not None, self.body_manips)

        #~ collision_receivers_present = ODE_COLLISION in eventManager().scene_connections
            
        self.stepTime = 0
        
        # Sim loop...
        subdt = getScene().timer().timestep/self.substeps
        for i in range(self.substeps):
            self.numcontacts = 0
            
            
            # Apply body manipulators
            for bmref in self.body_manips:
                bm = bmref()
                if bm is not None:
                    bm._apply()
            
            # Detect collisions and create contact joints
            self.space.collide(None, self.nearCallback)
            #print "#Contacts:",self.numcontacts

            # Simulation step
            t0 = time.time()
            if self.use_quick_step or self.numcontacts > 100:
                #~ print "quickStep"
                self.world.quickStep(subdt)
            else:
                #~ print "step"
                self.world.step(subdt)
            t1 = time.time()
            self.stepTime = t1 - t0

            # Remove all contact joints
            self.contactgroup.empty()

            
        # Update the world objects
        for body in self.bodies:
            if body.odebody != None and body.odebody.isEnabled():
                body.updateObj()
        
        # Update geoms
        for body in self.bodies:
            try: body.obj.geom.radius = body.odegeoms[0].geom.radius
            except: pass
            try: body.obj.geom.length = body.odegeoms[0].geom.length
            except: pass
            try: body.obj.geom.lx, body.obj.geom.ly, body.obj.geom.lz = body.odegeoms[0].geom.lengths
            except: pass
                

        # Reset body manipulators
        for bmref in self.body_manips:
            bm = bmref()
            if bm is not None:
                bm._reset()

        T1 = time.time()
        self.stepFrameTime = T1 - T0