官术网_书友最值得收藏!

Generating geometry at runtime

In some cases, Panda3D's model loading capabilities might not be enough for your needs. Maybe you want to procedurally generate new geometry at runtime or maybe you decided to drop the native file model file format of Panda3D in favor of your own custom data file layout. For all these cases where you need to glue together vertices by hand in order to form a model, the engine provides an API that you will learn about in this recipe.

Getting ready

As a prerequisite to the following steps, please create a new project as described in the recipe Setting up the game structure. This recipe can be found in the Chapter 1.

You will also need a texture image. Preferably it should be rectangular and in the best case be in a 2n format (64x64, 128x128, 256x256, and so on.). This recipe will use a crate texture in PNG format.

Lastly, add a directory called textures to your project and be sure it is in Panda3D's search path. This works analogous to what you did for the models and sounds directories.

How to do it...

Follow these steps to learn how to create geometry on the fly:

  1. Copy your texture image to the textures directory. Name it crate.png.
  2. Open Application.py. Insert the following code:
    from direct.showbase.ShowBase import ShowBase
    from panda3d.core import *
    
    vertices = [Vec3(1, 0, 1), Vec3(-1, 0, 1), Vec3(-1, 0, -1), Vec3(1, 0, -1)]
    texcoords = [Vec2(1, 1), Vec2(0, 1), Vec2(0, 0), Vec2(1, 0)]
    
    class Application(ShowBase):
        def __init__(self):
            ShowBase.__init__(self)
    
            format = GeomVertexFormat.getV3t2()
            geomData = GeomVertexData("box", format, Geom.UHStatic)
            vertexWriter = GeomVertexWriter(geomData, "vertex")
            uvWriter = GeomVertexWriter(geomData, "texcoord")
    
            for pos, tex in zip(vertices, texcoords):
                vertexWriter.addData3f(pos)
                uvWriter.addData2f(tex)
    
            triangles = GeomTriangles(Geom.UHStatic)
            triangles.addVertices(0, 1, 2)
            triangles.closePrimitive()
            triangles.addVertices(2, 3, 0)
            triangles.closePrimitive()
    
            geom = Geom(geomData)
            geom.addPrimitive(triangles)
            node = GeomNode("box")
            node.addGeom(geom)
            box = render.attachNewNode(node)
            texture = loader.loadTexture("crate.png")
            box.setTexture(texture)
    
            self.cam.setPos(0, -5, 0)
  3. Start the program. A quad with your texture on it should be rendered to the Panda3D window:

How it works...

Let's take a look at what this code is doing! We begin by creating a format descriptor for one of Panda3D's built in vertex data layouts. There are several of these layouts, which also can be completely customized, which describe what kind of data will be stored for each point in space that forms the mesh. In this particular case, we are using the getV3t2() method to get a descriptor for a vertex layout that stores the vertex position in space using three floating point values and the texture coordinate using two float values.

We then move on to create a GeomVertexData object, which uses the format we just requested. We also pass the Geom.UHStatic flag, which signals the underlying rendering systems that the vertex data will not change, which allows them to enable some optimizations. Additionally, we create two GeomVertexWriter objects—one for writing to the "vertex" channel, which stores the positions of the points that form the mesh, and the other one for writing to the "texcoord" channel of the point data we are adding to geomData in the loop that follows.

What we have so far is a cloud of seemingly random points—at least to the engine. To correct this issue, we need to connect the points to form primitives, which in this case are triangles. We create a new instance of GeomTriangles, using the Geom.UHStatic flag again to hint that the primitives will not be changed after they are defined. Then we create two triangles by passing indices to the proper points in the vertices list. After each triangle, we need to call the closePrimitive() method to mark the primitive as complete and start a new one.

At this point we have a collection of points in space, stored in a GeomVertexData object and a GeomTriangles primitive that holds the information necessary to connect the dots and form a mesh. To get the model to the screen, we need to create a new Geom, and add the point data and the triangle primitives. Because a model can in fact consist of multiple Geom objects, which also can't be added directly to the scene graph, we add it to a GeomNode. Finally, we attach the GeomNode to the scene graph, load and apply the texture and set the camera a bit back to be able to see our creation.

There's more...

There's a lot more to say about Panda3D's procedural geometry feature than what you just saw, so take your time and keep on reading to discover what else you can do to generate geometry at runtime.

Built in vertex formats

You already saw the built in GeomVertexFormat.getV3t2() format, but there are several more ready to use formats available:

  • getV3(): Vertices store position only
  • getV3c4(): Vertex position and a RGBA color value
  • getV3c4t2(): Position, color, and texture coordinates
  • getV3n3(): Position and normal vector
  • getV3n3c4(): Position, normal, and RGBA color
  • getV3n3c4t2(): This is the most extensive format. Contains position, normal, color, and texture coordinates
  • getV3n3t2(): Position, normal vector, and texture coordinates.

There's also a packed color format, which you can use by replacing c4 in the previous methods with cp. In this format, colors are stored into one 32-bit integer value. The best way to define color values for this format is in hexadecimal, because it lets you easily recognize the RGBA components of the color. For example, the value 0xFF0000FF is full red.

Custom vertex formats

Apart from the built-in vertex formats, Panda3D allows you to be much more flexible by defining your own custom formats. The key parts to this are the GeomVertexArrayFormat and GeomVertexFormat classes, which are used in the following way:

arrayFmt = GeomVertexArrayFormat()
arrayFmt.addColumn(InternalName.make("normal"), 3, Geom.NTFloat32, Geom.CVector)
fmt = GeomVertexFormat()
fmt.addArray(arrayFmt)
fmt = GeomVertexFormat.registerFormat(fmt)

In the beginning, you need to describe your vertex array data layout by adding columns. The first parameter is the channel that Panda3D is going to use the data for. Very commonly used channels are "vertex", "color", "normal", "texcoord", "tangent", and "binormal".

The second and third parameters are the number of components and data type the channel is using. In this sample, the normal data is composed out of three 32-bit floating point values. Legal values for the third parameter include NTFloat32, NTUint*, where * is one of 8, 16, or 32, describing an unsigned integer of the according bit width as well as NTPackedDcba and NTPackedDabc, used for packed index and color data.

The third parameter influences how the data is going to be treated internally—for example, if and how it will be transformed if a matrix is applied to the data in the column. Possible values include:

  • CPoint: Point data in 3D space, most often used for the "vertex" channel.
  • CVector: A vector giving a direction in space. Use this for normals, tangents, and binormals.
  • CTexcoord: The data in the column contains the coordinates of texture sample points.
  • CColor: The data is to be treated as color values.
  • CIndex: The column contains table indices.
  • COther: Arbitrary data values.

Points and texture coordinates are transformed as points, resulting in new positions if they are involved in a matrix multiplication. Vectors of course are following different rules when being transformed, because they describe directions, not positions! It would go too far to go into the details here, but lots of material on vector math and linear algebra are freely available on Wikipedia and other websites.

Primitive types

Panda3D supports all the standard primitive types commonly known in computer graphics: Triangles, triangle strips, triangle fans, lines, line strips, and points. The according classes used to describe these primitives are GeomTriangles, GeomTristrips, GeomTrifans, GeomLines, GeomLinestrips, and GeomPoints.

See also

Loading models and actors, Modifying the scene graph.

主站蜘蛛池模板: 东兰县| 扎鲁特旗| 鄂伦春自治旗| 新沂市| 芦山县| 前郭尔| 禄劝| 东台市| 溧阳市| 双鸭山市| 兴化市| 舒城县| 济宁市| 邵武市| 湖州市| 湖州市| 沽源县| 体育| 中西区| 阿荣旗| 延寿县| 怀安县| 武威市| 乌拉特中旗| 霞浦县| 舒兰市| 荃湾区| 郯城县| 维西| 阜南县| 金阳县| 平泉县| 成武县| 博湖县| 东至县| 天门市| 修文县| 广平县| 临沧市| 西盟| 新平|