Пример #1
0
    def update(self, dt):
        # Update player position
        movvec = self.target - self.player.get_pos()
        newpos = self.player.get_pos()
        if movvec.length_squared() < 0.4:
            newpos.set_x(self.target.x)
            newpos.set_y(self.target.y)
        else:
            movvec.normalize()
            movvec *= self.PLAYER_SPEED * dt
            newpos.set_x(self.player.get_x() + movvec.x)
            newpos.set_y(self.player.get_y() + movvec.y)
            self.player.look_at(newpos)

        if self.dungeon.is_walkable(*newpos.xy):
            self.player.set_pos(newpos)

        if self.dungeon.is_exit(*newpos.xy):
            next_didx = self.dungeon_idx + 1
            if next_didx >= len(self.dungeons):
                # Create a new dungeon
                self.dungeons.append(
                    Dungeon(self.mapgen, self.DUNGEON_SX, self.DUNGEON_SY))
            self.switch_to_dungeon(next_didx)

        if self.last_tele_loc is not None:
            if (self.last_tele_loc -
                    self.player.get_pos()).length_squared() > 3:
                self.last_tele_loc = None

        if self.last_tele_loc is None:
            teleloc = self.dungeon.get_tele_loc(*newpos.xy)
            if teleloc is not None:
                newpos.x, newpos.y = teleloc
                self.last_tele_loc = p3d.LVector3(newpos)
                self.target = p3d.LVector3(newpos)
                self.player.set_pos(newpos)
                self.reset_camera()

        if not self.debug_cam and base.mouseWatcherNode.has_mouse():
            mousex, mousey = base.mouseWatcherNode.get_mouse()
            border = self.CAM_MOVE_BORDER
            camdelta = p3d.LVector2(0, 0)
            if mousex < -border:
                camdelta.x -= 1
            elif mousex > border:
                camdelta.x += 1

            if mousey < -border:
                camdelta.y -= 1
            elif mousey > border:
                camdelta.y += 1

            camdelta.normalize()
            camdelta *= self.CAM_MOVE_SPEED * dt

            campos = base.cam.get_pos()
            campos.x += camdelta.x
            campos.y += camdelta.y
            base.cam.set_pos(campos)
Пример #2
0
    def update(self, dt, components):
        for camcomp in components['CAMERA3P']:
            cam = camcomp.camera
            target = camcomp.target

            # Clamp pitch value
            camcomp.pitch = max(min(camcomp.pitch, camcomp.pitch_max + 90),
                                camcomp.pitch_min + 90)

            # Normalize pitch
            pitch_t = (camcomp.pitch - 90) / 90

            # Compute distance and FoV scaling based on pitch
            if pitch_t < 0:
                distance_t = (camcomp.pitch - 90) / camcomp.pitch_min
                distance_t = tween.easeInCubic(distance_t)
                distance_t = 1.0 - 0.6 * distance_t
            else:
                distance_t = (camcomp.pitch - 90) / camcomp.pitch_max
                distance_t = tween.easeInQuad(distance_t)
                distance_t = 1.0 + 0.7 * distance_t

            # Apply rotation and distance
            rotation = p3d.Mat3.rotate_mat(90 - (0.5 * pitch_t + 0.5) * 180,
                                           p3d.LVector3(1, 0, 0))
            rotation = rotation * p3d.Mat3.rotate_mat(camcomp.yaw,
                                                      p3d.LVector3(0, 0, 1))

            position = p3d.LVector3(0, -camcomp.distance * distance_t, 0)

            position = rotation.xform(position)
            position += target.get_pos(base.render)

            cam.set_pos(position)
            cam.look_at(target.get_pos(base.render) + p3d.LVector3(0, 0, 1))
Пример #3
0
    def _update_character(self, t, dt):
        # Compute motion inputs
        input_vel = core.LVector3(self.pad_input, 0)
        input_vel = core.LMatrix3.rotateMat(90 + self.camera_angle).xform(input_vel)
        input_vel = (input_vel * 7.5).getXy()
        if input_vel.length() < 1.5: input_vel.set(0, 0)  # deadzone
        self.target_vel = self.target_vel*0.1 + input_vel*0.9

        self.strafe_amount = self.strafe_amount*0.1 + self.strafe_pressed*0.9

        input_dir = (atan2(self.target_vel[1], self.target_vel[0]) * 180 / pi
                     if self.target_vel.length() > 1e-5 else self.target_dir)
        input_dir = mix_angles(input_dir, 180 + self.camera_angle, self.strafe_amount)
        self.target_dir = mix_angles(self.target_dir, input_dir, 0.9)

        # Compute gait
        self.crouch_amount = self.crouch_amount*0.1 + self.crouch_pressed*0.9
        if self.target_vel.length() < 0.1:
            gaits = [1 - 10*self.target_vel.length(), 0, 0, 0, 0, 0]
        elif self.crouch_amount > 0.1:
            gaits = [0, 0, 0, self.crouch_amount, 0, 0]
        elif self.run_pressed:
            gaits = [0, 0, 1, 0, 0, 0]
        else:
            gaits = [0, 1, 0, 0, 0, 0]
        self.gaits = self.gaits*0.9 + np.array(gaits)*0.1

        # Run motion controller
        pos, xforms = self.motion_controller.frame(self.target_vel, self.target_dir,
                                                   self.gaits, self.strafe_amount)
        self.char_pos = core.LVector3(*pos)
        self.joint_global_xforms = xforms

        self.heightmap.update_trajectory(*self.motion_controller.get_trajectory())
Пример #4
0
    def __init__(self):
        super().__init__()

        self.accept('toggle-debug-cam', self.toggle_debug_cam)
        self.accept('move', self.move_player)
        self.accept('ability1', self.toggle_range, [0])
        self.accept('ability2', self.toggle_range, [1])
        self.accept('ability3', self.toggle_range, [2])
        self.accept('ability4', self.toggle_range, [3])

        self.mapgen = 'static'
        dungeon = Dungeon(self.mapgen, self.DUNGEON_SX, self.DUNGEON_SY)
        dungeon.model_root.reparent_to(self.root_node)

        dlight = p3d.DirectionalLight('sun')
        dlight.set_color(p3d.LVector3(0.2, 0.2, 0.2))
        dlight.set_shadow_caster(True, 4096, 4096)
        dlnp = self.root_node.attach_new_node(dlight)
        dlnp.set_z(10)
        dlnp.set_p(-90)
        lens = dlight.get_lens()
        lens.set_film_size(60)
        lens.set_near(1)
        lens.set_far(100)
        self.root_node.set_light(dlnp)

        dlight2 = p3d.DirectionalLight('ground')
        dlight2.set_color(p3d.LVector3(0.1, 0.1, 0.1))
        dlnp2 = self.root_node.attach_new_node(dlight2)
        self.root_node.set_light(dlnp2)

        loader = p3d.Loader.get_global_ptr()
        player = p3d.NodePath(
            loader.load_sync('dungeon.bam')).find('**/MonsterSpawn').node()
        playernp = self.root_node.attach_new_node(player)
        playernp.set_pos(dungeon.player_start)
        playernp.set_z(1.5)
        self.player_ranges = [
            RangeIndicator('box', length=5, width=1),
            RangeIndicator('circle', radius=2),
            RangeIndicator('circle', radius=3),
            RangeIndicator('circle', radius=4),
        ]
        for rangeindicator in self.player_ranges:
            rangeindicator.graphics.reparent_to(playernp)
            rangeindicator.visible = False

        # self.root_node.ls()
        # self.root_node.analyze()

        self.dungeons = [dungeon]
        self.dungeon_idx = 0
        self.dungeon = dungeon
        self.player = playernp
        self.last_tele_loc = None
        self.target = self.player.get_pos()
        self.debug_cam = False
        self.reset_camera()
def test_camera_sync(graphics_context, camera):
    graphics_context['camera'] = camera
    rpass = lionrender.Pass('test', **graphics_context)
    camera.set_pos(p3d.LVector3(1, 2, 3))
    camera.set_hpr(p3d.LVector3(1, 2, 3))
    graphics_context['engine'].render_frame()
    graphics_context['engine'].render_frame()
    graphics_context['engine'].render_frame()
    graphics_context['engine'].render_frame()

    rcam = rpass.display_region.get_camera()
    assert rcam.get_pos().compare_to(camera.get_pos()) == 0
    assert rcam.get_hpr().compare_to(camera.get_hpr()) == 0
    assert rcam.get_node(0).get_lens() == camera.get_node(0).get_lens()
def test_camera_sync_indirect(graphics_context, camera):
    graphics_context['camera'] = p3d.NodePath(p3d.ModelNode('indirect'))
    camera.reparent_to(graphics_context['camera'])
    indirect = graphics_context['camera']

    rpass = lionrender.Pass('test', **graphics_context)
    camera.set_pos(p3d.LVector3(1, 2, 3))
    camera.set_hpr(p3d.LVector3(1, 2, 3))
    graphics_context['engine'].render_frame()

    rcam = rpass.display_region.get_camera()
    assert rcam.get_pos().compare_to(indirect.get_pos()) == 0
    assert rcam.get_hpr().compare_to(indirect.get_hpr()) == 0
    assert rcam.get_node(0).get_lens() == camera.get_node(0).get_lens()
Пример #7
0
    def update(self, dt, components):
        self.physics_world.do_physics(dt, 10, 1.0 / 180.0)

        for character in components.get('PHY_CHARACTER', []):
            phynode = character.physics_node
            np = character.entity.get_component('NODEPATH').nodepath

            # Air Check
            frompt = np.get_pos(base.render) - p3d.LVector3(
                0, 0, character.height / 2.1)
            topt = frompt + p3d.LVector3(0, 0, -0.25)
            result = self.physics_world.ray_test_closest(frompt, topt)
            #print(frompt, topt, result.has_hit(), result.get_node())
            character.airborne = not result.has_hit()
Пример #8
0
    def update_weapon(self, weapon):
        if isinstance(weapon, str):
            gdb = gamedb.get_instance()
            weapon = gdb['weapons'][weapon]

        meshname = weapon.mesh['root_node']
        if meshname == '':
            return
        weapon_joint = self._path.expose_joint(None, 'modelRoot', 'weapon')
        modelroot = base.loader.load_model('models/{}.bam'.format(
            weapon.mesh['bam_file']))
        mesh = modelroot.find(f'**/{meshname}')
        if mesh.is_empty():
            print(f'Warning: could not find weapon {meshname}')
            modelroot.ls()
            return
        elif weapon_joint is None:
            print(f'Warning: could not find weapon joint on {self.form.name}')
            return

        # Update weapon transform
        weaponxf = self.form.weapon_offset
        pos, hpr, scale = weaponxf['position'][:], weaponxf[
            'hpr'][:], weaponxf['scale'][:]
        pos = [i * 0.1 for i in pos]
        pos[1] += 0.4
        mesh.set_pos(mesh.get_pos() + p3d.LVector3(*pos))
        mesh.set_hpr(*hpr)
        scale = [
            scale[idx] / inv
            for idx, inv in enumerate(weapon_joint.get_scale())
        ]
        mesh.set_scale(*scale)
        mesh.instance_to(weapon_joint)
Пример #9
0
    def update_camera(self, task):
        dt = task.time - self.last_update_cam_time

        # Update camera angle
        self.camera_angle += 90 * (self.cam_right_pressed -
                                   self.cam_left_pressed) * dt

        # Reposition camera
        ang_rads = self.camera_angle * pi / 180
        cam_offset = core.LVector3(300 * cos(ang_rads), 300 * sin(ang_rads),
                                   320)
        self.camera.setPos(self.char_pos + cam_offset)
        self.camera.lookAt(self.char_pos + core.LVector3(0, 0, 80),
                           core.LVector3(0, 0, 1))

        self.last_update_cam_time = task.time
        return Task.cont
Пример #10
0
 def setupLights(self):  # This function sets up some default lighting
     ambientLight = p3dc.AmbientLight("ambientLight")
     ambientLight.setColor((.8, .8, .8, 1))
     directionalLight = p3dc.DirectionalLight("directionalLight")
     directionalLight.setDirection(p3dc.LVector3(0, 45, -45))
     directionalLight.setColor((0.2, 0.2, 0.2, 1))
     self.render.setLight(self.render.attachNewNode(directionalLight))
     self.render.setLight(self.render.attachNewNode(ambientLight))
Пример #11
0
 def func():
     textnp.set_pos(target.as_nodepath, 0, 0, 2)
     intervals.Sequence(
         intervals.Func(textnp.show),
         intervals.LerpPosInterval(
             textnp, 1.0,
             textnp.get_pos() + p3d.LVector3(0, 0, 0.5)),
         intervals.Func(textnp.remove_node),
     ).start()
Пример #12
0
    def __init__(self):
        super().__init__()

        self.physics_world = bullet.BulletWorld()
        self.physics_world.set_gravity(p3d.LVector3(0, 0, -9.8))
        phydebug = bullet.BulletDebugNode('Physics Debug')
        phydebug.show_wireframe(True)
        #phydebug.show_bounding_boxes(True)
        self._debugnp = p3d.NodePath(phydebug)
        self.physics_world.set_debug_node(phydebug)
Пример #13
0
    def init_components(self, dt, components):
        for static_mesh in components.get('PHY_STATICMESH', []):
            self.physics_world.attach(static_mesh.physics_node)

        for character in components.get('PHY_CHARACTER', []):
            np = character.entity.get_component('NODEPATH').nodepath
            phynp = np.get_parent().attach_new_node(character.physics_node)
            phynp.set_pos(np.get_pos())
            np.reparent_to(phynp)
            np.set_pos(p3d.LVector3(0, 0, 0))
            self.physics_world.attach(character.physics_node)
Пример #14
0
    def __init__(self):
        ShowBase.__init__(self)

        dlight = core.DirectionalLight('dlight')
        dlight.setDirection(core.LVector3(1, 0, 1))
        dlnode = self.render.attachNewNode(dlight)
        self.render.setLight(dlnode)

        alight = core.AmbientLight('alight')
        alight.setColor((0.3, 0.3, 0.3, 1))
        alnode = self.render.attachNewNode(alight)
        self.render.setLight(alnode)
Пример #15
0
def test_combat_coords(app):
    arena = Arena(p3d.NodePath('root'), 5, 5)
    assert arena.tile_coord_to_world((2, 2)) == p3d.LVector3(4, 4, 0)
    assert arena.tilenp_to_coord(arena.tilenps[2][1]) == (2, 1)

    assert arena.tile_distance((0, 0), (0, 0)) == 0
    assert arena.tile_distance((0, 1), (0, -1)) == 2
    assert arena.tile_distance((1, 1), (3, 3)) == 4

    assert arena.tile_get_facing_to((0, 0), (1, 1)) == (1, 0)
    assert arena.tile_get_facing_to((1, 1), (0, 0)) == (-1, 0)
    assert arena.tile_get_facing_to((1, 1), (1, 3)) == (0, 1)
Пример #16
0
    def __init__(self, shape, **kwargs):
        sdftex = None
        frame = p3d.LVector4(-1, 1, -1, 1)
        scale = p3d.LVector3(1, 1, 1)
        offset = p3d.LVector3(0, 0, 0)

        if shape == 'circle':
            sdftex = _SDF_CIRCLE
            scale *= kwargs['radius']
        elif shape == 'box':
            sdftex = _SDF_BOX
            scale = p3d.LVector3(kwargs['width'] / 2.0, 1,
                                 kwargs['length'] / 2.0)
            offset = p3d.LVector3(0, kwargs['length'] / 2.0, 0)
        else:
            raise ValueError(
                "Unknown shape for RangeIndicator: {}".format(shape))

        cardmaker = p3d.CardMaker('RI_' + shape)
        cardmaker.set_frame(frame)

        card = p3d.NodePath(cardmaker.generate())
        card.set_p(-90)
        card.set_scale(scale)
        card.set_pos(offset)
        card.set_transparency(p3d.TransparencyAttrib.MAlpha)

        card.set_texture(sdftex)

        card.set_shader(_SHADER)
        card.set_shader_input('sdftex', sdftex)
        card.set_shader_input('ricolor', p3d.LVector4(0.8, 0.0, 0.0, 0.3))
        card.set_shader_input('outline_color',
                              p3d.LVector4(0.0, 0.0, 0.0, 0.8))

        self.graphics = card
Пример #17
0
        def update_movement(direction, activate):
            move_delta = p3d.LVector3(0, 0, 0)

            if direction == 'forward':
                move_delta.set_y(1)
            elif direction == 'backward':
                move_delta.set_y(-1)
            elif direction == 'left':
                move_delta.set_x(-1)
            elif direction == 'right':
                move_delta.set_x(1)

            if not activate:
                move_delta *= -1

            self.player_movement += move_delta
Пример #18
0
        def process_tile(x, y):
            tile = self._bsp[y][x]

            if tile != '.':
                tilenp = self._tile_root.attach_new_node('TileNode')
                tile_model.instance_to(tilenp)
                tile_pos = p3d.LVector3(x - sizex / 2.0, y - sizey / 2.0,
                                        -random.random() * 0.1)
                tilenp.set_pos(tile_pos)

                if tile == '*':
                    # Player start
                    self.player_start.x = tile_pos.x
                    self.player_start.y = tile_pos.y
                elif tile == '&':
                    # Exit
                    self.exit_loc.x = tile_pos.x
                    self.exit_loc.y = tile_pos.y

                    exitnp = p3d.NodePath('Exit')
                    tele_model.instance_to(exitnp)
                    exitnp.set_pos(tile_pos + p3d.LVector3(0, 0, 1))
                    exitnp.reparent_to(self.model_root)
                elif tile == '$':
                    # Monster spawn
                    spawnnp = p3d.NodePath('Spawn')
                    spawn_model.instance_to(spawnnp)
                    spawnnp.set_pos(tile_pos + p3d.LVector3(0, 0, 1))
                    spawnnp.set_h(180)
                    spawnnp.reparent_to(self.model_root)
                    self.spawners.append(spawnnp)
                elif tile.isdigit():
                    # Teleporter
                    telenp = self.model_root.attach_new_node('Teleporter')
                    tele_model.instance_to(telenp)
                    telenp.set_pos(tile_pos + p3d.LVector3(0, 0, 1))

                    if tile not in self._telemap:
                        self._telemap[tile] = [(x, y)]
                    else:
                        self._telemap[tile].append((x, y))

                        # This is the second teleporter we found for this pair so add a link
                        tlnp = self.model_root.attach_new_node(
                            'TeleporterLink')
                        telelink_model.instance_to(tlnp)
                        tlnp.set_pos(tile_pos + p3d.LVector3(0, 0, 1))

                        teleloc = self._tile_to_world(
                            *self._get_tele_loc_from_tile(x, y))
                        tovec = p3d.LVector3(teleloc, tlnp.get_z())
                        linkvec = tovec - tlnp.get_pos()

                        tlnp.set_scale(1, linkvec.length(), 1)
                        tlnp.look_at(tovec)
Пример #19
0
    def __init__(self,
                 rendernp,
                 targetpos=None,
                 scene=None,
                 calc_shadow_bounds=True):
        self.rendernp = rendernp

        targetpos = targetpos or p3d.LVector3(0, 0, 0)

        # Lights
        self.key_light = p3d.DirectionalLight('sun')
        self.key_light.color_temperature = 6000
        self.key_lightnp = rendernp.attach_new_node(self.key_light)
        self.key_lightnp.set_pos(targetpos + (0, -15, 15))
        self.key_lightnp.look_at(targetpos)
        base.render.set_light(self.key_lightnp)

        self.fill_light = p3d.DirectionalLight('fill light')
        self.fill_light.color_temperature = 4800
        self.fill_light.color = self.fill_light.color * 0.5
        self.fill_lightnp = rendernp.attach_new_node(self.fill_light)
        self.fill_lightnp.set_pos(targetpos + (-20, 0, 10))
        self.fill_lightnp.look_at(targetpos)
        base.render.set_light(self.fill_lightnp)

        self.back_light = p3d.DirectionalLight('fill light')
        self.back_light.color_temperature = 4800
        self.back_light.color = self.back_light.color * 0.25
        self.back_lightnp = rendernp.attach_new_node(self.back_light)
        self.back_lightnp.set_pos(20, 20, 0)
        self.back_lightnp.look_at(targetpos)
        base.render.set_light(self.back_lightnp)

        ambient_power = 0.1
        self.ambient_light = p3d.AmbientLight('ambient')
        self.ambient_light.color = (ambient_power, ambient_power,
                                    ambient_power, 1.0)
        self.ambient_lightnp = rendernp.attach_new_node(self.ambient_light)
        base.render.set_light(self.ambient_lightnp)

        # Shadows
        self.key_light.set_shadow_caster(True, 512, 512)
        if calc_shadow_bounds:
            self.recalc_bounds(scene)
Пример #20
0
    def load_monster_models(self, forms=None, weapons=None):
        for monact in self.monster_actors:
            monact.cleanup()
            monact.remove_node()
        self.monster_actors = []
        labels = []

        if forms is None:
            forms = [i.form for i in self.player.monsters]
            labels = [i.name for i in self.player.monsters]
            weapons = [i.weapon for i in self.player.monsters]

        if not labels:
            labels = itertools.repeat('')

        if weapons is None:
            weapons = itertools.repeat(None)

        stride = 2
        offset = 0
        for form, weapon, labelstr in zip(forms, weapons, labels):
            actor = MonsterActor(form, self.monsters_root, weapon)
            actor.set_h(45)
            actor.set_pos(self.monsters_root, p3d.LVector3(offset, 0, 0))
            self.monster_actors.append(actor)

            label = p3d.TextNode('monster label')
            label.set_align(p3d.TextNode.ACenter)
            label.set_text(labelstr)
            labelnp = actor.attach_new_node(label)
            labelnp.set_pos(0, 0, 2.3)
            labelnp.set_scale(0.2)
            labelnp.set_billboard_point_eye()
            labelnp.set_bin("fixed", 0)
            labelnp.set_depth_test(False)
            labelnp.set_depth_write(False)
            labelnp.set_shader_auto(True)
            labelnp.set_color_scale((0, 0, 0, 1))
            labelnp.set_light_off()

            offset += stride

        if self.monster_actors:
            self.lighting.recalc_bounds(self.monsters_root)
Пример #21
0
    def update(self, dt, components):
        for aicomp in components['AI']:
            # Pick target
            try:
                target = components['PLAYER'][0]
            except IndexError:
                continue

            targetnp = target.entity.get_component('NODEPATH').nodepath

            # Face target
            ainp = aicomp.entity.get_component('NODEPATH')
            look_point = targetnp.get_pos()
            look_point.z = ainp.nodepath.get_pos().z
            ainp.nodepath.look_at(look_point, p3d.LVector3(0, 0, 1))

            # Attack target
            aichar = aicomp.entity.get_component('CHARACTER')
            aichar.action_set.add('ATTACK')
Пример #22
0
 def addFirefly(self):
     pos1 = p3dc.LPoint3(random.uniform(-50, 50), random.uniform(-100, 150),
                         random.uniform(-10, 80))
     dir = p3dc.LVector3(random.uniform(-1, 1), random.uniform(-1, 1),
                         random.uniform(-1, 1))
     dir.normalize()
     pos2 = pos1 + (dir * 20)
     fly = self.lightroot.attachNewNode(p3dc.PandaNode("fly"))
     glow = fly.attachNewNode(p3dc.PandaNode("glow"))
     dot = fly.attachNewNode(p3dc.PandaNode("dot"))
     color_r = 1.0
     color_g = random.uniform(0.8, 1.0)
     color_b = min(color_g, random.uniform(0.5, 1.0))
     fly.setColor(color_r, color_g, color_b, 1.0)
     fly.setShaderInput("lightcolor", (color_r, color_g, color_b, 1.0))
     int1 = fly.posInterval(random.uniform(7, 12), pos1, pos2)
     int2 = fly.posInterval(random.uniform(7, 12), pos2, pos1)
     si1 = fly.scaleInterval(random.uniform(0.8, 1.5),
                             p3dc.LPoint3(0.2, 0.2, 0.2),
                             p3dc.LPoint3(0.2, 0.2, 0.2))
     si2 = fly.scaleInterval(random.uniform(1.5, 0.8),
                             p3dc.LPoint3(1.0, 1.0, 1.0),
                             p3dc.LPoint3(0.2, 0.2, 0.2))
     si3 = fly.scaleInterval(random.uniform(1.0, 2.0),
                             p3dc.LPoint3(0.2, 0.2, 0.2),
                             p3dc.LPoint3(1.0, 1.0, 1.0))
     siseq = Sequence(si1, si2, si3)
     siseq.loop()
     siseq.setT(random.uniform(0, 1000))
     seq = Sequence(int1, int2)
     seq.loop()
     self.spheremodel.instanceTo(glow)
     self.firefly.instanceTo(dot)
     glow.setScale(self.fireflysize * 1.1)
     glow.hide(p3dc.BitMask32(self.modelMask | self.plainMask))
     dot.hide(p3dc.BitMask32(self.modelMask | self.lightMask))
     dot.setColor(color_r, color_g, color_b, 1.0)
     self.fireflies.append(fly)
     self.sequences.append(seq)
     self.glowspheres.append(glow)
     self.scaleseqs.append(siseq)
Пример #23
0
    def start(self):
        # The main initialization of our class
        # This creates the on screen title that is in every tutorial
        self.title = OnscreenText(text="Panda3D: Tutorial - Lighting",
                                  style=1, fg=(1, 1, 0, 1), shadow=(0, 0, 0, 0.5),
                                  pos=(0.87, -0.95), scale = .07)

        # Creates labels used for onscreen instructions
        self.ambientText = self.makeStatusLabel(0)
        self.directionalText = self.makeStatusLabel(1)
        self.spotlightText = self.makeStatusLabel(2)
        self.pointLightText = self.makeStatusLabel(3)
        self.spinningText = self.makeStatusLabel(4)
        self.ambientBrightnessText = self.makeStatusLabel(5)
        self.directionalBrightnessText = self.makeStatusLabel(6)
        self.spotlightBrightnessText = self.makeStatusLabel(7)
        self.spotlightExponentText = self.makeStatusLabel(8)
        self.lightingPerPixelText = self.makeStatusLabel(9)
        self.lightingShadowsText = self.makeStatusLabel(10)

        self.disco = self.loader.loadModel("disco_lights_models/disco_hall")
        self.disco.reparentTo(self.render)
        self.disco.setPosHpr(0, 50, -4, 90, 0, 0)

        # First we create an ambient light. All objects are affected by ambient
        # light equally
        # Create and name the ambient light
        self.ambientLight = self.render.attachNewNode(p3dc.AmbientLight("ambientLight"))
        # Set the color of the ambient light
        self.ambientLight.node().setColor((.1, .1, .1, 1))
        # add the newly created light to the lightAttrib

        # Now we create a directional light. Directional lights add shading from a
        # given angle. This is good for far away sources like the sun
        self.directionalLight = self.render.attachNewNode(
            p3dc.DirectionalLight("directionalLight"))
        self.directionalLight.node().setColor((.35, .35, .35, 1))
        # The direction of a directional light is set as a 3D vector
        self.directionalLight.node().setDirection(p3dc.LVector3(1, 1, -2))
        # These settings are necessary for shadows to work correctly
        self.directionalLight.setZ(6)
        dlens = self.directionalLight.node().getLens()
        dlens.setFilmSize(41, 21)
        dlens.setNearFar(50, 75)
        # self.directionalLight.node().showFrustum()

        # Now we create a spotlight. Spotlights light objects in a given cone
        # They are good for simulating things like flashlights
        self.spotlight = self.camera.attachNewNode(p3dc.Spotlight("spotlight"))
        self.spotlight.node().setColor((.45, .45, .45, 1))
        self.spotlight.node().setSpecularColor((0, 0, 0, 1))
        # The cone of a spotlight is controlled by it's lens. This creates the lens
        self.spotlight.node().setLens(p3dc.PerspectiveLens())
        # This sets the Field of View (fov) of the lens, in degrees for width
        # and height.  The lower the numbers, the tighter the spotlight.
        self.spotlight.node().getLens().setFov(16, 16)
        # Attenuation controls how the light fades with distance.  The three
        # values represent the three attenuation constants (constant, linear,
        # and quadratic) in the internal lighting equation. The higher the
        # numbers the shorter the light goes.
        self.spotlight.node().setAttenuation(p3dc.LVector3(1, 0.0, 0.0))
        # This exponent value sets how soft the edge of the spotlight is.
        # 0 means a hard edge. 128 means a very soft edge.
        self.spotlight.node().setExponent(60.0)

        # Now we create three colored Point lights. Point lights are lights that
        # radiate from a single point, like a light bulb. Like spotlights, they
        # are given position by attaching them to NodePaths in the world
        self.redHelper = self.loader.loadModel('disco_lights_models/sphere')
        self.redHelper.setColor((1, 0, 0, 1))
        self.redHelper.setPos(-6.5, -3.75, 0)
        self.redHelper.setScale(.25)
        self.redPointLight = self.redHelper.attachNewNode(
            p3dc.PointLight("redPointLight"))
        self.redPointLight.node().setColor((.35, 0, 0, 1))
        self.redPointLight.node().setAttenuation(p3dc.LVector3(.1, 0.04, 0.0))

        # The green point light and helper
        self.greenHelper = self.loader.loadModel('disco_lights_models/sphere')
        self.greenHelper.setColor((0, 1, 0, 1))
        self.greenHelper.setPos(0, 7.5, 0)
        self.greenHelper.setScale(.25)
        self.greenPointLight = self.greenHelper.attachNewNode(
            p3dc.PointLight("greenPointLight"))
        self.greenPointLight.node().setAttenuation(p3dc.LVector3(.1, .04, .0))
        self.greenPointLight.node().setColor((0, .35, 0, 1))

        # The blue point light and helper
        self.blueHelper = self.loader.loadModel('disco_lights_models/sphere')
        self.blueHelper.setColor((0, 0, 1, 1))
        self.blueHelper.setPos(6.5, -3.75, 0)
        self.blueHelper.setScale(.25)
        self.bluePointLight = self.blueHelper.attachNewNode(
            p3dc.PointLight("bluePointLight"))
        self.bluePointLight.node().setAttenuation(p3dc.LVector3(.1, 0.04, 0.0))
        self.bluePointLight.node().setColor((0, 0, .35, 1))
        self.bluePointLight.node().setSpecularColor((1, 1, 1, 1))

        # Create a dummy node so the lights can be spun with one command
        self.pointLightHelper = self.render.attachNewNode("pointLightHelper")
        self.pointLightHelper.setPos(0, 50, 11)
        self.redHelper.reparentTo(self.pointLightHelper)
        self.greenHelper.reparentTo(self.pointLightHelper)
        self.blueHelper.reparentTo(self.pointLightHelper)

        # Finally we store the lights on the root of the scene graph.
        # This will cause them to affect everything in the scene.
        self.render.setLight(self.ambientLight)
        self.render.setLight(self.directionalLight)
        self.render.setLight(self.spotlight)
        self.render.setLight(self.redPointLight)
        self.render.setLight(self.greenPointLight)
        self.render.setLight(self.bluePointLight)

        # Create and start interval to spin the lights, and a variable to
        # manage them.
        self.pointLightsSpin = self.pointLightHelper.hprInterval(
            6, p3dc.LVector3(360, 0, 0))
        self.pointLightsSpin.loop()
        self.arePointLightsSpinning = True

        # Per-pixel lighting and shadows are initially off
        self.perPixelEnabled = False
        self.shadowsEnabled = False

        # listen to keys for controlling the lights
        self.accept("escape", sys.exit)
        self.accept("a", self.toggleLights, [[self.ambientLight]])
        self.accept("d", self.toggleLights, [[self.directionalLight]])
        self.accept("s", self.toggleLights, [[self.spotlight]])
        self.accept("p", self.toggleLights, [[self.redPointLight,
                                              self.greenPointLight,
                                              self.bluePointLight]])
        self.accept("r", self.toggleSpinningPointLights)
        self.accept("l", self.togglePerPixelLighting)
        self.accept("e", self.toggleShadows)
        self.accept("z", self.addBrightness, [self.ambientLight, -.05])
        self.accept("x", self.addBrightness, [self.ambientLight, .05])
        self.accept("c", self.addBrightness, [self.directionalLight, -.05])
        self.accept("v", self.addBrightness, [self.directionalLight, .05])
        self.accept("b", self.addBrightness, [self.spotlight, -.05])
        self.accept("n", self.addBrightness, [self.spotlight, .05])
        self.accept("q", self.adjustSpotlightExponent, [self.spotlight, -1])
        self.accept("w", self.adjustSpotlightExponent, [self.spotlight, 1])

        # Finally call the function that builds the instruction texts
        self.updateStatusLabel()
    def _update_character(self, t, dt):
        root_pos, global_xforms, forward, gaits = self.anim

        # Interpolate pos and xform
        frame = min(60 * t, root_pos.shape[0] - 2)
        f_num, f_off = int(frame), frame % 1.0
        pos = root_pos[f_num] * (1 - f_off) + root_pos[f_num + 1] * f_off
        xforms = global_xforms[f_num] * (1 - f_off) + global_xforms[f_num +
                                                                    1] * f_off

        self.char_pos = core.LVector3(*pos)
        self.joint_global_xforms = xforms

        # Update displayed trajectory
        nearest_frame = min(root_pos.shape[0] - 60, max(60, round(60 * t)))
        if nearest_frame > 100: return
        positions = root_pos[nearest_frame - 60:nearest_frame + 60].copy()
        positions[:, 2] = self.heightmap.get_height(positions[:, 0],
                                                    positions[:, 1])
        directions = forward[nearest_frame - 60:nearest_frame + 60, :2]
        self.heightmap.update_trajectory(positions, directions)

        if nearest_frame == 100: print('---------')
        if BUILD_NETWORK_INPUTS and nearest_frame == 100:

            td_angles = np.arctan2(directions[:, 1],
                                   directions[:, 0]) * 180 / np.pi
            prev_joint_pos = global_xforms[nearest_frame - 1, :, 3, :3]
            prev_joint_vels = global_xforms[nearest_frame, :,
                                            3, :3] - prev_joint_pos
            prev_joint_vels += root_pos[nearest_frame] - root_pos[nearest_frame
                                                                  - 1]
            prev_joint_pos[:, 2] += root_pos[nearest_frame - 1, 2]
            gts = gaits[nearest_frame - 60:nearest_frame + 60]

            rpos = np.empty(3)
            rpos[:2] = positions[60, :2]
            rpos[2] = positions[::10, 2].mean()
            rrot = td_angles[60] - 90

            x = np.empty(342, dtype=np.float32)

            # Trajectory positions and directions
            pos = rot2(-rrot) @ (positions[::10, :2] - rpos[:2]).T
            drc = ang2vec(td_angles[::10] - rrot).T
            x[0:12] = -pos[0]
            x[12:24] = pos[1]
            x[24:36] = -drc[0]
            x[36:48] = drc[1]

            # Gaits
            x[48:120] = gts[::10].T.flatten()

            # Last frame's joint positions and velocities
            jpos = prev_joint_pos
            jpos[:, :2] = jpos[:, :2] @ rot2(90 - td_angles[59]).T
            jvel = prev_joint_vels.copy()
            jvel[:, :2] = jvel[:, :2] @ rot2(90 - td_angles[59]).T
            x[120:213:3] = -jpos[:, 0]
            x[121:213:3] = jpos[:, 2] - self.rheight
            x[122:213:3] = jpos[:, 1]
            x[213:306:3] = -jvel[:, 0]
            x[214:306:3] = jvel[:, 2]
            x[215:306:3] = jvel[:, 1]

            # Trajectory heights (r and l are switched here for consistency with paper)
            positions_r = positions[::10, :2] + 25 * ang2vec(td_angles[::10] +
                                                             90)
            positions_l = positions[::10, :2] + 25 * ang2vec(td_angles[::10] -
                                                             90)
            x[306:318] = self.heightmap.get_height(positions_r[:, 0],
                                                   positions_r[:, 1])
            x[318:330] = self.heightmap.get_height(positions_l[:, 0],
                                                   positions_l[:, 1])
            x[330:342] = positions[::10, 2]
            # Subtract off root position height
            x[306:342] -= rpos[2]

            x -= PFNN_XMEAN
            x /= PFNN_XSTD

            np.save('12345', x)

        self.rheight = positions[::10, 2].mean()
Пример #25
0
    def __init__(self):
        # Setup a space to work with
        base.ecsmanager.space = Entity(None)
        base.ecsmanager.space.add_component(components.NodePathComponent())
        spacenp = base.ecsmanager.space.get_component('NODEPATH').nodepath
        spacenp.reparent_to(base.render)

        # Load assets
        self.level_entity = base.ecsmanager.create_entity()
        self.level = loader.load_model('cathedral.bam')
        level_start = self.level.find('**/PlayerStart')
        self.level.reparent_to(spacenp)

        for phynode in self.level.find_all_matches('**/+BulletBodyNode'):
            if not phynode.is_hidden():
                self.level_entity.add_component(
                    components.PhysicsStaticMeshComponent(phynode.node()))
            else:
                print("Skipping hidden node", phynode)

        self.player = base.template_factory.make_character(
            'character.bam', self.level, level_start.get_pos())

        # Attach camera to player
        playernp = self.player.get_component('NODEPATH').nodepath
        self.camera = base.ecsmanager.create_entity()
        self.camera.add_component(
            components.Camera3PComponent(base.camera, playernp))

        # Player movement
        self.player_movement = p3d.LVector3(0, 0, 0)

        def update_movement(direction, activate):
            move_delta = p3d.LVector3(0, 0, 0)

            if direction == 'forward':
                move_delta.set_y(1)
            elif direction == 'backward':
                move_delta.set_y(-1)
            elif direction == 'left':
                move_delta.set_x(-1)
            elif direction == 'right':
                move_delta.set_x(1)

            if not activate:
                move_delta *= -1

            self.player_movement += move_delta

        self.accept('move-forward', update_movement, ['forward', True])
        self.accept('move-forward-up', update_movement, ['forward', False])
        self.accept('move-backward', update_movement, ['backward', True])
        self.accept('move-backward-up', update_movement, ['backward', False])
        self.accept('move-left', update_movement, ['left', True])
        self.accept('move-left-up', update_movement, ['left', False])
        self.accept('move-right', update_movement, ['right', True])
        self.accept('move-right-up', update_movement, ['right', False])

        def jump():
            char = self.player.get_component('CHARACTER')
            char.jump = True

        self.accept('jump', jump)

        # Mouse look
        props = p3d.WindowProperties()
        props.set_cursor_hidden(True)
        props.set_mouse_mode(p3d.WindowProperties.M_confined)
        base.win.request_properties(props)
Пример #26
0
 def pixels_to_im_coords(self, point):
     px, py = point
     px, py = px - self.window_w / 2, py - self.window_h / 2
     return core.LVector3(px, 0,
                          -py) * (2.0 / min(self.window_w, self.window_h))
Пример #27
0
    def __init__(self):
        super().__init__()

        # Allow panda to synthesize shaders. Make sure hardware-animated-vertices is set
        # to true in panda config.
        render.setShaderAuto()

        # Show FPS
        self.setFrameRateMeter(True)

        # Load character
        self.character = Actor('data/character/character')
        self.character.reparentTo(self.render)
        self.joints = []
        for name in JOINT_NAMES:
            j = self.character.controlJoint(None, 'modelRoot', name)
            j.reparentTo(self.render)
            self.joints.append(j)

        # Add lights
        dlight = core.DirectionalLight('DirectionalLight')
        dlight.setDirection(core.LVector3(2, 0, -1))
        dlight.setColor(core.LColor(1, 1, 1, 1))
        dlnp = self.render.attachNewNode(dlight)
        self.render.setLight(dlnp)

        alight = core.AmbientLight('AmbientLight')
        alight.setColor(core.LColor(0.6, 0.6, 0.6, 1))
        alnp = self.render.attachNewNode(alight)
        self.render.setLight(alnp)

        # Camera angle in xy-plane (degrees)
        self.camera_angle = 0

        # Camera control
        self.cam_left_pressed, self.cam_right_pressed = 0, 0
        self.accept('a', self.set_cam_left_pressed, [1])
        self.accept('a-up', self.set_cam_left_pressed, [0])
        self.accept('d', self.set_cam_right_pressed, [1])
        self.accept('d-up', self.set_cam_right_pressed, [0])

        # Pad display
        self.pad_radius = 60
        self.pad_outline = OnscreenImage('project/data/pad/pad_outline.png',
                                         (0, 0, 0))
        self.pad_outline.setTransparency(core.TransparencyAttrib.MAlpha)
        self.pad_outline.hide()
        self.pad_response_circle = OnscreenImage(
            'project/data/pad/pad_response_indicator.png', (0, 0, 0))
        self.pad_response_circle.setTransparency(
            core.TransparencyAttrib.MAlpha)
        self.pad_response_circle.hide()
        self.accept('window-event', self.handle_window_event)

        # Pad control
        self.mouse1_pressed, self.controlling_pad = False, False
        self.accept('mouse1', self.set_mouse1_pressed, [True])
        self.accept('mouse1-up', self.set_mouse1_pressed, [False])

        # Load terrain
        self.heightmaps = {}
        self.set_heightmap('hmap2', 'project/data/heightmaps/hmap2.npy')

        # Heightmap choice
        self.accept('1', self.set_heightmap,
                    ['hmap1', 'project/data/heightmaps/hmap1.npy'])
        self.accept('2', self.set_heightmap,
                    ['hmap2', 'project/data/heightmaps/hmap2.npy'])
        self.accept('3', self.set_heightmap,
                    ['hmap3', 'project/data/heightmaps/hmap3.npy'])
        self.accept('4', self.set_heightmap,
                    ['hmap4', 'project/data/heightmaps/hmap4.npy'])
        self.accept('5', self.set_heightmap,
                    ['hmap5', 'project/data/heightmaps/hmap5.npy'])

        # Tasks
        self.taskMgr.add(self.update_pad, 'UpdatePadTask', sort=1)
        self.last_update_char_time = 0
        self.taskMgr.add(self.update_character, 'UpdateCharacterTask', sort=2)
        self.last_update_cam_time = 0
        self.taskMgr.add(self.update_camera, 'UpdateCameraTask', sort=3)
Пример #28
0
 def reset_level(self):
     self.camera_angle = 0
     self.char_pos = core.LVector3()
Пример #29
0
    def __init__(self):
        super().__init__()

        # Background Image
        bgnode.generate(self.root_node, 'arena')
        bgnode.generate(self.root_node, 'arena', True)

        # Background Music
        self.play_bg_music('the_last_encounter')

        # Arena
        self.arena = Arena(self.root_node, 10, 10)
        self.selected_tile = (0, 0)
        self.move_range_tiles = []
        self.ability_range_tiles = []

        self.player = base.blackboard['player']

        # Player Combatants
        self.player_combatants = [
            Combatant(mon, self.root_node) for mon in self.player.monsters
        ]
        random_placement = p3d.ConfigVariableBool(
            'mercury-random-combat-placement', True).get_value()
        possible_positions = [(x, y) for x in range(2)
                              for y in range(self.arena.sizey - 1)]
        if random_placement:
            placements = random.sample(possible_positions,
                                       len(self.player_combatants))
        else:
            placements = possible_positions
        for combatant, placement in zip(self.player_combatants, placements):
            self.move_combatant_to_tile(combatant, placement, True)
            combatant.set_h(90)
        self.starting_tile_position = (0, 0)

        # Enemy Combatants
        default_combat_type = p3d.ConfigVariableString(
            'mercury-default-combat-type', 'skirmish')
        self.combat_type = base.blackboard.get('combat_type',
                                               default_combat_type)
        if self.combat_type == 'tournament':
            num_enemies = {1: 3, 2: 5, 3: 8}.get(self.player.rank, 8)
        else:
            num_enemies = len(self.player_combatants)
        self.enemy_combatants = [
            Combatant(Monster.gen_random(f'combatant{i}', 1), self.root_node)
            for i in range(num_enemies)
        ]
        possible_positions = [
            (x, y)
            for x in range(self.arena.sizex - 1, self.arena.sizex - 3, -1)
            for y in range(self.arena.sizey - 1)
        ]
        placements = random.sample(possible_positions,
                                   len(self.enemy_combatants))
        for combatant, placement in zip(self.enemy_combatants, placements):
            self.move_combatant_to_tile(combatant, placement, True)
            combatant.set_h(-90)

        # Setup Lighting
        arena_world_center = self.arena.tile_coord_to_world(self.arena.center)
        CommonLighting(self.root_node, arena_world_center)

        # Setup Camera
        base.camera.set_pos(-15, -15, 15)
        lookat_offset = p3d.LVector3(-3, -3, 0)
        base.camera.look_at(
            self.arena.tile_coord_to_world(self.arena.center) + lookat_offset)

        # Setup UI
        self.load_ui('combat')

        # Setup AI
        self.aicontroller = AiController(self.arena, self, self.root_node)

        # Set initial input state
        self.input_state = 'END_TURN'
Пример #30
0
 def tile_coord_to_world(self, tile_pos):
     xtile, ytile = tile_pos
     return p3d.LVector3(xtile * 2, ytile * 2, 0)