Exemplo n.º 1
0
    def __init__(self):

        # Setup window size, title and so on
        load_prc_file_data("", """
            win-size 1600 900
            window-title Render Pipeline - Material Sample
        """)

        self.render_pipeline = RenderPipeline()
        self.render_pipeline.create(self)

        # Set time of day
        self.render_pipeline.daytime_mgr.time = "19:17"

        # Load the scene
        model = loader.load_model("scene/TestScene.bam")
        model.reparent_to(render)
        self.render_pipeline.prepare_scene(model)

        # Enable parallax mapping on the floor
        self.render_pipeline.set_effect(model.find("**/FloorPlane"),
            "effects/default.yaml", {"parallax_mapping": True}, 100)

        # Initialize movement controller
        self.controller = MovementController(self)
        self.controller.set_initial_position_hpr(
            Vec3(-17.2912578583, -13.290019989, 6.88211250305),
            Vec3(-39.7285499573, -14.6770210266, 0.0))
        self.controller.setup()
Exemplo n.º 2
0
    def __init__(self):
        # Setup window size and title
        load_prc_file_data("", """
            # win-size 1600 900
            window-title Render Pipeline - Projected Water Example
        """)

        # Construct the render pipeline
        self.render_pipeline = RenderPipeline()
        self.render_pipeline.create(self)
        self.render_pipeline.daytime_mgr.time = "19:17"
        # self.render_pipeline.daytime_mgr.time = "12:00"

        # Initialize the projected water
        self.water = ProjectedWater(WaterOptions)
        self.water.setup_water(pipeline=self.render_pipeline, water_level=-3.0)

        # Initialize movement controller, this is a convenience class
        # to provide an improved camera control compared to Panda3Ds default
        # mouse controller.
        self.controller = MovementController(self)
        self.controller.set_initial_position_hpr(
            Vec3(-23.2, -32.5, 5.3),
            Vec3(-33.8, -8.3, 0.0))
        self.controller.setup()
Exemplo n.º 3
0
    def __init__(self):
        from rpcore import RenderPipeline, PointLight
        from rpcore.util.movement_controller import MovementController

        self.render_pipeline = RenderPipeline()
        self.render_pipeline.create(self)

        self.render_pipeline.daytime_mgr.time = '08:00'

        self.point_light = PointLight()
        self.point_light.set_color(1, 1, 0.9)
        self.point_light.set_energy(10)
        self.point_light.set_pos(0, 5, 2)
        self.point_light.set_radius(20)
        self.render_pipeline.add_light(self.point_light)

        # load animations from EGG, because glTF animations aren't supported
        self.actor = Actor('snake.gltf', {'move': 'snake_anim.egg'})
        self.actor.reparent_to(self.render)
        self.actor.set_h(180)
        self.actor.loop('move')

        self.controller = MovementController(self)
        self.controller.set_initial_position_hpr(
            Vec3(0, 5, 0.8),  # position
            Vec3(180, -10, 0))  # hpr
        self.controller.setup()
Exemplo n.º 4
0
    def __init__(self):
        from rpcore import RenderPipeline, PointLight
        from rpcore.util.movement_controller import MovementController

        self.render_pipeline = RenderPipeline()
        self.render_pipeline.create(self)

        self.render_pipeline.daytime_mgr.time = '08:00'

        self.point_light = PointLight()
        self.point_light.set_color(1, 1, 0.9)
        self.point_light.set_energy(10)
        self.point_light.set_pos(0, 5, 2)
        self.point_light.set_radius(20)
        self.render_pipeline.add_light(self.point_light)

        self.ruby = Actor('ruby.egg', {'idle': 'ruby_anim.egg'})
        self.ruby.reparent_to(self.render)
        self.ruby.set_h(180)
        self.ruby.loop('idle')

        self.controller = MovementController(self)
        self.controller.set_initial_position_hpr(
            Vec3(0, 5, 1.75),  # position
            Vec3(180, -10, 0))  # hpr
        self.controller.setup()
Exemplo n.º 5
0
    def __init__(self):
        # Setup window size and title
        load_prc_file_data(
            "", """
            # win-size 1600 900
            window-title Render Pipeline - Material Sample
        """)

        # Construct the render pipeline
        self.render_pipeline = RenderPipeline()
        self.render_pipeline.create(self)
        self.render_pipeline.daytime_mgr.time = "19:17"
        # self.render_pipeline.daytime_mgr.time = "12:00"

        # Load the scene
        model = self.loader.load_model("scene/TestScene.bam")
        model.reparent_to(self.render)

        self.render_pipeline.prepare_scene(model)

        # Enable parallax mapping on the floor
        # self.render_pipeline.set_effect(
        #     model.find("**/FloorPlane"),
        #     "effects/default.yaml", {"parallax_mapping": True}, 100)

        # Initialize movement controller, this is a convenience class
        # to provide an improved camera control compared to Panda3Ds default
        # mouse controller.
        self.controller = MovementController(self)
        self.controller.set_initial_position_hpr(
            Vec3(-17.2912578583, -13.290019989, 6.88211250305),
            Vec3(-39.7285499573, -14.6770210266, 0.0))
        self.controller.setup()
Exemplo n.º 6
0
    def __init__(self):
        load_prc_file_data("", "win-size 1600 900")
        load_prc_file_data("", "window-title :)")
        # Later maybe icon/sound

        # -------RENDER PIPELINE--------

        pipeline_path = "../../"
        if not os.path.isfile(os.path.join(pipeline_path, "setup.py")):
            pipeline_path = "../../RenderPipeline/"

        sys.path.insert(0, pipeline_path)
        # Use the utility script to import the render pipeline classes
        from rpcore import RenderPipeline

        self.render_pipeline = RenderPipeline()
        self.render_pipeline.create(self)

        # -------END OF PIPELINE -------

        # time of day
        self.render_pipeline.daytime_mgr.time = 0.812

        self.menu = Menu(self)
        self.level = Level(self)
        self.cube = Cube(self.level, "./models/player1.egg", 1)
        self.cube1 = Cube(self.level, "./models/player2.egg", 2)
        self.movement = Movement(self.cube, self.cube1)
        self.cube.setMovement(self.movement)
        self.cube1.setMovement(self.movement)
        self.camControl = CamControl(self.cube)
        self.gui = GUI(self)
        self.menu.showMenu()
        base.accept("i", self.camControl.zoomIn)
        base.accept("o", self.camControl.zoomOut)
Exemplo n.º 7
0
    def __init__(self):
        from rpcore import RenderPipeline, PointLight
        from rpcore.util.movement_controller import MovementController

        self.render_pipeline = RenderPipeline()
        self.render_pipeline.create(self)

        self.render_pipeline.daytime_mgr.time = '08:00'

        self.point_light = PointLight()
        self.point_light.set_color(1, 1, 0.9)
        self.point_light.set_energy(10)
        self.point_light.set_pos(0, 5, 2)
        self.point_light.set_radius(20)
        self.render_pipeline.add_light(self.point_light)

        # load animations from EGG, because glTF animations aren't supported
        self.ruby_scene = self.loader.load_model('ruby.gltf')
        self.ruby = Actor(self.ruby_scene.find('+Character'), {'idle': 'ruby_anim.egg'})
        self.ruby.reparent_to(self.render)
        self.ruby.set_h(180)
        self.ruby.loop('idle')

        self.controller = MovementController(self)
        self.controller.set_initial_position_hpr(
            Vec3(0, 5, 1.75),  # position
            Vec3(180, -10, 0))  # hpr
        self.controller.setup()
    def __init__(self):
        from rpcore import RenderPipeline, PointLight
        from rpcore.util.movement_controller import MovementController

        self.render_pipeline = RenderPipeline()
        self.render_pipeline.create(self)

        self.render_pipeline.daytime_mgr.time = '08:00'

        self.point_light = PointLight()
        self.point_light.set_color(1, 1, 0.9)
        self.point_light.set_energy(10)
        self.point_light.set_pos(0, 5, 2)
        self.point_light.set_radius(20)
        self.render_pipeline.add_light(self.point_light)

        self.ruby = Actor('ruby_mesh.gltf', {'idle': 'ruby_anim.egg'})
        self.ruby.reparent_to(self.render)
        self.ruby.set_h(180)
        self.ruby.loop('idle')

        self.render_pipeline.set_effect(self.ruby, 'hardware_skinning.yaml', options={}, sort=25)
        sattrib = self.ruby.get_attrib(ShaderAttrib)
        sattrib = sattrib.set_flag(ShaderAttrib.F_hardware_skinning, True)
        self.ruby.set_attrib(sattrib)

        self.controller = MovementController(self)
        self.controller.set_initial_position_hpr(
            Vec3(0, 5, 1.75),  # position
            Vec3(180, -10, 0))  # hpr
        self.controller.setup()
Exemplo n.º 9
0
    def __init__(self, app):
        self.app = app
        sys.path.insert(0, "./")
        sys.path.insert(0, "./RenderPipeline")
        from rpcore import RenderPipeline

        self.render_pipeline = RenderPipeline()
        self.render_pipeline.create(app)
        from rpcore.util.movement_controller import MovementController
        self.controller = MovementController(app)
        self.controller.setup()
Exemplo n.º 10
0
    def __init__(self):
        cwd = os.path.abspath(os.getcwd())
        if cwd in sys.path:
            sys.path.remove(cwd)

        path = 'dist'
        for i in os.listdir(path):
            if i.endswith('.whl'):
                sys.path.insert(0, os.path.abspath(os.path.join(path, i)))

        from rpcore import RenderPipeline
        self.render_pipeline = RenderPipeline()
        self.render_pipeline.create(self)
Exemplo n.º 11
0
    def __init__(self):

        load_prc_file_data("", "textures-power-2 none")
        load_prc_file_data("", "win-size 1600 900")
        # load_prc_file_data("", "fullscreen #t")
        load_prc_file_data("", "window-title cuboid")
        load_prc_file_data("", "icon-filename res/icon.ico")

        # I found openal works better for me
        load_prc_file_data("", "audio-library-name p3openal_audio")

        # ------ Begin of render pipeline code ------

        # Insert the pipeline path to the system path, this is required to be
        # able to import the pipeline classes
        pipeline_path = "../../"

        # Just a special case for my development setup, so I don't accidentally
        # commit a wrong path. You can remove this in your own programs.
        if not os.path.isfile(os.path.join(pipeline_path, "setup.py")):
            pipeline_path = "../../RenderPipeline/"

        sys.path.insert(0, pipeline_path)

        # Use the utility script to import the render pipeline classes
        from rpcore import RenderPipeline

        self.render_pipeline = RenderPipeline()
        self.render_pipeline.mount_mgr.mount()
        self.render_pipeline.load_settings("/$$rpconfig/pipeline.yaml")
        self.render_pipeline.settings["pipeline.display_debugger"] = False
        self.render_pipeline.set_empty_loading_screen()
        self.render_pipeline.create(self)

        # [Optional] use the default skybox, you can use your own skybox as well
        # self.render_pipeline.create_default_skybox()

        # ------ End of render pipeline code, thats it! ------

        # Set time of day
        self.render_pipeline.daytime_mgr.time = 0.812

        self.menu = Menu(self)
        self.level = Level(self)
        self.cube = Cube(self.level)
        self.camControl = CamControl(self.cube)
        self.gui = GUI(self)
        self.menu.showMenu()
        base.accept("i", self.camControl.zoomIn)
        base.accept("o", self.camControl.zoomOut)
Exemplo n.º 12
0
    def __init__(self):

        # Setup window size, title and so on
        load_prc_file_data(
            "", """
            win-size 1600 900
            window-title Render Pipeline - Car Demo
        """)

        # ------ Begin of render pipeline code ------

        # Insert the pipeline path to the system path, this is required to be
        # able to import the pipeline classes
        pipeline_path = "../../"

        # Just a special case for my development setup, so I don't accidentally
        # commit a wrong path. You can remove this in your own programs.
        if not os.path.isfile(os.path.join(pipeline_path, "setup.py")):
            pipeline_path = "../../RenderPipeline/"

        sys.path.insert(0, pipeline_path)

        from rpcore import RenderPipeline, SpotLight
        self.render_pipeline = RenderPipeline()
        self.render_pipeline.create(self)

        # This is a helper class for better camera movement - its not really
        # a rendering element, but it included for convenience
        from rpcore.util.movement_controller import MovementController

        # ------ End of render pipeline code, thats it! ------

        self.render_pipeline.daytime_mgr.time = "20:08"

        # Load the scene
        model = loader.loadModel("scene/scene.bam")
        # model = loader.loadModel("scene2/Scene.bam")

        model.reparent_to(render)
        self.render_pipeline.prepare_scene(model)

        # Init movement controller
        self.controller = MovementController(self)
        self.controller.set_initial_position(Vec3(-7.5, -5.3, 1.8),
                                             Vec3(-5.9, -4.0, 1.6))
        self.controller.setup()

        base.accept("l", self.tour)
Exemplo n.º 13
0
    def __init__(self):
        # Notice that you must not call ShowBase.__init__ (or super), the render
        # pipeline does that for you.

        # Insert the pipeline path to the system path, this is required to be
        # able to import the pipeline classes. In case you placed the render
        # pipeline in a subfolder of your project, you have to adjust this.
        sys.path.insert(0, "../../")
        sys.path.insert(0, "../../RenderPipeline")

        # Import render pipeline classes
        from rpcore import RenderPipeline, SpotLight

        # Construct and create the pipeline
        self.render_pipeline = RenderPipeline()
        self.render_pipeline.create(self)
Exemplo n.º 14
0
    def __init__(self):
        #Modify the Panda3D config on-the-fly
        #In this case, edit the window title
        load_prc_file_data(
            "", """window-title PoultryGeist
								  threading-model /Draw
								  multisamples 2
								  framebuffer-multisample 1
							   """)

        # Construct and create the pipeline
        self.render_pipeline = RenderPipeline()
        self.render_pipeline.create(self)

        self.width, self.height = (800, 600)
        render.setAntialias(AntialiasAttrib.MAuto)

        # Set the model quality, (low or high)
        self.quality = "low"
        print("[>] PoultryGeist:\t      Setting Model Resolution to {}".format(
            self.quality.upper()))

        # Set the time
        self.render_pipeline.daytime_mgr.time = "20:15"

        # Turn off normal mouse controls
        self.disableMouse()

        # Hide the cursor
        props = WindowProperties()
        props.setCursorHidden(True)
        props.setMouseMode(WindowProperties.M_relative)
        # Lower the FOV to make the game more difficult
        self.win.requestProperties(props)
        self.camLens.setFov(90)

        # Register the buttons for movement
        self.w_button = KeyboardButton.ascii_key('w'.encode())
        self.s_button = KeyboardButton.ascii_key('s'.encode())

        self.switch_button = KeyboardButton.ascii_key('p'.encode())

        # Initialise the SceneManager
        self.sceneMgr = SceneManager(self)

        # Add the sceneMgr events to run as a task
        taskMgr.add(self.sceneMgr.runSceneTasks, "scene-tasks")
Exemplo n.º 15
0
    def __init__(self):
        # Notice that you must not call ShowBase.__init__ (or super), the
        # render pipeline does that for you. If this is unconvenient for you,
        # have a look at the other initialization possibilities.

        # Insert the pipeline path to the system path, this is required to be
        # able to import the pipeline classes. In case you placed the render
        # pipeline in a subfolder of your project, you have to adjust this.
        sys.path.insert(0, "../../")
        sys.path.insert(0, "../../RenderPipeline")

        # Import the main render pipeline class
        from rpcore import RenderPipeline

        # Construct and create the pipeline
        self.render_pipeline = RenderPipeline()
        self.render_pipeline.create(self)
Exemplo n.º 16
0
    def __init__(self):

        # Construct and create the pipeline
        self.render_pipeline = RenderPipeline()
        self.render_pipeline.create(self)
        self.render_pipeline.daytime_mgr.time = "19:17"
        # ShowBase.__init__(self)

        self.hexgrid = HexGrid(2, 2, self)

        ps = [None]

        def node_click(node):
            if ps[0] is not None:
                ps[0].deselect()
            node.select()
            ps[0] = node

        self.hexgrid.onclick(node_click)
Exemplo n.º 17
0
    def __init__(self):
        if not USE_RP:
            ShowBase.__init__(self)
        else:
            # Construct and create the pipeline
            self.render_pipeline = RenderPipeline()
            self.render_pipeline.create(self)

        self.win.setClearColor(Vec4(0.5, 0.8, 0.8, 1))

        self.disableMouse()

        if not USE_RP:
            self.render.setShaderAuto()

        self.loadingMessage = self.showLoadingMessage()

        self.world = World(self, USE_RP)
        self.acceptOnce('createWorld', self.createWorld)
        self.world.start('--gogogo' in sys.argv)
Exemplo n.º 18
0
    def __init__(self):
        # game version
        game_version = 'version 0.1.3'
        # Setup window size and title
        load_prc_file_data("", """
        win-size 1600 900
        window-title Craft game {}
        """.format(game_version))

        # ------ Begin of render pipeline code ------

        self.render_pipeline = RenderPipeline()
        self.render_pipeline.create(self)

        # ------ End of render pipeline code, that is it! ------

        # Set time of day
        self.render_pipeline.daytime_mgr.time = "5:20"

        # Configuration variables
        self.half_energy = 5000
        self.lamp_fov = 70
        self.lamp_radius = 10
Exemplo n.º 19
0
    def __init__(self, quality):
        # Set the model quality, (super-low, low or high)
        self.quality = quality
        print("[>] PoultryGeist:\t      Setting Model Resolution to {}".format(
            self.quality.upper()))

        load_prc_file_data("", "win-size 1920 1080")

        # Run the standard Showbase init if running in super-low resolution mode
        # Do some stuff if the game is running at normal or high resolution
        if self.quality != 'super-low':
            # Construct and create the pipeline
            self.render_pipeline = RenderPipeline()
            self.render_pipeline.pre_showbase_init()
            super(Application, self).__init__()
            self.render_pipeline.create(self)
            # Enable anti-aliasing for the game
            render.setAntialias(AntialiasAttrib.MAuto)
            # Set the time pipeline lighting simulation time
            self.render_pipeline.daytime_mgr.time = "20:15"

        else:
            super(Application, self).__init__()
            # Enable the filter handler
            self.filters = CommonFilters(base.win, base.cam)
            self.filters.setAmbientOcclusion()

        # Enable particles and physics
        self.enableParticles()

        #Modify the Panda3D config on-the-fly
        #In this case, edit the window title
        load_prc_file_data(
            "", """window-title PoultryGeist
								  threading-model /Draw
								  multisamples 2
								  framebuffer-multisample 1
							   """)

        # Set the window size
        self.width, self.height = (800, 600)

        # Initialise the movement controller
        self.controller = None

        # Turn off normal mouse controls
        self.disableMouse()

        # Hide the cursor
        self.props = WindowProperties()
        #
        self.props.setCursorHidden(True)
        # Lower the FOV to make the game more difficult
        self.win.requestProperties(self.props)
        self.camLens.setFov(60)
        # Reduces the distance of which the camera can render objects close to it
        self.camLens.setNear(0.1)
        # Store and empty renderTree for later use
        self.emptyRenderTree = deepcopy(self.render)

        # Register the buttons for movement
        # TODO remove this and overhaul the button handling
        self.w_button = KeyboardButton.ascii_key('w'.encode())
        self.s_button = KeyboardButton.ascii_key('s'.encode())
        self.l_button = KeyboardButton.ascii_key('l'.encode())

        self.switch_button = KeyboardButton.ascii_key('p'.encode())

        # Initialise the SceneManager
        self.sceneMgr = SceneManager(self)

        # Initialise the collision traverser
        self.collisionTraverser = CollisionTraverser('main_traverser')
        base.cTrav = self.collisionTraverser
        base.cTrav.showCollisions(self.render)

        # Add the sceneMgr events to run as a task
        taskMgr.add(self.sceneMgr.runSceneTasks, "scene-tasks")
Exemplo n.º 20
0
    def __init__(self):

        # Setup window size, title and so on
        load_prc_file_data(
            "", """
        win-size 1600 900
        window-title Render Pipeline - Material blending example
        """)

        # ------ Begin of render pipeline code ------

        # Insert the pipeline path to the system path, this is required to be
        # able to import the pipeline classes
        pipeline_path = "../../"

        # Just a special case for my development setup, so I don't accidentally
        # commit a wrong path. You can remove this in your own programs.
        if not os.path.isfile(os.path.join(pipeline_path, "setup.py")):
            pipeline_path = "../../RenderPipeline/"

        sys.path.insert(0, pipeline_path)

        from rpcore import RenderPipeline, SpotLight
        self.render_pipeline = RenderPipeline()
        self.render_pipeline.create(self)

        # This is a helper class for better camera movement - its not really
        # a rendering element, but it included for convenience
        from rpcore.util.movement_controller import MovementController

        # ------ End of render pipeline code, thats it! ------

        # Set time of day
        self.render_pipeline.daytime_mgr.time = "6:43"

        # Load the scene
        model = loader.loadModel("scene/Scene.bam")
        model.reparent_to(render)

        # Set the material blending effect on the terrain
        terrain = model.find("**/Terrain")
        self.render_pipeline.set_effect(
            terrain,
            "effects/material_blend4.yaml",
            {
                "parallax_mapping": False,  # Not supported
                "alpha_testing": False,
                "normal_mapping":
                False,  # The effect does its own normal mapping
            },
            100)

        # Configure the effect
        terrain.set_shader_input("detail_scale_factor", 4.0)

        # Detailmap blending factors.
        # Blending is calculated as  (detailmap + <add>) ^ <pow>
        # The base map has no blending since it is used as a filling material
        # and blending the base map would cause spots with no material at all.
        terrain.set_shader_input("material_0_pow", 10.0)
        terrain.set_shader_input("material_0_add", 0.5)
        terrain.set_shader_input("material_1_pow", 10.0)
        terrain.set_shader_input("material_1_add", 0.5)
        terrain.set_shader_input("material_2_pow", 10.0)
        terrain.set_shader_input("material_2_add", 0.5)

        # Init movement controller
        self.controller = MovementController(self)
        self.controller.set_initial_position(Vec3(-15.2, -9.0, 11.8),
                                             Vec3(-12.3, -7.0, 9.7))
        self.controller.setup()
Exemplo n.º 21
0
        self.render_pipeline.add_light(my_light)
"""
import sys
from direct.showbase.ShowBase import ShowBase

# Insert the pipeline path to the system path, this is required to be
# able to import the pipeline classes. In case you placed the render
# pipeline in a subfolder of your project, you have to adjust this.
sys.path.insert(0, "../../RenderPipeline")
sys.path.insert(0, "../../")

# Import render pipeline classes
from rpcore import RenderPipeline

# Construct and create the pipeline
render_pipeline = RenderPipeline()
#render_pipeline.pre_showbase_init()

# Construct and create the ShowBase


#from ursina import *
import ursina as urs
from ursina.shaders import basic_lighting_shader
#from ursina.prefabs import Button

#from ursina.prefabs.first_person_controller import FirstPersonController

# create a window
app = urs.Ursina()
Exemplo n.º 22
0
    def __init__(self):
        sys.path.insert(0, "../../")
        load_prc_file_data("", "win-size 512 512")
        load_prc_file_data("", "textures-power-2 none")
        load_prc_file_data("", "print-pipe-types #f")
        load_prc_file_data("", "notify-level-glgsg error")
        # load_prc_file_data("", "win-size 1024 1024")

        from rpcore import RenderPipeline, PointLight

        self.render_pipeline = RenderPipeline()
        self.render_pipeline.mount_mgr.config_dir = "config/"
        self.render_pipeline.set_empty_loading_screen()
        self.render_pipeline.create(self)

        sphere = loader.loadModel("res/sphere.bam")
        sphere.reparent_to(render)

        self.disableMouse()
        self.camLens.setFov(40)
        self.camLens.setNearFar(0.03, 2000.0)
        self.camera.set_pos(0, -3.5, 0)
        self.camera.look_at(0, -2.5, 0)

        self.render2d.hide()
        self.aspect2d.hide()

        light = PointLight()
        light.pos = 10, -10, 10
        light.radius = 1e20
        light.color = (1, 1, 1)
        light.inner_radius = 4.0
        light.energy = 3
        self.render_pipeline.add_light(light)

        light = PointLight()
        light.pos = -10, -10, 10
        light.radius = 1e20
        light.color = (1, 1, 1)
        light.inner_radius = 4.0
        light.energy = 3
        self.render_pipeline.add_light(light)

        for mat in sphere.find_all_materials():
            mat.roughness = material.roughness
            mat.base_color = Vec4(*(list(material.basecolor) + [1]))
            mat.refractive_index = material.ior

            mat.metallic = 1.0 if material.mat_type == "metallic" else 0.0

            if material.mat_type == "clearcoat":
                mat.emission = (2, 0, 0, 0)
                mat.metallic = 1.0
                mat.refractive_index = 1.51

            if material.mat_type == "foliage":
                mat.emission = (5, 0, 0, 0)
                mat.metallic = 0.0
                mat.refractive_index = 1.51

        for i in range(10):
            self.taskMgr.step()

        self.win.save_screenshot("scene-rp.png")

        base.accept("r", self.reload)
Exemplo n.º 23
0
    def __init__(self, rendering: bool):
        """
        Constructor

        :param rendering: boolean indicating whether to use RenderPipeline or default Panda3d as visualization-module.
        """
        super().__init__(self)
        self.dir = Filename.fromOsSpecific(
            pyrado.PANDA_ASSETS_DIR).getFullpath()

        # Initialize RenderPipeline
        if rendering:
            sys.path.insert(0, pyrado.RENDER_PIPELINE_DIR)
            from rpcore import RenderPipeline

            self.render_pipeline = RenderPipeline()
            self.render_pipeline.pre_showbase_init()
            self.render_pipeline.set_loading_screen_image(
                osp.join(self.dir, "logo.png"))
            self.render_pipeline.settings["pipeline.display_debugger"] = False
            self.render_pipeline.create(self)
            self.render_pipeline.daytime_mgr.time = "17:00"
        else:
            self.render_pipeline = None

        # Activate antialiasing
        self.render.setAntialias(AntialiasAttrib.MAuto)

        # Set window properties
        self.windowProperties = WindowProperties()
        self.windowProperties.setForeground(True)
        self.windowProperties.setTitle("Experiment")

        # Set background color
        self.setBackgroundColor(1, 1, 1)

        # Configuration of the lighting
        self.directionalLight1 = DirectionalLight("directionalLight")
        self.directionalLightNP1 = self.render.attachNewNode(
            self.directionalLight1)
        self.directionalLightNP1.setHpr(0, -8, 0)
        self.render.setLight(self.directionalLightNP1)

        self.directionalLight2 = DirectionalLight("directionalLight")
        self.directionalLightNP2 = self.render.attachNewNode(
            self.directionalLight2)
        self.directionalLightNP2.setHpr(180, -20, 0)
        self.render.setLight(self.directionalLightNP2)

        self.ambientLight = AmbientLight("ambientLight")
        self.ambientLightNP = self.render.attachNewNode(self.ambientLight)
        self.ambientLight.setColor((0.1, 0.1, 0.1, 1))
        self.render.setLight(self.ambientLightNP)

        # Create a text node displaying the physic parameters on the top left of the screen
        self.text = TextNode("parameters")
        self.textNodePath = aspect2d.attachNewNode(self.text)
        self.text.setTextColor(0, 0, 0, 1)  # black
        self.textNodePath.setScale(0.07)
        self.textNodePath.setPos(-1.9, 0, 0.9)

        # Configure trace
        self.trace = LineSegs()
        self.trace.setThickness(3)
        self.trace.setColor(0.8, 0.8, 0.8)  # light grey
        self.lines = self.render.attachNewNode("Lines")
        self.last_pos = None

        # Adds one instance of the update function to the task-manager, thus initializes the animation
        self.taskMgr.add(self.update, "update")
Exemplo n.º 24
0
    def __init__(self):
        load_prc_file_data("", "win-size 512 512")
        load_prc_file_data("", "window-type offscreen")
        load_prc_file_data("", "model-cache-dir")
        load_prc_file_data("", "model-cache-textures #f")
        load_prc_file_data("", "textures-power-2 none")
        load_prc_file_data("", "alpha-bits 0")
        load_prc_file_data("", "print-pipe-types #f")

        # Construct render pipeline
        self.render_pipeline = RenderPipeline()
        self.render_pipeline.mount_mgr.config_dir = "config/"
        self.render_pipeline.set_empty_loading_screen()
        self.render_pipeline.create(self)

        self.setup_scene()

        # Disable model caching
        BamCache.get_global_ptr().cache_models = False

        self.update_queue = []
        self.start_listen()

        # Render initial frames
        for i in range(10):
            self.taskMgr.step()

        last_update = 0.0
        self.scene_node = None

        # Wait for updates
        while True:

            # Update once in a while
            curr_time = time.time()
            if curr_time > last_update + 1.0:
                last_update = curr_time
                self.taskMgr.step()

            if self.update_queue:
                if self.scene_node:
                    self.scene_node.remove_node()

                # Only take the latest packet
                payload = self.update_queue.pop(0)
                print("RENDERING:", payload)

                scene = self.loader.loadModel(
                    Filename.from_os_specific(payload["scene"]))

                for light in scene.find_all_matches("**/+PointLight"):
                    light.remove_node()
                for light in scene.find_all_matches("**/+Spotlight"):
                    light.remove_node()

                # Find camera
                main_cam = scene.find("**/Camera")
                if main_cam:
                    transform_mat = main_cam.get_transform(
                        self.render).get_mat()
                    transform_mat = Mat4.convert_mat(
                        CS_zup_right, CS_yup_right) * transform_mat
                    self.camera.set_mat(transform_mat)
                else:
                    print("WARNING: No camera found")
                    self.camera.set_pos(0, -3.5, 0)
                    self.camera.look_at(0, -2.5, 0)

                self.camLens.set_fov(64.0)

                self.scene_node = scene
                scene.reparent_to(self.render)

                # Render scene
                for i in range(8):
                    self.taskMgr.step()

                dest_path = Filename.from_os_specific(payload["dest"])
                print("Saving screenshot to", dest_path)
                self.win.save_screenshot(dest_path)
                self.notify_about_finish(int(payload["pingback_port"]))
Exemplo n.º 25
0
    def __init__(self):

        # Notice that you must not call ShowBase.__init__ (or super), the
        # render pipeline does that for you. If this is unconvenient for you,
        # have a look at the other initialization possibilities.

        # Insert the pipeline path to the system path, this is required to be
        # able to import the pipeline classes. In case you placed the render
        # pipeline in a subfolder of your project, you have to adjust this.
        sys.path.insert(0, "../../")
        sys.path.insert(0, "../../RenderPipeline")

        # Import the main render pipeline class
        from rpcore import RenderPipeline, SpotLight
        world = BulletWorld()
        # Construct and create the pipeline
        self.render_pipeline = RenderPipeline()
        self.render_pipeline.create(self)
        from rpcore.util.movement_controller import MovementController
        self.render_pipeline.daytime_mgr.time = 0.769
        self.controller = MovementController(self)
        self.controller.set_initial_position(Vec3(6.6, -18.8, 4.5),
                                             Vec3(4.7, -16.7, 3.4))
        self.controller.setup()

        # Done! You can start setting up your application stuff as regular now.
        self.keyMap = {
            "left": 0,
            "right": 0,
            "forward": 0,
            "backward": 0,
            "cam-left": 0,
            "cam-right": 0
        }
        self.speed = 1.0
        base.win.setClearColor(Vec4(0, 0, 0, 1))

        #
        # vertex_format = GeomVertexFormat.get_v3n3()
        # vertex_data = GeomVertexData("triangle_data", vertex_format, Geom.UH_static)
        #
        # pos_writer = GeomVertexWriter(vertex_data,"vertex")
        # normal_writer = GeomVertexWriter(vertex_data,"normal")
        # normal = Vec3(0., -1., 0.)
        #
        # pos_writer.add_data3(-1., 0., -1.)
        # pos_writer.add_data3(1., 0., -1.)
        # pos_writer.add_data3(0., 0., 1.)
        #
        # for _ in range(3):
        #     normal_writer.add_data3(normal)
        #
        # prim = GeomTriangles(Geom.UH_static)
        # prim.add_vertices(0, 1, 2)
        #
        # geom = Geom(vertex_data)
        # geom.add_primitive(prim)
        # node = GeomNode("my_triangle")
        # node.add_geom(geom)
        # triangle = NodePath(node)
        # triangle.reparent_to(some_other_nodepath)
        # square1 = create_colored_rect(0, 0, 200, 200)
        # square2 = create_colored_rect(350, 100, 200, 200, (0, 0, 1, 1))
        # square3 = create_colored_rect(-640, -360, 200, 200, (0, 1, 0, 1))
        self.tr1 = create_triangle(0, 0, 0, 0, 200, 0, 0, 0, 200, (0, 1, 0, 1))
        self.tr2 = create_triangle(-500, 0, 0, -300, 200, 0, -300, 0, 200,
                                   (0, 1, 0, 1))
        radius = 60
        height = 40
        shape1 = BulletCylinderShape(radius, height, ZUp)
        shape2 = BulletCylinderShape(Vec3(radius, 0, 0.5 * height), ZUp)
        self.gnode = GeomNode('square')
        # gnode.addGeom(square1)
        # gnode.addGeom(square2)
        # gnode.addGeom(square3)
        height = 1.75
        radius = 0.4
        shape = BulletCapsuleShape(radius, height - 2 * radius, ZUp)
        self.gnode.addGeom(self.tr1)
        self.gnode.addGeom(self.tr2)
        playerNode = BulletCharacterControllerNode(shape, 0.4, 'Player')
        playerNP = self.render.attachNewNode(playerNode)
        playerNP.setPos(0, 0, 14)
        playerNP.setH(45)
        playerNP.setCollideMask(BitMask32.allOn())

        world.attachCharacter(playerNP.node())
        # self.tr1.setPos(400,400, 0)
        # self.render.attachNewNode(self.gnode)

        gnode2 = GeomNode('square2')
        textured_rect = create_textured_rect(-320, 0, 200, 280)
        gnode2.addGeom(textured_rect)

        texture = self.loader.loadTexture("assets/playte.png")
        ship = self.render.attachNewNode(gnode2)
        ship.setTransparency(TransparencyAttrib.MAlpha)
        ship.setTexture(texture)

        # self.ralph = Actor(tr1)

        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(render)

        self.accept("escape", sys.exit)
        self.accept("a", self.setKey, ["left", 1])
        self.accept("d", self.setKey, ["right", 1])
        self.accept("w", self.setKey, ["forward", 1])
        self.accept("p", self.setKey, ["backward", 1])
        self.accept("arrow_left", self.setKey, ["cam-left", 1])
        self.accept("arrow_right", self.setKey, ["cam-right", 1])
        self.accept("a-up", self.setKey, ["left", 0])
        self.accept("d-up", self.setKey, ["right", 0])
        self.accept("w-up", self.setKey, ["forward", 0])
        self.accept("s-up", self.setKey, ["backward", 0])
        self.accept("arrow_left-up", self.setKey, ["cam-left", 0])
        self.accept("arrow_right-up", self.setKey, ["cam-right", 0])
        self.accept("=", self.adjustSpeed, [0.25])
        self.accept("+", self.adjustSpeed, [0.25])
        self.accept("-", self.adjustSpeed, [-0.25])

        taskMgr.add(self.move, "moveTask")

        # Game state variables
        self.isMoving = False

        # Set up the camera

        base.disableMouse()
        base.camera.setPos(5, 5, 0)
        base.camLens.setFov(80)
    def loadPipeline(self):
        self._pipelineEngine = RenderPipeline()
        self._pipelineEngine.create(self)

        # set the time of day for the daytime cycle
        self._pipelineEngine.daytime_mgr.time = '1:00'
    def __init__(self):
        self.bspLoader = Py_CL_BSPLoader()
        self.bspLoader.setGlobalPtr(self.bspLoader)

        if metadata.USE_RENDER_PIPELINE:
            from rpcore import RenderPipeline
            self.pipeline = RenderPipeline()
            self.pipeline.create(self)
        else:
            ShowBase.__init__(self)
            self.loader.destroy()
            self.loader = CogInvasionLoader(self)
            __builtin__.loader = self.loader
            self.graphicsEngine.setDefaultLoader(self.loader.loader)

        self.cam.node().getDisplayRegion(0).setClearDepthActive(1)

        from panda3d.core import RenderAttribRegistry
        from panda3d.core import ShaderAttrib, TransparencyAttrib
        from libpandabsp import BSPMaterialAttrib
        attribRegistry = RenderAttribRegistry.getGlobalPtr()
        attribRegistry.setSlotSort(BSPMaterialAttrib.getClassSlot(), 0)
        attribRegistry.setSlotSort(ShaderAttrib.getClassSlot(), 1)
        attribRegistry.setSlotSort(TransparencyAttrib.getClassSlot(), 2)

        gsg = self.win.getGsg()

        # Let's print out the Graphics information.
        self.notify.info(
            'Graphics Information:\n\tVendor: {0}\n\tRenderer: {1}\n\tVersion: {2}\n\tSupports Cube Maps: {3}\n\tSupports 3D Textures: {4}\n\tSupports Compute Shaders: {5}'
            .format(gsg.getDriverVendor(), gsg.getDriverRenderer(),
                    gsg.getDriverVersion(), str(gsg.getSupportsCubeMap()),
                    str(gsg.getSupports3dTexture()),
                    str(gsg.getSupportsComputeShaders())))

        # Enable shader generation on all of the main scenes
        if gsg.getSupportsBasicShaders() and gsg.getSupportsGlsl():
            render.setShaderAuto()
            render2d.setShaderAuto()
            render2dp.setShaderAuto()
        else:
            # I don't know how this could be possible
            self.notify.error("GLSL shaders unsupported by graphics driver.")
            return

        # Let's disable fog on Intel graphics
        if gsg.getDriverVendor() == "Intel":
            metadata.NO_FOG = 1
            self.notify.info('Applied Intel-specific graphical fix.')

        self.win.disableClears()

        self.camNode.setCameraMask(CIGlobals.MainCameraBitmask)

        from direct.distributed.ClockDelta import globalClockDelta
        __builtin__.globalClockDelta = globalClockDelta

        # Any ComputeNodes should be parented to this node, not render.
        # We isolate ComputeNodes to avoid traversing the same ComputeNodes
        # when doing multi-pass rendering.
        self.computeRoot = NodePath('computeRoot')
        self.computeCam = self.makeCamera(base.win)
        self.computeCam.node().setCullBounds(OmniBoundingVolume())
        self.computeCam.node().setFinal(True)
        self.computeCam.reparentTo(self.computeRoot)

        # Initialized in initStuff()
        self.shaderGenerator = None

        render.hide()

        self.camLens.setNearFar(0.5, 10000)

        self.physicsWorld = BulletWorld()
        # Panda units are in feet, so the gravity is 32 feet per second,
        # not 9.8 meters per second.
        self.physicsWorld.setGravity(Vec3(0, 0, -32.1740))

        self.physicsWorld.setGroupCollisionFlag(7, 1, True)
        self.physicsWorld.setGroupCollisionFlag(7, 2, True)
        self.physicsWorld.setGroupCollisionFlag(7, 3, False)
        self.physicsWorld.setGroupCollisionFlag(7, 4, False)
        self.physicsWorld.setGroupCollisionFlag(7, 8, True)

        self.taskMgr.add(self.__physicsUpdate, "physicsUpdate", sort=30)

        debugNode = BulletDebugNode('Debug')
        self.debugNP = render.attachNewNode(debugNode)
        self.physicsWorld.setDebugNode(self.debugNP.node())

        self.physicsDbgFlag = False
        self.setPhysicsDebug(self.config.GetBool('physics-debug', False))

        #self.shadowCaster = ShadowCaster(Vec3(163, -67, 0))
        #self.shadowCaster.enable()

        self.bspLoader.setGamma(2.2)
        self.bspLoader.setWin(self.win)
        self.bspLoader.setCamera(self.camera)
        self.bspLoader.setRender(self.render)
        self.bspLoader.setMaterialsFile("phase_14/etc/materials.txt")
        #self.bspLoader.setTextureContentsFile("phase_14/etc/texturecontents.txt")
        self.bspLoader.setWantVisibility(True)
        self.bspLoader.setVisualizeLeafs(False)
        self.bspLoader.setWantLightmaps(True)
        #self.bspLoader.setShadowCamPos(Point3(-15, 5, 40))
        #self.bspLoader.setShadowResolution(60 * 2, 1024 * 1)
        self.bspLoader.setPhysicsWorld(self.physicsWorld)
        self.bspLevel = None
        self.materialData = {}
        self.skyBox = None
        self.skyBoxUtil = None

        #self.nmMgr = RNNavMeshManager.get_global_ptr()
        #self.nmMgr.set_root_node_path(self.render)
        #self.nmMgr.get_reference_node_path().reparentTo(self.render)
        #self.nmMgr.start_default_update()
        #self.nmMgr.get_reference_node_path_debug().reparentTo(self.render)
        self.navMeshNp = None

        # Setup 3d audio                                 run before igLoop so 3d positioning doesn't lag behind
        base.audio3d = Audio3DManager(base.sfxManagerList[0], camera, render)
        base.audio3d.setDropOffFactor(0.15)
        base.audio3d.setDopplerFactor(0.15)

        # Setup collision handlers
        base.cTrav = CollisionTraverser()
        base.lifter = CollisionHandlerFloor()
        base.pusher = CollisionHandlerPusher()
        base.queue = CollisionHandlerQueue()

        base.lightingCfg = None

        self.cl_attackMgr = None

        #self.accept('/', self.projectShadows)

        # Let's setup the user input storage system
        uis = UserInputStorage()
        self.inputStore = uis
        self.userInputStorage = uis
        __builtin__.inputStore = uis
        __builtin__.userInputStorage = uis

        self.credits2d = self.render2d.attachNewNode(PGTop("credits2d"))
        self.credits2d.setScale(1.0 / self.getAspectRatio(), 1.0, 1.0)

        self.wakeWaterHeight = -30.0

        self.bloomToggle = False
        self.hdrToggle = False
        self.fxaaToggle = CIGlobals.getSettingsMgr().getSetting(
            "aa").getValue() == "FXAA"
        self.aoToggle = False

        self.music = None
        self.currSongName = None

        render.show(CIGlobals.ShadowCameraBitmask)

        self.avatars = []

        wrm = WaterReflectionManager()
        self.waterReflectionMgr = wrm
        __builtin__.waterReflectionMgr = wrm

        # Let's setup our margins
        base.marginManager = MarginManager()
        base.margins = aspect2d.attachNewNode(
            base.marginManager, DirectGuiGlobals.MIDGROUND_SORT_INDEX + 1)
        base.leftCells = [
            base.marginManager.addCell(0.1, -0.6, base.a2dTopLeft),
            base.marginManager.addCell(0.1, -1.0, base.a2dTopLeft),
            base.marginManager.addCell(0.1, -1.4, base.a2dTopLeft)
        ]
        base.bottomCells = [
            base.marginManager.addCell(0.4, 0.1, base.a2dBottomCenter),
            base.marginManager.addCell(-0.4, 0.1, base.a2dBottomCenter),
            base.marginManager.addCell(-1.0, 0.1, base.a2dBottomCenter),
            base.marginManager.addCell(1.0, 0.1, base.a2dBottomCenter)
        ]
        base.rightCells = [
            base.marginManager.addCell(-0.1, -0.6, base.a2dTopRight),
            base.marginManager.addCell(-0.1, -1.0, base.a2dTopRight),
            base.marginManager.addCell(-0.1, -1.4, base.a2dTopRight)
        ]

        base.mouseWatcherNode.setEnterPattern('mouse-enter-%r')
        base.mouseWatcherNode.setLeavePattern('mouse-leave-%r')
        base.mouseWatcherNode.setButtonDownPattern('button-down-%r')
        base.mouseWatcherNode.setButtonUpPattern('button-up-%r')

        cbm = CullBinManager.getGlobalPtr()
        cbm.addBin('ground', CullBinManager.BTUnsorted, 18)
        # The portal uses the shadow bin by default,
        # but we still want to see it with real shadows.
        cbm.addBin('portal', CullBinManager.BTBackToFront, 19)
        if not metadata.USE_REAL_SHADOWS:
            cbm.addBin('shadow', CullBinManager.BTBackToFront, 19)
        else:
            cbm.addBin('shadow', CullBinManager.BTFixed, -100)
        cbm.addBin('gui-popup', CullBinManager.BTUnsorted, 60)
        cbm.addBin('gsg-popup', CullBinManager.BTFixed, 70)
        self.setBackgroundColor(CIGlobals.DefaultBackgroundColor)
        self.disableMouse()
        self.enableParticles()
        base.camLens.setNearFar(CIGlobals.DefaultCameraNear,
                                CIGlobals.DefaultCameraFar)
        base.transitions = CITransitions(loader)
        base.transitions.IrisModelName = "phase_3/models/misc/iris.bam"
        base.transitions.FadeModelName = "phase_3/models/misc/fade.bam"

        self.accept(self.inputStore.TakeScreenshot,
                    ScreenshotHandler.takeScreenshot)

        #self.accept('u', render.setShaderOff)
        #self.accept('i', render.setShaderOff, [1])
        #self.accept('o', render.setShaderOff, [2])

        # Disabled oobe culling
        #self.accept('o', self.oobeCull)
        #self.accept('c', self.reportCam)

        self.taskMgr.add(self.__updateShadersAndPostProcess,
                         'CIBase.updateShadersAndPostProcess', 47)
        self.taskMgr.add(self.__update3DAudio, 'CIBase.update3DAudio', 59)
Exemplo n.º 28
0
                            window-title {}
                            textures-power-2 none
                            framebuffer-multisample 1
                            multisamples 16
                            """.format(appName))

from direct.showbase.ShowBase import ShowBase
from direct.gui.DirectGui import *
import sys
sys.path.append(r"C:\Users\avise\Desktop\Games\RenderPipeline-master")

USE_RENDER_PIPELINE = True

if USE_RENDER_PIPELINE:
    from rpcore import RenderPipeline, SpotLight
    rp = RenderPipeline()

    models = {
        "terrain": "models/terrain.bam",
        "player": "models/jet/jet2.bam",
    }

else:
    models = {
        "terrain": "models/terrain_non_render_pipeline.egg",
        "player": "models/jet/jet2_non_render_pipeline.egg",
    }


class GameBase(ShowBase):
    def __init__(self, autoSetup=True, debug=False):
Exemplo n.º 29
0
    def __init__(self):

        # Setup window size, title and so on
        load_prc_file_data(
            "", """
        win-size 1600 900
        window-title Render Pipeline - Lights demo
        """)

        # ------ Begin of render pipeline code ------

        # Insert the pipeline path to the system path, this is required to be
        # able to import the pipeline classes
        pipeline_path = "../../"

        # Just a special case for my development setup, so I don't accidentally
        # commit a wrong path. You can remove this in your own programs.
        if not os.path.isfile(os.path.join(pipeline_path, "setup.py")):
            pipeline_path = "../../RenderPipeline/"

        sys.path.insert(0, pipeline_path)

        from rpcore import RenderPipeline, SpotLight
        self.render_pipeline = RenderPipeline()
        self.render_pipeline.create(self)

        # This is a helper class for better camera movement - its not really
        # a rendering element, but it included for convenience
        from rpcore.util.movement_controller import MovementController

        # ------ End of render pipeline code, thats it! ------

        # Set time of day
        self.render_pipeline.daytime_mgr.time = "4:50"

        self.half_energy = 5000
        self.lamp_fov = 70
        self.lamp_radius = 10
        # Load the scene
        model = loader.loadModel("scene/Scene.bam")
        model.reparent_to(render)

        # Animate balls, this is for testing the motion blur
        blend_type = "noBlend"

        np = model.find("**/MBRotate")
        np.hprInterval(1.5,
                       Vec3(360, 360, 0),
                       Vec3(0, 0, 0),
                       blendType=blend_type).loop()

        np = model.find("**/MBUpDown")
        np_pos = np.get_pos() - Vec3(0, 0, 2)
        Sequence(
            np.posInterval(0.15,
                           np_pos + Vec3(0, 0, 6),
                           np_pos,
                           blendType=blend_type),
            np.posInterval(0.15,
                           np_pos,
                           np_pos + Vec3(0, 0, 6),
                           blendType=blend_type)).loop()

        np = model.find("**/MBFrontBack")
        np_pos = np.get_pos() - Vec3(0, 0, 2)
        Sequence(
            np.posInterval(0.15,
                           np_pos + Vec3(0, 6, 0),
                           np_pos,
                           blendType=blend_type),
            np.posInterval(0.15,
                           np_pos,
                           np_pos + Vec3(0, 6, 0),
                           blendType=blend_type)).loop()

        np = model.find("**/MBScale")
        Sequence(
            np.scaleInterval(0.2, Vec3(1.5), Vec3(1), blendType=blend_type),
            np.scaleInterval(0.2, Vec3(1), Vec3(1.5),
                             blendType=blend_type)).loop()

        # Generate temperature lamps
        # This shows how to procedurally create lamps. In this case, we
        # base the lights positions on empties created in blender.
        self._lights = []
        light_key = lambda light: int(light.get_name().split("LampLum")[-1])
        lumlamps = sorted(model.find_all_matches("**/LampLum*"), key=light_key)
        for lumlamp in lumlamps:
            lum = float(lumlamp.get_name()[len("LampLum"):])
            light = SpotLight()
            light.direction = (0, -1.5, -1)
            light.fov = self.lamp_fov
            light.set_color_from_temperature(lum * 1000.0)
            light.energy = self.half_energy
            light.pos = lumlamp.get_pos(self.render)
            light.radius = self.lamp_radius
            light.casts_shadows = False
            light.shadow_map_resolution = 256
            self.render_pipeline.add_light(light)

            # Put Pandas on the edges
            if lumlamp in lumlamps[0:2] + lumlamps[-2:]:
                panda = loader.loadModel("panda")
                panda.reparent_to(render)
                panda_mat = Material("default")
                panda_mat.emission = 0
                panda.set_material(panda_mat)
                panda.set_pos(light.pos)
                panda.set_z(0.65)
                panda.set_h(180 + randint(-60, 60))
                panda.set_scale(0.2)
                panda.set_y(panda.get_y() - 3.0)

            self._lights.append(light)

        self.render_pipeline.prepare_scene(model)

        # Init movement controller
        self.controller = MovementController(self)
        self.controller.set_initial_position(Vec3(23.9, 42.5, 13.4),
                                             Vec3(23.8, 33.4, 10.8))
        self.controller.setup()

        self.day_time = 0.3
        self.time_direction = 0

        # Keys to modify the time, disabled in the demo
        self.accept("k", self.reset)
        self.accept("p", self.set_time_direction, [
            1,
        ])
        self.accept("p-up", self.set_time_direction, [
            0,
        ])
        self.accept("i", self.set_time_direction, [
            -1,
        ])
        self.accept("i-up", self.set_time_direction, [
            0,
        ])

        self.addTask(self.update, "update")
Exemplo n.º 30
0
    def __init__(self):

        # Setup window size, title and so on
        load_prc_file_data("", """
        win-size 1600 900
        window-title Render Pipeline - Roaming Ralph Demo
        """)

        # ------ Begin of render pipeline code ------

        # Insert the pipeline path to the system path, this is required to be
        # able to import the pipeline classes
        pipeline_path = "../../"

        # Just a special case for my development setup, so I don't accidentally
        # commit a wrong path. You can remove this in your own programs.
        if not os.path.isfile(os.path.join(pipeline_path, "setup.py")):
            pipeline_path = "../../RenderPipeline/"

        sys.path.insert(0, pipeline_path)

        from rpcore import RenderPipeline, SpotLight
        self.render_pipeline = RenderPipeline()
        self.render_pipeline.create(self)

        # ------ End of render pipeline code, thats it! ------

        # Set time of day
        self.render_pipeline.daytime_mgr.time = "7:40"

        # Use a special effect for rendering the scene, this is because the
        # roaming ralph model has no normals or valid materials
        self.render_pipeline.set_effect(render, "scene-effect.yaml", {}, sort=250)

        self.keyMap = {"left":0, "right":0, "forward":0, "backward":0, "cam-left":0, "cam-right":0}
        self.speed = 1.0
        base.win.setClearColor(Vec4(0,0,0,1))

        # Post the instructions

        self.inst1 = addInstructions(0.95, "[ESC]  Quit")
        self.inst4 = addInstructions(0.90, "[W]  Run Ralph Forward")
        self.inst4 = addInstructions(0.85, "[S]  Run Ralph Backward")
        self.inst2 = addInstructions(0.80, "[A]  Rotate Ralph Left")
        self.inst3 = addInstructions(0.75, "[D]  Rotate Ralph Right")
        self.inst6 = addInstructions(0.70, "[Left Arrow]  Rotate Camera Left")
        self.inst7 = addInstructions(0.65, "[Right Arrow]  Rotate Camera Right")

        # Set up the environment
        #
        # This environment model contains collision meshes.  If you look
        # in the egg file, you will see the following:
        #
        #    <Collide> { Polyset keep descend }
        #
        # This tag causes the following mesh to be converted to a collision
        # mesh -- a mesh which is optimized for collision, not rendering.
        # It also keeps the original mesh, so there are now two copies ---
        # one optimized for rendering, one for collisions.

        self.environ = loader.loadModel("resources/world")
        self.environ.reparentTo(render)
        self.environ.setPos(0,0,0)


        # Remove wall nodes
        self.environ.find("**/wall").remove_node()

        # Create the main character, Ralph
        self.ralph = Actor("resources/ralph",
                                 {"run":"resources/ralph-run",
                                  "walk":"resources/ralph-walk"})
        self.ralph.reparentTo(render)
        self.ralph.setScale(.2)
        self.ralph.setPos(Vec3(-110.9, 29.4, 1.8))

        # Create a floater object.  We use the "floater" as a temporary
        # variable in a variety of calculations.

        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(render)

        # Accept the control keys for movement and rotation

        self.accept("escape", sys.exit)
        self.accept("a", self.setKey, ["left",1])
        self.accept("d", self.setKey, ["right",1])
        self.accept("w", self.setKey, ["forward",1])
        self.accept("s", self.setKey, ["backward",1])
        self.accept("arrow_left", self.setKey, ["cam-left",1])
        self.accept("arrow_right", self.setKey, ["cam-right",1])
        self.accept("a-up", self.setKey, ["left",0])
        self.accept("d-up", self.setKey, ["right",0])
        self.accept("w-up", self.setKey, ["forward",0])
        self.accept("s-up", self.setKey, ["backward",0])
        self.accept("arrow_left-up", self.setKey, ["cam-left",0])
        self.accept("arrow_right-up", self.setKey, ["cam-right",0])
        self.accept("=", self.adjustSpeed, [0.25])
        self.accept("+", self.adjustSpeed, [0.25])
        self.accept("-", self.adjustSpeed, [-0.25])

        taskMgr.add(self.move,"moveTask")

        # Game state variables
        self.isMoving = False

        # Set up the camera

        base.disableMouse()
        base.camera.setPos(self.ralph.getX() + 10,self.ralph.getY() + 10, 2)
        base.camLens.setFov(80)

        # We will detect the height of the terrain by creating a collision
        # ray and casting it downward toward the terrain.  One ray will
        # start above ralph's head, and the other will start above the camera.
        # A ray may hit the terrain, or it may hit a rock or a tree.  If it
        # hits the terrain, we can detect the height.  If it hits anything
        # else, we rule that the move is illegal.
        self.cTrav = CollisionTraverser()

        self.ralphGroundRay = CollisionRay()
        self.ralphGroundRay.setOrigin(0,0,1000)
        self.ralphGroundRay.setDirection(0,0,-1)
        self.ralphGroundCol = CollisionNode('ralphRay')
        self.ralphGroundCol.addSolid(self.ralphGroundRay)
        self.ralphGroundCol.setFromCollideMask(BitMask32.bit(0))
        self.ralphGroundCol.setIntoCollideMask(BitMask32.allOff())
        self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol)
        self.ralphGroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler)

        self.camGroundRay = CollisionRay()
        self.camGroundRay.setOrigin(0,0,1000)
        self.camGroundRay.setDirection(0,0,-1)
        self.camGroundCol = CollisionNode('camRay')
        self.camGroundCol.addSolid(self.camGroundRay)
        self.camGroundCol.setFromCollideMask(BitMask32.bit(0))
        self.camGroundCol.setIntoCollideMask(BitMask32.allOff())
        self.camGroundColNp = base.camera.attachNewNode(self.camGroundCol)
        self.camGroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler)

        # Uncomment this line to see the collision rays
        #self.ralphGroundColNp.show()
        #self.camGroundColNp.show()

        # Uncomment this line to show a visual representation of the
        # collisions occuring
        #self.cTrav.showCollisions(render)

        # Create some lighting
        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor(Vec4(.3, .3, .3, 1))
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setDirection(Vec3(-5, -5, -5))
        directionalLight.setColor(Vec4(1, 1, 1, 1))
        directionalLight.setSpecularColor(Vec4(1, 1, 1, 1))
        render.setLight(render.attachNewNode(ambientLight))
        render.setLight(render.attachNewNode(directionalLight))