GLSL Learning

GLSL built-in function

sign()

Returns -1.0 if x is negative, 0.0 if x is zero, and 1.0 if x is positive.

Syntax

float sign(float x)
vec2 sign(vec2 x)
vec3 sign(vec3 x)
vec4 sign(vec4 x)

Parameters

x
The value whose sign you want. Vectors are processed per component.

Return value

A value of the same type as x where each component is -1.0, 0.0 or 1.0.

Live example

Edit the code and the preview updates as you type.

How it works

sign(x) keeps only the direction of a number and drops its size:

xsign(x)
-3.2-1.0
0.00.0
0.011.0

In the example the gray line is a smooth sin wave. Passing it through sign snaps every value to -1 or 1, which produces the green square wave.

Typical uses

  • Square waves and blinking: sign(sin(u_time)) flips between -1 and 1 at a steady rhythm.
  • Restoring a sign after abs: sign(x) * pow(abs(x), 2.0) squares a value but keeps it negative when it started negative.
  • Picking a side: sign(p.x) tells you whether a pixel is on the left (-1) or right (1) half.

Common mistakes

  • Expecting only two results. Exactly 0.0 gives 0.0, which can leave a one-pixel seam where a coordinate is exactly zero.
  • Using sign where you want a 0/1 mask. step(0.0, x) returns 0 or 1 and is usually easier to multiply with.

Related functions