当前位置: 首页>>代码示例>>Python>>正文


Python core.PNMImage类代码示例

本文整理汇总了Python中panda3d.core.PNMImage的典型用法代码示例。如果您正苦于以下问题:Python PNMImage类的具体用法?Python PNMImage怎么用?Python PNMImage使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了PNMImage类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __init__

    def __init__(self):
        load_prc_file_data("", """
            textures-power-2 none
            window-type offscreen
            win-size 100 100
            gl-coordinate-system default
            notify-level-display error
            print-pipe-types #f
        """)

        ShowBase.__init__(self)

        dest_tex = Texture()
        dest_tex.setup_2d_texture(2048, 2048, Texture.T_unsigned_byte, Texture.F_rgba8)
        cshader = Shader.load_compute(Shader.SL_GLSL, "grain.compute.glsl")
        node = NodePath("")
        node.set_shader(cshader)
        node.set_shader_input("DestTex", dest_tex)
        attr = node.get_attrib(ShaderAttrib)
        self.graphicsEngine.dispatch_compute(
            (2048 // 16, 2048 // 16, 1), attr, self.win.get_gsg())

        base.graphicsEngine.extract_texture_data(dest_tex, base.win.get_gsg())

        # Convert to single channel
        img = PNMImage(2048, 2048, 1, 255)
        dest_tex.store(img)
        img.set_num_channels(1)

        tex = Texture()
        tex.load(img)
        tex.write("grain.txo.pz")
开发者ID:aimoonchen,项目名称:RenderPipeline,代码行数:32,代码来源:generate.py

示例2: setupBackgroundImage

 def setupBackgroundImage(self):    
   
   image_file = Filename(TestGameBase.__BACKGROUND_IMAGE_PATH__)
   
   # check if image can be loaded
   img_head = PNMImageHeader()
   if not img_head.readHeader(image_file ):
       raise IOError("PNMImageHeader could not read file %s. Try using absolute filepaths"%(image_file.c_str()))
       sys.exit()
       
   # Load the image with a PNMImage
   w = img_head.getXSize()
   h = img_head.getYSize()
   img = PNMImage(w,h)
   #img.alphaFill(0)
   img.read(image_file) 
   
   texture = Texture()        
   texture.setXSize(w)
   texture.setYSize(h)
   texture.setZSize(1)    
   texture.load(img)
   texture.setWrapU(Texture.WM_border_color) # gets rid of odd black edges around image
   texture.setWrapV(Texture.WM_border_color)
   texture.setBorderColor(LColor(0,0,0,0))
   
   # creating CardMaker to hold the texture
   cm = CardMaker('background')
   cm.setFrame(-0.5*w,0.5*w,-0.5*h,0.5*h)  # This configuration places the image's topleft corner at the origin (left, right, bottom, top)
   background_np = NodePath(cm.generate())            
   background_np.setTexture(texture)
   
   background_np.reparentTo(self.render)
   background_np.setPos(TestGameBase.__BACKGROUND_POSITION__)
   background_np.setScale(TestGameBase.__BACKGROUND_SCALE__)
开发者ID:jrgnicho,项目名称:platformer_games_project,代码行数:35,代码来源:test_game_base.py

示例3: loadFlatQuad

 def loadFlatQuad(self, fullFilename):
     cm = CardMaker('cm-%s' % fullFilename)
     cm.setColor(1.0, 1.0, 1.0, 1.0)
     aspect = base.camLens.getAspectRatio()
     htmlWidth = 2.0 * aspect * WEB_WIDTH_PIXELS / float(WIN_WIDTH)
     htmlHeight = 2.0 * float(WEB_HEIGHT_PIXELS) / float(WIN_HEIGHT)
     cm.setFrame(-htmlWidth / 2.0, htmlWidth / 2.0, -htmlHeight / 2.0, htmlHeight / 2.0)
     bottomRightX = WEB_WIDTH_PIXELS / float(WEB_WIDTH + 1)
     bottomRightY = WEB_HEIGHT_PIXELS / float(WEB_HEIGHT + 1)
     cm.setUvRange(Point2(0, 1 - bottomRightY), Point2(bottomRightX, 1))
     card = cm.generate()
     quad = NodePath(card)
     jpgFile = PNMImage(WEB_WIDTH, WEB_HEIGHT)
     smallerJpgFile = PNMImage()
     readFile = smallerJpgFile.read(Filename(fullFilename))
     if readFile:
         jpgFile.copySubImage(smallerJpgFile, 0, 0)
         guiTex = Texture('guiTex')
         guiTex.setupTexture(Texture.TT2dTexture, WEB_WIDTH, WEB_HEIGHT, 1, Texture.TUnsignedByte, Texture.FRgba)
         guiTex.setMinfilter(Texture.FTLinear)
         guiTex.load(jpgFile)
         guiTex.setWrapU(Texture.WMClamp)
         guiTex.setWrapV(Texture.WMClamp)
         ts = TextureStage('webTS')
         quad.setTexture(ts, guiTex)
         quad.setTransparency(0)
         quad.setTwoSided(True)
         quad.setColor(1.0, 1.0, 1.0, 1.0)
         result = quad
     else:
         result = None
     Texture.setTexturesPower2(1)
     return result
开发者ID:RandomToon,项目名称:Toontown-2,代码行数:33,代码来源:IssueFrame.py

示例4: setupTexture

    def setupTexture(self):
        """
        This is the overlay/decal/etc. which contains the typed characters.

        The texture size and the font size are currently tied together.
        :return:
        """
        self.texImage = PNMImage(1024, 1024)
        self.texImage.addAlpha()
        self.texImage.fill(1.0)
        self.texImage.alphaFill(1.0)

        self.tex = Texture('typing')
        self.tex.setMagfilter(Texture.FTLinear)
        self.tex.setMinfilter(Texture.FTLinear)

        self.typingStage = TextureStage('typing')
        self.typingStage.setMode(TextureStage.MModulate)

        self.tex.load(self.texImage)

        # ensure we can quickly update subimages
        self.tex.setKeepRamImage(True)

        # temp for drawing chars
        self.chImage = PNMImage(*self.fontCharSize)
开发者ID:eswartz,项目名称:panda3d-stuff,代码行数:26,代码来源:typist.py

示例5: _createMapTextureCard

    def _createMapTextureCard(self):
        mapImage = PNMImage(MAP_RESOLUTION, MAP_RESOLUTION)
        mapImage.fill(*self._bgColor)
        fgColor = VBase4D(*self._fgColor)
        for x in xrange(self._mazeHeight):
            for y in xrange(self._mazeWidth):
                if self._mazeCollTable[y][x] == 1:
                    ax = float(x) / self._mazeWidth * MAP_RESOLUTION
                    invertedY = self._mazeHeight - 1 - y
                    ay = float(invertedY) / self._mazeHeight * MAP_RESOLUTION
                    self._drawSquare(mapImage, int(ax), int(ay), 10, fgColor)

        mapTexture = Texture('mapTexture')
        mapTexture.setupTexture(Texture.TT2dTexture, self._maskResolution, self._maskResolution, 1, Texture.TUnsignedByte, Texture.FRgba)
        mapTexture.setMinfilter(Texture.FTLinear)
        mapTexture.load(mapImage)
        mapTexture.setWrapU(Texture.WMClamp)
        mapTexture.setWrapV(Texture.WMClamp)
        mapImage.clear()
        del mapImage
        cm = CardMaker('map_cardMaker')
        cm.setFrame(-1.0, 1.0, -1.0, 1.0)
        map = self.attachNewNode(cm.generate())
        map.setTexture(mapTexture, 1)
        return map
开发者ID:nate97,项目名称:src,代码行数:25,代码来源:MazeMapGui.py

示例6: setHeightfield

 def setHeightfield(self, heightfield):
     '''Loads the heighmap image. Currently only accepts PNMIMage
     TODO: str path, FileName'''
     if type(heightfield) is str:
         heightfield = PNMImage(heightfield)
     self.heightfield = heightfield
     self.xsize = heightfield.getXSize()
     self.ysize = heightfield.getYSize()
开发者ID:croxis,项目名称:CityMania,代码行数:8,代码来源:PagedGeoMipTerrain.py

示例7: terrainFromHeightMap

    def terrainFromHeightMap(self, main):
        self.parentNodePath = NodePath("FloorNodePath")
        self.parentNodePath.setPos(0, 0, -2)
        self.parentNodePath.setScale(5, 5, 0.75)
        # Heightfield (static)
        height = 8.0

        img = PNMImage(Filename('models/elevation.png'))
        xdim = img.getXSize()
        ydim = img.getYSize()
        shape = BulletHeightfieldShape(img, height, ZUp)
        shape.setUseDiamondSubdivision(True)
        self.rigidNode = BulletRigidBodyNode('Heightfield')
        self.rigidNode.notifyCollisions(False)
        self.rigidNodePath = self.parentNodePath.attachNewNode(self.rigidNode)
        self.rigidNodePath.node().addShape(shape)
        self.rigidNodePath.setPos(0, 0, 0)
        self.rigidNodePath.setCollideMask(BitMask32.allOn())
        self.rigidNodePath.node().notifyCollisions(False)

        main.world.attachRigidBody(self.rigidNodePath.node())

        self.hf = self.rigidNodePath.node() # To enable/disable debug visualisation

        self.terrain = GeoMipTerrain('terrain')
        self.terrain.setHeightfield(img)

        self.terrain.setBlockSize(32)
        self.terrain.setNear(50)
        self.terrain.setFar(100)
        self.terrain.setFocalPoint(base.camera)

        rootNP = self.terrain.getRoot()
        rootNP.reparentTo(self.parentNodePath)
        rootNP.setSz(8.0)

        offset = img.getXSize() / 2.0 - 0.5
        rootNP.setPos(-offset, -offset, -height / 2.0)

        self.terrain.generate()

        # Apply texture
        diffuseTexture = loader.loadTexture(Filename('models/diffuseMap.jpg'))
        diffuseTexture.setWrapU(Texture.WMRepeat)
        diffuseTexture.setWrapV(Texture.WMRepeat)
        rootNP.setTexture(diffuseTexture)

        # Normal map
        texStage = TextureStage('texStageNormal')
        texStage.setMode(TextureStage.MNormal)
        normalTexture = loader.loadTexture(Filename('models/normalMap.jpg'))
        rootNP.setTexture(texStage, normalTexture)

        # Glow map
        texStage = TextureStage('texStageNormal')
        texStage.setMode(TextureStage.MGlow)
        glowTexture = loader.loadTexture(Filename('models/glowMap.jpg'))
        rootNP.setTexture(texStage, glowTexture)
开发者ID:genusgant,项目名称:CS594-ThrottleThunder-GameClient,代码行数:58,代码来源:Terrain.py

示例8: main

def main():

  sff_file =''
  output_dir=''

  if len(sys.argv) >= 2:
    sff_file = sys.argv[1]
  
  else:
    logging.error('Usage: sff-test ssf_file [output_dir]')
    return 
  
  if len(sys.argv) >= 3:
    output_dir = sys.argv[2]
  

  #checking output dir
  if (output_dir != '') and (not os.path.exists(output_dir)):
      os.makedirs(output_dir)
  else:
    logging.info("Output directory not set from command line, skipping image save")

  fh = open(sff_file, 'rb')

  header = sff1_file.parse(fh.read(512))
  print(header)

  next_subfile = header.next_subfile
  count = 0
  while next_subfile and count < header.image_total:
      fh.seek(next_subfile)
      subfile = sff1_subfile_header.parse(fh.read(32))
      next_subfile = subfile.next_subfile

      try:
          buff = StringIO(fh.read(subfile.length))
          image = Image.open(buff)
          
          buff = StringIO()
          image.save(buff,'PNG')
          output = PNMImage()
          if not output.read(StringStream(buff.getvalue()), "i.png"):
            logging.error("Failed to read image from buffer")
            raise ValueError("Invalid image!")
          

          print("Image Group: %i, no: %i, size: %i x %i ,offset: (%i , %i), palette %i"%(subfile.groupno,subfile.imageno, 
            image.size[0],image.size[1],subfile.axisx,subfile.axisy,subfile.palette))
      except IOError:
          print(("ioerror", subfile.groupno, subfile.imageno))
          pass
      else:
#           image.save(output_dir + "/g{0}-i{1}.png".format(subfile.groupno, subfile.imageno))
        if len(output_dir) > 0:
          output.write(output_dir + "/g{0}-i{1}.png".format(subfile.groupno, subfile.imageno))
            
      count+=1
开发者ID:jrgnicho,项目名称:platformer_games_project,代码行数:57,代码来源:test_sff_loader.py

示例9: _load_noise_tex

 def _load_noise_tex(self):
     """ Loads the default 4x4 noise tex """
     random.seed(42)
     img = PNMImage(4, 4, 3)
     for x in range(16):
         img.set_xel(x%4, x//4, random.random(), random.random(), random.random())
     tex = Texture("Random4x4")
     tex.load(img)
     self._pipeline.stage_mgr.add_input("Noise4x4", tex)
开发者ID:wdmwdm,项目名称:RenderPipeline,代码行数:9,代码来源:CommonResources.py

示例10: createGround

    def createGround(self, terrainData):
        """Create ground using a heightmap"""

        # Create heightfield for physics
        heightRange = terrainData["heightRange"]

        # Image needs to have dimensions that are a power of 2 + 1
        heightMap = PNMImage(self.basePath + terrainData["elevation"])
        xdim = heightMap.getXSize()
        ydim = heightMap.getYSize()
        shape = BulletHeightfieldShape(heightMap, heightRange, ZUp)
        shape.setUseDiamondSubdivision(True)

        np = self.outsideWorldRender.attachNewNode(BulletRigidBodyNode("terrain"))
        np.node().addShape(shape)
        np.setPos(0, 0, 0)
        self.physicsWorld.attachRigidBody(np.node())

        # Create graphical terrain from same height map
        terrain = GeoMipTerrain("terrain")
        terrain.setHeightfield(heightMap)

        terrain.setBlockSize(32)
        terrain.setBruteforce(True)
        rootNP = terrain.getRoot()
        rootNP.reparentTo(self.worldRender)
        rootNP.setSz(heightRange)

        offset = xdim / 2.0 - 0.5
        rootNP.setPos(-offset, -offset, -heightRange / 2.0)
        terrain.generate()

        # Apply texture
        diffuse = self.loader.loadTexture(Filename(self.basePath + terrainData["texture"]))
        diffuse.setWrapU(Texture.WMRepeat)
        diffuse.setWrapV(Texture.WMRepeat)
        rootNP.setTexture(diffuse)
        textureSize = 6.0
        ts = TextureStage.getDefault()
        rootNP.setTexScale(ts, xdim / textureSize, ydim / textureSize)

        # Create planes around area to prevent player flying off the edge
        # Levels can define barriers around them but it's probably a good
        # idea to leave this here just in case
        sides = (
            (Vec3(1, 0, 0), -xdim / 2.0),
            (Vec3(-1, 0, 0), -xdim / 2.0),
            (Vec3(0, 1, 0), -ydim / 2.0),
            (Vec3(0, -1, 0), -ydim / 2.0),
        )
        for sideNum, side in enumerate(sides):
            normal, offset = side
            sideShape = BulletPlaneShape(normal, offset)
            sideNode = BulletRigidBodyNode("side%d" % sideNum)
            sideNode.addShape(sideShape)
            self.physicsWorld.attachRigidBody(sideNode)
开发者ID:Red-Gravel,项目名称:Red-Gravel,代码行数:56,代码来源:game.py

示例11: create_noise_textures

 def create_noise_textures(self):
     # Always generate the same random textures
     seed(42)
     img = PNMImage(4, 4, 3)
     for x in range(4):
         for y in range(4):
             img.set_xel(x, y, random(), random(), random())
     tex = Texture("Rand4x4")
     tex.load(img)
     self._target.set_shader_input("Noise4x4", tex)
开发者ID:MYheavyGo,项目名称:RenderPipeline,代码行数:10,代码来源:AOStage.py

示例12: __apply_Textures

 def __apply_Textures(self, recipe, tex_dict):
     for i, ter_dict in enumerate(recipe['terrains']):
         tex_img = PNMImage()
         tex_img.read(Filename("{}/tex/{}".format(recipe['planet_path'], ter_dict['texture'])))
         tex = Texture()
         tex.load(tex_img)
         tex.setMinfilter(Texture.FTLinear)
         ts = TextureStage(str(i))
         ts.setSort(i)
         self.NP.setTexture(ts, tex, i*10)
开发者ID:svfgit,项目名称:solex,代码行数:10,代码来源:model.py

示例13: generate

 def generate(self):
     '''(Re)generate the entire terrain erasing any current changes'''
     factor = self.blockSize*self.chunkSize
     #print "Factor:", factor
     for terrain in self.terrains:
         terrain.getRoot().removeNode()
     self.terrains = []
     # Breaking master heightmap into subimages
     heightmaps = []
     self.xchunks = (self.heightfield.getXSize()-1)/factor
     self.ychunks = (self.heightfield.getYSize()-1)/factor
     #print "X,Y chunks:", self.xchunks, self.ychunks
     n = 0
     for y in range(0, self.ychunks):
         for x in range(0, self.xchunks):
             heightmap = PNMImage(factor+1, factor+1)
             heightmap.copySubImage(self.heightfield, 0, 0, xfrom = x*factor, yfrom = y*factor)
             heightmaps.append(heightmap)
             n += 1
     
     # Generate GeoMipTerrains
     n = 0
     y = self.ychunks-1
     x = 0
     for heightmap in heightmaps:
         terrain = GeoMipTerrain(str(n))
         terrain.setHeightfield(heightmap)
         terrain.setBruteforce(self.bruteForce)
         terrain.setBlockSize(self.blockSize)
         terrain.generate()
         self.terrains.append(terrain)
         root = terrain.getRoot()
         root.reparentTo(self.root)
         root.setPos(n%self.xchunks*factor, (y)*factor, 0)
         
         # In order to texture span properly we need to reiterate through every vertex
         # and redefine the uv coordinates based on our size, not the subGeoMipTerrain's
         root = terrain.getRoot()
         children = root.getChildren()
         for child in children:
             geomNode = child.node()
             for i in range(geomNode.getNumGeoms()):
                 geom = geomNode.modifyGeom(i)
                 vdata = geom.modifyVertexData()
                 texcoord = GeomVertexWriter(vdata, 'texcoord')
                 vertex = GeomVertexReader(vdata, 'vertex')
                 while not vertex.isAtEnd():
                     v = vertex.getData3f()
                     t = texcoord.setData2f((v[0]+ self.blockSize/2 + self.blockSize*x)/(self.xsize - 1),
                                                     (v[1] + self.blockSize/2 + self.blockSize*y)/(self.ysize - 1))
         x += 1
         if x >= self.xchunks:
             x = 0
             y -= 1
         n += 1
开发者ID:croxis,项目名称:CityMania,代码行数:55,代码来源:PagedGeoMipTerrain.py

示例14: generate_atlas

def generate_atlas(files, dest_dat, dest_png):
    entries = []

    virtual_atlas_size = 32
    all_entries_matched = False

    print("Loading", len(files), "entries ..")
    for verbose_name, source in files:
        entries.append(AtlasEntry(verbose_name, source))

    entries = sorted(entries, key=lambda a: -a.area)

    while not all_entries_matched:
        print("Trying to pack into a", virtual_atlas_size, "x", virtual_atlas_size, "atlas ..")

        packer = LUIAtlasPacker(virtual_atlas_size)
        all_entries_matched = True

        for entry in entries:
            print("Finding position for", entry.w, entry.h)
            uv = packer.find_position(entry.w, entry.h)

            if uv.get_x() < 0:
                # print "  Not all images matched, trying next power of 2"
                all_entries_matched = False
                virtual_atlas_size *= 2
                break
            entry.assigned_pos = uv

    print("Matched entries, writing atlas ..")

    atlas_description_content = ""
    dest = PNMImage(virtual_atlas_size, virtual_atlas_size, 4)

    for entry in entries:

        if not entry.tex.has_alpha():
            entry.tex.add_alpha()
            entry.tex.alpha_fill(1.0)

        dest.copy_sub_image(
            entry.tex, int(entry.assigned_pos.get_x()), int(entry.assigned_pos.get_y()))

        atlas_description_content += "{0} {1} {2} {3} {4}\n".format(
            entry.name.replace(" ", "_"),
            int(entry.assigned_pos.get_x()),
            int(entry.assigned_pos.get_y()),
            entry.w, entry.h)
        print("Writing", entry.name,"with dimensions", entry.w, entry.h)

    dest.write(dest_png)

    with open(dest_dat, "w") as handle:
        handle.write(atlas_description_content)
开发者ID:TheCheapestPixels,项目名称:LUI,代码行数:54,代码来源:LUIAtlasGen.py

示例15: __init__

class AtlasEntry:

    def __init__(self, verbose_name, source_path):
        self.name = verbose_name
        self.path = source_path
        self.tex = PNMImage(source_path)
        self.w = self.tex.get_x_size()
        self.h = self.tex.get_y_size()
        self.area = self.w * self.h
        self.assigned_pos = None

    def __repr__(self):
        return self.name
开发者ID:TheCheapestPixels,项目名称:LUI,代码行数:13,代码来源:LUIAtlasGen.py


注:本文中的panda3d.core.PNMImage类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。