diff --git a/docs/HLSD/selection-outline.md b/docs/HLSD/selection-outline.md new file mode 100644 index 0000000000..d2f94fcf26 --- /dev/null +++ b/docs/HLSD/selection-outline.md @@ -0,0 +1,102 @@ +# Selection outline — High Level Design + +## Purpose and scope + +When the Outline view option is on, the selected volumes of the 3D canvas are outlined: a ring of +constant screen width around their silhouette, and thinner lines along their inner edges, the creases +between faces, the contours where one part of the selection hides another, and the seams between +neighboring parts. It is a view setting. It changes nothing in the model or the project, and it reaches +neither the picking pass nor thumbnails. + +`SelectionOutline` draws it once per frame for the whole selection, after the object passes of +`GLCanvas3D::_render_scene()`. Its cost depends on the screen area of the selection, not on its triangle +count, apart from one extra draw of the selected volumes. + +## Passes + +`GLVolumeCollection::render()` collects the selected volumes it draws, when the canvas passes it a list, +and sets bit `SelectionOutline::StencilBit` of the canvas stencil wherever one of them passes the depth +test. The stencil is cleared with the depth buffer at the start of the frame. `SelectionOutline::render()` +then runs three passes, restricted by the scissor to the screen box of the selection, padded by how far +each pass reads the one before it. + +1. **Mask** (`outline_mask`). The selected volumes are drawn again, with the clipping of the object + passes, into a 16 bit RGBA target with a depth texture of its own. Each texel packs, in two bytes per + channel, the octahedral encoded view normal turned towards the camera, the part index of its volume, + and the distances from the texel center to the edge of its triangle along +x, -x, + +y and -y. GLModel gives every triangle three vertices of its own, so `gl_VertexID % 3` yields the + barycentrics, and their screen derivatives the distances. +2. **Edges** (`outline_edges`). For every texel, and each pair it forms with its right and upper neighbor, + an inner edge is classified and located, and packed as a 4 bit strength and a 4 bit crossing position + between the two texel centers. Along its row, the pass also finds the nearest covered texel and sums + the coverage under a gaussian. +3. **Composite** (`outline`). A full screen quad, drawn twice into the canvas framebuffer. The ring pass + draws where the stencil bit is clear, so its inner edge is the multisampled silhouette of the + selection itself. The lines pass draws where it is set, so inner lines stop exactly at the silhouette. + +The targets, 16 bytes a pixel at canvas size, are allocated when something is outlined and kept from frame +to frame, and they are freed in the first frame with nothing to outline. + +## Inner edges + +A pair of covered texels makes an edge when its normals differ by more than 25 degrees, fully at 40, +when one surface hides the other, or when the texels belong to different parts. One surface hides the +other when the view space step between the texels lies more than a few pixels off their planes, and +each texel lies more than a pixel off the surface of the other side carried on over the pair. A curved +surface seen edge on carries on smoothly, so it does not break into lines, nor does a fillet whose facets +turn a little at every texel on both sides. A texel on a triangle smaller than a pixel both ways +takes the normal of a neighbor beside it: the normals of such slivers can be far off their surface and +would otherwise show as dots. + +The crossing is placed between the texel centers, in this order of preference: + +- where the triangles under both texels end, when they agree: the edge they share; +- where the depth planes of the two sides meet, extrapolated from two texels on each side, when each side + is flat over them and the planes part clearly along the axis; +- for a hidden surface, where the triangle of the nearer one ends, when the texel behind it or the two + beside it end on the same straight line, as a curved contour made of strips narrower than a pixel does + not; +- otherwise half way. + +The lines pass takes the nearest crossing along the row of the pixel and the nearest along its column. +For a straight line at distance d, they lie at d / |cos| and d / |sin| of its normal, so +1 / d² = 1 / dx² + 1 / dy², which gives the distance at any angle without knowing it. The line is drawn +with a smooth edge around its half width. + +## Ring + +The binary mask places the silhouette only within half a texel, which would show as a ripple along the +outer edge of the ring. The coverage of the mask under a gaussian, summed over the rows by the edges pass +and over the columns by the ring pass, is the normal tail beyond d / sigma for a straight silhouette at +distance d, which the ring pass inverts for a sub-texel distance. Corners and features thinner than the +gaussian lose coverage faster, so the distance is kept within half a texel of the one to the nearest +covered texel, which the same two passes find exactly. + +## Occlusion + +The composite is depth tested against the canvas, so what stands in front of the selection hides its +outline. It writes the depth of the selection at each pixel, from the mask, moved forward by the spread +of that depth over the pixel, so that the selection passes the test on every sample. The ring takes the +depth of the nearest covered texel, brought forward with its distance from the silhouette, so that it +also shows over the plate the object stands on, which lies in front of the silhouette right below it. + +The outline sets `SelectionOutline::DrawnBit` of the stencil wherever it draws, and the screen space +ambient occlusion pass of the realistic view, which runs after it, leaves those samples as they are. The +outline lies on top of the surfaces, so their occlusion would only darken it, unevenly, in the creases it +marks. + +## Colors and sizes + +The outline is white. Its lines have a width on the model, 0.35 mm for the ring and 0.18 mm for the inner +lines, so they grow as the camera closes in, kept between 2.5 and 5 pixels for the ring and 1.2 and 2.4 for +the inner lines, scaled by the canvas scale. An inner line that would be thinner than 1.2 pixels fades +instead, down to 40%, so that a far selection does not turn into lines. Inner lines are drawn at 75% +opacity. Both have a smooth edge 1.2 pixels wide. + +## Requirements + +The outline needs ARB framebuffer objects, a 16 bit RGBA color renderable texture and the outline +shaders, and it is not drawn without them. Under GLSL 1.10 there is no `gl_VertexID`: crossings fall +back on the depth planes and the half way point, and slivers are not detected. Without 8 stencil bits, +which the two bits used need, the ring stays off the pixels the mask covers and loses the exact inner +edge, and the occlusion pass shades the outline too. diff --git a/resources/shaders/110/gouraud.fs b/resources/shaders/110/gouraud.fs index 50789327c5..7ce85f89f1 100644 --- a/resources/shaders/110/gouraud.fs +++ b/resources/shaders/110/gouraud.fs @@ -35,10 +35,6 @@ uniform vec4 uniform_color_clip_plane_1; uniform vec4 uniform_color_clip_plane_2; uniform SlopeDetection slope; -//BBS: add outline_color -uniform bool is_outline; -uniform sampler2D depth_tex; -uniform vec2 screen_size; #ifdef ENABLE_ENVIRONMENT_MAP @@ -53,8 +49,6 @@ uniform PrintVolumeDetection print_volume; uniform vec3 extruder_printable_heights; const float ONE_OVER_EPSILON = 1e4; -uniform float z_far; -uniform float z_near; // Depth-based shadow map (object-on-object and self shadows). shadow_intensity == 0 disables it. uniform sampler2D shadow_map; @@ -79,71 +73,6 @@ varying vec4 world_pos; varying float world_normal_z; varying vec3 eye_normal; -vec3 getBackfaceColor(vec3 fill) { - float brightness = 0.2126 * fill.r + 0.7152 * fill.g + 0.0722 * fill.b; - return (brightness > 0.75) ? vec3(0.11, 0.165, 0.208) : vec3(0.988, 0.988, 0.988); -} - -// Silhouette edge detection & rendering algorithem by leoneruggiero -// https://www.shadertoy.com/view/DslXz2 -#define INFLATE 1 - -float GetTolerance(float d, float k) -{ - // ------------------------------------------- - // Find a tolerance for depth that is constant - // in view space (k in view space). - // - // tol = k*ddx(ZtoDepth(z)) - // ------------------------------------------- - - float A=- (z_far+z_near)/(z_far-z_near); - float B=-2.0*z_far*z_near /(z_far-z_near); - - d = d*2.0-1.0; - - return -k*(d+A)*(d+A)/B; -} - -float DetectSilho(vec2 fragCoord, vec2 dir) -{ - // ------------------------------------------- - // x0 ___ x1----o - // :\ : - // r0 : \ : r1 - // : \ : - // o---x2 ___ x3 - // - // r0 and r1 are the differences between actual - // and expected (as if x0..3 where on the same - // plane) depth values. - // ------------------------------------------- - - float x0 = abs(texture2D(depth_tex, (fragCoord + dir*-2.0) / screen_size).r); - float x1 = abs(texture2D(depth_tex, (fragCoord + dir*-1.0) / screen_size).r); - float x2 = abs(texture2D(depth_tex, (fragCoord + dir* 0.0) / screen_size).r); - float x3 = abs(texture2D(depth_tex, (fragCoord + dir* 1.0) / screen_size).r); - - float d0 = (x1-x0); - float d1 = (x2-x3); - - float r0 = x1 + d0 - x2; - float r1 = x2 + d1 - x1; - - float tol = GetTolerance(x2, 0.04); - - return smoothstep(0.0, tol*tol, max( - r0*r1, 0.0)); - -} - -float DetectSilho(vec2 fragCoord) -{ - return max( - DetectSilho(fragCoord, vec2(1,0)), // Horizontal - DetectSilho(fragCoord, vec2(0,1)) // Vertical - ); -} - // Returns a lighting multiplier in [1 - shadow_intensity, 1]: < 1 where the fragment is // occluded from the light in the shadow map. 3x3 PCF softens the edges. float shadow_shade() @@ -225,25 +154,10 @@ void main() } float shade = shadow_shade(); - //BBS: add outline_color - if (is_outline) { - color = vec4((vec3(intensity.y) + color.rgb * intensity.x) * shade, color.a); - vec2 fragCoord = gl_FragCoord.xy; - float s = DetectSilho(fragCoord); - // Makes silhouettes thicker. - for(int i=1;i<=INFLATE; i++) - { - s = max(s, DetectSilho(fragCoord.xy + vec2(i, 0))); - s = max(s, DetectSilho(fragCoord.xy + vec2(0, i))); - } - if (s < 0.01) - discard; - gl_FragColor = vec4(mix(color.rgb, getBackfaceColor(color.rgb), s), color.a); - } #ifdef ENABLE_ENVIRONMENT_MAP - else if (use_environment_tex) + if (use_environment_tex) gl_FragColor = vec4((0.45 * texture(environment_tex, normalize(eye_normal).xy * 0.5 + 0.5).xyz + 0.8 * color.rgb * intensity.x) * shade, color.a); -#endif else +#endif gl_FragColor = vec4((vec3(intensity.y) + color.rgb * intensity.x) * shade, color.a); } \ No newline at end of file diff --git a/resources/shaders/110/gouraud.vs b/resources/shaders/110/gouraud.vs index 5ee685c070..2d7e70c1d6 100644 --- a/resources/shaders/110/gouraud.vs +++ b/resources/shaders/110/gouraud.vs @@ -31,8 +31,6 @@ uniform mat4 projection_matrix; uniform mat3 view_normal_matrix; uniform mat4 volume_world_matrix; uniform SlopeDetection slope; -uniform bool is_outline; -uniform vec2 screen_size; // Clipping plane, x = min z, y = max z. Used by the FFF and SLA previews to clip with a top / bottom plane. uniform vec2 z_range; @@ -82,15 +80,6 @@ void main() world_normal_z = slope.actived ? dot(normalize(slope.volume_world_normal_matrix * v_normal), slope.up_direction) : 0.0; gl_Position = projection_matrix * position; - if (is_outline) { - vec3 n = normalize((view_normal_matrix * v_normal).xyz); - vec2 dir = normalize(n.xy); - if (dot(dir, dir) > 0.0) { - //set outline thickness - float px = 3.0; - gl_Position.xy += dir * (px * 2.0 / screen_size) * gl_Position.w; - } - } // Fill in the scalars for fragment shader clipping. Fragments with any of these components lower than zero are discarded. clipping_planes_dots = vec3(dot(world_pos, clipping_plane), world_pos.z - z_range.x, z_range.y - world_pos.z); color_clip_plane_dot = dot(world_pos, color_clip_plane); diff --git a/resources/shaders/110/outline.fs b/resources/shaders/110/outline.fs new file mode 100644 index 0000000000..b691e2f2d8 --- /dev/null +++ b/resources/shaders/110/outline.fs @@ -0,0 +1,219 @@ +#version 110 + +const float INF = 1e9; + +uniform sampler2D mask_tex; +uniform sampler2D depth_tex; +uniform sampler2D edges_tex; +uniform vec2 tex_size; +// false draws the ring around the selection, true the lines along its inner edges. +uniform bool inner; +// The stencil keeps the ring off the samples of the selection, without it the ring stays off covered pixels. +uniform bool use_stencil; +// Widths in pixels: x at least, y at most, z the width on the model in view space units. +uniform vec3 ring_width; +uniform int ring_reach; +uniform float ring_sigma; +// Half the width of an inner line, as ring_width. +uniform vec3 line_width; +uniform int line_reach; +uniform float line_opacity; +uniform vec3 outline_color; +// The projection on view z: window depth is (x * z + y) / (z * z + w), remapped from [-1, 1]. +uniform vec4 depth_coef; +// View space size of a pixel at view depth z: x * -z + y. +uniform vec2 pixel_size_coef; + +vec4 fetch_mask(ivec2 p) +{ + return texture2D(mask_tex, (vec2(p) + 0.5) / tex_size); +} + +float fetch_depth(ivec2 p) +{ + return texture2D(depth_tex, (vec2(p) + 0.5) / tex_size).r; +} + +vec4 fetch_edges(ivec2 p) +{ + return texture2D(edges_tex, (vec2(p) + 0.5) / tex_size); +} + +bool covered(vec4 m) +{ + return m.g > 0.0; +} + +// The texel and its eight neighbors are covered. +bool inside_mask(ivec2 p) +{ + for (int y = -1; y <= 1; ++y) + for (int x = -1; x <= 1; ++x) + if (!covered(fetch_mask(p + ivec2(x, y)))) + return false; + return true; +} + +// Strength and crossing of an inner edge written by outline_edges.fs. +vec2 unpack_edge(float c) +{ + float v = floor(c * 255.0 + 0.5); + float s = floor(v / 16.0); + return vec2(s, v - s * 16.0) / 15.0; +} + +float pixel_size(float z) +{ + return dot(pixel_size_coef, vec2(-z, 1.0)); +} + +// Thicker as the camera closes in, within a range of pixels. +float width_at(vec3 width, float z) +{ + return clamp(width.z / pixel_size(z), width.x, width.y); +} + +// A smooth edge 1.2 pixels wide around width. +float edge_alpha(float width, float d) +{ + return 1.0 - smoothstep(width - 0.6, width + 0.6, d); +} + +float view_z(float depth) +{ + float ndc = depth * 2.0 - 1.0; + return (depth_coef.y - ndc * depth_coef.w) / (ndc * depth_coef.z - depth_coef.x); +} + +float window_depth(float z) +{ + return 0.5 * (depth_coef.x * z + depth_coef.y) / (depth_coef.z * z + depth_coef.w) + 0.5; +} + +// One sided, so that the slope does not span an edge. Uncovered texels keep the cleared depth of 1. +float depth_slope(float d, float before, float after) +{ + float s = INF; + if (before < 1.0) s = abs(d - before); + if (after < 1.0) s = min(s, abs(after - d)); + return s < INF ? s : 0.0; +} + +// The depth of the selection at p, moved forward by its spread over the pixel, so that it passes on every sample. +float surface_depth(ivec2 p) +{ + float d = fetch_depth(p); + float sx = depth_slope(d, fetch_depth(p - ivec2(1, 0)), fetch_depth(p + ivec2(1, 0))); + float sy = depth_slope(d, fetch_depth(p - ivec2(0, 1)), fetch_depth(p + ivec2(0, 1))); + return d - 0.5 * (sx + sy) - 1e-6; +} + +// x beyond which a standard normal has p of its mass, for p up to 0.5 (Abramowitz and Stegun 26.2.23). +float normal_tail_inverse(float p) +{ + float t = sqrt(-2.0 * log(p)); + return t - (2.515517 + t * (0.802853 + t * 0.010328)) / (1.0 + t * (1.432788 + t * (0.189269 + t * 0.001308))); +} + +void render_ring(ivec2 p) +{ + vec4 m = fetch_mask(p); + float alpha = 1.0; + float depth; + if (covered(m)) { + // Only the silhouette of the mask may hold samples off the selection. Inside, a face the mask has and the + // scene culled, say, would get no stencil bit and fill with the ring. + if (!use_stencil || inside_mask(p)) + discard; + depth = surface_depth(p); + } + else { + // The nearest covered texel from the nearest one of each row, and the gaussian coverage around p. + float best = INF; + ivec2 t = p; + float coverage = 0.0; + float weights = 0.0; + for (int j = -ring_reach; j <= ring_reach; ++j) { + vec4 e = fetch_edges(p + ivec2(0, j)); + float w = exp(-float(j * j) / (2.0 * ring_sigma * ring_sigma)); + weights += w; + coverage += w * e.a; + float v = floor(e.b * 255.0 + 0.5); + if (v > 0.0) { + float h = v - 16.0; + float d2 = h * h + float(j * j); + if (d2 < best) { + best = d2; + t = p + ivec2(int(h), j); + } + } + } + if (best >= INF) + discard; + // The coverage of a straight silhouette at dist is the normal tail beyond dist / sigma. Corners and thin + // parts fall off faster, so it is kept within half a texel of the midpoint to the nearest covered texel. + coverage /= weights; + float centers = sqrt(best) - 0.5; + float dist = coverage < 0.5 ? ring_sigma * normal_tail_inverse(max(coverage, 1e-6)) : 0.0; + dist = clamp(dist, centers - 0.5, centers + 0.5); + float z = view_z(fetch_depth(t)); + alpha = edge_alpha(width_at(ring_width, z), dist); + if (alpha <= 0.0) + discard; + m = fetch_mask(t); + // Brought forward with the distance, so that it shows over what the selection stands on. + depth = window_depth(z + 3.0 * (dist + 2.0) * pixel_size(z)); + } + gl_FragColor = vec4(outline_color, alpha); + gl_FragDepth = depth; +} + +void render_lines(ivec2 p) +{ + vec4 m = fetch_mask(p); + if (!covered(m)) + discard; + + // The nearest crossing along the row and along the column. For a straight line at distance d they lie at + // dx = d / |cos| and dy = d / |sin|, so 1 / d^2 = 1 / dx^2 + 1 / dy^2. + float dx = INF; + float sx = 0.0; + for (int i = -line_reach - 1; i <= line_reach; ++i) { + vec2 e = unpack_edge(fetch_edges(p + ivec2(i, 0)).r); + float d = abs(float(i) + e.y); + if (e.x > 0.0 && d < dx) { + dx = d; + sx = e.x; + } + } + float dy = INF; + float sy = 0.0; + for (int j = -line_reach - 1; j <= line_reach; ++j) { + vec2 e = unpack_edge(fetch_edges(p + ivec2(0, j)).g); + float d = abs(float(j) + e.y); + if (e.x > 0.0 && d < dy) { + dy = d; + sy = e.x; + } + } + if (dx >= INF && dy >= INF) + discard; + float d = (dx < INF && dy < INF) ? dx * dy * inversesqrt(max(dx * dx + dy * dy, 1e-8)) : min(dx, dy); + // A line thinner on screen than the narrowest drawn fades instead, so that a far selection is not all lines. + float z = view_z(fetch_depth(p)); + float fade = clamp(line_width.z / (pixel_size(z) * line_width.x), 0.4, 1.0); + float alpha = line_opacity * fade * max(sx, sy) * edge_alpha(width_at(line_width, z), d); + if (alpha <= 0.0) + discard; + gl_FragColor = vec4(outline_color, alpha); + gl_FragDepth = surface_depth(p); +} + +void main() +{ + ivec2 p = ivec2(gl_FragCoord.xy); + if (inner) + render_lines(p); + else + render_ring(p); +} diff --git a/resources/shaders/110/outline_edges.fs b/resources/shaders/110/outline_edges.fs new file mode 100644 index 0000000000..31fd7602e4 --- /dev/null +++ b/resources/shaders/110/outline_edges.fs @@ -0,0 +1,139 @@ +#version 110 + +// A crease fades in as the angle between its faces grows from 25 to 40 degrees. +const float CREASE_COS_START = 0.906; +const float CREASE_COS_FULL = 0.766; + +uniform sampler2D mask_tex; +uniform sampler2D depth_tex; +uniform vec2 tex_size; +uniform mat4 inv_projection_matrix; +// View space size of a pixel at view depth z: x * -z + y. +uniform vec2 pixel_size_coef; +uniform int ring_reach; +uniform float ring_sigma; + +vec2 unpack2(float c) +{ + float v = floor(c * 65535.0 + 0.5); + float hi = floor(v / 256.0); + return vec2(hi, v - hi * 256.0); +} + +vec4 fetch_mask(ivec2 p) +{ + return texture2D(mask_tex, (vec2(p) + 0.5) / tex_size); +} + +float fetch_depth(ivec2 p) +{ + return texture2D(depth_tex, (vec2(p) + 0.5) / tex_size).r; +} + +bool covered(vec4 m) +{ + return m.g > 0.0; +} + +vec3 normal_of(vec4 m) +{ + vec2 e = unpack2(m.r) / 255.0 * 2.0 - 1.0; + vec3 n = vec3(e, 1.0 - abs(e.x) - abs(e.y)); + if (n.z < 0.0) + n.xy = (1.0 - abs(n.yx)) * vec2(n.x >= 0.0 ? 1.0 : -1.0, n.y >= 0.0 ? 1.0 : -1.0); + return normalize(n); +} + +vec3 view_position(ivec2 p, float depth) +{ + vec4 v = inv_projection_matrix * vec4((vec2(p) + 0.5) / tex_size * 2.0 - 1.0, depth * 2.0 - 1.0, 1.0); + return v.xyz / v.w; +} + +// 1 for a turn between neighboring texels of about 7 to 23 degrees: neither flat nor a crease. +float gradual_turn(float cos_angle) +{ + return (1.0 - smoothstep(0.985, 0.997, cos_angle)) * smoothstep(0.88, 0.92, cos_angle); +} + +float pack_edge(float strength, float crossing) +{ + return (floor(strength * 15.0 + 0.5) * 16.0 + floor(clamp(crossing, 0.0, 1.0) * 15.0 + 0.5) + 0.25) / 255.0; +} + +// The inner edge between q and q + dir: how strong it is, and where it crosses from q (0) to q + dir (1). +float inner_edge(ivec2 q, ivec2 dir) +{ + vec4 m0 = fetch_mask(q); + vec4 m1 = fetch_mask(q + dir); + // The silhouette is drawn by the ring. + if (!covered(m0) || !covered(m1)) + return 0.0; + + vec3 n0 = normal_of(m0); + vec3 n1 = normal_of(m1); + vec4 mb = fetch_mask(q - dir); + vec4 ma = fetch_mask(q + 2 * dir); + vec3 nb = covered(mb) ? normal_of(mb) : n0; + vec3 na = covered(ma) ? normal_of(ma) : n1; + float d0 = fetch_depth(q); + float d1 = fetch_depth(q + dir); + float db = fetch_depth(q - dir); + float da = fetch_depth(q + 2 * dir); + vec3 p0 = view_position(q, d0); + vec3 p1 = view_position(q + dir, d1); + // One surface hides the other: they are pixels apart off their planes. + vec3 d = p1 - p0; + float px = dot(pixel_size_coef, vec2(-max(p0.z, p1.z), 1.0)); + float jump = smoothstep(2.0, 4.0, max(abs(dot(n0, d)), abs(dot(n1, d))) / px); + // A step: the texel after the pair lies pixels off the surface before it carried on, both ways, which a surface + // seen edge on does not. + float off = 1e9; + if (covered(mb)) + off = length(p1 - (2.0 * p0 - view_position(q - dir, db))); + if (covered(ma)) + off = min(off, length(p0 - (2.0 * p1 - view_position(q + 2 * dir, da)))); + if (off < 1e9) + jump *= smoothstep(1.0, 2.0, off / px); + // Nor a fillet, which turns a little at every texel on both sides. + jump *= 1.0 - gradual_turn(dot(nb, n0)) * gradual_turn(dot(n1, na)); + float crease = 1.0 - smoothstep(CREASE_COS_FULL, CREASE_COS_START, dot(n0, n1)); + float strength = m0.g == m1.g ? max(jump, crease) : 1.0; + if (strength <= 0.0) + return 0.0; + + // Where the depth planes of both sides meet, when each side is flat over two texels and the planes part + // clearly along dir. + float crossing = 0.5; + if (covered(mb) && covered(ma) && dot(nb, n0) > 0.999 && dot(na, n1) > 0.999) { + float a = d0 - db; + float b = da - d1; + float u = (d1 - d0 - b) / (a - b); + if (abs(a - b) > 0.1 * (abs(a) + abs(b)) && u >= 0.0 && u <= 1.0) + crossing = u; + } + return pack_edge(strength, crossing); +} + +void main() +{ + ivec2 q = ivec2(gl_FragCoord.xy); + + // For the ring around the selection: the nearest covered texel along the row, offset by 16, and the + // coverage of the row under a gaussian, whose sum over the column sets the silhouette between texels. + float nearest = 0.0; + float coverage = 0.0; + float weights = 0.0; + for (int k = -ring_reach; k <= ring_reach; ++k) { + float w = exp(-float(k * k) / (2.0 * ring_sigma * ring_sigma)); + weights += w; + if (covered(fetch_mask(q + ivec2(k, 0)))) { + coverage += w; + if (nearest == 0.0 || abs(float(k)) < abs(nearest - 16.0)) + nearest = float(16 + k); + } + } + + gl_FragColor = vec4(inner_edge(q, ivec2(1, 0)), inner_edge(q, ivec2(0, 1)), + nearest > 0.0 ? (nearest + 0.25) / 255.0 : 0.0, coverage / weights); +} diff --git a/resources/shaders/110/outline_mask.fs b/resources/shaders/110/outline_mask.fs new file mode 100644 index 0000000000..58755b8136 --- /dev/null +++ b/resources/shaders/110/outline_mask.fs @@ -0,0 +1,37 @@ +#version 110 + +const vec3 ZERO = vec3(0.0, 0.0, 0.0); + +// 1 to 65535, told apart between neighboring volumes. +uniform float part_id; + +varying vec3 clipping_planes_dots; +varying vec3 eye_normal; +varying vec3 to_camera; + +// Two bytes in one channel of the 16 bit target, offset so that a truncating conversion keeps them. +float pack2(float hi, float lo) +{ + return (hi * 256.0 + lo + 0.25) / 65535.0; +} + +vec2 oct_encode(vec3 n) +{ + n /= abs(n.x) + abs(n.y) + abs(n.z); + vec2 e = n.z >= 0.0 ? n.xy : (1.0 - abs(n.yx)) * vec2(n.x >= 0.0 ? 1.0 : -1.0, n.y >= 0.0 ? 1.0 : -1.0); + return floor((e * 0.5 + 0.5) * 255.0 + 0.5); +} + +void main() +{ + if (any(lessThan(clipping_planes_dots, ZERO))) + discard; + + // Back faces show through cuts, so every surface is compared by its side facing the camera. + vec3 n = normalize(eye_normal); + if (dot(n, to_camera) < 0.0) + n = -n; + vec2 e = oct_encode(n); + // Without gl_VertexID there are no barycentrics to tell where the triangle ends. + gl_FragColor = vec4(pack2(e.x, e.y), (part_id + 0.25) / 65535.0, 0.0, 0.0); +} diff --git a/resources/shaders/110/outline_mask.vs b/resources/shaders/110/outline_mask.vs new file mode 100644 index 0000000000..a09d2ed882 --- /dev/null +++ b/resources/shaders/110/outline_mask.vs @@ -0,0 +1,30 @@ +#version 110 + +uniform mat4 view_model_matrix; +uniform mat4 projection_matrix; +uniform mat3 view_normal_matrix; +uniform mat4 volume_world_matrix; + +// Clipping plane, x = min z, y = max z. Used by the FFF and SLA previews to clip with a top / bottom plane. +uniform vec2 z_range; +// Clipping plane - general orientation. Used by the SLA gizmo. +uniform vec4 clipping_plane; + +attribute vec3 v_position; +attribute vec3 v_normal; + +varying vec3 clipping_planes_dots; +varying vec3 eye_normal; +varying vec3 to_camera; + +void main() +{ + vec4 world_pos = volume_world_matrix * vec4(v_position, 1.0); + clipping_planes_dots = vec3(dot(world_pos, clipping_plane), world_pos.z - z_range.x, z_range.y - world_pos.z); + + vec4 position = view_model_matrix * vec4(v_position, 1.0); + eye_normal = view_normal_matrix * v_normal; + // projection_matrix[3][3] is 1 only for an orthographic camera, whose view rays all run along -z. + to_camera = mix(-position.xyz, vec3(0.0, 0.0, 1.0), projection_matrix[3][3]); + gl_Position = projection_matrix * position; +} diff --git a/resources/shaders/110/phong.fs b/resources/shaders/110/phong.fs index 7d1e7bfe8c..fd8c5575ec 100644 --- a/resources/shaders/110/phong.fs +++ b/resources/shaders/110/phong.fs @@ -50,10 +50,6 @@ uniform vec4 uniform_color_clip_plane_1; uniform vec4 uniform_color_clip_plane_2; uniform SlopeDetection slope; -//BBS: add outline_color -uniform bool is_outline; -uniform sampler2D depth_tex; -uniform vec2 screen_size; #ifdef ENABLE_ENVIRONMENT_MAP uniform sampler2D environment_tex; @@ -62,8 +58,6 @@ uniform vec2 screen_size; uniform PrintVolumeDetection print_volume; -uniform float z_far; -uniform float z_near; uniform bool enable_ssao; // 1 = the Design tab's studio lighting (studio_shade below); 0 = the two-light model above, which // every other canvas keeps. world_up_eye is world +Z in eye space, for the hemisphere ambient. @@ -88,51 +82,6 @@ varying float world_normal_z; varying vec3 eye_normal; varying vec3 eye_position; -vec3 getBackfaceColor(vec3 fill) { - float brightness = 0.2126 * fill.r + 0.7152 * fill.g + 0.0722 * fill.b; - return (brightness > 0.75) ? vec3(0.11, 0.165, 0.208) : vec3(0.988, 0.988, 0.988); -} - -// Silhouette edge detection & rendering algorithm by leoneruggiero -// https://www.shadertoy.com/view/DslXz2 -#define INFLATE 1 - -float GetTolerance(float d, float k) -{ - float A = -(z_far+z_near)/(z_far-z_near); - float B = -2.0*z_far*z_near /(z_far-z_near); - - d = d*2.0-1.0; - - return -k*(d+A)*(d+A)/B; -} - -float DetectSilho(vec2 fragCoord, vec2 dir) -{ - float x0 = abs(texture2D(depth_tex, (fragCoord + dir*-2.0) / screen_size).r); - float x1 = abs(texture2D(depth_tex, (fragCoord + dir*-1.0) / screen_size).r); - float x2 = abs(texture2D(depth_tex, (fragCoord + dir* 0.0) / screen_size).r); - float x3 = abs(texture2D(depth_tex, (fragCoord + dir* 1.0) / screen_size).r); - - float d0 = (x1-x0); - float d1 = (x2-x3); - - float r0 = x1 + d0 - x2; - float r1 = x2 + d1 - x1; - - float tol = GetTolerance(x2, 0.04); - - return smoothstep(0.0, tol*tol, max( - r0*r1, 0.0)); -} - -float DetectSilho(vec2 fragCoord) -{ - return max( - DetectSilho(fragCoord, vec2(1,0)), - DetectSilho(fragCoord, vec2(0,1)) - ); -} - float compute_ssao_factor(vec3 normal, vec3 view_dir, vec3 eye_pos) { vec3 normal_dx = dFdx(normal); @@ -295,24 +244,10 @@ void main() vec3 lit = (lighting_model == 1) ? studio_shade(color.rgb, normal, view_dir) : (vec3(specular) + window_reflection + color.rgb * diffuse) * PHONG_BRIGHTNESS; - if (is_outline) { - vec3 shaded_rgb = lit * shade; - vec4 shaded_color = vec4(clamp(shaded_rgb, vec3(0.0), vec3(1.0)), color.a); - vec2 fragCoord = gl_FragCoord.xy; - float s = DetectSilho(fragCoord); - for(int i=1;i<=INFLATE; i++) - { - s = max(s, DetectSilho(fragCoord.xy + vec2(i, 0))); - s = max(s, DetectSilho(fragCoord.xy + vec2(0, i))); - } - if (s < 0.01) - discard; - gl_FragColor = vec4(mix(shaded_color.rgb, getBackfaceColor(shaded_color.rgb), s), shaded_color.a); - } #ifdef ENABLE_ENVIRONMENT_MAP - else if (use_environment_tex) + if (use_environment_tex) gl_FragColor = vec4(clamp((0.45 * texture2D(environment_tex, normalize(eye_normal).xy * 0.5 + 0.5).xyz + window_reflection + 0.8 * color.rgb * diffuse) * PHONG_BRIGHTNESS * shade, vec3(0.0), vec3(1.0)), color.a); -#endif else +#endif gl_FragColor = vec4(clamp(lit * shade, vec3(0.0), vec3(1.0)), color.a); } \ No newline at end of file diff --git a/resources/shaders/110/phong.vs b/resources/shaders/110/phong.vs index d857147c28..320971afaa 100644 --- a/resources/shaders/110/phong.vs +++ b/resources/shaders/110/phong.vs @@ -15,8 +15,6 @@ uniform mat4 projection_matrix; uniform mat3 view_normal_matrix; uniform mat4 volume_world_matrix; uniform SlopeDetection slope; -uniform bool is_outline; -uniform vec2 screen_size; // Clipping plane, x = min z, y = max z. Used by the FFF and SLA previews to clip with a top / bottom plane. uniform vec2 z_range; @@ -51,15 +49,6 @@ void main() world_normal_z = slope.actived ? dot(normalize(slope.volume_world_normal_matrix * v_normal), slope.up_direction) : 0.0; gl_Position = projection_matrix * position; - if (is_outline) { - vec3 n = normalize((view_normal_matrix * v_normal).xyz); - vec2 dir = normalize(n.xy); - if (dot(dir, dir) > 0.0) { - //set outline thickness - float px = 3.0; - gl_Position.xy += dir * (px * 2.0 / screen_size) * gl_Position.w; - } - } // Fill in the scalars for fragment shader clipping. Fragments with any of these components lower than zero are discarded. clipping_planes_dots = vec3(dot(world_pos, clipping_plane), world_pos.z - z_range.x, z_range.y - world_pos.z); color_clip_plane_dot = dot(world_pos, color_clip_plane); diff --git a/resources/shaders/110/ssao.fs b/resources/shaders/110/ssao.fs index db266daba1..e2871d8ede 100644 --- a/resources/shaders/110/ssao.fs +++ b/resources/shaders/110/ssao.fs @@ -9,7 +9,6 @@ uniform sampler2D color_texture; uniform sampler2D depth_texture; uniform vec2 inv_tex_size; uniform float z_far; -uniform bool is_outline; // The pass has no normal target to read, so the surface normal is reconstructed from the depth // buffer. inv_projection_matrix unprojects a pixel back into view space and up_view is world +Z // expressed in view space, which is what tells a top surface from a wall. @@ -43,10 +42,6 @@ vec3 view_normal(vec2 uv, vec3 p) void main() { - if (is_outline) { - gl_FragColor = vec4(texture2D(color_texture, tex_coord).rgb, 1.0); - return; - } vec3 base = texture2D(color_texture, tex_coord).rgb; // Nothing was drawn here: occluding the background would only darken the gradient, and its diff --git a/resources/shaders/140/gouraud.fs b/resources/shaders/140/gouraud.fs index 0c9011d634..2a259fe04a 100644 --- a/resources/shaders/140/gouraud.fs +++ b/resources/shaders/140/gouraud.fs @@ -1,7 +1,4 @@ #version 140 -// Multisample depth texture for the anti-aliased outline (see 3DScene.cpp render_with_outline). -// Optional on the GLSL 140 path: if unavailable, fallback to a non-multisample depth texture. -#extension GL_ARB_texture_multisample : enable const vec3 ZERO = vec3(0.0, 0.0, 0.0); //BBS: add grey and orange @@ -38,21 +35,10 @@ uniform vec4 uniform_color_clip_plane_1; uniform vec4 uniform_color_clip_plane_2; uniform SlopeDetection slope; -//BBS: add outline_color -uniform bool is_outline; // ORCA: a part of a translucent filament, drawn as its print would show in premultiplied color, see // GLVolumeCollection::render(). It catches a highlight only with translucent_gloss, in realistic view. uniform bool translucent_filament; uniform bool translucent_gloss; -// The outline is a per-fragment discard mask, which the framebuffer MSAA cannot smooth, so the -// silhouette is resolved per sample from a multisample copy of the outlined model's depth buffer. -#ifdef GL_ARB_texture_multisample -uniform sampler2DMS depth_tex; -uniform int msaa_samples; // samples in depth_tex, 1 when MSAA is off -#else -uniform sampler2D depth_tex; -#endif -uniform vec2 screen_size; #ifdef ENABLE_ENVIRONMENT_MAP uniform sampler2D environment_tex; @@ -66,8 +52,6 @@ uniform PrintVolumeDetection print_volume; uniform vec3 extruder_printable_heights; const float ONE_OVER_EPSILON = 1e4; -uniform float z_far; -uniform float z_near; // Depth-based shadow map (object-on-object and self shadows). shadow_intensity == 0 disables it. uniform sampler2D shadow_map; @@ -92,113 +76,6 @@ in vec4 world_pos; in float world_normal_z; in vec3 eye_normal; -vec3 getBackfaceColor(vec3 fill) { - float brightness = 0.2126 * fill.r + 0.7152 * fill.g + 0.0722 * fill.b; - return (brightness > 0.75) ? vec3(0.11, 0.165, 0.208) : vec3(0.988, 0.988, 0.988); -} - -// Silhouette edge detection & rendering algorithem by leoneruggiero -// https://www.shadertoy.com/view/DslXz2 -#define INFLATE 1 - -float GetTolerance(float d, float k) -{ - // ------------------------------------------- - // Find a tolerance for depth that is constant - // in view space (k in view space). - // - // tol = k*ddx(ZtoDepth(z)) - // ------------------------------------------- - - float A=- (z_far+z_near)/(z_far-z_near); - float B=-2.0*z_far*z_near /(z_far-z_near); - - d = d*2.0-1.0; - - return -k*(d+A)*(d+A)/B; -} - -// Depth of sample s at integer pixel coord. -#ifdef GL_ARB_texture_multisample -float FetchDepth(ivec2 coord, int s) -{ - // texelFetch has no wrap mode, so clamp to the edge texel (sampler2D used CLAMP_TO_EDGE). - ivec2 sz = textureSize(depth_tex); - return abs(texelFetch(depth_tex, clamp(coord, ivec2(0), sz - 1), s).r); -} -#else -float FetchDepth(ivec2 coord, int s) -{ - return abs(texture(depth_tex, (vec2(coord) + 0.5) / screen_size).r); -} -#endif - -float DetectSilho(ivec2 coord, ivec2 dir, int s) -{ - // ------------------------------------------- - // x0 ___ x1----o - // :\ : - // r0 : \ : r1 - // : \ : - // o---x2 ___ x3 - // - // r0 and r1 are the differences between actual - // and expected (as if x0..3 where on the same - // plane) depth values. - // ------------------------------------------- - float x0 = FetchDepth(coord + dir*-2, s); - float x1 = FetchDepth(coord + dir*-1, s); - float x2 = FetchDepth(coord, s); - float x3 = FetchDepth(coord + dir* 1, s); - - float d0 = (x1-x0); - float d1 = (x2-x3); - - float r0 = x1 + d0 - x2; - float r1 = x2 + d1 - x1; - - float tol = GetTolerance(x2, 0.04); - - return smoothstep(0.0, tol*tol, max( - r0*r1, 0.0)); -} - -float DetectSilho(ivec2 coord, int s) -{ - return max( - DetectSilho(coord, ivec2(1,0), s), // Horizontal - DetectSilho(coord, ivec2(0,1), s) // Vertical - ); -} - -// Full response of one sample. Reduce the max() per sample and average only afterwards: -// max(mean) <= mean(max), and averaging first hollows out diagonal and curved lines. -float DetectSilhoSample(ivec2 coord, int s) -{ - float v = DetectSilho(coord, s); - // Makes silhouettes thicker. - for (int i = 1; i <= INFLATE; ++i) - { - v = max(v, DetectSilho(coord + ivec2(i, 0), s)); - v = max(v, DetectSilho(coord + ivec2(0, i), s)); - } - return v; -} - -// Average the per-sample coverage into the sub-pixel anti-aliasing of the line. -float DetectSilho(vec2 fragCoord) -{ - ivec2 coord = ivec2(fragCoord); -#ifdef GL_ARB_texture_multisample - int n = max(msaa_samples, 1); -#else - const int n = 1; -#endif - float acc = 0.0; - for (int s = 0; s < n; ++s) - acc += DetectSilhoSample(coord, s); - return acc / float(n); -} - // Returns a lighting multiplier in [1 - shadow_intensity, 1]: < 1 where the fragment is // occluded from the light in the shadow map. 3x3 PCF softens the edges. float shadow_shade() @@ -290,21 +167,12 @@ void main() } float shade = shadow_shade(); - //BBS: add outline_color - if (is_outline) { - color = vec4((vec3(intensity.y) + color.rgb * intensity.x) * shade, color.a); - float s = DetectSilho(gl_FragCoord.xy); - if (s < 0.01) - discard; - out_color = vec4(mix(color.rgb, getBackfaceColor(color.rgb), s), color.a); - if (translucent_filament) - out_color.rgb *= out_color.a; - } #ifdef ENABLE_ENVIRONMENT_MAP - else if (use_environment_tex) + if (use_environment_tex) out_color = vec4((0.45 * texture(environment_tex, normalize(eye_normal).xy * 0.5 + 0.5).xyz + 0.8 * color.rgb * intensity.x) * shade, color.a); + else #endif - else if (translucent_filament) + if (translucent_filament) out_color = translucent_filament_color(color.rgb * intensity.x * shade, color.a, translucent_gloss ? vec3(intensity.y * shade) : ZERO, abs(normalize(eye_normal).z)); else diff --git a/resources/shaders/140/gouraud.vs b/resources/shaders/140/gouraud.vs index 7f753a3059..5777a64102 100644 --- a/resources/shaders/140/gouraud.vs +++ b/resources/shaders/140/gouraud.vs @@ -31,8 +31,6 @@ uniform mat4 projection_matrix; uniform mat3 view_normal_matrix; uniform mat4 volume_world_matrix; uniform SlopeDetection slope; -uniform bool is_outline; -uniform vec2 screen_size; // Clipping plane, x = min z, y = max z. Used by the FFF and SLA previews to clip with a top / bottom plane. uniform vec2 z_range; @@ -82,15 +80,6 @@ void main() world_normal_z = slope.actived ? dot(normalize(slope.volume_world_normal_matrix * v_normal), slope.up_direction) : 0.0; gl_Position = projection_matrix * position; - if (is_outline) { - vec3 n = normalize((view_normal_matrix * v_normal).xyz); - vec2 dir = normalize(n.xy); - if (dot(dir, dir) > 0.0) { - //set outline thickness - float px = 3.0; - gl_Position.xy += dir * (px * 2.0 / screen_size) * gl_Position.w; - } - } // Fill in the scalars for fragment shader clipping. Fragments with any of these components lower than zero are discarded. clipping_planes_dots = vec3(dot(world_pos, clipping_plane), world_pos.z - z_range.x, z_range.y - world_pos.z); color_clip_plane_dot = dot(world_pos, color_clip_plane); diff --git a/resources/shaders/140/outline.fs b/resources/shaders/140/outline.fs new file mode 100644 index 0000000000..338de9f4db --- /dev/null +++ b/resources/shaders/140/outline.fs @@ -0,0 +1,223 @@ +#version 140 + +const float INF = 1e9; + +uniform sampler2D mask_tex; +uniform sampler2D depth_tex; +uniform sampler2D edges_tex; +// false draws the ring around the selection, true the lines along its inner edges. +uniform bool inner; +// The stencil keeps the ring off the samples of the selection, without it the ring stays off covered pixels. +uniform bool use_stencil; +// Widths in pixels: x at least, y at most, z the width on the model in view space units. +uniform vec3 ring_width; +uniform int ring_reach; +uniform float ring_sigma; +// Half the width of an inner line, as ring_width. +uniform vec3 line_width; +uniform int line_reach; +uniform float line_opacity; +uniform vec3 outline_color; +// The projection on view z: window depth is (x * z + y) / (z * z + w), remapped from [-1, 1]. +uniform vec4 depth_coef; +// View space size of a pixel at view depth z: x * -z + y. +uniform vec2 pixel_size_coef; + +out vec4 out_color; + +ivec2 tex_size; + +vec4 fetch_mask(ivec2 p) +{ + return texelFetch(mask_tex, clamp(p, ivec2(0), tex_size - 1), 0); +} + +float fetch_depth(ivec2 p) +{ + return texelFetch(depth_tex, clamp(p, ivec2(0), tex_size - 1), 0).r; +} + +vec4 fetch_edges(ivec2 p) +{ + return texelFetch(edges_tex, clamp(p, ivec2(0), tex_size - 1), 0); +} + +bool covered(vec4 m) +{ + return m.g > 0.0; +} + +// The texel and its eight neighbors are covered. +bool inside_mask(ivec2 p) +{ + for (int y = -1; y <= 1; ++y) + for (int x = -1; x <= 1; ++x) + if (!covered(fetch_mask(p + ivec2(x, y)))) + return false; + return true; +} + +// Strength and crossing of an inner edge written by outline_edges.fs. +vec2 unpack_edge(float c) +{ + float v = floor(c * 255.0 + 0.5); + float s = floor(v / 16.0); + return vec2(s, v - s * 16.0) / 15.0; +} + +float pixel_size(float z) +{ + return dot(pixel_size_coef, vec2(-z, 1.0)); +} + +// Thicker as the camera closes in, within a range of pixels. +float width_at(vec3 width, float z) +{ + return clamp(width.z / pixel_size(z), width.x, width.y); +} + +// A smooth edge 1.2 pixels wide around width. +float edge_alpha(float width, float d) +{ + return 1.0 - smoothstep(width - 0.6, width + 0.6, d); +} + +float view_z(float depth) +{ + float ndc = depth * 2.0 - 1.0; + return (depth_coef.y - ndc * depth_coef.w) / (ndc * depth_coef.z - depth_coef.x); +} + +float window_depth(float z) +{ + return 0.5 * (depth_coef.x * z + depth_coef.y) / (depth_coef.z * z + depth_coef.w) + 0.5; +} + +// One sided, so that the slope does not span an edge. Uncovered texels keep the cleared depth of 1. +float depth_slope(float d, float before, float after) +{ + float s = INF; + if (before < 1.0) s = abs(d - before); + if (after < 1.0) s = min(s, abs(after - d)); + return s < INF ? s : 0.0; +} + +// The depth of the selection at p, moved forward by its spread over the pixel, so that it passes on every sample. +float surface_depth(ivec2 p) +{ + float d = fetch_depth(p); + float sx = depth_slope(d, fetch_depth(p - ivec2(1, 0)), fetch_depth(p + ivec2(1, 0))); + float sy = depth_slope(d, fetch_depth(p - ivec2(0, 1)), fetch_depth(p + ivec2(0, 1))); + return d - 0.5 * (sx + sy) - 1e-6; +} + +// x beyond which a standard normal has p of its mass, for p up to 0.5 (Abramowitz and Stegun 26.2.23). +float normal_tail_inverse(float p) +{ + float t = sqrt(-2.0 * log(p)); + return t - (2.515517 + t * (0.802853 + t * 0.010328)) / (1.0 + t * (1.432788 + t * (0.189269 + t * 0.001308))); +} + +void render_ring(ivec2 p) +{ + vec4 m = fetch_mask(p); + float alpha = 1.0; + float depth; + if (covered(m)) { + // Only the silhouette of the mask may hold samples off the selection. Inside, a face the mask has and the + // scene culled, say, would get no stencil bit and fill with the ring. + if (!use_stencil || inside_mask(p)) + discard; + depth = surface_depth(p); + } + else { + // The nearest covered texel from the nearest one of each row, and the gaussian coverage around p. + float best = INF; + ivec2 t = p; + float coverage = 0.0; + float weights = 0.0; + for (int j = -ring_reach; j <= ring_reach; ++j) { + vec4 e = fetch_edges(p + ivec2(0, j)); + float w = exp(-float(j * j) / (2.0 * ring_sigma * ring_sigma)); + weights += w; + coverage += w * e.a; + float v = floor(e.b * 255.0 + 0.5); + if (v > 0.0) { + float h = v - 16.0; + float d2 = h * h + float(j * j); + if (d2 < best) { + best = d2; + t = p + ivec2(int(h), j); + } + } + } + if (best >= INF) + discard; + m = fetch_mask(t); + // The coverage of a straight silhouette at dist is the normal tail beyond dist / sigma. Corners and thin + // parts fall off faster, so it is kept within half a texel of the midpoint to the nearest covered texel. + coverage /= weights; + float centers = sqrt(best) - 0.5; + float dist = coverage < 0.5 ? ring_sigma * normal_tail_inverse(max(coverage, 1e-6)) : 0.0; + dist = clamp(dist, centers - 0.5, centers + 0.5); + float z = view_z(fetch_depth(t)); + alpha = edge_alpha(width_at(ring_width, z), dist); + if (alpha <= 0.0) + discard; + // Brought forward with the distance, so that it shows over what the selection stands on. + depth = window_depth(z + 3.0 * (dist + 2.0) * pixel_size(z)); + } + out_color = vec4(outline_color, alpha); + gl_FragDepth = depth; +} + +void render_lines(ivec2 p) +{ + vec4 m = fetch_mask(p); + if (!covered(m)) + discard; + + // The nearest crossing along the row and along the column. For a straight line at distance d they lie at + // dx = d / |cos| and dy = d / |sin|, so 1 / d^2 = 1 / dx^2 + 1 / dy^2. + float dx = INF; + float sx = 0.0; + for (int i = -line_reach - 1; i <= line_reach; ++i) { + vec2 e = unpack_edge(fetch_edges(p + ivec2(i, 0)).r); + float d = abs(float(i) + e.y); + if (e.x > 0.0 && d < dx) { + dx = d; + sx = e.x; + } + } + float dy = INF; + float sy = 0.0; + for (int j = -line_reach - 1; j <= line_reach; ++j) { + vec2 e = unpack_edge(fetch_edges(p + ivec2(0, j)).g); + float d = abs(float(j) + e.y); + if (e.x > 0.0 && d < dy) { + dy = d; + sy = e.x; + } + } + if (dx >= INF && dy >= INF) + discard; + float d = (dx < INF && dy < INF) ? dx * dy * inversesqrt(max(dx * dx + dy * dy, 1e-8)) : min(dx, dy); + // A line thinner on screen than the narrowest drawn fades instead, so that a far selection is not all lines. + float z = view_z(fetch_depth(p)); + float fade = clamp(line_width.z / (pixel_size(z) * line_width.x), 0.4, 1.0); + float alpha = line_opacity * fade * max(sx, sy) * edge_alpha(width_at(line_width, z), d); + if (alpha <= 0.0) + discard; + out_color = vec4(outline_color, alpha); + gl_FragDepth = surface_depth(p); +} + +void main() +{ + tex_size = textureSize(mask_tex, 0); + ivec2 p = ivec2(gl_FragCoord.xy); + if (inner) + render_lines(p); + else + render_ring(p); +} diff --git a/resources/shaders/140/outline_edges.fs b/resources/shaders/140/outline_edges.fs new file mode 100644 index 0000000000..c93f321eb3 --- /dev/null +++ b/resources/shaders/140/outline_edges.fs @@ -0,0 +1,209 @@ +#version 140 + +// Farthest triangle edge distance stored by outline_mask.fs, in pixels. +const float EXIT_REACH = 4.0; +// A crease fades in as the angle between its faces grows from 25 to 40 degrees. +const float CREASE_COS_START = 0.906; +const float CREASE_COS_FULL = 0.766; + +uniform sampler2D mask_tex; +uniform sampler2D depth_tex; +uniform mat4 inv_projection_matrix; +// View space size of a pixel at view depth z: x * -z + y. +uniform vec2 pixel_size_coef; +uniform int ring_reach; +uniform float ring_sigma; + +out vec4 out_color; + +ivec2 tex_size; + +vec2 unpack2(float c) +{ + float v = floor(c * 65535.0 + 0.5); + float hi = floor(v / 256.0); + return vec2(hi, v - hi * 256.0); +} + +vec4 fetch_mask(ivec2 p) +{ + return texelFetch(mask_tex, clamp(p, ivec2(0), tex_size - 1), 0); +} + +float fetch_depth(ivec2 p) +{ + return texelFetch(depth_tex, clamp(p, ivec2(0), tex_size - 1), 0).r; +} + +bool covered(vec4 m) +{ + return m.g > 0.0; +} + +vec3 normal_of(vec4 m) +{ + vec2 e = unpack2(m.r) / 255.0 * 2.0 - 1.0; + vec3 n = vec3(e, 1.0 - abs(e.x) - abs(e.y)); + if (n.z < 0.0) + n.xy = (1.0 - abs(n.yx)) * vec2(n.x >= 0.0 ? 1.0 : -1.0, n.y >= 0.0 ? 1.0 : -1.0); + return normalize(n); +} + +// Pixels to the edge of the triangle under the texel along an axis direction. +float exit_along(vec4 m, ivec2 dir) +{ + vec2 e = unpack2(dir.x != 0 ? m.b : m.a) / 255.0 * EXIT_REACH; + return dir.x + dir.y > 0 ? e.x : e.y; +} + +vec3 view_position(ivec2 p, float depth) +{ + vec4 v = inv_projection_matrix * vec4((vec2(p) + 0.5) / vec2(tex_size) * 2.0 - 1.0, depth * 2.0 - 1.0, 1.0); + return v.xyz / v.w; +} + +// Under a pixel along both axes: the normal of such a sliver may be far off its surface. +bool tiny_triangle(vec4 m) +{ + vec4 e = vec4(unpack2(m.b), unpack2(m.a)) / 255.0 * EXIT_REACH; + return e.x + e.y < 1.0 && e.z + e.w < 1.0; +} + +// The normal of the texel, or of one beside it when the texel lies on a tiny triangle. +vec3 surface_normal(vec4 m, vec4 l, vec4 r) +{ + if (tiny_triangle(m)) { + if (covered(l) && !tiny_triangle(l)) + return normal_of(l); + if (covered(r) && !tiny_triangle(r)) + return normal_of(r); + } + return normal_of(m); +} + +// One surface hides the other: d, between them, is pixels long off their planes. +float jump_strength(vec3 n0, vec3 n1, vec3 d, float px) +{ + float gap = max(abs(dot(n0, d)), abs(dot(n1, d))); + return smoothstep(2.0, 4.0, gap / px); +} + +// 1 for a turn between neighboring texels of about 7 to 23 degrees: neither flat nor a crease. +float gradual_turn(float cos_angle) +{ + return (1.0 - smoothstep(0.985, 0.997, cos_angle)) * smoothstep(0.88, 0.92, cos_angle); +} + +float pack_edge(float strength, float crossing) +{ + return (floor(strength * 15.0 + 0.5) * 16.0 + floor(clamp(crossing, 0.0, 1.0) * 15.0 + 0.5) + 0.25) / 255.0; +} + +// The inner edge between q and q + dir: how strong it is, and where it crosses from q (0) to q + dir (1). +float inner_edge(ivec2 q, ivec2 dir) +{ + vec4 m0 = fetch_mask(q); + vec4 m1 = fetch_mask(q + dir); + // The silhouette is drawn by the ring. + if (!covered(m0) || !covered(m1)) + return 0.0; + + vec3 n0 = normal_of(m0); + vec3 n1 = normal_of(m1); + float d0 = fetch_depth(q); + float d1 = fetch_depth(q + dir); + vec3 p0 = view_position(q, d0); + vec3 p1 = view_position(q + dir, d1); + vec3 d = p1 - p0; + float px = dot(pixel_size_coef, vec2(-max(p0.z, p1.z), 1.0)); + bool same_part = m0.g == m1.g; + if (same_part && jump_strength(n0, n1, d, px) <= 0.0 && dot(n0, n1) >= CREASE_COS_START) + return 0.0; + + // Beside the pair, and before and after it along dir. + ivec2 perp = ivec2(dir.y, dir.x); + vec4 l0 = fetch_mask(q - perp); + vec4 r0 = fetch_mask(q + perp); + vec4 l1 = fetch_mask(q + dir - perp); + vec4 r1 = fetch_mask(q + dir + perp); + vec4 mb = fetch_mask(q - dir); + vec4 ma = fetch_mask(q + 2 * dir); + n0 = surface_normal(m0, l0, r0); + n1 = surface_normal(m1, l1, r1); + vec3 nb = covered(mb) ? normal_of(mb) : n0; + vec3 na = covered(ma) ? normal_of(ma) : n1; + float db = fetch_depth(q - dir); + float da = fetch_depth(q + 2 * dir); + float jump = jump_strength(n0, n1, d, px); + // A step: the texel after the pair lies pixels off the surface before it carried on, both ways, which a surface + // seen edge on does not. + float off = 1e9; + if (covered(mb)) + off = length(p1 - (2.0 * p0 - view_position(q - dir, db))); + if (covered(ma)) + off = min(off, length(p0 - (2.0 * p1 - view_position(q + 2 * dir, da)))); + if (off < 1e9) + jump *= smoothstep(1.0, 2.0, off / px); + // Nor a fillet, which turns a little at every texel on both sides. + jump *= 1.0 - gradual_turn(dot(nb, n0)) * gradual_turn(dot(n1, na)); + float crease = 1.0 - smoothstep(CREASE_COS_FULL, CREASE_COS_START, dot(n0, n1)); + float strength = same_part ? max(jump, crease) : 1.0; + if (strength <= 0.0) + return 0.0; + + // Where the triangle under q ends and the one under q + dir starts: together when they share the edge. + float lo = exit_along(m0, dir); + float hi = 1.0 - exit_along(m1, -dir); + if (same_part && abs(hi - lo) < 0.15) + return pack_edge(strength, 0.5 * (lo + hi)); + // Where the depth planes of both sides meet, when each side is flat over two texels and the planes part + // clearly along dir. + if (covered(mb) && covered(ma) && dot(nb, n0) > 0.999 && dot(na, n1) > 0.999) { + float a = d0 - db; + float b = da - d1; + float u = (d1 - d0 - b) / (a - b); + if (abs(a - b) > 0.1 * (abs(a) + abs(b)) && u >= 0.0 && u <= 1.0) + return pack_edge(strength, u); + } + // Where the nearer surface ends, when its triangle ends on a straight edge: the texel behind it, or the + // texels beside it, end on the same line. + float crossing = 0.5; + if (jump > 0.0) { + if (p0.z > p1.z) { + if ((covered(mb) && abs(exit_along(mb, dir) - min(lo + 1.0, EXIT_REACH)) < 0.1) || + (covered(l0) && covered(r0) && abs(exit_along(l0, dir) + exit_along(r0, dir) - 2.0 * lo) < 0.1)) + crossing = lo; + } + else { + float e = 1.0 - hi; + if ((covered(ma) && abs(exit_along(ma, -dir) - min(e + 1.0, EXIT_REACH)) < 0.1) || + (covered(l1) && covered(r1) && abs(exit_along(l1, -dir) + exit_along(r1, -dir) - 2.0 * e) < 0.1)) + crossing = hi; + } + } + return pack_edge(strength, crossing); +} + +void main() +{ + tex_size = textureSize(mask_tex, 0); + ivec2 q = ivec2(gl_FragCoord.xy); + + // For the ring around the selection: the nearest covered texel along the row, offset by 16, and the + // coverage of the row under a gaussian, whose sum over the column sets the silhouette between texels. + float nearest = 0.0; + float coverage = 0.0; + float weights = 0.0; + for (int k = -ring_reach; k <= ring_reach; ++k) { + float w = exp(-float(k * k) / (2.0 * ring_sigma * ring_sigma)); + weights += w; + if (covered(fetch_mask(q + ivec2(k, 0)))) { + coverage += w; + if (nearest == 0.0 || abs(k) < abs(int(nearest) - 16)) + nearest = float(16 + k); + } + } + + out_color = vec4(inner_edge(q, ivec2(1, 0)), inner_edge(q, ivec2(0, 1)), + nearest > 0.0 ? (nearest + 0.25) / 255.0 : 0.0, coverage / weights); +} diff --git a/resources/shaders/140/outline_mask.fs b/resources/shaders/140/outline_mask.fs new file mode 100644 index 0000000000..39ebbe84e1 --- /dev/null +++ b/resources/shaders/140/outline_mask.fs @@ -0,0 +1,54 @@ +#version 140 + +const vec3 ZERO = vec3(0.0, 0.0, 0.0); +// Farthest triangle edge distance stored, in pixels. +const float EXIT_REACH = 4.0; + +// 1 to 65535, told apart between neighboring volumes. +uniform float part_id; + +in vec3 clipping_planes_dots; +in vec3 eye_normal; +in vec3 to_camera; +noperspective in vec3 barycentric; + +out vec4 out_color; + +// Two bytes in one channel of the 16 bit target, offset so that a truncating conversion keeps them. +float pack2(float hi, float lo) +{ + return (hi * 256.0 + lo + 0.25) / 65535.0; +} + +vec2 oct_encode(vec3 n) +{ + n /= abs(n.x) + abs(n.y) + abs(n.z); + vec2 e = n.z >= 0.0 ? n.xy : (1.0 - abs(n.yx)) * vec2(n.x >= 0.0 ? 1.0 : -1.0, n.y >= 0.0 ? 1.0 : -1.0); + return floor((e * 0.5 + 0.5) * 255.0 + 0.5); +} + +// Pixels to the edge of the triangle along the screen direction over which the barycentrics change by d. +float exit_distance(vec3 d) +{ + vec3 t = vec3(EXIT_REACH); + if (d.x < 0.0) t.x = barycentric.x / -d.x; + if (d.y < 0.0) t.y = barycentric.y / -d.y; + if (d.z < 0.0) t.z = barycentric.z / -d.z; + return floor(clamp(min(t.x, min(t.y, t.z)) / EXIT_REACH, 0.0, 1.0) * 255.0 + 0.5); +} + +void main() +{ + if (any(lessThan(clipping_planes_dots, ZERO))) + discard; + + // Back faces show through cuts, so every surface is compared by its side facing the camera. + vec3 n = normalize(eye_normal); + if (dot(n, to_camera) < 0.0) + n = -n; + vec2 e = oct_encode(n); + vec3 bx = dFdx(barycentric); + vec3 by = dFdy(barycentric); + out_color = vec4(pack2(e.x, e.y), (part_id + 0.25) / 65535.0, + pack2(exit_distance(bx), exit_distance(-bx)), pack2(exit_distance(by), exit_distance(-by))); +} diff --git a/resources/shaders/140/outline_mask.vs b/resources/shaders/140/outline_mask.vs new file mode 100644 index 0000000000..41b0ed884f --- /dev/null +++ b/resources/shaders/140/outline_mask.vs @@ -0,0 +1,33 @@ +#version 140 + +uniform mat4 view_model_matrix; +uniform mat4 projection_matrix; +uniform mat3 view_normal_matrix; +uniform mat4 volume_world_matrix; + +// Clipping plane, x = min z, y = max z. Used by the FFF and SLA previews to clip with a top / bottom plane. +uniform vec2 z_range; +// Clipping plane - general orientation. Used by the SLA gizmo. +uniform vec4 clipping_plane; + +in vec3 v_position; +in vec3 v_normal; + +out vec3 clipping_planes_dots; +out vec3 eye_normal; +out vec3 to_camera; +noperspective out vec3 barycentric; + +void main() +{ + vec4 world_pos = volume_world_matrix * vec4(v_position, 1.0); + clipping_planes_dots = vec3(dot(world_pos, clipping_plane), world_pos.z - z_range.x, z_range.y - world_pos.z); + + vec4 position = view_model_matrix * vec4(v_position, 1.0); + eye_normal = view_normal_matrix * v_normal; + // projection_matrix[3][3] is 1 only for an orthographic camera, whose view rays all run along -z. + to_camera = mix(-position.xyz, vec3(0.0, 0.0, 1.0), projection_matrix[3][3]); + // GLModel gives every triangle three vertices of its own. + barycentric = vec3(equal(ivec3(gl_VertexID % 3), ivec3(0, 1, 2))); + gl_Position = projection_matrix * position; +} diff --git a/resources/shaders/140/phong.fs b/resources/shaders/140/phong.fs index c0cbc1c144..ff861126e6 100644 --- a/resources/shaders/140/phong.fs +++ b/resources/shaders/140/phong.fs @@ -1,7 +1,4 @@ #version 140 -// Multisample depth texture for the anti-aliased outline (see 3DScene.cpp render_with_outline). -// Optional on the GLSL 140 path: if unavailable, fallback to a non-multisample depth texture. -#extension GL_ARB_texture_multisample : enable const vec3 ZERO = vec3(0.0, 0.0, 0.0); const vec3 LightRed = vec3(0.78, 0.0, 0.0); @@ -53,21 +50,10 @@ uniform vec4 uniform_color_clip_plane_1; uniform vec4 uniform_color_clip_plane_2; uniform SlopeDetection slope; -//BBS: add outline_color -uniform bool is_outline; // ORCA: a part of a translucent filament, drawn as its print would show in premultiplied color, see // GLVolumeCollection::render(). It catches a highlight only with translucent_gloss, in realistic view. uniform bool translucent_filament; uniform bool translucent_gloss; -// The outline is a per-fragment discard mask, which the framebuffer MSAA cannot smooth, so the -// silhouette is resolved per sample from a multisample copy of the outlined model's depth buffer. -#ifdef GL_ARB_texture_multisample -uniform sampler2DMS depth_tex; -uniform int msaa_samples; // samples in depth_tex, 1 when MSAA is off -#else -uniform sampler2D depth_tex; -#endif -uniform vec2 screen_size; #ifdef ENABLE_ENVIRONMENT_MAP uniform sampler2D environment_tex; @@ -76,8 +62,6 @@ uniform vec2 screen_size; uniform PrintVolumeDetection print_volume; -uniform float z_far; -uniform float z_near; uniform bool enable_ssao; // 1 = the Design tab's studio lighting (studio_shade below); 0 = the two-light model above, which // every other canvas keeps. world_up_eye is world +Z in eye space, for the hemisphere ambient. @@ -112,95 +96,6 @@ vec4 translucent_filament_color(vec3 diffuse, float alpha, vec3 highlight, float out vec4 out_color; -vec3 getBackfaceColor(vec3 fill) { - float brightness = 0.2126 * fill.r + 0.7152 * fill.g + 0.0722 * fill.b; - return (brightness > 0.75) ? vec3(0.11, 0.165, 0.208) : vec3(0.988, 0.988, 0.988); -} - -// Silhouette edge detection & rendering algorithm by leoneruggiero -// https://www.shadertoy.com/view/DslXz2 -#define INFLATE 1 - -float GetTolerance(float d, float k) -{ - float A=- (z_far+z_near)/(z_far-z_near); - float B=-2.0*z_far*z_near /(z_far-z_near); - - d = d*2.0-1.0; - - return -k*(d+A)*(d+A)/B; -} - -// Depth of sample s at integer pixel coord. -#ifdef GL_ARB_texture_multisample -float FetchDepth(ivec2 coord, int s) -{ - // texelFetch has no wrap mode, so clamp to the edge texel (sampler2D used CLAMP_TO_EDGE). - ivec2 sz = textureSize(depth_tex); - return abs(texelFetch(depth_tex, clamp(coord, ivec2(0), sz - 1), s).r); -} -#else -float FetchDepth(ivec2 coord, int s) -{ - return abs(texture(depth_tex, (vec2(coord) + 0.5) / screen_size).r); -} -#endif - -float DetectSilho(ivec2 coord, ivec2 dir, int s) -{ - float x0 = FetchDepth(coord + dir*-2, s); - float x1 = FetchDepth(coord + dir*-1, s); - float x2 = FetchDepth(coord, s); - float x3 = FetchDepth(coord + dir* 1, s); - - float d0 = (x1-x0); - float d1 = (x2-x3); - - float r0 = x1 + d0 - x2; - float r1 = x2 + d1 - x1; - - float tol = GetTolerance(x2, 0.04); - - return smoothstep(0.0, tol*tol, max( - r0*r1, 0.0)); -} - -float DetectSilho(ivec2 coord, int s) -{ - return max( - DetectSilho(coord, ivec2(1,0), s), - DetectSilho(coord, ivec2(0,1), s) - ); -} - -// Full response of one sample. Reduce the max() per sample and average only afterwards: -// max(mean) <= mean(max), and averaging first hollows out diagonal and curved lines. -float DetectSilhoSample(ivec2 coord, int s) -{ - float v = DetectSilho(coord, s); - // Makes silhouettes thicker. - for (int i = 1; i <= INFLATE; ++i) - { - v = max(v, DetectSilho(coord + ivec2(i, 0), s)); - v = max(v, DetectSilho(coord + ivec2(0, i), s)); - } - return v; -} - -// Average the per-sample coverage into the sub-pixel anti-aliasing of the line. -float DetectSilho(vec2 fragCoord) -{ - ivec2 coord = ivec2(fragCoord); -#ifdef GL_ARB_texture_multisample - int n = max(msaa_samples, 1); -#else - const int n = 1; -#endif - float acc = 0.0; - for (int s = 0; s < n; ++s) - acc += DetectSilhoSample(coord, s); - return acc / float(n); -} - float compute_ssao_factor(vec3 normal, vec3 view_dir, vec3 eye_pos) { vec3 normal_dx = dFdx(normal); @@ -364,21 +259,12 @@ void main() vec3 lit = (lighting_model == 1) ? studio_shade(color.rgb, normal, view_dir) : (vec3(specular) + window_reflection + color.rgb * diffuse) * PHONG_BRIGHTNESS; - if (is_outline) { - vec3 shaded_rgb = lit * shade; - vec4 shaded_color = vec4(clamp(shaded_rgb, vec3(0.0), vec3(1.0)), color.a); - float s = DetectSilho(gl_FragCoord.xy); - if (s < 0.01) - discard; - out_color = vec4(mix(shaded_color.rgb, getBackfaceColor(shaded_color.rgb), s), shaded_color.a); - if (translucent_filament) - out_color.rgb *= out_color.a; - } #ifdef ENABLE_ENVIRONMENT_MAP - else if (use_environment_tex) + if (use_environment_tex) out_color = vec4(clamp((0.45 * texture(environment_tex, normalize(eye_normal).xy * 0.5 + 0.5).xyz + window_reflection + 0.8 * color.rgb * diffuse) * PHONG_BRIGHTNESS * shade, vec3(0.0), vec3(1.0)), color.a); + else #endif - else if (translucent_filament) + if (translucent_filament) out_color = translucent_filament_color(clamp(color.rgb * diffuse * PHONG_BRIGHTNESS * shade, vec3(0.0), vec3(1.0)), color.a, translucent_gloss ? (vec3(specular) + window_reflection) * PHONG_BRIGHTNESS * shade : ZERO, abs(dot(normal, view_dir))); diff --git a/resources/shaders/140/phong.vs b/resources/shaders/140/phong.vs index 7120b62c66..14d7081605 100644 --- a/resources/shaders/140/phong.vs +++ b/resources/shaders/140/phong.vs @@ -15,8 +15,6 @@ uniform mat4 projection_matrix; uniform mat3 view_normal_matrix; uniform mat4 volume_world_matrix; uniform SlopeDetection slope; -uniform bool is_outline; -uniform vec2 screen_size; // Clipping plane, x = min z, y = max z. Used by the FFF and SLA previews to clip with a top / bottom plane. uniform vec2 z_range; @@ -51,15 +49,6 @@ void main() world_normal_z = slope.actived ? dot(normalize(slope.volume_world_normal_matrix * v_normal), slope.up_direction) : 0.0; gl_Position = projection_matrix * position; - if (is_outline) { - vec3 n = normalize((view_normal_matrix * v_normal).xyz); - vec2 dir = normalize(n.xy); - if (dot(dir, dir) > 0.0) { - //set outline thickness - float px = 3.0; - gl_Position.xy += dir * (px * 2.0 / screen_size) * gl_Position.w; - } - } // Fill in the scalars for fragment shader clipping. Fragments with any of these components lower than zero are discarded. clipping_planes_dots = vec3(dot(world_pos, clipping_plane), world_pos.z - z_range.x, z_range.y - world_pos.z); color_clip_plane_dot = dot(world_pos, color_clip_plane); diff --git a/resources/shaders/140/ssao.fs b/resources/shaders/140/ssao.fs index 28b561ba2c..91fa7d4cd6 100644 --- a/resources/shaders/140/ssao.fs +++ b/resources/shaders/140/ssao.fs @@ -9,7 +9,6 @@ uniform sampler2D color_texture; uniform sampler2D depth_texture; uniform vec2 inv_tex_size; uniform float z_far; -uniform bool is_outline; // The pass has no normal target to read, so the surface normal is reconstructed from the depth // buffer. inv_projection_matrix unprojects a pixel back into view space and up_view is world +Z // expressed in view space, which is what tells a top surface from a wall. @@ -44,10 +43,6 @@ vec3 view_normal(ivec2 pixel, vec3 p) void main() { - if (is_outline) { - frag_color = vec4(texture(color_texture, tex_coord).rgb, 1.0); - return; - } ivec2 pixel = ivec2(gl_FragCoord.xy); vec3 color = texture(color_texture, tex_coord).rgb; diff --git a/src/slic3r/CMakeLists.txt b/src/slic3r/CMakeLists.txt index 3b4962eec5..5c427315cc 100644 --- a/src/slic3r/CMakeLists.txt +++ b/src/slic3r/CMakeLists.txt @@ -509,6 +509,8 @@ set(SLIC3R_GUI_SOURCES GUI/SceneRaycaster.hpp GUI/SceneCache.cpp GUI/SceneCache.hpp + GUI/SelectionOutline.cpp + GUI/SelectionOutline.hpp GUI/FrameProfiler.cpp GUI/FrameProfiler.hpp GUI/SceneBenchmark.cpp diff --git a/src/slic3r/GUI/3DScene.cpp b/src/slic3r/GUI/3DScene.cpp index 5cdf3b0f25..60e8016fec 100644 --- a/src/slic3r/GUI/3DScene.cpp +++ b/src/slic3r/GUI/3DScene.cpp @@ -12,6 +12,7 @@ #include "PartPlate.hpp" #include "BitmapCache.hpp" #include "Camera.hpp" +#include "SelectionOutline.hpp" #include "libslic3r/BuildVolume.hpp" #include "libslic3r/ExtrusionEntity.hpp" @@ -107,9 +108,6 @@ float FullTransparentModdifiedToFixAlpha = 0.3f; // value like 0.18f could not because in C++ (int)(0.18f * 255) == 45 however in OpenGL it renders this as 46 // which breaks the `SelectMachineDialog::record_edge_pixels_data()` function! float FULL_BLACK_THRESHOLD = 0.2f; -// Keep depth_tex away from texture unit 0 to avoid sampler-type aliasing with -// shadow/environment samplers when realistic view is disabled. -static constexpr int OUTLINE_DEPTH_TEX_UNIT = 5; Slic3r::ColorRGBA adjust_color_for_rendering(const Slic3r::ColorRGBA &colors) { @@ -551,159 +549,6 @@ void GLVolume::render() simple_render(shader, model_objects, colors); } -//BBS: add outline related logic -void GLVolume::render_with_outline(const GUI::Size& cnv_size) -{ - if (!is_active) - return; - - GLShaderProgram *shader = GUI::wxGetApp().get_current_shader(); - if (shader == nullptr) - return; - - ModelObjectPtrs &model_objects = GUI::wxGetApp().model().objects; - std::vector colors = GUI::wxGetApp().plater()->get_extruders_colors(); - - const GUI::OpenGLManager::EFramebufferType framebuffers_type = GUI::OpenGLManager::get_framebuffers_type(); - if (framebuffers_type == GUI::OpenGLManager::EFramebufferType::Unknown) { - // No supported, degrade to normal rendering - simple_render(shader, model_objects, colors); - return; - } - // 0th. render pass, render the model using stencil buffer - glsafe(::glEnable(GL_STENCIL_TEST)); - glsafe(::glStencilMask(0xFF)); - glsafe(::glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE)); - glsafe(::glClearStencil(0)); - glsafe(::glClear(GL_STENCIL_BUFFER_BIT)); - glsafe(::glStencilFunc(GL_ALWAYS, 0xFF, 0xFF)); - // This pass paints the visible surface, so it must go through simple_render() to keep - // per-triangle MMU paint colors; the later is_outline passes only draw the flat silhouette - // highlight and are fine using the single-color model. - simple_render(shader, model_objects, colors); - glsafe(::glStencilFunc(GL_NOTEQUAL, 0xFF, 0xFF)); - glsafe(::glStencilMask(0x00)); - shader->set_uniform("is_outline", true); - shader->set_uniform("screen_size", Vec2f{cnv_size.get_width(), cnv_size.get_height()}); - if (tverts_range == std::make_pair(0, -1)) - model.render(shader); - else - model.render(this->tverts_range, shader); - shader->set_uniform("is_outline", false); - glsafe(::glStencilMask(0xFF)); - glsafe(::glDisable(GL_STENCIL_TEST)); - // render the outline using depth buffer and discard the pixels that are not on the outline - // The silhouette is resolved per sample in the shader (see DetectSilho in gouraud.fs/phong.fs). - // That needs the GL 3.2 entry points and a shader that declares depth_tex as sampler2DMS, which - // only the 140 ones do and only under GL_ARB_texture_multisample - so ask the compiled program - // rather than the GL version, or a sampler2D ends up bound to a multisample texture. - // Only the Arb branch below allocates a multisample texture, so keep the target consistent with it. - const bool use_msaa_outline = framebuffers_type == GUI::OpenGLManager::EFramebufferType::Arb && - GUI::wxGetApp().is_gl_version_greater_or_equal_to(3, 2) && - shader->get_uniform_location("msaa_samples") >= 0; - const GLenum depth_tex_target = use_msaa_outline ? GL_TEXTURE_2D_MULTISAMPLE : GL_TEXTURE_2D; - // Keep the depth texture off image unit 0. The object shaders leave shadow_map (and - // environment_tex) at the default sampler value 0 whenever the shadow pass is skipped - which is - // the case with realistic view off - and GL forbids two sampler types referring to the same image - // unit. A sampler2DMS on unit 0 then makes every draw fail with INVALID_OPERATION on drivers that - // enforce it (Mesa), i.e. the model disappears entirely. Unit 5 is unused (shadow_map takes 4). - const int depth_tex_unit = OUTLINE_DEPTH_TEX_UNIT; - int aa_samples = 1; - if (use_msaa_outline) { - if (const AppConfig* app_config = GUI::wxGetApp().app_config; app_config != nullptr) { - const std::string value = app_config->get(SETTING_OPENGL_AA_SAMPLES); - if (value == "2" || value == "4" || value == "8" || value == "16") - aa_samples = ::atoi(value.c_str()); - } - // Never request more samples than the driver supports for depth textures (a 1-sample texture - // is used when MSAA is disabled, keeping a single code path for the sampler2DMS shader). - GLint max_samples = 1; - glsafe(::glGetIntegerv(GL_MAX_DEPTH_TEXTURE_SAMPLES, &max_samples)); - if (aa_samples > max_samples) - aa_samples = max_samples < 1 ? 1 : max_samples; - if (aa_samples < 1) - aa_samples = 1; - } - // 1st. render pass, render the model into a separate render target that has only depth buffer - GLuint depth_fbo = 0; - GLuint depth_tex = 0; - if (framebuffers_type == GUI::OpenGLManager::EFramebufferType::Arb) { - glsafe(::glGenFramebuffers(1, &depth_fbo)); - glsafe(::glBindFramebuffer(GL_FRAMEBUFFER, depth_fbo)); - - glsafe(::glActiveTexture(GL_TEXTURE0 + depth_tex_unit)); - glsafe(::glGenTextures(1, &depth_tex)); - glsafe(::glBindTexture(depth_tex_target, depth_tex)); - if (use_msaa_outline) { - // Multisample textures do not take filter/wrap parameters. - glsafe(::glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, aa_samples, GL_DEPTH_COMPONENT32F, cnv_size.get_width(), cnv_size.get_height(), GL_TRUE)); - } else { - glsafe(::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)); - glsafe(::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)); - glsafe(::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)); - glsafe(::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)); - glsafe(::glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT32F, cnv_size.get_width(), cnv_size.get_height(), 0, GL_DEPTH_COMPONENT, GL_FLOAT, nullptr)); - } - - glsafe(::glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, depth_tex_target, depth_tex, 0)); - } else { - glsafe(::glGenFramebuffersEXT(1, &depth_fbo)); - glsafe(::glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, depth_fbo)); - - glsafe(::glActiveTexture(GL_TEXTURE0 + depth_tex_unit)); - glsafe(::glGenTextures(1, &depth_tex)); - glsafe(::glBindTexture(GL_TEXTURE_2D, depth_tex)); - glsafe(::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)); - glsafe(::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)); - glsafe(::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)); - glsafe(::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)); - glsafe(::glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT32F, cnv_size.get_width(), cnv_size.get_height(), 0, GL_DEPTH_COMPONENT, GL_FLOAT, nullptr)); - - glsafe(::glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, depth_tex, 0)); - } - // Unbind before drawing: the texture is this framebuffer's depth attachment, so leaving it bound - // to a sampled unit would be a feedback loop. - glsafe(::glBindTexture(depth_tex_target, 0)); - glsafe(::glActiveTexture(GL_TEXTURE0)); - glsafe(::glClear(GL_DEPTH_BUFFER_BIT)); - if (tverts_range == std::make_pair(0, -1)) - model.render(shader); - else - model.render(this->tverts_range, shader); - - // 2nd. render pass, just a normal render with the depth buffer passed as a texture - if (framebuffers_type == GUI::OpenGLManager::EFramebufferType::Arb) { - glsafe(::glBindFramebuffer(GL_FRAMEBUFFER, 0)); - } else if (framebuffers_type == GUI::OpenGLManager::EFramebufferType::Ext) { - glsafe(::glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0)); - } - shader->set_uniform("is_outline", true); - shader->set_uniform("screen_size", Vec2f{cnv_size.get_width(), cnv_size.get_height()}); - shader->set_uniform("msaa_samples", aa_samples); - glsafe(::glActiveTexture(GL_TEXTURE0 + depth_tex_unit)); - glsafe(::glBindTexture(depth_tex_target, depth_tex)); - glsafe(::glActiveTexture(GL_TEXTURE0)); - shader->set_uniform("depth_tex", depth_tex_unit); - simple_render(shader, model_objects, colors); - - // Some clean up to do - glsafe(::glActiveTexture(GL_TEXTURE0 + depth_tex_unit)); - glsafe(::glBindTexture(depth_tex_target, 0)); - glsafe(::glActiveTexture(GL_TEXTURE0)); - shader->set_uniform("is_outline", false); - if (framebuffers_type == GUI::OpenGLManager::EFramebufferType::Arb) { - glsafe(::glBindFramebuffer(GL_FRAMEBUFFER, 0)); - if (depth_fbo != 0) - glsafe(::glDeleteFramebuffers(1, &depth_fbo)); - } else if (framebuffers_type == GUI::OpenGLManager::EFramebufferType::Ext) { - glsafe(::glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0)); - if (depth_fbo != 0) - glsafe(::glDeleteFramebuffersEXT(1, &depth_fbo)); - } - if (depth_tex != 0) - glsafe(::glDeleteTextures(1, &depth_tex)); -} - //BBS add render for simple case void GLVolume::simple_render(GLShaderProgram* shader, ModelObjectPtrs& model_objects, std::vector& extruder_colors, bool ban_light, bool ban_color_volume) { @@ -1202,15 +1047,14 @@ float GLVolumeCollection::get_selection_support_normal_z() const return static_cast(-std::cos(std::clamp(angle_rad, 0.0, Geometry::deg2rad(89.0)))); } -//BBS: add outline drawing logic void GLVolumeCollection::render(GLVolumeCollection::ERenderType type, bool disable_cullface, const Transform3d & view_matrix, const Transform3d& projection_matrix, - const GUI::Size& cnv_size, std::function filter_func, bool partly_inside_enable, - std::vector * printable_heights) const + std::vector * printable_heights, + std::vector * outlined_volumes) const { GLVolumeWithIdAndZList to_render = volumes_to_render(volumes, type, view_matrix, filter_func); if (to_render.empty()) @@ -1238,17 +1082,10 @@ void GLVolumeCollection::render(GLVolumeCollection::ERenderType type, const float support_normal_z = get_selection_support_normal_z(); - // The outline passes below are driven by is_outline, which only the object shaders have; with an - // overlay one (wireframe, x-ray) bound they would just draw the volume again. - const bool shader_can_outline = shader->get_uniform_location("is_outline") >= 0; // ORCA: the object shaders that know how draw a part of a translucent filament as its print would // show, in premultiplied color, see translucent_filament_color() in gouraud.fs const bool shade_translucent_filaments = type == ERenderType::Transparent && shader->get_uniform_location("translucent_filament") >= 0; - // Prime depth_tex on every frame so non-outline draws do not keep the - // default sampler unit 0, which can conflict with other sampler types. - shader->set_uniform("depth_tex", OUTLINE_DEPTH_TEX_UNIT); - // Compute up direction accounting for build plate tilt. This is frame-invariant // (config cannot change mid-render), so compute it once before the volume loop. const Vec3f up_direction = GUI::build_plate_tilt_up_direction().cast(); @@ -1358,11 +1195,19 @@ void GLVolumeCollection::render(GLVolumeCollection::ERenderType type, glsafe(::glEnable(GL_POLYGON_OFFSET_FILL)); glsafe(::glPolygonOffset(1.0f, 1.0f)); } - //BBS: add outline related logic - if (volume.first->selected && shader_can_outline && GUI::wxGetApp().show_outline()) - volume.first->render_with_outline(cnv_size); - else - volume.first->render(); + const bool outlined = outlined_volumes != nullptr && volume.first->selected && volume.first->is_active && !volume.first->is_wipe_tower; + if (outlined) { + outlined_volumes->push_back(volume.first); + glsafe(::glEnable(GL_STENCIL_TEST)); + glsafe(::glStencilMask(GUI::SelectionOutline::StencilBit)); + glsafe(::glStencilFunc(GL_ALWAYS, GUI::SelectionOutline::StencilBit, GUI::SelectionOutline::StencilBit)); + glsafe(::glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE)); + } + volume.first->render(); + if (outlined) { + glsafe(::glDisable(GL_STENCIL_TEST)); + glsafe(::glStencilMask(0xFF)); + } if (volume.first->depth_bias) glsafe(::glDisable(GL_POLYGON_OFFSET_FILL)); diff --git a/src/slic3r/GUI/3DScene.hpp b/src/slic3r/GUI/3DScene.hpp index ac31946c80..47b451bb2c 100644 --- a/src/slic3r/GUI/3DScene.hpp +++ b/src/slic3r/GUI/3DScene.hpp @@ -48,9 +48,6 @@ extern Slic3r::ColorRGBA adjust_color_for_rendering(const Slic3r::C namespace Slic3r { -namespace GUI { - class Size; -} class SLAPrintObject; enum SLAPrintObjectStep : unsigned int; @@ -366,9 +363,6 @@ public: virtual void render(); - //BBS: add outline related logic and add virtual specifier - virtual void render_with_outline(const GUI::Size& cnv_size); - //BBS: add simple render function for thumbnail void simple_render(GLShaderProgram* shader, ModelObjectPtrs& model_objects, std::vector& extruder_colors, bool ban_light =false, bool ban_color_volume = false); @@ -400,7 +394,6 @@ class GLWipeTowerVolume : public GLVolume { public: GLWipeTowerVolume(const std::vector& colors); void render() override; - void render_with_outline(const GUI::Size& cnv_size) override { render(); } std::vector model_per_colors; bool IsTransparent(); @@ -512,17 +505,17 @@ public: float get_selection_support_normal_z() const; // Render the volumes by OpenGL. - //BBS: add outline drawing logic void render(ERenderType type, bool disable_cullface, const Transform3d & view_matrix, const Transform3d& projection_matrix, - const GUI::Size& cnv_size, std::function filter_func = std::function(), bool partly_inside_enable =true, // Per-extruder printable heights (extruder_printable_height); null / size<=1 // leaves the shader's extruder_printable_heights flag at 0.0 (single-extruder = inert). - std::vector * printable_heights = nullptr + std::vector * printable_heights = nullptr, + // Collects the selected volumes drawn, marked in the stencil for SelectionOutline. + std::vector * outlined_volumes = nullptr ) const; // Clear the geometry diff --git a/src/slic3r/GUI/GCodeViewer.cpp b/src/slic3r/GUI/GCodeViewer.cpp index 6f6c4c8f5c..017c88bb1c 100644 --- a/src/slic3r/GUI/GCodeViewer.cpp +++ b/src/slic3r/GUI/GCodeViewer.cpp @@ -2171,7 +2171,7 @@ GCodeViewer::ImexMarkerPlan GCodeViewer::resolve_imex_marker_plan(const DynamicP void GCodeViewer::render_scene(int canvas_width, int canvas_height) { glsafe(::glEnable(GL_DEPTH_TEST)); - render_shells(canvas_width, canvas_height); + render_shells(); if (m_viewer.get_extrusion_roles_count() == 0) return; @@ -3391,7 +3391,7 @@ void GCodeViewer::render_toolpaths() #endif // ENABLE_NEW_GCODE_VIEWER_DEBUG } -void GCodeViewer::render_shells(int canvas_width, int canvas_height) +void GCodeViewer::render_shells() { //BBS: add shell previewing logic if ((!m_shells.previewing && !m_shells.visible) || m_shells.volumes.empty()) @@ -3409,7 +3409,7 @@ void GCodeViewer::render_shells(int canvas_width, int canvas_height) const Camera& camera = wxGetApp().plater()->get_camera(); shader->set_uniform("z_far", camera.get_far_z()); shader->set_uniform("z_near", camera.get_near_z()); - m_shells.volumes.render(GLVolumeCollection::ERenderType::Transparent, false, camera.get_view_matrix(), camera.get_projection_matrix(), {canvas_width, canvas_height}); + m_shells.volumes.render(GLVolumeCollection::ERenderType::Transparent, false, camera.get_view_matrix(), camera.get_projection_matrix()); shader->set_uniform("emission_factor", 0.0f); shader->stop_using(); diff --git a/src/slic3r/GUI/GCodeViewer.hpp b/src/slic3r/GUI/GCodeViewer.hpp index 714a359ab8..c6abdc16a1 100644 --- a/src/slic3r/GUI/GCodeViewer.hpp +++ b/src/slic3r/GUI/GCodeViewer.hpp @@ -520,7 +520,7 @@ private: void render_toolpaths(); // The sequential markers and the IDEX/IQEX toolhead boxes. void render_markers(int canvas_width, int canvas_height); - void render_shells(int canvas_width, int canvas_height); + void render_shells(); // ORCA: a filament color as the toolpaths show it, opaque unless translucent filaments are shown ColorRGBA shown_filament_color(ColorRGBA color) const; diff --git a/src/slic3r/GUI/GLCanvas3D.cpp b/src/slic3r/GUI/GLCanvas3D.cpp index cea09c314d..11856cf33f 100644 --- a/src/slic3r/GUI/GLCanvas3D.cpp +++ b/src/slic3r/GUI/GLCanvas3D.cpp @@ -1678,6 +1678,7 @@ GLCanvas3D::~GLCanvas3D() { if (_set_current()) { m_scene_cache.reset(); + m_selection_outline.reset(); m_frame_profiler.reset(); if (m_fxaa_texture_id != 0) { glsafe(::glDeleteTextures(1, &m_fxaa_texture_id)); @@ -2810,7 +2811,8 @@ void GLCanvas3D::_render_scene(const Camera& camera, const Size& cnv_size) { // Recorded by PartPlate::render_icons() below, when it runs. wxGetApp().plater()->get_partplate_list().clear_hover_tooltip(); - glsafe(::glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)); + glsafe(::glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT)); + m_outlined_volumes.clear(); // Invalidate the shadow map each frame; the View3D and Preview paths below rebuild it. This // keeps the Assemble canvas from sampling a stale map with an outdated light matrix. m_shadow_map_valid = false; @@ -2876,6 +2878,8 @@ void GLCanvas3D::_render_scene(const Camera& camera, const Size& cnv_size) _render_objects(GLVolumeCollection::ERenderType::Transparent, !m_gizmos.is_running()); _render_wireframe_overlay(); m_frame_profiler.mark("transparent"); + _render_selection_outline(); + m_frame_profiler.mark("outline"); } /* preview render */ else if (m_canvas_type == ECanvasType::CanvasPreview && m_render_preview) { @@ -2889,6 +2893,7 @@ void GLCanvas3D::_render_scene(const Camera& camera, const Size& cnv_size) m_frame_profiler.mark("bed"); _render_platelist(camera.get_view_matrix(), camera.get_projection_matrix(), !camera.is_looking_downward(), only_current, true, hover_id); m_frame_profiler.mark("plates"); + _render_selection_outline(); // Realistic view: the print casts a shadow onto the plate here as it does in View3D. _render_shadows(camera.get_view_matrix(), camera.get_projection_matrix()); m_frame_profiler.mark("shadows"); @@ -2912,6 +2917,8 @@ void GLCanvas3D::_render_scene(const Camera& camera, const Size& cnv_size) _render_objects(GLVolumeCollection::ERenderType::Transparent, !m_gizmos.is_running()); _render_wireframe_overlay(); m_frame_profiler.mark("objects"); + _render_selection_outline(); + m_frame_profiler.mark("outline"); } _render_sequential_clearance(); @@ -8826,7 +8833,18 @@ void GLCanvas3D::_render_ssao_pass(unsigned int width, unsigned int height) glsafe(::glBindTexture(GL_TEXTURE_2D, m_ssao_color_texture_id)); glsafe(::glActiveTexture(GL_TEXTURE1)); glsafe(::glBindTexture(GL_TEXTURE_2D, m_ssao_depth_texture_id)); + // The selection outline sits on top of the surfaces, so it is not shaded by their occlusion. + const bool keep_outline = m_selection_outline.uses_stencil(); + if (keep_outline) { + glsafe(::glEnable(GL_STENCIL_TEST)); + glsafe(::glStencilMask(0x00)); + glsafe(::glStencilFunc(GL_NOTEQUAL, SelectionOutline::DrawnBit, SelectionOutline::DrawnBit)); + } m_background.render(); + if (keep_outline) { + glsafe(::glDisable(GL_STENCIL_TEST)); + glsafe(::glStencilMask(0xFF)); + } glsafe(::glBindTexture(GL_TEXTURE_2D, 0)); glsafe(::glActiveTexture(GL_TEXTURE0)); glsafe(::glBindTexture(GL_TEXTURE_2D, 0)); @@ -9012,7 +9030,6 @@ void GLCanvas3D::_render_below_plate_volumes() shader->set_uniform("z_range", std::array{ -FLT_MAX, float(SINKING_Z_THRESHOLD) }); shader->set_uniform("clipping_plane", m_volumes.get_clipping_plane()); shader->set_uniform("use_color_clip_plane", false); - shader->set_uniform("is_outline", false); shader->set_uniform("slope.actived", false); shader->set_uniform("print_volume.type", -1); shader->set_uniform("extruder_printable_heights", std::array{ 0.0f, 0.0f, 0.0f }); @@ -9717,12 +9734,7 @@ void GLCanvas3D::_render_objects(GLVolumeCollection::ERenderType type, bool with if (static_light.has_value()) shader->set_uniform("static_light_dir", *static_light); - const Size& cvn_size = get_canvas_size(); - { - const Camera& camera = wxGetApp().plater()->get_camera(); - shader->set_uniform("z_far", camera.get_far_z()); - shader->set_uniform("z_near", camera.get_near_z()); - } + std::vector* outlined_volumes = wxGetApp().show_outline() ? &m_outlined_volumes : nullptr; switch (type) { default: @@ -9734,10 +9746,10 @@ void GLCanvas3D::_render_objects(GLVolumeCollection::ERenderType type, bool with if (m_picking_enabled && m_layers_editing.is_enabled() && (m_layers_editing.last_object_id != -1) && (m_layers_editing.object_max_z() > 0.0f)) { int object_id = m_layers_editing.last_object_id; const Camera& camera = wxGetApp().plater()->get_camera(); - m_volumes.render(type, false, camera.get_view_matrix(), camera.get_projection_matrix(), cvn_size, [object_id](const GLVolume& volume) { + m_volumes.render(type, false, camera.get_view_matrix(), camera.get_projection_matrix(), [object_id](const GLVolume& volume) { // Which volume to paint without the layer height profile shader? return volume.is_active && (volume.is_modifier || volume.composite_id.object_id != object_id); - }); + }, true, nullptr, outlined_volumes); m_layers_editing.render_volumes(*this, m_volumes); } else { @@ -9750,7 +9762,7 @@ void GLCanvas3D::_render_objects(GLVolumeCollection::ERenderType type, bool with //BBS:add assemble view related logic // do not cull backfaces to show broken geometry, if any const Camera& camera = wxGetApp().plater()->get_camera(); - m_volumes.render(type, m_picking_enabled, camera.get_view_matrix(), camera.get_projection_matrix(), cvn_size, [this, canvas_type](const GLVolume& volume) { + m_volumes.render(type, m_picking_enabled, camera.get_view_matrix(), camera.get_projection_matrix(), [this, canvas_type](const GLVolume& volume) { if (canvas_type == ECanvasType::CanvasAssembleView) { return !volume.is_modifier && !volume.is_wipe_tower; } @@ -9758,7 +9770,7 @@ void GLCanvas3D::_render_objects(GLVolumeCollection::ERenderType type, bool with return (m_render_sla_auxiliaries || volume.composite_id.volume_id >= 0); } }, - partly_inside_enable, printable_heights); + partly_inside_enable, printable_heights, outlined_volumes); } } else { @@ -9786,7 +9798,7 @@ void GLCanvas3D::_render_objects(GLVolumeCollection::ERenderType type, bool with }*/ const Camera& camera = wxGetApp().plater()->get_camera(); //BBS:add assemble view related logic - m_volumes.render(type, false, camera.get_view_matrix(), camera.get_projection_matrix(), cvn_size, [canvas_type](const GLVolume& volume) { + m_volumes.render(type, false, camera.get_view_matrix(), camera.get_projection_matrix(), [canvas_type](const GLVolume& volume) { if (canvas_type == ECanvasType::CanvasAssembleView) { return !volume.is_modifier; } @@ -9794,7 +9806,7 @@ void GLCanvas3D::_render_objects(GLVolumeCollection::ERenderType type, bool with return true; } }, - partly_inside_enable, printable_heights); + partly_inside_enable, printable_heights, outlined_volumes); // IMEX ghosts are transparent and share the same shader/camera state; // render them right after the main transparent pass while the shader is still bound. _render_imex_ghosts(); @@ -9819,6 +9831,14 @@ void GLCanvas3D::_render_objects(GLVolumeCollection::ERenderType type, bool with m_camera_clipping_plane = ClippingPlane::ClipsNothing(); } +void GLCanvas3D::_render_selection_outline() +{ + // With the clipping the object passes left in m_volumes. + m_selection_outline.render(m_outlined_volumes, wxGetApp().plater()->get_camera(), m_volumes.get_z_range(), + m_volumes.get_clipping_plane(), get_scale(), m_background); + m_outlined_volumes.clear(); +} + void GLCanvas3D::_render_section_view_caps() { // A gizmo with its own clipper draws its own cut faces. @@ -9892,7 +9912,7 @@ void GLCanvas3D::_render_xray_volumes() shader->start_using(); m_volumes.render(GLVolumeCollection::ERenderType::All, true, camera.get_view_matrix(), camera.get_projection_matrix(), - get_canvas_size(), [this, canvas_type](const GLVolume& volume) { + [this, canvas_type](const GLVolume& volume) { if (canvas_type == ECanvasType::CanvasAssembleView) return !volume.is_modifier && !volume.is_wipe_tower; return m_render_sla_auxiliaries || volume.composite_id.volume_id >= 0; @@ -9951,7 +9971,6 @@ void GLCanvas3D::_render_wireframe_overlay() const Camera& camera = wxGetApp().plater()->get_camera(); const Transform3d& view_matrix = camera.get_view_matrix(); const Transform3d& proj_matrix = camera.get_projection_matrix(); - const Size sz = get_canvas_size(); shader->start_using(); shader->set_uniform("offset", OpenGLManager::get_gl_info().is_mesa() ? 0.0005 : 0.00001); @@ -9965,7 +9984,7 @@ void GLCanvas3D::_render_wireframe_overlay() glsafe(::glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)); #endif - m_volumes.render(GLVolumeCollection::ERenderType::All, false, view_matrix, proj_matrix, sz, [](const GLVolume& volume) { + m_volumes.render(GLVolumeCollection::ERenderType::All, false, view_matrix, proj_matrix, [](const GLVolume& volume) { return !volume.render_color.is_transparent() || (volume.visible && !volume.is_modifier && volume.color.is_transparent()); }); diff --git a/src/slic3r/GUI/GLCanvas3D.hpp b/src/slic3r/GUI/GLCanvas3D.hpp index 76b78091fe..d041c31ae7 100644 --- a/src/slic3r/GUI/GLCanvas3D.hpp +++ b/src/slic3r/GUI/GLCanvas3D.hpp @@ -39,6 +39,7 @@ #include "Camera.hpp" #include "SceneRaycaster.hpp" #include "SceneCache.hpp" +#include "SelectionOutline.hpp" #include "FrameProfiler.hpp" #include "IMToolbar.hpp" #include "slic3r/GUI/3DBed.hpp" @@ -930,6 +931,9 @@ public: std::array m_ssao_texture_size{ { 0, 0 } }; // The last scene pass, for frames that only rebuild the overlay. SceneCache m_scene_cache; + SelectionOutline m_selection_outline; + // Selected volumes the object passes of this frame drew, outlined after them. + std::vector m_outlined_volumes; // Signature of the overlay on screen; empty after render(), a paint request or a frame drawn but // not shown, so the next frame is presented regardless. std::optional m_presented_signature; @@ -1557,6 +1561,7 @@ private: // IMEX ghost hover tooltip: filament swatch + label drawn as an ImGui overlay. void _render_imex_ghost_tooltip(); void _render_section_view_caps(); + void _render_selection_outline(); void _render_wireframe_overlay(); bool _is_below_plate_view_active() const; void _render_below_plate_volumes(); diff --git a/src/slic3r/GUI/GLShadersManager.cpp b/src/slic3r/GUI/GLShadersManager.cpp index 003f994a21..0ea7faa4f5 100644 --- a/src/slic3r/GUI/GLShadersManager.cpp +++ b/src/slic3r/GUI/GLShadersManager.cpp @@ -98,6 +98,12 @@ std::pair GLShadersManager::init() ); // used to render objects as translucent, edge weighted surfaces in the X-Ray view valid &= append_shader("xray", { prefix + "xray.vs", prefix + "xray.fs" }); +#if !SLIC3R_OPENGL_ES + // used to outline the selected volumes, see SelectionOutline + valid &= append_shader("outline_mask", { prefix + "outline_mask.vs", prefix + "outline_mask.fs" }); + valid &= append_shader("outline_edges", { prefix + "background.vs", prefix + "outline_edges.fs" }); + valid &= append_shader("outline", { prefix + "background.vs", prefix + "outline.fs" }); +#endif // !SLIC3R_OPENGL_ES // used to render variable layers heights in 3d editor valid &= append_shader("variable_layer_height", { prefix + "variable_layer_height.vs", prefix + "variable_layer_height.fs" }); // used to render highlight contour around selected triangles inside the multi-material gizmo diff --git a/src/slic3r/GUI/OpenGLManager.cpp b/src/slic3r/GUI/OpenGLManager.cpp index fccfb57a9a..cd882847e8 100644 --- a/src/slic3r/GUI/OpenGLManager.cpp +++ b/src/slic3r/GUI/OpenGLManager.cpp @@ -483,6 +483,23 @@ bool OpenGLManager::is_scene_canvas(const wxWindow* window) return window != nullptr && window->GetName() == SCENE_CANVAS_NAME; } +int OpenGLManager::stencil_bits() +{ + GLint bits = 0; + ::glGetError(); // drop anything pending, so the check below sees only this query + ::glGetIntegerv(GL_STENCIL_BITS, &bits); // compatibility profiles + if (::glGetError() != GL_NO_ERROR) { + bits = 0; + GLint fbo = 0; + ::glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &fbo); + // The default framebuffer names its stencil buffer, a framebuffer object its stencil attachment. + ::glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, fbo == 0 ? GL_STENCIL : GL_STENCIL_ATTACHMENT, + GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE, &bits); + ::glGetError(); + } + return std::max(0, int(bits)); +} + void OpenGLManager::detect_multisample(int* attribList) { int wxVersion = wxMAJOR_VERSION * 10000 + wxMINOR_VERSION * 100 + wxRELEASE_NUMBER; diff --git a/src/slic3r/GUI/OpenGLManager.hpp b/src/slic3r/GUI/OpenGLManager.hpp index e9de7fc197..979e7cb2ec 100644 --- a/src/slic3r/GUI/OpenGLManager.hpp +++ b/src/slic3r/GUI/OpenGLManager.hpp @@ -105,6 +105,8 @@ public: static bool is_scene_canvas(const wxWindow* window); static const GLInfo& get_gl_info() { return s_gl_info; } static bool force_power_of_two_textures() { return s_force_power_of_two_textures; } + // Of the bound draw framebuffer. + static int stencil_bits(); private: static void detect_multisample(int* attribList); diff --git a/src/slic3r/GUI/SelectionOutline.cpp b/src/slic3r/GUI/SelectionOutline.cpp new file mode 100644 index 0000000000..36758e9a4d --- /dev/null +++ b/src/slic3r/GUI/SelectionOutline.cpp @@ -0,0 +1,303 @@ +#include "libslic3r/libslic3r.h" +#include "SelectionOutline.hpp" + +#include "3DScene.hpp" +#include "Camera.hpp" +#include "GLModel.hpp" +#include "GLShader.hpp" +#include "GUI_App.hpp" +#include "OpenGLManager.hpp" +#include "libslic3r/BoundingBox.hpp" +#include "libslic3r/Color.hpp" +#include "libslic3r/Point.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Slic3r { +namespace GUI { + +// Widths on the model in mm, kept between two widths in pixels at a scale of 1. +static constexpr float RING_WIDTH_MM = 0.35f; +static constexpr std::array RING_WIDTH_PX = { 2.5f, 5.0f }; +static constexpr float LINE_HALF_WIDTH_MM = 0.09f; +static constexpr std::array LINE_HALF_WIDTH_PX = { 0.6f, 1.2f }; +static constexpr float LINE_OPACITY = 0.75f; +// The farthest the outline shaders search. +static constexpr int MAX_REACH = 15; + +static const ColorRGB OUTLINE_COLOR = ColorRGB::WHITE(); + +void SelectionOutline::render(const std::vector& volumes, const Camera& camera, const std::array& z_range, + const std::array& clipping_plane, float scale, GLModel& quad) +{ + // The targets take 16 bytes a pixel, so they are kept only while something is outlined. + if (volumes.empty()) { + reset(); + return; + } + if (OpenGLManager::get_framebuffers_type() != OpenGLManager::EFramebufferType::Arb) + return; + GLShaderProgram* mask_shader = wxGetApp().get_shader("outline_mask"); + GLShaderProgram* edges_shader = wxGetApp().get_shader("outline_edges"); + GLShaderProgram* shader = wxGetApp().get_shader("outline"); + if (mask_shader == nullptr || edges_shader == nullptr || shader == nullptr) + return; + + const std::array& viewport = camera.get_viewport(); + const int width = viewport[2]; + const int height = viewport[3]; + if (width <= 0 || height <= 0 || !update_targets(width, height)) + return; + if (m_stencil_bits < 0) + m_stencil_bits = OpenGLManager::stencil_bits(); + + const Transform3d& view_matrix = camera.get_view_matrix(); + const Transform3d& projection_matrix = camera.get_projection_matrix(); + const Matrix4d& projection = projection_matrix.matrix(); + // The passes reach as far as the widest lines. + const float ring_width = RING_WIDTH_PX[1] * scale; + const float line_width = LINE_HALF_WIDTH_PX[1] * scale; + // Wide enough to place the silhouette between texels at the outer edge of the ring. + const float ring_sigma = 0.5f * (ring_width + 0.5f); + const int ring_reach = std::min(MAX_REACH, int(std::ceil(ring_width + 1.5f))); + const int line_reach = std::min(MAX_REACH - 1, int(std::ceil(line_width + 0.5f)) + 1); + // A pixel spans 2 / (P11 * height) of view space, at unit depth for a perspective camera. + const float pixel_size = float(2.0 / (projection(1, 1) * height)); + const Vec2f pixel_size_coef = camera.get_type() == Camera::EType::Ortho ? Vec2f(0.0f, pixel_size) : Vec2f(pixel_size, 0.0f); + + // Screen box of the volumes, the whole screen when one reaches behind the camera. + std::array box = { 0, 0, width, height }; + { + const Matrix4d view_projection = projection * view_matrix.matrix(); + Vec2d lo(DBL_MAX, DBL_MAX); + Vec2d hi(-DBL_MAX, -DBL_MAX); + bool behind = false; + for (const GLVolume* volume : volumes) { + const BoundingBoxf3& bb = volume->transformed_bounding_box(); + for (int i = 0; i < 8 && !behind; ++i) { + const Vec4d c = view_projection * Vec4d((i & 1) ? bb.max.x() : bb.min.x(), (i & 2) ? bb.max.y() : bb.min.y(), + (i & 4) ? bb.max.z() : bb.min.z(), 1.0); + behind = c.w() <= 0.0; + lo = lo.cwiseMin(c.head<2>() / c.w()); + hi = hi.cwiseMax(c.head<2>() / c.w()); + } + } + // Clamped before the conversion, as a corner close to the camera plane projects far off screen. + auto to_pixel = [](double ndc, int size) { return std::clamp((ndc * 0.5 + 0.5) * size, -1.0, size + 1.0); }; + if (!behind) + box = { int(std::floor(to_pixel(lo.x(), width))), int(std::floor(to_pixel(lo.y(), height))), + int(std::ceil(to_pixel(hi.x(), width))), int(std::ceil(to_pixel(hi.y(), height))) }; + } + auto scissor = [&box, width, height](int pad) { + const int x0 = std::clamp(box[0] - pad, 0, width); + const int y0 = std::clamp(box[1] - pad, 0, height); + const int x1 = std::clamp(box[2] + pad, 0, width); + const int y1 = std::clamp(box[3] + pad, 0, height); + glsafe(::glScissor(x0, y0, std::max(0, x1 - x0), std::max(0, y1 - y0))); + }; + // Each pass reads the one before it this far beyond the pixels it writes. + const int composite_pad = int(std::ceil(ring_width)) + 2; + const int edges_pad = composite_pad + std::max(ring_reach, line_reach + 1) + 1; + const int mask_pad = edges_pad + std::max(ring_reach, 2) + 1; + + GLint prev_fbo = 0; + glsafe(::glGetIntegerv(GL_FRAMEBUFFER_BINDING, &prev_fbo)); + GLfloat clear_color[4] = { 0.0f, 0.0f, 0.0f, 0.0f }; + glsafe(::glGetFloatv(GL_COLOR_CLEAR_VALUE, clear_color)); + const GLboolean blend = ::glIsEnabled(GL_BLEND); + const GLboolean cull = ::glIsEnabled(GL_CULL_FACE); + const GLboolean scissor_test = ::glIsEnabled(GL_SCISSOR_TEST); + GLint scissor_box[4] = { 0, 0, 0, 0 }; + glsafe(::glGetIntegerv(GL_SCISSOR_BOX, scissor_box)); + + // The mask: normal, part and the distances to the triangle edges of the nearest selected surface. + glsafe(::glBindFramebuffer(GL_FRAMEBUFFER, m_mask_fbo)); + glsafe(::glEnable(GL_SCISSOR_TEST)); + scissor(mask_pad); + // Before the clear, which leaves the depth alone under a closed depth mask. + glsafe(::glDepthMask(GL_TRUE)); + glsafe(::glClearColor(0.0f, 0.0f, 0.0f, 0.0f)); + glsafe(::glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)); + glsafe(::glEnable(GL_DEPTH_TEST)); + glsafe(::glDepthFunc(GL_LESS)); + glsafe(::glDisable(GL_BLEND)); + glsafe(::glDisable(GL_CULL_FACE)); + mask_shader->start_using(); + mask_shader->set_uniform("projection_matrix", projection_matrix); + mask_shader->set_uniform("z_range", z_range); + mask_shader->set_uniform("clipping_plane", clipping_plane); + for (size_t i = 0; i < volumes.size(); ++i) { + GLVolume& volume = *volumes[i]; + const Transform3d model_matrix = volume.world_matrix(); + mask_shader->set_uniform("volume_world_matrix", model_matrix); + mask_shader->set_uniform("view_model_matrix", view_matrix * model_matrix); + mask_shader->set_uniform("view_normal_matrix", Matrix3d(view_matrix.matrix().block(0, 0, 3, 3) * + model_matrix.matrix().block(0, 0, 3, 3).inverse().transpose())); + mask_shader->set_uniform("part_id", float(i % 65535 + 1)); + if (volume.tverts_range == std::make_pair(0, -1)) + volume.model.render(mask_shader); + else + volume.model.render(volume.tverts_range, mask_shader); + } + mask_shader->stop_using(); + + glsafe(::glActiveTexture(GL_TEXTURE0)); + glsafe(::glBindTexture(GL_TEXTURE_2D, m_mask_texture)); + glsafe(::glActiveTexture(GL_TEXTURE1)); + glsafe(::glBindTexture(GL_TEXTURE_2D, m_depth_texture)); + + // The edges: inner ones between neighboring texels, and the nearest covered texel along each row. + glsafe(::glBindFramebuffer(GL_FRAMEBUFFER, m_edges_fbo)); + glsafe(::glDisable(GL_DEPTH_TEST)); + scissor(edges_pad); + edges_shader->start_using(); + edges_shader->set_uniform("mask_tex", 0); + edges_shader->set_uniform("depth_tex", 1); + edges_shader->set_uniform("tex_size", Vec2f(float(width), float(height))); + edges_shader->set_uniform("inv_projection_matrix", Matrix4d(projection.inverse())); + edges_shader->set_uniform("pixel_size_coef", pixel_size_coef); + edges_shader->set_uniform("ring_reach", ring_reach); + edges_shader->set_uniform("ring_sigma", ring_sigma); + quad.render(); + edges_shader->stop_using(); + + glsafe(::glActiveTexture(GL_TEXTURE2)); + glsafe(::glBindTexture(GL_TEXTURE_2D, m_edges_texture)); + + // Over the scene, depth tested so that what is in front of the selection hides its outline. + glsafe(::glBindFramebuffer(GL_FRAMEBUFFER, static_cast(prev_fbo))); + scissor(composite_pad); + glsafe(::glEnable(GL_DEPTH_TEST)); + glsafe(::glDepthFunc(GL_LEQUAL)); + glsafe(::glDepthMask(GL_FALSE)); + glsafe(::glEnable(GL_BLEND)); + glsafe(::glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)); + const bool use_stencil = uses_stencil(); + if (use_stencil) { + glsafe(::glEnable(GL_STENCIL_TEST)); + glsafe(::glStencilMask(DrawnBit)); + glsafe(::glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE)); + } + shader->start_using(); + shader->set_uniform("mask_tex", 0); + shader->set_uniform("depth_tex", 1); + shader->set_uniform("edges_tex", 2); + shader->set_uniform("tex_size", Vec2f(float(width), float(height))); + shader->set_uniform("use_stencil", use_stencil); + shader->set_uniform("ring_width", std::array{ RING_WIDTH_PX[0] * scale, ring_width, RING_WIDTH_MM }); + shader->set_uniform("ring_reach", ring_reach); + shader->set_uniform("ring_sigma", ring_sigma); + shader->set_uniform("line_width", std::array{ LINE_HALF_WIDTH_PX[0] * scale, line_width, LINE_HALF_WIDTH_MM }); + shader->set_uniform("line_reach", line_reach); + shader->set_uniform("line_opacity", LINE_OPACITY); + shader->set_uniform("outline_color", OUTLINE_COLOR); + shader->set_uniform("depth_coef", std::array{ float(projection(2, 2)), float(projection(2, 3)), + float(projection(3, 2)), float(projection(3, 3)) }); + shader->set_uniform("pixel_size_coef", pixel_size_coef); + // The ring off the samples of the selection, the lines on them, both marking DrawnBit where they draw. + if (use_stencil) + glsafe(::glStencilFunc(GL_NOTEQUAL, StencilBit | DrawnBit, StencilBit)); + shader->set_uniform("inner", false); + quad.render(); + if (use_stencil) + glsafe(::glStencilFunc(GL_EQUAL, StencilBit | DrawnBit, StencilBit)); + shader->set_uniform("inner", true); + quad.render(); + shader->stop_using(); + + if (use_stencil) { + glsafe(::glDisable(GL_STENCIL_TEST)); + glsafe(::glStencilMask(0xFF)); + glsafe(::glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP)); + } + glsafe(::glScissor(scissor_box[0], scissor_box[1], scissor_box[2], scissor_box[3])); + if (!scissor_test) + glsafe(::glDisable(GL_SCISSOR_TEST)); + glsafe(::glDepthFunc(GL_LESS)); + glsafe(::glDepthMask(GL_TRUE)); + if (!blend) + glsafe(::glDisable(GL_BLEND)); + if (cull) + glsafe(::glEnable(GL_CULL_FACE)); + glsafe(::glClearColor(clear_color[0], clear_color[1], clear_color[2], clear_color[3])); + for (GLenum unit : { GL_TEXTURE2, GL_TEXTURE1, GL_TEXTURE0 }) { + glsafe(::glActiveTexture(unit)); + glsafe(::glBindTexture(GL_TEXTURE_2D, 0)); + } +} + +void SelectionOutline::reset() +{ + for (unsigned int* id : { &m_mask_texture, &m_depth_texture, &m_edges_texture }) { + if (*id != 0) { + glsafe(::glDeleteTextures(1, id)); + *id = 0; + } + } + for (unsigned int* id : { &m_mask_fbo, &m_edges_fbo }) { + if (*id != 0) { + glsafe(::glDeleteFramebuffers(1, id)); + *id = 0; + } + } + m_size = { { 0, 0 } }; + m_complete = false; + m_stencil_bits = -1; +} + +bool SelectionOutline::update_targets(unsigned int width, unsigned int height) +{ + if (m_mask_fbo != 0 && m_size[0] == width && m_size[1] == height) + return m_complete; + + auto allocate = [width, height](unsigned int& id, GLint format, GLenum data_format, GLenum type) { + if (id == 0) { + glsafe(::glGenTextures(1, &id)); + glsafe(::glBindTexture(GL_TEXTURE_2D, id)); + glsafe(::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)); + glsafe(::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)); + glsafe(::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)); + glsafe(::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)); + } + else + glsafe(::glBindTexture(GL_TEXTURE_2D, id)); + glsafe(::glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, data_format, type, nullptr)); + }; + allocate(m_mask_texture, GL_RGBA16, GL_RGBA, GL_UNSIGNED_SHORT); + allocate(m_depth_texture, wxGetApp().is_gl_version_greater_or_equal_to(3, 0) ? GL_DEPTH_COMPONENT32F : GL_DEPTH_COMPONENT24, + GL_DEPTH_COMPONENT, GL_FLOAT); + allocate(m_edges_texture, GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE); + glsafe(::glBindTexture(GL_TEXTURE_2D, 0)); + + GLint prev_fbo = 0; + glsafe(::glGetIntegerv(GL_FRAMEBUFFER_BINDING, &prev_fbo)); + if (m_mask_fbo == 0) + glsafe(::glGenFramebuffers(1, &m_mask_fbo)); + glsafe(::glBindFramebuffer(GL_FRAMEBUFFER, m_mask_fbo)); + glsafe(::glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_mask_texture, 0)); + glsafe(::glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, m_depth_texture, 0)); + m_complete = ::glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE; + if (m_edges_fbo == 0) + glsafe(::glGenFramebuffers(1, &m_edges_fbo)); + glsafe(::glBindFramebuffer(GL_FRAMEBUFFER, m_edges_fbo)); + glsafe(::glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_edges_texture, 0)); + m_complete = m_complete && ::glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE; + glsafe(::glBindFramebuffer(GL_FRAMEBUFFER, static_cast(prev_fbo))); + + m_size = { { width, height } }; + if (!m_complete) + BOOST_LOG_TRIVIAL(error) << "SelectionOutline: incomplete framebuffers, the selection is drawn without its outline"; + return m_complete; +} + +} // namespace GUI +} // namespace Slic3r diff --git a/src/slic3r/GUI/SelectionOutline.hpp b/src/slic3r/GUI/SelectionOutline.hpp new file mode 100644 index 0000000000..f0aedbe677 --- /dev/null +++ b/src/slic3r/GUI/SelectionOutline.hpp @@ -0,0 +1,47 @@ +#pragma once + +#include +#include + +namespace Slic3r { + +class GLVolume; + +namespace GUI { + +struct Camera; +class GLModel; + +// The outline of the selected volumes: a ring around them and lines along their inner edges, found in a mask +// of the volumes and drawn over the scene. See docs/HLSD/selection-outline.md. +class SelectionOutline +{ +public: + // Set in the stencil where the outlined volumes are drawn. + static constexpr unsigned int StencilBit = 0x80; + // Set in the stencil where the outline is drawn, which the occlusion pass leaves as it is. + static constexpr unsigned int DrawnBit = 0x40; + + // Over the bound framebuffer, whose stencil and depth hold the scene the volumes were drawn into. + void render(const std::vector& volumes, const Camera& camera, const std::array& z_range, + const std::array& clipping_plane, float scale, GLModel& quad); + // Frees the targets. + void reset(); + // The stencil holds the bits above, so the outline marks DrawnBit. + bool uses_stencil() const { return m_stencil_bits >= 8; } + +private: + bool update_targets(unsigned int width, unsigned int height); + + unsigned int m_mask_fbo{ 0 }; + unsigned int m_mask_texture{ 0 }; + unsigned int m_depth_texture{ 0 }; + unsigned int m_edges_fbo{ 0 }; + unsigned int m_edges_texture{ 0 }; + std::array m_size{ { 0, 0 } }; + bool m_complete{ false }; + int m_stencil_bits{ -1 }; +}; + +} // namespace GUI +} // namespace Slic3r diff --git a/src/slic3r/GUI/UVEditorCanvas.cpp b/src/slic3r/GUI/UVEditorCanvas.cpp index 2380205415..502a1cd912 100644 --- a/src/slic3r/GUI/UVEditorCanvas.cpp +++ b/src/slic3r/GUI/UVEditorCanvas.cpp @@ -1532,17 +1532,8 @@ void UVEditorCanvas::render() // Dim the texture everywhere but inside the islands: the fills go into the stencil only, then one // full-viewport quad washes the rest towards the background. Skipped without a stencil buffer, where the // quad would cover the islands too. - if (m_stencil_bits < 0) { - GLint bits = 0; - ::glGetError(); // drop anything pending, so the check below sees only this query - ::glGetIntegerv(GL_STENCIL_BITS, &bits); // compatibility profiles - if (::glGetError() != GL_NO_ERROR) { - bits = 0; - ::glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, GL_STENCIL, GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE, &bits); - ::glGetError(); - } - m_stencil_bits = std::max(0, int(bits)); - } + if (m_stencil_bits < 0) + m_stencil_bits = OpenGLManager::stencil_bits(); if (has_islands() && !m_island_fill.empty() && m_stencil_bits > 0) { if (!m_dim_quad_glmodel.is_initialized()) { GLModel::Geometry q;