def frame_adjust( self ): # FIXME sometimes this fails to call, also calls too often at startup self.setTextHeight() MI = self.getMaxItems() # does not count title >_< LI = len(self.items) DI = MI - LI if DI >= 0: for i in range(DI + 1): self.__create_item__(' blank') else: for i in range(-(DI + 1)): k, v = self.items.popitem() # remove the last nodes in order v.removeNode() # FIXME consider keeping these around? for k, b in self.items.items(): if k == 'title': if self.frame_bg.isHidden(): x, y, z = self.frame_bg.getPos() self.title_button.setPos(LVecBase3f(x, y, z - self.text_h)) else: self.title_button.setPos(LVecBase3f(0, 0, -self.text_h)) elif k == self.__first_item__: b.setPos(LVecBase3f(0, 0, -(self.text_h * 2))) else: b.setPos(LVecBase3f(0, 0, -self.text_h)) b['frameSize'] = 0, self.width, 0, self.text_h b['text_scale'] = self.text_s, self.text_s b['text_pos'] = 0, self.text_h - self.TEXT_MAGIC_NUMBER * self.text_s
def __init__(self, rootParent=None): self.frmMain = DirectFrame( frameColor=(1, 1, 1, 1), frameSize=(-1, 1, -1, 1), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0, 0, 0), parent=rootParent, ) self.frmMain.setTransparency(0) self.waitbar = DirectWaitBar( barColor=(0.0, 0.0, 1.0, 1.0), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0, 0, 0), state='normal', text='0%', value=50.0, text_align=TextNode.A_center, text_scale=(0.1, 0.1), text_pos=(0, -0.025), text_fg=LVecBase4f(0, 0, 0, 1), text_bg=LVecBase4f(0, 0, 0, 0), parent=self.frmMain, ) self.waitbar.setTransparency(0)
def __do_reset(self): # self.mEnabled = False self.mForward = self.mBackward = self.mStrafeLeft = self.mStrafeRight = self.mUp = self.mDown = \ self.mHeadLeft = self.mHeadRight = self.mPitchUp = self.mPitchDown = False #by default we consider mouse moved on every update, because #we want mouse poll by default this can be changed by calling #the enabler (for example by an handler responding to mouse-move #event if it is possible. See: http:#www.panda3d.org/forums/viewtopic.php?t=9326 # http:#www.panda3d.org/forums/viewtopic.php?t=6049) self.mMouseMove = True self.mForwardKey = self.mBackwardKey = self.mStrafeLeftKey = self.mStrafeRightKey = self.mUpKey = self.mDownKey = \ self.mHeadLeftKey = self.mHeadRightKey = self.mPitchUpKey = self.mPitchDownKey = \ self.mMouseMoveKey = False self.mSpeedKey = "shift" self.mMouseEnabledH = self.mMouseEnabledP = self.mHeadLimitEnabled = self.mPitchLimitEnabled = \ False self.mHLimit = self.mPLimit = 0.0 self.mSignOfTranslation = self.mSignOfMouse = 1 self.mFastFactor = 0.0 self.mActualSpeedXYZ = self.mMaxSpeedXYZ = self.mMaxSpeedSquaredXYZ = LVecBase3f() self.mActualSpeedH = self.mActualSpeedP = self.mMaxSpeedHP = self.mMaxSpeedSquaredHP = 0.0 self.mAccelXYZ = LVecBase3f() self.mAccelHP = 0.0 self.mFrictionXYZ = self.mFrictionHP = 0.0 self.mStopThreshold = 0.0 self.mSensX = self.mSensY = 0.0 self.mCentX = self.mCentY = 0.0
def __init__(self, rootParent=None): self.frmMain = DirectFrame( frameColor=(0.0, 0.0, 0.0, 0.5), frameSize=(-1, 1, -1, 1), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0, 0, 0), parent=rootParent, ) self.frmMain.setTransparency(0) self.lblVictory = DirectLabel( frameColor=(0.0, 0.0, 0.0, 0.0), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0, 0, 0), scale=LVecBase3f(0.2, 0.2, 0.2), text='Won Fight', text_align=TextNode.A_center, text_scale=(1, 1), text_pos=(0, 0), text_fg=LVecBase4f(1, 1, 1, 1), text_bg=LVecBase4f(0, 0, 0, 0), parent=self.frmMain, ) self.lblVictory.setTransparency(0)
def __init__(self, rootParent=None): self.overlay = DirectFrame( frameColor=(1.0, 1.0, 1.0, 0.0), frameSize=(-1, 1, -1, 1), hpr=LVecBase3f(0, 0, 0), image='chapter4/overlay.png', pos=LPoint3f(0, 0, 0), sortOrder=200, image_scale=LVecBase3f(0.8, 1, 0.8), image_pos=LPoint3f(0, 0, 0), parent=rootParent, ) self.overlay.setTransparency(1) self.newspaper = DirectFrame( frameColor=(1.0, 1.0, 1.0, 0.0), frameSize=(-1, 1, -1, 1), hpr=LVecBase3f(0, 0, 0), image='chapter4/newspaperA.png', pos=LPoint3f(0, 0, 0), sortOrder=200, image_scale=LVecBase3f(0.5, 1, 0.5), image_pos=LPoint3f(0, 0, 0), parent=rootParent, ) self.newspaper.setTransparency(1)
def __init__(self, rootParent=None): self.btnEndTurn = DirectButton( borderWidth=(0.0, 0.0), frameColor=(0.8, 0.8, 0.8, 0.0), frameSize=(-3.0, 3.0, -1.0, 1.0), hpr=LVecBase3f(0, 0, 0), image='./assets/Turn/EndTurn.png', pos=LPoint3f(0, 0, 0.1), relief=1, scale=LVecBase3f(0.1, 0.1, 0.1), text='End Turn', image_scale=LVecBase3f(3, 0, 1), image_pos=LPoint3f(0, 0, 0), text_align=TextNode.A_center, text_scale=(1.0, 1.0), text_pos=(0.0, -0.3), text_fg=LVecBase4f(1, 1, 1, 1), text_bg=LVecBase4f(0, 0, 0, 0), parent=rootParent, command=base.messenger.send, extraArgs=["endTurn"], pressEffect=0, ) self.btnEndTurn.setTransparency(1)
def setPos(self, x, y): """ actually sets the title button position since it is really the parent node """ self.x = x self.y = y #- self.text_h # FIXME is hard :/ self.frame_bg.setPos(LVecBase3f(x, 0, y)) if self.frame_bg.isHidden(): self.title_button.setPos(LVecBase3f(x, 0, y - self.text_h))
def testStep(self): scene = SunCgSceneLoader.loadHouseFromJson( "0004d52d1aeeb8ae6de39d6bd993e992", TEST_SUNCG_DATA_DIR) agentNp = scene.agents[0] agentNp.setPos(LVecBase3f(45, -42.5, 1.6)) agentNp.setHpr(45, 0, 0) # Define a sound source sourceSize = 0.25 modelId = 'source-0' modelFilename = os.path.join(TEST_DATA_DIR, 'models', 'sphere.egg') objectsNp = scene.scene.attachNewNode('objects') objectsNp.setTag('acoustics-mode', 'source') objectNp = objectsNp.attachNewNode('object-' + modelId) model = loadModel(modelFilename) model.setName('model-' + modelId) model.setTransform(TransformState.makeScale(sourceSize)) model.reparentTo(objectNp) objectNp.setPos(LVecBase3f(39, -40.5, 1.5)) samplingRate = 16000.0 hrtf = CipicHRTF(os.path.join(TEST_DATA_DIR, 'hrtf', 'cipic_hrir.mat'), samplingRate) acoustics = EvertAcoustics(scene, hrtf, samplingRate, maximumOrder=2, maxBufferLength=30.0) # Attach sound to object filename = os.path.join(TEST_DATA_DIR, 'audio', 'toilet.ogg') sound = EvertAudioSound(filename) acoustics.attachSoundToObject(sound, objectNp) sound.setLoop(True) sound.setLoopCount(1) sound.play() for i, dt in enumerate([5.0, 20.0, 10.0]): acoustics.step(dt) if i == 0: self.assertTrue(sound.status() == AudioSound.PLAYING) elif i > 1: self.assertTrue(sound.status() == AudioSound.READY) inbuf = acoustics.srcBuffers[sound] outbuf = acoustics.outBuffers[agentNp.getName()] fig = plt.figure() plt.subplot(121) plt.plot(inbuf) plt.subplot(122) plt.plot(outbuf.T) plt.show(block=False) time.sleep(4.0) plt.close(fig)
def __create_item__(self, text, command=None, args=tuple()): args = list(args) #if not len(self.items): #parent = self.frame if len(self.items) <= 1: parent = self.itemsParent #everyone else parents off 2nd text else: parent = list(self.items.values())[-1] if command != None: def cmd(*args): """ any item should raise """ self.raise_() command(*args) else: cmd = self.raise_ b = DirectButton( parent=parent, frameColor=(1, 1, 1, .0), # a = 0 => no border overlap frameSize=(0, self.width, 0, self.text_h), text=' ' + text, # hack to keep spacing from border text_font=self.text_font, text_fg=self.text_color, text_scale=self.text_s, text_pos=(0, self.text_h - self.TEXT_MAGIC_NUMBER * self.text_s), command=cmd, relief=DGG.FLAT, text_align=TextNode.ALeft, ) b.setPos(LVecBase3f(0, 0, -self.text_h)) b.setName('DirectButton-' + text) if not len(self.items): self.items['title'] = b b.setBin(*self.DRAW_ORDER['title']) else: b['extraArgs'] = args + [self, id(b)] b.node().setPythonTag('id', id(b)) b.setBin(*self.DRAW_ORDER['items']) if len(self.items) is 1: # the first item that is not the title b.setPos(LVecBase3f(0, 0, -(self.text_h * 2))) self.__first_item__ = id(b) self.items[id(b)] = b if text == ' blank': if self.__add_head__ is None: self.__add_head__ = 1 return b
def rotateSO(self, x, y, z): if self.nodePath != None: self.eAng = [x, y, z] a0v = LVecBase3f(self.a0[0], self.a0[1], self.a0[2]) a1v = LVecBase3f(self.a1[0], self.a1[1], self.a1[2]) a2v = LVecBase3f(self.a2[0], self.a2[1], self.a2[2]) mat3 = LMatrix3f(a0v, a1v, a2v) mato = LMatrix4f(mat3) self.nodePath.setMat(mato) self.nodePath.setPos(self.pos[0], self.pos[1], self.pos[2]) #Why would the center of rotation be the first corner ? #self.nodePath.setHpr(0,0,90) else: print('Non-existing Node Path to rotate')
def animateEnemyDraw(card, duration=0.3): hand = base.zoneMaker.enemyHand card.setPos(base.zoneMaker.enemyFace, 0, 0, 0) card.wrtReparentTo(hand) if base.bothPlayersMulliganed: fan = fanHand(len(base.enemy.hand) + 1)[-1] else: fan = (len(base.enemy.hand) * 1.1 / 2, 0, 0, 0, 0, 0) pos, hpr = fan[:3], fan[3:] newPos = LVecBase3f(*pos) newHpr = LVecBase3f(*hpr) return Sequence(Parallel(card.posInterval(duration / 2, newPos), card.hprInterval(duration / 2, newHpr)))
def __init__(self, rootParent=None): self.volume = DirectSlider( pos=LPoint3f(0.2, 0, 0.325), text='Volume', text_pos=(-1.05, -0.02), text_fg=(1, 1, 1, 1), text_scale=0.1, text_align=TextNode.ARight, parent=rootParent, command=base.messenger.send, extraArgs=["volumeChange"], ) self.volume.setTransparency(0) self.audioMute = DirectCheckButton( frameSize=(-2.925000047683716, 3.024999713897705, -0.225, 0.8250000238418579), pos=LPoint3f(0, 0, 0), scale=LVecBase3f(0.1, 0.1, 0.1), text='Mute', parent=rootParent, command=self.toggleMute, ) self.audioMute.setTransparency(0) self.btnBack = DirectButton( frameSize=(-1.5249999523162843, 1.6499999523162843, -0.21250001192092896, 0.8250000238418579), pos=LPoint3f(0, 0, -0.575), scale=LVecBase3f(0.1, 0.1, 0.1), text='Back', parent=rootParent, command=base.messenger.send, extraArgs=["optionBack"], pressEffect=1, ) self.btnBack.setTransparency(0) self.fullscreen = DirectCheckButton( frameSize=(-3.35, 2.6, -0.213, 0.825), pos=LPoint3f(0.045, 0, -0.175), scale=LVecBase3f(0.1, 0.1, 0.1), text='Fullscreen', parent=rootParent, command=self.toggleFullscreen, ) self.fullscreen.setTransparency(0)
def testMultipleSources(self): scene = SunCgSceneLoader.loadHouseFromJson( "0004d52d1aeeb8ae6de39d6bd993e992", TEST_SUNCG_DATA_DIR) agentNp = scene.agents[0] agentNp.setPos(LVecBase3f(45, -42.5, 1.6)) agentNp.setHpr(45, 0, 0) # Define multiple sound sources sources = [] for i, pos in enumerate([(39, -40.5, 1.5), (45.5, -42.5, 0.5)]): sourceSize = 0.25 modelId = 'source-%d' % (i) modelFilename = os.path.join(TEST_DATA_DIR, 'models', 'sphere.egg') objectsNp = scene.scene.attachNewNode('objects') objectsNp.setTag('acoustics-mode', 'source') objectNp = objectsNp.attachNewNode('object-' + modelId) model = loadModel(modelFilename) model.setName('model-' + modelId) model.setTransform(TransformState.makeScale(sourceSize)) model.reparentTo(objectNp) objectNp.setPos(LVecBase3f(*pos)) sources.append(objectNp) samplingRate = 16000.0 hrtf = CipicHRTF(os.path.join(TEST_DATA_DIR, 'hrtf', 'cipic_hrir.mat'), samplingRate) acoustics = EvertAcoustics(scene, hrtf, samplingRate, maximumOrder=2) audioFilenames = ['toilet.ogg', 'radio.ogg'] for audioFilename, source in zip(audioFilenames, sources): # Attach sound to object filename = os.path.join(TEST_DATA_DIR, 'audio', audioFilename) sound = EvertAudioSound(filename) acoustics.attachSoundToObject(sound, source) sound.setLoop(True) sound.setLoopCount(1) sound.play() for _ in range(20): acoustics.step(dt=0.1) obs = acoustics.getObservationsForAgent(agentNp.getName()) self.assertTrue('audio-buffer-right' in obs) self.assertTrue('audio-buffer-left' in obs) self.assertTrue( np.array_equal(obs['audio-buffer-right'].shape, obs['audio-buffer-left'].shape))
def getCollisionInfo(self, root, dt): result = self.bulletWorld.contactTest(root.node()) force = 0.0 relativePosition = LVecBase3f(0.0, 0.0, 0.0) isCollisionDetected = False for _ in result.getContacts(): # Iterate over all manifolds of the world # NOTE: it seems like the contact manifold doesn't hold the information # to calculate contact force. We need the persistent manifolds for that. for manifold in self.bulletWorld.getManifolds(): # Check if the root node is part of that manifold, by checking positions # TODO: there is surely a better way to compare the two nodes here #if (manifold.getNode0().getTransform().getPos() == root.getNetTransform().getPos()): if manifold.getNode0().getTag('model-id') == root.getTag( 'model-id'): # Calculate the to totalImpulse = 0.0 maxImpulse = 0.0 for pt in manifold.getManifoldPoints(): impulse = pt.getAppliedImpulse() totalImpulse += impulse if impulse > maxImpulse: maxImpulse = impulse relativePosition = pt.getLocalPointA() force = totalImpulse / dt isCollisionDetected = True return force, relativePosition, isCollisionDetected
def testUpdate(self): scene = SunCgSceneLoader.loadHouseFromJson( "0004d52d1aeeb8ae6de39d6bd993e992", TEST_SUNCG_DATA_DIR) agentNp = scene.agents[0] agentNp.setPos(LVecBase3f(45, -42.5, 1.6)) agentNp.setHpr(45, 0, 0) samplingRate = 16000.0 hrtf = CipicHRTF(os.path.join(TEST_DATA_DIR, 'hrtf', 'cipic_hrir.mat'), samplingRate) acoustics = EvertAcoustics(scene, hrtf, samplingRate, maximumOrder=2, maxBufferLength=30.0) # Add ambient sound filename = os.path.join(TEST_DATA_DIR, 'audio', 'radio.ogg') ambientSound = EvertAudioSound(filename) ambientSound.setLoop(True) ambientSound.setLoopCount(0) acoustics.addAmbientSound(ambientSound) ambientSound.play() acoustics.step(0.0) player = AudioPlayer(acoustics) for _ in range(10): taskMgr.step()
def calculate2dNavigationMap(self, agent, z=0.1, precision=0.1, yup=True): agentRbNp = agent.find('**/+BulletRigidBodyNode') # Calculate the bounding box of the scene bounds = [] for nodePath in self.scene.scene.findAllMatches('**/object*/+BulletRigidBodyNode'): node = nodePath.node() # NOTE: the bounding sphere doesn't seem to take into account the transform, # so apply it manually (translation only) bsphere = node.getShapeBounds() center = nodePath.getNetTransform().getPos() bounds.extend([center + bsphere.getMin(), center + bsphere.getMax()]) minBounds, maxBounds = np.min(bounds, axis=0), np.max(bounds, axis=0) # Using the X and Y dimensions of the bounding box, # discretize the 2D plan into a uniform grid with given precision X = np.arange(minBounds[0], maxBounds[0], step=precision) Y = np.arange(minBounds[1], maxBounds[1], step=precision) nbTotalCells = len(X) * len(Y) threshold10Perc = int(nbTotalCells / 10) # XXX: the simulation needs to be run a little before moving the agent, # not sure why self.bulletWorld.doPhysics(0.1) # Sweep the position of the agent across the grid, # checking if collision/contacts occurs with objects or walls in the # scene. occupancyMap = np.zeros((len(X), len(Y))) occupancyMapCoord = np.zeros((len(X), len(Y), 2)) n = 0 for i, x in enumerate(X): for j, y in enumerate(Y): agentRbNp.setPos(LVecBase3f(x, y, z)) if self.isCollision(agentRbNp): occupancyMap[i, j] = 1.0 occupancyMapCoord[i, j, 0] = x occupancyMapCoord[i, j, 1] = y n += 1 if n % threshold10Perc == 0: logger.debug( 'Collision test no.%d (out of %d total)' % (n, nbTotalCells)) if yup: # Convert to image format (y,x) occupancyMap = np.flipud(occupancyMap.T) occupancyMapCoord = np.flipud( np.transpose(occupancyMapCoord, axes=(1, 0, 2))) return occupancyMap, occupancyMapCoord
def densityFunction(x, y, z): point = LVecBase3f(x, y, z) warpfactor = 0.0004 warp = warpNoise(LVecBase3f(x*warpfactor, y*warpfactor, z*warpfactor)) * 8 point.componentwiseMult(LVecBase3f(warp, warp, warp)) density = -point.z floor = 4 ω = [16.03, 8.05, 4.03, 1.96, 1.01, 0.49, 0.23, 0.097] # frequencies A = [0.25, 0.25, 0.5, 0.5, 1, 2, 8, 32] # amplitudes for i in range(len(ω)): ωVec = LVecBase3f(ω[i], ω[i], ω[i]) ωVec.componentwiseMult(point) density += noise(ωVec) * A[i] density += max(min((floor - point.z)*3, 1), 0)*40; return density
def __init__(self, rootParent=None): self.frmMain = DirectFrame( frameColor=(0.25, 0.25, 0.25, 1.0), frameSize=(0.0, 2.0, -0.1, 0.0), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0, 0, 0), parent=rootParent, ) self.frmMain.setTransparency(0) self.btnLeave = DirectButton( hpr=LVecBase3f(0, 0, 0), pad=(0.1, 0.1), pos=LPoint3f(0.115, 0, -0.075), relief=1, scale=LVecBase3f(0.1, 0.1, 0.1), text='Leave', text_align=TextNode.A_center, text_scale=(0.75, 0.75), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0, 1), text_bg=LVecBase4f(0, 0, 0, 0), parent=self.frmMain, command=base.messenger.send, extraArgs=["leaveRoom"], ) self.btnLeave.setTransparency(0) self.lblPlayerName = DirectLabel( frameColor=(0.8, 0.8, 0.8, 0.0), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0.55, 0, -0.075), scale=LVecBase3f(0.1, 0.1, 0.1), text='Label', text_align=TextNode.A_left, text_scale=(0.75, 0.75), text_pos=(0, 0), text_fg=LVecBase4f(0.8, 0.8, 0.8, 1), text_bg=LVecBase4f(0, 0, 0, 0), parent=self.frmMain, ) self.lblPlayerName.setTransparency(0) self.pg1983 = DirectLabel( frameColor=(0.8, 0.8, 0.8, 0.0), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0.42, 0, -0.075), scale=LVecBase3f(0.1, 0.1, 0.1), text='Name:', text_align=TextNode.A_center, text_scale=(0.75, 0.75), text_pos=(0, 0), text_fg=LVecBase4f(0.6, 0.6, 0.6, 1), text_bg=LVecBase4f(0, 0, 0, 0), parent=self.frmMain, ) self.pg1983.setTransparency(0)
def setLinearVelocity(self, linearVelocity): # Apply the local transform to the velocity agentRbNp = self._getAgentNode() rotMat = agentRbNp.node().getTransform().getMat().getUpper3() linearVelocity = rotMat.xformVec( LVecBase3f(linearVelocity[0], linearVelocity[1], linearVelocity[2])) linearVelocity.z = 0.0 agentRbNp.node().setLinearVelocity(linearVelocity) agentRbNp.node().setActive(True, 1)
def setAgentLinearVelocity(self, linearVelocity): # Apply the local transform to the velocity # XXX: use BulletCharacterControllerNode class, which already handles local transform? rotMat = self.agentRbNp.node().getTransform().getMat().getUpper3() linearVelocity = rotMat.xformVec( LVecBase3f(linearVelocity[0], linearVelocity[1], linearVelocity[2])) linearVelocity.z = 0.0 self.agentRbNp.node().setLinearVelocity(linearVelocity) self.agentRbNp.node().setActive(True, 1)
def getNodePosition(depth, breadth): if Utils.VERTICAL_DEPTH: x = breadth * Utils.VERT_BREADTH_DIST y = float(depth) * Utils.VERT_DEPTH_DIST else: y = breadth * Utils.HORT_BREADTH_DIST x = float(depth) * Utils.HORT_DEPTH_DIST z = 0 # Should be addressed later on return LVecBase3f(x, y, z)
def __init__(self, rootParent=None): self.frmMain = DirectFrame( frameColor=(0.0, 0.0, 0.0, 0.75), frameSize=(-1, 1, -1, 1), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0, 0, 0), parent=rootParent, ) self.frmMain.setTransparency(1) self.btnQuit = DirectButton( hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0, 0, -0.75), scale=LVecBase3f(0.1, 0.1, 0.1), text='Quit', text_align=TextNode.A_center, text_scale=(1, 1), text_pos=(0, 0), text_fg=LVecBase4f(0, 0, 0, 1), text_bg=LVecBase4f(0, 0, 0, 0), parent=self.frmMain, command=base.messenger.send, extraArgs=["quitRoom"], pressEffect=1, ) self.btnQuit.setTransparency(0) self.lblMessage = DirectLabel( frameColor=(0.0, 0.0, 0.0, 0.0), frameSize=(-2.981, 3.106, -0.325, 0.725), hpr=LVecBase3f(0, 0, 0), pos=LPoint3f(0, 0, 0), scale=LVecBase3f(0.2, 0.2, 0.2), text='Player A Won', text_align=TextNode.A_center, text_scale=(1.0, 1.0), text_pos=(0, 0), text_fg=LVecBase4f(1, 1, 1, 1), text_bg=LVecBase4f(0, 0, 0, 0), parent=self.frmMain, ) self.lblMessage.setTransparency(0)
def __del_item__(self, index): """ I have no idea how this is going to work """ out = self.items[index] p = out.getParent() if out.getNumChildren(): # avoid the printing of the AssertionError :/ c = out.getChild(0) c.reparentTo(p) if index == self.__first_item__: # XXX is fails, ints from id != c.setPos(LVecBase3f(out.getPos())) id_ = c.getPythonTag('id') self.__first_item__ = id_ out.setPos(LVecBase3f(0, 0, -self.text_h)) self.items.pop(index) parent = list(self.items.values())[-1] out['text'] = ' del blank' #out['command'] = None out['extraArgs'] = [self, index] out.reparentTo(parent) self.items[index] = out if self.__add_head__ > 1: # title is always at 0 self.__add_head__ -= 1
def watchCanvasProps(self, task): """Watch for all properties that can be changed on the canvas and won't directly propagate down to the actual background, which is the element holder.""" self.sizer.refresh() sizeChanged = False cs = self.getEditorCanvasSize() if self.canvasLeft != cs[0]: sizeChanged = True elif self.canvasRight != cs[1]: sizeChanged = True elif self.canvasBottom != cs[2]: sizeChanged = True elif self.canvasTop != cs[3]: sizeChanged = True if sizeChanged: width = cs[1] - cs[0] height = cs[3] - cs[2] self.canvasScale = min(width, height) if self.currentVisEditorParent == base.pixel2d: if width > height: self.canvasScale *= self.visualEditor.getScale()[2] else: self.canvasScale *= self.visualEditor.getScale()[0] else: if width > height: self.canvasScale *= self.elementHolder.getScale()[2] else: self.canvasScale *= self.elementHolder.getScale()[0] #TODO: the scale probably needs to be calculated dependent on the users screen size self.elementHolder["scale"]= LVecBase3f(self.canvasScale/2,1,self.canvasScale/2), self.elementHolderSizer.refresh() self.scaleParentSizer.refresh() self.setCanvasPlacers() if self.visualEditor["frameColor"] != self.elementHolder["frameColor"]: fc = self.visualEditor["frameColor"] self.elementHolder["frameColor"] = fc self.elementHolderSizer["frameColor"] = fc self.scaleParentSizer["frameColor"] = fc self.scaleParent["frameColor"] = fc self.visualEditor return task.cont
def __init__(self, rootParent=None): self.btnRollDice = DirectButton( frameColor=(0.8, 0.8, 0.8, 0.0), frameSize=(-0.25, 0.25, -0.25, 0.25), hpr=LVecBase3f(0, 0, 0), image='./assets/Dice/DiceButton.png', pos=LPoint3f(0.25, 0, 0.25), relief=1, scale=LVecBase3f(1, 1, 1), text='', image_scale=LVecBase3f(0.25, 0.25, 0.25), image_pos=LPoint3f(0, 0, 0), text_align=TextNode.A_center, text_scale=(0.15, 0.15), text_pos=(-0.08, -0.09), text_fg=LVecBase4f(1, 1, 1, 1), text_bg=LVecBase4f(0, 0, 0, 0), parent=rootParent, command=base.messenger.send, extraArgs=["rollDice"], pressEffect=0, ) self.btnRollDice.setTransparency(1)
def __init__(self): ShowBase.__init__(self) terrainNode = GeomNode('terrain_node') terrainNode.addGeom(gpugemsTerrain()) terrainNodePath = render.attachNewNode(terrainNode) # terrainNodePath.setTwoSided (True); terrainNodePath.setPos(-16, -16, -32) sun = DirectionalLight('sun') sun.setColor((1, 1, 1, 1)) sun.setDirection(LVecBase3f(0.5, 0.5, -1)) sunNodePath = render.attachNewNode(sun) render.setLight(sunNodePath) render.setShaderAuto()
def _setup_camera(self): """Setup camera for this camera controller.""" last_camera_pos_abs = LVector3d( *self._camera.getPos(self._camera_anchor_parent)) target_anchor_hpr: LVecBase3 = self._camera.getHpr( self._camera_anchor_parent) # Place camera at anchor, reset camera's hpr self._camera.setPos(0, 0, 0) self._camera.setHpr(0, 0, 0) # Place anchor at last camera abs pos self._camera_anchor.setPos(self._camera_anchor_parent, LVecBase3f(*last_camera_pos_abs)) self._camera_anchor.setHpr(self._camera_anchor_parent, target_anchor_hpr)
def compute2dPosition(cam, camLens, nodePath, point = LVecBase3f(0, 0, 0)): """ Computes a 3-d point, relative to the indicated node, into a 2-d point as seen by the camera. The range of the returned value is based on the len's current film size and film offset, which is (-1 .. 1) by default. """ # Convert the point into the camera's coordinate space p3d = cam.getRelativePoint(nodePath, point) # Ask the lens to project the 3-d point to 2-d. p2d = Point2() if camLens.project(p3d, p2d): # Got it! return p2d # If project() returns false, it means the point was behind the # lens. return None
def setupDoor(doorNodePath, parentNode, doorOrigin, dnaStore, block, color): doorNodePath.setPosHprScale(doorOrigin, LVecBase3f(0), LVecBase3f(0), LVecBase3f(1)) doorNodePath.setColor(color) leftHole = doorNodePath.find("door_*_hole_left") leftHole.setName("doorFrameHoleLeft") leftHoleGeom = leftHole.find("**/+GeomNode") leftHoleGeom.setName("doorFrameHoleLeftGeom") rightHole = doorNodePath.find("door_*_hole_right") rightHole.setName("doorFrameHoleRight") rightHoleGeom = rightHole.find("**/+GeomNode") rightHoleGeom.setName("doorFrameHoleRightGeom") leftDoor = doorNodePath.find("door_*_left") leftDoor.setName("leftDoor") rightDoor = doorNodePath.find("door_*_right") rightDoor.setName("rightDoor") doorFlat = doorNodePath.find("door_*_flat") doorFlat.setEffect(DecalEffect.make()) leftHole.wrtReparentTo(doorFlat, 0) rightHole.wrtReparentTo(doorFlat, 0) if not leftHoleGeom.getNode(0).isGeomNode(): leftHoleGeom = leftHoleGeom.find("**/+GeomNode") if not rightHoleGeom.getNode(0).isGeomNode(): rightHoleGeom = rightHoleGeom.find("**/+GeomNode") leftHoleGeom.setEffect(DecalEffect.make()) rightHoleGeom.setEffect(DecalEffect.make()) rightDoor.wrtReparentTo(parentNode, 0) leftDoor.wrtReparentTo(parentNode, 0) rightDoor.setColor(color, 0) leftDoor.setColor(color, 0) rightDoor.hide() leftDoor.hide() rightHole.hide() leftHole.hide() leftHole.setColor(LVecBase4f(0, 0, 0, 1), 0) rightHole.setColor(LVecBase4f(0, 0, 0, 1), 0) doorTrigger = doorNodePath.find("door_*_trigger") doorTrigger.setScale(2, 2, 2) doorTrigger.wrtReparentTo(parentNode, 0) doorTrigger.setName("door_trigger_" + str(block)) storeNp = NodePath("door_trigger_" + str(block)) storeNp.setPosHprScale(doorTrigger, LVecBase3f(0), LVecBase3f(0), LVecBase3f(1)) dnaStore.storeBlockDoor(block, storeNp)
def getRandomPos(modelNP): """return a random point on the facing upwards surface of the model""" # collisions are made wrt render steerMgr = OSSteerManager.get_global_ptr() # get the bounding box of scene modelDims, modelDeltaCenter = (LVecBase3f(), LVector3f()) # modelRadius not used steerMgr.get_bounding_dimensions(modelNP, modelDims, modelDeltaCenter) # throw a ray downward from a point with z = double scene's height # and x,y randomly within the scene's (x,y) plane # set the ray origin at double of maximum height of the model zOrig = ((-modelDeltaCenter.get_z() + modelDims.get_z() / 2.0) + modelNP.get_z()) * 2.0 while True: x = modelDims.get_x() * (random.uniform(0.0, 1.0) - 0.5) - modelDeltaCenter.get_x() + modelNP.get_x() y = modelDims.get_y() * (random.uniform(0.0, 1.0) - 0.5) - modelDeltaCenter.get_y() + modelNP.get_y() gotCollisionZ = steerMgr.get_collision_height(LPoint3f(x, y, zOrig)) if gotCollisionZ.get_first(): break return LPoint3f(x, y, gotCollisionZ.get_second())