Copy as Markdown

Other Tools

#define SWGL 1
#define __VERSION__ 150
#define WR_MAX_VERTEX_TEXTURE_WIDTH 1024U
#define WR_FEATURE_TEXTURE_2D
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#ifdef WR_FEATURE_TEXTURE_EXTERNAL
// for this extension.
#endif
#ifdef WR_FEATURE_TEXTURE_EXTERNAL_ESSL1
// Some GLES 3 devices do not support GL_OES_EGL_image_external_essl3, so we
// must use GL_OES_EGL_image_external instead and make the shader ESSL1
// compatible.
#endif
#ifdef WR_FEATURE_TEXTURE_EXTERNAL_BT709
#endif
#ifdef WR_FEATURE_ADVANCED_BLEND
#endif
#ifdef WR_FEATURE_DUAL_SOURCE_BLENDING
#ifdef GL_ES
#else
#endif
#endif
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#if defined(GL_ES)
#if GL_ES == 1
// Sampler default precision is lowp on mobile GPUs.
// This causes RGBA32F texture data to be clamped to 16 bit floats on some GPUs (e.g. Mali-T880).
// Define highp precision macro to allow lossless FLOAT texture sampling.
#define HIGHP_SAMPLER_FLOAT highp
// Default int precision in GLES 3 is highp (32 bits) in vertex shaders
// and mediump (16 bits) in fragment shaders. If an int is being used as
// a texel address in a fragment shader it, and therefore requires > 16
// bits, it must be qualified with this.
#define HIGHP_FS_ADDRESS highp
// texelFetchOffset is buggy on some Android GPUs (see issue #1694).
// Fallback to texelFetch on mobile GPUs.
#define TEXEL_FETCH(sampler, position, lod, offset) texelFetch(sampler, position + offset, lod)
#else
#define HIGHP_SAMPLER_FLOAT
#define HIGHP_FS_ADDRESS
#define TEXEL_FETCH(sampler, position, lod, offset) texelFetchOffset(sampler, position, lod, offset)
#endif
#else
#define HIGHP_SAMPLER_FLOAT
#define HIGHP_FS_ADDRESS
#if defined(PLATFORM_MACOS) && !defined(SWGL)
// texelFetchOffset introduces a variety of shader compilation bugs on macOS Intel so avoid it.
#define TEXEL_FETCH(sampler, position, lod, offset) texelFetch(sampler, position + offset, lod)
#else
#define TEXEL_FETCH(sampler, position, lod, offset) texelFetchOffset(sampler, position, lod, offset)
#endif
#endif
#ifdef SWGL
#define SWGL_DRAW_SPAN
#define SWGL_CLIP_MASK
#define SWGL_ANTIALIAS
#define SWGL_BLEND
#define SWGL_CLIP_DIST
#endif
#ifdef WR_VERTEX_SHADER
#ifdef SWGL
// Annotate a vertex attribute as being flat per each drawn primitive instance.
// SWGL can use this information to avoid redundantly loading the attribute in all SIMD lanes.
#define PER_INSTANCE flat
#else
#define PER_INSTANCE
#endif
#if __VERSION__ != 100
#define varying out
#define attribute in
#endif
#endif
#ifdef WR_FRAGMENT_SHADER
precision highp float;
#if __VERSION__ != 100
#define varying in
#endif
#endif
// Flat interpolation is not supported on ESSL 1
#if __VERSION__ == 100
#define flat
#endif
#if defined(WR_FEATURE_TEXTURE_EXTERNAL_ESSL1)
#define TEX_SAMPLE(sampler, tex_coord) texture2D(sampler, tex_coord.xy)
#elif defined(WR_FEATURE_TEXTURE_EXTERNAL_BT709)
// Force conversion from yuv to rgb using BT709 colorspace
#define TEX_SAMPLE(sampler, tex_coord) vec4(yuv_2_rgb(texture(sampler, tex_coord.xy).xyz, itu_709), 1.0)
#else
#define TEX_SAMPLE(sampler, tex_coord) texture(sampler, tex_coord.xy)
#endif
#if defined(WR_FEATURE_TEXTURE_EXTERNAL) && defined(PLATFORM_ANDROID)
// On some Mali GPUs we have encountered crashes in glDrawElements when using
// textureSize(samplerExternalOES) in a vertex shader without potentially
// sampling from the texture. This tricks the driver in to thinking the texture
// may be sampled from, avoiding the crash. See bug 1692848.
uniform bool u_mali_workaround_dummy;
#define TEX_SIZE(sampler) (u_mali_workaround_dummy ? ivec2(texture(sampler, vec2(0.0, 0.0)).rr) : textureSize(sampler, 0))
#else
#define TEX_SIZE(sampler) textureSize(sampler, 0)
#endif
//======================================================================================
// Vertex shader attributes and uniforms
//======================================================================================
#ifdef WR_VERTEX_SHADER
// Uniform inputs
uniform mat4 uTransform; // Orthographic projection
// Attribute inputs
attribute vec2 aPosition;
// get_fetch_uv is a macro to work around a macOS Intel driver parsing bug.
// TODO: convert back to a function once the driver issues are resolved, if ever.
// Do the division with unsigned ints because that's more efficient with D3D
#define get_fetch_uv(i, vpi) ivec2(int(vpi * (uint(i) % (WR_MAX_VERTEX_TEXTURE_WIDTH/vpi))), int(uint(i) / (WR_MAX_VERTEX_TEXTURE_WIDTH/vpi)))
#endif
//======================================================================================
// Fragment shader attributes and uniforms
//======================================================================================
#ifdef WR_FRAGMENT_SHADER
// Uniform inputs
// Fragment shader outputs
#ifdef WR_FEATURE_ADVANCED_BLEND
layout(blend_support_all_equations) out;
#endif
#if __VERSION__ == 100
#define oFragColor gl_FragColor
#elif defined(WR_FEATURE_DUAL_SOURCE_BLENDING)
layout(location = 0, index = 0) out vec4 oFragColor;
layout(location = 0, index = 1) out vec4 oFragBlend;
#else
out vec4 oFragColor;
#endif
// Write an output color in normal shaders.
void write_output(vec4 color) {
oFragColor = color;
}
#define EPSILON 0.0001
// "Show Overdraw" color. Premultiplied.
#define WR_DEBUG_OVERDRAW_COLOR vec4(0.110, 0.077, 0.027, 0.125)
float distance_to_line(vec2 p0, vec2 perp_dir, vec2 p) {
vec2 dir_to_p0 = p0 - p;
return dot(normalize(perp_dir), dir_to_p0);
}
// fwidth is not defined in ESSL 1, but that's okay because we don't need
// it for any ESSL 1 shader variants.
#if __VERSION__ != 100
/// Find the appropriate half range to apply the AA approximation over.
/// This range represents a coefficient to go from one CSS pixel to half a device pixel.
vec2 compute_aa_range_xy(vec2 position) {
return fwidth(position);
}
float compute_aa_range(vec2 position) {
// The constant factor is chosen to compensate for the fact that length(fw) is equal
// to sqrt(2) times the device pixel ratio in the typical case.
//
// This coefficient is chosen to ensure that any sample 0.5 pixels or more inside of
// the shape has no anti-aliasing applied to it (since pixels are sampled at their center,
// such a pixel (axis aligned) is fully inside the border). We need this so that antialiased
// curves properly connect with non-antialiased vertical or horizontal lines, among other things.
//
// Lines over a half-pixel away from the pixel center *can* intersect with the pixel square;
// indeed, unless they are horizontal or vertical, they are guaranteed to. However, choosing
// a nonzero area for such pixels causes noticeable artifacts at the junction between an anti-
// aliased corner and a straight edge.
//
// We may want to adjust this constant in specific scenarios (for example keep the principled
// value for straight edges where we want pixel-perfect equivalence with non antialiased lines
// when axis aligned, while selecting a larger and smoother aa range on curves).
//
// As a further optimization, we compute the reciprocal of this range, such that we
// can then use the cheaper inversesqrt() instead of length(). This also elides a
// division that would otherwise be necessary inside distance_aa.
#ifdef SWGL
// SWGL uses an approximation for fwidth() such that it returns equal x and y.
// Thus, sqrt(2)/length(w) = sqrt(2)/sqrt(x*x + x*x) = recip(x).
return recip(fwidth(position).x);
#else
// sqrt(2)/length(w) = inversesqrt(0.5 * dot(w, w))
vec2 w = fwidth(position);
return inversesqrt(0.5 * dot(w, w));
#endif
}
#endif
/// Return the blending coefficient for distance antialiasing.
///
/// 0.0 means inside the shape, 1.0 means outside.
///
/// This makes the simplifying assumption that the area of a 1x1 pixel square
/// under a line is reasonably similar to just the signed Euclidian distance
/// from the center of the square to that line. This diverges slightly from
/// better approximations of the exact area, but the difference between the
/// methods is not perceptibly noticeable, while this approximation is much
/// faster to compute.
///
/// See the comments in `compute_aa_range()` for more information on the
/// cutoff values of -0.5 and 0.5.
float distance_aa_xy(vec2 aa_range, vec2 signed_distance) {
// The aa_range is the raw per-axis filter width, so we need to divide
// the local signed distance by the filter width to get an approximation
// of screen distance.
#ifdef SWGL
// The SWGL fwidth() approximation returns uniform X and Y ranges.
vec2 dist = signed_distance * recip(aa_range.x);
#else
vec2 dist = signed_distance / aa_range;
#endif
// Choose whichever axis is further outside the rectangle for AA.
return clamp(0.5 - max(dist.x, dist.y), 0.0, 1.0);
}
float distance_aa(float aa_range, float signed_distance) {
// The aa_range is already stored as a reciprocal with uniform scale,
// so just multiply it, then use that for AA.
float dist = signed_distance * aa_range;
return clamp(0.5 - dist, 0.0, 1.0);
}
/// Component-wise selection.
///
/// The idea of using this is to ensure both potential branches are executed before
/// selecting the result, to avoid observable timing differences based on the condition.
///
/// Example usage: color = if_then_else(LessThanEqual(color, vec3(0.5)), vec3(0.0), vec3(1.0));
///
/// The above example sets each component to 0.0 or 1.0 independently depending on whether
/// their values are below or above 0.5.
///
/// This is written as a macro in order to work with vectors of any dimension.
///
/// Note: Some older android devices don't support mix with bvec. If we ever run into them
/// the only option we have is to polyfill it with a branch per component.
#define if_then_else(cond, then_branch, else_branch) mix(else_branch, then_branch, cond)
#endif
//======================================================================================
// Shared shader uniforms
//======================================================================================
#ifdef WR_FEATURE_TEXTURE_2D
uniform sampler2D sColor0;
uniform sampler2D sColor1;
uniform sampler2D sColor2;
#elif defined WR_FEATURE_TEXTURE_RECT
uniform sampler2DRect sColor0;
uniform sampler2DRect sColor1;
uniform sampler2DRect sColor2;
#elif defined(WR_FEATURE_TEXTURE_EXTERNAL) || defined(WR_FEATURE_TEXTURE_EXTERNAL_ESSL1)
uniform samplerExternalOES sColor0;
uniform samplerExternalOES sColor1;
uniform samplerExternalOES sColor2;
#elif defined(WR_FEATURE_TEXTURE_EXTERNAL_BT709)
uniform __samplerExternal2DY2YEXT sColor0;
uniform __samplerExternal2DY2YEXT sColor1;
uniform __samplerExternal2DY2YEXT sColor2;
#endif
#ifdef WR_FEATURE_DITHERING
uniform sampler2D sDither;
#endif
//======================================================================================
// Interpolator definitions
//======================================================================================
//======================================================================================
// VS only types and UBOs
//======================================================================================
//======================================================================================
// VS only functions
//======================================================================================
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
struct RectWithSize {
vec2 p0;
vec2 size;
};
struct RectWithEndpoint {
vec2 p0;
vec2 p1;
};
float point_inside_rect(vec2 p, vec2 p0, vec2 p1) {
vec2 s = step(p0, p) - step(p1, p);
return s.x * s.y;
}
vec2 signed_distance_rect_xy(vec2 pos, vec2 p0, vec2 p1) {
// Instead of using a true signed distance to rect here, we just use the
// simpler approximation of the maximum distance on either axis from the
// outside of the rectangle. This avoids expensive use of length() and only
// causes mostly imperceptible differences at corner pixels.
return max(p0 - pos, pos - p1);
}
float signed_distance_rect(vec2 pos, vec2 p0, vec2 p1) {
// Collapse the per-axis distances to edges to a single approximate value.
vec2 d = signed_distance_rect_xy(pos, p0, p1);
return max(d.x, d.y);
}
vec2 rect_clamp(RectWithEndpoint rect, vec2 pt) {
return clamp(pt, rect.p0, rect.p1);
}
vec2 rect_size(RectWithEndpoint rect) {
return rect.p1 - rect.p0;
}
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#ifdef WR_VERTEX_SHADER
#define VECS_PER_RENDER_TASK 2U
uniform HIGHP_SAMPLER_FLOAT sampler2D sRenderTasks;
struct RenderTaskData {
RectWithEndpoint task_rect;
vec4 user_data;
};
// See RenderTaskData in render_task.rs
RenderTaskData fetch_render_task_data(int index) {
ivec2 uv = get_fetch_uv(index, VECS_PER_RENDER_TASK);
vec4 texel0 = TEXEL_FETCH(sRenderTasks, uv, 0, ivec2(0, 0));
vec4 texel1 = TEXEL_FETCH(sRenderTasks, uv, 0, ivec2(1, 0));
RectWithEndpoint task_rect = RectWithEndpoint(
texel0.xy,
texel0.zw
);
RenderTaskData data = RenderTaskData(
task_rect,
texel1
);
return data;
}
RectWithEndpoint fetch_render_task_rect(int index) {
ivec2 uv = get_fetch_uv(index, VECS_PER_RENDER_TASK);
vec4 texel0 = TEXEL_FETCH(sRenderTasks, uv, 0, ivec2(0, 0));
vec4 texel1 = TEXEL_FETCH(sRenderTasks, uv, 0, ivec2(1, 0));
RectWithEndpoint task_rect = RectWithEndpoint(
texel0.xy,
texel0.zw
);
return task_rect;
}
#define PIC_TYPE_IMAGE 1
#define PIC_TYPE_TEXT_SHADOW 2
/*
The dynamic picture that this brush exists on. Right now, it
contains minimal information. In the future, it will describe
the transform mode of primitives on this picture, among other things.
*/
struct PictureTask {
RectWithEndpoint task_rect;
float device_pixel_scale;
vec2 content_origin;
};
PictureTask fetch_picture_task(int address) {
RenderTaskData task_data = fetch_render_task_data(address);
PictureTask task = PictureTask(
task_data.task_rect,
task_data.user_data.x,
task_data.user_data.yz
);
return task;
}
#define CLIP_TASK_EMPTY 0x7FFFFFFF
struct ClipArea {
RectWithEndpoint task_rect;
float device_pixel_scale;
vec2 screen_origin;
};
ClipArea fetch_clip_area(int index) {
RenderTaskData task_data;
if (index >= CLIP_TASK_EMPTY) {
// We deliberately create a dummy RenderTaskData here then convert to a
// ClipArea after this if-else statement, rather than initialize the
// ClipArea in separate branches, to avoid a miscompile in some Adreno
// drivers. See bug 1884791. Unfortunately the specific details of the bug
// are unknown, so please take extra care not to regress this when
// refactoring.
task_data = RenderTaskData(RectWithEndpoint(vec2(0.0), vec2(0.0)),
vec4(0.0));
} else {
task_data = fetch_render_task_data(index);
}
return ClipArea(task_data.task_rect, task_data.user_data.x,
task_data.user_data.yz);
}
#endif //WR_VERTEX_SHADER
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
uniform HIGHP_SAMPLER_FLOAT sampler2D sGpuCache;
#define VECS_PER_IMAGE_RESOURCE 2
// TODO(gw): This is here temporarily while we have
// both GPU store and cache. When the GPU
// store code is removed, we can change the
// PrimitiveInstance instance structure to
// use 2x unsigned shorts as vertex attributes
// instead of an int, and encode the UV directly
// in the vertices.
ivec2 get_gpu_cache_uv(HIGHP_FS_ADDRESS int address) {
return ivec2(uint(address) % WR_MAX_VERTEX_TEXTURE_WIDTH,
uint(address) / WR_MAX_VERTEX_TEXTURE_WIDTH);
}
vec4[2] fetch_from_gpu_cache_2_direct(ivec2 address) {
return vec4[2](
TEXEL_FETCH(sGpuCache, address, 0, ivec2(0, 0)),
TEXEL_FETCH(sGpuCache, address, 0, ivec2(1, 0))
);
}
vec4[2] fetch_from_gpu_cache_2(HIGHP_FS_ADDRESS int address) {
ivec2 uv = get_gpu_cache_uv(address);
return vec4[2](
TEXEL_FETCH(sGpuCache, uv, 0, ivec2(0, 0)),
TEXEL_FETCH(sGpuCache, uv, 0, ivec2(1, 0))
);
}
vec4 fetch_from_gpu_cache_1_direct(ivec2 address) {
return texelFetch(sGpuCache, address, 0);
}
vec4 fetch_from_gpu_cache_1(HIGHP_FS_ADDRESS int address) {
ivec2 uv = get_gpu_cache_uv(address);
return texelFetch(sGpuCache, uv, 0);
}
#ifdef WR_VERTEX_SHADER
vec4[8] fetch_from_gpu_cache_8(int address) {
ivec2 uv = get_gpu_cache_uv(address);
return vec4[8](
TEXEL_FETCH(sGpuCache, uv, 0, ivec2(0, 0)),
TEXEL_FETCH(sGpuCache, uv, 0, ivec2(1, 0)),
TEXEL_FETCH(sGpuCache, uv, 0, ivec2(2, 0)),
TEXEL_FETCH(sGpuCache, uv, 0, ivec2(3, 0)),
TEXEL_FETCH(sGpuCache, uv, 0, ivec2(4, 0)),
TEXEL_FETCH(sGpuCache, uv, 0, ivec2(5, 0)),
TEXEL_FETCH(sGpuCache, uv, 0, ivec2(6, 0)),
TEXEL_FETCH(sGpuCache, uv, 0, ivec2(7, 0))
);
}
vec4[3] fetch_from_gpu_cache_3(int address) {
ivec2 uv = get_gpu_cache_uv(address);
return vec4[3](
TEXEL_FETCH(sGpuCache, uv, 0, ivec2(0, 0)),
TEXEL_FETCH(sGpuCache, uv, 0, ivec2(1, 0)),
TEXEL_FETCH(sGpuCache, uv, 0, ivec2(2, 0))
);
}
vec4[3] fetch_from_gpu_cache_3_direct(ivec2 address) {
return vec4[3](
TEXEL_FETCH(sGpuCache, address, 0, ivec2(0, 0)),
TEXEL_FETCH(sGpuCache, address, 0, ivec2(1, 0)),
TEXEL_FETCH(sGpuCache, address, 0, ivec2(2, 0))
);
}
vec4[4] fetch_from_gpu_cache_4_direct(ivec2 address) {
return vec4[4](
TEXEL_FETCH(sGpuCache, address, 0, ivec2(0, 0)),
TEXEL_FETCH(sGpuCache, address, 0, ivec2(1, 0)),
TEXEL_FETCH(sGpuCache, address, 0, ivec2(2, 0)),
TEXEL_FETCH(sGpuCache, address, 0, ivec2(3, 0))
);
}
vec4[4] fetch_from_gpu_cache_4(int address) {
ivec2 uv = get_gpu_cache_uv(address);
return vec4[4](
TEXEL_FETCH(sGpuCache, uv, 0, ivec2(0, 0)),
TEXEL_FETCH(sGpuCache, uv, 0, ivec2(1, 0)),
TEXEL_FETCH(sGpuCache, uv, 0, ivec2(2, 0)),
TEXEL_FETCH(sGpuCache, uv, 0, ivec2(3, 0))
);
}
//TODO: image resource is too specific for this module
struct ImageSource {
RectWithEndpoint uv_rect;
vec4 user_data;
};
ImageSource fetch_image_source(int address) {
//Note: number of blocks has to match `renderer::BLOCKS_PER_UV_RECT`
vec4 data[2] = fetch_from_gpu_cache_2(address);
RectWithEndpoint uv_rect = RectWithEndpoint(data[0].xy, data[0].zw);
return ImageSource(uv_rect, data[1]);
}
ImageSource fetch_image_source_direct(ivec2 address) {
vec4 data[2] = fetch_from_gpu_cache_2_direct(address);
RectWithEndpoint uv_rect = RectWithEndpoint(data[0].xy, data[0].zw);
return ImageSource(uv_rect, data[1]);
}
// Fetch optional extra data for a texture cache resource. This can contain
// a polygon defining a UV rect within the texture cache resource.
// Note: the polygon coordinates are in homogeneous space.
struct ImageSourceExtra {
vec4 st_tl;
vec4 st_tr;
vec4 st_bl;
vec4 st_br;
};
ImageSourceExtra fetch_image_source_extra(int address) {
vec4 data[4] = fetch_from_gpu_cache_4(address + VECS_PER_IMAGE_RESOURCE);
return ImageSourceExtra(
data[0],
data[1],
data[2],
data[3]
);
}
#endif //WR_VERTEX_SHADER
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
flat varying highp vec4 vTransformBounds;
#ifdef WR_VERTEX_SHADER
#define VECS_PER_TRANSFORM 8U
uniform HIGHP_SAMPLER_FLOAT sampler2D sTransformPalette;
void init_transform_vs(vec4 local_bounds) {
vTransformBounds = local_bounds;
}
struct Transform {
mat4 m;
mat4 inv_m;
bool is_axis_aligned;
};
Transform fetch_transform(int id) {
Transform transform;
transform.is_axis_aligned = (id >> 23) == 0;
int index = id & 0x007fffff;
// Create a UV base coord for each 8 texels.
// This is required because trying to use an offset
// of more than 8 texels doesn't work on some versions
// of macOS.
ivec2 uv = get_fetch_uv(index, VECS_PER_TRANSFORM);
ivec2 uv0 = ivec2(uv.x + 0, uv.y);
transform.m[0] = TEXEL_FETCH(sTransformPalette, uv0, 0, ivec2(0, 0));
transform.m[1] = TEXEL_FETCH(sTransformPalette, uv0, 0, ivec2(1, 0));
transform.m[2] = TEXEL_FETCH(sTransformPalette, uv0, 0, ivec2(2, 0));
transform.m[3] = TEXEL_FETCH(sTransformPalette, uv0, 0, ivec2(3, 0));
transform.inv_m[0] = TEXEL_FETCH(sTransformPalette, uv0, 0, ivec2(4, 0));
transform.inv_m[1] = TEXEL_FETCH(sTransformPalette, uv0, 0, ivec2(5, 0));
transform.inv_m[2] = TEXEL_FETCH(sTransformPalette, uv0, 0, ivec2(6, 0));
transform.inv_m[3] = TEXEL_FETCH(sTransformPalette, uv0, 0, ivec2(7, 0));
return transform;
}
// Return the intersection of the plane (set up by "normal" and "point")
// with the ray (set up by "ray_origin" and "ray_dir"),
// writing the resulting scaler into "t".
bool ray_plane(vec3 normal, vec3 pt, vec3 ray_origin, vec3 ray_dir, out float t)
{
float denom = dot(normal, ray_dir);
if (abs(denom) > 1e-6) {
vec3 d = pt - ray_origin;
t = dot(d, normal) / denom;
return t >= 0.0;
}
return false;
}
// Apply the inverse transform "inv_transform"
// to the reference point "ref" in CSS space,
// producing a local point on a Transform plane,
// set by a base point "a" and a normal "n".
vec4 untransform(vec2 ref, vec3 n, vec3 a, mat4 inv_transform) {
vec3 p = vec3(ref, -10000.0);
vec3 d = vec3(0, 0, 1.0);
float t = 0.0;
// get an intersection of the Transform plane with Z axis vector,
// originated from the "ref" point
ray_plane(n, a, p, d, t);
float z = p.z + d.z * t; // Z of the visible point on the Transform
vec4 r = inv_transform * vec4(ref, z, 1.0);
return r;
}
// Given a CSS space position, transform it back into the Transform space.
vec4 get_node_pos(vec2 pos, Transform transform) {
// get a point on the scroll node plane
vec4 ah = transform.m * vec4(0.0, 0.0, 0.0, 1.0);
vec3 a = ah.xyz / ah.w;
// get the normal to the scroll node plane
vec3 n = transpose(mat3(transform.inv_m)) * vec3(0.0, 0.0, 1.0);
return untransform(pos, n, a, transform.inv_m);
}
#endif //WR_VERTEX_SHADER
#ifdef WR_FRAGMENT_SHADER
// Assume transform bounds are set to a large scale to signal they are invalid.
bool has_valid_transform_bounds() {
return vTransformBounds.w < 1.0e15;
}
float init_transform_fs(vec2 local_pos) {
// Ideally we want to track distances in screen space after transformation
// as signed distance calculations lose context about the direction vector
// to exit the geometry, merely remembering the minimum distance to the
// exit. However, we can't always sanely track distances in screen space
// due to perspective transforms, clipping, and other concerns, so we do
// this in local space. However, this causes problems tracking distances
// in local space when attempting to scale by a uniform AA range later in
// the presence of a transform which actually has non-uniform scaling.
//
// To work around this, we independently track the distances on the local
// space X and Y axes and then scale them by the independent AA ranges (as
// computed from fwidth derivatives) for the X and Y axes. This can break
// down at certain angles (45 degrees or close to it), but still gives a
// better approximation of screen-space distances in the presence of non-
// uniform scaling for other rotations.
//
// Get signed distance from local rect bounds.
vec2 d = signed_distance_rect_xy(
local_pos,
vTransformBounds.xy,
vTransformBounds.zw
);
// Find the appropriate distance to apply the AA smoothstep over.
vec2 aa_range = compute_aa_range_xy(local_pos);
// Only apply AA to fragments outside the signed distance field.
return distance_aa_xy(aa_range, d);
}
float init_transform_rough_fs(vec2 local_pos) {
return point_inside_rect(
local_pos,
vTransformBounds.xy,
vTransformBounds.zw
);
}
#endif //WR_FRAGMENT_SHADER
#ifdef WR_VERTEX_SHADER
PER_INSTANCE in vec4 aClipDeviceArea;
PER_INSTANCE in vec4 aClipOrigins;
PER_INSTANCE in float aDevicePixelScale;
PER_INSTANCE in ivec2 aTransformIds;
struct ClipMaskInstanceCommon {
RectWithEndpoint sub_rect;
vec2 task_origin;
vec2 screen_origin;
float device_pixel_scale;
int clip_transform_id;
int prim_transform_id;
};
ClipMaskInstanceCommon fetch_clip_item_common() {
ClipMaskInstanceCommon cmi;
cmi.sub_rect = RectWithEndpoint(aClipDeviceArea.xy, aClipDeviceArea.zw);
cmi.task_origin = aClipOrigins.xy;
cmi.screen_origin = aClipOrigins.zw;
cmi.device_pixel_scale = aDevicePixelScale;
cmi.clip_transform_id = aTransformIds.x;
cmi.prim_transform_id = aTransformIds.y;
return cmi;
}
struct ClipVertexInfo {
vec4 local_pos;
RectWithEndpoint clipped_local_rect;
};
// The transformed vertex function that always covers the whole clip area,
// which is the intersection of all clip instances of a given primitive
ClipVertexInfo write_clip_tile_vertex(RectWithEndpoint local_clip_rect,
Transform prim_transform,
Transform clip_transform,
RectWithEndpoint sub_rect,
vec2 task_origin,
vec2 screen_origin,
float device_pixel_scale) {
vec2 device_pos = screen_origin + mix(sub_rect.p0, sub_rect.p1, aPosition.xy);
vec2 world_pos = device_pos / device_pixel_scale;
vec4 pos = prim_transform.m * vec4(world_pos, 0.0, 1.0);
pos.xyz /= pos.w;
vec4 p = get_node_pos(pos.xy, clip_transform);
vec4 local_pos = p * pos.w;
//TODO: Interpolate in clip space, where "local_pos.w" contains
// the W of the homogeneous transform *from* clip space into the world.
// float interpolate_w = 1.0 / local_pos.w;
// This is problematic today, because the W<=0 hemisphere is going to be
// clipped, while we currently want this shader to fill out the whole rect.
// We can therefore simplify this when the clip construction is rewritten
// to only affect the areas touched by a clip.
vec4 vertex_pos = vec4(
task_origin + mix(sub_rect.p0, sub_rect.p1, aPosition.xy),
0.0,
1.0
);
gl_Position = uTransform * vertex_pos;
init_transform_vs(vec4(local_clip_rect.p0, local_clip_rect.p1));
ClipVertexInfo vi = ClipVertexInfo(local_pos, local_clip_rect);
return vi;
}
#endif //WR_VERTEX_SHADER
varying highp vec4 vLocalPos;
varying highp vec2 vUv;
flat varying highp vec4 vUvBounds;
flat varying mediump vec4 vEdge;
flat varying highp vec4 vUvBounds_NoClamp;
// Clip mode. Packed in to a vector to avoid bug 1630356.
flat varying mediump vec2 vClipMode;
#define MODE_STRETCH 0
#define MODE_SIMPLE 1
#ifdef WR_VERTEX_SHADER
PER_INSTANCE in ivec2 aClipDataResourceAddress;
PER_INSTANCE in vec2 aClipSrcRectSize;
PER_INSTANCE in int aClipMode;
PER_INSTANCE in ivec2 aStretchMode;
PER_INSTANCE in vec4 aClipDestRect;
struct ClipMaskInstanceBoxShadow {
ClipMaskInstanceCommon base;
ivec2 resource_address;
};
ClipMaskInstanceBoxShadow fetch_clip_item() {
ClipMaskInstanceBoxShadow cmi;
cmi.base = fetch_clip_item_common();
cmi.resource_address = aClipDataResourceAddress;
return cmi;
}
struct BoxShadowData {
vec2 src_rect_size;
int clip_mode;
int stretch_mode_x;
int stretch_mode_y;
RectWithEndpoint dest_rect;
};
BoxShadowData fetch_data() {
BoxShadowData bs_data = BoxShadowData(
aClipSrcRectSize,
aClipMode,
aStretchMode.x,
aStretchMode.y,
RectWithEndpoint(aClipDestRect.xy, aClipDestRect.zw)
);
return bs_data;
}
void main(void) {
ClipMaskInstanceBoxShadow cmi = fetch_clip_item();
Transform clip_transform = fetch_transform(cmi.base.clip_transform_id);
Transform prim_transform = fetch_transform(cmi.base.prim_transform_id);
BoxShadowData bs_data = fetch_data();
ImageSource res = fetch_image_source_direct(cmi.resource_address);
RectWithEndpoint dest_rect = bs_data.dest_rect;
ClipVertexInfo vi = write_clip_tile_vertex(
dest_rect,
prim_transform,
clip_transform,
cmi.base.sub_rect,
cmi.base.task_origin,
cmi.base.screen_origin,
cmi.base.device_pixel_scale
);
vClipMode.x = float(bs_data.clip_mode);
vec2 texture_size = vec2(TEX_SIZE(sColor0));
vec2 local_pos = vi.local_pos.xy / vi.local_pos.w;
vLocalPos = vi.local_pos;
vec2 dest_rect_size = rect_size(dest_rect);
switch (bs_data.stretch_mode_x) {
case MODE_STRETCH: {
vEdge.x = 0.5;
vEdge.z = (dest_rect_size.x / bs_data.src_rect_size.x) - 0.5;
vUv.x = (local_pos.x - dest_rect.p0.x) / bs_data.src_rect_size.x;
break;
}
case MODE_SIMPLE:
default: {
vEdge.xz = vec2(1.0);
vUv.x = (local_pos.x - dest_rect.p0.x) / dest_rect_size.x;
break;
}
}
switch (bs_data.stretch_mode_y) {
case MODE_STRETCH: {
vEdge.y = 0.5;
vEdge.w = (dest_rect_size.y / bs_data.src_rect_size.y) - 0.5;
vUv.y = (local_pos.y - dest_rect.p0.y) / bs_data.src_rect_size.y;
break;
}
case MODE_SIMPLE:
default: {
vEdge.yw = vec2(1.0);
vUv.y = (local_pos.y - dest_rect.p0.y) / dest_rect_size.y;
break;
}
}
vUv *= vi.local_pos.w;
vec2 uv0 = res.uv_rect.p0;
vec2 uv1 = res.uv_rect.p1;
vUvBounds = vec4(uv0 + vec2(0.5), uv1 - vec2(0.5)) / texture_size.xyxy;
vUvBounds_NoClamp = vec4(uv0, uv1) / texture_size.xyxy;
}
#endif
#ifdef WR_FRAGMENT_SHADER
void main(void) {
vec2 uv_linear = vUv / vLocalPos.w;
vec2 uv = clamp(uv_linear, vec2(0.0), vEdge.xy);
uv += max(vec2(0.0), uv_linear - vEdge.zw);
uv = mix(vUvBounds_NoClamp.xy, vUvBounds_NoClamp.zw, uv);
uv = clamp(uv, vUvBounds.xy, vUvBounds.zw);
float in_shadow_rect = init_transform_rough_fs(vLocalPos.xy / vLocalPos.w);
float texel = TEX_SAMPLE(sColor0, uv).r;
float alpha = mix(texel, 1.0 - texel, vClipMode.x);
float result = vLocalPos.w > 0.0 ? mix(vClipMode.x, alpha, in_shadow_rect) : 0.0;
oFragColor = vec4(result);
}
#ifdef SWGL_DRAW_SPAN
// As with cs_clip_rectangle, this shader spends a lot of time doing clipping and
// combining for every fragment, even if outside of the primitive to initialize
// the clip tile, or inside the inner bounds of the primitive, where the shadow
// is unnecessary. To alleviate this, the span shader attempts to first intersect
// the the local clip bounds, outside of which we can just use a solid fill
// to initialize those clip tile fragments. Once inside the primitive bounds,
// we further intersect with the inner region where no shadow is necessary either
// so that we can commit entire spans of texture within this nine-patch region
// instead of having to do the work of mapping per fragment.
void swgl_drawSpanR8() {
// Perspective is not supported.
if (swgl_interpStep(vLocalPos).w != 0.0) {
return;
}
// If the span is completely outside the Z-range and clipped out, just
// output clear so we don't need to consider invalid W in the rest of the
// shader.
float w = swgl_forceScalar(vLocalPos.w);
if (w <= 0.0) {
swgl_commitSolidR8(0.0);
return;
}
// To start, we evaluate the box shadow in both UV and local space relative
// to the local-space position. This will be interpolated across the span to
// track whether we intersect the nine-patch.
w = 1.0 / w;
vec2 uv_linear = vUv * w;
vec2 uv_linear0 = swgl_forceScalar(uv_linear);
vec2 uv_linear_step = swgl_interpStep(vUv).xy * w;
vec2 local_pos = vLocalPos.xy * w;
vec2 local_pos0 = swgl_forceScalar(local_pos);
vec2 local_step = swgl_interpStep(vLocalPos).xy * w;
// We need to compute the local-space distance to the bounding box and then
// figure out how many processing steps that maps to. If we are stepping in
// a negative direction on an axis, we need to swap the sides of the box
// which we consider as the start or end. If there is no local-space step
// on an axis (i.e. constant Y), we need to take care to force the steps to
// either the start or end of the span depending on if we are inside or
// outside of the bounding box.
vec4 clip_dist =
mix(vTransformBounds, vTransformBounds.zwxy, lessThan(local_step, vec2(0.0)).xyxy)
- local_pos0.xyxy;
clip_dist =
mix(1.0e6 * step(0.0, clip_dist),
clip_dist * recip(local_step).xyxy,
notEqual(local_step, vec2(0.0)).xyxy);
// Find the start and end of the shadowed region on this span.
float shadow_start = max(clip_dist.x, clip_dist.y);
float shadow_end = min(clip_dist.z, clip_dist.w);
// Flip the offsets from the start of the span so we can compare against the
// remaining span length which automatically deducts as we commit fragments.
ivec2 shadow_steps = ivec2(clamp(
swgl_SpanLength - swgl_StepSize * vec2(floor(shadow_start), ceil(shadow_end)),
0.0, swgl_SpanLength));
int shadow_start_len = shadow_steps.x;
int shadow_end_len = shadow_steps.y;
// Likewise, once inside the primitive bounds, we also need to track which
// sector of the nine-patch we are in which requires intersecting against
// the inner box instead of the outer box.
vec4 opaque_dist =
mix(vEdge, vEdge.zwxy, lessThan(uv_linear_step, vec2(0.0)).xyxy)
- uv_linear0.xyxy;
opaque_dist =
mix(1.0e6 * step(0.0, opaque_dist),
opaque_dist * recip(uv_linear_step).xyxy,
notEqual(uv_linear_step, vec2(0.0)).xyxy);
// Unlike for the shadow clipping bounds, here we need to rather find the floor of all
// the offsets so that we don't accidentally process any chunks in the transitional areas
// between sectors of the nine-patch.
ivec4 opaque_steps = ivec4(clamp(
swgl_SpanLength -
swgl_StepSize *
vec4(floor(opaque_dist.x), floor(opaque_dist.y), floor(opaque_dist.z), floor(opaque_dist.w)),
shadow_end_len, swgl_SpanLength));
// Fill any initial sections of the span that are clipped out based on clip mode.
if (swgl_SpanLength > shadow_start_len) {
int num_before = swgl_SpanLength - shadow_start_len;
swgl_commitPartialSolidR8(num_before, vClipMode.x);
float steps_before = float(num_before / swgl_StepSize);
uv_linear += steps_before * uv_linear_step;
local_pos += steps_before * local_step;
}
// This loop tries to repeatedly process entire spans of the nine-patch that map
// to a contiguous spans of texture in the source box shadow. First, we process
// a chunk with per-fragment clipping and mapping in case we're starting on a
// transitional region between sectors of the nine-patch which may need to map
// to different spans of texture per-fragment. After, we find the largest span
// within the current sector before we hit the next transitional region, and
// attempt to commit an entire span of texture therein.
while (swgl_SpanLength > 0) {
// Here we might be in a transitional chunk, so do everything per-fragment.
{
vec2 uv = clamp(uv_linear, vec2(0.0), vEdge.xy);
uv += max(vec2(0.0), uv_linear - vEdge.zw);
uv = mix(vUvBounds_NoClamp.xy, vUvBounds_NoClamp.zw, uv);
uv = clamp(uv, vUvBounds.xy, vUvBounds.zw);
float in_shadow_rect = init_transform_rough_fs(local_pos);
float texel = TEX_SAMPLE(sColor0, uv).r;
float alpha = mix(texel, 1.0 - texel, vClipMode.x);
float result = mix(vClipMode.x, alpha, in_shadow_rect);
swgl_commitColorR8(result);
uv_linear += uv_linear_step;
local_pos += local_step;
}
// If we now hit the end of the clip bounds, just bail out since there is
// no more shadow to map.
if (swgl_SpanLength <= shadow_end_len) {
break;
}
// By here we've determined to be still inside the nine-patch. We need to
// compare against the inner rectangle thresholds to see which sector of
// the nine-patch to use and thus how to map the box shadow texture. Stop
// at least one step before the end of the shadow region to properly clip
// on the boundary.
int num_inside = swgl_SpanLength - swgl_StepSize - shadow_end_len;
vec4 uv_bounds = vUvBounds;
if (swgl_SpanLength >= opaque_steps.y) {
// We're in the top Y band of the nine-patch.
num_inside = min(num_inside, swgl_SpanLength - opaque_steps.y);
} else if (swgl_SpanLength >= opaque_steps.w) {
// We're in the middle Y band of the nine-patch. Set the UV clamp bounds
// to the vertical center texel of the box shadow.
num_inside = min(num_inside, swgl_SpanLength - opaque_steps.w);
uv_bounds.yw = vec2(clamp(mix(vUvBounds_NoClamp.y, vUvBounds_NoClamp.w, vEdge.y),
vUvBounds.y, vUvBounds.w));
}
if (swgl_SpanLength >= opaque_steps.x) {
// We're in the left X column of the nine-patch.
num_inside = min(num_inside, swgl_SpanLength - opaque_steps.x);
} else if (swgl_SpanLength >= opaque_steps.z) {
// We're in the middle X band of the nine-patch. Set the UV clamp bounds
// to the horizontal center texel of the box shadow.
num_inside = min(num_inside, swgl_SpanLength - opaque_steps.z);
uv_bounds.xz = vec2(clamp(mix(vUvBounds_NoClamp.x, vUvBounds_NoClamp.z, vEdge.x),
vUvBounds.x, vUvBounds.z));
}
if (num_inside > 0) {
// We have a non-zero span of fragments within the sector. Map to the UV
// start offset of the sector and the UV offset within the sector.
vec2 uv = clamp(uv_linear, vec2(0.0), vEdge.xy);
uv += max(vec2(0.0), uv_linear - vEdge.zw);
uv = mix(vUvBounds_NoClamp.xy, vUvBounds_NoClamp.zw, uv);
// If we're in the center sector of the nine-patch, then we only need to
// sample from a single texel of the box shadow. Just sample that single
// texel once and output it for the entire span. Otherwise, we just need
// to commit an actual span of texture from the box shadow. Depending on
// if we are in clip-out mode, we may need to invert the source texture.
if (uv_bounds.xy == uv_bounds.zw) {
uv = clamp(uv, uv_bounds.xy, uv_bounds.zw);
float texel = TEX_SAMPLE(sColor0, uv).r;
float alpha = mix(texel, 1.0 - texel, vClipMode.x);
swgl_commitPartialSolidR8(num_inside, alpha);
} else if (vClipMode.x != 0.0) {
swgl_commitPartialTextureLinearInvertR8(num_inside, sColor0, uv, uv_bounds);
} else {
swgl_commitPartialTextureLinearR8(num_inside, sColor0, uv, uv_bounds);
}
float steps_inside = float(num_inside / swgl_StepSize);
uv_linear += steps_inside * uv_linear_step;
local_pos += steps_inside * local_step;
}
// By here we're probably in a transitional chunk of the nine-patch that
// requires per-fragment processing, so loop around again to the handler
// for that case.
}
// Fill any remaining sections of the span that are clipped out.
if (swgl_SpanLength > 0) {
swgl_commitPartialSolidR8(swgl_SpanLength, vClipMode.x);
}
}
#endif
#endif