diff options
Diffstat (limited to 'servers')
63 files changed, 1793 insertions, 507 deletions
diff --git a/servers/display_server.cpp b/servers/display_server.cpp index be2a813fd1..3d44484033 100644 --- a/servers/display_server.cpp +++ b/servers/display_server.cpp @@ -346,8 +346,6 @@ void DisplayServer::_bind_methods() { ClassDB::bind_method(D_METHOD("global_menu_remove_item", "menu_root", "idx"), &DisplayServer::global_menu_remove_item); ClassDB::bind_method(D_METHOD("global_menu_clear", "menu_root"), &DisplayServer::global_menu_clear); - ClassDB::bind_method(D_METHOD("alert", "text", "title"), &DisplayServer::alert, DEFVAL("Alert!")); - ClassDB::bind_method(D_METHOD("mouse_set_mode", "mouse_mode"), &DisplayServer::mouse_set_mode); ClassDB::bind_method(D_METHOD("mouse_get_mode"), &DisplayServer::mouse_get_mode); diff --git a/servers/display_server.h b/servers/display_server.h index 8d289b10fd..788206768c 100644 --- a/servers/display_server.h +++ b/servers/display_server.h @@ -143,8 +143,6 @@ public: virtual void global_menu_remove_item(const String &p_menu_root, int p_idx); virtual void global_menu_clear(const String &p_menu_root); - virtual void alert(const String &p_alert, const String &p_title = "ALERT!") = 0; - enum MouseMode { MOUSE_MODE_VISIBLE, MOUSE_MODE_HIDDEN, diff --git a/servers/display_server_headless.h b/servers/display_server_headless.h index 870401b180..d9ee91084f 100644 --- a/servers/display_server_headless.h +++ b/servers/display_server_headless.h @@ -55,8 +55,6 @@ public: bool has_feature(Feature p_feature) const override { return false; } String get_name() const override { return "headless"; } - void alert(const String &p_alert, const String &p_title = "ALERT!") override {} - int get_screen_count() const override { return 0; } Point2i screen_get_position(int p_screen = SCREEN_OF_MAIN_WINDOW) const override { return Point2i(); } Size2i screen_get_size(int p_screen = SCREEN_OF_MAIN_WINDOW) const override { return Size2i(); } diff --git a/servers/physics_2d/body_2d_sw.cpp b/servers/physics_2d/body_2d_sw.cpp index 6f244deb1e..7aa2f9b7de 100644 --- a/servers/physics_2d/body_2d_sw.cpp +++ b/servers/physics_2d/body_2d_sw.cpp @@ -532,13 +532,13 @@ void Body2DSW::integrate_velocities(real_t p_step) { } void Body2DSW::wakeup_neighbours() { - for (List<Pair<Constraint2DSW *, int>>::Element *E = constraint_list.front(); E; E = E->next()) { - const Constraint2DSW *c = E->get().first; + for (const Pair<Constraint2DSW *, int> &E : constraint_list) { + const Constraint2DSW *c = E.first; Body2DSW **n = c->get_body_ptr(); int bc = c->get_body_count(); for (int i = 0; i < bc; i++) { - if (i == E->get().second) { + if (i == E.second) { continue; } Body2DSW *b = n[i]; diff --git a/servers/physics_2d/step_2d_sw.cpp b/servers/physics_2d/step_2d_sw.cpp index b8cb4cddc5..8b30160cc1 100644 --- a/servers/physics_2d/step_2d_sw.cpp +++ b/servers/physics_2d/step_2d_sw.cpp @@ -46,8 +46,8 @@ void Step2DSW::_populate_island(Body2DSW *p_body, LocalVector<Body2DSW *> &p_bod p_body_island.push_back(p_body); } - for (const List<Pair<Constraint2DSW *, int>>::Element *E = p_body->get_constraint_list().front(); E; E = E->next()) { - Constraint2DSW *constraint = (Constraint2DSW *)E->get().first; + for (const Pair<Constraint2DSW *, int> &E : p_body->get_constraint_list()) { + Constraint2DSW *constraint = (Constraint2DSW *)E.first; if (constraint->get_island_step() == _step) { continue; // Already processed. } @@ -56,7 +56,7 @@ void Step2DSW::_populate_island(Body2DSW *p_body, LocalVector<Body2DSW *> &p_bod all_constraints.push_back(constraint); for (int i = 0; i < constraint->get_body_count(); i++) { - if (i == E->get().second) { + if (i == E.second) { continue; } Body2DSW *other_body = constraint->get_body_ptr()[i]; diff --git a/servers/physics_3d/collision_solver_3d_sat.cpp b/servers/physics_3d/collision_solver_3d_sat.cpp index 1cfb9ba3ad..6a7f2b73c5 100644 --- a/servers/physics_3d/collision_solver_3d_sat.cpp +++ b/servers/physics_3d/collision_solver_3d_sat.cpp @@ -629,9 +629,7 @@ public: _FORCE_INLINE_ bool test_axis(const Vector3 &p_axis, bool p_directional = false) { Vector3 axis = p_axis; - if (Math::abs(axis.x) < CMP_EPSILON && - Math::abs(axis.y) < CMP_EPSILON && - Math::abs(axis.z) < CMP_EPSILON) { + if (axis.is_equal_approx(Vector3())) { // strange case, try an upwards separator axis = Vector3(0.0, 1.0, 0.0); } diff --git a/servers/physics_3d/joints/generic_6dof_joint_3d_sw.h b/servers/physics_3d/joints/generic_6dof_joint_3d_sw.h index d46437e782..d0f3dbbd35 100644 --- a/servers/physics_3d/joints/generic_6dof_joint_3d_sw.h +++ b/servers/physics_3d/joints/generic_6dof_joint_3d_sw.h @@ -322,12 +322,12 @@ public: m_angularLimits[2].m_hiLimit = angularUpper.z; } - //! Retrieves the angular limit informacion + //! Retrieves the angular limit information. G6DOFRotationalLimitMotor3DSW *getRotationalLimitMotor(int index) { return &m_angularLimits[index]; } - //! Retrieves the limit informacion + //! Retrieves the limit information. G6DOFTranslationalLimitMotor3DSW *getTranslationalLimitMotor() { return &m_linearLimits; } diff --git a/servers/physics_3d/joints/slider_joint_3d_sw.cpp b/servers/physics_3d/joints/slider_joint_3d_sw.cpp index db9bdb2986..1895fe1e2e 100644 --- a/servers/physics_3d/joints/slider_joint_3d_sw.cpp +++ b/servers/physics_3d/joints/slider_joint_3d_sw.cpp @@ -200,7 +200,7 @@ void SliderJoint3DSW::solve(real_t p_step) { real_t softness = (i) ? m_softnessOrthoLin : (m_solveLinLim ? m_softnessLimLin : m_softnessDirLin); real_t restitution = (i) ? m_restitutionOrthoLin : (m_solveLinLim ? m_restitutionLimLin : m_restitutionDirLin); real_t damping = (i) ? m_dampingOrthoLin : (m_solveLinLim ? m_dampingLimLin : m_dampingDirLin); - // calcutate and apply impulse + // Calculate and apply impulse. real_t normalImpulse = softness * (restitution * depth / p_step - damping * rel_vel) * m_jacLinDiagABInv[i]; Vector3 impulse_vector = normal * normalImpulse; if (dynamic_A) { diff --git a/servers/physics_3d/shape_3d_sw.cpp b/servers/physics_3d/shape_3d_sw.cpp index 2ffab0c923..04a174f9c8 100644 --- a/servers/physics_3d/shape_3d_sw.cpp +++ b/servers/physics_3d/shape_3d_sw.cpp @@ -1783,7 +1783,7 @@ bool HeightMapShape3DSW::intersect_segment(const Vector3 &p_begin, const Vector3 int z = floor(local_begin.z); // Workaround cases where the ray starts at an integer position. - if (Math::abs(cross_x) < CMP_EPSILON) { + if (Math::is_zero_approx(cross_x)) { cross_x += delta_x; // If going backwards, we should ignore the position we would get by the above flooring, // because the ray is not heading in that direction. @@ -1792,7 +1792,7 @@ bool HeightMapShape3DSW::intersect_segment(const Vector3 &p_begin, const Vector3 } } - if (Math::abs(cross_z) < CMP_EPSILON) { + if (Math::is_zero_approx(cross_z)) { cross_z += delta_z; if (z_step == -1) { z -= 1; diff --git a/servers/physics_3d/shape_3d_sw.h b/servers/physics_3d/shape_3d_sw.h index bc8bd3e695..0d1b7cc3d7 100644 --- a/servers/physics_3d/shape_3d_sw.h +++ b/servers/physics_3d/shape_3d_sw.h @@ -128,7 +128,7 @@ class PlaneShape3DSW : public Shape3DSW { public: Plane get_plane() const; - virtual real_t get_area() const { return Math_INF; } + virtual real_t get_area() const { return INFINITY; } virtual PhysicsServer3D::ShapeType get_type() const { return PhysicsServer3D::SHAPE_PLANE; } virtual void project_range(const Vector3 &p_normal, const Transform3D &p_transform, real_t &r_min, real_t &r_max) const; virtual Vector3 get_support(const Vector3 &p_normal) const; diff --git a/servers/physics_3d/soft_body_3d_sw.cpp b/servers/physics_3d/soft_body_3d_sw.cpp index 63a0fe11ba..724125bea8 100644 --- a/servers/physics_3d/soft_body_3d_sw.cpp +++ b/servers/physics_3d/soft_body_3d_sw.cpp @@ -1172,7 +1172,7 @@ struct _SoftBodyIntersectSegmentInfo { Vector3 dir; Vector3 hit_position; uint32_t hit_face_index = -1; - real_t hit_dist_sq = Math_INF; + real_t hit_dist_sq = INFINITY; static bool process_hit(uint32_t p_face_index, void *p_userdata) { _SoftBodyIntersectSegmentInfo &query_info = *(_SoftBodyIntersectSegmentInfo *)(p_userdata); @@ -1203,7 +1203,7 @@ bool SoftBodyShape3DSW::intersect_segment(const Vector3 &p_begin, const Vector3 soft_body->query_ray(p_begin, p_end, _SoftBodyIntersectSegmentInfo::process_hit, &query_info); - if (query_info.hit_dist_sq != Math_INF) { + if (query_info.hit_dist_sq != INFINITY) { r_result = query_info.hit_position; r_normal = soft_body->get_face_normal(query_info.hit_face_index); return true; diff --git a/servers/register_server_types.cpp b/servers/register_server_types.cpp index 717b4e8d14..857f112102 100644 --- a/servers/register_server_types.cpp +++ b/servers/register_server_types.cpp @@ -205,7 +205,7 @@ void register_server_types() { GDREGISTER_CLASS(RDPipelineColorBlendStateAttachment); GDREGISTER_CLASS(RDPipelineColorBlendState); GDREGISTER_CLASS(RDShaderSource); - GDREGISTER_CLASS(RDShaderBytecode); + GDREGISTER_CLASS(RDShaderSPIRV); GDREGISTER_CLASS(RDShaderFile); GDREGISTER_CLASS(RDPipelineSpecializationConstant); diff --git a/servers/rendering/rasterizer_dummy.h b/servers/rendering/rasterizer_dummy.h index 3f751cfbe8..b7cf0983af 100644 --- a/servers/rendering/rasterizer_dummy.h +++ b/servers/rendering/rasterizer_dummy.h @@ -201,6 +201,9 @@ public: void update() override {} void sdfgi_set_debug_probe_select(const Vector3 &p_position, const Vector3 &p_dir) override {} + virtual void decals_set_filter(RS::DecalFilter p_filter) override {} + virtual void light_projectors_set_filter(RS::LightProjectorFilter p_filter) override {} + RasterizerSceneDummy() {} ~RasterizerSceneDummy() {} }; diff --git a/servers/rendering/renderer_rd/cluster_builder_rd.h b/servers/rendering/renderer_rd/cluster_builder_rd.h index ebb81abdad..c0c03eb26a 100644 --- a/servers/rendering/renderer_rd/cluster_builder_rd.h +++ b/servers/rendering/renderer_rd/cluster_builder_rd.h @@ -235,7 +235,7 @@ public: Transform3D xform = view_xform * p_transform; float radius = xform.basis.get_uniform_scale(); - if (radius > 0.98 || radius < 1.02) { + if (radius < 0.98 || radius > 1.02) { xform.basis.orthonormalize(); } diff --git a/servers/rendering/renderer_rd/effects_rd.cpp b/servers/rendering/renderer_rd/effects_rd.cpp index 5cf8895c8e..47bb756d55 100644 --- a/servers/rendering/renderer_rd/effects_rd.cpp +++ b/servers/rendering/renderer_rd/effects_rd.cpp @@ -383,6 +383,8 @@ void EffectsRD::set_color(RID p_dest_texture, const Color &p_color, const Rect2i } void EffectsRD::gaussian_blur(RID p_source_rd_texture, RID p_texture, RID p_back_texture, const Rect2i &p_region, bool p_8bit_dst) { + ERR_FAIL_COND_MSG(!prefer_raster_effects, "Can't use the compute version of the gaussian blur with the mobile renderer."); + memset(©.push_constant, 0, sizeof(CopyPushConstant)); uint32_t base_flags = 0; @@ -416,6 +418,8 @@ void EffectsRD::gaussian_blur(RID p_source_rd_texture, RID p_texture, RID p_back } void EffectsRD::gaussian_glow(RID p_source_rd_texture, RID p_back_texture, const Size2i &p_size, float p_strength, bool p_high_quality, bool p_first_pass, float p_luminance_cap, float p_exposure, float p_bloom, float p_hdr_bleed_treshold, float p_hdr_bleed_scale, RID p_auto_exposure, float p_auto_exposure_grey) { + ERR_FAIL_COND_MSG(prefer_raster_effects, "Can't use the compute version of the gaussian glow with the mobile renderer."); + memset(©.push_constant, 0, sizeof(CopyPushConstant)); CopyMode copy_mode = p_first_pass && p_auto_exposure.is_valid() ? COPY_MODE_GAUSSIAN_GLOW_AUTO_EXPOSURE : COPY_MODE_GAUSSIAN_GLOW; @@ -449,6 +453,57 @@ void EffectsRD::gaussian_glow(RID p_source_rd_texture, RID p_back_texture, const RD::get_singleton()->compute_list_end(); } +void EffectsRD::gaussian_glow_raster(RID p_source_rd_texture, RID p_framebuffer_half, RID p_rd_texture_half, RID p_dest_framebuffer, const Vector2 &p_pixel_size, float p_strength, bool p_high_quality, bool p_first_pass, float p_luminance_cap, float p_exposure, float p_bloom, float p_hdr_bleed_treshold, float p_hdr_bleed_scale, RID p_auto_exposure, float p_auto_exposure_grey) { + ERR_FAIL_COND_MSG(!prefer_raster_effects, "Can't use the fragment version of the gaussian glow with the clustered renderer."); + + memset(&blur_raster.push_constant, 0, sizeof(BlurRasterPushConstant)); + + BlurRasterMode blur_mode = p_first_pass && p_auto_exposure.is_valid() ? BLUR_MODE_GAUSSIAN_GLOW_AUTO_EXPOSURE : BLUR_MODE_GAUSSIAN_GLOW; + uint32_t base_flags = 0; + + blur_raster.push_constant.pixel_size[0] = p_pixel_size.x; + blur_raster.push_constant.pixel_size[1] = p_pixel_size.y; + + blur_raster.push_constant.glow_strength = p_strength; + blur_raster.push_constant.glow_bloom = p_bloom; + blur_raster.push_constant.glow_hdr_threshold = p_hdr_bleed_treshold; + blur_raster.push_constant.glow_hdr_scale = p_hdr_bleed_scale; + blur_raster.push_constant.glow_exposure = p_exposure; + blur_raster.push_constant.glow_white = 0; //actually unused + blur_raster.push_constant.glow_luminance_cap = p_luminance_cap; + + blur_raster.push_constant.glow_auto_exposure_grey = p_auto_exposure_grey; //unused also + + //HORIZONTAL + RD::DrawListID draw_list = RD::get_singleton()->draw_list_begin(p_framebuffer_half, RD::INITIAL_ACTION_KEEP, RD::FINAL_ACTION_READ, RD::INITIAL_ACTION_KEEP, RD::FINAL_ACTION_DISCARD); + RD::get_singleton()->draw_list_bind_render_pipeline(draw_list, blur_raster.pipelines[blur_mode].get_render_pipeline(RD::INVALID_ID, RD::get_singleton()->framebuffer_get_format(p_framebuffer_half))); + RD::get_singleton()->draw_list_bind_uniform_set(draw_list, _get_uniform_set_from_texture(p_source_rd_texture), 0); + if (p_auto_exposure.is_valid() && p_first_pass) { + RD::get_singleton()->draw_list_bind_uniform_set(draw_list, _get_uniform_set_from_texture(p_auto_exposure), 1); + } + RD::get_singleton()->draw_list_bind_index_array(draw_list, index_array); + + blur_raster.push_constant.flags = base_flags | BLUR_FLAG_HORIZONTAL | (p_first_pass ? BLUR_FLAG_GLOW_FIRST_PASS : 0); + RD::get_singleton()->draw_list_set_push_constant(draw_list, &blur_raster.push_constant, sizeof(BlurRasterPushConstant)); + + RD::get_singleton()->draw_list_draw(draw_list, true); + RD::get_singleton()->draw_list_end(); + + blur_mode = BLUR_MODE_GAUSSIAN_GLOW; + + //VERTICAL + draw_list = RD::get_singleton()->draw_list_begin(p_dest_framebuffer, RD::INITIAL_ACTION_KEEP, RD::FINAL_ACTION_READ, RD::INITIAL_ACTION_KEEP, RD::FINAL_ACTION_DISCARD); + RD::get_singleton()->draw_list_bind_render_pipeline(draw_list, blur_raster.pipelines[blur_mode].get_render_pipeline(RD::INVALID_ID, RD::get_singleton()->framebuffer_get_format(p_dest_framebuffer))); + RD::get_singleton()->draw_list_bind_uniform_set(draw_list, _get_uniform_set_from_texture(p_rd_texture_half), 0); + RD::get_singleton()->draw_list_bind_index_array(draw_list, index_array); + + blur_raster.push_constant.flags = base_flags; + RD::get_singleton()->draw_list_set_push_constant(draw_list, &blur_raster.push_constant, sizeof(BlurRasterPushConstant)); + + RD::get_singleton()->draw_list_draw(draw_list, true); + RD::get_singleton()->draw_list_end(); +} + void EffectsRD::screen_space_reflection(RID p_diffuse, RID p_normal_roughness, RenderingServer::EnvironmentSSRRoughnessQuality p_roughness_quality, RID p_blur_radius, RID p_blur_radius2, RID p_metallic, const Color &p_metallic_mask, RID p_depth, RID p_scale_depth, RID p_scale_normal, RID p_output, RID p_output_blur, const Size2i &p_screen_size, int p_max_steps, float p_fade_in, float p_fade_out, float p_tolerance, const CameraMatrix &p_camera) { RD::ComputeListID compute_list = RD::get_singleton()->compute_list_begin(); @@ -736,6 +791,8 @@ void EffectsRD::tonemapper(RID p_source_color, RID p_dst_framebuffer, const Tone } void EffectsRD::luminance_reduction(RID p_source_texture, const Size2i p_source_size, const Vector<RID> p_reduce, RID p_prev_luminance, float p_min_luminance, float p_max_luminance, float p_adjust, bool p_set) { + ERR_FAIL_COND_MSG(prefer_raster_effects, "Can't use compute version of luminance reduction with the mobile renderer."); + luminance_reduce.push_constant.source_size[0] = p_source_size.x; luminance_reduce.push_constant.source_size[1] = p_source_size.y; luminance_reduce.push_constant.max_luminance = p_max_luminance; @@ -774,7 +831,41 @@ void EffectsRD::luminance_reduction(RID p_source_texture, const Size2i p_source_ RD::get_singleton()->compute_list_end(); } +void EffectsRD::luminance_reduction_raster(RID p_source_texture, const Size2i p_source_size, const Vector<RID> p_reduce, Vector<RID> p_fb, RID p_prev_luminance, float p_min_luminance, float p_max_luminance, float p_adjust, bool p_set) { + ERR_FAIL_COND_MSG(!prefer_raster_effects, "Can't use fragment version of luminance reduction with the clustered renderer."); + ERR_FAIL_COND_MSG(p_reduce.size() != p_fb.size(), "Incorrect frame buffer account for luminance reduction."); + + luminance_reduce_raster.push_constant.max_luminance = p_max_luminance; + luminance_reduce_raster.push_constant.min_luminance = p_min_luminance; + luminance_reduce_raster.push_constant.exposure_adjust = p_adjust; + + for (int i = 0; i < p_reduce.size(); i++) { + luminance_reduce_raster.push_constant.source_size[0] = i == 0 ? p_source_size.x : luminance_reduce_raster.push_constant.dest_size[0]; + luminance_reduce_raster.push_constant.source_size[1] = i == 0 ? p_source_size.y : luminance_reduce_raster.push_constant.dest_size[1]; + luminance_reduce_raster.push_constant.dest_size[0] = MAX(luminance_reduce_raster.push_constant.source_size[0] / 8, 1); + luminance_reduce_raster.push_constant.dest_size[1] = MAX(luminance_reduce_raster.push_constant.source_size[1] / 8, 1); + + bool final = !p_set && (luminance_reduce_raster.push_constant.dest_size[0] == 1) && (luminance_reduce_raster.push_constant.dest_size[1] == 1); + LuminanceReduceRasterMode mode = final ? LUMINANCE_REDUCE_FRAGMENT_FINAL : (i == 0 ? LUMINANCE_REDUCE_FRAGMENT_FIRST : LUMINANCE_REDUCE_FRAGMENT); + + RD::DrawListID draw_list = RD::get_singleton()->draw_list_begin(p_fb[i], RD::INITIAL_ACTION_KEEP, RD::FINAL_ACTION_READ, RD::INITIAL_ACTION_KEEP, RD::FINAL_ACTION_DISCARD); + RD::get_singleton()->draw_list_bind_render_pipeline(draw_list, luminance_reduce_raster.pipelines[mode].get_render_pipeline(RD::INVALID_ID, RD::get_singleton()->framebuffer_get_format(p_fb[i]))); + RD::get_singleton()->draw_list_bind_uniform_set(draw_list, _get_uniform_set_from_texture(i == 0 ? p_source_texture : p_reduce[i - 1]), 0); + if (final) { + RD::get_singleton()->draw_list_bind_uniform_set(draw_list, _get_uniform_set_from_texture(p_prev_luminance), 1); + } + RD::get_singleton()->draw_list_bind_index_array(draw_list, index_array); + + RD::get_singleton()->draw_list_set_push_constant(draw_list, &luminance_reduce_raster.push_constant, sizeof(LuminanceReduceRasterPushConstant)); + + RD::get_singleton()->draw_list_draw(draw_list, true); + RD::get_singleton()->draw_list_end(); + } +} + void EffectsRD::bokeh_dof(RID p_base_texture, RID p_depth_texture, const Size2i &p_base_texture_size, RID p_secondary_texture, RID p_halfsize_texture1, RID p_halfsize_texture2, bool p_dof_far, float p_dof_far_begin, float p_dof_far_size, bool p_dof_near, float p_dof_near_begin, float p_dof_near_size, float p_bokeh_size, RenderingServer::DOFBokehShape p_bokeh_shape, RS::DOFBlurQuality p_quality, bool p_use_jitter, float p_cam_znear, float p_cam_zfar, bool p_cam_orthogonal) { + ERR_FAIL_COND_MSG(prefer_raster_effects, "Can't use compute version of BOKEH DOF with the mobile renderer."); + bokeh.push_constant.blur_far_active = p_dof_far; bokeh.push_constant.blur_far_begin = p_dof_far_begin; bokeh.push_constant.blur_far_end = p_dof_far_begin + p_dof_far_size; @@ -924,6 +1015,78 @@ void EffectsRD::bokeh_dof(RID p_base_texture, RID p_depth_texture, const Size2i RD::get_singleton()->compute_list_end(); } +void EffectsRD::blur_dof_raster(RID p_base_texture, RID p_depth_texture, const Size2i &p_base_texture_size, RID p_base_fb, RID p_secondary_texture, RID p_secondary_fb, bool p_dof_far, float p_dof_far_begin, float p_dof_far_size, bool p_dof_near, float p_dof_near_begin, float p_dof_near_size, float p_dof_blur_amount, RS::DOFBlurQuality p_quality, float p_cam_znear, float p_cam_zfar, bool p_cam_orthogonal) { + ERR_FAIL_COND_MSG(!prefer_raster_effects, "Can't use blur DOF with the clustered renderer."); + + memset(&blur_raster.push_constant, 0, sizeof(BlurRasterPushConstant)); + + BlurRasterMode blur_mode; + int qsteps[4] = { 4, 4, 10, 20 }; + uint32_t base_flags = p_cam_orthogonal ? BLUR_FLAG_USE_ORTHOGONAL_PROJECTION : 0; + + Vector2 pixel_size = Vector2(1.0 / p_base_texture_size.width, 1.0 / p_base_texture_size.height); + + blur_raster.push_constant.dof_radius = (p_dof_blur_amount * p_dof_blur_amount) / qsteps[p_quality]; + blur_raster.push_constant.pixel_size[0] = pixel_size.x; + blur_raster.push_constant.pixel_size[1] = pixel_size.y; + blur_raster.push_constant.camera_z_far = p_cam_zfar; + blur_raster.push_constant.camera_z_near = p_cam_znear; + + if (p_dof_far || p_dof_near) { + if (p_quality == RS::DOF_BLUR_QUALITY_HIGH) { + blur_mode = BLUR_MODE_DOF_HIGH; + } else if (p_quality == RS::DOF_BLUR_QUALITY_MEDIUM) { + blur_mode = BLUR_MODE_DOF_MEDIUM; + } else { // for LOW or VERYLOW we use LOW + blur_mode = BLUR_MODE_DOF_LOW; + } + + if (p_dof_far) { + base_flags |= BLUR_FLAG_DOF_FAR; + blur_raster.push_constant.dof_far_begin = p_dof_far_begin; + blur_raster.push_constant.dof_far_end = p_dof_far_begin + p_dof_far_size; + } + + if (p_dof_near) { + base_flags |= BLUR_FLAG_DOF_NEAR; + blur_raster.push_constant.dof_near_begin = p_dof_near_begin; + blur_raster.push_constant.dof_near_end = p_dof_near_begin - p_dof_near_size; + } + + //HORIZONTAL + RD::DrawListID draw_list = RD::get_singleton()->draw_list_begin(p_secondary_fb, RD::INITIAL_ACTION_KEEP, RD::FINAL_ACTION_READ, RD::INITIAL_ACTION_KEEP, RD::FINAL_ACTION_DISCARD); + RD::get_singleton()->draw_list_bind_render_pipeline(draw_list, blur_raster.pipelines[blur_mode].get_render_pipeline(RD::INVALID_ID, RD::get_singleton()->framebuffer_get_format(p_secondary_fb))); + RD::get_singleton()->draw_list_bind_uniform_set(draw_list, _get_uniform_set_from_texture(p_base_texture), 0); + RD::get_singleton()->draw_list_bind_uniform_set(draw_list, _get_uniform_set_from_texture(p_depth_texture), 1); + RD::get_singleton()->draw_list_bind_index_array(draw_list, index_array); + + blur_raster.push_constant.flags = base_flags | BLUR_FLAG_HORIZONTAL; + blur_raster.push_constant.dof_dir[0] = 1.0; + blur_raster.push_constant.dof_dir[1] = 0.0; + + RD::get_singleton()->draw_list_set_push_constant(draw_list, &blur_raster.push_constant, sizeof(BlurRasterPushConstant)); + + RD::get_singleton()->draw_list_draw(draw_list, true); + RD::get_singleton()->draw_list_end(); + + //VERTICAL + draw_list = RD::get_singleton()->draw_list_begin(p_base_fb, RD::INITIAL_ACTION_KEEP, RD::FINAL_ACTION_READ, RD::INITIAL_ACTION_KEEP, RD::FINAL_ACTION_DISCARD); + RD::get_singleton()->draw_list_bind_render_pipeline(draw_list, blur_raster.pipelines[blur_mode].get_render_pipeline(RD::INVALID_ID, RD::get_singleton()->framebuffer_get_format(p_base_fb))); + RD::get_singleton()->draw_list_bind_uniform_set(draw_list, _get_uniform_set_from_texture(p_secondary_texture), 0); + RD::get_singleton()->draw_list_bind_uniform_set(draw_list, _get_uniform_set_from_texture(p_depth_texture), 1); + RD::get_singleton()->draw_list_bind_index_array(draw_list, index_array); + + blur_raster.push_constant.flags = base_flags; + blur_raster.push_constant.dof_dir[0] = 0.0; + blur_raster.push_constant.dof_dir[1] = 1.0; + + RD::get_singleton()->draw_list_set_push_constant(draw_list, &blur_raster.push_constant, sizeof(BlurRasterPushConstant)); + + RD::get_singleton()->draw_list_draw(draw_list, true); + RD::get_singleton()->draw_list_end(); + } +} + void EffectsRD::gather_ssao(RD::ComputeListID p_compute_list, const Vector<RID> p_ao_slices, const SSAOSettings &p_settings, bool p_adaptive_base_pass, RID p_gather_uniform_set, RID p_importance_map_uniform_set) { RD::get_singleton()->compute_list_bind_uniform_set(p_compute_list, p_gather_uniform_set, 0); if ((p_settings.quality == RS::ENV_SSAO_QUALITY_ULTRA) && !p_adaptive_base_pass) { @@ -1188,8 +1351,9 @@ void EffectsRD::generate_ssao(RID p_depth_buffer, RID p_normal_buffer, RID p_dep if (p_settings.quality > RS::ENV_SSAO_QUALITY_VERY_LOW) { if (pass < blur_passes - 2) { blur_pipeline = SSAO_BLUR_PASS_WIDE; + } else { + blur_pipeline = SSAO_BLUR_PASS_SMART; } - blur_pipeline = SSAO_BLUR_PASS_SMART; } for (int i = 0; i < 4; i++) { @@ -1464,7 +1628,35 @@ void EffectsRD::sort_buffer(RID p_uniform_set, int p_size) { RD::get_singleton()->compute_list_end(); } -EffectsRD::EffectsRD() { +EffectsRD::EffectsRD(bool p_prefer_raster_effects) { + prefer_raster_effects = p_prefer_raster_effects; + + if (prefer_raster_effects) { + // init blur shader (on compute use copy shader) + + Vector<String> blur_modes; + blur_modes.push_back("\n#define MODE_GAUSSIAN_BLUR\n"); // BLUR_MODE_GAUSSIAN_BLUR + blur_modes.push_back("\n#define MODE_GAUSSIAN_GLOW\n"); // BLUR_MODE_GAUSSIAN_GLOW + blur_modes.push_back("\n#define MODE_GAUSSIAN_GLOW\n#define GLOW_USE_AUTO_EXPOSURE\n"); // BLUR_MODE_GAUSSIAN_GLOW_AUTO_EXPOSURE + blur_modes.push_back("\n#define MODE_DOF_BLUR\n#define DOF_QUALITY_LOW\n"); // BLUR_MODE_DOF_LOW + blur_modes.push_back("\n#define MODE_DOF_BLUR\n#define DOF_QUALITY_MEDIUM\n"); // BLUR_MODE_DOF_MEDIUM + blur_modes.push_back("\n#define MODE_DOF_BLUR\n#define DOF_QUALITY_HIGH\n"); // BLUR_MODE_DOF_HIGH + + blur_raster.shader.initialize(blur_modes); + memset(&blur_raster.push_constant, 0, sizeof(BlurRasterPushConstant)); + blur_raster.shader_version = blur_raster.shader.version_create(); + + for (int i = 0; i < BLUR_MODE_MAX; i++) { + blur_raster.pipelines[i].setup(blur_raster.shader.version_get_shader(blur_raster.shader_version, i), RD::RENDER_PRIMITIVE_TRIANGLES, RD::PipelineRasterizationState(), RD::PipelineMultisampleState(), RD::PipelineDepthStencilState(), RD::PipelineColorBlendState::create_disabled(), 0); + } + + } else { + // not used in clustered + for (int i = 0; i < BLUR_MODE_MAX; i++) { + blur_raster.pipelines[i].clear(); + } + } + { // Initialize copy Vector<String> copy_modes; copy_modes.push_back("\n#define MODE_GAUSSIAN_BLUR\n"); @@ -1483,10 +1675,21 @@ EffectsRD::EffectsRD() { copy.shader.initialize(copy_modes); memset(©.push_constant, 0, sizeof(CopyPushConstant)); + + if (prefer_raster_effects) { + // disable shaders we can't use + copy.shader.set_variant_enabled(COPY_MODE_GAUSSIAN_COPY, false); + copy.shader.set_variant_enabled(COPY_MODE_GAUSSIAN_COPY_8BIT, false); + copy.shader.set_variant_enabled(COPY_MODE_GAUSSIAN_GLOW, false); + copy.shader.set_variant_enabled(COPY_MODE_GAUSSIAN_GLOW_AUTO_EXPOSURE, false); + } + copy.shader_version = copy.shader.version_create(); for (int i = 0; i < COPY_MODE_MAX; i++) { - copy.pipelines[i] = RD::get_singleton()->compute_pipeline_create(copy.shader.version_get_shader(copy.shader_version, i)); + if (copy.shader.is_variant_enabled(i)) { + copy.pipelines[i] = RD::get_singleton()->compute_pipeline_create(copy.shader.version_get_shader(copy.shader_version, i)); + } } } { @@ -1551,7 +1754,20 @@ EffectsRD::EffectsRD() { } } - { + if (prefer_raster_effects) { + Vector<String> luminance_reduce_modes; + luminance_reduce_modes.push_back("\n#define FIRST_PASS\n"); // LUMINANCE_REDUCE_FRAGMENT_FIRST + luminance_reduce_modes.push_back("\n"); // LUMINANCE_REDUCE_FRAGMENT + luminance_reduce_modes.push_back("\n#define FINAL_PASS\n"); // LUMINANCE_REDUCE_FRAGMENT_FINAL + + luminance_reduce_raster.shader.initialize(luminance_reduce_modes); + memset(&luminance_reduce_raster.push_constant, 0, sizeof(LuminanceReduceRasterPushConstant)); + luminance_reduce_raster.shader_version = luminance_reduce_raster.shader.version_create(); + + for (int i = 0; i < LUMINANCE_REDUCE_FRAGMENT_MAX; i++) { + luminance_reduce_raster.pipelines[i].setup(luminance_reduce_raster.shader.version_get_shader(luminance_reduce_raster.shader_version, i), RD::RENDER_PRIMITIVE_TRIANGLES, RD::PipelineRasterizationState(), RD::PipelineMultisampleState(), RD::PipelineDepthStencilState(), RD::PipelineColorBlendState::create_disabled(), 0); + } + } else { // Initialize luminance_reduce Vector<String> luminance_reduce_modes; luminance_reduce_modes.push_back("\n#define READ_TEXTURE\n"); @@ -1565,6 +1781,10 @@ EffectsRD::EffectsRD() { for (int i = 0; i < LUMINANCE_REDUCE_MAX; i++) { luminance_reduce.pipelines[i] = RD::get_singleton()->compute_pipeline_create(luminance_reduce.shader.version_get_shader(luminance_reduce.shader_version, i)); } + + for (int i = 0; i < LUMINANCE_REDUCE_FRAGMENT_MAX; i++) { + luminance_reduce_raster.pipelines[i].clear(); + } } { @@ -1583,7 +1803,9 @@ EffectsRD::EffectsRD() { cube_to_dp.pipeline.setup(shader, RD::RENDER_PRIMITIVE_TRIANGLES, RD::PipelineRasterizationState(), RD::PipelineMultisampleState(), dss, RD::PipelineColorBlendState(), 0); } - { + if (prefer_raster_effects) { + // not supported + } else { // Initialize bokeh Vector<String> bokeh_modes; bokeh_modes.push_back("\n#define MODE_GEN_BLUR_SIZE\n"); @@ -1974,13 +2196,18 @@ EffectsRD::~EffectsRD() { RD::get_singleton()->free(ssao.gather_constants_buffer); RD::get_singleton()->free(ssao.importance_map_load_counter); - bokeh.shader.version_free(bokeh.shader_version); + if (prefer_raster_effects) { + blur_raster.shader.version_free(blur_raster.shader_version); + luminance_reduce_raster.shader.version_free(luminance_reduce_raster.shader_version); + } else { + bokeh.shader.version_free(bokeh.shader_version); + luminance_reduce.shader.version_free(luminance_reduce.shader_version); + } copy.shader.version_free(copy.shader_version); copy_to_fb.shader.version_free(copy_to_fb.shader_version); cube_to_dp.shader.version_free(cube_to_dp.shader_version); cubemap_downsampler.shader.version_free(cubemap_downsampler.shader_version); filter.shader.version_free(filter.shader_version); - luminance_reduce.shader.version_free(luminance_reduce.shader_version); resolve.shader.version_free(resolve.shader_version); roughness.shader.version_free(roughness.shader_version); roughness_limiter.shader.version_free(roughness_limiter.shader_version); diff --git a/servers/rendering/renderer_rd/effects_rd.h b/servers/rendering/renderer_rd/effects_rd.h index 33d32f0c57..d072564c23 100644 --- a/servers/rendering/renderer_rd/effects_rd.h +++ b/servers/rendering/renderer_rd/effects_rd.h @@ -33,6 +33,7 @@ #include "core/math/camera_matrix.h" #include "servers/rendering/renderer_rd/pipeline_cache_rd.h" +#include "servers/rendering/renderer_rd/shaders/blur_raster.glsl.gen.h" #include "servers/rendering/renderer_rd/shaders/bokeh_dof.glsl.gen.h" #include "servers/rendering/renderer_rd/shaders/copy.glsl.gen.h" #include "servers/rendering/renderer_rd/shaders/copy_to_fb.glsl.gen.h" @@ -41,6 +42,7 @@ #include "servers/rendering/renderer_rd/shaders/cubemap_filter.glsl.gen.h" #include "servers/rendering/renderer_rd/shaders/cubemap_roughness.glsl.gen.h" #include "servers/rendering/renderer_rd/shaders/luminance_reduce.glsl.gen.h" +#include "servers/rendering/renderer_rd/shaders/luminance_reduce_raster.glsl.gen.h" #include "servers/rendering/renderer_rd/shaders/resolve.glsl.gen.h" #include "servers/rendering/renderer_rd/shaders/roughness_limiter.glsl.gen.h" #include "servers/rendering/renderer_rd/shaders/screen_space_reflection.glsl.gen.h" @@ -60,6 +62,63 @@ #include "servers/rendering_server.h" class EffectsRD { + enum BlurRasterMode { + BLUR_MODE_GAUSSIAN_BLUR, + BLUR_MODE_GAUSSIAN_GLOW, + BLUR_MODE_GAUSSIAN_GLOW_AUTO_EXPOSURE, + + BLUR_MODE_DOF_LOW, + BLUR_MODE_DOF_MEDIUM, + BLUR_MODE_DOF_HIGH, + + BLUR_MODE_MAX + }; + + enum { + BLUR_FLAG_HORIZONTAL = (1 << 0), + BLUR_FLAG_USE_ORTHOGONAL_PROJECTION = (1 << 1), + BLUR_FLAG_GLOW_FIRST_PASS = (1 << 2), + BLUR_FLAG_DOF_FAR = (1 << 3), + BLUR_FLAG_DOF_NEAR = (1 << 4), + }; + + struct BlurRasterPushConstant { + float pixel_size[2]; + uint32_t flags; + uint32_t pad; + + //glow + float glow_strength; + float glow_bloom; + float glow_hdr_threshold; + float glow_hdr_scale; + + float glow_exposure; + float glow_white; + float glow_luminance_cap; + float glow_auto_exposure_grey; + + //dof + float dof_far_begin; + float dof_far_end; + float dof_near_begin; + float dof_near_end; + + float dof_radius; + float dof_pad[3]; + + float dof_dir[2]; + float camera_z_far; + float camera_z_near; + }; + + struct BlurRaster { + BlurRasterPushConstant push_constant; + BlurRasterShaderRD shader; + RID shader_version; + PipelineCacheRD pipelines[BLUR_MODE_MAX]; + } blur_raster; + enum CopyMode { COPY_MODE_GAUSSIAN_COPY, COPY_MODE_GAUSSIAN_COPY_8BIT, @@ -239,6 +298,29 @@ class EffectsRD { RID pipelines[LUMINANCE_REDUCE_MAX]; } luminance_reduce; + enum LuminanceReduceRasterMode { + LUMINANCE_REDUCE_FRAGMENT_FIRST, + LUMINANCE_REDUCE_FRAGMENT, + LUMINANCE_REDUCE_FRAGMENT_FINAL, + LUMINANCE_REDUCE_FRAGMENT_MAX + }; + + struct LuminanceReduceRasterPushConstant { + int32_t source_size[2]; + int32_t dest_size[2]; + float exposure_adjust; + float min_luminance; + float max_luminance; + float pad[1]; + }; + + struct LuminanceReduceFragment { + LuminanceReduceRasterPushConstant push_constant; + LuminanceReduceRasterShaderRD shader; + RID shader_version; + PipelineCacheRD pipelines[LUMINANCE_REDUCE_FRAGMENT_MAX]; + } luminance_reduce_raster; + struct CopyToDPPushConstant { float z_far; float z_near; @@ -656,6 +738,8 @@ class EffectsRD { RID _get_compute_uniform_set_from_texture_pair(RID p_texture, RID p_texture2, bool p_use_mipmaps = false); RID _get_compute_uniform_set_from_image_pair(RID p_texture, RID p_texture2); + bool prefer_raster_effects; + public: void copy_to_fb_rect(RID p_source_rd_texture, RID p_dest_framebuffer, const Rect2i &p_rect, bool p_flip_y = false, bool p_force_luminance = false, bool p_alpha_to_zero = false, bool p_srgb = false, RID p_secondary = RID()); void copy_to_rect(RID p_source_rd_texture, RID p_dest_texture, const Rect2i &p_rect, bool p_flip_y = false, bool p_force_luminance = false, bool p_all_source = false, bool p_8_bit_dst = false, bool p_alpha_to_one = false); @@ -666,12 +750,16 @@ public: void gaussian_blur(RID p_source_rd_texture, RID p_texture, RID p_back_texture, const Rect2i &p_region, bool p_8bit_dst = false); void set_color(RID p_dest_texture, const Color &p_color, const Rect2i &p_region, bool p_8bit_dst = false); void gaussian_glow(RID p_source_rd_texture, RID p_back_texture, const Size2i &p_size, float p_strength = 1.0, bool p_high_quality = false, bool p_first_pass = false, float p_luminance_cap = 16.0, float p_exposure = 1.0, float p_bloom = 0.0, float p_hdr_bleed_treshold = 1.0, float p_hdr_bleed_scale = 1.0, RID p_auto_exposure = RID(), float p_auto_exposure_grey = 1.0); + void gaussian_glow_raster(RID p_source_rd_texture, RID p_framebuffer_half, RID p_rd_texture_half, RID p_dest_framebuffer, const Vector2 &p_pixel_size, float p_strength = 1.0, bool p_high_quality = false, bool p_first_pass = false, float p_luminance_cap = 16.0, float p_exposure = 1.0, float p_bloom = 0.0, float p_hdr_bleed_treshold = 1.0, float p_hdr_bleed_scale = 1.0, RID p_auto_exposure = RID(), float p_auto_exposure_grey = 1.0); void cubemap_roughness(RID p_source_rd_texture, RID p_dest_framebuffer, uint32_t p_face_id, uint32_t p_sample_count, float p_roughness, float p_size); void make_mipmap(RID p_source_rd_texture, RID p_dest_texture, const Size2i &p_size); void copy_cubemap_to_dp(RID p_source_rd_texture, RID p_dest_texture, const Rect2 &p_rect, float p_z_near, float p_z_far, bool p_dp_flip); void luminance_reduction(RID p_source_texture, const Size2i p_source_size, const Vector<RID> p_reduce, RID p_prev_luminance, float p_min_luminance, float p_max_luminance, float p_adjust, bool p_set = false); + void luminance_reduction_raster(RID p_source_texture, const Size2i p_source_size, const Vector<RID> p_reduce, Vector<RID> p_fb, RID p_prev_luminance, float p_min_luminance, float p_max_luminance, float p_adjust, bool p_set = false); + void bokeh_dof(RID p_base_texture, RID p_depth_texture, const Size2i &p_base_texture_size, RID p_secondary_texture, RID p_bokeh_texture1, RID p_bokeh_texture2, bool p_dof_far, float p_dof_far_begin, float p_dof_far_size, bool p_dof_near, float p_dof_near_begin, float p_dof_near_size, float p_bokeh_size, RS::DOFBokehShape p_bokeh_shape, RS::DOFBlurQuality p_quality, bool p_use_jitter, float p_cam_znear, float p_cam_zfar, bool p_cam_orthogonal); + void blur_dof_raster(RID p_base_texture, RID p_depth_texture, const Size2i &p_base_texture_size, RID p_base_fb, RID p_secondary_texture, RID p_secondary_fb, bool p_dof_far, float p_dof_far_begin, float p_dof_far_size, bool p_dof_near, float p_dof_near_begin, float p_dof_near_size, float p_dof_blur_amount, RS::DOFBlurQuality p_quality, float p_cam_znear, float p_cam_zfar, bool p_cam_orthogonal); struct TonemapSettings { bool use_glow = false; @@ -751,7 +839,7 @@ public: void sort_buffer(RID p_uniform_set, int p_size); - EffectsRD(); + EffectsRD(bool p_prefer_raster_effects); ~EffectsRD(); }; diff --git a/servers/rendering/renderer_rd/forward_clustered/render_forward_clustered.cpp b/servers/rendering/renderer_rd/forward_clustered/render_forward_clustered.cpp index b457f5d122..ac20515c28 100644 --- a/servers/rendering/renderer_rd/forward_clustered/render_forward_clustered.cpp +++ b/servers/rendering/renderer_rd/forward_clustered/render_forward_clustered.cpp @@ -589,11 +589,6 @@ void RenderForwardClustered::_setup_environment(const RenderDataRD *p_render_dat RendererStorageRD::store_soft_shadow_kernel(penumbra_shadow_kernel_get(), scene_state.ubo.penumbra_shadow_kernel); RendererStorageRD::store_soft_shadow_kernel(soft_shadow_kernel_get(), scene_state.ubo.soft_shadow_kernel); - scene_state.ubo.directional_penumbra_shadow_samples = directional_penumbra_shadow_samples_get(); - scene_state.ubo.directional_soft_shadow_samples = directional_soft_shadow_samples_get(); - scene_state.ubo.penumbra_shadow_samples = penumbra_shadow_samples_get(); - scene_state.ubo.soft_shadow_samples = soft_shadow_samples_get(); - Size2 screen_pixel_size = Vector2(1.0, 1.0) / Size2(p_screen_size); scene_state.ubo.screen_pixel_size[0] = screen_pixel_size.x; scene_state.ubo.screen_pixel_size[1] = screen_pixel_size.y; @@ -1942,13 +1937,67 @@ void RenderForwardClustered::_update_render_base_uniform_set() { { RD::Uniform u; u.binding = 3; + u.uniform_type = RD::UNIFORM_TYPE_SAMPLER; + RID sampler; + switch (decals_get_filter()) { + case RS::DECAL_FILTER_NEAREST: { + sampler = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_NEAREST, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED); + } break; + case RS::DECAL_FILTER_NEAREST_MIPMAPS: { + sampler = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_NEAREST_WITH_MIPMAPS, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED); + } break; + case RS::DECAL_FILTER_LINEAR: { + sampler = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED); + } break; + case RS::DECAL_FILTER_LINEAR_MIPMAPS: { + sampler = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR_WITH_MIPMAPS, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED); + } break; + case RS::DECAL_FILTER_LINEAR_MIPMAPS_ANISOTROPIC: { + sampler = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR_WITH_MIPMAPS_ANISOTROPIC, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED); + } break; + } + + u.ids.push_back(sampler); + uniforms.push_back(u); + } + + { + RD::Uniform u; + u.binding = 4; + u.uniform_type = RD::UNIFORM_TYPE_SAMPLER; + RID sampler; + switch (light_projectors_get_filter()) { + case RS::LIGHT_PROJECTOR_FILTER_NEAREST: { + sampler = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_NEAREST, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED); + } break; + case RS::LIGHT_PROJECTOR_FILTER_NEAREST_MIPMAPS: { + sampler = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_NEAREST_WITH_MIPMAPS, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED); + } break; + case RS::LIGHT_PROJECTOR_FILTER_LINEAR: { + sampler = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED); + } break; + case RS::LIGHT_PROJECTOR_FILTER_LINEAR_MIPMAPS: { + sampler = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR_WITH_MIPMAPS, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED); + } break; + case RS::LIGHT_PROJECTOR_FILTER_LINEAR_MIPMAPS_ANISOTROPIC: { + sampler = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR_WITH_MIPMAPS_ANISOTROPIC, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED); + } break; + } + + u.ids.push_back(sampler); + uniforms.push_back(u); + } + + { + RD::Uniform u; + u.binding = 5; u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER; u.ids.push_back(get_omni_light_buffer()); uniforms.push_back(u); } { RD::Uniform u; - u.binding = 4; + u.binding = 6; u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER; u.ids.push_back(get_spot_light_buffer()); uniforms.push_back(u); @@ -1956,35 +2005,35 @@ void RenderForwardClustered::_update_render_base_uniform_set() { { RD::Uniform u; - u.binding = 5; + u.binding = 7; u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER; u.ids.push_back(get_reflection_probe_buffer()); uniforms.push_back(u); } { RD::Uniform u; - u.binding = 6; + u.binding = 8; u.uniform_type = RD::UNIFORM_TYPE_UNIFORM_BUFFER; u.ids.push_back(get_directional_light_buffer()); uniforms.push_back(u); } { RD::Uniform u; - u.binding = 7; + u.binding = 9; u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER; u.ids.push_back(scene_state.lightmap_buffer); uniforms.push_back(u); } { RD::Uniform u; - u.binding = 8; + u.binding = 10; u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER; u.ids.push_back(scene_state.lightmap_capture_buffer); uniforms.push_back(u); } { RD::Uniform u; - u.binding = 9; + u.binding = 11; u.uniform_type = RD::UNIFORM_TYPE_TEXTURE; RID decal_atlas = storage->decal_atlas_get_texture(); u.ids.push_back(decal_atlas); @@ -1992,7 +2041,7 @@ void RenderForwardClustered::_update_render_base_uniform_set() { } { RD::Uniform u; - u.binding = 10; + u.binding = 12; u.uniform_type = RD::UNIFORM_TYPE_TEXTURE; RID decal_atlas = storage->decal_atlas_get_texture_srgb(); u.ids.push_back(decal_atlas); @@ -2000,7 +2049,7 @@ void RenderForwardClustered::_update_render_base_uniform_set() { } { RD::Uniform u; - u.binding = 11; + u.binding = 13; u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER; u.ids.push_back(get_decal_buffer()); uniforms.push_back(u); @@ -2009,7 +2058,7 @@ void RenderForwardClustered::_update_render_base_uniform_set() { { RD::Uniform u; u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER; - u.binding = 12; + u.binding = 14; u.ids.push_back(storage->global_variables_get_storage_buffer()); uniforms.push_back(u); } @@ -2017,7 +2066,7 @@ void RenderForwardClustered::_update_render_base_uniform_set() { { RD::Uniform u; u.uniform_type = RD::UNIFORM_TYPE_UNIFORM_BUFFER; - u.binding = 13; + u.binding = 15; u.ids.push_back(sdfgi_get_ubo()); uniforms.push_back(u); } @@ -2939,6 +2988,48 @@ void RenderForwardClustered::geometry_instance_set_softshadow_projector_pairing( _geometry_instance_mark_dirty(ginstance); } +void RenderForwardClustered::_update_shader_quality_settings() { + Vector<RD::PipelineSpecializationConstant> spec_constants; + + RD::PipelineSpecializationConstant sc; + sc.type = RD::PIPELINE_SPECIALIZATION_CONSTANT_TYPE_INT; + + sc.constant_id = SPEC_CONSTANT_SOFT_SHADOW_SAMPLES; + sc.int_value = soft_shadow_samples_get(); + + spec_constants.push_back(sc); + + sc.constant_id = SPEC_CONSTANT_PENUMBRA_SHADOW_SAMPLES; + sc.int_value = penumbra_shadow_samples_get(); + + spec_constants.push_back(sc); + + sc.constant_id = SPEC_CONSTANT_DIRECTIONAL_SOFT_SHADOW_SAMPLES; + sc.int_value = directional_soft_shadow_samples_get(); + + spec_constants.push_back(sc); + + sc.constant_id = SPEC_CONSTANT_DIRECTIONAL_PENUMBRA_SHADOW_SAMPLES; + sc.int_value = directional_penumbra_shadow_samples_get(); + + spec_constants.push_back(sc); + + sc.type = RD::PIPELINE_SPECIALIZATION_CONSTANT_TYPE_BOOL; + sc.constant_id = SPEC_CONSTANT_DECAL_FILTER; + sc.bool_value = decals_get_filter() == RS::DECAL_FILTER_NEAREST_MIPMAPS || decals_get_filter() == RS::DECAL_FILTER_LINEAR_MIPMAPS || decals_get_filter() == RS::DECAL_FILTER_LINEAR_MIPMAPS_ANISOTROPIC; + + spec_constants.push_back(sc); + + sc.constant_id = SPEC_CONSTANT_PROJECTOR_FILTER; + sc.bool_value = light_projectors_get_filter() == RS::LIGHT_PROJECTOR_FILTER_NEAREST_MIPMAPS || light_projectors_get_filter() == RS::LIGHT_PROJECTOR_FILTER_LINEAR_MIPMAPS || light_projectors_get_filter() == RS::LIGHT_PROJECTOR_FILTER_LINEAR_MIPMAPS_ANISOTROPIC; + + spec_constants.push_back(sc); + + scene_shader.set_default_specialization_constants(spec_constants); + + _base_uniforms_changed(); //also need this +} + RenderForwardClustered::RenderForwardClustered(RendererStorageRD *p_storage) : RendererSceneRenderRD(p_storage) { singleton = this; @@ -2976,6 +3067,8 @@ RenderForwardClustered::RenderForwardClustered(RendererStorageRD *p_storage) : } render_list_thread_threshold = GLOBAL_GET("rendering/limits/forward_renderer/threaded_render_minimum_instances"); + + _update_shader_quality_settings(); } RenderForwardClustered::~RenderForwardClustered() { diff --git a/servers/rendering/renderer_rd/forward_clustered/render_forward_clustered.h b/servers/rendering/renderer_rd/forward_clustered/render_forward_clustered.h index b70cefd980..6682c5e9b0 100644 --- a/servers/rendering/renderer_rd/forward_clustered/render_forward_clustered.h +++ b/servers/rendering/renderer_rd/forward_clustered/render_forward_clustered.h @@ -51,6 +51,15 @@ class RenderForwardClustered : public RendererSceneRenderRD { }; enum { + SPEC_CONSTANT_SOFT_SHADOW_SAMPLES = 6, + SPEC_CONSTANT_PENUMBRA_SHADOW_SAMPLES = 7, + SPEC_CONSTANT_DIRECTIONAL_SOFT_SHADOW_SAMPLES = 8, + SPEC_CONSTANT_DIRECTIONAL_PENUMBRA_SHADOW_SAMPLES = 9, + SPEC_CONSTANT_DECAL_FILTER = 10, + SPEC_CONSTANT_PROJECTOR_FILTER = 11, + }; + + enum { SDFGI_MAX_CASCADES = 8, MAX_VOXEL_GI_INSTANCESS = 8, MAX_LIGHTMAPS = 8, @@ -222,11 +231,6 @@ class RenderForwardClustered : public RendererSceneRenderRD { float penumbra_shadow_kernel[128]; float soft_shadow_kernel[128]; - uint32_t directional_penumbra_shadow_samples; - uint32_t directional_soft_shadow_samples; - uint32_t penumbra_shadow_samples; - uint32_t soft_shadow_samples; - float ambient_light_color_energy[4]; float ambient_color_sky_mix; @@ -573,6 +577,8 @@ class RenderForwardClustered : public RendererSceneRenderRD { RenderList render_list[RENDER_LIST_MAX]; + virtual void _update_shader_quality_settings() override; + protected: virtual void _render_scene(RenderDataRD *p_render_data, const Color &p_default_bg_color) override; diff --git a/servers/rendering/renderer_rd/forward_clustered/scene_shader_forward_clustered.cpp b/servers/rendering/renderer_rd/forward_clustered/scene_shader_forward_clustered.cpp index 706a75e641..333e87bdbd 100644 --- a/servers/rendering/renderer_rd/forward_clustered/scene_shader_forward_clustered.cpp +++ b/servers/rendering/renderer_rd/forward_clustered/scene_shader_forward_clustered.cpp @@ -324,7 +324,7 @@ void SceneShaderForwardClustered::ShaderData::set_code(const String &p_code) { } RID shader_variant = shader_singleton->shader.version_get_shader(version, k); - pipelines[i][j][k].setup(shader_variant, primitive_rd, raster_state, multisample_state, depth_stencil, blend_state, 0); + pipelines[i][j][k].setup(shader_variant, primitive_rd, raster_state, multisample_state, depth_stencil, blend_state, 0, singleton->default_specialization_constants); } } } @@ -408,7 +408,8 @@ RS::ShaderNativeSourceCode SceneShaderForwardClustered::ShaderData::get_native_s return shader_singleton->shader.version_get_native_source_code(version); } -SceneShaderForwardClustered::ShaderData::ShaderData() { +SceneShaderForwardClustered::ShaderData::ShaderData() : + shader_list_element(this) { valid = false; uses_screen_texture = false; } @@ -424,6 +425,7 @@ SceneShaderForwardClustered::ShaderData::~ShaderData() { RendererStorageRD::ShaderData *SceneShaderForwardClustered::_create_shader_func() { ShaderData *shader_data = memnew(ShaderData); + singleton->shader_list.add(&shader_data->shader_list_element); return shader_data; } @@ -681,7 +683,19 @@ void SceneShaderForwardClustered::init(RendererStorageRD *p_storage, const Strin //default material and shader default_shader = storage->shader_allocate(); storage->shader_initialize(default_shader); - storage->shader_set_code(default_shader, "shader_type spatial; void vertex() { ROUGHNESS = 0.8; } void fragment() { ALBEDO=vec3(0.6); ROUGHNESS=0.8; METALLIC=0.2; } \n"); + storage->shader_set_code(default_shader, R"( +shader_type spatial; + +void vertex() { + ROUGHNESS = 0.8; +} + +void fragment() { + ALBEDO = vec3(0.6); + ROUGHNESS = 0.8; + METALLIC = 0.2; +} +)"); default_material = storage->material_allocate(); storage->material_initialize(default_material); storage->material_set_shader(default_material, default_shader); @@ -698,7 +712,16 @@ void SceneShaderForwardClustered::init(RendererStorageRD *p_storage, const Strin overdraw_material_shader = storage->shader_allocate(); storage->shader_initialize(overdraw_material_shader); // Use relatively low opacity so that more "layers" of overlapping objects can be distinguished. - storage->shader_set_code(overdraw_material_shader, "shader_type spatial;\nrender_mode blend_add,unshaded;\n void fragment() { ALBEDO=vec3(0.4,0.8,0.8); ALPHA=0.1; }"); + storage->shader_set_code(overdraw_material_shader, R"( +shader_type spatial; + +render_mode blend_add, unshaded; + +void fragment() { + ALBEDO = vec3(0.4, 0.8, 0.8); + ALPHA = 0.1; +} +)"); overdraw_material = storage->material_allocate(); storage->material_initialize(overdraw_material); storage->material_set_shader(overdraw_material, overdraw_material_shader); @@ -728,3 +751,16 @@ void SceneShaderForwardClustered::init(RendererStorageRD *p_storage, const Strin shadow_sampler = RD::get_singleton()->sampler_create(sampler); } } + +void SceneShaderForwardClustered::set_default_specialization_constants(const Vector<RD::PipelineSpecializationConstant> &p_constants) { + default_specialization_constants = p_constants; + for (SelfList<ShaderData> *E = shader_list.first(); E; E = E->next()) { + for (int i = 0; i < ShaderData::CULL_VARIANT_MAX; i++) { + for (int j = 0; j < RS::PRIMITIVE_MAX; j++) { + for (int k = 0; k < SHADER_VERSION_MAX; k++) { + E->self()->pipelines[i][j][k].update_specialization_constants(default_specialization_constants); + } + } + } + } +} diff --git a/servers/rendering/renderer_rd/forward_clustered/scene_shader_forward_clustered.h b/servers/rendering/renderer_rd/forward_clustered/scene_shader_forward_clustered.h index 8dfd18cca5..8d75f30a20 100644 --- a/servers/rendering/renderer_rd/forward_clustered/scene_shader_forward_clustered.h +++ b/servers/rendering/renderer_rd/forward_clustered/scene_shader_forward_clustered.h @@ -160,10 +160,13 @@ public: virtual Variant get_default_parameter(const StringName &p_parameter) const; virtual RS::ShaderNativeSourceCode get_native_source_code() const; + SelfList<ShaderData> shader_list_element; ShaderData(); virtual ~ShaderData(); }; + SelfList<ShaderData>::List shader_list; + RendererStorageRD::ShaderData *_create_shader_func(); static RendererStorageRD::ShaderData *_create_shader_funcs() { return static_cast<SceneShaderForwardClustered *>(singleton)->_create_shader_func(); @@ -209,10 +212,12 @@ public: RID overdraw_material_uniform_set; ShaderData *overdraw_material_shader_ptr = nullptr; + Vector<RD::PipelineSpecializationConstant> default_specialization_constants; SceneShaderForwardClustered(); ~SceneShaderForwardClustered(); void init(RendererStorageRD *p_storage, const String p_defines); + void set_default_specialization_constants(const Vector<RD::PipelineSpecializationConstant> &p_constants); }; } // namespace RendererSceneRenderImplementation diff --git a/servers/rendering/renderer_rd/forward_mobile/render_forward_mobile.cpp b/servers/rendering/renderer_rd/forward_mobile/render_forward_mobile.cpp index 4985fd1687..5f6d9465c7 100644 --- a/servers/rendering/renderer_rd/forward_mobile/render_forward_mobile.cpp +++ b/servers/rendering/renderer_rd/forward_mobile/render_forward_mobile.cpp @@ -96,10 +96,6 @@ void RenderForwardMobile::RenderBufferDataForwardMobile::configure(RID p_color_b RD::DataFormat color_format = RenderForwardMobile::singleton->_render_buffers_get_color_format(); if (p_msaa == RS::VIEWPORT_MSAA_DISABLED) { - if (color_format == RD::DATA_FORMAT_A2B10G10R10_UNORM_PACK32) { - // @TODO add a second color buffer for alpha as this format is RGB only - } - Vector<RID> fb; fb.push_back(p_color_buffer); fb.push_back(depth); @@ -164,16 +160,13 @@ bool RenderForwardMobile::free(RID p_rid) { /* Render functions */ RD::DataFormat RenderForwardMobile::_render_buffers_get_color_format() { - // Using 32bit buffers enables AFBC on mobile devices which should have a definate performance improvement (MALI G710 and newer support this on 64bit RTs) - // NO ALPHA and unsigned float. - // @TODO No alpha is an issue, recommendation here is to add a second RT for alpha + // Using 32bit buffers enables AFBC on mobile devices which should have a definite performance improvement (MALI G710 and newer support this on 64bit RTs) return RD::DATA_FORMAT_A2B10G10R10_UNORM_PACK32; } bool RenderForwardMobile::_render_buffers_can_be_storage() { - // Using 32bit buffers enables AFBC on mobile devices which should have a definate performance improvement (MALI G710 and newer support this on 64bit RTs) - // NO ALPHA and unsigned float. - // @TODO No alpha is an issue, recommendation here is to add a second RT for alpha + // Using 32bit buffers enables AFBC on mobile devices which should have a definite performance improvement (MALI G710 and newer support this on 64bit RTs) + // Doesn't support storage return false; } @@ -899,13 +892,67 @@ void RenderForwardMobile::_update_render_base_uniform_set() { { RD::Uniform u; u.binding = 3; + u.uniform_type = RD::UNIFORM_TYPE_SAMPLER; + RID sampler; + switch (decals_get_filter()) { + case RS::DECAL_FILTER_NEAREST: { + sampler = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_NEAREST, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED); + } break; + case RS::DECAL_FILTER_NEAREST_MIPMAPS: { + sampler = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_NEAREST_WITH_MIPMAPS, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED); + } break; + case RS::DECAL_FILTER_LINEAR: { + sampler = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED); + } break; + case RS::DECAL_FILTER_LINEAR_MIPMAPS: { + sampler = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR_WITH_MIPMAPS, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED); + } break; + case RS::DECAL_FILTER_LINEAR_MIPMAPS_ANISOTROPIC: { + sampler = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR_WITH_MIPMAPS_ANISOTROPIC, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED); + } break; + } + + u.ids.push_back(sampler); + uniforms.push_back(u); + } + + { + RD::Uniform u; + u.binding = 4; + u.uniform_type = RD::UNIFORM_TYPE_SAMPLER; + RID sampler; + switch (light_projectors_get_filter()) { + case RS::LIGHT_PROJECTOR_FILTER_NEAREST: { + sampler = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_NEAREST, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED); + } break; + case RS::LIGHT_PROJECTOR_FILTER_NEAREST_MIPMAPS: { + sampler = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_NEAREST_WITH_MIPMAPS, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED); + } break; + case RS::LIGHT_PROJECTOR_FILTER_LINEAR: { + sampler = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED); + } break; + case RS::LIGHT_PROJECTOR_FILTER_LINEAR_MIPMAPS: { + sampler = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR_WITH_MIPMAPS, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED); + } break; + case RS::LIGHT_PROJECTOR_FILTER_LINEAR_MIPMAPS_ANISOTROPIC: { + sampler = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR_WITH_MIPMAPS_ANISOTROPIC, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED); + } break; + } + + u.ids.push_back(sampler); + uniforms.push_back(u); + } + + { + RD::Uniform u; + u.binding = 5; u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER; u.ids.push_back(get_omni_light_buffer()); uniforms.push_back(u); } { RD::Uniform u; - u.binding = 4; + u.binding = 6; u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER; u.ids.push_back(get_spot_light_buffer()); uniforms.push_back(u); @@ -913,35 +960,35 @@ void RenderForwardMobile::_update_render_base_uniform_set() { { RD::Uniform u; - u.binding = 5; + u.binding = 7; u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER; u.ids.push_back(get_reflection_probe_buffer()); uniforms.push_back(u); } { RD::Uniform u; - u.binding = 6; + u.binding = 8; u.uniform_type = RD::UNIFORM_TYPE_UNIFORM_BUFFER; u.ids.push_back(get_directional_light_buffer()); uniforms.push_back(u); } { RD::Uniform u; - u.binding = 7; + u.binding = 9; u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER; u.ids.push_back(scene_state.lightmap_buffer); uniforms.push_back(u); } { RD::Uniform u; - u.binding = 8; + u.binding = 10; u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER; u.ids.push_back(scene_state.lightmap_capture_buffer); uniforms.push_back(u); } { RD::Uniform u; - u.binding = 9; + u.binding = 11; u.uniform_type = RD::UNIFORM_TYPE_TEXTURE; RID decal_atlas = storage->decal_atlas_get_texture(); u.ids.push_back(decal_atlas); @@ -949,7 +996,7 @@ void RenderForwardMobile::_update_render_base_uniform_set() { } { RD::Uniform u; - u.binding = 10; + u.binding = 12; u.uniform_type = RD::UNIFORM_TYPE_TEXTURE; RID decal_atlas = storage->decal_atlas_get_texture_srgb(); u.ids.push_back(decal_atlas); @@ -957,7 +1004,7 @@ void RenderForwardMobile::_update_render_base_uniform_set() { } { RD::Uniform u; - u.binding = 11; + u.binding = 13; u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER; u.ids.push_back(get_decal_buffer()); uniforms.push_back(u); @@ -966,7 +1013,7 @@ void RenderForwardMobile::_update_render_base_uniform_set() { { RD::Uniform u; u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER; - u.binding = 12; + u.binding = 14; u.ids.push_back(storage->global_variables_get_storage_buffer()); uniforms.push_back(u); } @@ -1203,11 +1250,6 @@ void RenderForwardMobile::_setup_environment(const RenderDataRD *p_render_data, RendererStorageRD::store_soft_shadow_kernel(penumbra_shadow_kernel_get(), scene_state.ubo.penumbra_shadow_kernel); RendererStorageRD::store_soft_shadow_kernel(soft_shadow_kernel_get(), scene_state.ubo.soft_shadow_kernel); - scene_state.ubo.directional_penumbra_shadow_samples = directional_penumbra_shadow_samples_get(); - scene_state.ubo.directional_soft_shadow_samples = directional_soft_shadow_samples_get(); - scene_state.ubo.penumbra_shadow_samples = penumbra_shadow_samples_get(); - scene_state.ubo.soft_shadow_samples = soft_shadow_samples_get(); - Size2 screen_pixel_size = Vector2(1.0, 1.0) / Size2(p_screen_size); scene_state.ubo.screen_pixel_size[0] = screen_pixel_size.x; scene_state.ubo.screen_pixel_size[1] = screen_pixel_size.y; @@ -2237,6 +2279,48 @@ uint32_t RenderForwardMobile::get_max_elements() const { RenderForwardMobile *RenderForwardMobile::singleton = nullptr; +void RenderForwardMobile::_update_shader_quality_settings() { + Vector<RD::PipelineSpecializationConstant> spec_constants; + + RD::PipelineSpecializationConstant sc; + sc.type = RD::PIPELINE_SPECIALIZATION_CONSTANT_TYPE_INT; + + sc.constant_id = SPEC_CONSTANT_SOFT_SHADOW_SAMPLES; + sc.int_value = soft_shadow_samples_get(); + + spec_constants.push_back(sc); + + sc.constant_id = SPEC_CONSTANT_PENUMBRA_SHADOW_SAMPLES; + sc.int_value = penumbra_shadow_samples_get(); + + spec_constants.push_back(sc); + + sc.constant_id = SPEC_CONSTANT_DIRECTIONAL_SOFT_SHADOW_SAMPLES; + sc.int_value = directional_soft_shadow_samples_get(); + + spec_constants.push_back(sc); + + sc.constant_id = SPEC_CONSTANT_DIRECTIONAL_PENUMBRA_SHADOW_SAMPLES; + sc.int_value = directional_penumbra_shadow_samples_get(); + + spec_constants.push_back(sc); + + sc.type = RD::PIPELINE_SPECIALIZATION_CONSTANT_TYPE_BOOL; + sc.constant_id = SPEC_CONSTANT_DECAL_FILTER; + sc.bool_value = decals_get_filter() == RS::DECAL_FILTER_NEAREST_MIPMAPS || decals_get_filter() == RS::DECAL_FILTER_LINEAR_MIPMAPS || decals_get_filter() == RS::DECAL_FILTER_LINEAR_MIPMAPS_ANISOTROPIC; + + spec_constants.push_back(sc); + + sc.constant_id = SPEC_CONSTANT_PROJECTOR_FILTER; + sc.bool_value = light_projectors_get_filter() == RS::LIGHT_PROJECTOR_FILTER_NEAREST_MIPMAPS || light_projectors_get_filter() == RS::LIGHT_PROJECTOR_FILTER_LINEAR_MIPMAPS || light_projectors_get_filter() == RS::LIGHT_PROJECTOR_FILTER_LINEAR_MIPMAPS_ANISOTROPIC; + + spec_constants.push_back(sc); + + scene_shader.set_default_specialization_constants(spec_constants); + + _base_uniforms_changed(); //also need this +} + RenderForwardMobile::RenderForwardMobile(RendererStorageRD *p_storage) : RendererSceneRenderRD(p_storage) { singleton = this; @@ -2272,6 +2356,8 @@ RenderForwardMobile::RenderForwardMobile(RendererStorageRD *p_storage) : // !BAS! maybe we need a mobile version of this setting? render_list_thread_threshold = GLOBAL_GET("rendering/limits/forward_renderer/threaded_render_minimum_instances"); + + _update_shader_quality_settings(); } RenderForwardMobile::~RenderForwardMobile() { diff --git a/servers/rendering/renderer_rd/forward_mobile/render_forward_mobile.h b/servers/rendering/renderer_rd/forward_mobile/render_forward_mobile.h index 5d28cdb5d3..973925d562 100644 --- a/servers/rendering/renderer_rd/forward_mobile/render_forward_mobile.h +++ b/servers/rendering/renderer_rd/forward_mobile/render_forward_mobile.h @@ -65,6 +65,15 @@ protected: }; enum { + SPEC_CONSTANT_SOFT_SHADOW_SAMPLES = 6, + SPEC_CONSTANT_PENUMBRA_SHADOW_SAMPLES = 7, + SPEC_CONSTANT_DIRECTIONAL_SOFT_SHADOW_SAMPLES = 8, + SPEC_CONSTANT_DIRECTIONAL_PENUMBRA_SHADOW_SAMPLES = 9, + SPEC_CONSTANT_DECAL_FILTER = 10, + SPEC_CONSTANT_PROJECTOR_FILTER = 11, + }; + + enum { MAX_LIGHTMAPS = 8, MAX_RDL_CULL = 8, // maximum number of reflection probes, decals or lights we can cull per geometry instance INSTANCE_DATA_BUFFER_MIN_SIZE = 4096 @@ -228,11 +237,6 @@ protected: float penumbra_shadow_kernel[128]; float soft_shadow_kernel[128]; - uint32_t directional_penumbra_shadow_samples; - uint32_t directional_soft_shadow_samples; - uint32_t penumbra_shadow_samples; - uint32_t soft_shadow_samples; - float ambient_light_color_energy[4]; float ambient_color_sky_mix; @@ -569,6 +573,8 @@ protected: _FORCE_INLINE_ void _fill_push_constant_instance_indices(GeometryInstanceForwardMobile::PushConstant *p_push_constant, const GeometryInstanceForwardMobile *p_instance); + void _update_shader_quality_settings() override; + public: static void _geometry_instance_dependency_changed(RendererStorage::DependencyChangedNotification p_notification, RendererStorage::DependencyTracker *p_tracker); static void _geometry_instance_dependency_deleted(const RID &p_dependency, RendererStorage::DependencyTracker *p_tracker); diff --git a/servers/rendering/renderer_rd/forward_mobile/scene_shader_forward_mobile.cpp b/servers/rendering/renderer_rd/forward_mobile/scene_shader_forward_mobile.cpp index 7709c8aadc..bcdcb05653 100644 --- a/servers/rendering/renderer_rd/forward_mobile/scene_shader_forward_mobile.cpp +++ b/servers/rendering/renderer_rd/forward_mobile/scene_shader_forward_mobile.cpp @@ -318,7 +318,7 @@ void SceneShaderForwardMobile::ShaderData::set_code(const String &p_code) { } RID shader_variant = shader_singleton->shader.version_get_shader(version, k); - pipelines[i][j][k].setup(shader_variant, primitive_rd, raster_state, multisample_state, depth_stencil, blend_state, 0); + pipelines[i][j][k].setup(shader_variant, primitive_rd, raster_state, multisample_state, depth_stencil, blend_state, 0, singleton->default_specialization_constants); } } } @@ -402,7 +402,8 @@ RS::ShaderNativeSourceCode SceneShaderForwardMobile::ShaderData::get_native_sour return shader_singleton->shader.version_get_native_source_code(version); } -SceneShaderForwardMobile::ShaderData::ShaderData() { +SceneShaderForwardMobile::ShaderData::ShaderData() : + shader_list_element(this) { valid = false; uses_screen_texture = false; } @@ -418,6 +419,7 @@ SceneShaderForwardMobile::ShaderData::~ShaderData() { RendererStorageRD::ShaderData *SceneShaderForwardMobile::_create_shader_func() { ShaderData *shader_data = memnew(ShaderData); + singleton->shader_list.add(&shader_data->shader_list_element); return shader_data; } @@ -671,7 +673,19 @@ void SceneShaderForwardMobile::init(RendererStorageRD *p_storage, const String p //default material and shader default_shader = storage->shader_allocate(); storage->shader_initialize(default_shader); - storage->shader_set_code(default_shader, "shader_type spatial; void vertex() { ROUGHNESS = 0.8; } void fragment() { ALBEDO=vec3(0.6); ROUGHNESS=0.8; METALLIC=0.2; } \n"); + storage->shader_set_code(default_shader, R"( +shader_type spatial; + +void vertex() { + ROUGHNESS = 0.8; +} + +void fragment() { + ALBEDO = vec3(0.6); + ROUGHNESS = 0.8; + METALLIC = 0.2; +} +)"); default_material = storage->material_allocate(); storage->material_initialize(default_material); storage->material_set_shader(default_material, default_shader); @@ -687,7 +701,16 @@ void SceneShaderForwardMobile::init(RendererStorageRD *p_storage, const String p overdraw_material_shader = storage->shader_allocate(); storage->shader_initialize(overdraw_material_shader); // Use relatively low opacity so that more "layers" of overlapping objects can be distinguished. - storage->shader_set_code(overdraw_material_shader, "shader_type spatial;\nrender_mode blend_add,unshaded;\n void fragment() { ALBEDO=vec3(0.4,0.8,0.8); ALPHA=0.1; }"); + storage->shader_set_code(overdraw_material_shader, R"( +shader_type spatial; + +render_mode blend_add, unshaded; + +void fragment() { + ALBEDO = vec3(0.4, 0.8, 0.8); + ALPHA = 0.1; +} +)"); overdraw_material = storage->material_allocate(); storage->material_initialize(overdraw_material); storage->material_set_shader(overdraw_material, overdraw_material_shader); @@ -718,6 +741,19 @@ void SceneShaderForwardMobile::init(RendererStorageRD *p_storage, const String p } } +void SceneShaderForwardMobile::set_default_specialization_constants(const Vector<RD::PipelineSpecializationConstant> &p_constants) { + default_specialization_constants = p_constants; + for (SelfList<ShaderData> *E = shader_list.first(); E; E = E->next()) { + for (int i = 0; i < ShaderData::CULL_VARIANT_MAX; i++) { + for (int j = 0; j < RS::PRIMITIVE_MAX; j++) { + for (int k = 0; k < SHADER_VERSION_MAX; k++) { + E->self()->pipelines[i][j][k].update_specialization_constants(default_specialization_constants); + } + } + } + } +} + SceneShaderForwardMobile::~SceneShaderForwardMobile() { RD::get_singleton()->free(default_vec4_xform_buffer); RD::get_singleton()->free(shadow_sampler); diff --git a/servers/rendering/renderer_rd/forward_mobile/scene_shader_forward_mobile.h b/servers/rendering/renderer_rd/forward_mobile/scene_shader_forward_mobile.h index 5c9e35fd0d..e1c10f0206 100644 --- a/servers/rendering/renderer_rd/forward_mobile/scene_shader_forward_mobile.h +++ b/servers/rendering/renderer_rd/forward_mobile/scene_shader_forward_mobile.h @@ -151,6 +151,8 @@ public: virtual Variant get_default_parameter(const StringName &p_parameter) const; virtual RS::ShaderNativeSourceCode get_native_source_code() const; + SelfList<ShaderData> shader_list_element; + ShaderData(); virtual ~ShaderData(); }; @@ -174,6 +176,8 @@ public: virtual ~MaterialData(); }; + SelfList<ShaderData>::List shader_list; + RendererStorageRD::MaterialData *_create_material_func(ShaderData *p_shader); static RendererStorageRD::MaterialData *_create_material_funcs(RendererStorageRD::ShaderData *p_shader) { return static_cast<SceneShaderForwardMobile *>(singleton)->_create_material_func(static_cast<ShaderData *>(p_shader)); @@ -202,7 +206,10 @@ public: SceneShaderForwardMobile(); ~SceneShaderForwardMobile(); + Vector<RD::PipelineSpecializationConstant> default_specialization_constants; + void init(RendererStorageRD *p_storage, const String p_defines); + void set_default_specialization_constants(const Vector<RD::PipelineSpecializationConstant> &p_constants); }; } // namespace RendererSceneRenderImplementation diff --git a/servers/rendering/renderer_rd/pipeline_cache_rd.cpp b/servers/rendering/renderer_rd/pipeline_cache_rd.cpp index 2bdd523920..aefe926cb0 100644 --- a/servers/rendering/renderer_rd/pipeline_cache_rd.cpp +++ b/servers/rendering/renderer_rd/pipeline_cache_rd.cpp @@ -68,6 +68,9 @@ RID PipelineCacheRD::_generate_version(RD::VertexFormatID p_vertex_format_id, RD } void PipelineCacheRD::_clear() { +#ifndef _MSC_VER +#warning Clear should probably recompile all the variants already compiled instead to avoid stalls? needs discussion +#endif if (versions) { for (uint32_t i = 0; i < version_count; i++) { //shader may be gone, so this may not be valid @@ -94,6 +97,10 @@ void PipelineCacheRD::setup(RID p_shader, RD::RenderPrimitive p_primitive, const dynamic_state_flags = p_dynamic_state_flags; base_specialization_constants = p_base_specialization_constants; } +void PipelineCacheRD::update_specialization_constants(const Vector<RD::PipelineSpecializationConstant> &p_base_specialization_constants) { + base_specialization_constants = p_base_specialization_constants; + _clear(); +} void PipelineCacheRD::update_shader(RID p_shader) { ERR_FAIL_COND(p_shader.is_null()); diff --git a/servers/rendering/renderer_rd/pipeline_cache_rd.h b/servers/rendering/renderer_rd/pipeline_cache_rd.h index 71e26283e1..e52f47fa47 100644 --- a/servers/rendering/renderer_rd/pipeline_cache_rd.h +++ b/servers/rendering/renderer_rd/pipeline_cache_rd.h @@ -66,6 +66,7 @@ class PipelineCacheRD { public: void setup(RID p_shader, RD::RenderPrimitive p_primitive, const RD::PipelineRasterizationState &p_rasterization_state, RD::PipelineMultisampleState p_multisample, const RD::PipelineDepthStencilState &p_depth_stencil_state, const RD::PipelineColorBlendState &p_blend_state, int p_dynamic_state_flags = 0, const Vector<RD::PipelineSpecializationConstant> &p_base_specialization_constants = Vector<RD::PipelineSpecializationConstant>()); + void update_specialization_constants(const Vector<RD::PipelineSpecializationConstant> &p_base_specialization_constants); void update_shader(RID p_shader); _FORCE_INLINE_ RID get_render_pipeline(RD::VertexFormatID p_vertex_format_id, RD::FramebufferFormatID p_framebuffer_format_id, bool p_wireframe = false, uint32_t p_render_pass = 0, uint32_t p_bool_specializations = 0) { diff --git a/servers/rendering/renderer_rd/renderer_canvas_render_rd.cpp b/servers/rendering/renderer_rd/renderer_canvas_render_rd.cpp index 1e3dbe69a3..18c1fe02a0 100644 --- a/servers/rendering/renderer_rd/renderer_canvas_render_rd.cpp +++ b/servers/rendering/renderer_rd/renderer_canvas_render_rd.cpp @@ -620,7 +620,7 @@ void RendererCanvasRenderRD::_render_item(RD::DrawListID p_draw_list, RID p_rend RD::get_singleton()->draw_list_bind_index_array(p_draw_list, shader.quad_index_array); RD::get_singleton()->draw_list_draw(p_draw_list, true); - //restore if overrided + // Restore if overridden. push_constant.color_texture_pixel_size[0] = texpixel_size.x; push_constant.color_texture_pixel_size[1] = texpixel_size.y; @@ -2570,8 +2570,19 @@ RendererCanvasRenderRD::RendererCanvasRenderRD(RendererStorageRD *p_storage) { default_canvas_group_shader = storage->shader_allocate(); storage->shader_initialize(default_canvas_group_shader); - storage->shader_set_code(default_canvas_group_shader, "shader_type canvas_item; \nvoid fragment() {\n\tvec4 c = textureLod(SCREEN_TEXTURE,SCREEN_UV,0.0); if (c.a > 0.0001) c.rgb/=c.a; COLOR *= c; \n}\n"); + storage->shader_set_code(default_canvas_group_shader, R"( +shader_type canvas_item; +void fragment() { + vec4 c = textureLod(SCREEN_TEXTURE, SCREEN_UV, 0.0); + + if (c.a > 0.0001) { + c.rgb /= c.a; + } + + COLOR *= c; +} +)"); default_canvas_group_material = storage->material_allocate(); storage->material_initialize(default_canvas_group_material); diff --git a/servers/rendering/renderer_rd/renderer_compositor_rd.cpp b/servers/rendering/renderer_rd/renderer_compositor_rd.cpp index e6ae66d56f..02d548bf13 100644 --- a/servers/rendering/renderer_rd/renderer_compositor_rd.cpp +++ b/servers/rendering/renderer_rd/renderer_compositor_rd.cpp @@ -222,7 +222,7 @@ void RendererCompositorRD::set_boot_image(const Ref<Image> &p_image, const Color RD::get_singleton()->swap_buffers(); - RD::get_singleton()->free(texture); + storage->free(texture); } RendererCompositorRD *RendererCompositorRD::singleton = nullptr; @@ -280,6 +280,9 @@ RendererCompositorRD::RendererCompositorRD() { // default to our high end renderer scene = memnew(RendererSceneRenderImplementation::RenderForwardClustered(storage)); } + + // now we're ready to create our effects, + storage->init_effects(!scene->_render_buffers_can_be_storage()); } RendererCompositorRD::~RendererCompositorRD() { diff --git a/servers/rendering/renderer_rd/renderer_scene_render_rd.cpp b/servers/rendering/renderer_rd/renderer_scene_render_rd.cpp index 7b5f448c18..2e0e7c3c43 100644 --- a/servers/rendering/renderer_rd/renderer_scene_render_rd.cpp +++ b/servers/rendering/renderer_rd/renderer_scene_render_rd.cpp @@ -1383,12 +1383,20 @@ void RendererSceneRenderRD::_allocate_blur_textures(RenderBuffers *rb) { uint32_t mipmaps_required = Image::get_image_required_mipmaps(rb->width, rb->height, Image::FORMAT_RGBAH); + // TODO make sure texture_create_shared_from_slice works for multiview + RD::TextureFormat tf; - tf.format = RD::DATA_FORMAT_R16G16B16A16_SFLOAT; + tf.format = _render_buffers_get_color_format(); // RD::DATA_FORMAT_R16G16B16A16_SFLOAT; tf.width = rb->width; tf.height = rb->height; - tf.texture_type = RD::TEXTURE_TYPE_2D; - tf.usage_bits = RD::TEXTURE_USAGE_STORAGE_BIT | RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_CAN_COPY_TO_BIT; + tf.texture_type = rb->view_count > 1 ? RD::TEXTURE_TYPE_2D_ARRAY : RD::TEXTURE_TYPE_2D; + tf.array_layers = rb->view_count; + tf.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_CAN_COPY_TO_BIT; + if (_render_buffers_can_be_storage()) { + tf.usage_bits += RD::TEXTURE_USAGE_STORAGE_BIT; + } else { + tf.usage_bits += RD::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT; + } tf.mipmaps = mipmaps_required; rb->blur[0].texture = RD::get_singleton()->texture_create(tf, RD::TextureView()); @@ -1408,11 +1416,40 @@ void RendererSceneRenderRD::_allocate_blur_textures(RenderBuffers *rb) { mm.width = base_width; mm.height = base_height; + if (!_render_buffers_can_be_storage()) { + Vector<RID> fb; + fb.push_back(mm.texture); + + mm.fb = RD::get_singleton()->framebuffer_create(fb); + } + + if (!_render_buffers_can_be_storage()) { + // and half texture, this is an intermediate result so just allocate a texture, is this good enough? + tf.width = MAX(1, base_width >> 1); + tf.height = base_height; + tf.mipmaps = 1; // 1 or 0? + + mm.half_texture = RD::get_singleton()->texture_create(tf, RD::TextureView()); + + Vector<RID> half_fb; + half_fb.push_back(mm.half_texture); + mm.half_fb = RD::get_singleton()->framebuffer_create(half_fb); + } + rb->blur[0].mipmaps.push_back(mm); if (i > 0) { mm.texture = RD::get_singleton()->texture_create_shared_from_slice(RD::TextureView(), rb->blur[1].texture, 0, i - 1); + if (!_render_buffers_can_be_storage()) { + Vector<RID> fb; + fb.push_back(mm.texture); + + mm.fb = RD::get_singleton()->framebuffer_create(fb); + + // We can re-use the half texture here as it is an intermediate result + } + rb->blur[1].mipmaps.push_back(mm); } @@ -1435,26 +1472,48 @@ void RendererSceneRenderRD::_allocate_luminance_textures(RenderBuffers *rb) { tf.format = RD::DATA_FORMAT_R32_SFLOAT; tf.width = w; tf.height = h; - tf.usage_bits = RD::TEXTURE_USAGE_STORAGE_BIT; bool final = w == 1 && h == 1; - if (final) { - tf.usage_bits |= RD::TEXTURE_USAGE_SAMPLING_BIT; + if (_render_buffers_can_be_storage()) { + tf.usage_bits = RD::TEXTURE_USAGE_STORAGE_BIT; + if (final) { + tf.usage_bits |= RD::TEXTURE_USAGE_SAMPLING_BIT; + } + } else { + tf.usage_bits = RD::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | RD::TEXTURE_USAGE_SAMPLING_BIT; } RID texture = RD::get_singleton()->texture_create(tf, RD::TextureView()); rb->luminance.reduce.push_back(texture); + if (!_render_buffers_can_be_storage()) { + Vector<RID> fb; + fb.push_back(texture); + + rb->luminance.fb.push_back(RD::get_singleton()->framebuffer_create(fb)); + } if (final) { rb->luminance.current = RD::get_singleton()->texture_create(tf, RD::TextureView()); + + if (!_render_buffers_can_be_storage()) { + Vector<RID> fb; + fb.push_back(rb->luminance.current); + + rb->luminance.current_fb = RD::get_singleton()->framebuffer_create(fb); + } break; } } } void RendererSceneRenderRD::_free_render_buffer_data(RenderBuffers *rb) { + if (rb->texture_fb.is_valid()) { + RD::get_singleton()->free(rb->texture_fb); + rb->texture_fb = RID(); + } + if (rb->texture.is_valid()) { RD::get_singleton()->free(rb->texture); rb->texture = RID(); @@ -1466,19 +1525,43 @@ void RendererSceneRenderRD::_free_render_buffer_data(RenderBuffers *rb) { } for (int i = 0; i < 2; i++) { + for (int m = 0; m < rb->blur[i].mipmaps.size(); m++) { + // do we free the texture slice here? or is it enough to free the main texture? + + // do free the mobile extra stuff + if (rb->blur[i].mipmaps[m].fb.is_valid()) { + RD::get_singleton()->free(rb->blur[i].mipmaps[m].fb); + } + if (rb->blur[i].mipmaps[m].half_fb.is_valid()) { + RD::get_singleton()->free(rb->blur[i].mipmaps[m].half_fb); + } + if (rb->blur[i].mipmaps[m].half_texture.is_valid()) { + RD::get_singleton()->free(rb->blur[i].mipmaps[m].half_texture); + } + } + rb->blur[i].mipmaps.clear(); + if (rb->blur[i].texture.is_valid()) { RD::get_singleton()->free(rb->blur[i].texture); rb->blur[i].texture = RID(); - rb->blur[i].mipmaps.clear(); } } + for (int i = 0; i < rb->luminance.fb.size(); i++) { + RD::get_singleton()->free(rb->luminance.fb[i]); + } + rb->luminance.fb.clear(); + for (int i = 0; i < rb->luminance.reduce.size(); i++) { RD::get_singleton()->free(rb->luminance.reduce[i]); } - rb->luminance.reduce.clear(); + if (rb->luminance.current_fb.is_valid()) { + RD::get_singleton()->free(rb->luminance.current_fb); + rb->luminance.current_fb = RID(); + } + if (rb->luminance.current.is_valid()) { RD::get_singleton()->free(rb->luminance.current); rb->luminance.current = RID(); @@ -1750,17 +1833,27 @@ void RendererSceneRenderRD::_render_buffers_post_process_and_tonemap(const Rende CameraEffects *camfx = camera_effects_owner.getornull(p_render_data->camera_effects); bool can_use_effects = rb->width >= 8 && rb->height >= 8; + bool can_use_storage = _render_buffers_can_be_storage(); + + // @TODO IMPLEMENT MULTIVIEW, all effects need to support stereo buffers or effects are only applied to the left eye if (can_use_effects && camfx && (camfx->dof_blur_near_enabled || camfx->dof_blur_far_enabled) && camfx->dof_blur_amount > 0.0) { + RD::get_singleton()->draw_command_begin_label("DOF"); if (rb->blur[0].texture.is_null()) { _allocate_blur_textures(rb); } - float bokeh_size = camfx->dof_blur_amount * 64.0; - storage->get_effects()->bokeh_dof(rb->texture, rb->depth_texture, Size2i(rb->width, rb->height), rb->blur[0].mipmaps[0].texture, rb->blur[1].mipmaps[0].texture, rb->blur[0].mipmaps[1].texture, camfx->dof_blur_far_enabled, camfx->dof_blur_far_distance, camfx->dof_blur_far_transition, camfx->dof_blur_near_enabled, camfx->dof_blur_near_distance, camfx->dof_blur_near_transition, bokeh_size, dof_blur_bokeh_shape, dof_blur_quality, dof_blur_use_jitter, p_render_data->z_near, p_render_data->z_far, p_render_data->cam_ortogonal); + if (can_use_storage) { + float bokeh_size = camfx->dof_blur_amount * 64.0; + storage->get_effects()->bokeh_dof(rb->texture, rb->depth_texture, Size2i(rb->width, rb->height), rb->blur[0].mipmaps[0].texture, rb->blur[1].mipmaps[0].texture, rb->blur[0].mipmaps[1].texture, camfx->dof_blur_far_enabled, camfx->dof_blur_far_distance, camfx->dof_blur_far_transition, camfx->dof_blur_near_enabled, camfx->dof_blur_near_distance, camfx->dof_blur_near_transition, bokeh_size, dof_blur_bokeh_shape, dof_blur_quality, dof_blur_use_jitter, p_render_data->z_near, p_render_data->z_far, p_render_data->cam_ortogonal); + } else { + storage->get_effects()->blur_dof_raster(rb->texture, rb->depth_texture, Size2i(rb->width, rb->height), rb->texture_fb, rb->blur[0].mipmaps[0].texture, rb->blur[0].mipmaps[0].fb, camfx->dof_blur_far_enabled, camfx->dof_blur_far_distance, camfx->dof_blur_far_transition, camfx->dof_blur_near_enabled, camfx->dof_blur_near_distance, camfx->dof_blur_near_transition, camfx->dof_blur_amount, dof_blur_quality, p_render_data->z_near, p_render_data->z_far, p_render_data->cam_ortogonal); + } + RD::get_singleton()->draw_command_end_label(); } if (can_use_effects && env && env->auto_exposure) { + RD::get_singleton()->draw_command_begin_label("Auto exposure"); if (rb->luminance.current.is_null()) { _allocate_luminance_textures(rb); } @@ -1769,16 +1862,26 @@ void RendererSceneRenderRD::_render_buffers_post_process_and_tonemap(const Rende rb->auto_exposure_version = env->auto_exposure_version; double step = env->auto_exp_speed * time_step; - storage->get_effects()->luminance_reduction(rb->texture, Size2i(rb->width, rb->height), rb->luminance.reduce, rb->luminance.current, env->min_luminance, env->max_luminance, step, set_immediate); - + if (can_use_storage) { + storage->get_effects()->luminance_reduction(rb->texture, Size2i(rb->width, rb->height), rb->luminance.reduce, rb->luminance.current, env->min_luminance, env->max_luminance, step, set_immediate); + } else { + storage->get_effects()->luminance_reduction_raster(rb->texture, Size2i(rb->width, rb->height), rb->luminance.reduce, rb->luminance.fb, rb->luminance.current, env->min_luminance, env->max_luminance, step, set_immediate); + } //swap final reduce with prev luminance SWAP(rb->luminance.current, rb->luminance.reduce.write[rb->luminance.reduce.size() - 1]); + if (!can_use_storage) { + SWAP(rb->luminance.current_fb, rb->luminance.fb.write[rb->luminance.fb.size() - 1]); + } + RenderingServerDefault::redraw_request(); //redraw all the time if auto exposure rendering is on + RD::get_singleton()->draw_command_end_label(); } int max_glow_level = -1; if (can_use_effects && env && env->glow_enabled) { + RD::get_singleton()->draw_command_begin_label("Gaussian Glow"); + /* see that blur textures are allocated */ if (rb->blur[1].texture.is_null()) { @@ -1804,14 +1907,26 @@ void RendererSceneRenderRD::_render_buffers_post_process_and_tonemap(const Rende if (env->auto_exposure && rb->luminance.current.is_valid()) { luminance_texture = rb->luminance.current; } - storage->get_effects()->gaussian_glow(rb->texture, rb->blur[1].mipmaps[i].texture, Size2i(vp_w, vp_h), env->glow_strength, glow_high_quality, true, env->glow_hdr_luminance_cap, env->exposure, env->glow_bloom, env->glow_hdr_bleed_threshold, env->glow_hdr_bleed_scale, luminance_texture, env->auto_exp_scale); + if (can_use_storage) { + storage->get_effects()->gaussian_glow(rb->texture, rb->blur[1].mipmaps[i].texture, Size2i(vp_w, vp_h), env->glow_strength, glow_high_quality, true, env->glow_hdr_luminance_cap, env->exposure, env->glow_bloom, env->glow_hdr_bleed_threshold, env->glow_hdr_bleed_scale, luminance_texture, env->auto_exp_scale); + } else { + storage->get_effects()->gaussian_glow_raster(rb->texture, rb->blur[1].mipmaps[i].half_fb, rb->blur[1].mipmaps[i].half_texture, rb->blur[1].mipmaps[i].fb, Size2i(vp_w, vp_h), env->glow_strength, glow_high_quality, true, env->glow_hdr_luminance_cap, env->exposure, env->glow_bloom, env->glow_hdr_bleed_threshold, env->glow_hdr_bleed_scale, luminance_texture, env->auto_exp_scale); + } } else { - storage->get_effects()->gaussian_glow(rb->blur[1].mipmaps[i - 1].texture, rb->blur[1].mipmaps[i].texture, Size2i(vp_w, vp_h), env->glow_strength, glow_high_quality); + if (can_use_storage) { + storage->get_effects()->gaussian_glow(rb->blur[1].mipmaps[i - 1].texture, rb->blur[1].mipmaps[i].texture, Size2i(vp_w, vp_h), env->glow_strength, glow_high_quality); + } else { + storage->get_effects()->gaussian_glow_raster(rb->blur[1].mipmaps[i - 1].texture, rb->blur[1].mipmaps[i].half_fb, rb->blur[1].mipmaps[i].half_texture, rb->blur[1].mipmaps[i].fb, Vector2(1.0 / vp_w, 1.0 / vp_h), env->glow_strength, glow_high_quality); + } } } + + RD::get_singleton()->draw_command_end_label(); } { + RD::get_singleton()->draw_command_begin_label("Tonemap"); + //tonemap EffectsRD::TonemapSettings tonemap; @@ -1870,6 +1985,8 @@ void RendererSceneRenderRD::_render_buffers_post_process_and_tonemap(const Rende tonemap.view_count = p_render_data->view_count; storage->get_effects()->tonemapper(rb->texture, storage->render_target_get_rd_framebuffer(rb->render_target), tonemap); + + RD::get_singleton()->draw_command_end_label(); } storage->render_target_disable_clear_request(rb->render_target); @@ -2133,7 +2250,7 @@ bool RendererSceneRenderRD::_render_buffers_can_be_storage() { } void RendererSceneRenderRD::render_buffers_configure(RID p_render_buffers, RID p_render_target, int p_width, int p_height, RS::ViewportMSAA p_msaa, RenderingServer::ViewportScreenSpaceAA p_screen_space_aa, bool p_use_debanding, uint32_t p_view_count) { - ERR_FAIL_COND_MSG(p_view_count == 0, "Must have atleast 1 view"); + ERR_FAIL_COND_MSG(p_view_count == 0, "Must have at least 1 view"); RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers); rb->width = p_width; @@ -2197,6 +2314,14 @@ void RendererSceneRenderRD::render_buffers_configure(RID p_render_buffers, RID p rb->depth_texture = RD::get_singleton()->texture_create(tf, RD::TextureView()); } + if (!_render_buffers_can_be_storage()) { + // ONLY USED ON MOBILE RENDERER, ONLY USED FOR POST EFFECTS! + Vector<RID> fb; + fb.push_back(rb->texture); + + rb->texture_fb = RD::get_singleton()->framebuffer_create(fb, RenderingDevice::INVALID_ID, rb->view_count); + } + rb->data->configure(rb->texture, rb->depth_texture, p_width, p_height, p_msaa, p_view_count); if (is_clustered_enabled()) { @@ -2259,6 +2384,8 @@ void RendererSceneRenderRD::shadows_quality_set(RS::ShadowQuality p_quality) { get_vogel_disk(penumbra_shadow_kernel, penumbra_shadow_samples); get_vogel_disk(soft_shadow_kernel, soft_shadow_samples); } + + _update_shader_quality_settings(); } void RendererSceneRenderRD::directional_shadow_quality_set(RS::ShadowQuality p_quality) { @@ -2299,6 +2426,23 @@ void RendererSceneRenderRD::directional_shadow_quality_set(RS::ShadowQuality p_q get_vogel_disk(directional_penumbra_shadow_kernel, directional_penumbra_shadow_samples); get_vogel_disk(directional_soft_shadow_kernel, directional_soft_shadow_samples); } + + _update_shader_quality_settings(); +} + +void RendererSceneRenderRD::decals_set_filter(RenderingServer::DecalFilter p_filter) { + if (decals_filter == p_filter) { + return; + } + decals_filter = p_filter; + _update_shader_quality_settings(); +} +void RendererSceneRenderRD::light_projectors_set_filter(RenderingServer::LightProjectorFilter p_filter) { + if (light_projectors_filter == p_filter) { + return; + } + light_projectors_filter = p_filter; + _update_shader_quality_settings(); } int RendererSceneRenderRD::get_roughness_layers() const { @@ -4287,6 +4431,9 @@ RendererSceneRenderRD::RendererSceneRenderRD(RendererStorageRD *p_storage) { environment_set_volumetric_fog_volume_size(GLOBAL_GET("rendering/environment/volumetric_fog/volume_size"), GLOBAL_GET("rendering/environment/volumetric_fog/volume_depth")); environment_set_volumetric_fog_filter_active(GLOBAL_GET("rendering/environment/volumetric_fog/use_filter")); + decals_set_filter(RS::DecalFilter(int(GLOBAL_GET("rendering/textures/decals/filter")))); + light_projectors_set_filter(RS::LightProjectorFilter(int(GLOBAL_GET("rendering/textures/light_projectors/filter")))); + cull_argument.set_page_pool(&cull_argument_pool); } diff --git a/servers/rendering/renderer_rd/renderer_scene_render_rd.h b/servers/rendering/renderer_rd/renderer_scene_render_rd.h index cd2056d390..bb06eb608f 100644 --- a/servers/rendering/renderer_rd/renderer_scene_render_rd.h +++ b/servers/rendering/renderer_rd/renderer_scene_render_rd.h @@ -165,6 +165,8 @@ protected: virtual void _map_forward_id(ForwardIDType p_type, ForwardID p_id, uint32_t p_index) {} virtual bool _uses_forward_ids() const { return false; } + virtual void _update_shader_quality_settings() {} + private: RS::ViewportDebugDraw debug_draw = RS::VIEWPORT_DEBUG_DRAW_DISABLED; static RendererSceneRenderRD *singleton; @@ -305,6 +307,8 @@ private: int directional_soft_shadow_samples = 0; int penumbra_shadow_samples = 0; int soft_shadow_samples = 0; + RS::DecalFilter decals_filter = RS::DECAL_FILTER_LINEAR_MIPMAPS; + RS::LightProjectorFilter light_projectors_filter = RS::LIGHT_PROJECTOR_FILTER_LINEAR_MIPMAPS; /* DIRECTIONAL SHADOW */ @@ -446,6 +450,7 @@ private: RID texture; //main texture for rendering to, must be filled after done rendering RID depth_texture; //main depth texture + RID texture_fb; // framebuffer for the main texture, ONLY USED FOR MOBILE RENDERER POST EFFECTS, DO NOT USE FOR RENDERING 3D!!! RendererSceneGIRD::SDFGI *sdfgi = nullptr; VolumetricFog *volumetric_fog = nullptr; @@ -461,6 +466,11 @@ private: RID texture; int width; int height; + + // only used on mobile renderer + RID fb; + RID half_texture; + RID half_fb; }; Vector<Mipmap> mipmaps; @@ -471,6 +481,10 @@ private: struct Luminance { Vector<RID> reduce; RID current; + + // used only on mobile renderer + Vector<RID> fb; + RID current_fb; } luminance; struct SSAO { @@ -1197,6 +1211,10 @@ public: virtual void shadows_quality_set(RS::ShadowQuality p_quality) override; virtual void directional_shadow_quality_set(RS::ShadowQuality p_quality) override; + + virtual void decals_set_filter(RS::DecalFilter p_filter) override; + virtual void light_projectors_set_filter(RS::LightProjectorFilter p_filter) override; + _FORCE_INLINE_ RS::ShadowQuality shadows_quality_get() const { return shadows_quality; } _FORCE_INLINE_ RS::ShadowQuality directional_shadow_quality_get() const { return directional_shadow_quality; } _FORCE_INLINE_ float shadows_quality_radius_get() const { return shadows_quality_radius; } @@ -1212,6 +1230,9 @@ public: _FORCE_INLINE_ int penumbra_shadow_samples_get() const { return penumbra_shadow_samples; } _FORCE_INLINE_ int soft_shadow_samples_get() const { return soft_shadow_samples; } + _FORCE_INLINE_ RS::LightProjectorFilter light_projectors_get_filter() const { return light_projectors_filter; } + _FORCE_INLINE_ RS::DecalFilter decals_get_filter() const { return decals_filter; } + int get_roughness_layers() const; bool is_using_radiance_cubemap_array() const; diff --git a/servers/rendering/renderer_rd/renderer_scene_sky_rd.cpp b/servers/rendering/renderer_rd/renderer_scene_sky_rd.cpp index e701219617..bc1603a219 100644 --- a/servers/rendering/renderer_rd/renderer_scene_sky_rd.cpp +++ b/servers/rendering/renderer_rd/renderer_scene_sky_rd.cpp @@ -757,7 +757,13 @@ void RendererSceneSkyRD::init(RendererStorageRD *p_storage) { sky_shader.default_shader = storage->shader_allocate(); storage->shader_initialize(sky_shader.default_shader); - storage->shader_set_code(sky_shader.default_shader, "shader_type sky; void sky() { COLOR = vec3(0.0); } \n"); + storage->shader_set_code(sky_shader.default_shader, R"( +shader_type sky; + +void sky() { + COLOR = vec3(0.0); +} +)"); sky_shader.default_material = storage->material_allocate(); storage->material_initialize(sky_shader.default_material); @@ -838,7 +844,15 @@ void RendererSceneSkyRD::init(RendererStorageRD *p_storage) { sky_scene_state.fog_shader = storage->shader_allocate(); storage->shader_initialize(sky_scene_state.fog_shader); - storage->shader_set_code(sky_scene_state.fog_shader, "shader_type sky; uniform vec4 clear_color; void sky() { COLOR = clear_color.rgb; } \n"); + storage->shader_set_code(sky_scene_state.fog_shader, R"( +shader_type sky; + +uniform vec4 clear_color; + +void sky() { + COLOR = clear_color.rgb; +} +)"); sky_scene_state.fog_material = storage->material_allocate(); storage->material_initialize(sky_scene_state.fog_material); diff --git a/servers/rendering/renderer_rd/renderer_storage_rd.cpp b/servers/rendering/renderer_rd/renderer_storage_rd.cpp index 8e79f33dfa..d5c7db6fd2 100644 --- a/servers/rendering/renderer_rd/renderer_storage_rd.cpp +++ b/servers/rendering/renderer_rd/renderer_storage_rd.cpp @@ -2716,9 +2716,7 @@ void RendererStorageRD::mesh_add_surface(RID p_mesh, const RS::SurfaceData &p_su mesh->surfaces[mesh->surface_count] = s; mesh->surface_count++; - for (List<MeshInstance *>::Element *E = mesh->instances.front(); E; E = E->next()) { - //update instances - MeshInstance *mi = E->get(); + for (MeshInstance *mi : mesh->instances) { _mesh_instance_add_surface(mi, mesh, mesh->surface_count - 1); } @@ -3029,8 +3027,7 @@ void RendererStorageRD::mesh_clear(RID p_mesh) { mesh->surface_count = 0; mesh->material_cache.clear(); //clear instance data - for (List<MeshInstance *>::Element *E = mesh->instances.front(); E; E = E->next()) { - MeshInstance *mi = E->get(); + for (MeshInstance *mi : mesh->instances) { _mesh_instance_clear(mi); } mesh->has_bone_weights = false; @@ -4962,7 +4959,7 @@ void RendererStorageRD::particles_set_view_axis(RID p_particles, const Vector3 & RD::get_singleton()->compute_list_dispatch_threads(compute_list, particles->amount, 1, 1); RD::get_singleton()->compute_list_end(); - effects.sort_buffer(particles->particles_sort_uniform_set, particles->amount); + effects->sort_buffer(particles->particles_sort_uniform_set, particles->amount); } copy_push_constant.total_particles *= copy_push_constant.total_particles; @@ -7538,7 +7535,7 @@ void RendererStorageRD::render_target_copy_to_back_buffer(RID p_render_target, c //single texture copy for backbuffer //RD::get_singleton()->texture_copy(rt->color, rt->backbuffer_mipmap0, Vector3(region.position.x, region.position.y, 0), Vector3(region.position.x, region.position.y, 0), Vector3(region.size.x, region.size.y, 1), 0, 0, 0, 0, true); - effects.copy_to_rect(rt->color, rt->backbuffer_mipmap0, region, false, false, false, true, true); + effects->copy_to_rect(rt->color, rt->backbuffer_mipmap0, region, false, false, false, true, true); if (!p_gen_mipmaps) { return; @@ -7554,7 +7551,7 @@ void RendererStorageRD::render_target_copy_to_back_buffer(RID p_render_target, c region.size.y = MAX(1, region.size.y >> 1); const RenderTarget::BackbufferMipmap &mm = rt->backbuffer_mipmaps[i]; - effects.gaussian_blur(prev_texture, mm.mipmap, mm.mipmap_copy, region, true); + effects->gaussian_blur(prev_texture, mm.mipmap, mm.mipmap_copy, region, true); prev_texture = mm.mipmap; } } @@ -7577,7 +7574,7 @@ void RendererStorageRD::render_target_clear_back_buffer(RID p_render_target, con } //single texture copy for backbuffer - effects.set_color(rt->backbuffer_mipmap0, p_color, region, true); + effects->set_color(rt->backbuffer_mipmap0, p_color, region, true); } void RendererStorageRD::render_target_gen_back_buffer_mipmaps(RID p_render_target, const Rect2i &p_region) { @@ -7607,7 +7604,7 @@ void RendererStorageRD::render_target_gen_back_buffer_mipmaps(RID p_render_targe region.size.y = MAX(1, region.size.y >> 1); const RenderTarget::BackbufferMipmap &mm = rt->backbuffer_mipmaps[i]; - effects.gaussian_blur(prev_texture, mm.mipmap, mm.mipmap_copy, region, true); + effects->gaussian_blur(prev_texture, mm.mipmap, mm.mipmap_copy, region, true); prev_texture = mm.mipmap; } } @@ -7928,14 +7925,14 @@ void RendererStorageRD::_update_decal_atlas() { while ((K = decal_atlas.textures.next(K))) { DecalAtlas::Texture *t = decal_atlas.textures.getptr(*K); Texture *src_tex = texture_owner.getornull(*K); - effects.copy_to_atlas_fb(src_tex->rd_texture, mm.fb, t->uv_rect, draw_list, false, t->panorama_to_dp_users > 0); + effects->copy_to_atlas_fb(src_tex->rd_texture, mm.fb, t->uv_rect, draw_list, false, t->panorama_to_dp_users > 0); } RD::get_singleton()->draw_list_end(); prev_texture = mm.texture; } else { - effects.copy_to_fb_rect(prev_texture, mm.fb, Rect2i(Point2i(), mm.size)); + effects->copy_to_fb_rect(prev_texture, mm.fb, Rect2i(Point2i(), mm.size)); prev_texture = mm.texture; } } else { @@ -8413,10 +8410,10 @@ void RendererStorageRD::global_variables_load_settings(bool p_load_textures) { List<PropertyInfo> settings; ProjectSettings::get_singleton()->get_property_list(&settings); - for (List<PropertyInfo>::Element *E = settings.front(); E; E = E->next()) { - if (E->get().name.begins_with("shader_globals/")) { - StringName name = E->get().name.get_slice("/", 1); - Dictionary d = ProjectSettings::get_singleton()->get(E->get().name); + for (const PropertyInfo &E : settings) { + if (E.name.begins_with("shader_globals/")) { + StringName name = E.name.get_slice("/", 1); + Dictionary d = ProjectSettings::get_singleton()->get(E.name); ERR_CONTINUE(!d.has("type")); ERR_CONTINUE(!d.has("value")); @@ -8584,8 +8581,8 @@ void RendererStorageRD::_update_global_variables() { if (global_variables.must_update_buffer_materials) { // only happens in the case of a buffer variable added or removed, // so not often. - for (List<RID>::Element *E = global_variables.materials_using_buffer.front(); E; E = E->next()) { - Material *material = material_owner.getornull(E->get()); + for (const RID &E : global_variables.materials_using_buffer) { + Material *material = material_owner.getornull(E); ERR_CONTINUE(!material); //wtf _material_queue_update(material, true, false); @@ -8597,8 +8594,8 @@ void RendererStorageRD::_update_global_variables() { if (global_variables.must_update_texture_materials) { // only happens in the case of a buffer variable added or removed, // so not often. - for (List<RID>::Element *E = global_variables.materials_using_texture.front(); E; E = E->next()) { - Material *material = material_owner.getornull(E->get()); + for (const RID &E : global_variables.materials_using_texture) { + Material *material = material_owner.getornull(E); ERR_CONTINUE(!material); //wtf _material_queue_update(material, false, true); @@ -8807,8 +8804,13 @@ bool RendererStorageRD::free(RID p_rid) { return true; } +void RendererStorageRD::init_effects(bool p_prefer_raster_effects) { + effects = memnew(EffectsRD(p_prefer_raster_effects)); +} + EffectsRD *RendererStorageRD::get_effects() { - return &effects; + ERR_FAIL_NULL_V_MSG(effects, nullptr, "Effects haven't been initialised yet."); + return effects; } void RendererStorageRD::capture_timestamps_begin() { @@ -9388,7 +9390,13 @@ RendererStorageRD::RendererStorageRD() { // default material and shader for particles shader particles_shader.default_shader = shader_allocate(); shader_initialize(particles_shader.default_shader); - shader_set_code(particles_shader.default_shader, "shader_type particles; void process() { COLOR = vec4(1.0); } \n"); + shader_set_code(particles_shader.default_shader, R"( +shader_type particles; + +void process() { + COLOR = vec4(1.0); +} +)"); particles_shader.default_material = material_allocate(); material_initialize(particles_shader.default_material); material_set_shader(particles_shader.default_material, particles_shader.default_shader); @@ -9532,4 +9540,9 @@ RendererStorageRD::~RendererStorageRD() { if (decal_atlas.texture.is_valid()) { RD::get_singleton()->free(decal_atlas.texture); } + + if (effects) { + memdelete(effects); + effects = NULL; + } } diff --git a/servers/rendering/renderer_rd/renderer_storage_rd.h b/servers/rendering/renderer_rd/renderer_storage_rd.h index f471874c8e..b290c07705 100644 --- a/servers/rendering/renderer_rd/renderer_storage_rd.h +++ b/servers/rendering/renderer_rd/renderer_storage_rd.h @@ -1290,7 +1290,7 @@ private: void _update_global_variables(); /* EFFECTS */ - EffectsRD effects; + EffectsRD *effects = NULL; public: virtual bool can_create_resources_async() const; @@ -2374,6 +2374,7 @@ public: static RendererStorageRD *base_singleton; + void init_effects(bool p_prefer_raster_effects); EffectsRD *get_effects(); RendererStorageRD(); diff --git a/servers/rendering/renderer_rd/shader_compiler_rd.cpp b/servers/rendering/renderer_rd/shader_compiler_rd.cpp index b347197289..9c1068ea2e 100644 --- a/servers/rendering/renderer_rd/shader_compiler_rd.cpp +++ b/servers/rendering/renderer_rd/shader_compiler_rd.cpp @@ -571,7 +571,7 @@ String ShaderCompilerRD::_dump_node_code(const SL::Node *p_node, int p_level, Ge max_texture_uniforms++; } else { if (E->get().scope == SL::ShaderNode::Uniform::SCOPE_INSTANCE) { - continue; //instances are indexed directly, dont need index uniforms + continue; // Instances are indexed directly, don't need index uniforms. } max_uniforms++; @@ -605,7 +605,7 @@ String ShaderCompilerRD::_dump_node_code(const SL::Node *p_node, int p_level, Ge if (uniform.scope == SL::ShaderNode::Uniform::SCOPE_INSTANCE) { //insert, but don't generate any code. p_actions.uniforms->insert(uniform_name, uniform); - continue; //instances are indexed directly, dont need index uniforms + continue; // Instances are indexed directly, don't need index uniforms. } if (SL::is_sampler_type(uniform.type)) { ucode = "layout(set = " + itos(actions.texture_layout_set) + ", binding = " + itos(actions.base_texture_binding_index + uniform.texture_order) + ") uniform "; @@ -760,11 +760,11 @@ String ShaderCompilerRD::_dump_node_code(const SL::Node *p_node, int p_level, Ge if (var_frag_to_light.size() > 0) { String gcode = "\n\nstruct {\n"; - for (List<Pair<StringName, SL::ShaderNode::Varying>>::Element *E = var_frag_to_light.front(); E; E = E->next()) { - gcode += "\t" + _prestr(E->get().second.precision) + _typestr(E->get().second.type) + " " + _mkid(E->get().first); - if (E->get().second.array_size > 0) { + for (const Pair<StringName, SL::ShaderNode::Varying> &E : var_frag_to_light) { + gcode += "\t" + _prestr(E.second.precision) + _typestr(E.second.type) + " " + _mkid(E.first); + if (E.second.array_size > 0) { gcode += "["; - gcode += itos(E->get().second.array_size); + gcode += itos(E.second.array_size); gcode += "]"; } gcode += ";\n"; @@ -1351,7 +1351,13 @@ Error ShaderCompilerRD::compile(RS::ShaderMode p_mode, const String &p_code, Ide if (err != OK) { Vector<String> shader = p_code.split("\n"); for (int i = 0; i < shader.size(); i++) { - print_line(itos(i + 1) + " " + shader[i]); + if (i + 1 == parser.get_error_line()) { + // Mark the error line to be visible without having to look at + // the trace at the end. + print_line(vformat("E%4d-> %s", i + 1, shader[i])); + } else { + print_line(vformat("%5d | %s", i + 1, shader[i])); + } } _err_print_error(nullptr, p_path.utf8().get_data(), parser.get_error_line(), parser.get_error_text().utf8().get_data(), ERR_HANDLER_SHADER); @@ -1388,8 +1394,8 @@ void ShaderCompilerRD::initialize(DefaultIdentifierActions p_actions) { ShaderLanguage::get_builtin_funcs(&func_list); - for (List<String>::Element *E = func_list.front(); E; E = E->next()) { - internal_functions.insert(E->get()); + for (const String &E : func_list) { + internal_functions.insert(E); } texture_functions.insert("texture"); texture_functions.insert("textureProj"); diff --git a/servers/rendering/renderer_rd/shader_rd.cpp b/servers/rendering/renderer_rd/shader_rd.cpp index 27305cc938..5bb12fc168 100644 --- a/servers/rendering/renderer_rd/shader_rd.cpp +++ b/servers/rendering/renderer_rd/shader_rd.cpp @@ -116,8 +116,10 @@ void ShaderRD::setup(const char *p_vertex_code, const char *p_fragment_code, con } StringBuilder tohash; - tohash.append("[VersionKey]"); - tohash.append(RenderingDevice::get_singleton()->shader_get_cache_key()); + tohash.append("[SpirvCacheKey]"); + tohash.append(RenderingDevice::get_singleton()->shader_get_spirv_cache_key()); + tohash.append("[BinaryCacheKey]"); + tohash.append(RenderingDevice::get_singleton()->shader_get_binary_cache_key()); tohash.append("[Vertex]"); tohash.append(p_vertex_code ? p_vertex_code : ""); tohash.append("[Fragment]"); @@ -144,12 +146,14 @@ void ShaderRD::_clear_version(Version *p_version) { //clear versions if they exist if (p_version->variants) { for (int i = 0; i < variant_defines.size(); i++) { - RD::get_singleton()->free(p_version->variants[i]); + if (variants_enabled[i]) { + RD::get_singleton()->free(p_version->variants[i]); + } } memdelete_arr(p_version->variants); - if (p_version->variant_stages) { - memdelete_arr(p_version->variant_stages); + if (p_version->variant_data) { + memdelete_arr(p_version->variant_data); } p_version->variants = nullptr; } @@ -203,7 +207,7 @@ void ShaderRD::_compile_variant(uint32_t p_variant, Version *p_version) { return; //variant is disabled, return } - Vector<RD::ShaderStageData> &stages = p_version->variant_stages[p_variant]; + Vector<RD::ShaderStageSPIRVData> stages; String error; String current_source; @@ -217,8 +221,8 @@ void ShaderRD::_compile_variant(uint32_t p_variant, Version *p_version) { _build_variant_code(builder, p_variant, p_version, stage_templates[STAGE_TYPE_VERTEX]); current_source = builder.as_string(); - RD::ShaderStageData stage; - stage.spir_v = RD::get_singleton()->shader_compile_from_source(RD::SHADER_STAGE_VERTEX, current_source, RD::SHADER_LANGUAGE_GLSL, &error); + RD::ShaderStageSPIRVData stage; + stage.spir_v = RD::get_singleton()->shader_compile_spirv_from_source(RD::SHADER_STAGE_VERTEX, current_source, RD::SHADER_LANGUAGE_GLSL, &error); if (stage.spir_v.size() == 0) { build_ok = false; } else { @@ -235,8 +239,8 @@ void ShaderRD::_compile_variant(uint32_t p_variant, Version *p_version) { _build_variant_code(builder, p_variant, p_version, stage_templates[STAGE_TYPE_FRAGMENT]); current_source = builder.as_string(); - RD::ShaderStageData stage; - stage.spir_v = RD::get_singleton()->shader_compile_from_source(RD::SHADER_STAGE_FRAGMENT, current_source, RD::SHADER_LANGUAGE_GLSL, &error); + RD::ShaderStageSPIRVData stage; + stage.spir_v = RD::get_singleton()->shader_compile_spirv_from_source(RD::SHADER_STAGE_FRAGMENT, current_source, RD::SHADER_LANGUAGE_GLSL, &error); if (stage.spir_v.size() == 0) { build_ok = false; } else { @@ -254,8 +258,8 @@ void ShaderRD::_compile_variant(uint32_t p_variant, Version *p_version) { current_source = builder.as_string(); - RD::ShaderStageData stage; - stage.spir_v = RD::get_singleton()->shader_compile_from_source(RD::SHADER_STAGE_COMPUTE, current_source, RD::SHADER_LANGUAGE_GLSL, &error); + RD::ShaderStageSPIRVData stage; + stage.spir_v = RD::get_singleton()->shader_compile_spirv_from_source(RD::SHADER_STAGE_COMPUTE, current_source, RD::SHADER_LANGUAGE_GLSL, &error); if (stage.spir_v.size() == 0) { build_ok = false; } else { @@ -275,10 +279,15 @@ void ShaderRD::_compile_variant(uint32_t p_variant, Version *p_version) { return; } - RID shader = RD::get_singleton()->shader_create(stages); + Vector<uint8_t> shader_data = RD::get_singleton()->shader_compile_binary_from_spirv(stages); + + ERR_FAIL_COND(shader_data.size() == 0); + + RID shader = RD::get_singleton()->shader_create_from_bytecode(shader_data); { MutexLock lock(variant_set_mutex); p_version->variants[p_variant] = shader; + p_version->variant_data[p_variant] = shader_data; } } @@ -364,14 +373,12 @@ String ShaderRD::_version_get_sha1(Version *p_version) const { } static const char *shader_file_header = "GDSC"; -static const uint32_t cache_file_version = 1; +static const uint32_t cache_file_version = 2; bool ShaderRD::_load_from_cache(Version *p_version) { String sha1 = _version_get_sha1(p_version); String path = shader_cache_dir.plus_file(name).plus_file(base_sha256).plus_file(sha1) + ".cache"; - uint64_t time_from = OS::get_singleton()->get_ticks_usec(); - FileAccessRef f = FileAccess::open(path, FileAccess::READ); if (!f) { return false; @@ -390,76 +397,43 @@ bool ShaderRD::_load_from_cache(Version *p_version) { ERR_FAIL_COND_V(variant_count != (uint32_t)variant_defines.size(), false); //should not happen but check - bool success = true; for (uint32_t i = 0; i < variant_count; i++) { - uint32_t stage_count = f->get_32(); - p_version->variant_stages[i].resize(stage_count); - for (uint32_t j = 0; j < stage_count; j++) { - p_version->variant_stages[i].write[j].shader_stage = RD::ShaderStage(f->get_32()); - - int compression = f->get_32(); - uint32_t length = f->get_32(); - - if (compression == 0) { - Vector<uint8_t> data; - data.resize(length); - - f->get_buffer(data.ptrw(), length); - - p_version->variant_stages[i].write[j].spir_v = data; - } else { - Vector<uint8_t> data; - - if (compression == 2) { - //zstd - int smol_length = f->get_32(); - Vector<uint8_t> zstd_data; - - zstd_data.resize(smol_length); - f->get_buffer(zstd_data.ptrw(), smol_length); - - data.resize(length); - Compression::decompress(data.ptrw(), data.size(), zstd_data.ptr(), zstd_data.size(), Compression::MODE_ZSTD); - - } else { - data.resize(length); - f->get_buffer(data.ptrw(), length); - } - - Vector<uint8_t> spirv; - uint32_t spirv_size = smolv::GetDecodedBufferSize(data.ptr(), data.size()); - spirv.resize(spirv_size); - if (!smolv::Decode(data.ptr(), data.size(), spirv.ptrw(), spirv_size)) { - ERR_PRINT("Malformed smolv input uncompressing shader " + name + ", variant #" + itos(i) + " stage :" + itos(j)); - success = false; - break; - } - p_version->variant_stages[i].write[j].spir_v = spirv; - } + uint32_t variant_size = f->get_32(); + ERR_FAIL_COND_V(variant_size == 0 && variants_enabled[i], false); + if (!variants_enabled[i]) { + continue; } - } + Vector<uint8_t> variant_bytes; + variant_bytes.resize(variant_size); - if (!success) { - for (uint32_t i = 0; i < variant_count; i++) { - p_version->variant_stages[i].resize(0); - } - return false; - } + uint32_t br = f->get_buffer(variant_bytes.ptrw(), variant_size); - float time_ms = double(OS::get_singleton()->get_ticks_usec() - time_from) / 1000.0; + ERR_FAIL_COND_V(br != variant_size, false); - print_verbose("Shader cache load success '" + path + "' " + rtos(time_ms) + "ms."); + p_version->variant_data[i] = variant_bytes; + } for (uint32_t i = 0; i < variant_count; i++) { - RID shader = RD::get_singleton()->shader_create(p_version->variant_stages[i]); + if (!variants_enabled[i]) { + MutexLock lock(variant_set_mutex); + p_version->variants[i] = RID(); + continue; + } + RID shader = RD::get_singleton()->shader_create_from_bytecode(p_version->variant_data[i]); + if (shader.is_null()) { + for (uint32_t j = 0; j < i; j++) { + RD::get_singleton()->free(p_version->variants[i]); + } + ERR_FAIL_COND_V(shader.is_null(), false); + } { MutexLock lock(variant_set_mutex); p_version->variants[i] = shader; } } - memdelete_arr(p_version->variant_stages); //clear stages - p_version->variant_stages = nullptr; + memdelete_arr(p_version->variant_data); //clear stages + p_version->variant_data = nullptr; p_version->valid = true; return true; } @@ -476,49 +450,8 @@ void ShaderRD::_save_to_cache(Version *p_version) { f->store_32(variant_count); //variant count for (uint32_t i = 0; i < variant_count; i++) { - f->store_32(p_version->variant_stages[i].size()); //stage count - for (int j = 0; j < p_version->variant_stages[i].size(); j++) { - f->store_32(p_version->variant_stages[i][j].shader_stage); //stage count - Vector<uint8_t> spirv = p_version->variant_stages[i][j].spir_v; - - bool save_uncompressed = true; - if (shader_cache_save_compressed) { - smolv::ByteArray smolv; - bool strip_debug = !shader_cache_save_debug; - if (!smolv::Encode(spirv.ptr(), spirv.size(), smolv, strip_debug ? smolv::kEncodeFlagStripDebugInfo : 0)) { - ERR_PRINT("Error compressing shader " + name + ", variant #" + itos(i) + " stage :" + itos(i)); - } else { - bool compress_zstd = shader_cache_save_compressed_zstd; - - if (compress_zstd) { - Vector<uint8_t> zstd; - zstd.resize(Compression::get_max_compressed_buffer_size(smolv.size(), Compression::MODE_ZSTD)); - int dst_size = Compression::compress(zstd.ptrw(), &smolv[0], smolv.size(), Compression::MODE_ZSTD); - if (dst_size >= 0 && (uint32_t)dst_size < smolv.size()) { - f->store_32(2); //compressed zstd - f->store_32(smolv.size()); //size of smolv buffer - f->store_32(dst_size); //size of smolv buffer - f->store_buffer(zstd.ptr(), dst_size); //smolv buffer - } else { - compress_zstd = false; - } - } - - if (!compress_zstd) { - f->store_32(1); //compressed - f->store_32(smolv.size()); //size of smolv buffer - f->store_buffer(&smolv[0], smolv.size()); //smolv buffer - } - save_uncompressed = false; - } - } - - if (save_uncompressed) { - f->store_32(0); //uncompressed - f->store_32(spirv.size()); //stage count - f->store_buffer(spirv.ptr(), spirv.size()); //stage count - } - } + f->store_32(p_version->variant_data[i].size()); //stage count + f->store_buffer(p_version->variant_data[i].ptr(), p_version->variant_data[i].size()); } f->close(); @@ -531,8 +464,8 @@ void ShaderRD::_compile_version(Version *p_version) { p_version->dirty = false; p_version->variants = memnew_arr(RID, variant_defines.size()); - typedef Vector<RD::ShaderStageData> ShaderStageArray; - p_version->variant_stages = memnew_arr(ShaderStageArray, variant_defines.size()); + typedef Vector<uint8_t> ShaderStageData; + p_version->variant_data = memnew_arr(ShaderStageData, variant_defines.size()); if (shader_cache_dir_valid) { if (_load_from_cache(p_version)) { @@ -571,19 +504,19 @@ void ShaderRD::_compile_version(Version *p_version) { } } memdelete_arr(p_version->variants); - if (p_version->variant_stages) { - memdelete_arr(p_version->variant_stages); + if (p_version->variant_data) { + memdelete_arr(p_version->variant_data); } p_version->variants = nullptr; - p_version->variant_stages = nullptr; + p_version->variant_data = nullptr; return; } else if (shader_cache_dir_valid) { //save shader cache _save_to_cache(p_version); } - memdelete_arr(p_version->variant_stages); //clear stages - p_version->variant_stages = nullptr; + memdelete_arr(p_version->variant_data); //clear stages + p_version->variant_data = nullptr; p_version->valid = true; } diff --git a/servers/rendering/renderer_rd/shader_rd.h b/servers/rendering/renderer_rd/shader_rd.h index 9a68e02007..529328f0ed 100644 --- a/servers/rendering/renderer_rd/shader_rd.h +++ b/servers/rendering/renderer_rd/shader_rd.h @@ -59,7 +59,7 @@ class ShaderRD { Map<StringName, CharString> code_sections; Vector<CharString> custom_defines; - Vector<RD::ShaderStageData> *variant_stages = nullptr; + Vector<uint8_t> *variant_data = nullptr; RID *variants = nullptr; //same size as version defines bool valid; diff --git a/servers/rendering/renderer_rd/shaders/blur_raster.glsl b/servers/rendering/renderer_rd/shaders/blur_raster.glsl new file mode 100644 index 0000000000..b1d1c2365e --- /dev/null +++ b/servers/rendering/renderer_rd/shaders/blur_raster.glsl @@ -0,0 +1,228 @@ +/* clang-format off */ +#[vertex] + +#version 450 + +#VERSION_DEFINES + +#include "blur_raster_inc.glsl" + +layout(location = 0) out vec2 uv_interp; +/* clang-format on */ + +void main() { + vec2 base_arr[4] = vec2[](vec2(0.0, 0.0), vec2(0.0, 1.0), vec2(1.0, 1.0), vec2(1.0, 0.0)); + uv_interp = base_arr[gl_VertexIndex]; + + gl_Position = vec4(uv_interp * 2.0 - 1.0, 0.0, 1.0); +} + +/* clang-format off */ +#[fragment] + +#version 450 + +#VERSION_DEFINES + +#include "blur_raster_inc.glsl" + +layout(location = 0) in vec2 uv_interp; +/* clang-format on */ + +layout(set = 0, binding = 0) uniform sampler2D source_color; + +#ifdef GLOW_USE_AUTO_EXPOSURE +layout(set = 1, binding = 0) uniform sampler2D source_auto_exposure; +#endif + +layout(location = 0) out vec4 frag_color; + +//DOF +#ifdef MODE_DOF_BLUR + +layout(set = 1, binding = 0) uniform sampler2D dof_source_depth; + +#ifdef DOF_QUALITY_LOW +const int dof_kernel_size = 5; +const int dof_kernel_from = 2; +const float dof_kernel[5] = float[](0.153388, 0.221461, 0.250301, 0.221461, 0.153388); +#endif + +#ifdef DOF_QUALITY_MEDIUM +const int dof_kernel_size = 11; +const int dof_kernel_from = 5; +const float dof_kernel[11] = float[](0.055037, 0.072806, 0.090506, 0.105726, 0.116061, 0.119726, 0.116061, 0.105726, 0.090506, 0.072806, 0.055037); + +#endif + +#ifdef DOF_QUALITY_HIGH +const int dof_kernel_size = 21; +const int dof_kernel_from = 10; +const float dof_kernel[21] = float[](0.028174, 0.032676, 0.037311, 0.041944, 0.046421, 0.050582, 0.054261, 0.057307, 0.059587, 0.060998, 0.061476, 0.060998, 0.059587, 0.057307, 0.054261, 0.050582, 0.046421, 0.041944, 0.037311, 0.032676, 0.028174); +#endif + +#endif + +void main() { +#ifdef MODE_MIPMAP + + vec2 pix_size = blur.pixel_size; + vec4 color = texture(source_color, uv_interp + vec2(-0.5, -0.5) * pix_size); + color += texture(source_color, uv_interp + vec2(0.5, -0.5) * pix_size); + color += texture(source_color, uv_interp + vec2(0.5, 0.5) * pix_size); + color += texture(source_color, uv_interp + vec2(-0.5, 0.5) * pix_size); + frag_color = color / 4.0; + +#endif + +#ifdef MODE_GAUSSIAN_BLUR + + //Simpler blur uses SIGMA2 for the gaussian kernel for a stronger effect + + if (bool(blur.flags & FLAG_HORIZONTAL)) { + vec2 pix_size = blur.pixel_size; + pix_size *= 0.5; //reading from larger buffer, so use more samples + vec4 color = texture(source_color, uv_interp + vec2(0.0, 0.0) * pix_size) * 0.214607; + color += texture(source_color, uv_interp + vec2(1.0, 0.0) * pix_size) * 0.189879; + color += texture(source_color, uv_interp + vec2(2.0, 0.0) * pix_size) * 0.131514; + color += texture(source_color, uv_interp + vec2(3.0, 0.0) * pix_size) * 0.071303; + color += texture(source_color, uv_interp + vec2(-1.0, 0.0) * pix_size) * 0.189879; + color += texture(source_color, uv_interp + vec2(-2.0, 0.0) * pix_size) * 0.131514; + color += texture(source_color, uv_interp + vec2(-3.0, 0.0) * pix_size) * 0.071303; + frag_color = color; + } else { + vec2 pix_size = blur.pixel_size; + vec4 color = texture(source_color, uv_interp + vec2(0.0, 0.0) * pix_size) * 0.38774; + color += texture(source_color, uv_interp + vec2(0.0, 1.0) * pix_size) * 0.24477; + color += texture(source_color, uv_interp + vec2(0.0, 2.0) * pix_size) * 0.06136; + color += texture(source_color, uv_interp + vec2(0.0, -1.0) * pix_size) * 0.24477; + color += texture(source_color, uv_interp + vec2(0.0, -2.0) * pix_size) * 0.06136; + frag_color = color; + } +#endif + +#ifdef MODE_GAUSSIAN_GLOW + + //Glow uses larger sigma 1 for a more rounded blur effect + +#define GLOW_ADD(m_ofs, m_mult) \ + { \ + vec2 ofs = uv_interp + m_ofs * pix_size; \ + vec4 c = texture(source_color, ofs) * m_mult; \ + if (any(lessThan(ofs, vec2(0.0))) || any(greaterThan(ofs, vec2(1.0)))) { \ + c *= 0.0; \ + } \ + color += c; \ + } + + if (bool(blur.flags & FLAG_HORIZONTAL)) { + vec2 pix_size = blur.pixel_size; + pix_size *= 0.5; //reading from larger buffer, so use more samples + vec4 color = texture(source_color, uv_interp + vec2(0.0, 0.0) * pix_size) * 0.174938; + GLOW_ADD(vec2(1.0, 0.0), 0.165569); + GLOW_ADD(vec2(2.0, 0.0), 0.140367); + GLOW_ADD(vec2(3.0, 0.0), 0.106595); + GLOW_ADD(vec2(-1.0, 0.0), 0.165569); + GLOW_ADD(vec2(-2.0, 0.0), 0.140367); + GLOW_ADD(vec2(-3.0, 0.0), 0.106595); + color *= blur.glow_strength; + frag_color = color; + } else { + vec2 pix_size = blur.pixel_size; + vec4 color = texture(source_color, uv_interp + vec2(0.0, 0.0) * pix_size) * 0.288713; + GLOW_ADD(vec2(0.0, 1.0), 0.233062); + GLOW_ADD(vec2(0.0, 2.0), 0.122581); + GLOW_ADD(vec2(0.0, -1.0), 0.233062); + GLOW_ADD(vec2(0.0, -2.0), 0.122581); + color *= blur.glow_strength; + frag_color = color; + } + +#undef GLOW_ADD + + if (bool(blur.flags & FLAG_GLOW_FIRST_PASS)) { +#ifdef GLOW_USE_AUTO_EXPOSURE + + frag_color /= texelFetch(source_auto_exposure, ivec2(0, 0), 0).r / blur.glow_auto_exposure_grey; +#endif + frag_color *= blur.glow_exposure; + + float luminance = max(frag_color.r, max(frag_color.g, frag_color.b)); + float feedback = max(smoothstep(blur.glow_hdr_threshold, blur.glow_hdr_threshold + blur.glow_hdr_scale, luminance), blur.glow_bloom); + + frag_color = min(frag_color * feedback, vec4(blur.glow_luminance_cap)); + } + +#endif + +#ifdef MODE_DOF_BLUR + + vec4 color_accum = vec4(0.0); + + float depth = texture(dof_source_depth, uv_interp, 0.0).r; + depth = depth * 2.0 - 1.0; + + if (bool(blur.flags & FLAG_USE_ORTHOGONAL_PROJECTION)) { + depth = ((depth + (blur.camera_z_far + blur.camera_z_near) / (blur.camera_z_far - blur.camera_z_near)) * (blur.camera_z_far - blur.camera_z_near)) / 2.0; + } else { + depth = 2.0 * blur.camera_z_near * blur.camera_z_far / (blur.camera_z_far + blur.camera_z_near - depth * (blur.camera_z_far - blur.camera_z_near)); + } + + // mix near and far blur amount + float amount = 1.0; + if (bool(blur.flags & FLAG_DOF_FAR)) { + amount *= 1.0 - smoothstep(blur.dof_far_begin, blur.dof_far_end, depth); + } + if (bool(blur.flags & FLAG_DOF_NEAR)) { + amount *= smoothstep(blur.dof_near_end, blur.dof_near_begin, depth); + } + amount = 1.0 - amount; + + if (amount > 0.0) { + float k_accum = 0.0; + + for (int i = 0; i < dof_kernel_size; i++) { + int int_ofs = i - dof_kernel_from; + vec2 tap_uv = uv_interp + blur.dof_dir * float(int_ofs) * amount * blur.dof_radius; + + float tap_k = dof_kernel[i]; + + float tap_depth = texture(dof_source_depth, tap_uv, 0.0).r; + tap_depth = tap_depth * 2.0 - 1.0; + + if (bool(blur.flags & FLAG_USE_ORTHOGONAL_PROJECTION)) { + tap_depth = ((tap_depth + (blur.camera_z_far + blur.camera_z_near) / (blur.camera_z_far - blur.camera_z_near)) * (blur.camera_z_far - blur.camera_z_near)) / 2.0; + } else { + tap_depth = 2.0 * blur.camera_z_near * blur.camera_z_far / (blur.camera_z_far + blur.camera_z_near - tap_depth * (blur.camera_z_far - blur.camera_z_near)); + } + + // mix near and far blur amount + float tap_amount = 1.0; + if (bool(blur.flags & FLAG_DOF_FAR)) { + tap_amount *= mix(1.0 - smoothstep(blur.dof_far_begin, blur.dof_far_end, tap_depth), 0.0, int_ofs == 0); + } + if (bool(blur.flags & FLAG_DOF_NEAR)) { + tap_amount *= mix(smoothstep(blur.dof_near_end, blur.dof_near_begin, tap_depth), 0.0, int_ofs == 0); + } + tap_amount = 1.0 - tap_amount; + + tap_amount *= tap_amount * tap_amount; //prevent undesired glow effect + + vec4 tap_color = texture(source_color, tap_uv, 0.0) * tap_k; + + k_accum += tap_k * tap_amount; + color_accum += tap_color * tap_amount; + } + + if (k_accum > 0.0) { + color_accum /= k_accum; + } + + frag_color = color_accum; ///k_accum; + } else { + // we are in focus, don't waste time + frag_color = texture(source_color, uv_interp, 0.0); + } + +#endif +} diff --git a/servers/rendering/renderer_rd/shaders/blur_raster_inc.glsl b/servers/rendering/renderer_rd/shaders/blur_raster_inc.glsl new file mode 100644 index 0000000000..6ea968e595 --- /dev/null +++ b/servers/rendering/renderer_rd/shaders/blur_raster_inc.glsl @@ -0,0 +1,36 @@ +#define FLAG_HORIZONTAL (1 << 0) +#define FLAG_USE_ORTHOGONAL_PROJECTION (1 << 1) +#define FLAG_GLOW_FIRST_PASS (1 << 2) +#define FLAG_DOF_FAR (1 << 3) +#define FLAG_DOF_NEAR (1 << 4) + +layout(push_constant, binding = 1, std430) uniform Blur { + vec2 pixel_size; + uint flags; + uint pad; + + // Glow. + float glow_strength; + float glow_bloom; + float glow_hdr_threshold; + float glow_hdr_scale; + + float glow_exposure; + float glow_white; + float glow_luminance_cap; + float glow_auto_exposure_grey; + + // DOF. + float dof_far_begin; + float dof_far_end; + float dof_near_begin; + float dof_near_end; + + float dof_radius; + float dof_pad[3]; + + vec2 dof_dir; + float camera_z_far; + float camera_z_near; +} +blur; diff --git a/servers/rendering/renderer_rd/shaders/luminance_reduce_raster.glsl b/servers/rendering/renderer_rd/shaders/luminance_reduce_raster.glsl new file mode 100644 index 0000000000..29ebd74a90 --- /dev/null +++ b/servers/rendering/renderer_rd/shaders/luminance_reduce_raster.glsl @@ -0,0 +1,74 @@ +/* clang-format off */ +#[vertex] + +#version 450 + +#VERSION_DEFINES + +#include "luminance_reduce_raster_inc.glsl" + +layout(location = 0) out vec2 uv_interp; +/* clang-format on */ + +void main() { + vec2 base_arr[4] = vec2[](vec2(0.0, 0.0), vec2(0.0, 1.0), vec2(1.0, 1.0), vec2(1.0, 0.0)); + uv_interp = base_arr[gl_VertexIndex]; + + gl_Position = vec4(uv_interp * 2.0 - 1.0, 0.0, 1.0); +} + +/* clang-format off */ +#[fragment] + +#version 450 + +#VERSION_DEFINES + +#include "luminance_reduce_raster_inc.glsl" + +layout(location = 0) in vec2 uv_interp; +/* clang-format on */ + +layout(set = 0, binding = 0) uniform sampler2D source_exposure; + +#ifdef FINAL_PASS +layout(set = 1, binding = 0) uniform sampler2D prev_luminance; +#endif + +layout(location = 0) out highp float luminance; + +void main() { + ivec2 dest_pos = ivec2(uv_interp * settings.dest_size); + ivec2 src_pos = ivec2(uv_interp * settings.source_size); + + ivec2 next_pos = (dest_pos + ivec2(1)) * settings.source_size / settings.dest_size; + next_pos = max(next_pos, src_pos + ivec2(1)); //so it at least reads one pixel + + highp vec3 source_color = vec3(0.0); + for (int i = src_pos.x; i < next_pos.x; i++) { + for (int j = src_pos.y; j < next_pos.y; j++) { + source_color += texelFetch(source_exposure, ivec2(i, j), 0).rgb; + } + } + + source_color /= float((next_pos.x - src_pos.x) * (next_pos.y - src_pos.y)); + +#ifdef FIRST_PASS + luminance = max(source_color.r, max(source_color.g, source_color.b)); + + // This formula should be more "accurate" but gave an overexposed result when testing. + // Leaving it here so we can revisit it if we want. + // luminance = source_color.r * 0.21 + source_color.g * 0.71 + source_color.b * 0.07; +#else + luminance = source_color.r; +#endif + +#ifdef FINAL_PASS + // Obtain our target luminance + luminance = clamp(luminance, settings.min_luminance, settings.max_luminance); + + // Now smooth to our transition + highp float prev_lum = texelFetch(prev_luminance, ivec2(0, 0), 0).r; //1 pixel previous luminance + luminance = prev_lum + (luminance - prev_lum) * clamp(settings.exposure_adjust, 0.0, 1.0); +#endif +} diff --git a/servers/rendering/renderer_rd/shaders/luminance_reduce_raster_inc.glsl b/servers/rendering/renderer_rd/shaders/luminance_reduce_raster_inc.glsl new file mode 100644 index 0000000000..ed389ffe56 --- /dev/null +++ b/servers/rendering/renderer_rd/shaders/luminance_reduce_raster_inc.glsl @@ -0,0 +1,11 @@ + +layout(push_constant, binding = 1, std430) uniform PushConstant { + ivec2 source_size; + ivec2 dest_size; + + float exposure_adjust; + float min_luminance; + float max_luminance; + float pad; +} +settings; diff --git a/servers/rendering/renderer_rd/shaders/particles_copy.glsl b/servers/rendering/renderer_rd/shaders/particles_copy.glsl index 4dceeea995..e88e68b511 100644 --- a/servers/rendering/renderer_rd/shaders/particles_copy.glsl +++ b/servers/rendering/renderer_rd/shaders/particles_copy.glsl @@ -138,7 +138,7 @@ void main() { if (bool(particles.data[particle].flags & PARTICLE_FLAG_ACTIVE) || bool(particles.data[particle].flags & PARTICLE_FLAG_TRAILED)) { txform = particles.data[particle].xform; if (params.trail_size > 1) { - // since the steps dont fit precisely in the history frames, must do a tiny bit of + // Since the steps don't fit precisely in the history frames, must do a tiny bit of // interpolation to get them close to their intended location. uint part_ofs = particle % params.trail_size; float natural_ofs = fract((float(part_ofs) / float(params.trail_size)) * float(params.trail_total)) * params.frame_delta; diff --git a/servers/rendering/renderer_rd/shaders/scene_forward_clustered.glsl b/servers/rendering/renderer_rd/shaders/scene_forward_clustered.glsl index 763c3895a9..b3a349c948 100644 --- a/servers/rendering/renderer_rd/shaders/scene_forward_clustered.glsl +++ b/servers/rendering/renderer_rd/shaders/scene_forward_clustered.glsl @@ -356,13 +356,24 @@ void main() { #VERSION_DEFINES -/* Specialization Constants */ +/* Specialization Constants (Toggles) */ layout(constant_id = 0) const bool sc_use_forward_gi = false; layout(constant_id = 1) const bool sc_use_light_projector = false; layout(constant_id = 2) const bool sc_use_light_soft_shadows = false; layout(constant_id = 3) const bool sc_use_directional_soft_shadows = false; +/* Specialization Constants (Values) */ + +layout(constant_id = 6) const uint sc_soft_shadow_samples = 4; +layout(constant_id = 7) const uint sc_penumbra_shadow_samples = 4; + +layout(constant_id = 8) const uint sc_directional_soft_shadow_samples = 4; +layout(constant_id = 9) const uint sc_directional_penumbra_shadow_samples = 4; + +layout(constant_id = 10) const bool sc_decal_use_mipmaps = true; +layout(constant_id = 11) const bool sc_projector_use_mipmaps = true; + #include "scene_forward_clustered_inc.glsl" /* Varyings */ @@ -796,25 +807,35 @@ void main() { continue; //out of decal } - //we need ddx/ddy for mipmaps, so simulate them - vec2 ddx = (decals.data[decal_index].xform * vec4(vertex_ddx, 0.0)).xz; - vec2 ddy = (decals.data[decal_index].xform * vec4(vertex_ddy, 0.0)).xz; - float fade = pow(1.0 - (uv_local.y > 0.0 ? uv_local.y : -uv_local.y), uv_local.y > 0.0 ? decals.data[decal_index].upper_fade : decals.data[decal_index].lower_fade); if (decals.data[decal_index].normal_fade > 0.0) { fade *= smoothstep(decals.data[decal_index].normal_fade, 1.0, dot(normal_interp, decals.data[decal_index].normal) * 0.5 + 0.5); } + //we need ddx/ddy for mipmaps, so simulate them + vec2 ddx = (decals.data[decal_index].xform * vec4(vertex_ddx, 0.0)).xz; + vec2 ddy = (decals.data[decal_index].xform * vec4(vertex_ddy, 0.0)).xz; + if (decals.data[decal_index].albedo_rect != vec4(0.0)) { //has albedo - vec4 decal_albedo = textureGrad(sampler2D(decal_atlas_srgb, material_samplers[SAMPLER_LINEAR_WITH_MIPMAPS_CLAMP]), uv_local.xz * decals.data[decal_index].albedo_rect.zw + decals.data[decal_index].albedo_rect.xy, ddx * decals.data[decal_index].albedo_rect.zw, ddy * decals.data[decal_index].albedo_rect.zw); + vec4 decal_albedo; + if (sc_decal_use_mipmaps) { + decal_albedo = textureGrad(sampler2D(decal_atlas_srgb, decal_sampler), uv_local.xz * decals.data[decal_index].albedo_rect.zw + decals.data[decal_index].albedo_rect.xy, ddx * decals.data[decal_index].albedo_rect.zw, ddy * decals.data[decal_index].albedo_rect.zw); + } else { + decal_albedo = textureLod(sampler2D(decal_atlas_srgb, decal_sampler), uv_local.xz * decals.data[decal_index].albedo_rect.zw + decals.data[decal_index].albedo_rect.xy, 0.0); + } decal_albedo *= decals.data[decal_index].modulate; decal_albedo.a *= fade; albedo = mix(albedo, decal_albedo.rgb, decal_albedo.a * decals.data[decal_index].albedo_mix); if (decals.data[decal_index].normal_rect != vec4(0.0)) { - vec3 decal_normal = textureGrad(sampler2D(decal_atlas, material_samplers[SAMPLER_LINEAR_WITH_MIPMAPS_CLAMP]), uv_local.xz * decals.data[decal_index].normal_rect.zw + decals.data[decal_index].normal_rect.xy, ddx * decals.data[decal_index].normal_rect.zw, ddy * decals.data[decal_index].normal_rect.zw).xyz; + vec3 decal_normal; + if (sc_decal_use_mipmaps) { + decal_normal = textureGrad(sampler2D(decal_atlas, decal_sampler), uv_local.xz * decals.data[decal_index].normal_rect.zw + decals.data[decal_index].normal_rect.xy, ddx * decals.data[decal_index].normal_rect.zw, ddy * decals.data[decal_index].normal_rect.zw).xyz; + } else { + decal_normal = textureLod(sampler2D(decal_atlas, decal_sampler), uv_local.xz * decals.data[decal_index].normal_rect.zw + decals.data[decal_index].normal_rect.xy, 0.0).xyz; + } decal_normal.xy = decal_normal.xy * vec2(2.0, -2.0) - vec2(1.0, -1.0); //users prefer flipped y normal maps in most authoring software decal_normal.z = sqrt(max(0.0, 1.0 - dot(decal_normal.xy, decal_normal.xy))); //convert to view space, use xzy because y is up @@ -824,7 +845,12 @@ void main() { } if (decals.data[decal_index].orm_rect != vec4(0.0)) { - vec3 decal_orm = textureGrad(sampler2D(decal_atlas, material_samplers[SAMPLER_LINEAR_WITH_MIPMAPS_CLAMP]), uv_local.xz * decals.data[decal_index].orm_rect.zw + decals.data[decal_index].orm_rect.xy, ddx * decals.data[decal_index].orm_rect.zw, ddy * decals.data[decal_index].orm_rect.zw).xyz; + vec3 decal_orm; + if (sc_decal_use_mipmaps) { + decal_orm = textureGrad(sampler2D(decal_atlas, decal_sampler), uv_local.xz * decals.data[decal_index].orm_rect.zw + decals.data[decal_index].orm_rect.xy, ddx * decals.data[decal_index].orm_rect.zw, ddy * decals.data[decal_index].orm_rect.zw).xyz; + } else { + decal_orm = textureLod(sampler2D(decal_atlas, decal_sampler), uv_local.xz * decals.data[decal_index].orm_rect.zw + decals.data[decal_index].orm_rect.xy, 0.0).xyz; + } ao = mix(ao, decal_orm.r, decal_albedo.a); roughness = mix(roughness, decal_orm.g, decal_albedo.a); metallic = mix(metallic, decal_orm.b, decal_albedo.a); @@ -833,7 +859,11 @@ void main() { if (decals.data[decal_index].emission_rect != vec4(0.0)) { //emission is additive, so its independent from albedo - emission += textureGrad(sampler2D(decal_atlas_srgb, material_samplers[SAMPLER_LINEAR_WITH_MIPMAPS_CLAMP]), uv_local.xz * decals.data[decal_index].emission_rect.zw + decals.data[decal_index].emission_rect.xy, ddx * decals.data[decal_index].emission_rect.zw, ddy * decals.data[decal_index].emission_rect.zw).xyz * decals.data[decal_index].emission_energy * fade; + if (sc_decal_use_mipmaps) { + emission += textureGrad(sampler2D(decal_atlas_srgb, decal_sampler), uv_local.xz * decals.data[decal_index].emission_rect.zw + decals.data[decal_index].emission_rect.xy, ddx * decals.data[decal_index].emission_rect.zw, ddy * decals.data[decal_index].emission_rect.zw).xyz * decals.data[decal_index].emission_energy * fade; + } else { + emission += textureLod(sampler2D(decal_atlas_srgb, decal_sampler), uv_local.xz * decals.data[decal_index].emission_rect.zw + decals.data[decal_index].emission_rect.xy, 0.0).xyz * decals.data[decal_index].emission_energy * fade; + } } } } @@ -1184,7 +1214,7 @@ void main() { specular_light *= specular * metallic * albedo * 2.0; #else - // scales the specular reflections, needs to be be computed before lighting happens, + // scales the specular reflections, needs to be computed before lighting happens, // but after environment, GI, and reflection probes are added // Environment brdf approximation (Lazarov 2013) // see https://www.unrealengine.com/en-US/blog/physically-based-shading-on-mobile diff --git a/servers/rendering/renderer_rd/shaders/scene_forward_clustered_inc.glsl b/servers/rendering/renderer_rd/shaders/scene_forward_clustered_inc.glsl index 6599a42bab..b53bf6a6d4 100644 --- a/servers/rendering/renderer_rd/shaders/scene_forward_clustered_inc.glsl +++ b/servers/rendering/renderer_rd/shaders/scene_forward_clustered_inc.glsl @@ -52,6 +52,10 @@ layout(set = 0, binding = 1) uniform sampler material_samplers[12]; layout(set = 0, binding = 2) uniform sampler shadow_sampler; +layout(set = 0, binding = 3) uniform sampler decal_sampler; + +layout(set = 0, binding = 4) uniform sampler light_projector_sampler; + #define INSTANCE_FLAGS_NON_UNIFORM_SCALE (1 << 5) #define INSTANCE_FLAGS_USE_GI_BUFFERS (1 << 6) #define INSTANCE_FLAGS_USE_SDFGI (1 << 7) @@ -67,22 +71,22 @@ layout(set = 0, binding = 2) uniform sampler shadow_sampler; //3 bits of stride #define INSTANCE_FLAGS_PARTICLE_TRAIL_MASK 0xFF -layout(set = 0, binding = 3, std430) restrict readonly buffer OmniLights { +layout(set = 0, binding = 5, std430) restrict readonly buffer OmniLights { LightData data[]; } omni_lights; -layout(set = 0, binding = 4, std430) restrict readonly buffer SpotLights { +layout(set = 0, binding = 6, std430) restrict readonly buffer SpotLights { LightData data[]; } spot_lights; -layout(set = 0, binding = 5, std430) restrict readonly buffer ReflectionProbeData { +layout(set = 0, binding = 7, std430) restrict readonly buffer ReflectionProbeData { ReflectionData data[]; } reflections; -layout(set = 0, binding = 6, std140) uniform DirectionalLights { +layout(set = 0, binding = 8, std140) uniform DirectionalLights { DirectionalLightData data[MAX_DIRECTIONAL_LIGHT_DATA_STRUCTS]; } directional_lights; @@ -94,7 +98,7 @@ struct Lightmap { mat3 normal_xform; }; -layout(set = 0, binding = 7, std140) restrict readonly buffer Lightmaps { +layout(set = 0, binding = 9, std140) restrict readonly buffer Lightmaps { Lightmap data[]; } lightmaps; @@ -103,20 +107,20 @@ struct LightmapCapture { vec4 sh[9]; }; -layout(set = 0, binding = 8, std140) restrict readonly buffer LightmapCaptures { +layout(set = 0, binding = 10, std140) restrict readonly buffer LightmapCaptures { LightmapCapture data[]; } lightmap_captures; -layout(set = 0, binding = 9) uniform texture2D decal_atlas; -layout(set = 0, binding = 10) uniform texture2D decal_atlas_srgb; +layout(set = 0, binding = 11) uniform texture2D decal_atlas; +layout(set = 0, binding = 12) uniform texture2D decal_atlas_srgb; -layout(set = 0, binding = 11, std430) restrict readonly buffer Decals { +layout(set = 0, binding = 13, std430) restrict readonly buffer Decals { DecalData data[]; } decals; -layout(set = 0, binding = 12, std430) restrict readonly buffer GlobalVariableData { +layout(set = 0, binding = 14, std430) restrict readonly buffer GlobalVariableData { vec4 data[]; } global_variables; @@ -128,7 +132,7 @@ struct SDFVoxelGICascadeData { float to_cell; // 1/bounds * grid_size }; -layout(set = 0, binding = 13, std140) uniform SDFGI { +layout(set = 0, binding = 15, std140) uniform SDFGI { vec3 grid_size; uint max_cascades; @@ -173,17 +177,12 @@ layout(set = 1, binding = 0, std140) uniform SceneData { uint cluster_type_size; uint max_cluster_element_count_div_32; - //use vec4s because std140 doesnt play nice with vec2s, z and w are wasted + // Use vec4s because std140 doesn't play nice with vec2s, z and w are wasted. vec4 directional_penumbra_shadow_kernel[32]; vec4 directional_soft_shadow_kernel[32]; vec4 penumbra_shadow_kernel[32]; vec4 soft_shadow_kernel[32]; - uint directional_penumbra_shadow_samples; - uint directional_soft_shadow_samples; - uint penumbra_shadow_samples; - uint soft_shadow_samples; - vec4 ambient_light_color_energy; float ambient_color_sky_mix; diff --git a/servers/rendering/renderer_rd/shaders/scene_forward_lights_inc.glsl b/servers/rendering/renderer_rd/shaders/scene_forward_lights_inc.glsl index 79790b1bfe..7039ea2942 100644 --- a/servers/rendering/renderer_rd/shaders/scene_forward_lights_inc.glsl +++ b/servers/rendering/renderer_rd/shaders/scene_forward_lights_inc.glsl @@ -301,7 +301,7 @@ float sample_directional_pcf_shadow(texture2D shadow, vec2 shadow_pixel_size, ve float depth = coord.z; //if only one sample is taken, take it from the center - if (scene_data.directional_soft_shadow_samples == 1) { + if (sc_directional_soft_shadow_samples == 1) { return textureProj(sampler2DShadow(shadow, shadow_sampler), vec4(pos, depth, 1.0)); } @@ -315,11 +315,11 @@ float sample_directional_pcf_shadow(texture2D shadow, vec2 shadow_pixel_size, ve float avg = 0.0; - for (uint i = 0; i < scene_data.directional_soft_shadow_samples; i++) { + for (uint i = 0; i < sc_directional_soft_shadow_samples; i++) { avg += textureProj(sampler2DShadow(shadow, shadow_sampler), vec4(pos + shadow_pixel_size * (disk_rotation * scene_data.directional_soft_shadow_kernel[i].xy), depth, 1.0)); } - return avg * (1.0 / float(scene_data.directional_soft_shadow_samples)); + return avg * (1.0 / float(sc_directional_soft_shadow_samples)); } float sample_pcf_shadow(texture2D shadow, vec2 shadow_pixel_size, vec4 coord) { @@ -327,7 +327,7 @@ float sample_pcf_shadow(texture2D shadow, vec2 shadow_pixel_size, vec4 coord) { float depth = coord.z; //if only one sample is taken, take it from the center - if (scene_data.soft_shadow_samples == 1) { + if (sc_soft_shadow_samples == 1) { return textureProj(sampler2DShadow(shadow, shadow_sampler), vec4(pos, depth, 1.0)); } @@ -341,11 +341,11 @@ float sample_pcf_shadow(texture2D shadow, vec2 shadow_pixel_size, vec4 coord) { float avg = 0.0; - for (uint i = 0; i < scene_data.soft_shadow_samples; i++) { + for (uint i = 0; i < sc_soft_shadow_samples; i++) { avg += textureProj(sampler2DShadow(shadow, shadow_sampler), vec4(pos + shadow_pixel_size * (disk_rotation * scene_data.soft_shadow_kernel[i].xy), depth, 1.0)); } - return avg * (1.0 / float(scene_data.soft_shadow_samples)); + return avg * (1.0 / float(sc_soft_shadow_samples)); } float sample_directional_soft_shadow(texture2D shadow, vec3 pssm_coord, vec2 tex_scale) { @@ -361,7 +361,7 @@ float sample_directional_soft_shadow(texture2D shadow, vec3 pssm_coord, vec2 tex disk_rotation = mat2(vec2(cr, -sr), vec2(sr, cr)); } - for (uint i = 0; i < scene_data.directional_penumbra_shadow_samples; i++) { + for (uint i = 0; i < sc_directional_penumbra_shadow_samples; i++) { vec2 suv = pssm_coord.xy + (disk_rotation * scene_data.directional_penumbra_shadow_kernel[i].xy) * tex_scale; float d = textureLod(sampler2D(shadow, material_samplers[SAMPLER_LINEAR_CLAMP]), suv, 0.0).r; if (d < pssm_coord.z) { @@ -377,12 +377,12 @@ float sample_directional_soft_shadow(texture2D shadow, vec3 pssm_coord, vec2 tex tex_scale *= penumbra; float s = 0.0; - for (uint i = 0; i < scene_data.directional_penumbra_shadow_samples; i++) { + for (uint i = 0; i < sc_directional_penumbra_shadow_samples; i++) { vec2 suv = pssm_coord.xy + (disk_rotation * scene_data.directional_penumbra_shadow_kernel[i].xy) * tex_scale; s += textureProj(sampler2DShadow(shadow, shadow_sampler), vec4(suv, pssm_coord.z, 1.0)); } - return s / float(scene_data.directional_penumbra_shadow_samples); + return s / float(sc_directional_penumbra_shadow_samples); } else { //no blockers found, so no shadow @@ -448,7 +448,7 @@ float light_process_omni_shadow(uint idx, vec3 vertex, vec3 normal) { tangent *= omni_lights.data[idx].soft_shadow_size * omni_lights.data[idx].soft_shadow_scale; bitangent *= omni_lights.data[idx].soft_shadow_size * omni_lights.data[idx].soft_shadow_scale; - for (uint i = 0; i < scene_data.penumbra_shadow_samples; i++) { + for (uint i = 0; i < sc_penumbra_shadow_samples; i++) { vec2 disk = disk_rotation * scene_data.penumbra_shadow_kernel[i].xy; vec3 pos = splane.xyz + tangent * disk.x + bitangent * disk.y; @@ -485,7 +485,7 @@ float light_process_omni_shadow(uint idx, vec3 vertex, vec3 normal) { z_norm -= omni_lights.data[idx].inv_radius * omni_lights.data[idx].shadow_bias; shadow = 0.0; - for (uint i = 0; i < scene_data.penumbra_shadow_samples; i++) { + for (uint i = 0; i < sc_penumbra_shadow_samples; i++) { vec2 disk = disk_rotation * scene_data.penumbra_shadow_kernel[i].xy; vec3 pos = splane.xyz + tangent * disk.x + bitangent * disk.y; @@ -506,7 +506,7 @@ float light_process_omni_shadow(uint idx, vec3 vertex, vec3 normal) { shadow += textureProj(sampler2DShadow(shadow_atlas, shadow_sampler), vec4(pos.xy, z_norm, 1.0)); } - shadow /= float(scene_data.penumbra_shadow_samples); + shadow /= float(sc_penumbra_shadow_samples); } else { //no blockers found, so no shadow @@ -626,40 +626,45 @@ void light_process_omni(uint idx, vec3 vertex, vec3 eye_vec, vec3 normal, vec3 v local_v.xy = local_v.xy * 0.5 + 0.5; vec2 proj_uv = local_v.xy * atlas_rect.zw; - vec2 proj_uv_ddx; - vec2 proj_uv_ddy; - { - vec3 local_v_ddx = (omni_lights.data[idx].shadow_matrix * vec4(vertex + vertex_ddx, 1.0)).xyz; - local_v_ddx = normalize(local_v_ddx); + if (sc_projector_use_mipmaps) { + vec2 proj_uv_ddx; + vec2 proj_uv_ddy; + { + vec3 local_v_ddx = (omni_lights.data[idx].shadow_matrix * vec4(vertex + vertex_ddx, 1.0)).xyz; + local_v_ddx = normalize(local_v_ddx); - if (local_v_ddx.z >= 0.0) { - local_v_ddx.z += 1.0; - } else { - local_v_ddx.z = 1.0 - local_v_ddx.z; - } + if (local_v_ddx.z >= 0.0) { + local_v_ddx.z += 1.0; + } else { + local_v_ddx.z = 1.0 - local_v_ddx.z; + } - local_v_ddx.xy /= local_v_ddx.z; - local_v_ddx.xy = local_v_ddx.xy * 0.5 + 0.5; + local_v_ddx.xy /= local_v_ddx.z; + local_v_ddx.xy = local_v_ddx.xy * 0.5 + 0.5; - proj_uv_ddx = local_v_ddx.xy * atlas_rect.zw - proj_uv; + proj_uv_ddx = local_v_ddx.xy * atlas_rect.zw - proj_uv; - vec3 local_v_ddy = (omni_lights.data[idx].shadow_matrix * vec4(vertex + vertex_ddy, 1.0)).xyz; - local_v_ddy = normalize(local_v_ddy); + vec3 local_v_ddy = (omni_lights.data[idx].shadow_matrix * vec4(vertex + vertex_ddy, 1.0)).xyz; + local_v_ddy = normalize(local_v_ddy); - if (local_v_ddy.z >= 0.0) { - local_v_ddy.z += 1.0; - } else { - local_v_ddy.z = 1.0 - local_v_ddy.z; - } + if (local_v_ddy.z >= 0.0) { + local_v_ddy.z += 1.0; + } else { + local_v_ddy.z = 1.0 - local_v_ddy.z; + } - local_v_ddy.xy /= local_v_ddy.z; - local_v_ddy.xy = local_v_ddy.xy * 0.5 + 0.5; + local_v_ddy.xy /= local_v_ddy.z; + local_v_ddy.xy = local_v_ddy.xy * 0.5 + 0.5; - proj_uv_ddy = local_v_ddy.xy * atlas_rect.zw - proj_uv; - } + proj_uv_ddy = local_v_ddy.xy * atlas_rect.zw - proj_uv; + } - vec4 proj = textureGrad(sampler2D(decal_atlas_srgb, material_samplers[SAMPLER_LINEAR_WITH_MIPMAPS_CLAMP]), proj_uv + atlas_rect.xy, proj_uv_ddx, proj_uv_ddy); - color *= proj.rgb * proj.a; + vec4 proj = textureGrad(sampler2D(decal_atlas_srgb, light_projector_sampler), proj_uv + atlas_rect.xy, proj_uv_ddx, proj_uv_ddy); + color *= proj.rgb * proj.a; + } else { + vec4 proj = textureLod(sampler2D(decal_atlas_srgb, light_projector_sampler), proj_uv + atlas_rect.xy, 0.0); + color *= proj.rgb * proj.a; + } } light_attenuation *= shadow; @@ -736,7 +741,7 @@ float light_process_spot_shadow(uint idx, vec3 vertex, vec3 normal) { float uv_size = spot_lights.data[idx].soft_shadow_size * z_norm * spot_lights.data[idx].soft_shadow_scale; vec2 clamp_max = spot_lights.data[idx].atlas_rect.xy + spot_lights.data[idx].atlas_rect.zw; - for (uint i = 0; i < scene_data.penumbra_shadow_samples; i++) { + for (uint i = 0; i < sc_penumbra_shadow_samples; i++) { vec2 suv = shadow_uv + (disk_rotation * scene_data.penumbra_shadow_kernel[i].xy) * uv_size; suv = clamp(suv, spot_lights.data[idx].atlas_rect.xy, clamp_max); float d = textureLod(sampler2D(shadow_atlas, material_samplers[SAMPLER_LINEAR_CLAMP]), suv, 0.0).r; @@ -753,13 +758,13 @@ float light_process_spot_shadow(uint idx, vec3 vertex, vec3 normal) { uv_size *= penumbra; shadow = 0.0; - for (uint i = 0; i < scene_data.penumbra_shadow_samples; i++) { + for (uint i = 0; i < sc_penumbra_shadow_samples; i++) { vec2 suv = shadow_uv + (disk_rotation * scene_data.penumbra_shadow_kernel[i].xy) * uv_size; suv = clamp(suv, spot_lights.data[idx].atlas_rect.xy, clamp_max); shadow += textureProj(sampler2DShadow(shadow_atlas, shadow_sampler), vec4(suv, splane.z, 1.0)); } - shadow /= float(scene_data.penumbra_shadow_samples); + shadow /= float(sc_penumbra_shadow_samples); } else { //no blockers found, so no shadow @@ -861,17 +866,22 @@ void light_process_spot(uint idx, vec3 vertex, vec3 eye_vec, vec3 normal, vec3 v vec2 proj_uv = normal_to_panorama(splane.xyz) * spot_lights.data[idx].projector_rect.zw; - //ensure we have proper mipmaps - vec4 splane_ddx = (spot_lights.data[idx].shadow_matrix * vec4(vertex + vertex_ddx, 1.0)); - splane_ddx /= splane_ddx.w; - vec2 proj_uv_ddx = normal_to_panorama(splane_ddx.xyz) * spot_lights.data[idx].projector_rect.zw - proj_uv; + if (sc_projector_use_mipmaps) { + //ensure we have proper mipmaps + vec4 splane_ddx = (spot_lights.data[idx].shadow_matrix * vec4(vertex + vertex_ddx, 1.0)); + splane_ddx /= splane_ddx.w; + vec2 proj_uv_ddx = normal_to_panorama(splane_ddx.xyz) * spot_lights.data[idx].projector_rect.zw - proj_uv; - vec4 splane_ddy = (spot_lights.data[idx].shadow_matrix * vec4(vertex + vertex_ddy, 1.0)); - splane_ddy /= splane_ddy.w; - vec2 proj_uv_ddy = normal_to_panorama(splane_ddy.xyz) * spot_lights.data[idx].projector_rect.zw - proj_uv; + vec4 splane_ddy = (spot_lights.data[idx].shadow_matrix * vec4(vertex + vertex_ddy, 1.0)); + splane_ddy /= splane_ddy.w; + vec2 proj_uv_ddy = normal_to_panorama(splane_ddy.xyz) * spot_lights.data[idx].projector_rect.zw - proj_uv; - vec4 proj = textureGrad(sampler2D(decal_atlas_srgb, material_samplers[SAMPLER_LINEAR_WITH_MIPMAPS_CLAMP]), proj_uv + spot_lights.data[idx].projector_rect.xy, proj_uv_ddx, proj_uv_ddy); - color *= proj.rgb * proj.a; + vec4 proj = textureGrad(sampler2D(decal_atlas_srgb, light_projector_sampler), proj_uv + spot_lights.data[idx].projector_rect.xy, proj_uv_ddx, proj_uv_ddy); + color *= proj.rgb * proj.a; + } else { + vec4 proj = textureLod(sampler2D(decal_atlas_srgb, light_projector_sampler), proj_uv + spot_lights.data[idx].projector_rect.xy, 0.0); + color *= proj.rgb * proj.a; + } } light_attenuation *= shadow; diff --git a/servers/rendering/renderer_rd/shaders/scene_forward_mobile.glsl b/servers/rendering/renderer_rd/shaders/scene_forward_mobile.glsl index c28493d9e3..70900a847c 100644 --- a/servers/rendering/renderer_rd/shaders/scene_forward_mobile.glsl +++ b/servers/rendering/renderer_rd/shaders/scene_forward_mobile.glsl @@ -372,10 +372,23 @@ void main() { /* Specialization Constants */ -//unused but there for compatibility +/* Specialization Constants (Toggles) */ + layout(constant_id = 0) const bool sc_use_forward_gi = false; layout(constant_id = 1) const bool sc_use_light_projector = false; layout(constant_id = 2) const bool sc_use_light_soft_shadows = false; +layout(constant_id = 3) const bool sc_use_directional_soft_shadows = false; + +/* Specialization Constants (Values) */ + +layout(constant_id = 6) const uint sc_soft_shadow_samples = 4; +layout(constant_id = 7) const uint sc_penumbra_shadow_samples = 4; + +layout(constant_id = 8) const uint sc_directional_soft_shadow_samples = 4; +layout(constant_id = 9) const uint sc_directional_penumbra_shadow_samples = 4; + +layout(constant_id = 10) const bool sc_decal_use_mipmaps = true; +layout(constant_id = 11) const bool sc_projector_use_mipmaps = true; /* Include our forward mobile UBOs definitions etc. */ #include "scene_forward_mobile_inc.glsl" @@ -968,7 +981,7 @@ void main() { specular_light *= specular * metallic * albedo * 2.0; #else - // scales the specular reflections, needs to be be computed before lighting happens, + // scales the specular reflections, needs to be computed before lighting happens, // but after environment, GI, and reflection probes are added // Environment brdf approximation (Lazarov 2013) // see https://www.unrealengine.com/en-US/blog/physically-based-shading-on-mobile diff --git a/servers/rendering/renderer_rd/shaders/scene_forward_mobile_inc.glsl b/servers/rendering/renderer_rd/shaders/scene_forward_mobile_inc.glsl index d4ebcbeec4..d9682d7b23 100644 --- a/servers/rendering/renderer_rd/shaders/scene_forward_mobile_inc.glsl +++ b/servers/rendering/renderer_rd/shaders/scene_forward_mobile_inc.glsl @@ -51,6 +51,9 @@ layout(set = 0, binding = 1) uniform sampler material_samplers[12]; layout(set = 0, binding = 2) uniform sampler shadow_sampler; +layout(set = 0, binding = 3) uniform sampler decal_sampler; +layout(set = 0, binding = 4) uniform sampler light_projector_sampler; + #define INSTANCE_FLAGS_NON_UNIFORM_SCALE (1 << 5) #define INSTANCE_FLAGS_USE_GI_BUFFERS (1 << 6) #define INSTANCE_FLAGS_USE_SDFGI (1 << 7) @@ -66,22 +69,22 @@ layout(set = 0, binding = 2) uniform sampler shadow_sampler; //3 bits of stride #define INSTANCE_FLAGS_PARTICLE_TRAIL_MASK 0xFF -layout(set = 0, binding = 3, std430) restrict readonly buffer OmniLights { +layout(set = 0, binding = 5, std430) restrict readonly buffer OmniLights { LightData data[]; } omni_lights; -layout(set = 0, binding = 4, std430) restrict readonly buffer SpotLights { +layout(set = 0, binding = 6, std430) restrict readonly buffer SpotLights { LightData data[]; } spot_lights; -layout(set = 0, binding = 5, std430) restrict readonly buffer ReflectionProbeData { +layout(set = 0, binding = 7, std430) restrict readonly buffer ReflectionProbeData { ReflectionData data[]; } reflections; -layout(set = 0, binding = 6, std140) uniform DirectionalLights { +layout(set = 0, binding = 8, std140) uniform DirectionalLights { DirectionalLightData data[MAX_DIRECTIONAL_LIGHT_DATA_STRUCTS]; } directional_lights; @@ -93,7 +96,7 @@ struct Lightmap { mat3 normal_xform; }; -layout(set = 0, binding = 7, std140) restrict readonly buffer Lightmaps { +layout(set = 0, binding = 9, std140) restrict readonly buffer Lightmaps { Lightmap data[]; } lightmaps; @@ -102,20 +105,20 @@ struct LightmapCapture { vec4 sh[9]; }; -layout(set = 0, binding = 8, std140) restrict readonly buffer LightmapCaptures { +layout(set = 0, binding = 10, std140) restrict readonly buffer LightmapCaptures { LightmapCapture data[]; } lightmap_captures; -layout(set = 0, binding = 9) uniform texture2D decal_atlas; -layout(set = 0, binding = 10) uniform texture2D decal_atlas_srgb; +layout(set = 0, binding = 11) uniform texture2D decal_atlas; +layout(set = 0, binding = 12) uniform texture2D decal_atlas_srgb; -layout(set = 0, binding = 11, std430) restrict readonly buffer Decals { +layout(set = 0, binding = 13, std430) restrict readonly buffer Decals { DecalData data[]; } decals; -layout(set = 0, binding = 12, std430) restrict readonly buffer GlobalVariableData { +layout(set = 0, binding = 14, std430) restrict readonly buffer GlobalVariableData { vec4 data[]; } global_variables; @@ -135,17 +138,12 @@ layout(set = 1, binding = 0, std140) uniform SceneData { vec2 viewport_size; vec2 screen_pixel_size; - //use vec4s because std140 doesnt play nice with vec2s, z and w are wasted + // Use vec4s because std140 doesn't play nice with vec2s, z and w are wasted. vec4 directional_penumbra_shadow_kernel[32]; vec4 directional_soft_shadow_kernel[32]; vec4 penumbra_shadow_kernel[32]; vec4 soft_shadow_kernel[32]; - uint directional_penumbra_shadow_samples; - uint directional_soft_shadow_samples; - uint penumbra_shadow_samples; - uint soft_shadow_samples; - vec4 ambient_light_color_energy; float ambient_color_sky_mix; diff --git a/servers/rendering/renderer_rd/shaders/sdfgi_direct_light.glsl b/servers/rendering/renderer_rd/shaders/sdfgi_direct_light.glsl index 99db35bb34..d6e5c6a92e 100644 --- a/servers/rendering/renderer_rd/shaders/sdfgi_direct_light.glsl +++ b/servers/rendering/renderer_rd/shaders/sdfgi_direct_light.glsl @@ -20,10 +20,10 @@ layout(set = 0, binding = 3, std430) restrict readonly buffer DispatchData { dispatch_data; struct ProcessVoxel { - uint position; //xyz 7 bit packed, extra 11 bits for neigbours - uint albedo; //rgb bits 0-15 albedo, bits 16-21 are normal bits (set if geometry exists toward that side), extra 11 bits for neibhbours - uint light; //rgbe8985 encoded total saved light, extra 2 bits for neighbours - uint light_aniso; //55555 light anisotropy, extra 2 bits for neighbours + uint position; // xyz 7 bit packed, extra 11 bits for neighbors. + uint albedo; // rgb bits 0-15 albedo, bits 16-21 are normal bits (set if geometry exists toward that side), extra 11 bits for neighbors. + uint light; // rgbe8985 encoded total saved light, extra 2 bits for neighbors. + uint light_aniso; // 55555 light anisotropy, extra 2 bits for neighbors. //total neighbours: 26 }; diff --git a/servers/rendering/renderer_rd/shaders/sdfgi_integrate.glsl b/servers/rendering/renderer_rd/shaders/sdfgi_integrate.glsl index bc376e9522..eedd28959c 100644 --- a/servers/rendering/renderer_rd/shaders/sdfgi_integrate.glsl +++ b/servers/rendering/renderer_rd/shaders/sdfgi_integrate.glsl @@ -266,9 +266,9 @@ void main() { } else if (params.sky_mode == SKY_MODE_SKY) { #ifdef USE_CUBEMAP_ARRAY - light.rgb = textureLod(samplerCubeArray(sky_irradiance, linear_sampler_mipmaps), vec4(ray_dir, 0.0), 2.0).rgb; //use second mipmap because we dont usually throw a lot of rays, so this compensates + light.rgb = textureLod(samplerCubeArray(sky_irradiance, linear_sampler_mipmaps), vec4(ray_dir, 0.0), 2.0).rgb; // Use second mipmap because we don't usually throw a lot of rays, so this compensates. #else - light.rgb = textureLod(samplerCube(sky_irradiance, linear_sampler_mipmaps), ray_dir, 2.0).rgb; //use second mipmap because we dont usually throw a lot of rays, so this compensates + light.rgb = textureLod(samplerCube(sky_irradiance, linear_sampler_mipmaps), ray_dir, 2.0).rgb; // Use second mipmap because we don't usually throw a lot of rays, so this compensates. #endif light.rgb *= params.sky_energy; light.a = 0.0; diff --git a/servers/rendering/renderer_rd/shaders/sdfgi_preprocess.glsl b/servers/rendering/renderer_rd/shaders/sdfgi_preprocess.glsl index aa4ded146f..4d9fa85a74 100644 --- a/servers/rendering/renderer_rd/shaders/sdfgi_preprocess.glsl +++ b/servers/rendering/renderer_rd/shaders/sdfgi_preprocess.glsl @@ -101,7 +101,7 @@ layout(set = 0, binding = 10, std430) restrict buffer DispatchData { dispatch_data; struct ProcessVoxel { - uint position; //xyz 7 bit packed, extra 11 bits for neigbours + uint position; // xyz 7 bit packed, extra 11 bits for neighbors. uint albedo; //rgb bits 0-15 albedo, bits 16-21 are normal bits (set if geometry exists toward that side), extra 11 bits for neibhbours uint light; //rgbe8985 encoded total saved light, extra 2 bits for neighbours uint light_aniso; //55555 light anisotropy, extra 2 bits for neighbours @@ -134,7 +134,7 @@ layout(set = 0, binding = 5, std430) restrict buffer readonly DispatchData { dispatch_data; struct ProcessVoxel { - uint position; //xyz 7 bit packed, extra 11 bits for neigbours + uint position; // xyz 7 bit packed, extra 11 bits for neighbors. uint albedo; //rgb bits 0-15 albedo, bits 16-21 are normal bits (set if geometry exists toward that side), extra 11 bits for neibhbours uint light; //rgbe8985 encoded total saved light, extra 2 bits for neighbours uint light_aniso; //55555 light anisotropy, extra 2 bits for neighbours @@ -183,7 +183,7 @@ void main() { ivec3 write_pos = read_pos + params.scroll; if (any(lessThan(write_pos, ivec3(0))) || any(greaterThanEqual(write_pos, ivec3(params.grid_size)))) { - return; //fits outside the 3D texture, dont do anything + return; // Fits outside the 3D texture, don't do anything. } uint albedo = ((src_process_voxels.data[index].albedo & 0x7FFF) << 1) | 1; //add solid bit diff --git a/servers/rendering/renderer_scene.h b/servers/rendering/renderer_scene.h index 8273e53d46..972637d183 100644 --- a/servers/rendering/renderer_scene.h +++ b/servers/rendering/renderer_scene.h @@ -212,6 +212,9 @@ public: virtual void render_probes() = 0; virtual void update_visibility_notifiers() = 0; + virtual void decals_set_filter(RS::DecalFilter p_filter) = 0; + virtual void light_projectors_set_filter(RS::LightProjectorFilter p_filter) = 0; + virtual bool free(RID p_rid) = 0; RendererScene(); diff --git a/servers/rendering/renderer_scene_cull.cpp b/servers/rendering/renderer_scene_cull.cpp index 3336623f21..83d1b33bf2 100644 --- a/servers/rendering/renderer_scene_cull.cpp +++ b/servers/rendering/renderer_scene_cull.cpp @@ -1259,7 +1259,7 @@ void RendererSceneCull::_update_instance_visibility_depth(Instance *p_instance) } if (cycle_detected) { - ERR_PRINT("Cycle detected in the visibility dependecies tree."); + ERR_PRINT("Cycle detected in the visibility dependencies tree."); for (Set<Instance *>::Element *E = traversed_nodes.front(); E; E = E->next()) { Instance *instance = E->get(); InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(instance->base_data); @@ -2876,8 +2876,8 @@ void RendererSceneCull::_render_scene(const RendererSceneRender::CameraData *p_c Vector<Instance *> lights_with_shadow; - for (List<Instance *>::Element *E = scenario->directional_lights.front(); E; E = E->next()) { - if (!E->get()->visible) { + for (Instance *E : scenario->directional_lights) { + if (!E->visible) { continue; } @@ -2885,13 +2885,13 @@ void RendererSceneCull::_render_scene(const RendererSceneRender::CameraData *p_c break; } - InstanceLightData *light = static_cast<InstanceLightData *>(E->get()->base_data); + InstanceLightData *light = static_cast<InstanceLightData *>(E->base_data); //check shadow.. if (light) { - if (p_using_shadows && p_shadow_atlas.is_valid() && RSG::storage->light_has_shadow(E->get()->base) && !(RSG::storage->light_get_type(E->get()->base) == RS::LIGHT_DIRECTIONAL && RSG::storage->light_directional_is_sky_only(E->get()->base))) { - lights_with_shadow.push_back(E->get()); + if (p_using_shadows && p_shadow_atlas.is_valid() && RSG::storage->light_has_shadow(E->base) && !(RSG::storage->light_get_type(E->base) == RS::LIGHT_DIRECTIONAL && RSG::storage->light_directional_is_sky_only(E->base))) { + lights_with_shadow.push_back(E); } //add to list directional_lights.push_back(light->instance); @@ -3391,8 +3391,7 @@ void RendererSceneCull::render_probes() { idx++; } - for (List<Instance *>::Element *E = probe->owner->scenario->directional_lights.front(); E; E = E->next()) { - Instance *instance = E->get(); + for (const Instance *instance : probe->owner->scenario->directional_lights) { InstanceLightData *instance_light = (InstanceLightData *)instance->base_data; if (!instance->visible) { continue; @@ -3465,8 +3464,7 @@ void RendererSceneCull::render_probes() { idx++; } - for (List<Instance *>::Element *E = probe->owner->scenario->directional_lights.front(); E; E = E->next()) { - Instance *instance = E->get(); + for (const Instance *instance : probe->owner->scenario->directional_lights) { InstanceLightData *instance_light = (InstanceLightData *)instance->base_data; if (!instance->visible) { continue; @@ -3573,26 +3571,26 @@ void RendererSceneCull::render_particle_colliders() { void RendererSceneCull::_update_instance_shader_parameters_from_material(Map<StringName, Instance::InstanceShaderParameter> &isparams, const Map<StringName, Instance::InstanceShaderParameter> &existing_isparams, RID p_material) { List<RendererStorage::InstanceShaderParam> plist; RSG::storage->material_get_instance_shader_parameters(p_material, &plist); - for (List<RendererStorage::InstanceShaderParam>::Element *E = plist.front(); E; E = E->next()) { - StringName name = E->get().info.name; + for (const RendererStorage::InstanceShaderParam &E : plist) { + StringName name = E.info.name; if (isparams.has(name)) { - if (isparams[name].info.type != E->get().info.type) { - WARN_PRINT("More than one material in instance export the same instance shader uniform '" + E->get().info.name + "', but they do it with different data types. Only the first one (in order) will display correctly."); + if (isparams[name].info.type != E.info.type) { + WARN_PRINT("More than one material in instance export the same instance shader uniform '" + E.info.name + "', but they do it with different data types. Only the first one (in order) will display correctly."); } - if (isparams[name].index != E->get().index) { - WARN_PRINT("More than one material in instance export the same instance shader uniform '" + E->get().info.name + "', but they do it with different indices. Only the first one (in order) will display correctly."); + if (isparams[name].index != E.index) { + WARN_PRINT("More than one material in instance export the same instance shader uniform '" + E.info.name + "', but they do it with different indices. Only the first one (in order) will display correctly."); } continue; //first one found always has priority } Instance::InstanceShaderParameter isp; - isp.index = E->get().index; - isp.info = E->get().info; - isp.default_value = E->get().default_value; + isp.index = E.index; + isp.info = E.info; + isp.default_value = E.default_value; if (existing_isparams.has(name)) { isp.value = existing_isparams[name].value; } else { - isp.value = E->get().default_value; + isp.value = E.default_value; } isparams[name] = isp; } diff --git a/servers/rendering/renderer_scene_cull.h b/servers/rendering/renderer_scene_cull.h index b9009c9f59..96fe6ce25c 100644 --- a/servers/rendering/renderer_scene_cull.h +++ b/servers/rendering/renderer_scene_cull.h @@ -1143,6 +1143,9 @@ public: PASS1(set_debug_draw_mode, RS::ViewportDebugDraw) + PASS1(decals_set_filter, RS::DecalFilter) + PASS1(light_projectors_set_filter, RS::LightProjectorFilter) + virtual void update(); bool free(RID p_rid); diff --git a/servers/rendering/renderer_scene_render.h b/servers/rendering/renderer_scene_render.h index 0cf34773ef..2000afa0d3 100644 --- a/servers/rendering/renderer_scene_render.h +++ b/servers/rendering/renderer_scene_render.h @@ -262,6 +262,9 @@ public: virtual void sdfgi_set_debug_probe_select(const Vector3 &p_position, const Vector3 &p_dir) = 0; + virtual void decals_set_filter(RS::DecalFilter p_filter) = 0; + virtual void light_projectors_set_filter(RS::LightProjectorFilter p_filter) = 0; + virtual void update() = 0; virtual ~RendererSceneRender() {} }; diff --git a/servers/rendering/rendering_device.cpp b/servers/rendering/rendering_device.cpp index 3594939362..b298ad193b 100644 --- a/servers/rendering/rendering_device.cpp +++ b/servers/rendering/rendering_device.cpp @@ -38,23 +38,23 @@ RenderingDevice *RenderingDevice::get_singleton() { return singleton; } -RenderingDevice::ShaderCompileFunction RenderingDevice::compile_function = nullptr; +RenderingDevice::ShaderCompileToSPIRVFunction RenderingDevice::compile_to_spirv_function = nullptr; RenderingDevice::ShaderCacheFunction RenderingDevice::cache_function = nullptr; -RenderingDevice::ShaderGetCacheKeyFunction RenderingDevice::get_cache_key_function = nullptr; +RenderingDevice::ShaderSPIRVGetCacheKeyFunction RenderingDevice::get_spirv_cache_key_function = nullptr; -void RenderingDevice::shader_set_compile_function(ShaderCompileFunction p_function) { - compile_function = p_function; +void RenderingDevice::shader_set_compile_to_spirv_function(ShaderCompileToSPIRVFunction p_function) { + compile_to_spirv_function = p_function; } -void RenderingDevice::shader_set_cache_function(ShaderCacheFunction p_function) { +void RenderingDevice::shader_set_spirv_cache_function(ShaderCacheFunction p_function) { cache_function = p_function; } -void RenderingDevice::shader_set_get_cache_key_function(ShaderGetCacheKeyFunction p_function) { - get_cache_key_function = p_function; +void RenderingDevice::shader_set_get_cache_key_function(ShaderSPIRVGetCacheKeyFunction p_function) { + get_spirv_cache_key_function = p_function; } -Vector<uint8_t> RenderingDevice::shader_compile_from_source(ShaderStage p_stage, const String &p_source_code, ShaderLanguage p_language, String *r_error, bool p_allow_cache) { +Vector<uint8_t> RenderingDevice::shader_compile_spirv_from_source(ShaderStage p_stage, const String &p_source_code, ShaderLanguage p_language, String *r_error, bool p_allow_cache) { if (p_allow_cache && cache_function) { Vector<uint8_t> cache = cache_function(p_stage, p_source_code, p_language); if (cache.size()) { @@ -62,18 +62,24 @@ Vector<uint8_t> RenderingDevice::shader_compile_from_source(ShaderStage p_stage, } } - ERR_FAIL_COND_V(!compile_function, Vector<uint8_t>()); + ERR_FAIL_COND_V(!compile_to_spirv_function, Vector<uint8_t>()); - return compile_function(p_stage, p_source_code, p_language, r_error, &device_capabilities); + return compile_to_spirv_function(p_stage, p_source_code, p_language, r_error, &device_capabilities); } -String RenderingDevice::shader_get_cache_key() const { - if (get_cache_key_function) { - return get_cache_key_function(&device_capabilities); +String RenderingDevice::shader_get_spirv_cache_key() const { + if (get_spirv_cache_key_function) { + return get_spirv_cache_key_function(&device_capabilities); } return String(); } +RID RenderingDevice::shader_create_from_spirv(const Vector<ShaderStageSPIRVData> &p_spirv) { + Vector<uint8_t> bytecode = shader_compile_binary_from_spirv(p_spirv); + ERR_FAIL_COND_V(bytecode.size() == 0, RID()); + return shader_create_from_bytecode(bytecode); +} + RID RenderingDevice::_texture_create(const Ref<RDTextureFormat> &p_format, const Ref<RDTextureView> &p_view, const TypedArray<PackedByteArray> &p_data) { ERR_FAIL_COND_V(p_format.is_null(), RID()); ERR_FAIL_COND_V(p_view.is_null(), RID()); @@ -170,40 +176,59 @@ RID RenderingDevice::_vertex_array_create(uint32_t p_vertex_count, VertexFormatI return vertex_array_create(p_vertex_count, p_vertex_format, buffers); } -Ref<RDShaderBytecode> RenderingDevice::_shader_compile_from_source(const Ref<RDShaderSource> &p_source, bool p_allow_cache) { - ERR_FAIL_COND_V(p_source.is_null(), Ref<RDShaderBytecode>()); +Ref<RDShaderSPIRV> RenderingDevice::_shader_compile_spirv_from_source(const Ref<RDShaderSource> &p_source, bool p_allow_cache) { + ERR_FAIL_COND_V(p_source.is_null(), Ref<RDShaderSPIRV>()); - Ref<RDShaderBytecode> bytecode; + Ref<RDShaderSPIRV> bytecode; bytecode.instantiate(); for (int i = 0; i < RD::SHADER_STAGE_MAX; i++) { String error; ShaderStage stage = ShaderStage(i); - Vector<uint8_t> spirv = shader_compile_from_source(stage, p_source->get_stage_source(stage), p_source->get_language(), &error, p_allow_cache); + Vector<uint8_t> spirv = shader_compile_spirv_from_source(stage, p_source->get_stage_source(stage), p_source->get_language(), &error, p_allow_cache); bytecode->set_stage_bytecode(stage, spirv); bytecode->set_stage_compile_error(stage, error); } return bytecode; } -RID RenderingDevice::shader_create_from_bytecode(const Ref<RDShaderBytecode> &p_bytecode) { - ERR_FAIL_COND_V(p_bytecode.is_null(), RID()); +Vector<uint8_t> RenderingDevice::_shader_compile_binary_from_spirv(const Ref<RDShaderSPIRV> &p_spirv) { + ERR_FAIL_COND_V(p_spirv.is_null(), Vector<uint8_t>()); - Vector<ShaderStageData> stage_data; + Vector<ShaderStageSPIRVData> stage_data; for (int i = 0; i < RD::SHADER_STAGE_MAX; i++) { ShaderStage stage = ShaderStage(i); - ShaderStageData sd; + ShaderStageSPIRVData sd; sd.shader_stage = stage; - String error = p_bytecode->get_stage_compile_error(stage); - ERR_FAIL_COND_V_MSG(error != String(), RID(), "Can't create a shader from an errored bytecode. Check errors in source bytecode."); - sd.spir_v = p_bytecode->get_stage_bytecode(stage); + String error = p_spirv->get_stage_compile_error(stage); + ERR_FAIL_COND_V_MSG(error != String(), Vector<uint8_t>(), "Can't create a shader from an errored bytecode. Check errors in source bytecode."); + sd.spir_v = p_spirv->get_stage_bytecode(stage); if (sd.spir_v.is_empty()) { continue; } stage_data.push_back(sd); } - return shader_create(stage_data); + return shader_compile_binary_from_spirv(stage_data); +} + +RID RenderingDevice::_shader_create_from_spirv(const Ref<RDShaderSPIRV> &p_spirv) { + ERR_FAIL_COND_V(p_spirv.is_null(), RID()); + + Vector<ShaderStageSPIRVData> stage_data; + for (int i = 0; i < RD::SHADER_STAGE_MAX; i++) { + ShaderStage stage = ShaderStage(i); + ShaderStageSPIRVData sd; + sd.shader_stage = stage; + String error = p_spirv->get_stage_compile_error(stage); + ERR_FAIL_COND_V_MSG(error != String(), RID(), "Can't create a shader from an errored bytecode. Check errors in source bytecode."); + sd.spir_v = p_spirv->get_stage_bytecode(stage); + if (sd.spir_v.is_empty()) { + continue; + } + stage_data.push_back(sd); + } + return shader_create_from_spirv(stage_data); } RID RenderingDevice::_uniform_set_create(const Array &p_uniforms, RID p_shader, uint32_t p_shader_set) { @@ -366,8 +391,10 @@ void RenderingDevice::_bind_methods() { ClassDB::bind_method(D_METHOD("index_buffer_create", "size_indices", "format", "data", "use_restart_indices"), &RenderingDevice::index_buffer_create, DEFVAL(Vector<uint8_t>()), DEFVAL(false)); ClassDB::bind_method(D_METHOD("index_array_create", "index_buffer", "index_offset", "index_count"), &RenderingDevice::index_array_create); - ClassDB::bind_method(D_METHOD("shader_compile_from_source", "shader_source", "allow_cache"), &RenderingDevice::_shader_compile_from_source, DEFVAL(true)); - ClassDB::bind_method(D_METHOD("shader_create", "shader_data"), &RenderingDevice::shader_create_from_bytecode); + ClassDB::bind_method(D_METHOD("shader_compile_spirv_from_source", "shader_source", "allow_cache"), &RenderingDevice::_shader_compile_spirv_from_source, DEFVAL(true)); + ClassDB::bind_method(D_METHOD("shader_compile_binary_from_spirv", "spirv_data"), &RenderingDevice::_shader_compile_binary_from_spirv); + ClassDB::bind_method(D_METHOD("shader_create_from_spirv", "spirv_data"), &RenderingDevice::_shader_compile_binary_from_spirv); + ClassDB::bind_method(D_METHOD("shader_create_from_bytecode", "binary_data"), &RenderingDevice::shader_create_from_bytecode); ClassDB::bind_method(D_METHOD("shader_get_vertex_input_attribute_mask", "shader"), &RenderingDevice::shader_get_vertex_input_attribute_mask); ClassDB::bind_method(D_METHOD("uniform_buffer_create", "size_bytes", "data"), &RenderingDevice::uniform_buffer_create, DEFVAL(Vector<uint8_t>())); diff --git a/servers/rendering/rendering_device.h b/servers/rendering/rendering_device.h index 9a154ef7e9..eaf1ace798 100644 --- a/servers/rendering/rendering_device.h +++ b/servers/rendering/rendering_device.h @@ -41,7 +41,7 @@ class RDAttachmentFormat; class RDSamplerState; class RDVertexAttribute; class RDShaderSource; -class RDShaderBytecode; +class RDShaderSPIRV; class RDUniforms; class RDPipelineRasterizationState; class RDPipelineMultisampleState; @@ -105,14 +105,14 @@ public: bool supports_multiview = false; // If true this device supports multiview options }; - typedef String (*ShaderGetCacheKeyFunction)(const Capabilities *p_capabilities); - typedef Vector<uint8_t> (*ShaderCompileFunction)(ShaderStage p_stage, const String &p_source_code, ShaderLanguage p_language, String *r_error, const Capabilities *p_capabilities); + typedef String (*ShaderSPIRVGetCacheKeyFunction)(const Capabilities *p_capabilities); + typedef Vector<uint8_t> (*ShaderCompileToSPIRVFunction)(ShaderStage p_stage, const String &p_source_code, ShaderLanguage p_language, String *r_error, const Capabilities *p_capabilities); typedef Vector<uint8_t> (*ShaderCacheFunction)(ShaderStage p_stage, const String &p_source_code, ShaderLanguage p_language); private: - static ShaderCompileFunction compile_function; + static ShaderCompileToSPIRVFunction compile_to_spirv_function; static ShaderCacheFunction cache_function; - static ShaderGetCacheKeyFunction get_cache_key_function; + static ShaderSPIRVGetCacheKeyFunction get_spirv_cache_key_function; static RenderingDevice *singleton; @@ -651,24 +651,28 @@ public: const Capabilities *get_device_capabilities() const { return &device_capabilities; }; - virtual Vector<uint8_t> shader_compile_from_source(ShaderStage p_stage, const String &p_source_code, ShaderLanguage p_language = SHADER_LANGUAGE_GLSL, String *r_error = nullptr, bool p_allow_cache = true); - virtual String shader_get_cache_key() const; + virtual Vector<uint8_t> shader_compile_spirv_from_source(ShaderStage p_stage, const String &p_source_code, ShaderLanguage p_language = SHADER_LANGUAGE_GLSL, String *r_error = nullptr, bool p_allow_cache = true); + virtual String shader_get_spirv_cache_key() const; - static void shader_set_compile_function(ShaderCompileFunction p_function); - static void shader_set_cache_function(ShaderCacheFunction p_function); - static void shader_set_get_cache_key_function(ShaderGetCacheKeyFunction p_function); + static void shader_set_compile_to_spirv_function(ShaderCompileToSPIRVFunction p_function); + static void shader_set_spirv_cache_function(ShaderCacheFunction p_function); + static void shader_set_get_cache_key_function(ShaderSPIRVGetCacheKeyFunction p_function); - struct ShaderStageData { + struct ShaderStageSPIRVData { ShaderStage shader_stage; Vector<uint8_t> spir_v; - ShaderStageData() { + ShaderStageSPIRVData() { shader_stage = SHADER_STAGE_VERTEX; } }; - RID shader_create_from_bytecode(const Ref<RDShaderBytecode> &p_bytecode); - virtual RID shader_create(const Vector<ShaderStageData> &p_stages) = 0; + virtual String shader_get_binary_cache_key() const = 0; + virtual Vector<uint8_t> shader_compile_binary_from_spirv(const Vector<ShaderStageSPIRVData> &p_spirv) = 0; + + virtual RID shader_create_from_spirv(const Vector<ShaderStageSPIRVData> &p_spirv); + virtual RID shader_create_from_bytecode(const Vector<uint8_t> &p_shader_binary) = 0; + virtual uint32_t shader_get_vertex_input_attribute_mask(RID p_shader) = 0; /******************/ @@ -1194,7 +1198,9 @@ protected: VertexFormatID _vertex_format_create(const TypedArray<RDVertexAttribute> &p_vertex_formats); RID _vertex_array_create(uint32_t p_vertex_count, VertexFormatID p_vertex_format, const TypedArray<RID> &p_src_buffers); - Ref<RDShaderBytecode> _shader_compile_from_source(const Ref<RDShaderSource> &p_source, bool p_allow_cache = true); + Ref<RDShaderSPIRV> _shader_compile_spirv_from_source(const Ref<RDShaderSource> &p_source, bool p_allow_cache = true); + Vector<uint8_t> _shader_compile_binary_from_spirv(const Ref<RDShaderSPIRV> &p_bytecode); + RID _shader_create_from_spirv(const Ref<RDShaderSPIRV> &p_spirv); RID _uniform_set_create(const Array &p_uniforms, RID p_shader, uint32_t p_shader_set); diff --git a/servers/rendering/rendering_device_binds.cpp b/servers/rendering/rendering_device_binds.cpp index 2652edb1bc..fa3f2f3895 100644 --- a/servers/rendering/rendering_device_binds.cpp +++ b/servers/rendering/rendering_device_binds.cpp @@ -172,7 +172,7 @@ Error RDShaderFile::parse_versions_from_text(const String &p_text, const String /* STEP 2, Compile the versions, add to shader file */ for (Map<StringName, String>::Element *E = version_texts.front(); E; E = E->next()) { - Ref<RDShaderBytecode> bytecode; + Ref<RDShaderSPIRV> bytecode; bytecode.instantiate(); for (int i = 0; i < RD::SHADER_STAGE_MAX; i++) { @@ -182,7 +182,7 @@ Error RDShaderFile::parse_versions_from_text(const String &p_text, const String } code = code.replace("VERSION_DEFINES", E->get()); String error; - Vector<uint8_t> spirv = RenderingDevice::get_singleton()->shader_compile_from_source(RD::ShaderStage(i), code, RD::SHADER_LANGUAGE_GLSL, &error, false); + Vector<uint8_t> spirv = RenderingDevice::get_singleton()->shader_compile_spirv_from_source(RD::ShaderStage(i), code, RD::SHADER_LANGUAGE_GLSL, &error, false); bytecode->set_stage_bytecode(RD::ShaderStage(i), spirv); if (error != "") { error += String() + "\n\nStage '" + stage_str[i] + "' source code: \n\n"; diff --git a/servers/rendering/rendering_device_binds.h b/servers/rendering/rendering_device_binds.h index 4c31880faf..ccc3e2fb39 100644 --- a/servers/rendering/rendering_device_binds.h +++ b/servers/rendering/rendering_device_binds.h @@ -263,8 +263,8 @@ protected: } }; -class RDShaderBytecode : public Resource { - GDCLASS(RDShaderBytecode, Resource) +class RDShaderSPIRV : public Resource { + GDCLASS(RDShaderSPIRV, Resource) Vector<uint8_t> bytecode[RD::SHADER_STAGE_MAX]; String compile_error[RD::SHADER_STAGE_MAX]; @@ -280,6 +280,19 @@ public: return bytecode[p_stage]; } + Vector<RD::ShaderStageSPIRVData> get_stages() const { + Vector<RD::ShaderStageSPIRVData> stages; + for (int i = 0; i < RD::SHADER_STAGE_MAX; i++) { + if (bytecode[i].size()) { + RD::ShaderStageSPIRVData stage; + stage.shader_stage = RD::ShaderStage(i); + stage.spir_v = bytecode[i]; + stages.push_back(stage); + } + } + return stages; + } + void set_stage_compile_error(RD::ShaderStage p_stage, const String &p_compile_error) { ERR_FAIL_INDEX(p_stage, RD::SHADER_STAGE_MAX); compile_error[p_stage] = p_compile_error; @@ -292,11 +305,11 @@ public: protected: static void _bind_methods() { - ClassDB::bind_method(D_METHOD("set_stage_bytecode", "stage", "bytecode"), &RDShaderBytecode::set_stage_bytecode); - ClassDB::bind_method(D_METHOD("get_stage_bytecode", "stage"), &RDShaderBytecode::get_stage_bytecode); + ClassDB::bind_method(D_METHOD("set_stage_bytecode", "stage", "bytecode"), &RDShaderSPIRV::set_stage_bytecode); + ClassDB::bind_method(D_METHOD("get_stage_bytecode", "stage"), &RDShaderSPIRV::get_stage_bytecode); - ClassDB::bind_method(D_METHOD("set_stage_compile_error", "stage", "compile_error"), &RDShaderBytecode::set_stage_compile_error); - ClassDB::bind_method(D_METHOD("get_stage_compile_error", "stage"), &RDShaderBytecode::get_stage_compile_error); + ClassDB::bind_method(D_METHOD("set_stage_compile_error", "stage", "compile_error"), &RDShaderSPIRV::set_stage_compile_error); + ClassDB::bind_method(D_METHOD("get_stage_compile_error", "stage"), &RDShaderSPIRV::get_stage_compile_error); ADD_GROUP("Bytecode", "bytecode_"); ADD_PROPERTYI(PropertyInfo(Variant::PACKED_BYTE_ARRAY, "bytecode_vertex"), "set_stage_bytecode", "get_stage_bytecode", RD::SHADER_STAGE_VERTEX); @@ -316,24 +329,29 @@ protected: class RDShaderFile : public Resource { GDCLASS(RDShaderFile, Resource) - Map<StringName, Ref<RDShaderBytecode>> versions; + Map<StringName, Ref<RDShaderSPIRV>> versions; String base_error; public: - void set_bytecode(const Ref<RDShaderBytecode> &p_bytecode, const StringName &p_version = StringName()) { + void set_bytecode(const Ref<RDShaderSPIRV> &p_bytecode, const StringName &p_version = StringName()) { ERR_FAIL_COND(p_bytecode.is_null()); versions[p_version] = p_bytecode; emit_changed(); } - Ref<RDShaderBytecode> get_bytecode(const StringName &p_version = StringName()) const { - ERR_FAIL_COND_V(!versions.has(p_version), Ref<RDShaderBytecode>()); + Ref<RDShaderSPIRV> get_spirv(const StringName &p_version = StringName()) const { + ERR_FAIL_COND_V(!versions.has(p_version), Ref<RDShaderSPIRV>()); return versions[p_version]; } + Vector<RD::ShaderStageSPIRVData> get_spirv_stages(const StringName &p_version = StringName()) const { + ERR_FAIL_COND_V(!versions.has(p_version), Vector<RD::ShaderStageSPIRVData>()); + return versions[p_version]->get_stages(); + } + Vector<StringName> get_version_list() const { Vector<StringName> vnames; - for (Map<StringName, Ref<RDShaderBytecode>>::Element *E = versions.front(); E; E = E->next()) { + for (Map<StringName, Ref<RDShaderSPIRV>>::Element *E = versions.front(); E; E = E->next()) { vnames.push_back(E->key()); } vnames.sort_custom<StringName::AlphCompare>(); @@ -353,7 +371,7 @@ public: if (base_error != "") { ERR_PRINT("Error parsing shader '" + p_file + "':\n\n" + base_error); } else { - for (Map<StringName, Ref<RDShaderBytecode>>::Element *E = versions.front(); E; E = E->next()) { + for (Map<StringName, Ref<RDShaderSPIRV>>::Element *E = versions.front(); E; E = E->next()) { for (int i = 0; i < RD::SHADER_STAGE_MAX; i++) { String error = E->get()->get_stage_compile_error(RD::ShaderStage(i)); if (error != String()) { @@ -388,9 +406,9 @@ protected: versions.clear(); List<Variant> keys; p_versions.get_key_list(&keys); - for (List<Variant>::Element *E = keys.front(); E; E = E->next()) { - StringName name = E->get(); - Ref<RDShaderBytecode> bc = p_versions[E->get()]; + for (const Variant &E : keys) { + StringName name = E; + Ref<RDShaderSPIRV> bc = p_versions[E]; ERR_CONTINUE(bc.is_null()); versions[name] = bc; } @@ -400,7 +418,7 @@ protected: static void _bind_methods() { ClassDB::bind_method(D_METHOD("set_bytecode", "bytecode", "version"), &RDShaderFile::set_bytecode, DEFVAL(StringName())); - ClassDB::bind_method(D_METHOD("get_bytecode", "version"), &RDShaderFile::get_bytecode, DEFVAL(StringName())); + ClassDB::bind_method(D_METHOD("get_spirv", "version"), &RDShaderFile::get_spirv, DEFVAL(StringName())); ClassDB::bind_method(D_METHOD("get_version_list"), &RDShaderFile::get_version_list); ClassDB::bind_method(D_METHOD("set_base_error", "error"), &RDShaderFile::set_base_error); diff --git a/servers/rendering/rendering_server_default.h b/servers/rendering/rendering_server_default.h index 79665dcdd2..282b0564da 100644 --- a/servers/rendering/rendering_server_default.h +++ b/servers/rendering/rendering_server_default.h @@ -656,6 +656,8 @@ public: FUNC1(shadows_quality_set, ShadowQuality); FUNC1(directional_shadow_quality_set, ShadowQuality); + FUNC1(decals_set_filter, RS::DecalFilter); + FUNC1(light_projectors_set_filter, RS::LightProjectorFilter); /* SCENARIO API */ diff --git a/servers/rendering/shader_language.cpp b/servers/rendering/shader_language.cpp index f771d6d0ef..baa5381554 100644 --- a/servers/rendering/shader_language.cpp +++ b/servers/rendering/shader_language.cpp @@ -912,6 +912,8 @@ void ShaderLanguage::clear() { completion_class = SubClassTag::TAG_GLOBAL; completion_struct = StringName(); + unknown_varying_usages.clear(); + #ifdef DEBUG_ENABLED used_constants.clear(); used_varyings.clear(); @@ -946,7 +948,9 @@ void ShaderLanguage::_parse_used_identifier(const StringName &p_identifier, Iden break; case IdentifierType::IDENTIFIER_VARYING: if (HAS_WARNING(ShaderWarning::UNUSED_VARYING_FLAG) && used_varyings.has(p_identifier)) { - used_varyings[p_identifier].used = true; + if (shader->varyings[p_identifier].stage != ShaderNode::Varying::STAGE_VERTEX && shader->varyings[p_identifier].stage != ShaderNode::Varying::STAGE_FRAGMENT) { + used_varyings[p_identifier].used = true; + } } break; case IdentifierType::IDENTIFIER_UNIFORM: @@ -2434,6 +2438,10 @@ bool ShaderLanguage::_validate_function_call(BlockNode *p_block, const FunctionI if (shader->uniforms.has(varname)) { fail = true; } else { + if (shader->varyings.has(varname)) { + _set_error(vformat("Varyings cannot be passed for '%s' parameter!", "out")); + return false; + } if (p_function_info.built_ins.has(varname)) { BuiltInInfo info = p_function_info.built_ins[varname]; if (info.constant) { @@ -2812,6 +2820,20 @@ bool ShaderLanguage::is_token_operator(TokenType p_type) { p_type == TK_COLON); } +bool ShaderLanguage::is_token_operator_assign(TokenType p_type) { + return (p_type == TK_OP_ASSIGN || + p_type == TK_OP_ASSIGN_ADD || + p_type == TK_OP_ASSIGN_SUB || + p_type == TK_OP_ASSIGN_MUL || + p_type == TK_OP_ASSIGN_DIV || + p_type == TK_OP_ASSIGN_MOD || + p_type == TK_OP_ASSIGN_SHIFT_LEFT || + p_type == TK_OP_ASSIGN_SHIFT_RIGHT || + p_type == TK_OP_ASSIGN_BIT_AND || + p_type == TK_OP_ASSIGN_BIT_OR || + p_type == TK_OP_ASSIGN_BIT_XOR); +} + bool ShaderLanguage::convert_constant(ConstantNode *p_constant, DataType p_to_type, ConstantNode::Value *p_value) { if (p_constant->datatype == p_to_type) { if (p_value) { @@ -3306,8 +3328,8 @@ bool ShaderLanguage::_is_operator_assign(Operator p_op) const { } bool ShaderLanguage::_validate_varying_assign(ShaderNode::Varying &p_varying, String *r_message) { - if (current_function == String("light")) { - *r_message = RTR("Varying may not be assigned in the 'light' function."); + if (current_function != String("vertex") && current_function != String("fragment")) { + *r_message = vformat(RTR("Varying may not be assigned in the '%s' function."), current_function); return false; } switch (p_varying.stage) { @@ -3318,12 +3340,14 @@ bool ShaderLanguage::_validate_varying_assign(ShaderNode::Varying &p_varying, St p_varying.stage = ShaderNode::Varying::STAGE_FRAGMENT; } break; + case ShaderNode::Varying::STAGE_VERTEX_TO_FRAGMENT_LIGHT: case ShaderNode::Varying::STAGE_VERTEX: if (current_function == varying_function_names.fragment) { *r_message = RTR("Varyings which assigned in 'vertex' function may not be reassigned in 'fragment' or 'light'."); return false; } break; + case ShaderNode::Varying::STAGE_FRAGMENT_TO_LIGHT: case ShaderNode::Varying::STAGE_FRAGMENT: if (current_function == varying_function_names.vertex) { *r_message = RTR("Varyings which assigned in 'fragment' function may not be reassigned in 'vertex' or 'light'."); @@ -3339,13 +3363,14 @@ bool ShaderLanguage::_validate_varying_assign(ShaderNode::Varying &p_varying, St bool ShaderLanguage::_validate_varying_using(ShaderNode::Varying &p_varying, String *r_message) { switch (p_varying.stage) { case ShaderNode::Varying::STAGE_UNKNOWN: - *r_message = RTR("Varying must be assigned before using!"); - return false; + VaryingUsage usage; + usage.var = &p_varying; + usage.line = tk_line; + unknown_varying_usages.push_back(usage); + break; case ShaderNode::Varying::STAGE_VERTEX: - if (current_function == varying_function_names.fragment) { - p_varying.stage = ShaderNode::Varying::STAGE_VERTEX_TO_FRAGMENT; - } else if (current_function == varying_function_names.light) { - p_varying.stage = ShaderNode::Varying::STAGE_VERTEX_TO_LIGHT; + if (current_function == varying_function_names.fragment || current_function == varying_function_names.light) { + p_varying.stage = ShaderNode::Varying::STAGE_VERTEX_TO_FRAGMENT_LIGHT; } break; case ShaderNode::Varying::STAGE_FRAGMENT: @@ -3353,24 +3378,25 @@ bool ShaderLanguage::_validate_varying_using(ShaderNode::Varying &p_varying, Str p_varying.stage = ShaderNode::Varying::STAGE_FRAGMENT_TO_LIGHT; } break; - case ShaderNode::Varying::STAGE_VERTEX_TO_FRAGMENT: - if (current_function == varying_function_names.light) { - *r_message = RTR("Varying must only be used in two different stages, which can be 'vertex' 'fragment' and 'light'"); - return false; - } - break; - case ShaderNode::Varying::STAGE_VERTEX_TO_LIGHT: - if (current_function == varying_function_names.fragment) { - *r_message = RTR("Varying must only be used in two different stages, which can be 'vertex' 'fragment' and 'light'"); - return false; - } - break; default: break; } return true; } +bool ShaderLanguage::_check_varying_usages(int *r_error_line, String *r_error_message) const { + for (const List<ShaderLanguage::VaryingUsage>::Element *E = unknown_varying_usages.front(); E; E = E->next()) { + ShaderNode::Varying::Stage stage = E->get().var->stage; + if (stage != ShaderNode::Varying::STAGE_UNKNOWN && stage != ShaderNode::Varying::STAGE_VERTEX && stage != ShaderNode::Varying::STAGE_VERTEX_TO_FRAGMENT_LIGHT) { + *r_error_line = E->get().line; + *r_error_message = RTR("Fragment-stage varying could not been accessed in custom function!"); + return false; + } + } + + return true; +} + bool ShaderLanguage::_check_node_constness(const Node *p_node) const { switch (p_node->type) { case Node::TYPE_OPERATOR: { @@ -4114,6 +4140,10 @@ ShaderLanguage::Node *ShaderLanguage::_parse_expression(BlockNode *p_block, cons } else if (shader->uniforms.has(varname)) { error = true; } else { + if (shader->varyings.has(varname)) { + _set_error(vformat("Varyings cannot be passed for '%s' parameter!", _get_qualifier_str(call_function->arguments[i].qualifier))); + return nullptr; + } if (p_function_info.built_ins.has(varname)) { BuiltInInfo info = p_function_info.built_ins[varname]; if (info.constant) { @@ -4224,7 +4254,8 @@ ShaderLanguage::Node *ShaderLanguage::_parse_expression(BlockNode *p_block, cons Token next_token = _get_token(); _set_tkpos(prev_pos); String error; - if (next_token.type == TK_OP_ASSIGN) { + + if (is_token_operator_assign(next_token.type)) { if (!_validate_varying_assign(shader->varyings[identifier], &error)) { _set_error(error); return nullptr; @@ -4435,12 +4466,12 @@ ShaderLanguage::Node *ShaderLanguage::_parse_expression(BlockNode *p_block, cons String member_name = String(ident.ptr()); if (shader->structs.has(st)) { StructNode *n = shader->structs[st].shader_struct; - for (List<MemberNode *>::Element *E = n->members.front(); E; E = E->next()) { - if (String(E->get()->name) == member_name) { - member_type = E->get()->datatype; - array_size = E->get()->array_size; + for (const MemberNode *E : n->members) { + if (String(E->name) == member_name) { + member_type = E->datatype; + array_size = E->array_size; if (member_type == TYPE_STRUCT) { - member_struct_name = E->get()->struct_name; + member_struct_name = E->struct_name; } ok = true; break; @@ -4765,10 +4796,12 @@ ShaderLanguage::Node *ShaderLanguage::_parse_expression(BlockNode *p_block, cons String member_struct_name; if (expr->get_array_size() > 0) { - uint32_t index_constant = static_cast<ConstantNode *>(index)->values[0].uint; - if (index_constant >= (uint32_t)expr->get_array_size()) { - _set_error(vformat("Index [%s] out of range [%s..%s]", index_constant, 0, expr->get_array_size() - 1)); - return nullptr; + if (index->type == Node::TYPE_CONSTANT) { + uint32_t index_constant = static_cast<ConstantNode *>(index)->values[0].uint; + if (index_constant >= (uint32_t)expr->get_array_size()) { + _set_error(vformat("Index [%s] out of range [%s..%s]", index_constant, 0, expr->get_array_size() - 1)); + return nullptr; + } } member_type = expr->get_datatype(); if (member_type == TYPE_STRUCT) { @@ -7863,12 +7896,12 @@ Error ShaderLanguage::_parse_shader(const Map<StringName, FunctionInfo> &p_funct tk = _get_token(); } - for (Map<StringName, ShaderNode::Varying>::Element *E = shader->varyings.front(); E; E = E->next()) { - if (E->get().stage == ShaderNode::Varying::STAGE_VERTEX || E->get().stage == ShaderNode::Varying::STAGE_FRAGMENT) { - _set_tkpos(E->get().tkpos); - _set_error(RTR("Varying must only be used in two different stages, which can be 'vertex' 'fragment' and 'light'")); - return ERR_PARSE_ERROR; - } + int error_line; + String error_message; + if (!_check_varying_usages(&error_line, &error_message)) { + _set_tkpos({ 0, error_line }); + _set_error(error_message); + return ERR_PARSE_ERROR; } return OK; diff --git a/servers/rendering/shader_language.h b/servers/rendering/shader_language.h index a91fa57a8e..c02d6c47ec 100644 --- a/servers/rendering/shader_language.h +++ b/servers/rendering/shader_language.h @@ -646,10 +646,9 @@ public: struct Varying { enum Stage { STAGE_UNKNOWN, - STAGE_VERTEX, // transition stage to STAGE_VERTEX_TO_FRAGMENT or STAGE_VERTEX_TO_LIGHT, emits error if they are not used - STAGE_FRAGMENT, // transition stage to STAGE_FRAGMENT_TO_LIGHT, emits error if it's not used - STAGE_VERTEX_TO_FRAGMENT, - STAGE_VERTEX_TO_LIGHT, + STAGE_VERTEX, // transition stage to STAGE_VERTEX_TO_FRAGMENT_LIGHT, emits warning if it's not used + STAGE_FRAGMENT, // transition stage to STAGE_FRAGMENT_TO_LIGHT, emits warning if it's not used + STAGE_VERTEX_TO_FRAGMENT_LIGHT, STAGE_FRAGMENT_TO_LIGHT, }; @@ -767,6 +766,7 @@ public: static String get_datatype_name(DataType p_type); static bool is_token_nonvoid_datatype(TokenType p_type); static bool is_token_operator(TokenType p_type); + static bool is_token_operator_assign(TokenType p_type); static bool convert_constant(ConstantNode *p_constant, DataType p_to_type, ConstantNode::Value *p_value = nullptr); static DataType get_scalar_type(DataType p_type); @@ -876,6 +876,14 @@ private: VaryingFunctionNames varying_function_names; + struct VaryingUsage { + ShaderNode::Varying *var; + int line; + }; + List<VaryingUsage> unknown_varying_usages; + + bool _check_varying_usages(int *r_error_line, String *r_error_message) const; + TkPos _get_tkpos() { TkPos tkp; tkp.char_idx = char_idx; diff --git a/servers/rendering_server.cpp b/servers/rendering_server.cpp index a88fad9fe1..314b59869d 100644 --- a/servers/rendering_server.cpp +++ b/servers/rendering_server.cpp @@ -53,15 +53,15 @@ Array RenderingServer::_texture_debug_usage_bind() { List<TextureInfo> list; texture_debug_usage(&list); Array arr; - for (const List<TextureInfo>::Element *E = list.front(); E; E = E->next()) { + for (const TextureInfo &E : list) { Dictionary dict; - dict["texture"] = E->get().texture; - dict["width"] = E->get().width; - dict["height"] = E->get().height; - dict["depth"] = E->get().depth; - dict["format"] = E->get().format; - dict["bytes"] = E->get().bytes; - dict["path"] = E->get().path; + dict["texture"] = E.texture; + dict["width"] = E.width; + dict["height"] = E.height; + dict["depth"] = E.depth; + dict["format"] = E.format; + dict["bytes"] = E.bytes; + dict["path"] = E.path; arr.push_back(dict); } return arr; @@ -972,10 +972,10 @@ Error RenderingServer::mesh_create_surface_data_from_arrays(SurfaceData *r_surfa if (index_array_len) { List<Variant> keys; p_lods.get_key_list(&keys); - for (List<Variant>::Element *E = keys.front(); E; E = E->next()) { - float distance = E->get(); + for (const Variant &E : keys) { + float distance = E; ERR_CONTINUE(distance <= 0.0); - Vector<int> indices = p_lods[E->get()]; + Vector<int> indices = p_lods[E]; ERR_CONTINUE(indices.size() == 0); uint32_t index_count = indices.size(); ERR_CONTINUE(index_count >= (uint32_t)index_array_len); //should be smaller.. @@ -1854,6 +1854,14 @@ void RenderingServer::_bind_methods() { ClassDB::bind_method(D_METHOD("light_directional_set_blend_splits", "light", "enable"), &RenderingServer::light_directional_set_blend_splits); ClassDB::bind_method(D_METHOD("light_directional_set_sky_only", "light", "enable"), &RenderingServer::light_directional_set_sky_only); + ClassDB::bind_method(D_METHOD("light_projectors_set_filter", "filter"), &RenderingServer::light_projectors_set_filter); + + BIND_ENUM_CONSTANT(LIGHT_PROJECTOR_FILTER_NEAREST); + BIND_ENUM_CONSTANT(LIGHT_PROJECTOR_FILTER_NEAREST_MIPMAPS); + BIND_ENUM_CONSTANT(LIGHT_PROJECTOR_FILTER_LINEAR); + BIND_ENUM_CONSTANT(LIGHT_PROJECTOR_FILTER_LINEAR_MIPMAPS); + BIND_ENUM_CONSTANT(LIGHT_PROJECTOR_FILTER_LINEAR_MIPMAPS_ANISOTROPIC); + BIND_ENUM_CONSTANT(LIGHT_DIRECTIONAL); BIND_ENUM_CONSTANT(LIGHT_OMNI); BIND_ENUM_CONSTANT(LIGHT_SPOT); @@ -1939,12 +1947,20 @@ void RenderingServer::_bind_methods() { ClassDB::bind_method(D_METHOD("decal_set_fade", "decal", "above", "below"), &RenderingServer::decal_set_fade); ClassDB::bind_method(D_METHOD("decal_set_normal_fade", "decal", "fade"), &RenderingServer::decal_set_normal_fade); + ClassDB::bind_method(D_METHOD("decals_set_filter", "filter"), &RenderingServer::decals_set_filter); + BIND_ENUM_CONSTANT(DECAL_TEXTURE_ALBEDO); BIND_ENUM_CONSTANT(DECAL_TEXTURE_NORMAL); BIND_ENUM_CONSTANT(DECAL_TEXTURE_ORM); BIND_ENUM_CONSTANT(DECAL_TEXTURE_EMISSION); BIND_ENUM_CONSTANT(DECAL_TEXTURE_MAX); + BIND_ENUM_CONSTANT(DECAL_FILTER_NEAREST); + BIND_ENUM_CONSTANT(DECAL_FILTER_NEAREST_MIPMAPS); + BIND_ENUM_CONSTANT(DECAL_FILTER_LINEAR); + BIND_ENUM_CONSTANT(DECAL_FILTER_LINEAR_MIPMAPS); + BIND_ENUM_CONSTANT(DECAL_FILTER_LINEAR_MIPMAPS_ANISOTROPIC); + /* VOXEL GI API */ ClassDB::bind_method(D_METHOD("voxel_gi_create"), &RenderingServer::voxel_gi_create); @@ -2747,12 +2763,12 @@ RenderingServer::RenderingServer() { GLOBAL_DEF("rendering/2d/shadow_atlas/size", 2048); - GLOBAL_DEF_RST("rendering/vulkan/rendering/back_end", 0); - GLOBAL_DEF_RST("rendering/vulkan/rendering/back_end.mobile", 1); + GLOBAL_DEF_RST_BASIC("rendering/vulkan/rendering/back_end", 0); + GLOBAL_DEF_RST_BASIC("rendering/vulkan/rendering/back_end.mobile", 1); ProjectSettings::get_singleton()->set_custom_property_info("rendering/vulkan/rendering/back_end", PropertyInfo(Variant::INT, "rendering/vulkan/rendering/back_end", - PROPERTY_HINT_ENUM, "ForwardClustered,ForwardMobile")); + PROPERTY_HINT_ENUM, "Forward Clustered (Supports Desktop Only),Forward Mobile (Supports Desktop and Mobile)")); GLOBAL_DEF("rendering/shader_compiler/shader_cache/enabled", true); GLOBAL_DEF("rendering/shader_compiler/shader_cache/compress", true); @@ -2814,6 +2830,11 @@ RenderingServer::RenderingServer() { ProjectSettings::get_singleton()->set_custom_property_info("rendering/anti_aliasing/screen_space_roughness_limiter/amount", PropertyInfo(Variant::FLOAT, "rendering/anti_aliasing/screen_space_roughness_limiter/amount", PROPERTY_HINT_RANGE, "0.01,4.0,0.01")); ProjectSettings::get_singleton()->set_custom_property_info("rendering/anti_aliasing/screen_space_roughness_limiter/limit", PropertyInfo(Variant::FLOAT, "rendering/anti_aliasing/screen_space_roughness_limiter/limit", PROPERTY_HINT_RANGE, "0.01,1.0,0.01")); + GLOBAL_DEF("rendering/textures/decals/filter", DECAL_FILTER_LINEAR_MIPMAPS); + ProjectSettings::get_singleton()->set_custom_property_info("rendering/textures/decals/filter", PropertyInfo(Variant::INT, "rendering/textures/decals/filter", PROPERTY_HINT_ENUM, "Nearest (Fast),Nearest+Mipmaps,Linear,Linear+Mipmaps,Linear+Mipmaps Anisotropic (Slow)")); + GLOBAL_DEF("rendering/textures/light_projectors/filter", LIGHT_PROJECTOR_FILTER_LINEAR_MIPMAPS); + ProjectSettings::get_singleton()->set_custom_property_info("rendering/textures/light_projectors/filter", PropertyInfo(Variant::INT, "rendering/textures/light_projectors/filter", PROPERTY_HINT_ENUM, "Nearest (Fast),Nearest+Mipmaps,Linear,Linear+Mipmaps,Linear+Mipmaps Anisotropic (Slow)")); + GLOBAL_DEF_RST("rendering/occlusion_culling/occlusion_rays_per_thread", 512); GLOBAL_DEF_RST("rendering/occlusion_culling/bvh_build_quality", 2); ProjectSettings::get_singleton()->set_custom_property_info("rendering/occlusion_culling/bvh_build_quality", PropertyInfo(Variant::INT, "rendering/occlusion_culling/bvh_build_quality", PROPERTY_HINT_ENUM, "Low,Medium,High")); diff --git a/servers/rendering_server.h b/servers/rendering_server.h index e13b81f698..28aee1b575 100644 --- a/servers/rendering_server.h +++ b/servers/rendering_server.h @@ -483,6 +483,17 @@ public: virtual void shadows_quality_set(ShadowQuality p_quality) = 0; virtual void directional_shadow_quality_set(ShadowQuality p_quality) = 0; + + enum LightProjectorFilter { + LIGHT_PROJECTOR_FILTER_NEAREST, + LIGHT_PROJECTOR_FILTER_NEAREST_MIPMAPS, + LIGHT_PROJECTOR_FILTER_LINEAR, + LIGHT_PROJECTOR_FILTER_LINEAR_MIPMAPS, + LIGHT_PROJECTOR_FILTER_LINEAR_MIPMAPS_ANISOTROPIC, + }; + + virtual void light_projectors_set_filter(LightProjectorFilter p_filter) = 0; + /* PROBE API */ virtual RID reflection_probe_create() = 0; @@ -535,6 +546,16 @@ public: virtual void decal_set_fade(RID p_decal, float p_above, float p_below) = 0; virtual void decal_set_normal_fade(RID p_decal, float p_fade) = 0; + enum DecalFilter { + DECAL_FILTER_NEAREST, + DECAL_FILTER_NEAREST_MIPMAPS, + DECAL_FILTER_LINEAR, + DECAL_FILTER_LINEAR_MIPMAPS, + DECAL_FILTER_LINEAR_MIPMAPS_ANISOTROPIC, + }; + + virtual void decals_set_filter(DecalFilter p_quality) = 0; + /* VOXEL GI API */ virtual RID voxel_gi_create() = 0; @@ -1499,10 +1520,12 @@ VARIANT_ENUM_CAST(RenderingServer::LightParam); VARIANT_ENUM_CAST(RenderingServer::LightBakeMode); VARIANT_ENUM_CAST(RenderingServer::LightOmniShadowMode); VARIANT_ENUM_CAST(RenderingServer::LightDirectionalShadowMode); +VARIANT_ENUM_CAST(RenderingServer::LightProjectorFilter); VARIANT_ENUM_CAST(RenderingServer::ReflectionProbeUpdateMode); VARIANT_ENUM_CAST(RenderingServer::ReflectionProbeAmbientMode); VARIANT_ENUM_CAST(RenderingServer::VoxelGIQuality); VARIANT_ENUM_CAST(RenderingServer::DecalTexture); +VARIANT_ENUM_CAST(RenderingServer::DecalFilter); VARIANT_ENUM_CAST(RenderingServer::ParticlesMode); VARIANT_ENUM_CAST(RenderingServer::ParticlesTransformAlign); VARIANT_ENUM_CAST(RenderingServer::ParticlesDrawOrder); diff --git a/servers/xr/xr_interface.h b/servers/xr/xr_interface.h index 6031bd7003..6b248c9554 100644 --- a/servers/xr/xr_interface.h +++ b/servers/xr/xr_interface.h @@ -41,7 +41,7 @@ struct BlitToScreen; /** @author Bastiaan Olij <mux213@gmail.com> - The XR interface is a template class ontop of which we build interface to different AR, VR and tracking SDKs. + The XR interface is a template class on top of which we build interface to different AR, VR and tracking SDKs. The idea is that we subclass this class, implement the logic, and then instantiate a singleton of each interface when Godot starts. These instances do not initialize themselves but register themselves with the AR/VR server. |