Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GLSL How to ensure largest possible float value without overflow

From what I understand, there are no FLT_MAX type constants in GLSL.

Is there any way to ensure that a float represents the largest possible value without overflow?

EDIT:

Since it was asked what Im using this for:

I'm basically scaling a point out into "infinity". Its for 2D shadow casting, where I completely reshape the triangle strip shadows on the GPU. As I can only control deal with a single vertex at a time the w component stores whether it stays on the hull or is projected to infinity.

In the case that both 'shadow boundary' points on are the same edge, and the light is almost colinear with that edge, I need to ensure that the triangle still covers the entire screen. Its hard to describe.

like image 592
kbirk Avatar asked Apr 17 '13 20:04

kbirk


2 Answers

In GLSL, IEEE 754 infinity can conveniently be achieved by dividing by zero:

float infinity = 1.0 / 0.0;
like image 108
Lenar Hoyt Avatar answered Sep 17 '22 06:09

Lenar Hoyt


GLSL uses the IEEE 754 floating-point definition for float:

As an input value to one of the processing units, a single-precision or double-precision floating-point variable is expected to match the corresponding IEEE 754 floating-point definition for precision and dynamic range. Floating-point variables within a shader are also encoded according to the IEEE 754 specification for single-precision floating-point values (logically, not necessarily physically). While encodings are logically IEEE 754, operations (addition, multiplication, etc.) are not necessarily performed as required by IEEE 754.

The maximum representable float value is (1 − 2^-24) × 2^128

Typical maximum floating-point values

You can therefore use this (taken from Microsoft's float.h)

#define FLT_MAX 3.402823466e+38
#define FLT_MIN 1.175494351e-38
#define DBL_MAX 1.7976931348623158e+308
#define DBL_MIN 2.2250738585072014e-308

Exact maximum floating-point value

Also, since the maximum floating-point value is

7f7f ffff = 0 11111110 11111111111111111111111 = 2139095039

here's another interesting way to get an exact maximum value:

float fMaxFloat = intBitsToFloat(2139095039);
like image 29
bernie Avatar answered Sep 17 '22 06:09

bernie