def makeCube(geom, x, y, z, scale=1.0, texpos=None, colors=False): """ Function that adds six cards to a GeomNode to form a cube geom: GeomNode to add cards to x, y, z: Position offset scale: Optional, Scale factor, cube is 1x1x1 by default texpos: Optional, Dictionary of tuples with texture co-ordinates Tuple has Point2 for top-left and Point2 for bottom-right Faces are "front", "back", "left", "right", "top", "bottom" colors: Optional, if True set different color for each face for debugging (see cardcolors) """ cardmaker = CardMaker("cardmaker") mycards = deepcopy(CARDS) for k, i in mycards.iteritems(): points = i for j in points: j += Point3(x, y, z) j *= scale cardmaker.setFrame(*points) if texpos: cardmaker.setUvRange(*texpos[k]) if colors: cardmaker.setColor(*CARDCOLORS[k]) geom.addGeomsFrom(cardmaker.generate())
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
class FirstTry(visual): def setup(self): self.tex1 = MovieTexture('videos/saturn5_apollo_launch.mp4') assert self.tex1.read('videos/saturn5_apollo_launch.mp4') self.tex2 = MovieTexture('videos/boards_eye_view.mp4') assert self.tex2.read('videos/boards_eye_view.mp4') self.cm1 = CardMaker('saturn') self.cm1.setFrameFullscreenQuad() self.cm1.setUvRange(self.tex1) self.card1 = NodePath(self.cm1.generate()) self.card1.reparentTo(self.path) self.card1.setPos(0,0,10) self.card1.setP(50) self.cm2 = CardMaker('board') self.cm2.setFrameFullscreenQuad() self.cm2.setUvRange(self.tex2) self.card2 = NodePath(self.cm2.generate()) self.card2.reparentTo(self.path) self.card2.setPos(0,0,-10) self.card2.setP(-50) self.card1.setTexture(self.tex1) self.card1.setTexScale(TextureStage.getDefault(), self.tex1.getTexScale()) self.card2.setTexture(self.tex2) self.card2.setTexScale(TextureStage.getDefault(), self.tex2.getTexScale()) self.card1.setScale(10) self.card2.setScale(10) def getBeat(self): pass
def __init__(self): ShowBase.__init__(self) props = WindowProperties( ) props.setTitle( 'Differentiable Physics Engine' ) self.win.requestProperties( props ) self.t = 0 self.starttime = time.time() #self.setFrameRateMeter(True) cour = self.loader.loadFont('cmtt12.egg') self.textObject = OnscreenText(font= cour, text = 'abcdefghijklmnopqrstuvwxyz', pos=(0, -0.045), parent = self.a2dTopCenter, bg=(0,0,0,1), fg =(1,1,1,1), scale = 0.07, mayChange=True) cm = CardMaker("ground") cm.setFrame(-2000, 2000, -2000, 2000) cm.setUvRange(Point2(-2000/5,-2000/5),Point2(2000/5,2000/5)) tmp = self.render.attachNewNode(cm.generate()) tmp.reparentTo(self.render) tmp.setPos(0, 0, 0) tmp.lookAt((0, 0, -2)) tmp.setColor(1.0,1.0,1.0,1) tmp.setTexScale(TextureStage.getDefault(), 1, 1) tex = self.loader.loadTexture('textures/grid2.png') tex.setWrapU(Texture.WMRepeat) tex.setWrapV(Texture.WMRepeat) tmp.setTexture(tex,1) self.setBackgroundColor(0.0, 191.0/255.0, 1.0, 1.0) #color of the sky ambientLight = AmbientLight('ambientLight') ambientLight.setColor(Vec4(0.2, 0.2, 0.2, 1)) ambientLightNP = self.render.attachNewNode(ambientLight) self.render.setLight(ambientLightNP) # Directional light 01 directionalLight = DirectionalLight('directionalLight') directionalLight.setColor(Vec4(0.8, 0.8, 0.8, 1)) directionalLightNP = self.render.attachNewNode(directionalLight) # This light is facing backwards, towards the camera. directionalLightNP.setHpr(-60, -50, 0) directionalLightNP.node().setScene(self.render) directionalLightNP.node().setShadowCaster(True) directionalLightNP.node().getLens().setFov(40) directionalLightNP.node().getLens().setNearFar(10, 100) self.render.setLight(directionalLightNP) # Add the spinCameraTask procedure to the task manager. self.taskMgr.add(self.spinCameraTask, "SpinCameraTask") # Load the environment model. self.objects = dict() self.names = [] data = pickle.load(open("../PhysXVids/state-dump-exp15.pkl","rb")) self.json = json.loads(data["json"]) # json.loads(data["json"]) self.states = data["states"] self.load_robot_model() self.dt = self.json["integration_parameters"]["time_step"] self.setupKeys() self.robot_id = 0
def __init__(self, startSize, endSize, roll, color, duration): NodePath.__init__(self, 'muzzleParticle') muzzles = [1, 4] muzzleroot = "phase_14/hl2/muzzleflash{0}.png" cm = CardMaker("muzzleSpriteCard") cm.setFrame(-1, 1, -1, 1) cm.setHasUvs(True) cm.setUvRange((0, 0), (1, 1)) cmnp = self.attachNewNode(cm.generate()) cmnp.setBillboardAxis() self.setTexture(loader.loadTexture(muzzleroot.format(random.randint(*muzzles))), 1) #self.setShaderOff(1) self.setLightOff(1) self.setMaterialOff(1) self.setTransparency(1) self.startAlpha = 0.5 self.endAlpha = 0.0 self.duration = duration self.startSize = startSize self.endSize = endSize self.color = color self.startTime = globalClock.getFrameTime() self.roll = roll taskMgr.add(self.particleUpdate, "muzzleParticleUpdate-" + str(id(self)))
def __init__(self, startSize, endSize, roll, color, duration): NodePath.__init__(self, 'muzzleParticle') cm = CardMaker("muzzleSpriteCard") cm.setFrame(-1, 1, -1, 1) cm.setHasUvs(True) cm.setUvRange((0, 0), (1, 1)) cmnp = self.attachNewNode(cm.generate()) cmnp.setBillboardAxis() self.setTexture(loader.loadTexture(self.muzzleroot.format(random.randint(*self.muzzles))), 1) #self.setShaderOff(1) self.setLightOff(1) self.setMaterialOff(1) self.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MAdd, ColorBlendAttrib.OOne, ColorBlendAttrib.OOne), 1) self.setDepthWrite(False, 1) #self.setTransparency(1) self.startAlpha = 0.5 self.endAlpha = 0.0 self.duration = duration self.startSize = startSize self.endSize = endSize self.color = color self.startTime = globalClock.getFrameTime() self.roll = roll taskMgr.add(self.particleUpdate, "muzzleParticleUpdate-" + str(id(self)))
def loadVideo(videoFileName, loop=False): videoPathStr = 'Video/{}' videoPathStr = videoPathStr.format(videoFileName) try: tex = MovieTexture(videoFileName) success = tex.read(videoPathStr) assert success, "Failed to load video!" # Set up a fullscreen card to set the video texture on. cm = CardMaker("My Fullscreen Card") cm.setFrameFullscreenQuad() # Tell the CardMaker to create texture coordinates that take into # account the padding region of the texture. cm.setUvRange(tex) # Now place the card in the scene graph and apply the texture to it. card = render2d.attachNewNode(cm.generate()) card.setTexture(tex) card.hide() sound = loader.loadMusic(videoPathStr) # set loop false sound.setLoop(loop) # Synchronize the video to the sound. tex.synchronizeTo(sound) return sound, card except Exception as e: #logging.debug("loadvideo: {}".format(traceback.format_exc())) pass return sound, card
def scene_init(self, render, loader): # self.scene = self.loader.loadModel("models/environment") # self.scene.reparentTo(self.render) # region texture floor_texture = loader.loadTexture("models/maps/envir-ground.jpg") floor_texture.setMinfilter(SamplerState.FT_linear_mipmap_linear) wall_texture = loader.loadTexture("models/maps/envir-reeds.png") # endregion # region floor floor_card_maker = CardMaker("floor") floor_card_maker.setUvRange((0, 0), (self.size / 10, self.size / 10)) floor_gfx = render.attachNewNode(CardMaker.generate(floor_card_maker)) floor_gfx.setP(-90) # This rotates the card to face upwards floor_gfx.setPos(-self.size / 2, -self.size / 2, 0) floor_gfx.setScale(self.size) floor_gfx.setTexture(floor_texture) # endregion # region walls self.create_wall(render, wall_texture, -90, 0, 0) self.create_wall_collider(render, 0, 1, -180) self.create_wall(render, wall_texture, 0, 90, -90) self.create_wall_collider(render, 0, -1, 0) self.create_wall(render, wall_texture, 90, -90, -180) self.create_wall_collider(render, 1, 0, 90) self.create_wall(render, wall_texture, -90, -90, -270) self.create_wall_collider(render, -1, 0, -90)
def playVideo(self, video): # check if it is loadable try: # load the video texture self.tex = MovieTexture("MovieTexture") #print video self.tex.read(video) # Set up a fullscreen card to set the video texture on it. cm = CardMaker("Movie Card") cm.setFrameFullscreenQuad() cm.setUvRange(self.tex) self.card = NodePath(cm.generate()) self.card.reparentTo(base.render2d) self.card.setTexture(self.tex) self.card.setTexScale(TextureStage.getDefault(), self.tex.getTexScale()) # load the video self.sound = loader.loadSfx(video) # Synchronize the video to the sound. self.tex.synchronizeTo(self.sound) # play the video and audio self.sound.play() # start the task which checks if the video is finished taskMgr.add(self.isVideoFinish, "task_isVideoFinised") except: logging.error("Failed to load video: %s %s", video, sys.exc_info()) self.stopVideo() base.messenger.send(self.vidFinEvt)
class MatPlotLibDemo(ShowBase): def __init__(self): ShowBase.__init__(self) base.setFrameRateMeter(True) m = loader.loadModel("models/smiley") m.reparent_to(render) m.set_pos(0, 5, 0) x_size, y_size = 640, 480 xy_ratio = float(y_size) / float(x_size) self.plot = Plot(x_size, y_size) self.input_img = PNMImage(x_size, y_size) self.input_tex = Texture() self.input_tex.load(self.input_img) self.card = CardMaker('pygame_card') self.card.setUvRange(Point2(0, 1), # ll Point2(1, 1), # lr Point2(1, 0), # ur Point2(0, 0)) # ul self.screen = render.attach_new_node(self.card.generate()) self.screen.set_scale(1, 1, xy_ratio) self.screen.set_pos(-0.5, 2, -0.5 * xy_ratio) self.screen.setTexture(self.input_tex) # FIXME: Apparently mpl's print_to_buffer() doesn't write # alpha values properly. self.screen.setTransparency(TransparencyAttrib.MAlpha) taskMgr.add(self.update, "update plot") def update(self, task): self.input_tex.set_ram_image_as(self.plot.draw(), "RGBA") return task.cont
def setupTexture(self): cm = CardMaker('quadMaker') 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() self.quad = NodePath(card) self.quad.reparentTo(self.parent_) self.guiTex = Texture('guiTex') self.guiTex.setupTexture(Texture.TT2dTexture, WEB_WIDTH, WEB_HEIGHT, 1, Texture.TUnsignedByte, Texture.FRgba) self.guiTex.setMinfilter(Texture.FTLinear) self.guiTex.setKeepRamImage(True) self.guiTex.makeRamImage() self.guiTex.setWrapU(Texture.WMRepeat) self.guiTex.setWrapV(Texture.WMRepeat) ts = TextureStage('webTS') self.quad.setTexture(ts, self.guiTex) self.quad.setTexScale(ts, 1.0, -1.0) self.quad.setTransparency(0) self.quad.setTwoSided(True) self.quad.setColor(1.0, 1.0, 1.0, 1.0) self.calcMouseLimits()
def __init__(self, world, app): self.world = world self.image = PNMImage(self.world.width, 256) for z in self.world.zlevels(): for x in range(self.world.height): mix = sum([ZMap.COLORS[self.world.get_block(x, y, z).substance] for y in range(self.world.height)], VBase3F(0.0)) self.image.setXel(x, z, mix / float(self.world.height)) self.texture = Texture() self.texture.load(self.image) self.texture.setMagfilter(Texture.FTNearest) self.texture.setMinfilter(Texture.FTNearest) cm = CardMaker('zmap') cm.setFrame(0.95, 1, -1, 1) cm.setUvRange(Point2(1.0, 1.0), Point2(0.0, 1.0 - self.world.depth / 256.0)) self.zcard = app.render2d.attachNewNode(cm.generate()) self.zcard.setTexture(self.texture) cm = CardMaker('zpointer') cm.setFrame(0, 0.05, 0, 1.0 / self.world.depth) self.zpointer = app.render2d.attachNewNode(cm.generate()) self.zpointer.setColorScale(1.0, 0.0, 0.0, 0.4) self.accept('slice-changed', self.slice_changed)
def create_wall(self, render, wall_texture, x_angle, y_angle, angle): wall_card_maker = CardMaker("wall") wall_card_maker.setUvRange((0, 0), (self.size / 50, self.size / 50)) wall_gfx = render.attachNewNode(CardMaker.generate(wall_card_maker)) wall_gfx.setPos( copysign(1, x_angle) * self.size / 2, copysign(1, y_angle) * self.size / 2, 0) wall_gfx.setScale(self.size) wall_gfx.setHpr(angle, 0, 0) wall_gfx.setTransparency(True) wall_gfx.setTexture(wall_texture)
def __renderQuad(mat=None, tex=None): # Build a simple quad that uses the material cm = CardMaker('materialCard') cm.setFrame(-1, 1, -1, 1) cm.setHasUvs(True) cm.setUvRange(Point2(0, 0), Point2(1, 1)) cardNp = NodePath(cm.generate()) if mat: cardNp.setBSPMaterial(mat, 1) elif tex: cardNp.setTexture(tex, 1) # Render it! precacheScene(cardNp) cardNp.removeNode()
class BulletHoles: """The name says it all.""" def __init__(self, manager, xml): self.texture = loader.loadTexture('data/textures/bullet-hole.png') self.texture.setMinfilter(Texture.FTLinearMipmapLinear) self.container = render.attachNewNode(ModelRoot('bullet-holes')) self.card = CardMaker('bullet-hole') s = BULLETHOLE_SIZE * 0.5 self.card.setFrame(-s, s, -s, s) self.card.setUvRange(Point2(0, 0), Point2(1, 1)) def makeNew(self, pos, nor, parent=None): """Makes a new bullet hole.""" if parent == None: parent = self.container else: # Add a subnode to the parent, if it's not already there child = parent.find('bullet-holes') if child.isEmpty(): parent = parent.attachNewNode('bullet-holes') else: parent = child newhole = NodePath(self.card.generate()) newhole.reparentTo(parent) newhole.lookAt(render, Point3(newhole.getPos(render) - nor)) newhole.setR(newhole, random() * 360.0) newhole.setPos(render, pos) # Offset it a little to avoid z-fighting # Increase this value if you still see it. newhole.setY(newhole, -.001 - random() * 0.01) del newhole # We don't want one batch per bullet hole, so flatten it. # This could be made smarter to preserve culling, but # I have yet to see a performance loss. # The clearTexture() is a necessary hack. parent.clearTexture() parent.flattenStrong() parent.setTexture(self.texture) parent.setTransparency(TransparencyAttrib.MDual) parent.setShaderOff(1) parent.hide(BitMask32.bit( 2)) # Invisible to volumetric lighting camera (speedup) parent.hide(BitMask32.bit(3)) # Invisible to shadow cameras (speedup) def destroy(self): self.container.removeNode()
def _add_lane2bullet(self, middle, width, length, theta, lane: Union[StraightLane, CircularLane], lane_index): """ Add lane visualization and body for it :param middle: Middle point :param width: Lane width :param length: Segment length :param theta: Rotate theta :param lane: Lane info :return: None """ segment_np = NodePath(LaneNode(BodyName.Lane, lane, lane_index)) segment_node = segment_np.node() segment_node.set_active(False) segment_node.setKinematic(False) segment_node.setStatic(True) shape = BulletBoxShape(Vec3(length / 2, 0.1, width / 2)) segment_node.addShape(shape) self.static_nodes.append(segment_node) segment_np.setPos(panda_position(middle, -0.1)) segment_np.setQuat( LQuaternionf( numpy.cos(theta / 2) * numpy.cos(-numpy.pi / 4), numpy.cos(theta / 2) * numpy.sin(-numpy.pi / 4), -numpy.sin(theta / 2) * numpy.cos(-numpy.pi / 4), numpy.sin(theta / 2) * numpy.cos(-numpy.pi / 4))) segment_np.reparentTo(self.lane_node_path) if self.render: cm = CardMaker('card') cm.setFrame(-length / 2, length / 2, -width / 2, width / 2) cm.setHasNormals(True) cm.setUvRange((0, 0), (length / 20, width / 10)) card = self.lane_vis_node_path.attachNewNode(cm.generate()) card.setPos( panda_position(middle, numpy.random.rand() * 0.01 - 0.01)) card.setQuat( LQuaternionf( numpy.cos(theta / 2) * numpy.cos(-numpy.pi / 4), numpy.cos(theta / 2) * numpy.sin(-numpy.pi / 4), -numpy.sin(theta / 2) * numpy.cos(-numpy.pi / 4), numpy.sin(theta / 2) * numpy.cos(-numpy.pi / 4))) card.setTransparency(TransparencyAttrib.MMultisample) card.setTexture(self.ts_color, self.road_texture)
def getRenderMapCam(self, rawTile, inputMaps, shader, size): """ Sets up scene and cam for rendering the map Returns the cam """ margin=texMargin(size) altRender=NodePath("newRender") # setup square orthographic cam altCam=NodePath(Camera("renderMapCam")) altCam.reparentTo(altRender) altCam.setPos(.5,-1,.5) oLens = OrthographicLens() oLens.setFilmSize(1+margin*2, 1+margin*2) altCam.node().setLens(oLens) # Make a card on which the shader will render the map c=CardMaker("MapCardMaker") c.setUvRange(0-margin,1+margin,0-margin,1+margin) c.setFrame(0-margin,1+margin,0-margin,1+margin) mapCard=NodePath(c.generate()) mapCard.setPos(0,0,0) mapCard.setShader(shader.shader) mapCard.setShaderInput("offset",rawTile.x,rawTile.y,0,0) mapCard.setShaderInput("scale",rawTile.scale,0,0,0) for m in inputMaps: texStage=TextureStage(m.name+"stage") mapCard.setTexture(texStage,m.tex) for p in shader.shaderTex: mapCard.setTexture(*p) mapCard.reparentTo(altRender) # Comment out this line to cause the bug with multiple textures requireing an extra frame to work properly altRender.prepareScene(base.win.getGsg()) return altCam
def __init__(self): super(Terrain, self).__init__(random_seed=0) shape = BulletPlaneShape(Vec3(0, 0, 1), 0) node = BulletRigidBodyNode(BodyName.Ground) node.setFriction(.9) node.addShape(shape) node.setIntoCollideMask(self.COLLISION_MASK) self.dynamic_nodes.append(node) self.origin.attachNewNode(node) if self.render: self.origin.hide(CamMask.MiniMap | CamMask.Shadow | CamMask.DepthCam | CamMask.ScreenshotCam) # self.terrain_normal = self.loader.loadTexture( # AssetLoader.file_path( "textures", "grass2", "normal.jpg") # ) self.terrain_texture = self.loader.loadTexture( AssetLoader.file_path("textures", "ground.png")) self.terrain_texture.setWrapU(Texture.WM_repeat) self.terrain_texture.setWrapV(Texture.WM_repeat) self.ts_color = TextureStage("color") self.ts_normal = TextureStage("normal") self.ts_normal.set_mode(TextureStage.M_normal) self.origin.setPos(0, 0, self.HEIGHT) cm = CardMaker('card') scale = 20000 cm.setUvRange((0, 0), (scale / 10, scale / 10)) card = self.origin.attachNewNode(cm.generate()) # scale = 1 if self.use_hollow else 20000 card.set_scale(scale) card.setPos(-scale / 2, -scale / 2, -0.1) card.setZ(-.05) card.setTexture(self.ts_color, self.terrain_texture) # card.setTexture(self.ts_normal, self.terrain_normal) self.terrain_texture.setMinfilter( SamplerState.FT_linear_mipmap_linear) self.terrain_texture.setAnisotropicDegree(8) card.setQuat( LQuaternionf(math.cos(-math.pi / 4), math.sin(-math.pi / 4), 0, 0))
def _setupTextureBuffer(self): if self.buffer: self.card.remove() self.camera2d.remove() self.base.graphicsEngine.removeWindow(self.buffer) self.buffer = self.base.win.makeTextureBuffer("beastBuffer", self.base.win.getXSize(), self.base.win.getYSize()) self.buffer.setActive(True) self.buffer.getTexture().setOrigFileSize(self.base.win.getXSize(), self.base.win.getYSize()) self.camera2d = self.base.makeCamera2d(self.buffer) self.camera2d.reparentTo(self.point2d.getParent()) cm = CardMaker('beastDisplay') cm.setFrame(-1, 1, -1, 1) cm.setUvRange(self.buffer.getTexture()) self.card = self.base.render2d.attachNewNode(cm.generate()) self.card.setTransparency(TransparencyAttrib.MAlpha) self.card.setTexture(self.buffer.getTexture())
def announceGenerate(self): DistributedEntity.announceGenerate(self) cm = CardMaker('emblemCard') cm.setFrame(-0.5, 0.5, 0, 1) cm.setHasUvs(True) cm.setUvRange((0, 0), (1, 1)) self.emblem = self.attachNewNode(cm.generate()) self.emblem.setAttrib(BloomAttrib.make(False)) self.emblem.setBSPMaterial('phase_5/maps/quest_scroll_emblem.mat', 1) self.emblem.setBillboardAxis() self.emblem.setTransparency(True) self.emblem.setScale(2) self.emblemFloat = Sequence( LerpPosInterval(self.emblem, 1.0, (0, 0, 0.5), (0, 0, 0), blendType='easeInOut'), LerpPosInterval(self.emblem, 1.0, (0, 0, 0), (0, 0, 0.5), blendType='easeInOut')) self.emblemFloat.loop() self.setupPhysics() self.reparentTo(render)
class MatPlotLibDemo(ShowBase): def __init__(self): ShowBase.__init__(self) base.setFrameRateMeter(True) m = loader.loadModel("models/smiley") m.reparent_to(render) m.set_pos(0, 5, 0) x_size, y_size = 640, 480 xy_ratio = float(y_size) / float(x_size) self.plot = Plot(x_size, y_size) self.input_img = PNMImage(x_size, y_size) self.input_tex = Texture() self.input_tex.load(self.input_img) self.card = CardMaker('pygame_card') self.card.setUvRange( Point2(0, 1), # ll Point2(1, 1), # lr Point2(1, 0), # ur Point2(0, 0)) # ul self.screen = render.attach_new_node(self.card.generate()) self.screen.set_scale(1, 1, xy_ratio) self.screen.set_pos(-0.5, 2, -0.5 * xy_ratio) self.screen.setTexture(self.input_tex) # FIXME: Apparently mpl's print_to_buffer() doesn't write # alpha values properly. self.screen.setTransparency(TransparencyAttrib.MAlpha) taskMgr.add(self.update, "update plot") def update(self, task): self.input_tex.set_ram_image_as(self.plot.draw(), "RGBA") return task.cont
def _setupTextureBuffer(self): if self.buffer: self.card.remove() self.camera2d.remove() base.graphicsEngine.removeWindow(self.buffer) self.buffer = base.win.makeTextureBuffer( "textureBuffer-%s-%s" % (self.__id, self.getName()), base.win.getXSize(), base.win.getYSize()) self.buffer.setSort(100) self.buffer.setOneShot(True) self.buffer.setActive(True) self.buffer.getTexture().setOrigFileSize(base.win.getXSize(), base.win.getYSize()) self.camera2d = base.makeCamera2d(self.buffer) self.camera2d.reparentTo(self.fakeRender2d) cm = CardMaker('card-%s-%s' % (self.__id, self.getName())) cm.setFrameFullscreenQuad() cm.setUvRange(self.buffer.getTexture()) self.card = base.render2d.attachNewNode(cm.generate()) self.card.setTransparency(TransparencyAttrib.MAlpha) self.card.setTexture(self.buffer.getTexture())
def __init__(self): ShowBase.__init__(self) self.t = 0 self.starttime = None self.setFrameRateMeter(True) cour = self.loader.loadFont('cmtt12.egg') self.textObject = OnscreenText(font=cour, text='abcdefghijklmnopqrstuvwxyz', pos=(0, -0.045), parent=self.a2dTopCenter, bg=(0, 0, 0, 0.5), fg=(1, 1, 1, 1), scale=0.07, mayChange=True) cm = CardMaker("ground") cm.setFrame(-2000, 2000, -2000, 2000) cm.setUvRange(Point2(-2000 / 5, -2000 / 5), Point2(2000 / 5, 2000 / 5)) tmp = self.render.attachNewNode(cm.generate()) tmp.reparentTo(self.render) self.camLens.setNear(0.1) tmp.setPos(0, 0, 0) tmp.lookAt((0, 0, -2)) tmp.setColor(1.0, 1.0, 1.0, 0.) #tmp.setTexScale(TextureStage.getDefault(), 1, 1) tex = self.loader.loadTexture('textures/grid2.png') tex.setWrapU(Texture.WMRepeat) tex.setWrapV(Texture.WMRepeat) tmp.setTexture(tex, 1) self.setBackgroundColor(0.0, 191.0 / 255.0, 1.0, 1.0) #color of the sky ambientLight = AmbientLight('ambientLight') ambientLight.setColor(Vec4(0.2, 0.2, 0.2, 1)) ambientLightNP = self.render.attachNewNode(ambientLight) self.render.setLight(ambientLightNP) # Directional light 01 directionalLight = DirectionalLight('directionalLight') directionalLight.setColor(Vec4(0.8, 0.8, 0.8, 1)) directionalLightNP = self.render.attachNewNode(directionalLight) # This light is facing backwards, towards the camera. directionalLightNP.setHpr(-120, -50, 0) directionalLightNP.node().setScene(self.render) directionalLightNP.node().setShadowCaster(True) directionalLightNP.node().getLens().setFov(40) directionalLightNP.node().getLens().setNearFar(10, 100) self.render.setLight(directionalLightNP) # Add the spinCameraTask procedure to the task manager. self.taskMgr.add(self.spinCameraTask, "SpinCameraTask") self.physics = TheanoRigid3DBodyEngine() self.benchmark_physics = None #Rigid3DBodyEngine() # Load the environment model. self.objects = dict() #self.load_robot_model("robotmodel/test.json") self.load_robot_model("robotmodel/predator.json") #self.load_robot_model("robotmodel/simple_predator.json") if self.benchmark_physics: self.benchmark_physics.compile() print "Compiling..." self.positions, self.velocities, self.rotations = self.physics.getInitialState( ) self.physics.compile() import theano.tensor as T positions = T.fmatrix() velocities = T.fmatrix() rotations = T.ftensor3() a, b, c = self.physics.step_from_this_state( (positions, velocities, rotations), dt=0.001, motor_signals=[-1, 1, -1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) self.timestep = theano.function( inputs=[positions, velocities, rotations], outputs=[a, b, c], allow_input_downcast=True)
class CameraApp(GuiHandler): __ImageDir = "data/images" def __init__(self, device): GuiHandler.__init__(self) self.func3 = "Si" self.func2 = "" self.func1 = "No" self.title = "Guardar?" self.parent = device self.video_mode = False option = WebcamVideo.get_option(0) self.texture = MovieTexture(option) self.texture.setKeepRamImage(True) #self.texture = OpenCVTexture() #self.texture.fromCamera() scale = self.texture.getTexScale() print scale #self.texture = OpenCVTexture() self.card = CardMaker('webcam') self.card.setFrame(-scale[0], scale[0], -scale[1], scale[1]) self.card.setUvRange(Point2(scale[0], 0), Point2(0, scale[1])) self.card = render.attachNewNode(self.card.generate()) screen = self.parent.get_screen() self.card.reparentTo(screen.getParent()) self.card.setTransform(screen.getTransform()) self.card.setSx(0.49) self.card.setSz(0.394) self.card.setHpr(0, 270, 0) self.card.setPos(0.004, 0.335, 0.1) self.card.hide() def activate(self, events): self.toggle_view(True) events.add_action("boton_izq1", self.quit) events.add_action("centro", self.shoot) events.add_action("boton_der", self.shoot) events.add_action("boton_izq", self.cancel) def shoot(self): if self.video_mode: max = self.texture.getXSize() * self.texture.getYSize() data = array.array('B') data.fromstring(self.texture.getRamImageAs("BGR1").getData()) img = cairo.ImageSurface.create_for_data( data, cairo.FORMAT_ARGB32, self.texture.getXSize(), self.texture.getYSize(), self.texture.getXSize() * 4) self.cam_shot = cairo.ImageSurface(cairo.FORMAT_ARGB32, self.texture.getVideoWidth(), self.texture.getVideoHeight()) ctx = cairo.Context(self.cam_shot) ctx.set_source_surface(img, 0, 0) ctx.paint() self.paint_background() self.cr.set_source_surface(self.draw_viewer(self.cam_shot), 30, self.top_margin + 5) self.cr.paint() self.paint_foreground() self.surface.write_to_png(self.get_output()) self.parent.repaint() self.toggle_view(False) else: print "Saving..." pic_path = CameraApp.__ImageDir + "/p" + Util.generate_id( ) + ".png" print pic_path self.cam_shot.write_to_png(pic_path) self.toggle_view(True) def paint_scene(self): drawer_width = self.width - 60 drawer_height = 2 * self.height / 3 surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, self.width, self.height) context = cairo.Context(surface) scale_x = float(self.width) / float(self.cam_shot.get_width()) scale_y = float(self.height) / float(self.cam_shot.get_height()) context.scale(scale_x, scale_y) context.set_source_surface(self.cam_shot, 0, 0) context.paint() return surface def cancel(self): self.cam_shot = None self.toggle_view(True) def draw_viewer(self, image_surface): drawer_width = self.width - 60 drawer_height = 2 * self.height / 3 surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, drawer_width, drawer_height) context = cairo.Context(surface) context.rectangle(0, 0, drawer_width, drawer_height) context.set_source_rgba(.05, .05, .05, .8) context.fill() context.rectangle(1, 1, drawer_width - 2, drawer_height - 2) context.clip() context.new_path() context.transform( get_transformation_matrix(drawer_width, drawer_height, image_surface.get_width(), image_surface.get_height())) context.set_source_surface(image_surface, 0, 0) context.paint() return surface def paint_background(self): # Fondo gradient = cairo.LinearGradient(0, 0, 0, self.height) gradient.add_color_stop_rgb(0, 0, 0, 0) gradient.add_color_stop_rgb(1, .4, .4, .4) self.cr.set_source(gradient) self.cr.move_to(0, 0) self.cr.line_to(self.width, 0) self.cr.line_to(self.width, self.height) self.cr.line_to(0, self.height) self.cr.close_path() self.cr.fill() def quit(self): self.toggle_view(False) self.parent.launch("menu") def toggle_view(self, video): self.video_mode = video if video: #self.texture.fromCamera() self.card.setTexture(self.texture) print(self.texture.getVideoWidth(), self.texture.getVideoHeight()) self.card.show() self.parent.get_screen().hide() else: #self.texture = OpenCVTexture() self.card.setTexture(self.texture) self.card.hide() self.parent.get_screen().show()
def placePlantOnTerrain(self, itemStr, itemCnt, Mode, typItemWidth, typItemHeight, trrHorzSc, trrVertSc, numTxtTypes, txtList, planFileName): # Billboarding plants crd = CardMaker('mycard') crd.setColor(0.5, 0.5, 0.5, 1) ll = Point3(-0.5 * typItemWidth, 0, 0) lr = Point3(0.5 * typItemWidth, 0, 0) ur = Point3(0.5 * typItemWidth, 0, typItemHeight) ul = Point3(-0.5 * typItemWidth, 0, typItemHeight) crd.setFrame(ll, lr, ur, ul) crd.setHasNormals(False) crd.setHasUvs(True) # generate/save/load locations try: plan_data_fp = open(planFileName, 'r') item_list = [] for line in plan_data_fp: toks = line.split(',') px = float(toks[0].strip(' ')) py = float(toks[1].strip(' ')) ang = float(toks[2].strip(' ')) dht = float(toks[3].strip(' ')) scl = float(toks[4].strip(' ')) idx = int(toks[5].strip(' ')) item_list.append((px, py, ang, dht, scl, idx)) plan_data_fp.close() print 'loaded ', itemStr, ' data file of size:', len(item_list) except IOError: # generate list and try to save item_list = [] for a in range(itemCnt): px = random.randrange(-self.trrHorzSc * 64, self.trrHorzSc * 64) py = random.randrange(-self.trrHorzSc * 64, self.trrHorzSc * 64) ang = 180 * random.random() dht = 0.0 scl = 0.75 + 0.25 * (random.random() + random.random()) idx = random.randrange(0, numTxtTypes) item_list.append([px, py, ang, dht, scl, idx]) try: plan_data_fp = open(planFileName, 'w') for c in item_list: print >> plan_data_fp, c[0], ',', c[1], ',', c[2], ',', c[ 3], ',', c[4], ',', c[5] plan_data_fp.close() print 'saved ', itemStr, ' data of size: ', len(item_list) except IOError: print 'unable to store ', itemStr, ' data of size: ', len( item_list) # define each plant for c in item_list: px = c[0] py = c[1] ang = c[2] dht = c[3] scl = c[4] idx = c[5] if idx >= numTxtTypes: idx = 0 if Mode > 0: for b in range(Mode): crdNP = self.render.attachNewNode(crd.generate()) crdNP.setTexture(txtList[idx]) crdNP.setScale(scl) crdNP.setTwoSided(True) ht = self.terrain.getElevation(px / trrHorzSc, py / trrHorzSc) crdNP.setPos(px, py, ht * trrVertSc + dht) crdNP.setHpr(ang + (180 / Mode) * b, 0, 0) crdNP.setTransparency(TransparencyAttrib.MAlpha) crdNP.setLightOff() else: # set up item as defined crd.setUvRange(txtList[idx]) crdNP = self.render.attachNewNode(crd.generate()) crdNP.setBillboardAxis() crdNP.setTexture(txtList[idx]) crdNP.setScale(scl) ht = self.terrain.getElevation(px / trrHorzSc, py / trrHorzSc) crdNP.setPos(px, py, ht * trrVertSc) crdNP.setTransparency(TransparencyAttrib.MAlpha) crdNP.setLightOff()
class CameraApp(GuiHandler): __ImageDir = "data/images" def __init__(self, device): GuiHandler.__init__(self) self.func3 = "Si" self.func2 = "" self.func1 = "No" self.title = "Guardar?" self.parent = device self.video_mode = False option = WebcamVideo.get_option(0) self.texture = MovieTexture(option) self.texture.setKeepRamImage(True) #self.texture = OpenCVTexture() #self.texture.fromCamera() scale = self.texture.getTexScale() print scale #self.texture = OpenCVTexture() self.card = CardMaker('webcam') self.card.setFrame(-scale[0], scale[0], -scale[1], scale[1]) self.card.setUvRange(Point2(scale[0], 0), Point2(0, scale[1])) self.card = render.attachNewNode(self.card.generate()) screen = self.parent.get_screen() self.card.reparentTo(screen.getParent()) self.card.setTransform(screen.getTransform()) self.card.setSx(0.49) self.card.setSz(0.394) self.card.setHpr(0, 270, 0) self.card.setPos(0.004, 0.335, 0.1) self.card.hide() def activate(self, events): self.toggle_view(True) events.add_action("boton_izq1", self.quit) events.add_action("centro", self.shoot) events.add_action("boton_der", self.shoot) events.add_action("boton_izq", self.cancel) def shoot(self): if self.video_mode: max = self.texture.getXSize() * self.texture.getYSize() data = array.array('B') data.fromstring(self.texture.getRamImageAs("BGR1").getData()) img = cairo.ImageSurface.create_for_data(data, cairo.FORMAT_ARGB32, self.texture.getXSize(), self.texture.getYSize(), self.texture.getXSize() * 4) self.cam_shot = cairo.ImageSurface(cairo.FORMAT_ARGB32, self.texture.getVideoWidth(), self.texture.getVideoHeight()) ctx = cairo.Context(self.cam_shot) ctx.set_source_surface(img, 0 , 0) ctx.paint() self.paint_background() self.cr.set_source_surface(self.draw_viewer(self.cam_shot), 30, self.top_margin + 5) self.cr.paint() self.paint_foreground() self.surface.write_to_png(self.get_output()) self.parent.repaint() self.toggle_view(False) else: print "Saving..." pic_path = CameraApp.__ImageDir + "/p" + Util.generate_id() + ".png" print pic_path self.cam_shot.write_to_png(pic_path) self.toggle_view(True) def paint_scene(self): drawer_width = self.width - 60 drawer_height = 2 * self.height / 3 surface = cairo.ImageSurface (cairo.FORMAT_ARGB32, self.width, self.height) context = cairo.Context(surface) scale_x = float(self.width) / float(self.cam_shot.get_width()) scale_y = float(self.height) / float(self.cam_shot.get_height()) context.scale(scale_x, scale_y) context.set_source_surface(self.cam_shot, 0, 0) context.paint() return surface def cancel(self): self.cam_shot = None self.toggle_view(True) def draw_viewer(self, image_surface): drawer_width = self.width - 60 drawer_height = 2 * self.height / 3 surface = cairo.ImageSurface (cairo.FORMAT_ARGB32, drawer_width, drawer_height) context = cairo.Context(surface) context.rectangle(0, 0, drawer_width, drawer_height) context.set_source_rgba(.05, .05, .05, .8) context.fill() context.rectangle(1, 1, drawer_width - 2, drawer_height - 2) context.clip() context.new_path() context.transform(get_transformation_matrix(drawer_width, drawer_height, image_surface.get_width(), image_surface.get_height())) context.set_source_surface(image_surface, 0, 0) context.paint() return surface def paint_background(self): # Fondo gradient = cairo.LinearGradient(0, 0, 0, self.height) gradient.add_color_stop_rgb(0, 0, 0, 0) gradient.add_color_stop_rgb(1, .4, .4, .4) self.cr.set_source(gradient) self.cr.move_to(0, 0) self.cr.line_to(self.width, 0) self.cr.line_to(self.width, self.height) self.cr.line_to(0, self.height) self.cr.close_path() self.cr.fill() def quit(self): self.toggle_view(False) self.parent.launch("menu") def toggle_view(self, video): self.video_mode = video if video: #self.texture.fromCamera() self.card.setTexture(self.texture) print (self.texture.getVideoWidth(), self.texture.getVideoHeight()) self.card.show() self.parent.get_screen().hide() else: #self.texture = OpenCVTexture() self.card.setTexture(self.texture) self.card.hide() self.parent.get_screen().show()
def __init__(self): ShowBase.__init__(self) props = WindowProperties() props.setTitle('Differentiable Physics Engine') self.win.requestProperties(props) self.t = 0 self.starttime = time.time() #self.setFrameRateMeter(True) cour = self.loader.loadFont('cmtt12.egg') self.textObject = None #OnscreenText(font= cour, text = 'abcdefghijklmnopqrstuvwxyz', pos=(0, -0.045), parent = self.a2dTopCenter, bg=(0,0,0,0.5), fg =(1,1,1,1), scale = 0.07, mayChange=True) cm = CardMaker("ground") cm.setFrame(-2000, 2000, -2000, 2000) cm.setUvRange(Point2(-2000 / 5, -2000 / 5), Point2(2000 / 5, 2000 / 5)) tmp = self.render.attachNewNode(cm.generate()) tmp.reparentTo(self.render) self.camLens.setNear(0.1) tmp.setPos(0, 0, 0) tmp.lookAt((0, 0, -2)) tmp.setColor(1.0, 1.0, 1.0, 0.) tmp.setTexScale(TextureStage.getDefault(), 1, 1) tex = self.loader.loadTexture('textures/grid2.png') tex.setWrapU(Texture.WMRepeat) tex.setWrapV(Texture.WMRepeat) tmp.setTexture(tex, 1) self.setBackgroundColor(0.0, 191.0 / 255.0, 1.0, 1.0) #color of the sky ambientLight = AmbientLight('ambientLight') ambientLight.setColor(Vec4(0.2, 0.2, 0.2, 1)) ambientLightNP = self.render.attachNewNode(ambientLight) self.render.setLight(ambientLightNP) # Directional light 01 directionalLight = DirectionalLight('directionalLight') directionalLight.setColor(Vec4(0.8, 0.8, 0.8, 1)) directionalLightNP = self.render.attachNewNode(directionalLight) # This light is facing backwards, towards the camera. directionalLightNP.setHpr(-120, -50, 0) directionalLightNP.node().setScene(self.render) directionalLightNP.node().setShadowCaster(True) directionalLightNP.node().getLens().setFov(40) directionalLightNP.node().getLens().setNearFar(10, 100) self.render.setLight(directionalLightNP) # Add the spinCameraTask procedure to the task manager. self.taskMgr.add(self.spinCameraTask, "SpinCameraTask") self.physics = Rigid3DBodyEngine() # Load the environment model. self.objects = dict() #self.load_robot_model("robotmodel/test.json") #self.load_robot_model("robotmodel/predator.json") #self.load_robot_model("robotmodel/full_predator.json") #self.load_robot_model("robotmodel/demi_predator.json") #self.load_robot_model("robotmodel/ball.json") self.load_robot_model("robotmodel/robot_arm.json") #self.load_robot_model("robotmodel/robot_arm_mini.json") self.physics.compile() self.step = np.zeros(shape=(16, ))
import gizeh as gz import random s = ShowBase() image_x_size = 512 image_y_size = 512 # Quad in scene, to display the image on input_img = PNMImage(image_x_size, image_y_size) # It's RGB. input_tex = Texture() input_tex.load(input_img) card = CardMaker('in_scene_screen') card.setUvRange( Point2(0, 1), # ll Point2(1, 1), # lr Point2(1, 0), # ur Point2(0, 0)) # ul screen = render.attach_new_node(card.generate()) screen.set_pos(-0.5, 2, -0.5) screen.set_texture(input_tex) # Gizeh setup surface = gz.Surface(image_x_size, image_y_size) def update_gizeh_image(): star1 = gz.star(radius=70, ratio=.4, fill=(1, 1, 1), angle=-np.pi / 2,