Beispiel #1
0
    def __init__(self, **object_data):
        self.renderer = CoreManager.instance().renderer
        self.scene_manager = CoreManager.instance().scene_manager
        self.resource_manager = CoreManager.instance().resource_manager

        self.name = object_data.get('name', 'terrain')
        self.is_render_terrain = object_data.get('is_render_terrain', True)

        self.transform = TransformObject()
        self.transform.set_pos(object_data.get('pos', [0, 0, 0]))
        self.transform.set_rotation(object_data.get('rot', [0, 0, 0]))
        self.transform.set_scale(object_data.get('scale', [1, 1, 1]))

        self.width = object_data.get('width', 10)
        self.height = object_data.get('height', 10)
        self.subdivide_level = object_data.get('subdivide_level', 100)
        self.height_map_size = np.array(object_data.get(
            'height_map_size', [10.0, 10.0]),
                                        dtype=np.float32)

        self.instance_offset = None
        self.instance_buffer = None

        self.terrain_grid = None

        self.texture_height_map_name = object_data.get('texture_height_map',
                                                       "common.noise")
        self.texture_height_map = None
        self.terrain_render = None
        self.terrain_shadow = None

        self.attributes = Attributes()
Beispiel #2
0
 def set_attribute(self, attribute_name, attribute_value, parent_info, attribute_index):
     if attribute_name == 'mesh':
         mesh = CoreManager.instance().resource_manager.get_mesh(attribute_value)
         if mesh and self.mesh != mesh:
             self.set_mesh(mesh)
     elif attribute_name == 'material_instances':
         material_instance = CoreManager.instance().resource_manager.get_material_instance(
             attribute_value[attribute_index])
         self.set_material_instance(material_instance, attribute_index)
Beispiel #3
0
 def set_attribute(self, attribute_name, attribute_value, parent_info,
                   attribute_index):
     if attribute_name in self.macros and self.macros[
             attribute_name] != attribute_value:
         new_macros = copy.deepcopy(self.macros)
         new_macros[attribute_name] = attribute_value
         # if macro was changed then create a new material.
         CoreManager.instance().resource_manager.get_material(
             self.shader_name, new_macros)
Beispiel #4
0
 def set_attribute(self, attribute_name, attribute_value, item_info_history,
                   attribute_index):
     if attribute_name in self.macros and self.macros[
             attribute_name] != attribute_value:
         new_macros = copy.deepcopy(self.macros)
         new_macros[attribute_name] = attribute_value
         # if macro was changed then create a new material.
         CoreManager.instance().resource_manager.get_material(
             self.shader_name, new_macros)
     elif attribute_name in self.uniform_buffers:
         uniform_buffer = self.uniform_buffers[attribute_name]
         default_value = CreateUniformDataFromString(
             uniform_buffer.uniform_type, attribute_value)
         uniform_buffer.set_default_value(default_value)
    def simulateFFTWaves(self):
        framebuffer_manager = CoreManager.instance(
        ).renderer.framebuffer_manager
        RenderTargets = RenderTarget.RenderTargets

        fft_a_framebuffer = framebuffer_manager.get_framebuffer(
            RenderTargets.FFT_A, RenderTargets.FFT_A, RenderTargets.FFT_A,
            RenderTargets.FFT_A, RenderTargets.FFT_A)

        fft_b_framebuffer = framebuffer_manager.get_framebuffer(
            RenderTargets.FFT_B, RenderTargets.FFT_B, RenderTargets.FFT_B,
            RenderTargets.FFT_B, RenderTargets.FFT_B)

        # initialize
        fft_a_framebuffer.bind_framebuffer()
        glClear(GL_COLOR_BUFFER_BIT)

        self.fft_init.use_program()
        self.fft_init.bind_uniform_data("FFT_SIZE", FFT_SIZE)
        self.fft_init.bind_uniform_data("INVERSE_GRID_SIZES",
                                        INVERSE_GRID_SIZES)
        self.fft_init.bind_uniform_data("spectrum_1_2_Sampler",
                                        self.texture_spectrum_1_2)
        self.fft_init.bind_uniform_data("spectrum_3_4_Sampler",
                                        self.texture_spectrum_3_4)
        self.fft_init.bind_uniform_data("t",
                                        self.acc_time * self.simulation_wind)

        self.quad.draw_elements()

        # # fft passes
        self.fft_x.use_program()
        self.fft_x.bind_uniform_data("butterflySampler",
                                     self.texture_butterfly)
        for i in range(PASSES):
            self.fft_x.bind_uniform_data("pass", float(i + 0.5) / PASSES)
            if i % 2 == 0:
                self.fft_x.bind_uniform_data("imgSampler", RenderTargets.FFT_A)
                fft_b_framebuffer.bind_framebuffer()
            else:
                self.fft_x.bind_uniform_data("imgSampler", RenderTargets.FFT_B)
                fft_a_framebuffer.bind_framebuffer()
            self.quad.draw_elements()

        self.fft_y.use_program()
        self.fft_y.bind_uniform_data("butterflySampler",
                                     self.texture_butterfly)
        for i in range(PASSES, PASSES * 2, 1):
            self.fft_y.bind_uniform_data("pass",
                                         float(i - PASSES + 0.5) / PASSES)
            if i % 2 == 0:
                self.fft_y.bind_uniform_data("imgSampler", RenderTargets.FFT_A)
                fft_b_framebuffer.bind_framebuffer()
            else:
                self.fft_y.bind_uniform_data("imgSampler", RenderTargets.FFT_B)
                fft_a_framebuffer.bind_framebuffer()
            self.quad.draw_elements()

        RenderTargets.FFT_A.generate_mipmap()
Beispiel #6
0
    def __init__(self, name, **object_data):
        StaticActor.__init__(self, name, **object_data)

        self.isRendered = False

        if CoreManager.instance().is_basic_mode:
            self.texture_probe = None
        else:
            self.texture_probe = self.generate_texture_probe(self.name)
Beispiel #7
0
 def set_mesh(self, mesh):
     if mesh:
         self.mesh = mesh
         default_material_instance = CoreManager.instance().resource_manager.get_default_material_instance(
             skeletal=mesh.has_bone())
         material_instances = [default_material_instance, ] * len(mesh.geometries)
         for i in range(min(len(self.material_instances), len(material_instances))):
             material_instances[i] = self.material_instances[i]
         self.material_instances = material_instances
    def __init__(self, **object_data):
        self.name = object_data.get('name', 'ocean')
        self.height = object_data.get('height', 0.0)
        self.wind = object_data.get('wind', WIND)
        self.omega = object_data.get('omega', OMEGA)
        self.amplitude = object_data.get('amplitude', AMPLITUDE)

        self.simulation_wind = object_data.get('simulation_wind', 1.0)
        self.simulation_amplitude = object_data.get('simulation_amplitude',
                                                    3.0)
        self.simulation_scale = object_data.get('simulation_scale', 1.0)

        self.is_render_ocean = object_data.get('is_render_ocean', True)
        self.attributes = Attributes()

        self.acc_time = 0.0
        self.fft_seed = 1234
        self.simulation_size = GRID_SIZES * self.simulation_scale

        self.renderer = CoreManager.instance().renderer
        self.scene_manager = CoreManager.instance().scene_manager
        self.resource_manager = CoreManager.instance().resource_manager

        self.fft_init = None
        self.fft_x = None
        self.fft_y = None
        self.fft_render = None
        self.fft_variance = None

        self.texture_spectrum_1_2 = None
        self.texture_spectrum_3_4 = None
        self.texture_slope_variance = None
        self.texture_butterfly = None

        self.quad = None
        self.fft_grid = None

        self.caustic_index = 0
        self.texture_caustics = []

        self.texture_foam = None
        self.texture_noise = None
Beispiel #9
0
 def set_attribute(self, attribute_name, attribute_value, parent_info,
                   attribute_index):
     if attribute_name == 'shader_name':
         if attribute_value != self.shader_name:
             material = CoreManager.instance(
             ).resource_manager.get_material(attribute_value, self.macros)
             self.set_material(material)
     elif attribute_name in 'material_name':
         if self.material:
             material = CoreManager.instance(
             ).resource_manager.get_material(self.material.shader_name)
             self.set_material(material)
     elif attribute_name in self.linked_material_component_map:
         self.set_uniform_data_from_string(attribute_name, attribute_value)
     elif attribute_name in self.macros:
         if self.macros[attribute_name] != attribute_value:
             self.macros[attribute_name] = attribute_value
             material = CoreManager.instance(
             ).resource_manager.get_material(self.material.shader_name,
                                             self.macros)
             self.set_material(material)
     return self.Attributes
Beispiel #10
0
    def __init__(self, **object_data):
        self.renderer = CoreManager.instance().renderer
        self.scene_manager = CoreManager.instance().scene_manager
        self.resource_manager = CoreManager.instance().resource_manager

        self.name = object_data.get('name', 'terrain')
        self.is_render_terrain = object_data.get('is_render_terrain', True)

        self.transform = TransformObject()
        self.transform.set_pos(object_data.get('pos', [0, 0, 0]))
        self.transform.set_rotation(object_data.get('rot', [0, 0, 0]))
        self.transform.set_scale(object_data.get('scale', [1, 1, 1]))

        self.width = object_data.get('width', 10)
        self.height = object_data.get('height', 10)
        self.subdivide_level = object_data.get('subdivide_level', 100)
        self.height_map_size = np.array(object_data.get(
            'height_map_size', [10.0, 10.0]),
                                        dtype=np.float32)

        self.instance_offset = None
        self.set_instance_offset(self.width, self.height)
        self.instance_buffer = InstanceBuffer(name="terrain_instance_buffer",
                                              location_offset=5,
                                              element_datas=[
                                                  FLOAT4_ZERO,
                                              ])

        self.terrain_grid = None
        self.generate_terrain(self.subdivide_level)

        self.texture_height_map = self.resource_manager.get_texture(
            object_data.get('texture_height_map', "common.noise"))
        self.terrain_render = self.resource_manager.get_material_instance(
            'terrain.terrain_render_ps')
        self.terrain_shadow = self.resource_manager.get_material_instance(
            'terrain.terrain_shadow')

        self.attributes = Attributes()
Beispiel #11
0
    def __init__(self, material_name, material_datas={}):
        self.valid = False
        logger.info("Load %s material." % material_name)

        # for save
        self.material_datas = material_datas

        shader_codes = material_datas.get('shader_codes')
        binary_format = material_datas.get('binary_format')
        binary_data = material_datas.get('binary_data')
        uniforms = material_datas.get('uniforms', [])
        uniform_datas = material_datas.get('uniform_datas', {})

        self.material_component_names = [
            x[1] for x in material_datas.get('material_components', [])
        ]
        self.macros = material_datas.get('macros', OrderedDict())

        self.is_translucent = True if 0 < self.macros.get(
            'TRANSPARENT_MATERIAL', 0) else False

        self.name = material_name
        self.shader_name = material_datas.get('shader_name', '')
        self.program = -1
        self.uniform_buffers = dict(
        )  # OrderedDict()  # Declaration order is important.
        self.Attributes = Attributes()

        if CoreManager.instance().is_basic_mode:
            self.valid = True
        else:
            if binary_format is not None and binary_data is not None:
                self.compile_from_binary(binary_format, binary_data)
                self.valid = self.check_validate() and self.check_linked()
                if not self.valid:
                    logger.error(
                        "%s material has been failed to compile from binary" %
                        self.name)

            self.compile_message = ""

            if not self.valid:
                self.compile_from_source(shader_codes)
                self.valid = self.check_validate() and self.check_linked()
                if not self.valid:
                    logger.error(
                        "%s material has been failed to compile from source" %
                        self.name)

            if self.valid:
                self.create_uniform_buffers(uniforms, uniform_datas)
Beispiel #12
0
 def set_attribute(self, attribute_name, attribute_value, item_info_history,
                   attribute_index):
     if 'spline_data' == attribute_name:
         spline_data = CoreManager.instance().resource_manager.get_spline(
             attribute_value)
         if spline_data is not None:
             self.spline_data = spline_data
     elif 'color' == attribute_name:
         self.color = Float4(*attribute_value)
     elif attribute_name == 'pos':
         self.transform.set_pos(attribute_value)
     elif attribute_name == 'rot':
         self.transform.set_rotation(attribute_value)
     elif attribute_name == 'scale':
         self.transform.set_scale(attribute_value)
     elif hasattr(self, attribute_name):
         setattr(self, attribute_name, attribute_value)
Beispiel #13
0
def run(editor=GUIEditor.QT, project_filename=""):
    appCmdQueue = None
    uiCmdQueue = None
    pipe1, pipe2 = None, None
    editor_process = None

    config = Config("config.ini")

    # load last project file
    if "" == project_filename and config.hasValue('Project', 'recent'):
        last_project = config.getValue('Project', 'recent')
        if os.path.exists(last_project):
            project_filename = last_project

    # other process - GUIEditor
    if editor != GUIEditor.CLIENT_MODE:
        appCmdQueue = CustomQueue()
        uiCmdQueue = CustomQueue()
        pipe1, pipe2 = CustomPipe()

        # Select GUI backend
        if editor == GUIEditor.QT:
            from PyEngine3D.UI.QT.MainWindow import run_editor
        elif editor == GUIEditor.TKINTER:
            from PyEngine3D.UI.TKInter.MainWindow import run_editor
        editor_process = Process(target=run_editor, args=(project_filename, uiCmdQueue, appCmdQueue, pipe2))
        editor_process.start()

    # Client process
    coreManager = CoreManager.instance()
    result = coreManager.initialize(appCmdQueue, uiCmdQueue, pipe1, project_filename)
    if result:
        coreManager.run()
        next_next_open_project_filename = coreManager.get_next_open_project_filename()
    else:
        next_next_open_project_filename = ""

    # GUI Editor process end
    if editor_process:
        editor_process.join()

    return next_next_open_project_filename  # reload or not
Beispiel #14
0
    def generate(self, num_scattering_orders=4):
        resource_manager = CoreManager.instance().resource_manager
        framebuffer_manager = CoreManager.instance(
        ).renderer.framebuffer_manager

        if not self.precompute_illuminance:
            lambdas = [kLambdaR, kLambdaG, kLambdaB]
            luminance_from_radiance = Matrix3()
            self.Precompute(lambdas, luminance_from_radiance, False,
                            num_scattering_orders)
        else:
            num_iterations = (self.num_precomputed_wavelengths + 2) / 3
            dlambda = (kLambdaMax - kLambdaMin) / (3 * num_iterations)

            def coeff(L, component):
                x = CieColorMatchingFunctionTableValue(L, 1)
                y = CieColorMatchingFunctionTableValue(L, 2)
                z = CieColorMatchingFunctionTableValue(L, 3)
                return (XYZ_TO_SRGB[component * 3] * x +
                        XYZ_TO_SRGB[component * 3 + 1] * y +
                        XYZ_TO_SRGB[component * 3 + 2] * z) * dlambda

            for i in range(int(num_iterations)):
                lambdas = [
                    kLambdaMin + (3 * i + 0.5) * dlambda,
                    kLambdaMin + (3 * i + 1.5) * dlambda,
                    kLambdaMin + (3 * i + 2.5) * dlambda
                ]

                luminance_from_radiance = Matrix3()

                luminance_from_radiance[0] = [
                    coeff(lambdas[0], 0),
                    coeff(lambdas[1], 0),
                    coeff(lambdas[2], 0)
                ]
                luminance_from_radiance[1] = [
                    coeff(lambdas[0], 1),
                    coeff(lambdas[1], 1),
                    coeff(lambdas[2], 1)
                ]
                luminance_from_radiance[2] = [
                    coeff(lambdas[0], 2),
                    coeff(lambdas[1], 2),
                    coeff(lambdas[2], 2)
                ]

                self.Precompute(lambdas, luminance_from_radiance, 0 < i,
                                num_scattering_orders)

        # Note : recompute compute_transmittance
        framebuffer_manager.bind_framebuffer(self.transmittance_texture)

        recompute_transmittance_mi = resource_manager.get_material_instance(
            'precomputed_atmosphere.recompute_transmittance',
            macros=self.material_instance_macros)
        recompute_transmittance_mi.use_program()
        self.quad.draw_elements()

        # save textures
        def save_texture(texture):
            resource = resource_manager.texture_loader.get_resource(
                texture.name)
            if resource is None:
                resource = resource_manager.texture_loader.create_resource(
                    texture.name, texture)
                resource_manager.texture_loader.save_resource(resource.name)
            else:
                old_texture = resource.get_data()
                old_texture.delete()
                resource.set_data(texture)

        save_texture(self.transmittance_texture)
        save_texture(self.scattering_texture)
        save_texture(self.irradiance_texture)

        if not self.use_combined_textures:
            save_texture(self.optional_single_mie_scattering_texture)
Beispiel #15
0
 def refresh_attribute_info(self):
     CoreManager.instance().send(COMMAND.TRANS_RESOURCE_ATTRIBUTE,
                                 self.get_attribute())
Beispiel #16
0
    def __init__(self, **object_data):
        self.name = object_data.get('name', 'ocean')
        self.height = object_data.get('height', 0.0)
        self.wind = object_data.get('wind', WIND)
        self.omega = object_data.get('omega', OMEGA)
        self.amplitude = object_data.get('amplitude', AMPLITUDE)

        self.simulation_wind = object_data.get('simulation_wind', 1.0)
        self.simulation_amplitude = object_data.get('simulation_amplitude',
                                                    3.0)
        self.simulation_scale = object_data.get('simulation_scale', 1.0)

        self.is_render_ocean = object_data.get('is_render_ocean', True)
        self.attributes = Attributes()

        self.acc_time = 0.0
        self.fft_seed = 1234

        self.renderer = CoreManager.instance().renderer
        self.scene_manager = CoreManager.instance().scene_manager
        self.resource_manager = CoreManager.instance().resource_manager

        self.fft_init = self.resource_manager.get_material_instance(
            'fft_ocean.init')
        self.fft_x = self.resource_manager.get_material_instance(
            'fft_ocean.fft_x')
        self.fft_y = self.resource_manager.get_material_instance(
            'fft_ocean.fft_y')
        self.fft_render = self.resource_manager.get_material_instance(
            'fft_ocean.render')
        self.fft_variance = self.resource_manager.get_material_instance(
            'fft_ocean.fft_variance')

        self.texture_spectrum_1_2 = self.resource_manager.get_texture(
            "fft_ocean.spectrum_1_2", default_texture=False)
        self.texture_spectrum_3_4 = self.resource_manager.get_texture(
            "fft_ocean.spectrum_3_4", default_texture=False)
        self.texture_slope_variance = self.resource_manager.get_texture(
            "fft_ocean.slope_variance", default_texture=False)
        self.texture_butterfly = self.resource_manager.get_texture(
            "fft_ocean.butterfly", default_texture=False)

        self.quad = ScreenQuad.get_vertex_array_buffer()
        self.fft_grid = Plane("FFT_Grid",
                              mode=GL_QUADS,
                              width=GRID_VERTEX_COUNT,
                              height=GRID_VERTEX_COUNT,
                              xz_plane=False)

        self.simulation_size = GRID_SIZES * self.simulation_scale

        if None in (self.texture_spectrum_1_2, self.texture_spectrum_3_4,
                    self.texture_slope_variance, self.texture_butterfly):
            self.generate_texture()

        self.caustic_index = 0
        self.texture_caustics = []
        i = 0
        while True:
            resource_name = "common.water_caustic_%02d" % i
            if self.resource_manager.texture_loader.hasResource(resource_name):
                self.texture_caustics.append(
                    self.resource_manager.get_texture(resource_name))
                i += 1
                continue
            break

        self.texture_foam = self.resource_manager.get_texture(
            "common.water_foam")
        self.texture_noise = self.resource_manager.get_texture("common.noise")
Beispiel #17
0
    def __init__(self, wavelengths, solar_irradiance, sun_angular_radius,
                 bottom_radius, top_radius, rayleigh_density,
                 rayleigh_scattering, mie_density, mie_scattering,
                 mie_extinction, mie_phase_function_g, absorption_density,
                 absorption_extinction, ground_albedo, max_sun_zenith_angle,
                 length_unit_in_meters, num_precomputed_wavelengths,
                 precompute_illuminance, use_combined_textures):

        self.wavelengths = wavelengths
        self.solar_irradiance = solar_irradiance
        self.sun_angular_radius = sun_angular_radius
        self.bottom_radius = bottom_radius
        self.top_radius = top_radius
        self.rayleigh_density = rayleigh_density
        self.rayleigh_scattering = rayleigh_scattering
        self.mie_density = mie_density
        self.mie_scattering = mie_scattering
        self.mie_extinction = mie_extinction
        self.mie_phase_function_g = mie_phase_function_g
        self.absorption_density = absorption_density
        self.absorption_extinction = absorption_extinction
        self.ground_albedo = ground_albedo
        self.max_sun_zenith_angle = max_sun_zenith_angle
        self.length_unit_in_meters = length_unit_in_meters
        self.num_precomputed_wavelengths = num_precomputed_wavelengths
        self.precompute_illuminance = precompute_illuminance
        self.use_combined_textures = use_combined_textures

        self.material_instance_macros = {
            'COMBINED_SCATTERING_TEXTURES': 1 if use_combined_textures else 0
        }

        # Atmosphere shader code
        resource_manager = CoreManager.instance().resource_manager
        shaderLoader = resource_manager.shader_loader
        shader_name = 'precomputed_atmosphere.atmosphere_predefine'
        recompute_atmosphere_predefine = resource_manager.get_shader(
            shader_name)
        recompute_atmosphere_predefine.shader_code = self.glsl_header_factory(
            [kLambdaR, kLambdaG, kLambdaB])
        shaderLoader.save_resource(shader_name)
        shaderLoader.load_resource(shader_name)

        self.transmittance_texture = CreateTexture(
            name="precomputed_atmosphere.transmittance",
            texture_type=Texture2D,
            width=TRANSMITTANCE_TEXTURE_WIDTH,
            height=TRANSMITTANCE_TEXTURE_HEIGHT,
            internal_format=GL_RGBA32F,
            texture_format=GL_RGBA,
            min_filter=GL_LINEAR,
            mag_filter=GL_LINEAR,
            data_type=GL_FLOAT,
            wrap=GL_CLAMP_TO_EDGE)

        self.scattering_texture = CreateTexture(
            name="precomputed_atmosphere.scattering",
            texture_type=Texture3D,
            width=SCATTERING_TEXTURE_WIDTH,
            height=SCATTERING_TEXTURE_HEIGHT,
            depth=SCATTERING_TEXTURE_DEPTH,
            internal_format=GL_RGBA32F,
            texture_format=GL_RGBA,
            min_filter=GL_LINEAR,
            mag_filter=GL_LINEAR,
            data_type=GL_FLOAT,
            wrap=GL_CLAMP_TO_EDGE)

        self.irradiance_texture = CreateTexture(
            name="precomputed_atmosphere.irradiance",
            texture_type=Texture2D,
            width=IRRADIANCE_TEXTURE_WIDTH,
            height=IRRADIANCE_TEXTURE_HEIGHT,
            internal_format=GL_RGBA32F,
            texture_format=GL_RGBA,
            min_filter=GL_LINEAR,
            mag_filter=GL_LINEAR,
            data_type=GL_FLOAT,
            wrap=GL_CLAMP)

        self.optional_single_mie_scattering_texture = None
        if not self.use_combined_textures:
            self.optional_single_mie_scattering_texture = CreateTexture(
                name=
                "precomputed_atmosphere.optional_single_mie_scattering_texture",
                texture_type=Texture3D,
                width=SCATTERING_TEXTURE_WIDTH,
                height=SCATTERING_TEXTURE_HEIGHT,
                depth=SCATTERING_TEXTURE_DEPTH,
                internal_format=GL_RGBA32F,
                texture_format=GL_RGBA,
                min_filter=GL_LINEAR,
                mag_filter=GL_LINEAR,
                data_type=GL_FLOAT,
                wrap=GL_CLAMP)

        self.delta_irradiance_texture = CreateTexture(
            name="precomputed_atmosphere.delta_irradiance_texture",
            texture_type=Texture2D,
            width=IRRADIANCE_TEXTURE_WIDTH,
            height=IRRADIANCE_TEXTURE_HEIGHT,
            internal_format=GL_RGBA32F,
            texture_format=GL_RGBA,
            min_filter=GL_LINEAR,
            mag_filter=GL_LINEAR,
            data_type=GL_FLOAT,
            wrap=GL_CLAMP)

        self.delta_rayleigh_scattering_texture = CreateTexture(
            name="precomputed_atmosphere.delta_rayleigh_scattering_texture",
            texture_type=Texture3D,
            width=SCATTERING_TEXTURE_WIDTH,
            height=SCATTERING_TEXTURE_HEIGHT,
            depth=SCATTERING_TEXTURE_DEPTH,
            internal_format=GL_RGBA32F,
            texture_format=GL_RGBA,
            min_filter=GL_LINEAR,
            mag_filter=GL_LINEAR,
            data_type=GL_FLOAT,
            wrap=GL_CLAMP)

        self.delta_mie_scattering_texture = CreateTexture(
            name="precomputed_atmosphere.delta_mie_scattering_texture",
            texture_type=Texture3D,
            width=SCATTERING_TEXTURE_WIDTH,
            height=SCATTERING_TEXTURE_HEIGHT,
            depth=SCATTERING_TEXTURE_DEPTH,
            internal_format=GL_RGBA32F,
            texture_format=GL_RGBA,
            min_filter=GL_LINEAR,
            mag_filter=GL_LINEAR,
            data_type=GL_FLOAT,
            wrap=GL_CLAMP)

        self.delta_scattering_density_texture = CreateTexture(
            name="precomputed_atmosphere.delta_scattering_density_texture",
            texture_type=Texture3D,
            width=SCATTERING_TEXTURE_WIDTH,
            height=SCATTERING_TEXTURE_HEIGHT,
            depth=SCATTERING_TEXTURE_DEPTH,
            internal_format=GL_RGBA32F,
            texture_format=GL_RGBA,
            min_filter=GL_LINEAR,
            mag_filter=GL_LINEAR,
            data_type=GL_FLOAT,
            wrap=GL_CLAMP)

        self.delta_multiple_scattering_texture = self.delta_rayleigh_scattering_texture

        self.quad = ScreenQuad.get_vertex_array_buffer()
Beispiel #18
0
    def initialize(self):
        resource_manager = CoreManager.instance().resource_manager

        self.atmosphere_material_instance = resource_manager.get_material_instance(
            'precomputed_atmosphere.atmosphere',
            macros={
                'USE_LUMINANCE': 1 if self.luminance_type else 0,
                'COMBINED_SCATTERING_TEXTURES': 1 if self.use_combined_textures else 0
            }
        )

        # precompute constants
        max_sun_zenith_angle = 120.0 / 180.0 * kPi

        rayleigh_layer = DensityProfileLayer(0.0, 1.0, -1.0 / kRayleighScaleHeight, 0.0, 0.0)
        mie_layer = DensityProfileLayer(0.0, 1.0, -1.0 / kMieScaleHeight, 0.0, 0.0)

        ozone_density = [DensityProfileLayer(25000.0, 0.0, 0.0, 1.0 / 15000.0, -2.0 / 3.0),
                         DensityProfileLayer(0.0, 0.0, 0.0, -1.0 / 15000.0, 8.0 / 3.0)]

        wavelengths = []
        solar_irradiance = []
        rayleigh_scattering = []
        mie_scattering = []
        mie_extinction = []
        absorption_extinction = []
        ground_albedo = []

        for i in range(kLambdaMin, kLambdaMax + 1, 10):
            L = float(i) * 1e-3  # micro-meters
            mie = kMieAngstromBeta / kMieScaleHeight * math.pow(L, -kMieAngstromAlpha)
            wavelengths.append(i)
            if self.use_constant_solar_spectrum:
                solar_irradiance.append(kConstantSolarIrradiance)
            else:
                solar_irradiance.append(kSolarIrradiance[int((i - kLambdaMin) / 10)])
            rayleigh_scattering.append(kRayleigh * math.pow(L, -4))
            mie_scattering.append(mie * kMieSingleScatteringAlbedo)
            mie_extinction.append(mie)
            if self.use_ozone:
                absorption_extinction.append(kMaxOzoneNumberDensity * kOzoneCrossSection[int((i - kLambdaMin) / 10)])
            else:
                absorption_extinction.append(0.0)
            ground_albedo.append(kGroundAlbedo)

        rayleigh_density = [rayleigh_layer, ]
        mie_density = [mie_layer, ]

        if Luminance.PRECOMPUTED == self.luminance_type:
            self.kSky[...] = [MAX_LUMINOUS_EFFICACY, MAX_LUMINOUS_EFFICACY, MAX_LUMINOUS_EFFICACY]
        else:
            self.kSky[...] = ComputeSpectralRadianceToLuminanceFactors(wavelengths, solar_irradiance, -3)
        self.kSun[...] = ComputeSpectralRadianceToLuminanceFactors(wavelengths, solar_irradiance, 0)

        # generate precomputed textures
        if not resource_manager.texture_loader.hasResource('precomputed_atmosphere.transmittance') or \
                not resource_manager.texture_loader.hasResource('precomputed_atmosphere.scattering') or \
                not resource_manager.texture_loader.hasResource('precomputed_atmosphere.irradiance') or \
                not resource_manager.texture_loader.hasResource(
                    'precomputed_atmosphere.optional_single_mie_scattering') and not self.use_combined_textures:
            model = Model(wavelengths,
                          solar_irradiance,
                          kSunAngularRadius,
                          kBottomRadius,
                          kTopRadius,
                          rayleigh_density,
                          rayleigh_scattering,
                          mie_density,
                          mie_scattering,
                          mie_extinction,
                          kMiePhaseFunctionG,
                          ozone_density,
                          absorption_extinction,
                          ground_albedo,
                          max_sun_zenith_angle,
                          kLengthUnitInMeters,
                          self.num_precomputed_wavelengths,
                          Luminance.PRECOMPUTED == self.luminance_type,
                          self.use_combined_textures)
            model.generate()

        self.transmittance_texture = resource_manager.get_texture('precomputed_atmosphere.transmittance')
        self.scattering_texture = resource_manager.get_texture('precomputed_atmosphere.scattering')
        self.irradiance_texture = resource_manager.get_texture('precomputed_atmosphere.irradiance')

        if not self.use_combined_textures:
            self.optional_single_mie_scattering_texture = resource_manager.get_texture(
                'precomputed_atmosphere.optional_single_mie_scattering')

        self.cloud_texture = resource_manager.get_texture('precomputed_atmosphere.cloud_3d')
        self.noise_texture = resource_manager.get_texture('precomputed_atmosphere.noise_3d')
Beispiel #19
0
    def Precompute(self, lambdas, luminance_from_radiance, blend,
                   num_scattering_orders):

        resource_manager = CoreManager.instance().resource_manager
        framebuffer_manager = CoreManager.instance(
        ).renderer.framebuffer_manager
        shaderLoader = resource_manager.shader_loader

        shader_name = 'precomputed_atmosphere.compute_atmosphere_predefine'
        compute_atmosphere_predefine = resource_manager.get_shader(shader_name)
        compute_atmosphere_predefine.shader_code = self.glsl_header_factory(
            lambdas)
        shaderLoader.save_resource(shader_name)
        shaderLoader.load_resource(shader_name)

        glEnable(GL_BLEND)
        glBlendEquation(GL_FUNC_ADD)
        glBlendFunc(GL_ONE, GL_ONE)

        # compute_transmittance
        framebuffer_manager.bind_framebuffer(self.transmittance_texture)

        glDisablei(GL_BLEND, 0)

        compute_transmittance_mi = resource_manager.get_material_instance(
            'precomputed_atmosphere.compute_transmittance',
            macros=self.material_instance_macros)
        compute_transmittance_mi.use_program()
        self.quad.draw_elements()

        # compute_direct_irradiance
        framebuffer_manager.bind_framebuffer(self.delta_irradiance_texture,
                                             self.irradiance_texture)

        glDisablei(GL_BLEND, 0)
        if blend:
            glEnablei(GL_BLEND, 1)
        else:
            glDisablei(GL_BLEND, 1)

        compute_direct_irradiance_mi = resource_manager.get_material_instance(
            'precomputed_atmosphere.compute_direct_irradiance',
            macros=self.material_instance_macros)
        compute_direct_irradiance_mi.use_program()
        compute_direct_irradiance_mi.bind_uniform_data(
            'transmittance_texture', self.transmittance_texture)
        self.quad.draw_elements()

        # compute_single_scattering
        if self.optional_single_mie_scattering_texture is None:
            current_framebuffer = framebuffer_manager.bind_framebuffer(
                self.delta_rayleigh_scattering_texture,
                self.delta_mie_scattering_texture, self.scattering_texture)
        else:
            current_framebuffer = framebuffer_manager.bind_framebuffer(
                self.delta_rayleigh_scattering_texture,
                self.delta_mie_scattering_texture, self.scattering_texture,
                self.optional_single_mie_scattering_texture)

        compute_single_scattering_mi = resource_manager.get_material_instance(
            'precomputed_atmosphere.compute_single_scattering',
            macros=self.material_instance_macros)
        compute_single_scattering_mi.use_program()
        compute_single_scattering_mi.bind_uniform_data(
            'luminance_from_radiance', luminance_from_radiance)
        compute_single_scattering_mi.bind_uniform_data(
            'transmittance_texture', self.transmittance_texture)

        glDisablei(GL_BLEND, 0)
        glDisablei(GL_BLEND, 1)
        if blend:
            glEnablei(GL_BLEND, 2)
            glEnablei(GL_BLEND, 3)
        else:
            glDisablei(GL_BLEND, 2)
            glDisablei(GL_BLEND, 3)

        for layer in range(SCATTERING_TEXTURE_DEPTH):
            current_framebuffer.run_bind_framebuffer(target_layer=layer)
            compute_single_scattering_mi.bind_uniform_data("layer", layer)
            self.quad.draw_elements()

        for scattering_order in range(2, num_scattering_orders + 1):
            # compute_scattering_density
            framebuffer = framebuffer_manager.get_framebuffer(
                self.delta_scattering_density_texture)
            glDisablei(GL_BLEND, 0)

            compute_scattering_density_mi = resource_manager.get_material_instance(
                'precomputed_atmosphere.compute_scattering_density',
                macros=self.material_instance_macros)
            compute_scattering_density_mi.use_program()
            compute_scattering_density_mi.bind_uniform_data(
                'transmittance_texture', self.transmittance_texture)
            compute_scattering_density_mi.bind_uniform_data(
                'single_rayleigh_scattering_texture',
                self.delta_rayleigh_scattering_texture)
            compute_scattering_density_mi.bind_uniform_data(
                'single_mie_scattering_texture',
                self.delta_mie_scattering_texture)
            compute_scattering_density_mi.bind_uniform_data(
                'multiple_scattering_texture',
                self.delta_multiple_scattering_texture)
            compute_scattering_density_mi.bind_uniform_data(
                'irradiance_texture', self.delta_irradiance_texture)
            compute_scattering_density_mi.bind_uniform_data(
                'scattering_order', scattering_order)

            for layer in range(SCATTERING_TEXTURE_DEPTH):
                framebuffer.run_bind_framebuffer(target_layer=layer)
                compute_scattering_density_mi.bind_uniform_data('layer', layer)
                self.quad.draw_elements()

            # compute_indirect_irradiance
            framebuffer_manager.bind_framebuffer(self.delta_irradiance_texture,
                                                 self.irradiance_texture)
            glDisablei(GL_BLEND, 0)
            glEnablei(GL_BLEND, 1)

            compute_indirect_irradiance_mi = resource_manager.get_material_instance(
                'precomputed_atmosphere.compute_indirect_irradiance',
                macros=self.material_instance_macros)
            compute_indirect_irradiance_mi.use_program()
            compute_indirect_irradiance_mi.bind_uniform_data(
                'luminance_from_radiance', luminance_from_radiance)
            compute_indirect_irradiance_mi.bind_uniform_data(
                'scattering_order', scattering_order - 1)
            compute_indirect_irradiance_mi.bind_uniform_data(
                'single_rayleigh_scattering_texture',
                self.delta_rayleigh_scattering_texture)
            compute_indirect_irradiance_mi.bind_uniform_data(
                'single_mie_scattering_texture',
                self.delta_mie_scattering_texture)
            compute_indirect_irradiance_mi.bind_uniform_data(
                'multiple_scattering_texture',
                self.delta_multiple_scattering_texture)
            self.quad.draw_elements()

            # compute_multiple_scattering
            framebuffer = framebuffer_manager.get_framebuffer(
                self.delta_multiple_scattering_texture,
                self.scattering_texture)
            glDisablei(GL_BLEND, 0)
            glEnablei(GL_BLEND, 1)

            compute_multiple_scattering_mi = resource_manager.get_material_instance(
                'precomputed_atmosphere.compute_multiple_scattering',
                macros=self.material_instance_macros)
            compute_multiple_scattering_mi.use_program()
            compute_multiple_scattering_mi.bind_uniform_data(
                'luminance_from_radiance', luminance_from_radiance)
            compute_multiple_scattering_mi.bind_uniform_data(
                'transmittance_texture', self.transmittance_texture)
            compute_multiple_scattering_mi.bind_uniform_data(
                'scattering_density_texture',
                self.delta_scattering_density_texture)

            for layer in range(SCATTERING_TEXTURE_DEPTH):
                framebuffer.run_bind_framebuffer(target_layer=layer)
                compute_multiple_scattering_mi.bind_uniform_data(
                    'layer', layer)
                self.quad.draw_elements()
Beispiel #20
0
def CreateUniformDataFromString(data_type, strValue=None):
    """ return converted data from string or default data """
    if data_type == 'bool':
        return np.bool(strValue) if strValue else np.bool(False)
    elif data_type == 'float':
        # return float(strValue) if strValue else 0.0
        return np.float32(strValue) if strValue else np.float32(0)
    elif data_type == 'int':
        # return int(strValue) if strValue else 0
        return np.int32(strValue) if strValue else np.int32(0)
    elif data_type == 'uint':
        # return int(strValue) if strValue else 0
        return np.uint32(strValue) if strValue else np.uint32(0)
    elif data_type in ('vec2', 'vec3', 'vec4', 'bvec2', 'bvec3', 'bvec4', 'ivec2', 'ivec3', 'ivec4', 'uvec2', 'uvec3', 'uvec4'):
        if data_type in ('bvec2', 'bvec3', 'bvec4', 'ivec2', 'ivec3', 'ivec4'):
            dtype = np.int32
        elif data_type in ('uvec2', 'uvec3', 'uvec4'):
            dtype = np.uint32
        else:
            dtype = np.float32

        componentCount = int(data_type[-1])
        if strValue is not None:
            vecValue = eval(strValue) if type(strValue) is str else strValue
            if len(vecValue) == componentCount:
                return np.array(vecValue, dtype=dtype)
            else:
                logger.error(ValueError("%s need %d float members." % (data_type, componentCount)))
                raise ValueError
        else:
            return np.array([1, ] * componentCount, dtype=dtype)
    elif data_type in ('mat2', 'mat3', 'mat4', 'dmat2', 'dmat3', 'dmat4'):
        if data_type in ('dmat2', 'dmat3', 'dmat4'):
            dtype = np.float32
        else:
            dtype = np.double
        componentCount = int(data_type[-1])
        if strValue is not None:
            vecValue = eval(strValue) if type(strValue) is str else strValue
            if len(vecValue) == componentCount:
                return np.array(vecValue, dtype=dtype)
            else:
                logger.error(ValueError("%s need %d float members." % (data_type, componentCount)))
                raise ValueError
        else:
            return np.eye(componentCount, dtype=dtype)
    elif data_type in ('sampler2D', 'image2D'):
        texture = CoreManager.instance().resource_manager.get_texture(strValue or 'common.flat_gray')
        return texture
    elif data_type == 'sampler2DMS':
        logger.warn('sampler2DMS need multisample texture.')
        return CoreManager.instance().resource_manager.get_texture(strValue or 'common.flat_gray')
    elif data_type == 'sampler2DArray':
        return CoreManager.instance().resource_manager.get_texture(strValue or 'common.default_2d_array')
    elif data_type in ('sampler3D', 'image3D'):
        return CoreManager.instance().resource_manager.get_texture(strValue or 'common.default_3d')
    elif data_type == 'samplerCube':
        texture = CoreManager.instance().resource_manager.get_texture(strValue or 'common.default_cube')
        return texture

    error_message = 'Cannot find uniform data of %s.' % data_type
    logger.error(error_message)
    raise ValueError(error_message)
    return None
Beispiel #21
0
    def initialize(self):
        self.core_manager = CoreManager.instance()
        self.resource_manager = self.core_manager.resource_manager
        self.renderer = self.core_manager.renderer
        self.rendertarget_manager = self.core_manager.rendertarget_manager
        self.framebuffer_manager = FrameBufferManager.instance()

        self.quad = ScreenQuad.get_vertex_array_buffer()

        self.bloom = self.resource_manager.get_material_instance("bloom")
        self.bloom_highlight = self.resource_manager.get_material_instance(
            "bloom_highlight")
        self.bloom_downsampling = self.resource_manager.get_material_instance(
            "bloom_downsampling")

        # SSAO
        self.ssao = self.resource_manager.get_material_instance("ssao")
        for i in range(self.ssao_kernel_size):
            scale = float(i) / float(self.ssao_kernel_size)
            scale = min(max(0.1, scale * scale), 1.0)
            self.ssao_kernel[i][0] = random.uniform(-1.0, 1.0)
            self.ssao_kernel[i][1] = random.uniform(0.5, 1.0)
            self.ssao_kernel[i][2] = random.uniform(-1.0, 1.0)
            self.ssao_kernel[i][:] = normalize(self.ssao_kernel[i]) * scale
        self.ssao_random_texture = self.resource_manager.get_texture(
            'common.random_normal')

        # depth of field
        self.compute_focus_distance = self.resource_manager.get_material_instance(
            'compute_focus_distance')
        self.depth_of_field = self.resource_manager.get_material_instance(
            'depth_of_field')

        self.velocity = self.resource_manager.get_material_instance("velocity")

        self.light_shaft = self.resource_manager.get_material_instance(
            "light_shaft")
        self.tonemapping = self.resource_manager.get_material_instance(
            "tonemapping")
        self.blur = self.resource_manager.get_material_instance("blur")
        self.circle_blur = self.resource_manager.get_material_instance(
            "circle_blur")
        self.gaussian_blur = self.resource_manager.get_material_instance(
            "gaussian_blur")
        self.motion_blur = self.resource_manager.get_material_instance(
            "motion_blur")
        self.screen_space_reflection = self.resource_manager.get_material_instance(
            "screen_space_reflection")
        self.screen_space_reflection_resolve = self.resource_manager.get_material_instance(
            "screen_space_reflection_resolve")
        self.linear_depth = self.resource_manager.get_material_instance(
            "linear_depth")
        self.generate_min_z = self.resource_manager.get_material_instance(
            "generate_min_z")
        self.deferred_shading = self.resource_manager.get_material_instance(
            "deferred_shading")
        self.copy_texture_mi = self.resource_manager.get_material_instance(
            "copy_texture")
        self.render_texture_mi = self.resource_manager.get_material_instance(
            "render_texture")
        self.composite_shadowmap = self.resource_manager.get_material_instance(
            "composite_shadowmap")

        # TAA
        self.temporal_antialiasing = self.resource_manager.get_material_instance(
            "temporal_antialiasing")

        def get_anti_aliasing_name(anti_aliasing):
            anti_aliasing = str(anti_aliasing)
            return anti_aliasing.split(
                '.')[-1] if '.' in anti_aliasing else anti_aliasing

        anti_aliasing_list = [
            get_anti_aliasing_name(AntiAliasing.convert_index_to_enum(x))
            for x in range(AntiAliasing.COUNT.value)
        ]
        # Send to GUI
        self.core_manager.send_anti_aliasing_list(anti_aliasing_list)