本文整理汇总了Python中panda3d.core.PNMImage.read方法的典型用法代码示例。如果您正苦于以下问题:Python PNMImage.read方法的具体用法?Python PNMImage.read怎么用?Python PNMImage.read使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类panda3d.core.PNMImage
的用法示例。
在下文中一共展示了PNMImage.read方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __map_Topography
# 需要导入模块: from panda3d.core import PNMImage [as 别名]
# 或者: from panda3d.core.PNMImage import read [as 别名]
def __map_Topography(self, planet, model, pts=[]):
height_map = PNMImage()
height_map_path = "{}/maps/{}".format(planet.path, planet.height_map)
height_map.read(Filename(height_map_path))
_hu_size = height_map.getXSize()-1
_hv_size = height_map.getYSize()-1
radius = planet.radius
bottom = radius + planet.height_min
elev_range = planet.height_max - planet.height_min
_has_sea = "sea_level" in planet.__dict__
if _has_sea:
sea_level = planet.sea_level + planet.radius
if not pts: pts = model.read("vertex")
for pt in pts:
u, v = self.__get_Pt_Uv(pt, _hu_size, _hv_size)
height_val = height_map.getGray(u, v) ## watch when extending w colours.
height = bottom + elev_range*height_val
ratio = height / radius
pt *= ratio
# If planet has sea then raise vert to sea level.
if _has_sea:
len_pt = pt.length()
if len_pt <= sea_level:
ratio = sea_level/len_pt
pt *= ratio
model.modify("vertex", pts)
示例2: setupBackgroundImage
# 需要导入模块: from panda3d.core import PNMImage [as 别名]
# 或者: from panda3d.core.PNMImage import read [as 别名]
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__)
示例3: __apply_Textures
# 需要导入模块: from panda3d.core import PNMImage [as 别名]
# 或者: from panda3d.core.PNMImage import read [as 别名]
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)
示例4: __build_Normal_Map
# 需要导入模块: from panda3d.core import PNMImage [as 别名]
# 或者: from panda3d.core.PNMImage import read [as 别名]
def __build_Normal_Map(self, recipe):
# Load ref image.
ref_img = PNMImage()
height_map_path = "{}/maps/{}".format(recipe['path'], recipe['height_map'])
ref_img.read(Filename(height_map_path))
# Create normal map from height map with GPU.
with GPU_Image(ref_img, print_times=True) as gpu:
height_range = LVector2f(recipe['height_min'], recipe['height_max'])
norm_img = gpu.generate_normal_map(height_range=height_range)
norm_img.write(Filename("{}/maps/earth_norm.jpg".format(recipe['path'])))
return recipe
示例5: loadSpriteImages
# 需要导入模块: from panda3d.core import PNMImage [as 别名]
# 或者: from panda3d.core.PNMImage import read [as 别名]
def loadSpriteImages(self,file_path,cols,rows,flipx = False,flipy = False):
"""
Loads an image file containing individual animation frames and returns then in a list of PNMImages
inputs:
- file_path
- cols
- rows
- flipx
- flipy
Output:
- tuple ( bool , list[PNMImage] )
"""
# Make a filepath
image_file = Filename(file_path)
if image_file .empty():
raise IOError("File not found")
return (False, [])
# Instead of loading it outright, check with the PNMImageHeader if we can open
# the file.
img_head = PNMImageHeader()
if not img_head.readHeader(image_file ):
raise IOError("PNMImageHeader could not read file %s. Try using absolute filepaths"%(file_path))
return (False, [])
# Load the image with a PNMImage
full_image = PNMImage(img_head.getXSize(),img_head.getYSize())
full_image.alphaFill(0)
full_image.read(image_file)
if flipx or flipy:
full_image.flip(flipx,flipy,False)
w = int(full_image.getXSize()/cols)
h = int(full_image.getYSize()/rows)
images = []
counter = 0
for i in range(0,cols):
for j in range(0,rows):
sub_img = PNMImage(w,h)
sub_img.addAlpha()
sub_img.alphaFill(0)
sub_img.fill(1,1,1)
sub_img.copySubImage(full_image ,0 ,0 ,i*w ,j*h ,w ,h)
images.append(sub_img)
return (True, images)
示例6: loadFlatQuad
# 需要导入模块: from panda3d.core import PNMImage [as 别名]
# 或者: from panda3d.core.PNMImage import read [as 别名]
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
示例7: set_planet_textures
# 需要导入模块: from panda3d.core import PNMImage [as 别名]
# 或者: from panda3d.core.PNMImage import read [as 别名]
def set_planet_textures(cls, planet):
# Terrain map texture.
map_img = PNMImage()
map_img.read(Filename("{}/maps/{}".format(planet.path, planet.height_map)))
map_tex = Texture()
map_tex.load(map_img)
planet.LOD_NP.setShaderInput("height_map", map_tex)
# Colour map texture.
col_img = PNMImage()
col_img.read(Filename("{}/maps/{}".format(planet.path, planet.colour_map)))
col_tex = Texture()
col_tex.load(col_img)
planet.LOD_NP.setShaderInput("col_map", col_tex)
# Normal map texture.
norm_img = PNMImage()
norm_img.read(Filename("{}/maps/{}".format(planet.path, planet.normal_map)))
norm_tex = Texture()
norm_tex.load(norm_img)
planet.LOD_NP.setShaderInput("normal_map", norm_tex)
# Terrain map texture.
ter_img = PNMImage()
ter_img.read(Filename("{}/maps/{}".format(planet.path, planet.terrain_map)))
ter_tex = Texture()
ter_tex.load(ter_img)
planet.LOD_NP.setShaderInput("terrain_map", ter_tex)
# Terrain textures.
tex_count = len(planet.terrains)
near_tex_array = Texture()
far_tex_array = Texture()
near_tex_array.setup2dTextureArray(tex_count)
far_tex_array.setup2dTextureArray(tex_count)
for i, terrain in enumerate(planet.terrains):
near_tex_img, far_tex_img = PNMImage(), PNMImage()
near_tex_name, far_tex_name = terrain['textures']
near_tex_img.read(Filename("{}/textures/{}".format(planet.path, near_tex_name)))
far_tex_img.read(Filename("{}/textures/{}".format(planet.path, far_tex_name)))
near_tex_array.load(near_tex_img, i, 0)
far_tex_array.load(far_tex_img, i, 0)
planet.LOD_NP.setShaderInput("near_tex", near_tex_array)
planet.LOD_NP.setShaderInput("far_tex", far_tex_array)
示例8: __map_Colours
# 需要导入模块: from panda3d.core import PNMImage [as 别名]
# 或者: from panda3d.core.PNMImage import read [as 别名]
def __map_Colours(self, planet, model, rec, pts=[]):
col_map_path = planet.colour_map.replace(".","_low.")
col_map_fn = Filename("{}/maps/{}".format(planet.path, col_map_path))
col_map = PNMImage()
col_map.read(col_map_fn)
_cu_size = col_map.getXSize()-1
_cv_size = col_map.getYSize()-1
cols = []
if not pts: pts = model.read("vertex")
for pt in pts:
u, v = self.__get_Pt_Uv(pt, _cu_size, _cv_size)
r = col_map.getRed(u, v)
g = col_map.getGreen(u, v)
b = col_map.getBlue(u, v)
pt_col = (r, g, b, 1)
cols.append(pt_col)
model.modify("color", cols)
示例9: main
# 需要导入模块: from panda3d.core import PNMImage [as 别名]
# 或者: from panda3d.core.PNMImage import read [as 别名]
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
示例10: loadImage
# 需要导入模块: from panda3d.core import PNMImage [as 别名]
# 或者: from panda3d.core.PNMImage import read [as 别名]
def loadImage(self,file_path,cols,rows,scale_x,scale_y,frame_rate):
# Make a filepath
image_file = Filename(file_path)
if image_file .empty():
raise IOError, "File not found"
return False
# Instead of loading it outright, check with the PNMImageHeader if we can open
# the file.
img_head = PNMImageHeader()
if not img_head.readHeader(image_file ):
raise IOError, "PNMImageHeader could not read file %s. Try using absolute filepaths"%(file_path)
return False
# Load the image with a PNMImage
full_image = PNMImage(img_head.getXSize(),img_head.getYSize())
full_image.alphaFill(0)
full_image.read(image_file)
right_image = PNMImage(img_head.getXSize(),img_head.getYSize())
left_image = PNMImage(img_head.getXSize(),img_head.getYSize())
right_image.copyFrom(full_image)
left_image.copyFrom(full_image)
left_image.flip(True,False,False)
# storing individual sprite size
self.size_ = (right_image.getReadXSize()/cols,right_image.getReadYSize()/rows)
self.seq_right_ = self.attachNewNode(self.createSequenceNode(self.name_ + '_right_seq',right_image,cols,rows,scale_x,scale_y,frame_rate))
self.seq_left_ = self.attachNewNode(self.createSequenceNode(self.name_ + '_left_seq',left_image,cols,rows,scale_x,scale_y,frame_rate))
self.seq_right_.reparentTo(self)
self.seq_left_.reparentTo(self)
right_image.clear()
left_image.clear()
full_image.clear()
self.faceRight(True)
return True
示例11: __loadSpritePair__
# 需要导入模块: from panda3d.core import PNMImage [as 别名]
# 或者: from panda3d.core.PNMImage import read [as 别名]
def __loadSpritePair__(sprite_details):
image_file = sprite_details.im_file
img_head = PNMImageHeader()
if not img_head.readHeader(image_file ):
logging.error( "PNMImageHeader could not read file %s. Try using absolute filepaths"%(image_file))
return (None,None)
# Load the right side image as a PNMImage
right_img = PNMImage(img_head.getXSize(),img_head.getYSize())
right_img.alphaFill(0)
right_img.read(image_file)
# Flip to get the left side image
left_img = PNMImage(right_img.getXSize(),right_img.getYSize())
left_img.copyFrom(right_img)
left_img.flip(True ,False,False)
images = [(right_img,False),(left_img,True)]
sprites = []
for entry in images:
img = entry[0]
flip = entry[1]
sprite = Sprite()
sprite.setXSize(img.getXSize())
sprite.setYSize(img.getYSize())
sprite.setZSize(1)
sprite.axisx = -sprite_details.axisx if (not flip ) else sprite_details.axisx
sprite.axisy = sprite_details.axisy
sprite.group = sprite_details.group_no
sprite.no = sprite_details.image_no
sprite.load(img)
sprite.setWrapU(Texture.WM_border_color) # gets rid of odd black edges around image
sprite.setWrapV(Texture.WM_border_color)
sprite.setBorderColor(LColor(0,0,0,0))
sprites.append(sprite)
return (sprites[0],sprites[1])
示例12: mapSelection
# 需要导入模块: from panda3d.core import PNMImage [as 别名]
# 或者: from panda3d.core.PNMImage import read [as 别名]
def mapSelection(self, maps):
"""
Generate a window with list and thumbnails of region maps availiable.
Provide two options, load map or, if there is no local version, save local version
"""
self.mapDialog = DirectWindow(title = "Select Map")
mapList = []
m = [""]
import base64
for mapName in maps:
heightmap = maps[mapName]
image = PNMImage()
image.read(StringStream(heightmap))
thumbnail = PNMImage(64, 64)
thumbnail.gaussianFilterFrom(1, image)
heightTexture = Texture()
heightTexture.load(image)
label = DirectRadioButton(text=mapName, image=heightTexture, variable=m, value=[mapName])
mapList.append(label)
for button in mapList:
button.setOthers(mapList)
self.mapDialog.addScrolledList(mapList)
okButton = DirectButton(text = self.getText('TXT_UI_OK'), command = self.selectMap, extraArgs=m)
self.mapDialog.addVertical([okButton])
示例13: textureFromData
# 需要导入模块: from panda3d.core import PNMImage [as 别名]
# 或者: from panda3d.core.PNMImage import read [as 别名]
def textureFromData(image_data, filename=""):
tex = None
if image_data:
myTexture = Texture()
myImage = PNMImage()
success = myImage.read(StringStream(image_data), filename)
if success == 1:
#PNMImage can handle most texture formats
myTexture.load(myImage)
else:
#Except for DDS, which PNMImage.read will return 0, so try to load as DDS
success = myTexture.readDds(StringStream(image_data))
if success != 0:
tex = myTexture
tex.setMinfilter(Texture.FTLinearMipmapLinear)
return tex
示例14: __build_Terrain_Map
# 需要导入模块: from panda3d.core import PNMImage [as 别名]
# 或者: from panda3d.core.PNMImage import read [as 别名]
def __build_Terrain_Map(self, recipe):
# Height map.
height_map = PNMImage()
height_map_path = "{}/maps/{}".format(recipe['path'], recipe['height_map'])
height_map.read(Filename(height_map_path))
# Colour map.
col_map = PNMImage()
col_map_path = "{}/maps/{}".format(recipe['path'], recipe['colour_map'])
col_map.read(Filename(col_map_path))
# Normal map.
norm_map = PNMImage()
norm_map_path = "{}/maps/{}".format(recipe['path'], recipe['normal_map'])
norm_map.read(Filename(norm_map_path))
# Dict of range qualifiers to pass directly to 'generate_terrain_map'.
t_count = len(recipe['terrains'])
ranges_dict = {'lat_ranges':PTA_LVecBase2f([LVector2f(x*0,0) for x in range(t_count)]),
'lon_ranges':PTA_LVecBase2f([LVector2f(x*0,0) for x in range(t_count)]),
'alt_ranges':PTA_LVecBase2f([LVector2f(x*0,0) for x in range(t_count)]),
'red_ranges':PTA_LVecBase2f([LVector2f(x*0,0) for x in range(t_count)]),
'green_ranges':PTA_LVecBase2f([LVector2f(x*0,0) for x in range(t_count)]),
'blue_ranges':PTA_LVecBase2f([LVector2f(x*0,0) for x in range(t_count)])}
for i, terrain in enumerate(recipe['terrains']):
for attr, val in list(terrain.items()):
if attr.endswith("range"):
ranges_dict[attr+"s"][i] = LVector2f(*val)
# Create terrain map with GPU.
height_range = LVector2f(recipe['height_min'],recipe['height_max'])
with GPU_Image(height_map, print_times=True) as gpu:
terrain_img = gpu.generate_terrain_map(height_range=height_range,
col_map=col_map,
**ranges_dict)
file_path = "{}/maps/{}_ter.png".format(recipe['path'], recipe['name'].lower())
terrain_img.write(Filename(file_path))
示例15: __init__
# 需要导入模块: from panda3d.core import PNMImage [as 别名]
# 或者: from panda3d.core.PNMImage import read [as 别名]
def __init__(self, mesh_path, progressive_texture_path):
resolutions = []
f = tarfile.open(progressive_texture_path)
for resolution_name in f.getnames():
toset = {'size': resolution_name[:-4],
'contents': f.extractfile(resolution_name).read()}
texpnm = PNMImage()
texpnm.read(StringStream(toset['contents']), 'something.jpg')
newtex = Texture()
newtex.load(texpnm)
toset['texture'] = newtex
resolutions.append(toset)
self.resolutions = resolutions
def aux_loader(fname):
return resolutions[0]['contents']
mesh = collada.Collada(mesh_path, aux_file_loader=aux_loader)
scene_members = getSceneMembers(mesh)
base = ShowBase()
rotateNode = GeomNode("rotater")
rotatePath = render.attachNewNode(rotateNode)
matrix = numpy.identity(4)
if mesh.assetInfo.upaxis == collada.asset.UP_AXIS.X_UP:
r = collada.scene.RotateTransform(0,1,0,90)
matrix = r.matrix
elif mesh.assetInfo.upaxis == collada.asset.UP_AXIS.Y_UP:
r = collada.scene.RotateTransform(1,0,0,90)
matrix = r.matrix
rotatePath.setMat(Mat4(*matrix.T.flatten().tolist()))
geom, renderstate, mat4 = scene_members[0]
node = GeomNode("primitive")
node.addGeom(geom)
if renderstate is not None:
node.setGeomState(0, renderstate)
self.geomPath = rotatePath.attachNewNode(node)
self.geomPath.setMat(mat4)
wrappedNode = ensureCameraAt(self.geomPath, base.camera)
base.disableMouse()
attachLights(render)
render.setShaderAuto()
render.setTransparency(TransparencyAttrib.MDual, 1)
base.render.analyze()
KeyboardMovement()
MouseDrag(wrappedNode)
MouseScaleZoom(wrappedNode)
MouseCamera()
num_resolutions = len(resolutions) - 1
self.slider = DirectSlider(range=(0, num_resolutions),
value=0, pageSize=1,
command=self.sliderMoved, pos=(0, 0, -.9), scale=1)
for key, val in uiArgs.iteritems():
self.slider.thumb[key] = val
self.triText = OnscreenText(text="", pos=(-1,0.85), scale = 0.15,
fg=(1, 0.5, 0.5, 1), align=TextNode.ALeft, mayChange=1)
base.run()