示例#1
0
 def pick(self, x, y, viewer):
     if viewer.getSceneData():
         if self.usePolytopeIntersector():
             picker = osgUtil.PolytopeIntersector(osgUtil.Intersector.WINDOW, x - 2.0, y - 2.0, x + 2.0, y + 2.0)
         else:
             picker = osgUtil.LineSegmentIntersector(osgUtil.Intersector.WINDOW, x, y)
         intersectionVisitor = osgUtil.IntersectionVisitor(picker)
         viewer.getCamera().accept(intersectionVisitor)
         if picker.containsIntersections():
             intersections = picker.getIntersections()
             
             # The PolytopeIntersector mis-calculates the eye distance for geometry nested under a transform, which is true for all UnitShapes.  (See the thread at http://www.mail-archive.com/[email protected]/msg29195.html for some discussion.)
             # Calculate the correct distance and re-sort.
             # This will probably still work correctly after that bug is fixed but will be inefficient.
             visibleHits = []
             eye, center, up = (osg.Vec3(), osg.Vec3(), osg.Vec3())
             viewer.getCamera().getViewMatrixAsLookAt(eye, center, up)
             eye = (eye.x(), eye.y(), eye.z())
             for i in range(0, len(intersections)):
                 intersection = intersections[i]
                 for j in range(0, len(intersection.nodePath)):
                     node = intersection.nodePath[j]
                     geode = osg.NodeToGeode(node)
                     if geode != None:
                         visibleID = int(geode.getName())
                         visible = self._display.visibleWithId(visibleID)
                         if geode.getOrCreateStateSet().getAttribute(osg.StateAttribute.DEPTH):
                             # If a geode has this attribute set then (currently) it is being rendered in front of all other nodes.  Simulate this here by placing the geode right at the eye.
                             # If depths other than the default or osg.Depth.ALWAYS are used in the future then this check will need to be modified.
                             eyeDistance = 0.0
                         else:
                             intersectionPoint = intersection.localIntersectionPoint
                             if isinstance(visible.shape(), UnitShape):
                                 position = visible.worldPosition()
                                 size = visible.worldSize()
                                 intersectionPoint = (position[0] + size[0] * intersectionPoint.x(), position[1] + size[1] * intersectionPoint.y(), position[2] + size[2] * intersectionPoint.z())
                             eyeDistance = (intersectionPoint[0] - eye[0]) ** 2 + (intersectionPoint[1] - eye[1]) ** 2 + (intersectionPoint[2] - eye[2]) ** 2
                         visibleHits += [(eyeDistance, visible)]
             visibleHits.sort()
             
             # Loop through all of the hits to find the "deepest" one in the sense of the visible hierarchy.  For example, a neuron in a region will be picked instead of the region even though the region hit is closer.
             if self._display.useGhosts():
                 # Make a first pass only picking non-ghosted items.
                 # TODO: this could be done with node masks...
                 deepestVisible = None
                 for distance_, visible in visibleHits:
                     if (visible in self._display.highlightedVisibles or visible in self._display.animatedVisibles) and (deepestVisible is None or deepestVisible in visible.ancestors()):
                         deepestVisible = visible
                 if deepestVisible is not None:
                     self._display.selectVisibles([deepestVisible], self._display.selectionShouldExtend, self._display.findShortestPath, fromclick=True)
                     return True
             deepestVisible = None
             for distance_, visible in visibleHits:
                 if deepestVisible is None or deepestVisible in visible.ancestors():
                     deepestVisible = visible
             self._display.selectVisibles([deepestVisible], self._display.selectionShouldExtend, self._display.findShortestPath, fromclick=True)
         else:
             self._display.selectVisibles([])
     return True
示例#2
0
def createTesselatedBox(nsplit, size):
    geometry = osgAnimation.RigGeometry()
    vertices = osg.Vec3Array()
    colors = osg.Vec3Array()
    geometry.setVertexArray(vertices)
    geometry.setColorArray(colors)
    geometry.setColorBinding(osg.Geometry.BIND_PER_VERTEX)

    step = size / nsplit
    s = 0.5 / 4.0
    for i in range(nsplit):
        x = -1 + i * step
        vertices.push_back(osg.Vec3(x, s, s))
        vertices.push_back(osg.Vec3(x, -s, s))
        vertices.push_back(osg.Vec3(x, -s, -s))
        vertices.push_back(osg.Vec3(x, s, -s))
        c = osg.Vec3(0, 0, 0)
        c[i % 3] = 1
        colors.push_back(c)
        colors.push_back(c)
        colors.push_back(c)
        colors.push_back(c)

    faces = osg.DrawElementsUInt(osg.PrimitiveSet.TRIANGLES, 0)
    for i in range(nsplit - 1):
        base = i * 4
        faces.push_back(base)
        faces.push_back(base + 1)
        faces.push_back(base + 4)
        faces.push_back(base + 1)
        faces.push_back(base + 5)
        faces.push_back(base + 4)

        faces.push_back(base + 3)
        faces.push_back(base)
        faces.push_back(base + 4)
        faces.push_back(base + 7)
        faces.push_back(base + 3)
        faces.push_back(base + 4)

        faces.push_back(base + 5)
        faces.push_back(base + 1)
        faces.push_back(base + 2)
        faces.push_back(base + 2)
        faces.push_back(base + 6)
        faces.push_back(base + 5)

        faces.push_back(base + 2)
        faces.push_back(base + 3)
        faces.push_back(base + 7)
        faces.push_back(base + 6)
        faces.push_back(base + 2)
        faces.push_back(base + 7)

    geometry.addPrimitiveSet(faces)
    geometry.setUseDisplayList(False)
    return geometry
示例#3
0
 def quad_create(self, texture):
     stateset = osg.StateSet()
     stateset.setTextureAttributeAndModes(0, texture)
     corner = osg.Vec3(-self.aspect_ratio, -1.0, 0)
     width = osg.Vec3(2 * self.aspect_ratio, 0, 0)
     height = osg.Vec3(0, 2 * 1.0, 0)
     geom = osg.createTexturedQuadGeometry(corner, width, height, 0.0, 0.0,
                                           1.0, 1.0)
     geom.setStateSet(stateset)
     geode = osg.Geode()
     geode.addDrawable(geom)
     return geode
示例#4
0
 def startDragPanOrPick(self, eventAdaptor, viewer):
     eventWasHandled = False
     if viewer.getSceneData():
         # TODO: This is a major hack.  The intersection code below always picks the composite dragger, even if it isn't being rendered.  So we remove the inactive dragger while picking.
         # TODO: Figure out how to make the intersection code honor the LOD and get rid of the DraggerCullCallback class.
         if self._display.draggerLOD is not None:
             if self._display.activeDragger == self._display.simpleDragger:
                 self._display.draggerLOD.removeChild(
                     self._display.compositeDragger)
             if self._display.activeDragger == self._display.compositeDragger:
                 self._display.draggerLOD.removeChild(
                     self._display.simpleDragger)
         x, y = eventAdaptor.getX(), eventAdaptor.getY()
         if self.usePolytopeIntersector():
             picker = osgUtil.PolytopeIntersector(
                 osgUtil.Intersector.WINDOW, x - 2.0, y - 2.0, x + 2.0,
                 y + 2.0)
         else:
             picker = osgUtil.LineSegmentIntersector(
                 osgUtil.Intersector.WINDOW, x, y)
         intersectionVisitor = osgUtil.IntersectionVisitor(picker)
         intersectionVisitor.setTraversalMode(
             osg.NodeVisitor.TRAVERSE_ACTIVE_CHILDREN)
         viewer.getCamera().accept(intersectionVisitor)
         if picker.containsIntersections():
             # Add all intersections from the first dragger hit onward to the pointer info.  This allows dragging of nested regions.
             self.pointerInfo.setCamera(viewer.getCamera())
             self.pointerInfo.setMousePosition(eventAdaptor.getX(),
                                               eventAdaptor.getY())
             intersections = picker.getIntersections()
             for i in range(0, len(intersections)):
                 intersection = intersections[i]
                 for j in range(0, len(intersection.nodePath)):
                     node = intersection.nodePath[j]
                     if self.dragger is None:
                         self.dragger = osgManipulator.NodeToDragger(node)
                     if self.dragger is not None:
                         localPoint = intersection.localIntersectionPoint  # have to do stupid conversion from Vec3d to Vec3
                         if self.usePolytopeIntersector():
                             self.pointerInfo.addIntersection(
                                 intersection.nodePath,
                                 osg.Vec3(localPoint.x(), localPoint.y(),
                                          localPoint.z()))
                         else:
                             self.pointerInfo.addIntersection(
                                 intersection.nodePath,
                                 osg.Vec3d(localPoint.x(), localPoint.y(),
                                           localPoint.z()))
             if self.dragger is not None:
                 self.dragger.handle(self.pointerInfo, eventAdaptor, viewer)
                 eventWasHandled = True
         if self._display.draggerLOD is not None:
             if self._display.activeDragger == self._display.simpleDragger:
                 self._display.draggerLOD.addChild(
                     self._display.compositeDragger)
             if self._display.activeDragger == self._display.compositeDragger:
                 self._display.draggerLOD.addChild(
                     self._display.simpleDragger)
     return eventWasHandled
示例#5
0
 def __init__(self,
              axis=osg.Vec3(0.0, 0.0, 1.0),
              startangle=0.0,
              speed=0.001):
     self._angle = startangle
     self._axis = axis
     self._quat = osg.Quat()
     self._speed = speed
     osg.NodeCallback.__init__(self)
示例#6
0
def createAxis():
    geode = osg.Geode()
    geometry = osg.Geometry()

    vertices = osg.Vec3Array()
    vertices.push_back(osg.Vec3(0.0, 0.0, 0.0))
    vertices.push_back(osg.Vec3(1.0, 0.0, 0.0))
    vertices.push_back(osg.Vec3(0.0, 0.0, 0.0))
    vertices.push_back(osg.Vec3(0.0, 1.0, 0.0))
    vertices.push_back(osg.Vec3(0.0, 0.0, 0.0))
    vertices.push_back(osg.Vec3(0.0, 0.0, 1.0))
    geometry.setVertexArray(vertices)

    colors = osg.Vec4Array()
    colors.push_back(osg.Vec4(1.0, 0.0, 0.0, 1.0))
    colors.push_back(osg.Vec4(1.0, 0.0, 0.0, 1.0))
    colors.push_back(osg.Vec4(0.0, 1.0, 0.0, 1.0))
    colors.push_back(osg.Vec4(0.0, 1.0, 0.0, 1.0))
    colors.push_back(osg.Vec4(0.0, 0.0, 1.0, 1.0))
    colors.push_back(osg.Vec4(0.0, 0.0, 1.0, 1.0))
    geometry.setColorArray(colors)

    geometry.setColorBinding(osg.Geometry.BIND_PER_VERTEX)
    geometry.addPrimitiveSet(osg.DrawArrays(osg.PrimitiveSet.LINES, 0, 6))

    geode.addDrawable(geometry)
    return geode
示例#7
0
def createPreRenderSubGraph(subgraph, tex_width, tex_height, renderImplementation, \
                                                useImage, useTextureRectangle, useHDR, \
                                                samples, colorSamples):
    if not subgraph:
        return 0

    # create a group to contain the flag and the pre rendering camera.
    parent = osg.Group()

    #texture to render to and to use for rendering of flag.
    texture = 0
    if (useTextureRectangle):
        textureRect = osg.TextureRectangle()
        textureRect.setTextureSize(tex_width, tex_height)
        textureRect.setInternalFormat(osg.GL_RGBA)
        textureRect.setFilter(osg.Texture2D.MIN_FILTER, osg.Texture2D.LINEAR)
        textureRect.setFilter(osg.Texture2D.MAG_FILTER, osg.Texture2D.LINEAR)
        texture = textureRect
    else:
        texture2D = osg.Texture2D()
        texture2D.setTextureSize(tex_width, tex_height)
        texture2D.setInternalFormat(osg.GL_RGBA)
        texture2D.setFilter(osg.Texture2D.MIN_FILTER, osg.Texture2D.LINEAR)
        texture2D.setFilter(osg.Texture2D.MAG_FILTER, osg.Texture2D.LINEAR)
        texture = texture2D

    if useHDR:
        texture.setInternalFormat(osg.GL_RGBA16F_ARB)
        texture.setSourceFormat(osg.GL_RGBA)
        texture.setSourceType(osg.GL_FLOAT)

    #first create the geometry of the flag of which to view.

    if True:
        # create the to visualize.
        polyGeom = osg.Geometry()

        polyGeom.setName("PolyGeom")

        polyGeom.setDataVariance(osg.Object.DYNAMIC)
        polyGeom.setSupportsDisplayList(False)

        origin = osg.Vec3(0.0, 0.0, 0.0)
        xAxis = osg.Vec3(1.0, 0.0, 0.0)
        yAxis = osg.Vec3(0.0, 0.0, 1.0)
        zAxis = osg.Vec3(0.0, -1.0, 0.0)
        height = 100.0
        width = 200.0
        noSteps = 20

        vertices = osg.Vec3Array()
        bottom = osg.Vec3(origin[0], origin[1], origin[2])
        top = osg.Vec3(origin[0], origin[1], origin[2])
        top[2] += height
        dv = xAxis * (width / (float(noSteps - 1)))

        texcoords = osg.Vec2Array()

        # note, when we use TextureRectangle we have to scale the tex coords up to compensate.
        bottom_texcoord = osg.Vec2(0.0, 0.0)

        if useTextureRectangle:
            ltex_height = tex_height
            ltex_width = tex_width
        else:
            ltex_height = 1.0
            ltex_width = 1.0

        top_texcoord = osg.Vec2(0.0, ltex_height)
        dv_texcoord = osg.Vec2(ltex_width / float((noSteps - 1)), 0.0)

        for i in range(noSteps):
            vertices.push_back(top)
            vertices.push_back(bottom)
            top += dv
            bottom += dv

            texcoords.push_back(top_texcoord)
            texcoords.push_back(bottom_texcoord)
            top_texcoord += dv_texcoord
            bottom_texcoord += dv_texcoord

        # pass the created vertex array to the points geometry object.
        polyGeom.setVertexArray(vertices)

        polyGeom.setTexCoordArray(0, texcoords)

        colors = osg.Vec4Array()
        colors.push_back(osg.Vec4(1.0, 1.0, 1.0, 1.0))
        polyGeom.setColorArray(colors)
        polyGeom.setColorBinding(osg.Geometry.BIND_OVERALL)

        polyGeom.addPrimitiveSet(
            osg.DrawArrays(osg.PrimitiveSet.QUAD_STRIP, 0, vertices.size()))

        # new we need to add the texture to the Drawable, we do so by creating a
        # StateSet to contain the Texture StateAttribute.
        stateset = osg.StateSet()

        stateset.setTextureAttributeAndModes(0, texture, osg.StateAttribute.ON)

        polyGeom.setStateSet(stateset)

        #changes to the geometry
        polyGeom.setUpdateCallback(
            MyGeometryCallback(origin, xAxis, yAxis, zAxis, 1.0, 1.0 / width,
                               0.2).__disown__())

        geode = osg.Geode()
        geode.addDrawable(polyGeom)

        parent.addChild(geode)

    # then create the camera node to do the render to texture
    if True:
        camera = osg.Camera()

        # set up the background color and clear mask.
        camera.setClearColor(osg.Vec4(0.1, 0.1, 0.3, 1.0))
        camera.setClearMask(osg.GL_COLOR_BUFFER_BIT | osg.GL_DEPTH_BUFFER_BIT)

        bs = subgraph.getBound()
        if not bs.valid():
            return subgraph

        znear = 1.0 * bs.radius()
        zfar = 3.0 * bs.radius()

        # 2:1 aspect ratio as per flag geometry below.
        proj_top = 0.25 * znear
        proj_right = 0.5 * znear

        znear *= 0.9
        zfar *= 1.1

        # set up projection.
        camera.setProjectionMatrixAsFrustum(-proj_right, proj_right, -proj_top,
                                            proj_top, znear, zfar)

        # set view
        camera.setReferenceFrame(osg.Transform.ABSOLUTE_RF)
        camera.setViewMatrixAsLookAt(osg.Vec3d(bs.center())-osg.Vec3d(0.0,2.0,0.0)*bs.radius(), \
                                                          osg.Vec3d(bs.center()),\
                                                        osg.Vec3d(0.0,0.0,1.0))

        # set viewport
        camera.setViewport(0, 0, tex_width, tex_height)

        # set the camera to render before the main camera.
        camera.setRenderOrder(osg.Camera.PRE_RENDER)

        # tell the camera to use OpenGL frame buffer object where supported.
        camera.setRenderTargetImplementation(renderImplementation)

        if useImage:
            image = osg.Image()
            #image.allocateImage(tex_width, tex_height, 1, GL_RGBA, GL_UNSIGNED_BYTE);
            image.allocateImage(tex_width, tex_height, 1, osg.GL_RGBA,
                                osg.GL_FLOAT)

            # attach the image so its copied on each frame.
            camera.attach(osg.Camera.COLOR_BUFFER, image, samples,
                          colorSamples)

            camera.setPostDrawCallback(MyCameraPostDrawCallback(image))

            # Rather than attach the texture directly to illustrate the texture's ability to
            # detect an image update and to subload the image onto the texture.  You needn't
            # do this when using an Image for copying to, as a separate camera.attach(..)
            # would suffice as well, but we'll do it the long way round here just for demonstration
            # purposes (long way round meaning we'll need to copy image to main memory, then
            # copy it back to the graphics card to the texture in one frame).
            # The long way round allows us to manually modify the copied image via the callback
            # and then let this modified image by reloaded back.
            texture.setImage(0, image)

        else:
            # attach the texture and use it as the color buffer.
            camera.attach(osg.Camera.COLOR_BUFFER, texture, 0, 0, False,
                          samples, colorSamples)

        # add subgraph to render
        camera.addChild(subgraph)

        parent.addChild(camera)

    return parent
示例#8
0
import ctypes
import osgDB, osgViewer, osg, osgGA, osgAnimation

floatKeys = osgAnimation.FloatKeyframeContainer()
key0 = osgAnimation.FloatKeyframe(0.0, 1.0)
floatKeys.push_back(key0)

vec3Keys = osgAnimation.Vec3KeyframeContainer()
key0 = osgAnimation.Vec3Keyframe(0.0, osg.Vec3(1, 2, 3))
vec3Keys.push_back(key0)

vec4Keys = osgAnimation.Vec4KeyframeContainer()
key0 = osgAnimation.Vec4Keyframe(0.0, osg.Vec4(1, 2, 3, 4))
vec4Keys.push_back(key0)
示例#9
0
import ctypes
import osgDB, osgViewer, osg
group = osg.Group()
image = osgDB.readImageFile(
    "/home/trigrou/Pictures/backgrounds/games/Another_World_by_Orioto.jpg")
loadedModel = osg.Group()

corner = osg.Vec3(0, 0, 0)
width = osg.Vec3(1, 0, 0)
height = osg.Vec3(0, 1, 0)
geom = osg.createTexturedQuadGeometry(corner, width, height, 0.0, 0.0, 1.0,
                                      1.0)
geom.getOrCreateStateSet().setTextureAttributeAndModes(0, osg.Texture2D(image))
geom.getOrCreateStateSet().setTextureAttributeAndModes(
    1,
    osg.Texture2D(
        osgDB.readImageFile(
            "/home/trigrou/Pictures/backgrounds/games/Big_Blue_by_Orioto.jpg"))
)

vertProg = """
void main()
	{	
		gl_Position = ftransform();
                gl_TexCoord[0] = gl_TextureMatrix[0] * gl_MultiTexCoord0;
	}
"""
fragProg = """
uniform float test;
uniform int index;
uniform sampler2D tex0;
示例#10
0
def main():

    #arguments = osg.ArgumentParses(len(sys.argv),sys.argv)
    viewer = osgViewer.Viewer()  #arguments)

    viewer.setCameraManipulator(osgGA.TrackballManipulator())

    skelroot = osgAnimation.Skeleton()
    skelroot.setDefaultUpdateCallback()
    root = osgAnimation.Bone()
    root.setBindMatrixInBoneSpace(osg.Matrixd_identity())
    root.setBindMatrixInBoneSpace(osg.Matrixd_translate(-1, 0, 0))
    root.setName("root")
    root.setDefaultUpdateCallback()

    right0 = osgAnimation.Bone()
    right0.setBindMatrixInBoneSpace(osg.Matrixd_translate(1, 0, 0))
    right0.setName("right0")
    right0.setDefaultUpdateCallback("right0")

    right1 = osgAnimation.Bone()
    right1.setBindMatrixInBoneSpace(osg.Matrixd_translate(1, 0, 0))
    right1.setName("right1")
    right1.setDefaultUpdateCallback("right1")

    root.addChild(right0)
    right0.addChild(right1)
    skelroot.addChild(root)

    scene = osg.Group()
    manager = osgAnimation.BasicAnimationManager()
    scene.setUpdateCallback(manager)

    anim = osgAnimation.Animation()
    keys0 = osgAnimation.QuatKeyframeContainer()
    keys1 = osgAnimation.QuatKeyframeContainer()
    pKeys0 = int(keys0.this)
    pKeys1 = int(keys1.this)
    rotate = osg.Quat()
    rotate.makeRotate(PI_2, osg.Vec3(0, 0, 1))
    keys0.push_back(osgAnimation.QuatKeyframe(0, osg.Quat(0, 0, 0, 1)))
    keys0.push_back(osgAnimation.QuatKeyframe(3, rotate))
    keys0.push_back(osgAnimation.QuatKeyframe(6, rotate))
    keys1.push_back(osgAnimation.QuatKeyframe(0, osg.Quat(0, 0, 0, 1)))
    keys1.push_back(osgAnimation.QuatKeyframe(3, osg.Quat(0, 0, 0, 1)))
    keys1.push_back(osgAnimation.QuatKeyframe(6, rotate))

    sampler0 = osgAnimation.QuatSphericalLinearSampler()
    sampler0.setKeyframeContainer(keys0)
    channel0 = osgAnimation.QuatSphericalLinearChannel(sampler0)
    channel0.setName("quaternion")
    channel0.setTargetName("right0")
    anim.addChannel(channel0)
    sampler1 = osgAnimation.QuatSphericalLinearSampler()
    sampler1.setKeyframeContainer(keys1)
    channel1 = osgAnimation.QuatSphericalLinearChannel(sampler1)
    channel1.setName("quaternion")
    channel1.setTargetName("right1")
    anim.addChannel(channel1)
    manager.registerAnimation(anim)
    manager.buildTargetReference()

    # let's start !
    manager.playAnimation(anim)

    # we will use local data from the skeleton
    rootTransform = osg.MatrixTransform()
    rootTransform.setMatrix(osg.Matrixd_rotate(PI_2, osg.Vec3(1, 0, 0)))
    right0.addChild(createAxis())
    right0.setDataVariance(osg.Object.DYNAMIC)
    right1.addChild(createAxis())
    right1.setDataVariance(osg.Object.DYNAMIC)
    trueroot = osg.MatrixTransform()
    trueroot.setMatrix(osg.Matrixd(root.getMatrixInBoneSpace()))
    trueroot.addChild(createAxis())
    trueroot.addChild(skelroot)
    trueroot.setDataVariance(osg.Object.DYNAMIC)
    rootTransform.addChild(trueroot)
    scene.addChild(rootTransform)

    geom = createTesselatedBox(4, 4.0)
    geode = osg.Geode()
    geode.addDrawable(geom)
    skelroot.addChild(geode)
    src = geom.getVertexArray().asVec3Array()
    geom.getOrCreateStateSet().setMode(osg.GL_LIGHTING, False)
    geom.setDataVariance(osg.Object.DYNAMIC)

    initVertexMap(root, right0, right1, geom, src)

    #let's run !
    viewer.setSceneData(scene)
    viewer.realize()

    while not viewer.done():
        viewer.frame()
示例#11
0
import osg
import osgDB
import osgGA
import osgViewer

# create a root node
node = osg.Group()

# Line Geometry
lineGeode = osg.Geode()
lineGeometry = osg.Geometry()
lineGeode.addDrawable(lineGeometry)
lineStateSet = lineGeode.getOrCreateStateSet()

lineVertices = osg.Vec3Array()
lineVertices.push_back(osg.Vec3(-10, 10, 0))
lineVertices.push_back(osg.Vec3(-10, -10, 0))
lineGeometry.setVertexArray(lineVertices)

lineBase = osg.DrawElementsUInt(osg.PrimitiveSet.LINES, 0)
lineBase.push_back(0)
lineBase.push_back(1)
lineGeometry.addPrimitiveSet(lineBase)

node.addChild(lineGeode)

# Pyramid geometry, following tutorial
pyramidGeode = osg.Geode()
pyramidGeometry = osg.Geometry()
pyramidGeode.addDrawable(pyramidGeometry)
pyramidStateSet = pyramidGeode.getOrCreateStateSet()